【发布时间】:2016-01-30 19:55:05
【问题描述】:
我已经开始编程并尝试了“生命游戏”,在 20x20 板上一切都很好,但如果我采用 100 或更大的板尺寸,100 代之后,程序需要 500mb 的 RAM 和 25% 的 CPU(并且每一代都需要更多),我想这很糟糕。所以我想,我有一个逻辑错误,每一代都需要更多的内存。在下面发布代码
import time
from tkinter import *
class cell(object):
def __init__(self,lives):
self.lives = lives
def set(self, alive):
self.lives=alive
class grid(object):
gen = 0
def __init__(self,height,width,file=None):
if(file is None):
self.root=Tk()
self.root.title("Game of Life")
self.canvas=Canvas(self.root,height =height*6, width=width*6)
self.canvas.grid(row=0,column=0)
self.matrix=[[cell(False) for x in range(width)] for y in range(height)]
self.next_grid = [[cell(False) for x in range(width)] for y in range(height)]
self.width= width
self.height=height
else:
pass
#comes later with fileinput
def print_grid(self):
for i in range(self.height):
for j in range(self.width):
if(self.matrix[i][j].lives):
pass
self.canvas.create_rectangle(j*6,i*6,j*6+4,i*6 + 4,fill="black")
elif(not self.matrix[i][j].lives):
self.canvas.create_rectangle(j*6,i*6,j*6+5,i*6 + 5,fill="white",width=0)#invalid command name ".9727696"?!
def set_cell(self, height,width,live):
self.matrix[height][width].set(live)
def count_neighbours(self,height,width):
counter = 0
for hi in range(height-1,height+2):
for wi in range(width -1,width+2):
if(hi < self.height and hi > -1 and wi < self.width and wi > -1):
if(self.matrix[hi][wi].lives):
counter = counter +1
if(self.matrix[height][width].lives):
counter = counter -1
return counter
def does_survive(self,i,j):
neighbours = self.count_neighbours(i,j)
result =False
if(self.matrix[i][j].lives):
if(neighbours == 2 or neighbours == 3):
result = True
elif (neighbours == 3):
result = True
return result
def next_gen(self):
self.next_grid = [[cell(False) for x in range(self.width)] for y in range(self.height)]
self.gen = self.gen +1
for i in range(self.height):
for j in range(self.width):
self.next_grid[i][j].set(self.does_survive(i,j))
self.matrix = self.next_grid
def test():
cell1=cell(True)
cell2=cell(False)
cell2.set(True)
place=grid(150,150)
place.set_cell(50,60,True)
place.set_cell(51,60,True)
place.set_cell(51,59,True)
place.set_cell(52,60,True)
place.set_cell(50,61,True)
for i in range(1000):
place.print_grid()
#time.sleep(0.01)
place.next_gen()
place.canvas.update()
place.root.mainloop()
test()
这是我第一次使用一般图形,是的......我希望你能帮助我:D
编辑:我发现了错误并正在努力提高性能,但现在我遇到了问题,如果我不清除中的 next_gen 网格,世代就会很奇怪......你能帮我吗?
【问题讨论】:
-
您的 print_grid 代码创建了矩形并且它们永远不会被删除,您只需将新的堆叠在旧的之上。考虑拥有一个矩形数组(常量)并且只更改它们的颜色(或每次迭代删除旧的)。
-
@lejlot:这可能已经是一个答案了。
-
谢谢,我在打印新网格之前使用了 self.canvas.delete("all") 并且它有帮助,但是现在这几代人看起来有点奇怪......你能看看我在 dos_survive 中的规则吗写对了吗?
-
实际上没有理由每一代都创建矩形,因为只会显示最后一个矩形,因为直到所有较早的矩形都被覆盖(或删除)后才会调用
place.root.mainloop()。如果您想显示每一代的动画流程,请考虑使用 tkinter 小部件.after()方法定期调用place.next_gen()以更新建议的矩形@lejlot 的常量数组。您还需要修复代码的缩进,这是不正确的。
标签: python tkinter conways-game-of-life tkinter-canvas