显示棋子

6.1 说明1

每个棋子都是一张图片,能够在image文件夹中看到它们

为了能够区分它们是哪一方的用了“r”表示red红方,“b”表示black黑方

用"z"表示兵,“p”表示炮,“c”表示车,“m”表示马,“x”表示象,“s”表示士,“j”表示将

用到的这些素材图片,如果您没有下载,可以从 https://www.itprojects.cn/58.html 下载

6.2 说明2

在上一步显示棋盘的时候,我们知道棋盘就是一个图片,为了能够让要显示的棋子显示到合适的位置,我们要经过一定的计算,像2个棋子之间的间距是多少,“楚河、汉界”的高度是多少等。当我们计算除了这些数据之后,就可以通过代码的方式将棋子固定到这些位置即可

6.3 显示棋子

    # 棋子
    chessboard_map = [
        ["b_c", "b_m", "b_x", "b_s", "b_j", "b_s", "b_x", "b_m", "b_c"],
        ["", "", "", "", "", "", "", "", ""],
        ["", "b_p", "", "", "", "", "", "b_p", ""],
        ["b_z", "", "b_z", "", "b_z", "", "b_z", "", "b_z"],
        ["", "", "", "", "", "", "", "", ""],
        ["", "", "", "", "", "", "", "", ""],
        ["r_z", "", "r_z", "", "r_z", "", "r_z", "", "r_z"],
        ["", "r_p", "", "", "", "", "", "r_p", ""],
        ["", "", "", "", "", "", "", "", ""],
        ["r_c", "r_m", "r_x", "r_s", "r_j", "r_s", "r_x", "r_m", "r_c"],
    ]
    for row, line in enumerate(chessboard_map):
        for col, chess_name in enumerate(line):
            if chess_name:
                # 将创建的棋子添加到属性map中
                chessboard_map[row][col] = [pygame.image.load("images/" + chess_name + ".png"), (50 + col * 57, 50 + row * 57)]
            else:
                chessboard_map[row][col] = None

image-20210821180611832

        # 显示棋盘上的所有棋子
        for line_chess in chessboard_map:
            for chess in line_chess:
                if chess:
                    screen.blit(chess[0], chess[1])

image-20210821180642319

6.4 运行效果

img

6.5 注意

到现在为止我们已经显示很多张图片到窗口(screen)中,切记较大的图片在底层显示,小图片在上层显示,否则的话小图片会被大图片遮挡住就看到了

因此在右侧代码中,看到while True中调用screen.blit显示图片的顺序是,先显示最大的游戏背景,然后是中等大小的棋盘图片,最后是一个个的最小的棋子图片

Copyright © itprojects.cn 2021 all right reserved,著作权归itprojects.cn所有,由王铭东编写该文件修订时间: 2021-08-21 20:52:40