以下是我一直在研究的代码,一个简单的Tic Tac Toe游戏..我已经研究过这个错误,但我似乎找不到合适的解决方案 代码是:
def isSpaceFree(board,move):
return board[move]==' '
#--------------------------------------------------------------------------
def getPlayerMove(board):
move=' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,move):
print('Your chance,what square do you want to play in ?')
move=input()
return int(move)
while gameIsPlaying:
if turn == 'player':
# Player's turn.
drawBoard(theBoard)
move = getPlayerMove(theBoard)
错误讯息:
Traceback (most recent call last):
File "C:\Python33\FirstTime.py", line 162, in <module>
move=getPlayerMove(theBoard)
File "C:\Python33\FirstTime.py", line 82, in getPlayerMove
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,move):
File "C:\Python33\FirstTime.py", line 75, in isSpaceFree
return not board[move]== 'X' or board[move]=='O' TypeError: list indices must be integers, not str
答案 0 :(得分:2)
input
函数返回一个字符串。因此,在尝试将move
变量用作列表索引之前,需要先强制转换它。
此功能应该有效:
def isSpaceFree(board,move):
return board[int(move)]==' '
甚至更好,使用原始isSpaceFree
方法:
def getPlayerMove(board):
move = -1 # initialize a 'out of range' number, not an empty string, for consistency
while move not in range(1, 10) or not isSpaceFree(board,move):
print('Your chance,what square do you want to play in ?')
try:
move = int(input()) # parse number on the fly
except ValueError: # if the user doesn't enter a number, display an error
print('Please enter a number')
move = -1
return move
有关信息:
>>> range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
答案 1 :(得分:1)
问题在于move的第一个值应该是整数 所以你可以使它= 10之类的东西并在调用函数
时抛出它def getPlayerMove(board):
move='10'
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,int(move)):
print('Your chance,what square do you want to play in ?')
move=input()
return int(move)
答案 2 :(得分:0)
move
首先是一个字符串(' '
)。要将其用作列表中的索引,需要使用int。您可以使用int(move)
将字符串转换为int。
你应该使用
move = 0
作为初始化,
while move not in range(1, 10) ...
作为测试,因为输入已经返回一个int。