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

7
Library/web/template/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
release/
launcher/bin/
launcher/obj/
sprite-generator/output/
sprite-generator/__pycache__/
node_modules/
*.log

View File

@@ -0,0 +1,28 @@
# {{NAME}}
HTML-Canvas-Spiel ohne Build-Schritt, angelegt aus `D:\Oculusquest\Projekt\_Tools\Library` (Vorlage `webgame`).
Aufbau und Befehle: `README.md`.
## Spielkonzept
<!-- KONZEPT: wird beim Anlegen (Skill neues-projekt) ausgefüllt, danach aktuell halten -->
## 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 `<script src>` in `index.html` (build-web.mjs bettet sie ein).
- Reine Spiellogik ohne DOM in eigene Datei (wie `Byte Path\game\engine.js`), damit Node-Tests/Löser sie nutzen können.
- Grafik und Sound nur über `sprite-generator/` (ComfyGen, Katalog `_Tools\README.md`), Stilblock aus dem
Spielkonzept für alle Prompts. App-Icon = `game/assets/Sprites/icon.png` (`gen adopt --size 512 icon`).
Fehlt ein Bild, zeichnet das Spiel eine Ersatzform (`drawSprite` mit Fallback-Farbe) – nie abstürzen.
- Git nur lokal (kein Remote). Commit nur, wenn Michael es sagt.
- Release prüfen: `.\build.ps1 -Web`, dann `release\{{SLUG}}.html` per Doppelklick testen.

View File

@@ -0,0 +1,50 @@
# {{NAME}}
HTML-Spiel (Canvas, kein Build-Schritt). Angelegt am {{DATE}} aus `_Tools\Library` (Vorlage `webgame`).
Sprachen: Englisch, Deutsch (im Menü umschaltbar).
© {{YEAR}} Michael Media · Discord: https://discord.gg/Ej4JPmCZva
## Spielen / Entwickeln
`game/index.html` im Browser öffnen (Doppelklick reicht, kein Server). `index.html?play` überspringt das Menü.
| Taste | Wirkung |
|---|---|
| Pfeile / WASD, Tippen | bewegen |
| P / Esc | Pause |
| M | Sound an/aus |
| R | neu starten |
| F11 | Vollbild |
## Aufbau
```
game/
index.html Seite, HUD, Overlays (Styles inline)
game.js das Spiel
lang.js alle sichtbaren Texte, Englisch + Deutsch (L.t('key') / data-i18n="key")
kit/ Bausteine aus _Tools\Library\web\kit – hier NICHT ändern (siehe unten)
assets/ Sprites/ (icon.png = App-Icon), Audio/, Fonts/ – von sprite-generator (ComfyGen adopt)
launcher/ Windows-Fenster (WebView2) → {{IDENT}}.exe
sprite-generator/ ComfyGen-Projekt: gen generate <name>, gen adopt <name>, gen generate_audio <name>
docs/firebase/ Online-Highscores einrichten
docs/itchio/ itch.io-Seite
build-web.mjs → release/{{SLUG}}.html (alles in einer Datei)
build.ps1 → release/{{IDENT}}.exe + {{SLUG}}.html + {{SLUG}}-web.zip
```
## Release
```powershell
.\build.ps1 # exe + html + zip
.\build.ps1 -Web # nur html + zip
```
## Kit aktualisieren
Verbesserungen an `game/kit/*` gehören in `D:\Oculusquest\Projekt\_Tools\Library\web\kit`. Danach hier:
```powershell
D:\Oculusquest\Projekt\_Tools\Library\new-project.ps1 -UpdateKit -Path .
```

View File

@@ -0,0 +1,54 @@
// Builds release/{{SLUG}}.html: the whole game in ONE file. Local <script src> and
// <link rel="stylesheet"> are inlined, every file under game/assets is embedded as a data: URI
// (window.KIT_ASSETS, read by Kit.asset). Works by double-click (file://) and on any host
// (itch.io, webspace). From _Tools\Library\web\template.
// node build-web.mjs
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.dirname(fileURLToPath(import.meta.url));
const game = path.join(root, 'game');
const MIME = {
'.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif',
'.svg': 'image/svg+xml', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.wav': 'audio/wav',
'.ttf': 'font/ttf', '.otf': 'font/otf', '.woff2': 'font/woff2', '.json': 'application/json',
};
function walk(dir) {
if (!fs.existsSync(dir)) return [];
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(e =>
e.isDirectory() ? walk(path.join(dir, e.name)) : [path.join(dir, e.name)]);
}
const assets = {};
let bytes = 0;
for (const file of walk(path.join(game, 'assets'))) {
const mime = MIME[path.extname(file).toLowerCase()];
if (!mime) continue;
const rel = path.relative(game, file).split(path.sep).join('/');
const buf = fs.readFileSync(file);
bytes += buf.length;
assets[rel] = `data:${mime};base64,${buf.toString('base64')}`;
}
let html = fs.readFileSync(path.join(game, 'index.html'), 'utf8');
const local = p => !/^(https?:)?\/\//.test(p) && !p.startsWith('data:');
// "</script" inside an inlined file would end the tag early
const safe = s => s.replace(/<\/script/gi, '<\\/script');
html = html.replace(/<link\s+rel="stylesheet"\s+href="([^"]+)"\s*\/?>/g, (m, p) =>
local(p) ? `<style>\n${fs.readFileSync(path.join(game, p), 'utf8')}\n</style>` : m);
html = html.replace(/<script\s+src="([^"]+)"\s*><\/script>/g, (m, p) =>
local(p) ? `<script>\n${safe(fs.readFileSync(path.join(game, p), 'utf8'))}\n</script>` : 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 <script>
html = html.replace('<script>', () => `<script>window.KIT_ASSETS = ${JSON.stringify(assets)};</script>\n<script>`);
const out = path.join(root, 'release', '{{SLUG}}.html');
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, html);
const mb = n => (n / 1024 / 1024).toFixed(1);
console.log(`Fertig: ${out} (${mb(fs.statSync(out).size)} MB, ${Object.keys(assets).length} Assets, ${mb(bytes)} MB roh)`);

