Reputation: 13
I am coding the logic for a tic tac toe game.
I have already checked for all the winning conditions for tic tac toe.
I now need to check if the game is a draw.
board_values = [[x, x, x],
[None, None, None],
[None, None, None]]
#the if statement for that winning condition would be
if board_values[0][0]=='x' and board_values[1][0] =='x' and board_values[2][0]=='x':
board.display_message('player x won')
How would I write an if
statement to determine a draw?
Upvotes: 0
Views: 2583
Reputation: 77910
You would do that indirectly. If the board is full, and neither player has a win, then it's a draw. It would be the else clause of your if-elif-else statement.
if board_values[0][0] == 'x' and \
board_values[1][0] == 'x' and \
board_values[2][0] == 'x':
board.display_message('player x won')
elif board_values[0][0] == 'o' and \
board_values[1][0] == 'o' and \
board_values[2][0] == 'o':
board.display_message('player o won')
else:
board.display_message('The game is a draw')
Of course, you have to extend the checks for all possible wins.
Speaking of which, there's a neat way to encode the spaces to aid in checking. Instead of using the canonical
1 2 3
4 5 6
7 8 9
Number the squares as a 3x3 magic square
6 7 2
1 5 9
8 3 4
Now you can check for a win somewhat more efficiently: if a player owns any three squares that add up to 15, that's a win. Use itertools to generate those sets of 3, wrap that in a map(sum()), and slap an if any() check on that: your check for a win reduces to one complex line of code.
Upvotes: 5