Search code examples
pythonconways-game-of-life

Conways game of life in python


I have attempted to make Conway's game of life in python, and then save the output into a picture, but I think there is something wrong with the logic as most of the pictures don't look quite correct. (see picture)

game of life pic:

    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")

Solution

  • Your program cannot work correctly in its current state, because you compute the next generation in the same grid where the last generation is stored. You need a new (empty) grid to store the next generation. In your implementation you overwrite the last generation already while computing the next generation.