2017-09-28 52 views
0

我是python的新手。我正在構建一個Tic tac toe遊戲,並使用地圖將(x或o)的值存儲在棋盤上。我代表董事會作爲地圖。然後我設計了一個函數,在每次移動時都檢查一個玩家是否有一個遊戲。但是我得到了KeyError。我不明白爲什麼?地圖的比較單個地圖中的值python

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 

回答

1

鍵是STR( '1', '2',...)的類型,但你查詢INT爲板[1],板[2],...

+0

感謝它的工作。 – Asim