vibes.diy/docs Make an app → Discord
creator docs · reference · generated

Chess variants — small boards, odd pieces, a club's own rules, and an engine that plays them

This is the same document the Vibes code generator reads when it builds apps — rendered from prompts/pkg/llms/chess-variants.md on every deploy, so it can't drift from what the platform actually does. Read it from your terminal any time with npx vibes-diy skills.

Load this for chess on anything but the standard rules: 5×5 Gardner and 6×6 Los Alamos minichess, Pawn Wars and other pawns-only games, atomic, crazyhouse, antichess, horde, three-check, King of the Hill, Chess960, shogi and xiangqi, and a variant a club invents. It stands on the board-games skill, which owns the board's look, turns, seats and who sees what. Standard chess on 8×8 is the chess skill's (chess.js and Stockfish); this doc replaces both for every other game:

  1. The rules come from ffish, Fairy-Stockfish's rules library, in a Web Worker, whether the opponent is the computer or a friend on another phone. It knows about 120 variants by name and reads a new one from a few lines of text, so an app never writes a move generator, even for a piece nobody has played before.
  2. The computer opponent is fairy-stockfish-single, the Fairy-Stockfish engine built to run on one thread, in a second Web Worker. It plays every variant the rules worker knows, at any strength, and keeps the page responsive while it thinks.
  3. A club's own variant is a variants.ini section, loaded into both workers from the same string, so the board and the engine always agree on the rules.

The rules — ffish in a Worker

ffish-es6 loads from unpkg as an ES module. Run it in a module Worker built from a blob, as the worked example's lib/variants.js does, and ask it for positions by message.

jsconst ff = await (await import("https://unpkg.com/[email protected]/ffish.js")).default({
  locateFile: (f) => "https://unpkg.com/[email protected]/" + f,
});
ff.loadVariantConfig(iniText); // adds the variants in a variants.ini string
const board = new ff.Board("gardner"); // or new ff.Board("gardner", fen) — never pass undefined
board.legalMoves(); // "a2a3 b2b3 …": UCI moves, space-separated
board.sanMove("b1c3"); // "Nc3", for the move list (ask before pushing it)
board.push("b1c3"); // false when illegal
board.fen(); board.turn(); // true when White is to move
board.isCheck(); board.isGameOver(); board.result(); // "1-0", "0-1", "1/2-1/2" or "*"
board.delete(); // boards live in WebAssembly memory until deleted
  • The game is its UCI move list. Store moves: ["c2c3", "b4c3", …] and the variant's id; replay them on a fresh Board(variant) for every position. Ranks can have two digits on big boards (a10a9), a promotion adds the piece letter (b4b5q), and a drop reads P@e4.
  • A move is legal when it is in legalMoves(). The board's highlights come from the moves that start on the tapped square, and the engine's reply and a friend's move go through the same list.
  • Promotion asks when the rules offer a choice. Several legal moves with the same from and to squares are a promotion: show one button per piece. Gardner promotes to queen, rook, bishop or knight; a variant that allows one piece gives one move and needs no picker.
  • new ff.Board(variant, undefined) throws inside the worker, and a throw in an async onmessage reaches neither onerror nor the page. Pass a FEN only when there is one, and post errors back as a message, as the example does.

A club's own variant

A variant is an ini section that names a built-in parent and changes what differs. Fairy-Stockfish's variants.ini documents every option; these cover most club inventions:

Option What it sets
startFen the starting position, which also sets the board size with maxRank/maxFile
maxRank, maxFile a board up to 12 files by 10 ranks
king = - no king, so no check or mate: the game is won another way
castling, doubleStep turn castling or the pawn's two-step off
promotionPieceTypes what a pawn may become, such as q or nbrq
flagPiece, flagRegionWhite, flagRegionBlack a race: getting that piece to that region wins (a pawn that promotes on arrival is already the promoted piece, so name that)
extinctionValue, extinctionPieceTypes losing all of those pieces decides the game
checkCounting win by giving a number of checks (the FEN carries the count)
mustCapture captures are compulsory, as in antichess
stalemateValue stalemate wins or loses instead of drawing
customPiece1 = a:NB a new piece, letter a, moving in Betza notation (here knight plus bishop)
ini[pawnwars:chess]
startFen = 8/pppppppp/8/8/8/8/PPPPPPPP/8 w - - 0 1
king = -
castling = false
extinctionValue = loss
extinctionPieceTypes = *
flagPiece = q
flagRegionWhite = *8
flagRegionBlack = *1
promotionPieceTypes = q

