我正在尝试根据youtube上的《聪明程序员》指南制作井字游戏。直到那一刻,一切都像在教程中一样顺利进行:
board = ['-','-','-',
'-','-','-',
'-','-','-',]
def display_board():
print(board[0] + ' | ' + board[1] + ' | ' +board[2])
print(board[3] + ' | ' + board[4] + ' | ' +board[5])
print(board[6] + ' | ' + board[7] + ' | ' +board[8])
def play_game():
# Display initial board
display_board()
handle_turn()
def handle_turn():
position = input("Choose a position from 1-9: ")
postion = int(position) - 1
board[position] = "X"
display_board()
play_game()
是的,所以基本上,当他运行它时,他可以从1到9中选择一个数字,并且板上的减号之一更改为“ X”。 当我这样做时,我遇到问题,控制台显示
"TypeError: list indices must be integers or slices, not str".
你能帮我吗?我不知道这是否重要,因为我确实是新手,但他使用的是python 3.6.1,而我使用的是3.7
答案 0 :(得分:0)
您在handle_turn中有错字。更改为:
def handle_turn():
position = input("Choose a position from 1-9: ")
position = int(position) - 1
board[position] = "X"
display_board()
答案 1 :(得分:0)
您发布的代码段中有一个错字。下面是可变位置错误拼写的行。
代码行不正确
postion = int(position) - 1
更正的代码段
board = ['-','-','-',
'-','-','-',
'-','-','-',]
def display_board():
print(board[0] + ' | ' + board[1] + ' | ' +board[2])
print(board[3] + ' | ' + board[4] + ' | ' +board[5])
print(board[6] + ' | ' + board[7] + ' | ' +board[8])
def handle_turn():
position = input("Choose a position from 1-9: ")
position = int(position) - 1
board[position] = "X"
display_board()
def play_game():
# Display initial board
display_board()
handle_turn()
play_game()
此代码可以正常工作。