A winner is the player whose marks satisfy a game's winning condition. In Tic-Tac-Toe, the program reports X, O, or no winner after displaying the board. section 21.0 section 21.1
Determine the winner by:
- Representing the board as nine positions containing X, O, or an open-cell marker. section 21.1
- Checking the three horizontal, three vertical, and two diagonal winning combinations. section 21.2.3
- Returning the winning player immediately, or None when no combination belongs entirely to one player. section 21.1.4
- Testing every winning pattern for both players and shuffling losing boards to prevent false positives. section 21.1.4
A winning board
Running the program with XXXOO.... renders X across the top row and prints “X has won!”; an empty board prints “No winner.”
def find_winner(board):
"""Return the winner"""
winning = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], #1
[2, 5, 8], [0, 4, 8], [2, 4, 6]]
for player in ['X', 'O']:
for i, j, k in winning: #2
combo = [board[i], board[j], board[k]]
if combo == [player, player, player]:
return player
Browse the compact find_winner() implementation, including its indexed winning patterns and early return for X or O. section 21.2.3
