CandyFlappy
Flappy-Bird in your terminal
candy-flappy is a terminal flap game. The bird's vertical motion is a SugarSpring Projectile (gravity plus an upward velocity kick on each flap), pipes slide left one cell per tick, and collision is tested per cell. The game state is a pure value: Game is a SugarCraft Model, so every key, tick and resize returns a new Game, and Renderer paints one frame from it. The design is a native PHP take on flapioca; the Go original ticks at 5 Hz, and this port runs the same one-column-per-tick rule at 30 ticks per second.
Install
Requires PHP 8.3 or newer with the intl and mbstring extensions. The package is pre-1.0 and publishes a dev branch only, so Composer needs the explicit @dev constraint:
composer require sugarcraft/candy-flappy:@dev # the game binary lands in vendor/bin/candy-flappy
A standalone .phar is published with the GitHub releases and runs with php candy-flappy.phar. A monorepo checkout needs only composer install inside candy-flappy/.
Quickstart
# From a checkout: install the lib's own dependencies, then run the checked-in bin
cd candy-flappy && composer install && ./bin/candy-flappy
# From a Composer install: the vendored console bin
vendor/bin/candy-flappy
candy-flappy --version # prints the version line and exits 0
candy-flappy --help # prints the usage and exits 0
The game needs a terminal at least 62 columns by 21 rows, with stdout attached to a real TTY. A smaller window shows a notice screen instead of the board, and a piped stdout is refused with exit 1 before the game starts.
use SugarCraft\Core\Program;
use SugarCraft\Core\ProgramOptions;
use SugarCraft\Flappy\Game;
$final = (new Program(Game::start(), new ProgramOptions(useAltScreen: true)))->run(); // the final model: the Game
Program::run() returns the final model, typed as Model. A q or Esc quit settles a qualifying score inside update(), so that score is on the board before the call comes back. Ctrl+C does the same when the terminal delivers it as a key, as it does under kitty keyboard reporting. On a legacy terminal, Ctrl+C raises SIGINT instead. A signal death (SIGINT, SIGTERM, SIGHUP) skips update(), so a score from a run that ends that way is banked only if you also call settleOnExit() on the returned Game. When the program can receive a signal, check that the result is a Game and call settleOnExit() on it after run() returns, as bin/candy-flappy does. The call is idempotent. Read the best score from the Game with $final->highScore().
Concepts
The board opens on a ready card. The bird hovers and the world stays frozen until the first flap, so a launch never drops the player into the floor. The first flap starts the run and the 30 Hz tick subscription from Game::subscriptions() begins to deliver TickMsg values.
Each tick advances the bird, scrolls every pipe one column, spawns a pipe every Game::PIPE_EVERY ticks, and checks for a crash. A crash happens on the floor (the bird's row reaches Game::HEIGHT), on the ceiling (the row goes above 0), or in a pipe (the bird's cell lies outside the open gap). All three end the run the same way. Score rises by one for every pipe that has just slid past the bird's column, so surviving is scored, not flapping.
The pipe gap is the only progressive difficulty. PipeGenerator::gapHeightForScore() starts at 6 cells, shrinks by 1 every 5 points, and floors at 3. The gap's center row comes from the injected PRNG, so a gap never touches the floor or ceiling rows.
Physics constants
The bird's motion uses three constants on Bird, tuned for an 18-row playfield at 30 ticks per second:
| Constant | Value | Role |
|---|---|---|
Bird::FLAP_KICK | -10.0 | Upward velocity in cells per second, applied by flap() |
Bird::GRAVITY | 18.0 | Constant downward acceleration in cells per second squared |
Bird::TICKS_PER_SEC | 30 | Simulation rate, baked into the projectile's time step |
Fall speed is clamped to Projectile::TERMINAL_GRAVITY on every tick. The clamp never engages in ordinary play, because the fastest reachable fall peaks at about 25.4 cells per second while the bird is still inside the 18-row world, and at about 26 on the tick that reaches the floor. Both sit under one row per tick, so the bird cannot tunnel through a gap unchecked.
Tasks
Run the game headless and read the frame
use SugarCraft\Flappy\Game;
use SugarCraft\Flappy\Renderer;
$game = Game::start();
$after = $game->tickN(30); // advance 30 ticks, one second of physics, with no terminal
echo Renderer::render($after); // the full ANSI frame, as a string
Game::tickN($n) applies $n physics ticks in sequence. It is the deterministic helper the suite uses, and it needs no terminal.
Pin the pipe layout with an injected PRNG
use SugarCraft\Flappy\Game;
// The closure receives the inclusive upper bound and returns an int in 0..$max.
$pinned = Game::start(rand: static fn (int $max): int => intdiv($max, 2));
Every pipe gap is drawn through the closure, so the same seed gives the same board. Game::start() takes the closure as its first argument and a config directory as its second.
Read and merge the leaderboard
$game = Game::start();
$game->highScores(); // the kept top-ten list, lowest first (ascending)
$game->highScore(); // the best score, 0 when the board is empty; read this, not highScores()[0]
$merged = $game->withHighScore(42); // a new Game with 42 merged in; nothing is written to disk
withHighScore() only changes the in-memory board. The write happens through the Cmd the game returns on a finish, so a test or a script can check a score without touching the score file.
Reset the leaderboard
rm ~/.config/.candy-flappy/scores.json # or $XDG_CONFIG_HOME/.candy-flappy/scores.json
The next launch starts with an empty board. The lock sidecar next to the file stays in place on purpose; the lock is the anchor for concurrent writers, and removing it while another instance waits would race that instance.
Run the bundled example from a checkout
php examples/play.php --version
FORCE_COLOR=1 php examples/play.php # draws into a pipe on purpose; use a real terminal for play
The example mirrors the binary: it answers --version and --help, refuses unknown arguments with exit 2, and refuses a non-TTY stdout with exit 1 unless FORCE_COLOR or CLICOLOR_FORCE is set.
API reference
The public classes live in SugarCraft\Flappy\. Game is the only Model. Bird, Pipe, PipeGenerator and Renderer are value-level helpers that the Model calls, and the tests drive each of them directly.
| Class | Method | Description |
|---|---|---|
| Game | start(?Closure $rand = null, ?string $configDir = null) | Build the ready board, world frozen until the first flap. Loads the leaderboard from the config directory. |
| Game | init(), update(Msg), view() | The TEA contract. update() returns [Game, ?Cmd]; view() delegates to Renderer::render(). |
| Game | subscriptions() | The single source of the game cadence: a stable 30 Hz tick subscription. Returns null when crashed, before the first flap (the ready card), while blurred, when the viewport is too small, or when the terminal cannot play. |
| Game | tickN(int $n) | Apply $n ticks in sequence. The deterministic test helper. |
| Game | highScore(), highScores(), withHighScore(int $score) | The best score, the kept top-ten list, and an in-memory merge that returns a new Game. |
| Game | tooSmall(), rand() | Whether the live viewport is under 62 by 21, and the PRNG closure in use. |
| Game | settleOnExit() | Idempotent save of a qualifying score at the process boundary, the safety net for signal deaths. |
| Bird | spawn(int $x, float $y), tick(), flap(), row() | Create the bird, advance one physics step, apply the flap kick, and read the playfield row index. |
| Pipe | tick(), collides(int $col, int $row), isOffScreen() | Slide the pair one column left, test a cell against the open gap, and check whether it has left the field. |
| PipeGenerator | pipe(int $score, Closure $rand), gapHeightForScore(int $score) | Spawn a pipe pair at the right edge with a score-scaled gap. |
| Renderer | render(Game $g) | Compose one full frame for any Game state. Static, no side effects. |
| TickMsg | (a Msg value) | The message a tick subscription delivers to update(). |
| Support\Version | line(), current(), fromPharMetadata(string $path) | The version line printed by --version, and the phar stamp when one is present. |
| Lang | t($key, $params) | The i18n wrapper over SugarCraft\Core\I18n\T, with catalogs in lang/. |
Only methods declared in candy-flappy/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\Flappy
Bird final class
The bird's vertical motion is a SugarSpring Projectile with gravity pulling down at a constant rate. Tapping flap resets the vertical velocity to a fixed upward kick — same trick the original flapioca uses, just expressed as projectile state instead of an ad-hoc accumulator. Mirrors kbrgl/flapioca Model.Cursor (internal/model.go).
| Method | Summary |
|---|---|
__construct(public readonly int $x, public readonly Projectile $body) | |
static spawn(int $x, float $y): self | |
tick(): self | |
flap(): self | |
row(): int |
Game final class
Flappy-Bird as a SugarCraft Model. The world is width × height cells; the bird sits at column 8 and the world scrolls past it at a fixed cadence. Pipes spawn on the right edge every Game::PIPE_EVERY ticks and slide left one column per tick.
| Method | Summary |
|---|---|
__construct(public readonly Bird $bird, public readonly array $pipes, public readonly int $score = 0, public readonly bool $crashed = false, public readonly ?string $crashCause = null, public readonly int $tickIndex = 0, public readonly array $highScores = [], public readonly bool $newRecord = false, public readonly bool $started = false, public readonly bool $blurred = false, ?\Closure $rand = null, ?string $configDir = null, public readonly int $frameCols = self::MIN_COLS, public readonly int $frameRows = self::MIN_ROWS, public readonly ?ColorProfile $colorProfile = null, public readonly ?string $quarantinedSave = null, public readonly ?int $settledScore = null) | |
static start(?\Closure $rand = null, ?string $configDir = null): self | |
highScores(): array | |
highScore(): int | |
tooSmall(): bool | True when the live viewport cannot hold the 62x21 frame (M6). |
withHighScore(int $score): self | Merge a finished run into the leaderboard. |
init(): ?\Closure | |
update(Msg $msg): array | |
view(): string | |
settleOnExit(): Game | Process-boundary settle used by bin/candy-flappy after Program::run() returns. q/Esc already settle inside update() via a batched Cmd; the gap this closes is a signal death (Ctrl+C), where no KeyMsg ever ran and a live qualifying score would be lost. Idempotent: the settledScore stamp means a repeat call after a banking one is a no-op. A failed final save is reported there and then — see the catch — this method never throws and never touches the exit status. Returns the settled model: the banked run with its new-record flag when this call landed a fresh record on disk (flappy-70's ack line reads it), otherwise the unchanged instance. |
tickN(int $n): self | Test helper — apply N ticks deterministically. |
subscriptions(): ?Subscriptions |
Lang final class
Per-library translation facade for candy-flappy.
Pipe final class
One scrolling pipe pair. gapHeight is the number of OPEN rows between the upper and lower sections (m25: it is not a centre marker's symmetric radius). The band is anchored on gapY and, for even heights, tilts one row toward the floor — see collides(). Mirrors the obstacles of kbrgl/flapioca Model.Obstacles (internal/model.go — obst.Location.X--).
| Method | Summary |
|---|---|
__construct(public readonly int $x, public readonly int $gapY, public readonly int $gapHeight) | |
tick(): self | Slide the pipe one column to the left. |
collides(int $col, int $row): bool | True if the bird at (col, row) collides with the pipe. The pipe occupies a single column; collisions happen iff the bird is in that column AND the row is outside the open gap. |
isOffScreen(): bool |
PipeGenerator final class
Generates Pipe objects with gap height that varies based on score.
| Method | Summary |
|---|---|
static gapHeightForScore(int $score): int | Compute the gap height for a given score. |
static pipe(int $score, \Closure $rand): Pipe | Generate a new Pipe at the right edge with a variable gap height. |
Renderer final class
Pure view function: takes a Game and returns the framebuffer string. Walks the playfield once, fills every cell, then frames it with a rounded border.
| Method | Summary |
|---|---|
static render(Game $g): string |
TickMsg final class
Frame-tick. Fired every Game::TICK_SECONDS seconds (~30 fps) by the game-tick subscription that Game::subscriptions() declares — a periodic timer the Program owns, re-armed by the event loop itself (there is no fiber; sugar-core runs on a ReactPHP event loop).
SugarCraft\Flappy\Support
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 — the two-identity law 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. |
Configuration
Almost nothing is configurable, on purpose. The physics, tick rate, gap bands and key bindings are compiled in, because the leaderboard and the difficulty curve form one game, and knobs would let a session claim scores the defaults could not produce. What the environment controls is where the leaderboard lives and how color is drawn.
| Setting | Type | Default | Effect |
|---|---|---|---|
XDG_CONFIG_HOME | absolute path | unset | Config base for the score file. Falls back to HOME/.config. With neither set the game refuses to launch rather than guess. |
HOME | absolute path | system value | Used only when XDG_CONFIG_HOME is unset. |
NO_COLOR | any non-empty value | unset | Forces the ASCII posture. |
CLICOLOR_FORCE, FORCE_COLOR | any non-empty value except 0 or false | unset | Forces color on where detection would withhold it, and lets the bin draw into a pipe on purpose. |
TERM | terminal name | system value | dumb gets the plain refusal screen. |
The leaderboard lives at <config base>/.candy-flappy/scores.json. The directory is mode 0700 and the file is mode 0600. A write goes through sugar-core's AtomicJsonFile (flock plus temp-and-rename), never a bare truncating write.
Compiled-in limits
| Constant | Value | Meaning |
|---|---|---|
Game::WIDTH, Game::HEIGHT | 60, 18 | Playfield size in cells |
Game::MIN_COLS, Game::MIN_ROWS | 62, 21 | Smallest viewport that gets the board rather than the notice screen |
Game::PIPE_EVERY | 18 | Ticks between successive pipes |
PipeGenerator::GAP_DEFAULT, GAP_MIN | 6, 3 | Gap height at score 0, and the floor it shrinks to |
PipeGenerator::GAP_SHRINK_INTERVAL, GAP_SHRINK_STEP | 5, 1 | The gap loses one cell every five points |
Game::MAX_HIGH_SCORES | 10 | Entries kept on the board |
Game::MAX_SCORE_FILE_BYTES | 65536 | Larger score files are quarantined, not read |
Game::SCORE_CEILING | 100000 | Scores at or above this are refused on read and write, so 99999 is the highest score the board keeps |
Keys and input
| Input | Action |
|---|---|
| Space, Enter, ↑, w (either case) | Flap. The first flap also starts the run. |
| Mouse click or touch tap | Flap. The first click also starts the run. |
| r | Restart after a crash or mid-flight. A qualifying mid-flight score is settled first, and the run lands on the ready card. |
| q, Esc, Ctrl+C | Quit. A qualifying mid-flight score is saved before the process exits. |
Other Ctrl chords do nothing. On terminals without kitty-protocol reporting, Ctrl+M and Ctrl+J arrive as Enter and flap, and Ctrl+[ is byte-identical to Esc and quits.
Color and styling
Color follows sugar-core's ColorProfile::detect(). The game reads the profile the terminal reports through ColorProfileMsg. A NoTty profile gets the refusal screen and quits, and NO_COLOR selects the ASCII tier, which draws the same layout with plain glyphs. The game has no theme file, and the glyphs and colors are fixed by Renderer.
Examples
The examples/ directory holds one runnable program:
examples/play.phpruns the game straight from a checkout without thebin/wrapper. It accepts--versionand--help, refuses unknown arguments, and refuses a non-TTY stdout unlessFORCE_COLORorCLICOLOR_FORCEis set. It always exits 0 once the loop returns, settling the score on every path the bin does.
php examples/play.php # play, in a real terminal
php examples/play.php --help # usage, exit 0
The demo GIF below is recorded by the .vhs/play.tape script, which drives ./bin/candy-flappy itself and not the example.
Testing
The suite lives in tests/ and runs under PHPUnit 10. Run it from the package root with stdin redirected, so a stray read cannot hang the run:
cd candy-flappy && composer install && vendor/bin/phpunit < /dev/null
The tests drive the physics with tickN() and an injected PRNG, check the rendered frame with golden snapshots (GoldenRenderTest), and cover the binary's flags and preflight (BinFlagsTest, BinNoTtyPreflightTest). LocaleParityTest keeps every lang/ catalog in step with the default.
Troubleshooting
"needs an interactive terminal on stdout" and exit 1
Stdout is a pipe or a file. Run the game in a terminal window. To draw into a pipe on purpose, set FORCE_COLOR=1, which is the same escape hatch the bin honors.
A notice screen instead of the board
The viewport is smaller than 62 columns by 21 rows. Resize the window. The world stands still while the notice shows, and Game::subscriptions() returns null, so no ticks are spent.
The game refuses to launch
Neither XDG_CONFIG_HOME nor HOME is set, so there is no config base to write the leaderboard into. Export one, for example export XDG_CONFIG_HOME=$HOME/.config. The game refuses rather than guess a location.
The leaderboard is empty, or a file named scores.json.corrupt-<timestamp> appears
A corrupt, unreadable or oversized save was set aside, and play started with an empty board so a bad file cannot block launch. Inspect the quarantined file if you need the old scores. Entries that are not whole positive scores below SCORE_CEILING are dropped on read.
A score was not saved
A save that fails mid-run gives up silently. A failed end-of-run save prints one warning line to stderr. A score is written only when it earns a slot on the board, so a run that does not beat the lowest entry on a full board leaves the file alone.
Upstream mapping
| Upstream (Go or library) | candy-flappy (PHP) |
|---|---|
kbrgl/flapioca, the game loop and the bird and pipe rules | Game, Bird, Pipe, PipeGenerator |
| flapioca's draw pass | Renderer::render(), a one-pass canvas fill |
| Projectile motion (not in flapioca) | SugarSpring Projectile, used by Bird |
The tick rate differs from upstream on purpose. Flapioca slides at 5 cells per second; candy-flappy runs the same rule at 30 ticks per second, and the difficulty curve is tuned against that faster clock.
Architecture
Pure state, one frame per update
Game never mutates. Carry-through transitions (flaps, ticks, resizes, blur, settling) build a new instance through mutate(), so their field list lives in one place. start() and the two restart arms reset the board and call the constructor directly, so a new field must also be listed in those constructor calls; the restart arms pass the live viewport explicitly, so a restart cannot drop it. view() is a pure function of the state, so a test can compare two frames without a terminal.
Subscriptions drive the clock
The tick cadence is a subscription with a stable id, not a loop inside the Model. Program reconciles the subscription each cycle, which keeps exactly one tick chain alive across restarts and cancels it when the game stands down, so a dead bird or a frozen ready card burns no timer.
Persistence runs as a command
The leaderboard write is a Cmd that update() returns, so the synchronous reducer never touches the disk. The bin and the example also call settleOnExit() at the process boundary as a safety net for signal deaths.
Changelog and versioning
Tagged releases use the candy-flappy/ tag prefix, and the standalone phar is the release artifact. From a checkout, --version reports dev-master, and a phar reports the build stamp it was cut with.
Related
- SugarSpring: the
ProjectileandVectortypes the bird's motion is built on. - sugar-core: the Model, Msg, Cmd and Program runtime, plus
AtomicJsonFileandColorProfile.
Demos.
VHS-recorded by CI: the .vhs/play.tape script drives ./bin/candy-flappy itself, not the examples/ scripts, and the workflow re-renders the GIF on pushes that touch it.