用形状元素列表做好的单击格子变颜色示例

"""
用形状元素列表做好的单击格子变颜色示例
 
"""
import arcade

# 常量设置
ROW_COUNT = 15    # 行的数量
COLUMN_COUNT = 15 # 列的数量

# 格子宽度和高度
WIDTH = 30
HEIGHT = 30

# 格子边框厚度
MARGIN = 5

# 算出屏幕宽度和高度
SCREEN_WIDTH = (WIDTH + MARGIN) * COLUMN_COUNT + MARGIN
SCREEN_HEIGHT = (HEIGHT + MARGIN) * ROW_COUNT + MARGIN
SCREEN_TITLE = "用形状元素列表做好的单击格子变颜色示例:翻译:李兴球"

class MyGame(arcade.Window):
    """
    继承自arcade.Window类
    """

    def __init__(self, width, height,title):
        """
        设置应用程序
        """
        super().__init__(width, height,title)

        self.shape_list = None          # 形状列表

        # 创建二维阵列,这里用的是嵌套列表
        self.grid = []
        for row in range(ROW_COUNT):
 
            self.grid.append([])
            for column in range(COLUMN_COUNT):
                self.grid[row].append(0)  

        arcade.set_background_color(arcade.color.BLACK)
        self.recreate_grid()

    def recreate_grid(self):
        self.shape_list = arcade.ShapeElementList() # 创建形状元素列表
        for row in range(ROW_COUNT):
            for column in range(COLUMN_COUNT):
                if self.grid[row][column] == 0:     # 如果值为0则为白色
                    color = arcade.color.WHITE
                else:
                    color = arcade.color.GREEN      # 否则为绿色

                x = (MARGIN + WIDTH) * column + MARGIN + WIDTH // 2
                y = (MARGIN + HEIGHT) * row + MARGIN + HEIGHT // 2
                # 创建填充的矩形
                current_rect = arcade.create_rectangle_filled(x, y, WIDTH, HEIGHT, color)
                self.shape_list.append(current_rect)

    def on_draw(self):
        """
        渲染屏幕
        """

        # 在重画角色之前此命令要先执行
        arcade.start_render()
        # 重画所有格子   
        self.shape_list.draw() 

    def on_mouse_press(self, x, y, button, modifiers):
        """
        单击鼠标按钮时调用此方法
        """

        # 根据鼠标坐标得到行列编号
        column = x // (WIDTH + MARGIN)
        row = y // (HEIGHT + MARGIN)

        print(f"单击时的坐标: ({x}, {y}). 格子行列数: ({row}, {column})") # 以左下角为原点

        # 翻转格子逻辑
        if row < ROW_COUNT and column < COLUMN_COUNT:

            # Flip the location between 1 and 0.
            if self.grid[row][column] == 0:
                self.grid[row][column] = 1
            else:
                self.grid[row][column] = 0

        self.recreate_grid()


def main():
    MyGame(SCREEN_WIDTH, SCREEN_HEIGHT,SCREEN_TITLE)
    arcade.run()


if __name__ == "__main__":
    main()