Chess3D
A cinematic 3D chess game built with Three.js, played against an offline AI
opponent. The entire application is a static site: no server-side code, no API
calls, no network requests at runtime, and no external assets. Everything —
textures, geometry, sound effects and the chess engine itself — is generated or
computed in the browser.
Play it now: https://shawt.im/chess3d/

Quick start
Because ES modules are blocked over file://, serve the directory over HTTP:
npm run serve # http://localhost:4173
Any static host works. To deploy, publish the repository root as-is (see
Deployment).
Features
Gameplay
- Single-player against a built-in AI opponent, with six difficulty tiers from
Beginner (
500) to Maximum (1700), labelled by estimated strength rather
than by chess titles it does not play at.
- Play as White or Black; the AI opens when you take Black.
- Full rules: castling, en passant, promotion (including underpromotion, chosen
from a four-piece picker rather than assumed to be a queen), check,
checkmate, stalemate, the fifty-move rule, threefold repetition and
insufficient material.
- The engine opens from a small built-in book of main lines, so the first moves
arrive instantly and vary from game to game (1.e4 or 1.d4, and a different
defence each time); past eight plies it searches on its own.
- Undo (takes back both your move and the AI's reply, and cancels a search that
is still running), a Hint button that asks the worker for a strong move, and a
move list in standard algebraic notation with captured-piece trays. Clicking a
move shows the board as it stood after that move, with a visible way back.
- Starting a new game, or switching sides, asks for confirmation while a live
position is on the board.
- Promotion, hint and undo are all reachable from the keyboard, and the promotion
dialog is a real modal with focus handling.
- Share a game as a link. The whole game rides in the URL fragment
(
https://shawt.im/chess3d/#moves=e2e4,e7e5,g1f3), which browsers never send
to the server, so a link needs no backend and no database: whoever opens it
watches the moves replay through the rules engine and gets the position. The
same game can be copied as PGN for any other chess program.
Presentation
- Procedurally generated Staunton pieces: the pawn, rook, bishop, queen and king
are lathed from hand-tuned profiles; the knight's head is lofted along a
curved spine.
- The profiles are treated as cut work, not as a smooth surface of revolution:
every corner sharper than 31° is creased, so a bead's highlight stops at its
arris instead of being averaged away, and each piece carries a sub-millimetre
ovality so no section is a perfect circle. Both are asserted in
tests/geometry.test.mjs, which also checks that the creasing stays at the
corners (the rook's straight body reports none).
- Turned detail rather than stacked cones: every foot is a flat underside,
fillet, plinth band, parting groove, cove and a pair of beads; the pawn,
bishop, queen and king share a collar cut as neck groove, fillet, main bead,
groove, second bead and waist. The rook's crown is a moulded band, six tapered
merlons standing on a bead ring, and a recessed well behind them; the queen's
coronet alternates spikes with set pearls; the king's orb carries a ferrule at
the dome and a socket where the cross leaves it.
- Procedural wood and marble textures with derived roughness and normal maps.
Each board square samples a different part of the tiling grain (and half are
rotated a quarter turn), so the 32 light squares are no longer identical.
A hairline seam over a dark substrate separates the squares, so the top reads
as veneer rather than a printed surface.
- A hand-built studio environment: a dark room with a warm key softbox, a cool
fill panel, a narrow rim strip and a low bounce, captured to a PMREM. This is
what gives marble a long highlight down one flank instead of chalky white.
- A gradient backdrop sphere, atmospheric dust in the key light, soft contact
shadows under every piece, and a beveled frame with a brass inlay line and a
felt pad.
A soft warm pool of practical light on the table grounds the set.
- Physically based materials with clearcoat, sheen and anisotropic brushed metal,
soft shadows, ACES tone mapping, bloom on the glints, a vignette, SMAA, and a
final grade pass with film grain and a touch of lens aberration.
- Animated moves: pieces slide with a slight arc, knights leap and roll, the
picked piece lifts off the board, captured pieces dissolve into dust,
promotions pop, and a landed piece compresses a hair before it springs back.
Knights kick up a little dust on landing; reduced-motion users keep the slide
and lose the decoration.
- Synthesised sound effects (wooden knocks, chimes, check sting) via WebAudio,
played through a generated 0.45 s room so a knock reads as wood in a room
rather than a dry UI click.
- A phone layout that collapses both side panels into an on-demand sheet, so the
board gets the screen; framing adapts to the viewport shape and leans towards
a plan view on tall screens so the board fills the space instead of floating
low in it.
- Camera presets that solve their own framing against the live UI layout, centre
the board in the free band, and keep the whole board visible at any size.
Offline
- The opponent is a real search engine computed in the browser, not a model
called over the network. See How the AI works.
- Three.js is vendored into
vendor/three and referenced through an import map.
- The AI runs in a Web Worker so the render loop never stutters while it thinks.
- No
fetch, XMLHttpRequest, WebSocket or CDN reference exists in the game's
source. The only fetch in the repository is the service worker asking for its
own static files, which it then serves from the cache.
- A service worker (
sw.js) caches the whole game on the first visit, so the
page opens with the network switched off — and the manifest plus this worker
are what make it installable as an app. The AI keeps playing offline, because
the engine was always local; the cache only removes the last thing that still
needed a network, which was fetching the code itself.
- A shared link is a URL fragment, and fragments are never sent to the server. The
feature adds no request, no endpoint and no storage: the moves are replayed
locally, exactly like the auto-save.
Controls
| Input |
Action |
| Click / tap a piece, then a destination |
Move |
| Drag on the board |
Orbit the camera |
| Scroll or pinch |
Zoom |
| Click a move in the list (or focus it and press Enter) |
Review the position after that move (click again, or press Esc, to return) |
| Tap Menu (phone) |
Open difficulty, side, move list and captured pieces |
| Copy link / Copy PGN (left panel, or the phone sheet) |
Copy a link that reopens this position, or the game as PGN |
| How it works (left panel, or the phone sheet) |
Open the About panel: what the set, the engine and the offline cache are |
U |
Undo (also cancels an engine search in flight) |
H |
Hint (computed in the worker, so the board keeps rendering) |
N |
New game |
F |
Flip the camera 180 — this does not change sides or restart the game |
Q R B N |
Choose the promotion piece while the promotion dialog is open |
1 2 3 4 |
White / Black / Side / Top view |
Esc |
Close the promotion dialog, leave review, close the phone sheet, or clear the selection |
Difficulty, sound and the cinematic toggle are remembered in localStorage, so
a reload keeps the session's preferences. The game is auto-saved as well: the
move list is written after every move, undo and new game, and a reload replays it
through the rules engine. The position, the move list, the side you took and the
difficulty all come back. Only moves are stored — a stored board is never
trusted — so an entry that no longer replays is discarded instead of reaching the
screen. Everything else — the engine, the textures, the audio — is still
generated in the browser with no network access.
The address bar carries the game for the same reason: after every move it is
rewritten (with history.replaceState, so the back button still leaves the app
rather than walking through your own moves) to #moves=e2e4,e7e5,…. That makes
Copy link a copy of the current URL rather than a separate code path, and it
means a link you paste into a running game is followed — changing only the
fragment does not reload the page, so the controller watches hashchange. A link
that no longer replays is refused: the position on screen stays, and the bar is
put back.
Architecture
src/
engine/ Pure chess logic, no rendering or DOM dependencies
chess.js Board, move generation, FEN, SAN, game-end detection
evaluate.js Static evaluation (material, piece-square tables, structure)
ai.js Negamax + alpha-beta, transposition table, quiescence
render/ Three.js scene construction
textures.js Procedural canvas textures, roughness and normal maps
materials.js Shared PBR material library
pieces.js Lathed and lofted Staunton piece geometry
board.js Tiles, frame, coordinate labels, interaction overlays
pieceViews.js Piece meshes and every move/capture/promotion animation
scene.js Renderer, lighting, IBL environment, post-processing
camera.js Orbit controls and the framing solver
ui/ DOM overlay (HUD, move list, captured trays, modals)
audio/ Procedural WebAudio sound effects
game/ Game controller (single owner of state) and auto-save
worker/ AI Web Worker
The dependency rule is that engine/ imports nothing outside itself. That is
what lets the AI run in a Worker (import maps do not apply inside workers, so the
worker may only use relative imports) and keeps the rules testable in plain Node.
State flows one way: the controller mutates the Chess instance, then calls into
the views and the HUD. Views are pure functions of state, which is why undo and
new-game are simply "change state, rebuild views" and can never desync.
How the AI works — and why it is offline
The opponent is not a language model and not a remote service. It is a
conventional chess search engine: the same approach that has beaten human world
champions since 1997. Nothing about it needs a network connection, because
searching a game tree is arithmetic over data already in memory. The AI is
computed, not queried.
src/engine/ai.js is roughly 500 lines of plain JavaScript, in three parts.
1. Evaluation — "who is better here?"
evaluate.js scores any position in centipawns (100 = one pawn). Positive
favours White; the search negates the score as it descends.
| Term |
What it captures |
| Material |
Pawn 100, knight 320, bishop 335, rook 500, queen 950 |
| Piece-square tables |
Where a piece stands — a knight in the centre is worth far more than one on the rim |
| Pawn structure |
Doubled and isolated pawns |
| Bishop pair |
Two bishops are worth more than the sum of their parts |
| Rooks |
Bonus on open and semi-open files |
| King safety |
A pawn shield in front of the king while the queens are on |
| King activity |
A separate table for the endgame, where the king should march up the board |
Piece-square tables do most of the work. Instead of hand-writing dozens of
rules, one table per piece type encodes the principles directly, and each is a
single array lookup at evaluation time.
2. Search — "what happens if I look ahead?"
Negamax with alpha-beta pruning. The engine tries every move, assumes the
opponent replies with their best, tries every reply, and so on. Unpruned, the
branching factor is about 30, so six plies is 30^6 ~ 700 million positions —
hopeless.
Alpha-beta pruning fixes that. As soon as a branch is provably worse than a
choice already in hand, the whole branch is abandoned. In the best case this
cuts the work to roughly the square root, so six plies costs on the order of
30^3 nodes instead of 30^6.
On top of that:
- Iterative deepening. Search one ply, then two, then three. Each pass
reorders moves using the previous pass's results, which makes pruning far more
effective — and it means the engine can stop at any moment and still have a
complete answer, which is what makes a wall-clock time limit possible.
- Transposition table (1M entries, Zobrist-hashed). Different move orders
reach the same position; the table remembers what was already computed. Entries
are tagged exact, lower bound or upper bound.
- Quiescence search. At the depth limit the engine does not simply stop — it
keeps searching captures only, so it never misjudges a position mid-trade.
- Check extension. Being in check extends the search, so tactical sequences
are not cut off partway.
- Move ordering by transposition-table move, MVV-LVA captures, promotions,
killer moves and the history heuristic. Better ordering means better pruning.
3. Difficulty — six tiers
Each tier pairs a search budget with a little randomness, so the weaker bots
feel like a club player who makes mistakes rather than a shallow program:
| Tier |
Depth |
Time |
Randomness |
Blunder rate |
Book |
| Beginner (~500) |
1 |
120 ms |
90 cp |
30% |
no |
| Easy (~700) |
2 |
250 ms |
55 cp |
16% |
no |
| Intermediate (~950) |
3 |
600 ms |
28 cp |
7% |
yes |
| Advanced (~1200) |
5 |
1200 ms |
12 cp |
2% |
yes |
| Expert (~1450) |
7 |
2500 ms |
4 cp |
0% |
yes |
| Maximum (~1700) |
12 |
5000 ms |
0 cp |
0% |
yes |