gpt4 book ai didi

python - 如何使用 matplotlib 为一组点设置动画?

转载 作者:太空宇宙 更新时间:2023-11-03 14:49:34 25 4
gpt4 key购买 nike

我有一个已实现的康威生命游戏:

def neighbors(point):
x, y = point
for i, j in itertools.product(range(-1, 2), repeat=2):
if any((i, j)):
yield (x + i, y + j)

def advance(board):
newstate = set()
recalc = board | set(itertools.chain(*map(neighbors, board)))

for point in recalc:
count = sum((neigh in board)
for neigh in neighbors(point))
if count == 3 or (count == 2 and point in board):
newstate.add(point)

return newstate

我想可视化结果,所以我尝试修改给定的示例 Matplotlib animation example :

glider = set([(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)])

fig, ax = plt.subplots()

x, y = zip(*glider)
mat, = ax.plot(x, y, 'o')

def animate(i):
glider = advance(glider)
x, y = zip(*glider)
mat.set_data(x, y)
return mat,

ani = animation.FuncAnimation(fig, animate, interval=50)
plt.show()

但这只是情节 the initial points .

最佳答案

您的代码实际上应该会产生错误。问题是您在分配之前引用了 glider

注意 python 函数中变量的局部作用域。例如。尝试

a = 0
def f():
a = a + 1
f()

这会给你同样的错误。

在您的康威生命游戏代码中,您可以通过使 glider 可用于全局范围 global glider 来规避此问题。还要确保您的轴限制允许看到动画。

完整示例:

import itertools
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def neighbors(point):
x, y = point
for i, j in itertools.product(range(-1, 2), repeat=2):
if any((i, j)):
yield (x + i, y + j)

def advance(board):
newstate = set()
recalc = board | set(itertools.chain(*map(neighbors, board)))

for point in recalc:
count = sum((neigh in board)
for neigh in neighbors(point))
if count == 3 or (count == 2 and point in board):
newstate.add(point)

return newstate

glider = set([(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)])

fig, ax = plt.subplots()

x, y = zip(*glider)
mat, = ax.plot(x, y, 'o')

def animate(i):
global glider
glider = advance(glider)
x, y = zip(*glider)
mat.set_data(x, y)
return mat,

ax.axis([-15,5,-15,5])
ani = animation.FuncAnimation(fig, animate, interval=50)
plt.show()

enter image description here

关于python - 如何使用 matplotlib 为一组点设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46849712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com