A piece that moves differently swaps its letter onto another piece type. Bishops that also jump like knights are the built-in archbishop (bishop plus knight) wearing the bishop's letter:

ini[leapingbishops:chess]
bishop = -
archbishop = b
promotionPieceTypes = qrbn

Name the promotion pieces again after a swap: removing bishop also drops it from promotion, and b in promotionPieceTypes now means the archbishop.

The built-in types cover most club ideas: archbishop (B+N), chancellor (R+N), amazon (Q+N), centaur (K+N), commoner (moves like a king but is not one), wazir, fers, alfil. Anything else is a customPiece in Betza notation. Variants.ini lists every type and its letter.

The section name is the variant's id for new ff.Board("pawnwars") and for the engine's UCI_Variant. Load the same string into both workers.

The opponent — fairy-stockfish-single in a Web Worker

The published Fairy-Stockfish engines are multi-threaded and need SharedArrayBuffer, which a vibe's page does not have. VibesDIY/fairy-stockfish-single is the same engine built for one thread (1.1 MB of WebAssembly, from jsDelivr), and it loads the way the chess skill's Stockfish does:

  • A blob worker importScripts the engine, and the .wasm address rides in the worker URL's #hash: new Worker(${blobUrl}#${encodeURIComponent(wasmUrl)}).
  • Custom variants go in as an object: worker.postMessage({ variants: iniText }). Every other message is a UCI line: setoption name UCI_Variant value pawnwars, position startpos moves c2c3 b4c3, then go movetime 400.
  • Every go carries a limit (movetime, depth or nodes). The engine thinks on the worker's only thread, so a stop waits until it is done; an unlimited go searches for two seconds.
  • Strength is Skill Level (0 to 20) and the thinking time, as in the chess skill. The reply is a UCI move from legalMoves(); append it to the move list.
  • When the engine cannot load, the promise rejects: keep playing with a random legal move and say "Engine offline".
  • Credit it. ffish and the engine are GPL-3 and run unmodified in their own workers; a muted line under the board says "Rules and engine: Fairy-Stockfish (GPL-3)".

Two players on two phones

A friend on their own phone is the board-games turn rule: one game doc holds the variant, the moves list and the two seats, and only the seat whose turn it is writes. Each phone asks its rules worker for the position after moves and accepts a move only when it is in legal, the same as against the computer; there is just no engine worker. access.js cannot run ffish, so it checks the seat, the turn, that variant is unchanged, and that the new moves is the old list with exactly one move appended (every earlier move identical), so a turn can only add to the game.

Drawing the board — any size

Draw the board-games SVG board from the FEN, whatever its size: parseBoard(fen) in the example reads the rows (top rank first) and counts the files, so the same component draws 5×5, 6×6, 8×8 and 10×10. Chess letters (kqrbnp) take the solid glyphs ♚♛♜♝♞♟; any other letter is a fairy piece, drawn as its capital letter until the app's look gives it art. Square names run a…l by file and 1…10 by rank from White's side.

Variants clubs reach for

  • Small boards: gardner (5×5, every piece), losalamos (6×6, no bishops), minishogi, micro and kinglet.
  • Odd goals: kingofthehill (a king on a centre square wins), 3check, racingkings (race the kings to rank 8), antichess (lose everything to win), horde (36 pawns against an army), atomic (captures explode).
  • Pieces in hand: crazyhouse (captured pieces come back on your side), placement.
  • Starting positions: fischerandom for Chess960.

Name a built-in by its id; build anything else as an ini section on top of one of these.

Worked example — minichess against the computer

Three games behind one board: Gardner and Los Alamos are built in, and Pawn Wars is the club's own section. You play White at three strengths.

lib/variants.js

js// Chess variants: the rules from ffish (Fairy-Stockfish's rules library) and the opponent from
// fairy-stockfish-single (the same engine, built to run on one thread). Both are GPL-3 and run
// unmodified in their own Workers; the page only exchanges messages with them.
const FFISH = "https://unpkg.com/[email protected]/";
const FSF = "https://cdn.jsdelivr.net/gh/VibesDIY/[email protected]/dist/fairy-stockfish";

export const LEVELS = [
  { id: "easy", label: "Easy", skill: 0, ms: 150 },
  { id: "club", label: "Club", skill: 8, ms: 400 },
  { id: "strong", label: "Strong", skill: 20, ms: 1200 },
];

