Skip to content
lingyicutePublic

About

H5 Gomoku with an AI I Built from Scratch

Resources

Stars

3 stars

Watchers

0 watching

Forks

Latest commit

 

History

199 Commits

Folders and files

Repository files navigation

YiMoku

Just another gomoku — but this one has a real brain.

A clean, lightweight, and privacy-first gomoku (five-in-a-row) with a built-in threat-aware AI, crafted with Material You and modern web engineering.

Made with ❤️ by lingyicute.

[🇺🇸 English] • 🌐 Source Code • 🐛 Report Bug

License: AGPL-3.0 Single File ~240 KiB Zero Dependencies No Ads No Tracking GitHub Stars

📖 Overview

Browser gomoku is usually one of two things: a board buried under banner ads, or a "smart opponent" that plays random legal moves and lets you win by accident.

YiMoku keeps the classic rules — 15×15 board, black first, five in a row wins — and adds a genuine engine. Four difficulty levels take you from a deliberately beatable opponent up to an alpha–beta searcher with iterative deepening, undo takes back a full move pair instead of half your game, every stone is recorded in a coordinate-labelled move list, and records are kept locally. The entire game — markup, styles, logic, font — is one self-contained HTML file with zero dependencies and zero network requests.

✨ Features

  • ⚫ A Proper Game of Gomoku
    • Standard 15×15 board, black opens, five in a row horizontally, vertically or diagonally wins (overlines count); a full board is a draw.
    • The winning run is highlighted and the latest move is marked, so you never lose track of the game.
    • Undo retracts your move and the AI's reply as one pair — and even works after the game ends, resuming the clock where it stopped.
    • Live move counter and elapsed-time clock above the board; timing starts with the first stone on the board (the AI's opening move when you play white).
  • 🤖 An AI That Actually Plays
    • Four difficulties: 简单 Easy (noisy, occasionally misses your threats), 中等 Medium (greedy with a light jitter), 困难 Hard (alpha–beta under a 550 ms budget) and 专家 Expert (deeper iterative deepening under a 900 ms budget).
    • Choose your side — take black and open, or take white and let the AI start automatically.
    • The engine classifies stone shapes (open threes, jump fours, double threats…), detects every intersection that completes a five, and resolves provable wins and losses at the search leaves — so it is not fooled by the horizon effect.
    • A natural per-difficulty "thinking" pause keeps the opponent feeling human.
  • 👥 Two Ways to Play
    • 人机对战 vs. AI with selectable difficulty and side, or 双人对战 local PvP — pass-and-play on one screen, black vs. white.
  • 💾 Resume an Unfinished Game
    • The current board, move list, clock, mode, difficulty and side are saved to localStorage after every move and restored on reload.
    • Saves are validated move by move (integer coordinates, on-board, no duplicate points, no finished game); a corrupt save is discarded instead of breaking the page.
    • Background AI replies and clock updates do not overwrite a newer save from another tab; a deliberate move in the current tab takes ownership again.
  • 📜 Move List & Records
    • A running game record with board coordinates (A–P × 1–15, letter I skipped, Go-style).
    • Records per mode: AI wins / losses / draws with win rate, PvP results by colour, and your fastest win (fewest moves, with time and difficulty); one click — with a confirm — wipes the slate clean.
  • 🎨 Material You & Polished Design
    • Dynamic theming: eight accent hues (紫罗兰, 晴空蓝, 薄荷青, 青草绿, 暖阳黄, 落日橙, 樱花粉, 珊瑚红), each generating a complete Material token set for both modes.
    • Day / Night mode that follows prefers-color-scheme (live, until you pick one yourself), with prefers-reduced-motion respected.
    • A result bar summarises every finished game — winner, move count and time.
  • 🔒 100% Privacy, Offline & Ad-Free
    • Zero network requests — the game is fully self-contained and works with the network switched off.
    • Theme, mode, difficulty, side, sound, records and the unfinished game live in localStorage (yimoku:*); nothing is ever uploaded.
    • Licensed under AGPL-3.0.
  • ⌨️ Playable Without a Mouse
    • Arrow keys or W A S D move a cursor, Space / Enter places a stone, Z undoes, R restarts, H opens the help dialog.
    • Every intersection is a real <button> with a coordinate aria-label, and turn/game status changes are announced via aria-live.

🛠️ Why YiMoku? (Under the Hood)

1. Threat-Aware Shape Evaluation

Each empty intersection is scored by what a stone placed there would become: five, four, open three, jump/broken threes, and so on, in all four directions — for both players. On top of that, the engine finds every empty point where either side would complete five in one move; an intersection creating two such threats at once is scored as an immediate win. Defence is weighted at 90% of attack, with a small pull towards the centre of the board.

2. Alpha–Beta Search with Iterative Deepening

Hard and Expert don't guess — they search. Candidate moves are restricted to the neighbourhood of existing stones, ordered by the heuristic score, then searched with alpha–beta pruning, deepening one ply per pass under a fixed time budget (550 ms hard, 900 ms expert). Leaf positions run a provable threat check (a five-completing point for the side to move, or two for the opponent) before falling back to static window-based evaluation — which is what eliminates the classic horizon effect.

3. Difficulty as a Spectrum, Not a Switch

Easy and Medium are designed to be beatable: Easy only blocks your winning five ~82% of the time and picks noisily among the top-scored candidates, while Medium plays greedy with ±3.5% jitter. The result is an opponent that ramps from casual to punishing without ever changing the rules.

4. Zero-Dependency, Zero-Network Architecture

index.html contains everything — including a base64-embedded subset of the "Nebulove" typeface — and makes no external requests at all (the favicon is an inline SVG data URI, so the browser never falls back to /favicon.ico). It runs from file://, from a static host, or offline on a phone; no framework, no bundler, no analytics, no backend. Engine self-tests, fuzzing and strength benchmarks live under tests/ and run under Node, so none of that code ships to the browser.

🚀 Play It Now

There is nothing to install — the game is one HTML file.

Option 1 — Just open it

Download index.html (or clone the repository) and double-click the file. It works straight from disk, offline.

Option 2 — Serve it locally

git clone https://github.com/lingyicute/YiMoku.git
cd YiMoku
python3 -m http.server 8000     # then open http://localhost:8000

Option 3 — Publish it anywhere

Drop index.html on GitHub Pages, Cloudflare Pages, Netlify or any static host — a single file is the entire deployment.

Requirements

  • Browser: any modern browser (Chrome, Edge, Firefox, Safari, or their mobile counterparts).
  • Network: not required. Zero requests are made to any server.
  • Storage: localStorage only, for theme, settings, records and resuming an unfinished game.
  • Permissions: none.

🔨 Building from Source

There is no bundler and no dependency to install: index.html is the artifact. The one generated part — the embedded font subset — has its generator checked in.

  1. Clone the repository:
git clone https://github.com/lingyicute/YiMoku.git
cd YiMoku
  1. Edit and reload — the file is organised with banner comments (board generation, shape evaluation, search, rendering, theming, dialogs), so the engine parts and the UI parts stay easy to navigate.

  2. Ship it — commit and push; with GitHub Pages enabled, the update is live immediately.

Regenerating the embedded font subset

The page embeds a ~35.6 KB subset (308 glyphs) of the ~1.22 MB "Nebulove" typeface instead of linking it from a CDN, which is what keeps the "zero network requests" promise. When you add or change user-visible text, regenerate the subset — otherwise the new characters are simply not in the font and fall back to a system font:

pip install fonttools brotli
python3 scripts/subset_font.py          # rewrites the @font-face block of index.html in place
  • The script is idempotent: re-running it on an unchanged page produces no diff, and it reports any characters the typeface itself does not contain (which then fall back to the system emoji font).

🧪 Testing

The shipped artifact stays exactly as it is — one zero-dependency HTML file. Everything under tests/ is development-only tooling that the browser never loads.

npm install          # dev dependencies (jsdom only)
npm test             # offline/worker contract + engine self-test + AI regressions + DOM smoke + session resume  (~20 s)
npm run test:fuzz     # equivalence fuzzing & TT consistency                      (~10 s)
npm run test:session  # localStorage resume / corrupt-save regressions (also part of npm test)  (~3 s)
npm run test:bench    # AI strength & latency benchmark                           (~1–2 min)

npm test and test:fuzz run in GitHub Actions on pushes to main and on pull requests; test:bench runs in a separate job.

  • tests/selftest.js + tests/selftest-core.js — zero-dependency. The runner extracts the embedded <script id="main"> from index.html, appends the development-only assertion body kept in tests/selftest-core.js, and runs it in Node: win detection in all four directions, shape classification, threat counting and terminal leaf evaluation, the TW[0] NaN regression, guaranteed wins at every difficulty and blocks from Medium up (plus Easy's deliberate miss), and a full simulated game.
  • tests/offline-contract.js — zero-dependency. Static guard that the shipped HTML has no external src/href, no fetch/XHR, no remote CSS/@import, no dev-only self-test code, and that the Worker engine markers are present.
  • tests/worker-contract.js — zero-dependency. Evaluates the ENGINE_START/ENGINE_END slice in a scope with no document/window, then simulates a real chooseMove message round-trip — this is what makes the self-bootstrapping Worker safe to refactor.
  • tests/smoke.js — needs npm install. Boots the real page inside jsdom and drives it end to end: the first-run help dialog, stone placement, AI replies, undo pairs, mode / difficulty / side switching, theme & palette popovers, record clearing, keyboard play, win highlighting and all three result-bar texts. Without jsdom it prints a skip notice instead of failing, so a bare clone still passes npm test.
  • tests/session.js — needs npm install. Boots the real page in jsdom to verify automatic save/restore of the board, move list, clock and settings, plus rejection of eighteen kinds of malformed saves.
  • tests/ai-regression.js, tests/ai-audit.js, tests/ai-search-integrity.js, tests/ai-threat-proof.js — zero-dependency, run as npm run test:ai (part of npm test). Deterministic engine regressions with no wall-clock assertions: tactical positions, a correctness audit against an independent board oracle, hash / forcing-move / deepening-exit integrity, and proofs for the threat searches (VCT, stamp rollover, the reduced defence proof).
  • tests/fuzz.js — zero-dependency, npm run test:fuzz. Differential fuzzing on random positions: the sliding-window leaf code must match the reference implementation bit for bit, and transposition-table searches must be deterministic and rebase mate scores exactly across plies.
  • tests/ai-threat-match.js — zero-dependency, manual. Optional paired A/B matches against an older build (BASELINE_HTML=/path/to/old/index.html node tests/ai-threat-match.js); slow and machine-dependent, so it is not part of npm test or CI.
  • tests/bench.js — zero-dependency, slow on purpose. Plays real AI-vs-AI matches and fails on regression: Expert must beat Easy ≥ 5/6 and Medium ≥ 3/4, and per-move latency must stay inside the engine budgets (550 ms hard / 900 ms expert) plus machine slack. Run it whenever the engine changes.

🤗 Contributing

Contributions are always welcome!

  • Bug Reports & Feature Requests: submit an issue on the GitHub Issue Tracker.
  • Pull Requests: keep the single-file, zero-dependency philosophy intact and match the existing code style.
  • Before a PR: run npm test — and npm run test:bench if you touched the engine. Both live in tests/, are dev-only, and never affect the shipped file.
  • Translations: the interface is currently Simplified Chinese — an i18n layer plus translated string tables would be very welcome.
  • Engine improvements: opening books, deeper search, or Renju-style forbidden-move rules are all interesting directions.

📄 License

Copyright (C) 2026 lingyicute <li@92li.uk>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

About

H5 Gomoku with an AI I Built from Scratch

Resources

Stars

3 stars

Watchers

0 watching

Forks

Contributors

Languages