python 中的 Conways 人生游戏

Conways game of life in python

我曾尝试在python中制作康威的人生游戏,然后将输出保存到图片中,但我认为逻辑有问题,因为大多数图片看起来不太像正确的。 (见图)

生活游戏图片:

    import PIL.Image, random

    WIDTH = 1366
    HEIGHT = 768
    ROUNDS = 10

    DEAD = (0, 0, 0)
    ALIVE = (0, 64, 255)

    print("Creating image")
    img = PIL.Image.new("RGB", (WIDTH, HEIGHT))
    data = img.load()

    print("Creating grid")
    grid = []
    for y in range(HEIGHT):
        grid.append([])
        for x in range(WIDTH):
            grid[y].append(random.randint(0, 1))

    for i in range(ROUNDS):
        print("Starting round", i + 1, "of", ROUNDS)
        for y in range(HEIGHT):
            for x in range(WIDTH):
                n = 0
                for y2 in range(-1, 2):
                    for x2 in range(- 1, 2):
                        if x2 != 0 and y2 != 0 and grid[(y + y2) % HEIGHT][(x + x2) % WIDTH] == 1:
                            n += 1
                if n < 2:
                    grid[y][x] = 0
                elif n > 3:
                    grid[y][x] = 0
                elif grid[y][x] == 1 and n > 1 and n < 4:
                    grid[y][x] = 1
                elif grid[y][x] == 0 and n == 3:
                    grid[y][x] = 1

    print("Rendering image")
    for y in range(HEIGHT):
        for x in range(WIDTH):
            if grid[y][x] == 1:
                data[x, y] = ALIVE
            else:
                data[x, y] = DEAD

    print("Saving image")
    img.save("gofl.png")

您的程序在当前状态下无法正常工作,因为您在存储上一代的同一网格中计算下一代。您需要一个新的(空的)网格来存储下一代。在您的实现中,您在计算下一代时已经覆盖了上一代。