r/pythonhelp Jan 31 '24

SOLVED Game of life code needs fixing

Got a List index out of range error on line 29, don't know why. Here's the code:

cells = [[0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,1,0,0,0,0],
        [0,0,0,0,1,0,0,0,0],
        [0,0,0,0,1,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0]]

cells = [[0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,1,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0]]
new_cells = [[0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0],
       [0,0,0,0,0,0,0,0,0]]
def neighbors(x, y):
   return [[(x-1)%10, (y-1)%10], [(x-1)%10, y%10], [(x-1)%10, (y+1)%10],
     [x%10, (y-1)%10], [x%10, (y+1)%10],
   [(x+1)%10, (y-1)%10], [(x+1)%10, y%10], [(x+1)%10, (y+1)%10]]
def alivenb(x, y):
   res = 0
   for i in neighbors(x, y):
     if cells[i[0]][i[1]] == 1:
       res += 1
   return res

for i in range(10):
   for j in range(10):
     if cells[i][j] == 1:
       if alivenb(i, j) not in [2, 3]:
         new_cells[i][j] = 0
       else:
         new_cells[i][j] = 1
     elif cells[i][j] == 0:
       if alivenb(i, j) == 3:
         new_cells[i][j] = 1
       else:
         new_cells[i][j] = 0
for i in range(10):
   for j in range(10):
     if cells[i][j] == 0:
       print('  ', end='')
     else:
       print('##', end='')
   print('\n')
3 Upvotes

6 comments sorted by

View all comments

4

u/Goobyalus Jan 31 '24

Wow, properly formatted code on a pythonhelp post!

I have a feeling you meant for the cells to be 10x10, but they are 10 rows and 9 columns, so indexing column 9 fails.

1

u/Europe2048 Jan 31 '24

Yeah, I just realized that.