# @hiyve/react-music-games

React components for interactive music games. Six games, each a world of its own: board games on a river and along a forest trail (`TrailGame`), a note-reading railway (`NoteExpressGame`), a band to play in on the beat (`FrogBandGame`), a balloon steered by ear (`BalloonRideGame`) and a lab where chords and scales are brewed (`PotionLabGame`). `MusicGames` puts them in a lobby, ready to drop in, and `TopicPractice` is Practice: every kind of card on its own, by topic and level. Underneath them are thirty-three kinds of card — notes dragged onto a staff, intervals to name, note values added up with tiles, keys to tap, sounds to tell apart — played one at a time (`DeckPlayer`) or all at once (`DeckBoard`), with the answer checked at once, a word and a sound for right or wrong, another go after a wrong answer, and a score at the end. The games' frame — the HUD, the Ready and End screens, How to play, the phone layout — is exported for a game of your own (`GameShell`). The cards and the checking are `@hiyve/music-games`; the notation is drawn here as SVG, so nothing is loaded.

## Installation

```bash
npx @hiyve/cli login
npm install @hiyve/react-music-games @hiyve/music-games @hiyve/music-theory @mui/material @mui/icons-material @emotion/react @emotion/styled
```

## Quick start

The games and Practice, ready to drop in:

```tsx
import { createLocalStorageCollectionStore, createLocalStorageResultStore } from '@hiyve/music-games';
import { MusicGames, TopicPractice } from '@hiyve/react-music-games';

const results = createLocalStorageResultStore();
const collections = createLocalStorageCollectionStore();
const player = { id: 'player-1', name: 'Ada' };

// The lobby and its six games: pick one and it plays in place, with a button back.
export function Games() {
  return (
    <div style={{ height: '100dvh' }}>
      <MusicGames resultStore={results} collectionStore={collections} player={player} />
    </div>
  );
}

// Practice: topics, sets of eight cards at five levels, the cards missed.
export function Practice() {
  return <TopicPractice resultStore={results} player={player} sx={{ minHeight: '100dvh' }} />;
}
```

Or one deck of cards of your own:

```tsx
import { useState } from 'react';
import { newSeed, repeatCards } from '@hiyve/music-games';
import { DeckPlayer } from '@hiyve/react-music-games';

export function SpellingGame() {
  const [seed, setSeed] = useState(newSeed);
  return (
    <DeckPlayer
      settings={{ cards: repeatCards({ kind: 'spellOnStaff' }, 8) }}
      seed={seed}
      onDeckCompleted={(summary, record) => save(record)}
      onAnother={() => setSeed(newSeed())}
    />
  );
}
```

Mix kinds in one deck: `{ cards: [{ kind: 'spellOnStaff' }, { kind: 'intervalId', clef: 'bass' }, { kind: 'rhythmMath' }, { kind: 'symbolSpelling' }] }`. A one-letter word — `{ kind: 'spellOnStaff', words: ['A', 'B', 'C', 'D', 'E', 'F', 'G'] }` — asks for a single note to be dragged onto the staff.

### Sizing: the box, not the window

The components lay out by the box they are given, so they fit beside a sidebar, under a top bar or in a panel as well as on a whole screen. `MusicGames`, `MusicGame`, `GameLobby`, `TopicPractice`, `DeckPlayer`, `DeckBoard`'s cards, the trail games and the game frame each measure their own box; every responsive size inside them, and every choice between a phone's layout and a wide one, follows the nearest such box — a card in a game's side panel lays out for the panel, not the screen. The widths are fixed at 600, 900 and 1200 pixels, MUI's own, so a host theme with other breakpoints cannot move them; the rest of the host's theme (its fonts, colours and spacing) still applies.

Give a game, or the lobby, a height: it fills it, and scrolls inside it when it needs more (a trail on a phone takes the height it needs). Practice grows with its content, for the page around it to scroll.

## MusicGames

The lobby and its games in one: pick a game in the lobby and it plays in the lobby's place, with a button back (**All games**). Which game is open can be kept by the host — in an address, say — with `playing` and `onPlayingChange`, or by the component itself (`defaultPlaying`). Everything else is passed on to the lobby and the game: the catalogue, where results and what is won are kept, who is playing, sounds. While a game is open it fills the container's height, as `MusicGame` does, so give the container one.

```tsx
const [playing, setPlaying] = useState<string | null>(null);

<div style={{ height: '100dvh' }}>
  <MusicGames playing={playing} onPlayingChange={setPlaying} resultStore={results} collectionStore={collections} player={player} samples={{ baseUrl: 'https://your-host/soundfonts/FluidR3_GM/' }} />
</div>
```

| Prop | Type | Description |
|---|---|---|
| `playing` | `string \| null` | The id of the game open, or `null` for the lobby, when the host keeps it |
| `defaultPlaying` | `string \| null` | The game to open on when the component keeps it (default: `null`, the lobby) |
| `onPlayingChange` | `(id: string \| null) => void` | A game was picked (its id) or left (`null`) |
| `games` | `readonly MusicGameDef[]` | The games offered and played (default: `defaultMusicGames`) |
| `results` | `readonly GameResult[]` | Results to count each game's plays from in the lobby; read from `resultStore` when not given |
| `mascot` | `MascotName \| false` | The face beside the lobby's title, or `false` for none (default: `'owl'`) |
| `colors` | `Partial<MusicHubColors>` | The lobby's colours |
| `cardColors` | `Partial<GameColors>` | The cards' colours in each game |
| `lobbyLabels` | `Partial<GameLobbyLabels>` | The lobby's words |
| `gameLabels` | `Partial<MusicGameLabels>` | The words of the bar over each game, its back button among them |
| `level`, `defaultLevel`, `onLevelChange`, `topic`, `defaultTopic`, `onTopicChange`, `seed`, `onSeedChange`, `background`, `retryUntilRight`, `sounds`, `samples`, `player`, `resultStore`, `collectionStore`, `showInstructionsFirst`, `topics`, `onResult`, `onError`, `sx` | | As `MusicGame` takes them, for the game open; `resultStore` and `sx` go to the lobby too |

## GameLobby

The lobby on its own: a big card for each game with a living picture of its world, its pitch and how often it has been played (every result stamped with its id, at any level or topic). The pictures move as the lobby opens, then rest; a card's picture moves again while the card is pointed at or focused, never out of sight or while the page is hidden. Picking a game calls `onPlay` with its `MusicGameDef`. The cards stand up to three across on a wide screen and one under another on a phone.

```tsx
import { GameLobby, defaultMusicGames } from '@hiyve/react-music-games';

<GameLobby resultStore={results} onPlay={(game) => setPlaying(game.id)} />
<GameLobby games={defaultMusicGames.filter((game) => game.kind === 'trail')} onPlay={(game) => setPlaying(game.id)} labels={{ title: 'Board games' }} />
```

| Prop | Type | Description |
|---|---|---|
| `onPlay` | `(game: MusicGameDef) => void` | Called with the game picked (required) |
| `games` | `readonly MusicGameDef[]` | The games to offer, in order (default: `defaultMusicGames`) |
| `results` | `readonly GameResult[]` | Results to count each game's plays from; read from `resultStore` when not given |
| `resultStore` | `ResultStore` | Where results are kept, to count each game's plays |
| `mascot` | `MascotName \| false` | The face beside the title, or `false` for none (default: `'owl'`) |
| `labels` | `Partial<GameLobbyLabels>` | The lobby's words (`defaultGameLobbyLabels`, `mergeGameLobbyLabels`) |
| `colors` | `Partial<MusicHubColors>` | The lobby's colours (`defaultMusicHubColors`, `mergeMusicHubColors`) |
| `sx` | `SxProps<Theme>` | |

## MusicGame

One game from the catalogue — a trail, Note Express, Balloon Ride, Frog Band or Potion Lab — at a level, dealt from a seed. A bar over the game holds a back button (with `onBack`), a trail's level buttons (the other games offer their levels on their own Ready screen) and a **New game** button that deals a fresh seed. Pointed at a Practice topic the game plays (`topic`, or `defaultTopic`), a trail and Note Express deal that topic's cards and Potion Lab keeps to its chords or its keys; a chip names the topic ("Playing Bass notes"), and its close button goes back to the game's own cards. Balloon Ride and Frog Band always play their own, and a topic a game does not play is passed by. Level, topic and seed can each be kept by the host or by the game. Each finished game's result is stamped with `musicGameStamp`.

**It fills its container's height**: give it one (the screen less any bar above it, say). In a narrow box a trail takes the height it needs instead, and the game scrolls inside its box; there, too, a trail's five level buttons become one (**Level 2**, `levelButton`) that opens them, so the bar keeps to one row.

```tsx
<div style={{ height: 'calc(100dvh - 56px)' }}>
  <MusicGame game="noteExpress" defaultLevel={2} resultStore={results} collectionStore={collections} player={player} onBack={() => setPlaying(null)} />
</div>
```

