[英]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.