CandyMinesweeper
Minesweeper on the SugarCraft stack
CandyMinesweeper is Minesweeper for the terminal, built on the SugarCraft stack. It has a customisable board, an iterative flood-fill, win and loss detection, vim-style movement, mouse support, a mid-game save and resume, opt-in statistics and a 16-locale interface. It is a PHP 8.3+ port of the design of maxpaulus43/go-sweep, a Go game in the Charm ecosystem. The game logic lives in a pure Board class, so every reveal can be tested and driven without a terminal.
Install
composer global require sugarcraft/candy-minesweeper
candy-minesweeper # default 10x10 board, 12 mines
Requires PHP 8.3 or newer with ext-mbstring and ext-intl. The Composer path enforces both through sugar-core. The standalone phar installs nothing through Composer, so the binary checks the two extensions at boot and exits with status 1 and a named message if either is missing. On Debian or Ubuntu the packages are php8.3-mbstring and php8.3-intl.
A project-local install works through vendor/bin/candy-minesweeper. From a clone of the monorepo, run composer install inside candy-minesweeper/ and then ./bin/candy-minesweeper.
wget https://github.com/detain/sugarcraft/releases/download/candy-minesweeper/latest/candy-minesweeper.phar
sha256sum -c candy-minesweeper.phar.sha256 # verify the digest
php candy-minesweeper.phar --version
Quickstart
Start a game on a chosen board, or use the picker to pick a preset from inside the game.
candy-minesweeper --medium # 16x16 with 40 mines
candy-minesweeper 16 10 # 16 columns by 10 rows, 20 mines by default
candy-minesweeper 9 9 10 # 9 wide, 9 tall, 10 mines
candy-minesweeper --pick # open the board picker first
The game draws the board in a rounded frame, with a status line and a help footer below it. Move the cursor with the arrow keys or hjkl, reveal with Space, and flag with f.
The game logic also runs without a terminal. examples/headless.php reveals one cell on a fixed-seed 8x5 board, prints the grid as text and then reveals every safe cell. Its output on every run is:
after revealing (0,0):
.1######
.2######
.2######
12######
########
won: no
after revealing every safe cell:
.111.1#1
.2#2.111
.2#3211.
123#2#1.
1#21211.
won: yes
In the text grid, # is a hidden cell, F is a flag, . is a revealed empty cell, a digit is the count of neighbouring mines, and * is a revealed mine. The six # left at the end are the six mines.
Concepts
The board is a grid of immutable Cell values. Each cell records whether it holds a mine, whether it is revealed, whether it carries a flag or a question mark, and how many of its eight neighbours hide mines. Board is the only place that changes that state. Every transition returns a new board: reveal(), cycleMarker() and chord().
Numbers are the clue. A revealed cell shows how many of its eight neighbours hide mines. The in-game help footer teaches that rule on its first line.
The first reveal is always safe. Mines are placed after the first click, so the clicked cell and its 3x3 neighbourhood start mine-free. At edges and corners the zone is smaller, with 6 or 4 guaranteed-safe cells. A board too dense for the full zone falls back to keeping only the clicked cell clear. The custom-board limits prevent that from happening in a normal game.
Flood-fill. Revealing a zero cell reveals its neighbours, and so on across the connected empty region. The fill is iterative and stack-based, so a large open board cannot overflow the call stack.
Winning. You win by revealing every cell that is not a mine. Flags are notes. The win check counts revealed safe cells only, so a board can be won with no flags at all. Board::isWon() compares a counter with width x height - mines, so the check is constant-time on any board size.
Markers. f cycles a cell through flag, question mark and clear. A question mark is a free memo that never counts toward the mine total and never takes part in a chord. Flagging is refused once the flags equal the mine count, and un-flagging stays free.
Chords. When a revealed number has exactly that many flagged neighbours, c, a middle-click or a double left-click reveals the remaining neighbours. The flags must match exactly. If any flag is wrong, the chord detonates on it. A revealed zero is never chordable.
The clock. The timer starts at the first successful reveal or chord. It is wall-clock time and has no pause, so an idle spell inflates a game in progress. Saves restore the elapsed time but never record a best time.
Tasks and how-to
Pick a difficulty
Four presets exist. Pass one as a flag, or pick it from the in-game picker with n and the keys 1 to 4.
| Preset | Flag | Board | Mines |
|---|---|---|---|
Difficulty::Easy | --easy | 9 x 9 | 10 |
Difficulty::Standard | --standard (the default) | 10 x 10 | 12 |
Difficulty::Medium | --medium | 16 x 16 | 40 |
Difficulty::Expert | --expert | 30 x 16 | 99 |
Play a custom board
Pass a width, a height and a mine count. Width is columns and height is rows. Each side must be 2 to 50, and the mine count must leave a safe 3x3 area for the first click, so 1 <= mines <= width x height - 9. Boards of fewer than 10 cells are refused. If you give only the width and height, the mine count defaults to one eighth of the cells, rounded down, with a minimum of 1.
candy-minesweeper 30 16 99 # the Expert shape, by hand
candy-minesweeper 20 20 # 20x20 with 50 mines by default
Save and resume a game
Press S to write the live game to a single save slot, and L to load it. Loading works after a win or a loss too, so you can replay the exact board. Saving is refused once the board is finished, which leaves the slot unchanged.
The slot is $XDG_CONFIG_HOME/candy-minesweeper/savegame.json when XDG_CONFIG_HOME is set to an absolute path (a relative value is ignored), and ~/.config/candy-minesweeper/savegame.json otherwise. It is written with mode 0600 through an atomic write. The slot records the full mine layout as well as your progress. Treat the file as private if you sync dotfiles.
Keep statistics across sessions
Statistics are opt-in. Set CANDY_MINESWEEPER_STATS to a file path and each finished game is tallied there per preset: games, wins and best time. Only boards whose shape matches a preset are tallied, and a save restored with L never records a best time.
export CANDY_MINESWEEPER_STATS="$HOME/.local/state/candy-minesweeper/stats.json"
candy-minesweeper --standard
Start a game from code
Build a Game with Game::start(), Game::withDifficulty() or Game::withCustom(), and pass a seeded generator to make the layout repeatable. examples/play.php shows the full runtime wiring.
use SugarCraft\Core\Program;
use SugarCraft\Minesweeper\Difficulty;
use SugarCraft\Minesweeper\Game;
// one of the three constructors, passed to the runtime
$game = Game::withDifficulty(Difficulty::Medium); // a preset
$game = Game::withCustom(12, 10, 14); // a custom shape
$game = Game::start(width: 12, height: 10, mines: 14); // the blank board the binary uses
(new Program($game))->run();
Read the board without a terminal
Use Board directly. The cells come back as rows, and reveal() takes a generator closure for the first click. The examples/headless.php script is a complete worked version of this.
use SugarCraft\Minesweeper\Board;
$board = Board::blank(8, 5, 6);
$board = $board->reveal(0, 0, $rand); // $rand: Closure(int): int
if ($board->isWon()) {
// every safe cell is revealed
}
$cell = $board->cell(0, 0); // Cell|null, read-only
API reference
The public classes group by role. The table lists the methods a caller most often needs.
| Class | Method | Description |
|---|---|---|
| Game | start(width, height, mines, rand, stats, statsPath, notice) | Builds a game on a blank board. Mines are placed on the first reveal. |
| Game | withDifficulty(Difficulty, ...) | Builds a game on a preset shape. |
| Game | withCustom(width, height, mines, ...) | Builds a game on a custom shape. |
| Game | withPicker() / presetKeys() | Opens the board picker. presetKeys() lists the keys that start a preset. |
| Game | update(Msg) / view() / subscriptions() | The TEA surface: handle a key, mouse or tick message, render the frame, and subscribe to the 1 Hz clock. |
| Game | elapsed() / difficulty() / stats() / savePath() (static) | The elapsed seconds, the preset in play (or null), the current statistics, and the save slot path. |
| Board | blank(width, height, mines) / fromRows(...) | Builds an empty board, or one from explicit rows. |
| Board | reveal(x, y, rand) | Reveals a cell and flood-fills zeros. Places mines on the first reveal. |
| Board | cycleMarker(x, y) / chord(x, y) | Cycles a flag and question mark, or chords a satisfied number. |
| Board | cell(x, y) / rows() / isWon() / flagCount() | Reads one cell, all rows, the win state and the flag count. |
| Board | serialize() / unserialize(data) | Writes and reads the versioned save payload. The reader re-checks every field. |
| Cell | withMine() / withAdjacent() / reveal() / cycleMarker() | Immutable transitions on one cell. |
| Difficulty | width() / height() / mines() / fromDimensions(w, h, m) | The four presets, and the preset that matches a shape. |
| CustomDifficulty | new() / fromInput(rows, cols, mines) / label() / labelShape() | Validated custom-board input with named errors. |
| Stats | gamesPlayed(d) / wins(d) / winRate(d) / bestTime(d) / withGame(d, won, time) | Immutable per-preset tallies. |
| DifficultyStats | load(path) / save(path) / fromStats(stats) / withGame(...) | Atomic JSON persistence for the stats file. |
| Renderer | render(Game) / renderWithScanner(Game) / resolveClick(Game, col, row) | The pure view function, and the mapping from a mouse click to a cell. |
| Lang | t(key, params) | Looks up a UI string through sugar-core's translator. |
| TickMsg | () | The 1 Hz clock tick that repaints the status line. |
| Support\Version | line() / current() | The version line printed by --version. |
Only methods declared in candy-minesweeper/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.
SugarCraft\Minesweeper
Board final class
The minesweeper board — pure value object. Immutable; every reveal or flag returns a fresh Board with the changed cells swapped in.
| Method | Summary |
|---|---|
static fromRows(int $width, int $height, int $mineCount, array $rows, bool $minesPlaced = false, bool $exploded = false, int $revealedCount = 0, int $flaggedCount = 0): self | Public direct-construction boundary: the grid census for callers that hand us a full $rows map. Fail fast on a misshapen grid: a 5×5-claim over 2×2 data would silently produce an un-winnable board (win threshold unreachable, reveals outside the real data no-op). unserialize() runs its own stricter wire pass and constructs directly; both honour the same promise. |
static blank(int $width, int $height, int $mineCount): self | Empty board — all cells unrevealed, no mines. The first reveal triggers mine placement, avoiding the clicked cell + its eight neighbours whenever the mine count leaves room (so the player gets a non-trivial flood-fill on click 1). A board dense enough that the exclusion would starve the placement falls back to keeping only the clicked cell mine-free — see placeMines(). That regime is unreachable through the CLI: the launcher caps mines at cells − 9. |
cell(int $x, int $y): ?Cell | |
rows(): array | |
reveal(int $x, int $y, \Closure $rand): self | Reveal the cell at (x, y). If it has no adjacent mines, also reveal every neighbour transitively (classic flood fill). If mines aren't yet placed, place them first, excluding the clicked cell's 3×3 neighbourhood — or, on a board too dense for that exclusion to leave enough candidates, the clicked cell alone (placeMines()). |
cycleMarker(int $x, int $y): self | |
isWon(): bool | True exactly when every non-mine cell has been revealed. O(1) via revealedCount. |
flagCount(): int | Number of flagged cells. O(1) via the incrementally-tracked counter. |
serialize(): string | Serialize the board to a string for save/load mid-game. |
static unserialize(string $data): self | Reconstruct a Board from a string produced by serialize(). |
chord(int $x, int $y): self | Chord click — reveal all unflagged neighbours of a "satisfied" number. |
Cell final class
One cell on the minefield. Immutable value object — every transition (reveal, flag, etc.) routes the house Mutable with-pattern to return a fresh Cell rather than mutating in place, so Board can rebuild itself with normal array spread without aliasing issues.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(public readonly bool $mine, public readonly bool $revealed = false, public readonly bool $flagged = false, public readonly int $adjacent = 0, public readonly bool $questioned = false) | |
withMine(bool $mine): self | |
withAdjacent(int $n): self | |
reveal(): self | |
cycleMarker(): self | The classic marker cycle: empty → flag → question → empty (finding -093 GAP-05). Flag and question are mutually exclusive states on the same memo key; a revealed cell holds no marker at all (no-op). |
Difficulty enum
Difficulty levels for minesweeper.
Cases: Easy · Standard · Medium · Expert
PHP also provides cases().
| Method | Summary |
|---|---|
width(): int | |
height(): int | |
mines(): int | |
static fromDimensions(int $width, int $height, int $mines): ?self | Derive a Difficulty from board dimensions and mine count. |
Game final class
Minesweeper as a SugarCraft Model. Keys: - arrows / hjkl → move cursor - space / enter → reveal - f → toggle flag - c → chord - S → save the live game (single slot, 0600, under $XDG_CONFIG_HOME/candy-minesweeper/ when that env is set, else $HOME/.config/candy-minesweeper/) - L → load that save — works even after game over, so the player can step a lost board back to the saved one - r → restart - n → new-game picker: 1-4 start a preset, c opens the custom-board digit form, q/Esc walk back - q / esc / Ctrl+C → quit (q/Esc ask twice on a live unsaved board) Mouse: left-click reveals, right-click flags, middle-click chords.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(public readonly Board $board, public readonly int $cursorX = 0, public readonly int $cursorY = 0, ?\Closure $rand = null, public readonly ?float $startedAt = null, public readonly ?int $elapsedSeconds = null, public readonly ?Stats $stats = null, public readonly ?string $statsPath = null, public readonly ?string $notice = null, public readonly bool $newBest = false, public readonly ?int $beatenRecord = null, public readonly int $frameCols = 80, public readonly int $frameRows = 24, public readonly bool $restoredGame = false, public readonly bool $dirty = false, public readonly bool $confirmQuit = false, public readonly bool $picking = false, public readonly ?CustomForm $form = null, public readonly ?float $lastClickAt = null, public readonly int $lastClickX = -1, public readonly int $lastClickY = -1) | |
requiredRows(): int | Terminal rows the current frame consumes: board height, the rounded border (2), the status line (1), the four-line help footer, and a spare line — plus one more while a toast rides above the status. Below this the board cannot be shown whole, and the game refuses rather than painting a clipped minefield. |
tooSmall(): bool | True when the live terminal cannot host the full frame. |
withFrame(int $cols, int $rows): self | Seed the live viewport at boot (the runtime then owns updates). |
withPicker(): self | Open the new-game picker overlay on this game's board: the opt-in --pick launch lands here, so the first frame is the same overlay n opens mid-game. The board underneath is the plain 10x10 default, which is also where q/Esc walk back to, so the picker is a door in front of the unchanged launch contract rather than a different one. |
static start(int $width = 10, int $height = 10, int $mines = 12, ?\Closure $rand = null, ?Stats $stats = null, ?string $statsPath = null, ?string $notice = null): self | |
static withDifficulty(Difficulty $d, ?\Closure $rand = null, ?Stats $stats = null, ?string $statsPath = null, ?string $notice = null): self | |
static withCustom(int $width, int $height, int $mines, ?\Closure $rand = null, ?Stats $stats = null, ?string $statsPath = null, ?string $notice = null): self | Convenience alias of start() for named-argument call sites ("custom" dimensions vs the preset ladder). Deliberately carries no validation of its own — callers coming from user input route through \SugarCraft\Minesweeper\Ui\CustomDifficulty::fromInput() first (the CLI does), which is what makes the alias safe to keep. |
difficulty(): ?Difficulty | |
rand(): \Closure | The injected PRNG. Exposed because Board::reveal() takes the closure per call — a caller cloning a Game (or driving the Board directly, as the save round-trip pins do) must reuse this game's sequence rather than silently switching to random_int. |
stats(): Stats | |
init(): ?\Closure | |
update(Msg $msg): array | |
static presetKeys(): array | The picker's digit → preset table in display order (msw-09). One source for both the renderer's rows and the model's key handling: a re-ordered enum can never make key 2 start what the screen labelled 3 (finding 058's same-table-different-meaning class). |
static savePath(): ?string | Absolute path of the single-slot savegame, resolved from the environment at call time (never cached — tests sandbox HOME per test, and a process that learned its HOME after boot should still find the file). XDG_CONFIG_HOME wins when set AND absolute; a relative value is ignored and the slot falls to $HOME/.config (finding -064: the docblock promises an absolute path, and a relative XDG leg would make the slot CWD-dependent — the XDG spec bars relative values too). Null when neither carries a usable value: save then degrades to a no-op and load keeps the current game, mirroring the best-effort stats writes. |
view(): string | |
elapsed(): ?float | Elapsed seconds: the live wall clock while the game runs, the frozen $elapsedSeconds stamp once it is over (set at the transition or restored from a finished save), null before the first reveal. |
recordResult(?float $elapsed): self | Record the result of this game and return a new Game with updated stats. The returned Game has the same board state but updated stats. |
subscriptions(): ?\SugarCraft\Core\Subscriptions | Arm the 1 Hz 'clock' tick while — and only while — the timer is live: from the first actual reveal (startedAt set; dud keypresses and refused clicks never arm it) to the win/lose transition (board over, elapsed frozen into elapsedSeconds). The runtime reconciles subscriptions after every update cycle, so the tick starts on the first reveal and is cancelled when this method stops listing the id. |
Lang final class
Per-library translation facade for candy-minesweeper.
Renderer final class
Pure view function: takes a Game and returns the framebuffer string. No I/O, no caching — every call rebuilds from scratch so snapshot tests can assert against the output directly.
| Method | Summary |
|---|---|
static render(Game $g): string | |
static setBoardColourOverride(?bool $on): void | |
static renderWithScanner(Game $g): array | Render the minefield view and return a ready-to-use Scanner so callers can hit-test clicks. |
static resolveClick(Game $g, int $col, int $row, ?Scanner $scanner = null): ?array | Resolve a mouse click at (col, row) to a cell coordinate. |
Stats final class
Immutable stats tracker for minesweeper games.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(public readonly int $easyGames = 0, public readonly int $easyWins = 0, public readonly ?int $easyBest = null, public readonly int $standardGames = 0, public readonly int $standardWins = 0, public readonly ?int $standardBest = null, public readonly int $mediumGames = 0, public readonly int $mediumWins = 0, public readonly ?int $mediumBest = null, public readonly int $expertGames = 0, public readonly int $expertWins = 0, public readonly ?int $expertBest = null) | |
withGame(Difficulty $d, bool $won, ?int $time): self | Fold one finished game into the tally for its preset bucket. |
gamesPlayed(Difficulty $d): int | |
wins(Difficulty $d): int | |
winRate(Difficulty $d): float | |
bestTime(Difficulty $d): ?int |
TickMsg final readonly class
Fired at 1 Hz by the 'clock' tick subscription while a game's timer runs.
SugarCraft\Minesweeper\Stats
DifficultyStats final class
Atomic persistence wrapper for minesweeper difficulty statistics.
Not listed: the methods of SugarCraft\Core\Concerns\Mutable, a trait declared outside src/.
| Method | Summary |
|---|---|
__construct(private readonly Stats $stats) | |
static fromStats(Stats $stats): self | Build a DifficultyStats from an existing Stats object. |
static load(string $path): ?self | Load difficulty stats from a persistence file. |
save(string $path): void | Save difficulty stats atomically to a persistence file. |
withGame(Difficulty $d, bool $won, ?int $time): self | Record a game result and return a new DifficultyStats with the update applied. |
stats(): Stats | Underlying Stats snapshot (bare accessor — house convention, no get). |
SugarCraft\Minesweeper\Support
Requirements final class
Boot requirements as data (msw-23, finding candy-minesweeper-018). The app rides sugar-core's cell-width and i18n math, whose own manifest declares ext-intl + ext-mbstring (sugar-core/composer.json:34-35). The composer path enforces them transitively, but the advertised phar channel installs nothing through composer — without a preflight the first frame that measures a glyph would semi-die on an undefined-function Error laundered out of frozen vendor code.
| Method | Summary |
|---|---|
static firstMissing(array $loaded): ?string | |
static refuseMessage(string $extension): string |
Version final class
The version string this tool reports on --version.
| Method | Summary |
|---|---|
static line(): string | The --version line: plain text, newline-terminated, produced by no state and no host probe — the flag must answer anywhere. |
static current(): string | The version this process reports: the archive stamp when running from a stamped phar, self::CURRENT everywhere else. |
static fromPharMetadata(string $path): ?string | The version a phar archive at $path was built to carry, or null when it names none (unreadable archive, wrong metadata shape, the dev-build sentinel, or an empty stamp). Every refusal is a null, never an exception — --version must answer on a machine whose phar cannot be opened. |
static versionFromMetadata(mixed $metadata): ?string | The judgement on the stamp itself, split out because the archive-open leg is unreachable from a suite that must not build phars: the release namespace strip, the dev-build refusal, and the wrong-type nulls are a pure function over what getMetadata() answers. |
static hostArchive(): string | The filesystem path of the phar this process was launched from, or '' when it was not launched from one — measured on candy-code's real builds and pinned by the bin autoload guard: inside archive-loaded code Phar::running(false) answers the archive path, while the stub context answers '' and there a '.phar'-suffixed __DIR__ is the enclosing archive. |
SugarCraft\Minesweeper\Ui
CustomDifficulty final class
Board-shape validator + the backing store of the in-game custom-board form (msw-09/G5-b): the picker's CustomForm collects the digits and submits through fromInput(), so the player-specified rows, columns and mine count of a custom game really are validated here — the CLI positional door and the interactive door share one law.
| Method | Summary |
|---|---|
static new(): self | The default custom shape (msw-09/-032: the fleet factory spelling is new(), and the forbidden-by-name defaults() earns its keep only through real callers — the picker form seeds from this). |
static fromInput(int $rows, int $cols, int $mines): self | Build from raw input values. Throws on validation failure. |
label(): string | Return a display label for the current settings — translated, and WIDTH-first (the same order the CLI grammar, README and every on-screen shape speak; this object's rows is the height, its cols the width — msw-09/-033). |
static labelShape(int $width, int $height, int $mines): string | The single shape formatter (msw-09/-033): every surface that names a board as "{width}×{height} · {mines} mines" routes here, so the width-first convention and the translation cannot drift per-call. |
CustomForm final class
The in-game custom-board form state (msw-09/G5-b): three digit fields — width, height, mines — typed one field at a time, submitted through CustomDifficulty::fromInput() so the interactive door and the CLI positional door share one validation law (msw-18).
| Method | Summary |
|---|---|
__construct(public readonly string $width = '', public readonly string $height = '', public readonly string $mines = '', public readonly int $field = self::FIELD_WIDTH, public readonly ?string $error = null) | |
static seeded(): self | Seed the form from CustomDifficulty::new() so the default shape is the one the validator itself proposes — Enter three times plays a board, matching the preset ladder's easiest rung. |
values(): array | |
value(int $field): string | |
withDigit(string $digit): self | Append a digit to the active field; past the field's cap the keypress is inert (see MAX_DIGITS). Any edit answers the refusal. |
withBackspace(): self | Delete the last digit of the active field; empty stays empty. |
advanced(): self | Enter/Tab: move to the next field; on the mines field there is no next — the caller submits. The refusal line clears with the move: it blamed a digit the player has now stepped away from. |
atSubmitField(): bool | |
submit(): CustomDifficulty | Validate the typed shape. Throws the translated refusal (the ui wording names rows/columns — the bridge sentence above maps that vocabulary onto the field labels the player sees). |
withError(string $error): self | Attach a refusal message without touching the typed digits, and park the cursor back on the width field: the form advances only (Enter walks forward), so a player told "columns must be at least 2" must find the editing cursor where the fix begins, not stranded on the field that just submitted. |
Configuration
The binary takes its board from the command line and its environment from the shell. The options accepted by the binary are below. Every block of the README accepts the same options.
| Option | Effect |
|---|---|
--easy, --standard, --medium, --expert | Start a preset. Only one preset flag is allowed. |
[width] [height] [mines] | A custom board. Cannot be combined with a preset flag. |
-p, --pick | Open the board picker as the first frame. Cannot be combined with a preset or with dimensions. |
-v, --version | Print the version and exit. |
-h, --help | Print the usage text and exit. |
Any other option exits with status 1 and prints the usage text to stderr. Nothing is silently ignored.
| Environment variable | Effect |
|---|---|
CANDY_MINESWEEPER_STATS | Path of the statistics file. Unset means the game stays in memory. |
CANDY_MINES_STATS | The pre-rename variable. Still read, with a deprecation warning. |
XDG_CONFIG_HOME | Changes the directory of the save slot. |
NO_COLOR, CLICOLOR=0, TERM=dumb | Drop to plain text. The board switches to its narrow glyph set. |
FORCE_COLOR, CLICOLOR_FORCE | Assert colour to a host that misdetects as dumb. |
COLORFGBG | A background report ending in ;7 selects the darkened light-console palette. |
LC_ALL, LC_MESSAGES, LANG | Choose the interface locale. The game falls back to English. |
Keys
| Key | Action |
|---|---|
| ↑ ↓ ← → or h j k l | Move the cursor. |
| Home / End | Jump to the start or end of the row. |
| PgUp / PgDn | Jump half a board height up or down. |
| Space / Enter | Reveal the cell. |
| f | Cycle the marker: flag, then question mark, then clear. |
| c, middle-click or double left-click | Chord a revealed number. |
| S / L | Save the live game, or load the saved game. |
| r | Restart with new mines. |
| n | New game. Pick a preset with 1 to 4, or open the custom form with c. |
| q / Esc | Quit. On a live board with an unsaved position, the first press asks for confirmation. |
| Ctrl+C | Quit at once. |
| Left click / right click | Reveal / flag. Terminals that do not honour cell motion tracking simply never send mouse rows, and the keyboard still works. |
Ctrl and Alt letters are inert, so an editor habit cannot restart or save the game by accident. Some control combinations arrive as plain bytes and act as Enter or Escape. Ctrl+J and Ctrl+M reveal like Space, and Ctrl+[ quits like Esc.
Theming and colour
The board uses a number palette in which each adjacent count has its own hue. The count is also drawn as the digit itself, so the board reads correctly without colour. Flags are a bold gold F, hidden cells are a width-safe colon, and the cursor is reverse video.
Colour follows the terminal. Setting NO_COLOR, CLICOLOR=0 or TERM=dumb drops the output to plain text. The renderer then uses an ASCII glyph set: an x for a wrong flag and a + border. On a light console, a background report ending in ;7 in COLORFGBG selects darkened versions of every ink, each of which clears 4.5:1 contrast against white. Terminals that declare neither keep the dark palette.
The always-on help legend uses a dim lavender that sits below WCAG AA for body text against the dark background. NO_COLOR paints every line in the terminal's own ink, which is the highest-contrast option.
Examples
examples/play.php: the interactive game wired by hand, with the same locale, colour and mouse setup as the binary. Run it in a terminal withphp examples/play.php. With stdin at/dev/nullit draws one frame and exits with status 0.examples/headless.php: the pureBoardAPI with no terminal and no event loop. It takes no input, uses a fixed seed and prints the output shown in the Quickstart. Run it withphp examples/headless.php.
The gameplay recordings at the foot of this page are the .vhs/play.tape and .vhs/flagging.tape tapes, each of which drives ./bin/candy-minesweeper.
Testing
composer install
vendor/bin/phpunit
The suite covers the board rules, the game flow, the saves, the statistics and the views. Snapshot tests in tests/GoldenRenderTest.php pin the first-click safe area, the cascade reveal and the win overlay against golden files under tests/fixtures/, using sugar-testing. LocaleParityTest fails when any of the 16 locale files drifts from the English key set. FooterWidthGuardTest keeps the help footer within 80 columns in every locale.
Troubleshooting and FAQ
- The binary exits with
candy-minesweeper requires ext-mbstring. The phar cannot install extensions through Composer, so it checks them at boot. Installphp8.3-mbstringandphp8.3-intl, then check withphp -m. - The footer wraps on a wide-glyph terminal. Terminals set to double-width ambiguous characters, such as
--ambigwidth=2, widen the footer separator, the arrow hints and the rounded border. Set the terminal's ambiguous-width option to narrow. - The game shows a notice instead of the board. The board is never drawn clipped. While the terminal has fewer rows than the frame needs, the whole screen becomes a plain-text notice that names the rows needed and the rows available, with a reminder that q quits. Enlarge the window and the game resumes at once on the same board. The frame needs the board height plus 8 rows, so
Expert(16 rows high) needs 24 rows, and boards near 50 by 50 need a much taller terminal. Any status notice on screen adds one more row, soExpertthen needs 25: the save, load, restart and quit-confirm messages, the refusals, and the resume hint that shows at launch when a save is waiting. In a 24-row window the board is replaced by the fit notice. Movement, reveal, flag and chord keys do nothing while the notice is up, so enlarge the window to bring the board back. - The game refuses to start in a short terminal. At launch the binary measures the terminal before it paints anything. If the rows available are fewer than the frame needs, it prints the same translated message to stderr, with the row budget, and exits 1. Start it in a taller window, or launch a smaller board shape.
- The save refuses to load. The message
save refused (unreadable or tampered)means the file failed validation. The reader re-checks every field and refuses foreign versions, so a hand-edited slot leaves the game untouched. - Best times look wrong. The clock is wall-clock time with no pause, so an idle spell inflates a game in progress. A best time is a minimum, so one dishonestly slow first entry stands until a faster run beats it.
- Two instances lose statistics. Writes are atomic, but two processes sharing one stats file resolve as last-writer-wins. Give each parallel session its own
CANDY_MINESWEEPER_STATSpath. - Screen readers cannot read the board. The board is conveyed only through the visual frame, and there is no text-dump mode. Keyboard play works, and the digits,
Fand cursor reverse video carry the meaning without colour.
Architecture
The pure state lives in Board, Cell and Difficulty. The runtime is one Model, Game, which owns the cursor, the key routing, the flow and the timer. Renderer is a pure function from a Game to a string, built on sugar-cellbuffer and sugar-mouse. Persistence sits in Stats and DifficultyStats, which use sugar-core's atomic JSON file.
| File | Role |
|---|---|
Cell | A value object: mine, revealed, flagged, question mark and the adjacent count. |
Board | The grid and every transition. Win detection is O(1) through a revealed counter. Serialises to versioned JSON. |
Game | The TEA model: cursor, key routing, game flow and the timer. |
Difficulty | The four presets, with dimension and mine counts. |
Stats and DifficultyStats | Immutable tallies per preset, and their atomic JSON persistence. |
Renderer | The pure view function and the click-to-cell mapping. |
Ui\CustomDifficulty | Validated custom dimensions, with an error that names the violated bound. |
Lang and TickMsg | The translation facade and the 1 Hz clock message. |
The board uses an immutable list of lists of Cell. Mines are placed after the first click, and the save format is the same versioned JSON that the in-game slot uses.
Upstream mapping
The design antecedent is the Go game maxpaulus43/go-sweep. It was transcribed rather than cloned, and the parity record lives in the monorepo's docs/old/repo_map/. The table shows the rows that still hold.
| Aspect | go-sweep | candy-minesweeper |
|---|---|---|
| Language | Go | PHP 8.3+ |
| Framework | Bubble Tea | sugar-core (ReactPHP) |
| First-click safety | TODO comment, not implemented | Implemented, with a 3x3 safe zone and a dense-board fallback |
| Win detection | O(n) grid scan | O(1) through a revealed counter |
| Mine placement | Shuffle all cells up front | Deferred until the first click |
| Recursion | Recursive sweep | Iterative, stack-based flood-fill |
| Chord rule | Fires at adjFlags >= adjMines, chords revealed zeros | Exact match only, zeros are not chordable, chord on c or the middle click |
| RNG | Seeded from the clock | An injectable Closure(int): int |
| Serialization | None | Versioned JSON, shared with the save slot |
| Internationalisation | None | 16 locales |
| Timers | Whole seconds | Sub-second, shown by a 1 Hz tick |
The shape of the 10 x 10 default board, the picker, the custom form, the save payload and the colour degradation have no upstream counterpart.
Versioning and changelog
The version is reported by --version, and a phar build reads it from the archive metadata. The package was published as sugarcraft/candy-mines until the 2026-10 rename. The namespace moved from SugarCraft\Mines\ to SugarCraft\Minesweeper\. The old CANDY_MINES_STATS variable is still read, with a deprecation warning, and nothing under the old name receives updates.
Related
- sugar-core: the Model and Program runtime, the translator and the atomic JSON file.
- sugar-style: the styled frame and the colour profile.
- sugar-testing: the golden-file helpers behind the render tests.
Demos.
VHS-recorded GIFs of the shipped binary — each tape drives ./bin/candy-minesweeper in a scripted session. Regenerated automatically on every push that touches the source.
Play
Cursor walk, flood-fill reveal, flag plant.