| Prop | Type | Description |
|---|---|---|
| `game` | `MusicGameDef \| string` | The game to play: an entry, or its id in `games` (required) |
| `games` | `readonly MusicGameDef[]` | Where an id is looked up (default: `defaultMusicGames`) |
| `level` | `number` | The level played, 1 to the game's `levels`, when the host keeps it |
| `defaultLevel` | `number` | The level to start on when the game keeps it (default: 1) |
| `onLevelChange` | `(level: Level) => void` | The player picked another level |
| `topic` | `PracticeTopicId \| null` | The Practice topic whose cards it plays, or `null` for its own, when the host keeps it |
| `defaultTopic` | `PracticeTopicId \| null` | The topic to start on when the game keeps it (default: `null`, its own cards) |
| `onTopicChange` | `(topic: PracticeTopicId \| null) => void` | The player went back to the game's own cards |
| `seed` | `number` | The seed the game is dealt from, when the host keeps it; a new seed is a new game |
| `onSeedChange` | `(seed: number) => void` | The player asked for a new game: its seed |
| `onBack` | `() => void` | A back button before the level buttons, calling this |
| `background` | `string` | Behind the game: any CSS background (default: the game's colour glowing over a deep navy); `'transparent'` shows the host's own |
| `retryUntilRight` | `boolean` | Another go at the same card after a wrong answer, where the game plays that way (default: `true`; see `musicGameUsesRetry`) |
| `sounds` | `boolean` | Sounds on (default: `true`) |
| `samples` | `SampleSource` | Recorded instrument samples for the notes, from a host you choose; without it a small built-in voice plays |
| `player` | `{ id: string; name?: string }` | Who is playing, kept with each result |
| `resultStore` | `ResultStore` | Where each finished game's result is saved |
| `collectionStore` | `CollectionStore` | Where what is won is collected: a train's wagons, a sky, a band member, a potion |
| `showInstructionsFirst` | `boolean` | Open How to play before the first card (default: `true`) |
| `topics` | `readonly PracticeTopic[]` | The topics a pointed game names (default: `practiceTopics`) |
| `colors` | `Partial<GameColors>` | The cards' colours in a trail and in Note Express: right, wrong, the staff, a choice |
| `labels` | `Partial<MusicGameLabels>` | The bar's words (`defaultMusicGameLabels`, `mergeMusicGameLabels`) |
| `onResult` | `(result: GameResult) => void` | Called with each finished game's result |
| `onError` | `(error: Error) => void` | |
| `sx` | `SxProps<Theme>` | |

## TopicPractice

Practice, ready to drop in: every kind of card on its own, by topic and level, with no world around it. The list shows the topics in the order a beginner meets them (`practiceTopics` from `@hiyve/music-games`: listening, the keyboard, the letters A–G, beat, note values, line or space, treble notes, steps and intervals, time and bars, signs and terms, whole songs, bass notes, keys and scales, chords, the alto and tenor clefs), each with its five levels and the best stars won at each; tapping a topic opens it at the first level not yet won with two stars or more. A topic deals sets of eight cards at its level — from one way of practising it (its **How** choices) or from every way in turn (**Mix**, the default) — one card at a time, each question read aloud from a speaker button. Every way is a chip in sight: on a wide screen on as many lines as they take, beside the five levels; on a phone on one line to swipe along, faded at an edge with more beyond it, the way chosen scrolled into view, with the level one button beside the topic's name (**Level 2** over its stars) that opens the five. A way that suits only later levels (`from` on its row: Signs in a bar from level 3, say) is offered at every level with the level it starts at on its chip (**Level 3+**), and opens there; the mix leaves it out until then, and a level below it goes back to the mix. A set's score card offers **Again** (a fresh set) and **Next level**, the main button after two stars or more; with `onPlayGame` it also offers the games that play the topic, one or two of them (**Play a game with this**, or **Play Forest Trail** and **Play Note Express** for treble notes). **Practise what I missed** on the list, and **What I missed** in a topic (on a phone a button with the count, beside the topic's name), deal up to eight of the cards still missed, each the very question missed; a card leaves the list once it has been answered right first time in two different sets of missed cards.

Each set is saved to `resultStore`, and the stars and the cards missed are read back from it; without one they last while Practice is mounted. Where Practice is — the list, a topic at a level and a way, the cards missed — can be kept by the host (`view`, `onViewChange`), in an address say, or by Practice itself (`defaultView`). The catch and the hop are left out unless `omit` says otherwise (`defaultPracticeOmit` from `@hiyve/music-games`). A host can also show a topic's set as a board of every card at once (`board` in the view); Practice offers no button for it.

```tsx
import { useState } from 'react';
import type { Level, PracticeTopicId } from '@hiyve/music-games';
import { MusicGame, TopicPractice } from '@hiyve/react-music-games';
import type { PracticeView } from '@hiyve/react-music-games';

export function PracticeAndPlay() {
  const [view, setView] = useState<PracticeView>({});
  const [play, setPlay] = useState<{ game: string; topic: PracticeTopicId; level: Level } | null>(null);
  if (play) {
    return (
      <div style={{ height: '100dvh' }}>
        <MusicGame game={play.game} defaultTopic={play.topic} defaultLevel={play.level} resultStore={results} player={player} onBack={() => setPlay(null)} />
      </div>
    );
  }
  return <TopicPractice view={view} onViewChange={setView} resultStore={results} player={player} onPlayGame={(game, topic, level) => setPlay({ game: game.id, topic, level })} />;
}
```

| Prop | Type | Description |
|---|---|---|
| `view` | `PracticeView` | Where Practice is, when the host keeps it |
| `defaultView` | `PracticeView` | Where to open when Practice keeps it (default: the list of topics) |
| `onViewChange` | `(view: PracticeView) => void` | Called with where Practice goes next |
| `resultStore` | `ResultStore` | Where each set is saved, and the stars and the cards missed read back from (default: kept in memory while mounted) |
| `player` | `{ id: string; name?: string }` | Who is practising, kept with each result |
| `samples` | `SampleSource` | Recorded instrument samples for the notes, from a host you choose; without it a small built-in voice plays |
| `retryUntilRight` | `boolean` | Another go at the same card after a wrong answer (default: `true`) |
| `sounds` | `boolean` | Sounds on (default: `true`) |
| `topics` | `readonly PracticeTopic[]` | The topics offered, in order: any of `practiceTopics`, renamed or left out as you like (default: all of them) |
| `omit` | `readonly GameKind[]` | Kinds of card Practice leaves out (default: `defaultPracticeOmit`, the catch and the hop) |
| `games` | `readonly MusicGameDef[]` | The games a set's score card offers to play the topic with (default: `defaultMusicGames`); none without `onPlayGame` |
| `onPlayGame` | `(game: MusicGameDef, topic: PracticeTopicId, level: Level) => void` | A game was picked from a score card, with the topic and level just practised |
| `mascot` | `MascotName \| false` | The face beside the title, or `false` for none (default: `'owl'`) |
| `labels` | `Partial<TopicPracticeLabels>` | Practice's words (`defaultTopicPracticeLabels`, `mergeTopicPracticeLabels`) |
| `colors` | `Partial<MusicHubColors>` | Practice's colours (`defaultMusicHubColors`, `mergeMusicHubColors`) |
| `cardColors` | `Partial<GameColors>` | The cards' colours on Practice's dark panel |
| `onResult` | `(result: GameResult) => void` | Called with each finished set's result, after it is saved |
| `onError` | `(error: Error) => void` | A set could not be dealt or saved, or sound failed |
| `sx` | `SxProps<Theme>` | |

A `PracticeView`:

| Field | Type | Description |
|---|---|---|
| `topic` | `PracticeTopicId` | The topic open; none for the list of topics |
| `how` | `string` | The way to practise it — a `way` of one of the topic's `practiceRows`, or `PRACTICE_MIX` (default) |
| `level` | `Level` | The level, 1 to 5 |
| `seed` | `number` | The seed the set is dealt from; a new seed is a new set |
| `board` | `boolean` | Every card of the set at once, as a board — the host's to open: Practice shows no button for it |
| `missed` | `boolean` | The cards missed — in `topic`, when one is given |

## The catalogue

`defaultMusicGames` is the six games, in the order the lobby shows them. Each `MusicGameDef` has a home topic — what it plays, and where Practice sends a player who wants a game of that topic — and the Practice topics it can be pointed at instead.

| Game | `id` | `kind` | Home topics | Can be pointed at |
|---|---|---|---|---|
| Rhythm River | `rhythmRiver` | `trail` (a river, moonlit) | `values` | `time`, `beat` |
| Forest Trail | `forestTrail` | `trail` (a forest path, by day) | `treble` | `staff`, `bass`, `altoTenor`, `steps`, `letters`, `keyboard` |
| Note Express | `noteExpress` | `express` | `treble`, `bass` | `signs`, `values`, `keys`, `listening` |
| Balloon Ride | `balloonRide` | `balloon` | `listening` | |
| Frog Band | `frogBand` | `band` | `beat` | |
| Potion Lab | `potionLab` | `potion` | `chords`, `keys` | |

A catalogue of your own is a list of `MusicGameDef`s — the six filtered, reordered or retitled, or a trail of your own cards:

| Field | Type | Description |
|---|---|---|
| `id` | `string` | Tells games apart; results are stamped with it |
| `title` | `string` | |
| `pitch` | `string` | What you do, in one line, in the world's own words: shown in the lobby |
| `blurb` | `string` | The line under the title inside the game, when it differs from `pitch` |
| `kind` | `MusicGameKind` | Which game plays it: `'trail'`, `'express'`, `'balloon'`, `'band'` or `'potion'` |
| `home` | `PracticeTopicId` | The topic it plays |
| `homes` | `readonly PracticeTopicId[]` | Every home topic, when a game has more than one |
| `accepts` | `readonly PracticeTopicId[]` | Other topics it can be pointed at |
| `mascot` | `MascotName` | |
| `accent` | `string` | The game's colour: its card in the lobby, its buttons and progress |
| `levels` | `number` | Levels 1 to this; every card is asked at the level chosen |
| `trail` | `Partial<TrailSettings>` | A trail's cards and settings, when it is played with its own cards |
| `scene` | `'night' \| 'day'` | A trail's sky |
| `terrain` | `'river' \| 'forest'` | A trail's land |

| Function | What it gives |
|---|---|
| `musicGamesForTopic(topic, games?)` | Every game that plays a topic: those whose home it is first (treble notes: Forest Trail, then Note Express), then those that can be pointed at it |
| `musicGamePlays(game, topic)` | Whether a game plays a topic: one of its homes, or one it can be pointed at |
| `musicGameUsesRetry(game)` | Whether `retryUntilRight` changes how a game plays: a trail and Note Express take it; Balloon Ride, Frog Band and Potion Lab have their own rules for a wrong answer |
| `musicGameStamp(game, level, topic?)` | The name a game's results are stamped with: `<id>:L<level>`, and `:<topic>` when it played a Practice topic's cards (`forestTrail:L3:bass`) |
| `readMusicGameStamp(stamp)` | A stamp read back: `{ id, level, topic }`, or `null` for a result that is not a game's |

## The lobby's and Practice's look and words

The lobby and Practice are drawn as glass on a dark backdrop. `colors` (`MusicHubColors`; `defaultMusicHubColors`, `mergeMusicHubColors`) sets `background` (any CSS background, a deep navy lit from the top by default; `'transparent'` shows the host's own), `text`, `soft` (a line under a title), `faint` (a count, a hint) and `gold` (stars won). Every word is a label:

- `GameLobbyLabels` (`defaultGameLobbyLabels`, `mergeGameLobbyLabels`): `title` ("Music Games"), `subtitle`, `play`, `playGame` (`{title}`, for a screen reader) and `played` ("Played {count}×").
- `MusicGameLabels` (`defaultMusicGameLabels`, `mergeMusicGameLabels`): `level`, `levelButton` (`{level}`), `playingTopic` ("Playing {topic}"), `ownCards`, `newGame` and `back` ("All games").
- `TopicPracticeLabels` (`defaultTopicPracticeLabels`, `mergeTopicPracticeLabels`): the list (`title`, `subtitle`, `practiseMissed`, `topicLevel`, `stars`), a topic (`allTopics`, `level`, `levelButton`, `levelShort`, `how`, `mix`, `fromLevel`, `wayFromLevel`, `whatIMissedCount`), the cards missed (`back`, `missedTitle`, `missedTopicTitle`, `missedNone`, `missedOne`, `missedMany`, `missedLoading`, `missedEmpty`, `backToPractice`) and the score card (`again`, `nextLevel`, `done`, `playAGame`, `playGame`).

The lobby and the games' words use the "Fredoka" and "Nunito" fonts where the host page loads them (see [Requirements](#requirements)).

## DeckPlayer

| Prop | Type | Description |
|---|---|---|
| `settings` | `DeckSettings` | One entry per card; it may be written inline — the deck is dealt again only when its content changes |
| `seed` | `number` | The deck is dealt from it; change it for another deck |
| `retryUntilRight` | `boolean` | After a wrong answer, another go (default `true`) — up to `maxTries` goes; otherwise one answer settles the round. A wrong try with another go to come marks only the choice made, so the next go is still the player's own; once the round is settled the card shows its right answer (the right button lit, the right key or note drawn, the tiles or letters put right) and names it. A card of only two choices is settled by a wrong answer — the other choice would be no question — (a listening card plays its sound once more with the right answer lit), and a card that can't be worked out by trying (a chord to build, a rhythm to tap) is settled after its last go, a tap-the-beat card with a kind word, so no one is stuck. A catch, a hop or a memory match goes on until it is done |
| `maxTries` | `number` | With `retryUntilRight`, the goes a card gets before it is settled and its answer shown (default `3`; `Infinity` for no end) |
| `autoAdvanceMs` | `number \| null` | Move on by itself this long after a right answer (default `null`: wait for the button) |
| `sounds` | `boolean` | Sound a note as it is placed, a tone for right and wrong (default `true`) |
| `readAloud` | `'auto' \| 'button' \| false` | Read each card's question aloud — as the card opens and from a speaker button (`'auto'`), from the button only, or never (default `false`); where the answers are buttons of words, the question ends with them ("What is this note called? Whole note, half note or quarter note."), unless it names them already ("Do the notes step or skip?"); a listening or tapping card, which sounds itself, is read only from the button |
| `speak` | `(text) => void \| Promise<void>` | Your own voice for the questions, in place of the device's |
| `onRoundSettled` | `(round, index) => void` | A round was settled |
| `onDeckCompleted` | `(summary, record) => void` | The deck ended; `record` is small enough to store and `restoreDeck` brings it back |
| `onAnother` | `() => void` | The score card's **New deck** button, when given |
| `onAgain` | `() => void` | The score card's **Play again** calls it in place of dealing the same cards again — to deal fresh ones, change `seed` (default: the same deck again) |
| `onContinue` | `() => void` | The score card's **Continue** button, with a forward arrow, when given — the main, filled button unless `scorePrimary` says otherwise |
| `scorePrimary` | `'again' \| 'continue'` | Which score-card button is the main one (default: **Continue** when `onContinue` is given, else **Play again**); a step not passed keeps **Play again** first, say |
| `scoreExtraActions` | `ReactNode` | Buttons of your own on the score card, after its usual ones — **Play a game with this**, say |
| `onError` | `(error: Error) => void` | The deck could not be made from its settings, or sound failed |
| `names` | `Partial<IntervalNames>` | What each interval is called |
| `theoryNames` | `Partial<TheoryNames>` | What qualities, scales, modes and motions are called |
| `colors`, `labels`, `scoreLabels`, `sx` | | Customization |

A card whose answer is one choice — an interval, a note-value tile — is checked the moment the choice is made. A spelling waits for **Check** once every note or letter is placed. Every kind of card fits a phone's screen (390 × 844) with its **Check** or **Next** in sight: the count of cards sits beside the progress bar so the header keeps to one row, a settled card's words sit beside **Next** rather than over it, and the cards draw their staffs, keys and tiles to fit, no target smaller than a fingertip.

**After a wrong answer.** A wrong try with another go to come says "Not quite. Try again!" and, under it, a nudge towards the method in plain words — "Start on C and count up, a letter each line and space.", "Add the beats: a half note is 2.", "Look at the last sharp." — which stays while the card is open again, never the answer itself. Once the round is settled wrong (the last try, or a card of two choices, or with `retryUntilRight` off) the card names the answer and explains it in one sentence — "Start on middle C and count up: C, D, E. It's E.", "2 + 1 = 3 beats: a dotted half note.", "The last sharp is F♯; one letter up is G major." — while the picture works it out: the letters counted up the staff from the nearest C — or from bass F, between the bass clef's dots, for the notes beside it, from the treble staff's top line for the notes above it, out to the C on the second ledger line, and down from the bass staff's bottom line, G, for the notes below it, with treble G and bass F themselves read by their clef — (numbers for an interval or a scale degree), the line through a line note picked out, C and every white key to the right key named (F and G found by the three black keys instead — F just left of them, G one key right of F — and a key with no C below it on the keyboard counted down from the C above), the beats written under each value, the sharp or flat that names the key lit, a scale's gaps (W, H) written under its notes, a chord's notes named. A bar over an 8 (3/8, 6/8) is counted in eighths; an interval named with its kind (a minor 3rd, a perfect 5th) is counted in letters, then in half steps; a chord with a sharp or flat in it is built by counting half steps from its root ("Start on E♭. Count 4 half steps up to G, then 3 more to B♭. It's E♭ major."); an augmented or diminished chord is told by both its 3rds, and an inverted chord is restacked in 3rds first — and asked for its root, named after it ("Restack the notes in 3rds: G, B, D. The root is G, so the chord is G major."); music with D.C. al Fine is followed as it is played ("Play to D.C. al Fine, go back to bar 1, and play until Fine."). A speaker beside the words reads them aloud, only when tapped (`readAloud` on). Every sentence is a label, one per kind: `nudgeNoteName` … `nudgeFinishTune`, `explainCountUp` … `explainFinishTune` (their `{fields}` named beside each; a time-signature card has one for each thing it asks: `nudgeBottomNumber`, `nudgeStrongBeat`, `nudgeMediumStrongBeat`, `explainBottomNumber`, `explainBottomEight`, `explainStrongBeat`, `explainMediumStrongBeat`; melodic or harmonic: `nudgeIntervalShape`, `explainMelodic`, `explainHarmonic`; the bar rule: `nudgeBarRule` and its three explanations; a chord's root: `nudgeChordRoot`, `explainChordRoot`, `explainChordRootStacked`; D.C. al Fine: `nudgeTuneRoadMap`, `explainTuneRoadMap`), and `readHint` for the speaker. `DeckBoard` writes the same words under each card; `TrailGame` says them on its status line.

## Scores, results and help

Every player and game (`DeckPlayer`, `DeckBoard`, `TrailGame`, `NoteExpressGame`, `FrogBandGame`, `BalloonRideGame`, `PotionLabGame`) takes the same frame props:

| Prop | Description |
|---|---|
| `game` | The game's name, stamped on its results (default: the kinds of its cards) |
| `samples` | Recorded instrument samples for the notes (a `SampleSource` from `@hiyve/music-theory`), from a host you choose; without it a small built-in voice plays (see [useGameSounds](#usegamesounds)) |
| `resultStore` | Where results go (any `ResultStore` from `@hiyve/music-games`); nothing is kept without it |
| `player` | `{ id, name? }`, stamped on results |
| `onResult` | A result was made: once for each play, Play again with the same seed included, never again as the game re-renders |
| `instructions` | How to play, for the help button (default: made from the kinds of cards; `false` hides it) |
| `showInstructionsFirst` | Open how to play before the first card (default: false) |
| `mascot` | `'owl' \| 'fox' \| 'frog' \| 'cat'` (a `MascotName`), or `false`; reacts to answers |
| `showScore` | Points, stars and streak in the header (default: true) |

Points roll up as the game goes (`ScoreBar`), the mascot reacts, a perfect game gets confetti (`Celebration`), and the score card shows stars and points, with a word that matches the stars (three stars is "Brilliant!" or "Perfect!", never "Nearly there").

The games built in the game shell (`NoteExpressGame`, `FrogBandGame`, `BalloonRideGame`, `PotionLabGame`; see [GameShell](#gameshell-a-game-of-your-own)) take these as well:

| Prop | Description |
|---|---|
| `onLevelChange` | Level pills on the Ready screen: a pill was chosen, so deal the game again at that level. The pills show only when this is given |
| `levels` | How many levels the pills offer (default 5) |
| `onContinue` | Onward from the End screen (back to a map, say): the main button, with a forward arrow |
| `shellLabels` | The shell's words (`GameShellLabels`): the HUD, the Ready and End screens, How to play |
| `speak` | Your own recordings for How to play's words, read when its speaker is tapped |

**Motion.** The games are drawn to run smoothly on a phone: what moves for show (clouds, sails, twinkles, a fish's tail, a pad's drift, the HUD's flame) moves without the rest of the picture being drawn again and stops while the page is hidden. For a player whose device asks for less motion (`prefers-reduced-motion: reduce`) that decoration stands still everywhere, while what the game is made of keeps moving: a train crossing, fish swimming past, the lanterns on Frog Band's lane, the balloon's drift, the frog's hop. The timed games hold their clock while the page is hidden (another tab, a phone locked): Note Express's sun, Potion Lab's candle, and Frog Band's show, so no time is lost to switching away.

`HowToPlayDialog` and `defaultInstructions` (one entry per kind, with `instructionsFor(kinds)` for a mixed deck) are exported for use elsewhere, with each game's own How to play: `trailInstructions` (a river trail, another go after a wrong answer) and `trailInstructionsFor`, `expressInstructions`, `expressPlayInstructions` and `expressSingingInstructions`, `balloonRideInstructions`, `frogBandInstructions` and `potionLabInstructions` — each a `GameInstructions` (`title`, `summary`, `steps`, `tip`). `useResults({ store, query })` lists what a store holds and `ResultsTable` shows it — results kept at an older record version among them, brought up to date as they are read, their points, stars and dates as they were (a result whose cards can no longer be dealt again, `record.restorable: false`, still lists and still counts for a best).

## TrailGame

A board game on a course that winds differently every game (laid from the seed), bevelled stones for spaces, vines that climb ahead, the mascot as the piece hopping stone to stone, a glass HUD — the title, how far along, the points and stars, with tips and How to play as two small buttons in the corner — and a dark question panel: beside the board where the game is wide or square, under it where the game is tall. Answer right, roll the dice, hop along; reach the finish medallion to win. `terrain` makes it a river with whirlpools that pull back and nets that hold the piece (default) or a forest path with fox holes and mud (`'forest'`, with its own words for them — `forestTrailLabels`); a trap holds the piece for a few right answers, or until the die shows the number it asks for (three failed rolls at the most); `scene` picks a moonlit or daylight look; `title` and `subtitle` go over the board. A `level` in the settings asks every card at that level.

```tsx
import { TrailGame } from '@hiyve/react-music-games';

<TrailGame settings={{ spaces: 20, dice: 3, cards: [{ kind: 'noteNameId' }, { kind: 'rhythmFill' }, { kind: 'termId' }], course: { vines: 2, whirlpools: 2 }, level: 3 }} seed={seed} scene="night" title="Rhythm River" game="rhythm-river" resultStore={store} />
<TrailGame settings={{ spaces: 20, cards: [{ kind: 'noteNameId' }, { kind: 'stepSkip' }], level: 2 }} seed={seed} terrain="forest" scene="day" mascot="fox" title="Forest Trail" />
```

Its words follow its board: a river says vine, whirlpool and net, and a forest path says vine, fox hole and mud. That holds for the messages, the HUD chips and How to play. A trap counts its turns in words that fit the number ("Sit out 1 turn", "free next turn"). How to play comes from `trailInstructionsFor(terrain, retryUntilRight, title)`, which says whether a wrong answer gets another go or ends the turn; pass `instructions` to replace it. Play again starts a fresh board with the piece on START, and a mute takes effect at once, even mid-turn. A wrong answer gets another go until the card's last try, as in `DeckPlayer` — a wrong one of two choices, or the third — which ends the turn with the piece put.

| Prop | Type | Description |
|---|---|---|
| `settings` | `Partial<TrailSettings>` | The board: `spaces` (default 20), `cards` (asked in turn, one per turn), `dice` (the die's sides, default 3), `course` (how it winds and where its shortcuts fall), `shortcuts` and `traps` fixed by hand, `maxSlides`, and `level` — every card at that level, and that level's board unless the settings say otherwise |
| `seed` | `number` | Lays the same course and deals the same cards for the same seed |
| `scene` | `'night' \| 'day'` | Moonlit (default) or daylight |
| `terrain` | `'river' \| 'forest'` | A river (default) or a forest path, each with its own words |
| `title`, `subtitle` | `string` | Over the board |
| `retryUntilRight` | `boolean` | Another go after a wrong answer, up to the card's last try (default `true`) |
| `sounds` | `boolean` | Sound on (default `true`) |
| `onTrailCompleted` | `(state: TrailState) => void` | The piece reached the finish |
| `onAnother` | `() => void` | The finish's score card shows **New deck** for it, when given |
| `onError` | `(error: Error) => void` | |
| `trailLabels` | `Partial<TrailLabels>` | The board's words (`defaultTrailLabels`, `forestTrailLabels`, `mergeTrailLabels(overrides, terrain)`) |
| `names`, `theoryNames`, `colors`, `labels`, `sx` | | Customization, as `DeckPlayer` |

## NoteExpressGame

A note-reading railway game through the Key Meadow, played in trains before the sun sets. Each catch card of the deck is a **train**: short trains of wagons, each pulled by a little steam engine, roll past on three tracks — the far one smaller and higher, the near one larger and lower — seen from a little above like a model railway, and every wagon carries a note on an enamel sign set into its side (or, for other decks, a sign, a value, a key signature or a key), drawn the right way round whichever way the train runs. Your engine waits at the station platform in front with the conductor in a peaked cap, and your train grows as wagons hook on. There are two ways to play, chosen on the Ready screen:

- **Hook** — the station signboard names a note ("Hook every G") — its name only, so each wagon's note is read on its staff and matched to the name, never a picture matched to the same picture — with a small wagon on the board for each one in the train, filled as they are hooked. Tap every wagon carrying that note, in any octave the level allows: it uncouples, rolls over to your train and hooks on with a clank, and its place in the train it left stays empty, so the other wagons roll on where they were and a quick second tap lands. A wrong wagon jolts on its buffers with a clunk, breaks the combo, moves the sun on (`penaltySeconds`, from 1 at level 1 to 4 at level 5), and its train holds still a moment while a line under the signboard says what it was ("Not that one — it was a G."; a singing wagon, whether it sang higher or lower than the sign; on the keys, "Not that key — the wagon says G."), read aloud only when its speaker is tapped.
- **Play the wagons** — one octave of keys lies along the platform edge. Each wagon rolls by, pushed by its engine, with a note on its side; tap the key of that note — any key of the same letter — before it passes the signal. The key sounds and is coloured only while it sounds, and the wagon's panel lights with it as it rolls over to your train. A wrong key jolts the leading wagon, which rolls on, and breaks the combo; a wagon that passes the signal ends the combo and comes round again later. At level 1 one slow wagon comes at a time and the keys are named; more notes follow, then two wagons at once and faster, then the bass clef.

The way defaults to hooking at levels 1 and 2 and playing from level 3 (`mode`; `onModeChanged` hears the player's choice). A deck that can only be hooked by sight — by ear, or signs, values, key signatures or terms — or only played (cards with `play`) fixes the way, and the choice is not offered. Wagons hooked in a row build a **combo** — a chip in the HUD whose multiplier climbs to ×2 at three in a row, ×3 at six and ×4 at ten. Now and then a **golden wagon**, gold-trimmed and glinting, rolls by faster on a track of its own, worth five wagons. Hooked by sight, it counts only if it matches the signboard, and what it carries is harder to read: the note on a ledger line, or at level 5 the letter with a sharp or a flat (G♯ is not a G), a symbol or one that looks like it, a value a dot away, a key signature in the other clef. Played, it carries a harder note to play: on a ledger line, or a sharp or a flat on a black key at level 5. The **sun crossing the sky is the clock**: it rises over the left hills, crosses above the signboard and sets behind the right ones, the light warming to sunset as it goes; a screen reader hears the seconds left. When a train's right wagons are all hooked, the rest roll away and the next train comes in.

A deck of catch cards hooked by ear (`byEar`) is a train of **singing wagons**, always hooked by sight: the signboard plays a note (tap it to hear it again, lit while it sounds), each wagon chimes its own note when tapped — glowing, with rings of sound, while it chimes — and its train stops while it waits with a gold **Hook it!** badge; tap it again to hook it if it sang the signboard's note (`expressSingingInstructions`; `expressPlayInstructions` for the keys).

The deck's `level` sets the trains (`expressLevelSettings`) as well as what the wagons carry: three slow wagons with two to hook, a golden wagon every third train and plenty of daylight at level 1, to six quick wagons with three to hook and a golden wagon in every train after the first at level 5; on the keys one wagon at a time at levels 1 and 2 and two at once from level 3, the daylight counted per wagon. `expressNotesDeck(level)` from `@hiyve/music-games` is the game's own deck, reading notes: middle C to G on the treble staff at level 1, the bass clef from level 4, both with ledger lines at level 5. `timer` sets the daylight in seconds outright, or `false` for none; the sun holds still while How to play or the wagon book is open, or while the page is hidden (another tab, a phone locked). The Ready screen says the goal ("Hook 20 wagons to your train before the sun sets."), offers the level pills when `onLevelChange` is given and the way to play, and **Start the train** counts down 3, 2, 1 before the whistle. The End screen says "Your train is full!" for a clean run — every train cleared with no wrong wagon — "18 of 20 hooked" when a wrong wagon was tapped or a train left short, or "The sun set on 12 wagons", then the wagons on your train and the wrong wagons, the stars and their word (when the sun sets, the trains not reached count as missed, so the stars say how far the train got), the trains' points, the **Hook bonus** from the combos and golden wagons on its own line (kept in the result, with the way it was played as `extra.expressMode`), the total and the best, with **Play again** and **New train** (`onAnother`); the fanfare and confetti are for a clean run only, and Play again starts the result's clock afresh.

**Wrong wagons cost.** Each train's credit is the right wagons hooked less the wrong wagons tapped, never below nothing, over the wagons there were to hook (`expressScore` in `@hiyve/music-games`): a train cleared with no wrong wagon is worth 1, tapping every wagon is worth half a train at level 1 and nothing at level 5, and a run of tapping everything earns a star at most. The stars in the HUD follow the credit as the game goes, and the result keeps them. With `retryUntilRight={false}` a wrong wagon settles its train with what it had hooked.

**The wagon book.** Each topic Note Express carries — treble notes, bass notes, singing wagons, keys and letters, note values, signs and terms, key signatures — and each level has its own wagon design (`expressWagons`: the Treble Box Car, the Treble Mail Van, the Symbol Circus Wagon, thirty-five in all — each build in its own storybook livery — a brick box car, a timber wagon of natural wood, a teal mail van, a silver tanker, a maroon circus wagon — trimmed in its topic's colour), and the train's wagons are drawn in that design's livery and trim, each wagon of a train a different build in turn, like a goods train. Filling your train with no more than one wrong wagon puts it in the player's wagon book — the Ready screen says so under the book's button; "New in your wagon book!" on the End screen the first time, "Too many wrong wagons" when the train was full but more were tapped — with the most stars it was won with. The book opens from the Ready screen and the End screen. It is kept per `player` in `collectionStore` (a `CollectionStore`: `createLocalStorageCollectionStore()`, or `createCollectionStore({ read, write })` over any database); without one it lasts as long as the page. `onWagonCollected(wagon, isNew)` says when one is won; `wagonBook={false}` leaves the book out. `WagonBook` shows the book on its own — every wagon design, the ones won in colour with their names and stars, the rest as dark shapes — from a `Collection` you load yourself.

`scene` picks where the railway runs: through the Key Meadow by day (`'meadow'`, the default), out of the rocky tunnel mouths of Bass Clef Cave with lanterns (`'cave'`), or over the stone viaduct of Symbol Summit among snowy peaks (`'summit'`). On a phone the railway fills the screen: the HUD keeps to one row, the sun crosses the sky over the signboard, the tracks run above the platform in the bottom corner (or the keys along the bottom), and the notes on the wagons are drawn large enough to read and to tap. `title` and `subtitle` go in the HUD; `expressLabels` renames the signboard, the progress chip, the combo, the golden wagon, the wagon book and the messages.

```tsx
import { createLocalStorageCollectionStore, expressNotesDeck } from '@hiyve/music-games';
import { NoteExpressGame } from '@hiyve/react-music-games';

const collections = createLocalStorageCollectionStore();

<NoteExpressGame
  settings={expressNotesDeck(level)}
  seed={seed}
  title="Note Express"
  game="note-express"
  player={{ id: 'player-1', name: 'Ada' }}
  resultStore={store}
  collectionStore={collections}
  onWagonCollected={(wagon, isNew) => isNew && console.log(`New: ${wagon.name}`)}
  onLevelChange={(level) => setLevel(level)}
  onAnother={() => setSeed(newSeed())}
/>
```

| Prop | Type | Description |
|---|---|---|
| `settings` | `DeckSettings` | A deck of `catch` cards, a train each; its `level` sets the trains (`expressNotesDeck(level)` reads notes) |
| `mode` | `'catch' \| 'play'` | Hook the signboard's note, or play each wagon's note on the keys (default: hooking at levels 1–2, playing from 3) |
| `onModeChanged` | `(mode: ExpressMode) => void` | The player chose how to play on the Ready screen |
| `seed` | `number` | Deals the same trains again for the same seed |
| `scene` | `'meadow' \| 'cave' \| 'summit'` | Where the railway runs (default: `'meadow'`) |
| `timer` | `number \| false` | Seconds of daylight, or `false` for no clock (default: from the level and the trains) |
| `penaltySeconds` | `number` | Seconds a wrong wagon takes from the sun (default: from the level) |
| `retryUntilRight` | `boolean` | Keep hooking a train after a wrong wagon (default: `true`) |
| `collectionStore` | `CollectionStore` | Where the wagon book is kept, per `player` |
| `onWagonCollected` | `(wagon: ExpressWagon, isNew: boolean) => void` | A full train won its wagon design |
| `wagonBook` | `boolean` | Show the wagon book (default: `true`) |
| `onTrainCompleted` | `(summary: DeckSummary, points: number) => void` | The game ended: the train full or the sun set — every train in the summary (those the sun set on as missed), and the total points the End screen shows |
| `expressLabels` | `Partial<NoteExpressLabels>` | The game's words (`defaultNoteExpressLabels`, `mergeNoteExpressLabels`) |

`WagonBook` takes `open`, `onClose`, `collection` (a `Collection`, or `null`), `highlight` (a wagon design's id to pick out, `express:treble:2`), `labels` (`Partial<NoteExpressLabels>`) and `look`.


## FrogBandGame

Play in the band: keep the beat, echo it, then make up your own. A show is three songs on a lantern-lit lily-pad stage at night, the bandleader frog on the stage, the crowd on the near bank and a big drum — the stage's hero — at the end of a lane across the water with a gold ring on it. Each song is four short rounds of call and response, and every bar the player plays comes straight after a **count-in**: a bar of clicks (two of 2/4 and 6/8), accented on 1, the count big beside the ring — 1 2 3 4, or in 6/8 the two big beats with the eighths ticking lightly between — the ring, the drum and the lanterns pulsing on each beat, then **Your turn!** and the player's bar.

- **Keep the beat** — after the count-in, lanterns float down the lane, one on every beat; tap as each reaches the ring.
- **Echo** — the bandleader plays a bar on his woodblock, lit as each note sounds; a count-in; then tap it back. The bar is shown written out afterwards, each note green where it was played.
- **Read and play** — a bar is written on the board over the stage; after the count-in, tap each note as it comes round. At level 1 the bar also travels down the lane as notes, long ones with a tail for their length — a scaffold while the lane is learned; from level 2 the lane keeps only its beat dots and bar lines and the rhythm is read from the board, every time the bar comes round. At levels 3–5 holding the drum through a long note earns a bonus: How to play says so, and over a bar with a long note the board says "Hold the long notes!".
- **Your turn** — the band asks a question (a bar, shown and lit as it plays); a count-in; then tap a bar of your own against the metronome. Each tap is judged on the bar's beat grid (eighths, or quarters at the levels with nothing shorter) and the bar is written on the beat, then checked by the answer-the-rhythm card's rules for the level (end on a long note, use a note of the question, don't copy it). If it keeps them, the band plays the question and your answer back in time, each note lit as it sounds; if not, the board says why and the round comes round again (after three tries the band plays one answer that works).

**The metronome** clicks on every beat of every round — through the count-ins, the band's bars and every bar the player plays, accented on the first beat of each bar, mixed under the band — and its source, a small metronome over the ring, lights and swings with each click, timed from the same moments the clicks are heard. Tap the drum — or anywhere below the lane on a phone, or press Space or Enter — and it sounds at once and bounces; each tap is judged on the audio clock **Perfect**, **Good · early** or **Good · late** — so the next tap knows which way to move — or **Miss** beside the ring (a tap of a made-up bar between the beats is **Off the beat**), the lantern or note lighting as it is played. A round is in time with three notes in four played. Whatever sounds lights while it sounds: the drum, the metronome, the bandleader, each player in the band, each note on the board; the lanterns over the stage brighten on every beat and the crowd bobs along. On-beat taps fill the **crowd meter** in the HUD and misses drain it; at levels 1–3 it never empties, and at levels 4 and 5 an empty meter sends the crowd home and ends the show early — never in the first song, and after a warning (warm red in the HUD when it is low). **Stars** count the notes played in time over the notes asked for (and the taps of your own bars): three from 95%, two from 70%, one from 40%; the End screen says how many notes were in time and how many were Perfect, in words that match the stars. The level (`settings.level`) sets the tempo, the timing windows (wide at level 1), the rhythms (halves and quarters, then eighths, rests, dotted rhythms), the time signatures (4/4, then 3/4 and 2/4, 6/8 at level 5) and the length of the songs together: two to four minutes at level 1, no more than six at level 5.

**The band.** Every show finished brings a new player into the band — a Shaker Turtle, a Bass Frog, a Flute Bird, a Banjo Frog and a Marimba Newt, in that order — kept per `player` in `collectionStore` like Note Express's wagon book ("Joins the band!" on the End screen). Each one stands on the stage from then on and plays its part in the backing, so the band sounds fuller as you play. The band book opens from the Ready and End screens; `BandBook` shows it on its own.

The sound is the band's own: the drum, the woodblock and each player are recorded instruments (the metronome a built-in click) from the same soundfont collection as `samples` (`taiko_drum`, `woodblock`, `acoustic_bass`, `flute`, `banjo`, `marimba` beside the piano), timed on the audio clock; without `samples`, small built-in voices play. The HUD has a mute button; the show holds while How to play is open or the page is hidden (another tab, a phone locked) — nothing is missed meanwhile — and when it comes back the round starts again from its count-in (or, between rounds, the show goes on). A stray tap counts only inside the player's own bars, never while tapping along with the band. Where an answer must end on a long note, the board says so as the player's turn begins. The Ready screen says the goal, offers the level pills when `onLevelChange` is given and has a big **Start the show**; the End screen says "What a show!" (or "The crowd went home"), the stars and their word, the rounds' points, the **On the beat** bonus (Perfect and Good taps) on its own line, the total and the best, the notes in time (and long notes held), with **Play again** and **New show** (`onAnother`); the fanfare and confetti are for a finished show only. Results are stamped with the show's deck, so they keep and list like any deck.

```tsx
import { createLocalStorageCollectionStore } from '@hiyve/music-games';
import { FrogBandGame } from '@hiyve/react-music-games';

const collections = createLocalStorageCollectionStore();

<FrogBandGame
  settings={{ level }}
  seed={seed}
  title="Frog Band"
  game="frog-band"
  player={{ id: 'player-1', name: 'Ada' }}
  resultStore={store}
  collectionStore={collections}
  samples={{ baseUrl: 'https://your-host/soundfonts/FluidR3_GM/' }}
  onMemberCollected={(member, isNew) => isNew && console.log(`${member.part} joins the band`)}
  onLevelChange={(level) => setLevel(level)}
  onAnother={() => setSeed(newSeed())}
/>
```

| Prop | Type | Description |
|---|---|---|
| `settings` | `Partial<BandSettings>` | `level` (1–5) sets the tempo, the windows, the rhythms, the time signatures and the songs; `songs` how many (default 3); `tempo` and `meters` override the level's |
| `seed` | `number` | Deals the same show again for the same seed |
| `sounds` | `boolean` | Sound on (default `true`); the HUD's mute button silences it as the show goes on |
| `collectionStore` | `CollectionStore` | Where the band is kept, per `player` |
| `onMemberCollected` | `(member: BandMember, isNew: boolean) => void` | A finished show brought a player into the band |
| `bandBook` | `boolean` | Show the band book (default: `true`) |
| `onBandCompleted` | `(summary: DeckSummary) => void` | The show ended: the last song played, or the crowd went home |
| `onAnother` | `() => void` | The End screen's **New show** button |
| `onError` | `(error: Error) => void` | Settings the band cannot play (the level's own show is played instead), a sample that could not be fetched, a store that failed |
| `labels` | `Partial<FrogBandLabels>` | The band's words (`defaultFrogBandLabels`, `mergeFrogBandLabels`): the board, the pops, the End screen, the players' names |

`BandBook` takes `open`, `onClose`, `collection` (a `Collection`, or `null`), `highlight` (a member's id to pick out, `band:bass`) and `labels`. `frogBandInstructions` is its How to play.

## BalloonRideGame

Steer the balloon with your ears. The owl flies a hot-air balloon over the Key Meadow — the bandstand it takes off beside, hedgerows, the beehive, a pond, an orchard, a windmill — through twelve cloud gates to the meadow fair, where it lands by the big wheel. Each gate is a bank of cloud with an opening for each answer, a picture on each, and asks one listening question; its sound plays as it drifts in (the ear button plays it again), and the steering bar along the bottom has a big picture button for each opening — the same picture:

| Question | How you steer |
|---|---|
| Higher or lower (or the same) | Rise or sink through the right opening, or fly straight on |
| Loud or soft | A big burner flame up to the top opening, or a little one down to the low one |
| Long or short | The burner itself: hold it for a long note, tap it for a short one |
| Fast or slow | Ride the gust, or drift under the rainbow bridge |
| Step or leap | A small lift or a big one |
| Same or different | Two numbered birds sing, each lit while it sings; fly between them if they sang the same song |
| Major or minor | Fly into the sunshine, or under the rain cloud |

The buttons wake once the sound has played, and nothing shows the answer while it plays. Steering through the right opening catches a star — it flies up to the points with a chime — and the opening glows green. A wrong opening puffs shut: the balloon bumps it and wobbles, the star drifts away, the sound plays again with the right opening lit, and the balloon flies on through that one; there is no failing. Keys steer too: the arrows (up for the top opening, down for the bottom, right for straight on), the numbers, Space or Enter held for the burner, and R to hear the gate again. The question is read aloud only when its speaker is tapped. The world moves on a calm beat as it slides by, the far hills slower than the meadow.

The level (`settings.level`) sets the questions and how close their sounds are together (`balloonLevelSettings` from `@hiyve/music-games`): higher or lower and loud or soft, far apart, at level 1; fast or slow and long or short at 2; step or leap at 3; the same or different at 4; major or minor at 5 — never too close to tell apart (two notes a whole step apart or more, a 3rd once "the same" is an answer). A flight takes two to four minutes. The Ready screen says the goal, offers the level pills when `onLevelChange` is given and the skies to fly in, and has a big **Take off**; the End screen says "You landed at the fair!", the stars and their word, the gates' points, the **Stars caught** bonus on its own line, the total and the best, with **Play again** and **New flight** (`onAnother`); the fanfare and confetti come as it lands.

**Skies.** Every player flies the day sky; landing with two stars or more wins the next of dawn, sunset and night ("New sky to fly in" on the End screen) — dawn at any level, sunset from level 2, night from level 3, and the Ready and End screens say what wins the next one ("Land with 2 stars at level 2 or higher to win the Sunset sky.") — kept per `player` in `collectionStore` as the player's skies, and chosen on the Ready screen.

```tsx
import { createLocalStorageCollectionStore } from '@hiyve/music-games';
import { BalloonRideGame } from '@hiyve/react-music-games';

const collections = createLocalStorageCollectionStore();

<BalloonRideGame
  settings={{ level }}
  seed={seed}
  title="Balloon Ride"
  game="balloon-ride"
  player={{ id: 'player-1', name: 'Ada' }}
  resultStore={store}
  collectionStore={collections}
  onSkyCollected={(sky, isNew) => isNew && console.log(`New sky: ${sky}`)}
  onLevelChange={(level) => setLevel(level)}
  onAnother={() => setSeed(newSeed())}
/>
```

| Prop | Type | Description |
|---|---|---|
| `settings` | `Partial<BalloonSettings>` | `level` (1–5) sets the questions, how close their sounds are and the gates; `gates`, `questions` and `listen` change them |
| `seed` | `number` | Makes the same flight again for the same seed |
| `sky` | `BalloonSky` | The sky to fly in (default `'day'`) |
| `onSkyChange` | `(sky: BalloonSky) => void` | A sky was chosen on the Ready screen |
| `sounds` | `boolean` | The burner, the stars and the bumps (default `true`); the gates' sounds always play — they are the questions — unless the HUD's mute button is on |
| `collectionStore` | `CollectionStore` | Where the skies won are kept, per `player` |
| `onSkyCollected` | `(sky: BalloonSky, isNew: boolean) => void` | A landing won a sky |
| `onFlightCompleted` | `(summary: BalloonSummary) => void` | The balloon landed at the fair |
| `onAnother` | `() => void` | The End screen's **New flight** button |
| `onError` | `(error: Error) => void` | Settings that cannot be flown (the level's own flight is flown instead), a sample that could not be fetched, a store that failed |
| `labels` | `Partial<BalloonRideLabels>` | The flight's words (`defaultBalloonRideLabels`, `mergeBalloonRideLabels`): the questions, the answers, the steering, the skies, the End screen |

`balloonRideInstructions` is its How to play.

## PotionLabGame

Brew the potions: build chords and scales, note by note. An owl wizard's lab at the top of a tower at dusk — stone walls warmed by the fire, a round window with the moon, shelves of glowing bottles, a spell book on its lectern — with a big bubbling cauldron over the fire, and an arched hatch where forest customers (a hedgehog, a rabbit, a squirrel, a mouse, a badger, a raccoon) come with their orders. A session is six orders; three customers wait at once, each with an order ticket under the hatch, and the player picks which to brew.

- **Brewing is the music.** The order says what to brew — a chord by its root and quality ("C major chord"), by its symbol ("Chord Am"), as the tonic chord of a key, or as chord I, IV or V of a key; a scale up from its tonic (major, or harmonic minor); the sharps or flats of a key's signature; or the keynote of the minor key that shares a major key's signature. Each note is tapped on the keys (a keyboard picture with every white key named, at every level: theory for any instrument, no fingering — the order names the chord, scale or key, never its notes) or, at the higher levels, placed on the staff — treble or bass, under the key's signature — and drops into the cauldron as a crystal with its name on it, sounding and lighting its key (or its note on the staff) and its crystal as it goes in.
- **A wrong note** fizzes warm red and the crystal pops back out with a dull plop; the recipe pinned over the cauldron shows a hint in music words ("A major chord needs a major 3rd above the root: 4 half steps up", "Sharps come in the order F, C, G, D, A, E, B") and the tries left. After the level's tries the right brew is shown — its crystals in their places, its notes named on the recipe — and played.
- **A potion brewed right** plays — a chord's notes one by one and then together, or the scale up — every note lighting its key, its note and its crystal as it sounds; the cauldron flares, the crystals turn green, and the bottle is handed to the customer, who cheers.
- **Taste tests** ask by ear: "Taste this potion: is it major or minor?" The potion is heard (and can be tasted again), and the player taps the sun for major or the rain cloud for minor — the listening cards' own pictures. Nothing lights while it plays.
- **Rare potions** come sealed in gold: harder orders (from the next level up), worth a bonus — the **Rare potions** line on the End screen — and their customer goes home after a few brews if not served. Taking one is the choice and the risk.

Potions' colours are there for charm only: major or minor is shown by the sun and the rain cloud and by words, never by a colour. Gold is the thing to press (the tickets while an order is chosen) and the rare seal; green is right; warm red is wrong; sky blue is a note sounding — its key, its crystal and its note on the staff. From level 3 a **candle** on the lectern burns down across the session — a gentle clock in the HUD that burns only while the player can act (not while a potion plays and is handed over, nor while How to play or the book is open or the page is hidden); when it burns out the customers waiting go home, and a potion already on the fire can still be finished. **Stars** come from how well the orders went (a wrong note counts against an order). Every kind of potion brewed right for the first time goes on a shelf of the player's **potion book** — chord potions, scale potions, key signature potions, relative minor potions and the two tasted by ear, 39 in all — kept per `player` in `collectionStore`; the book opens from the Ready and End screens, and `PotionBook` shows it on its own.

What is brewed at each level (`potionLevelSettings` from `@hiyve/music-games`): major chords on C, F and G and tasting major or minor (level 1); major and minor chords on C to A and the tonic chord of a key (2); the scales of C, G and F major and their sharp or flat (3); D, B♭ and A major, the harmonic minors of A, E and D, chord symbols placed on the staff, and I, IV and V in a key (4); keys of up to three sharps or flats, relative minors, and I, IV and V placed on the treble and bass staves (5). `settings.topic` keeps a session to chords (`'chords'`) or to keys and scales (`'keys'`). A session takes three to five minutes.

On a phone the hatch runs across the top, the order on the fire replaces the tickets, and the keys sit in the case along the bottom, each at least 44 pixels wide — scrolling sideways in their own strip when a scale needs more than fit. The Ready screen says the goal, offers the level pills when `onLevelChange` is given and has a big **Open the lab**; the End screen says "Every order brewed!" (or "The candle burned out!" and how many orders were brewed), the stars and their word, the orders' points, the rare potions' bonus, the total and the best, the potions new to the book, with **Play again** and **New orders** (`onAnother`). Results are stamped with the session's deck, so they keep and list like any deck, and keep every brew as played — the keys tapped, right and wrong — in `extra.potion.brews`.

```tsx
import { createLocalStorageCollectionStore } from '@hiyve/music-games';
import { PotionLabGame } from '@hiyve/react-music-games';

const collections = createLocalStorageCollectionStore();

<PotionLabGame
  settings={{ level }}
  seed={seed}
  title="Potion Lab"
  game="potion-lab"
  player={{ id: 'player-1', name: 'Ada' }}
  resultStore={store}
  collectionStore={collections}
  samples={{ baseUrl: 'https://your-host/soundfonts/FluidR3_GM/' }}
  onPotionCollected={(bottle, isNew) => isNew && console.log(`New potion: ${bottle.id}`)}
  onLevelChange={(level) => setLevel(level)}
  onAnother={() => setSeed(newSeed())}
/>
```

| Prop | Type | Description |
|---|---|---|
| `settings` | `Partial<PotionSettings>` | `level` (1–5) sets what is brewed, the tries and the candle; `topic` (`'chords'` or `'keys'`), `orders`, `rareOrders`, `tries`, `candleSeconds` and `recipes` change them |
| `seed` | `number` | Deals the same orders again for the same seed |
| `sounds` | `boolean` | Sound on (default `true`); the HUD's mute button silences it as the session goes on |
| `collectionStore` | `CollectionStore` | Where the potion book is kept, per `player` |
| `onPotionCollected` | `(bottle: PotionBottle, isNew: boolean) => void` | A potion brewed right went into the potion book |
| `potionBook` | `boolean` | Show the potion book (default: `true`) |
| `onLabCompleted` | `(summary: DeckSummary) => void` | The lab closed: every order brewed, or the candle burned out |
| `onAnother` | `() => void` | The End screen's **New orders** button |
| `onError` | `(error: Error) => void` | Settings that cannot be dealt (the level's own session is dealt instead), a store that failed |
| `labels` | `Partial<PotionLabLabels>` | The lab's words (`defaultPotionLabLabels`, `mergePotionLabLabels`): the tickets, the recipes, the hints, the End screen, the potion book |

`PotionBook` takes `open`, `onClose`, `collection` (a `Collection`, or `null`), `highlight` (bottles to pick out, by id) and `labels`. `potionLabInstructions` is its How to play.

## GameShell: a game of your own

The games are built in one frame, exported so a game of your own looks and behaves the same. `GameShell` lays it out from the frame's own size, not the window's: on a phone (narrower than 700 pixels) the world fills the frame and the card rises from the bottom in a sheet; on a tablet or a desktop the card sits in a panel beside the world.

| Prop | Description |
|---|---|
| `world` | What is behind everything — sky, hills, water — filling the frame (or a function told the layout) |
| `look` | `'night'`, `'day'`, `'pond'`, `'castle'` (`gameLooks`), or a `GameLook` of your own colours |
| `hud` | The HUD row: a `GameHud` |
| `stage` | The play area: a node, or a function told the layout and `insetBottom`, the pixels the sheet covers, so a piece can be kept above it |
| `panel` | The card: beside the stage, or in the sheet on a phone (or a function told the layout) |
| `sheet` | `'up'` for a question, `'down'` while the piece moves (showing `peek`), `'hidden'` |
| `peek` | A short bar over the bottom of the world while the sheet is down |
| `overlay` | The Ready or End screen, over the world |
| `celebrate` | Confetti over the frame |
| `onLayout` | The layout (`GameShellLayout`) was worked out or changed |
| `children` | Anything that should know the frame's layout and look — `GameHowTo`, say |

- `soundingColors` — the sky blue the games light whatever is sounding in (`light` on a light ground, `dark` on a dark one): use it in a game of your own and keep gold for the one thing to press.
- `GameHud` — one glass row: the mascot's medallion and the `title` (with `subtitle` on a wide screen), the game's own `progress` chip and `extra` chips (a `HudChip`: a picture and a few words), points and stars (`score`), a streak flame from two right in a row (`streak`), and buttons for sound (`muted`, `onMutedChange`), the `tip` and How to play (`onHelp`). On a phone it stays one row under 56 pixels with 44-pixel buttons: the title is left to the Ready screen and the tip moves into How to play.
- `GameReady` — the Ready screen (its big button takes the focus as it opens over the game, unless something outside the game holds it): `title`, the `goal` in one sentence, level pills when `onLevelChange` is given (`level`, `levels`), a choice of the game's own under them (`options`: Note Express's way to play), and a big gold Start (`onStart`, `startLabel`), with How to play under it (`onHelp`) and anything of the game's own under that (`extra`: Note Express's wagon book button).
- `GameEnd` — the End screen (its main button takes the focus as it opens; it draws itself tighter in a frame under 860 pixels tall, so the longest one fits, and never grows taller than the frame leaves it — the reward and the points scroll inside it instead, the heading and the buttons always in view): the `headline` in the game's words, a `detail` line, the stars from `score` with a word that matches them, the cards' points, the game's `bonus` (`GameBonus`: a `label`, `points` and a `detail`) on a line of its own, the total, the `best` before this game ("New best!" when beaten), and **Play again** (`onAgain`), a new world (`onAnother` with `anotherLabel`: "New train", "New show", "New flight") and onward (`onContinue`); something won shows under the stars (`reward`: a new wagon for Note Express's wagon book).
- `GameHowTo` — How to play in the game's words: the goal, three steps each with a small picture (`pictures`), a tip, and a speaker button that reads it aloud only when tapped (`speak` for your own recordings).
- `useBestPoints({ resultStore, game, mode, player, finished, total })` — the best total before this game, from the result store (or this visit without one), kept up to date across Play again.
- `fitCamera({ content, view, inset, focus, minScale })` — where to draw a picture (a board) in a box clear of what covers it: fitted, or at `minScale` with `focus` kept in view. `shellLayout(width, height)` is the layout for a frame that size; `useGameShell()` gives the layout and look inside the frame.
- Words: `defaultGameShellLabels` / `mergeGameShellLabels`.
- Types: `GameShellProps`, `GameHudProps`, `HudChipProps`, `GameReadyProps`, `GameEndProps`, `GameHowToProps`, `GameStageView` (what the stage, the world and the panel are told), `GameShellLayout`, `GameLook` and `GameLookName`, `GameBonus`, `GameCamera` / `GameCameraInput`, `UseBestPointsOptions`, and `GameWorldProps` — what every game built in the shell takes besides its own props.

```tsx
import { GameEnd, GameHud, GameReady, GameShell, HudChip } from '@hiyve/react-music-games';

<GameShell
  look="day"
  world={<MySky />}
  hud={<GameHud title="Balloon Ride" mascot="owl" progress={<HudChip>Gate 3 of 12</HudChip>} score={{ points, stars }} streak={streak} muted={muted} onMutedChange={setMuted} onHelp={() => setHelp(true)} />}
  stage={({ insetBottom }) => <MySkyBoard keepAbove={insetBottom} />}
  panel={card && <MyCard card={card} />}
  sheet={moving ? 'down' : 'up'}
  overlay={ready ? <GameReady title="Balloon Ride" goal="Steer through every gate." onStart={start} /> : done ? <GameEnd headline="You landed at the fair!" score={score} bonus={{ label: 'Gates', points: 120 }} best={best} onAgain={again} /> : null}
/>
```

## DeckBoard

The same deck as a board: every card open at once in a grid, as on a printed page, each checked on its own — the moment a choice is made, or with its tick once every note or letter is placed. A right card turns green; a wrong one can be tried again. The score card appears under the board once every card is settled.

```tsx
import { DeckBoard } from '@hiyve/react-music-games';

<DeckBoard
  settings={{ cards: ['Bee', 'Ace', 'Feed', 'Face', 'Bed', 'Bag'].map((word) => ({ kind: 'spellOnStaff', words: [word] })) }}
  seed={seed}
  columns={2}
  cardSx={{ bgcolor: '#FFFBE6' }}
  colors={{ staff: '#FFFBE6' }}
/>
```

It takes the frame props and, as `DeckPlayer` does, `settings`, `seed`, `retryUntilRight` and `maxTries` (working the same, a card of two choices settled by a wrong answer with its right answer shown), `sounds`, `onDeckCompleted`, `onError`, `names`, `theoryNames`, `colors`, `labels`, `scoreLabels` and `sx` (the grid). Its score card's buttons are **Play again** (a fresh board) and **New deck** (`onAnother`). Its own props:

| Prop | Type | Description |
|---|---|---|
| `columns` | `number` | Cards across (default 2) |
| `prompt` | `'above' \| 'below' \| 'none'` | Where each card's prompt goes (default `'below'`: a word sits under its staff) |
| `dense` | `boolean` | Smaller cards, so a whole board fits one screen (default: `true` from three columns) |
| `showScoreCard` | `boolean` | The score card under the board once every card is settled (default `true`) |
| `onCardSettled` | `(round, index) => void` | A card was settled |
| `cardSx` | `SxProps<Theme>` | Each card's frame |

The board's artwork, title and background are yours: the board is only the grid of cards.

## useDeck

The deck in a component of your own:

```tsx
const deck = useDeck({ settings, seed, keepOpenWhenWrong: true });
// deck.round, deck.index, deck.total, deck.answer(answer) → boolean, deck.next(), deck.finish(), deck.restart(), deck.finished, deck.summary, deck.record
```

## The kinds of card

Thirty-three kinds of card, mixed freely in one deck, board or trail, each at any of five levels (`{ kind: 'noteNameId', level: 3 }`, or a `level` on the whole deck or trail). Four are arcade mechanics that work with any content (`DisplayView` draws whatever a fact shows):

| Arcade | What happens |
|---|---|
| Fish catch (`catch`) | Fish swim across a pond in lanes, each with a note, symbol, value, key or letter; tap the one asked for, or every one of a kind ("Catch every C", the letter drawn large). Caught by ear (`byEar`), the speaker plays the note to match, a fish sings when tapped (glowing while it sings) and a second tap catches it; these are the card's own sounds, like a listening card's, so they play when asked for even with the game's sounds off. A right fish counts the moment it is tapped, then leaps away |
| Lily pad hop (`hop`) | Pads drift on a pond; hop them in order — a word's notes, a scale, values short to long, the letters from C — and the frog jumps; a wrong pad splashes |
| Memory match (`memoryMatch`) | Cards face down; turn two, a thing and its name stay up |
| Sort (`order`) | Drag tiles into places, shortest to longest, lowest to highest, or the letters in order |

These judge each move live: a wrong fish, pad or pair counts as a try at once and the round settles the moment it is complete, with no button. Every card view takes `onEffect` for the moments worth a sound (`pop`, `hop`, `splash`, `flip`, `match`), which the players route to `useGameSounds` (`playPop`, `playSplash`). The rest:

| On the staff | On the keyboard | Symbols and rhythm | Words |
|---|---|---|---|
| Spell a word by placing notes (`spellOnStaff`) | Tap the key for a note on the staff (`keyboardNoteId`) | Name the symbol (`symbolId`) | Decode symbols into letters (`symbolSpelling`) |
| Name the note (`noteNameId`) | Tap the keys of a letter (`keyboardFind`) | Add or take away note values (`rhythmMath`) | Spell a word marked on the keys (`keyboardSpelling`) |
| Name the interval (`intervalId`) | Build a chord (`chordBuild`) | Fill the bar (`rhythmFill`) | What a term means (`termId`) |
| Build an interval (`intervalBuild`) | | Which time signature, what its bottom number means, which beat is strong (`timeSignatureId`) | What comes next on the alphabet (`letterStep`) |
| Step, skip, repeat or leap (`stepSkip`) | | | |
| Line note or space note (`lineOrSpace`) | | | |
| What kind of chord (`chordQualityId`) | | | |
| Name the key signature (`keySignatureId`) | | | |
| Name the scale (`scaleId`) | | Where the bar lines go (`barLines`) | |
| Which note of the scale (`scaleDegree`) — or find it on the keys or the staff | | Tie or slur (`tieOrSlur`) | |
| Chord names: C, Am, G7, or I, IV, V in a key (`chordName`) | | | |

Two more are played by ear, with no reading and no instrument, so a beginner can play them before reading anything on the staff:

| By ear | What happens |
|---|---|
| What did you hear? (`listen`) | A big **Listen** button plays a sound — two notes, a little tune, one long or short note — and the answers are big pictures with a word under each: an arrow up or down, a small or big speaker, bars rising or falling, bouncing dots or a flowing line, a tortoise or a hare, a speed dial, a short or long bar, a note with a dot for each beat, stairs stepped or leapt |
| Tap it back (`beatTap`) | A big drum. Hear a bar — a bar of dots, a big dot to tap and a small one a rest, or a rhythm in notes — on a woodblock over the metronome, after a count-in, each dot or note lighting as it sounds; then a count-in of the player's own, "Your turn!", and tap it back on the beat while the metronome keeps ticking, the beat it is on lit. Tap with a finger, a mouse, Space or Enter. A miss shows which taps came early or late and **Try again** plays it all again. A rhythm in 6/8 shows its time signature and is counted in on its two big beats |

The listening card also asks whether two tunes were **the same or different** — a **1** and a **2** light in turn as each is heard, the answers two matching bars and two bars that do not match — and whether a chord, a broken chord, a 3rd or a scale was **major or minor**, a bright sun or a rain cloud.

Three more work with whole songs, and two of them are made up, judged by rules rather than one right answer:

| Whole songs | What happens |
|---|---|
| Read a song (`tuneQuestions`) | A short tune, drawn once with its key, time and signs, and three or four questions under it asked in turn — its key, the beats in a bar, what the circled sign means (a change of speed among them: rit., rall., accel. or a tempo, written over the bar it changes), which bar has the highest note (tap the bar; the bars are numbered), the note under the arrow, and with D.C. al Fine (Fine over a final bar line, D.C. al Fine under the end) the bar played after the D.C. and the bar the music ends in. A right answer ticks the question off; a wrong one is a try. **Hear it** plays the tune as written, each note lit as it sounds — slower at a rit., back at a tempo, and round again at a D.C. to Fine, each bar lit as well — and a speaker reads the question |
| Answer the rhythm (`rhythmAnswer`) | Hear and see a one-bar rhythm, then make up an answer: drag note values into the answer bar under the question (or tap them), and tap a note to take it out. The question asks only to fill the bar; what else the answer must do — end on a long note, use a note of the question, not copy it — is listed under it, each ticked once it holds (none before a note is placed), and read aloud after the question. **Hear both** plays the question and the answer, each value lit, and they play by themselves once checked |
| Finish the song (`finishTune`) | A tune with its last one or two notes drawn faintly: tap a line or space (or drag, or use the arrow keys) to put each one, so it ends on the tonic by step or skip. The rules are listed and ticked as they hold; the whole tune, ending and all, plays once checked |

## The cards on their own

A card view lays out by the box of the component around it (see *Sizing* above); used on its own, outside any of them, it keeps to the window.

`GameCardView` shows any card with its answer so far. One kind each: `SpellOnStaffCardView`, `IntervalIdCardView`, `RhythmMathCardView`, `SymbolSpellingCardView`, `ChoiceStaffCardView` (notes, chords, keys, scales and motions read from the staff), `LineOrSpaceCardView`, `IntervalBuildCardView`, `KeyboardNoteIdCardView`, `KeyboardFindCardView`, `ChordBuildCardView`, `KeyboardSpellingCardView`, `SymbolIdCardView`, `RhythmFillCardView`, `TimeSignatureIdCardView`, `TermIdCardView`, `LetterStepCardView`, `ListenCardView`, `BeatTapCardView`, `TieOrSlurCardView`, `BarLinesCardView`, `ScaleDegreeCardView`, `ChordNameCardView`, `TuneQuestionsCardView`, `RhythmAnswerCardView` and `FinishTuneCardView`, and the arcade kinds' `CatchCardView`, `HopCardView` (with a `mascot` to hop), `MemoryMatchCardView` and `OrderCardView`. All take `card`, `answer`, `onAnswerChange`, `feedback` (`'open' | 'right' | 'wrong'`), `prompt` (where the prompt goes: `'above'`, the default, `'below'` or `'none'`), `dense` (smaller type, glyphs and staff, for several cards on one screen), `disabled`, `explain` (settled wrong, work the answer out in the picture — the count from a landmark, the beats, the last sharp; default `true`), `onNotePlayed`, `onMiss` (a wrong move on a card judged move by move), `onEffect`, `autoPlay`, `samples`, `names`, `theoryNames`, `colors`, `labels`, `sx`. `cardPrompt(card, labels, theoryNames)` gives the heading a card is asked under, as its view would show it — for a host that shows the heading itself and passes `prompt="none"`. Interval cards asked by number are named by `defaultIntervalNumberNames` (2nd, 3rd … Octave); a 2nd asked as a half or whole step offers "Half step" and "Whole step" (`halfStep`, `wholeStep`), and is explained by the key between its notes, the two notes named. Asked melodic or harmonic (`intervalShape`), it offers "Melodic" and "Harmonic" (`melodic`, `harmonic`), each with a little picture, and once answered plays the notes as written — one after the other, or together — each lit as it sounds, with **Hear it**. A note asked in a printed bar (`barRule`) is pointed at by an arrow (`nameNoteInBar`), explained by the sign earlier in the bar ("The sharp earlier in the bar still counts: it’s F♯.": `explainBarRuleSharp`, `explainBarRuleFlat`, `explainBarRuleNatural`), and the bar is heard once answered. A find-the-key card asked a half step from its note says so ("Tap the key a half step up from this note.", `findKeyHalfStepUp`, `findKeyHalfStepDown`), and is explained from the note's key to the very next one. A note read with a sharp, flat or natural, or under a key signature, is explained by its letter counted to, then what the sign does (`explainSharpMakes` … `explainKeySignatureNatural`). A find-every-key card names the keys as the card says — every white key, only the Cs, or none, the default — so a player still learning the letters can be shown them (`showNames` in its settings). A time-signature card asked what the bottom number means draws the signature large with that figure ringed, each answer a note drawn and named (`bottomNumber`), and once settled the note beside the figure (explained: "The bottom 4 means each beat is a quarter note.", "The bottom 8 means the music is counted in eighth notes."); asked the strong beat, it draws one bar a note a beat, each beat a button with its count, heard as it opens and from **Hear it** with each beat lit as it sounds and beat 1 the loudest (`strongBeat`, `mediumStrongBeat`, `beatNumber`), and settled wrong names how strong each beat is (`strongWord`, `mediumWord`, `weakWord`). A note placed on a staff (spelling a word, building an interval, finding a degree) sounds through `onNotePlayed` and is lit while it sounds; on a `dense` card it stays plain.

`LetterStepCardView` asks "What letter comes after G?", "What letter comes before D?" or "Count 2 letters up from F. Which letter is it?" (`letterAfter`, `letterBefore`, `letterUp`, `letterDown`) over the letter in a tile, an arrow the way to go, a small box for each letter passed and a tile with a question mark, which shows the letter landed on once settled; a wrong answer is counted out letter by letter, with "after G, start again at A" when the count goes round (`explainLetterWrapUp`, `explainLetterWrapDown`). Its props are `LetterStepCardViewProps`.

`TieOrSlurCardView` draws the notes and their curve large over two picture buttons, a tie and a slur (`tie`, `slur` labels; the question is `tieOrSlur`); once answered the notes play — a tie as one long sound, a slur smoothly — each lit as it sounds, and **Hear it** (`hearIt`, `stopIt`) plays them again. `BarLinesCardView` draws the line of values on one line, a faint mark in every gap: tap a gap (or press Enter on it) to put a bar line there or take it away, then Check; a long line wraps onto more lines on a phone, never where a bar line goes. A wrong go says which bar is out (`barLinesBar`), and once settled the line is heard with the first beat of every bar stressed. `ScaleDegreeCardView` asks "In G major, is this note the tonic or the dominant?" (`scaleDegreeTonicDominant`, `scaleDegreeName`), the numbers 1 and 5 named under them (`tonic`, `dominant`), or "Tap the tonic of D major on the keyboard." (`scaleDegreeFindKey`; on the staff `scaleDegreeFindStaff`, a placed note taking the key signature's sharp or flat). Asked by number alone, it names no key, tonic or dominant: "In the scale from C, which number is this note?" or "Tap note 5 of the scale from C." (`scaleDegreeNumber`, `scaleDegreeNumberFindKey`, `scaleDegreeNumberFindStaff`), the numbers alone on its buttons. `ChordNameCardView` asks "Which chord is this?" or "In G major, which chord is this?" (`chordSymbol`, `chordNumeral`) and plays the chord once answered, each note lit. `TuneQuestionsCardView` numbers its questions and ticks each off (`tuneQuestionOf`, `tuneKey` … `tuneDegree`, `tuneDaCapo`, `tuneFine`, `barNumber`) and takes `onMiss` for a wrong answer. `ChoiceStaffCardView` asks a chord's root as "Which note is the root of this chord?" (`nameChordRoot`), the chord's notes by name on its buttons; settled wrong, the root is lit and every note named. `RhythmAnswerCardView` (`rhythmAnswer`, `questionBar`, `answerBar`, `hearQuestion`, `hearBoth`, `clear`, `beatsToGo`) and `FinishTuneCardView` (`finishTune`, `finishTuneTwo`, `finishTonic`, `finishStepSkip`, `finishStepHome`) say after a wrong check which rule the answer breaks, and after a settled wrong one give one answer that works (`oneWay`).

`LineOrSpaceCardView` draws its one note large, with two big picture buttons under it — a small staff with a line through a note, and one with a note between two lines — each with its word (`line`, `space` labels) under it, line always first; the question is `lineOrSpace` ("Is this note on a line or in a space?"). Once answered the note turns the colour of a right answer and the right button is shown. A name-the-note card asks for a letter (`nameNote`, "What letter is this note?"), for a note when a choice has a sharp or a flat (`nameNoteAltered`, "Which note is this?"), and under a key signature draws the signature and the note plainly after it, under `nameNoteInKey` ("Which note is this? Check the key signature."); a find-the-key card writes a note's sharp or flat before it. A catch card of letters words its prompt `catchLetter` / `catchEveryLetter` ("Catch the {letter}", "Catch every {letter}"), the letter drawn large where `{letter}` stands — on its own and on Note Express's signboard, whose labels (`NoteExpressLabels`) have the same two.

Every card's question says what to do and to what, in plain words: "Tap every C on the keyboard.", "Drag the note that fills the bar.", "Is the second note higher or lower than the first?". A step-or-skip card asks only the motions it offers — "Do the notes step or skip?", "Do the notes repeat, step or skip?" (`stepSkip`, `{choices}` replaced, the last after `or`, capitalised only where it opens the question) — and each answer button carries a picture as well as its word: stairs stayed on, stepped, skipped or leapt, the same pictures a listening card answers with. An add-the-values card asks for what it is answered with: "Drag the note they make into the box." (`rhythmMath`), the rest when rests are added (`rhythmMathRest`), and what is left when one is taken away (`rhythmMathLeft`, `rhythmMathRestLeft`). A complete-the-measure card asks for "the note or rest" when a rest is among its tiles (`fillBar`, `fillBarRest`); a name-the-symbol card calls it a note or a rest when every choice is one (`nameSymbolNote`, `nameSymbolRest`), a sign otherwise (`nameSymbol`); an interval to build reads "Drag the second note a 3rd above the first." (`buildInterval`), or an octave (`buildOctave`). A key signature card asks "Which key does this key signature show?" (`nameKey`). A name-the-note card draws a natural sign before a note the card writes with one (cancelling the key signature's sharp or flat). A time signature card keeps its bar on one line on a phone, its final bar line with it; bars too long for one line go one under another. Sharps and flats in an answer or a heading ("B♭ major", "Tap the keys that make G♯ major.") are drawn as music signs, tight against their letters, while a screen reader still reads "B♭". On fish, pads and tiles a key is drawn on one octave of keys, marked with a dot and otherwise plain — a key is coloured only while it sounds or once it is chosen — with middle C left plain too; on a fish the keys sit on a card of their own and the fish swims a little larger. A lily pad draws a staff on a clear panel, clear of the pad's notch, a note value large, and on a phone the pond grows to hold its pads two to a row.

## Widgets

### InteractiveStaff

A staff with notes to place: tap a line or space, drag a note up or down, or move it with the arrow keys. An empty slot shows a faint note on the middle line to pick up. A column with a sharp or flat, or with a long label, is drawn wider, so signs and words never touch the note beside them. The sharps and flats of notes sounded together (`stack`) stand in columns as they are engraved — the top one nearest the notes, the next further left where they would touch — so a chord's signs a third apart never merge into one.

| Prop | Type | Description |
|---|---|---|
| `clef` | `Clef` | treble, bass, alto or tenor |
| `slots` | `StaffSlot[]` | One note each: `position` (see `staffPosition`) or `null`, `status` (`'right'`, `'wrong'`, or `'sounding'` — drawn in the sounding colour, glowing, while its note is heard), `label`, `alter`, `natural` (a natural sign before it, to cancel a key signature), `filled`, `stack`, `locked` |
| `keySignature` | `number` | Sharps (positive) or flats (negative) after the clef |
| `keySignatureMarks` | `number[]` | Sharps or flats of the signature to pick out, counted from the first written (0) |
| `count` | `{ from, to, labels?, marked? }` | A count written up (or down) the staff in a column after the notes: a small label at every line and space from one position to another (`from`, `to`) — the letters there unless `labels` are given — the last in the right colour (or those `marked`), to count from a landmark to a note |
| `markPosition` | `number` | The line a position sits on, or the space it sits in, picked out in the right colour |
| `ties` | `number[]` | Columns whose note is tied to the same note in the next column: the curve on the side away from the stems |
| `slurs` | `[number, number][]` | Slurs, each the columns of its first and last note: a curve on the side away from the stems |
| `lowestPosition`, `highestPosition` | `number` | Where a note can go (default −2 to 10) |
| `onSlotPlaced` | `(slot, position) => void` | A note was put somewhere; without it the staff is a picture |
| `onNotePlaced` | `(midi) => void` | The note placed, to sound it |
| `columnWidth` | `number` | How wide a column of notes is, in staff spaces (default 3.4): narrower for a long run such as a scale, so it is drawn larger on a short line |
| `minColumns` | `number` | Room for at least this many columns, so a staff with one note is no wider than one with three (default 1) |
| `maxHeight` | `number \| string` | The most height the staff takes, as CSS; it shrinks to fit, keeping its shape |
| `readOnly`, `spacing`, `showLabels`, `colors`, `labels`, `sx` | | |

`keySignaturePositions(clef, fifths)` gives the staff positions of a key signature's sharps or flats, in the order they are written.

### Mascot, Celebration and ScorePop

`<Mascot name="fox" mood="happy" size={96} />` draws one of four flat-vector friends with a mood (`idle`, `happy`, `oops`, `thinking`, `celebrate`). `<Celebration active />` bursts confetti over its positioned parent. `<ScorePop points={points} />` floats the points just won ("+120") up and away over its positioned parent each time `points` grows.

### PianoKeyboard

A piano keyboard drawn as SVG, two octaves from middle C unless told otherwise: `lowestMidi`, `highestMidi`, `selected` (keys lit as chosen), `sounding` (keys lit in the sounding colour while they sound, over a choice), `marks` (dots with a label; a black key's label sits in a badge as large as a white key's letter; marks on the same key share it, their labels written together, "1·3"), `onKeyTap`, `showNames` (`'all' | 'c' | 'none'`), `status`, `readOnly`, `minKeyWidth`, `markMiddleC` ("middle C" written on its key in words, for a player finding it among several octaves; off by default), `focusMidi` (the key a keyboard that scrolls starts scrolled to; default 60, middle C), `colors`, `labels` (`PianoKeyboardLabels`), `sx`. Only lit keys are ever coloured, so a colour always means "this key": a key chosen is filled solid in the chosen colour (`GameColors.tile`, its letter in white), a key sounding in the sounding colour, and a mark is a plain ink dot unless it says right or wrong. Without `onKeyTap` it is a picture. On a narrow screen it is drawn in rows of whole octaves — the lowest at the bottom and the highest on top, as notes climb a staff — with shorter keys, so two or three octaves stay on a phone's screen with a staff above them and tiles below, every key in sight and at least `minKeyWidth` wide (a keyboard that is only a picture takes a little less of the screen); it scrolls sideways only when one octave cannot fit.

### DragDropArea, DragTile, DropZone

Tiles dragged into boxes, or tapped and then the box tapped — for a finger, a mouse, a keyboard or a screen reader alike. `DragDropArea` takes `onDrop(tileId, zoneId)` and `onDropOutside(tileId)`; a `DragTile` has an `id` and a `label`; a `DropZone` has an `id`, a `label`, a `status` and whatever is in it.

### MusicGlyph

A symbol of notation drawn as SVG: `<MusicGlyph symbol="quarterRest" size={48} />`. Every `MusicSymbol` of `@hiyve/music-games` is drawn, with a name for a screen reader: common time as a C ("Common time"), `fourFourTime` as 4 over 4 ("4/4 time"), cut time as a C with a line through it.

### DisplayView

One thing shown small — a note on a staff, a symbol, a note value, a piano key, a key signature, or words: the face of a fish, a pad, a memory card or a tile. `<DisplayView display={display} size="large" />` takes a `Display` from `@hiyve/music-games`, a `size` (`'small'`, `'medium'` or `'large'`), an `ink`, `colors`, `labels`, `glyphLabels` and `sx`. `displayText(display, glyphLabels, beatsLabel, beatLabel?)` says what a display shows, in words for a screen reader.

### ChoiceButtons and DeckScoreCard

The answers as big buttons, coloured once settled — the choice made and the right answer; with `wrong`, a choice is marked wrong while the right answer stays hidden, for a try with another go to come. And the score at the end, its word matching its stars, with **Play again** (`onAgain`), **New deck** (`onAnother`, with a shuffle) and **Continue** (`onContinue`, with a forward arrow) as each is given: the main button is filled and the others outlined — **Continue** when it is there, unless `primary` says `'again'`. `extraActions` adds buttons of your own after those, in the same row; `actions` replaces the row outright. `deckPraise(summary, labels)` is the score card's word for a deck, matching its stars (three stars is never "Nearly there"), and `deckTone(summary, colors)` its colour — `good` from 90% right, `fair` from 60%, `poor` below — for a score card of your own.

`ListenCardView` plays its sound as it opens (`autoPlay`, default `true`) — once the browser lets sound start; otherwise its big **Listen** button waits to be pressed — and every time **Listen** (then **Listen again**) is pressed. The button sounds even with a game's sounds off: pressing it asks for the sound. The answers wake once the sound has been heard, so a guess cannot come first; after a wrong answer the sound plays again as the card opens for another go. Its question follows what it offers ("Is the second note higher or lower than the first?", "Is the second note higher, lower or the same?", "Did it get softer or louder?", "How fast was it played?", "Count the beats. Which note was it?", "Did the notes step or leap?" — `listenMovedChoices` — or "How did the notes move?" when the same note twice is a choice).

`BeatTapCardView` plays its bar as it opens (`autoPlay`) and on **Listen**, then counts the player in ("Get ready…", `tapReady`). The ticks are scheduled on the audio clock, and the taps are timed against when the ticks are heard, the device's output delay included, from the first beat of the player's bar. Taps made while the bar is heard do not count, so tapping along is fine; with no tap at all nothing is handed in and the card says "Tap the drum on the beat!". A go is handed in the moment every tap is in, or once the bar is past. The players pass `autoPlay` as their `sounds` prop says, except `DeckBoard`, whose cards wait for their buttons so a board of them does not play at once.

## useGameSounds

`useGameSounds({ enabled, samples, onError })` gives the sounds the games make: `playNote(midi, durationMs?, gain?)` for a note (it returns a function that stops the note early) — on a small built-in voice, or on recorded piano samples when `samples` names a host laid out like the `midi-js-soundfonts` collection (`{ baseUrl: 'https://cdn.example.com/soundfonts/FluidR3_GM/' }`; the SDK ships none, and the host's licence applies) — and `playRight`, `playWrong`, `playPop`, `playSplash`, `playBoing` (a vine), `playWhoosh` (a whirlpool), `playThud` (a fox hole, a trap), `playRattle` (the die) and `playFanfare` (free again, the finish). `playClick(sound?, atMs?)` sounds a click (`ClickSound`: `'tick'`, `'accent'`, `'wood'` or `'drum'`) now, or at `atMs` on the page's clock (`performance.now()`), scheduled on the audio clock so a row of clicks keeps perfect time; it returns when the click will be heard on that same clock, the device's output delay included, or `null` with sound off. `ready()` starts the sound from a tap and resolves `true` once clicks can be scheduled on time. Every game takes the same `samples` prop and passes it on. Sound starts on the first tap, as browsers require. Switching sound off silences at once even a sound already on its way, and once the component using the hook is gone no sound plays and no new audio is opened.

## Customization

Every label and colour has a default and a merge function, which spreads your overrides over the defaults:

| Default | Merge | For |
|---|---|---|
| `defaultGameLabels` | `mergeGameLabels` | The cards' words (`GameLabels`): every question, nudge and explanation |
| `defaultGameColors` | `mergeGameColors` | The cards' and widgets' colours (`GameColors`) |
| `defaultIntervalNames`, `defaultIntervalNumberNames` | `mergeIntervalNames` | What each interval is called (`IntervalNames`), and by number (2nd, 3rd … Octave) |
| `defaultTheoryNames` | `mergeTheoryNames` | Qualities, scales, modes, motions and terms (`TheoryNames`) |
| `defaultDeckScoreCardLabels` | `mergeDeckScoreCardLabels` | `DeckScoreCard` and the players' score cards |
| `defaultHowToPlayLabels` | `mergeHowToPlayLabels` | `HowToPlayDialog` |
| `defaultScoreBarLabels` | `mergeScoreBarLabels` | `ScoreBar` |
| `defaultResultsTableLabels` | `mergeResultsTableLabels` | `ResultsTable` |
| `defaultGameShellLabels` | `mergeGameShellLabels` | The game shell: the HUD, the Ready and End screens, How to play |
| `defaultTrailLabels`, `forestTrailLabels` | `mergeTrailLabels` | `TrailGame` (`mergeTrailLabels(overrides, 'forest')` starts from the forest's words) |
| `defaultNoteExpressLabels` | `mergeNoteExpressLabels` | `NoteExpressGame` and `WagonBook` |
| `defaultFrogBandLabels` | `mergeFrogBandLabels` | `FrogBandGame` and `BandBook` |
| `defaultBalloonRideLabels` | `mergeBalloonRideLabels` | `BalloonRideGame` |
| `defaultPotionLabLabels` | `mergePotionLabLabels` | `PotionLabGame` and `PotionBook` |
| `defaultGameLobbyLabels` | `mergeGameLobbyLabels` | `GameLobby` |
| `defaultMusicGameLabels` | `mergeMusicGameLabels` | `MusicGame`'s bar |
| `defaultTopicPracticeLabels` | `mergeTopicPracticeLabels` | `TopicPractice` |
| `defaultMusicHubColors` | `mergeMusicHubColors` | The lobby's and Practice's colours (`MusicHubColors`) |
| `defaultPianoKeyboardLabels` | `mergePianoKeyboardLabels` | `PianoKeyboard` |
| `defaultInteractiveStaffLabels` | `mergeInteractiveStaffLabels` | `InteractiveStaff` |
| `defaultMusicGlyphLabels` | `mergeMusicGlyphLabels` | `MusicGlyph`'s names for a screen reader |
| `defaultDragDropLabels` | `mergeDragDropLabels` | `DragDropArea`, `DragTile`, `DropZone` |
| `defaultChoiceButtonsLabels` | `mergeChoiceButtonsLabels` | `ChoiceButtons` |

`keyName(code, names)` writes a key as the cards show it, from a code such as `D:major` ("D major" with `defaultTheoryNames`). The game labels' `or` joins several choices said together ("step or skip", "whole note, half note or quarter note"). The game labels hold the words said after a wrong answer — a nudge per kind of card (`nudgeNoteName` … `nudgeFinishTune`), an explanation per kind (`explainCountUp` … `explainFinishTune`) and the speaker that reads them (`readHint`) — and the words of the listening and tapping cards too: their questions (`listenHigherLower`, `listenHowLoud` …), the word under each picture (`heardHigher` … `heardLeap`), the buttons (`listen`, `listenAgain`, `tapStart`, `tapTryAgain`) and what the drum says (`yourTurn`, `tapsEarly`, `tapsLate`, `tapsCount`, `tapsNone` …). Colours take MUI palette paths (`success.main`) or CSS colours. Each colour means one thing everywhere: gold is the one thing to press now, green is right or done, warm red is wrong, a deep indigo is what a player has chosen, and sky blue is a sound being heard — whatever makes a sound (a key, a note, a tile, a wagon, a lantern, a drum) is lit in it while it sounds and is plain again after. `GameColors.tile` is the chosen colour (default `#4B3BD6`, the same in every game: a host's theme accent tints the chrome, never a choice, a sound, right or wrong). `GameColors.sounding` sets the sounding colour for the cards and widgets: by default the theme's own `palette.sounding.main`, or else `soundingColors` — a `light` and a `dark` version, each a `SoundingColors` (`fill`, the `edge` a note is drawn in, `soft`, `glow`, and the `text` written on the fill), the deep edge on a light staff and the pale one on a dark staff. The listening cards' pictures are drawn in the ink of where they sit and told apart by their shape alone. Artwork and backgrounds are the host's: wrap the player in your own themed container.

### RhythmStaff and TimeSignature

`RhythmStaff` draws bars of note values and rests on a one-line rhythm staff with an engraved time signature, bar lines and a final double bar — the staff the rhythm cards use; `end="bar"` closes it with a plain bar line instead, for music carried on to a staff below, and `captions` writes a small word under each value (and under a gap), bar by bar — a count of beats, say. `TimeSignature` engraves one signature on its own; `mark` rings its top or bottom figure, to point at it. `MusicGlyph` draws any `MusicSymbol` (`staff={false}` leaves out the staff lines behind a rest or clef). A rest, a time signature or a bar line is drawn on a staff of wide spaces that fills its box, so a whole rest hanging from its line and a half rest sitting on its line can be told apart even drawn small.

## Notation glyphs

Clefs, noteheads, rests, flags, accidentals, time signatures, articulations, ornaments and signs are drawn from outlines of the [Bravura](https://github.com/steinbergmedia/bravura) music font by Steinberg Media Technologies GmbH, used under the SIL Open Font License 1.1 (see `LICENSES/OFL-Bravura.txt`). No font file is loaded at runtime.

## Requirements

- Peer dependencies: `react` 18 or 19 and `react-dom` 18 or later, `@mui/material` and `@mui/icons-material` 9, `@emotion/react` and `@emotion/styled` 11 or later, `@hiyve/music-games` and `@hiyve/music-theory` 0.1.
- No provider is required: every component works on its own, inside or outside an MUI `ThemeProvider` (a theme's `palette.sounding` is used when it has one). The one wrapper is `DragDropArea`, which `DragTile` and `DropZone` must be inside.
- `MusicGame`, and `MusicGames` while a game is open, fill their container's height: give the container one.
- The games, the lobby and Practice use the "Fredoka" and "Nunito" fonts when the host page loads them, and fall back to the system sans-serif otherwise. The notation needs no font.
- Recorded instrument samples come from a host the app chooses (`samples`, a `SampleSource` laid out like the `midi-js-soundfonts` collection; the SDK ships none, and that host's licence applies); without it a small built-in voice plays.
- Sound needs Web Audio and a user gesture first; everything else works without it.
- Touch, mouse, pen and keyboard are all supported. No room or sign-in is needed.
