BlueGit

projects-timfalken-com meteors

Files

meteors / src / main.js

main.js

main.js 12.6 KiB Download Raw
1'use strict';
2
3/**
4 * View and input for Meteors. The simulation lives in GameCore; this file
5 * only draws it, scales it to the viewport, and translates pointer events
6 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
7 * that reuses the same core.
8 */
9
10var IMAGES = [
11 { name: 'ember', url: 'images/block-ember.png' },
12 { name: 'aqua', url: 'images/block-aqua.png' },
13 { name: 'leaf', url: 'images/block-leaf.png' },
14 { name: 'sun', url: 'images/block-sun.png' },
15 { name: 'orchid', url: 'images/block-orchid.png' },
16 { name: 'gray', url: 'images/block-gray.png' },
17 { name: 'locked', url: 'images/block-locked.png' },
18 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
19 { name: 'cell', url: 'images/cell.png' },
20 { name: 'pixel', url: 'images/pixel.png' }
21];
22
23var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
24var GAME_OVER_DELAY = 2;
25
26var game = new Game();
27var app = {
28 mode: 'menu',
29 core: null,
30 scene: null,
31 manager: null,
32 planet: null,
33 lastScore: 0,
34 tile: 48,
35 fieldX: 0,
36 fieldY: 0,
37 fieldW: 0,
38 fieldH: 0,
39 hudH: 56,
40 sprites: Object.create(null),
41 flames: Object.create(null),
42 cells: [],
43 pointerId: null,
44 gameOverShown: false,
45 selectTween: null
46};
47
48window.onload = function ()
49{
50 var play = document.getElementById('btn-play');
51 play.addEventListener('click', onPlay);
52 play.addEventListener('pointerup', function (e)
53 {
54 // A touch-friendly path: some mobile browsers swallow the click
55 // after a slightly sloppy tap. Ignore the following click.
56 if (e.pointerType === 'touch' || e.pointerType === 'pen')
57 {
58 e.preventDefault();
59 onPlay();
60 }
61 });
62
63 game.preloadImagesThenStart(IMAGES, function ()
64 {
65 if (game.images.flame && game.images.flame.addAnimationCycle)
66 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
67 });
68};
69
70function onPlay ()
71{
72 if (app.mode === 'playing')
73 { return; }
74 startPlay();
75}
76
77function startPlay ()
78{
79 hideEl('menu');
80 hideEl('game-over');
81 showEl('hud');
82
83 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
84 app.core = new GameCore(app.planet, Math.random);
85 app.mode = 'playing';
86 app.gameOverShown = false;
87 app.sprites = Object.create(null);
88 app.flames = Object.create(null);
89 app.cells = [];
90 app.pointerId = null;
91 app.selectTween = null;
92
93 layout();
94 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
95 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
96 app.scene.renderBackground = true;
97 game.loadScene(app.scene);
98
99 buildCells();
100 app.manager = app.scene.addObject(makeManager());
101 bindPointer(app.scene.canvas);
102 refreshHud();
103}
104
105function returnToMenu ()
106{
107 unbindPointer();
108 if (app.scene)
109 {
110 app.scene.destroy();
111 app.scene = null;
112 }
113 app.manager = null;
114 app.core = null;
115 app.mode = 'menu';
116 app.sprites = Object.create(null);
117 app.flames = Object.create(null);
118 app.cells = [];
119 app.selectTween = null;
120
121 hideEl('hud');
122 hideEl('game-over');
123 showEl('menu');
124 var last = document.getElementById('last-score');
125 if (app.lastScore > 0)
126 {
127 last.hidden = false;
128 last.querySelector('strong').textContent = String(app.lastScore);
129 }
130}
131
132function buildCells ()
133{
134 if (!app.scene)
135 { return; }
136 var img = game.images.cell;
137 for (var row = 0; row < 13; row++)
138 {
139 for (var col = 0; col < 10; col++)
140 {
141 var obj = new GameObject(0, 0, img, 0);
142 placeTile(obj, col, row);
143 obj.renderer.alpha = 0.9;
144 app.scene.addObject(obj);
145 app.cells.push(obj);
146 }
147 }
148}
149
150function placeTile (obj, col, y)
151{
152 var t = app.tile;
153 obj.transform.position.x = col * t + t / 2;
154 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
155 obj.transform.size = { x: t, y: t };
156}
157
158function layout ()
159{
160 var vw = window.innerWidth || 320;
161 var vh = window.innerHeight || 480;
162 var safeTop = 0;
163 try
164 {
165 // env(safe-area) is a CSS thing; keep a conservative HUD height.
166 safeTop = 0;
167 }
168 catch (e) { /* ignore */ }
169 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
170 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
171 var availW = Math.max(80, vw - margin * 2);
172 var availH = Math.max(80, vh - app.hudH - margin);
173 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
174 app.fieldW = app.tile * 10;
175 app.fieldH = app.tile * 13;
176 app.fieldX = Math.floor((vw - app.fieldW) / 2);
177 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
178 if (app.fieldY < app.hudH)
179 { app.fieldY = app.hudH; }
180
181 if (app.scene)
182 {
183 app.scene.position.x = app.fieldX;
184 app.scene.position.y = app.fieldY;
185 app.scene.size.x = app.fieldW;
186 app.scene.size.y = app.fieldH;
187 }
188}
189
190function spriteFor (block)
191{
192 if (block.state === 'locked')
193 { return game.images.locked; }
194 if (block.color < 0)
195 { return game.images.gray; }
196 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
197}
198
199function syncSprites ()
200{
201 if (!app.core || !app.scene)
202 { return; }
203 var seen = Object.create(null);
204 var blocks = app.core.blocks;
205 for (var i = 0; i < blocks.length; i++)
206 {
207 var block = blocks[i];
208 seen[block.id] = true;
209 var obj = app.sprites[block.id];
210 if (!obj)
211 {
212 obj = new GameObject(0, 0, spriteFor(block), 2);
213 app.scene.addObject(obj);
214 app.sprites[block.id] = obj;
215 }
216 obj.renderer.sprite = spriteFor(block);
217 placeTile(obj, block.col, block.y);
218 applyBlockVisual(obj, block);
219 obj.renderer.visible = true;
220 obj.renderer.alpha = 1;
221
222 if (block.flame)
223 {
224 var flame = app.flames[block.id];
225 if (!flame)
226 {
227 flame = new GameObject(0, 0, game.images.flame, 1);
228 flame.renderer.setAnimation('burn', 0, 0.08);
229 app.scene.addObject(flame);
230 app.flames[block.id] = flame;
231 }
232 flame.renderer.visible = true;
233 var t = app.tile;
234 flame.transform.position.x = block.col * t + t / 2;
235 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
236 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
237 }
238 else if (app.flames[block.id])
239 { app.flames[block.id].renderer.visible = false; }
240 }
241
242 var ids = Object.keys(app.sprites);
243 for (var i = 0; i < ids.length; i++)
244 {
245 if (!seen[ids[i]])
246 {
247 app.sprites[ids[i]].destroy();
248 delete app.sprites[ids[i]];
249 if (app.flames[ids[i]])
250 {
251 app.flames[ids[i]].destroy();
252 delete app.flames[ids[i]];
253 }
254 }
255 }
256}
257
258function applyBlockVisual (obj, block)
259{
260 var t = app.tile;
261 var sx = 1;
262 var sy = 1;
263 var dy = 0;
264 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
265 && typeof Easing !== 'undefined' && Easing.bouncePose)
266 {
267 var u = block.bounceAge / app.planet.bounceDuration;
268 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
269 sx = pose.sx;
270 sy = pose.sy;
271 dy = pose.dy;
272 }
273 var sel = 1;
274 var tw = app.selectTween;
275 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
276 { sel = tw.scale; }
277 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
278 if (dy)
279 { obj.transform.position.y -= dy * t; }
280}
281
282function clickTween ()
283{
284 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
285}
286
287function startPressTween (blockId)
288{
289 var c = clickTween();
290 if (!c)
291 { return; }
292 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
293 app.selectTween = {
294 blockId: blockId,
295 from: from,
296 to: c.pressScale,
297 t: 0,
298 duration: c.pressDuration,
299 ease: c.pressEase,
300 scale: from,
301 phase: 'press'
302 };
303}
304
305function startReleaseTween ()
306{
307 var c = clickTween();
308 var tw = app.selectTween;
309 if (!c || !tw || tw.phase === 'idle')
310 { return; }
311 app.selectTween = {
312 blockId: tw.blockId,
313 from: tw.scale,
314 to: c.releaseScale,
315 t: 0,
316 duration: c.releaseDuration,
317 ease: c.releaseEase,
318 scale: tw.scale,
319 phase: 'release'
320 };
321}
322
323function updateSelectTween (dt)
324{
325 var tw = app.selectTween;
326 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
327 { return; }
328 tw.t += dt;
329 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
330 if (u >= 1)
331 {
332 tw.scale = tw.to;
333 tw.t = tw.duration;
334 if (tw.phase === 'press')
335 { tw.phase = 'hold'; }
336 else
337 {
338 tw.phase = 'idle';
339 tw.scale = 1;
340 tw.blockId = null;
341 }
342 return;
343 }
344 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
345 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
346}
347
348function refreshHud ()
349{
350 if (!app.core)
351 { return; }
352 document.getElementById('score').textContent = String(app.core.score);
353 var planet = app.planet;
354 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
355 var d = Planet.displayValues(planet);
356 document.getElementById('planet-stats').textContent =
357 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
358 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
359}
360
361function makeManager ()
362{
363 var obj = new GameObject(0, 0, game.images.pixel, 0);
364 obj.renderer.visible = false;
365 var base = obj.update.bind(obj);
366 obj.update = function (dt)
367 {
368 base(dt);
369 tickView(dt);
370 };
371 return obj;
372}
373
374function tickView (dt)
375{
376 if (app.mode !== 'playing' || !app.core)
377 { return; }
378
379 layout();
380 for (var i = 0; i < app.cells.length; i++)
381 {
382 var col = i % 10;
383 var row = Math.floor(i / 10);
384 placeTile(app.cells[i], col, row);
385 }
386
387 app.core.tick(dt);
388 updateSelectTween(dt);
389 syncSprites();
390 refreshHud();
391
392 if (app.core.state === 'gameover' && !app.gameOverShown)
393 {
394 app.gameOverShown = true;
395 app.lastScore = app.core.score;
396 document.getElementById('go-score').textContent = String(app.lastScore);
397 showEl('game-over');
398 }
399 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
400 { returnToMenu(); }
401}
402
403/* ---------- pointer input (mouse + touch) --------------------------- */
404/*
405 * Both mouse and touch use Pointer Events. After pointerdown we listen
406 * on window, so a drag that leaves the canvas (needed to launch a
407 * block at the top of a full column) still reaches moveDrag. We do
408 * not treat lostpointercapture as the end of a drag: on some touch
409 * browsers that fires mid-gesture and would cancel a launch.
410 */
411
412var boundCanvas = null;
413var windowListening = false;
414
415function addWindowPointer ()
416{
417 if (windowListening)
418 { return; }
419 window.addEventListener('pointermove', onPointerMove, true);
420 window.addEventListener('pointerup', onPointerUp, true);
421 window.addEventListener('pointercancel', onPointerUp, true);
422 windowListening = true;
423}
424
425function removeWindowPointer ()
426{
427 if (!windowListening)
428 { return; }
429 window.removeEventListener('pointermove', onPointerMove, true);
430 window.removeEventListener('pointerup', onPointerUp, true);
431 window.removeEventListener('pointercancel', onPointerUp, true);
432 windowListening = false;
433}
434
435function bindPointer (canvas)
436{
437 unbindPointer();
438 boundCanvas = canvas;
439 canvas.addEventListener('pointerdown', onPointerDown);
440 canvas.style.touchAction = 'none';
441 canvas.style.cursor = 'pointer';
442}
443
444function unbindPointer ()
445{
446 removeWindowPointer();
447 if (boundCanvas)
448 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
449 boundCanvas = null;
450 app.pointerId = null;
451}
452
453function fieldFromEvent (e)
454{
455 var canvas = app.scene && app.scene.canvas;
456 if (!canvas)
457 { return null; }
458 var rect = canvas.getBoundingClientRect();
459 if (rect.width <= 0 || rect.height <= 0)
460 { return null; }
461 var x = (e.clientX - rect.left) * (canvas.width / rect.width);
462 var y = (e.clientY - rect.top) * (canvas.height / rect.height);
463 var col = Math.floor(x / app.tile);
464 var fieldY = (canvas.height - y) / app.tile;
465 return { col: col, y: fieldY };
466}
467
468function onPointerDown (e)
469{
470 if (!app.core || app.core.state !== 'playing')
471 { return; }
472 if (app.pointerId != null)
473 { return; }
474 e.preventDefault();
475 app.pointerId = e.pointerId;
476 try
477 { boundCanvas.setPointerCapture(e.pointerId); }
478 catch (err) { /* ignore */ }
479 addWindowPointer();
480 var pos = fieldFromEvent(e);
481 if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
482 { startPressTween(app.core.drag.blockId); }
483}
484
485function onPointerMove (e)
486{
487 if (app.pointerId == null || e.pointerId !== app.pointerId)
488 { return; }
489 if (!app.core || !app.core.drag)
490 { return; }
491 e.preventDefault();
492 var pos = fieldFromEvent(e);
493 if (pos)
494 { app.core.moveDrag(pos.y); }
495}
496
497function onPointerUp (e)
498{
499 if (app.pointerId == null)
500 { return; }
501 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
502 { return; }
503 if (e)
504 { e.preventDefault(); }
505 app.pointerId = null;
506 removeWindowPointer();
507 if (boundCanvas)
508 {
509 try
510 { boundCanvas.releasePointerCapture(e && e.pointerId); }
511 catch (err) { /* ignore */ }
512 }
513 startReleaseTween();
514 if (app.core)
515 { app.core.endDrag(); }
516}
517
518function hideEl (id)
519{
520 document.getElementById(id).hidden = true;
521}
522
523function showEl (id)
524{
525 document.getElementById(id).hidden = false;
526}
527
528window.addEventListener('resize', function ()
529{
530 if (app.mode === 'playing')
531 { layout(); }
532});
533
534window.addEventListener('orientationchange', function ()
535{
536 setTimeout(function ()
537 {
538 if (app.mode === 'playing')
539 { layout(); }
540 }, 120);
541});