康威生命游戏列表索引

2024-10-05 10:16:01 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我尝试用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()

谢谢你的帮助!你知道吗


Tags: infalsetrueforlenrangepygamegrid
1条回答
网友
1楼 · 发布于 2024-10-05 10:16:01

您不复制不改变值的正方形-因此新行具有不同的长度-并且稍后您会遇到问题index

你需要这样的东西

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

相关问题 更多 >

    热门问题