gamehearth 0.10.0 → 0.11.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.
package/README.md CHANGED
@@ -76,6 +76,7 @@ In the template, `npm run dev` starts the command with `--build "npm run build:w
76
76
  - **Bots:** Every seat can be set to "Bot". If the game has a `bot` function, the seat plays with it, as on the platform: turn-based through `botMove` after a short pause, in realtime through `stepMatch` with the seat in `bots` (asked in every tick). Without `bot` the seat makes a random legal move after a short pause (in realtime a random input with a probability of 20% per tick), with placeholders (`text()`, `int()`) filled by random values like in `check`. If `bot` throws, picks a move that is not legal or tries to change what it gets, the seat plays a random legal move instead (in realtime no input), as on the platform, and the problem shows as a banner ("Problem in bot for p2") and once in a row in the terminal; the match is not paused. The frames get bots with `bot: true` in `players`. Moves of the UI count as legal if they fit a placeholder. Bots stay on in a new match. If a bot's move fails because of the game code, this bot pauses ("paused") until the rules are reloaded, a new match starts or it is switched on again.
77
77
  - **Away:** In a realtime game with `"away": "play-on"`, every phone has an "Away" switch. An away seat goes to `stepMatch` as `away`, so the game sees it in `ctx.away`, and its frame is dimmed; a bot seat is never away. Unlike the platform, `dev` does not pause when every seat is away. Other games have no such switch; they pause on the platform instead.
78
78
  - **Sound:** The frames play sounds with `game.sound(…)`; `dev` synthesizes them with Web Audio like the platform (named sounds from the SDK or own notes, at most 12 per second and frame), but only while the "Sound" switch in the header is on. It is off by default, like on the platform, and the page remembers it in the browser. Every frame, the TV and single-player games included, gets `{ type: "settings", sound }` after it has started and whenever the switch changes, so `game.soundOn` follows the switch. The header names the last sound and the frame that played it (`♪ p1: coin`), so it can be checked without speakers.
79
+ - **Music:** The frames play looping tracks with `game.music(…)`; `dev` plays them with the SDK's music player like the platform (`createMusicPlayer`: looped on the audio clock, a crossfade of about a second to another track, at most one change per 300 ms, the same track keeps playing, paused while the page is hidden), but only while both "Sound" and "Music" in the header are on. As on the platform, "Music" is on by default and "Sound" off, so turning on sound brings the music along; the page remembers both in the browser. `settings` carries `music: true` only while both are on and no bot plays the frame's seat, so `game.musicOn` follows. Only one frame's track plays: the TV's, otherwise that of the first seat that has one and is not played by a bot; a frame that loads again starts without music. The header names the playing track next to the last sound (`♪ Forest`, or `♪ music` for a track without a name), but only while music actually plays, that is while the page's audio context runs. A `suspended` or `interrupted` context is resumed on the next click or key.
79
80
  - **Insight:** Below every seat, the snapshot its client gets can be expanded; at the bottom the whole state including `secret`, the moves and the seed.
80
81
  - **Realtime:** With `"mode": "realtime"`, `dev` computes 20 ticks per second like the server. Inputs wait until the next tick; if more than 4 are waiting from one seat, the oldest expires, and like the platform, `dev` rejects more than 30 inputs per second and seat with `rate-limited`. While paused (by hand or after an error), `dev` answers inputs right away and keeps the last one per seat for the next tick, also for "One tick". If the game has the role `screen`, also an optional one, a "TV" frame in landscape format is in front, with its own address `/tv`; the phones get the role `controller`, or `player` if the game has that role (as with an optional TV). At the top there are "Pause"/"Resume", "One tick" (only while paused) and slow motion (half and quarter speed; the game time per tick stays 50 ms, the frames get the longer tick duration as `tickMs`, so that `createTimeline` keeps drawing smoothly). Bot seats press a random legal input in every tick with a probability of 20%, unless the game has `bot` (see "Bots"). Like the server, `dev` catches up on late ticks (at most 200 ms behind), so that the game time keeps pace with the clock. If a tick fails because of time, memory or a crash of the sandbox, `dev` computes it once more like the server. An error in `tick` pauses the match ("Tick N failed" or "Error in tick (tick N)"); "Resume" tries again. `dev` reports illegal inputs as an error of the UI only if they were not in `snapshot.moves` already on arrival; what only becomes illegal through an earlier input in the same tick is not an error. If the rules change, the ticks stand still until they are loaded, then a new match starts with the same seed, the same seats and bots, instead of replaying; the same inputs would run differently with new rules anyway. Countdown and pauses of the platform (missing phone, missing TV) do not exist in `dev`. The list of moves shows only the last inputs.
81
82
  - **Reloading means replaying:** If something under `src/` or `manifest.json` changes, `dev` bundles again and replays the same match from seed and moves with the new code. If a move is no longer legal or the code throws, it stops there and says why; "New match" starts over. If the player count no longer fits the manifest, a new match starts. If the rules cannot be built or cannot be loaded in QuickJS, the last version keeps running.
package/dist/cli.js CHANGED
@@ -1055,6 +1055,12 @@ function screenSnapshot(match) {
1055
1055
  });
1056
1056
  }
1057
1057
 
1058
+ // ../sdk/src/sound.ts
1059
+ var soundWaves = ["square", "sine", "triangle", "sawtooth"];
1060
+
1061
+ // ../sdk/src/music.ts
1062
+ var musicInstruments = [...soundWaves, "musicbox", "organ", "pluck", "bass", "noise"];
1063
+
1058
1064
  // ../sdk/src/bridge.ts
1059
1065
  var maxSaveBytes = 64 * 1024;
1060
1066
  var maxSaveDepth = 64;
@@ -1103,8 +1109,12 @@ function recordProblem(stat, value) {
1103
1109
  return void 0;
1104
1110
  }
1105
1111
 
1112
+ // ../sdk/src/music-player.ts
1113
+ var musicLimiter = { threshold: -6, knee: 0, ratio: 20, attack: 3e-3, release: 0.25 };
1114
+ var musicMasterGain = 10 ** (musicLimiter.threshold * (1 - 1 / musicLimiter.ratio) * 0.6 / 20);
1115
+
1106
1116
  // ../sdk/src/platform.ts
1107
- var sdkVersion = "0.1.8";
1117
+ var sdkVersion = "0.1.9";
1108
1118
 
1109
1119
  // src/download.ts
1110
1120
  var DownloadError = class extends Error {
@@ -4959,7 +4969,9 @@ body.single #solo-box { display: none; }
4959
4969
  <span class="spacer"></span>
4960
4970
  <span id="status">connecting \u2026</span>
4961
4971
  <span id="sound-note" class="tag" aria-live="polite"></span>
4972
+ <span id="music-note" class="tag" aria-live="polite"></span>
4962
4973
  <label id="sound-box" title="Plays the sounds of the game (game.sound) like the platform: off by default, and on iPhones only with the ringer on"><input type="checkbox" id="sound"> Sound</label>
4974
+ <label id="music-box" title="Plays the music of the game (game.music) like the platform: on by default, but only together with Sound; the TV's track, otherwise that of the first seat no bot plays"><input type="checkbox" id="music"> Music</label>
4963
4975
  <button id="pause" type="button" class="multi" hidden>Pause</button>
4964
4976
  <button id="step" type="button" class="multi" hidden>One tick</button>
4965
4977
  <select id="speed" class="multi" aria-label="Speed" hidden><option value="1">normal</option><option value="0.5">half speed</option><option value="0.25">quarter speed</option></select>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gamehearth",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Dev tool for Gamehearth games: create a new game, try it locally with several players, check it with bot matches and build it as a package",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -44,7 +44,7 @@
44
44
  "build": "esbuild src/cli.ts --bundle --platform=node --format=esm --target=node22 --outfile=dist/cli.js --external:esbuild --external:quickjs-emscripten-core --external:@jitl/quickjs-wasmfile-release-sync --log-level=warning \"--banner:js=#!/usr/bin/env node\""
45
45
  },
46
46
  "dependencies": {
47
- "@gamehearth/sdk": "^0.1.8",
47
+ "@gamehearth/sdk": "^0.1.9",
48
48
  "@jitl/quickjs-wasmfile-release-sync": "0.32.0",
49
49
  "esbuild": "^0.28.2",
50
50
  "quickjs-emscripten-core": "0.32.0"
@@ -1,9 +1,11 @@
1
- import { bridgeVersion, localize, parseGameMessage, type Localized, type MoveResult, type Sound } from "@gamehearth/sdk/platform";
1
+ import { bridgeVersion, createMusicPlayer, localize, parseGameMessage, type Localized, type MoveResult, type MusicTrack, type Sound } from "@gamehearth/sdk/platform";
2
2
  import {
3
3
  admitSound,
4
4
  formatProblem,
5
5
  frameSnapshot,
6
6
  frameUpdate,
7
+ musicLabel,
8
+ musicSource,
7
9
  screenSeat,
8
10
  settingsMessage,
9
11
  soloMessage,
@@ -13,6 +15,7 @@ import {
13
15
  type DevProblem,
14
16
  type DevView,
15
17
  type SeatView,
18
+ devSwitchDefaults,
16
19
  } from "../view";
17
20
 
18
21
  interface Frame {
@@ -25,10 +28,12 @@ interface Frame {
25
28
  botState: HTMLElement | undefined;
26
29
  away?: HTMLInputElement;
27
30
  sounds: number[];
31
+ track: MusicTrack | null;
28
32
  details: HTMLDetailsElement;
29
33
  snapshot: HTMLElement;
30
34
  ready: boolean;
31
35
  sent: string | undefined;
36
+ settings?: string | undefined;
32
37
  profile?: { box: HTMLDetailsElement; summary: HTMLElement; text: HTMLTextAreaElement; guest: HTMLInputElement; note: HTMLElement; dirty: boolean; shown: string; latest: string };
33
38
  }
34
39
 
@@ -39,20 +44,24 @@ const frames = new Map<string, Frame>();
39
44
  let view: DevView | undefined;
40
45
  let layoutKey = "";
41
46
  const soundKey = "gamehearth-dev.sound";
42
- let soundOn = readSoundSetting();
47
+ const musicKey = "gamehearth-dev.music";
48
+ let soundOn = readSetting(soundKey, devSwitchDefaults.sound);
49
+ let musicOn = readSetting(musicKey, devSwitchDefaults.music);
43
50
  let audio: AudioContext | undefined;
51
+ const player = createMusicPlayer({ context: () => audioContext() });
44
52
 
45
- function readSoundSetting(): boolean {
53
+ function readSetting(key: string, fallback: boolean): boolean {
46
54
  try {
47
- return localStorage.getItem(soundKey) === "on";
55
+ const stored = localStorage.getItem(key);
56
+ return stored === "on" ? true : stored === "off" ? false : fallback;
48
57
  } catch {
49
- return false;
58
+ return fallback;
50
59
  }
51
60
  }
52
61
 
53
- function storeSoundSetting(on: boolean): void {
62
+ function storeSetting(key: string, on: boolean): void {
54
63
  try {
55
- localStorage.setItem(soundKey, on ? "on" : "off");
64
+ localStorage.setItem(key, on ? "on" : "off");
56
65
  } catch {
57
66
  return;
58
67
  }
@@ -72,16 +81,21 @@ function audioContext(): AudioContext | undefined {
72
81
  } catch {
73
82
  return undefined;
74
83
  }
84
+ audio.addEventListener("statechange", refreshMusic);
75
85
  return audio;
76
86
  }
77
87
 
78
88
  function unlockSound(): void {
79
89
  const context = soundOn ? audioContext() : undefined;
80
- if (context?.state === "suspended") {
90
+ if (context !== undefined && context.state !== "running" && context.state !== "closed") {
81
91
  void context.resume().catch(() => undefined);
82
92
  }
83
93
  }
84
94
 
95
+ function botSeats(): Set<string> {
96
+ return new Set((view?.session.seats ?? []).filter((entry) => entry.bot).map((entry) => entry.seat));
97
+ }
98
+
85
99
  function playSound(frame: Frame, sound: Sound): void {
86
100
  if (!soundOn || !admitSound(frame.sounds, performance.now())) {
87
101
  return;
@@ -109,20 +123,49 @@ function playSound(frame: Frame, sound: Sound): void {
109
123
  }
110
124
  }
111
125
 
126
+ function refreshMusic(): void {
127
+ const track = soundOn && musicOn ? (musicSource(frames.values(), botSeats())?.track ?? null) : null;
128
+ const hidden = document.visibilityState === "hidden";
129
+ if (track !== null && !hidden) {
130
+ unlockSound();
131
+ }
132
+ player.setPaused(hidden);
133
+ player.play(track);
134
+ byId("music-note").textContent = musicLabel(track, !hidden && audio?.state === "running");
135
+ }
136
+
112
137
  function sendSettings(frame: Frame): void {
113
- frame.iframe?.contentWindow?.postMessage(settingsMessage(soundOn), "*");
138
+ const message = settingsMessage(soundOn, musicOn && !botSeats().has(frame.seat));
139
+ const text = JSON.stringify(message);
140
+ if (text === frame.settings) {
141
+ return;
142
+ }
143
+ frame.settings = text;
144
+ frame.iframe?.contentWindow?.postMessage(message, "*");
114
145
  }
115
146
 
116
- function setSound(on: boolean): void {
117
- soundOn = on;
118
- storeSoundSetting(on);
119
- unlockSound();
120
- byId("sound-note").textContent = "";
147
+ function sendAllSettings(): void {
121
148
  for (const frame of frames.values()) {
122
149
  if (frame.ready) {
123
150
  sendSettings(frame);
124
151
  }
125
152
  }
153
+ refreshMusic();
154
+ }
155
+
156
+ function setSound(on: boolean): void {
157
+ soundOn = on;
158
+ storeSetting(soundKey, on);
159
+ unlockSound();
160
+ byId("sound-note").textContent = "";
161
+ sendAllSettings();
162
+ }
163
+
164
+ function setMusic(on: boolean): void {
165
+ musicOn = on;
166
+ storeSetting(musicKey, on);
167
+ unlockSound();
168
+ sendAllSettings();
126
169
  }
127
170
 
128
171
  function element<K extends keyof HTMLElementTagNameMap>(tag: K, props: Partial<HTMLElementTagNameMap[K]> = {}, ...children: (Node | string)[]): HTMLElementTagNameMap[K] {
@@ -179,7 +222,10 @@ function loadFrame(frame: Frame): void {
179
222
  const current = view;
180
223
  frame.ready = false;
181
224
  frame.sent = undefined;
225
+ frame.settings = undefined;
182
226
  frame.sounds = [];
227
+ frame.track = null;
228
+ refreshMusic();
183
229
  frame.iframe?.remove();
184
230
  frame.iframe = undefined;
185
231
  frame.holder.replaceChildren();
@@ -211,7 +257,7 @@ function buildScreenFrame(root: HTMLElement): void {
211
257
  details.addEventListener("toggle", refreshInsight);
212
258
  const article = element("article", { className: "seat tv" }, bar, holder, details);
213
259
  root.append(article);
214
- const frame: Frame = { seat: screenSeat, screen: true, root: article, iframe: undefined, holder, bot: undefined, botState: undefined, sounds: [], details, snapshot, ready: false, sent: undefined };
260
+ const frame: Frame = { seat: screenSeat, screen: true, root: article, iframe: undefined, holder, bot: undefined, botState: undefined, sounds: [], track: null, details, snapshot, ready: false, sent: undefined };
215
261
  frames.set(screenSeat, frame);
216
262
  loadFrame(frame);
217
263
  }
@@ -228,7 +274,7 @@ function buildSoloFrame(current: DevView, root: HTMLElement): void {
228
274
  const details = element("details", {}, snapshot);
229
275
  const article = element("article", { className: `seat solo-${current.solo?.screen ?? "small"}` }, bar, holder);
230
276
  root.append(article);
231
- const frame: Frame = { seat: "p1", screen: false, root: article, iframe: undefined, holder, bot: undefined, botState: undefined, sounds: [], details, snapshot, ready: false, sent: undefined };
277
+ const frame: Frame = { seat: "p1", screen: false, root: article, iframe: undefined, holder, bot: undefined, botState: undefined, sounds: [], track: null, details, snapshot, ready: false, sent: undefined };
232
278
  frames.set("p1", frame);
233
279
  loadFrame(frame);
234
280
  }
@@ -238,6 +284,7 @@ function buildFrames(current: DevView): void {
238
284
  const root = byId("seats");
239
285
  frames.clear();
240
286
  root.replaceChildren();
287
+ refreshMusic();
241
288
  if (current.solo !== undefined) {
242
289
  buildSoloFrame(current, root);
243
290
  return;
@@ -283,6 +330,7 @@ function buildFrames(current: DevView): void {
283
330
  botState,
284
331
  ...(away === undefined ? {} : { away }),
285
332
  sounds: [],
333
+ track: null,
286
334
  details,
287
335
  snapshot,
288
336
  ready: false,
@@ -566,8 +614,12 @@ function render(next: DevView): void {
566
614
  renderLogs(next.logs);
567
615
  renderInsight(next);
568
616
  for (const frame of frames.values()) {
617
+ if (frame.ready) {
618
+ sendSettings(frame);
619
+ }
569
620
  sendUpdate(frame);
570
621
  }
622
+ refreshMusic();
571
623
  }
572
624
 
573
625
  addEventListener("message", (event: MessageEvent) => {
@@ -588,6 +640,15 @@ addEventListener("message", (event: MessageEvent) => {
588
640
  playSound(frame, message.sound);
589
641
  return;
590
642
  }
643
+ if (message.type === "music") {
644
+ frame.track = message.track;
645
+ refreshMusic();
646
+ return;
647
+ }
648
+ if (message.type === "ready" || message.type === "solo-ready") {
649
+ frame.track = null;
650
+ refreshMusic();
651
+ }
591
652
  if (view?.solo !== undefined) {
592
653
  handleSolo(frame, message);
593
654
  return;
@@ -595,6 +656,7 @@ addEventListener("message", (event: MessageEvent) => {
595
656
  if (message.type === "ready") {
596
657
  frame.ready = true;
597
658
  frame.sent = undefined;
659
+ frame.settings = undefined;
598
660
  sendSettings(frame);
599
661
  sendUpdate(frame);
600
662
  return;
@@ -645,13 +707,14 @@ function handleSolo(frame: Frame, message: NonNullable<ReturnType<typeof parseGa
645
707
  }
646
708
  if (message.type === "solo-ready") {
647
709
  frame.ready = true;
710
+ frame.settings = undefined;
648
711
  sendSettings(frame);
649
712
  void fetch("/__dev/view")
650
713
  .then((response) => response.json() as Promise<DevView>)
651
714
  .then((current) => soloReply(frame, soloMessage(current.language, current.solo?.saved, current.solo?.best ?? {})));
652
715
  return;
653
716
  }
654
- if (message.type === "sound") {
717
+ if (message.type === "sound" || message.type === "music") {
655
718
  return;
656
719
  }
657
720
  if (message.type === "move") {
@@ -706,6 +769,10 @@ function start(): void {
706
769
  const sound = byId<HTMLInputElement>("sound");
707
770
  sound.checked = soundOn;
708
771
  sound.addEventListener("change", () => setSound(sound.checked));
772
+ const music = byId<HTMLInputElement>("music");
773
+ music.checked = musicOn;
774
+ music.addEventListener("change", () => setMusic(music.checked));
775
+ document.addEventListener("visibilitychange", refreshMusic);
709
776
  addEventListener("pointerdown", unlockSound, { capture: true });
710
777
  addEventListener("keydown", unlockSound, { capture: true });
711
778
  const events = new EventSource("/__dev/events");
package/src/dev/page.ts CHANGED
@@ -117,7 +117,9 @@ body.single #solo-box { display: none; }
117
117
  <span class="spacer"></span>
118
118
  <span id="status">connecting …</span>
119
119
  <span id="sound-note" class="tag" aria-live="polite"></span>
120
+ <span id="music-note" class="tag" aria-live="polite"></span>
120
121
  <label id="sound-box" title="Plays the sounds of the game (game.sound) like the platform: off by default, and on iPhones only with the ringer on"><input type="checkbox" id="sound"> Sound</label>
122
+ <label id="music-box" title="Plays the music of the game (game.music) like the platform: on by default, but only together with Sound; the TV's track, otherwise that of the first seat no bot plays"><input type="checkbox" id="music"> Music</label>
121
123
  <button id="pause" type="button" class="multi" hidden>Pause</button>
122
124
  <button id="step" type="button" class="multi" hidden>One tick</button>
123
125
  <select id="speed" class="multi" aria-label="Speed" hidden><option value="1">normal</option><option value="0.5">half speed</option><option value="0.25">quarter speed</option></select>
package/src/dev/view.ts CHANGED
@@ -2,8 +2,10 @@ import {
2
2
  bridgeVersion,
3
3
  soundNotes,
4
4
  tickMs,
5
+ trackLabel,
5
6
  type GameOptions,
6
7
  type Localized,
8
+ type MusicTrack,
7
9
  type OptionsSpec,
8
10
  type PlayerInfo,
9
11
  type ProfileData,
@@ -159,8 +161,25 @@ export function frameUpdate(current: DevView, seat: string): Record<string, unkn
159
161
  };
160
162
  }
161
163
 
162
- export function settingsMessage(sound: boolean): Record<string, unknown> {
163
- return { gamehearth: bridgeVersion, type: "settings", sound };
164
+ export function settingsMessage(sound: boolean, music = false): Record<string, unknown> {
165
+ return { gamehearth: bridgeVersion, type: "settings", sound, music: sound && music };
166
+ }
167
+
168
+ export const devSwitchDefaults = { sound: false, music: true } as const;
169
+
170
+ export interface MusicFrame {
171
+ screen: boolean;
172
+ seat: string;
173
+ track: MusicTrack | null;
174
+ }
175
+
176
+ export function musicSource<F extends MusicFrame>(frames: Iterable<F>, bots: ReadonlySet<string> = new Set()): F | undefined {
177
+ const all = [...frames].filter((frame) => !bots.has(frame.seat));
178
+ return all.find((frame) => frame.screen && frame.track !== null) ?? all.find((frame) => !frame.screen && frame.track !== null);
179
+ }
180
+
181
+ export function musicLabel(track: MusicTrack | null, playing: boolean): string {
182
+ return track === null || !playing ? "" : `♪ ${trackLabel(track)}`;
164
183
  }
165
184
 
166
185
  export const soundPeakGain = 0.12;
@@ -177,6 +177,16 @@ The platform plays the sounds; the UI only names them: `game.sound("coin")` with
177
177
  - Sound is off by default; players turn it on in the menu of the game page, the TV has its own switch, and on an iPhone the ringer switch must be on too. So nothing important may only be heard. `game.soundOn` says whether it is on.
178
178
  - In `npm run dev` the "Sound" switch at the top turns it on for the TV and all phones (also off by default); the header names the last sound played and its frame, so you can check it without speakers.
179
179
 
180
+ ## Music
181
+
182
+ The platform also plays music: a loop the game describes with notes. `game.music(track)` starts it, `game.music(null)` stops it; again no audio files and no Phaser audio. Tag has no music; add some only if the person wants it.
183
+
184
+ - **Shared music comes from the TV.** Call `game.music` only in the TV's code (`client/src/screen.ts`), so that the phones do not all play along; the TV has its own switches.
185
+ - **One loop per scene,** for example one for the round and none between rounds. Call `game.music` when the scene changes, never on every tick: the same track again keeps playing, another one crossfades in about a second.
186
+ - A track has `bpm` (40 to 240), `beats` (the length of the loop, a whole number from 1 to 128; at most 60 seconds), an optional `name` (`dev` shows it) and 1 to 4 `voices`, each with an `instrument` (`square`, `sine`, `triangle`, `sawtooth`, `musicbox`, `organ`, `pluck`, `bass`, `noise`), an optional `volume` and its `notes`: `freq` in hertz, `at` and `length` in beats, optionally `volume` and `to` (slides to this pitch). At most 256 notes in all, 64 per second and 24 sounding at the same time (SDK README, "Music"). Keep tracks as constants in `client/src/view.ts` and give each a test with `trackProblem` from `@gamehearth/sdk/platform`; an invalid track plays nothing and only shows up on the console.
187
+ - **Plays only with sound on.** Music plays only when sound and the music switch are both on; sound is off by default and music on, so turning on sound brings the music along, and players can turn music off on its own. The platform remembers the last track and starts it once both are on, so the game does not need to react to the switches. `game.musicOn` and `game.onMusic` say whether music plays. Music is mood: nothing important may only be heard in it.
188
+ - In `npm run dev` the "Music" switch at the top is on by default and "Sound" off, as on the platform: music plays once you turn on "Sound", and only one frame's: the TV's, otherwise that of the first seat with a track that no bot plays. The header names the playing track while it plays.
189
+
180
190
  ## Languages
181
191
 
182
192
  The example speaks English and German; the German is only an example of a translation. Replace it with the languages of your game (see "Who you work with").
@@ -18,12 +18,12 @@
18
18
  "pack": "npm run build && gamehearth pack ."
19
19
  },
20
20
  "dependencies": {
21
- "@gamehearth/sdk": "^0.1.8",
21
+ "@gamehearth/sdk": "^0.1.9",
22
22
  "phaser": "4.2.1"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@types/node": "^22.20.5",
26
- "gamehearth": "^0.10.0",
26
+ "gamehearth": "^0.11.0",
27
27
  "typescript": "^7.0.2",
28
28
  "vite": "^8.3.5",
29
29
  "vitest": "^5.1.0"
@@ -24,7 +24,7 @@ The person probably can't program. They know their game, not the code.
24
24
  | `client/src/main.ts` | connects the game to the platform (`connectSolo`), starts Phaser and the menu |
25
25
  | `client/src/scene.ts` | the level in Phaser 4 with arcade physics: walls, character, mushrooms, time |
26
26
  | `client/src/controls.ts` | d-pad and keyboard |
27
- | `client/src/view.ts` | everything the UI decides, without Phaser and without a browser (no `document`, no `HTMLElement`; texts, menu, time format, steering); the tests and `npm run typecheck` check it without a DOM |
27
+ | `client/src/view.ts` | everything the UI decides, without Phaser and without a browser (no `document`, no `HTMLElement`; texts, menu, time format, steering, music); the tests and `npm run typecheck` check it without a DOM |
28
28
  | `client/src/texts.ts` | every text of the game, one block per language |
29
29
  | `client/index.html` | field, d-pad and the menu as HTML |
30
30
  | `client/public/cover.svg` | the cover of the game (4:3); the build copies `client/public/` into the client folder |
@@ -118,6 +118,15 @@ The platform plays the sounds; the game only names them: `game.sound("coin")` wi
118
118
  - Sound is off by default; players turn it on in the menu of the game page, and on an iPhone the ringer switch must be on too. So nothing important may only be heard. `game.soundOn` says whether it is on.
119
119
  - In `npm run dev` the "Sound" switch at the top turns it on (also off by default); the header names the last sound played, so you can check it without speakers.
120
120
 
121
+ ## Music
122
+
123
+ The platform also plays music: a loop the game describes with notes. `game.music(track)` starts it, `game.music(null)` stops it; again no audio files and no Phaser audio.
124
+
125
+ - **One loop per scene.** Mushroom Hunt plays `levelMusic`, a short music-box loop in `client/src/view.ts`, while a level runs, and nothing in the menu (`sceneMusic`, called in `client/src/main.ts` when the scene changes). Call `game.music` when the scene changes, never every frame: the same track again keeps playing, another one crossfades in about a second.
126
+ - A track has `bpm` (40 to 240), `beats` (the length of the loop, a whole number from 1 to 128; at most 60 seconds), an optional `name` (`dev` shows it) and 1 to 4 `voices`, each with an `instrument` (`square`, `sine`, `triangle`, `sawtooth`, `musicbox`, `organ`, `pluck`, `bass`, `noise`), an optional `volume` and its `notes`: `freq` in hertz, `at` and `length` in beats, optionally `volume` and `to` (slides to this pitch). At most 256 notes in all, 64 per second and 24 sounding at the same time (SDK README, "Music"). Every track gets a test with `trackProblem` from `@gamehearth/sdk/platform`, as in `test/view.test.ts`; an invalid track plays nothing and only shows up on the console.
127
+ - **Plays only with sound on.** Music plays only when sound and the music switch are both on; sound is off by default and music on, so turning on sound brings the music along, and players can turn music off on its own. The platform remembers the last track and starts it once both are on, so the game does not need to react to the switches. `game.musicOn` and `game.onMusic` say whether music plays. Music is mood: nothing important may only be heard in it.
128
+ - In `npm run dev` the "Music" switch at the top is on by default and "Sound" off, as on the platform: music plays once you turn on "Sound". The header names the playing track (`♪ Mushroom forest`) while it plays.
129
+
121
130
  ## Languages
122
131
 
123
132
  The example speaks English and German; the German is only an example of a translation. Replace it with the languages of your game (see "Who you work with").
@@ -13,7 +13,7 @@ A single-player game for [Gamehearth](https://github.com/hearthbit/gamehearth-st
13
13
 
14
14
  ## Sound
15
15
 
16
- With the sound switched on, you hear the start of a level, every mushroom, a level done and the end of the run.
16
+ With the sound switched on, you hear the start of a level, every mushroom, a level done and the end of the run. While you play a level, a short music-box loop runs; the music switch in the menu turns it off on its own.
17
17
 
18
18
  ## Languages
19
19
 
@@ -4,7 +4,7 @@ import { finishLevel, readSave, startRun, withLevelTime, type Save } from "../..
4
4
  import { mountControls } from "./controls";
5
5
  import { fieldHeight, fieldWidth, LevelScene } from "./scene";
6
6
  import { texts } from "./texts";
7
- import { finishLine, finishSound, menuEntries, recordLine, sharpness, type MenuEntry } from "./view";
7
+ import { finishLine, finishSound, menuEntries, recordLine, sceneMusic, sharpness, type MenuEntry } from "./view";
8
8
 
9
9
  function byId(id: string): HTMLElement {
10
10
  const node = document.getElementById(id);
@@ -42,6 +42,7 @@ async function start(): Promise<void> {
42
42
  const entries = byId("entries");
43
43
 
44
44
  const showMenu = (message: string) => {
45
+ game.music(sceneMusic("menu"));
45
46
  byId("record").textContent = recordLine(t, game.best["best-time"]);
46
47
  byId("message").textContent = message;
47
48
  entries.replaceChildren(
@@ -105,6 +106,7 @@ async function start(): Promise<void> {
105
106
  }
106
107
  menu.hidden = true;
107
108
  game.sound("start");
109
+ game.music(sceneMusic("level"));
108
110
  controls.reset();
109
111
  const run = save.run;
110
112
  if (run !== null) {
@@ -1,4 +1,4 @@
1
- import type { SoundName } from "@gamehearth/sdk/client";
1
+ import type { MusicTrack, SoundName } from "@gamehearth/sdk/client";
2
2
  import { levelCount, type Finished, type Save } from "../../src/rules";
3
3
  import type { Texts } from "./texts";
4
4
 
@@ -50,6 +50,40 @@ export function finishSound(finished: Finished | undefined): SoundName {
50
50
  return finished === undefined ? "coin" : "win";
51
51
  }
52
52
 
53
+ export const levelMusic: MusicTrack = {
54
+ name: "Mushroom forest",
55
+ bpm: 100,
56
+ beats: 8,
57
+ voices: [
58
+ {
59
+ instrument: "musicbox",
60
+ notes: [
61
+ { freq: 783.99, at: 0, length: 1 },
62
+ { freq: 659.25, at: 1, length: 0.5 },
63
+ { freq: 587.33, at: 1.5, length: 0.5 },
64
+ { freq: 523.25, at: 2, length: 1 },
65
+ { freq: 659.25, at: 3, length: 1 },
66
+ { freq: 880, at: 4, length: 1 },
67
+ { freq: 783.99, at: 5, length: 0.5 },
68
+ { freq: 659.25, at: 5.5, length: 0.5 },
69
+ { freq: 587.33, at: 6, length: 2 },
70
+ ],
71
+ },
72
+ {
73
+ instrument: "bass",
74
+ volume: 0.3,
75
+ notes: [
76
+ { freq: 130.81, at: 0, length: 4 },
77
+ { freq: 98, at: 4, length: 4 },
78
+ ],
79
+ },
80
+ ],
81
+ };
82
+
83
+ export function sceneMusic(scene: "menu" | "level"): MusicTrack | null {
84
+ return scene === "level" ? levelMusic : null;
85
+ }
86
+
53
87
  export function hudLine(t: Texts, level: number, elapsedMs: number, found: number, total: number): string {
54
88
  return t.hud(level + 1, levelCount, formatTime(t, elapsedMs), found, total);
55
89
  }
@@ -18,12 +18,12 @@
18
18
  "pack": "npm run build && gamehearth pack ."
19
19
  },
20
20
  "dependencies": {
21
- "@gamehearth/sdk": "^0.1.8",
21
+ "@gamehearth/sdk": "^0.1.9",
22
22
  "phaser": "4.2.1"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@types/node": "^22.20.5",
26
- "gamehearth": "^0.10.0",
26
+ "gamehearth": "^0.11.0",
27
27
  "typescript": "^7.0.2",
28
28
  "vite": "^8.3.5",
29
29
  "vitest": "^5.1.0"
@@ -1,7 +1,28 @@
1
+ import { musicSeconds, trackProblem } from "@gamehearth/sdk/platform";
1
2
  import { describe, expect, it } from "vitest";
2
3
  import manifest from "../manifest.json";
3
4
  import { texts } from "../client/src/texts";
4
- import { cell, directionOfKey, finishLine, finishSound, formatTime, frameMs, hudLine, menuEntries, padDirection, pressKey, recordLine, releaseKey, sharpness, speed, steerTowardLane, topKey, velocity } from "../client/src/view";
5
+ import {
6
+ cell,
7
+ directionOfKey,
8
+ finishLine,
9
+ finishSound,
10
+ formatTime,
11
+ frameMs,
12
+ hudLine,
13
+ levelMusic,
14
+ menuEntries,
15
+ padDirection,
16
+ pressKey,
17
+ recordLine,
18
+ releaseKey,
19
+ sceneMusic,
20
+ sharpness,
21
+ speed,
22
+ steerTowardLane,
23
+ topKey,
24
+ velocity,
25
+ } from "../client/src/view";
5
26
 
6
27
  const en = texts("en");
7
28
  const de = texts("de");
@@ -52,6 +73,15 @@ describe("Sound", () => {
52
73
  });
53
74
  });
54
75
 
76
+ describe("Music", () => {
77
+ it("plays a valid music-box loop in a level and nothing in the menu", () => {
78
+ expect(trackProblem(levelMusic)).toBeUndefined();
79
+ expect(musicSeconds(levelMusic)).toBeCloseTo(4.8);
80
+ expect(sceneMusic("level")).toBe(levelMusic);
81
+ expect(sceneMusic("menu")).toBeNull();
82
+ });
83
+ });
84
+
55
85
  describe("Controls", () => {
56
86
  it("moves in exactly one direction", () => {
57
87
  expect(velocity("up")).toEqual({ x: 0, y: -speed });
@@ -202,6 +202,15 @@ The platform plays the sounds; the UI only names them: `game.sound("coin")` with
202
202
  - Sound is off by default; players turn it on in the menu of the game page, and on an iPhone the ringer switch must be on too. So nothing important may only be heard. `game.soundOn` says whether it is on.
203
203
  - In `npm run dev` the "Sound" switch at the top turns it on (also off by default); the header names the last sound played, so you can check it without speakers.
204
204
 
205
+ ## Music
206
+
207
+ The platform also plays music: a loop the game describes with notes. `game.music(track)` starts it, `game.music(null)` stops it; again no audio files and no Phaser audio. Card Duel has no music; add some only if the person wants it.
208
+
209
+ - **One loop per scene,** for example one for the match and none for the result. Call `game.music` when the scene changes, never on every update: the same track again keeps playing, another one crossfades in about a second. Here every phone plays its own music, so all players hear the loop on their own device.
210
+ - A track has `bpm` (40 to 240), `beats` (the length of the loop, a whole number from 1 to 128; at most 60 seconds), an optional `name` (`dev` shows it) and 1 to 4 `voices`, each with an `instrument` (`square`, `sine`, `triangle`, `sawtooth`, `musicbox`, `organ`, `pluck`, `bass`, `noise`), an optional `volume` and its `notes`: `freq` in hertz, `at` and `length` in beats, optionally `volume` and `to` (slides to this pitch). At most 256 notes in all, 64 per second and 24 sounding at the same time (SDK README, "Music"). Keep tracks as constants in `client/src/view.ts` and give each a test with `trackProblem` from `@gamehearth/sdk/platform`; an invalid track plays nothing and only shows up on the console.
211
+ - **Plays only with sound on.** Music plays only when sound and the music switch are both on; sound is off by default and music on, so turning on sound brings the music along, and players can turn music off on its own. The platform remembers the last track and starts it once both are on, so the game does not need to react to the switches. `game.musicOn` and `game.onMusic` say whether music plays. Music is mood: nothing important may only be heard in it.
212
+ - In `npm run dev` the "Music" switch at the top is on by default and "Sound" off, as on the platform: music plays once you turn on "Sound", and only one frame's: that of the first seat with a track that no bot plays. The header names the playing track while it plays.
213
+
205
214
  ## Languages
206
215
 
207
216
  The example speaks English and German; the German is only an example of a translation. Replace it with the languages of your game (see "Who you work with").
@@ -18,12 +18,12 @@
18
18
  "pack": "npm run build && gamehearth pack ."
19
19
  },
20
20
  "dependencies": {
21
- "@gamehearth/sdk": "^0.1.8",
21
+ "@gamehearth/sdk": "^0.1.9",
22
22
  "phaser": "4.2.1"
23
23
  },
24
24
  "devDependencies": {
25
25
  "@types/node": "^22.20.5",
26
- "gamehearth": "^0.10.0",
26
+ "gamehearth": "^0.11.0",
27
27
  "typescript": "^7.0.2",
28
28
  "vite": "^8.3.5",
29
29
  "vitest": "^5.1.0"