我正在阅读“使用Python发明自己的游戏”#39;我试图创造一本书中的游戏。即使我的代码与书中的代码相符,我仍然会收到错误:
File "/Users/Rocky/reverso.py", line 251, in <module>
resetBoard(mainBoard)
File "/Users/Rocky/reverso.py", line 27, in resetBoard
board[x][y] = ' '
IndexError: list index out of range
代码:
def resetBoard(board):
for x in range(8):
for y in range(8):
board[x][y] = ' ' #This is line 27
board[3][3] = 'X'
board[3][4] = 'O'
board[4][3] = 'O'
board[4][4] = 'X'
def getNewBoard():
board = []
for i in range(8):
board.append([' '] * 8)
return board
while True: # line 248
mainBoard = getNewBoard()
resetBoard(mainBoard) # This is line 251
playerTile, computerTile = enterPlayerTile()
showHints = False
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
答案 0 :(得分:0)
函数HL_DEBUG_CODEGEN=1
中的返回语句缩进不正确。
答案 1 :(得分:-1)
您可以使用以下方式初始化列表:
board = [[' ' for _ in range(8)] for _ in range(8)]
它应该初始化一个8x8 2d列表(这将无错误地工作)。
此代码有效:
def resetBoard(board):
for x in range(8):
for y in range(8):
board[y][x] = ' '
board[3][3] = 'X'
board[3][4] = 'O'
board[4][3] = 'O'
board[4][4] = 'X'
def getNewBoard():
return [[' ' for _ in range(8)] for _ in range(8)]
while True: # line 248
mainBoard = getNewBoard()
resetBoard(mainBoard) # This is line 251
playerTile, computerTile = enterPlayerTile()
showHints = False
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')