mirror of
https://github.com/kuhyx/testsAndMisc.git
synced 2026-11-24 20:36:18 +01:00
Compare commits
No commits in common. "5d0caa972543aa4e33398ead1578f79ef915c130" and "b0c7baf22eb8740489fa94f737af25adbd3ef783" have entirely different histories.
5d0caa9725
...
b0c7baf22e
@ -1,15 +0,0 @@
|
||||
{
|
||||
"title": "Reverse Survivors: difficulty tiers",
|
||||
"objective": "Add three difficulty tiers - Haunting, Normal and Crusade - scaling enemy hp and speed, the survivor's health, director income, and the length of the night. Normal must be the exact identity tier so no existing behaviour or assertion changes.",
|
||||
"acceptance_criteria": [
|
||||
"`npm run check` passes standalone: tsc --noEmit clean, eslint --max-warnings 0 clean, vitest at 100% on all four metrics.",
|
||||
"Normal is exactly 1.0 on every multiplier, so all pre-existing raw-value assertions hold unchanged.",
|
||||
"An explicit duration argument still overrides the tier's duration.",
|
||||
"Changing difficulty restarts the game on the new tier, and restarting preserves the selected tier."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Endless mode: fmtTime(Infinity) renders Infinity:NaN and would need a guard plus tests for a mode whose only content is the same game but longer.",
|
||||
"localStorage persistence of the chosen tier: its catch arm is only reachable by stubbing a throwing setItem, which tests the mock rather than the game."
|
||||
],
|
||||
"verifier": "npm run check (typecheck + eslint --max-warnings 0 + vitest --coverage at 100%), plus an App-level test asserting the clock changes from 5:00 to 6:00 when Crusade is selected"
|
||||
}
|
||||
@ -1,17 +0,0 @@
|
||||
{
|
||||
"title": "Reverse Survivors: director powers (ambush, frenzy, rift)",
|
||||
"objective": "Give the director three powers beyond spawn/wave/boss, buying back some control over where enemies appear. Ambush places a unit next to the survivor at a premium, Frenzy drives the horde harder for six seconds, and Rift pins spawns to one edge for ten. Placement becomes purchasable rather than free.",
|
||||
"acceptance_criteria": [
|
||||
"`npm run check` passes standalone: tsc --noEmit clean, eslint --max-warnings 0 clean, vitest at 100% on all four metrics.",
|
||||
"Existing seeded replays are unaffected: the unpinned edgeSpawnPos path draws the same RNG values in the same order as before.",
|
||||
"Ambush placement is deterministic and draws no RNG.",
|
||||
"Ambush lanes never repeat, including past a full turn.",
|
||||
"Frenzy scales every damage channel - contact, projectile and blast - not just melee.",
|
||||
"Each power is independently gated by cooldown and affordability, and rejects cleanly when either fails."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Difficulty tiers, which ship as a separate commit.",
|
||||
"Letting the player choose the ambush unit: the bar binds it to a fixed cheap unit so SpawnBar stays a pure snapshot-to-buttons function with no local state."
|
||||
],
|
||||
"verifier": "npm run check (typecheck + eslint --max-warnings 0 + vitest --coverage at 100%), plus director.test.ts assertions on cooldown gating, lane rotation across 24 summons, and rift edge pinning"
|
||||
}
|
||||
@ -1,18 +0,0 @@
|
||||
{
|
||||
"title": "Reverse Survivors gameplay extension: enemies, statuses, director powers, difficulty",
|
||||
"objective": "Extend the game with four systems, landed as four independently-green commits: new enemy kinds; survivor status debuffs (slow/suppress/bleed); director powers that buy back placement control (ambush/frenzy/rift); and difficulty tiers. Each commit must typecheck, lint at --max-warnings 0, and hold 100% coverage on its own, so the history stays bisectable.",
|
||||
"acceptance_criteria": [
|
||||
"Every commit passes `npm run check` in reverse_survivors/ standalone: tsc --noEmit clean, eslint --max-warnings 0 clean, vitest at 100% statements/branches/functions/lines.",
|
||||
"No lint suppressions, @ts-ignore, or coverage excludes are introduced.",
|
||||
"New status logic contributes zero branches, verified against the v8 branch count.",
|
||||
"Seeded replays stay deterministic: the same seed and action sequence produce identical outcomes.",
|
||||
"The game runs and both sides can still win, verified by driving the real simulation rather than tests alone."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Endless mode: fmtTime(Infinity) renders Infinity:NaN and would need a guard plus tests for a mode whose only content is the same game but longer.",
|
||||
"localStorage difficulty persistence: its catch arm is only reachable by stubbing a throwing setItem, which tests the mock rather than the game.",
|
||||
"The pending dependency refresh (7 packages one patch behind) ships separately.",
|
||||
"Rebalancing the pre-existing economy, where a trickle strategy loses to the survivor's kill rate."
|
||||
],
|
||||
"verifier": "npm run check (typecheck + eslint --max-warnings 0 + vitest --coverage at 100%), npm run build, and a headless full-game playtest driving src/core/sim.ts via vite-node"
|
||||
}
|
||||
@ -1,16 +0,0 @@
|
||||
{
|
||||
"title": "Reverse Survivors: survivor status effects",
|
||||
"objective": "Give the survivor three debuff channels - slow (movement), suppress (fire rate) and bleed (regen block) - so ranged and fast units have a lever beyond raw damage. The system must be cross-cutting yet contribute zero branches, so the 100% coverage gate stays affordable.",
|
||||
"acceptance_criteria": [
|
||||
"`npm run check` passes standalone: tsc --noEmit clean, eslint --max-warnings 0 clean, vitest at 100% statements/branches/functions/lines.",
|
||||
"The status module itself adds zero branches, verified against the v8 branch count (117 -> 119 accounted for solely by the draw halo gate and the snapshot chip filter).",
|
||||
"Re-applying a status refreshes rather than stacks, so total lockdown is capped at one duration regardless of horde size.",
|
||||
"An enemy that inflicts nothing leaves all three timers at exactly 0.",
|
||||
"Survivor-fired projectiles can never debuff the survivor."
|
||||
],
|
||||
"out_of_scope": [
|
||||
"Director powers and difficulty tiers, which ship as separate commits.",
|
||||
"Aura or ranged-application debuffs: all three require contact by design, so a cleanly kiting survivor takes none."
|
||||
],
|
||||
"verifier": "npm run check (typecheck + eslint --max-warnings 0 + vitest --coverage at 100%), plus targeted sim.test.ts assertions comparing slowed movement against an unslowed control run"
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
{
|
||||
"intent": "Add Haunting/Normal/Crusade difficulty tiers and document the whole four-part extension in the README.",
|
||||
"scope": [
|
||||
"reverse_survivors/src/core/types.ts (DifficultyId, DifficultyConfig, DIFFICULTIES)",
|
||||
"reverse_survivors/src/core/sim.ts (createInitialState parameter, enemySpeed helper, hp scaling), director.ts (regenRate rate)",
|
||||
"reverse_survivors/src/App.tsx (tier selector), src/styles.css, README.md",
|
||||
"Non-goal: endless mode and localStorage persistence, both deliberately excluded"
|
||||
],
|
||||
"changes": [
|
||||
"Difficulty is a pure config object resolved once in createInitialState and stored on GameState, so no downstream code re-looks-it-up.",
|
||||
"Normal is exactly 1.0 on every multiplier, which is what lets every pre-existing raw-hp assertion keep passing unchanged.",
|
||||
"Enemy speed now derives from a single enemySpeed helper, so difficulty and frenzy compose in one place instead of fighting at three call sites.",
|
||||
"regenRate gained an optional rate parameter defaulting to 1, keeping its existing call sites and assertions valid.",
|
||||
"Fixed while wiring the selector: handleRestart ignored the chosen tier, so restarting after picking Crusade silently reverted to Normal. Surfaced by the react-hooks purity rule flagging Date.now() in the new handler, which led to extracting restartSeed().",
|
||||
"README rewritten to cover the new units, powers, statuses and tiers, and to document the deliberate reversal of its former 'placement is never yours to choose' promise."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "npm run check (typecheck + eslint --max-warnings 0 + vitest --coverage)",
|
||||
"result": "pass",
|
||||
"evidence": "160 tests passed. Coverage 100% on all four metrics: statements 531/531, branches 159/159, functions 101/101, lines 514/514."
|
||||
},
|
||||
{
|
||||
"command": "npm run build",
|
||||
"result": "pass",
|
||||
"evidence": "tsc --noEmit clean, vite build in ~72ms, 210.08 kB / 66.26 kB gzip."
|
||||
},
|
||||
{
|
||||
"command": "headless full-game playtest driving the real sim (vite-node)",
|
||||
"result": "pass",
|
||||
"evidence": "Banking energy then bursting wave+frenzy+ambush killed the survivor at t=53s with the warden's slow live (1.92s) and frenzy active (4.20s). A passive director loses on every tier; Crusade won at t=56s; Haunting and Normal went to the survivor. Same seed twice produced byte-identical outcomes."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Tier multipliers are simulation-verified rather than human-playtested and may need retuning.",
|
||||
"Pre-existing and unchanged here: with a trickle strategy the survivor out-kills a 6 energy/sec income, so banking and bursting is the effective approach."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; the game returns to a single fixed difficulty with no persisted state to migrate.",
|
||||
"After rollback run `npm run check` in reverse_survivors/ and confirm the suite passes at 100% coverage."
|
||||
]
|
||||
}
|
||||
@ -1,47 +0,0 @@
|
||||
{
|
||||
"intent": "Add three director powers - ambush, frenzy and rift - giving the player priced control over enemy placement and a burst tempo lever.",
|
||||
"scope": [
|
||||
"reverse_survivors/src/core/types.ts (PowerKind, costs/cooldowns, EdgeId, DirectorState fields, new DirectorAction variants)",
|
||||
"reverse_survivors/src/core/director.ts (spendPower gate, ambush/frenzy/rift, rift-aware edgeSpawnPos)",
|
||||
"reverse_survivors/src/core/sim.ts (frenzy speed and damage), snapshot.ts, src/ui/SpawnBar.tsx, src/ui/Hud.tsx, src/styles.css",
|
||||
"Non-goal: difficulty tiers ship as their own commit"
|
||||
],
|
||||
"changes": [
|
||||
"A shared spendPower gate handles cooldown and affordability for all three powers, so each additional power costs no new branches in the dispatcher.",
|
||||
"EDGES converted from an array to Record<EdgeId, EdgeFn>: under noUncheckedIndexedAccess an array index would be possibly-undefined and force an unreachable fallback branch, whereas a finite-union Record stays non-optional.",
|
||||
"Ambush placement uses a golden-angle step so successive summons never reuse a lane. An earlier 2*PI/7 formulation was caught in review: it silently cycled every 7 summons, with index 7 landing byte-identically on index 0.",
|
||||
"Frenzy damage derives from one shared frenzyDamageMul helper. Review caught that an earlier version multiplied contact damage only, leaving enemy projectiles and bomber blasts unscaled - which contradicted the README and left the bomber, whose contactDamage is 0, entirely unaffected.",
|
||||
"MOVE_FNS gained a speed parameter so frenzy (and later difficulty) multiply in one place rather than at three call sites.",
|
||||
"The README's former promise that enemy placement is never the player's to choose is deliberately reversed here and documented as such."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "npm run check (typecheck + eslint --max-warnings 0 + vitest --coverage)",
|
||||
"result": "pass",
|
||||
"evidence": "145 tests passed. Coverage 100% on all four metrics: statements 516/516, branches 153/153, functions 96/96, lines 499/499."
|
||||
},
|
||||
{
|
||||
"command": "ambush lane probe via vite-node",
|
||||
"result": "pass",
|
||||
"evidence": "24 consecutive ambushes produced 24 distinct spawn positions. Before the golden-angle fix the same probe produced only 7, with index 7 identical to index 0 at (610.0000, 300.0000)."
|
||||
},
|
||||
{
|
||||
"command": "frenzy damage-channel probe via vite-node",
|
||||
"result": "pass",
|
||||
"evidence": "Ratios with frenzy on vs off, measured over 360 ticks: warden contact 1.300, artillery projectile 1.300, stalker projectile 1.300, bomber blast 1.300. Before the fix the last three measured 1.000."
|
||||
},
|
||||
{
|
||||
"command": "RNG-identity check against the pre-change implementation",
|
||||
"result": "pass",
|
||||
"evidence": "The old array-based pick was reimplemented from git HEAD and compared across 50 seeds x 20 calls on both the returned position and the final RNG state: 0 mismatches. Existing seeded replays are unchanged."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Powers are gated by cooldown rather than energy alone, because late-game income reaches 24/s and an energy-only gate would degenerate into spamming the highest-value button.",
|
||||
"Ambush lets the director bypass the survivor's kiting AI, which is the intended counter to its late-game power curve but is the most likely thing to need retuning."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; no persisted state or data migration is involved.",
|
||||
"After rollback run `npm run check` in reverse_survivors/ and confirm the suite passes at 100% coverage."
|
||||
]
|
||||
}
|
||||
@ -1,33 +0,0 @@
|
||||
{
|
||||
"intent": "Add four enemy kinds to Reverse Survivors: Splitter, Artillery, Warden, and the Leech boss.",
|
||||
"scope": [
|
||||
"reverse_survivors/src/core/types.ts (specs, UnitKind/BossKind, orders, unlock/cooldown tables)",
|
||||
"reverse_survivors/src/core/sim.ts (split(), spawnKind generalization)",
|
||||
"reverse_survivors/src/render/draw.ts (colors, boss ring flags)",
|
||||
"Non-goal: status debuffs, director powers and difficulty tiers ship as their own commits"
|
||||
],
|
||||
"changes": [
|
||||
"Two new EnemySpec fields: spawnKind and splitCount. spawnKind generalizes the previously hardcoded 'rusher' in the hivemind's minion spawn; splitCount drives on-death splitting.",
|
||||
"Splitter (34) dies into 3 rushers at fixed 120-degree offsets, so killing it creates pressure. Children are rushers, making recursion structurally impossible - no depth counter needed.",
|
||||
"Artillery (52) has 460 range against the survivor's 260 and keepDistance 420, so it outranges the survivor's kiting AI entirely.",
|
||||
"Warden (40) moves at 215, faster than the survivor's base 150.",
|
||||
"Leech (190, unlocks at 180s) is a third boss, cheaper and squishier than the Colossus.",
|
||||
"split() is called unconditionally from killByShot; splitCount: 0 makes it a no-op, which avoids a guard branch that would need two tests under the 100% gate.",
|
||||
"Child positions use fixed angular offsets rather than the RNG, so seeded replays are unaffected."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "npm run check (typecheck + eslint --max-warnings 0 + vitest --coverage)",
|
||||
"result": "pass",
|
||||
"evidence": "105 tests passed. Coverage 100% on all four metrics: statements 417/417, branches 117/117, functions 76/76, lines 402/402. Branch count unchanged from the 117 baseline, confirming this feature adds zero branches."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Balance is simulation-verified rather than human-playtested; the new units may need retuning.",
|
||||
"Splitter children spawn into state.enemies during projectilesStep, so a later projectile in the same tick can interact with them. Verified: SPLIT_RADIUS 22 exceeds rusher radius 9 + projectile radius 4, so children spawn outside immediate hit range."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; no data migration and no persisted state is involved.",
|
||||
"After rollback run `npm run check` in reverse_survivors/ and confirm 95 tests pass at 100% coverage."
|
||||
]
|
||||
}
|
||||
@ -1,38 +0,0 @@
|
||||
{
|
||||
"intent": "Give the survivor three status debuffs - slow, suppress (fire rate) and bleed (regen block) - so the new ranged and fast units have a lever beyond raw damage.",
|
||||
"scope": [
|
||||
"reverse_survivors/src/core/status.ts (new leaf module) and status.test.ts",
|
||||
"reverse_survivors/src/core/types.ts (StatusKind, STATUS_POWER/LABELS, per-spec debuff fields, Survivor.statuses, Projectile payload)",
|
||||
"reverse_survivors/src/core/sim.ts (tick and consume), snapshot.ts (chips), src/ui/Hud.tsx, src/render/draw.ts (halo), src/styles.css",
|
||||
"Non-goal: director powers and difficulty tiers ship as their own commits"
|
||||
],
|
||||
"changes": [
|
||||
"isOn/factor are arithmetic (Math.min(1, Math.ceil(t))) rather than comparisons, so the whole status system contributes ZERO branches; consumers multiply by the result instead of branching on it.",
|
||||
"applyStatus uses Math.max, making refresh-not-stack a structural guarantee: a horde can never chain-lock the survivor past one status duration, regardless of how many enemies land hits.",
|
||||
"Statuses are applied unconditionally at contact and projectile-hit sites; a 0-duration spec makes the call a provable no-op, which is cheaper than a guard branch under the 100% gate.",
|
||||
"Projectiles carry their own debuff payload so a hit needs no lookup of a possibly-dead firer.",
|
||||
"Statuses tick at the top of survivorStep, before they are read, so a status applied on tick N is felt from N+1 and an inert application is never observable.",
|
||||
"Suppression scales the reload rather than the countdown, keeping the remaining timer linear in dt so replays and assertions stay exact.",
|
||||
"The draw.ts halo is gated so an unafflicted survivor renders exactly as before, keeping the existing BASE draw-call counts valid."
|
||||
],
|
||||
"verification": [
|
||||
{
|
||||
"command": "npm run check (typecheck + eslint --max-warnings 0 + vitest --coverage)",
|
||||
"result": "pass",
|
||||
"evidence": "123 tests passed. Coverage 100% on all four metrics: statements 446/446, branches 119/119, functions 84/84, lines 429/429. Branch count rose 117 -> 119, accounted for by the halo gate and the snapshot chip filter; the status module itself adds none."
|
||||
},
|
||||
{
|
||||
"command": "targeted assertions in sim.test.ts",
|
||||
"result": "pass",
|
||||
"evidence": "Warden contact slows movement by exactly STATUS_POWER.slow against an unslowed control run; artillery shells lengthen the next reload to 0.55 * 1.75; a leech contact blocks regen and it resumes on expiry; two simultaneous warden contacts do not exceed the 2.0s cap; a plain rusher leaves all three timers at 0."
|
||||
}
|
||||
],
|
||||
"risks": [
|
||||
"Bleed is a no-op unless the survivor has bought the regen upgrade, since it starts at regen 0. This is intended - the Leech counters a specific build - and matches the README description.",
|
||||
"All three debuffs require contact, so a survivor that kites cleanly takes none of them. This is deliberate: debuffs punish positional failure rather than taxing existence."
|
||||
],
|
||||
"rollback": [
|
||||
"git revert the commit; src/core/status.ts and status.test.ts are new files and disappear with it.",
|
||||
"After rollback run `npm run check` in reverse_survivors/ and confirm the suite passes at 100% coverage."
|
||||
]
|
||||
}
|
||||
@ -14,32 +14,14 @@ npm run dev
|
||||
```
|
||||
|
||||
- **Rusher / Stalker / Tank / Bomber** — single spawns at a random arena edge.
|
||||
- **Splitter** — dies into three rushers. Killing it _creates_ pressure.
|
||||
- **Artillery** — outranges the survivor (460 vs its 260) and holds station beyond
|
||||
reach. Its shells **stifle**, stretching the survivor's reload.
|
||||
- **Warden** — faster than the survivor and **mires** it on contact.
|
||||
- **Wave N** — a ring formation around the survivor; each call grows and costs more.
|
||||
- **Colossus** (1:00), **Hivemind** (2:00) and **Leech** (3:00) — expensive, on
|
||||
cooldown. The Hivemind births free rushers; the Leech's touch **unknits** flesh,
|
||||
shutting off regeneration while it lives.
|
||||
- **Ambush** places a unit right next to the survivor, at a premium.
|
||||
**Frenzy** drives the whole horde faster and harder for six seconds.
|
||||
**Rift** pins every spawn to one edge for ten, so you can mass a flank.
|
||||
- **Colossus** (unlocks 1:00) and **Hivemind** (unlocks 2:00) — expensive, on cooldown.
|
||||
The Hivemind births free rushers while it lives.
|
||||
- The survivor gains XP per kill and rolls an upgrade per level
|
||||
(damage, fire rate, speed, vitality, regen, multishot). Time favors it. Pressure early.
|
||||
- **Haunting / Normal / Crusade** scale enemy hp and speed, the survivor's health,
|
||||
your income, and the length of the night.
|
||||
|
||||
Placement is purchasable, never free. By default the director picks _what_ and
|
||||
_when_ while the seeded RNG picks _where_ — Ambush and Rift buy that choice back,
|
||||
one at a premium and the other at a cooldown.
|
||||
|
||||
> Earlier versions made the loss of placement control absolute. Ambush and Rift
|
||||
> deliberately reverse that: the interesting decision turned out to be _what a
|
||||
> placement is worth_, not being denied one.
|
||||
|
||||
All three debuffs need contact — a survivor that kites cleanly takes none of them —
|
||||
and they refresh rather than stack, so a horde can never chain-lock the intruder.
|
||||
Where enemies appear is deliberately not yours to choose — the director picks
|
||||
_what_ and _when_; the seeded RNG picks _where_.
|
||||
|
||||
## Quality gates
|
||||
|
||||
@ -60,11 +42,6 @@ ESLint 10.8.0 · typescript-eslint 8.65.0 · TypeScript **6.0.3**.
|
||||
|
||||
## Architecture (what makes 100 % honest)
|
||||
|
||||
- `src/core/status.ts` — the survivor's debuff timers. `isOn`/`factor` are written
|
||||
as arithmetic (`Math.min(1, Math.ceil(t))`) rather than comparisons, so the whole
|
||||
status system contributes **zero branches** to the coverage gate; consumers just
|
||||
multiply by the result. `applyStatus` uses `Math.max`, which is what makes
|
||||
refresh-not-stack a structural guarantee rather than a tuned number.
|
||||
- `src/core/` — the whole game as pure-ish functions over a plain state object.
|
||||
Deterministic: seeded mulberry32 RNG lives _in_ the state; same seed + same
|
||||
action sequence ⇒ identical run. Behavior dispatch uses records instead of
|
||||
|
||||
@ -60,26 +60,6 @@ describe('App', () => {
|
||||
expect(screen.getByText('30 / 400')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('restarts on a new tier when the difficulty is changed', () => {
|
||||
const raf = installRaf()
|
||||
render(<App seed={9} />)
|
||||
pump(raf, 0)
|
||||
// Normal runs 5:00; Crusade runs 6:00, so the clock proves the tier took.
|
||||
expect(screen.getByText(/\/ 5:00/)).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Crusade' }))
|
||||
expect(screen.getByText(/\/ 6:00/)).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Crusade' })).toHaveClass('diff-on')
|
||||
})
|
||||
|
||||
it('dispatches a director power from the bar', () => {
|
||||
const raf = installRaf()
|
||||
render(<App seed={9} boot={(state) => { state.director.energy = 400 }} />)
|
||||
pump(raf, 0)
|
||||
fireEvent.click(screen.getByRole('button', { name: /frenzy/i }))
|
||||
pump(raf, 16)
|
||||
expect(screen.getByText(/frenzied/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the dawn overlay when the survivor outlasts the horde', () => {
|
||||
const raf = installRaf()
|
||||
render(<App boot={(state) => { state.duration = 0.05 }} />)
|
||||
|
||||
@ -4,8 +4,7 @@ import { fmtTime } from './ui/format'
|
||||
import { createInitialState, step } from './core/sim'
|
||||
import type { HudSnapshot } from './core/snapshot'
|
||||
import { snapshotOf } from './core/snapshot'
|
||||
import type { DifficultyId, DirectorAction, GameState } from './core/types'
|
||||
import { DIFFICULTIES, DIFFICULTY_ORDER } from './core/types'
|
||||
import type { DirectorAction, GameState } from './core/types'
|
||||
import type { Ctx2D } from './render/draw'
|
||||
import { draw } from './render/draw'
|
||||
import { CanvasStage } from './ui/CanvasStage'
|
||||
@ -19,18 +18,8 @@ interface Props {
|
||||
boot?: (state: GameState) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Fresh seed for a restart. Extracted so the impurity lives outside render —
|
||||
* the react-hooks purity rule rejects `Date.now()` inline in a component body.
|
||||
*/
|
||||
const restartSeed = (): number => Date.now() >>> 0
|
||||
|
||||
const createGame = (
|
||||
seed: number,
|
||||
boot: Props['boot'],
|
||||
difficulty: DifficultyId = 'normal',
|
||||
): GameState => {
|
||||
const state = createInitialState(seed, undefined, difficulty)
|
||||
const createGame = (seed: number, boot: Props['boot']): GameState => {
|
||||
const state = createInitialState(seed)
|
||||
if (boot !== undefined) {
|
||||
boot(state)
|
||||
}
|
||||
@ -38,7 +27,6 @@ const createGame = (
|
||||
}
|
||||
|
||||
export const App = ({ seed = 20260802, boot }: Props): ReactElement => {
|
||||
const [difficulty, setDifficulty] = useState<DifficultyId>('normal')
|
||||
const gameRef = useRef<GameState>(createGame(seed, boot))
|
||||
const [snap, setSnap] = useState<HudSnapshot>(() => snapshotOf(createGame(seed, boot)))
|
||||
const ctxRef = useRef<Ctx2D | null>(null)
|
||||
@ -59,13 +47,7 @@ export const App = ({ seed = 20260802, boot }: Props): ReactElement => {
|
||||
queueRef.current.push(action)
|
||||
}
|
||||
const handleRestart = (): void => {
|
||||
gameRef.current = createGame(Date.now() >>> 0, undefined, difficulty)
|
||||
queueRef.current = []
|
||||
setSnap(snapshotOf(gameRef.current))
|
||||
}
|
||||
const handleDifficulty = (id: DifficultyId): void => {
|
||||
setDifficulty(id)
|
||||
gameRef.current = createGame(restartSeed(), undefined, id)
|
||||
gameRef.current = createGame(Date.now() >>> 0, undefined)
|
||||
queueRef.current = []
|
||||
setSnap(snapshotOf(gameRef.current))
|
||||
}
|
||||
@ -79,18 +61,6 @@ export const App = ({ seed = 20260802, boot }: Props): ReactElement => {
|
||||
<h1>Reverse Survivors</h1>
|
||||
<p className="tagline">You are the horde. The hero is the problem.</p>
|
||||
<p className="clock">{fmtTime(snap.t)} / {fmtTime(snap.duration)}</p>
|
||||
<div className="difficulty" role="group" aria-label="Difficulty">
|
||||
{DIFFICULTY_ORDER.map((id) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
className={id === difficulty ? 'diff diff-on' : 'diff'}
|
||||
onClick={() => { handleDifficulty(id) }}
|
||||
>
|
||||
{DIFFICULTIES[id].label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</header>
|
||||
<main className="board">
|
||||
<CanvasStage onCtx={handleCtx} />
|
||||
|
||||
@ -3,10 +3,7 @@ import { applyAction, edgeSpawnPos, regenRate, tickDirector, waveCost } from './
|
||||
import { createInitialState } from './sim'
|
||||
import { snapshotOf } from './snapshot'
|
||||
import type { GameState } from './types'
|
||||
import {
|
||||
AMBUSH_RADIUS, ARENA, BOSS_COOLDOWN, ENEMY_SPECS, ENERGY_CAP, FRENZY_DURATION,
|
||||
POWER_COOLDOWN, POWER_COST, RIFT_DURATION,
|
||||
} from './types'
|
||||
import { ARENA, BOSS_COOLDOWN, ENERGY_CAP } from './types'
|
||||
|
||||
const fresh = (seed = 1): GameState => createInitialState(seed)
|
||||
|
||||
@ -172,144 +169,3 @@ describe('snapshot', () => {
|
||||
expect(snapshotOf(s).survivorHp).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('director powers', () => {
|
||||
it('power cooldowns drain and floor at zero', () => {
|
||||
const s = fresh()
|
||||
s.director.powerCooldowns.ambush = 0.3
|
||||
s.director.powerCooldowns.frenzy = 2
|
||||
tickDirector(s, 0.5)
|
||||
expect(s.director.powerCooldowns.ambush).toBe(0)
|
||||
expect(s.director.powerCooldowns.frenzy).toBeCloseTo(1.5)
|
||||
})
|
||||
|
||||
it('frenzy and rift timers drain and floor at zero', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 0.2
|
||||
s.director.riftTimer = 5
|
||||
tickDirector(s, 0.5)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
expect(s.director.riftTimer).toBeCloseTo(4.5)
|
||||
})
|
||||
|
||||
it('ambush lands a unit near the survivor and debits both costs', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(true)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
const e = s.enemies[0]
|
||||
const d = Math.hypot(
|
||||
(e?.pos.x ?? 0) - s.survivor.pos.x,
|
||||
(e?.pos.y ?? 0) - s.survivor.pos.y,
|
||||
)
|
||||
expect(d).toBeCloseTo(AMBUSH_RADIUS, 5)
|
||||
expect(s.director.energy).toBe(400 - POWER_COST.ambush - ENEMY_SPECS.rusher.cost)
|
||||
expect(s.director.powerCooldowns.ambush).toBe(POWER_COOLDOWN.ambush)
|
||||
})
|
||||
|
||||
it('ambush is rejected when it cannot be afforded', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 5
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(false)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
expect(s.director.energy).toBe(5)
|
||||
})
|
||||
|
||||
it('ambush is rejected while cooling', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(true)
|
||||
expect(applyAction(s, { type: 'ambush', kind: 'rusher' })).toBe(false)
|
||||
expect(s.enemies).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('ambush lanes never repeat, even past a full turn', () => {
|
||||
// Regression: a 2*PI/7 step cycled silently, so index 7 reused index 0.
|
||||
const s = fresh()
|
||||
const seen: string[] = []
|
||||
for (let i = 0; i < 24; i += 1) {
|
||||
s.director.powerCooldowns.ambush = 0
|
||||
s.director.energy = 400
|
||||
s.enemies = []
|
||||
applyAction(s, { type: 'ambush', kind: 'rusher' })
|
||||
const e = s.enemies[0]
|
||||
seen.push(`${(e?.pos.x ?? 0).toFixed(6)},${(e?.pos.y ?? 0).toFixed(6)}`)
|
||||
}
|
||||
expect(new Set(seen).size).toBe(24)
|
||||
})
|
||||
|
||||
it('successive ambushes rotate to a different lane, deterministically', () => {
|
||||
const angles = (): number[] => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
const out: number[] = []
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
s.director.powerCooldowns.ambush = 0
|
||||
s.director.energy = 400
|
||||
applyAction(s, { type: 'ambush', kind: 'rusher' })
|
||||
}
|
||||
for (const e of s.enemies) {
|
||||
out.push(Math.atan2(e.pos.y - s.survivor.pos.y, e.pos.x - s.survivor.pos.x))
|
||||
}
|
||||
return out
|
||||
}
|
||||
const first = angles()
|
||||
expect(new Set(first).size).toBe(3)
|
||||
expect(angles()).toEqual(first)
|
||||
})
|
||||
|
||||
it('frenzy sets its timer and debits the cost', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'frenzy' })).toBe(true)
|
||||
expect(s.director.frenzyTimer).toBe(FRENZY_DURATION)
|
||||
expect(s.director.energy).toBe(400 - POWER_COST.frenzy)
|
||||
})
|
||||
|
||||
it('frenzy is rejected when unaffordable', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 10
|
||||
expect(applyAction(s, { type: 'frenzy' })).toBe(false)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
})
|
||||
|
||||
it('a rift pins every spawn to the chosen edge', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 400
|
||||
expect(applyAction(s, { type: 'rift', edge: 2 })).toBe(true)
|
||||
expect(s.director.riftTimer).toBe(RIFT_DURATION)
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
expect(edgeSpawnPos(s).x).toBe(0)
|
||||
}
|
||||
})
|
||||
|
||||
it('once the rift closes, all four edges return', () => {
|
||||
const s = fresh(7)
|
||||
s.director.riftTimer = 0
|
||||
const seen = new Set<string>()
|
||||
for (let i = 0; i < 40; i += 1) {
|
||||
const p = edgeSpawnPos(s)
|
||||
seen.add(`${String(p.x === 0 || p.x === ARENA.w)}-${String(p.y === 0 || p.y === ARENA.h)}`)
|
||||
}
|
||||
expect(seen.size).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
it('a rift is rejected when unaffordable', () => {
|
||||
const s = fresh()
|
||||
s.director.energy = 1
|
||||
expect(applyAction(s, { type: 'rift', edge: 1 })).toBe(false)
|
||||
expect(s.director.riftTimer).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('difficulty economy', () => {
|
||||
it('regen defaults to a rate of 1', () => {
|
||||
expect(regenRate(0)).toBe(6)
|
||||
expect(regenRate(30)).toBe(8)
|
||||
})
|
||||
|
||||
it('regen scales with the tier rate', () => {
|
||||
expect(regenRate(0, 1.25)).toBeCloseTo(7.5)
|
||||
expect(regenRate(0, 0.85)).toBeCloseTo(5.1)
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,49 +1,36 @@
|
||||
import { makeEnemy } from './sim'
|
||||
import { nextFloat, pick } from './rng'
|
||||
import type { BossKind, DirectorAction, EdgeId, GameState, PowerKind, UnitKind } from './types'
|
||||
import type { BossKind, DirectorAction, GameState, UnitKind } from './types'
|
||||
import {
|
||||
AMBUSH_RADIUS, ARENA, BOSS_COOLDOWN, BOSS_ORDER, BOSS_UNLOCK_AT, EDGE_ORDER, ENERGY_CAP,
|
||||
ENEMY_SPECS, FRENZY_DURATION, GOLDEN_ANGLE, POWER_COOLDOWN, POWER_COST, POWER_ORDER,
|
||||
RIFT_DURATION,
|
||||
ARENA, BOSS_COOLDOWN, BOSS_ORDER, BOSS_UNLOCK_AT, ENERGY_CAP, ENEMY_SPECS,
|
||||
} from './types'
|
||||
import type { Vec } from './vec'
|
||||
import { clamp } from './vec'
|
||||
|
||||
/** Energy per second: ramps every 30 seconds so pressure always grows. */
|
||||
export const regenRate = (t: number, rate = 1): number => (6 + 2 * Math.floor(t / 30)) * rate
|
||||
export const regenRate = (t: number): number => 6 + 2 * Math.floor(t / 30)
|
||||
|
||||
export const waveCost = (waveIndex: number): number => 60 + 25 * waveIndex
|
||||
|
||||
export const tickDirector = (state: GameState, dt: number): void => {
|
||||
const d = state.director
|
||||
d.energy = Math.min(ENERGY_CAP, d.energy + regenRate(state.t, state.difficulty.energyRate) * dt)
|
||||
d.energy = Math.min(ENERGY_CAP, d.energy + regenRate(state.t) * dt)
|
||||
for (const boss of BOSS_ORDER) {
|
||||
d.bossCooldowns[boss] = Math.max(0, d.bossCooldowns[boss] - dt)
|
||||
}
|
||||
for (const power of POWER_ORDER) {
|
||||
d.powerCooldowns[power] = Math.max(0, d.powerCooldowns[power] - dt)
|
||||
}
|
||||
d.frenzyTimer = Math.max(0, d.frenzyTimer - dt)
|
||||
d.riftTimer = Math.max(0, d.riftTimer - dt)
|
||||
}
|
||||
|
||||
type EdgeFn = (roll: number) => Vec
|
||||
/** Keyed by EdgeId rather than an array: index access then stays non-optional. */
|
||||
const EDGES: Record<EdgeId, EdgeFn> = {
|
||||
0: (roll): Vec => ({ x: roll * ARENA.w, y: 0 }),
|
||||
1: (roll): Vec => ({ x: roll * ARENA.w, y: ARENA.h }),
|
||||
2: (roll): Vec => ({ x: 0, y: roll * ARENA.h }),
|
||||
3: (roll): Vec => ({ x: ARENA.w, y: roll * ARENA.h }),
|
||||
}
|
||||
const EDGES: readonly [EdgeFn, ...EdgeFn[]] = [
|
||||
(roll): Vec => ({ x: roll * ARENA.w, y: 0 }),
|
||||
(roll): Vec => ({ x: roll * ARENA.w, y: ARENA.h }),
|
||||
(roll): Vec => ({ x: 0, y: roll * ARENA.h }),
|
||||
(roll): Vec => ({ x: ARENA.w, y: roll * ARENA.h }),
|
||||
]
|
||||
|
||||
/**
|
||||
* A live rift pins the edge; otherwise the RNG picks. The unpinned path draws
|
||||
* exactly two values in the original order, so existing seeded replays are unchanged.
|
||||
*/
|
||||
export const edgeSpawnPos = (state: GameState): Vec => {
|
||||
const d = state.director
|
||||
const chosen = d.riftTimer > 0 ? d.riftEdge : pick(state.rng, EDGE_ORDER)
|
||||
return EDGES[chosen](nextFloat(state.rng))
|
||||
const edge = pick(state.rng, EDGES)
|
||||
return edge(nextFloat(state.rng))
|
||||
}
|
||||
|
||||
const spawnUnit = (state: GameState, kind: UnitKind): boolean => {
|
||||
@ -96,62 +83,6 @@ const summonBoss = (state: GameState, kind: BossKind): boolean => {
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared gate for every power: one cooldown check and one affordability check,
|
||||
* so adding a power costs no new branches here.
|
||||
*
|
||||
* Named `spendPower`, not `usePower`: the React hooks lint rules treat any
|
||||
* `use`-prefixed function as a hook and reject calls from plain functions.
|
||||
*/
|
||||
const spendPower = (state: GameState, kind: PowerKind, extra: number): boolean => {
|
||||
const d = state.director
|
||||
if (d.powerCooldowns[kind] > 0) {
|
||||
return false
|
||||
}
|
||||
const cost = POWER_COST[kind] + extra
|
||||
if (d.energy < cost) {
|
||||
return false
|
||||
}
|
||||
d.energy -= cost
|
||||
d.powerCooldowns[kind] = POWER_COOLDOWN[kind]
|
||||
return true
|
||||
}
|
||||
|
||||
const ambush = (state: GameState, kind: UnitKind): boolean => {
|
||||
if (!spendPower(state, 'ambush', ENEMY_SPECS[kind].cost)) {
|
||||
return false
|
||||
}
|
||||
const d = state.director
|
||||
// Golden angle: an irrational fraction of a turn, so successive ambushes keep
|
||||
// landing in the widest remaining gap and never repeat a lane. (A rational
|
||||
// step like 2*PI/7 looks varied but silently cycles every 7 summons.)
|
||||
const angle = d.ambushIndex * GOLDEN_ANGLE
|
||||
d.ambushIndex += 1
|
||||
const sv = state.survivor.pos
|
||||
makeEnemy(state, kind, {
|
||||
x: clamp(sv.x + Math.cos(angle) * AMBUSH_RADIUS, 10, ARENA.w - 10),
|
||||
y: clamp(sv.y + Math.sin(angle) * AMBUSH_RADIUS, 10, ARENA.h - 10),
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
const frenzy = (state: GameState): boolean => {
|
||||
if (!spendPower(state, 'frenzy', 0)) {
|
||||
return false
|
||||
}
|
||||
state.director.frenzyTimer = FRENZY_DURATION
|
||||
return true
|
||||
}
|
||||
|
||||
const rift = (state: GameState, edge: EdgeId): boolean => {
|
||||
if (!spendPower(state, 'rift', 0)) {
|
||||
return false
|
||||
}
|
||||
state.director.riftEdge = edge
|
||||
state.director.riftTimer = RIFT_DURATION
|
||||
return true
|
||||
}
|
||||
|
||||
/** Applies a director order. Returns false when rejected (cost, lock, or cooldown). */
|
||||
export const applyAction = (state: GameState, action: DirectorAction): boolean => {
|
||||
switch (action.type) {
|
||||
@ -161,11 +92,5 @@ export const applyAction = (state: GameState, action: DirectorAction): boolean =
|
||||
return callWave(state)
|
||||
case 'boss':
|
||||
return summonBoss(state, action.kind)
|
||||
case 'ambush':
|
||||
return ambush(state, action.kind)
|
||||
case 'frenzy':
|
||||
return frenzy(state)
|
||||
case 'rift':
|
||||
return rift(state, action.edge)
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,12 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
applyUpgrade, createInitialState, DANGER_RADIUS, grantXp, makeEnemy, SPLIT_RADIUS, step,
|
||||
xpForLevel,
|
||||
applyUpgrade, createInitialState, DANGER_RADIUS, grantXp, makeEnemy, step, xpForLevel,
|
||||
} from './sim'
|
||||
import type { GameState, Projectile } from './types'
|
||||
import {
|
||||
ARENA, DIFFICULTIES, FRENZY_DAMAGE, FRENZY_SPEED, GAME_DURATION, STATUS_POWER,
|
||||
} from './types'
|
||||
import { ARENA, GAME_DURATION } from './types'
|
||||
|
||||
const CENTER = { x: ARENA.w / 2, y: ARENA.h / 2 }
|
||||
|
||||
@ -22,8 +19,6 @@ const shot = (state: GameState, x: number, y: number, damage: number): Projectil
|
||||
radius: 4,
|
||||
damage,
|
||||
ttl: 1,
|
||||
debuff: 'slow',
|
||||
debuffDuration: 0,
|
||||
}
|
||||
state.nextId += 1
|
||||
state.projectiles.push(p)
|
||||
@ -316,7 +311,6 @@ describe('projectiles', () => {
|
||||
s.projectiles.push({
|
||||
id: 500, from: 'enemy', pos: { x: CENTER.x, y: CENTER.y },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 7, ttl: 1,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
})
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.hp).toBe(93)
|
||||
@ -328,7 +322,6 @@ describe('projectiles', () => {
|
||||
s.projectiles.push({
|
||||
id: 501, from: 'enemy', pos: { x: 30, y: 30 },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 7, ttl: 1,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
})
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.hp).toBe(100)
|
||||
@ -375,324 +368,3 @@ describe('game end', () => {
|
||||
expect(s.director.energy).toBeLessThan(30)
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitter', () => {
|
||||
it('dies into three rushers at fixed offsets', () => {
|
||||
const s = fresh()
|
||||
const sp = makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
const children = s.enemies.filter((e) => e.id !== sp.id)
|
||||
expect(children).toHaveLength(3)
|
||||
expect(children.every((c) => c.kind === 'rusher')).toBe(true)
|
||||
// Children drift toward the survivor within the same tick, so assert the
|
||||
// spawn ring loosely — the exact geometry is pinned by the test below.
|
||||
for (const c of children) {
|
||||
expect(Math.hypot(c.pos.x - 300, c.pos.y - 300)).toBeLessThan(SPLIT_RADIUS + 5)
|
||||
}
|
||||
})
|
||||
|
||||
it('spawns children on a ring at 120-degree offsets', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
// dt of 0 isolates the spawn geometry from the movement that follows it.
|
||||
step(s, [], 0)
|
||||
const angles = s.enemies
|
||||
.map((e) => Math.atan2(e.pos.y - 300, e.pos.x - 300))
|
||||
.sort((a, b) => a - b)
|
||||
expect(angles).toHaveLength(3)
|
||||
// Pairwise gaps without indexing (noUncheckedIndexedAccess would widen those).
|
||||
const gaps: number[] = []
|
||||
let prev: number | null = null
|
||||
for (const a of angles) {
|
||||
if (prev !== null) {
|
||||
gaps.push(a - prev)
|
||||
}
|
||||
prev = a
|
||||
}
|
||||
expect(gaps).toHaveLength(2)
|
||||
for (const g of gaps) {
|
||||
expect(g).toBeCloseTo((Math.PI * 2) / 3, 5)
|
||||
}
|
||||
})
|
||||
|
||||
it('children are deterministic and draw no RNG', () => {
|
||||
const run = (): { x: number; y: number }[] => {
|
||||
const s = fresh(42)
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
return s.enemies.map((e) => ({ x: e.pos.x, y: e.pos.y }))
|
||||
}
|
||||
expect(run()).toEqual(run())
|
||||
})
|
||||
|
||||
it('clamps children into the arena when it dies in a corner', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 2, y: 2 })
|
||||
shot(s, 2, 2, 999)
|
||||
step(s, [], 0.001)
|
||||
for (const e of s.enemies) {
|
||||
expect(e.pos.x).toBeGreaterThanOrEqual(10)
|
||||
expect(e.pos.y).toBeGreaterThanOrEqual(10)
|
||||
}
|
||||
})
|
||||
|
||||
it('a later projectile in the same tick can hit a fresh child', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'splitter', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
shot(s, 300 + SPLIT_RADIUS, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.kills).toBe(2)
|
||||
})
|
||||
|
||||
it('non-splitting kinds spawn no children', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: 300, y: 300 })
|
||||
shot(s, 300, 300, 999)
|
||||
step(s, [], 0.001)
|
||||
expect(s.enemies).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('new units', () => {
|
||||
it('artillery outranges the survivor and fires while it cannot', () => {
|
||||
const s = fresh()
|
||||
const a = makeEnemy(s, 'artillery', { x: CENTER.x + 400, y: CENTER.y })
|
||||
a.fireTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.projectiles.some((p) => p.from === 'enemy')).toBe(true)
|
||||
expect(s.projectiles.some((p) => p.from === 'survivor')).toBe(false)
|
||||
})
|
||||
|
||||
it('artillery holds station at its keep distance', () => {
|
||||
const s = fresh()
|
||||
const a = makeEnemy(s, 'artillery', { x: CENTER.x + 420, y: CENTER.y })
|
||||
const before = a.pos.x
|
||||
step(s, [], 0.016)
|
||||
expect(a.pos.x).toBeCloseTo(before, 5)
|
||||
})
|
||||
|
||||
it('warden closes faster than a rusher', () => {
|
||||
const s = fresh()
|
||||
const w = makeEnemy(s, 'warden', { x: CENTER.x + 300, y: CENTER.y })
|
||||
const r = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.016)
|
||||
expect(CENTER.x + 300 - w.pos.x).toBeGreaterThan(CENTER.x + 300 - r.pos.x)
|
||||
})
|
||||
|
||||
it('the hivemind still births rushers via spawnKind', () => {
|
||||
const s = fresh()
|
||||
const h = makeEnemy(s, 'hivemind', { x: 40, y: 40 })
|
||||
h.spawnTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.enemies.some((e) => e.kind === 'rusher')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('status effects', () => {
|
||||
it('a warden contact mires the survivor and halves its movement', () => {
|
||||
const slowed = fresh()
|
||||
slowed.survivor.pos = { x: 100, y: CENTER.y }
|
||||
makeEnemy(slowed, 'warden', { x: 100, y: CENTER.y })
|
||||
step(slowed, [], 0.01)
|
||||
// Statuses tick in survivorStep, which runs before enemiesStep applies
|
||||
// contact — so a status landing this tick starts at its full duration.
|
||||
expect(slowed.survivor.statuses.slow).toBe(2.0)
|
||||
|
||||
// Control: same displacement, an enemy that inflicts nothing.
|
||||
const control = fresh()
|
||||
control.survivor.pos = { x: 100, y: CENTER.y }
|
||||
makeEnemy(control, 'rusher', { x: 100, y: CENTER.y })
|
||||
step(control, [], 0.01)
|
||||
expect(control.survivor.statuses.slow).toBe(0)
|
||||
|
||||
const before = { slowed: slowed.survivor.pos.x, control: control.survivor.pos.x }
|
||||
slowed.enemies = []
|
||||
control.enemies = []
|
||||
step(slowed, [], 0.05)
|
||||
step(control, [], 0.05)
|
||||
const movedSlowed = slowed.survivor.pos.x - before.slowed
|
||||
const movedControl = control.survivor.pos.x - before.control
|
||||
expect(movedSlowed).toBeCloseTo(movedControl * STATUS_POWER.slow, 5)
|
||||
})
|
||||
|
||||
it('slow expires and full speed returns', () => {
|
||||
const s = fresh()
|
||||
s.survivor.pos = { x: 100, y: CENTER.y }
|
||||
s.survivor.statuses.slow = 0.02
|
||||
step(s, [], 0.05)
|
||||
expect(s.survivor.statuses.slow).toBe(0)
|
||||
})
|
||||
|
||||
it('an artillery shell stifles the survivor and lengthens its reload', () => {
|
||||
const s = fresh()
|
||||
s.projectiles.push({
|
||||
id: 900, from: 'enemy', pos: { x: CENTER.x, y: CENTER.y },
|
||||
vel: { x: 0, y: 0 }, radius: 5, damage: 13, ttl: 1,
|
||||
debuff: 'suppress', debuffDuration: 2.5,
|
||||
})
|
||||
makeEnemy(s, 'tank', { x: CENTER.x + 200, y: CENTER.y })
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.statuses.suppress).toBeGreaterThan(0)
|
||||
// The shot fired this tick reloaded before the status landed; the next one pays.
|
||||
s.survivor.fireTimer = 0
|
||||
step(s, [], 0.001)
|
||||
expect(s.survivor.fireTimer).toBeCloseTo(0.55 * STATUS_POWER.suppress, 5)
|
||||
})
|
||||
|
||||
it('a leech contact blocks regeneration until it expires', () => {
|
||||
const s = fresh()
|
||||
s.survivor.regen = 5
|
||||
s.survivor.hp = 50
|
||||
makeEnemy(s, 'leech', { x: CENTER.x, y: CENTER.y })
|
||||
const hp0 = s.survivor.hp
|
||||
step(s, [], 0.1)
|
||||
// Contact damage lands and regen is suppressed, so hp cannot have risen.
|
||||
expect(s.survivor.hp).toBeLessThan(hp0)
|
||||
expect(s.survivor.statuses.bleed).toBeGreaterThan(0)
|
||||
|
||||
s.enemies = []
|
||||
s.survivor.statuses.bleed = 0
|
||||
const hp1 = s.survivor.hp
|
||||
step(s, [], 0.1)
|
||||
expect(s.survivor.hp).toBeGreaterThan(hp1)
|
||||
})
|
||||
|
||||
it('repeated warden contacts refresh rather than stack', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'warden', { x: CENTER.x, y: CENTER.y })
|
||||
makeEnemy(s, 'warden', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.statuses.slow).toBeLessThanOrEqual(2.0)
|
||||
})
|
||||
|
||||
it('a plain rusher inflicts no status at all', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.statuses).toEqual({ slow: 0, suppress: 0, bleed: 0 })
|
||||
})
|
||||
|
||||
it('survivor fire never debuffs the survivor', () => {
|
||||
const s = fresh()
|
||||
makeEnemy(s, 'tank', { x: CENTER.x + 200, y: CENTER.y })
|
||||
step(s, [], 0.001)
|
||||
const own = s.projectiles.find((p) => p.from === 'survivor')
|
||||
expect(own?.debuffDuration).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('frenzy', () => {
|
||||
it('speeds the horde while it lasts', () => {
|
||||
const base = fresh()
|
||||
const b = makeEnemy(base, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(base, [], 0.05)
|
||||
const normal = CENTER.x + 300 - b.pos.x
|
||||
|
||||
const hyped = fresh()
|
||||
hyped.director.frenzyTimer = 5
|
||||
const h = makeEnemy(hyped, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(hyped, [], 0.05)
|
||||
const rushed = CENTER.x + 300 - h.pos.x
|
||||
|
||||
expect(rushed).toBeCloseTo(normal * FRENZY_SPEED, 5)
|
||||
})
|
||||
|
||||
it('raises contact damage while it lasts', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 5
|
||||
makeEnemy(s, 'rusher', { x: CENTER.x, y: CENTER.y })
|
||||
step(s, [], 0.01)
|
||||
expect(s.survivor.hp).toBeCloseTo(100 - 6 * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('expires back to baseline speed', () => {
|
||||
const s = fresh()
|
||||
s.director.frenzyTimer = 0.01
|
||||
const e = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.5)
|
||||
expect(s.director.frenzyTimer).toBe(0)
|
||||
const after = e.pos.x
|
||||
step(s, [], 0.05)
|
||||
const moved = after - e.pos.x
|
||||
expect(moved).toBeCloseTo(170 * 0.05, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('difficulty tiers', () => {
|
||||
it('defaults to normal, the identity tier', () => {
|
||||
const s = fresh()
|
||||
expect(s.difficulty).toBe(DIFFICULTIES.normal)
|
||||
expect(s.survivor.maxHp).toBe(100)
|
||||
})
|
||||
|
||||
it('accepts an explicit tier', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
expect(s.difficulty).toBe(DIFFICULTIES.crusade)
|
||||
})
|
||||
|
||||
it('takes its duration from the tier when none is given', () => {
|
||||
expect(createInitialState(1, undefined, 'haunting').duration)
|
||||
.toBe(DIFFICULTIES.haunting.duration)
|
||||
})
|
||||
|
||||
it('an explicit duration still wins over the tier', () => {
|
||||
expect(createInitialState(1, 42, 'haunting').duration).toBe(42)
|
||||
})
|
||||
|
||||
it('scales enemy hp', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
const e = makeEnemy(s, 'rusher', { x: 0, y: 0 })
|
||||
expect(e.hp).toBeCloseTo(14 * DIFFICULTIES.crusade.enemyHp, 5)
|
||||
})
|
||||
|
||||
it('scales survivor hp', () => {
|
||||
const s = createInitialState(1, undefined, 'haunting')
|
||||
expect(s.survivor.maxHp).toBe(125)
|
||||
})
|
||||
|
||||
it('scales enemy speed', () => {
|
||||
const s = createInitialState(1, undefined, 'crusade')
|
||||
const e = makeEnemy(s, 'rusher', { x: CENTER.x + 300, y: CENTER.y })
|
||||
step(s, [], 0.05)
|
||||
const moved = CENTER.x + 300 - e.pos.x
|
||||
expect(moved).toBeCloseTo(170 * DIFFICULTIES.crusade.enemySpeed * 0.05, 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('frenzy damage reaches every channel', () => {
|
||||
// Regression: frenzy multiplied contact damage only, so ranged and blast
|
||||
// units — including the bomber, whose whole purpose is damage — ignored it.
|
||||
const dealt = (frenzied: boolean, kind: 'warden' | 'artillery' | 'bomber', at: number): number => {
|
||||
const s = fresh(3)
|
||||
s.survivor.hp = 1e6
|
||||
s.survivor.maxHp = 1e6
|
||||
s.survivor.speed = 0
|
||||
s.duration = 1e6
|
||||
if (frenzied) {
|
||||
s.director.frenzyTimer = 1e6
|
||||
}
|
||||
makeEnemy(s, kind, { x: CENTER.x + at, y: CENTER.y })
|
||||
const before = s.survivor.hp
|
||||
for (let i = 0; i < 360; i += 1) {
|
||||
step(s, [], 1 / 60)
|
||||
}
|
||||
return before - s.survivor.hp
|
||||
}
|
||||
|
||||
it('scales contact damage', () => {
|
||||
expect(dealt(true, 'warden', 0)).toBeCloseTo(dealt(false, 'warden', 0) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('scales ranged damage', () => {
|
||||
expect(dealt(true, 'artillery', 300))
|
||||
.toBeCloseTo(dealt(false, 'artillery', 300) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
|
||||
it('scales blast damage', () => {
|
||||
expect(dealt(true, 'bomber', 0)).toBeCloseTo(dealt(false, 'bomber', 0) * FRENZY_DAMAGE, 5)
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,13 +1,10 @@
|
||||
import { applyAction, tickDirector } from './director'
|
||||
import { createRng, pick } from './rng'
|
||||
import { applyStatus, factor, tickStatuses } from './status'
|
||||
import type {
|
||||
DifficultyConfig, DifficultyId, DirectorAction, Enemy, EnemyKind, EnemySpec, GameState,
|
||||
Survivor, UpgradeId,
|
||||
DirectorAction, Enemy, EnemyKind, GameState, Survivor, UpgradeId,
|
||||
} from './types'
|
||||
import {
|
||||
ARENA, CONTACT_COOLDOWN, DIFFICULTIES, ENERGY_START, ENEMY_SPECS, FRENZY_DAMAGE,
|
||||
FRENZY_SPEED, STATUS_POWER, UPGRADE_POOL,
|
||||
ARENA, CONTACT_COOLDOWN, ENERGY_START, ENEMY_SPECS, GAME_DURATION, UPGRADE_POOL,
|
||||
} from './types'
|
||||
import type { Vec } from './vec'
|
||||
import { clamp, dist, toward } from './vec'
|
||||
@ -22,10 +19,10 @@ const CENTER: Vec = { x: ARENA.w / 2, y: ARENA.h / 2 }
|
||||
|
||||
export const xpForLevel = (level: number): number => 20 + 15 * (level - 1)
|
||||
|
||||
const createSurvivor = (cfg: DifficultyConfig): Survivor => ({
|
||||
const createSurvivor = (): Survivor => ({
|
||||
pos: { x: CENTER.x, y: CENTER.y },
|
||||
hp: 100 * cfg.survivorHp,
|
||||
maxHp: 100 * cfg.survivorHp,
|
||||
hp: 100,
|
||||
maxHp: 100,
|
||||
speed: 150,
|
||||
regen: 0,
|
||||
damage: 8,
|
||||
@ -36,43 +33,25 @@ const createSurvivor = (cfg: DifficultyConfig): Survivor => ({
|
||||
xp: 0,
|
||||
xpNext: xpForLevel(1),
|
||||
kills: 0,
|
||||
statuses: { slow: 0, suppress: 0, bleed: 0 },
|
||||
})
|
||||
|
||||
export const createInitialState = (
|
||||
seed: number,
|
||||
duration?: number,
|
||||
difficulty: DifficultyId = 'normal',
|
||||
): GameState => {
|
||||
const cfg = DIFFICULTIES[difficulty]
|
||||
return {
|
||||
status: 'running',
|
||||
difficulty: cfg,
|
||||
t: 0,
|
||||
duration: duration ?? cfg.duration,
|
||||
rng: createRng(seed),
|
||||
survivor: createSurvivor(cfg),
|
||||
enemies: [],
|
||||
projectiles: [],
|
||||
director: {
|
||||
energy: ENERGY_START,
|
||||
waveIndex: 0,
|
||||
bossCooldowns: { colossus: 0, hivemind: 0, leech: 0 },
|
||||
powerCooldowns: { ambush: 0, frenzy: 0, rift: 0 },
|
||||
frenzyTimer: 0,
|
||||
riftTimer: 0,
|
||||
riftEdge: 0,
|
||||
ambushIndex: 0,
|
||||
},
|
||||
upgrades: [],
|
||||
nextId: 1,
|
||||
outcomeTime: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** Single place enemy speed is derived: difficulty and frenzy both land here. */
|
||||
export const enemySpeed = (state: GameState, kind: EnemyKind, frenzyMul: number): number =>
|
||||
ENEMY_SPECS[kind].speed * state.difficulty.enemySpeed * frenzyMul
|
||||
export const createInitialState = (seed: number, duration = GAME_DURATION): GameState => ({
|
||||
status: 'running',
|
||||
t: 0,
|
||||
duration,
|
||||
rng: createRng(seed),
|
||||
survivor: createSurvivor(),
|
||||
enemies: [],
|
||||
projectiles: [],
|
||||
director: {
|
||||
energy: ENERGY_START,
|
||||
waveIndex: 0,
|
||||
bossCooldowns: { colossus: 0, hivemind: 0 },
|
||||
},
|
||||
upgrades: [],
|
||||
nextId: 1,
|
||||
outcomeTime: 0,
|
||||
})
|
||||
|
||||
export const makeEnemy = (state: GameState, kind: EnemyKind, pos: Vec): Enemy => {
|
||||
const id = state.nextId
|
||||
@ -81,7 +60,7 @@ export const makeEnemy = (state: GameState, kind: EnemyKind, pos: Vec): Enemy =>
|
||||
id,
|
||||
kind,
|
||||
pos: { x: pos.x, y: pos.y },
|
||||
hp: ENEMY_SPECS[kind].hp * state.difficulty.enemyHp,
|
||||
hp: ENEMY_SPECS[kind].hp,
|
||||
hitTimer: 0,
|
||||
fireTimer: 0,
|
||||
spawnTimer: ENEMY_SPECS[kind].spawnEvery,
|
||||
@ -131,13 +110,6 @@ const nearestEnemy = (state: GameState): Enemy | null => {
|
||||
|
||||
const survivorStep = (state: GameState, dt: number): void => {
|
||||
const sv = state.survivor
|
||||
// Tick before reading: a status applied this tick is felt from the next one,
|
||||
// and a 0-second (inert) application is never observable.
|
||||
tickStatuses(sv, dt)
|
||||
const moveMul = factor(sv.statuses.slow, STATUS_POWER.slow)
|
||||
const fireMul = factor(sv.statuses.suppress, STATUS_POWER.suppress)
|
||||
const regenMul = factor(sv.statuses.bleed, STATUS_POWER.bleed)
|
||||
const speed = sv.speed * moveMul
|
||||
let fleeX = 0
|
||||
let fleeY = 0
|
||||
for (const e of state.enemies) {
|
||||
@ -151,14 +123,14 @@ const survivorStep = (state: GameState, dt: number): void => {
|
||||
const fleeMag = Math.hypot(fleeX, fleeY)
|
||||
let vel: Vec = { x: 0, y: 0 }
|
||||
if (fleeMag > 0) {
|
||||
vel = { x: (fleeX / fleeMag) * speed, y: (fleeY / fleeMag) * speed }
|
||||
vel = { x: (fleeX / fleeMag) * sv.speed, y: (fleeY / fleeMag) * sv.speed }
|
||||
} else if (dist(sv.pos, CENTER) > 4) {
|
||||
vel = toward(sv.pos, CENTER, speed * 0.4)
|
||||
vel = toward(sv.pos, CENTER, sv.speed * 0.4)
|
||||
}
|
||||
sv.pos.x = clamp(sv.pos.x + vel.x * dt, SURVIVOR_RADIUS, ARENA.w - SURVIVOR_RADIUS)
|
||||
sv.pos.y = clamp(sv.pos.y + vel.y * dt, SURVIVOR_RADIUS, ARENA.h - SURVIVOR_RADIUS)
|
||||
|
||||
sv.hp = Math.min(sv.maxHp, sv.hp + sv.regen * regenMul * dt)
|
||||
sv.hp = Math.min(sv.maxHp, sv.hp + sv.regen * dt)
|
||||
|
||||
sv.fireTimer = Math.max(0, sv.fireTimer - dt)
|
||||
const target = nearestEnemy(state)
|
||||
@ -176,42 +148,17 @@ const survivorStep = (state: GameState, dt: number): void => {
|
||||
radius: 4,
|
||||
damage: sv.damage,
|
||||
ttl: PROJ_TTL,
|
||||
debuff: 'slow',
|
||||
debuffDuration: 0,
|
||||
})
|
||||
}
|
||||
// Suppression scales the reload, not the countdown: the remaining timer stays
|
||||
// linear in dt, which keeps replays and assertions exact.
|
||||
sv.fireTimer = sv.fireCooldown * fireMul
|
||||
sv.fireTimer = sv.fireCooldown
|
||||
}
|
||||
}
|
||||
|
||||
/** Frenzy's damage multiplier, derived from state so every damage channel agrees. */
|
||||
export const frenzyDamageMul = (state: GameState): number =>
|
||||
factor(state.director.frenzyTimer, FRENZY_DAMAGE)
|
||||
|
||||
const detonate = (state: GameState, enemy: Enemy): void => {
|
||||
const spec = ENEMY_SPECS[enemy.kind]
|
||||
enemy.hp = 0
|
||||
if (dist(enemy.pos, state.survivor.pos) <= spec.blastRadius) {
|
||||
state.survivor.hp -= spec.blastDamage * frenzyDamageMul(state)
|
||||
}
|
||||
}
|
||||
|
||||
export const SPLIT_RADIUS = 22
|
||||
|
||||
/**
|
||||
* Emits `splitCount` children at fixed angular offsets. Deterministic on purpose:
|
||||
* drawing from the RNG here would shift every seeded replay downstream.
|
||||
* Loop-only — `splitCount: 0` makes this a no-op without a guard branch.
|
||||
*/
|
||||
const split = (state: GameState, spec: EnemySpec, pos: Vec): void => {
|
||||
for (let i = 0; i < spec.splitCount; i += 1) {
|
||||
const angle = (Math.PI * 2 * i) / spec.splitCount
|
||||
makeEnemy(state, spec.spawnKind, {
|
||||
x: clamp(pos.x + Math.cos(angle) * SPLIT_RADIUS, 10, ARENA.w - 10),
|
||||
y: clamp(pos.y + Math.sin(angle) * SPLIT_RADIUS, 10, ARENA.h - 10),
|
||||
})
|
||||
state.survivor.hp -= spec.blastDamage
|
||||
}
|
||||
}
|
||||
|
||||
@ -222,20 +169,17 @@ const killByShot = (state: GameState, enemy: Enemy): void => {
|
||||
if (spec.detonates) {
|
||||
detonate(state, enemy)
|
||||
}
|
||||
split(state, spec, enemy.pos)
|
||||
}
|
||||
|
||||
type MoveFn = (e: Enemy, sv: Survivor, d: number, speed: number) => Vec
|
||||
|
||||
const MOVE_FNS: Record<'chase' | 'skirmish', MoveFn> = {
|
||||
chase: (e, sv, _d, speed) => toward(e.pos, sv.pos, speed),
|
||||
skirmish: (e, sv, d, speed) => {
|
||||
const MOVE_FNS: Record<'chase' | 'skirmish', (e: Enemy, sv: Survivor, d: number) => Vec> = {
|
||||
chase: (e, sv) => toward(e.pos, sv.pos, ENEMY_SPECS[e.kind].speed),
|
||||
skirmish: (e, sv, d) => {
|
||||
const spec = ENEMY_SPECS[e.kind]
|
||||
if (d > spec.keepDistance) {
|
||||
return toward(e.pos, sv.pos, speed)
|
||||
return toward(e.pos, sv.pos, spec.speed)
|
||||
}
|
||||
if (d < spec.keepDistance * 0.65) {
|
||||
return toward(sv.pos, e.pos, speed)
|
||||
return toward(sv.pos, e.pos, spec.speed)
|
||||
}
|
||||
return { x: 0, y: 0 }
|
||||
},
|
||||
@ -244,14 +188,11 @@ const MOVE_FNS: Record<'chase' | 'skirmish', MoveFn> = {
|
||||
const enemiesStep = (state: GameState, dt: number): void => {
|
||||
const sv = state.survivor
|
||||
const spawned: { kind: EnemyKind; pos: Vec }[] = []
|
||||
// Frenzy is read straight off director state — no import, so no new import cycle.
|
||||
const speedMul = factor(state.director.frenzyTimer, FRENZY_SPEED)
|
||||
const damageMul = frenzyDamageMul(state)
|
||||
for (const e of state.enemies) {
|
||||
const spec = ENEMY_SPECS[e.kind]
|
||||
e.hitTimer = Math.max(0, e.hitTimer - dt)
|
||||
const d = dist(e.pos, sv.pos)
|
||||
const vel = MOVE_FNS[spec.move](e, sv, d, enemySpeed(state, e.kind, speedMul))
|
||||
const vel = MOVE_FNS[spec.move](e, sv, d)
|
||||
e.pos.x = clamp(e.pos.x + vel.x * dt, spec.radius, ARENA.w - spec.radius)
|
||||
e.pos.y = clamp(e.pos.y + vel.y * dt, spec.radius, ARENA.h - spec.radius)
|
||||
|
||||
@ -259,10 +200,7 @@ const enemiesStep = (state: GameState, dt: number): void => {
|
||||
if (spec.detonates) {
|
||||
detonate(state, e)
|
||||
} else if (e.hitTimer === 0) {
|
||||
sv.hp -= spec.contactDamage * damageMul
|
||||
// Unconditional: a 0-duration spec makes this a provable no-op, which is
|
||||
// cheaper than a guard branch under the 100 % gate.
|
||||
applyStatus(sv, spec.debuff, spec.debuffDuration)
|
||||
sv.hp -= spec.contactDamage
|
||||
e.hitTimer = CONTACT_COOLDOWN
|
||||
}
|
||||
}
|
||||
@ -278,10 +216,8 @@ const enemiesStep = (state: GameState, dt: number): void => {
|
||||
pos: { x: e.pos.x, y: e.pos.y },
|
||||
vel: toward(e.pos, sv.pos, spec.projSpeed),
|
||||
radius: 5,
|
||||
damage: spec.projDamage * damageMul,
|
||||
damage: spec.projDamage,
|
||||
ttl: ENEMY_PROJ_TTL,
|
||||
debuff: spec.debuff,
|
||||
debuffDuration: spec.debuffDuration,
|
||||
})
|
||||
e.fireTimer = spec.fireCooldown
|
||||
}
|
||||
@ -290,7 +226,7 @@ const enemiesStep = (state: GameState, dt: number): void => {
|
||||
if (spec.spawnEvery > 0) {
|
||||
e.spawnTimer = Math.max(0, e.spawnTimer - dt)
|
||||
if (e.spawnTimer === 0) {
|
||||
spawned.push({ kind: spec.spawnKind, pos: { x: e.pos.x, y: e.pos.y } })
|
||||
spawned.push({ kind: 'rusher', pos: { x: e.pos.x, y: e.pos.y } })
|
||||
e.spawnTimer = spec.spawnEvery
|
||||
}
|
||||
}
|
||||
@ -330,7 +266,6 @@ const projectilesStep = (state: GameState, dt: number): void => {
|
||||
}
|
||||
} else if (dist(p.pos, sv.pos) <= p.radius + SURVIVOR_RADIUS) {
|
||||
sv.hp -= p.damage
|
||||
applyStatus(sv, p.debuff, p.debuffDuration)
|
||||
continue
|
||||
}
|
||||
surviving.push(p)
|
||||
|
||||
@ -1,17 +1,11 @@
|
||||
import { waveCost } from './director'
|
||||
import type {
|
||||
BossKind, EdgeId, GameState, PowerKind, Status, StatusKind, UnitKind, UpgradeId,
|
||||
} from './types'
|
||||
import type { BossKind, GameState, Status, UnitKind, UpgradeId } from './types'
|
||||
import {
|
||||
BOSS_ORDER, BOSS_UNLOCK_AT, EDGE_NAMES, EDGE_ORDER, ENERGY_CAP, ENEMY_SPECS, POWER_COST,
|
||||
POWER_NAMES, POWER_ORDER, STATUS_LABELS, STATUS_ORDER, UNIT_ORDER,
|
||||
BOSS_ORDER, BOSS_UNLOCK_AT, ENERGY_CAP, ENEMY_SPECS, UNIT_ORDER,
|
||||
} from './types'
|
||||
|
||||
export type BossPhase = 'locked' | 'cooling' | 'ready'
|
||||
|
||||
/** Ambush summons a fixed cheap unit, so the bar needs no unit-selection mode. */
|
||||
export const AMBUSH_UNIT: UnitKind = 'rusher'
|
||||
|
||||
export interface UnitButton {
|
||||
kind: UnitKind
|
||||
name: string
|
||||
@ -34,27 +28,6 @@ export interface UpgradeEntry {
|
||||
id: UpgradeId
|
||||
}
|
||||
|
||||
export interface PowerButton {
|
||||
kind: PowerKind
|
||||
name: string
|
||||
cost: number
|
||||
cooldown: number
|
||||
ready: boolean
|
||||
affordable: boolean
|
||||
}
|
||||
|
||||
export interface EdgeButton {
|
||||
edge: EdgeId
|
||||
name: string
|
||||
active: boolean
|
||||
}
|
||||
|
||||
export interface StatusChip {
|
||||
kind: StatusKind
|
||||
label: string
|
||||
seconds: number
|
||||
}
|
||||
|
||||
export interface HudSnapshot {
|
||||
status: Status
|
||||
t: number
|
||||
@ -71,12 +44,6 @@ export interface HudSnapshot {
|
||||
upgrades: UpgradeEntry[]
|
||||
units: UnitButton[]
|
||||
bosses: BossButton[]
|
||||
statuses: StatusChip[]
|
||||
powers: Record<PowerKind, PowerButton>
|
||||
edges: EdgeButton[]
|
||||
frenzyActive: boolean
|
||||
riftSeconds: number
|
||||
ambushKind: UnitKind
|
||||
outcomeTime: number
|
||||
}
|
||||
|
||||
@ -90,29 +57,6 @@ const bossPhase = (state: GameState, kind: BossKind): BossPhase => {
|
||||
return 'ready'
|
||||
}
|
||||
|
||||
/** Ambush also pays for the unit it summons; the others carry no surcharge. */
|
||||
const POWER_SURCHARGE: Record<PowerKind, number> = {
|
||||
ambush: ENEMY_SPECS[AMBUSH_UNIT].cost,
|
||||
frenzy: 0,
|
||||
rift: 0,
|
||||
}
|
||||
|
||||
const powerButtons = (state: GameState): Record<PowerKind, PowerButton> => {
|
||||
const out = {} as Record<PowerKind, PowerButton>
|
||||
for (const kind of POWER_ORDER) {
|
||||
const cost = POWER_COST[kind] + POWER_SURCHARGE[kind]
|
||||
out[kind] = {
|
||||
kind,
|
||||
name: POWER_NAMES[kind],
|
||||
cost,
|
||||
cooldown: Math.ceil(state.director.powerCooldowns[kind]),
|
||||
ready: state.director.powerCooldowns[kind] === 0,
|
||||
affordable: state.director.energy >= cost,
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export const snapshotOf = (state: GameState): HudSnapshot => ({
|
||||
status: state.status,
|
||||
t: state.t,
|
||||
@ -127,13 +71,6 @@ export const snapshotOf = (state: GameState): HudSnapshot => ({
|
||||
survivorLevel: state.survivor.level,
|
||||
kills: state.survivor.kills,
|
||||
upgrades: state.upgrades.map((id, i) => ({ n: i + 1, id })).slice(-3),
|
||||
statuses: STATUS_ORDER
|
||||
.map((kind) => ({
|
||||
kind,
|
||||
label: STATUS_LABELS[kind],
|
||||
seconds: Math.ceil(state.survivor.statuses[kind]),
|
||||
}))
|
||||
.filter((chip) => chip.seconds > 0),
|
||||
units: UNIT_ORDER.map((kind) => ({
|
||||
kind,
|
||||
name: ENEMY_SPECS[kind].name,
|
||||
@ -149,14 +86,5 @@ export const snapshotOf = (state: GameState): HudSnapshot => ({
|
||||
cooldown: Math.ceil(state.director.bossCooldowns[kind]),
|
||||
affordable: state.director.energy >= ENEMY_SPECS[kind].cost,
|
||||
})),
|
||||
powers: powerButtons(state),
|
||||
edges: EDGE_ORDER.map((edge) => ({
|
||||
edge,
|
||||
name: EDGE_NAMES[edge],
|
||||
active: state.director.riftTimer > 0 && state.director.riftEdge === edge,
|
||||
})),
|
||||
frenzyActive: state.director.frenzyTimer > 0,
|
||||
riftSeconds: Math.ceil(state.director.riftTimer),
|
||||
ambushKind: AMBUSH_UNIT,
|
||||
outcomeTime: state.outcomeTime,
|
||||
})
|
||||
|
||||
@ -1,82 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { applyStatus, factor, isOn, tickStatuses } from './status'
|
||||
import type { Survivor } from './types'
|
||||
import { STATUS_POWER } from './types'
|
||||
|
||||
const sv = (): Survivor => ({
|
||||
pos: { x: 0, y: 0 },
|
||||
hp: 100,
|
||||
maxHp: 100,
|
||||
speed: 150,
|
||||
regen: 0,
|
||||
damage: 8,
|
||||
multishot: 1,
|
||||
fireCooldown: 0.55,
|
||||
fireTimer: 0,
|
||||
level: 1,
|
||||
xp: 0,
|
||||
xpNext: 20,
|
||||
kills: 0,
|
||||
statuses: { slow: 0, suppress: 0, bleed: 0 },
|
||||
})
|
||||
|
||||
describe('isOn', () => {
|
||||
it('is 0 only at exactly zero', () => {
|
||||
expect(isOn(0)).toBe(0)
|
||||
})
|
||||
|
||||
it('is 1 for any live remainder, however small', () => {
|
||||
expect(isOn(0.001)).toBe(1)
|
||||
expect(isOn(5)).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('factor', () => {
|
||||
it('is 1 when the timer is idle', () => {
|
||||
expect(factor(0, STATUS_POWER.slow)).toBe(1)
|
||||
})
|
||||
|
||||
it('is the active multiplier while the timer runs', () => {
|
||||
expect(factor(2, STATUS_POWER.slow)).toBeCloseTo(0.55)
|
||||
})
|
||||
|
||||
it('supports a total shutdown multiplier', () => {
|
||||
expect(factor(1, STATUS_POWER.bleed)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('tickStatuses', () => {
|
||||
it('drains every timer and floors at zero', () => {
|
||||
const s = sv()
|
||||
s.statuses.slow = 1
|
||||
s.statuses.suppress = 0.4
|
||||
tickStatuses(s, 0.5)
|
||||
expect(s.statuses.slow).toBeCloseTo(0.5)
|
||||
expect(s.statuses.suppress).toBe(0)
|
||||
expect(s.statuses.bleed).toBe(0)
|
||||
})
|
||||
|
||||
it('never goes negative on a large dt', () => {
|
||||
const s = sv()
|
||||
s.statuses.bleed = 1
|
||||
tickStatuses(s, 99)
|
||||
expect(s.statuses.bleed).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('applyStatus', () => {
|
||||
it('refreshes to the longer remainder and never stacks', () => {
|
||||
const s = sv()
|
||||
applyStatus(s, 'slow', 2)
|
||||
applyStatus(s, 'slow', 1)
|
||||
expect(s.statuses.slow).toBe(2)
|
||||
applyStatus(s, 'slow', 3)
|
||||
expect(s.statuses.slow).toBe(3)
|
||||
})
|
||||
|
||||
it('a zero duration is a no-op, which is how inert specs call it', () => {
|
||||
const s = sv()
|
||||
applyStatus(s, 'bleed', 0)
|
||||
expect(s.statuses.bleed).toBe(0)
|
||||
})
|
||||
})
|
||||
@ -1,34 +0,0 @@
|
||||
import type { StatusKind, Survivor } from './types'
|
||||
import { STATUS_ORDER } from './types'
|
||||
|
||||
/**
|
||||
* 1 while the timer is live, 0 once it has expired.
|
||||
*
|
||||
* Deliberately arithmetic rather than `timer > 0`: every consumer of this value
|
||||
* multiplies by it, so an `if` here would add a branch pair per status per
|
||||
* consumer — the coverage gate is 100 % and those branches buy nothing.
|
||||
* Timers only reach 0 via `Math.max(0, t - dt)`, so the domain is [0, inf).
|
||||
*/
|
||||
export const isOn = (timer: number): number => Math.min(1, Math.ceil(timer))
|
||||
|
||||
/** `active` while the timer runs, 1 when idle. Branch-free blend. */
|
||||
export const factor = (timer: number, active: number): number =>
|
||||
1 - isOn(timer) * (1 - active)
|
||||
|
||||
export const tickStatuses = (sv: Survivor, dt: number): void => {
|
||||
for (const kind of STATUS_ORDER) {
|
||||
sv.statuses[kind] = Math.max(0, sv.statuses[kind] - dt)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh-not-stack: re-applying extends the timer, never compounds it.
|
||||
* This is what caps a horde's total lockdown at one status duration — the
|
||||
* guarantee is structural, not a tuned number.
|
||||
*
|
||||
* A 0-second duration is a no-op, which is how non-debuffing enemies call this
|
||||
* unconditionally without needing a guard branch.
|
||||
*/
|
||||
export const applyStatus = (sv: Survivor, kind: StatusKind, seconds: number): void => {
|
||||
sv.statuses[kind] = Math.max(sv.statuses[kind], seconds)
|
||||
}
|
||||
@ -7,25 +7,8 @@ export const CONTACT_COOLDOWN = 0.5
|
||||
export const ENERGY_CAP = 400
|
||||
export const ENERGY_START = 30
|
||||
|
||||
export type StatusKind = 'slow' | 'suppress' | 'bleed'
|
||||
export const STATUS_ORDER: readonly [StatusKind, ...StatusKind[]] = ['slow', 'suppress', 'bleed']
|
||||
|
||||
/** Multiplier applied to the survivor while the matching status is live. */
|
||||
export const STATUS_POWER: Record<StatusKind, number> = {
|
||||
slow: 0.55, // move speed
|
||||
suppress: 1.75, // fire cooldown — higher is slower
|
||||
bleed: 0, // regen
|
||||
}
|
||||
|
||||
export const STATUS_LABELS: Record<StatusKind, string> = {
|
||||
slow: 'mired',
|
||||
suppress: 'stifled',
|
||||
bleed: 'unknitting',
|
||||
}
|
||||
|
||||
export type UnitKind =
|
||||
| 'rusher' | 'stalker' | 'tank' | 'bomber' | 'splitter' | 'artillery' | 'warden'
|
||||
export type BossKind = 'colossus' | 'hivemind' | 'leech'
|
||||
export type UnitKind = 'rusher' | 'stalker' | 'tank' | 'bomber'
|
||||
export type BossKind = 'colossus' | 'hivemind'
|
||||
export type EnemyKind = UnitKind | BossKind
|
||||
export type MoveMode = 'chase' | 'skirmish'
|
||||
|
||||
@ -50,14 +33,6 @@ export interface EnemySpec {
|
||||
readonly blastDamage: number
|
||||
/** 0 disables minion spawning. */
|
||||
readonly spawnEvery: number
|
||||
/** What `spawnEvery` and `splitCount` emit. Always a kind — the `> 0` gates guard every read. */
|
||||
readonly spawnKind: UnitKind
|
||||
/** 0 disables on-death splitting. */
|
||||
readonly splitCount: number
|
||||
/** Status inflicted on contact (or on projectile hit). Inert when duration is 0. */
|
||||
readonly debuff: StatusKind
|
||||
/** 0 means this kind inflicts nothing — `applyStatus` becomes a no-op. */
|
||||
readonly debuffDuration: number
|
||||
}
|
||||
|
||||
const spec = (s: EnemySpec): EnemySpec => s
|
||||
@ -68,148 +43,43 @@ export const ENEMY_SPECS: Record<EnemyKind, EnemySpec> = {
|
||||
contactDamage: 6, xp: 4, move: 'chase',
|
||||
projDamage: 0, projSpeed: 0, fireRange: 0, fireCooldown: 0, keepDistance: 0,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
}),
|
||||
stalker: spec({
|
||||
name: 'Stalker', cost: 24, hp: 20, speed: 110, radius: 10,
|
||||
contactDamage: 4, xp: 8, move: 'skirmish',
|
||||
projDamage: 7, projSpeed: 260, fireRange: 250, fireCooldown: 1.6, keepDistance: 200,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
}),
|
||||
tank: spec({
|
||||
name: 'Tank', cost: 45, hp: 120, speed: 55, radius: 18,
|
||||
contactDamage: 14, xp: 20, move: 'chase',
|
||||
projDamage: 0, projSpeed: 0, fireRange: 0, fireCooldown: 0, keepDistance: 0,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
}),
|
||||
bomber: spec({
|
||||
name: 'Bomber', cost: 30, hp: 16, speed: 140, radius: 10,
|
||||
contactDamage: 0, xp: 10, move: 'chase',
|
||||
projDamage: 0, projSpeed: 0, fireRange: 0, fireCooldown: 0, keepDistance: 0,
|
||||
detonates: true, blastRadius: 70, blastDamage: 22, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
}),
|
||||
splitter: spec({
|
||||
name: 'Splitter', cost: 34, hp: 30, speed: 95, radius: 13,
|
||||
contactDamage: 5, xp: 12, move: 'chase',
|
||||
projDamage: 0, projSpeed: 0, fireRange: 0, fireCooldown: 0, keepDistance: 0,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 3,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
}),
|
||||
artillery: spec({
|
||||
name: 'Artillery', cost: 52, hp: 26, speed: 70, radius: 12,
|
||||
contactDamage: 0, xp: 16, move: 'skirmish',
|
||||
projDamage: 13, projSpeed: 190, fireRange: 460, fireCooldown: 2.6, keepDistance: 420,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'suppress', debuffDuration: 2.5,
|
||||
}),
|
||||
warden: spec({
|
||||
name: 'Warden', cost: 40, hp: 34, speed: 215, radius: 8,
|
||||
contactDamage: 7, xp: 14, move: 'chase',
|
||||
projDamage: 0, projSpeed: 0, fireRange: 0, fireCooldown: 0, keepDistance: 0,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'slow', debuffDuration: 2.0,
|
||||
}),
|
||||
colossus: spec({
|
||||
name: 'Colossus', cost: 150, hp: 700, speed: 40, radius: 34,
|
||||
contactDamage: 30, xp: 80, move: 'chase',
|
||||
projDamage: 0, projSpeed: 0, fireRange: 0, fireCooldown: 0, keepDistance: 0,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
}),
|
||||
hivemind: spec({
|
||||
name: 'Hivemind', cost: 220, hp: 420, speed: 60, radius: 28,
|
||||
contactDamage: 10, xp: 100, move: 'chase',
|
||||
projDamage: 0, projSpeed: 0, fireRange: 0, fireCooldown: 0, keepDistance: 0,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 2.5,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'slow', debuffDuration: 0,
|
||||
}),
|
||||
leech: spec({
|
||||
name: 'Leech', cost: 190, hp: 500, speed: 75, radius: 30,
|
||||
contactDamage: 12, xp: 90, move: 'chase',
|
||||
projDamage: 0, projSpeed: 0, fireRange: 0, fireCooldown: 0, keepDistance: 0,
|
||||
detonates: false, blastRadius: 0, blastDamage: 0, spawnEvery: 0,
|
||||
spawnKind: 'rusher', splitCount: 0,
|
||||
debuff: 'bleed', debuffDuration: 3.5,
|
||||
}),
|
||||
} as const
|
||||
|
||||
export const UNIT_ORDER: readonly [UnitKind, ...UnitKind[]] = [
|
||||
'rusher', 'stalker', 'tank', 'bomber', 'splitter', 'artillery', 'warden',
|
||||
]
|
||||
export const BOSS_ORDER: readonly [BossKind, ...BossKind[]] = ['colossus', 'hivemind', 'leech']
|
||||
export const BOSS_UNLOCK_AT: Record<BossKind, number> = {
|
||||
colossus: 60, hivemind: 120, leech: 180,
|
||||
}
|
||||
export const BOSS_COOLDOWN: Record<BossKind, number> = {
|
||||
colossus: 25, hivemind: 30, leech: 28,
|
||||
}
|
||||
|
||||
export type DifficultyId = 'haunting' | 'normal' | 'crusade'
|
||||
|
||||
export interface DifficultyConfig {
|
||||
readonly label: string
|
||||
readonly enemyHp: number
|
||||
readonly enemySpeed: number
|
||||
readonly survivorHp: number
|
||||
readonly energyRate: number
|
||||
readonly duration: number
|
||||
}
|
||||
|
||||
/** `normal` is exactly 1 across the board, so it is the identity tier. */
|
||||
export const DIFFICULTIES: Record<DifficultyId, DifficultyConfig> = {
|
||||
haunting: {
|
||||
label: 'Haunting',
|
||||
enemyHp: 0.85, enemySpeed: 0.95, survivorHp: 1.25, energyRate: 1.25, duration: 240,
|
||||
},
|
||||
normal: {
|
||||
label: 'Normal',
|
||||
enemyHp: 1, enemySpeed: 1, survivorHp: 1, energyRate: 1, duration: GAME_DURATION,
|
||||
},
|
||||
crusade: {
|
||||
label: 'Crusade',
|
||||
enemyHp: 1.2, enemySpeed: 1.05, survivorHp: 0.85, energyRate: 0.85, duration: 360,
|
||||
},
|
||||
}
|
||||
export const DIFFICULTY_ORDER: readonly [DifficultyId, ...DifficultyId[]] = [
|
||||
'haunting', 'normal', 'crusade',
|
||||
]
|
||||
|
||||
export type PowerKind = 'ambush' | 'frenzy' | 'rift'
|
||||
export const POWER_ORDER: readonly [PowerKind, ...PowerKind[]] = ['ambush', 'frenzy', 'rift']
|
||||
export const POWER_NAMES: Record<PowerKind, string> = {
|
||||
ambush: 'Ambush', frenzy: 'Frenzy', rift: 'Rift',
|
||||
}
|
||||
/** Ambush additionally costs the summoned unit's own price. */
|
||||
export const POWER_COST: Record<PowerKind, number> = { ambush: 45, frenzy: 90, rift: 25 }
|
||||
export const POWER_COOLDOWN: Record<PowerKind, number> = { ambush: 8, frenzy: 45, rift: 12 }
|
||||
|
||||
/** How close to the survivor an ambush lands. Just outside its contact ring. */
|
||||
export const AMBUSH_RADIUS = 130
|
||||
/** ~137.5deg. Irrational share of a turn, so repeated steps never land twice. */
|
||||
export const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5))
|
||||
export const FRENZY_DURATION = 6
|
||||
export const FRENZY_SPEED = 1.35
|
||||
export const FRENZY_DAMAGE = 1.3
|
||||
export const RIFT_DURATION = 10
|
||||
|
||||
/** Arena edge, as a finite union so `Record` indexing stays non-optional. */
|
||||
export type EdgeId = 0 | 1 | 2 | 3
|
||||
export const EDGE_ORDER: readonly [EdgeId, ...EdgeId[]] = [0, 1, 2, 3]
|
||||
export const EDGE_NAMES: Record<EdgeId, string> = {
|
||||
0: 'North', 1: 'South', 2: 'West', 3: 'East',
|
||||
}
|
||||
export const UNIT_ORDER: readonly [UnitKind, ...UnitKind[]] = ['rusher', 'stalker', 'tank', 'bomber']
|
||||
export const BOSS_ORDER: readonly [BossKind, ...BossKind[]] = ['colossus', 'hivemind']
|
||||
export const BOSS_UNLOCK_AT: Record<BossKind, number> = { colossus: 60, hivemind: 120 }
|
||||
export const BOSS_COOLDOWN: Record<BossKind, number> = { colossus: 25, hivemind: 30 }
|
||||
|
||||
export type UpgradeId = 'damage' | 'fireRate' | 'speed' | 'vitality' | 'regen' | 'multishot'
|
||||
export const UPGRADE_POOL: readonly [UpgradeId, ...UpgradeId[]] = [
|
||||
@ -230,8 +100,6 @@ export interface Survivor {
|
||||
xp: number
|
||||
xpNext: number
|
||||
kills: number
|
||||
/** Seconds remaining per status. A finite-union Record, so indexing stays `number`. */
|
||||
statuses: Record<StatusKind, number>
|
||||
}
|
||||
|
||||
export interface Enemy {
|
||||
@ -252,36 +120,23 @@ export interface Projectile {
|
||||
radius: number
|
||||
damage: number
|
||||
ttl: number
|
||||
/** Carried on the shot itself so a hit needs no lookup of a possibly-dead firer. */
|
||||
debuff: StatusKind
|
||||
debuffDuration: number
|
||||
}
|
||||
|
||||
export interface DirectorState {
|
||||
energy: number
|
||||
waveIndex: number
|
||||
bossCooldowns: Record<BossKind, number>
|
||||
powerCooldowns: Record<PowerKind, number>
|
||||
frenzyTimer: number
|
||||
riftTimer: number
|
||||
riftEdge: EdgeId
|
||||
/** Rotates ambush placement deterministically, without drawing from the RNG. */
|
||||
ambushIndex: number
|
||||
}
|
||||
|
||||
export type DirectorAction =
|
||||
| { type: 'spawn'; kind: UnitKind }
|
||||
| { type: 'wave' }
|
||||
| { type: 'boss'; kind: BossKind }
|
||||
| { type: 'ambush'; kind: UnitKind }
|
||||
| { type: 'frenzy' }
|
||||
| { type: 'rift'; edge: EdgeId }
|
||||
|
||||
export type Status = 'running' | 'directorWon' | 'survivorWon'
|
||||
|
||||
export interface GameState {
|
||||
status: Status
|
||||
difficulty: DifficultyConfig
|
||||
t: number
|
||||
duration: number
|
||||
rng: Rng
|
||||
|
||||
@ -24,14 +24,8 @@ describe('draw', () => {
|
||||
const ctx = makeCtxStub()
|
||||
const s = fresh()
|
||||
s.projectiles.push(
|
||||
{
|
||||
id: 1, from: 'survivor', pos: { x: 10, y: 10 }, vel: { x: 0, y: 0 },
|
||||
radius: 4, damage: 1, ttl: 1, debuff: 'slow', debuffDuration: 0,
|
||||
},
|
||||
{
|
||||
id: 2, from: 'enemy', pos: { x: 20, y: 20 }, vel: { x: 0, y: 0 },
|
||||
radius: 5, damage: 1, ttl: 1, debuff: 'slow', debuffDuration: 0,
|
||||
},
|
||||
{ id: 1, from: 'survivor', pos: { x: 10, y: 10 }, vel: { x: 0, y: 0 }, radius: 4, damage: 1, ttl: 1 },
|
||||
{ id: 2, from: 'enemy', pos: { x: 20, y: 20 }, vel: { x: 0, y: 0 }, radius: 5, damage: 1, ttl: 1 },
|
||||
)
|
||||
draw(ctx, s)
|
||||
expect(ctx.fill).toHaveBeenCalledTimes(BASE.fill + 2)
|
||||
@ -67,19 +61,3 @@ describe('draw', () => {
|
||||
expect(ctx.arc).toHaveBeenCalledTimes(BASE.arc + 2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('status halo', () => {
|
||||
it('is absent for an unafflicted survivor', () => {
|
||||
const ctx = makeCtxStub()
|
||||
draw(ctx, fresh())
|
||||
expect(ctx.stroke).toHaveBeenCalledTimes(BASE.stroke)
|
||||
})
|
||||
|
||||
it('draws one extra ring when a status is live', () => {
|
||||
const ctx = makeCtxStub()
|
||||
const s = fresh()
|
||||
s.survivor.statuses.slow = 1.5
|
||||
draw(ctx, s)
|
||||
expect(ctx.stroke).toHaveBeenCalledTimes(BASE.stroke + 1)
|
||||
})
|
||||
})
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { FIRE_RANGE, SURVIVOR_RADIUS } from '../core/sim'
|
||||
import type { EnemyKind, GameState } from '../core/types'
|
||||
import { ARENA, ENEMY_SPECS, STATUS_ORDER } from '../core/types'
|
||||
import { ARENA, ENEMY_SPECS } from '../core/types'
|
||||
|
||||
/** Structural subset of CanvasRenderingContext2D — stubbable in tests. */
|
||||
export interface Ctx2D {
|
||||
@ -30,12 +30,8 @@ const ENEMY_COLORS: Record<EnemyKind, string> = {
|
||||
stalker: '#b06ce8',
|
||||
tank: '#8a4b3c',
|
||||
bomber: '#e0a13d',
|
||||
splitter: '#5fae6b',
|
||||
artillery: '#d4693a',
|
||||
warden: '#e6d15c',
|
||||
colossus: '#7d2c50',
|
||||
hivemind: '#5a3d8a',
|
||||
leech: '#3f7d6e',
|
||||
}
|
||||
|
||||
const IS_BOSS: Record<EnemyKind, boolean> = {
|
||||
@ -43,12 +39,8 @@ const IS_BOSS: Record<EnemyKind, boolean> = {
|
||||
stalker: false,
|
||||
tank: false,
|
||||
bomber: false,
|
||||
splitter: false,
|
||||
artillery: false,
|
||||
warden: false,
|
||||
colossus: true,
|
||||
hivemind: true,
|
||||
leech: true,
|
||||
}
|
||||
|
||||
const circle = (ctx: Ctx2D, x: number, y: number, r: number): void => {
|
||||
@ -112,13 +104,4 @@ export const draw = (ctx: Ctx2D, state: GameState): void => {
|
||||
-Math.PI / 2, -Math.PI / 2 + (Math.max(0, sv.hp) / sv.maxHp) * Math.PI * 2,
|
||||
)
|
||||
ctx.stroke()
|
||||
|
||||
// Afflicted halo. Gated so an unafflicted survivor draws exactly as before.
|
||||
const afflicted = STATUS_ORDER.some((kind) => sv.statuses[kind] > 0)
|
||||
if (afflicted) {
|
||||
ctx.strokeStyle = COLORS.arcane
|
||||
ctx.lineWidth = 2
|
||||
circle(ctx, sv.pos.x, sv.pos.y, SURVIVOR_RADIUS + 10)
|
||||
ctx.stroke()
|
||||
}
|
||||
}
|
||||
|
||||
@ -143,29 +143,6 @@ body {
|
||||
|
||||
.feed li::before { content: "▲ "; color: var(--bone-dim); }
|
||||
|
||||
.status-chips {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin: 8px 0 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.chip {
|
||||
font-family: var(--font-data);
|
||||
font-size: 0.68rem;
|
||||
letter-spacing: 0.04em;
|
||||
padding: 2px 7px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid currentcolor;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.chip-slow { color: var(--arcane); }
|
||||
.chip-suppress { color: var(--blood); }
|
||||
.chip-bleed { color: var(--bone-dim); }
|
||||
|
||||
.spawnbar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@ -243,34 +220,3 @@ body {
|
||||
.board { flex-direction: column; }
|
||||
.hud { width: 100%; }
|
||||
}
|
||||
|
||||
.card-power { border-color: var(--arcane); }
|
||||
.card-rift { border-color: var(--bone-dim); }
|
||||
.card-rift-active { border-color: var(--holy); color: var(--holy); }
|
||||
|
||||
.frenzy-banner {
|
||||
margin: 10px 0 0;
|
||||
padding: 5px 9px;
|
||||
border: 1px solid var(--blood);
|
||||
border-radius: 4px;
|
||||
color: var(--blood);
|
||||
font-family: var(--font-data);
|
||||
font-size: 0.72rem;
|
||||
letter-spacing: 0.06em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.difficulty { display: flex; gap: 6px; justify-content: center; margin-top: 6px; }
|
||||
|
||||
.diff {
|
||||
background: none;
|
||||
border: 1px solid var(--panel-edge);
|
||||
border-radius: 4px;
|
||||
color: var(--bone-dim);
|
||||
cursor: pointer;
|
||||
font-family: var(--font-data);
|
||||
font-size: 0.7rem;
|
||||
padding: 3px 10px;
|
||||
}
|
||||
|
||||
.diff-on { border-color: var(--holy); color: var(--holy); }
|
||||
|
||||
@ -41,13 +41,6 @@ export const Hud = ({ snap, onRestart }: Props): ReactElement => {
|
||||
<p className="hud-num">
|
||||
{Math.ceil(snap.survivorHp)} hp · level {snap.survivorLevel} · {snap.kills} of yours slain
|
||||
</p>
|
||||
<ul className="status-chips">
|
||||
{snap.statuses.map((c) => (
|
||||
<li key={`st-${c.kind}`} className={`chip chip-${c.kind}`}>
|
||||
{c.label} {c.seconds}s
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<ul className="feed">
|
||||
{snap.upgrades.map((u) => (
|
||||
<li key={`up-${String(u.n)}`}>{UPGRADE_LABELS[u.id]}</li>
|
||||
@ -55,10 +48,6 @@ export const Hud = ({ snap, onRestart }: Props): ReactElement => {
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{snap.frenzyActive && (
|
||||
<p className="frenzy-banner">The horde is frenzied</p>
|
||||
)}
|
||||
|
||||
{snap.status === 'directorWon' && (
|
||||
<div className="overlay overlay-win">
|
||||
<h2>The intruder falls</h2>
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
import type { ReactElement } from 'react'
|
||||
import type { BossButton, PowerButton } from '../core/snapshot'
|
||||
import type { BossButton } from '../core/snapshot'
|
||||
import type { HudSnapshot } from '../core/snapshot'
|
||||
import type { DirectorAction } from '../core/types'
|
||||
|
||||
@ -18,12 +18,8 @@ const bossCaption = (b: BossButton): string => {
|
||||
return `${String(b.cost)} souls`
|
||||
}
|
||||
|
||||
const powerCaption = (p: PowerButton): string =>
|
||||
p.ready ? `${String(p.cost)} souls` : `recovering ${String(p.cooldown)}s`
|
||||
|
||||
export const SpawnBar = ({ snap, onAction }: Props): ReactElement => {
|
||||
const running = snap.status === 'running'
|
||||
const { ambush, frenzy, rift } = snap.powers
|
||||
return (
|
||||
<nav className="spawnbar" aria-label="Summoning">
|
||||
{snap.units.map((u) => (
|
||||
@ -59,36 +55,6 @@ export const SpawnBar = ({ snap, onAction }: Props): ReactElement => {
|
||||
<span className="card-cost">{bossCaption(b)}</span>
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
className="card card-power"
|
||||
disabled={!running || !ambush.ready || !ambush.affordable}
|
||||
onClick={() => { onAction({ type: 'ambush', kind: snap.ambushKind }) }}
|
||||
>
|
||||
<span className="card-name">Ambush</span>
|
||||
<span className="card-cost">{powerCaption(ambush)}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="card card-power"
|
||||
disabled={!running || !frenzy.ready || !frenzy.affordable}
|
||||
onClick={() => { onAction({ type: 'frenzy' }) }}
|
||||
>
|
||||
<span className="card-name">Frenzy</span>
|
||||
<span className="card-cost">{powerCaption(frenzy)}</span>
|
||||
</button>
|
||||
{snap.edges.map((e) => (
|
||||
<button
|
||||
key={`edge-${String(e.edge)}`}
|
||||
type="button"
|
||||
className={e.active ? 'card card-rift card-rift-active' : 'card card-rift'}
|
||||
disabled={!running || !rift.ready || !rift.affordable}
|
||||
onClick={() => { onAction({ type: 'rift', edge: e.edge }) }}
|
||||
>
|
||||
<span className="card-name">{e.name}</span>
|
||||
<span className="card-cost">{e.active ? `open ${String(snap.riftSeconds)}s` : 'rift'}</span>
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
@ -21,24 +21,6 @@ describe('Hud', () => {
|
||||
expect(screen.getByText('200 / 400')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('lists live status chips and omits idle ones', () => {
|
||||
const snap = snapWith((s) => {
|
||||
s.survivor.statuses.slow = 1.2
|
||||
s.survivor.statuses.bleed = 3
|
||||
})
|
||||
const { container } = render(<Hud snap={snap} onRestart={() => undefined} />)
|
||||
const chips = container.querySelectorAll('.status-chips li')
|
||||
expect(chips).toHaveLength(2)
|
||||
expect(screen.getByText(/mired/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/unknitting/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/stifled/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders no status chips for an unafflicted survivor', () => {
|
||||
const { container } = render(<Hud snap={snapWith()} onRestart={() => undefined} />)
|
||||
expect(container.querySelectorAll('.status-chips li')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('reports the intruder and its recent upgrades', () => {
|
||||
const snap = snapWith((s) => {
|
||||
s.survivor.hp = 50
|
||||
@ -116,74 +98,3 @@ describe('SpawnBar', () => {
|
||||
expect(onAction).toHaveBeenCalledWith({ type: 'boss', kind: 'colossus' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('SpawnBar powers', () => {
|
||||
it('dispatches an ambush when funded and ready', () => {
|
||||
const onAction = vi.fn()
|
||||
render(<SpawnBar snap={snapWith((s) => { s.director.energy = 400 })} onAction={onAction} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /ambush/i }))
|
||||
expect(onAction).toHaveBeenCalledWith({ type: 'ambush', kind: 'rusher' })
|
||||
})
|
||||
|
||||
it('disables ambush while it is cooling and shows the timer', () => {
|
||||
render(
|
||||
<SpawnBar
|
||||
snap={snapWith((s) => {
|
||||
s.director.energy = 400
|
||||
s.director.powerCooldowns.ambush = 4
|
||||
})}
|
||||
onAction={() => undefined}
|
||||
/>,
|
||||
)
|
||||
const btn = screen.getByRole('button', { name: /ambush/i })
|
||||
expect(btn).toBeDisabled()
|
||||
expect(btn).toHaveTextContent('recovering 4s')
|
||||
})
|
||||
|
||||
it('dispatches frenzy when funded and blocks it when broke', () => {
|
||||
const onAction = vi.fn()
|
||||
const { rerender } = render(<SpawnBar snap={snapWith()} onAction={onAction} />)
|
||||
expect(screen.getByRole('button', { name: /frenzy/i })).toBeDisabled()
|
||||
rerender(
|
||||
<SpawnBar snap={snapWith((s) => { s.director.energy = 400 })} onAction={onAction} />,
|
||||
)
|
||||
fireEvent.click(screen.getByRole('button', { name: /frenzy/i }))
|
||||
expect(onAction).toHaveBeenCalledWith({ type: 'frenzy' })
|
||||
})
|
||||
|
||||
it('dispatches a rift on the chosen edge', () => {
|
||||
const onAction = vi.fn()
|
||||
render(<SpawnBar snap={snapWith((s) => { s.director.energy = 400 })} onAction={onAction} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /west/i }))
|
||||
expect(onAction).toHaveBeenCalledWith({ type: 'rift', edge: 2 })
|
||||
})
|
||||
|
||||
it('marks the open rift edge and counts it down', () => {
|
||||
const { container } = render(
|
||||
<SpawnBar
|
||||
snap={snapWith((s) => {
|
||||
s.director.energy = 400
|
||||
s.director.riftTimer = 7
|
||||
s.director.riftEdge = 3
|
||||
})}
|
||||
onAction={() => undefined}
|
||||
/>,
|
||||
)
|
||||
expect(container.querySelectorAll('.card-rift-active')).toHaveLength(1)
|
||||
expect(screen.getByRole('button', { name: /east/i })).toHaveTextContent('open 7s')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Hud frenzy banner', () => {
|
||||
it('appears only while the horde is frenzied', () => {
|
||||
const { rerender } = render(<Hud snap={snapWith()} onRestart={() => undefined} />)
|
||||
expect(screen.queryByText(/frenzied/i)).not.toBeInTheDocument()
|
||||
rerender(
|
||||
<Hud
|
||||
snap={snapWith((s) => { s.director.frenzyTimer = 3 })}
|
||||
onRestart={() => undefined}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText(/frenzied/i)).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
Loading…
Reference in New Issue
Block a user