I’m writing a type of cellular automata That has a higher chance of making a cell be alive(1) the more neighbors it has but obviously get errors when trying to check the amount of neighbors on a cell on the edge or corner of the board since I can’t check for example if the cell to the right of a cell on the far right is alive or not but I want it to then wrap around to the far left and check those ones.
I understand that I can check where the cell I’m looking at is but that would increase the amount of code in amt() to around 9 times the code which I think is too much and I assume there’s probably a way to make it neater.
from random import randint
global board
board = []
csize = 69
rsize = 69
for col in range(csize):
board.append([])
for row in range(rsize):
#board[col].append(0)
if col == 0:
board[col].append(1)
else:
board[col].append(0)
def ranize():
for col in range(len(board)):
for row in range(len(board)):
board[col][row] = randint(0,1)
def check():
for col in range(len(board)):
for row in range(len(board)):
if board[col][row] == 1:
return True
return False
def show():
loc = "n"
for col in range(len(board)):
for row in range(len(board[col])):
if board[col][row] == 1:
loc += "@ "
else:
loc += f"{amt(col, row)} "
loc += "n"
print(loc, end = "r")
def amt(col ,row):
loc = 0
if col != 0 and col != csize-1 and row != 0 and row != rsize-1: #Center board
if board[col-1][row-1] == 1: #Check Col-1
loc += 1
if board[col-1][row] == 1:
loc += 1
if board[col-1][row+1] == 1:
loc += 1
if board[col][row-1] == 1: #Check Col
loc += 1
if board[col][row+1] == 1:
loc += 1
if board[col+1][row-1] == 1: #check Col+1
loc += 1
if board[col+1][row] == 1:
loc += 1
if board[col+1][row+1] == 1:
loc += 1
return(loc)
def onestep():
if not check():
input("All cells dead, press Enter to randomize board: ")
ranize()
for col in range(len(board)):
for row in range(len(board[col])):
neighbors = amt(col, row)
ranum = randint(0, 8)
if board[col][row] == 1:
if 8-neighbors > ranum:
board[col][row] = 0
else:
if neighbors > ranum:
board[col][row] = 1
while True:
show()
onestep()
# input()
aecy four is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.