Most modern online Mahjong clients fall into two camps: hardcore Japanese-only Riichi servers with 2000s UIs, or heavy gacha games filled with anime avatars you'd rather not open on a subway or during a lunch break. Meanwhile, if you want to learn or practice Hong Kong, Chinese Official (MCR 81 fans), Sichuan Blood Battle, or American Mahjong, most search results lead straight to tile-matching Solitaire.
So I built Mahjong Steps — a 100% free, zero-signup, static browser Mahjong studio and learning playground written in pure vanilla HTML, CSS, and ES6 JavaScript. No React, no bundler, no backend server.
Getting the UI to look clean was the easy part. Making a browser-side Mahjong AI play smart across four completely different rulesets — while keeping real-user performance snappy — turned out to be a genuinely fun engineering rabbit hole.
Here are the four most interesting technical problems I ran into and how I solved them.
1. Fast Exact Shanten in Pure JS via Base-5 Suit Memoization
In Mahjong, Shanten is the minimum number of tile replacements needed to reach Tenpai (one tile away from winning), and Ukeire is the count of remaining visible tiles that reduce your Shanten.
My first AI was a 5-line local adjacency heuristic (bonus for pairs, bonus for neighbors). It was terrible: bots broke completed melds, hoarded dead tiles, and rarely won.
The problem with naive recursive Shanten search in JavaScript is that you need to evaluate it dozens of times per turn — once for every candidate discard, multiplied by every possible next draw when computing Ukeire, plus simulations for Chow/Pung/Kong decisions.
A standard trick from competitive Riichi engines translates beautifully to pure JS:
- Represent a concealed hand as an
Int8Array(34)(9 characters, 9 circles, 9 bamboos, 7 honors). - Notice that the three numbered suits (
m,p,s) are completely independent when extracting melds (triplets/sequences) and proto-melds (taatsu). - Since any tile count is in
0..4, an entire 9-tile suit encodes uniquely into a single base-5 integer key (5^9 = 1,953,125possible states).
Instead of re-running DFS on every suit slice, we memoize the Pareto-optimal (melds, maxTaatsu) profile per base-5 key:
const SUIT_PROFILE_CACHE = new Map();
const ZERO_PROFILE = new Int8Array([-1, -1, -1, -1, -1]);
ZERO_PROFILE[0] = 0;
// Returns Int8Array(5) where bestT[m] = max taatsu achievable with m melds
function suitProfile(counts, base) {
let key = 0;
for (let i = 0; i < 9; i++) key = key * 5 + counts[base + i];
if (key === 0) return ZERO_PROFILE;
const cached = SUIT_PROFILE_CACHE.get(key);
if (cached !== undefined) return cached;
const bestT = new Int8Array(5);
bestT.fill(-1);
function dfs(pos, m, t) {
while (pos < 9 && counts[base + pos] === 0) pos++;
if (pos === 9) {
if (t > bestT[m]) bestT[m] = t;
return;
}
const idx = base + pos;
// Triplet
if (counts[idx] >= 3) {
counts[idx] -= 3;
dfs(pos, m + 1, t);
counts[idx] += 3;
}
// Sequence
if (pos <= 6 && counts[idx + 1] > 0 && counts[idx + 2] > 0) {
counts[idx]--; counts[idx + 1]--; counts[idx + 2]--;
dfs(pos, m + 1, t);
counts[idx]++; counts[idx + 1]++; counts[idx + 2]++;
}
// Pair / adjacent / gapped proto-melds ...
}
dfs(0, 0, 0);
SUIT_PROFILE_CACHE.set(key, bestT);
return bestT;
}
Once the cache warms up over the first few turns, evaluating all 14 candidate discards and their exact visible-tile Ukeire takes sub-millisecond time in the browser — with zero external libraries.
2. The "Dead Tenpai" Trap: Why Pure Shanten Fails in Hong Kong & MCR
After shipping the Shanten engine, I ran an automated 120-hand benchmark. The bots got faster at reaching Tenpai… and then stalled out and couldn't legally win.
Why? Unlike simplified Mahjong, Hong Kong Mahjong requires a 3-faan minimum, and Chinese Official MCR requires an 8-point minimum.
If an AI only optimizes raw Shanten:
- It eagerly calls Chow/Pung on cheap tiles to reach 0-shanten fast;
- It ends up waiting on a 0-faan or 1-faan "chicken hand" (dead Tenpai);
- Even when its winning tile appears, the rules engine rejects the win.
To fix this, I added a Target-Route Engine on top of the Shanten core. Instead of evaluating a single generic distance-to-win, it evaluates multiple minimum-score-compliant routes in parallel:
- Hong Kong (3-faan min): Half Flush, Full Flush, All Triplets, Seven Pairs (optional 4-faan house rule), Value Honor + Self-Draw / Concealed paths;
- MCR (8-point min): Seven Pairs, Pure Straight, Half/Full Flush, All Pungs, Fully Concealed combinations;
- Sichuan Blood Battle: Strictly enforces discarding the chosen missing suit first while weighing roots (gen) and flush/triplet upgrades.
Before making a discard or accepting a Chow/Pung call, the engine checks whether that move keeps a legal scoring route alive.
The impact on our automated 4-bot Node.js benchmark was immediate:
- Hong Kong (120 hands): wins jumped from 69 → 103
- Sichuan (40 hands): wins jumped from 4 → 40
- MCR (80 hands): wins jumped from 33 → 43
Even better: I plugged the exact same Target-Route engine into the live AI Coach on the player's table and a Daily 5 Puzzles (WWYD & Scoring) mode — so beginners don't just see which tile to cut, they see which scoring route they're aiming for and how many live tiles remain.
3. Fixing Web Audio Latency & Tile-Clack Desync
In Mahjong, tactile feedback is half the joy. Rather than shipping bulky MP3 sprites, I synthesized the tile clacks, draw ticks, and win chimes using the Web Audio API (playground/sound.js).
On real mobile devices and macOS, I hit a sneaky problem: the first click after 2 seconds of idle time had noticeable audio lag, making the tile clack sound out of sync with the discard animation.
Three small fixes eliminated the desync completely:
-
Request low latency explicitly:
new AudioContext({ latencyHint: 'interactive' }). -
Pre-warm on
pointerdown/touchstart/keydown(a few dozen milliseconds beforeclickfires) by playing a 1-sample silent buffer if idle > 1.5s — waking up macOScoreaudiodand mobile audio pipelines ahead of time:
function warmup() {
const ac = ensureContext();
if (!ac) return;
const nowMs = Date.now();
if (nowMs - lastActiveMs > 1500 && silentBuf) {
try {
const src = ac.createBufferSource();
src.buffer = silentBuf;
src.connect(ac.destination);
src.start(0);
} catch (_) {}
lastActiveMs = nowMs;
}
}
-
Fire sound at
0msbefore synchronous AI computation: when the player clicks to discard, trigger the pre-cached percussive noise buffer immediately before running the bot response loop, and tighten the discard flight animation from650msdown to220ms.
4. Dual-Loaded Zero-Build Architecture & 416ms Real-User LCP
Every engine module (deck.js, judges.js, efficiency.js, bot-ai.js, full-engine.js) uses a tiny UMD-style wrapper so the exact same .js file loads natively in <script defer> in the browser and via require() in Node.js.
That gives me:
- Zero build step (push to GitHub / static Caddy server and it's live);
-
35 pure Node.js regression test suites (running deterministic seeded games using
xorshift32PRNG so every hand and bug is 100% reproducible by Deal Seed); - Static SEO pre-rendering: an offline Node script generates 24 static trilingual landing pages (English, Simplified Chinese, Traditional Chinese) with 125 real SVG hand diagrams directly from the rule data;
- Real-user speed: PageSpeed Insights scores 100 / 100 on both mobile and desktop, and Cloudflare Web Analytics shows real-world P75 metrics of LCP 416ms, INP 72ms, and CLS 0.
Try It Out (No Sign-Up Needed)
If you're curious to test the pure-JS Shanten engine, try today's Daily 5 Puzzles, or play a no-timer 4-player game with the live AI coach:
- Live site (EN / 简 / 繁): https://mahjongsteps.com/en/
- Playable HTML5 embed on itch.io: Mahjong Steps on itch.io
- Source code on GitHub: francisling07/mahjong-steps-preview
I'd love to hear from other web game / zero-build builders:
- Have you used base-N lookup/memoization tricks for browser board-game AI?
- For a solo browser game, would you invest next in Japanese Riichi rules or lightweight 2–3 friend + AI bot rooms?

Top comments (0)