View File

@@ -0,0 +1,41 @@
# Builds everything into release\:
# {{IDENT}}.exe one self-contained file (.NET runtime + game embedded, WebView2 window)
# {{SLUG}}.html whole game in one HTML file
# {{SLUG}}-web.zip upload package for itch.io & co (the page as index.html)
# Needs .NET 8+ SDK and Node. The PC running the exe needs the Edge WebView2 Runtime (Win 10/11 has it).
# .\build.ps1 all .\build.ps1 -Web only HTML + zip .\build.ps1 -Exe only exe
param([switch]$Web, [switch]$Exe)
$ErrorActionPreference = 'Stop'
$root = $PSScriptRoot
$out = Join-Path $root 'release'
if (-not $Web -and -not $Exe) { $Web = $true; $Exe = $true }
New-Item -ItemType Directory -Force $out | Out-Null
if ($Exe) {
# app icon from game\assets\Sprites\icon.png (once; delete launcher\app.ico to redo)
$ico = Join-Path $root 'launcher\app.ico'
$png = Join-Path $root 'game\assets\Sprites\icon.png'
if (-not (Test-Path $ico) -and (Test-Path $png)) {
py -3.12 -c "import sys; from PIL import Image; Image.open(sys.argv[1]).convert('RGBA').save(sys.argv[2], sizes=[(16,16),(24,24),(32,32),(48,48),(64,64),(128,128),(256,256)])" $png $ico
}
$pub = Join-Path $env:TEMP '{{SLUG}}-publish'
Remove-Item $pub -Recurse -Force -ErrorAction SilentlyContinue
dotnet publish (Join-Path $root 'launcher\Launcher.csproj') -c Release -o $pub --nologo
if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed ($LASTEXITCODE)" }
Copy-Item (Join-Path $pub '{{IDENT}}.exe') $out -Force
Remove-Item $pub -Recurse -Force
$exeFile = Get-Item (Join-Path $out '{{IDENT}}.exe')
"Fertig: $($exeFile.FullName) ($([math]::Round($exeFile.Length / 1MB, 1)) MB)"
}
if ($Web) {
node (Join-Path $root 'build-web.mjs')
if ($LASTEXITCODE -ne 0) { throw "web build failed ($LASTEXITCODE)" }
$tmp = Join-Path $env:TEMP '{{SLUG}}-web'
Remove-Item $tmp -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory $tmp | Out-Null
Copy-Item (Join-Path $out '{{SLUG}}.html') (Join-Path $tmp 'index.html')
Compress-Archive -Path (Join-Path $tmp 'index.html') -DestinationPath (Join-Path $out '{{SLUG}}-web.zip') -Force
Remove-Item $tmp -Recurse -Force
"Fertig: $(Join-Path $out '{{SLUG}}-web.zip')"
}

View File

