Add Netwall solo client, shared simulation core and protocol spec
- public/js/sim.js: pure game rules shared by browser and server (flow-field pathing with no corner cutting, placement validation that can never seal the route, towers, enemies, waves, economy, snapshots) - Responsive canvas client: desktop, landscape and portrait phones (board rotates 90 degrees in portrait), mouse + touch input, pinch zoom/pan, tap-to-preview placement, route preview, effects, synth sfx + music - Local and Remote controllers behind one interface (remote: snapshot interpolation, auto-reconnect, seat resume) - docs/PROTOCOL.md: co-op wire protocol and server requirements - README, PWA manifest and icons, 20 sim unit tests Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Tb8pW2KAN4oFkh1aK1BfD8
This commit is contained in:
commit
107ef60ec6
20 changed files with 4100 additions and 0 deletions
318
public/js/audio.js
Normal file
318
public/js/audio.js
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
/*
|
||||
* NETWALL audio: synthesised sound effects + background music.
|
||||
*
|
||||
* Music: looks for assets/music/<track>.mp3 (or .ogg) - tracks: theme (menu), battle, boss - plus one-shot
|
||||
* stingers win / lose. Any track that is missing falls back to a small generative synth melody, so the game
|
||||
* has music out of the box and a Suno-made file simply replaces it when you drop it in.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const NW = root.NW = root.NW || {};
|
||||
|
||||
const MUSIC_DIR = 'assets/music/';
|
||||
const STORE = 'nw.audio';
|
||||
|
||||
let ctx = null, master = null, sfxBus = null, musBus = null, delayNode = null;
|
||||
let muted = false, musicVol = 0.55, sfxVol = 0.8;
|
||||
let unlocked = false;
|
||||
let wanted = null; // music track the game currently wants ('theme' | 'battle' | 'boss' | null)
|
||||
let current = null; // { name, kind:'file'|'synth', el?, stop() }
|
||||
const fileState = {}; // name -> 'unknown' | 'ok' | 'missing'
|
||||
const lastPlay = {};
|
||||
const files = {}; // name -> HTMLAudioElement
|
||||
|
||||
try {
|
||||
const s = JSON.parse(localStorage.getItem(STORE) || '{}');
|
||||
if (typeof s.muted === 'boolean') muted = s.muted;
|
||||
if (typeof s.music === 'number') musicVol = Math.min(1, Math.max(0, s.music));
|
||||
} catch (e) { /* storage unavailable */ }
|
||||
function save() { try { localStorage.setItem(STORE, JSON.stringify({ muted, music: musicVol })); } catch (e) { /* ignore */ } }
|
||||
|
||||
function ensureCtx() {
|
||||
if (ctx) return ctx;
|
||||
const AC = root.AudioContext || root.webkitAudioContext;
|
||||
if (!AC) return null;
|
||||
try { ctx = new AC(); } catch (e) { return null; }
|
||||
master = ctx.createGain(); master.gain.value = muted ? 0 : 0.9;
|
||||
master.connect(ctx.destination);
|
||||
sfxBus = ctx.createGain(); sfxBus.gain.value = 0.32 * sfxVol; sfxBus.connect(master);
|
||||
musBus = ctx.createGain(); musBus.gain.value = 0.3 * musicVol; musBus.connect(master);
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- sfx
|
||||
function tone(freq, dur, type, vol, slideTo, when) {
|
||||
if (!ctx || muted) return;
|
||||
const t0 = ctx.currentTime + (when || 0);
|
||||
const o = ctx.createOscillator(), g = ctx.createGain();
|
||||
o.type = type || 'square';
|
||||
o.frequency.setValueAtTime(freq, t0);
|
||||
if (slideTo) o.frequency.exponentialRampToValueAtTime(Math.max(20, slideTo), t0 + dur);
|
||||
g.gain.setValueAtTime(0.0001, t0);
|
||||
g.gain.exponentialRampToValueAtTime(vol, t0 + 0.008);
|
||||
g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
|
||||
o.connect(g); g.connect(sfxBus);
|
||||
o.start(t0); o.stop(t0 + dur + 0.02);
|
||||
}
|
||||
let noiseBuf = null;
|
||||
function noiseBuffer() {
|
||||
if (noiseBuf) return noiseBuf;
|
||||
noiseBuf = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
|
||||
const d = noiseBuf.getChannelData(0);
|
||||
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
|
||||
return noiseBuf;
|
||||
}
|
||||
function noise(dur, vol, filterType, f0, f1, when, bus) {
|
||||
if (!ctx || muted) return;
|
||||
const t0 = ctx.currentTime + (when || 0);
|
||||
const s = ctx.createBufferSource(); s.buffer = noiseBuffer();
|
||||
const f = ctx.createBiquadFilter(); f.type = filterType || 'lowpass';
|
||||
f.frequency.setValueAtTime(f0, t0);
|
||||
if (f1) f.frequency.exponentialRampToValueAtTime(f1, t0 + dur);
|
||||
const g = ctx.createGain();
|
||||
g.gain.setValueAtTime(vol, t0);
|
||||
g.gain.exponentialRampToValueAtTime(0.0001, t0 + dur);
|
||||
s.connect(f); f.connect(g); g.connect(bus || sfxBus);
|
||||
s.start(t0, Math.random() * 0.5); s.stop(t0 + dur + 0.02);
|
||||
}
|
||||
|
||||
const SFX = {
|
||||
click: () => tone(660, 0.04, 'square', 0.12),
|
||||
place: () => { tone(420, 0.07, 'square', 0.22, 700); noise(0.05, 0.12, 'highpass', 3000); },
|
||||
wall: () => tone(240, 0.05, 'square', 0.16, 330),
|
||||
sell: () => tone(560, 0.12, 'triangle', 0.22, 220),
|
||||
up: () => { tone(520, 0.08, 'square', 0.18); tone(780, 0.08, 'square', 0.18, 0, 0.07); tone(1040, 0.14, 'square', 0.18, 0, 0.14); },
|
||||
error: () => { tone(190, 0.1, 'square', 0.2); tone(150, 0.12, 'square', 0.2, 0, 0.09); },
|
||||
shot_filter: () => noise(0.03, 0.07, 'highpass', 5000),
|
||||
shot_ids: () => { tone(1100, 0.14, 'sawtooth', 0.2, 180); noise(0.08, 0.12, 'highpass', 2500); },
|
||||
shot_mortar: () => tone(150, 0.18, 'sine', 0.45, 60),
|
||||
arc: () => { noise(0.1, 0.16, 'bandpass', 3500, 900); tone(900, 0.08, 'sawtooth', 0.1, 300); },
|
||||
boom: () => noise(0.32, 0.5, 'lowpass', 1800, 90),
|
||||
kill: () => tone(820, 0.05, 'triangle', 0.1, 1200),
|
||||
leak: () => { tone(320, 0.35, 'sawtooth', 0.3, 70); noise(0.25, 0.25, 'lowpass', 900, 100); },
|
||||
wave: () => { tone(220, 0.35, 'sawtooth', 0.14, 330); tone(330, 0.35, 'sawtooth', 0.12, 495, 0.05); tone(440, 0.45, 'sawtooth', 0.1, 660, 0.1); },
|
||||
boss: () => { tone(110, 0.8, 'sawtooth', 0.28, 55); tone(116, 0.8, 'sawtooth', 0.22, 58); noise(0.6, 0.2, 'lowpass', 600, 80); },
|
||||
clear: () => { tone(660, 0.09, 'triangle', 0.2); tone(880, 0.09, 'triangle', 0.2, 0, 0.09); tone(1320, 0.2, 'triangle', 0.2, 0, 0.18); },
|
||||
ping: () => { tone(1320, 0.18, 'sine', 0.25, 1760); tone(1760, 0.3, 'sine', 0.12, 0, 0.12); },
|
||||
join: () => { tone(660, 0.1, 'triangle', 0.2); tone(990, 0.16, 'triangle', 0.2, 0, 0.1); },
|
||||
};
|
||||
const MIN_GAP = { shot_filter: 0.06, kill: 0.05, arc: 0.07, boom: 0.08, shot_mortar: 0.1, shot_ids: 0.08, wall: 0.03 };
|
||||
|
||||
function sfx(name) {
|
||||
if (muted || !unlocked || !ctx || !SFX[name]) return;
|
||||
const now = ctx.currentTime, gap = MIN_GAP[name] || 0;
|
||||
if (gap && lastPlay[name] && now - lastPlay[name] < gap) return;
|
||||
lastPlay[name] = now;
|
||||
SFX[name]();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- generative music (fallback)
|
||||
const NOTE = (n) => 440 * Math.pow(2, (n - 69) / 12); // midi -> Hz
|
||||
const PROGS = {
|
||||
theme: { bpm: 76, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], bass: [45, 41, 36, 43] },
|
||||
battle: { bpm: 112, chords: [[57, 60, 64], [53, 57, 60], [48, 52, 55], [55, 59, 62]], bass: [45, 41, 36, 43] },
|
||||
boss: { bpm: 138, chords: [[57, 60, 64], [57, 60, 64], [53, 57, 60], [52, 56, 59]], bass: [45, 45, 41, 40] },
|
||||
};
|
||||
const ARP = [0, 1, 2, 1, 2, 1, 2, 0, 1, 2, 1, 2, 1, 0, 2, 1]; // chord-tone index per 16th
|
||||
|
||||
function startSynth(name) {
|
||||
const p = PROGS[name] || PROGS.battle;
|
||||
const out = ctx.createGain(); out.gain.value = 0.0001; out.connect(musBus);
|
||||
out.gain.exponentialRampToValueAtTime(1, ctx.currentTime + 1.5);
|
||||
const delay = ctx.createDelay(1.0); delay.delayTime.value = 60 / p.bpm * 0.75;
|
||||
const fb = ctx.createGain(); fb.gain.value = 0.38; delay.connect(fb); fb.connect(delay);
|
||||
const wet = ctx.createGain(); wet.gain.value = 0.5; delay.connect(wet); wet.connect(out);
|
||||
const sixteenth = 60 / p.bpm / 4;
|
||||
let step = 0, next = ctx.currentTime + 0.1, timer = 0, dead = false;
|
||||
|
||||
function note(type, freq, t, dur, vol, cutoff, dest) {
|
||||
const o = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain();
|
||||
o.type = type; o.frequency.value = freq;
|
||||
f.type = 'lowpass'; f.frequency.value = cutoff; f.Q.value = 2;
|
||||
g.gain.setValueAtTime(0.0001, t);
|
||||
g.gain.exponentialRampToValueAtTime(vol, t + Math.min(0.02, dur / 3));
|
||||
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
|
||||
o.connect(f); f.connect(g); g.connect(dest || out);
|
||||
o.start(t); o.stop(t + dur + 0.05);
|
||||
}
|
||||
function pad(chord, t, dur) {
|
||||
for (const n of chord) {
|
||||
for (const det of [-7, 7]) {
|
||||
const o = ctx.createOscillator(), f = ctx.createBiquadFilter(), g = ctx.createGain();
|
||||
o.type = 'sawtooth'; o.frequency.value = NOTE(n + 12); o.detune.value = det;
|
||||
f.type = 'lowpass'; f.frequency.setValueAtTime(500, t); f.frequency.linearRampToValueAtTime(1400, t + dur * 0.5); f.frequency.linearRampToValueAtTime(600, t + dur);
|
||||
g.gain.setValueAtTime(0.0001, t);
|
||||
g.gain.linearRampToValueAtTime(0.05, t + dur * 0.3);
|
||||
g.gain.linearRampToValueAtTime(0.0001, t + dur);
|
||||
o.connect(f); f.connect(g); g.connect(out);
|
||||
o.start(t); o.stop(t + dur + 0.05);
|
||||
}
|
||||
}
|
||||
}
|
||||
function kick(t) {
|
||||
const o = ctx.createOscillator(), g = ctx.createGain();
|
||||
o.type = 'sine'; o.frequency.setValueAtTime(140, t); o.frequency.exponentialRampToValueAtTime(42, t + 0.12);
|
||||
g.gain.setValueAtTime(0.9, t); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.22);
|
||||
o.connect(g); g.connect(out); o.start(t); o.stop(t + 0.25);
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
if (dead) return;
|
||||
while (next < ctx.currentTime + 0.25) {
|
||||
const bar = Math.floor(step / 16) % p.chords.length, s = step % 16;
|
||||
const chord = p.chords[bar], t = next;
|
||||
if (s === 0) pad(chord, t, sixteenth * 16 * 1.02);
|
||||
if (name !== 'theme' || s % 4 === 0) {
|
||||
// arpeggio, quieter and sparser for the menu theme
|
||||
const idx = ARP[s], n = chord[idx % 3] + 12 * (idx === 2 ? 1 : 0) + 12;
|
||||
const pat = name === 'theme' ? (s % 8 === 0) : (name === 'boss' ? true : (s % 2 === 0 || s % 16 === 15));
|
||||
if (pat) note('square', NOTE(n), t, sixteenth * 1.6, name === 'theme' ? 0.05 : 0.06, 2600, delay);
|
||||
if (pat) note('square', NOTE(n), t, sixteenth * 1.6, 0.03, 2600);
|
||||
}
|
||||
if (name !== 'theme') {
|
||||
if (s % 2 === 0) note('sawtooth', NOTE(p.bass[bar] + (s % 8 === 6 ? 12 : 0)), t, sixteenth * 1.7, 0.16, 420);
|
||||
if (s % 4 === 0) kick(t);
|
||||
if (s % 4 === 2) noise(0.05, 0.12, 'highpass', 7000, 0, t - ctx.currentTime, out);
|
||||
if (name === 'boss' && s % 8 === 4) noise(0.12, 0.2, 'bandpass', 1800, 900, t - ctx.currentTime, out);
|
||||
} else if (s === 0) {
|
||||
note('sine', NOTE(p.bass[bar]), t, sixteenth * 14, 0.22, 300);
|
||||
}
|
||||
step++; next += sixteenth;
|
||||
}
|
||||
}
|
||||
timer = setInterval(schedule, 40);
|
||||
schedule();
|
||||
return {
|
||||
name, kind: 'synth',
|
||||
stop(fade) {
|
||||
dead = true; clearInterval(timer);
|
||||
const t = ctx.currentTime;
|
||||
out.gain.cancelScheduledValues(t);
|
||||
out.gain.setValueAtTime(Math.max(0.0001, out.gain.value), t);
|
||||
out.gain.exponentialRampToValueAtTime(0.0001, t + (fade || 0.8));
|
||||
setTimeout(() => { try { out.disconnect(); } catch (e) { /* ignore */ } }, ((fade || 0.8) + 0.2) * 1000);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- file music
|
||||
// assets/music/tracks.json maps track names to file names, e.g. {"battle": "my-song.mp3"}; null = use the synth.
|
||||
// Reading one small manifest (instead of probing for files) keeps the console free of 404s.
|
||||
let manifestP = null;
|
||||
function manifest() {
|
||||
if (!manifestP) {
|
||||
manifestP = (typeof fetch === 'function' && root.location && /^https?:/.test(root.location.protocol))
|
||||
? fetch(MUSIC_DIR + 'tracks.json', { cache: 'no-cache' }).then((r) => (r.ok ? r.json() : {})).catch(() => ({}))
|
||||
: Promise.resolve({});
|
||||
}
|
||||
return manifestP;
|
||||
}
|
||||
function fileFor(name, cb) {
|
||||
if (fileState[name] === 'missing') { cb(null); return; }
|
||||
if (files[name]) { cb(files[name]); return; }
|
||||
manifest().then((m) => {
|
||||
const f = m && typeof m[name] === 'string' && /^[\w .()-]+\.(mp3|ogg|m4a|wav)$/i.test(m[name]) ? m[name] : null;
|
||||
if (!f) { fileState[name] = 'missing'; cb(null); return; }
|
||||
const el = new Audio();
|
||||
el.preload = 'auto';
|
||||
el.loop = name !== 'win' && name !== 'lose';
|
||||
el.addEventListener('canplay', () => { fileState[name] = 'ok'; files[name] = el; cb(el); }, { once: true });
|
||||
el.addEventListener('error', () => { fileState[name] = 'missing'; cb(null); }, { once: true });
|
||||
el.src = MUSIC_DIR + encodeURIComponent(f).replace(/%2F/g, '/');
|
||||
el.load();
|
||||
});
|
||||
}
|
||||
|
||||
function fadeEl(el, to, ms, done) {
|
||||
const from = el.volume, t0 = performance.now();
|
||||
const step = () => {
|
||||
const k = Math.min(1, (performance.now() - t0) / ms);
|
||||
try { el.volume = Math.max(0, Math.min(1, from + (to - from) * k)); } catch (e) { /* ignore */ }
|
||||
if (k < 1) requestAnimationFrame(step); else if (done) done();
|
||||
};
|
||||
step();
|
||||
}
|
||||
|
||||
function stopCurrent(fade) {
|
||||
const c = current; current = null;
|
||||
if (!c || c.kind === 'pending') return;
|
||||
if (c.kind === 'synth') c.stop(fade);
|
||||
else fadeEl(c.el, 0, (fade || 0.8) * 1000, () => { try { c.el.pause(); } catch (e) { /* ignore */ } });
|
||||
}
|
||||
|
||||
function applyMusic() {
|
||||
if (!unlocked) return;
|
||||
if (!wanted || muted) { stopCurrent(0.4); return; }
|
||||
if (current && current.name === wanted) return;
|
||||
const name = wanted;
|
||||
stopCurrent(0.9);
|
||||
// placeholder so that rapid calls do not stack
|
||||
const token = current = { name, kind: 'pending', stop() {} };
|
||||
fileFor(name, (el) => {
|
||||
if (current !== token) return; // superseded while loading
|
||||
if (el) {
|
||||
el.currentTime = 0; el.volume = 0;
|
||||
const pr = el.play();
|
||||
if (pr && pr.catch) pr.catch(() => { /* blocked: will retry on next gesture */ current = null; });
|
||||
current = { name, kind: 'file', el, stop() {} };
|
||||
fadeEl(el, 0.8 * musicVol, 1200);
|
||||
} else {
|
||||
const c = ensureCtx();
|
||||
current = c ? startSynth(name) : null;
|
||||
if (current) current.name = name;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function stinger(name) {
|
||||
if (muted || !unlocked) return;
|
||||
fileFor(name, (el) => {
|
||||
if (el) { try { el.currentTime = 0; el.volume = Math.min(1, 0.9 * Math.max(0.3, musicVol)); el.play().catch(() => {}); } catch (e) { /* ignore */ } return; }
|
||||
if (name === 'win') { [0, 4, 7, 12, 16, 19, 24].forEach((n, i) => tone(NOTE(69 + n), 0.3, 'triangle', 0.22, 0, i * 0.11)); }
|
||||
else { [0, -3, -7, -12, -17].forEach((n, i) => tone(NOTE(60 + n), 0.5, 'sawtooth', 0.2, NOTE(58 + n), i * 0.22)); }
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- public
|
||||
function unlock() {
|
||||
if (unlocked) return;
|
||||
const c = ensureCtx();
|
||||
if (c && c.state === 'suspended') c.resume();
|
||||
unlocked = true;
|
||||
applyMusic();
|
||||
}
|
||||
|
||||
root.addEventListener('pointerdown', unlock, { passive: true });
|
||||
root.addEventListener('keydown', unlock, { passive: true });
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (!ctx) return;
|
||||
if (document.hidden) {
|
||||
ctx.suspend && ctx.suspend();
|
||||
if (current && current.kind === 'file') current.el.pause();
|
||||
} else {
|
||||
ctx.resume && ctx.resume();
|
||||
if (current && current.kind === 'file' && !muted) current.el.play().catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
NW.Audio = {
|
||||
sfx,
|
||||
unlock,
|
||||
stinger,
|
||||
get muted() { return muted; },
|
||||
setMuted(m) {
|
||||
muted = !!m; save();
|
||||
if (master) master.gain.value = muted ? 0 : 0.9;
|
||||
if (muted) stopCurrent(0.2); else applyMusic();
|
||||
},
|
||||
toggleMuted() { this.setMuted(!muted); return muted; },
|
||||
// Which music the game wants right now: 'theme' | 'battle' | 'boss' | null
|
||||
music(name) { wanted = name; applyMusic(); },
|
||||
get musicVolume() { return musicVol; },
|
||||
setMusicVolume(v) {
|
||||
musicVol = Math.min(1, Math.max(0, v)); save();
|
||||
if (musBus) musBus.gain.value = 0.3 * musicVol;
|
||||
if (current && current.kind === 'file') current.el.volume = 0.8 * musicVol;
|
||||
},
|
||||
};
|
||||
})(typeof self !== 'undefined' ? self : this);
|
||||
353
public/js/controllers.js
Normal file
353
public/js/controllers.js
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
/*
|
||||
* NETWALL controllers. The UI and renderer talk to a "controller" and do not care whether the game runs
|
||||
* in this tab (LocalController, solo, works from file://) or on the server (RemoteController, co-op).
|
||||
*
|
||||
* ctrl.kind 'local' | 'remote'
|
||||
* ctrl.board TD.Board (own for local, a mirror for remote: used for route previews)
|
||||
* ctrl.view render state, refreshed by ctrl.update(nowMs):
|
||||
* gold lives maxLives wave state auto nextWaveIn kills winWave rev queued speed paused
|
||||
* towers[{id,type,x,y,level,mode,spent,owner,tgt,kills}]
|
||||
* monsters[{id,kind,x,y,hp,maxhp,slow,air}] bullets[{id,k,x,y}] cursors[{slot,x,y}]
|
||||
* ctrl.send(cmd) place / sell / upgrade / target / wave / auto / continue
|
||||
* ctrl.ctl(c, v) 'pause' | 'speed'
|
||||
* ctrl.preview(x,y,routes) would a block there be legal, and what does it do to the route?
|
||||
* events ctrl.on('events', list) | 'reject' | 'mark' | 'players' | 'status' | 'joined' | 'newgame' | 'fatal' | 'rtt'
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const NW = root.NW = root.NW || {};
|
||||
const TD = root.TD;
|
||||
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
|
||||
|
||||
class Emitter {
|
||||
constructor() { this._h = {}; }
|
||||
on(ev, fn) { (this._h[ev] = this._h[ev] || []).push(fn); return this; }
|
||||
emit(ev, a, b) {
|
||||
const l = this._h[ev];
|
||||
if (!l) return;
|
||||
for (const fn of l.slice()) { try { fn(a, b); } catch (e) { console.error(e); } }
|
||||
}
|
||||
}
|
||||
|
||||
// ws(s)://<same host>/ws, relative to the page so it also works under a proxy path prefix
|
||||
function wsUrl() {
|
||||
const u = new URL('ws', root.location.href);
|
||||
u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
u.search = ''; u.hash = '';
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
// ================================================================= local (solo)
|
||||
class LocalController extends Emitter {
|
||||
constructor(opts) {
|
||||
super();
|
||||
this.kind = 'local';
|
||||
this.mapId = (opts && opts.map) || 'open';
|
||||
this.speed = 1; this.paused = false;
|
||||
this.players = [{ slot: 0, name: 'You', online: true, host: true }];
|
||||
this.you = { slot: 0, host: true };
|
||||
this._fresh();
|
||||
}
|
||||
_fresh() {
|
||||
this.sim = new TD.Sim({ map: this.mapId });
|
||||
this.board = this.sim.board;
|
||||
this.acc = 0; this.last = 0;
|
||||
this.view = {
|
||||
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
|
||||
speed: this.speed, paused: this.paused, time: 0,
|
||||
towers: this.sim.towers, monsters: this.sim.monsters, bullets: this.sim.bullets, cursors: [],
|
||||
};
|
||||
this._sync();
|
||||
}
|
||||
_sync() {
|
||||
const s = this.sim, v = this.view;
|
||||
v.gold = s.gold; v.lives = s.lives; v.maxLives = s.maxLives; v.wave = s.wave; v.state = s.state;
|
||||
v.auto = s.autoWaves; v.nextWaveIn = s.autoWaves ? s.nextWaveIn : -1; v.kills = s.kills;
|
||||
v.winWave = isFinite(s.winWave) ? s.winWave : 0; v.rev = s.rev; v.queued = s.spawnQ.length;
|
||||
v.speed = this.speed; v.paused = this.paused; v.time = s.time;
|
||||
v.towers = s.towers; v.monsters = s.monsters; v.bullets = s.bullets;
|
||||
}
|
||||
update(now) {
|
||||
if (!this.last) this.last = now;
|
||||
const dt = Math.min(0.25, Math.max(0, (now - this.last) / 1000));
|
||||
this.last = now;
|
||||
if (!this.paused) {
|
||||
this.acc = Math.min(0.6, this.acc + dt * this.speed);
|
||||
while (this.acc >= TD.STEP) { this.sim.tick(TD.STEP); this.acc -= TD.STEP; }
|
||||
}
|
||||
const ev = this.sim.drainEvents();
|
||||
this._sync();
|
||||
if (ev.length) this.emit('events', ev);
|
||||
}
|
||||
send(cmd) {
|
||||
const res = this.sim.cmd(Object.assign({}, cmd, { by: 0 }));
|
||||
if (!res.ok) this.emit('reject', { c: cmd.c, reason: res.reason, x: cmd.x, y: cmd.y, id: cmd.id });
|
||||
return res;
|
||||
}
|
||||
ctl(c, v) {
|
||||
if (c === 'pause') this.paused = !!v;
|
||||
else if (c === 'speed') this.speed = clamp(v | 0, 1, 3);
|
||||
this._sync();
|
||||
}
|
||||
preview(x, y, routes) { return this.sim.preview(x, y, routes); }
|
||||
newGame(map) { if (map) this.mapId = map; this._fresh(); this.emit('newgame'); }
|
||||
sendCursor() {}
|
||||
sendMark(x, y) { this.emit('mark', { slot: 0, x, y }); }
|
||||
requestSync() {}
|
||||
close() {}
|
||||
}
|
||||
|
||||
// ================================================================= remote (co-op)
|
||||
class RemoteController extends Emitter {
|
||||
constructor(opts) {
|
||||
super();
|
||||
this.kind = 'remote';
|
||||
this.url = opts.url || wsUrl();
|
||||
this.pid = opts.pid; this.name = opts.name || 'Player';
|
||||
this.room = opts.room || null; // null => create a room on first connect
|
||||
this.mapId = opts.map || 'open';
|
||||
this.status = 'idle'; // idle | connecting | joined | reconnecting | closed
|
||||
this.ws = null; this.players = []; this.you = null; this.board = null;
|
||||
this.buf = []; this.delay = 120;
|
||||
this.rev = -1; this.recvRev = -1; this.towers = [];
|
||||
this.monCache = new Map(); this.bulCache = new Map(); this._gen = 0;
|
||||
this.rtt = 0;
|
||||
this.retry = 0; this.intentional = false; this.fatal = false;
|
||||
this.lastMsg = 0; this.lastSync = 0; this.lastCursor = 0;
|
||||
this.speed = 1; this.paused = false;
|
||||
this.view = {
|
||||
gold: 0, lives: 0, maxLives: 0, wave: 0, state: 'playing', auto: false, nextWaveIn: -1, kills: 0, winWave: 0, rev: 0, queued: 0,
|
||||
speed: 1, paused: false, time: 0, towers: [], monsters: [], bullets: [], cursors: [],
|
||||
};
|
||||
this._onVis = () => { if (!document.hidden) this._wake(); };
|
||||
document.addEventListener('visibilitychange', this._onVis);
|
||||
root.addEventListener('online', this._onVis);
|
||||
this._timers = [];
|
||||
}
|
||||
|
||||
connect() {
|
||||
if (this.intentional || this.fatal) return;
|
||||
if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) return;
|
||||
this._setStatus(this.status === 'joined' || this.status === 'reconnecting' ? 'reconnecting' : 'connecting');
|
||||
let ws;
|
||||
try { ws = new WebSocket(this.url); } catch (e) { this._failed(); return; }
|
||||
this.ws = ws;
|
||||
ws.onopen = () => {
|
||||
const j = { t: 'join', pid: this.pid, name: this.name };
|
||||
if (this.room) j.room = this.room; else j.map = this.mapId;
|
||||
this._send(j);
|
||||
};
|
||||
ws.onmessage = (e) => { this.lastMsg = performance.now(); this._onMsg(e.data); };
|
||||
ws.onclose = (e) => { if (this.ws === ws) this._onClose(e); };
|
||||
ws.onerror = () => { /* onclose follows */ };
|
||||
}
|
||||
|
||||
_setStatus(s) { if (this.status !== s) { this.status = s; this.emit('status', s); } }
|
||||
|
||||
_failed() {
|
||||
if (this.status === 'connecting') { this._die('connect', 'Could not reach the game server.'); return; }
|
||||
this.retry++;
|
||||
if (this.retry > 14) { this._die('lost', 'Lost connection to the server.'); return; }
|
||||
this._setStatus('reconnecting');
|
||||
const wait = Math.min(5000, 350 * Math.pow(1.7, this.retry - 1));
|
||||
const id = setTimeout(() => this.connect(), wait);
|
||||
this._timers.push(id);
|
||||
}
|
||||
_die(code, msg) {
|
||||
this.fatal = true; this._setStatus('closed');
|
||||
this._stopTimers();
|
||||
this.emit('fatal', { code, msg });
|
||||
}
|
||||
_onClose(e) {
|
||||
this.ws = null;
|
||||
this._stopRtt();
|
||||
if (this.intentional || this.fatal) { this._setStatus('closed'); return; }
|
||||
if (e && e.code === 4001) { this._die('replaced', 'This game was opened in another tab or device.'); return; }
|
||||
this._failed();
|
||||
}
|
||||
_wake() {
|
||||
// back from sleep / background / network switch: a socket that looks open may be dead, so reconnect quickly
|
||||
if (this.intentional || this.fatal || this.status === 'connecting') return;
|
||||
const stale = performance.now() - this.lastMsg > 2500;
|
||||
if (!this.ws || this.ws.readyState > 1) { this.retry = 0; this.connect(); }
|
||||
else if (this.status === 'joined' && stale) { try { this.ws.close(); } catch (e) { /* ignore */ } }
|
||||
}
|
||||
_stopTimers() { for (const t of this._timers) clearTimeout(t); this._timers.length = 0; this._stopRtt(); }
|
||||
_stopRtt() { if (this._rttT) { clearInterval(this._rttT); this._rttT = 0; } if (this._wdT) { clearInterval(this._wdT); this._wdT = 0; } }
|
||||
_startRtt() {
|
||||
this._stopRtt();
|
||||
this._rttT = setInterval(() => this._send({ t: 'rtt', ts: performance.now() }), 2000);
|
||||
this._wdT = setInterval(() => { // snapshots flow at 20 Hz even when paused: silence means a dead socket
|
||||
if (this.status === 'joined' && this.ws && performance.now() - this.lastMsg > 5000) { try { this.ws.close(); } catch (e) { /* ignore */ } }
|
||||
}, 1000);
|
||||
}
|
||||
_send(o) { if (this.ws && this.ws.readyState === 1) this.ws.send(JSON.stringify(o)); }
|
||||
|
||||
_onMsg(raw) {
|
||||
let m;
|
||||
try { m = JSON.parse(raw); } catch (e) { return; }
|
||||
if (!m || typeof m.t !== 'string') return;
|
||||
switch (m.t) {
|
||||
case 'snap': this._onSnap(m); break;
|
||||
case 'joined':
|
||||
this.room = m.room; this.you = m.you; this.players = m.players || [];
|
||||
this.retry = 0; this.speed = m.speed || 1; this.paused = !!m.paused;
|
||||
this._applyState(m.state, m.snap);
|
||||
this._setStatus('joined');
|
||||
this._startRtt();
|
||||
this.emit('joined', m);
|
||||
this.emit('players', this.players);
|
||||
break;
|
||||
case 'state':
|
||||
this.speed = m.speed || 1; this.paused = !!m.paused;
|
||||
this._applyState(m.state, m.snap);
|
||||
if (m.newgame) this.emit('newgame');
|
||||
break;
|
||||
case 'players':
|
||||
this.players = m.players || [];
|
||||
{ const me = this.players.find((p) => this.you && p.pid === this.you.pid); if (me) this.you = Object.assign({}, this.you, { host: me.host, slot: me.slot }); }
|
||||
this.emit('players', this.players);
|
||||
break;
|
||||
case 'reject': this.emit('reject', m); break;
|
||||
case 'mark': this.emit('mark', m); break;
|
||||
case 'rtt':
|
||||
{ const s = performance.now() - m.ts; this.rtt = this.rtt ? Math.round(this.rtt * 0.7 + s * 0.3) : Math.round(s); this.emit('rtt', this.rtt); }
|
||||
break;
|
||||
case 'error': {
|
||||
const msgs = { no_room: 'That room does not exist (any more).', full: 'That room already has two players.', bad_request: 'The server did not understand the request.', too_many_rooms: 'The server is full right now. Try again in a minute.', bad_map: 'Unknown map.' };
|
||||
this._die(m.code || 'error', msgs[m.code] || m.msg || 'Server error.');
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
_setTowers(list) {
|
||||
const b = this.board;
|
||||
b.solid.set(b.obst);
|
||||
this.towers = list.map((a) => {
|
||||
b.setSolid(a[2], a[3], 1);
|
||||
return { id: a[0], type: a[1], x: a[2], y: a[3], level: a[4], mode: a[5], spent: a[6], owner: a[7], tgt: 0, kills: 0 };
|
||||
});
|
||||
b.recompute();
|
||||
}
|
||||
_applyState(state, snap) {
|
||||
if (!this.board || this.board.mapId !== state.map) { this.board = new TD.Board(state.map); this.mapId = state.map; }
|
||||
this._setTowers(state.towers);
|
||||
this.rev = this.recvRev = state.rev;
|
||||
this.maxLives = state.maxLives; this.winWave = state.winWave;
|
||||
this.buf.length = 0; this.monCache.clear(); this.bulCache.clear();
|
||||
if (snap) this._push(snap, true);
|
||||
}
|
||||
_push(snap, first) {
|
||||
const mo = new Map(), bu = new Map(), tt = new Map();
|
||||
for (const a of snap.mo || []) mo.set(a[0], a);
|
||||
for (const a of snap.bu || []) bu.set(a[0], a);
|
||||
for (const a of snap.tt || []) tt.set(a[0], a);
|
||||
const e = { t: performance.now(), snap, mo, bu, tt, rel: !!first };
|
||||
this.buf.push(e);
|
||||
if (this.buf.length > 10) this.buf.shift();
|
||||
}
|
||||
// Towers ride along with the snapshot that changed them and are applied when that snapshot is *displayed*
|
||||
// (see update), so a new tower and the credits it cost appear on screen together.
|
||||
_onSnap(m) {
|
||||
if (m.tw) this.recvRev = m.rev;
|
||||
else if (m.rev !== this.recvRev) this.requestSync();
|
||||
this._push(m, false);
|
||||
}
|
||||
requestSync() {
|
||||
const now = performance.now();
|
||||
if (now - this.lastSync < 1000) return;
|
||||
this.lastSync = now;
|
||||
this._send({ t: 'sync' });
|
||||
}
|
||||
|
||||
update(now) {
|
||||
const buf = this.buf;
|
||||
if (!buf.length || !this.board) return;
|
||||
const rt = now - this.delay;
|
||||
for (const e of buf) {
|
||||
if (!e.rel && e.t <= rt) { e.rel = true; if (e.snap.ev && e.snap.ev.length) this.emit('events', e.snap.ev); }
|
||||
}
|
||||
let i = buf.length - 1;
|
||||
while (i > 0 && buf[i].t > rt) i--;
|
||||
const a = buf[i], b = buf[Math.min(i + 1, buf.length - 1)];
|
||||
const alpha = a === b ? 1 : clamp((rt - a.t) / (b.t - a.t), 0, 1);
|
||||
let lastTw = null;
|
||||
for (let k = 0; k <= i; k++) { if (buf[k].snap.tw && !buf[k].twDone) { lastTw = buf[k]; } buf[k].twDone = true; }
|
||||
if (lastTw) { this._setTowers(lastTw.snap.tw); this.rev = lastTw.snap.rev; }
|
||||
const s = a.snap, v = this.view;
|
||||
v.gold = s.g; v.lives = s.l; v.wave = s.w; v.state = s.s; v.auto = !!s.au; v.nextWaveIn = s.nw; v.kills = s.k;
|
||||
v.rev = s.rev; v.queued = s.q || 0; v.time = s.time;
|
||||
v.maxLives = this.maxLives; v.winWave = this.winWave;
|
||||
v.speed = s.sp || 1; v.paused = !!s.pa;
|
||||
|
||||
const gen = ++this._gen;
|
||||
const kinds = TD.ENEMY_ORDER;
|
||||
const mons = v.monsters; mons.length = 0;
|
||||
for (const mb of b.mo.values()) {
|
||||
const ma = a !== b ? a.mo.get(mb[0]) : null;
|
||||
let o = this.monCache.get(mb[0]);
|
||||
if (!o) { o = { id: mb[0], kind: kinds[mb[1]], air: !!TD.ENEMIES[kinds[mb[1]]].air }; this.monCache.set(mb[0], o); }
|
||||
o.x = ma ? ma[2] + (mb[2] - ma[2]) * alpha : mb[2];
|
||||
o.y = ma ? ma[3] + (mb[3] - ma[3]) * alpha : mb[3];
|
||||
o.hp = mb[4]; o.maxhp = mb[5]; o.slow = mb[6]; o.gen = gen;
|
||||
mons.push(o);
|
||||
}
|
||||
for (const [id, o] of this.monCache) if (o.gen !== gen) this.monCache.delete(id);
|
||||
|
||||
const buls = v.bullets; buls.length = 0;
|
||||
for (const bb of b.bu.values()) {
|
||||
const ba = a !== b ? a.bu.get(bb[0]) : null;
|
||||
let o = this.bulCache.get(bb[0]);
|
||||
if (!o) { o = { id: bb[0], k: bb[1] === 1 ? 'mortar' : 'filter' }; this.bulCache.set(bb[0], o); }
|
||||
o.x = ba ? ba[2] + (bb[2] - ba[2]) * alpha : bb[2];
|
||||
o.y = ba ? ba[3] + (bb[3] - ba[3]) * alpha : bb[3];
|
||||
o.gen = gen;
|
||||
buls.push(o);
|
||||
}
|
||||
for (const [id, o] of this.bulCache) if (o.gen !== gen) this.bulCache.delete(id);
|
||||
|
||||
for (const t of this.towers) {
|
||||
const r = a.tt.get(t.id);
|
||||
t.tgt = r ? r[1] : 0; t.kills = r ? r[2] : 0;
|
||||
}
|
||||
v.towers = this.towers;
|
||||
const mySlot = this.you ? this.you.slot : -1;
|
||||
v.cursors = (b.snap.cur || []).filter((c) => c[0] !== mySlot).map((c) => ({ slot: c[0], x: c[1], y: c[2] }));
|
||||
}
|
||||
|
||||
send(cmd) {
|
||||
const c = Object.assign({}, cmd); delete c.by;
|
||||
this._send(Object.assign({ t: 'cmd' }, c));
|
||||
return { ok: true, pending: true };
|
||||
}
|
||||
ctl(c, v) { this._send({ t: 'ctl', c, v }); }
|
||||
preview(x, y, routes) {
|
||||
if (!this.board) return { ok: false, reason: 'bounds' };
|
||||
const reserved = new Set();
|
||||
for (const m of this.view.monsters) if (!m.air) reserved.add(Math.floor(m.y) * this.board.cols + Math.floor(m.x));
|
||||
return this.board.trial(x, y, reserved, null, routes);
|
||||
}
|
||||
newGame(map) { this._send({ t: 'newgame', map }); }
|
||||
sendCursor(x, y) {
|
||||
const now = performance.now();
|
||||
if (now - this.lastCursor < 70) return;
|
||||
this.lastCursor = now;
|
||||
this._send({ t: 'cursor', x: x === null ? null : Math.round(x * 100) / 100, y: y === null ? null : Math.round(y * 100) / 100 });
|
||||
}
|
||||
sendMark(x, y) { this._send({ t: 'mark', x: Math.round(x * 100) / 100, y: Math.round(y * 100) / 100 }); }
|
||||
close() {
|
||||
this.intentional = true;
|
||||
this._stopTimers();
|
||||
document.removeEventListener('visibilitychange', this._onVis);
|
||||
root.removeEventListener('online', this._onVis);
|
||||
if (this.ws) { try { this._send({ t: 'leave' }); this.ws.close(); } catch (e) { /* ignore */ } }
|
||||
this._setStatus('closed');
|
||||
}
|
||||
}
|
||||
|
||||
NW.LocalController = LocalController;
|
||||
NW.RemoteController = RemoteController;
|
||||
NW.wsUrl = wsUrl;
|
||||
})(typeof self !== 'undefined' ? self : this);
|
||||
888
public/js/main.js
Normal file
888
public/js/main.js
Normal file
|
|
@ -0,0 +1,888 @@
|
|||
/*
|
||||
* NETWALL main: screens, HUD, input (mouse + touch), lobby, glue between controllers, renderer and audio.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const TD = root.TD, NW = root.NW, Audio = NW.Audio;
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
|
||||
|
||||
// ------------------------------------------------------------------ storage (every access guarded)
|
||||
const store = {
|
||||
get(k, d) { try { const v = root.localStorage.getItem(k); return v === null ? d : JSON.parse(v); } catch (e) { return d; } },
|
||||
set(k, v) { try { root.localStorage.setItem(k, JSON.stringify(v)); } catch (e) { /* ignore */ } },
|
||||
del(k) { try { root.localStorage.removeItem(k); } catch (e) { /* ignore */ } },
|
||||
};
|
||||
const sess = {
|
||||
get(k) { try { return root.sessionStorage.getItem(k); } catch (e) { return null; } },
|
||||
set(k, v) { try { root.sessionStorage.setItem(k, v); } catch (e) { /* ignore */ } },
|
||||
del(k) { try { root.sessionStorage.removeItem(k); } catch (e) { /* ignore */ } },
|
||||
};
|
||||
function randomId(n) {
|
||||
const abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
|
||||
let out = '';
|
||||
const buf = new Uint8Array(n);
|
||||
if (root.crypto && root.crypto.getRandomValues) root.crypto.getRandomValues(buf); else for (let i = 0; i < n; i++) buf[i] = Math.random() * 256;
|
||||
for (let i = 0; i < n; i++) out += abc[buf[i] & 63];
|
||||
return out;
|
||||
}
|
||||
function getPid() { let p = sess.get('nw.pid'); if (!p || !/^[A-Za-z0-9_-]{8,40}$/.test(p)) { p = randomId(22); sess.set('nw.pid', p); } return p; }
|
||||
|
||||
const REASONS = {
|
||||
bounds: 'Out of bounds', obstacle: 'That node is dead. Pick another cell', occupied: 'Something is already there', spawn: "Can't build on a gateway",
|
||||
core: "Can't build on the server", monster: 'A packet is in the way', blocks: 'That would seal the route. Leave a path!', gold: 'Not enough credits',
|
||||
over: 'The game is over', no_tower: 'That tower no longer exists', max: 'Already at max level', not_host: 'Only the host can do that',
|
||||
bad_map: 'Unknown map', bad_type: 'Unknown tower', bad_cmd: 'Invalid command', not_won: 'Nothing to continue',
|
||||
};
|
||||
const MODE_NAMES = { first: 'First', last: 'Last', strong: 'Strongest', close: 'Closest' };
|
||||
|
||||
// ------------------------------------------------------------------ app state
|
||||
const app = {
|
||||
ctrl: null, renderer: null, screen: 'menu', inGame: false,
|
||||
mapId: store.get('nw.map', 'open'),
|
||||
selType: null, selTower: 0,
|
||||
hover: null, pending: null, preview: null, valid: true, previewDirty: true, lastPreviewAt: 0,
|
||||
zoomed: false, last: {}, names: {}, started: false, lastBossCheck: 0, bossMusic: false,
|
||||
endShown: false, prevPlayers: null,
|
||||
};
|
||||
const ui = { hover: null, selType: null, selTower: 0, preview: null, valid: true, coop: false, names: {} };
|
||||
|
||||
const canvas = $('board');
|
||||
const renderer = new NW.Renderer(canvas);
|
||||
app.renderer = renderer;
|
||||
if (!TD.MAPS[app.mapId]) app.mapId = 'open';
|
||||
|
||||
// ------------------------------------------------------------------ small UI helpers
|
||||
let lastToast = '', lastToastAt = 0;
|
||||
function toast(text, kind) {
|
||||
const now = performance.now();
|
||||
if (text === lastToast && now - lastToastAt < 900) return;
|
||||
lastToast = text; lastToastAt = now;
|
||||
const d = document.createElement('div');
|
||||
d.className = 'toast' + (kind ? ' ' + kind : '');
|
||||
d.textContent = text;
|
||||
$('toasts').appendChild(d);
|
||||
setTimeout(() => d.remove(), 2700);
|
||||
while ($('toasts').children.length > 3) $('toasts').firstChild.remove();
|
||||
}
|
||||
let bannerT = 0;
|
||||
function banner(text, boss) {
|
||||
const b = $('banner');
|
||||
b.textContent = text; b.className = 'banner show' + (boss ? ' boss' : '');
|
||||
clearTimeout(bannerT);
|
||||
bannerT = setTimeout(() => { b.className = 'banner' + (boss ? ' boss' : ''); }, 1500);
|
||||
}
|
||||
function hint(text, kind) {
|
||||
const h = $('hint');
|
||||
if (!text) { h.hidden = true; return; }
|
||||
h.hidden = false; h.textContent = text; h.className = 'hint ' + (kind || 'info');
|
||||
}
|
||||
const fmtLen = (v) => String(Math.round(v / Math.max(1, ui.spawns || 1)));
|
||||
|
||||
function showOverlay(id) {
|
||||
for (const o of document.querySelectorAll('.overlay')) o.hidden = o.id !== id;
|
||||
}
|
||||
function setScreen(name) {
|
||||
app.screen = name;
|
||||
$('app').dataset.screen = name;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ controller switching
|
||||
function useController(ctrl) {
|
||||
if (app.ctrl && app.ctrl !== ctrl && app.ctrl.kind === 'remote') { /* closed by caller */ }
|
||||
app.ctrl = ctrl;
|
||||
ctrl.on('events', onEvents);
|
||||
ctrl.on('reject', onReject);
|
||||
ctrl.on('mark', (m) => { renderer.addMark(m.x, m.y, m.slot); Audio.sfx('ping'); });
|
||||
ctrl.on('players', onPlayers);
|
||||
ctrl.on('newgame', () => { resetSelection(); app.endShown = false; app.last.state = 'playing'; adoptBoard(); $('end').hidden = true; });
|
||||
adoptBoard(true);
|
||||
}
|
||||
function adoptBoard(force) {
|
||||
const b = app.ctrl.board;
|
||||
if (b && (force || renderer.board !== b)) {
|
||||
renderer.setBoard(b);
|
||||
$('app').style.setProperty('--aspect', b.cols + ' / ' + b.rows);
|
||||
$('app').style.setProperty('--aspect-p', b.rows + ' / ' + b.cols);
|
||||
ui.spawns = b.spawns.length;
|
||||
resizeCanvas();
|
||||
}
|
||||
}
|
||||
function resetSelection() {
|
||||
app.selType = null; app.selTower = 0; app.pending = null; app.hover = null; app.preview = null; app.previewDirty = true;
|
||||
syncPalette(); renderInfo(true); updateConfirm();
|
||||
}
|
||||
|
||||
function startSolo(mapId) {
|
||||
leaveRemote(true);
|
||||
app.mapId = mapId; store.set('nw.map', mapId);
|
||||
const c = new NW.LocalController({ map: mapId });
|
||||
useController(c);
|
||||
app.inGame = true; app.started = true; app.endShown = false; app.last = {};
|
||||
resetSelection(); setScreen('playing'); showOverlay(null);
|
||||
$('players').hidden = true; $('netChip').hidden = true; $('reconnect').hidden = true;
|
||||
renderInfo(true);
|
||||
Audio.music('battle');
|
||||
requestWakeLock();
|
||||
if (!store.get('nw.helped', false)) { store.set('nw.helped', true); showOverlay('help'); }
|
||||
}
|
||||
function previewMap(mapId) {
|
||||
const c = new NW.LocalController({ map: mapId });
|
||||
c.paused = true;
|
||||
useController(c);
|
||||
app.inGame = false;
|
||||
}
|
||||
|
||||
function leaveRemote(silent) {
|
||||
const c = app.ctrl;
|
||||
if (c && c.kind === 'remote') { c.close(); }
|
||||
sess.del('nw.room'); store.del('nw.session');
|
||||
clearRoomFromUrl();
|
||||
if (!silent) { /* caller handles screens */ }
|
||||
}
|
||||
function clearRoomFromUrl() {
|
||||
try { if (root.location.search) root.history.replaceState(null, '', root.location.pathname); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ events from the controller
|
||||
function onEvents(evs) {
|
||||
renderer.addEvents(evs);
|
||||
for (const e of evs) {
|
||||
switch (e.e) {
|
||||
case 'place': Audio.sfx(e.type === 'wall' ? 'wall' : 'place'); break;
|
||||
case 'sell': Audio.sfx('sell'); break;
|
||||
case 'up': Audio.sfx('up'); break;
|
||||
case 'shot': Audio.sfx('shot_' + e.k); break;
|
||||
case 'arc': Audio.sfx('arc'); break;
|
||||
case 'boom': Audio.sfx('boom'); break;
|
||||
case 'kill': Audio.sfx('kill'); break;
|
||||
case 'leak': Audio.sfx('leak'); break;
|
||||
case 'wave': banner(e.boss ? 'BOSS WAVE ' + e.n : 'WAVE ' + e.n, e.boss); Audio.sfx(e.boss ? 'boss' : 'wave'); break;
|
||||
case 'clear': toast('Wave ' + e.n + ' cleared +' + e.bonus + ' credits', 'good'); Audio.sfx('clear'); break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
function onReject(r) {
|
||||
toast(REASONS[r.reason] || ('Not possible: ' + r.reason), 'bad');
|
||||
Audio.sfx('error');
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ palette + info panel
|
||||
function buildPalette() {
|
||||
const pal = $('palette');
|
||||
pal.textContent = '';
|
||||
for (const type of TD.TOWER_ORDER) {
|
||||
const def = TD.TOWERS[type];
|
||||
const b = document.createElement('button');
|
||||
b.className = 'tbtn'; b.dataset.type = type; b.type = 'button';
|
||||
b.setAttribute('aria-label', def.name + ', ' + def.levels[0].cost + ' credits');
|
||||
b.innerHTML = '<span class="key">' + def.key + '</span><canvas></canvas><span class="nm"></span><span class="cost"></span>';
|
||||
b.querySelector('.nm').textContent = def.name;
|
||||
b.querySelector('.cost').textContent = String(def.levels[0].cost);
|
||||
b.addEventListener('click', () => { Audio.sfx('click'); selectType(app.selType === type ? null : type); });
|
||||
pal.appendChild(b);
|
||||
}
|
||||
drawPaletteIcons();
|
||||
}
|
||||
function drawPaletteIcons() {
|
||||
for (const b of $('palette').children) NW.drawIcon(b.querySelector('canvas'), b.dataset.type, 1);
|
||||
}
|
||||
function syncPalette() {
|
||||
for (const b of $('palette').children) {
|
||||
const sel = b.dataset.type === app.selType;
|
||||
b.classList.toggle('sel', sel);
|
||||
b.setAttribute('aria-pressed', sel ? 'true' : 'false');
|
||||
}
|
||||
}
|
||||
function selectType(type) {
|
||||
app.selType = type; app.selTower = 0; app.pending = null; app.previewDirty = true;
|
||||
syncPalette(); renderInfo(true); updateConfirm();
|
||||
if (!type) { ui.preview = null; hint(null); }
|
||||
}
|
||||
function selectTower(id) {
|
||||
app.selTower = id; app.selType = null; app.pending = null; app.preview = null; ui.preview = null;
|
||||
syncPalette(); renderInfo(true); updateConfirm(); hint(null);
|
||||
}
|
||||
|
||||
function statsFor(type, lv) {
|
||||
const L = TD.TOWERS[type].levels[lv], out = [];
|
||||
if (L.dmg) out.push(['Damage', String(Math.round(L.dmg))]);
|
||||
if (L.rate) out.push(['Fire rate', L.rate.toFixed(1) + '/s']);
|
||||
if (L.dmg && L.rate) out.push(['DPS', String(Math.round(L.dmg * L.rate))]);
|
||||
if (L.range) out.push(['Range', L.range.toFixed(1)]);
|
||||
if (L.splash) out.push(['Splash', L.splash.toFixed(1)]);
|
||||
if (L.slow) out.push(['Slows', Math.round(L.slow * 100) + '%']);
|
||||
if (L.chains) out.push(['Chains', String(L.chains)]);
|
||||
return out;
|
||||
}
|
||||
function targetsText(def) { return def.ground && def.air ? 'ground + air' : def.ground ? 'ground only' : 'none'; }
|
||||
|
||||
let infoSig = '';
|
||||
function renderInfo(force) {
|
||||
const box = $('info'), ctrl = app.ctrl, view = ctrl.view;
|
||||
let sig, tower = null;
|
||||
if (app.selTower) {
|
||||
tower = view.towers.find((t) => t.id === app.selTower);
|
||||
if (!tower) { app.selTower = 0; }
|
||||
}
|
||||
if (tower) sig = 't' + tower.id + ':' + tower.level + ':' + tower.mode;
|
||||
else if (app.selType) sig = 'b' + app.selType;
|
||||
else sig = '';
|
||||
if (!force && sig === infoSig) return;
|
||||
infoSig = sig;
|
||||
if (!sig) { box.textContent = ''; return; }
|
||||
if (tower) {
|
||||
const def = TD.TOWERS[tower.type], i = tower.level - 1;
|
||||
const cur = statsFor(tower.type, i), nxt = tower.level < 3 ? statsFor(tower.type, i + 1) : null;
|
||||
let kv = '';
|
||||
cur.forEach((row, k) => {
|
||||
const n = nxt && nxt[k] && nxt[k][1] !== row[1] ? ' <span class="up">→ ' + nxt[k][1] + '</span>' : '';
|
||||
kv += '<div class="kvp"><span>' + row[0] + '</span><span>' + row[1] + n + '</span></div>';
|
||||
});
|
||||
if (tower.type !== 'wall') kv += '<div class="kvp"><span>Targets</span><span>' + targetsText(def) + '</span></div>';
|
||||
const sellVal = def.refund ? tower.spent : Math.floor(tower.spent * TD.SELL_RATIO);
|
||||
const upCost = tower.level < 3 ? def.levels[tower.level].cost : null;
|
||||
const owner = ctrl.kind === 'remote' && ctrl.players.length > 1;
|
||||
const ownerP = owner ? ctrl.players.find((p) => p.slot === tower.owner) : null;
|
||||
box.innerHTML =
|
||||
'<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div>' +
|
||||
'<div class="desc"></div><div class="kv">' + kv + '</div><div class="actions">' +
|
||||
(tower.type === 'wall' ? '' :
|
||||
'<button type="button" data-act="up"' + (upCost === null ? ' disabled' : '') + '><svg class="ic"><use href="#i-up"/></svg>' + (upCost === null ? 'Max level' : 'Upgrade <span class="cost" id="upCost">' + upCost + '</span>') + '</button>' +
|
||||
'<button type="button" data-act="mode" title="Which packet to shoot"><span>Target: ' + MODE_NAMES[tower.mode] + '</span></button>') +
|
||||
'<button type="button" data-act="sell" class="danger"><svg class="ic"><use href="#i-trash"/></svg>Sell <span class="cost">' + sellVal + '</span></button></div>' +
|
||||
'<div class="byline">' + (tower.type === 'wall' ? '' : '<span id="infoKills"></span>') + (ownerP ? '<span class="dot" style="background:' + NW.SLOT_COLORS[ownerP.slot] + '"></span><span id="infoOwner"></span>' : '') + '</div></div>';
|
||||
box.querySelector('.nm').textContent = def.name;
|
||||
box.querySelector('.lv').textContent = tower.type === 'wall' ? '' : 'Level ' + tower.level + ' / 3';
|
||||
box.querySelector('.desc').textContent = def.desc;
|
||||
if (ownerP) box.querySelector('#infoOwner').textContent = 'Built by ' + ownerP.name;
|
||||
NW.drawIcon(box.querySelector('canvas'), tower.type, tower.level);
|
||||
} else {
|
||||
const def = TD.TOWERS[app.selType];
|
||||
let kv = '';
|
||||
for (const row of statsFor(app.selType, 0)) kv += '<div class="kvp"><span>' + row[0] + '</span><span>' + row[1] + '</span></div>';
|
||||
if (app.selType !== 'wall') kv += '<div class="kvp"><span>Targets</span><span>' + targetsText(def) + '</span></div>';
|
||||
box.innerHTML = '<div class="panel info"><div class="info-head"><canvas></canvas><div><div class="nm"></div><div class="lv"></div></div></div><div class="desc"></div><div class="kv">' + kv + '</div></div>';
|
||||
box.querySelector('.nm').textContent = def.name;
|
||||
box.querySelector('.lv').textContent = def.levels[0].cost + ' credits';
|
||||
box.querySelector('.desc').textContent = def.desc;
|
||||
NW.drawIcon(box.querySelector('canvas'), app.selType, 1);
|
||||
}
|
||||
}
|
||||
function updateInfoDynamic() {
|
||||
if (!app.selTower) return;
|
||||
const t = app.ctrl.view.towers.find((x) => x.id === app.selTower);
|
||||
if (!t) return;
|
||||
const k = $('infoKills'); if (k) k.textContent = t.kills + (t.kills === 1 ? ' kill' : ' kills');
|
||||
const def = TD.TOWERS[t.type];
|
||||
const up = $('info').querySelector('[data-act="up"]');
|
||||
if (up && t.level < 3) up.disabled = app.ctrl.view.gold < def.levels[t.level].cost;
|
||||
}
|
||||
$('info').addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button[data-act]'); if (!btn || !app.selTower) return;
|
||||
const ctrl = app.ctrl, tower = ctrl.view.towers.find((t) => t.id === app.selTower);
|
||||
if (!tower) return;
|
||||
Audio.sfx('click');
|
||||
switch (btn.dataset.act) {
|
||||
case 'up': ctrl.send({ c: 'upgrade', id: tower.id }); break;
|
||||
case 'sell': ctrl.send({ c: 'sell', id: tower.id }); app.selTower = 0; renderInfo(true); app.previewDirty = true; break;
|
||||
case 'mode': {
|
||||
const modes = TD.TARGET_MODES; ctrl.send({ c: 'target', id: tower.id, mode: modes[(modes.indexOf(tower.mode) + 1) % modes.length] });
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
});
|
||||
|
||||
function renderWavePanel(view) {
|
||||
const n = view.wave + 1;
|
||||
const key = n + ':' + view.state;
|
||||
if (app.last.waveKey === key) return;
|
||||
app.last.waveKey = key;
|
||||
const box = $('nextwave');
|
||||
if (view.state !== 'playing') { box.textContent = ''; return; }
|
||||
const sum = TD.waveSummary(n);
|
||||
let html = '<div class="panel"><h4>Next · wave ' + n + '</h4><div class="wv">';
|
||||
let air = false;
|
||||
for (const g of sum) {
|
||||
const d = TD.ENEMIES[g.k];
|
||||
if (d.air) air = true;
|
||||
html += '<span class="e"><i style="background:' + d.color + '"></i>' + g.c + '× ' + d.name + '</span>';
|
||||
}
|
||||
if (air) html += '<span class="tag air">AIR</span>';
|
||||
if (n % 10 === 0) html += '<span class="tag boss">BOSS</span>';
|
||||
html += '</div></div>';
|
||||
box.innerHTML = html;
|
||||
}
|
||||
|
||||
function onPlayers(list) {
|
||||
const ctrl = app.ctrl;
|
||||
ui.names = {}; for (const p of list) ui.names[p.slot] = p.name;
|
||||
ui.coop = list.length > 1;
|
||||
// join / leave toasts
|
||||
if (app.prevPlayers) {
|
||||
for (const p of list) if (!app.prevPlayers.find((q) => q.pid === p.pid)) { toast(p.name + ' joined', 'good'); Audio.sfx('join'); }
|
||||
for (const q of app.prevPlayers) if (!list.find((p) => p.pid === q.pid)) toast(q.name + ' left');
|
||||
for (const p of list) { const q = app.prevPlayers.find((x) => x.pid === p.pid); if (q && q.online && !p.online) toast(p.name + ' lost connection'); if (q && !q.online && p.online) toast(p.name + ' is back', 'good'); }
|
||||
}
|
||||
app.prevPlayers = list.map((p) => Object.assign({}, p));
|
||||
renderPlayers();
|
||||
if (ctrl.kind === 'remote') renderInfo(true);
|
||||
}
|
||||
function renderPlayers() {
|
||||
const ctrl = app.ctrl, box = $('players');
|
||||
if (!ctrl || ctrl.kind !== 'remote') { box.hidden = true; return; }
|
||||
box.hidden = false;
|
||||
let html = '<div class="panel"><h4>Room ' + (ctrl.room || '') + '</h4>';
|
||||
for (const p of ctrl.players) {
|
||||
html += '<div class="pl"><span class="dot" style="background:' + NW.SLOT_COLORS[p.slot] + '"></span><span class="pn"></span>' +
|
||||
(ctrl.you && p.pid === ctrl.you.pid ? '<span class="you">(you)</span>' : '') + (p.host ? '<span class="you">host</span>' : '') + (p.online ? '' : '<span class="off">offline</span>') + '</div>';
|
||||
}
|
||||
if (ctrl.players.length < 2) html += '<div class="muted small">Waiting for a partner… share the invite link.</div>';
|
||||
html += '<div class="actions"><button type="button" data-act="invite"><svg class="ic"><use href="#i-share"/></svg>Invite</button><button type="button" data-act="leave" class="danger">Leave</button></div></div>';
|
||||
box.innerHTML = html;
|
||||
const names = box.querySelectorAll('.pn');
|
||||
ctrl.players.forEach((p, i) => { names[i].textContent = p.name; });
|
||||
}
|
||||
$('players').addEventListener('click', (e) => {
|
||||
const b = e.target.closest('button[data-act]'); if (!b) return;
|
||||
if (b.dataset.act === 'invite') invite();
|
||||
if (b.dataset.act === 'leave') { leaveToMenu(); }
|
||||
});
|
||||
function inviteUrl() { return root.location.origin + root.location.pathname + '?room=' + app.ctrl.room; }
|
||||
function invite() {
|
||||
const url = inviteUrl(), text = 'Join my Netwall game (room ' + app.ctrl.room + ')';
|
||||
if (root.navigator.share) { root.navigator.share({ title: 'Netwall', text, url }).catch(() => {}); return; }
|
||||
const done = () => toast('Invite link copied', 'good');
|
||||
if (root.navigator.clipboard && root.navigator.clipboard.writeText) root.navigator.clipboard.writeText(url).then(done, () => root.prompt('Copy this link', url));
|
||||
else root.prompt('Copy this link', url);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ HUD
|
||||
function updateHud(view) {
|
||||
const L = app.last, ctrl = app.ctrl;
|
||||
if (L.gold !== view.gold) { L.gold = view.gold; $('vGold').textContent = String(view.gold); }
|
||||
if (L.lives !== view.lives) {
|
||||
L.lives = view.lives; $('vLives').textContent = String(view.lives);
|
||||
$('statLives').classList.toggle('low', view.maxLives > 0 && view.lives <= view.maxLives * 0.25);
|
||||
}
|
||||
if (L.wave !== view.wave) { L.wave = view.wave; $('vWave').textContent = String(view.wave); }
|
||||
if (L.winWave !== view.winWave) { L.winWave = view.winWave; $('vWaveMax').textContent = view.winWave ? '/' + view.winWave : ''; }
|
||||
const idle = view.queued === 0 && view.monsters.length === 0;
|
||||
const timer = view.auto && view.nextWaveIn >= 0 ? ' · ' + Math.ceil(view.nextWaveIn) + 's' : '';
|
||||
const wtxt = 'Wave ' + (view.wave + 1) + timer;
|
||||
if (L.wtxt !== wtxt) { L.wtxt = wtxt; $('btnWaveText').textContent = wtxt; }
|
||||
const wdis = view.state !== 'playing';
|
||||
if (L.wdis !== wdis) { L.wdis = wdis; $('btnWave').disabled = wdis; }
|
||||
const attn = idle && view.wave === 0 && view.state === 'playing';
|
||||
if (L.attn !== attn) { L.attn = attn; $('btnWave').classList.toggle('attn', attn); }
|
||||
if (L.auto !== view.auto) { L.auto = view.auto; $('btnAuto').setAttribute('aria-pressed', view.auto ? 'true' : 'false'); }
|
||||
if (L.speed !== view.speed) { L.speed = view.speed; $('speedText').textContent = view.speed + '×'; }
|
||||
if (L.paused !== view.paused) { L.paused = view.paused; $('btnPause').innerHTML = '<svg class="ic"><use href="#i-' + (view.paused ? 'play' : 'pause') + '"/></svg>'; $('btnPause').setAttribute('aria-label', view.paused ? 'Resume' : 'Pause'); }
|
||||
if (L.muted !== Audio.muted) { L.muted = Audio.muted; $('btnSound').innerHTML = '<svg class="ic"><use href="#i-' + (Audio.muted ? 'mute' : 'sound') + '"/></svg>'; }
|
||||
// palette affordability
|
||||
const gold = view.gold;
|
||||
if (L.palGold !== gold) {
|
||||
L.palGold = gold;
|
||||
for (const b of $('palette').children) b.classList.toggle('poor', gold < TD.TOWERS[b.dataset.type].levels[0].cost);
|
||||
}
|
||||
if (ctrl.kind === 'remote') {
|
||||
const chip = $('netChip');
|
||||
chip.hidden = false;
|
||||
$('netRoom').textContent = ctrl.room || '';
|
||||
const p = ctrl.rtt ? ctrl.rtt + ' ms' : '';
|
||||
if (L.ping !== p) { L.ping = p; $('netPing').textContent = p; chip.classList.toggle('bad', ctrl.rtt > 220); }
|
||||
}
|
||||
renderWavePanel(view);
|
||||
updateInfoDynamic();
|
||||
}
|
||||
|
||||
function endScreen(view) {
|
||||
const ctrl = app.ctrl;
|
||||
const won = view.state === 'won';
|
||||
$('endTitle').textContent = won ? 'Server secured!' : 'Breach!';
|
||||
$('endTitle').style.color = won ? 'var(--green)' : 'var(--red)';
|
||||
const best = store.get('nw.best.' + ctrl.board.mapId, 0);
|
||||
if (!won && view.wave > best) store.set('nw.best.' + ctrl.board.mapId, view.wave);
|
||||
$('endText').textContent = won ? 'You held the line through wave ' + view.wave + '. Every packet was filtered.' : 'The server fell on wave ' + view.wave + '.';
|
||||
const walls = view.towers.filter((t) => t.type === 'wall').length;
|
||||
const rows = [['Wave', view.wave], ['Packets killed', view.kills], ['Turrets', view.towers.length - walls], ['Firewalls', walls], ['Integrity left', view.lives], ['Best (map)', Math.max(best, view.wave)]];
|
||||
$('endStats').innerHTML = rows.map((r) => '<div><span>' + r[0] + '</span><b>' + r[1] + '</b></div>').join('');
|
||||
const remoteGuest = ctrl.kind === 'remote' && !(ctrl.you && ctrl.you.host);
|
||||
$('btnAgain').hidden = remoteGuest; $('endWait').hidden = !remoteGuest;
|
||||
$('btnContinue').hidden = !won;
|
||||
showOverlay('end');
|
||||
Audio.music(null); Audio.stinger(won ? 'win' : 'lose');
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ placement + previews
|
||||
function cellFromEvent(e) {
|
||||
const r = canvas.getBoundingClientRect();
|
||||
return renderer.screenToCell(e.clientX - r.left, e.clientY - r.top);
|
||||
}
|
||||
function placeAt(cell) {
|
||||
const ctrl = app.ctrl;
|
||||
if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) return false;
|
||||
const cost = TD.TOWERS[app.selType].levels[0].cost;
|
||||
if (ctrl.view.gold < cost) { onReject({ reason: 'gold' }); return false; }
|
||||
ctrl.send({ c: 'place', type: app.selType, x: cell.x, y: cell.y });
|
||||
app.previewDirty = true;
|
||||
return true;
|
||||
}
|
||||
function refreshPreview(force) {
|
||||
const ctrl = app.ctrl, now = performance.now();
|
||||
const cell = app.pending || app.hover;
|
||||
if (cell && app.selType && ui.noGhost) { if (ui.preview || !$('hint').hidden) { ui.preview = null; ui.valid = true; hint(null); } return; }
|
||||
if (!app.selType || !cell || !ctrl.board.inBounds(cell.x, cell.y)) {
|
||||
if (ui.preview || !$('hint').hidden) { ui.preview = null; ui.valid = true; hint(null); }
|
||||
return;
|
||||
}
|
||||
if (!force && !app.previewDirty && now - app.lastPreviewAt < 250) return;
|
||||
app.previewDirty = false; app.lastPreviewAt = now;
|
||||
const pv = ctrl.preview(cell.x, cell.y, true);
|
||||
const cost = TD.TOWERS[app.selType].levels[0].cost;
|
||||
const poor = ctrl.view.gold < cost;
|
||||
ui.preview = pv; ui.valid = pv.ok && !poor;
|
||||
if (!pv.ok) hint('✕ ' + (REASONS[pv.reason] || pv.reason), 'bad');
|
||||
else if (poor) hint('Need ' + cost + ' credits (have ' + ctrl.view.gold + ')', 'bad');
|
||||
else {
|
||||
const d = Math.round(pv.after - pv.before) / 1;
|
||||
const a = Math.round(pv.before / (ui.spawns || 1)), b = Math.round(pv.after / (ui.spawns || 1));
|
||||
hint(b === a ? 'Route ' + a : 'Route ' + a + ' → ' + b + (b > a ? ' (+' + (b - a) + ')' : ' (' + (b - a) + ')'), d > 0.5 ? 'ok' : 'info');
|
||||
}
|
||||
}
|
||||
|
||||
// touch placement bar
|
||||
function updateConfirm() {
|
||||
const show = !!(app.pending && app.selType && app.selType !== 'wall');
|
||||
$('confirm').hidden = !show;
|
||||
if (show) {
|
||||
$('confirmText').textContent = 'Build · ' + TD.TOWERS[app.selType].levels[0].cost;
|
||||
// keep the bar clear of the cell being placed: show it on the opposite half of the stage
|
||||
const p = renderer.cellToScreen(app.pending.x, app.pending.y);
|
||||
$('confirm').classList.toggle('top', p.y > $('stage').clientHeight * 0.5);
|
||||
}
|
||||
}
|
||||
$('btnConfirmBuild').addEventListener('click', () => { if (app.pending && placeAt(app.pending)) { app.pending = null; updateConfirm(); } });
|
||||
$('btnCancelBuild').addEventListener('click', () => { selectType(null); });
|
||||
|
||||
// ------------------------------------------------------------------ pointer input
|
||||
const ptrs = new Map();
|
||||
let painting = false, paintCell = null, panning = false, longT = 0, longFired = false, rightDown = null, prevPending = null, pinch = null;
|
||||
|
||||
function cancelLong() { clearTimeout(longT); longT = 0; }
|
||||
function setHover(cell) {
|
||||
const c = cell && app.ctrl.board.inBounds(cell.x, cell.y) ? { x: cell.x, y: cell.y } : null;
|
||||
if (!c && !app.hover) return;
|
||||
if (c && app.hover && c.x === app.hover.x && c.y === app.hover.y) return;
|
||||
app.hover = c; app.previewDirty = true;
|
||||
}
|
||||
function paintLine(from, to) { // place on every cell crossed by a fast drag (Bresenham)
|
||||
let x0 = from.x, y0 = from.y; const x1 = to.x, y1 = to.y;
|
||||
const dx = Math.abs(x1 - x0), dy = -Math.abs(y1 - y0), sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1;
|
||||
let err = dx + dy;
|
||||
for (let guard = 0; guard < 80; guard++) {
|
||||
if (x0 !== from.x || y0 !== from.y) placeAt({ x: x0, y: y0 });
|
||||
if (x0 === x1 && y0 === y1) break;
|
||||
const e2 = 2 * err;
|
||||
if (e2 >= dy) { err += dy; x0 += sx; }
|
||||
if (e2 <= dx) { err += dx; y0 += sy; }
|
||||
}
|
||||
}
|
||||
function markAt(cell) {
|
||||
if (!cell || !app.ctrl.board.inBounds(cell.x, cell.y)) return;
|
||||
app.ctrl.sendMark(cell.x, cell.y);
|
||||
if (navigator.vibrate) try { navigator.vibrate(15); } catch (e) { /* ignore */ }
|
||||
}
|
||||
function towerAtCell(cell) {
|
||||
return app.ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y) || null;
|
||||
}
|
||||
function tapSelect(cell) {
|
||||
const ctrl = app.ctrl;
|
||||
if (!ctrl.board.inBounds(cell.x, cell.y)) { selectTower(0); return; }
|
||||
const t = ctrl.view.towers.find((x) => x.x === cell.x && x.y === cell.y);
|
||||
if (t) { selectTower(t.id); Audio.sfx('click'); } else selectTower(0);
|
||||
}
|
||||
|
||||
canvas.addEventListener('contextmenu', (e) => e.preventDefault());
|
||||
canvas.addEventListener('pointerdown', (e) => {
|
||||
if (!app.inGame) return;
|
||||
e.preventDefault();
|
||||
try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ }
|
||||
Audio.unlock();
|
||||
const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top;
|
||||
ptrs.set(e.pointerId, { x: sx, y: sy, sx, sy, type: e.pointerType, moved: false, btn: e.button });
|
||||
if (ptrs.size === 2) { // second finger: pinch/pan, abandon whatever the first finger started
|
||||
cancelLong(); painting = false; tapSelectOnUp = false;
|
||||
const [a, b] = [...ptrs.values()];
|
||||
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y) || 1, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
|
||||
return;
|
||||
}
|
||||
if (ptrs.size > 2) return;
|
||||
const cell = renderer.screenToCell(sx, sy);
|
||||
longFired = false;
|
||||
if (e.pointerType === 'mouse') {
|
||||
if (e.button === 2) { rightDown = { x: sx, y: sy, moved: false }; return; }
|
||||
if (e.button === 1) { panning = true; return; }
|
||||
if (e.altKey) { markAt(cell); return; }
|
||||
const ex = towerAtCell(cell);
|
||||
if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) { selectTower(ex.id); Audio.sfx('click'); }
|
||||
else if (app.selType) {
|
||||
setHover(cell);
|
||||
if (!ex) placeAt(cell);
|
||||
if (app.selType === 'wall') { painting = true; paintCell = cell; }
|
||||
} else {
|
||||
tapSelectOnUp = true; panning = renderer.zoom > 1.01;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// touch / pen
|
||||
prevPending = app.pending ? { x: app.pending.x, y: app.pending.y } : null;
|
||||
const ex = towerAtCell(cell);
|
||||
if (app.selType && ex && !(app.selType === 'wall' && ex.type === 'wall')) {
|
||||
selectTower(ex.id); Audio.sfx('click');
|
||||
} else if (app.selType === 'wall') {
|
||||
setHover(cell); if (!ex) placeAt(cell); painting = true; paintCell = cell;
|
||||
} else if (app.selType) {
|
||||
app.pending = { x: cell.x, y: cell.y }; setHover(cell); updateConfirm();
|
||||
} else {
|
||||
tapSelectOnUp = true;
|
||||
longT = setTimeout(() => { longFired = true; tapSelectOnUp = false; markAt(cell); }, 520);
|
||||
}
|
||||
});
|
||||
let tapSelectOnUp = false;
|
||||
|
||||
canvas.addEventListener('pointermove', (e) => {
|
||||
const r = canvas.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top;
|
||||
const p = ptrs.get(e.pointerId);
|
||||
if (!app.inGame) return;
|
||||
if (!p) { // hovering mouse
|
||||
if (e.pointerType === 'mouse') {
|
||||
const cell = renderer.screenToCell(sx, sy);
|
||||
setHover(cell);
|
||||
app.ctrl.sendCursor(cell.fx, cell.fy);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const dx = sx - p.x, dy = sy - p.y;
|
||||
p.x = sx; p.y = sy;
|
||||
if (Math.hypot(sx - p.sx, sy - p.sy) > 8) p.moved = true;
|
||||
if (ptrs.size === 2 && pinch) {
|
||||
const [a, b] = [...ptrs.values()];
|
||||
const d = Math.hypot(a.x - b.x, a.y - b.y) || 1, mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
|
||||
renderer.panBy(mx - pinch.mx, my - pinch.my);
|
||||
renderer.setZoom(renderer.zoom * d / pinch.d, mx, my);
|
||||
pinch.d = d; pinch.mx = mx; pinch.my = my;
|
||||
updateFit();
|
||||
return;
|
||||
}
|
||||
const cell = renderer.screenToCell(sx, sy);
|
||||
if (e.pointerType === 'mouse') {
|
||||
if (rightDown) { if (Math.hypot(sx - rightDown.x, sy - rightDown.y) > 5) rightDown.moved = true; if (rightDown.moved) { renderer.panBy(dx, dy); updateFit(); } rightDown.x = rightDown.moved ? sx : rightDown.x; return; }
|
||||
if (panning && p.moved) { renderer.panBy(dx, dy); updateFit(); tapSelectOnUp = false; return; }
|
||||
setHover(cell);
|
||||
app.ctrl.sendCursor(cell.fx, cell.fy);
|
||||
if (painting && app.selType === 'wall' && paintCell && (cell.x !== paintCell.x || cell.y !== paintCell.y)) { paintLine(paintCell, cell); paintCell = cell; }
|
||||
return;
|
||||
}
|
||||
// touch / pen
|
||||
if (p.moved) { cancelLong(); tapSelectOnUp = tapSelectOnUp && !p.moved; }
|
||||
if (painting && app.selType === 'wall') {
|
||||
setHover(cell);
|
||||
if (paintCell && (cell.x !== paintCell.x || cell.y !== paintCell.y)) { paintLine(paintCell, cell); paintCell = cell; }
|
||||
} else if (app.selType) {
|
||||
app.pending = { x: cell.x, y: cell.y }; setHover(cell); updateConfirm();
|
||||
app.ctrl.sendCursor(cell.fx, cell.fy);
|
||||
} else if (p.moved && renderer.zoom > 1.01) {
|
||||
renderer.panBy(dx, dy); updateFit();
|
||||
}
|
||||
});
|
||||
|
||||
function endPointer(e) {
|
||||
const p = ptrs.get(e.pointerId);
|
||||
ptrs.delete(e.pointerId);
|
||||
try { canvas.releasePointerCapture(e.pointerId); } catch (err) { /* ignore */ }
|
||||
if (!p || !app.inGame) return;
|
||||
cancelLong();
|
||||
if (ptrs.size < 2) pinch = null;
|
||||
const r = canvas.getBoundingClientRect(), cell = renderer.screenToCell(e.clientX - r.left, e.clientY - r.top);
|
||||
if (e.pointerType === 'mouse') {
|
||||
if (e.button === 2 && rightDown) { if (!rightDown.moved) { selectType(null); selectTower(0); } rightDown = null; return; }
|
||||
if (e.button === 1) { panning = false; return; }
|
||||
if (tapSelectOnUp && !p.moved && e.type === 'pointerup') tapSelect(cell);
|
||||
tapSelectOnUp = false; painting = false; panning = false;
|
||||
return;
|
||||
}
|
||||
if (e.type === 'pointercancel') { painting = false; tapSelectOnUp = false; return; }
|
||||
if (painting) { painting = false; return; }
|
||||
if (ptrs.size > 0) return; // lifted one finger of a pinch
|
||||
if (app.selType && app.pending && !p.moved && prevPending && prevPending.x === app.pending.x && prevPending.y === app.pending.y) {
|
||||
if (placeAt(app.pending)) { app.pending = null; updateConfirm(); } // tapping the previewed cell again builds
|
||||
} else if (!app.selType && tapSelectOnUp && !p.moved && !longFired) tapSelect(cell);
|
||||
tapSelectOnUp = false;
|
||||
}
|
||||
canvas.addEventListener('pointerup', endPointer);
|
||||
canvas.addEventListener('pointercancel', endPointer);
|
||||
canvas.addEventListener('pointerleave', (e) => { if (e.pointerType === 'mouse' && !ptrs.size) { app.hover = null; app.previewDirty = true; app.ctrl.sendCursor(null, null); } });
|
||||
canvas.addEventListener('wheel', (e) => {
|
||||
if (!app.inGame) return;
|
||||
e.preventDefault();
|
||||
const r = canvas.getBoundingClientRect();
|
||||
renderer.setZoom(renderer.zoom * (e.deltaY < 0 ? 1.15 : 1 / 1.15), e.clientX - r.left, e.clientY - r.top);
|
||||
updateFit();
|
||||
}, { passive: false });
|
||||
|
||||
function updateFit() {
|
||||
const z = renderer.zoom > 1.02;
|
||||
if (z !== app.zoomed) { app.zoomed = z; $('btnFit').hidden = !z; }
|
||||
}
|
||||
$('btnFit').addEventListener('click', () => { renderer.resetCamera(); updateFit(); });
|
||||
|
||||
// ------------------------------------------------------------------ keyboard
|
||||
root.addEventListener('keydown', (e) => {
|
||||
if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
|
||||
if (e.ctrlKey || e.metaKey) return;
|
||||
if (!app.inGame) return;
|
||||
if (document.querySelector('.overlay:not([hidden])')) { if (e.key === 'Escape') { closeOverlayToGame(); } return; }
|
||||
const ctrl = app.ctrl, view = ctrl.view;
|
||||
const k = e.key.toLowerCase();
|
||||
const idx = '123456'.indexOf(k);
|
||||
if (idx >= 0 && k.length === 1) { selectType(app.selType === TD.TOWER_ORDER[idx] ? null : TD.TOWER_ORDER[idx]); Audio.sfx('click'); e.preventDefault(); return; }
|
||||
switch (k) {
|
||||
case 'escape': case 'q': selectType(null); selectTower(0); app.pending = null; updateConfirm(); break;
|
||||
case ' ': case 'enter': ctrl.send({ c: 'wave' }); e.preventDefault(); break;
|
||||
case 'p': ctrl.ctl('pause', !view.paused); break;
|
||||
case 'f': ctrl.ctl('speed', view.speed % 3 + 1); break;
|
||||
case 'a': ctrl.send({ c: 'auto', v: !view.auto }); break;
|
||||
case 'm': Audio.toggleMuted(); break;
|
||||
case 'u': if (app.selTower) $('info').querySelector('[data-act="up"]') && $('info').querySelector('[data-act="up"]').click(); break;
|
||||
case 'x': case 'delete': case 'backspace': if (app.selTower) { $('info').querySelector('[data-act="sell"]') && $('info').querySelector('[data-act="sell"]').click(); e.preventDefault(); } break;
|
||||
case 't': if (app.selTower) $('info').querySelector('[data-act="mode"]') && $('info').querySelector('[data-act="mode"]').click(); break;
|
||||
case '?': case 'h': showOverlay('help'); break;
|
||||
default: break;
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('click', (e) => { const b = e.target.closest && e.target.closest('button'); if (b && e.detail > 0) b.blur(); });
|
||||
|
||||
// ------------------------------------------------------------------ top bar buttons
|
||||
$('btnWave').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.send({ c: 'wave' }); });
|
||||
$('btnAuto').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.send({ c: 'auto', v: !app.ctrl.view.auto }); });
|
||||
$('btnSpeed').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('speed', app.ctrl.view.speed % 3 + 1); });
|
||||
$('btnPause').addEventListener('click', () => { Audio.sfx('click'); app.ctrl.ctl('pause', !app.ctrl.view.paused); });
|
||||
$('btnSound').addEventListener('click', () => { Audio.unlock(); Audio.toggleMuted(); Audio.sfx('click'); });
|
||||
$('btnMenu').addEventListener('click', () => { Audio.sfx('click'); openMenu(); });
|
||||
|
||||
// ------------------------------------------------------------------ menu / lobby
|
||||
function buildMapPicker() {
|
||||
const box = $('mapPick'); box.textContent = '';
|
||||
for (const id of TD.MAP_ORDER) {
|
||||
const def = TD.MAPS[id];
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button'; b.className = 'mapcard'; b.dataset.map = id; b.setAttribute('role', 'radio');
|
||||
b.innerHTML = '<canvas width="208" height="128"></canvas><span class="nm"></span><span class="df">DIFFICULTY <b></b></span>';
|
||||
b.querySelector('.nm').textContent = def.name;
|
||||
b.querySelector('.df b').textContent = '●'.repeat(def.difficulty) + '○'.repeat(3 - def.difficulty);
|
||||
drawMapPreview(b.querySelector('canvas'), def);
|
||||
b.addEventListener('click', () => { Audio.sfx('click'); chooseMap(id); });
|
||||
box.appendChild(b);
|
||||
}
|
||||
chooseMap(app.mapId, true);
|
||||
}
|
||||
function drawMapPreview(cv, def) {
|
||||
const p = TD.parseMap(def), ctx = cv.getContext('2d'), w = cv.width / p.cols, h = cv.height / p.rows;
|
||||
ctx.fillStyle = '#09101f'; ctx.fillRect(0, 0, cv.width, cv.height);
|
||||
ctx.fillStyle = '#26304f';
|
||||
for (let y = 0; y < p.rows; y++) for (let x = 0; x < p.cols; x++) if (p.obst[y * p.cols + x]) ctx.fillRect(x * w + 1, y * h + 1, w - 2, h - 2);
|
||||
ctx.fillStyle = '#ff5c7a'; for (const s of p.spawns) { ctx.beginPath(); ctx.arc((s.x + 0.5) * w, (s.y + 0.5) * h, h * 0.6, 0, Math.PI * 2); ctx.fill(); }
|
||||
ctx.fillStyle = '#4de3ff'; ctx.fillRect(p.core.x * w - 2, p.core.y * h - 2, w + 4, h + 4);
|
||||
}
|
||||
function chooseMap(id, silent) {
|
||||
app.mapId = id; store.set('nw.map', id);
|
||||
for (const b of $('mapPick').children) b.setAttribute('aria-checked', b.dataset.map === id ? 'true' : 'false');
|
||||
$('mapDesc').textContent = TD.MAPS[id].desc;
|
||||
$('lobbyMapName').textContent = 'Map: ' + TD.MAPS[id].name;
|
||||
if (!silent && !app.inGame) previewMap(id);
|
||||
}
|
||||
|
||||
function openMenu() {
|
||||
if (app.inGame && app.ctrl.kind === 'local') app.ctrl.ctl('pause', true);
|
||||
setScreen(app.inGame ? 'playing' : 'menu');
|
||||
$('btnCloseMenu').hidden = !app.inGame;
|
||||
$('btnSolo').lastChild.textContent = app.inGame ? 'New solo game' : 'Play solo';
|
||||
showOverlay('menu');
|
||||
if (!app.inGame) Audio.music('theme');
|
||||
updateResumeButton();
|
||||
}
|
||||
function closeOverlayToGame() {
|
||||
if (!app.inGame) return;
|
||||
showOverlay(null);
|
||||
if (app.ctrl.kind === 'local' && app.ctrl.view.paused) app.ctrl.ctl('pause', false);
|
||||
}
|
||||
function leaveToMenu() {
|
||||
leaveRemote(true);
|
||||
app.prevPlayers = null;
|
||||
app.inGame = false;
|
||||
$('reconnect').hidden = true; $('players').hidden = true; $('netChip').hidden = true;
|
||||
previewMap(app.mapId);
|
||||
setScreen('menu'); openMenu();
|
||||
}
|
||||
|
||||
$('btnSolo').addEventListener('click', () => { Audio.unlock(); startSolo(app.mapId); });
|
||||
$('btnCloseMenu').addEventListener('click', closeOverlayToGame);
|
||||
$('btnHelp').addEventListener('click', () => showOverlay('help'));
|
||||
$('btnHelpClose').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else showOverlay('menu'); });
|
||||
$('btnFullscreen').addEventListener('click', () => {
|
||||
const d = document, el = d.documentElement;
|
||||
if (d.fullscreenElement) d.exitFullscreen(); else if (el.requestFullscreen) el.requestFullscreen().catch(() => {});
|
||||
});
|
||||
if (!document.documentElement.requestFullscreen || (root.matchMedia && root.matchMedia('(display-mode: standalone)').matches)) $('btnFullscreen').hidden = true; else $('btnFullscreen').hidden = false;
|
||||
|
||||
$('btnAgain').addEventListener('click', () => {
|
||||
Audio.sfx('click');
|
||||
if (app.ctrl.kind === 'local') { app.ctrl.newGame(app.ctrl.mapId); Audio.music('battle'); }
|
||||
else { app.ctrl.newGame(app.ctrl.board.mapId); }
|
||||
});
|
||||
$('btnContinue').addEventListener('click', () => { app.ctrl.send({ c: 'continue' }); $('end').hidden = true; app.endShown = false; Audio.music('battle'); });
|
||||
$('btnEndMenu').addEventListener('click', () => { if (app.ctrl.kind === 'remote') leaveToMenu(); else { app.inGame = false; previewMap(app.mapId); setScreen('menu'); openMenu(); } });
|
||||
|
||||
// lobby
|
||||
function lobbyMsg(text, bad) { const m = $('lobbyMsg'); m.textContent = text || ''; m.className = 'msg' + (bad ? ' bad' : ''); }
|
||||
function openLobby(code) {
|
||||
showOverlay('lobby'); setScreen(app.inGame ? 'playing' : 'menu');
|
||||
$('inName').value = store.get('nw.name', '') || '';
|
||||
if (code) $('inCode').value = code;
|
||||
lobbyMsg(root.location.protocol === 'file:' ? 'Co-op needs the Netwall server: run "npm start" and open its address (the page is currently opened as a file).' : '', root.location.protocol === 'file:');
|
||||
}
|
||||
$('btnCoop').addEventListener('click', () => { Audio.unlock(); openLobby(); });
|
||||
$('btnLobbyBack').addEventListener('click', () => { if (app.inGame) closeOverlayToGame(); else openMenu(); });
|
||||
$('inCode').addEventListener('input', (e) => { e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 4); });
|
||||
$('btnCreate').addEventListener('click', () => connectRemote({ room: null, map: app.mapId }));
|
||||
$('btnJoin').addEventListener('click', () => {
|
||||
const code = $('inCode').value.trim().toUpperCase();
|
||||
if (!/^[A-Z0-9]{4}$/.test(code)) { lobbyMsg('Enter the 4 character room code.', true); return; }
|
||||
connectRemote({ room: code });
|
||||
});
|
||||
$('inCode').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('btnJoin').click(); });
|
||||
|
||||
function connectRemote(opts) {
|
||||
if (root.location.protocol === 'file:') { lobbyMsg('Open the game through the Netwall server to play online.', true); return; }
|
||||
const name = ($('inName').value || store.get('nw.name', '') || '').trim().slice(0, 16) || 'Player';
|
||||
store.set('nw.name', name);
|
||||
if (app.ctrl && app.ctrl.kind === 'remote') app.ctrl.close();
|
||||
lobbyMsg('Connecting…');
|
||||
const rc = new NW.RemoteController({ pid: getPid(), name, room: opts.room, map: opts.map });
|
||||
let first = true;
|
||||
rc.on('joined', () => {
|
||||
sess.set('nw.room', rc.room); store.set('nw.session', { pid: getPid(), room: rc.room, name, ts: Date.now() });
|
||||
$('reconnect').hidden = true;
|
||||
if (first) {
|
||||
first = false;
|
||||
useController(rc);
|
||||
app.inGame = true; app.started = true; app.last = {}; app.endShown = false; app.prevPlayers = null;
|
||||
resetSelection(); setScreen('playing'); showOverlay(null);
|
||||
onPlayers(rc.players);
|
||||
try { root.history.replaceState(null, '', root.location.pathname + '?room=' + rc.room); } catch (e) { /* ignore */ }
|
||||
toast('Room ' + rc.room + (rc.players.length < 2 ? '. Send the invite link to your partner!' : ''), 'good');
|
||||
Audio.music('battle'); requestWakeLock();
|
||||
} else { toast('Reconnected', 'good'); adoptBoard(); }
|
||||
lobbyMsg('');
|
||||
});
|
||||
rc.on('status', (s) => { if (app.ctrl === rc && app.inGame) $('reconnect').hidden = s !== 'reconnecting'; });
|
||||
rc.on('fatal', (f) => {
|
||||
sess.del('nw.room'); store.del('nw.session');
|
||||
if (app.ctrl === rc && app.inGame) { toast(f.msg, 'bad'); leaveToMenu(); openLobby(); lobbyMsg(f.msg, true); }
|
||||
else lobbyMsg(f.msg, true);
|
||||
});
|
||||
rc.connect();
|
||||
}
|
||||
|
||||
function updateResumeButton() {
|
||||
const s = store.get('nw.session', null), b = $('btnResume');
|
||||
const fresh = s && s.room && Date.now() - s.ts < 15 * 60 * 1000 && !(app.ctrl && app.ctrl.kind === 'remote');
|
||||
b.hidden = !fresh || root.location.protocol === 'file:';
|
||||
if (fresh) b.textContent = 'Resume co-op game · room ' + s.room;
|
||||
}
|
||||
$('btnResume').addEventListener('click', () => {
|
||||
const s = store.get('nw.session', null); if (!s) return;
|
||||
sess.set('nw.pid', s.pid);
|
||||
$('inName').value = s.name || '';
|
||||
connectRemote({ room: s.room });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ misc platform bits
|
||||
let wakeLock = null;
|
||||
function requestWakeLock() {
|
||||
try { if (navigator.wakeLock && !wakeLock) navigator.wakeLock.request('screen').then((l) => { wakeLock = l; l.addEventListener('release', () => { wakeLock = null; }); }).catch(() => {}); } catch (e) { /* ignore */ }
|
||||
}
|
||||
document.addEventListener('visibilitychange', () => { if (!document.hidden && app.inGame) requestWakeLock(); });
|
||||
|
||||
function resizeCanvas() {
|
||||
const st = $('stage'), r = st.getBoundingClientRect();
|
||||
renderer.setRotation(r.height > r.width * 1.05); // portrait: draw the board turned 90 degrees (bigger cells)
|
||||
const dpr = Math.min(root.devicePixelRatio || 1, root.matchMedia && root.matchMedia('(pointer: coarse)').matches ? 2 : 2.5);
|
||||
renderer.resize(r.width, r.height, dpr);
|
||||
}
|
||||
if (root.ResizeObserver) new ResizeObserver(resizeCanvas).observe($('stage')); else root.addEventListener('resize', resizeCanvas);
|
||||
root.addEventListener('orientationchange', () => setTimeout(() => { resizeCanvas(); drawPaletteIcons(); }, 250));
|
||||
// keep the page from scrolling/bouncing or zooming on iOS
|
||||
document.addEventListener('gesturestart', (e) => e.preventDefault());
|
||||
document.addEventListener('touchmove', (e) => { if (e.target === canvas || e.target.closest('#stage')) e.preventDefault(); }, { passive: false });
|
||||
|
||||
// ------------------------------------------------------------------ main loop
|
||||
function frame(now) {
|
||||
root.requestAnimationFrame(frame);
|
||||
const ctrl = app.ctrl; if (!ctrl) return;
|
||||
ctrl.update(now);
|
||||
const view = ctrl.view;
|
||||
if (app.inGame) {
|
||||
if (app.last.state !== view.state) {
|
||||
app.last.state = view.state;
|
||||
if (view.state === 'won' || view.state === 'lost') { if (!app.endShown) { app.endShown = true; endScreen(view); } }
|
||||
else if (app.endShown) { app.endShown = false; $('end').hidden = true; }
|
||||
}
|
||||
if (app.selTower && !view.towers.some((t) => t.id === app.selTower)) { app.selTower = 0; renderInfo(true); }
|
||||
if (app.last.rev !== view.rev) { app.last.rev = view.rev; app.previewDirty = true; if (app.selTower) renderInfo(true); }
|
||||
updateHud(view);
|
||||
if (now - app.lastBossCheck > 600 && view.state === 'playing') {
|
||||
app.lastBossCheck = now;
|
||||
const boss = view.monsters.some((m) => m.kind === 'rootkit');
|
||||
if (boss !== app.bossMusic) { app.bossMusic = boss; if (!app.endShown) Audio.music(boss ? 'boss' : 'battle'); }
|
||||
}
|
||||
}
|
||||
ui.hover = app.pending || app.hover; ui.selType = app.selType; ui.selTower = app.selTower;
|
||||
// hovering an existing tower while a build type is active: a click selects it, so show no ghost
|
||||
ui.noGhost = !!(ui.hover && app.selType && view.towers.some((t) => t.x === ui.hover.x && t.y === ui.hover.y));
|
||||
refreshPreview(false);
|
||||
renderer.frame(now, view, ui);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ boot
|
||||
function boot() {
|
||||
buildPalette(); buildMapPicker();
|
||||
previewMap(app.mapId);
|
||||
setScreen('menu'); showOverlay('menu');
|
||||
$('btnCloseMenu').hidden = true;
|
||||
resizeCanvas(); drawPaletteIcons();
|
||||
root.requestAnimationFrame(frame);
|
||||
|
||||
const q = new URLSearchParams(root.location.search), codeParam = (q.get('room') || '').toUpperCase();
|
||||
const savedRoom = sess.get('nw.room');
|
||||
if (savedRoom && /^[A-Z0-9]{4}$/.test(savedRoom) && root.location.protocol !== 'file:' && (!codeParam || codeParam === savedRoom)) {
|
||||
// page reload in the same tab: slip straight back into the room
|
||||
$('inName').value = store.get('nw.name', '') || '';
|
||||
connectRemote({ room: savedRoom });
|
||||
} else if (/^[A-Z0-9]{4}$/.test(codeParam)) {
|
||||
openLobby(codeParam);
|
||||
lobbyMsg('Enter your name and press Join.');
|
||||
} else {
|
||||
updateResumeButton();
|
||||
Audio.music('theme');
|
||||
}
|
||||
if (root.navigator.serviceWorker && root.location.protocol.startsWith('http')) { /* reserved for offline support */ }
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
|
||||
|
||||
NW.app = app; // handy for debugging and automated tests
|
||||
})(typeof self !== 'undefined' ? self : this);
|
||||
609
public/js/render.js
Normal file
609
public/js/render.js
Normal file
|
|
@ -0,0 +1,609 @@
|
|||
/*
|
||||
* NETWALL renderer: canvas 2D, world units = 40 px per cell, camera (zoom + pan) maps world -> CSS px.
|
||||
* No shadowBlur / per-frame gradients so it stays smooth on phones.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const NW = root.NW = root.NW || {};
|
||||
const TD = root.TD;
|
||||
const C = 40; // world px per cell
|
||||
const TAU = Math.PI * 2;
|
||||
const SLOT_COLORS = ['#4de3ff', '#ffd24d'];
|
||||
const BG = '#050810', BOARD = '#09101f';
|
||||
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
|
||||
const lerpAngle = (a, b, k) => { let d = ((b - a + Math.PI * 3) % TAU) - Math.PI; return a + d * k; };
|
||||
|
||||
function rr(ctx, x, y, w, h, r) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y);
|
||||
ctx.arcTo(x + w, y, x + w, y + h, r);
|
||||
ctx.arcTo(x + w, y + h, x, y + h, r);
|
||||
ctx.arcTo(x, y + h, x, y, r);
|
||||
ctx.arcTo(x, y, x + w, y, r);
|
||||
ctx.closePath();
|
||||
}
|
||||
function poly(ctx, n, r, rot) {
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < n; i++) {
|
||||
const a = rot + (i / n) * TAU;
|
||||
i ? ctx.lineTo(Math.cos(a) * r, Math.sin(a) * r) : ctx.moveTo(Math.cos(a) * r, Math.sin(a) * r);
|
||||
}
|
||||
ctx.closePath();
|
||||
}
|
||||
function rgba(hex, a) {
|
||||
const n = parseInt(hex.slice(1), 16);
|
||||
return 'rgba(' + (n >> 16) + ',' + ((n >> 8) & 255) + ',' + (n & 255) + ',' + a + ')';
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tower glyphs (also used for UI icons)
|
||||
// S = tile size, (cx,cy) = centre, ang = barrel angle (radians), t = seconds (animation)
|
||||
function drawGlyph(ctx, type, level, cx, cy, S, ang, t, alpha, rot) {
|
||||
const def = TD.TOWERS[type]; if (!def) return;
|
||||
const col = def.color;
|
||||
ctx.save();
|
||||
ctx.globalAlpha *= alpha === undefined ? 1 : alpha;
|
||||
ctx.translate(cx, cy);
|
||||
if (rot) { ctx.rotate(-rot); ang = (ang || 0) + rot; } // board is drawn rotated: keep glyphs upright
|
||||
const h = S * 0.43;
|
||||
if (type === 'wall') {
|
||||
ctx.fillStyle = '#10305f'; rr(ctx, -h * 0.92, -h * 0.92, h * 1.84, h * 1.84, S * 0.09); ctx.fill();
|
||||
ctx.lineWidth = S * 0.05; ctx.strokeStyle = col; ctx.stroke();
|
||||
ctx.fillStyle = 'rgba(90,169,255,.28)';
|
||||
ctx.fillRect(-h * 0.55, -h * 0.55, h * 1.1, h * 0.5);
|
||||
ctx.fillRect(-h * 0.55, h * 0.05, h * 0.5, h * 0.5);
|
||||
ctx.fillRect(h * 0.05, h * 0.05, h * 0.5, h * 0.5);
|
||||
ctx.restore(); return;
|
||||
}
|
||||
ctx.fillStyle = '#0c1426'; rr(ctx, -h, -h, h * 2, h * 2, S * 0.12); ctx.fill();
|
||||
ctx.lineWidth = S * (level >= 3 ? 0.075 : 0.05); ctx.strokeStyle = col; ctx.stroke();
|
||||
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
|
||||
switch (type) {
|
||||
case 'filter':
|
||||
ctx.fillStyle = rgba(col, 0.22); ctx.beginPath(); ctx.arc(0, 0, S * 0.2, 0, TAU); ctx.fill();
|
||||
ctx.lineWidth = S * 0.04; ctx.stroke();
|
||||
ctx.save(); ctx.rotate(ang); ctx.fillStyle = col; ctx.fillRect(0, -S * 0.05, S * 0.34, S * 0.1); ctx.restore();
|
||||
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, S * 0.07, 0, TAU); ctx.fill();
|
||||
break;
|
||||
case 'ids':
|
||||
ctx.lineWidth = S * 0.035;
|
||||
ctx.beginPath(); ctx.arc(0, 0, S * 0.19, 0, TAU); ctx.stroke();
|
||||
ctx.save(); ctx.rotate(ang);
|
||||
ctx.fillStyle = col; ctx.fillRect(0, -S * 0.03, S * 0.46, S * 0.06);
|
||||
ctx.fillRect(S * 0.36, -S * 0.07, S * 0.05, S * 0.14);
|
||||
ctx.restore();
|
||||
ctx.beginPath(); ctx.moveTo(-S * 0.26, 0); ctx.lineTo(-S * 0.12, 0); ctx.moveTo(0, -S * 0.26); ctx.lineTo(0, -S * 0.12); ctx.moveTo(0, S * 0.26); ctx.lineTo(0, S * 0.12); ctx.stroke();
|
||||
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, S * 0.05, 0, TAU); ctx.fill();
|
||||
break;
|
||||
case 'mortar':
|
||||
ctx.fillStyle = rgba(col, 0.25); ctx.beginPath(); ctx.arc(0, 0, S * 0.22, 0, TAU); ctx.fill();
|
||||
ctx.lineWidth = S * 0.04; ctx.stroke();
|
||||
ctx.save(); ctx.rotate(ang); ctx.fillStyle = col; rr(ctx, -S * 0.02, -S * 0.1, S * 0.3, S * 0.2, S * 0.04); ctx.fill(); ctx.restore();
|
||||
ctx.fillStyle = '#0c1426'; ctx.beginPath(); ctx.arc(0, 0, S * 0.08, 0, TAU); ctx.fill();
|
||||
break;
|
||||
case 'throttle': {
|
||||
const pulse = ((t * 0.9) % 1);
|
||||
ctx.lineWidth = S * 0.04;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const r = S * (0.08 + 0.085 * i) + (i === 2 ? pulse * S * 0.05 : 0);
|
||||
ctx.strokeStyle = rgba(col, 1 - i * 0.28 - (i === 2 ? pulse * 0.3 : 0));
|
||||
ctx.beginPath(); ctx.arc(0, 0, r, -2.3, -0.84); ctx.stroke();
|
||||
ctx.beginPath(); ctx.arc(0, 0, r, 0.84, 2.3); ctx.stroke();
|
||||
}
|
||||
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, S * 0.05, 0, TAU); ctx.fill();
|
||||
ctx.strokeStyle = col;
|
||||
break;
|
||||
}
|
||||
case 'arc':
|
||||
ctx.fillStyle = col;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(-S * 0.03, -S * 0.26); ctx.lineTo(-S * 0.14, S * 0.02); ctx.lineTo(-S * 0.01, S * 0.02);
|
||||
ctx.lineTo(-S * 0.07, S * 0.27); ctx.lineTo(S * 0.15, -S * 0.07); ctx.lineTo(S * 0.02, -S * 0.07); ctx.lineTo(S * 0.11, -S * 0.26);
|
||||
ctx.closePath(); ctx.fill();
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
// level pips
|
||||
ctx.fillStyle = '#ffffff';
|
||||
for (let i = 0; i < level; i++) { ctx.beginPath(); ctx.arc((i - (level - 1) / 2) * S * 0.13, h - S * 0.08, S * 0.035, 0, TAU); ctx.fill(); }
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ monsters
|
||||
function drawMonster(ctx, m, ang, t, flash, rot) {
|
||||
const def = TD.ENEMIES[m.kind], r = def.r * C, col = def.color;
|
||||
ctx.save();
|
||||
ctx.translate(m.x * C, m.y * C);
|
||||
if (rot) { ctx.rotate(-rot); ang += rot; }
|
||||
ctx.lineJoin = 'round'; ctx.lineCap = 'round';
|
||||
switch (m.kind) {
|
||||
case 'ping':
|
||||
ctx.fillStyle = '#2a0b16'; ctx.beginPath(); ctx.arc(0, 0, r, 0, TAU); ctx.fill();
|
||||
ctx.lineWidth = 2.4; ctx.strokeStyle = col; ctx.stroke();
|
||||
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(Math.cos(ang) * r * 0.35, Math.sin(ang) * r * 0.35, r * 0.38, 0, TAU); ctx.fill();
|
||||
break;
|
||||
case 'worm': {
|
||||
ctx.fillStyle = col;
|
||||
for (let i = 2; i >= 0; i--) {
|
||||
const k = i * r * 1.05, w = Math.sin(t * 11 + m.id + i * 1.3) * r * 0.35;
|
||||
const px = -Math.cos(ang) * k - Math.sin(ang) * w, py = -Math.sin(ang) * k + Math.cos(ang) * w;
|
||||
ctx.globalAlpha = 1 - i * 0.22;
|
||||
ctx.beginPath(); ctx.arc(px, py, r * (1 - i * 0.18), 0, TAU); ctx.fill();
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.fillStyle = '#2a1204'; ctx.beginPath(); ctx.arc(Math.cos(ang) * r * 0.3, Math.sin(ang) * r * 0.3, r * 0.28, 0, TAU); ctx.fill();
|
||||
break;
|
||||
}
|
||||
case 'trojan':
|
||||
poly(ctx, 6, r, ang); ctx.fillStyle = '#2a0e1a'; ctx.fill();
|
||||
ctx.lineWidth = 3; ctx.strokeStyle = col; ctx.stroke();
|
||||
ctx.fillStyle = col; rr(ctx, -r * 0.32, -r * 0.1, r * 0.64, r * 0.5, 2); ctx.fill();
|
||||
ctx.lineWidth = 2.2; ctx.strokeStyle = col; ctx.beginPath(); ctx.arc(0, -r * 0.1, r * 0.22, Math.PI, 0); ctx.stroke();
|
||||
break;
|
||||
case 'spam':
|
||||
ctx.save(); ctx.rotate(ang);
|
||||
ctx.beginPath(); ctx.moveTo(r * 1.25, 0); ctx.lineTo(-r, r * 0.9); ctx.lineTo(-r, -r * 0.9); ctx.closePath();
|
||||
ctx.fillStyle = col; ctx.fill(); ctx.restore();
|
||||
break;
|
||||
case 'ghost': {
|
||||
const bob = Math.sin(t * 5 + m.id) * 2;
|
||||
ctx.translate(0, -7 + bob);
|
||||
ctx.globalAlpha = 0.72 + Math.sin(t * 9 + m.id) * 0.18;
|
||||
poly(ctx, 4, r * 1.25, Math.PI / 4); ctx.fillStyle = rgba(col, 0.28); ctx.fill();
|
||||
ctx.lineWidth = 2.2; ctx.strokeStyle = col; ctx.stroke();
|
||||
ctx.beginPath(); ctx.arc(0, 0, r * 0.42, 0, TAU); ctx.fillStyle = col; ctx.fill();
|
||||
ctx.globalAlpha = 1;
|
||||
break;
|
||||
}
|
||||
case 'rootkit': {
|
||||
ctx.save(); ctx.rotate(t * 0.6);
|
||||
ctx.fillStyle = col;
|
||||
for (let i = 0; i < 8; i++) {
|
||||
ctx.rotate(TAU / 8);
|
||||
ctx.beginPath(); ctx.moveTo(r * 0.8, -r * 0.18); ctx.lineTo(r * 1.28, 0); ctx.lineTo(r * 0.8, r * 0.18); ctx.closePath(); ctx.fill();
|
||||
}
|
||||
ctx.restore();
|
||||
poly(ctx, 8, r, 0.39); ctx.fillStyle = '#240609'; ctx.fill();
|
||||
ctx.lineWidth = 3.2; ctx.strokeStyle = col; ctx.stroke();
|
||||
ctx.fillStyle = rgba('#ff3b3b', 0.55 + Math.sin(t * 4) * 0.3); ctx.beginPath(); ctx.arc(0, 0, r * 0.45, 0, TAU); ctx.fill();
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ctx.fillStyle = col; ctx.beginPath(); ctx.arc(0, 0, r, 0, TAU); ctx.fill();
|
||||
}
|
||||
if (flash > 0) { ctx.globalAlpha = Math.min(0.85, flash * 9); ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r * 1.05, 0, TAU); ctx.fill(); ctx.globalAlpha = 1; }
|
||||
if (m.slow > 0) { ctx.lineWidth = 1.6; ctx.strokeStyle = 'rgba(77,227,255,.85)'; ctx.beginPath(); ctx.arc(0, m.kind === 'ghost' ? -7 : 0, r + 3.5, 0, TAU); ctx.stroke(); }
|
||||
ctx.restore();
|
||||
// health bar
|
||||
if (m.hp < m.maxhp) {
|
||||
const w = Math.max(15, r * 2.3), y = -r - (m.kind === 'ghost' ? 16 : 9), x = -w / 2;
|
||||
const f = clamp(m.hp / m.maxhp, 0, 1);
|
||||
ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot);
|
||||
ctx.fillStyle = 'rgba(0,0,0,.65)'; ctx.fillRect(x - 1, y - 1, w + 2, 5);
|
||||
ctx.fillStyle = f > 0.5 ? '#35e0a1' : f > 0.25 ? '#ffd24d' : '#ff5c7a';
|
||||
ctx.fillRect(x, y, w * f, 3);
|
||||
ctx.restore();
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ renderer
|
||||
class Renderer {
|
||||
constructor(canvas) {
|
||||
this.cv = canvas;
|
||||
this.ctx = canvas.getContext('2d', { alpha: false });
|
||||
this.W = 300; this.H = 200; this.dpr = 1;
|
||||
this.cam = { zoom: 1, px: 0, py: 0 };
|
||||
this.board = null;
|
||||
this.parts = []; this.rings = []; this.lines = []; this.texts = []; this.marks = [];
|
||||
this.aim = new Map(); this.trk = new Map();
|
||||
this.wallGrid = null;
|
||||
this.shake = 0; this.flashCore = 0; this.lastNow = 0;
|
||||
this.rot = 0; // 0, or PI/2 when the board is drawn rotated for portrait screens
|
||||
this.fx = (root.matchMedia && root.matchMedia('(pointer: coarse)').matches) ? 0.55 : 1; // fewer particles on phones
|
||||
this.names = {};
|
||||
}
|
||||
|
||||
setBoard(board) {
|
||||
this.board = board;
|
||||
this.wallGrid = new Uint8Array(board.cols * board.rows);
|
||||
this.parts.length = 0; this.rings.length = 0; this.lines.length = 0; this.texts.length = 0; this.marks.length = 0;
|
||||
this.aim.clear(); this.trk.clear();
|
||||
this.resetCamera();
|
||||
}
|
||||
resize(w, h, dpr) {
|
||||
this.W = Math.max(50, w); this.H = Math.max(50, h); this.dpr = dpr || 1;
|
||||
this.cv.width = Math.round(this.W * this.dpr); this.cv.height = Math.round(this.H * this.dpr);
|
||||
this._layout();
|
||||
}
|
||||
resetCamera() { this.cam.zoom = 1; this.cam.px = 0; this.cam.py = 0; this._layout(); }
|
||||
get zoom() { return this.cam.zoom; }
|
||||
|
||||
setRotation(on) {
|
||||
const r = on ? Math.PI / 2 : 0;
|
||||
if (r === this.rot) return;
|
||||
this.rot = r; this.cam.zoom = 1; this.cam.px = 0; this.cam.py = 0; this._layout();
|
||||
}
|
||||
_dims() {
|
||||
const b = this.board;
|
||||
return this.rot ? { w: b.rows * C, h: b.cols * C } : { w: b.cols * C, h: b.rows * C };
|
||||
}
|
||||
_layout() {
|
||||
const b = this.board; if (!b) return;
|
||||
const d = this._dims(), pad = 4;
|
||||
this.fit = Math.min((this.W - pad * 2) / d.w, (this.H - pad * 2) / d.h);
|
||||
this.scale = this.fit * this.cam.zoom;
|
||||
const sw = d.w * this.scale, sh = d.h * this.scale;
|
||||
const mx = sw > this.W ? (sw - this.W) / 2 + 24 : 0, my = sh > this.H ? (sh - this.H) / 2 + 24 : 0;
|
||||
this.cam.px = clamp(this.cam.px, -mx, mx); this.cam.py = clamp(this.cam.py, -my, my);
|
||||
this.ox = (this.W - sw) / 2 + this.cam.px; this.oy = (this.H - sh) / 2 + this.cam.py;
|
||||
}
|
||||
// CSS px <-> world px (world is always unrotated: 40 px per cell)
|
||||
_s2w(sx, sy) {
|
||||
const u = (sx - this.ox) / this.scale, v = (sy - this.oy) / this.scale;
|
||||
return this.rot ? { x: v, y: this.board.rows * C - u } : { x: u, y: v };
|
||||
}
|
||||
_w2s(wx, wy) {
|
||||
return this.rot
|
||||
? { x: this.ox + (this.board.rows * C - wy) * this.scale, y: this.oy + wx * this.scale }
|
||||
: { x: this.ox + wx * this.scale, y: this.oy + wy * this.scale };
|
||||
}
|
||||
setZoom(z, ax, ay) {
|
||||
z = clamp(z, 1, 4);
|
||||
const w = this._s2w(ax, ay);
|
||||
this.cam.zoom = z; this._layout();
|
||||
const s = this._w2s(w.x, w.y);
|
||||
this.cam.px += ax - s.x; this.cam.py += ay - s.y;
|
||||
this._layout();
|
||||
}
|
||||
panBy(dx, dy) { this.cam.px += dx; this.cam.py += dy; this._layout(); }
|
||||
// CSS px (relative to the canvas) -> cell coordinates
|
||||
screenToCell(sx, sy) {
|
||||
const w = this._s2w(sx, sy), fx = w.x / C, fy = w.y / C;
|
||||
return { x: Math.floor(fx), y: Math.floor(fy), fx, fy };
|
||||
}
|
||||
cellToScreen(cx, cy) { return this._w2s((cx + 0.5) * C, (cy + 0.5) * C); }
|
||||
cellSizePx() { return C * this.scale; }
|
||||
|
||||
// ---------------------------------------------------------------- effects
|
||||
_burst(x, y, col, n, speed, life) {
|
||||
n = Math.max(1, Math.round(n * this.fx));
|
||||
if (this.parts.length > 260) return;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const a = Math.random() * TAU, s = (0.4 + Math.random()) * speed;
|
||||
this.parts.push({ x, y, vx: Math.cos(a) * s, vy: Math.sin(a) * s, life: life * (0.6 + Math.random() * 0.6), max: life, s: 2 + Math.random() * 2.5, c: col });
|
||||
}
|
||||
}
|
||||
_ring(x, y, r0, r1, col, life, w) { if (this.rings.length < 40) this.rings.push({ x, y, r0, r1, col, life, max: life, w: w || 2 }); }
|
||||
_text(x, y, txt, col) { if (this.texts.length < 24) this.texts.push({ x, y, txt, col, life: 0.9, max: 0.9 }); }
|
||||
addMark(x, y, slot) { this.marks.push({ x, y, slot: slot | 0, life: 1.6, max: 1.6 }); if (this.marks.length > 12) this.marks.shift(); }
|
||||
addEvents(evs) {
|
||||
for (const e of evs) {
|
||||
switch (e.e) {
|
||||
case 'kill': {
|
||||
const d = TD.ENEMIES[e.k];
|
||||
this._burst(e.x * C, e.y * C, d ? d.color : '#fff', e.k === 'rootkit' ? 26 : 6, 90, 0.5);
|
||||
if (e.rw >= 3) this._text(e.x * C, e.y * C - 8, '+' + e.rw, '#ffd24d');
|
||||
break;
|
||||
}
|
||||
case 'leak': {
|
||||
const b = this.board;
|
||||
this.flashCore = 1; this.shake = Math.min(2, this.shake + 0.9);
|
||||
if (b) this._ring((b.core.x + 0.5) * C, (b.core.y + 0.5) * C, 10, 48, '#ff5c7a', 0.5, 3);
|
||||
break;
|
||||
}
|
||||
case 'boom': this._ring(e.x * C, e.y * C, 4, e.r * C, '#d4f04a', 0.32, 3); this._burst(e.x * C, e.y * C, '#d4f04a', 8, 110, 0.4); break;
|
||||
case 'shot':
|
||||
if (e.k === 'ids') this.lines.push({ pts: [[e.x * C, e.y * C], [e.tx * C, e.ty * C]], col: '#b78cff', w: 2.5, life: 0.16, max: 0.16, jit: 0 });
|
||||
else if (e.k === 'filter') this._burst(e.x * C + Math.cos(e.a) * 14, e.y * C + Math.sin(e.a) * 14, '#35e0a1', 1, 30, 0.12);
|
||||
else if (e.k === 'mortar') this._burst(e.x * C + Math.cos(e.a) * 16, e.y * C + Math.sin(e.a) * 16, '#d4f04a', 3, 40, 0.25);
|
||||
break;
|
||||
case 'arc': this.lines.push({ pts: e.pts.map((p) => [p[0] * C, p[1] * C]), col: '#ff7ad9', w: 2.4, life: 0.18, max: 0.18, jit: 5 }); break;
|
||||
case 'place': { const d = TD.TOWERS[e.type]; this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 34, d ? d.color : '#fff', 0.35, 2.5); this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, d ? d.color : '#fff', 5, 60, 0.35); break; }
|
||||
case 'sell': this._burst((e.x + 0.5) * C, (e.y + 0.5) * C, '#9db4d8', 6, 70, 0.35); break;
|
||||
case 'up': this._ring((e.x + 0.5) * C, (e.y + 0.5) * C, 6, 38, '#ffffff', 0.4, 2.5); break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- frame
|
||||
// ui: { hover:{x,y}|null, selType, selTower, preview, valid, coop, mySlot, names:{slot:name} }
|
||||
frame(now, view, ui) {
|
||||
const b = this.board; if (!b) return;
|
||||
const ctx = this.ctx, dpr = this.dpr;
|
||||
const t = now / 1000;
|
||||
const dt = clamp((now - (this.lastNow || now)) / 1000, 0, 0.1); this.lastNow = now;
|
||||
const sc = this.scale;
|
||||
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.fillStyle = BG; ctx.fillRect(0, 0, this.W, this.H);
|
||||
|
||||
let shx = 0, shy = 0;
|
||||
if (this.shake > 0.02) { shx = (Math.random() - 0.5) * this.shake * 5; shy = (Math.random() - 0.5) * this.shake * 5; this.shake *= Math.pow(0.02, dt); }
|
||||
const rot = this.rot;
|
||||
if (rot) ctx.setTransform(0, dpr * sc, -dpr * sc, 0, dpr * (this.ox + shx + b.rows * C * sc), dpr * (this.oy + shy));
|
||||
else ctx.setTransform(dpr * sc, 0, 0, dpr * sc, dpr * (this.ox + shx), dpr * (this.oy + shy));
|
||||
|
||||
const cols = b.cols, rows = b.rows;
|
||||
// board plate
|
||||
ctx.fillStyle = BOARD; ctx.fillRect(0, 0, cols * C, rows * C);
|
||||
ctx.lineWidth = 1 / sc * 1.5; ctx.strokeStyle = 'rgba(77,227,255,.35)'; ctx.strokeRect(0, 0, cols * C, rows * C);
|
||||
// grid
|
||||
ctx.lineWidth = 1 / sc; ctx.strokeStyle = 'rgba(80,150,255,.10)';
|
||||
ctx.beginPath();
|
||||
for (let x = 1; x < cols; x++) { ctx.moveTo(x * C, 0); ctx.lineTo(x * C, rows * C); }
|
||||
for (let y = 1; y < rows; y++) { ctx.moveTo(0, y * C); ctx.lineTo(cols * C, y * C); }
|
||||
ctx.stroke();
|
||||
ctx.fillStyle = 'rgba(120,200,255,.22)';
|
||||
ctx.beginPath();
|
||||
for (let y = 0; y <= rows; y++) for (let x = 0; x <= cols; x++) ctx.rect(x * C - 1.2, y * C - 1.2, 2.4, 2.4);
|
||||
ctx.fill();
|
||||
|
||||
// dead nodes
|
||||
for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
|
||||
if (!b.obst[y * cols + x]) continue;
|
||||
const px = x * C, py = y * C;
|
||||
ctx.fillStyle = '#121828'; rr(ctx, px + 4, py + 4, C - 8, C - 8, 6); ctx.fill();
|
||||
ctx.lineWidth = 1.5; ctx.strokeStyle = '#2b3556'; ctx.stroke();
|
||||
ctx.strokeStyle = 'rgba(255,92,122,.32)'; ctx.lineWidth = 2;
|
||||
ctx.beginPath(); ctx.moveTo(px + 12, py + 12); ctx.lineTo(px + C - 12, py + C - 12); ctx.moveTo(px + C - 12, py + 12); ctx.lineTo(px + 12, py + C - 12); ctx.stroke();
|
||||
}
|
||||
|
||||
this._drawRoutes(ctx, b, ui, t);
|
||||
this._drawEndpoints(ctx, b, view, t, dt, rot);
|
||||
|
||||
// walls (with trace links) then turrets
|
||||
const wg = this.wallGrid; wg.fill(0);
|
||||
const towers = view.towers;
|
||||
for (let i = 0; i < towers.length; i++) if (towers[i].type === 'wall') wg[towers[i].y * cols + towers[i].x] = 1;
|
||||
ctx.lineCap = 'round';
|
||||
ctx.strokeStyle = 'rgba(90,169,255,.55)'; ctx.lineWidth = 3.2;
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < towers.length; i++) {
|
||||
const w = towers[i]; if (w.type !== 'wall') continue;
|
||||
const cx = (w.x + 0.5) * C, cy = (w.y + 0.5) * C;
|
||||
if (w.x + 1 < cols && wg[w.y * cols + w.x + 1]) { ctx.moveTo(cx, cy); ctx.lineTo(cx + C, cy); }
|
||||
if (w.y + 1 < rows && wg[(w.y + 1) * cols + w.x]) { ctx.moveTo(cx, cy); ctx.lineTo(cx, cy + C); }
|
||||
}
|
||||
ctx.stroke();
|
||||
ctx.strokeStyle = 'rgba(90,169,255,.32)'; ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < towers.length; i++) {
|
||||
const w = towers[i]; if (w.type !== 'wall') continue;
|
||||
const cx = (w.x + 0.5) * C, cy = (w.y + 0.5) * C;
|
||||
if (w.x + 1 < cols && w.y + 1 < rows && wg[(w.y + 1) * cols + w.x + 1]) { ctx.moveTo(cx, cy); ctx.lineTo(cx + C, cy + C); }
|
||||
if (w.x > 0 && w.y + 1 < rows && wg[(w.y + 1) * cols + w.x - 1]) { ctx.moveTo(cx, cy); ctx.lineTo(cx - C, cy + C); }
|
||||
}
|
||||
ctx.stroke();
|
||||
|
||||
// monster lookup for aiming
|
||||
const monById = new Map();
|
||||
for (let i = 0; i < view.monsters.length; i++) monById.set(view.monsters[i].id, view.monsters[i]);
|
||||
|
||||
const coop = ui.coop;
|
||||
for (let i = 0; i < towers.length; i++) {
|
||||
const tw = towers[i];
|
||||
let ang = this.aim.get(tw.id);
|
||||
if (ang === undefined) ang = -Math.PI / 2;
|
||||
const tg = tw.tgt ? monById.get(tw.tgt) : null;
|
||||
if (tg) { ang = lerpAngle(ang, Math.atan2(tg.y - (tw.y + 0.5), tg.x - (tw.x + 0.5)), 0.35); this.aim.set(tw.id, ang); }
|
||||
const cx = (tw.x + 0.5) * C, cy = (tw.y + 0.5) * C;
|
||||
drawGlyph(ctx, tw.type, tw.level, cx, cy, C, ang, t, 1, rot);
|
||||
if (coop && tw.type !== 'wall') {
|
||||
ctx.fillStyle = SLOT_COLORS[tw.owner] || '#fff';
|
||||
ctx.beginPath(); ctx.moveTo(cx - C * 0.43, cy - C * 0.43); ctx.lineTo(cx - C * 0.43 + 8, cy - C * 0.43); ctx.lineTo(cx - C * 0.43, cy - C * 0.43 + 8); ctx.closePath(); ctx.fill();
|
||||
}
|
||||
}
|
||||
if (this.aim.size > towers.length + 40) { const live = new Set(towers.map((x) => x.id)); for (const k of this.aim.keys()) if (!live.has(k)) this.aim.delete(k); }
|
||||
|
||||
// selection and ranges
|
||||
if (ui.selTower) {
|
||||
const st = towers.find((x) => x.id === ui.selTower);
|
||||
if (st) {
|
||||
const def = TD.TOWERS[st.type], lv = def.levels[st.level - 1];
|
||||
const cx = (st.x + 0.5) * C, cy = (st.y + 0.5) * C;
|
||||
if (lv.range) this._rangeRing(ctx, cx, cy, lv.range * C, def.color);
|
||||
ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; const k = 3 + Math.sin(t * 5) * 1.2, h = C / 2 + k;
|
||||
ctx.beginPath();
|
||||
for (const [sx, sy] of [[-1, -1], [1, -1], [1, 1], [-1, 1]]) { ctx.moveTo(cx + sx * h, cy + sy * (h - 9)); ctx.lineTo(cx + sx * h, cy + sy * h); ctx.lineTo(cx + sx * (h - 9), cy + sy * h); }
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
// ground monsters, then flyers on top
|
||||
this._drawMonsters(ctx, view, t, dt, false, rot);
|
||||
this._drawMonsters(ctx, view, t, dt, true, rot);
|
||||
|
||||
// bullets
|
||||
for (const bu of view.bullets) {
|
||||
if (bu.k === 'mortar') {
|
||||
ctx.fillStyle = 'rgba(0,0,0,.35)'; ctx.beginPath(); ctx.arc(bu.x * C, bu.y * C + 5, 4, 0, TAU); ctx.fill();
|
||||
ctx.fillStyle = '#d4f04a'; ctx.beginPath(); ctx.arc(bu.x * C, bu.y * C - 2, 4.5, 0, TAU); ctx.fill();
|
||||
} else {
|
||||
ctx.fillStyle = 'rgba(53,224,161,.3)'; ctx.beginPath(); ctx.arc(bu.x * C, bu.y * C, 6, 0, TAU); ctx.fill();
|
||||
ctx.fillStyle = '#d6fff0'; ctx.beginPath(); ctx.arc(bu.x * C, bu.y * C, 2.6, 0, TAU); ctx.fill();
|
||||
}
|
||||
}
|
||||
|
||||
this._drawFx(ctx, dt, sc, rot);
|
||||
|
||||
// placement ghost
|
||||
if (ui.hover && ui.selType && !ui.noGhost && b.inBounds(ui.hover.x, ui.hover.y)) {
|
||||
const def = TD.TOWERS[ui.selType], lv = def.levels[0];
|
||||
const cx = (ui.hover.x + 0.5) * C, cy = (ui.hover.y + 0.5) * C;
|
||||
const ok = ui.valid !== false;
|
||||
if (lv.range) this._rangeRing(ctx, cx, cy, lv.range * C, ok ? def.color : '#ff5c7a');
|
||||
drawGlyph(ctx, ui.selType, 1, cx, cy, C, -Math.PI / 2 - rot, t, ok ? 0.7 : 0.4, rot);
|
||||
if (!ok) {
|
||||
ctx.fillStyle = 'rgba(255,60,90,.28)'; ctx.fillRect(ui.hover.x * C + 2, ui.hover.y * C + 2, C - 4, C - 4);
|
||||
ctx.strokeStyle = '#ff5c7a'; ctx.lineWidth = 3; ctx.beginPath();
|
||||
ctx.moveTo(cx - 9, cy - 9); ctx.lineTo(cx + 9, cy + 9); ctx.moveTo(cx + 9, cy - 9); ctx.lineTo(cx - 9, cy + 9); ctx.stroke();
|
||||
} else {
|
||||
ctx.strokeStyle = rgba(def.color, 0.9); ctx.lineWidth = 2; rr(ctx, ui.hover.x * C + 2, ui.hover.y * C + 2, C - 4, C - 4, 6); ctx.stroke();
|
||||
}
|
||||
} else if (ui.hover && (!ui.selType || ui.noGhost) && b.inBounds(ui.hover.x, ui.hover.y)) {
|
||||
ctx.strokeStyle = 'rgba(255,255,255,.22)'; ctx.lineWidth = 1.5; ctx.strokeRect(ui.hover.x * C + 1, ui.hover.y * C + 1, C - 2, C - 2);
|
||||
}
|
||||
|
||||
// partner cursors and pings
|
||||
ctx.font = '600 ' + (11 / sc) + 'px system-ui, sans-serif'; ctx.textBaseline = 'middle';
|
||||
for (const cu of view.cursors || []) {
|
||||
const col = SLOT_COLORS[cu.slot] || '#fff', gx = Math.floor(cu.x), gy = Math.floor(cu.y);
|
||||
ctx.strokeStyle = col; ctx.lineWidth = 2; ctx.strokeRect(gx * C + 1, gy * C + 1, C - 2, C - 2);
|
||||
const nm = (ui.names && ui.names[cu.slot]) || 'Partner';
|
||||
const tw = ctx.measureText(nm).width + 10 / sc;
|
||||
ctx.save(); ctx.translate((gx + 0.5) * C, (gy + 0.5) * C); if (rot) ctx.rotate(-rot);
|
||||
ctx.fillStyle = col; ctx.fillRect(-tw / 2, -C / 2 - 17 / sc, tw, 15 / sc);
|
||||
ctx.fillStyle = '#04101a'; ctx.textAlign = 'center'; ctx.fillText(nm, 0, -C / 2 - 9.5 / sc);
|
||||
ctx.restore();
|
||||
}
|
||||
ctx.textAlign = 'start';
|
||||
for (let i = this.marks.length - 1; i >= 0; i--) {
|
||||
const m = this.marks[i]; m.life -= dt;
|
||||
if (m.life <= 0) { this.marks.splice(i, 1); continue; }
|
||||
const k = 1 - m.life / m.max, col = SLOT_COLORS[m.slot] || '#fff';
|
||||
ctx.strokeStyle = col; ctx.lineWidth = 3;
|
||||
for (let j = 0; j < 3; j++) {
|
||||
const kk = k - j * 0.16; if (kk <= 0) continue;
|
||||
ctx.globalAlpha = (1 - kk) * 0.9; ctx.beginPath(); ctx.arc((m.x + 0.5) * C, (m.y + 0.5) * C, 6 + kk * 46, 0, TAU); ctx.stroke();
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.fillStyle = col; ctx.beginPath(); ctx.arc((m.x + 0.5) * C, (m.y + 0.5) * C, 5, 0, TAU); ctx.fill();
|
||||
}
|
||||
}
|
||||
|
||||
_rangeRing(ctx, cx, cy, r, col) {
|
||||
ctx.fillStyle = rgba(col, 0.07); ctx.beginPath(); ctx.arc(cx, cy, r, 0, TAU); ctx.fill();
|
||||
ctx.strokeStyle = rgba(col, 0.55); ctx.lineWidth = 1.5; ctx.stroke();
|
||||
}
|
||||
|
||||
_drawRoutes(ctx, b, ui, t) {
|
||||
const pv = ui && ui.preview && ui.preview.ok && ui.preview.routes;
|
||||
const dash = (col, w, speed) => { ctx.strokeStyle = col; ctx.lineWidth = w; ctx.setLineDash([9, 9]); ctx.lineDashOffset = -t * speed; };
|
||||
ctx.lineJoin = 'round'; ctx.lineCap = 'round';
|
||||
dash(pv ? 'rgba(77,227,255,.10)' : 'rgba(77,227,255,.34)', 3, 34);
|
||||
for (const r of b.routes) {
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < r.length; i++) { const px = (r[i][0] + 0.5) * C, py = (r[i][1] + 0.5) * C; i ? ctx.lineTo(px, py) : ctx.moveTo(px, py); }
|
||||
ctx.stroke();
|
||||
}
|
||||
if (pv) {
|
||||
dash('rgba(255,210,77,.85)', 3.6, 60);
|
||||
for (const r of ui.preview.routes) {
|
||||
ctx.beginPath();
|
||||
for (let i = 0; i < r.length; i++) { const px = (r[i][0] + 0.5) * C, py = (r[i][1] + 0.5) * C; i ? ctx.lineTo(px, py) : ctx.moveTo(px, py); }
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
ctx.setLineDash([]);
|
||||
}
|
||||
|
||||
_drawEndpoints(ctx, b, view, t, dt, rot) {
|
||||
// spawns: red gateways
|
||||
for (const sp of b.spawns) {
|
||||
const p = (t * 0.7) % 1;
|
||||
ctx.save(); ctx.translate((sp.x + 0.5) * C, (sp.y + 0.5) * C); if (rot) ctx.rotate(-rot);
|
||||
ctx.strokeStyle = rgba('#ff5c7a', 0.5 * (1 - p)); ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(0, 0, 12 + p * 16, 0, TAU); ctx.stroke();
|
||||
ctx.fillStyle = '#2a0c18'; ctx.beginPath(); ctx.arc(0, 0, 13, 0, TAU); ctx.fill();
|
||||
ctx.strokeStyle = '#ff5c7a'; ctx.lineWidth = 2; ctx.stroke();
|
||||
ctx.lineWidth = 1.3; ctx.beginPath(); ctx.ellipse(0, 0, 5.5, 13, 0, 0, TAU); ctx.moveTo(-13, 0); ctx.lineTo(13, 0); ctx.stroke();
|
||||
ctx.restore();
|
||||
}
|
||||
// core: server rack with an integrity ring
|
||||
const c = b.core;
|
||||
const frac = view.maxLives ? clamp(view.lives / view.maxLives, 0, 1) : 1;
|
||||
const col = frac > 0.5 ? '#35e0a1' : frac > 0.25 ? '#ffd24d' : '#ff5c7a';
|
||||
this.flashCore = Math.max(0, this.flashCore - dt * 2.2);
|
||||
ctx.save(); ctx.translate((c.x + 0.5) * C, (c.y + 0.5) * C); if (rot) ctx.rotate(-rot);
|
||||
ctx.strokeStyle = 'rgba(255,255,255,.08)'; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(0, 0, 25, 0, TAU); ctx.stroke();
|
||||
ctx.strokeStyle = col; ctx.lineWidth = 4; ctx.beginPath(); ctx.arc(0, 0, 25, -Math.PI / 2, -Math.PI / 2 + TAU * frac); ctx.stroke();
|
||||
if (this.flashCore > 0) { ctx.fillStyle = 'rgba(255,60,90,' + (this.flashCore * 0.4) + ')'; ctx.beginPath(); ctx.arc(0, 0, 29, 0, TAU); ctx.fill(); }
|
||||
ctx.fillStyle = '#0d2038'; rr(ctx, -13, -16, 26, 32, 5); ctx.fill();
|
||||
ctx.strokeStyle = '#4de3ff'; ctx.lineWidth = 2; ctx.stroke();
|
||||
ctx.lineWidth = 1.5; ctx.beginPath();
|
||||
for (let i = 0; i < 3; i++) { ctx.moveTo(-9, -9 + i * 8); ctx.lineTo(3, -9 + i * 8); }
|
||||
ctx.stroke();
|
||||
for (let i = 0; i < 3; i++) { ctx.fillStyle = (Math.floor(t * 3 + i * 1.7) % 2) ? col : rgba(col, 0.35); ctx.beginPath(); ctx.arc(8, -9 + i * 8, 2, 0, TAU); ctx.fill(); }
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
_drawMonsters(ctx, view, t, dt, air, rot) {
|
||||
const trk = this.trk;
|
||||
for (const m of view.monsters) {
|
||||
if (!!m.air !== air) continue;
|
||||
let k = trk.get(m.id);
|
||||
if (!k) { k = { x: m.x, y: m.y, ang: 0, hp: m.hp, flash: 0 }; trk.set(m.id, k); }
|
||||
const dx = m.x - k.x, dy = m.y - k.y;
|
||||
if (dx * dx + dy * dy > 1e-6) k.ang = lerpAngle(k.ang, Math.atan2(dy, dx), 0.35);
|
||||
k.x = m.x; k.y = m.y;
|
||||
if (m.hp < k.hp) k.flash = 0.1;
|
||||
k.hp = m.hp; k.flash = Math.max(0, k.flash - dt);
|
||||
if (air) { const er = TD.ENEMIES[m.kind].r * C; ctx.fillStyle = 'rgba(0,0,0,.28)'; ctx.save(); ctx.translate(m.x * C, m.y * C); if (rot) ctx.rotate(-rot); ctx.beginPath(); ctx.ellipse(0, 5, er, er * 0.45, 0, 0, TAU); ctx.fill(); ctx.restore(); }
|
||||
drawMonster(ctx, m, k.ang, t, k.flash, rot);
|
||||
}
|
||||
if (air && trk.size > view.monsters.length + 60) { // drop stale trackers
|
||||
const live = new Set(view.monsters.map((x) => x.id));
|
||||
for (const id of trk.keys()) if (!live.has(id)) trk.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
_drawFx(ctx, dt, sc, rot) {
|
||||
// lines (tracers, arcs)
|
||||
ctx.lineCap = 'round'; ctx.lineJoin = 'round';
|
||||
for (let i = this.lines.length - 1; i >= 0; i--) {
|
||||
const l = this.lines[i]; l.life -= dt;
|
||||
if (l.life <= 0) { this.lines.splice(i, 1); continue; }
|
||||
ctx.globalAlpha = l.life / l.max; ctx.strokeStyle = l.col; ctx.lineWidth = l.w;
|
||||
ctx.beginPath();
|
||||
for (let j = 0; j < l.pts.length; j++) {
|
||||
const jx = l.jit && j > 0 ? (Math.random() - 0.5) * l.jit * 2 : 0, jy = l.jit && j > 0 ? (Math.random() - 0.5) * l.jit * 2 : 0;
|
||||
j ? ctx.lineTo(l.pts[j][0] + jx, l.pts[j][1] + jy) : ctx.moveTo(l.pts[j][0], l.pts[j][1]);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
for (let i = this.rings.length - 1; i >= 0; i--) {
|
||||
const r = this.rings[i]; r.life -= dt;
|
||||
if (r.life <= 0) { this.rings.splice(i, 1); continue; }
|
||||
const k = 1 - r.life / r.max;
|
||||
ctx.globalAlpha = 1 - k; ctx.strokeStyle = r.col; ctx.lineWidth = r.w;
|
||||
ctx.beginPath(); ctx.arc(r.x, r.y, r.r0 + (r.r1 - r.r0) * k, 0, TAU); ctx.stroke();
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
for (let i = this.parts.length - 1; i >= 0; i--) {
|
||||
const p = this.parts[i]; p.life -= dt;
|
||||
if (p.life <= 0) { this.parts.splice(i, 1); continue; }
|
||||
p.x += p.vx * dt; p.y += p.vy * dt; p.vx *= 0.94; p.vy *= 0.94;
|
||||
ctx.globalAlpha = Math.min(1, p.life / p.max * 1.4); ctx.fillStyle = p.c;
|
||||
ctx.fillRect(p.x - p.s / 2, p.y - p.s / 2, p.s, p.s);
|
||||
}
|
||||
ctx.globalAlpha = 1;
|
||||
if (this.texts.length) {
|
||||
ctx.font = '700 ' + (12 / sc) + 'px ui-monospace, monospace'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
|
||||
for (let i = this.texts.length - 1; i >= 0; i--) {
|
||||
const x = this.texts[i]; x.life -= dt;
|
||||
if (x.life <= 0) { this.texts.splice(i, 1); continue; }
|
||||
if (rot) x.x -= 22 * dt; else x.y -= 22 * dt; // drift towards the top of the screen
|
||||
ctx.globalAlpha = Math.min(1, x.life / x.max * 1.6); ctx.fillStyle = x.col;
|
||||
ctx.save(); ctx.translate(x.x, x.y); if (rot) ctx.rotate(-rot); ctx.fillText(x.txt, 0, 0); ctx.restore();
|
||||
}
|
||||
ctx.globalAlpha = 1; ctx.textAlign = 'start';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Draw a tower icon into a small canvas (palette buttons, info panel)
|
||||
function drawIcon(canvas, type, level) {
|
||||
const dpr = Math.min(2, root.devicePixelRatio || 1), size = canvas.clientWidth || 34;
|
||||
canvas.width = canvas.height = Math.round(size * dpr);
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||
ctx.clearRect(0, 0, size, size);
|
||||
drawGlyph(ctx, type, level || 1, size / 2, size / 2, size * 1.1, -0.6, 0.3, 1);
|
||||
}
|
||||
|
||||
NW.Renderer = Renderer;
|
||||
NW.drawIcon = drawIcon;
|
||||
NW.drawGlyph = drawGlyph;
|
||||
NW.SLOT_COLORS = SLOT_COLORS;
|
||||
NW.CELL = C;
|
||||
})(typeof self !== 'undefined' ? self : this);
|
||||
819
public/js/sim.js
Normal file
819
public/js/sim.js
Normal file
|
|
@ -0,0 +1,819 @@
|
|||
/*
|
||||
* NETWALL - shared simulation core.
|
||||
*
|
||||
* Pure game logic, no DOM, no timers. Loaded as a classic <script> in the browser (window.TD)
|
||||
* and with require() in Node (the multiplayer server runs the authoritative copy).
|
||||
*
|
||||
* Coordinates are in cell units; the centre of cell (i, j) is (i + 0.5, j + 0.5).
|
||||
*/
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) module.exports = factory();
|
||||
else root.TD = factory();
|
||||
})(typeof self !== 'undefined' ? self : this, function () {
|
||||
'use strict';
|
||||
|
||||
const STEP = 1 / 60;
|
||||
const SQRT2 = Math.SQRT2;
|
||||
const DX = [1, -1, 0, 0, 1, 1, -1, -1];
|
||||
const DY = [0, 0, 1, -1, 1, -1, 1, -1];
|
||||
const WAVE_INTERVAL = 28;
|
||||
const START_GOLD = 140;
|
||||
const START_LIVES = 20;
|
||||
const SELL_RATIO = 0.7;
|
||||
const WIN_WAVE = 30;
|
||||
|
||||
// ---------------------------------------------------------------- maps
|
||||
// '.' open, '#' dead node (permanent obstacle), 'S' spawn (internet gateway), 'C' core (the server)
|
||||
const MAPS = {
|
||||
open: {
|
||||
id: 'open', name: 'Open Field', difficulty: 1,
|
||||
desc: 'One gateway, one server, wide open. Build your own maze.',
|
||||
rows: [
|
||||
'..........................',
|
||||
'..........................',
|
||||
'....##..........##........',
|
||||
'....#............#........',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'S.........................',
|
||||
'.........................C',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'....#............#........',
|
||||
'....##..........##........',
|
||||
'..........................',
|
||||
'..........................',
|
||||
],
|
||||
},
|
||||
twin: {
|
||||
id: 'twin', name: 'Twin Gateways', difficulty: 2,
|
||||
desc: 'Two gateways flood one server. A central pillar splits the field.',
|
||||
rows: [
|
||||
'S.........................',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'.........#######..........',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'.........................C',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'.........#######..........',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'S.........................',
|
||||
],
|
||||
},
|
||||
hub: {
|
||||
id: 'hub', name: 'The Hub', difficulty: 3,
|
||||
desc: 'The server sits in the middle. Traffic arrives from three sides.',
|
||||
rows: [
|
||||
'............S.............',
|
||||
'..........................',
|
||||
'..##..................##..',
|
||||
'..#....................#..',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'S.........................',
|
||||
'.............C............',
|
||||
'.........................S',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'..........................',
|
||||
'..#....................#..',
|
||||
'..##..................##..',
|
||||
'..........................',
|
||||
],
|
||||
},
|
||||
};
|
||||
const MAP_ORDER = ['open', 'twin', 'hub'];
|
||||
|
||||
function parseMap(m) {
|
||||
const rows = m.rows.length, cols = m.rows[0].length;
|
||||
const obst = new Uint8Array(cols * rows);
|
||||
const spawns = [];
|
||||
let core = null;
|
||||
for (let y = 0; y < rows; y++) {
|
||||
if (m.rows[y].length !== cols) throw new Error('map ' + m.id + ' row ' + y + ' has wrong width');
|
||||
for (let x = 0; x < cols; x++) {
|
||||
const ch = m.rows[y][x];
|
||||
if (ch === '#') obst[y * cols + x] = 1;
|
||||
else if (ch === 'S') spawns.push({ x, y });
|
||||
else if (ch === 'C') core = { x, y };
|
||||
}
|
||||
}
|
||||
if (!core || !spawns.length) throw new Error('map ' + m.id + ' needs a core and a spawn');
|
||||
return { cols, rows, obst, spawns, core };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- definitions
|
||||
const TOWER_ORDER = ['wall', 'filter', 'ids', 'mortar', 'throttle', 'arc'];
|
||||
const TARGET_MODES = ['first', 'last', 'strong', 'close'];
|
||||
const TOWERS = {
|
||||
wall: {
|
||||
name: 'Firewall', key: '1', color: '#5aa9ff', refund: 1,
|
||||
desc: 'Blocks the route. Cheap: use it to build a long maze.',
|
||||
levels: [{ cost: 5 }],
|
||||
},
|
||||
filter: {
|
||||
name: 'Packet Filter', key: '2', color: '#35e0a1', air: true, ground: true,
|
||||
desc: 'Fast, cheap rapid fire. Weak against armour.',
|
||||
levels: [
|
||||
{ cost: 25, dmg: 6, range: 3.2, rate: 3.0 },
|
||||
{ cost: 30, dmg: 9, range: 3.5, rate: 3.4 },
|
||||
{ cost: 55, dmg: 13, range: 3.9, rate: 4.0 },
|
||||
],
|
||||
bulletSpeed: 14,
|
||||
},
|
||||
ids: {
|
||||
name: 'IDS Sniper', key: '3', color: '#b78cff', air: true, ground: true,
|
||||
desc: 'Long range, hard hitting, slow. Great against armour and bosses.',
|
||||
levels: [
|
||||
{ cost: 60, dmg: 50, range: 6.5, rate: 0.7 },
|
||||
{ cost: 70, dmg: 85, range: 7.2, rate: 0.75 },
|
||||
{ cost: 110, dmg: 150, range: 8.0, rate: 0.8 },
|
||||
],
|
||||
},
|
||||
mortar: {
|
||||
name: 'Flood Mortar', key: '4', color: '#d4f04a', air: false, ground: true,
|
||||
desc: 'Splash damage against ground swarms. Cannot hit flyers.',
|
||||
levels: [
|
||||
{ cost: 55, dmg: 28, range: 4.8, rate: 0.8, splash: 1.3 },
|
||||
{ cost: 60, dmg: 45, range: 5.2, rate: 0.85, splash: 1.5 },
|
||||
{ cost: 100, dmg: 75, range: 5.6, rate: 0.9, splash: 1.7 },
|
||||
],
|
||||
shellSpeed: 5.5,
|
||||
},
|
||||
throttle: {
|
||||
name: 'Rate Limiter', key: '5', color: '#4de3ff', air: true, ground: true,
|
||||
desc: 'Slows everything in range. Pair it with damage dealers.',
|
||||
levels: [
|
||||
{ cost: 40, range: 3.2, slow: 0.35 },
|
||||
{ cost: 40, range: 3.6, slow: 0.45 },
|
||||
{ cost: 70, range: 4.0, slow: 0.55 },
|
||||
],
|
||||
},
|
||||
arc: {
|
||||
name: 'Router Arc', key: '6', color: '#ff7ad9', air: true, ground: true,
|
||||
desc: 'Chain lightning that jumps between nearby packets.',
|
||||
levels: [
|
||||
{ cost: 75, dmg: 16, range: 3.6, rate: 1.2, chains: 2, chainRange: 1.9, falloff: 0.7 },
|
||||
{ cost: 70, dmg: 24, range: 3.8, rate: 1.25, chains: 3, chainRange: 2.0, falloff: 0.72 },
|
||||
{ cost: 120, dmg: 36, range: 4.2, rate: 1.4, chains: 4, chainRange: 2.2, falloff: 0.75 },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const ENEMY_ORDER = ['ping', 'worm', 'trojan', 'spam', 'ghost', 'rootkit'];
|
||||
const ENEMIES = {
|
||||
ping: { name: 'Ping', hp: 30, speed: 1.5, armor: 0, reward: 3, leak: 1, air: false, r: 0.26, color: '#ff5c7a' },
|
||||
worm: { name: 'Worm', hp: 18, speed: 2.8, armor: 0, reward: 2, leak: 1, air: false, r: 0.22, color: '#ff9f43' },
|
||||
trojan: { name: 'Trojan', hp: 140, speed: 0.85, armor: 3, reward: 9, leak: 2, air: false, r: 0.38, color: '#c8506b' },
|
||||
spam: { name: 'Spam', hp: 7, speed: 2.0, armor: 0, reward: 1, leak: 1, air: false, r: 0.16, color: '#ffd166' },
|
||||
ghost: { name: 'Spoof', hp: 40, speed: 1.6, armor: 0, reward: 5, leak: 1, air: true, r: 0.28, color: '#e29bff' },
|
||||
rootkit: { name: 'Rootkit', hp: 1400, speed: 0.65, armor: 5, reward: 100, leak: 5, air: false, r: 0.55, color: '#ff3b3b', slowRes: 0.5 },
|
||||
};
|
||||
|
||||
// Wave n (1-based). The first eight waves introduce each unit type; later ones loop with bigger numbers.
|
||||
function waveGroups(n) {
|
||||
const f = 1 + (n - 1) * 0.08;
|
||||
const c = (b) => Math.max(1, Math.round(b * f));
|
||||
let g;
|
||||
switch ((n - 1) % 8) {
|
||||
case 0: g = [{ k: 'ping', c: c(8), gap: 0.7 }]; break;
|
||||
case 1: g = [{ k: 'worm', c: c(10), gap: 0.4 }]; break;
|
||||
case 2: g = [{ k: 'ping', c: c(8), gap: 0.6 }, { k: 'trojan', c: c(1), gap: 1.4 }]; break;
|
||||
case 3: g = [{ k: 'spam', c: c(24), gap: 0.18 }]; break;
|
||||
case 4: g = [{ k: 'ghost', c: c(5), gap: 0.9 }, { k: 'ping', c: c(6), gap: 0.5 }]; break;
|
||||
case 5: g = [{ k: 'trojan', c: c(3), gap: 1.2 }, { k: 'worm', c: c(8), gap: 0.35 }]; break;
|
||||
case 6: g = [{ k: 'ghost', c: c(8), gap: 0.6 }, { k: 'spam', c: c(16), gap: 0.2 }]; break;
|
||||
default: g = [{ k: 'ping', c: c(10), gap: 0.4 }, { k: 'trojan', c: c(3), gap: 1.0 }, { k: 'ghost', c: c(4), gap: 0.8 }];
|
||||
}
|
||||
if (n % 10 === 0) g.push({ k: 'rootkit', c: n / 10, gap: 3 });
|
||||
return g;
|
||||
}
|
||||
function waveSummary(n) {
|
||||
const out = [];
|
||||
for (const g of waveGroups(n)) out.push({ k: g.k, c: g.c });
|
||||
return out;
|
||||
}
|
||||
function hpScale(n) { return 1 + 0.16 * (n - 1) + 0.022 * (n - 1) * (n - 1); }
|
||||
function rewardScale(n) { return 1 + 0.03 * (n - 1); }
|
||||
|
||||
// ---------------------------------------------------------------- path finding
|
||||
class MinHeap {
|
||||
constructor() { this.k = []; this.v = []; }
|
||||
get size() { return this.k.length; }
|
||||
peekKey() { return this.k[0]; }
|
||||
push(key, val) {
|
||||
let i = this.k.length;
|
||||
this.k.push(key); this.v.push(val);
|
||||
while (i > 0) {
|
||||
const p = (i - 1) >> 1;
|
||||
if (this.k[p] <= key) break;
|
||||
this.k[i] = this.k[p]; this.v[i] = this.v[p]; i = p;
|
||||
}
|
||||
this.k[i] = key; this.v[i] = val;
|
||||
}
|
||||
pop() {
|
||||
const top = this.v[0];
|
||||
const lk = this.k.pop(), lv = this.v.pop();
|
||||
const n = this.k.length;
|
||||
if (n > 0) {
|
||||
let i = 0;
|
||||
for (;;) {
|
||||
let l = 2 * i + 1;
|
||||
if (l >= n) break;
|
||||
const r = l + 1;
|
||||
if (r < n && this.k[r] < this.k[l]) l = r;
|
||||
if (this.k[l] >= lk) break;
|
||||
this.k[i] = this.k[l]; this.v[i] = this.v[l]; i = l;
|
||||
}
|
||||
this.k[i] = lk; this.v[i] = lv;
|
||||
}
|
||||
return top;
|
||||
}
|
||||
}
|
||||
|
||||
// Distance-to-core field. 8-way movement; diagonal steps may not cut a corner (both orthogonal
|
||||
// neighbours must be free), so two walls touching diagonally still form a seal.
|
||||
function buildField(cols, rows, solid, coreIdx) {
|
||||
const dist = new Float64Array(cols * rows).fill(Infinity);
|
||||
const heap = new MinHeap();
|
||||
dist[coreIdx] = 0;
|
||||
heap.push(0, coreIdx);
|
||||
while (heap.size) {
|
||||
const d = heap.peekKey();
|
||||
const i = heap.pop();
|
||||
if (d > dist[i]) continue;
|
||||
const x = i % cols, y = (i / cols) | 0;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
const nx = x + DX[k], ny = y + DY[k];
|
||||
if (nx < 0 || ny < 0 || nx >= cols || ny >= rows) continue;
|
||||
const ni = ny * cols + nx;
|
||||
if (solid[ni]) continue;
|
||||
const diag = DX[k] !== 0 && DY[k] !== 0;
|
||||
if (diag && (solid[y * cols + nx] || solid[ny * cols + x])) continue;
|
||||
const nd = d + (diag ? SQRT2 : 1);
|
||||
if (nd < dist[ni] - 1e-6) { dist[ni] = nd; heap.push(nd, ni); }
|
||||
}
|
||||
}
|
||||
return dist;
|
||||
}
|
||||
|
||||
// Best neighbour of cell (x,y) towards the core, or -1 when there is none.
|
||||
function nextCell(cols, rows, solid, dist, x, y) {
|
||||
const here = dist[y * cols + x];
|
||||
if (!isFinite(here)) return -1;
|
||||
let best = -1, bv = Infinity;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
const nx = x + DX[k], ny = y + DY[k];
|
||||
if (nx < 0 || ny < 0 || nx >= cols || ny >= rows) continue;
|
||||
const ni = ny * cols + nx;
|
||||
if (solid[ni]) continue;
|
||||
const diag = DX[k] !== 0 && DY[k] !== 0;
|
||||
if (diag && (solid[y * cols + nx] || solid[ny * cols + x])) continue;
|
||||
const v = dist[ni] + (diag ? SQRT2 : 1);
|
||||
if (dist[ni] < here && v < bv - 1e-6) { bv = v; best = ni; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function traceRoute(cols, rows, solid, dist, sx, sy) {
|
||||
const out = [[sx, sy]];
|
||||
let x = sx, y = sy;
|
||||
for (let guard = cols * rows; guard > 0; guard--) {
|
||||
const n = nextCell(cols, rows, solid, dist, x, y);
|
||||
if (n < 0) break;
|
||||
x = n % cols; y = (n / cols) | 0;
|
||||
out.push([x, y]);
|
||||
if (dist[n] === 0) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- board (grid + pathing)
|
||||
// The part of the game that is purely about the maze. The server's Sim owns one; browser clients
|
||||
// keep a mirror of it so they can preview a placement (and the new route) without a round trip.
|
||||
class Board {
|
||||
constructor(mapId) {
|
||||
const def = typeof mapId === 'object' ? mapId : MAPS[mapId || 'open'];
|
||||
if (!def) throw new Error('unknown map: ' + mapId);
|
||||
this.mapId = def.id;
|
||||
this.def = def;
|
||||
const p = parseMap(def);
|
||||
this.cols = p.cols; this.rows = p.rows;
|
||||
this.obst = p.obst;
|
||||
this.spawns = p.spawns;
|
||||
this.core = p.core;
|
||||
this.coreIdx = p.core.y * p.cols + p.core.x;
|
||||
this.solid = Uint8Array.from(p.obst);
|
||||
this.field = null;
|
||||
this.routes = [];
|
||||
this.routeLen = 0;
|
||||
this.recompute();
|
||||
}
|
||||
idx(x, y) { return y * this.cols + x; }
|
||||
inBounds(x, y) { return Number.isInteger(x) && Number.isInteger(y) && x >= 0 && y >= 0 && x < this.cols && y < this.rows; }
|
||||
isSpecial(x, y) {
|
||||
if (x === this.core.x && y === this.core.y) return 'core';
|
||||
for (const s of this.spawns) if (s.x === x && s.y === y) return 'spawn';
|
||||
return null;
|
||||
}
|
||||
recompute() {
|
||||
this.field = buildField(this.cols, this.rows, this.solid, this.coreIdx);
|
||||
this.routes = this.spawns.map((s) => traceRoute(this.cols, this.rows, this.solid, this.field, s.x, s.y));
|
||||
this.routeLen = this.lengthOf(this.field);
|
||||
}
|
||||
lengthOf(field) {
|
||||
let sum = 0;
|
||||
for (const s of this.spawns) sum += field[s.y * this.cols + s.x];
|
||||
return sum;
|
||||
}
|
||||
// Would a block at (x,y) be legal, and what would it do to the route?
|
||||
// reserved: Set of cell indexes monsters are in/entering (cannot build there)
|
||||
// must: cell indexes that must stay connected to the core (monster cells)
|
||||
// Returns {ok, reason, before, after, routes}
|
||||
trial(x, y, reserved, must, wantRoutes) {
|
||||
const r = { ok: false, reason: '', before: this.routeLen, after: this.routeLen, routes: null };
|
||||
if (!this.inBounds(x, y)) { r.reason = 'bounds'; return r; }
|
||||
const i = this.idx(x, y);
|
||||
if (this.obst[i]) { r.reason = 'obstacle'; return r; }
|
||||
if (this.solid[i]) { r.reason = 'occupied'; return r; }
|
||||
const sp = this.isSpecial(x, y);
|
||||
if (sp) { r.reason = sp; return r; }
|
||||
if (reserved && reserved.has(i)) { r.reason = 'monster'; return r; }
|
||||
this.solid[i] = 1;
|
||||
const f = buildField(this.cols, this.rows, this.solid, this.coreIdx);
|
||||
let blocked = false;
|
||||
for (const s of this.spawns) if (!isFinite(f[s.y * this.cols + s.x])) { blocked = true; break; }
|
||||
if (!blocked && must) for (const c of must) if (!isFinite(f[c])) { blocked = true; break; }
|
||||
if (!blocked && wantRoutes) {
|
||||
r.routes = this.spawns.map((s) => traceRoute(this.cols, this.rows, this.solid, f, s.x, s.y));
|
||||
}
|
||||
this.solid[i] = 0;
|
||||
if (blocked) { r.reason = 'blocks'; return r; }
|
||||
r.ok = true;
|
||||
r.after = this.lengthOf(f);
|
||||
return r;
|
||||
}
|
||||
setSolid(x, y, v) { this.solid[y * this.cols + x] = v ? 1 : 0; }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- simulation
|
||||
class Sim {
|
||||
constructor(opts) {
|
||||
opts = opts || {};
|
||||
this.board = new Board(opts.map || 'open');
|
||||
this.mapId = this.board.mapId;
|
||||
this.winWave = opts.winWave === undefined ? WIN_WAVE : opts.winWave;
|
||||
this.gold = opts.gold === undefined ? START_GOLD : opts.gold;
|
||||
this.lives = opts.lives === undefined ? START_LIVES : opts.lives;
|
||||
this.maxLives = this.lives;
|
||||
this.collectEvents = opts.events !== false;
|
||||
|
||||
this.time = 0;
|
||||
this.nid = 1;
|
||||
this.rev = 0; // bumped whenever towers are added/removed/upgraded/retargeted
|
||||
this.state = 'playing'; // playing | won | lost
|
||||
this.wave = 0; // waves started so far
|
||||
this.bonusWave = 0; // last wave that paid its clear bonus
|
||||
this.kills = 0;
|
||||
this.leaks = 0;
|
||||
this.autoWaves = false;
|
||||
this.nextWaveIn = -1;
|
||||
this.spawnRR = 0;
|
||||
|
||||
this.towers = [];
|
||||
this.towerAt = new Array(this.board.cols * this.board.rows).fill(null);
|
||||
this.monsters = [];
|
||||
this.bullets = [];
|
||||
this.spawnQ = [];
|
||||
this.events = [];
|
||||
}
|
||||
|
||||
emit(e) {
|
||||
if (!this.collectEvents) return;
|
||||
this.events.push(e);
|
||||
if (this.events.length > 800) this.events.splice(0, 300);
|
||||
}
|
||||
drainEvents() { const e = this.events; this.events = []; return e; }
|
||||
|
||||
// ---- commands -------------------------------------------------------------------------
|
||||
cmd(c) {
|
||||
if (!c || typeof c !== 'object') return { ok: false, reason: 'bad_cmd' };
|
||||
switch (c.c) {
|
||||
case 'place': return this.place(c.type, c.x, c.y, c.by | 0);
|
||||
case 'sell': return this.sell(c.id);
|
||||
case 'upgrade': return this.upgrade(c.id);
|
||||
case 'target': return this.setTargetMode(c.id, c.mode);
|
||||
case 'wave': return this.startWave();
|
||||
case 'auto': return this.setAuto(!!c.v);
|
||||
case 'continue': return this.continueEndless();
|
||||
default: return { ok: false, reason: 'bad_cmd' };
|
||||
}
|
||||
}
|
||||
|
||||
// Cells monsters occupy or are about to enter; used to refuse placements that would trap or clip them.
|
||||
monsterCells() {
|
||||
const b = this.board, cols = b.cols;
|
||||
const reserved = new Set(), must = [];
|
||||
for (const m of this.monsters) {
|
||||
if (m.dead || m.air) continue;
|
||||
const ci = m.cy * cols + m.cx;
|
||||
reserved.add(ci); must.push(ci);
|
||||
reserved.add(Math.floor(m.y) * cols + Math.floor(m.x));
|
||||
if (m.tx >= 0) {
|
||||
const ti = m.ty * cols + m.tx;
|
||||
reserved.add(ti); must.push(ti);
|
||||
if (m.cx !== m.tx && m.cy !== m.ty) { // diagonal step: keep both corners clear
|
||||
reserved.add(m.cy * cols + m.tx);
|
||||
reserved.add(m.ty * cols + m.cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { reserved, must };
|
||||
}
|
||||
|
||||
preview(x, y, wantRoutes) {
|
||||
const mc = this.monsterCells();
|
||||
return this.board.trial(x, y, mc.reserved, mc.must, wantRoutes);
|
||||
}
|
||||
|
||||
place(type, x, y, by) {
|
||||
if (this.state !== 'playing') return { ok: false, reason: 'over' };
|
||||
if (typeof type !== 'string' || !Object.prototype.hasOwnProperty.call(TOWERS, type)) return { ok: false, reason: 'bad_type' };
|
||||
const def = TOWERS[type];
|
||||
const cost = def.levels[0].cost;
|
||||
if (this.gold < cost) return { ok: false, reason: 'gold' };
|
||||
const t = this.preview(x, y, false);
|
||||
if (!t.ok) return { ok: false, reason: t.reason };
|
||||
const tower = {
|
||||
id: this.nid++, type, x, y, level: 1, mode: 'first', spent: cost, owner: by | 0,
|
||||
cd: 0, tgt: 0, kills: 0, dealt: 0,
|
||||
};
|
||||
this.gold -= cost;
|
||||
this.towers.push(tower);
|
||||
this.towerAt[y * this.board.cols + x] = tower;
|
||||
this.board.setSolid(x, y, 1);
|
||||
this.board.recompute();
|
||||
this.rev++;
|
||||
this.emit({ e: 'place', id: tower.id, type, x, y, by: tower.owner });
|
||||
return { ok: true, id: tower.id, before: t.before, after: t.after };
|
||||
}
|
||||
|
||||
towerById(id) {
|
||||
for (const t of this.towers) if (t.id === id) return t;
|
||||
return null;
|
||||
}
|
||||
|
||||
sell(id) {
|
||||
if (this.state === 'lost') return { ok: false, reason: 'over' };
|
||||
const t = this.towerById(id);
|
||||
if (!t) return { ok: false, reason: 'no_tower' };
|
||||
const def = TOWERS[t.type];
|
||||
const refund = def.refund ? t.spent : Math.floor(t.spent * SELL_RATIO);
|
||||
this.gold += refund;
|
||||
this.towers.splice(this.towers.indexOf(t), 1);
|
||||
this.towerAt[t.y * this.board.cols + t.x] = null;
|
||||
this.board.setSolid(t.x, t.y, 0);
|
||||
this.board.recompute();
|
||||
this.rev++;
|
||||
this.emit({ e: 'sell', id: t.id, x: t.x, y: t.y, refund });
|
||||
return { ok: true, refund };
|
||||
}
|
||||
|
||||
upgradeCost(t) {
|
||||
const lv = TOWERS[t.type].levels[t.level];
|
||||
return lv ? lv.cost : null;
|
||||
}
|
||||
upgrade(id) {
|
||||
if (this.state !== 'playing') return { ok: false, reason: 'over' };
|
||||
const t = this.towerById(id);
|
||||
if (!t) return { ok: false, reason: 'no_tower' };
|
||||
const cost = this.upgradeCost(t);
|
||||
if (cost === null) return { ok: false, reason: 'max' };
|
||||
if (this.gold < cost) return { ok: false, reason: 'gold' };
|
||||
this.gold -= cost;
|
||||
t.spent += cost;
|
||||
t.level++;
|
||||
this.rev++;
|
||||
this.emit({ e: 'up', id: t.id, level: t.level, x: t.x, y: t.y });
|
||||
return { ok: true, level: t.level };
|
||||
}
|
||||
|
||||
setTargetMode(id, mode) {
|
||||
const t = this.towerById(id);
|
||||
if (!t) return { ok: false, reason: 'no_tower' };
|
||||
if (TARGET_MODES.indexOf(mode) < 0) return { ok: false, reason: 'bad_mode' };
|
||||
t.mode = mode;
|
||||
this.rev++;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
setAuto(v) {
|
||||
this.autoWaves = v;
|
||||
if (v && this.nextWaveIn < 0) this.nextWaveIn = WAVE_INTERVAL;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
continueEndless() {
|
||||
if (this.state !== 'won') return { ok: false, reason: 'not_won' };
|
||||
this.state = 'playing';
|
||||
this.winWave = Infinity;
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
startWave() {
|
||||
if (this.state !== 'playing') return { ok: false, reason: 'over' };
|
||||
const n = ++this.wave;
|
||||
let t = this.time + 0.3;
|
||||
for (const g of waveGroups(n)) {
|
||||
for (let i = 0; i < g.c; i++) { this.spawnQ.push({ t, k: g.k, wave: n }); t += g.gap; }
|
||||
t += 1.5;
|
||||
}
|
||||
this.spawnQ.sort((a, b) => a.t - b.t);
|
||||
if (this.autoWaves) this.nextWaveIn = WAVE_INTERVAL;
|
||||
this.emit({ e: 'wave', n, boss: n % 10 === 0 });
|
||||
return { ok: true, wave: n };
|
||||
}
|
||||
|
||||
spawnMonster(q) {
|
||||
const def = ENEMIES[q.k];
|
||||
const b = this.board;
|
||||
const s = b.spawns[this.spawnRR++ % b.spawns.length];
|
||||
const hp = Math.round(def.hp * hpScale(q.wave));
|
||||
const m = {
|
||||
id: this.nid++, kind: q.k, air: !!def.air,
|
||||
x: s.x + 0.5, y: s.y + 0.5, cx: s.x, cy: s.y, tx: -1, ty: -1,
|
||||
hp, maxhp: hp, armor: def.armor, speed: def.speed,
|
||||
reward: Math.max(1, Math.round(def.reward * rewardScale(q.wave))),
|
||||
leak: def.leak, slow: 0, rem: 0, dead: false, wave: q.wave,
|
||||
};
|
||||
m.rem = m.air
|
||||
? Math.hypot(b.core.x - s.x, b.core.y - s.y)
|
||||
: b.field[s.y * b.cols + s.x];
|
||||
this.monsters.push(m);
|
||||
}
|
||||
|
||||
// ---- main step ------------------------------------------------------------------------
|
||||
tick(dt) {
|
||||
if (this.state !== 'playing') return;
|
||||
this.time += dt;
|
||||
if (this.autoWaves) {
|
||||
this.nextWaveIn -= dt;
|
||||
if (this.nextWaveIn <= 0) this.startWave();
|
||||
}
|
||||
while (this.spawnQ.length && this.spawnQ[0].t <= this.time) this.spawnMonster(this.spawnQ.shift());
|
||||
|
||||
for (const m of this.monsters) m.slow = 0;
|
||||
for (const t of this.towers) this.updateTower(t, dt);
|
||||
this.updateBullets(dt);
|
||||
for (const m of this.monsters) if (!m.dead) this.moveMonster(m, dt);
|
||||
|
||||
let w = 0;
|
||||
for (let i = 0; i < this.monsters.length; i++) {
|
||||
const m = this.monsters[i];
|
||||
if (!m.dead) this.monsters[w++] = m;
|
||||
}
|
||||
this.monsters.length = w;
|
||||
|
||||
if (this.lives <= 0) {
|
||||
this.lives = 0;
|
||||
this.state = 'lost';
|
||||
this.emit({ e: 'lose', wave: this.wave });
|
||||
return;
|
||||
}
|
||||
if (this.wave > this.bonusWave && !this.monsters.length && !this.spawnQ.length) {
|
||||
const bonus = 10 + 2 * this.wave;
|
||||
this.gold += bonus;
|
||||
this.bonusWave = this.wave;
|
||||
this.emit({ e: 'clear', n: this.wave, bonus });
|
||||
if (this.wave >= this.winWave) {
|
||||
this.state = 'won';
|
||||
this.emit({ e: 'win', wave: this.wave });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- monsters -------------------------------------------------------------------------
|
||||
moveMonster(m, dt) {
|
||||
const b = this.board;
|
||||
const slowMul = 1 - Math.min(0.6, m.slow);
|
||||
let remaining = m.speed * slowMul * dt;
|
||||
if (m.air) {
|
||||
const gx = b.core.x + 0.5, gy = b.core.y + 0.5;
|
||||
const dx = gx - m.x, dy = gy - m.y, d = Math.hypot(dx, dy);
|
||||
if (d <= remaining + 0.05) { this.leak(m); return; }
|
||||
m.x += (dx / d) * remaining; m.y += (dy / d) * remaining;
|
||||
m.rem = d - remaining;
|
||||
return;
|
||||
}
|
||||
for (let guard = 4; remaining > 1e-6 && guard > 0; guard--) {
|
||||
if (m.tx < 0) {
|
||||
if (m.cx === b.core.x && m.cy === b.core.y) { this.leak(m); return; }
|
||||
const n = nextCell(b.cols, b.rows, b.solid, b.field, m.cx, m.cy);
|
||||
if (n < 0) break;
|
||||
m.tx = n % b.cols; m.ty = (n / b.cols) | 0;
|
||||
}
|
||||
const gx = m.tx + 0.5, gy = m.ty + 0.5;
|
||||
const dx = gx - m.x, dy = gy - m.y, d = Math.hypot(dx, dy);
|
||||
if (d <= remaining) {
|
||||
m.x = gx; m.y = gy; remaining -= d;
|
||||
m.cx = m.tx; m.cy = m.ty; m.tx = -1; m.ty = -1;
|
||||
if (m.cx === b.core.x && m.cy === b.core.y) { this.leak(m); return; }
|
||||
} else {
|
||||
m.x += (dx / d) * remaining; m.y += (dy / d) * remaining; remaining = 0;
|
||||
}
|
||||
}
|
||||
const f = b.field;
|
||||
m.rem = m.tx >= 0
|
||||
? f[m.ty * b.cols + m.tx] + Math.hypot(m.x - (m.tx + 0.5), m.y - (m.ty + 0.5))
|
||||
: f[m.cy * b.cols + m.cx];
|
||||
}
|
||||
|
||||
leak(m) {
|
||||
m.dead = true; m.leaked = true;
|
||||
this.lives -= m.leak;
|
||||
this.leaks++;
|
||||
this.emit({ e: 'leak', x: m.x, y: m.y, n: m.leak });
|
||||
}
|
||||
|
||||
damage(m, raw, src) {
|
||||
if (m.dead) return;
|
||||
const d = Math.max(raw - m.armor, raw * 0.25);
|
||||
m.hp -= d;
|
||||
if (src) src.dealt += d;
|
||||
if (m.hp <= 0) {
|
||||
m.dead = true;
|
||||
this.gold += m.reward;
|
||||
this.kills++;
|
||||
if (src) src.kills++;
|
||||
this.emit({ e: 'kill', x: m.x, y: m.y, k: m.kind, rw: m.reward });
|
||||
}
|
||||
}
|
||||
|
||||
// ---- towers ---------------------------------------------------------------------------
|
||||
findTarget(t, range, def) {
|
||||
const tx = t.x + 0.5, ty = t.y + 0.5, r2 = range * range;
|
||||
let best = null, bv = 0;
|
||||
for (const m of this.monsters) {
|
||||
if (m.dead) continue;
|
||||
if (m.air ? !def.air : !def.ground) continue;
|
||||
const dx = m.x - tx, dy = m.y - ty, d2 = dx * dx + dy * dy;
|
||||
if (d2 > r2) continue;
|
||||
let v;
|
||||
switch (t.mode) {
|
||||
case 'last': v = m.rem; break;
|
||||
case 'strong': v = m.hp; break;
|
||||
case 'close': v = -d2; break;
|
||||
default: v = -m.rem; // 'first': smallest remaining distance wins
|
||||
}
|
||||
if (best === null || v > bv) { best = m; bv = v; }
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
updateTower(t, dt) {
|
||||
if (t.type === 'wall') return;
|
||||
const def = TOWERS[t.type];
|
||||
const st = def.levels[t.level - 1];
|
||||
const cx = t.x + 0.5, cy = t.y + 0.5;
|
||||
if (t.type === 'throttle') {
|
||||
const r2 = st.range * st.range;
|
||||
for (const m of this.monsters) {
|
||||
if (m.dead) continue;
|
||||
const dx = m.x - cx, dy = m.y - cy;
|
||||
if (dx * dx + dy * dy > r2) continue;
|
||||
const eff = st.slow * (1 - (ENEMIES[m.kind].slowRes || 0));
|
||||
if (eff > m.slow) m.slow = eff;
|
||||
}
|
||||
return;
|
||||
}
|
||||
t.cd -= dt;
|
||||
const m = this.findTarget(t, st.range, def);
|
||||
t.tgt = m ? m.id : 0;
|
||||
if (!m) { if (t.cd < 0) t.cd = 0; return; }
|
||||
if (t.cd > 0) return;
|
||||
t.cd += 1 / st.rate;
|
||||
this.fire(t, st, def, m, cx, cy);
|
||||
}
|
||||
|
||||
fire(t, st, def, m, cx, cy) {
|
||||
switch (t.type) {
|
||||
case 'filter':
|
||||
this.bullets.push({ id: this.nid++, k: 'filter', x: cx, y: cy, sp: def.bulletSpeed, tgt: m, gx: m.x, gy: m.y, dmg: st.dmg, src: t });
|
||||
this.emit({ e: 'shot', k: 'filter', x: cx, y: cy, a: Math.atan2(m.y - cy, m.x - cx) });
|
||||
break;
|
||||
case 'ids':
|
||||
this.damage(m, st.dmg, t);
|
||||
this.emit({ e: 'shot', k: 'ids', x: cx, y: cy, tx: m.x, ty: m.y });
|
||||
break;
|
||||
case 'mortar': {
|
||||
let gx = m.x, gy = m.y;
|
||||
if (m.tx >= 0) { // lead the target along its current step
|
||||
const ex = m.tx + 0.5 - m.x, ey = m.ty + 0.5 - m.y, el = Math.hypot(ex, ey) || 1;
|
||||
const T = Math.hypot(m.x - cx, m.y - cy) / def.shellSpeed;
|
||||
const lead = Math.min(el, m.speed * (1 - Math.min(0.6, m.slow)) * T);
|
||||
gx += (ex / el) * lead; gy += (ey / el) * lead;
|
||||
}
|
||||
this.bullets.push({ id: this.nid++, k: 'mortar', x: cx, y: cy, sp: def.shellSpeed, tgt: null, gx, gy, dmg: st.dmg, splash: st.splash, src: t });
|
||||
this.emit({ e: 'shot', k: 'mortar', x: cx, y: cy, a: Math.atan2(gy - cy, gx - cx) });
|
||||
break;
|
||||
}
|
||||
case 'arc': {
|
||||
const pts = [[cx, cy], [m.x, m.y]];
|
||||
const hit = new Set([m]);
|
||||
let dmg = st.dmg, cur = m;
|
||||
this.damage(cur, dmg, t);
|
||||
for (let c = 0; c < st.chains; c++) {
|
||||
let nb = null, nd = st.chainRange * st.chainRange;
|
||||
for (const o of this.monsters) {
|
||||
if (o.dead || hit.has(o)) continue;
|
||||
if (o.air ? !def.air : !def.ground) continue;
|
||||
const dx = o.x - cur.x, dy = o.y - cur.y, d2 = dx * dx + dy * dy;
|
||||
if (d2 <= nd) { nd = d2; nb = o; }
|
||||
}
|
||||
if (!nb) break;
|
||||
hit.add(nb);
|
||||
dmg *= st.falloff;
|
||||
this.damage(nb, dmg, t);
|
||||
pts.push([nb.x, nb.y]);
|
||||
cur = nb;
|
||||
}
|
||||
this.emit({ e: 'arc', pts: pts.map((p) => [round2(p[0]), round2(p[1])]) });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateBullets(dt) {
|
||||
let w = 0;
|
||||
for (let i = 0; i < this.bullets.length; i++) {
|
||||
const b = this.bullets[i];
|
||||
if (b.tgt && !b.tgt.dead) { b.gx = b.tgt.x; b.gy = b.tgt.y; }
|
||||
const dx = b.gx - b.x, dy = b.gy - b.y, d = Math.hypot(dx, dy), step = b.sp * dt;
|
||||
if (d <= step || d < 0.05) {
|
||||
if (b.k === 'mortar') {
|
||||
const r2 = b.splash * b.splash;
|
||||
for (const m of this.monsters) {
|
||||
if (m.dead || m.air) continue;
|
||||
const ex = m.x - b.gx, ey = m.y - b.gy;
|
||||
if (ex * ex + ey * ey <= r2) this.damage(m, b.dmg, b.src);
|
||||
}
|
||||
this.emit({ e: 'boom', x: b.gx, y: b.gy, r: b.splash });
|
||||
} else if (b.tgt && !b.tgt.dead) {
|
||||
this.damage(b.tgt, b.dmg, b.src);
|
||||
}
|
||||
continue; // bullet consumed
|
||||
}
|
||||
b.x += (dx / d) * step; b.y += (dy / d) * step;
|
||||
this.bullets[w++] = b;
|
||||
}
|
||||
this.bullets.length = w;
|
||||
}
|
||||
|
||||
// ---- views of the state ---------------------------------------------------------------
|
||||
towerList() {
|
||||
return this.towers.map((t) => [t.id, t.type, t.x, t.y, t.level, t.mode, t.spent, t.owner]);
|
||||
}
|
||||
|
||||
// Everything a client needs to (re)build the board from scratch.
|
||||
fullState() {
|
||||
return {
|
||||
map: this.mapId, rev: this.rev, towers: this.towerList(),
|
||||
winWave: this.winWave === Infinity ? 0 : this.winWave,
|
||||
maxLives: this.maxLives,
|
||||
};
|
||||
}
|
||||
|
||||
// Compact per-tick state for the wire. Arrays, not objects, to keep it small.
|
||||
snapshot() {
|
||||
const mo = this.monsters.map((m) => [m.id, ENEMY_ORDER.indexOf(m.kind), round2(m.x), round2(m.y), Math.ceil(m.hp), m.maxhp, m.slow > 0 ? 1 : 0]);
|
||||
const bu = this.bullets.map((b) => [b.id, b.k === 'mortar' ? 1 : 0, round2(b.x), round2(b.y)]);
|
||||
const tt = [];
|
||||
for (const t of this.towers) if (t.type !== 'wall') tt.push([t.id, t.tgt, t.kills]);
|
||||
return {
|
||||
time: round2(this.time), g: this.gold, l: this.lives, w: this.wave, s: this.state,
|
||||
au: this.autoWaves ? 1 : 0, nw: this.autoWaves ? round2(this.nextWaveIn) : -1,
|
||||
k: this.kills, rev: this.rev, mo, bu, tt,
|
||||
q: this.spawnQ.length,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function round2(v) { return Math.round(v * 100) / 100; }
|
||||
|
||||
return {
|
||||
STEP, WAVE_INTERVAL, START_GOLD, START_LIVES, SELL_RATIO, WIN_WAVE,
|
||||
MAPS, MAP_ORDER, TOWERS, TOWER_ORDER, TARGET_MODES, ENEMIES, ENEMY_ORDER,
|
||||
waveGroups, waveSummary, hpScale, rewardScale,
|
||||
buildField, nextCell, traceRoute, parseMap, Board, Sim, round2,
|
||||
};
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue