BlueGit

projects-timfalken-com meteors

Merge branch 'feature/t1139-planet-designer'

Planet Designer for logged-in players (lifetime points, unlockable
blocks, custom planets) and custom planets in every mode's picker
(t1139, t1140).

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
e23622d9963950be382c1b57d35290f8d974ff5a
Pipeline
Passed
63 files changed +6021 −40
README.md +28 −0
@@ -56,6 +56,10 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
56 56 | Pad | Rol |
57 57 | --- | --- |
58 58 | `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce |
59 | `src/blocks.js` | Append-only blokjesregister, drempels, ontgrendeling |
60 | `src/designer.js` | Planeetontwerper (lijst, bewerken, blokjes-modal) |
61 | `server/lib/blocks.json` | Blokjesregister (JS en PHP delen dit bestand) |
62 | `server/lib/Blocks.php` | Server-kant van het register en de drempels |
59 63 | `src/rng.js` | Seedable RNG (tests en later replays) |
60 64 | `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |
61 65 | `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
@@ -111,6 +115,30 @@ staan in `server/lib/planets.json`. De blokplaatjes zijn unieke
111 115 placeholders (`build/images/block-{planeet}-{kleur}.png`); Tim kan ze
112 116 zelf vervangen.
113 117
118 ## Planeetontwerper
119
120 Ingelogde spelers zien op het hoofdmenu hun puntentotaal en de knop
121 **Planeetontwerper**. Punten verzamel je door ingelogd te spelen
122 (solo aan het einde, elke ronde van Offline Strijd, en Online bij
123 uitschakeling). Ze worden niet uitgegeven: bij vaste drempels (Terra
124 gratis, daarna 500 punten en elke volgende 14,5 % hoger) ontgrendel
125 je extra blokjes.
126
127 In de ontwerper maak, bewerk of verwijder je eigen planeten (naam,
128 bevolking, de drie sliders voor zwaartekracht / lucht / massa, en
129 een live Power-preview met dezelfde formule als in het spel). Vijf
130 blokjesvakjes openen een raster van het hele register: blokjes die
131 al in een ander vak zitten zijn grijs, vergrendelde blokjes zijn
132 grijs mét een slotje.
133
134 Eigen planeten kun je in **elke** modus kiezen (Spelen, Offline
135 Strijd, Online). Online valideert de server de configuratie en
136 deelt een snapshot met de andere spelers.
137
138 Lokaal inloggen: `auth.php?test=1`. Op de live site blijft de
139 ontwerper verborgen tot OAuth (`callback.php` + CI-geheim
140 `auth_client_secret`) is ingesteld.
141
114 142 ## Deploy
115 143
116 144 BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.
@@ -56,6 +56,10 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
56| Pad | Rol |
56| Pad | Rol |
57| --- | --- |
57| --- | --- |
58| `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce |
58| `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce |
59| `src/blocks.js` | Append-only blokjesregister, drempels, ontgrendeling |
60| `src/designer.js` | Planeetontwerper (lijst, bewerken, blokjes-modal) |
61| `server/lib/blocks.json` | Blokjesregister (JS en PHP delen dit bestand) |
62| `server/lib/Blocks.php` | Server-kant van het register en de drempels |
59| `src/rng.js` | Seedable RNG (tests en later replays) |
63| `src/rng.js` | Seedable RNG (tests en later replays) |
60| `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |
64| `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |
61| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
65| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
@@ -111,6 +115,30 @@ staan in `server/lib/planets.json`. De blokplaatjes zijn unieke
111placeholders (`build/images/block-{planeet}-{kleur}.png`); Tim kan ze
115placeholders (`build/images/block-{planeet}-{kleur}.png`); Tim kan ze
112zelf vervangen.
116zelf vervangen.
113
117
118## Planeetontwerper
119
120Ingelogde spelers zien op het hoofdmenu hun puntentotaal en de knop
121**Planeetontwerper**. Punten verzamel je door ingelogd te spelen
122(solo aan het einde, elke ronde van Offline Strijd, en Online bij
123uitschakeling). Ze worden niet uitgegeven: bij vaste drempels (Terra
124gratis, daarna 500 punten en elke volgende 14,5 % hoger) ontgrendel
125je extra blokjes.
126
127In de ontwerper maak, bewerk of verwijder je eigen planeten (naam,
128bevolking, de drie sliders voor zwaartekracht / lucht / massa, en
129een live Power-preview met dezelfde formule als in het spel). Vijf
130blokjesvakjes openen een raster van het hele register: blokjes die
131al in een ander vak zitten zijn grijs, vergrendelde blokjes zijn
132grijs mét een slotje.
133
134Eigen planeten kun je in **elke** modus kiezen (Spelen, Offline
135Strijd, Online). Online valideert de server de configuratie en
136deelt een snapshot met de andere spelers.
137
138Lokaal inloggen: `auth.php?test=1`. Op de live site blijft de
139ontwerper verborgen tot OAuth (`callback.php` + CI-geheim
140`auth_client_secret`) is ingesteld.
141
114## Deploy
142## Deploy
115
143
116BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.
144BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.
build/game.js +1773 −12
@@ -187,6 +187,839 @@ var PLANET_CATALOG = {
187 187 ]
188 188 }
189 189 ;
190 var BLOCK_REGISTRY = {
191 "_comment": "Append-only block registry. Never reorder, rename ids, or insert in the middle. New blocks go at the end. The first five (Terra) are unlocked by default; index 5 requires 500 lifetime points, each next index requires 14.5% more (rounded).",
192 "terraCount": 5,
193 "firstThreshold": 500,
194 "thresholdGrowth": 1.145,
195 "blocks": [
196 {
197 "id": "terra-ember",
198 "name": "Ember",
199 "hex": "#e85d3a",
200 "shape": "triangle",
201 "image": "images/block-terra-ember.png",
202 "terra": true
203 },
204 {
205 "id": "terra-aqua",
206 "name": "Aqua",
207 "hex": "#3db8e8",
208 "shape": "circle",
209 "image": "images/block-terra-aqua.png",
210 "terra": true
211 },
212 {
213 "id": "terra-leaf",
214 "name": "Leaf",
215 "hex": "#4cbf4c",
216 "shape": "square",
217 "image": "images/block-terra-leaf.png",
218 "terra": true
219 },
220 {
221 "id": "terra-sun",
222 "name": "Sun",
223 "hex": "#f0c53a",
224 "shape": "diamond",
225 "image": "images/block-terra-sun.png",
226 "terra": true
227 },
228 {
229 "id": "terra-orchid",
230 "name": "Orchid",
231 "hex": "#c45ad4",
232 "shape": "star",
233 "image": "images/block-terra-orchid.png",
234 "terra": true
235 },
236 {
237 "id": "rune-fehu",
238 "name": "Fehu",
239 "hex": "#e8a44a",
240 "shape": "rune_fehu",
241 "image": "images/block-rune-fehu.png",
242 "terra": false
243 },
244 {
245 "id": "rune-ansuz",
246 "name": "Ansuz",
247 "hex": "#6ab0e8",
248 "shape": "rune_ansuz",
249 "image": "images/block-rune-ansuz.png",
250 "terra": false
251 },
252 {
253 "id": "rune-thurisaz",
254 "name": "Thurisaz",
255 "hex": "#c05040",
256 "shape": "rune_thurisaz",
257 "image": "images/block-rune-thurisaz.png",
258 "terra": false
259 },
260 {
261 "id": "rune-raido",
262 "name": "Raido",
263 "hex": "#d0c070",
264 "shape": "rune_raido",
265 "image": "images/block-rune-raido.png",
266 "terra": false
267 },
268 {
269 "id": "rune-sowilo",
270 "name": "Sowilo",
271 "hex": "#f0d040",
272 "shape": "rune_sowilo",
273 "image": "images/block-rune-sowilo.png",
274 "terra": false
275 },
276 {
277 "id": "rune-algiz",
278 "name": "Algiz",
279 "hex": "#80d0a0",
280 "shape": "rune_algiz",
281 "image": "images/block-rune-algiz.png",
282 "terra": false
283 },
284 {
285 "id": "arrow-up",
286 "name": "Arrow",
287 "hex": "#f07040",
288 "shape": "arrow",
289 "image": "images/block-arrow-up.png",
290 "terra": false
291 },
292 {
293 "id": "arrow-chevron",
294 "name": "Chevron",
295 "hex": "#50c0e0",
296 "shape": "chevron",
297 "image": "images/block-arrow-chevron.png",
298 "terra": false
299 },
300 {
301 "id": "arrow-double",
302 "name": "Double Arrow",
303 "hex": "#e05080",
304 "shape": "double_arrow",
305 "image": "images/block-arrow-double.png",
306 "terra": false
307 },
308 {
309 "id": "arrow-return",
310 "name": "Return",
311 "hex": "#a080e0",
312 "shape": "return_arrow",
313 "image": "images/block-arrow-return.png",
314 "terra": false
315 },
316 {
317 "id": "fig-person",
318 "name": "Figure",
319 "hex": "#f0c0a0",
320 "shape": "person",
321 "image": "images/block-fig-person.png",
322 "terra": false
323 },
324 {
325 "id": "fig-walker",
326 "name": "Walker",
327 "hex": "#c09070",
328 "shape": "walker",
329 "image": "images/block-fig-walker.png",
330 "terra": false
331 },
332 {
333 "id": "fig-hero",
334 "name": "Hero",
335 "hex": "#e8b070",
336 "shape": "hero",
337 "image": "images/block-fig-hero.png",
338 "terra": false
339 },
340 {
341 "id": "face-smile",
342 "name": "Smile",
343 "hex": "#f0d060",
344 "shape": "smile",
345 "image": "images/block-face-smile.png",
346 "terra": false
347 },
348 {
349 "id": "face-wink",
350 "name": "Wink",
351 "hex": "#f0a050",
352 "shape": "wink",
353 "image": "images/block-face-wink.png",
354 "terra": false
355 },
356 {
357 "id": "face-cool",
358 "name": "Cool",
359 "hex": "#6090d0",
360 "shape": "cool",
361 "image": "images/block-face-cool.png",
362 "terra": false
363 },
364 {
365 "id": "face-grin",
366 "name": "Grin",
367 "hex": "#f0c848",
368 "shape": "grin",
369 "image": "images/block-face-grin.png",
370 "terra": false
371 },
372 {
373 "id": "icon-heart",
374 "name": "Heart",
375 "hex": "#e04060",
376 "shape": "heart",
377 "image": "images/block-icon-heart.png",
378 "terra": false
379 },
380 {
381 "id": "icon-moon",
382 "name": "Moon",
383 "hex": "#d0d8f0",
384 "shape": "crescent",
385 "image": "images/block-icon-moon.png",
386 "terra": false
387 },
388 {
389 "id": "icon-bolt",
390 "name": "Bolt",
391 "hex": "#f0e050",
392 "shape": "lightning",
393 "image": "images/block-icon-bolt.png",
394 "terra": false
395 },
396 {
397 "id": "icon-shield",
398 "name": "Shield",
399 "hex": "#5080c0",
400 "shape": "shield",
401 "image": "images/block-icon-shield.png",
402 "terra": false
403 },
404 {
405 "id": "icon-crown",
406 "name": "Crown",
407 "hex": "#f0c030",
408 "shape": "crown",
409 "image": "images/block-icon-crown.png",
410 "terra": false
411 },
412 {
413 "id": "icon-eye",
414 "name": "Eye",
415 "hex": "#70d0c0",
416 "shape": "eye",
417 "image": "images/block-icon-eye.png",
418 "terra": false
419 },
420 {
421 "id": "icon-star6",
422 "name": "Hexastar",
423 "hex": "#f0e8a0",
424 "shape": "star6",
425 "image": "images/block-icon-star6.png",
426 "terra": false
427 },
428 {
429 "id": "icon-spiral",
430 "name": "Spiral",
431 "hex": "#c070d0",
432 "shape": "spiral",
433 "image": "images/block-icon-spiral.png",
434 "terra": false
435 },
436 {
437 "id": "icon-wave",
438 "name": "Wave",
439 "hex": "#3090d0",
440 "shape": "wave",
441 "image": "images/block-icon-wave.png",
442 "terra": false
443 },
444 {
445 "id": "icon-mountain",
446 "name": "Mountain",
447 "hex": "#809070",
448 "shape": "mountain",
449 "image": "images/block-icon-mountain.png",
450 "terra": false
451 },
452 {
453 "id": "icon-fish",
454 "name": "Fish",
455 "hex": "#40a8c8",
456 "shape": "fish",
457 "image": "images/block-icon-fish.png",
458 "terra": false
459 },
460 {
461 "id": "icon-bird",
462 "name": "Bird",
463 "hex": "#e07050",
464 "shape": "bird",
465 "image": "images/block-icon-bird.png",
466 "terra": false
467 },
468 {
469 "id": "icon-key",
470 "name": "Key",
471 "hex": "#d0b050",
472 "shape": "key",
473 "image": "images/block-icon-key.png",
474 "terra": false
475 },
476 {
477 "id": "icon-comet",
478 "name": "Comet",
479 "hex": "#90d0f0",
480 "shape": "comet",
481 "image": "images/block-icon-comet.png",
482 "terra": false
483 },
484 {
485 "id": "icon-clover",
486 "name": "Clover",
487 "hex": "#40b060",
488 "shape": "clover",
489 "image": "images/block-icon-clover.png",
490 "terra": false
491 },
492 {
493 "id": "icon-paw",
494 "name": "Paw",
495 "hex": "#c08050",
496 "shape": "paw",
497 "image": "images/block-icon-paw.png",
498 "terra": false
499 },
500 {
501 "id": "icon-sword",
502 "name": "Sword",
503 "hex": "#b0b8c0",
504 "shape": "sword",
505 "image": "images/block-icon-sword.png",
506 "terra": false
507 },
508 {
509 "id": "icon-bell",
510 "name": "Bell",
511 "hex": "#f0c848",
512 "shape": "bell",
513 "image": "images/block-icon-bell.png",
514 "terra": false
515 },
516 {
517 "id": "icon-mushroom",
518 "name": "Mushroom",
519 "hex": "#e06050",
520 "shape": "mushroom",
521 "image": "images/block-icon-mushroom.png",
522 "terra": false
523 },
524 {
525 "id": "icon-cactus",
526 "name": "Cactus",
527 "hex": "#50b068",
528 "shape": "cactus",
529 "image": "images/block-icon-cactus.png",
530 "terra": false
531 },
532 {
533 "id": "icon-ring",
534 "name": "Ring",
535 "hex": "#e8d080",
536 "shape": "ring",
537 "image": "images/block-icon-ring.png",
538 "terra": false
539 },
540 {
541 "id": "icon-flag",
542 "name": "Flag",
543 "hex": "#d04050",
544 "shape": "flag",
545 "image": "images/block-icon-flag.png",
546 "terra": false
547 },
548 {
549 "id": "icon-snow",
550 "name": "Snowflake",
551 "hex": "#c8e0f8",
552 "shape": "snowflake",
553 "image": "images/block-icon-snow.png",
554 "terra": false
555 },
556 {
557 "id": "icon-flame",
558 "name": "Flame",
559 "hex": "#ff7030",
560 "shape": "flame_icon",
561 "image": "images/block-icon-flame.png",
562 "terra": false
563 },
564 {
565 "id": "icon-ankh",
566 "name": "Ankh",
567 "hex": "#d0a060",
568 "shape": "ankh",
569 "image": "images/block-icon-ankh.png",
570 "terra": false
571 },
572 {
573 "id": "icon-yin",
574 "name": "Yin Yang",
575 "hex": "#606080",
576 "shape": "yinyang",
577 "image": "images/block-icon-yin.png",
578 "terra": false
579 },
580 {
581 "id": "aurel-gold",
582 "name": "Aurel gold",
583 "hex": "#f4c860",
584 "shape": "hexagon",
585 "image": "images/block-aurel-gold.png",
586 "terra": false
587 },
588 {
589 "id": "aurel-cream",
590 "name": "Aurel cream",
591 "hex": "#f6e7c1",
592 "shape": "circle",
593 "image": "images/block-aurel-cream.png",
594 "terra": false
595 },
596 {
597 "id": "aurel-amber",
598 "name": "Aurel amber",
599 "hex": "#e09a3e",
600 "shape": "teardrop",
601 "image": "images/block-aurel-amber.png",
602 "terra": false
603 },
604 {
605 "id": "aurel-sage",
606 "name": "Aurel sage",
607 "hex": "#8fb86f",
608 "shape": "plus",
609 "image": "images/block-aurel-sage.png",
610 "terra": false
611 },
612 {
613 "id": "aurel-rose",
614 "name": "Aurel rose",
615 "hex": "#e8a0a8",
616 "shape": "pentagon",
617 "image": "images/block-aurel-rose.png",
618 "terra": false
619 },
620 {
621 "id": "cinder-magma",
622 "name": "Cinder magma",
623 "hex": "#ff3b1f",
624 "shape": "triangle",
625 "image": "images/block-cinder-magma.png",
626 "terra": false
627 },
628 {
629 "id": "cinder-coal",
630 "name": "Cinder coal",
631 "hex": "#3a3232",
632 "shape": "square",
633 "image": "images/block-cinder-coal.png",
634 "terra": false
635 },
636 {
637 "id": "cinder-spark",
638 "name": "Cinder spark",
639 "hex": "#ffb347",
640 "shape": "diamond",
641 "image": "images/block-cinder-spark.png",
642 "terra": false
643 },
644 {
645 "id": "cinder-ash",
646 "name": "Cinder ash",
647 "hex": "#8a7a76",
648 "shape": "circle",
649 "image": "images/block-cinder-ash.png",
650 "terra": false
651 },
652 {
653 "id": "cinder-core",
654 "name": "Cinder core",
655 "hex": "#ff6a00",
656 "shape": "star",
657 "image": "images/block-cinder-core.png",
658 "terra": false
659 },
660 {
661 "id": "lunara-silver",
662 "name": "Lunara silver",
663 "hex": "#c5d0e0",
664 "shape": "circle",
665 "image": "images/block-lunara-silver.png",
666 "terra": false
667 },
668 {
669 "id": "lunara-dust",
670 "name": "Lunara dust",
671 "hex": "#8b90a0",
672 "shape": "diamond",
673 "image": "images/block-lunara-dust.png",
674 "terra": false
675 },
676 {
677 "id": "lunara-pale",
678 "name": "Lunara pale",
679 "hex": "#e8d9a8",
680 "shape": "crescent",
681 "image": "images/block-lunara-pale.png",
682 "terra": false
683 },
684 {
685 "id": "lunara-void",
686 "name": "Lunara void",
687 "hex": "#2c3348",
688 "shape": "square",
689 "image": "images/block-lunara-void.png",
690 "terra": false
691 },
692 {
693 "id": "lunara-lilac",
694 "name": "Lunara lilac",
695 "hex": "#b9a4d4",
696 "shape": "star",
697 "image": "images/block-lunara-lilac.png",
698 "terra": false
699 },
700 {
701 "id": "mire-moss",
702 "name": "Mire moss",
703 "hex": "#3d7a45",
704 "shape": "hexagon",
705 "image": "images/block-mire-moss.png",
706 "terra": false
707 },
708 {
709 "id": "mire-bog",
710 "name": "Mire bog",
711 "hex": "#1f4d3a",
712 "shape": "teardrop",
713 "image": "images/block-mire-bog.png",
714 "terra": false
715 },
716 {
717 "id": "mire-rust",
718 "name": "Mire rust",
719 "hex": "#8b5a2b",
720 "shape": "pentagon",
721 "image": "images/block-mire-rust.png",
722 "terra": false
723 },
724 {
725 "id": "mire-spore",
726 "name": "Mire spore",
727 "hex": "#9cbf5a",
728 "shape": "circle",
729 "image": "images/block-mire-spore.png",
730 "terra": false
731 },
732 {
733 "id": "mire-murk",
734 "name": "Mire murk",
735 "hex": "#2e3b2f",
736 "shape": "diamond",
737 "image": "images/block-mire-murk.png",
738 "terra": false
739 },
740 {
741 "id": "galeon-sky",
742 "name": "Galeon sky",
743 "hex": "#4aa3ff",
744 "shape": "arrow",
745 "image": "images/block-galeon-sky.png",
746 "terra": false
747 },
748 {
749 "id": "galeon-cloud",
750 "name": "Galeon cloud",
751 "hex": "#e8eef6",
752 "shape": "circle",
753 "image": "images/block-galeon-cloud.png",
754 "terra": false
755 },
756 {
757 "id": "galeon-storm",
758 "name": "Galeon storm",
759 "hex": "#3d4d6e",
760 "shape": "square",
761 "image": "images/block-galeon-storm.png",
762 "terra": false
763 },
764 {
765 "id": "galeon-sand",
766 "name": "Galeon sand",
767 "hex": "#d4b483",
768 "shape": "diamond",
769 "image": "images/block-galeon-sand.png",
770 "terra": false
771 },
772 {
773 "id": "galeon-kite",
774 "name": "Galeon kite",
775 "hex": "#7fd0c0",
776 "shape": "star",
777 "image": "images/block-galeon-kite.png",
778 "terra": false
779 },
780 {
781 "id": "obsid-glass",
782 "name": "Obsid glass",
783 "hex": "#1a1a22",
784 "shape": "gem",
785 "image": "images/block-obsid-glass.png",
786 "terra": false
787 },
788 {
789 "id": "obsid-violet",
790 "name": "Obsid violet",
791 "hex": "#5a3d8a",
792 "shape": "hexagon",
793 "image": "images/block-obsid-violet.png",
794 "terra": false
795 },
796 {
797 "id": "obsid-shard",
798 "name": "Obsid shard",
799 "hex": "#8a8aa0",
800 "shape": "triangle",
801 "image": "images/block-obsid-shard.png",
802 "terra": false
803 },
804 {
805 "id": "obsid-vein",
806 "name": "Obsid vein",
807 "hex": "#c45a3a",
808 "shape": "diamond",
809 "image": "images/block-obsid-vein.png",
810 "terra": false
811 },
812 {
813 "id": "obsid-basalt",
814 "name": "Obsid basalt",
815 "hex": "#3a3a42",
816 "shape": "square",
817 "image": "images/block-obsid-basalt.png",
818 "terra": false
819 },
820 {
821 "id": "wisp-glow",
822 "name": "Wisp glow",
823 "hex": "#c8ffe0",
824 "shape": "circle",
825 "image": "images/block-wisp-glow.png",
826 "terra": false
827 },
828 {
829 "id": "wisp-mist",
830 "name": "Wisp mist",
831 "hex": "#a8d4e8",
832 "shape": "diamond",
833 "image": "images/block-wisp-mist.png",
834 "terra": false
835 },
836 {
837 "id": "wisp-sparkle",
838 "name": "Wisp sparkle",
839 "hex": "#fff6a8",
840 "shape": "star",
841 "image": "images/block-wisp-sparkle.png",
842 "terra": false
843 },
844 {
845 "id": "wisp-veil",
846 "name": "Wisp veil",
847 "hex": "#d0b8f0",
848 "shape": "teardrop",
849 "image": "images/block-wisp-veil.png",
850 "terra": false
851 },
852 {
853 "id": "wisp-gleam",
854 "name": "Wisp gleam",
855 "hex": "#f4f7ff",
856 "shape": "plus",
857 "image": "images/block-wisp-gleam.png",
858 "terra": false
859 },
860 {
861 "id": "thorn-briar",
862 "name": "Thorn briar",
863 "hex": "#5a7a30",
864 "shape": "triangle",
865 "image": "images/block-thorn-briar.png",
866 "terra": false
867 },
868 {
869 "id": "thorn-berry",
870 "name": "Thorn berry",
871 "hex": "#8b1a4a",
872 "shape": "circle",
873 "image": "images/block-thorn-berry.png",
874 "terra": false
875 },
876 {
877 "id": "thorn-bark",
878 "name": "Thorn bark",
879 "hex": "#5a3a20",
880 "shape": "square",
881 "image": "images/block-thorn-bark.png",
882 "terra": false
883 },
884 {
885 "id": "thorn-petal",
886 "name": "Thorn petal",
887 "hex": "#e89ab0",
888 "shape": "diamond",
889 "image": "images/block-thorn-petal.png",
890 "terra": false
891 },
892 {
893 "id": "thorn-gold",
894 "name": "Thorn gold",
895 "hex": "#c8a030",
896 "shape": "star",
897 "image": "images/block-thorn-gold.png",
898 "terra": false
899 },
900 {
901 "id": "zephyr-azure",
902 "name": "Zephyr azure",
903 "hex": "#6ec8ff",
904 "shape": "crescent",
905 "image": "images/block-zephyr-azure.png",
906 "terra": false
907 },
908 {
909 "id": "zephyr-breeze",
910 "name": "Zephyr breeze",
911 "hex": "#b8e8ff",
912 "shape": "circle",
913 "image": "images/block-zephyr-breeze.png",
914 "terra": false
915 },
916 {
917 "id": "zephyr-cirrus",
918 "name": "Zephyr cirrus",
919 "hex": "#f0f7ff",
920 "shape": "plus",
921 "image": "images/block-zephyr-cirrus.png",
922 "terra": false
923 },
924 {
925 "id": "zephyr-dusk",
926 "name": "Zephyr dusk",
927 "hex": "#7a6ab0",
928 "shape": "diamond",
929 "image": "images/block-zephyr-dusk.png",
930 "terra": false
931 },
932 {
933 "id": "zephyr-haze",
934 "name": "Zephyr haze",
935 "hex": "#ffe08a",
936 "shape": "star",
937 "image": "images/block-zephyr-haze.png",
938 "terra": false
939 },
940 {
941 "id": "frore-ice",
942 "name": "Frore ice",
943 "hex": "#a8d8f0",
944 "shape": "hexagon",
945 "image": "images/block-frore-ice.png",
946 "terra": false
947 },
948 {
949 "id": "frore-frost",
950 "name": "Frore frost",
951 "hex": "#eef7ff",
952 "shape": "circle",
953 "image": "images/block-frore-frost.png",
954 "terra": false
955 },
956 {
957 "id": "frore-deep",
958 "name": "Frore deep",
959 "hex": "#3a6a8a",
960 "shape": "diamond",
961 "image": "images/block-frore-deep.png",
962 "terra": false
963 },
964 {
965 "id": "frore-aurora",
966 "name": "Frore aurora",
967 "hex": "#5ae8c0",
968 "shape": "star",
969 "image": "images/block-frore-aurora.png",
970 "terra": false
971 },
972 {
973 "id": "frore-rime",
974 "name": "Frore rime",
975 "hex": "#d0e4f0",
976 "shape": "triangle",
977 "image": "images/block-frore-rime.png",
978 "terra": false
979 },
980 {
981 "id": "forge-iron",
982 "name": "Forge iron",
983 "hex": "#6a6a72",
984 "shape": "square",
985 "image": "images/block-forge-iron.png",
986 "terra": false
987 },
988 {
989 "id": "forge-slag",
990 "name": "Forge slag",
991 "hex": "#3a3028",
992 "shape": "hexagon",
993 "image": "images/block-forge-slag.png",
994 "terra": false
995 },
996 {
997 "id": "forge-spark",
998 "name": "Forge spark",
999 "hex": "#ff7a1a",
1000 "shape": "triangle",
1001 "image": "images/block-forge-spark.png",
1002 "terra": false
1003 },
1004 {
1005 "id": "forge-brass",
1006 "name": "Forge brass",
1007 "hex": "#c8a048",
1008 "shape": "diamond",
1009 "image": "images/block-forge-brass.png",
1010 "terra": false
1011 },
1012 {
1013 "id": "forge-soot",
1014 "name": "Forge soot",
1015 "hex": "#2a2a28",
1016 "shape": "circle",
1017 "image": "images/block-forge-soot.png",
1018 "terra": false
1019 }
1020 ]
1021 }
1022 ;
190 1023
191 1024 /*
192 1025 * Start File:
@@ -353,6 +1186,34 @@ function loadCatalog ()
353 1186 return { planets: [] };
354 1187 }
355 1188
1189 /** Player-owned custom planets (from the profile) and any remembered
1190 * snapshots (opponents in a lobby), not part of the official catalog. */
1191 var _customPlanets = [];
1192 var _remembered = Object.create(null);
1193
1194 function setCustomPlanets (list)
1195 {
1196 _customPlanets = [];
1197 if (!list || !list.length)
1198 { return; }
1199 for (var i = 0; i < list.length; i++)
1200 { _customPlanets.push(planetFromData(list[i])); }
1201 }
1202
1203 function rememberPlanet (data)
1204 {
1205 if (!data || !data.id)
1206 { return null; }
1207 var pl = planetFromData(data);
1208 _remembered[pl.id] = pl;
1209 return pl;
1210 }
1211
1212 function forgetRemembered ()
1213 {
1214 _remembered = Object.create(null);
1215 }
1216
356 1217 function planetFromData (data)
357 1218 {
358 1219 var planet = createPlanet({
@@ -364,6 +1225,10 @@ function planetFromData (data)
364 1225 colors: data.colors
365 1226 });
366 1227 planet.id = data.id;
1228 if (data.custom)
1229 { planet.custom = true; }
1230 if (data.owner_id)
1231 { planet.owner_id = data.owner_id; }
367 1232 return planet;
368 1233 }
369 1234
@@ -375,6 +1240,8 @@ function allPlanets ()
375 1240 { out.push(planetFromData(raw[i])); }
376 1241 if (out.length === 0)
377 1242 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
1243 for (var c = 0; c < _customPlanets.length; c++)
1244 { out.push(_customPlanets[c]); }
378 1245 return out;
379 1246 }
380 1247
@@ -386,9 +1253,30 @@ function planetById (id)
386 1253 if (all[i].id === id)
387 1254 { return all[i]; }
388 1255 }
1256 if (id && _remembered[id])
1257 { return _remembered[id]; }
389 1258 return defaultPlanet();
390 1259 }
391 1260
1261 function officialPlanets ()
1262 {
1263 var raw = loadCatalog().planets || [];
1264 var out = [];
1265 for (var i = 0; i < raw.length; i++)
1266 { out.push(planetFromData(raw[i])); }
1267 return out;
1268 }
1269
1270 function customPlanets ()
1271 {
1272 return _customPlanets.slice();
1273 }
1274
1275 function pickerPlanets ()
1276 {
1277 return officialPlanets().concat(_customPlanets);
1278 }
1279
392 1280 function defaultPlanet ()
393 1281 {
394 1282 var all = allPlanets();
@@ -415,6 +1303,11 @@ function spriteKey (planet, colorIndex)
415 1303 var c = colors && colors[colorIndex];
416 1304 if (!c)
417 1305 { return 'gray'; }
1306 // Custom planets (and any color that names a registry block) share
1307 // the preloaded Blocks.images() sprite, so late-loaded customs and
1308 // opponent snapshots do not need a second preload.
1309 if (c.block)
1310 { return 'block:' + c.block; }
418 1311 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
419 1312 }
420 1313
@@ -512,6 +1405,12 @@ var Planet = {
512 1405 defaultPlanet: defaultPlanet,
513 1406 defaultColors: defaultColors,
514 1407 allPlanets: allPlanets,
1408 officialPlanets: officialPlanets,
1409 customPlanets: customPlanets,
1410 pickerPlanets: pickerPlanets,
1411 setCustomPlanets: setCustomPlanets,
1412 rememberPlanet: rememberPlanet,
1413 forgetRemembered: forgetRemembered,
515 1414 planetById: planetById,
516 1415 planetFromData: planetFromData,
517 1416 formatStats: formatStats,
@@ -528,13 +1427,183 @@ var Planet = {
528 1427 };
529 1428
530 1429 if (typeof module !== 'undefined' && module.exports)
531 { module.exports = Planet; }
1430 { module.exports = Planet; }
1431 else if (typeof globalThis !== 'undefined')
1432 { globalThis.Planet = Planet; }
1433
1434 /*
1435 * End File:
1436 * /workspace/meteors/src/planet.js
1437 */
1438
1439 /*
1440 * Start File:
1441 * /workspace/meteors/src/blocks.js
1442 */
1443 'use strict';
1444
1445 /**
1446 * Append-only block registry. Thresholds and order stay in lockstep with
1447 * server/lib/Blocks.php: Terra's first five are free; the next costs 500
1448 * lifetime points; each one after that costs 14.5% more (rounded, always
1449 * strictly increasing). Points are a requirement, not a spend.
1450 */
1451
1452 var Blocks = (function ()
1453 {
1454 var TERRA_COUNT = 5;
1455 var FIRST_THRESHOLD = 500;
1456 var GROWTH = 1.145;
1457 var _all = null;
1458
1459 function loadRegistry ()
1460 {
1461 if (_all)
1462 { return _all; }
1463 var data = null;
1464 if (typeof BLOCK_REGISTRY !== 'undefined' && BLOCK_REGISTRY && BLOCK_REGISTRY.blocks)
1465 { data = BLOCK_REGISTRY; }
1466 else if (typeof require !== 'undefined')
1467 {
1468 try
1469 { data = require('../server/lib/blocks.json'); }
1470 catch (e) { data = null; }
1471 }
1472 _all = (data && data.blocks) ? data.blocks.slice() : [];
1473 return _all;
1474 }
1475
1476 function all ()
1477 {
1478 return loadRegistry();
1479 }
1480
1481 function byId (id)
1482 {
1483 var list = all();
1484 for (var i = 0; i < list.length; i++)
1485 {
1486 if (list[i].id === id)
1487 { return list[i]; }
1488 }
1489 return null;
1490 }
1491
1492 function indexOf (id)
1493 {
1494 var list = all();
1495 for (var i = 0; i < list.length; i++)
1496 {
1497 if (list[i].id === id)
1498 { return i; }
1499 }
1500 return -1;
1501 }
1502
1503 function threshold (index)
1504 {
1505 if (index < TERRA_COUNT)
1506 { return 0; }
1507 var t = FIRST_THRESHOLD;
1508 for (var i = TERRA_COUNT; i < index; i++)
1509 {
1510 var next = Math.round(t * GROWTH);
1511 t = Math.max(t + 1, next);
1512 }
1513 return t;
1514 }
1515
1516 function unlocked (index, points)
1517 {
1518 points = points || 0;
1519 return points >= threshold(index);
1520 }
1521
1522 function unlockedId (id, points)
1523 {
1524 var i = indexOf(id);
1525 return i >= 0 && unlocked(i, points);
1526 }
1527
1528 function present (points)
1529 {
1530 points = points || 0;
1531 var list = all();
1532 var out = [];
1533 for (var i = 0; i < list.length; i++)
1534 {
1535 var b = list[i];
1536 var need = threshold(i);
1537 out.push({
1538 id: b.id,
1539 name: b.name || b.id,
1540 hex: b.hex,
1541 shape: b.shape,
1542 image: b.image,
1543 terra: !!b.terra || i < TERRA_COUNT,
1544 index: i,
1545 threshold: need,
1546 unlocked: points >= need
1547 });
1548 }
1549 return out;
1550 }
1551
1552 function asColor (id, slot)
1553 {
1554 var b = byId(id);
1555 if (!b)
1556 { return null; }
1557 return {
1558 id: slot,
1559 block: b.id,
1560 name: b.name || b.id,
1561 hex: b.hex,
1562 shape: b.shape,
1563 image: b.image
1564 };
1565 }
1566
1567 function images ()
1568 {
1569 var list = all();
1570 var out = [];
1571 var seen = Object.create(null);
1572 for (var i = 0; i < list.length; i++)
1573 {
1574 var url = list[i].image;
1575 if (!url || seen[url])
1576 { continue; }
1577 seen[url] = true;
1578 out.push({ name: 'block:' + list[i].id, url: url });
1579 }
1580 return out;
1581 }
1582
1583 return {
1584 TERRA_COUNT: TERRA_COUNT,
1585 FIRST_THRESHOLD: FIRST_THRESHOLD,
1586 GROWTH: GROWTH,
1587 all: all,
1588 byId: byId,
1589 indexOf: indexOf,
1590 threshold: threshold,
1591 unlocked: unlocked,
1592 unlockedId: unlockedId,
1593 present: present,
1594 asColor: asColor,
1595 images: images
1596 };
1597 })();
1598
1599 if (typeof module !== 'undefined' && module.exports)
1600 { module.exports = Blocks; }
532 1601 else if (typeof globalThis !== 'undefined')
533 { globalThis.Planet = Planet; }
1602 { globalThis.Blocks = Blocks; }
534 1603
535 1604 /*
536 1605 * End File:
537 * /workspace/meteors/src/planet.js
1606 * /workspace/meteors/src/blocks.js
538 1607 */
539 1608
540 1609 /*
@@ -4074,6 +5143,10 @@ var Online = {
4074 5143 local: false,
4075 5144 csrf: '',
4076 5145 me: null,
5146 lifetimePoints: 0,
5147 locale: null,
5148 blocks: [],
5149 planets: [],
4077 5150 lobby: null,
4078 5151 incoming: [],
4079 5152 shotResults: [],
@@ -4125,6 +5198,26 @@ Online._apply = function (data)
4125 5198 { this.error = data.error; }
4126 5199 else if (data.ok)
4127 5200 { this.error = ''; }
5201 if (data.lifetime_points != null)
5202 { this.lifetimePoints = data.lifetime_points; }
5203 if (data.locale !== undefined)
5204 { this.locale = data.locale; }
5205 if (data.blocks)
5206 { this.blocks = data.blocks; }
5207 if (data.planets)
5208 {
5209 this.planets = data.planets;
5210 if (typeof Planet !== 'undefined' && Planet.setCustomPlanets)
5211 { Planet.setCustomPlanets(data.planets); }
5212 }
5213 if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet)
5214 {
5215 for (var i = 0; i < data.lobby.players.length; i++)
5216 {
5217 if (data.lobby.players[i].planet)
5218 { Planet.rememberPlanet(data.lobby.players[i].planet); }
5219 }
5220 }
4128 5221 };
4129 5222
4130 5223 Online.request = function (action, body)
@@ -4196,6 +5289,31 @@ Online.setPlanet = function (planetId)
4196 5289 return this.request('lobby_set_planet', { planet_id: planetId });
4197 5290 };
4198 5291
5292 Online.playBegin = function (mode)
5293 {
5294 return this.request('play_begin', { mode: mode || 'solo' });
5295 };
5296
5297 Online.playFinish = function (token, score)
5298 {
5299 return this.request('play_finish', { token: token, score: score || 0 });
5300 };
5301
5302 Online.savePlanet = function (planet)
5303 {
5304 return this.request('planet_save', { planet: planet });
5305 };
5306
5307 Online.deletePlanet = function (id)
5308 {
5309 return this.request('planet_delete', { id: id });
5310 };
5311
5312 Online.setLocale = function (locale)
5313 {
5314 return this.request('set_locale', { locale: locale });
5315 };
5316
4199 5317 Online.leaveLobby = function ()
4200 5318 {
4201 5319 return this.request('lobby_leave');
@@ -6444,6 +7562,545 @@ if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undef
6444 7562 * /workspace/meteors/src/offline.js
6445 7563 */
6446 7564
7565 /*
7566 * Start File:
7567 * /workspace/meteors/src/designer.js
7568 */
7569 'use strict';
7570
7571 /**
7572 * Planeetontwerper (t1139). Only available on the main menu when the
7573 * player is logged in. Talks to api.php through Online.
7574 */
7575 var Designer = {
7576 openSlot: 0,
7577 editingId: null,
7578 slots: [null, null, null, null, null],
7579 dirty: false
7580 };
7581
7582 Designer._blocks = function ()
7583 {
7584 if (typeof Blocks !== 'undefined')
7585 { return Blocks; }
7586 if (typeof require !== 'undefined')
7587 {
7588 try
7589 { return require('./blocks.js'); }
7590 catch (e)
7591 { return null; }
7592 }
7593 return null;
7594 };
7595
7596 Designer.defaultSlots = function ()
7597 {
7598 var B = Designer._blocks();
7599 var all = B ? B.all() : [];
7600 var ids = [];
7601 for (var i = 0; i < 5 && i < all.length; i++)
7602 { ids.push(all[i].id); }
7603 return ids;
7604 };
7605
7606 Designer.points = function ()
7607 {
7608 return (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
7609 };
7610
7611 Designer.blocks = function ()
7612 {
7613 if (typeof Online !== 'undefined' && Online.blocks && Online.blocks.length)
7614 { return Online.blocks; }
7615 var B = Designer._blocks();
7616 if (B)
7617 { return B.present(Designer.points()); }
7618 return [];
7619 };
7620
7621 Designer.planets = function ()
7622 {
7623 if (typeof Planet !== 'undefined' && Planet.customPlanets)
7624 { return Planet.customPlanets(); }
7625 return (typeof Online !== 'undefined' && Online.planets) || [];
7626 };
7627
7628 Designer.openList = function ()
7629 {
7630 if (typeof Online === 'undefined' || !Online.me)
7631 { return; }
7632 if (typeof app !== 'undefined')
7633 { app.mode = 'designer'; }
7634 hideIf('menu');
7635 hideIf('planet-select');
7636 hideIf('online-panel');
7637 hideIf('designer-edit');
7638 showIf('designer');
7639 Designer.renderList();
7640 };
7641
7642 Designer.close = function ()
7643 {
7644 hideIf('designer');
7645 hideIf('designer-edit');
7646 Designer.closeModal();
7647 if (typeof app !== 'undefined')
7648 { app.mode = 'menu'; }
7649 showIf('menu');
7650 if (typeof refreshMenuAccount === 'function')
7651 { refreshMenuAccount(); }
7652 if (typeof renderPlanetGrid === 'function')
7653 {
7654 renderPlanetGrid('planet-grid', false);
7655 renderPlanetGrid('lobby-planet-grid', true);
7656 }
7657 };
7658
7659 Designer.renderList = function ()
7660 {
7661 var box = document.getElementById('designer-list');
7662 var pts = document.getElementById('designer-points');
7663 if (pts)
7664 { pts.textContent = String(Designer.points()); }
7665 if (!box)
7666 { return; }
7667 box.innerHTML = '';
7668 var planets = Designer.planets();
7669 if (!planets.length)
7670 {
7671 var empty = document.createElement('p');
7672 empty.className = 'hint';
7673 empty.textContent = 'Je hebt nog geen eigen planeten. Maak er een aan.';
7674 box.appendChild(empty);
7675 return;
7676 }
7677 for (var i = 0; i < planets.length; i++)
7678 {
7679 var pl = planets[i];
7680 if (typeof Planet !== 'undefined' && Planet.planetFromData && !pl.baseJumpHeight)
7681 { pl = Planet.planetFromData(pl); }
7682 var card = document.createElement('div');
7683 card.className = 'planet-card designer-card';
7684 var swatches = '';
7685 var colors = pl.colors || [];
7686 for (var c = 0; c < colors.length; c++)
7687 {
7688 swatches += '<img src="' + Designer.esc(colors[c].image) + '" alt="'
7689 + Designer.esc(colors[c].name) + '">';
7690 }
7691 var stats = (typeof Planet !== 'undefined' && Planet.formatStats)
7692 ? Planet.formatStats(pl) : '';
7693 card.innerHTML = '<div class="planet-title">' + Designer.esc(pl.name) + '</div>'
7694 + '<div class="planet-people">' + Designer.esc(pl.people) + '</div>'
7695 + '<div class="planet-nums">' + Designer.esc(stats) + '</div>'
7696 + '<div class="planet-swatches">' + swatches + '</div>'
7697 + '<div class="designer-card-actions">'
7698 + '<button type="button" class="btn-tiny" data-edit>Bewerken</button>'
7699 + '<button type="button" class="btn-tiny btn-danger-lite" data-del>Verwijderen</button>'
7700 + '</div>';
7701 (function (id)
7702 {
7703 card.querySelector('[data-edit]').addEventListener('click', function ()
7704 { Designer.openEdit(id); });
7705 card.querySelector('[data-del]').addEventListener('click', function ()
7706 { Designer.confirmDelete(id); });
7707 })(pl.id);
7708 box.appendChild(card);
7709 }
7710 };
7711
7712 Designer.confirmDelete = function (id)
7713 {
7714 var pl = Designer.planetById(id);
7715 var name = pl ? pl.name : id;
7716 if (!window.confirm('Wil je de planeet “' + name + '” verwijderen?'))
7717 { return; }
7718 Online.deletePlanet(id).then(function (data)
7719 {
7720 if (!data || !data.ok)
7721 {
7722 window.alert((data && data.error) || 'Verwijderen is mislukt.');
7723 return;
7724 }
7725 Designer.renderList();
7726 if (typeof renderPlanetGrid === 'function')
7727 {
7728 renderPlanetGrid('planet-grid', false);
7729 renderPlanetGrid('lobby-planet-grid', true);
7730 }
7731 });
7732 };
7733
7734 Designer.planetById = function (id)
7735 {
7736 var list = Designer.planets();
7737 for (var i = 0; i < list.length; i++)
7738 {
7739 if (list[i].id === id)
7740 { return list[i]; }
7741 }
7742 return null;
7743 };
7744
7745 Designer.openEdit = function (id)
7746 {
7747 var pl = id ? Designer.planetById(id) : null;
7748 Designer.editingId = pl ? pl.id : null;
7749 if (pl)
7750 {
7751 Designer.slots = [];
7752 for (var i = 0; i < 5; i++)
7753 {
7754 var c = pl.colors && pl.colors[i];
7755 Designer.slots[i] = c ? (c.block || c.id) : Designer.defaultSlots()[i];
7756 // c.id is the slot index 0-4 on snapshots; prefer c.block
7757 if (c && c.block)
7758 { Designer.slots[i] = c.block; }
7759 else if (c && typeof c.id === 'string')
7760 { Designer.slots[i] = c.id; }
7761 }
7762 document.getElementById('des-name').value = pl.name || '';
7763 document.getElementById('des-people').value = pl.people || '';
7764 document.getElementById('des-gravity').value = String(pl.jumpsToClear != null ? pl.jumpsToClear : 2);
7765 document.getElementById('des-air').value = String(pl.fallTime != null ? pl.fallTime : 3);
7766 document.getElementById('des-mass').value = String(pl.riseTime != null ? pl.riseTime : 1.5);
7767 document.getElementById('designer-edit-title').textContent = 'Planeet bewerken';
7768 document.getElementById('btn-designer-delete').hidden = false;
7769 }
7770 else
7771 {
7772 Designer.slots = Designer.defaultSlots().slice();
7773 document.getElementById('des-name').value = '';
7774 document.getElementById('des-people').value = '';
7775 document.getElementById('des-gravity').value = '2';
7776 document.getElementById('des-air').value = '3';
7777 document.getElementById('des-mass').value = '1.5';
7778 document.getElementById('designer-edit-title').textContent = 'Nieuwe planeet';
7779 document.getElementById('btn-designer-delete').hidden = true;
7780 }
7781 hideIf('designer');
7782 showIf('designer-edit');
7783 Designer.syncPreview();
7784 Designer.renderSlots();
7785 var name = document.getElementById('des-name');
7786 if (name)
7787 { name.focus(); }
7788 };
7789
7790 Designer.draftPlanet = function ()
7791 {
7792 var jumps = clampNum(document.getElementById('des-gravity').value, 1, 4, 2);
7793 var fall = clampNum(document.getElementById('des-air').value, 1, 5, 3);
7794 var rise = clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5);
7795 var colors = [];
7796 for (var i = 0; i < 5; i++)
7797 {
7798 var B = Designer._blocks();
7799 var col = B ? B.asColor(Designer.slots[i], i) : null;
7800 if (col)
7801 { colors.push(col); }
7802 }
7803 var opts = {
7804 id: Designer.editingId || 'draft',
7805 name: (document.getElementById('des-name').value || 'Nieuwe planeet').trim() || 'Nieuwe planeet',
7806 people: (document.getElementById('des-people').value || 'Volk').trim() || 'Volk',
7807 jumpsToClear: jumps,
7808 fallTime: fall,
7809 riseTime: rise,
7810 colors: colors
7811 };
7812 if (typeof Planet === 'undefined')
7813 { return opts; }
7814 return Planet.createPlanet ? (function ()
7815 {
7816 var p = Planet.createPlanet(opts);
7817 p.id = opts.id;
7818 p.custom = true;
7819 return p;
7820 })() : opts;
7821 };
7822
7823 Designer.syncPreview = function ()
7824 {
7825 var p = Designer.draftPlanet();
7826 var d = (typeof Planet !== 'undefined' && Planet.displayValues) ? Planet.displayValues(p) : null;
7827 setText('des-gravity-val', Number(document.getElementById('des-gravity').value).toFixed(1)
7828 + (d ? ' · g ' + d.gravity.toFixed(2) : ''));
7829 setText('des-air-val', Number(document.getElementById('des-air').value).toFixed(1)
7830 + (d ? ' · d ' + d.density.toFixed(2) : ''));
7831 setText('des-mass-val', Number(document.getElementById('des-mass').value).toFixed(1)
7832 + (d ? ' · F ' + Math.round(d.newtons) + ' N' : ''));
7833 var power = d ? d.power : 0;
7834 setText('des-power', 'Power ' + power + '%');
7835 };
7836
7837 Designer.renderSlots = function ()
7838 {
7839 var row = document.getElementById('des-slots');
7840 if (!row)
7841 { return; }
7842 row.innerHTML = '';
7843 for (var i = 0; i < 5; i++)
7844 {
7845 var id = Designer.slots[i];
7846 var B = Designer._blocks();
7847 var b = B ? B.byId(id) : null;
7848 var btn = document.createElement('button');
7849 btn.type = 'button';
7850 btn.className = 'des-slot';
7851 btn.setAttribute('aria-label', 'Blokje ' + (i + 1));
7852 if (b)
7853 {
7854 btn.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="' + Designer.esc(b.name) + '">'
7855 + '<span>' + Designer.esc(b.name) + '</span>';
7856 }
7857 else
7858 {
7859 btn.innerHTML = '<span class="des-slot-empty">Kies</span>';
7860 }
7861 (function (slot)
7862 {
7863 btn.addEventListener('click', function ()
7864 { Designer.openModal(slot); });
7865 })(i);
7866 row.appendChild(btn);
7867 }
7868 };
7869
7870 Designer.openModal = function (slot)
7871 {
7872 Designer.openSlot = slot;
7873 var modal = document.getElementById('des-modal');
7874 var grid = document.getElementById('des-modal-grid');
7875 if (!modal || !grid)
7876 { return; }
7877 grid.innerHTML = '';
7878 var blocks = Designer.blocks();
7879 var used = Object.create(null);
7880 for (var i = 0; i < 5; i++)
7881 {
7882 if (i !== slot && Designer.slots[i])
7883 { used[Designer.slots[i]] = true; }
7884 }
7885 for (var i = 0; i < blocks.length; i++)
7886 {
7887 var b = blocks[i];
7888 var cell = document.createElement('button');
7889 cell.type = 'button';
7890 cell.className = 'des-block';
7891 cell.dataset.id = b.id;
7892 var locked = !b.unlocked;
7893 var taken = !!used[b.id];
7894 if (locked)
7895 { cell.classList.add('locked'); }
7896 if (taken)
7897 { cell.classList.add('used'); }
7898 if (Designer.slots[slot] === b.id)
7899 { cell.classList.add('current'); }
7900 var title = b.name;
7901 if (locked)
7902 { title += ' — ' + b.threshold + ' punten nodig'; }
7903 else if (taken)
7904 { title += ' — al in een ander vak'; }
7905 cell.title = title;
7906 cell.setAttribute('aria-label', title);
7907 cell.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="">'
7908 + (locked ? '<span class="des-lock" aria-hidden="true">'
7909 + '<svg viewBox="0 0 18 18" width="16" height="16">'
7910 + '<rect x="4" y="8" width="10" height="8" rx="1.5" fill="#ffe27a"/>'
7911 + '<path d="M6 8 V6 a3 3 0 0 1 6 0 v2" fill="none" stroke="#ffe27a" stroke-width="1.8" stroke-linecap="round"/>'
7912 + '<circle cx="9" cy="12" r="1.2" fill="#1a1628"/>'
7913 + '</svg></span>' : '')
7914 + '<span class="des-block-name">' + Designer.esc(b.name) + '</span>'
7915 + (locked ? '<span class="des-block-need">' + b.threshold + '</span>' : '');
7916 if (locked || taken)
7917 { cell.disabled = true; }
7918 else
7919 {
7920 cell.addEventListener('click', (function (id)
7921 {
7922 return function ()
7923 {
7924 Designer.slots[Designer.openSlot] = id;
7925 Designer.closeModal();
7926 Designer.renderSlots();
7927 };
7928 })(b.id));
7929 }
7930 grid.appendChild(cell);
7931 }
7932 modal.hidden = false;
7933 modal.setAttribute('aria-hidden', 'false');
7934 var close = document.getElementById('des-modal-close');
7935 if (close)
7936 { close.focus(); }
7937 };
7938
7939 Designer.closeModal = function ()
7940 {
7941 var modal = document.getElementById('des-modal');
7942 if (!modal)
7943 { return; }
7944 modal.hidden = true;
7945 modal.setAttribute('aria-hidden', 'true');
7946 };
7947
7948 Designer.save = function ()
7949 {
7950 var name = (document.getElementById('des-name').value || '').trim();
7951 var people = (document.getElementById('des-people').value || '').trim();
7952 if (!name || !people)
7953 {
7954 window.alert('Vul een naam voor de planeet en voor de bevolking in.');
7955 return;
7956 }
7957 for (var i = 0; i < 5; i++)
7958 {
7959 if (!Designer.slots[i])
7960 {
7961 window.alert('Kies vijf blokjes.');
7962 return;
7963 }
7964 }
7965 var payload = {
7966 id: Designer.editingId || undefined,
7967 name: name,
7968 people: people,
7969 jumpsToClear: clampNum(document.getElementById('des-gravity').value, 1, 4, 2),
7970 fallTime: clampNum(document.getElementById('des-air').value, 1, 5, 3),
7971 riseTime: clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5),
7972 colors: Designer.slots.slice()
7973 };
7974 Online.savePlanet(payload).then(function (data)
7975 {
7976 if (!data || !data.ok)
7977 {
7978 window.alert((data && data.error) || 'Opslaan is mislukt.');
7979 return;
7980 }
7981 hideIf('designer-edit');
7982 showIf('designer');
7983 Designer.editingId = data.planet ? data.planet.id : null;
7984 Designer.renderList();
7985 if (typeof renderPlanetGrid === 'function')
7986 {
7987 renderPlanetGrid('planet-grid', false);
7988 renderPlanetGrid('lobby-planet-grid', true);
7989 }
7990 });
7991 };
7992
7993 Designer.bind = function ()
7994 {
7995 var btn = document.getElementById('btn-designer');
7996 if (btn)
7997 { btn.addEventListener('click', function () { Designer.openList(); }); }
7998 var back = document.getElementById('btn-designer-back');
7999 if (back)
8000 { back.addEventListener('click', Designer.close); }
8001 var neu = document.getElementById('btn-designer-new');
8002 if (neu)
8003 { neu.addEventListener('click', function () { Designer.openEdit(null); }); }
8004 var cancel = document.getElementById('btn-designer-cancel');
8005 if (cancel)
8006 {
8007 cancel.addEventListener('click', function ()
8008 {
8009 hideIf('designer-edit');
8010 showIf('designer');
8011 Designer.renderList();
8012 });
8013 }
8014 var save = document.getElementById('btn-designer-save');
8015 if (save)
8016 { save.addEventListener('click', function (e) { e.preventDefault(); Designer.save(); }); }
8017 var form = document.getElementById('designer-form');
8018 if (form)
8019 { form.addEventListener('submit', function (e) { e.preventDefault(); Designer.save(); }); }
8020 var del = document.getElementById('btn-designer-delete');
8021 if (del)
8022 {
8023 del.addEventListener('click', function ()
8024 {
8025 if (!Designer.editingId)
8026 { return; }
8027 Designer.confirmDelete(Designer.editingId);
8028 hideIf('designer-edit');
8029 showIf('designer');
8030 });
8031 }
8032 ['des-gravity', 'des-air', 'des-mass'].forEach(function (id)
8033 {
8034 var el = document.getElementById(id);
8035 if (!el)
8036 { return; }
8037 el.addEventListener('input', Designer.syncPreview);
8038 });
8039 var modal = document.getElementById('des-modal');
8040 if (modal)
8041 {
8042 modal.addEventListener('click', function (e)
8043 {
8044 if (e.target === modal)
8045 { Designer.closeModal(); }
8046 });
8047 }
8048 var close = document.getElementById('des-modal-close');
8049 if (close)
8050 { close.addEventListener('click', Designer.closeModal); }
8051 document.addEventListener('keydown', function (e)
8052 {
8053 if (e.key === 'Escape')
8054 { Designer.closeModal(); }
8055 });
8056 };
8057
8058 Designer.esc = function (s)
8059 {
8060 return String(s == null ? '' : s)
8061 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
8062 .replace(/"/g, '&quot;');
8063 };
8064
8065 function hideIf (id)
8066 {
8067 var el = document.getElementById(id);
8068 if (el)
8069 { el.hidden = true; }
8070 }
8071
8072 function showIf (id)
8073 {
8074 var el = document.getElementById(id);
8075 if (el)
8076 { el.hidden = false; }
8077 }
8078
8079 function setText (id, text)
8080 {
8081 var el = document.getElementById(id);
8082 if (el)
8083 { el.textContent = text; }
8084 }
8085
8086 function clampNum (v, lo, hi, fallback)
8087 {
8088 var n = Number(v);
8089 if (!isFinite(n))
8090 { n = fallback; }
8091 return Math.max(lo, Math.min(hi, n));
8092 }
8093
8094 if (typeof module !== 'undefined' && module.exports)
8095 { module.exports = Designer; }
8096 else if (typeof globalThis !== 'undefined')
8097 { globalThis.Designer = Designer; }
8098
8099 /*
8100 * End File:
8101 * /workspace/meteors/src/designer.js
8102 */
8103
6447 8104 /*
6448 8105 * Start File:
6449 8106 * /workspace/meteors/src/main.js
@@ -6486,6 +8143,12 @@ function planetImages ()
6486 8143 });
6487 8144 }
6488 8145 }
8146 if (typeof Blocks !== 'undefined' && Blocks.images)
8147 {
8148 var extra = Blocks.images();
8149 for (var b = 0; b < extra.length; b++)
8150 { list.push(extra[b]); }
8151 }
6489 8152 return list;
6490 8153 }
6491 8154
@@ -6560,6 +8223,20 @@ window.onload = function ()
6560 8223 bindOfflineUi();
6561 8224 bindPlanetSelect();
6562 8225 restoreSelectedPlanet();
8226 if (typeof Designer !== 'undefined' && Designer.bind)
8227 { Designer.bind(); }
8228 if (typeof Online !== 'undefined' && Online.refresh)
8229 {
8230 Online.refresh().then(function ()
8231 {
8232 refreshMenuAccount();
8233 restoreSelectedPlanet();
8234 renderPlanetGrid('planet-grid', false);
8235 renderPlanetGrid('lobby-planet-grid', true);
8236 });
8237 }
8238 else
8239 { refreshMenuAccount(); }
6563 8240 };
6564 8241
6565 8242 function onPlay ()
@@ -6579,6 +8256,10 @@ function startPlay (opts)
6579 8256 hideEl('podium');
6580 8257 hideEl('planet-select');
6581 8258 hideEl('offline-result');
8259 hideEl('designer');
8260 hideEl('designer-edit');
8261 if (typeof Designer !== 'undefined' && Designer.closeModal)
8262 { Designer.closeModal(); }
6582 8263 showEl('hud');
6583 8264
6584 8265 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
@@ -6642,6 +8323,8 @@ function startPlay (opts)
6642 8323 buildColumnWarn();
6643 8324 refreshOfflineHud();
6644 8325 refreshChainIndicator();
8326 if (!opts.online)
8327 { beginPlaySession(opts.offline ? 'offline' : 'solo'); }
6645 8328 }
6646 8329
6647 8330 function teardownPlay ()
@@ -7234,7 +8917,10 @@ function tickView (dt)
7234 8917 else if (app.offline)
7235 8918 { /* Offline result is shown from tickOffline. */ }
7236 8919 else
7237 { showEl('game-over'); }
8920 {
8921 showEl('game-over');
8922 finishPlaySession(app.lastScore);
8923 }
7238 8924 }
7239 8925 if (!app.online && !app.offline && app.core.state === 'gameover'
7240 8926 && app.core.gameOverTime >= GAME_OVER_DELAY)
@@ -7845,6 +9531,8 @@ function startNextOfflineRound ()
7845 9531 // Tear down the current scene then start a fresh player field,
7846 9532 // keeping the same battle (already advanced).
7847 9533 var planet = app.battle.playerPlanet;
9534 var roundScore = app.core ? app.core.score : 0;
9535 finishPlaySession(roundScore);
7848 9536 app._keepBattleOnTeardown = true;
7849 9537 teardownPlay();
7850 9538 app.offline = true;
@@ -7870,6 +9558,7 @@ function showOfflineResult ()
7870 9558 }
7871 9559 hideEl('game-over');
7872 9560 showEl('offline-result');
9561 finishPlaySession(app.core ? app.core.score : 0);
7873 9562 }
7874 9563
7875 9564 function refreshOfflineHud ()
@@ -8181,10 +9870,18 @@ function startOnlineMatch ()
8181 9870 if (app.mode === 'playing' && app.online)
8182 9871 { return; }
8183 9872 var planet = Planet.planetById(selectedPlanetId());
9873 var miss = Planet.missChance(planet);
8184 9874 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
8185 if (me && me.planet && me.planet.id)
8186 { planet = Planet.planetById(me.planet.id); }
8187 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
9875 if (me && me.planet)
9876 {
9877 if (typeof Planet.rememberPlanet === 'function')
9878 { planet = Planet.rememberPlanet(me.planet) || planet; }
9879 else if (me.planet.id)
9880 { planet = Planet.planetById(me.planet.id); }
9881 if (typeof me.planet.miss_chance === 'number')
9882 { miss = me.planet.miss_chance; }
9883 }
9884 startPlay({ online: true, planet: planet, missChance: miss });
8188 9885 if (typeof Online !== 'undefined')
8189 9886 { Online.startPolling(onlinePayload); }
8190 9887 }
@@ -8562,19 +10259,22 @@ function renderPlanetGrid (containerId, compact)
8562 10259 var pl = all[i];
8563 10260 var btn = document.createElement('button');
8564 10261 btn.type = 'button';
8565 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
10262 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
10263 + (pl.custom ? ' custom' : '');
8566 10264 btn.setAttribute('role', 'listitem');
8567 10265 btn.dataset.planet = pl.id;
8568 10266 var swatches = '';
8569 for (var c = 0; c < pl.colors.length; c++)
10267 var colors = pl.colors || [];
10268 for (var c = 0; c < colors.length; c++)
8570 10269 {
8571 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
8572 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
10270 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
10271 + escapeText(colors[c].name) + '" title="' + escapeText(colors[c].name) + '">';
8573 10272 }
8574 10273 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
8575 10274 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
8576 10275 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
8577 + '<div class="planet-swatches">' + swatches + '</div>';
10276 + '<div class="planet-swatches">' + swatches + '</div>'
10277 + (pl.custom ? '<span class="custom-badge">Eigen</span>' : '');
8578 10278 btn.addEventListener('click', (function (id, isCompact)
8579 10279 {
8580 10280 return function ()
@@ -8636,6 +10336,67 @@ function bindPlanetSelect ()
8636 10336 }
8637 10337 }
8638 10338
10339
10340 function refreshMenuAccount ()
10341 {
10342 var guest = document.getElementById('menu-guest');
10343 var user = document.getElementById('menu-user');
10344 var designerBtn = document.getElementById('btn-designer');
10345 var localLogin = document.getElementById('menu-local-login');
10346 var me = (typeof Online !== 'undefined') ? Online.me : null;
10347 if (me)
10348 {
10349 if (guest)
10350 { guest.hidden = true; }
10351 if (user)
10352 { user.hidden = false; }
10353 var name = document.getElementById('menu-name');
10354 if (name)
10355 { name.textContent = me.name || me.id || 'speler'; }
10356 var pts = document.getElementById('menu-points');
10357 if (pts)
10358 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
10359 if (designerBtn)
10360 { designerBtn.hidden = false; }
10361 }
10362 else
10363 {
10364 if (guest)
10365 { guest.hidden = false; }
10366 if (user)
10367 { user.hidden = true; }
10368 if (designerBtn)
10369 { designerBtn.hidden = true; }
10370 }
10371 if (localLogin)
10372 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
10373 }
10374
10375 function beginPlaySession (mode)
10376 {
10377 if (app.playToken)
10378 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
10379 app.playToken = null;
10380 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
10381 { return; }
10382 Online.playBegin(mode || 'solo').then(function (data)
10383 {
10384 if (data && data.ok && data.token)
10385 { app.playToken = data.token; }
10386 });
10387 }
10388
10389 function finishPlaySession (score)
10390 {
10391 var token = app.playToken;
10392 app.playToken = null;
10393 if (!token || typeof Online === 'undefined' || !Online.playFinish)
10394 { return; }
10395 Online.playFinish(token, score || 0).then(function ()
10396 { refreshMenuAccount(); });
10397 }
10398
10399
8639 10400 /*
8640 10401 * End File:
8641 10402 * /workspace/meteors/src/main.js
@@ -187,6 +187,839 @@ var PLANET_CATALOG = {
187 ]
187 ]
188}
188}
189;
189;
190var BLOCK_REGISTRY = {
191 "_comment": "Append-only block registry. Never reorder, rename ids, or insert in the middle. New blocks go at the end. The first five (Terra) are unlocked by default; index 5 requires 500 lifetime points, each next index requires 14.5% more (rounded).",
192 "terraCount": 5,
193 "firstThreshold": 500,
194 "thresholdGrowth": 1.145,
195 "blocks": [
196 {
197 "id": "terra-ember",
198 "name": "Ember",
199 "hex": "#e85d3a",
200 "shape": "triangle",
201 "image": "images/block-terra-ember.png",
202 "terra": true
203 },
204 {
205 "id": "terra-aqua",
206 "name": "Aqua",
207 "hex": "#3db8e8",
208 "shape": "circle",
209 "image": "images/block-terra-aqua.png",
210 "terra": true
211 },
212 {
213 "id": "terra-leaf",
214 "name": "Leaf",
215 "hex": "#4cbf4c",
216 "shape": "square",
217 "image": "images/block-terra-leaf.png",
218 "terra": true
219 },
220 {
221 "id": "terra-sun",
222 "name": "Sun",
223 "hex": "#f0c53a",
224 "shape": "diamond",
225 "image": "images/block-terra-sun.png",
226 "terra": true
227 },
228 {
229 "id": "terra-orchid",
230 "name": "Orchid",
231 "hex": "#c45ad4",
232 "shape": "star",
233 "image": "images/block-terra-orchid.png",
234 "terra": true
235 },
236 {
237 "id": "rune-fehu",
238 "name": "Fehu",
239 "hex": "#e8a44a",
240 "shape": "rune_fehu",
241 "image": "images/block-rune-fehu.png",
242 "terra": false
243 },
244 {
245 "id": "rune-ansuz",
246 "name": "Ansuz",
247 "hex": "#6ab0e8",
248 "shape": "rune_ansuz",
249 "image": "images/block-rune-ansuz.png",
250 "terra": false
251 },
252 {
253 "id": "rune-thurisaz",
254 "name": "Thurisaz",
255 "hex": "#c05040",
256 "shape": "rune_thurisaz",
257 "image": "images/block-rune-thurisaz.png",
258 "terra": false
259 },
260 {
261 "id": "rune-raido",
262 "name": "Raido",
263 "hex": "#d0c070",
264 "shape": "rune_raido",
265 "image": "images/block-rune-raido.png",
266 "terra": false
267 },
268 {
269 "id": "rune-sowilo",
270 "name": "Sowilo",
271 "hex": "#f0d040",
272 "shape": "rune_sowilo",
273 "image": "images/block-rune-sowilo.png",
274 "terra": false
275 },
276 {
277 "id": "rune-algiz",
278 "name": "Algiz",
279 "hex": "#80d0a0",
280 "shape": "rune_algiz",
281 "image": "images/block-rune-algiz.png",
282 "terra": false
283 },
284 {
285 "id": "arrow-up",
286 "name": "Arrow",
287 "hex": "#f07040",
288 "shape": "arrow",
289 "image": "images/block-arrow-up.png",
290 "terra": false
291 },
292 {
293 "id": "arrow-chevron",
294 "name": "Chevron",
295 "hex": "#50c0e0",
296 "shape": "chevron",
297 "image": "images/block-arrow-chevron.png",
298 "terra": false
299 },
300 {
301 "id": "arrow-double",
302 "name": "Double Arrow",
303 "hex": "#e05080",
304 "shape": "double_arrow",
305 "image": "images/block-arrow-double.png",
306 "terra": false
307 },
308 {
309 "id": "arrow-return",
310 "name": "Return",
311 "hex": "#a080e0",
312 "shape": "return_arrow",
313 "image": "images/block-arrow-return.png",
314 "terra": false
315 },
316 {
317 "id": "fig-person",
318 "name": "Figure",
319 "hex": "#f0c0a0",
320 "shape": "person",
321 "image": "images/block-fig-person.png",
322 "terra": false
323 },
324 {
325 "id": "fig-walker",
326 "name": "Walker",
327 "hex": "#c09070",
328 "shape": "walker",
329 "image": "images/block-fig-walker.png",
330 "terra": false
331 },
332 {
333 "id": "fig-hero",
334 "name": "Hero",
335 "hex": "#e8b070",
336 "shape": "hero",
337 "image": "images/block-fig-hero.png",
338 "terra": false
339 },
340 {
341 "id": "face-smile",
342 "name": "Smile",
343 "hex": "#f0d060",
344 "shape": "smile",
345 "image": "images/block-face-smile.png",
346 "terra": false
347 },
348 {
349 "id": "face-wink",
350 "name": "Wink",
351 "hex": "#f0a050",
352 "shape": "wink",
353 "image": "images/block-face-wink.png",
354 "terra": false
355 },
356 {
357 "id": "face-cool",
358 "name": "Cool",
359 "hex": "#6090d0",
360 "shape": "cool",
361 "image": "images/block-face-cool.png",
362 "terra": false
363 },
364 {
365 "id": "face-grin",
366 "name": "Grin",
367 "hex": "#f0c848",
368 "shape": "grin",
369 "image": "images/block-face-grin.png",
370 "terra": false
371 },
372 {
373 "id": "icon-heart",
374 "name": "Heart",
375 "hex": "#e04060",
376 "shape": "heart",
377 "image": "images/block-icon-heart.png",
378 "terra": false
379 },
380 {
381 "id": "icon-moon",
382 "name": "Moon",
383 "hex": "#d0d8f0",
384 "shape": "crescent",
385 "image": "images/block-icon-moon.png",
386 "terra": false
387 },
388 {
389 "id": "icon-bolt",
390 "name": "Bolt",
391 "hex": "#f0e050",
392 "shape": "lightning",
393 "image": "images/block-icon-bolt.png",
394 "terra": false
395 },
396 {
397 "id": "icon-shield",
398 "name": "Shield",
399 "hex": "#5080c0",
400 "shape": "shield",
401 "image": "images/block-icon-shield.png",
402 "terra": false
403 },
404 {
405 "id": "icon-crown",
406 "name": "Crown",
407 "hex": "#f0c030",
408 "shape": "crown",
409 "image": "images/block-icon-crown.png",
410 "terra": false
411 },
412 {
413 "id": "icon-eye",
414 "name": "Eye",
415 "hex": "#70d0c0",
416 "shape": "eye",
417 "image": "images/block-icon-eye.png",
418 "terra": false
419 },
420 {
421 "id": "icon-star6",
422 "name": "Hexastar",
423 "hex": "#f0e8a0",
424 "shape": "star6",
425 "image": "images/block-icon-star6.png",
426 "terra": false
427 },
428 {
429 "id": "icon-spiral",
430 "name": "Spiral",
431 "hex": "#c070d0",
432 "shape": "spiral",
433 "image": "images/block-icon-spiral.png",
434 "terra": false
435 },
436 {
437 "id": "icon-wave",
438 "name": "Wave",
439 "hex": "#3090d0",
440 "shape": "wave",
441 "image": "images/block-icon-wave.png",
442 "terra": false
443 },
444 {
445 "id": "icon-mountain",
446 "name": "Mountain",
447 "hex": "#809070",
448 "shape": "mountain",
449 "image": "images/block-icon-mountain.png",
450 "terra": false
451 },
452 {
453 "id": "icon-fish",
454 "name": "Fish",
455 "hex": "#40a8c8",
456 "shape": "fish",
457 "image": "images/block-icon-fish.png",
458 "terra": false
459 },
460 {
461 "id": "icon-bird",
462 "name": "Bird",
463 "hex": "#e07050",
464 "shape": "bird",
465 "image": "images/block-icon-bird.png",
466 "terra": false
467 },
468 {
469 "id": "icon-key",
470 "name": "Key",
471 "hex": "#d0b050",
472 "shape": "key",
473 "image": "images/block-icon-key.png",
474 "terra": false
475 },
476 {
477 "id": "icon-comet",
478 "name": "Comet",
479 "hex": "#90d0f0",
480 "shape": "comet",
481 "image": "images/block-icon-comet.png",
482 "terra": false
483 },
484 {
485 "id": "icon-clover",
486 "name": "Clover",
487 "hex": "#40b060",
488 "shape": "clover",
489 "image": "images/block-icon-clover.png",
490 "terra": false
491 },
492 {
493 "id": "icon-paw",
494 "name": "Paw",
495 "hex": "#c08050",
496 "shape": "paw",
497 "image": "images/block-icon-paw.png",
498 "terra": false
499 },
500 {
501 "id": "icon-sword",
502 "name": "Sword",
503 "hex": "#b0b8c0",
504 "shape": "sword",
505 "image": "images/block-icon-sword.png",
506 "terra": false
507 },
508 {
509 "id": "icon-bell",
510 "name": "Bell",
511 "hex": "#f0c848",
512 "shape": "bell",
513 "image": "images/block-icon-bell.png",
514 "terra": false
515 },
516 {
517 "id": "icon-mushroom",
518 "name": "Mushroom",
519 "hex": "#e06050",
520 "shape": "mushroom",
521 "image": "images/block-icon-mushroom.png",
522 "terra": false
523 },
524 {
525 "id": "icon-cactus",
526 "name": "Cactus",
527 "hex": "#50b068",
528 "shape": "cactus",
529 "image": "images/block-icon-cactus.png",
530 "terra": false
531 },
532 {
533 "id": "icon-ring",
534 "name": "Ring",
535 "hex": "#e8d080",
536 "shape": "ring",
537 "image": "images/block-icon-ring.png",
538 "terra": false
539 },
540 {
541 "id": "icon-flag",
542 "name": "Flag",
543 "hex": "#d04050",
544 "shape": "flag",
545 "image": "images/block-icon-flag.png",
546 "terra": false
547 },
548 {
549 "id": "icon-snow",
550 "name": "Snowflake",
551 "hex": "#c8e0f8",
552 "shape": "snowflake",
553 "image": "images/block-icon-snow.png",
554 "terra": false
555 },
556 {
557 "id": "icon-flame",
558 "name": "Flame",
559 "hex": "#ff7030",
560 "shape": "flame_icon",
561 "image": "images/block-icon-flame.png",
562 "terra": false
563 },
564 {
565 "id": "icon-ankh",
566 "name": "Ankh",
567 "hex": "#d0a060",
568 "shape": "ankh",
569 "image": "images/block-icon-ankh.png",
570 "terra": false
571 },
572 {
573 "id": "icon-yin",
574 "name": "Yin Yang",
575 "hex": "#606080",
576 "shape": "yinyang",
577 "image": "images/block-icon-yin.png",
578 "terra": false
579 },
580 {
581 "id": "aurel-gold",
582 "name": "Aurel gold",
583 "hex": "#f4c860",
584 "shape": "hexagon",
585 "image": "images/block-aurel-gold.png",
586 "terra": false
587 },
588 {
589 "id": "aurel-cream",
590 "name": "Aurel cream",
591 "hex": "#f6e7c1",
592 "shape": "circle",
593 "image": "images/block-aurel-cream.png",
594 "terra": false
595 },
596 {
597 "id": "aurel-amber",
598 "name": "Aurel amber",
599 "hex": "#e09a3e",
600 "shape": "teardrop",
601 "image": "images/block-aurel-amber.png",
602 "terra": false
603 },
604 {
605 "id": "aurel-sage",
606 "name": "Aurel sage",
607 "hex": "#8fb86f",
608 "shape": "plus",
609 "image": "images/block-aurel-sage.png",
610 "terra": false
611 },
612 {
613 "id": "aurel-rose",
614 "name": "Aurel rose",
615 "hex": "#e8a0a8",
616 "shape": "pentagon",
617 "image": "images/block-aurel-rose.png",
618 "terra": false
619 },
620 {
621 "id": "cinder-magma",
622 "name": "Cinder magma",
623 "hex": "#ff3b1f",
624 "shape": "triangle",
625 "image": "images/block-cinder-magma.png",
626 "terra": false
627 },
628 {
629 "id": "cinder-coal",
630 "name": "Cinder coal",
631 "hex": "#3a3232",
632 "shape": "square",
633 "image": "images/block-cinder-coal.png",
634 "terra": false
635 },
636 {
637 "id": "cinder-spark",
638 "name": "Cinder spark",
639 "hex": "#ffb347",
640 "shape": "diamond",
641 "image": "images/block-cinder-spark.png",
642 "terra": false
643 },
644 {
645 "id": "cinder-ash",
646 "name": "Cinder ash",
647 "hex": "#8a7a76",
648 "shape": "circle",
649 "image": "images/block-cinder-ash.png",
650 "terra": false
651 },
652 {
653 "id": "cinder-core",
654 "name": "Cinder core",
655 "hex": "#ff6a00",
656 "shape": "star",
657 "image": "images/block-cinder-core.png",
658 "terra": false
659 },
660 {
661 "id": "lunara-silver",
662 "name": "Lunara silver",
663 "hex": "#c5d0e0",
664 "shape": "circle",
665 "image": "images/block-lunara-silver.png",
666 "terra": false
667 },
668 {
669 "id": "lunara-dust",
670 "name": "Lunara dust",
671 "hex": "#8b90a0",
672 "shape": "diamond",
673 "image": "images/block-lunara-dust.png",
674 "terra": false
675 },
676 {
677 "id": "lunara-pale",
678 "name": "Lunara pale",
679 "hex": "#e8d9a8",
680 "shape": "crescent",
681 "image": "images/block-lunara-pale.png",
682 "terra": false
683 },
684 {
685 "id": "lunara-void",
686 "name": "Lunara void",
687 "hex": "#2c3348",
688 "shape": "square",
689 "image": "images/block-lunara-void.png",
690 "terra": false
691 },
692 {
693 "id": "lunara-lilac",
694 "name": "Lunara lilac",
695 "hex": "#b9a4d4",
696 "shape": "star",
697 "image": "images/block-lunara-lilac.png",
698 "terra": false
699 },
700 {
701 "id": "mire-moss",
702 "name": "Mire moss",
703 "hex": "#3d7a45",
704 "shape": "hexagon",
705 "image": "images/block-mire-moss.png",
706 "terra": false
707 },
708 {
709 "id": "mire-bog",
710 "name": "Mire bog",
711 "hex": "#1f4d3a",
712 "shape": "teardrop",
713 "image": "images/block-mire-bog.png",
714 "terra": false
715 },
716 {
717 "id": "mire-rust",
718 "name": "Mire rust",
719 "hex": "#8b5a2b",
720 "shape": "pentagon",
721 "image": "images/block-mire-rust.png",
722 "terra": false
723 },
724 {
725 "id": "mire-spore",
726 "name": "Mire spore",
727 "hex": "#9cbf5a",
728 "shape": "circle",
729 "image": "images/block-mire-spore.png",
730 "terra": false
731 },
732 {
733 "id": "mire-murk",
734 "name": "Mire murk",
735 "hex": "#2e3b2f",
736 "shape": "diamond",
737 "image": "images/block-mire-murk.png",
738 "terra": false
739 },
740 {
741 "id": "galeon-sky",
742 "name": "Galeon sky",
743 "hex": "#4aa3ff",
744 "shape": "arrow",
745 "image": "images/block-galeon-sky.png",
746 "terra": false
747 },
748 {
749 "id": "galeon-cloud",
750 "name": "Galeon cloud",
751 "hex": "#e8eef6",
752 "shape": "circle",
753 "image": "images/block-galeon-cloud.png",
754 "terra": false
755 },
756 {
757 "id": "galeon-storm",
758 "name": "Galeon storm",
759 "hex": "#3d4d6e",
760 "shape": "square",
761 "image": "images/block-galeon-storm.png",
762 "terra": false
763 },
764 {
765 "id": "galeon-sand",
766 "name": "Galeon sand",
767 "hex": "#d4b483",
768 "shape": "diamond",
769 "image": "images/block-galeon-sand.png",
770 "terra": false
771 },
772 {
773 "id": "galeon-kite",
774 "name": "Galeon kite",
775 "hex": "#7fd0c0",
776 "shape": "star",
777 "image": "images/block-galeon-kite.png",
778 "terra": false
779 },
780 {
781 "id": "obsid-glass",
782 "name": "Obsid glass",
783 "hex": "#1a1a22",
784 "shape": "gem",
785 "image": "images/block-obsid-glass.png",
786 "terra": false
787 },
788 {
789 "id": "obsid-violet",
790 "name": "Obsid violet",
791 "hex": "#5a3d8a",
792 "shape": "hexagon",
793 "image": "images/block-obsid-violet.png",
794 "terra": false
795 },
796 {
797 "id": "obsid-shard",
798 "name": "Obsid shard",
799 "hex": "#8a8aa0",
800 "shape": "triangle",
801 "image": "images/block-obsid-shard.png",
802 "terra": false
803 },
804 {
805 "id": "obsid-vein",
806 "name": "Obsid vein",
807 "hex": "#c45a3a",
808 "shape": "diamond",
809 "image": "images/block-obsid-vein.png",
810 "terra": false
811 },
812 {
813 "id": "obsid-basalt",
814 "name": "Obsid basalt",
815 "hex": "#3a3a42",
816 "shape": "square",
817 "image": "images/block-obsid-basalt.png",
818 "terra": false
819 },
820 {
821 "id": "wisp-glow",
822 "name": "Wisp glow",
823 "hex": "#c8ffe0",
824 "shape": "circle",
825 "image": "images/block-wisp-glow.png",
826 "terra": false
827 },
828 {
829 "id": "wisp-mist",
830 "name": "Wisp mist",
831 "hex": "#a8d4e8",
832 "shape": "diamond",
833 "image": "images/block-wisp-mist.png",
834 "terra": false
835 },
836 {
837 "id": "wisp-sparkle",
838 "name": "Wisp sparkle",
839 "hex": "#fff6a8",
840 "shape": "star",
841 "image": "images/block-wisp-sparkle.png",
842 "terra": false
843 },
844 {
845 "id": "wisp-veil",
846 "name": "Wisp veil",
847 "hex": "#d0b8f0",
848 "shape": "teardrop",
849 "image": "images/block-wisp-veil.png",
850 "terra": false
851 },
852 {
853 "id": "wisp-gleam",
854 "name": "Wisp gleam",
855 "hex": "#f4f7ff",
856 "shape": "plus",
857 "image": "images/block-wisp-gleam.png",
858 "terra": false
859 },
860 {
861 "id": "thorn-briar",
862 "name": "Thorn briar",
863 "hex": "#5a7a30",
864 "shape": "triangle",
865 "image": "images/block-thorn-briar.png",
866 "terra": false
867 },
868 {
869 "id": "thorn-berry",
870 "name": "Thorn berry",
871 "hex": "#8b1a4a",
872 "shape": "circle",
873 "image": "images/block-thorn-berry.png",
874 "terra": false
875 },
876 {
877 "id": "thorn-bark",
878 "name": "Thorn bark",
879 "hex": "#5a3a20",
880 "shape": "square",
881 "image": "images/block-thorn-bark.png",
882 "terra": false
883 },
884 {
885 "id": "thorn-petal",
886 "name": "Thorn petal",
887 "hex": "#e89ab0",
888 "shape": "diamond",
889 "image": "images/block-thorn-petal.png",
890 "terra": false
891 },
892 {
893 "id": "thorn-gold",
894 "name": "Thorn gold",
895 "hex": "#c8a030",
896 "shape": "star",
897 "image": "images/block-thorn-gold.png",
898 "terra": false
899 },
900 {
901 "id": "zephyr-azure",
902 "name": "Zephyr azure",
903 "hex": "#6ec8ff",
904 "shape": "crescent",
905 "image": "images/block-zephyr-azure.png",
906 "terra": false
907 },
908 {
909 "id": "zephyr-breeze",
910 "name": "Zephyr breeze",
911 "hex": "#b8e8ff",
912 "shape": "circle",
913 "image": "images/block-zephyr-breeze.png",
914 "terra": false
915 },
916 {
917 "id": "zephyr-cirrus",
918 "name": "Zephyr cirrus",
919 "hex": "#f0f7ff",
920 "shape": "plus",
921 "image": "images/block-zephyr-cirrus.png",
922 "terra": false
923 },
924 {
925 "id": "zephyr-dusk",
926 "name": "Zephyr dusk",
927 "hex": "#7a6ab0",
928 "shape": "diamond",
929 "image": "images/block-zephyr-dusk.png",
930 "terra": false
931 },
932 {
933 "id": "zephyr-haze",
934 "name": "Zephyr haze",
935 "hex": "#ffe08a",
936 "shape": "star",
937 "image": "images/block-zephyr-haze.png",
938 "terra": false
939 },
940 {
941 "id": "frore-ice",
942 "name": "Frore ice",
943 "hex": "#a8d8f0",
944 "shape": "hexagon",
945 "image": "images/block-frore-ice.png",
946 "terra": false
947 },
948 {
949 "id": "frore-frost",
950 "name": "Frore frost",
951 "hex": "#eef7ff",
952 "shape": "circle",
953 "image": "images/block-frore-frost.png",
954 "terra": false
955 },
956 {
957 "id": "frore-deep",
958 "name": "Frore deep",
959 "hex": "#3a6a8a",
960 "shape": "diamond",
961 "image": "images/block-frore-deep.png",
962 "terra": false
963 },
964 {
965 "id": "frore-aurora",
966 "name": "Frore aurora",
967 "hex": "#5ae8c0",
968 "shape": "star",
969 "image": "images/block-frore-aurora.png",
970 "terra": false
971 },
972 {
973 "id": "frore-rime",
974 "name": "Frore rime",
975 "hex": "#d0e4f0",
976 "shape": "triangle",
977 "image": "images/block-frore-rime.png",
978 "terra": false
979 },
980 {
981 "id": "forge-iron",
982 "name": "Forge iron",
983 "hex": "#6a6a72",
984 "shape": "square",
985 "image": "images/block-forge-iron.png",
986 "terra": false
987 },
988 {
989 "id": "forge-slag",
990 "name": "Forge slag",
991 "hex": "#3a3028",
992 "shape": "hexagon",
993 "image": "images/block-forge-slag.png",
994 "terra": false
995 },
996 {
997 "id": "forge-spark",
998 "name": "Forge spark",
999 "hex": "#ff7a1a",
1000 "shape": "triangle",
1001 "image": "images/block-forge-spark.png",
1002 "terra": false
1003 },
1004 {
1005 "id": "forge-brass",
1006 "name": "Forge brass",
1007 "hex": "#c8a048",
1008 "shape": "diamond",
1009 "image": "images/block-forge-brass.png",
1010 "terra": false
1011 },
1012 {
1013 "id": "forge-soot",
1014 "name": "Forge soot",
1015 "hex": "#2a2a28",
1016 "shape": "circle",
1017 "image": "images/block-forge-soot.png",
1018 "terra": false
1019 }
1020 ]
1021}
1022;
190
1023
191/*
1024/*
192 * Start File:
1025 * Start File:
@@ -353,6 +1186,34 @@ function loadCatalog ()
353 return { planets: [] };
1186 return { planets: [] };
354}
1187}
355
1188
1189/** Player-owned custom planets (from the profile) and any remembered
1190 * snapshots (opponents in a lobby), not part of the official catalog. */
1191var _customPlanets = [];
1192var _remembered = Object.create(null);
1193
1194function setCustomPlanets (list)
1195{
1196 _customPlanets = [];
1197 if (!list || !list.length)
1198 { return; }
1199 for (var i = 0; i < list.length; i++)
1200 { _customPlanets.push(planetFromData(list[i])); }
1201}
1202
1203function rememberPlanet (data)
1204{
1205 if (!data || !data.id)
1206 { return null; }
1207 var pl = planetFromData(data);
1208 _remembered[pl.id] = pl;
1209 return pl;
1210}
1211
1212function forgetRemembered ()
1213{
1214 _remembered = Object.create(null);
1215}
1216
356function planetFromData (data)
1217function planetFromData (data)
357{
1218{
358 var planet = createPlanet({
1219 var planet = createPlanet({
@@ -364,6 +1225,10 @@ function planetFromData (data)
364 colors: data.colors
1225 colors: data.colors
365 });
1226 });
366 planet.id = data.id;
1227 planet.id = data.id;
1228 if (data.custom)
1229 { planet.custom = true; }
1230 if (data.owner_id)
1231 { planet.owner_id = data.owner_id; }
367 return planet;
1232 return planet;
368}
1233}
369
1234
@@ -375,6 +1240,8 @@ function allPlanets ()
375 { out.push(planetFromData(raw[i])); }
1240 { out.push(planetFromData(raw[i])); }
376 if (out.length === 0)
1241 if (out.length === 0)
377 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
1242 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
1243 for (var c = 0; c < _customPlanets.length; c++)
1244 { out.push(_customPlanets[c]); }
378 return out;
1245 return out;
379}
1246}
380
1247
@@ -386,9 +1253,30 @@ function planetById (id)
386 if (all[i].id === id)
1253 if (all[i].id === id)
387 { return all[i]; }
1254 { return all[i]; }
388 }
1255 }
1256 if (id && _remembered[id])
1257 { return _remembered[id]; }
389 return defaultPlanet();
1258 return defaultPlanet();
390}
1259}
391
1260
1261function officialPlanets ()
1262{
1263 var raw = loadCatalog().planets || [];
1264 var out = [];
1265 for (var i = 0; i < raw.length; i++)
1266 { out.push(planetFromData(raw[i])); }
1267 return out;
1268}
1269
1270function customPlanets ()
1271{
1272 return _customPlanets.slice();
1273}
1274
1275function pickerPlanets ()
1276{
1277 return officialPlanets().concat(_customPlanets);
1278}
1279
392function defaultPlanet ()
1280function defaultPlanet ()
393{
1281{
394 var all = allPlanets();
1282 var all = allPlanets();
@@ -415,6 +1303,11 @@ function spriteKey (planet, colorIndex)
415 var c = colors && colors[colorIndex];
1303 var c = colors && colors[colorIndex];
416 if (!c)
1304 if (!c)
417 { return 'gray'; }
1305 { return 'gray'; }
1306 // Custom planets (and any color that names a registry block) share
1307 // the preloaded Blocks.images() sprite, so late-loaded customs and
1308 // opponent snapshots do not need a second preload.
1309 if (c.block)
1310 { return 'block:' + c.block; }
418 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
1311 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
419}
1312}
420
1313
@@ -512,6 +1405,12 @@ var Planet = {
512 defaultPlanet: defaultPlanet,
1405 defaultPlanet: defaultPlanet,
513 defaultColors: defaultColors,
1406 defaultColors: defaultColors,
514 allPlanets: allPlanets,
1407 allPlanets: allPlanets,
1408 officialPlanets: officialPlanets,
1409 customPlanets: customPlanets,
1410 pickerPlanets: pickerPlanets,
1411 setCustomPlanets: setCustomPlanets,
1412 rememberPlanet: rememberPlanet,
1413 forgetRemembered: forgetRemembered,
515 planetById: planetById,
1414 planetById: planetById,
516 planetFromData: planetFromData,
1415 planetFromData: planetFromData,
517 formatStats: formatStats,
1416 formatStats: formatStats,
@@ -528,13 +1427,183 @@ var Planet = {
528};
1427};
529
1428
530if (typeof module !== 'undefined' && module.exports)
1429if (typeof module !== 'undefined' && module.exports)
531{ module.exports = Planet; }
1430{ module.exports = Planet; }
1431else if (typeof globalThis !== 'undefined')
1432{ globalThis.Planet = Planet; }
1433
1434/*
1435 * End File:
1436 * /workspace/meteors/src/planet.js
1437 */
1438
1439/*
1440 * Start File:
1441 * /workspace/meteors/src/blocks.js
1442 */
1443'use strict';
1444
1445/**
1446 * Append-only block registry. Thresholds and order stay in lockstep with
1447 * server/lib/Blocks.php: Terra's first five are free; the next costs 500
1448 * lifetime points; each one after that costs 14.5% more (rounded, always
1449 * strictly increasing). Points are a requirement, not a spend.
1450 */
1451
1452var Blocks = (function ()
1453{
1454 var TERRA_COUNT = 5;
1455 var FIRST_THRESHOLD = 500;
1456 var GROWTH = 1.145;
1457 var _all = null;
1458
1459 function loadRegistry ()
1460 {
1461 if (_all)
1462 { return _all; }
1463 var data = null;
1464 if (typeof BLOCK_REGISTRY !== 'undefined' && BLOCK_REGISTRY && BLOCK_REGISTRY.blocks)
1465 { data = BLOCK_REGISTRY; }
1466 else if (typeof require !== 'undefined')
1467 {
1468 try
1469 { data = require('../server/lib/blocks.json'); }
1470 catch (e) { data = null; }
1471 }
1472 _all = (data && data.blocks) ? data.blocks.slice() : [];
1473 return _all;
1474 }
1475
1476 function all ()
1477 {
1478 return loadRegistry();
1479 }
1480
1481 function byId (id)
1482 {
1483 var list = all();
1484 for (var i = 0; i < list.length; i++)
1485 {
1486 if (list[i].id === id)
1487 { return list[i]; }
1488 }
1489 return null;
1490 }
1491
1492 function indexOf (id)
1493 {
1494 var list = all();
1495 for (var i = 0; i < list.length; i++)
1496 {
1497 if (list[i].id === id)
1498 { return i; }
1499 }
1500 return -1;
1501 }
1502
1503 function threshold (index)
1504 {
1505 if (index < TERRA_COUNT)
1506 { return 0; }
1507 var t = FIRST_THRESHOLD;
1508 for (var i = TERRA_COUNT; i < index; i++)
1509 {
1510 var next = Math.round(t * GROWTH);
1511 t = Math.max(t + 1, next);
1512 }
1513 return t;
1514 }
1515
1516 function unlocked (index, points)
1517 {
1518 points = points || 0;
1519 return points >= threshold(index);
1520 }
1521
1522 function unlockedId (id, points)
1523 {
1524 var i = indexOf(id);
1525 return i >= 0 && unlocked(i, points);
1526 }
1527
1528 function present (points)
1529 {
1530 points = points || 0;
1531 var list = all();
1532 var out = [];
1533 for (var i = 0; i < list.length; i++)
1534 {
1535 var b = list[i];
1536 var need = threshold(i);
1537 out.push({
1538 id: b.id,
1539 name: b.name || b.id,
1540 hex: b.hex,
1541 shape: b.shape,
1542 image: b.image,
1543 terra: !!b.terra || i < TERRA_COUNT,
1544 index: i,
1545 threshold: need,
1546 unlocked: points >= need
1547 });
1548 }
1549 return out;
1550 }
1551
1552 function asColor (id, slot)
1553 {
1554 var b = byId(id);
1555 if (!b)
1556 { return null; }
1557 return {
1558 id: slot,
1559 block: b.id,
1560 name: b.name || b.id,
1561 hex: b.hex,
1562 shape: b.shape,
1563 image: b.image
1564 };
1565 }
1566
1567 function images ()
1568 {
1569 var list = all();
1570 var out = [];
1571 var seen = Object.create(null);
1572 for (var i = 0; i < list.length; i++)
1573 {
1574 var url = list[i].image;
1575 if (!url || seen[url])
1576 { continue; }
1577 seen[url] = true;
1578 out.push({ name: 'block:' + list[i].id, url: url });
1579 }
1580 return out;
1581 }
1582
1583 return {
1584 TERRA_COUNT: TERRA_COUNT,
1585 FIRST_THRESHOLD: FIRST_THRESHOLD,
1586 GROWTH: GROWTH,
1587 all: all,
1588 byId: byId,
1589 indexOf: indexOf,
1590 threshold: threshold,
1591 unlocked: unlocked,
1592 unlockedId: unlockedId,
1593 present: present,
1594 asColor: asColor,
1595 images: images
1596 };
1597})();
1598
1599if (typeof module !== 'undefined' && module.exports)
1600{ module.exports = Blocks; }
532else if (typeof globalThis !== 'undefined')
1601else if (typeof globalThis !== 'undefined')
533{ globalThis.Planet = Planet; }
1602{ globalThis.Blocks = Blocks; }
534
1603
535/*
1604/*
536 * End File:
1605 * End File:
537 * /workspace/meteors/src/planet.js
1606 * /workspace/meteors/src/blocks.js
538 */
1607 */
539
1608
540/*
1609/*
@@ -4074,6 +5143,10 @@ var Online = {
4074 local: false,
5143 local: false,
4075 csrf: '',
5144 csrf: '',
4076 me: null,
5145 me: null,
5146 lifetimePoints: 0,
5147 locale: null,
5148 blocks: [],
5149 planets: [],
4077 lobby: null,
5150 lobby: null,
4078 incoming: [],
5151 incoming: [],
4079 shotResults: [],
5152 shotResults: [],
@@ -4125,6 +5198,26 @@ Online._apply = function (data)
4125 { this.error = data.error; }
5198 { this.error = data.error; }
4126 else if (data.ok)
5199 else if (data.ok)
4127 { this.error = ''; }
5200 { this.error = ''; }
5201 if (data.lifetime_points != null)
5202 { this.lifetimePoints = data.lifetime_points; }
5203 if (data.locale !== undefined)
5204 { this.locale = data.locale; }
5205 if (data.blocks)
5206 { this.blocks = data.blocks; }
5207 if (data.planets)
5208 {
5209 this.planets = data.planets;
5210 if (typeof Planet !== 'undefined' && Planet.setCustomPlanets)
5211 { Planet.setCustomPlanets(data.planets); }
5212 }
5213 if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet)
5214 {
5215 for (var i = 0; i < data.lobby.players.length; i++)
5216 {
5217 if (data.lobby.players[i].planet)
5218 { Planet.rememberPlanet(data.lobby.players[i].planet); }
5219 }
5220 }
4128};
5221};
4129
5222
4130Online.request = function (action, body)
5223Online.request = function (action, body)
@@ -4196,6 +5289,31 @@ Online.setPlanet = function (planetId)
4196 return this.request('lobby_set_planet', { planet_id: planetId });
5289 return this.request('lobby_set_planet', { planet_id: planetId });
4197};
5290};
4198
5291
5292Online.playBegin = function (mode)
5293{
5294 return this.request('play_begin', { mode: mode || 'solo' });
5295};
5296
5297Online.playFinish = function (token, score)
5298{
5299 return this.request('play_finish', { token: token, score: score || 0 });
5300};
5301
5302Online.savePlanet = function (planet)
5303{
5304 return this.request('planet_save', { planet: planet });
5305};
5306
5307Online.deletePlanet = function (id)
5308{
5309 return this.request('planet_delete', { id: id });
5310};
5311
5312Online.setLocale = function (locale)
5313{
5314 return this.request('set_locale', { locale: locale });
5315};
5316
4199Online.leaveLobby = function ()
5317Online.leaveLobby = function ()
4200{
5318{
4201 return this.request('lobby_leave');
5319 return this.request('lobby_leave');
@@ -6444,6 +7562,545 @@ if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undef
6444 * /workspace/meteors/src/offline.js
7562 * /workspace/meteors/src/offline.js
6445 */
7563 */
6446
7564
7565/*
7566 * Start File:
7567 * /workspace/meteors/src/designer.js
7568 */
7569'use strict';
7570
7571/**
7572 * Planeetontwerper (t1139). Only available on the main menu when the
7573 * player is logged in. Talks to api.php through Online.
7574 */
7575var Designer = {
7576 openSlot: 0,
7577 editingId: null,
7578 slots: [null, null, null, null, null],
7579 dirty: false
7580};
7581
7582Designer._blocks = function ()
7583{
7584 if (typeof Blocks !== 'undefined')
7585 { return Blocks; }
7586 if (typeof require !== 'undefined')
7587 {
7588 try
7589 { return require('./blocks.js'); }
7590 catch (e)
7591 { return null; }
7592 }
7593 return null;
7594};
7595
7596Designer.defaultSlots = function ()
7597{
7598 var B = Designer._blocks();
7599 var all = B ? B.all() : [];
7600 var ids = [];
7601 for (var i = 0; i < 5 && i < all.length; i++)
7602 { ids.push(all[i].id); }
7603 return ids;
7604};
7605
7606Designer.points = function ()
7607{
7608 return (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
7609};
7610
7611Designer.blocks = function ()
7612{
7613 if (typeof Online !== 'undefined' && Online.blocks && Online.blocks.length)
7614 { return Online.blocks; }
7615 var B = Designer._blocks();
7616 if (B)
7617 { return B.present(Designer.points()); }
7618 return [];
7619};
7620
7621Designer.planets = function ()
7622{
7623 if (typeof Planet !== 'undefined' && Planet.customPlanets)
7624 { return Planet.customPlanets(); }
7625 return (typeof Online !== 'undefined' && Online.planets) || [];
7626};
7627
7628Designer.openList = function ()
7629{
7630 if (typeof Online === 'undefined' || !Online.me)
7631 { return; }
7632 if (typeof app !== 'undefined')
7633 { app.mode = 'designer'; }
7634 hideIf('menu');
7635 hideIf('planet-select');
7636 hideIf('online-panel');
7637 hideIf('designer-edit');
7638 showIf('designer');
7639 Designer.renderList();
7640};
7641
7642Designer.close = function ()
7643{
7644 hideIf('designer');
7645 hideIf('designer-edit');
7646 Designer.closeModal();
7647 if (typeof app !== 'undefined')
7648 { app.mode = 'menu'; }
7649 showIf('menu');
7650 if (typeof refreshMenuAccount === 'function')
7651 { refreshMenuAccount(); }
7652 if (typeof renderPlanetGrid === 'function')
7653 {
7654 renderPlanetGrid('planet-grid', false);
7655 renderPlanetGrid('lobby-planet-grid', true);
7656 }
7657};
7658
7659Designer.renderList = function ()
7660{
7661 var box = document.getElementById('designer-list');
7662 var pts = document.getElementById('designer-points');
7663 if (pts)
7664 { pts.textContent = String(Designer.points()); }
7665 if (!box)
7666 { return; }
7667 box.innerHTML = '';
7668 var planets = Designer.planets();
7669 if (!planets.length)
7670 {
7671 var empty = document.createElement('p');
7672 empty.className = 'hint';
7673 empty.textContent = 'Je hebt nog geen eigen planeten. Maak er een aan.';
7674 box.appendChild(empty);
7675 return;
7676 }
7677 for (var i = 0; i < planets.length; i++)
7678 {
7679 var pl = planets[i];
7680 if (typeof Planet !== 'undefined' && Planet.planetFromData && !pl.baseJumpHeight)
7681 { pl = Planet.planetFromData(pl); }
7682 var card = document.createElement('div');
7683 card.className = 'planet-card designer-card';
7684 var swatches = '';
7685 var colors = pl.colors || [];
7686 for (var c = 0; c < colors.length; c++)
7687 {
7688 swatches += '<img src="' + Designer.esc(colors[c].image) + '" alt="'
7689 + Designer.esc(colors[c].name) + '">';
7690 }
7691 var stats = (typeof Planet !== 'undefined' && Planet.formatStats)
7692 ? Planet.formatStats(pl) : '';
7693 card.innerHTML = '<div class="planet-title">' + Designer.esc(pl.name) + '</div>'
7694 + '<div class="planet-people">' + Designer.esc(pl.people) + '</div>'
7695 + '<div class="planet-nums">' + Designer.esc(stats) + '</div>'
7696 + '<div class="planet-swatches">' + swatches + '</div>'
7697 + '<div class="designer-card-actions">'
7698 + '<button type="button" class="btn-tiny" data-edit>Bewerken</button>'
7699 + '<button type="button" class="btn-tiny btn-danger-lite" data-del>Verwijderen</button>'
7700 + '</div>';
7701 (function (id)
7702 {
7703 card.querySelector('[data-edit]').addEventListener('click', function ()
7704 { Designer.openEdit(id); });
7705 card.querySelector('[data-del]').addEventListener('click', function ()
7706 { Designer.confirmDelete(id); });
7707 })(pl.id);
7708 box.appendChild(card);
7709 }
7710};
7711
7712Designer.confirmDelete = function (id)
7713{
7714 var pl = Designer.planetById(id);
7715 var name = pl ? pl.name : id;
7716 if (!window.confirm('Wil je de planeet “' + name + '” verwijderen?'))
7717 { return; }
7718 Online.deletePlanet(id).then(function (data)
7719 {
7720 if (!data || !data.ok)
7721 {
7722 window.alert((data && data.error) || 'Verwijderen is mislukt.');
7723 return;
7724 }
7725 Designer.renderList();
7726 if (typeof renderPlanetGrid === 'function')
7727 {
7728 renderPlanetGrid('planet-grid', false);
7729 renderPlanetGrid('lobby-planet-grid', true);
7730 }
7731 });
7732};
7733
7734Designer.planetById = function (id)
7735{
7736 var list = Designer.planets();
7737 for (var i = 0; i < list.length; i++)
7738 {
7739 if (list[i].id === id)
7740 { return list[i]; }
7741 }
7742 return null;
7743};
7744
7745Designer.openEdit = function (id)
7746{
7747 var pl = id ? Designer.planetById(id) : null;
7748 Designer.editingId = pl ? pl.id : null;
7749 if (pl)
7750 {
7751 Designer.slots = [];
7752 for (var i = 0; i < 5; i++)
7753 {
7754 var c = pl.colors && pl.colors[i];
7755 Designer.slots[i] = c ? (c.block || c.id) : Designer.defaultSlots()[i];
7756 // c.id is the slot index 0-4 on snapshots; prefer c.block
7757 if (c && c.block)
7758 { Designer.slots[i] = c.block; }
7759 else if (c && typeof c.id === 'string')
7760 { Designer.slots[i] = c.id; }
7761 }
7762 document.getElementById('des-name').value = pl.name || '';
7763 document.getElementById('des-people').value = pl.people || '';
7764 document.getElementById('des-gravity').value = String(pl.jumpsToClear != null ? pl.jumpsToClear : 2);
7765 document.getElementById('des-air').value = String(pl.fallTime != null ? pl.fallTime : 3);
7766 document.getElementById('des-mass').value = String(pl.riseTime != null ? pl.riseTime : 1.5);
7767 document.getElementById('designer-edit-title').textContent = 'Planeet bewerken';
7768 document.getElementById('btn-designer-delete').hidden = false;
7769 }
7770 else
7771 {
7772 Designer.slots = Designer.defaultSlots().slice();
7773 document.getElementById('des-name').value = '';
7774 document.getElementById('des-people').value = '';
7775 document.getElementById('des-gravity').value = '2';
7776 document.getElementById('des-air').value = '3';
7777 document.getElementById('des-mass').value = '1.5';
7778 document.getElementById('designer-edit-title').textContent = 'Nieuwe planeet';
7779 document.getElementById('btn-designer-delete').hidden = true;
7780 }
7781 hideIf('designer');
7782 showIf('designer-edit');
7783 Designer.syncPreview();
7784 Designer.renderSlots();
7785 var name = document.getElementById('des-name');
7786 if (name)
7787 { name.focus(); }
7788};
7789
7790Designer.draftPlanet = function ()
7791{
7792 var jumps = clampNum(document.getElementById('des-gravity').value, 1, 4, 2);
7793 var fall = clampNum(document.getElementById('des-air').value, 1, 5, 3);
7794 var rise = clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5);
7795 var colors = [];
7796 for (var i = 0; i < 5; i++)
7797 {
7798 var B = Designer._blocks();
7799 var col = B ? B.asColor(Designer.slots[i], i) : null;
7800 if (col)
7801 { colors.push(col); }
7802 }
7803 var opts = {
7804 id: Designer.editingId || 'draft',
7805 name: (document.getElementById('des-name').value || 'Nieuwe planeet').trim() || 'Nieuwe planeet',
7806 people: (document.getElementById('des-people').value || 'Volk').trim() || 'Volk',
7807 jumpsToClear: jumps,
7808 fallTime: fall,
7809 riseTime: rise,
7810 colors: colors
7811 };
7812 if (typeof Planet === 'undefined')
7813 { return opts; }
7814 return Planet.createPlanet ? (function ()
7815 {
7816 var p = Planet.createPlanet(opts);
7817 p.id = opts.id;
7818 p.custom = true;
7819 return p;
7820 })() : opts;
7821};
7822
7823Designer.syncPreview = function ()
7824{
7825 var p = Designer.draftPlanet();
7826 var d = (typeof Planet !== 'undefined' && Planet.displayValues) ? Planet.displayValues(p) : null;
7827 setText('des-gravity-val', Number(document.getElementById('des-gravity').value).toFixed(1)
7828 + (d ? ' · g ' + d.gravity.toFixed(2) : ''));
7829 setText('des-air-val', Number(document.getElementById('des-air').value).toFixed(1)
7830 + (d ? ' · d ' + d.density.toFixed(2) : ''));
7831 setText('des-mass-val', Number(document.getElementById('des-mass').value).toFixed(1)
7832 + (d ? ' · F ' + Math.round(d.newtons) + ' N' : ''));
7833 var power = d ? d.power : 0;
7834 setText('des-power', 'Power ' + power + '%');
7835};
7836
7837Designer.renderSlots = function ()
7838{
7839 var row = document.getElementById('des-slots');
7840 if (!row)
7841 { return; }
7842 row.innerHTML = '';
7843 for (var i = 0; i < 5; i++)
7844 {
7845 var id = Designer.slots[i];
7846 var B = Designer._blocks();
7847 var b = B ? B.byId(id) : null;
7848 var btn = document.createElement('button');
7849 btn.type = 'button';
7850 btn.className = 'des-slot';
7851 btn.setAttribute('aria-label', 'Blokje ' + (i + 1));
7852 if (b)
7853 {
7854 btn.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="' + Designer.esc(b.name) + '">'
7855 + '<span>' + Designer.esc(b.name) + '</span>';
7856 }
7857 else
7858 {
7859 btn.innerHTML = '<span class="des-slot-empty">Kies</span>';
7860 }
7861 (function (slot)
7862 {
7863 btn.addEventListener('click', function ()
7864 { Designer.openModal(slot); });
7865 })(i);
7866 row.appendChild(btn);
7867 }
7868};
7869
7870Designer.openModal = function (slot)
7871{
7872 Designer.openSlot = slot;
7873 var modal = document.getElementById('des-modal');
7874 var grid = document.getElementById('des-modal-grid');
7875 if (!modal || !grid)
7876 { return; }
7877 grid.innerHTML = '';
7878 var blocks = Designer.blocks();
7879 var used = Object.create(null);
7880 for (var i = 0; i < 5; i++)
7881 {
7882 if (i !== slot && Designer.slots[i])
7883 { used[Designer.slots[i]] = true; }
7884 }
7885 for (var i = 0; i < blocks.length; i++)
7886 {
7887 var b = blocks[i];
7888 var cell = document.createElement('button');
7889 cell.type = 'button';
7890 cell.className = 'des-block';
7891 cell.dataset.id = b.id;
7892 var locked = !b.unlocked;
7893 var taken = !!used[b.id];
7894 if (locked)
7895 { cell.classList.add('locked'); }
7896 if (taken)
7897 { cell.classList.add('used'); }
7898 if (Designer.slots[slot] === b.id)
7899 { cell.classList.add('current'); }
7900 var title = b.name;
7901 if (locked)
7902 { title += ' — ' + b.threshold + ' punten nodig'; }
7903 else if (taken)
7904 { title += ' — al in een ander vak'; }
7905 cell.title = title;
7906 cell.setAttribute('aria-label', title);
7907 cell.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="">'
7908 + (locked ? '<span class="des-lock" aria-hidden="true">'
7909 + '<svg viewBox="0 0 18 18" width="16" height="16">'
7910 + '<rect x="4" y="8" width="10" height="8" rx="1.5" fill="#ffe27a"/>'
7911 + '<path d="M6 8 V6 a3 3 0 0 1 6 0 v2" fill="none" stroke="#ffe27a" stroke-width="1.8" stroke-linecap="round"/>'
7912 + '<circle cx="9" cy="12" r="1.2" fill="#1a1628"/>'
7913 + '</svg></span>' : '')
7914 + '<span class="des-block-name">' + Designer.esc(b.name) + '</span>'
7915 + (locked ? '<span class="des-block-need">' + b.threshold + '</span>' : '');
7916 if (locked || taken)
7917 { cell.disabled = true; }
7918 else
7919 {
7920 cell.addEventListener('click', (function (id)
7921 {
7922 return function ()
7923 {
7924 Designer.slots[Designer.openSlot] = id;
7925 Designer.closeModal();
7926 Designer.renderSlots();
7927 };
7928 })(b.id));
7929 }
7930 grid.appendChild(cell);
7931 }
7932 modal.hidden = false;
7933 modal.setAttribute('aria-hidden', 'false');
7934 var close = document.getElementById('des-modal-close');
7935 if (close)
7936 { close.focus(); }
7937};
7938
7939Designer.closeModal = function ()
7940{
7941 var modal = document.getElementById('des-modal');
7942 if (!modal)
7943 { return; }
7944 modal.hidden = true;
7945 modal.setAttribute('aria-hidden', 'true');
7946};
7947
7948Designer.save = function ()
7949{
7950 var name = (document.getElementById('des-name').value || '').trim();
7951 var people = (document.getElementById('des-people').value || '').trim();
7952 if (!name || !people)
7953 {
7954 window.alert('Vul een naam voor de planeet en voor de bevolking in.');
7955 return;
7956 }
7957 for (var i = 0; i < 5; i++)
7958 {
7959 if (!Designer.slots[i])
7960 {
7961 window.alert('Kies vijf blokjes.');
7962 return;
7963 }
7964 }
7965 var payload = {
7966 id: Designer.editingId || undefined,
7967 name: name,
7968 people: people,
7969 jumpsToClear: clampNum(document.getElementById('des-gravity').value, 1, 4, 2),
7970 fallTime: clampNum(document.getElementById('des-air').value, 1, 5, 3),
7971 riseTime: clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5),
7972 colors: Designer.slots.slice()
7973 };
7974 Online.savePlanet(payload).then(function (data)
7975 {
7976 if (!data || !data.ok)
7977 {
7978 window.alert((data && data.error) || 'Opslaan is mislukt.');
7979 return;
7980 }
7981 hideIf('designer-edit');
7982 showIf('designer');
7983 Designer.editingId = data.planet ? data.planet.id : null;
7984 Designer.renderList();
7985 if (typeof renderPlanetGrid === 'function')
7986 {
7987 renderPlanetGrid('planet-grid', false);
7988 renderPlanetGrid('lobby-planet-grid', true);
7989 }
7990 });
7991};
7992
7993Designer.bind = function ()
7994{
7995 var btn = document.getElementById('btn-designer');
7996 if (btn)
7997 { btn.addEventListener('click', function () { Designer.openList(); }); }
7998 var back = document.getElementById('btn-designer-back');
7999 if (back)
8000 { back.addEventListener('click', Designer.close); }
8001 var neu = document.getElementById('btn-designer-new');
8002 if (neu)
8003 { neu.addEventListener('click', function () { Designer.openEdit(null); }); }
8004 var cancel = document.getElementById('btn-designer-cancel');
8005 if (cancel)
8006 {
8007 cancel.addEventListener('click', function ()
8008 {
8009 hideIf('designer-edit');
8010 showIf('designer');
8011 Designer.renderList();
8012 });
8013 }
8014 var save = document.getElementById('btn-designer-save');
8015 if (save)
8016 { save.addEventListener('click', function (e) { e.preventDefault(); Designer.save(); }); }
8017 var form = document.getElementById('designer-form');
8018 if (form)
8019 { form.addEventListener('submit', function (e) { e.preventDefault(); Designer.save(); }); }
8020 var del = document.getElementById('btn-designer-delete');
8021 if (del)
8022 {
8023 del.addEventListener('click', function ()
8024 {
8025 if (!Designer.editingId)
8026 { return; }
8027 Designer.confirmDelete(Designer.editingId);
8028 hideIf('designer-edit');
8029 showIf('designer');
8030 });
8031 }
8032 ['des-gravity', 'des-air', 'des-mass'].forEach(function (id)
8033 {
8034 var el = document.getElementById(id);
8035 if (!el)
8036 { return; }
8037 el.addEventListener('input', Designer.syncPreview);
8038 });
8039 var modal = document.getElementById('des-modal');
8040 if (modal)
8041 {
8042 modal.addEventListener('click', function (e)
8043 {
8044 if (e.target === modal)
8045 { Designer.closeModal(); }
8046 });
8047 }
8048 var close = document.getElementById('des-modal-close');
8049 if (close)
8050 { close.addEventListener('click', Designer.closeModal); }
8051 document.addEventListener('keydown', function (e)
8052 {
8053 if (e.key === 'Escape')
8054 { Designer.closeModal(); }
8055 });
8056};
8057
8058Designer.esc = function (s)
8059{
8060 return String(s == null ? '' : s)
8061 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
8062 .replace(/"/g, '&quot;');
8063};
8064
8065function hideIf (id)
8066{
8067 var el = document.getElementById(id);
8068 if (el)
8069 { el.hidden = true; }
8070}
8071
8072function showIf (id)
8073{
8074 var el = document.getElementById(id);
8075 if (el)
8076 { el.hidden = false; }
8077}
8078
8079function setText (id, text)
8080{
8081 var el = document.getElementById(id);
8082 if (el)
8083 { el.textContent = text; }
8084}
8085
8086function clampNum (v, lo, hi, fallback)
8087{
8088 var n = Number(v);
8089 if (!isFinite(n))
8090 { n = fallback; }
8091 return Math.max(lo, Math.min(hi, n));
8092}
8093
8094if (typeof module !== 'undefined' && module.exports)
8095{ module.exports = Designer; }
8096else if (typeof globalThis !== 'undefined')
8097{ globalThis.Designer = Designer; }
8098
8099/*
8100 * End File:
8101 * /workspace/meteors/src/designer.js
8102 */
8103
6447/*
8104/*
6448 * Start File:
8105 * Start File:
6449 * /workspace/meteors/src/main.js
8106 * /workspace/meteors/src/main.js
@@ -6486,6 +8143,12 @@ function planetImages ()
6486 });
8143 });
6487 }
8144 }
6488 }
8145 }
8146 if (typeof Blocks !== 'undefined' && Blocks.images)
8147 {
8148 var extra = Blocks.images();
8149 for (var b = 0; b < extra.length; b++)
8150 { list.push(extra[b]); }
8151 }
6489 return list;
8152 return list;
6490}
8153}
6491
8154
@@ -6560,6 +8223,20 @@ window.onload = function ()
6560 bindOfflineUi();
8223 bindOfflineUi();
6561 bindPlanetSelect();
8224 bindPlanetSelect();
6562 restoreSelectedPlanet();
8225 restoreSelectedPlanet();
8226 if (typeof Designer !== 'undefined' && Designer.bind)
8227 { Designer.bind(); }
8228 if (typeof Online !== 'undefined' && Online.refresh)
8229 {
8230 Online.refresh().then(function ()
8231 {
8232 refreshMenuAccount();
8233 restoreSelectedPlanet();
8234 renderPlanetGrid('planet-grid', false);
8235 renderPlanetGrid('lobby-planet-grid', true);
8236 });
8237 }
8238 else
8239 { refreshMenuAccount(); }
6563};
8240};
6564
8241
6565function onPlay ()
8242function onPlay ()
@@ -6579,6 +8256,10 @@ function startPlay (opts)
6579 hideEl('podium');
8256 hideEl('podium');
6580 hideEl('planet-select');
8257 hideEl('planet-select');
6581 hideEl('offline-result');
8258 hideEl('offline-result');
8259 hideEl('designer');
8260 hideEl('designer-edit');
8261 if (typeof Designer !== 'undefined' && Designer.closeModal)
8262 { Designer.closeModal(); }
6582 showEl('hud');
8263 showEl('hud');
6583
8264
6584 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
8265 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
@@ -6642,6 +8323,8 @@ function startPlay (opts)
6642 buildColumnWarn();
8323 buildColumnWarn();
6643 refreshOfflineHud();
8324 refreshOfflineHud();
6644 refreshChainIndicator();
8325 refreshChainIndicator();
8326 if (!opts.online)
8327 { beginPlaySession(opts.offline ? 'offline' : 'solo'); }
6645}
8328}
6646
8329
6647function teardownPlay ()
8330function teardownPlay ()
@@ -7234,7 +8917,10 @@ function tickView (dt)
7234 else if (app.offline)
8917 else if (app.offline)
7235 { /* Offline result is shown from tickOffline. */ }
8918 { /* Offline result is shown from tickOffline. */ }
7236 else
8919 else
7237 { showEl('game-over'); }
8920 {
8921 showEl('game-over');
8922 finishPlaySession(app.lastScore);
8923 }
7238 }
8924 }
7239 if (!app.online && !app.offline && app.core.state === 'gameover'
8925 if (!app.online && !app.offline && app.core.state === 'gameover'
7240 && app.core.gameOverTime >= GAME_OVER_DELAY)
8926 && app.core.gameOverTime >= GAME_OVER_DELAY)
@@ -7845,6 +9531,8 @@ function startNextOfflineRound ()
7845 // Tear down the current scene then start a fresh player field,
9531 // Tear down the current scene then start a fresh player field,
7846 // keeping the same battle (already advanced).
9532 // keeping the same battle (already advanced).
7847 var planet = app.battle.playerPlanet;
9533 var planet = app.battle.playerPlanet;
9534 var roundScore = app.core ? app.core.score : 0;
9535 finishPlaySession(roundScore);
7848 app._keepBattleOnTeardown = true;
9536 app._keepBattleOnTeardown = true;
7849 teardownPlay();
9537 teardownPlay();
7850 app.offline = true;
9538 app.offline = true;
@@ -7870,6 +9558,7 @@ function showOfflineResult ()
7870 }
9558 }
7871 hideEl('game-over');
9559 hideEl('game-over');
7872 showEl('offline-result');
9560 showEl('offline-result');
9561 finishPlaySession(app.core ? app.core.score : 0);
7873}
9562}
7874
9563
7875function refreshOfflineHud ()
9564function refreshOfflineHud ()
@@ -8181,10 +9870,18 @@ function startOnlineMatch ()
8181 if (app.mode === 'playing' && app.online)
9870 if (app.mode === 'playing' && app.online)
8182 { return; }
9871 { return; }
8183 var planet = Planet.planetById(selectedPlanetId());
9872 var planet = Planet.planetById(selectedPlanetId());
9873 var miss = Planet.missChance(planet);
8184 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
9874 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
8185 if (me && me.planet && me.planet.id)
9875 if (me && me.planet)
8186 { planet = Planet.planetById(me.planet.id); }
9876 {
8187 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
9877 if (typeof Planet.rememberPlanet === 'function')
9878 { planet = Planet.rememberPlanet(me.planet) || planet; }
9879 else if (me.planet.id)
9880 { planet = Planet.planetById(me.planet.id); }
9881 if (typeof me.planet.miss_chance === 'number')
9882 { miss = me.planet.miss_chance; }
9883 }
9884 startPlay({ online: true, planet: planet, missChance: miss });
8188 if (typeof Online !== 'undefined')
9885 if (typeof Online !== 'undefined')
8189 { Online.startPolling(onlinePayload); }
9886 { Online.startPolling(onlinePayload); }
8190}
9887}
@@ -8562,19 +10259,22 @@ function renderPlanetGrid (containerId, compact)
8562 var pl = all[i];
10259 var pl = all[i];
8563 var btn = document.createElement('button');
10260 var btn = document.createElement('button');
8564 btn.type = 'button';
10261 btn.type = 'button';
8565 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
10262 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
10263 + (pl.custom ? ' custom' : '');
8566 btn.setAttribute('role', 'listitem');
10264 btn.setAttribute('role', 'listitem');
8567 btn.dataset.planet = pl.id;
10265 btn.dataset.planet = pl.id;
8568 var swatches = '';
10266 var swatches = '';
8569 for (var c = 0; c < pl.colors.length; c++)
10267 var colors = pl.colors || [];
10268 for (var c = 0; c < colors.length; c++)
8570 {
10269 {
8571 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
10270 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
8572 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
10271 + escapeText(colors[c].name) + '" title="' + escapeText(colors[c].name) + '">';
8573 }
10272 }
8574 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
10273 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
8575 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
10274 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
8576 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
10275 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
8577 + '<div class="planet-swatches">' + swatches + '</div>';
10276 + '<div class="planet-swatches">' + swatches + '</div>'
10277 + (pl.custom ? '<span class="custom-badge">Eigen</span>' : '');
8578 btn.addEventListener('click', (function (id, isCompact)
10278 btn.addEventListener('click', (function (id, isCompact)
8579 {
10279 {
8580 return function ()
10280 return function ()
@@ -8636,6 +10336,67 @@ function bindPlanetSelect ()
8636 }
10336 }
8637}
10337}
8638
10338
10339
10340function refreshMenuAccount ()
10341{
10342 var guest = document.getElementById('menu-guest');
10343 var user = document.getElementById('menu-user');
10344 var designerBtn = document.getElementById('btn-designer');
10345 var localLogin = document.getElementById('menu-local-login');
10346 var me = (typeof Online !== 'undefined') ? Online.me : null;
10347 if (me)
10348 {
10349 if (guest)
10350 { guest.hidden = true; }
10351 if (user)
10352 { user.hidden = false; }
10353 var name = document.getElementById('menu-name');
10354 if (name)
10355 { name.textContent = me.name || me.id || 'speler'; }
10356 var pts = document.getElementById('menu-points');
10357 if (pts)
10358 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
10359 if (designerBtn)
10360 { designerBtn.hidden = false; }
10361 }
10362 else
10363 {
10364 if (guest)
10365 { guest.hidden = false; }
10366 if (user)
10367 { user.hidden = true; }
10368 if (designerBtn)
10369 { designerBtn.hidden = true; }
10370 }
10371 if (localLogin)
10372 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
10373}
10374
10375function beginPlaySession (mode)
10376{
10377 if (app.playToken)
10378 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
10379 app.playToken = null;
10380 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
10381 { return; }
10382 Online.playBegin(mode || 'solo').then(function (data)
10383 {
10384 if (data && data.ok && data.token)
10385 { app.playToken = data.token; }
10386 });
10387}
10388
10389function finishPlaySession (score)
10390{
10391 var token = app.playToken;
10392 app.playToken = null;
10393 if (!token || typeof Online === 'undefined' || !Online.playFinish)
10394 { return; }
10395 Online.playFinish(token, score || 0).then(function ()
10396 { refreshMenuAccount(); });
10397}
10398
10399
8639/*
10400/*
8640 * End File:
10401 * End File:
8641 * /workspace/meteors/src/main.js
10402 * /workspace/meteors/src/main.js
build/images/block-arrow-chevron.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-arrow-double.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-arrow-return.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-arrow-up.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-face-cool.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-face-grin.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-face-smile.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-face-wink.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-fig-hero.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-fig-person.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-fig-walker.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-ankh.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-bell.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-bird.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-bolt.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-cactus.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-clover.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-comet.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-crown.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-eye.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-fish.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-flag.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-flame.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-heart.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-key.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-moon.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-mountain.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-mushroom.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-paw.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-ring.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-shield.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-snow.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-spiral.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-star6.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-sword.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-wave.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-icon-yin.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-rune-algiz.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-rune-ansuz.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-rune-fehu.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-rune-raido.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-rune-sowilo.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-rune-thurisaz.png added Binary file +0 −0

The contents of this binary file are not shown.

build/index.html +73 −0
@@ -21,8 +21,24 @@
21 21 <button type="button" id="btn-play">Spelen</button>
22 22 <button type="button" id="btn-offline" class="btn-secondary">Offline Strijd</button>
23 23 <button type="button" id="btn-online" class="btn-secondary">Online spelen</button>
24 <button type="button" id="btn-designer" class="btn-secondary" hidden>Planeetontwerper</button>
24 25 <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
25 26 <p class="hint">Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.</p>
27 <div id="menu-account" class="menu-account">
28 <p id="menu-guest">
29 <a id="menu-login" href="auth.php">Inloggen</a>
30 <span id="menu-local-login" hidden>
31 · lokale test:
32 <a href="auth.php?test=1">test_user_1</a> ·
33 <a href="auth.php?test=2">test_user_2</a>
34 </span>
35 </p>
36 <p id="menu-user" hidden>
37 Ingelogd als <strong id="menu-name"></strong>
38 · Totaal: <strong id="menu-points">0</strong> punten
39 · <a id="menu-logout" href="logout.php">Uitloggen</a>
40 </p>
41 </div>
26 42 </div>
27 43
28 44 <div id="planet-select" class="screen" hidden>
@@ -85,6 +101,63 @@
85 101 </div>
86 102 </div>
87 103
104 <div id="designer" class="screen" hidden>
105 <h1>Planeetontwerper</h1>
106 <p class="tagline">Totaal: <strong id="designer-points">0</strong> punten. Blokjes ontgrendel je door punten te verdienen — je geeft ze niet uit.</p>
107 <div id="designer-list" class="planet-grid" role="list"></div>
108 <div class="planet-actions">
109 <button type="button" id="btn-designer-new">Nieuwe planeet</button>
110 <button type="button" id="btn-designer-back" class="btn-secondary">Terug</button>
111 </div>
112 </div>
113
114 <div id="designer-edit" class="screen" hidden>
115 <h1 id="designer-edit-title">Nieuwe planeet</h1>
116 <form id="designer-form" class="designer-form" action="javascript:void(0)">
117 <label class="des-field">
118 <span>Naam van de planeet</span>
119 <input id="des-name" type="text" maxlength="32" autocomplete="off" required>
120 </label>
121 <label class="des-field">
122 <span>Naam van de bevolking</span>
123 <input id="des-people" type="text" maxlength="32" autocomplete="off" required>
124 </label>
125 <label class="des-field des-slider">
126 <span>Zwaartekracht</span>
127 <input id="des-gravity" type="range" min="1" max="4" step="0.1" value="2">
128 <span id="des-gravity-val" class="des-val"></span>
129 </label>
130 <label class="des-field des-slider">
131 <span>Luchtweerstand</span>
132 <input id="des-air" type="range" min="1" max="5" step="0.1" value="3">
133 <span id="des-air-val" class="des-val"></span>
134 </label>
135 <label class="des-field des-slider">
136 <span>Massa</span>
137 <input id="des-mass" type="range" min="0.5" max="3" step="0.1" value="1.5">
138 <span id="des-mass-val" class="des-val"></span>
139 </label>
140 <div id="des-power" class="des-power">Power 0%</div>
141 <p class="hint">Kies vijf blokjes. Klik op een vak om te wisselen.</p>
142 <div id="des-slots" class="des-slots"></div>
143 <div class="planet-actions">
144 <button type="submit" id="btn-designer-save">Opslaan</button>
145 <button type="button" id="btn-designer-delete" class="btn-secondary" hidden>Verwijderen</button>
146 <button type="button" id="btn-designer-cancel" class="btn-secondary">Terug</button>
147 </div>
148 </form>
149 </div>
150
151 <div id="des-modal" class="des-modal" hidden aria-hidden="true" role="dialog" aria-labelledby="des-modal-title">
152 <div class="des-modal-card">
153 <div class="des-modal-head">
154 <h2 id="des-modal-title">Kies een blokje</h2>
155 <button type="button" id="des-modal-close" class="btn-tiny">Sluiten</button>
156 </div>
157 <div id="des-modal-grid" class="des-block-grid"></div>
158 </div>
159 </div>
160
88 161 <div id="minis" hidden></div>
89 162
90 163 <div id="hud" hidden>
@@ -21,8 +21,24 @@
21 <button type="button" id="btn-play">Spelen</button>
21 <button type="button" id="btn-play">Spelen</button>
22 <button type="button" id="btn-offline" class="btn-secondary">Offline Strijd</button>
22 <button type="button" id="btn-offline" class="btn-secondary">Offline Strijd</button>
23 <button type="button" id="btn-online" class="btn-secondary">Online spelen</button>
23 <button type="button" id="btn-online" class="btn-secondary">Online spelen</button>
24 <button type="button" id="btn-designer" class="btn-secondary" hidden>Planeetontwerper</button>
24 <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
25 <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
25 <p class="hint">Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.</p>
26 <p class="hint">Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.</p>
27 <div id="menu-account" class="menu-account">
28 <p id="menu-guest">
29 <a id="menu-login" href="auth.php">Inloggen</a>
30 <span id="menu-local-login" hidden>
31 · lokale test:
32 <a href="auth.php?test=1">test_user_1</a> ·
33 <a href="auth.php?test=2">test_user_2</a>
34 </span>
35 </p>
36 <p id="menu-user" hidden>
37 Ingelogd als <strong id="menu-name"></strong>
38 · Totaal: <strong id="menu-points">0</strong> punten
39 · <a id="menu-logout" href="logout.php">Uitloggen</a>
40 </p>
41 </div>
26 </div>
42 </div>
27
43
28 <div id="planet-select" class="screen" hidden>
44 <div id="planet-select" class="screen" hidden>
@@ -85,6 +101,63 @@
85 </div>
101 </div>
86 </div>
102 </div>
87
103
104 <div id="designer" class="screen" hidden>
105 <h1>Planeetontwerper</h1>
106 <p class="tagline">Totaal: <strong id="designer-points">0</strong> punten. Blokjes ontgrendel je door punten te verdienen — je geeft ze niet uit.</p>
107 <div id="designer-list" class="planet-grid" role="list"></div>
108 <div class="planet-actions">
109 <button type="button" id="btn-designer-new">Nieuwe planeet</button>
110 <button type="button" id="btn-designer-back" class="btn-secondary">Terug</button>
111 </div>
112 </div>
113
114 <div id="designer-edit" class="screen" hidden>
115 <h1 id="designer-edit-title">Nieuwe planeet</h1>
116 <form id="designer-form" class="designer-form" action="javascript:void(0)">
117 <label class="des-field">
118 <span>Naam van de planeet</span>
119 <input id="des-name" type="text" maxlength="32" autocomplete="off" required>
120 </label>
121 <label class="des-field">
122 <span>Naam van de bevolking</span>
123 <input id="des-people" type="text" maxlength="32" autocomplete="off" required>
124 </label>
125 <label class="des-field des-slider">
126 <span>Zwaartekracht</span>
127 <input id="des-gravity" type="range" min="1" max="4" step="0.1" value="2">
128 <span id="des-gravity-val" class="des-val"></span>
129 </label>
130 <label class="des-field des-slider">
131 <span>Luchtweerstand</span>
132 <input id="des-air" type="range" min="1" max="5" step="0.1" value="3">
133 <span id="des-air-val" class="des-val"></span>
134 </label>
135 <label class="des-field des-slider">
136 <span>Massa</span>
137 <input id="des-mass" type="range" min="0.5" max="3" step="0.1" value="1.5">
138 <span id="des-mass-val" class="des-val"></span>
139 </label>
140 <div id="des-power" class="des-power">Power 0%</div>
141 <p class="hint">Kies vijf blokjes. Klik op een vak om te wisselen.</p>
142 <div id="des-slots" class="des-slots"></div>
143 <div class="planet-actions">
144 <button type="submit" id="btn-designer-save">Opslaan</button>
145 <button type="button" id="btn-designer-delete" class="btn-secondary" hidden>Verwijderen</button>
146 <button type="button" id="btn-designer-cancel" class="btn-secondary">Terug</button>
147 </div>
148 </form>
149 </div>
150
151 <div id="des-modal" class="des-modal" hidden aria-hidden="true" role="dialog" aria-labelledby="des-modal-title">
152 <div class="des-modal-card">
153 <div class="des-modal-head">
154 <h2 id="des-modal-title">Kies een blokje</h2>
155 <button type="button" id="des-modal-close" class="btn-tiny">Sluiten</button>
156 </div>
157 <div id="des-modal-grid" class="des-block-grid"></div>
158 </div>
159 </div>
160
88 <div id="minis" hidden></div>
161 <div id="minis" hidden></div>
89
162
90 <div id="hud" hidden>
163 <div id="hud" hidden>
build/style.css +238 −3
@@ -46,7 +46,7 @@ html, body {
46 46 text-align: center;
47 47 }
48 48
49 .screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden] { display: none !important; }
49 .screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden], #designer[hidden], #designer-edit[hidden] { display: none !important; }
50 50
51 51 h1 {
52 52 font-size: clamp(48px, 14vw, 96px);
@@ -208,11 +208,12 @@ a.button:is(:hover, :focus-visible) {
208 208 color: #fff6c8;
209 209 }
210 210 #btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
211 #btn-play, #btn-planet-go {
211 #btn-play, #btn-planet-go, #btn-designer-new, #btn-designer-save {
212 212 /* play already styled */
213 213 }
214 214
215 #btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate {
215 #btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
216 #btn-designer-new, #btn-designer-save {
216 217 padding: 10px 28px;
217 218 font-size: clamp(16px, 4vw, 20px);
218 219 border: 0;
@@ -627,3 +628,237 @@ a.button:is(:hover, :focus-visible) {
627 628 @media (max-width: 520px) {
628 629 .hud-offline { font-size: 11px; bottom: 4px; }
629 630 }
631
632 /* —— t1139 Planet Designer + account chrome —— */
633 .menu-account {
634 margin-top: 1.2rem;
635 font-size: 0.9rem;
636 color: #c8c4d4;
637 }
638 .menu-account a { color: #ffe27a; }
639 .menu-account a:hover { color: #fff; }
640 #btn-designer {
641 display: block;
642 margin: 0.7rem auto 0;
643 }
644 #btn-designer[hidden] { display: none; }
645 #menu-user[hidden], #menu-guest[hidden], #menu-local-login[hidden],
646 #btn-designer-delete[hidden] { display: none; }
647 .designer-card { cursor: default; text-align: left; }
648 .designer-card-actions {
649 display: flex;
650 gap: 6px;
651 margin-top: 8px;
652 justify-content: center;
653 }
654 .btn-tiny {
655 font: inherit;
656 font-size: 0.85rem;
657 padding: 6px 10px;
658 border-radius: 8px;
659 border: 1px solid #5a5470;
660 background: #2a2540;
661 color: #eee;
662 cursor: pointer;
663 min-height: 36px;
664 }
665 .btn-tiny:hover, .btn-tiny:focus-visible { background: #3a3555; border-color: #ffe27a; }
666 .btn-danger-lite { color: #ffb4b4; }
667 .designer-form {
668 max-width: 28rem;
669 margin: 0 auto;
670 display: flex;
671 flex-direction: column;
672 gap: 0.7rem;
673 text-align: left;
674 }
675 .des-field { display: flex; flex-direction: column; gap: 4px; }
676 .des-field > span:first-child { font-weight: 600; color: #ddd; }
677 .des-field input[type="text"] {
678 font: inherit;
679 padding: 8px 10px;
680 border-radius: 8px;
681 border: 1px solid #5a5470;
682 background: #1a1628;
683 color: #fff;
684 min-height: 40px;
685 }
686 .des-slider input[type="range"] { width: 100%; min-height: 32px; }
687 .des-val, .des-power {
688 font-variant-numeric: tabular-nums;
689 color: #ffe27a;
690 font-weight: 700;
691 }
692 .des-power {
693 font-size: 1.25rem;
694 text-align: center;
695 margin: 0.2rem 0;
696 }
697 .des-slots {
698 display: grid;
699 grid-template-columns: repeat(5, 1fr);
700 gap: 8px;
701 }
702 .des-slot {
703 font: inherit;
704 background: #1a1628;
705 border: 1px solid #5a5470;
706 border-radius: 10px;
707 padding: 8px 4px;
708 cursor: pointer;
709 color: #eee;
710 display: flex;
711 flex-direction: column;
712 align-items: center;
713 gap: 4px;
714 min-height: 88px;
715 }
716 .des-slot img { width: 48px; height: 48px; image-rendering: pixelated; }
717 .des-slot span { font-size: 0.7rem; text-align: center; line-height: 1.15; }
718 .des-slot:hover, .des-slot:focus-visible { border-color: #ffe27a; background: #2a2540; }
719 .des-modal {
720 position: fixed;
721 inset: 0;
722 background: rgba(8, 6, 16, 0.78);
723 z-index: 40;
724 display: flex;
725 align-items: flex-start;
726 justify-content: center;
727 padding: 12px;
728 overflow: auto;
729 }
730 .des-modal[hidden] { display: none !important; }
731 .des-modal-card {
732 background: #161226;
733 border: 1px solid #5a5470;
734 border-radius: 14px;
735 padding: 14px 14px 18px;
736 max-width: 56rem;
737 width: 100%;
738 margin: 1.5rem auto 3rem;
739 box-shadow: 0 12px 40px rgba(0,0,0,0.5);
740 }
741 .des-modal-head {
742 display: flex;
743 align-items: center;
744 justify-content: space-between;
745 gap: 12px;
746 margin-bottom: 12px;
747 }
748 .des-modal-head h2 { margin: 0; font-size: 1.2rem; }
749 .des-block-grid {
750 display: grid;
751 grid-template-columns: repeat(auto-fill, minmax(76px, 1fr));
752 gap: 8px;
753 }
754 .des-block {
755 position: relative;
756 font: inherit;
757 background: #1a1628;
758 border: 1px solid #5a5470;
759 border-radius: 10px;
760 padding: 6px 4px 8px;
761 cursor: pointer;
762 color: #eee;
763 display: flex;
764 flex-direction: column;
765 align-items: center;
766 gap: 3px;
767 min-height: 92px;
768 }
769 .des-block img { width: 48px; height: 48px; image-rendering: pixelated; }
770 .des-block-name {
771 font-size: 0.65rem;
772 text-align: center;
773 line-height: 1.15;
774 overflow: hidden;
775 text-overflow: ellipsis;
776 max-width: 100%;
777 }
778 .des-block:hover:not(:disabled), .des-block:focus-visible:not(:disabled) {
779 border-color: #ffe27a;
780 background: #2a2540;
781 }
782 .des-block.current { outline: 2px solid #ffe27a; }
783 .des-block.used img, .des-block.locked img,
784 .des-block.used .des-block-name, .des-block.locked .des-block-name {
785 opacity: 0.42;
786 filter: grayscale(1);
787 }
788 .des-block.used, .des-block.locked {
789 cursor: not-allowed;
790 }
791 .des-block-need {
792 font-size: 0.6rem;
793 color: #ffe27a;
794 opacity: 0.9;
795 }
796 .des-lock {
797 position: absolute;
798 top: 2px;
799 right: 2px;
800 width: 22px;
801 height: 22px;
802 display: flex;
803 align-items: center;
804 justify-content: center;
805 background: rgba(16, 12, 28, 0.92);
806 border-radius: 5px;
807 pointer-events: none;
808 z-index: 2;
809 box-shadow: 0 0 0 1px rgba(255, 226, 122, 0.35);
810 }
811 .des-lock svg { display: block; }
812 .planet-card.custom { position: relative; }
813 .planet-card .custom-badge {
814 position: absolute;
815 top: 6px;
816 right: 6px;
817 font-size: 0.65rem;
818 background: #3a2a10;
819 color: #ffe27a;
820 border: 1px solid #ffe27a;
821 border-radius: 999px;
822 padding: 1px 6px;
823 letter-spacing: 0.02em;
824 }
825 @media (max-width: 520px) {
826 .des-slots { grid-template-columns: repeat(5, 1fr); gap: 4px; }
827 .des-slot { min-height: 76px; padding: 4px 2px; }
828 .des-slot img, .des-block img { width: 36px; height: 36px; }
829 .des-block { min-height: 80px; }
830 .des-block-grid { grid-template-columns: repeat(auto-fill, minmax(64px, 1fr)); gap: 6px; }
831 .des-field input[type="text"], .btn-tiny { min-height: 44px; }
832 }
833
834 #designer, #designer-edit {
835 justify-content: flex-start;
836 overflow-y: auto;
837 touch-action: pan-y;
838 -webkit-overflow-scrolling: touch;
839 padding-top: 16px;
840 padding-bottom: 40px;
841 }
842 #designer h1, #designer-edit h1 {
843 font-size: clamp(28px, 8vw, 56px);
844 margin-bottom: 6px;
845 }
846 #designer .tagline, #designer-edit .tagline { margin-bottom: 12px; }
847 #designer-list {
848 width: min(1000px, 100%);
849 margin-bottom: 16px;
850 }
851 @media (max-width: 520px) {
852 #designer-edit .designer-form { gap: 0.45rem; }
853 .des-slots { margin-bottom: 8px; }
854 #designer-edit .planet-actions, #designer .planet-actions {
855 position: sticky;
856 bottom: 0;
857 padding-bottom: 8px;
858 background: linear-gradient(180deg, transparent, #0b1020 30%);
859 }
860 }
861
862 #designer-edit .hint, #designer .hint { margin: 8px auto 4px; }
863 #designer-edit .designer-form { max-width: 26rem; }
864 #designer-edit .planet-actions { margin-top: 12px; padding-bottom: 16px; }
@@ -46,7 +46,7 @@ html, body {
46 text-align: center;
46 text-align: center;
47}
47}
48
48
49.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden] { display: none !important; }
49.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden], #designer[hidden], #designer-edit[hidden] { display: none !important; }
50
50
51h1 {
51h1 {
52 font-size: clamp(48px, 14vw, 96px);
52 font-size: clamp(48px, 14vw, 96px);
@@ -208,11 +208,12 @@ a.button:is(:hover, :focus-visible) {
208 color: #fff6c8;
208 color: #fff6c8;
209}
209}
210#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
210#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
211#btn-play, #btn-planet-go {
211#btn-play, #btn-planet-go, #btn-designer-new, #btn-designer-save {
212 /* play already styled */
212 /* play already styled */
213}
213}
214
214
215#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate {
215#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
216#btn-designer-new, #btn-designer-save {
216 padding: 10px 28px;
217 padding: 10px 28px;
217 font-size: clamp(16px, 4vw, 20px);
218 font-size: clamp(16px, 4vw, 20px);
218 border: 0;
219 border: 0;
@@ -627,3 +628,237 @@ a.button:is(:hover, :focus-visible) {
627@media (max-width: 520px) {
628@media (max-width: 520px) {
628 .hud-offline { font-size: 11px; bottom: 4px; }
629 .hud-offline { font-size: 11px; bottom: 4px; }
629}
630}
631
632/* —— t1139 Planet Designer + account chrome —— */
633.menu-account {
634 margin-top: 1.2rem;
635 font-size: 0.9rem;
636 color: #c8c4d4;
637}
638.menu-account a { color: #ffe27a; }
639.menu-account a:hover { color: #fff; }
640#btn-designer {
641 display: block;
642 margin: 0.7rem auto 0;
643}
644#btn-designer[hidden] { display: none; }
645#menu-user[hidden], #menu-guest[hidden], #menu-local-login[hidden],
646#btn-designer-delete[hidden] { display: none; }
647.designer-card { cursor: default; text-align: left; }
648.designer-card-actions {
649 display: flex;
650 gap: 6px;
651 margin-top: 8px;
652 justify-content: center;
653}
654.btn-tiny {
655 font: inherit;
656 font-size: 0.85rem;
657 padding: 6px 10px;
658 border-radius: 8px;
659 border: 1px solid #5a5470;
660 background: #2a2540;
661 color: #eee;
662 cursor: pointer;
663 min-height: 36px;
664}
665.btn-tiny:hover, .btn-tiny:focus-visible { background: #3a3555; border-color: #ffe27a; }
666.btn-danger-lite { color: #ffb4b4; }
667.designer-form {
668 max-width: 28rem;
669 margin: 0 auto;
670 display: flex;
671 flex-direction: column;
672 gap: 0.7rem;
673 text-align: left;
674}
675.des-field { display: flex; flex-direction: column; gap: 4px; }
676.des-field > span:first-child { font-weight: 600; color: #ddd; }
677.des-field input[type="text"] {
678 font: inherit;
679 padding: 8px 10px;
680 border-radius: 8px;
681 border: 1px solid #5a5470;
682 background: #1a1628;
683 color: #fff;
684 min-height: 40px;
685}
686.des-slider input[type="range"] { width: 100%; min-height: 32px; }
687.des-val, .des-power {
688 font-variant-numeric: tabular-nums;
689 color: #ffe27a;
690 font-weight: 700;
691}
692.des-power {
693 font-size: 1.25rem;
694 text-align: center;
695 margin: 0.2rem 0;
696}
697.des-slots {
698 display: grid;
699 grid-template-columns: repeat(5, 1fr);
700 gap: 8px;
701}
702.des-slot {
703 font: inherit;
704 background: #1a1628;
705 border: 1px solid #5a5470;
706 border-radius: 10px;
707 padding: 8px 4px;
708 cursor: pointer;
709 color: #eee;
710 display: flex;
711 flex-direction: column;
712 align-items: center;
713 gap: 4px;
714 min-height: 88px;
715}
716.des-slot img { width: 48px; height: 48px; image-rendering: pixelated; }
717.des-slot span { font-size: 0.7rem; text-align: center; line-height: 1.15; }
718.des-slot:hover, .des-slot:focus-visible { border-color: #ffe27a; background: #2a2540; }
719.des-modal {
720 position: fixed;
721 inset: 0;
722 background: rgba(8, 6, 16, 0.78);
723 z-index: 40;
724 display: flex;
725 align-items: flex-start;
726 justify-content: center;
727 padding: 12px;
728 overflow: auto;
729}
730.des-modal[hidden] { display: none !important; }
731.des-modal-card {
732 background: #161226;
733 border: 1px solid #5a5470;
734 border-radius: 14px;
735 padding: 14px 14px 18px;
736 max-width: 56rem;
737 width: 100%;
738 margin: 1.5rem auto 3rem;
739 box-shadow: 0 12px 40px rgba(0,0,0,0.5);
740}
741.des-modal-head {
742 display: flex;
743 align-items: center;
744 justify-content: space-between;
745 gap: 12px;
746 margin-bottom: 12px;
747}
748.des-modal-head h2 { margin: 0; font-size: 1.2rem; }
749.des-block-grid {
750 display: grid;
751 grid-template-columns: repeat(auto-fill, minmax(76px, 1fr));
752 gap: 8px;
753}
754.des-block {
755 position: relative;
756 font: inherit;
757 background: #1a1628;
758 border: 1px solid #5a5470;
759 border-radius: 10px;
760 padding: 6px 4px 8px;
761 cursor: pointer;
762 color: #eee;
763 display: flex;
764 flex-direction: column;
765 align-items: center;
766 gap: 3px;
767 min-height: 92px;
768}
769.des-block img { width: 48px; height: 48px; image-rendering: pixelated; }
770.des-block-name {
771 font-size: 0.65rem;
772 text-align: center;
773 line-height: 1.15;
774 overflow: hidden;
775 text-overflow: ellipsis;
776 max-width: 100%;
777}
778.des-block:hover:not(:disabled), .des-block:focus-visible:not(:disabled) {
779 border-color: #ffe27a;
780 background: #2a2540;
781}
782.des-block.current { outline: 2px solid #ffe27a; }
783.des-block.used img, .des-block.locked img,
784.des-block.used .des-block-name, .des-block.locked .des-block-name {
785 opacity: 0.42;
786 filter: grayscale(1);
787}
788.des-block.used, .des-block.locked {
789 cursor: not-allowed;
790}
791.des-block-need {
792 font-size: 0.6rem;
793 color: #ffe27a;
794 opacity: 0.9;
795}
796.des-lock {
797 position: absolute;
798 top: 2px;
799 right: 2px;
800 width: 22px;
801 height: 22px;
802 display: flex;
803 align-items: center;
804 justify-content: center;
805 background: rgba(16, 12, 28, 0.92);
806 border-radius: 5px;
807 pointer-events: none;
808 z-index: 2;
809 box-shadow: 0 0 0 1px rgba(255, 226, 122, 0.35);
810}
811.des-lock svg { display: block; }
812.planet-card.custom { position: relative; }
813.planet-card .custom-badge {
814 position: absolute;
815 top: 6px;
816 right: 6px;
817 font-size: 0.65rem;
818 background: #3a2a10;
819 color: #ffe27a;
820 border: 1px solid #ffe27a;
821 border-radius: 999px;
822 padding: 1px 6px;
823 letter-spacing: 0.02em;
824}
825@media (max-width: 520px) {
826 .des-slots { grid-template-columns: repeat(5, 1fr); gap: 4px; }
827 .des-slot { min-height: 76px; padding: 4px 2px; }
828 .des-slot img, .des-block img { width: 36px; height: 36px; }
829 .des-block { min-height: 80px; }
830 .des-block-grid { grid-template-columns: repeat(auto-fill, minmax(64px, 1fr)); gap: 6px; }
831 .des-field input[type="text"], .btn-tiny { min-height: 44px; }
832}
833
834#designer, #designer-edit {
835 justify-content: flex-start;
836 overflow-y: auto;
837 touch-action: pan-y;
838 -webkit-overflow-scrolling: touch;
839 padding-top: 16px;
840 padding-bottom: 40px;
841}
842#designer h1, #designer-edit h1 {
843 font-size: clamp(28px, 8vw, 56px);
844 margin-bottom: 6px;
845}
846#designer .tagline, #designer-edit .tagline { margin-bottom: 12px; }
847#designer-list {
848 width: min(1000px, 100%);
849 margin-bottom: 16px;
850}
851@media (max-width: 520px) {
852 #designer-edit .designer-form { gap: 0.45rem; }
853 .des-slots { margin-bottom: 8px; }
854 #designer-edit .planet-actions, #designer .planet-actions {
855 position: sticky;
856 bottom: 0;
857 padding-bottom: 8px;
858 background: linear-gradient(180deg, transparent, #0b1020 30%);
859 }
860}
861
862#designer-edit .hint, #designer .hint { margin: 8px auto 4px; }
863#designer-edit .designer-form { max-width: 26rem; }
864#designer-edit .planet-actions { margin-top: 12px; padding-bottom: 16px; }
docs/ASSUMPTIONS.md +52 −0
@@ -763,3 +763,55 @@ Aanname:
763 763 uiteinden, corridors, en de fallSpeed-overdracht. Playwright
764 764 legt early/mid/late vast op 1024×532 en 1920×1080, plus een
765 765 webm van beide formaten.
766
767
768 ## t1139 — Planeetontwerper
769
770 - De ontwerper is alleen beschikbaar op het hoofdmenu, en alleen als
771 je bent ingelogd. Tot de live OAuth-callback en het CI-geheim
772 `auth_client_secret` zijn ingericht, is dat op productie onzichtbaar.
773 Lokaal kun je inloggen met `auth.php?test=1` (of `test=2`).
774 - Levenslange punten staan in het server-profiel (`profiles`). Alleen
775 ingelogde spellen tellen mee. Bots leveren geen punten op.
776 - **Spelen** (solo): de score aan het einde van het spel.
777 - **Offline Strijd**: de score van **elke ronde**, gewonnen of
778 verloren, omdat de score per ronde opnieuw begint.
779 - **Online**: de server kent de score via de poll; punten worden
780 toegekend bij uitschakeling of als de lobby klaar is, één keer per
781 `online:{lobbyId}:{userId}`. De client kan hier geen punten
782 insturen.
783 - Anti-cheat voor solo/offline: `play_begin` geeft een eenmalig token
784 (geldig 6 uur). `play_finish` klempt de score op 0–10000, weigert
785 een positieve score als het spel korter dan 3 seconden duurde, en
786 laat maximaal 4 punten per seconde door. Herhaalde finishes van
787 hetzelfde token zijn een no-op. Overduidelijk valsspelen wordt
788 geklemd, niet keihard verboden, zodat een trage verbinding geen
789 eerlijke score weggooit.
790 - Het blokjesregister (`server/lib/blocks.json`) is append-only: de
791 volgorde ligt nu vast. Eerst Terra's vijf (gratis), daarna 43 nieuwe
792 icoontjes (eerste, Fehu, op 500 punten; daarna telkens 14,5 % meer,
793 afgerond en strikt stijgend — de laatste icoon zit rond de 147 000
794 punten), daarna de 55 kleuren van de officiële niet-Terra-planeten
795 als lange staart (de laatste zit in de honderden miljoenen). Punten
796 zijn een **eis**, geen uitgave. Officiële planeten blijven hun eigen
797 blokjes gebruiken zonder ontgrendeling; ontgrendelen is alleen voor
798 de ontwerper.
799 - Een speler mag tot 30 eigen planeten hebben. Id's zijn `c_` plus
800 16 hex-tekens. Namen (planeet en volk) zijn 1–32 tekens, zonder
801 tags. De vijf blokjes moeten verschillend en ontgrendeld zijn.
802 - Nieuwe blokjes-plaatjes staan in `build/images/block-*.png`, 64×64,
803 in dezelfde stijl als Terra (gekleurde silhouet, donkere omtrek,
804 highlight, slagschaduw). Gegenereerd door
805 `scripts/gen_unlock_blocks.py`.
806
807 ## t1140 — Eigen planeten in elke modus
808
809 - In Spelen, Offline Strijd en Online Spelen toont de planeetkiezer
810 naast de officiële catalogus ook **je eigen** ontworpen planeten
811 (badge "Eigen"). Planeten van anderen staan daar niet in.
812 - Voor Online stuurt de client alleen het planeet-id. De server
813 controleert eigendom, legt een **snapshot** (`planet_json`) vast bij
814 kiezen/aanmaken/joinen, en stuurt de volledige configuratie
815 (variabelen, kleuren, `miss_chance`) mee in de lobby. Tegenstanders
816 onthouden die snapshot om fysica, miss-kans en sprites te simuleren;
817 een latere wijziging of verwijdering verandert een lopend spel niet.
@@ -763,3 +763,55 @@ Aanname:
763 uiteinden, corridors, en de fallSpeed-overdracht. Playwright
763 uiteinden, corridors, en de fallSpeed-overdracht. Playwright
764 legt early/mid/late vast op 1024×532 en 1920×1080, plus een
764 legt early/mid/late vast op 1024×532 en 1920×1080, plus een
765 webm van beide formaten.
765 webm van beide formaten.
766
767
768## t1139 — Planeetontwerper
769
770- De ontwerper is alleen beschikbaar op het hoofdmenu, en alleen als
771 je bent ingelogd. Tot de live OAuth-callback en het CI-geheim
772 `auth_client_secret` zijn ingericht, is dat op productie onzichtbaar.
773 Lokaal kun je inloggen met `auth.php?test=1` (of `test=2`).
774- Levenslange punten staan in het server-profiel (`profiles`). Alleen
775 ingelogde spellen tellen mee. Bots leveren geen punten op.
776 - **Spelen** (solo): de score aan het einde van het spel.
777 - **Offline Strijd**: de score van **elke ronde**, gewonnen of
778 verloren, omdat de score per ronde opnieuw begint.
779 - **Online**: de server kent de score via de poll; punten worden
780 toegekend bij uitschakeling of als de lobby klaar is, één keer per
781 `online:{lobbyId}:{userId}`. De client kan hier geen punten
782 insturen.
783- Anti-cheat voor solo/offline: `play_begin` geeft een eenmalig token
784 (geldig 6 uur). `play_finish` klempt de score op 0–10000, weigert
785 een positieve score als het spel korter dan 3 seconden duurde, en
786 laat maximaal 4 punten per seconde door. Herhaalde finishes van
787 hetzelfde token zijn een no-op. Overduidelijk valsspelen wordt
788 geklemd, niet keihard verboden, zodat een trage verbinding geen
789 eerlijke score weggooit.
790- Het blokjesregister (`server/lib/blocks.json`) is append-only: de
791 volgorde ligt nu vast. Eerst Terra's vijf (gratis), daarna 43 nieuwe
792 icoontjes (eerste, Fehu, op 500 punten; daarna telkens 14,5 % meer,
793 afgerond en strikt stijgend — de laatste icoon zit rond de 147 000
794 punten), daarna de 55 kleuren van de officiële niet-Terra-planeten
795 als lange staart (de laatste zit in de honderden miljoenen). Punten
796 zijn een **eis**, geen uitgave. Officiële planeten blijven hun eigen
797 blokjes gebruiken zonder ontgrendeling; ontgrendelen is alleen voor
798 de ontwerper.
799- Een speler mag tot 30 eigen planeten hebben. Id's zijn `c_` plus
800 16 hex-tekens. Namen (planeet en volk) zijn 1–32 tekens, zonder
801 tags. De vijf blokjes moeten verschillend en ontgrendeld zijn.
802- Nieuwe blokjes-plaatjes staan in `build/images/block-*.png`, 64×64,
803 in dezelfde stijl als Terra (gekleurde silhouet, donkere omtrek,
804 highlight, slagschaduw). Gegenereerd door
805 `scripts/gen_unlock_blocks.py`.
806
807## t1140 — Eigen planeten in elke modus
808
809- In Spelen, Offline Strijd en Online Spelen toont de planeetkiezer
810 naast de officiële catalogus ook **je eigen** ontworpen planeten
811 (badge "Eigen"). Planeten van anderen staan daar niet in.
812- Voor Online stuurt de client alleen het planeet-id. De server
813 controleert eigendom, legt een **snapshot** (`planet_json`) vast bij
814 kiezen/aanmaken/joinen, en stuurt de volledige configuratie
815 (variabelen, kleuren, `miss_chance`) mee in de lobby. Tegenstanders
816 onthouden die snapshot om fysica, miss-kans en sprites te simuleren;
817 een latere wijziging of verwijdering verandert een lopend spel niet.
scripts/gen_unlock_blocks.py added +665 −0
@@ -0,0 +1,665 @@
1 #!/usr/bin/env python3
2 """Build server/lib/blocks.json (append-only registry) and new unlockable
3 block PNGs in the existing 64×64 style: coloured silhouette, dark outline,
4 soft highlight, drop shadow.
5
6 Official catalog colours are listed first (Terra's five, then the other
7 planets in catalog order) and their existing PNGs are left untouched.
8 New icons are appended and rendered here.
9
10 Run from the repo root: python3 scripts/gen_unlock_blocks.py
11 """
12 from __future__ import annotations
13
14 import json
15 import math
16 from pathlib import Path
17
18 from PIL import Image, ImageDraw, ImageFilter
19
20 ROOT = Path(__file__).resolve().parents[1]
21 CATALOG = ROOT / 'server' / 'lib' / 'planets.json'
22 OUT_JSON = ROOT / 'server' / 'lib' / 'blocks.json'
23 OUT_IMG = ROOT / 'build' / 'images'
24 SIZE = 64
25 SCALE = 4
26 SS = SIZE * SCALE
27
28
29 def hex_rgb(h):
30 h = h.lstrip('#')
31 return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
32
33
34 def lighten(rgb, f=0.35):
35 return tuple(min(255, int(c + (255 - c) * f)) for c in rgb)
36
37
38 def darken(rgb, f=0.28):
39 return tuple(max(0, int(c * (1 - f))) for c in rgb)
40
41
42 def regular_poly(cx, cy, r, n, rot=-math.pi / 2):
43 pts = []
44 for i in range(n):
45 a = rot + i * 2 * math.pi / n
46 pts.append((cx + r * math.cos(a), cy + r * math.sin(a)))
47 return pts
48
49
50 def star_pts(cx, cy, r, n=5, inner=0.42, rot=-math.pi / 2):
51 pts = []
52 for i in range(n * 2):
53 a = rot + i * math.pi / n
54 rr = r if i % 2 == 0 else r * inner
55 pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
56 return pts
57
58
59 # ---------- shape primitives (filled polygons / lines) ----------
60
61 def poly_stroke(draw, pts, fill, outline, width):
62 draw.polygon(pts, fill=fill, outline=outline, width=width)
63
64
65 def thick_lines(draw, segs, color, width, closed=False):
66 """segs: list of point lists."""
67 for pts in segs:
68 if len(pts) < 2:
69 continue
70 draw.line(pts, fill=color, width=width, joint='curve')
71 # round caps
72 r = width / 2
73 for p in (pts[0], pts[-1]):
74 draw.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r], fill=color)
75 if closed and pts[0] != pts[-1]:
76 draw.line([pts[-1], pts[0]], fill=color, width=width)
77
78
79 def icon_path(cx, cy, r, kind):
80 """Return ('poly', pts) or ('polys', [pts, ...]) or ('lines', [pts,...], wfrac)
81 or ('combo', list of commands). Coordinates in actual pixels."""
82 def P(x, y):
83 return (cx + x * r, cy + y * r)
84
85 k = kind.lower()
86 if k == 'circle':
87 return ('ellipse', [-1, -1, 1, 1])
88 if k == 'square':
89 s = 0.86
90 return ('roundrect', [-s, -s, s, s], 0.12)
91 if k == 'triangle':
92 return ('poly', regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2))
93 if k == 'diamond':
94 return ('poly', regular_poly(cx, cy, r * 1.05, 4, 0))
95 if k == 'star':
96 return ('poly', star_pts(cx, cy, r * 1.12))
97 if k == 'hexagon':
98 return ('poly', regular_poly(cx, cy, r * 1.05, 6, 0))
99 if k == 'pentagon':
100 return ('poly', regular_poly(cx, cy, r * 1.08, 5))
101 if k == 'arrow':
102 return ('poly', [
103 P(0, -1.1), P(0.85, 0.05), P(0.28, 0.05), P(0.28, 1),
104 P(-0.28, 1), P(-0.28, 0.05), P(-0.85, 0.05),
105 ])
106 if k == 'chevron':
107 return ('poly', [
108 P(0, -1.05), P(0.95, 0.15), P(0.95, 0.55), P(0, -0.15),
109 P(-0.95, 0.55), P(-0.95, 0.15),
110 ])
111 if k == 'double_arrow':
112 return ('poly', [
113 P(0, -1.15), P(0.72, -0.25), P(0.28, -0.25), P(0.28, 0.05),
114 P(0.72, 0.05), P(0, 1.15), P(-0.72, 0.05), P(-0.28, 0.05),
115 P(-0.28, -0.25), P(-0.72, -0.25),
116 ])
117 if k == 'return_arrow':
118 return ('poly', [
119 P(-0.15, -1.1), P(0.7, -0.4), P(0.25, -0.4), P(0.25, 0.15),
120 P(0.85, 0.15), P(0.85, 0.55), P(-0.25, 0.55), P(-0.25, -0.4),
121 P(-0.7, -0.4),
122 ])
123 # Runes — stylized, thick, readable
124 if k == 'rune_fehu':
125 return ('lines', [
126 [P(-0.15, 1.0), P(-0.15, -1.0)],
127 [P(-0.15, -0.55), P(0.85, -0.95)],
128 [P(-0.15, -0.05), P(0.85, -0.45)],
129 ], 0.28)
130 if k == 'rune_ansuz':
131 return ('lines', [
132 [P(-0.2, 1.0), P(-0.2, -1.0)],
133 [P(-0.2, -0.85), P(0.85, -0.25)],
134 [P(-0.2, -0.15), P(0.7, 0.45)],
135 ], 0.28)
136 if k == 'rune_thurisaz':
137 return ('lines', [
138 [P(-0.35, 1.0), P(-0.35, -1.0)],
139 [P(-0.35, -0.55), P(0.7, 0), P(-0.35, 0.55)],
140 ], 0.28)
141 if k == 'rune_raido':
142 return ('lines', [
143 [P(-0.3, 1.0), P(-0.3, -1.0)],
144 [P(-0.3, -1.0), P(0.65, -0.55), P(-0.3, -0.1)],
145 [P(-0.05, -0.1), P(0.7, 1.0)],
146 ], 0.26)
147 if k == 'rune_sowilo':
148 return ('lines', [
149 [P(0.55, -1.05), P(-0.45, -0.25), P(0.45, 0.25), P(-0.55, 1.05)],
150 ], 0.30)
151 if k == 'rune_algiz':
152 return ('lines', [
153 [P(0, 1.05), P(0, -1.05)],
154 [P(0, -0.15), P(-0.75, -0.95)],
155 [P(0, -0.15), P(0.75, -0.95)],
156 ], 0.28)
157 # Figures
158 if k == 'person':
159 # head + body + arms + legs as one silhouette
160 head = []
161 for i in range(16):
162 a = i * 2 * math.pi / 16
163 head.append(P(0.0 + 0.28 * math.cos(a), -0.72 + 0.28 * math.sin(a)))
164 body = [
165 P(-0.22, -0.42), P(-0.72, -0.15), P(-0.72, 0.12), P(-0.22, -0.08),
166 P(-0.28, 0.35), P(-0.55, 1.05), P(-0.22, 1.05), P(0, 0.5),
167 P(0.22, 1.05), P(0.55, 1.05), P(0.28, 0.35), P(0.22, -0.08),
168 P(0.72, 0.12), P(0.72, -0.15), P(0.22, -0.42),
169 ]
170 return ('polys', [head, body])
171 if k == 'walker':
172 head = [P(0.15 + 0.26 * math.cos(i * 2 * math.pi / 16),
173 -0.7 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)]
174 body = [
175 P(-0.05, -0.42), P(-0.65, 0.05), P(-0.45, 0.25), P(-0.05, -0.05),
176 P(-0.15, 0.35), P(-0.7, 0.95), P(-0.4, 1.08), P(0.05, 0.45),
177 P(0.45, 1.08), P(0.7, 0.85), P(0.25, 0.3), P(0.25, -0.05),
178 P(0.7, -0.25), P(0.5, -0.45), P(0.2, -0.42),
179 ]
180 return ('polys', [head, body])
181 if k == 'hero':
182 # arms up in a V
183 head = [P(0.0 + 0.26 * math.cos(i * 2 * math.pi / 16),
184 -0.62 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)]
185 body = [
186 P(-0.18, -0.35), P(-0.95, -0.95), P(-0.7, -1.08), P(-0.1, -0.4),
187 P(-0.25, 0.35), P(-0.5, 1.08), P(-0.18, 1.08), P(0, 0.5),
188 P(0.18, 1.08), P(0.5, 1.08), P(0.25, 0.35), P(0.1, -0.4),
189 P(0.7, -1.08), P(0.95, -0.95), P(0.18, -0.35),
190 ]
191 return ('polys', [head, body])
192 # Faces
193 if k == 'smile':
194 return ('face', 'smile')
195 if k == 'wink':
196 return ('face', 'wink')
197 if k == 'cool':
198 return ('face', 'cool')
199 if k == 'grin':
200 return ('face', 'grin')
201 # Icons
202 if k == 'heart':
203 pts = []
204 for i in range(32):
205 t = i * 2 * math.pi / 32
206 # classic heart parametric, scaled
207 x = 16 * math.sin(t) ** 3
208 y = -(13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t))
209 pts.append(P(x / 16.5, y / 16.5 + 0.08))
210 return ('poly', pts)
211 if k == 'lightning':
212 return ('poly', [
213 P(0.15, -1.1), P(0.55, -1.1), P(0.05, -0.1), P(0.45, -0.1),
214 P(-0.55, 1.15), P(-0.05, 0.15), P(-0.5, 0.15),
215 ])
216 if k == 'shield':
217 return ('poly', [
218 P(0, -1.1), P(0.95, -0.7), P(0.85, 0.25), P(0, 1.1),
219 P(-0.85, 0.25), P(-0.95, -0.7),
220 ])
221 if k == 'crown':
222 return ('poly', [
223 P(-0.95, 0.45), P(-0.95, -0.15), P(-0.5, 0.25), P(0, -0.95),
224 P(0.5, 0.25), P(0.95, -0.15), P(0.95, 0.45),
225 P(0.85, 0.85), P(-0.85, 0.85),
226 ])
227 if k == 'eye':
228 return ('eye',)
229 if k == 'star6':
230 return ('poly', star_pts(cx, cy, r * 1.12, n=6, inner=0.48))
231 if k == 'spiral':
232 pts = []
233 for i in range(60):
234 t = i / 59 * 3.4 * math.pi
235 rr = 0.12 + 0.88 * (i / 59)
236 pts.append(P(rr * math.cos(t), rr * math.sin(t)))
237 return ('lines', [pts], 0.26)
238 if k == 'wave':
239 pts_top, pts_bot = [], []
240 for i in range(21):
241 x = -1.05 + i * 2.1 / 20
242 y = 0.28 * math.sin(x * math.pi * 1.4)
243 pts_top.append(P(x, y - 0.28))
244 pts_bot.append(P(x, y + 0.28))
245 return ('poly', pts_top + list(reversed(pts_bot)))
246 if k == 'mountain':
247 return ('poly', [
248 P(-1.1, 0.9), P(-0.45, -0.55), P(-0.15, -0.05),
249 P(0.15, -1.05), P(0.5, -0.25), P(0.7, -0.55),
250 P(1.1, 0.9),
251 ])
252 if k == 'fish':
253 return ('poly', [
254 P(-1.05, 0), P(-0.55, -0.55), P(0.35, -0.55), P(0.75, -0.15),
255 P(1.1, -0.55), P(0.85, 0), P(1.1, 0.55), P(0.75, 0.15),
256 P(0.35, 0.55), P(-0.55, 0.55),
257 ])
258 if k == 'bird':
259 return ('poly', [
260 P(-1.05, 0.15), P(-0.3, -0.15), P(-0.05, -0.85), P(0.2, -0.15),
261 P(0.55, -0.25), P(1.05, 0.05), P(0.45, 0.15),
262 P(0.2, 0.85), P(-0.05, 0.2), P(-0.55, 0.45),
263 ])
264 if k == 'key':
265 # head circle + shaft + teeth as one poly
266 pts = []
267 for i in range(12):
268 a = -math.pi * 0.6 + i * 1.6 * math.pi / 11
269 pts.append(P(-0.55 + 0.42 * math.cos(a), -0.55 + 0.42 * math.sin(a)))
270 pts += [
271 P(-0.25, -0.2), P(1.05, -0.2), P(1.05, 0.15),
272 P(0.85, 0.15), P(0.85, 0.5), P(0.6, 0.5), P(0.6, 0.15),
273 P(0.4, 0.15), P(0.4, 0.38), P(0.15, 0.38), P(0.15, 0.15),
274 P(-0.25, 0.15),
275 ]
276 return ('poly', pts)
277 if k == 'comet':
278 return ('poly', [
279 P(0.95, -0.95), P(0.35, -0.45), P(0.15, -0.7), P(-0.15, -0.15),
280 P(0.15, -0.05), P(-1.05, 1.05), P(-0.05, 0.15), P(0.15, 0.35),
281 P(0.55, -0.15), P(0.45, -0.45),
282 ])
283 if k == 'clover':
284 lobes = []
285 for ang, ox, oy in ((0, 0, -0.42), (2.1, -0.4, 0.18), (4.2, 0.4, 0.18)):
286 pts = []
287 for i in range(16):
288 a = i * 2 * math.pi / 16
289 pts.append(P(ox + 0.42 * math.cos(a), oy + 0.42 * math.sin(a)))
290 lobes.append(pts)
291 stem = [P(-0.08, 0.35), P(0.08, 0.35), P(0.18, 1.05), P(-0.05, 1.05)]
292 lobes.append(stem)
293 return ('polys', lobes)
294 if k == 'paw':
295 pads = []
296 for ox, oy, rr in ((-0.5, -0.55, 0.28), (0, -0.75, 0.28), (0.5, -0.55, 0.28),
297 (0.0, 0.28, 0.52)):
298 pts = []
299 for i in range(16):
300 a = i * 2 * math.pi / 16
301 pts.append(P(ox + rr * math.cos(a), oy + rr * math.sin(a)))
302 pads.append(pts)
303 return ('polys', pads)
304 if k == 'sword':
305 return ('poly', [
306 P(-0.18, 1.1), P(-0.18, 0.45), P(-0.55, 0.45), P(-0.55, 0.22),
307 P(-0.18, 0.22), P(-0.18, -0.95), P(0, -1.15), P(0.18, -0.95),
308 P(0.18, 0.22), P(0.55, 0.22), P(0.55, 0.45), P(0.18, 0.45),
309 P(0.18, 1.1),
310 ])
311 if k == 'bell':
312 pts = []
313 for i in range(18):
314 a = math.pi + i * math.pi / 17
315 pts.append(P(0.85 * math.cos(a), -0.25 + 0.85 * math.sin(a)))
316 pts += [P(0.95, 0.55), P(0.7, 0.75), P(0.15, 0.75), P(0.15, 0.95),
317 P(-0.15, 0.95), P(-0.15, 0.75), P(-0.7, 0.75), P(-0.95, 0.55)]
318 return ('poly', pts)
319 if k == 'mushroom':
320 cap = []
321 for i in range(18):
322 a = math.pi + i * math.pi / 17
323 cap.append(P(0.95 * math.cos(a), -0.25 + 0.7 * math.sin(a)))
324 cap += [P(0.95, 0.05), P(-0.95, 0.05)]
325 stem = [P(-0.32, 0.05), P(0.32, 0.05), P(0.38, 1.05), P(-0.38, 1.05)]
326 return ('polys', [cap, stem])
327 if k == 'cactus':
328 return ('poly', [
329 P(-0.22, 1.05), P(-0.22, 0.15), P(-0.75, 0.15), P(-0.75, -0.35),
330 P(-0.5, -0.35), P(-0.5, -0.05), P(-0.22, -0.05), P(-0.22, -1.05),
331 P(0.22, -1.05), P(0.22, -0.25), P(0.55, -0.25), P(0.55, -0.7),
332 P(0.8, -0.7), P(0.8, -0.02), P(0.22, -0.02), P(0.22, 1.05),
333 ])
334 if k == 'ring':
335 return ('ring', 1.0, 0.55)
336 if k == 'flag':
337 return ('poly', [
338 P(-0.7, 1.1), P(-0.7, -1.05), P(-0.5, -1.05), P(-0.5, -0.85),
339 P(1.0, -0.85), P(0.7, -0.4), P(1.0, 0.05), P(-0.5, 0.05),
340 P(-0.5, 1.1),
341 ])
342 if k == 'snowflake':
343 arms = []
344 for k0 in range(6):
345 a = k0 * math.pi / 3
346 c, s = math.cos(a), math.sin(a)
347 def rot(x, y):
348 return P(x * c - y * s, x * s + y * c)
349 arms.append([rot(0, 0), rot(0, -1.05)])
350 arms.append([rot(-0.28, -0.6), rot(0, -0.4), rot(0.28, -0.6)])
351 return ('lines', arms, 0.22)
352 if k == 'flame_icon':
353 return ('poly', [
354 P(0, -1.15), P(0.35, -0.45), P(0.55, -0.7), P(0.75, -0.15),
355 P(0.55, 0.55), P(0.2, 1.0), P(-0.25, 1.0), P(-0.6, 0.5),
356 P(-0.7, -0.05), P(-0.35, -0.55), P(-0.15, -0.2),
357 ])
358 if k == 'ankh':
359 return ('lines', [
360 [P(0, 1.05), P(0, -0.25)],
361 [P(-0.55, 0.15), P(0.55, 0.15)],
362 ], 0.28) # loop added in combo
363 if k == 'yinyang':
364 return ('yinyang',)
365 if k == 'crescent':
366 # moon
367 return ('crescent',)
368 # fallback
369 return ('ellipse', [-1, -1, 1, 1])
370
371
372 def draw_kind(draw, img, kind, cx, cy, r, fill, outline, width):
373 cmd = icon_path(cx, cy, r, kind)
374 kind_l = kind.lower()
375
376 def fill_poly(pts):
377 if len(pts) >= 3:
378 draw.polygon(pts, fill=fill, outline=outline, width=width)
379
380 def fill_lines(segs, wfrac):
381 w = max(width, int(r * wfrac))
382 # draw in outline color slightly thicker, then fill
383 thick_lines(draw, segs, outline, w + max(2, width // 2))
384 thick_lines(draw, segs, fill, w)
385
386 if cmd[0] == 'poly':
387 fill_poly(cmd[1])
388 elif cmd[0] == 'polys':
389 for pts in cmd[1]:
390 fill_poly(pts)
391 elif cmd[0] == 'lines':
392 fill_lines(cmd[1], cmd[2])
393 if kind_l == 'ankh':
394 # loop at top
395 box = [cx - r * 0.42, cy - r * 1.15, cx + r * 0.42, cy - r * 0.25]
396 draw.ellipse(box, outline=outline, width=int(r * 0.28) + width)
397 draw.ellipse([box[0] + r * 0.14, box[1] + r * 0.14,
398 box[2] - r * 0.14, box[3] - r * 0.14],
399 outline=fill, width=int(r * 0.16))
400 # fill ring by a second pass
401 # simpler: thick ellipse
402 w = int(r * 0.26)
403 draw.ellipse(box, outline=outline, width=w + width)
404 draw.ellipse(box, outline=fill, width=w)
405 elif cmd[0] == 'ellipse':
406 a, b, c, d = cmd[1]
407 box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r]
408 draw.ellipse(box, fill=fill, outline=outline, width=width)
409 elif cmd[0] == 'roundrect':
410 a, b, c, d = cmd[1]
411 box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r]
412 draw.rounded_rectangle(box, radius=r * cmd[2], fill=fill, outline=outline, width=width)
413 elif cmd[0] == 'ring':
414 _, ro, ri = cmd
415 outer = [cx - r * ro, cy - r * ro, cx + r * ro, cy + r * ro]
416 inner = [cx - r * ri, cy - r * ri, cx + r * ri, cy + r * ri]
417 draw.ellipse(outer, fill=fill, outline=outline, width=width)
418 # punch inner with destination-out
419 # We'll handle punch at a higher level; draw inner as transparent later
420 draw.ellipse(inner, fill=(0, 0, 0, 0), outline=outline, width=width)
421 elif cmd[0] == 'face':
422 box = [cx - r, cy - r, cx + r, cy + r]
423 draw.ellipse(box, fill=fill, outline=outline, width=width)
424 eye_c = outline
425 er = r * 0.12
426 if cmd[1] == 'wink':
427 draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er,
428 cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
429 draw.line([(cx + r * 0.18, cy - r * 0.28), (cx + r * 0.52, cy - r * 0.28)],
430 fill=eye_c, width=max(width, int(r * 0.12)))
431 elif cmd[1] == 'cool':
432 # sunglasses
433 draw.rounded_rectangle([cx - r * 0.7, cy - r * 0.42, cx - r * 0.08, cy - r * 0.08],
434 radius=r * 0.12, fill=eye_c)
435 draw.rounded_rectangle([cx + r * 0.08, cy - r * 0.42, cx + r * 0.7, cy - r * 0.08],
436 radius=r * 0.12, fill=eye_c)
437 draw.line([(cx - r * 0.08, cy - r * 0.25), (cx + r * 0.08, cy - r * 0.25)],
438 fill=eye_c, width=max(3, int(r * 0.1)))
439 else:
440 draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er,
441 cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
442 draw.ellipse([cx + r * 0.38 - er, cy - r * 0.28 - er,
443 cx + r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
444 # smile
445 smile = []
446 for i in range(9):
447 a = math.pi * 0.2 + i * math.pi * 0.6 / 8
448 smile.append((cx + r * 0.48 * math.cos(a), cy + r * 0.12 + r * 0.42 * math.sin(a)))
449 sw = max(width, int(r * 0.12))
450 if cmd[1] == 'grin':
451 draw.chord([cx - r * 0.5, cy + r * 0.05, cx + r * 0.5, cy + r * 0.65],
452 start=0, end=180, fill=eye_c, outline=eye_c)
453 else:
454 draw.line(smile, fill=eye_c, width=sw, joint='curve')
455 elif cmd[0] == 'eye':
456 # almond
457 pts = []
458 for i in range(24):
459 t = i * 2 * math.pi / 24
460 x = math.cos(t)
461 y = 0.5 * math.sin(t)
462 pts.append((cx + r * 1.05 * x, cy + r * 0.85 * y))
463 fill_poly(pts)
464 iris_c = outline
465 draw.ellipse([cx - r * 0.38, cy - r * 0.38, cx + r * 0.38, cy + r * 0.38],
466 fill=iris_c)
467 draw.ellipse([cx - r * 0.14, cy - r * 0.18, cx + r * 0.06, cy + r * 0.02],
468 fill=lighten(fill[:3] if isinstance(fill, tuple) else (255, 255, 255), 0.8) + (255,))
469 elif cmd[0] == 'yinyang':
470 draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
471 # right half dark via chord is messy; draw a dark semicircle + two dots
472 # Use a path: top-center to bottom via right, with small circles
473 # We'll approximate with a pie and two discs
474 dark = outline
475 draw.pieslice([cx - r, cy - r, cx + r, cy + r], start=90, end=270, fill=dark)
476 draw.ellipse([cx - r * 0.5, cy - r, cx + r * 0.5, cy], fill=dark)
477 draw.ellipse([cx - r * 0.5, cy, cx + r * 0.5, cy + r], fill=fill)
478 # dots
479 draw.ellipse([cx - r * 0.16, cy - r * 0.58, cx + r * 0.16, cy - r * 0.26], fill=fill)
480 draw.ellipse([cx - r * 0.16, cy + r * 0.26, cx + r * 0.16, cy + r * 0.58], fill=dark)
481 draw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=outline, width=width)
482 elif cmd[0] == 'crescent':
483 # moon: two circles, punch later — draw a crescent polygon
484 outer, inner = [], []
485 for i in range(24):
486 a = -math.pi * 0.75 + i * (1.5 * math.pi) / 23
487 outer.append((cx + r * math.cos(a) - r * 0.05, cy + r * math.sin(a)))
488 ox, oy = cx + r * 0.42, cy - r * 0.05
489 for i in range(20, -1, -1):
490 a = -math.pi * 0.7 + i * (1.4 * math.pi) / 20
491 inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a)))
492 fill_poly(outer + inner)
493 else:
494 draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
495
496
497 def render_block(hex_color, shape):
498 rgb = hex_rgb(hex_color)
499 hi = lighten(rgb, 0.42)
500 lo = darken(rgb, 0.32)
501 img = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
502 cx = cy = SS / 2
503 r = SS * 0.36
504 width = max(2, SCALE)
505 # drop shadow
506 shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
507 sd = ImageDraw.Draw(shadow)
508 draw_kind(sd, shadow, shape, cx + SCALE * 1.2, cy + SCALE * 1.6, r,
509 (0, 0, 0, 90), None, 0)
510 shadow = shadow.filter(ImageFilter.GaussianBlur(radius=SCALE * 1.1))
511 img = Image.alpha_composite(img, shadow)
512 # For ring, punch a hole after drawing body
513 body = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
514 bd = ImageDraw.Draw(body)
515 draw_kind(bd, body, shape, cx, cy, r, rgb + (255,), lo + (255,), width)
516 if shape == 'ring':
517 # punch inner hole
518 mask = Image.new('L', (SS, SS), 0)
519 md = ImageDraw.Draw(mask)
520 ri = r * 0.55
521 md.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], fill=255)
522 clear = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
523 body = Image.composite(clear, body, mask)
524 # redraw inner outline
525 bd = ImageDraw.Draw(body)
526 bd.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], outline=lo + (255,), width=width)
527 img = Image.alpha_composite(img, body)
528 # highlight
529 hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
530 hd = ImageDraw.Draw(hi_layer)
531 draw_kind(hd, hi_layer, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55,
532 hi + (110,), None, 0)
533 hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6))
534 # clip highlight to body alpha
535 body_a = body.split()[3]
536 ha = hi_layer.split()[3]
537 from PIL import ImageChops
538 ha = ImageChops.multiply(ha, body_a)
539 hi_layer.putalpha(ha)
540 img = Image.alpha_composite(img, hi_layer)
541 return img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)
542
543
544 # New unlockable blocks, appended after official catalog colours.
545 # ids are stable and must never be reordered or reused.
546 NEW_BLOCKS = [
547 # Runes
548 {'id': 'rune-fehu', 'name': 'Fehu', 'hex': '#e8a44a', 'shape': 'rune_fehu'},
549 {'id': 'rune-ansuz', 'name': 'Ansuz', 'hex': '#6ab0e8', 'shape': 'rune_ansuz'},
550 {'id': 'rune-thurisaz', 'name': 'Thurisaz', 'hex': '#c05040', 'shape': 'rune_thurisaz'},
551 {'id': 'rune-raido', 'name': 'Raido', 'hex': '#d0c070', 'shape': 'rune_raido'},
552 {'id': 'rune-sowilo', 'name': 'Sowilo', 'hex': '#f0d040', 'shape': 'rune_sowilo'},
553 {'id': 'rune-algiz', 'name': 'Algiz', 'hex': '#80d0a0', 'shape': 'rune_algiz'},
554 # Arrows
555 {'id': 'arrow-up', 'name': 'Arrow', 'hex': '#f07040', 'shape': 'arrow'},
556 {'id': 'arrow-chevron', 'name': 'Chevron', 'hex': '#50c0e0', 'shape': 'chevron'},
557 {'id': 'arrow-double', 'name': 'Double Arrow', 'hex': '#e05080', 'shape': 'double_arrow'},
558 {'id': 'arrow-return', 'name': 'Return', 'hex': '#a080e0', 'shape': 'return_arrow'},
559 # Figures
560 {'id': 'fig-person', 'name': 'Figure', 'hex': '#f0c0a0', 'shape': 'person'},
561 {'id': 'fig-walker', 'name': 'Walker', 'hex': '#c09070', 'shape': 'walker'},
562 {'id': 'fig-hero', 'name': 'Hero', 'hex': '#e8b070', 'shape': 'hero'},
563 # Faces
564 {'id': 'face-smile', 'name': 'Smile', 'hex': '#f0d060', 'shape': 'smile'},
565 {'id': 'face-wink', 'name': 'Wink', 'hex': '#f0a050', 'shape': 'wink'},
566 {'id': 'face-cool', 'name': 'Cool', 'hex': '#6090d0', 'shape': 'cool'},
567 {'id': 'face-grin', 'name': 'Grin', 'hex': '#f0c848', 'shape': 'grin'},
568 # Icons
569 {'id': 'icon-heart', 'name': 'Heart', 'hex': '#e04060', 'shape': 'heart'},
570 {'id': 'icon-moon', 'name': 'Moon', 'hex': '#d0d8f0', 'shape': 'crescent'},
571 {'id': 'icon-bolt', 'name': 'Bolt', 'hex': '#f0e050', 'shape': 'lightning'},
572 {'id': 'icon-shield', 'name': 'Shield', 'hex': '#5080c0', 'shape': 'shield'},
573 {'id': 'icon-crown', 'name': 'Crown', 'hex': '#f0c030', 'shape': 'crown'},
574 {'id': 'icon-eye', 'name': 'Eye', 'hex': '#70d0c0', 'shape': 'eye'},
575 {'id': 'icon-star6', 'name': 'Hexastar', 'hex': '#f0e8a0', 'shape': 'star6'},
576 {'id': 'icon-spiral', 'name': 'Spiral', 'hex': '#c070d0', 'shape': 'spiral'},
577 {'id': 'icon-wave', 'name': 'Wave', 'hex': '#3090d0', 'shape': 'wave'},
578 {'id': 'icon-mountain', 'name': 'Mountain', 'hex': '#809070', 'shape': 'mountain'},
579 {'id': 'icon-fish', 'name': 'Fish', 'hex': '#40a8c8', 'shape': 'fish'},
580 {'id': 'icon-bird', 'name': 'Bird', 'hex': '#e07050', 'shape': 'bird'},
581 {'id': 'icon-key', 'name': 'Key', 'hex': '#d0b050', 'shape': 'key'},
582 {'id': 'icon-comet', 'name': 'Comet', 'hex': '#90d0f0', 'shape': 'comet'},
583 {'id': 'icon-clover', 'name': 'Clover', 'hex': '#40b060', 'shape': 'clover'},
584 {'id': 'icon-paw', 'name': 'Paw', 'hex': '#c08050', 'shape': 'paw'},
585 {'id': 'icon-sword', 'name': 'Sword', 'hex': '#b0b8c0', 'shape': 'sword'},
586 {'id': 'icon-bell', 'name': 'Bell', 'hex': '#f0c848', 'shape': 'bell'},
587 {'id': 'icon-mushroom', 'name': 'Mushroom', 'hex': '#e06050', 'shape': 'mushroom'},
588 {'id': 'icon-cactus', 'name': 'Cactus', 'hex': '#50b068', 'shape': 'cactus'},
589 {'id': 'icon-ring', 'name': 'Ring', 'hex': '#e8d080', 'shape': 'ring'},
590 {'id': 'icon-flag', 'name': 'Flag', 'hex': '#d04050', 'shape': 'flag'},
591 {'id': 'icon-snow', 'name': 'Snowflake', 'hex': '#c8e0f8', 'shape': 'snowflake'},
592 {'id': 'icon-flame', 'name': 'Flame', 'hex': '#ff7030', 'shape': 'flame_icon'},
593 {'id': 'icon-ankh', 'name': 'Ankh', 'hex': '#d0a060', 'shape': 'ankh'},
594 {'id': 'icon-yin', 'name': 'Yin Yang', 'hex': '#606080', 'shape': 'yinyang'},
595 ]
596
597
598 def official_blocks(catalog):
599 out = []
600 seen = set()
601 for planet in catalog['planets']:
602 pid = planet['id']
603 for c in planet['colors']:
604 bid = f"{pid}-{c['name']}"
605 if bid in seen:
606 raise SystemExit(f'duplicate official id {bid}')
607 seen.add(bid)
608 out.append({
609 'id': bid,
610 'name': c['name'].capitalize() if pid == 'terra' else f"{planet['name']} {c['name']}",
611 'hex': c['hex'],
612 'shape': c.get('shape') or 'circle',
613 'image': c['image'],
614 'terra': pid == 'terra',
615 })
616 return out
617
618
619 def main():
620 catalog = json.loads(CATALOG.read_text())
621 official = official_blocks(catalog)
622 terra = [b for b in official if b.get('terra')]
623 others = [b for b in official if not b.get('terra')]
624 if len(terra) != 5 or terra[0]['id'] != 'terra-ember':
625 raise SystemExit(f'Terra five unexpected: {[b["id"] for b in terra]}')
626
627 new = []
628 seen = {b['id'] for b in official}
629 OUT_IMG.mkdir(parents=True, exist_ok=True)
630 for b in NEW_BLOCKS:
631 if b['id'] in seen:
632 raise SystemExit(f'duplicate new id {b["id"]}')
633 seen.add(b['id'])
634 image = f"images/block-{b['id']}.png"
635 path = ROOT / 'build' / image
636 img = render_block(b['hex'], b['shape'])
637 img.save(path, 'PNG', optimize=True)
638 new.append({
639 'id': b['id'],
640 'name': b['name'],
641 'hex': b['hex'],
642 'shape': b['shape'],
643 'image': image,
644 'terra': False,
645 })
646 print(f' wrote {path.relative_to(ROOT)} ({path.stat().st_size} bytes)')
647
648 registry = {
649 '_comment': (
650 'Append-only block registry. Never reorder, rename ids, or insert '
651 'in the middle. New blocks go at the end. The first five (Terra) '
652 'are unlocked by default; index 5 requires 500 lifetime points, '
653 'each next index requires 14.5% more (rounded).'
654 ),
655 'terraCount': 5,
656 'firstThreshold': 500,
657 'thresholdGrowth': 1.145,
658 'blocks': terra + new + others,
659 }
660 OUT_JSON.write_text(json.dumps(registry, indent=2, ensure_ascii=False) + '\n')
661 print(f'wrote {OUT_JSON.relative_to(ROOT)}: {len(terra)} terra + {len(new)} new + {len(others)} official = {len(registry["blocks"])} total')
662
663
664 if __name__ == '__main__':
665 main()
@@ -0,0 +1,665 @@
1#!/usr/bin/env python3
2"""Build server/lib/blocks.json (append-only registry) and new unlockable
3block PNGs in the existing 64×64 style: coloured silhouette, dark outline,
4soft highlight, drop shadow.
5
6Official catalog colours are listed first (Terra's five, then the other
7planets in catalog order) and their existing PNGs are left untouched.
8New icons are appended and rendered here.
9
10Run from the repo root: python3 scripts/gen_unlock_blocks.py
11"""
12from __future__ import annotations
13
14import json
15import math
16from pathlib import Path
17
18from PIL import Image, ImageDraw, ImageFilter
19
20ROOT = Path(__file__).resolve().parents[1]
21CATALOG = ROOT / 'server' / 'lib' / 'planets.json'
22OUT_JSON = ROOT / 'server' / 'lib' / 'blocks.json'
23OUT_IMG = ROOT / 'build' / 'images'
24SIZE = 64
25SCALE = 4
26SS = SIZE * SCALE
27
28
29def hex_rgb(h):
30 h = h.lstrip('#')
31 return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
32
33
34def lighten(rgb, f=0.35):
35 return tuple(min(255, int(c + (255 - c) * f)) for c in rgb)
36
37
38def darken(rgb, f=0.28):
39 return tuple(max(0, int(c * (1 - f))) for c in rgb)
40
41
42def regular_poly(cx, cy, r, n, rot=-math.pi / 2):
43 pts = []
44 for i in range(n):
45 a = rot + i * 2 * math.pi / n
46 pts.append((cx + r * math.cos(a), cy + r * math.sin(a)))
47 return pts
48
49
50def star_pts(cx, cy, r, n=5, inner=0.42, rot=-math.pi / 2):
51 pts = []
52 for i in range(n * 2):
53 a = rot + i * math.pi / n
54 rr = r if i % 2 == 0 else r * inner
55 pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
56 return pts
57
58
59# ---------- shape primitives (filled polygons / lines) ----------
60
61def poly_stroke(draw, pts, fill, outline, width):
62 draw.polygon(pts, fill=fill, outline=outline, width=width)
63
64
65def thick_lines(draw, segs, color, width, closed=False):
66 """segs: list of point lists."""
67 for pts in segs:
68 if len(pts) < 2:
69 continue
70 draw.line(pts, fill=color, width=width, joint='curve')
71 # round caps
72 r = width / 2
73 for p in (pts[0], pts[-1]):
74 draw.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r], fill=color)
75 if closed and pts[0] != pts[-1]:
76 draw.line([pts[-1], pts[0]], fill=color, width=width)
77
78
79def icon_path(cx, cy, r, kind):
80 """Return ('poly', pts) or ('polys', [pts, ...]) or ('lines', [pts,...], wfrac)
81 or ('combo', list of commands). Coordinates in actual pixels."""
82 def P(x, y):
83 return (cx + x * r, cy + y * r)
84
85 k = kind.lower()
86 if k == 'circle':
87 return ('ellipse', [-1, -1, 1, 1])
88 if k == 'square':
89 s = 0.86
90 return ('roundrect', [-s, -s, s, s], 0.12)
91 if k == 'triangle':
92 return ('poly', regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2))
93 if k == 'diamond':
94 return ('poly', regular_poly(cx, cy, r * 1.05, 4, 0))
95 if k == 'star':
96 return ('poly', star_pts(cx, cy, r * 1.12))
97 if k == 'hexagon':
98 return ('poly', regular_poly(cx, cy, r * 1.05, 6, 0))
99 if k == 'pentagon':
100 return ('poly', regular_poly(cx, cy, r * 1.08, 5))
101 if k == 'arrow':
102 return ('poly', [
103 P(0, -1.1), P(0.85, 0.05), P(0.28, 0.05), P(0.28, 1),
104 P(-0.28, 1), P(-0.28, 0.05), P(-0.85, 0.05),
105 ])
106 if k == 'chevron':
107 return ('poly', [
108 P(0, -1.05), P(0.95, 0.15), P(0.95, 0.55), P(0, -0.15),
109 P(-0.95, 0.55), P(-0.95, 0.15),
110 ])
111 if k == 'double_arrow':
112 return ('poly', [
113 P(0, -1.15), P(0.72, -0.25), P(0.28, -0.25), P(0.28, 0.05),
114 P(0.72, 0.05), P(0, 1.15), P(-0.72, 0.05), P(-0.28, 0.05),
115 P(-0.28, -0.25), P(-0.72, -0.25),
116 ])
117 if k == 'return_arrow':
118 return ('poly', [
119 P(-0.15, -1.1), P(0.7, -0.4), P(0.25, -0.4), P(0.25, 0.15),
120 P(0.85, 0.15), P(0.85, 0.55), P(-0.25, 0.55), P(-0.25, -0.4),
121 P(-0.7, -0.4),
122 ])
123 # Runes — stylized, thick, readable
124 if k == 'rune_fehu':
125 return ('lines', [
126 [P(-0.15, 1.0), P(-0.15, -1.0)],
127 [P(-0.15, -0.55), P(0.85, -0.95)],
128 [P(-0.15, -0.05), P(0.85, -0.45)],
129 ], 0.28)
130 if k == 'rune_ansuz':
131 return ('lines', [
132 [P(-0.2, 1.0), P(-0.2, -1.0)],
133 [P(-0.2, -0.85), P(0.85, -0.25)],
134 [P(-0.2, -0.15), P(0.7, 0.45)],
135 ], 0.28)
136 if k == 'rune_thurisaz':
137 return ('lines', [
138 [P(-0.35, 1.0), P(-0.35, -1.0)],
139 [P(-0.35, -0.55), P(0.7, 0), P(-0.35, 0.55)],
140 ], 0.28)
141 if k == 'rune_raido':
142 return ('lines', [
143 [P(-0.3, 1.0), P(-0.3, -1.0)],
144 [P(-0.3, -1.0), P(0.65, -0.55), P(-0.3, -0.1)],
145 [P(-0.05, -0.1), P(0.7, 1.0)],
146 ], 0.26)
147 if k == 'rune_sowilo':
148 return ('lines', [
149 [P(0.55, -1.05), P(-0.45, -0.25), P(0.45, 0.25), P(-0.55, 1.05)],
150 ], 0.30)
151 if k == 'rune_algiz':
152 return ('lines', [
153 [P(0, 1.05), P(0, -1.05)],
154 [P(0, -0.15), P(-0.75, -0.95)],
155 [P(0, -0.15), P(0.75, -0.95)],
156 ], 0.28)
157 # Figures
158 if k == 'person':
159 # head + body + arms + legs as one silhouette
160 head = []
161 for i in range(16):
162 a = i * 2 * math.pi / 16
163 head.append(P(0.0 + 0.28 * math.cos(a), -0.72 + 0.28 * math.sin(a)))
164 body = [
165 P(-0.22, -0.42), P(-0.72, -0.15), P(-0.72, 0.12), P(-0.22, -0.08),
166 P(-0.28, 0.35), P(-0.55, 1.05), P(-0.22, 1.05), P(0, 0.5),
167 P(0.22, 1.05), P(0.55, 1.05), P(0.28, 0.35), P(0.22, -0.08),
168 P(0.72, 0.12), P(0.72, -0.15), P(0.22, -0.42),
169 ]
170 return ('polys', [head, body])
171 if k == 'walker':
172 head = [P(0.15 + 0.26 * math.cos(i * 2 * math.pi / 16),
173 -0.7 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)]
174 body = [
175 P(-0.05, -0.42), P(-0.65, 0.05), P(-0.45, 0.25), P(-0.05, -0.05),
176 P(-0.15, 0.35), P(-0.7, 0.95), P(-0.4, 1.08), P(0.05, 0.45),
177 P(0.45, 1.08), P(0.7, 0.85), P(0.25, 0.3), P(0.25, -0.05),
178 P(0.7, -0.25), P(0.5, -0.45), P(0.2, -0.42),
179 ]
180 return ('polys', [head, body])
181 if k == 'hero':
182 # arms up in a V
183 head = [P(0.0 + 0.26 * math.cos(i * 2 * math.pi / 16),
184 -0.62 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)]
185 body = [
186 P(-0.18, -0.35), P(-0.95, -0.95), P(-0.7, -1.08), P(-0.1, -0.4),
187 P(-0.25, 0.35), P(-0.5, 1.08), P(-0.18, 1.08), P(0, 0.5),
188 P(0.18, 1.08), P(0.5, 1.08), P(0.25, 0.35), P(0.1, -0.4),
189 P(0.7, -1.08), P(0.95, -0.95), P(0.18, -0.35),
190 ]
191 return ('polys', [head, body])
192 # Faces
193 if k == 'smile':
194 return ('face', 'smile')
195 if k == 'wink':
196 return ('face', 'wink')
197 if k == 'cool':
198 return ('face', 'cool')
199 if k == 'grin':
200 return ('face', 'grin')
201 # Icons
202 if k == 'heart':
203 pts = []
204 for i in range(32):
205 t = i * 2 * math.pi / 32
206 # classic heart parametric, scaled
207 x = 16 * math.sin(t) ** 3
208 y = -(13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t))
209 pts.append(P(x / 16.5, y / 16.5 + 0.08))
210 return ('poly', pts)
211 if k == 'lightning':
212 return ('poly', [
213 P(0.15, -1.1), P(0.55, -1.1), P(0.05, -0.1), P(0.45, -0.1),
214 P(-0.55, 1.15), P(-0.05, 0.15), P(-0.5, 0.15),
215 ])
216 if k == 'shield':
217 return ('poly', [
218 P(0, -1.1), P(0.95, -0.7), P(0.85, 0.25), P(0, 1.1),
219 P(-0.85, 0.25), P(-0.95, -0.7),
220 ])
221 if k == 'crown':
222 return ('poly', [
223 P(-0.95, 0.45), P(-0.95, -0.15), P(-0.5, 0.25), P(0, -0.95),
224 P(0.5, 0.25), P(0.95, -0.15), P(0.95, 0.45),
225 P(0.85, 0.85), P(-0.85, 0.85),
226 ])
227 if k == 'eye':
228 return ('eye',)
229 if k == 'star6':
230 return ('poly', star_pts(cx, cy, r * 1.12, n=6, inner=0.48))
231 if k == 'spiral':
232 pts = []
233 for i in range(60):
234 t = i / 59 * 3.4 * math.pi
235 rr = 0.12 + 0.88 * (i / 59)
236 pts.append(P(rr * math.cos(t), rr * math.sin(t)))
237 return ('lines', [pts], 0.26)
238 if k == 'wave':
239 pts_top, pts_bot = [], []
240 for i in range(21):
241 x = -1.05 + i * 2.1 / 20
242 y = 0.28 * math.sin(x * math.pi * 1.4)
243 pts_top.append(P(x, y - 0.28))
244 pts_bot.append(P(x, y + 0.28))
245 return ('poly', pts_top + list(reversed(pts_bot)))
246 if k == 'mountain':
247 return ('poly', [
248 P(-1.1, 0.9), P(-0.45, -0.55), P(-0.15, -0.05),
249 P(0.15, -1.05), P(0.5, -0.25), P(0.7, -0.55),
250 P(1.1, 0.9),
251 ])
252 if k == 'fish':
253 return ('poly', [
254 P(-1.05, 0), P(-0.55, -0.55), P(0.35, -0.55), P(0.75, -0.15),
255 P(1.1, -0.55), P(0.85, 0), P(1.1, 0.55), P(0.75, 0.15),
256 P(0.35, 0.55), P(-0.55, 0.55),
257 ])
258 if k == 'bird':
259 return ('poly', [
260 P(-1.05, 0.15), P(-0.3, -0.15), P(-0.05, -0.85), P(0.2, -0.15),
261 P(0.55, -0.25), P(1.05, 0.05), P(0.45, 0.15),
262 P(0.2, 0.85), P(-0.05, 0.2), P(-0.55, 0.45),
263 ])
264 if k == 'key':
265 # head circle + shaft + teeth as one poly
266 pts = []
267 for i in range(12):
268 a = -math.pi * 0.6 + i * 1.6 * math.pi / 11
269 pts.append(P(-0.55 + 0.42 * math.cos(a), -0.55 + 0.42 * math.sin(a)))
270 pts += [
271 P(-0.25, -0.2), P(1.05, -0.2), P(1.05, 0.15),
272 P(0.85, 0.15), P(0.85, 0.5), P(0.6, 0.5), P(0.6, 0.15),
273 P(0.4, 0.15), P(0.4, 0.38), P(0.15, 0.38), P(0.15, 0.15),
274 P(-0.25, 0.15),
275 ]
276 return ('poly', pts)
277 if k == 'comet':
278 return ('poly', [
279 P(0.95, -0.95), P(0.35, -0.45), P(0.15, -0.7), P(-0.15, -0.15),
280 P(0.15, -0.05), P(-1.05, 1.05), P(-0.05, 0.15), P(0.15, 0.35),
281 P(0.55, -0.15), P(0.45, -0.45),
282 ])
283 if k == 'clover':
284 lobes = []
285 for ang, ox, oy in ((0, 0, -0.42), (2.1, -0.4, 0.18), (4.2, 0.4, 0.18)):
286 pts = []
287 for i in range(16):
288 a = i * 2 * math.pi / 16
289 pts.append(P(ox + 0.42 * math.cos(a), oy + 0.42 * math.sin(a)))
290 lobes.append(pts)
291 stem = [P(-0.08, 0.35), P(0.08, 0.35), P(0.18, 1.05), P(-0.05, 1.05)]
292 lobes.append(stem)
293 return ('polys', lobes)
294 if k == 'paw':
295 pads = []
296 for ox, oy, rr in ((-0.5, -0.55, 0.28), (0, -0.75, 0.28), (0.5, -0.55, 0.28),
297 (0.0, 0.28, 0.52)):
298 pts = []
299 for i in range(16):
300 a = i * 2 * math.pi / 16
301 pts.append(P(ox + rr * math.cos(a), oy + rr * math.sin(a)))
302 pads.append(pts)
303 return ('polys', pads)
304 if k == 'sword':
305 return ('poly', [
306 P(-0.18, 1.1), P(-0.18, 0.45), P(-0.55, 0.45), P(-0.55, 0.22),
307 P(-0.18, 0.22), P(-0.18, -0.95), P(0, -1.15), P(0.18, -0.95),
308 P(0.18, 0.22), P(0.55, 0.22), P(0.55, 0.45), P(0.18, 0.45),
309 P(0.18, 1.1),
310 ])
311 if k == 'bell':
312 pts = []
313 for i in range(18):
314 a = math.pi + i * math.pi / 17
315 pts.append(P(0.85 * math.cos(a), -0.25 + 0.85 * math.sin(a)))
316 pts += [P(0.95, 0.55), P(0.7, 0.75), P(0.15, 0.75), P(0.15, 0.95),
317 P(-0.15, 0.95), P(-0.15, 0.75), P(-0.7, 0.75), P(-0.95, 0.55)]
318 return ('poly', pts)
319 if k == 'mushroom':
320 cap = []
321 for i in range(18):
322 a = math.pi + i * math.pi / 17
323 cap.append(P(0.95 * math.cos(a), -0.25 + 0.7 * math.sin(a)))
324 cap += [P(0.95, 0.05), P(-0.95, 0.05)]
325 stem = [P(-0.32, 0.05), P(0.32, 0.05), P(0.38, 1.05), P(-0.38, 1.05)]
326 return ('polys', [cap, stem])
327 if k == 'cactus':
328 return ('poly', [
329 P(-0.22, 1.05), P(-0.22, 0.15), P(-0.75, 0.15), P(-0.75, -0.35),
330 P(-0.5, -0.35), P(-0.5, -0.05), P(-0.22, -0.05), P(-0.22, -1.05),
331 P(0.22, -1.05), P(0.22, -0.25), P(0.55, -0.25), P(0.55, -0.7),
332 P(0.8, -0.7), P(0.8, -0.02), P(0.22, -0.02), P(0.22, 1.05),
333 ])
334 if k == 'ring':
335 return ('ring', 1.0, 0.55)
336 if k == 'flag':
337 return ('poly', [
338 P(-0.7, 1.1), P(-0.7, -1.05), P(-0.5, -1.05), P(-0.5, -0.85),
339 P(1.0, -0.85), P(0.7, -0.4), P(1.0, 0.05), P(-0.5, 0.05),
340 P(-0.5, 1.1),
341 ])
342 if k == 'snowflake':
343 arms = []
344 for k0 in range(6):
345 a = k0 * math.pi / 3
346 c, s = math.cos(a), math.sin(a)
347 def rot(x, y):
348 return P(x * c - y * s, x * s + y * c)
349 arms.append([rot(0, 0), rot(0, -1.05)])
350 arms.append([rot(-0.28, -0.6), rot(0, -0.4), rot(0.28, -0.6)])
351 return ('lines', arms, 0.22)
352 if k == 'flame_icon':
353 return ('poly', [
354 P(0, -1.15), P(0.35, -0.45), P(0.55, -0.7), P(0.75, -0.15),
355 P(0.55, 0.55), P(0.2, 1.0), P(-0.25, 1.0), P(-0.6, 0.5),
356 P(-0.7, -0.05), P(-0.35, -0.55), P(-0.15, -0.2),
357 ])
358 if k == 'ankh':
359 return ('lines', [
360 [P(0, 1.05), P(0, -0.25)],
361 [P(-0.55, 0.15), P(0.55, 0.15)],
362 ], 0.28) # loop added in combo
363 if k == 'yinyang':
364 return ('yinyang',)
365 if k == 'crescent':
366 # moon
367 return ('crescent',)
368 # fallback
369 return ('ellipse', [-1, -1, 1, 1])
370
371
372def draw_kind(draw, img, kind, cx, cy, r, fill, outline, width):
373 cmd = icon_path(cx, cy, r, kind)
374 kind_l = kind.lower()
375
376 def fill_poly(pts):
377 if len(pts) >= 3:
378 draw.polygon(pts, fill=fill, outline=outline, width=width)
379
380 def fill_lines(segs, wfrac):
381 w = max(width, int(r * wfrac))
382 # draw in outline color slightly thicker, then fill
383 thick_lines(draw, segs, outline, w + max(2, width // 2))
384 thick_lines(draw, segs, fill, w)
385
386 if cmd[0] == 'poly':
387 fill_poly(cmd[1])
388 elif cmd[0] == 'polys':
389 for pts in cmd[1]:
390 fill_poly(pts)
391 elif cmd[0] == 'lines':
392 fill_lines(cmd[1], cmd[2])
393 if kind_l == 'ankh':
394 # loop at top
395 box = [cx - r * 0.42, cy - r * 1.15, cx + r * 0.42, cy - r * 0.25]
396 draw.ellipse(box, outline=outline, width=int(r * 0.28) + width)
397 draw.ellipse([box[0] + r * 0.14, box[1] + r * 0.14,
398 box[2] - r * 0.14, box[3] - r * 0.14],
399 outline=fill, width=int(r * 0.16))
400 # fill ring by a second pass
401 # simpler: thick ellipse
402 w = int(r * 0.26)
403 draw.ellipse(box, outline=outline, width=w + width)
404 draw.ellipse(box, outline=fill, width=w)
405 elif cmd[0] == 'ellipse':
406 a, b, c, d = cmd[1]
407 box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r]
408 draw.ellipse(box, fill=fill, outline=outline, width=width)
409 elif cmd[0] == 'roundrect':
410 a, b, c, d = cmd[1]
411 box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r]
412 draw.rounded_rectangle(box, radius=r * cmd[2], fill=fill, outline=outline, width=width)
413 elif cmd[0] == 'ring':
414 _, ro, ri = cmd
415 outer = [cx - r * ro, cy - r * ro, cx + r * ro, cy + r * ro]
416 inner = [cx - r * ri, cy - r * ri, cx + r * ri, cy + r * ri]
417 draw.ellipse(outer, fill=fill, outline=outline, width=width)
418 # punch inner with destination-out
419 # We'll handle punch at a higher level; draw inner as transparent later
420 draw.ellipse(inner, fill=(0, 0, 0, 0), outline=outline, width=width)
421 elif cmd[0] == 'face':
422 box = [cx - r, cy - r, cx + r, cy + r]
423 draw.ellipse(box, fill=fill, outline=outline, width=width)
424 eye_c = outline
425 er = r * 0.12
426 if cmd[1] == 'wink':
427 draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er,
428 cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
429 draw.line([(cx + r * 0.18, cy - r * 0.28), (cx + r * 0.52, cy - r * 0.28)],
430 fill=eye_c, width=max(width, int(r * 0.12)))
431 elif cmd[1] == 'cool':
432 # sunglasses
433 draw.rounded_rectangle([cx - r * 0.7, cy - r * 0.42, cx - r * 0.08, cy - r * 0.08],
434 radius=r * 0.12, fill=eye_c)
435 draw.rounded_rectangle([cx + r * 0.08, cy - r * 0.42, cx + r * 0.7, cy - r * 0.08],
436 radius=r * 0.12, fill=eye_c)
437 draw.line([(cx - r * 0.08, cy - r * 0.25), (cx + r * 0.08, cy - r * 0.25)],
438 fill=eye_c, width=max(3, int(r * 0.1)))
439 else:
440 draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er,
441 cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
442 draw.ellipse([cx + r * 0.38 - er, cy - r * 0.28 - er,
443 cx + r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
444 # smile
445 smile = []
446 for i in range(9):
447 a = math.pi * 0.2 + i * math.pi * 0.6 / 8
448 smile.append((cx + r * 0.48 * math.cos(a), cy + r * 0.12 + r * 0.42 * math.sin(a)))
449 sw = max(width, int(r * 0.12))
450 if cmd[1] == 'grin':
451 draw.chord([cx - r * 0.5, cy + r * 0.05, cx + r * 0.5, cy + r * 0.65],
452 start=0, end=180, fill=eye_c, outline=eye_c)
453 else:
454 draw.line(smile, fill=eye_c, width=sw, joint='curve')
455 elif cmd[0] == 'eye':
456 # almond
457 pts = []
458 for i in range(24):
459 t = i * 2 * math.pi / 24
460 x = math.cos(t)
461 y = 0.5 * math.sin(t)
462 pts.append((cx + r * 1.05 * x, cy + r * 0.85 * y))
463 fill_poly(pts)
464 iris_c = outline
465 draw.ellipse([cx - r * 0.38, cy - r * 0.38, cx + r * 0.38, cy + r * 0.38],
466 fill=iris_c)
467 draw.ellipse([cx - r * 0.14, cy - r * 0.18, cx + r * 0.06, cy + r * 0.02],
468 fill=lighten(fill[:3] if isinstance(fill, tuple) else (255, 255, 255), 0.8) + (255,))
469 elif cmd[0] == 'yinyang':
470 draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
471 # right half dark via chord is messy; draw a dark semicircle + two dots
472 # Use a path: top-center to bottom via right, with small circles
473 # We'll approximate with a pie and two discs
474 dark = outline
475 draw.pieslice([cx - r, cy - r, cx + r, cy + r], start=90, end=270, fill=dark)
476 draw.ellipse([cx - r * 0.5, cy - r, cx + r * 0.5, cy], fill=dark)
477 draw.ellipse([cx - r * 0.5, cy, cx + r * 0.5, cy + r], fill=fill)
478 # dots
479 draw.ellipse([cx - r * 0.16, cy - r * 0.58, cx + r * 0.16, cy - r * 0.26], fill=fill)
480 draw.ellipse([cx - r * 0.16, cy + r * 0.26, cx + r * 0.16, cy + r * 0.58], fill=dark)
481 draw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=outline, width=width)
482 elif cmd[0] == 'crescent':
483 # moon: two circles, punch later — draw a crescent polygon
484 outer, inner = [], []
485 for i in range(24):
486 a = -math.pi * 0.75 + i * (1.5 * math.pi) / 23
487 outer.append((cx + r * math.cos(a) - r * 0.05, cy + r * math.sin(a)))
488 ox, oy = cx + r * 0.42, cy - r * 0.05
489 for i in range(20, -1, -1):
490 a = -math.pi * 0.7 + i * (1.4 * math.pi) / 20
491 inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a)))
492 fill_poly(outer + inner)
493 else:
494 draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
495
496
497def render_block(hex_color, shape):
498 rgb = hex_rgb(hex_color)
499 hi = lighten(rgb, 0.42)
500 lo = darken(rgb, 0.32)
501 img = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
502 cx = cy = SS / 2
503 r = SS * 0.36
504 width = max(2, SCALE)
505 # drop shadow
506 shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
507 sd = ImageDraw.Draw(shadow)
508 draw_kind(sd, shadow, shape, cx + SCALE * 1.2, cy + SCALE * 1.6, r,
509 (0, 0, 0, 90), None, 0)
510 shadow = shadow.filter(ImageFilter.GaussianBlur(radius=SCALE * 1.1))
511 img = Image.alpha_composite(img, shadow)
512 # For ring, punch a hole after drawing body
513 body = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
514 bd = ImageDraw.Draw(body)
515 draw_kind(bd, body, shape, cx, cy, r, rgb + (255,), lo + (255,), width)
516 if shape == 'ring':
517 # punch inner hole
518 mask = Image.new('L', (SS, SS), 0)
519 md = ImageDraw.Draw(mask)
520 ri = r * 0.55
521 md.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], fill=255)
522 clear = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
523 body = Image.composite(clear, body, mask)
524 # redraw inner outline
525 bd = ImageDraw.Draw(body)
526 bd.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], outline=lo + (255,), width=width)
527 img = Image.alpha_composite(img, body)
528 # highlight
529 hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
530 hd = ImageDraw.Draw(hi_layer)
531 draw_kind(hd, hi_layer, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55,
532 hi + (110,), None, 0)
533 hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6))
534 # clip highlight to body alpha
535 body_a = body.split()[3]
536 ha = hi_layer.split()[3]
537 from PIL import ImageChops
538 ha = ImageChops.multiply(ha, body_a)
539 hi_layer.putalpha(ha)
540 img = Image.alpha_composite(img, hi_layer)
541 return img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)
542
543
544# New unlockable blocks, appended after official catalog colours.
545# ids are stable and must never be reordered or reused.
546NEW_BLOCKS = [
547 # Runes
548 {'id': 'rune-fehu', 'name': 'Fehu', 'hex': '#e8a44a', 'shape': 'rune_fehu'},
549 {'id': 'rune-ansuz', 'name': 'Ansuz', 'hex': '#6ab0e8', 'shape': 'rune_ansuz'},
550 {'id': 'rune-thurisaz', 'name': 'Thurisaz', 'hex': '#c05040', 'shape': 'rune_thurisaz'},
551 {'id': 'rune-raido', 'name': 'Raido', 'hex': '#d0c070', 'shape': 'rune_raido'},
552 {'id': 'rune-sowilo', 'name': 'Sowilo', 'hex': '#f0d040', 'shape': 'rune_sowilo'},
553 {'id': 'rune-algiz', 'name': 'Algiz', 'hex': '#80d0a0', 'shape': 'rune_algiz'},
554 # Arrows
555 {'id': 'arrow-up', 'name': 'Arrow', 'hex': '#f07040', 'shape': 'arrow'},
556 {'id': 'arrow-chevron', 'name': 'Chevron', 'hex': '#50c0e0', 'shape': 'chevron'},
557 {'id': 'arrow-double', 'name': 'Double Arrow', 'hex': '#e05080', 'shape': 'double_arrow'},
558 {'id': 'arrow-return', 'name': 'Return', 'hex': '#a080e0', 'shape': 'return_arrow'},
559 # Figures
560 {'id': 'fig-person', 'name': 'Figure', 'hex': '#f0c0a0', 'shape': 'person'},
561 {'id': 'fig-walker', 'name': 'Walker', 'hex': '#c09070', 'shape': 'walker'},
562 {'id': 'fig-hero', 'name': 'Hero', 'hex': '#e8b070', 'shape': 'hero'},
563 # Faces
564 {'id': 'face-smile', 'name': 'Smile', 'hex': '#f0d060', 'shape': 'smile'},
565 {'id': 'face-wink', 'name': 'Wink', 'hex': '#f0a050', 'shape': 'wink'},
566 {'id': 'face-cool', 'name': 'Cool', 'hex': '#6090d0', 'shape': 'cool'},
567 {'id': 'face-grin', 'name': 'Grin', 'hex': '#f0c848', 'shape': 'grin'},
568 # Icons
569 {'id': 'icon-heart', 'name': 'Heart', 'hex': '#e04060', 'shape': 'heart'},
570 {'id': 'icon-moon', 'name': 'Moon', 'hex': '#d0d8f0', 'shape': 'crescent'},
571 {'id': 'icon-bolt', 'name': 'Bolt', 'hex': '#f0e050', 'shape': 'lightning'},
572 {'id': 'icon-shield', 'name': 'Shield', 'hex': '#5080c0', 'shape': 'shield'},
573 {'id': 'icon-crown', 'name': 'Crown', 'hex': '#f0c030', 'shape': 'crown'},
574 {'id': 'icon-eye', 'name': 'Eye', 'hex': '#70d0c0', 'shape': 'eye'},
575 {'id': 'icon-star6', 'name': 'Hexastar', 'hex': '#f0e8a0', 'shape': 'star6'},
576 {'id': 'icon-spiral', 'name': 'Spiral', 'hex': '#c070d0', 'shape': 'spiral'},
577 {'id': 'icon-wave', 'name': 'Wave', 'hex': '#3090d0', 'shape': 'wave'},
578 {'id': 'icon-mountain', 'name': 'Mountain', 'hex': '#809070', 'shape': 'mountain'},
579 {'id': 'icon-fish', 'name': 'Fish', 'hex': '#40a8c8', 'shape': 'fish'},
580 {'id': 'icon-bird', 'name': 'Bird', 'hex': '#e07050', 'shape': 'bird'},
581 {'id': 'icon-key', 'name': 'Key', 'hex': '#d0b050', 'shape': 'key'},
582 {'id': 'icon-comet', 'name': 'Comet', 'hex': '#90d0f0', 'shape': 'comet'},
583 {'id': 'icon-clover', 'name': 'Clover', 'hex': '#40b060', 'shape': 'clover'},
584 {'id': 'icon-paw', 'name': 'Paw', 'hex': '#c08050', 'shape': 'paw'},
585 {'id': 'icon-sword', 'name': 'Sword', 'hex': '#b0b8c0', 'shape': 'sword'},
586 {'id': 'icon-bell', 'name': 'Bell', 'hex': '#f0c848', 'shape': 'bell'},
587 {'id': 'icon-mushroom', 'name': 'Mushroom', 'hex': '#e06050', 'shape': 'mushroom'},
588 {'id': 'icon-cactus', 'name': 'Cactus', 'hex': '#50b068', 'shape': 'cactus'},
589 {'id': 'icon-ring', 'name': 'Ring', 'hex': '#e8d080', 'shape': 'ring'},
590 {'id': 'icon-flag', 'name': 'Flag', 'hex': '#d04050', 'shape': 'flag'},
591 {'id': 'icon-snow', 'name': 'Snowflake', 'hex': '#c8e0f8', 'shape': 'snowflake'},
592 {'id': 'icon-flame', 'name': 'Flame', 'hex': '#ff7030', 'shape': 'flame_icon'},
593 {'id': 'icon-ankh', 'name': 'Ankh', 'hex': '#d0a060', 'shape': 'ankh'},
594 {'id': 'icon-yin', 'name': 'Yin Yang', 'hex': '#606080', 'shape': 'yinyang'},
595]
596
597
598def official_blocks(catalog):
599 out = []
600 seen = set()
601 for planet in catalog['planets']:
602 pid = planet['id']
603 for c in planet['colors']:
604 bid = f"{pid}-{c['name']}"
605 if bid in seen:
606 raise SystemExit(f'duplicate official id {bid}')
607 seen.add(bid)
608 out.append({
609 'id': bid,
610 'name': c['name'].capitalize() if pid == 'terra' else f"{planet['name']} {c['name']}",
611 'hex': c['hex'],
612 'shape': c.get('shape') or 'circle',
613 'image': c['image'],
614 'terra': pid == 'terra',
615 })
616 return out
617
618
619def main():
620 catalog = json.loads(CATALOG.read_text())
621 official = official_blocks(catalog)
622 terra = [b for b in official if b.get('terra')]
623 others = [b for b in official if not b.get('terra')]
624 if len(terra) != 5 or terra[0]['id'] != 'terra-ember':
625 raise SystemExit(f'Terra five unexpected: {[b["id"] for b in terra]}')
626
627 new = []
628 seen = {b['id'] for b in official}
629 OUT_IMG.mkdir(parents=True, exist_ok=True)
630 for b in NEW_BLOCKS:
631 if b['id'] in seen:
632 raise SystemExit(f'duplicate new id {b["id"]}')
633 seen.add(b['id'])
634 image = f"images/block-{b['id']}.png"
635 path = ROOT / 'build' / image
636 img = render_block(b['hex'], b['shape'])
637 img.save(path, 'PNG', optimize=True)
638 new.append({
639 'id': b['id'],
640 'name': b['name'],
641 'hex': b['hex'],
642 'shape': b['shape'],
643 'image': image,
644 'terra': False,
645 })
646 print(f' wrote {path.relative_to(ROOT)} ({path.stat().st_size} bytes)')
647
648 registry = {
649 '_comment': (
650 'Append-only block registry. Never reorder, rename ids, or insert '
651 'in the middle. New blocks go at the end. The first five (Terra) '
652 'are unlocked by default; index 5 requires 500 lifetime points, '
653 'each next index requires 14.5% more (rounded).'
654 ),
655 'terraCount': 5,
656 'firstThreshold': 500,
657 'thresholdGrowth': 1.145,
658 'blocks': terra + new + others,
659 }
660 OUT_JSON.write_text(json.dumps(registry, indent=2, ensure_ascii=False) + '\n')
661 print(f'wrote {OUT_JSON.relative_to(ROOT)}: {len(terra)} terra + {len(new)} new + {len(others)} official = {len(registry["blocks"])} total')
662
663
664if __name__ == '__main__':
665 main()
server/api.php +57 −1
@@ -18,8 +18,16 @@ try {
18 18
19 19 if ($action === 'me' || $action === '') {
20 20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
21 $profile = [
22 'lifetime_points' => 0,
23 'locale' => null,
24 'blocks' => [],
25 'planets' => [],
26 ];
21 27 if ($user) {
22 $view = Store::open()->viewFor($user['id']);
28 $store = Store::open();
29 $view = $store->viewFor($user['id']);
30 $profile = $store->profilePayload($user['id']);
23 31 }
24 32 jsonOut([
25 33 'ok' => true,
@@ -35,6 +43,10 @@ try {
35 43 'flight_duration' => METEORS_FLIGHT_DURATION,
36 44 'login_url' => 'auth.php',
37 45 'logout_url' => 'logout.php',
46 'lifetime_points' => $profile['lifetime_points'],
47 'locale' => $profile['locale'],
48 'blocks' => $profile['blocks'],
49 'planets' => $profile['planets'],
38 50 ]);
39 51 }
40 52
@@ -97,6 +109,7 @@ try {
97 109 $eliminated = !empty($body['eliminated']);
98 110 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
99 111 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
112 $profile = $store->profilePayload($userId);
100 113 jsonOut([
101 114 'ok' => true,
102 115 'csrf' => csrfToken(),
@@ -105,8 +118,51 @@ try {
105 118 'incoming' => $view['incoming'],
106 119 'shot_results' => $view['shot_results'],
107 120 'shot_flights' => $view['shot_flights'] ?? [],
121 'lifetime_points' => $profile['lifetime_points'],
122 'locale' => $profile['locale'],
123 'blocks' => $profile['blocks'],
124 'planets' => $profile['planets'],
108 125 ]);
109 126
127 case 'play_begin':
128 $mode = (string) ($body['mode'] ?? 'solo');
129 $ses = $store->playBegin($userId, $mode);
130 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'token' => $ses['token']]);
131
132 case 'play_finish':
133 $token = (string) ($body['token'] ?? '');
134 $score = isset($body['score']) ? (int) $body['score'] : 0;
135 $result = $store->playFinish($userId, $token, $score);
136 jsonOut([
137 'ok' => true,
138 'csrf' => csrfToken(),
139 'lifetime_points' => $result['lifetime_points'],
140 'awarded' => $result['awarded'],
141 'already' => $result['already'],
142 'blocks' => Blocks::present($result['lifetime_points']),
143 ]);
144
145 case 'planet_save':
146 $snap = $store->saveCustomPlanet($userId, is_array($body['planet'] ?? null) ? $body['planet'] : $body);
147 jsonOut([
148 'ok' => true,
149 'csrf' => csrfToken(),
150 'planet' => $snap,
151 'planets' => $store->listCustomPlanets($userId),
152 ]);
153
154 case 'planet_delete':
155 $store->deleteCustomPlanet($userId, (string) ($body['id'] ?? $body['planet_id'] ?? ''));
156 jsonOut([
157 'ok' => true,
158 'csrf' => csrfToken(),
159 'planets' => $store->listCustomPlanets($userId),
160 ]);
161
162 case 'set_locale':
163 $locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
164 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);
165
110 166 default:
111 167 jsonFail('Onbekende actie.', 404);
112 168 }
@@ -18,8 +18,16 @@ try {
18
18
19 if ($action === 'me' || $action === '') {
19 if ($action === 'me' || $action === '') {
20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
21 $profile = [
22 'lifetime_points' => 0,
23 'locale' => null,
24 'blocks' => [],
25 'planets' => [],
26 ];
21 if ($user) {
27 if ($user) {
22 $view = Store::open()->viewFor($user['id']);
28 $store = Store::open();
29 $view = $store->viewFor($user['id']);
30 $profile = $store->profilePayload($user['id']);
23 }
31 }
24 jsonOut([
32 jsonOut([
25 'ok' => true,
33 'ok' => true,
@@ -35,6 +43,10 @@ try {
35 'flight_duration' => METEORS_FLIGHT_DURATION,
43 'flight_duration' => METEORS_FLIGHT_DURATION,
36 'login_url' => 'auth.php',
44 'login_url' => 'auth.php',
37 'logout_url' => 'logout.php',
45 'logout_url' => 'logout.php',
46 'lifetime_points' => $profile['lifetime_points'],
47 'locale' => $profile['locale'],
48 'blocks' => $profile['blocks'],
49 'planets' => $profile['planets'],
38 ]);
50 ]);
39 }
51 }
40
52
@@ -97,6 +109,7 @@ try {
97 $eliminated = !empty($body['eliminated']);
109 $eliminated = !empty($body['eliminated']);
98 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
110 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
99 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
111 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
112 $profile = $store->profilePayload($userId);
100 jsonOut([
113 jsonOut([
101 'ok' => true,
114 'ok' => true,
102 'csrf' => csrfToken(),
115 'csrf' => csrfToken(),
@@ -105,8 +118,51 @@ try {
105 'incoming' => $view['incoming'],
118 'incoming' => $view['incoming'],
106 'shot_results' => $view['shot_results'],
119 'shot_results' => $view['shot_results'],
107 'shot_flights' => $view['shot_flights'] ?? [],
120 'shot_flights' => $view['shot_flights'] ?? [],
121 'lifetime_points' => $profile['lifetime_points'],
122 'locale' => $profile['locale'],
123 'blocks' => $profile['blocks'],
124 'planets' => $profile['planets'],
108 ]);
125 ]);
109
126
127 case 'play_begin':
128 $mode = (string) ($body['mode'] ?? 'solo');
129 $ses = $store->playBegin($userId, $mode);
130 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'token' => $ses['token']]);
131
132 case 'play_finish':
133 $token = (string) ($body['token'] ?? '');
134 $score = isset($body['score']) ? (int) $body['score'] : 0;
135 $result = $store->playFinish($userId, $token, $score);
136 jsonOut([
137 'ok' => true,
138 'csrf' => csrfToken(),
139 'lifetime_points' => $result['lifetime_points'],
140 'awarded' => $result['awarded'],
141 'already' => $result['already'],
142 'blocks' => Blocks::present($result['lifetime_points']),
143 ]);
144
145 case 'planet_save':
146 $snap = $store->saveCustomPlanet($userId, is_array($body['planet'] ?? null) ? $body['planet'] : $body);
147 jsonOut([
148 'ok' => true,
149 'csrf' => csrfToken(),
150 'planet' => $snap,
151 'planets' => $store->listCustomPlanets($userId),
152 ]);
153
154 case 'planet_delete':
155 $store->deleteCustomPlanet($userId, (string) ($body['id'] ?? $body['planet_id'] ?? ''));
156 jsonOut([
157 'ok' => true,
158 'csrf' => csrfToken(),
159 'planets' => $store->listCustomPlanets($userId),
160 ]);
161
162 case 'set_locale':
163 $locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
164 jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);
165
110 default:
166 default:
111 jsonFail('Onbekende actie.', 404);
167 jsonFail('Onbekende actie.', 404);
112 }
168 }
server/lib/Blocks.php added +141 −0
@@ -0,0 +1,141 @@
1 <?php
2 declare(strict_types=1);
3
4 /**
5 * Append-only block registry shared with the JS client (server/lib/blocks.json).
6 * Never reorder entries; new blocks are appended. Thresholds stay in lockstep
7 * with src/blocks.js: Terra's first five are free; index 5 costs 500 lifetime
8 * points, each next index costs 14.5% more (rounded to a strictly increasing int).
9 */
10 final class Blocks
11 {
12 public const TERRA_COUNT = 5;
13 public const FIRST_THRESHOLD = 500;
14 public const GROWTH = 1.145;
15
16 private static ?array $all = null;
17 private static ?array $byId = null;
18
19 public static function path(): string
20 {
21 return __DIR__ . '/blocks.json';
22 }
23
24 /** @return list<array> */
25 public static function all(): array
26 {
27 if (self::$all !== null) {
28 return self::$all;
29 }
30 $raw = file_get_contents(self::path());
31 if ($raw === false) {
32 throw new RuntimeException('blocks.json ontbreekt.');
33 }
34 $data = json_decode($raw, true);
35 if (!is_array($data) || !isset($data['blocks']) || !is_array($data['blocks'])) {
36 throw new RuntimeException('blocks.json is ongeldig.');
37 }
38 self::$all = [];
39 self::$byId = [];
40 foreach ($data['blocks'] as $i => $row) {
41 if (!is_array($row) || empty($row['id'])) {
42 continue;
43 }
44 $row['_index'] = $i;
45 self::$all[] = $row;
46 self::$byId[(string) $row['id']] = $row;
47 }
48 if (count(self::$all) < self::TERRA_COUNT) {
49 throw new RuntimeException('blocks.json mist de Terra-blokjes.');
50 }
51 return self::$all;
52 }
53
54 public static function byId(string $id): ?array
55 {
56 if (self::$byId === null) {
57 self::all();
58 }
59 return self::$byId[$id] ?? null;
60 }
61
62 public static function known(string $id): bool
63 {
64 return self::byId($id) !== null;
65 }
66
67 public static function indexOf(string $id): ?int
68 {
69 $b = self::byId($id);
70 return $b !== null ? (int) $b['_index'] : null;
71 }
72
73 public static function isTerra(string $id): bool
74 {
75 $i = self::indexOf($id);
76 return $i !== null && $i < self::TERRA_COUNT;
77 }
78
79 /** Lifetime points required to unlock the block at $index (0-based). */
80 public static function threshold(int $index): int
81 {
82 if ($index < self::TERRA_COUNT) {
83 return 0;
84 }
85 $t = self::FIRST_THRESHOLD;
86 for ($i = self::TERRA_COUNT; $i < $index; $i++) {
87 $next = (int) round($t * self::GROWTH);
88 $t = max($t + 1, $next);
89 }
90 return $t;
91 }
92
93 public static function unlocked(int $index, int $points): bool
94 {
95 return $points >= self::threshold($index);
96 }
97
98 public static function unlockedId(string $id, int $points): bool
99 {
100 $i = self::indexOf($id);
101 return $i !== null && self::unlocked($i, $points);
102 }
103
104 /** Public list for the client: every block plus its threshold and unlock state. */
105 public static function present(int $points): array
106 {
107 $out = [];
108 foreach (self::all() as $i => $b) {
109 $need = self::threshold($i);
110 $out[] = [
111 'id' => (string) $b['id'],
112 'name' => (string) ($b['name'] ?? $b['id']),
113 'hex' => (string) ($b['hex'] ?? '#888'),
114 'shape' => (string) ($b['shape'] ?? ''),
115 'image' => (string) ($b['image'] ?? ''),
116 'terra' => !empty($b['terra']) || $i < self::TERRA_COUNT,
117 'index' => $i,
118 'threshold' => $need,
119 'unlocked' => $points >= $need,
120 ];
121 }
122 return $out;
123 }
124
125 /** Resolve a registry id to a planet-slot colour (with a 0–4 slot id). */
126 public static function asColor(string $id, int $slot): ?array
127 {
128 $b = self::byId($id);
129 if ($b === null) {
130 return null;
131 }
132 return [
133 'id' => $slot,
134 'block' => (string) $b['id'],
135 'name' => (string) ($b['name'] ?? $b['id']),
136 'hex' => (string) ($b['hex'] ?? '#888'),
137 'shape' => (string) ($b['shape'] ?? ''),
138 'image' => (string) ($b['image'] ?? ''),
139 ];
140 }
141 }
@@ -0,0 +1,141 @@
1<?php
2declare(strict_types=1);
3
4/**
5 * Append-only block registry shared with the JS client (server/lib/blocks.json).
6 * Never reorder entries; new blocks are appended. Thresholds stay in lockstep
7 * with src/blocks.js: Terra's first five are free; index 5 costs 500 lifetime
8 * points, each next index costs 14.5% more (rounded to a strictly increasing int).
9 */
10final class Blocks
11{
12 public const TERRA_COUNT = 5;
13 public const FIRST_THRESHOLD = 500;
14 public const GROWTH = 1.145;
15
16 private static ?array $all = null;
17 private static ?array $byId = null;
18
19 public static function path(): string
20 {
21 return __DIR__ . '/blocks.json';
22 }
23
24 /** @return list<array> */
25 public static function all(): array
26 {
27 if (self::$all !== null) {
28 return self::$all;
29 }
30 $raw = file_get_contents(self::path());
31 if ($raw === false) {
32 throw new RuntimeException('blocks.json ontbreekt.');
33 }
34 $data = json_decode($raw, true);
35 if (!is_array($data) || !isset($data['blocks']) || !is_array($data['blocks'])) {
36 throw new RuntimeException('blocks.json is ongeldig.');
37 }
38 self::$all = [];
39 self::$byId = [];
40 foreach ($data['blocks'] as $i => $row) {
41 if (!is_array($row) || empty($row['id'])) {
42 continue;
43 }
44 $row['_index'] = $i;
45 self::$all[] = $row;
46 self::$byId[(string) $row['id']] = $row;
47 }
48 if (count(self::$all) < self::TERRA_COUNT) {
49 throw new RuntimeException('blocks.json mist de Terra-blokjes.');
50 }
51 return self::$all;
52 }
53
54 public static function byId(string $id): ?array
55 {
56 if (self::$byId === null) {
57 self::all();
58 }
59 return self::$byId[$id] ?? null;
60 }
61
62 public static function known(string $id): bool
63 {
64 return self::byId($id) !== null;
65 }
66
67 public static function indexOf(string $id): ?int
68 {
69 $b = self::byId($id);
70 return $b !== null ? (int) $b['_index'] : null;
71 }
72
73 public static function isTerra(string $id): bool
74 {
75 $i = self::indexOf($id);
76 return $i !== null && $i < self::TERRA_COUNT;
77 }
78
79 /** Lifetime points required to unlock the block at $index (0-based). */
80 public static function threshold(int $index): int
81 {
82 if ($index < self::TERRA_COUNT) {
83 return 0;
84 }
85 $t = self::FIRST_THRESHOLD;
86 for ($i = self::TERRA_COUNT; $i < $index; $i++) {
87 $next = (int) round($t * self::GROWTH);
88 $t = max($t + 1, $next);
89 }
90 return $t;
91 }
92
93 public static function unlocked(int $index, int $points): bool
94 {
95 return $points >= self::threshold($index);
96 }
97
98 public static function unlockedId(string $id, int $points): bool
99 {
100 $i = self::indexOf($id);
101 return $i !== null && self::unlocked($i, $points);
102 }
103
104 /** Public list for the client: every block plus its threshold and unlock state. */
105 public static function present(int $points): array
106 {
107 $out = [];
108 foreach (self::all() as $i => $b) {
109 $need = self::threshold($i);
110 $out[] = [
111 'id' => (string) $b['id'],
112 'name' => (string) ($b['name'] ?? $b['id']),
113 'hex' => (string) ($b['hex'] ?? '#888'),
114 'shape' => (string) ($b['shape'] ?? ''),
115 'image' => (string) ($b['image'] ?? ''),
116 'terra' => !empty($b['terra']) || $i < self::TERRA_COUNT,
117 'index' => $i,
118 'threshold' => $need,
119 'unlocked' => $points >= $need,
120 ];
121 }
122 return $out;
123 }
124
125 /** Resolve a registry id to a planet-slot colour (with a 0–4 slot id). */
126 public static function asColor(string $id, int $slot): ?array
127 {
128 $b = self::byId($id);
129 if ($b === null) {
130 return null;
131 }
132 return [
133 'id' => $slot,
134 'block' => (string) $b['id'],
135 'name' => (string) ($b['name'] ?? $b['id']),
136 'hex' => (string) ($b['hex'] ?? '#888'),
137 'shape' => (string) ($b['shape'] ?? ''),
138 'image' => (string) ($b['image'] ?? ''),
139 ];
140 }
141}
server/lib/Planets.php +33 −0
@@ -149,6 +149,39 @@ final class Planets
149 149 ];
150 150 }
151 151
152 /** Present a raw planet array (catalog or a validated custom snapshot). */
153 public static function presentData(array $p): array
154 {
155 $d = self::displayValues($p);
156 $colors = [];
157 foreach ($p['colors'] ?? [] as $c) {
158 if (!is_array($c)) {
159 continue;
160 }
161 $colors[] = [
162 'id' => (int) ($c['id'] ?? 0),
163 'block' => (string) ($c['block'] ?? $c['name'] ?? ''),
164 'name' => (string) ($c['name'] ?? ''),
165 'hex' => (string) ($c['hex'] ?? '#888'),
166 'shape' => (string) ($c['shape'] ?? ''),
167 'image' => (string) ($c['image'] ?? ''),
168 ];
169 }
170 return [
171 'id' => (string) ($p['id'] ?? ''),
172 'name' => (string) ($p['name'] ?? ''),
173 'people' => (string) ($p['people'] ?? ''),
174 'jumpsToClear' => (float) ($p['jumpsToClear'] ?? 2),
175 'fallTime' => (float) ($p['fallTime'] ?? 3),
176 'riseTime' => (float) ($p['riseTime'] ?? 1.5),
177 'miss_chance' => $d['missChance'],
178 'display' => $d,
179 'colors' => $colors,
180 'custom' => !empty($p['custom']),
181 'owner_id' => isset($p['owner_id']) ? (string) $p['owner_id'] : null,
182 ];
183 }
184
152 185 private static function clamp(float $value, float $lo, float $hi): float
153 186 {
154 187 return max($lo, min($hi, $value));
@@ -149,6 +149,39 @@ final class Planets
149 ];
149 ];
150 }
150 }
151
151
152 /** Present a raw planet array (catalog or a validated custom snapshot). */
153 public static function presentData(array $p): array
154 {
155 $d = self::displayValues($p);
156 $colors = [];
157 foreach ($p['colors'] ?? [] as $c) {
158 if (!is_array($c)) {
159 continue;
160 }
161 $colors[] = [
162 'id' => (int) ($c['id'] ?? 0),
163 'block' => (string) ($c['block'] ?? $c['name'] ?? ''),
164 'name' => (string) ($c['name'] ?? ''),
165 'hex' => (string) ($c['hex'] ?? '#888'),
166 'shape' => (string) ($c['shape'] ?? ''),
167 'image' => (string) ($c['image'] ?? ''),
168 ];
169 }
170 return [
171 'id' => (string) ($p['id'] ?? ''),
172 'name' => (string) ($p['name'] ?? ''),
173 'people' => (string) ($p['people'] ?? ''),
174 'jumpsToClear' => (float) ($p['jumpsToClear'] ?? 2),
175 'fallTime' => (float) ($p['fallTime'] ?? 3),
176 'riseTime' => (float) ($p['riseTime'] ?? 1.5),
177 'miss_chance' => $d['missChance'],
178 'display' => $d,
179 'colors' => $colors,
180 'custom' => !empty($p['custom']),
181 'owner_id' => isset($p['owner_id']) ? (string) $p['owner_id'] : null,
182 ];
183 }
184
152 private static function clamp(float $value, float $lo, float $hi): float
185 private static function clamp(float $value, float $lo, float $hi): float
153 {
186 {
154 return max($lo, min($hi, $value));
187 return max($lo, min($hi, $value));
server/lib/Store.php +408 −15
@@ -2,6 +2,7 @@
2 2 declare(strict_types=1);
3 3
4 4 require_once __DIR__ . '/Planets.php';
5 require_once __DIR__ . '/Blocks.php';
5 6
6 7 final class Store
7 8 {
@@ -74,9 +75,46 @@ CREATE TABLE IF NOT EXISTS shots (
74 75 CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
75 76 SQL);
76 77 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
78 $this->ensureColumn('members', 'planet_json', 'TEXT');
77 79 $this->ensureColumn('shots', 'land_col', 'INTEGER');
78 80 $this->ensureColumn('shots', 'from_col', 'INTEGER');
79 81 $this->ensureColumn('shots', 'from_y', 'REAL');
82 $this->pdo->exec(<<<'SQL'
83 CREATE TABLE IF NOT EXISTS profiles (
84 user_id TEXT PRIMARY KEY,
85 lifetime_points INTEGER NOT NULL DEFAULT 0,
86 locale TEXT,
87 updated INTEGER NOT NULL
88 );
89 CREATE TABLE IF NOT EXISTS point_awards (
90 award_key TEXT PRIMARY KEY,
91 user_id TEXT NOT NULL,
92 mode TEXT NOT NULL,
93 points INTEGER NOT NULL,
94 created INTEGER NOT NULL
95 );
96 CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id);
97 CREATE TABLE IF NOT EXISTS play_sessions (
98 token TEXT PRIMARY KEY,
99 user_id TEXT NOT NULL,
100 mode TEXT NOT NULL,
101 started INTEGER NOT NULL,
102 finished INTEGER
103 );
104 CREATE TABLE IF NOT EXISTS custom_planets (
105 id TEXT PRIMARY KEY,
106 user_id TEXT NOT NULL,
107 name TEXT NOT NULL,
108 people TEXT NOT NULL,
109 jumps_to_clear REAL NOT NULL,
110 fall_time REAL NOT NULL,
111 rise_time REAL NOT NULL,
112 colors TEXT NOT NULL,
113 created INTEGER NOT NULL,
114 updated INTEGER NOT NULL
115 );
116 CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id);
117 SQL);
80 118 }
81 119
82 120 private function ensureColumn(string $table, string $column, string $ddl): void
@@ -111,9 +149,12 @@ SQL);
111 149 }
112 150 }
113 151
152 /** Tests may freeze the clock without sleeping. */
153 public ?int $testNow = null;
154
114 155 private function now(): int
115 156 {
116 return time();
157 return $this->testNow ?? time();
117 158 }
118 159
119 160 private function nowf(): float
@@ -205,11 +246,11 @@ SQL);
205 246 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
206 247 VALUES (?,?,?,?,?,?,?)'
207 248 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
208 $planet = Planets::known($planetId) ? $planetId : Planets::defaultId();
249 $choice = $this->choosePlanet($userId, $planetId, false);
209 250 $this->pdo->prepare(
210 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
211 VALUES (?,?,?,0,?,?,?)'
212 )->execute([$id, $userId, $name, $now, $now, $planet]);
251 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json)
252 VALUES (?,?,?,0,?,?,?,?)'
253 )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
213 254 return $this->getLobby($id);
214 255 });
215 256 }
@@ -236,9 +277,10 @@ SQL);
236 277 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
237 278 }
238 279 $now = $this->now();
280 $choice = $this->choosePlanet($userId, $planetId, false);
239 281 $this->pdo->prepare(
240 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id)
241 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
282 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json)
283 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?)
242 284 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
243 285 name = excluded.name,
244 286 ready = 0,
@@ -249,8 +291,9 @@ SQL);
249 291 last_seen = excluded.last_seen,
250 292 score = 0,
251 293 snapshot = NULL,
252 planet_id = excluded.planet_id'
253 )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
294 planet_id = excluded.planet_id,
295 planet_json = excluded.planet_json'
296 )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
254 297 return $this->getLobby($lobby['id']);
255 298 });
256 299 }
@@ -352,12 +395,10 @@ SQL);
352 395 if ($lobby['status'] !== 'waiting') {
353 396 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
354 397 }
355 if (!Planets::known($planetId)) {
356 throw new RuntimeException('Onbekende planeet.');
357 }
398 $choice = $this->choosePlanet($userId, $planetId, true);
358 399 $this->pdo->prepare(
359 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
360 )->execute([$planetId, $this->now(), $lobby['id'], $userId]);
400 'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
401 )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]);
361 402 return $this->getLobby($lobby['id']);
362 403 });
363 404 }
@@ -368,6 +409,12 @@ SQL);
368 409 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
369 410 return max(0.0, min(1.0, $this->testMissOverride));
370 411 }
412 if (!empty($member['planet_json'])) {
413 $data = json_decode((string) $member['planet_json'], true);
414 if (is_array($data)) {
415 return Planets::missChance($data);
416 }
417 }
371 418 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
372 419 return Planets::missChanceForId($id);
373 420 }
@@ -662,6 +709,7 @@ SQL);
662 709 if ($lobby['status'] === 'playing') {
663 710 $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
664 711 }
712 $this->maybeAwardOnlineLobby($lobby);
665 713 return [
666 714 'lobby' => $this->presentLobby($lobby, $userId),
667 715 'incoming' => $incoming,
@@ -691,7 +739,7 @@ SQL);
691 739 'is_me' => $m['user_id'] === $userId,
692 740 'score' => (int) $m['score'],
693 741 'snapshot' => $m['user_id'] === $userId ? null : $snap,
694 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())),
742 'planet' => $this->presentMemberPlanet($m),
695 743 ];
696 744 }
697 745 $rankings = [];
@@ -725,4 +773,349 @@ SQL);
725 773 'podium_seconds' => METEORS_PODIUM_SECONDS,
726 774 ];
727 775 }
776
777 public const MAX_CUSTOM_PLANETS = 30;
778 public const MAX_GAME_POINTS = 10000;
779 public const MAX_POINTS_PER_SEC = 4.0;
780 public const MIN_PLAY_SECONDS = 3;
781 public const PLAY_TOKEN_TTL = 21600;
782 public const NAME_MAX = 32;
783
784 /** @return array{planet_id:string,planet_json:?string} */
785 public function choosePlanet(string $userId, string $planetId, bool $strict): array
786 {
787 if ($planetId === '') {
788 if ($strict) {
789 throw new RuntimeException('Onbekende planeet.');
790 }
791 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
792 }
793 if (Planets::known($planetId)) {
794 return ['planet_id' => $planetId, 'planet_json' => null];
795 }
796 $row = $this->ownedCustom($userId, $planetId);
797 if ($row) {
798 return [
799 'planet_id' => $planetId,
800 'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE),
801 ];
802 }
803 if ($strict) {
804 throw new RuntimeException('Onbekende planeet.');
805 }
806 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
807 }
808
809 /** @param array<string,mixed> $member */
810 public function presentMemberPlanet(array $member): array
811 {
812 if (!empty($member['planet_json'])) {
813 $data = json_decode((string) $member['planet_json'], true);
814 if (is_array($data) && !empty($data['id'])) {
815 return Planets::presentData($data);
816 }
817 }
818 return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId()));
819 }
820
821 public function ensureProfile(string $userId): array
822 {
823 $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
824 $stmt->execute([$userId]);
825 $row = $stmt->fetch();
826 if ($row) {
827 return $row;
828 }
829 $now = $this->now();
830 $this->pdo->prepare(
831 'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)'
832 )->execute([$userId, $now]);
833 return [
834 'user_id' => $userId,
835 'lifetime_points' => 0,
836 'locale' => null,
837 'updated' => $now,
838 ];
839 }
840
841 public function lifetimePoints(string $userId): int
842 {
843 return (int) $this->ensureProfile($userId)['lifetime_points'];
844 }
845
846 public function locale(string $userId): ?string
847 {
848 $v = $this->ensureProfile($userId)['locale'] ?? null;
849 return is_string($v) && $v !== '' ? $v : null;
850 }
851
852 /** @var list<string> */
853 public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
854
855 public function setLocale(string $userId, string $locale): string
856 {
857 $locale = strtolower($locale);
858 if (!in_array($locale, self::LOCALES, true)) {
859 throw new RuntimeException('Onbekende taal.');
860 }
861 $this->ensureProfile($userId);
862 $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
863 ->execute([$locale, $this->now(), $userId]);
864 return $locale;
865 }
866
867 /**
868 * Add points once for a unique award_key. Returns the new lifetime total.
869 * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op.
870 */
871 public function awardPoints(string $userId, int $points, string $key, string $mode): int
872 {
873 return $this->transaction(function () use ($userId, $points, $key, $mode) {
874 $this->ensureProfile($userId);
875 $points = max(0, min(self::MAX_GAME_POINTS, $points));
876 $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
877 $stmt->execute([$key]);
878 if ($stmt->fetch()) {
879 return $this->lifetimePoints($userId);
880 }
881 $this->pdo->prepare(
882 'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)'
883 )->execute([$key, $userId, $mode, $points, $this->now()]);
884 if ($points > 0) {
885 $this->pdo->prepare(
886 'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?'
887 )->execute([$points, $this->now(), $userId]);
888 }
889 return $this->lifetimePoints($userId);
890 });
891 }
892
893 public function playBegin(string $userId, string $mode): array
894 {
895 if (!in_array($mode, ['solo', 'offline'], true)) {
896 throw new RuntimeException('Onbekende speelmodus.');
897 }
898 $token = bin2hex(random_bytes(16));
899 $this->pdo->prepare(
900 'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)'
901 )->execute([$token, $userId, $mode, $this->now()]);
902 return ['token' => $token, 'started' => $this->now()];
903 }
904
905 public function playFinish(string $userId, string $token, int $score): array
906 {
907 return $this->transaction(function () use ($userId, $token, $score) {
908 $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?');
909 $stmt->execute([$token]);
910 $ses = $stmt->fetch();
911 if (!$ses || $ses['user_id'] !== $userId) {
912 throw new RuntimeException('Ongeldige speelsessie.');
913 }
914 $key = 'play:' . $token;
915 if ($ses['finished'] !== null) {
916 return [
917 'lifetime_points' => $this->lifetimePoints($userId),
918 'awarded' => 0,
919 'already' => true,
920 ];
921 }
922 $now = $this->now();
923 $started = (int) $ses['started'];
924 if ($now - $started > self::PLAY_TOKEN_TTL) {
925 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
926 ->execute([$now, $token]);
927 throw new RuntimeException('Speelsessie is verlopen.');
928 }
929 $duration = max(0, $now - $started);
930 $score = max(0, $score);
931 $awarded = 0;
932 if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) {
933 $awarded = 0;
934 } else {
935 $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC);
936 $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0)));
937 }
938 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
939 ->execute([$now, $token]);
940 $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']);
941 return [
942 'lifetime_points' => $total,
943 'awarded' => $awarded,
944 'already' => false,
945 ];
946 });
947 }
948
949 /** @param array<string,mixed> $lobby */
950 public function maybeAwardOnlineLobby(array $lobby): void
951 {
952 $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
953 foreach ($this->members($lobby['id'], true) as $m) {
954 if (!$finished && empty($m['eliminated'])) {
955 continue;
956 }
957 $uid = (string) $m['user_id'];
958 $key = 'online:' . $lobby['id'] . ':' . $uid;
959 $this->awardPoints($uid, (int) $m['score'], $key, 'online');
960 }
961 }
962
963 /** @return ?array<string,mixed> */
964 public function ownedCustom(string $userId, string $id): ?array
965 {
966 $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?');
967 $stmt->execute([$id, $userId]);
968 $row = $stmt->fetch();
969 return $row ?: null;
970 }
971
972 /** @return list<array<string,mixed>> */
973 public function listCustomPlanets(string $userId): array
974 {
975 $stmt = $this->pdo->prepare(
976 'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC'
977 );
978 $stmt->execute([$userId]);
979 $out = [];
980 foreach ($stmt->fetchAll() as $row) {
981 $out[] = $this->snapshotCustom($row);
982 }
983 return $out;
984 }
985
986 public static function sanitizeName(string $raw, string $field): string
987 {
988 $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? '');
989 $s = strip_tags($s);
990 if ($s === '') {
991 throw new RuntimeException('Vul een ' . $field . ' in.');
992 }
993 if (mb_strlen($s) > self::NAME_MAX) {
994 $s = mb_substr($s, 0, self::NAME_MAX);
995 }
996 return $s;
997 }
998
999 /**
1000 * Create or update a custom planet owned by $userId.
1001 * @param array<string,mixed> $data
1002 * @return array<string,mixed> snapshot
1003 */
1004 public function saveCustomPlanet(string $userId, array $data): array
1005 {
1006 return $this->transaction(function () use ($userId, $data) {
1007 $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam');
1008 $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam');
1009 $j = self::clampFloat((float) ($data['jumpsToClear'] ?? 2), 1, 4);
1010 $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5);
1011 $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3);
1012 $ids = $data['colors'] ?? $data['blocks'] ?? [];
1013 if (!is_array($ids) || count($ids) !== 5) {
1014 throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.');
1015 }
1016 $points = $this->lifetimePoints($userId);
1017 $blockIds = [];
1018 foreach ($ids as $entry) {
1019 if (is_array($entry)) {
1020 $bid = (string) ($entry['block'] ?? $entry['id'] ?? '');
1021 } else {
1022 $bid = (string) $entry;
1023 }
1024 if ($bid === '' || !Blocks::known($bid)) {
1025 throw new RuntimeException('Onbekend blokje.');
1026 }
1027 if (!Blocks::unlockedId($bid, $points)) {
1028 throw new RuntimeException('Dit blokje is nog niet ontgrendeld.');
1029 }
1030 if (in_array($bid, $blockIds, true)) {
1031 throw new RuntimeException('Elk blokje mag maar in één vak.');
1032 }
1033 $blockIds[] = $bid;
1034 }
1035 $now = $this->now();
1036 $id = isset($data['id']) ? (string) $data['id'] : '';
1037 if ($id !== '') {
1038 $row = $this->ownedCustom($userId, $id);
1039 if (!$row) {
1040 throw new RuntimeException('Onbekende planeet.');
1041 }
1042 $this->pdo->prepare(
1043 'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?'
1044 )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]);
1045 } else {
1046 $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?');
1047 $stmt->execute([$userId]);
1048 if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) {
1049 throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.');
1050 }
1051 $id = 'c_' . bin2hex(random_bytes(8));
1052 $this->pdo->prepare(
1053 'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated)
1054 VALUES (?,?,?,?,?,?,?,?,?,?)'
1055 )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]);
1056 }
1057 $row = $this->ownedCustom($userId, $id);
1058 if (!$row) {
1059 throw new RuntimeException('Opslaan is mislukt.');
1060 }
1061 return $this->snapshotCustom($row);
1062 });
1063 }
1064
1065 public function deleteCustomPlanet(string $userId, string $id): void
1066 {
1067 $row = $this->ownedCustom($userId, $id);
1068 if (!$row) {
1069 throw new RuntimeException('Onbekende planeet.');
1070 }
1071 $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?')
1072 ->execute([$id, $userId]);
1073 }
1074
1075 /** @param array<string,mixed> $row */
1076 public function snapshotCustom(array $row): array
1077 {
1078 $ids = json_decode((string) $row['colors'], true);
1079 if (!is_array($ids)) {
1080 $ids = [];
1081 }
1082 $colors = [];
1083 foreach ($ids as $i => $id) {
1084 $c = Blocks::asColor((string) $id, (int) $i);
1085 if ($c === null) {
1086 continue;
1087 }
1088 $colors[] = $c;
1089 }
1090 $p = [
1091 'id' => (string) $row['id'],
1092 'name' => (string) $row['name'],
1093 'people' => (string) $row['people'],
1094 'jumpsToClear' => (float) $row['jumps_to_clear'],
1095 'fallTime' => (float) $row['fall_time'],
1096 'riseTime' => (float) $row['rise_time'],
1097 'colors' => $colors,
1098 'custom' => true,
1099 'owner_id' => (string) $row['user_id'],
1100 ];
1101 return Planets::presentData($p);
1102 }
1103
1104 public function profilePayload(string $userId): array
1105 {
1106 $points = $this->lifetimePoints($userId);
1107 return [
1108 'lifetime_points' => $points,
1109 'locale' => $this->locale($userId),
1110 'blocks' => Blocks::present($points),
1111 'planets' => $this->listCustomPlanets($userId),
1112 ];
1113 }
1114
1115 private static function clampFloat(float $value, float $lo, float $hi): float
1116 {
1117 return max($lo, min($hi, $value));
1118 }
1119
1120
728 1121 }
@@ -2,6 +2,7 @@
2declare(strict_types=1);
2declare(strict_types=1);
3
3
4require_once __DIR__ . '/Planets.php';
4require_once __DIR__ . '/Planets.php';
5require_once __DIR__ . '/Blocks.php';
5
6
6final class Store
7final class Store
7{
8{
@@ -74,9 +75,46 @@ CREATE TABLE IF NOT EXISTS shots (
74CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
75CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
75SQL);
76SQL);
76 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
77 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
78 $this->ensureColumn('members', 'planet_json', 'TEXT');
77 $this->ensureColumn('shots', 'land_col', 'INTEGER');
79 $this->ensureColumn('shots', 'land_col', 'INTEGER');
78 $this->ensureColumn('shots', 'from_col', 'INTEGER');
80 $this->ensureColumn('shots', 'from_col', 'INTEGER');
79 $this->ensureColumn('shots', 'from_y', 'REAL');
81 $this->ensureColumn('shots', 'from_y', 'REAL');
82 $this->pdo->exec(<<<'SQL'
83CREATE TABLE IF NOT EXISTS profiles (
84 user_id TEXT PRIMARY KEY,
85 lifetime_points INTEGER NOT NULL DEFAULT 0,
86 locale TEXT,
87 updated INTEGER NOT NULL
88);
89CREATE TABLE IF NOT EXISTS point_awards (
90 award_key TEXT PRIMARY KEY,
91 user_id TEXT NOT NULL,
92 mode TEXT NOT NULL,
93 points INTEGER NOT NULL,
94 created INTEGER NOT NULL
95);
96CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id);
97CREATE TABLE IF NOT EXISTS play_sessions (
98 token TEXT PRIMARY KEY,
99 user_id TEXT NOT NULL,
100 mode TEXT NOT NULL,
101 started INTEGER NOT NULL,
102 finished INTEGER
103);
104CREATE TABLE IF NOT EXISTS custom_planets (
105 id TEXT PRIMARY KEY,
106 user_id TEXT NOT NULL,
107 name TEXT NOT NULL,
108 people TEXT NOT NULL,
109 jumps_to_clear REAL NOT NULL,
110 fall_time REAL NOT NULL,
111 rise_time REAL NOT NULL,
112 colors TEXT NOT NULL,
113 created INTEGER NOT NULL,
114 updated INTEGER NOT NULL
115);
116CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id);
117SQL);
80 }
118 }
81
119
82 private function ensureColumn(string $table, string $column, string $ddl): void
120 private function ensureColumn(string $table, string $column, string $ddl): void
@@ -111,9 +149,12 @@ SQL);
111 }
149 }
112 }
150 }
113
151
152 /** Tests may freeze the clock without sleeping. */
153 public ?int $testNow = null;
154
114 private function now(): int
155 private function now(): int
115 {
156 {
116 return time();
157 return $this->testNow ?? time();
117 }
158 }
118
159
119 private function nowf(): float
160 private function nowf(): float
@@ -205,11 +246,11 @@ SQL);
205 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
246 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
206 VALUES (?,?,?,?,?,?,?)'
247 VALUES (?,?,?,?,?,?,?)'
207 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
248 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
208 $planet = Planets::known($planetId) ? $planetId : Planets::defaultId();
249 $choice = $this->choosePlanet($userId, $planetId, false);
209 $this->pdo->prepare(
250 $this->pdo->prepare(
210 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
251 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json)
211 VALUES (?,?,?,0,?,?,?)'
252 VALUES (?,?,?,0,?,?,?,?)'
212 )->execute([$id, $userId, $name, $now, $now, $planet]);
253 )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
213 return $this->getLobby($id);
254 return $this->getLobby($id);
214 });
255 });
215 }
256 }
@@ -236,9 +277,10 @@ SQL);
236 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
277 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
237 }
278 }
238 $now = $this->now();
279 $now = $this->now();
280 $choice = $this->choosePlanet($userId, $planetId, false);
239 $this->pdo->prepare(
281 $this->pdo->prepare(
240 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id)
282 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json)
241 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
283 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?)
242 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
284 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
243 name = excluded.name,
285 name = excluded.name,
244 ready = 0,
286 ready = 0,
@@ -249,8 +291,9 @@ SQL);
249 last_seen = excluded.last_seen,
291 last_seen = excluded.last_seen,
250 score = 0,
292 score = 0,
251 snapshot = NULL,
293 snapshot = NULL,
252 planet_id = excluded.planet_id'
294 planet_id = excluded.planet_id,
253 )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
295 planet_json = excluded.planet_json'
296 )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
254 return $this->getLobby($lobby['id']);
297 return $this->getLobby($lobby['id']);
255 });
298 });
256 }
299 }
@@ -352,12 +395,10 @@ SQL);
352 if ($lobby['status'] !== 'waiting') {
395 if ($lobby['status'] !== 'waiting') {
353 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
396 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
354 }
397 }
355 if (!Planets::known($planetId)) {
398 $choice = $this->choosePlanet($userId, $planetId, true);
356 throw new RuntimeException('Onbekende planeet.');
357 }
358 $this->pdo->prepare(
399 $this->pdo->prepare(
359 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
400 'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
360 )->execute([$planetId, $this->now(), $lobby['id'], $userId]);
401 )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]);
361 return $this->getLobby($lobby['id']);
402 return $this->getLobby($lobby['id']);
362 });
403 });
363 }
404 }
@@ -368,6 +409,12 @@ SQL);
368 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
409 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
369 return max(0.0, min(1.0, $this->testMissOverride));
410 return max(0.0, min(1.0, $this->testMissOverride));
370 }
411 }
412 if (!empty($member['planet_json'])) {
413 $data = json_decode((string) $member['planet_json'], true);
414 if (is_array($data)) {
415 return Planets::missChance($data);
416 }
417 }
371 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
418 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
372 return Planets::missChanceForId($id);
419 return Planets::missChanceForId($id);
373 }
420 }
@@ -662,6 +709,7 @@ SQL);
662 if ($lobby['status'] === 'playing') {
709 if ($lobby['status'] === 'playing') {
663 $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
710 $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
664 }
711 }
712 $this->maybeAwardOnlineLobby($lobby);
665 return [
713 return [
666 'lobby' => $this->presentLobby($lobby, $userId),
714 'lobby' => $this->presentLobby($lobby, $userId),
667 'incoming' => $incoming,
715 'incoming' => $incoming,
@@ -691,7 +739,7 @@ SQL);
691 'is_me' => $m['user_id'] === $userId,
739 'is_me' => $m['user_id'] === $userId,
692 'score' => (int) $m['score'],
740 'score' => (int) $m['score'],
693 'snapshot' => $m['user_id'] === $userId ? null : $snap,
741 'snapshot' => $m['user_id'] === $userId ? null : $snap,
694 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())),
742 'planet' => $this->presentMemberPlanet($m),
695 ];
743 ];
696 }
744 }
697 $rankings = [];
745 $rankings = [];
@@ -725,4 +773,349 @@ SQL);
725 'podium_seconds' => METEORS_PODIUM_SECONDS,
773 'podium_seconds' => METEORS_PODIUM_SECONDS,
726 ];
774 ];
727 }
775 }
776
777 public const MAX_CUSTOM_PLANETS = 30;
778 public const MAX_GAME_POINTS = 10000;
779 public const MAX_POINTS_PER_SEC = 4.0;
780 public const MIN_PLAY_SECONDS = 3;
781 public const PLAY_TOKEN_TTL = 21600;
782 public const NAME_MAX = 32;
783
784 /** @return array{planet_id:string,planet_json:?string} */
785 public function choosePlanet(string $userId, string $planetId, bool $strict): array
786 {
787 if ($planetId === '') {
788 if ($strict) {
789 throw new RuntimeException('Onbekende planeet.');
790 }
791 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
792 }
793 if (Planets::known($planetId)) {
794 return ['planet_id' => $planetId, 'planet_json' => null];
795 }
796 $row = $this->ownedCustom($userId, $planetId);
797 if ($row) {
798 return [
799 'planet_id' => $planetId,
800 'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE),
801 ];
802 }
803 if ($strict) {
804 throw new RuntimeException('Onbekende planeet.');
805 }
806 return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
807 }
808
809 /** @param array<string,mixed> $member */
810 public function presentMemberPlanet(array $member): array
811 {
812 if (!empty($member['planet_json'])) {
813 $data = json_decode((string) $member['planet_json'], true);
814 if (is_array($data) && !empty($data['id'])) {
815 return Planets::presentData($data);
816 }
817 }
818 return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId()));
819 }
820
821 public function ensureProfile(string $userId): array
822 {
823 $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
824 $stmt->execute([$userId]);
825 $row = $stmt->fetch();
826 if ($row) {
827 return $row;
828 }
829 $now = $this->now();
830 $this->pdo->prepare(
831 'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)'
832 )->execute([$userId, $now]);
833 return [
834 'user_id' => $userId,
835 'lifetime_points' => 0,
836 'locale' => null,
837 'updated' => $now,
838 ];
839 }
840
841 public function lifetimePoints(string $userId): int
842 {
843 return (int) $this->ensureProfile($userId)['lifetime_points'];
844 }
845
846 public function locale(string $userId): ?string
847 {
848 $v = $this->ensureProfile($userId)['locale'] ?? null;
849 return is_string($v) && $v !== '' ? $v : null;
850 }
851
852 /** @var list<string> */
853 public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
854
855 public function setLocale(string $userId, string $locale): string
856 {
857 $locale = strtolower($locale);
858 if (!in_array($locale, self::LOCALES, true)) {
859 throw new RuntimeException('Onbekende taal.');
860 }
861 $this->ensureProfile($userId);
862 $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
863 ->execute([$locale, $this->now(), $userId]);
864 return $locale;
865 }
866
867 /**
868 * Add points once for a unique award_key. Returns the new lifetime total.
869 * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op.
870 */
871 public function awardPoints(string $userId, int $points, string $key, string $mode): int
872 {
873 return $this->transaction(function () use ($userId, $points, $key, $mode) {
874 $this->ensureProfile($userId);
875 $points = max(0, min(self::MAX_GAME_POINTS, $points));
876 $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
877 $stmt->execute([$key]);
878 if ($stmt->fetch()) {
879 return $this->lifetimePoints($userId);
880 }
881 $this->pdo->prepare(
882 'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)'
883 )->execute([$key, $userId, $mode, $points, $this->now()]);
884 if ($points > 0) {
885 $this->pdo->prepare(
886 'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?'
887 )->execute([$points, $this->now(), $userId]);
888 }
889 return $this->lifetimePoints($userId);
890 });
891 }
892
893 public function playBegin(string $userId, string $mode): array
894 {
895 if (!in_array($mode, ['solo', 'offline'], true)) {
896 throw new RuntimeException('Onbekende speelmodus.');
897 }
898 $token = bin2hex(random_bytes(16));
899 $this->pdo->prepare(
900 'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)'
901 )->execute([$token, $userId, $mode, $this->now()]);
902 return ['token' => $token, 'started' => $this->now()];
903 }
904
905 public function playFinish(string $userId, string $token, int $score): array
906 {
907 return $this->transaction(function () use ($userId, $token, $score) {
908 $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?');
909 $stmt->execute([$token]);
910 $ses = $stmt->fetch();
911 if (!$ses || $ses['user_id'] !== $userId) {
912 throw new RuntimeException('Ongeldige speelsessie.');
913 }
914 $key = 'play:' . $token;
915 if ($ses['finished'] !== null) {
916 return [
917 'lifetime_points' => $this->lifetimePoints($userId),
918 'awarded' => 0,
919 'already' => true,
920 ];
921 }
922 $now = $this->now();
923 $started = (int) $ses['started'];
924 if ($now - $started > self::PLAY_TOKEN_TTL) {
925 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
926 ->execute([$now, $token]);
927 throw new RuntimeException('Speelsessie is verlopen.');
928 }
929 $duration = max(0, $now - $started);
930 $score = max(0, $score);
931 $awarded = 0;
932 if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) {
933 $awarded = 0;
934 } else {
935 $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC);
936 $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0)));
937 }
938 $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
939 ->execute([$now, $token]);
940 $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']);
941 return [
942 'lifetime_points' => $total,
943 'awarded' => $awarded,
944 'already' => false,
945 ];
946 });
947 }
948
949 /** @param array<string,mixed> $lobby */
950 public function maybeAwardOnlineLobby(array $lobby): void
951 {
952 $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
953 foreach ($this->members($lobby['id'], true) as $m) {
954 if (!$finished && empty($m['eliminated'])) {
955 continue;
956 }
957 $uid = (string) $m['user_id'];
958 $key = 'online:' . $lobby['id'] . ':' . $uid;
959 $this->awardPoints($uid, (int) $m['score'], $key, 'online');
960 }
961 }
962
963 /** @return ?array<string,mixed> */
964 public function ownedCustom(string $userId, string $id): ?array
965 {
966 $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?');
967 $stmt->execute([$id, $userId]);
968 $row = $stmt->fetch();
969 return $row ?: null;
970 }
971
972 /** @return list<array<string,mixed>> */
973 public function listCustomPlanets(string $userId): array
974 {
975 $stmt = $this->pdo->prepare(
976 'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC'
977 );
978 $stmt->execute([$userId]);
979 $out = [];
980 foreach ($stmt->fetchAll() as $row) {
981 $out[] = $this->snapshotCustom($row);
982 }
983 return $out;
984 }
985
986 public static function sanitizeName(string $raw, string $field): string
987 {
988 $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? '');
989 $s = strip_tags($s);
990 if ($s === '') {
991 throw new RuntimeException('Vul een ' . $field . ' in.');
992 }
993 if (mb_strlen($s) > self::NAME_MAX) {
994 $s = mb_substr($s, 0, self::NAME_MAX);
995 }
996 return $s;
997 }
998
999 /**
1000 * Create or update a custom planet owned by $userId.
1001 * @param array<string,mixed> $data
1002 * @return array<string,mixed> snapshot
1003 */
1004 public function saveCustomPlanet(string $userId, array $data): array
1005 {
1006 return $this->transaction(function () use ($userId, $data) {
1007 $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam');
1008 $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam');
1009 $j = self::clampFloat((float) ($data['jumpsToClear'] ?? 2), 1, 4);
1010 $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5);
1011 $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3);
1012 $ids = $data['colors'] ?? $data['blocks'] ?? [];
1013 if (!is_array($ids) || count($ids) !== 5) {
1014 throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.');
1015 }
1016 $points = $this->lifetimePoints($userId);
1017 $blockIds = [];
1018 foreach ($ids as $entry) {
1019 if (is_array($entry)) {
1020 $bid = (string) ($entry['block'] ?? $entry['id'] ?? '');
1021 } else {
1022 $bid = (string) $entry;
1023 }
1024 if ($bid === '' || !Blocks::known($bid)) {
1025 throw new RuntimeException('Onbekend blokje.');
1026 }
1027 if (!Blocks::unlockedId($bid, $points)) {
1028 throw new RuntimeException('Dit blokje is nog niet ontgrendeld.');
1029 }
1030 if (in_array($bid, $blockIds, true)) {
1031 throw new RuntimeException('Elk blokje mag maar in één vak.');
1032 }
1033 $blockIds[] = $bid;
1034 }
1035 $now = $this->now();
1036 $id = isset($data['id']) ? (string) $data['id'] : '';
1037 if ($id !== '') {
1038 $row = $this->ownedCustom($userId, $id);
1039 if (!$row) {
1040 throw new RuntimeException('Onbekende planeet.');
1041 }
1042 $this->pdo->prepare(
1043 'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?'
1044 )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]);
1045 } else {
1046 $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?');
1047 $stmt->execute([$userId]);
1048 if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) {
1049 throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.');
1050 }
1051 $id = 'c_' . bin2hex(random_bytes(8));
1052 $this->pdo->prepare(
1053 'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated)
1054 VALUES (?,?,?,?,?,?,?,?,?,?)'
1055 )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]);
1056 }
1057 $row = $this->ownedCustom($userId, $id);
1058 if (!$row) {
1059 throw new RuntimeException('Opslaan is mislukt.');
1060 }
1061 return $this->snapshotCustom($row);
1062 });
1063 }
1064
1065 public function deleteCustomPlanet(string $userId, string $id): void
1066 {
1067 $row = $this->ownedCustom($userId, $id);
1068 if (!$row) {
1069 throw new RuntimeException('Onbekende planeet.');
1070 }
1071 $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?')
1072 ->execute([$id, $userId]);
1073 }
1074
1075 /** @param array<string,mixed> $row */
1076 public function snapshotCustom(array $row): array
1077 {
1078 $ids = json_decode((string) $row['colors'], true);
1079 if (!is_array($ids)) {
1080 $ids = [];
1081 }
1082 $colors = [];
1083 foreach ($ids as $i => $id) {
1084 $c = Blocks::asColor((string) $id, (int) $i);
1085 if ($c === null) {
1086 continue;
1087 }
1088 $colors[] = $c;
1089 }
1090 $p = [
1091 'id' => (string) $row['id'],
1092 'name' => (string) $row['name'],
1093 'people' => (string) $row['people'],
1094 'jumpsToClear' => (float) $row['jumps_to_clear'],
1095 'fallTime' => (float) $row['fall_time'],
1096 'riseTime' => (float) $row['rise_time'],
1097 'colors' => $colors,
1098 'custom' => true,
1099 'owner_id' => (string) $row['user_id'],
1100 ];
1101 return Planets::presentData($p);
1102 }
1103
1104 public function profilePayload(string $userId): array
1105 {
1106 $points = $this->lifetimePoints($userId);
1107 return [
1108 'lifetime_points' => $points,
1109 'locale' => $this->locale($userId),
1110 'blocks' => Blocks::present($points),
1111 'planets' => $this->listCustomPlanets($userId),
1112 ];
1113 }
1114
1115 private static function clampFloat(float $value, float $lo, float $hi): float
1116 {
1117 return max($lo, min($hi, $value));
1118 }
1119
1120
728}
1121}
server/lib/blocks.json added +832 −0
@@ -0,0 +1,832 @@
1 {
2 "_comment": "Append-only block registry. Never reorder, rename ids, or insert in the middle. New blocks go at the end. The first five (Terra) are unlocked by default; index 5 requires 500 lifetime points, each next index requires 14.5% more (rounded).",
3 "terraCount": 5,
4 "firstThreshold": 500,
5 "thresholdGrowth": 1.145,
6 "blocks": [
7 {
8 "id": "terra-ember",
9 "name": "Ember",
10 "hex": "#e85d3a",
11 "shape": "triangle",
12 "image": "images/block-terra-ember.png",
13 "terra": true
14 },
15 {
16 "id": "terra-aqua",
17 "name": "Aqua",
18 "hex": "#3db8e8",
19 "shape": "circle",
20 "image": "images/block-terra-aqua.png",
21 "terra": true
22 },
23 {
24 "id": "terra-leaf",
25 "name": "Leaf",
26 "hex": "#4cbf4c",
27 "shape": "square",
28 "image": "images/block-terra-leaf.png",
29 "terra": true
30 },
31 {
32 "id": "terra-sun",
33 "name": "Sun",
34 "hex": "#f0c53a",
35 "shape": "diamond",
36 "image": "images/block-terra-sun.png",
37 "terra": true
38 },
39 {
40 "id": "terra-orchid",
41 "name": "Orchid",
42 "hex": "#c45ad4",
43 "shape": "star",
44 "image": "images/block-terra-orchid.png",
45 "terra": true
46 },
47 {
48 "id": "rune-fehu",
49 "name": "Fehu",
50 "hex": "#e8a44a",
51 "shape": "rune_fehu",
52 "image": "images/block-rune-fehu.png",
53 "terra": false
54 },
55 {
56 "id": "rune-ansuz",
57 "name": "Ansuz",
58 "hex": "#6ab0e8",
59 "shape": "rune_ansuz",
60 "image": "images/block-rune-ansuz.png",
61 "terra": false
62 },
63 {
64 "id": "rune-thurisaz",
65 "name": "Thurisaz",
66 "hex": "#c05040",
67 "shape": "rune_thurisaz",
68 "image": "images/block-rune-thurisaz.png",
69 "terra": false
70 },
71 {
72 "id": "rune-raido",
73 "name": "Raido",
74 "hex": "#d0c070",
75 "shape": "rune_raido",
76 "image": "images/block-rune-raido.png",
77 "terra": false
78 },
79 {
80 "id": "rune-sowilo",
81 "name": "Sowilo",
82 "hex": "#f0d040",
83 "shape": "rune_sowilo",
84 "image": "images/block-rune-sowilo.png",
85 "terra": false
86 },
87 {
88 "id": "rune-algiz",
89 "name": "Algiz",
90 "hex": "#80d0a0",
91 "shape": "rune_algiz",
92 "image": "images/block-rune-algiz.png",
93 "terra": false
94 },
95 {
96 "id": "arrow-up",
97 "name": "Arrow",
98 "hex": "#f07040",
99 "shape": "arrow",
100 "image": "images/block-arrow-up.png",
101 "terra": false
102 },
103 {
104 "id": "arrow-chevron",
105 "name": "Chevron",
106 "hex": "#50c0e0",
107 "shape": "chevron",
108 "image": "images/block-arrow-chevron.png",
109 "terra": false
110 },
111 {
112 "id": "arrow-double",
113 "name": "Double Arrow",
114 "hex": "#e05080",
115 "shape": "double_arrow",
116 "image": "images/block-arrow-double.png",
117 "terra": false
118 },
119 {
120 "id": "arrow-return",
121 "name": "Return",
122 "hex": "#a080e0",
123 "shape": "return_arrow",
124 "image": "images/block-arrow-return.png",
125 "terra": false
126 },
127 {
128 "id": "fig-person",
129 "name": "Figure",
130 "hex": "#f0c0a0",
131 "shape": "person",
132 "image": "images/block-fig-person.png",
133 "terra": false
134 },
135 {
136 "id": "fig-walker",
137 "name": "Walker",
138 "hex": "#c09070",
139 "shape": "walker",
140 "image": "images/block-fig-walker.png",
141 "terra": false
142 },
143 {
144 "id": "fig-hero",
145 "name": "Hero",
146 "hex": "#e8b070",
147 "shape": "hero",
148 "image": "images/block-fig-hero.png",
149 "terra": false
150 },
151 {
152 "id": "face-smile",
153 "name": "Smile",
154 "hex": "#f0d060",
155 "shape": "smile",
156 "image": "images/block-face-smile.png",
157 "terra": false
158 },
159 {
160 "id": "face-wink",
161 "name": "Wink",
162 "hex": "#f0a050",
163 "shape": "wink",
164 "image": "images/block-face-wink.png",
165 "terra": false
166 },
167 {
168 "id": "face-cool",
169 "name": "Cool",
170 "hex": "#6090d0",
171 "shape": "cool",
172 "image": "images/block-face-cool.png",
173 "terra": false
174 },
175 {
176 "id": "face-grin",
177 "name": "Grin",
178 "hex": "#f0c848",
179 "shape": "grin",
180 "image": "images/block-face-grin.png",
181 "terra": false
182 },
183 {
184 "id": "icon-heart",
185 "name": "Heart",
186 "hex": "#e04060",
187 "shape": "heart",
188 "image": "images/block-icon-heart.png",
189 "terra": false
190 },
191 {
192 "id": "icon-moon",
193 "name": "Moon",
194 "hex": "#d0d8f0",
195 "shape": "crescent",
196 "image": "images/block-icon-moon.png",
197 "terra": false
198 },
199 {
200 "id": "icon-bolt",
201 "name": "Bolt",
202 "hex": "#f0e050",
203 "shape": "lightning",
204 "image": "images/block-icon-bolt.png",
205 "terra": false
206 },
207 {
208 "id": "icon-shield",
209 "name": "Shield",
210 "hex": "#5080c0",
211 "shape": "shield",
212 "image": "images/block-icon-shield.png",
213 "terra": false
214 },
215 {
216 "id": "icon-crown",
217 "name": "Crown",
218 "hex": "#f0c030",
219 "shape": "crown",
220 "image": "images/block-icon-crown.png",
221 "terra": false
222 },
223 {
224 "id": "icon-eye",
225 "name": "Eye",
226 "hex": "#70d0c0",
227 "shape": "eye",
228 "image": "images/block-icon-eye.png",
229 "terra": false
230 },
231 {
232 "id": "icon-star6",
233 "name": "Hexastar",
234 "hex": "#f0e8a0",
235 "shape": "star6",
236 "image": "images/block-icon-star6.png",
237 "terra": false
238 },
239 {
240 "id": "icon-spiral",
241 "name": "Spiral",
242 "hex": "#c070d0",
243 "shape": "spiral",
244 "image": "images/block-icon-spiral.png",
245 "terra": false
246 },
247 {
248 "id": "icon-wave",
249 "name": "Wave",
250 "hex": "#3090d0",
251 "shape": "wave",
252 "image": "images/block-icon-wave.png",
253 "terra": false
254 },
255 {
256 "id": "icon-mountain",
257 "name": "Mountain",
258 "hex": "#809070",
259 "shape": "mountain",
260 "image": "images/block-icon-mountain.png",
261 "terra": false
262 },
263 {
264 "id": "icon-fish",
265 "name": "Fish",
266 "hex": "#40a8c8",
267 "shape": "fish",
268 "image": "images/block-icon-fish.png",
269 "terra": false
270 },
271 {
272 "id": "icon-bird",
273 "name": "Bird",
274 "hex": "#e07050",
275 "shape": "bird",
276 "image": "images/block-icon-bird.png",
277 "terra": false
278 },
279 {
280 "id": "icon-key",
281 "name": "Key",
282 "hex": "#d0b050",
283 "shape": "key",
284 "image": "images/block-icon-key.png",
285 "terra": false
286 },
287 {
288 "id": "icon-comet",
289 "name": "Comet",
290 "hex": "#90d0f0",
291 "shape": "comet",
292 "image": "images/block-icon-comet.png",
293 "terra": false
294 },
295 {
296 "id": "icon-clover",
297 "name": "Clover",
298 "hex": "#40b060",
299 "shape": "clover",
300 "image": "images/block-icon-clover.png",
301 "terra": false
302 },
303 {
304 "id": "icon-paw",
305 "name": "Paw",
306 "hex": "#c08050",
307 "shape": "paw",
308 "image": "images/block-icon-paw.png",
309 "terra": false
310 },
311 {
312 "id": "icon-sword",
313 "name": "Sword",
314 "hex": "#b0b8c0",
315 "shape": "sword",
316 "image": "images/block-icon-sword.png",
317 "terra": false
318 },
319 {
320 "id": "icon-bell",
321 "name": "Bell",
322 "hex": "#f0c848",
323 "shape": "bell",
324 "image": "images/block-icon-bell.png",
325 "terra": false
326 },
327 {
328 "id": "icon-mushroom",
329 "name": "Mushroom",
330 "hex": "#e06050",
331 "shape": "mushroom",
332 "image": "images/block-icon-mushroom.png",
333 "terra": false
334 },
335 {
336 "id": "icon-cactus",
337 "name": "Cactus",
338 "hex": "#50b068",
339 "shape": "cactus",
340 "image": "images/block-icon-cactus.png",
341 "terra": false
342 },
343 {
344 "id": "icon-ring",
345 "name": "Ring",
346 "hex": "#e8d080",
347 "shape": "ring",
348 "image": "images/block-icon-ring.png",
349 "terra": false
350 },
351 {
352 "id": "icon-flag",
353 "name": "Flag",
354 "hex": "#d04050",
355 "shape": "flag",
356 "image": "images/block-icon-flag.png",
357 "terra": false
358 },
359 {
360 "id": "icon-snow",
361 "name": "Snowflake",
362 "hex": "#c8e0f8",
363 "shape": "snowflake",
364 "image": "images/block-icon-snow.png",
365 "terra": false
366 },
367 {
368 "id": "icon-flame",
369 "name": "Flame",
370 "hex": "#ff7030",
371 "shape": "flame_icon",
372 "image": "images/block-icon-flame.png",
373 "terra": false
374 },
375 {
376 "id": "icon-ankh",
377 "name": "Ankh",
378 "hex": "#d0a060",
379 "shape": "ankh",
380 "image": "images/block-icon-ankh.png",
381 "terra": false
382 },
383 {
384 "id": "icon-yin",
385 "name": "Yin Yang",
386 "hex": "#606080",
387 "shape": "yinyang",
388 "image": "images/block-icon-yin.png",
389 "terra": false
390 },
391 {
392 "id": "aurel-gold",
393 "name": "Aurel gold",
394 "hex": "#f4c860",
395 "shape": "hexagon",
396 "image": "images/block-aurel-gold.png",
397 "terra": false
398 },
399 {
400 "id": "aurel-cream",
401 "name": "Aurel cream",
402 "hex": "#f6e7c1",
403 "shape": "circle",
404 "image": "images/block-aurel-cream.png",
405 "terra": false
406 },
407 {
408 "id": "aurel-amber",
409 "name": "Aurel amber",
410 "hex": "#e09a3e",
411 "shape": "teardrop",
412 "image": "images/block-aurel-amber.png",
413 "terra": false
414 },
415 {
416 "id": "aurel-sage",
417 "name": "Aurel sage",
418 "hex": "#8fb86f",
419 "shape": "plus",
420 "image": "images/block-aurel-sage.png",
421 "terra": false
422 },
423 {
424 "id": "aurel-rose",
425 "name": "Aurel rose",
426 "hex": "#e8a0a8",
427 "shape": "pentagon",
428 "image": "images/block-aurel-rose.png",
429 "terra": false
430 },
431 {
432 "id": "cinder-magma",
433 "name": "Cinder magma",
434 "hex": "#ff3b1f",
435 "shape": "triangle",
436 "image": "images/block-cinder-magma.png",
437 "terra": false
438 },
439 {
440 "id": "cinder-coal",
441 "name": "Cinder coal",
442 "hex": "#3a3232",
443 "shape": "square",
444 "image": "images/block-cinder-coal.png",
445 "terra": false
446 },
447 {
448 "id": "cinder-spark",
449 "name": "Cinder spark",
450 "hex": "#ffb347",
451 "shape": "diamond",
452 "image": "images/block-cinder-spark.png",
453 "terra": false
454 },
455 {
456 "id": "cinder-ash",
457 "name": "Cinder ash",
458 "hex": "#8a7a76",
459 "shape": "circle",
460 "image": "images/block-cinder-ash.png",
461 "terra": false
462 },
463 {
464 "id": "cinder-core",
465 "name": "Cinder core",
466 "hex": "#ff6a00",
467 "shape": "star",
468 "image": "images/block-cinder-core.png",
469 "terra": false
470 },
471 {
472 "id": "lunara-silver",
473 "name": "Lunara silver",
474 "hex": "#c5d0e0",
475 "shape": "circle",
476 "image": "images/block-lunara-silver.png",
477 "terra": false
478 },
479 {
480 "id": "lunara-dust",
481 "name": "Lunara dust",
482 "hex": "#8b90a0",
483 "shape": "diamond",
484 "image": "images/block-lunara-dust.png",
485 "terra": false
486 },
487 {
488 "id": "lunara-pale",
489 "name": "Lunara pale",
490 "hex": "#e8d9a8",
491 "shape": "crescent",
492 "image": "images/block-lunara-pale.png",
493 "terra": false
494 },
495 {
496 "id": "lunara-void",
497 "name": "Lunara void",
498 "hex": "#2c3348",
499 "shape": "square",
500 "image": "images/block-lunara-void.png",
501 "terra": false
502 },
503 {
504 "id": "lunara-lilac",
505 "name": "Lunara lilac",
506 "hex": "#b9a4d4",
507 "shape": "star",
508 "image": "images/block-lunara-lilac.png",
509 "terra": false
510 },
511 {
512 "id": "mire-moss",
513 "name": "Mire moss",
514 "hex": "#3d7a45",
515 "shape": "hexagon",
516 "image": "images/block-mire-moss.png",
517 "terra": false
518 },
519 {
520 "id": "mire-bog",
521 "name": "Mire bog",
522 "hex": "#1f4d3a",
523 "shape": "teardrop",
524 "image": "images/block-mire-bog.png",
525 "terra": false
526 },
527 {
528 "id": "mire-rust",
529 "name": "Mire rust",
530 "hex": "#8b5a2b",
531 "shape": "pentagon",
532 "image": "images/block-mire-rust.png",
533 "terra": false
534 },
535 {
536 "id": "mire-spore",
537 "name": "Mire spore",
538 "hex": "#9cbf5a",
539 "shape": "circle",
540 "image": "images/block-mire-spore.png",
541 "terra": false
542 },
543 {
544 "id": "mire-murk",
545 "name": "Mire murk",
546 "hex": "#2e3b2f",
547 "shape": "diamond",
548 "image": "images/block-mire-murk.png",
549 "terra": false
550 },
551 {
552 "id": "galeon-sky",
553 "name": "Galeon sky",
554 "hex": "#4aa3ff",
555 "shape": "arrow",
556 "image": "images/block-galeon-sky.png",
557 "terra": false
558 },
559 {
560 "id": "galeon-cloud",
561 "name": "Galeon cloud",
562 "hex": "#e8eef6",
563 "shape": "circle",
564 "image": "images/block-galeon-cloud.png",
565 "terra": false
566 },
567 {
568 "id": "galeon-storm",
569 "name": "Galeon storm",
570 "hex": "#3d4d6e",
571 "shape": "square",
572 "image": "images/block-galeon-storm.png",
573 "terra": false
574 },
575 {
576 "id": "galeon-sand",
577 "name": "Galeon sand",
578 "hex": "#d4b483",
579 "shape": "diamond",
580 "image": "images/block-galeon-sand.png",
581 "terra": false
582 },
583 {
584 "id": "galeon-kite",
585 "name": "Galeon kite",
586 "hex": "#7fd0c0",
587 "shape": "star",
588 "image": "images/block-galeon-kite.png",
589 "terra": false
590 },
591 {
592 "id": "obsid-glass",
593 "name": "Obsid glass",
594 "hex": "#1a1a22",
595 "shape": "gem",
596 "image": "images/block-obsid-glass.png",
597 "terra": false
598 },
599 {
600 "id": "obsid-violet",
601 "name": "Obsid violet",
602 "hex": "#5a3d8a",
603 "shape": "hexagon",
604 "image": "images/block-obsid-violet.png",
605 "terra": false
606 },
607 {
608 "id": "obsid-shard",
609 "name": "Obsid shard",
610 "hex": "#8a8aa0",
611 "shape": "triangle",
612 "image": "images/block-obsid-shard.png",
613 "terra": false
614 },
615 {
616 "id": "obsid-vein",
617 "name": "Obsid vein",
618 "hex": "#c45a3a",
619 "shape": "diamond",
620 "image": "images/block-obsid-vein.png",
621 "terra": false
622 },
623 {
624 "id": "obsid-basalt",
625 "name": "Obsid basalt",
626 "hex": "#3a3a42",
627 "shape": "square",
628 "image": "images/block-obsid-basalt.png",
629 "terra": false
630 },
631 {
632 "id": "wisp-glow",
633 "name": "Wisp glow",
634 "hex": "#c8ffe0",
635 "shape": "circle",
636 "image": "images/block-wisp-glow.png",
637 "terra": false
638 },
639 {
640 "id": "wisp-mist",
641 "name": "Wisp mist",
642 "hex": "#a8d4e8",
643 "shape": "diamond",
644 "image": "images/block-wisp-mist.png",
645 "terra": false
646 },
647 {
648 "id": "wisp-sparkle",
649 "name": "Wisp sparkle",
650 "hex": "#fff6a8",
651 "shape": "star",
652 "image": "images/block-wisp-sparkle.png",
653 "terra": false
654 },
655 {
656 "id": "wisp-veil",
657 "name": "Wisp veil",
658 "hex": "#d0b8f0",
659 "shape": "teardrop",
660 "image": "images/block-wisp-veil.png",
661 "terra": false
662 },
663 {
664 "id": "wisp-gleam",
665 "name": "Wisp gleam",
666 "hex": "#f4f7ff",
667 "shape": "plus",
668 "image": "images/block-wisp-gleam.png",
669 "terra": false
670 },
671 {
672 "id": "thorn-briar",
673 "name": "Thorn briar",
674 "hex": "#5a7a30",
675 "shape": "triangle",
676 "image": "images/block-thorn-briar.png",
677 "terra": false
678 },
679 {
680 "id": "thorn-berry",
681 "name": "Thorn berry",
682 "hex": "#8b1a4a",
683 "shape": "circle",
684 "image": "images/block-thorn-berry.png",
685 "terra": false
686 },
687 {
688 "id": "thorn-bark",
689 "name": "Thorn bark",
690 "hex": "#5a3a20",
691 "shape": "square",
692 "image": "images/block-thorn-bark.png",
693 "terra": false
694 },
695 {
696 "id": "thorn-petal",
697 "name": "Thorn petal",
698 "hex": "#e89ab0",
699 "shape": "diamond",
700 "image": "images/block-thorn-petal.png",
701 "terra": false
702 },
703 {
704 "id": "thorn-gold",
705 "name": "Thorn gold",
706 "hex": "#c8a030",
707 "shape": "star",
708 "image": "images/block-thorn-gold.png",
709 "terra": false
710 },
711 {
712 "id": "zephyr-azure",
713 "name": "Zephyr azure",
714 "hex": "#6ec8ff",
715 "shape": "crescent",
716 "image": "images/block-zephyr-azure.png",
717 "terra": false
718 },
719 {
720 "id": "zephyr-breeze",
721 "name": "Zephyr breeze",
722 "hex": "#b8e8ff",
723 "shape": "circle",
724 "image": "images/block-zephyr-breeze.png",
725 "terra": false
726 },
727 {
728 "id": "zephyr-cirrus",
729 "name": "Zephyr cirrus",
730 "hex": "#f0f7ff",
731 "shape": "plus",
732 "image": "images/block-zephyr-cirrus.png",
733 "terra": false
734 },
735 {
736 "id": "zephyr-dusk",
737 "name": "Zephyr dusk",
738 "hex": "#7a6ab0",
739 "shape": "diamond",
740 "image": "images/block-zephyr-dusk.png",
741 "terra": false
742 },
743 {
744 "id": "zephyr-haze",
745 "name": "Zephyr haze",
746 "hex": "#ffe08a",
747 "shape": "star",
748 "image": "images/block-zephyr-haze.png",
749 "terra": false
750 },
751 {
752 "id": "frore-ice",
753 "name": "Frore ice",
754 "hex": "#a8d8f0",
755 "shape": "hexagon",
756 "image": "images/block-frore-ice.png",
757 "terra": false
758 },
759 {
760 "id": "frore-frost",
761 "name": "Frore frost",
762 "hex": "#eef7ff",
763 "shape": "circle",
764 "image": "images/block-frore-frost.png",
765 "terra": false
766 },
767 {
768 "id": "frore-deep",
769 "name": "Frore deep",
770 "hex": "#3a6a8a",
771 "shape": "diamond",
772 "image": "images/block-frore-deep.png",
773 "terra": false
774 },
775 {
776 "id": "frore-aurora",
777 "name": "Frore aurora",
778 "hex": "#5ae8c0",
779 "shape": "star",
780 "image": "images/block-frore-aurora.png",
781 "terra": false
782 },
783 {
784 "id": "frore-rime",
785 "name": "Frore rime",
786 "hex": "#d0e4f0",
787 "shape": "triangle",
788 "image": "images/block-frore-rime.png",
789 "terra": false
790 },
791 {
792 "id": "forge-iron",
793 "name": "Forge iron",
794 "hex": "#6a6a72",
795 "shape": "square",
796 "image": "images/block-forge-iron.png",
797 "terra": false
798 },
799 {
800 "id": "forge-slag",
801 "name": "Forge slag",
802 "hex": "#3a3028",
803 "shape": "hexagon",
804 "image": "images/block-forge-slag.png",
805 "terra": false
806 },
807 {
808 "id": "forge-spark",
809 "name": "Forge spark",
810 "hex": "#ff7a1a",
811 "shape": "triangle",
812 "image": "images/block-forge-spark.png",
813 "terra": false
814 },
815 {
816 "id": "forge-brass",
817 "name": "Forge brass",
818 "hex": "#c8a048",
819 "shape": "diamond",
820 "image": "images/block-forge-brass.png",
821 "terra": false
822 },
823 {
824 "id": "forge-soot",
825 "name": "Forge soot",
826 "hex": "#2a2a28",
827 "shape": "circle",
828 "image": "images/block-forge-soot.png",
829 "terra": false
830 }
831 ]
832 }
@@ -0,0 +1,832 @@
1{
2 "_comment": "Append-only block registry. Never reorder, rename ids, or insert in the middle. New blocks go at the end. The first five (Terra) are unlocked by default; index 5 requires 500 lifetime points, each next index requires 14.5% more (rounded).",
3 "terraCount": 5,
4 "firstThreshold": 500,
5 "thresholdGrowth": 1.145,
6 "blocks": [
7 {
8 "id": "terra-ember",
9 "name": "Ember",
10 "hex": "#e85d3a",
11 "shape": "triangle",
12 "image": "images/block-terra-ember.png",
13 "terra": true
14 },
15 {
16 "id": "terra-aqua",
17 "name": "Aqua",
18 "hex": "#3db8e8",
19 "shape": "circle",
20 "image": "images/block-terra-aqua.png",
21 "terra": true
22 },
23 {
24 "id": "terra-leaf",
25 "name": "Leaf",
26 "hex": "#4cbf4c",
27 "shape": "square",
28 "image": "images/block-terra-leaf.png",
29 "terra": true
30 },
31 {
32 "id": "terra-sun",
33 "name": "Sun",
34 "hex": "#f0c53a",
35 "shape": "diamond",
36 "image": "images/block-terra-sun.png",
37 "terra": true
38 },
39 {
40 "id": "terra-orchid",
41 "name": "Orchid",
42 "hex": "#c45ad4",
43 "shape": "star",
44 "image": "images/block-terra-orchid.png",
45 "terra": true
46 },
47 {
48 "id": "rune-fehu",
49 "name": "Fehu",
50 "hex": "#e8a44a",
51 "shape": "rune_fehu",
52 "image": "images/block-rune-fehu.png",
53 "terra": false
54 },
55 {
56 "id": "rune-ansuz",
57 "name": "Ansuz",
58 "hex": "#6ab0e8",
59 "shape": "rune_ansuz",
60 "image": "images/block-rune-ansuz.png",
61 "terra": false
62 },
63 {
64 "id": "rune-thurisaz",
65 "name": "Thurisaz",
66 "hex": "#c05040",
67 "shape": "rune_thurisaz",
68 "image": "images/block-rune-thurisaz.png",
69 "terra": false
70 },
71 {
72 "id": "rune-raido",
73 "name": "Raido",
74 "hex": "#d0c070",
75 "shape": "rune_raido",
76 "image": "images/block-rune-raido.png",
77 "terra": false
78 },
79 {
80 "id": "rune-sowilo",
81 "name": "Sowilo",
82 "hex": "#f0d040",
83 "shape": "rune_sowilo",
84 "image": "images/block-rune-sowilo.png",
85 "terra": false
86 },
87 {
88 "id": "rune-algiz",
89 "name": "Algiz",
90 "hex": "#80d0a0",
91 "shape": "rune_algiz",
92 "image": "images/block-rune-algiz.png",
93 "terra": false
94 },
95 {
96 "id": "arrow-up",
97 "name": "Arrow",
98 "hex": "#f07040",
99 "shape": "arrow",
100 "image": "images/block-arrow-up.png",
101 "terra": false
102 },
103 {
104 "id": "arrow-chevron",
105 "name": "Chevron",
106 "hex": "#50c0e0",
107 "shape": "chevron",
108 "image": "images/block-arrow-chevron.png",
109 "terra": false
110 },
111 {
112 "id": "arrow-double",
113 "name": "Double Arrow",
114 "hex": "#e05080",
115 "shape": "double_arrow",
116 "image": "images/block-arrow-double.png",
117 "terra": false
118 },
119 {
120 "id": "arrow-return",
121 "name": "Return",
122 "hex": "#a080e0",
123 "shape": "return_arrow",
124 "image": "images/block-arrow-return.png",
125 "terra": false
126 },
127 {
128 "id": "fig-person",
129 "name": "Figure",
130 "hex": "#f0c0a0",
131 "shape": "person",
132 "image": "images/block-fig-person.png",
133 "terra": false
134 },
135 {
136 "id": "fig-walker",
137 "name": "Walker",
138 "hex": "#c09070",
139 "shape": "walker",
140 "image": "images/block-fig-walker.png",
141 "terra": false
142 },
143 {
144 "id": "fig-hero",
145 "name": "Hero",
146 "hex": "#e8b070",
147 "shape": "hero",
148 "image": "images/block-fig-hero.png",
149 "terra": false
150 },
151 {
152 "id": "face-smile",
153 "name": "Smile",
154 "hex": "#f0d060",
155 "shape": "smile",
156 "image": "images/block-face-smile.png",
157 "terra": false
158 },
159 {
160 "id": "face-wink",
161 "name": "Wink",
162 "hex": "#f0a050",
163 "shape": "wink",
164 "image": "images/block-face-wink.png",
165 "terra": false
166 },
167 {
168 "id": "face-cool",
169 "name": "Cool",
170 "hex": "#6090d0",
171 "shape": "cool",
172 "image": "images/block-face-cool.png",
173 "terra": false
174 },
175 {
176 "id": "face-grin",
177 "name": "Grin",
178 "hex": "#f0c848",
179 "shape": "grin",
180 "image": "images/block-face-grin.png",
181 "terra": false
182 },
183 {
184 "id": "icon-heart",
185 "name": "Heart",
186 "hex": "#e04060",
187 "shape": "heart",
188 "image": "images/block-icon-heart.png",
189 "terra": false
190 },
191 {
192 "id": "icon-moon",
193 "name": "Moon",
194 "hex": "#d0d8f0",
195 "shape": "crescent",
196 "image": "images/block-icon-moon.png",
197 "terra": false
198 },
199 {
200 "id": "icon-bolt",
201 "name": "Bolt",
202 "hex": "#f0e050",
203 "shape": "lightning",
204 "image": "images/block-icon-bolt.png",
205 "terra": false
206 },
207 {
208 "id": "icon-shield",
209 "name": "Shield",
210 "hex": "#5080c0",
211 "shape": "shield",
212 "image": "images/block-icon-shield.png",
213 "terra": false
214 },
215 {
216 "id": "icon-crown",
217 "name": "Crown",
218 "hex": "#f0c030",
219 "shape": "crown",
220 "image": "images/block-icon-crown.png",
221 "terra": false
222 },
223 {
224 "id": "icon-eye",
225 "name": "Eye",
226 "hex": "#70d0c0",
227 "shape": "eye",
228 "image": "images/block-icon-eye.png",
229 "terra": false
230 },
231 {
232 "id": "icon-star6",
233 "name": "Hexastar",
234 "hex": "#f0e8a0",
235 "shape": "star6",
236 "image": "images/block-icon-star6.png",
237 "terra": false
238 },
239 {
240 "id": "icon-spiral",
241 "name": "Spiral",
242 "hex": "#c070d0",
243 "shape": "spiral",
244 "image": "images/block-icon-spiral.png",
245 "terra": false
246 },
247 {
248 "id": "icon-wave",
249 "name": "Wave",
250 "hex": "#3090d0",
251 "shape": "wave",
252 "image": "images/block-icon-wave.png",
253 "terra": false
254 },
255 {
256 "id": "icon-mountain",
257 "name": "Mountain",
258 "hex": "#809070",
259 "shape": "mountain",
260 "image": "images/block-icon-mountain.png",
261 "terra": false
262 },
263 {
264 "id": "icon-fish",
265 "name": "Fish",
266 "hex": "#40a8c8",
267 "shape": "fish",
268 "image": "images/block-icon-fish.png",
269 "terra": false
270 },
271 {
272 "id": "icon-bird",
273 "name": "Bird",
274 "hex": "#e07050",
275 "shape": "bird",
276 "image": "images/block-icon-bird.png",
277 "terra": false
278 },
279 {
280 "id": "icon-key",
281 "name": "Key",
282 "hex": "#d0b050",
283 "shape": "key",
284 "image": "images/block-icon-key.png",
285 "terra": false
286 },
287 {
288 "id": "icon-comet",
289 "name": "Comet",
290 "hex": "#90d0f0",
291 "shape": "comet",
292 "image": "images/block-icon-comet.png",
293 "terra": false
294 },
295 {
296 "id": "icon-clover",
297 "name": "Clover",
298 "hex": "#40b060",
299 "shape": "clover",
300 "image": "images/block-icon-clover.png",
301 "terra": false
302 },
303 {
304 "id": "icon-paw",
305 "name": "Paw",
306 "hex": "#c08050",
307 "shape": "paw",
308 "image": "images/block-icon-paw.png",
309 "terra": false
310 },
311 {
312 "id": "icon-sword",
313 "name": "Sword",
314 "hex": "#b0b8c0",
315 "shape": "sword",
316 "image": "images/block-icon-sword.png",
317 "terra": false
318 },
319 {
320 "id": "icon-bell",
321 "name": "Bell",
322 "hex": "#f0c848",
323 "shape": "bell",
324 "image": "images/block-icon-bell.png",
325 "terra": false
326 },
327 {
328 "id": "icon-mushroom",
329 "name": "Mushroom",
330 "hex": "#e06050",
331 "shape": "mushroom",
332 "image": "images/block-icon-mushroom.png",
333 "terra": false
334 },
335 {
336 "id": "icon-cactus",
337 "name": "Cactus",
338 "hex": "#50b068",
339 "shape": "cactus",
340 "image": "images/block-icon-cactus.png",
341 "terra": false
342 },
343 {
344 "id": "icon-ring",
345 "name": "Ring",
346 "hex": "#e8d080",
347 "shape": "ring",
348 "image": "images/block-icon-ring.png",
349 "terra": false
350 },
351 {
352 "id": "icon-flag",
353 "name": "Flag",
354 "hex": "#d04050",
355 "shape": "flag",
356 "image": "images/block-icon-flag.png",
357 "terra": false
358 },
359 {
360 "id": "icon-snow",
361 "name": "Snowflake",
362 "hex": "#c8e0f8",
363 "shape": "snowflake",
364 "image": "images/block-icon-snow.png",
365 "terra": false
366 },
367 {
368 "id": "icon-flame",
369 "name": "Flame",
370 "hex": "#ff7030",
371 "shape": "flame_icon",
372 "image": "images/block-icon-flame.png",
373 "terra": false
374 },
375 {
376 "id": "icon-ankh",
377 "name": "Ankh",
378 "hex": "#d0a060",
379 "shape": "ankh",
380 "image": "images/block-icon-ankh.png",
381 "terra": false
382 },
383 {
384 "id": "icon-yin",
385 "name": "Yin Yang",
386 "hex": "#606080",
387 "shape": "yinyang",
388 "image": "images/block-icon-yin.png",
389 "terra": false
390 },
391 {
392 "id": "aurel-gold",
393 "name": "Aurel gold",
394 "hex": "#f4c860",
395 "shape": "hexagon",
396 "image": "images/block-aurel-gold.png",
397 "terra": false
398 },
399 {
400 "id": "aurel-cream",
401 "name": "Aurel cream",
402 "hex": "#f6e7c1",
403 "shape": "circle",
404 "image": "images/block-aurel-cream.png",
405 "terra": false
406 },
407 {
408 "id": "aurel-amber",
409 "name": "Aurel amber",
410 "hex": "#e09a3e",
411 "shape": "teardrop",
412 "image": "images/block-aurel-amber.png",
413 "terra": false
414 },
415 {
416 "id": "aurel-sage",
417 "name": "Aurel sage",
418 "hex": "#8fb86f",
419 "shape": "plus",
420 "image": "images/block-aurel-sage.png",
421 "terra": false
422 },
423 {
424 "id": "aurel-rose",
425 "name": "Aurel rose",
426 "hex": "#e8a0a8",
427 "shape": "pentagon",
428 "image": "images/block-aurel-rose.png",
429 "terra": false
430 },
431 {
432 "id": "cinder-magma",
433 "name": "Cinder magma",
434 "hex": "#ff3b1f",
435 "shape": "triangle",
436 "image": "images/block-cinder-magma.png",
437 "terra": false
438 },
439 {
440 "id": "cinder-coal",
441 "name": "Cinder coal",
442 "hex": "#3a3232",
443 "shape": "square",
444 "image": "images/block-cinder-coal.png",
445 "terra": false
446 },
447 {
448 "id": "cinder-spark",
449 "name": "Cinder spark",
450 "hex": "#ffb347",
451 "shape": "diamond",
452 "image": "images/block-cinder-spark.png",
453 "terra": false
454 },
455 {
456 "id": "cinder-ash",
457 "name": "Cinder ash",
458 "hex": "#8a7a76",
459 "shape": "circle",
460 "image": "images/block-cinder-ash.png",
461 "terra": false
462 },
463 {
464 "id": "cinder-core",
465 "name": "Cinder core",
466 "hex": "#ff6a00",
467 "shape": "star",
468 "image": "images/block-cinder-core.png",
469 "terra": false
470 },
471 {
472 "id": "lunara-silver",
473 "name": "Lunara silver",
474 "hex": "#c5d0e0",
475 "shape": "circle",
476 "image": "images/block-lunara-silver.png",
477 "terra": false
478 },
479 {
480 "id": "lunara-dust",
481 "name": "Lunara dust",
482 "hex": "#8b90a0",
483 "shape": "diamond",
484 "image": "images/block-lunara-dust.png",
485 "terra": false
486 },
487 {
488 "id": "lunara-pale",
489 "name": "Lunara pale",
490 "hex": "#e8d9a8",
491 "shape": "crescent",
492 "image": "images/block-lunara-pale.png",
493 "terra": false
494 },
495 {
496 "id": "lunara-void",
497 "name": "Lunara void",
498 "hex": "#2c3348",
499 "shape": "square",
500 "image": "images/block-lunara-void.png",
501 "terra": false
502 },
503 {
504 "id": "lunara-lilac",
505 "name": "Lunara lilac",
506 "hex": "#b9a4d4",
507 "shape": "star",
508 "image": "images/block-lunara-lilac.png",
509 "terra": false
510 },
511 {
512 "id": "mire-moss",
513 "name": "Mire moss",
514 "hex": "#3d7a45",
515 "shape": "hexagon",
516 "image": "images/block-mire-moss.png",
517 "terra": false
518 },
519 {
520 "id": "mire-bog",
521 "name": "Mire bog",
522 "hex": "#1f4d3a",
523 "shape": "teardrop",
524 "image": "images/block-mire-bog.png",
525 "terra": false
526 },
527 {
528 "id": "mire-rust",
529 "name": "Mire rust",
530 "hex": "#8b5a2b",
531 "shape": "pentagon",
532 "image": "images/block-mire-rust.png",
533 "terra": false
534 },
535 {
536 "id": "mire-spore",
537 "name": "Mire spore",
538 "hex": "#9cbf5a",
539 "shape": "circle",
540 "image": "images/block-mire-spore.png",
541 "terra": false
542 },
543 {
544 "id": "mire-murk",
545 "name": "Mire murk",
546 "hex": "#2e3b2f",
547 "shape": "diamond",
548 "image": "images/block-mire-murk.png",
549 "terra": false
550 },
551 {
552 "id": "galeon-sky",
553 "name": "Galeon sky",
554 "hex": "#4aa3ff",
555 "shape": "arrow",
556 "image": "images/block-galeon-sky.png",
557 "terra": false
558 },
559 {
560 "id": "galeon-cloud",
561 "name": "Galeon cloud",
562 "hex": "#e8eef6",
563 "shape": "circle",
564 "image": "images/block-galeon-cloud.png",
565 "terra": false
566 },
567 {
568 "id": "galeon-storm",
569 "name": "Galeon storm",
570 "hex": "#3d4d6e",
571 "shape": "square",
572 "image": "images/block-galeon-storm.png",
573 "terra": false
574 },
575 {
576 "id": "galeon-sand",
577 "name": "Galeon sand",
578 "hex": "#d4b483",
579 "shape": "diamond",
580 "image": "images/block-galeon-sand.png",
581 "terra": false
582 },
583 {
584 "id": "galeon-kite",
585 "name": "Galeon kite",
586 "hex": "#7fd0c0",
587 "shape": "star",
588 "image": "images/block-galeon-kite.png",
589 "terra": false
590 },
591 {
592 "id": "obsid-glass",
593 "name": "Obsid glass",
594 "hex": "#1a1a22",
595 "shape": "gem",
596 "image": "images/block-obsid-glass.png",
597 "terra": false
598 },
599 {
600 "id": "obsid-violet",
601 "name": "Obsid violet",
602 "hex": "#5a3d8a",
603 "shape": "hexagon",
604 "image": "images/block-obsid-violet.png",
605 "terra": false
606 },
607 {
608 "id": "obsid-shard",
609 "name": "Obsid shard",
610 "hex": "#8a8aa0",
611 "shape": "triangle",
612 "image": "images/block-obsid-shard.png",
613 "terra": false
614 },
615 {
616 "id": "obsid-vein",
617 "name": "Obsid vein",
618 "hex": "#c45a3a",
619 "shape": "diamond",
620 "image": "images/block-obsid-vein.png",
621 "terra": false
622 },
623 {
624 "id": "obsid-basalt",
625 "name": "Obsid basalt",
626 "hex": "#3a3a42",
627 "shape": "square",
628 "image": "images/block-obsid-basalt.png",
629 "terra": false
630 },
631 {
632 "id": "wisp-glow",
633 "name": "Wisp glow",
634 "hex": "#c8ffe0",
635 "shape": "circle",
636 "image": "images/block-wisp-glow.png",
637 "terra": false
638 },
639 {
640 "id": "wisp-mist",
641 "name": "Wisp mist",
642 "hex": "#a8d4e8",
643 "shape": "diamond",
644 "image": "images/block-wisp-mist.png",
645 "terra": false
646 },
647 {
648 "id": "wisp-sparkle",
649 "name": "Wisp sparkle",
650 "hex": "#fff6a8",
651 "shape": "star",
652 "image": "images/block-wisp-sparkle.png",
653 "terra": false
654 },
655 {
656 "id": "wisp-veil",
657 "name": "Wisp veil",
658 "hex": "#d0b8f0",
659 "shape": "teardrop",
660 "image": "images/block-wisp-veil.png",
661 "terra": false
662 },
663 {
664 "id": "wisp-gleam",
665 "name": "Wisp gleam",
666 "hex": "#f4f7ff",
667 "shape": "plus",
668 "image": "images/block-wisp-gleam.png",
669 "terra": false
670 },
671 {
672 "id": "thorn-briar",
673 "name": "Thorn briar",
674 "hex": "#5a7a30",
675 "shape": "triangle",
676 "image": "images/block-thorn-briar.png",
677 "terra": false
678 },
679 {
680 "id": "thorn-berry",
681 "name": "Thorn berry",
682 "hex": "#8b1a4a",
683 "shape": "circle",
684 "image": "images/block-thorn-berry.png",
685 "terra": false
686 },
687 {
688 "id": "thorn-bark",
689 "name": "Thorn bark",
690 "hex": "#5a3a20",
691 "shape": "square",
692 "image": "images/block-thorn-bark.png",
693 "terra": false
694 },
695 {
696 "id": "thorn-petal",
697 "name": "Thorn petal",
698 "hex": "#e89ab0",
699 "shape": "diamond",
700 "image": "images/block-thorn-petal.png",
701 "terra": false
702 },
703 {
704 "id": "thorn-gold",
705 "name": "Thorn gold",
706 "hex": "#c8a030",
707 "shape": "star",
708 "image": "images/block-thorn-gold.png",
709 "terra": false
710 },
711 {
712 "id": "zephyr-azure",
713 "name": "Zephyr azure",
714 "hex": "#6ec8ff",
715 "shape": "crescent",
716 "image": "images/block-zephyr-azure.png",
717 "terra": false
718 },
719 {
720 "id": "zephyr-breeze",
721 "name": "Zephyr breeze",
722 "hex": "#b8e8ff",
723 "shape": "circle",
724 "image": "images/block-zephyr-breeze.png",
725 "terra": false
726 },
727 {
728 "id": "zephyr-cirrus",
729 "name": "Zephyr cirrus",
730 "hex": "#f0f7ff",
731 "shape": "plus",
732 "image": "images/block-zephyr-cirrus.png",
733 "terra": false
734 },
735 {
736 "id": "zephyr-dusk",
737 "name": "Zephyr dusk",
738 "hex": "#7a6ab0",
739 "shape": "diamond",
740 "image": "images/block-zephyr-dusk.png",
741 "terra": false
742 },
743 {
744 "id": "zephyr-haze",
745 "name": "Zephyr haze",
746 "hex": "#ffe08a",
747 "shape": "star",
748 "image": "images/block-zephyr-haze.png",
749 "terra": false
750 },
751 {
752 "id": "frore-ice",
753 "name": "Frore ice",
754 "hex": "#a8d8f0",
755 "shape": "hexagon",
756 "image": "images/block-frore-ice.png",
757 "terra": false
758 },
759 {
760 "id": "frore-frost",
761 "name": "Frore frost",
762 "hex": "#eef7ff",
763 "shape": "circle",
764 "image": "images/block-frore-frost.png",
765 "terra": false
766 },
767 {
768 "id": "frore-deep",
769 "name": "Frore deep",
770 "hex": "#3a6a8a",
771 "shape": "diamond",
772 "image": "images/block-frore-deep.png",
773 "terra": false
774 },
775 {
776 "id": "frore-aurora",
777 "name": "Frore aurora",
778 "hex": "#5ae8c0",
779 "shape": "star",
780 "image": "images/block-frore-aurora.png",
781 "terra": false
782 },
783 {
784 "id": "frore-rime",
785 "name": "Frore rime",
786 "hex": "#d0e4f0",
787 "shape": "triangle",
788 "image": "images/block-frore-rime.png",
789 "terra": false
790 },
791 {
792 "id": "forge-iron",
793 "name": "Forge iron",
794 "hex": "#6a6a72",
795 "shape": "square",
796 "image": "images/block-forge-iron.png",
797 "terra": false
798 },
799 {
800 "id": "forge-slag",
801 "name": "Forge slag",
802 "hex": "#3a3028",
803 "shape": "hexagon",
804 "image": "images/block-forge-slag.png",
805 "terra": false
806 },
807 {
808 "id": "forge-spark",
809 "name": "Forge spark",
810 "hex": "#ff7a1a",
811 "shape": "triangle",
812 "image": "images/block-forge-spark.png",
813 "terra": false
814 },
815 {
816 "id": "forge-brass",
817 "name": "Forge brass",
818 "hex": "#c8a048",
819 "shape": "diamond",
820 "image": "images/block-forge-brass.png",
821 "terra": false
822 },
823 {
824 "id": "forge-soot",
825 "name": "Forge soot",
826 "hex": "#2a2a28",
827 "shape": "circle",
828 "image": "images/block-forge-soot.png",
829 "terra": false
830 }
831 ]
832}
server/tests/run.php +210 −0
@@ -297,8 +297,218 @@ $store->leaveLobby('local:test_user_1');
297 297 $store->leaveLobby('local:test_user_2');
298 298 $store->leaveLobby('local:test_user_3');
299 299
300
301 echo "\nBlocks registry and unlock thresholds\n";
302 require_once dirname(__DIR__) . '/lib/Blocks.php';
303 $allBlocks = Blocks::all();
304 expect(count($allBlocks) >= 48, 'registry has Terra + new icons (got ' . count($allBlocks) . ')');
305 for ($i = 0; $i < 5; $i++) {
306 expect(Blocks::threshold($i) === 0, "terra index $i is free");
307 }
308 expect(Blocks::threshold(5) === 500, 'first unlock is 500 points');
309 $prev = 500;
310 for ($i = 6; $i < count($allBlocks); $i++) {
311 $t = Blocks::threshold($i);
312 if ($t <= $prev) {
313 expect(false, "threshold at $i should be > $prev, got $t");
314 break;
315 }
316 $prev = $t;
317 }
318 expect($prev > 500, 'later thresholds grow');
319 expect(Blocks::unlocked(0, 0) === true, 'terra unlocked at 0 points');
320 expect(Blocks::unlocked(5, 499) === false, 'fehu locked at 499');
321 expect(Blocks::unlocked(5, 500) === true, 'fehu unlocked at 500');
322 $terraIds = [];
323 foreach ($allBlocks as $i => $b) {
324 if ($i >= 5) break;
325 $terraIds[] = $b['id'];
326 }
327
328 echo "\nLifetime points, anti-cheat, custom planets\n";
329 $ptsStore = Store::open($tmp);
330 $u = 'local:designer_a';
331 $v = 'local:designer_b';
332 expect($ptsStore->lifetimePoints($u) === 0, 'new profile starts at 0');
333 $t1 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
334 expect($t1 === 200, 'first award adds 200');
335 $t2 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
336 expect($t2 === 200, 'same award_key is idempotent');
337 $t3 = $ptsStore->awardPoints($u, 50, 'k-two', 'offline');
338 expect($t3 === 250, 'second key adds 50');
339
340 $ptsStore->testNow = 1_000_000;
341 $ses = $ptsStore->playBegin($u, 'solo');
342 expect(isset($ses['token']) && strlen($ses['token']) === 32, 'playBegin returns a token');
343 $ptsStore->testNow = 1_000_001;
344 $fin = $ptsStore->playFinish($u, $ses['token'], 9000);
345 expect($fin['awarded'] === 0, 'score with duration under 3s awards 0');
346 expect($fin['lifetime_points'] === 250, 'lifetime unchanged after clamped zero');
347 $again = $ptsStore->playFinish($u, $ses['token'], 9000);
348 expect(!empty($again['already']), 'second finish of same token is a no-op');
349
350 $ptsStore->testNow = 2_000_000;
351 $ses2 = $ptsStore->playBegin($u, 'offline');
352 $ptsStore->testNow = 2_000_010;
353 $fin2 = $ptsStore->playFinish($u, $ses2['token'], 9000);
354 expect($fin2['awarded'] === 40, 'cap is 4 points/s over 10s (got ' . $fin2['awarded'] . ')');
355 expect($fin2['lifetime_points'] === 290, 'capped award is added');
356
357 $ptsStore->testNow = 3_000_000;
358 $ses3 = $ptsStore->playBegin($u, 'solo');
359 $ptsStore->testNow = 3_000_020;
360 $fin3 = $ptsStore->playFinish($u, $ses3['token'], 17);
361 expect($fin3['awarded'] === 17, 'honest score under the cap is kept');
362
363 try {
364 $ptsStore->saveCustomPlanet($u, [
365 'name' => 'Lockworld', 'people' => 'Lockers',
366 'jumpsToClear' => 2, 'fallTime' => 3, 'riseTime' => 1.5,
367 'colors' => array_merge($terraIds, ['rune-fehu']),
368 ]);
369 // 6 items? no that's 6. Use 4 terra + fehu
370 expect(false, 'should not reach (wrong colors count would throw first)');
371 } catch (RuntimeException $e) {
372 expect(str_contains($e->getMessage(), 'vijf') || str_contains($e->getMessage(), 'ontgrendeld') || str_contains($e->getMessage(), 'Onbekend'),
373 'invalid colors refused: ' . $e->getMessage());
374 }
375
376 try {
377 $ptsStore->saveCustomPlanet($u, [
378 'name' => 'Lockworld', 'people' => 'Lockers',
379 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'rune-fehu'],
380 ]);
381 expect(false, 'locked block should throw');
382 } catch (RuntimeException $e) {
383 expect(str_contains($e->getMessage(), 'ontgrendeld'), 'locked block refused: ' . $e->getMessage());
384 }
385
386 try {
387 $ptsStore->saveCustomPlanet($u, [
388 'name' => 'Ghost', 'people' => 'Ghosts',
389 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'no-such-block'],
390 ]);
391 expect(false, 'unknown block should throw');
392 } catch (RuntimeException $e) {
393 expect(str_contains($e->getMessage(), 'Onbekend'), 'unknown block refused: ' . $e->getMessage());
394 }
395
396 try {
397 $ptsStore->saveCustomPlanet($u, [
398 'name' => 'Twins', 'people' => 'Twins',
399 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], $terraIds[0]],
400 ]);
401 expect(false, 'duplicate block should throw');
402 } catch (RuntimeException $e) {
403 expect(str_contains($e->getMessage(), 'één vak') || str_contains($e->getMessage(), 'vak'),
404 'duplicate block refused: ' . $e->getMessage());
405 }
406
407 $snap = $ptsStore->saveCustomPlanet($u, [
408 'name' => 'My World', 'people' => 'My People',
409 'jumpsToClear' => 2.5, 'fallTime' => 2, 'riseTime' => 1,
410 'colors' => $terraIds,
411 ]);
412 expect(!empty($snap['id']) && str_starts_with($snap['id'], 'c_'), 'custom id is c_ + hex');
413 expect($snap['custom'] === true, 'snapshot is marked custom');
414 expect($snap['name'] === 'My World', 'name stored');
415 expect(count($snap['colors']) === 5, 'five colors in snapshot');
416 expect($snap['colors'][0]['block'] === $terraIds[0], 'color has registry block id');
417 expect($snap['owner_id'] === $u, 'owner_id set');
418
419 $listed = $ptsStore->listCustomPlanets($u);
420 expect(count($listed) === 1, 'owner lists the planet');
421 expect($ptsStore->listCustomPlanets($v) === [], 'other user has no planets');
422
423 try {
424 $ptsStore->setPlanet($u, $snap['id']);
425 expect(false, 'setPlanet without a lobby should throw');
426 } catch (RuntimeException $e) {
427 expect(true, 'setPlanet requires a lobby: ' . $e->getMessage());
428 }
429
430 $lobby = $ptsStore->createLobby($u, 'A', 0.3, $snap['id']);
431 $view = $ptsStore->viewFor($u);
432 $meP = $view['lobby']['players'][0]['planet'] ?? null;
433 expect($meP && $meP['id'] === $snap['id'], 'createLobby stores custom planet');
434 expect(!empty($meP['custom']), 'presented planet is custom');
435 expect(count($meP['colors']) === 5 && $meP['colors'][0]['image'] !== '', 'presented colors include images');
436 expect(isset($meP['miss_chance']) && is_float($meP['miss_chance']), 'server sends miss_chance for custom');
437
438 $ptsStore->joinLobby($v, 'B', $lobby['code']);
439 $viewB = $ptsStore->viewFor($v);
440 $seen = null;
441 foreach ($viewB['lobby']['players'] as $plr) {
442 if ($plr['planet']['id'] === $snap['id']) { $seen = $plr['planet']; }
443 }
444 expect($seen !== null, 'other player sees the custom planet snapshot');
445 expect(($seen['colors'][2]['block'] ?? '') === $terraIds[2], 'opponent sees block ids');
446
447 try {
448 $ptsStore->setPlanet($v, $snap['id']);
449 expect(false, 'cannot pick someone else\'s custom planet');
450 } catch (RuntimeException $e) {
451 expect(str_contains($e->getMessage(), 'Onbekende'), 'foreign custom refused: ' . $e->getMessage());
452 }
453
454 $ptsStore->leaveLobby($u);
455 $ptsStore->leaveLobby($v);
456 $ptsStore->deleteCustomPlanet($u, $snap['id']);
457 expect($ptsStore->listCustomPlanets($u) === [], 'deleted planet is gone');
458
459 // Snapshot survives mid-match edits: create, join, start, then edit/delete, opponent still sees original.
460 $snap2 = $ptsStore->saveCustomPlanet($u, [
461 'name' => 'Frozen', 'people' => 'Ice',
462 'jumpsToClear' => 3, 'fallTime' => 2, 'riseTime' => 1,
463 'colors' => $terraIds,
464 ]);
465 $lobby2 = $ptsStore->createLobby($u, 'A', 0.3, $snap2['id']);
466 $ptsStore->joinLobby($v, 'B', $lobby2['code']);
467 $ptsStore->setReady($u, true);
468 $ptsStore->setReady($v, true);
469 $ptsStore->startGame($u);
470 $ptsStore->saveCustomPlanet($u, [
471 'id' => $snap2['id'],
472 'name' => 'Changed', 'people' => 'Ice',
473 'jumpsToClear' => 1, 'fallTime' => 5, 'riseTime' => 3,
474 'colors' => $terraIds,
475 ]);
476 $viewMid = $ptsStore->viewFor($v);
477 $midP = null;
478 foreach ($viewMid['lobby']['players'] as $plr) {
479 if (($plr['planet']['id'] ?? '') === $snap2['id']) { $midP = $plr['planet']; }
480 }
481 expect($midP && $midP['name'] === 'Frozen', 'in-match snapshot keeps the original name (got ' . ($midP['name'] ?? '?') . ')');
482 expect($midP && almostEqual((float) $midP['jumpsToClear'], 3.0), 'in-match snapshot keeps original gravity');
483 $ptsStore->leaveLobby($u);
484 $ptsStore->leaveLobby($v);
485
486 // Online award is idempotent and server-side.
487 $u3 = 'local:online_award_a';
488 $v3 = 'local:online_award_b';
489 $lob = $ptsStore->createLobby($u3, 'A', 0.0, 'terra');
490 $ptsStore->joinLobby($v3, 'B', $lob['code']);
491 $ptsStore->setReady($u3, true);
492 $ptsStore->setReady($v3, true);
493 $ptsStore->startGame($u3);
494 $ptsStore->viewFor($u3, null, 80, false, []);
495 $ptsStore->viewFor($u3, null, 80, true, []);
496 expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the score');
497 $ptsStore->viewFor($u3, null, 999, true, []);
498 expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');
499
500 $ptsStore->setLocale($u, 'nl');
501 expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');
502 try {
503 $ptsStore->setLocale($u, 'xx');
504 expect(false, 'unknown locale should throw');
505 } catch (RuntimeException $e) {
506 expect(true, 'unknown locale refused');
507 }
508
300 509 echo "\nConfig helpers\n";
301 510
511
302 512 $cfg = config();
303 513 expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
304 514 expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
@@ -297,8 +297,218 @@ $store->leaveLobby('local:test_user_1');
297$store->leaveLobby('local:test_user_2');
297$store->leaveLobby('local:test_user_2');
298$store->leaveLobby('local:test_user_3');
298$store->leaveLobby('local:test_user_3');
299
299
300
301echo "\nBlocks registry and unlock thresholds\n";
302require_once dirname(__DIR__) . '/lib/Blocks.php';
303$allBlocks = Blocks::all();
304expect(count($allBlocks) >= 48, 'registry has Terra + new icons (got ' . count($allBlocks) . ')');
305for ($i = 0; $i < 5; $i++) {
306 expect(Blocks::threshold($i) === 0, "terra index $i is free");
307}
308expect(Blocks::threshold(5) === 500, 'first unlock is 500 points');
309$prev = 500;
310for ($i = 6; $i < count($allBlocks); $i++) {
311 $t = Blocks::threshold($i);
312 if ($t <= $prev) {
313 expect(false, "threshold at $i should be > $prev, got $t");
314 break;
315 }
316 $prev = $t;
317}
318expect($prev > 500, 'later thresholds grow');
319expect(Blocks::unlocked(0, 0) === true, 'terra unlocked at 0 points');
320expect(Blocks::unlocked(5, 499) === false, 'fehu locked at 499');
321expect(Blocks::unlocked(5, 500) === true, 'fehu unlocked at 500');
322$terraIds = [];
323foreach ($allBlocks as $i => $b) {
324 if ($i >= 5) break;
325 $terraIds[] = $b['id'];
326}
327
328echo "\nLifetime points, anti-cheat, custom planets\n";
329$ptsStore = Store::open($tmp);
330$u = 'local:designer_a';
331$v = 'local:designer_b';
332expect($ptsStore->lifetimePoints($u) === 0, 'new profile starts at 0');
333$t1 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
334expect($t1 === 200, 'first award adds 200');
335$t2 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
336expect($t2 === 200, 'same award_key is idempotent');
337$t3 = $ptsStore->awardPoints($u, 50, 'k-two', 'offline');
338expect($t3 === 250, 'second key adds 50');
339
340$ptsStore->testNow = 1_000_000;
341$ses = $ptsStore->playBegin($u, 'solo');
342expect(isset($ses['token']) && strlen($ses['token']) === 32, 'playBegin returns a token');
343$ptsStore->testNow = 1_000_001;
344$fin = $ptsStore->playFinish($u, $ses['token'], 9000);
345expect($fin['awarded'] === 0, 'score with duration under 3s awards 0');
346expect($fin['lifetime_points'] === 250, 'lifetime unchanged after clamped zero');
347$again = $ptsStore->playFinish($u, $ses['token'], 9000);
348expect(!empty($again['already']), 'second finish of same token is a no-op');
349
350$ptsStore->testNow = 2_000_000;
351$ses2 = $ptsStore->playBegin($u, 'offline');
352$ptsStore->testNow = 2_000_010;
353$fin2 = $ptsStore->playFinish($u, $ses2['token'], 9000);
354expect($fin2['awarded'] === 40, 'cap is 4 points/s over 10s (got ' . $fin2['awarded'] . ')');
355expect($fin2['lifetime_points'] === 290, 'capped award is added');
356
357$ptsStore->testNow = 3_000_000;
358$ses3 = $ptsStore->playBegin($u, 'solo');
359$ptsStore->testNow = 3_000_020;
360$fin3 = $ptsStore->playFinish($u, $ses3['token'], 17);
361expect($fin3['awarded'] === 17, 'honest score under the cap is kept');
362
363try {
364 $ptsStore->saveCustomPlanet($u, [
365 'name' => 'Lockworld', 'people' => 'Lockers',
366 'jumpsToClear' => 2, 'fallTime' => 3, 'riseTime' => 1.5,
367 'colors' => array_merge($terraIds, ['rune-fehu']),
368 ]);
369 // 6 items? no that's 6. Use 4 terra + fehu
370 expect(false, 'should not reach (wrong colors count would throw first)');
371} catch (RuntimeException $e) {
372 expect(str_contains($e->getMessage(), 'vijf') || str_contains($e->getMessage(), 'ontgrendeld') || str_contains($e->getMessage(), 'Onbekend'),
373 'invalid colors refused: ' . $e->getMessage());
374}
375
376try {
377 $ptsStore->saveCustomPlanet($u, [
378 'name' => 'Lockworld', 'people' => 'Lockers',
379 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'rune-fehu'],
380 ]);
381 expect(false, 'locked block should throw');
382} catch (RuntimeException $e) {
383 expect(str_contains($e->getMessage(), 'ontgrendeld'), 'locked block refused: ' . $e->getMessage());
384}
385
386try {
387 $ptsStore->saveCustomPlanet($u, [
388 'name' => 'Ghost', 'people' => 'Ghosts',
389 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'no-such-block'],
390 ]);
391 expect(false, 'unknown block should throw');
392} catch (RuntimeException $e) {
393 expect(str_contains($e->getMessage(), 'Onbekend'), 'unknown block refused: ' . $e->getMessage());
394}
395
396try {
397 $ptsStore->saveCustomPlanet($u, [
398 'name' => 'Twins', 'people' => 'Twins',
399 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], $terraIds[0]],
400 ]);
401 expect(false, 'duplicate block should throw');
402} catch (RuntimeException $e) {
403 expect(str_contains($e->getMessage(), 'één vak') || str_contains($e->getMessage(), 'vak'),
404 'duplicate block refused: ' . $e->getMessage());
405}
406
407$snap = $ptsStore->saveCustomPlanet($u, [
408 'name' => 'My World', 'people' => 'My People',
409 'jumpsToClear' => 2.5, 'fallTime' => 2, 'riseTime' => 1,
410 'colors' => $terraIds,
411]);
412expect(!empty($snap['id']) && str_starts_with($snap['id'], 'c_'), 'custom id is c_ + hex');
413expect($snap['custom'] === true, 'snapshot is marked custom');
414expect($snap['name'] === 'My World', 'name stored');
415expect(count($snap['colors']) === 5, 'five colors in snapshot');
416expect($snap['colors'][0]['block'] === $terraIds[0], 'color has registry block id');
417expect($snap['owner_id'] === $u, 'owner_id set');
418
419$listed = $ptsStore->listCustomPlanets($u);
420expect(count($listed) === 1, 'owner lists the planet');
421expect($ptsStore->listCustomPlanets($v) === [], 'other user has no planets');
422
423try {
424 $ptsStore->setPlanet($u, $snap['id']);
425 expect(false, 'setPlanet without a lobby should throw');
426} catch (RuntimeException $e) {
427 expect(true, 'setPlanet requires a lobby: ' . $e->getMessage());
428}
429
430$lobby = $ptsStore->createLobby($u, 'A', 0.3, $snap['id']);
431$view = $ptsStore->viewFor($u);
432$meP = $view['lobby']['players'][0]['planet'] ?? null;
433expect($meP && $meP['id'] === $snap['id'], 'createLobby stores custom planet');
434expect(!empty($meP['custom']), 'presented planet is custom');
435expect(count($meP['colors']) === 5 && $meP['colors'][0]['image'] !== '', 'presented colors include images');
436expect(isset($meP['miss_chance']) && is_float($meP['miss_chance']), 'server sends miss_chance for custom');
437
438$ptsStore->joinLobby($v, 'B', $lobby['code']);
439$viewB = $ptsStore->viewFor($v);
440$seen = null;
441foreach ($viewB['lobby']['players'] as $plr) {
442 if ($plr['planet']['id'] === $snap['id']) { $seen = $plr['planet']; }
443}
444expect($seen !== null, 'other player sees the custom planet snapshot');
445expect(($seen['colors'][2]['block'] ?? '') === $terraIds[2], 'opponent sees block ids');
446
447try {
448 $ptsStore->setPlanet($v, $snap['id']);
449 expect(false, 'cannot pick someone else\'s custom planet');
450} catch (RuntimeException $e) {
451 expect(str_contains($e->getMessage(), 'Onbekende'), 'foreign custom refused: ' . $e->getMessage());
452}
453
454$ptsStore->leaveLobby($u);
455$ptsStore->leaveLobby($v);
456$ptsStore->deleteCustomPlanet($u, $snap['id']);
457expect($ptsStore->listCustomPlanets($u) === [], 'deleted planet is gone');
458
459// Snapshot survives mid-match edits: create, join, start, then edit/delete, opponent still sees original.
460$snap2 = $ptsStore->saveCustomPlanet($u, [
461 'name' => 'Frozen', 'people' => 'Ice',
462 'jumpsToClear' => 3, 'fallTime' => 2, 'riseTime' => 1,
463 'colors' => $terraIds,
464]);
465$lobby2 = $ptsStore->createLobby($u, 'A', 0.3, $snap2['id']);
466$ptsStore->joinLobby($v, 'B', $lobby2['code']);
467$ptsStore->setReady($u, true);
468$ptsStore->setReady($v, true);
469$ptsStore->startGame($u);
470$ptsStore->saveCustomPlanet($u, [
471 'id' => $snap2['id'],
472 'name' => 'Changed', 'people' => 'Ice',
473 'jumpsToClear' => 1, 'fallTime' => 5, 'riseTime' => 3,
474 'colors' => $terraIds,
475]);
476$viewMid = $ptsStore->viewFor($v);
477$midP = null;
478foreach ($viewMid['lobby']['players'] as $plr) {
479 if (($plr['planet']['id'] ?? '') === $snap2['id']) { $midP = $plr['planet']; }
480}
481expect($midP && $midP['name'] === 'Frozen', 'in-match snapshot keeps the original name (got ' . ($midP['name'] ?? '?') . ')');
482expect($midP && almostEqual((float) $midP['jumpsToClear'], 3.0), 'in-match snapshot keeps original gravity');
483$ptsStore->leaveLobby($u);
484$ptsStore->leaveLobby($v);
485
486// Online award is idempotent and server-side.
487$u3 = 'local:online_award_a';
488$v3 = 'local:online_award_b';
489$lob = $ptsStore->createLobby($u3, 'A', 0.0, 'terra');
490$ptsStore->joinLobby($v3, 'B', $lob['code']);
491$ptsStore->setReady($u3, true);
492$ptsStore->setReady($v3, true);
493$ptsStore->startGame($u3);
494$ptsStore->viewFor($u3, null, 80, false, []);
495$ptsStore->viewFor($u3, null, 80, true, []);
496expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the score');
497$ptsStore->viewFor($u3, null, 999, true, []);
498expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');
499
500$ptsStore->setLocale($u, 'nl');
501expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');
502try {
503 $ptsStore->setLocale($u, 'xx');
504 expect(false, 'unknown locale should throw');
505} catch (RuntimeException $e) {
506 expect(true, 'unknown locale refused');
507}
508
300echo "\nConfig helpers\n";
509echo "\nConfig helpers\n";
301
510
511
302$cfg = config();
512$cfg = config();
303expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
513expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
304expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
514expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
src/blocks.js added +160 −0
@@ -0,0 +1,160 @@
1 'use strict';
2
3 /**
4 * Append-only block registry. Thresholds and order stay in lockstep with
5 * server/lib/Blocks.php: Terra's first five are free; the next costs 500
6 * lifetime points; each one after that costs 14.5% more (rounded, always
7 * strictly increasing). Points are a requirement, not a spend.
8 */
9
10 var Blocks = (function ()
11 {
12 var TERRA_COUNT = 5;
13 var FIRST_THRESHOLD = 500;
14 var GROWTH = 1.145;
15 var _all = null;
16
17 function loadRegistry ()
18 {
19 if (_all)
20 { return _all; }
21 var data = null;
22 if (typeof BLOCK_REGISTRY !== 'undefined' && BLOCK_REGISTRY && BLOCK_REGISTRY.blocks)
23 { data = BLOCK_REGISTRY; }
24 else if (typeof require !== 'undefined')
25 {
26 try
27 { data = require('../server/lib/blocks.json'); }
28 catch (e) { data = null; }
29 }
30 _all = (data && data.blocks) ? data.blocks.slice() : [];
31 return _all;
32 }
33
34 function all ()
35 {
36 return loadRegistry();
37 }
38
39 function byId (id)
40 {
41 var list = all();
42 for (var i = 0; i < list.length; i++)
43 {
44 if (list[i].id === id)
45 { return list[i]; }
46 }
47 return null;
48 }
49
50 function indexOf (id)
51 {
52 var list = all();
53 for (var i = 0; i < list.length; i++)
54 {
55 if (list[i].id === id)
56 { return i; }
57 }
58 return -1;
59 }
60
61 function threshold (index)
62 {
63 if (index < TERRA_COUNT)
64 { return 0; }
65 var t = FIRST_THRESHOLD;
66 for (var i = TERRA_COUNT; i < index; i++)
67 {
68 var next = Math.round(t * GROWTH);
69 t = Math.max(t + 1, next);
70 }
71 return t;
72 }
73
74 function unlocked (index, points)
75 {
76 points = points || 0;
77 return points >= threshold(index);
78 }
79
80 function unlockedId (id, points)
81 {
82 var i = indexOf(id);
83 return i >= 0 && unlocked(i, points);
84 }
85
86 function present (points)
87 {
88 points = points || 0;
89 var list = all();
90 var out = [];
91 for (var i = 0; i < list.length; i++)
92 {
93 var b = list[i];
94 var need = threshold(i);
95 out.push({
96 id: b.id,
97 name: b.name || b.id,
98 hex: b.hex,
99 shape: b.shape,
100 image: b.image,
101 terra: !!b.terra || i < TERRA_COUNT,
102 index: i,
103 threshold: need,
104 unlocked: points >= need
105 });
106 }
107 return out;
108 }
109
110 function asColor (id, slot)
111 {
112 var b = byId(id);
113 if (!b)
114 { return null; }
115 return {
116 id: slot,
117 block: b.id,
118 name: b.name || b.id,
119 hex: b.hex,
120 shape: b.shape,
121 image: b.image
122 };
123 }
124
125 function images ()
126 {
127 var list = all();
128 var out = [];
129 var seen = Object.create(null);
130 for (var i = 0; i < list.length; i++)
131 {
132 var url = list[i].image;
133 if (!url || seen[url])
134 { continue; }
135 seen[url] = true;
136 out.push({ name: 'block:' + list[i].id, url: url });
137 }
138 return out;
139 }
140
141 return {
142 TERRA_COUNT: TERRA_COUNT,
143 FIRST_THRESHOLD: FIRST_THRESHOLD,
144 GROWTH: GROWTH,
145 all: all,
146 byId: byId,
147 indexOf: indexOf,
148 threshold: threshold,
149 unlocked: unlocked,
150 unlockedId: unlockedId,
151 present: present,
152 asColor: asColor,
153 images: images
154 };
155 })();
156
157 if (typeof module !== 'undefined' && module.exports)
158 { module.exports = Blocks; }
159 else if (typeof globalThis !== 'undefined')
160 { globalThis.Blocks = Blocks; }
@@ -0,0 +1,160 @@
1'use strict';
2
3/**
4 * Append-only block registry. Thresholds and order stay in lockstep with
5 * server/lib/Blocks.php: Terra's first five are free; the next costs 500
6 * lifetime points; each one after that costs 14.5% more (rounded, always
7 * strictly increasing). Points are a requirement, not a spend.
8 */
9
10var Blocks = (function ()
11{
12 var TERRA_COUNT = 5;
13 var FIRST_THRESHOLD = 500;
14 var GROWTH = 1.145;
15 var _all = null;
16
17 function loadRegistry ()
18 {
19 if (_all)
20 { return _all; }
21 var data = null;
22 if (typeof BLOCK_REGISTRY !== 'undefined' && BLOCK_REGISTRY && BLOCK_REGISTRY.blocks)
23 { data = BLOCK_REGISTRY; }
24 else if (typeof require !== 'undefined')
25 {
26 try
27 { data = require('../server/lib/blocks.json'); }
28 catch (e) { data = null; }
29 }
30 _all = (data && data.blocks) ? data.blocks.slice() : [];
31 return _all;
32 }
33
34 function all ()
35 {
36 return loadRegistry();
37 }
38
39 function byId (id)
40 {
41 var list = all();
42 for (var i = 0; i < list.length; i++)
43 {
44 if (list[i].id === id)
45 { return list[i]; }
46 }
47 return null;
48 }
49
50 function indexOf (id)
51 {
52 var list = all();
53 for (var i = 0; i < list.length; i++)
54 {
55 if (list[i].id === id)
56 { return i; }
57 }
58 return -1;
59 }
60
61 function threshold (index)
62 {
63 if (index < TERRA_COUNT)
64 { return 0; }
65 var t = FIRST_THRESHOLD;
66 for (var i = TERRA_COUNT; i < index; i++)
67 {
68 var next = Math.round(t * GROWTH);
69 t = Math.max(t + 1, next);
70 }
71 return t;
72 }
73
74 function unlocked (index, points)
75 {
76 points = points || 0;
77 return points >= threshold(index);
78 }
79
80 function unlockedId (id, points)
81 {
82 var i = indexOf(id);
83 return i >= 0 && unlocked(i, points);
84 }
85
86 function present (points)
87 {
88 points = points || 0;
89 var list = all();
90 var out = [];
91 for (var i = 0; i < list.length; i++)
92 {
93 var b = list[i];
94 var need = threshold(i);
95 out.push({
96 id: b.id,
97 name: b.name || b.id,
98 hex: b.hex,
99 shape: b.shape,
100 image: b.image,
101 terra: !!b.terra || i < TERRA_COUNT,
102 index: i,
103 threshold: need,
104 unlocked: points >= need
105 });
106 }
107 return out;
108 }
109
110 function asColor (id, slot)
111 {
112 var b = byId(id);
113 if (!b)
114 { return null; }
115 return {
116 id: slot,
117 block: b.id,
118 name: b.name || b.id,
119 hex: b.hex,
120 shape: b.shape,
121 image: b.image
122 };
123 }
124
125 function images ()
126 {
127 var list = all();
128 var out = [];
129 var seen = Object.create(null);
130 for (var i = 0; i < list.length; i++)
131 {
132 var url = list[i].image;
133 if (!url || seen[url])
134 { continue; }
135 seen[url] = true;
136 out.push({ name: 'block:' + list[i].id, url: url });
137 }
138 return out;
139 }
140
141 return {
142 TERRA_COUNT: TERRA_COUNT,
143 FIRST_THRESHOLD: FIRST_THRESHOLD,
144 GROWTH: GROWTH,
145 all: all,
146 byId: byId,
147 indexOf: indexOf,
148 threshold: threshold,
149 unlocked: unlocked,
150 unlockedId: unlockedId,
151 present: present,
152 asColor: asColor,
153 images: images
154 };
155})();
156
157if (typeof module !== 'undefined' && module.exports)
158{ module.exports = Blocks; }
159else if (typeof globalThis !== 'undefined')
160{ globalThis.Blocks = Blocks; }
src/build.sh +6 −0
@@ -15,11 +15,13 @@ rm -f "$BUILD_FILE"
15 15 FILES=(
16 16 "$SRC_DIR/rng.js"
17 17 "$SRC_DIR/planet.js"
18 "$SRC_DIR/blocks.js"
18 19 "$SRC_DIR/easing.js"
19 20 "$SRC_DIR/gameCore.js"
20 21 "$SRC_DIR/miniLayout.js"
21 22 "$SRC_DIR/online.js"
22 23 "$SRC_DIR/offline.js"
24 "$SRC_DIR/designer.js"
23 25 "$SRC_DIR/main.js"
24 26 )
25 27
@@ -31,6 +33,9 @@ FILES=(
31 33 printf '%s' "var PLANET_CATALOG = "
32 34 cat "$ROOT/server/lib/planets.json"
33 35 printf ';\n'
36 printf '%s' "var BLOCK_REGISTRY = "
37 cat "$ROOT/server/lib/blocks.json"
38 printf ';\n'
34 39 } >> "$BUILD_FILE"
35 40
36 41 for file in "${FILES[@]}"
@@ -55,6 +60,7 @@ cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
55 60 mkdir -p "$ROOT/build/lib"
56 61 cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
57 62 "$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \
63 "$SERVER/lib/Blocks.php" "$SERVER/lib/blocks.json" \
58 64 "$ROOT/build/lib/"
59 65 mkdir -p "$ROOT/build/data"
60 66 cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
@@ -15,11 +15,13 @@ rm -f "$BUILD_FILE"
15FILES=(
15FILES=(
16 "$SRC_DIR/rng.js"
16 "$SRC_DIR/rng.js"
17 "$SRC_DIR/planet.js"
17 "$SRC_DIR/planet.js"
18 "$SRC_DIR/blocks.js"
18 "$SRC_DIR/easing.js"
19 "$SRC_DIR/easing.js"
19 "$SRC_DIR/gameCore.js"
20 "$SRC_DIR/gameCore.js"
20 "$SRC_DIR/miniLayout.js"
21 "$SRC_DIR/miniLayout.js"
21 "$SRC_DIR/online.js"
22 "$SRC_DIR/online.js"
22 "$SRC_DIR/offline.js"
23 "$SRC_DIR/offline.js"
24 "$SRC_DIR/designer.js"
23 "$SRC_DIR/main.js"
25 "$SRC_DIR/main.js"
24)
26)
25
27
@@ -31,6 +33,9 @@ FILES=(
31 printf '%s' "var PLANET_CATALOG = "
33 printf '%s' "var PLANET_CATALOG = "
32 cat "$ROOT/server/lib/planets.json"
34 cat "$ROOT/server/lib/planets.json"
33 printf ';\n'
35 printf ';\n'
36 printf '%s' "var BLOCK_REGISTRY = "
37 cat "$ROOT/server/lib/blocks.json"
38 printf ';\n'
34} >> "$BUILD_FILE"
39} >> "$BUILD_FILE"
35
40
36for file in "${FILES[@]}"
41for file in "${FILES[@]}"
@@ -55,6 +60,7 @@ cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
55mkdir -p "$ROOT/build/lib"
60mkdir -p "$ROOT/build/lib"
56cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
61cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
57 "$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \
62 "$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \
63 "$SERVER/lib/Blocks.php" "$SERVER/lib/blocks.json" \
58 "$ROOT/build/lib/"
64 "$ROOT/build/lib/"
59mkdir -p "$ROOT/build/data"
65mkdir -p "$ROOT/build/data"
60cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
66cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
src/designer.js added +529 −0
@@ -0,0 +1,529 @@
1 'use strict';
2
3 /**
4 * Planeetontwerper (t1139). Only available on the main menu when the
5 * player is logged in. Talks to api.php through Online.
6 */
7 var Designer = {
8 openSlot: 0,
9 editingId: null,
10 slots: [null, null, null, null, null],
11 dirty: false
12 };
13
14 Designer._blocks = function ()
15 {
16 if (typeof Blocks !== 'undefined')
17 { return Blocks; }
18 if (typeof require !== 'undefined')
19 {
20 try
21 { return require('./blocks.js'); }
22 catch (e)
23 { return null; }
24 }
25 return null;
26 };
27
28 Designer.defaultSlots = function ()
29 {
30 var B = Designer._blocks();
31 var all = B ? B.all() : [];
32 var ids = [];
33 for (var i = 0; i < 5 && i < all.length; i++)
34 { ids.push(all[i].id); }
35 return ids;
36 };
37
38 Designer.points = function ()
39 {
40 return (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
41 };
42
43 Designer.blocks = function ()
44 {
45 if (typeof Online !== 'undefined' && Online.blocks && Online.blocks.length)
46 { return Online.blocks; }
47 var B = Designer._blocks();
48 if (B)
49 { return B.present(Designer.points()); }
50 return [];
51 };
52
53 Designer.planets = function ()
54 {
55 if (typeof Planet !== 'undefined' && Planet.customPlanets)
56 { return Planet.customPlanets(); }
57 return (typeof Online !== 'undefined' && Online.planets) || [];
58 };
59
60 Designer.openList = function ()
61 {
62 if (typeof Online === 'undefined' || !Online.me)
63 { return; }
64 if (typeof app !== 'undefined')
65 { app.mode = 'designer'; }
66 hideIf('menu');
67 hideIf('planet-select');
68 hideIf('online-panel');
69 hideIf('designer-edit');
70 showIf('designer');
71 Designer.renderList();
72 };
73
74 Designer.close = function ()
75 {
76 hideIf('designer');
77 hideIf('designer-edit');
78 Designer.closeModal();
79 if (typeof app !== 'undefined')
80 { app.mode = 'menu'; }
81 showIf('menu');
82 if (typeof refreshMenuAccount === 'function')
83 { refreshMenuAccount(); }
84 if (typeof renderPlanetGrid === 'function')
85 {
86 renderPlanetGrid('planet-grid', false);
87 renderPlanetGrid('lobby-planet-grid', true);
88 }
89 };
90
91 Designer.renderList = function ()
92 {
93 var box = document.getElementById('designer-list');
94 var pts = document.getElementById('designer-points');
95 if (pts)
96 { pts.textContent = String(Designer.points()); }
97 if (!box)
98 { return; }
99 box.innerHTML = '';
100 var planets = Designer.planets();
101 if (!planets.length)
102 {
103 var empty = document.createElement('p');
104 empty.className = 'hint';
105 empty.textContent = 'Je hebt nog geen eigen planeten. Maak er een aan.';
106 box.appendChild(empty);
107 return;
108 }
109 for (var i = 0; i < planets.length; i++)
110 {
111 var pl = planets[i];
112 if (typeof Planet !== 'undefined' && Planet.planetFromData && !pl.baseJumpHeight)
113 { pl = Planet.planetFromData(pl); }
114 var card = document.createElement('div');
115 card.className = 'planet-card designer-card';
116 var swatches = '';
117 var colors = pl.colors || [];
118 for (var c = 0; c < colors.length; c++)
119 {
120 swatches += '<img src="' + Designer.esc(colors[c].image) + '" alt="'
121 + Designer.esc(colors[c].name) + '">';
122 }
123 var stats = (typeof Planet !== 'undefined' && Planet.formatStats)
124 ? Planet.formatStats(pl) : '';
125 card.innerHTML = '<div class="planet-title">' + Designer.esc(pl.name) + '</div>'
126 + '<div class="planet-people">' + Designer.esc(pl.people) + '</div>'
127 + '<div class="planet-nums">' + Designer.esc(stats) + '</div>'
128 + '<div class="planet-swatches">' + swatches + '</div>'
129 + '<div class="designer-card-actions">'
130 + '<button type="button" class="btn-tiny" data-edit>Bewerken</button>'
131 + '<button type="button" class="btn-tiny btn-danger-lite" data-del>Verwijderen</button>'
132 + '</div>';
133 (function (id)
134 {
135 card.querySelector('[data-edit]').addEventListener('click', function ()
136 { Designer.openEdit(id); });
137 card.querySelector('[data-del]').addEventListener('click', function ()
138 { Designer.confirmDelete(id); });
139 })(pl.id);
140 box.appendChild(card);
141 }
142 };
143
144 Designer.confirmDelete = function (id)
145 {
146 var pl = Designer.planetById(id);
147 var name = pl ? pl.name : id;
148 if (!window.confirm('Wil je de planeet “' + name + '” verwijderen?'))
149 { return; }
150 Online.deletePlanet(id).then(function (data)
151 {
152 if (!data || !data.ok)
153 {
154 window.alert((data && data.error) || 'Verwijderen is mislukt.');
155 return;
156 }
157 Designer.renderList();
158 if (typeof renderPlanetGrid === 'function')
159 {
160 renderPlanetGrid('planet-grid', false);
161 renderPlanetGrid('lobby-planet-grid', true);
162 }
163 });
164 };
165
166 Designer.planetById = function (id)
167 {
168 var list = Designer.planets();
169 for (var i = 0; i < list.length; i++)
170 {
171 if (list[i].id === id)
172 { return list[i]; }
173 }
174 return null;
175 };
176
177 Designer.openEdit = function (id)
178 {
179 var pl = id ? Designer.planetById(id) : null;
180 Designer.editingId = pl ? pl.id : null;
181 if (pl)
182 {
183 Designer.slots = [];
184 for (var i = 0; i < 5; i++)
185 {
186 var c = pl.colors && pl.colors[i];
187 Designer.slots[i] = c ? (c.block || c.id) : Designer.defaultSlots()[i];
188 // c.id is the slot index 0-4 on snapshots; prefer c.block
189 if (c && c.block)
190 { Designer.slots[i] = c.block; }
191 else if (c && typeof c.id === 'string')
192 { Designer.slots[i] = c.id; }
193 }
194 document.getElementById('des-name').value = pl.name || '';
195 document.getElementById('des-people').value = pl.people || '';
196 document.getElementById('des-gravity').value = String(pl.jumpsToClear != null ? pl.jumpsToClear : 2);
197 document.getElementById('des-air').value = String(pl.fallTime != null ? pl.fallTime : 3);
198 document.getElementById('des-mass').value = String(pl.riseTime != null ? pl.riseTime : 1.5);
199 document.getElementById('designer-edit-title').textContent = 'Planeet bewerken';
200 document.getElementById('btn-designer-delete').hidden = false;
201 }
202 else
203 {
204 Designer.slots = Designer.defaultSlots().slice();
205 document.getElementById('des-name').value = '';
206 document.getElementById('des-people').value = '';
207 document.getElementById('des-gravity').value = '2';
208 document.getElementById('des-air').value = '3';
209 document.getElementById('des-mass').value = '1.5';
210 document.getElementById('designer-edit-title').textContent = 'Nieuwe planeet';
211 document.getElementById('btn-designer-delete').hidden = true;
212 }
213 hideIf('designer');
214 showIf('designer-edit');
215 Designer.syncPreview();
216 Designer.renderSlots();
217 var name = document.getElementById('des-name');
218 if (name)
219 { name.focus(); }
220 };
221
222 Designer.draftPlanet = function ()
223 {
224 var jumps = clampNum(document.getElementById('des-gravity').value, 1, 4, 2);
225 var fall = clampNum(document.getElementById('des-air').value, 1, 5, 3);
226 var rise = clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5);
227 var colors = [];
228 for (var i = 0; i < 5; i++)
229 {
230 var B = Designer._blocks();
231 var col = B ? B.asColor(Designer.slots[i], i) : null;
232 if (col)
233 { colors.push(col); }
234 }
235 var opts = {
236 id: Designer.editingId || 'draft',
237 name: (document.getElementById('des-name').value || 'Nieuwe planeet').trim() || 'Nieuwe planeet',
238 people: (document.getElementById('des-people').value || 'Volk').trim() || 'Volk',
239 jumpsToClear: jumps,
240 fallTime: fall,
241 riseTime: rise,
242 colors: colors
243 };
244 if (typeof Planet === 'undefined')
245 { return opts; }
246 return Planet.createPlanet ? (function ()
247 {
248 var p = Planet.createPlanet(opts);
249 p.id = opts.id;
250 p.custom = true;
251 return p;
252 })() : opts;
253 };
254
255 Designer.syncPreview = function ()
256 {
257 var p = Designer.draftPlanet();
258 var d = (typeof Planet !== 'undefined' && Planet.displayValues) ? Planet.displayValues(p) : null;
259 setText('des-gravity-val', Number(document.getElementById('des-gravity').value).toFixed(1)
260 + (d ? ' · g ' + d.gravity.toFixed(2) : ''));
261 setText('des-air-val', Number(document.getElementById('des-air').value).toFixed(1)
262 + (d ? ' · d ' + d.density.toFixed(2) : ''));
263 setText('des-mass-val', Number(document.getElementById('des-mass').value).toFixed(1)
264 + (d ? ' · F ' + Math.round(d.newtons) + ' N' : ''));
265 var power = d ? d.power : 0;
266 setText('des-power', 'Power ' + power + '%');
267 };
268
269 Designer.renderSlots = function ()
270 {
271 var row = document.getElementById('des-slots');
272 if (!row)
273 { return; }
274 row.innerHTML = '';
275 for (var i = 0; i < 5; i++)
276 {
277 var id = Designer.slots[i];
278 var B = Designer._blocks();
279 var b = B ? B.byId(id) : null;
280 var btn = document.createElement('button');
281 btn.type = 'button';
282 btn.className = 'des-slot';
283 btn.setAttribute('aria-label', 'Blokje ' + (i + 1));
284 if (b)
285 {
286 btn.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="' + Designer.esc(b.name) + '">'
287 + '<span>' + Designer.esc(b.name) + '</span>';
288 }
289 else
290 {
291 btn.innerHTML = '<span class="des-slot-empty">Kies</span>';
292 }
293 (function (slot)
294 {
295 btn.addEventListener('click', function ()
296 { Designer.openModal(slot); });
297 })(i);
298 row.appendChild(btn);
299 }
300 };
301
302 Designer.openModal = function (slot)
303 {
304 Designer.openSlot = slot;
305 var modal = document.getElementById('des-modal');
306 var grid = document.getElementById('des-modal-grid');
307 if (!modal || !grid)
308 { return; }
309 grid.innerHTML = '';
310 var blocks = Designer.blocks();
311 var used = Object.create(null);
312 for (var i = 0; i < 5; i++)
313 {
314 if (i !== slot && Designer.slots[i])
315 { used[Designer.slots[i]] = true; }
316 }
317 for (var i = 0; i < blocks.length; i++)
318 {
319 var b = blocks[i];
320 var cell = document.createElement('button');
321 cell.type = 'button';
322 cell.className = 'des-block';
323 cell.dataset.id = b.id;
324 var locked = !b.unlocked;
325 var taken = !!used[b.id];
326 if (locked)
327 { cell.classList.add('locked'); }
328 if (taken)
329 { cell.classList.add('used'); }
330 if (Designer.slots[slot] === b.id)
331 { cell.classList.add('current'); }
332 var title = b.name;
333 if (locked)
334 { title += ' — ' + b.threshold + ' punten nodig'; }
335 else if (taken)
336 { title += ' — al in een ander vak'; }
337 cell.title = title;
338 cell.setAttribute('aria-label', title);
339 cell.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="">'
340 + (locked ? '<span class="des-lock" aria-hidden="true">'
341 + '<svg viewBox="0 0 18 18" width="16" height="16">'
342 + '<rect x="4" y="8" width="10" height="8" rx="1.5" fill="#ffe27a"/>'
343 + '<path d="M6 8 V6 a3 3 0 0 1 6 0 v2" fill="none" stroke="#ffe27a" stroke-width="1.8" stroke-linecap="round"/>'
344 + '<circle cx="9" cy="12" r="1.2" fill="#1a1628"/>'
345 + '</svg></span>' : '')
346 + '<span class="des-block-name">' + Designer.esc(b.name) + '</span>'
347 + (locked ? '<span class="des-block-need">' + b.threshold + '</span>' : '');
348 if (locked || taken)
349 { cell.disabled = true; }
350 else
351 {
352 cell.addEventListener('click', (function (id)
353 {
354 return function ()
355 {
356 Designer.slots[Designer.openSlot] = id;
357 Designer.closeModal();
358 Designer.renderSlots();
359 };
360 })(b.id));
361 }
362 grid.appendChild(cell);
363 }
364 modal.hidden = false;
365 modal.setAttribute('aria-hidden', 'false');
366 var close = document.getElementById('des-modal-close');
367 if (close)
368 { close.focus(); }
369 };
370
371 Designer.closeModal = function ()
372 {
373 var modal = document.getElementById('des-modal');
374 if (!modal)
375 { return; }
376 modal.hidden = true;
377 modal.setAttribute('aria-hidden', 'true');
378 };
379
380 Designer.save = function ()
381 {
382 var name = (document.getElementById('des-name').value || '').trim();
383 var people = (document.getElementById('des-people').value || '').trim();
384 if (!name || !people)
385 {
386 window.alert('Vul een naam voor de planeet en voor de bevolking in.');
387 return;
388 }
389 for (var i = 0; i < 5; i++)
390 {
391 if (!Designer.slots[i])
392 {
393 window.alert('Kies vijf blokjes.');
394 return;
395 }
396 }
397 var payload = {
398 id: Designer.editingId || undefined,
399 name: name,
400 people: people,
401 jumpsToClear: clampNum(document.getElementById('des-gravity').value, 1, 4, 2),
402 fallTime: clampNum(document.getElementById('des-air').value, 1, 5, 3),
403 riseTime: clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5),
404 colors: Designer.slots.slice()
405 };
406 Online.savePlanet(payload).then(function (data)
407 {
408 if (!data || !data.ok)
409 {
410 window.alert((data && data.error) || 'Opslaan is mislukt.');
411 return;
412 }
413 hideIf('designer-edit');
414 showIf('designer');
415 Designer.editingId = data.planet ? data.planet.id : null;
416 Designer.renderList();
417 if (typeof renderPlanetGrid === 'function')
418 {
419 renderPlanetGrid('planet-grid', false);
420 renderPlanetGrid('lobby-planet-grid', true);
421 }
422 });
423 };
424
425 Designer.bind = function ()
426 {
427 var btn = document.getElementById('btn-designer');
428 if (btn)
429 { btn.addEventListener('click', function () { Designer.openList(); }); }
430 var back = document.getElementById('btn-designer-back');
431 if (back)
432 { back.addEventListener('click', Designer.close); }
433 var neu = document.getElementById('btn-designer-new');
434 if (neu)
435 { neu.addEventListener('click', function () { Designer.openEdit(null); }); }
436 var cancel = document.getElementById('btn-designer-cancel');
437 if (cancel)
438 {
439 cancel.addEventListener('click', function ()
440 {
441 hideIf('designer-edit');
442 showIf('designer');
443 Designer.renderList();
444 });
445 }
446 var save = document.getElementById('btn-designer-save');
447 if (save)
448 { save.addEventListener('click', function (e) { e.preventDefault(); Designer.save(); }); }
449 var form = document.getElementById('designer-form');
450 if (form)
451 { form.addEventListener('submit', function (e) { e.preventDefault(); Designer.save(); }); }
452 var del = document.getElementById('btn-designer-delete');
453 if (del)
454 {
455 del.addEventListener('click', function ()
456 {
457 if (!Designer.editingId)
458 { return; }
459 Designer.confirmDelete(Designer.editingId);
460 hideIf('designer-edit');
461 showIf('designer');
462 });
463 }
464 ['des-gravity', 'des-air', 'des-mass'].forEach(function (id)
465 {
466 var el = document.getElementById(id);
467 if (!el)
468 { return; }
469 el.addEventListener('input', Designer.syncPreview);
470 });
471 var modal = document.getElementById('des-modal');
472 if (modal)
473 {
474 modal.addEventListener('click', function (e)
475 {
476 if (e.target === modal)
477 { Designer.closeModal(); }
478 });
479 }
480 var close = document.getElementById('des-modal-close');
481 if (close)
482 { close.addEventListener('click', Designer.closeModal); }
483 document.addEventListener('keydown', function (e)
484 {
485 if (e.key === 'Escape')
486 { Designer.closeModal(); }
487 });
488 };
489
490 Designer.esc = function (s)
491 {
492 return String(s == null ? '' : s)
493 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
494 .replace(/"/g, '&quot;');
495 };
496
497 function hideIf (id)
498 {
499 var el = document.getElementById(id);
500 if (el)
501 { el.hidden = true; }
502 }
503
504 function showIf (id)
505 {
506 var el = document.getElementById(id);
507 if (el)
508 { el.hidden = false; }
509 }
510
511 function setText (id, text)
512 {
513 var el = document.getElementById(id);
514 if (el)
515 { el.textContent = text; }
516 }
517
518 function clampNum (v, lo, hi, fallback)
519 {
520 var n = Number(v);
521 if (!isFinite(n))
522 { n = fallback; }
523 return Math.max(lo, Math.min(hi, n));
524 }
525
526 if (typeof module !== 'undefined' && module.exports)
527 { module.exports = Designer; }
528 else if (typeof globalThis !== 'undefined')
529 { globalThis.Designer = Designer; }
@@ -0,0 +1,529 @@
1'use strict';
2
3/**
4 * Planeetontwerper (t1139). Only available on the main menu when the
5 * player is logged in. Talks to api.php through Online.
6 */
7var Designer = {
8 openSlot: 0,
9 editingId: null,
10 slots: [null, null, null, null, null],
11 dirty: false
12};
13
14Designer._blocks = function ()
15{
16 if (typeof Blocks !== 'undefined')
17 { return Blocks; }
18 if (typeof require !== 'undefined')
19 {
20 try
21 { return require('./blocks.js'); }
22 catch (e)
23 { return null; }
24 }
25 return null;
26};
27
28Designer.defaultSlots = function ()
29{
30 var B = Designer._blocks();
31 var all = B ? B.all() : [];
32 var ids = [];
33 for (var i = 0; i < 5 && i < all.length; i++)
34 { ids.push(all[i].id); }
35 return ids;
36};
37
38Designer.points = function ()
39{
40 return (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
41};
42
43Designer.blocks = function ()
44{
45 if (typeof Online !== 'undefined' && Online.blocks && Online.blocks.length)
46 { return Online.blocks; }
47 var B = Designer._blocks();
48 if (B)
49 { return B.present(Designer.points()); }
50 return [];
51};
52
53Designer.planets = function ()
54{
55 if (typeof Planet !== 'undefined' && Planet.customPlanets)
56 { return Planet.customPlanets(); }
57 return (typeof Online !== 'undefined' && Online.planets) || [];
58};
59
60Designer.openList = function ()
61{
62 if (typeof Online === 'undefined' || !Online.me)
63 { return; }
64 if (typeof app !== 'undefined')
65 { app.mode = 'designer'; }
66 hideIf('menu');
67 hideIf('planet-select');
68 hideIf('online-panel');
69 hideIf('designer-edit');
70 showIf('designer');
71 Designer.renderList();
72};
73
74Designer.close = function ()
75{
76 hideIf('designer');
77 hideIf('designer-edit');
78 Designer.closeModal();
79 if (typeof app !== 'undefined')
80 { app.mode = 'menu'; }
81 showIf('menu');
82 if (typeof refreshMenuAccount === 'function')
83 { refreshMenuAccount(); }
84 if (typeof renderPlanetGrid === 'function')
85 {
86 renderPlanetGrid('planet-grid', false);
87 renderPlanetGrid('lobby-planet-grid', true);
88 }
89};
90
91Designer.renderList = function ()
92{
93 var box = document.getElementById('designer-list');
94 var pts = document.getElementById('designer-points');
95 if (pts)
96 { pts.textContent = String(Designer.points()); }
97 if (!box)
98 { return; }
99 box.innerHTML = '';
100 var planets = Designer.planets();
101 if (!planets.length)
102 {
103 var empty = document.createElement('p');
104 empty.className = 'hint';
105 empty.textContent = 'Je hebt nog geen eigen planeten. Maak er een aan.';
106 box.appendChild(empty);
107 return;
108 }
109 for (var i = 0; i < planets.length; i++)
110 {
111 var pl = planets[i];
112 if (typeof Planet !== 'undefined' && Planet.planetFromData && !pl.baseJumpHeight)
113 { pl = Planet.planetFromData(pl); }
114 var card = document.createElement('div');
115 card.className = 'planet-card designer-card';
116 var swatches = '';
117 var colors = pl.colors || [];
118 for (var c = 0; c < colors.length; c++)
119 {
120 swatches += '<img src="' + Designer.esc(colors[c].image) + '" alt="'
121 + Designer.esc(colors[c].name) + '">';
122 }
123 var stats = (typeof Planet !== 'undefined' && Planet.formatStats)
124 ? Planet.formatStats(pl) : '';
125 card.innerHTML = '<div class="planet-title">' + Designer.esc(pl.name) + '</div>'
126 + '<div class="planet-people">' + Designer.esc(pl.people) + '</div>'
127 + '<div class="planet-nums">' + Designer.esc(stats) + '</div>'
128 + '<div class="planet-swatches">' + swatches + '</div>'
129 + '<div class="designer-card-actions">'
130 + '<button type="button" class="btn-tiny" data-edit>Bewerken</button>'
131 + '<button type="button" class="btn-tiny btn-danger-lite" data-del>Verwijderen</button>'
132 + '</div>';
133 (function (id)
134 {
135 card.querySelector('[data-edit]').addEventListener('click', function ()
136 { Designer.openEdit(id); });
137 card.querySelector('[data-del]').addEventListener('click', function ()
138 { Designer.confirmDelete(id); });
139 })(pl.id);
140 box.appendChild(card);
141 }
142};
143
144Designer.confirmDelete = function (id)
145{
146 var pl = Designer.planetById(id);
147 var name = pl ? pl.name : id;
148 if (!window.confirm('Wil je de planeet “' + name + '” verwijderen?'))
149 { return; }
150 Online.deletePlanet(id).then(function (data)
151 {
152 if (!data || !data.ok)
153 {
154 window.alert((data && data.error) || 'Verwijderen is mislukt.');
155 return;
156 }
157 Designer.renderList();
158 if (typeof renderPlanetGrid === 'function')
159 {
160 renderPlanetGrid('planet-grid', false);
161 renderPlanetGrid('lobby-planet-grid', true);
162 }
163 });
164};
165
166Designer.planetById = function (id)
167{
168 var list = Designer.planets();
169 for (var i = 0; i < list.length; i++)
170 {
171 if (list[i].id === id)
172 { return list[i]; }
173 }
174 return null;
175};
176
177Designer.openEdit = function (id)
178{
179 var pl = id ? Designer.planetById(id) : null;
180 Designer.editingId = pl ? pl.id : null;
181 if (pl)
182 {
183 Designer.slots = [];
184 for (var i = 0; i < 5; i++)
185 {
186 var c = pl.colors && pl.colors[i];
187 Designer.slots[i] = c ? (c.block || c.id) : Designer.defaultSlots()[i];
188 // c.id is the slot index 0-4 on snapshots; prefer c.block
189 if (c && c.block)
190 { Designer.slots[i] = c.block; }
191 else if (c && typeof c.id === 'string')
192 { Designer.slots[i] = c.id; }
193 }
194 document.getElementById('des-name').value = pl.name || '';
195 document.getElementById('des-people').value = pl.people || '';
196 document.getElementById('des-gravity').value = String(pl.jumpsToClear != null ? pl.jumpsToClear : 2);
197 document.getElementById('des-air').value = String(pl.fallTime != null ? pl.fallTime : 3);
198 document.getElementById('des-mass').value = String(pl.riseTime != null ? pl.riseTime : 1.5);
199 document.getElementById('designer-edit-title').textContent = 'Planeet bewerken';
200 document.getElementById('btn-designer-delete').hidden = false;
201 }
202 else
203 {
204 Designer.slots = Designer.defaultSlots().slice();
205 document.getElementById('des-name').value = '';
206 document.getElementById('des-people').value = '';
207 document.getElementById('des-gravity').value = '2';
208 document.getElementById('des-air').value = '3';
209 document.getElementById('des-mass').value = '1.5';
210 document.getElementById('designer-edit-title').textContent = 'Nieuwe planeet';
211 document.getElementById('btn-designer-delete').hidden = true;
212 }
213 hideIf('designer');
214 showIf('designer-edit');
215 Designer.syncPreview();
216 Designer.renderSlots();
217 var name = document.getElementById('des-name');
218 if (name)
219 { name.focus(); }
220};
221
222Designer.draftPlanet = function ()
223{
224 var jumps = clampNum(document.getElementById('des-gravity').value, 1, 4, 2);
225 var fall = clampNum(document.getElementById('des-air').value, 1, 5, 3);
226 var rise = clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5);
227 var colors = [];
228 for (var i = 0; i < 5; i++)
229 {
230 var B = Designer._blocks();
231 var col = B ? B.asColor(Designer.slots[i], i) : null;
232 if (col)
233 { colors.push(col); }
234 }
235 var opts = {
236 id: Designer.editingId || 'draft',
237 name: (document.getElementById('des-name').value || 'Nieuwe planeet').trim() || 'Nieuwe planeet',
238 people: (document.getElementById('des-people').value || 'Volk').trim() || 'Volk',
239 jumpsToClear: jumps,
240 fallTime: fall,
241 riseTime: rise,
242 colors: colors
243 };
244 if (typeof Planet === 'undefined')
245 { return opts; }
246 return Planet.createPlanet ? (function ()
247 {
248 var p = Planet.createPlanet(opts);
249 p.id = opts.id;
250 p.custom = true;
251 return p;
252 })() : opts;
253};
254
255Designer.syncPreview = function ()
256{
257 var p = Designer.draftPlanet();
258 var d = (typeof Planet !== 'undefined' && Planet.displayValues) ? Planet.displayValues(p) : null;
259 setText('des-gravity-val', Number(document.getElementById('des-gravity').value).toFixed(1)
260 + (d ? ' · g ' + d.gravity.toFixed(2) : ''));
261 setText('des-air-val', Number(document.getElementById('des-air').value).toFixed(1)
262 + (d ? ' · d ' + d.density.toFixed(2) : ''));
263 setText('des-mass-val', Number(document.getElementById('des-mass').value).toFixed(1)
264 + (d ? ' · F ' + Math.round(d.newtons) + ' N' : ''));
265 var power = d ? d.power : 0;
266 setText('des-power', 'Power ' + power + '%');
267};
268
269Designer.renderSlots = function ()
270{
271 var row = document.getElementById('des-slots');
272 if (!row)
273 { return; }
274 row.innerHTML = '';
275 for (var i = 0; i < 5; i++)
276 {
277 var id = Designer.slots[i];
278 var B = Designer._blocks();
279 var b = B ? B.byId(id) : null;
280 var btn = document.createElement('button');
281 btn.type = 'button';
282 btn.className = 'des-slot';
283 btn.setAttribute('aria-label', 'Blokje ' + (i + 1));
284 if (b)
285 {
286 btn.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="' + Designer.esc(b.name) + '">'
287 + '<span>' + Designer.esc(b.name) + '</span>';
288 }
289 else
290 {
291 btn.innerHTML = '<span class="des-slot-empty">Kies</span>';
292 }
293 (function (slot)
294 {
295 btn.addEventListener('click', function ()
296 { Designer.openModal(slot); });
297 })(i);
298 row.appendChild(btn);
299 }
300};
301
302Designer.openModal = function (slot)
303{
304 Designer.openSlot = slot;
305 var modal = document.getElementById('des-modal');
306 var grid = document.getElementById('des-modal-grid');
307 if (!modal || !grid)
308 { return; }
309 grid.innerHTML = '';
310 var blocks = Designer.blocks();
311 var used = Object.create(null);
312 for (var i = 0; i < 5; i++)
313 {
314 if (i !== slot && Designer.slots[i])
315 { used[Designer.slots[i]] = true; }
316 }
317 for (var i = 0; i < blocks.length; i++)
318 {
319 var b = blocks[i];
320 var cell = document.createElement('button');
321 cell.type = 'button';
322 cell.className = 'des-block';
323 cell.dataset.id = b.id;
324 var locked = !b.unlocked;
325 var taken = !!used[b.id];
326 if (locked)
327 { cell.classList.add('locked'); }
328 if (taken)
329 { cell.classList.add('used'); }
330 if (Designer.slots[slot] === b.id)
331 { cell.classList.add('current'); }
332 var title = b.name;
333 if (locked)
334 { title += ' — ' + b.threshold + ' punten nodig'; }
335 else if (taken)
336 { title += ' — al in een ander vak'; }
337 cell.title = title;
338 cell.setAttribute('aria-label', title);
339 cell.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="">'
340 + (locked ? '<span class="des-lock" aria-hidden="true">'
341 + '<svg viewBox="0 0 18 18" width="16" height="16">'
342 + '<rect x="4" y="8" width="10" height="8" rx="1.5" fill="#ffe27a"/>'
343 + '<path d="M6 8 V6 a3 3 0 0 1 6 0 v2" fill="none" stroke="#ffe27a" stroke-width="1.8" stroke-linecap="round"/>'
344 + '<circle cx="9" cy="12" r="1.2" fill="#1a1628"/>'
345 + '</svg></span>' : '')
346 + '<span class="des-block-name">' + Designer.esc(b.name) + '</span>'
347 + (locked ? '<span class="des-block-need">' + b.threshold + '</span>' : '');
348 if (locked || taken)
349 { cell.disabled = true; }
350 else
351 {
352 cell.addEventListener('click', (function (id)
353 {
354 return function ()
355 {
356 Designer.slots[Designer.openSlot] = id;
357 Designer.closeModal();
358 Designer.renderSlots();
359 };
360 })(b.id));
361 }
362 grid.appendChild(cell);
363 }
364 modal.hidden = false;
365 modal.setAttribute('aria-hidden', 'false');
366 var close = document.getElementById('des-modal-close');
367 if (close)
368 { close.focus(); }
369};
370
371Designer.closeModal = function ()
372{
373 var modal = document.getElementById('des-modal');
374 if (!modal)
375 { return; }
376 modal.hidden = true;
377 modal.setAttribute('aria-hidden', 'true');
378};
379
380Designer.save = function ()
381{
382 var name = (document.getElementById('des-name').value || '').trim();
383 var people = (document.getElementById('des-people').value || '').trim();
384 if (!name || !people)
385 {
386 window.alert('Vul een naam voor de planeet en voor de bevolking in.');
387 return;
388 }
389 for (var i = 0; i < 5; i++)
390 {
391 if (!Designer.slots[i])
392 {
393 window.alert('Kies vijf blokjes.');
394 return;
395 }
396 }
397 var payload = {
398 id: Designer.editingId || undefined,
399 name: name,
400 people: people,
401 jumpsToClear: clampNum(document.getElementById('des-gravity').value, 1, 4, 2),
402 fallTime: clampNum(document.getElementById('des-air').value, 1, 5, 3),
403 riseTime: clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5),
404 colors: Designer.slots.slice()
405 };
406 Online.savePlanet(payload).then(function (data)
407 {
408 if (!data || !data.ok)
409 {
410 window.alert((data && data.error) || 'Opslaan is mislukt.');
411 return;
412 }
413 hideIf('designer-edit');
414 showIf('designer');
415 Designer.editingId = data.planet ? data.planet.id : null;
416 Designer.renderList();
417 if (typeof renderPlanetGrid === 'function')
418 {
419 renderPlanetGrid('planet-grid', false);
420 renderPlanetGrid('lobby-planet-grid', true);
421 }
422 });
423};
424
425Designer.bind = function ()
426{
427 var btn = document.getElementById('btn-designer');
428 if (btn)
429 { btn.addEventListener('click', function () { Designer.openList(); }); }
430 var back = document.getElementById('btn-designer-back');
431 if (back)
432 { back.addEventListener('click', Designer.close); }
433 var neu = document.getElementById('btn-designer-new');
434 if (neu)
435 { neu.addEventListener('click', function () { Designer.openEdit(null); }); }
436 var cancel = document.getElementById('btn-designer-cancel');
437 if (cancel)
438 {
439 cancel.addEventListener('click', function ()
440 {
441 hideIf('designer-edit');
442 showIf('designer');
443 Designer.renderList();
444 });
445 }
446 var save = document.getElementById('btn-designer-save');
447 if (save)
448 { save.addEventListener('click', function (e) { e.preventDefault(); Designer.save(); }); }
449 var form = document.getElementById('designer-form');
450 if (form)
451 { form.addEventListener('submit', function (e) { e.preventDefault(); Designer.save(); }); }
452 var del = document.getElementById('btn-designer-delete');
453 if (del)
454 {
455 del.addEventListener('click', function ()
456 {
457 if (!Designer.editingId)
458 { return; }
459 Designer.confirmDelete(Designer.editingId);
460 hideIf('designer-edit');
461 showIf('designer');
462 });
463 }
464 ['des-gravity', 'des-air', 'des-mass'].forEach(function (id)
465 {
466 var el = document.getElementById(id);
467 if (!el)
468 { return; }
469 el.addEventListener('input', Designer.syncPreview);
470 });
471 var modal = document.getElementById('des-modal');
472 if (modal)
473 {
474 modal.addEventListener('click', function (e)
475 {
476 if (e.target === modal)
477 { Designer.closeModal(); }
478 });
479 }
480 var close = document.getElementById('des-modal-close');
481 if (close)
482 { close.addEventListener('click', Designer.closeModal); }
483 document.addEventListener('keydown', function (e)
484 {
485 if (e.key === 'Escape')
486 { Designer.closeModal(); }
487 });
488};
489
490Designer.esc = function (s)
491{
492 return String(s == null ? '' : s)
493 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
494 .replace(/"/g, '&quot;');
495};
496
497function hideIf (id)
498{
499 var el = document.getElementById(id);
500 if (el)
501 { el.hidden = true; }
502}
503
504function showIf (id)
505{
506 var el = document.getElementById(id);
507 if (el)
508 { el.hidden = false; }
509}
510
511function setText (id, text)
512{
513 var el = document.getElementById(id);
514 if (el)
515 { el.textContent = text; }
516}
517
518function clampNum (v, lo, hi, fallback)
519{
520 var n = Number(v);
521 if (!isFinite(n))
522 { n = fallback; }
523 return Math.max(lo, Math.min(hi, n));
524}
525
526if (typeof module !== 'undefined' && module.exports)
527{ module.exports = Designer; }
528else if (typeof globalThis !== 'undefined')
529{ globalThis.Designer = Designer; }
src/main.js +113 −9
@@ -36,6 +36,12 @@ function planetImages ()
36 36 });
37 37 }
38 38 }
39 if (typeof Blocks !== 'undefined' && Blocks.images)
40 {
41 var extra = Blocks.images();
42 for (var b = 0; b < extra.length; b++)
43 { list.push(extra[b]); }
44 }
39 45 return list;
40 46 }
41 47
@@ -110,6 +116,20 @@ window.onload = function ()
110 116 bindOfflineUi();
111 117 bindPlanetSelect();
112 118 restoreSelectedPlanet();
119 if (typeof Designer !== 'undefined' && Designer.bind)
120 { Designer.bind(); }
121 if (typeof Online !== 'undefined' && Online.refresh)
122 {
123 Online.refresh().then(function ()
124 {
125 refreshMenuAccount();
126 restoreSelectedPlanet();
127 renderPlanetGrid('planet-grid', false);
128 renderPlanetGrid('lobby-planet-grid', true);
129 });
130 }
131 else
132 { refreshMenuAccount(); }
113 133 };
114 134
115 135 function onPlay ()
@@ -129,6 +149,10 @@ function startPlay (opts)
129 149 hideEl('podium');
130 150 hideEl('planet-select');
131 151 hideEl('offline-result');
152 hideEl('designer');
153 hideEl('designer-edit');
154 if (typeof Designer !== 'undefined' && Designer.closeModal)
155 { Designer.closeModal(); }
132 156 showEl('hud');
133 157
134 158 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
@@ -192,6 +216,8 @@ function startPlay (opts)
192 216 buildColumnWarn();
193 217 refreshOfflineHud();
194 218 refreshChainIndicator();
219 if (!opts.online)
220 { beginPlaySession(opts.offline ? 'offline' : 'solo'); }
195 221 }
196 222
197 223 function teardownPlay ()
@@ -784,7 +810,10 @@ function tickView (dt)
784 810 else if (app.offline)
785 811 { /* Offline result is shown from tickOffline. */ }
786 812 else
787 { showEl('game-over'); }
813 {
814 showEl('game-over');
815 finishPlaySession(app.lastScore);
816 }
788 817 }
789 818 if (!app.online && !app.offline && app.core.state === 'gameover'
790 819 && app.core.gameOverTime >= GAME_OVER_DELAY)
@@ -1395,6 +1424,8 @@ function startNextOfflineRound ()
1395 1424 // Tear down the current scene then start a fresh player field,
1396 1425 // keeping the same battle (already advanced).
1397 1426 var planet = app.battle.playerPlanet;
1427 var roundScore = app.core ? app.core.score : 0;
1428 finishPlaySession(roundScore);
1398 1429 app._keepBattleOnTeardown = true;
1399 1430 teardownPlay();
1400 1431 app.offline = true;
@@ -1420,6 +1451,7 @@ function showOfflineResult ()
1420 1451 }
1421 1452 hideEl('game-over');
1422 1453 showEl('offline-result');
1454 finishPlaySession(app.core ? app.core.score : 0);
1423 1455 }
1424 1456
1425 1457 function refreshOfflineHud ()
@@ -1731,10 +1763,18 @@ function startOnlineMatch ()
1731 1763 if (app.mode === 'playing' && app.online)
1732 1764 { return; }
1733 1765 var planet = Planet.planetById(selectedPlanetId());
1766 var miss = Planet.missChance(planet);
1734 1767 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1735 if (me && me.planet && me.planet.id)
1736 { planet = Planet.planetById(me.planet.id); }
1737 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
1768 if (me && me.planet)
1769 {
1770 if (typeof Planet.rememberPlanet === 'function')
1771 { planet = Planet.rememberPlanet(me.planet) || planet; }
1772 else if (me.planet.id)
1773 { planet = Planet.planetById(me.planet.id); }
1774 if (typeof me.planet.miss_chance === 'number')
1775 { miss = me.planet.miss_chance; }
1776 }
1777 startPlay({ online: true, planet: planet, missChance: miss });
1738 1778 if (typeof Online !== 'undefined')
1739 1779 { Online.startPolling(onlinePayload); }
1740 1780 }
@@ -2112,19 +2152,22 @@ function renderPlanetGrid (containerId, compact)
2112 2152 var pl = all[i];
2113 2153 var btn = document.createElement('button');
2114 2154 btn.type = 'button';
2115 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
2155 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
2156 + (pl.custom ? ' custom' : '');
2116 2157 btn.setAttribute('role', 'listitem');
2117 2158 btn.dataset.planet = pl.id;
2118 2159 var swatches = '';
2119 for (var c = 0; c < pl.colors.length; c++)
2160 var colors = pl.colors || [];
2161 for (var c = 0; c < colors.length; c++)
2120 2162 {
2121 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
2122 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
2163 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
2164 + escapeText(colors[c].name) + '" title="' + escapeText(colors[c].name) + '">';
2123 2165 }
2124 2166 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
2125 2167 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
2126 2168 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2127 + '<div class="planet-swatches">' + swatches + '</div>';
2169 + '<div class="planet-swatches">' + swatches + '</div>'
2170 + (pl.custom ? '<span class="custom-badge">Eigen</span>' : '');
2128 2171 btn.addEventListener('click', (function (id, isCompact)
2129 2172 {
2130 2173 return function ()
@@ -2185,3 +2228,64 @@ function bindPlanetSelect ()
2185 2228 back.addEventListener('click', cancelPlanetSelect);
2186 2229 }
2187 2230 }
2231
2232
2233 function refreshMenuAccount ()
2234 {
2235 var guest = document.getElementById('menu-guest');
2236 var user = document.getElementById('menu-user');
2237 var designerBtn = document.getElementById('btn-designer');
2238 var localLogin = document.getElementById('menu-local-login');
2239 var me = (typeof Online !== 'undefined') ? Online.me : null;
2240 if (me)
2241 {
2242 if (guest)
2243 { guest.hidden = true; }
2244 if (user)
2245 { user.hidden = false; }
2246 var name = document.getElementById('menu-name');
2247 if (name)
2248 { name.textContent = me.name || me.id || 'speler'; }
2249 var pts = document.getElementById('menu-points');
2250 if (pts)
2251 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
2252 if (designerBtn)
2253 { designerBtn.hidden = false; }
2254 }
2255 else
2256 {
2257 if (guest)
2258 { guest.hidden = false; }
2259 if (user)
2260 { user.hidden = true; }
2261 if (designerBtn)
2262 { designerBtn.hidden = true; }
2263 }
2264 if (localLogin)
2265 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
2266 }
2267
2268 function beginPlaySession (mode)
2269 {
2270 if (app.playToken)
2271 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
2272 app.playToken = null;
2273 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
2274 { return; }
2275 Online.playBegin(mode || 'solo').then(function (data)
2276 {
2277 if (data && data.ok && data.token)
2278 { app.playToken = data.token; }
2279 });
2280 }
2281
2282 function finishPlaySession (score)
2283 {
2284 var token = app.playToken;
2285 app.playToken = null;
2286 if (!token || typeof Online === 'undefined' || !Online.playFinish)
2287 { return; }
2288 Online.playFinish(token, score || 0).then(function ()
2289 { refreshMenuAccount(); });
2290 }
2291
@@ -36,6 +36,12 @@ function planetImages ()
36 });
36 });
37 }
37 }
38 }
38 }
39 if (typeof Blocks !== 'undefined' && Blocks.images)
40 {
41 var extra = Blocks.images();
42 for (var b = 0; b < extra.length; b++)
43 { list.push(extra[b]); }
44 }
39 return list;
45 return list;
40}
46}
41
47
@@ -110,6 +116,20 @@ window.onload = function ()
110 bindOfflineUi();
116 bindOfflineUi();
111 bindPlanetSelect();
117 bindPlanetSelect();
112 restoreSelectedPlanet();
118 restoreSelectedPlanet();
119 if (typeof Designer !== 'undefined' && Designer.bind)
120 { Designer.bind(); }
121 if (typeof Online !== 'undefined' && Online.refresh)
122 {
123 Online.refresh().then(function ()
124 {
125 refreshMenuAccount();
126 restoreSelectedPlanet();
127 renderPlanetGrid('planet-grid', false);
128 renderPlanetGrid('lobby-planet-grid', true);
129 });
130 }
131 else
132 { refreshMenuAccount(); }
113};
133};
114
134
115function onPlay ()
135function onPlay ()
@@ -129,6 +149,10 @@ function startPlay (opts)
129 hideEl('podium');
149 hideEl('podium');
130 hideEl('planet-select');
150 hideEl('planet-select');
131 hideEl('offline-result');
151 hideEl('offline-result');
152 hideEl('designer');
153 hideEl('designer-edit');
154 if (typeof Designer !== 'undefined' && Designer.closeModal)
155 { Designer.closeModal(); }
132 showEl('hud');
156 showEl('hud');
133
157
134 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
158 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
@@ -192,6 +216,8 @@ function startPlay (opts)
192 buildColumnWarn();
216 buildColumnWarn();
193 refreshOfflineHud();
217 refreshOfflineHud();
194 refreshChainIndicator();
218 refreshChainIndicator();
219 if (!opts.online)
220 { beginPlaySession(opts.offline ? 'offline' : 'solo'); }
195}
221}
196
222
197function teardownPlay ()
223function teardownPlay ()
@@ -784,7 +810,10 @@ function tickView (dt)
784 else if (app.offline)
810 else if (app.offline)
785 { /* Offline result is shown from tickOffline. */ }
811 { /* Offline result is shown from tickOffline. */ }
786 else
812 else
787 { showEl('game-over'); }
813 {
814 showEl('game-over');
815 finishPlaySession(app.lastScore);
816 }
788 }
817 }
789 if (!app.online && !app.offline && app.core.state === 'gameover'
818 if (!app.online && !app.offline && app.core.state === 'gameover'
790 && app.core.gameOverTime >= GAME_OVER_DELAY)
819 && app.core.gameOverTime >= GAME_OVER_DELAY)
@@ -1395,6 +1424,8 @@ function startNextOfflineRound ()
1395 // Tear down the current scene then start a fresh player field,
1424 // Tear down the current scene then start a fresh player field,
1396 // keeping the same battle (already advanced).
1425 // keeping the same battle (already advanced).
1397 var planet = app.battle.playerPlanet;
1426 var planet = app.battle.playerPlanet;
1427 var roundScore = app.core ? app.core.score : 0;
1428 finishPlaySession(roundScore);
1398 app._keepBattleOnTeardown = true;
1429 app._keepBattleOnTeardown = true;
1399 teardownPlay();
1430 teardownPlay();
1400 app.offline = true;
1431 app.offline = true;
@@ -1420,6 +1451,7 @@ function showOfflineResult ()
1420 }
1451 }
1421 hideEl('game-over');
1452 hideEl('game-over');
1422 showEl('offline-result');
1453 showEl('offline-result');
1454 finishPlaySession(app.core ? app.core.score : 0);
1423}
1455}
1424
1456
1425function refreshOfflineHud ()
1457function refreshOfflineHud ()
@@ -1731,10 +1763,18 @@ function startOnlineMatch ()
1731 if (app.mode === 'playing' && app.online)
1763 if (app.mode === 'playing' && app.online)
1732 { return; }
1764 { return; }
1733 var planet = Planet.planetById(selectedPlanetId());
1765 var planet = Planet.planetById(selectedPlanetId());
1766 var miss = Planet.missChance(planet);
1734 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1767 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
1735 if (me && me.planet && me.planet.id)
1768 if (me && me.planet)
1736 { planet = Planet.planetById(me.planet.id); }
1769 {
1737 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
1770 if (typeof Planet.rememberPlanet === 'function')
1771 { planet = Planet.rememberPlanet(me.planet) || planet; }
1772 else if (me.planet.id)
1773 { planet = Planet.planetById(me.planet.id); }
1774 if (typeof me.planet.miss_chance === 'number')
1775 { miss = me.planet.miss_chance; }
1776 }
1777 startPlay({ online: true, planet: planet, missChance: miss });
1738 if (typeof Online !== 'undefined')
1778 if (typeof Online !== 'undefined')
1739 { Online.startPolling(onlinePayload); }
1779 { Online.startPolling(onlinePayload); }
1740}
1780}
@@ -2112,19 +2152,22 @@ function renderPlanetGrid (containerId, compact)
2112 var pl = all[i];
2152 var pl = all[i];
2113 var btn = document.createElement('button');
2153 var btn = document.createElement('button');
2114 btn.type = 'button';
2154 btn.type = 'button';
2115 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
2155 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
2156 + (pl.custom ? ' custom' : '');
2116 btn.setAttribute('role', 'listitem');
2157 btn.setAttribute('role', 'listitem');
2117 btn.dataset.planet = pl.id;
2158 btn.dataset.planet = pl.id;
2118 var swatches = '';
2159 var swatches = '';
2119 for (var c = 0; c < pl.colors.length; c++)
2160 var colors = pl.colors || [];
2161 for (var c = 0; c < colors.length; c++)
2120 {
2162 {
2121 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
2163 swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
2122 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
2164 + escapeText(colors[c].name) + '" title="' + escapeText(colors[c].name) + '">';
2123 }
2165 }
2124 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
2166 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
2125 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
2167 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
2126 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2168 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
2127 + '<div class="planet-swatches">' + swatches + '</div>';
2169 + '<div class="planet-swatches">' + swatches + '</div>'
2170 + (pl.custom ? '<span class="custom-badge">Eigen</span>' : '');
2128 btn.addEventListener('click', (function (id, isCompact)
2171 btn.addEventListener('click', (function (id, isCompact)
2129 {
2172 {
2130 return function ()
2173 return function ()
@@ -2185,3 +2228,64 @@ function bindPlanetSelect ()
2185 back.addEventListener('click', cancelPlanetSelect);
2228 back.addEventListener('click', cancelPlanetSelect);
2186 }
2229 }
2187}
2230}
2231
2232
2233function refreshMenuAccount ()
2234{
2235 var guest = document.getElementById('menu-guest');
2236 var user = document.getElementById('menu-user');
2237 var designerBtn = document.getElementById('btn-designer');
2238 var localLogin = document.getElementById('menu-local-login');
2239 var me = (typeof Online !== 'undefined') ? Online.me : null;
2240 if (me)
2241 {
2242 if (guest)
2243 { guest.hidden = true; }
2244 if (user)
2245 { user.hidden = false; }
2246 var name = document.getElementById('menu-name');
2247 if (name)
2248 { name.textContent = me.name || me.id || 'speler'; }
2249 var pts = document.getElementById('menu-points');
2250 if (pts)
2251 { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); }
2252 if (designerBtn)
2253 { designerBtn.hidden = false; }
2254 }
2255 else
2256 {
2257 if (guest)
2258 { guest.hidden = false; }
2259 if (user)
2260 { user.hidden = true; }
2261 if (designerBtn)
2262 { designerBtn.hidden = true; }
2263 }
2264 if (localLogin)
2265 { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); }
2266}
2267
2268function beginPlaySession (mode)
2269{
2270 if (app.playToken)
2271 { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); }
2272 app.playToken = null;
2273 if (typeof Online === 'undefined' || !Online.me || !Online.playBegin)
2274 { return; }
2275 Online.playBegin(mode || 'solo').then(function (data)
2276 {
2277 if (data && data.ok && data.token)
2278 { app.playToken = data.token; }
2279 });
2280}
2281
2282function finishPlaySession (score)
2283{
2284 var token = app.playToken;
2285 app.playToken = null;
2286 if (!token || typeof Online === 'undefined' || !Online.playFinish)
2287 { return; }
2288 Online.playFinish(token, score || 0).then(function ()
2289 { refreshMenuAccount(); });
2290}
2291
src/online.js +49 −0
@@ -14,6 +14,10 @@ var Online = {
14 14 local: false,
15 15 csrf: '',
16 16 me: null,
17 lifetimePoints: 0,
18 locale: null,
19 blocks: [],
20 planets: [],
17 21 lobby: null,
18 22 incoming: [],
19 23 shotResults: [],
@@ -65,6 +69,26 @@ Online._apply = function (data)
65 69 { this.error = data.error; }
66 70 else if (data.ok)
67 71 { this.error = ''; }
72 if (data.lifetime_points != null)
73 { this.lifetimePoints = data.lifetime_points; }
74 if (data.locale !== undefined)
75 { this.locale = data.locale; }
76 if (data.blocks)
77 { this.blocks = data.blocks; }
78 if (data.planets)
79 {
80 this.planets = data.planets;
81 if (typeof Planet !== 'undefined' && Planet.setCustomPlanets)
82 { Planet.setCustomPlanets(data.planets); }
83 }
84 if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet)
85 {
86 for (var i = 0; i < data.lobby.players.length; i++)
87 {
88 if (data.lobby.players[i].planet)
89 { Planet.rememberPlanet(data.lobby.players[i].planet); }
90 }
91 }
68 92 };
69 93
70 94 Online.request = function (action, body)
@@ -136,6 +160,31 @@ Online.setPlanet = function (planetId)
136 160 return this.request('lobby_set_planet', { planet_id: planetId });
137 161 };
138 162
163 Online.playBegin = function (mode)
164 {
165 return this.request('play_begin', { mode: mode || 'solo' });
166 };
167
168 Online.playFinish = function (token, score)
169 {
170 return this.request('play_finish', { token: token, score: score || 0 });
171 };
172
173 Online.savePlanet = function (planet)
174 {
175 return this.request('planet_save', { planet: planet });
176 };
177
178 Online.deletePlanet = function (id)
179 {
180 return this.request('planet_delete', { id: id });
181 };
182
183 Online.setLocale = function (locale)
184 {
185 return this.request('set_locale', { locale: locale });
186 };
187
139 188 Online.leaveLobby = function ()
140 189 {
141 190 return this.request('lobby_leave');
@@ -14,6 +14,10 @@ var Online = {
14 local: false,
14 local: false,
15 csrf: '',
15 csrf: '',
16 me: null,
16 me: null,
17 lifetimePoints: 0,
18 locale: null,
19 blocks: [],
20 planets: [],
17 lobby: null,
21 lobby: null,
18 incoming: [],
22 incoming: [],
19 shotResults: [],
23 shotResults: [],
@@ -65,6 +69,26 @@ Online._apply = function (data)
65 { this.error = data.error; }
69 { this.error = data.error; }
66 else if (data.ok)
70 else if (data.ok)
67 { this.error = ''; }
71 { this.error = ''; }
72 if (data.lifetime_points != null)
73 { this.lifetimePoints = data.lifetime_points; }
74 if (data.locale !== undefined)
75 { this.locale = data.locale; }
76 if (data.blocks)
77 { this.blocks = data.blocks; }
78 if (data.planets)
79 {
80 this.planets = data.planets;
81 if (typeof Planet !== 'undefined' && Planet.setCustomPlanets)
82 { Planet.setCustomPlanets(data.planets); }
83 }
84 if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet)
85 {
86 for (var i = 0; i < data.lobby.players.length; i++)
87 {
88 if (data.lobby.players[i].planet)
89 { Planet.rememberPlanet(data.lobby.players[i].planet); }
90 }
91 }
68};
92};
69
93
70Online.request = function (action, body)
94Online.request = function (action, body)
@@ -136,6 +160,31 @@ Online.setPlanet = function (planetId)
136 return this.request('lobby_set_planet', { planet_id: planetId });
160 return this.request('lobby_set_planet', { planet_id: planetId });
137};
161};
138
162
163Online.playBegin = function (mode)
164{
165 return this.request('play_begin', { mode: mode || 'solo' });
166};
167
168Online.playFinish = function (token, score)
169{
170 return this.request('play_finish', { token: token, score: score || 0 });
171};
172
173Online.savePlanet = function (planet)
174{
175 return this.request('planet_save', { planet: planet });
176};
177
178Online.deletePlanet = function (id)
179{
180 return this.request('planet_delete', { id: id });
181};
182
183Online.setLocale = function (locale)
184{
185 return this.request('set_locale', { locale: locale });
186};
187
139Online.leaveLobby = function ()
188Online.leaveLobby = function ()
140{
189{
141 return this.request('lobby_leave');
190 return this.request('lobby_leave');
src/planet.js +66 −0
@@ -105,6 +105,34 @@ function loadCatalog ()
105 105 return { planets: [] };
106 106 }
107 107
108 /** Player-owned custom planets (from the profile) and any remembered
109 * snapshots (opponents in a lobby), not part of the official catalog. */
110 var _customPlanets = [];
111 var _remembered = Object.create(null);
112
113 function setCustomPlanets (list)
114 {
115 _customPlanets = [];
116 if (!list || !list.length)
117 { return; }
118 for (var i = 0; i < list.length; i++)
119 { _customPlanets.push(planetFromData(list[i])); }
120 }
121
122 function rememberPlanet (data)
123 {
124 if (!data || !data.id)
125 { return null; }
126 var pl = planetFromData(data);
127 _remembered[pl.id] = pl;
128 return pl;
129 }
130
131 function forgetRemembered ()
132 {
133 _remembered = Object.create(null);
134 }
135
108 136 function planetFromData (data)
109 137 {
110 138 var planet = createPlanet({
@@ -116,6 +144,10 @@ function planetFromData (data)
116 144 colors: data.colors
117 145 });
118 146 planet.id = data.id;
147 if (data.custom)
148 { planet.custom = true; }
149 if (data.owner_id)
150 { planet.owner_id = data.owner_id; }
119 151 return planet;
120 152 }
121 153
@@ -127,6 +159,8 @@ function allPlanets ()
127 159 { out.push(planetFromData(raw[i])); }
128 160 if (out.length === 0)
129 161 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
162 for (var c = 0; c < _customPlanets.length; c++)
163 { out.push(_customPlanets[c]); }
130 164 return out;
131 165 }
132 166
@@ -138,9 +172,30 @@ function planetById (id)
138 172 if (all[i].id === id)
139 173 { return all[i]; }
140 174 }
175 if (id && _remembered[id])
176 { return _remembered[id]; }
141 177 return defaultPlanet();
142 178 }
143 179
180 function officialPlanets ()
181 {
182 var raw = loadCatalog().planets || [];
183 var out = [];
184 for (var i = 0; i < raw.length; i++)
185 { out.push(planetFromData(raw[i])); }
186 return out;
187 }
188
189 function customPlanets ()
190 {
191 return _customPlanets.slice();
192 }
193
194 function pickerPlanets ()
195 {
196 return officialPlanets().concat(_customPlanets);
197 }
198
144 199 function defaultPlanet ()
145 200 {
146 201 var all = allPlanets();
@@ -167,6 +222,11 @@ function spriteKey (planet, colorIndex)
167 222 var c = colors && colors[colorIndex];
168 223 if (!c)
169 224 { return 'gray'; }
225 // Custom planets (and any color that names a registry block) share
226 // the preloaded Blocks.images() sprite, so late-loaded customs and
227 // opponent snapshots do not need a second preload.
228 if (c.block)
229 { return 'block:' + c.block; }
170 230 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
171 231 }
172 232
@@ -264,6 +324,12 @@ var Planet = {
264 324 defaultPlanet: defaultPlanet,
265 325 defaultColors: defaultColors,
266 326 allPlanets: allPlanets,
327 officialPlanets: officialPlanets,
328 customPlanets: customPlanets,
329 pickerPlanets: pickerPlanets,
330 setCustomPlanets: setCustomPlanets,
331 rememberPlanet: rememberPlanet,
332 forgetRemembered: forgetRemembered,
267 333 planetById: planetById,
268 334 planetFromData: planetFromData,
269 335 formatStats: formatStats,
@@ -105,6 +105,34 @@ function loadCatalog ()
105 return { planets: [] };
105 return { planets: [] };
106}
106}
107
107
108/** Player-owned custom planets (from the profile) and any remembered
109 * snapshots (opponents in a lobby), not part of the official catalog. */
110var _customPlanets = [];
111var _remembered = Object.create(null);
112
113function setCustomPlanets (list)
114{
115 _customPlanets = [];
116 if (!list || !list.length)
117 { return; }
118 for (var i = 0; i < list.length; i++)
119 { _customPlanets.push(planetFromData(list[i])); }
120}
121
122function rememberPlanet (data)
123{
124 if (!data || !data.id)
125 { return null; }
126 var pl = planetFromData(data);
127 _remembered[pl.id] = pl;
128 return pl;
129}
130
131function forgetRemembered ()
132{
133 _remembered = Object.create(null);
134}
135
108function planetFromData (data)
136function planetFromData (data)
109{
137{
110 var planet = createPlanet({
138 var planet = createPlanet({
@@ -116,6 +144,10 @@ function planetFromData (data)
116 colors: data.colors
144 colors: data.colors
117 });
145 });
118 planet.id = data.id;
146 planet.id = data.id;
147 if (data.custom)
148 { planet.custom = true; }
149 if (data.owner_id)
150 { planet.owner_id = data.owner_id; }
119 return planet;
151 return planet;
120}
152}
121
153
@@ -127,6 +159,8 @@ function allPlanets ()
127 { out.push(planetFromData(raw[i])); }
159 { out.push(planetFromData(raw[i])); }
128 if (out.length === 0)
160 if (out.length === 0)
129 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
161 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
162 for (var c = 0; c < _customPlanets.length; c++)
163 { out.push(_customPlanets[c]); }
130 return out;
164 return out;
131}
165}
132
166
@@ -138,9 +172,30 @@ function planetById (id)
138 if (all[i].id === id)
172 if (all[i].id === id)
139 { return all[i]; }
173 { return all[i]; }
140 }
174 }
175 if (id && _remembered[id])
176 { return _remembered[id]; }
141 return defaultPlanet();
177 return defaultPlanet();
142}
178}
143
179
180function officialPlanets ()
181{
182 var raw = loadCatalog().planets || [];
183 var out = [];
184 for (var i = 0; i < raw.length; i++)
185 { out.push(planetFromData(raw[i])); }
186 return out;
187}
188
189function customPlanets ()
190{
191 return _customPlanets.slice();
192}
193
194function pickerPlanets ()
195{
196 return officialPlanets().concat(_customPlanets);
197}
198
144function defaultPlanet ()
199function defaultPlanet ()
145{
200{
146 var all = allPlanets();
201 var all = allPlanets();
@@ -167,6 +222,11 @@ function spriteKey (planet, colorIndex)
167 var c = colors && colors[colorIndex];
222 var c = colors && colors[colorIndex];
168 if (!c)
223 if (!c)
169 { return 'gray'; }
224 { return 'gray'; }
225 // Custom planets (and any color that names a registry block) share
226 // the preloaded Blocks.images() sprite, so late-loaded customs and
227 // opponent snapshots do not need a second preload.
228 if (c.block)
229 { return 'block:' + c.block; }
170 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
230 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
171}
231}
172
232
@@ -264,6 +324,12 @@ var Planet = {
264 defaultPlanet: defaultPlanet,
324 defaultPlanet: defaultPlanet,
265 defaultColors: defaultColors,
325 defaultColors: defaultColors,
266 allPlanets: allPlanets,
326 allPlanets: allPlanets,
327 officialPlanets: officialPlanets,
328 customPlanets: customPlanets,
329 pickerPlanets: pickerPlanets,
330 setCustomPlanets: setCustomPlanets,
331 rememberPlanet: rememberPlanet,
332 forgetRemembered: forgetRemembered,
267 planetById: planetById,
333 planetById: planetById,
268 planetFromData: planetFromData,
334 planetFromData: planetFromData,
269 formatStats: formatStats,
335 formatStats: formatStats,
test/blocks.test.js added +184 −0
@@ -0,0 +1,184 @@
1 'use strict';
2
3 const { describe, it } = require('node:test');
4 const assert = require('node:assert/strict');
5 const Blocks = require('../src/blocks.js');
6 const Planet = require('../src/planet.js');
7 const Designer = require('../src/designer.js');
8 const fs = require('node:fs');
9 const path = require('node:path');
10
11 describe('Block registry (t1139)', () =>
12 {
13 it('loads the append-only registry with Terra first', () =>
14 {
15 const all = Blocks.all();
16 assert.ok(all.length >= 48, 'got ' + all.length);
17 assert.equal(all[0].id, 'terra-ember');
18 assert.equal(all[4].id, 'terra-orchid');
19 assert.equal(all[5].id, 'rune-fehu');
20 assert.equal(Blocks.TERRA_COUNT, 5);
21 assert.equal(Blocks.FIRST_THRESHOLD, 500);
22 assert.ok(Math.abs(Blocks.GROWTH - 1.145) < 1e-12);
23 });
24
25 it('Terra is free, the next block is 500, then 14.5% more and strictly increasing', () =>
26 {
27 for (let i = 0; i < 5; i++)
28 { assert.equal(Blocks.threshold(i), 0, 'index ' + i); }
29 assert.equal(Blocks.threshold(5), 500);
30 let prev = 500;
31 const all = Blocks.all();
32 for (let i = 6; i < all.length; i++)
33 {
34 const t = Blocks.threshold(i);
35 assert.ok(t > prev, 'index ' + i + ': ' + t + ' vs ' + prev);
36 const expected = Math.max(prev + 1, Math.round(prev * 1.145));
37 assert.equal(t, expected);
38 prev = t;
39 }
40 });
41
42 it('unlock is a requirement, not a spend', () =>
43 {
44 assert.equal(Blocks.unlocked(0, 0), true);
45 assert.equal(Blocks.unlocked(5, 499), false);
46 assert.equal(Blocks.unlocked(5, 500), true);
47 assert.equal(Blocks.unlocked(6, 500), false);
48 assert.equal(Blocks.unlockedId('rune-fehu', 500), true);
49 assert.equal(Blocks.unlockedId('no-such', 999999), false);
50 });
51
52 it('present() marks each block with threshold and unlock state', () =>
53 {
54 const list = Blocks.present(500);
55 assert.equal(list.length, Blocks.all().length);
56 assert.equal(list[0].unlocked, true);
57 assert.equal(list[5].unlocked, true);
58 assert.equal(list[5].threshold, 500);
59 assert.equal(list[6].unlocked, false);
60 assert.ok(list[5].image.startsWith('images/'));
61 });
62
63 it('asColor() fills a planet slot from a registry id', () =>
64 {
65 const c = Blocks.asColor('terra-ember', 2);
66 assert.equal(c.id, 2);
67 assert.equal(c.block, 'terra-ember');
68 assert.equal(c.name, 'Ember');
69 assert.ok(c.hex && c.image);
70 });
71
72 it('every registry image file exists on disk', () =>
73 {
74 const root = path.join(__dirname, '..');
75 for (const b of Blocks.all())
76 {
77 const file = path.join(root, 'build', b.image);
78 assert.ok(fs.existsSync(file), 'missing ' + b.image);
79 }
80 });
81 });
82
83 describe('Custom planets in the picker (t1140)', () =>
84 {
85 it('allPlanets and pickerPlanets include owned customs, officialPlanets does not', () =>
86 {
87 const before = Planet.officialPlanets().length;
88 assert.ok(before >= 8 && before <= 12);
89 Planet.setCustomPlanets([
90 {
91 id: 'c_abc123',
92 name: 'Home',
93 people: 'Homers',
94 jumpsToClear: 2,
95 fallTime: 3,
96 riseTime: 1.5,
97 custom: true,
98 owner_id: 'u1',
99 colors: [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i))
100 }
101 ]);
102 assert.equal(Planet.officialPlanets().length, before);
103 assert.equal(Planet.customPlanets().length, 1);
104 const all = Planet.allPlanets();
105 assert.equal(all.length, before + 1);
106 assert.equal(all[all.length - 1].id, 'c_abc123');
107 assert.equal(all[all.length - 1].custom, true);
108 const picker = Planet.pickerPlanets();
109 assert.ok(picker.some((p) => p.id === 'c_abc123'));
110 assert.equal(Planet.planetById('c_abc123').name, 'Home');
111 Planet.setCustomPlanets([]);
112 assert.equal(Planet.customPlanets().length, 0);
113 assert.equal(Planet.allPlanets().length, before);
114 });
115
116 it('rememberPlanet is used for opponents and is not in the picker', () =>
117 {
118 const opp = Planet.rememberPlanet({
119 id: 'c_opponent',
120 name: 'Rival',
121 people: 'Rivals',
122 jumpsToClear: 3,
123 fallTime: 2,
124 riseTime: 1,
125 custom: true,
126 owner_id: 'u2',
127 colors: [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i))
128 });
129 assert.equal(opp.name, 'Rival');
130 assert.equal(Planet.planetById('c_opponent').name, 'Rival');
131 assert.ok(!Planet.pickerPlanets().some((p) => p.id === 'c_opponent'));
132 assert.ok(!Planet.allPlanets().some((p) => p.id === 'c_opponent'));
133 Planet.forgetRemembered();
134 });
135
136 it('spriteKey for a registry colour uses the preloaded block: id', () =>
137 {
138 const colors = [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i));
139 const p = Planet.planetFromData({
140 id: 'c_key',
141 name: 'K',
142 people: 'K',
143 jumpsToClear: 2,
144 fallTime: 3,
145 riseTime: 1.5,
146 custom: true,
147 colors: colors
148 });
149 assert.equal(Planet.spriteKey(p, 0), 'block:terra-ember');
150 assert.equal(Planet.spriteKey(p, 4), 'block:terra-orchid');
151 const terra = Planet.planetById('terra');
152 assert.ok(!String(Planet.spriteKey(terra, 0)).startsWith('block:')
153 || terra.colors[0].block,
154 'official Terra keeps its catalog sprite unless it has a block field');
155 });
156 });
157
158 describe('Designer draft uses the existing Power formula', () =>
159 {
160 it('displayPower matches Planet.displayPower on a draft', () =>
161 {
162 const colors = [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i));
163 const p = Planet.createPlanet({
164 name: 'Draft',
165 people: 'Drafts',
166 jumpsToClear: 3,
167 fallTime: 2,
168 riseTime: 1,
169 colors: colors
170 });
171 const power = Planet.displayPower(p);
172 assert.equal(typeof power, 'number');
173 assert.equal(power, Planet.displayValues(p).power);
174 assert.ok(power >= 0 && power <= 100);
175 });
176
177 it('Designer.defaultSlots returns Terra\'s five', () =>
178 {
179 const slots = Designer.defaultSlots();
180 assert.equal(slots.length, 5);
181 assert.equal(slots[0], 'terra-ember');
182 assert.equal(slots[4], 'terra-orchid');
183 });
184 });
@@ -0,0 +1,184 @@
1'use strict';
2
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
5const Blocks = require('../src/blocks.js');
6const Planet = require('../src/planet.js');
7const Designer = require('../src/designer.js');
8const fs = require('node:fs');
9const path = require('node:path');
10
11describe('Block registry (t1139)', () =>
12{
13 it('loads the append-only registry with Terra first', () =>
14 {
15 const all = Blocks.all();
16 assert.ok(all.length >= 48, 'got ' + all.length);
17 assert.equal(all[0].id, 'terra-ember');
18 assert.equal(all[4].id, 'terra-orchid');
19 assert.equal(all[5].id, 'rune-fehu');
20 assert.equal(Blocks.TERRA_COUNT, 5);
21 assert.equal(Blocks.FIRST_THRESHOLD, 500);
22 assert.ok(Math.abs(Blocks.GROWTH - 1.145) < 1e-12);
23 });
24
25 it('Terra is free, the next block is 500, then 14.5% more and strictly increasing', () =>
26 {
27 for (let i = 0; i < 5; i++)
28 { assert.equal(Blocks.threshold(i), 0, 'index ' + i); }
29 assert.equal(Blocks.threshold(5), 500);
30 let prev = 500;
31 const all = Blocks.all();
32 for (let i = 6; i < all.length; i++)
33 {
34 const t = Blocks.threshold(i);
35 assert.ok(t > prev, 'index ' + i + ': ' + t + ' vs ' + prev);
36 const expected = Math.max(prev + 1, Math.round(prev * 1.145));
37 assert.equal(t, expected);
38 prev = t;
39 }
40 });
41
42 it('unlock is a requirement, not a spend', () =>
43 {
44 assert.equal(Blocks.unlocked(0, 0), true);
45 assert.equal(Blocks.unlocked(5, 499), false);
46 assert.equal(Blocks.unlocked(5, 500), true);
47 assert.equal(Blocks.unlocked(6, 500), false);
48 assert.equal(Blocks.unlockedId('rune-fehu', 500), true);
49 assert.equal(Blocks.unlockedId('no-such', 999999), false);
50 });
51
52 it('present() marks each block with threshold and unlock state', () =>
53 {
54 const list = Blocks.present(500);
55 assert.equal(list.length, Blocks.all().length);
56 assert.equal(list[0].unlocked, true);
57 assert.equal(list[5].unlocked, true);
58 assert.equal(list[5].threshold, 500);
59 assert.equal(list[6].unlocked, false);
60 assert.ok(list[5].image.startsWith('images/'));
61 });
62
63 it('asColor() fills a planet slot from a registry id', () =>
64 {
65 const c = Blocks.asColor('terra-ember', 2);
66 assert.equal(c.id, 2);
67 assert.equal(c.block, 'terra-ember');
68 assert.equal(c.name, 'Ember');
69 assert.ok(c.hex && c.image);
70 });
71
72 it('every registry image file exists on disk', () =>
73 {
74 const root = path.join(__dirname, '..');
75 for (const b of Blocks.all())
76 {
77 const file = path.join(root, 'build', b.image);
78 assert.ok(fs.existsSync(file), 'missing ' + b.image);
79 }
80 });
81});
82
83describe('Custom planets in the picker (t1140)', () =>
84{
85 it('allPlanets and pickerPlanets include owned customs, officialPlanets does not', () =>
86 {
87 const before = Planet.officialPlanets().length;
88 assert.ok(before >= 8 && before <= 12);
89 Planet.setCustomPlanets([
90 {
91 id: 'c_abc123',
92 name: 'Home',
93 people: 'Homers',
94 jumpsToClear: 2,
95 fallTime: 3,
96 riseTime: 1.5,
97 custom: true,
98 owner_id: 'u1',
99 colors: [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i))
100 }
101 ]);
102 assert.equal(Planet.officialPlanets().length, before);
103 assert.equal(Planet.customPlanets().length, 1);
104 const all = Planet.allPlanets();
105 assert.equal(all.length, before + 1);
106 assert.equal(all[all.length - 1].id, 'c_abc123');
107 assert.equal(all[all.length - 1].custom, true);
108 const picker = Planet.pickerPlanets();
109 assert.ok(picker.some((p) => p.id === 'c_abc123'));
110 assert.equal(Planet.planetById('c_abc123').name, 'Home');
111 Planet.setCustomPlanets([]);
112 assert.equal(Planet.customPlanets().length, 0);
113 assert.equal(Planet.allPlanets().length, before);
114 });
115
116 it('rememberPlanet is used for opponents and is not in the picker', () =>
117 {
118 const opp = Planet.rememberPlanet({
119 id: 'c_opponent',
120 name: 'Rival',
121 people: 'Rivals',
122 jumpsToClear: 3,
123 fallTime: 2,
124 riseTime: 1,
125 custom: true,
126 owner_id: 'u2',
127 colors: [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i))
128 });
129 assert.equal(opp.name, 'Rival');
130 assert.equal(Planet.planetById('c_opponent').name, 'Rival');
131 assert.ok(!Planet.pickerPlanets().some((p) => p.id === 'c_opponent'));
132 assert.ok(!Planet.allPlanets().some((p) => p.id === 'c_opponent'));
133 Planet.forgetRemembered();
134 });
135
136 it('spriteKey for a registry colour uses the preloaded block: id', () =>
137 {
138 const colors = [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i));
139 const p = Planet.planetFromData({
140 id: 'c_key',
141 name: 'K',
142 people: 'K',
143 jumpsToClear: 2,
144 fallTime: 3,
145 riseTime: 1.5,
146 custom: true,
147 colors: colors
148 });
149 assert.equal(Planet.spriteKey(p, 0), 'block:terra-ember');
150 assert.equal(Planet.spriteKey(p, 4), 'block:terra-orchid');
151 const terra = Planet.planetById('terra');
152 assert.ok(!String(Planet.spriteKey(terra, 0)).startsWith('block:')
153 || terra.colors[0].block,
154 'official Terra keeps its catalog sprite unless it has a block field');
155 });
156});
157
158describe('Designer draft uses the existing Power formula', () =>
159{
160 it('displayPower matches Planet.displayPower on a draft', () =>
161 {
162 const colors = [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i));
163 const p = Planet.createPlanet({
164 name: 'Draft',
165 people: 'Drafts',
166 jumpsToClear: 3,
167 fallTime: 2,
168 riseTime: 1,
169 colors: colors
170 });
171 const power = Planet.displayPower(p);
172 assert.equal(typeof power, 'number');
173 assert.equal(power, Planet.displayValues(p).power);
174 assert.ok(power >= 0 && power <= 100);
175 });
176
177 it('Designer.defaultSlots returns Terra\'s five', () =>
178 {
179 const slots = Designer.defaultSlots();
180 assert.equal(slots.length, 5);
181 assert.equal(slots[0], 'terra-ember');
182 assert.equal(slots[4], 'terra-orchid');
183 });
184});
test/designer-playwright.py added +404 −0
@@ -0,0 +1,404 @@
1 #!/usr/bin/env python3
2 """t1139 / t1140: Planet Designer UI, locked modal, custom planets in every picker."""
3 from __future__ import annotations
4
5 import os
6 import socket
7 import subprocess
8 import sys
9 import tempfile
10 import time
11 from pathlib import Path
12
13 from playwright.sync_api import sync_playwright
14
15 ROOT = Path("/workspace/meteors")
16 SHOTS = Path("/workspace/meteors-shots")
17 SHOTS.mkdir(parents=True, exist_ok=True)
18 PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
19 CHROME = "/usr/bin/google-chrome"
20 CHROME_ARGS = [
21 "--use-gl=angle",
22 "--use-angle=swiftshader",
23 "--no-sandbox",
24 "--disable-dev-shm-usage",
25 ]
26 FAILURES = []
27 URL = None
28
29 MOBILE = {
30 "viewport": {"width": 390, "height": 844},
31 "device_scale_factor": 2,
32 "is_mobile": True,
33 "has_touch": True,
34 "user_agent": (
35 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
36 "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
37 "Mobile/15E148 Safari/604.1"
38 ),
39 }
40
41
42 def check(cond, msg):
43 if cond:
44 print("OK ", msg)
45 else:
46 print("FAIL", msg)
47 FAILURES.append(msg)
48 return cond
49
50
51 def shot(page, name):
52 path = SHOTS / name
53 page.screenshot(path=str(path), full_page=False)
54 print(f"wrote {path} ({path.stat().st_size} bytes)")
55 return path
56
57
58 def free_port():
59 s = socket.socket()
60 s.bind(("127.0.0.1", 0))
61 port = s.getsockname()[1]
62 s.close()
63 return port
64
65
66 def start_php(port, data, log_path):
67 env = os.environ.copy()
68 env["METEORS_DATA_DIR"] = str(data)
69 log = open(log_path, "w")
70 proc = subprocess.Popen(
71 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
72 cwd=str(ROOT / "build"),
73 env=env,
74 stdout=log,
75 stderr=log,
76 )
77 time.sleep(0.5)
78 if proc.poll() is not None:
79 err = Path(log_path).read_text(errors="replace")
80 raise RuntimeError("php -S failed: " + err)
81 return proc
82
83
84 def seed_points(data, user="local:test_user_1", points=2000):
85 script = Path(data) / "seed.php"
86 script.write_text(f"""<?php
87 define('METEORS_NO_SESSION', true);
88 putenv('METEORS_DATA_DIR={data}');
89 require '{ROOT}/server/lib/bootstrap.php';
90 require '{ROOT}/server/lib/Store.php';
91 $s = Store::open('{data}');
92 echo $s->awardPoints('{user}', {points}, 'seed-playwright', 'solo');
93 """)
94 r = subprocess.run([PHP, str(script)], capture_output=True, text=True)
95 if r.returncode != 0:
96 raise RuntimeError("seed failed: " + r.stdout + "\n" + r.stderr)
97 print("seeded points, lifetime=", r.stdout.strip())
98 return r.stdout.strip()
99
100
101 def login(page, n=1):
102 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=20000)
103 page.wait_for_timeout(200)
104 page.goto(f"{URL}index.html", wait_until="networkidle", timeout=20000)
105 page.wait_for_function(
106 "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
107 timeout=10000,
108 )
109 page.wait_for_timeout(300)
110
111
112
113 def show_custom(page, grid=None):
114 try:
115 page.evaluate(
116 """() => {
117 const c = document.querySelector('%s .planet-card.custom, .planet-card.custom');
118 if (c) c.scrollIntoView({block: 'center', behavior: 'instant'});
119 }""" % (grid or '#planet-select')
120 )
121 page.wait_for_timeout(250)
122 except Exception as e:
123 print("show_custom:", e)
124
125 def wait_vis(page, sel, timeout=8000):
126 page.locator(sel).wait_for(state="visible", timeout=timeout)
127
128
129 def fill_new_planet(page, name="Aurora", people="Aurorans"):
130 wait_vis(page, "#designer-edit")
131 page.locator("#des-name").fill(name)
132 page.locator("#des-people").fill(people)
133 page.locator("#des-gravity").fill("2.5")
134 page.locator("#des-air").fill("2")
135 page.locator("#des-mass").fill("1.2")
136 page.wait_for_timeout(150)
137
138
139 def main():
140 global URL
141 port = free_port()
142 URL = f"http://127.0.0.1:{port}/"
143 data = Path(tempfile.mkdtemp(prefix="meteors-designer-"))
144 log_path = data / "php.log"
145 print("data", data, "url", URL)
146 proc = start_php(port, data, log_path)
147 try:
148 with sync_playwright() as p:
149 browser = p.chromium.launch(
150 executable_path=CHROME, args=CHROME_ARGS, headless=True
151 )
152 desktop = browser.new_context(viewport={"width": 1280, "height": 800})
153 page = desktop.new_page()
154 errors = []
155 page.on("pageerror", lambda e: errors.append(str(e)))
156 page.on(
157 "console",
158 lambda m: errors.append(m.text) if m.type == "error" else None,
159 )
160
161 login(page)
162 check(page.locator("#btn-designer").is_visible(), "designer button on menu when logged in")
163 check("test_user_1" in page.locator("#menu-name").inner_text(), "menu shows login name")
164 shot(page, "t1139-menu-logged-in-1280.png")
165
166 page.locator("#btn-designer").click()
167 wait_vis(page, "#designer")
168 page.wait_for_timeout(200)
169 shot(page, "t1139-designer-empty-1280.png")
170
171 page.locator("#btn-designer-new").click()
172 fill_new_planet(page)
173 power = page.locator("#des-power").inner_text()
174 check("Power" in power, f"live Power preview: {power!r}")
175 check(page.locator(".des-slot").count() == 5, "five block slots")
176 shot(page, "t1139-designer-edit-1280.png")
177
178 # Modal: defaults are Terra, so opening slot 0: other four Terra used (grey), rest locked.
179 page.locator(".des-slot").nth(0).click()
180 wait_vis(page, "#des-modal")
181 page.wait_for_timeout(200)
182 locked = page.locator(".des-block.locked").count()
183 used = page.locator(".des-block.used").count()
184 locks = page.locator(".des-lock").count()
185 check(locked > 20, f"many locked blocks ({locked})")
186 check(locks == locked, f"lock icon on every locked block ({locks} vs {locked})")
187 check(used == 4, f"other four Terra slots greyed as used ({used})")
188 check(page.locator(".des-block:not(.locked):not(.used)").count() >= 1, "current terra is selectable")
189 shot(page, "t1139-modal-locked-grey-1280.png")
190 page.locator("#des-modal-close").click()
191 page.wait_for_timeout(150)
192
193 page.locator("#btn-designer-save").click()
194 wait_vis(page, "#designer")
195 page.wait_for_timeout(300)
196 cards = page.locator("#designer-list .designer-card")
197 check(cards.count() >= 1, "saved planet appears in the list")
198 check("Aurora" in page.locator("#designer-list").inner_text(), "list shows planet name")
199 shot(page, "t1139-designer-list-1280.png")
200
201 # Seed points so some later blocks unlock, then reopen the modal.
202 seed_points(data, points=2000)
203 page.reload(wait_until="networkidle")
204 page.wait_for_function(
205 "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
206 timeout=10000,
207 )
208 pts = page.locator("#menu-points").inner_text().strip()
209 check(pts == "2000" or int(pts) >= 2000, f"menu points after seed ({pts})")
210 page.locator("#btn-designer").click()
211 wait_vis(page, "#designer")
212 page.locator("[data-edit]").first.click()
213 wait_vis(page, "#designer-edit")
214 page.locator(".des-slot").nth(4).click()
215 wait_vis(page, "#des-modal")
216 page.wait_for_timeout(250)
217 unlocked = page.locator(".des-block:not(.locked)").count()
218 locked = page.locator(".des-block.locked").count()
219 check(unlocked > 8, f"after 2000 points, several blocks unlocked ({unlocked})")
220 check(locked > 10, f"later blocks still locked ({locked})")
221 # Pick the first unlocked unused non-current block (Fehu etc.)
222 pick = page.locator(".des-block:not(.locked):not(.used):not(.current)").first
223 check(pick.count() == 1, "an unlocked unused block is clickable")
224 pick.click()
225 page.wait_for_timeout(200)
226 check(page.locator("#des-modal").is_hidden(), "modal closes after pick")
227 page.locator("#btn-designer-save").click()
228 wait_vis(page, "#designer")
229 page.wait_for_timeout(200)
230 shot(page, "t1139-modal-mixed-unlocked-1280.png") # will re-open for a clean shot
231
232 # Re-open modal just for a clear mixed locked/unlocked screenshot
233 page.locator("[data-edit]").first.click()
234 wait_vis(page, "#designer-edit")
235 page.locator(".des-slot").nth(0).click()
236 wait_vis(page, "#des-modal")
237 page.wait_for_timeout(200)
238 shot(page, "t1139-modal-mixed-unlocked-1280.png")
239 page.locator("#des-modal-close").click()
240 page.locator("#btn-designer-cancel").click()
241 page.locator("#btn-designer-back").click()
242 wait_vis(page, "#menu")
243
244 # --- pickers in all three modes ---
245 page.locator("#btn-play").click()
246 wait_vis(page, "#planet-select")
247 page.wait_for_timeout(250)
248 check(page.locator(".planet-card.custom").count() >= 1, "solo picker shows custom planet")
249 check("Aurora" in page.locator("#planet-grid").inner_text(), "solo picker lists Aurora")
250 check("Eigen" in page.locator(".custom-badge").first.inner_text(), "custom badge in solo picker")
251 shot(page, "t1139-picker-solo-1280.png")
252 page.locator("#btn-planet-back").click()
253 wait_vis(page, "#menu")
254
255 page.locator("#btn-offline").click()
256 wait_vis(page, "#planet-select")
257 page.wait_for_timeout(250)
258 check(page.locator(".planet-card.custom").count() >= 1, "offline picker shows custom planet")
259 shot(page, "t1139-picker-offline-1280.png")
260 page.locator("#btn-planet-back").click()
261 wait_vis(page, "#menu")
262
263 page.locator("#btn-online").click()
264 wait_vis(page, "#online-panel")
265 page.wait_for_timeout(400)
266 if page.locator("#btn-create").is_visible():
267 page.locator("#btn-create").click()
268 wait_vis(page, "#online-lobby")
269 page.wait_for_timeout(400)
270 check(page.locator("#lobby-planet-grid .planet-card.custom").count() >= 1,
271 "online lobby picker shows custom planet")
272 shot(page, "t1139-picker-online-1280.png")
273 if page.locator("#btn-leave-lobby").is_visible():
274 page.locator("#btn-leave-lobby").click()
275 page.wait_for_timeout(300)
276 # back to menu
277 back = page.locator("[data-back-menu]")
278 if back.count() and back.first.is_visible():
279 back.first.click()
280 else:
281 page.goto(f"{URL}index.html", wait_until="networkidle")
282 page.wait_for_timeout(400)
283
284 # Custom planet in play (solo)
285 wait_vis(page, "#menu")
286 page.locator("#btn-play").click()
287 wait_vis(page, "#planet-select")
288 page.locator(".planet-card.custom").first.click()
289 page.wait_for_timeout(150)
290 page.locator("#btn-planet-go").click()
291 page.wait_for_function(
292 "() => typeof app !== 'undefined' && app.mode === 'playing' && app.core",
293 timeout=10000,
294 )
295 page.wait_for_timeout(5500)
296 name = page.evaluate("() => app.planet && app.planet.name")
297 custom = page.evaluate("() => !!(app.planet && app.planet.custom)")
298 check(name == "Aurora", f"playing on custom planet ({name!r})")
299 check(custom is True, "planet.custom is true in play")
300 shot(page, "t1139-custom-in-play-1280.png")
301
302 # 1920 play + menu for consistency
303 page2 = desktop.new_page() # same context, still logged in? new page shares cookies
304 page2.set_viewport_size({"width": 1920, "height": 1080})
305 # already mid-play on page; start fresh on page2
306 page2.goto(f"{URL}index.html", wait_until="networkidle")
307 page2.wait_for_function(
308 "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
309 timeout=10000,
310 )
311 shot(page2, "t1139-menu-logged-in-1920x1080.png")
312 page2.locator("#btn-play").click()
313 wait_vis(page2, "#planet-select")
314 page2.wait_for_timeout(200)
315 shot(page2, "t1139-picker-solo-1920x1080.png")
316 page2.locator(".planet-card.custom").first.click()
317 page2.locator("#btn-planet-go").click()
318 page2.wait_for_function(
319 "() => typeof app !== 'undefined' && app.mode === 'playing'",
320 timeout=10000,
321 )
322 page2.wait_for_timeout(5500)
323 shot(page2, "t1139-custom-in-play-1920x1080.png")
324 page2.close()
325
326 # --- mobile ---
327 mobile = browser.new_context(**MOBILE)
328 m = mobile.new_page()
329 login(m)
330 shot(m, "t1139-menu-logged-in-390.png")
331 m.locator("#btn-designer").click()
332 wait_vis(m, "#designer")
333 m.wait_for_timeout(200)
334 shot(m, "t1139-designer-list-390.png")
335 m.locator("[data-edit]").first.click()
336 wait_vis(m, "#designer-edit")
337 m.wait_for_timeout(200)
338 shot(m, "t1139-designer-edit-390.png")
339 m.locator(".des-slot").nth(0).click()
340 wait_vis(m, "#des-modal")
341 m.wait_for_timeout(200)
342 check(m.locator(".des-lock").count() > 0, "mobile modal shows lock icons")
343 shot(m, "t1139-modal-locked-grey-390.png")
344 m.locator("#des-modal-close").click()
345 m.wait_for_timeout(150)
346 m.evaluate("() => { if (typeof Designer !== 'undefined') Designer.close(); }")
347 m.wait_for_timeout(200)
348 if not m.locator("#menu").is_visible():
349 m.goto(f"{URL}index.html", wait_until="networkidle")
350 m.wait_for_function(
351 "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
352 timeout=10000,
353 )
354 wait_vis(m, "#menu")
355 m.locator("#btn-play").click()
356 wait_vis(m, "#planet-select")
357 m.wait_for_timeout(200)
358 check(m.locator(".planet-card.custom").count() >= 1, "mobile solo picker shows custom")
359 show_custom(m)
360 shot(m, "t1139-picker-solo-390.png")
361 m.locator("#btn-planet-back").click()
362 wait_vis(m, "#menu")
363 m.locator("#btn-offline").click()
364 wait_vis(m, "#planet-select")
365 m.wait_for_timeout(200)
366 show_custom(m)
367 shot(m, "t1139-picker-offline-390.png")
368 m.locator("#btn-planet-back").click()
369 m.locator("#btn-online").click()
370 wait_vis(m, "#online-panel")
371 m.wait_for_timeout(400)
372 if m.locator("#btn-create").is_visible():
373 m.locator("#btn-create").click()
374 wait_vis(m, "#online-lobby")
375 m.wait_for_timeout(400)
376 check(m.locator("#lobby-planet-grid .planet-card.custom").count() >= 1,
377 "mobile online picker shows custom")
378 show_custom(m)
379 shot(m, "t1139-picker-online-390.png")
380
381 if errors:
382 print("page errors:", errors)
383 # fail only on real exceptions, not leftover console
384 real = [e for e in errors if "Failed to load" not in e]
385 if real:
386 FAILURES.append("page errors: " + "; ".join(real[:5]))
387
388 browser.close()
389 finally:
390 proc.terminate()
391 try:
392 proc.wait(timeout=3)
393 except Exception:
394 proc.kill()
395 print("php log:\n", log_path.read_text(errors="replace")[-2000:])
396
397 print("\n{} failures".format(len(FAILURES)))
398 for f in FAILURES:
399 print(" -", f)
400 return 0 if not FAILURES else 1
401
402
403 if __name__ == "__main__":
404 sys.exit(main())
@@ -0,0 +1,404 @@
1#!/usr/bin/env python3
2"""t1139 / t1140: Planet Designer UI, locked modal, custom planets in every picker."""
3from __future__ import annotations
4
5import os
6import socket
7import subprocess
8import sys
9import tempfile
10import time
11from pathlib import Path
12
13from playwright.sync_api import sync_playwright
14
15ROOT = Path("/workspace/meteors")
16SHOTS = Path("/workspace/meteors-shots")
17SHOTS.mkdir(parents=True, exist_ok=True)
18PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
19CHROME = "/usr/bin/google-chrome"
20CHROME_ARGS = [
21 "--use-gl=angle",
22 "--use-angle=swiftshader",
23 "--no-sandbox",
24 "--disable-dev-shm-usage",
25]
26FAILURES = []
27URL = None
28
29MOBILE = {
30 "viewport": {"width": 390, "height": 844},
31 "device_scale_factor": 2,
32 "is_mobile": True,
33 "has_touch": True,
34 "user_agent": (
35 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
36 "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
37 "Mobile/15E148 Safari/604.1"
38 ),
39}
40
41
42def check(cond, msg):
43 if cond:
44 print("OK ", msg)
45 else:
46 print("FAIL", msg)
47 FAILURES.append(msg)
48 return cond
49
50
51def shot(page, name):
52 path = SHOTS / name
53 page.screenshot(path=str(path), full_page=False)
54 print(f"wrote {path} ({path.stat().st_size} bytes)")
55 return path
56
57
58def free_port():
59 s = socket.socket()
60 s.bind(("127.0.0.1", 0))
61 port = s.getsockname()[1]
62 s.close()
63 return port
64
65
66def start_php(port, data, log_path):
67 env = os.environ.copy()
68 env["METEORS_DATA_DIR"] = str(data)
69 log = open(log_path, "w")
70 proc = subprocess.Popen(
71 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
72 cwd=str(ROOT / "build"),
73 env=env,
74 stdout=log,
75 stderr=log,
76 )
77 time.sleep(0.5)
78 if proc.poll() is not None:
79 err = Path(log_path).read_text(errors="replace")
80 raise RuntimeError("php -S failed: " + err)
81 return proc
82
83
84def seed_points(data, user="local:test_user_1", points=2000):
85 script = Path(data) / "seed.php"
86 script.write_text(f"""<?php
87define('METEORS_NO_SESSION', true);
88putenv('METEORS_DATA_DIR={data}');
89require '{ROOT}/server/lib/bootstrap.php';
90require '{ROOT}/server/lib/Store.php';
91$s = Store::open('{data}');
92echo $s->awardPoints('{user}', {points}, 'seed-playwright', 'solo');
93""")
94 r = subprocess.run([PHP, str(script)], capture_output=True, text=True)
95 if r.returncode != 0:
96 raise RuntimeError("seed failed: " + r.stdout + "\n" + r.stderr)
97 print("seeded points, lifetime=", r.stdout.strip())
98 return r.stdout.strip()
99
100
101def login(page, n=1):
102 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=20000)
103 page.wait_for_timeout(200)
104 page.goto(f"{URL}index.html", wait_until="networkidle", timeout=20000)
105 page.wait_for_function(
106 "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
107 timeout=10000,
108 )
109 page.wait_for_timeout(300)
110
111
112
113def show_custom(page, grid=None):
114 try:
115 page.evaluate(
116 """() => {
117 const c = document.querySelector('%s .planet-card.custom, .planet-card.custom');
118 if (c) c.scrollIntoView({block: 'center', behavior: 'instant'});
119 }""" % (grid or '#planet-select')
120 )
121 page.wait_for_timeout(250)
122 except Exception as e:
123 print("show_custom:", e)
124
125def wait_vis(page, sel, timeout=8000):
126 page.locator(sel).wait_for(state="visible", timeout=timeout)
127
128
129def fill_new_planet(page, name="Aurora", people="Aurorans"):
130 wait_vis(page, "#designer-edit")
131 page.locator("#des-name").fill(name)
132 page.locator("#des-people").fill(people)
133 page.locator("#des-gravity").fill("2.5")
134 page.locator("#des-air").fill("2")
135 page.locator("#des-mass").fill("1.2")
136 page.wait_for_timeout(150)
137
138
139def main():
140 global URL
141 port = free_port()
142 URL = f"http://127.0.0.1:{port}/"
143 data = Path(tempfile.mkdtemp(prefix="meteors-designer-"))
144 log_path = data / "php.log"
145 print("data", data, "url", URL)
146 proc = start_php(port, data, log_path)
147 try:
148 with sync_playwright() as p:
149 browser = p.chromium.launch(
150 executable_path=CHROME, args=CHROME_ARGS, headless=True
151 )
152 desktop = browser.new_context(viewport={"width": 1280, "height": 800})
153 page = desktop.new_page()
154 errors = []
155 page.on("pageerror", lambda e: errors.append(str(e)))
156 page.on(
157 "console",
158 lambda m: errors.append(m.text) if m.type == "error" else None,
159 )
160
161 login(page)
162 check(page.locator("#btn-designer").is_visible(), "designer button on menu when logged in")
163 check("test_user_1" in page.locator("#menu-name").inner_text(), "menu shows login name")
164 shot(page, "t1139-menu-logged-in-1280.png")
165
166 page.locator("#btn-designer").click()
167 wait_vis(page, "#designer")
168 page.wait_for_timeout(200)
169 shot(page, "t1139-designer-empty-1280.png")
170
171 page.locator("#btn-designer-new").click()
172 fill_new_planet(page)
173 power = page.locator("#des-power").inner_text()
174 check("Power" in power, f"live Power preview: {power!r}")
175 check(page.locator(".des-slot").count() == 5, "five block slots")
176 shot(page, "t1139-designer-edit-1280.png")
177
178 # Modal: defaults are Terra, so opening slot 0: other four Terra used (grey), rest locked.
179 page.locator(".des-slot").nth(0).click()
180 wait_vis(page, "#des-modal")
181 page.wait_for_timeout(200)
182 locked = page.locator(".des-block.locked").count()
183 used = page.locator(".des-block.used").count()
184 locks = page.locator(".des-lock").count()
185 check(locked > 20, f"many locked blocks ({locked})")
186 check(locks == locked, f"lock icon on every locked block ({locks} vs {locked})")
187 check(used == 4, f"other four Terra slots greyed as used ({used})")
188 check(page.locator(".des-block:not(.locked):not(.used)").count() >= 1, "current terra is selectable")
189 shot(page, "t1139-modal-locked-grey-1280.png")
190 page.locator("#des-modal-close").click()
191 page.wait_for_timeout(150)
192
193 page.locator("#btn-designer-save").click()
194 wait_vis(page, "#designer")
195 page.wait_for_timeout(300)
196 cards = page.locator("#designer-list .designer-card")
197 check(cards.count() >= 1, "saved planet appears in the list")
198 check("Aurora" in page.locator("#designer-list").inner_text(), "list shows planet name")
199 shot(page, "t1139-designer-list-1280.png")
200
201 # Seed points so some later blocks unlock, then reopen the modal.
202 seed_points(data, points=2000)
203 page.reload(wait_until="networkidle")
204 page.wait_for_function(
205 "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
206 timeout=10000,
207 )
208 pts = page.locator("#menu-points").inner_text().strip()
209 check(pts == "2000" or int(pts) >= 2000, f"menu points after seed ({pts})")
210 page.locator("#btn-designer").click()
211 wait_vis(page, "#designer")
212 page.locator("[data-edit]").first.click()
213 wait_vis(page, "#designer-edit")
214 page.locator(".des-slot").nth(4).click()
215 wait_vis(page, "#des-modal")
216 page.wait_for_timeout(250)
217 unlocked = page.locator(".des-block:not(.locked)").count()
218 locked = page.locator(".des-block.locked").count()
219 check(unlocked > 8, f"after 2000 points, several blocks unlocked ({unlocked})")
220 check(locked > 10, f"later blocks still locked ({locked})")
221 # Pick the first unlocked unused non-current block (Fehu etc.)
222 pick = page.locator(".des-block:not(.locked):not(.used):not(.current)").first
223 check(pick.count() == 1, "an unlocked unused block is clickable")
224 pick.click()
225 page.wait_for_timeout(200)
226 check(page.locator("#des-modal").is_hidden(), "modal closes after pick")
227 page.locator("#btn-designer-save").click()
228 wait_vis(page, "#designer")
229 page.wait_for_timeout(200)
230 shot(page, "t1139-modal-mixed-unlocked-1280.png") # will re-open for a clean shot
231
232 # Re-open modal just for a clear mixed locked/unlocked screenshot
233 page.locator("[data-edit]").first.click()
234 wait_vis(page, "#designer-edit")
235 page.locator(".des-slot").nth(0).click()
236 wait_vis(page, "#des-modal")
237 page.wait_for_timeout(200)
238 shot(page, "t1139-modal-mixed-unlocked-1280.png")
239 page.locator("#des-modal-close").click()
240 page.locator("#btn-designer-cancel").click()
241 page.locator("#btn-designer-back").click()
242 wait_vis(page, "#menu")
243
244 # --- pickers in all three modes ---
245 page.locator("#btn-play").click()
246 wait_vis(page, "#planet-select")
247 page.wait_for_timeout(250)
248 check(page.locator(".planet-card.custom").count() >= 1, "solo picker shows custom planet")
249 check("Aurora" in page.locator("#planet-grid").inner_text(), "solo picker lists Aurora")
250 check("Eigen" in page.locator(".custom-badge").first.inner_text(), "custom badge in solo picker")
251 shot(page, "t1139-picker-solo-1280.png")
252 page.locator("#btn-planet-back").click()
253 wait_vis(page, "#menu")
254
255 page.locator("#btn-offline").click()
256 wait_vis(page, "#planet-select")
257 page.wait_for_timeout(250)
258 check(page.locator(".planet-card.custom").count() >= 1, "offline picker shows custom planet")
259 shot(page, "t1139-picker-offline-1280.png")
260 page.locator("#btn-planet-back").click()
261 wait_vis(page, "#menu")
262
263 page.locator("#btn-online").click()
264 wait_vis(page, "#online-panel")
265 page.wait_for_timeout(400)
266 if page.locator("#btn-create").is_visible():
267 page.locator("#btn-create").click()
268 wait_vis(page, "#online-lobby")
269 page.wait_for_timeout(400)
270 check(page.locator("#lobby-planet-grid .planet-card.custom").count() >= 1,
271 "online lobby picker shows custom planet")
272 shot(page, "t1139-picker-online-1280.png")
273 if page.locator("#btn-leave-lobby").is_visible():
274 page.locator("#btn-leave-lobby").click()
275 page.wait_for_timeout(300)
276 # back to menu
277 back = page.locator("[data-back-menu]")
278 if back.count() and back.first.is_visible():
279 back.first.click()
280 else:
281 page.goto(f"{URL}index.html", wait_until="networkidle")
282 page.wait_for_timeout(400)
283
284 # Custom planet in play (solo)
285 wait_vis(page, "#menu")
286 page.locator("#btn-play").click()
287 wait_vis(page, "#planet-select")
288 page.locator(".planet-card.custom").first.click()
289 page.wait_for_timeout(150)
290 page.locator("#btn-planet-go").click()
291 page.wait_for_function(
292 "() => typeof app !== 'undefined' && app.mode === 'playing' && app.core",
293 timeout=10000,
294 )
295 page.wait_for_timeout(5500)
296 name = page.evaluate("() => app.planet && app.planet.name")
297 custom = page.evaluate("() => !!(app.planet && app.planet.custom)")
298 check(name == "Aurora", f"playing on custom planet ({name!r})")
299 check(custom is True, "planet.custom is true in play")
300 shot(page, "t1139-custom-in-play-1280.png")
301
302 # 1920 play + menu for consistency
303 page2 = desktop.new_page() # same context, still logged in? new page shares cookies
304 page2.set_viewport_size({"width": 1920, "height": 1080})
305 # already mid-play on page; start fresh on page2
306 page2.goto(f"{URL}index.html", wait_until="networkidle")
307 page2.wait_for_function(
308 "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
309 timeout=10000,
310 )
311 shot(page2, "t1139-menu-logged-in-1920x1080.png")
312 page2.locator("#btn-play").click()
313 wait_vis(page2, "#planet-select")
314 page2.wait_for_timeout(200)
315 shot(page2, "t1139-picker-solo-1920x1080.png")
316 page2.locator(".planet-card.custom").first.click()
317 page2.locator("#btn-planet-go").click()
318 page2.wait_for_function(
319 "() => typeof app !== 'undefined' && app.mode === 'playing'",
320 timeout=10000,
321 )
322 page2.wait_for_timeout(5500)
323 shot(page2, "t1139-custom-in-play-1920x1080.png")
324 page2.close()
325
326 # --- mobile ---
327 mobile = browser.new_context(**MOBILE)
328 m = mobile.new_page()
329 login(m)
330 shot(m, "t1139-menu-logged-in-390.png")
331 m.locator("#btn-designer").click()
332 wait_vis(m, "#designer")
333 m.wait_for_timeout(200)
334 shot(m, "t1139-designer-list-390.png")
335 m.locator("[data-edit]").first.click()
336 wait_vis(m, "#designer-edit")
337 m.wait_for_timeout(200)
338 shot(m, "t1139-designer-edit-390.png")
339 m.locator(".des-slot").nth(0).click()
340 wait_vis(m, "#des-modal")
341 m.wait_for_timeout(200)
342 check(m.locator(".des-lock").count() > 0, "mobile modal shows lock icons")
343 shot(m, "t1139-modal-locked-grey-390.png")
344 m.locator("#des-modal-close").click()
345 m.wait_for_timeout(150)
346 m.evaluate("() => { if (typeof Designer !== 'undefined') Designer.close(); }")
347 m.wait_for_timeout(200)
348 if not m.locator("#menu").is_visible():
349 m.goto(f"{URL}index.html", wait_until="networkidle")
350 m.wait_for_function(
351 "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
352 timeout=10000,
353 )
354 wait_vis(m, "#menu")
355 m.locator("#btn-play").click()
356 wait_vis(m, "#planet-select")
357 m.wait_for_timeout(200)
358 check(m.locator(".planet-card.custom").count() >= 1, "mobile solo picker shows custom")
359 show_custom(m)
360 shot(m, "t1139-picker-solo-390.png")
361 m.locator("#btn-planet-back").click()
362 wait_vis(m, "#menu")
363 m.locator("#btn-offline").click()
364 wait_vis(m, "#planet-select")
365 m.wait_for_timeout(200)
366 show_custom(m)
367 shot(m, "t1139-picker-offline-390.png")
368 m.locator("#btn-planet-back").click()
369 m.locator("#btn-online").click()
370 wait_vis(m, "#online-panel")
371 m.wait_for_timeout(400)
372 if m.locator("#btn-create").is_visible():
373 m.locator("#btn-create").click()
374 wait_vis(m, "#online-lobby")
375 m.wait_for_timeout(400)
376 check(m.locator("#lobby-planet-grid .planet-card.custom").count() >= 1,
377 "mobile online picker shows custom")
378 show_custom(m)
379 shot(m, "t1139-picker-online-390.png")
380
381 if errors:
382 print("page errors:", errors)
383 # fail only on real exceptions, not leftover console
384 real = [e for e in errors if "Failed to load" not in e]
385 if real:
386 FAILURES.append("page errors: " + "; ".join(real[:5]))
387
388 browser.close()
389 finally:
390 proc.terminate()
391 try:
392 proc.wait(timeout=3)
393 except Exception:
394 proc.kill()
395 print("php log:\n", log_path.read_text(errors="replace")[-2000:])
396
397 print("\n{} failures".format(len(FAILURES)))
398 for f in FAILURES:
399 print(" -", f)
400 return 0 if not FAILURES else 1
401
402
403if __name__ == "__main__":
404 sys.exit(main())