5

コンウェイのライフ ゲームの実装を書いています。私の最初の試みは、1 と 0 の NxN ボードで matplotlib の imshow を使用して、各更新後にボードをプロットすることでした。ただし、プロットを表示するたびにプログラムが一時停止するため、これは機能しませんでした。次のループ反復を取得するには、プロットを閉じる必要があります。

matplotlib にアニメーション パッケージがあることがわかりましたが、変数を取らない (または与えない) ため、私が見たすべての実装 ( matplotlib のドキュメントでさえ) はグローバル変数に依存しています。

ここで 2 つの質問があります。

1)これはグローバルを使用してもよい場所ですか? 私はいつもそれが良い考えではないことを読んできましたが、これは単なるドグマですか?

2)グローバルなしでPythonでそのようなアニメーションをどのように行いますか(matplotlibを捨てることを意味するとしても、標準ライブラリが常に優先されます)。

4

2 に答える 2

5

これらは単なるサンプルプログラムです。次のように、グローバル変数の代わりにオブジェクトを使用できます。

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()

本当にクラスを回避したい場合は、次のようにプログラムを書き直すこともできます。

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を好む場合があることに注意してください。

于 2013-07-07T11:58:48.557 に答える