Conway's Game of Life with Python

前端 未结 2 2068
萌比男神i
萌比男神i 2021-02-06 12:48

I took a liking to Conway\'s Game of Life and began to try and write it in python. At this moment I have yet to write any code for the borders of the program so I am just asking

相关标签:
2条回答
  • 2021-02-06 13:44

    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.

    0 讨论(0)
  • 2021-02-06 13:52

    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.

    0 讨论(0)
提交回复
热议问题