Skip to content

Repository files navigation

Chess Bot

Live demo: https://chess-bot-deployment.vercel.app/

Full-stack chess bot: a PyTorch neural network trained on Stockfish-labeled positions for evaluation, paired with a classical alpha-beta search engine for move selection. Flask REST API on the backend, React / TypeScript frontend with a live evaluation bar, candidate-move arrows, and click-to-move legal-move hints. Containerized with Docker (Render-deployable) and currently live on Vercel as a serverless Python function plus a static React build.

Architecture

PyTorch evaluator — train_advanced_model.py, chess_model_improved.pth

A fully connected neural network with shape 768 → 256 → 128 → 1 and ReLU activations. Each position is encoded as 12 piece-type planes (768 binary features) capturing where every piece sits for both colors, plus hand-crafted positional signals — material balance, mobility, castling rights, and center control.

Training data was generated by python-chess simulating thousands of legal board positions through random move sampling. Each position was labeled with the Stockfish chess engine's evaluation as the ground-truth target. The network was optimized with the Adam optimizer and MSE loss, with dropout and batch normalization for regularization, across multiple training iterations targeting improved validation loss.

Classical search engine — engine.py

Iterative-deepening negamax with alpha-beta pruning, quiescence search on captures and queen promotions, MVV-LVA capture ordering with killer-move and history heuristics, a Zobrist-keyed transposition table, and a check extension. Evaluation is tapered between a midgame and endgame score using a phase weight derived from non-pawn material, blending material, piece-square tables, pawn structure (doubled, isolated), bishop pair, and a king-shield safety term.

Threefold-repetition and 50-move-rule draws are scored as 0 inside the search tree, so the engine actively refuses to repeat when winning and accepts the draw when losing.

Opening repertoire

Eight curated openings — Italian Game, Ruy Lopez, Sicilian Defense, French Defense, Caro-Kann, Queen's Gambit, King's Indian Defense, English Opening — compiled at startup from canonical move lines covering both colors. The user picks one from a dropdown in the UI and the bot follows the line until either side deviates, at which point the search takes over.

Frontend — chess-frontend/

A single-screen React app built around the board.

  • Board. react-chessboard with chess.js for rules. Click a piece to see its legal squares (a dot on empty squares, a ring on captures) and click again to move, or drag. The last move and any king in check are highlighted.
  • Evaluation bar. A vertical bar beside the board, white-POV, driven by /api/evaluate. Mate scores pin the bar and read as M3.
  • Engine lines. The top three candidate moves from /api/suggested-moves, drawn as arrows on the board (brass for the best line) and listed with their scores. Hidden on the engine's turn so it never telegraphs its reply.
  • Move list and history. Every move is clickable; the arrow keys step through the game. A banner shows when you are viewing an earlier position, and the engine waits until you return to the live position.
  • Game setup. Play the engine or two players locally, choose a side, and pick the engine's opening. Undo in engine mode reverts the engine's reply as well. Game-over and connection errors appear inline instead of as browser alerts.
  • Design. Dark by default: a warm near-black surface, bone text, one brass accent reserved for engine signals, and board squares in muted tournament green and buff. Type is Geist for the interface and Geist Mono for notation, evaluations, and the FEN. Built against Vercel's Web Interface Guidelines: labelled controls, visible focus states, aria-live status regions, reduced-motion support, and tabular numerals throughout.

Stack

Layer Tech
Backend Python, Flask, python-chess
Frontend React, TypeScript, react-chessboard, chess.js
Training PyTorch, NumPy, Stockfish (for ground-truth labels)
Deploy Vercel (serverless Python function + static React build); Docker image for Render

Repo layout

engine.py                  # Move-selection engine (negamax + α-β + quiescence + TT + opening books)
backend_improved.py        # Flask REST API (used for the Docker / Render deploy path)
api/index.py               # Same Flask app, packaged as a Vercel serverless function
chess-frontend/            # React + TypeScript UI
  src/App.tsx              #   Game state, API calls, board wiring
  src/components/          #   EvalBar, PlayerRow, EngineLines, MoveList, Setup
  src/lib/                 #   Chess helpers (material, replay, results) and number formatting
  src/index.css            #   Design tokens (palette, type, spacing)
train_advanced_model.py    # PyTorch training pipeline
chess_model_improved.pth   # Trained PyTorch weights
requirements.txt           # Runtime deps (flask, python-chess)
requirements-training.txt  # Training deps (torch, numpy, tqdm)
Dockerfile                 # Multi-stage build (React + Python backend)
vercel.json                # Vercel serverless function + static-build config

API

Method Path Body Returns
GET /api/health — service status
GET /api/openings — list of named openings the bot can play
POST /api/evaluate {fen} white-POV evaluation in pawns, optional mate_in
POST /api/best-move {fen} best move (UCI + SAN)
POST /api/suggested-moves {fen, top_n?} top-N candidate moves with scores
POST /api/make-ai-move {fen, opening?} bot's move and resulting FEN

Local development

# Backend
python -m venv venv && source venv/bin/activate
pip install -r requirements.txt
python backend_improved.py            # serves on :5001

# Frontend (separate terminal)
cd chess-frontend
npm install
npm start                              # opens http://localhost:3000

The dev server talks to http://localhost:5001/api; the production build uses the relative /api path that Vercel rewrites to the serverless function. Set REACT_APP_API_URL to point the frontend somewhere else.

To re-run the training pipeline, install the training deps and run the script (you'll need a local Stockfish binary on PATH for label generation):

pip install -r requirements-training.txt
python train_advanced_model.py

Releases

Packages

Contributors

Languages