康威的生命游戏列表索引错误

时间:2016-11-28 14:28:38

标签: python pygame

所以我试图在Python / pygame中制作Conway的生活游戏,并且第一次使新网格生效,但第二次不会因为列表索引超出范围错误。我一直想弄清楚什么是错的,但是列表索引不应该超出范围。这是我的代码,错误应该在changevalue(),但我怀疑它不是,因为第一次迭代有效:

import pygame
import random

width = 400
height = 400
blocksize = 10

white = (255, 255, 255)
black = (0, 0, 0)

visual = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()

IsOn = True

grid = []
templist = []
tempgrid = []
class square(object):
    def __init__(self, x, y, alive):
        self.x = x
        self.y = y
        self.alive = alive

for y in range(height/blocksize):
    templist = []
    for x in range(width/blocksize):
        templist.append(square(x, y, random.choice([True, False, False, False])))
    grid.append(templist)

def changevalue(cx, cy, cgrid):
    neighbours = []
    for dy in range(3):
        ddy = dy - 1
        for dx in range(3):
            ddx = dx - 1
            if not (dx - 1 == 0 and dy - 1 == 0):
                #print cgrid[(cy + ddy)%len(cgrid)][(cx + ddx)%len(cgrid[y])].alive
                    #NO ERRORS
                #print len(cgrid) > (cy + ddy)%len(cgrid), len(cgrid[y]) > (cx + ddx)%len(cgrid[cy])
                    #NO ERRORS
                neighbours.append(cgrid[(cy + ddy)%len(cgrid)][(cx + ddx)%len(cgrid[cy])].alive)
    return len(filter(lambda p: p == True, neighbours))

while IsOn:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            IsOn = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_c:
                proceed = True

    tempgrid = []
    for times in range(len(grid)):
        tempgrid.append([])
    for ty in range(len(grid)):
        for tx in range(len(grid[ty])):
            if changevalue(tx, ty, grid) < 2 and grid[ty][tx].alive == True:
                tempgrid[ty].append(square(tx, ty, False))
            elif changevalue(tx, ty, grid) > 3 and grid[ty][tx].alive == True:
                tempgrid[ty].append(square(tx, ty, False))
            elif changevalue(tx, ty, grid) == 3 and grid[ty][tx].alive == False:
                tempgrid[ty].append(square(tx, ty, True))

    grid = list(tempgrid)

    visual.fill(white)
    for y in range(len(grid)):
        for x in range(len(grid[y])):
            if grid[y][x].alive == True:
                pygame.draw.rect(visual, black, (grid[y][x].x*blocksize, grid[y][x].y*blocksize, blocksize, blocksize))
    pygame.display.update()
    clock.tick(2)

pygame.quit()
quit()

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你不会复制没有改变价值的广场 - 所以新行的长度不同 - 后来你遇到index的问题

你需要这样的东西

if changevalue ...:
   ...
elif changevalue ...:
   ...
elif changevalue ...:
   ... 
else:
   # copy other elements
   tempgrid[ty].append(grid[ty][tx])