229 lines
10 KiB
JavaScript
229 lines
10 KiB
JavaScript
|
|
/* {{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 => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[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();
|
||
|
|
})();
|