@vibechain/os 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/AGENTS.md +52 -11
  2. package/README.md +115 -20
  3. package/SECURITY.md +6 -4
  4. package/dist/app-client.js +20 -4
  5. package/dist/app-host.d.ts +74 -5
  6. package/dist/app-host.js +94 -6
  7. package/dist/app-protocol.d.ts +21 -0
  8. package/dist/app-protocol.js +9 -0
  9. package/dist/app-wire.d.ts +186 -6
  10. package/dist/app-wire.js +213 -7
  11. package/dist/audio.d.ts +65 -0
  12. package/dist/audio.js +162 -0
  13. package/dist/browser.d.ts +2 -1
  14. package/dist/browser.js +2 -1
  15. package/dist/bundle.d.ts +2 -0
  16. package/dist/bundle.js +5 -3
  17. package/dist/check.js +11 -4
  18. package/dist/cli.js +3 -1
  19. package/dist/commands.d.ts +6 -0
  20. package/dist/commands.js +17 -0
  21. package/dist/fake-services.d.ts +88 -0
  22. package/dist/fake-services.js +132 -0
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +1 -1
  25. package/dist/links.d.ts +13 -0
  26. package/dist/links.js +17 -1
  27. package/dist/listing.d.ts +12 -0
  28. package/dist/listing.js +49 -1
  29. package/dist/manifest.d.ts +76 -1
  30. package/dist/manifest.js +170 -5
  31. package/dist/os.d.ts +83 -5
  32. package/dist/os.js +179 -15
  33. package/dist/preview-parent.d.ts +21 -2
  34. package/dist/preview-parent.js +101 -8
  35. package/dist/preview-surfaces.d.ts +36 -0
  36. package/dist/preview-surfaces.js +84 -0
  37. package/dist/preview-ui.js +1 -1
  38. package/dist/preview.js +4 -2
  39. package/dist/templates/plain/game.js +3 -1
  40. package/dist/testing.d.ts +50 -7
  41. package/dist/testing.js +137 -13
  42. package/dist/transport.d.ts +4 -1
  43. package/dist/transport.js +2 -2
  44. package/dist/vibemarket-os.js +1 -1
  45. package/examples/paw-beat/README.md +38 -10
  46. package/examples/paw-beat/cat.ts +13 -0
  47. package/examples/paw-beat/game.ts +290 -123
  48. package/examples/paw-beat/index.html +20 -4
  49. package/examples/paw-beat/main.ts +156 -48
  50. package/examples/paw-beat/music.ts +72 -337
  51. package/examples/paw-beat/stage.ts +23 -9
  52. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  53. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  54. package/examples/paw-beat/synth.ts +477 -0
  55. package/examples/paw-beat/tracks.ts +286 -0
  56. package/examples/paw-beat/vibemarket.json +15 -8
  57. package/examples/vibexp-app/plain/game.ts +6 -2
  58. package/package.json +7 -1
  59. package/skill.md +471 -0
@@ -2,88 +2,252 @@
2
2
  * Paw Beat rules. Pure TypeScript: no DOM, no renderer, no audio, no SDK. main.ts feeds
3
3
  * in the song clock and key presses and reads state out, so every rule is unit-testable.
4
4
  *
5
- * The song's shape lives here too, as plain data: its sections and its lead melody. music.ts
6
- * plays them, createChart writes the steps from them and the stage colours itself by them,
7
- * so what you hear, what you press and what you see cannot drift apart.
5
+ * A track is plain data (tracks.ts): its tempo and meter, its sections with their chords, and
6
+ * its tune written as note names. These rules read that data to lay the song out in time,
7
+ * to write the steps the player presses, and to pick the next track; synth.ts reads the same
8
+ * data to play it. What you hear, what you press and what you see cannot drift apart.
8
9
  */
9
10
 
10
11
  export const LANES = ["left", "down", "up", "right"] as const;
11
12
  export type Lane = typeof LANES[number];
12
13
 
13
- export const BPM = 120;
14
- export const BEAT_SECONDS = 60 / BPM;
15
- export const BEATS_PER_BAR = 4;
16
- /** One bar of count-in clicks, then 28 bars of song: just under a minute in all. */
17
- export const COUNT_IN_BEATS = 4;
18
- export const SONG_BEATS = 116;
19
- export const SONG_SECONDS = SONG_BEATS * BEAT_SECONDS;
20
14
  /** The host accepts integer scores up to this value. */
21
15
  export const SCORE_LIMIT = 1_000_000_000;
16
+ /** No two steps (other than the two paws of a jump) are ever closer than this, in seconds. */
17
+ export const MIN_STEP_GAP = 0.2;
22
18
 
