Richard Okpala Richard Okpala -4 years ago 226
Python Question

python tic tac toe winning conditons

hey guys for my class assignment we were told to code the logic for a tic tac toe game ive already checked for all the winning conditions for tic tac toe expect if the game is a draw

the board[col_index][row_index]
for ex a winning condition for
if the values were:

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')

going off of that code how would i write an if statement to determine a draw

Answer Source

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')

    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download