SLOPSHOPPER

codyssey

Claude Code, played as an adventure: generative music that follows the agent's mood (/miod), a pixel knight who fights a monster for every edit and command…

bandrowsguardcommandtoastprompt
★ 1v0.2.1MITupdated 2026-10-11delexw/codyssey
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · codyssey
╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ◆ YOU │ │ │ │ fix the failing auth test and add an audit log call │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ⏺ Read(src/auth.ts) ⎿ Read 6 lines ✓ ⚒ FORGE Edit · …/app/src/auth.ts ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Done. I made refresh reject expired claims and added an audit call. │ ╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ✻ Worked for 42s · done 4:20 PM › /knightod ⎿ codyssey: knightod on. Lv 1 · ♥♥♥♥♡ · 5 slain · 21 gold · 1 quests · played 0m · 0 of 5 bosses slain · fell 0 times. Use ⌂ Lv 1 · ♥♥♥♥♡ · 5 slain · 21 gold · progress saved ▣ client module ./strip.tsx ♪ fixed ▣ client module ./wave.tsx ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
⌂ Lv 1 · ♥♥♥♥♡ · 5 slain · 21 gold · progress saved ▣ client module ./strip.tsx ♪ fixed ▣ client module ./wave.tsx ⟨Claude Code's own drawing⟩
Your message
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ ◆ YOU │ │ │ │ fix the failing auth test and add an audit log call │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
Claude's reply
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Done. I made refresh reject expired claims and added an audit call. │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
Tool row
✓ ⚒ FORGE Edit · …/app/src/auth.ts
README

<img src="docs/codyssey.png" alt="codyssey logo: an amber shield with a sword whose crossguard is a pair of code brackets, a scroll and a music note" width="200">

<h1 align="center">codyssey</h1>

[!IMPORTANT] miod's music only works on macOS.

I'm an engineer, but these days I solve the boring problems entirely by vibe coding. Somewhere along the way I felt I had lost the creativity and curiosity I used to have when writing code myself.

So I started thinking about how to make vibe coding fun again. codyssey turns a Claude Code session into a little adventure: while the agent does the work, you hear it as music, watch a pixel knight fight through it, and read it back as a quest log.

It's three mods in one plugin, and each one turns on and off on its own.

What it is

Three Claude Code mods in one plugin.

miod: the soundtrack

Generative music written on the spot while Claude works. No music files, no library, no AI model.

  • Every task picks its own flavour (lo-fi, chiptune, ambient, jazzy and 8 more), key, chord progression, tempo, sound and theme.
  • The mood follows what the agent is doing: reading sounds airy, editing bright, testing focused, shipping triumphant, failing tense until a command passes.
  • The faster it spends tokens, the busier the music.
  • Above the prompt, one line shows the mood, flavour, key, tempo and energy, with a wave under it that scrolls with the music:

miod's status line and moving wave

knightod: the hero

A pixel knight walks a narrow strip above the prompt while Claude works.

  • Every tool call is an encounter: reading finds a scroll, editing a file fights its monster (slime, goblin, skeleton, orc, spider), web searches raise bats and ghosts, and subagents send a skeleton.
  • A failed command costs a heart. A test that passes after a failure summons the Bug Dragon.
  • Committing, pushing or opening a PR opens a treasure chest.
  • Every two minutes of play a boss comes: King Slime, Ogre, Lich, Demon, then the Shadow King.
  • Monsters and bosses grow tougher as the knight levels up.
  • Kills bring gold and xp, and xp brings levels. Progress carries from task to task within a session; a new session starts a new knight. The knight makes camp while you're away.

The knight fighting through a task

What you can meet on the road:

When Claude…The knight meetsWhat it brings
Reads or searches files (Read, Grep, Glob)A scrollHeals 1 heart
Edits or writes a fileA Slime, Goblin, Skeleton, Orc or Spider (the file name picks which)1 xp and 1 to 3 gold, plus 1 xp and 1 gold for each extra heart
Searches or fetches the webA Bat or GhostSame as any monster
Runs a commandA Goblin or WolfSame as any monster
Hands work to a subagentA SkeletonSame as any monster
Calls an MCP toolA SlimeSame as any monster
Runs a command that failsA hitLoses 1 heart
Runs a passing test or check after a failureThe Bug Dragon, 4 hearts2 xp and 5 gold or more per heart
Commits, pushes, merges, tags, or opens or merges a PRA treasure chest5 to 24 gold
Has been playing for 2, 4, 6, 8, then 10 minutesKing Slime (3 hearts), Ogre (4), Lich (5), Demon (6), Shadow King (7)2 xp and 5 gold or more per heart

The knight picks a weapon at random for every strike:

WeaponRangePowerHow oftenHow it hits
⚔️ SwordClose1 heart, or 2 with a specialOftenA slash. Now and then it becomes a glowing yellow special
🪓 AxeClose2 heartsSometimesA heavy chop
🔱 LanceA little further1 heartSometimesReaches the monster a few steps early
🗡️ DaggerFar1 heartSometimesThrown early, flies to the monster
🔥 FireballFurthest2 heartsRarelyCast from far off, flies to the monster

Thrown weapons only open a fight. Once a monster has been hit and is coming in close, the knight switches to the sword, axe or lance. Each weapon is one file in hooks/knightod/game/weapons/, with its range, power and how often it's picked.

How the game works:

MechanismHow it works
❤️ HeartsThe knight starts with 5. Every monster and boss shows one heart and the number it has left beside it, like ♥3. Past 5 hearts, the knight's line shows the count too, like ♥7/12.
📈 Monsters level upMonsters start with 1 heart and gain one every 3 knight levels. Bosses gain one every 2 knight levels, on top of their own.
⭐ LevelsEach level needs 8 more xp than the last. A new level adds a heart and heals the knight fully.
👹 Boss fightsA boss swings back and can wound the knight, but never lands the last blow. Some of the knight's strikes are specials that hit for 2.
💀 FallingLosing the last heart to a failed command brings the knight back with full hearts and half the gold.
⚡ SpeedThe knight walks faster the quicker Claude spends tokens: normal, then double from 30k tokens a minute, then triple from 80k.
📜 ProgressLevel, hearts, kills, gold, quests, play time, bosses slain and falls add up from task to task, for the rest of the session. A new session starts a new knight. Between tasks the knight sits by a campfire.
⏸️ PausingIf Claude ends its turn while a background command or subagent is still running, the knight shows ⏸ paused and stays on the road. When the last one finishes, the knight makes camp.

scrollod: the quest log

