在棋盘中创建棋子

3.1 说明

每次游戏开始时需要创建多个棋子对象,如果将所有的创建代码放到mian函数中,感觉不是很舒服,也导致main函数中有大量零碎的代码,这对于“封装”来说不够好。我们应该的做法是:main函数中尽量保留更少的代码,能封装的就封装到类的方法中去

在本节中,我们主要的目标就是将在main函数中的代码再次进行“精简优化”

3.2 代码实现

        self.chessboard_map = None  # 用来存储当前棋盘上的所有棋子对象
        self.create_chess()  # 调用创建棋盘的方法

image-20210821182431347

def create_chess(self):
        """创建默认棋盘上的棋子对象"""
        # 棋子
        self.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(self.chessboard_map):
            for col, chess_name in enumerate(line):
                if chess_name:
                    # 将创建的棋子添加到属性map中
                    self.chessboard_map[row][col] = Chess(self.screen, chess_name, row, col)
                else:
                    self.chessboard_map[row][col] = None

image-20210821182706522

for line_chess in chessboard.chessboard_map:

image-20210821182817804

3.3 运行效果

img

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