All 22 apps

CandyMinesweeper

Minesweeper on the SugarCraft stack

inspired by maxpaulus43/go-sweep game minesweeper sugarcraft injectable-rng

CandyMinesweeper code coverage

Customizable board (width / height / mine count), iterative zero-flood-fill, win / lose detection. Pure-state Board class so every reveal is unit-testable without touching the runtime.

Requirements

PHP 8.3+ with ext-mbstring (the cell-width math behind every glyph) and ext-intl (the locale machinery behind the 16-locale interface). The composer path enforces both transitively through sugar-core's manifest; the standalone phar installs nothing through composer, so the binary preflights them itself and refuses with a named exit-1 message (candy-minesweeper requires ext-mbstring) before the first frame, never a half-rendered board dying on an undefined function.

Install

composer require sugarcraft/candy-minesweeper
./vendor/bin/candy-minesweeper       # play straight from the dependency

# or run the shipped binary from a clone:
composer install
./bin/candy-minesweeper

# or grab the rolling latest phar (rebuilt on every push to master):
wget https://github.com/detain/sugarcraft/releases/download/candy-minesweeper/latest/candy-minesweeper.phar
php candy-minesweeper.phar

Quickstart

./bin/candy-minesweeper                    # 10×10, 12 mines (defaults)
./bin/candy-minesweeper 16 16 40           # positional args: width height mines
// Programmatic:
use SugarCraft\Core\MouseMode;
use SugarCraft\Core\Program;
use SugarCraft\Core\ProgramOptions;
use SugarCraft\Minesweeper\Game;

(new Program(Game::start(width: 16, height: 16, mines: 40),
             new ProgramOptions(useAltScreen: true,
                                mouseMode: MouseMode::CellMotion)))->run();

What's in the box

First-click safetyMines aren't placed until the first reveal, with the clicked cell's 3×3 neighbourhood excluded (6 or 4 cells at edges) — every game gets a non-trivial flood-fill on click 1. On densely customized boards that cannot spare a full 3×3 the exclusion falls back to the clicked cell alone, so the first click is still never a mine and every requested mine is placed.
Iterative flood fillZero-adjacency cells reveal their neighbours transitively, exactly like classic Minesweeper.
Vim-style movementhjkl alongside arrows; cursor clamps at board edges.
Flag togglef flags / unflags the cursor cell; flagged cells can't be revealed by accident.
Chord clickc or middle-click on a satisfied number reveals all unflagged neighbours — mirrors classic left+right chord behavior.
Sub-second timerThe clock reads microtime(true) internally, but every observable path — the status line and the persisted best times — is whole seconds; frozen on win/lose.
Best-time persistenceOpt-in via CANDY_MINESWEEPER_STATS=/path/stats.json (off by default): DifficultyStats then persists games/wins/best time per difficulty to JSON atomically via sugar-core AtomicJsonFile (flock sidecar, temp + rename) so crashes never corrupt the record. Records ride live clocks only: a savegame restore re-anchors the timer from the file, so restored games still count games and wins but can never set a best time (the brand is monotonic per session). The live clock is wall-clock with no pause — AFK time and laptop sleeps inflate a running game, and one dishonestly slow first entry shadows a preset's minimum until a faster run beats it.
Win + lose detectionisWon = every non-mine revealed; exploded = at least one mine was clicked. O(1) via revealedCount — no grid scan on each move.
Restart keyr reseeds with a fresh layout, preserving the chosen board size.
Save / resume mid-gamePress S to write the live board to the single save slot — $XDG_CONFIG_HOME/candy-minesweeper/savegame.json when set, ~/.config/candy-minesweeper/savegame.json otherwise (mode 0600) — and L to restore it. The slot carries the full live mine layout: it is the answer key to the game in progress, so keep the file private if you sync dotfiles. Backed by Board::serialize() versioned JSON; unserialize() re-validates every shape and recomputes the counts, so tampered payloads are refused rather than half-parsed.
New-game pickerPress n — live or on the post-game banner — to choose another board without a shell round-trip: 1-4 start the presets, c opens a digit form (width, height, mines) validated by the same rules as the CLI arguments, refusals included. Plain launch still plays the classic 10×10 board straight away (ruling G5-b), and the whole picker speaks the terminal's locale.
Localized interfaceStatus line, win/lose banners and the help footer route through Lang::t; LC_ALL/LC_MESSAGES/LANG pick the locale from 16 shipped files.
Custom difficultyUi\CustomDifficulty validates rows (2–50), cols (2–50), mines (1 to rows×cols−9) with i18n-aware error messages.
Terminal graceful downgradeSetting NO_COLOR, CLICOLOR=0, or TERM=dumb strips the foreground/background colors through the fleet color authority; the game stays fully playable without them.

Source & demos

Try the quickstart →

API

ClassMethodDescription
Gamestart(width, height, mines)Start a new game (optional $rand, $stats, $statsPath, $notice)
GamewithDifficulty(d)Start with a preset difficulty
GamewithCustom(width, height, mines)Start a custom-sized game; it tallies stats when its dimensions match a preset (via difficulty()) and plays without preset tallies otherwise
Gamedifficulty()The Difficulty whose dimensions the board matches, or null for a custom shape
GamesavePath()Absolute save-slot path resolved at call time ($XDG_CONFIG_HOME wins, then $HOME/.config); null when neither is usable, degrading save/load to announced no-ops
Gameelapsed()Elapsed time as float seconds (the status line and stats carry whole seconds)
GamerecordResult(elapsed)Record win/loss and update stats
Boardblank(width, height, mineCount)Empty board; mines placed on the first reveal
Boardcell(x, y)Get cell at position
Boardreveal(x, y, rand)Reveal the cursor cell — places mines on the first call, then floods; no-ops on revealed or flagged cells
BoardtoggleFlag(x, y)Flag / unflag a cell; no-ops once the cell is revealed
Boardchord(x, y)Chord-click — reveals the unflagged neighbours of a satisfied number; a mis-flagged mine detonates through the flood
BoardisWon()True when every non-mine cell is revealed (O(1))
BoardflagCount()Live flag total (tracked incrementally)
Boardserialize()Emit versioned JSON string ({v:1, w, h, m, p, e, r, c}) — the save slot's board payload
Boardunserialize(data)Reconstruct a Board from a serialize() payload, re-validating shapes and recomputing counts
Difficultyenum (Easy/Standard/Medium/Expert)The four shipped presets; fromDimensions(w, h, m) maps a board shape back to its preset (or null)
Statspure value objectIn-memory games/wins/best time per difficulty — withGame(d, won, time), gamesPlayed(d), wins(d), winRate(d), bestTime(d)
Ui\CustomDifficultyfromInput(rows, cols, mines)Validate custom board dimensions; throws the translated string via Lang::t on violation
Ui\CustomDifficultydefaults()Factory — 9×9, 10 mines
DifficultyStatsload(path)Load stats from atomic JSON file (null if absent; RuntimeException on an invalid or unsupported-version file)
DifficultyStatssave(path)Persist stats atomically via AtomicJsonFile (flock + temp + rename)
DifficultyStatswithGame(d, won, time)Return new DifficultyStats with the game recorded
DifficultyStatsstats()Read side as the pure Stats value object

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

Play

Cursor walk, flood-fill reveal, flag plant.
Flagging

Flagging

f key toggles a flag on the cursor cell to mark suspected mines.