samedi 29 novembre 2014

Help with Game of Life emulator written in python


I have wrote a python script (the features are far from perfect) that will show the next generation in a 5x5 grid of cells if the rules of John Conway's Game of Life. It is used in a linux command line. A 0 represents a dead cell and a 1 represents a live cell. This is the code:


cGrid = [[0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [1, 1, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]


nextGrid = [[], [], [], [], []]


for row in cGrid: for cell in row: neighbours = 0 nCell = 0



rIndex = cGrid.index(row)
cIndex = row.index(cell)

if cGrid[rIndex][cIndex-1] == 1:
neighbours += 1
if cGrid[rIndex][cIndex+1] == 1:
neighbours += 1

if row != 0:
if cGrid[rIndex-1][cIndex-1] == 1:
neighbours += 1
if cGrid[rIndex-1][cIndex] == 1:
neighbours += 1
if cGrid[rIndex-1][cIndex+1] == 1:
neighbours += 1
if row != 4:
if cGrid[rIndex+1][cIndex-1] == 1:
neighbours += 1
if cGrid[rIndex+1][cIndex] == 1:
neighbours += 1
if cGrid[rIndex+1][cIndex+1] == 1:
neighbours += 1

if cell == 0 and neighbours == 3:
nCell = 1

if cell == 1 and neighbours == 2:
nCell = 1
if cell == 1 and neighbours == 3:
nCell = 1
if cell == 1 and neighbours >= 4:
nCell = 0

nextGrid[rIndex].append(nCell)

neighbours = 0
nCell = 0


print(nextGrid[0]) print(nextGrid[1]) print(nextGrid[2]) print(nextGrid[3]) print(nextGrid[4])


The output should look like this: [0, 0, 0, 0, 0] [1, 0, 1, 0, 0] [0, 1, 1, 0, 0] [0, 1, 0, 0, 0] [0, 0, 0, 0, 0]


But it looks like this: [0, 0, 0, 0, 0] [1, 1, 1, 1, 1] [0, 0, 0, 0, 0] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] []


I haven't got a clue why it doesn't work, so any help would be appreciated.





Aucun commentaire:

Enregistrer un commentaire