concept NamedTuple in category python

appears as: NamedTuple, NamedTuple, A NamedTuple
Tiny Python Projects: Learn coding and testing with puzzles and games

This is an excerpt from Manning's book Tiny Python Projects: Learn coding and testing with puzzles and games.

I’m going to improve our State class by using the NamedTuple class from the typing module as the base class. First we need to import from the typing module the classes we’ll need, such as NamedTuple, List, and Optional, the last of which describes a type that could be None or some other class like a str:

#!/usr/bin/env python3
""" Interactive Tic-Tac-Toe using NamedTuple """
 
from typing import List, NamedTuple, Optional                                 #1
 
 
class State(NamedTuple):                                                      #2
    board: List[str] = list('.' * 9)
    player: str = 'X'
    quit: bool = False
    draw: bool = False
    error: Optional[str] = None
    winner: Optional[str] = None
 
 
# --------------------------------------------------
def main() -> None:
    """Make a jazz noise here"""
 
    state = State()                                                           #3
 
    while True:                                                               #4
        print("\033[H\033[J")                                                 #5
        print(format_board(state.board))                                      #6
 
        if state.error:                                                       #7
            print(state.error)
        elif state.winner:                                                    #8
            print(f'{state.winner} has won!')
            break
 
        state = get_move(state)                                               #9
 
        if state.quit:                                                        #10
            print('You lose, loser!')
            break
        elif state.draw:                                                      #11
            print("All right, we'll call it a draw.")
            break
 
 
# --------------------------------------------------
def get_move(state: State) -> State:                                          #12
    """Get the player's move"""
 
    player = state.player                                                     #13
    cell = input(f'Player {player}, what is your move? [q to quit]: ')        #14
 
    if cell == 'q':                                                           #15
        return state._replace(quit=True)                                      #16
 
    if not (cell.isdigit() and int(cell) in range(1, 10)):                    #17
        return state._replace(error=f'Invalid cell "{cell}", please use 1-9') #18
 
    cell_num = int(cell)                                                      #19
    if state.board[cell_num - 1] in 'XO':                                     #20
        return state._replace(error=f'Cell "{cell}" already taken')           ㉑
 
    board = state.board                                                       ㉒
    board[cell_num - 1] = player                                             2#
    return state._replace(board=board,                                       2$
                          player='O' if player == 'X' else 'X',
                          winner=find_winner(board),
                          draw='.' not in board,
                          error=None)
 
 
# --------------------------------------------------
def format_board(board: List[str]) -> str:                                   2%
    """Format the board"""
 
    cells = [str(i) if c == '.' else c for i, c in enumerate(board, 1)]
    bar = '-------------'
    cells_tmpl = '| {} | {} | {} |'
    return '\n'.join([
        bar,
        cells_tmpl.format(*cells[:3]), bar,
        cells_tmpl.format(*cells[3:6]), bar,
        cells_tmpl.format(*cells[6:]), bar
    ])
 
 
# --------------------------------------------------
def find_winner(board: List[str]) -> Optional[str]:                          2^
    """Return the winner"""
 
    winning = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7],
               [2, 5, 8], [0, 4, 8], [2, 4, 6]]
 
    for player in ['X', 'O']:
        for i, j, k in winning:
            combo = [board[i], board[j], board[k]]
            if combo == [player, player, player]:
                return player
 
    return None
 
 
# --------------------------------------------------
if __name__ == '__main__':
    main()