[英]Python Creating Conway's Game Of Life
所以我正在编写一个代码来模拟康威的“生命游戏”。 我已经成功地实现了游戏,但是,我还缺少一个额外的步骤
除了用于确定细胞是活着还是死亡的逻辑之外,我已经处理了所有事情。 我们使用numpy数组来存储1和0,其中1被认为是活着的,0被认为是死的。
有没有什么方法可以循环遍历数组并打印一个单元格是活着还是死了,还是某种形式的?
这是我的代码。
对于初始创作。
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output
from time import sleep
def update_plot(array, figsize=(7,5), title=''):
clear_output(wait=False)
plt.figure(figsize=figsize)
plt.imshow(array,cmap="gray")
plt.title(title)
#plt.grid(True)
plt.xlabel('Remember alive is white, dead is black')
plt.show();
然后,这是为了开始游戏。
def startup(random_percent=None):
size_to_build = input("enter the size of your game of life\n")
dimension = int(size_to_build)
##Build the game board, bias is an optional parameter you can pass the function
if random_percent==None:
game_board = np.random.randint(2,size=(dimension,dimension))
else:
game_board = np.arange(dimension**2)
#In place shuffle
np.random.shuffle(game_board)
#Grab number we should make alive
alive = int(np.floor(len(game_board)*random_percent))
#Set those elements to be alive
zeros = np.zeros(dimension**2)
alive_cells = game_board[0:alive:1]
zeros[alive_cells]=1
game_board = zeros.reshape(dimension,-1)
return game_board
这是为了运行游戏。
def game_of_life():
start_board = startup()
board = start_board
count = 1
not_stable = True
while not_stable:
title_plot="This is iteration number: " + str(count)
update_plot(board,title=title_plot)
board_prev = board
board = update_game_board(board)
if np.array_equal(board_prev,board):
not_stable = False
sleep(2)
count+=1
print("Stable game conditions reached after:",count,"iterations")
这是我试图改进的功能。
def update_game_board(input_board):
for element in input_board:
print("Alive Or Dead")
return np.logical_not(input_board)*1
我如何访问数组中的“死”和“活”元素?
我对numpy和python很新,并且只使用它几乎没有。 任何帮助将非常感激!
为初学者实现这一目标的最简单方法是一次循环NumPy数组一个元素并计算其相邻元素的总和。 你没有指定边界条件,所以我假设了周期性边界(即世界在顶部/底部和左/右环绕)。
您可以使用NumPy的“形状”功能访问数组的形状,该功能将告诉您阵列中有多少行和列(尽管它们在您的规范中相同)。 您还可以使用NumPy的“zeros_like”函数创建一个大小相似的全零数组。
def update_game_board(board):
new_board = np.zeros_like(board)
r, r = np.shape(board)
for i in range(r):
for j in range(r):
neighbors = [[i,j],
[i,j+1],
[i,j-1],
[i+1,j],
[i-1,j],
[i+1,j+1],
[i+1,j-1],
[i-1,j+1],
[i-1,j-1]]
neighbor_sum = 0
# Let's count all of the living neighbors
for n in neighbors:
x = n[0] % r
y = n[1] % r
neighbor_sum += board[x,y]
if board[i,j] == 1:
if neighbor_sum in [2,3]:
new_board[i,j] = 1
else:
if neighbor_sum == 3:
new_board[i,j] = 1
return new_board
一旦您对Python和NumPy阵列更加熟悉,您就可以使用不同的边界条件或更有效的方法来计算更新的板。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.