Restyles the transcript so the story is easier to follow.

  • Tool calls become one-liners, and their results show only when they fail.
  • Claude's replies stand out from the tool noise.
  • Two styles. game (the default): each tool call wears a badge (☰ SCOUT, ⚒ FORGE, ⚔ FIGHT, ☄ MAGIC, ♞ ALLY, ⚗ POTION), Claude speaks from a nameplate, your prompts sit in a ◆ YOU box, finished background tasks arrive as ⚑ QUEST rows, and a subagent's report comes back in a green ♞ box under its name. plain: the same quiet transcript without the badges.

The transcript in the game style

Install

Needs Claude Code 2.1.290 or newer.

claude plugin marketplace add delexw/codyssey
claude plugin install codyssey@codyssey

Then start a new session. All three mods start on.

If you loaded miod, knightod or scrollod on their own before (from delexw/miod, or a folder in CLAUDE_CODE_PLUGIN_DIRS), remove those first, or their commands are registered twice.

Pick your mods

All three come in the one plugin, and each turns on and off with its own command:

  • Turn one off: /miod off, /knightod off or /scrollod off, and on to bring it back. The choice is remembered in later sessions.
  • Game style: scrollod starts in the game style. Switch to the plain look with /scrollod style plain; it stays plain in later sessions until you pick /scrollod style game.

Usage

/miod                    is the music on or off?
/miod off                stop the music
/miod on                 play again from the next task
/miod wave               list the wave looks: bars, line, mirror, dots, pulse
/miod wave dots          switch the wave to the dots look

/knightod                this session's game: level, hearts, kills, gold, bosses
/knightod off            put the knight away
/knightod on             send the knight out again
/knightod reset          start over with a new knight

/scrollod                on or off, and which style
/scrollod off            show the transcript as Claude Code draws it
/scrollod on             restyle it again
/scrollod style plain    the quieter plain look
/scrollod style game     back to badges, nameplates and quest rows

Add your own

Each mod lives in its own folder under hooks/, and hooks/register.tsx turns all three on.

  • miod: each mood is one row in hooks/miod/moods.ts, each flavour one row in hooks/miod/flavours.ts, each sound style one entry in hooks/miod/styles.ts, and each wave look one file in hooks/miod/waves/.
  • knightod: each weapon is one file in hooks/knightod/game/weapons/; monsters and bosses are sprites in hooks/knightod/sprites/; which tool raises which encounter is in hooks/knightod/game/cues.ts, and the boss order and timing in hooks/knightod/game/bosses.ts.
  • scrollod: the game style's badges are in hooks/scrollod/badge.ts, and the styles in hooks/scrollod/style.ts.

Then check it:

claude plugin validate .
claude plugin test .

Run a checkout without installing it with claude --plugin-dir <path to this repo>.

Limitations

  • miod's music only plays on macOS, where Claude Code plays it through afplay.
  • miod's sound is simple chiptune-style tones.
  • codyssey only sees the session it's loaded in.
