首页 > 解决方案 > 方法 __missing__ 不适用于康威人生游戏中的字典

问题描述

为我的无知道歉,我对 micropython 完全陌生。因此,我的第一次尝试是尝试使用 128x128 oled 在 Raspberry Pi Pico 上实现 Conway 的生活游戏代码。我想出了如何使用“蛮力”(即 128x128 矩阵)来做到这一点,但优化的速度,甚至超频 Pi,都不是我想要的(游戏中的步骤之间大约 2 秒)。我移植到 circuitpython,希望从 ulab 处理矩阵中获利,但最终得到了一个较慢的最终产品(原因并不重要,但我决定回到 micropython)。

我在网上找到了一种使用活细胞字典的单独方法,该方法应该大大加快速度,因为它只在每次迭代中严格处理那些需要观察的细胞,而忽略了在游戏的给定步骤中无法进化的大多数细胞。为此,它依赖于使用缺少的方法来为当前不在字典中的任何单元格返回零值。(简化的)代码如下。它返回错误

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)

这似乎表明缺失没有按应有的方式工作(该键确实对应于正在访问的单元格的坐标,而该坐标在前面的字典中不存在)。我通过导入 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)

标签: pythondictionaryconways-game-of-life

解决方案


推荐阅读