Dies ist ein Codeschnipsel aus Conways Spiel des Lebens mit Python. Es ist ziemlich simpel, um zu überprüfen, ob es funktioniert - und das nicht. Kann nicht herausfinden, warum, aber soweit ich das beurteilen kann, ist es etwas mit der Aktualisierung.(Closed) Conways Game of Life wird nicht korrekt aktualisiert (Python)
Würde schätzen jede Eingabe, warum es aktualisiert, wie es funktioniert:
Gif in pygame (gleichen Code): http://imgur.com/6US3Nje nicht korrekt Aktualisierung: http://imgur.com/9gubzAF
import pprint,random
#here we make the initial board, 6x6
board = []
for y in range (6):
row = []
for x in range (6):
row.append(random.randint(0,1))
board.append(row)
#and display it
pprint.pprint(board)
#this function counts the neighbours for each cell
def neighbours(x,y):
counter = 0
neighbours = \
[(x-1,y+1),(x,y+1),(x+1,y+1),\
(x-1,y), (x+1,y),\
(x-1,y-1),(x,y-1),(x+1,y-1)]
for n in neighbours:
a, b = n
try:
counter += board[a][b]
except:
pass
#printed out the counter to check if it counted correctly (it does, as far as I could tell)
if x == 4 and y == 4:
print(counter)
return counter
#function to make a new board based off the old one - basically, the updater.
#here's where the problem might lie - but for the life of me I cannot tell where and why.
def new(board):
new_board = []
for y in range(6):
new_row = []
for x in range(6):
n = neighbours(x,y)
oldcell = board[x][y]
#everything is set up to be according to the rules
#(if dead(0) can only come alive with 3 alive cells
#(if alive(1) can continue to live with exactly 2 or 3 live neighbours
if oldcell == 0:
newcell = 0
if n == 3:
newcell = 1
elif oldcell == 1:
newcell = 1
if n > 3 or n < 2:
newcell = 0
new_row.append(newcell)
new_board.append(new_row)
return new_board
#displaying the board for 6 instances
for i in range (6):
nboard = new(board)
board = nboard
pprint.pprint(board)
Vielen Dank im Voraus!
Nicht sicher, was das Problem ist, aber Sie könnten diese innere Logik zu 'newcell = int (n in (2, 3)) vereinfachen, wenn oldcell sonst int (n == 3)' –
@tobias_k Diese Art der Vereinfachung ist wirklich nur gut in einem Wettbewerb, wo Sie anhand der Anzahl der im Code verwendeten Anweisungen beurteilt werden könnten. In fast allen anderen Fällen ist die Erweiterung der Logik, wie sie das OP gemacht hat, für Lesbarkeits- und Debugging-Zwecke viel besser. – Xirema
@Xirema Ich denke, das ist eine Frage der Meinung. Wenn ich diese Zeile sehe, lese ich "newcell ist am Leben, wenn es zwei oder drei Nachbarn gibt, wenn die alte Zelle lebt, ansonsten wenn es genau drei Nachbarn gibt", die IMHO ist viel einfacher zu begreifen als diese 8 Zeilen verschachtelten if/sonst. Aber wie gesagt, es ist eine Frage der persönlichen Vorliebe. –