首页 > 解决方案 > 尝试用 Python 制作康威的生命游戏

问题描述

我正在尝试用 Python 制作 Conway 的生命游戏(我只是把它放在我的 Discord 机器人中,因为为什么不这样做)。我的问题是,当我运行它时,什么也没有发生,消息没有被编辑。没有错误消息。我想代码认为与上一代相比没有任何变化,所以它停止了,尽管有些东西已经发生了。

这是我的代码,我相信问题出在环境函数或for y, row in enumerate(grid):循环中。

    @commands.command()
    async def gameoflife(self, ctx):

        grid = [[0 for i in range(15)] for i in range(13)]
        grid[5][5], grid[5][6], grid[5][7] = (1, 1, 1) #just a simple blinker for now

        def emojify(i):
            convert = {0 : '⬛', 1 : '⬜'}
            return convert[i]

        gridmap = '\n'.join([''.join(list(map(emojify, i))) for i in grid])

        embed = discord.Embed(colour = 0xf1c40f)
        embed.set_author(name = 'CONWAY\'S GAME OF LIFE')
        embed.add_field(name = '_ _', value = gridmap, inline = False)
        embed.set_footer(text = 'Generation 1')
        m = await ctx.send(embed = embed)

        def surroundings(y, x):
            count = 0
            surrtiles = ((-1, 0), (-1, 1), (0, 1), (1, 1), 
                        (1, 0), (1, -1), (0, -1), (-1, -1))
            for i in surrtiles:
                row = y
                column = x
                if row > 11 and i[0] == 1:
                    row = 0
                if column > 13 and i[1] == 1:
                    column = 0
                if grid[row + i[0]][column + i[1]] == 1:
                    count += 1
            return count

        gen = 1
        while True:
            gen += 1
            await asyncio.sleep(2.0)

            nextgrid = grid[:]
            for y, row in enumerate(grid):
                for x, column in enumerate(row):
                    if surroundings(y, x) == 3:
                        nextgrid[y][x] = 1
                    if surroundings(y, x) > 3:
                        nextgrid[y][x] = 0
                    if surroundings(y, x) < 2:
                        nextgrid[y][x] = 0

            if nextgrid == grid:
                break
            else:
                grid = nextgrid[:]

            gridmap = '\n'.join([''.join(list(map(emojify, i))) for i in grid])
            embed = discord.Embed(colour = 0xf1c40f)
            embed.set_author(name = 'CONWAY\'S GAME OF LIFE')
            embed.add_field(name = '_ _', value = gridmap, inline = False)
            embed.set_footer(text = f'Generation {gen}')
            await m.edit(embed = embed)

标签: pythonconways-game-of-life

解决方案


解决了这个问题。虽然nextgrid是 的单独副本grid,但它存储的列表不是。我刚刚替换nextgrid = grid[:]nextgrid = [i[:] for i in grid],它工作正常!


推荐阅读