77 game-dev skills for AI coding agents — Godot, Unity, Unreal, Phaser, PixiJS, three.js, Bevy, pygame, LÖVE, Roblox. Portable SKILL.md Agent Skills (the format Anthropic launched as Claude Skills), with a router that loads the right skill for your engine and task. Runs in Claude Code, Cursor, Kiro, Codex, Copilot, Gemini CLI and more.
Python agent-skillsai-agentsantigravityawesome-listclaude-codeclinecodexcursorgame-devgame-developmentgamedevgemini-cligithub-copilotgodotkirooh-my-piskillsunityunrealwindsurf
feat(genres): author 9 genre skills
AbhishekBarali1a2f8bfcb5867
diff --git a/docs/progress/SESSION-10-genres.md b/docs/progress/SESSION-10-genres.mdnew file mode 100644index 0000000..21896f0--- /dev/null+++ b/docs/progress/SESSION-10-genres.md@@ -0,0 +1,89 @@+# Session 10 — Author: Genres++> Public build-log entry. Value-focused only. No growth/marketing/strategy language.++- **Session:** S10+- **Wave:** 3 (parallel with S06–S09, S11)+- **Date (UTC):** 2026-06-24+- **Depends on:** S05+- **Status:** complete+- **Branch / commits:** `session/S10-genres` (isolated worktree) → genre-authoring commit(s)++## Objective+Author the nine engine-agnostic **genre** skills from the frozen catalog as compositional+playbooks: each defines the core loop, must-have systems, design knobs, failure modes, and how+to compose with engine + discipline skills — without re-teaching primitives.++## What was produced+All under `skills/genres/`, each a `SKILL.md` plus one `references/` depth file:++- **`platformer`** — run/jump feel (coyote time, jump buffering, variable height, asymmetric+ gravity), tiled levels, hazards, camera; `references/feel-tuning.md` (jump math, corner+ correction, one-way/moving platforms, camera follow).+- **`roguelike`** — turn scheduler, procedural dungeons, FOV, permadeath, loot; anchored to the+ Berlin Interpretation; `references/generation-fov-loot.md` (rooms/BSP/cellular, connectivity,+ shadowcasting, weighted depth-scaled tables, run vs. profile state).+- **`rpg`** — stats/leveling, inventory/equipment, quests, dialogue, save, combat;+ `references/stats-combat-quests.md` (derived stats, damage formulas, XP curves, turn-vs-action,+ quest state model).+- **`fps-shooter`** — first-person controller, hitscan/projectile shooting, TTK, recoil/spread,+ enemy AI; `references/shooting-and-feel.md` (falloff, recoil patterns, TTK math, lag comp, AI FSM).+- **`tower-defense`** — pathing, wave spawner, tower targeting, economy, lives;+ `references/balancing.md` (path representations, targeting modes, DPS/economy math, scaling, pacing).+- **`card-game`** — card data, zones, draw/reshuffle, turn phases, effect resolution;+ `references/effect-resolution.md` (effects-as-data interpreter, queue/stack, triggers/keywords,+ Fisher–Yates, deckbuilder vs. constructed, curves).+- **`visual-novel`** — branching script, presentation, choices, save-anywhere, backlog/skip/auto;+ `references/script-and-flow.md` (script data model, route structures, flags, save data, localization).+- **`survival-crafting`** — gather→craft→build loop, needs, tech tree, base building;+ `references/needs-and-crafting.md` (needs thresholds, tech-tree graph, gather/respawn, building, escalation).+- **`puzzle`** — board model, rule resolution (match-3/sokoban/logic), cascades, undo, generation;+ `references/board-and-resolution.md` (match-3 gravity/refill, deadlock+reshuffle, sokoban, undo,+ solvable generation, input locking).++## Key decisions+- **Genres orchestrate, never re-teach.** Each skill defines the loop and systems and links out+ to engine + discipline skills via a "Composition" section using exact catalog names; primitives+ (physics, tilemaps, dialogue runtime, RNG) are deferred, not duplicated.+- **Engine-agnostic, pseudocode patterns.** Code blocks are clearly labelled engine-neutral+ pseudocode (y-axis down to match 2D engines) so they stay correct without claiming any specific+ engine API — consistent with how the catalog frames genres and disciplines.+- **One `references/` file per skill.** Lean playbooks (≤~150 lines) with depth (formulas, tables,+ algorithms) pushed into a single reference file each, per the progressive-disclosure budget.+- **Consistent body shape** across all nine: when-to-use (with sibling pointers) → core loop →+ must-have systems → design knobs (table) → ≥2 patterns → pitfalls/failure modes → composition →+ references. Mirrors the golden skill's structure.++## Verification+- **Validator:** `python scripts/validate-skills.py` → "Validated 10 skill file(s). All checks+ passed." (exit 0) — the 9 genre skills plus the golden skill.+- **Size budget:** every `SKILL.md` is 122–147 lines (< 500); every `references/` file is 89–122+ lines. Bodies are well under the ~5k-token tier-2 budget.+- **Descriptions:** all nine are 184–198 chars (≤200 soft target for claude.ai, ≤1024 hard limit),+ third person, leading with what-it-does then "Use for …" with trigger vocabulary.+- **Cross-skill names:** every hyphenated skill reference in the bodies was checked against the+ frozen 62-name catalog set — all resolve to real skills (engine, discipline, or workflow).+- **Reference links:** all `references/*.md` links resolve (validator-enforced).+- **Skills authored:** 9; all pass the rubric in `docs/SKILL-FORMAT.md`: yes.++## Sources consulted (design references)+- `https://www.roguebasin.com/index.php/Berlin_Interpretation` — canonical roguelike+ "roguelikeness" factors (RogueBasin / IRDC 2008), used to anchor the `roguelike` design.+- Established, widely-documented design patterns were used as *patterns only* and written from+ scratch: platformer game-feel (coyote time / jump buffering / variable jump height),+ tower-defense wave/economy balancing, match-3 cascade resolution, hitscan-vs-projectile and+ time-to-kill, deckbuilder draw/discard/reshuffle, and the survival gather→craft→build loop.+- Implementation primitives are deferred to the discipline/engine skills cited in each+ "Composition" section (e.g. `procedural-gen`, `save-systems`, `dialogue-systems`, `game-ai`).++## Handoff to next sessions+- **S12 (router):** these genres are compositional entry points. Each `SKILL.md` lists its+ composition targets by exact name; the router can layer a genre on top of the detected engine+ set plus the triggered discipline skills. Router signal phrases match the catalog `says:` cues.+- **S13 (QA):** descriptions, sizes, names, and links are pre-checked; an originality pass can+ confirm the prose is written from scratch (no copied text/code).++## If partial — remaining work+- None. All nine catalog genres are authored and pass the validator. `docs/progress/INDEX.md`+ is intentionally left untouched (shared file, edited by the consolidating session to avoid+ parallel-wave conflicts).diff --git a/skills/genres/card-game/SKILL.md b/skills/genres/card-game/SKILL.mdnew file mode 100644index 0000000..81e560a--- /dev/null+++ b/skills/genres/card-game/SKILL.md@@ -0,0 +1,137 @@+---+name: card-game+description: >+ Build a card game: card data, deck/hand/discard zones, draw/shuffle/reshuffle, a turn structure,+ costs, and effect resolution. Use for a deckbuilder, TCG/CCG, or roguelike deckbuilder.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: intermediate+---++# Card Game++A playbook for card games — card data, the deck/hand/discard zones, the turn structure, and+how card effects resolve. This is a **compositional** skill: it models cards as data and wires+them to UI. It does not re-teach data assets or UI nodes; it defines the zone model, the draw+machinery, and the effect-resolution rules that keep a card game correct and bug-free.++## When to use++- Use when building any game where the core objects are **cards** moving between zones+ (deck → hand → play → discard): deckbuilder, TCG/CCG, solitaire, roguelike deckbuilder.+- Use when designing draw/shuffle/reshuffle, turn structure, card costs, or how effects resolve.++**When *not* to use:** board/tile state with matching rules → `puzzle`. RPG with an+incidental card battler → start from `rpg`. For defining cards as assets, use `godot-resources`+/ `unity-scriptableobjects`; for the hand/drag UI, use `godot-ui-control`.++## Core loop++**Draw to your hand → spend resources to play cards → effects resolve and change the board →+end the turn (cleanup/discard) → opponent/next phase → repeat until a win condition.** Depth+comes from the *combinations* a hand allows; the engine's job is to resolve them unambiguously.++## Must-have systems++1. **Card data** — id, name, cost, type, text, and an effect spec (data, not code).+2. **Zones** — deck (draw pile), hand, play/board, discard, exile/removed; cards live in exactly one.+3. **Draw + shuffle + reshuffle** — draw from deck to hand; reshuffle discard into deck when empty.+4. **Turn structure** — phases (untap/draw/main/combat/end) as a state machine.+5. **Resource system** — mana/energy/actions that gate how much you do per turn.+6. **Effect resolution** — apply a card's effects in a defined order; handle targets and triggers.+7. **Win/loss condition** — life total, deck-out, objective.+8. **UI** — hand layout, drag/drop or tap-to-play, zone counts, targeting affordances.++## Design knobs++| Knob | Effect | Notes |+|------|--------|-------|+| Starting hand / draw-per-turn | tempo, consistency | More draw = less variance. |+| Hand size limit | hoarding vs. use | Discard down at end of turn. |+| Deck size (min) | consistency | Smaller = more reliable combos. |+| Resource curve | what's playable when | "Mana curve" paces power. |+| Card rarity / power budget | balance | Stronger cards cost more / are rarer. |+| Determinism vs. randomness | skill vs. swing | Shuffle + random effects add variance. |+| Reshuffle rules | deck-out, fatigue | Reshuffle discard, or punish empty deck. |+| Removal / answers | counterplay | Every threat needs an answer in the pool. |++## Patterns++### 1. Zones + draw with automatic reshuffle++```python+# Pseudocode. A card is in exactly one zone at a time; moving = remove here, add there.+def draw(n):+ for _ in range(n):+ if not deck:+ if not discard: # truly empty: deck-out (lose, or take fatigue)+ on_deck_out(); return+ deck.extend(discard) # reshuffle discard into deck+ discard.clear()+ shuffle(deck, rng) # use a seeded RNG (see save-systems for replays)+ hand.append(deck.pop())+```++### 2. Card as data + effect resolution++```python+# Pseudocode. Effects are a data list interpreted by the engine — not bespoke code per card.+card = {+ "id": "fireball", "cost": 3, "type": "spell",+ "effects": [ {"op": "damage", "amount": 6, "target": "chosen_enemy"} ],+}+def play(card, caster):+ if resources[caster] < card.cost: return False # can't afford+ resources[caster] -= card.cost+ move(card, from_zone=hand, to_zone=play_or_discard(card))+ for fx in card.effects:+ resolve_effect(fx, caster) # one interpreter handles every card+ return True+```++### 3. Turn structure as a phase machine++```python+# Pseudocode. Fixed phases keep timing windows (triggers, priority) unambiguous.+PHASES = ["untap", "draw", "main", "combat", "end"]+def take_turn(player):+ for phase in PHASES:+ enter_phase(player, phase) # fire "on_phase" triggers here+ if phase == "draw": draw(1)+ if phase == "main": await player_plays_cards()+ if phase == "combat": resolve_combat()+ if phase == "end": discard_to_hand_limit(player); clear_temporary_effects()+```++## Pitfalls / failure modes++- **A card existing in two zones at once** → duplication/loss bugs. Enforce "exactly one zone";+ move = remove-then-add, and assert no card appears twice.+- **Forgetting to reshuffle** → draws silently fail or crash on empty deck. Reshuffle discard,+ or define deck-out/fatigue explicitly (Pattern 1).+- **One function per card** → unmaintainable and untestable. Make effects **data** interpreted+ by a small set of operations (Pattern 2).+- **Ambiguous effect order / simultaneous triggers** → nondeterministic outcomes. Resolve in a+ defined order (a queue or stack); document LIFO vs. FIFO (refs).+- **Unseeded shuffle in a game that needs replays/undo** → can't reproduce. Use a seeded RNG.+- **No hand limit / no answers** → degenerate hoarding or unbeatable threats. Add a hand cap and+ ensure removal exists for every threat archetype.+- **Targeting state leaks** → a cancelled play leaves the board mid-targeting. Make play+ atomic: validate cost + targets first, then commit.++## Composition (build it from these skills)++- **Card content:** `godot-resources` / `unity-scriptableobjects` — define each card as a data asset.+- **UI:** `godot-ui-control` for hand layout, drag/drop, zone counts, and targeting prompts.+- **Persistence/replays:** `save-systems` for collection, run state (roguelike deckbuilder), and seeded replays.+- **Opponent AI:** `game-ai` for an AI that evaluates playable cards and picks targets.+- **Animation/feedback:** the engine animation skill for card movement; `audio-design` for cues.+- **Scripting:** `godot-gdscript` / `unity-csharp-scripting` for the effect interpreter.++## References++- For the effect queue/stack, keywords/triggers, targeting, deckbuilder vs. constructed+ archetypes, and shuffle fairness, read `references/effect-resolution.md`.diff --git a/skills/genres/card-game/references/effect-resolution.md b/skills/genres/card-game/references/effect-resolution.mdnew file mode 100644index 0000000..1dc45ad--- /dev/null+++ b/skills/genres/card-game/references/effect-resolution.md@@ -0,0 +1,100 @@+# Card effect resolution and structure (depth)++Detail behind `SKILL.md`. Engine-neutral pseudocode. Models how card effects resolve, how+triggers stack, and how deck construction shapes the game.++## 1. Effects as data + an interpreter++Define a small vocabulary of **operations**; every card is a list of them. Adding a card means+adding data, not code. This keeps cards testable and prevents per-card spaghetti.++```python+# A handful of ops cover most card games. Extend deliberately.+OPS = {+ "damage": lambda fx, ctx: deal_damage(ctx.target(fx), fx["amount"]),+ "heal": lambda fx, ctx: heal(ctx.target(fx), fx["amount"]),+ "draw": lambda fx, ctx: ctx.owner.draw(fx["amount"]),+ "gain_res": lambda fx, ctx: add_resource(ctx.owner, fx["amount"]),+ "summon": lambda fx, ctx: summon(ctx.owner, fx["unit_id"]),+ "buff": lambda fx, ctx: add_modifier(ctx.target(fx), fx["mod"]),+ "destroy": lambda fx, ctx: move_to_discard(ctx.target(fx)),+}+def resolve_effect(fx, ctx):+ OPS[fx["op"]](fx, ctx)+```++## 2. The resolution queue / stack++When effects can trigger other effects (e.g. "when a creature dies, draw a card"), resolve+through an explicit structure so order is deterministic:++- **Queue (FIFO):** effects resolve in the order they were added. Intuitive for simple games.+- **Stack (LIFO):** the most recently added effect resolves first — this is how trading card+ games model "responses" (the last thing said happens first). Choose one and document it.++```python+# Stack model (pseudocode): pushing during resolution lets responses resolve first.+stack = []+def push_effect(fx, ctx): stack.append((fx, ctx))+def resolve_stack():+ while stack:+ fx, ctx = stack.pop() # LIFO: last in resolves first+ resolve_effect(fx, ctx) # may push more (triggers) -> they resolve next+```++Decide simultaneity rules up front: when several triggers fire at once, order them by a fixed+rule (active player first, then by timestamp) so outcomes are reproducible.++## 3. Triggers and keywords++- **Triggers:** "when X happens, do Y" (on-play, on-death, on-draw, start/end of turn). Register+ listeners by event; when the event fires, push the triggered effects onto the queue/stack.+- **Keywords:** named, reusable abilities (e.g. taunt/guard, lifesteal, poison/DoT, shield).+ Implement each once as a modifier or trigger and tag cards with it — never re-implement per card.++```python+# Event bus (pseudocode): triggers subscribe; effects fire when the event is published.+on("creature_died", lambda ev: [push_effect(t, ctx_for(t)) for t in triggers_for("on_death", ev)])+```++## 4. Targeting++- Resolve targets at the moment of resolution (or at play, per your rules) and **validate** them+ — a target may have left the zone or died before the effect resolves; define "fizzle" behavior.+- Make playing a card **atomic**: validate cost + legal targets first, then pay and commit. A+ cancelled or illegal play must leave zones exactly as they were.++## 5. Deckbuilder vs. constructed++| | Constructed (TCG/CCG) | Deckbuilder (in-run) |+|---|---|---|+| Deck built | Before the game, from a collection | During play (draft/buy cards) |+| Variance | Mulligans, draw order | Reshuffle of a growing deck each "shuffle" |+| Power growth | Fixed deck | Deck thins/grows; combos emerge mid-run |+| Persistence | Collection + decklists | Run state (often roguelike: see `roguelike`) |++In a roguelike deckbuilder, the deck *is* the build: adding/removing cards mid-run is the core+progression. Keep run state separate from any meta-collection (see `save-systems`).++## 6. Shuffle fairness and consistency++- Use a correct **Fisher–Yates** shuffle (engine RNG); naive "sort by random" is biased.+- Seed the RNG if you want reproducible runs, replays, or deterministic undo.+- For digital games, players perceive true-random as "streaky". Some games use a *pity* /+ smoothing system (e.g. bound how long before a needed resource appears). Decide intentionally;+ document it so balance math accounts for it.++```python+def shuffle(cards, rng): # Fisher–Yates+ for i in range(len(cards) - 1, 0, -1):+ j = rng.range(0, i + 1) # 0..i inclusive+ cards[i], cards[j] = cards[j], cards[i]+```++## 7. Mana / resource curves++- The **resource curve** (how much you can spend by turn N) paces power. Cheap cards early,+ expensive payoffs later.+- A deck's **cost distribution** (its "curve") determines consistency: too top-heavy and you+ can't act early; too cheap and you run out of gas. Balance card power against cost so a+ higher cost reliably buys more impact, with rarer cards bending the rule.diff --git a/skills/genres/fps-shooter/SKILL.md b/skills/genres/fps-shooter/SKILL.mdnew file mode 100644index 0000000..e37182f--- /dev/null+++ b/skills/genres/fps-shooter/SKILL.md@@ -0,0 +1,122 @@+---+name: fps-shooter+description: >+ Build a first-person shooter: move+mouse-look controller, hitscan or projectile shooting, weapons,+ health, and enemy AI. Use for an FPS, or tuning aim feel, time-to-kill, recoil, or spread.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: advanced+---++# FPS Shooter++A playbook for first-person shooters — the look/move controller, the shooting model, weapon+feel, and combat. This is a **compositional** skill: it wires a 3D controller, input, and AI+into a shooter. It does not re-teach 3D nodes or raycasts; it defines the shooting model and+the feel knobs (TTK, recoil, spread) that decide whether the guns feel good.++## When to use++- Use when building a first-person game whose core verb is **aim and shoot** — arena shooter,+ tactical FPS, PvE shooter, boomer-shooter.+- Use when deciding hitscan vs. projectile, tuning time-to-kill, recoil, spread, or aim feel.++**When *not* to use:** third-person/2D shooting → reuse the shooting model here but build the+camera/controller from the relevant genre. Wave survival with towers → `tower-defense`.+For the camera/character body itself, use `godot-3d-essentials` / `unreal-cpp-gameplay`.++## Core loop++**Scan → acquire a target → aim and fire → confirm the kill (feedback) → reposition / reload+/ advance.** The whole experience rests on the *aim-and-fire* micro-loop feeling crisp:+responsive look, clear hit feedback, and a death that reads instantly.++## Must-have systems++1. **First-person controller** — move (WASD/stick) + mouse/stick look, gravity, jump/crouch.+2. **Camera** — eye-height view, configurable FOV and sensitivity, recoil kick.+3. **Shooting model** — hitscan raycast and/or projectile spawn; one impact path for feedback.+4. **Weapons + ammo** — damage, fire rate, magazine, reload, switching.+5. **Health + damage** — HP, hit/headshot multipliers, death; player and enemy share the model.+6. **Enemy AI** — perceive → alert → attack → search; cover and reaction delays (`game-ai`).+7. **Feedback** — hitmarkers, impact decals/particles, hit sounds, screen shake, kill confirms.+8. **Objectives** — what you do besides shoot: clear, capture, survive, escort.++## Design knobs++| Knob | Effect | Sane default |+|------|--------|--------------|+| Time-to-kill (TTK) | lethality, forgiveness | Tune dmg × fire-rate × HP together (refs). |+| Hitscan vs projectile | aim skill type | Hitscan = flick; projectile = lead/dodge. |+| Damage falloff | range limiting | Full to ~20 m, floor by ~60 m. |+| Headshot multiplier | skill reward | ~1.5–2.0×. |+| Recoil pattern | learnable kick | Fixed pattern > pure random. |+| Spread (bloom) | suppress laser-accuracy | First shot accurate; grows while firing. |+| Fire rate / magazine / reload | rhythm, downtime | Reload = vulnerability window. |+| Mouse sensitivity / FOV | comfort, readability | Always expose both as options. |+| Aim assist (pad) | controller parity | Magnetism/slowdown near targets. |++## Patterns++### 1. Hitscan shot (instant ray, the workhorse)++```python+# Pseudocode. Cast from the camera; first hit takes damage scaled by range + headshot.+direction = apply_spread(camera.forward, current_spread)+hit = raycast(camera.world_position, direction, max_dist=RANGE, mask=SHOOTABLE)+if hit:+ dmg = base_damage * falloff(hit.distance)+ if hit.is_head: dmg *= HEADSHOT_MULT+ hit.actor.take_damage(dmg)+ spawn_impact_fx(hit.point, hit.normal) # decal + sound + hitmarker+```++### 2. Projectile shot (dodgeable, leads the target)++```python+# Pseudocode. Spawn a moving body; it deals damage on its own collision.+p = spawn(projectile_scene, at=muzzle.world_position)+p.velocity = camera.forward * PROJECTILE_SPEED+p.on_hit = lambda other, point: (other.take_damage(base_damage), explode_fx(point))+p.lifetime = RANGE / PROJECTILE_SPEED # despawn so shots don't live forever+```++### 3. Time-to-kill (balance the trio together)++```python+# Pseudocode. TTK falls out of HP, per-shot damage, and fire rate — tune as one system.+shots_to_kill = ceil(target_hp / damage_per_shot)+ttk_seconds = (shots_to_kill - 1) / fire_rate_per_second # first shot at t=0+```++## Pitfalls / failure modes++- **Look tied to frame rate or unscaled by `dt`** → sensitivity changes with FPS. Look should+ be driven by raw mouse delta; movement integration uses `dt` (see `physics-tuning`).+- **Pure random recoil/spread** → feels uncontrollable and unfair. Use a learnable recoil+ pattern; keep the first shot accurate.+- **Hitscan with no falloff** → pistols snipe across the map. Add range-based damage falloff.+- **No hit feedback** → players can't tell if shots land. Always show hitmarkers, impact FX, and+ a distinct kill confirm.+- **Mismatched TTK** → too low feels twitchy/unfair; too high feels spongy. Tune damage,+ fire rate, and HP as one system (Pattern 3).+- **Trusting the client in multiplayer** → cheating and "I shot first" disputes. Keep authority+ server-side; use lag compensation (refs) and defer netcode to the engine multiplayer skill.+- **No FOV / sensitivity options** → motion sickness and accessibility failures. Always expose them.++## Composition (build it from these skills)++- **Controller + camera:** `godot-3d-essentials` (Godot) or `unreal-cpp-gameplay` / `unreal-blueprints`; Unity uses `unity-physics` + a character controller.+- **Input:** `input-systems` (or `unreal-enhanced-input`) for look/move, rebinding, and gamepad aim assist.+- **Shooting physics:** `godot-physics` / `unity-physics` for raycasts and projectile collision.+- **Enemies:** `game-ai` with `unity-navmesh` / `unreal-behavior-trees` / Godot navigation.+- **Polish:** `audio-design` for weapon/impact sound; `shader-programming` for muzzle/impact VFX.+- **Process:** `prototype-fast` to validate aim feel before building content.++## References++- For hitscan vs. projectile trade-offs, damage falloff, recoil/spread, TTK math, hit+ registration/lag compensation, and enemy AI states, read `references/shooting-and-feel.md`.diff --git a/skills/genres/fps-shooter/references/shooting-and-feel.md b/skills/genres/fps-shooter/references/shooting-and-feel.mdnew file mode 100644index 0000000..6e8dae9--- /dev/null+++ b/skills/genres/fps-shooter/references/shooting-and-feel.md@@ -0,0 +1,102 @@+# FPS shooting model and feel (depth)++Detail behind `SKILL.md`. Engine-neutral pseudocode. For the camera/character body and the+raycast/physics APIs, defer to your engine 3D + physics skill; this file is the shooter glue.++## 1. Hitscan vs. projectile++| | Hitscan | Projectile |+|---|---|---|+| Travel | Instant ray to target | Object flies over time |+| Player skill | Pure aim/flick | Leading, prediction, arcs |+| Feel | Crisp, precise (rifles, pistols) | Dodgeable, readable (rockets, plasma) |+| Cost | One raycast per shot | Spawn + per-frame move + collision |+| Range design | Add damage falloff to limit reach | Speed/lifetime limit reach naturally |+| Counterplay | Cover, peeking | Dodging, sidestepping |++Many shooters mix both: hitscan for hip-fire/automatics, projectiles for heavies and lobs.+Slow projectiles enable big readable fights; hitscan rewards precision but can feel "unfair"+at long range without falloff.++## 2. Hitscan shot++```python+# Pseudocode. Cast from the camera along its forward vector; the first hit takes damage.+origin = camera.world_position+direction = camera.forward+direction = apply_spread(direction, current_spread) # see §4+hit = raycast(origin, direction, max_dist=RANGE, mask=SHOOTABLE)+if hit:+ dmg = base_damage * falloff(hit.distance) # see §3+ if hit.is_head: dmg *= HEADSHOT_MULT # e.g. 2.0+ hit.actor.take_damage(dmg)+ spawn_impact_fx(hit.point, hit.normal) # decal + particles = feedback+```++## 3. Damage falloff (range limiting for hitscan)++```python+# Full damage up to a near distance, then lerp down to a floor by a far distance.+def falloff(d, near=20.0, far=60.0, min_mult=0.4):+ if d <= near: return 1.0+ if d >= far: return min_mult+ t = (d - near) / (far - near)+ return lerp(1.0, min_mult, t)+```++## 4. Spread and recoil++- **Spread** is randomized inaccuracy (a cone). It grows while firing/moving and shrinks while+ still/aiming. Good for automatics; keep the first shot accurate so single taps feel precise.+- **Recoil** is a (often patterned) camera kick. A *fixed* pattern is learnable and skill-based;+ pure random recoil feels bad. Recover toward the original aim over time.++```python+# Spread: random offset within a cone whose half-angle = current_spread.+def apply_spread(dir, spread_rad):+ yaw = rng.range(-spread_rad, spread_rad)+ pitch = rng.range(-spread_rad, spread_rad)+ return rotate(dir, yaw, pitch)++# On each shot: grow spread and kick the camera; recover every frame.+def on_fire():+ camera.pitch -= recoil_pattern[shot_index % len(recoil_pattern)] # learnable kick+ current_spread = min(current_spread + SPREAD_PER_SHOT, MAX_SPREAD)+def tick(dt):+ current_spread = max(BASE_SPREAD, current_spread - SPREAD_RECOVER * dt)+ camera.pitch = move_toward(camera.pitch, aim_pitch, RECOIL_RECOVER * dt)+```++## 5. Time-to-kill (TTK) — the master balance lever++```+shots_to_kill = ceil(target_hp / damage_per_shot)+TTK_seconds = (shots_to_kill - 1) / fire_rate_per_second # first shot at t=0+```++- **Low TTK** (fast kills): positioning/first-shot advantage dominate; twitchy, less forgiving.+- **High TTK**: tracking/sustained aim and team play matter; more time to react and reposition.+- Tune `damage_per_shot`, `fire_rate`, and `target_hp` together — they are one system. Headshot+ multipliers create a skill-based *faster* TTK without lowering the body TTK.++## 6. Hit registration and (multiplayer) lag++- **Single-player:** raycast on the same frame as input; no networking concerns.+- **Multiplayer:** the shooter and the target see slightly different worlds. Common server-side+ approach is **lag compensation** — the server rewinds other actors to where the shooter saw+ them (using the shooter's timestamp/ping) before testing the hit. This is hard; for networking+ plumbing defer to the engine multiplayer skill and keep authority on the server.++## 7. Enemy AI states (single-player)++A small state machine covers most PvE shooters:++```+IDLE/PATROL --(sees player)--> ALERT --(in range)--> ATTACK+ATTACK --(lost line of sight)--> SEARCH(last known pos) --(timeout)--> PATROL+any --(took damage from unseen)--> ALERT (turn toward source)+```++Use cover queries, burst-fire with reload pauses, and a reaction delay so enemies feel fair.+Implement the tree/FSM with `game-ai` and the engine's navigation (`unity-navmesh`,+`unreal-behavior-trees`, Godot navigation).diff --git a/skills/genres/platformer/SKILL.md b/skills/genres/platformer/SKILL.mdnew file mode 100644index 0000000..a366148--- /dev/null+++ b/skills/genres/platformer/SKILL.md@@ -0,0 +1,142 @@+---+name: platformer+description: >+ Build a 2D platformer: run/jump control with coyote time, jump buffering, and variable jump+ height, plus tiled levels and hazards. Use for a platformer or Mario/Celeste-like, or tuning jump feel.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: intermediate+---++# Platformer++A playbook for 2D platformers — the run/jump controller "feel", level structure, hazards,+and goals. This is a **compositional** skill: it wires an engine movement skill, a tilemap+skill, and design skills into a working game. It does **not** re-teach physics or tilemaps;+it tells you what to build and how to make jumping feel good.++## When to use++- Use when building a side-scrolling or single-screen platformer, a "Mario-like" /+ "Celeste-like", or any game whose core verb is **jump between surfaces**.+- Use when a jump feels floaty, unresponsive, or "unfair" and you need feel fixes+ (coyote time, jump buffering, variable height, corner correction).++**When *not* to use:** top-down movement with no gravity → use the engine movement skill+directly. 3D first-person traversal → `fps-shooter`. Grid/turn movement → `roguelike`.+For the raw kinematic body API, use `godot-2d-movement` (or your engine's controller skill).++## Core loop++**Observe a gap/hazard → commit to a jump or move → land safely (or die) → reach the next+checkpoint/goal.** A platformer lives or dies on the *moment-to-moment* feel of that single+jump, repeated thousands of times. Tighten the controller first; everything else is content.++## Must-have systems++1. **Run/jump controller** — horizontal accel/decel, gravity, jump, with the feel aids below.+2. **Solid + one-way collision** — ground, walls, and "jump-through" platforms.+3. **Level geometry** — a tilemap or hand-placed colliders; the playable space.+4. **Hazards + death/respawn** — spikes, pits, enemies; reset to the last checkpoint.+5. **Checkpoints / level goal** — progress markers and a win condition (flag, door, exit).+6. **Camera** — follows the player with a deadzone and look-ahead, clamped to level bounds.+7. **Juice** — landing dust, squash/stretch, hit-stop, sound. Cheap, huge feel payoff.++## Design knobs (make the jump feel right)++Tune these by **outcome** (height in tiles, time to apex in seconds), not by raw numbers.++| Knob | Effect | Sane starting point |+|------|--------|---------------------|+| Max jump height | reach | 3–4 tiles |+| Time to apex | "weight"/snappiness | 0.30–0.40 s |+| Fall gravity multiplier | snappy, non-floaty fall | 1.5–2.0× rise gravity |+| Coyote time | jump just after leaving a ledge | 0.08–0.12 s (~5–7 frames @60) |+| Jump buffer | press just before landing still jumps | 0.10–0.15 s |+| Variable jump cut | tap = short hop, hold = full | cut upward velocity ×0.4–0.5 on release |+| Apex hang | brief float at the top for air control | reduce gravity ×0.5 near `|vy|`<threshold |+| Ground accel / friction | responsiveness vs. ice | reach top speed in 0.05–0.1 s |+| Corner correction | nudge past a ledge clipped by 1–2 px | nudge up to ~4 px sideways |++Derive gravity and jump velocity from the *feel* values rather than guessing — see Pattern 1.++## Patterns++### 1. Solve jump physics from height + time (not magic numbers)++```python+# Pseudocode. Pick the FEEL you want, then derive the physics. y-axis points DOWN.+# From kinematics: h = (g * t^2) / 2 and v0 = g * t.+JUMP_HEIGHT = 3.5 * TILE # how high, in world units+TIME_TO_APEX = 0.35 # seconds to reach the top++gravity = (2 * JUMP_HEIGHT) / (TIME_TO_APEX ** 2) # rising gravity+jump_velocity = -(2 * JUMP_HEIGHT) / TIME_TO_APEX # negative = upward+fall_gravity = gravity * 1.8 # heavier on the way down → less floaty+```++### 2. Coyote time + jump buffer + variable height (the feel core)++```python+# Pseudocode in the per-frame update. dt = seconds since last frame.+# Timers count DOWN; refresh coyote while grounded, buffer on a fresh press.+if on_floor:+ coyote_timer = COYOTE_TIME # 0.1+if jump_pressed_this_frame:+ buffer_timer = JUMP_BUFFER # 0.12+coyote_timer -= dt+buffer_timer -= dt++# A jump is allowed if we pressed recently AND were grounded recently.+if buffer_timer > 0 and coyote_timer > 0:+ velocity.y = jump_velocity+ buffer_timer = 0+ coyote_timer = 0 # consume both so we can't double-jump++# Variable height: releasing jump early while still rising cuts the arc short.+if jump_released_this_frame and velocity.y < 0:+ velocity.y *= 0.45++# Asymmetric gravity: snappier fall than rise.+g = fall_gravity if velocity.y > 0 else gravity+velocity.y += g * dt+```++### 3. One-way platforms++Solid from above, pass-through from below. Most engines expose a "one-way collision" flag on+the tile/collider; enable it and let the player **drop through** by disabling that collision+for a few frames when the player holds Down + Jump. Do not re-implement collision math.++## Pitfalls / failure modes++- **Per-frame movement not scaled by `dt`** → speed changes with frame rate. Every velocity+ integration and timer must use `dt`. (See `physics-tuning`.)+- **Floaty jumps** → symmetric gravity. Make fall gravity heavier than rise gravity.+- **"The jump didn't register"** → no input buffering. Buffer presses for ~0.1 s before landing.+- **"I fell off and couldn't jump"** → no coyote time. Allow a jump for ~0.1 s after leaving ground.+- **Sticking to walls / catching on tile seams** → use a single capsule/box collider, not+ per-tile colliders, and add corner correction.+- **Tunneling through floors at high speed** → enable continuous collision / smaller fixed+ timestep for fast bodies (see `physics-tuning`).+- **Camera snaps and induces nausea** → smooth/lerp the follow, add a deadzone, clamp to bounds.+- **Difficulty wall from bad teaching** → introduce one mechanic per area before combining them.++## Composition (build it from these skills)++- **Controller body:** `godot-2d-movement` (Godot `CharacterBody2D`); for other engines use+ the engine core + physics skill (`unity-physics`, `phaser-arcade-physics`, `pygame-core`).+- **Levels:** `godot-tilemap` / `unity-tilemap-2d` for geometry; `level-design` for layout,+ pacing, and teaching order.+- **Feel/physics:** `physics-tuning` for timestep, CCD, and stability.+- **Input:** `input-systems` for buffering, rebinding, and gamepad support.+- **Polish:** `audio-design` for SFX/music; the engine animation skill for squash/stretch.+- **Process:** `prototype-fast` to greybox the controller before building content.++## References++- For jump math derivation, a full feel-tuning table, corner correction, moving/one-way+ platforms, and camera follow, read `references/feel-tuning.md`.diff --git a/skills/genres/platformer/references/feel-tuning.md b/skills/genres/platformer/references/feel-tuning.mdnew file mode 100644index 0000000..9843b1e--- /dev/null+++ b/skills/genres/platformer/references/feel-tuning.md@@ -0,0 +1,105 @@+# Platformer feel tuning (depth)++Deeper detail behind the controller in `SKILL.md`. All snippets are engine-neutral+pseudocode; the math is standard kinematics and ports to any engine. Tune by *outcome*+(tiles of height, seconds to apex), then read off the physics values.++## 1. Deriving jump physics++A jump is just projectile motion. Choose the two values a designer can actually feel —+**peak height** `h` and **time to reach the peak** `t` — and solve for the rest. With the+y-axis pointing down (most 2D engines):++```+gravity g = 2h / t²+jump_velocity v0 = -2h / t # negative = upward+peak reached after t seconds; total airtime ≈ 2t (symmetric gravity)+```++Asymmetric gravity makes the fall snappier than the rise without changing peak height:++```+rise_gravity = g+fall_gravity = g * fall_multiplier # 1.5–2.0 feels good+# airtime shortens; the arc looks like a fast, weighty drop after a quick pop up.+```++If you instead know the jump velocity and want the height: `h = v0² / (2g)`.++## 2. Full feel knob reference++| Knob | What it changes | Typical range | Notes |+|------|-----------------|---------------|-------|+| Jump height | vertical reach | 2–5 tiles | Keep below the player's *commit* comfort. |+| Time to apex | weight/snappiness | 0.25–0.45 s | Lower = snappier, "tighter". |+| Fall multiplier | floatiness on descent | 1.3–2.2× | The single biggest "feel" lever. |+| Coyote time | post-ledge grace | 0.05–0.15 s | ~3–9 frames at 60 Hz. |+| Jump buffer | pre-land grace | 0.08–0.18 s | Forgive early presses. |+| Variable-jump cut | tap vs hold height | ×0.3–0.6 of vy | Cut only while rising. |+| Apex hang | air control at top | ×0.4–0.6 g near apex | Define apex as `|vy| < hang_threshold`. |+| Max fall speed | terminal velocity | clamp | Prevents tunneling and runaway speed. |+| Ground accel | time to top speed | 0.03–0.12 s | Instant = arcadey; longer = momentum. |+| Air control | steering mid-jump | 0.5–1.0× ground | <1 gives committed arcs. |+| Coyote-after-jump lockout | prevents double jumps | consume timers | Zero both timers on jump. |++## 3. Apex hang and fast-fall++```python+# Reduced gravity near the apex gives a moment of extra air control ("hang time").+if abs(velocity.y) < APEX_THRESHOLD and not on_floor:+ g = g * 0.5++# Optional fast-fall: holding Down past the apex increases downward gravity.+if holding_down and velocity.y > 0:+ g = g * 1.5+```++## 4. Corner correction (ceiling and ledge nudging)++When a rising jump clips a corner by a pixel or two, players read it as the game being+"sticky". Nudge them past it instead of stopping the jump dead:++```python+# On hitting a ceiling while rising, if only the outer 1–4 px are blocked,+# shift the body sideways into the free space and keep the upward velocity.+if blocked_overhead and velocity.y < 0:+ for offset in (1, 2, 3, 4): # check small horizontal nudges+ if free_at(position + sideways * offset):+ position += sideways * offset+ break # keep rising; don't zero velocity.y+```++The same idea on landing edges (a few px of "ledge grab"/snap) makes platforms feel generous.++## 5. One-way platforms and drop-through++- Mark the platform's collision as one-directional (solid only when the player is above and+ moving down). Engines expose this directly — do not hand-roll it.+- **Drop-through:** when the player holds Down + Jump on a one-way platform, disable that+ collision for ~0.1–0.2 s (or until the player's top passes below the platform), then re-enable.++## 6. Moving platforms++- Carry the player: add the platform's per-frame delta to the player's position while standing+ on it, so they ride it instead of sliding off.+- Apply the platform's velocity to the player on jump-off so leaps from a moving platform feel+ physical. Cap the inherited horizontal velocity so it can't fling the player uncontrollably.++## 7. Camera follow++- **Deadzone:** a rectangle the player can move within before the camera reacts; stops jitter.+- **Look-ahead:** offset the camera target in the direction of motion / facing so the player+ sees what's coming. Lerp the offset; don't snap it.+- **Smoothing:** move the camera toward its target with an exponential `lerp(cam, target,+ 1 - exp(-k*dt))` rather than a fixed fraction, so it is frame-rate independent.+- **Clamp:** keep the camera rect inside the level bounds so you never show out-of-level space.+- **Vertical care:** lock or slow vertical follow during normal jumps; only follow Y on large+ height changes (falling into a pit, climbing) to avoid bobbing on every hop.++## 8. Teaching and pacing (hand-off to `level-design`)++- Introduce one mechanic in isolation, let the player practice it safely, *then* combine it+ with a known one. Never introduce two new things in the same hazard.+- Place the first instance of any lethal hazard where failure is cheap (near a checkpoint,+ no long re-traversal).+- Keep checkpoint-to-checkpoint segments short early, longer later; respawn must be instant.diff --git a/skills/genres/puzzle/SKILL.md b/skills/genres/puzzle/SKILL.mdnew file mode 100644index 0000000..bb8f6b9--- /dev/null+++ b/skills/genres/puzzle/SKILL.md@@ -0,0 +1,147 @@+---+name: puzzle+description: >+ Build a puzzle game: grid/board state, move input, rule-based resolution (match-3 cascades, sokoban+ pushes, tile logic), scoring, and undo. Use for a match-3, sokoban, or grid-logic puzzle.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: intermediate+---++# Puzzle++A playbook for grid/board puzzle games — the board model, move input, rule resolution+(matching, pushing, logic), scoring, undo, and level progression. This is a **compositional**+skill: it models board state and rules and presents them through a tilemap/UI. It does not+re-teach tilemaps; it defines the resolution loop and the correctness rules (clean state,+deterministic resolution, undo) that keep a puzzle fair and bug-free.++## When to use++- Use when the game is a **discrete board** the player changes with moves, and the board+ **resolves by rules**: match-3/tile-matching, sokoban/block-pusher, sliding puzzle, logic grid.+- Use when designing match/cascade resolution, undo, level progression, or solvability.++**When *not* to use:** real-time grid action with permadeath → `roguelike`. Card zones/turns →+`card-game`. Physics-based "puzzle platformer" → `platformer` + `physics-tuning`. For the tile+rendering, use `godot-tilemap` / `unity-tilemap-2d`.++## Core loop++**Read the board → plan a move → make the move → the board resolves by its rules (match, push,+fall, fill, cascade) → see progress toward the objective → repeat until solved/failed.** The+fun is the *planning*; the engine's job is to resolve each move **deterministically** and+present it clearly.++## Must-have systems++1. **Board model** — a grid of cells holding pieces; the single source of truth (logic, not visuals).+2. **Move input** — swap, push, drag, rotate, or place; validate legality before applying.+3. **Rule resolution** — detect and apply the genre's rule (matches, pushes, logic) until stable.+4. **Cascades/chains** — when resolution changes the board, re-resolve until no more changes.+5. **Objectives + scoring** — win/lose conditions (score, clear all, reach goal); move/time limits.+6. **Undo** — revert the last move (and its resolution) exactly; essential for thinky puzzles.+7. **Level progression + (often) generation** — hand-authored or generated **solvable** boards.+8. **Feedback ("juice")** — clear, satisfying animation/sound for matches, falls, and chains.++## Design knobs++| Knob | Effect | Notes |+|------|--------|-------|+| Grid size / shape | complexity | Square is standard; hex/irregular change feel. |+| Match/push rule | genre identity | 3-in-a-row, shapes, push-into-goal, etc. |+| Cascade scoring | reward depth | Bigger chains = exponential payoff. |+| Move / time limit | pressure | Move-limited = puzzly; time = arcade. |+| Difficulty curve | learning | Introduce one mechanic at a time. |+| Undo depth | forgiveness | Single-step vs. full history. |+| Solvability guarantee | fairness | Generated boards must be solvable. |+| Deadlock handling | no dead ends | Detect no-moves; shuffle or end (refs). |++## Patterns++### 1. Board model + match detection (logic separate from visuals)++```python+# Pseudocode. The board is the truth; rendering reads from it. (0,0) top-left, y grows down.+board = [[piece_or_empty for _ in range(W)] for _ in range(H)]++def find_matches(board):+ matched = set()+ for y in range(H): # horizontal runs of >= 3 equal pieces+ run = 1+ for x in range(1, W):+ if board[y][x] and board[y][x] == board[y][x-1]: run += 1+ else:+ if run >= 3: matched |= {(y, k) for k in range(x-run, x)}+ run = 1+ if run >= 3: matched |= {(y, k) for k in range(W-run, W)}+ # ... repeat the same scan vertically (columns) ...+ return matched+```++### 2. Resolve → collapse → refill → cascade (repeat to stability)++```python+# Pseudocode. One player move can trigger a chain; loop until the board stops changing.+def resolve(board):+ chain = 0+ while True:+ matches = find_matches(board)+ if not matches: break # stable: resolution complete+ chain += 1+ score += score_for(matches, chain) # later chain steps score more (see refs)+ clear(board, matches) # remove matched pieces+ apply_gravity(board) # pieces fall into the gaps+ refill(board, rng) # spawn new pieces at the top (seeded RNG)+ return chain+```++### 3. Undo via state snapshot or command++```python+# Pseudocode. Snapshot before each move; undo restores it exactly (board + score + counters).+def make_move(move):+ history.append(snapshot(board, score, moves_left)) # push BEFORE applying+ apply(move); resolve(board); moves_left -= 1++def undo():+ if history:+ board, score, moves_left = history.pop() # exact revert, including resolution+```++For large boards prefer the **command** pattern (store the move + enough to invert it) over full+snapshots to save memory; snapshots are simplest and fine for small boards.++## Pitfalls / failure modes++- **Mixing logic and visuals** → animations desync from state and cause bugs. The board model is+ the single source of truth; the view only renders it.+- **Resolving only once** → cascades/chains are missed. Loop resolution until the board is stable+ (Pattern 2).+- **Undo that doesn't restore everything** → score/move-count/random-state drift. Snapshot *all*+ state, or make the move fully invertible.+- **Unseeded refill RNG** → can't reproduce a level / no deterministic undo or daily puzzle. Seed it.+- **Generated boards that aren't solvable** → unfair dead ends. Generate-and-verify, or generate+ from a known solution backward (refs).+- **No deadlock detection** (match-3) → board with no valid moves softlocks. Detect "no moves"+ and shuffle or end the level (refs).+- **Difficulty spikes** → too many mechanics at once. Teach one mechanic per level before combining.+- **Resolution mid-animation accepts input** → double-moves/corruption. Lock input until the+ board is stable.++## Composition (build it from these skills)++- **Board rendering:** `godot-tilemap` / `unity-tilemap-2d` for the grid; `godot-ui-control` for HUD, score, and menus.+- **Levels:** `level-design` for hand-authored puzzles and difficulty pacing; `procedural-gen` for solvable generated boards.+- **Persistence:** `save-systems` for level progress, high scores, and seeded daily puzzles.+- **Juice:** the engine animation/`Tween` skill for swaps/falls/clears; `audio-design` for match and chain cues.+- **Scripting:** `godot-gdscript` / `unity-csharp-scripting` for the resolution loop and rules.++## References++- For match-3 detection/gravity/refill/cascade detail, deadlock detection and reshuffles,+ sokoban/rule-based puzzles, undo strategies, solvable generation, and scoring, read+ `references/board-and-resolution.md`.diff --git a/skills/genres/puzzle/references/board-and-resolution.md b/skills/genres/puzzle/references/board-and-resolution.mdnew file mode 100644index 0000000..8d0d9a8--- /dev/null+++ b/skills/genres/puzzle/references/board-and-resolution.md@@ -0,0 +1,122 @@+# Puzzle board models and resolution (depth)++Detail behind `SKILL.md`. Engine-neutral pseudocode. Board coordinates are `(y, x)` with+`(0,0)` top-left and `y` growing downward (matches most tilemaps).++## 1. Match-3 full resolution++The resolution loop is: detect matches → score → clear → gravity → refill → repeat until stable.++```python+def apply_gravity(board):+ for x in range(W):+ # Compact non-empty cells downward within each column.+ column = [board[y][x] for y in range(H) if board[y][x] is not EMPTY]+ pad = [EMPTY] * (H - len(column))+ for y in range(H):+ board[y][x] = (pad + column)[y] # empties on top, pieces settle to the bottom++def refill(board, rng):+ for y in range(H):+ for x in range(W):+ if board[y][x] is EMPTY:+ board[y][x] = random_piece(rng) # seeded RNG for reproducibility+```++**Avoid spawning matches on refill** if you don't want free cascades: when filling, reject a+color that would immediately complete a line, or resolve those cascades intentionally as part+of scoring.++**Initial board:** generate so there are **no pre-existing matches** but **at least one valid+move** (see deadlocks). A common method: fill randomly, clear any starting matches, then verify+a move exists.++## 2. Deadlock detection and reshuffle (match-3)++A board with no possible matching move is a soft-lock. Detect it and react:++```python+def has_valid_move(board):+ # Try every adjacent swap; if any creates a match, a move exists.+ for y in range(H):+ for x in range(W):+ for dy, dx in ((0, 1), (1, 0)):+ if in_bounds(y+dy, x+dx):+ swap(board, (y, x), (y+dy, x+dx))+ ok = bool(find_matches(board))+ swap(board, (y, x), (y+dy, x+dx)) # swap back+ if ok: return True+ return False+# If not has_valid_move(board): reshuffle existing pieces (keep counts) until a move exists,+# or end the level, depending on your rules.+```++## 3. Cascade scoring++Reward chains so deep setups feel great:++```python+def score_for(matches, chain):+ base = len(matches) * 10+ return base * chain # linear in chain; or base * 2**(chain-1) for exponential+# Bonus for larger single matches (4 = line-clear piece, 5 = color bomb, etc.) is a common+# layer on top — special pieces created by 4+/5+ matches add strategy.+```++## 4. Sokoban / push puzzles++A different rule family: the player pushes blocks; the goal is to place blocks on targets.+Resolution is a legality check, not a cascade.++```python+def try_push(board, player, dir):+ ahead = player + dir+ beyond = player + dir * 2+ if is_wall(board, ahead): return False+ if is_block(board, ahead):+ if is_wall(board, beyond) or is_block(board, beyond):+ return False # can't push two blocks or into a wall+ move_block(board, ahead, beyond)+ move_player(board, player, ahead)+ return True+# Win when every target cell holds a block. Undo is essential — sokoban is unforgiving.+# Detect dead states (a block pushed into a corner that isn't a target) to hint a restart.+```++## 5. Rule-based / logic puzzles++For logic grids (nonograms, sliding tiles, circuit/flow puzzles), the "resolution" is usually+just **validity + win check** after each move — no cascade. Keep the rule check pure and total:+given a board, return solved / unsolved / invalid. Undo and a clear "current constraints"+display matter more than animation here.++## 6. Undo strategies++| Strategy | Stores | Pros | Cons |+|----------|--------|------|------|+| Snapshot | full board + counters per move | trivial, exact | memory on big boards |+| Command | the move + inverse data | compact | must implement invert per rule |+| Redo stack | future snapshots/commands | redo support | extra bookkeeping |++Whatever you choose, undo must restore **everything** that affects play: board, score, moves+left, RNG state, and any special-piece state. Test undo by hashing full state before a move and+after undo — they must match.++## 7. Solvable generation++Generated levels must be solvable, or players hit unfair dead ends:++- **Generate-and-verify:** make a candidate, run a solver (BFS/DFS/A\* over board states for+ push/slide puzzles; move-existence for match-3); keep it only if solvable within the move/time+ budget. Use a seed so a level is reproducible.+- **Reverse generation:** start from a solved board and apply random *legal inverse* moves; the+ scrambled result is guaranteed solvable by reversing them. Great for sliding/sokoban puzzles.+- Tag each level with its seed and intended difficulty so progression curves are tunable and a+ bad level can be reproduced and fixed.++## 8. Input locking and presentation++The board model resolves instantly; animation plays the resolution out over time. **Lock input+until the board is stable** so the player can't act on a mid-cascade board. Drive visuals from+the sequence of state changes resolution produced (a list of clears/falls/spawns), not by+re-reading a half-updated board.diff --git a/skills/genres/roguelike/SKILL.md b/skills/genres/roguelike/SKILL.mdnew file mode 100644index 0000000..0e8b6d1--- /dev/null+++ b/skills/genres/roguelike/SKILL.md@@ -0,0 +1,138 @@+---+name: roguelike+description: >+ Build a roguelike: turn-based grid movement, procedural dungeons, permadeath, field-of-view,+ and loot tables. Use for a roguelike/roguelite or turn-based grid dungeon crawler with procedural levels.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: advanced+---++# Roguelike++A playbook for roguelikes — the turn engine, procedural dungeons, field-of-view, permadeath,+and run economy. This is a **compositional** skill: it orchestrates procedural generation,+tilemaps, save handling, and AI into a run-based game. It does not re-teach noise/RNG or+tilemap APIs; it defines the loop and the systems that make a *run* compelling.++## When to use++- Use when building a **turn-based, grid-based** dungeon crawler where each death ends the+ run and the world is regenerated — a roguelike or "roguelite" (with meta-progression).+- Use when designing procedural dungeons, FOV/fog-of-war, permadeath stakes, or loot tables.++**When *not* to use:** real-time action with roguelike *dressing* → build the action genre+(`platformer`/`fps-shooter`) and layer `procedural-gen`. Deep stats/quests/dialogue without+permadeath → `rpg`. Open-world needs/crafting → `survival-crafting`.++## What makes it a roguelike (design anchor)++The community reference is the **Berlin Interpretation** (RogueBasin, IRDC 2008): a set of+"roguelikeness" factors, not a checklist. The high-value ones are the design targets:+**random environment generation, permadeath, turn-based, grid-based, non-modal** (all actions+in one mode), **complexity** (many item/monster interactions), **resource management**,+**hack-and-slash**, and **exploration & discovery**. Lean into these to feel roguelike; pick+which to keep deliberately. "Roguelite" usually relaxes permadeath with meta-progression.++## Core loop++**Take a turn (move / fight / use) → the world resolves its turn → see new state → descend /+loot / survive → die and restart with a fresh dungeon.** Replayability comes from the *world*+changing each run, not the player memorizing a fixed layout.++## Must-have systems++1. **Turn scheduler** — energy/initiative system so fast actors act more often (Pattern 2).+2. **Grid map + movement** — tile coordinates; bump-to-attack; blocked/walkable queries.+3. **Procedural dungeon generator** — rooms + corridors, or BSP/cellular; guarantee connectivity.+4. **Field of view + explored memory** — what's visible now vs. seen-before (Pattern 3 / refs).+5. **Combat + entities** — HP, attack/defense, status; monsters obey the same rules as the player.+6. **Loot + drop tables** — weighted, depth-scaled item/monster spawning (refs).+7. **Permadeath + (optional) meta-progression** — wipe the run; persist only unlocks/score.+8. **Message log + clear UI** — the player reasons from text/state; surface numbers and events.++## Design knobs++| Knob | Effect | Notes |+|------|--------|-------|+| Dungeon size / room count | run length, density | Scale with depth. |+| Connectivity guarantee | no unreachable rooms | Always verify reachability after generation. |+| Monster density / depth curve | difficulty ramp | Spawn by depth-weighted table. |+| Loot rarity weights | power variance | Rarer = bigger swing; identify adds discovery. |+| FOV radius / lighting | tension, information | Smaller radius = scarier, slower. |+| Resource scarcity (food/HP/ammo) | pressure to descend | Core tension lever in classic RLs. |+| Permadeath vs meta-progression | run stakes vs. retention | Roguelite softens the wall. |+| Identification / unknowns | exploration value | Unidentified items reward experimentation. |+| Seedable RNG | daily runs, debugging | Always allow a fixed seed (see `procedural-gen`). |++## Patterns++### 1. Deterministic, seedable run RNG++```python+# Pseudocode. One seeded RNG per run makes dungeons reproducible (daily runs, bug repro).+run_seed = chosen_seed or random_seed()+rng = Rng(run_seed) # use your engine's seedable RNG, not global random+dungeon = generate_dungeon(rng, depth) # same seed + depth => same dungeon+# Persist run_seed in the save so a crash can resume the same world (see save-systems).+```++### 2. Energy-based turn scheduler (speeds differ)++```python+# Pseudocode. Each actor gains energy each tick and acts when it has enough.+# Faster actors gain more per tick, so they act more often — no fixed "player then enemies".+TURN_COST = 100+def next_actor(actors):+ while True:+ for a in actors: # stable order avoids ties favoring one side+ a.energy += a.speed # e.g. speed 100 = normal, 150 = hasted+ if a.energy >= TURN_COST:+ a.energy -= TURN_COST+ return a # this actor takes exactly one action now+```++### 3. Field of view + explored memory++```python+# Pseudocode. Recompute visibility from the player each time they move.+visible = compute_fov(map, player.pos, radius=8) # symmetric shadowcasting (see refs)+for cell in visible:+ explored.add(cell) # remember it forever (dim "fog of war")+# Render: visible -> lit; explored-but-not-visible -> dim; never-seen -> hidden.+```++Use a proven FOV algorithm (recursive shadowcasting or symmetric shadowcasting). Do not+roll a naive raycast-per-cell — it produces asymmetric, "blinking" vision. See refs.++## Pitfalls / failure modes++- **Disconnected dungeons** → rooms the player can't reach. Always run a connectivity/flood-fill+ pass and carve corridors until every walkable cell is reachable.+- **Naive FOV** → vision that flickers or is asymmetric (you see them, they don't see you).+ Use shadowcasting; test symmetry.+- **Real-time loop pretending to be turn-based** → input races and double-moves. Resolve one+ discrete turn at a time; queue input.+- **Flat difficulty** → no descent pressure. Scale monsters/loot by depth and keep resources scarce.+- **Permadeath that wipes meta-unlocks** → frustration. Separate *run* state (wiped) from+ *profile* state (unlocks, scores) when saving (see `save-systems`).+- **Save-scumming a "permadeath" game** → delete or invalidate the run save on load if you want+ true permadeath; keep only the profile.+- **Unreadable state** → the player can't plan. Show HP, turn results, and a message log.++## Composition (build it from these skills)++- **Generation:** `procedural-gen` (noise, seeded RNG, dungeon/room algorithms) — the engine of replayability.+- **Map rendering:** `godot-tilemap` / `unity-tilemap-2d` for the grid; `level-design` for set-piece rooms/vaults.+- **Enemies:** `game-ai` for monster decision-making (often simple on a grid: seek/flee/patrol).+- **Persistence:** `save-systems` for run-resume, profile/meta-progression, and true permadeath wipes.+- **Scripting/data:** `godot-resources` / `unity-scriptableobjects` to define items, monsters, and drop tables as data.+- **UI:** `godot-ui-control` for the message log, inventory, and HUD.++## References++- For dungeon-generation algorithms (rooms-and-corridors, BSP, cellular automata, connectivity),+ FOV (shadowcasting), and weighted loot/spawn tables, read `references/generation-fov-loot.md`.diff --git a/skills/genres/roguelike/references/generation-fov-loot.md b/skills/genres/roguelike/references/generation-fov-loot.mdnew file mode 100644index 0000000..b7d79c1--- /dev/null+++ b/skills/genres/roguelike/references/generation-fov-loot.md@@ -0,0 +1,120 @@+# Roguelike generation, FOV, and loot (depth)++Algorithms behind the systems in `SKILL.md`. Engine-neutral pseudocode. For the noise/RNG+primitives and seeding, defer to `procedural-gen`; this file is the roguelike-specific glue.++## 1. Dungeon generation approaches++Pick by the *texture* you want. All must end with a **connectivity pass** (§2).++### Rooms-and-corridors (classic, readable)++```python+# Place non-overlapping rooms, then connect their centers with L-shaped tunnels.+rooms = []+for _ in range(MAX_ROOMS):+ r = random_rect(rng, min=4, max=10)+ if any(r.intersects(other.expand(1)) for other in rooms):+ continue # reject overlaps (expand by 1 to keep walls between)+ carve_room(map, r)+ if rooms: # connect to the previous room+ carve_h_then_v(map, rooms[-1].center, r.center, rng)+ rooms.append(r)+# First room = player spawn; last/farthest room = stairs down.+```++### BSP (binary space partition — tidy, building-like)++Recursively split the map rectangle into sub-rectangles; place one room per leaf; connect+sibling rooms as you unwind the recursion. Produces evenly distributed, non-overlapping rooms.++### Cellular automata (organic caves)++```python+# Random fill, then smooth: a cell becomes wall if most neighbors are walls.+fill_random(map, wall_chance=0.45, rng=rng)+for _ in range(4, 6): # 4–6 smoothing passes+ for cell in map:+ walls = count_wall_neighbors(map, cell) # 8-neighborhood+ map[cell] = WALL if walls >= 5 else FLOOR+# Then keep only the largest connected floor region (discard isolated pockets).+```++### Drunkard's walk (cheap, winding)++Start at a point and random-walk, carving floor, until a target floor percentage is reached.+Guaranteed connected (one continuous path) but can be too snaky without tuning.++## 2. Connectivity (never skip this)++```python+# Flood-fill from the player's start; any walkable cell not reached must be connected or removed.+reached = flood_fill(map, player_start)+regions = find_disconnected_floor_regions(map, reached)+for region in regions:+ carve_corridor(map, nearest_cell(reached), nearest_cell(region), rng)+# Re-flood and assert: every floor cell is now reachable.+```++For caves, the common shortcut is to keep only the single largest region and discard the rest.++## 3. Field of view — symmetric shadowcasting++Properties you want: **symmetric** (if A sees B, B sees A), no blind spots, no flicker as the+player moves. Recursive shadowcasting scans the eight octants around the origin, tracking a+"shadow" of slopes blocked by walls:++```+for each of 8 octants:+ scan rows outward from the origin up to radius R+ track the visible slope range [start_slope, end_slope]+ when a wall is hit, recurse into the narrower slope range beyond it,+ and continue the current row with the reduced range+mark a cell visible if it lies within the current slope range and within R+```++Implementation notes:+- Transform each octant into a common coordinate frame so one routine handles all eight.+- Use a circular radius check (`dx*dx + dy*dy <= R*R`) for a round light, not a square.+- Cache `explored` separately; render explored-but-not-visible cells dimmed.++A symmetric variant ("symmetric shadowcasting") is simpler to reason about and avoids+single-cell asymmetries; prefer it if you implement from scratch.++## 4. Weighted, depth-scaled loot and spawn tables++```python+# A drop table is a list of (entry, weight). Weight is relative, not a probability.+goblin_loot = [+ ("nothing", 60),+ ("gold_small", 25),+ ("healing_potion", 10),+ ("rare_scroll", 5),+]+def roll(table, rng):+ total = sum(w for _, w in table)+ pick = rng.range(0, total) # [0, total)+ upto = 0+ for entry, w in table:+ upto += w+ if pick < upto:+ return entry++# Depth scaling: shift weights toward stronger entries as depth increases,+# e.g. add depth-gated entries or multiply rare weights by a depth factor.+```++Design guidance:+- Keep "nothing"/common as the bulk of weight so rares stay exciting.+- Gate powerful items behind a minimum depth so early runs can't snowball.+- Separate **monster** spawn tables from **item** drop tables; both scale with depth.+- For "exactly one of" results use weighted pick; for "each may drop" iterate independent rolls.++## 5. Run vs. profile state (permadeath + meta-progression)++- **Run state** (current dungeon, HP, inventory, seed): lives only during the run. For *true*+ permadeath, delete or invalidate this save the moment it is loaded so it cannot be reloaded.+- **Profile state** (unlocked items/classes, high scores, achievements, currency): persists+ across deaths. This is what a roguelite spends on meta-progression.+- Keep them in separate files/sections so wiping a run never touches the profile (see+ `save-systems` for slot/versioning details).diff --git a/skills/genres/rpg/SKILL.md b/skills/genres/rpg/SKILL.mdnew file mode 100644index 0000000..0deec7a--- /dev/null+++ b/skills/genres/rpg/SKILL.md@@ -0,0 +1,135 @@+---+name: rpg+description: >+ Build an RPG: stats and leveling, inventory and equipment, quests, branching dialogue, save/load,+ and combat. Use for an RPG/JRPG, or designing stat, inventory, quest, or combat systems.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: advanced+---++# RPG++A playbook for role-playing games — stats and progression, inventory/equipment, quests,+dialogue, and combat. This is a **compositional** skill: it ties data-driven content,+dialogue, and saving together. It does not re-teach those primitives; it defines the systems+that make growth and choice feel meaningful, and points to the skills that implement each.++## When to use++- Use when building an RPG/JRPG/action-RPG: the player has **stats that grow**, an+ **inventory**, **quests**, **dialogue**, and persistent progress.+- Use when designing a leveling curve, a damage formula, an inventory/equipment model, or a+ quest state machine.++**When *not* to use:** permadeath dungeon runs with no persistent character → `roguelike`.+Pure conversation/branching story → `visual-novel`. Open-world needs/crafting/base-building →+`survival-crafting`. For the dialogue engine itself, use `dialogue-systems`.++## Core loop++**Explore → encounter (fight / talk / solve) → earn rewards (XP, loot, story) → grow+(level up, gear up, unlock) → take on harder content.** The fantasy is *getting stronger and+shaping who your character is*; every system should feed that growth-and-choice loop.++## Must-have systems++1. **Stats + leveling** — base attributes, derived combat stats, XP curve, level-up gains.+2. **Inventory + equipment** — data-defined items, stacking, slots, stat modifiers.+3. **Combat** — turn-based or action; damage formula, status effects, win/loss.+4. **Quests** — objectives, state machine (available→active→complete→turned-in), rewards.+5. **Dialogue** — branching lines, conditions on game state, choices that matter.+6. **Save/load** — persist character, inventory, quest progress, world flags, with versioning.+7. **Economy + progression gating** — gold/shops; gate power behind level/quest/region.+8. **UI** — HUD, inventory, quest log, dialogue box, character sheet.++## Design knobs++| Knob | Effect | Notes |+|------|--------|-------|+| XP curve shape | pacing of power | Fast early, slow late (see refs). |+| Stat→derived scaling | build diversity | One attribute shouldn't dominate. |+| Damage formula | tactical feel | Subtractive vs. ratio mitigation (refs). |+| Random variance / crit | swinginess | ±10% and ~1.5× crit are safe defaults. |+| Drop rates / economy | reward cadence | Avoid trivializing shops with loot. |+| Power gating | difficulty gating | Level/region/quest locks. |+| Reversible modifiers | buff/gear correctness | Layer mods; never edit base stats. |+| Choice consequence | role-play weight | Quest/dialogue flags should branch outcomes. |++## Patterns++### 1. Derived stats from base attributes (recompute, never store as truth)++```python+# Pseudocode. Base attributes are the only "truth"; combat stats are derived each time.+def derive(base, mods):+ s = apply_modifiers(base, mods) # base + flat adds + percent, then clamp+ return {+ "max_hp": 20 + s["VIT"] * 8,+ "attack": s["STR"] * 2,+ "defense": s["VIT"] + s["AGI"] * 0.5,+ }+# Equipping pushes a modifier; unequipping pops it. HP/attack recompute automatically.+```++### 2. XP curve + level-up++```python+# Pseudocode. Quadratic curve: fast early levels, long late ones.+def xp_to_next(level, base=100): return base * level * level++def gain_xp(actor, amount):+ actor.xp += amount+ while actor.xp >= xp_to_next(actor.level):+ actor.xp -= xp_to_next(actor.level)+ actor.level += 1+ actor.base["STR"] += 2; actor.base["VIT"] += 2 # grant gains / skill points+ on_level_up(actor) # heal, unlock, notify+```++### 3. Quest objective update driven by game events++```python+# Pseudocode. Game events advance matching objectives; completion grants rewards.+def on_event(kind, data):+ for q in active_quests:+ for obj in q.objectives:+ if obj.event == kind and matches(obj, data) and not obj.done:+ obj.count += 1+ if obj.count >= obj.needed: obj.done = True+ if all(o.done for o in q.objectives):+ q.state = "complete" # turn-in grants xp/gold/items+```++## Pitfalls / failure modes++- **Editing base stats for buffs/gear** → values drift and corrupt on save/reload. Keep a+ modifier layer; push/pop it (Pattern 1).+- **Storing derived stats as truth** → desync after a stat change. Recompute from base.+- **Runaway XP/damage numbers** → either an exponential curve with no cap or a subtractive+ formula at huge values. Pick a curve and a formula family deliberately (refs).+- **Content as code** → every item/quest hardcoded. Define items, enemies, and quests as+ **data** (`godot-resources` / `unity-scriptableobjects`).+- **Save format with no version field** → old saves break on update. Add a `version` and a+ migration path from day one (see `save-systems`).+- **Choices without consequences** → dialogue branches that reconverge immediately feel hollow.+ Set flags that actually change later quests/world state.+- **Quest progress not persisted** → reloading loses mid-quest state. Save quest state, not+ just completion.++## Composition (build it from these skills)++- **Dialogue:** `dialogue-systems` (Yarn Spinner / Ink) — branching lines, conditions, variables.+- **Persistence:** `save-systems` — character, inventory, quest flags, world state, versioning.+- **Content data:** `godot-resources` / `unity-scriptableobjects` — items, enemies, quests, skills as assets.+- **Combat AI:** `game-ai` for enemy behavior; for turn order reuse the scheduler idea in `roguelike`.+- **UI:** `godot-ui-control` for inventory, quest log, character sheet, dialogue box.+- **World:** `level-design` plus your engine's tilemap/3D skill (`godot-tilemap`, `godot-3d-essentials`).++## References++- For stat/damage formulas, leveling curves, turn-vs-action combat timelines, inventory/equipment+ data shapes, and the quest state model, read `references/stats-combat-quests.md`.diff --git a/skills/genres/rpg/references/stats-combat-quests.md b/skills/genres/rpg/references/stats-combat-quests.mdnew file mode 100644index 0000000..cc4b849--- /dev/null+++ b/skills/genres/rpg/references/stats-combat-quests.md@@ -0,0 +1,110 @@+# RPG stats, combat, and quests (depth)++Formulas and data shapes behind `SKILL.md`. Engine-neutral pseudocode. Treat every number+as a starting point to tune against playtests, not a law.++## 1. Stat block: base, derived, and modifiers++Separate **base** attributes from **derived** combat stats so a single attribute change+ripples predictably, and keep **modifiers** in their own layer so buffs/equipment are+reversible without corrupting base values.++```python+# Base attributes (what leveling/allocation changes)+base = { "STR": 10, "AGI": 10, "INT": 10, "VIT": 10 }++# Derived stats are pure functions of base (+ modifiers). Recompute; never store as truth.+def derive(base, mods):+ s = sum_layers(base, mods) # base + flat + percent modifiers+ return {+ "max_hp": 20 + s["VIT"] * 8,+ "attack": s["STR"] * 2,+ "defense": s["VIT"] * 1 + s["AGI"] * 0.5,+ "crit": min(0.05 + s["AGI"] * 0.005, 0.50), # cap it+ "speed": s["AGI"],+ }+```++Modifier layers (apply in this order): **base → flat adds → percent multipliers → clamp**.+Equipping an item pushes a modifier; unequipping pops the same one. This avoids the classic+"buff wore off and left me at the wrong HP" bug.++## 2. Damage formulas++Two common families — pick one and stay consistent:++```python+# (a) Subtractive: defense flatly reduces damage. Simple; high defense can trivialize hits.+dmg = max(1, attacker.attack - defender.defense) # floor at 1 so nothing is immune++# (b) Ratio/mitigation: defense gives diminishing % reduction. Scales smoothly to high numbers.+mitigation = defender.defense / (defender.defense + K) # K ~ 100; tune the curve+dmg = attacker.attack * (1 - mitigation)++# Layer on: random variance (±10%), crit multiplier, and type effectiveness.+dmg *= rng.range(0.9, 1.1)+if is_crit: dmg *= 1.5+dmg *= type_multiplier(attacker.element, defender.element) # 0.5 / 1.0 / 2.0+```++Subtractive feels "tactical" at low numbers; ratio scales better for big late-game values.++## 3. Leveling curves++XP-to-next-level shapes the whole pace. Three common curves:++```python+# Linear-ish (gentle): next = base * level+# Quadratic (classic JRPG):next = base * level^2+# Exponential (steep): next = base * growth^level # growth ~1.2–1.5++def xp_to_next(level, base=100, kind="quadratic", growth=1.3):+ if kind == "linear": return base * level+ if kind == "quadratic": return base * level * level+ if kind == "exponential": return int(base * (growth ** level))+```++Guidance: keep early levels fast (reward in minutes) and stretch later ones. Grant stat gains+and/or skill points on level-up; telegraph the next unlock to pull players forward.++## 4. Turn-based vs. action combat timelines++| | Turn-based | Action |+|---|---|---|+| Time | Discrete; pause to choose | Real-time; reflexes matter |+| Initiative | Speed stat / ATB gauge orders turns | Cooldowns / attack timing |+| Strength | Deep tactics, accessible | Visceral, skill-expressive |+| Build with | A turn scheduler (see `roguelike` Pattern 2) | The engine movement/physics skill |++ATB ("active time battle") is a hybrid: a gauge fills by `speed`; when full, the actor may act.++## 5. Inventory and equipment data++```python+# Items are data, not code. Define them as resources/assets (see godot-resources /+# unity-scriptableobjects) and reference by id.+item = {+ "id": "iron_sword", "name": "Iron Sword", "slot": "weapon",+ "stackable": False, "max_stack": 1,+ "modifiers": [ {"stat": "STR", "type": "flat", "value": 3} ],+ "value": 50,+}+# Inventory = list of (item_id, count). Equipment = slot -> item_id.+# Equipping applies the item's modifiers (push); unequipping removes them (pop).+```++## 6. Quest state model++```python+# A quest is a small state machine with objectives. Persist its state in the save.+quest = {+ "id": "missing_cat", "state": "available", # available -> active -> complete -> turned_in+ "objectives": [ {"id": "find_cat", "done": False, "count": 0, "needed": 1} ],+ "rewards": { "xp": 150, "gold": 30, "items": ["iron_sword"] },+}+# Game events (kill, pickup, talk) update matching objectives; when all done, state=complete.+# Dialogue conditions read quest state; turning in grants rewards and advances dependent quests.+```++Keep quest *definitions* as data and quest *progress* in the save. Gate dialogue lines and+NPC behavior on quest state via `dialogue-systems` conditions/variables.diff --git a/skills/genres/survival-crafting/SKILL.md b/skills/genres/survival-crafting/SKILL.mdnew file mode 100644index 0000000..e723038--- /dev/null+++ b/skills/genres/survival-crafting/SKILL.md@@ -0,0 +1,147 @@+---+name: survival-crafting+description: >+ Build a survival-crafting game: resource gathering, inventory, crafting and a tech tree,+ needs (hunger/thirst/temperature), and base building. Use for a survival or crafting/base-building game.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: advanced+---++# Survival Crafting++A playbook for survival-crafting games — the gather → craft → build loop, survival needs, the+crafting/tech progression, and base building. This is a **compositional** skill: it orchestrates+inventory data, world content, persistence, and threats. It does not re-teach those primitives;+it defines the loop and the pressure systems (needs, scarcity, escalation) that make survival+tense rather than tedious.++## When to use++- Use when the player **gathers resources, crafts items/structures, manages survival needs, and+ builds a base** against escalating threats: survival sandbox, crafting/base-building game.+- Use when designing needs (hunger/thirst/temperature), a crafting tech tree, gathering loops,+ or base placement/building.++**When *not* to use:** crafting as a minor RPG feature → `rpg`. Permadeath grid dungeon →+`roguelike`. For inventory/items as data assets, use `godot-resources` /+`unity-scriptableobjects`; for world generation, `procedural-gen`.++## Core loop++**Gather raw resources → craft tools/items → build and upgrade a base → manage survival needs+→ explore farther for better resources → survive escalating threats → repeat at a higher tier.**+Each loop should unlock the *next* loop (better tools → reach new biomes → new resources →+better crafts). When that ladder breaks, the game becomes a grind.++## Must-have systems++1. **Resource nodes + gathering** — harvestable world objects; tool requirements/tiers; respawn.+2. **Inventory** — stacks, capacity (slots or weight), drop/transfer, hotbar.+3. **Crafting** — recipes (inputs → output), a crafting station/tech gate, a tech tree.+4. **Survival needs** — hunger, thirst, temperature, stamina, health, with decay + consequences.+5. **Base building** — placeable structures, a build grid/snapping, storage, crafting stations.+6. **World + day/night** — biomes/resources (often procedural); a time cycle driving threats.+7. **Threats** — hostile creatures/weather/events that escalate; combat or avoidance.+8. **Save/load** — world state, inventory, base, needs, progression; large-world persistence.++## Design knobs++| Knob | Effect | Notes |+|------|--------|-------|+| Needs decay rates | pressure cadence | Slow enough to explore, fast enough to matter. |+| Need-failure consequence | stakes | Damage over time, not instant death. |+| Resource scarcity / respawn | exploration push | Scarce near base → travel for more. |+| Tool tiers / gating | progression ladder | Better tool → new node types. |+| Recipe complexity / tech depth | long-term goals | Multi-step chains, not flat lists. |+| Inventory limit (slots/weight) | logistics tension | Forces base trips and storage. |+| Threat escalation curve | difficulty over time | Night/seasonal/event ramps. |+| Day length | rhythm | Day = gather, night = defend. |++## Patterns++### 1. Needs decay with graded consequences++```python+# Pseudocode in the per-frame/per-tick update. dt = seconds. Needs fall; failure bleeds HP.+def update_needs(p, dt):+ p.hunger = max(0, p.hunger - HUNGER_RATE * dt)+ p.thirst = max(0, p.thirst - THIRST_RATE * dt)+ p.temp = approach(p.temp, ambient_temperature(p), TEMP_RATE * dt)++ # Consequences are graded, not binary: warnings, then attrition — never instant death.+ if p.hunger == 0 or p.thirst == 0:+ p.hp -= STARVE_DAMAGE * dt # damage over time creates urgency with recovery room+ if p.temp < COLD_THRESHOLD or p.temp > HEAT_THRESHOLD:+ p.hp -= EXPOSURE_DAMAGE * dt+ if p.hunger > 0 and p.thirst > 0 and not exposed(p):+ p.hp = min(p.max_hp, p.hp + REGEN_RATE * dt) # safe + fed => heal+```++### 2. Crafting: validate, then atomically consume inputs++```python+# Pseudocode. Recipes are data: inputs -> output, with an optional station/tech requirement.+recipe = {"id": "stone_axe",+ "inputs": {"wood": 3, "stone": 2}, "output": ("stone_axe", 1),+ "station": "workbench", "requires_tech": "basic_tools"}++def can_craft(recipe, inv, tech, station):+ if recipe.get("requires_tech") and recipe["requires_tech"] not in tech: return False+ if recipe.get("station") and recipe["station"] != station: return False+ return all(inv.count(item) >= n for item, n in recipe["inputs"].items())++def craft(recipe, inv, tech, station):+ if not can_craft(recipe, inv, tech, station): return False+ for item, n in recipe["inputs"].items(): inv.remove(item, n) # consume all, then add+ inv.add(*recipe["output"]) # atomic: no partial craft+ return True+```++### 3. Gathering gated by tool tier++```python+# Pseudocode. A node yields only if the held tool meets its required tier.+def harvest(node, tool):+ if tool.tier < node.required_tier:+ return notify("Need a better tool") # e.g. stone node needs a pickaxe, not fists+ node.hp -= tool.power+ if node.hp <= 0:+ spawn_drops(node.drop_table) # weighted drops (see roguelike loot pattern)+ node.start_respawn(node.respawn_time) # node returns later; world isn't depleted forever+```++## Pitfalls / failure modes++- **Needs that kill instantly** → frustration and save-scumming. Make failure damage over time,+ with clear warnings and a recovery path (Pattern 1).+- **Grind without a ladder** → gathering that never unlocks new gathering. Each tier must open+ the next (better tool → new node → new resource → better craft).+- **Non-atomic crafting** → inputs consumed but output not granted on an edge case. Validate+ first, then consume-and-add as one step (Pattern 2).+- **Inventory with no limits** → no logistics tension and no reason for a base/storage. Cap by+ slots or weight.+- **Permanently depleting the world** → players strip the map and quit. Respawn nodes or+ regenerate resources over time.+- **Per-frame decay unscaled by `dt`** → needs drain at different speeds on different hardware.+ Scale by `dt`.+- **No save / fragile save of a large world** → a crash wipes hours. Persist world+base+needs+ incrementally; version it (see `save-systems`).+- **Flat threat curve** → no late-game pressure. Escalate via night/season/event tiers.++## Composition (build it from these skills)++- **Items/recipes as data:** `godot-resources` / `unity-scriptableobjects` — items, recipes, tech tree, drop tables.+- **World:** `procedural-gen` for biomes/resource placement; `level-design` for authored areas.+- **Persistence:** `save-systems` for large-world state, base, inventory, needs, and versioning.+- **Threats:** `game-ai` for creatures; the engine physics skill for melee/collision.+- **Building/placement:** `godot-tilemap` / `unity-tilemap-2d` (2D) or `godot-3d-essentials` (3D) plus UI snapping.+- **UI:** `godot-ui-control` for inventory, crafting menu, needs HUD, build mode.++## References++- For the full needs model and thresholds, the crafting tech-tree graph, gather/respawn tuning,+ base-building grids, and threat escalation, read `references/needs-and-crafting.md`.diff --git a/skills/genres/survival-crafting/references/needs-and-crafting.md b/skills/genres/survival-crafting/references/needs-and-crafting.mdnew file mode 100644index 0000000..b54321a--- /dev/null+++ b/skills/genres/survival-crafting/references/needs-and-crafting.md@@ -0,0 +1,102 @@+# Survival needs, crafting trees, and building (depth)++Detail behind `SKILL.md`. Engine-neutral pseudocode. Numbers are starting points to tune.++## 1. Needs model++Each need is a value in `[0, max]` that decays over time and triggers consequences at+thresholds. Keep consequences **graded** (warn → attrition) so players have time to react.++| Need | Decays from | Failure consequence | Restored by |+|------|-------------|---------------------|-------------|+| Hunger | time, activity | HP attrition at 0 | eating food |+| Thirst | time (faster than hunger) | HP attrition at 0 | drinking |+| Temperature | ambient, wetness, time of day | HP attrition when too cold/hot | fire, shelter, clothing |+| Stamina | sprint/work | can't sprint/attack at 0 | rest |+| Health | need failure, damage | death at 0 | safe + fed regen, healing items |++```python+# Rates as fraction of max per real second (tune so a day cycle has meaningful pressure).+HUNGER_RATE = 0.6 / 60 # ~empty in ~100 s of neglect at this scale (illustrative)+THIRST_RATE = 1.0 / 60 # thirst should bite before hunger+```++Design notes:+- Thirst usually drains faster than hunger; both should be manageable during normal play and+ only dangerous when neglected.+- Tie decay to activity (sprinting/cold raises hunger) for emergent pressure.+- Always show needs on the HUD with a warning state before they hit zero.++## 2. Crafting tech tree++Model progression as a directed acyclic graph of **tech nodes**; recipes unlock when their+prerequisite tech is researched/built. This turns crafting into long-term goals, not a flat list.++```python+tech = {+ "basic_tools": {"requires": [], "unlocks": ["stone_axe", "stone_pick"]},+ "workbench": {"requires": ["basic_tools"], "unlocks": ["workbench_recipes"]},+ "metalworking": {"requires": ["workbench"], "unlocks": ["furnace", "iron_tools"]},+}+def can_unlock(node, owned): return all(r in owned for r in tech[node]["requires"])+```++Gate stations behind tech (workbench → furnace → forge) and recipes behind stations, so the+player physically builds their way up the tree. Each tier should grant access to a new+resource tier (stone → iron → advanced), closing the gather→craft→reach loop.++## 3. Recipe data and multi-step chains++```python+# Intermediate products make crafting feel like progression, not a vending machine.+recipes = {+ "plank": {"inputs": {"log": 1}, "output": ("plank", 2), "station": None},+ "nails": {"inputs": {"iron_ingot": 1}, "output": ("nails", 4), "station": "forge"},+ "wall": {"inputs": {"plank": 4, "nails": 2}, "output": ("wall", 1), "station": "workbench"},+}+# Refining (log -> plank, ore -> ingot) before assembly (plank+nails -> wall) adds depth+# without more raw resource types.+```++## 4. Gathering and respawn++- Nodes have an HP/tool-tier requirement and a **drop table** (weighted; see the roguelike loot+ pattern). Wrong/weak tool = no yield or slow yield.+- Respawn so the world isn't permanently stripped: timer-based regrowth, or zone-based+ repopulation when the player is away. Scarcity near the base pushes exploration outward.+- Tool tiers gate node types (fists → wood; stone pick → stone/ore; metal pick → hard ore),+ which is the main lever turning "explore farther" into "unlock better gathering".++## 5. Base building++- **Grid/snap placement:** snap structures to a grid or to existing pieces' sockets; validate+ placement (not overlapping, on valid ground, within reach) before committing.+- **Structural sanity (optional):** support/stability rules add depth but cost complexity — add+ only if it serves the fantasy.+- **Function:** bases provide storage (extra inventory), crafting stations (tech gates), and+ defense (walls/traps) against the threat cycle. Storage relieves the inventory cap so the+ player gathers in bulk, then returns — a deliberate logistics loop.++```python+def place(structure, pos, world, inv):+ if not world.is_valid_placement(structure, pos): return notify("Can't build here")+ if not inv.has(structure.cost): return notify("Missing materials")+ inv.consume(structure.cost)+ world.add_structure(structure, pos) # now functions as storage/station/defense+```++## 6. Threat escalation++- **Day/night:** day for gathering, night for defense — a natural rhythm. Threats spawn or+ strengthen at night.+- **Tiered escalation:** ramp threat by elapsed days, tech tier reached, or distance from+ spawn, so the world keeps pace with the player's power. Telegraph big events (a "blood moon"+ style raid) so players can prepare a base.+- Balance escalation against the progression ladder: new threats should arrive roughly as the+ player unlocks the tools/defenses to answer them.++## 7. Saving a large world++Survival saves are big and frequent. Persist incrementally (changed chunks/structures), keep a+`version` for migration, and autosave on safe events (sleeping, day rollover) rather than+mid-combat. Defer slot/versioning mechanics to `save-systems`.diff --git a/skills/genres/tower-defense/SKILL.md b/skills/genres/tower-defense/SKILL.mdnew file mode 100644index 0000000..090c61f--- /dev/null+++ b/skills/genres/tower-defense/SKILL.md@@ -0,0 +1,125 @@+---+name: tower-defense+description: >+ Build a tower defense: enemies pathing along lanes, wave spawning, towers that auto-target and fire,+ an economy, and lives. Use for a tower-defense/wave-defense game, or balancing waves and economy.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: intermediate+---++# Tower Defense++A playbook for tower defense — enemy pathing, wave spawning, tower targeting, and the+economy that ties them together. This is a **compositional** skill: it orchestrates pathing,+AI, and UI into a TD loop. It does not re-teach pathfinding; it defines the systems and the+balance levers (DPS vs. HP vs. income) that decide whether a TD is tense or trivial.++## When to use++- Use when building a game where the player **places towers** that automatically attack+ **waves of enemies** following a path, spends earned currency to expand/upgrade, and loses+ if too many enemies leak through.+- Use when designing wave composition/pacing, tower targeting priorities, or the gold economy.++**When *not* to use:** the player directly controls a shooter → `fps-shooter`. Free-form base+building with needs → `survival-crafting`. For the pathfinding algorithm itself, use `game-ai`.++## Core loop++**Prepare (place/upgrade towers with current gold) → start the wave → enemies path toward the+goal while towers auto-fire → earn gold from kills → survive the wave → repeat against a+harder one.** The tension is a planning puzzle: is my current DPS enough for what's coming,+and can I afford the answer?++## Must-have systems++1. **Enemy path** — waypoint lanes, or grid + pathfinding for maze TD (refs).+2. **Wave spawner** — timed, scripted sequences of enemy types with per-wave scaling.+3. **Towers** — range, fire rate, damage, projectile/hitscan, splash; placement validity.+4. **Targeting** — per-tower priority (first/last/closest/strongest/weakest) (refs).+5. **Economy** — gold from kills + wave bonuses; tower/upgrade costs; sell refund.+6. **Lives / leak** — enemies reaching the goal cost lives; 0 = game over.+7. **Wave/prep UI** — lives, gold, next-wave preview, start-next-wave control.++## Design knobs++| Knob | Effect | Notes |+|------|--------|-------|+| Enemy HP growth/wave | upgrade pressure | Geometric ~1.1–1.2× (refs). |+| Income vs. HP curves | difficulty | Player should *almost* afford each wave. |+| Tower DPS / range / cost | tower identity | Cheap+wide vs. expensive+tall. |+| Targeting priority | optimal placement | Changes play more than raw stats. |+| Enemy variety | counters one-build wins | Fast / armored / flying / swarm / boss. |+| Leak penalty | stakes | Cost lives *and* lost bounty. |+| Upgrade vs. build economy | strategy depth | Diminishing upgrade returns. |+| Wave pacing | tension curve | Spike → breather → spike, not monotonic. |++## Patterns++### 1. Wave spawner (timed, data-driven)++```python+# Pseudocode. A wave is data: a list of (enemy_type, count, spacing). Spawn over time.+wave = [ ("grunt", 10, 0.5), ("runner", 5, 0.3), ("tank", 2, 1.0) ]++def run_wave(wave):+ for enemy_type, count, spacing in wave:+ for _ in range(count):+ spawn_enemy(enemy_type, at=path[0]) # enter at the path start+ wait(spacing) # seconds between spawns (use a timer/coroutine)+ # wave clears when all spawned enemies are dead or have leaked+```++### 2. Tower targeting (filter to range, then pick by priority)++```python+# Pseudocode. "First" (furthest along path) is the standard default for stopping leaks.+def acquire_target(tower, enemies, mode="first"):+ in_range = [e for e in enemies if distance(tower.pos, e.pos) <= tower.range]+ if not in_range: return None+ if mode == "first": return max(in_range, key=lambda e: e.progress)+ if mode == "closest": return min(in_range, key=lambda e: distance(tower.pos, e.pos))+ if mode == "strongest":return max(in_range, key=lambda e: e.hp)+ return in_range[0]+```++### 3. "Can this lane hold?" sanity check (DPS vs. HP)++```python+# Pseudocode. One tower's damage to one enemy crossing its range.+tower_dps = tower.damage * tower.fire_rate+time_in_range = tower.range_coverage_length / enemy.speed+damage_dealt = tower_dps * time_in_range+# Lane holds if summed damage_dealt from covering towers >= enemy.hp (per enemy). See refs.+```++## Pitfalls / failure modes++- **Enemy HP scales slower than player income/DPS** → game trivializes after a few waves.+ Tune the HP curve against the income curve (refs).+- **One dominant tower/strategy** → no decisions. Add enemy types that hard-counter builds+ (armored vs. rapid-fire, flying vs. ground-only) and diminishing upgrade returns.+- **Maze TD that can fully block the goal** → enemies get stuck/softlock. Forbid placements+ that sever the path; recompute paths when towers change (refs).+- **No next-wave telegraph** → specials feel random and unfair. Preview upcoming composition.+- **Per-frame movement unscaled by `dt`** → speed varies with frame rate. Scale steering by `dt`.+- **Leaks only cost lives, not gold** → leaking is sometimes optimal. Make leaks lose bounty too.+- **Monotonic difficulty ramp** → exhausting. Pace spikes and breathers.++## Composition (build it from these skills)++- **Pathing:** `game-ai` for A\*/flow-field/steering; for fixed lanes, simple waypoint following.+- **Enemy movement:** `godot-2d-movement` (or engine equivalent) to move along the path; `unity-navmesh` for nav-based pathing.+- **Map:** `godot-tilemap` / `unity-tilemap-2d` for the grid/lanes; `level-design` for map layouts.+- **Data:** `godot-resources` / `unity-scriptableobjects` to define towers, enemies, and waves as assets.+- **UI:** `godot-ui-control` for HUD (lives, gold, wave preview, build menu).+- **Polish:** `audio-design` for fire/hit/leak sound cues.++## References++- For path representations (waypoints / A\* / flow fields), targeting modes, DPS and economy+ math, enemy scaling, and wave pacing, read `references/balancing.md`.diff --git a/skills/genres/tower-defense/references/balancing.md b/skills/genres/tower-defense/references/balancing.mdnew file mode 100644index 0000000..0d22882--- /dev/null+++ b/skills/genres/tower-defense/references/balancing.md@@ -0,0 +1,110 @@+# Tower defense balancing and pathing (depth)++Math and structures behind `SKILL.md`. Engine-neutral pseudocode. The numbers are starting+points; tune against playtests. For pathfinding internals defer to `game-ai`.++## 1. Representing the path++Three common approaches:++- **Fixed waypoints (lanes):** an ordered list of points; enemies steer toward the next one.+ Simplest, fully authored, ideal for lane defense. Most TD games use this.+- **Grid + pathfinding (A\*):** enemies path from spawn to goal over a walkable grid. Enables+ **maze TD**, where placing towers reshapes the path. Recompute paths when towers change and+ forbid placements that fully block the goal.+- **Flow field:** precompute one direction per tile pointing toward the goal; every enemy reads+ it. Scales to huge crowds (one computation for all enemies) — see `game-ai`.++```python+# Waypoint following (pseudocode): move toward the next waypoint; advance when close.+def update_enemy(e, dt):+ target = path[e.wp_index]+ e.pos = move_toward(e.pos, target, e.speed * dt)+ if distance(e.pos, target) < ARRIVE_EPS:+ e.wp_index += 1+ if e.wp_index >= len(path):+ leak(e) # reached the goal: cost the player a life+```++## 2. Tower targeting modes++Expose a per-tower targeting priority; it changes optimal play more than raw stats:++| Mode | Picks | Good for |+|------|-------|----------|+| First | enemy furthest along the path | default; stops leaks |+| Last | enemy least far along | feeding another tower / slows |+| Closest | nearest to the tower | short-range/splash towers |+| Strongest | highest current/max HP | focus tanks |+| Weakest | lowest HP | last-hit / efficiency |++```python+# Pseudocode. Filter to in-range, then pick by mode.+def acquire_target(tower, enemies, mode):+ in_range = [e for e in enemies if distance(tower.pos, e.pos) <= tower.range]+ if not in_range: return None+ if mode == "first": return max(in_range, key=lambda e: e.progress)+ if mode == "last": return min(in_range, key=lambda e: e.progress)+ if mode == "closest": return min(in_range, key=lambda e: distance(tower.pos, e.pos))+ if mode == "strongest":return max(in_range, key=lambda e: e.hp)+ if mode == "weakest": return min(in_range, key=lambda e: e.hp)+```++## 3. DPS and "can this lane hold?"++```+tower_dps = damage * fire_rate # shots/sec+effective_dps = tower_dps * (1 - target.armor_reduction)+time_in_range = path_length_in_range / enemy_speed+damage_dealt = effective_dps * time_in_range # what one tower does to one passing enemy+```++A lane holds a wave if the **sum of damage_dealt across all covering towers** ≥ enemy HP for+each enemy, accounting for how many enemies overlap in range at once (a single tower can only+shoot one target at a time unless it has splash/multi-shot).++## 4. Enemy scaling across waves++```python+# Pseudocode. Scale HP (and sometimes count/speed) so towers must be upgraded, not just spammed.+def wave_enemy_hp(base_hp, wave, growth=1.15):+ return int(base_hp * (growth ** wave)) # geometric HP growth++# Mix enemy types so one tower build can't answer everything:+# fast/low-HP (rush slows), armored (counters low-damage rapid fire),+# flying (needs anti-air), swarm (needs splash), boss (huge HP spike).+```++Geometric HP growth (~1.1–1.2× per wave) paired with a linear-ish income curve forces+upgrades. If HP grows slower than the player's income/DPS, the game trivializes; faster, and+it walls. Tune the two curves against each other.++## 5. Economy++Income sources and sinks must be balanced so the player is *almost* able to cover each wave:++```+income_per_wave = kill_bounty * enemies_killed + wave_clear_bonus (+ interest, optional)+spend = tower_costs + upgrade_costs+```++- **Kill bounty:** gold per enemy. Leaks should cost income *and* lives so leaking hurts twice.+- **Upgrade vs. build curve:** make upgrades cost-efficient enough that "tall" (few upgraded+ towers) competes with "wide" (many cheap towers). Diminishing upgrade returns prevent one+ god-tower.+- **Interest/banking (optional):** rewards saving but can snowball; cap it.+- **Sell refund:** partial (e.g. 70%) so repositioning is possible but not free.++## 6. Leak / lives model++- Each enemy reaching the goal removes lives (often 1, bosses more). Game over at 0.+- Show a clear "lives" counter and telegraph the next wave's composition so players can prepare.+- A short build/prep phase between waves (or a "start next wave early" bonus) gives agency and+ pacing control.++## 7. Wave pacing++- Alternate pressure: a hard wave, then a breather, then a spike. Pure monotonic ramps exhaust.+- Telegraph specials (flying/boss) one wave ahead via UI so the counter feels fair, not random.+- Let players trigger the next wave early for an economy bonus — rewards confidence and speeds+ pacing for experts without punishing newcomers.diff --git a/skills/genres/visual-novel/SKILL.md b/skills/genres/visual-novel/SKILL.mdnew file mode 100644index 0000000..c576c54--- /dev/null+++ b/skills/genres/visual-novel/SKILL.md@@ -0,0 +1,139 @@+---+name: visual-novel+description: >+ Build a visual novel: a branching script, character and background display, a text box with choices,+ save/load, backlog, and skip/auto. Use for a VN, dating sim, or branching story game.+license: Apache-2.0+compatibility: Engine-agnostic design patterns; snippets are pseudocode (port to your engine)+metadata:+ engine: none+ category: genres+ difficulty: beginner+---++# Visual Novel++A playbook for visual novels — the branching script, the presentation (text box, characters,+backgrounds), choices, and the quality-of-life systems players expect (save anywhere, backlog,+skip, auto). This is a **compositional** skill: it drives a dialogue engine and a UI layer. It+does not re-teach the dialogue engine or UI nodes; it defines the script model and the player+conveniences that make a VN pleasant to read.++## When to use++- Use when the game is **mostly reading branching text** with character art and backgrounds:+ visual novel, dating sim, branching interactive fiction, story-choice game.+- Use when designing a choice/route structure, story flags, or VN conveniences (backlog,+ skip, auto-advance, save-anywhere).++**When *not* to use:** dialogue as one feature inside a larger game → `rpg` consuming+`dialogue-systems`. Card/board play → other genres. For the branching-script engine itself,+use `dialogue-systems` (Ink / Yarn Spinner).++## Core loop++**Read a line → advance → (at a branch) make a choice → the story branches on flags/choices →+read on → reach an ending.** The "game" is the *shape of the branching* and whether choices+feel consequential; everything else is presentation and convenience.++## Must-have systems++1. **Branching script** — ordered lines + choices + jumps, with conditions and variables (Ink/Yarn).+2. **Text box** — speaker name, body text, typewriter reveal, advance on click/key.+3. **Characters** — sprites with expressions/poses, positions, show/hide transitions.+4. **Backgrounds + transitions** — scene images, fades/dissolves.+5. **Choices** — present options, gate some on flags, record the pick.+6. **Story state** — flags/variables that branch the script and unlock content.+7. **Save/load (save-anywhere)** — full script position + state; multiple slots; quick save.+8. **VN conveniences** — backlog/history, skip (read text), auto-advance, text-speed setting.+9. **Audio** — music per scene, SFX, optional voice clips.++## Design knobs++| Knob | Effect | Notes |+|------|--------|-------|+| Text speed / instant | reading comfort | Always allow instant + a skip. |+| Auto-advance delay | hands-free reading | Tunable; pause on choices. |+| Skip scope | re-reading | Skip *read* text only by default. |+| Branch breadth/depth | replay value vs. cost | Branches multiply writing/art work. |+| Flag-gated content | reactivity | Lines/choices that check past decisions. |+| Route structure | story shape | Branch-and-merge vs. distinct routes (refs). |+| Choice visibility | fairness | Show locked choices vs. hide them. |+| Backlog length | convenience | Keep enough to re-read recent context. |++## Patterns++### 1. Script as data the engine walks++```python+# Pseudocode. Lines, choices, and jumps as data — usually authored in Ink/Yarn and stepped+# through by that runtime. The engine asks the script for "the next thing to show".+node = script.current()+if node.kind == "line":+ show_text(node.speaker, node.text) # wait for advance input+elif node.kind == "choice":+ options = [o for o in node.options if condition_met(o.condition, flags)] # gate by flags+ show_choices(options) # wait for selection+elif node.kind == "set":+ flags[node.var] = eval_expr(node.expr, flags)+script.advance(selected_option_or_none)+```++### 2. Typewriter reveal + advance (skippable)++```python+# Pseudocode. Reveal characters over time; a click first completes the line, then advances.+def show_text(speaker, text):+ name_label.text = speaker+ revealed = 0+ while revealed < len(text):+ if advance_pressed(): # first press: reveal the whole line instantly+ revealed = len(text); break+ revealed += chars_per_second * dt+ body_label.text = text[:int(revealed)]+ push_to_backlog_when_complete(speaker, text)+ wait_for_advance() # second press: go to the next line+```++### 3. Choice sets a flag that branches later content++```python+# Pseudocode. Choices write flags; later conditions read them — that is "reactivity".+def on_choice(option):+ if option.set: flags[option.set] = True # e.g. flags["helped_npc"] = True+ script.jump(option.target) # follow the branch++# Elsewhere, a line/choice/ending checks the flag:+if flags.get("helped_npc"): play_route("good_ending") else: play_route("neutral_ending")+```++## Pitfalls / failure modes++- **Save that only stores a checkpoint** → VNs need **save-anywhere**. Persist the exact script+ position *and* all flags/variables (and seen-text data) so a load resumes the same line.+- **Presentation logic baked into the script** → unmaintainable. Keep *content* (text, choices)+ in the script and *how it looks* (sprites, transitions) in the engine layer.+- **No skip/auto/backlog** → readers feel trapped, especially on replays. These are expected+ baseline features, not extras.+- **Skipping unread text** → players miss content. Skip should fast-forward **read** text only.+- **Choices with no consequence** → branches that reconverge instantly feel fake. Set flags that+ visibly change later lines, choices, or endings.+- **Combinatorial branch explosion** → unshippable. Prefer branch-and-merge with a few flagged+ variations over fully distinct trees (refs).+- **Lost reading context** → no backlog to re-read the last lines. Keep a history buffer.+- **Hardcoded language** → no localization path. Keep text in data keyed for translation.++## Composition (build it from these skills)++- **Script engine:** `dialogue-systems` (Ink / Yarn Spinner) — branching, conditions, variables, localization hooks.+- **Presentation:** `godot-ui-control` for the text box, choice menu, name plate, and backlog UI.+- **Persistence:** `save-systems` for save-anywhere slots, seen-text/skip data, and settings.+- **Audio:** `audio-design` for per-scene music, SFX, and voice playback.+- **Visuals:** the engine animation/`Tween` skill for sprite/background transitions; `shader-programming` for dissolves.+- **Process:** `prototype-fast` to test the branch structure in plain text before adding art.++## References++- For the branching data model, route structures (branch-and-merge vs. routes), flags/variables,+ save-anywhere + backlog/skip data, and the content/presentation split, read+ `references/script-and-flow.md`.diff --git a/skills/genres/visual-novel/references/script-and-flow.md b/skills/genres/visual-novel/references/script-and-flow.mdnew file mode 100644index 0000000..bc389ec--- /dev/null+++ b/skills/genres/visual-novel/references/script-and-flow.md@@ -0,0 +1,89 @@+# Visual novel script model and flow (depth)++Detail behind `SKILL.md`. Engine-neutral pseudocode. Covers the branching data model, route+structures, and the save/backlog/skip data a VN needs. For the branching-script runtime+(Ink/Yarn) defer to `dialogue-systems`; this file is the VN-specific glue.++## 1. The script data model++A VN script is a graph of nodes. Whether authored in Ink, Yarn, or your own format, the engine+walks it node by node:++- **Line:** `speaker`, `text`, optional portrait/expression, optional voice clip.+- **Choice:** a set of options, each with display text, an optional `condition` (flag check),+ a `target` to jump to, and optional flags to `set`.+- **Command:** show/hide character, change background, play music/SFX, set a variable, jump/call.+- **Label / knot:** a named entry point you can jump to.++Keep **content** (lines, choices, conditions) separate from **direction** (which sprite, what+transition). Direction can live as lightweight commands in the script, but the *rendering* of+those commands belongs in the engine layer so writers don't touch code.++## 2. Route structures++| Structure | Shape | Cost | Use |+|-----------|-------|------|-----|+| Linear | one path, no branches | low | Kinetic novels (story-first). |+| Branch-and-merge | branches that reconverge | medium | Most VNs; choices vary the trip, not the destination. |+| Gauntlet / routes | distinct routes per choice/character | high | Dating sims, route-based stories. |+| Flag-driven (state) | endings/lines computed from accumulated flags | medium | Reactive stories; "affection" systems. |++Branch-and-merge gives the *feeling* of choice at a fraction of the writing/art cost of fully+distinct routes. Reserve full routes for the moments that matter (e.g. character endings).++## 3. Flags and variables++- **Booleans** for one-off decisions (`helped_npc`).+- **Counters** for accumulated state (`affection_alice`, `corruption`), compared with thresholds+ to pick lines or endings.+- Evaluate conditions when presenting a choice (to gate/hide options) and when branching (to pick+ a target). Keep all of this in the dialogue runtime's variable store so it saves cleanly.++```python+# Pseudocode. Ending selection from accumulated state.+def pick_ending(flags):+ if flags["affection_alice"] >= 5 and flags["helped_npc"]: return "alice_good"+ if flags["affection_alice"] >= 5: return "alice_neutral"+ return "solo"+```++## 4. Save-anywhere data++A VN save must let the player resume the **exact** line. Persist:++```python+save = {+ "version": 1,+ "script_position": script.serialize_position(), # knot + line index (from the runtime)+ "variables": dict(flags), # all story flags/counters+ "seen_text": list(seen_line_ids), # for skip-read-only + completion %+ "history": recent_backlog[-200:], # optional: restore the backlog+ "scene": {"bg": current_bg, "chars": visible_chars, "music": current_track},+}+```++The runtime must expose a serializable position (Ink and Yarn both can save/restore state). Add+a `version` and a migration path so old saves survive script edits (see `save-systems`).++## 5. Backlog, skip, and auto++- **Backlog/history:** append each completed line (speaker + text, and voice handle if any) to a+ ring buffer; a backlog screen scrolls it and can replay voice. Cap length (e.g. 100–200 lines).+- **Skip:** fast-forwards text. Default to skipping **only seen** lines (track `seen_text`);+ optionally allow "skip all" as a setting. Skipping must stop at unseen text and at choices.+- **Auto-advance:** after a line fully reveals, wait `auto_delay` (scaled to text length) then+ advance; pause at choices and cancel on any input.++## 6. Presentation conventions++- **Character positions:** discrete slots (left/center/right); show/hide with a fade or slide.+- **Expressions:** swap a portrait layer rather than reloading the whole sprite.+- **Transitions:** dissolve between backgrounds; a brief fade-to-black marks scene/time changes.+- **Text reveal:** typewriter at a configurable rate; first advance completes the line, second+ advances. Never trap the player in a non-skippable reveal.++## 7. Localization++Keep every player-facing string in data keyed by id (not inline in code/branch logic), so a+translation is a swap of the string table. Allow text expansion (some languages are longer) in+the text box layout, and avoid baking text into images where possible.