Return to system

Project

The Royal Gambit

Chess × Blackjack × Game AI

A browser-based chess variant where players can risk active material in blackjack to recover captured pieces. I built the custom rule engine, Monte Carlo probability model, Stockfish-backed bot and expected-value decision system, alongside online multiplayer and deployment.

ReactJavaScriptStockfishMonte CarloGame AIWebSocketsNode.jsVercel
01 — The Idea

Chess with a recovery mechanic

Standard chess rules apply throughout. The variant adds a single option: when a player falls far enough behind in material, they can risk active pieces in a blackjack challenge to recover captured ones. That one rule adds a second layer of decision-making around:

materialrisktempoprobabilityresource management
02 — Custom Game Engine

Standard legality plus a piece-state model

chess.js handles standard chess legality. On top of it I maintain a separate piece-state model for the Royal Gambit-specific rules.

Standard chess handled
  • Legal chess moves
  • Check and checkmate
  • Castling
  • Promotion
  • Stalemate
  • Threefold repetition
Custom state tracks
  • Original square
  • Captured state
  • Promotion state
  • Recovery eligibility
  • Temporary protection
03 — Blackjack Recovery

Staking active pieces to recover material

Pawn1
Knight3
Bishop3
Rook5
Queen9

When a player is sufficiently behind, they select captured pieces to recover and choose active pieces to stake. Before a challenge is allowed, the system checks:

Validation
  • Material deficit
  • Recovery value
  • Stake value
  • Available captured pieces
  • Original-square availability
  • King safety
  • Blackjack attempt limits

A piece cannot be staked if removing it would expose its own king to check.

Normal blackjack is limited to five attempts per player, making blackjack itself a limited strategic resource.

04 — Monte Carlo Model

Estimating blackjack odds by simulation

A separate blackjack simulation handles card generation, ace values, player hit/stand behaviour, dealer behaviour and win/loss/tie resolution. Monte Carlo simulation then plays many rounds to estimate the outcome probabilities for a given state:

P(win)
P(loss)
P(tie)

The bot uses these probabilities when deciding whether a blackjack gamble is worthwhile. Results are cached, so identical states are not repeatedly simulated.

05 — Decision Engine

Comparing every option by expected value

The bot compares the expected value of continuing with a normal chess move, taking a blackjack recovery gamble, or using the King's Gamble, and picks the best.

Chess MoveBlackjack RecoveryKing's Gamble
Decision Engine
Best Action
best action = max(chess move EV, blackjack EV, king gamble EV)

The blackjack decision depends on:

probability of winningvalue of recovered materialcost of staked materialcurrent material deficitcost of giving up a chess tempoopponent tactical threatsremaining blackjack attemptsscarcity of those attemptsbot risk tolerance
Stockfish chess evaluationMonte Carlo blackjack oddsMaterial / recovery valueRisk + tempo
Choose action
06 — Stockfish Integration

In-browser evaluation via a Web Worker

Stockfish runs inside the browser through a Web Worker.

Current positionFENStockfishCentipawn / mate evalBest moveDecision engine
Configurable search depth / strengthUCI move parsingCentipawn evaluationMate evaluationTimeout / failure handling
07 — Bot Difficulty

More than raw engine strength

Difficulty levels change more than Stockfish's strength. Each level also varies its evaluation and gambling behaviour:

Evaluation noiseMistake probabilityBlunder probabilityMaterial awarenessTactical awarenessKing-safety awarenessBlackjack strategyMonte Carlo simulation countRisk toleranceStake disciplineBlackjack resource management

The displayed Elo-style numbers are difficulty levels / approximate strength labels, not officially calibrated Elo ratings.

08 — The King's Gamble

A recovery mode from a lone king

When a player is reduced to only their king, they can enter a special blackjack-based recovery mode. Blackjack wins generate recovery points that can be spent on recovering material. A blackjack loss does not directly end the chess game — checkmate remains the actual loss condition. The bot evaluates this option separately from a normal move.

09 — Stake & Recovery Search

A small combinatorial problem inside the game

Each gamble poses two questions — what should I recover? and what should I risk? — which the bot solves as a small combinatorial search:

Recover
  • Identify legal recovery targets
  • Check original-square availability
  • Rank recovery options
Stake
  • Find legal stake pieces
  • Reject king-unsafe stakes
  • Generate stake combinations
  • Compare combination cost
  • Select a valid low-cost stake
10 — Online Multiplayer

Two networking paths

Local / LAN

Express + WebSockets
Supports
  • Room creation
  • White / Black role assignment
  • Spectators
  • Presence
  • Game-state synchronisation

Deployed (Vercel)

Serverless API routesHTTP pollingClient IDsRoom versionsPresence tracking

Friend rooms run on serverless routes with optional Vercel KV / Upstash Redis. The API includes input validation and payload-size limits.

11 — Frontend

Interactive board and interface

React 19ViteInteractive chess boardMove highlightingPromotion handlingMaterial trackingBlackjack interfaceBot strength selectorFriend linksBoard flippingResponsive design

Three themes, with preference persisted locally:

RoyalPink & WhiteOrange & Black
12 — Testing

Automated rule-level tests

Monte Carlo outputBot fallback behaviourKing's Gamble availabilityMaterial valuesThreefold repetitionFive-attempt blackjack limitPinned-piece stake safetyPiece recoveryScore normalisation
13 — Skills Developed

What the project built up

Software Engineering

ReactJavaScriptComponent DesignState ManagementModular ArchitectureGitTesting

Algorithms & Decision Making

Expected-Value ModellingMonte Carlo SimulationCombinatorial SearchHeuristic EvaluationRisk-Based Decision Making

Game AI

Stockfish IntegrationWeb WorkersGame-State EvaluationBot Difficulty ModellingDecision Policies

Probability

Monte Carlo EstimationOutcome ProbabilitiesExpected ValueRisk / Reward Modelling

Backend / Networking

Node.jsExpressWebSocketsREST APIsHTTP PollingState Synchronisation

Cloud / Deployment

VercelServerless FunctionsRedis / KVEnvironment Configuration

Game Systems

Rule DesignState MachinesEdge-Case HandlingResource ConstraintsMultiplayer Synchronisation