SLOPSHOPPER

pokemon

A pixel Pokémon that lives at the right edge of the band above the prompt

panebandspinnerguardcommandprompt
★ 35v?no licenseupdated 2026-10-26dgokcin/claude-pokemon-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pokemon
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /pokemon ⎿ pokemon: Showing default Abra Lv. 5, wandering (food 80%, happiness 80%). Options: <mon>, default, shiny, new, list, pe ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-pokemon

A pixel Pokémon that lives above your Claude Code prompt, in the terminal or the desktop app, and reacts to everything Claude does.

CI Release 151 Pokémon 135 moves

A wild Bulbasaur strikes Charmander with Vine Whip, goes weak as Claude works, and gets caught in a Poké Ball

claude plugin marketplace add dgokcin/claude-pokemon-mod
claude plugin install pokemon@claude-pokemon

Then pick your starter, like /pokemon charmander. Bulbasaur, Charmander, Squirtle, and Pikachu are on offer, and the rest you catch in the wild.

[!TIP] It works best in kitty, Ghostty, or a recent iTerm2, which draw images, so the small band keeps every pixel. iTerm2 also needs images turned on in the env block of ~/.claude/settings.json:

{
  "env": {
    "CLAUDE_CODE_FORCE_TERMINAL_IMAGES": "1"
  }
}

Why you'll keep it on

  • 🔎 It watches Claude work. A pencil for edits, a magnifier for reads, >_ for shell commands, a TM disc for skills.
  • ⚪ Every subagent is a Poké Ball. It drops when the subagent starts, a mon from your box steps out to work beside yours, and it goes back in when the subagent reports back.
  • ❗ It tells you when Claude needs you. A red "!" for questions, plan approvals, and permission prompts.
  • 💦 It flinches when a tool fails. A shake and a sweat drop, so you notice.
  • 📈 It levels up as you ship. Every answered turn earns XP, and mons evolve at their levels from the games.
  • 🫐 It needs you too. Feed it and pet it, or it gets hungry and lonely. Leave it long enough and it faints, and then it runs away.
  • 🎒 You start with one starter. Bulbasaur, Charmander, Squirtle, or Pikachu. Every other mon has to be caught.
  • 🌿 Wild Pokémon show up, and they fight back. Your work wears them down while they strike your mon with their own moves. Once one is weak, /pokemon catch fills your Pokédex, but knock it out and it's gone.
  • ⚡ It fights. 135 moves from gen 1, each with its own pixel animation.
  • 🎨 All 151 gen 1 Pokémon, each in default and shiny, and gen 2 to 5 with /pokemon new.

See it

Watch it follow Claude's tools. >_ for shell commands, a TM disc for skills, a magnifier for reads, a pencil for writes.

Mew's bubble shows a shell prompt while Claude reads files, then a TM disc while a skill runs

Run subagents and your party steps out. Each subagent drops a ball, a mon from your box works beside yours, and it goes back in when the subagent is done.

Three Explore subagents start, and three party mons step out beside Squirtle and run shell commands in their bubbles

Evolve it. At the right level, or with a stone.

Growlithe gets a Fire Stone, glows white, sparkles, and flashes into Arcanine

Make it attack. Magikarp uses Splash. Nothing happens. Gengar uses Hypnosis.

Magikarp splashes to no effect, then Gengar casts Hypnosis

Look after it. Feed it berries and pet it, so it stays happy.

Gengar eats a razz berry and an oran berry, then hearts float up as it gets petted

Revive it. Neglect it long enough and it faints. Nurse Joy gets it back on its feet.

A fainted Bulbasaur with dizzy stars is taken to a Pokémon Center, and Nurse Joy starts healing it

Use it in the desktop app. The same mon, in the Code tab.

Bulbasaur grows to the large band and attacks above the prompt in the Claude desktop app's Code tab

Commands

