我正在尝试使用pygame在conthon中制作conway的生活游戏。我无法弄清楚为什么,但它产生的模式是关闭的。我已经查看了一百万次代码,我看不出什么是错的。
以下是其中一代人的屏幕截图
这是完整的游戏代码。
import pygame, sys
from pygame.locals import *
from random import randint
import numpy
#inititalize
pygame.init()
clock = pygame.time.Clock()
#constants
FPS = 10
BLACK = (0,0,0)
RED = (255,0,0)
GREY = (30,30,30)
SCREENX = 640
SCREENY = 480
CELLSIZE = 10
HEIGHT = SCREENY/CELLSIZE
WIDTH = SCREENX/CELLSIZE
#set up window
window = pygame.display.set_mode((SCREENX, SCREENY))
pygame.display.set_caption('Game of Life')
window.fill(BLACK)
#generate random seed
cells = numpy.zeros((WIDTH,HEIGHT), dtype=numpy.int)
for x in range(0,WIDTH):
for y in range(0,HEIGHT):
#0 is a dead cell, 1 is an alive cell
cells[x][y] = randint(0,1)
def findNeighbors(grid, x, y):
if 0 < x < len(grid) - 1:
xi = (0, -1, 1)
elif x > 0:
xi = (0, -1)
else:
xi = (0, 1)
if 0 < y < len(grid[0]) - 1:
yi = (0, -1, 1)
elif y > 0:
yi = (0, -1)
else:
yi = (0, 1)
for a in xi:
for b in yi:
if a == b == 0:
continue
yield grid[x + a][y + b]
def update(grid, x, y):
#determine num of living neighbors
neighbors = findNeighbors(cells,x,y)
alive = 0
for i in neighbors:
if i == 1:
alive+=1
#if current cell is alive
if grid[x][y] == 1:
#kill if less than 2 or more than 3 alive neighbors
if (alive < 2) or (alive > 3):
return 0
else:
return 1
#if current cell is dead
elif grid[x][y] == 0:
#make alive if 3 alive neighbors
if alive == 3:
return 1
else:
return 0
#main loop
while True:
#check if user wants to exit
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
#update cells
for x in range(0,WIDTH):
for y in range(0,HEIGHT):
cells[x][y] = update(cells,x,y)
#draw grid
for x in range(0,SCREENX,CELLSIZE):
for y in range(0,SCREENY,CELLSIZE):
#if cell is alive
if cells[x/CELLSIZE][y/CELLSIZE] == 1:
#draw red square
pygame.draw.rect(window, RED, [x, y, CELLSIZE, CELLSIZE])
else:
#draw black square
pygame.draw.rect(window, BLACK, [x, y, CELLSIZE, CELLSIZE])
#draw square border
pygame.draw.rect(window, GREY, [x, y, CELLSIZE, CELLSIZE], 1)
#draw updates
pygame.display.update()
#generations per second
clock.tick(FPS)
我认为问题不在于findNeighbors函数,因为我是从this stackoverflow回答得到的。所以我假设问题在于更新功能,但根据游戏规则,我无法看出逻辑错误的位置。
答案 0 :(得分:6)
我怀疑这是问题所在:
cells[x][y] = update(cells,x,y)
你只有一个网格,当你还在用它计算时,你正在更新 。第n + 1代只应考虑来自第n代的信息 - 而目前你已经得到了来自n和n + 1的信息混合。您最终会得到上方和左侧邻居的 new 值,以及您右侧和下方邻居的旧值,因为它们尚未重新计算。
例如,采用这种模式(其中#表示“活着”):
...
###
...
应该转到:
.#.
.#.
.#.
......但事实上,你最终会(我认为):
.##
#.#
... // Bottom-middle only has one live neighbour at computation time
当我们计算右上角时,它有三个邻居。左中间在计算时有2个活的邻居;中心有4个,右边中间有2个。在计算时,底行上没有任何东西有三个邻居,所以它一直没死。
通常,Conway的Life实现将为每一代计算一个全新的网格,或者它将在两个网格之间翻转,从另一个网格计算所有网格。