问题描述
为我的无知道歉,我对 micropython 完全陌生。因此,我的第一次尝试是尝试使用 128x128 oled 在 RaspBerry Pi Pico 上实现 Conway 游戏的代码。我想出了如何使用“蛮力”(即 128x128 矩阵)来做到这一点,但优化的速度,甚至对 Pi 超频,都不是我想要的(游戏中的步骤之间大约有 2 秒)。我移植到了 circuitpython,希望从对矩阵的 ulab 处理中获利,但最终得到了一个较慢的最终产品(原因并不重要,但我决定回到 micropython)。
我在网上找到了一种使用活细胞字典的单独方法,该方法应该大大加快问题的处理速度,因为它只在每次迭代中严格处理需要观察的那些细胞,而忽略了在特定步骤中无法进化的大多数细胞游戏。为此,它依赖于使用 missing 方法为字典中当前不存在的任何单元格返回零值。 (简化的)代码如下。它返回错误
Traceback (most recent call last):
File "<stdin>",line 62,in <module>
File "<stdin>",line 46,in play_game
File "<stdin>",line 18,in check_cell
KeyError: (24,13)
这似乎表明 missing 没有按应有的方式工作(该键确实对应于正在访问的单元格的坐标,而该单元格在前面的字典中不存在)。我通过导入 defaultdict 等尝试了几件事,但无济于事。任何人都可以帮忙吗?提前致谢。
import time
class Life(dict):
def __init__(self,*args,**kwargs):
super(Life,self).__init__(*args,**kwargs)
def __missing__(self,**kwargs):
return 0
def check_cell(self,x: int,y: int): #determine if cell lives or dies
x_coords = (x-1,x,x+1)
y_coords = (y-1,y,y+1)
total = 0
for x_coord in x_coords:
for y_coord in y_coords:
total += self[x_coord,y_coord]
live,dead = [],[]
cell = self[x,y]
if total == 3 and not cell:
live.append((x,y))
elif total < 3 or total > 4 and cell:
dead.append((x,y))
elif cell:
pass
return live,dead
def queue_cells(self):
cells = []
for x,y in self.keys():
# Add all cell neighbors to the function.
x_coords = (x-1,x+1)
y_coords = (y-1,y+1)
for x_coord in x_coords:
for y_coord in y_coords:
cells.append((x_coord,y_coord))
# print(cells)
return cells
def play_game(self):
live,[]
# Create all the transitions for the turn
for x,y in self.queue_cells():
step_live,step_dead = self.check_cell(x,y)
live += step_live
dead += step_dead
# Apply all transitions. Remember that in Life,the state of the board
# doesn't change until every cell is accounted for.
for x,y in dead:
if self[x,y]:
del self[x,y]
for x,y in live:
self[x,y] = 1
game = Life({(25,15): 1,(26,(25,16): 1,(24,17): 1,})
while 1:
game.play_game()
time.sleep(.1)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)