Я пытаюсь выполнить реалистичную жизнь игры Conway на основе списка, не используя никаких надстроек или списков списков в python 3.5.2. Проблема, с которой я сталкиваюсь сейчас, заключается в том, что число «соседей», которое имеет каждая точка, неверно. Я оставил свой оператор печати в приведенном ниже коде. В этом примере занятая ячейка обозначается символом «o», а незанятая ячейка обозначается символом «.».Правила игры в игре Conway не работают должным образом в python
#Determine how many neighbors are surrounding the provided point
def getNeighbors(board, index, columns):
neighbors = 0
try:
if(board[index + 1] == "o"):
neighbors += 1
except:
pass
try:
if(board[index - 1] == "o"):
neighbors += 1
except:
pass
try:
if(board[index + columns] == "o"):
neighbors += 1
except:
pass
try:
if(board[index - columns] == "o"):
neighbors += 1
except:
pass
try:
if(board[index - columns + 1] == "o"):
neighbors += 1
except:
pass
try:
if(board[index - columns - 1] == "o"):
neighbors += 1
except:
pass
try:
if(board[index + columns + 1] == "o"):
neighbors += 1
except:
pass
try:
if(board[index + columns - 1] == "o"):
neighbors += 1
except:
pass
return neighbors
#Creates the game board in a list of lists
def mkBoard(rows,columns):
board = ["."] * rows * columns
return board
#Used to edit a point on the game board
def editPoint(x,y,board,columns):
i = 0
i = x + ((y - 1) * columns) - 1
if(board[i] == "o"):
board[i] = "."
elif(board[i] == "."):
board[i] = "o"
return board
#Simulates the next step in the game
def nextTurn(board, columns):
prevBoard = board
i = 0
for index in prevBoard:
neighbors = 0
if(index == 'o'):
neighbors = getNeighbors(prevBoard, i, columns)
print(neighbors)
if(neighbors == 0 or neighbors == 1):
board[i] = "."
elif(neighbors >= 4):
board[i] = "."
elif(index == "."):
neighbors = getNeighbors(prevBoard, i, columns)
print(neighbors)
if(neighbors == 3):
board[i] = "o"
i += 1
return board
#Prints the board to the screen to show the user what is happening
def printBoard(board, columns):
counter = 0
for cell in board:
print(cell,end=" ")
counter += 1
if(counter == columns):
print('\n')
counter = 0
print("======Conway's Game of Life======")
#Take user input for number of rows and columns for the board and converts them into integers
rows = input('Enter the number of rows:')
rows = int(rows)
columns = input('Enter the number of columns:')
columns = int(columns)
#Create the board and show it to the user
board = mkBoard(rows,columns)
printBoard(board,columns)
choice = 0
#If the user wants to add points to the board they can, otherwise they can begin the game
while(1 != 3):
choice = input('Make a choice:\n1) Change a point\n2) Continue the game\n3) Quit\n')
if(choice =='1'):
x = input('Enter the x coordinate of the point to negate: ')
x = int(x)
y = input('Enter the y coordinate of the point to negate: ')
y = int(y)
board = editPoint(x,y,board, rows)
printBoard(board,columns)
elif(choice =='2'):
board = nextTurn(board, columns)
printBoard(board,columns)
elif(choice == '3'):
break
Что происходит в 'getNeighbors', если' index' находится в начале или в конце строки? – jwodder
Можете ли вы создать [mcve]? Если 'getNeighbors' - это код, о котором вы спрашиваете, удалите как можно больше остальной части кода. –
@jwoddler Похоже, проблема в том, что мой код не знает разницы между началом и концами строк. Я попытался проверить ваше предложение, и значения соседства верны для пространств, которые должны иметь соседние, но любые пробелы, которые находятся на дальнем конце, также регистрируются как находящиеся на одном конце дисплея. – dff