没有全局变量的python动画 [英] python animation without globals

查看:58
本文介绍了没有全局变量的python动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写Conway的人生游戏"实施方案.我的第一个尝试只是在每次更新后使用matplotlib的imshow在1和0的NxN板上绘制板图.但是,由于程序在显示绘图时会暂停,因此无法正常工作.您必须关闭图才能进行下一个循环迭代.

I'm writing a Conway's Game of Life implementation. My first attempt was just to plot the board after each update using matplotlib's imshow on a NxN board of 1's and 0's. However, this didn't work as the program pauses whenever it shows the plot. You have to close the plot to get the next loop iteration.

我发现matplotlib中有一个动画包,但是它不带(或给出)变量,所以我见过它的每个实现(甚至

I found out there was an animation package in matplotlib, but it doesn't take (or give) variables, so every implementatin of it I've seen (even matplotlib's documentation) relies on global variables.

所以这里有两个问题:

1)这是可以使用全局变量的地方吗?我一直都读到,这永远不是一个好主意,但这只是教条吗?

1) Is this a place where it's ok to use globals? I've always read that it's never a good idea, but is this just dogma?

2)如何在没有全局变量的情况下在python中制作这样的动画(即使我想放弃matplotlib,我也想;标准库始终是首选).

2) how would you do such an animation in python without globals (Even if it means ditching matplotlib, I guess; standard library is always preferred).

推荐答案

这些只是示例程序.您可以使用对象代替全局变量,如下所示:

These are just example programs. You can use an object instead of global variables, like this:

class GameOfLife(object):
    def __init__(self, initial):
        self.state = initial
    def step(self):
        # TODO: Game of Life implementation goes here
        # Either assign a new value to self.state, or modify it
    def plot_step(self):
        self.step()
        # TODO: Plot here

# TODO: Initialize matplotlib here
initial = [(0,0), (0,1), (0,2)]
game = GameOfLife(initial)
ani = animation.FuncAnimation(fig, game.plot_step)
plt.show()

如果您真的想避免使用类,还可以像这样重写程序:

If you really want to avoid classes, you can also rewrite the program like this:

def step(state):
    newstate = state[:] # TODO Game of Life implementation goes here
    return newstate
def plot(state):
    # TODO: Plot here
def play_game(state):
    while True:
         yield state
         state = step(state)

initial = [(0,0), (0,1), (0,2)]
game = play_game(initial)
ani = animation.FuncAnimation(fig, lambda: next(game))
plt.show()

请注意,对于非数学动画(没有标签,图形,比例等),您可能更喜欢 pyglet pygame .

Note that for non-mathematical animations (without labels, graphs, scales, etc.), you may prefer pyglet or pygame.

这篇关于没有全局变量的python动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