【发布时间】:2021-02-12 21:10:08
【问题描述】:
我正在做康威的生命游戏。 有两件事是错误的。
- 出于某种原因,动画代码正在接收网格信息但未正确绘制它,只为所有单元格显示一个值。这以前有效,但我对 matplotlib 了解不多,所以我找不到问题所在。
- 我需要找到一种方法使我的网格相等但不连接,即何时更新一个我不希望另一个更改。 [我认为我做错了什么在第 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