liveBook · Manning

Winner

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A winner is the player determined by a game's rules to have achieved the winning condition.

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

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Implements all eight winning patterns and tests positive and negative boards, stopping short of a complete interactive game.
Examples
Uses empty, partially marked, and XXXOO.... boards, plus exhaustive winning-pattern and randomized losing-board tests.
What it assumes
Assumes basic Python while teaching board state, indexed combinations, enumerate(), all(), map(), and None through the implementation.
What you can do after
Build it from scratch by implementing find_winner(), rendering outcomes, and testing winning and losing boards with pytest.
How it connects
Connects game state, board representation, Boolean logic, lists, functions, and unit testing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.