BlueGit

projects-timfalken-com meteors

Files

meteors / src / online.js

online.js

online.js 13.6 KiB Download Raw
1'use strict';
2
3/**
4 * Online play: talks to api.php (cookie session), polls lobby and game
5 * state, and draws opponent miniatures plus flying-block tweens.
6 * Real-time sync is not required; a 0.75 s poll is enough.
7 */
8
9var Online = {
10 POLL_MS: 750,
11 DEFAULT_MISS_CHANCE: 0.30,
12 FLIGHT_DURATION: 1.2,
13 configured: false,
14 local: false,
15 csrf: '',
16 me: null,
17 lobby: null,
18 incoming: [],
19 shotResults: [],
20 error: '',
21 _timer: null,
22 _pendingShots: [],
23 _flights: [],
24 _lastStatus: null,
25 onChange: null,
26 onGameStart: null,
27 onIncoming: null,
28 onFinished: null,
29 onLobbyReturn: null
30};
31
32Online._headers = function (json)
33{
34 var h = { 'Accept': 'application/json' };
35 if (json)
36 { h['Content-Type'] = 'application/json'; }
37 if (this.csrf)
38 { h['X-CSRF-Token'] = this.csrf; }
39 return h;
40};
41
42Online._apply = function (data)
43{
44 if (!data)
45 { return; }
46 if (typeof data.configured === 'boolean')
47 { this.configured = data.configured; }
48 if (typeof data.local === 'boolean')
49 { this.local = data.local; }
50 if (data.csrf)
51 { this.csrf = data.csrf; }
52 if (data.me !== undefined)
53 { this.me = data.me; }
54 if (data.lobby !== undefined)
55 { this.lobby = data.lobby; }
56 if (data.incoming)
57 { this.incoming = data.incoming; }
58 if (data.shot_results)
59 { this.shotResults = data.shot_results; }
60 if (data.miss_chance_default != null)
61 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
62 if (data.flight_duration != null)
63 { this.FLIGHT_DURATION = data.flight_duration; }
64 if (data.error)
65 { this.error = data.error; }
66 else if (data.ok)
67 { this.error = ''; }
68};
69
70Online.request = function (action, body)
71{
72 var self = this;
73 var isGet = action === 'me' || action === '';
74 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
75 var opts = {
76 method: isGet && !body ? 'GET' : 'POST',
77 credentials: 'same-origin',
78 headers: this._headers(!!body || !isGet)
79 };
80 if (opts.method === 'POST')
81 {
82 var payload = body ? Object.assign({ action: action }, body) : { action: action };
83 opts.body = JSON.stringify(payload);
84 }
85 return fetch(url, opts).then(function (res)
86 {
87 return res.json().then(function (data)
88 {
89 data = data || {};
90 if (!res.ok && !data.error)
91 { data.error = 'De server gaf ' + res.status; data.ok = false; }
92 self._apply(data);
93 return data;
94 }, function ()
95 {
96 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
97 self.error = fail.error;
98 return fail;
99 });
100 }).catch(function (err)
101 {
102 var fail = { ok: false, error: 'Geen verbinding met de server.' };
103 self.error = fail.error;
104 return fail;
105 });
106};
107
108Online.refresh = function ()
109{
110 return this.request('me');
111};
112
113Online.testLogin = function (who)
114{
115 return this.request('test_login', { user: who });
116};
117
118Online.createLobby = function (planetId)
119{
120 return this.request('lobby_create', {
121 miss_chance: this.DEFAULT_MISS_CHANCE,
122 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
123 });
124};
125
126Online.joinLobby = function (code, planetId)
127{
128 return this.request('lobby_join', {
129 code: code,
130 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
131 });
132};
133
134Online.setPlanet = function (planetId)
135{
136 return this.request('lobby_set_planet', { planet_id: planetId });
137};
138
139Online.leaveLobby = function ()
140{
141 return this.request('lobby_leave');
142};
143
144Online.setReady = function (ready)
145{
146 return this.request('lobby_ready', { ready: !!ready });
147};
148
149Online.startGame = function ()
150{
151 var self = this;
152 var prev = this.lobby && this.lobby.status;
153 return this.request('lobby_start').then(function (data)
154 {
155 self._handleTransitions(prev, data);
156 return data;
157 });
158};
159
160Online.queueShots = function (shots)
161{
162 for (var i = 0; i < shots.length; i++)
163 {
164 this._pendingShots.push({
165 client_id: String(shots[i].id),
166 color: shots[i].color,
167 col: shots[i].col,
168 y: shots[i].y
169 });
170 }
171};
172
173Online.poll = function (opts)
174{
175 opts = opts || {};
176 var body = {};
177 if (opts.snapshot)
178 { body.snapshot = opts.snapshot; }
179 if (opts.score != null)
180 { body.score = opts.score; }
181 if (opts.eliminated)
182 { body.eliminated = true; }
183 if (this._pendingShots.length)
184 {
185 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
186 }
187 var self = this;
188 var prevStatus = this.lobby && this.lobby.status;
189 return this.request('poll', body).then(function (data)
190 {
191 self._handleTransitions(prevStatus, data);
192 if (self.onChange)
193 { self.onChange(self); }
194 return data;
195 });
196};
197
198Online._handleTransitions = function (prevStatus, data)
199{
200 var lobby = this.lobby;
201 var status = lobby && lobby.status;
202 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
203 { this.onGameStart(lobby); }
204 if (data && data.incoming && data.incoming.length && this.onIncoming)
205 { this.onIncoming(data.incoming); }
206 if (data && data.shot_results && data.shot_results.length)
207 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
208 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
209 { this.onFinished(lobby); }
210 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
211 { this.onLobbyReturn(lobby); }
212};
213
214Online.startPolling = function (getPayload)
215{
216 this.stopPolling();
217 var self = this;
218 var tick = function ()
219 {
220 var payload = getPayload ? getPayload() : {};
221 self.poll(payload);
222 };
223 tick();
224 this._timer = setInterval(tick, this.POLL_MS);
225};
226
227Online.stopPolling = function ()
228{
229 if (this._timer)
230 {
231 clearInterval(this._timer);
232 this._timer = null;
233 }
234};
235
236Online.loginUrl = function ()
237{
238 return 'auth.php';
239};
240
241Online.logoutUrl = function ()
242{
243 return 'logout.php';
244};
245
246Online.opponents = function ()
247{
248 if (!this.lobby || !this.lobby.players)
249 { return []; }
250 return this.lobby.players.filter(function (p) { return !p.is_me; });
251};
252
253Online.aliveOpponents = function ()
254{
255 return this.opponents().filter(function (p) { return !p.eliminated; });
256};
257
258Online.mePlayer = function ()
259{
260 if (!this.lobby || !this.lobby.players)
261 { return null; }
262 for (var i = 0; i < this.lobby.players.length; i++)
263 {
264 if (this.lobby.players[i].is_me)
265 { return this.lobby.players[i]; }
266 }
267 return null;
268};
269
270/* ---------- miniatures --------------------------------------------- */
271
272Online.renderMinis = function (container)
273{
274 if (!container)
275 { return; }
276 var opponents = this.opponents();
277 var existing = {};
278 var kids = container.querySelectorAll('[data-player]');
279 for (var i = 0; i < kids.length; i++)
280 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
281
282 var seen = Object.create(null);
283 for (var i = 0; i < opponents.length; i++)
284 {
285 var p = opponents[i];
286 seen[p.id] = true;
287 var el = existing[p.id];
288 if (!el)
289 {
290 el = document.createElement('div');
291 el.className = 'mini';
292 el.setAttribute('data-player', p.id);
293 el.innerHTML = '<div class="mini-name"></div>'
294 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
295 + '<div class="mini-meta"></div>';
296 container.appendChild(el);
297 }
298 el.classList.toggle('eliminated', !!p.eliminated);
299 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
300 el.querySelector('.mini-meta').textContent = p.eliminated
301 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
302 : ('Punten ' + (p.score || 0));
303 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
304 }
305 for (var id in existing)
306 {
307 if (!seen[id])
308 { existing[id].remove(); }
309 }
310};
311
312var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
313
314function miniColor (planet, color)
315{
316 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
317 { return planet.colors[color].hex; }
318 return MINI_COLORS[color] || '#888';
319}
320
321
322Online._drawMini = function (canvas, snapshot, planet)
323{
324 if (!canvas)
325 { return; }
326 var ctx = canvas.getContext('2d');
327 var w = 10;
328 var h = 13;
329 var tw = canvas.width / w;
330 var th = canvas.height / h;
331 ctx.fillStyle = '#0c1020';
332 ctx.fillRect(0, 0, canvas.width, canvas.height);
333 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
334 ctx.lineWidth = 1;
335 for (var c = 0; c <= w; c++)
336 {
337 ctx.beginPath();
338 ctx.moveTo(c * tw + 0.5, 0);
339 ctx.lineTo(c * tw + 0.5, canvas.height);
340 ctx.stroke();
341 }
342 for (var r = 0; r <= h; r++)
343 {
344 ctx.beginPath();
345 ctx.moveTo(0, r * th + 0.5);
346 ctx.lineTo(canvas.width, r * th + 0.5);
347 ctx.stroke();
348 }
349 if (!snapshot || !snapshot.blocks)
350 { return; }
351 // t1123: cheap sine pulse behind blocks of nearly-full columns.
352 if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
353 {
354 var warns = GameCore.warnColumnsFromSnapshot(snapshot);
355 var pulse = GameCore.columnWarnPulse();
356 for (var wc = 0; wc < warns.length; wc++)
357 {
358 if (!warns[wc])
359 { continue; }
360 ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
361 ctx.fillRect(wc * tw, 0, tw, canvas.height);
362 }
363 }
364 var blocks = snapshot.blocks;
365 for (var i = 0; i < blocks.length; i++)
366 {
367 var b = blocks[i];
368 var x = b.col * tw;
369 var y = canvas.height - (b.y + 1) * th;
370 if (b.state === 'locked')
371 { ctx.fillStyle = '#3a3d4a'; }
372 else if (b.color < 0)
373 { ctx.fillStyle = '#5a5d66'; }
374 else
375 { ctx.fillStyle = miniColor(planet, b.color); }
376 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
377 }
378};
379
380Online.miniElement = function (playerId)
381{
382 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
383};
384
385/* ---------- flight tweens ------------------------------------------ */
386
387function colorSpriteUrl (color, planetId)
388{
389 if (color < 0)
390 { return 'images/block-gray.png'; }
391 var planet = null;
392 if (typeof Planet !== 'undefined')
393 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
394 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
395 { return planet.colors[color].image; }
396 return 'images/block-gray.png';
397}
398
399/**
400 * Animate shot results. `locals` is a map of client_id → {col, y, color,
401 * startX, startY} in viewport pixels, filled by the view just after
402 * consumeOutgoingShots.
403 */
404Online.spawnFlights = function (results, locals)
405{
406 locals = locals || this._flightLocals || {};
407 var layer = document.getElementById('flights');
408 if (!layer)
409 { return; }
410 for (var i = 0; i < results.length; i++)
411 {
412 var r = results[i];
413 var meta = locals[r.client_id] || {};
414 var start = this._flightStart(meta.col);
415 var end;
416 var miss = !!r.miss;
417 if (miss)
418 { end = this._missEnd(start); }
419 else
420 { end = this._targetEnd(r.target_id, start); }
421 var el = document.createElement('img');
422 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
423 el.alt = '';
424 el.className = 'flight';
425 layer.appendChild(el);
426 var spin = (Math.random() * 2 - 1) * 720;
427 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
428 this._flights.push({
429 el: el,
430 start: start,
431 end: end,
432 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
433 t0: performance.now(),
434 duration: duration,
435 spin: spin,
436 miss: miss,
437 angle: Math.random() * 360
438 });
439 }
440 this._flightLocals = {};
441};
442
443Online.rememberFlightLocal = function (shot, startX, startY)
444{
445 if (!this._flightLocals)
446 { this._flightLocals = {}; }
447 this._flightLocals[String(shot.id)] = {
448 col: shot.col,
449 y: shot.y,
450 color: shot.color,
451 startX: startX,
452 startY: startY
453 };
454};
455
456Online._flightStart = function (col)
457{
458 var field = document.querySelector('canvas');
459 var appRef = typeof app !== 'undefined' ? app : null;
460 if (appRef && appRef.scene && appRef.scene.canvas)
461 {
462 var canvas = appRef.scene.canvas;
463 var rect = canvas.getBoundingClientRect();
464 var c = col == null ? 4.5 : col;
465 return {
466 x: rect.left + (c + 0.5) * (rect.width / 10),
467 y: rect.top + 4
468 };
469 }
470 if (field)
471 {
472 var rect = field.getBoundingClientRect();
473 return { x: rect.left + rect.width / 2, y: rect.top };
474 }
475 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
476};
477
478Online._targetEnd = function (targetId, start)
479{
480 var el = targetId && this.miniElement(targetId);
481 if (el)
482 {
483 var r = el.getBoundingClientRect();
484 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
485 }
486 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
487};
488
489Online._missEnd = function (start)
490{
491 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
492 return {
493 x: start.x + dx,
494 y: start.y - (120 + Math.random() * 220)
495 };
496};
497
498Online._missCtrl = function (start, end)
499{
500 return {
501 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
502 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
503 };
504};
505
506Online._hitCtrl = function (start, end)
507{
508 return {
509 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
510 y: (start.y + end.y) / 2 - 30
511 };
512};
513
514Online.tickFlights = function (now)
515{
516 now = now || performance.now();
517 var leftover = [];
518 for (var i = 0; i < this._flights.length; i++)
519 {
520 var f = this._flights[i];
521 var u = (now - f.t0) / f.duration;
522 if (u >= 1)
523 {
524 if (f.el && f.el.parentNode)
525 { f.el.parentNode.removeChild(f.el); }
526 continue;
527 }
528 // Quadratic bezier, ease-in so they feel like they recede.
529 var e = u * u;
530 var mt = 1 - e;
531 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
532 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
533 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
534 var angle = f.angle + f.spin * u;
535 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
536 + angle + 'deg) scale(' + scale + ')';
537 f.el.style.opacity = f.miss ? String(1 - e) : '1';
538 leftover.push(f);
539 }
540 this._flights = leftover;
541};
542
543Online.clearFlights = function ()
544{
545 for (var i = 0; i < this._flights.length; i++)
546 {
547 var el = this._flights[i].el;
548 if (el && el.parentNode)
549 { el.parentNode.removeChild(el); }
550 }
551 this._flights = [];
552 this._flightLocals = {};
553};
554
555if (typeof globalThis !== 'undefined')
556{ globalThis.Online = Online; }
557if (typeof module !== 'undefined' && module.exports)
558{ module.exports = Online; }