繁体   English   中英

使用matplotlib在Python 3中使用Conway进行生活游戏-显示形式的问题

[英]Conway's game of life in Python 3 with matplotlib - problem with displaying a formation

我目前正在尝试编写生活游戏的python 3实现。 我的主要目标是显示大小为n的网格,该网格将根据conway的规则随机填充。 那部分工作正常。

现在,我想实现第二种模式,该模式可以让您从给定的编队之一开始-在我的第一个尝试滑翔机中。

这是main():

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from gol_functions import *

def main():

    # get arguments from input function
    arguments = input_arguments()
    # set the arguments 
    gridsize = int(arguments.gridsize)
    interval = int(arguments.interval)
    formation = arguments.formationflag

    # if you want to start with a formation:
    if formation:
        grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
        add_glider(1, 1, grid)

    # else display a randopm grid
    else:
        grid = randomgrid(gridsize)

    fig, ax = plt.subplots()

    # colormap: black -> alive, white -> dead
    img = ax.imshow(grid, cmap='binary', interpolation='nearest')

    # this will be used to save the animation in a later version
    ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
                                  frames=10,
                                  interval=interval,
                                  save_count=50)

    # remove x and y - axis labels, numbers and ticks
    ax.axes.xaxis.set_ticklabels([])
    ax.axes.yaxis.set_ticklabels([])
    plt.xticks([])
    plt.yticks([])

    # plot the animated output
    plt.show()


    if __name__ == '__main__':
        main()

这是添加滑翔机的功能:

def add_glider(i, j, grid):
    """adds a glider with top-left cell at (i, j)"""
    glider = np.array([[0,    0, 255],
                       [255,  0, 255],
                       [0,  255, 255]])

    grid[i:i+3, j:j+3] = glider

它在位置1、1的网格中添加了一个滑翔机

这是我的更新功能:

def update(frameNum, img, grid, gridsize):
    """Updates the grid every time it is refreshed"""
    newgrid = grid.copy()
    for i in range(gridsize):
        for j in range(gridsize):
            # this formula considers the edge/boundary conditions that appear
            # every cell has to have 8 neighbouring cells
            # to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
            # we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
            total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
                         grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
                         grid[(i - 1) % gridsize, (j - 1) % gridsize] +             
                         grid[(i - 1) % gridsize, (j + 1) % gridsize] +
                         grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
                         (i + 1) % gridsize, (j + 1) % gridsize]) / 255)

        # apply conway's basic rules of the game of life for each cell
            if grid[i, j] == ON:
                if (total < 2) or (total > 3):
                    newgrid[i, j] = OFF
            else:
                if total == 3:
                    newgrid[i, j] = ON
                    # update data
                    img.set_data(newgrid)
                    grid[:] = newgrid[:]
                    return img,

但是,当我运行它以使其显示滑翔机的选项时,我看到的只是以下形式...

failedglider_1.png

迅速变成这个并变成静态的:

failedglider_2.png

...而不是在add_glider矩阵中看到的实际滑翔机。 因此,似乎该程序以某种方式在顶部添加了一个不需要的活细胞。 我试图找到它的来源...但是我找不到。

有人有任何线索吗? 我非常感谢您的帮助。 提前致谢!

通过对原始帖子中的代码进行一些较小的修复,我可以准确地生成您想要的内容。 修改后的代码在底部列出。 第一帧显示在图像框的左侧。 几帧后,看起来像右边的图像。 所以滑翔机似乎很好用:)

在此处输入图片说明

#!/usr/bin/python
# call with: python3 cgl.py 10 500 1 1

import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation

ON = 255
OFF = 0


def update(frameNum, img, grid, gridsize):
    """Updates the grid every time it is refreshed"""
    newgrid = grid.copy()
    for i in range(gridsize):
        for j in range(gridsize):
            # this formula considers the edge/boundary conditions that appear
            # every cell has to have 8 neighbouring cells
            # to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
            # we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
            total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
                         grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
                         grid[(i - 1) % gridsize, (j - 1) % gridsize] +
                         grid[(i - 1) % gridsize, (j + 1) % gridsize] +
                         grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
                         (i + 1) % gridsize, (j + 1) % gridsize]) / 255)

        # apply conway's basic rules of the game of life for each cell
            if grid[i, j] == ON:
                if (total < 2) or (total > 3):
                    newgrid[i, j] = OFF
            else:
                if total == 3:
                    newgrid[i, j] = ON
    # update data
    grid[:] = newgrid[:]
    img.set_data(newgrid)
    return img,


def add_glider(i, j, grid):
    """adds a glider with top-left cell at (i, j)"""
    glider = np.array([[0,    0, 255],
                       [255,  0, 255],
                       [0,  255, 255]])

    grid[i:i+3, j:j+3] = glider


def main():
    parser = argparse.ArgumentParser(description="Conway's game of life in Python 3")
    parser.add_argument('gridsize', type=int, help='Dimension of grid.')
    parser.add_argument('interval', type=int, help='Interval.')
    parser.add_argument('formationflag', type=bool, help='Predefined formation.')
    parser.add_argument('frame', type=int, help='How many frames to animate.')

    # get arguments from input function
    arguments = parser.parse_args()
    # set the arguments
    frame = int(arguments.frame)
    gridsize = int(arguments.gridsize)
    interval = int(arguments.interval)
    formation = arguments.formationflag

    # if you want to start with a formation:
    if formation:
        grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
        add_glider(1, 1, grid)

    # else display a randopm grid
    else:
        grid = randomgrid(gridsize)

    fig, ax = plt.subplots()

    # colormap: black -> alive, white -> dead
    img = ax.imshow(grid, cmap='binary', interpolation='nearest')

    # # this will be used to save the animation in a later version
    ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
                                  frames=frame,
                                  interval=interval,
                                  save_count=50)

    # remove x and y - axis labels, numbers and ticks
    ax.axes.xaxis.set_ticklabels([])
    ax.axes.yaxis.set_ticklabels([])
    plt.xticks([])
    plt.yticks([])

    # plot the animated output
    plt.show()

if __name__ == '__main__':
    main()
    print("DONE")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM