SLOPSHOPPER

monster

Raise a digital monster that grows from your Claude Code work

panebandguardcommandtoastprocess
v0.7.4MITupdated 2026-10-13K-Mertin/claude-monster-pet
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · monster
│ ┃ Byte ✕ › fix the failing auth test and add an ╭───────────────────────────╮ │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ │ monster │ │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ⏺ Read(src/auth.ts) │ ✨ Byte evolved into baby! │ │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ⎿ Read 6 lines ╰───────────────────────────╯ │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ⏺ Update(src/auth.ts) ╭────────────────────────╮ │ ┃ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ⎿ Added 2 lines, removed 1 line │ monster │ │ ┃ ⏺ Bash(bun test) │ ⚠ Byte is very hungry. │ │ ┃ ⎿ 3 pass, 1 fail ╰────────────────────────╯ │ ┃ │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /pet │ ┃ ⎿ monster: Byte · Lv 1 baby — Badge: Shipped it │ ┃ Byte · Lv 1 baby · grumpy 🍂 autumn │ ┃ food ░░░░░░ joy ░░░░░░ nrg ██████ stress │ ┃ ░░░░░░ xp 10/40 │ ┃ ▸ Next up: Byte is hungry: Feed it, use a │ ┃ 🍪, or give Claude some work. │ ┃ [ Home ] [ Items 3 ] [ Games ] [ Shop 💎1 ] │ ┃ [ Feed ] [ Play ] [ Pat ♥ ] [ Talk ] [ Tuck │ ┃ │ ┃ Quests 0/7: ○ Feed it once · ○ Talk with it │ ┃ · ○ Win a treat hunt · ○ Train a skill · ○ │ ┃ Buy a decoration · ○ Make its card (/pet Byte · Lv 1 baby ▄▀▀▄ food ░░░░░░ joy ░░░░░░ nrg █████ xp ░░░░░░ ▀▀▀▀▀▀ ♥ 💬 Tip 2/6: It hatched! Type /pet to visit its habitat. Skip tour ▀▀▀▀▀ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Byte · Lv 1 baby ▄▀▀▄ food ░░░░░░ joy ░░░░░░ nrg █████ xp ░░░░░░ ▀▀▀▀▀▀ ♥ 💬 Tip 2/6: It hatched! Type /pet to visit its habitat. Skip tour ▀▀▀▀▀
Pane · Byte
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ Byte · Lv 1 baby · grumpy 🍂 autumn food ░░░░░░ joy ░░░░░░ nrg ██████ stress ░░░░░░ xp 10/40 ▸ Next up: Byte is hungry: Feed it, use a 🍪, or give Claude some work. [ Home ] [ Items 3 ] [ Games ] [ Shop 💎1 ] [ Style ] [ Badg [ Feed ] [ Play ] [ Pat ♥ ] [ Talk ] [ Tuck in ] [ Hide band Quests 0/7: ○ Feed it once · ○ Talk with it · ○ Win a treat hunt · ○ Train a skill · ○ Buy a decoration · ○ Make its card (/pet card) · ○ Fight a weekly Bug Boss · Badge: Shipped it · Badge: Hello, world · Byte hatched!
README

Claude Monster Pet

A Claude Code mod that hatches a pixel-art digital monster and raises it from your work. Tokens feed it, passing tests and commits cheer it up, failed commands stress it, and the way you work decides what it evolves into.

A Forge monster in a party hat strolling through its habitat among a flower pot, desk, toy box, fountain and lantern

Install

Requires Claude Code 2.1.287 or later with mods allowed (an organization can turn them off). Check your version with claude --version.

From your shell:

claude plugin marketplace add K-Mertin/claude-monster-pet
claude plugin install monster@claude-monster-pet

Or, at the prompt of a terminal session: /plugin install monster --marketplace K-Mertin/claude-monster-pet, then y to add the marketplace and pick a scope.

If a session is already open, run /reload-plugins in it; new sessions load it on their own. To check it loaded, run /plugin: the line under the tabs should name monster among the active mods, and an egg appears above your prompt.

To update later: claude plugin update monster@claude-monster-pet, then /reload-plugins.

Use

  • The band above the prompt shows your monster with its food, joy, energy and XP, plus what it is up to.
  • The band has ♥ (pat) and 💬 (talk) buttons.
  • /pet opens its habitat, where it strolls about under the season's weather. Six tabs:
  • Home: Feed, Play, Pat, Talk, Clean (after meals it makes a mess), Tuck in (it sleeps and recovers), sound and alert toggles
  • Items: treats earned from your work, each with its own effect
  • Games: the weekly Bug Boss, a three-round treat hunt with prizes, and training for Power, Wisdom and Speed
  • Shop: spend gems on decorations for the habitat
  • Style: hats unlocked by badges
  • Badges: 23 achievements, each announced with a toast, and the Hall of Fame
  • New here? Tips appear above your prompt, the habitat shows what to do next, and /pet help lists every command.
  • Commands: /pet help, /pet card, /pet visit [<code>|play|spar|bye], /pet feed|play|talk|clean|tuck, /pet hunt [left|middle|right], /pet boss [strike|outsmart|dodge], /pet use cookie|coffee|gem|bug, /pet train power|wisdom|speed, /pet buy <decoration>, /pet hat <hat>|none, /pet retire, /pet name <name>, /pet sound on|off, /pet alerts on|off, /pet hide|show, /pet close (closes the habitat pane)

Your monster's DNA

From the child stage on, your habits draw your monster, so no two look alike, even on the same evolution line:

Four Forge adults with different DNA: a slim blue night-owl TypeScript monster with glasses, a stout bold-blue Python monster with a yellow patch, and two Rust monsters with Go-cyan markings that differ only by their owners' seeds

HabitBecomes
Your main language (by file extension)Its colour; the more you stick to one language, the bolder it gets
Your second languageThe colour of its pattern
The hours you workA forehead mark: a moon for night owls, a sun for early birds, a star for steady hours
Edits per commitIts build: small frequent commits make it slim, big ones stout
Passing testsArmour scales on its belly
Few errors, late nights, lots of researchSharp eyes, sleepy eyes, glasses
A 30-day streakA red scarf
Who you are (a hash of your git email)Its exact tint, pattern style and placement, horn length, and a one-in-256 chance of a shiny gold colouring

The Style tab explains each trait and where it came from. Only counts are kept: languages by extension, active hours, commit sizes and test results, plus a hash of your git email. No file paths, code, messages or the email itself.

Share your card

/pet card saves a pixel card of your monster as ~/.claude/monster/card.png and opens it: its form, languages, habits, record and a DNA code. The Style tab shows a preview.

A card for Byte, a level 11 Emberkin: a blue striped Forge monster, TypeScript 75%, CSS 18%, Shell 8%, armoured, with its DNA code

The DNA code (like BYTE-00B43-QW2E-8835) holds its seed and traits.

Friends' visits

Byte, a blue TypeScript Forge child, hosting Mochi, a Python Wanderer adult, in the rain

Swap DNA codes with a friend. /pet visit <their code> brings their monster to stay for a day, drawn from the code and strolling beside yours. Play together for joy and XP, or have a friendly spar (stage and skills decide it, with a little luck), once each per visit. /pet visit shows your own code to share. No server: just copy and paste.

Hats

Badges unlock eight hats: party hat, cap, headphones, wizard hat, flower, bow, beanie and halo.

The eight hats, worn by adult monsters

The weekly Bug Boss

A Forge monster in a cap facing the three-headed Flaky Hydra

Each week a boss forms from your previous week's failures: a Lint Imp after a clean week, a Stacktrace Golem after broken commands, a Flaky Hydra after failing tests, a Regression Kraken after a rough week. Fight it turn by turn with Strike (Power), Outsmart (Wisdom) and Dodge (Speed); each turn it shows which move hits hard. Beat it for 3 gems, 30 xp and a badge. From the child stage on.

Secret forms and generations

Extreme habits unlock hidden forms: Archivist (a Scribe with 50 Wisdom), Bugslayer (3 bosses beaten), Goldheart (a 30-day streak). After 30 days as an ultimate your monster can retire to the Hall of Fame; the next egg keeps your badges, hats, items and decorations, and inherits a head start in its best skill.

The habitat

The habitat in four seasons: spring petals, a summer day, Halloween at dusk with pumpkins, and Christmas snow with a tree

Seasons and daily weather follow your calendar (blossoms, sun, falling leaves, rain, snow), with Halloween pumpkins, a Christmas tree, New Year fireworks and a cake on its birthday. Gems buy a flower pot, lantern, sign, picnic rug, bed, toy box, desk with a laptop and a fountain. It naps in its bed if it has one.

How it grows

Your workEffect
Tokens Claude processesFood and XP; a ☕ coffee every 50k tokens
Passing test runsJoy, XP and a 🍪 cookie; a 🐛 bug snack when a failing test passes again
Git commits and pushesJoy, XP and a 💎 gem
Finished todo itemsJoy and XP
New subagentsIt waves at them
Failed or denied commandsStress; too much makes it sick, and it recovers over time
A new day of workA daily gift and a growing streak, with gems at 3, 7 and 30 days
Hours awayIt gets hungry and sleeps. It never dies.

Stages: egg → baby (Lv 1) → child (Lv 4) → adult (Lv 10) → ultimate (Lv 20).

At the child stage it picks an evolution line from how you have worked:

Evolution lines: each row goes egg, baby, child, bright adult, bright ultimate, shadow adult, shadow ultimate, for Forge, Scribe, Summoner and Wanderer

LineWhenLooksAdult (bright / shadow)Ultimate (bright / shadow)
Forgemostly shell commandshorns, flame tailEmberkin / CinderhornSolforge / Ashtyrant
Scribemostly reading and editing codea floating ghost with a quillQuillwisp / InkshadeLorewraith / Hexscript
Summonermany subagentsbig earsCallpup / HollowearChoirlord / Legionmaw
Wandererlots of web researchwings and a beakSkylark / DuskwingZephyrus / Stormcrow

How well you care for it decides whether its adult form is bright or shadow. Each monster also hatches with a personality (cheerful, lazy, curious or grumpy) that colors what it says.

There is one monster per machine, shared by every session, saved in ~/.claude/monster/pet.json. The mod makes no model calls and no network requests.

Platforms

Everything works on macOS. On Linux and Windows the monster, habitat and games work the same, but sounds stay silent (they play through afplay), and /pet card saves the PNG (using python3) without opening it.

What it accesses

A mod runs inside Claude Code with your permissions, so here is everything this one touches:

  • Your sessions: it watches Claude's tool calls and token usage to feed and shape the monster, keeping only counts: file extensions, active hours, commit sizes and test results. Never file paths, code, prompts or messages.
  • Files: it reads and writes ~/.claude/monster/ (pet.json, and card.png when you make a card).
  • Commands: once per session git config --global user.email, of which it keeps only a hash; afplay for sounds (off by default); open, base64 or python3 for the card.
  • Nothing else: no network requests and no model calls.

To see this for yourself before installing, clone the repo and run claude plugin validate .: it lists every event the mod hooks and every call it makes.

Develop

claude --plugin-dir .
claude plugin validate .
claude plugin test .

License

MIT

Source 11 files
hooks/register.tsx 884 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, Timer } from 'claude-code'
3
4import { talkLine } from './lines'
5import {
6  BADGES, DECOR, HATS, ITEMS, LINE_NAMES, PERSONALITIES, QUESTS, RETIRE_AFTER, SKILL_NAMES, canRetire, nextUp, tourTip,
7  age, alerts, applyAll, face, formName, hatch, isAsleep, isSick, level, normalize, spar, xpFor,
8  type Decor, type Event, type Hat, type Item, type Pet, type Skill,
9} from './pet'
10import { MOVES, canFight, move, skillOf, startBattle, type Battle } from './boss'
11import { card, dnaCode, pngBase64, readCode } from './card'
12import { describe, extOf } from './dna'
13import { HAB_H, HAB_W, compose, habitat, sceneSvg, type Scene } from './habitat'
14import type { Sprite } from './art'
15import { FRAME_MS, cells, cropAll, framesSvg, halfAll, petFrames } from './render'
16
17const PANE = 'monster'
18const FLUSH_MS = 5000
19const TABS = ['home', 'items', 'games', 'shop', 'style', 'badges'] as const
20type Tab = (typeof TABS)[number]
21
22const petAtom = atom({ plugin: 'monster', key: 'pet' } as const, null)
23const hiddenAtom = atom({ plugin: 'monster', key: 'isHidden' } as const, false)
24const tabAtom = atom({ plugin: 'monster', key: 'tab' } as const, 'home')
25const huntAtom = atom({ plugin: 'monster', key: 'hunt' } as const, null)
26const battleAtom = atom({ plugin: 'monster', key: 'battle' } as const, null)
27let lastMoveAt = 0
28
29// ── The shared pet lives in one file every session reads and writes; each session queues
30// what happened and folds it in on a short timer.
31let file = ''
32let pending: Event[] = []
33const todoDone = new Map<string, number>()
34
35function bar(n: number, width = 8) {
36  const k = Math.round((Math.max(0, Math.min(100, n)) / 100) * width)
37  return '█'.repeat(k) + '░'.repeat(width - k)
38}
39
40function xpPct(p: Pet) {
41  const lv = level(p.xp)
42  return ((p.xp - xpFor(lv)) / (xpFor(lv + 1) - xpFor(lv))) * 100
43}
44
45async function load($: EngineInterface): Promise<Pet> {
46  try {
47    if (file && (await $.fs.exists(file))) return normalize(JSON.parse(await $.fs.read(file)) as Partial<Pet>)
48  } catch {}
49  const kept = (await $.store.get('pet')) as Partial<Pet> | undefined
50  if (kept) return normalize(kept)
51  const now = await $.clock.now()
52  return hatch(now, 'Byte', PERSONALITIES[Math.floor(Math.random() * PERSONALITIES.length)]!)
53}
54
55async function flush($: EngineInterface) {
56  const events = pending
57  pending = []
58  const now = await $.clock.now()
59  const before = await load($)
60  const raised = alerts(applyAll(before, events, now))
61  const pet = raised.pet
62  try {
63    if (file) await $.fs.write(file, JSON.stringify(pet))
64    else await $.store.set('pet', pet)
65  } catch {}
66  // Announce what this session's events earned.
67  for (const id of pet.badges.filter(b => !before.badges.includes(b))) {
68    const b = BADGES.find(x => x.id === id)
69    if (b) $.ui.toast(`🏅 ${pet.name} earned “${b.name}”${b.hat ? ` · new hat: ${HATS[b.hat]}` : ''}`)
70  }
71  if (pet.stage !== before.stage) $.ui.toast(`✨ ${pet.name} evolved into ${formName(pet)}!`)
72  for (const text of raised.fire) $.ui.toast(`⚠ ${text}`)
73  if (pet.stage !== before.stage) void sound($, pet, 'evolve')
74  else if (pet.badges.length > before.badges.length) void sound($, pet, 'badge')
75  else if (raised.fire.length) void sound($, pet, 'alert')
76  await update($, petAtom, () => pet)
77}
78
79async function sound($: EngineInterface, p: Pet, name: 'evolve' | 'badge' | 'win' | 'alert') {
80  if (!p.settings.sound) return
81  try {
82    await $.audio.play({ asset: `sounds/${name}.wav` }, { gain: 0.5 })
83  } catch {}
84}
85
86// ── The treat hunt, played from the pane's buttons or typed as /pet hunt.
87const BUSHES = ['left', 'middle', 'right'] as const
88
89async function huntStart($: EngineInterface): Promise<string> {
90  const p = await read($, petAtom)
91  const wait = (p?.cooldowns.game ?? 0) - Date.now()
92  if (wait > 0) return `${p?.name ?? 'Your monster'} is resting. Try again in ${since(wait)}.`
93  if (p && p.energy < 10) return `${p.name} is too tired to play. Tuck it in or give it a coffee.`
94  await update($, huntAtom, () => ({ round: 1, score: 0, treat: Math.floor(Math.random() * 3), picked: null }))
95  return `${p?.name ?? 'It'} hid a cookie. Round 1/3: left, middle or right? (/pet hunt <bush>)`
96}
97
98async function huntPick($: EngineInterface, b: number, advance: boolean): Promise<string> {
99  const h = await read($, huntAtom)
100  if (!h) return 'No hunt running. Start one with /pet hunt.'
101  if (h.picked !== null) return advance ? huntNext($) : 'Already picked. Press Next round.'
102  const found = b === h.treat
103  const next = { ...h, picked: b, score: h.score + (found ? 1 : 0) }
104  await update($, huntAtom, () => next)
105  const said = found ? `Found it under the ${BUSHES[b]} bush!` : `Not there… it was under the ${BUSHES[h.treat]} bush.`
106  return advance ? `${said} ${await huntNext($)}` : said
107}
108
109async function huntNext($: EngineInterface): Promise<string> {
110  const h = await read($, huntAtom)
111  if (!h) return ''
112  if (h.round < 3) {
113    await update($, huntAtom, () => ({ round: h.round + 1, score: h.score, treat: Math.floor(Math.random() * 3), picked: null }))
114    return `Round ${h.round + 1}/3: left, middle or right?`
115  }
116  const won = h.score >= 2
117  const prize = won ? PRIZES[Math.floor(Math.random() * PRIZES.length)] : undefined
118  await update($, huntAtom, () => null)
119  await act($, { kind: 'game', won, prize, at: Date.now() })
120  const p = await read($, petAtom)
121  if (won && p) void sound($, p, 'win')
122  return won ? `Won ${h.score}/3! Prize: ${prize ? ITEMS[prize].icon + ' ' + ITEMS[prize].name : 'none'}.` : `Found ${h.score}/3. Better luck next time!`
123}
124
125// ── The weekly Bug Boss, fought from the pane or typed as /pet boss <move>.
126async function bossStart($: EngineInterface): Promise<string> {
127  const p = await load($)
128  const why = canFight(p)
129  if (why || !p.boss) return why ?? 'No boss yet.'
130  const b = startBattle(p, p.boss, Math.random)
131  await update($, battleAtom, () => b)
132  return `${b.log.at(-1)} Your move: /pet boss strike, outsmart or dodge. ${p.name} ${b.petHp} HP · boss ${b.hp} HP.`
133}
134
135async function bossMove($: EngineInterface, skill: Skill): Promise<string> {
136  const b = await read($, battleAtom)
137  const p = await load($)
138  if (!b || b.over) return 'No fight running. Start one with /pet boss.'
139  if (!p.boss) return 'The boss has gone.'
140  const next: Battle = move(b, p, p.boss, skill, Math.random)
141  lastMoveAt = Date.now()
142  await update($, battleAtom, () => next)
143  const turn = next.log.slice(b.log.length > 0 ? -3 : 0).join(' ')
144  if (next.over) {
145    await act($, { kind: 'boss', won: next.over === 'won', at: Date.now() })
146    const q = await read($, petAtom)
147    if (next.over === 'won' && q) void sound($, q, 'win')
148    return `${turn} ${next.over === 'won' ? 'Victory! +3 💎, +30 xp.' : 'Defeated… rest up and try again.'}`
149  }
150  return `${turn} ${p.name} ${next.petHp}/${next.petMax} HP · boss ${next.hp}/${next.maxHp} HP.`
151}
152
153async function buy($: EngineInterface, d: Decor): Promise<string> {
154  const p = await load($)
155  if (p.decor.includes(d)) return `You already have the ${DECOR[d].name.toLowerCase()}.`
156  if (p.items.gem < DECOR[d].cost) return `The ${DECOR[d].name.toLowerCase()} costs ${DECOR[d].cost} 💎; you have ${p.items.gem}.`
157  await act($, { kind: 'buy', decor: d, at: Date.now() })
158  return `Bought the ${DECOR[d].name.toLowerCase()}! It's in the habitat now.`
159}
160
161async function retireNow($: EngineInterface): Promise<string> {
162  const p = await load($)
163  const now = Date.now()
164  if (!canRetire(p, now)) {
165    if (p.stage !== 'ultimate') return `${p.name} can retire after 30 days as an ultimate.`
166    return `${p.name} can retire in ${Math.ceil(((p.ultimateAt ?? now) + RETIRE_AFTER - now) / 86400000)} days.`
167  }
168  await act($, { kind: 'retire', at: now })
169  return `${p.name} retired to the Hall of Fame. A new egg appeared, keeping your badges, hats, items and decorations.`
170}
171
172const WEATHER_ICON = { clear: '☀', cloudy: '☁', rain: '🌧', snow: '❄', petals: '🌸', leaves: '🍂' } as const
173const HOLIDAY_NAME: Record<string, string> = { birthday: '🎂 birthday!', halloween: '🎃 Halloween', christmas: '🎄 Christmas', newyear: '🎆 New Year' }
174
175// ── Friends' visits: a DNA code brings their monster over for a day.
176async function visit($: EngineInterface, arg: string): Promise<string> {
177  const p = await load($)
178  const now = Date.now()
179  const word = arg.trim().toLowerCase()
180  const v = p.visitor && p.visitor.until > now ? p.visitor : null
181  if (!word) {
182    const mine = `Your code: ${dnaCode(p)}. Share it; a friend types /pet visit <code> to have ${p.name} over.`
183    return v ? `${v.name} is visiting (leaves in ${Math.ceil((v.until - now) / 3600000)}h). ${mine}` : mine
184  }
185  if (word === 'play') {
186    if (!v) return 'Nobody is visiting. /pet visit <code> invites a friend’s monster.'
187    if (v.played) return `${p.name} and ${v.name} already played today.`
188    await act($, { kind: 'visit-play', at: now })
189    return `${p.name} and ${v.name} played together! +joy, +5 xp.`
190  }
191  if (word === 'spar') {
192    if (!v) return 'Nobody is visiting. /pet visit <code> invites a friend’s monster.'
193    if (v.sparred) return `${p.name} and ${v.name} already sparred today.`
194    if (p.stage === 'egg') return 'An egg cannot spar yet.'
195    const r = spar(p, v.dna, Math.random)
196    await act($, { kind: 'visit-spar', won: r.won, at: now })
197    return r.won ? `${p.name} won the spar, ${r.ours} to ${r.theirs}! 🍪` : `${v.name} won the spar, ${r.theirs} to ${r.ours}. Good game!`
198  }
199  if (word === 'bye' || word === 'end') {
200    if (!v) return 'Nobody is visiting.'
201    await act($, { kind: 'visit-end', at: now })
202    return `${v.name} went home.`
203  }
204  const parsed = readCode(arg)
205  if (!parsed) return 'That isn’t a DNA code. They look like BYTE-00B43-QW2E-8835; the owner gets theirs from /pet visit or /pet card.'
206  if (parsed.fields.seed === p.seed && p.seed !== null) return `That's ${p.name}'s own code! Share it with a friend instead.`
207  const name = parsed.name.charAt(0) + parsed.name.slice(1).toLowerCase()
208  await act($, { kind: 'visit', code: arg.trim().toUpperCase(), name, dna: parsed.fields, at: now })
209  const kind = parsed.fields.line && parsed.fields.stage !== 'egg' && parsed.fields.stage !== 'baby' ? `${LINE_NAMES[parsed.fields.line]} ${parsed.fields.stage}` : parsed.fields.stage
210  return `${name} the ${kind} came to visit for a day! Play together or spar in /pet.`
211}
212
213/** Draws the card and saves it as a PNG beside the pet's file, then opens it. */
214async function makeCard($: EngineInterface): Promise<string> {
215  const p = await load($)
216  const dir = file ? file.replace(/\/pet\.json$/, '') : ''
217  if (!dir) return `Your card's DNA code: ${dnaCode(p)}`
218  const b64 = `${dir}/card.b64`
219  const png = `${dir}/card.png`
220  await $.fs.write(b64, pngBase64(card(p, Date.now()), 3))
221  const decoders = [
222    ['base64', '-D', '-i', b64, '-o', png],
223    ['python3', '-c', 'import base64,sys;open(sys.argv[2],"wb").write(base64.b64decode(open(sys.argv[1]).read()))', b64, png],
224  ]
225  let saved = false
226  for (const argv of decoders) {
227    try {
228      if ((await $.process.run(argv)).exitCode === 0) {
229        saved = true
230        break
231      }
232    } catch {}
233  }
234  if (!saved) return `Couldn't write the PNG. Your DNA code: ${dnaCode(p)}`
235  queue({ kind: 'card', at: Date.now() })
236  try {
237    await $.process.run(['open', png])
238  } catch {}
239  return `Card saved to ${png} · DNA ${dnaCode(p)}`
240}
241
242/** A number from who you are: a hash of your git email (or your home folder). The email is never stored. */
243async function seed($: EngineInterface, home: string | undefined) {
244  let id = ''
245  try {
246    const r = await $.process.run(['git', 'config', '--global', 'user.email'])
247    if (r.exitCode === 0) id = r.stdout.trim().toLowerCase()
248  } catch {}
249  if (!id) id = home ?? 'monster'
250  let h = 2166136261
251  for (let i = 0; i < id.length; i++) h = Math.imul(h ^ id.charCodeAt(i), 16777619)
252  queue({ kind: 'seed', value: h >>> 0, at: Date.now() })
253}
254
255/** What a typed /pet command did, told plainly. */
256function reply(verb: string, arg: string, before: Pet | null, after: Pet, now: number): string | undefined {
257  const name = after.name
258  switch (verb) {
259    case 'feed':
260      if (before && (before.cooldowns.feed ?? 0) > now) return `${name} is still full. Feed again in ${since((before.cooldowns.feed ?? 0) - now)}, or use a cookie.`
261      return `You fed ${name}. Food ${Math.round(after.hunger)}%.`
262    case 'play':
263      if (before && (before.cooldowns.play ?? 0) > now) return `${name} is tired of playing. Again in ${since((before.cooldowns.play ?? 0) - now)}.`
264      if (before && before.energy < 10) return `${name} is too tired to play.`
265      return `You played with ${name}. Joy ${Math.round(after.joy)}%.`
266    case 'clean':
267      return before && before.mess === 0 ? 'Nothing to clean yet. Messes appear after every third meal.' : `All clean! ${name} is happier.`
268    case 'tuck':
269      return `${name} is tucked in for two hours. Good night!`
270    case 'wake':
271      return before && (before.asleepUntil ?? 0) > now ? `Good morning, ${name}!` : `${name} is already awake.`
272    case 'talk':
273      return after.said ? `“${after.said.text}”` : undefined
274    case 'use': {
275      if (!(arg in ITEMS)) return `Use what? ${Object.keys(ITEMS).join(', ')}.`
276      const item = arg as Item
277      if (before && before.items[item] <= 0) return `No ${ITEMS[item].name.toLowerCase()}s left. ${ITEMS[item].what}`
278      return `${name} had a ${ITEMS[item].name.toLowerCase()} ${ITEMS[item].icon}. ${after.items[item]} left.`
279    }
280    case 'train': {
281      if (!(arg in SKILL_NAMES)) return 'Train what? power, wisdom or speed.'
282      const skill = arg as Skill
283      if (before && (before.cooldowns.train ?? 0) > now) return `${name} is resting. Train again in ${since((before.cooldowns.train ?? 0) - now)}.`
284      if (before && after.skills[skill] === before.skills[skill]) return `${name} is too tired or hungry to train.`
285      return `${name} trained ${SKILL_NAMES[skill]}: now ${after.skills[skill]}.`
286    }
287    case 'hat':
288      if (!arg || arg === 'none') return `${name} took its hat off.`
289      if (!after.hats.includes(arg as Hat)) return `${name} hasn't unlocked that. Unlocked: ${after.hats.length ? after.hats.join(', ') : 'none yet'}.`
290      return `${name} is wearing the ${HATS[arg as Hat].toLowerCase()}.`
291    case 'sound':
292    case 'alerts':
293      return `${verb === 'sound' ? 'Sounds' : 'Alerts'} ${after.settings[verb] ? 'on' : 'off'}.`
294  }
295  return undefined
296}
297
298function queue(e: Event) {
299  pending.push(e)
300  if (pending.length > 500) pending.splice(0, pending.length - 500)
301}
302
303async function act($: EngineInterface, e: Event) {
304  queue(e)
305  await flush($)
306}
307
308function title(p: Pet) {
309  const line = p.line && p.stage === 'child' ? `${LINE_NAMES[p.line]} ` : ''
310  return `${p.name} · Lv ${level(p.xp)} ${line}${formName(p)}`
311}
312
313function said(p: Pet, now: number) {
314  return p.said && now - p.said.at < 60_000 ? p.said.text : undefined
315}
316
317function status(p: Pet, now: number) {
318  const words = said(p, now)
319  if (words && now - p.said!.at < 15_000) return `“${words}”`
320  const last = p.log.at(-1)
321  if (last && now - last.at < 15000) return last.text
322  switch (face(p, now)) {
323    case 'sleep': return (p.asleepUntil ?? 0) > now ? `zzz… tucked in, wakes in ${since(p.asleepUntil! - now)}` : 'zzz… sleeping until you are back'
324    case 'sick': return 'feeling sick from all the errors'
325    case 'hungry': return 'hungry… give Claude some work, or feed it'
326    case 'sleepy': return 'sleepy… a coffee would help'
327    case 'sad': return 'a bit lonely'
328    case 'wave': return 'waves at the new agent 👋'
329    case 'sweat': return 'working hard…'
330    case 'cheer': return '♪'
331    case 'ouch': return 'ouch!'
332    case 'eat': return 'nom nom'
333    default:
334      if (p.mess >= 2) return 'it’s getting messy in here'
335      return `${age(p, now)} old · ${p.streak.days > 1 ? `🔥 ${p.streak.days}-day streak · ` : ''}${Math.round(p.stats.tokens / 1000)}k tokens eaten`
336  }
337}
338
339function since(ms: number) {
340  const m = Math.ceil(ms / 60_000)
341  return m >= 60 ? `${Math.ceil(m / 60)}h` : `${m}m`
342}
343
344const HELP = [
345  'Your monster grows from Claude’s work in every session. /pet opens its habitat.',
346  'Care:    /pet feed · play · talk · clean · tuck · wake · use <cookie|coffee|gem|bug>',
347  'Play:    /pet hunt [left|middle|right] · boss [strike|outsmart|dodge] · train <power|wisdom|speed>',
348  'Collect: /pet buy <decoration> · hat <hat|none> · retire (after 30 days as an ultimate)',
349  'Share:   /pet card (a PNG with its DNA code) · visit [<code>|play|spar|bye]',
350  'Setup:   /pet name <name> · sound on|off · alerts on|off · hide|show · close · tour [skip]',
351].join('\n')
352
353// ── The terminal shows the habitat without most of its sky, and no wider than the pane.
354type View = { x: number; y: number; w: number; h: number }
355
356function viewOf(columns: number): View {
357  const w = Math.min(HAB_W, Math.max(40, columns - 2))
358  return { x: Math.floor((HAB_W - w) / 2), y: 12, w, h: HAB_H - 12 }
359}
360
361function crop(s: Sprite, v: View): Sprite {
362  const px: (number | null)[] = []
363  for (let y = v.y; y < v.y + v.h; y++) for (let x = v.x; x < v.x + v.w; x++) px.push(s.px[y * s.w + x] ?? null)
364  return { w: v.w, h: v.h, px }
365}
366
367const PRIZES: Item[] = ['cookie', 'cookie', 'cookie', 'coffee', 'coffee', 'gem']
368
369async function petCommand($: EngineInterface, args: string): Promise<{ text: string }> {
370  const [verb = '', ...rest] = args.trim().split(/\s+/)
371  const arg = rest.join(' ').toLowerCase()
372  const now = await $.clock.now()
373  const before = await load($)
374  if (verb === 'boss') {
375    if (!arg) return { text: await bossStart($) }
376    const skill = skillOf(arg)
377    return { text: skill ? await bossMove($, skill) : 'Use strike, outsmart or dodge.' }
378  }
379  if (verb === 'buy') {
380    const d = (Object.keys(DECOR) as Decor[]).find(k => k === arg || DECOR[k].name.toLowerCase().startsWith(arg))
381    return { text: d ? await buy($, d) : `Buy what? ${(Object.keys(DECOR) as Decor[]).map(k => `${k} (${DECOR[k].cost}💎)`).join(', ')}` }
382  }
383  if (verb === 'retire') return { text: await retireNow($) }
384  if (verb === 'card') return { text: await makeCard($) }
385  if (verb === 'help') return { text: HELP }
386  if (verb === 'close') {
387    await $.ui.close({ id: PANE })
388    return { text: 'Habitat closed. /pet opens it again.' }
389  }
390  if (verb === 'visit') return { text: await visit($, rest.join(' ')) }
391  if (verb === 'tour') {
392    await act($, { kind: 'tour', action: arg === 'skip' ? 'skip' : 'restart', at: Date.now() })
393    return { text: arg === 'skip' ? 'Tour skipped. /pet tour brings it back.' : 'Tour restarted: tips will show above your prompt.' }
394  }
395  if (verb === 'hunt') {
396    const b = BUSHES.indexOf(arg as (typeof BUSHES)[number])
397    const text = !arg ? await huntStart($) : b < 0 ? 'Pick left, middle or right.' : await huntPick($, b, true)
398    return { text }
399  }
400  switch (verb) {
401    case 'feed': queue({ kind: 'feed', at: now }); break
402    case 'play': queue({ kind: 'play', at: now }); break
403    case 'clean': queue({ kind: 'clean', at: now }); break
404    case 'tuck': queue({ kind: 'tuck', at: now }); break
405    case 'wake': queue({ kind: 'wake', at: now }); break
406    case 'talk': if (before) queue({ kind: 'talk', text: talkLine(before, now), at: now }); break
407    case 'use': if (arg in ITEMS) queue({ kind: 'use', item: arg as Item, at: now }); break
408    case 'train': if (arg in SKILL_NAMES) queue({ kind: 'train', skill: arg as Skill, at: now }); break
409    case 'hat': queue({ kind: 'equip', hat: arg === 'none' || !arg ? null : (arg as Hat), at: now }); break
410    case 'name': if (arg) queue({ kind: 'rename', name: rest.join(' ').slice(0, 24), at: now }); break
411    case 'sound':
412    case 'alerts': queue({ kind: 'setting', key: verb, on: arg !== 'off', at: now }); break
413    case 'hide':
414    case 'show': await update($, hiddenAtom, () => verb === 'hide'); break
415  }
416  await flush($)
417  const p = await read($, petAtom)
418  if (!verb) await $.ui.open({ id: PANE, title: p ? p.name : 'Monster', rows: 24 })
419  if (!p) return { text: 'Your monster is on its way.' }
420  return { text: `${title(p)} — ${reply(verb, arg, before, p, now) ?? status(p, now)}` }
421}
422
423export const register: Register = on => {
424  let ticker: Timer | undefined
425  let animator: Timer | undefined
426  let frame = 0
427  let bandFrames: string[] = []
428  let paneScene: Scene | null = null
429  let paneView = viewOf(80)
430  const started = Date.now()
431  let bandId = ''
432
433  on('session.start', async ($, e, next) => {
434    const home = await $.env.get('HOME')
435    file = home ? `${home}/.claude/monster/pet.json` : ''
436    await $.command.register({
437      name: 'pet',
438      description: 'See and care for your monster',
439      argumentHint: '[help|card|visit <code>|feed|play|talk|clean|tuck|wake|hunt [bush]|boss [move]|buy <decor>|retire|use <item>|train <skill>|hat <hat>|name <name>|sound on|off|alerts on|off|hide|show|close]',
440    })
441    void seed($, home)
442    ticker?.cancel()
443    ticker = $.clock.every(FLUSH_MS, () => void flush($))
444    // Animate the terminal drawings: swap their frames in place.
445    animator?.cancel()
446    animator = $.clock.every(FRAME_MS, () => {
447      frame++
448      const b = bandFrames[frame % Math.max(1, bandFrames.length)]
449      if (b && bandId) void $.ui.blit({ requestId: bandId, key: 'pet', cells: b })
450      if (paneScene) void $.ui.blit({ requestId: PANE, key: 'habitat', cells: cells(crop(compose(paneScene, Date.now() - started), paneView)).cells })
451    })
452    void flush($)
453    return next(e)
454  })
455
456  on('command.run', { command: 'pet' }, async ($, e) => {
457    try {
458      return await petCommand($, e.args)
459    } catch (err) {
460      return { text: `Something went wrong with /pet ${e.args.trim()}: ${err instanceof Error ? err.message : String(err)}`.slice(0, 300) }
461    }
462  })
463
464  // ── What it eats and learns from.
465  on('turn.step', async function* ($, e, next) {
466    const r = yield* next(e)
467    const u = r.usage
468    if (u) queue({ kind: 'tokens', n: u.input_tokens + u.output_tokens + u.cache_creation_input_tokens, at: Date.now() })
469    return r
470  })
471
472  on('agent.spawn', async ($, e, next) => {
473    const r = await next(e)
474    if (r.agentId) queue({ kind: 'agent', at: Date.now() })
475    return r
476  }).catch(($, e, next) => next(e))
477
478  on('tool.call', async ($, e, next) => {
479    const started = Date.now()
480    let r: Awaited<ReturnType<typeof next>> | undefined
481    try {
482      r = await next(e)
483      return r
484    } finally {
485      const input = e as unknown as Record<string, unknown>
486      const tool = String(e.tool)
487      const failed = !r || r.isError === true || r.deny !== undefined
488      const command = typeof input.command === 'string' ? input.command : undefined
489      const path = typeof input.file_path === 'string' ? input.file_path : typeof input.notebook_path === 'string' ? input.notebook_path : ''
490      queue({ kind: 'tool', tool, command, failed, ms: Date.now() - started, ext: extOf(path), at: Date.now() })
491      if (tool === 'TodoWrite' && r && 'result' in r) {
492        const todos = ((r.result ?? {}) as { newTodos?: { status: string }[] }).newTodos ?? []
493        const done = todos.filter(t => t.status === 'completed').length
494        const key = e.agentId ?? 'main'
495        const before = todoDone.get(key) ?? 0
496        if (done > before) queue({ kind: 'task', n: done - before, at: Date.now() })
497        todoDone.set(key, done)
498      }
499      if (tool === 'TaskUpdate' && !failed && input.status === 'completed') queue({ kind: 'task', n: 1, at: Date.now() })
500    }
501  }).catch(($, e, next) => next(e))
502
503  // ── The band above the prompt.
504  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
505    const p = await read($, petAtom)
506    if (e.props.hasSurvey || !p || (await read($, hiddenAtom))) {
507      bandFrames = []
508      return next(e)
509    }
510    const now = await $.clock.now()
511    const frames = cropAll(petFrames(p, now))
512    const { Box, Button, Text } = $.ui.resolve(e)
513    const info = (
514      <Box flexDirection="column">
515        <Text color="#FFCD75" bold>{title(p)}{p.streak.days > 1 ? ` · 🔥${p.streak.days}` : ''}</Text>
516        <Text>
517          <Text color="#EF7D57">food {bar(p.hunger, 6)}</Text> <Text color="#A7F070">joy {bar(p.joy, 6)}</Text>{' '}
518          <Text color="#FFCD75">nrg {bar(p.energy, 5)}</Text> <Text color="#73EFF7">xp {bar(xpPct(p), 6)}</Text>
519          {isSick(p) && <Text color="#E24B4A"> sick</Text>}
520        </Text>
521        <Box flexDirection="row" gap={1}>
522          <Button key="band-pat" label="♥" plain onPress={() => act($, { kind: 'pet', at: Date.now() })} />
523          <Button key="band-talk" label="💬" plain onPress={async () => {
524            const q = await read($, petAtom)
525            if (q) await act($, { kind: 'talk', text: talkLine(q, Date.now()), at: Date.now() })
526          }} />
527          {tourTip(p) ? (
528            <>
529              <Text color="#73EFF7">{tourTip(p)}</Text>
530              <Button key="band-skip" label="Skip tour" plain onPress={() => act($, { kind: 'tour', action: 'skip', at: Date.now() })} />
531            </>
532          ) : (
533            <Text dimColor>{status(p, now)}</Text>
534          )}
535        </Box>
536      </Box>
537    )
538    if (e.surface === 'terminal') {
539      const { Raster } = $.ui.resolve(e)
540      // Half size in the terminal, so the band stays a few rows tall.
541      const small = cropAll(halfAll(frames))
542      bandFrames = small.map(f => cells(f).cells)
543      bandId = e.requestId
544      const first = cells(small[0]!)
545      return (
546        <Box flexDirection="row" gap={1}>
547          <Raster key="pet" columns={first.columns} rows={first.rows} cells={first.cells} />
548          {info}
549        </Box>
550      )
551    }
552    if (e.surface === 'desktop') {
553      const { Svg } = $.ui.resolve(e)
554      return (
555        <Box flexDirection="row" gap={2} alignItems="center">
556          <Svg source={framesSvg(frames, 3)} alt={`${p.name}, your monster`} />
557          {info}
558        </Box>
559      )
560    }
561    return <Box>{info}</Box>
562  })
563
564  // ── The /pet pane.
565  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
566    const p = await read($, petAtom)
567    const { Box, Button, Text } = $.ui.resolve(e)
568    if (!p) return <Text dimColor>Your monster is on its way…</Text>
569    const now = await $.clock.now()
570    const tab = (await read($, tabAtom)) as Tab
571    // Note what has been opened, for the tour (folded in on the next flush).
572    for (const what of ['pane', tab] as const) {
573      if (what !== 'home' && !p.seen.includes(what) && !pending.some(ev => ev.kind === 'seen' && ev.what === what)) queue({ kind: 'seen', what, at: now })
574    }
575    const hunt = await read($, huntAtom)
576    let preview: RenderElement | null = null
577    if (e.surface === 'desktop' && tab === 'style') {
578      const { Svg } = $.ui.resolve(e)
579      preview = <Svg source={framesSvg([card(p, now)], 2)} alt={`${p.name}'s card`} />
580    }
581    const battle = await read($, battleAtom)
582    const fighting = battle && p.boss && tab === 'games' ? { kind: p.boss.kind, hit: !battle.over && now - lastMoveAt < 1200 } : null
583    const scene = habitat(p, now, new Date(now).getHours(), { hunt: tab === 'games' && !battle ? hunt : null, boss: fighting })
584    const lv = level(p.xp)
585
586    const compact = e.surface === 'terminal'
587    const header = compact ? (
588      <Box flexDirection="column">
589        <Text color="#FFCD75" bold>
590          {title(p)} · {p.personality}{p.streak.days > 1 ? ` · 🔥${p.streak.days}` : ''}{isAsleep(p, now) ? ' · asleep' : ''}{isSick(p) ? ' · sick' : ''} <Text dimColor>{WEATHER_ICON[scene.weather]} {scene.season}{scene.holiday ? ` · ${HOLIDAY_NAME[scene.holiday]}` : ''}</Text>
591        </Text>
592        <Text>
593          <Text color="#EF7D57">food {bar(p.hunger, 6)}</Text> <Text color="#A7F070">joy {bar(p.joy, 6)}</Text> <Text color="#FFCD75">nrg {bar(p.energy, 6)}</Text> <Text color="#E24B4A">stress {bar(p.stress, 6)}</Text> <Text color="#73EFF7">xp {Math.floor(p.xp)}/{xpFor(lv + 1)}</Text>
594        </Text>
595        <Text color="#73EFF7">{said(p, now) ? `💬 “${said(p, now)}”` : `▸ Next up: ${nextUp(p, now)}`}</Text>
596      </Box>
597    ) : (
598      <Box flexDirection="column">
599        <Text color="#FFCD75" bold>
600          {title(p)} · {p.personality} · {age(p, now)} old{p.streak.days > 1 ? ` · 🔥 ${p.streak.days}-day streak` : ''}
601          {isAsleep(p, now) ? ' · asleep' : ''}{isSick(p) ? ' · sick' : ''}
602        </Text>
603        <Text>
604          <Text color="#EF7D57">food {bar(p.hunger, 10)}</Text>  <Text color="#A7F070">joy {bar(p.joy, 10)}</Text>  <Text color="#FFCD75">energy {bar(p.energy, 10)}</Text>  <Text color="#E24B4A">stress {bar(p.stress, 10)}</Text>
605        </Text>
606        <Text color="#73EFF7">xp {bar(xpPct(p), 20)} {Math.floor(p.xp)}/{xpFor(lv + 1)} → Lv {lv + 1}</Text>
607        <Text dimColor>
608          {WEATHER_ICON[scene.weather]} {scene.season} · {scene.weather}{scene.holiday ? ` · ${HOLIDAY_NAME[scene.holiday]}` : ''}{p.generation > 1 ? ` · generation ${p.generation}` : ''}
609        </Text>
610        {said(p, now) && <Text color="#F4F4F4">💬 “{said(p, now)}”</Text>}
611        <Text color="#73EFF7">▸ Next up: {nextUp(p, now)}</Text>
612      </Box>
613    )
614
615    const tabs = (
616      <Box flexDirection="row" gap={1}>
617        {TABS.map(t => (
618          <Button
619            key={`tab-${t}`}
620            label={t === 'items' ? `Items ${Object.values(p.items).reduce((a, b) => a + b, 0)}` : t === 'shop' ? `Shop 💎${p.items.gem}` : t === 'badges' ? `Badges ${p.badges.length}/${BADGES.length}` : t[0]!.toUpperCase() + t.slice(1)}
621            variant={t === tab ? 'primary' : 'secondary'}
622            onPress={() => update($, tabAtom, () => t)}
623          />
624        ))}
625      </Box>
626    )
627
628    const body = await (async () => {
629      if (tab === 'items') {
630        return (
631          <Box flexDirection="column">
632            {(Object.keys(ITEMS) as Item[]).map(item => (
633              <Box key={`it-${item}`} flexDirection="row" gap={1}>
634                <Button key={`use-${item}`} label={p.items[item] > 0 ? `Use ${ITEMS[item].name}` : `${ITEMS[item].name}: none`} onPress={() => act($, { kind: 'use', item, at: Date.now() })} />
635                <Text>
636                  {ITEMS[item].icon} ×{p.items[item]}  <Text dimColor>{ITEMS[item].what}</Text>
637                </Text>
638              </Box>
639            ))}
640          </Box>
641        )
642      }
643      if (tab === 'games') {
644        const wait = (p.cooldowns.game ?? 0) - now
645        const huntRow = !hunt ? (
646          <Box flexDirection="row" gap={1}>
647            <Button
648              key="hunt-start"
649              label={wait > 0 ? `Treat hunt (rest ${since(wait)})` : 'Start treat hunt'}
650              hotkey="t"
651              onPress={async () => {
652                await huntStart($)
653              }}
654            />
655            <Text dimColor>{p.name} hides a cookie in one of three bushes. Find it in 2 of 3 rounds to win a prize.</Text>
656          </Box>
657        ) : hunt.picked === null ? (
658          <Box flexDirection="row" gap={1}>
659            <Text>Round {hunt.round}/3 · found {hunt.score} · which bush?</Text>
660            {(['Left', 'Middle', 'Right'] as const).map((label, b) => (
661              <Button key={`bush-${b}`} label={label} hotkey={String(b + 1)} onPress={async () => { await huntPick($, b, false) }} />
662            ))}
663          </Box>
664        ) : (
665          <Box flexDirection="row" gap={1}>
666            <Text color={hunt.picked === hunt.treat ? '#A7F070' : '#EF7D57'}>
667              {hunt.picked === hunt.treat ? 'Found it!' : 'Not there…'} Round {hunt.round}/3 · found {hunt.score}
668            </Text>
669            <Button
670              key="hunt-next"
671              label={hunt.round < 3 ? 'Next round' : 'Finish'}
672              variant="primary"
673              hotkey="n"
674              onPress={async () => {
675                await huntNext($)
676              }}
677            />
678          </Box>
679        )
680        const trainWait = (p.cooldowns.train ?? 0) - now
681        const hpBar = (n: number, max: number) => bar((n / Math.max(1, max)) * 100, 12)
682        const bossRow = !p.boss ? (
683          <Text dimColor>No Bug Boss yet. One forms at the start of each week from the last week’s failures.</Text>
684        ) : battle ? (
685          <Box flexDirection="column">
686            <Text>
687              <Text color="#A7F070">{p.name} {hpBar(battle.petHp, battle.petMax)} {battle.petHp}</Text>  vs  <Text color="#E24B4A">{p.boss.name} {hpBar(battle.hp, battle.maxHp)} {battle.hp}</Text>
688            </Text>
689            {battle.log.slice(-3).map((l, i) => (
690              <Text key={`bl-${i}`} color="#94B0C2">· {l}</Text>
691            ))}
692            {battle.over ? (
693              <Button key="boss-done" label={battle.over === 'won' ? 'Victory! Done' : 'Retreat'} variant="primary" onPress={() => update($, battleAtom, () => null)} />
694            ) : (
695              <Box flexDirection="row" gap={1}>
696                {(['power', 'wisdom', 'speed'] as const).map((sk, i) => (
697                  <Button key={`mv-${sk}`} label={`${MOVES[sk].name} (${SKILL_NAMES[sk]} ${p.skills[sk]})`} hotkey={String(i + 1)} variant={battle.weak === sk ? 'primary' : 'secondary'} onPress={async () => { await bossMove($, sk) }} />
698                ))}
699              </Box>
700            )}
701          </Box>
702        ) : (
703          <Box flexDirection="row" gap={1}>
704            <Button key="boss-fight" label={p.boss.beaten ? `${p.boss.name}: beaten ✓` : `Fight the ${p.boss.name}`} hotkey="b" onPress={async () => { await bossStart($) }} />
705            <Text dimColor>
706              {p.boss.beaten ? 'A new boss forms next week.' : (canFight(p) ?? `${p.boss.hp} HP · attack ${p.boss.atk} · built from last week’s failures · ${p.boss.tries} tries`)}
707            </Text>
708          </Box>
709        )
710        return (
711          <Box flexDirection="column" gap={1}>
712            <Text color="#FFCD75" bold>Weekly Bug Boss</Text>
713            {bossRow}
714            <Text color="#FFCD75" bold>Treat hunt</Text>
715            {huntRow}
716            <Text color="#FFCD75" bold>Training</Text>
717            <Box flexDirection="row" gap={1}>
718              {(Object.keys(SKILL_NAMES) as Skill[]).map(skill => (
719                <Button key={`train-${skill}`} label={`Train ${SKILL_NAMES[skill]} (${p.skills[skill]})`} onPress={() => act($, { kind: 'train', skill, at: Date.now() })} />
720              ))}
721              <Text dimColor>{trainWait > 0 ? `resting ${since(trainWait)}` : 'costs food and energy'}{p.line ? ` · ${LINE_NAMES[p.line]}s learn ${p.line === 'forge' ? 'Power' : p.line === 'scribe' ? 'Wisdom' : p.line === 'wanderer' ? 'Speed' : 'everything'} faster` : ''}</Text>
722            </Box>
723            <Text dimColor>Treat hunts: {p.stats.wins} won of {p.stats.games} · trained {p.stats.trained} times</Text>
724          </Box>
725        )
726      }
727      if (tab === 'shop') {
728        return (
729          <Box flexDirection="column">
730            <Text dimColor>Spend 💎 gems (from commits, pushes, streaks and Bug Bosses) on things for the habitat. You have {p.items.gem}.</Text>
731            {(Object.keys(DECOR) as Decor[]).map(d => (
732              <Box key={`shop-${d}`} flexDirection="row" gap={1}>
733                <Button
734                  key={`buy-${d}`}
735                  label={p.decor.includes(d) ? `${DECOR[d].name} ✓` : `Buy ${DECOR[d].name} · ${DECOR[d].cost}💎`}
736                  variant={p.decor.includes(d) ? 'secondary' : p.items.gem >= DECOR[d].cost ? 'primary' : 'secondary'}
737                  onPress={async () => { await buy($, d) }}
738                />
739              </Box>
740            ))}
741          </Box>
742        )
743      }
744      if (tab === 'style') {
745        return (
746          <Box flexDirection="column" gap={1}>
747            <Box flexDirection="column">
748              <Text color="#FFCD75" bold>DNA{p.shiny ? ' ✦ shiny' : ''}</Text>
749              {describe(p).map((line, i) => (
750                <Text key={`dna-${i}`}>{line}</Text>
751              ))}
752              <Text dimColor>Only counts are kept: languages by file extension, active hours, commit sizes, test results, and a hash of your git email. No paths, code or messages.</Text>
753            </Box>
754            <Box flexDirection="column">
755              <Text color="#FFCD75" bold>Card</Text>
756              {preview}
757              <Box flexDirection="row" gap={1}>
758                <Button key="card" label="Save card as PNG" hotkey="k" onPress={async () => { $.ui.toast(await makeCard($)) }} />
759                <Text dimColor>DNA {dnaCode(p)}</Text>
760              </Box>
761            </Box>
762            <Text color="#FFCD75" bold>Hats</Text>
763            <Box flexDirection="row" gap={1} flexWrap="wrap">
764              <Button key="hat-none" label="No hat" variant={p.hat === null ? 'primary' : 'secondary'} onPress={() => act($, { kind: 'equip', hat: null, at: Date.now() })} />
765              {p.hats.map(hat => (
766                <Button key={`hat-${hat}`} label={HATS[hat]} variant={p.hat === hat ? 'primary' : 'secondary'} onPress={() => act($, { kind: 'equip', hat, at: Date.now() })} />
767              ))}
768            </Box>
769            {(Object.keys(HATS) as Hat[])
770              .filter(hat => !p.hats.includes(hat))
771              .map(hat => {
772                const b = BADGES.find(x => x.hat === hat)
773                return <Text key={`locked-${hat}`} dimColor>🔒 {HATS[hat]}: {b ? b.what.toLowerCase() : 'secret'}</Text>
774              })}
775          </Box>
776        )
777      }
778      if (tab === 'badges') {
779        const retireIn = p.stage === 'ultimate' && p.ultimateAt ? Math.ceil((p.ultimateAt + RETIRE_AFTER - now) / 86400000) : null
780        return (
781          <Box flexDirection="column">
782            <Text color="#FFCD75" bold>Hall of Fame{p.hall.length ? '' : ': empty'}</Text>
783            {p.hall.map((l, i) => (
784              <Text key={`hof-${i}`} color="#FFCD75">👑 Gen {l.generation}: {l.name} the {l.form} · Lv {l.level} · {l.days} days</Text>
785            ))}
786            {canRetire(p, now) ? (
787              <Button key="retire" label={`Retire ${p.name} to the Hall of Fame`} onPress={async () => { await retireNow($) }} />
788            ) : (
789              <Text dimColor>{retireIn !== null ? `${p.name} can retire in ${retireIn} days.` : 'An ultimate can retire after 30 days; the next egg keeps your treasures and a head start.'}</Text>
790            )}
791            <Text color="#FFCD75" bold>Badges</Text>
792            {BADGES.map(b => (
793              <Text key={`b-${b.id}`} color={p.badges.includes(b.id) ? '#FFCD75' : undefined} dimColor={!p.badges.includes(b.id)}>
794                {p.badges.includes(b.id) ? '🏅' : '○ '} {b.name}: {b.what}{b.hat ? ` (unlocks ${HATS[b.hat].toLowerCase()})` : ''}
795              </Text>
796            ))}
797          </Box>
798        )
799      }
800      // Home.
801      const tucked = (p.asleepUntil ?? 0) > now
802      return (
803        <Box flexDirection="column" gap={1}>
804          <Box flexDirection="row" gap={1} flexWrap="wrap">
805            <Button key="feed" label={(p.cooldowns.feed ?? 0) > now ? 'Feed (full)' : 'Feed'} hotkey="f" onPress={() => act($, { kind: 'feed', at: Date.now() })} />
806            <Button key="play" label={(p.cooldowns.play ?? 0) > now ? 'Play (tired)' : 'Play'} hotkey="p" onPress={() => act($, { kind: 'play', at: Date.now() })} />
807            <Button key="pat" label="Pat ♥" hotkey="h" onPress={() => act($, { kind: 'pet', at: Date.now() })} />
808            <Button key="talk" label="Talk" hotkey="t" onPress={async () => {
809              const q = await read($, petAtom)
810              if (q) await act($, { kind: 'talk', text: talkLine(q, Date.now()), at: Date.now() })
811            }} />
812            {p.mess > 0 && <Button key="clean" label={`Clean (${p.mess})`} hotkey="c" onPress={() => act($, { kind: 'clean', at: Date.now() })} />}
813            <Button key="tuck" label={tucked ? 'Wake up' : 'Tuck in'} hotkey="z" onPress={() => act($, { kind: tucked ? 'wake' : 'tuck', at: Date.now() })} />
814            <Button key="band" label={(await read($, hiddenAtom)) ? 'Show band' : 'Hide band'} onPress={() => update($, hiddenAtom, hidden => !hidden)} />
815            <Button key="sound" label={p.settings.sound ? 'Sound: on' : 'Sound: off'} onPress={() => act($, { kind: 'setting', key: 'sound', on: !p.settings.sound, at: Date.now() })} />
816            <Button key="alerts" label={p.settings.alerts ? 'Alerts: on' : 'Alerts: off'} onPress={() => act($, { kind: 'setting', key: 'alerts', on: !p.settings.alerts, at: Date.now() })} />
817          </Box>
818          {p.visitor && p.visitor.until > now && (
819            <Box flexDirection="row" gap={1}>
820              <Text color="#FFCD75">👋 {p.visitor.name} is visiting · leaves in {Math.ceil((p.visitor.until - now) / 3600000)}h</Text>
821              <Button key="visit-play" label={p.visitor.played ? 'Played ✓' : 'Play together'} onPress={async () => { $.ui.toast(await visit($, 'play')) }} />
822              <Button key="visit-spar" label={p.visitor.sparred ? 'Sparred ✓' : 'Spar'} onPress={async () => { $.ui.toast(await visit($, 'spar')) }} />
823              <Button key="visit-bye" label="Say goodbye" onPress={async () => { $.ui.toast(await visit($, 'bye')) }} />
824            </Box>
825          )}
826          <Text dimColor>
827            Quests {p.quests.length}/{QUESTS.length}: {QUESTS.map(q => `${p.quests.includes(q.id) ? '✓' : '○'} ${q.what}`).join(' · ')}
828          </Text>
829          <Box flexDirection="column">
830            {p.log.slice(compact ? -3 : -5).reverse().map((l, i) => (
831              <Text key={`log-${i}`} color="#94B0C2">· {l.text}</Text>
832            ))}
833          </Box>
834        </Box>
835      )
836    })()
837
838    if (e.surface === 'terminal') {
839      const { Raster } = $.ui.resolve(e)
840      paneScene = scene
841      paneView = viewOf(e.props.bodyColumns || e.viewport?.columns || 80)
842      const first = cells(crop(compose(scene, Date.now() - started), paneView))
843      return (
844        <Box flexDirection="column">
845          <Raster key="habitat" columns={first.columns} rows={first.rows} cells={first.cells} />
846          {header}
847          {tabs}
848          {body}
849        </Box>
850      )
851    }
852    if (e.surface === 'desktop') {
853      const { Svg } = $.ui.resolve(e)
854      return (
855        <Box flexDirection="column" gap={1}>
856          <Svg source={sceneSvg(scene, 7)} alt={`${p.name} in its habitat`} />
857          {header}
858          {tabs}
859          {body}
860        </Box>
861      )
862    }
863    return (
864      <Box flexDirection="column" gap={1}>
865        {header}
866        {tabs}
867        {body}
868      </Box>
869    )
870  })
871
872  on('ui.close', { id: PANE }, ($, e, next) => {
873    paneScene = null
874    return next(e)
875  }).catch(($, e, next) => next(e))
876
877  on('session.end', async ($, e, next) => {
878    ticker?.cancel()
879    animator?.cancel()
880    await flush($)
881    return next(e)
882  }).catch(($, e, next) => next(e))
883}
884
hooks/lines.ts 90 lines
1// What the monster says when you talk to it: picked from its needs, the hour, recent work,
2// its line and its personality. Offline and canned: no model calls.
3
4import { FORM_NAMES, ITEMS, LINE_NAMES, isAsleep, isSick, level, xpFor, type Item, type Pet } from './pet'
5
6type Pool = string[]
7
8const NEEDS = {
9  hungry: ['My tummy is rumbling… got any tokens?', 'Food? Food. Food!', 'I could eat a whole diff right now.', 'Feed me and I’ll debug anything.'],
10  sleepy: ['*yawn* Can we take a nap?', 'My eyes keep closing…', 'A coffee would really help right now.', 'Five more minutes…'],
11  sick: ['I don’t feel so good… too many red errors.', 'Can we try green tests for a while?', 'My head is full of stack traces.'],
12  messy: ['Um… it’s a bit messy in here.', 'Could you clean up? I stepped in something.', 'The habitat needs a tidy-up!'],
13  sad: ['I missed you.', 'It’s been quiet. Want to play?', 'Pat me? Just once?'],
14}
15
16const HOURS: [number, number, Pool][] = [
17  [5, 11, ['Good morning! Fresh day, fresh bugs.', 'Morning! What are we building today?', 'Coffee first, then commits.']],
18  [11, 17, ['Afternoon push! You’ve got this.', 'Halfway through the day already?', 'Lunch break for me too?']],
19  [17, 22, ['Evening coding is the best coding.', 'The sky is so orange right now.', 'One more feature, then rest?']],
20  [22, 29, ['It’s late… don’t forget to sleep.', 'The stars are out. So are the bugs.', 'Night owl mode activated.']],
21]
22
23const CHEERS: Pool = [
24  'I believe in you!', 'Every bug you fix makes me stronger.', 'Let’s ship something great today.',
25  'You type so fast!', 'I like it when the tests turn green.', 'We make a good team.',
26]
27
28const QUIPS: Pool = [
29  'Did you know? Rubber ducks are great listeners. So am I.', 'It works on my machine. I live on your machine!',
30  'A commit a day keeps the merge conflicts away.', 'Naming things is hard. You named me well, though.',
31  'I dreamt about semicolons.', 'Have you tried turning it off and on again?', 'Small PRs are tasty PRs.',
32  'Off-by-one errors are my natural enemy.', 'I read the logs so you don’t have to. Mostly.',
33  'Today’s forecast: 100% chance of refactoring.', 'Caches are just memories with an expiry date.',
34]
35
36const LINE_TALK: Record<string, Pool> = {
37  forge: ['Let’s run something loud in the shell!', 'I love the smell of a fresh build.', 'Pipes! Greps! Fire!'],
38  scribe: ['I read every line you edit.', 'Good code reads like a story.', 'Let me float over that file with you.'],
39  summoner: ['More agents! More friends!', 'I can hear the subagents humming.', 'Delegate, delegate, delegate.'],
40  wanderer: ['What’s out there on the web today?', 'I flew past three docs pages this morning.', 'Let’s go look something up!'],
41}
42
43const FLAVOR: Record<Pet['personality'], (s: string) => string> = {
44  cheerful: s => (s.endsWith('!') || s.endsWith('?') ? s : s.replace(/\.$/, '') + '!'),
45  lazy: s => `*yawn* ${s.charAt(0).toLowerCase()}${s.slice(1)}`,
46  curious: s => (s.endsWith('?') ? s : `${s} …what are you working on?`),
47  grumpy: s => `Hmph. ${s}`,
48}
49
50function pick<T>(pool: readonly T[], rnd: () => number): T {
51  return pool[Math.floor(rnd() * pool.length) % pool.length]!
52}
53
54export function talkLine(p: Pet, now: number, rnd: () => number = Math.random): string {
55  if (p.stage === 'egg') return pick(['*wobble*', '*tap tap*', '…(something stirs inside)', '*the egg feels warm*'], rnd)
56  if (isAsleep(p, now) && (p.asleepUntil ?? 0) > now) return pick(['Zzz…', '*snore*', 'mmh… five more minutes…'], rnd)
57  if (isSick(p)) return pick(NEEDS.sick, rnd)
58  if (p.hunger < 25) return FLAVOR[p.personality](pick(NEEDS.hungry, rnd))
59  if (p.energy < 20) return pick(NEEDS.sleepy, rnd)
60  if (p.mess >= 2) return pick(NEEDS.messy, rnd)
61  if (p.joy < 30) return pick(NEEDS.sad, rnd)
62
63  const options: string[] = []
64  const hour = new Date(now).getHours()
65  const h = hour < 5 ? hour + 24 : hour
66  for (const [from, to, pool] of HOURS) if (h >= from && h < to) options.push(pick(pool, rnd))
67  if (p.streak.days >= 2) options.push(`Day ${p.streak.days} in a row together!`)
68  if (p.visitor && p.visitor.until > now) {
69    const v = p.visitor
70    options.push(`I like ${v.name}!${v.dna.lang1 ? ` They smell like ${v.dna.lang1}.` : ''}`, `Can ${v.name} stay a bit longer?`, `${v.name} and I are racing to the fountain!`)
71  }
72  const lv = level(p.xp)
73  const toNext = Math.ceil(xpFor(lv + 1) - p.xp)
74  if (toNext <= 15) options.push(`Only ${toNext} xp until level ${lv + 1}!`)
75  if (p.line) options.push(pick(LINE_TALK[p.line]!, rnd))
76  if (p.stage === 'child' && p.line) {
77    const v = p.care.n && p.care.sum / p.care.n >= 55 ? 'bright' : 'shadow'
78    options.push(`When I grow up I want to be ${FORM_NAMES[p.line][v][0]}!`)
79  }
80  const stash = (Object.keys(p.items) as Item[]).filter(i => p.items[i] > 0)
81  if (stash.length) {
82    const i = pick(stash, rnd)
83    options.push(`We have ${p.items[i]} ${ITEMS[i].name.toLowerCase()}${p.items[i] === 1 ? '' : 's'} saved up ${ITEMS[i].icon}`)
84  }
85  if (p.stats.tests > 0) options.push(`You’ve passed ${p.stats.tests} test run${p.stats.tests === 1 ? '' : 's'} with me.`)
86  if (p.line) options.push(`I’m a ${LINE_NAMES[p.line]}. It suits us, right?`)
87  options.push(pick(CHEERS, rnd), pick(QUIPS, rnd), pick(QUIPS, rnd))
88  return FLAVOR[p.personality](pick(options, rnd))
89}
90
hooks/pet.ts 830 lines
1// The monster and the rules that raise it. Pure: events in, a new pet out.
2
3import type { Boss, BossKind, Decor, Event, Hat, Item, Legend, Line, Personality, Pet, Secret, Skill, Stage, Variant, Visitor, VisitorDna } from '../types'
4
5export type { Boss, BossKind, Decor, Event, Hat, Item, Legend, Line, Personality, Pet, Secret, Skill, Stage, Variant, Visitor, VisitorDna }
6
7export const HOUR = 3600_000
8const MIN = 60_000
9
10const clamp = (n: number) => Math.max(0, Math.min(100, n))
11
12export const PERSONALITIES: Personality[] = ['cheerful', 'lazy', 'curious', 'grumpy']
13
14export function hatch(now: number, name = 'Byte', personality: Personality = 'cheerful'): Pet {
15  return normalize({ name, born: now, updatedAt: now, lastActive: now, personality, log: [{ at: now, text: 'An egg appeared.' }] })
16}
17
18/** Fills in every field a pet saved by an older version lacks. */
19export function normalize(raw: Partial<Pet>): Pet {
20  const now = raw.updatedAt ?? 0
21  return {
22    name: raw.name ?? 'Byte',
23    born: raw.born ?? now,
24    updatedAt: now,
25    lastActive: raw.lastActive ?? now,
26    personality: raw.personality ?? 'cheerful',
27    stage: raw.stage ?? 'egg',
28    line: raw.line ?? null,
29    variant: raw.variant ?? null,
30    xp: raw.xp ?? 0,
31    hunger: raw.hunger ?? 80,
32    joy: raw.joy ?? 70,
33    stress: raw.stress ?? 0,
34    energy: raw.energy ?? 80,
35    asleepUntil: raw.asleepUntil,
36    mess: raw.mess ?? 0,
37    skills: { power: 0, wisdom: 0, speed: 0, ...raw.skills },
38    items: { cookie: 1, coffee: 0, gem: 0, bug: 0, ...raw.items },
39    hat: raw.hat ?? null,
40    hats: raw.hats ?? [],
41    badges: raw.badges ?? [],
42    streak: raw.streak ?? { days: 0, lastDay: '' },
43    care: raw.care ?? { sum: 0, n: 0 },
44    traits: { shell: 0, code: 0, agents: 0, web: 0, ...raw.traits },
45    stats: {
46      tokens: 0, tests: 0, commits: 0, pushes: 0, tasks: 0, errors: 0, fed: 0, meals: 0, played: 0, pats: 0,
47      talks: 0, games: 0, wins: 0, trained: 0, cleaned: 0, agents: 0, bossWins: 0, bossTries: 0, cards: 0, visits: 0, spars: 0, ...raw.stats,
48    },
49    cooldowns: { ...raw.cooldowns },
50    mood: raw.mood,
51    said: raw.said,
52    settings: { sound: false, alerts: true, ...raw.settings },
53    week: raw.week ?? { id: '', errors: 0, testFails: 0 },
54    boss: raw.boss ?? null,
55    secret: raw.secret ?? null,
56    ultimateAt: raw.ultimateAt,
57    generation: raw.generation ?? 1,
58    hall: raw.hall ?? [],
59    decor: raw.decor ?? [],
60    habits: {
61      langs: {}, hours: new Array(24).fill(0), edits: 0, editsSinceCommit: 0, committedEdits: 0, testRuns: 0, toolCalls: 0,
62      ...raw.habits,
63    },
64    seed: raw.seed ?? null,
65    shiny: raw.shiny ?? false,
66    tour: raw.tour ?? { step: 0, done: false },
67    quests: raw.quests ?? [],
68    seen: raw.seen ?? [],
69    visitor: raw.visitor ?? null,
70    alerted: { ...raw.alerted },
71    log: raw.log ?? [],
72  }
73}
74
75export function level(xp: number) {
76  return Math.floor(Math.sqrt(Math.max(0, xp) / 10))
77}
78
79/** XP at which a level begins. */
80export function xpFor(lv: number) {
81  return lv * lv * 10
82}
83
84/** Things you do with it: each wakes it and counts as you being around. */
85const INTERACTIONS = new Set<Event['kind']>(['feed', 'play', 'pet', 'talk', 'clean', 'use', 'game', 'train', 'visit-play', 'visit-spar'])
86
87const STAGE_AT: { stage: Stage; level: number }[] = [
88  { stage: 'baby', level: 1 },
89  { stage: 'child', level: 4 },
90  { stage: 'adult', level: 10 },
91  { stage: 'ultimate', level: 20 },
92]
93
94export const LINE_NAMES: Record<Line, string> = { forge: 'Forge', scribe: 'Scribe', summoner: 'Summoner', wanderer: 'Wanderer' }
95
96/** What each line's adults are called, bright and shadow. */
97export const FORM_NAMES: Record<Line, Record<Variant, [string, string]>> = {
98  forge: { bright: ['Emberkin', 'Solforge'], shadow: ['Cinderhorn', 'Ashtyrant'] },
99  scribe: { bright: ['Quillwisp', 'Lorewraith'], shadow: ['Inkshade', 'Hexscript'] },
100  summoner: { bright: ['Callpup', 'Choirlord'], shadow: ['Hollowear', 'Legionmaw'] },
101  wanderer: { bright: ['Skylark', 'Zephyrus'], shadow: ['Duskwing', 'Stormcrow'] },
102}
103
104export const ITEMS: Record<Item, { name: string; icon: string; what: string }> = {
105  cookie: { name: 'Cookie', icon: '🍪', what: '+15 food, +5 joy. Earned from passing tests and daily gifts.' },
106  coffee: { name: 'Coffee', icon: '☕', what: '+30 energy. Earned every 50k tokens of work.' },
107  gem: { name: 'Gem', icon: '💎', what: '+20 xp, +10 joy. Earned from commits, pushes and streaks.' },
108  bug: { name: 'Bug snack', icon: '🐛', what: '+25 food, +5 xp. Earned when a failing test passes again.' },
109}
110
111export const SKILL_NAMES: Record<Skill, string> = { power: 'Power', wisdom: 'Wisdom', speed: 'Speed' }
112
113/** Each line trains one skill faster. */
114const SKILL_OF: Record<Line, Skill | null> = { forge: 'power', scribe: 'wisdom', wanderer: 'speed', summoner: null }
115
116export const HATS: Record<Hat, string> = {
117  party: 'Party hat', cap: 'Cap', headphones: 'Headphones', wizard: 'Wizard hat',
118  flower: 'Flower', bow: 'Bow', beanie: 'Beanie', halo: 'Halo',
119}
120
121type Badge = { id: string; name: string; what: string; hat?: Hat; earned: (p: Pet) => boolean }
122
123export const BADGES: Badge[] = [
124  { id: 'hatched', name: 'Hello, world', what: 'Hatch your egg', earned: p => p.stage !== 'egg' },
125  { id: 'lv5', name: 'Growing up', what: 'Reach level 5', hat: 'party', earned: p => level(p.xp) >= 5 },
126  { id: 'adult', name: 'All grown up', what: 'Evolve into an adult', earned: p => p.stage === 'adult' || p.stage === 'ultimate' },
127  { id: 'ultimate', name: 'Legend', what: 'Reach the ultimate stage', earned: p => p.stage === 'ultimate' },
128  { id: 'tests10', name: 'Green light', what: 'Pass 10 test runs', earned: p => p.stats.tests >= 10 },
129  { id: 'tests25', name: 'Test whisperer', what: 'Pass 25 test runs', hat: 'halo', earned: p => p.stats.tests >= 25 },
130  { id: 'commits10', name: 'Committed', what: 'Make 10 commits', hat: 'cap', earned: p => p.stats.commits >= 10 },
131  { id: 'push', name: 'Shipped it', what: 'Push to a remote', earned: p => p.stats.pushes >= 1 },
132  { id: 'shell100', name: 'Shell dweller', what: 'Run 100 shell commands', hat: 'headphones', earned: p => p.traits.shell >= 100 },
133  { id: 'wisdom20', name: 'Bookworm', what: 'Train Wisdom to 20', hat: 'wizard', earned: p => p.skills.wisdom >= 20 },
134  { id: 'fed10', name: 'Well fed', what: 'Feed it 10 times', hat: 'flower', earned: p => p.stats.meals >= 10 },
135  { id: 'pats30', name: 'Beloved', what: 'Pat it 30 times', hat: 'bow', earned: p => p.stats.pats >= 30 },
136  { id: 'streak7', name: 'Regular', what: 'Work 7 days in a row', hat: 'beanie', earned: p => p.streak.days >= 7 },
137  { id: 'wins10', name: 'Treat hunter', what: 'Win 10 treat hunts', earned: p => p.stats.wins >= 10 },
138  { id: 'agents10', name: 'Summoner’s call', what: 'Spawn 10 subagents', earned: p => p.stats.agents >= 10 },
139  { id: 'tokens1m', name: 'Big eater', what: 'Eat a million tokens', earned: p => p.stats.tokens >= 1_000_000 },
140  { id: 'clean5', name: 'Tidy', what: 'Clean up 5 times', earned: p => p.stats.cleaned >= 5 },
141  { id: 'talk20', name: 'Chatterbox', what: 'Talk with it 20 times', earned: p => p.stats.talks >= 20 },
142  { id: 'boss1', name: 'Bug squasher', what: 'Defeat a weekly Bug Boss', earned: p => p.stats.bossWins >= 1 },
143  { id: 'boss5', name: 'Exterminator', what: 'Defeat 5 weekly Bug Bosses', earned: p => p.stats.bossWins >= 5 },
144  { id: 'secret', name: 'Hidden path', what: 'Reach a secret form', earned: p => p.secret !== null },
145  { id: 'decor4', name: 'Home sweet home', what: 'Own 4 decorations', earned: p => p.decor.length >= 4 },
146  { id: 'host3', name: 'Good host', what: 'Host 3 visiting monsters', earned: p => p.stats.visits >= 3 },
147  { id: 'spar5', name: 'Sparring partner', what: 'Spar 5 visitors', earned: p => p.stats.spars >= 5 },
148  { id: 'legacy', name: 'Legacy', what: 'Retire a monster to the Hall of Fame', earned: p => p.hall.length > 0 },
149]
150
151function topLine(p: Pet): Line {
152  const t = p.traits
153  const ranked: [Line, number][] = [['forge', t.shell], ['scribe', t.code], ['summoner', t.agents * 3], ['wanderer', t.web * 2]]
154  ranked.sort((a, b) => b[1] - a[1])
155  return ranked[0]![0]
156}
157
158export const SECRET_NAMES: Record<Secret, [string, string]> = {
159  archivist: ['Archivist', 'High Archivist'],
160  bugslayer: ['Bugslayer', 'Bug Sovereign'],
161  goldheart: ['Goldheart', 'Sunheart'],
162}
163
164export const DECOR: Record<Decor, { name: string; cost: number }> = {
165  plant: { name: 'Potted plant', cost: 1 }, lamp: { name: 'Lamp', cost: 1 }, poster: { name: 'Poster', cost: 1 },
166  rug: { name: 'Rug', cost: 2 }, bed: { name: 'Bed', cost: 2 }, toybox: { name: 'Toy box', cost: 2 },
167  desk: { name: 'Desk and laptop', cost: 3 }, fountain: { name: 'Fountain', cost: 4 },
168}
169
170export function formName(p: Pet): string {
171  if (p.secret && (p.stage === 'adult' || p.stage === 'ultimate')) return SECRET_NAMES[p.secret][p.stage === 'adult' ? 0 : 1]
172  if (!p.line || !p.variant || (p.stage !== 'adult' && p.stage !== 'ultimate')) return p.stage
173  return FORM_NAMES[p.line][p.variant][p.stage === 'adult' ? 0 : 1]
174}
175
176function note(p: Pet, at: number, text: string) {
177  p.log = [...p.log, { at, text }].slice(-40)
178}
179
180export function isAsleep(p: Pet, now: number) {
181  return (p.asleepUntil ?? 0) > now || now - p.lastActive > 30 * MIN
182}
183
184export function isSick(p: Pet) {
185  return p.stress >= 80
186}
187
188export function dayOf(at: number) {
189  const d = new Date(at)
190  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
191}
192
193/** Time passes: hunger falls, stress eases, energy drains awake and returns asleep. */
194export function decay(p: Pet, now: number): Pet {
195  const hours = Math.max(0, (now - p.updatedAt) / HOUR)
196  if (hours <= 0) return p
197  const next = { ...p, updatedAt: now }
198  if (p.visitor && p.visitor.until <= now) next.visitor = null
199  const sleeping = isAsleep(p, now)
200  next.hunger = clamp(p.hunger - hours * (sleeping ? 2 : 4))
201  next.stress = clamp(p.stress - hours * (sleeping ? 10 : 6))
202  next.energy = clamp(p.energy + hours * (sleeping ? 15 : -3))
203  const lonely = now - p.lastActive > 24 * HOUR
204  const grubby = p.mess >= 2
205  if (next.hunger < 30 || lonely || grubby) next.joy = clamp(p.joy - hours * (grubby ? 4 : 3))
206  return next
207}
208
209function order(s: Stage) {
210  return ['egg', 'baby', 'child', 'adult', 'ultimate'].indexOf(s)
211}
212
213function grow(p: Pet, at: number) {
214  const lv = level(p.xp)
215  for (const s of STAGE_AT) {
216    if (lv >= s.level && order(p.stage) < order(s.stage)) {
217      if (s.stage === 'child' && !p.line) p.line = topLine(p)
218      if (s.stage === 'adult' && !p.variant) {
219        const avg = p.care.n ? p.care.sum / p.care.n : p.joy
220        p.variant = avg >= 55 && p.stress < 60 ? 'bright' : 'shadow'
221      }
222      p.stage = s.stage
223      if (s.stage === 'ultimate') p.ultimateAt = at
224      const what = s.stage === 'baby' ? `${p.name} hatched!` : `${p.name} evolved into ${article(formName(p))}${p.line && s.stage === 'child' ? ` (${LINE_NAMES[p.line]} line)` : ''}!`
225      note(p, at, what)
226      p.mood = { kind: 'evolve', until: at + 8000 }
227    }
228  }
229}
230
231function article(word: string) {
232  return /^[aeiou]/i.test(word) ? `an ${word}` : `a ${word}`
233}
234
235function give(p: Pet, item: Item, n = 1) {
236  p.items = { ...p.items, [item]: Math.min(99, p.items[item] + n) }
237}
238
239const TEST = /\b(npm|pnpm|yarn|bun)\s+(run\s+)?test\b|\bpytest\b|\bjest\b|\bvitest\b|\bcargo\s+test\b|\bgo\s+test\b|\bplugin\s+test\b|\bmake\s+test\b|\brspec\b|\bphpunit\b/
240const COMMIT = /\bgit\s+commit\b/
241const PUSH = /\bgit\s+push\b/
242
243/** A new day of work: extend or restart the streak, and hand out the daily gift. */
244function streak(p: Pet, at: number) {
245  const today = dayOf(at)
246  if (p.streak.lastDay === today) return
247  const yesterday = dayOf(at - 24 * HOUR)
248  const days = p.streak.lastDay === yesterday ? p.streak.days + 1 : 1
249  p.streak = { days, lastDay: today }
250  give(p, 'cookie')
251  if (days === 3 || days === 7 || days % 30 === 0) {
252    give(p, 'gem')
253    note(p, at, `${days}-day streak! A gem for you.`)
254  } else if (days > 1) note(p, at, `Day ${days} together. A cookie for you.`)
255}
256
257/** The ISO week of a time, e.g. 2026-W41. */
258export function weekOf(at: number) {
259  const d = new Date(at)
260  const day = (d.getDay() + 6) % 7
261  d.setHours(0, 0, 0, 0)
262  d.setDate(d.getDate() - day + 3)
263  const firstThursday = new Date(d.getFullYear(), 0, 4)
264  const week = 1 + Math.round(((d.getTime() - firstThursday.getTime()) / 86400000 - 3 + ((firstThursday.getDay() + 6) % 7)) / 7)
265  return `${d.getFullYear()}-W${String(week).padStart(2, '0')}`
266}
267
268export const BOSS_NAMES: Record<BossKind, string> = {
269  imp: 'Lint Imp', golem: 'Stacktrace Golem', hydra: 'Flaky Hydra', kraken: 'Regression Kraken',
270}
271
272/** A boss shaped by a week's failures: more failures, a tougher boss. */
273export function makeBoss(week: string, errors: number, testFails: number): Boss {
274  const kind: BossKind = errors >= 15 ? 'kraken' : testFails >= 3 && testFails * 2 >= errors ? 'hydra' : errors >= 5 ? 'golem' : 'imp'
275  return { week, kind, name: BOSS_NAMES[kind], hp: Math.min(220, 40 + errors * 4), atk: 6 + Math.min(14, Math.floor(errors / 3)), beaten: false, tries: 0 }
276}
277
278function rollWeek(p: Pet, at: number) {
279  const id = weekOf(at)
280  if (p.week.id === id) return
281  p.boss = makeBoss(id, p.week.errors, p.week.testFails)
282  p.week = { id, errors: 0, testFails: 0 }
283}
284
285function active(p: Pet, at: number) {
286  rollWeek(p, at)
287  const hours = [...p.habits.hours]
288  hours[new Date(at).getHours()] = (hours[new Date(at).getHours()] ?? 0) + 1
289  p.habits = { ...p.habits, hours }
290  p.lastActive = at
291  p.care = { sum: p.care.sum + p.joy, n: p.care.n + 1 }
292  streak(p, at)
293}
294
295/** One thing that happened in some session, applied to the pet. */
296export function apply(prev: Pet, e: Event): Pet {
297  const d = decay(prev, e.at)
298  const p: Pet = {
299    ...d, traits: { ...d.traits }, stats: { ...d.stats }, cooldowns: { ...d.cooldowns },
300    items: { ...d.items }, skills: { ...d.skills }, hats: [...d.hats], badges: [...d.badges],
301  }
302  const xp0 = p.xp
303  // You are here: caring for it or playing with it wakes it up and counts as being around.
304  if (INTERACTIONS.has(e.kind)) {
305    if ((p.asleepUntil ?? 0) > e.at) {
306      p.asleepUntil = undefined
307      p.joy = clamp(p.joy - 2)
308      note(p, e.at, `${p.name} woke up, a little grumpy.`)
309    }
310    p.lastActive = Math.max(p.lastActive, e.at)
311  }
312  switch (e.kind) {
313    case 'tokens': {
314      p.hunger = clamp(p.hunger + e.n / 2500)
315      p.xp += e.n / 8000
316      const coffees = Math.floor((p.stats.tokens + e.n) / 50_000) - Math.floor(p.stats.tokens / 50_000)
317      p.stats.tokens += e.n
318      if (coffees > 0) give(p, 'coffee', coffees)
319      active(p, e.at)
320      break
321    }
322    case 'tool': {
323      active(p, e.at)
324      habitsOf(p, e)
325      if (e.tool === 'Bash') p.traits.shell += 1
326      else if (['Read', 'Edit', 'Write', 'Grep', 'Glob', 'NotebookEdit', 'MultiEdit'].includes(e.tool)) p.traits.code += 1
327      else if (e.tool === 'Agent') p.traits.agents += 1
328      else if (e.tool === 'WebSearch' || e.tool === 'WebFetch') p.traits.web += 1
329      if (e.failed) {
330        p.stress = clamp(p.stress + 3)
331        p.stats.errors += 1
332        p.week = { ...p.week, errors: p.week.errors + 1 }
333        p.mood = { kind: 'ouch', until: e.at + 4000 }
334      } else if ((e.ms ?? 0) > 60_000) {
335        p.mood = { kind: 'sweat', until: e.at + 4000 }
336      }
337      const cmd = e.command ?? ''
338      if (e.tool === 'Bash' && TEST.test(cmd)) {
339        if (e.failed) {
340          p.stress = clamp(p.stress + 5)
341          p.stats.lastTestFailed = true
342          p.week = { ...p.week, testFails: p.week.testFails + 1 }
343        } else {
344          p.joy = clamp(p.joy + 8)
345          p.xp += 5
346          p.stats.tests += 1
347          give(p, 'cookie')
348          if (p.stats.lastTestFailed) {
349            give(p, 'bug')
350            note(p, e.at, 'Fixed it! A bug snack for you.')
351          } else note(p, e.at, 'Tests passed! A cookie for you.')
352          p.stats.lastTestFailed = false
353          p.mood = { kind: 'cheer', until: e.at + 5000 }
354        }
355      }
356      if (e.tool === 'Bash' && COMMIT.test(cmd) && !e.failed) {
357        p.joy = clamp(p.joy + 5)
358        p.xp += 10
359        p.stats.commits += 1
360        give(p, 'gem')
361        p.mood = { kind: 'cheer', until: e.at + 5000 }
362        note(p, e.at, 'A commit! A gem for you.')
363      }
364      if (e.tool === 'Bash' && PUSH.test(cmd) && !e.failed) {
365        p.joy = clamp(p.joy + 8)
366        p.xp += 10
367        p.stats.pushes += 1
368        give(p, 'gem')
369        p.mood = { kind: 'cheer', until: e.at + 6000 }
370        note(p, e.at, 'Shipped! Pushed to the remote.')
371      }
372      break
373    }
374    case 'task': {
375      p.xp += 5 * e.n
376      p.joy = clamp(p.joy + 3 * e.n)
377      p.stats.tasks += e.n
378      active(p, e.at)
379      p.mood = { kind: 'cheer', until: e.at + 4000 }
380      break
381    }
382    case 'agent': {
383      p.stats.agents += 1
384      p.mood = { kind: 'wave', until: e.at + 4000 }
385      break
386    }
387    case 'feed': {
388      if ((p.cooldowns.feed ?? 0) > e.at) {
389        p.mood = { kind: 'full', until: e.at + 3000 }
390        break
391      }
392      p.hunger = clamp(p.hunger + 25)
393      p.cooldowns.feed = e.at + HOUR
394      p.stats.fed += 1
395      meal(p)
396      p.mood = { kind: 'eat', until: e.at + 4000 }
397      note(p, e.at, `You fed ${p.name}.`)
398      break
399    }
400    case 'use': {
401      if (p.items[e.item] <= 0) break
402      p.items[e.item] -= 1
403      if (e.item === 'cookie') {
404        p.hunger = clamp(p.hunger + 15)
405        p.joy = clamp(p.joy + 5)
406        meal(p)
407        p.mood = { kind: 'eat', until: e.at + 4000 }
408      } else if (e.item === 'bug') {
409        p.hunger = clamp(p.hunger + 25)
410        p.xp += 5
411        meal(p)
412        p.mood = { kind: 'eat', until: e.at + 4000 }
413      } else if (e.item === 'coffee') {
414        p.energy = clamp(p.energy + 30)
415        p.asleepUntil = undefined
416        p.mood = { kind: 'cheer', until: e.at + 4000 }
417      } else if (e.item === 'gem') {
418        p.xp += 20
419        p.joy = clamp(p.joy + 10)
420        p.mood = { kind: 'love', until: e.at + 4000 }
421      }
422      note(p, e.at, `${p.name} had a ${ITEMS[e.item].name.toLowerCase()}.`)
423      break
424    }
425    case 'play': {
426      if ((p.cooldowns.play ?? 0) > e.at || p.energy < 10) {
427        p.mood = { kind: 'tired', until: e.at + 3000 }
428        break
429      }
430      p.joy = clamp(p.joy + 15)
431      p.stress = clamp(p.stress - 10)
432      p.energy = clamp(p.energy - 8)
433      p.xp += 2
434      p.cooldowns.play = e.at + 30 * MIN
435      p.stats.played += 1
436      p.mood = { kind: 'cheer', until: e.at + 4000 }
437      note(p, e.at, `You played with ${p.name}.`)
438      break
439    }
440    case 'pet': {
441      p.joy = clamp(p.joy + 2)
442      p.stats.pats += 1
443      p.mood = { kind: 'love', until: e.at + 3000 }
444      break
445    }
446    case 'talk': {
447      p.joy = clamp(p.joy + 1)
448      p.stats.talks += 1
449      p.said = { text: e.text, at: e.at }
450      p.mood = { kind: 'talk', until: e.at + 5000 }
451      break
452    }
453    case 'clean': {
454      if (p.mess === 0) break
455      p.mess = 0
456      p.joy = clamp(p.joy + 5)
457      p.stats.cleaned += 1
458      p.mood = { kind: 'cheer', until: e.at + 3000 }
459      note(p, e.at, `You tidied up after ${p.name}.`)
460      break
461    }
462    case 'wake': {
463      if ((p.asleepUntil ?? 0) <= e.at) break
464      p.asleepUntil = undefined
465      p.lastActive = Math.max(p.lastActive, e.at)
466      p.mood = { kind: 'wave', until: e.at + 3000 }
467      note(p, e.at, `Good morning, ${p.name}!`)
468      break
469    }
470    case 'tuck': {
471      p.asleepUntil = e.at + 2 * HOUR
472      p.stress = clamp(p.stress - 5)
473      p.mood = undefined
474      note(p, e.at, `${p.name} is tucked in. Good night!`)
475      break
476    }
477    case 'game': {
478      p.stats.games += 1
479      p.energy = clamp(p.energy - 5)
480      p.cooldowns.game = e.at + 5 * MIN
481      if (e.won) {
482        p.stats.wins += 1
483        p.joy = clamp(p.joy + 10)
484        p.xp += 4
485        if (e.prize) give(p, e.prize)
486        p.mood = { kind: 'win', until: e.at + 5000 }
487        note(p, e.at, `${p.name} won the treat hunt${e.prize ? ` and found a ${ITEMS[e.prize].name.toLowerCase()}` : ''}!`)
488      } else {
489        p.joy = clamp(p.joy + 3)
490        p.mood = { kind: 'lose', until: e.at + 4000 }
491      }
492      break
493    }
494    case 'train': {
495      if ((p.cooldowns.train ?? 0) > e.at || p.energy < 10 || p.hunger < 10) {
496        p.mood = { kind: 'tired', until: e.at + 3000 }
497        break
498      }
499      const bonus = p.line && SKILL_OF[p.line] === e.skill ? 2 : 0
500      p.skills[e.skill] += 3 + bonus
501      p.hunger = clamp(p.hunger - 8)
502      p.energy = clamp(p.energy - 10)
503      p.xp += 3
504      p.stats.trained += 1
505      p.cooldowns.train = e.at + 15 * MIN
506      p.mood = { kind: 'sweat', until: e.at + 4000 }
507      note(p, e.at, `${p.name} trained ${SKILL_NAMES[e.skill]} (+${3 + bonus}).`)
508      break
509    }
510    case 'equip': {
511      if (e.hat === null || p.hats.includes(e.hat)) p.hat = e.hat
512      break
513    }
514    case 'boss': {
515      if (!p.boss || p.boss.beaten) break
516      p.boss = { ...p.boss, tries: p.boss.tries + 1 }
517      p.stats.bossTries += 1
518      p.energy = clamp(p.energy - 15)
519      if (e.won) {
520        p.boss = { ...p.boss, beaten: true }
521        p.stats.bossWins += 1
522        give(p, 'gem', 3)
523        p.xp += 30
524        p.joy = clamp(p.joy + 15)
525        p.mood = { kind: 'win', until: e.at + 6000 }
526        note(p, e.at, `${p.name} defeated the ${p.boss.name}! +3 gems, +30 xp.`)
527      } else {
528        p.joy = clamp(p.joy - 5)
529        p.mood = { kind: 'lose', until: e.at + 5000 }
530        note(p, e.at, `The ${p.boss.name} won this time.`)
531      }
532      break
533    }
534    case 'buy': {
535      const d = DECOR[e.decor]
536      if (!d || p.decor.includes(e.decor) || p.items.gem < d.cost) break
537      p.items = { ...p.items, gem: p.items.gem - d.cost }
538      p.decor = [...p.decor, e.decor]
539      p.mood = { kind: 'cheer', until: e.at + 4000 }
540      note(p, e.at, `New for the habitat: ${d.name.toLowerCase()}.`)
541      break
542    }
543    case 'retire': {
544      if (!canRetire(p, e.at)) break
545      return retire(p, e.at)
546    }
547    case 'seed': {
548      if (p.seed !== null) break
549      p.seed = e.value
550      // One in 256 monsters is shiny, decided once by who you are and when it hatched.
551      p.shiny = mix(e.value, p.born) % 256 === 0
552      if (p.shiny) note(p, e.at, `${p.name} has a rare shiny colouring! ✦`)
553      break
554    }
555    case 'visit': {
556      p.visitor = { code: e.code, name: e.name, dna: e.dna, arrived: e.at, until: e.at + VISIT_MS, played: false, sparred: false }
557      p.stats.visits += 1
558      p.mood = { kind: 'wave', until: e.at + 5000 }
559      note(p, e.at, `${e.name} came to visit!`)
560      break
561    }
562    case 'visit-play': {
563      if (!p.visitor || p.visitor.played) break
564      p.visitor = { ...p.visitor, played: true }
565      p.joy = clamp(p.joy + 12)
566      p.xp += 5
567      p.mood = { kind: 'love', until: e.at + 5000 }
568      note(p, e.at, `${p.name} and ${p.visitor.name} played together.`)
569      break
570    }
571    case 'visit-spar': {
572      if (!p.visitor || p.visitor.sparred) break
573      p.visitor = { ...p.visitor, sparred: true }
574      p.stats.spars += 1
575      p.energy = clamp(p.energy - 8)
576      if (e.won) {
577        give(p, 'cookie')
578        p.xp += 8
579        p.mood = { kind: 'win', until: e.at + 5000 }
580        note(p, e.at, `${p.name} won a friendly spar against ${p.visitor.name}! 🍪`)
581      } else {
582        p.joy = clamp(p.joy + 3)
583        p.mood = { kind: 'cheer', until: e.at + 4000 }
584        note(p, e.at, `${p.visitor.name} won the spar. Good game!`)
585      }
586      break
587    }
588    case 'visit-end': {
589      if (p.visitor) note(p, e.at, `${p.visitor.name} went home.`)
590      p.visitor = null
591      break
592    }
593    case 'seen': {
594      if (!p.seen.includes(e.what)) p.seen = [...p.seen, e.what]
595      break
596    }
597    case 'card': {
598      p.stats.cards += 1
599      break
600    }
601    case 'tour': {
602      p.tour = e.action === 'skip' ? { ...p.tour, done: true } : { step: 0, done: false }
603      break
604    }
605    case 'setting': {
606      p.settings = { ...p.settings, [e.key]: e.on }
607      break
608    }
609    case 'rename': {
610      note(p, e.at, `${p.name} is now called ${e.name}.`)
611      p.name = e.name
612      break
613    }
614  }
615  if (p.stress >= 80 && prev.stress < 80) note(p, e.at, `${p.name} feels sick from all the errors.`)
616  if (level(p.xp) > level(xp0)) {
617    note(p, e.at, `${p.name} reached level ${level(p.xp)}.`)
618    p.mood ??= { kind: 'cheer', until: e.at + 4000 }
619  }
620  grow(p, e.at)
621  secrets(p, e.at)
622  badges(p, e.at)
623  quests(p, e.at)
624  advanceTour(p)
625  return p
626}
627
628// ── Starter quests: small first goals, each rewarded once.
629type Quest = { id: string; what: string; reward: Item; done: (p: Pet) => boolean }
630
631export const QUESTS: Quest[] = [
632  { id: 'feed', what: 'Feed it once', reward: 'cookie', done: p => p.stats.meals >= 1 },
633  { id: 'talk', what: 'Talk with it', reward: 'cookie', done: p => p.stats.talks >= 1 },
634  { id: 'hunt', what: 'Win a treat hunt', reward: 'coffee', done: p => p.stats.wins >= 1 },
635  { id: 'train', what: 'Train a skill', reward: 'cookie', done: p => p.stats.trained >= 1 },
636  { id: 'buy', what: 'Buy a decoration', reward: 'gem', done: p => p.decor.length >= 1 },
637  { id: 'card', what: 'Make its card (/pet card)', reward: 'gem', done: p => p.stats.cards >= 1 },
638  { id: 'boss', what: 'Fight a weekly Bug Boss', reward: 'coffee', done: p => p.stats.bossTries >= 1 },
639]
640
641function quests(p: Pet, at: number) {
642  for (const q of QUESTS) {
643    if (p.quests.includes(q.id) || !q.done(p)) continue
644    p.quests = [...p.quests, q.id]
645    give(p, q.reward)
646    note(p, at, `Quest done: ${q.what.replace(/ \(.*\)$/, '').toLowerCase()}. ${ITEMS[q.reward].icon} for you.`)
647  }
648}
649
650// ── The first-run tour: one tip at a time, each moving on once you have done it.
651export const TOUR: { tip: string; done: (p: Pet) => boolean }[] = [
652  { tip: 'Your egg hatches from Claude’s work: every token feeds it. Just keep coding!', done: p => p.stage !== 'egg' },
653  { tip: 'It hatched! Type /pet to visit its habitat.', done: p => p.seen.includes('pane') },
654  { tip: 'Say hi: press ♥ or 💬 here, or Feed and Talk in /pet.', done: p => p.stats.pats + p.stats.talks + p.stats.meals > 0 },
655  { tip: 'Real work earns treats: passing tests 🍪, commits 💎. See the Items tab.', done: p => p.seen.includes('items') },
656  { tip: 'Try the Games tab: a treat hunt, training, and a weekly Bug Boss.', done: p => p.seen.includes('games') || p.stats.games > 0 },
657  { tip: 'Your habits shape its looks. See its DNA in Style, and share it with /pet card.', done: p => p.seen.includes('style') || p.stats.cards > 0 },
658]
659
660function advanceTour(p: Pet) {
661  if (p.tour.done) return
662  let step = p.tour.step
663  while (step < TOUR.length && TOUR[step]!.done(p)) step++
664  p.tour = step >= TOUR.length ? { step, done: true } : { step, done: false }
665}
666
667export function tourTip(p: Pet): string | null {
668  if (p.tour.done) return null
669  const t = TOUR[p.tour.step]
670  return t ? `Tip ${p.tour.step + 1}/${TOUR.length}: ${t.tip}` : null
671}
672
673/** The single most useful thing to do next, as one line. */
674export function nextUp(p: Pet, now: number): string {
675  if (isSick(p)) return `${p.name} is sick from errors. Some green test runs and rest will help.`
676  if (p.hunger < 25) return `${p.name} is hungry: Feed it, use a 🍪, or give Claude some work.`
677  if (p.mess >= 2) return 'It’s messy in here: press Clean.'
678  if (p.energy < 15) return `${p.name} is exhausted: Tuck it in, or use a ☕.`
679  if (p.boss && !p.boss.beaten && p.stage !== 'egg' && p.stage !== 'baby') return `Your weekly Bug Boss, the ${p.boss.name}, is waiting in Games.`
680  const unworn = p.hats.find(h => p.hat === null && h)
681  if (unworn) return `You've unlocked the ${HATS[unworn].toLowerCase()}: try it on in Style.`
682  const quest = QUESTS.find(q => !p.quests.includes(q.id))
683  const lv = level(p.xp)
684  const nextStage = STAGE_AT.find(s => order(s.stage) > order(p.stage))
685  if (nextStage) {
686    const need = Math.ceil(xpFor(nextStage.level) - p.xp)
687    const why = nextStage.stage === 'child' ? ', when it picks its line from how you work' : nextStage.stage === 'adult' ? '; care decides bright or shadow' : ''
688    if (need <= 40 || !quest) return `${need} xp until it becomes ${article(nextStage.stage)}${why}.`
689  }
690  if (quest) return `Quest: ${quest.what} (reward ${ITEMS[quest.reward].icon}).`
691  const affordable = (Object.keys(DECOR) as Decor[]).find(d => !p.decor.includes(d) && DECOR[d].cost <= p.items.gem)
692  if (affordable) return `You have ${p.items.gem} 💎: the ${DECOR[affordable].name.toLowerCase()} is in the Shop.`
693  return `Level ${lv + 1} in ${Math.ceil(xpFor(lv + 1) - p.xp)} xp. Keep your ${p.streak.days}-day streak going!`
694}
695
696function secretFor(p: Pet): Secret | null {
697  if (p.stats.bossWins >= 3) return 'bugslayer'
698  if (p.streak.days >= 30) return 'goldheart'
699  if (p.line === 'scribe' && p.skills.wisdom >= 50) return 'archivist'
700  return null
701}
702
703function secrets(p: Pet, at: number) {
704  if (p.secret || (p.stage !== 'adult' && p.stage !== 'ultimate')) return
705  const s = secretFor(p)
706  if (!s) return
707  p.secret = s
708  p.mood = { kind: 'evolve', until: at + 8000 }
709  note(p, at, `${p.name} took a hidden path and became ${article(formName(p))}!`)
710}
711
712export const RETIRE_AFTER = 30 * 24 * HOUR
713export const VISIT_MS = 24 * HOUR
714
715export function canRetire(p: Pet, now: number) {
716  return p.stage === 'ultimate' && p.ultimateAt !== undefined && now - p.ultimateAt >= RETIRE_AFTER
717}
718
719/** The monster joins the Hall of Fame; a new egg keeps your treasures and a head start. */
720function retire(p: Pet, at: number): Pet {
721  const legend: Legend = {
722    name: p.name, form: formName(p), level: level(p.xp), days: Math.floor((at - p.born) / (24 * HOUR)), generation: p.generation, retiredAt: at,
723  }
724  const best = (Object.keys(p.skills) as Skill[]).sort((a, b) => p.skills[b] - p.skills[a])[0]!
725  const egg = hatch(at, p.name, p.personality)
726  return normalize({
727    ...egg,
728    generation: p.generation + 1,
729    hall: [...p.hall, legend],
730    items: p.items, hats: p.hats, hat: p.hat, badges: [...p.badges, ...(p.badges.includes('legacy') ? [] : ['legacy'])],
731    decor: p.decor, settings: p.settings, streak: p.streak, week: p.week, boss: p.boss,
732    skills: { power: 0, wisdom: 0, speed: 0, [best]: Math.floor(p.skills[best] * 0.25) },
733    log: [{ at, text: `${legend.name} retired to the Hall of Fame. A new egg appeared: generation ${p.generation + 1}.` }],
734  })
735}
736
737function meal(p: Pet) {
738  p.stats.meals += 1
739  if (p.stats.meals % 3 === 0) p.mess = Math.min(3, p.mess + 1)
740}
741
742function badges(p: Pet, at: number) {
743  for (const b of BADGES) {
744    if (p.badges.includes(b.id) || !b.earned(p)) continue
745    p.badges.push(b.id)
746    if (b.hat && !p.hats.includes(b.hat)) p.hats.push(b.hat)
747    note(p, at, `Badge: ${b.name}${b.hat ? ` (unlocked the ${HATS[b.hat].toLowerCase()})` : ''}`)
748  }
749}
750
751export function applyAll(p: Pet, events: readonly Event[], now: number): Pet {
752  let next = normalize(p)
753  for (const e of events) next = apply(next, e)
754  return decay(next, now)
755}
756
757export type Face = 'happy' | 'sad' | 'sick' | 'sleep' | 'hungry' | 'sleepy' | NonNullable<Pet['mood']>['kind']
758
759/** What the monster looks like it feels right now. */
760export function face(p: Pet, now: number): Face {
761  if (p.mood && p.mood.until > now) return p.mood.kind
762  if (isSick(p)) return 'sick'
763  if (isAsleep(p, now)) return 'sleep'
764  if (p.hunger < 25) return 'hungry'
765  if (p.energy < 20) return 'sleepy'
766  if (p.joy < 30) return 'sad'
767  return 'happy'
768}
769
770export function age(p: Pet, now: number) {
771  const d = Math.floor((now - p.born) / (24 * HOUR))
772  if (d >= 1) return `${d} day${d === 1 ? '' : 's'}`
773  const h = Math.floor((now - p.born) / HOUR)
774  return h >= 1 ? `${h}h` : `${Math.max(1, Math.floor((now - p.born) / MIN))}m`
775}
776
777const ALERTS = {
778  hungry: { when: (p: Pet) => p.hunger < 20, text: (p: Pet) => `${p.name} is very hungry.` },
779  sick: { when: (p: Pet) => isSick(p), text: (p: Pet) => `${p.name} feels sick from all the errors.` },
780  messy: { when: (p: Pet) => p.mess >= 3, text: (p: Pet) => `${p.name}'s habitat needs a clean.` },
781  tired: { when: (p: Pet) => p.energy < 10, text: (p: Pet) => `${p.name} is exhausted. Tuck it in or try a coffee.` },
782} as const
783
784/** Alerts that just became true: each fires once, and re-arms when its condition clears. */
785export function alerts(p: Pet): { pet: Pet; fire: string[] } {
786  const alerted = { ...p.alerted }
787  const fire: string[] = []
788  for (const [key, a] of Object.entries(ALERTS) as [keyof typeof ALERTS, (typeof ALERTS)[keyof typeof ALERTS]][]) {
789    const now = a.when(p)
790    if (now && !alerted[key]) fire.push(a.text(p))
791    alerted[key] = now
792  }
793  return { pet: { ...p, alerted }, fire: p.settings.alerts ? fire : [] }
794}
795
796/** Mixes two numbers into a well-spread 32-bit value. */
797export function mix(a: number, b: number) {
798  let h = (Math.imul(a | 0, 0x9e3779b1) ^ Math.imul((b / 1000) | 0, 0x85ebca6b)) >>> 0
799  h = Math.imul(h ^ (h >>> 16), 0x7feb352d) >>> 0
800  h = Math.imul(h ^ (h >>> 15), 0x846ca68b) >>> 0
801  return (h ^ (h >>> 16)) >>> 0
802}
803
804const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit'])
805
806function habitsOf(p: Pet, e: Extract<Event, { kind: 'tool' }>) {
807  const h = { ...p.habits, langs: { ...p.habits.langs }, toolCalls: p.habits.toolCalls + 1 }
808  if (EDIT_TOOLS.has(e.tool) && e.ext && !e.failed) {
809    h.langs[e.ext] = (h.langs[e.ext] ?? 0) + 1
810    h.edits += 1
811    h.editsSinceCommit += 1
812  }
813  const cmd = e.command ?? ''
814  if (e.tool === 'Bash' && TEST.test(cmd)) h.testRuns += 1
815  if (e.tool === 'Bash' && COMMIT.test(cmd) && !e.failed) {
816    h.committedEdits += h.editsSinceCommit
817    h.editsSinceCommit = 0
818  }
819  p.habits = h
820}
821
822const STAGE_POWER: Record<Stage, number> = { egg: 0, baby: 10, child: 25, adult: 45, ultimate: 70 }
823
824/** A friendly spar: stage and skills against the visitor's stage, with luck. */
825export function spar(p: Pet, v: VisitorDna, rnd: () => number): { won: boolean; ours: number; theirs: number } {
826  const ours = Math.round(STAGE_POWER[p.stage] + (p.skills.power + p.skills.wisdom + p.skills.speed) / 3 + rnd() * 20)
827  const theirs = Math.round(STAGE_POWER[v.stage] + (v.seed % 15) + (v.armor ? 5 : 0) + rnd() * 20)
828  return { won: ours >= theirs, ours, theirs }
829}
830
hooks/boss.ts 65 lines
1// The weekly Bug Boss battle: pure turns, so the pane and /pet boss share it and tests can drive it.
2
3import { level, type Boss, type Pet, type Skill } from './pet'
4
5export type Battle = { hp: number; maxHp: number; petHp: number; petMax: number; turn: number; weak: Skill; log: string[]; over: 'won' | 'lost' | null }
6
7const SKILLS: Skill[] = ['power', 'wisdom', 'speed']
8
9export const MOVES: Record<Skill, { name: string; verb: string }> = {
10  power: { name: 'Strike', verb: 'strikes' },
11  wisdom: { name: 'Outsmart', verb: 'outsmarts' },
12  speed: { name: 'Dodge', verb: 'dodges and counters' },
13}
14
15const TELLS: Record<Skill, string> = {
16  power: 'its shell is cracked: Strike hits hard',
17  wisdom: 'it looks confused: Outsmart hits hard',
18  speed: 'it is winding up: Dodge hits hard',
19}
20
21export function canFight(p: Pet): string | null {
22  if (!p.boss) return 'No boss yet. One forms at the start of each week from the last week’s failures.'
23  if (p.boss.beaten) return `The ${p.boss.name} is beaten for this week. A new boss forms next week.`
24  if (p.stage === 'egg' || p.stage === 'baby') return `${p.name} is too young to fight. Bosses can be fought from the child stage.`
25  if (p.energy < 15) return `${p.name} is too tired to fight. Tuck it in or have a coffee.`
26  return null
27}
28
29export function startBattle(p: Pet, boss: Boss, rnd: () => number): Battle {
30  const petMax = 40 + level(p.xp) * 3 + Math.floor((p.skills.power + p.skills.wisdom + p.skills.speed) / 2)
31  const weak = SKILLS[Math.floor(rnd() * 3)]!
32  return { hp: boss.hp, maxHp: boss.hp, petHp: petMax, petMax, turn: 1, weak, log: [`The ${boss.name} appears! ${cap(TELLS[weak])}.`], over: null }
33}
34
35function cap(s: string) {
36  return s.charAt(0).toUpperCase() + s.slice(1)
37}
38
39export function move(b: Battle, p: Pet, boss: Boss, skill: Skill, rnd: () => number): Battle {
40  if (b.over) return b
41  const stage = p.stage === 'ultimate' ? 1.5 : p.stage === 'adult' ? 1.25 : 1
42  const crit = skill === b.weak
43  const dmg = Math.round((4 + p.skills[skill] * 0.6 + rnd() * 4) * (crit ? 2 : 1) * stage)
44  const hp = Math.max(0, b.hp - dmg)
45  const log = [...b.log, `${p.name} ${MOVES[skill].verb} for ${dmg}${crit ? ' (super effective!)' : ''}.`]
46  if (hp === 0) return { ...b, hp, log: [...log, `The ${boss.name} is defeated!`].slice(-6), over: 'won' }
47  const evade = skill === 'speed' && rnd() < Math.min(0.4, p.skills.speed / 120)
48  let hit = Math.round(boss.atk * (0.7 + rnd() * 0.6) * (skill === 'speed' ? 0.5 : 1))
49  if (evade) hit = 0
50  const petHp = Math.max(0, b.petHp - hit)
51  log.push(evade ? `${p.name} evades the counterattack!` : `The ${boss.name} hits back for ${hit}.`)
52  if (petHp === 0) return { ...b, hp, petHp, log: [...log, `${p.name} is knocked out…`].slice(-6), over: 'lost' }
53  const weak = SKILLS[Math.floor(rnd() * 3)]!
54  return { ...b, hp, petHp, turn: b.turn + 1, weak, log: [...log, `Turn ${b.turn + 1}: ${TELLS[weak]}.`].slice(-6), over: null }
55}
56
57export function skillOf(word: string): Skill | null {
58  const w = word.toLowerCase()
59  if (w === 'strike' || w === 'power') return 'power'
60  if (w === 'outsmart' || w === 'wisdom') return 'wisdom'
61  if (w === 'dodge' || w === 'speed') return 'speed'
62  return null
63}
64
65
hooks/card.ts 287 lines
1// The monster's card: a pixel-art picture of it and what makes it yours, to share. Drawn as
2// pixels (so one picture serves the PNG file and the desktop preview), plus a DNA code that
3// another person's mod can turn back into the same monster.
4
5import { SIZE, type Rgb, type Sprite } from './art'
6import { LANGS, commitSize, dnaOf, languages, rhythm } from './dna'
7import { drawText, textWidth } from './font'
8import { seasonOf } from './habitat'
9import { BADGES, LINE_NAMES, formName, level, type Line, type Pet, type Stage, type Variant } from './pet'
10import { base64, petFrames } from './render'
11
12export const CARD_W = 240
13export const CARD_H = 128
14
15const INK = 0x14161f
16const PANEL = 0x1f2230
17const TEXT = 0xf4f4f4
18const DIM = 0x8a90a8
19const GOLD = 0xffcd75
20
21// ── The DNA code: a few traits and the seed, in 13 Crockford base-32 characters.
22const B32 = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
23const LANG_NAMES = [...new Set(Object.values(LANGS).map(l => l.name))]
24const STAGES: Stage[] = ['egg', 'baby', 'child', 'adult', 'ultimate']
25const LINES: (Line | null)[] = [null, 'forge', 'scribe', 'summoner', 'wanderer']
26const VARIANTS: (Variant | null)[] = [null, 'bright', 'shadow']
27const PATTERN = ['none', 'stripes', 'spots', 'patch'] as const
28const MARK = ['none', 'moon', 'sun', 'star'] as const
29const BUILD = ['normal', 'slim', 'stout'] as const
30const EYES = ['round', 'sharp', 'sleepy'] as const
31const EXTRA = ['none', 'glasses', 'scarf'] as const
32
33export type CodeFields = {
34  seed: number; lang1: string | null; lang2: string | null
35  pattern: (typeof PATTERN)[number]; mark: (typeof MARK)[number]; build: (typeof BUILD)[number]
36  armor: boolean; eyes: (typeof EYES)[number]; extra: (typeof EXTRA)[number]; shiny: boolean
37  stage: Stage; line: Line | null; variant: Variant | null
38}
39
40const FIELDS: [keyof CodeFields, number][] = [
41  ['seed', 32], ['lang1', 6], ['lang2', 6], ['pattern', 2], ['mark', 2], ['build', 2], ['armor', 1],
42  ['eyes', 2], ['extra', 2], ['shiny', 1], ['stage', 3], ['line', 3], ['variant', 2],
43]
44
45function toNumber(f: CodeFields, key: keyof CodeFields): number {
46  switch (key) {
47    case 'seed': return f.seed >>> 0
48    case 'lang1': return f.lang1 ? LANG_NAMES.indexOf(f.lang1) + 1 : 0
49    case 'lang2': return f.lang2 ? LANG_NAMES.indexOf(f.lang2) + 1 : 0
50    case 'pattern': return PATTERN.indexOf(f.pattern)
51    case 'mark': return MARK.indexOf(f.mark)
52    case 'build': return BUILD.indexOf(f.build)
53    case 'armor': return f.armor ? 1 : 0
54    case 'eyes': return EYES.indexOf(f.eyes)
55    case 'extra': return EXTRA.indexOf(f.extra)
56    case 'shiny': return f.shiny ? 1 : 0
57    case 'stage': return STAGES.indexOf(f.stage)
58    case 'line': return LINES.indexOf(f.line)
59    case 'variant': return VARIANTS.indexOf(f.variant)
60  }
61}
62
63export function codeFields(p: Pet): CodeFields {
64  const dna = dnaOf(p)
65  const langs = languages(p)
66  return {
67    seed: p.seed ?? 0,
68    lang1: langs[0]?.name ?? null,
69    lang2: langs[1] && langs[1].share >= 0.12 ? langs[1].name : null,
70    pattern: dna?.pattern ?? 'none', mark: dna?.mark ?? 'none', build: dna?.build ?? 'normal',
71    armor: dna?.armor ?? false, eyes: dna?.eyes ?? 'round', extra: dna?.extra ?? 'none', shiny: p.shiny,
72    stage: p.stage, line: p.line, variant: p.variant,
73  }
74}
75
76/** e.g. BYTE-7K2F-9QXA-M3P1-Z: the name, then 13 characters of DNA in groups of four. */
77export function dnaCode(p: Pet): string {
78  const f = codeFields(p)
79  let n = 0n
80  for (const [key, bits] of FIELDS) n = (n << BigInt(bits)) | BigInt.asUintN(bits, BigInt(toNumber(f, key)))
81  let s = ''
82  for (let i = 0; i < 13; i++) {
83    s = B32[Number(n & 31n)]! + s
84    n >>= 5n
85  }
86  const name = p.name.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8) || 'PET'
87  return `${name}-${s.slice(0, 5)}-${s.slice(5, 9)}-${s.slice(9)}`
88}
89
90/** Reads a DNA code back into its fields; null if it is not one. */
91export function readCode(code: string): { name: string; fields: CodeFields } | null {
92  const m = /^([A-Z0-9]{1,8})-([0-9A-Z-]+)$/.exec(code.trim().toUpperCase())
93  if (!m) return null
94  const body = m[2]!.replace(/-/g, '')
95  if (body.length !== 13 || [...body].some(c => !B32.includes(c))) return null
96  let n = 0n
97  for (const c of body) n = (n << 5n) | BigInt(B32.indexOf(c))
98  const raw: Record<string, number> = {}
99  for (const [key, bits] of [...FIELDS].reverse()) {
100    raw[key] = Number(n & ((1n << BigInt(bits)) - 1n))
101    n >>= BigInt(bits)
102  }
103  const pick = <T,>(list: readonly T[], i: number): T | undefined => list[i]
104  const fields: CodeFields = {
105    seed: raw.seed! >>> 0,
106    lang1: raw.lang1 ? (LANG_NAMES[raw.lang1 - 1] ?? null) : null,
107    lang2: raw.lang2 ? (LANG_NAMES[raw.lang2 - 1] ?? null) : null,
108    pattern: pick(PATTERN, raw.pattern!) ?? 'none', mark: pick(MARK, raw.mark!) ?? 'none', build: pick(BUILD, raw.build!) ?? 'normal',
109    armor: raw.armor === 1, eyes: pick(EYES, raw.eyes!) ?? 'round', extra: pick(EXTRA, raw.extra!) ?? 'none', shiny: raw.shiny === 1,
110    stage: pick(STAGES, raw.stage!) ?? 'egg', line: pick(LINES, raw.line!) ?? null, variant: pick(VARIANTS, raw.variant!) ?? null,
111  }
112  return { name: m[1]!, fields }
113}
114
115// ── The picture.
116const SHORT: Record<string, string> = {
117  TypeScript: 'TS', JavaScript: 'JS', Python: 'PY', Kotlin: 'KOTLIN', Shell: 'SHELL', Elixir: 'ELIXIR', Haskell: 'HASKEL', Clojure: 'CLOJUR',
118}
119
120function langColour(name: string): Rgb {
121  const l = Object.values(LANGS).find(x => x.name === name)
122  if (!l) return DIM
123  const h = l.hue
124  const k = (n: number) => (n + h / 30) % 12
125  const a = 0.7 * Math.min(0.6, 0.4)
126  const f = (n: number) => 0.6 - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)))
127  return (Math.round(f(0) * 255) << 16) | (Math.round(f(8) * 255) << 8) | Math.round(f(4) * 255)
128}
129
130function fill(px: (Rgb | null)[], x: number, y: number, w: number, h: number, c: Rgb) {
131  for (let j = 0; j < h; j++) for (let i = 0; i < w; i++) {
132    const X = x + i
133    const Y = y + j
134    if (X >= 0 && Y >= 0 && X < CARD_W && Y < CARD_H) px[Y * CARD_W + X] = c
135  }
136}
137
138function blit(px: (Rgb | null)[], s: Sprite, x: number, y: number, scale: number) {
139  for (let j = 0; j < s.h * scale; j++) for (let i = 0; i < s.w * scale; i++) {
140    const c = s.px[Math.floor(j / scale) * s.w + Math.floor(i / scale)]
141    const X = x + i
142    const Y = y + j
143    if (c !== null && c !== undefined && X >= 0 && Y >= 0 && X < CARD_W && Y < CARD_H) px[Y * CARD_W + X] = c
144  }
145}
146
147const SKY: Record<string, [Rgb, Rgb, Rgb]> = {
148  spring: [0x9fd3f7, 0x5aa85e, 0x3e8948], summer: [0x73c2fb, 0x6abf54, 0x4a9a3e],
149  autumn: [0xf2b27a, 0x9aa04a, 0x7a8a3a], winter: [0xb8c4d0, 0xe8eef2, 0x8aa89a],
150}
151
152export function card(p: Pet, now: number): Sprite {
153  const px: (Rgb | null)[] = new Array(CARD_W * CARD_H).fill(INK)
154  const dna = dnaOf(p)
155  const accent = dna?.shiny ? GOLD : (dna?.palette.base ?? 0x5aa85e)
156  const text = (s: string, x: number, y: number, c: Rgb = TEXT, scale = 1) => drawText(px, CARD_W, CARD_H, s, x, y, c, scale)
157
158  // Frame.
159  fill(px, 0, 0, CARD_W, 2, accent)
160  fill(px, 0, CARD_H - 2, CARD_W, 2, accent)
161  fill(px, 0, 0, 2, CARD_H, accent)
162  fill(px, CARD_W - 2, 0, 2, CARD_H, accent)
163
164  // The monster in its season, three times its size.
165  const [sky, hill, grass] = SKY[seasonOf(now)]!
166  fill(px, 8, 8, 82, 92, sky)
167  fill(px, 8, 66, 82, 6, hill)
168  fill(px, 8, 72, 82, 28, grass)
169  const sprite = petFrames({ ...p, mood: undefined, asleepUntil: undefined, lastActive: now }, now)[0]!
170  blit(px, sprite, 8 + Math.round((82 - SIZE * 3) / 2), 100 - sprite.h * 3 + 2, 3)
171  fill(px, 8, 100, 82, 2, accent)
172  if (p.shiny) text('✦', 80, 11, GOLD)
173
174  // Who it is.
175  const x0 = 98
176  const name = p.name.toUpperCase().slice(0, 11)
177  text(name, x0, 9, TEXT, 2)
178  const form = formName(p).toUpperCase()
179  text(`LV ${level(p.xp)} ${form}`, x0, 28, GOLD)
180  const lineName = p.line ? LINE_NAMES[p.line].toUpperCase() : 'NO LINE YET'
181  text(`${lineName} · ${p.personality.toUpperCase()}${p.generation > 1 ? ` · GEN ${p.generation}` : ''}`, x0, 38, DIM)
182
183  // Languages.
184  const langs = languages(p).slice(0, 3)
185  if (langs.length) {
186    langs.forEach((l, i) => {
187      const y = 50 + i * 9
188      text(SHORT[l.name] ?? l.name.toUpperCase().slice(0, 6), x0, y, DIM)
189      fill(px, x0 + 40, y + 1, 70, 5, PANEL)
190      fill(px, x0 + 40, y + 1, Math.max(1, Math.round(70 * l.share)), 5, langColour(l.name))
191      text(`${Math.round(l.share * 100)}%`, x0 + 114, y, DIM)
192    })
193  } else text('LANGUAGES: NOT YET', x0, 50, DIM)
194
195  // Traits and record.
196  const r = rhythm(p)
197  const size = commitSize(p)
198  const traits = [
199    r.mark === 'moon' ? 'NIGHT OWL' : r.mark === 'sun' ? 'EARLY BIRD' : r.mark === 'star' ? 'STEADY' : null,
200    dna?.build === 'slim' ? 'SMALL COMMITS' : dna?.build === 'stout' ? 'BIG COMMITS' : size !== null ? 'MID COMMITS' : null,
201    dna?.armor ? 'ARMOURED' : null,
202  ].filter(Boolean).join(' · ')
203  text(traits || 'TRAITS: GROWING', x0, 80, TEXT)
204  text(`STREAK ${p.streak.days} · TESTS ${p.stats.tests}`, x0, 90, DIM)
205  text(`BOSSES ${p.stats.bossWins} · BADGES ${p.badges.length}/${BADGES.length}`, x0, 99, DIM)
206
207  // Footer: the DNA code.
208  fill(px, 2, 108, CARD_W - 4, 1, PANEL)
209  text(dnaCode(p), 8, 113, accent)
210  const tag = 'CLAUDE MONSTER'
211  text(tag, CARD_W - 8 - textWidth(tag), 113, DIM)
212  return { w: CARD_W, h: CARD_H, px }
213}
214
215// ── PNG: palette colour, stored (uncompressed) deflate, so no library is needed.
216const CRC = (() => {
217  const t = new Uint32Array(256)
218  for (let n = 0; n < 256; n++) {
219    let c = n
220    for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
221    t[n] = c >>> 0
222  }
223  return t
224})()
225
226function crc32(bytes: Uint8Array) {
227  let c = 0xffffffff
228  for (const b of bytes) c = CRC[(c ^ b) & 255]! ^ (c >>> 8)
229  return (c ^ 0xffffffff) >>> 0
230}
231
232function u32(n: number) {
233  return [(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]
234}
235
236function chunk(type: string, data: Uint8Array): number[] {
237  const body = new Uint8Array(4 + data.length)
238  for (let i = 0; i < 4; i++) body[i] = type.charCodeAt(i)
239  body.set(data, 4)
240  return [...u32(data.length), ...body, ...u32(crc32(body))]
241}
242
243/** A PNG of the sprite at scale, as base64. */
244export function pngBase64(s: Sprite, scale: number): string {
245  const W = s.w * scale
246  const H = s.h * scale
247  const colours: Rgb[] = []
248  const index = new Map<Rgb, number>()
249  const at = (c: Rgb | null) => {
250    const v = c ?? INK
251    let i = index.get(v)
252    if (i === undefined) {
253      i = colours.length
254      colours.push(v)
255      index.set(v, i)
256    }
257    return i
258  }
259  const raw = new Uint8Array((W + 1) * H)
260  for (let y = 0; y < H; y++) {
261    raw[y * (W + 1)] = 0
262    for (let x = 0; x < W; x++) raw[y * (W + 1) + 1 + x] = at(s.px[Math.floor(y / scale) * s.w + Math.floor(x / scale)] ?? null)
263  }
264  if (colours.length > 256) throw new Error('too many colours for a palette PNG')
265  // zlib with stored blocks.
266  const blocks: number[] = [0x78, 0x01]
267  for (let i = 0; i < raw.length; i += 65535) {
268    const len = Math.min(65535, raw.length - i)
269    blocks.push(i + len >= raw.length ? 1 : 0, len & 255, len >> 8, ~len & 255, (~len >> 8) & 255)
270    for (let j = 0; j < len; j++) blocks.push(raw[i + j]!)
271  }
272  let a = 1
273  let b = 0
274  for (const v of raw) {
275    a = (a + v) % 65521
276    b = (b + a) % 65521
277  }
278  blocks.push(...u32(((b << 16) | a) >>> 0))
279  const ihdr = new Uint8Array([...u32(W), ...u32(H), 8, 3, 0, 0, 0])
280  const plte = new Uint8Array(colours.flatMap(c => [(c >> 16) & 255, (c >> 8) & 255, c & 255]))
281  const bytes = new Uint8Array([
282    137, 80, 78, 71, 13, 10, 26, 10,
283    ...chunk('IHDR', ihdr), ...chunk('PLTE', plte), ...chunk('IDAT', new Uint8Array(blocks)), ...chunk('IEND', new Uint8Array()),
284  ])
285  return base64(bytes)
286}
287
hooks/dna.ts 158 lines
1// A monster's DNA: how your habits draw it. Languages pick its colours, the hours you keep its
2// mark, your commits its build, your tests its armour; a seed from who you are places its
3// pattern, so no two monsters come out alike.
4
5import type { Dna, Rgb } from './art'
6import { mix, type Pet, type VisitorDna } from './pet'
7
8export type { Dna }
9
10type Lang = { name: string; hue: number; sat?: number }
11
12/** File extensions to languages. Data and docs (json, yaml, md, lock files) do not count. */
13export const LANGS: Record<string, Lang> = {
14  ts: { name: 'TypeScript', hue: 214 }, tsx: { name: 'TypeScript', hue: 214 }, mts: { name: 'TypeScript', hue: 214 }, cts: { name: 'TypeScript', hue: 214 },
15  js: { name: 'JavaScript', hue: 50 }, jsx: { name: 'JavaScript', hue: 50 }, mjs: { name: 'JavaScript', hue: 50 }, cjs: { name: 'JavaScript', hue: 50 },
16  py: { name: 'Python', hue: 207 }, ipynb: { name: 'Python', hue: 207 },
17  rs: { name: 'Rust', hue: 22 }, go: { name: 'Go', hue: 186 }, java: { name: 'Java', hue: 8 },
18  kt: { name: 'Kotlin', hue: 275 }, kts: { name: 'Kotlin', hue: 275 }, swift: { name: 'Swift', hue: 14 },
19  rb: { name: 'Ruby', hue: 352 }, php: { name: 'PHP', hue: 240 }, cs: { name: 'C#', hue: 265 },
20  c: { name: 'C', hue: 220, sat: 0.35 }, h: { name: 'C', hue: 220, sat: 0.35 },
21  cpp: { name: 'C++', hue: 330 }, cc: { name: 'C++', hue: 330 }, hpp: { name: 'C++', hue: 330 },
22  css: { name: 'CSS', hue: 318 }, scss: { name: 'CSS', hue: 318 }, sass: { name: 'CSS', hue: 318 }, less: { name: 'CSS', hue: 318 },
23  html: { name: 'HTML', hue: 12 }, vue: { name: 'Vue', hue: 153 }, svelte: { name: 'Svelte', hue: 16 },
24  sh: { name: 'Shell', hue: 110 }, bash: { name: 'Shell', hue: 110 }, zsh: { name: 'Shell', hue: 110 }, fish: { name: 'Shell', hue: 110 },
25  sql: { name: 'SQL', hue: 196 }, dart: { name: 'Dart', hue: 192 }, ex: { name: 'Elixir', hue: 278 }, exs: { name: 'Elixir', hue: 278 },
26  hs: { name: 'Haskell', hue: 258 }, lua: { name: 'Lua', hue: 236 }, zig: { name: 'Zig', hue: 38 }, scala: { name: 'Scala', hue: 0 },
27  r: { name: 'R', hue: 205 }, jl: { name: 'Julia', hue: 290 }, ml: { name: 'OCaml', hue: 28 }, clj: { name: 'Clojure', hue: 128 },
28}
29
30/** The extension of a path, lowercased, if it names a language; nothing else of the path is kept. */
31export function extOf(path: string): string | undefined {
32  const m = /\.([A-Za-z0-9]+)$/.exec(path)
33  const ext = m?.[1]?.toLowerCase()
34  return ext && LANGS[ext] ? ext : undefined
35}
36
37function hsl(h: number, s: number, l: number): Rgb {
38  const k = (n: number) => (n + h / 30) % 12
39  const a = s * Math.min(l, 1 - l)
40  const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)))
41  return (Math.round(f(0) * 255) << 16) | (Math.round(f(8) * 255) << 8) | Math.round(f(4) * 255)
42}
43
44export type LangShare = { name: string; hue: number; sat: number; share: number }
45
46/** Languages by share of edits, merged by name (ts and tsx are one TypeScript). */
47export function languages(p: Pet): LangShare[] {
48  const byName = new Map<string, LangShare>()
49  let total = 0
50  for (const [ext, n] of Object.entries(p.habits.langs)) {
51    const l = LANGS[ext]
52    if (!l) continue
53    total += n
54    const cur = byName.get(l.name) ?? { name: l.name, hue: l.hue, sat: l.sat ?? 1, share: 0 }
55    cur.share += n
56    byName.set(l.name, cur)
57  }
58  return [...byName.values()].map(l => ({ ...l, share: total ? l.share / total : 0 })).sort((a, b) => b.share - a.share)
59}
60
61/** The hour band most of the activity falls in, and how concentrated it is. */
62export function rhythm(p: Pet): { mark: Dna['mark']; peak: number; samples: number } {
63  const hours = p.habits.hours
64  const samples = hours.reduce((a, b) => a + b, 0)
65  if (samples < 30) return { mark: 'none', peak: -1, samples }
66  const night = [22, 23, 0, 1, 2, 3, 4].reduce((n, h) => n + (hours[h] ?? 0), 0) / samples
67  const morning = [5, 6, 7, 8, 9, 10].reduce((n, h) => n + (hours[h] ?? 0), 0) / samples
68  const peak = hours.indexOf(Math.max(...hours))
69  // Concentrated within a working day: the busiest 9 consecutive hours hold most of it.
70  let best = 0
71  for (let s = 0; s < 24; s++) {
72    let n = 0
73    for (let i = 0; i < 9; i++) n += hours[(s + i) % 24] ?? 0
74    best = Math.max(best, n)
75  }
76  const mark: Dna['mark'] = night >= 0.35 ? 'moon' : morning >= 0.35 ? 'sun' : best / samples >= 0.85 ? 'star' : 'none'
77  return { mark, peak, samples }
78}
79
80/** Average edits per commit, once there are a few commits to go on. */
81export function commitSize(p: Pet): number | null {
82  return p.stats.commits >= 3 ? p.habits.committedEdits / p.stats.commits : null
83}
84
85const PATTERNS: Dna['pattern'][] = ['stripes', 'spots', 'patch']
86
87/** The DNA your habits have written so far; nothing until it has seen enough to say. */
88export function dnaOf(p: Pet): Dna | undefined {
89  const langs = languages(p)
90  const main = langs[0]
91  if (!main || p.habits.edits < 10) return undefined
92  const seed = p.seed ?? mix(p.born, 1)
93  const jitter = ((seed % 1000) / 1000 - 0.5) * 0.08 // a person's own shade, ±4% lightness
94  // How dominant the main language is decides how vivid the colour is: 40% is muted, 95% is bold.
95  const vivid = 0.35 + Math.min(1, Math.max(0, (main.share - 0.4) / 0.55)) * 0.55
96  const s = vivid * main.sat
97  const hue = (main.hue + ((seed >> 10) % 17) - 8 + 360) % 360 // and its own tint, ±8°
98  const palette = { base: hsl(hue, s, 0.55 + jitter), dark: hsl(hue, s * 0.9, 0.32 + jitter), light: hsl(hue, s * 0.8, 0.76 + jitter) }
99  const second = langs[1] && langs[1].share >= 0.12 ? langs[1] : undefined
100  const accentHue = second ? second.hue : main.name === 'Python' ? 48 : (main.hue + 150 + (seed % 60)) % 360
101  const accent = hsl(accentHue, 0.75, 0.6)
102  const pattern: Dna['pattern'] = second || main.name === 'Python' ? PATTERNS[seed % PATTERNS.length]! : 'none'
103  const { mark } = rhythm(p)
104  const size = commitSize(p)
105  const build: Dna['build'] = size === null ? 'normal' : size <= 6 ? 'slim' : size >= 20 ? 'stout' : 'normal'
106  const passRate = p.habits.testRuns ? p.stats.tests / p.habits.testRuns : 0
107  const armor = p.stats.tests >= 10 && passRate >= 0.7
108  const errorRate = p.habits.toolCalls ? p.stats.errors / p.habits.toolCalls : 1
109  const eyes: Dna['eyes'] = mark === 'moon' ? 'sleepy' : p.habits.toolCalls >= 100 && errorRate < 0.05 ? 'sharp' : 'round'
110  const t = p.traits
111  const traitSum = Math.max(1, t.shell + t.code + t.agents + t.web)
112  const extra: Dna['extra'] = p.streak.days >= 30 ? 'scarf' : t.web / traitSum >= 0.15 ? 'glasses' : 'none'
113  return { palette, accent, pattern, mark, build, armor, eyes, extra, shiny: p.shiny, seed }
114}
115
116/** Why it looks the way it does, one line per trait, for the Style tab. */
117export function describe(p: Pet): string[] {
118  const langs = languages(p)
119  const dna = dnaOf(p)
120  if (!dna) {
121    const need = Math.max(0, 10 - p.habits.edits)
122    return [`Its colours appear after ${need} more file edit${need === 1 ? '' : 's'} with Claude.`]
123  }
124  const pct = (n: number) => `${Math.round(n * 100)}%`
125  const main = langs[0]!
126  const second = langs[1] && langs[1].share >= 0.12 ? langs[1] : undefined
127  const r = rhythm(p)
128  const size = commitSize(p)
129  const lines = [
130    `Colour: ${main.name} ${pct(main.share)}${main.share >= 0.85 ? ' (bold)' : main.share < 0.55 ? ' (muted)' : ''}`,
131    `Pattern: ${dna.pattern === 'none' ? 'none (one main language)' : `${dna.pattern}${second ? ` in ${second.name} colours (${pct(second.share)})` : ''}`}, placed by your seed`,
132    `Mark: ${dna.mark === 'moon' ? 'moon, a night owl' : dna.mark === 'sun' ? 'sun, an early bird' : dna.mark === 'star' ? 'star, steady hours' : r.samples < 30 ? 'not yet (needs more activity)' : 'none, irregular hours'}${r.peak >= 0 ? ` · busiest at ${r.peak}:00` : ''}`,
133    `Build: ${dna.build}${size === null ? ' (after 3 commits)' : ` · ${size.toFixed(1)} edits per commit`}`,
134    `Armour: ${dna.armor ? `yes · ${p.stats.tests} test runs passed` : `not yet · needs 10 passing test runs mostly green (${p.stats.tests} so far)`}`,
135    `Eyes: ${dna.eyes}${dna.eyes === 'sharp' ? ' · few errors' : dna.eyes === 'sleepy' ? ' · late nights' : ''}`,
136    `Extra: ${dna.extra === 'scarf' ? 'scarf, a 30-day streak' : dna.extra === 'glasses' ? 'glasses, lots of research' : 'none yet'}`,
137  ]
138  if (dna.shiny) lines.push('Shiny: yes! A one-in-256 colouring ✦')
139  return lines
140}
141
142/** Someone else's DNA, from their code: the share of each language is not in the code, so colours are mid-vivid. */
143export function dnaFromCode(v: VisitorDna): Dna | undefined {
144  const main = v.lang1 ? Object.values(LANGS).find(l => l.name === v.lang1) : undefined
145  if (!main) return undefined
146  const seed = v.seed
147  const jitter = ((seed % 1000) / 1000 - 0.5) * 0.08
148  const hue = (main.hue + ((seed >> 10) % 17) - 8 + 360) % 360
149  const s = 0.68 * (main.sat ?? 1)
150  const second = v.lang2 ? Object.values(LANGS).find(l => l.name === v.lang2) : undefined
151  const accentHue = second ? second.hue : main.name === 'Python' ? 48 : (main.hue + 150 + (seed % 60)) % 360
152  return {
153    palette: { base: hsl(hue, s, 0.55 + jitter), dark: hsl(hue, s * 0.9, 0.32 + jitter), light: hsl(hue, s * 0.8, 0.76 + jitter) },
154    accent: hsl(accentHue, 0.75, 0.6),
155    pattern: v.pattern, mark: v.mark, build: v.build, armor: v.armor, eyes: v.eyes, extra: v.extra, shiny: v.shiny, seed,
156  }
157}
158
hooks/habitat.ts 278 lines
1// The habitat as layers: an animated background (sky, season, weather, decorations, holidays),
2// the pet strolling over it, and a boss when one is being fought.
3
4import { DECOR_SPRITES, SIZE, ball, bossSprite, bowl, bush, cake, cookie, heart, mess, note, pumpkin, star, sweat, xmasTree, zz, type Rgb, type Sprite } from './art'
5import { face, type BossKind, type Pet } from './pet'
6import { FRAME_MS, paths, petFrames, visitorFrames, type Hunt } from './render'
7
8export const HAB_W = 72
9export const HAB_H = 40
10const FRAMES = 4
11/** One stroll back and forth. */
12export const WALK_MS = 18_000
13
14export type Season = 'spring' | 'summer' | 'autumn' | 'winter'
15export type Weather = 'clear' | 'cloudy' | 'rain' | 'snow' | 'petals' | 'leaves'
16
17export type Scene = {
18  bg: Sprite[]
19  pet: Sprite[]
20  petX: number
21  petY: number
22  /** How far it strolls each way; 0 stands still. */
23  walk: number
24  boss?: { frames: Sprite[]; x: number; y: number }
25  /** A friend's monster, strolling opposite yours. */
26  visitor?: { frames: Sprite[]; x: number; y: number }
27  season: Season
28  weather: Weather
29  holiday: string | null
30}
31
32export function seasonOf(at: number): Season {
33  const m = new Date(at).getMonth() + 1
34  return m >= 3 && m <= 5 ? 'spring' : m >= 6 && m <= 8 ? 'summer' : m >= 9 && m <= 11 ? 'autumn' : 'winter'
35}
36
37function hashDay(at: number) {
38  const d = new Date(at)
39  let h = d.getFullYear() * 372 + d.getMonth() * 31 + d.getDate()
40  h = Math.imul(h ^ (h >>> 13), 0x5bd1e995)
41  return ((h ^ (h >>> 15)) >>> 0) / 4294967296
42}
43
44/** Today's weather: the same all day, different each day, fitting the season. */
45export function weatherOf(at: number): Weather {
46  const s = seasonOf(at)
47  const r = hashDay(at)
48  if (r < 0.45) return 'clear'
49  if (r < 0.7) return 'cloudy'
50  if (r < 0.85) return s === 'winter' ? 'snow' : 'rain'
51  return s === 'spring' ? 'petals' : s === 'autumn' ? 'leaves' : s === 'winter' ? 'snow' : 'clear'
52}
53
54export function holidayOf(p: Pet, at: number): string | null {
55  const d = new Date(at)
56  const m = d.getMonth() + 1
57  const day = d.getDate()
58  const born = new Date(p.born)
59  if (at - p.born > 24 * 3600_000 && born.getMonth() === d.getMonth() && born.getDate() === day) return 'birthday'
60  if (m === 10 && day >= 25) return 'halloween'
61  if (m === 12 && day >= 20 && day <= 26) return 'christmas'
62  if ((m === 12 && day === 31) || (m === 1 && day === 1)) return 'newyear'
63  return null
64}
65
66function sky(hour: number, weather: Weather, tucked: boolean): [Rgb, Rgb] {
67  if (tucked || hour < 6 || hour >= 20) return weather === 'cloudy' || weather === 'rain' ? [0x1f2433, 0x2d3550] : [0x29366f, 0x3b5dc9]
68  if (weather === 'cloudy' || weather === 'rain' || weather === 'snow') return [0x8a9bb0, 0xb8c4d0]
69  if (hour >= 17) return [0xef7d57, 0xffcd75]
70  return [0x73c2fb, 0xb5e1ff]
71}
72
73const GROUND: Record<Season, [Rgb, Rgb, Rgb]> = {
74  spring: [0x3e8948, 0x5aa85e, 0x2d6b3a],
75  summer: [0x4a9a3e, 0x6abf54, 0x2f7a2c],
76  autumn: [0x7a8a3a, 0x9aa04a, 0x5a6a2a],
77  winter: [0x6a8a7a, 0x8aa89a, 0x4a6a5a],
78}
79
80function blank(c: Rgb | null = null): (Rgb | null)[] {
81  return new Array(HAB_W * HAB_H).fill(c)
82}
83
84function stamp(px: (Rgb | null)[], s: Sprite, x: number, y: number, w = HAB_W, h = HAB_H) {
85  for (let j = 0; j < s.h; j++) {
86    for (let i = 0; i < s.w; i++) {
87      const c = s.px[j * s.w + i]
88      const X = x + i
89      const Y = y + j
90      if (c !== null && c !== undefined && X >= 0 && Y >= 0 && X < w && Y < h) px[Y * w + X] = c
91    }
92  }
93}
94
95const DECOR_AT: Record<keyof typeof DECOR_SPRITES, [number, number]> = {
96  plant: [2, 27], lamp: [66, 26], poster: [2, 18], rug: [30, 34], bed: [52, 30], toybox: [44, 30], desk: [8, 27], fountain: [58, 21],
97}
98
99export function habitat(p: Pet, now: number, hour: number, opts: { hunt?: Hunt | null; boss?: { kind: BossKind; hit: boolean } | null } = {}): Scene {
100  const tucked = (p.asleepUntil ?? 0) > now
101  const season = seasonOf(now)
102  const holiday = holidayOf(p, now)
103  const weather: Weather = holiday === 'christmas' ? 'snow' : weatherOf(now)
104  const night = tucked || hour < 6 || hour >= 20
105  const [top, bottom] = sky(hour, weather, tucked)
106  const [grass, hill, dark] = GROUND[season]
107  const f = face(p, now)
108
109  // The still part of the background.
110  const base = blank()
111  for (let y = 0; y < HAB_H; y++) for (let x = 0; x < HAB_W; x++) base[y * HAB_W + x] = y < 14 ? top : y < 28 ? bottom : grass
112  for (let x = 0; x < HAB_W; x++) {
113    const h = Math.round(26 + Math.sin(x / 9) * 2 + Math.sin(x / 4) * 0.8)
114    for (let y = h; y < 28; y++) base[y * HAB_W + x] = hill
115    for (let y = 28; y < HAB_H; y++) if ((x * 7 + y * 13) % 17 === 0) base[y * HAB_W + x] = dark
116    base[28 * HAB_W + x] = dark
117    if (weather === 'snow') for (let y = 28; y < HAB_H; y++) if ((x * 5 + y * 11) % 4 !== 0) base[y * HAB_W + x] = 0xe8eef2
118  }
119  if (season === 'spring') for (const [x, y] of [[6, 33], [17, 37], [49, 35], [63, 38], [27, 31]] as const) base[y * HAB_W + x] = 0xf4a0b0
120  if (season === 'autumn') for (const [x, y] of [[9, 35], [21, 32], [40, 38], [55, 33], [67, 36]] as const) base[y * HAB_W + x] = 0xef7d57
121  const orb = night ? 0xf4f4f4 : 0xffcd75
122  if (weather !== 'cloudy' && weather !== 'rain') for (let y = -3; y <= 3; y++) for (let x = -3; x <= 3; x++) if (x * x + y * y <= 9) base[(6 + y) * HAB_W + 62 + x] = orb
123  if (night) for (const [x, y] of [[8, 4], [20, 8], [33, 3], [47, 7], [55, 2]] as const) base[y * HAB_W + x] = 0xf4f4f4
124  const cloud = weather === 'cloudy' || weather === 'rain' ? 0xd6dce4 : 0xf4f4f4
125  const clouds = weather === 'cloudy' || weather === 'rain' ? [[10, 5], [30, 8], [50, 4], [64, 9]] : night ? [] : [[12, 6], [36, 9]]
126  for (const [cx, cy] of clouds) for (let i = -5; i <= 5; i++) for (let j = -1; j <= 1; j++) if (Math.abs(i) + Math.abs(j) * 3 < 7) base[(cy! + j) * HAB_W + cx! + i] = cloud
127
128  // Things on the ground.
129  const full = (p.cooldowns.feed ?? 0) > now
130  stamp(base, bowl(full || p.hunger > 70), 14, 32)
131  if ((p.cooldowns.play ?? 0) > now - 10 * 60_000 && p.stats.played > 0) stamp(base, ball(), 22, 34)
132  for (let i = 0; i < p.mess; i++) stamp(base, mess(), 34 + i * 6, 35 - (i % 2))
133  if (holiday === 'halloween') {
134    stamp(base, pumpkin, 24, 31)
135    stamp(base, pumpkin, 60, 33)
136  }
137  if (holiday === 'christmas') stamp(base, xmasTree, 62, 25)
138  if (holiday === 'birthday') stamp(base, cake, 26, 32)
139
140  const owned = new Set(p.decor)
141  const bg: Sprite[] = []
142  for (let i = 0; i < FRAMES; i++) {
143    const px = base.slice()
144    for (const d of p.decor) {
145      const frames = DECOR_SPRITES[d]
146      const [x, y] = DECOR_AT[d]
147      stamp(px, frames[i % frames.length]!, x, y)
148    }
149    if (opts.hunt) {
150      const h = opts.hunt
151      for (let b = 0; b < 3; b++) {
152        const bx = 8 + b * 22
153        stamp(px, bush(), bx, 22)
154        if (h.picked !== null && b === h.treat) stamp(px, cookie(), bx + 2, 17)
155        if (h.picked === b && b !== h.treat) for (let k = 0; k < 3; k++) px[(19 + k) * HAB_W + bx + 4 + k] = 0xe24b4a
156      }
157    }
158    particles(px, weather, holiday, night, i)
159    bg.push({ w: HAB_W, h: HAB_H, px })
160  }
161
162  // The pet, with what it feels drawn beside it.
163  const frames = petFrames(p, now)
164  const ph = frames[0]!.h
165  const pet = frames.map((s, i) => {
166    const W = SIZE + 8
167    const px = new Array<Rgb | null>(W * ph).fill(null)
168    stamp(px, s, 0, 0, W, ph)
169    const fx = SIZE - 2
170    const fy = 6 - (i % 2)
171    if (f === 'sleep' || f === 'sleepy') stamp(px, zz(), fx + (i % 2), fy - i, W, ph)
172    else if (f === 'love') stamp(px, heart(), fx, fy - i, W, ph)
173    else if (f === 'cheer') stamp(px, note(), fx + (i % 2) * 2, fy - i, W, ph)
174    else if (f === 'evolve') for (const [x, y] of [[0, 8 + i], [SIZE, 12 - i], [4, 4 - i]] as const) stamp(px, star(), x, y, W, ph)
175    else if (f === 'ouch' || f === 'sick' || f === 'sweat' || f === 'lose') stamp(px, sweat(), 4, 10 + (i % 2), W, ph)
176    else if (f === 'win') for (const [x, y] of [[2, 6 - i], [SIZE - 4, 8 - i]] as const) stamp(px, heart(), x, y, W, ph)
177    else if (f === 'wave') stamp(px, star(), fx + (i % 2), fy, W, ph)
178    return { w: W, h: ph, px }
179  })
180
181  const asleep = f === 'sleep'
182  const fighting = !!opts.boss
183  let petX = Math.round(HAB_W / 2 - SIZE / 2)
184  let petY = HAB_H - ph - 4
185  let walk = asleep || opts.hunt || fighting ? 0 : 14
186  if (asleep && owned.has('bed')) {
187    petX = DECOR_AT.bed[0] - 6
188    petY = DECOR_AT.bed[1] + 4 - ph
189    walk = 0
190  }
191  if (fighting) petX = 4
192  const hosting = p.visitor && p.visitor.until > now && !fighting && !opts.hunt
193  if (hosting && !(asleep && owned.has('bed'))) {
194    // Side by side: each strolls a little, never into the other.
195    petX = 6
196    walk = asleep ? 0 : 5
197  }
198
199  const scene: Scene = { bg, pet, petX, petY, walk, season, weather, holiday }
200  if (hosting) {
201    const vf = visitorFrames(p.visitor!.dna)
202    scene.visitor = { frames: vf, x: HAB_W - SIZE - 6, y: HAB_H - vf[0]!.h - 4 }
203  }
204  if (opts.boss) {
205    const bf = [0, 1, 2, 3].map(i => bossSprite(opts.boss!.kind, i, opts.boss!.hit && i % 2 === 1))
206    scene.boss = { frames: bf, x: HAB_W - bf[0]!.w - 2, y: HAB_H - bf[0]!.h - 3 }
207  }
208  return scene
209}
210
211function particles(px: (Rgb | null)[], weather: Weather, holiday: string | null, night: boolean, i: number) {
212  const set = (x: number, y: number, c: Rgb) => {
213    if (x >= 0 && y >= 0 && x < HAB_W && y < HAB_H) px[y * HAB_W + x] = c
214  }
215  const drops = (n: number, fn: (x: number, y: number, k: number) => void) => {
216    for (let k = 0; k < n; k++) {
217      const x = (k * 37 + 11) % HAB_W
218      const y = ((k * 23 + i * 5) % (HAB_H - 6))
219      fn(x, y, k)
220    }
221  }
222  if (weather === 'rain') drops(22, (x, y) => { set(x, y, 0x85b7eb); set(x, y + 1, 0x85b7eb) })
223  if (weather === 'snow') drops(18, (x, y, k) => set(x + ((i + k) % 2), y, 0xffffff))
224  if (weather === 'petals') drops(10, (x, y, k) => set(x + ((i + k) % 3) - 1, y, 0xf4a0b0))
225  if (weather === 'leaves') drops(10, (x, y, k) => set(x + ((i + k) % 3) - 1, y, k % 2 ? 0xef7d57 : 0xe8a33d))
226  if (holiday === 'newyear' && night) {
227    const bursts = [[14, 8], [40, 5], [58, 10]] as const
228    const [bx, by] = bursts[i % bursts.length]!
229    const c = [0xffcd75, 0xf4a0b0, 0x73eff7][i % 3]!
230    for (const [dx, dy] of [[0, -3], [0, 3], [-3, 0], [3, 0], [-2, -2], [2, 2], [-2, 2], [2, -2]] as const) set(bx + dx, by + dy, c)
231  }
232}
233
234function walkOffset(scene: Scene, t: number) {
235  return scene.walk ? Math.round(Math.sin((t / WALK_MS) * Math.PI * 2) * scene.walk) : 0
236}
237
238/** The whole picture at time t: what the terminal draws each frame. */
239export function compose(scene: Scene, t: number): Sprite {
240  const i = Math.floor(t / FRAME_MS) % FRAMES
241  const px = scene.bg[i]!.px.slice()
242  const pet = scene.pet[i]!
243  stamp(px, pet, scene.petX + walkOffset(scene, t), scene.petY)
244  if (scene.boss) stamp(px, scene.boss.frames[i]!, scene.boss.x, scene.boss.y)
245  if (scene.visitor) stamp(px, scene.visitor.frames[(i + 2) % FRAMES]!, scene.visitor.x - walkOffset(scene, t), scene.visitor.y)
246  return { w: HAB_W, h: HAB_H, px }
247}
248
249/** Four still frames, for tests and for anything that cannot animate the stroll. */
250export function habitatFrames(p: Pet, now: number, hour: number, hunt?: Hunt | null): Sprite[] {
251  const scene = habitat(p, now, hour, { hunt })
252  return [0, 1, 2, 3].map(i => compose(scene, i * FRAME_MS))
253}
254
255/** The desktop picture: background frames in turn, the pet strolling smoothly over them. */
256export function sceneSvg(scene: Scene, scale: number): string {
257  const n = FRAMES
258  const dur = n * FRAME_MS
259  const times = Array.from({ length: n }, (_, i) => (i / n).toFixed(4)).join(';')
260  const cycle = (frames: Sprite[]) =>
261    frames
262      .map((f, i) => {
263        const values = frames.map((_, j) => (j === i ? 'visible' : 'hidden')).join(';')
264        return `<g visibility="${i === 0 ? 'visible' : 'hidden'}"><animate attributeName="visibility" values="${values}" keyTimes="${times}" dur="${dur}ms" calcMode="discrete" repeatCount="indefinite"/>${paths(f)}</g>`
265      })
266      .join('')
267  const w = scene.walk
268  const stroll = w
269    ? `<animateTransform attributeName="transform" type="translate" values="${scene.petX} ${scene.petY};${scene.petX + w} ${scene.petY};${scene.petX} ${scene.petY};${scene.petX - w} ${scene.petY};${scene.petX} ${scene.petY}" keyTimes="0;0.25;0.5;0.75;1" calcMode="spline" keySplines="0.4 0 0.6 1;0.4 0 0.6 1;0.4 0 0.6 1;0.4 0 0.6 1" dur="${WALK_MS}ms" repeatCount="indefinite"/>`
270    : ''
271  const boss = scene.boss ? `<g transform="translate(${scene.boss.x} ${scene.boss.y})">${cycle(scene.boss.frames)}</g>` : ''
272  const v = scene.visitor
273  const visitor = v
274    ? `<g transform="translate(${v.x} ${v.y})">${w ? `<animateTransform attributeName="transform" type="translate" values="${v.x} ${v.y};${v.x - w} ${v.y};${v.x} ${v.y};${v.x + w} ${v.y};${v.x} ${v.y}" keyTimes="0;0.25;0.5;0.75;1" calcMode="spline" keySplines="0.4 0 0.6 1;0.4 0 0.6 1;0.4 0 0.6 1;0.4 0 0.6 1" dur="${WALK_MS}ms" repeatCount="indefinite"/>` : ''}${cycle([...v.frames.slice(2), ...v.frames.slice(0, 2)])}</g>`
275    : ''
276  return `<svg xmlns="http://www.w3.org/2000/svg" width="${HAB_W * scale}" height="${HAB_H * scale}" viewBox="0 0 ${HAB_W} ${HAB_H}" shape-rendering="crispEdges">${cycle(scene.bg)}<g transform="translate(${scene.petX} ${scene.petY})">${stroll}${cycle(scene.pet)}</g>${boss}${visitor}</svg>`
277}
278
hooks/art.ts 560 lines
1// Draws the monster procedurally: a body, its line's features, eyes and mouth for its mood,
2// then an outline and shading. Every stage and line comes out in one consistent style.
3
4import type { BossKind, Decor, Hat, Line, Stage, Variant } from './pet'
5
6export type Rgb = number
7export type Sprite = { readonly w: number; readonly h: number; readonly px: readonly (Rgb | null)[] }
8
9export const INK = 0x1a1c2c
10const WHITE = 0xf4f4f4
11const GOLD = 0xffcd75
12const GOLD_DARK = 0xe8a33d
13const PINK = 0xf4a0b0
14const SILVER = 0x94b0c2
15const RED = 0xe24b4a
16
17export type Palette = { base: Rgb; dark: Rgb; light: Rgb }
18
19const SHADOW: Record<Line, Palette> = {
20  forge: { base: 0x8a3a3a, dark: 0x4a1a2a, light: 0xc96a4a },
21  scribe: { base: 0x4a3a6a, dark: 0x2a1a3a, light: 0x7a5aa0 },
22  summoner: { base: 0x2a4a7a, dark: 0x1a2a4a, light: 0x4a7aa0 },
23  wanderer: { base: 0x2a6a4a, dark: 0x1a3a2a, light: 0x5a9a6a },
24}
25
26const PALETTES: Record<Line | 'baby', Palette> = {
27  baby: { base: 0x8fd694, dark: 0x3e8948, light: 0xc9f2b5 },
28  forge: { base: 0xef7d57, dark: 0xb13e53, light: 0xffcd75 },
29  scribe: { base: 0x9b59d0, dark: 0x5d275d, light: 0xd9b8f0 },
30  summoner: { base: 0x41a6f6, dark: 0x3b5dc9, light: 0x73eff7 },
31  wanderer: { base: 0x38b764, dark: 0x257179, light: 0xa7f070 },
32}
33
34export type Eyes = 'open' | 'closed' | 'happy' | 'x' | 'dizzy'
35export type Mouth = 'smile' | 'open' | 'frown' | 'flat' | 'o'
36export type Pose = { eyes: Eyes; mouth: Mouth; squash: boolean; flicker: boolean }
37
38class Grid {
39  px: (Rgb | null)[]
40  constructor(readonly w: number, readonly h: number) {
41    this.px = new Array(w * h).fill(null)
42  }
43  get(x: number, y: number) {
44    return x >= 0 && y >= 0 && x < this.w && y < this.h ? this.px[y * this.w + x]! : null
45  }
46  set(x: number, y: number, c: Rgb | null) {
47    x = Math.round(x)
48    y = Math.round(y)
49    if (x >= 0 && y >= 0 && x < this.w && y < this.h) this.px[y * this.w + x] = c
50  }
51  ellipse(cx: number, cy: number, rx: number, ry: number, c: Rgb) {
52    for (let y = Math.floor(cy - ry); y <= Math.ceil(cy + ry); y++) {
53      for (let x = Math.floor(cx - rx); x <= Math.ceil(cx + rx); x++) {
54        const dx = (x + 0.5 - cx) / rx
55        const dy = (y + 0.5 - cy) / ry
56        if (dx * dx + dy * dy <= 1) this.set(x, y, c)
57      }
58    }
59  }
60  tri(x: number, y: number, h: number, dir: 1 | -1, c: Rgb) {
61    // A small upward spike: h rows, widening by one each row.
62    for (let j = 0; j < h; j++) for (let i = 0; i <= j; i++) this.set(x + dir * i, y + j, c)
63  }
64  outline() {
65    const add: [number, number][] = []
66    for (let y = 0; y < this.h; y++) {
67      for (let x = 0; x < this.w; x++) {
68        if (this.get(x, y) !== null) continue
69        const near = [this.get(x - 1, y), this.get(x + 1, y), this.get(x, y - 1), this.get(x, y + 1)]
70        if (near.some(c => c !== null && c !== INK)) add.push([x, y])
71      }
72    }
73    for (const [x, y] of add) this.set(x, y, INK)
74  }
75  sprite(): Sprite {
76    return { w: this.w, h: this.h, px: this.px }
77  }
78}
79
80export const SIZE = 24
81
82const BODY: Record<Stage, { rx: number; ry: number }> = {
83  egg: { rx: 5, ry: 6.5 },
84  baby: { rx: 4.5, ry: 4 },
85  child: { rx: 5.5, ry: 5 },
86  adult: { rx: 7, ry: 6.5 },
87  ultimate: { rx: 8, ry: 7.5 },
88}
89
90function egg(pose: Pose, cracked: boolean): Sprite {
91  const g = new Grid(SIZE, SIZE)
92  const cx = 12
93  const cy = 14 + (pose.squash ? 0.5 : 0)
94  g.ellipse(cx, cy, 5, 6.5, WHITE)
95  for (let y = 0; y < SIZE; y++) {
96    for (let x = 0; x < SIZE; x++) {
97      if (g.get(x, y) === WHITE && (x - cx) / 5 + (y - cy) / 6.5 > 0.8) g.set(x, y, 0xc2c3c7)
98    }
99  }
100  for (const [x, y] of [[10, 11], [11, 11], [14, 14], [15, 14], [15, 15], [9, 16], [10, 16], [13, 18]] as const) g.set(x, y, GOLD)
101  if (cracked) for (const [x, y] of [[9, 13], [10, 12], [11, 13], [12, 12], [13, 13], [14, 12], [15, 13]] as const) g.set(x, y, INK)
102  g.outline()
103  return g.sprite()
104}
105
106/** What a person's habits make of their monster, drawn over its line and stage (see dna.ts). */
107export type Dna = {
108  palette: Palette
109  accent: Rgb
110  pattern: 'none' | 'stripes' | 'spots' | 'patch'
111  mark: 'none' | 'moon' | 'sun' | 'star'
112  build: 'slim' | 'normal' | 'stout'
113  armor: boolean
114  eyes: 'round' | 'sharp' | 'sleepy'
115  extra: 'none' | 'glasses' | 'scarf'
116  shiny: boolean
117  /** From your identity: where the pattern falls. */
118  seed: number
119}
120
121const SHINY: Palette = { base: 0xf2d16b, dark: 0xb8862b, light: 0xfff3c4 }
122const SCARF = 0xd84a4a
123
124export function monster(stage: Stage, line: Line | null, pose: Pose, opts: { cracked?: boolean; variant?: Variant | null; hat?: Hat | null; dna?: Dna } = {}): Sprite {
125  if (stage === 'egg') return egg(pose, opts.cracked ?? false)
126  const grown = stage === 'adult' || stage === 'ultimate'
127  const dna = stage === 'baby' ? undefined : opts.dna
128  const linePal = line && grown && opts.variant === 'shadow' ? SHADOW[line] : PALETTES[stage === 'baby' || !line ? 'baby' : line]
129  // A shadow form keeps its darker line colours unless it is shiny; otherwise habits paint it.
130  const pal = dna ? (dna.shiny ? SHINY : opts.variant === 'shadow' && grown ? darken(dna.palette) : dna.palette) : linePal
131  const g = new Grid(SIZE, SIZE)
132  const b0 = BODY[stage]
133  const rx = b0.rx * (dna?.build === 'slim' ? 0.84 : dna?.build === 'stout' ? 1.16 : 1)
134  const ry0 = b0.ry * (dna?.build === 'slim' ? 1.06 : dna?.build === 'stout' ? 0.94 : 1)
135  const ry = pose.squash ? ry0 - 0.6 : ry0
136  const rxs = pose.squash ? rx + 0.5 : rx
137  const floats = line === 'scribe' && stage !== 'baby'
138  const cx = 12
139  const cy = SIZE - 2 - ry - (floats ? 2 : 1)
140  const big = stage === 'adult' || stage === 'ultimate'
141  const top = Math.round(cy - ry)
142
143  // Behind the body.
144  if (line === 'wanderer' && stage !== 'baby') {
145    // Wings: soft white blobs tucked against each side, flapping on the flicker frame.
146    const wy = cy - (pose.flicker ? 1.5 : 0.5)
147    const wr = big ? 2.5 : 2.1
148    g.ellipse(cx - rxs - wr * 0.4, wy, wr, wr * 0.8, WHITE)
149    g.ellipse(cx + rxs + wr * 0.4, wy, wr, wr * 0.8, WHITE)
150    g.set(Math.round(cx - rxs - wr * 0.6), Math.round(wy + 1), SILVER)
151    g.set(Math.round(cx + rxs + wr * 0.6), Math.round(wy + 1), SILVER)
152  }
153  if (line === 'forge' && stage !== 'baby') {
154    const tx = Math.round(cx + rxs)
155    const ty = Math.round(cy + ry * 0.4)
156    g.set(tx + 1, ty, pal.base)
157    g.set(tx + 2, ty - 1, pal.light)
158    g.set(tx + 2, ty - 2 - (pose.flicker ? 1 : 0), GOLD)
159    if (big) {
160      g.set(tx + 3, ty - 2, pal.light)
161      g.set(tx + 3, ty - 3 - (pose.flicker ? 0 : 1), GOLD)
162    }
163  }
164
165  // Body with shading.
166  g.ellipse(cx, cy, rxs, ry, pal.base)
167  for (let y = 0; y < SIZE; y++) {
168    for (let x = 0; x < SIZE; x++) {
169      if (g.get(x, y) !== pal.base) continue
170      const dx = (x + 0.5 - cx) / rxs
171      const dy = (y + 0.5 - cy) / ry
172      if (dx * 0.6 + dy > 0.75) g.set(x, y, pal.dark)
173      else if (dx < -0.25 && dy < -0.35 && dx * dx + dy * dy < 0.75) g.set(x, y, pal.light)
174    }
175  }
176  // Pattern from the second language, placed by the seed, never over the face.
177  if (dna && dna.pattern !== 'none') {
178    const body = new Set([pal.base, pal.dark, pal.light])
179    const k = dna.seed
180    for (let y = 0; y < SIZE; y++) for (let x = 0; x < SIZE; x++) {
181      if (!body.has(g.get(x, y) as Rgb)) continue
182      const dx = (x + 0.5 - cx) / rxs
183      const dy = (y + 0.5 - cy) / ry
184      if (Math.abs(dx) < 0.62 && dy > -0.5 && dy < 0.55) continue
185      // The seed sets stripe spacing, slant and offset, and spot density and placement.
186      const period = 2 + (k % 2)
187      const slant = (k >> 1) % 3 - 1
188      const along = slant === 0 ? y : x + slant * y
189      const density = 7 + ((k >> 3) % 5)
190      const on =
191        dna.pattern === 'stripes' ? (dy < -0.5 ? (x + (k >> 4)) % period === 0 : Math.abs(dx) > 0.62 && (((along + (k >> 5)) % period) + period) % period === 0) :
192        dna.pattern === 'spots' ? (x * 7 + y * 5 + (k >> 2)) % density === 0 || (dy < -0.55 && (x * 3 + y + (k >> 6)) % (density - 3) === 0) :
193        (k % 2 ? dx > 0.3 - ((k >> 7) % 3) * 0.1 : dx < -0.3 + ((k >> 7) % 3) * 0.1) && dy < 0.45
194      if (on) g.set(x, y, dna.accent)
195    }
196  }
197  // Belly: armour scales for steady testers.
198  if (stage !== 'baby') {
199    g.ellipse(cx, cy + ry * 0.35, rxs * 0.45, ry * 0.35, pal.light)
200    if (dna?.armor) {
201      for (let y = Math.round(cy); y < cy + ry; y++) for (let x = Math.round(cx - rxs * 0.45); x <= cx + rxs * 0.45; x++) {
202        if (g.get(x, y) === pal.light && (x + (y % 2)) % 2 === 0) g.set(x, y, SILVER)
203      }
204    }
205  }
206  // A mark on the forehead from the hours it keeps.
207  if (dna && dna.mark !== 'none') {
208    const marks: Record<Exclude<Dna['mark'], 'none'>, [number, number][]> = {
209      moon: [[0, 0], [1, 0], [-1, 1], [0, 2], [1, 2]],
210      sun: [[0, 0], [-1, 1], [0, 1], [1, 1], [0, 2]],
211      star: [[0, 0], [-1, 1], [1, 1], [0, 2]],
212    }
213    for (const [mx, my] of marks[dna.mark]) g.set(cx + mx, top + 1 + my, dna.mark === 'moon' ? WHITE : GOLD)
214  }
215
216  // Line features on top.
217  if (line === 'forge' && stage !== 'baby') {
218    const h = (big ? 3 : 2) + (dna && (dna.seed >> 8) % 3 === 0 ? 1 : 0)
219    g.tri(cx - rxs * 0.5, top - h + 1, h, -1, GOLD)
220    g.tri(cx + rxs * 0.5 - 1, top - h + 1, h, 1, GOLD)
221  } else if (line === 'summoner' && stage !== 'baby') {
222    const h = big ? 4 : 3
223    g.tri(Math.round(cx - rxs + 1), top - h + 2, h, -1, pal.base)
224    g.tri(Math.round(cx + rxs - 2), top - h + 2, h, 1, pal.base)
225  } else if (line === 'scribe' && stage !== 'baby') {
226    // A quill on the head, and a wisp instead of feet.
227    g.set(cx + 2, top - 1, WHITE)
228    g.set(cx + 3, top - 2, WHITE)
229    g.set(cx + 4, top - 3, SILVER)
230    const by = Math.round(cy + ry)
231    for (let i = -2; i <= 2; i++) g.set(cx + i, by + 1 + (Math.abs(i + (pose.flicker ? 1 : 0)) % 2), pal.base)
232  } else if (line === 'wanderer' && stage !== 'baby') {
233    g.set(cx - 1, top - 1, pal.light)
234    g.set(cx, top - 2, pal.light)
235    g.set(cx + 1, top - 1, pal.light)
236  } else if (stage === 'baby') {
237    g.set(cx, top - 1, pal.base)
238    g.set(cx + 1, top - 2, pal.light)
239  }
240
241  // Feet.
242  if (!floats) {
243    const fy = Math.round(cy + ry)
244    for (const fx of [cx - Math.round(rxs * 0.5), cx + Math.round(rxs * 0.5) - 1]) {
245      g.set(fx, fy, pal.dark)
246      g.set(fx + 1, fy, pal.dark)
247    }
248  }
249
250  // Face.
251  const ey = Math.round(cy - ry * 0.2)
252  const ex = Math.max(2, Math.round(rxs * 0.42))
253  for (const side of [-1, 1] as const) {
254    const x = cx + side * ex - (side < 0 ? 1 : 0)
255    eye(g, x, ey, pose.eyes, stage === 'baby' ? 1 : 2)
256    if (dna && pose.eyes === 'open') {
257      if (dna.eyes === 'sharp') g.set(x + (side < 0 ? 0 : 1), ey - 1, INK)
258      if (dna.eyes === 'sleepy') {
259        g.set(x, ey, pal.dark)
260        g.set(x + 1, ey, pal.dark)
261      }
262    }
263    if (dna?.extra === 'glasses') {
264      for (const [gx, gy] of [[-1, 0], [2, 0], [-1, 1], [2, 1], [0, -1], [1, -1], [0, 2], [1, 2]] as const) g.set(x + gx, ey + gy, INK)
265    }
266    // Shadow forms: a red glint in the eye, nowhere else.
267    if (grown && opts.variant === 'shadow' && pose.eyes === 'open') g.set(x, ey, RED)
268    if (pose.eyes === 'happy' || pose.mouth === 'smile') g.set(x + (side < 0 ? -1 : 2), ey + 2, PINK)
269  }
270  mouth(g, cx, Math.round(cy + ry * 0.3), line === 'wanderer' && stage !== 'baby' ? 'beak' : pose.mouth)
271
272  if (dna?.extra === 'scarf') {
273    const sy = Math.round(cy + ry * 0.62)
274    for (let x = Math.round(cx - rxs * 0.85); x <= cx + rxs * 0.85; x++) if (g.get(x, sy) !== null) g.set(x, sy, SCARF)
275    g.set(Math.round(cx + rxs * 0.55), sy + 1, SCARF)
276    g.set(Math.round(cx + rxs * 0.55), sy + 2, SCARF)
277  }
278  if (dna?.shiny) for (const [x, y] of [[cx - 4, top + 1], [cx + 5, top + 3]] as const) g.set(x, y, WHITE)
279
280  // Ultimate: an aura of sparkles and a crown (unless it wears a hat).
281  if (stage === 'ultimate') {
282    const spots = pose.flicker ? [[2, 6], [21, 9], [4, 18], [20, 19]] : [[3, 10], [20, 5], [2, 15], [21, 16]]
283    for (const [x, y] of spots) {
284      if (g.get(x!, y!) !== null) continue
285      g.set(x!, y!, GOLD)
286      g.set(x! - 1, y!, 0xfff3c4)
287      g.set(x! + 1, y!, 0xfff3c4)
288      g.set(x!, y! - 1, 0xfff3c4)
289      g.set(x!, y! + 1, 0xfff3c4)
290    }
291    if (!opts.hat) {
292      const y = top - 3
293      for (let i = -2; i <= 2; i++) g.set(cx + i, y + 2, GOLD)
294      for (const i of [-2, 0, 2]) g.set(cx + i, y + 1, GOLD)
295      g.set(cx, y, GOLD_DARK)
296    }
297  }
298
299  g.outline()
300  if (opts.hat) {
301    const h = HAT_SPRITES[opts.hat]
302    const off = HAT_OFFSET[opts.hat]
303    const hx = Math.round(cx - h.w / 2) + off[0]
304    const hy = top - h.h + 1 + off[1]
305    for (let j = 0; j < h.h; j++) for (let i = 0; i < h.w; i++) {
306      const c = h.px[j * h.w + i]
307      if (c !== null && c !== undefined) g.set(hx + i, hy + j, c)
308    }
309  }
310  return g.sprite()
311}
312
313function eye(g: Grid, x: number, y: number, kind: Eyes, size: 1 | 2) {
314  switch (kind) {
315    case 'open':
316      if (size === 1) {
317        g.set(x, y, INK)
318        g.set(x, y + 1, INK)
319      } else {
320        g.set(x, y, WHITE)
321        g.set(x + 1, y, INK)
322        g.set(x, y + 1, INK)
323        g.set(x + 1, y + 1, INK)
324      }
325      break
326    case 'closed':
327      g.set(x, y + 1, INK)
328      if (size === 2) g.set(x + 1, y + 1, INK)
329      break
330    case 'happy':
331      g.set(x, y + 1, INK)
332      if (size === 2) {
333        g.set(x + 1, y, INK)
334        g.set(x + 2, y + 1, INK)
335      }
336      break
337    case 'x':
338      g.set(x, y, INK)
339      g.set(x + 1, y + 1, INK)
340      if (size === 2) {
341        g.set(x + 1, y, INK)
342        g.set(x, y + 1, INK)
343      }
344      break
345    case 'dizzy':
346      g.set(x, y, INK)
347      g.set(x + 1, y, INK)
348      g.set(x + 1, y + 1, INK)
349      break
350  }
351}
352
353function mouth(g: Grid, cx: number, y: number, kind: Mouth | 'beak') {
354  switch (kind) {
355    case 'smile':
356      g.set(cx - 1, y, INK)
357      g.set(cx, y + 1, INK)
358      g.set(cx + 1, y, INK)
359      break
360    case 'open':
361      g.set(cx - 1, y, INK)
362      g.set(cx, y, INK)
363      g.set(cx + 1, y, INK)
364      g.set(cx, y + 1, RED)
365      g.set(cx - 1, y + 1, INK)
366      g.set(cx + 1, y + 1, INK)
367      break
368    case 'frown':
369      g.set(cx - 1, y + 1, INK)
370      g.set(cx, y, INK)
371      g.set(cx + 1, y + 1, INK)
372      break
373    case 'flat':
374      g.set(cx, y, INK)
375      g.set(cx + 1, y, INK)
376      break
377    case 'o':
378      g.set(cx, y, INK)
379      g.set(cx, y + 1, INK)
380      break
381    case 'beak':
382      g.set(cx - 1, y, GOLD)
383      g.set(cx, y, GOLD)
384      g.set(cx, y + 1, GOLD_DARK)
385      break
386  }
387}
388
389// ── Small props for the habitat.
390export function heart(): Sprite {
391  const rows = ['.r.r.', 'rrrrr', 'rrrrr', '.rrr.', '..r..']
392  return fromRows(rows, { r: RED })
393}
394export function note(): Sprite {
395  return fromRows(['..kk', '..k.', '..k.', 'kkk.', 'kk..'], { k: WHITE })
396}
397export function zz(): Sprite {
398  return fromRows(['kkk', '..k', '.k.', 'kkk'], { k: WHITE })
399}
400export function sweat(): Sprite {
401  return fromRows(['.b', 'bb', 'bb'], { b: 0x73eff7 })
402}
403export function star(): Sprite {
404  return fromRows(['.y.', 'yyy', '.y.'], { y: GOLD })
405}
406export function bowl(full: boolean): Sprite {
407  return fromRows([full ? '.oyoy.' : '......', 'kkkkkk', 'kbbbbk', '.kkkk.'], { o: 0xef7d57, y: GOLD, k: INK, b: 0x3b5dc9 })
408}
409export function ball(): Sprite {
410  return fromRows(['.kk.', 'krwk', 'kwrk', '.kk.'], { k: INK, r: RED, w: WHITE })
411}
412
413function fromRows(rows: string[], key: Record<string, Rgb>): Sprite {
414  const w = Math.max(...rows.map(r => r.length))
415  const px: (Rgb | null)[] = []
416  for (const r of rows) for (let x = 0; x < w; x++) px.push(key[r[x] ?? '.'] ?? null)
417  return { w, h: rows.length, px }
418}
419
420/** The smallest box holding every drawn pixel, padded to an even height for half-block cells. */
421export function crop(s: Sprite): Sprite {
422  let x0 = s.w
423  let y0 = s.h
424  let x1 = -1
425  let y1 = -1
426  for (let y = 0; y < s.h; y++) {
427    for (let x = 0; x < s.w; x++) {
428      if (s.px[y * s.w + x] === null) continue
429      x0 = Math.min(x0, x)
430      y0 = Math.min(y0, y)
431      x1 = Math.max(x1, x)
432      y1 = Math.max(y1, y)
433    }
434  }
435  if (x1 < 0) return s
436  if ((y1 - y0 + 1) % 2) y0 = Math.max(0, y0 - 1)
437  const w = x1 - x0 + 1
438  const h = y1 - y0 + 1
439  const px: (Rgb | null)[] = []
440  for (let y = y0; y < y0 + h; y++) for (let x = x0; x < x0 + w; x++) px.push(s.px[y * s.w + x] ?? null)
441  return { w, h, px }
442}
443
444// ── Hats, each with its own outline, set on top of the head.
445const HAT_KEY = { k: INK, y: GOLD, p: PINK, r: RED, b: 0x3b5dc9, B: 0x41a6f6, w: WHITE, v: 0x9b59d0, s: SILVER, g: 0x38b764 }
446const HAT_SPRITES: Record<Hat, Sprite> = {
447  party: fromRows(['...k...', '..kyk..', '..kpk..', '.kypyk.', '.kpypk.', 'kkkkkkk'], HAT_KEY),
448  cap: fromRows(['.kkkkk...', 'kBBBBBk..', 'kBBwBBkkk', 'kbbbbbbbk', 'kkkkkkkkk'], HAT_KEY),
449  headphones: fromRows(['..kkkkkkk..', '.kssssssk..', 'kk.......kk', 'krk.....krk', 'krk.....krk', 'kk.......kk'], HAT_KEY),
450  wizard: fromRows(['.....k..', '....kvk.', '...kvvk.', '...kvyk.', '..kvvvvk', '.kvvvvvvk', 'kyyyyyyyyk', 'kkkkkkkkkk'], HAT_KEY),
451  flower: fromRows(['.k.k.', 'kpkpk', '.kyk.', 'kpkpk', '.k.k.'], HAT_KEY),
452  bow: fromRows(['kk...kk', 'krk.krk', 'krrkrrk', 'krk.krk', 'kk...kk'], HAT_KEY),
453  beanie: fromRows(['...kk...', '..kwwk..', '.kbbbbk.', 'kbBbBbbk', 'kwwwwwwk', 'kkkkkkkk'], HAT_KEY),
454  halo: fromRows(['.kkkkk.', 'kyyyyyk', '.kkkkk.', '.......', '.......'], HAT_KEY),
455}
456const HAT_OFFSET: Record<Hat, [number, number]> = {
457  party: [0, 0], cap: [1, 1], headphones: [0, 4], wizard: [0, 1], flower: [3, 1], bow: [3, 1], beanie: [0, 2], halo: [0, -2],
458}
459
460export function hatIcon(hat: Hat): Sprite {
461  return HAT_SPRITES[hat]
462}
463
464export function mess(): Sprite {
465  return fromRows(['..k..', '.kwk.', 'kwwwk', 'kkkkk'], { k: INK, w: 0x8a5a3a })
466}
467export function bush(): Sprite {
468  return fromRows(['..kkkkk...', '.kgggggkk.', 'kggGgggggk', 'kgggggGggk', 'kGgggggggk', '.kkkkkkkk.'], { k: INK, g: 0x38b764, G: 0xa7f070 })
469}
470export function cookie(): Sprite {
471  return fromRows(['.kkk.', 'kyoyk', 'koyok', 'kyoyk', '.kkk.'], { k: INK, y: GOLD, o: 0x8a5a3a })
472}
473
474// ── Bug bosses: one body plan, dressed by kind.
475
476const BOSS_PAL: Record<BossKind, Palette & { eye: Rgb }> = {
477  imp: { base: 0x97c459, dark: 0x4e7a2a, light: 0xc9f2b5, eye: RED },
478  golem: { base: 0x8a8aa0, dark: 0x4a4a5e, light: 0xc9c9d4, eye: GOLD },
479  hydra: { base: 0x9b59d0, dark: 0x5d275d, light: 0xd9b8f0, eye: 0x73eff7 },
480  kraken: { base: 0x257179, dark: 0x0f3a3e, light: 0x5dcaa5, eye: RED },
481}
482
483export function bossSprite(kind: BossKind, frame: number, hit: boolean): Sprite {
484  const W = 30
485  const H = 24
486  const g = new Grid(W, H)
487  const pal = BOSS_PAL[kind]
488  const size = kind === 'imp' ? 0.75 : kind === 'kraken' ? 1.15 : 1
489  const cx = 16
490  const cy = 15
491  const rx = 9 * size
492  const ry = 6 * size
493  const step = frame % 2
494  // Legs (or tentacles), drawn first.
495  for (let i = 0; i < 3; i++) {
496    const lx = cx - rx * 0.6 + i * rx * 0.6
497    if (kind === 'kraken') {
498      for (let j = 0; j < 4; j++) g.set(lx + ((j + step) % 2), cy + ry - 1 + j, pal.dark)
499    } else {
500      g.set(lx - 1, cy + ry, pal.dark)
501      g.set(lx - 2 + step, cy + ry + 1, pal.dark)
502    }
503  }
504  g.ellipse(cx, cy, rx, ry, pal.base)
505  for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
506    if (g.get(x, y) !== pal.base) continue
507    const dy = (y + 0.5 - cy) / ry
508    if (dy > 0.45) g.set(x, y, pal.dark)
509    else if (dy < -0.5 && (x + y) % 3 === 0) g.set(x, y, pal.light)
510  }
511  // Shell stripes for the golem, spots for the imp.
512  if (kind === 'golem') for (let x = Math.round(cx - rx + 2); x < cx + rx - 1; x += 3) for (let y = Math.round(cy - ry + 2); y < cy + 2; y++) g.set(x, y, pal.dark)
513  // Heads: the hydra has three.
514  const heads = kind === 'hydra' ? [[-7, -8], [0, -10], [7, -8]] : [[-rx - 2, -2]]
515  for (const [hx, hy] of heads) {
516    const x = cx + hx!
517    const y = cy + hy! + (kind === 'hydra' ? step : 0)
518    g.ellipse(x, y, 3.2 * size, 2.8 * size, pal.base)
519    g.set(Math.round(x - 1), Math.round(y - 1), pal.eye)
520    g.set(Math.round(x + 1), Math.round(y - 1), pal.eye)
521    g.set(Math.round(x - 1), Math.round(y + 2), WHITE) // mandibles
522    g.set(Math.round(x + 1), Math.round(y + 2), WHITE)
523  }
524  // Antennae.
525  if (kind !== 'kraken') {
526    const [hx, hy] = heads[Math.floor(heads.length / 2)]!
527    g.set(cx + hx! - 2, cy + hy! - 3 - step, pal.dark)
528    g.set(cx + hx! - 3, cy + hy! - 4, pal.dark)
529  }
530  g.outline()
531  if (hit) for (let i = 0; i < g.px.length; i++) if (g.px[i] !== null && g.px[i] !== INK) g.px[i] = 0xfff3c4
532  return g.sprite()
533}
534
535// ── Garden decorations bought with gems, and holiday props.
536const DK = { k: INK, w: WHITE, y: GOLD, Y: GOLD_DARK, r: RED, p: PINK, s: SILVER, g: 0x38b764, G: 0xa7f070, b: 0x3b5dc9, B: 0x41a6f6, o: 0xef7d57, n: 0x73472c, N: 0x4a2e1d, c: 0x73eff7, v: 0x9b59d0, d: 0x333c57, t: 0xd9b382 }
537
538export const DECOR_SPRITES: Record<Decor, Sprite[]> = {
539  plant: [fromRows(['..kGk..', '.kGgGk.', 'kGgGgGk', '.kgGgk.', '..kkk..', '.kooook', '.koook.', '..kkk..'], DK)],
540  lamp: [fromRows(['.kkk.', 'kyYyk', 'kyyyk', '.kkk.', '..k..', '..k..', '..k..', '..k..', '.kkk.'], DK), fromRows(['.kkk.', 'kYyYk', 'kyYyk', '.kkk.', '..k..', '..k..', '..k..', '..k..', '.kkk.'], DK)],
541  poster: [fromRows(['kkkkkkkk', 'ktttttk.', 'ktbbtbtk', 'kttttttk', 'kkkkkkkk', '...kk...', '...kk...', '...kk...'], DK)],
542  rug: [fromRows(['.kkkkkkkkkkkk.', 'krrwrrwrrwrrwk', 'kwrrwrrwrrwrrk', '.kkkkkkkkkkkk.'], DK)],
543  bed: [fromRows(['k..........k', 'kkkkkkkkkkkk', 'kwwwbbbbbbbk', 'kwwwbBbBbBbk', 'kkkkkkkkkkkk', 'kn........nk'], DK)],
544  toybox: [fromRows(['..k..kk...', '.krk.kyk..', 'kkkkkkkkkk', 'knnNnnNnnk', 'knyyNnyynk', 'knnNnnNnnk', 'kkkkkkkkkk'], DK)],
545  desk: [fromRows(['...kkkkk...', '...kdcdk...', '...kdddk...', '..kkkkkkk..', 'kkkkkkkkkkk', 'knnnnnnnnnk', 'kn.......nk', 'kn.......nk'], DK)],
546  fountain: [
547    fromRows(['....c....', '...cBc...', '..c.B.c..', '....B....', '.kkkkkkk.', 'ksBBBBBsk', 'kssssssk.', '.kkkkkkk.'], DK),
548    fromRows(['...c.c...', '..c.B.c..', '.c..B..c.', '....B....', '.kkkkkkk.', 'ksBcBBBsk', 'kssssssk.', '.kkkkkkk.'], DK),
549  ],
550}
551
552export const pumpkin = fromRows(['...kk...', '..kgk...', '.kkkkkk.', 'kooyooyk', 'kooooook', 'koyyyyok', '.kkkkkk.'], DK)
553export const xmasTree = fromRows(['...y...', '..kgk..', '..kgrk.', '.kggggk', '.kgygk.', 'kgggrgk', '.kkkkk.', '...n...'], DK)
554export const cake = fromRows(['..y.y..', '..k.k..', '.kpppk.', 'kwwwwwk', 'kpppppk', 'kkkkkkk'], DK)
555
556function darken(p: Palette): Palette {
557  const d = (c: Rgb, k: number) => (Math.round(((c >> 16) & 255) * k) << 16) | (Math.round(((c >> 8) & 255) * k) << 8) | Math.round((c & 255) * k)
558  return { base: d(p.base, 0.62), dark: d(p.dark, 0.6), light: d(p.light, 0.7) }
559}
560
hooks/render.ts 260 lines
1// Turns the pet into animation frames, and frames into an SVG (desktop) or cells (terminal).
2
3import { INK, SIZE, monster, type Pose, type Rgb, type Sprite } from './art'
4import { dnaFromCode, dnaOf } from './dna'
5import { face, type Face, type Pet, type VisitorDna } from './pet'
6
7export const FRAME_MS = 260
8
9function poses(f: Face): { pose: Pose; dy: number }[] {
10  const p = (eyes: Pose['eyes'], mouth: Pose['mouth'], squash = false, flicker = false, dy = 0) => ({ pose: { eyes, mouth, squash, flicker }, dy })
11  switch (f) {
12    case 'cheer':
13    case 'evolve':
14      return [p('happy', 'open', true), p('happy', 'open', false, true, -3), p('happy', 'open', false, false, -1), p('happy', 'smile', true, true)]
15    case 'ouch':
16      return [p('x', 'frown', true), p('x', 'frown', true, true), p('x', 'flat'), p('x', 'frown', true, true)]
17    case 'eat':
18      return [p('happy', 'open'), p('happy', 'flat', true, true), p('happy', 'open'), p('happy', 'flat', true, true)]
19    case 'full':
20    case 'tired':
21      return [p('closed', 'flat'), p('closed', 'flat', false, true), p('closed', 'flat'), p('open', 'flat', false, true)]
22    case 'love':
23      return [p('happy', 'smile'), p('happy', 'smile', false, true, -1), p('happy', 'smile'), p('happy', 'smile', true, true)]
24    case 'sleep':
25      return [p('closed', 'flat', true), p('closed', 'flat', true, true), p('closed', 'o'), p('closed', 'flat', true, true)]
26    case 'sick':
27      return [p('dizzy', 'frown'), p('dizzy', 'frown', true, true), p('dizzy', 'flat'), p('dizzy', 'frown', true, true)]
28    case 'hungry':
29      return [p('open', 'o'), p('open', 'o', false, true), p('open', 'o'), p('closed', 'o', false, true)]
30    case 'sad':
31      return [p('open', 'frown'), p('open', 'frown', false, true), p('open', 'frown'), p('closed', 'frown', false, true)]
32    case 'happy':
33      return [p('open', 'smile'), p('open', 'smile', false, true, -1), p('open', 'smile'), p('closed', 'smile', false, true)]
34    case 'wave':
35      return [p('happy', 'open', false, false, -1), p('happy', 'smile', false, true), p('happy', 'open', false, false, -1), p('happy', 'smile', false, true)]
36    case 'sweat':
37      return [p('closed', 'flat', true), p('closed', 'open', false, true, -1), p('closed', 'flat', true), p('closed', 'open', false, true, -1)]
38    case 'win':
39      return [p('happy', 'open', true), p('happy', 'open', false, true, -4), p('happy', 'open', false, false, -2), p('happy', 'smile', true, true)]
40    case 'lose':
41      return [p('closed', 'frown'), p('closed', 'frown', true, true), p('open', 'frown'), p('closed', 'frown', true, true)]
42    case 'talk':
43      return [p('open', 'open'), p('open', 'smile', false, true), p('open', 'open'), p('open', 'flat', false, true)]
44    case 'sleepy':
45      return [p('closed', 'flat'), p('closed', 'o', false, true), p('closed', 'flat'), p('open', 'flat', false, true)]
46  }
47}
48
49function blank(w: number, h: number, c: Rgb | null = null): (Rgb | null)[] {
50  return new Array(w * h).fill(c)
51}
52
53function stamp(px: (Rgb | null)[], w: number, h: number, s: Sprite, x: number, y: number) {
54  for (let j = 0; j < s.h; j++) {
55    for (let i = 0; i < s.w; i++) {
56      const c = s.px[j * s.w + i]
57      const X = x + i
58      const Y = y + j
59      if (c !== null && c !== undefined && X >= 0 && Y >= 0 && X < w && Y < h) px[Y * w + X] = c
60    }
61  }
62}
63
64/** The pet alone, one frame per pose, each in the same box (so it can bob without the box moving). */
65export function petFrames(p: Pet, now: number): Sprite[] {
66  const f = face(p, now)
67  const dna = dnaOf(p)
68  const hatching = p.stage === 'egg' && p.xp >= 6
69  const pad = 4
70  const H = SIZE + pad
71  return poses(f).map(({ pose, dy }) => {
72    const px = blank(SIZE, H)
73    stamp(px, SIZE, H, monster(p.stage, p.line, pose, { cracked: hatching, variant: p.variant, hat: p.hat, dna }), 0, pad + dy)
74    return { w: SIZE, h: H, px }
75  })
76}
77
78/** A visiting monster, drawn from its DNA code and turned to face yours. */
79export function visitorFrames(v: VisitorDna): Sprite[] {
80  const pad = 4
81  const H = SIZE + pad
82  const dna = dnaFromCode(v)
83  return poses('happy').map(({ pose, dy }) => {
84    const px = blank(SIZE, H)
85    stamp(px, SIZE, H, mirror(monster(v.stage, v.line, pose, { variant: v.variant, dna })), 0, pad + dy)
86    return { w: SIZE, h: H, px }
87  })
88}
89
90function mirror(s: Sprite): Sprite {
91  const px: (Rgb | null)[] = []
92  for (let y = 0; y < s.h; y++) for (let x = s.w - 1; x >= 0; x--) px.push(s.px[y * s.w + x] ?? null)
93  return { w: s.w, h: s.h, px }
94}
95
96/** Half size: each 2×2 block becomes its most common colour, with dark lines (eyes, mouth, outline) favoured so the face survives. */
97export function half(s: Sprite, ox = 0, oy = 0): Sprite {
98  const w = Math.ceil((s.w + ox) / 2)
99  const h = Math.ceil((s.h + oy) / 2)
100  const at = (x: number, y: number) => (x >= 0 && y >= 0 && x < s.w && y < s.h ? s.px[y * s.w + x] ?? null : null)
101  const px: (Rgb | null)[] = []
102  for (let y = 0; y < h; y++) {
103    for (let x = 0; x < w; x++) {
104      const count = new Map<Rgb, number>()
105      let filled = 0
106      for (const [dx, dy] of [[0, 0], [1, 0], [0, 1], [1, 1]] as const) {
107        const c = at(2 * x + dx - ox, 2 * y + dy - oy)
108        if (c === null) continue
109        filled++
110        count.set(c, (count.get(c) ?? 0) + (c === INK ? 1.5 : 1))
111      }
112      if (filled < 2) {
113        px.push(null)
114        continue
115      }
116      let best: Rgb | null = null
117      let most = 0
118      for (const [c, n] of count) if (n > most) [best, most] = [c, n]
119      px.push(best)
120    }
121  }
122  return { w, h, px }
123}
124
125/** Dark pixels with colour on both sides: eyes and mouth, what a face needs to read. */
126function faceScore(s: Sprite) {
127  let n = 0
128  for (let y = 0; y < s.h; y++) {
129    for (let x = 1; x < s.w - 1; x++) {
130      const l = s.px[y * s.w + x - 1]
131      const r = s.px[y * s.w + x + 1]
132      if (s.px[y * s.w + x] === INK && l !== null && l !== INK && r !== null && r !== INK) n++
133    }
134  }
135  return n
136}
137
138/** Halves every frame on the same 2×2 grid, the one that keeps the most of the face. */
139export function halfAll(frames: Sprite[]): Sprite[] {
140  const first = frames[0]
141  if (!first) return frames
142  let best: [number, number] = [0, 0]
143  let score = -1
144  for (const ox of [0, 1]) for (const oy of [0, 1]) {
145    const n = faceScore(half(first, ox, oy))
146    if (n > score) [best, score] = [[ox, oy], n]
147  }
148  return frames.map(f => half(f, best[0], best[1]))
149}
150
151/** One box around every frame's pixels, so frames crop alike; height even for half blocks. */
152export function cropAll(frames: Sprite[]): Sprite[] {
153  const first = frames[0]
154  if (!first) return frames
155  let x0 = first.w
156  let y0 = first.h
157  let x1 = -1
158  let y1 = -1
159  for (const s of frames) {
160    for (let y = 0; y < s.h; y++) {
161      for (let x = 0; x < s.w; x++) {
162        if (s.px[y * s.w + x] === null) continue
163        x0 = Math.min(x0, x)
164        y0 = Math.min(y0, y)
165        x1 = Math.max(x1, x)
166        y1 = Math.max(y1, y)
167      }
168    }
169  }
170  if (x1 < 0) return frames
171  if ((y1 - y0 + 1) % 2) y0 = Math.max(0, y0 - 1)
172  const w = x1 - x0 + 1
173  const h = y1 - y0 + 1
174  return frames.map(s => {
175    const px: (Rgb | null)[] = []
176    for (let y = y0; y < y0 + h; y++) for (let x = x0; x < x0 + w; x++) px.push(s.px[y * s.w + x] ?? null)
177    return { w, h, px }
178  })
179}
180
181export type Hunt = { round: number; score: number; treat: number; picked: number | null }
182
183// ── SVG: each frame defined once, shown in turn with discrete visibility animation.
184const hex = (c: Rgb) => '#' + c.toString(16).padStart(6, '0')
185
186export function paths(s: Sprite): string {
187  const byColor = new Map<Rgb, string>()
188  for (let y = 0; y < s.h; y++) {
189    let x = 0
190    while (x < s.w) {
191      const c = s.px[y * s.w + x]
192      if (c === null || c === undefined) {
193        x++
194        continue
195      }
196      let run = 1
197      while (x + run < s.w && s.px[y * s.w + x + run] === c) run++
198      byColor.set(c, (byColor.get(c) ?? '') + `M${x} ${y}h${run}v1h-${run}z`)
199      x += run
200    }
201  }
202  return [...byColor].map(([c, d]) => `<path fill="${hex(c)}" d="${d}"/>`).join('')
203}
204
205export function framesSvg(frames: Sprite[], scale: number, ms = FRAME_MS): string {
206  const s = frames[0]!
207  const n = frames.length
208  const dur = n * ms
209  const times = frames.map((_, i) => (i / n).toFixed(4)).join(';')
210  const layers = frames
211    .map((f, i) => {
212      const values = frames.map((_, j) => (j === i ? 'visible' : 'hidden')).join(';')
213      return `<g visibility="${i === 0 ? 'visible' : 'hidden'}"><animate attributeName="visibility" values="${values}" keyTimes="${times}" dur="${dur}ms" calcMode="discrete" repeatCount="indefinite"/>${paths(f)}</g>`
214    })
215    .join('')
216  return `<svg xmlns="http://www.w3.org/2000/svg" width="${s.w * scale}" height="${s.h * scale}" viewBox="0 0 ${s.w} ${s.h}" shape-rendering="crispEdges">${layers}</svg>`
217}
218
219// ── Terminal cells: two pixels per cell; transparent pixels take the terminal's own colour.
220const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
221const DEFAULT = 0x01000000
222
223export function base64(bytes: Uint8Array): string {
224  let out = ''
225  for (let i = 0; i < bytes.length; i += 3) {
226    const n = (bytes[i]! << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0)
227    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]!
228    out += i + 1 < bytes.length ? B64[(n >> 6) & 63]! : '='
229    out += i + 2 < bytes.length ? B64[n & 63]! : '='
230  }
231  return out
232}
233
234export function cells(s: Sprite): { columns: number; rows: number; cells: string } {
235  const rows = Math.ceil(s.h / 2)
236  const words = new Uint32Array(s.w * rows * 3)
237  for (let r = 0; r < rows; r++) {
238    for (let x = 0; x < s.w; x++) {
239      const top = s.px[2 * r * s.w + x] ?? null
240      const bottom = 2 * r + 1 < s.h ? (s.px[(2 * r + 1) * s.w + x] ?? null) : null
241      const n = (r * s.w + x) * 3
242      if (top === null && bottom === null) {
243        words[n] = 0x20
244        words[n + 1] = DEFAULT
245        words[n + 2] = DEFAULT
246      } else if (top === null) {
247        words[n] = 0x2584 // lower half block
248        words[n + 1] = bottom!
249        words[n + 2] = DEFAULT
250      } else {
251        words[n] = 0x2580 // upper half block
252        words[n + 1] = top
253        words[n + 2] = bottom ?? DEFAULT
254      }
255    }
256  }
257  return { columns: s.w, rows, cells: base64(new Uint8Array(words.buffer)) }
258}
259
260
hooks/font.ts 70 lines
1// A 5×7 pixel font for the card: capitals, digits and a little punctuation. Each glyph is seven
2// rows of five bits, high bit on the left. Lower case draws as capitals; anything else as '?'.
3
4const G: Record<string, number[]> = {
5  A: [0x0e, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11], B: [0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e],
6  C: [0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e], D: [0x1e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x1e],
7  E: [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x1f], F: [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10],
8  G: [0x0e, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0f], H: [0x11, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11],
9  I: [0x0e, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0e], J: [0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0c],
10  K: [0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11], L: [0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f],
11  M: [0x11, 0x1b, 0x15, 0x15, 0x11, 0x11, 0x11], N: [0x11, 0x11, 0x19, 0x15, 0x13, 0x11, 0x11],
12  O: [0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e], P: [0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10],
13  Q: [0x0e, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0d], R: [0x1e, 0x11, 0x11, 0x1e, 0x14, 0x12, 0x11],
14  S: [0x0f, 0x10, 0x10, 0x0e, 0x01, 0x01, 0x1e], T: [0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04],
15  U: [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e], V: [0x11, 0x11, 0x11, 0x11, 0x11, 0x0a, 0x04],
16  W: [0x11, 0x11, 0x11, 0x15, 0x15, 0x15, 0x0a], X: [0x11, 0x11, 0x0a, 0x04, 0x0a, 0x11, 0x11],
17  Y: [0x11, 0x11, 0x11, 0x0a, 0x04, 0x04, 0x04], Z: [0x1f, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1f],
18  '0': [0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e], '1': [0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e],
19  '2': [0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f], '3': [0x1f, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0e],
20  '4': [0x02, 0x06, 0x0a, 0x12, 0x1f, 0x02, 0x02], '5': [0x1f, 0x10, 0x1e, 0x01, 0x01, 0x11, 0x0e],
21  '6': [0x06, 0x08, 0x10, 0x1e, 0x11, 0x11, 0x0e], '7': [0x1f, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08],
22  '8': [0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x0e], '9': [0x0e, 0x11, 0x11, 0x0f, 0x01, 0x02, 0x0c],
23  ' ': [0, 0, 0, 0, 0, 0, 0], '.': [0, 0, 0, 0, 0, 0x0c, 0x0c], ',': [0, 0, 0, 0, 0x0c, 0x04, 0x08],
24  ':': [0, 0x0c, 0x0c, 0, 0x0c, 0x0c, 0], '-': [0, 0, 0, 0x1f, 0, 0, 0], '+': [0, 0x04, 0x04, 0x1f, 0x04, 0x04, 0],
25  '/': [0, 0x01, 0x02, 0x04, 0x08, 0x10, 0], '%': [0x18, 0x19, 0x02, 0x04, 0x08, 0x13, 0x03],
26  '#': [0x0a, 0x0a, 0x1f, 0x0a, 0x1f, 0x0a, 0x0a], '!': [0x04, 0x04, 0x04, 0x04, 0x04, 0, 0x04],
27  '?': [0x0e, 0x11, 0x01, 0x02, 0x04, 0, 0x04], "'": [0x0c, 0x04, 0x08, 0, 0, 0, 0],
28  '(': [0x02, 0x04, 0x08, 0x08, 0x08, 0x04, 0x02], ')': [0x08, 0x04, 0x02, 0x02, 0x02, 0x04, 0x08],
29  '=': [0, 0, 0x1f, 0, 0x1f, 0, 0], '_': [0, 0, 0, 0, 0, 0, 0x1f], '$': [0x04, 0x0f, 0x14, 0x0e, 0x05, 0x1e, 0x04],
30  '&': [0x0c, 0x12, 0x14, 0x08, 0x15, 0x12, 0x0d], '*': [0, 0x04, 0x15, 0x0e, 0x15, 0x04, 0],
31  '♥': [0, 0x0a, 0x1f, 0x1f, 0x0e, 0x04, 0], '✦': [0x04, 0x04, 0x0e, 0x1f, 0x0e, 0x04, 0x04],
32  '·': [0, 0, 0, 0x04, 0, 0, 0],
33}
34
35export const GLYPH_W = 5
36export const GLYPH_H = 7
37/** Width of a character cell, glyph plus one column of space. */
38export const ADVANCE = 6
39
40export function glyph(ch: string): number[] {
41  return G[ch] ?? G[ch.toUpperCase()] ?? G['?']!
42}
43
44export function textWidth(text: string, scale = 1) {
45  return Math.max(0, [...text].length * ADVANCE - 1) * scale
46}
47
48/** Draws text into a pixel buffer of width w; returns the x after it. */
49export function drawText(px: (number | null)[], w: number, h: number, text: string, x: number, y: number, color: number, scale = 1): number {
50  let cx = x
51  for (const ch of text) {
52    const rows = glyph(ch)
53    for (let r = 0; r < GLYPH_H; r++) {
54      const bits = rows[r] ?? 0
55      for (let c = 0; c < GLYPH_W; c++) {
56        if (!(bits & (0x10 >> c))) continue
57        for (let sy = 0; sy < scale; sy++) {
58          for (let sx = 0; sx < scale; sx++) {
59            const X = cx + c * scale + sx
60            const Y = y + r * scale + sy
61            if (X >= 0 && Y >= 0 && X < w && Y < h) px[Y * w + X] = color
62          }
63        }
64      }
65    }
66    cx += ADVANCE * scale
67  }
68  return cx
69}
70
types/index.d.ts 168 lines
1// The monster mod's state contract: the pet, plain JSON, shared by every session on this machine.
2
3export type Stage = 'egg' | 'baby' | 'child' | 'adult' | 'ultimate'
4
5/** The evolution line, chosen by how you work when it grows into a child. */
6export type Line = 'forge' | 'scribe' | 'summoner' | 'wanderer'
7
8/** Chosen by how well it was cared for when it grows into an adult. */
9export type Variant = 'bright' | 'shadow'
10
11export type Personality = 'cheerful' | 'lazy' | 'curious' | 'grumpy'
12
13/** Treats earned from your work. */
14export type Item = 'cookie' | 'coffee' | 'gem' | 'bug'
15
16export type Hat = 'party' | 'cap' | 'headphones' | 'wizard' | 'flower' | 'bow' | 'beanie' | 'halo'
17
18export type Skill = 'power' | 'wisdom' | 'speed'
19
20/** A hidden form for an extreme habit, replacing the line's usual adult or ultimate. */
21export type Secret = 'archivist' | 'bugslayer' | 'goldheart'
22
23export type Decor = 'plant' | 'lamp' | 'poster' | 'rug' | 'bed' | 'toybox' | 'desk' | 'fountain'
24
25export type BossKind = 'hydra' | 'golem' | 'imp' | 'kraken'
26
27/** This week's boss, built from the previous week's failures. */
28export type Boss = { week: string; kind: BossKind; name: string; hp: number; atk: number; beaten: boolean; tries: number }
29
30/** What a DNA code carries: enough to draw someone else's monster. */
31export type VisitorDna = {
32  seed: number; lang1: string | null; lang2: string | null
33  pattern: 'none' | 'stripes' | 'spots' | 'patch'; mark: 'none' | 'moon' | 'sun' | 'star'; build: 'normal' | 'slim' | 'stout'
34  armor: boolean; eyes: 'round' | 'sharp' | 'sleepy'; extra: 'none' | 'glasses' | 'scarf'; shiny: boolean
35  stage: Stage; line: Line | null; variant: Variant | null
36}
37
38/** A friend's monster staying for a day, from their DNA code. */
39export type Visitor = { code: string; name: string; dna: VisitorDna; arrived: number; until: number; played: boolean; sparred: boolean }
40
41/** A monster that retired to the Hall of Fame. */
42export type Legend = { name: string; form: string; level: number; days: number; generation: number; retiredAt: number }
43
44export type Mood = {
45  kind: 'cheer' | 'ouch' | 'eat' | 'full' | 'tired' | 'love' | 'evolve' | 'wave' | 'sweat' | 'win' | 'lose' | 'talk'
46  until: number
47}
48
49export type Pet = {
50  name: string
51  born: number
52  updatedAt: number
53  /** The last time anything happened in any session. */
54  lastActive: number
55  personality: Personality
56  stage: Stage
57  line: Line | null
58  variant: Variant | null
59  xp: number
60  /** 0–100: 100 is full. */
61  hunger: number
62  joy: number
63  stress: number
64  energy: number
65  /** Tucked in: asleep until then. */
66  asleepUntil?: number
67  /** Droppings after meals, 0–3. */
68  mess: number
69  skills: Record<Skill, number>
70  items: Record<Item, number>
71  hat: Hat | null
72  hats: Hat[]
73  badges: string[]
74  streak: { days: number; lastDay: string }
75  /** Joy sampled while active, for the adult variant. */
76  care: { sum: number; n: number }
77  traits: { shell: number; code: number; agents: number; web: number }
78  stats: {
79    tokens: number; tests: number; commits: number; pushes: number; tasks: number; errors: number
80    fed: number; meals: number; played: number; pats: number; talks: number
81    games: number; wins: number; trained: number; cleaned: number; agents: number
82    bossWins: number; bossTries: number; cards: number; visits: number; spars: number
83    lastTestFailed?: boolean
84  }
85  cooldowns: { feed?: number; play?: number; train?: number; game?: number }
86  mood?: Mood
87  said?: { text: string; at: number }
88  settings: { sound: boolean; alerts: boolean }
89  /** Failures this week, which shape next week's boss. */
90  week: { id: string; errors: number; testFails: number }
91  boss: Boss | null
92  secret: Secret | null
93  /** When it became an ultimate; it may retire 30 days later. */
94  ultimateAt?: number
95  generation: number
96  hall: Legend[]
97  decor: Decor[]
98  /** Habits, as counts only: what its DNA is drawn from. */
99  habits: {
100    /** Edits per language, from file extensions. */
101    langs: Record<string, number>
102    /** Activity per local hour, 0–23. */
103    hours: number[]
104    edits: number
105    editsSinceCommit: number
106    /** Edits that went into commits, for the average commit size. */
107    committedEdits: number
108    testRuns: number
109    toolCalls: number
110  }
111  /** A number derived from your identity (a hash of your git email): never the email itself. */
112  seed: number | null
113  shiny: boolean
114  /** The first-run tour: which step it is on, or done. */
115  tour: { step: number; done: boolean }
116  /** Starter quests already completed and rewarded. */
117  quests: string[]
118  /** Parts of the pet's world you have opened, for the tour. */
119  seen: string[]
120  visitor: Visitor | null
121  /** Which alerts have already been shown, so each fires once until it clears. */
122  alerted: { hungry?: boolean; sick?: boolean; messy?: boolean; tired?: boolean }
123  log: { at: number; text: string }[]
124}
125
126/** Something that happened in a session, waiting to be applied to the shared pet. */
127export type Event =
128  | { kind: 'tokens'; n: number; at: number }
129  | { kind: 'tool'; tool: string; command?: string; failed: boolean; ms?: number; ext?: string; at: number }
130  | { kind: 'task'; n: number; at: number }
131  | { kind: 'agent'; at: number }
132  | { kind: 'feed'; at: number }
133  | { kind: 'play'; at: number }
134  | { kind: 'pet'; at: number }
135  | { kind: 'talk'; text: string; at: number }
136  | { kind: 'clean'; at: number }
137  | { kind: 'tuck'; at: number }
138  | { kind: 'wake'; at: number }
139  | { kind: 'use'; item: Item; at: number }
140  | { kind: 'game'; won: boolean; prize?: Item; at: number }
141  | { kind: 'train'; skill: Skill; at: number }
142  | { kind: 'equip'; hat: Hat | null; at: number }
143  | { kind: 'rename'; name: string; at: number }
144  | { kind: 'setting'; key: 'sound' | 'alerts'; on: boolean; at: number }
145  | { kind: 'boss'; won: boolean; at: number }
146  | { kind: 'buy'; decor: Decor; at: number }
147  | { kind: 'retire'; at: number }
148  | { kind: 'seed'; value: number; at: number }
149  | { kind: 'seen'; what: 'pane' | 'items' | 'games' | 'shop' | 'style' | 'badges'; at: number }
150  | { kind: 'card'; at: number }
151  | { kind: 'tour'; action: 'skip' | 'restart'; at: number }
152  | { kind: 'visit'; code: string; name: string; dna: VisitorDna; at: number }
153  | { kind: 'visit-play'; at: number }
154  | { kind: 'visit-spar'; won: boolean; at: number }
155  | { kind: 'visit-end'; at: number }
156
157declare module 'claude-code' {
158  interface PluginState {
159    monster: {
160      pet: Pet | null
161      isHidden: boolean
162      tab: 'home' | 'items' | 'games' | 'shop' | 'style' | 'badges'
163      battle: { hp: number; maxHp: number; petHp: number; petMax: number; turn: number; weak: Skill; log: string[]; over: 'won' | 'lost' | null } | null
164      hunt: { round: number; score: number; treat: number; picked: number | null } | null
165    }
166  }
167}
168