main init

This commit is contained in:
2026-11-13 00:38:47 +01:00
commit e377873a85
124 changed files with 12320 additions and 0 deletions

View File

@@ -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);

142
Library/web/kit/kit-core.js Normal file
View File

@@ -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);

72
Library/web/kit/kit-fx.js Normal file
View File

@@ -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);

View File

@@ -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); <html> 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);

View File

@@ -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);

View File

@@ -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 <input>/<textarea> is ignored.
Keys are matched case-insensitively for letters. */
(function (root) {
'use strict';
const Kit = (root.Kit = root.Kit || {});
Kit.input = (opt = {}) => {
const map = {};
for (const [k, a] of Object.entries(opt.keys || {})) map[k.length === 1 ? k.toLowerCase() : k] = a;
const held = [], pressed = new Set();
const api = {};
function press(a, e) {
const i = held.indexOf(a);
if (i >= 0) return; // already held (key repeat)
held.push(a); pressed.add(a);
opt.onPress && opt.onPress(a, e);
}
function release(a) {
const i = held.indexOf(a);
if (i < 0) return;
held.splice(i, 1);
opt.onRelease && opt.onRelease(a);
}
const typing = e => e.target && /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName);
const keyOf = e => (e.key.length === 1 ? e.key.toLowerCase() : e.key);
addEventListener('keydown', e => {
if (typing(e)) return;
const a = map[keyOf(e)];
if (!a) return;
e.preventDefault();
if (!e.repeat) press(a, e);
});
addEventListener('keyup', e => { const a = map[keyOf(e)]; if (a) release(a); });
addEventListener('blur', () => { while (held.length) release(held[held.length - 1]); });
api.bindButtons = (scope = document) => {
scope.querySelectorAll('[data-action]').forEach(b => {
if (b._kitBound) return;
b._kitBound = true;
const a = b.dataset.action;
b.addEventListener('pointerdown', e => { e.preventDefault(); b.setPointerCapture(e.pointerId); press(a, e); });
b.addEventListener('pointerup', () => release(a));
b.addEventListener('pointercancel', () => release(a));
b.addEventListener('contextmenu', e => e.preventDefault());
});
};
if (typeof document !== 'undefined') {
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => api.bindButtons());
else api.bindButtons();
}
api.down = a => held.includes(a);
api.latest = list => { for (let i = held.length - 1; i >= 0; i--) if (list.includes(held[i])) return held[i]; return null; };
api.consume = a => pressed.delete(a);
api.clear = () => { held.length = 0; pressed.clear(); };
return api;
};
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -0,0 +1,75 @@
/* Kit loop + view (v1) - from _Tools\Library\web\kit. Needs kit-core.js.
Game loop with a fixed simulation step and smooth rendering:
const loop = Kit.loop({
step: 1000 / 60, // ms per update (fixed: deterministic, replayable)
update(dt) { ... }, // dt = step in seconds
render(alpha, now) { ... }, // alpha 0..1 between the last two updates (interpolate)
});
loop.start(); loop.pause(); loop.resume(); loop.paused
Pauses itself while the tab is hidden; a long hitch is capped (no spiral of death).
Fixed-size layout scaled to the window (sharp canvases on hi-DPI screens):
Kit.fit(Kit.$('app'), { canvases: [[cv, 960, 540]], onFit(scale) {} })
#app is laid out at its natural pixel size and scaled with CSS transform to fill the
window; every listed canvas gets a backing store of size * scale * devicePixelRatio
and a matching ctx transform, so you always draw in design pixels (960 x 540). */
(function (root) {
'use strict';
const Kit = (root.Kit = root.Kit || {});
Kit.loop = opt => {
const step = opt.step || 1000 / 60, maxFrame = opt.maxFrame || 250;
let acc = 0, last = 0, raf = 0, running = false;
const api = { paused: false, ticks: 0 };
function frame(now) {
raf = requestAnimationFrame(frame);
let d = now - last; last = now;
if (api.paused || document.hidden) { acc = 0; opt.render && opt.render(1, now); return; }
if (d > maxFrame) d = maxFrame;
acc += d;
while (acc >= step) { acc -= step; api.ticks++; opt.update && opt.update(step / 1000); if (api.paused) { acc = 0; break; } }
opt.render && opt.render(acc / step, now);
}
api.start = () => { if (running) return api; running = true; last = performance.now(); raf = requestAnimationFrame(frame); return api; };
api.stop = () => { running = false; cancelAnimationFrame(raf); };
api.pause = () => { api.paused = true; };
api.resume = () => { api.paused = false; acc = 0; last = performance.now(); };
return api;
};
Kit.setRes = (cv, w, h, k) => {
cv.width = Math.round(w * k);
cv.height = Math.round(h * k);
cv.style.width = w + 'px';
cv.style.height = h + 'px';
const c = cv.getContext('2d');
c.setTransform(k, 0, 0, k, 0, 0);
return c;
};
Kit.fit = (app, opt = {}) => {
const margin = opt.margin == null ? 0.96 : opt.margin, min = opt.min || 0.3, max = opt.max || 4;
const canvases = opt.canvases || [];
app.style.transformOrigin = 'center center';
function fit() {
app.style.transform = 'none';
const w = app.offsetWidth, h = app.offsetHeight;
const sc = Kit.clamp(Math.min(innerWidth * margin / w, innerHeight * margin / h), min, max);
app.style.transform = `scale(${sc})`;
const k = sc * (root.devicePixelRatio || 1);
for (const [cv, cw, ch] of canvases) Kit.setRes(cv, cw, ch, k);
opt.onFit && opt.onFit(sc);
}
addEventListener('resize', fit);
if (document.fonts) document.fonts.ready.then(fit);
fit();
return fit;
};
// Screen position (mouse/touch event) -> design pixels of a canvas laid out by Kit.fit.
Kit.toCanvas = (cv, e, w, h) => {
const r = cv.getBoundingClientRect();
return { x: (e.clientX - r.left) * (w / r.width), y: (e.clientY - r.top) * (h / r.height) };
};
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -0,0 +1,64 @@
/* Kit scores (v1) - online highscores via Firebase Realtime Database REST (no SDK, no login).
From _Tools\Library\web\kit. Rules to install: template docs/firebase/database.rules.json.
const scores = Kit.scores({ url: 'https://<project>-default-rtdb.europe-west1.firebasedatabase.app' });
if (scores.enabled) {
const rows = await scores.top(10); // [{ key, name, score, level, time }] best first
const key = await scores.submit({ name, score, level }); // key of the new entry or null
}
Kit.cleanName(s) -> trimmed, max 20 chars, no control chars / angle brackets
Kit.badName(s) -> true for slurs/insults (also l33t spelling); block on entry, hide in lists
Without a url (or with the placeholder) scores.enabled is false and both calls resolve to
[] / null - the game runs offline. The rules only check format and range: anyone can post a
fake score by hand. Real protection needs a server check (Cloud Function). */
(function (root) {
'use strict';
const Kit = (root.Kit = root.Kit || {});
const BAD_WORDS = ['nigg', 'niga', 'neger', 'negro', 'kike', 'fag', 'cunt', 'fuck', 'fick', 'hitler', 'nazi',
'siegheil', 'kkk', 'whore', 'hure', 'fotze', 'wichs', 'schwuchtel', 'spast', 'retard', 'slut', 'bitch',
'kanake', 'zigeuner', 'judensau'];
Kit.cleanName = s => String(s || '').replace(/[\u0000-\u001f<>]/g, '').trim().slice(0, 20);
Kit.badName = s => {
const norm = String(s || '').toLowerCase()
.replace(/[1!|]/g, 'i').replace(/3/g, 'e').replace(/0/g, 'o').replace(/[4@]/g, 'a')
.replace(/[5$]/g, 's').replace(/7/g, 't').replace(/ph/g, 'f')
.replace(/[^a-zäöüß]/g, '');
return BAD_WORDS.some(w => norm.includes(w));
};
Kit.scores = (opt = {}) => {
const url = (opt.url || '').replace(/\/+$/, '');
const path = opt.path || 'highscores';
const enabled = /^https:\/\/.+firebase(io|database)\.(com|app)$/.test(url);
return {
enabled,
async top(n = 10) {
if (!enabled) return [];
// fetch spare rows: filtered names must not leave the list short
const q = new URLSearchParams({ orderBy: '"score"', limitToLast: String(n + 15) });
const res = await fetch(`${url}/${path}.json?${q}`, { cache: 'no-store' });
if (!res.ok) throw new Error('scores ' + res.status);
const data = (await res.json()) || {};
return Object.entries(data)
.map(([key, v]) => Object.assign({ key }, v))
.filter(v => typeof v.name === 'string' && typeof v.score === 'number' && !Kit.badName(v.name))
.sort((a, b) => b.score - a.score || (a.time || 0) - (b.time || 0))
.slice(0, n);
},
async submit({ name, score, level = 1 }) {
name = Kit.cleanName(name);
if (!enabled || !name || !(score > 0) || Kit.badName(name)) return null;
try {
const res = await fetch(`${url}/${path}.json`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, score: Math.floor(score), level: Math.floor(level), time: { '.sv': 'timestamp' } }),
});
return res.ok ? (await res.json()).name : null;
} catch (e) { return null; }
},
};
};
})(typeof window !== 'undefined' ? window : globalThis);