我试图用Python创建生命游戏,但是由于某些原因,我的图形窗口在“运行模拟”功能期间崩溃。为什么会这样呢?日志上没有错误。
from graphics import * #Using zelle graphics module for Python
S=20 #Size of each cell. The bigger the number the bigger it is
class Cell: #Cell is a rectangular box. Can be alive or dead
def __init__(self,window,x,y,alive):
self.window=window
self.alive=alive
self.x=x
self.y=y
self.rectangle=Rectangle(Point(x*S,(y*S)+S),Point((x*S)+S,y*S))
self.draw(x,y,self.window)
def draw(self,x,y,window):
self.rectangle.setFill("black")
self.rectangle.draw(window)
def getX(self):
return self.x*S
def getY(self):
return self.y*S+S
def die(self):
self.rectangle.setFill("black")
self.alive=False
def becomeAlive(self,window):
self.rectangle.setFill("white")
self.alive=True
def isAlive(self):
return self.alive
def clickedOn(self,mouseX,mouseY):
if (mouseX>self.getX() and mouseX<self.getX()+S and mouseY<self.getY()+S and mouseY<self.getY()):
return True
else:
return False
def totalNeighbours(self,cell0,cell1,cell2,cell3):
if(cell0.isAlive() and cell0.isAlive() and cell0.isAlive() and cell0.isAlive()):
return True
def createGraphics():
win=GraphWin("Game of Life!",1000,1000)
return win
def createGrid(window): #Creating the grid of cell objects
cellList=[]
for x in range(150):
for y in range(150):
cell=Cell(window,x,y,alive=False)
cellList.append(cell)
for i in range(10):
getM=window.getMouse()
j=0
for cells in cellList:
if cellList[j].clickedOn(getM.getX(),getM.getY()): #Checking whether the cell has been clicked.
cellList[j].becomeAlive(window)
break
else:
j=j+1
return cellList
def runSimulation(window,cellList): #At this part my graphics window ceases functioning and the program crashes
for i in range(10000000000):
j=150
for cell in cellList:
if cell.isAlive():
if cell.totalNeighbours(cellList[j-1],cellList[j+1],cellList[j+150],cellList[j-150])==4:
cellList[j].die()
j=j+1
def main():
window=createGraphics()
cellList=createGrid(window)
runSimulation(window,cellList)
main()
当我说“崩溃”时,是指程序停止运行,并且图形窗口没有响应。我以前遇到过这些问题,通常我只需要在shell配置中使用Tkinter gui,但是这次不起作用。