1

Hello I have simple code here to determine if there is a win in a tic-tac-toe game. I am having trouble getting the condition right to determine a win.

board = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3']]

the top row is 7,8,9 the middle 4,5,6 and the bottom 1,2,3 I wrote a if statement to detect when a winner of 'X' or 'O' has been determined.

   if ('X' == (board[0][0] and board[0][1] and board[0][2])) or ('O' == (board[0][0] and board[0][1] and board[0][2])):
    return True
elif ('X' == (board[1][0] and board[1][1] and board[1][2])) or ('O' == (board[1][0] and board[1][1] and board[1][2])):
    return True
elif ('X' == (board[2][0] and board[2][1] and board[2][2])) or ('O' == (board[2][0] and board[2][1] and board[2][2])):
    return True
elif ('X' == (board[0][0] and board[1][0] and board[2][0])) or ('O' == (board[0][0] and board[1][0] and board[2][0])):
    return True
elif ('X' == (board[0][1] and board[1][1] and board[2][1])) or ('O' == (board[0][1] and board[1][1] and board[2][1])):
    return True
elif ('X' == (board[0][2] and board[1][2] and board[2][2])) or ('O' == (board[0][2] and board[1][2] and board[2][2])):
    return True
elif ('X' == (board[0][0] and board[1][1] and board[2][2])) or ('O' == (board[0][0] and board[1][1] and board[2][2])):
    return True
elif ('X' == (board[0][2] and board[1][1] and board[2][0])) or ('O' == (board[0][2] and board[1][1] and board[2][0])):
    return True
else:
    return False

I would like for the conditions to return True if all three of the Boards are full of either X's or O's. Sorry for the repeat question notice, I have rewrote the if statements again and wish someone could explain what I have done wrong here. At this moment I am having lot's of issues writing these conditionals and any explanation would be much appreciated. -Thanks

kwjamesblond
  • 39
  • 1
  • 1
  • 7
  • Is that code your, or is not mutable? – T.Woody Aug 27 '18 at 21:52
  • 3
    Try typing `('X' or 'O')` into your interactive interpreter and see what it actually means. – abarnert Aug 27 '18 at 21:53
  • Just as an aside, you would be better off with a function that returned the winner (`X`, `O` or `None`, for example) rather than the fact that someone has one. Then you can act approriately in the caller and your statements become simpler: `if (board[0][0] != ' ') and (board[0][0] == board[0][1]) and (board[0][0] == board[0][2]): return board[0][0]`, returning `None` if all eight tests fail. – paxdiablo Aug 28 '18 at 00:49

0 Answers0