// The rules worker: a module worker that imports ffish, loads the custom variants once, and
// answers each { variant, moves } with the position after those moves.
const RULES_WORKER = (ini) => `
const ready = import(${JSON.stringify(FFISH + "ffish.js")})
  .then((m) => m.default({ locateFile: (f) => ${JSON.stringify(FFISH)} + f }))
  .then((ff) => { if (${JSON.stringify(ini)}) ff.loadVariantConfig(${JSON.stringify(ini)}); return ff; });
onmessage = async (e) => {
  const { id, variant, moves } = e.data;
  try {
    const ff = await ready;
    const board = new ff.Board(variant); // a second argument must be a FEN string, never undefined
    const san = [];
    for (const uci of moves) { san.push(board.sanMove(uci)); board.push(uci); }
    const out = { id, fen: board.fen(), legal: board.legalMoves().split(" ").filter(Boolean),
      white: board.turn(), check: board.isCheck(), over: board.isGameOver(), result: board.result(), san };
    board.delete(); // ffish boards live in WebAssembly memory until deleted
    postMessage(out);
  } catch (err) { postMessage({ id, error: String(err) }); }
};`;

export function startRules(ini = "") {
  const url = URL.createObjectURL(new Blob([RULES_WORKER(ini)], { type: "text/javascript" }));
  const worker = new Worker(url, { type: "module" });
  let n = 0;
  const pending = new Map();
  worker.onmessage = (e) => {
    const p = pending.get(e.data.id);
    pending.delete(e.data.id);
    if (p) e.data.error ? p.reject(new Error(e.data.error)) : p.resolve(e.data);
  };
  worker.onerror = (e) => {
    for (const p of pending.values()) p.reject(new Error(e.message || "rules unavailable"));
    pending.clear();
  };
  return {
    // The position after `moves` (UCI strings) from the variant's start.
    position: (variant, moves) =>
      new Promise((resolve, reject) => {
        const id = ++n;
        pending.set(id, { resolve, reject });
        worker.postMessage({ id, variant, moves });
      }),
    stop: () => worker.terminate(),
  };
}

export function startEngine(ini = "") {
  const boot = URL.createObjectURL(new Blob([`importScripts("${FSF}.js");`], { type: "application/javascript" }));
  const worker = new Worker(`${boot}#${encodeURIComponent(`${FSF}.wasm`)}`);
  let current = null;
  let queue = Promise.resolve();
  let broken = null;
  worker.onmessage = (e) => {
    const line = String(e.data);
    if (line.startsWith("bestmove") && current) {
      const uci = line.split(" ")[1];
      const done = current;
      current = null;
      done.resolve(uci && uci !== "(none)" ? uci : null);
    }
  };
  worker.onerror = () => {
    broken = new Error("engine unavailable");
    if (current) current.reject(broken);
    current = null;
  };
  worker.postMessage("uci");
  if (ini) worker.postMessage({ variants: ini }); // the same rules text the rules worker loaded

  return {
    bestMove: (variant, moves, level) => {
      const run = () =>
        new Promise((resolve, reject) => {
          if (broken) return reject(broken);
          current = { resolve, reject };
          worker.postMessage(`setoption name UCI_Variant value ${variant}`);
          worker.postMessage(`setoption name Skill Level value ${level.skill}`);
          worker.postMessage(`position startpos moves ${moves.join(" ")}`);
          worker.postMessage(`go movetime ${level.ms}`); // every search needs a limit on one thread
        });
      const next = queue.then(run, run);
      queue = next.catch(() => {});
      return next;
    },
    stop: () => worker.terminate(),
  };
}

// The FEN's board as rows of cells, top rank first, for any width: "10" is ten empty squares,
// "+P" a promoted piece, and a crazyhouse "[...]" pocket is not part of the board.
export function parseBoard(fen) {
  const rows = fen.split(" ")[0].replace(/\[.*\]$/, "").split("/");
  return rows.map((row) => {
    const cells = [];
    for (const m of row.matchAll(/(\d+)|(\+?[A-Za-z]~?)/g)) {
      if (m[1]) for (let i = 0; i < Number(m[1]); i++) cells.push(null);
      else {
        const letter = m[2].replace(/[+~]/g, "");
        cells.push({ type: letter.toLowerCase(), white: letter === letter.toUpperCase() });
      }
    }
    return cells;
  });
}