23
- // ---- The song's sections ----
24
-
25
- export type SectionName = "count-in" | "intro" | "build" | "drop" | "breakdown" | "finale" | "outro";
26
- export interface Section { readonly name: SectionName; readonly start: number; readonly beats: number }
27
- /** In order, back to back, from beat 0 to SONG_BEATS. */
28
- export const SECTIONS: readonly Section[] = [
29
- { name: "count-in", start: 0, beats: 4 },
30
- { name: "intro", start: 4, beats: 16 },
31
- { name: "build", start: 20, beats: 16 },
32
- { name: "drop", start: 36, beats: 32 },
33
- { name: "breakdown", start: 68, beats: 16 },
34
- { name: "finale", start: 84, beats: 24 },
35
- { name: "outro", start: 108, beats: 8 },
36
- ];
19
+ // ---- Tracks: the data ----
20
+
21
+ /**
22
+ * What a section does in the song. The stage, the chart and the cat's energy follow the role:
23
+ * the steps stay on the beat until the first drop, and jumps belong to the finale and outro.
24
+ */
25
+ export type SectionRole = "count-in" | "intro" | "build" | "drop" | "break" | "finale" | "outro";
26
+ /**
27
+ * How a section's steps are written: on beats 1 and 3, on every beat, from the tune, from the
28
+ * tune with the beat filling the gaps where it rests ("groove", for airy tunes), or none.
29
+ */
30
+ export type StepStyle = "half" | "beat" | "tune" | "groove" | "none";
31
+ /** Which instrument carries the tune in a section: the track's main lead, its second lead, a pluck or a bell. */
32
+ export type Voice = "lead" | "lead2" | "pluck" | "bell";
33
+
34
+ export interface TrackSection {
35
+ readonly role: SectionRole;
36
+ /** What the player sees: "Verse", "Chorus"… */
37
+ readonly label: string;
38
+ readonly bars: number;
39
+ /** Chord names, one per bar ("F,G" shares a bar), repeated to fill the section: "Am F C G". */
40
+ readonly chords: string;
41
+ /** Phrase names from the track's `phrases`, played back to back from the section's start. */
42
+ readonly tune?: readonly string[];
43
+ readonly voice?: Voice;
44
+ readonly steps: StepStyle;
45
+ /** Two-paw jumps where the tune starts a bar. */
46
+ readonly jumps?: boolean;
47
+ /** Semitones to shift the chords and tune: a key change. */
48
+ readonly transpose?: number;
49
+ // The arrangement, read by synth.ts: pattern names from the track's sound, and transition effects.
50
+ readonly drums: string;
51
+ readonly bass: string;
52
+ readonly pad?: string;
53
+ readonly arp?: string;
54
+ /** Space-separated: "crash" at the start, "riser", "roll", "swell" or "stop" leading into the next section. */
55
+ readonly fx?: string;
56
+ }
57
+
58
+ export interface Track {
59
+ readonly id: string;
60
+ readonly name: string;
61
+ /** One line about its character, for the title card and the README. */
62
+ readonly mood: string;
63
+ readonly bpm: number;
64
+ /** Beats per bar: 4, or 3 for a waltz. */
65
+ readonly meter: 3 | 4;
66
+ /** How late the off-beat eighths fall, as a share of an eighth (0 straight, 0.33 a lazy shuffle). */
67
+ readonly swing: number;
68
+ /** In a drop, the share of off-beat tune notes that become steps; set per track so every track is about as hard. */
69
+ readonly offbeats: number;
70
+ readonly sections: readonly TrackSection[];
71
+ /**
72
+ * Tunes as note names and lengths in eighths ("E5:2 A5:1 r:1"), by name. A list holds
73
+ * alternatives; the round's seed picks one, so each round sounds a little different.
74
+ */
75
+ readonly phrases: Readonly<Record<string, string | readonly string[]>>;
76
+ }
77
+
78
+ // ---- Notation ----
79
+
80
+ const PITCH: Readonly<Record<string, number>> = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
81
+ /** "F#5" → MIDI note 78. */
82
+ export function parseNote(name: string): number {
83
+ const match = /^([A-G])(#|b)?(-?\d)$/.exec(name);
84
+ if (!match) throw Error(`Bad note: ${name}`);
85
+ return 12 * (Number(match[3]) + 1) + PITCH[match[1]!]! + (match[2] === "#" ? 1 : match[2] === "b" ? -1 : 0);
86
+ }
87
+
88
+ /** Semitones above the root for each chord quality. */
89
+ const QUALITIES: Readonly<Record<string, readonly number[]>> = {
90
+ "": [0, 4, 7], m: [0, 3, 7], "7": [0, 4, 7, 10], maj7: [0, 4, 7, 11], m7: [0, 3, 7, 10], m7b5: [0, 3, 6, 10],
91
+ "9": [0, 4, 7, 10, 14], m9: [0, 3, 7, 10, 14], maj9: [0, 4, 7, 11, 14], sus4: [0, 5, 7], "6": [0, 4, 7, 9],
92
+ m6: [0, 3, 7, 9], add9: [0, 4, 7, 14], dim: [0, 3, 6],
93
+ };
94
+ export interface Chord { readonly name: string; /** MIDI root from E2 to D#3 */ readonly root: number; readonly intervals: readonly number[] }
95
+ /** "Bbmaj7" → root B♭2 and its intervals; `transpose` shifts it. */
96
+ export function parseChord(name: string, transpose = 0): Chord {
97
+ const match = /^([A-G])(#|b)?(.*)$/.exec(name), intervals = match ? QUALITIES[match[3]!] : undefined;
98
+ if (!match || !intervals) throw Error(`Bad chord: ${name}`);
99
+ const pitchClass = (((PITCH[match[1]!]! + (match[2] === "#" ? 1 : match[2] === "b" ? -1 : 0) + transpose) % 12) + 12) % 12;
100
+ return { name, root: 40 + ((pitchClass - 4 + 12) % 12), intervals };
101
+ }
102
+
103
+ export interface TuneNote { readonly beat: number; readonly length: number; readonly midi: number; readonly voice: Voice }
104
+
105
+ /** Small deterministic generator, so a seed replays the same steps. */
106
+ function random(seed: number): () => number {
107
+ let state = seed >>> 0;
108
+ return () => {
109
+ state = (state + 0x6d2b79f5) >>> 0;
110
+ let value = Math.imul(state ^ (state >>> 15), 1 | state);
111
+ value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
112
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
113
+ };
114
+ }
115
+
116
+ // ---- Layout: when everything happens ----
117
+
118
+ export interface Section extends TrackSection { readonly index: number; readonly start: number; readonly beats: number }
119
+ interface Layout {
120
+ readonly sections: readonly Section[];
121
+ readonly beats: number;
122
+ /** The chord under each eighth note of the song. */
123
+ readonly chords: readonly Chord[];
124
+ }
125
+ const layouts = new WeakMap<Track, Layout>();
126
+ function layout(track: Track): Layout {
127
+ const known = layouts.get(track);
128
+ if (known) return known;
129
+ const sections: Section[] = [], chords: Chord[] = [];
130
+ let start = 0;
131
+ track.sections.forEach((section, index) => {
132
+ const beats = section.bars * track.meter, bars = section.chords.split(/\s+/).filter(Boolean);
133
+ sections.push({ ...section, index, start, beats });
134
+ for (let bar = 0; bar < section.bars; bar++) {
135
+ const shared = bars[bar % bars.length]!.split(","), eighths = track.meter * 2;
136
+ for (let eighth = 0; eighth < eighths; eighth++) chords.push(parseChord(shared[Math.floor((eighth * shared.length) / eighths)]!, section.transpose));
137
+ }
138
+ start += beats;
139
+ });
140
+ const made = { sections, beats: start, chords };
141
+ layouts.set(track, made);
142
+ return made;
143
+ }
144
+
145
+ export const songBeats = (track: Track) => layout(track).beats;
146
+ export const beatSeconds = (track: Track) => 60 / track.bpm;
147
+ export const songSeconds = (track: Track) => songBeats(track) * beatSeconds(track);
148
+ export const sectionsOf = (track: Track): readonly Section[] => layout(track).sections;
149
+ /** Beats of count-in clicks before the first step. */
150
+ export const countInBeats = (track: Track) => (layout(track).sections[0]?.role === "count-in" ? layout(track).sections[0]!.beats : 0);
37
151
 
38
152
  /** The section playing at `beat` (clamped to the song). */
39
- export function sectionAt(beat: number): Section {
40
- for (let index = SECTIONS.length - 1; index > 0; index--) if (beat >= SECTIONS[index]!.start) return SECTIONS[index]!;
41
- return SECTIONS[0]!;
153
+ export function sectionAt(track: Track, beat: number): Section {
154
+ const sections = layout(track).sections;
155
+ for (let index = sections.length - 1; index > 0; index--) if (beat >= sections[index]!.start) return sections[index]!;
156
+ return sections[0]!;
42
157
  }
43
158
 
44
- // ---- The lead melody ----
159
+ /** The chord sounding at `beat`. */
160
+ export function chordAt(track: Track, beat: number): Chord {
161
+ const chords = layout(track).chords;
162
+ return chords[Math.max(0, Math.min(chords.length - 1, Math.floor(beat * 2)))]!;
163
+ }
45
164
 
46
165
  /**
47
- * One note of the tune, in song beats. `degree` is a step of the A natural minor scale with
48
- * 0 = A4 (so 4 = E5, 7 = A5). `voice` says which instrument plays it: the lead carries the tune
49
- * in the drop, finale and outro; the pluck teases it in the intro; the bell echoes it in the breakdown.
166
+ * Swing: where a straight position in the beat is actually played. Off-beat eighths fall
167
+ * later by `swing` of an eighth and the sixteenths around them move with them, so the
168
+ * chart and the synth agree on every swung note.
50
169
  */
51
- export type Voice = "lead" | "pluck" | "bell";
52
- export interface TuneNote { readonly beat: number; readonly length: number; readonly degree: number; readonly voice: Voice }
53
-
54
- /** Two bars of tune: [start, length, degree], with start and length in eighth notes. */
55
- type Phrase = readonly (readonly [number, number, number])[];
56
- // The call, over A minor then F: a leap up to A5, a fall back to E, then a settle on C.
57
- const CALL_A: Phrase = [[0, 2, 4], [2, 1, 7], [3, 1, 6], [4, 2, 4], [6, 1, 3], [7, 1, 4], [8, 3, 2], [11, 1, 3], [12, 1, 2], [13, 1, 0], [14, 2, 2]];
58
- // Over C then G it climbs to C6 and stops on D, a question.
59
- const CALL_B: Phrase = [[0, 2, 6], [2, 1, 4], [3, 1, 6], [4, 3, 9], [7, 1, 8], [8, 3, 7], [11, 1, 6], [12, 4, 3]];
60
- // Three ways to answer it; the seed picks one, so each round's drop ends a little differently.
61
- const ANSWERS: readonly Phrase[] = [
62
- [[0, 2, 6], [2, 1, 4], [3, 1, 6], [4, 2, 9], [6, 1, 8], [7, 1, 7], [8, 3, 8], [11, 1, 6], [12, 4, 4]],
63
- [[0, 1, 4], [1, 1, 6], [2, 2, 9], [4, 2, 8], [6, 1, 7], [7, 1, 6], [8, 2, 8], [10, 2, 7], [12, 4, 6]],
64
- [[0, 2, 9], [2, 1, 8], [3, 1, 6], [4, 2, 4], [6, 2, 6], [8, 2, 3], [10, 1, 4], [11, 1, 6], [12, 4, 8]],
65
- ];
66
- // G, A, B over the G chord, then home to A over A minor: the ending resolves.
67
- const CADENCE: Phrase = [[0, 3, 6], [3, 1, 7], [4, 4, 8], [8, 8, 7]];
68
-
69
- /** The whole tune for one round, ordered by beat. Deterministic per seed. */
70
- export function createTune(seed: number): TuneNote[] {
71
- const tune: TuneNote[] = [];
72
- const place = (phrase: Phrase, start: number, voice: Voice, onBeatOnly = false) => {
73
- for (const [at, length, degree] of phrase) {
74
- if (onBeatOnly && at % 2 === 1) continue;
75
- tune.push({ beat: start + at / 2, length: length / 2, degree, voice });
170
+ export function swung(track: Track, beat: number): number {
171
+ const whole = Math.floor(beat), part = beat - whole, late = 0.5 + track.swing / 2;
172
+ return whole + (part < 0.5 ? part * 2 * late : late + (part - 0.5) * 2 * (1 - late));
173
+ }
174
+
175
+ /** The whole tune for one round, in song beats (straight, before swing), ordered by beat. Deterministic per seed. */
176
+ export function createTune(track: Track, seed: number): TuneNote[] {
177
+ const next = random(seed ^ 0x2545f491), chosen = new Map<string, string>(), tune: TuneNote[] = [];
178
+ for (const section of layout(track).sections) {
179
+ let beat = section.start;
180
+ for (const name of section.tune ?? []) {
181
+ const phrase = track.phrases[name];
182
+ if (phrase === undefined) throw Error(`${track.id}: no phrase ${name}`);
183
+ // One choice per phrase name per round, so a repeated phrase repeats.
184
+ if (!chosen.has(name)) chosen.set(name, typeof phrase === "string" ? phrase : phrase[Math.floor(next() * phrase.length)] ?? "");
185
+ for (const token of chosen.get(name)!.split(/\s+/).filter(Boolean)) {
186
+ const [note = "", eighths = "1"] = token.split(":"), length = Number(eighths) / 2;
187
+ if (note !== "r") tune.push({ beat, length, midi: parseNote(note) + (section.transpose ?? 0), voice: section.voice ?? "lead" });
188
+ beat += length;
189
+ }
76
190
  }
77
- };
78
- const answer = ANSWERS[(seed >>> 0) % ANSWERS.length]!;
79
- place(CALL_A, 12, "pluck"); // the second half of the intro hints at the tune
80
- place(CALL_A, 36, "lead"); place(CALL_B, 44, "lead"); place(CALL_A, 52, "lead"); place(answer, 60, "lead"); // drop
81
- place(CALL_A, 68, "bell", true); place(CALL_B, 76, "bell", true); // breakdown: the tune's downbeats, softly
82
- place(CALL_A, 84, "lead"); place(CALL_B, 92, "lead"); place(CALL_A, 100, "lead"); // finale
83
- place(CADENCE, 108, "lead"); // outro
191
+ if (beat > section.start + section.beats + 1e-9) throw Error(`${track.id}: the tune overruns ${section.label}`);
192
+ }
84
193
  return tune;
85
194
  }
86
195
 
196
+ // ---- Picking the next track ----
197
+
198
+ /** A track index for round `seed`: any track but the one just played. */
199
+ export function pickTrack(count: number, seed: number, previous: number | null): number {
200
+ const others = previous === null || count < 2 ? count : count - 1;
201
+ let index = Math.floor(random(seed ^ 0x5bd1e995)() * others);
202
+ if (previous !== null && count > 1 && index >= previous) index++;
203
+ return index;
204
+ }
205
+
206
+ // ---- Progress: the personal bests kept in the checkpoint ----
207
+
208
+ export interface Progress {
209
+ /** The best score on any track. */
210
+ readonly best: number;
211
+ /** The best score per track id. */
212
+ readonly bests: Readonly<Record<string, number>>;
213
+ readonly rounds: number;
214
+ readonly muted: boolean;
215
+ /** The track played last, so the next round picks another. */
216
+ readonly last: string | null;
217
+ /** The coat Biscuit wears: "midnight" only once the player owns it (the game checks with os.products()). */
218
+ readonly coat: "classic" | "midnight";
219
+ }
220
+
221
+ /**
222
+ * Read a checkpoint into progress. Anything malformed counts as nothing. A checkpoint from
223
+ * 1.1, before there were tracks, has one `best`: that was set on the original song, `firstTrack`.
224
+ */
225
+ export function readProgress(value: unknown, trackIds: readonly string[]): Progress {
226
+ const record = value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
227
+ const count = (input: unknown) => (typeof input === "number" && Number.isFinite(input) && input >= 0 ? Math.floor(input) : 0);
228
+ const bests: Record<string, number> = {};
229
+ const saved = record.bests && typeof record.bests === "object" && !Array.isArray(record.bests) ? record.bests as Record<string, unknown> : null;
230
+ for (const id of trackIds) if (saved && count(saved[id]) > 0) bests[id] = count(saved[id]);
231
+ const best = Math.max(count(record.best), ...Object.values(bests));
232
+ if (!saved && best > 0 && trackIds[0]) bests[trackIds[0]] = best;
233
+ const last = typeof record.last === "string" && trackIds.includes(record.last) ? record.last : null;
234
+ return { best, bests, rounds: count(record.rounds), muted: record.muted === true, last, coat: record.coat === "midnight" ? "midnight" : "classic" };
235
+ }
236
+
237
+ // ---- Achievements: the ids vibemarket.json declares, and when a round earns each ----
238
+
239
+ export const ACHIEVEMENTS = { firstDance: "first-dance", combo50: "combo-50", fullCombo: "full-combo" } as const;
240
+ /** The achievements a finished round earns. Unlocking one again is harmless, so a round simply names all it earned. */
241
+ export function roundAchievements(round: { bestCombo: number; fullCombo: boolean }): string[] {
242
+ return [ACHIEVEMENTS.firstDance, ...(round.bestCombo >= 50 ? [ACHIEVEMENTS.combo50] : []), ...(round.fullCombo ? [ACHIEVEMENTS.fullCombo] : [])];
243
+ }
244
+
245
+ /** Progress after a round of `trackId` that scored `score`. */
246
+ export function recordRound(progress: Progress, trackId: string, score: number): Progress {
247
+ const bests = { ...progress.bests, [trackId]: Math.max(progress.bests[trackId] ?? 0, score) };
248
+ return { ...progress, best: Math.max(progress.best, score), bests, rounds: progress.rounds + 1, last: trackId };
249
+ }
250
+
87
251
  // ---- Judging ----
88
252
 
89
253
  /** How close to the beat a press must land, in seconds, and what it pays. */
@@ -108,6 +272,7 @@ export interface DanceState {
108
272
  }
109
273
 
110
274
  export interface DanceGame {
275
+ readonly track: Track;
111
276
  readonly notes: readonly NoteView[];
112
277
  readonly state: DanceState;
113
278
  /** Move the song clock to `time` seconds. Notes that scrolled past unhit become misses. */
@@ -142,102 +307,104 @@ export function gradeRound(counts: Readonly<Record<Judgement, number>>): RoundRe
142
307
  return { accuracy, grade, fullCombo };
143
308
  }
144
309
 
145
- /** Small deterministic generator, so a seed replays the same steps. */
146
- function random(seed: number): () => number {
147
- let state = seed >>> 0;
148
- return () => {
149
- state = (state + 0x6d2b79f5) >>> 0;
150
- let value = Math.imul(state ^ (state >>> 15), 1 | state);
151
- value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value;
152
- return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
153
- };
154
- }
155
-
156
310
  /** The other paw of a jump: left with right, up with down. */
157
311
  const MIRROR: Readonly<Record<Lane, Lane>> = { left: "right", right: "left", up: "down", down: "up" };
158
312
  /** The neighbour with the same sense (up and right read as "higher", down and left as "lower"). */
159
313
  const NEIGHBOUR: Readonly<Record<Lane, Lane>> = { up: "right", right: "up", down: "left", left: "down" };
160
- /** Four-beat walking patterns for the sections without a tune to follow. */
314
+ /** Four-step walking patterns for the sections without a tune to follow. */
161
315
  const WALKS: readonly (readonly Lane[])[] = [
162
316
  ["left", "right", "left", "right"], ["down", "up", "down", "up"], ["left", "down", "up", "right"],
163
317
  ["right", "up", "down", "left"], ["left", "up", "right", "down"], ["up", "left", "down", "right"],
164
318
  ];
165
319
 
166
320
  /**
167
- * Write the steps for one round from the song itself:
168
- * - intro: half notes, then every beat, on the kick;
169
- * - build: every beat, in walking patterns;
170
- * - drop: the lead melody's rhythm, with arrows that follow its shape (a step up is ↑, a leap
171
- * up is →, a step down ↓, a leap down ←), keeping every on-beat note and most off-beat ones;
172
- * - breakdown: half notes on the bell, then a bar of quarters to lead back in;
173
- * - finale: every note of the melody, with two-paw jumps on the bar downbeats;
174
- * - outro: the closing cadence and a final jump on the last chord.
175
- * No lane ever follows itself and a jump's two lanes are never the next step's, so every
176
- * pattern is playable with four keys.
321
+ * Write the steps for one round from the track itself, section by section:
322
+ * - "half" and "beat" sections walk on the beat in simple patterns;
323
+ * - "groove" sections do the same and also step on any beat where the tune rests;
324
+ * - "tune" sections step where the tune plays a note, with arrows that follow its shape (a step
325
+ * up is ↑, a leap up is →, a step down ↓, a leap down ←). Before the first drop only on-beat
326
+ * notes count; in a drop the track's `offbeats` share of off-beat notes count, and in the
327
+ * finale and outro a little more;
328
+ * - sections with `jumps` add a second paw where the tune starts a bar, and the song's last
329
+ * note is always a jump.
330
+ * No lane is asked for straight after it was pressed (jumps included), no two steps are closer
331
+ * than MIN_STEP_GAP, and swing moves the steps exactly as it moves the notes.
177
332
  */
178
- export function createChart(seed: number): Note[] {
179
- const next = random(seed), notes: Note[] = [];
180
- let previous: Lane | undefined, jumpPartner: Lane | undefined;
181
- const add = (beat: number, wanted: Lane, jump = false) => {
333
+ export function createChart(track: Track, seed: number): Note[] {
334
+ const next = random(seed), notes: Note[] = [], seconds = beatSeconds(track), { sections } = layout(track);
335
+ const tune = createTune(track, seed), lastNote = tune.at(-1);
336
+ const firstDrop = sections.find(section => section.role === "drop" || section.role === "finale")?.start ?? Infinity;
337
+ let previous: Lane | undefined, jumpPartner: Lane | undefined, lastTime = -Infinity;
338
+ const add = (beat: number, wanted: Lane, jump: boolean) => {
339
+ const time = swung(track, beat) * seconds;
340
+ if (time - lastTime < MIN_STEP_GAP - 1e-9) return;
182
341
  // The wanted lane, or the nearest one in sense that uses none of the lanes just pressed.
183
342
  const used = (lane: Lane) => lane === previous || lane === jumpPartner;
184
343
  const lane = [wanted, NEIGHBOUR[wanted], MIRROR[wanted], MIRROR[NEIGHBOUR[wanted]]].find(lane => !used(lane) && !(jump && used(MIRROR[lane]))) ?? wanted;
185
- notes.push({ time: beat * BEAT_SECONDS, lane });
344
+ notes.push({ time, lane });
186
345
  previous = lane;
187
346
  jumpPartner = undefined;
347
+ lastTime = time;
188
348
  if (jump) {
189
- notes.push({ time: beat * BEAT_SECONDS, lane: MIRROR[lane] });
349
+ notes.push({ time, lane: MIRROR[lane] });
190
350
  jumpPartner = MIRROR[lane];
191
351
  }
192
352
  };
193
- const walk = (from: number, to: number, every: number) => {
194
- let pattern = WALKS[0]!;
195
- for (let beat = from, step = 0; beat < to; beat += every, step++) {
196
- if (step % 4 === 0) pattern = WALKS[Math.floor(next() * WALKS.length)] ?? WALKS[0]!;
197
- add(beat, pattern[step % 4]!);
198
- }
199
- };
200
-
201
- const tune = createTune(seed).filter(note => note.voice === "lead");
202
- let lastDegree = 4;
203
- const sing = (from: number, to: number) => {
204
- for (const note of tune) {
205
- if (note.beat < from || note.beat >= to) continue;
206
- const section = sectionAt(note.beat).name, offBeat = note.beat % 1 !== 0;
207
- const rise = note.degree - lastDegree;
208
- lastDegree = note.degree;
209
- // The drop leaves out about a third of its off-beat notes; the finale and outro keep them all.
210
- if (section === "drop" && offBeat && next() < 0.35) continue;
211
- const shaped: Lane = rise >= 3 ? "right" : rise > 0 ? "up" : rise <= -3 ? "left" : rise < 0 ? "down" : next() < 0.5 ? "left" : "right";
212
- add(note.beat, shaped, (section === "finale" && note.beat % BEATS_PER_BAR === 0) || note.beat === SONG_BEATS - 4);
353
+ let lastMidi: number | null = null, pattern = WALKS[0]!, walked = 0;
354
+ for (const section of sections) {
355
+ const end = section.start + section.beats;
356
+ if (section.steps === "half" || section.steps === "beat") {
357
+ const every = section.steps === "beat" ? 1 : track.meter === 3 ? 3 : 2;
358
+ for (let beat = section.start; beat < end; beat += every, walked++) {
359
+ if (walked % 4 === 0) pattern = WALKS[Math.floor(next() * WALKS.length)] ?? WALKS[0]!;
360
+ add(beat, pattern[walked % 4]!, false);
361
+ }
362
+ } else if (section.steps === "tune" || section.steps === "groove") {
363
+ // In a groove, a beat with no tune note within half a beat of it gets a step of its own.
364
+ const moments: { beat: number; midi: number | null; note: TuneNote | null }[] = [];
365
+ for (const note of tune) if (note.beat >= section.start && note.beat < end) moments.push({ beat: note.beat, midi: note.midi, note });
366
+ if (section.steps === "groove") {
367
+ for (let beat = section.start; beat < end; beat++) if (!moments.some(moment => Math.abs(moment.beat - beat) < 0.75)) moments.push({ beat, midi: null, note: null });
368
+ moments.sort((a, b) => a.beat - b.beat);
369
+ }
370
+ const keepOffbeats = section.start < firstDrop || section.role === "build" || section.role === "intro" ? 0 : section.role === "drop" || section.role === "break" ? track.offbeats : Math.min(1, track.offbeats + 0.3);
371
+ for (const { beat, midi, note } of moments) {
372
+ if (midi === null) {
373
+ // A gap in the tune: keep walking on the beat.
374
+ if (walked % 4 === 0) pattern = WALKS[Math.floor(next() * WALKS.length)] ?? WALKS[0]!;
375
+ add(beat, pattern[walked++ % 4]!, false);
376
+ continue;
377
+ }
378
+ const rise = lastMidi === null ? 0 : midi - lastMidi;
379
+ lastMidi = midi;
380
+ if (beat % 1 !== 0 && next() >= keepOffbeats) continue;
381
+ const shaped: Lane = rise >= 5 ? "right" : rise > 0 ? "up" : rise <= -5 ? "left" : rise < 0 ? "down" : next() < 0.5 ? "left" : "right";
382
+ const downbeat = (beat - section.start) % track.meter === 0;
383
+ add(beat, shaped, (section.jumps === true && downbeat) || note === lastNote);
384
+ }
213
385
  }
214
- };
215
- walk(4, 12, 2); // intro: half notes
216
- walk(12, 36, 1); // the rest of the intro and the build: every beat
217
- sing(36, 68); // drop
218
- walk(68, 80, 2); // breakdown
219
- walk(80, 84, 1); // and a bar of quarters back in
220
- sing(84, SONG_BEATS); // finale and outro
386
+ }
221
387
  return notes;
222
388
  }
223
389
 
224
390
  const NONE: readonly NoteView[] = Object.freeze([]);
225
391
 
226
- export function createGame(seed = 1): DanceGame {
227
- const chart = createChart(seed);
392
+ export function createGame(track: Track, seed = 1): DanceGame {
393
+ const chart = createChart(track, seed), length = songSeconds(track);
228
394
  const judged: (Judgement | null)[] = chart.map(() => null);
229
395
  const counts: Record<Judgement, number> = { perfect: 0, great: 0, good: 0, miss: 0 };
230
396
  let time = 0, score = 0, combo = 0, bestCombo = 0, firstOpen = 0;
231
397
  const view = (index: number): NoteView => ({ ...chart[index]!, index, judged: judged[index] ?? null });
232
398
 
233
399
  return {
400
+ track,
234
401
  get notes() { return chart.map((_, index) => view(index)); },
235
402
  get state(): DanceState {
236
- return { time, score, combo, bestCombo, counts: { ...counts }, finished: time >= SONG_SECONDS };
403
+ return { time, score, combo, bestCombo, counts: { ...counts }, finished: time >= length };
237
404
  },
238
405
  advance(next) {
239
406
  if (!Number.isFinite(next) || next <= time) return NONE;
240
- time = Math.min(next, SONG_SECONDS);
407
+ time = Math.min(next, length);
241
408
  // Called every frame, so it allocates only when something was actually missed.
242
409
  let missed: NoteView[] | undefined;
243
410
  for (let index = firstOpen; index < chart.length && chart[index]!.time < time - MISS_AFTER; index++) {
@@ -262,7 +429,7 @@ export function createGame(seed = 1): DanceGame {
262
429
  for (let index = low; index < chart.length && chart[index]!.time <= to; index++) visit(chart[index]!, judged[index] ?? null);
263
430
  },
264
431
  press(lane) {
265
- if (time >= SONG_SECONDS) return null;
432
+ if (time >= length) return null;
266
433
  // The closest unjudged note in this lane, if it is inside the widest window.
267
434
  let best = -1, bestOff = Infinity;
268
435
  for (let index = firstOpen; index < chart.length && chart[index]!.time <= time + MISS_AFTER; index++) {
@@ -61,6 +61,12 @@
61
61
  .key { display: inline-grid; place-items: center; width: clamp(24px, calc(var(--unit) * 5), 46px); aspect-ratio: 1; border-radius: 10px; border: 2px solid currentColor; font-weight: 900; font-size: clamp(13px, calc(var(--unit) * 2.6), 24px); background: #ffffff0d; }
62
62
  .key small { font-size: .45em; opacity: .8; display: block; margin-top: -.2em; }
63
63
  .best { color: var(--gold); font-weight: 700; }
64
+ /* The track: its name on the title card, in the heads-up display and on the results card. */
65
+ .track { display: flex; align-items: baseline; gap: .6em; flex-wrap: wrap; }
66
+ .track b { font-size: clamp(14px, calc(var(--unit) * 2.4), 22px); }
67
+ .track small { opacity: .8; font-size: clamp(10px, calc(var(--unit) * 1.5), 14px); }
68
+ .next { border: 2px solid #ffffff40; background: #ffffff0d; border-radius: 999px; padding: .2em .8em; font-weight: 700; font-size: clamp(11px, calc(var(--unit) * 1.5), 14px); }
69
+ .hud .now { display: block; margin-top: .3em; font-size: clamp(9px, calc(var(--unit) * 1.4), 13px); opacity: .85; text-align: center; font-weight: 600; letter-spacing: .04em; }
64
70
  .grade { font-size: clamp(40px, calc(var(--unit) * 13), 130px); line-height: .9; font-weight: 900; color: var(--gold); text-shadow: 0 4px 0 #0007; }
65
71
  .final { font-size: clamp(18px, calc(var(--unit) * 4.4), 44px); font-weight: 900; font-variant-numeric: tabular-nums; }
66
72
  .final mark { background: var(--gold); color: var(--ink); border-radius: 999px; padding: .1em .55em; font-size: .4em; vertical-align: .45em; margin-left: .4em; white-space: nowrap; display: inline-block; }
@@ -70,7 +76,9 @@
70
76
  .stats dd { margin: 0; font-weight: 800; font-variant-numeric: tabular-nums; }
71
77
  /* Very short windows keep the essentials: title and start, or grade, score, accuracy and best combo. */
72
78
  @media (max-height: 330px) {
73
- .tagline, .how, .note, .stats div:nth-child(n+3) { display: none; }
79
+ .tagline, .how, .note, .stats div:nth-child(n+3), #done-track-best, #up-next { display: none; }
80
+ .grade { font-size: 30px; }
81
+ .primary { padding: .4em 1em; white-space: nowrap; }
74
82
  .stats { grid-template-columns: repeat(2, auto); }
75
83
  }
76
84
  .overlay { position: fixed; inset: 0; display: grid; place-items: center; text-align: center; background: #0d0918e8; padding: 16px; z-index: 4; }
@@ -81,7 +89,10 @@
81
89
 
82
90
  <div class="hud" id="hud" hidden>
83
91
  <div><small>SCORE</small><div class="score"><span id="score">0</span><em id="multiplier" hidden></em></div></div>
84
- <div class="progress" role="progressbar" aria-label="Song progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" id="progress"><i style="flex: 4"></i><i style="flex: 16"></i><i style="flex: 16"></i><i style="flex: 32"></i><i style="flex: 16"></i><i style="flex: 24"></i><i style="flex: 8; border: 0"></i><b id="played"></b></div>
92
+ <div>
93
+ <div class="progress" role="progressbar" aria-label="Song progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" id="progress"><b id="played"></b></div>
94
+ <span class="now" id="now-playing"></span>
95
+ </div>
85
96
  <div class="spacer"></div>
86
97
  </div>
87
98
  <button class="sound" id="sound" type="button" aria-pressed="true">♪ Sound on</button>
@@ -109,11 +120,15 @@
109
120
  <span class="key" style="color: var(--right)">→<small>D</small></span>
110
121
  </div>
111
122
  <p class="note">Or tap the pads. Perfect timing scores most, and every ten in a row adds 10%. <kbd>M</kbd> mutes.</p>
112
- <p class="best" id="best">One song, about a minute.</p>
123
+ <div class="track" aria-live="polite"><b id="track-name">Biscuit's Groove</b><button class="next" id="next-track" type="button">Next track ›</button></div>
124
+ <p class="note" id="track-mood"></p>
125
+ <p class="best" id="best">Six tracks, about a minute each.</p>
113
126
  <div><button class="primary" id="start" type="button" disabled>Connecting…</button></div>
127
+ <div class="track"><button class="next" id="coat" type="button" hidden>Midnight coat</button><small id="shop" aria-live="polite"></small></div>
114
128
  </section>
115
129
 
116
130
  <section class="card" id="done" hidden aria-labelledby="grade">
131
+ <div class="track"><b id="done-track"></b><small id="done-track-best"></small></div>
117
132
  <div class="grade" id="grade" aria-label="Grade">A</div>
118
133
  <div class="final"><span id="done-score">0</span><mark id="new-best" hidden>New best!</mark><mark id="full-combo" hidden>Full combo</mark></div>
119
134
  <dl class="stats">
@@ -125,7 +140,8 @@
125
140
  <div><dt>MISSED</dt><dd id="done-miss">0</dd></div>
126
141
  </dl>
127
142
  <p class="note" id="sent"></p>
128
- <div><button class="primary" id="again" type="button">Dance again</button></div>
143
+ <div class="track"><button class="primary" id="again" type="button">Dance again</button><small id="up-next"></small></div>
144
+ <div class="track"><button class="next" id="share" type="button">Share score</button><button class="next" id="board" type="button">Leaderboard</button></div>
129
145
  </section>
130
146
 
131
147
  <section class="overlay" id="lost" hidden>