试图用Python制作康威的生活游戏

2024-04-25 05:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python制作康威的生活游戏(我只是把它放在我的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)

Tags: nameinforifdefcolumnembedgrid
1条回答
网友
1楼 · 发布于 2024-04-25 05:31:25

解决了这个问题。尽管nextgridgrid的单独副本,但它存储的列表不是。我刚刚用nextgrid = [i[:] for i in grid]替换了nextgrid = grid[:],效果很好

相关问题 更多 >