BlueGit

projects-timfalken-com meteors

chore: rebuild game.js with Offline Strijd and t1119–t1123 features

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
ac06eb0ce0f8a2dd414f1a9a8a5afcf1146c64de
Parent
f94ef6d8
1 file changed +1498 −136
build/game.js +1498 −136
@@ -256,10 +256,16 @@ else if (typeof globalThis !== 'undefined')
256 256 * that later planets only need new data, not new physics code.
257 257 *
258 258 * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
259 * A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —
260 * at 1, one jump from the floor clears the field; at 4, you need four.
259 * A horizontal match of 3 jumps JUMP_HEIGHT_SCALE * FIELD_HEIGHT
260 * / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the
261 * minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so
262 * one jump from the floor clears the 13-tile field with room to spare;
263 * at 4 you still need more than one jump, but each is 50% taller.
261 264 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
262 * After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.
265 * After a jump peaks, blocks float down at DESCENT_SPEED_SCALE *
266 * FIELD_HEIGHT / fallTime tiles/s (DESCENT_SPEED_SCALE is 0.5 since
267 * t1122: all descent speeds are halved). Relative differences between
268 * planets (1 / fallTime) are unchanged. Upward launch is not affected.
263 269 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
264 270 * Time to reach the apex, independent of jump height.
265 271 *
@@ -274,6 +280,14 @@ else if (typeof globalThis !== 'undefined')
274 280
275 281 var FIELD_WIDTH = 10;
276 282 var FIELD_HEIGHT = 13;
283 /** t1119: every match jump (the gravity-applied minimum and the
284 * vertical / extra-block bonuses derived from it) is 50% higher. */
285 var JUMP_HEIGHT_SCALE = 1.5;
286 /** t1122: every descent speed is halved. Terminal fallSpeed, spawn
287 * fall, unsupported / released / cargo fall, and the post-apex
288 * float-down all use this scale. Upward launch is unchanged. */
289 var DESCENT_SPEED_SCALE = 0.5;
290
277 291
278 292 function clamp (value, lo, hi)
279 293 {
@@ -306,12 +320,14 @@ function createPlanet (opts)
306 320 fallTime: fallTime,
307 321 riseTime: riseTime,
308 322 colors: colors,
309 baseJumpHeight: FIELD_HEIGHT / jumpsToClear,
310 fallSpeed: FIELD_HEIGHT / fallTime,
323 baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear,
324 fallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime,
311 325 // Time to ease from vy=0 at the apex to terminal fallSpeed.
312 // Shorter when air resistance is low (small fallTime).
326 // Shorter when air resistance is low (small fallTime). The ease
327 // duration is unchanged; fallAccel scales with the halved
328 // fallSpeed so the ease still lasts apexEaseTime seconds.
313 329 apexEaseTime: 0.15 * fallTime,
314 fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
330 fallAccel: (DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
315 331 // Visual landing bounce: faster at low air resistance. Stage-3 params.
316 332 bounceDuration: 0.12 * fallTime,
317 333 bounceSquash: 0.16
@@ -480,6 +496,8 @@ function displayValues (planet)
480 496 var Planet = {
481 497 FIELD_WIDTH: FIELD_WIDTH,
482 498 FIELD_HEIGHT: FIELD_HEIGHT,
499 JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE,
500 DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE,
483 501 COLOR_COUNT: 5,
484 502 SETTLE_TIME: 3,
485 503 SPAWN_INTERVAL: 1,
@@ -571,11 +589,29 @@ function easeOutElastic (t)
571 589 return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
572 590 }
573 591
592 /** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */
593 function easeOutCubic (t)
594 {
595 t = clamp01(t);
596 var u = 1 - t;
597 return 1 - u * u * u;
598 }
599
574 600 function tween (from, to, t, ease)
575 601 {
576 602 return from + (to - from) * ease(clamp01(t));
577 603 }
578 604
605 /**
606 * Visual-only block swap tween (t1121). Game logic and the grid update
607 * immediately; this only moves the displaced sprite. 100 ms sits in the
608 * requested 80–120 ms range.
609 */
610 var SWAP_TWEEN = {
611 duration: 0.100,
612 ease: easeOutCubic
613 };
614
579 615 /**
580 616 * DEFAULT settings of Tim's KWin Click Tween
581 617 * (git.timfalken.com/timfa/click-tween).
@@ -619,8 +655,10 @@ var Easing = {
619 655 ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
620 656 easeOutBack: easeOutBack,
621 657 easeOutElastic: easeOutElastic,
658 easeOutCubic: easeOutCubic,
622 659 tween: tween,
623 660 CLICK_TWEEN: CLICK_TWEEN,
661 SWAP_TWEEN: SWAP_TWEEN,
624 662 clamp01: clamp01,
625 663 bouncePose: bouncePose
626 664 };
@@ -672,6 +710,13 @@ var SWAP_DISTANCE = 0.25;
672 710 var SNAP_Y = 0.5;
673 711 // Horizontal slop (tiles) for snapping to a neighbouring column on press.
674 712 var HORIZONTAL_SLOP = 0.35;
713 /** t1120: additive jump bonus per landing-chain step. A landing that
714 * immediately makes a match launches at (1 + 0.25 * chain) times the
715 * usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */
716 var LANDING_CHAIN_BONUS = 0.25;
717 /** t1123: a column pulses red at or above this many grounded rows
718 * (10 of 13 is just over 70%). */
719 var COLUMN_WARN_ROWS = 10;
675 720
676 721 function UnionFind ()
677 722 {
@@ -726,6 +771,10 @@ function GameCore (planet, rng)
726 771 this.strictInvariants = false;
727 772 this.debugInvariants = false;
728 773 this.lastInvariantViolations = [];
774 // t1121: visual-only swap events, consumed by the view each frame.
775 this.swapEvents = [];
776 // t1120: last landing-chain indicator { chain, bonusPct }, or null.
777 this.lastChainIndicator = null;
729 778 }
730 779
731 780 function optsMissChance (args)
@@ -744,6 +793,8 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
744 793 GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
745 794 GameCore.SNAP_Y = SNAP_Y;
746 795 GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
796 GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;
797 GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;
747 798 GameCore.DEFAULT_MISS_CHANCE = 0.30;
748 799 GameCore.STATE_STILL = STATE_STILL;
749 800 GameCore.STATE_FALLING = STATE_FALLING;
@@ -892,6 +943,56 @@ GameCore.prototype.groundedCount = function (col)
892 943 return n;
893 944 };
894 945
946 GameCore.prototype.columnNeedsWarn = function (col)
947 {
948 return this.groundedCount(col) >= COLUMN_WARN_ROWS;
949 };
950
951 /**
952 * Which columns of a field snapshot should pulse (t1123). Flying,
953 * falling and manual (airborne) blocks do not count: they are
954 * temporary and would flicker the warning. Still, settling and
955 * locked (grounded) blocks do.
956 */
957 GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)
958 {
959 threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;
960 var width = (snapshot && snapshot.width) || 10;
961 var flags = [];
962 var counts = [];
963 for (var c = 0; c < width; c++)
964 {
965 counts[c] = 0;
966 flags[c] = false;
967 }
968 var blocks = (snapshot && snapshot.blocks) || [];
969 for (var i = 0; i < blocks.length; i++)
970 {
971 var b = blocks[i];
972 if (b.col < 0 || b.col >= width)
973 { continue; }
974 if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')
975 { counts[b.col]++; }
976 }
977 for (var c = 0; c < width; c++)
978 { flags[c] = counts[c] >= threshold; }
979 return flags;
980 };
981
982 GameCore.columnWarnPulse = function (timeSec)
983 {
984 // Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player
985 // field and opponent / bot minis so they pulse in sync.
986 var t = timeSec;
987 if (t == null)
988 {
989 t = (typeof performance !== 'undefined' && performance.now)
990 ? performance.now() / 1000
991 : Date.now() / 1000;
992 }
993 return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));
994 };
995
895 996 GameCore.prototype.blockAt = function (col, row)
896 997 {
897 998 for (var i = 0; i < this.blocks.length; i++)
@@ -1513,6 +1614,14 @@ GameCore.prototype.mergeClusterGroup = function (clusters)
1513 1614 keep.decel = decelSum / n;
1514 1615 keep.jumpHeight = hSum / n;
1515 1616 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1617 var maxChain = 0;
1618 for (var c = 0; c < clusters.length; c++)
1619 {
1620 var ch = clusters[c].landingChain || 0;
1621 if (ch > maxChain)
1622 { maxChain = ch; }
1623 }
1624 keep.landingChain = maxChain;
1516 1625 for (var c = 0; c < clusters.length; c++)
1517 1626 {
1518 1627 var mem = this.clusterMembers(clusters[c].id);
@@ -1907,6 +2016,9 @@ GameCore.prototype.landCluster = function (cluster, members)
1907 2016 }
1908 2017 cluster.phase = 'landed';
1909 2018 cluster.vy = 0;
2019 cluster.landedPending = true;
2020 if (cluster.landingChain == null)
2021 { cluster.landingChain = 0; }
1910 2022 };
1911 2023
1912 2024 /**
@@ -1928,6 +2040,10 @@ GameCore.prototype.releaseLandedCluster = function (cluster)
1928 2040 block.color = this.randomColor();
1929 2041 block.settleTime = 0;
1930 2042 }
2043 // Persist the chain across release so a post-recolor match in
2044 // this same tick still gets the landing bonus (t1120).
2045 block.justLanded = !!cluster.landedPending;
2046 block.landingChain = cluster.landingChain || 0;
1931 2047 this.leaveCluster(block);
1932 2048 // Always drop leftover launch / manual velocity. A stale upward
1933 2049 // vy here is what sends blocks off the top "very fast" after
@@ -2803,7 +2919,10 @@ GameCore.prototype.resolveMatches = function ()
2803 2919 { return []; }
2804 2920 var lines = this.findMatchLines();
2805 2921 if (!lines.length)
2806 { return []; }
2922 {
2923 this.finishLandingChains([]);
2924 return [];
2925 }
2807 2926
2808 2927 var uf = new UnionFind();
2809 2928 var blockById = Object.create(null);
@@ -2870,9 +2989,19 @@ GameCore.prototype.resolveMatches = function ()
2870 2989 { height = h; }
2871 2990 }
2872 2991 }
2873 this.launchCluster(group, height);
2874 launched.push({ blocks: group, jumpHeight: height });
2992 var chain = this.landingChainFor(group);
2993 var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
2994 height *= bonusMul;
2995 this.launchCluster(group, height, { landingChain: chain });
2996 launched.push({
2997 blocks: group,
2998 jumpHeight: height,
2999 landingChain: chain,
3000 chainBonus: bonusMul
3001 });
2875 3002 }
3003 this.finishLandingChains(launched);
3004 this.updateChainIndicator(launched);
2876 3005 return launched;
2877 3006 };
2878 3007
@@ -2880,8 +3009,9 @@ GameCore.prototype.resolveMatches = function ()
2880 3009 * Gray the matched blocks, take everything sitting on top of them in
2881 3010 * those columns, link them, and launch with jump height `height`.
2882 3011 */
2883 GameCore.prototype.launchCluster = function (matchedBlocks, height)
3012 GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
2884 3013 {
3014 opts = opts || {};
2885 3015 var lowestInCol = Object.create(null);
2886 3016 var matchedIds = Object.create(null);
2887 3017 for (var i = 0; i < matchedBlocks.length; i++)
@@ -2898,7 +3028,9 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)
2898 3028 jumpHeight: height,
2899 3029 vy: PlanetMod.launchVelocity(this.planet, height),
2900 3030 decel: PlanetMod.launchDeceleration(this.planet, height),
2901 phase: 'up'
3031 phase: 'up',
3032 landingChain: opts.landingChain || 0,
3033 landedPending: false
2902 3034 };
2903 3035 this.clusters[clusterId] = cluster;
2904 3036
@@ -3274,10 +3406,149 @@ GameCore.prototype.swapToward = function (block, targetY)
3274 3406
3275 3407 GameCore.prototype.swapBlocks = function (a, b)
3276 3408 {
3277 var y = a.y;
3278 a.y = b.y;
3279 b.y = y;
3409 var ay = a.y;
3410 var by = b.y;
3411 a.y = by;
3412 b.y = ay;
3280 3413 this.transferLandedMembership(a, b);
3414 if (!this.swapEvents)
3415 { this.swapEvents = []; }
3416 this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
3417 this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
3418 };
3419
3420 GameCore.prototype.consumeSwapEvents = function ()
3421 {
3422 var ev = this.swapEvents || [];
3423 this.swapEvents = [];
3424 return ev;
3425 };
3426
3427 /**
3428 * Highest landing-chain counter among just-landed members of this
3429 * match group, plus one. Returns 0 when the match did not come from
3430 * a cluster landing (player/bot swap, mid-air, etc.).
3431 */
3432 GameCore.prototype.landingChainFor = function (group)
3433 {
3434 var maxChain = 0;
3435 var fromLanding = false;
3436 for (var i = 0; i < group.length; i++)
3437 {
3438 var block = group[i];
3439 if (block.justLanded)
3440 {
3441 fromLanding = true;
3442 if ((block.landingChain || 0) > maxChain)
3443 { maxChain = block.landingChain || 0; }
3444 }
3445 if (block.clusterId != null)
3446 {
3447 var cluster = this.clusters[block.clusterId];
3448 if (cluster && cluster.landedPending)
3449 {
3450 fromLanding = true;
3451 if ((cluster.landingChain || 0) > maxChain)
3452 { maxChain = cluster.landingChain || 0; }
3453 }
3454 }
3455 }
3456 if (!fromLanding)
3457 { return 0; }
3458 return maxChain + 1;
3459 };
3460
3461 /**
3462 * After resolveMatches: clear the landing-pending flag and reset the
3463 * chain on landings that did not make a match. A cluster that is still
3464 * settling (greys not yet recolored) keeps landedPending so a later
3465 * post-recolor match in this same landing still gets the bonus.
3466 */
3467 GameCore.prototype.finishLandingChains = function (launched)
3468 {
3469 var launchedIds = Object.create(null);
3470 launched = launched || [];
3471 for (var i = 0; i < launched.length; i++)
3472 {
3473 var blocks = launched[i].blocks || [];
3474 for (var j = 0; j < blocks.length; j++)
3475 { launchedIds[blocks[j].id] = true; }
3476 }
3477
3478 for (var i = 0; i < this.blocks.length; i++)
3479 {
3480 var block = this.blocks[i];
3481 if (!block.justLanded)
3482 { continue; }
3483 if (!launchedIds[block.id])
3484 { block.landingChain = 0; }
3485 block.justLanded = false;
3486 }
3487
3488 var ids = Object.keys(this.clusters);
3489 for (var c = 0; c < ids.length; c++)
3490 {
3491 var cluster = this.clusters[ids[c]];
3492 if (!cluster || !cluster.landedPending)
3493 { continue; }
3494 var members = this.clusterMembers(cluster.id);
3495 var anyLaunched = false;
3496 var stillSettling = false;
3497 for (var i = 0; i < members.length; i++)
3498 {
3499 if (launchedIds[members[i].id])
3500 { anyLaunched = true; }
3501 if (members[i].state === STATE_SETTLING)
3502 { stillSettling = true; }
3503 }
3504 if (anyLaunched)
3505 {
3506 cluster.landingChain = 0;
3507 cluster.landedPending = false;
3508 }
3509 else if (!stillSettling)
3510 {
3511 // Released leftovers or a fully-still landed group that
3512 // already had its match opportunity and missed it.
3513 cluster.landingChain = 0;
3514 cluster.landedPending = false;
3515 }
3516 // else: still settling, no match yet — keep landedPending.
3517 }
3518 };
3519
3520 GameCore.prototype.updateChainIndicator = function (launched)
3521 {
3522 var maxChain = 0;
3523 for (var i = 0; i < launched.length; i++)
3524 {
3525 var ch = launched[i].landingChain || 0;
3526 if (ch > maxChain)
3527 { maxChain = ch; }
3528 }
3529 if (maxChain >= 1)
3530 {
3531 this.lastChainIndicator = {
3532 chain: maxChain,
3533 bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
3534 };
3535 return;
3536 }
3537 if (!this.hasActiveLandingChain())
3538 { this.lastChainIndicator = null; }
3539 };
3540
3541 GameCore.prototype.hasActiveLandingChain = function ()
3542 {
3543 var ids = Object.keys(this.clusters);
3544 for (var i = 0; i < ids.length; i++)
3545 {
3546 var cluster = this.clusters[ids[i]];
3547 if (cluster && (cluster.landingChain || 0) >= 1
3548 && cluster.phase !== 'landed')
3549 { return true; }
3550 }
3551 return false;
3281 3552 };
3282 3553
3283 3554 /**
@@ -3811,6 +4082,19 @@ Online._drawMini = function (canvas, snapshot, planet)
3811 4082 }
3812 4083 if (!snapshot || !snapshot.blocks)
3813 4084 { return; }
4085 // t1123: cheap sine pulse behind blocks of nearly-full columns.
4086 if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
4087 {
4088 var warns = GameCore.warnColumnsFromSnapshot(snapshot);
4089 var pulse = GameCore.columnWarnPulse();
4090 for (var wc = 0; wc < warns.length; wc++)
4091 {
4092 if (!warns[wc])
4093 { continue; }
4094 ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
4095 ctx.fillRect(wc * tw, 0, tw, canvas.height);
4096 }
4097 }
3814 4098 var blocks = snapshot.blocks;
3815 4099 for (var i = 0; i < blocks.length; i++)
3816 4100 {
@@ -4014,146 +4298,792 @@ if (typeof module !== 'undefined' && module.exports)
4014 4298
4015 4299 /*
4016 4300 * Start File:
4017 * /workspace/meteors/src/main.js
4301 * /workspace/meteors/src/offline.js
4018 4302 */
4019 4303 'use strict';
4020 4304
4021 4305 /**
4022 * View and input for Meteors. The simulation lives in GameCore; this file
4023 * only draws it, scales it to the viewport, and translates pointer events
4024 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
4025 * through Online (src/online.js) and the same GameCore.
4306 * Offline Strijd: a client-side single-player mode that plays like
4307 * multiplayer (shots, miss chance, opponent minis) against local bots
4308 * (t1119). Pure simulation — no server.
4026 4309 */
4027 4310
4028 function planetImages ()
4311 var Offline = (function ()
4029 4312 {
4030 var list = [
4031 { name: 'gray', url: 'images/block-gray.png' },
4032 { name: 'locked', url: 'images/block-locked.png' },
4033 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
4034 { name: 'cell', url: 'images/cell.png' },
4035 { name: 'pixel', url: 'images/pixel.png' },
4036 // Keep the original Terra placeholders as aliases (Tim may still have them).
4037 { name: 'ember', url: 'images/block-ember.png' },
4038 { name: 'aqua', url: 'images/block-aqua.png' },
4039 { name: 'leaf', url: 'images/block-leaf.png' },
4040 { name: 'sun', url: 'images/block-sun.png' },
4041 { name: 'orchid', url: 'images/block-orchid.png' }
4042 ];
4043 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
4044 for (var i = 0; i < planets.length; i++)
4313
4314 var BOT_INTERVAL = 0.5;
4315 var SKILL_START = 0.05;
4316 var SKILL_STEP = 0.01;
4317 var SKILL_CAP = 1;
4318 var FLIGHT_DURATION = 1.2;
4319 var ROUND_WON_DELAY = 1.5;
4320
4321 /**
4322 * N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.
4323 * Documented in docs/ASSUMPTIONS.md (t1119).
4324 */
4325 function roundsAtOpponentCount (n)
4326 {
4327 if (n <= 1)
4328 { return 1; }
4329 return n - 1;
4330 }
4331
4332 function skillForRound (round)
4333 {
4334 var r = Math.max(1, Math.floor(Number(round) || 1));
4335 var pct = 5 + (r - 1);
4336 if (pct > 100)
4337 { pct = 100; }
4338 return pct / 100;
4339 }
4340
4341 function scheduleForRound (round)
4342 {
4343 var r = Math.max(1, Math.floor(Number(round) || 1));
4344 var cursor = 1;
4345 var n = 1;
4346 for (;;)
4045 4347 {
4046 var pl = planets[i];
4047 for (var c = 0; c < pl.colors.length; c++)
4348 var count = roundsAtOpponentCount(n);
4349 if (r < cursor + count)
4048 4350 {
4049 list.push({
4050 name: Planet.spriteKey(pl, c),
4051 url: pl.colors[c].image
4052 });
4351 return {
4352 round: r,
4353 opponents: n,
4354 skill: skillForRound(r),
4355 roundsAtLevel: count,
4356 indexInLevel: r - cursor + 1
4357 };
4358 }
4359 cursor += count;
4360 n++;
4361 if (n > 10000)
4362 {
4363 return {
4364 round: r,
4365 opponents: n,
4366 skill: SKILL_CAP,
4367 roundsAtLevel: roundsAtOpponentCount(n),
4368 indexInLevel: 1
4369 };
4053 4370 }
4054 4371 }
4055 return list;
4056 4372 }
4057 4373
4058 var IMAGES = planetImages();
4059 var GAME_OVER_DELAY = 2;
4374 function GameCoreCtor ()
4375 {
4376 if (typeof GameCore !== 'undefined')
4377 { return GameCore; }
4378 if (typeof module !== 'undefined')
4379 { return require('./gameCore.js').GameCore; }
4380 return null;
4381 }
4060 4382
4061 var game = new Game();
4062 var app = {
4063 mode: 'menu',
4064 core: null,
4065 scene: null,
4066 manager: null,
4067 planet: null,
4068 lastScore: 0,
4069 tile: 48,
4070 fieldX: 0,
4071 fieldY: 0,
4072 fieldW: 0,
4073 fieldH: 0,
4074 hudH: 56,
4075 sprites: Object.create(null),
4076 flames: Object.create(null),
4077 cells: [],
4078 pointerId: null,
4079 pointerType: null,
4080 activeTouchId: null,
4081 debugDrag: false,
4082 debugPhysics: false,
4083 gameOverShown: false,
4084 selectTween: null,
4085 online: false,
4086 eliminatedReported: false,
4087 spectating: false,
4088 miniH: 0,
4089 selectedPlanetId: 'terra',
4090 planetSelectContext: 'solo'
4091 };
4383 function PlanetMod ()
4384 {
4385 if (typeof Planet !== 'undefined')
4386 { return Planet; }
4387 if (typeof module !== 'undefined')
4388 { return require('./planet.js'); }
4389 return null;
4390 }
4092 4391
4093 window.onload = function ()
4392 /**
4393 * Integer-row colour grid of grounded (still / settling / locked)
4394 * blocks, including greys (color < 0) so a swap can shift them.
4395 */
4396 function snapshotGrid (core)
4094 4397 {
4095 app.debugDrag = isDragDebugEnabled();
4096 app.debugPhysics = isPhysicsDebugEnabled();
4097 var play = document.getElementById('btn-play');
4098 play.addEventListener('click', onPlay);
4099 play.addEventListener('pointerup', function (e)
4398 var width = core.width;
4399 var height = core.height;
4400 var grid = [];
4401 for (var c = 0; c < width; c++)
4100 4402 {
4101 // A touch-friendly path: some mobile browsers swallow the click
4102 // after a slightly sloppy tap. Ignore the following click.
4103 if (e.pointerType === 'touch' || e.pointerType === 'pen')
4104 {
4105 e.preventDefault();
4106 onPlay();
4107 }
4108 });
4109
4110 game.preloadImagesThenStart(IMAGES, function ()
4403 grid[c] = [];
4404 for (var r = 0; r < height; r++)
4405 { grid[c][r] = null; }
4406 }
4407 for (var i = 0; i < core.blocks.length; i++)
4111 4408 {
4112 if (game.images.flame && game.images.flame.addAnimationCycle)
4113 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
4114 });
4409 var b = core.blocks[i];
4410 if (!core.isGrounded(b))
4411 { continue; }
4412 var row = Math.round(b.y);
4413 if (row < 0 || row >= height || b.col < 0 || b.col >= width)
4414 { continue; }
4415 if (Math.abs(b.y - row) > 0.2)
4416 { continue; }
4417 grid[b.col][row] = b.color;
4418 }
4419 return grid;
4420 }
4115 4421
4116 bindOnlineUi();
4117 bindPlanetSelect();
4118 restoreSelectedPlanet();
4119 };
4422 function cloneGrid (grid)
4423 {
4424 var out = [];
4425 for (var c = 0; c < grid.length; c++)
4426 { out[c] = grid[c].slice(); }
4427 return out;
4428 }
4120 4429
4121 function onPlay ()
4430 /**
4431 * Apply swapToward's net result: the block at fromRow moves to toRow,
4432 * and the blocks it passed through each shift one cell toward fromRow.
4433 */
4434 function applyColumnMove (grid, col, fromRow, toRow)
4122 4435 {
4123 if (app.mode === 'playing')
4436 if (fromRow === toRow)
4124 4437 { return; }
4125 openPlanetSelect('solo');
4438 var moving = grid[col][fromRow];
4439 if (toRow > fromRow)
4440 {
4441 for (var y = fromRow; y < toRow; y++)
4442 { grid[col][y] = grid[col][y + 1]; }
4443 grid[col][toRow] = moving;
4444 }
4445 else
4446 {
4447 for (var y = fromRow; y > toRow; y--)
4448 { grid[col][y] = grid[col][y - 1]; }
4449 grid[col][toRow] = moving;
4450 }
4126 4451 }
4127 4452
4128 function startPlay (opts)
4453 function hasMatch (grid, width, height)
4129 4454 {
4130 opts = opts || {};
4131 hideEl('menu');
4132 hideEl('game-over');
4133 hideEl('online-panel');
4134 hideEl('spectator');
4135 hideEl('podium');
4136 hideEl('planet-select');
4137 showEl('hud');
4138
4139 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
4140 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
4141 var miss = opts.missChance;
4142 if (typeof miss !== 'number' || !isFinite(miss))
4143 { miss = planetMod.missChance(app.planet); }
4144 app.core = new GameCore(app.planet, Math.random, miss);
4145 if (app.debugPhysics)
4146 { app.core.debugInvariants = true; }
4147 app.mode = 'playing';
4148 app.online = !!opts.online;
4149 app.gameOverShown = false;
4150 app.eliminatedReported = false;
4151 app.spectating = false;
4152 app.sprites = Object.create(null);
4153 app.flames = Object.create(null);
4154 app.cells = [];
4155 app.pointerId = null;
4455 var c, r, run, prev;
4456 for (r = 0; r < height; r++)
4457 {
4458 run = 0;
4459 prev = null;
4460 for (c = 0; c < width; c++)
4461 {
4462 var color = grid[c][r];
4463 if (color != null && color >= 0 && color === prev)
4464 {
4465 run++;
4466 if (run >= 3)
4467 { return true; }
4468 }
4469 else
4470 {
4471 run = (color != null && color >= 0) ? 1 : 0;
4472 prev = (color != null && color >= 0) ? color : null;
4473 }
4474 }
4475 }
4476 for (c = 0; c < width; c++)
4477 {
4478 run = 0;
4479 prev = null;
4480 for (r = 0; r < height; r++)
4481 {
4482 var color = grid[c][r];
4483 if (color != null && color >= 0 && color === prev)
4484 {
4485 run++;
4486 if (run >= 3)
4487 { return true; }
4488 }
4489 else
4490 {
4491 run = (color != null && color >= 0) ? 1 : 0;
4492 prev = (color != null && color >= 0) ? color : null;
4493 }
4494 }
4495 }
4496 return false;
4497 }
4498
4499 /**
4500 * Contiguous segments of draggable, nearly-integer-y blocks in a
4501 * column. Gaps break a segment the same way swapToward stops at gaps.
4502 */
4503 function contiguousSegments (core, col)
4504 {
4505 if (!core.columnAllowsDrag(col))
4506 { return []; }
4507 var list = core.blocksInColumn(col).filter(function (b)
4508 {
4509 return core.isDraggableBlock(b);
4510 });
4511 list.sort(function (a, b) { return a.y - b.y; });
4512 var segs = [];
4513 var cur = [];
4514 for (var i = 0; i < list.length; i++)
4515 {
4516 var y = list[i].y;
4517 if (Math.abs(y - Math.round(y)) > 0.15)
4518 {
4519 if (cur.length)
4520 {
4521 segs.push(cur);
4522 cur = [];
4523 }
4524 continue;
4525 }
4526 if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)
4527 {
4528 segs.push(cur);
4529 cur = [list[i]];
4530 }
4531 else
4532 { cur.push(list[i]); }
4533 }
4534 if (cur.length)
4535 { segs.push(cur); }
4536 return segs;
4537 }
4538
4539 /**
4540 * The shortest vertical move that would create a 3+ match, or null.
4541 * Ties break on lowest column, then lowest fromY, then lowest toY.
4542 */
4543 function findBotMove (core)
4544 {
4545 var grid = snapshotGrid(core);
4546 if (hasMatch(grid, core.width, core.height))
4547 { return null; }
4548 var best = null;
4549 for (var col = 0; col < core.width; col++)
4550 {
4551 var segs = contiguousSegments(core, col);
4552 for (var s = 0; s < segs.length; s++)
4553 {
4554 var seg = segs[s];
4555 if (seg.length < 2)
4556 { continue; }
4557 for (var i = 0; i < seg.length; i++)
4558 {
4559 var fromY = Math.round(seg[i].y);
4560 for (var j = 0; j < seg.length; j++)
4561 {
4562 if (i === j)
4563 { continue; }
4564 var toY = Math.round(seg[j].y);
4565 var dist = Math.abs(toY - fromY);
4566 if (best && dist > best.dist)
4567 { continue; }
4568 var trial = cloneGrid(grid);
4569 applyColumnMove(trial, col, fromY, toY);
4570 if (!hasMatch(trial, core.width, core.height))
4571 { continue; }
4572 var cand = {
4573 col: col,
4574 fromY: fromY,
4575 toY: toY,
4576 dist: dist,
4577 blockId: seg[i].id
4578 };
4579 if (!best || dist < best.dist
4580 || (dist === best.dist && col < best.col)
4581 || (dist === best.dist && col === best.col && fromY < best.fromY)
4582 || (dist === best.dist && col === best.col && fromY === best.fromY
4583 && toY < best.toY))
4584 { best = cand; }
4585 }
4586 }
4587 }
4588 }
4589 return best;
4590 }
4591
4592 function executeBotMove (core, move)
4593 {
4594 if (!core || !move)
4595 { return false; }
4596 var list = core.blocksInColumn(move.col);
4597 var block = null;
4598 for (var i = 0; i < list.length; i++)
4599 {
4600 if (move.blockId != null && list[i].id === move.blockId)
4601 {
4602 block = list[i];
4603 break;
4604 }
4605 if (Math.abs(list[i].y - move.fromY) < 0.2)
4606 { block = list[i]; }
4607 }
4608 if (!block || !core.isDraggableBlock(block))
4609 { return false; }
4610 core.swapToward(block, move.toY);
4611 return true;
4612 }
4613
4614 /**
4615 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
4616 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
4617 */
4618 function tryBotRoll (core, skill, rng)
4619 {
4620 rng = rng || Math.random;
4621 var roll = rng();
4622 if (!(roll < skill))
4623 {
4624 return { rolled: true, success: false, moved: false, roll: roll, move: null };
4625 }
4626 var move = findBotMove(core);
4627 if (!move)
4628 {
4629 return { rolled: true, success: true, moved: false, roll: roll, move: null };
4630 }
4631 var ok = executeBotMove(core, move);
4632 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
4633 }
4634
4635 function pickPlanet (rng, P)
4636 {
4637 var all = P.allPlanets();
4638 if (!all.length)
4639 { return P.defaultPlanet(); }
4640 var i = Math.floor(rng() * all.length) % all.length;
4641 return all[i];
4642 }
4643
4644 function OfflineBattle (opts)
4645 {
4646 opts = opts || {};
4647 var P = PlanetMod();
4648 this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());
4649 this.rng = opts.rng || Math.random;
4650 this.round = opts.round || 1;
4651 this.schedule = scheduleForRound(this.round);
4652 this.clock = 0;
4653 this.state = 'playing';
4654 this.pending = [];
4655 this.flightResults = [];
4656 this.shotLocals = [];
4657 this.bots = [];
4658 this.playerId = 'player';
4659 this._initBots();
4660 }
4661
4662 OfflineBattle.prototype._initBots = function ()
4663 {
4664 var P = PlanetMod();
4665 var Ctor = GameCoreCtor();
4666 var n = this.schedule.opponents;
4667 this.bots = [];
4668 for (var i = 0; i < n; i++)
4669 {
4670 var planet = pickPlanet(this.rng, P);
4671 var miss = P.missChance(planet);
4672 var core = new Ctor(planet, this.rng, miss);
4673 this.bots.push({
4674 id: 'bot-' + (i + 1),
4675 name: 'Bot ' + (i + 1),
4676 planet: planet,
4677 core: core,
4678 eliminated: false,
4679 score: 0,
4680 aiAcc: 0
4681 });
4682 }
4683 };
4684
4685 OfflineBattle.prototype.aliveBots = function ()
4686 {
4687 var out = [];
4688 for (var i = 0; i < this.bots.length; i++)
4689 {
4690 if (!this.bots[i].eliminated && this.bots[i].core
4691 && this.bots[i].core.state !== 'gameover')
4692 { out.push(this.bots[i]); }
4693 }
4694 return out;
4695 };
4696
4697 OfflineBattle.prototype.coreFor = function (id, playerCore)
4698 {
4699 if (id === this.playerId)
4700 { return playerCore; }
4701 for (var i = 0; i < this.bots.length; i++)
4702 {
4703 if (this.bots[i].id === id)
4704 { return this.bots[i].core; }
4705 }
4706 return null;
4707 };
4708
4709 OfflineBattle.prototype._targetsFor = function (fromId, playerCore)
4710 {
4711 var targets = [];
4712 if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')
4713 { targets.push({ id: this.playerId, core: playerCore }); }
4714 for (var i = 0; i < this.bots.length; i++)
4715 {
4716 var bot = this.bots[i];
4717 if (bot.id === fromId || bot.eliminated)
4718 { continue; }
4719 if (bot.core && bot.core.state === 'playing')
4720 { targets.push({ id: bot.id, core: bot.core }); }
4721 }
4722 return targets;
4723 };
4724
4725 OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)
4726 {
4727 if (!core || !core.consumeOutgoingShots)
4728 { return; }
4729 var shots = core.consumeOutgoingShots();
4730 if (!shots.length)
4731 { return; }
4732 var P = PlanetMod();
4733 var missChance = (P && planet) ? P.missChance(planet) : 0.30;
4734 var targets = this._targetsFor(fromId, playerCore);
4735 for (var i = 0; i < shots.length; i++)
4736 {
4737 var shot = shots[i];
4738 var miss = targets.length === 0 || this.rng() < missChance;
4739 var target = null;
4740 if (!miss)
4741 {
4742 var idx = Math.floor(this.rng() * targets.length) % targets.length;
4743 target = targets[idx];
4744 }
4745 var clientId = fromId + '-' + shot.id + '-' + this.clock;
4746 var result = {
4747 client_id: clientId,
4748 miss: miss,
4749 target_id: target ? target.id : null,
4750 color: shot.color,
4751 flight_duration: FLIGHT_DURATION,
4752 from_id: fromId,
4753 col: shot.col,
4754 y: shot.y
4755 };
4756 this.flightResults.push(result);
4757 this.shotLocals.push({
4758 client_id: clientId,
4759 col: shot.col,
4760 y: shot.y,
4761 color: shot.color,
4762 from_id: fromId
4763 });
4764 if (!miss && target)
4765 {
4766 this.pending.push({
4767 at: this.clock + FLIGHT_DURATION,
4768 targetId: target.id,
4769 color: shot.color,
4770 fromId: fromId
4771 });
4772 }
4773 }
4774 };
4775
4776 OfflineBattle.prototype._deliver = function (playerCore)
4777 {
4778 var keep = [];
4779 for (var i = 0; i < this.pending.length; i++)
4780 {
4781 var ev = this.pending[i];
4782 if (this.clock + 1e-9 < ev.at)
4783 {
4784 keep.push(ev);
4785 continue;
4786 }
4787 var core = this.coreFor(ev.targetId, playerCore);
4788 if (core && core.state === 'playing' && core.ingestGarbage)
4789 { core.ingestGarbage(); }
4790 }
4791 this.pending = keep;
4792 };
4793
4794 OfflineBattle.prototype.tick = function (dt, playerCore)
4795 {
4796 this.flightResults = [];
4797 this.shotLocals = [];
4798 if (this.state !== 'playing')
4799 { return { flights: [], locals: [] }; }
4800 if (dt < 0)
4801 { dt = 0; }
4802 this.clock += dt;
4803
4804 var skill = this.schedule.skill;
4805 for (var i = 0; i < this.bots.length; i++)
4806 {
4807 var bot = this.bots[i];
4808 if (bot.eliminated)
4809 { continue; }
4810 if (bot.core.state === 'gameover')
4811 {
4812 bot.eliminated = true;
4813 bot.score = bot.core.score;
4814 continue;
4815 }
4816 bot.core.tick(dt);
4817 bot.score = bot.core.score;
4818 bot.aiAcc += dt;
4819 while (bot.aiAcc >= BOT_INTERVAL)
4820 {
4821 bot.aiAcc -= BOT_INTERVAL;
4822 if (bot.core.state === 'playing' && !bot.core.drag)
4823 { tryBotRoll(bot.core, skill, this.rng); }
4824 }
4825 }
4826
4827 this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);
4828 for (var i = 0; i < this.bots.length; i++)
4829 {
4830 var bot = this.bots[i];
4831 if (bot.eliminated)
4832 { continue; }
4833 this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);
4834 }
4835 this._deliver(playerCore);
4836
4837 for (var i = 0; i < this.bots.length; i++)
4838 {
4839 if (this.bots[i].core && this.bots[i].core.state === 'gameover')
4840 {
4841 this.bots[i].eliminated = true;
4842 this.bots[i].score = this.bots[i].core.score;
4843 }
4844 }
4845
4846 if (playerCore && playerCore.state === 'gameover')
4847 { this.state = 'lost'; }
4848 else if (this.aliveBots().length === 0 && this.bots.length > 0)
4849 { this.state = 'round_won'; }
4850
4851 return { flights: this.flightResults, locals: this.shotLocals };
4852 };
4853
4854 /**
4855 * Start the next round (fresh bots, new skill and opponent count).
4856 * The caller must also give the player a fresh GameCore.
4857 */
4858 OfflineBattle.prototype.advanceRound = function ()
4859 {
4860 this.round += 1;
4861 this.schedule = scheduleForRound(this.round);
4862 this.state = 'playing';
4863 this.pending = [];
4864 this.flightResults = [];
4865 this.shotLocals = [];
4866 this.clock = 0;
4867 this._initBots();
4868 return this.schedule;
4869 };
4870
4871 function createBattle (opts)
4872 {
4873 return new OfflineBattle(opts);
4874 }
4875
4876 var api = {
4877 BOT_INTERVAL: BOT_INTERVAL,
4878 SKILL_START: SKILL_START,
4879 SKILL_STEP: SKILL_STEP,
4880 SKILL_CAP: SKILL_CAP,
4881 FLIGHT_DURATION: FLIGHT_DURATION,
4882 ROUND_WON_DELAY: ROUND_WON_DELAY,
4883 roundsAtOpponentCount: roundsAtOpponentCount,
4884 skillForRound: skillForRound,
4885 scheduleForRound: scheduleForRound,
4886 findBotMove: findBotMove,
4887 tryBotRoll: tryBotRoll,
4888 executeBotMove: executeBotMove,
4889 snapshotGrid: snapshotGrid,
4890 applyColumnMove: applyColumnMove,
4891 hasMatch: hasMatch,
4892 createBattle: createBattle,
4893 OfflineBattle: OfflineBattle
4894 };
4895
4896 if (typeof module !== 'undefined' && module.exports)
4897 { module.exports = api; }
4898 else if (typeof globalThis !== 'undefined')
4899 { globalThis.Offline = api; }
4900
4901 return api;
4902
4903 })();
4904
4905 if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')
4906 { module.exports = Offline; }
4907
4908 /*
4909 * End File:
4910 * /workspace/meteors/src/offline.js
4911 */
4912
4913 /*
4914 * Start File:
4915 * /workspace/meteors/src/main.js
4916 */
4917 'use strict';
4918
4919 /**
4920 * View and input for Meteors. The simulation lives in GameCore; this file
4921 * only draws it, scales it to the viewport, and translates pointer events
4922 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
4923 * through Online (src/online.js) and the same GameCore. Offline Strijd
4924 * (t1119) uses Offline (src/offline.js) against local bots.
4925 */
4926
4927 function planetImages ()
4928 {
4929 var list = [
4930 { name: 'gray', url: 'images/block-gray.png' },
4931 { name: 'locked', url: 'images/block-locked.png' },
4932 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
4933 { name: 'cell', url: 'images/cell.png' },
4934 { name: 'pixel', url: 'images/pixel.png' },
4935 { name: 'columnWarn', url: 'images/column-warn.png' },
4936 // Keep the original Terra placeholders as aliases (Tim may still have them).
4937 { name: 'ember', url: 'images/block-ember.png' },
4938 { name: 'aqua', url: 'images/block-aqua.png' },
4939 { name: 'leaf', url: 'images/block-leaf.png' },
4940 { name: 'sun', url: 'images/block-sun.png' },
4941 { name: 'orchid', url: 'images/block-orchid.png' }
4942 ];
4943 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
4944 for (var i = 0; i < planets.length; i++)
4945 {
4946 var pl = planets[i];
4947 for (var c = 0; c < pl.colors.length; c++)
4948 {
4949 list.push({
4950 name: Planet.spriteKey(pl, c),
4951 url: pl.colors[c].image
4952 });
4953 }
4954 }
4955 return list;
4956 }
4957
4958 var IMAGES = planetImages();
4959 var GAME_OVER_DELAY = 2;
4960
4961 var game = new Game();
4962 var app = {
4963 mode: 'menu',
4964 core: null,
4965 scene: null,
4966 manager: null,
4967 planet: null,
4968 lastScore: 0,
4969 tile: 48,
4970 fieldX: 0,
4971 fieldY: 0,
4972 fieldW: 0,
4973 fieldH: 0,
4974 hudH: 56,
4975 sprites: Object.create(null),
4976 flames: Object.create(null),
4977 cells: [],
4978 pointerId: null,
4979 pointerType: null,
4980 activeTouchId: null,
4981 debugDrag: false,
4982 debugPhysics: false,
4983 gameOverShown: false,
4984 selectTween: null,
4985 online: false,
4986 eliminatedReported: false,
4987 spectating: false,
4988 miniH: 0,
4989 selectedPlanetId: 'terra',
4990 planetSelectContext: 'solo',
4991 offline: false,
4992 battle: null,
4993 swapTweens: null,
4994 columnWarn: null,
4995 warnClock: 0,
4996 miniAcc: 0,
4997 offlineResultShown: false,
4998 roundWonDelay: 0,
4999 roundWonHandled: false
5000 };
5001
5002 window.onload = function ()
5003 {
5004 app.debugDrag = isDragDebugEnabled();
5005 app.debugPhysics = isPhysicsDebugEnabled();
5006 var play = document.getElementById('btn-play');
5007 play.addEventListener('click', onPlay);
5008 play.addEventListener('pointerup', function (e)
5009 {
5010 // A touch-friendly path: some mobile browsers swallow the click
5011 // after a slightly sloppy tap. Ignore the following click.
5012 if (e.pointerType === 'touch' || e.pointerType === 'pen')
5013 {
5014 e.preventDefault();
5015 onPlay();
5016 }
5017 });
5018
5019 game.preloadImagesThenStart(IMAGES, function ()
5020 {
5021 if (game.images.flame && game.images.flame.addAnimationCycle)
5022 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
5023 });
5024
5025 bindOnlineUi();
5026 bindOfflineUi();
5027 bindPlanetSelect();
5028 restoreSelectedPlanet();
5029 };
5030
5031 function onPlay ()
5032 {
5033 if (app.mode === 'playing')
5034 { return; }
5035 openPlanetSelect('solo');
5036 }
5037
5038 function startPlay (opts)
5039 {
5040 opts = opts || {};
5041 hideEl('menu');
5042 hideEl('game-over');
5043 hideEl('online-panel');
5044 hideEl('spectator');
5045 hideEl('podium');
5046 hideEl('planet-select');
5047 hideEl('offline-result');
5048 showEl('hud');
5049
5050 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
5051 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
5052 var miss = opts.missChance;
5053 if (typeof miss !== 'number' || !isFinite(miss))
5054 { miss = planetMod.missChance(app.planet); }
5055 app.core = new GameCore(app.planet, Math.random, miss);
5056 if (app.debugPhysics)
5057 { app.core.debugInvariants = true; }
5058 app.mode = 'playing';
5059 app.online = !!opts.online;
5060 app.offline = !!opts.offline;
5061 app.gameOverShown = false;
5062 app.eliminatedReported = false;
5063 app.spectating = false;
5064 app.sprites = Object.create(null);
5065 app.flames = Object.create(null);
5066 app.cells = [];
5067 app.pointerId = null;
4156 5068 app.selectTween = null;
5069 app.swapTweens = Object.create(null);
5070 app.columnWarn = [];
5071 app.warnClock = 0;
5072 app.miniAcc = 1; // draw minis on the first frame
5073 app.offlineResultShown = false;
5074 if (!opts.keepBattle)
5075 {
5076 app.roundWonDelay = 0;
5077 app.roundWonHandled = false;
5078 }
5079 if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
5080 {
5081 app.battle = Offline.createBattle({
5082 playerPlanet: app.planet,
5083 rng: Math.random,
5084 round: opts.round || 1
5085 });
5086 }
4157 5087
4158 5088 layout();
4159 5089 if (app.scene)
@@ -4171,10 +5101,13 @@ function startPlay (opts)
4171 5101 if (!app.spectating)
4172 5102 { bindPointer(app.scene.canvas); }
4173 5103 refreshHud();
4174 if (app.online)
5104 if (app.online || app.offline)
4175 5105 { showEl('minis'); }
4176 5106 else
4177 5107 { hideEl('minis'); }
5108 buildColumnWarn();
5109 refreshOfflineHud();
5110 refreshChainIndicator();
4178 5111 }
4179 5112
4180 5113 function teardownPlay ()
@@ -4191,14 +5124,25 @@ function teardownPlay ()
4191 5124 app.flames = Object.create(null);
4192 5125 app.cells = [];
4193 5126 app.selectTween = null;
5127 app.swapTweens = Object.create(null);
5128 app.columnWarn = [];
4194 5129 app.pointerId = null;
4195 5130 app.gameOverShown = false;
4196 5131 hideEl('hud');
4197 5132 hideEl('game-over');
4198 5133 hideEl('spectator');
4199 5134 hideEl('minis');
5135 hideEl('offline-result');
5136 hideOfflineHud();
5137 hideChainIndicator();
4200 5138 if (typeof Online !== 'undefined')
4201 5139 { Online.clearFlights(); }
5140 if (!app._keepBattleOnTeardown)
5141 {
5142 app.battle = null;
5143 app.offline = false;
5144 }
5145 app._keepBattleOnTeardown = false;
4202 5146 }
4203 5147
4204 5148 function returnToMenu ()
@@ -4212,6 +5156,8 @@ function returnToMenu ()
4212 5156 teardownPlay();
4213 5157 app.mode = 'menu';
4214 5158 app.online = false;
5159 app.offline = false;
5160 app.battle = null;
4215 5161 hideEl('planet-select');
4216 5162 showEl('menu');
4217 5163 var last = document.getElementById('last-score');
@@ -4276,8 +5222,12 @@ function layout ()
4276 5222 catch (e) { /* ignore */ }
4277 5223 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
4278 5224 app.miniH = 0;
4279 if (app.online)
4280 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
5225 if (app.online || app.offline)
5226 {
5227 var nBots = (app.battle && app.battle.bots) ? app.battle.bots.length : 2;
5228 var share = nBots > 6 ? 0.26 : 0.20;
5229 app.miniH = Math.min(nBots > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));
5230 }
4281 5231 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
4282 5232 var availW = Math.max(80, vw - margin * 2);
4283 5233 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
@@ -4315,10 +5265,13 @@ function spriteFor (block)
4315 5265 return game.images[key] || game.images.gray;
4316 5266 }
4317 5267
4318 function syncSprites ()
5268 function syncSprites (dt)
4319 5269 {
4320 5270 if (!app.core || !app.scene)
4321 5271 { return; }
5272 dt = dt || 0;
5273 consumeAndStartSwapTweens();
5274 advanceSwapTweens(dt);
4322 5275 var seen = Object.create(null);
4323 5276 var blocks = app.core.blocks;
4324 5277 for (var i = 0; i < blocks.length; i++)
@@ -4333,7 +5286,7 @@ function syncSprites ()
4333 5286 app.sprites[block.id] = obj;
4334 5287 }
4335 5288 obj.renderer.sprite = spriteFor(block);
4336 placeTile(obj, block.col, block.y);
5289 placeTile(obj, block.col, blockVisualY(block));
4337 5290 applyBlockVisual(obj, block);
4338 5291 obj.renderer.visible = true;
4339 5292 obj.renderer.alpha = 1;
@@ -4471,6 +5424,95 @@ function updateSelectTween (dt)
4471 5424 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
4472 5425 }
4473 5426
5427
5428 /* ---------- visual-only swap tween (t1121) -------------------------- */
5429
5430 function swapTweenSpec ()
5431 {
5432 if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
5433 { return Easing.SWAP_TWEEN; }
5434 return { duration: 0.100, ease: null };
5435 }
5436
5437 function swapEase (u)
5438 {
5439 if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
5440 { return Easing.easeOutCubic(u); }
5441 var v = 1 - Math.max(0, Math.min(1, u));
5442 return 1 - v * v * v;
5443 }
5444
5445 function tweenVisualY (tw)
5446 {
5447 var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
5448 return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
5449 }
5450
5451 /**
5452 * Consume GameCore swap events. The currently dragged block is skipped
5453 * (it follows the pointer). A block that is mid-tween and is swapped
5454 * again restarts from its current visual y, so rapid swaps chain
5455 * smoothly without snapping.
5456 */
5457 function consumeAndStartSwapTweens ()
5458 {
5459 if (!app.core || !app.core.consumeSwapEvents)
5460 { return; }
5461 if (!app.swapTweens)
5462 { app.swapTweens = Object.create(null); }
5463 var ev = app.core.consumeSwapEvents();
5464 if (!ev.length)
5465 { return; }
5466 var dragId = app.core.drag && app.core.drag.blockId;
5467 var duration = swapTweenSpec().duration;
5468 for (var i = 0; i < ev.length; i++)
5469 {
5470 var e = ev[i];
5471 if (e.id === dragId)
5472 {
5473 delete app.swapTweens[e.id];
5474 continue;
5475 }
5476 var fromY = e.fromY;
5477 var existing = app.swapTweens[e.id];
5478 if (existing)
5479 { fromY = tweenVisualY(existing); }
5480 app.swapTweens[e.id] = {
5481 fromY: fromY,
5482 toY: e.toY,
5483 age: 0,
5484 duration: duration
5485 };
5486 }
5487 }
5488
5489 function advanceSwapTweens (dt)
5490 {
5491 if (!app.swapTweens)
5492 { return; }
5493 var ids = Object.keys(app.swapTweens);
5494 for (var i = 0; i < ids.length; i++)
5495 {
5496 var tw = app.swapTweens[ids[i]];
5497 tw.age += dt;
5498 if (tw.age >= tw.duration)
5499 { delete app.swapTweens[ids[i]]; }
5500 }
5501 }
5502
5503 function blockVisualY (block)
5504 {
5505 if (!app.swapTweens)
5506 { return block.y; }
5507 var dragId = app.core && app.core.drag && app.core.drag.blockId;
5508 if (block.id === dragId)
5509 { return block.y; }
5510 var tw = app.swapTweens[block.id];
5511 if (!tw)
5512 { return block.y; }
5513 return tweenVisualY(tw);
5514 }
5515
4474 5516 function refreshHud ()
4475 5517 {
4476 5518 if (!app.core)
@@ -4512,9 +5554,14 @@ function tickView (dt)
4512 5554 }
4513 5555
4514 5556 app.core.tick(dt);
5557 if (app.offline && app.battle)
5558 { tickOffline(dt); }
4515 5559 updateSelectTween(dt);
4516 syncSprites();
5560 syncSprites(dt);
5561 updateColumnWarn(dt);
4517 5562 refreshHud();
5563 refreshOfflineHud();
5564 refreshChainIndicator();
4518 5565 tickOnline(dt);
4519 5566 if (app.debugPhysics)
4520 5567 { logPhysicsDebug(); }
@@ -4526,10 +5573,13 @@ function tickView (dt)
4526 5573 document.getElementById('go-score').textContent = String(app.lastScore);
4527 5574 if (app.online)
4528 5575 { onOnlineEliminated(); }
5576 else if (app.offline)
5577 { /* Offline result is shown from tickOffline. */ }
4529 5578 else
4530 5579 { showEl('game-over'); }
4531 5580 }
4532 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
5581 if (!app.online && !app.offline && app.core.state === 'gameover'
5582 && app.core.gameOverTime >= GAME_OVER_DELAY)
4533 5583 { returnToMenu(); }
4534 5584 }
4535 5585
@@ -5032,6 +6082,313 @@ function tickOnline (dt)
5032 6082 Online.renderMinis(document.getElementById('minis'));
5033 6083 }
5034 6084
6085
6086 /* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
6087
6088 function bindOfflineUi ()
6089 {
6090 var btn = document.getElementById('btn-offline');
6091 if (btn)
6092 {
6093 btn.addEventListener('click', onOffline);
6094 btn.addEventListener('pointerup', function (e)
6095 {
6096 if (e.pointerType === 'touch' || e.pointerType === 'pen')
6097 {
6098 e.preventDefault();
6099 onOffline();
6100 }
6101 });
6102 }
6103 var back = document.getElementById('btn-offline-menu');
6104 if (back)
6105 {
6106 back.addEventListener('click', function ()
6107 {
6108 teardownPlay();
6109 app.mode = 'menu';
6110 app.offline = false;
6111 app.battle = null;
6112 hideEl('offline-result');
6113 showEl('menu');
6114 });
6115 }
6116 }
6117
6118 function onOffline ()
6119 {
6120 openPlanetSelect('offline');
6121 }
6122
6123 function tickOffline (dt)
6124 {
6125 if (!app.battle || !app.core || typeof Offline === 'undefined')
6126 { return; }
6127
6128 if (app.battle.state === 'round_won')
6129 {
6130 if (!app.roundWonHandled)
6131 {
6132 app.roundWonHandled = true;
6133 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
6134 }
6135 app.roundWonDelay -= dt;
6136 if (app.roundWonDelay <= 0)
6137 { startNextOfflineRound(); }
6138 updateOfflineMinis(dt, true);
6139 return;
6140 }
6141
6142 var result = app.battle.tick(dt, app.core);
6143 if (result && result.flights && result.flights.length
6144 && typeof Online !== 'undefined' && Online.spawnFlights)
6145 {
6146 var locals = Object.create(null);
6147 var list = result.locals || [];
6148 for (var i = 0; i < list.length; i++)
6149 {
6150 var s = list[i];
6151 var start;
6152 if (s.from_id === 'player')
6153 { start = fieldToViewport(s.col, s.y + 1); }
6154 else
6155 { start = miniViewportCenter(s.from_id); }
6156 locals[s.client_id] = {
6157 col: s.col,
6158 y: s.y,
6159 color: s.color,
6160 startX: start.x,
6161 startY: start.y
6162 };
6163 }
6164 Online.spawnFlights(result.flights, locals);
6165 }
6166 if (typeof Online !== 'undefined' && Online.tickFlights)
6167 { Online.tickFlights(); }
6168 updateOfflineMinis(dt, false);
6169
6170 if (app.battle.state === 'lost' && !app.offlineResultShown)
6171 { showOfflineResult(); }
6172 }
6173
6174 function startNextOfflineRound ()
6175 {
6176 if (!app.battle)
6177 { return; }
6178 app.battle.advanceRound();
6179 app.roundWonHandled = false;
6180 app.roundWonDelay = 0;
6181 app._keepBattleOnTeardown = true;
6182 // Tear down the current scene then start a fresh player field,
6183 // keeping the same battle (already advanced).
6184 var planet = app.battle.playerPlanet;
6185 app._keepBattleOnTeardown = true;
6186 teardownPlay();
6187 app.offline = true;
6188 app.battle = app.battle; // kept
6189 startPlay({ planet: planet, offline: true, keepBattle: true });
6190 }
6191
6192 function showOfflineResult ()
6193 {
6194 app.offlineResultShown = true;
6195 var battle = app.battle;
6196 var reached = document.getElementById('offline-reached');
6197 if (reached)
6198 { reached.textContent = String(battle.round); }
6199 var detail = document.getElementById('offline-result-detail');
6200 if (detail)
6201 {
6202 var sch = battle.schedule;
6203 var n = sch.opponents;
6204 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
6205 detail.textContent = 'Je speelde tegen ' + n + ' ' + noun
6206 + ' met skill ' + Math.round(sch.skill * 100) + '%.';
6207 }
6208 hideEl('game-over');
6209 showEl('offline-result');
6210 }
6211
6212 function refreshOfflineHud ()
6213 {
6214 var el = document.getElementById('offline-hud');
6215 if (!el)
6216 { return; }
6217 if (!(app.offline && app.battle && app.mode === 'playing'))
6218 {
6219 el.hidden = true;
6220 return;
6221 }
6222 el.hidden = false;
6223 var sch = app.battle.schedule;
6224 var n = sch.opponents;
6225 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
6226 var r = document.getElementById('offline-round');
6227 var o = document.getElementById('offline-opponents');
6228 var s = document.getElementById('offline-skill');
6229 if (r)
6230 { r.textContent = 'Ronde ' + sch.round; }
6231 if (o)
6232 { o.textContent = n + ' ' + noun; }
6233 if (s)
6234 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
6235 }
6236
6237 function hideOfflineHud ()
6238 {
6239 var el = document.getElementById('offline-hud');
6240 if (el)
6241 { el.hidden = true; }
6242 }
6243
6244 function refreshChainIndicator ()
6245 {
6246 var el = document.getElementById('chain-indicator');
6247 if (!el)
6248 { return; }
6249 var info = app.core && app.core.lastChainIndicator;
6250 var active = app.core && app.core.hasActiveLandingChain
6251 && app.core.hasActiveLandingChain();
6252 // Show only while a chained cluster is still in the air.
6253 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
6254 {
6255 el.hidden = true;
6256 return;
6257 }
6258 el.hidden = false;
6259 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
6260 }
6261
6262 function hideChainIndicator ()
6263 {
6264 var el = document.getElementById('chain-indicator');
6265 if (el)
6266 { el.hidden = true; }
6267 }
6268
6269 function miniViewportCenter (botId)
6270 {
6271 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
6272 if (!el)
6273 { return { x: window.innerWidth / 2, y: 40 }; }
6274 var rect = el.getBoundingClientRect();
6275 return { x: rect.left + rect.width / 2, y: rect.bottom };
6276 }
6277
6278 function offlineMiniSize (n)
6279 {
6280 if (n >= 10)
6281 { return { w: 40, h: 52 }; }
6282 if (n >= 6)
6283 { return { w: 56, h: 73 }; }
6284 return { w: 80, h: 104 };
6285 }
6286
6287 function updateOfflineMinis (dt, force)
6288 {
6289 app.miniAcc = (app.miniAcc || 0) + dt;
6290 if (!force && app.miniAcc < 0.1)
6291 { return; }
6292 app.miniAcc = 0;
6293 renderOfflineMinis();
6294 }
6295
6296 function renderOfflineMinis ()
6297 {
6298 var container = document.getElementById('minis');
6299 if (!container || !app.battle)
6300 { return; }
6301 var bots = app.battle.bots;
6302 var size = offlineMiniSize(bots.length);
6303 container.classList.toggle('crowded', bots.length > 5);
6304 var existing = {};
6305 var kids = container.querySelectorAll('[data-player]');
6306 for (var i = 0; i < kids.length; i++)
6307 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
6308 var seen = Object.create(null);
6309 for (var i = 0; i < bots.length; i++)
6310 {
6311 var bot = bots[i];
6312 seen[bot.id] = true;
6313 var el = existing[bot.id];
6314 if (!el)
6315 {
6316 el = document.createElement('div');
6317 el.className = 'mini';
6318 el.setAttribute('data-player', bot.id);
6319 el.innerHTML = '<div class="mini-name"></div>'
6320 + '<canvas class="mini-canvas" width="' + size.w
6321 + '" height="' + size.h + '"></canvas>'
6322 + '<div class="mini-meta"></div>';
6323 container.appendChild(el);
6324 }
6325 var canvas = el.querySelector('canvas');
6326 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
6327 {
6328 canvas.width = size.w;
6329 canvas.height = size.h;
6330 }
6331 el.classList.toggle('eliminated', !!bot.eliminated);
6332 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
6333 el.querySelector('.mini-name').textContent = bot.name
6334 + (planetName ? ' · ' + planetName : '');
6335 el.querySelector('.mini-meta').textContent = bot.eliminated
6336 ? 'Uit'
6337 : ('Punten ' + (bot.score || 0));
6338 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
6339 if (typeof Online !== 'undefined' && Online._drawMini)
6340 { Online._drawMini(canvas, snap, bot.planet); }
6341 }
6342 for (var id in existing)
6343 {
6344 if (!seen[id])
6345 { existing[id].remove(); }
6346 }
6347 }
6348
6349 function buildColumnWarn ()
6350 {
6351 app.columnWarn = [];
6352 if (!app.scene)
6353 { return; }
6354 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
6355 if (!img)
6356 { return; }
6357 for (var c = 0; c < 10; c++)
6358 {
6359 var obj = new GameObject(0, 0, img, 0);
6360 obj.renderer.alpha = 0;
6361 obj.renderer.visible = false;
6362 app.scene.addObject(obj);
6363 app.columnWarn.push(obj);
6364 }
6365 updateColumnWarn(0);
6366 }
6367
6368 function updateColumnWarn (dt)
6369 {
6370 if (!app.columnWarn || !app.core)
6371 { return; }
6372 app.warnClock = (app.warnClock || 0) + (dt || 0);
6373 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
6374 ? GameCore.columnWarnPulse(app.warnClock)
6375 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
6376 var t = app.tile;
6377 for (var c = 0; c < app.columnWarn.length; c++)
6378 {
6379 var obj = app.columnWarn[c];
6380 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
6381 obj.renderer.visible = !!on;
6382 obj.renderer.alpha = on ? pulse : 0;
6383 if (t)
6384 {
6385 obj.transform.position.x = c * t + t / 2;
6386 obj.transform.position.y = app.fieldH / 2;
6387 obj.transform.size = { x: t, y: app.fieldH };
6388 }
6389 }
6390 }
6391
5035 6392 function fieldToViewport (col, fieldY)
5036 6393 {
5037 6394 var canvas = app.scene && app.scene.canvas;
@@ -5519,6 +6876,11 @@ function confirmPlanetSelect ()
5519 6876 openOnlinePanel();
5520 6877 return;
5521 6878 }
6879 if (app.planetSelectContext === 'offline')
6880 {
6881 startPlay({ planet: planet, offline: true });
6882 return;
6883 }
5522 6884 startPlay({ planet: planet });
5523 6885 }
5524 6886
@@ -256,10 +256,16 @@ else if (typeof globalThis !== 'undefined')
256 * that later planets only need new data, not new physics code.
256 * that later planets only need new data, not new physics code.
257 *
257 *
258 * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
258 * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
259 * A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles —
259 * A horizontal match of 3 jumps JUMP_HEIGHT_SCALE * FIELD_HEIGHT
260 * at 1, one jump from the floor clears the field; at 4, you need four.
260 * / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the
261 * minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so
262 * one jump from the floor clears the 13-tile field with room to spare;
263 * at 4 you still need more than one jump, but each is 50% taller.
261 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
264 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
262 * After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.
265 * After a jump peaks, blocks float down at DESCENT_SPEED_SCALE *
266 * FIELD_HEIGHT / fallTime tiles/s (DESCENT_SPEED_SCALE is 0.5 since
267 * t1122: all descent speeds are halved). Relative differences between
268 * planets (1 / fallTime) are unchanged. Upward launch is not affected.
263 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
269 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
264 * Time to reach the apex, independent of jump height.
270 * Time to reach the apex, independent of jump height.
265 *
271 *
@@ -274,6 +280,14 @@ else if (typeof globalThis !== 'undefined')
274
280
275var FIELD_WIDTH = 10;
281var FIELD_WIDTH = 10;
276var FIELD_HEIGHT = 13;
282var FIELD_HEIGHT = 13;
283/** t1119: every match jump (the gravity-applied minimum and the
284 * vertical / extra-block bonuses derived from it) is 50% higher. */
285var JUMP_HEIGHT_SCALE = 1.5;
286/** t1122: every descent speed is halved. Terminal fallSpeed, spawn
287 * fall, unsupported / released / cargo fall, and the post-apex
288 * float-down all use this scale. Upward launch is unchanged. */
289var DESCENT_SPEED_SCALE = 0.5;
290
277
291
278function clamp (value, lo, hi)
292function clamp (value, lo, hi)
279{
293{
@@ -306,12 +320,14 @@ function createPlanet (opts)
306 fallTime: fallTime,
320 fallTime: fallTime,
307 riseTime: riseTime,
321 riseTime: riseTime,
308 colors: colors,
322 colors: colors,
309 baseJumpHeight: FIELD_HEIGHT / jumpsToClear,
323 baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear,
310 fallSpeed: FIELD_HEIGHT / fallTime,
324 fallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime,
311 // Time to ease from vy=0 at the apex to terminal fallSpeed.
325 // Time to ease from vy=0 at the apex to terminal fallSpeed.
312 // Shorter when air resistance is low (small fallTime).
326 // Shorter when air resistance is low (small fallTime). The ease
327 // duration is unchanged; fallAccel scales with the halved
328 // fallSpeed so the ease still lasts apexEaseTime seconds.
313 apexEaseTime: 0.15 * fallTime,
329 apexEaseTime: 0.15 * fallTime,
314 fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
330 fallAccel: (DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
315 // Visual landing bounce: faster at low air resistance. Stage-3 params.
331 // Visual landing bounce: faster at low air resistance. Stage-3 params.
316 bounceDuration: 0.12 * fallTime,
332 bounceDuration: 0.12 * fallTime,
317 bounceSquash: 0.16
333 bounceSquash: 0.16
@@ -480,6 +496,8 @@ function displayValues (planet)
480var Planet = {
496var Planet = {
481 FIELD_WIDTH: FIELD_WIDTH,
497 FIELD_WIDTH: FIELD_WIDTH,
482 FIELD_HEIGHT: FIELD_HEIGHT,
498 FIELD_HEIGHT: FIELD_HEIGHT,
499 JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE,
500 DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE,
483 COLOR_COUNT: 5,
501 COLOR_COUNT: 5,
484 SETTLE_TIME: 3,
502 SETTLE_TIME: 3,
485 SPAWN_INTERVAL: 1,
503 SPAWN_INTERVAL: 1,
@@ -571,11 +589,29 @@ function easeOutElastic (t)
571 return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
589 return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
572}
590}
573
591
592/** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */
593function easeOutCubic (t)
594{
595 t = clamp01(t);
596 var u = 1 - t;
597 return 1 - u * u * u;
598}
599
574function tween (from, to, t, ease)
600function tween (from, to, t, ease)
575{
601{
576 return from + (to - from) * ease(clamp01(t));
602 return from + (to - from) * ease(clamp01(t));
577}
603}
578
604
605/**
606 * Visual-only block swap tween (t1121). Game logic and the grid update
607 * immediately; this only moves the displaced sprite. 100 ms sits in the
608 * requested 80–120 ms range.
609 */
610var SWAP_TWEEN = {
611 duration: 0.100,
612 ease: easeOutCubic
613};
614
579/**
615/**
580 * DEFAULT settings of Tim's KWin Click Tween
616 * DEFAULT settings of Tim's KWin Click Tween
581 * (git.timfalken.com/timfa/click-tween).
617 * (git.timfalken.com/timfa/click-tween).
@@ -619,8 +655,10 @@ var Easing = {
619 ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
655 ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
620 easeOutBack: easeOutBack,
656 easeOutBack: easeOutBack,
621 easeOutElastic: easeOutElastic,
657 easeOutElastic: easeOutElastic,
658 easeOutCubic: easeOutCubic,
622 tween: tween,
659 tween: tween,
623 CLICK_TWEEN: CLICK_TWEEN,
660 CLICK_TWEEN: CLICK_TWEEN,
661 SWAP_TWEEN: SWAP_TWEEN,
624 clamp01: clamp01,
662 clamp01: clamp01,
625 bouncePose: bouncePose
663 bouncePose: bouncePose
626};
664};
@@ -672,6 +710,13 @@ var SWAP_DISTANCE = 0.25;
672var SNAP_Y = 0.5;
710var SNAP_Y = 0.5;
673// Horizontal slop (tiles) for snapping to a neighbouring column on press.
711// Horizontal slop (tiles) for snapping to a neighbouring column on press.
674var HORIZONTAL_SLOP = 0.35;
712var HORIZONTAL_SLOP = 0.35;
713/** t1120: additive jump bonus per landing-chain step. A landing that
714 * immediately makes a match launches at (1 + 0.25 * chain) times the
715 * usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */
716var LANDING_CHAIN_BONUS = 0.25;
717/** t1123: a column pulses red at or above this many grounded rows
718 * (10 of 13 is just over 70%). */
719var COLUMN_WARN_ROWS = 10;
675
720
676function UnionFind ()
721function UnionFind ()
677{
722{
@@ -726,6 +771,10 @@ function GameCore (planet, rng)
726 this.strictInvariants = false;
771 this.strictInvariants = false;
727 this.debugInvariants = false;
772 this.debugInvariants = false;
728 this.lastInvariantViolations = [];
773 this.lastInvariantViolations = [];
774 // t1121: visual-only swap events, consumed by the view each frame.
775 this.swapEvents = [];
776 // t1120: last landing-chain indicator { chain, bonusPct }, or null.
777 this.lastChainIndicator = null;
729}
778}
730
779
731function optsMissChance (args)
780function optsMissChance (args)
@@ -744,6 +793,8 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
744GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
793GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
745GameCore.SNAP_Y = SNAP_Y;
794GameCore.SNAP_Y = SNAP_Y;
746GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
795GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
796GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;
797GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;
747GameCore.DEFAULT_MISS_CHANCE = 0.30;
798GameCore.DEFAULT_MISS_CHANCE = 0.30;
748GameCore.STATE_STILL = STATE_STILL;
799GameCore.STATE_STILL = STATE_STILL;
749GameCore.STATE_FALLING = STATE_FALLING;
800GameCore.STATE_FALLING = STATE_FALLING;
@@ -892,6 +943,56 @@ GameCore.prototype.groundedCount = function (col)
892 return n;
943 return n;
893};
944};
894
945
946GameCore.prototype.columnNeedsWarn = function (col)
947{
948 return this.groundedCount(col) >= COLUMN_WARN_ROWS;
949};
950
951/**
952 * Which columns of a field snapshot should pulse (t1123). Flying,
953 * falling and manual (airborne) blocks do not count: they are
954 * temporary and would flicker the warning. Still, settling and
955 * locked (grounded) blocks do.
956 */
957GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)
958{
959 threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;
960 var width = (snapshot && snapshot.width) || 10;
961 var flags = [];
962 var counts = [];
963 for (var c = 0; c < width; c++)
964 {
965 counts[c] = 0;
966 flags[c] = false;
967 }
968 var blocks = (snapshot && snapshot.blocks) || [];
969 for (var i = 0; i < blocks.length; i++)
970 {
971 var b = blocks[i];
972 if (b.col < 0 || b.col >= width)
973 { continue; }
974 if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')
975 { counts[b.col]++; }
976 }
977 for (var c = 0; c < width; c++)
978 { flags[c] = counts[c] >= threshold; }
979 return flags;
980};
981
982GameCore.columnWarnPulse = function (timeSec)
983{
984 // Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player
985 // field and opponent / bot minis so they pulse in sync.
986 var t = timeSec;
987 if (t == null)
988 {
989 t = (typeof performance !== 'undefined' && performance.now)
990 ? performance.now() / 1000
991 : Date.now() / 1000;
992 }
993 return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));
994};
995
895GameCore.prototype.blockAt = function (col, row)
996GameCore.prototype.blockAt = function (col, row)
896{
997{
897 for (var i = 0; i < this.blocks.length; i++)
998 for (var i = 0; i < this.blocks.length; i++)
@@ -1513,6 +1614,14 @@ GameCore.prototype.mergeClusterGroup = function (clusters)
1513 keep.decel = decelSum / n;
1614 keep.decel = decelSum / n;
1514 keep.jumpHeight = hSum / n;
1615 keep.jumpHeight = hSum / n;
1515 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1616 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1617 var maxChain = 0;
1618 for (var c = 0; c < clusters.length; c++)
1619 {
1620 var ch = clusters[c].landingChain || 0;
1621 if (ch > maxChain)
1622 { maxChain = ch; }
1623 }
1624 keep.landingChain = maxChain;
1516 for (var c = 0; c < clusters.length; c++)
1625 for (var c = 0; c < clusters.length; c++)
1517 {
1626 {
1518 var mem = this.clusterMembers(clusters[c].id);
1627 var mem = this.clusterMembers(clusters[c].id);
@@ -1907,6 +2016,9 @@ GameCore.prototype.landCluster = function (cluster, members)
1907 }
2016 }
1908 cluster.phase = 'landed';
2017 cluster.phase = 'landed';
1909 cluster.vy = 0;
2018 cluster.vy = 0;
2019 cluster.landedPending = true;
2020 if (cluster.landingChain == null)
2021 { cluster.landingChain = 0; }
1910};
2022};
1911
2023
1912/**
2024/**
@@ -1928,6 +2040,10 @@ GameCore.prototype.releaseLandedCluster = function (cluster)
1928 block.color = this.randomColor();
2040 block.color = this.randomColor();
1929 block.settleTime = 0;
2041 block.settleTime = 0;
1930 }
2042 }
2043 // Persist the chain across release so a post-recolor match in
2044 // this same tick still gets the landing bonus (t1120).
2045 block.justLanded = !!cluster.landedPending;
2046 block.landingChain = cluster.landingChain || 0;
1931 this.leaveCluster(block);
2047 this.leaveCluster(block);
1932 // Always drop leftover launch / manual velocity. A stale upward
2048 // Always drop leftover launch / manual velocity. A stale upward
1933 // vy here is what sends blocks off the top "very fast" after
2049 // vy here is what sends blocks off the top "very fast" after
@@ -2803,7 +2919,10 @@ GameCore.prototype.resolveMatches = function ()
2803 { return []; }
2919 { return []; }
2804 var lines = this.findMatchLines();
2920 var lines = this.findMatchLines();
2805 if (!lines.length)
2921 if (!lines.length)
2806 { return []; }
2922 {
2923 this.finishLandingChains([]);
2924 return [];
2925 }
2807
2926
2808 var uf = new UnionFind();
2927 var uf = new UnionFind();
2809 var blockById = Object.create(null);
2928 var blockById = Object.create(null);
@@ -2870,9 +2989,19 @@ GameCore.prototype.resolveMatches = function ()
2870 { height = h; }
2989 { height = h; }
2871 }
2990 }
2872 }
2991 }
2873 this.launchCluster(group, height);
2992 var chain = this.landingChainFor(group);
2874 launched.push({ blocks: group, jumpHeight: height });
2993 var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
2994 height *= bonusMul;
2995 this.launchCluster(group, height, { landingChain: chain });
2996 launched.push({
2997 blocks: group,
2998 jumpHeight: height,
2999 landingChain: chain,
3000 chainBonus: bonusMul
3001 });
2875 }
3002 }
3003 this.finishLandingChains(launched);
3004 this.updateChainIndicator(launched);
2876 return launched;
3005 return launched;
2877};
3006};
2878
3007
@@ -2880,8 +3009,9 @@ GameCore.prototype.resolveMatches = function ()
2880 * Gray the matched blocks, take everything sitting on top of them in
3009 * Gray the matched blocks, take everything sitting on top of them in
2881 * those columns, link them, and launch with jump height `height`.
3010 * those columns, link them, and launch with jump height `height`.
2882 */
3011 */
2883GameCore.prototype.launchCluster = function (matchedBlocks, height)
3012GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
2884{
3013{
3014 opts = opts || {};
2885 var lowestInCol = Object.create(null);
3015 var lowestInCol = Object.create(null);
2886 var matchedIds = Object.create(null);
3016 var matchedIds = Object.create(null);
2887 for (var i = 0; i < matchedBlocks.length; i++)
3017 for (var i = 0; i < matchedBlocks.length; i++)
@@ -2898,7 +3028,9 @@ GameCore.prototype.launchCluster = function (matchedBlocks, height)
2898 jumpHeight: height,
3028 jumpHeight: height,
2899 vy: PlanetMod.launchVelocity(this.planet, height),
3029 vy: PlanetMod.launchVelocity(this.planet, height),
2900 decel: PlanetMod.launchDeceleration(this.planet, height),
3030 decel: PlanetMod.launchDeceleration(this.planet, height),
2901 phase: 'up'
3031 phase: 'up',
3032 landingChain: opts.landingChain || 0,
3033 landedPending: false
2902 };
3034 };
2903 this.clusters[clusterId] = cluster;
3035 this.clusters[clusterId] = cluster;
2904
3036
@@ -3274,10 +3406,149 @@ GameCore.prototype.swapToward = function (block, targetY)
3274
3406
3275GameCore.prototype.swapBlocks = function (a, b)
3407GameCore.prototype.swapBlocks = function (a, b)
3276{
3408{
3277 var y = a.y;
3409 var ay = a.y;
3278 a.y = b.y;
3410 var by = b.y;
3279 b.y = y;
3411 a.y = by;
3412 b.y = ay;
3280 this.transferLandedMembership(a, b);
3413 this.transferLandedMembership(a, b);
3414 if (!this.swapEvents)
3415 { this.swapEvents = []; }
3416 this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
3417 this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
3418};
3419
3420GameCore.prototype.consumeSwapEvents = function ()
3421{
3422 var ev = this.swapEvents || [];
3423 this.swapEvents = [];
3424 return ev;
3425};
3426
3427/**
3428 * Highest landing-chain counter among just-landed members of this
3429 * match group, plus one. Returns 0 when the match did not come from
3430 * a cluster landing (player/bot swap, mid-air, etc.).
3431 */
3432GameCore.prototype.landingChainFor = function (group)
3433{
3434 var maxChain = 0;
3435 var fromLanding = false;
3436 for (var i = 0; i < group.length; i++)
3437 {
3438 var block = group[i];
3439 if (block.justLanded)
3440 {
3441 fromLanding = true;
3442 if ((block.landingChain || 0) > maxChain)
3443 { maxChain = block.landingChain || 0; }
3444 }
3445 if (block.clusterId != null)
3446 {
3447 var cluster = this.clusters[block.clusterId];
3448 if (cluster && cluster.landedPending)
3449 {
3450 fromLanding = true;
3451 if ((cluster.landingChain || 0) > maxChain)
3452 { maxChain = cluster.landingChain || 0; }
3453 }
3454 }
3455 }
3456 if (!fromLanding)
3457 { return 0; }
3458 return maxChain + 1;
3459};
3460
3461/**
3462 * After resolveMatches: clear the landing-pending flag and reset the
3463 * chain on landings that did not make a match. A cluster that is still
3464 * settling (greys not yet recolored) keeps landedPending so a later
3465 * post-recolor match in this same landing still gets the bonus.
3466 */
3467GameCore.prototype.finishLandingChains = function (launched)
3468{
3469 var launchedIds = Object.create(null);
3470 launched = launched || [];
3471 for (var i = 0; i < launched.length; i++)
3472 {
3473 var blocks = launched[i].blocks || [];
3474 for (var j = 0; j < blocks.length; j++)
3475 { launchedIds[blocks[j].id] = true; }
3476 }
3477
3478 for (var i = 0; i < this.blocks.length; i++)
3479 {
3480 var block = this.blocks[i];
3481 if (!block.justLanded)
3482 { continue; }
3483 if (!launchedIds[block.id])
3484 { block.landingChain = 0; }
3485 block.justLanded = false;
3486 }
3487
3488 var ids = Object.keys(this.clusters);
3489 for (var c = 0; c < ids.length; c++)
3490 {
3491 var cluster = this.clusters[ids[c]];
3492 if (!cluster || !cluster.landedPending)
3493 { continue; }
3494 var members = this.clusterMembers(cluster.id);
3495 var anyLaunched = false;
3496 var stillSettling = false;
3497 for (var i = 0; i < members.length; i++)
3498 {
3499 if (launchedIds[members[i].id])
3500 { anyLaunched = true; }
3501 if (members[i].state === STATE_SETTLING)
3502 { stillSettling = true; }
3503 }
3504 if (anyLaunched)
3505 {
3506 cluster.landingChain = 0;
3507 cluster.landedPending = false;
3508 }
3509 else if (!stillSettling)
3510 {
3511 // Released leftovers or a fully-still landed group that
3512 // already had its match opportunity and missed it.
3513 cluster.landingChain = 0;
3514 cluster.landedPending = false;
3515 }
3516 // else: still settling, no match yet — keep landedPending.
3517 }
3518};
3519
3520GameCore.prototype.updateChainIndicator = function (launched)
3521{
3522 var maxChain = 0;
3523 for (var i = 0; i < launched.length; i++)
3524 {
3525 var ch = launched[i].landingChain || 0;
3526 if (ch > maxChain)
3527 { maxChain = ch; }
3528 }
3529 if (maxChain >= 1)
3530 {
3531 this.lastChainIndicator = {
3532 chain: maxChain,
3533 bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
3534 };
3535 return;
3536 }
3537 if (!this.hasActiveLandingChain())
3538 { this.lastChainIndicator = null; }
3539};
3540
3541GameCore.prototype.hasActiveLandingChain = function ()
3542{
3543 var ids = Object.keys(this.clusters);
3544 for (var i = 0; i < ids.length; i++)
3545 {
3546 var cluster = this.clusters[ids[i]];
3547 if (cluster && (cluster.landingChain || 0) >= 1
3548 && cluster.phase !== 'landed')
3549 { return true; }
3550 }
3551 return false;
3281};
3552};
3282
3553
3283/**
3554/**
@@ -3811,6 +4082,19 @@ Online._drawMini = function (canvas, snapshot, planet)
3811 }
4082 }
3812 if (!snapshot || !snapshot.blocks)
4083 if (!snapshot || !snapshot.blocks)
3813 { return; }
4084 { return; }
4085 // t1123: cheap sine pulse behind blocks of nearly-full columns.
4086 if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
4087 {
4088 var warns = GameCore.warnColumnsFromSnapshot(snapshot);
4089 var pulse = GameCore.columnWarnPulse();
4090 for (var wc = 0; wc < warns.length; wc++)
4091 {
4092 if (!warns[wc])
4093 { continue; }
4094 ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
4095 ctx.fillRect(wc * tw, 0, tw, canvas.height);
4096 }
4097 }
3814 var blocks = snapshot.blocks;
4098 var blocks = snapshot.blocks;
3815 for (var i = 0; i < blocks.length; i++)
4099 for (var i = 0; i < blocks.length; i++)
3816 {
4100 {
@@ -4014,146 +4298,792 @@ if (typeof module !== 'undefined' && module.exports)
4014
4298
4015/*
4299/*
4016 * Start File:
4300 * Start File:
4017 * /workspace/meteors/src/main.js
4301 * /workspace/meteors/src/offline.js
4018 */
4302 */
4019'use strict';
4303'use strict';
4020
4304
4021/**
4305/**
4022 * View and input for Meteors. The simulation lives in GameCore; this file
4306 * Offline Strijd: a client-side single-player mode that plays like
4023 * only draws it, scales it to the viewport, and translates pointer events
4307 * multiplayer (shots, miss chance, opponent minis) against local bots
4024 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
4308 * (t1119). Pure simulation — no server.
4025 * through Online (src/online.js) and the same GameCore.
4026 */
4309 */
4027
4310
4028function planetImages ()
4311var Offline = (function ()
4029{
4312{
4030 var list = [
4313
4031 { name: 'gray', url: 'images/block-gray.png' },
4314var BOT_INTERVAL = 0.5;
4032 { name: 'locked', url: 'images/block-locked.png' },
4315var SKILL_START = 0.05;
4033 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
4316var SKILL_STEP = 0.01;
4034 { name: 'cell', url: 'images/cell.png' },
4317var SKILL_CAP = 1;
4035 { name: 'pixel', url: 'images/pixel.png' },
4318var FLIGHT_DURATION = 1.2;
4036 // Keep the original Terra placeholders as aliases (Tim may still have them).
4319var ROUND_WON_DELAY = 1.5;
4037 { name: 'ember', url: 'images/block-ember.png' },
4320
4038 { name: 'aqua', url: 'images/block-aqua.png' },
4321/**
4039 { name: 'leaf', url: 'images/block-leaf.png' },
4322 * N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.
4040 { name: 'sun', url: 'images/block-sun.png' },
4323 * Documented in docs/ASSUMPTIONS.md (t1119).
4041 { name: 'orchid', url: 'images/block-orchid.png' }
4324 */
4042 ];
4325function roundsAtOpponentCount (n)
4043 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
4326{
4044 for (var i = 0; i < planets.length; i++)
4327 if (n <= 1)
4328 { return 1; }
4329 return n - 1;
4330}
4331
4332function skillForRound (round)
4333{
4334 var r = Math.max(1, Math.floor(Number(round) || 1));
4335 var pct = 5 + (r - 1);
4336 if (pct > 100)
4337 { pct = 100; }
4338 return pct / 100;
4339}
4340
4341function scheduleForRound (round)
4342{
4343 var r = Math.max(1, Math.floor(Number(round) || 1));
4344 var cursor = 1;
4345 var n = 1;
4346 for (;;)
4045 {
4347 {
4046 var pl = planets[i];
4348 var count = roundsAtOpponentCount(n);
4047 for (var c = 0; c < pl.colors.length; c++)
4349 if (r < cursor + count)
4048 {
4350 {
4049 list.push({
4351 return {
4050 name: Planet.spriteKey(pl, c),
4352 round: r,
4051 url: pl.colors[c].image
4353 opponents: n,
4052 });
4354 skill: skillForRound(r),
4355 roundsAtLevel: count,
4356 indexInLevel: r - cursor + 1
4357 };
4358 }
4359 cursor += count;
4360 n++;
4361 if (n > 10000)
4362 {
4363 return {
4364 round: r,
4365 opponents: n,
4366 skill: SKILL_CAP,
4367 roundsAtLevel: roundsAtOpponentCount(n),
4368 indexInLevel: 1
4369 };
4053 }
4370 }
4054 }
4371 }
4055 return list;
4056}
4372}
4057
4373
4058var IMAGES = planetImages();
4374function GameCoreCtor ()
4059var GAME_OVER_DELAY = 2;
4375{
4376 if (typeof GameCore !== 'undefined')
4377 { return GameCore; }
4378 if (typeof module !== 'undefined')
4379 { return require('./gameCore.js').GameCore; }
4380 return null;
4381}
4060
4382
4061var game = new Game();
4383function PlanetMod ()
4062var app = {
4384{
4063 mode: 'menu',
4385 if (typeof Planet !== 'undefined')
4064 core: null,
4386 { return Planet; }
4065 scene: null,
4387 if (typeof module !== 'undefined')
4066 manager: null,
4388 { return require('./planet.js'); }
4067 planet: null,
4389 return null;
4068 lastScore: 0,
4390}
4069 tile: 48,
4070 fieldX: 0,
4071 fieldY: 0,
4072 fieldW: 0,
4073 fieldH: 0,
4074 hudH: 56,
4075 sprites: Object.create(null),
4076 flames: Object.create(null),
4077 cells: [],
4078 pointerId: null,
4079 pointerType: null,
4080 activeTouchId: null,
4081 debugDrag: false,
4082 debugPhysics: false,
4083 gameOverShown: false,
4084 selectTween: null,
4085 online: false,
4086 eliminatedReported: false,
4087 spectating: false,
4088 miniH: 0,
4089 selectedPlanetId: 'terra',
4090 planetSelectContext: 'solo'
4091};
4092
4391
4093window.onload = function ()
4392/**
4393 * Integer-row colour grid of grounded (still / settling / locked)
4394 * blocks, including greys (color < 0) so a swap can shift them.
4395 */
4396function snapshotGrid (core)
4094{
4397{
4095 app.debugDrag = isDragDebugEnabled();
4398 var width = core.width;
4096 app.debugPhysics = isPhysicsDebugEnabled();
4399 var height = core.height;
4097 var play = document.getElementById('btn-play');
4400 var grid = [];
4098 play.addEventListener('click', onPlay);
4401 for (var c = 0; c < width; c++)
4099 play.addEventListener('pointerup', function (e)
4100 {
4402 {
4101 // A touch-friendly path: some mobile browsers swallow the click
4403 grid[c] = [];
4102 // after a slightly sloppy tap. Ignore the following click.
4404 for (var r = 0; r < height; r++)
4103 if (e.pointerType === 'touch' || e.pointerType === 'pen')
4405 { grid[c][r] = null; }
4104 {
4406 }
4105 e.preventDefault();
4407 for (var i = 0; i < core.blocks.length; i++)
4106 onPlay();
4107 }
4108 });
4109
4110 game.preloadImagesThenStart(IMAGES, function ()
4111 {
4408 {
4112 if (game.images.flame && game.images.flame.addAnimationCycle)
4409 var b = core.blocks[i];
4113 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
4410 if (!core.isGrounded(b))
4114 });
4411 { continue; }
4412 var row = Math.round(b.y);
4413 if (row < 0 || row >= height || b.col < 0 || b.col >= width)
4414 { continue; }
4415 if (Math.abs(b.y - row) > 0.2)
4416 { continue; }
4417 grid[b.col][row] = b.color;
4418 }
4419 return grid;
4420}
4115
4421
4116 bindOnlineUi();
4422function cloneGrid (grid)
4117 bindPlanetSelect();
4423{
4118 restoreSelectedPlanet();
4424 var out = [];
4119};
4425 for (var c = 0; c < grid.length; c++)
4426 { out[c] = grid[c].slice(); }
4427 return out;
4428}
4120
4429
4121function onPlay ()
4430/**
4431 * Apply swapToward's net result: the block at fromRow moves to toRow,
4432 * and the blocks it passed through each shift one cell toward fromRow.
4433 */
4434function applyColumnMove (grid, col, fromRow, toRow)
4122{
4435{
4123 if (app.mode === 'playing')
4436 if (fromRow === toRow)
4124 { return; }
4437 { return; }
4125 openPlanetSelect('solo');
4438 var moving = grid[col][fromRow];
4439 if (toRow > fromRow)
4440 {
4441 for (var y = fromRow; y < toRow; y++)
4442 { grid[col][y] = grid[col][y + 1]; }
4443 grid[col][toRow] = moving;
4444 }
4445 else
4446 {
4447 for (var y = fromRow; y > toRow; y--)
4448 { grid[col][y] = grid[col][y - 1]; }
4449 grid[col][toRow] = moving;
4450 }
4126}
4451}
4127
4452
4128function startPlay (opts)
4453function hasMatch (grid, width, height)
4129{
4454{
4130 opts = opts || {};
4455 var c, r, run, prev;
4131 hideEl('menu');
4456 for (r = 0; r < height; r++)
4132 hideEl('game-over');
4457 {
4133 hideEl('online-panel');
4458 run = 0;
4134 hideEl('spectator');
4459 prev = null;
4135 hideEl('podium');
4460 for (c = 0; c < width; c++)
4136 hideEl('planet-select');
4461 {
4137 showEl('hud');
4462 var color = grid[c][r];
4138
4463 if (color != null && color >= 0 && color === prev)
4139 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
4464 {
4140 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
4465 run++;
4141 var miss = opts.missChance;
4466 if (run >= 3)
4142 if (typeof miss !== 'number' || !isFinite(miss))
4467 { return true; }
4143 { miss = planetMod.missChance(app.planet); }
4468 }
4144 app.core = new GameCore(app.planet, Math.random, miss);
4469 else
4145 if (app.debugPhysics)
4470 {
4146 { app.core.debugInvariants = true; }
4471 run = (color != null && color >= 0) ? 1 : 0;
4147 app.mode = 'playing';
4472 prev = (color != null && color >= 0) ? color : null;
4148 app.online = !!opts.online;
4473 }
4149 app.gameOverShown = false;
4474 }
4150 app.eliminatedReported = false;
4475 }
4151 app.spectating = false;
4476 for (c = 0; c < width; c++)
4152 app.sprites = Object.create(null);
4477 {
4153 app.flames = Object.create(null);
4478 run = 0;
4154 app.cells = [];
4479 prev = null;
4155 app.pointerId = null;
4480 for (r = 0; r < height; r++)
4481 {
4482 var color = grid[c][r];
4483 if (color != null && color >= 0 && color === prev)
4484 {
4485 run++;
4486 if (run >= 3)
4487 { return true; }
4488 }
4489 else
4490 {
4491 run = (color != null && color >= 0) ? 1 : 0;
4492 prev = (color != null && color >= 0) ? color : null;
4493 }
4494 }
4495 }
4496 return false;
4497}
4498
4499/**
4500 * Contiguous segments of draggable, nearly-integer-y blocks in a
4501 * column. Gaps break a segment the same way swapToward stops at gaps.
4502 */
4503function contiguousSegments (core, col)
4504{
4505 if (!core.columnAllowsDrag(col))
4506 { return []; }
4507 var list = core.blocksInColumn(col).filter(function (b)
4508 {
4509 return core.isDraggableBlock(b);
4510 });
4511 list.sort(function (a, b) { return a.y - b.y; });
4512 var segs = [];
4513 var cur = [];
4514 for (var i = 0; i < list.length; i++)
4515 {
4516 var y = list[i].y;
4517 if (Math.abs(y - Math.round(y)) > 0.15)
4518 {
4519 if (cur.length)
4520 {
4521 segs.push(cur);
4522 cur = [];
4523 }
4524 continue;
4525 }
4526 if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)
4527 {
4528 segs.push(cur);
4529 cur = [list[i]];
4530 }
4531 else
4532 { cur.push(list[i]); }
4533 }
4534 if (cur.length)
4535 { segs.push(cur); }
4536 return segs;
4537}
4538
4539/**
4540 * The shortest vertical move that would create a 3+ match, or null.
4541 * Ties break on lowest column, then lowest fromY, then lowest toY.
4542 */
4543function findBotMove (core)
4544{
4545 var grid = snapshotGrid(core);
4546 if (hasMatch(grid, core.width, core.height))
4547 { return null; }
4548 var best = null;
4549 for (var col = 0; col < core.width; col++)
4550 {
4551 var segs = contiguousSegments(core, col);
4552 for (var s = 0; s < segs.length; s++)
4553 {
4554 var seg = segs[s];
4555 if (seg.length < 2)
4556 { continue; }
4557 for (var i = 0; i < seg.length; i++)
4558 {
4559 var fromY = Math.round(seg[i].y);
4560 for (var j = 0; j < seg.length; j++)
4561 {
4562 if (i === j)
4563 { continue; }
4564 var toY = Math.round(seg[j].y);
4565 var dist = Math.abs(toY - fromY);
4566 if (best && dist > best.dist)
4567 { continue; }
4568 var trial = cloneGrid(grid);
4569 applyColumnMove(trial, col, fromY, toY);
4570 if (!hasMatch(trial, core.width, core.height))
4571 { continue; }
4572 var cand = {
4573 col: col,
4574 fromY: fromY,
4575 toY: toY,
4576 dist: dist,
4577 blockId: seg[i].id
4578 };
4579 if (!best || dist < best.dist
4580 || (dist === best.dist && col < best.col)
4581 || (dist === best.dist && col === best.col && fromY < best.fromY)
4582 || (dist === best.dist && col === best.col && fromY === best.fromY
4583 && toY < best.toY))
4584 { best = cand; }
4585 }
4586 }
4587 }
4588 }
4589 return best;
4590}
4591
4592function executeBotMove (core, move)
4593{
4594 if (!core || !move)
4595 { return false; }
4596 var list = core.blocksInColumn(move.col);
4597 var block = null;
4598 for (var i = 0; i < list.length; i++)
4599 {
4600 if (move.blockId != null && list[i].id === move.blockId)
4601 {
4602 block = list[i];
4603 break;
4604 }
4605 if (Math.abs(list[i].y - move.fromY) < 0.2)
4606 { block = list[i]; }
4607 }
4608 if (!block || !core.isDraggableBlock(block))
4609 { return false; }
4610 core.swapToward(block, move.toY);
4611 return true;
4612}
4613
4614/**
4615 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
4616 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
4617 */
4618function tryBotRoll (core, skill, rng)
4619{
4620 rng = rng || Math.random;
4621 var roll = rng();
4622 if (!(roll < skill))
4623 {
4624 return { rolled: true, success: false, moved: false, roll: roll, move: null };
4625 }
4626 var move = findBotMove(core);
4627 if (!move)
4628 {
4629 return { rolled: true, success: true, moved: false, roll: roll, move: null };
4630 }
4631 var ok = executeBotMove(core, move);
4632 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
4633}
4634
4635function pickPlanet (rng, P)
4636{
4637 var all = P.allPlanets();
4638 if (!all.length)
4639 { return P.defaultPlanet(); }
4640 var i = Math.floor(rng() * all.length) % all.length;
4641 return all[i];
4642}
4643
4644function OfflineBattle (opts)
4645{
4646 opts = opts || {};
4647 var P = PlanetMod();
4648 this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());
4649 this.rng = opts.rng || Math.random;
4650 this.round = opts.round || 1;
4651 this.schedule = scheduleForRound(this.round);
4652 this.clock = 0;
4653 this.state = 'playing';
4654 this.pending = [];
4655 this.flightResults = [];
4656 this.shotLocals = [];
4657 this.bots = [];
4658 this.playerId = 'player';
4659 this._initBots();
4660}
4661
4662OfflineBattle.prototype._initBots = function ()
4663{
4664 var P = PlanetMod();
4665 var Ctor = GameCoreCtor();
4666 var n = this.schedule.opponents;
4667 this.bots = [];
4668 for (var i = 0; i < n; i++)
4669 {
4670 var planet = pickPlanet(this.rng, P);
4671 var miss = P.missChance(planet);
4672 var core = new Ctor(planet, this.rng, miss);
4673 this.bots.push({
4674 id: 'bot-' + (i + 1),
4675 name: 'Bot ' + (i + 1),
4676 planet: planet,
4677 core: core,
4678 eliminated: false,
4679 score: 0,
4680 aiAcc: 0
4681 });
4682 }
4683};
4684
4685OfflineBattle.prototype.aliveBots = function ()
4686{
4687 var out = [];
4688 for (var i = 0; i < this.bots.length; i++)
4689 {
4690 if (!this.bots[i].eliminated && this.bots[i].core
4691 && this.bots[i].core.state !== 'gameover')
4692 { out.push(this.bots[i]); }
4693 }
4694 return out;
4695};
4696
4697OfflineBattle.prototype.coreFor = function (id, playerCore)
4698{
4699 if (id === this.playerId)
4700 { return playerCore; }
4701 for (var i = 0; i < this.bots.length; i++)
4702 {
4703 if (this.bots[i].id === id)
4704 { return this.bots[i].core; }
4705 }
4706 return null;
4707};
4708
4709OfflineBattle.prototype._targetsFor = function (fromId, playerCore)
4710{
4711 var targets = [];
4712 if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')
4713 { targets.push({ id: this.playerId, core: playerCore }); }
4714 for (var i = 0; i < this.bots.length; i++)
4715 {
4716 var bot = this.bots[i];
4717 if (bot.id === fromId || bot.eliminated)
4718 { continue; }
4719 if (bot.core && bot.core.state === 'playing')
4720 { targets.push({ id: bot.id, core: bot.core }); }
4721 }
4722 return targets;
4723};
4724
4725OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)
4726{
4727 if (!core || !core.consumeOutgoingShots)
4728 { return; }
4729 var shots = core.consumeOutgoingShots();
4730 if (!shots.length)
4731 { return; }
4732 var P = PlanetMod();
4733 var missChance = (P && planet) ? P.missChance(planet) : 0.30;
4734 var targets = this._targetsFor(fromId, playerCore);
4735 for (var i = 0; i < shots.length; i++)
4736 {
4737 var shot = shots[i];
4738 var miss = targets.length === 0 || this.rng() < missChance;
4739 var target = null;
4740 if (!miss)
4741 {
4742 var idx = Math.floor(this.rng() * targets.length) % targets.length;
4743 target = targets[idx];
4744 }
4745 var clientId = fromId + '-' + shot.id + '-' + this.clock;
4746 var result = {
4747 client_id: clientId,
4748 miss: miss,
4749 target_id: target ? target.id : null,
4750 color: shot.color,
4751 flight_duration: FLIGHT_DURATION,
4752 from_id: fromId,
4753 col: shot.col,
4754 y: shot.y
4755 };
4756 this.flightResults.push(result);
4757 this.shotLocals.push({
4758 client_id: clientId,
4759 col: shot.col,
4760 y: shot.y,
4761 color: shot.color,
4762 from_id: fromId
4763 });
4764 if (!miss && target)
4765 {
4766 this.pending.push({
4767 at: this.clock + FLIGHT_DURATION,
4768 targetId: target.id,
4769 color: shot.color,
4770 fromId: fromId
4771 });
4772 }
4773 }
4774};
4775
4776OfflineBattle.prototype._deliver = function (playerCore)
4777{
4778 var keep = [];
4779 for (var i = 0; i < this.pending.length; i++)
4780 {
4781 var ev = this.pending[i];
4782 if (this.clock + 1e-9 < ev.at)
4783 {
4784 keep.push(ev);
4785 continue;
4786 }
4787 var core = this.coreFor(ev.targetId, playerCore);
4788 if (core && core.state === 'playing' && core.ingestGarbage)
4789 { core.ingestGarbage(); }
4790 }
4791 this.pending = keep;
4792};
4793
4794OfflineBattle.prototype.tick = function (dt, playerCore)
4795{
4796 this.flightResults = [];
4797 this.shotLocals = [];
4798 if (this.state !== 'playing')
4799 { return { flights: [], locals: [] }; }
4800 if (dt < 0)
4801 { dt = 0; }
4802 this.clock += dt;
4803
4804 var skill = this.schedule.skill;
4805 for (var i = 0; i < this.bots.length; i++)
4806 {
4807 var bot = this.bots[i];
4808 if (bot.eliminated)
4809 { continue; }
4810 if (bot.core.state === 'gameover')
4811 {
4812 bot.eliminated = true;
4813 bot.score = bot.core.score;
4814 continue;
4815 }
4816 bot.core.tick(dt);
4817 bot.score = bot.core.score;
4818 bot.aiAcc += dt;
4819 while (bot.aiAcc >= BOT_INTERVAL)
4820 {
4821 bot.aiAcc -= BOT_INTERVAL;
4822 if (bot.core.state === 'playing' && !bot.core.drag)
4823 { tryBotRoll(bot.core, skill, this.rng); }
4824 }
4825 }
4826
4827 this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);
4828 for (var i = 0; i < this.bots.length; i++)
4829 {
4830 var bot = this.bots[i];
4831 if (bot.eliminated)
4832 { continue; }
4833 this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);
4834 }
4835 this._deliver(playerCore);
4836
4837 for (var i = 0; i < this.bots.length; i++)
4838 {
4839 if (this.bots[i].core && this.bots[i].core.state === 'gameover')
4840 {
4841 this.bots[i].eliminated = true;
4842 this.bots[i].score = this.bots[i].core.score;
4843 }
4844 }
4845
4846 if (playerCore && playerCore.state === 'gameover')
4847 { this.state = 'lost'; }
4848 else if (this.aliveBots().length === 0 && this.bots.length > 0)
4849 { this.state = 'round_won'; }
4850
4851 return { flights: this.flightResults, locals: this.shotLocals };
4852};
4853
4854/**
4855 * Start the next round (fresh bots, new skill and opponent count).
4856 * The caller must also give the player a fresh GameCore.
4857 */
4858OfflineBattle.prototype.advanceRound = function ()
4859{
4860 this.round += 1;
4861 this.schedule = scheduleForRound(this.round);
4862 this.state = 'playing';
4863 this.pending = [];
4864 this.flightResults = [];
4865 this.shotLocals = [];
4866 this.clock = 0;
4867 this._initBots();
4868 return this.schedule;
4869};
4870
4871function createBattle (opts)
4872{
4873 return new OfflineBattle(opts);
4874}
4875
4876var api = {
4877 BOT_INTERVAL: BOT_INTERVAL,
4878 SKILL_START: SKILL_START,
4879 SKILL_STEP: SKILL_STEP,
4880 SKILL_CAP: SKILL_CAP,
4881 FLIGHT_DURATION: FLIGHT_DURATION,
4882 ROUND_WON_DELAY: ROUND_WON_DELAY,
4883 roundsAtOpponentCount: roundsAtOpponentCount,
4884 skillForRound: skillForRound,
4885 scheduleForRound: scheduleForRound,
4886 findBotMove: findBotMove,
4887 tryBotRoll: tryBotRoll,
4888 executeBotMove: executeBotMove,
4889 snapshotGrid: snapshotGrid,
4890 applyColumnMove: applyColumnMove,
4891 hasMatch: hasMatch,
4892 createBattle: createBattle,
4893 OfflineBattle: OfflineBattle
4894};
4895
4896if (typeof module !== 'undefined' && module.exports)
4897{ module.exports = api; }
4898else if (typeof globalThis !== 'undefined')
4899{ globalThis.Offline = api; }
4900
4901return api;
4902
4903})();
4904
4905if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')
4906{ module.exports = Offline; }
4907
4908/*
4909 * End File:
4910 * /workspace/meteors/src/offline.js
4911 */
4912
4913/*
4914 * Start File:
4915 * /workspace/meteors/src/main.js
4916 */
4917'use strict';
4918
4919/**
4920 * View and input for Meteors. The simulation lives in GameCore; this file
4921 * only draws it, scales it to the viewport, and translates pointer events
4922 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
4923 * through Online (src/online.js) and the same GameCore. Offline Strijd
4924 * (t1119) uses Offline (src/offline.js) against local bots.
4925 */
4926
4927function planetImages ()
4928{
4929 var list = [
4930 { name: 'gray', url: 'images/block-gray.png' },
4931 { name: 'locked', url: 'images/block-locked.png' },
4932 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
4933 { name: 'cell', url: 'images/cell.png' },
4934 { name: 'pixel', url: 'images/pixel.png' },
4935 { name: 'columnWarn', url: 'images/column-warn.png' },
4936 // Keep the original Terra placeholders as aliases (Tim may still have them).
4937 { name: 'ember', url: 'images/block-ember.png' },
4938 { name: 'aqua', url: 'images/block-aqua.png' },
4939 { name: 'leaf', url: 'images/block-leaf.png' },
4940 { name: 'sun', url: 'images/block-sun.png' },
4941 { name: 'orchid', url: 'images/block-orchid.png' }
4942 ];
4943 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
4944 for (var i = 0; i < planets.length; i++)
4945 {
4946 var pl = planets[i];
4947 for (var c = 0; c < pl.colors.length; c++)
4948 {
4949 list.push({
4950 name: Planet.spriteKey(pl, c),
4951 url: pl.colors[c].image
4952 });
4953 }
4954 }
4955 return list;
4956}
4957
4958var IMAGES = planetImages();
4959var GAME_OVER_DELAY = 2;
4960
4961var game = new Game();
4962var app = {
4963 mode: 'menu',
4964 core: null,
4965 scene: null,
4966 manager: null,
4967 planet: null,
4968 lastScore: 0,
4969 tile: 48,
4970 fieldX: 0,
4971 fieldY: 0,
4972 fieldW: 0,
4973 fieldH: 0,
4974 hudH: 56,
4975 sprites: Object.create(null),
4976 flames: Object.create(null),
4977 cells: [],
4978 pointerId: null,
4979 pointerType: null,
4980 activeTouchId: null,
4981 debugDrag: false,
4982 debugPhysics: false,
4983 gameOverShown: false,
4984 selectTween: null,
4985 online: false,
4986 eliminatedReported: false,
4987 spectating: false,
4988 miniH: 0,
4989 selectedPlanetId: 'terra',
4990 planetSelectContext: 'solo',
4991 offline: false,
4992 battle: null,
4993 swapTweens: null,
4994 columnWarn: null,
4995 warnClock: 0,
4996 miniAcc: 0,
4997 offlineResultShown: false,
4998 roundWonDelay: 0,
4999 roundWonHandled: false
5000};
5001
5002window.onload = function ()
5003{
5004 app.debugDrag = isDragDebugEnabled();
5005 app.debugPhysics = isPhysicsDebugEnabled();
5006 var play = document.getElementById('btn-play');
5007 play.addEventListener('click', onPlay);
5008 play.addEventListener('pointerup', function (e)
5009 {
5010 // A touch-friendly path: some mobile browsers swallow the click
5011 // after a slightly sloppy tap. Ignore the following click.
5012 if (e.pointerType === 'touch' || e.pointerType === 'pen')
5013 {
5014 e.preventDefault();
5015 onPlay();
5016 }
5017 });
5018
5019 game.preloadImagesThenStart(IMAGES, function ()
5020 {
5021 if (game.images.flame && game.images.flame.addAnimationCycle)
5022 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
5023 });
5024
5025 bindOnlineUi();
5026 bindOfflineUi();
5027 bindPlanetSelect();
5028 restoreSelectedPlanet();
5029};
5030
5031function onPlay ()
5032{
5033 if (app.mode === 'playing')
5034 { return; }
5035 openPlanetSelect('solo');
5036}
5037
5038function startPlay (opts)
5039{
5040 opts = opts || {};
5041 hideEl('menu');
5042 hideEl('game-over');
5043 hideEl('online-panel');
5044 hideEl('spectator');
5045 hideEl('podium');
5046 hideEl('planet-select');
5047 hideEl('offline-result');
5048 showEl('hud');
5049
5050 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
5051 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
5052 var miss = opts.missChance;
5053 if (typeof miss !== 'number' || !isFinite(miss))
5054 { miss = planetMod.missChance(app.planet); }
5055 app.core = new GameCore(app.planet, Math.random, miss);
5056 if (app.debugPhysics)
5057 { app.core.debugInvariants = true; }
5058 app.mode = 'playing';
5059 app.online = !!opts.online;
5060 app.offline = !!opts.offline;
5061 app.gameOverShown = false;
5062 app.eliminatedReported = false;
5063 app.spectating = false;
5064 app.sprites = Object.create(null);
5065 app.flames = Object.create(null);
5066 app.cells = [];
5067 app.pointerId = null;
4156 app.selectTween = null;
5068 app.selectTween = null;
5069 app.swapTweens = Object.create(null);
5070 app.columnWarn = [];
5071 app.warnClock = 0;
5072 app.miniAcc = 1; // draw minis on the first frame
5073 app.offlineResultShown = false;
5074 if (!opts.keepBattle)
5075 {
5076 app.roundWonDelay = 0;
5077 app.roundWonHandled = false;
5078 }
5079 if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
5080 {
5081 app.battle = Offline.createBattle({
5082 playerPlanet: app.planet,
5083 rng: Math.random,
5084 round: opts.round || 1
5085 });
5086 }
4157
5087
4158 layout();
5088 layout();
4159 if (app.scene)
5089 if (app.scene)
@@ -4171,10 +5101,13 @@ function startPlay (opts)
4171 if (!app.spectating)
5101 if (!app.spectating)
4172 { bindPointer(app.scene.canvas); }
5102 { bindPointer(app.scene.canvas); }
4173 refreshHud();
5103 refreshHud();
4174 if (app.online)
5104 if (app.online || app.offline)
4175 { showEl('minis'); }
5105 { showEl('minis'); }
4176 else
5106 else
4177 { hideEl('minis'); }
5107 { hideEl('minis'); }
5108 buildColumnWarn();
5109 refreshOfflineHud();
5110 refreshChainIndicator();
4178}
5111}
4179
5112
4180function teardownPlay ()
5113function teardownPlay ()
@@ -4191,14 +5124,25 @@ function teardownPlay ()
4191 app.flames = Object.create(null);
5124 app.flames = Object.create(null);
4192 app.cells = [];
5125 app.cells = [];
4193 app.selectTween = null;
5126 app.selectTween = null;
5127 app.swapTweens = Object.create(null);
5128 app.columnWarn = [];
4194 app.pointerId = null;
5129 app.pointerId = null;
4195 app.gameOverShown = false;
5130 app.gameOverShown = false;
4196 hideEl('hud');
5131 hideEl('hud');
4197 hideEl('game-over');
5132 hideEl('game-over');
4198 hideEl('spectator');
5133 hideEl('spectator');
4199 hideEl('minis');
5134 hideEl('minis');
5135 hideEl('offline-result');
5136 hideOfflineHud();
5137 hideChainIndicator();
4200 if (typeof Online !== 'undefined')
5138 if (typeof Online !== 'undefined')
4201 { Online.clearFlights(); }
5139 { Online.clearFlights(); }
5140 if (!app._keepBattleOnTeardown)
5141 {
5142 app.battle = null;
5143 app.offline = false;
5144 }
5145 app._keepBattleOnTeardown = false;
4202}
5146}
4203
5147
4204function returnToMenu ()
5148function returnToMenu ()
@@ -4212,6 +5156,8 @@ function returnToMenu ()
4212 teardownPlay();
5156 teardownPlay();
4213 app.mode = 'menu';
5157 app.mode = 'menu';
4214 app.online = false;
5158 app.online = false;
5159 app.offline = false;
5160 app.battle = null;
4215 hideEl('planet-select');
5161 hideEl('planet-select');
4216 showEl('menu');
5162 showEl('menu');
4217 var last = document.getElementById('last-score');
5163 var last = document.getElementById('last-score');
@@ -4276,8 +5222,12 @@ function layout ()
4276 catch (e) { /* ignore */ }
5222 catch (e) { /* ignore */ }
4277 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
5223 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
4278 app.miniH = 0;
5224 app.miniH = 0;
4279 if (app.online)
5225 if (app.online || app.offline)
4280 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
5226 {
5227 var nBots = (app.battle && app.battle.bots) ? app.battle.bots.length : 2;
5228 var share = nBots > 6 ? 0.26 : 0.20;
5229 app.miniH = Math.min(nBots > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));
5230 }
4281 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
5231 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
4282 var availW = Math.max(80, vw - margin * 2);
5232 var availW = Math.max(80, vw - margin * 2);
4283 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
5233 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
@@ -4315,10 +5265,13 @@ function spriteFor (block)
4315 return game.images[key] || game.images.gray;
5265 return game.images[key] || game.images.gray;
4316}
5266}
4317
5267
4318function syncSprites ()
5268function syncSprites (dt)
4319{
5269{
4320 if (!app.core || !app.scene)
5270 if (!app.core || !app.scene)
4321 { return; }
5271 { return; }
5272 dt = dt || 0;
5273 consumeAndStartSwapTweens();
5274 advanceSwapTweens(dt);
4322 var seen = Object.create(null);
5275 var seen = Object.create(null);
4323 var blocks = app.core.blocks;
5276 var blocks = app.core.blocks;
4324 for (var i = 0; i < blocks.length; i++)
5277 for (var i = 0; i < blocks.length; i++)
@@ -4333,7 +5286,7 @@ function syncSprites ()
4333 app.sprites[block.id] = obj;
5286 app.sprites[block.id] = obj;
4334 }
5287 }
4335 obj.renderer.sprite = spriteFor(block);
5288 obj.renderer.sprite = spriteFor(block);
4336 placeTile(obj, block.col, block.y);
5289 placeTile(obj, block.col, blockVisualY(block));
4337 applyBlockVisual(obj, block);
5290 applyBlockVisual(obj, block);
4338 obj.renderer.visible = true;
5291 obj.renderer.visible = true;
4339 obj.renderer.alpha = 1;
5292 obj.renderer.alpha = 1;
@@ -4471,6 +5424,95 @@ function updateSelectTween (dt)
4471 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
5424 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
4472}
5425}
4473
5426
5427
5428/* ---------- visual-only swap tween (t1121) -------------------------- */
5429
5430function swapTweenSpec ()
5431{
5432 if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
5433 { return Easing.SWAP_TWEEN; }
5434 return { duration: 0.100, ease: null };
5435}
5436
5437function swapEase (u)
5438{
5439 if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
5440 { return Easing.easeOutCubic(u); }
5441 var v = 1 - Math.max(0, Math.min(1, u));
5442 return 1 - v * v * v;
5443}
5444
5445function tweenVisualY (tw)
5446{
5447 var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
5448 return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
5449}
5450
5451/**
5452 * Consume GameCore swap events. The currently dragged block is skipped
5453 * (it follows the pointer). A block that is mid-tween and is swapped
5454 * again restarts from its current visual y, so rapid swaps chain
5455 * smoothly without snapping.
5456 */
5457function consumeAndStartSwapTweens ()
5458{
5459 if (!app.core || !app.core.consumeSwapEvents)
5460 { return; }
5461 if (!app.swapTweens)
5462 { app.swapTweens = Object.create(null); }
5463 var ev = app.core.consumeSwapEvents();
5464 if (!ev.length)
5465 { return; }
5466 var dragId = app.core.drag && app.core.drag.blockId;
5467 var duration = swapTweenSpec().duration;
5468 for (var i = 0; i < ev.length; i++)
5469 {
5470 var e = ev[i];
5471 if (e.id === dragId)
5472 {
5473 delete app.swapTweens[e.id];
5474 continue;
5475 }
5476 var fromY = e.fromY;
5477 var existing = app.swapTweens[e.id];
5478 if (existing)
5479 { fromY = tweenVisualY(existing); }
5480 app.swapTweens[e.id] = {
5481 fromY: fromY,
5482 toY: e.toY,
5483 age: 0,
5484 duration: duration
5485 };
5486 }
5487}
5488
5489function advanceSwapTweens (dt)
5490{
5491 if (!app.swapTweens)
5492 { return; }
5493 var ids = Object.keys(app.swapTweens);
5494 for (var i = 0; i < ids.length; i++)
5495 {
5496 var tw = app.swapTweens[ids[i]];
5497 tw.age += dt;
5498 if (tw.age >= tw.duration)
5499 { delete app.swapTweens[ids[i]]; }
5500 }
5501}
5502
5503function blockVisualY (block)
5504{
5505 if (!app.swapTweens)
5506 { return block.y; }
5507 var dragId = app.core && app.core.drag && app.core.drag.blockId;
5508 if (block.id === dragId)
5509 { return block.y; }
5510 var tw = app.swapTweens[block.id];
5511 if (!tw)
5512 { return block.y; }
5513 return tweenVisualY(tw);
5514}
5515
4474function refreshHud ()
5516function refreshHud ()
4475{
5517{
4476 if (!app.core)
5518 if (!app.core)
@@ -4512,9 +5554,14 @@ function tickView (dt)
4512 }
5554 }
4513
5555
4514 app.core.tick(dt);
5556 app.core.tick(dt);
5557 if (app.offline && app.battle)
5558 { tickOffline(dt); }
4515 updateSelectTween(dt);
5559 updateSelectTween(dt);
4516 syncSprites();
5560 syncSprites(dt);
5561 updateColumnWarn(dt);
4517 refreshHud();
5562 refreshHud();
5563 refreshOfflineHud();
5564 refreshChainIndicator();
4518 tickOnline(dt);
5565 tickOnline(dt);
4519 if (app.debugPhysics)
5566 if (app.debugPhysics)
4520 { logPhysicsDebug(); }
5567 { logPhysicsDebug(); }
@@ -4526,10 +5573,13 @@ function tickView (dt)
4526 document.getElementById('go-score').textContent = String(app.lastScore);
5573 document.getElementById('go-score').textContent = String(app.lastScore);
4527 if (app.online)
5574 if (app.online)
4528 { onOnlineEliminated(); }
5575 { onOnlineEliminated(); }
5576 else if (app.offline)
5577 { /* Offline result is shown from tickOffline. */ }
4529 else
5578 else
4530 { showEl('game-over'); }
5579 { showEl('game-over'); }
4531 }
5580 }
4532 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
5581 if (!app.online && !app.offline && app.core.state === 'gameover'
5582 && app.core.gameOverTime >= GAME_OVER_DELAY)
4533 { returnToMenu(); }
5583 { returnToMenu(); }
4534}
5584}
4535
5585
@@ -5032,6 +6082,313 @@ function tickOnline (dt)
5032 Online.renderMinis(document.getElementById('minis'));
6082 Online.renderMinis(document.getElementById('minis'));
5033}
6083}
5034
6084
6085
6086/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
6087
6088function bindOfflineUi ()
6089{
6090 var btn = document.getElementById('btn-offline');
6091 if (btn)
6092 {
6093 btn.addEventListener('click', onOffline);
6094 btn.addEventListener('pointerup', function (e)
6095 {
6096 if (e.pointerType === 'touch' || e.pointerType === 'pen')
6097 {
6098 e.preventDefault();
6099 onOffline();
6100 }
6101 });
6102 }
6103 var back = document.getElementById('btn-offline-menu');
6104 if (back)
6105 {
6106 back.addEventListener('click', function ()
6107 {
6108 teardownPlay();
6109 app.mode = 'menu';
6110 app.offline = false;
6111 app.battle = null;
6112 hideEl('offline-result');
6113 showEl('menu');
6114 });
6115 }
6116}
6117
6118function onOffline ()
6119{
6120 openPlanetSelect('offline');
6121}
6122
6123function tickOffline (dt)
6124{
6125 if (!app.battle || !app.core || typeof Offline === 'undefined')
6126 { return; }
6127
6128 if (app.battle.state === 'round_won')
6129 {
6130 if (!app.roundWonHandled)
6131 {
6132 app.roundWonHandled = true;
6133 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
6134 }
6135 app.roundWonDelay -= dt;
6136 if (app.roundWonDelay <= 0)
6137 { startNextOfflineRound(); }
6138 updateOfflineMinis(dt, true);
6139 return;
6140 }
6141
6142 var result = app.battle.tick(dt, app.core);
6143 if (result && result.flights && result.flights.length
6144 && typeof Online !== 'undefined' && Online.spawnFlights)
6145 {
6146 var locals = Object.create(null);
6147 var list = result.locals || [];
6148 for (var i = 0; i < list.length; i++)
6149 {
6150 var s = list[i];
6151 var start;
6152 if (s.from_id === 'player')
6153 { start = fieldToViewport(s.col, s.y + 1); }
6154 else
6155 { start = miniViewportCenter(s.from_id); }
6156 locals[s.client_id] = {
6157 col: s.col,
6158 y: s.y,
6159 color: s.color,
6160 startX: start.x,
6161 startY: start.y
6162 };
6163 }
6164 Online.spawnFlights(result.flights, locals);
6165 }
6166 if (typeof Online !== 'undefined' && Online.tickFlights)
6167 { Online.tickFlights(); }
6168 updateOfflineMinis(dt, false);
6169
6170 if (app.battle.state === 'lost' && !app.offlineResultShown)
6171 { showOfflineResult(); }
6172}
6173
6174function startNextOfflineRound ()
6175{
6176 if (!app.battle)
6177 { return; }
6178 app.battle.advanceRound();
6179 app.roundWonHandled = false;
6180 app.roundWonDelay = 0;
6181 app._keepBattleOnTeardown = true;
6182 // Tear down the current scene then start a fresh player field,
6183 // keeping the same battle (already advanced).
6184 var planet = app.battle.playerPlanet;
6185 app._keepBattleOnTeardown = true;
6186 teardownPlay();
6187 app.offline = true;
6188 app.battle = app.battle; // kept
6189 startPlay({ planet: planet, offline: true, keepBattle: true });
6190}
6191
6192function showOfflineResult ()
6193{
6194 app.offlineResultShown = true;
6195 var battle = app.battle;
6196 var reached = document.getElementById('offline-reached');
6197 if (reached)
6198 { reached.textContent = String(battle.round); }
6199 var detail = document.getElementById('offline-result-detail');
6200 if (detail)
6201 {
6202 var sch = battle.schedule;
6203 var n = sch.opponents;
6204 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
6205 detail.textContent = 'Je speelde tegen ' + n + ' ' + noun
6206 + ' met skill ' + Math.round(sch.skill * 100) + '%.';
6207 }
6208 hideEl('game-over');
6209 showEl('offline-result');
6210}
6211
6212function refreshOfflineHud ()
6213{
6214 var el = document.getElementById('offline-hud');
6215 if (!el)
6216 { return; }
6217 if (!(app.offline && app.battle && app.mode === 'playing'))
6218 {
6219 el.hidden = true;
6220 return;
6221 }
6222 el.hidden = false;
6223 var sch = app.battle.schedule;
6224 var n = sch.opponents;
6225 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
6226 var r = document.getElementById('offline-round');
6227 var o = document.getElementById('offline-opponents');
6228 var s = document.getElementById('offline-skill');
6229 if (r)
6230 { r.textContent = 'Ronde ' + sch.round; }
6231 if (o)
6232 { o.textContent = n + ' ' + noun; }
6233 if (s)
6234 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
6235}
6236
6237function hideOfflineHud ()
6238{
6239 var el = document.getElementById('offline-hud');
6240 if (el)
6241 { el.hidden = true; }
6242}
6243
6244function refreshChainIndicator ()
6245{
6246 var el = document.getElementById('chain-indicator');
6247 if (!el)
6248 { return; }
6249 var info = app.core && app.core.lastChainIndicator;
6250 var active = app.core && app.core.hasActiveLandingChain
6251 && app.core.hasActiveLandingChain();
6252 // Show only while a chained cluster is still in the air.
6253 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
6254 {
6255 el.hidden = true;
6256 return;
6257 }
6258 el.hidden = false;
6259 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
6260}
6261
6262function hideChainIndicator ()
6263{
6264 var el = document.getElementById('chain-indicator');
6265 if (el)
6266 { el.hidden = true; }
6267}
6268
6269function miniViewportCenter (botId)
6270{
6271 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
6272 if (!el)
6273 { return { x: window.innerWidth / 2, y: 40 }; }
6274 var rect = el.getBoundingClientRect();
6275 return { x: rect.left + rect.width / 2, y: rect.bottom };
6276}
6277
6278function offlineMiniSize (n)
6279{
6280 if (n >= 10)
6281 { return { w: 40, h: 52 }; }
6282 if (n >= 6)
6283 { return { w: 56, h: 73 }; }
6284 return { w: 80, h: 104 };
6285}
6286
6287function updateOfflineMinis (dt, force)
6288{
6289 app.miniAcc = (app.miniAcc || 0) + dt;
6290 if (!force && app.miniAcc < 0.1)
6291 { return; }
6292 app.miniAcc = 0;
6293 renderOfflineMinis();
6294}
6295
6296function renderOfflineMinis ()
6297{
6298 var container = document.getElementById('minis');
6299 if (!container || !app.battle)
6300 { return; }
6301 var bots = app.battle.bots;
6302 var size = offlineMiniSize(bots.length);
6303 container.classList.toggle('crowded', bots.length > 5);
6304 var existing = {};
6305 var kids = container.querySelectorAll('[data-player]');
6306 for (var i = 0; i < kids.length; i++)
6307 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
6308 var seen = Object.create(null);
6309 for (var i = 0; i < bots.length; i++)
6310 {
6311 var bot = bots[i];
6312 seen[bot.id] = true;
6313 var el = existing[bot.id];
6314 if (!el)
6315 {
6316 el = document.createElement('div');
6317 el.className = 'mini';
6318 el.setAttribute('data-player', bot.id);
6319 el.innerHTML = '<div class="mini-name"></div>'
6320 + '<canvas class="mini-canvas" width="' + size.w
6321 + '" height="' + size.h + '"></canvas>'
6322 + '<div class="mini-meta"></div>';
6323 container.appendChild(el);
6324 }
6325 var canvas = el.querySelector('canvas');
6326 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
6327 {
6328 canvas.width = size.w;
6329 canvas.height = size.h;
6330 }
6331 el.classList.toggle('eliminated', !!bot.eliminated);
6332 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
6333 el.querySelector('.mini-name').textContent = bot.name
6334 + (planetName ? ' · ' + planetName : '');
6335 el.querySelector('.mini-meta').textContent = bot.eliminated
6336 ? 'Uit'
6337 : ('Punten ' + (bot.score || 0));
6338 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
6339 if (typeof Online !== 'undefined' && Online._drawMini)
6340 { Online._drawMini(canvas, snap, bot.planet); }
6341 }
6342 for (var id in existing)
6343 {
6344 if (!seen[id])
6345 { existing[id].remove(); }
6346 }
6347}
6348
6349function buildColumnWarn ()
6350{
6351 app.columnWarn = [];
6352 if (!app.scene)
6353 { return; }
6354 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
6355 if (!img)
6356 { return; }
6357 for (var c = 0; c < 10; c++)
6358 {
6359 var obj = new GameObject(0, 0, img, 0);
6360 obj.renderer.alpha = 0;
6361 obj.renderer.visible = false;
6362 app.scene.addObject(obj);
6363 app.columnWarn.push(obj);
6364 }
6365 updateColumnWarn(0);
6366}
6367
6368function updateColumnWarn (dt)
6369{
6370 if (!app.columnWarn || !app.core)
6371 { return; }
6372 app.warnClock = (app.warnClock || 0) + (dt || 0);
6373 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
6374 ? GameCore.columnWarnPulse(app.warnClock)
6375 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
6376 var t = app.tile;
6377 for (var c = 0; c < app.columnWarn.length; c++)
6378 {
6379 var obj = app.columnWarn[c];
6380 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
6381 obj.renderer.visible = !!on;
6382 obj.renderer.alpha = on ? pulse : 0;
6383 if (t)
6384 {
6385 obj.transform.position.x = c * t + t / 2;
6386 obj.transform.position.y = app.fieldH / 2;
6387 obj.transform.size = { x: t, y: app.fieldH };
6388 }
6389 }
6390}
6391
5035function fieldToViewport (col, fieldY)
6392function fieldToViewport (col, fieldY)
5036{
6393{
5037 var canvas = app.scene && app.scene.canvas;
6394 var canvas = app.scene && app.scene.canvas;
@@ -5519,6 +6876,11 @@ function confirmPlanetSelect ()
5519 openOnlinePanel();
6876 openOnlinePanel();
5520 return;
6877 return;
5521 }
6878 }
6879 if (app.planetSelectContext === 'offline')
6880 {
6881 startPlay({ planet: planet, offline: true });
6882 return;
6883 }
5522 startPlay({ planet: planet });
6884 startPlay({ planet: planet });
5523}
6885}
5524
6886