// "a7a8q" → { from: "a7", to: "a8", promo: "q" }; ranks can be two digits on big boards, and a
// drop reads "P@e4".
export function splitMove(uci) {
  const m = uci.match(/^([a-z]\d+|[A-Za-z]@)([a-z]\d+)(.*)$/);
  return m ? { from: m[1], to: m[2], promo: m[3] } : null;
}

App.jsx

jsximport React, { useEffect, useRef, useState } from "react";
import { Badge, Button, Card, Heading, Row, Stack, Text } from "@vibes.diy/ui";
import { LEVELS, parseBoard, splitMove, startEngine, startRules } from "./lib/variants.js";

// A club's own rules, written in Fairy-Stockfish's variant format. Both workers load the same text.
const CLUB_RULES = `
[pawnwars:chess]
startFen = 8/pppppppp/8/8/8/8/PPPPPPPP/8 w - - 0 1
king = -
castling = false
extinctionValue = loss
extinctionPieceTypes = *
flagPiece = q
flagRegionWhite = *8
flagRegionBlack = *1
promotionPieceTypes = q
`;

const GAMES = [
  { id: "gardner", label: "5×5 Gardner", about: "Every chess piece on a 5×5 board. Mate comes fast." },
  { id: "losalamos", label: "6×6 Los Alamos", about: "The 1956 computer chess board: no bishops, no castling." },
  { id: "pawnwars", label: "Pawn Wars", about: "Only pawns. Reach the far side or take every enemy pawn to win." },
];

const S = 100;
const FILES = "abcdefghijkl";
const GLYPH = { k: "♚", q: "♛", r: "♜", b: "♝", n: "♞", p: "♟" };
const PIECE_NAME = { q: "Queen", r: "Rook", b: "Bishop", n: "Knight", k: "King" };

function outcome(pos) {
  if (!pos?.over) return null;
  if (pos.result === "1-0") return "You win";
  if (pos.result === "0-1") return "The computer wins";
  return "Draw";
}

function VariantBoard({ pos, selected, lastMove, onSquare }) {
  const rows = parseBoard(pos.fen);
  const width = rows[0].length;
  const targets = selected ? pos.legal.map(splitMove).filter((m) => m && m.from === selected).map((m) => m.to) : [];
  return (
    <svg viewBox={`0 0 ${width * S} ${rows.length * S}`} className="w-full max-w-md touch-manipulation select-none" role="group" aria-label="Game board">
      {rows.map((row, r) =>
        row.map((piece, f) => {
          const square = FILES[f] + (rows.length - r);
          const x = f * S;
          const y = r * S;
          return (
            <g key={square} role="button" tabIndex={0} aria-label={piece ? `${square}, ${piece.white ? "white" : "black"} ${PIECE_NAME[piece.type] ?? piece.type}` : square} onClick={() => onSquare(square)} onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), onSquare(square))} className="cursor-pointer">
              <rect x={x} y={y} width={S} height={S} className={(r + f) % 2 ? "fill-muted" : "fill-card"} />
              {lastMove?.includes(square) && <rect x={x} y={y} width={S} height={S} className="fill-accent opacity-40" />}
              {selected === square && <rect x={x + 4} y={y + 4} width={S - 8} height={S - 8} strokeWidth="8" className="fill-none stroke-primary" />}
              {piece && (
                <text x={x + S / 2} y={y + S / 2 + 4} textAnchor="middle" dominantBaseline="central" fontSize={GLYPH[piece.type] ? 78 : 52} strokeWidth="3" className={piece.white ? "fill-card stroke-foreground" : "fill-foreground stroke-foreground"}>
                  {GLYPH[piece.type] ? GLYPH[piece.type] + "︎" : piece.type.toUpperCase()}
                </text>
              )}
              {targets.includes(square) && <circle cx={x + S / 2} cy={y + S / 2} r={piece ? 44 : 14} strokeWidth={piece ? 6 : 0} className={piece ? "fill-none stroke-primary" : "fill-primary opacity-70"} />}
            </g>
          );
        })
      )}
    </svg>
  );
}

