method\uuuuu missing\uuuuuuu不适用于dictionary

pvcm50d1  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(131)

很抱歉我的无知,我对micropython是完全陌生的。因此,我的第一次尝试是在raspberry pi pico上使用128x128 oled实现康威的生活游戏代码。我知道如何使用“蛮力”(即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, *args,**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, x+1)
            y_coords = (y-1, y, 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, dead = [], []
        # 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, 15): 1, (25, 16): 1, (24, 16): 1, (25, 17): 1,})

while 1:
    game.play_game()
    time.sleep(.1)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题