pygame 生命游戏索引超出范围绘制矩形
pygame game of life index out of range drawing rect
我正在尝试重新创建 Conways 生活游戏,我一直在关注并尝试在编码火车挑战 #85 的 pygame“教程”中重新创建它。但是如果在我的 [i][j] == 1 上的数组中尝试实际绘制一个矩形时,我迷路了:当我 运行 文件时,它告诉我 IndexError 列表索引超出范围。
import pygame
import random
WIDTH = 400
HEIGHT = 400
pygame.init()
window = pygame.display.set_mode((WIDTH,HEIGHT))
# create 2d array
def create_2d_list(cols, rows):
arr = []
for i in range(cols):
arr.append([0] * rows)
return arr
resolution = 40
cols = WIDTH // resolution
rows = HEIGHT // resolution
def main():
global grid
grid = create_2d_list(cols, rows)
for i in range(cols):
for j in range(rows):
grid[i][j] = random.randint(0,1)
draw()
pygame.display.flip()
def draw():
background = window.fill((255,255,255))
cols = 10 * resolution
rows = 10 * resolution
for i in range(cols):
for j in range(rows):
x = i * resolution
y = j * resolution
if grid[i][j] == 1:
pygame.draw.rect(window,(0,0,0), pygame.Rect(x , y, resolution, resolution))
if __name__ == "__main__":
main()
错误告诉我:
line 46, in draw
if grid[i][j] == 1:
IndexError: list index out of range
我试过调试它,问题似乎发生在 for cycle j 的第一个循环之后
但我无法确定问题所在
如果有人能帮助我,我会很高兴。
您已经重新创建了 cols 和 rows 变量:
cols = 10 * resolution
只需删除这些行。
我正在尝试重新创建 Conways 生活游戏,我一直在关注并尝试在编码火车挑战 #85 的 pygame“教程”中重新创建它。但是如果在我的 [i][j] == 1 上的数组中尝试实际绘制一个矩形时,我迷路了:当我 运行 文件时,它告诉我 IndexError 列表索引超出范围。
import pygame
import random
WIDTH = 400
HEIGHT = 400
pygame.init()
window = pygame.display.set_mode((WIDTH,HEIGHT))
# create 2d array
def create_2d_list(cols, rows):
arr = []
for i in range(cols):
arr.append([0] * rows)
return arr
resolution = 40
cols = WIDTH // resolution
rows = HEIGHT // resolution
def main():
global grid
grid = create_2d_list(cols, rows)
for i in range(cols):
for j in range(rows):
grid[i][j] = random.randint(0,1)
draw()
pygame.display.flip()
def draw():
background = window.fill((255,255,255))
cols = 10 * resolution
rows = 10 * resolution
for i in range(cols):
for j in range(rows):
x = i * resolution
y = j * resolution
if grid[i][j] == 1:
pygame.draw.rect(window,(0,0,0), pygame.Rect(x , y, resolution, resolution))
if __name__ == "__main__":
main()
错误告诉我:
line 46, in draw if grid[i][j] == 1: IndexError: list index out of range
我试过调试它,问题似乎发生在 for cycle j 的第一个循环之后 但我无法确定问题所在 如果有人能帮助我,我会很高兴。
您已经重新创建了 cols 和 rows 变量:
cols = 10 * resolution
只需删除这些行。