@@ -0,0 +1,26 @@
# Online-Highscores (Firebase Realtime Database)
Das Spiel spricht die Datenbank über die REST-API an (`game/kit/kit-scores.js`), ohne SDK und ohne Login.
Solange `DB_URL` in `game/game.js` leer ist, läuft alles offline (keine Namenseingabe, keine Liste).
## Einrichten (einmal, ~5 Minuten)
1. [Firebase-Konsole](https://console.firebase.google.com/) → **Projekt hinzufügen** (Name z. B. `{{SLUG}}`, Analytics aus).
2. **Build → Realtime Database → Datenbank erstellen** → Standort **europe-west1** → „Im gesperrten Modus starten“.
3. Tab **Regeln**: alles durch den Inhalt von `database.rules.json` ersetzen → **Veröffentlichen**.
4. Die URL oben im Tab **Daten** (`https://<projekt>-default-rtdb.europe-west1.firebasedatabase.app`)
in `game/game.js` bei `DB_URL` eintragen.
## Was die Regeln erlauben
- Lesen: nur `highscores` (sortiert/begrenzt nach `score`).
- Schreiben: nur **neue** Einträge unter `highscores` – bestehende können nicht geändert/gelöscht werden.
- Jeder Eintrag hat genau `name` (1–20 Zeichen), `score` (1–10 000 000), `level` (1–999), `time` (Server-Zeit).
## Grenzen
Punkte lassen sich per Hand-Request fälschen; die Regeln prüfen nur Format und Bereich. Echter Schutz
bräuchte eine Server-Prüfung (Cloud Function). Einträge löschen: Konsole → **Daten** → `highscores` →
Eintrag → ⋮ / Papierkorb. Schimpfwort-Namen blockt `Kit.badName` bei der Eingabe und blendet sie in der Liste aus.
Referenz im Einsatz: `D:\Oculusquest\Projekt\Pipefix\docs\firebase\`.

View File

@@ -0,0 +1,19 @@
{
"rules": {
".read": false,
".write": false,
"highscores": {
".read": true,
".indexOn": ["score"],
"$entry": {
".write": "!data.exists()",
".validate": "newData.hasChildren(['name', 'score', 'level', 'time'])",
"name": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 20" },
"score": { ".validate": "newData.isNumber() && newData.val() > 0 && newData.val() <= 10000000" },
"level": { ".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 999" },
"time": { ".validate": "newData.val() == now" },
"$other": { ".validate": false }
}
}
}
}

View File

@@ -0,0 +1,38 @@
# itch.io-Seite einrichten
Bilder erzeugen (Cover, Banner, Hintergrund) aus einem Hintergrundbild und dem Titel:
```
py -3.12 D:\Oculusquest\Projekt\_Tools\Itch\itch_images.py --title "{{NAME}}" --tagline "…" --backdrop <bild.png> --out docs\itchio
```
Upload-Dateien: `.\build.ps1` → `release\{{SLUG}}-web.zip` (Browser) und `release\{{IDENT}}.exe` (Windows).
## Felder unter „Edit game“
| Feld | Eintrag |
|---|---|
| Title | `{{NAME}}` |
| Project URL | `{{SLUG}}` |
| Short description or tagline | _ein Satz_ |
| Classification | Games |
| Kind of project | **HTML** |
| Release status | Released |
| Pricing | z. B. „No payments“ oder „Donation“ |
| Uploads | `release/{{SLUG}}-web.zip` → „This file will be played in the browser“ · optional `release/{{IDENT}}.exe` → Windows |
| Viewport dimensions | `1120 × 720` (oder passend zum Seitenverhältnis von `#app`) |
| Frame options | ✅ Fullscreen button · Mobile friendly nur wenn Touch getestet |
| Description | Inhalt von `description.html` (im Browser öffnen, Strg+A, kopieren, einfügen) |
| Genre / Tags | passend, max. 10 Tags |
| AI generation disclosure | **Yes** – Grafik/Sound mit KI erzeugt (ComfyUI, Flux, Stable Audio) |
| Input methods | Keyboard, Mouse, Touchscreen (falls getestet) |
| Cover image | `cover.png` (630×500) |
| Screenshots | 3–5 Stück, 1920×1080 oder Spielgröße |
## Seiten-Design („Edit theme“)
- Banner: `banner_960x256.png` (oder `banner_1920x512.png`)
- Background: `background_1920x1200.jpg`, Repeat aus, oben mittig
- Farben passend zum Spiel (`:root` in `game/index.html`)
Referenz im Einsatz: `D:\Oculusquest\Projekt\Pipefix\docs\itchio\`.

View File

@@ -0,0 +1,28 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{{NAME}} - itch.io description</title></head>
<body style="max-width:720px;margin:40px auto;font:16px/1.5 system-ui,sans-serif">
<!-- Open in a browser, Ctrl+A, copy, paste into the itch.io "Description" field.
Placeholder text - the itchiocreater skill writes the real one. -->
<h2>🎮 {{NAME}}</h2>
<p><strong>One sentence that sells the game.</strong> Two or three more that say what you do and why it is fun.</p>
<h3>✨ Features</h3>
<ul>
<li>⭐ <strong>Feature one</strong> – …</li>
<li>⭐ <strong>Feature two</strong> – …</li>
<li>🏆 <strong>Online highscores</strong></li>
</ul>
<h3>🕹️ Controls</h3>
<p>⌨️ <strong>Arrows / WASD</strong> move · <strong>P / Esc</strong> pause · <strong>M</strong> sound · <strong>F11</strong> fullscreen</p>
<h3>🌍 Languages</h3>
<p>English, Deutsch (switch in the menu).</p>
<h3>💬 Community</h3>
<p>Feedback and ideas are welcome on <a href="https://discord.gg/Ej4JPmCZva">Discord</a>.</p>
<p><em>© {{YEAR}} Michael Media. Graphics, music and sound were created with the help of AI tools (ComfyUI).</em></p>
</body>
</html>

View File

@@ -0,0 +1,228 @@
/* {{NAME}} - game. Demo content from the Library template: collect orbs, dodge the red ones,
60 seconds. Replace the "game" section; keep the frame (menus, save, audio, scores, loop,
texts via L.t() from lang.js, credits line in the menu). */
(function () {
'use strict';
const $ = Kit.$;
const W = 960, H = 540; // design size of the canvas
const ID = '{{SLUG}}'; // localStorage prefix
// Paste the Firebase Realtime Database URL here to switch online highscores on
// (docs/firebase/README.md). Empty = offline.
const DB_URL = '';
// Credits (standard for every game): shown in the menu, links open in the normal browser
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
const CREDITS = `© {{YEAR}} Michael Media · <a href="${DISCORD}" target="_blank" rel="noopener">Discord</a>`;
// ---------------------------------------------------------------- services
const L = Kit.i18n(window.LANG, { prefix: ID }); // texts: lang.js, English + German
const t = L.t;
const store = Kit.store(ID);
const slot = Kit.saveSlot(ID + '.save', () => ({ best: 0, games: 0, name: '', tutorialSeen: false }));
let save = slot.load();
const audio = Kit.createAudio({
prefix: ID,
files: ['sfx_click', 'sfx_pickup', 'sfx_hit', 'sfx_win', 'music_game'], // assets/Audio/*.mp3
throttle: { sfx_pickup: 50 },
});
const scores = Kit.scores({ url: DB_URL });
const IMG = Kit.images(['player', 'orb', 'bad']); // assets/Sprites/*.png
const fx = Kit.fx();
const input = Kit.input({
keys: {
ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right',
p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok', ' ': 'ok', r: 'restart',
},
onPress(a) {
if (a === 'pause') togglePause();
else if (a === 'mute') toggleMute();
else if (a === 'restart' && mode !== 'menu') newGame();
else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); }
},
});
// sound with synth fallback while no ComfyGen clips exist
const SFX = {
click() { audio.sfx('sfx_click'); },
pickup() { audio.sfx('sfx_pickup'); audio.tone(880, 0.06, 'square', 0.12); audio.tone(1320, 0.08, 'square', 0.1, 0, 0.05); },
hit() { audio.sfx('sfx_hit'); audio.noise(0.25, 0.3, 900); },
over() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046], 0.09); },
};
// ---------------------------------------------------------------- view
const cv = $('cv');
let ctx = cv.getContext('2d');
Kit.fit($('app'), { canvases: [[cv, W, H]], onFit() { ctx = cv.getContext('2d'); } });
Kit.host.dragArea(document.body);
// ---------------------------------------------------------------- game state
let mode = 'menu'; // menu | play | pause | over
let g = null;
function newGame() {
g = { x: W / 2, y: H / 2, r: 18, vx: 0, vy: 0, score: 0, time: 60, orbs: [], spawn: 0, flash: 0, target: null };
fx.clear();
mode = 'play';
hideOverlay();
loop.resume();
audio.music('music_game');
hud();
}
function spawnOrb() {
const bad = Math.random() < Math.min(0.45, 0.15 + (60 - g.time) / 120);
g.orbs.push({ x: 40 + Math.random() * (W - 80), y: 40 + Math.random() * (H - 80), r: bad ? 16 : 12, bad, t: 0 });
}
function update(dt) {
fx.update(dt);
if (mode !== 'play') return;
// move: keys, or pointer target on touch / mouse
const ax = (input.down('right') ? 1 : 0) - (input.down('left') ? 1 : 0);
const ay = (input.down('down') ? 1 : 0) - (input.down('up') ? 1 : 0);
const SPEED = 340;
if (ax || ay) { g.target = null; const l = Math.hypot(ax, ay); g.vx = ax / l * SPEED; g.vy = ay / l * SPEED; }
else if (g.target) {
const dx = g.target.x - g.x, dy = g.target.y - g.y, l = Math.hypot(dx, dy);
if (l < 6) { g.target = null; g.vx = g.vy = 0; } else { g.vx = dx / l * SPEED; g.vy = dy / l * SPEED; }
} else { g.vx *= 0.8; g.vy *= 0.8; }
g.x = Kit.clamp(g.x + g.vx * dt, g.r, W - g.r);
g.y = Kit.clamp(g.y + g.vy * dt, g.r, H - g.r);
g.spawn -= dt;
if (g.spawn <= 0) { spawnOrb(); g.spawn = 0.55; }
for (let i = g.orbs.length - 1; i >= 0; i--) {
const o = g.orbs[i];
o.t += dt;
if (o.t > 6) { g.orbs.splice(i, 1); continue; }
if (Math.hypot(o.x - g.x, o.y - g.y) < o.r + g.r) {
g.orbs.splice(i, 1);
if (o.bad) { g.score = Math.max(0, g.score - 25); g.flash = 0.25; fx.shake(10); fx.burst(o.x, o.y, '#ff5a5a', 20); fx.float(o.x, o.y, '-25', '#ff8a8a'); SFX.hit(); }
else { g.score += 10; fx.burst(o.x, o.y, '#4fd8ff', 12); fx.float(o.x, o.y, '+10', '#bff3ff'); SFX.pickup(); }
}
}
g.flash = Math.max(0, g.flash - dt);
g.time -= dt;
if (g.time <= 0) { g.time = 0; gameOver(); }
hud();
}
// pointer: move towards the tap / click
cv.addEventListener('pointerdown', e => {
if (mode !== 'play') return;
g.target = Kit.toCanvas(cv, e, W, H);
});
cv.addEventListener('pointermove', e => { if (mode === 'play' && e.buttons) g.target = Kit.toCanvas(cv, e, W, H); });
// ---------------------------------------------------------------- drawing
function drawSprite(name, x, y, size, fallbackColor) {
const im = IMG[name];
if (im && im.ok) ctx.drawImage(im, x - size / 2, y - size / 2, size, size);
else { ctx.fillStyle = fallbackColor; ctx.beginPath(); ctx.arc(x, y, size / 2, 0, Math.PI * 2); ctx.fill(); }
}
function render(alpha, now) {
ctx.fillStyle = '#0a1020';
ctx.fillRect(0, 0, W, H);
// grid backdrop
ctx.strokeStyle = '#ffffff0d'; ctx.lineWidth = 1;
for (let x = 0; x <= W; x += 40) { ctx.beginPath(); ctx.moveTo(x + 0.5, 0); ctx.lineTo(x + 0.5, H); ctx.stroke(); }
for (let y = 0; y <= H; y += 40) { ctx.beginPath(); ctx.moveTo(0, y + 0.5); ctx.lineTo(W, y + 0.5); ctx.stroke(); }
if (!g) return;
fx.apply(ctx);
for (const o of g.orbs) {
const pulse = 1 + Math.sin(now / 160 + o.x) * 0.08, fade = o.t > 5 ? 6 - o.t : 1;
ctx.globalAlpha = Math.max(0, fade);
drawSprite(o.bad ? 'bad' : 'orb', o.x, o.y, o.r * 2 * pulse, o.bad ? '#ff4a4a' : '#4fd8ff');
}
ctx.globalAlpha = 1;
drawSprite('player', g.x, g.y, g.r * 2, '#ffd83a');
fx.draw(ctx);
ctx.restore();
if (g.flash > 0) { ctx.fillStyle = `rgba(255,60,60,${g.flash})`; ctx.fillRect(0, 0, W, H); }
}
const loop = Kit.loop({ step: 1000 / 60, update, render }).start();
// ---------------------------------------------------------------- HUD + menus
function hud() {
$('hScore').textContent = Kit.fmt(g ? g.score : 0);
$('hTime').textContent = g ? Math.ceil(g.time) : 60;
$('hBest').textContent = Kit.fmt(save.best);
$('bMute').textContent = audio.muted ? t('sound_off') : t('sound_on');
}
const overlay = $('overlay');
function card(html) { overlay.innerHTML = `<div class="card">${html}</div>`; overlay.classList.remove('hide'); }
function hideOverlay() { overlay.classList.add('hide'); overlay.innerHTML = ''; }
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
function boardHtml() { return scores.enabled ? `<ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
async function fillBoard(myKey) {
const el = $('board');
if (!el) return;
try {
const rows = await scores.top(10);
el.innerHTML = rows.length
? rows.map((r, i) => `<li class="${r.key === myKey ? 'me' : ''}"><span>${i + 1}.</span><span class="nm">${esc(r.name)}</span><span>${Kit.fmt(r.score)}</span></li>`).join('')
: `<li class="muted">${t('no_scores')}</li>`;
} catch (e) { el.innerHTML = `<li class="muted">${t('scores_offline')}</li>`; }
}
function showMenu() {
mode = 'menu';
const nameField = scores.enabled ? `<div><input id="name" maxlength="20" placeholder="${esc(t('name_placeholder'))}" value="${esc(save.name)}"></div>` : '';
card(`<h1>{{NAME}}</h1><p>${t('menu_text')}</p>
${nameField}<button class="primary" id="bStart">${t('play')}</button>
<div class="row"><button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button></div>
${boardHtml()}<p class="credits">${CREDITS}</p>`);
$('bLang').onclick = () => { SFX.click(); L.next(); };
const name = $('name'), start = $('bStart');
if (name) {
const check = () => { const n = Kit.cleanName(name.value); start.disabled = !n || Kit.badName(n); };
name.addEventListener('input', check); check();
name.addEventListener('keydown', e => { if (e.key === 'Enter' && !start.disabled) start.click(); });
setTimeout(() => name.focus(), 50);
}
start.onclick = () => {
if (name) { save.name = Kit.cleanName(name.value); slot.save(save); }
SFX.click(); newGame();
};
fillBoard();
}
async function gameOver() {
mode = 'over';
SFX.over();
const newBest = g.score > save.best;
save.best = Math.max(save.best, g.score);
save.games++;
slot.save(save);
hud();
card(`<h1>${t('time_up')}</h1><p>${t('score_line', { score: Kit.fmt(g.score) })}${newBest ? t('new_best') : ''}</p>
<button class="primary" id="bAgain">${t('again')}</button> <button id="bMenu">${t('menu')}</button>${boardHtml()}`);
$('bAgain').onclick = () => { SFX.click(); newGame(); };
$('bMenu').onclick = () => { SFX.click(); showMenu(); };
const key = await scores.submit({ name: save.name, score: g.score, level: 1 });
fillBoard(key);
}
function togglePause() {
if (mode === 'play') {
mode = 'pause'; loop.pause();
card(`<h1>${t('pause')}</h1><button class="primary" id="bGo">${t('continue')}</button> <button id="bQuit">${t('menu')}</button>`);
$('bGo').onclick = togglePause;
$('bQuit').onclick = showMenu;
} else if (mode === 'pause') { mode = 'play'; hideOverlay(); loop.resume(); }
}
function toggleMute() { audio.toggleMute(); hud(); }
$('bMute').onclick = toggleMute;
$('bPause').onclick = togglePause;
addEventListener('blur', () => { if (mode === 'play') togglePause(); });
// language switch: static texts update themselves (data-i18n), menus are drawn again
L.onChange(() => { hud(); if (mode === 'menu') showMenu(); });
if (slot.failed()) console.warn('save failed');
hud();
// dev: index.html?play skips the menu
if (new URLSearchParams(location.search).has('play')) newGame(); else showMenu();
})();

