【问题标题】:Make copy of class arrays without the same id复制没有相同 id 的类数组
【发布时间】:2021-02-12 21:10:08
【问题描述】:

我正在做康威的生命游戏。 有两件事是错误的。

  1. 出于某种原因,动画代码正在接收网格信息但未正确绘制它,只为所有单元格显示一个值。这以前有效,但我对 matplotlib 了解不多,所以我找不到问题所在。
  2. 我需要找到一种方法使我的网格相等但不连接,即何时更新一个我不希望另一个更改。 [我认为我做错了什么在第 91 行]
import numpy as np
import random as rnd
import matplotlib.pyplot as plt
from matplotlib import animation, rc, cm
rc('animation', html='html5')



class Board(object):
    def __init__(self, row, col, empty=False):
        '''
        Rows and columns established,
        grid is made either empty or not.
        '''
        self.row = row
        self.col = col

        if empty:
            self.grid = self.__MakeEmptyGrid()
        else:
            self.grid = self.__MakeRandomGrid()
        
    def __MakeRandomGrid(self):
        '''
        Makes an array filled with random ones and 
        '''
        return np.random.randint(2, size=(self.row, self.col))

    def __MakeEmptyGrid(self):
        '''
        Makes an array filled with zeros
        '''
        return np.zeros((self.row, self.col), dtype=int)


class Game(Board):
    '''Class does operation on the grids'''
    SIZE = 10  ##### Change SIZE here #####

    def __init__(self):
        '''
        Making 2 grids
        nr.1 is to check each cell.
        nr.2 is used to update the grid
        '''
        self.grid_1 = Board(Game.SIZE, Game.SIZE, empty=False).grid
        self.grid_2 = Board(Game.SIZE, Game.SIZE, empty=True).grid

    def __get_neighbours(self, r, c):
        '''
        Calculates number of live neighbours around a given cell
        '''
        self.total = 0
        for rr in [-1, 0, 1]:
            for cc in [-1, 0, 1]:

                if r+rr == -1 or c+cc == -1:
                    continue
                elif r+rr == Game.SIZE or c+cc == Game.SIZE:
                    continue
                else:
                    self.total += self.grid_1[r+rr][c+cc]
        # Only count neighbours so we subtract the middle cell (r,c)
        self.total -= self.grid_1[r][c]

    def __update_table(self, r, c):
        '''
        Table is updated with Conway's Rules
        '''
        if self.grid_1[r][c]  == 1: 
            if self.total < 2 or self.total > 3: 
                self.grid_2[r][c] = 0
            else:
                self.grid_2[r][c] = 1

        else: 
            if self.total == 3: 
                self.grid_2[r][c] = 1

    def cycle(self):
        '''
        Call method to cycle through game one time
        '''
        for r in range(Game.SIZE):
            for c in range(Game.SIZE):

                self.__get_neighbours(r, c)
                self.__update_table(r, c)

        ## I think this is my error.
        self.grid_1 = self.grid_2.copy() ######
        # i have tried:
        # self.grid_1 = self.grid_2[:]
        # self.grid_1 = self.grid_2

    def __str__(self):
        string = ''
        for row in self.grid_1:
            for c in row:
                string += str(c)
            string += '\n'
        return string


grid = Game()

def update_grid(*args):
    grid.cycle()
    im.set_array(grid.grid_2)
    return im,

fig, ax = plt.subplots()
ax.axis('off')
im = plt.imshow(grid.grid_2, interpolation = "nearest", animated=True)

anim = animation.FuncAnimation(fig, update_grid, frames=60, 
                                interval=150, blit=True)
plt.show()
#plt.close()
anim

'''
Það er tvennt sem er að.
1. Griddin eru að updatast saman, þ.e. þegar ég updata grid2 þá gerist það sama við grid1
2. af eh ástæðum þá vill hann ekki plott shittið.
'''




【问题讨论】:

    标签: python arrays list class animation


    【解决方案1】:

    我认为这里的问题是您正在制作“浅拷贝”,而不是“深拷贝”。请参阅here 了解更多信息。

    作为修复,请尝试导入副本:

    import copy
    

    并将第 91 行更改为:

    self.grid_1 = copy.deepcopy(self.grid_2)
    

    【讨论】:

    • 谢谢,这解决了我的问题。您有解决动画错误的想法吗?
    • 你的意思是你的动画没有变化?一直显示同一帧?
    • 一直显示紫框。它应该是紫色的,活细胞是黄色的。我添加了一个打印语句来打印出每一帧的网格,并且网格在不断变化,但不是绘图,所以这告诉我错误可能在动画代码或 updateGrid 函数的某个地方。
    • 在动画中发现我的错误,由于某种原因,我无法使用 grid_2 进行绘图,但 grid_1 可以完美运行,并且使用您的 deepcopy 解决方案,一切正常。谢谢!
    猜你喜欢
    • 2015-09-29
    • 2014-06-13
    • 2011-11-24
    • 2014-10-08
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多