February 19, 2015

Week of 02/15/15 - Python Part 20: Debugging

    I have found a bug in my code. The problem is that, when the diagonal, starting from the bottom left and ending in the top right, is completed, the game doesn't register it as a win. For example:

    Turn # 9
       [1] [2] [3]
     1    | X | O 
       -----------
     2  X | O | X 
       -----------
     3  O | X | O 
    Player 1: Enter the column number of your move:

    Even though the bottom-left to top-right diagonal is completed, the game doesn't recognize it. The other diagonal is recognized, and so are the other rows and columns. Now, let's look at the code behind the checker function:

    elif (row + column) == 2:
        if board[0][2] == board[1][1] == board[2][0]:
            if board[0][2] == " X ":
                return 1
            elif board[0][2] == " O ":
                return 2
(I have colored the background of the code blue to signify that this is code, not terminal output.)

    First, I must explain that in order for the board to work, 1 is subtracted from both the row and the column in order to make the row and column numbers correspond with their list entry. With that out of the way,  how my code checks for a win is: after checking the column the move was in, and the row the move was in, it checks if the column was equal to the row. Because the row can only equal the column on a single diagonal, from the top-left to the bottom-right, it checks if those three are equal to each other. Then, after that, the code above checks if the column added to the row is equal to 2 because the (row,column) combinations that are on that diagonal are (0,2), (1,1), and (2,0) and when you add each (row,column) pair you get 2 for each. Then it checks if they're all equal, and then it decides whether to return a 1 or a 2 depending on who's move was in the diagonal. In theory, this should work. In practice, it does not. It just goes to the next turn. Which it shouldn't. I suspect the problem to be in the first line, elif (row + column) == 2:, because the rest of the code is being used in the other elif statements.

No comments: