From 9bc39faffb89aa28b4d8326d620324a3c789af03 Mon Sep 17 00:00:00 2001 From: Michi Date: Fri, 13 Nov 2026 00:41:54 +0100 Subject: [PATCH] main init --- .dashboard.json | 8 + .gitignore | 7 + CLAUDE.md | 70 ++++ README.md | 70 ++++ build-web.mjs | 54 +++ build.ps1 | 41 ++ docs/firebase/README.md | 26 ++ docs/firebase/database.rules.json | 19 + docs/itchio/README.md | 38 ++ docs/itchio/description.html | 28 ++ game/ai.js | 134 ++++++ game/combat.js | 428 +++++++++++++++++++ game/game.js | 440 ++++++++++++++++++++ game/garage.js | 95 +++++ game/index.html | 211 ++++++++++ game/kit/kit-audio.js | 157 +++++++ game/kit/kit-core.js | 142 +++++++ game/kit/kit-fx.js | 72 ++++ game/kit/kit-host.js | 39 ++ game/kit/kit-i18n.js | 62 +++ game/kit/kit-input.js | 73 ++++ game/kit/kit-loop.js | 75 ++++ game/kit/kit-scores.js | 64 +++ game/lang.js | 168 ++++++++ game/parts.js | 66 +++ game/render3d.js | 666 ++++++++++++++++++++++++++++++ game/robot.js | 58 +++ game/vendor/three.min.js | 6 + launcher/Launcher.csproj | 42 ++ launcher/Program.cs | 175 ++++++++ sprite-generator/audio.py | 11 + sprite-generator/config.py | 38 ++ sprite-generator/gen.cmd | 24 ++ sprite-generator/prompts.py | 18 + tests/balance.js | 26 ++ tests/sim.test.js | 56 +++ 36 files changed, 3707 insertions(+) create mode 100644 .dashboard.json create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 README.md create mode 100644 build-web.mjs create mode 100644 build.ps1 create mode 100644 docs/firebase/README.md create mode 100644 docs/firebase/database.rules.json create mode 100644 docs/itchio/README.md create mode 100644 docs/itchio/description.html create mode 100644 game/ai.js create mode 100644 game/combat.js create mode 100644 game/game.js create mode 100644 game/garage.js create mode 100644 game/index.html create mode 100644 game/kit/kit-audio.js create mode 100644 game/kit/kit-core.js create mode 100644 game/kit/kit-fx.js create mode 100644 game/kit/kit-host.js create mode 100644 game/kit/kit-i18n.js create mode 100644 game/kit/kit-input.js create mode 100644 game/kit/kit-loop.js create mode 100644 game/kit/kit-scores.js create mode 100644 game/lang.js create mode 100644 game/parts.js create mode 100644 game/render3d.js create mode 100644 game/robot.js create mode 100644 game/vendor/three.min.js create mode 100644 launcher/Launcher.csproj create mode 100644 launcher/Program.cs create mode 100644 sprite-generator/audio.py create mode 100644 sprite-generator/config.py create mode 100644 sprite-generator/gen.cmd create mode 100644 sprite-generator/prompts.py create mode 100644 tests/balance.js create mode 100644 tests/sim.test.js diff --git a/.dashboard.json b/.dashboard.json new file mode 100644 index 0000000..c03bb04 --- /dev/null +++ b/.dashboard.json @@ -0,0 +1,8 @@ +{ + "status": "active", + "priority": "medium", + "notes": "Roboterkampf-Webspiel (three.js), Vorlage webgame aus _Tools\\Library", + "tags": ["webgame"], + "tasks": [], + "updatedAt": "2026-11-12T22:46:03.678Z" +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fe87b55 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +release/ +launcher/bin/ +launcher/obj/ +sprite-generator/output/ +sprite-generator/__pycache__/ +node_modules/ +*.log diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..e0d166a --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,70 @@ +# Robot Clash + +HTML-Spiel mit three.js (3D, isometrisch) ohne Build-Schritt, angelegt aus `D:\Oculusquest\Projekt\_Tools\Library` +(Vorlage `webgame`). Aufbau und Befehle: `README.md`. + +## Herkunft / Abgrenzung + +Inspiriert vom Genre der Roboterkampf-Browserspiele (z. B. Robot Rage / Robot Kampen, 2005). **Eigenes Spiel:** +keine Namen, Figuren, Arenen, Hausroboter, Grafiken, Sounds oder Code aus dem Original oder aus Ports davon +(z. B. `github.com/AndrewEyesman/robot-rage` – dessen Spielskripte/Assets gehören Raketspel/Miniclip). +Übernommen sind nur allgemeine Genre-Mechaniken (Teile-Slots, Werkstatt-Regeln, Arena-Gefahren, Grube). + +## Spielkonzept + +**Ablauf** +1. **Werkstatt:** Roboter aus Teilen bauen – je 1 Chassis, Motor, Räder, Batterie (Pflicht), dazu Panzerung, + Hauptwaffe (Keil, Flipper, Axt, Säge, Zange, Spinner) und Turm (Flammen, Minigun, Raketen). Max. 100 kg, + Batterie muss den Strom liefern. Kaufen / einbauen / verkaufen (50 %), Lack + Akzentfarbe, Name. +2. **Liga:** 8 KI-Gegner nacheinander (Stile: Raufbold, Flankierer, Schieber, Schütze), steigende Preise. +3. **Kampf (2 min, isometrisch 3D):** Arena mit Stachelwänden, 2 Bodensägen, 2 Flammengittern, 2 Arena-Wächtern + in den Ecken (Schmiedepresse, Magnetkran) und einer Grube, die zur Halbzeit aufgeht. +4. **Sieg:** K.o., Gegner in der Grube, oder nach Zeit über Schaden (Fallen-Schaden zählt für den Gegner). +5. **Ergebnis:** Preisgeld (+ K.o./Gruben-Bonus) bzw. Antrittsgeld, Reparaturkosten, Ruhm → zurück in die Werkstatt. + +**Ziel / Ende:** Meister der Saison (alle 8 besiegt) → neue Saison, Gegner stärker, Preise ×1,5. Ruhm = Punktestand +(Online-Rangliste über `Kit.scores`, sobald `DB_URL` gesetzt ist). + +**Steuerung:** WASD/Pfeile Panzersteuerung, Leertaste Hauptwaffe, Shift/E Turm, P/Esc Pause, M Ton; Gamepad +(Stick, A Waffe, B Turm, Start Pause); Touch-Knöpfe auf Touchgeräten. + +**Stil:** Industrielle Show-Arena bei Nacht, Flutlicht, kantige Bastel-Roboter aus Blech, Funken, Warnstreifen. +Akzent `#FF7A1A`, Überschriften „Russo One“ (Fallback Segoe UI Black). Grafik derzeit komplett prozedural (three.js). +Stilblock für ComfyGen: *isometric 3/4 view game sprite, chunky handmade combat robot, scratched painted steel, +bolts and hazard stripes, bold clean shapes, soft studio lighting, high detail, plain solid black background* + +**Erste Version (drin):** Werkstatt mit 25 Teilen in 7 Slots, 1 Arena, 8 Liga-Gegner + Training, Saisons, +Speichern, en/de, Synth-Sounds. **Später:** Firebase-Rangliste (URL von Michael), asynchrones PvP (hochgeladene +Roboter, KI-gesteuert), echtes PvP (WebRTC), Replays/Zuschauer, weitere Arenen + Gewichtsklassen, Icon/Musik/SFX +über ComfyGen, Schrift „Russo One“ lokal in `assets/Fonts`. + +## Dateien + +- `game/parts.js` Teilekatalog · `game/robot.js` Bauregeln + Werte · `game/combat.js` Physik, Waffen, Fallen, + Siegregeln · `game/ai.js` KI + Liga-Kader – alle ohne DOM, laufen in Node. +- `game/render3d.js` three.js-Szenen (Werkstatt, Arena), Roboter-Modelle aus Teilen, Partikel. +- `game/garage.js` Werkstatt-Panel · `game/game.js` Ablauf, Menüs, Kampf-HUD, Sound, Speichern. +- `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten). +- Tests: `node tests/sim.test.js` (Regeln, Kämpfe ohne NaN, Grube), `node tests/balance.js [-v]` (Zahlen). +- Dev-Parameter: `index.html?play` (Werkstatt), `?fight=N` (Training gegen Liga-Gegner N), `&auto` (KI fährt + für dich), `&ff=30` (30 s vorspulen). + +## Arbeitsweise + +- Antworten auf Deutsch, knapp. Code und Kommentare auf Englisch, Dokumentation für Michael auf Deutsch. +- **Jeder sichtbare Text** steht in `game/lang.js`, immer **Englisch und Deutsch**; im Code nur `t('key')`, + in `index.html` `data-i18n="key"`. Kein fest eingebauter Text in `game.js`. +- **Credits bleiben drin:** Menü zeigt „© Jahr Michael Media“ + Discord-Link (`CREDITS` in `game.js`), + README ebenso, exe-Eigenschaften (Company/Copyright) in `launcher/Launcher.csproj`. +- `game/kit/` ist eine Kopie aus `_Tools\Library\web\kit`. Fehlt dort etwas oder ist ein Fehler drin: + **in der Library** ändern, dann `new-project.ps1 -UpdateKit -Path .` – nie nur hier. +- Spiel muss per Doppelklick auf `game/index.html` laufen (`file://`): keine ES-Module, kein fetch auf + lokale JSON-Dateien (Daten als `.js`, die ein globales Objekt setzen). +- Kleine Dateien mit sprechenden Namen, sobald `game.js` über ~1500 Zeilen wächst (z. B. `levels.js`, + `render.js`, `ui.js`), alle als `` : m); +// static references in CSS / HTML attributes +html = html.replace(/url\((['"]?)(assets\/[^'")]+)\1\)/g, (m, q, p) => (assets[p] ? `url('${assets[p]}')` : m)); +html = html.replace(/(src|href)="(assets\/[^"]+)"/g, (m, a, p) => (assets[p] ? `${a}="${assets[p]}"` : m)); +// everything the scripts load at runtime: must come before the first other \n + + + + + + + + + + + + + + + + + + diff --git a/game/kit/kit-audio.js b/game/kit/kit-audio.js new file mode 100644 index 0000000..cdaad0e --- /dev/null +++ b/game/kit/kit-audio.js @@ -0,0 +1,157 @@ +/* Kit audio (v1) - WebAudio for HTML games. From _Tools\Library\web\kit. Needs kit-core.js. + + const audio = Kit.createAudio({ + prefix: 'mygame', // localStorage keys mygame.muted / .music / .sfx + dir: 'assets/Audio/', ext: '.mp3', // where ComfyGen adopt_audio puts the files + files: ['sfx_click', 'sfx_win', 'music_game'], + throttle: { sfx_step: 60 }, // optional min gap in ms per clip + }); + audio.sfx('sfx_click') play once (silent if missing / not decoded yet) + audio.music('music_game') loop as music (switching tracks fades the old one) + const h = audio.loop('sfx_flow', 0.5); h.stop() looping effect + audio.tone(880, 0.1) / audio.noise(0.2) synth fallback sounds, no files needed + audio.toggleMute() / audio.setVolume(music, sfx) / audio.muted / audio.musicVol / audio.sfxVol + + Best effort everywhere: missing files, a blocked AudioContext or no WebAudio never throw. + The context is created on the first pointer/key press (autoplay policy) - nothing to call. */ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + + Kit.createAudio = (opt = {}) => { + const st = Kit.store(opt.prefix || 'kit'); + const dir = opt.dir || 'assets/Audio/', ext = opt.ext || '.mp3'; + const files = opt.files || [], throttle = opt.throttle || {}; + let ctx = null, musicGain = null, sfxGain = null, musicSrc = null, musicName = null, wantMusic = null; + const buffers = {}, loading = {}, last = {}; + const api = { + muted: st.get('muted', false), + musicVol: st.get('music', 0.35), + sfxVol: st.get('sfx', 0.8), + }; + // slider 0..1 -> gain; squared so the low end of a slider is fine-grained + const g = v => (api.muted ? 0 : v * v); + + function unlock() { + if (ctx) { if (ctx.state === 'suspended') ctx.resume().catch(() => {}); return; } + try { + ctx = new (root.AudioContext || root.webkitAudioContext)(); + musicGain = ctx.createGain(); musicGain.gain.value = g(api.musicVol); musicGain.connect(ctx.destination); + sfxGain = ctx.createGain(); sfxGain.gain.value = g(api.sfxVol); sfxGain.connect(ctx.destination); + for (const n of files) load(n); + if (wantMusic) api.music(wantMusic); + } catch (e) { ctx = null; } + } + if (typeof document !== 'undefined') { + for (const ev of ['pointerdown', 'keydown', 'touchstart']) addEventListener(ev, unlock, { capture: true, passive: true }); + // Android leaves a context suspended after backgrounding unless it is resumed by hand + document.addEventListener('visibilitychange', () => { + if (!ctx) return; + if (document.hidden) ctx.suspend().catch(() => {}); else ctx.resume().catch(() => {}); + }); + } + + function load(name) { + if (!ctx) return Promise.resolve(null); + if (buffers[name]) return Promise.resolve(buffers[name]); + if (loading[name]) return loading[name]; + return (loading[name] = Kit.loadBytes(Kit.asset(dir + name + ext)) + .then(b => ctx.decodeAudioData(b)) + .then(buf => (buffers[name] = buf)) + .catch(() => null) + .finally(() => { delete loading[name]; })); + } + + function start(buf, vol, loop, bus) { + const src = ctx.createBufferSource(); + src.buffer = buf; src.loop = loop; + const gn = ctx.createGain(); gn.gain.value = vol; + src.connect(gn).connect(bus); + src.start(); + src.gainNode = gn; + return src; + } + function fadeStop(src) { + if (!src || !ctx) return; + try { src.gainNode.gain.setTargetAtTime(0, ctx.currentTime, 0.08); src.stop(ctx.currentTime + 0.4); } catch (e) { /* stopped */ } + } + + api.sfx = (name, vol = 1) => { + if (!ctx || api.muted) return; + if (ctx.state === 'suspended') ctx.resume().catch(() => {}); + const gap = throttle[name] || 0, now = performance.now(); + if (gap && now - (last[name] || 0) < gap) return; + last[name] = now; + // first use of a clip that is still decoding: play it once it is ready instead of dropping it + if (buffers[name]) start(buffers[name], vol, false, sfxGain); + else load(name).then(b => { if (b && !api.muted) start(b, vol, false, sfxGain); }); + }; + + api.loop = (name, vol = 1) => { + const h = { src: null, stopped: false, stop() { h.stopped = true; fadeStop(h.src); h.src = null; } }; + if (!ctx) return h; + load(name).then(b => { if (b && !h.stopped) h.src = start(b, vol, true, sfxGain); }); + return h; + }; + + api.music = name => { + wantMusic = name; + if (!ctx || musicName === name) return; + musicName = name; + load(name).then(b => { + if (!b || musicName !== name) { if (!b && musicName === name) musicName = null; return; } + fadeStop(musicSrc); + musicSrc = start(b, 1, true, musicGain); + }); + }; + api.stopMusic = () => { wantMusic = null; musicName = null; fadeStop(musicSrc); musicSrc = null; }; + + function apply() { + if (musicGain) musicGain.gain.value = g(api.musicVol); + if (sfxGain) sfxGain.gain.value = g(api.sfxVol); + } + api.toggleMute = () => { api.muted = !api.muted; st.set('muted', api.muted); apply(); return api.muted; }; + api.setVolume = (music, sfx) => { + if (music != null) { api.musicVol = Kit.clamp(+music || 0, 0, 1); st.set('music', api.musicVol); } + if (sfx != null) { api.sfxVol = Kit.clamp(+sfx || 0, 0, 1); st.set('sfx', api.sfxVol); } + if (api.muted && (music > 0 || sfx > 0)) { api.muted = false; st.set('muted', false); } + apply(); + }; + // duck music under a big moment (ramped, no clicks) + api.duck = (on, secs = 0.2) => { + if (!ctx || !musicGain) return; + const t = ctx.currentTime; + musicGain.gain.cancelScheduledValues(t); + musicGain.gain.setValueAtTime(musicGain.gain.value, t); + musicGain.gain.linearRampToValueAtTime(on ? 0 : g(api.musicVol), t + secs); + }; + api.suspend = () => { if (ctx) ctx.suspend().catch(() => {}); }; + api.resume = () => { if (ctx && !document.hidden) ctx.resume().catch(() => {}); }; + api.unlock = unlock; + + // ---- synth (placeholder sounds until ComfyGen clips exist) -------------------------- + api.tone = (freq, dur = 0.1, type = 'square', vol = 0.3, slide = 0, delay = 0) => { + if (!ctx || api.muted) return; + const t = ctx.currentTime + delay; + const o = ctx.createOscillator(), gn = ctx.createGain(); + o.type = type; o.frequency.setValueAtTime(freq, t); + if (slide) o.frequency.exponentialRampToValueAtTime(Math.max(30, freq + slide), t + dur); + gn.gain.setValueAtTime(vol, t); gn.gain.exponentialRampToValueAtTime(0.001, t + dur); + o.connect(gn).connect(sfxGain); o.start(t); o.stop(t + dur + 0.02); + }; + api.noise = (dur = 0.2, vol = 0.3, cutoff = 1200, delay = 0) => { + if (!ctx || api.muted) return; + const t = ctx.currentTime + delay, len = Math.floor(ctx.sampleRate * dur); + const buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0); + for (let i = 0; i < len; i++) d[i] = (Math.random() * 2 - 1) * (1 - i / len); + const src = ctx.createBufferSource(), f = ctx.createBiquadFilter(), gn = ctx.createGain(); + src.buffer = buf; f.type = 'lowpass'; f.frequency.value = cutoff; gn.gain.value = vol; + src.connect(f).connect(gn).connect(sfxGain); src.start(t); + }; + // little arpeggio: audio.arp([523, 659, 784], 0.12) + api.arp = (freqs, step = 0.08, type = 'square', vol = 0.18) => + freqs.forEach((f, i) => api.tone(f, step * 1.6, type, vol, 0, i * step)); + + return api; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/kit/kit-core.js b/game/kit/kit-core.js new file mode 100644 index 0000000..1bd0b67 --- /dev/null +++ b/game/kit/kit-core.js @@ -0,0 +1,142 @@ +/* Kit core (v1) - from D:\Oculusquest\Projekt\_Tools\Library\web\kit. + Do not fork this copy inside a project: improve it in the Library and re-copy with + new-project.ps1 -UpdateKit. Classic script (no ES module) so the game also runs from file://. + + Kit.$(id) document.getElementById + Kit.asset(path) path, or the data: URI the single-file build embedded + Kit.loadBytes(url) ArrayBuffer (works for data: URIs and files) + Kit.images(names, dir, ext) { name: Image } - img.ok is true once loaded + Kit.store(prefix) safe localStorage JSON get/set/del + Kit.saveSlot(key, defaults, opt) versioned save with backup copy + defaults merge + Kit.rng(seed) seeded random() in [0,1) (mulberry32) + Kit.clamp / lerp / shuffle / pick / fmt +*/ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + Kit.version = 1; + Kit.$ = id => document.getElementById(id); + + // ---- assets --------------------------------------------------------------------------- + // build-web.mjs puts every asset into window.KIT_ASSETS as a data: URI, so the release + // HTML works from file:// and on any web host without a folder next to it. + Kit.asset = path => (root.KIT_ASSETS && root.KIT_ASSETS[path]) || path; + + Kit.loadBytes = url => { + if (url.startsWith('data:')) { + const bin = atob(url.slice(url.indexOf(',') + 1)); + const buf = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i); + return Promise.resolve(buf.buffer); + } + return fetch(url).then(r => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(r.status + ' ' + url)))); + }; + + // Missing images are fine: draw a fallback shape while !img.ok. + Kit.images = (names, dir = 'assets/Sprites/', ext = '.png') => { + const out = {}; + for (const n of names) { + const im = new Image(); + im.ok = false; + im.onload = () => { im.ok = true; }; + im.src = Kit.asset(dir + n + ext); + out[n] = im; + } + return out; + }; + + // ---- storage -------------------------------------------------------------------------- + // Every access is wrapped: private mode, blocked storage or a full quota must not crash. + Kit.store = prefix => { + const p = prefix ? prefix + '.' : ''; + return { + get(k, d) { + try { const v = localStorage.getItem(p + k); return v == null ? d : JSON.parse(v); } catch (e) { return d; } + }, + set(k, v) { + try { localStorage.setItem(p + k, JSON.stringify(v)); return true; } catch (e) { return false; } + }, + del(k) { try { localStorage.removeItem(p + k); } catch (e) { /* ignore */ } }, + }; + }; + + /* Save slot for game progress. + const slot = Kit.saveSlot('mygame.save', () => ({ level: 1, best: {} }), { version: 2, migrate }) + let save = slot.load(); ... slot.save(save); + - defaults() is a function so every load gets fresh nested objects. + - Loaded data is merged over defaults (one level deep for plain objects), so fields added + in a later version exist in old saves. + - migrate(data, fromVersion) runs when the stored version is older; return the data. + - Every backupEvery-th save also writes a backup; a corrupt primary falls back to it. + - slot.failed() turns true once a write failed - tell the player once. */ + Kit.saveSlot = (key, defaults, opt = {}) => { + const version = opt.version || 1, every = opt.backupEvery || 10; + let since = 0, failed = false; + const isObj = v => v && typeof v === 'object' && !Array.isArray(v); + function merge(d, s) { + const out = Object.assign({}, d, s); + for (const k of Object.keys(d)) if (isObj(d[k]) && isObj(s[k])) out[k] = Object.assign({}, d[k], s[k]); + return out; + } + function read(k) { + try { + const raw = localStorage.getItem(k); + if (!raw) return null; + const parsed = JSON.parse(raw); + if (!isObj(parsed)) return null; + const from = typeof parsed._v === 'number' ? parsed._v : 1; + let s = merge(defaults(), parsed); + if (from < version && opt.migrate) s = opt.migrate(s, from) || s; + s._v = version; + return s; + } catch (e) { return null; } + } + return { + load() { return read(key) || read(key + '.bak') || Object.assign(defaults(), { _v: version }); }, + save(data) { + data._v = version; + try { + const json = JSON.stringify(data); + localStorage.setItem(key, json); + if (++since >= every) { since = 0; localStorage.setItem(key + '.bak', json); } + return true; + } catch (e) { failed = true; return false; } + }, + clear() { try { localStorage.removeItem(key); localStorage.removeItem(key + '.bak'); } catch (e) { /* ignore */ } }, + failed: () => failed, + }; + }; + + // ---- math / random -------------------------------------------------------------------- + Kit.rng = seed => { + let a = seed >>> 0 || 1; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; + }; + Kit.clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v); + Kit.lerp = (a, b, t) => a + (b - a) * t; + Kit.pick = (arr, rnd = Math.random) => arr[Math.floor(rnd() * arr.length)]; + Kit.shuffle = (arr, rnd = Math.random) => { + for (let i = arr.length - 1; i > 0; i--) { + const j = Math.floor(rnd() * (i + 1)); + [arr[i], arr[j]] = [arr[j], arr[i]]; + } + return arr; + }; + // 1234567 -> "1.23M" (idle games); below 10 000 plain with thousands separator + Kit.fmt = n => { + if (!Number.isFinite(n)) return '0'; + const a = Math.abs(n); + if (a < 1e4) return Math.round(n).toLocaleString('en-US'); + const units = ['K', 'M', 'B', 'T', 'Qa', 'Qi']; + let u = -1, v = a; + while (v >= 1000 && u < units.length - 1) { v /= 1000; u++; } + return (n < 0 ? '-' : '') + (v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)) + units[u]; + }; + + if (typeof module !== 'undefined' && module.exports) module.exports = Kit; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/kit/kit-fx.js b/game/kit/kit-fx.js new file mode 100644 index 0000000..0e4aaaf --- /dev/null +++ b/game/kit/kit-fx.js @@ -0,0 +1,72 @@ +/* Kit fx (v1) - small juice helpers for canvas games. From _Tools\Library\web\kit. + + const fx = Kit.fx(); + fx.burst(x, y, '#ffd83a', 16, 180) particles (count, speed px/s) + fx.float(x, y, '+10', '#fff') rising, fading text + fx.shake(8) screen shake strength in px (decays) + fx.update(dt) in loop update + fx.apply(ctx) ... draw world ... ctx.restore() (apply saves + offsets for shake) + fx.draw(ctx) particles + texts on top + Kit.tween(from, to, t, Kit.ease.outBack) */ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + + Kit.ease = { + linear: t => t, + outQuad: t => 1 - (1 - t) * (1 - t), + inOutQuad: t => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2), + outCubic: t => 1 - Math.pow(1 - t, 3), + outBack: t => 1 + 2.70158 * Math.pow(t - 1, 3) + 1.70158 * Math.pow(t - 1, 2), + outElastic: t => (t === 0 || t === 1 ? t : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * (2 * Math.PI / 3)) + 1), + }; + Kit.tween = (a, b, t, ease = Kit.ease.outQuad) => a + (b - a) * ease(Math.max(0, Math.min(1, t))); + + Kit.fx = () => { + const parts = [], texts = []; + let shake = 0; + return { + burst(x, y, color = '#fff', n = 14, speed = 160, life = 0.6) { + for (let i = 0; i < n; i++) { + const a = Math.random() * Math.PI * 2, v = speed * (0.4 + Math.random() * 0.8); + parts.push({ x, y, vx: Math.cos(a) * v, vy: Math.sin(a) * v, life, max: life, color, r: 2 + Math.random() * 2.5 }); + } + }, + float(x, y, text, color = '#fff', size = 18) { texts.push({ x, y, text, color, size, life: 0.9, max: 0.9 }); }, + shake(px) { shake = Math.max(shake, px); }, + update(dt) { + for (let i = parts.length - 1; i >= 0; i--) { + const p = parts[i]; + p.life -= dt; if (p.life <= 0) { parts.splice(i, 1); continue; } + p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.96; p.vy = p.vy * 0.96 + 220 * dt; + } + for (let i = texts.length - 1; i >= 0; i--) { + const t = texts[i]; + t.life -= dt; if (t.life <= 0) { texts.splice(i, 1); continue; } + t.y -= 40 * dt; + } + shake = Math.max(0, shake - 40 * dt); + }, + apply(ctx) { + ctx.save(); + if (shake > 0) ctx.translate((Math.random() * 2 - 1) * shake, (Math.random() * 2 - 1) * shake); + }, + draw(ctx) { + for (const p of parts) { + ctx.globalAlpha = p.life / p.max; + ctx.fillStyle = p.color; + ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill(); + } + ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; + for (const t of texts) { + ctx.globalAlpha = Math.min(1, t.life / t.max * 2); + ctx.font = `bold ${t.size}px system-ui, sans-serif`; + ctx.lineWidth = 4; ctx.strokeStyle = 'rgba(0,0,0,.6)'; ctx.strokeText(t.text, t.x, t.y); + ctx.fillStyle = t.color; ctx.fillText(t.text, t.x, t.y); + } + ctx.globalAlpha = 1; + }, + clear() { parts.length = 0; texts.length = 0; shake = 0; }, + }; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/kit/kit-host.js b/game/kit/kit-host.js new file mode 100644 index 0000000..20278a3 --- /dev/null +++ b/game/kit/kit-host.js @@ -0,0 +1,39 @@ +/* Kit host (v1) - window control for the desktop exe (WebView2 launcher) and the browser. + From _Tools\Library\web\kit. + + Kit.host.exe true inside the launcher (Launcher.csproj); gets class "exe" + Kit.host.fullscreen() exe: toggle borderless-maximised; browser: Fullscreen API + Kit.host.minimize() / Kit.host.quit() exe only (no-ops in the browser) + Kit.host.dragArea(el) mousedown on el itself drags the window, double-click = fullscreen + + The launcher draws no title bar; put minimise/fullscreen/close buttons into the page and + show them only for html.exe (template: #winctl). */ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + const wv = root.chrome && root.chrome.webview; + const send = c => { if (wv) wv.postMessage(c); }; + + const host = { + exe: !!wv, + send, + fullscreen() { + if (wv) return send('maximize'); + if (document.fullscreenElement) document.exitFullscreen().catch(() => {}); + else document.documentElement.requestFullscreen().catch(() => {}); + }, + minimize: () => send('minimize'), + quit: () => send('quit'), + dragArea(el) { + if (!wv) return; + el.addEventListener('mousedown', e => { if (e.button === 0 && e.target === el) send('drag'); }); + el.addEventListener('dblclick', e => { if (e.target === el) send('maximize'); }); + }, + }; + Kit.host = host; + if (wv && typeof document !== 'undefined') document.documentElement.classList.add('exe'); + // F11 in the browser: same toggle as the exe (the launcher handles F11 / Alt+Enter itself) + if (!wv && typeof addEventListener !== 'undefined') { + addEventListener('keydown', e => { if (e.key === 'F11') { e.preventDefault(); host.fullscreen(); } }); + } +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/kit/kit-i18n.js b/game/kit/kit-i18n.js new file mode 100644 index 0000000..be73653 --- /dev/null +++ b/game/kit/kit-i18n.js @@ -0,0 +1,62 @@ +/* Kit i18n (v1) - texts in several languages for HTML games. From _Tools\Library\web\kit. + Needs kit-core.js. Dictionaries live in game/lang.js (a script, not JSON: file:// cannot fetch). + + game/lang.js: window.LANG = { en: { play: 'Play', score: 'Score {n}' }, de: { play: 'Spielen' } }; + const L = Kit.i18n(window.LANG, { prefix: 'mygame' }); + L.t('score', { n: 5 }) "Score 5" - missing key: English, then the key itself (visible = easy to spot) + L.lang / L.langs current language / ['en', 'de'] + L.set('de') switch + remember; re-fills data-i18n elements, calls onChange listeners + L.next() cycle to the next language (one "English / Deutsch" button) + L.apply(root) fills [data-i18n="key"] (text), [data-i18n-html] (HTML), [data-i18n-title], + [data-i18n-placeholder]; runs once at start and after every set() + L.onChange(fn) re-render menus/HUD after a switch + Start language: saved choice, else browser language if there is a dictionary, else the first one. */ +(function (root) { + 'use strict'; + const Kit = (root.Kit = root.Kit || {}); + + Kit.i18n = (dicts, opt = {}) => { + const langs = Object.keys(dicts || {}); + if (!langs.length) throw new Error('Kit.i18n: no dictionaries (game/lang.js loaded?)'); + const st = Kit.store(opt.prefix || 'kit'); + const fallback = dicts.en ? 'en' : langs[0]; + const listeners = []; + const browser = (typeof navigator !== 'undefined' && (navigator.language || '').slice(0, 2).toLowerCase()) || ''; + const saved = st.get('lang', null); + const api = { + langs, + lang: langs.includes(saved) ? saved : langs.includes(browser) ? browser : fallback, + }; + + api.t = (key, vars) => { + let s = dicts[api.lang]?.[key] ?? dicts[fallback]?.[key] ?? key; + if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v)); + return s; + }; + + api.apply = (scope = typeof document !== 'undefined' ? document : null) => { + if (!scope) return; + for (const el of scope.querySelectorAll('[data-i18n]')) el.textContent = api.t(el.dataset.i18n); + for (const el of scope.querySelectorAll('[data-i18n-html]')) el.innerHTML = api.t(el.dataset.i18nHtml); + for (const el of scope.querySelectorAll('[data-i18n-title]')) el.title = api.t(el.dataset.i18nTitle); + for (const el of scope.querySelectorAll('[data-i18n-placeholder]')) el.placeholder = api.t(el.dataset.i18nPlaceholder); + if (typeof document !== 'undefined') document.documentElement.lang = api.lang; + }; + + api.set = l => { + if (!langs.includes(l) || l === api.lang) return; + api.lang = l; + st.set('lang', l); + api.apply(); + for (const fn of listeners) fn(l); + }; + api.next = () => api.set(langs[(langs.indexOf(api.lang) + 1) % langs.length]); + api.onChange = fn => { listeners.push(fn); }; + + if (typeof document !== 'undefined') { + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.apply()); + else api.apply(); + } + return api; + }; +})(typeof window !== 'undefined' ? window : globalThis); diff --git a/game/kit/kit-input.js b/game/kit/kit-input.js new file mode 100644 index 0000000..494fc0a --- /dev/null +++ b/game/kit/kit-input.js @@ -0,0 +1,73 @@ +/* Kit input (v1) - keyboard + touch buttons mapped to actions. From _Tools\Library\web\kit. + + const input = Kit.input({ + keys: { ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', + ArrowRight: 'right', d: 'right', ' ': 'action', p: 'pause', Escape: 'pause', m: 'mute' }, + onPress(action, e) {}, // first press only (no key repeat) + onRelease(action) {}, + }); + input.down('left') is it held right now? + input.latest(['up','right','down','left']) most recently pressed of these that is still held + input.consume('action') true once per press (polling style inside update()) + + Touch buttons: any element with data-action="left" works like the key (pointer capture, + so sliding off the button releases it). Typing into /