Conway's Game of Life with Python

断了今生、忘了曾经 提交于 2019-12-03 03:41:18

You will need to swap D and C, and not just assign C to D. As it stands now, D and C will be referring to the same list after the first iteration.

Here is a simple algorithm to do Conway's Game of Life in python using a numpy array of arbitrary 2D size:

import numpy

# this function does all the work
def play_life(a):
    xmax, ymax = a.shape
    b = a.copy() # copy grid & Rule 2
    for x in range(xmax):
        for y in range(ymax):
            n = numpy.sum(a[max(x - 1, 0):min(x + 2, xmax), max(y - 1, 0):min(y + 2, ymax)]) - a[x, y]
            if a[x, y]:
                if n < 2 or n > 3:
                    b[x, y] = 0 # Rule 1 and 3
            elif n == 3:
                b[x, y] = 1 # Rule 4
    return(b)

# replace (5, 5) with the desired dimensions
life = numpy.zeros((5, 5), dtype=numpy.byte)

# place starting conditions here
life[2, 1:4] = 1 # a simple "spinner"

# now let's play
print(life)
for i in range(3):
    life = play_life(life)
    print(life)

This is not very efficient, but will certainly get the job done. Replace print(life) with whatever graphical calls you prefer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!