Source 90 files
hooks/register.tsx 12 lines
1import type { Register } from 'claude-code'
2
3import { registerKnightod } from './knightod/register'
4import { registerMiod } from './miod/register'
5import { registerScrollod } from './scrollod/register'
6
7export const register: Register = (on, options) => {
8  registerKnightod(on, options)
9  registerMiod(on, options)
10  registerScrollod(on, options)
11}
12
hooks/knightod/register.tsx 222 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import { drawBand, STRIP_KEY } from './band'
5import { BOSS_TIERS, dueBoss, withBoss } from './game/bosses'
6import type { Cue } from './game/cues'
7import { cueForCommand, cueForTool, isTestCommand } from './game/cues'
8import { hashText } from './game/random'
9import { finishQuest, NEW_SAVE, playMinutes } from './game/save'
10import { overflowIds, restScene, startScene, unsettledIdsExceptBosses, withCue, withoutUnfoughtBosses } from './game/scene'
11import { settledIdsOf, settleEvents, woundEvents, woundsOf } from './game/settle'
12import { speedFromRate } from './game/speed'
13import { isSessionCall } from '../shared/origin'
14import type { Spend } from '../shared/tokenRate'
15import { RATE_WINDOW_MS, tokensPerMinute } from '../shared/tokenRate'
16import { hearts } from './game/label'
17import { levelledCue } from './game/level'
18
19const STORE_KEY = 'knightod.isEnabled'
20const isEnabled = atom({ plugin: 'codyssey', key: 'knightod.isEnabled' } as const, true)
21const save = atom({ plugin: 'codyssey', key: 'knightod.save' } as const, NEW_SAVE)
22const scene = atom({ plugin: 'codyssey', key: 'knightod.scene' } as const, null)
23
24const CAMP_MS = 12_000
25
26type Session = { turnId: string | null; spends: Spend[]; wasFailing: boolean; campTimer: Timer | null; backgroundTasks: number; minionSlots: Map<string, number> }
27
28const session: Session = { turnId: null, spends: [], wasFailing: false, campTimer: null, backgroundTasks: 0, minionSlots: new Map() }
29
30async function startQuest($: EngineInterface, prompt: string, turnId: string) {
31  session.campTimer?.cancel()
32  session.campTimer = null
33  session.turnId = turnId
34  session.spends = []
35  session.wasFailing = false
36  const now = await $.clock.now()
37  await update($, scene, previous => startScene(hashText(`${now}:${prompt}`), previous, now))
38}
39
40async function settle($: EngineInterface, ids: readonly number[]) {
41  const current = await read($, scene)
42  if (current === null || ids.length === 0) return
43  const settled = settleEvents(await read($, save), current, ids)
44  await update($, save, () => settled.save)
45  await update($, scene, () => settled.scene)
46}
47
48async function wound($: EngineInterface, wounds: Readonly<Record<string, number>>) {
49  const current = await read($, scene)
50  if (current === null || Object.keys(wounds).length === 0) return
51  const wounded = woundEvents(await read($, save), current, wounds)
52  await update($, save, () => wounded.save)
53  await update($, scene, () => wounded.scene)
54}
55
56function minionSlotOf(agentId: string): number {
57  const slot = session.minionSlots.get(agentId) ?? session.minionSlots.size
58  session.minionSlots.set(agentId, slot)
59  return slot
60}
61
62function cueFrom(cue: Cue, agentId: string | undefined): Cue {
63  return agentId === undefined ? cue : { ...cue, minionSlot: minionSlotOf(agentId) }
64}
65
66async function recordCue($: EngineInterface, cue: Cue) {
67  const current = await read($, scene)
68  if (current === null || !current.isRunning) return
69  const next = withCue(current, levelledCue(cue, (await read($, save)).level))
70  await update($, scene, () => next)
71  await settle($, overflowIds(next))
72}
73
74async function summonDueBoss($: EngineInterface) {
75  const current = await read($, scene)
76  if (current === null) return
77  const tier = dueBoss(await read($, save), current, await $.clock.now())
78  if (tier === null) return
79  const next = withBoss(current, tier, (await read($, save)).level)
80  await update($, scene, () => next)
81  await settle($, overflowIds(next))
82}
83
84async function endQuest($: EngineInterface) {
85  session.turnId = null
86  const current = await read($, scene)
87  if (current === null || !current.isRunning) return
88  await settle($, unsettledIdsExceptBosses(current))
89  const endedAt = await $.clock.now()
90  await update($, save, previous => finishQuest(previous, endedAt - current.startedAt))
91  const isPaused = session.backgroundTasks > 0
92  await update($, scene, now => (now === null ? now : restScene(withoutUnfoughtBosses(now), isPaused)))
93  if (!isPaused) makeCamp($)
94}
95
96function makeCamp($: EngineInterface) {
97  session.campTimer = $.clock.after(CAMP_MS, () => {
98    session.campTimer = null
99    update($, scene, now => (now !== null && !now.isRunning ? null : now)).catch(() => undefined)
100  })
101}
102
103function startsInBackground(input: unknown): boolean {
104  return typeof input === 'object' && input !== null && (input as { run_in_background?: unknown }).run_in_background === true
105}
106
107async function finishBackgroundTask($: EngineInterface) {
108  if (session.backgroundTasks === 0) return
109  session.backgroundTasks -= 1
110  if (session.backgroundTasks > 0 || session.turnId !== null) return
111  const current = await read($, scene)
112  if (current === null || current.isPaused !== true) return
113  await update($, scene, now => (now === null || now.isRunning ? now : restScene(now)))
114  makeCamp($)
115}
116
117export const registerKnightod: Register = on => {
118  on('session.start', { cwd: /^/ }, async ($, e, next) => {
119    session.backgroundTasks = 0
120    session.minionSlots = new Map()
121    const saved = await $.store.get(STORE_KEY)
122    if (typeof saved === 'boolean') await update($, isEnabled, () => saved)
123    await $.command.register({
124      name: 'knightod',
125      description: 'knightod, the pixel knight: show the saved game, or turn it on, off, or start over.',
126      argumentHint: '[on|off|reset]',
127      immediate: true,
128    })
129    return next(e)
130  })
131
132  on('command.run', { command: 'knightod' }, async ($, e) => {
133    const choice = e.args.trim().toLowerCase()
134    if (choice === 'on' || choice === 'off') {
135      await update($, isEnabled, () => choice === 'on')
136      await $.store.set(STORE_KEY, choice === 'on')
137      if (choice === 'off') await update($, scene, () => null)
138      return { text: `knightod ${choice}.` }
139    }
140    if (choice === 'reset') {
141      await update($, save, () => NEW_SAVE)
142      return { text: 'A new knight sets out.' }
143    }
144    const now = await read($, save)
145    const state = (await read($, isEnabled)) ? 'on' : 'off'
146    return {
147      text: `knightod ${state}. Lv ${now.level} · ${hearts(now)} · ${now.kills} slain · ${now.gold} gold · ${now.quests} quests · played ${playMinutes(now)}m · ${now.bossesSlain} of ${BOSS_TIERS.length} bosses slain · fell ${now.deaths} times. Use /knightod on, off or reset.`,
148    }
149  })
150
151  on('turn.start', { turnId: /^/ }, async ($, e, next) => {
152    const result = await next(e)
153    if (session.turnId === null && (await read($, isEnabled))) await startQuest($, e.text, e.turnId)
154    return result
155  })
156
157  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
158    if (!isSessionCall(next.origin)) return next(e)
159    const ran = await next(e)
160    if (startsInBackground(e) && ran.deny === undefined && ran.isError !== true) session.backgroundTasks += 1
161    const hasFailed = ran.deny === undefined && ran.isError === true
162    await recordCue($, cueFrom(cueForCommand(e.command, hasFailed, session.wasFailing), e.agentId))
163    await summonDueBoss($)
164    if (hasFailed) session.wasFailing = true
165    else if (isTestCommand(e.command)) session.wasFailing = false
166    return ran
167  }).catch(($, e, next) => next(e))
168
169  on('tool.call', { tool: /^/ }, async ($, e, next) => {
170    if (e.tool === 'Bash' || !isSessionCall(next.origin)) return next(e)
171    await recordCue($, cueFrom(cueForTool(e.tool, e as unknown as Record<string, unknown>), e.agentId))
172    await summonDueBoss($)
173    const ran = await next(e)
174    if (startsInBackground(e) && ran.deny === undefined && ran.isError !== true) session.backgroundTasks += 1
175    return ran
176  }).catch(($, e, next) => next(e))
177
178  on('prompt.submit', { origin: { kind: 'task-notification' } }, async ($, e, next) => {
179    const result = await next(e)
180    await finishBackgroundTask($)
181    return result
182  }).catch(($, e, next) => next(e))
183
184  on('turn.step', { turnId: /^/ }, async function* ($, e, next) {
185    const result = yield* next(e)
186    if (session.turnId !== null && result.usage) {
187      const { input_tokens, output_tokens, cache_creation_input_tokens } = result.usage
188      const now = await $.clock.now()
189      session.spends = [...session.spends.filter(spend => now - spend.at < RATE_WINDOW_MS), { at: now, tokens: input_tokens + output_tokens + cache_creation_input_tokens }]
190      const speed = speedFromRate(tokensPerMinute(session.spends, now))
191      await update($, scene, current => (current === null || current.speed === speed ? current : { ...current, speed }))
192      await summonDueBoss($)
193    }
194    return result
195  })
196
197  on('turn.complete', { turnId: /^/ }, async ($, e, next) => {
198    const result = await next(e)
199    if (e.turnId === session.turnId) await endQuest($)
200    return result
201  })
202
203  on('ui.message', async ($, e, next) => {
204    if (e.element !== STRIP_KEY) return next(e)
205    await wound($, woundsOf(e.data))
206    await settle($, settledIdsOf(e.data))
207    return {}
208  })
209
210  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
211    const below = await next(e)
212    const current = await read($, scene)
213    if (current === null || e.props.hasSurvey) return below
214    return drawBand($.ui.resolve(e), await read($, save), current, e.props.bodyColumns, below)
215  })
216
217  on('session.end', { sessionId: /^/ }, async ($, e, next) => {
218    session.campTimer?.cancel()
219    return next(e)
220  })
221}
222
hooks/miod/register.tsx 318 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import { activityForCommand, activityForTool, strongestActivity } from './activity'
5import type { Activity } from './activity'
6import { drawBand } from './band'
7import { composeFinish, composeFixed, composePhrase, energyFromRate, soundingScale } from './compose'
8import type { Moment, Note } from './compose'
9import { nextMood } from './moods'
10import type { MoodChoice } from './moods'
11import { seededRandom } from './random'
12import { renderClip, toBase64, WAVE_POINTS_PER_SECOND } from './synth'
13import type { Fade } from './synth'
14import { describeTask, phraseSeconds, startTask } from './task'
15import { DEFAULT_WAVE, isWaveName, WAVE_NAMES } from './waves'
16import type { Task } from './task'
17import type { ScaleName } from './theory'
18import type { NowPlaying } from '../../types'
19import { isSessionCall } from '../shared/origin'
20import type { Spend } from '../shared/tokenRate'
21import { RATE_WINDOW_MS, tokensPerMinute } from '../shared/tokenRate'
22
23const STORE_KEY = 'miod.isEnabled'
24const isEnabled = atom({ plugin: 'codyssey', key: 'miod.isEnabled' } as const, true)
25const nowPlaying = atom({ plugin: 'codyssey', key: 'miod.nowPlaying' } as const, null)
26const chosenWave = atom({ plugin: 'codyssey', key: 'miod.wave' } as const, DEFAULT_WAVE)
27
28const GAIN = 0.1
29const FINISH_LOOK: Look = { label: 'finished', color: '#F5A623' }
30const FIXED_LOOK: Look = { label: 'fixed', color: '#81C784' }
31
32type Look = { label: string; color: string }
33
34type PlayOptions = { fade?: Fade }
35
36type Session = {
37  task: Task | null
38  turnId: string | null
39  phraseNumber: number
40  ticker: Timer | null
41  playing: Set<AbortController>
42  spends: Spend[]
43  toolCalls: number
44  contextFill: number
45  seenThisPhrase: Activity[]
46  isFailing: boolean
47  helpers: number
48  clipCount: number
49  lastTask: Task | null
50  moodChoice: MoodChoice | null
51  phraseEndsAt: number
52  finishTimer: Timer | null
53}
54
55const session: Session = {
56  task: null,
57  turnId: null,
58  phraseNumber: 0,
59  ticker: null,
60  playing: new Set(),
61  spends: [],
62  toolCalls: 0,
63  contextFill: 0,
64  seenThisPhrase: [],
65  isFailing: false,
66  helpers: 0,
67  clipCount: 0,
68  lastTask: null,
69  moodChoice: null,
70  phraseEndsAt: 0,
71  finishTimer: null,
72}
73
74function play($: EngineInterface, task: Task, notes: Note[], seconds: number, look: Look, options: PlayOptions = {}) {
75  const controller = new AbortController()
76  session.playing.add(controller)
77  const clip = renderClip(task.style, notes, seconds, task.seed, options.fade)
78  session.clipCount += 1
79  showWave($, { clipId: session.clipCount, ...look, levels: clip.levels, pointsPerSecond: WAVE_POINTS_PER_SECOND })
80  $.audio
81    .play({ base64: toBase64(clip.wav), mime: 'audio/wav' }, { gain: GAIN, signal: controller.signal })
82    .catch(() => $.ui.toast('miod: could not play audio'))
83    .finally(() => session.playing.delete(controller))
84}
85
86function silence() {
87  session.playing.forEach(controller => controller.abort())
88  session.playing.clear()
89}
90
91function showWave($: EngineInterface, clip: NowPlaying | null) {
92  update($, nowPlaying, () => clip).catch(() => undefined)
93}
94
95async function readMoment($: EngineInterface, now: number): Promise<Moment> {
96  session.spends = session.spends.filter(spend => now - spend.at < RATE_WINDOW_MS)
97  const seen = session.isFailing ? ['failing' as const] : session.seenThisPhrase
98
99  const task = session.task
100  const random = seededRandom((task?.seed ?? 0) + session.phraseNumber * 7919)
101  session.moodChoice = nextMood(session.moodChoice, strongestActivity(seen), random)
102  const moment: Moment = {
103    mood: session.moodChoice.mood,
104    scale: session.moodChoice.scale,
105    energy: energyFromRate(tokensPerMinute(session.spends, now)),
106    contextFill: session.contextFill,
107    toolCalls: session.toolCalls,
108    helpers: session.helpers,
109  }
110  session.toolCalls = 0
111  session.seenThisPhrase = []
112  return moment
113}
114
115async function playNextPhrase($: EngineInterface) {
116  const task = session.task
117  if (!task) {
118    return
119  }
120  const now = await $.clock.now()
121  const moment = await readMoment($, now)
122  const mood = moment.mood
123  const seconds = phraseSeconds(task)
124  const isFirst = session.phraseNumber === 0
125  const look = { label: `${mood.feel} · ${describeTask(task, soundingScale(task, moment.scale))} · energy ${Math.round(moment.energy * 100)}%`, color: mood.color }
126  play($, task, composePhrase(task, session.phraseNumber, moment), seconds, look, {
127    fade: isFirst ? { inSeconds: seconds / 2 } : undefined,
128  })
129  session.phraseNumber += 1
130  session.phraseEndsAt = now + seconds * 1000
131}
132
133async function startMusic($: EngineInterface, prompt: string, turnId: string) {
134  session.finishTimer?.cancel()
135  session.finishTimer = null
136  const task = startTask(prompt, await $.clock.now(), session.lastTask ?? undefined)
137  Object.assign(session, {
138    task,
139    turnId,
140    phraseNumber: 0,
141    spends: [],
142    toolCalls: 0,
143    seenThisPhrase: [],
144    isFailing: false,
145    helpers: 0,
146    moodChoice: null,
147  })
148  await playNextPhrase($)
149  session.ticker = $.clock.every(Math.round(phraseSeconds(task) * 1000), () => {
150    playNextPhrase($).catch(() => undefined)
151  })
152}
153
154async function stopMusic($: EngineInterface, shouldPlayFinish: boolean) {
155  session.ticker?.cancel()
156  session.ticker = null
157  session.finishTimer?.cancel()
158  session.finishTimer = null
159  const task = session.task
160  const scale = session.moodChoice?.scale
161  if (task && scale && shouldPlayFinish) {
162    session.lastTask = task
163    const wait = Math.max(0, session.phraseEndsAt - (await $.clock.now()))
164    session.finishTimer = $.clock.after(Math.round(wait), () => playFinish($, task, scale))
165  } else {
166    silence()
167    showWave($, null)
168  }
169  session.task = null
170  session.turnId = null
171}
172
173function playFinish($: EngineInterface, task: Task, scale: ScaleName) {
174  session.finishTimer = null
175  if (session.task) {
176    return
177  }
178  const seconds = phraseSeconds(task)
179  play($, task, composeFinish(task, soundingScale(task, scale)), seconds, FINISH_LOOK, { fade: { outSeconds: seconds / 2 } })
180  session.finishTimer = $.clock.after(Math.round(seconds * 1000), () => {
181    session.finishTimer = null
182    if (!session.task) {
183      showWave($, null)
184    }
185  })
186}
187
188function noteActivity(activity: Activity) {
189  if (session.task) {
190    session.seenThisPhrase.push(activity)
191  }
192}
193
194function noteCommandResult($: EngineInterface, hasFailed: boolean) {
195  const task = session.task
196  if (!task) {
197    return
198  }
199  if (hasFailed) {
200    session.isFailing = true
201    return
202  }
203  if (session.isFailing) {
204    session.isFailing = false
205    play($, task, composeFixed(task), phraseSeconds(task) / 2, FIXED_LOOK)
206  }
207}
208
209export const registerMiod: Register = on => {
210  on('session.start', async ($, e, next) => {
211    const saved = await $.store.get(STORE_KEY)
212    if (typeof saved === 'boolean') await update($, isEnabled, () => saved)
213    await $.command.register({
214      name: 'miod',
215      description: 'Turn the task music on or off.',
216      argumentHint: '[on|off|wave <name>]',
217      immediate: true,
218    })
219    return next(e)
220  })
221
222  on('command.run', { command: 'miod' }, async ($, e) => {
223    const [choice = '', name = ''] = e.args.trim().toLowerCase().split(/\s+/)
224    if (choice === 'wave') {
225      if (!isWaveName(name)) {
226        return { text: `waves: ${WAVE_NAMES.join(', ')}. Now: ${await read($, chosenWave)}. Use /miod wave <name>.` }
227      }
228      await update($, chosenWave, () => name)
229      return { text: `wave is ${name}.` }
230    }
231    if (choice === 'on' || choice === 'off') {
232      await update($, isEnabled, () => choice === 'on')
233      await $.store.set(STORE_KEY, choice === 'on')
234      if (choice === 'off') {
235        await stopMusic($, false)
236      }
237      return { text: `${choice}.` }
238    }
239    const state = (await read($, isEnabled)) ? 'on' : 'off'
240    return { text: `${state}. Use /miod on, /miod off, or /miod wave <name>.` }
241  })
242
243  on('turn.start', async ($, e, next) => {
244    const result = await next(e)
245    if (!session.task && (await read($, isEnabled))) {
246      await startMusic($, e.text, e.turnId)
247    }
248    return result
249  })
250
251  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
252    if (!isSessionCall(next.origin)) return next(e)
253    noteActivity(activityForCommand(e.command))
254    const ran = await next(e)
255    noteCommandResult($, ran.deny === undefined && ran.isError === true)
256    return ran
257  }).catch(($, e, next) => next(e))
258
259  on('tool.call', async ($, e, next) => {
260    if (e.tool === 'Bash' || !isSessionCall(next.origin)) {
261      return next(e)
262    }
263    const activity = activityForTool(e.tool)
264    noteActivity(activity)
265    if (activity !== 'delegating') {
266      return next(e)
267    }
268    session.helpers += 1
269    try {
270      return await next(e)
271    } finally {
272      session.helpers = Math.max(0, session.helpers - 1)
273    }
274  }).catch(($, e, next) => next(e))
275
276  on('turn.step', async function* ($, e, next) {
277    const result = yield* next(e)
278    if (session.task && result.usage) {
279      const { input_tokens, output_tokens, cache_creation_input_tokens } = result.usage
280      session.spends.push({
281        at: await $.clock.now(),
282        tokens: input_tokens + output_tokens + cache_creation_input_tokens,
283      })
284      session.toolCalls += result.toolUses.length
285    }
286    return result
287  })
288
289  on('session.measure', ($, e, next) => {
290    if (e.context.percent !== undefined) {
291      session.contextFill = e.context.percent / 100
292    }
293    return next(e)
294  })
295
296  on('turn.complete', async ($, e, next) => {
297    const result = await next(e)
298    if (session.task && e.turnId === session.turnId) {
299      await stopMusic($, e.reason === 'answer')
300    }
301    return result
302  })
303
304  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
305    const below = await next(e)
306    const clip = await read($, nowPlaying)
307    if (!clip || e.props.hasSurvey) {
308      return below
309    }
310    return drawBand($.ui.resolve(e), clip, await read($, chosenWave), e.props.bodyColumns, below)
311  })
312
313  on('session.end', async ($, e, next) => {
314    await stopMusic($, false)
315    return next(e)
316  })
317}
318
hooks/scrollod/register.tsx 98 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import { drawAllyBox } from './ally-box'
5import { drawNoticeRow } from './notice-row'
6import { drawPromptBox } from './prompt-box'
7import { drawReply } from './reply'
8import { markRunStarts, MAX_RUN_STARTS } from './runs'
9import { DEFAULT_STYLE, isStyle, STYLES } from './style'
10import { drawToolRow } from './tool-row'
11
12const STORE_KEY = 'scrollod.isOn'
13const STYLE_STORE_KEY = 'scrollod.style'
14const isOn = atom({ plugin: 'codyssey', key: 'scrollod.isOn' } as const, true)
15const style = atom({ plugin: 'codyssey', key: 'scrollod.style' } as const, DEFAULT_STYLE)
16const runStarts = atom({ plugin: 'codyssey', key: 'scrollod.runStarts' } as const, [])
17const lastBlock = atom({ plugin: 'codyssey', key: 'scrollod.lastBlock' } as const, null)
18
19export const registerScrollod: Register = on => {
20  on('session.start', { cwd: /^/ }, async ($, e, next) => {
21    const saved = await $.store.get(STORE_KEY)
22    if (typeof saved === 'boolean') await update($, isOn, () => saved)
23    const savedStyle = await $.store.get(STYLE_STORE_KEY)
24    if (isStyle(savedStyle)) await update($, style, () => savedStyle)
25    await $.command.register({
26      name: 'scrollod',
27      description: 'Quiet transcript: show its state, turn it on or off, or pick the plain or game style.',
28      argumentHint: '[on|off|style <plain|game>]',
29      immediate: true,
30    })
31    return next(e)
32  })
33
34  on('command.run', { command: 'scrollod' }, async ($, e) => {
35    const [choice = '', name = ''] = e.args.trim().toLowerCase().split(/\s+/)
36    if (choice === 'style') {
37      if (!isStyle(name)) return { text: `styles: ${STYLES.join(', ')}. Now: ${await read($, style)}. Use /scrollod style <name>.` }
38      await update($, style, () => name)
39      await $.store.set(STYLE_STORE_KEY, name)
40      return { text: `scrollod style is ${name}.` }
41    }
42    if (choice === 'on' || choice === 'off') {
43      await update($, isOn, () => choice === 'on')
44      await $.store.set(STORE_KEY, choice === 'on')
45      return { text: `scrollod ${choice}.` }
46    }
47    return { text: `scrollod is ${(await read($, isOn)) ? 'on' : 'off'}, style ${await read($, style)}. Use /scrollod on, off or style <plain|game>.` }
48  })
49
50  on('session.append', async ($, e, next) => {
51    const result = await next(e)
52    if (e.agentId !== undefined) return result
53    if (e.door === 'prompt') {
54      await update($, lastBlock, () => 'prose')
55    } else if (e.door === 'response') {
56      const marked = markRunStarts(await read($, lastBlock), e.message.content as readonly { type: string; id?: unknown }[])
57      await update($, lastBlock, () => marked.last)
58      if (marked.starts.length > 0) await update($, runStarts, ids => [...ids, ...marked.starts].slice(-MAX_RUN_STARTS))
59    }
60    return result
61  }).catch(($, e, next) => next(e))
62
63  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
64    if (e.surface !== 'terminal' || !(await read($, isOn))) return next(e)
65    return drawToolRow($.ui.resolve(e), {
66      id: e.props.tool_use_id,
67      tool: e.props.tool,
68      input: e.props.input,
69      isRunning: e.props.isRunning,
70      isErrored: e.props.isErrored,
71      isInterrupted: e.props.isInterrupted,
72      style: await read($, style),
73      startsRun: (await read($, runStarts)).includes(e.props.tool_use_id),
74    })
75  })
76
77  on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
78    if (e.surface !== 'terminal' || e.props.isErrored || !(await read($, isOn))) return next(e)
79    const { Box } = $.ui.resolve(e)
80    return <Box />
81  })
82
83  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
84    if (e.surface !== 'terminal' || !(await read($, isOn)) || (await read($, style)) !== 'game') return next(e)
85    if (e.props.origin.kind === 'composer') return drawPromptBox($.ui.resolve(e), e.props.text)
86    if (e.props.origin.kind === 'task-notification') {
87      return drawNoticeRow($.ui.resolve(e), { text: e.props.text, status: e.props.task?.status, durationMs: e.props.task?.durationMs })
88    }
89    if (e.props.from !== undefined) return drawAllyBox($.ui.resolve(e), { name: e.props.from.name, text: e.props.text })
90    return next(e)
91  })
92
93  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
94    if (e.surface !== 'terminal' || e.props.isSummary || !(await read($, isOn))) return next(e)
95    return drawReply($.ui.resolve(e), { text: e.props.text, isFirstOfReply: e.props.isFirstOfReply, style: await read($, style) })
96  })
97}
98
hooks/knightod/band.tsx 29 lines
1import type { ElementTable, RenderElement } from 'claude-code'
2
3import type { Save, Scene } from '../../types'
4import { statusLine } from './game/label'
5import { STRIP_PIXEL_ROWS } from './world/world'
6
7export const STRIP_MAX_COLUMNS = 64
8export const STRIP_MIN_COLUMNS = 16
9export const STRIP_KEY = 'knightod-strip'
10
11export function drawBand(elements: ElementTable, save: Save, scene: Scene, columns: number, below: RenderElement): RenderElement {
12  const { Box, Text } = elements
13  const stripColumns = Math.min(STRIP_MAX_COLUMNS, columns)
14  const strip =
15    'Client' in elements && stripColumns >= STRIP_MIN_COLUMNS ? (
16      <elements.Client key={STRIP_KEY} module="./strip.tsx" props={{ scene }} width={stripColumns} height={STRIP_PIXEL_ROWS / 2} />
17    ) : null
18
19  return (
20    <Box flexDirection="column">
21      <Text color={scene.isRunning ? '#FFC107' : 'subtle'} wrap="truncate-end">
22        {statusLine(save, scene)}
23      </Text>
24      {strip}
25      {below}
26    </Box>
27  )
28}
29
hooks/knightod/game/bosses.ts 34 lines
1import type { BossSpecies, Save, Scene, Species } from '../../../types'
2import { levelledCue } from './level'
3import { withCue } from './scene'
4
5export type BossTier = { species: BossSpecies; hearts: number; atMs: number }
6
7const MINUTE_MS = 60_000
8
9export const BOSS_TIERS: readonly BossTier[] = [
10  { species: 'king-slime', hearts: 3, atMs: 2 * MINUTE_MS },
11  { species: 'ogre', hearts: 4, atMs: 4 * MINUTE_MS },
12  { species: 'lich', hearts: 5, atMs: 6 * MINUTE_MS },
13  { species: 'demon', hearts: 6, atMs: 8 * MINUTE_MS },
14  { species: 'shadow-king', hearts: 7, atMs: 10 * MINUTE_MS },
15]
16
17export function playedMs(save: Save, scene: Scene, now: number): number {
18  return save.playMs + (scene.isRunning ? Math.max(0, now - scene.startedAt) : 0)
19}
20
21export function isTimedBoss(species: Species | null): boolean {
22  return BOSS_TIERS.some(tier => tier.species === species)
23}
24
25export function dueBoss(save: Save, scene: Scene, now: number): BossTier | null {
26  const tier = BOSS_TIERS[save.bossesSlain]
27  if (!scene.isRunning || tier === undefined || playedMs(save, scene, now) < tier.atMs) return null
28  return scene.events.some(event => event.kind === 'boss' && !event.isSettled) ? null : tier
29}
30
31export function withBoss(scene: Scene, tier: BossTier, level = 1): Scene {
32  return withCue(scene, levelledCue({ kind: 'boss', species: tier.species, target: '', hearts: tier.hearts }, level))
33}
34
hooks/knightod/game/cues.ts 118 lines
1import type { EventKind, GameEvent, Species } from '../../../types'
2import { heartCount } from './label'
3import { hashText } from './random'
4
5export type Cue = { kind: EventKind; species: Species | null; target: string; hearts?: number; minionSlot?: number }
6
7const READING_TOOLS = ['Read', 'Grep', 'Glob', 'LS', 'NotebookRead']
8const EXPLORING_TOOLS = ['WebFetch', 'WebSearch']
9const EDITING_TOOLS = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit']
10const DELEGATING_TOOLS = ['Agent', 'Task']
11const EDIT_SPECIES: readonly Species[] = ['slime', 'goblin', 'skeleton', 'orc', 'spider']
12const WEB_SPECIES: readonly Species[] = ['bat', 'ghost']
13const SHELL_SPECIES: readonly Species[] = ['goblin', 'wolf']
14const BUG_DRAGON_HEARTS = 4
15
16const SHIPPING_COMMAND = /\bgit (commit|push|merge|tag)\b|\bgh pr (create|merge)\b/
17const TEST_COMMAND = /\b(test|tests|spec|jest|vitest|pytest|rspec|mocha|check|lint|tsc)\b/
18
19export function isTestCommand(command: string): boolean {
20  return TEST_COMMAND.test(command)
21}
22
23function baseName(path: string): string {
24  return path.split('/').filter(Boolean).at(-1) ?? path
25}
26
27function textField(input: Record<string, unknown>, ...names: string[]): string {
28  for (const name of names) {
29    const value = input[name]
30    if (typeof value === 'string' && value.trim() !== '') return value.trim()
31  }
32  return ''
33}
34
35function pickSpecies(species: readonly Species[], target: string): Species {
36  return species[hashText(target) % species.length] ?? 'slime'
37}
38
39function hostOf(url: string): string {
40  const match = /^[a-z]+:\/\/([^/]+)/i.exec(url)
41  return match?.[1] ?? url
42}
43
44export function cueForTool(tool: string, input: Record<string, unknown>): Cue {
45  if (READING_TOOLS.includes(tool)) {
46    return { kind: 'scroll', species: null, target: baseName(textField(input, 'file_path', 'notebook_path', 'path', 'pattern')) || tool }
47  }
48  if (EXPLORING_TOOLS.includes(tool)) {
49    const target = hostOf(textField(input, 'url', 'query')) || 'the web'
50    return { kind: 'monster', species: pickSpecies(WEB_SPECIES, target), target }
51  }
52  if (EDITING_TOOLS.includes(tool)) {
53    const target = baseName(textField(input, 'file_path', 'notebook_path')) || tool
54    return { kind: 'monster', species: pickSpecies(EDIT_SPECIES, target), target }
55  }
56  if (DELEGATING_TOOLS.includes(tool)) {
57    return { kind: 'monster', species: 'skeleton', target: textField(input, 'description') || 'the crypt' }
58  }
59  if (tool.startsWith('mcp__')) {
60    return { kind: 'monster', species: 'slime', target: tool.split('__')[1] ?? tool }
61  }
62  return { kind: 'monster', species: 'slime', target: tool }
63}
64
65export function cueForCommand(command: string, hasFailed: boolean, wasFailing: boolean): Cue {
66  const target = command.trim().split(/\s+/).slice(0, 2).join(' ') || 'the shell'
67  if (hasFailed) return { kind: 'hurt', species: null, target }
68  if (SHIPPING_COMMAND.test(command)) return { kind: 'chest', species: null, target }
69  if (isTestCommand(command) && wasFailing) return { kind: 'boss', species: 'dragon', target, hearts: BUG_DRAGON_HEARTS }
70  return { kind: 'monster', species: pickSpecies(SHELL_SPECIES, target), target }
71}
72
73const SPECIES_NAMES: Record<Species, string> = {
74  slime: 'Slime',
75  goblin: 'Goblin',
76  bat: 'Bat',
77  skeleton: 'Skeleton',
78  wolf: 'Wolf',
79  spider: 'Spider',
80  ghost: 'Ghost',
81  orc: 'Orc',
82  'king-slime': 'King Slime',
83  ogre: 'Ogre',
84  lich: 'Lich',
85  demon: 'Demon',
86  'shadow-king': 'Shadow King',
87  dragon: 'Bug Dragon',
88}
89
90export function cueName(cue: Cue): string {
91  switch (cue.kind) {
92    case 'monster':
93      return `the ${SPECIES_NAMES[cue.species ?? 'slime']} of "${cue.target}"`
94    case 'boss':
95      return `the ${SPECIES_NAMES[cue.species ?? 'dragon']} ${heartCount(cue.hearts ?? 1)}`
96    case 'chest':
97      return 'a treasure chest'
98    case 'scroll':
99      return `a scroll of "${cue.target}"`
100    case 'hurt':
101      return `hit by "${cue.target}"`
102  }
103}
104
105export function settledName(event: GameEvent): string {
106  switch (event.kind) {
107    case 'monster':
108    case 'boss':
109      return `slew ${event.name}`
110    case 'chest':
111      return `opened ${event.name}`
112    case 'scroll':
113      return `picked up ${event.name}`
114    case 'hurt':
115      return event.name
116  }
117}
118
hooks/knightod/game/random.ts 20 lines
1export function hashText(text: string): number {
2  let hash = 2166136261
3  for (let index = 0; index < text.length; index += 1) {
4    hash ^= text.charCodeAt(index)
5    hash = Math.imul(hash, 16777619)
6  }
7  return hash >>> 0
8}
9
10export function seededRandom(seed: number): () => number {
11  let state = seed >>> 0
12  return () => {
13    state = (state + 0x6d2b79f5) >>> 0
14    let mixed = state
15    mixed = Math.imul(mixed ^ (mixed >>> 15), mixed | 1)
16    mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61)
17    return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296
18  }
19}
20
hooks/knightod/game/save.ts 44 lines
1import type { EventKind, Save } from '../../../types'
2
3export const NEW_SAVE: Save = { level: 1, xp: 0, hp: 5, maxHp: 5, kills: 0, gold: 0, deaths: 0, quests: 0, playMs: 0, bossesSlain: 0 }
4
5export function playMinutes(save: Save): number {
6  return Math.floor(save.playMs / 60_000)
7}
8
9export function xpForNextLevel(level: number): number {
10  return level * 8
11}
12
13function gainXp(save: Save, xp: number): Save {
14  let next = { ...save, xp: save.xp + xp }
15  while (next.xp >= xpForNextLevel(next.level)) {
16    next = { ...next, xp: next.xp - xpForNextLevel(next.level), level: next.level + 1, maxHp: next.maxHp + 1 }
17    next = { ...next, hp: next.maxHp }
18  }
19  return next
20}
21
22export function applyEvent(save: Save, kind: EventKind, random: () => number, hearts = 1): Save {
23  switch (kind) {
24    case 'monster':
25      return gainXp({ ...save, kills: save.kills + 1, gold: save.gold + hearts + Math.floor(random() * 3) }, hearts)
26    case 'boss':
27      return gainXp({ ...save, kills: save.kills + 1, gold: save.gold + 5 * hearts + Math.floor(random() * 10) }, 2 * hearts)
28    case 'chest':
29      return { ...save, gold: save.gold + 5 + Math.floor(random() * 20) }
30    case 'scroll':
31      return { ...save, hp: Math.min(save.maxHp, save.hp + 1) }
32    case 'hurt':
33      return save.hp > 1 ? { ...save, hp: save.hp - 1 } : { ...save, hp: save.maxHp, deaths: save.deaths + 1, gold: Math.floor(save.gold / 2) }
34  }
35}
36
37export function woundByBoss(save: Save, hits: number): Save {
38  return { ...save, hp: Math.max(Math.min(save.hp, 1), save.hp - hits) }
39}
40
41export function finishQuest(save: Save, playedMs: number): Save {
42  return { ...save, quests: save.quests + 1, playMs: save.playMs + Math.max(0, playedMs) }
43}
44
hooks/knightod/game/scene.ts 47 lines
1import type { GameEvent, Scene } from '../../../types'
2import type { Cue } from './cues'
3import { cueName } from './cues'
4
5export const MAX_EVENTS = 12
6export const MAX_UNSETTLED = 24
7
8export function startScene(seed: number, previous: Scene | null, now: number): Scene {
9  return {
10    isRunning: true,
11    seed,
12    speed: 1,
13    events: [],
14    nextId: previous?.nextId ?? 1,
15    latest: previous ? 'back on the road' : 'sets out',
16    startedAt: now,
17  }
18}
19
20export function withCue(scene: Scene, cue: Cue): Scene {
21  const event: GameEvent = { id: scene.nextId, kind: cue.kind, species: cue.species, name: cueName(cue), isSettled: false }
22  if (cue.hearts !== undefined) event.hearts = cue.hearts
23  if (cue.minionSlot !== undefined) event.minionSlot = cue.minionSlot
24  const events = [...scene.events, event]
25  while (events.length > MAX_EVENTS && events[0]?.isSettled === true) events.shift()
26  return { ...scene, events, nextId: scene.nextId + 1, latest: event.name }
27}
28
29export function unsettledIdsExceptBosses(scene: Scene): number[] {
30  return scene.events.filter(event => !event.isSettled && event.kind !== 'boss').map(event => event.id)
31}
32
33export function withoutUnfoughtBosses(scene: Scene): Scene {
34  return { ...scene, events: scene.events.filter(event => event.isSettled || event.kind !== 'boss') }
35}
36
37export function overflowIds(scene: Scene): number[] {
38  const waiting = unsettledIdsExceptBosses(scene)
39  return waiting.slice(0, Math.max(0, waiting.length - MAX_UNSETTLED))
40}
41
42export const PAUSED_TEXT = 'paused, waiting on background work'
43
44export function restScene(scene: Scene, isPaused = false): Scene {
45  return { ...scene, isRunning: false, isPaused, latest: isPaused ? PAUSED_TEXT : 'progress saved' }
46}
47
hooks/knightod/game/settle.ts 48 lines
1import type { Save, Scene } from '../../../types'
2import { settledName } from './cues'
3import { seededRandom } from './random'
4import { isTimedBoss } from './bosses'
5import { counterHits } from './fight'
6import { applyEvent, woundByBoss } from './save'
7
8export function settleEvents(save: Save, scene: Scene, ids: readonly number[]): { save: Save; scene: Scene } {
9  let next = save
10  let latest = scene.latest
11  const events = scene.events.map(event => {
12    if (event.isSettled || !ids.includes(event.id)) return event
13    if (event.kind === 'boss') next = woundByBoss(next, counterHits(scene.seed, event.id, event.hearts ?? 1) - (event.woundsTaken ?? 0))
14    if (event.kind === 'boss' && isTimedBoss(event.species)) next = { ...next, bossesSlain: next.bossesSlain + 1 }
15    next = applyEvent(next, event.kind, seededRandom(scene.seed + event.id * 7919), event.hearts)
16    latest = settledName(event)
17    return { ...event, isSettled: true }
18  })
19  return { save: next, scene: { ...scene, events, latest } }
20}
21
22export function woundEvents(save: Save, scene: Scene, wounds: Readonly<Record<string, number>>): { save: Save; scene: Scene } {
23  let next = save
24  const events = scene.events.map(event => {
25    const landed = wounds[String(event.id)]
26    if (event.kind !== 'boss' || event.isSettled || landed === undefined) return event
27    const total = Math.min(landed, counterHits(scene.seed, event.id, event.hearts ?? 1))
28    const fresh = total - (event.woundsTaken ?? 0)
29    if (fresh <= 0) return event
30    next = woundByBoss(next, fresh)
31    return { ...event, woundsTaken: total }
32  })
33  return { save: next, scene: { ...scene, events } }
34}
35
36export function woundsOf(data: unknown): Record<string, number> {
37  if (typeof data !== 'object' || data === null || !('wounds' in data)) return {}
38  const wounds = (data as { wounds: unknown }).wounds
39  if (typeof wounds !== 'object' || wounds === null) return {}
40  return Object.fromEntries(Object.entries(wounds).filter((entry): entry is [string, number] => typeof entry[1] === 'number'))
41}
42
43export function settledIdsOf(data: unknown): number[] {
44  if (typeof data !== 'object' || data === null || !('settled' in data)) return []
45  const settled = (data as { settled: unknown }).settled
46  return Array.isArray(settled) ? settled.filter((id): id is number => typeof id === 'number') : []
47}
48
hooks/knightod/game/speed.ts 6 lines
1export function speedFromRate(perMinute: number): number {
2  if (perMinute >= 80_000) return 3
3  if (perMinute >= 30_000) return 2
4  return 1
5}
6