'use strict'; /** * Online play: talks to api.php (cookie session), polls lobby and game * state, and draws opponent miniatures plus flying-block tweens. * Real-time sync is not required; a 0.75 s poll is enough. */ var Online = { POLL_MS: 750, DEFAULT_MISS_CHANCE: 0.30, FLIGHT_DURATION: 1.2, configured: false, local: false, csrf: '', me: null, lobby: null, incoming: [], shotResults: [], error: '', _timer: null, _pendingShots: [], _flights: [], _lastStatus: null, onChange: null, onGameStart: null, onIncoming: null, onFinished: null, onLobbyReturn: null }; Online._headers = function (json) { var h = { 'Accept': 'application/json' }; if (json) { h['Content-Type'] = 'application/json'; } if (this.csrf) { h['X-CSRF-Token'] = this.csrf; } return h; }; Online._apply = function (data) { if (!data) { return; } if (typeof data.configured === 'boolean') { this.configured = data.configured; } if (typeof data.local === 'boolean') { this.local = data.local; } if (data.csrf) { this.csrf = data.csrf; } if (data.me !== undefined) { this.me = data.me; } if (data.lobby !== undefined) { this.lobby = data.lobby; } if (data.incoming) { this.incoming = data.incoming; } if (data.shot_results) { this.shotResults = data.shot_results; } if (data.miss_chance_default != null) { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; } if (data.flight_duration != null) { this.FLIGHT_DURATION = data.flight_duration; } if (data.error) { this.error = data.error; } else if (data.ok) { this.error = ''; } }; Online.request = function (action, body) { var self = this; var isGet = action === 'me' || action === ''; var url = 'api.php?action=' + encodeURIComponent(action || 'me'); var opts = { method: isGet && !body ? 'GET' : 'POST', credentials: 'same-origin', headers: this._headers(!!body || !isGet) }; if (opts.method === 'POST') { var payload = body ? Object.assign({ action: action }, body) : { action: action }; opts.body = JSON.stringify(payload); } return fetch(url, opts).then(function (res) { return res.json().then(function (data) { data = data || {}; if (!res.ok && !data.error) { data.error = 'De server gaf ' + res.status; data.ok = false; } self._apply(data); return data; }, function () { var fail = { ok: false, error: 'Geen geldig antwoord van de server.' }; self.error = fail.error; return fail; }); }).catch(function (err) { var fail = { ok: false, error: 'Geen verbinding met de server.' }; self.error = fail.error; return fail; }); }; Online.refresh = function () { return this.request('me'); }; Online.testLogin = function (who) { return this.request('test_login', { user: who }); }; Online.createLobby = function (planetId) { return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') }); }; Online.joinLobby = function (code, planetId) { return this.request('lobby_join', { code: code, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') }); }; Online.setPlanet = function (planetId) { return this.request('lobby_set_planet', { planet_id: planetId }); }; Online.leaveLobby = function () { return this.request('lobby_leave'); }; Online.setReady = function (ready) { return this.request('lobby_ready', { ready: !!ready }); }; Online.startGame = function () { var self = this; var prev = this.lobby && this.lobby.status; return this.request('lobby_start').then(function (data) { self._handleTransitions(prev, data); return data; }); }; Online.queueShots = function (shots) { for (var i = 0; i < shots.length; i++) { this._pendingShots.push({ client_id: String(shots[i].id), color: shots[i].color, col: shots[i].col, y: shots[i].y }); } }; Online.poll = function (opts) { opts = opts || {}; var body = {}; if (opts.snapshot) { body.snapshot = opts.snapshot; } if (opts.score != null) { body.score = opts.score; } if (opts.eliminated) { body.eliminated = true; } if (this._pendingShots.length) { body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length); } var self = this; var prevStatus = this.lobby && this.lobby.status; return this.request('poll', body).then(function (data) { self._handleTransitions(prevStatus, data); if (self.onChange) { self.onChange(self); } return data; }); }; Online._handleTransitions = function (prevStatus, data) { var lobby = this.lobby; var status = lobby && lobby.status; if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart) { this.onGameStart(lobby); } if (data && data.incoming && data.incoming.length && this.onIncoming) { this.onIncoming(data.incoming); } // Own outgoing results (immediate) and lobby-wide recent flights // (so every client can draw opponent and enemy-to-enemy arcs, t1125). var flights = []; if (data && data.shot_results && data.shot_results.length) { flights = flights.concat(data.shot_results); } if (data && data.shot_flights && data.shot_flights.length) { flights = flights.concat(data.shot_flights); } if (flights.length) { this.spawnFlights(flights, this._flightLocals); } if (status === 'finished' && prevStatus !== 'finished' && this.onFinished) { this.onFinished(lobby); } if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn) { this.onLobbyReturn(lobby); } }; Online.startPolling = function (getPayload) { this.stopPolling(); var self = this; var tick = function () { var payload = getPayload ? getPayload() : {}; self.poll(payload); }; tick(); this._timer = setInterval(tick, this.POLL_MS); }; Online.stopPolling = function () { if (this._timer) { clearInterval(this._timer); this._timer = null; } }; Online.loginUrl = function () { return 'auth.php'; }; Online.logoutUrl = function () { return 'logout.php'; }; Online.opponents = function () { if (!this.lobby || !this.lobby.players) { return []; } return this.lobby.players.filter(function (p) { return !p.is_me; }); }; Online.aliveOpponents = function () { return this.opponents().filter(function (p) { return !p.eliminated; }); }; Online.mePlayer = function () { if (!this.lobby || !this.lobby.players) { return null; } for (var i = 0; i < this.lobby.players.length; i++) { if (this.lobby.players[i].is_me) { return this.lobby.players[i]; } } return null; }; /* ---------- miniatures --------------------------------------------- */ Online.renderMinis = function (container) { if (!container) { return; } var opponents = this.opponents(); var existing = {}; var kids = container.querySelectorAll('[data-player]'); for (var i = 0; i < kids.length; i++) { existing[kids[i].getAttribute('data-player')] = kids[i]; } var seen = Object.create(null); for (var i = 0; i < opponents.length; i++) { var p = opponents[i]; seen[p.id] = true; var el = existing[p.id]; if (!el) { el = document.createElement('div'); el.className = 'mini'; el.setAttribute('data-player', p.id); el.innerHTML = '
' + '' + ''; container.appendChild(el); } var mz = (typeof app !== 'undefined' && app.miniLayout && app.miniLayout.mini) ? app.miniLayout.mini : { w: 80, h: 104 }; var canvas = el.querySelector('canvas'); if (canvas && (canvas.width !== mz.w || canvas.height !== mz.h)) { canvas.width = mz.w; canvas.height = mz.h; } if (canvas) { canvas.style.width = mz.w + 'px'; canvas.style.height = mz.h + 'px'; } el.classList.toggle('eliminated', !!p.eliminated); el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : ''); el.querySelector('.mini-meta').textContent = p.eliminated ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : '')) : ('Punten ' + (p.score || 0)); this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet); } for (var id in existing) { if (!seen[id]) { existing[id].remove(); } } if (typeof applyMinisLayout === 'function') { applyMinisLayout(); } }; var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4']; function miniColor (planet, color) { if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex) { return planet.colors[color].hex; } return MINI_COLORS[color] || '#888'; } Online._drawMini = function (canvas, snapshot, planet) { if (!canvas) { return; } var ctx = canvas.getContext('2d'); var w = 10; var h = 13; var tw = canvas.width / w; var th = canvas.height / h; ctx.fillStyle = '#0c1020'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = 'rgba(255,255,255,0.06)'; ctx.lineWidth = 1; for (var c = 0; c <= w; c++) { ctx.beginPath(); ctx.moveTo(c * tw + 0.5, 0); ctx.lineTo(c * tw + 0.5, canvas.height); ctx.stroke(); } for (var r = 0; r <= h; r++) { ctx.beginPath(); ctx.moveTo(0, r * th + 0.5); ctx.lineTo(canvas.width, r * th + 0.5); ctx.stroke(); } if (!snapshot || !snapshot.blocks) { return; } // t1123: cheap sine pulse behind blocks of nearly-full columns. if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot) { var warns = GameCore.warnColumnsFromSnapshot(snapshot); var pulse = GameCore.columnWarnPulse(); for (var wc = 0; wc < warns.length; wc++) { if (!warns[wc]) { continue; } ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')'; ctx.fillRect(wc * tw, 0, tw, canvas.height); } } var blocks = snapshot.blocks; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; var x = b.col * tw; var y = canvas.height - (b.y + 1) * th; if (b.state === 'locked') { ctx.fillStyle = '#3a3d4a'; } else if (b.color < 0) { ctx.fillStyle = '#5a5d66'; } else { ctx.fillStyle = miniColor(planet, b.color); } ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1); } }; Online.miniElement = function (playerId) { return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]'); }; /* ---------- flight tweens ------------------------------------------ */ function colorSpriteUrl (color, planetId) { if (color < 0) { return 'images/block-gray.png'; } var planet = null; if (typeof Planet !== 'undefined') { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); } if (planet && planet.colors && planet.colors[color] && planet.colors[color].image) { return planet.colors[color].image; } return 'images/block-gray.png'; } /** * Animate shot results. `locals` is a map of client_id → {col, y, color, * startX, startY} in viewport pixels, filled by the view just after * consumeOutgoingShots. */ Online.playerId = function () { if (typeof app !== 'undefined' && app.offline) { return 'player'; } if (this.lobby && this.lobby.players) { for (var i = 0; i < this.lobby.players.length; i++) { if (this.lobby.players[i].is_me) { return this.lobby.players[i].id; } } } return 'player'; }; /** * Classify a shot for visual treatment (t1125). * player-to-enemy, enemy-to-player, enemy-to-enemy, * player-miss, enemy-miss. */ Online.flightKind = function (fromId, targetId, miss) { var me = this.playerId(); var fromMe = !fromId || fromId === me || fromId === 'player'; if (miss) { return fromMe ? 'player-miss' : 'enemy-miss'; } if (fromMe) { return 'player-to-enemy'; } if (targetId === me || targetId === 'player') { return 'enemy-to-player'; } return 'enemy-to-enemy'; }; /** * Parabolic arc: linear in x, a rise of `height` pixels above the * chord at mid-flight (screen y grows downward, so we subtract). */ Online.arcPoint = function (start, end, u, height) { var t = u < 0 ? 0 : (u > 1 ? 1 : u); var x = start.x + (end.x - start.x) * t; var y = start.y + (end.y - start.y) * t - 4 * height * t * (1 - t); return { x: x, y: y }; }; Online.arcHeight = function (start, end) { var dx = end.x - start.x; var dy = end.y - start.y; var dist = Math.sqrt(dx * dx + dy * dy); return Math.max(48, Math.min(220, dist * 0.28)); }; Online.easeInOutCubic = function (t) { if (t < 0.5) { return 4 * t * t * t; } var u = -2 * t + 2; return 1 - (u * u * u) / 2; }; Online._miniCellSize = function (playerId) { var el = this.miniElement(playerId); var canvas = el && el.querySelector('canvas'); if (canvas) { var r = canvas.getBoundingClientRect(); return Math.max(6, r.width / 10); } return 10; }; Online._fullTileSize = function () { if (typeof app !== 'undefined' && app.tile) { return app.tile; } return 40; }; Online._miniAnchor = function (playerId, dir) { var el = this.miniElement(playerId); var canvas = el && (el.querySelector ? el.querySelector('canvas') : null); var box = canvas || el; if (!box) { return { x: window.innerWidth / 2, y: 48 }; } var r = box.getBoundingClientRect(); if (dir === 'out') { return { x: r.left + r.width / 2, y: r.top + 4 }; } return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }; Online._fieldTop = function (col) { return this._flightStart(col); }; /** * Animate shot results. `locals` is a map of client_id → {col, y, color, * startX, startY, from_id} in viewport pixels. * * Visual-only (t1125): a parabolic arc whose scale goes from mini-cell * to full tile (or the reverse). Enemy-to-enemy arcs stay small and * are drawn behind the player's field. Delivery timing is unchanged; * a late-seen flight starts mid-arc via `age`. */ Online.spawnFlights = function (results, locals) { locals = locals || this._flightLocals || {}; var front = document.getElementById('flights'); var back = document.getElementById('flights-back') || front; if (!front) { return; } if (!this._flightSeen) { this._flightSeen = Object.create(null); } var now = performance.now(); var full = this._fullTileSize(); for (var i = 0; i < results.length; i++) { var r = results[i]; var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i))); if (this._flightSeen[sid]) { continue; } this._flightSeen[sid] = now; var meta = locals[r.client_id] || locals[sid] || {}; var fromId = r.from_id || r.from_user || meta.from_id || null; var targetId = r.target_id != null ? r.target_id : r.to_user; var miss = !!r.miss; var kind = this.flightKind(fromId, targetId, miss); var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000; if (r.age != null && isFinite(r.age) && r.age * 1000 >= duration) { continue; } var start; if (meta.startX != null && isFinite(meta.startX)) { start = { x: meta.startX, y: meta.startY }; } else if (kind === 'player-to-enemy' || kind === 'player-miss') { start = this._flightStart(meta.col != null ? meta.col : r.col); } else { start = this._miniAnchor(fromId, 'out'); } var end; if (miss) { end = this._missEnd(start, kind === 'enemy-miss'); } else if (kind === 'enemy-to-player') { end = this._fieldTop(null); } else { end = this._targetEnd(targetId, start); } var startScale; var endScale; var mini = this._miniCellSize(fromId || targetId) / full; if (mini < 0.12) { mini = 0.2; } if (kind === 'player-to-enemy') { startScale = 1; endScale = mini; } else if (kind === 'enemy-to-player') { startScale = mini; endScale = 1; } else if (kind === 'enemy-to-enemy') { startScale = mini; endScale = mini; } else if (kind === 'enemy-miss') { startScale = mini; endScale = 0; } else { startScale = 1; endScale = 0; } var layer = (kind === 'enemy-to-enemy' && back) ? back : front; var el = document.createElement('img'); el.src = colorSpriteUrl(r.color != null ? r.color : meta.color); el.alt = ''; el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : ''); el.style.width = full + 'px'; el.style.height = full + 'px'; layer.appendChild(el); var t0 = now; if (r.age != null && isFinite(r.age) && r.age > 0) { var u0 = Math.min(0.95, (r.age * 1000) / duration); t0 = now - u0 * duration; } var height = miss ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35)) : this.arcHeight(start, end); this._flights.push({ el: el, start: start, end: end, ctrl: miss ? this._missCtrl(start, end) : null, height: height, t0: t0, duration: duration, spin: (Math.random() * 2 - 1) * 720, miss: miss, kind: kind, startScale: startScale, endScale: endScale, angle: Math.random() * 360, id: sid }); } this._flightLocals = {}; }; Online.rememberFlightLocal = function (shot, startX, startY) { if (!this._flightLocals) { this._flightLocals = {}; } this._flightLocals[String(shot.id)] = { col: shot.col, y: shot.y, color: shot.color, startX: startX, startY: startY, from_id: shot.from_id }; }; Online._flightStart = function (col) { var appRef = typeof app !== 'undefined' ? app : null; if (appRef && appRef.scene && appRef.scene.canvas) { var canvas = appRef.scene.canvas; var rect = canvas.getBoundingClientRect(); var c = col == null ? 4.5 : col; return { x: rect.left + (c + 0.5) * (rect.width / 10), y: rect.top + 4 }; } var field = document.querySelector('canvas'); if (field) { var rect = field.getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top }; } return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 }; }; Online._targetEnd = function (targetId, start) { var el = targetId && this.miniElement(targetId); if (el) { var canvas = el.querySelector('canvas') || el; var r = canvas.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; } return { x: start.x + (Math.random() - 0.5) * 80, y: 40 }; }; Online._missEnd = function (start, fromMini) { var w = window.innerWidth || 800; var outward; if (start.x < w * 0.4) { outward = -(80 + Math.random() * w * 0.25); } else if (start.x > w * 0.6) { outward = (80 + Math.random() * w * 0.25); } else { outward = (Math.random() * 2 - 1) * w * 0.35; } var lift = fromMini ? (80 + Math.random() * 160) : (120 + Math.random() * 220); return { x: start.x + outward, y: start.y - lift }; }; Online._missCtrl = function (start, end) { return { x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160, y: Math.min(start.y, end.y) - 40 - Math.random() * 80 }; }; Online._hitCtrl = function (start, end) { return { x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40, y: (start.y + end.y) / 2 - 30 }; }; Online.tickFlights = function (now) { now = now || performance.now(); var leftover = []; for (var i = 0; i < this._flights.length; i++) { var f = this._flights[i]; var raw = (now - f.t0) / f.duration; if (raw >= 1) { if (f.el && f.el.parentNode) { f.el.parentNode.removeChild(f.el); } continue; } if (raw < 0) { raw = 0; } var u = this.easeInOutCubic(raw); var x, y; if (f.miss && f.ctrl) { var e = raw * raw; var mt = 1 - e; x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x; y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y; } else { var pt = this.arcPoint(f.start, f.end, u, f.height || 80); x = pt.x; y = pt.y; } var scale = f.startScale + (f.endScale - f.startScale) * u; if (f.miss) { var fadeU = raw * raw; scale = f.startScale * (1 - fadeU); } var angle = f.angle + f.spin * raw; f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate(' + angle + 'deg) scale(' + scale + ')'; f.el.style.opacity = f.miss ? String(Math.max(0, 1 - raw * raw)) : '1'; leftover.push(f); } this._flights = leftover; if (this._flightSeen) { var cutoff = now - 8000; var ids = Object.keys(this._flightSeen); for (var k = 0; k < ids.length; k++) { if (this._flightSeen[ids[k]] < cutoff) { delete this._flightSeen[ids[k]]; } } } }; Online.clearFlights = function () { for (var i = 0; i < this._flights.length; i++) { var el = this._flights[i].el; if (el && el.parentNode) { el.parentNode.removeChild(el); } } this._flights = []; this._flightLocals = {}; this._flightSeen = Object.create(null); }; if (typeof globalThis !== 'undefined') { globalThis.Online = Online; } if (typeof module !== 'undefined' && module.exports) { module.exports = Online; }