[Tutor] Basic Question
Osmaan Mysorewala
osmaan at mysorewala.com
Thu Sep 9 02:50:45 EDT 2021
Hello,
I'm trying to write a python program to create the game of life (Here's the
wikipedia link to how the game of life works:
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life). Right now it works
only for the first iteration but then the new_arr becomes something
completely wrong the second time I run the function. I think something is
logically wrong with the neighbors function (other than how badly the
if-statements are written). For reference, I'm eventually trying to put it
on a display so that's why there's some display stuff in the comments
there. Here's the code:
rows, cols = (22, 18)
old_arr = [[0 for i in range(cols)] for j in range(rows)]
new_arr = [[0 for i in range(cols)] for j in range(rows)]
def game_of_life():
global new_arr, old_arr
for x in range(1, 21):
for y in range(1, 17):
neighbors = get_neighbors(x, y)
if old_arr[x][y] == 0:
if neighbors == 3:
new_arr[x][y] = 1
print(neighbors)
else:
new_arr[x][y] = 0
else:
if neighbors == 2:
new_arr[x][y] = 1
else:
new_arr[x][y] = 0
for i in range(len(new_arr)):
print(new_arr[i])
print()
# for x in range(0, 20):
# for y in range(0, 16):
# bitmap[x, y] = new_arr[x+1][y+1]
# display.show(group)
# new_arr = old_arr.copy()
old_arr = new_arr.copy()
# The neighbors function returns how many neighbors are present
def get_neighbors(a, b):
neighbors = 0
if old_arr[a + 1][b] == 1:
neighbors = neighbors + 1
if old_arr[a - 1][b] == 1:
neighbors = neighbors + 1
if old_arr[a][b + 1] == 1:
neighbors = neighbors + 1
if old_arr[a][b - 1] == 1:
neighbors = neighbors + 1
if old_arr[a - 1][b - 1] == 1:
neighbors = neighbors + 1
if old_arr[a + 1][b - 1] == 1:
neighbors = neighbors + 1
if old_arr[a - 1][b + 1] == 1:
neighbors = neighbors + 1
if old_arr[a + 1][b + 1] == 1:
neighbors = neighbors + 1
"""
for na in range(a - 1, a + 1):
for nb in range(b - 1, b + 1):
if (na != a and nb != b) and old_arr[na][nb]:
neighbors = neighbors + 1
# print (neighbors)
"""
return neighbors
#testing ground to try out new starting live cells
"""
old_arr[8][8] = 1
old_arr[9][8] = 1
old_arr[10][8] = 1
old_arr[7][9] = 1
old_arr[8][9] = 1
old_arr[9][9] = 1
"""
old_arr[7][8] = 1
old_arr[7][9] = 1
old_arr[8][10] = 1
old_arr[9][7] = 1
old_arr[10][8] = 1
old_arr[10][9] = 1
game_of_life()
game_of_life()
Please tell me if something is hard to understand in my description or code.
Thank You,
Osmaan Mysorewala
More information about the Tutor
mailing list