Flask backend for a web implementation of the Nim game.
The API stores independent game sessions per user, exposes endpoints for game state and moves, validates player actions server-side, and implements the computer move logic using a Nim/XOR-based strategy with fallback random moves.
Companion frontend:
https://github.com/abenjas7/nimgame
Live API:
https://api-nim.onrender.com
- REST API for starting games, reading state, applying player moves, and applying computer moves.
- Server-side validation for invalid, out-of-bounds, non-adjacent, or already removed sticks.
- Per-user sessions through the
X-User-IDrequest header. - Computer move selection based on game-state analysis and XOR-style Nim strategy.
- CORS enabled for frontend integration.
- Python
- Flask
- Flask-CORS
- Gunicorn
| Method | Endpoint | Purpose |
|---|---|---|
GET |
/ |
Health/status message |
POST |
/novo-jogo |
Start a new game for the current user |
GET |
/estado |
Return current game state |
POST |
/jogada |
Apply a player move |
POST |
/jogada-computador |
Apply a computer move |
Player move payload:
{
"linha": 2,
"inicio": 1,
"quantidade": 2
}Example state response:
{
"rows": [1, 2, 3, 4, 5],
"available_paus": [[true], [true, true], [true, true, true], [true, true, true, true], [true, true, true, true, true]],
"xor_total": 1,
"jogo_terminado": false
}The computer move logic evaluates possible moves and searches for favourable game states. It prioritizes positions with isolated sticks that match winning odd-count patterns, then falls back to moves that reduce the computed Nim/XOR state to zero. If no strategic move is found, it selects a valid random move.
This makes the project more than a CRUD API: it includes state modelling, rule validation, search over legal moves, and algorithmic decision-making.
Install dependencies:
pip install -r requirements.txtRun locally:
python app.pyThe application listens on:
0.0.0.0:10000
This project demonstrates backend API design, game-state modelling, input validation, algorithmic decision-making, and frontend/backend integration.