Asim
Asim

Reputation: 543

Comparing values in single map python

I am new to python. I am building a Tic tac toe game and using a map to store the values of (x or o) on the board. I am representing the board as a map. I have then designed a function that checks if a player has one the game or not each time a move is made. But I am getting KeyError. I don't really understand why?

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

Upvotes: 0

Views: 44

Answers (1)

Ali Cevahir
Ali Cevahir

Reputation: 66

Keys of your map is type of str ('1', '2', ...), but you query int as board[1], board[2], ...

Upvotes: 1

Related Questions