python - Python 更新二维列表中的对象
问题描述
我正在使用 pygame 制作康威的生命游戏,并尝试在单击棋盘时更新位置状态。棋盘上的每个位置都是一个 Cell 对象,其变量“状态”默认设置为 0。
这就是如何创建 Cell() 对象“板”的 2D 列表的方式。
block_size = 25
board = []
rows, cols = (int((window_height - 100)/ block_size), int(window_width / block_size))
for i in range(rows):
cell = Cell()
col = []
for j in range(cols):
col.append(cell)
board.append(col)
这是更新位置的代码。mouse_round() 用于将 mouse_pos 向下舍入为 25 的倍数,block_size 是屏幕上正方形的像素大小。
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if mouse_pos[1] < window_height - 100: # if a square in the board is clicked
block_size = 25
x, y = pygame.mouse.get_pos()
rect = pygame.Rect(mouse_round(x), mouse_round(y), block_size, block_size)
board_pos_x = int(mouse_round(y) / block_size)
board_pos_y = int(mouse_round(x) / block_size)
current_pos = board[board_pos_x][board_pos_y]
if current_pos.state == 0: # if the color where they clicked is black, make it white
current_pos.state = 1
pygame.draw.rect(window, white, rect)
else: # if the color where they clicked is white, make it black
pygame.draw.rect(window, black, rect)
current_pos.state = 0
我遇到的问题是,当单击黑色方块时,行中每个单元格对象的状态都更改为 1,而我终生无法弄清楚。
解决方案
因为每行只创建 1 个单元格。然后将同一单元格附加到该行的每一列。在列循环内移动单元格创建。IE
for i in range(rows):
col = []
for j in range(cols):
cell = Cell()
col.append(cell)
推荐阅读
- xml - 在 XSLT 中使用 position() 检索多个同名节点
- drupal - 限制 Drupal 8 中顶级菜单项的数量
- c# - Asp.Net-Core 在点击时读取 js 模型值
- javascript - 如何访问 refs 数组元素
- laravel - 是否可以在不安装 Laravel 的情况下将已经运行的本地 Laravel 应用程序上传到云端?
- excel - 从 10 个列表框中选择。运行时错误“390”
- javascript - 在 Web javascript 中获取云 Firestore 集合的快照大小
- javascript - 点击时从动态添加的元素中获取数据
- java - 如何使用 Java 在 cmd 窗口上显示 .txt 文件的内容?
- azure-ad-graph-api - Azure AD Graph API:无法在任何函数下使用 StartsWith