Home Ask Login Register

Developers Planet

Your answer is one click away!

AKor February 2016

Logical flow in tic-tac-toe issue

I'm trying to make a tic-tac-toe game. Not sure what the convention is, but I used 1 for X and 4 for O, since then a sum of 3 on a column, row, or diagonal will mean a win for X, and a sum of 12 will mean a win for O, and that combination cannot be reached in a non-winning scenario. Similarly, if all rows, columns, and diagonals equal 1,1,4 or 1,4,4 (i.e. 6 or 9) then the game is a draw.

The rest of the game works fine, except for the win conditions:

#if a row, column, or diagonal sums to 3, you win, if 12, they win 
#a number 1 = X, a number 4 = O
if (    row1 == 3
    or  row2 == 3
    or  row3 == 3
    or  col1 == 3
    or  col2 == 3
    or  col3 == 3
    or  dia1 == 3
    or  dia2 == 3
    endCondition = True
    whoWon = "You won!"

if (    row1 == 12
    or  row2 == 12
    or  row3 == 12
    or  col1 == 12
    or  col2 == 12
    or  col3 == 12
    or  dia1 == 12
    or  dia2 == 12
    endCondition = True
    whoWon = "You lost! Computer wins."

#if that was the last spot, then it is a draw
#a losing row is either 1,1,4 or 1,4,4 which equal six and 9 respectively
if (row1 and row2 and row3 and col1 and col2 and col3 and dia1 and dia2) == (6 or 9):
    endCondition = True
    whoWon = "No one. It was a draw."

Any help? I know it's a simple mistake somewhere.


Kevin February 2016

if (row1 and row2 and row3 and col1 and col2 and col3 and dia1 and dia2) == (6 or 9):

This is not the proper syntax for checking multiple values against multiple other values. (6 or 9) will always evaluate to 9. (row1 and row2 and ... and dia2) will evaluate to either 0 if any of the values are 0; or the value of dia2 if none of the values are 0. So the conditional will incorrectly evaluate to False if the board is full and dia2 is something other than 9.

Instead, try:

if all(x == 6 or x == 9 for x in (row1, row2, row3, col1, col2, col3, dia1, dia2)):

Post Status

Asked in February 2016
Viewed 2,033 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life