Hiyve Components - v1.0.0
    Preparing search index...

    Module @hiyve/music-games

    @hiyve/music-games — framework-agnostic music games: thirty-three kinds of card at five levels each, made to order from a seed, checked, and kept small to store, and the rules of the games built on them.

    • createCard / checkCard — a card of any kind from its settings (gameKinds, levelPresets), and whether an answer is right
    • startDeck / answerDeck / nextCard / finishDeck / deckSummary — a deck of cards, round by round, seeded so the same deck can be made again
    • deckRecord / restoreDeck — a finished deck kept small, and brought back
    • scoreDeck / resultOf / createResultStore — points and stars, and results kept in any database
    • startTrail — a board game on a trail, its river course generated from a seed
    • Note Express, Frog Band, Balloon Ride, Potion Lab — the rules of each game (express*, band*, balloon*, potion*), with collections of what is won (createCollectionStore)
    • practiceTopics / practiceSet — Practice as data: topics in the order a beginner meets them, the ways to practise each, and sets of eight cards at a level
    • staffPosition / pitchAtPosition — where a note sits on a clef's staff, and the note at a place on it
    import { startDeck, answerDeck, nextCard, deckSummary, repeatCards } from '@hiyve/music-games';

    let deck = startDeck({ cards: [...repeatCards({ kind: 'spellOnStaff' }, 5), ...repeatCards({ kind: 'intervalId' }, 5)] }, { seed: 7 });
    deck = answerDeck(deck, answer, 3200);
    deck = nextCard(deck);

    @hiyve/music-games

    Framework-agnostic music games: thirty-three kinds of card at five levels each — notes to read, place and play, intervals, chords, keys and scales to name and build, note values to add and fill into bars, symbols and terms, sounds to tell apart by ear, beats to tap, whole songs to read and finish — Practice as data (topics in the order a beginner meets them, the ways to practise each, and sets of eight cards at a level), and the rules of the games built on them: a board game on a trail, Note Express, Frog Band, Balloon Ride and Potion Lab. Each card is made to order from a seed, so the same deck can be dealt again; each answer is checked; a finished deck is kept small to store and brought back later, and a game's result goes to any database. No framework, no DOM: the React components are in @hiyve/react-music-games.

    npx @hiyve/cli login
    npm install @hiyve/music-games @hiyve/music-theory

    @hiyve/music-theory is a peer: the pitches, the interval questions and the seeded random source come from it.

    import { startDeck, answerDeck, nextCard, isDeckFinished, deckSummary, deckRecord, repeatCards, newSeed } from '@hiyve/music-games';

    const settings = { cards: [...repeatCards({ kind: 'spellOnStaff' }, 5), ...repeatCards({ kind: 'intervalId' }, 5)] };
    let deck = startDeck(settings, { seed: newSeed() });

    // Each round: show deck.rounds[deck.index].card, take an answer, then
    deck = answerDeck(deck, answer, elapsedMs);
    deck = nextCard(deck);

    if (isDeckFinished(deck)) {
    const summary = deckSummary(deck); // accuracy 0–1, right, first try, missed cards
    const record = deckRecord(deck, settings); // small enough to store; restoreDeck brings it back
    }
    Kind Card Answer Made from
    spellOnStaff A word (letters A–G) to spell by placing one note per letter on a clef's staff; a one-letter "word" asks for one note (Pitch | null)[], one per letter SpellOnStaffSettings: clef, words, any octave, MIDI range
    intervalId Two notes on the staff with the interval to choose, as @hiyve/music-theory asks it — by number ("3") between naturals unless told otherwise, the numbers offered smallest first; asked by number, each number comes up as often as the others, its two notes any the range holds whatever the quality (E–F and B–C as 2nds, minor 6ths and 7ths too); with halfWhole, a 2nd named a half step (m2) or a whole step (M2), for a player who has not met interval quality; with ask: 'shape' (IntervalAsk), whether the two notes are written one after the other or together, a melodic or a harmonic interval (IntervalShape) the choice made: a number, a code (M3), or 'melodic' / 'harmonic' IntervalIdSettings: clef, range, intervals, melodic, accidentals, choices, naturalsOnly, generic, halfWhole, ask
    rhythmMath Two note values to add or take away, with note-value tiles to answer from; two rests make a rest, answered among rests, and a note is never added to a rest the beats (number) RhythmMathSettings: values (notes and rests), operators, tiles offered
    symbolSpelling A word written as symbols from a legend, with letters to spell it back (string | null)[], one per symbol SymbolSpellingSettings: words, legend, extra letters
    noteNameId A note on the staff with its name to choose — or, with keySignatures, a plain note under a key signature, named as the signature makes it; a natural can be written with its sign; with barRule (BarRuleSign), a note in a short printed bar with no sign of its own, after a sharp, a flat or a natural on its letter earlier in the bar, which it keeps (the card's bar) the name chosen ("F♯") NoteNameIdSettings: clef, range, accidentals, choices, keySignatures, alteredShare, spelling, naturalShare, barRule
    chordQualityId A chord on the staff with its quality to choose, in root position, any inversion, or only inverted — or, asked ask: 'root', its root among its own notes the quality (major), or the root's name ('G') ChordQualityIdSettings: clef, range, qualities, inversions (false, true or 'only'), choices, asked, roots, ask
    keySignatureId A key signature with its key to choose the key (D:major) KeySignatureIdSettings: clef, most accidentals, modes, choices
    scaleId A scale on the staff with its name to choose the scale (dorian), or notMajor when asked as major or not ScaleIdSettings: clef, range, scales, choices, majorOrNot
    stepSkip Two notes, with how the melody moved to choose, the choices smallest first; each motion comes up as often as the others repeat, step, skip or leap StepSkipSettings: clef, range, motions, the motions asked
    lineOrSpace A note on the staff, with whether it sits on a line or in a space to choose (a ledger line is a line) line or space LineOrSpaceSettings: clef, range
    intervalBuild A note given, with a natural to place an interval above or below it the Pitch placed IntervalBuildSettings: clef, range, numbers, directions
    keyboardNoteId A note on the staff with its piano key to tap — with accidentals, a sharp or flat too, its black key the answer; with halfStep, the key a half step up or down from it instead, the very next key, black or white the key's MIDI number KeyboardNoteIdSettings: clef, range, keyboard range, any octave, accidentals, spelling, halfStep
    keyboardFind A letter, with every key of that letter to tap the keys tapped, as MIDI numbers KeyboardFindSettings: letters, keyboard range, keys named (showNames)
    chordBuild A chord named, with its keys to tap in any voicing — on one octave too, the chord wrapping round; a black-key root is named as its chord usually is (D♭ major, C♯ minor), and every chord is spelled plainly, never with E♯, B♯, C♭ or F♭ (F diminished, E and A augmented are never dealt) the keys tapped ChordBuildSettings: qualities, roots, accidentals, keyboard range
    keyboardSpelling A word marked on the keys, to spell back with letters; a letter met again is marked on a key of its own, and a word needing more keys of a letter than the keyboard has is not drawn while another fits (string | null)[], one per marked key KeyboardSpellingSettings: words, extra letters, keyboard range
    symbolId A symbol with its name to choose the symbol code SymbolIdSettings: symbols, choices, the symbols asked
    rhythmFill A bar with a note value missing, and tiles to fill it — written over 4, or in one of the timeSignatures given (2/4, 3/4, 4/4, 6/8, 2/2 …); a compound bar is built in dotted-quarter beats; a value as long as the whole bar can be a wrong tile the beats (number) RhythmFillSettings: beats per bar or time signatures, values (notes and rests), the values asked as the missing one, tiles offered
    timeSignatureId Full bars of note values, with the time signature they are written in to choose; signatures whose bars are the same length (3/4 and 6/8) are never offered together, and a compound bar is built in dotted-quarter beats. Asked ask: 'bottom', one of the signatures with what its bottom number means to choose — the note the music is counted in (a quarter note for a bottom 4, a half note for 2, an eighth note for 8), among the other notes of values. Asked ask: 'strong', one bar of 2/4, 3/4, 4/4 or 2/2, a note on each beat, with its strong beat to tap: beat 1, or — where strengths allows, from level 4 — the medium-strong beat 3 of 4/4 the signature ('3/4'); the note ('quarter'); the beat ('1') TimeSignatureIdSettings: signatures, values, bars shown, choices, ask (TimeSignatureAsk), strengths (BeatStrength)
    termId A term as written in a score, with its meaning to choose the term code TermIdSettings: categories (dynamics, tempo, articulation, expression, form), terms, choices
    letterStep What comes next on the musical alphabet: the letter after or before one, or so many letters up or down from it, round from G to A — with H offered after G, the letter the English alphabet would give the letter LetterStepSettings: letters to start from, directions (up / down, a LetterStepDirection), steps, wrap, choices
    catch Targets drifting by (fish), each showing a note, symbol, value, key or letter; catch the one — or every one — named; each wrong target shows once. Caught by ear (byEar), the targets show nothing: the card's sings is the note to match and each target's midi the note it sings, the others distances half steps away. Played on a keyboard (play), there is no name to catch: every target — a note, a key or a letter — is caught by playing its key, each with the midi of its key (displayMidi) the ids caught CatchSettings: content, count, rule (one / all), targets, byEar, distances, play
    hop Stepping stones to hop in order: a word's notes, a scale, values short to long (every pad on the run: any other value would be on the way too), the musical alphabet forwards or backwards the ids hopped, in order HopSettings: content, sequence, words, length, extra pads, direction
    memoryMatch Pairs face down: a thing and its name the pairs found MemoryMatchSettings: content, pairs
    order Things to put in order: notes or keys low to high, values short to long, key signatures from the most flats to the most sharps, letters in alphabet order — never dealt already in order; symbols and terms have no order and throw the ids in order OrderSettings: content, count, direction
    listen A sound to listen to — two notes, a little tune played a certain way, one long or short note, two tunes to compare, a chord — with what was heard to choose: higher or lower, loud or soft, short or smooth, fast or slow, long or short, step or leap, the same or different, major or minor the answer chosen ('higher', 'crescendo', 'half' …) ListenSettings: the question, and for each question the answers offered and how far apart they sound
    beatTap A bar of dots (beats and rests) or a one-bar rhythm in notes to hear, then tap back on the beat after a count-in — in 4/4, 3/4, 2/4 or 6/8 the tap times in milliseconds BeatTapSettings: mode (steady / echo), tempo or tempos, window, count-in, beats or beat choices, rests, values, time signatures
    tieOrSlur Two or three notes with a curve over them: a tie (the same pitch twice) or a slur (notes that move) to choose — in the same note values whichever it is, across a bar line, and at the top level a slur from a note to its own sharp or flat tie or slur TieOrSlurSettings: clef, range, notes under a slur, step or skip, barLine, accidentals
    barLines A line of note values in a time signature with its bar lines left out: tap the gaps where they go the gaps chosen, each the place of the value before it BarLinesSettings: time signatures, values, bars
    scaleDegree A note in a named key with its degree to choose (mode: 'name': tonic 1, dominant 5 …), or a degree of a key with its note to find on the keyboard or the staff, any octave ('find'); with numbersOnly, asked by number alone in the scale from the key's first note, naming no key, tonic or dominant the degree ('5'), or the key tapped / note placed as a MIDI number ScaleDegreeSettings: mode, keys, degrees, choices, clef, range, findOn, keyboard range, numbersOnly
    chordName A root-position chord on the staff with its symbol to choose (C, Am, G7), or its Roman numeral in a named key (I, IV, V, i) the name ('Am', 'IV') ChordNameSettings: namings, symbols, keys, numerals, clef, range, choices
    tuneQuestions A short tune — a key, a time, two to four bars, signs — with three or four questions about it asked in turn, each answered by choosing or by tapping a bar the answers given, in turn TuneQuestionsSettings: the tune's settings, the kinds of question, how many
    rhythmAnswer A one-bar rhythm to answer with a bar of the player's own, built of the card's values: any full bar that keeps the rules is right the values of the answer RhythmAnswerSettings: time signatures, values, rules, tempo
    finishTune A tune with its last one or two notes missing, to place on the staff so it ends by the rules: on the tonic, by step or skip the notes placed FinishTuneSettings: the tune's settings, notes missing, rules

    Catch, hop, memory match and order draw from content: contentFacts({ content, … }) lists what a kind can show — noteNames, symbols, noteValues, pianoKeys, keySignatures, terms, letters — each as a Display (how it is shown) with a name and a rank, so the same catch round can ask for notes one level and symbols the next. Whatever ContentSettings are not given come from defaultContentSettings (naturals on the treble staff from middle C, every symbol, the common note values, two octaves of keys from middle C, key signatures to three sharps or flats); mergeContentSettings lays settings over them. uniqueByName(facts) keeps one fact per name, the first of each — one note per letter, say. judgesLive says which kinds judge each move as it is made (catch, hop, memory match, and the questions of a read-a-song card), so a wrong move is a try at once and the card settles itself when complete.

    Letters are the musical alphabet, A to G, each shown as a big letter — content for a player who cannot read words yet. letters picks some of them (default: all seven) and letterStart says where the alphabet starts, so going forwards from C runs C D E F G A B, round from G to A (musicalAlphabet is the seven; letterPlace(letter, start, direction) counts a letter's place from a start, forwards or backwards). An order card puts letters in alphabet order — "Drag the letters in ABC order.", from A unless letterStart says otherwise ("Drag the letters in order, from C.") — or backwards with direction: 'descending', from G unless told otherwise. A hop card with sequence: 'alphabet' hops length letters in a row from letterStart (or from a letter drawn from letters), forwards round from G to A or backwards with direction: 'descending', the order hidden since knowing it is the puzzle ("Hop the letters in order, from C."); a word can be hopped on letter pads too ("Hop the letters that spell Bee."). A catch card asks for a letter ("Catch every C"; the card's content says the targets are letters). A memory card throws for letters — a letter's name is itself, so each pair would be one letter twice; pair letters with their keys through pianoKeys content instead.

    A line-or-space card shows a natural on the staff and asks whether it sits on a line or in a space: lineOrSpaceAt(position) says which for any staff position — the even ones, ledger lines among them, are lines; the odd ones, the spaces just outside the staff among them, are spaces. Lines and spaces are asked equally often whatever the range, and the choices are always ['line', 'space'] in that order, so the two answers stay in place card after card. Level 1 keeps to the treble staff E4 to F5; level 2 adds the spaces just outside it; level 3 reads the bass staff; levels 4 and 5 add one and then two ledger lines each way. defaultLineOrSpaceSettings / mergeLineOrSpaceSettings give its defaults.

    A name-the-note card with keySignatures (sharps positive, flats negative, [1, -1]) reads the note under one of them: the staff shows the signature (keySignature on the card) and a plain note. A note whose letter the signature alters is named with its sharp or flat — "F♯" under one sharp — with the plain letter among the choices; any other note keeps its plain name, with the letter and the signature's sign ("G♯") among the choices, so guessing the sharp never pays. alteredShare (default 0.5) sets how often the note is an altered one; 1 asks only those, for a first card. The same sound under another name is never offered. keySignatureAlter(fifths, letter) says what a signature does to a letter: 1, −1 or 0.

    A written natural is read with naturalShare, 0 to 1 (default 0): how often the note is written with a natural sign, the card's writtenNatural set for the view to draw it. Under keySignatures the natural cancels the signature on a note it alters — F♮ under one sharp — so the answer is the plain letter, with the signature's name (F♯) beside it. With accidentals and no key signature, a natural is written with its sign before it and named plainly, with its sharp or flat beside it. naturalShare: 1 writes one on every card, for a first card after the natural is shown.

    Sharps or flats, one way. With accidentals, a name-the-note card asks each black key both ways, C♯ and D♭. spelling: 'sharps' writes every black key as a sharp and offers only sharps and naturals, 'flats' the same with flats (an AccidentalSpelling; default 'both'). Whatever the spelling, no two names of one sound are ever offered together — never G♭ beside F♯ — and a sharp or flat answer always has its plain letter among the choices — F beside F♯ — so the sign has to be read. { kind: 'noteNameId', accidentals: true, spelling: 'sharps', lowestMidi: 66, highestMidi: 66, choiceCount: 2 } asks F♯, with F the other choice. A find-the-key card takes spelling too, for the note it writes.

    Every kind has a maker (create…Card) and a checker (check…), listed below; createCard and checkCard take any kind, and gameKinds lists them. settlesOnChoice says whether a kind is settled the moment one choice is made (a name, a key, a tile) or checked once every part is in place (a spelling, a chord, an interval to build). spellOnStaffMarks, symbolSpellingMarks and keyboardSpellingMarks say which parts of an answer are right, wrong or empty, one entry per note, symbol or marked key; isAnswerComplete says when an answer is ready to check; emptyAnswer gives a blank one.

    A name-the-symbol card shows any of its symbols and offers others as the names to choose from. To name one new symbol beside known ones, give it in asked: { kind: 'symbolId', symbols: ['dottedHalfNote', 'halfNote', 'quarterNote', 'wholeNote'], asked: ['dottedHalfNote'] } always shows the dotted half, with the known notes offered only as wrong names. The term, key signature, scale, chord-quality, interval and step-or-skip cards take asked too — the answers to ask, as the card's answer names them (term codes like 'mp'; numbers like '6' for a generic interval; motions like 'repeat') — so a first card can ask just the new item while the others are still offered as choices; a card whose asked the settings can never draw throws. A complete-the-measure card takes asked as the note values the missing one is drawn from, the bar still filled from values: { kind: 'rhythmFill', values: ['half', 'quarter', 'eighth'], asked: ['eighth'] } always leaves a single eighth out. A chord-quality card takes roots as a build-a-chord card does, so an augmented chord can be kept to roots that never need a double sharp, and inversions: 'only' asks every chord in an inversion, the root never at the bottom — for the first card after inversions are shown (true mixes root position with inversions; false, the default, asks root position only). Given ask: 'root' (ChordQualityAsk), a chord-quality card asks the chord's root instead — the note it is built on and named after — among the chord's own notes in letter order (the card's ask is then 'root' and its answer the root's name, 'G'); with choiceCount: 2 the choices are the root and the bottom note, so an inverted chord must be restacked in 3rds to tell them apart.

    Bars in eighths — the compound time signatures 6/8, 9/8 and 12/8, and 3/8, whose three eighths are grouped as one — are built in dotted-quarter beats, on complete-the-measure and which-time-signature cards alike: each beat is a dotted quarter, a quarter and an eighth, three eighths and so on, so a 6/8 bar reads as two beats of three eighths and never as three quarters, and the gap of a complete-the-measure card falls inside one beat. compoundBeat(signature) gives that group, 1.5 quarter-note beats, or null for a signature over 2 or 4; fillBar(values, beats, random, beat) fills a bar beat by beat, and valuesForSignature(values, signature) keeps the values that read well in a signature — none longer than its bar, and over 8 none longer than a dotted quarter, so the bar is counted in eighths. Every bar a card draws writes its rests the way printed music does: never a bar of rests alone (a whole bar of silence is a whole rest in any time, and none is ever asked), in simple time a half rest only on a strong beat (the first or third of 4/4 and 2/2, the first of 3/4) and never two quarter rests where a half rest is written, in compound time no beat of rests alone and a quarter rest only at the start of its beat.

    A maker throws when its settings cannot make a card — a word with letters other than A–G, an interval that does not fit the range, values that never add up to another. startDeck throws for the same reasons, and for an empty deck or one over MAX_DECK_LENGTH. Through createCard (and so in any deck), a setting given as undefined takes its default and a note range beyond the MIDI numbers 0 to 127 is brought within them, and a count that is not a number takes its default.

    A kind's maker takes its settings — anything left out takes the kind's default — and a random source (createRandom(seed)), and returns a card; its checker takes the card and an answer and says whether the answer is right. default…Settings are the settings a card is made from when nothing is given, and merge…Settings(overrides) lays partial settings over them. A maker does not read level: createCard and every deck fold the level's preset in (withLevel).

    Kind Asks Maker Checker Defaults / merge
    spellOnStaff Spell a word with notes on the staff createSpellOnStaffCard checkSpellOnStaff defaultSpellOnStaffSettings / mergeSpellOnStaffSettings
    intervalId Name the interval between two notes createIntervalIdCard checkIntervalId defaultIntervalSettings / mergeIntervalSettings
    rhythmMath Add or take away two note values createRhythmMathCard checkRhythmMath defaultRhythmMathSettings / mergeRhythmMathSettings
    symbolSpelling Spell back a word written in symbols createSymbolSpellingCard checkSymbolSpelling defaultSymbolSpellingSettings / mergeSymbolSpellingSettings
    noteNameId Name a note on the staff createNoteNameIdCard checkChoice defaultNoteNameIdSettings / mergeNoteNameIdSettings
    chordQualityId Name a chord's quality, or its root createChordQualityIdCard checkChoice defaultChordQualityIdSettings / mergeChordQualityIdSettings
    keySignatureId Name the key of a signature createKeySignatureIdCard checkChoice defaultKeySignatureIdSettings / mergeKeySignatureIdSettings
    scaleId Name a scale createScaleIdCard checkChoice defaultScaleIdSettings / mergeScaleIdSettings
    stepSkip Say how a melody moved createStepSkipCard checkChoice defaultStepSkipSettings / mergeStepSkipSettings
    lineOrSpace Line or space createLineOrSpaceCard checkLineOrSpace defaultLineOrSpaceSettings / mergeLineOrSpaceSettings
    intervalBuild Place an interval above or below a note createIntervalBuildCard checkIntervalBuild defaultIntervalBuildSettings / mergeIntervalBuildSettings
    keyboardNoteId Tap the key of a note on the staff createKeyboardNoteIdCard checkKeyboardNoteId defaultKeyboardNoteIdSettings / mergeKeyboardNoteIdSettings
    keyboardFind Tap every key of a letter createKeyboardFindCard checkKeyboardFind defaultKeyboardFindSettings / mergeKeyboardFindSettings
    chordBuild Tap a chord's keys createChordBuildCard checkChordBuild defaultChordBuildSettings / mergeChordBuildSettings
    keyboardSpelling Spell back a word marked on the keys createKeyboardSpellingCard checkKeyboardSpelling defaultKeyboardSpellingSettings / mergeKeyboardSpellingSettings
    symbolId Name a symbol createSymbolIdCard checkSymbolId defaultSymbolIdSettings / mergeSymbolIdSettings
    rhythmFill Fill the value missing from a bar createRhythmFillCard checkRhythmFill defaultRhythmFillSettings / mergeRhythmFillSettings
    timeSignatureId Name a time signature, its bottom number or its strong beat createTimeSignatureIdCard checkTimeSignatureId defaultTimeSignatureIdSettings / mergeTimeSignatureIdSettings
    termId Choose a term's meaning createTermIdCard checkTermId defaultTermIdSettings / mergeTermIdSettings
    letterStep Choose the letter so many along createLetterStepCard checkLetterStep defaultLetterStepSettings / mergeLetterStepSettings
    catch Catch the target named createCatchCard checkCatch defaultCatchSettings / mergeCatchSettings
    hop Hop the stones in order createHopCard checkHop defaultHopSettings / mergeHopSettings
    memoryMatch Find the pairs createMemoryMatchCard checkMemoryMatch defaultMemoryMatchSettings / mergeMemoryMatchSettings
    order Put things in order createOrderCard checkOrder defaultOrderSettings / mergeOrderSettings
    listen Say what was heard createListenCard checkListen defaultListenSettings / mergeListenSettings
    beatTap Tap a bar of dots, or a rhythm in notes, back on the beat createBeatTapCard checkBeatTap defaultBeatTapSettings / mergeBeatTapSettings
    tieOrSlur Tie or slur createTieOrSlurCard checkTieOrSlur defaultTieOrSlurSettings / mergeTieOrSlurSettings
    barLines Put the bar lines in createBarLinesCard checkBarLines defaultBarLinesSettings / mergeBarLinesSettings
    scaleDegree Name a note's degree, or find a degree's note createScaleDegreeCard checkScaleDegree defaultScaleDegreeSettings / mergeScaleDegreeSettings
    chordName Name a chord by its symbol or numeral createChordNameCard checkChordName defaultChordNameSettings / mergeChordNameSettings
    tuneQuestions Answer questions about a song createTuneQuestionsCard checkTuneQuestions defaultTuneQuestionsSettings / mergeTuneQuestionsSettings
    rhythmAnswer Answer a rhythm with a bar of one's own createRhythmAnswerCard checkRhythmAnswer defaultRhythmAnswerSettings / mergeRhythmAnswerSettings
    finishTune Finish a song by the rules createFinishTuneCard checkFinishTune defaultFinishTuneSettings / mergeFinishTuneSettings

    letterAlong(from, by, direction) gives the letter so many along the musical alphabet, round from G to A (letterAlong('G', 1, 'up') is 'A'), and letterStepWraps(from, by, direction) whether the count goes round.

    checkChoice(card, answer) is the plain check of a card answered by one choice: whether the choice is the card's answer.

    import { checkIntervalId, createIntervalIdCard, createRandom, mergeIntervalSettings } from '@hiyve/music-games';

    const card = createIntervalIdCard({ clef: 'bass', choiceCount: 3 }, createRandom(7));
    checkIntervalId(card, card.answer); // true
    const settings = mergeIntervalSettings({ clef: 'bass' }); // the bass clef, every other setting its default

    A few smaller readers go with the cards: intervalNumber(interval) is an interval's number ('M3' is 3, 'P8' 8); motionBetween(clef, from, to) says how a melody moved between two notes (a Motion: repeat, step, skip or leap, as motions lists them); sameBeats(a, b) says whether two beat counts are the same, allowing for rounding.

    Two kinds need no reading and no instrument: the sound is the question.

    A listening card (listen) plays a sound and asks what was heard. Its sound is a ListenTune — notes, tempo, loudness, touch and lengths, as data — and its choices keep the order the settings give them, so a picture stays where the player last saw it; the answer is drawn evenly from them. One kind asks eight questions (listenQuestions; listenAnswers lists what each can offer):

    question Plays Answers, set by
    higherLower (default) Two notes, one after the other, distances half steps apart (12 an octave … 1 a half step) between lowestMidi and highestMidi directions: higher, lower, same (the same note twice)
    loudSoft A tune played at the soft or loud end of loudness, or changing from one to the other dynamics: soft, loud, crescendo (getting louder), decrescendo
    shortSmooth A tune played short and detached, smooth and joined, every other note stressed, or the last held touches: staccato, legato, accent, fermata
    fastSlow A tune at the slow or fast end of tempos, speeding up or slowing down between them, or at a tempo word's speed (listenTempoWords: Largo 50, Andante 84, Allegro 132, Presto 184) speeds: slow, fast, ritardando, accelerando, largo, andante, allegro, presto
    longShort One note lengthBeats long — or a quarter, half, dotted half or whole note with a soft tick on each beat it lasts, to count it by lengths: short, long, quarter, half, dottedHalf, whole
    stepSkip Two naturals: the same note again, the next letter, one letter skipped, or a leap of a 4th to a 6th motions: repeat, step, skip, leap
    sameDifferent Two tunes (or two single notes) one after the other — the card's sound, then its second — the second the first again, or changed as one of changes says: turned the other way (direction), two notes moved (notes), one note moved a step (note), one note's length changed (rhythm), or a single note against another distances away (pitch). The change is drawn first whichever the answer, so a tune or a note never gives it away comparisons: same, different
    majorMinor A chord, an arpeggio, a 3rd (one note, the other, then both) or five notes of the scale up and back, built on one of tonics (MIDI numbers) as one of harmonies says; only the 3rd differs — four half steps for major, three for minor. The card's harmony says which was played qualities: major, minor

    The tunes come from tunes (defaultListenTunes: five to seven notes around middle C), played at tempo (but for fastSlow). Each question reads only its own fields, so a level's preset sets every question's difficulty at once and { kind: 'listen', question: 'loudSoft', level: 3 } asks loud or soft at level 3. The ramps: higher or lower from an octave apart (level 1) to a half or whole step with "the same" offered (level 5); loud or soft from very soft against very loud, to soft against loud, to getting louder or softer, to all four; short or smooth adds the fermata (level 3) and the accent (level 4); fast or slow goes from very fast against very slow to speeding up and slowing down, then all four, then the tempo words (level 5); long or short from a quarter beat against four beats to quarter or half (level 3), quarter, half or whole (4) and the dotted half (5); step or leap adds the repeated note, then the skip; same or different goes from a tune turned the other way (level 1) to one note or one rhythm changed (level 5); major or minor from block chords on C (level 1), on C, F and G (2), to arpeggios (3), 3rds (4) and scales on any note (5). listenChanges and listenHarmonies list what those two can play. mp and mf are not asked by ear: heard on their own, on a device of any loudness, they cannot be told apart. A question offered fewer than two answers, an answer of another question, a range or tune that cannot make the sound, or two ends of a change the wrong way round throws. checkListen(card, answer) is a plain choice; defaultListenSettings / mergeListenSettings give the defaults.

    A chord in a ListenTune is written 'C4+E4+G4': its notes sound together. A ListenTune is played at a tempo (beats a minute), a loudness and a touch — or changing from one tempo or loudness to another across the tune. A Loudness is one of very soft, soft, medium soft (mp), medium, medium loud (mf), loud and very loud; the touches are staccato, legato, accent (every note stressed), fermata (the last held) and tenuto (each held its full length, slightly stressed); accents stresses only the notes it names, by place, so strong and weak beats can be heard; beats gives each note its length in beats, and pulse adds a soft tick on every beat to count them by.

    A tap-the-beat card (beatTap) is answered with taps. Both are heard first, then tapped back on the beat after a count-in of the player's own. With mode: 'steady' (the default) the bar is beats beats shown as dots — a tap on each, or with rests (numbers of rests, one drawn per card) some of them rests, never the first and never so many that fewer than two taps are left; beatChoices draws the number of beats per card. With 'echo' the bar is a rhythm in notes drawn from values, tapped back — each note one tap however long, a rest none, two eighths two; the rhythm always starts with a note and has one rest at most and two taps or more, a dotted quarter always comes with the eighth that completes its beat, and sixteenths and eighth rests are not echoed. The card holds its pattern (note values), onsets (when each tap is due, in beats), tempo and window; tempos draws the tempo per card. The answer is the tap times in milliseconds (BeatTapAnswer), from the first beat of the player's bar (a tap a little before it is negative). checkBeatTap(card, taps) is right when there are as many taps as are due and each falls within window (a share of a beat either side) of its own; beatTapVerdicts says how each tap fell — onTime, early, late, missed or extra — and beatTapTimes when each is due. The levels go from 100 beats a minute — near a natural tapping pace, where a beat is easiest to keep — with 35% of a beat either side and an echo of halves and quarters (level 1), through pairs of eighths (2) and quarter rests (3), to dotted values, eight beats and 12% either side at 112 beats a minute (level 5), where an echo may be a bar of 6/8. With timeSignatures an echo's bar is written in one of them (the card's timeSignature): a 6/8 bar keeps its two dotted-quarter beats — a dotted quarter, a quarter and the eighth after it, three eighths, or a dotted half — and the count-in ticks on them (the card's beat, 1.5). patternOnsets(values) gives any pattern's onsets; defaultBeatTapSettings / mergeBeatTapSettings give the defaults.

    A tie-or-slur card (tieOrSlur) draws two or three notes with a curve over them: the same pitch twice is a tie, notes that move a slur. Ties and slurs come up equally often, written in the same note values; barLine crosses a bar line with the curve half the time, and accidentals adds the look-alike — F to F♯ under a curve is a slur. The choices are always ['tie', 'slur']. Levels: two notes by step (1), slurs of three and skips (2), the bass staff (3), across a bar line (4), sharps and flats (5).

    A bar-lines card (barLines) is a line of bars full bars of note values with its bar lines left out. Each bar is a common fill of the values — in 6/8 one dotted-quarter beat at a time — the line starts with a note, and where the values allow no two bars in a row are alike and not every bar is one value, so the bar lines are counted rather than seen. The answer is the gaps a bar line goes in, each the place of the value before it, in any order; checkBarLines is right when every bar adds up, and barLinesBars(card, gaps) gives the beats in each bar the gaps make. Levels: two bars of halves and quarters in 2/4, 3/4 or 4/4 (1), three bars with whole notes and dotted halves (2), eighths and quarter rests (3), dotted quarters and half rests (4), four bars with 6/8 and every rest (5).

    A scale-degree card (scaleDegree) names a note's place in a key's scale, 1 (the tonic) to 7 (5 is the dominant): the key's signature and the note on the staff, written as the signature makes it, with degrees to choose from in order — or, with mode: 'find', a degree named, its note tapped on the keyboard or placed on the staff under the key's signature (findOn), in any octave. Keys are codes like 'G:major' or 'A:minor'; a minor key's 7th is its raised 7th, the harmonic minor's leading note (G♯ in A minor, written with its sharp) — so it is not asked where a note is placed on the staff, where no sharp can be written. keyInfo(code) reads a key — its tonic, mode and signature — keyScale(key, octave) gives its seven notes (the natural minor's for a minor key) and degreeNotes(key, degree, low, high, harmonic?) a degree's note in every octave of a range, the raised 7th with harmonic. Levels: tonic or dominant in C, G and F major (1), found on the keys (2), notes 1 to 5 in five keys (3), every degree, a minor key too (4), placed on the staff in keys to three sharps or flats (5).

    A chord-name card (chordName) draws a root-position chord and asks its name: its symbol — a root with an optional ♯ or ♭, then nothing for major, m minor, 7 a dominant 7th, dim diminished — drawn with no key signature, or its Roman numeral in a named key, drawn under the key's signature: upper case major, lower case minor, ° diminished, a minor key's V major and its vii° built on its raised 7th. A chord is read by the key's letters, never by sound, so a numeral whose chord needs a note the key does not spell (vi in a minor key) is never asked. The names offered are the nearest of those asked, lowest root (or degree) first. chordSymbolParts, chordNumeralParts and chordSymbol read and write the names. Levels: C, F and G (1), with Am, Dm and Em (2), I, IV and V in C, G and F major (3), 7ths on the bass staff (4), symbols and numerals in major and minor keys (5).

    A tune (createTune) is two to four bars that sound like music: each bar a common rhythm of the values given (tunePatterns), the first bar's rhythm usually coming back once, the last ending on a long note; a melody that starts on the tonic, 3rd or 5th, moves mostly by step, rises then falls, and comes home to the tonic by step with no leap wider than a 5th into its last two notes, a minor key's 7th raised on the way and reached neither from the 6th (no augmented 2nd to sing) nor from the natural 7th (no chromatic step) — after either the tune comes home from above or goes to the 5th first; and one to three of the signs written where they belong — a dynamic under the first note, a tempo word over the start, staccato on a bar's quarters, an accent, a slur over notes moving by step, a fermata on the last note, a hairpin under a bar, and (speed) changes of speed at the start of the bars they change, as music writes them: rit. or rall. into the last bars, or before a tempo brings the first speed back, and accel. before a tempo — only the words in speedChanges (default tuneSpeedChanges: ritardando, rallentando, accelerando, aTempo). With daCapo (on every tune when it is the only sign given, on half of them beside others), a tune of three or four bars is written as D.C. al Fine: a first part of one to three bars that comes home to the tonic, with Fine over its last bar line, and a second that ends on the 5th, with D.C. al Fine at the end. A Tune is data: its notes (TuneNote), bar lines, slurs, dynamics, hairpins, tempo word, speedChanges, the note Fine follows (fine) and beats a minute (tuneTempoBpm). tuneBarOf, tuneBarBeats and tuneBarsFull read its bars; tuneNoteBpm gives the speed each note is played at, slower through a rit., back at a tempo; tunePlayOrder the notes in the order played, back to the beginning and on to Fine after a D.C. tuneSigns lists every sign a tune can carry; defaultTuneSettings (four bars in C major on the treble staff, in 2/4, 3/4 or 4/4, of whole, dotted half, half and quarter notes, with no signs) and mergeTuneSettings fill in a TuneSettings.

    A read-a-song card (tuneQuestions) draws a tune once and asks count questions about it in turn (TuneQuestion): its key (key), the beats in a bar (beats), its time signature, which is then hidden (time), what a circled sign means (sign), which bar has the highest or the lowest note (highest, lowest), the same rhythm as bar 1 (sameRhythm) or a rest (rest), the name or the degree of the note under an arrow (noteName, degree), and on a tune with D.C. al Fine which bar is played after the D.C. (daCapo, always bar 1) and which bar the music ends in, at Fine (fine). A sign's meaning is chosen among those of its family — a change of speed among gradually slower, gradually faster and back to the first speed, never two of one meaning (rit. beside rall.). Only what the tune can answer is asked — the highest note in one bar only, one bar with bar 1's rhythm — and every question has three choices or more, so none is a toss-up; a bar question is answered with a bar number. tuneQuestionKinds lists them in the order asked; the card's meanings give each sign's meaning in words. The card judges each answer as it is given (judgesLive): a wrong one is a try, and the card settles itself right once every answer is in. Levels: four bars in C major asking beats, bars and a note's name (1), eighths and the time signature (2), G and F major (3), dotted rhythms, the signs and a degree (4), minor keys, 6/8 and the key (5).

    Two kinds are made up, judged by rules rather than one right answer. An answer-the-rhythm card (rhythmAnswer) plays a one-bar rhythm — the question — and takes any bar built of its tiles that fills the bar (in 6/8 one dotted-quarter beat at a time) and keeps its rules: end on a long note (endLong: a half note or longer, a quarter in 2/4, a dotted quarter in 6/8 — longEnough), use a note value of the question (useQuestion), and not copy it (notSame) — rhythmAnswerRules lists them. rhythmAnswerProblems(card, values) says what is wrong — notFull, tooFull, acrossBeat, or a rule — and rhythmFromTaps(card, taps) turns taps on a drum (beats from the start of the bar) into the card's values: snapped to the eighth (or the beat), each note lasting until the next tap, a late first tap a rest. example is one answer that keeps every rule. Levels: any full bar of halves and quarters (1), ending long (2), using a value of the question, with eighths and a rest (3), no copy (4), dotted rhythms and 6/8 (5).

    A finish-the-song card (finishTune) is a tune with its last missing notes left out — their lengths shown — to place on the staff under the key's signature. Any ending that keeps its rules is right: the tonic last, in any octave (tonic); each note placed a step or a skip from the one before (stepSkip); the last reached by a step (stepHome) — finishTuneRules lists them. finishTuneProblems says which rule an ending breaks (or notPlaced, outOfRange), and example is the tune's own ending. Levels: the last note of a C major tune (1), by step or skip in G and F major too (2), the last two notes (3), reached by step (4), four bars in more keys, minor among them (5).

    Every kind has a preset for five levels of difficulty, so a card can be asked at a level instead of with its settings spelled out: { kind: 'noteNameId', level: 3 } reads the bass staff, { kind: 'rhythmFill', level: 5 } writes bars in 6/8 and 2/2 with rests among the values, { kind: 'termId', level: 1 } asks pp, p, f and ff only. Level 1 stays within the treble staff with a few choices; each level adds ledger lines, the bass clef, more symbols, values, intervals, qualities, keys and terms; level 5 asks the whole of what the kind can. Settings given alongside the level win over the preset. A deck or a trail takes a level too, for every card without one of its own.

    Function Does
    levels Every level, easiest first: 1 to 5
    levelPresets The five presets of every kind, easiest first
    levelSettings(kind, level) One kind's preset at a level; a level outside 1 to 5 is brought within it
    withLevel(cardSettings) Card settings with their level folded in
    Function Does
    startDeck(settings, { seed }) Deals one card per entry of settings.cards, all from the seed
    repeatCards(settings, count) The same card settings count times, for a deck of one kind
    answerDeck(deck, answer, elapsedMs?, keepOpenWhenWrong?) Settles the round — or, with keepOpenWhenWrong, counts a wrong answer as a try and leaves the round open
    answerRound(deck, roundIndex, answer, elapsedMs?, keepOpenWhenWrong?) The same for any round, for a board where every card is open at once
    isDeckSettled(deck) Whether every round is settled, in whatever order
    nextCard(deck) Moves on once the round is settled
    finishDeck(deck) Ends the deck where it stands
    isDeckFinished(deck) Whether every round has been played
    deckSummary(deck) total, answered, correct, firstTry, accuracy (0–1), meanElapsedMs, missed
    deckRecord(deck, settings) The deck kept small: settings, seed and answers
    isDeckRecord(value) / restoreDeck(value) Whether something read back is a whole record, and the deck it describes — or null
    migrateDeckRecord(value) A record read back brought up to DECK_RECORD_VERSION — an older one kept with restorable: false — or null for anything else

    Balanced answers. As a deck is dealt, the answers of the cards settled by one choice (settlesOnChoice: a name, a tile, a key, a listening answer) are balanced, so tapping the same button every time never wins: a kind's cards in a deck — three or more — never all have the same answer, and no answer comes up more than three times in a row among them. A card that breaks either rule is drawn again from its own settings, from the deck's seeded source, so the same seed still deals the same deck. A card its settings pin to one answer — asked with one item, a range of one note — is kept as it is, so a first card that asks just the new item still does. In the same way no card comes up twice in one deck: one asking the same as a card already dealt — the same note to name, though its choices come in another order — is drawn again while its settings can make one the deck does not hold yet (with an answer that keeps the deck balanced), and where they cannot, at least never twice in a row. Only the repeats are drawn again: a deck without one is dealt just as its cards came.

    DECK_RECORD_VERSION (now 9: "Horn" in place of "Tune" among the symbol-spelling cards' default words; at 8, chords spelled plainly, rests written as read, a minor key's 7th raised, minor tunes brought home as sung, three eighths in 6/8 echoes) is stamped on every record and goes up if the same settings and seed would ever deal different cards, so an old record is never restored against the wrong cards. A record of an older version is never thrown away: migrateDeckRecord brings it up one version at a time (deckRecordMigrations, one step per bump), and where the deal changed since it was made — as it has at every bump so far, though from 8 to 9 only for a deck that can deal a symbol-spelling card from the default words — the record keeps its settings, seed, answers and so its score, marked restorable: false: restoreDeck gives null for it and missedCards passes it by, because the cards it answered cannot be dealt again. A record of a version not made yet is left alone, for the code that made it.

    Keyboard cards share a KeyboardRange: keyboardLowestMidi (a C, default 60) and keyboardOctaves (default 2) — defaultKeyboardRange, two octaves up from middle C. keyboardHighestMidi(range) is the top key and keysOfLetter(letter, lowest, highest) every key of a letter within it. A find-the-key card with accidentals writes a sharp or a flat before some notes — each black key asked both ways, C♯ and D♭, unless spelling keeps to 'sharps' or 'flats' — and the black key is the one to tap; off, the default, it asks naturals only.

    A find-every-key card can name the keys for a player still learning where the letters are: showNames: 'all' names every white key by its letter, 'c' only the Cs, and 'none', the default, none. The card carries it (KeyNames) for the view to draw.

    A build-a-chord card draws its root from roots when they are given — names such as ['C', 'F', 'G'] or ['D♭', 'E♭', 'G♭', 'A♭', 'B♭'] ('F#' and 'Bb' work too) — each spelled as written, so 'D♭' asks for D♭ major and never C♯ major, and paired with every one of the qualities. Without roots it draws any white-key root, and the black-key roots too with accidentals. Any octave of each tone counts, so a chord can be built on one octave (keyboardOctaves: 1, one row of keys on a phone): the root can be any key and a tone above the top key wraps round to the same letter lower down — G major on the octave from middle C is G, B and the D below them, and the card's answer gives those keys. On two octaves or more the root sits an octave or more below the top key, so the chord fits above it. A name that is not a letter with an optional sharp or flat throws, as do roots on which no chord of the qualities can be spelled without a double sharp or flat.

    A keyboard-spelling card marks one key per letter, each in an octave drawn at random; a letter met again in the word is marked on a key of its own when the keyboard has one free, so "Dad" on two octaves marks two different Ds (on one octave, its one D twice).

    import { startDeck } from '@hiyve/music-games';

    const deck = startDeck(
    {
    cards: [
    // C, D or E on one octave, every white key named.
    { kind: 'keyboardFind', letters: ['C', 'D', 'E'], keyboardOctaves: 1, showNames: 'all' },
    // Chords on the white keys alone, on one octave: C, F or G major, then D, E or A minor.
    { kind: 'chordBuild', qualities: ['major'], roots: ['C', 'F', 'G'], keyboardOctaves: 1 },
    { kind: 'chordBuild', qualities: ['minor'], roots: ['D', 'E', 'A'], keyboardOctaves: 1 },
    ],
    },
    { seed: 7 },
    );

    scoreDeck(deck) turns a deck into a Score over the cards that were answered (a trail deals more than a game needs): points for each card right (100), more for a first-try answer (50), a quick one (up to 50, shrinking evenly to nothing at six seconds) and each card right in a row (10), with maxPoints, the accuracy, the best streak and 0–3 stars (starsFor). defaultScoreOptions / mergeScoreOptions tune it.

    A finished game becomes a GameResult with resultOf(deck, settings, { game, mode, player }): the deck kept small, its summary and score, stamped with the game (as the host names it), the mode it was played in (a PlayMode, such as deck, board or trail), the player and the time, with anything else the host wants kept in extra. gameResult(deck, record, details) does the same from a record already made (deckRecord); both give the result a fresh id (newResultId()) and the current time unless id and playedAt are given. Results go anywhere through a ResultStore:

    import { createResultStore, createLocalStorageResultStore, createMemoryResultStore } from '@hiyve/music-games';

    // Any database: say how to read the list back and how to write it, whole.
    const store = createResultStore(
    {
    read: async () => (await db.collection('results').find().toArray()),
    write: async (items) => db.collection('results').replaceAll(items),
    },
    { limit: 500 },
    );
    await store.save(result);
    const recent = await store.list({ player: 'player-1', limit: 10 }); // newest first

    What a store keeps. The list is the adapter's to hold and the store's to understand; write gets the whole list back every time. Nothing in it is ever lost on a write: a result kept at an older DECK_RECORD_VERSION is brought up to the current one (migrateGameResult: its id, game, mode, player, times, score and summary as they were, its record marked restorable: false where its cards can no longer be dealt again — so it still lists, still counts for a best, and is only left out of the cards missed) and written back so on the next save, and anything the store does not know — a result of a newer version, something else kept under the same key — is written back exactly as it was found, and never listed. save replaces a result of the same id, remove and clear take only results the store knows, and saves, removals and reads run one after another, so two games ending at once keep both results. The store keeps the newest limit results (ResultStoreOptions; DEFAULT_RESULT_LIMIT, 500): as one is saved past that, the oldest go; Infinity keeps them all.

    createLocalStorageResultStore(key?, options?) keeps results in the browser — where the browser refuses a write (its storage full, or blocked) the result is not kept and onError is told (LocalStoreOptions; without it the save is rejected), and a key whose contents cannot be read is left as it is — and createMemoryResultStore(initial?, options?) for the page's life. isGameResult checks something read back is a result of the current version; selectResults filters and sorts a list already fetched; bestResult finds the top score.

    Passing. stepPassed(deck, options?) says whether a finished deck was played well enough to move on: two stars' worth of credit (an accuracy of 0.7 or more, as scoreDeck counts it) and its last three cards right, no more than one of them on a second go and none on a third — the last four for a deck whose every choice is one of two, such as higher or lower by ear, or line or space, where one wrong tap settles a card — so tapping at random does not pass. Only the cards answered count, and a deck with none fails. defaultPassOptions / mergePassOptions tune it (PassOptions: credit, tail, twoChoiceTail, tailRetries).

    Cards missed. missedCards(results) reads the cards a player missed back from any results — answered wrong or needing another go — newest first, each a MissedCard: its key, the game it was missed in, when, and settings that deal the very question again where the kind allows, the same kind of card otherwise (pinnedCard(settings, card)). The same question missed twice comes once. A card leaves the list only after it is answered right first time in two different sets of missed cards — results whose extra is a MissedExtra, { from }, the key of the card each round came from — with no miss between, and comes back if it is missed again; a result whose record can no longer be dealt again (restorable: false) is passed by.

    Practice is the cards laid out as data, for a screen where a player picks a topic, a way to practise it and a level: fifteen topics in the order a beginner meets them — listening, the keyboard, the letters A to G, the 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, and the alto and tenor clefs — each with the ways it can be practised, and the card settings each way deals at each level, 1 to 5. A set is plain card settings, so it is dealt, played, scored and kept like any deck.

    Export Gives
    practiceTopics Every topic, in order (PracticeTopic: id, a PracticeTopicId; title; a line about it; and the picture its tile shows — a PracticePicture: a music symbol, on a staff with staff, a few letters, or an icon: ear, keys, drum, stairs, tune or chord)
    practiceTopicById(id) A topic by its id, or undefined
    practiceRows Every way to practise every topic (PracticeRow: its topic; way, a stable id that results are stamped with; how, a short label such as "Name it" or "Find the key"; levels, what it deals at each level — one card's settings, or several dealt in turn; and from, the first level the way suits, when it is later than 1: Signs in a bar and D.C. al Fine from 3, The bottom number from 3, Slower and faster from 4)
    practiceRowFrom(row) The first level a row suits: its from, or 1
    practiceRow(topic, way) One row, whether Practice offers it or not
    practiceRowsOf(topic, omit?) The ways a topic is offered, in order: its rows, less those that deal only kinds left out
    defaultPracticeOmit The kinds left out unless told otherwise: the catch and the hop, each a little game of its own rather than a card to think over. Their rows stay in practiceRows
    practiceDeals(kind, omit?) Whether a kind is dealt: every kind but those left out
    practiceSet(topic, way, level, seed, options?) A set's card settings: PRACTICE_SET_SIZE (eight) cards from one way, or, with PRACTICE_MIX as the way, from every way offered in turn, starting at a way the seed picks so sets differ. The mix leaves out a way below its first level; a way alone below it is dealt at that level. A way not offered deals the mix. PracticeSetOptions sets the size and the kinds to omit
    practiceGameCards(topic, level, use) One card from each of a topic's ways that suits the level, those left out included, for a game: 'board' for a trail's cards (leaving out the catch, the hop and memory match where the topic has other ways), 'catch' for its catch cards alone, as Note Express plays them
    toPracticeLevel(value) Any number as a level: rounded and kept to 1–5, 1 when there is none
    practiceStamp(topic, way, level) The game to keep a set's result under, 'practice:treble:mix:2' — 'all' for every topic, level 0 for none — so stars and the cards missed can be read back by topic
    readPracticeStamp(game) A stamp read back, { topic, way, level }, or null for a result of another game
    practiceTopicOfCard(settings) The topic any card settings practise, with their level applied: { kind: 'noteNameId', level: 3 } reads the bass staff, so 'bass'
    practiceMissedCards(results, omit?) Every card still missed, newest first (missedCards), each under its topic (PracticeMissedCard: a MissedCard with its topic), less the kinds left out
    import { PRACTICE_MIX, newSeed, practiceRowsOf, practiceSet, practiceStamp, resultOf, startDeck } from '@hiyve/music-games';

    // The ways to practise treble notes: Name it, Signs in a bar, Place it, Find the key, Match pairs
    const ways = practiceRowsOf('treble').map((row) => row.how);

    // Eight cards at level 2, from every way in turn, dealt as any deck.
    const seed = newSeed();
    const settings = { cards: practiceSet('treble', PRACTICE_MIX, 2, seed) };
    let deck = startDeck(settings, { seed });

    // ... play it round by round (answerDeck, nextCard), then keep the result under its stamp:
    const result = resultOf(deck, settings, { game: practiceStamp('treble', PRACTICE_MIX, 2), mode: 'deck', player: { id: 'player-1' } });

    The cards missed are dealt again as a set of their own: their settings as the deck's cards, the result stamped with PRACTICE_MISSED and keeping, in its extra, the keys of the cards it came from (MissedExtra), so a card put right leaves the list.

    import { PRACTICE_MISSED, practiceMissedCards, practiceStamp, resultOf, startDeck } from '@hiyve/music-games';

    const missed = practiceMissedCards(await store.list({ player: 'player-1' })).slice(0, 8);
    const settings = { cards: missed.map((card) => card.settings) };
    let deck = startDeck(settings, { seed: 7 });

    // ... once it is played:
    await store.save(resultOf(deck, settings, { game: practiceStamp('all', PRACTICE_MISSED, 0), mode: 'deck', extra: { from: missed.map((card) => card.key) } }));

    A trail is a board game: startTrail({ spaces, cards, dice, course, maxSlides, level }, seed) lays a course from the seed — a winding, self-avoiding course on a grid (generateTrailCourse; course.shape: 'serpentine' for the classic snake) with course.vines ladders (their starts laid apart from each other) of at most course.longestVine spaces (default 6), course.whirlpools slides and course.traps traps placed along it — placed again, and the course wound again, until every one asked for fits, and until even the luckiest rolls take course.fewestTurns right answers to finish (default 0, no floor; vines are left out when nothing else keeps to it) — or shortcuts and traps fixed by hand — and deals three cards per space (the first two a space as one deck, the rest after it), so a player who answers every card right always reaches the end; answerTrail(trail, answer) rolls the die on a right answer and moves the piece — up any ladder it lands on, down a slide at most maxSlides times a game (default 3), so the end can always be reached — or leaves it put on a wrong one. A trap holds the piece: a wait trap for a number of right answers, a roll trap until the die shows the number it asks for, three failed rolls at the most — the third lets it go, and that roll moves it (TrailTrap; state.trapped says which holds it and the turns or tries it has left, each move's trap says whether the piece was caught, held or freed). No whirlpool lies one roll past a trap to pull the piece back behind it. A level asks every card at that level and, unless the settings say otherwise, lays that level's board (trailLevelSettings: 15 spaces, two vines of at most four spaces and a whirlpool at level 1, laid so that even the luckiest rolls take five turns — as at level 2, on 15 spaces with two whirlpools — up to 20 spaces, a four-sided die, three whirlpools and two traps at level 5). trailProgress and trailSummary say how it is going. The die is seeded, so a replay rolls the same. A course ends at the side of its board where it can, leaving room beyond for whatever marks the end.

    defaultTrailSettings (twenty spaces, moves of one to three, a name-the-note card at every turn, three slides at most) and mergeTrailSettings — given a level, with that level's board under the settings given — fill in a TrailSettings; defaultTrailCourseSettings is the course unless told otherwise: a winding river on a six-by-five grid, two vines of up to six spaces, two whirlpools, no traps and no floor on how quickly it can be run.

    Note Express reads notes on a railway, played in waves — trains of wagons, one for each catch card of a deck — in one of two ways (ExpressMode): 'catch' — the signboard names a note and every wagon carrying it is hooked — or 'play' — every wagon is hooked by playing its note on the keys. expressDefaultMode(level) hooks by sight at levels 1 and 2 and plays from level 3; expressDeckMode(deck) says when a deck fixes the way — played when its cards say play, hooked by sight when any can only be (by ear, signs, values, key signatures, terms). expressNotesDeck(level, waves) is the game's own deck (ten waves unless told otherwise): notes on the staff, middle C to G on the treble staff at level 1, to the C above at level 2, the whole treble staff at level 3, the bass clef joining at level 4, both clefs with ledger lines at level 5. expressLevel(level) keeps any number to a level, 1–5 (level 2 when there is none), and expressDeckLevel(deck) is the level a deck plays at. expressLevelSettings says how each level plays: the wagons in a wave and how many to hook, the tracks on a narrow screen, how long a wagon takes to roll across, how often a golden wagon comes and how much faster it rolls, the seconds of daylight a wave is given and the seconds a wrong wagon takes away — and on the keys how many wagons roll by at once (playAtOnce: one at levels 1 and 2, then two), how long each takes to cross (playCrossSeconds) and the daylight per wagon (playSecondsPerWagon). expressWaves(level, count, seed) deals the waves (ExpressWave: wagons, right, golden; the first is the gentlest and never golden), expressWaveSettings(card, wave, level, mode) makes a catch card a wave (hooked by sight: rule: 'all', the wave's wagons and targets, one hooked by ear hearing the level's listening distances; played: play with the wave's wagons), and expressDeckSettings(deck, seed, mode) does it for a whole deck, so startDeck(expressDeckSettings(deck, seed, mode), { seed }) deals the trains. ExpressScene names where the railway runs: 'meadow', 'cave' or 'summit'.

    import { expressDeckSettings, expressGoldenWagons, expressNotesDeck, startDeck } from '@hiyve/music-games';

    const deck = expressNotesDeck(3);
    const trains = startDeck(expressDeckSettings(deck, 42, 'play'), { seed: 42 });
    const golden = expressGoldenWagons(deck, trains.rounds.map((round) => round.card), 42); // one per wave that has one

    A golden wagon (ExpressGoldenWagon: display, correct, and the midi it sings or is played by) carries, when hooked, the name asked for as often as not, in a harder form than the train's own wagons — a note on a ledger line out of the wave's range, a letter as a key at levels 1–2 or on the staff after, a key on a keyboard that starts on F, G or A, a symbol or one that looks like it (never its twin), a value or rest of the same length or one a dot or a half away, a key signature in the other clef, a term from the whole list, a note sung nearer the signboard's — and otherwise something easy to take for it, at level 5 the very letter with a sharp or a flat. Played, it is always one to hook, with a harder note to play: on a ledger line, or a sharp or a flat on a black key at level 5. expressGoldenWagon(settings, card, random) makes one; expressGoldenWagons(deck, cards, seed) makes each wave's, the same for the same seed.

    Combos and points. An ExpressTally counts wagons and golden wagons hooked, wrong wagons, the combo and the best combo, and the points they made: expressHook(tally, golden) adds a wagon, expressMiss(tally) breaks the combo; emptyExpressTally starts one. A wagon is worth 10 and a golden wagon 50 (expressPoints: wagon, golden), times the combo's multiplier — ×2 from three in a row, ×3 from six, ×4 from ten (expressComboSteps, expressComboMultiplier); expressHookPoints(combo, golden) says what the next hook will make. Stars come from the trains' credit: expressRoundCredit(round) is a settled train's right wagons hooked less the wrong wagons tapped (its tries), never below nothing, over the wagons it asked for (expressWagonsToHook) — a train the sun set on is worth nothing — expressAccuracy(state) is the mean over the trains settled, and expressScore(state) is scoreDeck's points with that accuracy and its stars, so tapping every wagon earns a star at most.

    The wagon book. A train carries a topic (ExpressTopic: treble, bass, singing, keyboard — keys and letters —, values, signs, keys — expressTopics in the book's order); expressTopicOf(card) reads a card's and expressDeckTopic(deck) a deck's (a deck of both clefs in turn is the clef it starts with). Each topic and level has a wagon design (ExpressWagon: an id like express:treble:3, a name like "Treble Mail Van", a body — ExpressWagonBody: a box car, a timber wagon, a mail van, a tanker or a circus wagon —, a paint — ExpressWagonPaint — and its colors: the build's livery and the topic's trim): expressWagons lists all thirty-five, expressWagonOf(topic, level) finds one, expressWagonId names its id, and expressDeckWagon(deck) is the one a full train puts in the book.

    What a player has won across the games — Note Express's wagon book, Frog Band's players, Balloon Ride's skies and Potion Lab's potion book — is a Collection: a player's id and the things won by id (CollectedItem: when it was first won, how many times, and the most stars). collect(collection, ids, stars) adds what was won and says which are new (added); hasCollected checks one; emptyCollection(player) starts one. Collections are kept one per player in a CollectionStore: createCollectionStore({ read, write }) over any database, createLocalStorageCollectionStore(key?, { onError }) in the browser, createMemoryCollectionStore() for tests; isCollection checks one read back, and migrateCollection brings one of an older COLLECTION_VERSION up (collectionMigrations, one step per bump; there has been one version). The store keeps its list as a result store does: a collection of an older version is written back migrated, and anything it does not know is written back exactly as it was found.

    import { collect, createLocalStorageCollectionStore } from '@hiyve/music-games';

    const store = createLocalStorageCollectionStore();
    const book = await store.load('player-1');
    const { collection, added } = collect(book, ['express:treble:1'], 3);
    await store.save(collection);

    midiName(midi) names a MIDI note with its octave, a natural where it can be ('G4', 'F#4'): the name of a catch card caught by ear.

    Frog Band is a show of songs played with a band, call and response on the beat. startBand({ level, songs }, seed) deals a show (BandShow): three songs (songs, 1–8) in the level's time signatures — the first in 4/4, every other one of the level's before any comes round again — each in a key with a little chord progression for the backing (BandSong: meter, barBeats, beat — a dotted quarter in 6/8 — key, chords), and four rounds each (bandRoundKinds): 'beat', a steady beat to keep; 'echo', a bar the band plays (calls) to tap back; 'read', a written bar (pattern) to play as it comes; and 'answer', the band's question to answer with a bar of the player's own. Every round (BandRound) is laid out in quarter-note beats from the start of its first count-in: the taps due (BandNote: at, value, length, its place in the bar index, and which time round pass), the bars the player plays (turns, the first at turn), the count-ins (countIns, each countIn long — one bar, or two of 2/4 and 6/8) and how long it is (length). Every bar the player plays comes straight after a count-in: at the start of a round, and again after the band's bar in an echo (band's bar, count-in, player's bar, as many times as the level repeats it) and an answer (count-in, question, count-in, answer). The metronome clicks on every beat of the round (clicks, BandClick: at, accent on each bar's first beat, count — the number counted in a count-in — and in 6/8 light sub ticks on the eighths between the two big beats); bandClicks(meter, from, length, counting) lays out the clicks of any stretch. Every round is also a card of the show's deck — tap-the-beat cards and an answer-the-rhythm card — so show.deck scores and keeps like any deck (show.deckSettings with deckRecord; bandDeckSettings(settings, seed) gives the same settings without dealing the show), and the same settings and seed deal the same show. defaultBandSettings (three songs at level 1), mergeBandSettings and bandLevel (any number kept to 1–5, level 1 when there is none) complete the settings, which also take a tempo and the meters of the songs in place of the level's. bandBeat(meter) is the beat a time signature is counted in, in quarter-note beats (1.5 in 6/8, else 1); bandCountInBars(meter) the bars of count-in (two for a bar of only two beats, 2/4 and 6/8, else one); bandBarNotes(pattern) the notes of a bar's pattern from its start — one for each value that is not a rest, two for a pair of eighths.

    bandLevelSettings sets the level: the tempo, the Perfect and Good windows (a share of a beat either side), the time signatures (4/4, then 3/4, 2/4 and at level 5 6/8), the note values of the bars (halves and quarters, then eighths, rests, dotted rhythms), the values and rules of a made-up answer (as the answer-the-rhythm card's presets), the bars of beat to keep, whether the echo and the bar to read come round twice, the crowd, whether long notes are held, and whether the bar to read is drawn on the lane as well as the board (laneNotes: level 1 only; from level 2 it is read from the board). bandWindows(level, tempo) gives the windows in milliseconds. bandJudgeTap(due, played, at, windows) says which note a tap plays — the nearest still to play whose window holds it, never more than half way to its neighbour — and how well (BandJudgement: 'perfect', 'good', 'miss'); bandMissedBy finds the notes whose window has closed; bandJudgeTaps judges a round's taps at once; bandInTime says a round was played in time (three notes in four, few stray taps); bandHeld and bandHoldable judge a long note held to its end. A made-up answer is tapped against the metronome after its count-in and played on the bar's beat grid — eighths, or quarters when the answer's values have nothing shorter (bandAnswerGrid): bandJudgeGridTap(at, grid, level) judges a tap against the nearest point of the grid, and bandAnswerTaps(card, taps, level) judges a bar of taps and writes the points tapped as the card's values (values), a second tap on one point left out (extra). bandSettle(deck, round, answer, right, tries) settles a round on the deck.

    The crowd's meter (0–1) moves with every note: bandCrowd(meter, event, level) adds a Perfect, a Good or an answer that keeps the rules and takes away a miss or a stray tap, never below the level's floor; bandCrowdLeft(meter, level, played) says the crowd has drifted away — only at levels 4 and 5, and never before the first song is over — and bandCrowdDrifting warns that it is about to. BandTally — from emptyBandTally, with bandTally and bandPoints — counts the notes played Perfect and Good, the misses, the notes in a row and the points. Stars count the notes played in time — Perfect or Good — over the notes asked for and the taps of made-up bars (bandHitRate), with the usual thresholds: three from 95%, two from 70%, one from 40% (bandStars). bandSummary(deck, tally) sums a show up: rounds in time, notes played, hitRate, points (the rounds' and the notes') and stars. Every show finished brings a player into the band, kept in a collection like Note Express's wagon book: bandMembers (a shaker turtle, a bass frog, a flute bird, a banjo frog, a marimba newt, in the order they join, as bandParts lists the parts; BandMember: id, part, animal and the General MIDI instrument it is sampled from), bandNextMember(collection), bandMembersIn(collection) and bandMemberId(part); bandBacking(song, bar, parts) says what each part in the band plays over a bar (BandSound), so the band sounds fuller as it grows.

    import { bandJudgeTap, bandRounds, bandWindows, startBand } from '@hiyve/music-games';

    const show = startBand({ level: 2 }, 42);
    const beatMs = 60000 / show.tempo;
    const round = bandRounds(show)[0]!;
    const due = round.taps.map((note) => note.at * beatMs);
    const hit = bandJudgeTap(due, [], due[0]! + 20, bandWindows(show.level, show.tempo)); // { index: 0, judgement: 'perfect', offsetMs: 20 }

    Balloon Ride is a listening game in the sky: a flight is a row of cloud gates, and each gate asks one listening question. startFlight({ level, gates, questions, listen }, seed) makes a flight (BalloonFlight): its gates (BalloonGate), each with a listen card (card: its sound, its answer and its choices), an opening for each choice (choices, the highest first — BalloonChoice: the answer, how the balloon is steered there (steer, a BalloonSteer), how high it is (altitude, 0 to 1) and how it is chosen (press: 'tap', or 'hold' for a long note)), how high the balloon waits before it (start) and what the meadow shows below it (landmark, one of balloonLandmarks). A gate asks one of balloonQuestions: higher or lower (rise or sink, or fly straight on for the same), loud or soft (a big flame or a little one), fast or slow (ride the gust, or drift under the bridge), long or short (hold the burner, or tap it — balloonPressAnswer(gate, heldMs) reads a press, long from balloonHoldMs), step or leap (a big lift or a small one), the same or different (between the two birds, or under them), and major or minor (into the sunshine, or under the rain cloud); balloonChoices(card) makes the openings for any listening card and says which answers cannot be steered; balloonChoiceFor(gate, answer) finds a gate's opening for an answer, or undefined when the gate does not offer it. The first gate asks the level's first question; after it every question comes in turn, shuffled, never one twice in a row, and the openings are balanced, so steering the same way every time never wins. The same settings and seed make the same flight; flight.deck holds the gates' cards as a deck (flight.deckSettings with deckRecord), so a flight scores and keeps like any deck.

    balloonLevelSettings sets each level's gates (twelve), questions and sounds together: higher or lower and loud or soft at level 1, an octave apart and very soft or very loud; fast or slow and long or short at level 2; step or leap at 3; the same or different (and "the same" among higher and lower) at 4; major or minor at 5 — each question's sounds closer as the levels climb, never so close they are hard to tell apart (two notes at least a whole step apart, a 3rd once "the same" joins; a long note at least four times a short one). mergeBalloonSettings lays settings over the level's (listen field by field); defaultBalloonSettings is a flight at level 1; balloonLevel keeps a level to 1–5 (level 1 when there is none).

    answerGate(flight, answer, elapsedMs) steers the gate in front of the balloon: one steer a gate, right or wrong, and the balloon flies on (currentGate, flightLanded). A right steer catches a star (flight.stars); a wrong one bumps a cloud (flight.bumps). balloonSummary(flight) sums it up: gates flown, stars and bumps, the gates' score (scoreDeck), the stars' bonus (balloonStarPoints each) and how each question went.

    Skies. Every player flies the day sky; landing with balloonSkyStars stars or more wins the next of dawn, sunset and night (balloonSkies) — dawn at any level, sunset from level 2, night from level 3 (balloonSkyLevels) — kept in a Collection as the player's skies: balloonSkyId(sky), balloonSkiesOpen(collection), balloonNextSky(collection) and balloonSkyWon(collection, stars, level).

    import { answerGate, balloonSummary, currentGate, startFlight } from '@hiyve/music-games';

    let flight = startFlight({ level: 2 }, 42);
    const gate = currentGate(flight)!; // gate.card.sound to play, gate.choices to steer through
    flight = answerGate(flight, gate.choices[0]!.answer, 2400);
    const summary = balloonSummary(flight); // { flown: 1, stars: 0 or 1, ... }

    Potion Lab is an owl wizard's lab where forest customers come to the hatch with orders, and each potion is brewed note by note. startPotionLab({ level, topic, orders, rareOrders, tries, candleSeconds, recipes, rareRecipes }, seed) deals a session (PotionLab): its orders (PotionOrder) in the order the customers arrive — the level's regular orders (six), every one to be brewed, and its rare orders (two), each coming in a few arrivals after the last — with three waiting at the hatch at once (POTION_HATCH) and the rest in the queue. An order (kind, one of potionOrderKinds) asks for a chord by its root and quality ('chord'), by its symbol ('symbol', 'Am'), as a key's tonic chord ('tonicChord') or as I, IV or V of a key ('numeral'); a scale up from its tonic ('scale': major, or harmonic minor for a minor key); the sharps or flats of a key's signature ('signature', its notes as potionSignatureNotes(fifths) gives them: in the octave from middle C, in the order they are written); the keynote of the minor key that shares a major key's signature ('relative'); or a taste by ear, major or minor ('taste'). It carries what it names (root, quality, symbol, numeral, degree, key, answerKey, scale, fifths), the notes to brew, spelled (in order for a scale, ordered), how it is answered (pad: 'keys', 'staff' with its clef, or 'taste'), the potion as it plays once brewed (sound, ending struck together for a chord, chord), its tries, its bottle in the potion book (bottle), its customer (customer, 0 to POTION_CUSTOMERS − 1, six of them) and its liquid's colour (colour, 0 to POTION_COLOURS − 1, seven, there for charm only). Every order is a card of the lab's deck, dealt from the existing card makers — build a chord (chordBuild) for every chord, a scale (scaleId), a key signature (keySignatureId) for a key's sharps or flats and for a relative minor, a listening card (listen, major or minor) for a taste — so the session scores and keeps like any deck (deckRecord(lab.deck, lab.deckSettings), potionDeckSettings), and the same settings and seed deal the same session.

    potionLevelSettings sets what each level asks: major chords on C, F and G and tasting major or minor (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 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) — with each level's recipes (PotionRecipe, data a host can give its own — a chord placed on the staff takes its sharps and flats from the key signature alone, so one it cannot spell is refused), the rare orders' recipes from the level above, the tries, how long a rare customer waits (rareWait), the rare bonus (rarePoints) and the candle (candleSeconds, none at levels 1 and 2). topic (potionTopics, potionTopicOf) keeps a session to chords or to keys and scales, from the nearest levels when its own has too few (potionTopicRecipes). mergePotionSettings, defaultPotionSettings and potionLevel complete the settings.

    Brewing: choosePotionOrder(lab, order) takes an order from the hatch onto the fire (brewing, a PotionBrew; potionBrewingOrder(lab) is the order on it, or null), and putBackPotionOrder puts it back before a note goes in. dropPotionNote(lab, midi) drops a note in — a key tapped, or a note placed on the staff (potionStaffMidi reads one under a key signature) — and judges it (PotionDrop, its verdict): kept in the brew, a note in already (no cost), wrong — a try, with a hint in music words (PotionHint: the other 3rd for the chord's quality, a 5th that is not perfect, a note not stacked in 3rds, a chord symbol's quality, the chord's root, a scale's first note, a sharp or flat missed, a letter skipped, harmonic minor's raised 7th, the order of sharps or flats, where the relative minor starts) — brewed (the last right note), or spoiled (the last try), each settling the order's round. tastePotion(lab, 'major' | 'minor') answers a taste. potionNoteName spells a note as an order does (F♯ in G major) and potionHint explains any wrong note. Each brew keeps every key tapped, right and wrong, in order (taps; a note in already is left out), so a host can keep exactly what was played even where the order's round keeps only the key or scale named. servePotionOrder(lab) hands the potion over (the brew joins lab.brews, in the order handed over): its customer leaves, the next arrives, every rare customer waiting has waited one brew more and leaves after the lab's rareWait, and once no regular order is left the rare ones go home too (PotionServe). closePotionLab closes the lab as the candle burns out. potionLabDone and potionLabFinished (every regular order brewed) say when it is over; potionPlayedDeck is the orders brewed as a finished deck, and potionSummary sums a session up (PotionSummary: orders, brewed, right, rare brewed and gone, the brews' points, the rare bonus, stars).

    The potion book. potionBook lists every kind of potion (PotionBottle) shelf by shelf (potionShelves): fifteen chord potions, ten scale potions, six key signature potions, six relative minor potions, and the two tasted by ear. Each kind brewed right for the first time is kept in a Collection like the wagon book: potionChordId, potionBottlesIn(collection) and potionBottlesBrewed(lab) (a session's right brews, each kind once).

    import { choosePotionOrder, dropPotionNote, potionBrewingOrder, servePotionOrder, startPotionLab } from '@hiyve/music-games';

    let lab = startPotionLab({ level: 1 }, 42);
    const chord = lab.hatch.find((index) => index !== null && lab.orders[index]!.pad === 'keys')!; // an order brewed on the keys
    lab = choosePotionOrder(lab, chord);
    const order = potionBrewingOrder(lab)!; // order.notes: the chord's notes, spelled — F, A and C for F major
    for (const note of order.notes) lab = dropPotionNote(lab, note.midi).lab;
    lab = servePotionOrder(lab).lab; // the next customer comes to the hatch

    staffPosition(clef, pitch) is where a note sits, counted in lines and spaces from the bottom line: 0 is the bottom line, 1 the first space, 8 the top line, −2 the first ledger line below and 10 the first above. pitchAtPosition(clef, position) reads the natural back. isLedgerPosition says when a position needs a ledger line. clefBottomLine gives each clef's bottom-line note: E4 for treble, G2 for bass, F3 for alto, D3 for tenor.

    noteFromText(text) reads a note written as text — a letter, a sharp (# or ♯), a flat (b or ♭) or a natural (♮ or n), and an octave: 'C4', 'F#4', 'Bb3', 'C♯5', 'F♮4' — as a Pitch, or null if it is not one; a natural reads as the plain letter. wordLetters(word) gives a word's letters, capitalised, or null when any letter is not A to G.

    createRandom(seed) is a small seeded random source — the random every maker takes — and newSeed() gives a fresh seed; the same seed always deals the same cards. Both come from @hiyve/music-theory, given here so a consumer needs only this package.

    defaultSpellingWords (Bee, Ace, Feed, Face, Bed, Bag … Cabbage), defaultMusicTerms (sixty terms: ppp to fff, Grave to Prestissimo, staccato, legato, fermata, dolce, cantabile, D.C., D.S., 8va …; musicTermsOf(codes) picks a few; musicTermTwins groups the terms whose meanings are near enough to pick either — lento's "Slowly" and adagio's "Slow" — and no card offers one beside another of its group, nor puts two of a group on one table or row of targets, unless nothing else is left; musicSymbolTwins does the same for symbols that mean the same, common time and 4/4 time; areTwins(groups, a, b) says whether two codes are twins), defaultSymbolLegend (A is a quarter note, B a half rest, C a bass clef … Z a repeat sign), defaultSymbolWords, noteValueBeats, noteValueSymbol, noteValues (notes and rests; noteValuesNotes, noteValuesRests), musicSymbols (fifty-one: notes, rests, clefs, accidentals to the double sharp and flat, time signatures (common time drawn as a C, fourFourTime as 4 over 4), bar lines and repeats, coda and segno, fermata, articulations, ornaments, hairpins, tie, slur, pedal, breath mark and caesura; basicMusicSymbols for the first thirteen), knownTimeSignatures with timeSignatureBeats, timeSignatureParts, compoundBeat and beatNoteOf (the note a signature's bottom number counts in), motions, defaultKeyboardRange, and default…Settings and merge…Settings for every kind (see Makers, checkers and defaults).

    Every type is exported for TypeScript. Each card kind has its …Settings (what its maker takes) and its …Card (what it makes), and most an …Answer too.

    Area Types
    Music Clef, Pitch, Step, NoteValue, TimeSignature, MusicSymbol, SymbolLegend, ChordQuality, IntervalQuestion, ChordQuestion, KeySignatureQuestion, NoteQuestion, ScaleQuestion, KeyInfo, TermCategory, MusicTerm
    Any card GameKind, Level, Leveled, CardSettings, SettingsByKind, LevelPresets, GameCard, GameAnswer, AnswerFor, ChoiceAnswer
    Staff and theory cards SpellOnStaffSettings, SpellOnStaffCard, SpellOnStaffAnswer, IntervalIdSettings, IntervalIdCard, IntervalAsk, IntervalShape, IntervalIdAnswer, NoteNameIdSettings, NoteNameIdCard, AccidentalSpelling, BarRuleSign, ChordQualityIdSettings, ChordQualityAsk, ChordQualityIdCard, KeySignatureIdSettings, KeySignatureIdCard, ScaleIdSettings, ScaleIdCard, Motion, StepSkipSettings, StepSkipCard, LineOrSpace, LineOrSpaceSettings, LineOrSpaceCard, IntervalBuildSettings, IntervalBuildCard, IntervalBuildAnswer, TieOrSlur, TieOrSlurSettings, TieOrSlurCard, ScaleDegreeMode, ScaleDegreeSettings, ScaleDegreeCard, ScaleDegreeAnswer, ChordNaming, ChordNameSettings, ChordNameCard
    Keyboard cards KeyboardRange, KeyNames, KeyboardNoteIdSettings, KeyboardNoteIdCard, KeyboardNoteIdAnswer, KeyboardFindSettings, KeyboardFindCard, KeyboardFindAnswer, ChordBuildSettings, ChordBuildCard, ChordBuildAnswer, KeyboardSpellingSettings, KeyboardSpellingCard, KeyboardSpellingAnswer
    Symbols, terms and spelling SymbolSpellingSettings, SymbolSpellingCard, SymbolSpellingAnswer, SymbolIdSettings, SymbolIdCard, TermIdSettings, TermIdCard, LetterStepDirection, LetterStepSettings, LetterStepCard
    Rhythm and time RhythmMathSettings, RhythmOperator, RhythmMathCard, RhythmMathAnswer, RhythmFillSettings, RhythmFillCard, RhythmFillAnswer, TimeSignatureIdSettings, TimeSignatureIdCard, TimeSignatureIdBarsCard, TimeSignatureIdBottomCard, TimeSignatureIdStrongCard, TimeSignatureAsk, BeatStrength, BarLinesSettings, BarLinesCard, BarLinesAnswer
    Content games Display, ContentKind, Fact, ContentSettings, CatchSettings, CatchCard, CatchAnswer, HopSettings, HopCard, HopAnswer, MemoryMatchSettings, MemoryMatchCard, MemoryMatchAnswer, OrderSettings, OrderCard, OrderAnswer
    Listening and tapping ListenQuestion, ListenDirection, ListenDynamic, ListenTouch, ListenSpeed, ListenLength, ListenAnswer, ListenComparison, ListenChange, ListenQuality, ListenHarmony, ListenSettings, ListenCard, ListenTune, Loudness, BeatTapMode, BeatTapSettings, BeatTapCard, BeatTapAnswer, BeatTapVerdict
    Songs TuneNote, Tune, TuneSign, TuneSettings, TuneQuestionKind, TuneQuestion, TuneQuestionsSettings, TuneQuestionsCard, TuneQuestionsAnswer, RhythmAnswerRule, RhythmAnswerSettings, RhythmAnswerCard, RhythmAnswerAnswer, RhythmAnswerProblem, FinishTuneRule, FinishTuneSettings, FinishTuneCard, FinishTuneAnswer, FinishTuneProblem
    Decks DeckSettings, DeckOptions, DeckRound, DeckState, DeckAnswer, DeckRecord, DeckSummary
    Scores and results ScoreOptions, Score, PassOptions, PlayMode, GameResult, GameResultQuery, ResultStore, ResultStoreAdapter, ResultStoreOptions, LocalStoreOptions, MissedCard, MissedExtra
    Practice PracticeTopicId, PracticePicture, PracticeTopic, PracticeRow, PracticeSetOptions, PracticeMissedCard
    Trails TrailSettings, TrailCourseSettings, TrailCourse, TrailCell, TrailTrap, TrailTrapState, TrailMove, TrailState
    Note Express ExpressLevelSettings, ExpressMode, ExpressScene, ExpressWave, ExpressGoldenWagon, ExpressTally, ExpressTopic, ExpressWagonBody, ExpressWagonPaint, ExpressWagon
    Collections CollectedItem, Collection, CollectionStore, CollectionStoreAdapter
    Frog Band BandRoundKind, BandCrowdSettings, BandLevelSettings, BandSettings, BandKey, BandChord, BandNote, BandRound, BandTurn, BandClick, BandSong, BandShow, BandJudgement, BandWindows, BandHit, BandGridTap, BandCrowdEvent, BandTally, BandSummary, BandPart, BandMember, BandSound
    Balloon Ride BalloonQuestion, BalloonSteer, BalloonChoice, BalloonLandmark, BalloonGate, BalloonLevelSettings, BalloonSettings, BalloonFlight, BalloonSummary, BalloonSky
    Potion Lab PotionOrderKind, PotionTopic, PotionQuality, PotionPad, PotionRecipe, PotionLevelSettings, PotionSettings, PotionShelf, PotionBottle, PotionOrder, PotionBrew, PotionLab, PotionHint, PotionVerdict, PotionDrop, PotionServe, PotionSummary
    • Node 18 or later, or any modern browser. Pure data: no DOM, no audio.
    • @hiyve/music-theory installed alongside: a peer dependency (^0.1.0 || ^0.2.0).

    Interfaces

    BalloonChoice
    BalloonFlight
    BalloonGate
    BalloonLevelSettings
    BalloonSettings
    BalloonSummary
    BandChord
    BandClick
    BandCrowdSettings
    BandGridTap
    BandHit
    BandLevelSettings
    BandMember
    BandNote
    BandRound
    BandSettings
    BandShow
    BandSong
    BandSound
    BandSummary
    BandTally
    BandTurn
    BandWindows
    BarLinesCard
    BarLinesSettings
    BeatTapCard
    BeatTapSettings
    CatchCard
    CatchSettings
    ChordBuildCard
    ChordBuildSettings
    ChordNameCard
    ChordNameSettings
    ChordQualityIdCard
    ChordQuestion
    CollectedItem
    Collection
    CollectionStore
    CollectionStoreAdapter
    ContentSettings
    DeckAnswer
    DeckOptions
    DeckRecord
    DeckRound
    DeckSettings
    DeckState
    DeckSummary
    ExpressGoldenWagon
    ExpressLevelSettings
    ExpressTally
    ExpressWagon
    ExpressWave
    Fact
    FinishTuneCard
    FinishTuneSettings
    GameResult
    GameResultQuery
    HopCard
    HopSettings
    IntervalBuildCard
    IntervalBuildSettings
    IntervalIdCard
    IntervalIdSettings
    IntervalQuestion
    KeyboardFindCard
    KeyboardFindSettings
    KeyboardNoteIdCard
    KeyboardNoteIdSettings
    KeyboardRange
    KeyboardSpellingCard
    KeyboardSpellingSettings
    KeyInfo
    KeySignatureIdCard
    KeySignatureQuestion
    LetterStepCard
    LetterStepSettings
    Leveled
    LineOrSpaceCard
    LineOrSpaceSettings
    ListenCard
    ListenSettings
    ListenTune
    LocalStoreOptions
    MemoryMatchCard
    MemoryMatchSettings
    MissedCard
    MissedExtra
    MusicTerm
    NoteNameIdCard
    NoteQuestion
    OrderCard
    OrderSettings
    PassOptions
    Pitch
    PotionBottle
    PotionBrew
    PotionDrop
    PotionLab
    PotionLevelSettings
    PotionOrder
    PotionServe
    PotionSettings
    PotionSummary
    PracticeMissedCard
    PracticeRow
    PracticeSetOptions
    PracticeTopic
    ResultStore
    ResultStoreAdapter
    ResultStoreOptions
    RhythmAnswerCard
    RhythmAnswerSettings
    RhythmFillCard
    RhythmFillSettings
    RhythmMathCard
    RhythmMathSettings
    ScaleDegreeCard
    ScaleDegreeSettings
    ScaleIdCard
    ScaleQuestion
    Score
    ScoreOptions
    SettingsByKind
    SpellOnStaffCard
    SpellOnStaffSettings
    StepSkipCard
    StepSkipSettings
    SymbolIdCard
    SymbolIdSettings
    SymbolSpellingCard
    SymbolSpellingSettings
    TermIdCard
    TermIdSettings
    TieOrSlurCard
    TieOrSlurSettings
    TimeSignatureIdBarsCard
    TimeSignatureIdBottomCard
    TimeSignatureIdSettings
    TimeSignatureIdStrongCard
    TrailCell
    TrailCourse
    TrailCourseSettings
    TrailMove
    TrailSettings
    TrailState
    TrailTrapState
    Tune
    TuneNote
    TuneQuestion
    TuneQuestionsCard
    TuneQuestionsSettings
    TuneSettings

    Type Aliases

    AccidentalSpelling
    AnswerFor
    BalloonLandmark
    BalloonQuestion
    BalloonSky
    BalloonSteer
    BandCrowdEvent
    BandJudgement
    BandKey
    BandPart
    BandRoundKind
    BarLinesAnswer
    BarRuleSign
    BeatStrength
    BeatTapAnswer
    BeatTapMode
    BeatTapVerdict
    CardSettings
    CatchAnswer
    ChoiceAnswer
    ChordBuildAnswer
    ChordNaming
    ChordQuality
    ChordQualityAsk
    ChordQualityIdSettings
    Clef
    ContentKind
    Display
    ExpressMode
    ExpressScene
    ExpressTopic
    ExpressWagonBody
    ExpressWagonPaint
    FinishTuneAnswer
    FinishTuneProblem
    FinishTuneRule
    GameAnswer
    GameCard
    GameKind
    HopAnswer
    IntervalAsk
    IntervalBuildAnswer
    IntervalIdAnswer
    IntervalShape
    KeyboardFindAnswer
    KeyboardNoteIdAnswer
    KeyboardSpellingAnswer
    KeyNames
    KeySignatureIdSettings
    LetterStepDirection
    Level
    LevelPresets
    LineOrSpace
    ListenAnswer
    ListenChange
    ListenComparison
    ListenDirection
    ListenDynamic
    ListenHarmony
    ListenLength
    ListenQuality
    ListenQuestion
    ListenSpeed
    ListenTouch
    Loudness
    MemoryMatchAnswer
    Motion
    MusicSymbol
    NoteNameIdSettings
    NoteValue
    OrderAnswer
    PlayMode
    PotionHint
    PotionOrderKind
    PotionPad
    PotionQuality
    PotionRecipe
    PotionShelf
    PotionTopic
    PotionVerdict
    PracticePicture
    PracticeTopicId
    RhythmAnswerAnswer
    RhythmAnswerProblem
    RhythmAnswerRule
    RhythmFillAnswer
    RhythmMathAnswer
    RhythmOperator
    ScaleDegreeAnswer
    ScaleDegreeMode
    ScaleIdSettings
    SpellOnStaffAnswer
    Step
    SymbolLegend
    SymbolSpellingAnswer
    TermCategory
    TieOrSlur
    TimeSignature
    TimeSignatureAsk
    TimeSignatureIdCard
    TrailTrap
    TuneQuestionKind
    TuneQuestionsAnswer
    TuneSign

    Variables

    balloonHoldMs
    balloonLandmarks
    balloonLevelSettings
    balloonQuestions
    balloonSkies
    balloonSkyLevels
    balloonSkyStars
    balloonStarPoints
    bandLevelSettings
    bandMembers
    bandParts
    bandPoints
    bandRoundKinds
    basicMusicSymbols
    clefBottomLine
    COLLECTION_VERSION
    collectionMigrations
    DECK_RECORD_VERSION
    deckRecordMigrations
    DEFAULT_RESULT_LIMIT
    defaultBalloonSettings
    defaultBandSettings
    defaultBarLinesSettings
    defaultBeatTapSettings
    defaultCatchSettings
    defaultChordBuildSettings
    defaultChordNameSettings
    defaultChordQualityIdSettings
    defaultContentSettings
    defaultFinishTuneSettings
    defaultHopSettings
    defaultIntervalBuildSettings
    defaultIntervalSettings
    defaultKeyboardFindSettings
    defaultKeyboardNoteIdSettings
    defaultKeyboardRange
    defaultKeyboardSpellingSettings
    defaultKeySignatureIdSettings
    defaultLetterStepSettings
    defaultLineOrSpaceSettings
    defaultListenSettings
    defaultListenTunes
    defaultMemoryMatchSettings
    defaultMusicTerms
    defaultNoteNameIdSettings
    defaultOrderSettings
    defaultPassOptions
    defaultPotionSettings
    defaultPracticeOmit
    defaultRhythmAnswerSettings
    defaultRhythmFillSettings
    defaultRhythmMathSettings
    defaultScaleDegreeSettings
    defaultScaleIdSettings
    defaultScoreOptions
    defaultSpellingWords
    defaultSpellOnStaffSettings
    defaultStepSkipSettings
    defaultSymbolIdSettings
    defaultSymbolLegend
    defaultSymbolSpellingSettings
    defaultSymbolWords
    defaultTermIdSettings
    defaultTieOrSlurSettings
    defaultTimeSignatureIdSettings
    defaultTrailCourseSettings
    defaultTrailSettings
    defaultTuneQuestionsSettings
    defaultTuneSettings
    emptyBandTally
    emptyExpressTally
    expressComboSteps
    expressLevelSettings
    expressPoints
    expressTopics
    expressWagons
    finishTuneRules
    gameKinds
    knownTimeSignatures
    levelPresets
    levels
    listenAnswers
    listenChanges
    listenHarmonies
    listenQuestions
    listenTempoWords
    MAX_DECK_LENGTH
    motions
    musicalAlphabet
    musicSymbols
    musicSymbolTwins
    musicTermTwins
    noteValueBeats
    noteValues
    noteValuesNotes
    noteValuesRests
    noteValueSymbol
    POTION_COLOURS
    POTION_CUSTOMERS
    POTION_HATCH
    potionBook
    potionLevelSettings
    potionOrderKinds
    potionShelves
    potionTopicOf
    potionTopics
    PRACTICE_MISSED
    PRACTICE_MIX
    PRACTICE_SET_SIZE
    practiceRows
    practiceTopics
    rhythmAnswerRules
    trailLevelSettings
    tuneQuestionKinds
    tuneSigns
    tuneSpeedChanges
    tuneTempoBpm

    Functions

    answerDeck
    answerGate
    answerRound
    answerTrail
    areTwins
    balloonChoiceFor
    balloonChoices
    balloonLevel
    balloonNextSky
    balloonPressAnswer
    balloonSkiesOpen
    balloonSkyId
    balloonSkyWon
    balloonSummary
    bandAnswerGrid
    bandAnswerTaps
    bandBacking
    bandBarNotes
    bandBeat
    bandClicks
    bandCountInBars
    bandCrowd
    bandCrowdDrifting
    bandCrowdLeft
    bandDeckSettings
    bandHeld
    bandHitRate
    bandHoldable
    bandInTime
    bandJudgeGridTap
    bandJudgeTap
    bandJudgeTaps
    bandLevel
    bandMemberId
    bandMembersIn
    bandMissedBy
    bandNextMember
    bandRounds
    bandSettle
    bandStars
    bandSummary
    bandTally
    bandWindows
    barLinesBars
    beatNoteOf
    beatTapTimes
    beatTapVerdicts
    bestResult
    checkBarLines
    checkBeatTap
    checkCard
    checkCatch
    checkChoice
    checkChordBuild
    checkChordName
    checkFinishTune
    checkHop
    checkIntervalBuild
    checkIntervalId
    checkKeyboardFind
    checkKeyboardNoteId
    checkKeyboardSpelling
    checkLetterStep
    checkLineOrSpace
    checkListen
    checkMemoryMatch
    checkOrder
    checkRhythmAnswer
    checkRhythmFill
    checkRhythmMath
    checkScaleDegree
    checkSpellOnStaff
    checkSymbolId
    checkSymbolSpelling
    checkTermId
    checkTieOrSlur
    checkTimeSignatureId
    checkTuneQuestions
    choosePotionOrder
    chordNumeralParts
    chordSymbol
    chordSymbolParts
    closePotionLab
    collect
    compoundBeat
    contentFacts
    createBarLinesCard
    createBeatTapCard
    createCard
    createCatchCard
    createChordBuildCard
    createChordNameCard
    createChordQualityIdCard
    createCollectionStore
    createFinishTuneCard
    createHopCard
    createIntervalBuildCard
    createIntervalIdCard
    createKeyboardFindCard
    createKeyboardNoteIdCard
    createKeyboardSpellingCard
    createKeySignatureIdCard
    createLetterStepCard
    createLineOrSpaceCard
    createListenCard
    createLocalStorageCollectionStore
    createLocalStorageResultStore
    createMemoryCollectionStore
    createMemoryMatchCard
    createMemoryResultStore
    createNoteNameIdCard
    createOrderCard
    createRandom
    createResultStore
    createRhythmAnswerCard
    createRhythmFillCard
    createRhythmMathCard
    createScaleDegreeCard
    createScaleIdCard
    createSpellOnStaffCard
    createStepSkipCard
    createSymbolIdCard
    createSymbolSpellingCard
    createTermIdCard
    createTieOrSlurCard
    createTimeSignatureIdCard
    createTune
    createTuneQuestionsCard
    currentGate
    deckRecord
    deckSummary
    degreeNotes
    displayMidi
    dropPotionNote
    emptyAnswer
    emptyCollection
    expressAccuracy
    expressComboMultiplier
    expressDeckLevel
    expressDeckMode
    expressDeckSettings
    expressDeckTopic
    expressDeckWagon
    expressDefaultMode
    expressGoldenWagon
    expressGoldenWagons
    expressHook
    expressHookPoints
    expressLevel
    expressMiss
    expressNotesDeck
    expressRoundCredit
    expressScore
    expressTopicOf
    expressWagonId
    expressWagonOf
    expressWagonsToHook
    expressWaves
    expressWaveSettings
    fillBar
    finishDeck
    finishTuneProblems
    flightLanded
    gameResult
    generateTrailCourse
    hasCollected
    intervalNumber
    isAnswerComplete
    isCollection
    isDeckFinished
    isDeckRecord
    isDeckSettled
    isGameResult
    isLedgerPosition
    judgesLive
    keyboardHighestMidi
    keyboardSpellingMarks
    keyInfo
    keyScale
    keySignatureAlter
    keysOfLetter
    letterAlong
    letterPlace
    letterStepWraps
    levelSettings
    lineOrSpaceAt
    longEnough
    mergeBalloonSettings
    mergeBandSettings
    mergeBarLinesSettings
    mergeBeatTapSettings
    mergeCatchSettings
    mergeChordBuildSettings
    mergeChordNameSettings
    mergeChordQualityIdSettings
    mergeContentSettings
    mergeFinishTuneSettings
    mergeHopSettings
    mergeIntervalBuildSettings
    mergeIntervalSettings
    mergeKeyboardFindSettings
    mergeKeyboardNoteIdSettings
    mergeKeyboardSpellingSettings
    mergeKeySignatureIdSettings
    mergeLetterStepSettings
    mergeLineOrSpaceSettings
    mergeListenSettings
    mergeMemoryMatchSettings
    mergeNoteNameIdSettings
    mergeOrderSettings
    mergePassOptions
    mergePotionSettings
    mergeRhythmAnswerSettings
    mergeRhythmFillSettings
    mergeRhythmMathSettings
    mergeScaleDegreeSettings
    mergeScaleIdSettings
    mergeScoreOptions
    mergeSpellOnStaffSettings
    mergeStepSkipSettings
    mergeSymbolIdSettings
    mergeSymbolSpellingSettings
    mergeTermIdSettings
    mergeTieOrSlurSettings
    mergeTimeSignatureIdSettings
    mergeTrailSettings
    mergeTuneQuestionsSettings
    mergeTuneSettings
    midiName
    migrateCollection
    migrateDeckRecord
    migrateGameResult
    missedCards
    motionBetween
    musicTermsOf
    newResultId
    newSeed
    nextCard
    noteFromText
    patternOnsets
    pinnedCard
    pitchAtPosition
    potionBottlesBrewed
    potionBottlesIn
    potionBrewingOrder
    potionChordId
    potionDeckSettings
    potionHint
    potionLabDone
    potionLabFinished
    potionLevel
    potionNoteName
    potionPlayedDeck
    potionSignatureNotes
    potionStaffMidi
    potionSummary
    potionTopicRecipes
    practiceDeals
    practiceGameCards
    practiceMissedCards
    practiceRow
    practiceRowFrom
    practiceRowsOf
    practiceSet
    practiceStamp
    practiceTopicById
    practiceTopicOfCard
    putBackPotionOrder
    readPracticeStamp
    repeatCards
    restoreDeck
    resultOf
    rhythmAnswerProblems
    rhythmFromTaps
    sameBeats
    scoreDeck
    selectResults
    servePotionOrder
    settlesOnChoice
    spellOnStaffMarks
    staffPosition
    starsFor
    startBand
    startDeck
    startFlight
    startPotionLab
    startTrail
    stepPassed
    symbolSpellingMarks
    tastePotion
    timeSignatureBeats
    timeSignatureParts
    toPracticeLevel
    trailProgress
    trailSummary
    tuneBarBeats
    tuneBarOf
    tuneBarsFull
    tuneNoteBpm
    tunePatterns
    tunePlayOrder
    uniqueByName
    valuesForSignature
    withLevel
    wordLetters