Make copy of class arrays without the same id

Viewed 40

I am doing Conway's Game Of Life. There are two things that are wrong.

  1. For some reason the animation code is receiving the grid information but not plotting it right, just shows one value for all cells. This was working before but I don't know much about matplotlib so i can't find what's wrong.
  2. I need to find a way to make my grids equal but not connected, that is when is update one I don't want the other one to change. [I think what i'm doing wrong is in line 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ð.
'''




1 Answers

I think the issue here is that you are making a "shallow copy", not a "deep copy". See here for more information.

As a fix, try importing copy:

import copy

and changing line 91 to:

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