export default function App() {
  const [variant, setVariant] = useState(GAMES[0].id);
  const [moves, setMoves] = useState([]); // the game is its UCI move list from the variant's start
  const [pos, setPos] = useState(null);
  const [level, setLevel] = useState(LEVELS[1]);
  const [selected, setSelected] = useState(null);
  const [choices, setChoices] = useState(null); // promotion moves waiting for a pick
  const [thinking, setThinking] = useState(false);
  const [engineDown, setEngineDown] = useState(false);
  const rules = useRef(null);
  const engine = useRef(null);

  useEffect(() => {
    rules.current = startRules(CLUB_RULES);
    engine.current = startEngine(CLUB_RULES);
    return () => (rules.current.stop(), engine.current.stop());
  }, []);

  // Every position comes from the rules worker: legal moves, check, the end of the game.
  useEffect(() => {
    let live = true;
    rules.current.position(variant, moves).then((p) => live && setPos(p));
    return () => {
      live = false;
    };
  }, [variant, moves]);

  const result = outcome(pos);
  const myTurn = pos && pos.white && !pos.over;

  // The computer plays Black.
  useEffect(() => {
    if (!pos || pos.white || pos.over || pos.legal.length === 0) return;
    let live = true;
    setThinking(true);
    engine.current
      .bestMove(variant, moves, level)
      .then((uci) => live && uci && setMoves([...moves, uci]))
      .catch(() => {
        setEngineDown(true);
        if (live) setMoves([...moves, pos.legal[Math.floor(Math.random() * pos.legal.length)]]);
      })
      .finally(() => live && setThinking(false));
    return () => {
      live = false;
    };
  }, [pos]);

  function onSquare(square) {
    if (!myTurn || thinking || choices) return; // a promotion picker waits for its pick
    const options = selected ? pos.legal.filter((uci) => { const m = splitMove(uci); return m && m.from === selected && m.to === square; }) : [];
    if (options.length > 1) return setChoices(options); // a promotion: let the player pick the piece
    if (options.length === 1) return (setMoves([...moves, options[0]]), setSelected(null));
    const owns = pos.legal.some((uci) => splitMove(uci)?.from === square);
    setSelected(owns ? square : null);
  }

  function newGame(id) {
    setVariant(id);
    setMoves([]);
    setPos(null);
    setSelected(null);
    setChoices(null);
    setThinking(false); // a search still running for the old game is ignored when it returns
  }

  const game = GAMES.find((g) => g.id === variant);
  const last = moves.length ? splitMove(moves[moves.length - 1]) : null;
  const status = result ?? (thinking ? "The computer is thinking…" : pos?.check ? "Check! Your move" : "Your move, you play White");

  return (
    <main className="min-h-screen bg-background text-foreground font-sans p-4 flex flex-col items-center gap-4">
      <Heading level={1}>Mini chess</Heading>
      <Row gap={2} wrap>
        {GAMES.map((g) => (
          <Button key={g.id} type="button" size="sm" variant={g.id === variant ? "solid" : "quiet"} onClick={() => newGame(g.id)}>
            {g.label}
          </Button>
        ))}
      </Row>
      <Text size="sm" muted>{game.about}</Text>
      <Row gap={2} align="center">
        <Badge tone={result ? "up" : "info"}>{pos ? status : "Setting up the board…"}</Badge>
        {engineDown && <Text size="sm" muted>Engine offline, playing random moves</Text>}
      </Row>

      {pos && <VariantBoard pos={pos} selected={selected} lastMove={last ? [last.from, last.to] : null} onSquare={onSquare} />}

      {choices && (
        <Row gap={2} wrap>
          {choices.map((uci) => (
            <Button key={uci} type="button" size="sm" onClick={() => (setMoves([...moves, uci]), setChoices(null), setSelected(null))}>
              {PIECE_NAME[splitMove(uci).promo] ?? splitMove(uci).promo.toUpperCase()}
            </Button>
          ))}
        </Row>
      )}

      <Row gap={2} wrap>
        {LEVELS.map((l) => (
          <Button key={l.id} type="button" size="sm" variant={l.id === level.id ? "solid" : "quiet"} onClick={() => setLevel(l)}>
            {l.label}
          </Button>
        ))}
        <Button type="button" size="sm" variant="quiet" onClick={() => newGame(variant)}>New game</Button>
      </Row>

      <div className="w-full max-w-md">
        <Card>
          <Stack gap={2}>
            <Heading level={2}>Moves</Heading>
            <Text size="sm">{pos?.san.map((s, i) => (i % 2 ? s : `${i / 2 + 1}. ${s}`)).join(" ") || "No moves yet."}</Text>
          </Stack>
        </Card>
      </div>
      <Text size="sm" muted>Rules and engine: Fairy-Stockfish (GPL-3).</Text>
    </main>
  );
}