我正在尝试重新创建Conways生活游戏,我一直在关注并尝试在pygame中重新创建它"教程";来自编码列车挑战#85。但当我试图实际绘制一个矩形时,如果在[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()
错误告诉我:
第46行,绘制中如果网格[i][j]==1:IndexError:列出超出范围的索引
我试过调试它,问题似乎发生在for循环j的第一个循环之后但我不能准确指出问题所在如果有人能帮我,我会很高兴。
您已经重新创建了列和行变量:
cols = 10 * resolution
只需删除那些行。