diff game/js/audio.js @ 8:2c4fed8baed9

art update, persistent sound setting, tower selling as double action
author ark
date 2026-10-19 13:37 +0200
parents 910b26feca76
children
line wrap: on
line diff
--- a/game/js/audio.js	Mon Oct 19 11:50:24 2026 +0200
+++ b/game/js/audio.js	Mon Oct 19 13:37:52 2026 +0200
@@ -1,5 +1,6 @@
 // sound: recorded sounds from data/sounds.js, placeholder beeps for events
-// without a recording
+// without a recording. the player's sound on or off choice is stored with
+// MM.storage; the config's enabled setting applies until the first choice.
 
 window.MM = window.MM || {};
 
@@ -12,15 +13,16 @@
     var last = {};      // event -> audio clock time of its last play
     var ends = {};      // event -> audio clock time when its sounds have ended
     var started = false;
+    var on = MM.storage.get("sound", cfg.enabled);
 
     // create the audio context and decode the recordings. the browser keeps
     // the context suspended until unlock() runs in a user interaction.
     function init() {
         var AC = window.AudioContext || window.webkitAudioContext;
-        if (!AC || !cfg.enabled) return;
+        if (!AC) return;
         ctx = new AC();
         master = ctx.createGain();
-        master.gain.value = cfg.volume;
+        master.gain.value = on ? cfg.volume : 0;
         master.connect(ctx.destination);
         var sounds = MM.sounds || {};
         Object.keys(sounds).forEach(function (name) {
@@ -80,7 +82,7 @@
     // variants are picked with Math.random, so sound does not change the
     // game's seeded random numbers.
     function play(name, after) {
-        if (!ctx || ctx.state !== "running") return;
+        if (!on || !ctx || ctx.state !== "running") return;
         var ev = cfg.event[name];
         if (!ev) return;
         var now = ctx.currentTime;
@@ -108,5 +110,17 @@
         ends[name] = Math.max(ends[name] || 0, when + length);
     }
 
-    return { init: init, start: start, unlock: unlock, play: play };
+    function enabled() {
+        return on;
+    }
+
+    // switch sound on or off and store the choice. sounds already playing
+    // are muted at once.
+    function toggle() {
+        on = !on;
+        if (master) master.gain.value = on ? cfg.volume : 0;
+        MM.storage.set("sound", on);
+    }
+
+    return { init: init, start: start, unlock: unlock, play: play, enabled: enabled, toggle: toggle };
 })();