Files
plan2code/.agents-docs/AGENTS-architecture-activities.md
T

53 KiB

Architecture: Activities (the games)

Part of AGENTS.md and the Architecture index: project guidance for AI coding agents.

One row per file of every game but Ghoul Rush (which has its own files: core, stages, rides), then the rules every game follows.

File Role
public/activities.js the list of activities (ACTIVITIES: each game's id, title, picker card line blurb and module path) an optional courses list (Mini golf's six course ids, which open a course dashboard), bestKey(id, course?), the flat looks.json key for its best score (activityBestSnake, one per golf course activityBestGolfPirate to activityBestGolfFrost, activityBestTrails, activityBestBugs, activityBestDrive, activityBestStack, activityBestBumper, activityBestRapids, activityBestFuse, activityBestHop, activityBestBounce, activityBestGhoul, activityBestFlock); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, bestKeys(entry), every best key a game keeps, and documents the game contract including the course parts (courses and preview() on the export, setCourse() and course on the game), the optional pointer(type, x, y), release(name) (a game key let go) and lowerIsBetter; data only, imported by the page and by Node
public/activities/snake.js Snake: its rules as plain exported functions and the game contract (create({ canvas, tone, onScore }) returning start, pause, resume, key, tick, resize, score, state); it never runs a timer or listens for keys, so the Activities window drives it; it also holds the music's rules: MUSIC_TRACKS, dealMusic(random, last) (a round's shuffle of the ten tracks, never opening on the last round's opener), trackFor(deck, level) and heat(round) (the snake's speed as 0.3 to 1, so the lead and drums are in from the first step)
public/activities/trails.js Light Trails: its rules as plain exported functions (newRound, newHeat, turn, boost, advance in 8 ms slices (where your crash is held for GRACE_MS, a turn in that time riding out of it; rivals get no grace), choose and room for the rivals' flood-fill steering, applyPower (a Mystery becoming another pad), pickPower (by each pad's from arena, a Heart only under MAX_LIVES), fireLaser, hyperjump, awardLives (a life every LIFE_SCORE points, the mark moving on at the cap), spawnItem, closeRing), the ARENAS (rivals, sharpness and what each adds), the POWERS pads (Boost, Phase, Eraser, Slow-mo, Coin, Heart, Shield held across heats until a crash in your grace pops it, Laser with LASER_SHOTS, Score x2 through one gain() every score goes through, Wide Trail with its side cells in rider.wide, Coin Rain whose rain coins never hold back a pad, Hyperjump, Mystery) and the game contract; START_LIVES is 5; memo is the furthest arena reached; a read-only round getter for the tests only; it also holds the music's rules: MUSIC_TRACKS (its five songs) and dealMusic(random, last) (a shuffle of them, never opening on last); a run plays the deal one song after another, each in full from the top (asking with { restart: true } until the music takes it), moves on when music() answers "ended", deals again after the last, and a new run deals afresh, never opening on the song the last run was playing; its tones and hums play SFX_LOUDER times as loud through tones.js's louder, all but the engine drones (DRONES), kept low under the songs
public/activities/bugs.js Bug Hunt: its rules as plain exported functions (newRound, spawnWave, slotPos, advance in 8 ms slices over round.input, which key() and release() set, hurtBug, hurtBoss, hitShip, applyPower, ghostly, tentacleTip, bossRadius), the BUGS by first wave, the BOSSES every BOSS_EVERY waves, the POWERS, the SECTORS scenery and the game contract with release(); memo is the tally of DISCOVERIES as bits; a read-only round getter for the tests only
public/activities/drive.js Sunset Drive: its rules as plain exported functions (newRound, buildStage, which appends a stage of road and returns its forkAt, gateAt and fork, segAt, advance in 8 ms slices over round.input, which key() and release() set, boost, usePower (the oldest queued power-up, which space fires ahead of boost), hopHeight, checkTime), the POWERS in POWER_ORDER, the REGIONS (roads with their bonus, bends, hills, traffic, colors and props) in REGION_ORDER, the projection and drawing (sky, road far to near, props, traffic, Planny's car) and the game contract with release(); the next road is built only when the fork is chosen, and FORK_LEN must stay at least DRAW so it is built before it comes into view; memo is the roads found as bits; a read-only round getter for the tests only
public/activities/stack.js Stack Deploy: its rules as plain exported functions (newRound, spawnBlock, advance in 8 ms slices that slides the block between the walls, drop, which drops it where it was last drawn and returns { kept, sliced, perfect, miss }, isPerfect and zoneOf (3% of the block's width, the slide in PERFECT_MS, or round.minZone, the MIN_ZONE_PX floor the game sets at each resize, whichever is most, but never more than half the block's width, so a drop off the tower is never perfect), grow, speedAt, twistsAt, styleAt, comboPitch), the TWISTS by floor (speed ramp, either side and turning back, lag spikes, wind, rush hour, faster) and the STYLES of the tower, the drawing (sky by height, blocks per style, Planny riding the top, the dashed marker of the highest floor) and the game contract with pointer() (a press on the board drops) and release() (a held up drops once, not at every key repeat, and key(name, repeat) ignores a repeat the window marks, so up held through the countdown never drops at its first repeat); a press waits for the first tick after a start or a play-on, so an arrow that resumes never also drops; a miss holds the round running for OUTRO_MS while the camera pulls back over the whole tower; memo is the highest floor ever reached, saved on a pause and at the end; a read-only round getter for the tests only
public/activities/bumper.js Bumper Ring: its rules and physics as plain exported functions (newRound, newHeat, advance on a fixed 4 ms sub-step over round.input, which key() and release() set, push (accel toward the held direction, capped at the top speed that way, drag easing a car to the floor's own speed), collide (circle bounce with restitution BOUNCE; the faster car rams and gives SHOVE_BONUS more, takes that much less back; under IMPACT_SPEED it is a lean, no bounce and no shove, so a pushing match goes to the stronger push), dash, edgeGap and outOfRing (a car is out when its center is past the edge or over an open hole; round or, in the Hall of Mirrors, square), shrinkAt and nextShrinkIn (whole for SHRINK_START_MS, SHRINK_STEP a step to MIN_RING, then after SUDDEN_MS sudden death to LAST_RING, under one car's radius, so every heat ends), aim (a rival's push, dash and target per personality, with panic near the edge and a sharpness-scaled chance to misjudge), applyPower, spawnPad, creditKo (the last toucher within CREDIT_MS, your hit carried through a rival counting as yours, and a rival you rammed into another keeping your credit, the carry lasting CAROM_MS from your hit; the combo, the double and the bait bonus), rivalPower and arenaFor (each built once per arena, since the rules ask every slice), holeState), the ARENAS (rivals, sharpness, shrink pace, then endless Finals past the ninth), the RIVALS personalities and the POWERS pads, and the game contract with release(); a rival winds a dash up for WINDUP_MS (shorter when sharper) before it goes, which is the player's moment to step aside; a big hit holds the action for HIT_STOP_MS; memo is the furthest arena reached, which can pass 9; a read-only round getter for the tests only. Hand-tuned from the brief's starting numbers (the changes are listed under "As built" in game-ideas/bumper-ring.md), aiming for heats of 20 to 60 s from arena 2 on
public/activities/bumper-draw.js Bumper Ring's drawing: drawScene(ctx, view) from a plain view bumper.js builds (the round, the board geometry, the effects, the pill numbers), each arena's ring in its fixed palette (themeFor), the floor (ice, oil, holes, bumpers, the magnet, the warning bands), the cars (Planny upright at the wheel of a car in --accent, star eye and stick arms; rivals with a face each), the pills (laid out by hudLayout, which starts a row below rather than run into the ring's countdown or off the board), banners and the start and end strip, and readColors(canvas); decides nothing
public/activities/rapids.js Rapids Run: its rules as plain exported functions over a round on a river scrolling down a 64 unit wide field, 84 units of it on the board (newRound(seed), newRiver(seed), buildStretch(river, n, random) (a stretch's rows from its own seed, each row a center, width and island width: a calm opening, then drifts, narrows and islands, every bank slanting at most SLOPE a unit, every channel at least MIN_CHANNEL wide, then a BASIN_W basin on a boss stretch and the narrowing to the DAM_W dam; and its plan of foes, buoys and crates, none in the first SAFE_START (where you start again) or by the dam), ensureRiver, riverAt (a row's banks and island eased from the row before's, so they slant as drawn), channelsAt, channelAt, isWater, onLand (the hull sampled at seven points), placeAt (the start of a stretch, its dam whole and its plan loaded afresh), advance in 4 ms slices over round.input, which key() and release() set: steering eased in, the whirlpools' tug, the speed held (up, down or neither, times the stretch's pace), the battery drained (DRAIN a second cruising, more at speed), distance points, the guns (FIRE_MS, Spread's fan), shots against foes, the boss, the dam and buoys, the foes (skiffs and darters drift and turn at the banks, a darter swerves into your lane, gulls take off as you near and swoop across, sentries fire at you), the boss (spawnBoss holds the river and the battery; its volleys by kind), bolts, pickups (a buoy BUOY_CHARGE, the magnet's pull, crates), crashes (lose: a shield takes any crash but a flat battery and slides you off a bank; blinking for GRACE_MS after a restart), skims (SKIM_POINTS each SKIM_MS closer than SKIM_GAP at speed), the dam (hitDam, then past it the next stretch, with FLAWLESS_POINTS times it for no life lost), hurtFoe (the combo, up to MAX_COMBO), hurtBoss (a life back and a crate), applyPower, stretchFor (built once a stretch; past the eighth, Night Water 2, 3 and on), underBanner, screenY, seeded), the FOES, BOSSES, POWERS and STRETCHES, and the game contract with release() (held arrows steer, speed and slow, held space fires; a pause lets go of every key); memo is the furthest dam blasted, which can pass 8; a read-only round getter for the tests only. Tuned by a scratch sim: a careful bot clears a stretch in 20 to 35 seconds, and the battery runs flat for one that grabs too few buoys
public/activities/rapids-draw.js Rapids Run's drawing: drawScene(ctx, view) from one view object rapids.js refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by hudLayout, which starts a second row rather than run off the board and centers its rows in the strip), the river a look at a time (LOOKS: meadow, autumn, canyon, marsh, dusk and night, each in fixed colors, the look changing at each dam): banded banks, the water between them with shore lines and flow streaks carried downstream by the view's clock, pointed islands, trees or rocks; the dam ahead (hazard stripes, a crack for every share knocked out, a trickle once it is close to going) and the broken one behind; charge buoys, crates with their glyphs, whirlpools, skiffs, darters, mines, bank sentries aiming at you and gull drones with their shadows; the mini-boss and its health bar; Planny's jet-skimmer in your highlight with a white trim (so a blue highlight still shows on blue water), his wake, jets, arms to the bars (up when a dam or a boss goes), his box and his star eye in your highlight, bobbing with the star spinning after a crash; shots, bolts, sparks, rings, floating words (kept on the field by labelSpot), the combo's big number, the battery gauge beside the field (green, amber, then red and blinking under the low mark), banners, and the start and end strip with the big final score and a dot per named stretch whose dam you have blasted; readColors(canvas), lookColor, inkOn, contrast; decides nothing
public/activities/flock.js Flock Dash: its rules as plain exported functions over a round scrolling right to left over a 96 by 54 unit field (newRound(seed), steer (the leader eased up and down inside the BAND_MIN to BAND_MAX band at the left), recordPath, placeFlock, screenX, collect and spawnStrays (a stray joins the flock, the combo up to MAX_COMBO within COMBO_MS), buildStage(seed, n) (a stage's hazards by distance from its own seed, a clear SAFE_START and SAFE_END, and clearGap keeping a way through), moveHazards, hazardHits, snapAt (a snap drops the birds behind the one hit, scattered for SCATTER_MS so they can be picked up again), hitLeader (a life, or a shield; GRACE_MS after), reachPortal (the jet stream portal, the V of V_POINTS a bird when the flock has min, FLAWLESS_POINTS for no snap or life lost, and the final portal that sways), applyPower (crates: tailwind, shield up to MAX_SHIELDS, magnet), banner, bannerRow, underBanner, advance in SLICE_MS slices, teaser, seeded, dealMusic), the STAGES table (eight stages, each with its speed, length, stray gap, portal min, hazard weights and gap; the place to tune the difficulty), the HAZARDS (balloon, gust, stream, cluster, storm, kite, each from its own stage) and POWERS, and the game contract with release() (held arrows steer, a pause lets go of every key); the round also carries events (what the draw and the sounds react to) and warned (one gust or storm warning each); memo is the furthest stage reached. The flock is a recorded path with running arc length: follower k sits k * SPACING behind the leader along it, so it copies every turn at any speed. MUSIC_TRACKS names the five songs, dealt afresh each round
public/activities/flock-draw.js Flock Dash's drawing: drawScene(ctx, view) and hudLayout from one view object flock.js refills each frame, in field units: the sunset sky (SKIES, one palette per stage: the sun sinking, clouds, a rim light from stage 6 and stars on the last), the hazards (balloons and bunches, the head-wind's warning band and gust, slipstreams, thunderheads with their flash and bolt, kites on their strings), the strays and scattered birds, the flock, Planny as the lead bird with a star for an eye, crates and the magnet ring, the tailwind streaks, the portal and the V, the pills (laid out by hudLayout, which shrinks them to fit the board), banners, and the end strip with the final score, the best and the teaser; readColors(canvas); decides nothing
public/activities/fuse.js Hot Potato: its rules as plain exported functions over a round on a 104 by 70 arena (newRound, newMatch(round, venue), which lights each bomb on a rival, never you, in a match's first fuse, advance in 8 ms slices over round.input, which key() and release() set, move (speed eased toward the held direction at GRIP, a dash holding its line, belts and ice from the floor), dash (a holder's dash is a numbered lunge), tag (a holder touching a runner with no bomb passes it, never inside NO_TAGBACK_MS of the bomb changing hands, nor back to the one who just passed it within TAGBACK_MS while three or more are left, tagBack, with tagSafe saying who is safe that way for the drawing; a fuse under PASS_FLOOR_MS, NO_TAGBACK_MS plus PASS_REACT_MS, is raised to it on any pass, once a fuse for each runner (bomb.lifted); your pass scores, a hot one under HOT_MS as passed steps the streak), burn (Freeze takes its share first), blast (the holder out, everyone near knocked back, the match over when that was you or one is left), nextFuse (a survivor with no bomb, the next shorter fuse from fuseFor, never more bombs than one for every two left), think (a holder chases by its own flood-fill path, weighted toward a boxed-in or dashless target; a runner without a bomb scores candidate spots by the holders' path distance against its own and flees to the best; personalities bend both), applyPower, spawnPickup, speedOf, clearLine, rivalPower and venueFor (each built once per venue), rivalColors(you)), the VENUES, LAYOUTS, RIVALS and POWERS, and the game contract with release() (key(name, repeat) never dashes on a repeat); a rival holder winds up (WINDUP_MS, shorter when sharp) or, a Trickster, feints (FAKE_MS) before a lunge, and a runner a lunge comes at dodges once a lunge at its venue's odds after its reaction time; the fuse ticks quicker and higher as it burns down, on one clock however many bombs burn (yours, else the shortest); a bomb whose fuse has run out passes to nobody; memo is the furthest venue reached, which can pass 9; a read-only round getter for the tests only. Tuned by a scratch sim (see "As built" in game-ideas/hot-potato.md)
public/activities/fuse-draw.js Hot Potato's drawing: drawScene(ctx, view) from one view object fuse.js refills each frame, in arena units: the strip above the arena in the page's colors with the pills (laid out by hudLayout, which starts a second row rather than run into the fuse and centers its rows in the strip), each venue's floor in its fixed palette (themeFor, venueColor), ice, running belts, the Rooftop's open edge, the things to run round, pickups, the runners (Planny on his feet with his star eye and stick arms, flailing while he holds a bomb, and still Planny when charred; arms and feet on the floor in limbInk(level), the ink that stands out from that venue's tiles; rivals with a mark per personality; a white ring with a dark edge at the feet of a runner safe from a tag-back; the charred waddle to the nearest wall and the fall from the roof), the bomb over its holder (a red ball with a <<< band, growing and glowing as it burns, flashing white while it cannot be passed, its fuse a shortening curl with a spark, the last seconds in big numbers (under the holder's feet when there is no room above, countY), a hop across on a pass), blast clouds, the Blackout's dark worked out once a frame in cells, the red edge pulse in a fuse's last second, banners and the start and end strip with the big final score, and readColors(canvas); decides nothing
public/activities/hop.js Crossing Rush: its rules as plain exported functions over a round on a strip COLS (11) cells wide of 30 to 40 lanes, VIEW_ROWS (14) on the board at once (newRound, newHeat(round, zone), which builds the heat's lanes from the round's seed, kept when a heat runs again, buildLanes(zone, seed) (groups of road, highway, ice, river, turtle, rapids or rail lanes with a grass row between each two, the zone's new thing first; the same seed builds the same lanes), advance in 8 ms slices (lanes flow, riders drift with their log, rivals choose, everyone is checked where they stand before any hop moves on, then hops and flights; hoppers home in the same slice finish by the moment each landed, a dead heat to you), hop(round, hopper, dir) (one cell, two with a Spring; a hopper counts in the cell it leaves for the first half and the one it lands on for the second; an icy lane slides it a cell more), laneAt, occupied(round, row, col, atMs) (a car or a train on it, or in a river no float or the edge, atMs ahead through shiftAt, which follows a lane's flips, surges and a Horn exactly), sendBack (to the last grass row, safeBelow, crediting a shove within SHOVE_CREDIT_MS), shove(round, from, to) (a cell the way from faces, only on a hopper inReach and never on one past the half of its hop home, once every SHOVE_MS), plan(round, hopper, random, power) (a look ahead of LOOKAHEAD to LOOKAHEAD_SHARP hops over the lanes as they will move, each hop followed by the hopper's wait where it lands; never a hop where it would be hit or fall in at full sharpness; a sloppy rival now and then hops on regardless), applyPower, zoneFor and rivalPower (each built once per zone), rivalColors(you), standings), the ZONES, RIVALS and POWERS, and the game contract with release() (key(name, repeat) hops once a press: never on a repeat, never again until the arrow is let go, never with the press that plays on, and with one hop queued behind the one in the air; a pause drops what is held and the queue); rivals wait REACT_MS down to a sharp rival's after each landing, a Bruiser shoves anyone beside it into a lane, a Tagalong follows a row behind you and shoves near the top, and a rival that lets a shove go weighs the next one only after SHOVE_LOOK_MS; memo is the furthest zone reached, which can pass 9; a read-only round getter for the tests only. Tuned by a scratch sim (see "As built" in game-ideas/crossing-rush.md)
public/activities/hop-draw.js Crossing Rush's drawing: drawScene(ctx, view) from one view object hop.js refills each frame, in board units: the strip above the field in the page's colors with the pills (laid out by hudLayout, which starts a second row rather than run into your place and centers its rows in the strip), the lanes in fixed colors (LANES, lookOf; pavement, grass with tufts, bushes and rocks, the checkered finish, roads with dashes and surge chevrons, icy roads, rivers with ripples and Rapids arrows, tracks with a signal that flashes while a train is coming), cars, vans, trucks, logs, turtles that sink and dive, the train, pickups, the hoppers (Planny on his stick feet with his star eye in every state: stretching mid-hop, spinning as he flies back, cheering, slumped when beaten; rival critters with a Hopper's ears, a Daredevil's goggles, a Bruiser's brow and a Tagalong's beak; arms and feet, and each rival's body edge, in limbInk(look), the ink that stands out from that lane), a Shield's ring and a Spring's coil, staggered stars, arrows at the edge for hoppers out of view, the Night Market's dark (soft lights cut from a layer the size of the field with one gradient made with the layer, or in steps with no second canvas), the race bar in the page's colors, banners, and the start and end strip with the big final score; every word kept on the field by labelSpot, and readColors(canvas), zoneColor; decides nothing
public/activities/bounce.js Bounce Road: the cars, the hazards against them, the scoring and the round, as plain exported functions over a round on a road scrolling up a 72 unit wide field, 90 units of it on the board (it re-exports every rule of bounce-road.js and bounce-rivals.js, so the suite imports one module): newRound(seed, random), advance in 4 ms slices over round.input, which key() and release() set (a jump press first, then your move, the rivals' think and move, the pads (a boost strip pushes you to NITRO_TOP for BOOST_MS even off the throttle, and the brake cuts it; a ramp launches any car crossing its lip quick enough RAMP_AIR the usual jump; a slick eases the steering at SLICK_EASE and makes a knock last for SLICK_MS), the bumps (collide: boxes pushed apart along the shallower overlap, side on a knock split by mass and harder for the car that did not steer in, end on speed passed forward, into a HEAVY truck's back at CRASH_CLOSE a crash; with Mega wheels a touch flattens; a close shave, NEAR_GAP or less between the boxes at speed and no touch, scores once), the barriers (a cone or a tire knocked flying slows you to CONE_SLOW; a block, pot or bucket nose first is a crash, from the side a push out), the hazards placed by the round's clock (a train hits a car on its track, a ball knocks a car by BALL_KICK, a sprinkler's jet pushes at SPRAY_PUSH, a drop falls DROP_FALL_MS after you come within DROP_TRIGGER, aimed at your line, and lies there after, a gust pushes at WIND_PUSH), then the ground (water or a hole under your middle a life, a flowerbed nose first a crash, a rival off the road out and yours within CREDIT_MS)), jump, land (on a car: flattened for its points times the chain up to MAX_CHAIN, a truck's roof HAUL_POINTS, the Monster a stomp, STOMP_POINTS, and on its last of BOSS_HP BOSS_POINTS times the lap and a life; on the road the chain ends, and the holes, trains, balls and barriers flown over and a ramp's big air score), stunt (a stunt's points times comboOf(streak): every COMBO_STEP stunts within STREAK_MS of each other one more, up to MAX_COMBO), lose (a Bubble throws you clear instead), applyPower, underBanner(round, y, cam) (a rival, a coming train, a ball or a thing still falling in the strip) and BANNER_Y, rivalColors(you)), the POWERS (Spring, Bubble, Nitro, Mega wheels) and the game contract with release() (key(name, repeat): held arrows drive and steer, space jumps once a press, never on a repeat or with the press that plays on, and a press up to JUMP_BUFFER_MS before a landing jumps on it; a pause lets go of every key and drops a press). A stage line scores STAGE_POINTS times the stage, TIME_POINTS a second under its par and, flawless, FLAWLESS_POINTS and a life back up to MAX_LIVES. Memo is the furthest stage reached, which can pass 10. A read-only round getter is for the tests only. Tuned by scratch bots: a careful bot clears all ten stages with no rivals on every seed tried (23 to 42 s a stage), and a bot with 150 ms reactions and 80 ms jump timing error reaches a median of stage 5 with the rivals out, stage 10 without
public/activities/bounce-draw.js Bounce Road's drawing: drawScene(ctx, view) from one view object bounce.js refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by hudLayout: stage, lives, Spring, Bubble, Nitro and Mega with their timers, the chain and the combo with its timer; a pill that would run off the board starts a second row), the road a chunk of CHUNK_ROWS rows at a time, drawn off screen once per road and scale, a few kept and copied each frame (rows from bounce-scenery.js), the layers over it (bounce-scenery.js), the landing rings (yours in your highlight, a rival's in red, the Monster's its own size), the cars through bounce-cars.js (every shadow first, upright, then every body with its tumble: Planny in your highlight with his box in the page's panel color and his star eye, arms to the wheel, up in the air or cheering, down at the end; each rival kind in its own style and color, the Cop's siren while it chases, the Monster's dents and a star per life left above it, headlights at Night Lights), sparks, rings, the dark of Night Lights, the chain's big number, the stage bar beside the field, banners, and the start and end strip with the big final score and a dot per stage reached; every word kept on the field by labelSpot, and readColors(canvas), limbInk, inkOn; decides nothing
public/activities/bounce-cars.js Bounce Road's cars, drawing only and no imports: drawCarBody(ctx, style, opts) draws one top-down toy car about the origin, nose up, filling w by h field units exactly (tires on the box's corners), in one of CAR_STYLES (STYLE_NAMES: Planny's convertible with his star eye and arms to the wheel, hatch, sedan, coupe, muscle, pickup, van, box truck, police, racer, taxi, jeep, monster) with flat-fill shading worked out from color and accent (shade, rgbOf), and options for roll (tilt), a jump (air: it draws the shadow and the lift itself), a pancake (squash), night beams, a siren bar, damage, a boost flame and brake lights, all moving parts on opts.clock; drawCarShadow and shadow: false for a shadows-first pass in screen space; carLength(style, w) for a style's natural length and carReach(style, opts) (with MARGINS) for what reaches outside the box
public/activities/bounce-scenery.js Bounce Road's scenery, drawing only: each stage's look in fixed colors (LOOKS: patio slabs, lawn stripes, kitchen tiles, garden, sand, a toy room's rug, a pond with lily pads, roof shingles, the night lawn with lamps and the Monster's dirt; lookOf, stageColor, contrast, better), drawRow (one row of the road in three passes over a chunk: the yard, the road's surface, the details: edges slanting from row to row, rivers, plank bridges with jagged broken ends, cracks, flowerbeds, rails across a crossing, cracked road over a pit, checkered stage lines, verge decor), and the layers drawn fresh each frame from the round's clock: drawTimed (a drawbridge lifting with its red lights, a swaying bridge where it is now, crumbled road gone to the pit), drawPads (running boost chevrons, ramps, slicks), drawBlocks (cones, toy blocks, pots, buckets, acorns and tires, knocked ones tumbling off), drawStars, drawSigns (a mark per hazard), drawItems, drawHazardsLow (crossing lights, the train, a rolling ball, a falling thing's growing shadow, a sprinkler's head), drawHazardsHigh (the jet, gust streaks, the thing still falling), drawNight and drawFireflies; decides nothing
public/activities/bounce-road.js Bounce Road's road, rules only: the jump math every hole is sized by (airMs(v), reach(v), LONGEST_JUMP, JUMP_FAIR, TOP_SPEED, MAX_SPEED), stageFor(n) (built once a stage: the ten of bounce-roads.js, then laps from LAP_FROM, quicker, keener, busier, the Monster at every Monster Mash) and stageName, newRoad(seed) and buildStage(road, n, random) (a stage's rows from its own seed, by the stage's piece weights: straights, cracks, rivers on bridges with one or two broken spans or a drawbridge, splits round flowerbeds, ramps before a crack with stars beyond, cone or block chicanes, crumbling road, train crossings, swaying bridges, boost strips, slicks, balls, sprinklers, drops and gusts; every hole after a RUNUP with a sign and no longer than MAX_HOLE, the bridge between two breaks long enough to land LONGEST_JUMP on), ensureRoad, groundAt(road, x, d, t) (a row's edges eased from the row before's; a drawbridge water while lifted, a swaying bridge shifted, crumbled road a hole), rowGone, spanAt, holesIn, firstAt, plainRow, safeSpot (no hole, water, timed part or rails for RESPAWN_RUN ahead), and where each timed thing is at a moment: swayOff, drawLift, crumbleAt (falling away CRUMBLE_DELAY after you reach it, at CRUMBLE_SPEED, under a fair speed), trainAt (on, and lit TRAIN_WARN_MS before), ballX, sprayAt, gustAt; plus seeded, GROUND, MARK, SPAN
public/activities/bounce-rivals.js Bounce Road's rivals, rules only: RIVALS (the Zigzag, Brick, Frog, Nudge, Hauler, Sneak, Bruiser, Racer, Cop and Monster: box, mass, speed, points, how readily each dodges, how often each comes, its car style and whether it comes from behind), makeCar, think(round, car, ms, random) (each kind's choice of speed and line: the Zigzag's weave, into your path when you follow; the Brick holding your lane and brake-checking from in front, then resting BRAKE_REST_MS or more; the Frog's hops toward you; the Nudge's chase and up to 1 + 2 times the stage's sharp swipes; the Hauler drifting to block; the Sneak dropping up to SNEAK_DROPS cones while you follow; the Bruiser slamming you within BRUISER_RANGE; the Racer passing then fleeing; the Cop sitting on your roomier side and leaning in to push you to the near edge for COP_MS, never on a bridge or by the water (nearWater), nor the Bruiser; the Monster keeping BOSS_AHEAD in front, hopping every BOSS_HOP_MS to come down where you will be and dropping tires; every rival rubber-banded to stay near you, swerving from under your landing as sharply as its stage allows, keeping to the narrowest road just ahead and the band a swaying bridge always covers, holding a slower car's speed, and hopping any hole, drawbridge, barrier or coming train, or flying off a ramp), spawnRival, pickKind (one of each special kind at a time), HEAVY, RIVAL_MIN_SPEED
public/activities/bounce-roads.js Bounce Road's ten stages as data (no imports): FIELD_W, FIELD_H, ROW, MAX_HOLE, LAP_FROM, and per stage its length, par time, road widths, piece weights (straights, holes, rivers, splits, ramps, chicanes, crumbling road, trains, swaying bridges, boost strips, slicks, balls, sprinklers, drops, gusts), crack and broken span lengths, bridge widths and shares of broken, double and drawbridge spans, flowerbed sizes, barrier and drop kinds, the rivals' count, kinds, pace and sharpness, power-ups, stars, and whether the Monster comes
public/activities/pills.js The pills every game but Mini golf draws along its top (no imports): drawPill(ctx, x, y, w, h, text, color, fill, textY) on one opaque dark backing, PILL, the same in light and dark and over any scene, a timer's share still left tinted at PILL_TINT, and the text in pillInk(color, tinted): the pill's own color when it reads at PILL_CONTRAST (4.5:1) on the backing (and on the tint while a timer runs), else the least step toward white that does, so warnings stay red; lives are the one solid pill: a pill in the LIVES color is drawn on LIVES_BACK in white (LIVES_INK), its text from livesText(n) (a heart per life up to five, ♥ xN past that, ♡ at none); pillTint and pillContrast for the unit suite
public/activities/golf.js Mini golf: six eighteen-hole courses, one round at a time; its rules and physics as plain exported functions (newRound(courseId), holesOf, coursePar, strike, advance on a fixed 4 ms sub-step, nextHole, total, toPar, predictPath for the spyglass, moverAt, gateShut, plus ice that barely slows the ball and wells that pull it in or push it away), the POWERUPS held for the next putt (round.held, then round.active for that putt), the arcade swing (startSwing, setPower, meterAt, meterZone, swingShot: a ping-pong power meter, slow at the bottom and fast at the top, with a MAX band that boosts and an overswing band that shanks; a shot clock in advance() that starts the meter after SHOT_CLOCK_MS and dribbles the ball after METER_TRIPS trips; all on the round's own clock), the pop-up gags, and the game contract with pointer() (the aim follows the pointer, a press swings, a press held on a roll fast-forwards), release() (held arrows turn the aim, held space fast-forwards) and lowerIsBetter, courses (the dashboard's cards), preview(canvas, id, w, h) (a course's card art) and setCourse(id); deterministic (no Math.random()), a read-only round getter for the unit suite only
public/activities/golf-draw.js Mini golf's drawing: drawCourse(ctx, view) from a plain view golf.js builds, each hole in its theme's fixed palette (pirate, cave with its darkness and glows, or a newer course's look from golf-looks.js, asked first for its grounds, water, tunnels, gates and wells), ice, the scorecard and banners in the course's voice, a bare view for the dashboard's card art, knownGround/knownLiquid for the unit suite, and readColors(canvas), which reads the --golf-* properties styles/activities.css mixes from the tokens for the ball, pills and scorecard; decides nothing
public/activities/golf-decor.js Mini golf's scenery and props for Pirate Cove and the Caves of Doom: each decor kind (sharks, ships, parrots, bats, torches, eyes, a dragon) on its layer, the looks of bumpers, movers and spinners, and the power-up icons, each asking the hole's course look first (decorKinds(theme) lists a theme's scenery); drawing only, moving with the round's clock
public/activities/golf-holes.js Mini golf's courses: COURSES, the six eighteen-hole courses in dashboard order (Pirate Cove, Caves of Doom, Dino Valley, Candy Carnival, Cosmic Glow, Frosty Peaks), courseById, HOLE_COUNT, FRONT_NINE, COURSE_W, COURSE_H
public/activities/golf-kit.js Mini golf's course kit, data only: COURSE_W, COURSE_H, the helpers course files build holes with (pt, rect, wall, bump, pad, deco), hole(def, defaults) (what a hole holds: theme, quip, ground, liquid, tee, cup, outline, walls, bumpers, sand, ice, water, slopes, wells, bridges, spinners, tunnels, movers, gates, powerups, decor) and course(), which freezes a course with its name, card line, cover hole and voice
public/activities/golf-course-pirate.js Mini golf's Pirate Cove course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-cave.js Mini golf's the Caves of Doom course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-dino.js Mini golf's Dino Valley course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-candy.js Mini golf's Candy Carnival course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-space.js Mini golf's Cosmic Glow course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-course-frost.js Mini golf's Frosty Peaks course: its eighteen holes and its voice (the hole label, splash, bump and ace words, the turn and end lines and the scorecard quips); data only
public/activities/golf-looks.js Mini golf's course looks by theme id, and the look contract (palette, liquids, grounds, rough, tunnel, lights, and the looks of bumpers, movers, spinners, gates, wells and scenery)
public/activities/golf-look-dino.js How Dino Valley is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock
public/activities/golf-look-candy.js How Candy Carnival is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock
public/activities/golf-look-space.js How Cosmic Glow is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock
public/activities/golf-look-frost.js How Frosty Peaks is drawn: its palette, ground, water, props and scenery; drawing only, moving with the round's clock
public/activities/golf-paint.js Mini golf's shared canvas helpers (polygon, circle, ellipse, radial, fill, stroke, line, label, turned, t, scatter, bounds), no imports, so the drawing files and the looks share them without import loops
public/tones.js the activities' sound engine, all synthesized in the browser. Three parts: a shared kit of rich one-shot sounds (RICH: layers of parts played together, each a wave or a noise (noise, pink, brown) with its own delay, gain, attack, a sweeping filter and vibrato: explode, smash, skid, whoosh, splashBig, fanfare, gameOver and some fifty more, up to 1.2 s, at most MAX_VOICES parts sounding at once), held hums (hum(id, name, level, pitch), called every frame a game wants it: oscillators and noise through one filter that follows the pitch, pulsed for an engine's strokes; a hum not asked for within HUM_HOLD_MS fades by itself, so a paused or closed game goes quiet without saying so, hushTones() quiets every one and the Activities window calls it whenever it stops ticking; at most MAX_HUMS; shared ones car, toycar, electric, outboard, river, wind, cycle, fuse, haunt, squeal, meter, swarm, train, crowd), and each game's own extras in public/activities/<id>-sfx.js ({ tones, hums }, plain objects, names prefixed with the game id, merged and frozen here; a name may be defined once across all of them, which scripts/test-web-console-tones.mjs checks along with every spec's shape and every name a game's source asks for). Everything plays through one compressor. The older single blips (BLIPS): tone(name, level, pitch) with an optional loudness from 0 to 1 and an optional pitch that scales every frequency, kept between 0.25 and 4, and an optional fourth louder (a game lifting its sounds as a whole, up to LOUDER_MAX, also the fifth argument of hum()), unlockTones(); Snake's blips plus golf's putt, wall, bump, cup, ace (a three-note rise), splash, power (a power-up, three notes), tunnel, boom (a cannon putt), sizzle (lava) and fall (the pit), the countdown's count and go, Stack Deploy's thunk, slice and perfect, which it pitches up a scale step for each perfect in a row, and Bumper Ring's ram, pitched and leveled by how hard the hit, and rev, a rival winding up a dash, and Hot Potato's tick, the fuse, which it ticks quicker and pitches higher as the fuse burns down, and pop, a pass, and Crossing Rush's hop, which it pitches up a step for each quick hop forward in a row, boing, a send-back, bell, a train coming, and horn, and Bounce Road's engine, a soft low triangle hum it plays every few frames while you pick up speed (quiet once you cruise or coast), pitched up with your speed, spring, a jump, pitched with your speed, and squash, a rival flattened, pitched up a step for each in a chain, and beat, a low thump while your wheels run on the verge (it borrows the other games' blips for its hazards and rivals), and Rapids Run's pew (a shot, a short soft triangle played quietly about seven times a second while fire is held), charge (a buoy taken), lowcell (the low battery's two-note beep, quicker the lower it runs), dambreak (a dam bursting) and skim (a bank skimmed at speed, pitched up the more you have skimmed), and Ghoul Rush's ghoulBlast (the blaster's bolt, a short soft triangle repeated while fire is held), zombiePop (a kill, pitched up a step for each in the chain), ghoulStomp, ghoulBoo, ghoulRoar and zombieGroan (now kept for the other games and the tests: Ghoul Rush's monsters speak with their own voices from ghoul-sfx.js), ghoulCandy (pitched up for candy in quick succession), batSwoop (a bat's kill), doorUnlock (the key), doorThrough (the door to the next room) and creakBoard (a crawler coming up, a chandelier or a crumbling board about to go), all soft triangles and sines), silent while Play sounds is off; separate from sound.js's cue queue
public/music.js the games' chiptune music: a small sequencer over tones.js's context and compressor (audioOut()). A game calls music(name, intensity) from its tick; the track fades out within MUSIC_HOLD_MS once it stops being asked for, picks up again on the bar it left, asking for a different track crossfades the two over CROSSFADE_S (the old one keeps playing as it fades, so a new level is not a cut), and hushMusic() stops it at once. Tracks are note data under music in each game's activities/<id>-sfx.js ({ bpm, rush, bar, voices, patterns, order }, bar the steps in a bar when it is not 16, so the track resumes on a bar start and each pattern is whole bars: pulse, triangle and noise-drum voices, each joining once the intensity reaches its from; a step a token, A4, - to hold, . a rest, A3^037 an arpeggio, drums k s h o), read by compileTrack() and booked LOOKAHEAD_S ahead on the audio clock. It also plays recorded songs: mp3s a game names under songs in its sfx file (a name to a served path, merged by tones.js as SONG_TABLES, listed by songNames()), asked for the same way, one <audio> element each made on first use, at SONG_PEAK times the volume, faded over SONG_FADE_MS; a song plays once, never looped, music() returning "playing" or "ended" (which the window's wrapper passes back to the game), { restart: true } taking it back to the top with load() (no seeking, since the server sends no byte ranges), and a song no longer asked for fades and pauses where it was. The window plays it only while Play sounds, Play game sounds and Play game music (looks.gameMusic, off by default) are all on
public/activities/snake-music.js Snake's ten music tracks as data (no imports): SNAKE_MUSIC, { bpm, rush, voices, patterns, order } each, named snake<Place> and listed in MUSIC_TRACKS in snake.js. A round deals them in a fresh order, one to each level, so a run hears a different track at every level and none twice. They were picked on the pages in prototypes/music/snake (rhythm-first folk and world tunes led by something plucked or reedy, mostly dark or modal), and their bars are not all sixteen steps: 6/8 is 12, 7/8 is 14, ten beats is 20, twelve beats is 24, each pattern a whole number of its bars; merged by snake-sfx.js
public/activities/light-trails/1.mp3 to 5.mp3 Light Trails' five background songs, named trailsSong1 to trailsSong5 under songs in trails-sfx.js and listed in SERVABLE; re-encoded for size with ffmpeg (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with loudnorm, metadata stripped), about 7.6 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm
public/activities/flock-dash/1.mp3 to 5.mp3 Flock Dash's five background songs, named flockSong1 to flockSong5 under songs in flock-sfx.js and listed in SERVABLE; re-encoded for size with ffmpeg the way Light Trails' were (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with loudnorm, metadata stripped), about 6.4 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm; flock.js deals all five in a fresh order each round with dealMusic(), plays each in full one after another and deals again after the last, never opening on the song that just ended
public/screens/activities.js Activities: #btn-activities (the die right of the megaphone), #activities-modal, the one frame timer (requestAnimationFrame, swappable with setTickSource() for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind; CHEAT_CODE, typed on a game's board, turns on endless lives through the game's cheat(on) until the round starts over, and dropCheats() turns it off on leaving for the picker or closing; STAGE_CODE, the same arrows then S, calls the game's stageSelect() where it has one, Ghoul Rush's practice stage select) and pauseAll(), which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with pointer(), and key releases to a game with release(); a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes, except while a round is held: a question or finish that pauses a round on an open window holds it, the banner adds #activities-unpause (Unpause game) beside Go to it, and only that button plays on (play() refuses a held round), since a key or click already on its way used to dismiss the banner unread. Go to it, or closing the window any other way, lets the hold go, and a banner with nothing left to say drops it. Every start and play-on first counts down 3, 2, 1 (COUNT_FROM, 700 ms a number, setCountdownMs() for the page tests, which set 0 unless they test it): the game is already running, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. With two or more games listed the window opens on the picker (view: "picker" or "game", applyView()): a card button per game (drawPicker(), covers in COVERS drawn as SVG with cv-* token classes, since the page's policy refuses a style attribute) with its blurb, best and a Last played or Round paused tag, arrows walking the cards (moveFocus()), and #activities-back (All games) back to it. One game at a time: pick() drops the last game from games when another is picked, and openActivities() goes straight back into a paused round. The last pick is kept as lastActivity and gets the focus; lowerIsBetter games keep the lowest round as the best; the header shows the current game's best (paintTitle()). renderActivities() in the render pass compares myTurn() and finish() with the last render and shows the banner with Go to it. Loads a game with import() when it is picked and keeps it until another is picked; setActivityList() lets a test list a stub second game, which brings up the picker
public/styles/activities.css the Activities rules: the die in the top bar, the Notebook-sized dialog, the board and its state overlay, the your-turn banner in the highlight color, the picker and the notes

Building an Activities game: the rules every game follows, so a new one plays like the rest.

  • Lives are prominent. A game with lives draws them as the lives pill: livesText(round.lives) in the LIVES color from pills.js, placed right after the level/stage pill, which drawPill() draws solid pink with a heart per life. Never a plain ♥ N on the dark backing: that was hard to read at a glance. The unit suite checks every game with lives for it.
  • Every game with lives takes the endless-lives code. Typing up, down, up, down, left, right, left, right, B, A, space on the board gives endless lives until the round starts over or the person leaves the game (CHEAT_CODE in screens/activities.js, which calls the game's cheat(true) and cheat(false) on leaving for the picker or closing). A game with lives answers cheat(on) by setting round.infinite, never takes a life while it is set (if (!round.infinite) round.lives -= 1), lets start() make a new round without it, and shows livesText(Infinity) ("♥ x∞") in its lives pill. scripts/test-web-console-activities.mjs checks every listed game whose round has lives.
  • Banners never get in the way. A banner over the board ("Hit!", a new level, a power-up) is placed on the frame it first shows, on the part of the board away from the player, and fades to BANNER_SEE_THROUGH (0.12) over BANNER_FADE_MS while the player, or anything the player must react to (a diving bug, a bomb, a rival, a hazard, the road over a hill), is in its strip; Snake's bannerRow() and underBanner() are the model. Give the banner object a see field, multiply the draw's alpha by it, and export the strip check (underBanner) for the unit suite.
  • The window owns pausing. A game never resumes itself; screens/activities.js decides when a key or click plays on, including the hold on a question or finish (see the row above), so a game needs nothing of its own for it. Full screen is the window's too (setFull(): the button, F, and a turn or finish putting it back; fitFull() sizes the game to the whole screen (black bars where its shape leaves room) and docks the overlaid panel in a bar that holds it, data-dock="side" or "below", or floats it, "float", shrunk to the score while a round plays and the pointer is still; and tells the desktop app activities-full); a game only sees a bigger resize(), so a new game needs nothing for it, as long as its resize() sets the canvas's CSS size.
  • Every moment has a sound, and moving things hum. A game plays a one-shot through the tone it is handed for each event worth hearing (a hit, a pickup, a level, a new best, game over) and keeps continuous things (an engine, a motor, wind, water, a fuse, a monster close by) going with hum(id, name, level, pitch) from its tick, pitch following speed. Never a one-shot every frame: a repeating cue is throttled by a timer in the round. Its own sounds live in activities/<id>-sfx.js, named with the game id; the shared kit is in tones.js. create() defaults tone and hum to no-ops, since the suites make games with neither, and a sound never changes the game's state.
  • Its logic tests pin the dice. A game rolls Math.random for roads, spawns and layouts, and an unlucky roll once failed a test on CI at random (Ghoul Rush's Eye, Bounce Road twice). Import ./seed-random.mjs FIRST in every scripts/test-web-console-activities*.mjs file: it seeds Math.random (set PLAN2CODE_TEST_SEED to try another roll), so a test sees the same world on every run.