From a88ceb194bcec6008d499436f9a1fca7c4cf8e8a Mon Sep 17 00:00:00 2001 From: Douwe de Vries Date: Fri, 13 Nov 2026 21:35:04 +0100 Subject: [PATCH 1/2] feat(guns): Lance is the home gun from sector 3; Scatter and Seekers run on a charge The main gun is no longer a picked ship system. From sector 3 the ship flies Lance, and Q (or the touch swap key) steps Lance -> Scatter -> Seekers -> Lance. One charge meter (SPECIAL_GUN_CHARGE, gameplay clock) pays for the specials: it drains while one is out (full = 10 s) and hands back Lance at empty, refills on Lance over 30 s plus 0.02 per kill, needs 0.2 to leave Lance, and starts full every sector and after a respawn or checkpoint load. It is never saved. - ShipSystemsRuntime owns the gun and the charge; GUN_SWAP, the swap cooldown and the fire silence are gone. - HUD: gun name and charge bar under the reserve ships (amber draining, cyan refilling, tick at the threshold); the touch swap key mirrors it. - Removed the gun slot from ShipSystems, the sector-2 pick, the refit bay gun tile, the pause SYSTEMS gun row and the gun in save-slot labels. Old saves with a gun field load with it ignored. - Boss balance script measures Lance only (--guns removed). - Browser harness snapshot exposes the gun and charge for e2e. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 14 + README.md | 9 +- docs/architecture-guidelines.md | 2 +- docs/level-design.md | 5 +- scripts/balance/bossFights.ts | 32 +- src/browserHarness/snapshot.ts | 10 +- src/config/shipSystems.ts | 107 ++++-- src/scenes/GameScene.ts | 9 +- src/scenes/gameScene/PauseOverlay.ts | 21 +- src/scenes/gameScene/PauseStateController.ts | 11 +- .../gameScene/combatFeedbackHandlers.ts | 6 + .../createPoolsAndGameplaySystems.ts | 2 +- src/scenes/gameScene/gameplayFrameBehavior.ts | 35 +- src/scenes/gameScene/hudSyncOrchestration.ts | 5 + src/scenes/gameScene/pauseOverlay/types.ts | 7 +- .../gameScene/runGameSceneCreateBootstrap.ts | 6 +- src/scenes/gameScene/showControlsHint.ts | 4 +- src/scenes/menuScene/devLevelJump.ts | 8 +- src/scenes/planetIntermission/refitView.ts | 2 +- src/systems/HUD.ts | 41 +- src/systems/MobileControls.ts | 77 ++-- src/systems/ShipSystemsRuntime.ts | 89 +++-- src/systems/hud/bootstrapRelayout.ts | 18 +- src/systems/hud/meterRenderers.ts | 46 +++ src/systems/hud/statusBarLayout.ts | 26 +- src/systems/mainGun.ts | 16 +- tests/MobileControlsDrag.test.ts | 10 +- tests/PauseStateController.test.ts | 6 +- tests/PlayerState.test.ts | 26 +- tests/SaveSlotConcurrency.test.ts | 2 +- tests/SaveSlotShieldPersistence.test.ts | 2 +- tests/SaveSlotStorage.test.ts | 16 +- tests/chainOverdrive.test.ts | 7 +- tests/combatFeedbackHandlers.test.ts | 11 +- tests/e2e/directRetry.spec.ts | 4 +- tests/e2e/shipSystems.spec.ts | 219 ++++------- .../gameplayFrameBehaviorPerformance.test.ts | 7 +- tests/gunSwap.test.ts | 270 ------------- tests/mainGun.test.ts | 47 ++- tests/rivalDuel.test.ts | 2 +- tests/shipSystems.test.ts | 61 +-- tests/specialGunCharge.test.ts | 356 ++++++++++++++++++ tests/startRun.test.ts | 4 +- 43 files changed, 964 insertions(+), 694 deletions(-) delete mode 100644 tests/gunSwap.test.ts create mode 100644 tests/specialGunCharge.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b8f1d3..b61b045 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ All notable changes to this project will be documented in this file. +## [Unreleased] + +### Changed + +- Lance is now your main gun from sector 3 on, and Scatter and Seekers are special guns you use on a charge. Press Q (or the swap button on touch screens) to go Lance → Scatter → Seekers → Lance. A special gun runs down a charge meter: a full meter lasts 10 seconds, and when it empties you go back to Lance on your own, with the gun's name flashing over your ship. The meter only refills on Lance, over 30 seconds, and every enemy you destroy tops it up a little. You need a fifth of the meter to leave Lance; below that Q just clicks. Switching between the special guns, or back to Lance, always works. +- The meter starts full at the start of every sector and after you respawn or load a checkpoint. Pausing and hit-stops never run it down. +- The HUD shows the current gun and its charge under your reserve ships from sector 3: amber while a special gun drains it, cyan while Lance refills it. The touch swap button shows the same charge along its foot. Sectors 1 and 2 are unchanged: standard gun, no meter, and Q does nothing. +- `bun run balance:bosses` measures every boss with Lance only; its `--guns` option is gone. + +### Removed + +- The CHOOSE YOUR MAIN GUN pick after sector 2, the main gun at the refit bay and in the pause panel's SYSTEMS tab, and the gun's name in save slots. Saves from earlier versions still load; the gun they stored is ignored. +- The 2-second wait between gun swaps and the half second of silence after a swap. The charge is the cost now. + ## [1.34.0] - 2026-11-13 ### Added diff --git a/README.md b/README.md index 30e9c41..f7373f9 100644 --- a/README.md +++ b/README.md @@ -36,15 +36,15 @@ Open `http://localhost:5173` in your browser. |-------|--------| | Arrow keys / WASD | Move ship | | Space / Click | Fire weapons | -| Q | Swap main gun (once the run has picked one) | +| Q | From sector 3: switch to a special gun while its charge lasts (Lance → Scatter → Seekers → Lance) | | Esc | Pause (closes the settings sheet on the menu) | The ship flies with inertia: it builds speed over about a second and slides after you let go. On touch devices, drag anywhere to fly: the ship follows your finger's movement and the main gun fires automatically. Pressing a key on a hardware keyboard hands steering and firing to the -keyboard, and the next touch hands them back (tap-to-pause stays available). Once the run has a main -gun, a swap button sits under the pause button. +keyboard, and the next touch hands them back (tap-to-pause stays available). From sector 3, a swap +button under the pause button switches guns and shows the special-gun charge. Autofire is set in SETTINGS (menu or pause panel). Touch flight autofires by default; turn it off to fire only while your finger is on the screen. Keyboard and mouse play can turn autofire on, so @@ -114,7 +114,8 @@ Bought during the planet intermission screen using score as currency: - **Fire Rate** — improves firing speed - **Shield** — increases hit absorption - **AEGIS Picket** — installs and overclocks automatic flank-defense turrets -- **Ship systems** — free picks after sectors 2, 5 and 8 that change how the ship plays: a main gun (Lance, Scatter, Seekers), a support system (Magnet, Surge Core, Wingman) and a doctrine (Overdrive, Bulwark, Salvager). Picks can be changed freely at any later refit bay, and mid-run: the main gun on Q or the touch swap button, the others from the pause panel +- **Lance and special guns** — from sector 3 the ship flies Lance, a piercing gun. Q (or the touch swap button) switches to Scatter or Seekers for as long as a charge meter lasts: a full meter gives 10 seconds, then the gun returns to Lance. On Lance the meter refills over time and a little with every kill, and you need a fifth of it to switch again. The meter starts full every sector and after every respawn +- **Ship systems** — free picks after sectors 5 and 8 that change how the ship plays: a support system (Magnet, Surge Core, Wingman) and a doctrine (Overdrive, Bulwark, Salvager). Picks can be changed freely at any later refit bay, and mid-run from the pause panel - **A different run every time** — each run has its own sky and may fly sectors mirrored; RETRY replays the same run, NEW RUN starts a fresh one Some upgrades unlock later in the campaign and use progression caps so the run scales in a controlled way. diff --git a/docs/architecture-guidelines.md b/docs/architecture-guidelines.md index 8192d01..08e3b18 100644 --- a/docs/architecture-guidelines.md +++ b/docs/architecture-guidelines.md @@ -35,7 +35,7 @@ This document describes the scene boundaries, system contracts, and coding rules - `src/systems/PlayerState.ts` is the only place that should define registry keys and helper functions for persistent run data. - Use `getPlayerState`, `setPlayerState`, `saveScoreToState`, `saveCurrentHp`, `advanceToNextLevel`, `getRunSummary`, and `setRunSummary` instead of writing raw registry keys in scenes. -- During a sector, `ShipSystemsRuntime` is the one owner of the run's current ship systems. The gun, the surge, doctrine effects and the pause panel read them from it, and every mid-run change goes through it so the live effects (Wingman's drone, Magnet, the gun-swap cost) and `saveShipSystems` stay in step. Do not copy the systems onto other objects. +- During a sector, `ShipSystemsRuntime` is the one owner of the run's current ship systems, the current main gun and the special-gun charge. The gun, the surge, doctrine effects, the HUD, the touch swap key and the pause panel read them from it, and every mid-run change goes through it so the live effects (Wingman's drone, Magnet, the charge draining and refilling) and `saveShipSystems` stay in step. The gun and its charge are per sector and never saved. Do not copy them onto other objects. - `PlayerStateData` is the long-lived run state used between scenes. - `RunSummaryData` is the terminal summary contract used by `GameOverScene` and `VictoryScene`. - When adding new terminal UI data, extend `RunSummaryData` and update the setter/getter helpers first so every scene reads the same contract. diff --git a/docs/level-design.md b/docs/level-design.md index a318d81..b2fd01b 100644 --- a/docs/level-design.md +++ b/docs/level-design.md @@ -24,7 +24,8 @@ shields recharge on every respawn. Levels 5–10 add payoff without adding player inputs: - **AEGIS Picket** becomes purchasable after Level 4. Its fixed flank turrets trim chaff with flat-damage bolts while the main gun remains the dominant damage source. Pickets never target bosses. -- **Ship systems** are free one-of-three picks at the refit bay after sectors 2, 5 and 8 (`config/shipSystems.ts`). They change how the ship plays rather than how hard it hits, and are balanced by measurement: each main gun trades single-target damage for one strength and scored inside the standard gun's run-to-run spread in sector 5. Nothing is offered in sectors 1–2, which stay a gentle introduction. A system works without input; the only new input is changing one. Once a slot has a pick the player may change it to another option of that slot: freely at every later refit bay (the picks sit beside the upgrade cards and reopen the pick dialog, which Escape dismisses), the main gun mid-flight on Q or the touch swap key, and support and doctrine from the pause panel's SYSTEMS tab. A gun change in flight costs `GUN_SWAP` (0.5 s of silence, 2 s before the next change, both on the gameplay clock), so swapping mid-fight is a decision and never a free best-of-all-guns; between sectors, at the refit bay, a change is free and has no cooldown. In flight, feedback is a brief name flash over the ship and a short swap sound, and each gun's shots have their own look (the profile's `look`), so the active gun reads from the fire itself; there is no persistent panel. The current pick is saved with the run. +- **Main guns** (`config/shipSystems.ts`): sectors 1–2 fly the standard bolt and have no gun input, so the opening stays a gentle introduction. From sector 3 the home gun is Lance; Scatter and Seekers are special guns borrowed on a charge, not picks. Each gun trades single-target damage for one strength and scored inside the standard gun's run-to-run spread in sector 5. Q or the touch swap key steps Lance → Scatter → Seekers → Lance. One meter, `SPECIAL_GUN_CHARGE`, counted on the gameplay clock, pays for the specials: it drains while one is selected (a full meter lasts 10 s) and returns the gun to Lance at empty; on Lance it refills over 30 s plus a bonus per enemy destroyed; leaving Lance needs at least 0.2 of it, while moving between specials or back to Lance is always allowed. It starts full every sector and after every respawn or checkpoint load, and is never saved. Feedback is a name flash over the ship and a short swap sound on every change (including the automatic return), the quiet click when leaving Lance is refused, each gun's own shot look (the profile's `look`), and the HUD's gun row under the reserve ships: the gun's name and a charge bar that burns amber while a special drains and refills cyan on Lance, with a tick at the threshold. The touch swap key mirrors the bar along its foot. +- **Ship systems** are free one-of-three picks at the refit bay after sectors 5 and 8. They change how the ship plays rather than how hard it hits. A system works without input; the only input is changing one. Once a slot has a pick the player may change it to another option of that slot: freely at every later refit bay (the picks sit beside the upgrade cards and reopen the pick dialog, which Escape dismisses) and mid-run from the pause panel's SYSTEMS tab. The current pick is saved with the run. - **Run variation** comes from one seed per run (`systems/runVariation.ts`, `systems/gameplayRandom.ts`). It decides the wave choices, whether each sector is mirrored left to right, and the sky. Two rules keep scores comparable: the sky is looks only, and the only layout change is the mirror, which is as hard by symmetry. Never vary wave order, enemy counts or timing by seed. RETRY keeps the seed; NEW RUN draws a new one. Enemies, asteroids and wormholes each draw from their own seeded stream, so one cannot shift another's choices; how far a run gets through a stream still depends on play. Enemy jitter and pickup drops stay unseeded because they depend on how the fight goes. - **Marked Aces** are sparse authored variants of existing enemies. Their gilded treatment signals 2× durability, 4× score, and exactly one guaranteed power-up. - **Boss volleys are telegraphed.** For the last 400 ms before every volley the boss's core swells and its hardpoints flash white. Bosses have no stun or bonus-damage window; fights are paced by the wind-up and each attack's cooldown. @@ -169,7 +170,7 @@ Difficulty shorthand: G = gentle, R = ramp, H = hard. ### L3: Ember Monsoon (G->R) - planet Cinderreach - motif: ember storm - Sower + minefield debut; energy-storm returns as the weather. -- First boss: Pyre Herald (barrage), taught by a mid-boss elite wave at 60%. Two gentle phases of two attacks each; it never escalates and needs no gun pick. +- First boss: Pyre Herald (barrage), taught by a mid-boss elite wave at 60%. Two gentle phases of two attacks each; it never escalates and needs no special gun. - distance 14500, spawnRate 1.35; enemies: fighter 30, sower 18, swarm 27, diver 25. - Drops: health at the heat front, shield pre-boss. diff --git a/scripts/balance/bossFights.ts b/scripts/balance/bossFights.ts index c402943..4930d3d 100644 --- a/scripts/balance/bossFights.ts +++ b/scripts/balance/bossFights.ts @@ -4,12 +4,13 @@ * Fights every boss with a scripted bot and reports how long each fight took and what it cost. * * bun run balance:bosses - * bun run balance:bosses --sectors 6 --guns standard,lance --port 4302 + * bun run balance:bosses --sectors 6 --port 4302 * bun run balance:bosses --invulnerable # time to kill even where the bot would die * * Starts its own dev server (the browser harness is dev-only), jumps straight to each boss with the * sector's representative ship, and lets `startBossFight` in the browser harness fly a fixed bot: it - * holds a low line under the boss and steps away from shots that will cross it. Fights run in real + * holds a low line under the boss and steps away from shots that will cross it. Every boss sector flies + * Lance; the bot never spends the special-gun charge. Fights run in real * time on the gameplay clock (no speed-up), several at once in separate pages; `seconds` is gameplay * time from the boss alarm to the kill, so pauses and hit-stops do not count. */ @@ -18,13 +19,10 @@ import { createServer } from 'vite'; import type { BossFightReport } from '../../src/browserHarness'; import { getUpgradeByKey, getUpgradeProgressionLimit, type UpgradeKey } from '../../src/config/UpgradesConfig'; -const GUNS = ['standard', 'lance', 'scatter', 'seekers'] as const; -type Gun = (typeof GUNS)[number]; const BOSS_SECTORS = [3, 4, 5, 6, 7, 8, 9, 10]; interface Options { sectors: number[]; - guns: Gun[]; parallel: number; limitSeconds: number; invulnerable: boolean; @@ -41,11 +39,8 @@ function parseOptions(argv: readonly string[]): Options { flag(name) ?.split(',') .map((part) => part.trim()); - const guns = (list('--guns') ?? [...GUNS]) as Gun[]; - if (guns.some((gun) => !GUNS.includes(gun))) throw new Error(`--guns takes ${GUNS.join(',')}`); return { sectors: list('--sectors')?.map(Number) ?? BOSS_SECTORS, - guns, parallel: Number(flag('--parallel') ?? 4), limitSeconds: Number(flag('--limit') ?? 240), invulnerable: argv.includes('--invulnerable'), @@ -67,12 +62,11 @@ function representativeUpgrades(sector: number): string { interface FightResult extends BossFightReport { sector: number; - gun: Gun; /** Frames per second the page held; the bot needs a real frame rate to dodge like a player. */ fps: number; } -async function fight(browser: Browser, baseUrl: string, sector: number, gun: Gun, options: Options) { +async function fight(browser: Browser, baseUrl: string, sector: number, options: Options) { const context = await browser.newContext({ viewport: { width: 1280, height: 720 } }); const page = await context.newPage(); try { @@ -81,9 +75,8 @@ async function fight(browser: Browser, baseUrl: string, sector: number, gun: Gun // Low effects keep several pages at full frame rate; quality never changes the simulation. window.localStorage.setItem('space-explorer.visualQuality.v1', 'low'); }); - const systems = gun === 'standard' ? '' : `&systems=${gun}`; const upgrades = representativeUpgrades(sector); - await page.goto(`${baseUrl}/?browserHarness=1&startLevel=${sector}&upgrades=${upgrades}${systems}&seed=1`); + await page.goto(`${baseUrl}/?browserHarness=1&startLevel=${sector}&upgrades=${upgrades}&seed=1`); await page.waitForFunction( () => window.__SPACE_EXPLORER_BROWSER_HARNESS__?.snapshot().activeScenes.includes('Game') ?? false, undefined, @@ -108,10 +101,10 @@ async function fight(browser: Browser, baseUrl: string, sector: number, gun: Gun .catch(() => false); if (!report || report.killed || gameOver || report.seconds > options.limitSeconds) break; } - if (!report) throw new Error(`Sector ${sector} ${gun}: no fight report`); + if (!report) throw new Error(`Sector ${sector}: no fight report`); const frames = await page.evaluate(() => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.renderStats.read().frames); const fps = frames / ((Date.now() - startedAt) / 1000); - return { ...report, sector, gun, fps } satisfies FightResult; + return { ...report, sector, fps } satisfies FightResult; } finally { await context.close(); } @@ -128,7 +121,7 @@ async function main(): Promise { if (!address || typeof address === 'string') throw new Error('Dev server did not report a port'); const baseUrl = `http://127.0.0.1:${address.port}`; - const queue = options.sectors.flatMap((sector) => options.guns.map((gun) => ({ sector, gun }))); + const queue = [...options.sectors]; const results: FightResult[] = []; // Without the GPU, headless Chromium renders the game at about 10 fps and the bot reacts too late. const browser = await chromium.launch({ @@ -137,9 +130,9 @@ async function main(): Promise { }); try { const workers = Array.from({ length: Math.max(1, options.parallel) }, async () => { - for (let job = queue.shift(); job; job = queue.shift()) { - const result = await fight(browser, baseUrl, job.sector, job.gun, options); - console.error(`sector ${result.sector} ${result.gun}: ${result.seconds.toFixed(1)} s`); + for (let sector = queue.shift(); sector !== undefined; sector = queue.shift()) { + const result = await fight(browser, baseUrl, sector, options); + console.error(`sector ${result.sector}: ${result.seconds.toFixed(1)} s`); results.push(result); } }); @@ -149,12 +142,11 @@ async function main(): Promise { await server.close(); } - results.sort((a, b) => a.sector - b.sector || GUNS.indexOf(a.gun) - GUNS.indexOf(b.gun)); + results.sort((a, b) => a.sector - b.sector); console.log(`Boss fights${options.invulnerable ? ' (invulnerable bot)' : ''}`); console.table( results.map((result) => ({ sector: result.sector, - gun: result.gun, upgrades: representativeUpgrades(result.sector), 'kill s': result.killed ? Number(result.seconds.toFixed(1)) : `- (${Math.round(result.seconds)})`, 'boss hp': result.killed ? 0 : `${Math.round(result.bossHp)}/${result.bossMaxHp}`, diff --git a/src/browserHarness/snapshot.ts b/src/browserHarness/snapshot.ts index a075271..c767f50 100644 --- a/src/browserHarness/snapshot.ts +++ b/src/browserHarness/snapshot.ts @@ -24,6 +24,8 @@ export interface BrowserHarnessSnapshot { audioPauseReasons: readonly AudioPauseReason[]; audioContextState: AudioContextState | null; levelProgress: number | null; + /** The Game scene's main gun and special-gun charge (0..1); null before sector 3 or outside a sector. */ + gun: Readonly<{ id: string; charge: number }> | null; preload: Readonly<{ status: number; progress: number; texts: readonly string[] }> | null; texts: readonly Readonly<{ text: string; x: number; y: number; width: number; height: number; shown: boolean }>[]; objects: readonly Readonly<{ @@ -121,7 +123,12 @@ export function createBrowserHarnessSnapshot(game: Phaser.Game): BrowserHarnessS const physicsWorld = primaryScene?.physics?.world; const gameScene = activeScenes.find((scene) => scene.scene.key === 'Game') as - (Phaser.Scene & { levelManager?: { progress: number } }) | undefined; + | (Phaser.Scene & { + levelManager?: { progress: number }; + shipSystems?: { getGun(): string | null; getGunCharge(): number }; + }) + | undefined; + const gunId = gameScene?.shipSystems?.getGun() ?? null; const preloadScene = game.scene.getScene('Preload'); const preloadTexts = preloadScene.children.list .filter((child): child is Phaser.GameObjects.Text => child instanceof Phaser.GameObjects.Text) @@ -149,6 +156,7 @@ export function createBrowserHarnessSnapshot(game: Phaser.Game): BrowserHarnessS audioPauseReasons: Object.freeze([...audioManager.getPauseReasons()]), audioContextState: audioManager.getContextState(), levelProgress: gameScene?.levelManager?.progress ?? null, + gun: gunId === null ? null : Object.freeze({ id: gunId, charge: gameScene!.shipSystems!.getGunCharge() }), preload: Object.freeze({ status: preloadScene.sys.settings.status, progress: preloadScene.load.progress, diff --git a/src/config/shipSystems.ts b/src/config/shipSystems.ts index 7a10746..1367ae6 100644 --- a/src/config/shipSystems.ts +++ b/src/config/shipSystems.ts @@ -1,18 +1,18 @@ /** * Ship systems: free picks that change how the ship plays, offered at the refit bay. Once picked, a slot - * can be changed to another of its options: freely at any later refit bay, and mid-run the main gun on - * the swap key or touch button (`GUN_SWAP` keeps it a decision), support and doctrine from the pause panel. Nothing else needs input, - * so touch and keyboard stay equal. Stat upgrades are bought separately. + * can be changed to another of its options: freely at any later refit bay, and mid-run from the pause + * panel. Nothing needs input, so touch and keyboard stay equal. Stat upgrades are bought separately. + * + * The main gun is not a pick: from sector 3 on the ship flies Lance, and the swap key borrows one of the + * two special guns for as long as `SPECIAL_GUN_CHARGE` lasts (see below). */ export type MainGunId = 'lance' | 'scatter' | 'seekers'; type SupportSystemId = 'magnet' | 'surgeCore' | 'wingman'; type LateSystemId = 'overdrive' | 'bulwark' | 'salvager'; -export type ShipSystemId = MainGunId | SupportSystemId | LateSystemId; -export type ShipSystemSlot = 'gun' | 'support' | 'late'; +export type ShipSystemId = SupportSystemId | LateSystemId; +export type ShipSystemSlot = 'support' | 'late'; export interface ShipSystems { - /** Null keeps the standard bolt. */ - gun: MainGunId | null; support: SupportSystemId | null; late: LateSystemId | null; } @@ -34,17 +34,6 @@ export interface ShipSystemSlotDef { } const SHIP_SYSTEM_SLOTS: readonly ShipSystemSlotDef[] = [ - { - slot: 'gun', - title: 'MAIN GUN', - shortTitle: 'GUN', - offeredAfterLevel: 2, - options: [ - { id: 'lance', name: 'LANCE', description: 'Slower shots that pierce every ship in a line.' }, - { id: 'scatter', name: 'SCATTER', description: 'Three-way spread. Strong up close, thin at range.' }, - { id: 'seekers', name: 'SEEKERS', description: 'Shots curve toward targets. Slow to fire, rarely miss.' }, - ], - }, { slot: 'support', title: 'SUPPORT SYSTEM', @@ -73,7 +62,7 @@ const SHIP_SYSTEM_SLOTS: readonly ShipSystemSlotDef[] = [ }, ]; -export const NO_SHIP_SYSTEMS: ShipSystems = { gun: null, support: null, late: null }; +export const NO_SHIP_SYSTEMS: ShipSystems = { support: null, late: null }; /** A slot's title and options, e.g. to offer them again at the refit bay. */ export function getShipSystemSlot(slot: ShipSystemSlot): ShipSystemSlotDef { @@ -85,12 +74,12 @@ function optionIds(slot: ShipSystemSlot): readonly ShipSystemId[] { return getShipSystemSlot(slot).options.map((option) => option.id); } -/** Clamps untrusted persisted picks to the authored options. */ +/** Clamps untrusted persisted picks to the authored options; anything else stored with them is dropped. */ export function normalizeShipSystems(value: unknown): ShipSystems { const record = value && typeof value === 'object' ? (value as Record) : {}; const pick = (slot: ShipSystemSlot): T | null => optionIds(slot).includes(record[slot] as ShipSystemId) ? (record[slot] as T) : null; - return { gun: pick('gun'), support: pick('support'), late: pick('late') }; + return { support: pick('support'), late: pick('late') }; } /** The pick to offer after clearing `level`: the earliest unlocked slot that is still empty. */ @@ -98,12 +87,12 @@ export function getPendingShipSystemSlot(level: number, systems: ShipSystems): S return SHIP_SYSTEM_SLOTS.find((def) => level >= def.offeredAfterLevel && systems[def.slot] === null) ?? null; } -/** Puts `id` in its slot. Usable anywhere a pick changes: the refit bay, the swap key, the pause panel. */ +/** Puts `id` in its slot. Usable anywhere a pick changes: the refit bay and the pause panel. */ export function setShipSystem(systems: ShipSystems, slot: ShipSystemSlot, id: ShipSystemId): ShipSystems { return normalizeShipSystems({ ...systems, [slot]: id }); } -/** The slot's next option, wrapping around (Lance -> Scatter -> Seekers -> Lance). An empty slot stays empty. */ +/** The slot's next option, wrapping around (Magnet -> Surge Core -> Wingman -> Magnet). An empty slot stays empty. */ export function selectNextShipSystem(systems: ShipSystems, slot: ShipSystemSlot): ShipSystems { const current = systems[slot]; if (current === null) return systems; @@ -113,7 +102,7 @@ export function selectNextShipSystem(systems: ShipSystems, slot: ShipSystemSlot) interface PickedShipSystem { slot: ShipSystemSlot; - /** The slot's title, e.g. `MAIN GUN`. */ + /** The slot's title, e.g. `SUPPORT SYSTEM`. */ title: string; shortTitle: string; option: ShipSystemOption; @@ -127,12 +116,7 @@ export function describePickedShipSystems(systems: ShipSystems): PickedShipSyste }); } -/** The display name of a system, e.g. `SCATTER`. */ -export function getShipSystemName(id: ShipSystemId): string { - return SHIP_SYSTEM_SLOTS.flatMap((def) => def.options).find((option) => option.id === id)?.name ?? ''; -} - -/** The picks as one line for a save slot, e.g. `SYSTEMS: LANCE · MAGNET`; empty with none. */ +/** The picks as one line for a save slot, e.g. `SYSTEMS: MAGNET · BULWARK`; empty with none. */ export function describeShipSystems(systems: ShipSystems): string { const names = describePickedShipSystems(systems).map((picked) => picked.option.name); return names.length > 0 ? `SYSTEMS: ${names.join(' · ')}` : ''; @@ -147,6 +131,8 @@ export type PlayerShotLook = 'bolt' | 'lance' | 'pellet' | 'dart'; /** Main-gun firing patterns. Damage per shot is unchanged; the fire cooldown pays for the pattern. */ export interface MainGunProfile { + /** Shown in the HUD and flashed over the ship on a change, e.g. `SCATTER`. */ + name: string; look: PlayerShotLook; /** Multiplies the fire cooldown. */ cooldownScale: number; @@ -158,6 +144,7 @@ export interface MainGunProfile { } const STANDARD_GUN: MainGunProfile = { + name: 'STANDARD', look: 'bolt', cooldownScale: 1, spreadDegrees: [0], @@ -166,22 +153,71 @@ const STANDARD_GUN: MainGunProfile = { }; /** + * Lance is the home gun from sector 3 on; Scatter and Seekers are the special guns, used on the charge. * Tuned by measurement, not only arithmetic: 40 s of sector 5 with autofire and a sweeping ship scored * 72k-132k with the standard gun over four runs, and each of these landed inside that spread. */ const GUN_PROFILES: Record = { // One target: 0.77x the standard gun. Two in a line: 1.54x. Rewards lining ships up. - lance: { look: 'lance', cooldownScale: 1.3, spreadDegrees: [0], pierce: true, seekDegreesPerSecond: 0 }, + lance: { + name: 'LANCE', + look: 'lance', + cooldownScale: 1.3, + spreadDegrees: [0], + pierce: true, + seekDegreesPerSecond: 0, + }, // All three hit up close: 1.67x. Only the centre shot at range: 0.56x. Rewards flying in. - scatter: { look: 'pellet', cooldownScale: 1.8, spreadDegrees: [-13, 0, 13], pierce: false, seekDegreesPerSecond: 0 }, + scatter: { + name: 'SCATTER', + look: 'pellet', + cooldownScale: 1.8, + spreadDegrees: [-13, 0, 13], + pierce: false, + seekDegreesPerSecond: 0, + }, // Half the shots of the standard gun, but almost every one connects. Rewards dodging over aiming. - seekers: { look: 'dart', cooldownScale: 2, spreadDegrees: [0], pierce: false, seekDegreesPerSecond: 150 }, + seekers: { + name: 'SEEKERS', + look: 'dart', + cooldownScale: 2, + spreadDegrees: [0], + pierce: false, + seekDegreesPerSecond: 150, + }, }; +/** The order the swap key steps through: Lance -> Scatter -> Seekers -> Lance. */ +const MAIN_GUN_CYCLE: readonly MainGunId[] = ['lance', 'scatter', 'seekers']; + export function getMainGunProfile(gun: MainGunId | null): MainGunProfile { return gun ? GUN_PROFILES[gun] : STANDARD_GUN; } +export function getNextMainGun(gun: MainGunId): MainGunId { + return MAIN_GUN_CYCLE[(MAIN_GUN_CYCLE.indexOf(gun) + 1) % MAIN_GUN_CYCLE.length]; +} + +/** + * The special-gun charge: one meter (0 empty, 1 full) on the gameplay clock, so pause and hit-stop never + * run it. Sectors before `fromLevel` fly the standard gun and have no meter; from there the ship flies + * Lance and the swap key steps to Scatter, Seekers and back. + * - `drainMs`: a full meter lasts this long while a special gun is selected; at empty the gun returns + * to Lance by itself. + * - `refillMs`: on Lance an empty meter refills in this long, plus `perKill` for every enemy destroyed. + * It never refills while a special gun is selected. + * - `minToLeaveLance`: leaving Lance needs at least this much; below it the swap is refused. Moving + * between the special guns, or back to Lance, is always allowed. + * The meter starts full every sector and after every respawn or checkpoint load, and is never saved. + */ +export const SPECIAL_GUN_CHARGE = { + fromLevel: 3, + drainMs: 10_000, + refillMs: 30_000, + perKill: 0.02, + minToLeaveLance: 0.2, +} as const; + /** Surge Core: grazes count for more and the pulse clears a wider circle. */ export const SURGE_CORE = { grazeValueScale: 1.6, clearRadiusScale: 1.35 } as const; /** Magnet: pickups within this distance drift toward the ship at this speed. */ @@ -192,8 +228,3 @@ export const WINGMAN = { offsetX: 34, offsetY: 10, everyNthVolley: 2 } as const; export const OVERDRIVE_COOLDOWN_STEP = 0.06; /** Bulwark: a shield hit clears enemy shots inside this radius. */ export const BULWARK_CLEAR_RADIUS = 160; -/** - * Changing the main gun mid-run, counted on the gameplay clock: the next change waits `cooldownMs` and - * the new gun stays silent for `fireSilenceMs`, so swapping is a decision and never a free best-of-all. - */ -export const GUN_SWAP = { cooldownMs: 2000, fireSilenceMs: 500 } as const; diff --git a/src/scenes/GameScene.ts b/src/scenes/GameScene.ts index 45284a6..7b963d5 100644 --- a/src/scenes/GameScene.ts +++ b/src/scenes/GameScene.ts @@ -50,7 +50,7 @@ import { GameplayClock, runGameSceneUpdateFrame } from './gameScene/updateFrame' import { HitStop } from '@/systems/HitStop'; import { getGameplayDifficultyTier } from '@/config/gameplayDifficulty'; import type { ShipSystemsRuntime } from '@/systems/ShipSystemsRuntime'; -import { getShipSystemName } from '@/config/shipSystems'; +import { getMainGunProfile } from '@/config/shipSystems'; import { createShipLabel } from '@/systems/effects/ephemeralOverlayTweens'; import { NEON_TEXT } from './shared/neonUiTheme'; import { clampPlayerToViewport, getPlayerSpawnPoint, syncSceneViewport } from './gameScene/viewport'; @@ -125,7 +125,6 @@ export class GameScene extends Phaser.Scene { stopPlayerMotion: () => this.stopPlayerMotion(), captureCurrentRunStateForSave: () => this.captureCurrentRunStateForSave(), canSaveCurrentRun: () => this.canSaveCurrentRun(), - getGameplayNow: () => this.gameplayClock.now, }); this.installBootstrapRuntime(runtime); const handlers = this.createCombatFeedbackHandlers(); @@ -202,6 +201,8 @@ export class GameScene extends Phaser.Scene { syncLastLifeHelperWingState: () => this.syncLastLifeHelperWingState(), getGameplayNow: () => this.gameplayClock.now, getShipSystems: () => this.shipSystems.getSystems(), + recordGunChargeKill: () => this.shipSystems.recordKill(), + resetGunCharge: () => this.shipSystems.resetGunCharge(), hitStop: (durationMs) => this.hitStop.trigger(durationMs), constants: { bossExplosionVisualIntensity: GameScene.BOSS_EXPLOSION_VISUAL_INTENSITY, @@ -409,6 +410,8 @@ export class GameScene extends Phaser.Scene { lastHudShieldCount: this.lastHudShieldCount, now: this.gameplayClock.now, surgeRatio: this.grazeSurge?.getGaugeRatio() ?? 0, + gun: this.shipSystems?.getGun() ?? null, + gunCharge: this.shipSystems?.getGunCharge() ?? 0, }); } @@ -424,7 +427,7 @@ export class GameScene extends Phaser.Scene { shipSystems: this.shipSystems, gunSwapFeedback: { swapped: (gun) => { - createShipLabel(this, this.player.x, this.player.y, getShipSystemName(gun), NEON_TEXT.cyan); + createShipLabel(this, this.player.x, this.player.y, getMainGunProfile(gun).name, NEON_TEXT.cyan); audioManager.playSfx('gunSwap'); }, denied: () => audioManager.playSfx('uiClick'), diff --git a/src/scenes/gameScene/PauseOverlay.ts b/src/scenes/gameScene/PauseOverlay.ts index 5c13040..b9e59e7 100644 --- a/src/scenes/gameScene/PauseOverlay.ts +++ b/src/scenes/gameScene/PauseOverlay.ts @@ -20,7 +20,7 @@ const SUBVIEWS: ReadonlyArray<[PauseSubview, string]> = [ ['systems', 'SYSTEMS'], ['settings', 'SETTINGS'], ]; -const SYSTEM_SLOTS: readonly ShipSystemSlot[] = ['gun', 'support', 'late']; +const SYSTEM_SLOTS: readonly ShipSystemSlot[] = ['support', 'late']; /** The status line: the controller's message, else a note about the active subview. */ export function describePauseStatus( @@ -94,25 +94,19 @@ interface SystemRow { refresh: (state: PauseOverlayState) => void; } -/** - * A picked ship system: its slot, name and what it does. Support and doctrine get SWAP to cycle to the - * slot's next option; the main gun is swapped in flight only, where its cooldown applies. - */ +/** A picked ship system: its slot, name, what it does, and SWAP to cycle to the slot's next option. */ function createSystemRow(slot: ShipSystemSlot, handlers: PauseOverlayHandlers): SystemRow { const kicker = h('span', { className: 'pause-system__slot' }); const name = h('span'); const description = h('span', { className: 'pause-slot__sub ui-ellipsis' }); - let swap: HTMLButtonElement | null = null; - if (slot !== 'gun') { - swap = h('button', { type: 'button', className: 'ui-btn ui-btn--slim' }, 'SWAP'); - swap.addEventListener('click', () => handlers.onCycleSystem(slot)); - } + const swap = h('button', { type: 'button', className: 'ui-btn ui-btn--slim' }, 'SWAP'); + swap.addEventListener('click', () => handlers.onCycleSystem(slot)); const element = h( 'div', { className: 'ui-card pause-slot pause-system', 'data-occupied': '' }, h('span', { className: 'pause-slot__title ui-ellipsis' }, kicker, name), description, - ...(swap ? [h('div', { className: 'pause-slot__actions' }, swap)] : []) + h('div', { className: 'pause-slot__actions' }, swap) ); return { @@ -124,7 +118,7 @@ function createSystemRow(slot: ShipSystemSlot, handlers: PauseOverlayHandlers): kicker.textContent = picked.title; name.textContent = picked.option.name; description.textContent = picked.option.description; - swap?.setAttribute('aria-label', `Swap ${picked.title.toLowerCase()}, now ${picked.option.name}`); + swap.setAttribute('aria-label', `Swap ${picked.title.toLowerCase()}, now ${picked.option.name}`); }, }; } @@ -152,6 +146,7 @@ export class PauseOverlay { storageAvailable: false, saveSlots: [], systems: NO_SHIP_SYSTEMS, + specialGuns: false, statusMessage: '', }; @@ -260,7 +255,7 @@ export class PauseOverlay { ); } this.systemRows.forEach((row) => row.refresh(this.state)); - this.hint.textContent = this.state.systems.gun ? 'ESC RESUME Q SWAP GUN IN FLIGHT' : 'ESC RESUME'; + this.hint.textContent = this.state.specialGuns ? 'ESC RESUME Q SPECIAL GUN WHILE CHARGED' : 'ESC RESUME'; for (const [subview, { tab, view }] of this.tabs) { const active = subview === this.activeSubview; if (subview === 'systems') tab.hidden = describePickedShipSystems(this.state.systems).length === 0; diff --git a/src/scenes/gameScene/PauseStateController.ts b/src/scenes/gameScene/PauseStateController.ts index 495dc55..fa5a568 100644 --- a/src/scenes/gameScene/PauseStateController.ts +++ b/src/scenes/gameScene/PauseStateController.ts @@ -1,13 +1,13 @@ import type Phaser from 'phaser'; import { noteRunDifficulty } from '@/systems/PlayerState'; -import { NO_SHIP_SYSTEMS, type ShipSystems } from '@/config/shipSystems'; +import { NO_SHIP_SYSTEMS, type ShipSystems, type ShipSystemSlot } from '@/config/shipSystems'; import { setGameplayDifficultyTier, type GameplayDifficultyTier } from '@/config/gameplayDifficulty'; import { setVisualQualityTier, type VisualQualityTier } from '@/config/visualQuality'; import { createArmingAction } from '@/systems/armingAction'; import { audioManager } from '@/systems/AudioManager'; import type { SaveSlotId, SaveSlotViewModel } from '@/systems/SaveSlotStorage'; import { PauseOverlay } from './PauseOverlay'; -import type { PauseOverlayHandlers, PauseOverlayState, PauseSwappableSlot } from './pauseOverlay/types'; +import type { PauseOverlayHandlers, PauseOverlayState } from './pauseOverlay/types'; type SaveSlotActionResult = { ok: true; message: string } | { ok: false; message: string }; @@ -23,7 +23,9 @@ export interface PauseSaveSlotAdapter { /** The run's current ship systems, which the pause panel shows and can cycle. */ export interface PauseShipSystemsPort { getSystems: () => ShipSystems; - cycleSystem: (slot: PauseSwappableSlot) => void; + cycleSystem: (slot: ShipSystemSlot) => void; + /** True from sector 3, where the swap key borrows a special gun. */ + hasSpecialGuns: () => boolean; } interface PauseOverlayPort { @@ -233,7 +235,7 @@ export class PauseStateController { } /** The change takes effect at once; the frozen clock means it is felt on resume. */ - private handleCycleSystemRequested(slot: PauseSwappableSlot): void { + private handleCycleSystemRequested(slot: ShipSystemSlot): void { if (!this.manualPauseRequested || !this.shipSystems) return; this.playClick?.(); this.shipSystems.cycleSystem(slot); @@ -277,6 +279,7 @@ export class PauseStateController { storageAvailable: this.saveSlotAdapter.isAvailable(), saveSlots: this.saveSlotAdapter.list(), systems: this.shipSystems?.getSystems() ?? NO_SHIP_SYSTEMS, + specialGuns: this.shipSystems?.hasSpecialGuns() ?? false, statusMessage: this.statusMessage, statusOk: this.statusOk, }; diff --git a/src/scenes/gameScene/combatFeedbackHandlers.ts b/src/scenes/gameScene/combatFeedbackHandlers.ts index 9398515..47ac8b4 100644 --- a/src/scenes/gameScene/combatFeedbackHandlers.ts +++ b/src/scenes/gameScene/combatFeedbackHandlers.ts @@ -50,6 +50,10 @@ interface GameSceneCombatFeedbackDeps { getGameplayNow: () => number; /** The run's current ship systems; doctrine effects read them on every event. */ getShipSystems: () => ShipSystems; + /** Tops up the special-gun charge for an enemy destroyed (only counts while on Lance). */ + recordGunChargeKill: () => void; + /** A respawn returns to Lance with a full special-gun charge. */ + resetGunCharge: () => void; /** Briefly slows gameplay on a big impact (see `HitStop`). */ hitStop: (durationMs: number) => void; constants: CombatFeedbackConstants; @@ -176,6 +180,7 @@ export function createGameSceneCombatFeedbackHandlers( return { handleEnemyDeath: (score, x, y, isAce): void => { const awarded = deps.scoreManager.registerKill(score, deps.getGameplayNow()); + deps.recordGunChargeKill(); deps.effectsManager.createScorePopup(x, y, awarded); runBestEffort(() => audioManager.playSfx('explosionSmall', stereoPan(deps.scene, x))); if (isAce) { @@ -201,6 +206,7 @@ export function createGameSceneCombatFeedbackHandlers( deps.scoreManager.onPlayerDeath(); deps.collisionManager.clearPlayerHazards(); deps.waveManager.applyDeathRelief(); + deps.resetGunCharge(); } if (shouldSyncHelperWingAfterPlayerDeath(outcome)) { diff --git a/src/scenes/gameScene/createPoolsAndGameplaySystems.ts b/src/scenes/gameScene/createPoolsAndGameplaySystems.ts index 23f828b..3584839 100644 --- a/src/scenes/gameScene/createPoolsAndGameplaySystems.ts +++ b/src/scenes/gameScene/createPoolsAndGameplaySystems.ts @@ -248,7 +248,7 @@ export function createPoolsAndGameplaySystems(params: CreatePoolsAndGameplaySyst }); waveManager.setPowerUpGroup?.(powerUpGroup); - const shipSystems = new ShipSystemsRuntime(scene, player, powerUpGroup, state.systems); + const shipSystems = new ShipSystemsRuntime(scene, player, powerUpGroup, state.systems, state.level); const grazeSurge = new GrazeSurgeSystem( { diff --git a/src/scenes/gameScene/gameplayFrameBehavior.ts b/src/scenes/gameScene/gameplayFrameBehavior.ts index 74d7a47..55ca787 100644 --- a/src/scenes/gameScene/gameplayFrameBehavior.ts +++ b/src/scenes/gameScene/gameplayFrameBehavior.ts @@ -48,18 +48,22 @@ interface GameSceneGameplayFrameDelegate { } | null; shipSystems: { getSystems(): ShipSystems; - trySwapGun(now: number): GunSwapOutcome; - isGunSilenced(now: number): boolean; - getGunSwapCooldownRatio(now: number): number; + getGun(): MainGunId | null; + getGunCharge(): number; + trySwapGun(): GunSwapOutcome; + updateGunCharge(deltaMs: number): boolean; update(): void; }; - /** Name flash and sound for a gun swap, or the quiet cue for one refused during the cooldown. */ + /** + * Name flash and sound for a gun change (a swap, or the meter running out and handing back Lance), or + * the quiet cue for leaving Lance refused on a low meter. + */ gunSwapFeedback: { swapped(gun: MainGunId): void; denied(): void; }; mobileControls: { - setGunSwapState(available: boolean, cooldownRatio: number): void; + setGunChargeState(gun: MainGunId | null, charge: number): void; } | null; grazeSurge: { update(): void; @@ -149,30 +153,30 @@ export function createGameSceneGameplayFrameBehavior( delegate.updateHud(); }; - const updateGunSwap = (time: number): void => { + const updateGunSwap = (delta: number): void => { const shipSystems = delegate.shipSystems; if (delegate.inputManager.consumeGunSwapRequest() && delegate.player.isAlive) { - const outcome = shipSystems.trySwapGun(time); - const gun = shipSystems.getSystems().gun; + const outcome = shipSystems.trySwapGun(); + const gun = shipSystems.getGun(); if (outcome === 'swapped' && gun) delegate.gunSwapFeedback.swapped(gun); - else if (outcome === 'cooling') delegate.gunSwapFeedback.denied(); + else if (outcome === 'low-charge') delegate.gunSwapFeedback.denied(); } - delegate.mobileControls?.setGunSwapState( - shipSystems.getSystems().gun !== null, - shipSystems.getGunSwapCooldownRatio(time) - ); + if (shipSystems.updateGunCharge(delta)) delegate.gunSwapFeedback.swapped('lance'); + delegate.mobileControls?.setGunChargeState(shipSystems.getGun(), shipSystems.getGunCharge()); }; const updatePlayerFiring = (time: number): void => { const shipSystems = delegate.shipSystems; - if (!delegate.inputManager.isFiring() || !delegate.player.isAlive || shipSystems.isGunSilenced(time)) { + if (!delegate.inputManager.isFiring() || !delegate.player.isAlive) { return; } const systems = shipSystems.getSystems(); + const gun = shipSystems.getGun(); const fireCooldown = resolveMainGunCooldownMs( delegate.player.fireRate, delegate.scoreManager.getChainState(time).multiplier, + gun, systems ); if (time <= lastFireTime + fireCooldown) { @@ -188,6 +192,7 @@ export function createGameSceneGameplayFrameBehavior( volleyIndex += 1; fireMainGunVolley({ + gun, systems, volleyIndex, origin: shotOrigin, @@ -305,7 +310,7 @@ export function createGameSceneGameplayFrameBehavior( delegate.shipSystems.update(); delegate.grazeSurge.update(); - updateGunSwap(time); + updateGunSwap(delta); updatePlayerFiring(time); updateEncounterAndLevelProgress(time, delta); updateBossHudIfNeeded(); diff --git a/src/scenes/gameScene/hudSyncOrchestration.ts b/src/scenes/gameScene/hudSyncOrchestration.ts index 152c2b7..0c5ab2a 100644 --- a/src/scenes/gameScene/hudSyncOrchestration.ts +++ b/src/scenes/gameScene/hudSyncOrchestration.ts @@ -1,4 +1,5 @@ import type { Player } from '@/entities/Player'; +import type { MainGunId } from '@/config/shipSystems'; import type { HUD } from '@/systems/HUD'; import type { LevelManager } from '@/systems/LevelManager'; import type { ScoreManager } from '@/systems/ScoreManager'; @@ -19,6 +20,9 @@ interface HudUpdateInput { lastHudShieldCount: number | null; now: number; surgeRatio: number; + /** Null before sector 3, where there is no gun row. */ + gun: MainGunId | null; + gunCharge: number; } export function syncHudShields(input: HudSyncInput): number | null { @@ -40,6 +44,7 @@ export function updateHud(input: HudUpdateInput): number | null { ); input.hud.updateChainMeter(input.scoreManager.getChainState(input.now)); input.hud.updateSurge(input.surgeRatio); + input.hud.updateGunCharge(input.gun, input.gunCharge); return syncHudShields({ hud: input.hud, diff --git a/src/scenes/gameScene/pauseOverlay/types.ts b/src/scenes/gameScene/pauseOverlay/types.ts index 0a0041a..e41f867 100644 --- a/src/scenes/gameScene/pauseOverlay/types.ts +++ b/src/scenes/gameScene/pauseOverlay/types.ts @@ -11,7 +11,7 @@ export interface PauseOverlayHandlers { onDeleteSlot: (slotId: SaveSlotId) => void; onSelectDifficulty: (tier: GameplayDifficultyTier) => boolean; onSelectQuality: (tier: VisualQualityTier) => boolean; - onCycleSystem: (slot: PauseSwappableSlot) => void; + onCycleSystem: (slot: ShipSystemSlot) => void; } export interface PauseOverlayState { @@ -22,11 +22,10 @@ export interface PauseOverlayState { saveSlots: SaveSlotViewModel[]; /** The run's ship systems; the SYSTEMS tab shows only when one is picked. */ systems: ShipSystems; + /** From sector 3 the swap key borrows a special gun; the controls hint names it. */ + specialGuns: boolean; statusMessage: string; statusOk?: boolean; } -/** The main gun is swapped in flight only, so pausing can never skip its cooldown. */ -export type PauseSwappableSlot = Exclude; - export type PauseSubview = 'checkpoints' | 'systems' | 'settings'; diff --git a/src/scenes/gameScene/runGameSceneCreateBootstrap.ts b/src/scenes/gameScene/runGameSceneCreateBootstrap.ts index 9369b98..6456762 100644 --- a/src/scenes/gameScene/runGameSceneCreateBootstrap.ts +++ b/src/scenes/gameScene/runGameSceneCreateBootstrap.ts @@ -42,7 +42,6 @@ export type GameSceneBootstrapHost = { stopPlayerMotion: () => void; captureCurrentRunStateForSave: () => PlayerStateData; canSaveCurrentRun: () => boolean; - getGameplayNow: () => number; }; export type GameSceneBootstrapRuntime = { @@ -140,7 +139,8 @@ export function runGameSceneCreateBootstrap( canSaveCurrentRun: host.canSaveCurrentRun, shipSystems: { getSystems: () => gameplay.shipSystems.getSystems(), - cycleSystem: (slot) => gameplay.shipSystems.cycleSystem(slot, host.getGameplayNow()), + cycleSystem: (slot) => gameplay.shipSystems.cycleSystem(slot), + hasSpecialGuns: () => gameplay.shipSystems.getGun() !== null, }, }); @@ -166,7 +166,7 @@ export function runGameSceneCreateBootstrap( host.scene.events.once(Phaser.Scenes.Events.SHUTDOWN, unsubscribeInput); dependencies.showControlsHint(host.scene, { mobile: dependencies.isTouchMobileDevice(), - gunSwap: state.systems.gun !== null, + gunSwap: gameplay.shipSystems.getGun() !== null, }); return { diff --git a/src/scenes/gameScene/showControlsHint.ts b/src/scenes/gameScene/showControlsHint.ts index 0b144b0..acd91a0 100644 --- a/src/scenes/gameScene/showControlsHint.ts +++ b/src/scenes/gameScene/showControlsHint.ts @@ -9,7 +9,7 @@ const AUTO_FIRE_HINT = 'Guns fire automatically'; const MOBILE_FIRE_HINT = 'Guns fire while you touch'; const KEYBOARD_TITLE = 'WASD / Arrows to Move'; const KEYBOARD_FIRE_HINT = 'SPACE / Click to Fire'; -const KEYBOARD_SWAP_HINT = 'Q to Swap Main Gun'; +const KEYBOARD_SWAP_HINT = 'Q for a Special Gun'; /** The fire line follows the autofire setting for the input in use. */ function fireHintFor(mobile: boolean): string { @@ -20,7 +20,7 @@ function fireHintFor(mobile: boolean): string { type ShowControlsHintOptions = { mobile?: boolean; - /** The run has a main gun, so the keyboard card adds the swap key (touch has its own button). */ + /** Sector 3 on: the keyboard card adds the special-gun key (touch has its own button). */ gunSwap?: boolean; }; diff --git a/src/scenes/menuScene/devLevelJump.ts b/src/scenes/menuScene/devLevelJump.ts index 4a376fe..d0fdbae 100644 --- a/src/scenes/menuScene/devLevelJump.ts +++ b/src/scenes/menuScene/devLevelJump.ts @@ -67,8 +67,8 @@ function resolveJumpUpgrades(raw: string | null, level: number): PlayerUpgradeLe * progression-legal max loadout for that level. `&upgrades=3,3,3,2` (hp,damage, * fireRate,shield) forces an explicit loadout with stock turrets; append an optional * fifth value (`&upgrades=3,3,3,2,1`) to include a turret tier. `&upgrades=0` jumps - * with a stock ship. `&systems=lance,magnet,overdrive` (gun,support,doctrine) picks ship systems; leave - * a place empty to skip it (`&systems=scatter` or `&systems=,wingman`). + * with a stock ship. `&systems=magnet,overdrive` (support,doctrine) picks ship systems; leave a place + * empty to skip it (`&systems=wingman` or `&systems=,bulwark`). */ export function resolveDevLevelJump(search: string): DevLevelJumpRequest | null { const params = new URLSearchParams(search); @@ -84,12 +84,12 @@ export function resolveDevLevelJump(search: string): DevLevelJumpRequest | null const level = Math.min(getTotalLevels(), Math.max(1, parsed)); const upgrades = resolveJumpUpgrades(params.get(UPGRADES_PARAM), level); - const [gun, support, late] = (params.get(SYSTEMS_PARAM) ?? '').split(',').map((part) => part.trim()); + const [support, late] = (params.get(SYSTEMS_PARAM) ?? '').split(',').map((part) => part.trim()); const seed = Number.parseInt(params.get(SEED_PARAM) ?? '', 10); return { level, upgrades, - systems: normalizeShipSystems({ gun, support, late }), + systems: normalizeShipSystems({ support, late }), runSeed: Number.isFinite(seed) && seed > 0 ? seed : null, }; } diff --git a/src/scenes/planetIntermission/refitView.ts b/src/scenes/planetIntermission/refitView.ts index f581b9e..5378bea 100644 --- a/src/scenes/planetIntermission/refitView.ts +++ b/src/scenes/planetIntermission/refitView.ts @@ -112,7 +112,7 @@ function createUpgradeCard(evaluation: UpgradeEvaluation, onBuy: (key: UpgradeKe }; } -const SYSTEM_SLOTS: readonly ShipSystemSlot[] = ['gun', 'support', 'late']; +const SYSTEM_SLOTS: readonly ShipSystemSlot[] = ['support', 'late']; interface SystemKey { slot: ShipSystemSlot; diff --git a/src/systems/HUD.ts b/src/systems/HUD.ts index ea44433..7f26be8 100644 --- a/src/systems/HUD.ts +++ b/src/systems/HUD.ts @@ -1,12 +1,15 @@ import Phaser from 'phaser'; import type { LevelConfig } from '../config/LevelsConfig'; import { colorToHexString, mixColor } from '../utils/colorUtils'; +import { getMainGunProfile, type MainGunId } from '../config/shipSystems'; +import { NEON_TEXT } from '../scenes/shared/neonUiTheme'; import type { ChainState } from './ScoreManager'; import { HudAnnouncementTweens } from './hud/announcementTweens'; import { resolveChainReadout } from './hud/chainReadout'; import { renderBossBar, renderChainBadge, + renderGunChargeBar, renderHullCells, renderProgressBar, renderReserveIcons, @@ -40,6 +43,8 @@ export class HUD { private currentSurgeRatio: number | null = null; private currentBossHp: number | null = null; private currentBossMaxHp: number | null = null; + private currentGun: MainGunId | null = null; + private currentGunCharge: number | null = null; create(scene: Phaser.Scene, levelConfig?: LevelConfig): void { this.scene = scene; @@ -54,6 +59,8 @@ export class HUD { this.currentSurgeRatio = null; this.currentBossHp = null; this.currentBossMaxHp = null; + this.currentGun = null; + this.currentGunCharge = null; this.bossVisible = false; const levelAccent = levelConfig?.accentColor ?? DEFAULT_ACCENT; @@ -91,6 +98,7 @@ export class HUD { renderReserveIcons(this.widgets.reserveIcons, this.currentLives ?? 0, layout); renderShieldPips(this.widgets.shieldPips, this.currentShields ?? 0, layout); renderSurgeBar(this.widgets.surgeFill, this.currentSurgeRatio, layout); + this.renderGunCharge(layout); renderProgressBar(this.widgets.progressFill, this.currentProgress, this.accentColor, layout); this.renderChainBadge(); this.renderBossBar(); @@ -201,6 +209,27 @@ export class HUD { renderSurgeBar(this.widgets.surgeFill, clampedRatio, layout); } + /** + * The gun row: from sector 3 the current gun's name and the special-gun charge. A sector without one + * (gun null) keeps the row hidden and the cluster its old size. + */ + updateGunCharge(gun: MainGunId | null, charge: number): void { + const clampedCharge = Math.max(0, Math.min(1, charge)); + if (gun !== this.currentGun) { + const rowChanged = (gun === null) !== (this.currentGun === null); + this.currentGun = gun; + this.currentGunCharge = clampedCharge; + if (rowChanged) this.relayout(); + else this.renderGunCharge(this.layout()); + return; + } + if (gun === null) return; + const layout = this.layout(); + if (!shouldRenderMeterRatio(this.currentGunCharge, clampedCharge, 1 / layout.gunBarWidth)) return; + this.currentGunCharge = clampedCharge; + this.renderGunCharge(layout); + } + showBossWarning(): void { this.announcementTweens.showBossWarning(); } @@ -226,7 +255,17 @@ export class HUD { } private layout(): HudLayoutMetrics { - return getLayoutMetrics(this.scene); + return getLayoutMetrics(this.scene, this.currentGun !== null); + } + + private renderGunCharge(layout: HudLayoutMetrics): void { + const { gunName, gunChargeTrack, gunChargeFill } = this.widgets; + const gun = this.currentGun; + for (const widget of [gunName, gunChargeTrack, gunChargeFill]) widget.setVisible(gun !== null); + if (gun === null) return; + const draining = gun !== 'lance'; + gunName.setText(getMainGunProfile(gun).name).setColor(draining ? NEON_TEXT.gold : NEON_TEXT.cyan); + renderGunChargeBar(gunChargeFill, this.currentGunCharge ?? 1, draining, layout); } private renderChainBadge(): void { diff --git a/src/systems/MobileControls.ts b/src/systems/MobileControls.ts index 11cc0eb..ac24ddf 100644 --- a/src/systems/MobileControls.ts +++ b/src/systems/MobileControls.ts @@ -4,6 +4,7 @@ import { getViewportBounds } from '../utils/layout'; import { drawAngledRectPath, NEON } from '../scenes/shared/neonUiTheme'; import { scaleUiGlowAlpha } from '../utils/renderingCompat'; import { beginDrag, dragDesiredVelocity, dragTarget, type DragState } from './input/relativeDrag'; +import { SPECIAL_GUN_CHARGE, type MainGunId } from '../config/shipSystems'; const CONTROLS_DEPTH = 1000; const PAUSE_BUTTON_SIZE = 44; @@ -11,8 +12,8 @@ const PAUSE_BUTTON_TOP_INSET = 84; const PAUSE_BUTTON_RIGHT_INSET = 22; /** The gun-swap key sits under pause: on the edge, clear of the steering thumb and the lane centre. */ const SWAP_BUTTON_GAP = 14; -/** Cooldown redraws in steps, not every frame. */ -const SWAP_COOLDOWN_STEPS = 20; +/** The charge bar redraws in steps, not every frame. */ +const SWAP_CHARGE_STEPS = 20; /** Keeps the dragged ship clear of the very edge so it stays fully visible. */ const DRAG_EDGE_MARGIN = 18; @@ -24,8 +25,8 @@ interface ControlKey { /** * Touch controls for momentum flight: drag anywhere and the ship follows the finger's movement, - * while the main gun autofires. A pause button stays available in the top-right corner, and once the - * run has a main gun a swap button sits under it. + * while the main gun autofires. A pause button stays available in the top-right corner, and from sector 3 + * a swap button sits under it that borrows a special gun and shows the charge. */ export class MobileControls { private scene: Phaser.Scene | null = null; @@ -42,8 +43,10 @@ export class MobileControls { private swapButtonPointerId: number | null = null; private swapButtonY: number = 0; private swapAvailable: boolean = false; - /** Cooldown left, in `SWAP_COOLDOWN_STEPS` (0 = ready). */ - private swapCooldownStep: number = 0; + /** A special gun is out and burning the charge. */ + private swapDraining: boolean = false; + /** Special-gun charge, in `SWAP_CHARGE_STEPS` (the full count = full). */ + private swapChargeStep: number = SWAP_CHARGE_STEPS; private swapPressPending: boolean = false; private dragPointerId: number | null = null; private dragState: DragState | null = null; @@ -147,7 +150,8 @@ export class MobileControls { this.touchSteeringSuppressed = false; this.pauseButtonHandler = null; this.swapAvailable = false; - this.swapCooldownStep = 0; + this.swapDraining = false; + this.swapChargeStep = SWAP_CHARGE_STEPS; this.swapPressPending = false; } @@ -210,15 +214,18 @@ export class MobileControls { } /** - * Shows the swap button only while the run has a main gun, dimmed and charging while - * `cooldownRatio` (1 just swapped, 0 ready) runs down. + * Shows the swap button only while there is a gun to swap (sector 3 on), with the special-gun charge + * along its foot: amber and draining while a special gun is out, cyan and refilling on Lance. */ - setGunSwapState(available: boolean, cooldownRatio: number): void { - const step = available ? Math.ceil(cooldownRatio * SWAP_COOLDOWN_STEPS) : 0; - if (available === this.swapAvailable && step === this.swapCooldownStep) return; + setGunChargeState(gun: MainGunId | null, charge: number): void { + const available = gun !== null; + const draining = available && gun !== 'lance'; + const step = Math.ceil(Math.max(0, Math.min(1, charge)) * SWAP_CHARGE_STEPS); + if (available === this.swapAvailable && draining === this.swapDraining && step === this.swapChargeStep) return; const visibilityChanged = available !== this.swapAvailable; this.swapAvailable = available; - this.swapCooldownStep = step; + this.swapDraining = draining; + this.swapChargeStep = step; if (visibilityChanged) this.refreshVisibility(); this.updateSwapButtonVisual(); } @@ -353,28 +360,30 @@ export class MobileControls { key.hitArea.setPosition(x, y); } - /** Two opposed arrows; while cooling the key dims and a bar charges along its foot. */ + /** + * Two opposed arrows over the charge bar. A special gun out lights the key's edge and bar amber while + * it drains; on Lance the bar refills cyan, and the key dims until there is enough charge to leave. + */ private updateSwapButtonVisual(): void { const key = this.swapKey; if (!key) return; const active = this.swapButtonPointerId !== null && this.isEnabled(); - const cooling = this.swapCooldownStep > 0; + const charge = this.swapChargeStep / SWAP_CHARGE_STEPS; + const ready = this.swapDraining || charge >= SPECIAL_GUN_CHARGE.minToLeaveLance; const x = this.pauseButtonX; const y = this.swapButtonY; const half = PAUSE_BUTTON_SIZE / 2; + const barColor = this.swapDraining ? NEON.amber : NEON.cyanBright; - drawKeyFrame(key.bg, x, y, active, cooling ? 0.55 : 1); - if (cooling) { - const charged = 1 - this.swapCooldownStep / SWAP_COOLDOWN_STEPS; - const barWidth = PAUSE_BUTTON_SIZE - 20; - key.bg.fillStyle(NEON.cyan, 0.25); - key.bg.fillRect(x - barWidth / 2, y + half - 8, barWidth, 3); - key.bg.fillStyle(NEON.cyanBright, 0.95); - key.bg.fillRect(x - barWidth / 2, y + half - 8, barWidth * charged, 3); - } + drawKeyFrame(key.bg, x, y, active, ready ? 1 : 0.55, this.swapDraining ? NEON.amber : NEON.cyan); + const barWidth = PAUSE_BUTTON_SIZE - 20; + key.bg.fillStyle(barColor, 0.25); + key.bg.fillRect(x - barWidth / 2, y + half - 8, barWidth, 3); + key.bg.fillStyle(barColor, 0.95); + key.bg.fillRect(x - barWidth / 2, y + half - 8, barWidth * charge, 3); key.icon.clear(); - key.icon.fillStyle(active ? NEON.ink : 0xe8f9ff, cooling ? 0.45 : 1); + key.icon.fillStyle(active ? NEON.ink : 0xe8f9ff, ready ? 1 : 0.45); key.icon.fillRect(x - 9, y - 6, 12, 3); key.icon.fillTriangle(x + 3, y - 10, x + 3, y + 1, x + 10, y - 4.5); key.icon.fillRect(x - 3, y + 3, 12, 3); @@ -406,17 +415,27 @@ function setControlKeyVisible(key: ControlKey | null, visible: boolean, interact if (key?.hitArea.input) key.hitArea.input.enabled = interactive; } -/** Glass key in the shared cut-corner shape; pressing it lights it solid like a primary button. */ -function drawKeyFrame(bg: Phaser.GameObjects.Graphics, x: number, y: number, active: boolean, alpha: number): void { +/** + * Glass key in the shared cut-corner shape; pressing it lights it solid like a primary button. `edge` + * tints the unpressed outline and glow (the swap key goes amber while a special gun is out). + */ +function drawKeyFrame( + bg: Phaser.GameObjects.Graphics, + x: number, + y: number, + active: boolean, + alpha: number, + edge: number = NEON.cyan +): void { const half = PAUSE_BUTTON_SIZE / 2; bg.clear(); drawAngledRectPath(bg, x - half - 2, y - half - 2, PAUSE_BUTTON_SIZE + 4, PAUSE_BUTTON_SIZE + 4, 12); - bg.lineStyle(3, NEON.cyan, scaleUiGlowAlpha(active ? 0.3 : 0.1) * alpha); + bg.lineStyle(3, edge, scaleUiGlowAlpha(active ? 0.3 : 0.1) * alpha); bg.strokePath(); drawAngledRectPath(bg, x - half, y - half, PAUSE_BUTTON_SIZE, PAUSE_BUTTON_SIZE, 11); bg.fillStyle(active ? NEON.cyan : NEON.panel, active ? 0.95 : 0.7); bg.fillPath(); drawAngledRectPath(bg, x - half, y - half, PAUSE_BUTTON_SIZE, PAUSE_BUTTON_SIZE, 11); - bg.lineStyle(1.5, active ? NEON.cyanBright : NEON.cyan, (active ? 1 : 0.75) * alpha); + bg.lineStyle(1.5, active ? NEON.cyanBright : edge, (active ? 1 : 0.75) * alpha); bg.strokePath(); } diff --git a/src/systems/ShipSystemsRuntime.ts b/src/systems/ShipSystemsRuntime.ts index 41f0e3e..9346c7f 100644 --- a/src/systems/ShipSystemsRuntime.ts +++ b/src/systems/ShipSystemsRuntime.ts @@ -1,9 +1,11 @@ import type Phaser from 'phaser'; import { - GUN_SWAP, + getNextMainGun, MAGNET, selectNextShipSystem, + SPECIAL_GUN_CHARGE, WINGMAN, + type MainGunId, type ShipSystems, type ShipSystemSlot, } from '../config/shipSystems'; @@ -23,26 +25,30 @@ interface Ship { type Pickup = Phaser.Physics.Arcade.Sprite; -export type GunSwapOutcome = 'swapped' | 'cooling' | 'unavailable'; +export type GunSwapOutcome = 'swapped' | 'low-charge' | 'unavailable'; /** - * The one owner of the run's current ship systems during a sector. Everything that depends on them - * (the gun, the surge, doctrine effects) reads them from here, so a change applies at once: Magnet - * pulls pickups in, Wingman shows its drone, and a changed main gun pays the `GUN_SWAP` cost. Times - * are on the gameplay clock, so pause and hit-stop never run the swap cost down. + * The one owner of the run's current ship systems and main gun during a sector. Everything that depends + * on them (the gun, the surge, doctrine effects, the HUD) reads them from here, so a change applies at + * once: Magnet pulls pickups in, Wingman shows its drone, and a special gun runs the + * `SPECIAL_GUN_CHARGE` meter down. The meter counts gameplay time only, so pause and hit-stop never run it. */ export class ShipSystemsRuntime { private systems: ShipSystems; private drone: Phaser.GameObjects.Image | null = null; - private lastGunSwapAt = Number.NEGATIVE_INFINITY; + /** Null flies the standard gun: sectors before `SPECIAL_GUN_CHARGE.fromLevel`. */ + private gun: MainGunId | null; + private gunCharge = 1; constructor( private readonly scene: Pick & { registry: PlayerStateRegistry }, private readonly ship: Ship, private readonly pickups: Phaser.Physics.Arcade.Group, - systems: ShipSystems + systems: ShipSystems, + level: number ) { this.systems = systems; + this.gun = level >= SPECIAL_GUN_CHARGE.fromLevel ? 'lance' : null; this.syncDrone(); } @@ -50,14 +56,57 @@ export class ShipSystemsRuntime { return this.systems; } + getGun(): MainGunId | null { + return this.gun; + } + + /** The special-gun meter, 0 empty to 1 full. */ + getGunCharge(): number { + return this.gunCharge; + } + + /** Steps Lance -> Scatter -> Seekers -> Lance. Leaving Lance needs `minToLeaveLance` charge. */ + trySwapGun(): GunSwapOutcome { + if (this.gun === null) return 'unavailable'; + if (this.gun === 'lance' && this.gunCharge < SPECIAL_GUN_CHARGE.minToLeaveLance) return 'low-charge'; + this.gun = getNextMainGun(this.gun); + return 'swapped'; + } + + /** + * Runs the meter for one gameplay frame: a special gun drains it, Lance refills it. Returns true on the + * frame an empty meter hands the gun back to Lance. + */ + updateGunCharge(deltaMs: number): boolean { + if (this.gun === null) return false; + if (this.gun === 'lance') { + this.gunCharge = Math.min(1, this.gunCharge + deltaMs / SPECIAL_GUN_CHARGE.refillMs); + return false; + } + this.gunCharge = Math.max(0, this.gunCharge - deltaMs / SPECIAL_GUN_CHARGE.drainMs); + if (this.gunCharge > 0) return false; + this.gun = 'lance'; + return true; + } + + /** An enemy destroyed tops the meter up, but only while on Lance. */ + recordKill(): void { + if (this.gun === 'lance') this.gunCharge = Math.min(1, this.gunCharge + SPECIAL_GUN_CHARGE.perKill); + } + + /** A respawn starts over on Lance with a full meter. */ + resetGunCharge(): void { + if (this.gun !== null) this.gun = 'lance'; + this.gunCharge = 1; + } + /** * Moves a picked slot to its next option and keeps the change for the next sector and for saves. The - * pause panel calls this for support and doctrine; the main gun goes through `trySwapGun`. + * pause panel calls this for support and doctrine. */ - cycleSystem(slot: ShipSystemSlot, now: number): void { + cycleSystem(slot: ShipSystemSlot): void { const previous = this.systems; const next = selectNextShipSystem(previous, slot); - if (next.gun !== previous.gun) this.lastGunSwapAt = now; this.systems = next; saveShipSystems(this.scene.registry, next); // Pickups the magnet was pulling go back to falling instead of drifting on forever. @@ -65,24 +114,6 @@ export class ShipSystemsRuntime { this.syncDrone(); } - /** Cycles the main gun when the run has one and the last swap has cooled down. */ - trySwapGun(now: number): GunSwapOutcome { - if (this.systems.gun === null) return 'unavailable'; - if (this.getGunSwapCooldownRatio(now) > 0) return 'cooling'; - this.cycleSystem('gun', now); - return 'swapped'; - } - - /** True while a freshly swapped gun is still coming online. */ - isGunSilenced(now: number): boolean { - return now - this.lastGunSwapAt < GUN_SWAP.fireSilenceMs; - } - - /** Share of the swap cooldown still to run: 1 right after a swap, 0 when the next swap is ready. */ - getGunSwapCooldownRatio(now: number): number { - return Math.min(1, Math.max(0, 1 - (now - this.lastGunSwapAt) / GUN_SWAP.cooldownMs)); - } - update(): void { if (this.drone) { this.drone.setVisible(this.ship.isAlive); diff --git a/src/systems/hud/bootstrapRelayout.ts b/src/systems/hud/bootstrapRelayout.ts index 87e6503..ca8edb1 100644 --- a/src/systems/hud/bootstrapRelayout.ts +++ b/src/systems/hud/bootstrapRelayout.ts @@ -1,8 +1,8 @@ import type Phaser from 'phaser'; import { NEON, NEON_FONT, NEON_TEXT, neonLabelStyle, neonReadoutStyle } from '../../scenes/shared/neonUiTheme'; import { getVisualQualityProfile } from '../../config/visualQuality'; -import { renderProgressTrack, renderSurgeTrack } from './meterRenderers'; -import { RESERVE_ICON_HEIGHT, type HudLayoutMetrics } from './statusBarLayout'; +import { renderGunChargeTrack, renderProgressTrack, renderSurgeTrack } from './meterRenderers'; +import type { HudLayoutMetrics } from './statusBarLayout'; interface CreateHudWidgetsParams { scene: Phaser.Scene; @@ -20,6 +20,10 @@ export interface HudWidgets { surgeFill: Phaser.GameObjects.Graphics; reserveLabel: Phaser.GameObjects.Text; reserveIcons: Phaser.GameObjects.Graphics; + /** From sector 3: the current gun's name and the special-gun charge. Hidden before then. */ + gunName: Phaser.GameObjects.Text; + gunChargeTrack: Phaser.GameObjects.Graphics; + gunChargeFill: Phaser.GameObjects.Graphics; scoreLabel: Phaser.GameObjects.Text; scoreText: Phaser.GameObjects.Text; sectorText: Phaser.GameObjects.Text; @@ -55,6 +59,9 @@ export function createHudWidgets({ scene, labelColor, sectorColor }: CreateHudWi const surgeFill = graphics(101); const reserveLabel = label('RES', neonLabelStyle(11, labelColor)); const reserveIcons = graphics(100); + const gunName = label('', neonLabelStyle(11, NEON_TEXT.cyan)).setVisible(false); + const gunChargeTrack = graphics(100).setVisible(false); + const gunChargeFill = graphics(101).setVisible(false); const scoreLabel = label('SCORE', neonLabelStyle(11, NEON_TEXT.gold)).setOrigin(1, 0); const scoreText = label('0', neonReadoutStyle(24)).setOrigin(1, 0); @@ -119,6 +126,9 @@ export function createHudWidgets({ scene, labelColor, sectorColor }: CreateHudWi surgeFill, reserveLabel, reserveIcons, + gunName, + gunChargeTrack, + gunChargeFill, scoreLabel, scoreText, sectorText, @@ -154,7 +164,7 @@ function drawPlate( /** Positions every static HUD element and repaints the parts that only change with the viewport. */ export function relayoutHudWidgets(widgets: HudWidgets, layout: HudLayoutMetrics, accentColor: number): void { const clusterTop = layout.hullLabelY - 5; - const hullClusterHeight = layout.reserveY + RESERVE_ICON_HEIGHT + 6 - clusterTop; + const hullClusterHeight = layout.hullClusterBottom + 6 - clusterTop; const scoreClusterWidth = layout.compact ? 126 : 148; const scoreClusterBottom = layout.compact ? layout.levelY + 19 : layout.scoreY + 31; @@ -184,6 +194,8 @@ export function relayoutHudWidgets(widgets: HudWidgets, layout: HudLayoutMetrics widgets.hpText.setPosition(layout.hullX + 42, layout.hullLabelY); widgets.reserveLabel.setPosition(layout.hullX, layout.reserveY - 3); renderSurgeTrack(widgets.surgeTrack, layout); + widgets.gunName.setPosition(layout.hullX, layout.gunY - 3); + renderGunChargeTrack(widgets.gunChargeTrack, layout); widgets.scoreLabel.setPosition(layout.scoreRight, layout.scoreLabelY).setVisible(!layout.compact); widgets.scoreText.setFontSize(layout.compact ? 22 : 24).setPosition(layout.scoreRight, layout.scoreY); diff --git a/src/systems/hud/meterRenderers.ts b/src/systems/hud/meterRenderers.ts index 844b8ce..4bc5d1a 100644 --- a/src/systems/hud/meterRenderers.ts +++ b/src/systems/hud/meterRenderers.ts @@ -1,9 +1,11 @@ import type Phaser from 'phaser'; import { NEON } from '../../scenes/shared/neonUiTheme'; +import { SPECIAL_GUN_CHARGE } from '../../config/shipSystems'; import { mixColor } from '../../utils/colorUtils'; import { scaleUiGlowAlpha } from '../../utils/renderingCompat'; import { BOSS_BAR_HEIGHT, + GUN_CHARGE_BAR_HEIGHT, HULL_CELL_HEIGHT, RESERVE_ICON_HEIGHT, SURGE_BAR_HEIGHT, @@ -111,6 +113,50 @@ export function renderSurgeBar(graphics: Graphics, ratio: number | null, layout: graphics.fillPath(); } +/** Lance refilling reads cyan like the hull; a special gun burning its charge reads amber. */ +const GUN_CHARGE_COLORS = { refilling: NEON.cyan, draining: NEON.amber } as const; + +/** Where the charge bar sits: centred on the gun name's line. */ +function gunChargeBarY(layout: HudLayoutMetrics): number { + return layout.gunY + 2; +} + +/** The unlit charge bar, with a tick where the meter is full enough to leave Lance. */ +export function renderGunChargeTrack(graphics: Graphics, layout: HudLayoutMetrics): void { + graphics.clear(); + const y = gunChargeBarY(layout); + slantedPath(graphics, layout.gunBarX, y, layout.gunBarWidth, GUN_CHARGE_BAR_HEIGHT); + graphics.fillStyle(TRACK_COLOR, TRACK_ALPHA); + graphics.fillPath(); + const tickX = layout.gunBarX + layout.gunBarWidth * SPECIAL_GUN_CHARGE.minToLeaveLance + SLANT / 2; + graphics.fillStyle(NEON.cyan, 0.55); + graphics.fillRect(tickX, y - 2, 1, GUN_CHARGE_BAR_HEIGHT + 4); +} + +/** + * The special-gun charge. Draining (a special gun is out) burns amber; refilling on Lance is cyan, dim + * until it passes the threshold to leave Lance and bright once full. + */ +export function renderGunChargeBar( + graphics: Graphics, + charge: number, + draining: boolean, + layout: HudLayoutMetrics +): void { + graphics.clear(); + if (charge <= 0) return; + const width = layout.gunBarWidth * Math.min(1, charge); + const y = gunChargeBarY(layout); + if (draining) { + fillLitSegment(graphics, layout.gunBarX, y, width, GUN_CHARGE_BAR_HEIGHT, GUN_CHARGE_COLORS.draining); + return; + } + const color = charge >= 1 ? mixColor(GUN_CHARGE_COLORS.refilling, 0xffffff, 0.45) : GUN_CHARGE_COLORS.refilling; + slantedPath(graphics, layout.gunBarX, y, width, GUN_CHARGE_BAR_HEIGHT); + graphics.fillStyle(color, charge < SPECIAL_GUN_CHARGE.minToLeaveLance ? 0.45 : 1); + graphics.fillPath(); +} + /** Where the hull label and its numeric readout end on the label row; shield pips stay right of it. */ const HULL_READOUT_WIDTH = 86; const SHIELD_PIP_STEP = 13; diff --git a/src/systems/hud/statusBarLayout.ts b/src/systems/hud/statusBarLayout.ts index a310523..1a9d010 100644 --- a/src/systems/hud/statusBarLayout.ts +++ b/src/systems/hud/statusBarLayout.ts @@ -9,11 +9,15 @@ export const HULL_CELL_HEIGHT = 10; export const SURGE_BAR_HEIGHT = 3; export const RESERVE_ICON_HEIGHT = 9; export const BOSS_BAR_HEIGHT = 12; +export const GUN_CHARGE_BAR_HEIGHT = 4; +/** Room the gun name takes before the charge bar starts; fits `SEEKERS`. */ +const GUN_NAME_WIDTH = 64; /** - * Where every HUD instrument sits. Two floating clusters hold the top corners (hull, surge, shields and - * reserve ships on the left; score and chain on the right) and a flight-vector rail runs along the top: - * between the clusters on wide viewports, edge to edge above them on phones. + * Where every HUD instrument sits. Two floating clusters hold the top corners (hull, surge, shields, + * reserve ships and, from sector 3, the gun and its charge on the left; score and chain on the right) and + * a flight-vector rail runs along the top: between the clusters on wide viewports, edge to edge above + * them on phones. */ export interface HudLayoutMetrics { left: number; @@ -32,6 +36,12 @@ export interface HudLayoutMetrics { surgeY: number; reserveY: number; reserveIconsX: number; + /** The gun row under the reserve ships: its name, then the special-gun charge bar. */ + gunY: number; + gunBarX: number; + gunBarWidth: number; + /** Bottom of the left cluster: under the gun row when it shows, else under the reserve ships. */ + hullClusterBottom: number; scoreRight: number; scoreLabelY: number; scoreY: number; @@ -57,7 +67,7 @@ export interface HudLayoutMetrics { announcementMaxWidth: number; } -export function getLayoutMetrics(scene: Phaser.Scene): HudLayoutMetrics { +export function getLayoutMetrics(scene: Phaser.Scene, gunRow: boolean): HudLayoutMetrics { const viewport = getViewportBounds(scene); const compact = viewport.width < COMPACT_WIDTH; const clusterTop = viewport.top + (compact ? 22 : 12); @@ -66,6 +76,8 @@ export function getLayoutMetrics(scene: Phaser.Scene): HudLayoutMetrics { const hullCellsY = clusterTop + 17; const surgeY = hullCellsY + HULL_CELL_HEIGHT + 4; const reserveY = surgeY + SURGE_BAR_HEIGHT + 7; + const gunY = reserveY + RESERVE_ICON_HEIGHT + 8; + const hullClusterBottom = gunRow ? gunY + RESERVE_ICON_HEIGHT : reserveY + RESERVE_ICON_HEIGHT; const scoreRight = viewport.right - EDGE_INSET; const progressWidth = compact ? viewport.width - EDGE_INSET * 2 @@ -83,6 +95,10 @@ export function getLayoutMetrics(scene: Phaser.Scene): HudLayoutMetrics { surgeY, reserveY, reserveIconsX: hullX + 32, + gunY, + gunBarX: hullX + GUN_NAME_WIDTH, + gunBarWidth: hullWidth - GUN_NAME_WIDTH - 4, + hullClusterBottom, scoreRight, scoreLabelY: clusterTop, scoreY: compact ? clusterTop - 3 : clusterTop + 11, @@ -92,7 +108,7 @@ export function getLayoutMetrics(scene: Phaser.Scene): HudLayoutMetrics { levelX: compact ? scoreRight : progressX + progressWidth, levelY: compact ? clusterTop + 36 : viewport.top + 9, chainX: compact ? hullX : scoreRight, - chainY: compact ? reserveY + RESERVE_ICON_HEIGHT + 10 : clusterTop + 44, + chainY: compact ? hullClusterBottom + 10 : clusterTop + 44, chainOriginX: compact ? 0 : 1, progressX, progressY: viewport.top + (compact ? 9 : 28), diff --git a/src/systems/mainGun.ts b/src/systems/mainGun.ts index 02b79aa..1ab3d25 100644 --- a/src/systems/mainGun.ts +++ b/src/systems/mainGun.ts @@ -4,6 +4,7 @@ import { getMainGunProfile, OVERDRIVE_COOLDOWN_STEP, WINGMAN, + type MainGunId, type PlayerShotLook, type ShipSystems, } from '../config/shipSystems'; @@ -15,6 +16,8 @@ interface Point { } export interface MainGunVolley { + /** Null fires the standard bolt (sectors 1-2). */ + gun: MainGunId | null; systems: ShipSystems; /** Counts volleys since the run began, so the Wingman fires on every Nth. */ volleyIndex: number; @@ -40,9 +43,9 @@ function rotate(direction: Point, degrees: number): Point { return { x: direction.x * cos - direction.y * sin, y: direction.x * sin + direction.y * cos }; } -/** Fires one volley of the picked main gun, plus the Wingman's shot when it is due. */ +/** Fires one volley of the current main gun, plus the Wingman's shot when it is due. */ export function fireMainGunVolley(volley: MainGunVolley): void { - const profile = getMainGunProfile(volley.systems.gun); + const profile = getMainGunProfile(volley.gun); const behaviour: BulletBehaviour | undefined = profile.pierce || profile.seekDegreesPerSecond > 0 ? { @@ -79,8 +82,13 @@ export function fireMainGunVolley(volley: MainGunVolley): void { * The main gun's cooldown: the ship's fire rate, stretched by the gun's pattern, then shortened by the * score chain. Overdrive rewards every chain step; without it only the max chain speeds the gun up. */ -export function resolveMainGunCooldownMs(fireRateMs: number, chainMultiplier: number, systems: ShipSystems): number { - const patterned = fireRateMs * getMainGunProfile(systems.gun).cooldownScale; +export function resolveMainGunCooldownMs( + fireRateMs: number, + chainMultiplier: number, + gun: MainGunId | null, + systems: ShipSystems +): number { + const patterned = fireRateMs * getMainGunProfile(gun).cooldownScale; if (systems.late !== 'overdrive') return resolvePlayerFireCooldownMs(patterned, chainMultiplier); const steps = Math.max(0, Math.floor(chainMultiplier) - 1); return Math.max(PLAYER_CONFIG.absoluteMinFireRate, patterned * (1 - OVERDRIVE_COOLDOWN_STEP * steps)); diff --git a/tests/MobileControlsDrag.test.ts b/tests/MobileControlsDrag.test.ts index 4d2ffa3..f77e1c9 100644 --- a/tests/MobileControlsDrag.test.ts +++ b/tests/MobileControlsDrag.test.ts @@ -156,12 +156,12 @@ describe('MobileControls relative drag', () => { }); describe('MobileControls gun-swap key', () => { - test('a tap requests one swap, only while the run has a main gun', () => { + test('a tap requests one swap, only from sector 3 where there is a gun to swap', () => { const { controls, tapKey } = createControls(); tapKey(SWAP_KEY, { id: 4, ...SWAP }); expect(controls.consumeGunSwapPress()).toBe(false); - controls.setGunSwapState(true, 0); + controls.setGunChargeState('lance', 1); tapKey(SWAP_KEY, { id: 4, ...SWAP }); expect(controls.consumeGunSwapPress()).toBe(true); expect(controls.consumeGunSwapPress()).toBe(false); @@ -170,19 +170,19 @@ describe('MobileControls gun-swap key', () => { test('the swap key never starts a drag, and its spot steers again when there is no key', () => { const { controls, emit } = createControls(); - controls.setGunSwapState(true, 0.5); + controls.setGunChargeState('scatter', 0.5); emit('pointerdown', { id: 4, ...SWAP }); expect(controls.getDragDesiredVelocity(195, 760, 0, 480)).toBeNull(); emit('pointerup', { id: 4, ...SWAP }); - controls.setGunSwapState(false, 0); + controls.setGunChargeState(null, 0); emit('pointerdown', { id: 5, ...SWAP }); expect(controls.getDragDesiredVelocity(195, 760, 0, 480)).toEqual({ vx: 0, vy: 0 }); }); test('pausing drops a tap that has not been handled yet', () => { const { controls, tapKey } = createControls(); - controls.setGunSwapState(true, 0); + controls.setGunChargeState('lance', 1); tapKey(SWAP_KEY, { id: 4, ...SWAP }); controls.setBlocked(true); expect(controls.consumeGunSwapPress()).toBe(false); diff --git a/tests/PauseStateController.test.ts b/tests/PauseStateController.test.ts index ef88d38..41c9bfa 100644 --- a/tests/PauseStateController.test.ts +++ b/tests/PauseStateController.test.ts @@ -54,7 +54,8 @@ function createOverlayState(overrides: Partial): PauseOverlay canSave: false, storageAvailable: false, saveSlots: [], - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, + specialGuns: false, statusMessage: '', statusOk: true, ...overrides, @@ -346,7 +347,7 @@ describe('PauseStateController regression coverage', () => { }); test('the SYSTEMS tab cycles a slot through the ship-systems port, only while paused', () => { - let systems = { gun: 'lance', support: 'magnet', late: null } as PauseOverlayState['systems']; + let systems = { support: 'magnet', late: null } as PauseOverlayState['systems']; const cycled: string[] = []; const harness = createPauseHarness(undefined, { shipSystems: { @@ -355,6 +356,7 @@ describe('PauseStateController regression coverage', () => { cycled.push(slot); systems = { ...systems, support: 'surgeCore' }; }, + hasSpecialGuns: () => true, }, }); diff --git a/tests/PlayerState.test.ts b/tests/PlayerState.test.ts index 7dadce4..27c53ff 100644 --- a/tests/PlayerState.test.ts +++ b/tests/PlayerState.test.ts @@ -49,7 +49,7 @@ describe('PlayerState schema behavior', () => { currentShields: 0, remainingLives: 3, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 0, turrets: 0 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { slots: [], grantedSlots: 0 }, }); expect(registry.get('playerState')).toEqual(state); @@ -74,7 +74,7 @@ describe('PlayerState schema behavior', () => { shield: 2.9, turrets: 1.9, }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: Number.POSITIVE_INFINITY, slots: [null, { remainingLives: -3, hp: 2.6 }, []], @@ -91,7 +91,7 @@ describe('PlayerState schema behavior', () => { currentShields: 8, remainingLives: 0, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 2, turrets: 1 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 3, slots: [ @@ -140,7 +140,7 @@ describe('PlayerState schema behavior', () => { registry.set('playerState', { level: 3, upgrades: { shield: 1.8 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, currentShields: 9, helperWing: { slots: [{}] }, }); @@ -170,7 +170,7 @@ describe('PlayerState schema behavior', () => { shield: Number.MAX_VALUE, turrets: Number.MAX_VALUE, }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: Number.MAX_VALUE, hp: Number.MAX_VALUE }], @@ -187,7 +187,7 @@ describe('PlayerState schema behavior', () => { currentShields: 8, remainingLives: 3, upgrades: { hp: 5, damage: 4, fireRate: 4, shield: 3, turrets: 2 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: 3, hp: 15 }], @@ -207,7 +207,7 @@ describe('PlayerState schema behavior', () => { currentShields: 2.9, remainingLives: 2.9, upgrades: { hp: 1.9, damage: 2.9, fireRate: 3.9, shield: 2.9, turrets: 1.9 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: 2.9, hp: 6.9 }] }, }); @@ -220,7 +220,7 @@ describe('PlayerState schema behavior', () => { currentShields: 2, remainingLives: 2, upgrades: { hp: 1, damage: 2, fireRate: 3, shield: 2, turrets: 1 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: 2, hp: 6 }] }, }); }); @@ -250,7 +250,7 @@ describe('PlayerState schema behavior', () => { currentShields: 3, remainingLives: 3, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 1, turrets: 0 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [] }, }); @@ -282,7 +282,7 @@ describe('PlayerState schema behavior', () => { shield: 2, turrets: 0, }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [], @@ -311,7 +311,7 @@ describe('PlayerState schema behavior', () => { shield: 3, turrets: 1, }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [], @@ -341,7 +341,7 @@ describe('PlayerState schema behavior', () => { currentShields: 0, remainingLives: 3, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 0, turrets: 1 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { slots: [], grantedSlots: 0 }, }); expect(getPlayerTurretTier(getPlayerState(registry))).toBe(1); @@ -356,7 +356,7 @@ describe('PlayerState schema behavior', () => { currentShields: 0, remainingLives: 3, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 0, turrets: 99 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { slots: [], grantedSlots: 0 }, }); expect(getPlayerTurretTier(getPlayerState(registry))).toBe(2); diff --git a/tests/SaveSlotConcurrency.test.ts b/tests/SaveSlotConcurrency.test.ts index 36962b2..2a95e36 100644 --- a/tests/SaveSlotConcurrency.test.ts +++ b/tests/SaveSlotConcurrency.test.ts @@ -83,7 +83,7 @@ function createRecord(id: 'slot-1' | 'slot-2' | 'slot-3', score: number): SaveSl currentShields: 0, remainingLives: 3, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 0, turrets: 0 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [] }, }, { finalScore: score, levelReached: 2, deathCause: null }, diff --git a/tests/SaveSlotShieldPersistence.test.ts b/tests/SaveSlotShieldPersistence.test.ts index 5545527..12f53ee 100644 --- a/tests/SaveSlotShieldPersistence.test.ts +++ b/tests/SaveSlotShieldPersistence.test.ts @@ -48,7 +48,7 @@ describe('save-slot shield persistence', () => { currentShields: 3, remainingLives: 3, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 1, turrets: 0 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [] }, }, { finalScore: 800, levelReached: 2, deathCause: null }, diff --git a/tests/SaveSlotStorage.test.ts b/tests/SaveSlotStorage.test.ts index c53745d..94bd4a5 100644 --- a/tests/SaveSlotStorage.test.ts +++ b/tests/SaveSlotStorage.test.ts @@ -75,7 +75,7 @@ function playerState(overrides: Partial = {}): PlayerStateInpu currentShields: 0, remainingLives: 3, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 0, turrets: 0 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [] }, ...overrides, }; @@ -137,7 +137,7 @@ describe('SaveSlotStorage', () => { currentShields: 1, remainingLives: 2, upgrades: { hp: 1, damage: 2, fireRate: 1, shield: 2, turrets: 1 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: 2, hp: 5 }] }, }); @@ -158,12 +158,12 @@ describe('SaveSlotStorage', () => { test('restores picked ship systems and names them on the slot', () => { installWindow(new MemoryStorage()); - const systems = { gun: 'seekers', support: 'surgeCore', late: 'overdrive' } as const; + const systems = { support: 'surgeCore', late: 'overdrive' } as const; expect(writeSaveSlot(record({ level: 9, systems }, {}, 'slot-2'))).not.toBeNull(); expect(readSaveSlot('slot-2')?.playerState.systems).toEqual(systems); - expect(slotView('slot-2').systemsLabel).toBe('SYSTEMS: SEEKERS · SURGE CORE · OVERDRIVE'); + expect(slotView('slot-2').systemsLabel).toBe('SYSTEMS: SURGE CORE · OVERDRIVE'); }); test('keeps the autosave apart from the manual slots until the run ends', () => { @@ -194,7 +194,7 @@ describe('SaveSlotStorage', () => { currentShields: 1, remainingLives: 2, upgrades: { hp: 1, damage: 2, fireRate: 1, shield: 2, turrets: 1 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: 2, hp: 5 }] }, }, { deathCause: 'beam' } @@ -320,7 +320,7 @@ describe('SaveSlotStorage', () => { currentHp: 5, remainingLives: 2, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 3 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [] }, }, runSummary: { finalScore: 900, levelReached: 4 }, @@ -362,7 +362,7 @@ describe('SaveSlotStorage', () => { currentShields: max, remainingLives: max, upgrades: { hp: max, damage: max, fireRate: max, shield: max, turrets: max }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: max, hp: max }] }, }, }, @@ -378,7 +378,7 @@ describe('SaveSlotStorage', () => { currentShields: 8, remainingLives: 3, upgrades: { hp: 5, damage: 4, fireRate: 4, shield: 3, turrets: 2 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: 3, hp: 15 }] }, }); expect(readSaveSlot('slot-1')?.runSummary.finalScore).toBe(Number.MAX_SAFE_INTEGER); diff --git a/tests/chainOverdrive.test.ts b/tests/chainOverdrive.test.ts index 8e1b62a..8aa03b4 100644 --- a/tests/chainOverdrive.test.ts +++ b/tests/chainOverdrive.test.ts @@ -99,10 +99,11 @@ function createFiringHarness(chainMultiplier: number) { getPicketTurrets: () => null, grazeSurge: { update: () => {} }, shipSystems: { - getSystems: () => ({ gun: null, support: null, late: null }), + getSystems: () => ({ support: null, late: null }), + getGun: () => null, + getGunCharge: () => 0, trySwapGun: () => 'unavailable', - isGunSilenced: () => false, - getGunSwapCooldownRatio: () => 0, + updateGunCharge: () => false, update: () => {}, }, gunSwapFeedback: { swapped: () => {}, denied: () => {} }, diff --git a/tests/combatFeedbackHandlers.test.ts b/tests/combatFeedbackHandlers.test.ts index 143f684..91bee9a 100644 --- a/tests/combatFeedbackHandlers.test.ts +++ b/tests/combatFeedbackHandlers.test.ts @@ -161,6 +161,8 @@ function createCombatFeedbackHarness( const showBossWarning = mock(); const showBossBar = mock(); const hitStop = mock(); + const recordGunChargeKill = mock(); + const resetGunCharge = mock(); const handlers = createGameSceneCombatFeedbackHandlers({ scene: { @@ -173,7 +175,9 @@ function createCombatFeedbackHarness( time: { now: 1000 }, } as never, player: player as never, - getShipSystems: () => ({ gun: null, support: null, late: options.late ?? null }), + getShipSystems: () => ({ support: null, late: options.late ?? null }), + recordGunChargeKill, + resetGunCharge, scoreManager: { addScore, registerKill, @@ -228,6 +232,8 @@ function createCombatFeedbackHarness( return { hitStop, + recordGunChargeKill, + resetGunCharge, clearBulletsAround, handlers, onPlayerHit, @@ -281,6 +287,7 @@ describe('createGameSceneCombatFeedbackHandlers', () => { expect(trySpawnRandomPowerUp).toHaveBeenCalledWith({ id: 'powerups' }, 12, 34); expect(spawnGuaranteedPowerUp).not.toHaveBeenCalled(); expect(harness.hitStop).not.toHaveBeenCalled(); + expect(harness.recordGunChargeKill).toHaveBeenCalledTimes(1); }); test('handleEnemyDeath grants a marked ace exactly one guaranteed drop and skips the random roll', () => { @@ -315,6 +322,7 @@ describe('createGameSceneCombatFeedbackHandlers', () => { expect(harness.createExplosion).toHaveBeenCalledWith(24, 48, 2.2, 0.6); expect(harness.handlePlayerDeath).toHaveBeenCalledWith(harness.flowContext, 'unknown'); expect(harness.syncLastLifeHelperWingState).toHaveBeenCalledTimes(1); + expect(harness.resetGunCharge).toHaveBeenCalledTimes(1); }); test('handlePlayerDeath suppresses helper wing sync when level completion remains queued', () => { @@ -353,6 +361,7 @@ describe('createGameSceneCombatFeedbackHandlers', () => { terminalHarness.handlers.handlePlayerDeath({ outcome: 'fatal', source: 'unknown', hullDamage: 1 }); expect(gameOverHarness.syncLastLifeHelperWingState).not.toHaveBeenCalled(); + expect(gameOverHarness.resetGunCharge).not.toHaveBeenCalled(); expect(terminalHarness.syncLastLifeHelperWingState).not.toHaveBeenCalled(); expect(terminalHarness.handlePlayerDeath).toHaveBeenCalledWith(terminalHarness.flowContext, 'unknown'); expect(terminalHarness.player.playDeathAnimation).not.toHaveBeenCalled(); diff --git a/tests/e2e/directRetry.spec.ts b/tests/e2e/directRetry.spec.ts index a6c8be2..c08cd5b 100644 --- a/tests/e2e/directRetry.spec.ts +++ b/tests/e2e/directRetry.spec.ts @@ -45,7 +45,7 @@ test('retry resets a loaded run while preserving checkpoints and settings', asyn remainingLives: 1, currentShields: 2, upgrades: { hp: 2, damage: 2, fireRate: 2, shield: 2, turrets: 1 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ hp: 4, remainingLives: 1 }] }, }, { finalScore: 9500, levelReached: 4 } @@ -96,7 +96,7 @@ test('retry resets a loaded run while preserving checkpoints and settings', asyn remainingLives: 3, currentShields: 0, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 0, turrets: 0 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [] }, }); // Retry changes nothing that was stored, apart from recording the lost run's score as the best. diff --git a/tests/e2e/shipSystems.spec.ts b/tests/e2e/shipSystems.spec.ts index 4579e3d..d67eea4 100644 --- a/tests/e2e/shipSystems.spec.ts +++ b/tests/e2e/shipSystems.spec.ts @@ -1,6 +1,6 @@ import { expect, openMenu, pinQualityTier, snapshot, startNewRun, test, waitForScene, type Page } from './fixtures'; -/** The pause panel's SYSTEMS card for one slot, e.g. `MAIN GUN`. */ +/** The pause panel's SYSTEMS card for one slot, e.g. `SUPPORT SYSTEM`. */ function systemRow(page: Page, slotTitle: string) { return page.locator('.pause-system').filter({ hasText: slotTitle }); } @@ -42,78 +42,32 @@ async function openPause(page: Page, isMobile: boolean): Promise { if (!isMobile) await page.keyboard.up('Escape'); } -test('a free main-gun pick is offered after sector 2, must be made, and changes how the gun fires', async ({ +async function gunState(page: Page) { + return (await snapshot(page)).gun; +} + +test('no main-gun pick after sectors 1 and 2: the refit bay goes straight to the upgrades', async ({ page, - isMobile, assertNoBrowserErrors, }) => { test.setTimeout(120_000); await pinQualityTier(page, 'low'); - await page.addInitScript(() => - window.localStorage.setItem('space-explorer.autoFire.v1', JSON.stringify({ touch: true, keyboard: true })) - ); await openMenu(page); await startNewRun(page); - // Sector 1 is part of the gentle opening: no pick yet. - await page.evaluate(() => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.showPlanetIntermission(1)); - await waitForScene(page, 'PlanetIntermission'); - await expect(page.getByRole('dialog')).toHaveCount(0); - await expect(page.getByRole('group', { name: 'Ship systems' })).toHaveCount(0); - - await page.evaluate(() => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.showPlanetIntermission(2)); - const dialog = page.getByRole('dialog', { name: 'CHOOSE YOUR MAIN GUN' }); - await expect(dialog).toBeVisible(); - for (const name of ['LANCE', 'SCATTER', 'SEEKERS']) { - await expect(dialog.getByRole('button', { name: new RegExp(`^${name}`) })).toBeInViewport({ ratio: 1 }); + for (const level of [1, 2]) { + await page.evaluate((cleared) => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.showPlanetIntermission(cleared), level); + await waitForScene(page, 'PlanetIntermission'); + await expect(page.getByRole('button', { name: /Continue to/ })).toBeVisible(); + await expect(page.getByRole('dialog')).toHaveCount(0); + await expect(page.getByRole('group', { name: 'Ship systems' })).toHaveCount(0); } - await page.screenshot({ path: test.info().outputPath('system-pick.png') }); + await page.screenshot({ path: test.info().outputPath('refit-after-sector-2.png') }); - // The refit bay behind the dialog cannot be reached: Tab stays on the three options. - for (let press = 0; press < 5; press += 1) { - await page.keyboard.press('Tab'); - expect(await dialog.evaluate((element) => element.contains(document.activeElement))).toBe(true); - } - expect(await page.locator('.refit').evaluate((element) => (element.closest('.ui-layer') as HTMLElement).inert)).toBe( - true - ); - - // The run waits for the pick: neither a plain key nor Escape carries on or closes the dialog. Both are - // held across game frames so Phaser would see them. - await page.keyboard.down('KeyX'); - await page.keyboard.down('Escape'); - await page.waitForTimeout(600); - await page.keyboard.up('Escape'); - await page.keyboard.up('KeyX'); - expect((await snapshot(page)).activeScenes).toContain('PlanetIntermission'); - await expect(dialog).toBeVisible(); - - await dialog.getByRole('button', { name: /^SCATTER/ }).click(); - await expect(page.getByRole('dialog')).toHaveCount(0); - await expect(page.locator('.ui-layer')).toHaveCount(1); - expect(await page.locator('.refit').evaluate((element) => (element.closest('.ui-layer') as HTMLElement).inert)).toBe( - false - ); + // Sector 3 flies Lance with a full charge. await page.getByRole('button', { name: /Continue to/ }).click(); await waitForScene(page, 'Game'); - if (isMobile) await page.touchscreen.tap(195, 700); - - // Scatter fans its shots: some fly at an angle, which the standard gun never does. - await expect - .poll(async () => - (await snapshot(page)).objects.some( - (object) => object.active && object.textureKey === 'player-bullet' && Math.abs(object.rotation) > 0.1 - ) - ) - .toBe(true); - - // The pause panel names the pick. - if (!isMobile) { - await openPause(page, false); - await page.getByRole('tab', { name: 'SYSTEMS' }).click(); - await expect(systemRow(page, 'MAIN GUN')).toContainText('SCATTER'); - await page.screenshot({ path: test.info().outputPath('pause-systems.png') }); - } + await expect.poll(() => gunState(page)).toEqual({ id: 'lance', charge: 1 }); assertNoBrowserErrors(); }); @@ -123,45 +77,47 @@ test('a picked system can be kept or swapped for free at a later refit bay, and assertNoBrowserErrors, }) => { test.setTimeout(120_000); - await startSector(page, 3, 'lance'); - await page.evaluate(() => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.showPlanetIntermission(3)); + await startSector(page, 6, 'magnet'); + await page.evaluate(() => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.showPlanetIntermission(6)); await waitForScene(page, 'PlanetIntermission'); - const gun = page.getByRole('group', { name: 'Ship systems' }).getByRole('button', { name: /^Swap main gun/ }); - await expect(gun).toHaveAccessibleName('Swap main gun, now LANCE'); - await expect(gun).toBeInViewport({ ratio: 1 }); + const systems = page.getByRole('group', { name: 'Ship systems' }); + await expect(systems.getByRole('button', { name: /^Swap main gun/ })).toHaveCount(0); + const support = systems.getByRole('button', { name: /^Swap support system/ }); + await expect(support).toHaveAccessibleName('Swap support system, now MAGNET'); + await expect(support).toBeInViewport({ ratio: 1 }); await page.screenshot({ path: test.info().outputPath('refit-systems.png') }); // Reopening shows the same three options with the current one marked and focused. Dismissing keeps it: // Escape on a keyboard, the current option on touch. - const dialog = page.getByRole('dialog', { name: 'SWAP YOUR MAIN GUN' }); - const current = dialog.getByRole('button', { name: /^LANCE/ }); - await gun.click(); + const dialog = page.getByRole('dialog', { name: 'SWAP YOUR SUPPORT SYSTEM' }); + const current = dialog.getByRole('button', { name: /^MAGNET/ }); + await support.click(); await expect(current).toHaveAttribute('aria-pressed', 'true'); await expect(current).toBeFocused(); - await expect(dialog.getByRole('button', { name: /^SCATTER/ })).toHaveAttribute('aria-pressed', 'false'); + await expect(dialog.getByRole('button', { name: /^WINGMAN/ })).toHaveAttribute('aria-pressed', 'false'); expect(await page.locator('.refit').evaluate((element) => (element.closest('.ui-layer') as HTMLElement).inert)).toBe( true ); - await page.screenshot({ path: test.info().outputPath('refit-swap-dialog.png') }); if (isMobile) await current.tap(); else await page.keyboard.press('Escape'); await expect(dialog).toHaveCount(0); - await expect(gun).toHaveAccessibleName('Swap main gun, now LANCE'); - await expect(gun).toBeFocused(); + await expect(support).toHaveAccessibleName('Swap support system, now MAGNET'); + await expect(support).toBeFocused(); // Neither opening nor closing the dialog carried on to the next sector. await page.waitForTimeout(600); expect((await snapshot(page)).activeScenes).toContain('PlanetIntermission'); - await gun.click(); - await dialog.getByRole('button', { name: /^SCATTER/ }).click(); - await expect(gun).toHaveAccessibleName('Swap main gun, now SCATTER'); + await support.click(); + await dialog.getByRole('button', { name: /^WINGMAN/ }).click(); + await expect(support).toHaveAccessibleName('Swap support system, now WINGMAN'); await page.getByRole('button', { name: /Continue to/ }).click(); await waitForScene(page, 'Game'); - if (isMobile) await page.touchscreen.tap(195, 700); - await expect.poll(async () => (await playerShots(page)).some((shot) => Math.abs(shot.rotation) > 0.1)).toBe(true); + await expect.poll(() => wingmanDrones(page)).toBe(1); await openPause(page, isMobile); await page.getByRole('tab', { name: 'SYSTEMS' }).click(); - await expect(systemRow(page, 'MAIN GUN')).toContainText('SCATTER'); + await expect(systemRow(page, 'SUPPORT SYSTEM')).toContainText('WINGMAN'); + await expect(systemRow(page, 'MAIN GUN')).toHaveCount(0); + await page.screenshot({ path: test.info().outputPath('pause-systems-tab.png') }); assertNoBrowserErrors(); }); @@ -172,13 +128,15 @@ test('every ship system runs in a real sector without errors', async ({ page, is await page.addInitScript(() => window.localStorage.setItem('space-explorer.autoFire.v1', JSON.stringify({ touch: true, keyboard: true })) ); - for (const systems of ['lance,magnet,overdrive', 'scatter,surgeCore,bulwark', 'seekers,wingman,salvager']) { - await page.goto(`/?browserHarness=1&startLevel=5&systems=${systems}`); + for (const systems of ['magnet,overdrive', 'surgeCore,bulwark', 'wingman,salvager']) { + await page.goto(`/?browserHarness=1&startLevel=9&systems=${systems}`); await waitForScene(page, 'Game'); await expect .poll(async () => (await snapshot(page)).objects.some((o) => o.active && o.textureKey === 'player-bullet')) .toBe(true); + // Fly a sweep with each gun: Lance, then both special guns. for (let sweep = 0; sweep < 6; sweep += 1) { + if (sweep % 2 === 0 && sweep > 0) await page.keyboard.press('KeyQ'); const key = sweep % 2 ? 'ArrowLeft' : 'ArrowRight'; await page.keyboard.down(key); await page.waitForTimeout(900); @@ -186,58 +144,59 @@ test('every ship system runs in a real sector without errors', async ({ page, is } await openPause(page, false); await page.getByRole('tab', { name: 'SYSTEMS' }).click(); - const [gun, support, late] = systems.split(','); + const [support, late] = systems.split(','); const label = { surgeCore: 'SURGE CORE' }[support] ?? support.toUpperCase(); - await expect(systemRow(page, 'MAIN GUN')).toContainText(gun.toUpperCase()); await expect(systemRow(page, 'SUPPORT SYSTEM')).toContainText(label); await expect(systemRow(page, 'COMBAT DOCTRINE')).toContainText(late.toUpperCase()); - await page.screenshot({ path: test.info().outputPath(`systems-${gun}.png`) }); + await page.screenshot({ path: test.info().outputPath(`systems-${support}.png`) }); } assertNoBrowserErrors(); }); -test('the main gun swaps mid-sector on Q or the touch key, and a second swap waits for the cooldown', async ({ +test('in sector 3 the swap key borrows a special gun until the charge runs out, then Lance comes back', async ({ page, isMobile, assertNoBrowserErrors, }) => { - test.setTimeout(90_000); - await startSector(page, 3, 'lance'); + test.setTimeout(120_000); + await startSector(page, 3, ''); const swap = async (): Promise => { if (isMobile) await page.touchscreen.tap(TOUCH_KEY_X, TOUCH_SWAP_Y); else await page.keyboard.press('KeyQ'); }; - // Lance fires long piercing bolts straight ahead. + // Lance fires long piercing bolts straight ahead, and the meter starts full. await expect.poll(async () => (await playerShots(page)).length).toBeGreaterThan(0); expect((await playerShots(page)).every((shot) => Math.abs(shot.rotation) < 0.01 && shot.frameName === 'lance')).toBe( true ); + expect(await gunState(page)).toEqual({ id: 'lance', charge: 1 }); + await expect.poll(() => shownTexts(page)).toContain('LANCE'); + await page.screenshot({ path: test.info().outputPath('lance-full-charge.png') }); await swap(); + await expect.poll(async () => (await gunState(page))?.id).toBe('scatter'); await expect.poll(() => shownTexts(page)).toContain('SCATTER'); - await page.screenshot({ path: test.info().outputPath('swap-flash.png') }); - // A second press inside the cooldown is ignored: the gun stays Scatter. - await swap(); - if (isMobile) await page.screenshot({ path: test.info().outputPath('swap-key-cooling.png') }); - await page.waitForTimeout(300); - expect(await shownTexts(page)).not.toContain('SEEKERS'); - - // Scatter fans its shots, and they are pellets. + // Scatter fans its shots, and they are pellets; the charge drains while it is out. await expect .poll(async () => (await playerShots(page)).some((shot) => Math.abs(shot.rotation) > 0.1 && shot.frameName === 'pellet') ) .toBe(true); + await expect.poll(async () => (await gunState(page))?.charge ?? 1, { timeout: 30_000 }).toBeLessThan(0.7); + await page.screenshot({ path: test.info().outputPath('special-gun-draining.png') }); - await openPause(page, isMobile); - await page.getByRole('tab', { name: 'SYSTEMS' }).click(); - await expect(systemRow(page, 'MAIN GUN')).toContainText('SCATTER'); - await page.screenshot({ path: test.info().outputPath('pause-systems-tab.png') }); + // On to Seekers is always allowed, and the empty meter hands back Lance on its own. + await swap(); + await expect.poll(async () => (await gunState(page))?.id).toBe('seekers'); + await expect.poll(async () => (await gunState(page))?.id, { timeout: 90_000 }).toBe('lance'); + // It comes back nearly empty and refills from there (the refusal below the threshold is unit-tested). + expect((await gunState(page))!.charge).toBeLessThan(0.5); + await expect.poll(() => shownTexts(page)).toContain('LANCE'); assertNoBrowserErrors(); }); -test('sectors 1-2 have no swap: Q does nothing and the pause panel has no SYSTEMS tab', async ({ +test('sectors 1-2 have no swap: Q does nothing, no meter, and the pause panel has no SYSTEMS tab', async ({ page, isMobile, assertNoBrowserErrors, @@ -247,6 +206,7 @@ test('sectors 1-2 have no swap: Q does nothing and the pause panel has no SYSTEM if (!isMobile) await page.keyboard.press('KeyQ'); await page.waitForTimeout(300); expect(await shownTexts(page)).not.toContain('LANCE'); + expect(await gunState(page)).toBeNull(); if (isMobile) await page.screenshot({ path: test.info().outputPath('no-swap-key.png') }); await openPause(page, isMobile); await expect(page.getByRole('tab', { name: 'SYSTEMS' })).toBeHidden(); @@ -259,7 +219,7 @@ test('switching support to Wingman from the pause panel launches the drone; swit assertNoBrowserErrors, }) => { test.setTimeout(90_000); - await startSector(page, 6, 'lance,surgeCore'); + await startSector(page, 6, 'surgeCore'); await expect.poll(async () => (await playerShots(page)).length).toBeGreaterThan(0); expect(await wingmanDrones(page)).toBe(0); @@ -281,49 +241,6 @@ test('switching support to Wingman from the pause panel launches the drone; swit assertNoBrowserErrors(); }); -test('a swapped gun carries into the next sector and is what a checkpoint stores @desktop-only', async ({ - page, - assertNoBrowserErrors, -}) => { - test.setTimeout(120_000); - await startSector(page, 3, 'lance'); - await expect.poll(async () => (await playerShots(page)).length).toBeGreaterThan(0); - await page.keyboard.press('KeyQ'); - await expect.poll(() => shownTexts(page)).toContain('SCATTER'); - - // Checkpoint with Scatter, then fly on to the next sector. - await openPause(page, false); - await page.getByRole('button', { name: 'Save to SLOT 1' }).click(); - await expect(page.getByText(/checkpoint to slot 1/)).toBeVisible(); - await page.getByRole('button', { name: 'RESUME' }).click(); - await page.evaluate(() => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.showPlanetIntermission(3)); - await page.getByRole('button', { name: /Continue to/ }).click(); - await waitForScene(page, 'Game'); - - await openPause(page, false); - await page.getByRole('tab', { name: 'SYSTEMS' }).click(); - await expect(systemRow(page, 'MAIN GUN')).toContainText('SCATTER'); - await page.getByRole('button', { name: 'RESUME' }).click(); - - // Swap on to Seekers, then load the checkpoint: it brings back the Scatter it stored. - await page.waitForTimeout(300); - await page.keyboard.press('KeyQ'); - await expect.poll(() => shownTexts(page)).toContain('SEEKERS'); - await openPause(page, false); - await page - .getByRole('button', { name: /^Load / }) - .first() - .click(); - // The load restarts the Game scene, so "Game is active" is true before and after. The old pause panel - // closing is what marks the restart; only then is a new pause the loaded run's. - await expect(page.getByRole('dialog', { name: 'Paused' })).toBeHidden(); - await expect.poll(async () => (await playerShots(page)).length).toBeGreaterThan(0); - await openPause(page, false); - await page.getByRole('tab', { name: 'SYSTEMS' }).click(); - await expect(systemRow(page, 'MAIN GUN')).toContainText('SCATTER'); - assertNoBrowserErrors(); -}); - test('leaving the refit bay autosaves the run, picks included, until the run ends', async ({ page, isMobile, @@ -335,10 +252,10 @@ test('leaving the refit bay autosaves the run, picks included, until the run end await expect(page.getByRole('button', { name: /^Load AUTOSAVE/ })).toHaveCount(0); await startNewRun(page); - await page.evaluate(() => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.showPlanetIntermission(2)); + await page.evaluate(() => window.__SPACE_EXPLORER_BROWSER_HARNESS__!.showPlanetIntermission(5)); await page - .getByRole('dialog', { name: 'CHOOSE YOUR MAIN GUN' }) - .getByRole('button', { name: /^SCATTER/ }) + .getByRole('dialog', { name: 'CHOOSE YOUR SUPPORT SYSTEM' }) + .getByRole('button', { name: /^MAGNET/ }) .click(); await page.getByRole('button', { name: /Continue to/ }).click(); await waitForScene(page, 'Game'); @@ -348,15 +265,15 @@ test('leaving the refit bay autosaves the run, picks included, until the run end await waitForScene(page, 'Menu'); const autosave = page.getByRole('button', { name: /^Load AUTOSAVE/ }); await expect(autosave).toBeVisible(); - await expect(autosave).toContainText('LVL 3'); - await expect(autosave).toContainText('SYSTEMS: SCATTER'); + await expect(autosave).toContainText('LVL 6'); + await expect(autosave).toContainText('SYSTEMS: MAGNET'); await page.screenshot({ path: test.info().outputPath('menu-autosave.png') }); await autosave.click(); await waitForScene(page, 'Game'); await openPause(page, isMobile); await page.getByRole('tab', { name: 'SYSTEMS' }).click(); - await expect(systemRow(page, 'MAIN GUN')).toContainText('SCATTER'); + await expect(systemRow(page, 'SUPPORT SYSTEM')).toContainText('MAGNET'); // The autosave is not one of the pause panel's checkpoints. await expect(page.getByRole('button', { name: /AUTOSAVE/ })).toHaveCount(0); diff --git a/tests/gameplayFrameBehaviorPerformance.test.ts b/tests/gameplayFrameBehaviorPerformance.test.ts index f5eb1a5..4ff6aca 100644 --- a/tests/gameplayFrameBehaviorPerformance.test.ts +++ b/tests/gameplayFrameBehaviorPerformance.test.ts @@ -74,10 +74,11 @@ function createHarness(level = 1): { getPicketTurrets: () => null, grazeSurge: { update: () => {} }, shipSystems: { - getSystems: () => ({ gun: null, support: null, late: null }), + getSystems: () => ({ support: null, late: null }), + getGun: () => null, + getGunCharge: () => 0, trySwapGun: () => 'unavailable', - isGunSilenced: () => false, - getGunSwapCooldownRatio: () => 0, + updateGunCharge: () => false, update: () => {}, }, gunSwapFeedback: { swapped: () => {}, denied: () => {} }, diff --git a/tests/gunSwap.test.ts b/tests/gunSwap.test.ts deleted file mode 100644 index 8af7901..0000000 --- a/tests/gunSwap.test.ts +++ /dev/null @@ -1,270 +0,0 @@ -import { describe, expect, mock, test } from 'bun:test'; - -mock.module('phaser', () => ({ - default: { - Math: { - Vector2: class { - x = 0; - y = 0; - }, - }, - }, -})); - -mock.module('../src/systems/AudioManager', () => ({ - audioManager: { playSfx: () => {}, setMusicIntensity: () => {} }, -})); - -const { getLevelConfig } = await import('../src/config/LevelsConfig'); -const { GUN_SWAP, NO_SHIP_SYSTEMS } = await import('../src/config/shipSystems'); -const { getPlayerState } = await import('../src/systems/PlayerState'); -const { ShipSystemsRuntime } = await import('../src/systems/ShipSystemsRuntime'); -const { createGameSceneGameplayFrameBehavior } = await import('../src/scenes/gameScene/gameplayFrameBehavior'); -const { GameplayClock, runGameSceneUpdateFrame } = await import('../src/scenes/gameScene/updateFrame'); - -type ShipSystems = typeof NO_SHIP_SYSTEMS; -type GameplayDelegate = Parameters[0]; - -function createRegistry() { - const values = new Map(); - return { get: (key: string) => values.get(key), set: (key: string, value: unknown) => values.set(key, value) }; -} - -function createRuntime(systems: Partial) { - const registry = createRegistry(); - const drones: Array<{ destroyed: boolean }> = []; - const pickup = { - active: true, - x: 0, - y: 0, - velocity: [0, 0], - setVelocity(x: number, y: number) { - pickup.velocity = [x, y]; - }, - }; - const scene = { - registry, - add: { - image: () => { - const drone = { - destroyed: false, - setScale: () => drone, - setDepth: () => drone, - destroy: () => { - drone.destroyed = true; - }, - }; - drones.push(drone); - return drone; - }, - }, - }; - const ship = { x: 0, y: 100, isAlive: true }; - const runtime = new ShipSystemsRuntime(scene as never, ship, { getChildren: () => [pickup] } as never, { - ...NO_SHIP_SYSTEMS, - ...systems, - }); - return { runtime, registry, drones, pickup }; -} - -describe('live ship-system changes', () => { - test('a run without a main gun cannot swap and its gun is never silenced', () => { - const { runtime } = createRuntime({}); - expect(runtime.trySwapGun(1000)).toBe('unavailable'); - expect(runtime.isGunSilenced(1000)).toBe(false); - expect(runtime.getGunSwapCooldownRatio(1000)).toBe(0); - expect(runtime.getSystems()).toEqual(NO_SHIP_SYSTEMS); - }); - - test('a swap cycles the gun, keeps it for the run, silences it briefly and then cools down', () => { - const { runtime, registry } = createRuntime({ gun: 'lance' }); - expect(runtime.isGunSilenced(0)).toBe(false); - - expect(runtime.trySwapGun(1000)).toBe('swapped'); - expect(runtime.getSystems().gun).toBe('scatter'); - expect(getPlayerState(registry).systems.gun).toBe('scatter'); - - expect(runtime.isGunSilenced(1000 + GUN_SWAP.fireSilenceMs - 1)).toBe(true); - expect(runtime.isGunSilenced(1000 + GUN_SWAP.fireSilenceMs)).toBe(false); - - expect(runtime.trySwapGun(1000 + GUN_SWAP.cooldownMs - 1)).toBe('cooling'); - expect(runtime.getSystems().gun).toBe('scatter'); - expect(runtime.trySwapGun(1000 + GUN_SWAP.cooldownMs)).toBe('swapped'); - expect(runtime.getSystems().gun).toBe('seekers'); - }); - - test('changing support leaves the gun firing', () => { - const { runtime } = createRuntime({ gun: 'seekers', support: 'magnet' }); - runtime.cycleSystem('support', 500); - expect(runtime.isGunSilenced(500)).toBe(false); - expect(runtime.trySwapGun(500)).toBe('swapped'); - }); - - test('switching support to Wingman launches the drone and switching away removes it', () => { - const { runtime, drones } = createRuntime({ gun: 'lance', support: 'surgeCore' }); - expect(drones).toHaveLength(0); - runtime.cycleSystem('support', 0); - expect(runtime.getSystems().support).toBe('wingman'); - expect(drones).toHaveLength(1); - runtime.cycleSystem('support', 0); - expect(runtime.getSystems().support).toBe('magnet'); - expect(drones[0].destroyed).toBe(true); - }); - - test('switching away from Magnet lets go of the pickups it was pulling', () => { - const { runtime, pickup } = createRuntime({ support: 'magnet' }); - runtime.update(); - expect(pickup.velocity[1]).toBeGreaterThan(60); - runtime.cycleSystem('support', 0); - expect(pickup.velocity).toEqual([0, 60]); - }); -}); - -function createFrameHarness(systems: Partial) { - const { runtime } = createRuntime(systems); - const clock = new GameplayClock(); - const shots: number[] = []; - const feedback: string[] = []; - const buttonStates: Array<[boolean, number]> = []; - let swapPressed = false; - let paused = false; - let realTime = 0; - const vector = { x: 0, y: 0 } as GameplayDelegate['shotDirection']; - const levelConfig = getLevelConfig(3); - const behavior = createGameSceneGameplayFrameBehavior({ - inputManager: { - consumePauseToggleRequest: () => false, - consumeGunSwapRequest: () => { - const pressed = swapPressed; - swapPressed = false; - return pressed; - }, - isFiring: () => true, - }, - pauseStateController: { togglePauseRequest: () => {}, isGameplayPaused: () => paused }, - flow: { - isGameplayLocked: () => false, - sampleRespawnTransitionFrame: () => {}, - isTerminalTransitionActive: () => false, - }, - parallax: { update: () => {}, setSectionAtmosphere: () => {} }, - player: { - isAlive: true, - fireRate: 150, - getFireDirection: (out) => out, - getMuzzlePosition: (_distance, out) => out, - update: () => {}, - }, - getLastLifeHelperWing: () => null, - getPicketTurrets: () => null, - shipSystems: runtime, - gunSwapFeedback: { - swapped: (gun) => feedback.push(gun), - denied: () => feedback.push('denied'), - }, - mobileControls: { setGunSwapState: (available, ratio) => buttonStates.push([available, ratio]) }, - grazeSurge: { update: () => {} }, - waveManager: { update: () => {}, updateBossAdds: () => {}, getDuelHull: () => null }, - levelManager: { - progress: 0, - hasBossSpawned: () => false, - isComplete: () => false, - update: () => {}, - getLevelConfig: () => levelConfig, - shouldSpawnBoss: () => false, - }, - scoreManager: { getChainState: () => ({ chain: 0, multiplier: 1 }) }, - events: { emit: () => {} }, - hud: { showBossBar: () => {}, hideBossBar: () => {}, updateBossHp: () => {} }, - bulletPool: { fire: () => shots.push(clock.now) }, - findBulletTarget: () => null, - effectsManager: { createMuzzleFlash: () => {}, updateLighting: () => {} }, - getBoss: () => null, - updateHud: () => {}, - shotDirection: vector, - shotOrigin: { ...vector } as GameplayDelegate['shotOrigin'], - muzzleFlashOrigin: { ...vector } as GameplayDelegate['muzzleFlashOrigin'], - }); - - /** Runs real frames of 16 ms; gameplay time only moves while unpaused. */ - const run = (ms: number): void => { - for (let elapsed = 0; elapsed < ms; elapsed += 16) { - realTime += 16; - runGameSceneUpdateFrame(behavior, realTime, 16, clock); - } - }; - - return { - runtime, - clock, - shots, - feedback, - buttonStates, - run, - pressSwap: () => { - swapPressed = true; - }, - setPaused: (next: boolean) => { - paused = next; - }, - }; -} - -describe('gun swap during play', () => { - test('swapping silences the gun for the swap delay, and a pause does not run it down', () => { - const harness = createFrameHarness({ gun: 'lance' }); - harness.run(400); - expect(harness.shots.length).toBeGreaterThan(0); - - harness.pressSwap(); - harness.run(16); - const swappedAt = harness.clock.now; - expect(harness.feedback).toEqual(['scatter']); - const shotsBeforeSilence = harness.shots.length; - - harness.run(200); - harness.setPaused(true); - harness.run(5000); - harness.setPaused(false); - harness.run(200); - expect(harness.shots.length).toBe(shotsBeforeSilence); - - harness.run(GUN_SWAP.fireSilenceMs); - const firstShotAfterSwap = harness.shots[shotsBeforeSilence]; - expect(firstShotAfterSwap - swappedAt).toBeGreaterThanOrEqual(GUN_SWAP.fireSilenceMs); - }); - - test('a second press inside the cooldown is refused quietly and changes nothing', () => { - const harness = createFrameHarness({ gun: 'scatter' }); - harness.pressSwap(); - harness.run(16); - harness.run(GUN_SWAP.cooldownMs / 2); - harness.pressSwap(); - harness.run(16); - expect(harness.feedback).toEqual(['seekers', 'denied']); - expect(harness.runtime.getSystems().gun).toBe('seekers'); - const [available, ratio] = harness.buttonStates.at(-1)!; - expect(available).toBe(true); - expect(ratio).toBeGreaterThan(0.4); - }); - - test('a press while paused is dropped, not saved for resume', () => { - const harness = createFrameHarness({ gun: 'lance' }); - harness.setPaused(true); - harness.pressSwap(); - harness.run(32); - harness.setPaused(false); - harness.run(32); - expect(harness.feedback).toEqual([]); - expect(harness.runtime.getSystems().gun).toBe('lance'); - }); - - test('without a main gun the key does nothing and the touch button stays hidden', () => { - const harness = createFrameHarness({}); - harness.pressSwap(); - harness.run(400); - expect(harness.feedback).toEqual([]); - expect(harness.buttonStates.every(([available]) => !available)).toBe(true); - expect(harness.shots.length).toBeGreaterThan(0); - }); -}); diff --git a/tests/mainGun.test.ts b/tests/mainGun.test.ts index c09468e..31ec37d 100644 --- a/tests/mainGun.test.ts +++ b/tests/mainGun.test.ts @@ -1,10 +1,17 @@ import { describe, expect, mock, test } from 'bun:test'; -import { getMainGunProfile, NO_SHIP_SYSTEMS, type PlayerShotLook, type ShipSystems } from '../src/config/shipSystems'; +import { + getMainGunProfile, + NO_SHIP_SYSTEMS, + type MainGunId, + type PlayerShotLook, + type ShipSystems, +} from '../src/config/shipSystems'; import { fireMainGunVolley, resolveMainGunCooldownMs } from '../src/systems/mainGun'; -function volley(systems: Partial, volleyIndex = 1) { +function volley(gun: MainGunId | null, systems: Partial = {}, volleyIndex = 1) { const fire = mock(); fireMainGunVolley({ + gun, systems: { ...NO_SHIP_SYSTEMS, ...systems }, volleyIndex, origin: { x: 100, y: 500 }, @@ -20,19 +27,19 @@ function volley(systems: Partial, volleyIndex = 1) { describe('main gun', () => { test('the standard gun fires one plain bolt straight ahead', () => { - const shots = volley({}); + const shots = volley(null); expect(shots).toHaveLength(1); expect(shots[0].slice(0, 4)).toEqual([100, 500, 0, -600]); expect(shots[0][4]).toBeUndefined(); }); test('Lance fires one piercing shot, Seekers one seeking shot', () => { - expect(volley({ gun: 'lance' })[0][4]?.pierce).toBe(true); - expect(volley({ gun: 'seekers' })[0][4]?.seekDegreesPerSecond).toBeGreaterThan(0); + expect(volley('lance')[0][4]?.pierce).toBe(true); + expect(volley('seekers')[0][4]?.seekDegreesPerSecond).toBeGreaterThan(0); }); test('Scatter fires three shots fanned evenly around straight ahead, all at full speed', () => { - const shots = volley({ gun: 'scatter' }); + const shots = volley('scatter'); expect(shots).toHaveLength(3); const [left, centre, right] = shots; expect(centre[2]).toBeCloseTo(0); @@ -42,26 +49,26 @@ describe('main gun', () => { }); test('Wingman adds a plain bolt from the drone on every other volley', () => { - expect(volley({ support: 'wingman', gun: 'lance' }, 1)).toHaveLength(1); - const shots = volley({ support: 'wingman', gun: 'lance' }, 2); + expect(volley('lance', { support: 'wingman' }, 1)).toHaveLength(1); + const shots = volley('lance', { support: 'wingman' }, 2); expect(shots).toHaveLength(2); expect(shots[1][0]).toBeGreaterThan(100); expect(shots[1][4]).toBeUndefined(); }); test('each gun fires in its own look; the standard gun and the Wingman keep the plain bolt', () => { - expect(volley({}).map((shot) => shot[5])).toEqual(['bolt']); - expect(volley({ gun: 'lance' }).map((shot) => shot[5])).toEqual(['lance']); - expect(volley({ gun: 'scatter' }).map((shot) => shot[5])).toEqual(['pellet', 'pellet', 'pellet']); - expect(volley({ gun: 'seekers' }).map((shot) => shot[5])).toEqual(['dart']); + expect(volley(null).map((shot) => shot[5])).toEqual(['bolt']); + expect(volley('lance').map((shot) => shot[5])).toEqual(['lance']); + expect(volley('scatter').map((shot) => shot[5])).toEqual(['pellet', 'pellet', 'pellet']); + expect(volley('seekers').map((shot) => shot[5])).toEqual(['dart']); // The drone's shot leaves the look out, so the bullet keeps its standard bolt. - expect(volley({ support: 'wingman', gun: 'lance' }, 2)[1][5]).toBeUndefined(); + expect(volley('lance', { support: 'wingman' }, 2)[1][5]).toBeUndefined(); }); test('each gun pays for its pattern with a slower cooldown', () => { - expect(resolveMainGunCooldownMs(150, 1, NO_SHIP_SYSTEMS)).toBe(150); + expect(resolveMainGunCooldownMs(150, 1, null, NO_SHIP_SYSTEMS)).toBe(150); for (const gun of ['lance', 'scatter', 'seekers'] as const) { - const cooldown = resolveMainGunCooldownMs(150, 1, { ...NO_SHIP_SYSTEMS, gun }); + const cooldown = resolveMainGunCooldownMs(150, 1, gun, NO_SHIP_SYSTEMS); expect(cooldown).toBeCloseTo(150 * getMainGunProfile(gun).cooldownScale); expect(cooldown).toBeGreaterThan(150); } @@ -85,10 +92,10 @@ describe('main gun', () => { test('Overdrive speeds the gun up with every chain step; without it only the max chain does', () => { const overdrive = { ...NO_SHIP_SYSTEMS, late: 'overdrive' as const }; - expect(resolveMainGunCooldownMs(150, 1, overdrive)).toBe(150); - expect(resolveMainGunCooldownMs(150, 3, overdrive)).toBeCloseTo(150 * 0.88); - expect(resolveMainGunCooldownMs(150, 5, overdrive)).toBeCloseTo(150 * 0.76); - expect(resolveMainGunCooldownMs(150, 3, NO_SHIP_SYSTEMS)).toBe(150); - expect(resolveMainGunCooldownMs(150, 5, NO_SHIP_SYSTEMS)).toBeCloseTo(150 * 0.85); + expect(resolveMainGunCooldownMs(150, 1, null, overdrive)).toBe(150); + expect(resolveMainGunCooldownMs(150, 3, null, overdrive)).toBeCloseTo(150 * 0.88); + expect(resolveMainGunCooldownMs(150, 5, null, overdrive)).toBeCloseTo(150 * 0.76); + expect(resolveMainGunCooldownMs(150, 3, null, NO_SHIP_SYSTEMS)).toBe(150); + expect(resolveMainGunCooldownMs(150, 5, null, NO_SHIP_SYSTEMS)).toBeCloseTo(150 * 0.85); }); }); diff --git a/tests/rivalDuel.test.ts b/tests/rivalDuel.test.ts index 142ac59..b1868de 100644 --- a/tests/rivalDuel.test.ts +++ b/tests/rivalDuel.test.ts @@ -147,7 +147,7 @@ describe('rival duel hold', () => { getLastLifeHelperWing: () => null, getPicketTurrets: () => null, grazeSurge: { update: noop }, - shipSystems: { update: noop, getSystems: () => ({ gun: null }), getGunSwapCooldownRatio: () => 0 }, + shipSystems: { update: noop, getSystems: () => ({}), getGun: () => null, updateGunCharge: () => false }, mobileControls: null, waveManager: { update: waveUpdate, updateBossAdds: noop, getDuelHull: () => duel }, levelManager: { diff --git a/tests/shipSystems.test.ts b/tests/shipSystems.test.ts index 68fd346..7cc8acb 100644 --- a/tests/shipSystems.test.ts +++ b/tests/shipSystems.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from 'bun:test'; import { describePickedShipSystems, + getNextMainGun, getPendingShipSystemSlot, getShipSystemSlot, NO_SHIP_SYSTEMS, @@ -15,62 +16,74 @@ describe('ship systems', () => { expect(getPendingShipSystemSlot(1, NO_SHIP_SYSTEMS)).toBeNull(); }); - test('the main gun is offered after sector 2, support after 5, doctrine after 8', () => { - expect(getPendingShipSystemSlot(2, NO_SHIP_SYSTEMS)?.slot).toBe('gun'); - const withGun = { ...NO_SHIP_SYSTEMS, gun: 'lance' as const }; - expect(getPendingShipSystemSlot(4, withGun)).toBeNull(); - expect(getPendingShipSystemSlot(5, withGun)?.slot).toBe('support'); - const withSupport = { ...withGun, support: 'magnet' as const }; + test('support is offered after sector 5 and doctrine after 8; the main gun is never a pick', () => { + expect(getPendingShipSystemSlot(2, NO_SHIP_SYSTEMS)).toBeNull(); + expect(getPendingShipSystemSlot(4, NO_SHIP_SYSTEMS)).toBeNull(); + expect(getPendingShipSystemSlot(5, NO_SHIP_SYSTEMS)?.slot).toBe('support'); + const withSupport = { ...NO_SHIP_SYSTEMS, support: 'magnet' as const }; expect(getPendingShipSystemSlot(8, withSupport)?.slot).toBe('late'); expect(getPendingShipSystemSlot(9, { ...withSupport, late: 'bulwark' })).toBeNull(); }); test('a run that starts late (a loaded save, a level jump) is offered each missed pick in turn', () => { - expect(getPendingShipSystemSlot(9, NO_SHIP_SYSTEMS)?.slot).toBe('gun'); + expect(getPendingShipSystemSlot(9, NO_SHIP_SYSTEMS)?.slot).toBe('support'); }); - test('stored picks are clamped to their own slot', () => { + test("stored picks are clamped to their own slot, and an old save's main gun is ignored", () => { expect(normalizeShipSystems({ gun: 'scatter', support: 'lance', late: 42 })).toEqual({ - gun: 'scatter', support: null, late: null, }); + expect(normalizeShipSystems({ gun: 'seekers', support: 'magnet', late: 'bulwark' })).toEqual({ + support: 'magnet', + late: 'bulwark', + }); expect(normalizeShipSystems(undefined)).toEqual(NO_SHIP_SYSTEMS); }); test('cycling a slot steps through its options and wraps around', () => { - let systems: ShipSystems = { ...NO_SHIP_SYSTEMS, gun: 'lance', support: 'magnet' }; - const guns: Array = []; + let systems: ShipSystems = { ...NO_SHIP_SYSTEMS, support: 'magnet', late: 'bulwark' }; + const supports: Array = []; for (let step = 0; step < 3; step += 1) { - systems = selectNextShipSystem(systems, 'gun'); - guns.push(systems.gun); + systems = selectNextShipSystem(systems, 'support'); + supports.push(systems.support); } - expect(guns).toEqual(['scatter', 'seekers', 'lance']); - expect(systems.support).toBe('magnet'); - expect(selectNextShipSystem(systems, 'support').support).toBe('surgeCore'); + expect(supports).toEqual(['surgeCore', 'wingman', 'magnet']); + expect(systems.late).toBe('bulwark'); + }); + + test('the swap key steps the main gun Lance -> Scatter -> Seekers -> Lance', () => { + expect([getNextMainGun('lance'), getNextMainGun('scatter'), getNextMainGun('seekers')]).toEqual([ + 'scatter', + 'seekers', + 'lance', + ]); }); test('cycling an empty slot leaves it empty, so nothing can be picked early', () => { - expect(selectNextShipSystem(NO_SHIP_SYSTEMS, 'gun')).toEqual(NO_SHIP_SYSTEMS); - expect(selectNextShipSystem({ ...NO_SHIP_SYSTEMS, gun: 'seekers' }, 'late').late).toBeNull(); + expect(selectNextShipSystem(NO_SHIP_SYSTEMS, 'support')).toEqual(NO_SHIP_SYSTEMS); + expect(selectNextShipSystem({ ...NO_SHIP_SYSTEMS, support: 'magnet' }, 'late').late).toBeNull(); }); test("setting a slot only accepts that slot's own options", () => { expect(setShipSystem(NO_SHIP_SYSTEMS, 'support', 'wingman').support).toBe('wingman'); - expect(setShipSystem(NO_SHIP_SYSTEMS, 'support', 'lance').support).toBeNull(); + expect(setShipSystem(NO_SHIP_SYSTEMS, 'support', 'bulwark').support).toBeNull(); }); test('a picked slot can be offered again at the refit bay with its own three options', () => { - const gun = getShipSystemSlot('gun'); - expect(gun.title).toBe('MAIN GUN'); - expect(gun.options.map((option) => option.id)).toEqual(['lance', 'scatter', 'seekers']); + const support = getShipSystemSlot('support'); + expect(support.title).toBe('SUPPORT SYSTEM'); + expect(support.options.map((option) => option.id)).toEqual(['magnet', 'surgeCore', 'wingman']); expect(getShipSystemSlot('late').options.map((option) => option.id)).toEqual(['overdrive', 'bulwark', 'salvager']); }); test('the pause panel lists only picked slots, in slot order', () => { - const picked = describePickedShipSystems({ gun: 'scatter', support: null, late: 'bulwark' }); + expect(describePickedShipSystems({ support: null, late: 'bulwark' }).map((system) => system.title)).toEqual([ + 'COMBAT DOCTRINE', + ]); + const picked = describePickedShipSystems({ support: 'wingman', late: 'bulwark' }); expect(picked.map((system) => [system.title, system.option.name])).toEqual([ - ['MAIN GUN', 'SCATTER'], + ['SUPPORT SYSTEM', 'WINGMAN'], ['COMBAT DOCTRINE', 'BULWARK'], ]); }); diff --git a/tests/specialGunCharge.test.ts b/tests/specialGunCharge.test.ts new file mode 100644 index 0000000..6e40558 --- /dev/null +++ b/tests/specialGunCharge.test.ts @@ -0,0 +1,356 @@ +import { describe, expect, mock, test } from 'bun:test'; + +mock.module('phaser', () => ({ + default: { + Math: { + Vector2: class { + x = 0; + y = 0; + }, + }, + }, +})); + +mock.module('../src/systems/AudioManager', () => ({ + audioManager: { playSfx: () => {}, setMusicIntensity: () => {} }, +})); + +const { getLevelConfig } = await import('../src/config/LevelsConfig'); +const { NO_SHIP_SYSTEMS, SPECIAL_GUN_CHARGE } = await import('../src/config/shipSystems'); +const { getPlayerState } = await import('../src/systems/PlayerState'); +const { ShipSystemsRuntime } = await import('../src/systems/ShipSystemsRuntime'); +const { createGameSceneGameplayFrameBehavior } = await import('../src/scenes/gameScene/gameplayFrameBehavior'); +const { GameplayClock, runGameSceneUpdateFrame } = await import('../src/scenes/gameScene/updateFrame'); + +type ShipSystems = typeof NO_SHIP_SYSTEMS; +type GameplayDelegate = Parameters[0]; + +/** First sector with Lance and the special guns. */ +const GUN_SECTOR = SPECIAL_GUN_CHARGE.fromLevel; + +function createRegistry() { + const values = new Map(); + return { get: (key: string) => values.get(key), set: (key: string, value: unknown) => values.set(key, value) }; +} + +function createRuntime(level: number, systems: Partial = {}) { + const registry = createRegistry(); + const drones: Array<{ destroyed: boolean }> = []; + const pickup = { + active: true, + x: 0, + y: 0, + velocity: [0, 0], + setVelocity(x: number, y: number) { + pickup.velocity = [x, y]; + }, + }; + const scene = { + registry, + add: { + image: () => { + const drone = { + destroyed: false, + setScale: () => drone, + setDepth: () => drone, + destroy: () => { + drone.destroyed = true; + }, + }; + drones.push(drone); + return drone; + }, + }, + }; + const ship = { x: 0, y: 100, isAlive: true }; + const runtime = new ShipSystemsRuntime( + scene as never, + ship, + { getChildren: () => [pickup] } as never, + { ...NO_SHIP_SYSTEMS, ...systems }, + level + ); + return { runtime, registry, drones, pickup }; +} + +describe('special-gun charge', () => { + test('sectors 1-2 fly the standard gun: no swap, no meter', () => { + for (const level of [1, 2]) { + const { runtime } = createRuntime(level); + expect(runtime.getGun()).toBeNull(); + expect(runtime.trySwapGun()).toBe('unavailable'); + expect(runtime.updateGunCharge(60_000)).toBe(false); + expect(runtime.getGun()).toBeNull(); + } + }); + + test('from sector 3 the ship starts every sector on Lance with a full meter', () => { + const { runtime } = createRuntime(GUN_SECTOR); + expect(runtime.getGun()).toBe('lance'); + expect(runtime.getGunCharge()).toBe(1); + }); + + test('the swap key steps Lance -> Scatter -> Seekers -> Lance', () => { + const { runtime } = createRuntime(GUN_SECTOR); + const guns: Array = []; + for (let press = 0; press < 3; press += 1) { + expect(runtime.trySwapGun()).toBe('swapped'); + guns.push(runtime.getGun()); + } + expect(guns).toEqual(['scatter', 'seekers', 'lance']); + }); + + test('a special gun drains a full meter in drainMs and then hands back Lance', () => { + const { runtime } = createRuntime(GUN_SECTOR); + runtime.trySwapGun(); + expect(runtime.updateGunCharge(SPECIAL_GUN_CHARGE.drainMs / 2)).toBe(false); + expect(runtime.getGunCharge()).toBeCloseTo(0.5); + expect(runtime.getGun()).toBe('scatter'); + expect(runtime.updateGunCharge(SPECIAL_GUN_CHARGE.drainMs / 2 - 1)).toBe(false); + expect(runtime.getGun()).toBe('scatter'); + expect(runtime.updateGunCharge(1)).toBe(true); + expect(runtime.getGun()).toBe('lance'); + expect(runtime.getGunCharge()).toBe(0); + }); + + test('Lance refills an empty meter in refillMs; a special gun never refills it', () => { + const { runtime } = createRuntime(GUN_SECTOR); + runtime.trySwapGun(); + runtime.updateGunCharge(SPECIAL_GUN_CHARGE.drainMs); + runtime.updateGunCharge(SPECIAL_GUN_CHARGE.refillMs / 2); + expect(runtime.getGunCharge()).toBeCloseTo(0.5); + runtime.updateGunCharge(SPECIAL_GUN_CHARGE.refillMs); + expect(runtime.getGunCharge()).toBe(1); + + runtime.trySwapGun(); + runtime.updateGunCharge(1000); + const drained = runtime.getGunCharge(); + runtime.recordKill(); + expect(runtime.getGunCharge()).toBe(drained); + }); + + test('every enemy destroyed on Lance adds perKill, up to full', () => { + const { runtime } = createRuntime(GUN_SECTOR); + runtime.trySwapGun(); + runtime.updateGunCharge(SPECIAL_GUN_CHARGE.drainMs); + runtime.recordKill(); + runtime.recordKill(); + expect(runtime.getGunCharge()).toBeCloseTo(2 * SPECIAL_GUN_CHARGE.perKill); + runtime.updateGunCharge(SPECIAL_GUN_CHARGE.refillMs); + runtime.recordKill(); + expect(runtime.getGunCharge()).toBe(1); + }); + + test('leaving Lance needs minToLeaveLance; moving between specials or back to Lance never does', () => { + const { runtime } = createRuntime(GUN_SECTOR); + runtime.trySwapGun(); + runtime.updateGunCharge(SPECIAL_GUN_CHARGE.drainMs); + expect(runtime.getGun()).toBe('lance'); + + const justShort = (SPECIAL_GUN_CHARGE.minToLeaveLance - 0.01) * SPECIAL_GUN_CHARGE.refillMs; + runtime.updateGunCharge(justShort); + expect(runtime.trySwapGun()).toBe('low-charge'); + expect(runtime.getGun()).toBe('lance'); + + runtime.updateGunCharge(0.01 * SPECIAL_GUN_CHARGE.refillMs + 1); + expect(runtime.trySwapGun()).toBe('swapped'); + // Almost empty, but stepping on through the specials and home again is always allowed. + runtime.updateGunCharge(SPECIAL_GUN_CHARGE.minToLeaveLance * SPECIAL_GUN_CHARGE.drainMs - 10); + expect(runtime.trySwapGun()).toBe('swapped'); + expect(runtime.getGun()).toBe('seekers'); + expect(runtime.trySwapGun()).toBe('swapped'); + expect(runtime.getGun()).toBe('lance'); + }); + + test('a respawn starts over on Lance with a full meter', () => { + const { runtime } = createRuntime(GUN_SECTOR); + runtime.trySwapGun(); + runtime.updateGunCharge(SPECIAL_GUN_CHARGE.drainMs / 2); + runtime.resetGunCharge(); + expect(runtime.getGun()).toBe('lance'); + expect(runtime.getGunCharge()).toBe(1); + + const early = createRuntime(2).runtime; + early.resetGunCharge(); + expect(early.getGun()).toBeNull(); + }); + + test('the gun and its charge are never part of the saved systems', () => { + const { runtime, registry } = createRuntime(GUN_SECTOR, { support: 'magnet' }); + runtime.trySwapGun(); + runtime.cycleSystem('support'); + expect(getPlayerState(registry).systems).toEqual({ support: 'surgeCore', late: null }); + }); +}); + +describe('live ship-system changes', () => { + test('switching support to Wingman launches the drone and switching away removes it', () => { + const { runtime, drones } = createRuntime(GUN_SECTOR, { support: 'surgeCore' }); + expect(drones).toHaveLength(0); + runtime.cycleSystem('support'); + expect(runtime.getSystems().support).toBe('wingman'); + expect(drones).toHaveLength(1); + runtime.cycleSystem('support'); + expect(runtime.getSystems().support).toBe('magnet'); + expect(drones[0].destroyed).toBe(true); + }); + + test('switching away from Magnet lets go of the pickups it was pulling', () => { + const { runtime, pickup } = createRuntime(GUN_SECTOR, { support: 'magnet' }); + runtime.update(); + expect(pickup.velocity[1]).toBeGreaterThan(60); + runtime.cycleSystem('support'); + expect(pickup.velocity).toEqual([0, 60]); + }); +}); + +function createFrameHarness(level: number) { + const { runtime } = createRuntime(level); + const clock = new GameplayClock(); + const shots: number[] = []; + const feedback: string[] = []; + const buttonStates: Array<[string | null, number]> = []; + let swapPressed = false; + let paused = false; + let realTime = 0; + const vector = { x: 0, y: 0 } as GameplayDelegate['shotDirection']; + const levelConfig = getLevelConfig(level); + const behavior = createGameSceneGameplayFrameBehavior({ + inputManager: { + consumePauseToggleRequest: () => false, + consumeGunSwapRequest: () => { + const pressed = swapPressed; + swapPressed = false; + return pressed; + }, + isFiring: () => true, + }, + pauseStateController: { togglePauseRequest: () => {}, isGameplayPaused: () => paused }, + flow: { + isGameplayLocked: () => false, + sampleRespawnTransitionFrame: () => {}, + isTerminalTransitionActive: () => false, + }, + parallax: { update: () => {}, setSectionAtmosphere: () => {} }, + player: { + isAlive: true, + fireRate: 150, + getFireDirection: (out) => out, + getMuzzlePosition: (_distance, out) => out, + update: () => {}, + }, + getLastLifeHelperWing: () => null, + getPicketTurrets: () => null, + shipSystems: runtime, + gunSwapFeedback: { + swapped: (gun) => feedback.push(gun), + denied: () => feedback.push('denied'), + }, + mobileControls: { setGunChargeState: (gun, charge) => buttonStates.push([gun, charge]) }, + grazeSurge: { update: () => {} }, + waveManager: { update: () => {}, updateBossAdds: () => {}, getDuelHull: () => null }, + levelManager: { + progress: 0, + hasBossSpawned: () => false, + isComplete: () => false, + update: () => {}, + getLevelConfig: () => levelConfig, + shouldSpawnBoss: () => false, + }, + scoreManager: { getChainState: () => ({ chain: 0, multiplier: 1 }) }, + events: { emit: () => {} }, + hud: { showBossBar: () => {}, hideBossBar: () => {}, updateBossHp: () => {} }, + bulletPool: { fire: () => shots.push(clock.now) }, + findBulletTarget: () => null, + effectsManager: { createMuzzleFlash: () => {}, updateLighting: () => {} }, + getBoss: () => null, + updateHud: () => {}, + shotDirection: vector, + shotOrigin: { ...vector } as GameplayDelegate['shotOrigin'], + muzzleFlashOrigin: { ...vector } as GameplayDelegate['muzzleFlashOrigin'], + }); + + /** Runs real frames of 16 ms; gameplay time only moves while unpaused. */ + const run = (ms: number): void => { + for (let elapsed = 0; elapsed < ms; elapsed += 16) { + realTime += 16; + runGameSceneUpdateFrame(behavior, realTime, 16, clock); + } + }; + + return { + runtime, + clock, + shots, + feedback, + buttonStates, + run, + pressSwap: () => { + swapPressed = true; + }, + setPaused: (next: boolean) => { + paused = next; + }, + }; +} + +describe('special guns during play', () => { + test('a swap fires at once, with no silence after the change', () => { + const harness = createFrameHarness(GUN_SECTOR); + harness.run(400); + harness.pressSwap(); + harness.run(16); + expect(harness.feedback).toEqual(['scatter']); + const shotsAtSwap = harness.shots.length; + harness.run(300); + expect(harness.shots.length).toBeGreaterThan(shotsAtSwap); + }); + + test('the meter drains on the gameplay clock only, then flashes Lance back', () => { + const harness = createFrameHarness(GUN_SECTOR); + harness.pressSwap(); + harness.run(16); + harness.setPaused(true); + harness.run(SPECIAL_GUN_CHARGE.drainMs * 2); + harness.setPaused(false); + expect(harness.runtime.getGun()).toBe('scatter'); + expect(harness.runtime.getGunCharge()).toBeGreaterThan(0.99); + + harness.run(SPECIAL_GUN_CHARGE.drainMs + 32); + expect(harness.runtime.getGun()).toBe('lance'); + expect(harness.feedback).toEqual(['scatter', 'lance']); + const [gun, charge] = harness.buttonStates.at(-1)!; + expect(gun).toBe('lance'); + expect(charge).toBeLessThan(0.01); + }); + + test('leaving Lance on a low meter is refused with the quiet cue and changes nothing', () => { + const harness = createFrameHarness(GUN_SECTOR); + harness.pressSwap(); + harness.run(SPECIAL_GUN_CHARGE.drainMs + 32); + harness.pressSwap(); + harness.run(16); + expect(harness.feedback).toEqual(['scatter', 'lance', 'denied']); + expect(harness.runtime.getGun()).toBe('lance'); + }); + + test('a press while paused is dropped, not saved for resume', () => { + const harness = createFrameHarness(GUN_SECTOR); + harness.setPaused(true); + harness.pressSwap(); + harness.run(32); + harness.setPaused(false); + harness.run(32); + expect(harness.feedback).toEqual([]); + expect(harness.runtime.getGun()).toBe('lance'); + }); + + test('in sectors 1-2 the key does nothing and the touch button stays hidden', () => { + const harness = createFrameHarness(2); + harness.pressSwap(); + harness.run(400); + expect(harness.feedback).toEqual([]); + expect(harness.buttonStates.every(([gun]) => gun === null)).toBe(true); + expect(harness.shots.length).toBeGreaterThan(0); + }); +}); diff --git a/tests/startRun.test.ts b/tests/startRun.test.ts index 436deb4..e955db7 100644 --- a/tests/startRun.test.ts +++ b/tests/startRun.test.ts @@ -40,7 +40,7 @@ describe('canonical new run action', () => { remainingLives: 0, currentShields: 2, upgrades: { hp: 3, damage: 3, fireRate: 3, shield: 3, turrets: 3 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 1, slots: [{ remainingLives: 0, hp: 0 }] }, }); setRunSummary(registry, { finalScore: 16000, levelReached: 8 }); @@ -58,7 +58,7 @@ describe('canonical new run action', () => { currentShields: 0, remainingLives: 3, upgrades: { hp: 0, damage: 0, fireRate: 0, shield: 0, turrets: 0 }, - systems: { gun: null, support: null, late: null }, + systems: { support: null, late: null }, helperWing: { grantedSlots: 0, slots: [] }, }); expect(getRunSummary(registry)).toMatchObject({ finalScore: 0, levelReached: 1 }); From bdc5f1dc1dacce0e470fa4d1e0cda32317d154df Mon Sep 17 00:00:00 2001 From: Douwe de Vries Date: Fri, 13 Nov 2026 21:37:12 +0100 Subject: [PATCH 2/2] fix(touch): swap key only looks ready once the charge allows leaving Lance Co-Authored-By: Claude Fable 5.2 --- src/systems/MobileControls.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/systems/MobileControls.ts b/src/systems/MobileControls.ts index ac24ddf..22ee50c 100644 --- a/src/systems/MobileControls.ts +++ b/src/systems/MobileControls.ts @@ -220,7 +220,10 @@ export class MobileControls { setGunChargeState(gun: MainGunId | null, charge: number): void { const available = gun !== null; const draining = available && gun !== 'lance'; - const step = Math.ceil(Math.max(0, Math.min(1, charge)) * SWAP_CHARGE_STEPS); + const steps = Math.max(0, Math.min(1, charge)) * SWAP_CHARGE_STEPS; + // Rounded down on Lance, so the key never looks ready before the charge allows leaving; up while + // draining, so a special gun never shows an empty bar. + const step = draining ? Math.ceil(steps) : Math.floor(steps); if (available === this.swapAvailable && draining === this.swapDraining && step === this.swapChargeStep) return; const visibilityChanged = available !== this.swapAvailable; this.swapAvailable = available;