目前用 Python自動化的樂趣 這本書寫到 Conway's game of life 問題
以下是書中的解答
def conway_game_of_life1():
import random, time, copy
WIDTH = 30
HEIGHT = 10
# Create a list of list for the cell
nextCells = []
for x in range(WIDTH):
column = [] # Create a new column
for y in range(HEIGHT):
if random.randint(0, 1) == 0:
column.append('#')
else:
column.append(' ')
nextCells.append(column)
while True : # This is Main loop.
print('\n\n\n\n\n') # Separate each step with newlines.
currentCwlls = copy.deepcopy(nextCells)
# Print currentCells on the screen :
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCwlls[x][y], end = '') # Print the 0 or 1.
print() # Print a newline at the end of the row.
# Calculate the next step's cells based on current step's cells :
for x in range(WIDTH):
for y in range(HEIGHT):
# Get neigboring coordinates:
# use " % WIDTH " can ensure leftCoord is always between 0 and WIDTH - 1.
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
# Count the number of living neighbors:
numNeighbors = 0
**# 在下一行出錯**
if currentCwlls[leftCoord][aboveCoord] == '#' :
numNeighbors += 1
if currentCwlls[x][aboveCoord] == '#' :
numNeighbors += 1
if currentCwlls[rightCoord][aboveCoord] == '#' :
numNeighbors += 1
if currentCwlls[rightCoord][y] == '#' :
numNeighbors += 1
if currentCwlls[leftCoord][y] == '#' :
numNeighbors += 1
if currentCwlls[rightCoord][belowCoord] == '#' :
numNeighbors += 1
if currentCwlls[x][belowCoord] == '#' :
numNeighbors += 1
if currentCwlls[leftCoord][belowCoord] == '#' :
numNeighbors += 1
# Set cell based on Conway's Game of Life rules:
if currentCwlls[x][y] == 1 and (numNeighbors == 2 or numNeighbors == 3) :
nextCells[x][y] = '#'
elif currentCwlls[x][y] == 0 and numNeighbors == 3 :
nextCells[x][y] = '#'
else:
currentCwlls = ' '
time.sleep(1)
但是出現了 string index out of range 這個錯誤
請問如何更改呢 (我用的是Anaconda的Spyder)
會報錯是因為您貼出來的程式碼,最後# Set cell based on Conway's Game of Life rules部分
else:
currentCwlls = ' '
會使currentCwlls從原本的30*10二維陣列,變為' '
所以運行到
if currentCwlls[leftCoord][aboveCoord] == '#' :
就報錯了
沒看過那本書,後面定規則的部分可能錯了,可試試改成這樣
# Set cell based on Conway's Game of Life rules:
if currentCwlls[x][y] == '#':
if numNeighbors < 2 or numNeighbors > 3:
nextCells[x][y] = ' '
elif numNeighbors == 3:
nextCells[x][y] = '#'
參考自康威生命遊戲#規則
Please accept my sincerest appreciation for the author's willingness to delve deeply into geometry dash web the complexities of the topic and provide readers with a wealth of valuable information.
It seems there's an indexing issue in your Conway's Game of Life code. Make sure you're using the correct dimensions for your lists. For a fun challenge, consider trying an "iq test free online" to sharpen your problem-solving skills!
Games with complex storylines bitlife 2 can improve literacy and language skills. Reading instructions, following plots, and engaging with in-game dialogue helps expand vocabulary and comprehension.