I'm am beginning my journey into the world of python. I have done a couple of small projects, but the game of life really piqued my interest. Unfortunately, when I tried to replicate the game, everything worked except for the death of my cells. Per the rules, if a live cell has less than 2 neighbors, or more than 3, it should die. Cells are being born, but alas, they seem to be immortal. Can anyone spot my mistake? I'm including the entire code because I have no idea where I went wrong.
import random, time, copy
height = 10
width = 10
next = []
for x in range(width):
column = []
for y in range(height):
if random.randint(0, 1) == 0:
column.append(" ")
else:
column.append("#")
next.append(column)
while True:
print("\n\n\n\n")
current = copy.deepcopy(next)
for y in range(height):
for x in range(width):
print(current[x][y], end=" ")
print()
for x in range(width):
for y in range(height):
leftco = (x - 1) % width
rightco = (x + 1) % width
botco = (y - 1) % height
topco = (y + 1) % height
neighbors = 0
if current[leftco][topco] == "#":
neighbors = neighbors + 1
if current[leftco][y] == "#":
neighbors = neighbors + 1
if current[leftco][botco] == "#":
neighbors = neighbors + 1
if current[x][topco] == "#":
neighbors = neighbors + 1
if current[x][botco] == "#":
neighbors = neighbors + 1
if current[rightco][topco] == "#":
neighbors = neighbors + 1
if current[rightco][y] == "#":
neighbors = neighbors + 1
if current[rightco][botco] == "#":
neighbors = neighbors + 1
if current[x][y] == "#" and (neighbors == 2 or neighbors == 3):
next[x][y] = "#"
elif current[x][y] == " " and neighbors == 3:
next[x][y] == "#"
else:
next[x][y] == " "
time.sleep(1)
In this section, you confused ==
and =
when you try to assign to a value of next[x][y]
if current[x][y] == "#" and (neighbors == 2 or neighbors == 3):
next[x][y] = "#"
elif current[x][y] == " " and neighbors == 3:
next[x][y] == "#"
else:
next[x][y] == " "
So it should be:
if current[x][y] == "#" and (neighbors == 2 or neighbors == 3):
next[x][y] = "#"
elif current[x][y] == " " and neighbors == 3:
next[x][y] = "#"
else:
next[x][y] = " "
By the way, you see next
is highlighted as a special name. That's because next()
is a special function in Python standard library, and you shouldn't name your own variables like that. It's harmless in your current program, because you don't use it, but develop a habit to use more specific names, that don't shadow the standard ones
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.