-1

I have a 3x3 nested list for a tic tac toe program and I'm trying to evaluate if the current board state matches certain conditions, but it seems to be evaluating True for the wrong conditions? For example the following returns True when in my mind it shouldn't, can anybody explain why?

current_board_state = [['.', '.', 'o'], ['.', 'o', '.'], ['o', '.', '.']]
def check_if_win(current_board_state, current_mark):
    if current_board_state[0][0] and current_board_state[1][0] and current_board_state[2][0] == current_mark:
        print("Yes")
        return True
    else:
        print("No")
        return False
print(check_if_win(current_board_state, "o"))
mnms
  • 1

1 Answers1

0

You're being affected by what Python considers True vs. False.

For your condition, your intention is that you're trying to check 3 spots on the board to see if they're all the current_mark:

if current_board_state[0][0] and current_board_state[1][0] and current_board_state[2][0] == current_mark:

However, that's not what you're actually doing in your code. Instead, your if statement is more like:

if current_board_state[0][0]:
    if current_board_state[1][0]:
        if current_board_state[2][0] == current_mark:
            return True

And the first two statements will evaluate to true because if on a str returns True unless the string value you're checking is empty or None.

The simplest solution for you is to check everything against current_mark:

current_board_state = [['.', '.', 'o'], ['.', 'o', '.'], ['o', '.', '.']]
def check_if_win(current_board_state, current_mark):
    if (current_board_state[0][0] == current_mark
        and current_board_state[1][0] == current_mark
        and current_board_state[2][0] == current_mark):
        print("Yes")
        return True
    else:
        print("No")
        return False
print(check_if_win(current_board_state, "o"))

Note that this is quite a wordy way to do comparisons of n-values against the same value. You could use alternatives like the following or from the link in the comments to your post.

# a chained comparison
if current_board_state[0][0] == current_board_state[1][0] == current_board_state[2][0] == current_mark:
wkl
  • 77,184
  • 16
  • 165
  • 176