CommandWhat it does
/pokemon <mon>Pick a mon, like /pokemon charmander
/pokemon petPet it
/pokemon feedToss it a berry
/pokemon reviveTake a fainted mon to a Pokémon Center
/pokemon attack [move]Use a random move, or a named one like thunderbolt
/pokemon evolveEvolve with a stone or a trade
/pokemon statsLevel, XP, evolution, and meters
/pokemon boxEvery mon you've raised
/pokemon partyThe mons that come out for subagents, and who each works for
/pokemon party add <mon>Put a mon from your box in your party, like /pokemon party add dratini
/pokemon party assign <agent> <mon>Send the same mon out for every subagent of a type, like /pokemon party assign explore abra
/pokemon catchThrow a Poké Ball at a wild mon
/pokemon trainerTurn trainer mode off to show any mon without catching it, or back on
/pokemon dexEvery wild mon you've seen and caught
/pokemon new <mon>Fetch a mon from gen 2 to 5, like /pokemon new mudkip, or a random one with /pokemon new gen3
CommandEffect
/pokemonShow the active mon, its variant, level, meters, and the options
/pokemon <mon>Pick the mon for this session, or for every open session with /pokemon sync on. A new session starts with the one picked last
/pokemon listList every mon name
/pokemon helpList every option and what it does, with each toggle's setting
/pokemon shiny, /pokemon defaultPick a variant, saved across sessions
/pokemon wanderToggle idle wandering (on by default)
/pokemon petPet the mon. A sleeping mon stays asleep. Counts pets across sessions
/pokemon feedToss it a random oran 🫐, pecha 🍑, razz 🍓, or sitrus 🍋 berry
/pokemon attackUse a random move from the mon's moveset
/pokemon attack <move>Use a named move, ignoring case, spaces, and dashes
/pokemon moves, /pokemon attack listList the active mon's moves
/pokemon moves <mon>List another mon's moves
/pokemon evolveEvolve with a stone or a trade. Also evolves a mon at its level with autoevolve off, and restarts an evolution you cancelled
/pokemon evolve <mon>Pick what Eevee becomes, like /pokemon evolve jolteon
/pokemon stopCancel an evolution
/pokemon revive, /pokemon revive <mon>Take a fainted mon to a Pokémon Center. Nurse Joy heals it in 5 minutes, and it stands up at 50% food and 30% happiness
/pokemon nuzlockeToggle nuzlocke (off by default, saved across sessions). On, a mon that faints is gone for good
/pokemon trainerToggle trainer mode (on by default, saved across sessions). On, /pokemon <mon> shows only mons in your box, so the rest have to be caught in the wild. The mons already in your box stay. An empty box, or one whose mons are all gone, picks one starter: Bulbasaur, Charmander, Squirtle, or Pikachu. Mons fetched with /pokemon new stay free to show. Off, /pokemon <mon> shows any mon
/pokemon sleepTuck the mon in, so its meters drain slower until Claude starts working in a session showing it. Run it again to wake it
/pokemon needsToggle food and happiness (on by default). Off, the faint and runaway clocks stop too
/pokemon syncToggle syncing the mon across sessions (off by default, saved across sessions). On, every open session switches to the mon picked last in any of them, fetched mons included. Off, each session keeps its own
/pokemon autoevolveToggle level evolutions starting on their own once idle (on by default). Off, the mon waits for /pokemon evolve
/pokemon emojiToggle emoji meters, 🍓 and 💗 instead of ● and ♥ (off by default, saved across sessions)
/pokemon size small, /pokemon size largeDraw the band at half size or full size (large by default, saved across sessions). A short pane still shrinks it further. See How it works for crisp small mons in iTerm2
/pokemon images auto, on, offDraw the small band and the hearts as pixel images, or in half blocks and text (auto by default, saved across sessions). auto uses images only in kitty, Ghostty, and iTerm2 builds that draw them. off fixes a terminal that shows boxes, and on tries images in a terminal not on that list
/pokemon paneMove the mon out of the band into a pane half the terminal wide, docked beside the transcript in the fullscreen layout so Claude's replies keep the left half. Run it again, or close the pane, to bring it back to the band (saved across sessions). On the main screen the pane sits above the prompt instead
/pokemon statsShow the level, XP to the next one, how it evolves, the meters, and your pets and feeds
/pokemon boxList every mon you've raised, highest level first
/pokemon partyList your party, the mons in your box beside the one on show, highest level first, up to 5, and the subagent each one works for. Fainted mons, ones that ran away, and ones lost in a nuzlocke stay out of it
/pokemon party add <mon>, /pokemon party remove <mon>Pick your party from your box, up to 5, saved across sessions. Mons come out in the order you added them. The first change starts from the party as it stands, and a mon you take out while it works finishes its subagent first
/pokemon party assign <agent> <mon>, /pokemon party unassign <agent>Tie a mon from your box to an agent type, like explore, plan, or one of your own agents' names, so you can tell which agent is working or done by who steps out (saved across sessions). The mon comes out for that type alone, outside the party of 5, and a mon works for one type at a time, so assigning it again moves it. When it's busy with another subagent of its type, or fainted, that subagent gets the next mon from the party
/pokemon new <mon>Fetch a mon from any generation in vscode-pokemon (gen 1 to 5) and show it. It's saved in the mod's store, so it stays through plugin updates and shows up in every session. Moves come from its types, using gen 1 animations
/pokemon new random, /pokemon new gen<N>Fetch a random mon you don't have yet, from gen 2 to 5 or from gen N
/pokemon nickname <name>Nickname the mon, up to 12 characters. It keeps the name when it evolves, and its species name takes the nickname away
/pokemon release <mon>Release a mon from your box. It starts over at its first level with fresh meters
/pokemon catchThrow a Poké Ball at the wild mon. The odds rise as its HP falls
/pokemon runSend the wild mon away
/pokemon dexCount the wild mons you've seen and caught, and list them in Pokédex order. ✦ marks a shiny catch, † a species lost in a nuzlocke, and the mons you lost are listed last
/pokemon dex <mon>Show one mon's Pokédex number, how rare it is, and whether you've seen or caught it
Ctrl+X Ctrl+ACollapse or expand the band (Claude Code's own binding)

Requirements

  • Claude Code v2.1.287 or later, in the terminal or the Desktop app's Code tab.
  • In the terminal, a truecolor one, like iTerm2, Ghostty, kitty, or WezTerm. Light and dark themes both work.
  • The VS Code extension and the mobile app have no band to draw in, so the mon doesn't show there.

How it works

WhenThe monDriven by
Claude worksPaces back and forth across the stripband isWorking
Claude thinksShows a thought bubble with animated dotsspinner mode === 'thinking'
Claude runs a toolShows the tool in its bubble: a pencil for edits, a magnifier for reads and searches, >_ for shell, a Poké Ball for subagents, a wrench for the resttool.call (main agent only)
A skill is usedShows a TM disc in its bubble while a Skill call runs in any agent, and for 3 s when you type a skill as /name. Skills from your own files, plugins, and MCP servers count; Claude Code's built-in commands don'ttool.call (any agent), command.run, skill.prompt
A tool call failsShakes, then holds still with a blue sweat drop. Calls you deny or interrupt don't count. It skips the flinch while a move or a "!" is showingtool.call (main agent only), tool.check
Claude needs youStops, faces you, and shows a red "!" until you answer. If you don't reply within a minute of a turn ending, it shows the "!" for 2 minutesAskUserQuestion, ExitPlanMode, turn.complete, classic.PermissionRequest, classic.Notification
A subagent runsDrops a Poké Ball that wobbles while the subagent works and pops when it ends, or when the agent list stops reporting it at work, as for a teammate in its own pane. Past six, the last slot shows +n. With other mons in your box, the ball opens and one steps out to work beside yours, showing that subagent's thinking and tools in its own bubble, flinching when its calls fail, and hopping when it finishes before it goes back inagent.spawn, turn.step, tool.call (that agent), turn.complete, $.agent.list()
A turn endsHops twice, unless you interrupted itturn.complete (main agent only)
A turn ends with an answerEarns XP, and may level up or evolveturn.complete (main agent only)
A wild mon is dueWalks home, and the strip widens as the foe walks in from the lefttool.call (main agent only), the shared wildAt store key
Claude works during a battleBanks a move per tool call and answered turn, and fires one at the foe every 6 to 8 stool.call (any agent), turn.complete
You're idleStrolls to random spots, resting 3 to 8 s between walks. With wandering off, it walks home and bobs
5 minutes with no activityFalls asleep with pixel Zsprompt.edit, prompt.submit, turns
Food or happiness under 30%Thinks of a berry (hungry) or a heart (lonely). Walks slower when hungry
Happiness at 80% or moreHops for joy every 20 to 40 s
Both meters empty for 3 hours of open timeFaints, and runs away after 24 more unless you revive it$.clock, the shared stats store key

Some organizations run a policy plugin that blocks classic.* events from user plugins. Under one, the "!" still shows for questions, plan approval, and the idle minute, but not for permission dialogs.

Two meters sit at the bottom right of the band. Each icon is 20%.

MeterIconsEmpties from full inFilled by
Food●●●○○8 hours/pokemon feed: +20
Happiness♥♥♥♥♥, the last two dimmed12 hours/pokemon pet: +25, /pokemon feed: +5

The icons are plain text, one column each. Empty hearts are a dimmed ♥, because many fonts lack ♡ and borrow it from another font at another size. If your terminal draws emoji well, /pokemon emoji swaps them for 🍓🍓🍓○ ○ and 💗💗💗♡ ♡, two columns each. Run it again to switch back.

The meters drain at a quarter speed while Claude Code is closed. Only the mons on show drain, so the others in your box keep their meters until you pick them again. Each open session shows its own mon, but level, meters, nickname, and sleep belong to the mon, so sessions showing the same one share them. Asleep with /pokemon sleep, food drains at half speed and happiness at a quarter. A new mon starts at 80%. The meters scale the XP a turn earns, from half when both are empty to one and a half when both are full. /pokemon needs turns them off, and XP then ignores them.

Each subagent Claude starts drops a Poké Ball on the left of the strip. If your box holds other mons than the one on show, the subagent gets the next one free, highest level first, in the variant and nickname it was saved with. /pokemon party add <mon> and /pokemon party remove <mon> pick the party yourself, and then mons come out in the order you added them. /pokemon party assign <agent> <mon> ties a mon to an agent type, matched by the Agent tool's subagent_type without minding case, so an explore subagent always comes out as the same mon and the others never do. Once the ball lands it opens in a flash, and the mon hops out of it to work beside yours while the subagent runs, one mon at a time when several balls land together. It strolls about on its own, rests 3 to 8 s between walks, and shares the room with the other party mons, stepping aside when a neighbor's bubble needs it. Its bubble shows its own subagent's thinking dots and tools, a sweat drop shows when one of that subagent's calls fails, it hops along whenever your mon hops, jumps when a wild mon walks in behind it, and hops when the subagent finishes. Then it turns red, goes back into its ball in a flash, and the ball pops. /pokemon party lists the party and the subagent each one works for.

Party mons stand as tall as your mon and never shrink to fit. While one is out, the strip grows to the whole band, the same way it grows for a wild mon, and the party gets the room left of your mon's own 40 columns. As many come out as fit there side by side, each mon's width plus a gap, so an 80 column band fits one or two and a 160 column one up to five. The rest keep their balls closed and wobbling, with +n past six as before, and step out when room frees up. A wild mon gets its room first, so a party mon it crowds out goes back into its ball until the foe leaves. The strip shrinks back once the last party mon's ball pops. /pokemon pane follows the same rule in the pane's width.

A mon left with both meters empty for 3 hours of open session time faints. Time with Claude Code closed or the laptop asleep never counts, and each session gives the mon 10 minutes from when it first shows it before the clock runs, so a mon you come back to after a weekend is hungry but still yours to feed. Feeding or petting it before then stops the clock.

A fainted mon lies still with X eyes in faded colors while dizzy stars circle over its head. It doesn't move, earn XP, sleep, or evolve, wild mons stay away, and a foe on stage flees. /pokemon revive takes it to a Pokémon Center: it turns red and goes into its ball, and the band shows Nurse Joy, as she looks in FireRed and LeafGreen, behind her counter with the ball in the healing machine, flashing to its jingle. After 5 minutes of open time she bows, and the mon bursts back out of its ball at 50% food and 30% happiness. You can switch to another mon meanwhile, and the fainted one stays fainted in your box.

Left fainted for 24 hours of open session time, it runs away. Its record stays in your box, marked "ran away", with its level, XP, and nickname, and the band shows your highest level mon instead, or a line saying it ran away. The first wild encounter at least 30 minutes later is that mon, at its own level and variant, and after that it's one encounter in four until you catch it. It's a tier tougher and breaks out of the ball more often, even weak. Catching it brings it back with 50% food and 30% happiness.

/pokemon nuzlocke makes fainting final. A mon that faints is lost: its level, XP, and meters are gone, it leaves your box, and the Pokédex marks its species with †. /pokemon dex lists the mons you lost with their level and the date. The species can only be raised again by catching a new one in the wild, which starts at its first level. A mon fainted already when you turn nuzlocke on is lost at the next check, unless it's being healed. Turning nuzlocke off brings no one back.

StateStarts afterEnds with
Fainted3 h of open time at empty meters, past a session's first 10 min/pokemon revive, 5 min
Ran away24 h of open time faintedCatching it in the wild, first encounter 30 min on, then one in four
Lost (nuzlocke)The moment it would faintCatching a new one, from its first level

Each answered turn of the main agent earns 10 + 2 × level XP, doubled for turns of two minutes or more and scaled by the meters. Levels follow the games' medium fast curve, where level L takes L³ XP. A new mon starts at 5, or at the level it evolves at, so Charmeleon starts at 16. With 30 s turns and full meters, 5 to 16 takes about 75 turns.

When the mon reaches its evolution level from Red and Blue, it evolves once idle. It glows, flickers between its two shapes, and flashes into its new form. /pokemon stop cancels, and the next level-up tries again. Level, XP, and meters carry over. With /pokemon autoevolve off, reaching the level only makes the mon ready, and it evolves when you run /pokemon evolve.

The 19 mons that evolve with a stone or a trade, like Pikachu, Eevee, and Kadabra, use /pokemon evolve. Eevee needs a pick, like /pokemon evolve jolteon.

A move takes over the mon's body. For a move aimed ahead, the mon turns toward the roomier side, backs up to the far edge, and then winds up, lunges, or leaps as the effect plays across the strip. A move on itself, like Harden or Recover, plays in place, and the mon braces, shrinks, glows, or falls asleep. Teleport moves it to a random spot, Dig tunnels it forward, Transform borrows another mon's sprite, and Splash does nothing at all.

hooks/moves.js holds two tables. MOVE_FX maps each move to an effect, with an optional color, a power of 1 or 2, and a text line. MOVES lists each mon's moves. An entry can be { name, from: 'top' } to launch from the top of the sprite, like Vine Whip from Bulbasaur's bulb, or { name, from: 'body' } to pour from the whole body, like Koffing's Smog. An unknown effect plays impact.

File in hooks/effects/Effects
beams.jshyperbeam, solarbeam, psybeam, aurorabeam, icebeam, bubblebeam
electric.jsthundershock, thunderbolt, thunder, thunderwave
fire.jsember, flamethrower, firespin, dragonrage
water.jswatergun, hydropump, surf, waterfall, bubble, clamp
nature.jsvinewhip, razorleaf, petaldance, leechseed, drain, leechlife, powder, stringshot
poison.jspoisonsting, twineedle, acid, sludge, gas, pinmissile, spikecannon
mind.jsconfusion, psychic, kinesis, hypnosis, nightshade, lick, confuseray, dreameater
sound.jsscreech, supersonic, growl, roar, sing, lovelykiss
charge.jstackle, quickattack, bodyslam, headbutt, skullbash, takedown, rage, thrash, outrage, hornattack, horndrill, stomp, slam
strikes.jspound, doubleslap, megapunch, cometpunch, firepunch, icepunch, thunderpunch, megakick, lowkick, doublekick, hijumpkick, seismictoss, submission, karatechop
weapons.jsscratch, slash, furyswipes, cut, bite, hyperfang, crabhammer, vicegrip, guillotine, peck, drillpeck, furyattack, boneclub, bonemerang, wrap
sky.jsgust, wingattack, fly, skyattack, agility, doubleteam
earth.jsearthquake, dig, rockthrow, rockslide, sandattack, blizzard, mist
guard.jsharden, withdraw, defensecurl, minimize, focusenergy, meditate, amnesia, barrier, reflect, lightscreen, acidarmor
self.jsrecover, softboiled, rest, splash, teleport, transform, explosion
special.jsswift, payday, triattack, eggbomb

|

Source 52 files
hooks/register.js 1748 lines
1import { INKS } from './art.js'
2import { prepareAttack } from './attacks.js'
3import { drawScene, inkFor } from './band.js'
4import { clearAlert, isAlerted, raiseAlert } from './bubble.js'
5import {
6  attackCommand, battleWait, careReply, evolvingReply, moveKey, movesText, nicknameCommand, releaseCommand, waitsForCare,
7  waitsForEvolution,
8} from './commands.js'
9import { IMAGE_WAIT_TICKS, TICK_MS } from './constants.js'
10import { CREW_SIZE, crewThinking, crewToolEnds, crewToolStarts, isOut, joinCrew } from './crew.js'
11import { CUSTOM_PREFIX, fetchMon, monsOfGen } from './custom.js'
12import { dexKey, mergedDexEntry, pickWild, tierOf } from './dex.js'
13import { catchCommand, foeMoves, runawayFoe, wildMoves, wildName } from './encounter.js'
14import { evolutionsOf, startLevel } from './evolutions.js'
15import { SPRITES } from './frames.js'
16import { bandRows, bandZoom, battleFits, clampX, homeX, isHome, stripTarget, wildAt } from './layout.js'
17import { careOf, turnXp, xpAt } from './levels.js'
18import { bumpStat, filledIcons, iconsFor, isFull, isHappiest, park, STAT_ICONS, statNow, STATS, unpark } from './meters.js'
19import { feed, flinch, pet, startAttack, step } from './motion.js'
20import { displayName } from './names.js'
21import {
22  applyImageMode, cellsNow, drawsHearts, drawsImage, drawsImages, heartsImage, IMAGE_MODES, imageNow, svgNow,
23} from './paint.js'
24import { joinParty } from './party.js'
25import {
26  conditionOf, downReply, fullNameOf, goneLine, HEAL_MS, healingReply, levelOf, nameOf, readyToEvolve, revivedMeters,
27  settleHeal, xpOf,
28} from './records.js'
29import { addCustom, MONS, VARIANTS } from './sprites.js'
30import { S } from './state.js'
31import {
32  hasRunAway, isAsleep, isDead, isDown, isFainted, isFlinching, isFree, isGone, isHealing, isPetted, isTuckedIn, markActive,
33} from './status.js'
34import { assignedTo, canWork, crewVariant, endAgent, partyMons, stepCrewMons, typesOf } from './team.js'
35import { andList, boxText, dexText, evolutionText, HELP, helpText, orList, statsText } from './texts.js'
36import {
37  chargedWild, damageOf, faintedWild, fleeingWild, foeX, isHere, isOnStage, isWeak, newWild, STRIKE_GAP_MS, STRIKE_JITTER_MS,
38  stepWild, strikingWild, WEAK_MS, WILD_STAY_MS, WILD_TURNS,
39} from './wild.js'
40import { SIZES } from './zoom.js'
41
42// One pixel Pokémon lives in a strip at the right of the band above the prompt.
43// While Claude works it paces, with a thought bubble while Claude thinks. It
44// hops when a turn ends, then wanders while idle (or stays at the right edge,
45// after /pokemon wander) and falls asleep after five quiet minutes.
46// /pokemon pet makes pixel hearts float up, and /pokemon feed drops a random pixel
47// berry for it to walk over and eat. Food and happiness drain over time, slower while Claude Code is closed,
48// shown as ●●●○○ and ♥♥♥♡♡ at the right edge, so it needs both now and then.
49// /pokemon emoji swaps the meters' icons for 🍓 and 💗.
50// /pokemon sleep tucks it in, so both meters drain slower until Claude starts working.
51// /pokemon attack plays one of its moves, with the animations in attacks.js.
52// While a tool runs, the bubble shows it, with a TM disc for a skill from any agent, and
53// when Claude waits on you the mon stops and shows a "!". Each running subagent is a Poké Ball along the left of the strip,
54// and while the band has room a mon from your box steps out of it and works beside yours, as in crew.js.
55// A main-loop tool call that fails makes it flinch, with a sweat drop by its head.
56// Answered turns earn XP, and the mon evolves at the levels from the games.
57// Now and then a wild mon walks in from the left, and the strip widens to fit both.
58// Each open session shows its own mon, starting with the one last picked anywhere. XP,
59// meters, nickname, and sleep belong to the mon, so sessions showing the same mon share them.
60// Left with empty meters for hours it faints until /pokemon revive heals it, and left fainted it runs away.
61// With /pokemon nuzlocke on, a mon that faints is gone for good.
62// The mon, hearts, berries, bubbles, balls, and Zs are pixels in one Raster, two per cell.
63// The desktop app has no Raster, so there the same pixels are one Svg.
64//
65// Every function handed $ lives in this file, since the engine follows $ only into
66// functions declared in the hooks module itself. The rest of the band is in the modules
67// imported above, sharing its state through S in state.js.
68
69// How long the TM disc stays up after a skill is typed as /name
70const DISC_TICKS = 60
71// /pokemon pane moves the scene from the band into a pane, docked beside the transcript in
72// the fullscreen layout so Claude's replies keep the rest of the screen. It's drawn there
73// once the surface places it; until then the band goes on drawing it.
74const PANE_ID = 'pokemon'
75// The turn.step chunks that start or end a subagent's thinking
76const THOUGHT_KINDS = new Set(['thinking', 'text', 'tool', 'stop'])
77// Tools that ask you something, and notifications that wait on you
78const QUESTION_TOOLS = ['AskUserQuestion', 'ExitPlanMode']
79const ALERT_NOTIFICATIONS = ['permission_prompt', 'worker_permission_prompt', 'agent_needs_input', 'elicitation_dialog']
80// A minute after a turn with no word from you, the "!" shows for two
81const IDLE_WAIT_MS = 60 * 1000
82// What core tells the model when you turn a call down at its dialog or interrupt it.
83// Nothing else marks a refusal there, so the wording is the one sign.
84const REFUSED = /The user doesn't want to (proceed with this tool use|take this action)|\[Request interrupted by user/
85
86// Hold the disc when a command that ran is a skill, by its source in the command list
87async function markSkillCommand($, command) {
88  const found = (await $.command.list()).find((c) => c.name === command)
89  if (found && found.source !== 'builtin') S.discUntil = S.tick + DISC_TICKS
90}
91
92// What a fainted mon can't do, and what a mon that's gone can't do either
93const DOWN_WAITS = ['pet', 'feed', 'attack', 'catch', 'evolve', 'sleep']
94const GONE_WAITS = [...DOWN_WAITS, ...VARIANTS, 'nickname']
95
96// Play the evolve effect with the evolved mon swapped in, in a band grown to fit both
97function startEvolution($, into) {
98  $.ui.toast('What? ' + nameOf(S.mon) + ' is evolving!')
99  startAttack({ effect: 'evolve', color: S.ink.silhouette })
100  S.attack.swap = into
101  S.evolving = { from: S.mon, into }
102  S.evolveDue = null
103  $.ui.invalidate('ui.render')
104}
105
106// Start a due evolution once the mon is free, and finish one whose effect is over
107function stepEvolution($) {
108  if (S.evolving && !S.attack) finishEvolution($)
109  else if (S.evolveDue && isFree()) startEvolution($, S.evolveDue)
110}
111
112// The evolved mon takes over the record as last saved, so XP earned elsewhere comes along.
113// 'evolved' tells another session showing the old mon that it evolved rather than being released.
114async function moveRecord($, from, into) {
115  await freshen($, [from])
116  S.stats[into] = { ...S.stats[from], xp: xpOf(from) }
117  delete S.stats[from]
118  await saveStats($, [from, into])
119  const evolved = (await $.store.get('evolved')) ?? {}
120  await $.store.set('evolved', { ...evolved, [from]: into })
121}
122
123// The mon becomes the evolved one. Its record moves along, so level, XP, and meters carry over.
124function finishEvolution($) {
125  const { from, into } = S.evolving
126  const wasHome = isHome()
127  S.evolving = null
128  S.mon = into
129  if (wasHome) S.x = homeX()
130  clampX()
131  const name = nameOf(from)
132  saveMon($).catch((err) => logOnce($, err))
133  moveRecord($, from, into).catch((err) => logOnce($, err))
134  $.ui.toast('Congratulations! Your ' + name + ' evolved into ' + displayName(into) + '!')
135  $.ui.invalidate('ui.render')
136}
137
138// Call off an evolution under way or due. The mon stays as it is.
139function stopEvolution($) {
140  const name = nameOf(S.mon)
141  if (!S.evolving && !S.evolveDue) return { text: name + ' isn\'t evolving.' }
142  if (S.evolving) S.attack = null
143  S.evolving = null
144  S.evolveDue = null
145  $.ui.invalidate('ui.render')
146  return { text: 'Huh? ' + name + ' stopped evolving!' }
147}
148
149// A stone, a trade, or a level the mon has reached starts its evolution now. Several
150// ways and none named get a list.
151function evolveCommand($, wanted) {
152  const name = nameOf(S.mon)
153  const entries = evolutionsOf(S.mon)
154  if (entries.length === 0) return { text: name + ' doesn\'t evolve.' }
155  if (S.attack || S.food) return { text: name + ' is busy right now.' }
156  const picked = wanted ? entries.filter((entry) => moveKey(entry.into) === moveKey(wanted)) : entries
157  if (picked.length !== 1) {
158    const example = entries[Math.floor(Math.random() * entries.length)].into
159    return { text: name + ' can become ' + orList(entries.map(evolutionText)) + '. Try /pokemon evolve ' + example + '.' }
160  }
161  const [entry] = picked
162  const level = levelOf(S.mon)
163  if (entry.level && level < entry.level) {
164    return { text: name + ' evolves into ' + displayName(entry.into) + ' at Lv. ' + entry.level + '. It\'s Lv. ' + level + '.' }
165  }
166  startEvolution($, entry.into)
167  if (entry.item) return { text: 'You use a ' + entry.item + ' on ' + name + '.' }
168  if (entry.trade) return { text: 'You trade ' + name + ' to a friend, and they trade it right back.' }
169  return { text: 'You let ' + name + ' evolve.' }
170}
171
172// Send the foe off, with a toast unless quiet. One still calling just doesn't come, and
173// a fainted one blinks away where it lies.
174function fleeWild($, quiet = false) {
175  if (S.wild?.phase === 'fainted') return
176  const shown = isOnStage(S.wild) && S.wild.phase !== 'fleeing'
177  if (shown && !quiet) $.ui.toast('Wild ' + displayName(S.wild.mon) + ' fled!')
178  S.wild = fleeingWild(S.wild, wildAt())
179}
180
181// Mark a mon in the Pokédex as last saved by any session, so two sessions marking at once
182// lose a mark at worst
183async function markDex($, key, patch) {
184  const saved = await $.store.get('dex')
185  const dex = saved && typeof saved === 'object' ? { ...saved } : {}
186  dex[key] = mergedDexEntry(dex[key], patch)
187  await $.store.set('dex', dex)
188}
189
190// Move the visit on a tick. Asleep or fainted, the home mon can't fight, so the foe leaves.
191function stepWildPhase($) {
192  if (!S.wild) return
193  if (!['fleeing', 'fainted'].includes(S.wild.phase) && (isTuckedIn() || isAsleep() || isDown())) return fleeWild($)
194  const result = stepWild(S.wild, { tick: S.tick, atHome: isHome() && !S.attack, at: wildAt(), stayTicks: WILD_STAY_MS / TICK_MS })
195  if (result.event === 'timeout') fleeWild($)
196  else S.wild = result.wild
197  if (result.event === 'arrived') {
198    S.wild = { ...S.wild, nextStrikeAt: S.tick + strikeGap() }
199    const yours = S.wild.runaway ? ' It looks a lot like ' + (S.stats[S.wild.mon]?.nickname ?? 'your ' + displayName(S.wild.mon)) + '.' : ''
200    $.ui.toast('A ' + wildName() + ' (Lv. ' + S.wild.level + ') appeared!' + yours)
201    markDex($, S.wild.key, { seen: S.nowMs }).catch((err) => logOnce($, err))
202    if (S.wild.runaway) metRunaway($, S.wild.mon).catch((err) => logOnce($, err))
203  } else if (result.event === 'caught') {
204    caughtFoe($, S.wild).catch((err) => logOnce($, err))
205  } else if (result.event === 'brokefree') {
206    $.ui.toast(BROKE_FREE[S.wild.throw.shakes])
207  }
208  if (S.wild?.phase === 'battle') stepBattle($)
209}
210
211// What breaks free says, by how many times the ball rocked first
212const BROKE_FREE = ['Oh no! It broke free!', 'Aww! It appeared to be caught!', 'Aww! It appeared to be caught!', 'Argh! So close!']
213
214// Mark the catch in the Pokédex, and put the species in the box at its first level with
215// fresh meters, parked unless it's the mon on show. A species already there stays as it is,
216// unless it ran away, when its record comes back, or died, when a fresh one takes its place.
217async function caughtFoe($, caught) {
218  const species = caught.mon
219  const name = displayName(species)
220  S.nowMs = await $.clock.now()
221  await markDex($, caught.key, { caught: S.nowMs, ...(caught.variant === 'shiny' ? { shiny: true } : {}) })
222  await freshen($, [species])
223  if (hasRunAway(species)) {
224    const { ranAway, fainted, healing, starving, ...record } = S.stats[species]
225    S.stats[species] = { ...record, ...revivedMeters(), ...(species === S.mon ? {} : { parked: true }) }
226    await saveRecords($, [species])
227    $.ui.toast('Gotcha! ' + nameOf(species) + ' came back to you.')
228    $.ui.invalidate('ui.render')
229    return
230  }
231  if (isDead(species)) delete S.stats[species]
232  if (S.stats[species]) {
233    $.ui.toast('Gotcha! ' + name + ' was caught! ' + name + ' is already in your box, so it\'s marked in your Pokédex.')
234    return
235  }
236  S.stats[species] = { xp: xpAt(startLevel(species)), caught: true, ...(species === S.mon ? {} : { parked: true }) }
237  await saveRecords($, [species])
238  $.ui.toast('Gotcha! ' + name + ' was caught! It joined your box.')
239}
240
241// The desktop app stops the running turn when you send it a message, and a foe only
242// fights mid-turn, so the desktop band attacks and throws the ball from buttons instead.
243// They can't be disabled, so while the mon is evolving, busy or down they draw dim and a
244// press only says why, as /pokemon catch and attack would.
245function battleButtons($, { Box, Button }) {
246  if (S.wild?.phase !== 'battle') return []
247  const press = (act) => {
248    const reply = battleWait() ?? act()
249    markActive()
250    $.ui.toast(reply.text)
251    $.ui.invalidate('ui.render')
252  }
253  const dimColor = battleWait() !== null
254  return [
255    Box({
256      flexDirection: 'row',
257      gap: 1,
258      children: [
259        Button({ key: 'catch', label: 'Catch', variant: 'primary', dimColor, onPress: () => press(catchCommand) }),
260        Button({ key: 'attack', label: 'Attack', dimColor, onPress: () => press(() => attackCommand('')) }),
261      ],
262    }),
263  ]
264}
265
266const strikeGap = () => Math.round((STRIKE_GAP_MS + Math.random() * STRIKE_JITTER_MS) / TICK_MS)
267const STRIKE_DELAY_TICKS = 2000 / TICK_MS
268
269// Land a move on the foe 60% of the way through it, and spend banked work on the next
270// move once the mon is free, awake, at home, and its last move is long enough ago. The
271// mon holds off a weak foe, so only /pokemon attack knocks it out.
272function stepBattle($) {
273  if (S.attack?.atFoe && !S.attack.landed && !S.attack.backing && S.tick >= S.attack.start + Math.round(S.attack.ticks * 0.6)) {
274    S.attack.landed = true
275    hitFoe($)
276    if (S.wild.phase !== 'battle') return
277  }
278  strikeBack($)
279  const ready = !S.wild.strike && !S.attack && !S.food && !S.evolving && !isAlerted() && !isFlinching() && !isAsleep() && S.x === homeX()
280  if (!ready || isWeak(S.wild) || S.wild.charge === 0 || S.tick < S.wild.nextAttackAt) return
281  const moves = foeMoves()
282  const move = moves[Math.floor(Math.random() * moves.length)]
283  S.wild = { ...S.wild, charge: S.wild.charge - 1 }
284  startAttack(move, { foe: true })
285  $.ui.toast(nameOf(S.mon) + ' used ' + move.name + '!')
286}
287
288// Now and then the foe plays one of its own moves at the free mon. It lands 60% of the
289// way through, and only makes the mon flinch and puts its next move off, so a fight
290// never touches the mon's meters.
291function strikeBack($) {
292  const { strike } = S.wild
293  if (strike && !strike.landed && S.tick >= strike.start + Math.round(strike.attack.ticks * 0.6)) {
294    S.wild = { ...S.wild, strike: { ...strike, landed: true }, nextAttackAt: Math.max(S.wild.nextAttackAt, S.tick + STRIKE_DELAY_TICKS) }
295    flinch()
296  }
297  if (strike && S.tick >= strike.start + strike.attack.ticks) S.wild = { ...S.wild, strike: null }
298  const free = !S.wild.strike && !S.attack && !S.food && !S.evolving && !isAsleep() && S.x === homeX()
299  if (!free || S.tick < S.wild.nextStrikeAt) return
300  const moves = wildMoves()
301  const move = moves[Math.floor(Math.random() * moves.length)]
302  const seed = Math.floor(Math.random() * 0x7fffffff)
303  const attack = prepareAttack(move, { side: 'right', seed, x: foeX(S.wild, wildAt()), home: homeX() })
304  S.wild = strikingWild(S.wild, move, attack, S.tick, S.tick + strikeGap())
305  $.ui.toast('Wild ' + displayName(S.wild.mon) + ' used ' + move.name + '!')
306}
307
308// A hit resets the foe's wait for a fight. Weak, it waits WEAK_MS for a ball, and at 0 HP
309// it faints.
310function hitFoe($) {
311  const name = displayName(S.wild.mon)
312  const hp = Math.max(0, Math.round(S.wild.hp - damageOf(S.wild, S.attack.power, Math.random())))
313  if (hp === 0) {
314    S.wild = faintedWild(S.wild, S.tick)
315    $.ui.toast('Wild ' + name + ' fainted! It can\'t be caught now.')
316    return
317  }
318  const weak = isWeak({ ...S.wild, hp })
319  const stay = (weak ? WEAK_MS : WILD_STAY_MS) / TICK_MS
320  if (weak && !isWeak(S.wild)) $.ui.toast('Wild ' + name + ' is weak! Throw a ball with /pokemon catch. Another hit could knock it out.')
321  S.wild = { ...S.wild, hp, hitAt: S.tick, leaveAt: S.tick + stay }
322}
323
324const SPAWN_CHECK_TICKS = (30 * 1000) / TICK_MS
325const FIRST_WILD_MS = 5 * 60 * 1000
326const WILD_EVERY_MS = [20 * 60 * 1000, 40 * 60 * 1000]
327
328// Every session shares one gate in the store, wildAt = { at, by }, so encounters come
329// every 20 to 40 minutes of work however many sessions run. A session finding it due
330// claims it with its token and checks on its next call that no other session's claim
331// landed over its own before the mon shows up.
332async function maybeSpawn($) {
333  if (S.tick - S.lastSpawnCheck < SPAWN_CHECK_TICKS) return
334  S.lastSpawnCheck = S.tick
335  const pick = S.claimedPick
336  S.claimedPick = null
337  if (!S.turnRunning || S.wild || isTuckedIn() || isAsleep() || isDown()) return
338  const now = await $.clock.now()
339  const gate = await $.store.get('wildAt')
340  if (pick) {
341    if (gate?.by === S.sessionToken && !S.wild && !isDown() && battleFits(pick.mon, pick.variant)) S.wild = newWild(pick, Math.floor(Math.random() * 0x7fffffff))
342    return
343  }
344  if (typeof gate?.at !== 'number') return $.store.set('wildAt', { at: now + FIRST_WILD_MS, by: S.sessionToken })
345  if (now < gate.at) return
346  const next = (await runawayPick($, now)) ?? pickWild(Math.random)
347  if (!battleFits(next.mon, next.variant)) return
348  const wait = WILD_EVERY_MS[0] + Math.random() * (WILD_EVERY_MS[1] - WILD_EVERY_MS[0])
349  await $.store.set('wildAt', { at: now + Math.round(wait), by: S.sessionToken })
350  S.claimedPick = next
351}
352
353const RUNAWAY_BACK_MS = 30 * 60 * 1000
354const RUNAWAY_ODDS = 0.25
355
356// The first encounter at least RUNAWAY_BACK_MS after a mon ran away is that mon, and after
357// that it's one in RUNAWAY_ODDS until it's caught. Null for a wild mon as usual.
358async function runawayPick($, now) {
359  const saved = await $.store.get('stats')
360  if (!saved || typeof saved !== 'object') return null
361  const back = Object.keys(saved).filter((name) => MONS.includes(name) && saved[name]?.ranAway && !saved[name].dead && now - saved[name].ranAway.at >= RUNAWAY_BACK_MS)
362  if (back.length === 0) return null
363  await freshen($, back)
364  const unmet = back.find((name) => hasRunAway(name) && !S.stats[name].ranAway.met)
365  if (unmet) return runawayFoe(unmet)
366  const met = back.filter(hasRunAway)
367  return met.length > 0 && Math.random() < RUNAWAY_ODDS ? runawayFoe(met[Math.floor(Math.random() * met.length)]) : null
368}
369
370// Once a mon that ran away has shown up, it's met, and later encounters are it only by chance
371async function metRunaway($, name) {
372  await freshen($, [name])
373  if (!hasRunAway(name) || S.stats[name].ranAway.met) return
374  S.stats[name] = { ...S.stats[name], ranAway: { ...S.stats[name].ranAway, met: true } }
375  await saveRecords($, [name])
376}
377
378// The hidden debug spawn, /pokemon wild [<mon>] [shiny]. Null when debug is off, so it
379// reads as an unknown option. A mon that ran away comes as itself.
380async function wildCommand($, rest) {
381  if ((await $.store.get('debug')) !== true) return null
382  const words = rest.split(/\s+/).filter(Boolean)
383  const name = words.find((word) => word !== 'shiny')
384  if (name && !MONS.includes(name)) return { text: 'Unknown mon "' + name + '". See /pokemon list for every mon.' }
385  if (S.wild) return { text: 'A wild ' + displayName(S.wild.mon) + ' is already here.' }
386  if (isTuckedIn()) return { text: nameOf(S.mon) + ' is asleep.' }
387  if (isDown()) return downReply()
388  if (name) await freshen($, [name])
389  const own = name && hasRunAway(name) ? runawayFoe(name) : null
390  const pick = own ?? (name ? { mon: name, variant: 'default', key: dexKey(name), tier: tierOf(name), level: startLevel(name) } : pickWild(Math.random))
391  if (words.includes('shiny')) pick.variant = 'shiny'
392  if (!battleFits(pick.mon, pick.variant)) return { text: 'The band is too narrow for a wild ' + displayName(pick.mon) + '. Widen the pane and try again.' }
393  S.wild = newWild(pick, Math.floor(Math.random() * 0x7fffffff))
394  S.wanderTarget = null
395  return { text: 'A wild ' + displayName(pick.mon) + ' is on its way.' }
396}
397
398// The hidden debug faint, /pokemon kill. It faints the shown mon as neglect would, or
399// loses it under nuzlocke. Null when debug is off, so it reads as an unknown option.
400async function killCommand($) {
401  if ((await $.store.get('debug')) !== true) return null
402  S.nowMs = await $.clock.now()
403  await freshen($, [S.mon])
404  if (isDown()) return downReply()
405  const name = nameOf(S.mon)
406  await (S.nuzlockeOn ? loseMon($, S.mon) : faintMon($))
407  return { text: name + (S.nuzlockeOn ? ' fainted for good.' : ' fainted.') }
408}
409
410const PET_HAPPINESS = 25
411const STAT_REDRAW_TICKS = 1200
412
413// Fill the meters once the berry is eaten or the hearts have floated away, not when
414// asked, for the mon that was fed or petted
415function stepOwed($) {
416  if (S.pettingFills && !isPetted()) {
417    S.owed.push({ name: S.pettingFills, happiness: PET_HAPPINESS })
418    S.pettingFills = null
419  }
420  if (S.owed.length > 0) payOwed($, S.owed.splice(0)).catch((err) => logOnce($, err))
421}
422
423async function payOwed($, gains) {
424  S.nowMs = await $.clock.now()
425  const names = [...new Set(gains.map((g) => g.name))]
426  await freshen($, names)
427  for (const { name, ...meters } of gains) {
428    for (const [key, amount] of Object.entries(meters)) bumpStat(key, amount, name)
429  }
430  await saveRecords($, names)
431  $.ui.invalidate('ui.render')
432}
433
434// Saves both meters as they are now before the drain rate changes, so the slower
435// rate only covers the time asleep
436async function setAsleep($, asleep) {
437  await freshen($, [S.mon])
438  for (const key of Object.keys(STATS)) bumpStat(key, 0)
439  S.stats[S.mon] = { ...S.stats[S.mon], asleep }
440  await saveStats($, [S.mon])
441  $.ui.invalidate('ui.render')
442}
443
444// Every open session shares the store, so a session saves only the records it changed
445// over the stored ones and picks up the others' as it goes. It counts its saves, and the
446// ones still being written, so a sync that read the store before one landed doesn't undo it.
447let statWrites = 0
448let statSaving = 0
449
450async function saveStats($, names) {
451  await saveRecords($, names)
452}
453
454// Take these mons' records as last saved by any session, right before changing them, so
455// a change lands on another session's newest XP and meters rather than on this one's
456// copy from the last sync. A record gone from the store was released in another session,
457// so it goes here too rather than being saved back. The shown mon is never parked here.
458async function freshen($, names) {
459  const saved = await $.store.get('stats')
460  if (!saved || typeof saved !== 'object') return
461  for (const name of names) {
462    if (!saved[name]) {
463      delete S.stats[name]
464      continue
465    }
466    const { parked, ...shown } = saved[name]
467    S.stats[name] = name === S.mon ? shown : saved[name]
468  }
469}
470
471async function saveRecords($, names) {
472  statWrites += 1
473  statSaving += 1
474  try {
475    const saved = await $.store.get('stats')
476    const merged = saved && typeof saved === 'object' ? { ...saved } : {}
477    const started = names.filter((name) => S.stats[name] && !merged[name])
478    for (const name of names) {
479      if (S.stats[name]) merged[name] = S.stats[name]
480      else delete merged[name]
481    }
482    S.stats = merged
483    await $.store.set('stats', merged)
484    // A mon raised again from scratch no longer points at what it once evolved into
485    if (started.length > 0) {
486      const evolved = await $.store.get('evolved')
487      if (evolved && started.some((name) => name in evolved)) {
488        const rest = { ...evolved }
489        for (const name of started) delete rest[name]
490        await $.store.set('evolved', rest)
491      }
492    }
493  } finally {
494    statSaving -= 1
495  }
496}
497
498// 'mon' is the last one picked in any session, and a new session starts with it. A mon
499// picked here is shown as itself, even if it once evolved in another session.
500async function saveMon($) {
501  S.seenPick = S.mon
502  await $.store.set('mon', S.mon)
503  const evolved = await $.store.get('evolved')
504  if (evolved && S.mon in evolved) {
505    const { [S.mon]: _, ...rest } = evolved
506    await $.store.set('evolved', rest)
507  }
508}
509
510// Earlier versions kept a mon per session under 'mon:' keys and a busy mark under 'busy:' keys
511async function forgetOldKeys($) {
512  for (const key of await $.store.keys()) {
513    if (key.startsWith('mon:') || key.startsWith('busy:')) await $.store.delete(key)
514  }
515}
516
517const SYNC_TICKS = 20
518// How often the party is checked against the live agents, and how old a ball must be
519// before a missing agent pops it, so a fresh spawn the list hasn't caught up with stays
520const PARTY_SYNC_TICKS = 40
521// An agent still at work, as the agent list reports it
522const LIVE_STATUSES = ['pending', 'running', 'waiting']
523
524// Pop the ball of any agent the engine no longer reports at work. A teammate in a pane of
525// its own runs no loop here, so its turn never completes in this process, and this is the
526// only way its ball ever pops.
527async function syncParty($) {
528  const open = S.party.filter((ball) => ball.popStart === null && S.tick - ball.born >= PARTY_SYNC_TICKS)
529  if (open.length === 0) return
530  const live = new Set()
531  for (const agent of await $.agent.list()) {
532    if (!LIVE_STATUSES.includes(agent.status)) continue
533    live.add(agent.id)
534    if (agent.teammateId) live.add(agent.teammateId)
535  }
536  for (const ball of open) if (!live.has(ball.id)) endAgent(ball.id)
537}
538
539async function loadPartyPicks($) {
540  const saved = await $.store.get('partyPicks')
541  S.partyPicks = Array.isArray(saved) ? saved.filter((name) => MONS.includes(name)) : null
542  const agents = await $.store.get('partyAgents')
543  S.partyAgents = {}
544  if (agents && typeof agents === 'object') {
545    for (const [type, name] of Object.entries(agents)) if (MONS.includes(name)) S.partyAgents[type] = name
546  }
547}
548
549// Give a new subagent the mon assigned to its agent type, or when that one is busy or
550// can't work, the next party mon nobody has, from the box as last saved
551async function joinCrewFor($, id, type) {
552  const saved = await $.store.get('stats')
553  if (saved && typeof saved === 'object') await freshen($, Object.keys(saved))
554  await loadPartyPicks($)
555  const dex = await $.store.get('dex')
556  const assigned = assignedTo(type)
557  const mons = assigned && canWork(assigned) ? [assigned, ...partyMons()] : partyMons()
558  S.crew = joinCrew(S.crew, id, mons, (name) => crewVariant(name, dex))
559}
560
561// Show the mon this one evolved into in another session, once nothing here is mid-move
562function followEvolution($, into, record) {
563  if (S.evolving || S.attack) return
564  const name = nameOf(S.mon)
565  const wasHome = isHome()
566  delete S.stats[S.mon]
567  S.stats[into] = record
568  S.evolveDue = null
569  S.mon = into
570  if (wasHome) S.x = homeX()
571  clampX()
572  S.sentCells = null
573  $.ui.toast('Congratulations! Your ' + name + ' evolved into ' + displayName(into) + '!')
574  $.ui.invalidate('ui.render')
575}
576
577// With sync on, show the mon last picked in another session. A pick that's this mon
578// evolving elsewhere is left to followEvolution. Says whether it switched.
579async function followPick($) {
580  const pick = await $.store.get('mon')
581  if (pick === S.seenPick || typeof pick !== 'string') return false
582  if (!MONS.includes(pick)) await loadCustom($)
583  const evolved = await $.store.get('evolved')
584  if (S.evolving || S.attack || evolved?.[S.mon] === pick) return false
585  S.seenPick = pick
586  if (pick === S.mon || !MONS.includes(pick)) return false
587  // A mon gone from the box can't be shown, so this session keeps its own
588  await freshen($, [pick])
589  if (isGone(pick)) return false
590  await switchTo($, pick, { save: false })
591  S.sentCells = null
592  $.ui.invalidate('ui.render')
593  return true
594}
595
596// Take the shown mon's record as another session showing it saved it: fed, petted, earned
597// XP, or put to bed. Put to bed elsewhere while Claude works here, it wakes right back up
598// in stepWake.
599async function syncSessions($) {
600  S.syncOn = (await $.store.get('sync')) === true
601  S.nuzlockeOn = (await $.store.get('nuzlocke')) === true
602  S.trainerOn = (await $.store.get('trainer')) !== false
603  if (S.syncOn && (await followPick($))) return
604  const writes = statWrites
605  const saved = await $.store.get('stats')
606  const evolved = await $.store.get('evolved')
607  // Nothing may await between this check and acting on what was read
608  if (statSaving > 0 || writes !== statWrites) return
609  // Evolved in another session, the shown mon evolves here too. Released, it starts over.
610  if (!saved?.[S.mon]) {
611    const into = evolved?.[S.mon]
612    if (MONS.includes(into) && saved?.[into]) {
613      followEvolution($, into, saved[into])
614      return
615    }
616    if (S.stats[S.mon] && saved && typeof saved === 'object') {
617      delete S.stats[S.mon]
618      S.evolveDue = null
619      $.ui.invalidate('ui.render')
620    }
621    return
622  }
623  // Run away or lost in another session, it leaves this band too
624  if (!isGone(S.mon) && (saved[S.mon].ranAway || saved[S.mon].dead)) {
625    S.stats[S.mon] = saved[S.mon]
626    await leaveBand($, { save: false })
627    return
628  }
629  // A session that switched away from the shown mon parked it. It's still on show here, so
630  // its record goes back unparked and drains on from where the park left it.
631  const { parked, ...theirs } = saved[S.mon]
632  if (parked && !isGone(S.mon)) {
633    await freshen($, [S.mon])
634    await saveRecords($, [S.mon])
635  } else if (JSON.stringify(theirs) === JSON.stringify(S.stats[S.mon])) {
636    return
637  } else {
638    const wasFainted = isFainted(S.mon)
639    S.stats[S.mon] = theirs
640    if (!wasFainted && isFainted(S.mon)) $.ui.toast(nameOf(S.mon) + ' fainted! /pokemon revive takes it to a Pokémon Center.')
641  }
642  $.ui.invalidate('ui.render')
643}
644
645// A tucked-in mon wakes when Claude starts working, or when it has a berry to eat,
646// a move to play, or an evolution to go through
647function stepWake($) {
648  if (isTuckedIn() && (S.turnRunning || S.food || S.attack || S.evolving || S.evolveDue)) setAsleep($, false).catch((err) => logOnce($, err))
649}
650
651// An answered turn earns XP, scaled by care. A level-up toasts the new level once, and
652// an evolution it reaches is due.
653async function gainXp($, durationMs) {
654  S.nowMs = await $.clock.now()
655  await freshen($, [S.mon])
656  if (isDown()) return
657  const was = levelOf(S.mon)
658  const care = S.needsOn ? careOf(statNow(S.mon, 'food'), statNow(S.mon, 'happiness')) : 1
659  S.stats[S.mon] = { ...S.stats[S.mon], xp: xpOf(S.mon) + turnXp({ level: was, durationMs, care }) }
660  await saveStats($, [S.mon])
661  const level = levelOf(S.mon)
662  if (level === was) return
663  $.ui.toast(nameOf(S.mon) + ' grew to Lv. ' + level + '!')
664  $.ui.invalidate('ui.render')
665  const into = readyToEvolve()
666  if (!into) return
667  if (S.autoEvolve) S.evolveDue = into
668  else $.ui.toast(nameOf(S.mon) + ' is ready to evolve into ' + displayName(into) + '! /pokemon evolve lets it.')
669}
670
671// The box's mons beside the one on show that come out of subagents' balls, one a line,
672// like "Sparky (Pikachu), Lv. 12, working for Count files", with the agent named by its
673// description in the agent list
674async function partyText($) {
675  const saved = await $.store.get('stats')
676  if (saved && typeof saved === 'object') await freshen($, Object.keys(saved))
677  await loadPartyPicks($)
678  const assigned = [...new Set(Object.values(S.partyAgents))].filter(canWork)
679  const mons = [...assigned, ...partyMons()]
680  if (mons.length === 0 && S.partyPicks) return 'Your party is empty. Add a mon from your box with /pokemon party add <mon>.'
681  if (mons.length === 0) return 'Your party is empty. Raise or catch another mon, and it comes out of a subagent\'s Poké Ball to work beside ' + nameOf(S.mon) + '.'
682  const agents = await $.agent.list().catch(() => [])
683  const described = new Map((Array.isArray(agents) ? agents : []).map((agent) => [agent.id, agent.description || agent.id]))
684  const lines = mons.map((name) => {
685    const member = S.crew.find((m) => m.mon === name && m.endAt === null)
686    const types = typesOf(name)
687    const shown = fullNameOf(name) + ', Lv. ' + levelOf(name) + (types.length > 0 ? ', for ' + types.join(' and ') : '')
688    if (!member) return shown + ', free'
689    const waiting = isOut(member, S.tick) ? '' : ', waiting in its ball for room'
690    return shown + ', working for ' + (described.get(member.id) ?? member.id) + waiting
691  })
692  const count = mons.length + (mons.length === 1 ? ' mon' : ' mons')
693  return count + ' in your party, beside ' + nameOf(S.mon) + ':\n' + lines.join('\n')
694}
695
696// Add a box mon to the party or take one out. The first change starts from the party as
697// it stands, and a mon taken out while it works finishes its subagent first.
698async function partyCommand($, verb, wanted) {
699  const saved = await $.store.get('stats')
700  if (saved && typeof saved === 'object') await freshen($, Object.keys(saved))
701  await loadPartyPicks($)
702  const example = verb === 'add' ? 'dratini' : (partyMons()[0] ?? 'pikachu')
703  if (!wanted) return { text: 'Name the mon, like /pokemon party ' + verb + ' ' + example + '. /pokemon box lists yours.' }
704  if (!MONS.includes(wanted)) return { text: 'Unknown mon "' + wanted + '". /pokemon box lists yours.' }
705  const picks = S.partyPicks ?? partyMons()
706  const name = nameOf(wanted)
707  if (verb === 'remove') {
708    if (!picks.includes(wanted)) return { text: name + ' isn\'t in your party.' }
709    S.partyPicks = picks.filter((pick) => pick !== wanted)
710    await $.store.set('partyPicks', S.partyPicks)
711    const working = S.crew.some((m) => m.mon === wanted && m.endAt === null)
712    return { text: name + ' leaves your party.' + (working ? ' It finishes its subagent\'s work first.' : '') }
713  }
714  if (wanted === S.mon) return { text: name + ' is the mon on show. Pick another with /pokemon <mon> first.' }
715  if (!S.stats[wanted] || isDead(wanted)) return { text: displayName(wanted) + ' isn\'t in your box. Catch one, or pick it with /pokemon ' + wanted + '.' }
716  if (isGone(wanted)) return { text: name + ' ran away. Catch it in the wild to bring it back.' }
717  if (picks.includes(wanted)) return { text: name + ' is already in your party.' }
718  if (picks.length >= CREW_SIZE) return { text: 'Your party is full at ' + CREW_SIZE + '. Take one out with /pokemon party remove <mon> first.' }
719  S.partyPicks = [...picks, wanted]
720  await $.store.set('partyPicks', S.partyPicks)
721  const resting = isFainted(wanted) ? ' It rests until it\'s revived.' : ''
722  return { text: name + ' joins your party.' + resting }
723}
724
725// Assign a box mon to an agent type, so every subagent of that type comes out as it, or
726// take an assignment back. A mon works for one agent type at a time.
727async function assignCommand($, verb, words) {
728  const saved = await $.store.get('stats')
729  if (saved && typeof saved === 'object') await freshen($, Object.keys(saved))
730  await loadPartyPicks($)
731  if (verb === 'unassign') {
732    const type = words.join(' ')
733    if (!type) return { text: 'Name the agent type, like /pokemon party unassign explore.' }
734    if (!S.partyAgents[type]) return { text: 'No mon is assigned to ' + type + '.' }
735    const name = nameOf(S.partyAgents[type])
736    delete S.partyAgents[type]
737    await $.store.set('partyAgents', S.partyAgents)
738    return { text: name + ' no longer comes out for ' + type + '.' }
739  }
740  if (words.length < 2) return { text: 'Name the agent type and the mon, like /pokemon party assign explore abra.' }
741  const wanted = words.at(-1)
742  const type = words.slice(0, -1).join(' ')
743  if (!MONS.includes(wanted)) return { text: 'Unknown mon "' + wanted + '". /pokemon box lists yours.' }
744  const name = nameOf(wanted)
745  if (wanted === S.mon) return { text: name + ' is the mon on show. Pick another with /pokemon <mon> first.' }
746  if (!S.stats[wanted] || isDead(wanted)) return { text: displayName(wanted) + ' isn\'t in your box. Catch one, or pick it with /pokemon ' + wanted + '.' }
747  if (isGone(wanted)) return { text: name + ' ran away. Catch it in the wild to bring it back.' }
748  const before = typesOf(wanted).filter((other) => other !== type)
749  for (const other of before) delete S.partyAgents[other]
750  S.partyAgents[type] = wanted
751  await $.store.set('partyAgents', S.partyAgents)
752  const moved = before.length > 0 ? ' It no longer comes out for ' + before.join(' or ') + '.' : ''
753  const resting = isFainted(wanted) ? ' It rests until it\'s revived.' : ''
754  return { text: name + ' comes out for every ' + type + ' subagent.' + moved + resting }
755}
756
757const OPTIONS = [...HELP.flatMap(([, rows]) => rows.map(([usage]) => usage.split(' ')[0])), 'help']
758
759const PET_LINES = ['loves it', 'wiggles happily', 'leans into your hand', 'does a little hop', 'looks very pleased']
760
761// Send the frame only when it differs from the last one sent or drawn. A resize can
762// remount the band, and the host then refuses frames for the old one, so a refused
763// frame asks for a redraw, at most once a second, which draws the band anew.
764const REDRAW_AFTER_REFUSAL_TICKS = 20
765let refusedAt = -Infinity
766function blitFrame($) {
767  const zoom = bandZoom()
768  if (!zoom) return
769  if (S.imageRetryAt !== null && S.tick >= S.imageRetryAt) S.imageRetryAt = null
770  // Going between the Image and cells takes a redraw, so the blits wait for it
771  if (drawsImage() !== S.drawnImage || drawsHearts() !== S.drawnHearts) return $.ui.invalidate('ui.render')
772  if (S.drawnHearts) blitHearts($)
773  if (S.drawnImage) return blitImage($, zoom)
774  const cells = cellsNow()
775  if (cells === S.sentCells) return
776  S.sentCells = cells
777  $.ui
778    .blit({ requestId: S.bandId, key: 'pokemon', columns: zoom.columns, rows: zoom.rows, cells })
779    .then((result) => {
780      if (!result?.deny) return
781      S.sentCells = null
782      redrawRefused($, result.deny)
783    })
784    .catch((err) => logOnce($, err))
785}
786
787function redrawRefused($, deny) {
788  if (S.tick - refusedAt < REDRAW_AFTER_REFUSAL_TICKS) return
789  refusedAt = S.tick
790  logOnce($, 'frame refused: ' + deny)
791  $.ui.invalidate('ui.render')
792}
793
794// Swap the small band's Image to the frame now, when it differs from the last one sent
795// or drawn. A terminal that draws the Image's alt gets half blocks for a while.
796function blitImage($, zoom) {
797  const source = imageNow(zoom)
798  if (source.png === S.sentImage) return
799  S.sentImage = source.png
800  $.ui
801    .blit({ requestId: S.bandId, key: 'pokemon', columns: zoom.columns, rows: zoom.rows, source })
802    .then((result) => {
803      if (!result?.deny) {
804        S.imagesDrawn = true
805        return
806      }
807      S.sentImage = null
808      deniedImage($, result.deny)
809    })
810    .catch((err) => logOnce($, err))
811}
812
813// Send the pixel hearts as drawn, once per PNG, to learn whether the terminal draws them
814function blitHearts($) {
815  const source = heartsImage(filledIcons('happiness'))
816  if (source.png === S.sentHearts) return
817  S.sentHearts = source.png
818  $.ui
819    .blit({ requestId: S.bandId, key: 'hearts', columns: STAT_ICONS, rows: 1, source })
820    .then((result) => {
821      if (!result?.deny) {
822        S.imagesDrawn = true
823        return
824      }
825      S.sentHearts = null
826      deniedImage($, result.deny)
827    })
828    .catch((err) => logOnce($, err))
829}
830
831function deniedImage($, deny) {
832  if (!/draws its alt/.test(deny)) return redrawRefused($, deny)
833  if (S.imageRetryAt !== null) return
834  // A terminal that has drawn Images denies one only for a while, as when its focus
835  // resets, so the wait starts over
836  if (S.imagesDrawn) S.imageWait = IMAGE_WAIT_TICKS[0]
837  S.imagesDrawn = false
838  S.imageRetryAt = S.tick + S.imageWait
839  S.imageWait = Math.min(IMAGE_WAIT_TICKS[1], S.imageWait * 2)
840  logOnce($, 'drawing half blocks and text hearts: ' + deny)
841  $.ui.invalidate('ui.render')
842}
843
844// The desktop has no Raster to repaint, so a changed frame draws the band again. The
845// host draws a plugin's band ten times a second at most.
846const DESKTOP_FRAME_TICKS = 2
847function redrawSvg($) {
848  if (!bandZoom() || svgNow() === S.sentSvg) return
849  $.ui.invalidate('ui.render')
850}
851
852// Ticks stop while the machine sleeps, so the meters resync with the real clock
853// The meters drain at OFF_DRAIN of their speed while no session runs: Claude Code closed,
854// or the laptop off or asleep. Every open session marks the store as seen every BEAT_MS.
855// A session that starts long after the last mark, or a running one whose own beat comes
856// late because the laptop slept, moves every meter's timestamp on by the rest of that
857// time, so only OFF_DRAIN of it counts. This stacks with /pokemon sleep's slower drain.
858const OFF_DRAIN = 0.25
859const BEAT_MS = 10 * 1000
860const BEAT_TICKS = BEAT_MS / TICK_MS
861const OFF_AFTER_MS = 60 * 1000
862
863async function slowMeters($, now, offMs) {
864  await freshen($, Object.keys(S.stats))
865  // A stamp set during the gap, by another session, only sees the gap after it
866  const overlap = (at) => Math.min(offMs, Math.max(0, now - at))
867  const draining = Object.keys(S.stats).filter((name) => !S.stats[name].parked)
868  for (const name of draining) {
869    const record = { ...S.stats[name] }
870    for (const key of Object.keys(STATS)) {
871      if (record[key]?.at !== undefined) record[key] = { ...record[key], at: record[key].at + overlap(record[key].at) * (1 - OFF_DRAIN) }
872    }
873    S.stats[name] = record
874  }
875  // A heal takes open time too, so its end moves on by all of the gap it ran through
876  const healing = Object.keys(S.stats).filter((name) => typeof S.stats[name].healing?.until === 'number')
877  for (const name of healing) {
878    const { from, until } = S.stats[name].healing
879    const start = from ?? until - HEAL_MS
880    const shift = overlap(start)
881    S.stats[name] = { ...S.stats[name], healing: { from: start + shift, until: until + shift } }
882  }
883  await saveRecords($, [...new Set([...draining, ...healing])])
884}
885
886// The gap runs from the last mark any session left, so time another session was open
887// never counts as off, whether this one is starting or its own ticks came late
888async function beat($) {
889  const since = await $.store.get('seenAt')
890  const now = await $.clock.now()
891  S.nowMs = now
892  if (typeof since === 'number' && now - since > OFF_AFTER_MS) await slowMeters($, now, now - since - BEAT_MS)
893  await $.store.set('seenAt', now)
894}
895
896async function resyncMeters($) {
897  S.nowMs = await $.clock.now()
898  $.ui.invalidate('ui.render')
899}
900
901// A mon faints once food and happiness have both sat empty for FAINT_AFTER_MS of open
902// session time, kept in its record as starving = { ms, at }. Each check adds the time since
903// the last one by any session, when that's under COUNTED_GAP_MS, so time with every session
904// closed or the laptop asleep never counts. A session holds the clock for FAINT_GRACE_MS
905// after it first shows the mon. Left fainted for RUNAWAY_AFTER_MS, counted the same way in
906// fainted = { ms, at }, it runs away. With needs off, both clocks stop.
907const FAINT_AFTER_MS = 3 * 3600 * 1000
908const RUNAWAY_AFTER_MS = 24 * 3600 * 1000
909const FAINT_GRACE_MS = 10 * 60 * 1000
910const COUNTED_GAP_MS = OFF_AFTER_MS
911
912// The mon on show ran away or died, so the band shows the next one in the box: the
913// highest level one still standing, else a fainted one. With none, the band is a line of
914// text. Returns the mon it shows next, if any.
915async function leaveBand($, { save = true } = {}) {
916  const gone = S.mon
917  const next = Object.keys(S.stats)
918    .filter((name) => name !== gone && MONS.includes(name) && S.stats[name] && typeof S.stats[name] === 'object' && !isGone(name))
919    .sort((a, b) => isFainted(a) - isFainted(b) || levelOf(b) - levelOf(a) || a.localeCompare(b))[0]
920  S.attack = null
921  S.food = null
922  S.evolving = null
923  S.evolveDue = null
924  if (S.wild) fleeWild($, true)
925  if (next) await switchTo($, next, { save })
926  S.sentCells = null
927  $.ui.invalidate('ui.render')
928  return next ?? null
929}
930
931async function faintMon($) {
932  const { starving, asleep, ...record } = S.stats[S.mon]
933  S.stats[S.mon] = { ...record, food: { value: 0, at: S.nowMs }, happiness: { value: 0, at: S.nowMs }, fainted: { ms: 0, at: S.nowMs } }
934  await saveRecords($, [S.mon])
935  $.ui.toast(nameOf(S.mon) + ' fainted! /pokemon revive takes it to a Pokémon Center.')
936  $.ui.invalidate('ui.render')
937}
938
939// The record stays, marked with when it left and the variant it was shown in, for its
940// comeback in the wild
941async function runAway($) {
942  const name = nameOf(S.mon)
943  const { fainted, healing, starving, asleep, ...record } = S.stats[S.mon]
944  S.stats[S.mon] = { ...record, ranAway: { at: S.nowMs, variant: S.variant } }
945  await saveRecords($, [S.mon])
946  const next = await leaveBand($)
947  $.ui.toast(name + ' ran away! It may turn up in the wild.' + (next ? ' ' + nameOf(next) + ' takes its place.' : ''))
948}
949
950// Under nuzlocke a fainted mon is lost. Its record goes for a dead mark that locks the
951// species until a new one is caught, and the graveyard keeps who it was.
952async function loseMon($, name) {
953  const shownName = nameOf(name)
954  const grave = { mon: name, level: levelOf(name), at: S.nowMs, ...(S.stats[name]?.nickname ? { nickname: S.stats[name].nickname } : {}) }
955  const graveyard = await $.store.get('graveyard')
956  await $.store.set('graveyard', [...(Array.isArray(graveyard) ? graveyard : []), grave])
957  S.stats[name] = { dead: { at: S.nowMs } }
958  await saveRecords($, [name])
959  const next = name === S.mon ? await leaveBand($) : null
960  $.ui.toast(shownName + ' fainted for good. Rest well.' + (next ? ' ' + nameOf(next) + ' takes its place.' : ''))
961}
962
963// With nuzlocke on, every fainted mon in the box is lost, except one already being healed
964async function loseFainted($) {
965  const saved = await $.store.get('stats')
966  if (!saved || typeof saved !== 'object') return
967  const names = Object.keys(saved).filter((name) => saved[name]?.fainted && !saved[name].healing && !saved[name].dead && !saved[name].ranAway)
968  if (names.length === 0) return
969  await freshen($, names)
970  for (const name of names) if (isFainted(name) && !isHealing(name)) await loseMon($, name)
971}
972
973// Move the shown mon's faint clock or runaway clock on, as often as the beat
974async function checkNeglect($) {
975  if (S.checkingNeglect) return
976  S.checkingNeglect = true
977  try {
978    S.nowMs = await $.clock.now()
979    if (S.nuzlockeOn) await loseFainted($)
980    await freshen($, [S.mon])
981    const record = S.stats[S.mon]
982    if (!S.needsOn || !record || isGone(S.mon) || isHealing(S.mon)) return
983    const now = S.nowMs
984    const counts = now - (S.firstShown.get(S.mon) ?? now) >= FAINT_GRACE_MS
985    const added = (clock) => (counts && clock && now - clock.at <= COUNTED_GAP_MS ? Math.max(0, now - clock.at) : 0)
986    if (isFainted(S.mon)) {
987      const ms = (record.fainted.ms ?? 0) + added(record.fainted)
988      if (ms >= RUNAWAY_AFTER_MS) return await runAway($)
989      S.stats[S.mon] = { ...record, fainted: { ms, at: now } }
990      return await saveRecords($, [S.mon])
991    }
992    if (statNow(S.mon, 'food') > 0 || statNow(S.mon, 'happiness') > 0) {
993      if (!record.starving) return
994      const { starving, ...rest } = record
995      S.stats[S.mon] = rest
996      return await saveRecords($, [S.mon])
997    }
998    const ms = (record.starving?.ms ?? 0) + added(record.starving)
999    if (ms >= FAINT_AFTER_MS) return await (S.nuzlockeOn ? loseMon($, S.mon) : faintMon($))
1000    S.stats[S.mon] = { ...record, starving: { ms, at: now } }
1001    await saveRecords($, [S.mon])
1002  } finally {
1003    S.checkingNeglect = false
1004  }
1005}
1006
1007async function finishHeal($) {
1008  S.finishingHeal = true
1009  try {
1010    S.nowMs = await $.clock.now()
1011    await freshen($, [S.mon])
1012    const healed = settleHeal(S.mon)
1013    if (healed) await saveRecords($, [S.mon])
1014    if (healed || !isFainted(S.mon)) {
1015      markActive()
1016      S.hopStart = S.tick
1017      S.releasedAt = S.tick
1018      $.ui.toast(nameOf(S.mon) + ' is healed and back on its feet!')
1019      $.ui.invalidate('ui.render')
1020    }
1021  } finally {
1022    S.finishingHeal = false
1023  }
1024}
1025
1026// Stop whatever the shown mon was doing once it's down, here or in another session
1027function stepDown($) {
1028  if (!isDown()) return
1029  if (isHealing(S.mon) && !S.finishingHeal && S.nowMs >= S.stats[S.mon].healing.until) finishHeal($).catch((err) => logOnce($, err))
1030  S.attack = null
1031  S.evolving = null
1032  S.evolveDue = null
1033  S.food = null
1034}
1035
1036// /pokemon revive [<mon>] takes a fainted mon to a Pokémon Center for HEAL_MS
1037async function reviveCommand($, wanted) {
1038  const name = wanted || S.mon
1039  if (!MONS.includes(name)) return { text: 'Unknown mon "' + wanted + '". /pokemon box lists yours.' }
1040  await freshen($, [name])
1041  if (name === S.mon && isDown()) {
1042    if (isGone(S.mon) || isHealing(S.mon)) return downReply()
1043  } else if (isDead(name)) {
1044    return { text: displayName(name) + ' is gone.' }
1045  } else if (hasRunAway(name)) {
1046    return { text: goneLine(name) }
1047  }
1048  const shown = nameOf(name)
1049  if (!isFainted(name)) return { text: shown + ' hasn\'t fainted.' }
1050  if (isHealing(name)) return { text: shown + ' is already at the Pokémon Center.' }
1051  if (S.nuzlockeOn) return { text: 'Nuzlocke is on, so ' + shown + ' can\'t be revived.' }
1052  S.stats[name] = { ...S.stats[name], healing: { from: S.nowMs, until: S.nowMs + HEAL_MS } }
1053  await saveRecords($, [name])
1054  // It comes back out of its ball at home
1055  if (name === S.mon) S.x = homeX()
1056  $.ui.invalidate('ui.render')
1057  return { text: 'You take ' + shown + ' to a Pokémon Center. It\'ll be back on its feet in ' + HEAL_MS / 60000 + ' minutes.' }
1058}
1059
1060// The shown mon is at the Pokémon Center, so it can't be swapped out until it's back
1061async function stillHealing($) {
1062  await freshen($, [S.mon])
1063  return isHealing(S.mon) && S.nowMs < S.stats[S.mon].healing.until
1064}
1065
1066async function nuzlockeCommand($) {
1067  S.nuzlockeOn = !S.nuzlockeOn
1068  await $.store.set('nuzlocke', S.nuzlockeOn)
1069  if (!S.nuzlockeOn) return { text: 'Nuzlocke is off. A mon that faints can be revived again. The ones you lost stay gone.' }
1070  const saved = await $.store.get('stats')
1071  if (saved && typeof saved === 'object') await freshen($, Object.keys(saved))
1072  const doomed = Object.keys(S.stats).filter((name) => MONS.includes(name) && isFainted(name) && !isHealing(name))
1073  const fate = doomed.length === 1 ? ' has fainted already, so it\'s gone for good in a moment.' : ' have fainted already, so they\'re gone for good in a moment.'
1074  const warning = doomed.length > 0 ? ' ' + andList(doomed.map(nameOf)) + fate : ''
1075  return { text: 'Nuzlocke is on. A mon that faints is gone for good, with no revive and no coming back. Keep them fed and happy.' + warning }
1076}
1077
1078async function trainerCommand($) {
1079  S.trainerOn = !S.trainerOn
1080  await $.store.set('trainer', S.trainerOn)
1081  if (!S.trainerOn) return { text: 'Trainer mode is off. /pokemon <mon> shows any mon.' }
1082  const pick = (await boxIsEmpty($)) ? 'Pick your starter, ' + orList(STARTERS.map(displayName)) + ', then catch the rest in the wild.' : 'You can only switch to mons in your box, so catch the rest in the wild.'
1083  return { text: 'Trainer mode is on. ' + pick + ' Mons fetched with /pokemon new stay free to show.' }
1084}
1085
1086// With trainer mode on, only mons in your box can be shown. A box with no mon in it, new
1087// or with every mon gone, picks one of the starters, so it's never stuck with nothing to
1088// show or catch with. Mons fetched with /pokemon new are left out of it.
1089const STARTERS = ['bulbasaur', 'charmander', 'squirtle', 'pikachu']
1090
1091async function boxIsEmpty($) {
1092  const saved = await $.store.get('stats')
1093  if (saved && typeof saved === 'object') await freshen($, Object.keys(saved))
1094  return !Object.keys(S.stats).some((name) => MONS.includes(name) && !isGone(name))
1095}
1096
1097// Why trainer mode keeps asked off the band, or null when it may be shown. The caller has
1098// freshened asked's record. A starter picked joins the box at its first level.
1099async function trainerWait($, asked) {
1100  if (!S.trainerOn || asked === S.mon || S.stats[asked] || (await $.store.get(CUSTOM_PREFIX + asked))) return null
1101  const off = ', or turn trainer mode off with /pokemon trainer.'
1102  if (!(await boxIsEmpty($))) return { text: 'Trainer mode is on, so you can only switch to mons in your box. Catch a wild ' + displayName(asked) + ' to raise one' + off }
1103  if (!STARTERS.includes(asked)) return { text: 'Trainer mode is on, so pick your starter first: ' + orList(STARTERS.map(displayName)) + '. Catch the rest in the wild' + off }
1104  S.stats[asked] = { xp: xpAt(startLevel(asked)) }
1105  await saveRecords($, [asked])
1106  return null
1107}
1108
1109// A broken frame goes to the debug log, each distinct message once
1110const logged = new Set()
1111function logOnce($, err) {
1112  const message = String(err?.message ?? err)
1113  if (logged.has(message)) return
1114  logged.add(message)
1115  // Logging is best effort: a log that fails must not break the hook that hit the error
1116  try {
1117    Promise.resolve($.ui.log('pokemon: ' + message, { to: 'debug' })).catch(() => {})
1118  } catch {}
1119}
1120
1121async function themeInk($) {
1122  try {
1123    const rows = await $.config.list()
1124    return inkFor(rows.find((row) => row.key === 'theme')?.value)
1125  } catch {
1126    return INKS.dark
1127  }
1128}
1129
1130
1131// Show another mon, parking the one that leaves so its meters stop where they are
1132async function switchTo($, asked, { save = true } = {}) {
1133  const wasHome = isHome()
1134  S.evolveDue = null
1135  const left = S.mon
1136  S.nowMs = await $.clock.now()
1137  await freshen($, [left, asked])
1138  settleHeal(asked)
1139  if (!S.firstShown.has(asked)) S.firstShown.set(asked, S.nowMs)
1140  if (asked !== left && (S.stats[left] || S.stats[asked])) {
1141    park(left)
1142    unpark(asked)
1143    await saveRecords($, [left, asked])
1144  }
1145  S.mon = asked
1146  if (wasHome) S.x = homeX()
1147  clampX()
1148  if (save) await saveMon($)
1149}
1150
1151// Load the mons fetched with /pokemon new, in this session or another, not loaded yet
1152async function loadCustom($) {
1153  for (const key of await $.store.keys()) {
1154    const name = key.slice(CUSTOM_PREFIX.length)
1155    if (!key.startsWith(CUSTOM_PREFIX) || SPRITES[name]) continue
1156    const saved = await $.store.get(key)
1157    if (saved?.sprite) addCustom(name, saved)
1158  }
1159}
1160
1161// /pokemon new <mon> fetches a mon from any generation and shows it. "random" picks one
1162// from gen 2 to 5 you don't have yet, and "random gen3" or "gen3" one from that generation.
1163async function newCommand($, wanted) {
1164  const genAsked = wanted.match(/^(?:random\s*)?gen\s*([1-5])$/)
1165  const random = wanted === 'random' || genAsked !== null
1166  let name = random ? '' : wanted.replace(/\s+/g, '_')
1167  let gen
1168  const get = (url, init) => $.http.fetch(url, init)
1169  if (!wanted) return { text: 'Name a mon to fetch, like /pokemon new mudkip, or try /pokemon new random or /pokemon new gen3.' }
1170  try {
1171    if (random) {
1172      gen = genAsked ? Number(genAsked[1]) : 2 + Math.floor(Math.random() * 4)
1173      const fresh = (await monsOfGen(get, gen)).filter((n) => !SPRITES[n])
1174      if (fresh.length === 0) return { text: 'You already have every gen ' + gen + ' mon.' }
1175      name = fresh[Math.floor(Math.random() * fresh.length)]
1176    } else if (SPRITES[name]) {
1177      return { text: nameOf(name) + ' is already here. /pokemon ' + name + ' shows it.' }
1178    } else if (!/^[a-z0-9_.-]+$/.test(name)) {
1179      return { text: 'Unknown mon "' + wanted + '". Names are like mudkip or mr._mime.' }
1180    }
1181    const entry = await fetchMon(get, name, gen)
1182    await $.store.set(CUSTOM_PREFIX + name, entry)
1183    addCustom(name, entry)
1184    await switchTo($, name)
1185    $.ui.invalidate('ui.render')
1186    return { text: 'Fetched gen ' + entry.gen + ' ' + nameOf(name) + '. It knows ' + entry.moves.join(', ') + '. Now showing ' + S.variant + ' ' + nameOf(name) + '.' }
1187  } catch (err) {
1188    return { text: "Couldn't fetch " + (name || 'a mon') + ': ' + (err?.message ?? String(err)) }
1189  }
1190}
1191
1192// Asks for half the terminal, unless the person sized the dock themselves
1193async function openPane($, columns) {
1194  const opened = await $.ui.open({ id: PANE_ID, title: 'Pokémon', ...(columns > 0 ? { columns } : {}) })
1195  if (!opened.isPlaced) leavePane($)
1196  return opened
1197}
1198
1199// The band draws the scene again, and blits go to it
1200function leavePane($) {
hooks/art.js 149 lines
1// The band's pixel art, the inks it draws straight on the terminal background, and stamps to place art in the scene
2
3export const HEART_COLORS = [0xff4f8b, 0xff9ec4]
4// Pixel hearts, big and small in turn: p body, h highlight
5export const HEARTS = [['pp.pp', 'phppp', '.ppp.', '..p..'], ['p.p', 'ppp', '.p.']]
6export const HEART_SHINE = 0xffe0ec
7// A 4x4 pixel berry: k leaf, b rim, B body, h highlight. Each kind recolors it.
8export const BERRY = ['.kk.', 'bBBb', 'bBhb', '.bb.']
9export const BERRY_SIZE = 4
10const LEAF_COLOR = 0x3a7a2a
11export const BERRIES = [
12  { name: 'oran berry', emoji: '🫐', colors: { k: LEAF_COLOR, b: 0x2c3f9e, B: 0x4a63d8, h: 0x9fb4ff } },
13  { name: 'pecha berry', emoji: '🍑', colors: { k: LEAF_COLOR, b: 0xc2477a, B: 0xf48fb1, h: 0xffd1e3 } },
14  { name: 'razz berry', emoji: '🍓', colors: { k: LEAF_COLOR, b: 0x8e1240, B: 0xd81b60, h: 0xff7aa8 } },
15  { name: 'sitrus berry', emoji: '🍋', colors: { k: LEAF_COLOR, b: 0xc9a400, B: 0xfdd835, h: 0xfff59d } },
16]
17// Colors the band draws straight on the terminal background, one set per theme
18export const INKS = {
19  dark: {
20    bubble: 0xf0f0f0, dots: 0x9a9ab0, z: 0xe8e8ff, star: 0xffd54f, silhouette: 0xf8f8ff,
21    pencil: 0xffc83d, lens: 0x6cc4ff, shell: 0x5fe08a, ball: 0xeeeef6, disc: 0xd4d4e0, wrench: 0xb8b8c8, party: 0xb4b4c8,
22    discShade: 0x8e8ea0, sweat: 0x6ec8ff, sweatShine: 0xe6f7ff, hpEmpty: 0x404048,
23  },
24  light: {
25    bubble: 0x4a4a58, dots: 0x70708a, z: 0x5a5aa8, star: 0xe0a000, silhouette: 0x2e2e3a,
26    pencil: 0xe08a00, lens: 0x2a7ad0, shell: 0x1f9a4a, ball: 0xa8a8b4, disc: 0x6e6e88, wrench: 0x6a6a80, party: 0x5c5c74,
27    discShade: 0x44445a, sweat: 0x2b8fe0, sweatShine: 0xbfe4ff, hpEmpty: 0xc8c8d0,
28  },
29}
30
31// Pixel art stamps: rows of letters, each letter a color, '.' transparent
32// The thought bubble is an outline with no fill, drawn in the theme's bubble ink
33const BUBBLE = ['.OOOOOOO.', 'O.......O', 'O.......O', 'O.......O', 'O.......O', 'O.......O', 'O.......O', '.OOOOOOO.']
34const BUBBLE_WIDTH = BUBBLE[0].length
35// The columns a bubble and its tail take beside the head
36export const BUBBLE_SPAN = BUBBLE_WIDTH + 3
37export const BUBBLE_TAIL_ROW = 2
38// Each icon has small art too, for a shrunk band's bubble
39export const BUBBLE_ICONS = {
40  food: { rows: ['.rgr.', 'rrrrr', '.rrr.', '..r..'], small: ['.g.', 'rrr', '.r.'], colors: { r: 0xd84040, g: 0x58a040 } },
41  happiness: { rows: ['pp.pp', 'ppppp', '.ppp.', '..p..'], small: ['p.p', 'ppp', '.p.'], colors: { p: 0xf0609a } },
42}
43export const STAR = ['..s..', 'sssss', '.sss.', '.s.s.']
44export const SMALL_STAR = ['.s.', 'sss', 's.s']
45export const SMALL_Z = ['zzz', '.z.', 'zzz']
46export const BIG_Z = ['zzzz', '..z.', '.z..', 'zzzz']
47// A shrunk band draws the bubble, Zs, and berry at its own pixel size, from art made for
48// it, instead of shrinking the full-size art down to specks. Its bubble is the full-size
49// one's shape a size down, holding the icons' small art with a pixel of room around it.
50export const SMALL_ZS = { glyphs: [SMALL_Z, SMALL_Z], drift: 3 }
51export const SMALL_BERRY = ['.k.', 'BhB', '.b.']
52// The bubble drawn: the full-size one, with the icon's columns and rows in from its corner
53export const FULL_BUBBLE = { frame: BUBBLE, inset: [2, 2], small: false }
54// A shrunk band's bubble, with the icon's small art in the middle of it
55const SMALL_BUBBLE = ['.OOOOO.', 'O.....O', 'O.....O', 'O.....O', 'O.....O', 'O.....O', '.OOOOO.']
56export function shrunkBubble(icon) {
57  const room = SMALL_BUBBLE.length - 2
58  const inset = [1 + Math.floor((room - icon.small[0].length) / 2), 1 + Math.floor((room - icon.small.length) / 2)]
59  return { frame: SMALL_BUBBLE, inset, small: true }
60}
61// The columns a bubble and its tail take beside the head
62export const bubbleSpan = (look) => look.frame[0].length + 3
63// A sweat drop on the head when a tool call fails: d drop, h shine
64export const SWEAT = ['..d.', '.dd.', 'dhdd', 'dddd', '.dd.']
65// The "!" of a trainer who spots you, shown while Claude waits on you
66export const ALERT_ICON = { rows: ['..a..', '..a..', '.....', '..a..'], small: ['a', 'a', '.', 'a'], colors: { a: 0xff3d3d } }
67// What the bubble shows while a tool runs: a pencil (p body, e eraser, t wood, g lead),
68// a magnifier (l rim, h handle), a shell prompt (s), a Poké Ball (r top, k band,
69// w button, b bottom), a TM disc (c disc, d shade, n shine) for a skill, or a wrench (m) for
70// every other tool, MCP tools included
71export const TOOL_ICONS = {
72  pencil: ['...pe', '..pp.', '.pp..', 'gt...'],
73  lens: ['.ll..', 'l..l.', '.llh.', '....h'],
74  shell: ['s....', '.s...', 's....', '..sss'],
75  ball: ['.rrr.', 'rrrrr', 'kkwkk', '.bbb.'],
76  disc: ['.ncc.', 'nc.cc', 'ccccd', '.cdd.'],
77  wrench: ['..m.m', '..mmm', '.m...', 'm....'],
78}
79export const SMALL_TOOL_ICONS = {
80  pencil: ['..e', '.p.', 'g..'],
81  lens: ['.l.', 'l.l', '.lh'],
82  shell: ['s..', '.s.', 's..'],
83  ball: ['rrr', 'kwk', 'bbb'],
84  disc: ['ncc', 'c.c', 'ccd'],
85  wrench: ['m.m', 'mmm', '.m.'],
86}
87export const TOOL_KINDS = {
88  pencil: ['Edit', 'Write', 'NotebookEdit', 'MultiEdit'],
89  lens: ['Read', 'Grep', 'Glob', 'LS', 'WebFetch', 'WebSearch', 'ToolSearch', 'LSP'],
90  shell: ['Bash', 'PowerShell', 'Monitor', 'BashOutput', 'KillShell'],
91  ball: ['Agent', 'Task', 'SendMessage', 'Workflow'],
92  disc: ['Skill'],
93}
94
95export const stamp = (x, y, rows, colors) => ({ x, y, rows, colors })
96
97// A stamp's color at a strip column and pixel row, or null
98export function stampPixel(s, cx, py) {
99  const row = s.rows[py - s.y]
100  if (!row) return null
101  const ch = row[cx - s.x]
102  return ch === undefined ? null : (s.colors[ch] ?? null)
103}
104
105export const SPARKLE = { s: 0xfff2a0, w: 0xffffff }
106export const SPARKLES = [[-2, -2], [8, -1], [-3, 3], [9, 4], [3, -3]]
107// The meters' icons, plain text unless /pokemon emoji turns emoji on. Each text pair is a
108// filled and an empty glyph from one Unicode block, drawn one column wide at one size, with
109// no emoji presentation. An emoji icon takes two columns: a filled one is drawn two wide from
110// the emoji font whatever the terminal's font, and an empty one is followed by a space. Some
111// fonts lack ○ or ♡ and borrow a wider glyph, which then spills into the space, not the next icon.
112export const METER_STYLES = {
113  text: {
114    columns: 1,
115    food: { icon: '●', emptyIcon: '○', color: '#ea697d' },
116    happiness: { icon: '♥', emptyIcon: '♡', color: '#ff5f9e' },
117  },
118  emoji: {
119    columns: 2,
120    // The empty icons take the color of the emoji they stand in for
121    food: { icon: '🍓', emptyIcon: '○', color: '#e0303e' },
122    happiness: { icon: '💗', emptyIcon: '♡', color: '#ff7aa8' },
123  },
124}
125// A terminal that draws Images gets the text hearts as pixel hearts instead, since some
126// fonts lack ♥ or ♡. Each takes one cell, HEART_CELL pixels wide and twice as tall, and
127// sits where a font like Hack draws ● beside it: the cell's full width, about as tall,
128// from HEART_TOP down. An empty heart is the full one's rim, two pixels thick.
129// A retina cell is about 14 device pixels wide and a non-retina one about 7. The
130// terminal scales the PNG to the cell without smoothing, so there it keeps about every
131// other pixel. Every feature is at least two pixels wide, and the lobes sit on even
132// columns, so what's kept is still a heart with a closed rim.
133export const HEART_ICON = [
134  '..pppp..pppp..',
135  '.ppppp..ppppp.',
136  'pppppppppppppp',
137  'pppppppppppppp',
138  'pppppppppppppp',
139  'pppppppppppppp',
140  '.pppppppppppp.',
141  '..pppppppppp..',
142  '...pppppppp...',
143  '....pppppp....',
144  '.....pppp.....',
145  '......pp......',
146]
147export const HEART_CELL = 14
148export const HEART_TOP = 10
149
hooks/attacks.js 123 lines
1// Attack animations for /pokemon attack. Each effect is a pure function of the
2// attack, its age in ticks, and where the mon stands. It paints pixels over and
3// under the sprite, and can move, squash, turn, recolor, or hide the sprite itself.
4// The effects live in effects/, one file per family, on the helpers in effects/draw.js.
5//
6// Coordinates are strip pixels: x is a column, y a half row from the top.
7// `side` is 1 when the attack goes right and -1 when it goes left.
8
9import { BASIC } from './effects/basic.js'
10import { BEAMS } from './effects/beams.js'
11import { CHARGES } from './effects/charge.js'
12import { EARTH } from './effects/earth.js'
13import { ELECTRIC } from './effects/electric.js'
14import { EVOLVE } from './effects/evolve.js'
15import { FIRE } from './effects/fire.js'
16import { GUARD } from './effects/guard.js'
17import { MIND } from './effects/mind.js'
18import { NATURE } from './effects/nature.js'
19import { POISON } from './effects/poison.js'
20import { SELF } from './effects/self.js'
21import { SKY } from './effects/sky.js'
22import { SOUND } from './effects/sound.js'
23import { SPECIAL } from './effects/special.js'
24import { STRIKES } from './effects/strikes.js'
25import { WATER } from './effects/water.js'
26import { WEAPONS } from './effects/weapons.js'
27import { clamp } from './effects/draw.js'
28
29const EFFECTS = {
30  ...BASIC, ...BEAMS, ...CHARGES, ...EARTH, ...ELECTRIC, ...EVOLVE, ...FIRE, ...GUARD, ...MIND,
31  ...NATURE, ...POISON, ...SELF, ...SKY, ...SOUND, ...SPECIAL, ...STRIKES, ...WATER, ...WEAPONS,
32}
33
34const FALLBACK = 'impact'
35const MOUTH = 0.35
36const POSE = { view: 'side', stride: false, swap: false, asleep: false }
37
38export const effectOf = (id) => (EFFECTS[id] ? id : FALLBACK)
39
40// The parts of an attack its move decides: the effect and its options, how long it
41// plays, and where it leaves the mon (toX, or null to stay put)
42export function prepareAttack(move, { side, seed, x, home }) {
43  const effect = effectOf(move.effect)
44  const spec = EFFECTS[effect]
45  const attack = {
46    effect,
47    color: move.color ?? null,
48    from: move.from ?? null,
49    mouth: move.mouth ?? MOUTH,
50    power: move.power ?? spec.power ?? 1,
51    ticks: spec.ticks,
52    side,
53    seed,
54  }
55  attack.toX = spec.lands ? clamp(Math.round(spec.lands(attack, x, home)), 0, home) : null
56  return attack
57}
58
59// How the sprite stands this tick, needed before it is drawn: side on or facing out,
60// striding, swapped for another mon, or asleep
61export function attackPose(attack, t) {
62  const pose = EFFECTS[attack.effect].pose
63  return { ...POSE, ...(typeof pose === 'function' ? pose(t, attack) : pose) }
64}
65
66// Whether a move plays side on toward a target, staying where it stands. Only those
67// can hit a foe in front of the mon.
68export function aimsAhead(move) {
69  const effect = effectOf(move.effect)
70  if (EFFECTS[effect].lands || effect === 'transform') return false
71  return attackPose(prepareAttack(move, { side: 'left', seed: 0, x: 0, home: 0 }), 0).view === 'side'
72}
73
74// The attack's drawing this tick, described in effects/draw.js
75export function attackFrame(attack, t, g) {
76  const out = {
77    dots: [], under: [], chars: [], ghosts: [], hidden: false,
78    dx: 0, dy: 0, sx: 1, sy: 1, flipX: false, flipY: false, skew: null, shade: null, shake: [0, 0],
79  }
80  const spec = EFFECTS[attack.effect]
81  spec.draw(out, t, attack, aim(g, attack), attack.color ?? spec.color)
82  return out
83}
84
85// Where the attack starts and lands. frontAt(y) is just in front of the sprite on row y.
86// The mouth is the front a third of the way down, which is the face for nearly every
87// side-on mon. A move can set its own `mouth` height for a mon whose face sits lower.
88// With a foe's box in g.foe, the move aims at the middle of the foe.
89function aim(g, a) {
90  const cx = Math.round((g.left + g.right) / 2)
91  const cy = Math.round((g.top + g.bottom) / 2)
92  const frontAt = (y) => {
93    let x = g.side > 0 ? g.right : g.left
94    while (x !== cx && !g.solid(x, y)) x -= g.side
95    return x + g.side
96  }
97  const my = g.top + Math.round((g.bottom - g.top + 1) * a.mouth)
98  const mouth = { x: frontAt(my), y: my }
99  const ground = g.pixels - 1
100  const ahead = (d) => mouth.x + g.side * d
101  let reach = g.side > 0 ? g.columns - 1 - mouth.x : mouth.x
102  let target = { x: ahead(clamp(reach - 4, 3, 13)), y: clamp(ground - 7, mouth.y, ground - 3) }
103  if (g.foe) {
104    target = { x: Math.round((g.foe.left + g.foe.right) / 2), y: Math.round((g.foe.top + g.foe.bottom) / 2) }
105    reach = Math.abs(target.x - mouth.x)
106  }
107  const geo = { ...g, cx, cy, frontAt, mouth, ground, reach, ahead, target }
108  if (a.from === 'top') geo.crown = crownOf(geo)
109  return geo
110}
111
112// The middle of the sprite's topmost row of pixels, like the tip of a bulb
113function crownOf(g) {
114  let left = g.right
115  let right = g.left
116  for (let x = g.left; x <= g.right; x++) {
117    if (!g.solid(x, g.top)) continue
118    left = Math.min(left, x)
119    right = Math.max(right, x)
120  }
121  return { x: Math.round((left + right) / 2), y: g.top }
122}
123
hooks/band.js 118 lines
1import { BUBBLE_SPAN, INKS } from './art.js'
2import { PIXEL_PX } from './constants.js'
3import { SPRITES } from './frames.js'
4import {
5  bandRows, bandZoom, baseStrip, clampX, gapRightOf, homeX, isHome, isSmall, leadFloor, sceneRoom, smallZoom, stripTarget,
6} from './layout.js'
7import { filledIcons, iconsFor, meterColumns, meterStyle, STAT_ICONS } from './meters.js'
8import { displayName } from './names.js'
9import { cellsNow, drawsHearts, drawsImage, heartsImage, imageNow, svgNow } from './paint.js'
10import { conditionOf, goneLine, levelLine, nameOf } from './records.js'
11import { S } from './state.js'
12import { isGone } from './status.js'
13import { isOnStage } from './wild.js'
14
15// The scene laid out in the band or the pane, with the level and meters beside or over it
16
17// Any light theme takes the light ink. Every other theme, or none, takes the dark.
18export const inkFor = (theme) => (typeof theme === 'string' && theme.startsWith('light') ? INKS.light : INKS.dark)
19
20// Lays out the scene, the mon with its meters beside or over it, in the room the band
21// or the pane gives it, and returns its parts, drawn with the surface's elements, for the
22// site to wrap. The desktop draws the site's buttons under the meters.
23export function drawScene(elements, e, site) {
24  const desktop = e.surface === 'desktop'
25  const { Box, Text } = elements
26  const wasHome = isHome()
27  S.bandId = e.requestId
28  S.bandSurface = e.surface
29  S.maxRows = site.maxRows
30  // The panel goes over the scene's right end when the band shows at full size and
31  // has room for it, and beside a shrunk band otherwise. The desktop draws text in its
32  // own font, so its meters can't line up with the pixels and always sit beside them.
33  // A small band at its own size lays out as a full-size one and shows it at its scale,
34  // so its panel and margin take more of the scene's columns per band column.
35  const panelColumns = meterColumns() + 1
36  const fullSize = !isSmall() && bandRows() <= S.maxRows
37  const small = smallZoom()
38  // It goes over the scene only when the mon at home still keeps its gap from it.
39  const atHome = SPRITES[S.mon].width + gapRightOf(S.mon)
40  S.panel = !desktop && fullSize && site.bodyColumns >= atHome + panelColumns ? panelColumns : 0
41  if (small && !desktop && site.bodyColumns >= atHome * small.scale + panelColumns) S.panel = Math.ceil(panelColumns / small.scale)
42  S.lastBodyColumns = site.bodyColumns
43  S.columns = stripTarget(site.bodyColumns)
44  S.drawnColumns = S.columns
45  // The party mons' columns open up on the strip's left, so the lead keeps its spot on screen
46  const hadCrew = S.crewWidth
47  S.crewWidth = Math.max(0, S.columns - baseStrip(sceneRoom(site.bodyColumns)))
48  S.margin = fullSize ? Math.max(0, Math.min(BUBBLE_SPAN, site.bodyColumns - S.panel - S.columns)) : 0
49  if (small) {
50    const room = Math.floor((site.bodyColumns - (S.panel > 0 ? 0 : panelColumns)) / small.scale) - S.columns - S.panel - 1
51    S.margin = Math.max(0, Math.min(BUBBLE_SPAN, room))
52  }
53  const shift = S.crewWidth - hadCrew
54  if (wasHome) S.x = homeX()
55  else S.x += shift
56  if (shift !== 0 && S.wanderTarget !== null) S.wanderTarget = Math.max(leadFloor(), Math.min(homeX(), S.wanderTarget + shift))
57  if (S.food) S.food.x += shift
58  clampX()
59
60  const zoom = bandZoom()
61  // Pixel hearts go out with the band's blits, so a band too short for them has none
62  S.drawnHearts = Boolean(zoom) && drawsHearts()
63  const meter = (key, lead = '') => {
64    const text = Text({ color: meterStyle()[key].color, children: [lead + iconsFor(key)] })
65    if (key !== 'happiness' || !S.drawnHearts) return text
66    const source = heartsImage(filledIcons(key))
67    // Until a blit says the terminal draws Images, the next tick asks with one
68    S.sentHearts = S.imagesDrawn ? source.png : null
69    return elements.Image({ key: 'hearts', source, columns: STAT_ICONS, rows: 1, alt: iconsFor(key) })
70  }
71  const level = Text({ dimColor: true, children: [levelLine()] })
72  let corner
73  S.drawnImage = false
74  if (isGone(S.mon)) {
75    // Ran away or lost with no other mon in the box, the band is just a line saying so
76    S.bandId = null
77    S.drawnHearts = false
78    corner = [Text({ dimColor: true, children: [goneLine(S.mon)] })]
79  } else if (zoom) {
80    let sprite
81    if (desktop) {
82      const svg = svgNow()
83      if (svg !== S.sentSvg) S.svgFrame += 1
84      S.sentSvg = svg
85      const alt = isOnStage(S.wild) ? nameOf(S.mon) + ' vs. wild ' + displayName(S.wild.mon) : nameOf(S.mon) + (conditionOf(S.mon) ? ', ' + conditionOf(S.mon) : '')
86      const image = elements.Svg({ source: svg, alt, width: zoom.columns * PIXEL_PX, height: zoom.rows * 2 * PIXEL_PX })
87      sprite = Box({ key: 'pokemon-' + S.svgFrame, children: [image] })
88    } else if (drawsImage()) {
89      const source = imageNow(zoom)
90      // Until a blit says the terminal draws Images, the next tick asks with one
91      S.sentImage = S.imagesDrawn ? source.png : null
92      S.drawnImage = true
93      sprite = elements.Image({ key: 'pokemon', source, columns: zoom.columns, rows: zoom.rows, alt: ' ' })
94    } else {
95      S.sentCells = cellsNow()
96      sprite = elements.Raster({ key: 'pokemon', columns: zoom.columns, rows: zoom.rows, cells: S.sentCells })
97    }
98    const meterLines = [...(S.needsOn ? [level, meter('food'), meter('happiness')] : [level]), ...(desktop ? (site.buttons ?? []) : [])]
99    if (S.panel > 0) {
100      const meters = Box({ position: 'absolute', right: 0, bottom: 0, width: panelColumns, paddingLeft: 1, flexDirection: 'column', children: meterLines })
101      corner = [Box({ position: 'relative', children: [sprite, meters] })]
102    } else {
103      const meters = Box({ flexDirection: 'column', justifyContent: 'flex-end', paddingLeft: 1, children: meterLines })
104      corner = site.bodyColumns >= zoom.columns + panelColumns ? [sprite, meters] : [sprite]
105      // The desktop clips the band's right edge, so its meters keep clear of it
106      if (desktop) corner = [Box({ flexDirection: 'row', flexShrink: 0, paddingRight: 2, children: corner })]
107    }
108  } else {
109    // Too short even for a shrunk mon: its name, level, and meters on one line, and no blits
110    S.bandId = null
111    const name = Text({ children: [nameOf(S.mon) + ' ' + levelLine() + (conditionOf(S.mon) ? ' ' + conditionOf(S.mon) : '')] })
112    const meters = S.needsOn ? [meter('food', ' '), meter('happiness', ' ')] : []
113    corner = [Box({ flexDirection: 'row', children: [name, ...meters] })]
114  }
115
116  return corner
117}
118
hooks/bubble.js 152 lines
1import {
2  ALERT_ICON, BIG_Z, BUBBLE_ICONS, BUBBLE_TAIL_ROW, bubbleSpan, FULL_BUBBLE, SMALL_STAR, SMALL_TOOL_ICONS, SMALL_Z, stamp, STAR,
3  SWEAT, TOOL_ICONS, TOOL_KINDS,
4} from './art.js'
5import { DRIP_TICKS, TICK_MS } from './constants.js'
6import { stripColumns } from './layout.js'
7import { NEEDY_BELOW, statNow, STATS } from './meters.js'
8import { S } from './state.js'
9import { isAsleep, isDown, isPetted, markActive } from './status.js'
10
11// What shows by the mon's head: the thought bubble and its icon, the "!" that calls you
12// over, the Zs while it sleeps, and a sweat drop when a tool call fails
13
14const ZZZ_EVERY_MS = 1100
15const ZZZ_LIFE_MS = 2200
16// The gap between a new Z and the side of the body, and how far out it drifts from there, in pixels
17const ZZZ_GAP = 0
18const ZZZ_DRIFT = 4
19const IDLE_ALERT_MS = 2 * 60 * 1000
20
21// The thinking dots: one to three grey pixels, growing in turn
22export function dotsIcon() {
23  const dots = 1 + (Math.floor((S.tick * TICK_MS) / 400) % 3)
24  const row = ['d', '.', 'd', '.', 'd'].map((ch, i) => (i / 2 < dots ? ch : '.')).join('')
25  return { rows: ['.....', '.....', row, '.....'], small: [row], colors: { d: S.ink.dots } }
26}
27
28// A skill is in use: a Skill call runs in some agent, or a skill was typed as /name
29const skillInUse = () => S.runningSkills.size > 0 || S.tick < S.discUntil
30
31export const toolKind = (name) => Object.keys(TOOL_KINDS).find((k) => TOOL_KINDS[k].includes(name)) ?? 'wrench'
32
33// The kind of the main loop's most recently started tool that is still running. A skill
34// in use anywhere, in the main loop or a subagent, shows as a TM disc instead.
35const leadToolKind = () => (skillInUse() ? 'disc' : toolKind([...S.runningTools.values()].pop()))
36
37// A tool kind's icon in the bubble
38export function toolIcon(kind) {
39  const colors = {
40    p: S.ink.pencil, e: 0xe06888, t: 0xb88048, g: 0x767688,
41    l: S.ink.lens, h: 0xb07040,
42    s: S.ink.shell,
43    r: 0xee4444, k: 0x60606c, w: 0xc0c0cc, b: S.ink.ball,
44    c: S.ink.disc, d: S.ink.discShade, n: 0xf6f6fc,
45    m: S.ink.wrench,
46  }
47  return { rows: TOOL_ICONS[kind], small: SMALL_TOOL_ICONS[kind], colors }
48}
49
50// What the bubble beside the head shows, if anything
51export function bubbleIcon() {
52  if (S.attack || isDown()) return null
53  if (isAlerted()) return ALERT_ICON
54  if (S.tick < S.yumUntil) return { rows: STAR, small: SMALL_STAR, colors: { s: S.ink.star } }
55  if (skillInUse()) return toolIcon(leadToolKind())
56  if (S.working && S.runningTools.size > 0) return toolIcon(leadToolKind())
57  if (S.working && S.thinking) return dotsIcon()
58  const need = S.needsOn && needNow()
59  return need ? BUBBLE_ICONS[need] : null
60}
61
62// The mon calls you over while a dialog waits on a call to one of alertTools,
63// or until a notification's alert runs out at alertUntil
64export const isAlerted = () => S.alertTools.size > 0 || S.tick < S.alertUntil
65
66// Wake up, stand still facing you, and show the "!" until a call to the tool
67// resolves or the ticks run out, or until you answer first
68export function raiseAlert({ tool, ticks }) {
69  markActive()
70  if (tool !== undefined) S.alertTools.add(tool)
71  if (ticks !== undefined) S.alertUntil = Math.max(S.alertUntil, S.tick + ticks)
72}
73
74// Typing, sending, any /pokemon command, or the end of Claude's turn answers the "!",
75// and the idle "!" waiting to show
76export function clearAlert() {
77  S.alertTools.clear()
78  S.alertUntil = 0
79  S.idleAlertAt = null
80}
81
82// Raise the idle "!" once its minute is up, unless a turn is running by then
83export function stepIdleAlert() {
84  if (S.idleAlertAt === null || S.tick < S.idleAlertAt) return
85  S.idleAlertAt = null
86  if (!S.working) raiseAlert({ ticks: IDLE_ALERT_MS / TICK_MS })
87}
88
89// A framed thought bubble beside the head, with a single pixel of tail between it and
90// the head. It leads on the side a walking mon heads for, and sits on the left of a
91// standing one, unless that side has no room for it. room is the columns it may take,
92// the margin and the strip, or a shrunk band's own columns, and look the bubble drawn.
93function bubbleOnLeft(head, side, room = [-S.margin, stripColumns()], look = FULL_BUBBLE) {
94  const span = bubbleSpan(look)
95  const fitsLeft = head[0] - span >= room[0]
96  const fitsRight = head[1] + span + 1 <= room[1]
97  return side === 'left' ? fitsLeft : fitsLeft && !fitsRight
98}
99
100export function bubbleStamps(icon, head, side, room, look = FULL_BUBBLE) {
101  const { frame, inset, small } = look
102  const onLeft = bubbleOnLeft(head, side, room, look)
103  const left = onLeft ? head[0] - bubbleSpan(look) : head[1] + 4
104  const tail = onLeft ? head[0] - 2 : head[1] + 2
105  // The first stamp with a pixel wins, so the icon goes before the bubble
106  return [
107    stamp(left + inset[0], inset[1], small ? icon.small : icon.rows, icon.colors),
108    stamp(left, 0, frame, { O: S.ink.bubble }),
109    stamp(tail, BUBBLE_TAIL_ROW, ['O'], { O: S.ink.bubble }),
110  ]
111}
112
113// Zs rising from just left of the middle of a sleeping body and drifting out and up until
114// they float off the top of the band, small and big in turn, a new one every ZZZ_EVERY_MS.
115// body is the sprite's drawn pixels in strip columns and pixel rows, so every mon's Zs
116// start at the same spot on it whatever its shape. With no room on the left, they start
117// from the right edge instead. look is the Zs drawn, and a shrunk band passes its own.
118export function sleepStamps(body, { glyphs, drift: reach } = { glyphs: [SMALL_Z, BIG_Z], drift: ZZZ_DRIFT }) {
119  const elapsed = S.tick * TICK_MS
120  const middleY = Math.floor((body.top + body.bottom) / 2)
121  const onLeft = body.left - ZZZ_GAP - glyphs[1][0].length - reach >= 0
122  const newest = Math.floor(elapsed / ZZZ_EVERY_MS)
123  const zs = []
124  for (let i = Math.max(0, newest - 2); i <= newest; i++) {
125    const p = (elapsed - i * ZZZ_EVERY_MS) / ZZZ_LIFE_MS
126    if (p >= 1) continue
127    const glyph = glyphs[i % 2]
128    const drift = Math.round(p * reach)
129    const x = onLeft ? body.left - ZZZ_GAP - glyph[0].length - drift : body.right + 1 + ZZZ_GAP + drift
130    const startY = middleY - Math.floor(glyph.length / 2)
131    zs.push(stamp(x, startY - Math.round(p * (startY + glyph.length)), glyph, { z: S.ink.z }))
132  }
133  return zs
134}
135
136// The sweat drop sliding down the corner of the head away from the bubble, which leads
137// on side when there's room, since ticks into the flinch
138export function sweatStamps(head, y, side, { since = S.tick - S.flinchStart, room } = {}) {
139  const width = SWEAT[0].length
140  const sx = bubbleOnLeft(head, side, room) ? Math.min(S.columns - width, head[1] - 1) : Math.max(0, head[0] - 2)
141  const drip = Math.floor(since / DRIP_TICKS)
142  return [stamp(sx, y + drip, SWEAT, { d: S.ink.sweat, h: S.ink.sweatShine })]
143}
144
145// What the idle mon is asking for, if anything. With both low it takes turns.
146function needNow() {
147  if (S.working || S.food || S.attack || isPetted() || isAsleep() || S.tick < S.yumUntil) return null
148  const needs = Object.keys(STATS).filter((key) => statNow(S.mon, key) < NEEDY_BELOW)
149  if (needs.length === 0) return null
150  return needs[Math.floor((S.tick * TICK_MS) / 3000) % needs.length]
151}
152
hooks/commands.js 96 lines
1import { aimsAhead } from './attacks.js'
2import { foeMoves } from './encounter.js'
3import { startAttack } from './motion.js'
4import { movesOf } from './moves.js'
5import { displayName } from './names.js'
6import { downReply, nameOf } from './records.js'
7import { MONS } from './sprites.js'
8import { S } from './state.js'
9import { isDead, isDown, isPetted } from './status.js'
10
11// The /pokemon options that need nothing from the engine, and which options wait while
12// the mon evolves, eats, or enjoys a pet
13
14// Petting, feeding, sleeping, attacking, releasing, and switching mons wait while it evolves
15const WAITS_FOR_EVOLUTION = ['pet', 'feed', 'sleep', 'attack', 'release', 'catch', 'new']
16// While it eats a berry or enjoys a pet, only the commands that just show something run,
17// so nothing changes the record the berry or pet is about to fill
18const SHOWS_ONLY = ['', 'list', 'help', 'stats', 'box', 'party', 'moves', 'dex']
19export const waitsForCare = (asked) => (S.food !== null || isPetted()) && !SHOWS_ONLY.includes(asked.split(' ')[0]) && asked !== 'attack list'
20
21export const evolvingReply = () => ({ text: nameOf(S.mon) + ' is evolving! /pokemon stop cancels it.' })
22export const careReply = () => ({ text: nameOf(S.mon) + (S.food ? ' is busy eating.' : ' is enjoying the pets.') + ' Try again in a moment.' })
23
24// What stops the mon fighting now, as the command's reply, or null when it's free
25export function battleWait() {
26  if (S.evolving !== null) return evolvingReply()
27  if (S.food !== null || isPetted()) return careReply()
28  if (isDown()) return downReply()
29  return null
30}
31
32export const waitsForEvolution = (asked) => S.evolving !== null && (MONS.includes(asked) || WAITS_FOR_EVOLUTION.includes(asked.split(' ')[0]))
33
34// Drop a mon's record from the box, so it starts over at its first level with fresh
35// meters. The active mon stays on screen and starts over in place.
36export function releaseCommand(wanted) {
37  if (!wanted) return { text: 'Name the mon to release, like /pokemon release ' + S.mon + '. /pokemon box lists yours.' }
38  if (!MONS.includes(wanted)) return { text: 'Unknown mon "' + wanted + '". /pokemon box lists yours.' }
39  if (!S.stats[wanted] || isDead(wanted)) return { text: displayName(wanted) + ' isn\'t in your box.' }
40  const name = nameOf(wanted)
41  delete S.stats[wanted]
42  if (wanted !== S.mon) return { text: 'You release ' + name + '. Bye-bye, ' + name + '!' }
43  S.evolveDue = null
44  return { text: 'You release ' + name + '. Bye-bye, ' + name + '! A fresh ' + displayName(S.mon) + ' takes its place.' }
45}
46
47const NICKNAME_MAX = 12
48
49// Name the active mon. Its species name, as in the games, takes the nickname away.
50export function nicknameCommand(wanted) {
51  const species = displayName(S.mon)
52  const nickname = wanted.replace(/\p{C}/gu, '').replace(/\s+/g, ' ').trim()
53  if (!nickname) {
54    const now = S.stats[S.mon]?.nickname ? species + ' goes by ' + S.stats[S.mon].nickname + '. ' : ''
55    return { text: now + 'Name it with /pokemon nickname <name>, up to ' + NICKNAME_MAX + ' characters.' }
56  }
57  if ([...nickname].length > NICKNAME_MAX) return { text: 'That\'s too long. A nickname fits ' + NICKNAME_MAX + ' characters.' }
58  const old = S.stats[S.mon]?.nickname
59  if (moveKey(nickname) === moveKey(species) || moveKey(nickname) === moveKey(S.mon)) {
60    if (!old) return { text: species + ' has no nickname.' }
61    const { nickname: _, ...rest } = S.stats[S.mon]
62    if (Object.keys(rest).length > 0) S.stats[S.mon] = rest
63    else delete S.stats[S.mon]
64    return { text: old + ' is just ' + species + ' again.' }
65  }
66  S.stats[S.mon] = { ...S.stats[S.mon], nickname }
67  return { text: (old ?? species) + ' is now ' + nickname + '!' }
68}
69
70export const FALLBACK_MOVES = [{ name: 'Tackle', effect: 'tackle' }]
71export const moveKey = (name) => name.toLowerCase().replace(/[\s\-_'.]/g, '')
72
73// A mon's moves, like "Pikachu knows Thunderbolt, Quick Attack, Thunder, Agility."
74export function movesText(name) {
75  const known = movesOf(name)
76  const moves = known.length > 0 ? known : FALLBACK_MOVES
77  return { text: nameOf(name) + ' knows ' + moves.map((m) => m.name).join(', ') + '.' }
78}
79
80// Play a random move, or the one named, and announce it. "list" lists the moves instead.
81export function attackCommand(wanted) {
82  const name = nameOf(S.mon)
83  if (wanted === 'list') return movesText(S.mon)
84  if (S.attack) return { text: name + ' is still attacking.' }
85  if (S.food) return { text: name + ' is busy eating.' }
86  const known = movesOf(S.mon)
87  const moves = known.length > 0 ? known : FALLBACK_MOVES
88  // Facing a foe, a random move is one that reaches it, and any such move is aimed at it
89  const battle = S.wild?.phase === 'battle'
90  const pool = battle && !wanted ? foeMoves() : moves
91  const move = wanted ? moves.find((m) => moveKey(m.name) === moveKey(wanted)) : pool[Math.floor(Math.random() * pool.length)]
92  if (!move) return { text: name + ' doesn\'t know "' + wanted + '". Its moves: ' + moves.map((m) => m.name).join(', ') + '.' }
93  startAttack(move, { foe: battle && aimsAhead(move) })
94  return { text: name + ' used ' + move.name + '!' + (move.text ? '\n' + move.text : '') }
95}
96
hooks/constants.js 30 lines
1// The band's clock, and the timings and sizes its parts share
2
3export const TICK_MS = 50
4// CSS pixels per sprite pixel on the desktop
5export const PIXEL_PX = 4
6// Image pixels per sprite pixel. The terminal scales the Image to its box, so sending
7// each pixel as a block keeps its edges sharp.
8export const IMAGE_UP = 4
9// How long a terminal that drew an Image's alt gets half blocks before the Image is asked
10// for again, from the first wait to the longest
11export const IMAGE_WAIT_TICKS = [(2 * 1000) / TICK_MS, (5 * 60 * 1000) / TICK_MS]
12export const MOVE_TICKS = 3
13export const HOP_TICKS = 12
14export const SLEEP_AFTER_MS = 5 * 60 * 1000
15export const REST_TICKS = [60, 160]
16export const STRIP_COLUMNS = 40
17export const HEAD_ROWS = 1
18export const HEAD_PIXELS = 8
19export const DEFAULT_COLOR = 0x01000000
20export const HEART_COUNT = 7
21export const HEART_GAP_TICKS = 7
22export const HEART_RISE_TICKS = 3
23export const PET_TICKS = 60
24export const FALL_TICKS = 2
25export const EAT_TICKS = 30
26export const YUM_TICKS = 30
27export const FLINCH_TICKS = 24
28export const SHAKE_TICKS = 12
29export const DRIP_TICKS = 8
30
hooks/crew.js 249 lines
1import { FLASH } from './party.js'
2
3// The party mons out of subagents' Poké Balls. Each running subagent gets a mon from the
4// box, and once its ball has landed and the band has room, the ball opens in a flash and
5// the mon hops out beside the lead. It strolls about the crew's columns, keeping off the
6// other mons out and their bubbles, shows its agent's thinking and tools, hops along with
7// the lead and when a wild mon passes behind it, hops when its agent finishes, then goes
8// back into the ball in a red flash, and the ball pops. A mon that loses its room goes
9// back the same way and waits in its ball. A crew is a plain array of members, oldest
10// first; every function returns a new crew or member and leaves its input alone.
11
12// The most mons out at once, one per ball slot before the +n label
13export const CREW_SIZE = 5
14// The columns kept clear right of each mon's body, between it and the next mon or the lead
15export const CREW_GAP = 3
16const FLASH_BEAT = 3
17const RELEASE_TICKS = FLASH_BEAT * FLASH.length
18const HOP_TICKS = 6
19const RED_TICKS = 12
20const RECALL_TICKS = RED_TICKS + FLASH_BEAT * FLASH.length
21const REST_TICKS = [60, 160]
22// Balls open this far apart, so mons come out one after the other
23const STAGGER_TICKS = 8
24// A cheer ripples along the crew this far apart
25const CHEER_STEP = 2
26
27// A member for agent id, with pick = { mon, variant } from the box
28const newMember = (id, { mon, variant }) => ({
29  id,
30  mon,
31  variant,
32  x: 0,
33  facing: 'right',
34  target: null,
35  restUntil: 0,
36  outAt: null,
37  backAt: null,
38  endAt: null,
39  done: false,
40  flinchAt: null,
41  hopAt: null,
42  startledBy: null,
43  thinking: false,
44  tools: [],
45})
46
47// Give agent id the first of mons no member has yet. variantOf says which colors it shows in.
48export function joinCrew(crew, id, mons, variantOf) {
49  if (crew.some((m) => m.id === id)) return crew
50  const free = mons.find((name) => !crew.some((m) => m.mon === name))
51  return free ? [...crew, newMember(id, { mon: free, variant: variantOf(free) })] : crew
52}
53
54const updated = (crew, id, fn) => crew.map((m) => (m.id === id ? fn(m) : m))
55
56export const crewThinking = (crew, id, thinking) => updated(crew, id, (m) => (m.thinking === thinking ? m : { ...m, thinking }))
57
58export const crewToolStarts = (crew, id, call, name) => updated(crew, id, (m) => ({ ...m, tools: [...m.tools, { call, name }] }))
59
60// A call ending, and the flinch it starts when it failed
61export const crewToolEnds = (crew, id, call, failed, tick) =>
62  updated(crew, id, (m) => ({ ...m, tools: m.tools.filter((t) => t.call !== call), flinchAt: failed ? tick : m.flinchAt }))
63
64// The agent finished: its mon hops, then goes back into its ball
65export const endedCrew = (crew, id, tick) =>
66  updated(crew, id, (m) => (m.endAt !== null ? m : { ...m, endAt: tick, thinking: false, tools: [] }))
67
68// The tool its agent started last and still runs, or null
69export const crewTool = (m) => m.tools.at(-1)?.name ?? null
70
71// Where a member is at: in its 'ball', on its way out in a 'release' flash, 'out', giving
72// its finishing 'hop', turning red on its way back in a 'recall', gone in its 'flash',
73// and back 'in' its ball
74export function crewPhase(m, tick) {
75  if (m.outAt === null) return 'ball'
76  if (m.backAt !== null) {
77    const t = tick - m.backAt
78    return t < RED_TICKS ? 'recall' : t < RECALL_TICKS ? 'flash' : 'in'
79  }
80  if (tick - m.outAt < RELEASE_TICKS) return 'release'
81  return m.endAt !== null ? 'hop' : 'out'
82}
83
84// Standing on the stage
85export const isOut = (m, tick) => ['release', 'out', 'hop', 'recall'].includes(crewPhase(m, tick))
86
87// Drawn on the stage: standing, or gone in the flash where it stood
88export const isShown = (m, tick) => isOut(m, tick) || crewPhase(m, tick) === 'flash'
89
90// Inside its flash, so its body stays out of sight: the first beat coming out, and all
91// of the way back in
92export function crewHidden(m, tick) {
93  const phase = crewPhase(m, tick)
94  return phase === 'flash' || (phase === 'release' && tick - m.outAt < FLASH_BEAT)
95}
96
97// Its ball lifts the lid while the mon comes out or goes back in
98export const ballOpen = (m, tick) => ['release', 'recall', 'flash'].includes(crewPhase(m, tick))
99
100// How far to tint it red on its way back into its ball
101export const crewRed = (m, tick) => (crewPhase(m, tick) === 'recall' ? Math.min(1, (tick - m.backAt + 1) / RED_TICKS) : 0)
102
103// The FLASH frame it comes out or goes back in, or null
104export function crewFlash(m, tick) {
105  const phase = crewPhase(m, tick)
106  if (phase === 'release') return FLASH[Math.floor((tick - m.outAt) / FLASH_BEAT)]
107  if (phase === 'flash') return FLASH[Math.floor((tick - m.backAt - RED_TICKS) / FLASH_BEAT)]
108  return null
109}
110
111// The finishing hop starts once it's all the way out
112const finishHopAt = (m) => Math.max(m.endAt, m.outAt + RELEASE_TICKS)
113
114// Up for the first half of a hop: its finishing hop, or the short one it started at
115// hopAt, stepping out, cheering with the lead, or startled by a passing wild mon
116export function crewHopping(m, tick) {
117  if (crewPhase(m, tick) === 'hop') return tick - finishHopAt(m) < HOP_TICKS / 2
118  return m.hopAt !== null && tick >= m.hopAt && tick - m.hopAt < HOP_TICKS / 2
119}
120
121// The mons out hop along with the lead, one after the other from the left
122export function cheerCrew(crew, tick) {
123  const out = crew.filter((m) => crewPhase(m, tick) === 'out').sort((a, b) => a.x - b.x)
124  return crew.map((m) => (out.includes(m) ? { ...m, hopAt: tick + out.indexOf(m) * CHEER_STEP } : m))
125}
126
127const flinching = (m, tick, flinchTicks) => m.flinchAt !== null && tick - m.flinchAt < flinchTicks
128
129export const crewWalking = (m, tick, flinchTicks) =>
130  crewPhase(m, tick) === 'out' && m.target !== null && m.target !== m.x && !flinching(m, tick, flinchTicks)
131
132// The columns a member's body and the gap after it take, from its idle box
133export const spanOf = (box) => box.right - box.left + 1 + CREW_GAP
134
135// How many of members, in order, fit their bodies and gaps in width columns
136export function crewFit(members, boxOf, width) {
137  let used = 0
138  let n = 0
139  for (const m of members) {
140    used += spanOf(boxOf(m))
141    if (used > width) break
142    n += 1
143  }
144  return n
145}
146
147// A lane per member across width columns, left to right: its body, its gap, and an even
148// share of the columns to spare. Each lane is the range of frame columns, lo to hi, its
149// mon may stand at.
150export function crewLanes(members, boxOf, width) {
151  const spans = members.map((m) => spanOf(boxOf(m)))
152  const share = Math.max(0, Math.floor((width - spans.reduce((a, b) => a + b, 0)) / Math.max(1, members.length)))
153  let left = 0
154  return new Map(
155    members.map((m, i) => {
156      const box = boxOf(m)
157      const lo = left - box.left
158      left += spans[i] + share
159      return [m.id, { lo, hi: Math.max(lo, left - CREW_GAP - 1 - box.right) }]
160    }),
161  )
162}
163
164const clamp = (v, lane) => Math.max(lane.lo, Math.min(lane.hi, v))
165const restFor = (tick, rand) => tick + REST_TICKS[0] + Math.floor(rand() * (REST_TICKS[1] - REST_TICKS[0]))
166
167// The frame columns m may stand at this tick: the crew's width columns, short of the
168// bodies of the mons out either side of it, their gaps, and the bubble room each shows
169// an icon in on its left, as bubbleOf gives. Mons share the room between them as they
170// stroll, so one squeezed by a bubble steps aside. hi falls short of lo when it's pinched.
171function roomOf(crew, m, tick, width, boxOf, bubbleOf) {
172  const box = boxOf(m)
173  let lo = bubbleOf(m) - box.left
174  let hi = width - CREW_GAP - 1 - box.right
175  for (const o of crew) {
176    if (o.id === m.id || !isOut(o, tick)) continue
177    const other = boxOf(o)
178    if (o.x < m.x) lo = Math.max(lo, o.x + other.right + 1 + CREW_GAP + bubbleOf(m) - box.left)
179    else hi = Math.min(hi, o.x + other.left - bubbleOf(o) - CREW_GAP - 1 - box.right)
180  }
181  return { lo, hi }
182}
183
184// Whether another mon on stage stands where m's body would at frame column x
185function blocked(crew, m, x, tick, boxOf) {
186  const box = boxOf(m)
187  return crew.some((o) => {
188    if (o.id === m.id || !isOut(o, tick)) return false
189    const other = boxOf(o)
190    return x + box.left <= o.x + other.right + CREW_GAP && o.x + other.left <= x + box.right + CREW_GAP
191  })
192}
193
194// Stroll like the lead idles: a random spot in its room, then a rest of 3 to 8 s. A mon
195// outside its room, as when the crew's columns shrink or a neighbor's bubble opens, walks
196// straight back into it, and a pinched one stands where it is until room opens.
197function strolled(m, room, tick, moveTicks, rand) {
198  if (room.hi < room.lo) return m.target === null ? m : { ...m, target: null }
199  let target = m.target
200  if (m.x < room.lo || m.x > room.hi) target = clamp(m.x, room)
201  else if (target !== null) target = clamp(target, room)
202  else if (tick >= m.restUntil) target = room.lo + Math.floor(rand() * (room.hi - room.lo + 1))
203  if (target === null || tick % moveTicks !== 0) return target === m.target ? m : { ...m, target }
204  if (target === m.x) return { ...m, target: null, restUntil: restFor(tick, rand) }
205  const facing = target < m.x ? 'left' : 'right'
206  return { ...m, target, facing, x: m.x + (facing === 'left' ? -1 : 1) }
207}
208
209// A wild mon walking in behind m makes it jump once, the first tick they overlap
210function startled(m, foe, tick, boxOf) {
211  if (!foe || m.startledBy === foe.id) return m
212  const box = boxOf(m)
213  if (foe.right < m.x + box.left || foe.left > m.x + box.right) return m
214  return { ...m, hopAt: tick, startledBy: foe.id }
215}
216
217// One tick of the crew. lanes holds a lane for each member that should be out across
218// the crew's width columns, and ready says whether a member's ball has landed so it can
219// open. A mon comes out in the middle of its lane, with a hop, once no other mon stands
220// there and the last one out has had its moment, then strolls the room it finds, as
221// roomOf gives it. foe is the columns of a wild mon walking in, or null. done lists the
222// agents whose mons are back in their balls for good, so their balls can pop.
223export function stepCrew(crew, { tick, lanes, width = 0, ready, boxOf, bubbleOf = () => 0, foe = null, moveTicks, flinchTicks, rand }) {
224  const done = []
225  let lastOut = Math.max(-Infinity, ...crew.map((m) => m.outAt ?? -Infinity))
226  const next = crew.map((m) => {
227    const lane = lanes.get(m.id)
228    const phase = crewPhase(m, tick)
229    if (phase === 'in') {
230      if (m.endAt === null) return { ...m, outAt: null, backAt: null, target: null, hopAt: null }
231      if (!m.done) done.push(m.id)
232      return m.done ? m : { ...m, done: true }
233    }
234    if (phase === 'ball') {
235      if (!lane || m.endAt !== null || !ready(m) || tick - lastOut < STAGGER_TICKS) return m
236      const x = lane.lo + Math.floor((lane.hi - lane.lo) / 2)
237      if (blocked(crew, m, x, tick, boxOf)) return m
238      lastOut = tick
239      return { ...m, x, outAt: tick, hopAt: tick + RELEASE_TICKS, startledBy: null, target: null, restUntil: restFor(tick, rand) }
240    }
241    if (phase === 'hop') return tick >= finishHopAt(m) + HOP_TICKS ? { ...m, backAt: tick } : m
242    if (phase !== 'out') return m
243    if (!lane) return { ...m, backAt: tick }
244    if (flinching(m, tick, flinchTicks)) return m
245    return strolled(startled(m, foe, tick, boxOf), roomOf(crew, m, tick, width, boxOf, bubbleOf), tick, moveTicks, rand)
246  })
247  return { crew: next, done }
248}
249
hooks/custom.js 306 lines
1// Mons fetched with /pokemon new, from any generation jakobhoeg/vscode-pokemon has.
2// The GIFs come through GitHub's contents API as base64, since $.http.fetch hands back
3// text, and are decoded here the way scripts/build-frames.mjs decodes the bundled ones.
4// Each mon is saved in the store under 'custom:<mon>', so it outlives plugin updates.
5// Every fetch goes through the get passed in, (url, init) => $.http.fetch(url, init).
6
7const REPO = 'https://api.github.com/repos/jakobhoeg/vscode-pokemon/contents/media'
8const GENS = [1, 2, 3, 4, 5]
9const VARIANTS = ['default', 'shiny']
10const ANIMS = ['idle', 'walk']
11const LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
12const HEADERS = { Accept: 'application/vnd.github+json', 'User-Agent': 'claude-pokemon' }
13
14export const CUSTOM_PREFIX = 'custom:'
15
16// Moves with animations, picked by the mon's types since later moves have none
17const TYPE_MOVES = {
18  normal: ['Tackle', 'Quick Attack', 'Headbutt', 'Growl'],
19  fire: ['Ember', 'Flamethrower', 'Fire Spin'],
20  water: ['Water Gun', 'Bubble Beam', 'Hydro Pump'],
21  grass: ['Vine Whip', 'Razor Leaf', 'Absorb'],
22  electric: ['Thunder Shock', 'Thunderbolt', 'Thunder Wave'],
23  ice: ['Ice Beam', 'Aurora Beam', 'Blizzard'],
24  fighting: ['Karate Chop', 'Low Kick', 'Double Kick'],
25  poison: ['Poison Sting', 'Acid', 'Sludge'],
26  ground: ['Sand Attack', 'Dig', 'Earthquake'],
27  flying: ['Gust', 'Wing Attack', 'Peck'],
28  psychic: ['Confusion', 'Psybeam', 'Psychic'],
29  bug: ['String Shot', 'Leech Life', 'Pin Missile'],
30  rock: ['Rock Throw', 'Rock Slide', 'Harden'],
31  ghost: ['Lick', 'Night Shade', 'Confuse Ray'],
32  dragon: ['Dragon Rage', 'Outrage', 'Agility'],
33  dark: ['Bite', 'Fury Swipes', 'Screech'],
34  steel: ['Harden', 'Slash', 'Take Down'],
35  fairy: ['Sing', 'Double Slap', 'Swift'],
36}
37
38// Two moves of the first type, one of the second, and Tackle to round out four
39export function movesForTypes(types) {
40  const [first, second] = types.filter((t) => TYPE_MOVES[t])
41  const picked = [...(TYPE_MOVES[first] ?? []).slice(0, 2), ...(TYPE_MOVES[second] ?? []).slice(0, 1), 'Tackle']
42  return [...new Set(picked)].slice(0, 4)
43}
44
45const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
46
47export function fromBase64(text) {
48  const clean = text.replace(/[^A-Za-z0-9+/]/g, '')
49  const out = new Uint8Array(Math.floor((clean.length * 3) / 4))
50  let o = 0
51  for (let i = 0; i < clean.length; i += 4) {
52    const n = (B64.indexOf(clean[i]) << 18) | (B64.indexOf(clean[i + 1]) << 12) | ((B64.indexOf(clean[i + 2]) & 63) << 6) | (B64.indexOf(clean[i + 3]) & 63)
53    out[o++] = n >> 16
54    if (i + 2 < clean.length) out[o++] = (n >> 8) & 255
55    if (i + 3 < clean.length) out[o++] = n & 255
56  }
57  return out.subarray(0, o)
58}
59
60// GIF LZW, least significant bit first, into count palette indices
61function lzw(minSize, data, count) {
62  const clear = 1 << minSize
63  const eoi = clear + 1
64  const prefix = new Int32Array(4096)
65  const suffix = new Uint8Array(4096)
66  const stack = new Uint8Array(4097)
67  for (let i = 0; i < clear; i++) suffix[i] = i
68  const out = new Uint8Array(count)
69  let o = 0
70  let size = minSize + 1
71  let next = eoi + 1
72  let prev = -1
73  let first = 0
74  let cur = 0
75  let bits = 0
76  for (const byte of data) {
77    cur |= byte << bits
78    bits += 8
79    while (bits >= size) {
80      const code = cur & ((1 << size) - 1)
81      cur >>>= size
82      bits -= size
83      if (code === clear) {
84        size = minSize + 1
85        next = eoi + 1
86        prev = -1
87        continue
88      }
89      if (code === eoi) return out
90      if (prev === -1) {
91        if (o < count) out[o++] = suffix[code]
92        prev = code
93        first = code
94        continue
95      }
96      let sp = 0
97      let c = code
98      if (code >= next) {
99        stack[sp++] = first
100        c = prev
101      }
102      while (c > eoi) {
103        stack[sp++] = suffix[c]
104        c = prefix[c]
105      }
106      first = suffix[c]
107      stack[sp++] = first
108      while (sp > 0 && o < count) out[o++] = stack[--sp]
109      if (next < 4096) {
110        prefix[next] = prev
111        suffix[next] = first
112        next++
113        if (next === 1 << size && size < 12) size++
114      }
115      prev = code
116    }
117  }
118  return out
119}
120
121// Every frame composited onto the canvas, as 0xRRGGBB or null where it's transparent
122export function decodeGif(bytes) {
123  const sig = String.fromCharCode(...bytes.subarray(0, 3))
124  if (sig !== 'GIF') throw new Error('not a GIF')
125  const u16 = (p) => bytes[p] | (bytes[p + 1] << 8)
126  const width = u16(6)
127  const height = u16(8)
128  const flags = bytes[10]
129  let p = 13
130  const table = (n) => {
131    const colors = []
132    for (let i = 0; i < n; i++, p += 3) colors.push((bytes[p] << 16) | (bytes[p + 1] << 8) | bytes[p + 2])
133    return colors
134  }
135  const global = flags & 0x80 ? table(2 << (flags & 7)) : []
136  const skipBlocks = () => {
137    while (bytes[p] !== 0 && p < bytes.length) p += bytes[p] + 1
138    p++
139  }
140  let canvas = new Array(width * height).fill(null)
141  let control = { delay: 0, transparent: -1, disposal: 0 }
142  const frames = []
143  while (p < bytes.length) {
144    const block = bytes[p++]
145    if (block === 0x3b) break
146    if (block === 0x21) {
147      const label = bytes[p++]
148      if (label === 0xf9) {
149        const packed = bytes[p + 1]
150        control = { delay: u16(p + 2), transparent: packed & 1 ? bytes[p + 4] : -1, disposal: (packed >> 2) & 7 }
151      }
152      skipBlocks()
153    } else if (block === 0x2c) {
154      const [fx, fy, fw, fh] = [u16(p), u16(p + 2), u16(p + 4), u16(p + 6)]
155      const packed = bytes[p + 8]
156      p += 9
157      const colors = packed & 0x80 ? table(2 << (packed & 7)) : global
158      const interlaced = (packed & 0x40) !== 0
159      const minSize = bytes[p++]
160      const chunks = []
161      while (bytes[p] !== 0 && p < bytes.length) {
162        chunks.push(bytes.subarray(p + 1, p + 1 + bytes[p]))
163        p += bytes[p] + 1
164      }
165      p++
166      const data = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0))
167      let at = 0
168      for (const c of chunks) {
169        data.set(c, at)
170        at += c.length
171      }
172      const indices = lzw(minSize, data, fw * fh)
173      const rowOrder = interlaced ? interlacedRows(fh) : [...Array(fh).keys()]
174      const before = control.disposal === 3 ? canvas.slice() : null
175      rowOrder.forEach((row, k) => {
176        const y = fy + row
177        if (y >= height) return
178        for (let col = 0; col < fw; col++) {
179          const x = fx + col
180          const index = indices[k * fw + col]
181          if (x < width && index !== control.transparent) canvas[y * width + x] = colors[index] ?? null
182        }
183      })
184      frames.push({ ms: control.delay < 2 ? 100 : control.delay * 10, px: canvas.slice() })
185      if (control.disposal === 2) {
186        for (let y = fy; y < Math.min(fy + fh, height); y++) for (let x = fx; x < Math.min(fx + fw, width); x++) canvas[y * width + x] = null
187      } else if (before) {
188        canvas = before
189      }
190      control = { delay: 0, transparent: -1, disposal: 0 }
191    } else {
192      break
193    }
194  }
195  return { width, height, frames }
196}
197
198// The image row each stored row of an interlaced frame lands on
199function interlacedRows(h) {
200  const rows = []
201  for (const [start, step] of [[0, 8], [4, 8], [2, 4], [1, 2]]) for (let y = start; y < h; y += step) rows.push(y)
202  return rows
203}
204
205// The decoded sheets, as sheets[variant][anim], into the shape hooks/frames.js holds:
206// cropped to the box every frame fits in, each variant with its own palette letters
207export function buildSprite(sheets) {
208  const { width: size } = sheets.default.idle
209  let minX = Infinity
210  let minY = Infinity
211  let maxX = -1
212  let maxY = -1
213  for (const v of VARIANTS) {
214    for (const a of ANIMS) {
215      for (const { px } of sheets[v][a].frames) {
216        px.forEach((c, i) => {
217          if (c === null) return
218          const x = i % size
219          const y = Math.floor(i / size)
220          minX = Math.min(minX, x)
221          maxX = Math.max(maxX, x)
222          minY = Math.min(minY, y)
223          maxY = Math.max(maxY, y)
224        })
225      }
226    }
227  }
228  if (maxX < 0) throw new Error('the sprite is empty')
229  const out = { width: maxX - minX + 1, height: maxY - minY + 1, variants: {} }
230  for (const v of VARIANTS) {
231    const palette = []
232    const letter = (c) => {
233      if (c === null) return '.'
234      let i = palette.indexOf(c)
235      if (i < 0) i = palette.push(c) - 1
236      if (i >= LETTERS.length) throw new Error(`more than ${LETTERS.length} colors`)
237      return LETTERS[i]
238    }
239    const anims = {}
240    for (const a of ANIMS) {
241      anims[a] = sheets[v][a].frames.map(({ ms, px }) => {
242        const rows = []
243        for (let y = minY; y <= maxY; y++) {
244          let row = ''
245          for (let x = minX; x <= maxX; x++) row += letter(px[y * size + x])
246          rows.push(row)
247        }
248        return { ms, rows }
249      })
250    }
251    out.variants[v] = { palette: palette.map((c) => '#' + c.toString(16).padStart(6, '0')), ...anims }
252  }
253  return out
254}
255
256// A failed GitHub request as a line for the person
257function githubError(res) {
258  if (res.status === 403 || res.status === 429) return "GitHub's hourly limit for anonymous requests is used up. Try again in a while."
259  return 'GitHub answered ' + res.status + '.'
260}
261
262async function fetchGif(get, gen, name, file) {
263  const res = await get(`${REPO}/gen${gen}/${name}/${file}`, { headers: HEADERS })
264  if (!res.ok) return { status: res.status, error: githubError(res) }
265  const { content } = JSON.parse(res.text)
266  return { gif: decodeGif(fromBase64(content)) }
267}
268
269// Every mon folder in a generation
270export async function monsOfGen(get, gen) {
271  const res = await get(`${REPO}/gen${gen}`, { headers: HEADERS })
272  if (!res.ok) throw new Error(githubError(res))
273  return JSON.parse(res.text).filter((entry) => entry.type === 'dir').map((entry) => entry.name)
274}
275
276// The mon's types from PokéAPI, or normal when it doesn't know the name
277async function typesOf(get, name) {
278  try {
279    const res = await get(`https://pokeapi.co/api/v2/pokemon-form/${name.replace(/_/g, '-')}`)
280    if (!res.ok) return ['normal']
281    return JSON.parse(res.text).types.map((t) => t.type.name)
282  } catch {
283    return ['normal']
284  }
285}
286
287// Fetch a mon's four GIFs, from the generation given or the first that has it, and build
288// the entry the store keeps: { gen, sprite, moves }. Throws with a line for the person.
289export async function fetchMon(get, name, gen) {
290  for (const g of gen ? [gen] : GENS) {
291    const firstFile = `${VARIANTS[0]}_${ANIMS[0]}_8fps.gif`
292    const first = await fetchGif(get, g, name, firstFile)
293    if (first.status === 404) continue
294    if (first.error) throw new Error(first.error)
295    const rest = await Promise.all(
296      VARIANTS.flatMap((v) => ANIMS.map((a) => [v, a])).slice(1).map(([v, a]) => fetchGif(get, g, name, `${v}_${a}_8fps.gif`)),
297    )
298    const failed = rest.find((r) => r.error)
299    if (failed) throw new Error(failed.status === 404 ? `${name} is missing some of its GIFs.` : failed.error)
300    const gifs = [first, ...rest].map((r) => r.gif)
301    const sheets = { default: { idle: gifs[0], walk: gifs[1] }, shiny: { idle: gifs[2], walk: gifs[3] } }
302    return { gen: g, sprite: buildSprite(sheets), moves: movesForTypes(await typesOf(get, name)) }
303  }
304  throw new Error(`No mon named "${name}" in generations ${(gen ? [gen] : GENS).join(', ')}.`)
305}
306
hooks/dex.js 93 lines
1import { BASE_FORM, evolutionsOf, preEvolutionOf, startLevel } from './evolutions.js'
2
3// The gen 1 Pokédex and how often each mon turns up in the wild. DEX lists the 151
4// sprite keys in national dex order. A female sprite counts as its base form's entry.
5
6export const DEX = [
7  'bulbasaur', 'ivysaur', 'venusaur', 'charmander', 'charmeleon', 'charizard', 'squirtle', 'wartortle', 'blastoise', 'caterpie',
8  'metapod', 'butterfree', 'weedle', 'kakuna', 'beedrill', 'pidgey', 'pidgeotto', 'pidgeot', 'rattata', 'raticate',
9  'spearow', 'fearow', 'ekans', 'arbok', 'pikachu', 'raichu', 'sandshrew', 'sandslash', 'nidoran_female', 'nidorina',
10  'nidoqueen', 'nidoran_male', 'nidorino', 'nidoking', 'clefairy', 'clefable', 'vulpix', 'ninetales', 'jigglypuff', 'wigglytuff',
11  'zubat', 'golbat', 'oddish', 'gloom', 'vileplume', 'paras', 'parasect', 'venonat', 'venomoth', 'diglett',
12  'dugtrio', 'meowth', 'persian', 'psyduck', 'golduck', 'mankey', 'primeape', 'growlithe', 'arcanine', 'poliwag',
13  'poliwhirl', 'poliwrath', 'abra', 'kadabra', 'alakazam', 'machop', 'machoke', 'machamp', 'bellsprout', 'weepinbell',
14  'victreebel', 'tentacool', 'tentacruel', 'geodude', 'graveler', 'golem', 'ponyta', 'rapidash', 'slowpoke', 'slowbro',
15  'magnemite', 'magneton', 'farfetchd', 'doduo', 'dodrio', 'seel', 'dewgong', 'grimer', 'muk', 'shellder',
16  'cloyster', 'gastly', 'haunter', 'gengar', 'onix', 'drowzee', 'hypno', 'krabby', 'kingler', 'voltorb',
17  'electrode', 'exeggcute', 'exeggutor', 'cubone', 'marowak', 'hitmonlee', 'hitmonchan', 'lickitung', 'koffing', 'weezing',
18  'rhyhorn', 'rhydon', 'chansey', 'tangela', 'kangaskhan', 'horsea', 'seadra', 'goldeen', 'seaking', 'staryu',
19  'starmie', 'mrmime', 'scyther', 'jynx', 'electabuzz', 'magmar', 'pinsir', 'tauros', 'magikarp', 'gyarados',
20  'lapras', 'ditto', 'eevee', 'vaporeon', 'jolteon', 'flareon', 'porygon', 'omanyte', 'omastar', 'kabuto',
21  'kabutops', 'aerodactyl', 'snorlax', 'articuno', 'zapdos', 'moltres', 'dratini', 'dragonair', 'dragonite', 'mewtwo',
22  'mew',
23]
24
25export const dexKey = (mon) => BASE_FORM[mon] ?? mon
26
27export const dexNumber = (mon) => DEX.indexOf(dexKey(mon)) + 1
28
29export const LEGENDARY = ['articuno', 'zapdos', 'moltres', 'mewtwo', 'mew']
30
31// Rare mons and everything they evolve into
32export const RARE = [
33  'lapras', 'snorlax', 'eevee', 'dratini', 'omanyte', 'kabuto', 'aerodactyl', 'chansey', 'tauros', 'kangaskhan',
34  'scyther', 'pinsir', 'porygon', 'ditto', 'hitmonlee', 'hitmonchan',
35]
36
37// weight is how often a tier turns up, hits how many attacks wear one out, and catch
38// the best odds of a ball holding it
39export const TIERS = {
40  common: { weight: 60, hits: 3, catch: 0.9 },
41  uncommon: { weight: 25, hits: 5, catch: 0.75 },
42  rare: { weight: 6, hits: 7, catch: 0.55 },
43  legendary: { weight: 1, hits: 10, catch: 0.35 },
44}
45
46const STAGE_TIERS = ['common', 'uncommon', 'rare']
47const SHINY_ODDS = 1 / 128
48const FEMALE_FORM = Object.fromEntries(Object.entries(BASE_FORM).map(([female, base]) => [base, female]))
49
50// Outside the short lists, a family's base form is common and each evolution a tier
51// rarer. A mon with no family is uncommon.
52export function tierOf(mon) {
53  const key = dexKey(mon)
54  if (LEGENDARY.includes(key)) return 'legendary'
55  let base = key
56  let stage = 0
57  for (let parent = preEvolutionOf(base); parent; parent = preEvolutionOf(base)) {
58    base = parent
59    stage++
60  }
61  if (RARE.includes(base)) return 'rare'
62  if (stage === 0 && evolutionsOf(base).length === 0) return 'uncommon'
63  return STAGE_TIERS[stage]
64}
65
66const BY_TIER = Object.fromEntries(Object.keys(TIERS).map((tier) => [tier, DEX.filter((mon) => tierOf(mon) === tier)]))
67
68// A tier by weight, then a mon from it. random() returns a number in [0, 1).
69export function pickWild(random) {
70  const total = Object.values(TIERS).reduce((sum, { weight }) => sum + weight, 0)
71  let roll = random() * total
72  const tier = Object.keys(TIERS).find((name) => (roll -= TIERS[name].weight) < 0) ?? 'common'
73  const pool = BY_TIER[tier]
74  const key = pool[Math.floor(random() * pool.length)]
75  const mon = FEMALE_FORM[key] && random() < 0.5 ? FEMALE_FORM[key] : key
76  const variant = random() < SHINY_ODDS ? 'shiny' : 'default'
77  return { mon, variant, key, tier, level: startLevel(mon) }
78}
79
80// Two marks of one mon as one: the earliest time for each of seen and caught, and shiny
81// if either has it
82export function mergedDexEntry(old, patch) {
83  const entry = old && typeof old === 'object' ? { ...old } : {}
84  for (const key of ['seen', 'caught']) {
85    const times = [entry[key], patch[key]].filter((t) => typeof t === 'number')
86    if (times.length > 0) entry[key] = Math.min(...times)
87  }
88  if (entry.shiny || patch.shiny) entry.shiny = true
89  return entry
90}
91
92export const isCaught = (entry) => typeof entry?.caught === 'number'
93
hooks/encounter.js 50 lines
1import { aimsAhead } from './attacks.js'
2import { FALLBACK_MOVES } from './commands.js'
3import { dexKey, tierOf, TIERS } from './dex.js'
4import { bandRows, foeMiddle } from './layout.js'
5import { movesOf } from './moves.js'
6import { displayName } from './names.js'
7import { BALL } from './party.js'
8import { levelOf } from './records.js'
9import { VARIANTS } from './sprites.js'
10import { S } from './state.js'
11import { thrownWild } from './wild.js'
12
13// The wild mon on show, kept as data in wild.js, as the home mon faces it: its name, the
14// moves that reach it, the ball thrown at it, and a mon that ran away coming back as one
15
16export const wildName = () => (S.wild.variant === 'shiny' ? 'shiny wild ' : 'wild ') + displayName(S.wild.mon)
17
18// Throw a ball at the foe in battle. It falls from the foe's middle to the ground.
19export function catchCommand() {
20  if (S.wild?.phase !== 'battle' && S.wild?.phase !== 'throw') return { text: 'There\'s no wild Pokémon here.' }
21  if (S.attack || S.wild.phase === 'throw') return { text: 'Wait for the move to end.' }
22  const rows = bandRows()
23  const drop = Math.max(0, rows * 2 - BALL.length - (foeMiddle(rows).y - Math.floor(BALL.length / 2)))
24  S.wild = thrownWild(S.wild, S.tick, drop)
25  return { text: 'You threw a Poké Ball!' }
26}
27
28// The moves that can reach a foe in front of the mon
29export function foeMoves() {
30  const moves = movesOf(S.mon).filter(aimsAhead)
31  return moves.length > 0 ? moves : FALLBACK_MOVES
32}
33
34// The foe's own moves that reach the home mon
35export function wildMoves() {
36  const moves = movesOf(S.wild.mon).filter(aimsAhead)
37  return moves.length > 0 ? moves : FALLBACK_MOVES
38}
39
40// A mon that ran away turns up again at its own level and variant, a tier harder and
41// harder still to hold in a ball
42const TIER_ORDER = Object.keys(TIERS)
43const RUNAWAY_CATCH = 0.5
44
45export function runawayFoe(name) {
46  const tier = TIER_ORDER[Math.min(TIER_ORDER.length - 1, TIER_ORDER.indexOf(tierOf(name)) + 1)]
47  const variant = VARIANTS.includes(S.stats[name].ranAway.variant) ? S.stats[name].ranAway.variant : 'default'
48  return { mon: name, variant, key: dexKey(name), tier, level: levelOf(name), runaway: true, catchScale: RUNAWAY_CATCH }
49}
50
hooks/evolutions.js 113 lines
1// The gen 1 evolutions follow the Red and Blue rules and are keyed by sprite key, in
2// Pokédex order. Each entry is one thing the mon can become: { into, level } on level-up,
3// { into, item } with an evolution stone, or { into, trade: true }. A mon that doesn't
4// evolve has no entry.
5
6const FIRST_LEVEL = 5
7
8// Female sprites take their base form's place in the family, so raichu comes from
9// pikachu and venusaur_female from ivysaur
10export const BASE_FORM = { pikachu_female: 'pikachu', venusaur_female: 'venusaur' }
11
12export const EVOLUTIONS = {
13  bulbasaur: [{ into: 'ivysaur', level: 16 }],
14  ivysaur: [{ into: 'venusaur', level: 32 }],
15  charmander: [{ into: 'charmeleon', level: 16 }],
16  charmeleon: [{ into: 'charizard', level: 36 }],
17  squirtle: [{ into: 'wartortle', level: 16 }],
18  wartortle: [{ into: 'blastoise', level: 36 }],
19  caterpie: [{ into: 'metapod', level: 7 }],
20  metapod: [{ into: 'butterfree', level: 10 }],
21  weedle: [{ into: 'kakuna', level: 7 }],
22  kakuna: [{ into: 'beedrill', level: 10 }],
23  pidgey: [{ into: 'pidgeotto', level: 18 }],
24  pidgeotto: [{ into: 'pidgeot', level: 36 }],
25  rattata: [{ into: 'raticate', level: 20 }],
26  spearow: [{ into: 'fearow', level: 20 }],
27  ekans: [{ into: 'arbok', level: 22 }],
28  pikachu: [{ into: 'raichu', item: 'Thunder Stone' }],
29  pikachu_female: [{ into: 'raichu', item: 'Thunder Stone' }],
30  sandshrew: [{ into: 'sandslash', level: 22 }],
31  nidoran_female: [{ into: 'nidorina', level: 16 }],
32  nidorina: [{ into: 'nidoqueen', item: 'Moon Stone' }],
33  nidoran_male: [{ into: 'nidorino', level: 16 }],
34  nidorino: [{ into: 'nidoking', item: 'Moon Stone' }],
35  clefairy: [{ into: 'clefable', item: 'Moon Stone' }],
36  vulpix: [{ into: 'ninetales', item: 'Fire Stone' }],
37  jigglypuff: [{ into: 'wigglytuff', item: 'Moon Stone' }],
38  zubat: [{ into: 'golbat', level: 22 }],
39  oddish: [{ into: 'gloom', level: 21 }],
40  gloom: [{ into: 'vileplume', item: 'Leaf Stone' }],
41  paras: [{ into: 'parasect', level: 24 }],
42  venonat: [{ into: 'venomoth', level: 31 }],
43  diglett: [{ into: 'dugtrio', level: 26 }],
44  meowth: [{ into: 'persian', level: 28 }],
45  psyduck: [{ into: 'golduck', level: 33 }],
46  mankey: [{ into: 'primeape', level: 28 }],
47  growlithe: [{ into: 'arcanine', item: 'Fire Stone' }],
48  poliwag: [{ into: 'poliwhirl', level: 25 }],
49  poliwhirl: [{ into: 'poliwrath', item: 'Water Stone' }],
50  abra: [{ into: 'kadabra', level: 16 }],
51  kadabra: [{ into: 'alakazam', trade: true }],
52  machop: [{ into: 'machoke', level: 28 }],
53  machoke: [{ into: 'machamp', trade: true }],
54  bellsprout: [{ into: 'weepinbell', level: 21 }],
55  weepinbell: [{ into: 'victreebel', item: 'Leaf Stone' }],
56  tentacool: [{ into: 'tentacruel', level: 30 }],
57  geodude: [{ into: 'graveler', level: 25 }],
58  graveler: [{ into: 'golem', trade: true }],
59  ponyta: [{ into: 'rapidash', level: 40 }],
60  slowpoke: [{ into: 'slowbro', level: 37 }],
61  magnemite: [{ into: 'magneton', level: 30 }],
62  doduo: [{ into: 'dodrio', level: 31 }],
63  seel: [{ into: 'dewgong', level: 34 }],
64  grimer: [{ into: 'muk', level: 38 }],
65  shellder: [{ into: 'cloyster', item: 'Water Stone' }],
66  gastly: [{ into: 'haunter', level: 25 }],
67  haunter: [{ into: 'gengar', trade: true }],
68  drowzee: [{ into: 'hypno', level: 26 }],
69  krabby: [{ into: 'kingler', level: 28 }],
70  voltorb: [{ into: 'electrode', level: 30 }],
71  exeggcute: [{ into: 'exeggutor', item: 'Leaf Stone' }],
72  cubone: [{ into: 'marowak', level: 28 }],
73  koffing: [{ into: 'weezing', level: 35 }],
74  rhyhorn: [{ into: 'rhydon', level: 42 }],
75  horsea: [{ into: 'seadra', level: 32 }],
76  goldeen: [{ into: 'seaking', level: 33 }],
77  staryu: [{ into: 'starmie', item: 'Water Stone' }],
78  magikarp: [{ into: 'gyarados', level: 20 }],
79  eevee: [
80    { into: 'vaporeon', item: 'Water Stone' },
81    { into: 'jolteon', item: 'Thunder Stone' },
82    { into: 'flareon', item: 'Fire Stone' },
83  ],
84  omanyte: [{ into: 'omastar', level: 40 }],
85  kabuto: [{ into: 'kabutops', level: 40 }],
86  dratini: [{ into: 'dragonair', level: 30 }],
87  dragonair: [{ into: 'dragonite', level: 55 }],
88}
89
90// PARENTS maps each evolved mon to the mon it comes from and the entry that takes it there
91const PARENTS = new Map()
92for (const [from, entries] of Object.entries(EVOLUTIONS)) {
93  if (BASE_FORM[from]) continue
94  for (const entry of entries) PARENTS.set(entry.into, { from, entry })
95}
96
97const parentOf = (mon) => PARENTS.get(BASE_FORM[mon] ?? mon)
98
99export const evolutionsOf = (mon) => EVOLUTIONS[mon] ?? []
100
101export const levelEvolutionOf = (mon) => evolutionsOf(mon).find((entry) => entry.level) ?? null
102
103export const preEvolutionOf = (mon) => parentOf(mon)?.from ?? null
104
105// A mon reached by level-up starts at that level, one reached by stone or trade starts
106// where its pre-evolution does, and any other mon starts at FIRST_LEVEL, the lowest
107// levels the games allow
108export function startLevel(mon) {
109  const parent = parentOf(mon)
110  if (!parent) return FIRST_LEVEL
111  return parent.entry.level ?? startLevel(parent.from)
112}
113