康威的生活游戏使用Python matplotlib

2024-09-28 21:39:10 发布

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

我刚开始学习Python,所以我们必须做这个家庭作业,用matplotlib编写一个程序来运行康威的人生游戏。教授已经完成了我的注释和代码。所以我写了它,我不知道为什么它没有运行动画。我做错了什么?谢谢你们!!!因为程序中的注释很长。在

# life.py - Once complete, this program will play the game of
#           life.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# The update function is needed for the animation
#   to work properly. It has four parameters:
# frameNum - this is handled by the animation, don't change this.
# img - the plot that is passed and changed, don't change this.
# world - the two-D array that represents the world for the
#         game of life. This will be updated to the next gen.
# N - the size of the world (which is square).

def update( frameNum, img, world, N ) :

    newWorld = world.copy( )

    ## TODO - Write code here to update the cells in newWorld
    ##        for the next generation of life. Remember to
    ##        use the toroidal model. Rather than making
    ##        special cases for row/column 0 and N-1, just
    ##        use the % operator.

    for i in range (N):
        for j in range (N):
            total= (world[(i-1)%N][(j-1)%N]+world[(i-1)%N][j]+world[(i-1)%N][(j+1)%N]+
                   world[i][(j-1)%N]+world[i][(j+1)%N]+ world[(i+1)%N][(j-1)%N]+
                   world[(i+1)%N][j]+ world[(i+1)%N][(j+1)%N])/255

            if world[i][j]== 255:

                if total>3 or total<2:
                    newWorld[i][j]== 0
                elif total==3:
                    newWorld[i][j]== 255

    img.set_data( newWorld )
    world[:] = newWorld[:]
    return img

N = 50
SPEED = 100
PROB_LIFE = 40


## TODO - Write code here to create the initial population
##   of the world. I recommend creating an N x N array that
##   is initially filled with random numbers from 0 to 99.
##   Then use the PROB_LIFE to change the entries to be
##   either alive (255) or dead (0).
world= np.random.choice([0,255], N*N, p=[1-((PROB_LIFE)/100),(PROB_LIFE)/100]).reshape(N,N)

fig, ax = plt.subplots( )
img = ax.imshow( world, interpolation='nearest' )
ani = animation.FuncAnimation( fig, update, fargs = ( img, world, N ),
                               frames = 10, interval = SPEED,
                               save_count = 50 )
plt.show( )

# This is the end of the program. You should not need
#   anything after this point.

Tags: ofthetoimgforworldisupdate
1条回答
网友
1楼 · 发布于 2024-09-28 21:39:10

必须使用=而不是==在中分配新值

newWorld[i][j] = 0   # need `=` instead of `==

newWorld[i][j] = 255 # need `=` instead of `==

现在你将看到动画。在

但是你也有错误的elif-错误的缩进-正确

^{pr2}$

或者更具可读性

        if world[i][j] == 255:

            if total > 3 or total < 2:
                newWorld[i][j] = 0

        else:

            if total == 3:
                newWorld[i][j] = 255

相关问题 更多 >