我是python的新手。我正在构建一个Tic tac toe游戏并使用地图在板上存储(x或o)的值。我代表董事会作为地图。然后我设计了一个功能,每次移动时都会检查玩家是否拥有一个游戏。但是我得到了KeyError。我真的不明白为什么?
board = {'1':'','2':'','3':'','4':'','5':'','6':'','7':'','8':'','9':''}
def win_lose_draw(board, player):
global number_of_moves
if (number_of_moves <= 9 and
board[1] == board[2] == board[3] == player or
board[4] == board[5] == board[6] == player or
board[7] == board[8] == board[9] == player or
board[1] == board[4] == board[7] == player or
board[2] == board[5] == board[8] == player or
board[3] == board[6] == board[9] == player or
board[1] == board[5] == board[9] == player or
board[3] == board[5] == board[7] == player):
print 'Player ', player, ' is the winner'
elif number_of_moves == 9:
print 'The game is a draw'
def move ():
move = raw_input("Where do you want to place your sign ?")
global board
if x_turn == True:
if board[move] == 'x' or board[move] == 'o':
print 'Place already taken, can not be overwritten'
else:
board[move] = 'x'
print_board()
win_lose_draw(board, 'x')
decrement_moves()
elif o_turn == True:
if board[move] == 'x' or board[move] == 'o':
print 'Place already taken, can not be overwritten'
else:
board[move] = 'o'
print_board()
win_lose_draw(board, 'o')
decrement_moves()
set_turn()
KeyError Traceback (most recent call last)
<ipython-input-12-5a5102ef4061> in <module>()
----> 1 move()
<ipython-input-11-d25eecea0c9b> in move()
8 board[move] = 'x'
9 print_board()
---> 10 win_lose_draw(board, 'x')
11 decrement_moves()
12 elif o_turn == True:
<ipython-input-8-731dc4754d29> in win_lose_draw(board, player)
13 global number_of_moves
14 if (number_of_moves <= 9 and
---> 15 board[1] == board[2] == board[3] == player or
16 board[4] == board[5] == board[6] == player or
17 board[7] == board[8] == board[9] == player or
KeyError: 1
答案 0 :(得分:1)
你的地图的键是str的类型('1','2',...),但你查询int为board [1],board [2],...