This is a Python implementation of the mathematical strategy game NIM, where players take turns removing objects from distinct heaps. In this version, the game is played against a computer that implements the optimal winning strategy.
- The game starts with a pile of
n
pieces - Players take turns removing pieces from the pile
- On each turn, a player must remove at least 1 piece and at most
m
pieces - The player who removes the last piece wins
- The computer uses an optimal strategy based on the (m+1) rule
- Single game mode
- Championship mode (best of 3)
- Computer player with optimal strategy
- Input validation
- Interactive gameplay
- Single Game: Play one isolated game against the computer
- Championship: Play a series of three games against the computer
computador_escolhe_jogada(n, m)
: Implements the computer's optimal strategyusuario_escolhe_jogada(n, m)
: Handles player moves with input validationpartida()
: Manages a single gamecampeonato()
: Handles a championship (3 games)main()
: Game initialization and mode selection
The computer uses the optimal winning strategy based on the (m+1) rule:
- Tries to leave a multiple of (m+1) pieces after its move
- If no optimal move is found, removes m pieces
- Run the program
- Choose game mode:
- Enter 1 for a single game
- Enter 2 for championship mode
- Input the initial number of pieces (n)
- Input the maximum pieces that can be removed per turn (m)
- Follow the prompts to make your moves
Example:
python nim_game.py
- Program determines who starts based on optimal strategy
- Players alternate turns
- On each turn:
- Current game state is displayed
- Player selects number of pieces to remove
- Move validity is checked
- Game ends when no pieces remain
The program validates:
- Game mode selection (1 or 2)
- Number of pieces to remove (between 1 and m)
- Available pieces (can't remove more than remaining)
- Written in Python 3.x
- No external dependencies required
- Implements optimal NIM game strategy
- Includes input validation and error handling
The computer's strategy is based on the mathematical principle that:
- If n is a multiple of (m+1), the next player to move will lose with optimal play
- Otherwise, there exists a move that leaves a multiple of (m+1) pieces, leading to a win
Feel free to submit issues and enhancement requests. Areas for potential improvement:
- Graphical user interface
- Additional game modes
- Statistics tracking
- Difficulty levels