A complete, playable implementation of Big Two (鋤大弟 / Dai Di) — the card-shedding game for 2–4 players — with two independent AI engines, a C rollout accelerator, a full self-play training pipeline for a neural bot, and a dependency-free browser front-end.
Web front-end: a hosted version is in development and will be linked here
once it is live. The server (webapp.py) and the browser client (web/) are
complete and run locally today — python webapp.py, no installs.
- A hand-written C rollout engine bridged via
ctypes, with a graceful pure-Python fallback if it isn't built. The same policy runs in both, so results are comparable — the C path is just far faster. Measured over eight mixed lead/response positions at 100 samples per candidate: median 333 ms → 11 ms per decision, a ~27× speedup (setBIGTWO_NO_C=1to force the Python path and reproduce the comparison). - Exact hypergeometric beat probability for singles — a closed form over
the unseen cards, no sampling. Pairs, triples and 5-card hands are estimated
by sampling opponent hands instead, because the "the whole combo must sit in
one hand" constraint has no clean closed form. Separately,
is_unbeatable()is an exact check for every hand type: it proves a play cannot be beaten by any arrangement of the remaining unseen cards, which is what enables guaranteed-win detection when running out a hand. - Exact set-partition DP for hand decomposition — a bitmask DP over subsets
with the lowest-set-bit optimization, giving the true minimum number of plays
needed to empty a hand rather than a greedy approximation. Exact up to 14
cards (
bot.max_dpinconfig.json); above that the cost spikes and it falls back to the greedy count. - A DouZero-style Deep Monte-Carlo trainer with three interchangeable self-play backends: single-process pure Python, a CPU multi-actor pool, and a batched GPU pipeline built on its own hand-written C self-play engine, which gathers every pending decision across hundreds of concurrent deals into one forward pass per step. Self-play always runs on lagged weight snapshots, and a pool of independent sub-environments keeps opponent policies diverse.
- 154 passing tests covering rules, game flow, scoring, and bot behavior (about 4 minutes for the full suite).
Everything except the neural bot runs on the Python standard library alone — no dependencies required to play, benchmark, or serve the web app.
┌─────────────────────┐
│ big_two/game.py │ Rules engine: Game, PlayerStrategy,
│ big_two/play.py │ GameView, HandType, valid_plays()
│ big_two/deck.py │
└──────────┬───────────┘
│ GameView (read-only per-turn snapshot)
┌────────────────┼────────────────┐
│ │ │
┌────────▼───────┐ ┌──────▼───────┐ ┌──────▼───────┐
│ SmartBot │ │ Neural bot │ │ Human / │
│ (bot.py) │ │ (rl/) │ │ RandomBot │
│ │ │ │ │ (cli.py) │
│ Monte-Carlo + │ │ DMCNet, self- │ │ │
│ combinatorics, │ │ play trained │ │ │
│ optional C │ │ via a batched │ │ │
│ rollout engine │ │ GPU or CPU │ │ │
│ (engine/*.c) │ │ multi-actor │ │ │
│ │ │ pipeline │ │ │
└─────────────────┘ └───────────────┘ └───────────────┘
│ │ │
└────────────────┼────────────────┘
│
┌───────────────┼────────────────┐
│ │ │
main.py (CLI) webapp.py (SPA) benchmark.py / advisor.py / compare.py
Every bot is a drop-in PlayerStrategy subclass, so the CLI, the web app, and
the benchmark harness all run any combination of human, SmartBot, neural, or
random players without special-casing.
git clone https://github.com/XavionM/Big_Two.git
cd Big_Two
# Play a game in the terminal (stdlib only)
python main.py
# Launch the web app, then open the printed URL (default http://127.0.0.1:8000)
python webapp.py
# Run the tests
python -m pytest tests/ # full suite (154 tests, ~4 min)
python -m pytest tests/ -m "not slow" # skip the multi-game strength testOptional, for extra speed / the neural bot:
# Build the C rollout engine (falls back to pure Python if skipped)
bash big_two/engine/build.sh # Linux/WSL/macOS
big_two\engine\build.bat # Windows (needs gcc, e.g. TDM-GCC)
# The neural bot and its trainer additionally need PyTorch
python -m big_two.rl.train --device cuda --players 4 --batched --minutes 60See help.md for the full command reference and big-two-rules.md for the authoritative rules this engine encodes.
SmartBot (big_two/bot.py) picks moves using only its own hand and the public discard pile — no opponent modeling, by design. It infers the unseen cards, decomposes its hand via the exact set-partition DP, computes beat probabilities (exact for singles, sampled for pairs/triples/5-card hands), runs determinized Monte-Carlo rollouts against imaginary opponent hands with adaptive racing to drop dominated candidates early, and picks the move with the best risk-adjusted expected points. Every recommendation is fully explainable — the advisor and CLI print the odds and reasoning behind each move.
Neural bot (big_two/rl/) is a DouZero-style network:
Q(state, action) ≈ expected end-of-deal return, trained by self-play Deep
Monte-Carlo. It supports both a legacy MLP and a residual architecture (the arch
is recorded in the checkpoint), a 303-dim state+action encoding with an adapter
that keeps older 288-dim checkpoints playable, and a separate model per player
count (a net trained for 4 players plays badly at 2).
Full technical detail on both engines is in help.md.
Every strategy — human, SmartBot, neural, random — is a PlayerStrategy
subclass, so adding a new one is a few lines:
from typing import Optional
from big_two.game import Game, PlayerStrategy, GameView
from big_two.play import Play, valid_plays
class MyBot(PlayerStrategy):
def choose_play(self, view: GameView) -> Optional[Play]:
options = valid_plays(view.my_hand, view.current_play, view.must_include_card)
if not options:
return None # no legal move -> pass
return options[0] # play the first legal option
game = Game(num_players=4, strategies={1: MyBot(), 2: MyBot(), 3: MyBot(), 4: MyBot()})
winner = game.run()The two shipped checkpoints in checkpoints_final/ were each trained for six hours on one GPU with the batched pipeline on the 288-dim v1 feature encoding. Their full training transcripts are committed alongside them, and the exact commands are in commands.txt.
| Table | Self-play deals | Throughput | Best deal-win vs SmartBot | Fair share |
|---|---|---|---|---|
| 4-player | 32.7 M | ~1,610 deals/s | 47.1% | 25% |
| 3-player | 35.5 M | ~1,760 deals/s | 61.3% | 33.3% |
Read those numbers with the caveat attached: they come from the trainer's in-training evaluation — the greedy net in seat 1 against SmartBots in every other seat, 800 deals per evaluation, with SmartBot running 16 Monte-Carlo samples per decision rather than the 100 it uses in normal play. They measure progress against a deliberately cheap opponent, not the bot's strength against SmartBot at full strength.
This project is under active development, and the neural engine specifically is a work in progress:
- The proven baseline is an older 288-dim MLP — it reaches ~42% deal-win vs. SmartBot at a 4-player table.
- The newer batched GPU pipeline trains ~17× faster, but in a definitive 15,000-deal head-to-head, the resulting model is a few points weaker than the older, slower-trained baseline. Prime suspect: the newer 303-dim feature encoding. The planned next step is to ablate it (retrain the fast pipeline on the original 288-dim features) to isolate whether the regression is in the features or the training dynamics.
- The checkpoints in
checkpoints_final/are that ablation run — batched pipeline, 288-dim v1 features — and their logs are included. Their numbers in the Results table are in-training evals against a 16-sample SmartBot, so they are not directly comparable to the model-vs-model head-to-head above, which remains the last clean statement of the regression. - Training health is judged by the loss curve, not just win-rate: in DMC a healthy policy keeps improving, so loss should rise over a long run, not collapse flat. Naive live-weight self-play collapses the policy; this trainer fixes it with a lagged self-play snapshot and a self-play policy pool for opponent diversity.
- The hosted web front-end isn't live yet — the backend (
webapp.py) and the browser client (web/) are complete and run locally today. It will be linked from this README once it ships.
I'm keeping this section honest rather than polished — the batched pipeline's speed/quality tradeoff is a real, unresolved result, not a bug I've hidden.
- Python 3.10+ for the core game and all stdlib-only tools (engine, SmartBot, CLI, advisor, compare, web app, benchmark).
- PyTorch (CUDA optional) only for the neural bot and its trainer; the trainer's feature/eval path also uses NumPy.
- gcc / TDM-GCC (optional) to build the C rollout and self-play engines — the project runs in pure Python without them.
MIT © 2026 Xavion Mirchandani.