View File

@@ -0,0 +1,103 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>{{NAME}}</title>
<link rel="icon" href="assets/Sprites/icon.png">
<style>
:root {
--bg: #0b0f1a; --panel: #141b2d; --line: #2a3658; --text: #e3e9ff; --dim: #8b97bd;
--accent: #4fd8ff; --good: #6dff9e; --warn: #ff6b6b;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; overflow: hidden; background: var(--bg); color: var(--text);
font: 16px/1.4 "Segoe UI", system-ui, sans-serif; user-select: none; -webkit-user-select: none;
touch-action: none; }
body { display: flex; align-items: center; justify-content: center;
background: radial-gradient(circle at 50% 30%, #18234a 0%, var(--bg) 70%); }
/* fixed design size, scaled to the window by Kit.fit */
#app { position: relative; width: 960px; display: flex; flex-direction: column; gap: 10px; }
#hud { display: flex; gap: 10px; align-items: center; }
.chip { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; }
.chip b { color: var(--accent); font-variant-numeric: tabular-nums; }
.grow { flex: 1; }
#stage { position: relative; border: 2px solid var(--line); border-radius: 10px; overflow: hidden; background: #000; }
canvas { display: block; }
button { font: inherit; color: var(--text); background: var(--panel); border: 1px solid var(--line);
border-radius: 8px; padding: 6px 12px; cursor: pointer; }
button:hover { border-color: var(--accent); }
button.primary { background: var(--accent); color: #04121a; border-color: var(--accent); font-weight: 700; padding: 10px 26px; }
button:disabled { opacity: .45; cursor: default; }
/* overlays (menus) */
#overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
background: rgba(5, 8, 16, .72); backdrop-filter: blur(3px); }
#overlay.hide { display: none; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 26px 34px;
min-width: 360px; text-align: center; box-shadow: 0 20px 60px #0008; }
.card h1 { margin: 0 0 6px; font-size: 40px; letter-spacing: .06em; color: var(--accent); }
.card p { color: var(--dim); margin: 6px 0 16px; }
.card input { font: inherit; width: 220px; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line);
background: #0b1222; color: var(--text); text-align: center; margin-bottom: 14px; }
.board { list-style: none; padding: 0; margin: 16px 0 0; text-align: left; font-variant-numeric: tabular-nums; }
.board li { display: flex; gap: 10px; padding: 2px 0; }
.board li .nm { flex: 1; } .board li.me { color: var(--good); }
.muted { color: var(--dim); font-size: 13px; }
.card .row { display: flex; gap: 8px; justify-content: center; margin-top: 14px; }
/* credits (standard for every game: © year Michael Media + Discord) */
.credits { margin: 18px 0 0; font-size: 12px; color: var(--dim); }
.credits a { color: var(--accent); text-decoration: none; }
.credits a:hover { text-decoration: underline; }
/* touch pad: only on touch screens */
#pad { position: absolute; left: 18px; bottom: 18px; display: none; grid-template-columns: repeat(3, 64px); gap: 6px; }
#pad button { height: 64px; font-size: 22px; opacity: .7; }
@media (pointer: coarse) { #pad { display: grid; } }
/* window buttons: only inside the exe (html.exe set by kit-host.js) */
#winctl { position: fixed; top: 8px; right: 8px; display: none; gap: 6px; z-index: 10; }
html.exe #winctl { display: flex; }
#winctl button { width: 34px; height: 30px; padding: 0; opacity: .75; }
</style>
</head>
<body>
<div id="winctl">
<button onclick="Kit.host.minimize()" data-i18n-title="win_min">&#8211;</button>
<button onclick="Kit.host.fullscreen()" data-i18n-title="win_full">&#9634;</button>
<button onclick="Kit.host.quit()" data-i18n-title="win_close">&#10005;</button>
</div>
<div id="app">
<div id="hud">
<div class="chip"><span data-i18n="hud_score">Score</span> <b id="hScore">0</b></div>
<div class="chip"><span data-i18n="hud_time">Time</span> <b id="hTime">60</b></div>
<div class="chip"><span data-i18n="hud_best">Best</span> <b id="hBest">0</b></div>
<div class="grow"></div>
<button id="bMute" title="M">Sound</button>
<button id="bPause" title="P / Esc" data-i18n="pause">Pause</button>
</div>
<div id="stage">
<canvas id="cv"></canvas>
<div id="pad">
<span></span><button data-action="up">&#9650;</button><span></span>
<button data-action="left">&#9664;</button><button data-action="down">&#9660;</button><button data-action="right">&#9654;</button>
</div>
<div id="overlay" class="hide"></div>
</div>
</div>
<script src="kit/kit-core.js"></script>
<script src="kit/kit-audio.js"></script>
<script src="kit/kit-loop.js"></script>
<script src="kit/kit-input.js"></script>
<script src="kit/kit-host.js"></script>
<script src="kit/kit-scores.js"></script>
<script src="kit/kit-fx.js"></script>
<script src="kit/kit-i18n.js"></script>
<script src="lang.js"></script>
<script src="game.js"></script>
</body>
</html>

View File

@@ -0,0 +1,41 @@
/* {{NAME}} - all visible texts, English + German. Used via L.t('key') in game.js and
data-i18n="key" in index.html (kit-i18n.js). A new text always gets BOTH languages.
Values may contain simple HTML (<b>, <br>) and {placeholders}. */
window.LANG = {
en: {
lang_self: 'English',
hud_score: 'Score', hud_time: 'Time', hud_best: 'Best',
sound_on: 'Sound on', sound_off: 'Sound off', pause: 'Pause',
win_min: 'Minimise', win_full: 'Fullscreen (F11)', win_close: 'Close',
menu_text: 'Collect the blue orbs, avoid the red ones.<br>Arrows / WASD or tap to move.',
name_placeholder: 'Your name',
play: 'Play',
loading: 'loading…',
no_scores: 'No scores yet - be the first!',
scores_offline: 'Highscores offline',
time_up: 'Time!',
score_line: 'Score <b>{score}</b>',
new_best: ' - new best!',
again: 'Again',
menu: 'Menu',
continue: 'Continue',
},
de: {
lang_self: 'Deutsch',
hud_score: 'Punkte', hud_time: 'Zeit', hud_best: 'Rekord',
sound_on: 'Sound an', sound_off: 'Sound aus', pause: 'Pause',
win_min: 'Minimieren', win_full: 'Vollbild (F11)', win_close: 'Schließen',
menu_text: 'Sammle die blauen Kugeln, weiche den roten aus.<br>Pfeile / WASD oder tippen zum Bewegen.',
name_placeholder: 'Dein Name',
play: 'Spielen',
loading: 'lädt…',
no_scores: 'Noch keine Punkte – sei der Erste!',
scores_offline: 'Bestenliste offline',
time_up: 'Zeit um!',
score_line: 'Punkte <b>{score}</b>',
new_best: ' – neuer Rekord!',
again: 'Nochmal',
menu: 'Menü',
continue: 'Weiter',
},
};

View File

@@ -0,0 +1,42 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- {{NAME}} desktop window: shows the HTML game in WebView2. game\** is embedded as
resources (game/...) and served from https://{{SLUG}}.game/ - one exe, nothing unpacked.
Build with ..\build.ps1. From _Tools\Library\web\template. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<UseWindowsForms>true</UseWindowsForms>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>{{IDENT}}</AssemblyName>
<RootNamespace>{{IDENT}}</RootNamespace>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
<Product>{{NAME}}</Product>
<Company>Michael Media</Company>
<Copyright>(c) {{YEAR}} Michael Media</Copyright>
<Version>1.0.0</Version>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>true</PublishSingleFile>
<EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<DebugType>none</DebugType>
<SatelliteResourceLanguages>de</SatelliteResourceLanguages>
<NoWarn>$(NoWarn);MSB3277</NoWarn>
</PropertyGroup>
<!-- build.ps1 creates app.ico from game\assets\Sprites\icon.png -->
<PropertyGroup Condition="Exists('app.ico')">
<ApplicationIcon>app.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2903.40" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="..\game\**\*.*" LogicalName="game/%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,175 @@
using System.Diagnostics;
using System.Reflection;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
namespace {{IDENT}};
static class Program
{
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new MainForm());
}
}
// One borderless window with WebView2. The game files are embedded resources ("game/<path>")
// and answered from https://{{SLUG}}.game/<path> via WebResourceRequested.
// localStorage (saves, settings) lives in %LOCALAPPDATA%\{{IDENT}}\WebView2.
// The page talks to the window with chrome.webview.postMessage("maximize"|"minimize"|"quit"|"drag")
// - see kit-host.js. From _Tools\Library\web\template.
sealed class MainForm : Form
{
const string AppName = "{{NAME}}";
const string Host = "https://{{SLUG}}.game/";
const double Aspect = 16.0 / 10.0; // start window width / height
const string WebView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703";
static readonly string DataDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "{{IDENT}}");
readonly WebView2 web = new() { Dock = DockStyle.Fill, Visible = false, DefaultBackgroundColor = Color.FromArgb(11, 15, 26) };
readonly Label status = new()
{
Dock = DockStyle.Fill,
TextAlign = ContentAlignment.MiddleCenter,
Font = new Font("Segoe UI", 12f),
ForeColor = Color.FromArgb(160, 160, 160),
Text = $"Starte {AppName} …",
};
[System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool ReleaseCapture();
[System.Runtime.InteropServices.DllImport("user32.dll")] static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
const int WM_NCLBUTTONDOWN = 0xA1, HTCAPTION = 2;
public MainForm()
{
Text = AppName;
Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
BackColor = Color.FromArgb(11, 15, 26);
FormBorderStyle = FormBorderStyle.None; // the page draws its own window buttons
// Start large: 88 % of the screen height, centred on the screen with the mouse.
var wa = Screen.FromPoint(Cursor.Position).WorkingArea;
int h = (int)(wa.Height * 0.88);
int w = Math.Min((int)(h * Aspect), (int)(wa.Width * 0.92));
StartPosition = FormStartPosition.Manual;
Bounds = new Rectangle(wa.X + (wa.Width - w) / 2, wa.Y + (wa.Height - h) / 2, w, h);
KeyPreview = true;
Controls.Add(web);
Controls.Add(status);
Shown += async (_, _) => await StartAsync();
}
async Task StartAsync()
{
try
{
Directory.CreateDirectory(DataDir);
var args = "--autoplay-policy=no-user-gesture-required";
// GAME_DEBUG_PORT=9333 opens the DevTools protocol (automated tests)
if (int.TryParse(Environment.GetEnvironmentVariable("GAME_DEBUG_PORT"), out var dbg))
args += $" --remote-debugging-port={dbg}";
var env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataDir, "WebView2"),
new CoreWebView2EnvironmentOptions(args));
await web.EnsureCoreWebView2Async(env);
var core = web.CoreWebView2;
core.Settings.IsStatusBarEnabled = false;
core.Settings.AreDefaultContextMenusEnabled = false;
core.Settings.IsZoomControlEnabled = false;
core.Settings.AreBrowserAcceleratorKeysEnabled = false;
#if DEBUG
core.Settings.AreDevToolsEnabled = true;
#else
core.Settings.AreDevToolsEnabled = false;
#endif
core.AddWebResourceRequestedFilter(Host + "*", CoreWebView2WebResourceContext.All);
core.WebResourceRequested += (_, e) => e.Response = Serve(core.Environment, e.Request.Uri);
// links with target=_blank open in the normal browser
core.NewWindowRequested += (_, e) =>
{
e.Handled = true;
if (e.Uri.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
try { Process.Start(new ProcessStartInfo(e.Uri) { UseShellExecute = true }); } catch { }
};
core.NavigationStarting += (_, e) => { if (!e.Uri.StartsWith(Host)) e.Cancel = true; };
core.WebMessageReceived += (_, e) =>
{
switch (e.TryGetWebMessageAsString())
{
case "maximize": ToggleFullscreen(); break;
case "minimize": WindowState = FormWindowState.Minimized; break;
case "quit": Close(); break;
case "drag":
if (WindowState == FormWindowState.Normal && (MouseButtons & MouseButtons.Left) != 0)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HTCAPTION, IntPtr.Zero);
}
break;
}
};
web.Source = new Uri(Host + "index.html");
web.Visible = true;
status.Visible = false;
}
catch (WebView2RuntimeNotFoundException)
{
status.Text = $"Es fehlt die „Microsoft Edge WebView2 Runtime“.\n\nHier klicken zum Herunterladen, danach {AppName} neu starten.";
status.Cursor = Cursors.Hand;
status.Click += (_, _) => { try { Process.Start(new ProcessStartInfo(WebView2Download) { UseShellExecute = true }); } catch { } };
}
catch (Exception ex)
{
status.Text = $"{AppName} konnte nicht starten:\n\n" + ex.Message;
status.ForeColor = Color.FromArgb(220, 60, 60);
}
}
// Resource names from %(RecursiveDir) contain backslashes - map "game/a/b.png" -> real name.
static readonly Dictionary<string, string> Resources = Assembly.GetExecutingAssembly()
.GetManifestResourceNames()
.ToDictionary(n => n.Replace('\\', '/'), n => n, StringComparer.OrdinalIgnoreCase);
static CoreWebView2WebResourceResponse Serve(CoreWebView2Environment env, string uri)
{
var path = Uri.UnescapeDataString(new Uri(uri).AbsolutePath.TrimStart('/'));
if (path.Length == 0) path = "index.html";
var stream = Resources.TryGetValue("game/" + path, out var name)
? Assembly.GetExecutingAssembly().GetManifestResourceStream(name) : null;
if (stream == null) return env.CreateWebResourceResponse(null, 404, "Not Found", "");
var mem = new MemoryStream();
stream.CopyTo(mem);
mem.Position = 0;
return env.CreateWebResourceResponse(mem, 200, "OK",
$"Content-Type: {Mime(path)}\nContent-Length: {mem.Length}\nCache-Control: no-cache");
}
static string Mime(string path) => Path.GetExtension(path).ToLowerInvariant() switch
{
".html" => "text/html; charset=utf-8",
".js" or ".mjs" => "text/javascript",
".css" => "text/css",
".json" => "application/json",
".png" => "image/png",
".jpg" or ".jpeg" => "image/jpeg",
".webp" => "image/webp",
".svg" => "image/svg+xml",
".mp3" => "audio/mpeg",
".ogg" => "audio/ogg",
".wav" => "audio/wav",
".ttf" => "font/ttf",
".otf" => "font/otf",
".woff2" => "font/woff2",
_ => "application/octet-stream",
};
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.F11 || keyData == (Keys.Alt | Keys.Enter)) { ToggleFullscreen(); return true; }
return base.ProcessCmdKey(ref msg, keyData);
}
// Borderless window: maximised = covers the whole screen incl. taskbar.
void ToggleFullscreen() =>
WindowState = WindowState == FormWindowState.Maximized ? FormWindowState.Normal : FormWindowState.Maximized;
}