Mage Knight Digital
Open-source, non-commercial digital implementation and reinforcement learning environment for the Mage Knight board game.
Mage Knight Digital brings Vlaada Chvátil’s acclaimed tactical deck-building and hex-exploration tabletop game into a fast, faithful software stack built for solo and cooperative play as well as reinforcement learning (RL) and game-AI research.
Designed around “The Quiet Map Room” philosophy (PRODUCT.md, DESIGN.md), the project prioritizes canonical rules accuracy, tactical legibility, and deterministic simulation throughput over flashy fantasy chrome:
- Canonical Rust Rules Engine (
packages/engine-rs) — A deterministic 8-crate Rust workspace backed by 2,300+ tests, modeling multi-step card and skill effects via an explicit VecDeque effect queue, 4-phase elemental combat, day/night mana rules, terrain modifiers, site conquests, and snapshot-based undo.
- Tactile Hex-Map Web Client (
packages/client) — A browser interface powered by React 19, PixiJS v8, and TypeScript communicating over WebSockets (mk-server). Every button, playable card, and valid hex move is driven directly by the engine’s LegalActionSet.
- High-Throughput Python RL Environment (
packages/python-sdk) — Native PyO3 bindings (mk-python) and Rayon-vectorized parallel environments (mk-env) for training PPO and REINFORCE policy-gradient agents without IPC overhead, paired with an exhaustive DFS Combat Search Oracle, TensorBoard logging, and a game replay viewer.
Highlights & Game Content
| Area |
Implemented Scope |
| Playable Heroes (7) |
Arythea, Tovak, Goldyx, Norowas (Base Game), Wolfhawk (The Lost Legion), Krang (Krang Character), Braevalar (Shades of Tezla) |
| Cards & Decks |
120+ Action & Advanced Action cards, 24 Spells, 25 Artifacts, 70 Hero Skills, Day & Night Tactics, Wound mechanics, and Solo Dummy Player |
| Units & Enemies |
31 Recruitable Units (regular & elite, 16 ability types) and 72+ Enemy definitions across Green, Gray, Brown, Violet, Red, and White pools |
| Hex Map & Sites |
Base + Lost Legion Countryside & Core tiles, Villages, Monasteries, Keeps, Mage Towers, Dungeons, Tombs, Ruins, Mines, Magical Glades, Spawning Grounds, Mazes, Labyrinths, and Colored Cities |
| 4-Phase Combat |
Ranged/Siege → Block → Assign Damage → Attack with Physical, Fire, Ice, and Cold Fire resistances, Fortifications, Brutal, Swift, Poison, Paralyze, Summon, Vampiric, Elusive, Arcane Immunity, Assassination, and Cooperative Assaults |
| Mana Economy |
Shared Ambient Mana Source dice (Day Gold / Night Black depletion), temporary Mana Tokens, and permanent Crystals |
| AI & Search |
Structured state/action feature encoders (mk-features), exhaustive DFS Combat Oracle (combat_search), PPO/REINFORCE trainers, and curriculum evaluation suites |
Quick Start
Prerequisites
- Rust (stable toolchain)
- Bun >= 1.0 (workspace scripts, TypeScript shared package, and web client)
- Python 3.11+ (optional — required only for the Python RL SDK and replay tools)
1. Clone & Install
git clone https://github.com/mage-knight-digital/MageKnight.git
cd MageKnight
bun install
git config core.hooksPath .githooks
2. Play Locally (Web Client + Rust Server)
Start both the Rust WebSocket server (mk-server) and the Vite/React web client in parallel:
bun run dev
Or run headless games directly in the terminal via the Rust CLI runner:
bun run cli
3. Run Engine Tests & Lints
# Fast optimized Rust workspace test run
bun run test:fast
# Full Rust workspace checks
cd packages/engine-rs
cargo check
cargo test
cargo clippy --workspace -- -D warnings
# Client & shared TypeScript build + oxlint
bun run build && bun run lint
Reinforcement Learning & AI Research
Mage Knight is a uniquely rich benchmark for sequential decision-making and combinatorial game AI: long episodes, deck-building state transitions, stochastic tile/enemy reveals, hidden information, multi-resource mana conversion, and ~70 distinct PlayerAction variants with dynamic branching factors.
Build the Native Python Extension & Train an Agent
# 1. Create virtualenv and install RL dependencies (PyTorch + TensorBoard)
cd packages/python-sdk
python3 -m venv .venv
source .venv/bin/activate
pip install -e ".[rl,viewer]"
# 2. Compile the Rust engine into the Python environment via maturin / PyO3
cd ../engine-rs
maturin develop --release
# 3. Train a PPO agent or run native simulations
mage-knight-run-native --seed 42 --hero arythea
mage-knight-train-rl --ppo --episodes 1000 --batch-episodes 16
Programmatic Python API
from mage_knight_sdk import run_native_game
result = run_native_game(seed=42, hero="arythea", max_steps=5000)
print(f"Outcome: {result.outcome} | Steps: {result.steps} | Fame: {result.fame}")
See packages/python-sdk/README.md for full details on vectorized environments, reward shaping, checkpoint evaluation leaderboards, TensorBoard metrics (bun run tensorboard), and the interactive game viewer (bun run viewer).
Architecture
Monorepo Layout
MageKnight/
├── packages/
│ ├── engine-rs/ # Canonical Rust game engine & RL core
│ │ ├── crates/
│ │ │ ├── rl-core/ # Generic vectorized RL framework for turn-based games
│ │ │ ├── mk-types/ # Branded IDs, enums, GameState, PlayerAction, Mulberry32 RNG
│ │ │ ├── mk-data/ # Static cards, skills, units, enemies, tiles, sites, tactics
│ │ │ ├── mk-engine/ # Action pipeline, VecDeque effect queue, combat, undo, oracle
│ │ │ ├── mk-features/ # RL state (85 scalars + pools) & action feature encoders
│ │ │ ├── mk-adapter/ # Mage Knight adapter implementing rl-core traits
│ │ │ ├── mk-env/ # Rayon-parallelized VecEnv / SingleEnv with combat oracle
│ │ │ └── mk-python/ # PyO3 native extension module for Python
│ │ └── tools/
│ │ ├── mk-cli/ # Terminal game runner (human & random policy modes)
│ │ ├── mk-server/ # WebSocket game server bridging Rust engine to browser UI
│ │ └── mk-combat-search/ # Exhaustive DFS vs MCTS combat tree search benchmark
│ ├── client/ # React 19 + PixiJS v8 hex-map UI & replay viewer
│ ├── shared/ # TypeScript protocol, event, and client-state types
│ ├── python-sdk/ # PPO/REINFORCE training, evaluation suites, TensorBoard tools
│ └── mage-dev/ # Trace generation and developer debugging CLI
├── docs/ # Consolidated rules reference, effect specs, and design notes
├── monitoring/ # Prometheus + Grafana observability stack
└── terraform/ # Optional self-hosted Cloudflare + Hetzner deployment modules
Crate & Client Dataflow
flowchart LR
subgraph Rust["Rust Workspace (packages/engine-rs)"]
Types["mk-types"] --> Data["mk-data"]
Data --> Engine["mk-engine"]
Engine --> Features["mk-features"]
RLCore["rl-core"] --> Adapter["mk-adapter"]
Features --> Adapter
Adapter --> Env["mk-env (Rayon)"]
Env --> Py["mk-python (PyO3)"]
Engine --> Server["mk-server (WS)"]
end
Server <-->|"PlayerAction / LegalActionSet"| Client["Web Client (React 19 + PixiJS v8)"]
Py <-->|"Zero-IPC Tensors"| SDK["Python RL SDK (PPO / REINFORCE)"]
Documentation
Contributing
Contributions, bug reports, rules edge-case reproductions, and AI research experiments are welcome!
- Check open issues on the Issues tab.
- Follow Red-Green-Refactor for rules engine bug fixes: add a minimal failing Rust test in
mk-engine first, implement the fix, and verify cargo test && cargo clippy --workspace -- -D warnings.
- For client or shared protocol changes, ensure
bun run build && bun run lint passes cleanly before opening a pull request targeting main.
Non-Commercial Disclaimer & Attribution
Strictly Non-Commercial Open-Source Project: This repository is an independent, hobbyist software engineering and artificial intelligence research project. It is 100% non-commercial — there are no sales, subscriptions, microtransactions, advertisements, or monetization of any kind.
- Mage Knight Board Game was designed by Vlaada Chvátil and is published by WizKids / NECA. All game mechanics concepts, character names, card names, and tabletop trademarks belong to their respective copyright and trademark owners.
- This project is unofficial and is not affiliated with, endorsed by, or sponsored by WizKids, NECA, or Vlaada Chvátil.
- Proprietary tabletop card scans and artwork assets are not included or redistributed in this Git repository (
packages/client/public/ is gitignored).
- If you enjoy Mage Knight, please support the creators by purchasing the official physical Mage Knight: Ultimate Edition board game!
Source Code License
All original source code in this repository (Rust engine, TypeScript/React client code, and Python SDK) is released under the MIT License.
评论