BlueGit

projects-timfalken-com meteors

Merge branch 'feature/t1106-touch-drag'

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
1ede900852a313ace0fbf0c3a655fe2057be8abb
Pipeline
Passed
10 files changed +2523 −146
build/game.js +749 −72
@@ -668,8 +668,8 @@ var LAUNCH_PULL = 0.35;
668 668 // Minimal accumulated vertical pointer travel (tiles) to swap one step.
669 669 // No hold delay: the first swap fires as soon as this distance is reached.
670 670 var SWAP_DISTANCE = 0.25;
671 // Grab a still block if the pointer is at most this far (tiles) from it.
672 var SNAP_Y = 0.65;
671 // Fallback snap (tiles) when the press cell is empty: nearest block in the column.
672 var SNAP_Y = 0.5;
673 673 // Horizontal slop (tiles) for snapping to a neighbouring column on press.
674 674 var HORIZONTAL_SLOP = 0.35;
675 675
@@ -1073,12 +1073,29 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)
1073 1073 if (other.y + 1 > roof)
1074 1074 { roof = other.y + 1; }
1075 1075 }
1076 var oldN = this.clusterMembers(cluster.id).length;
1077 var fallingVy = block.vy;
1076 1078 block.y = roof;
1077 1079 block.state = STATE_FLYING;
1078 1080 block.clusterId = cluster.id;
1079 block.vy = cluster.vy;
1080 1081 block.flame = false;
1081 1082 block.settleTime = 0;
1083 // A cluster born from a thrown block averages in falling cargo
1084 // the same way two flying clusters merge (t1108). Other rockets
1085 // keep their velocity and just pick the cargo up.
1086 if (cluster.fromManual)
1087 {
1088 var newN = oldN + 1;
1089 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
1090 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
1091 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
1092 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
1093 var members = this.clusterMembers(cluster.id);
1094 for (var m = 0; m < members.length; m++)
1095 { members[m].vy = cluster.vy; }
1096 }
1097 else
1098 { block.vy = cluster.vy; }
1082 1099 return true;
1083 1100 };
1084 1101
@@ -1141,6 +1158,7 @@ GameCore.prototype.tick = function (dt)
1141 1158 this.integrateClusters(step);
1142 1159 this.mergeFlyingClusters();
1143 1160 this.integrateManual(step);
1161 this.mergeAnyManualFallingOverlaps();
1144 1162 this.cullOffTop();
1145 1163 left -= step;
1146 1164 }
@@ -1222,6 +1240,12 @@ GameCore.prototype.integrateFalling = function (dt)
1222 1240 { continue; }
1223 1241 this.accelerateFall(block, dt);
1224 1242 var nextY = block.y + block.vy * dt;
1243 var manual = this.manualInColumnHit(block, block.y, nextY);
1244 if (manual)
1245 {
1246 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
1247 continue;
1248 }
1225 1249 var flyer = this.highestFlyingBelow(block);
1226 1250 if (flyer && nextY <= flyer.y + 1 + 1e-9)
1227 1251 {
@@ -1622,6 +1646,8 @@ GameCore.prototype.integrateManual = function (dt)
1622 1646 block.vy = proxy.vy;
1623 1647 block.manualPhase = proxy.phase;
1624 1648 block.y = Math.min(nextY, block.manualTarget);
1649 if (this.tryMergeManualWithFalling(block, oldY, block.y))
1650 { continue; }
1625 1651 if (block.y >= block.manualTarget - 1e-12)
1626 1652 {
1627 1653 block.y = block.manualTarget;
@@ -1655,11 +1681,207 @@ GameCore.prototype.integrateManual = function (dt)
1655 1681 else
1656 1682 {
1657 1683 block.y = Math.min(nextY, this.height - 1);
1684 if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))
1685 { continue; }
1658 1686 }
1659 1687 }
1660 1688 }
1661 1689 };
1662 1690
1691 /**
1692 * If the manual throw (or its path this step) hits falling blocks, merge
1693 * them into a flying cluster with mass-weighted velocity, the same rule
1694 * as two flying clusters colliding (t1108). Returns true if merged.
1695 */
1696 GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
1697 {
1698 if (!manual || manual.state !== STATE_MANUAL)
1699 { return false; }
1700 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
1701 if (!hits.length)
1702 { return false; }
1703 this.mergeManualWithFalling(manual, hits);
1704 return true;
1705 };
1706
1707 GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
1708 {
1709 var lo = Math.min(oldY, newY);
1710 var hi = Math.max(oldY, newY) + 1;
1711 for (var i = 0; i < this.blocks.length; i++)
1712 {
1713 var other = this.blocks[i];
1714 if (other === falling || other.col !== falling.col)
1715 { continue; }
1716 if (other.state !== STATE_MANUAL)
1717 { continue; }
1718 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1719 { return other; }
1720 }
1721 return null;
1722 };
1723
1724 GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
1725 {
1726 var lo = Math.min(oldY, newY);
1727 var hi = Math.max(oldY, newY) + 1;
1728 var hits = [];
1729 for (var i = 0; i < this.blocks.length; i++)
1730 {
1731 var other = this.blocks[i];
1732 if (other === manual || other.col !== manual.col)
1733 { continue; }
1734 if (other.state !== STATE_FALLING)
1735 { continue; }
1736 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1737 { hits.push(other); }
1738 }
1739 if (!hits.length)
1740 { return hits; }
1741 return this.contiguousFallingInColumn(manual.col, manual, hits);
1742 };
1743
1744 /**
1745 * Every falling block in `col` that overlaps `anchor` or a hit already
1746 * in `seed`, plus a contiguous falling stack sitting on them.
1747 */
1748 GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
1749 {
1750 var falling = [];
1751 for (var i = 0; i < this.blocks.length; i++)
1752 {
1753 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
1754 { falling.push(this.blocks[i]); }
1755 }
1756 falling.sort(function (a, b) { return a.y - b.y; });
1757 var include = Object.create(null);
1758 var queue = [];
1759 function enqueue (b)
1760 {
1761 if (!b || include[b.id])
1762 { return; }
1763 include[b.id] = true;
1764 queue.push(b);
1765 }
1766 if (seed)
1767 {
1768 for (var s = 0; s < seed.length; s++)
1769 { enqueue(seed[s]); }
1770 }
1771 // Also include falling that already overlap the anchor.
1772 if (anchor)
1773 {
1774 for (var i = 0; i < falling.length; i++)
1775 {
1776 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
1777 { enqueue(falling[i]); }
1778 }
1779 }
1780 for (var q = 0; q < queue.length; q++)
1781 {
1782 var a = queue[q];
1783 for (var i = 0; i < falling.length; i++)
1784 {
1785 var b = falling[i];
1786 if (include[b.id])
1787 { continue; }
1788 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
1789 { enqueue(b); }
1790 }
1791 }
1792 var out = [];
1793 for (var i = 0; i < falling.length; i++)
1794 {
1795 if (include[falling[i].id])
1796 { out.push(falling[i]); }
1797 }
1798 return out;
1799 };
1800
1801 /**
1802 * Merge a thrown (manual) block with falling blocks into one flying
1803 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
1804 * averages by block count, identical to mergeClusterGroup. The thrown
1805 * block stops being manual and the group follows normal cluster physics.
1806 * fromManual marks the cluster so later falling cargo also averages in.
1807 */
1808 GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1809 {
1810 if (!manual || manual.state !== STATE_MANUAL)
1811 { return null; }
1812 var blocks = [manual];
1813 for (var i = 0; i < fallingList.length; i++)
1814 {
1815 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
1816 { blocks.push(fallingList[i]); }
1817 }
1818 if (blocks.length < 2)
1819 { return null; }
1820 var n = blocks.length;
1821 var vySum = 0;
1822 var decelSum = 0;
1823 var hSum = 0;
1824 for (var i = 0; i < n; i++)
1825 {
1826 var b = blocks[i];
1827 vySum += b.vy;
1828 if (b === manual)
1829 {
1830 decelSum += manual.manualDecel || 0;
1831 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
1832 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
1833 }
1834 }
1835 var cluster = {
1836 id: this.nextClusterId++,
1837 jumpHeight: hSum / n,
1838 vy: vySum / n,
1839 decel: decelSum / n,
1840 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
1841 fromManual: true
1842 };
1843 this.clusters[cluster.id] = cluster;
1844 for (var i = 0; i < n; i++)
1845 {
1846 var b = blocks[i];
1847 b.clusterId = cluster.id;
1848 b.state = STATE_FLYING;
1849 b.vy = cluster.vy;
1850 b.flame = b.color === COLOR_GRAY;
1851 b.manualPhase = null;
1852 b.manualTarget = null;
1853 b.manualDecel = 0;
1854 b.manualJumpHeight = 0;
1855 b.pushedClusters = null;
1856 b.settleTime = 0;
1857 }
1858 if (this.drag && this.drag.blockId === manual.id)
1859 { this.drag = null; }
1860 this.packClusterOverlaps(cluster);
1861 this.checkChainRelaunch(cluster);
1862 return cluster;
1863 };
1864
1865 /** Safety net: any remaining manual/falling overlaps after the substep. */
1866 GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1867 {
1868 var manuals = [];
1869 for (var i = 0; i < this.blocks.length; i++)
1870 {
1871 if (this.blocks[i].state === STATE_MANUAL)
1872 { manuals.push(this.blocks[i]); }
1873 }
1874 for (var m = 0; m < manuals.length; m++)
1875 {
1876 var manual = manuals[m];
1877 if (manual.state !== STATE_MANUAL)
1878 { continue; }
1879 var hits = this.contiguousFallingInColumn(manual.col, manual);
1880 if (hits.length)
1881 { this.mergeManualWithFalling(manual, hits); }
1882 }
1883 };
1884
1663 1885 GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1664 1886 {
1665 1887 if (!manual.pushedClusters)
@@ -1791,10 +2013,12 @@ GameCore.prototype.startManualLaunch = function (block)
1791 2013 {
1792 2014 var target = this.height - 1;
1793 2015 var height = Math.max(0.05, target - block.y);
2016 this.leaveCluster(block);
1794 2017 block.state = STATE_MANUAL;
1795 2018 block.pushedClusters = Object.create(null);
1796 2019 block.manualTarget = target;
1797 2020 block.manualPhase = 'up';
2021 block.manualJumpHeight = height;
1798 2022 block.vy = PlanetMod.launchVelocity(this.planet, height);
1799 2023 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
1800 2024 block.flame = false;
@@ -1968,7 +2192,11 @@ GameCore.prototype.findMatchLines = function ()
1968 2192 for (var i = 0; i < this.blocks.length; i++)
1969 2193 {
1970 2194 var block = this.blocks[i];
1971 if (block.state === STATE_STILL && block.color >= 0)
2195 // Coloured cargo in a just-landed cluster (SETTLING) can match
2196 // with already-resting blocks immediately (t1110). Greys have no
2197 // colour and wait until they recolor; after release they are STILL.
2198 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
2199 && block.color >= 0)
1972 2200 { candidates.push(block); }
1973 2201 }
1974 2202 return this.collectLines(candidates, true);
@@ -2278,48 +2506,103 @@ GameCore.prototype.beginDrag = function (col, y)
2278 2506 };
2279 2507
2280 2508 /**
2281 * Instant grab: the nearest still, coloured block to (col, y), allowing
2282 * a small vertical miss and a horizontal slop into a neighbouring
2283 * column. `col` may be fractional (pointer x in tiles). No hold delay.
2509 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
2510 * floor(col), floor(y); any press inside that cell — corners, padding,
2511 * gaps between sprites, a visually tweened or bouncing sprite — grabs
2512 * the block that occupies it. This uses simulation cells, not the drawn
2513 * sprite bounds. If no block sits in that cell (mid-animation, a block
2514 * whose y is off the integer), fall back to the nearest grabbable block
2515 * in the same column within SNAP_Y (about half a tile). A small
2516 * horizontal slop still consults a neighbouring column when the press
2517 * is near the edge and the primary cell is empty.
2284 2518 */
2285 2519 GameCore.prototype.snapDragBlock = function (col, y)
2286 2520 {
2287 2521 var raw = col;
2288 2522 var c0 = Math.floor(raw + 1e-9);
2523 var row = Math.floor(y + 1e-9);
2289 2524 var frac = raw - c0;
2290 var candidates = [];
2291 if (c0 >= 0 && c0 < this.width)
2292 { candidates.push(c0); }
2293 // Only consult a neighbour when the pointer is actually near the edge
2294 // (a whole-number col, as in unit tests, stays in that column).
2525
2526 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
2527 {
2528 var exact = this.draggableInCell(c0, row);
2529 if (exact)
2530 { return exact; }
2531 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
2532 if (near)
2533 { return near; }
2534 }
2535
2536 // Primary cell empty: allow a small horizontal slop into a neighbour.
2537 var neighbours = [];
2295 2538 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
2296 { candidates.push(c0 - 1); }
2539 { neighbours.push(c0 - 1); }
2297 2540 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
2298 { candidates.push(c0 + 1); }
2541 { neighbours.push(c0 + 1); }
2542 var best = null;
2543 var bestDist = Infinity;
2544 for (var n = 0; n < neighbours.length; n++)
2545 {
2546 var cc = neighbours[n];
2547 if (!this.columnAllowsDrag(cc))
2548 { continue; }
2549 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
2550 if (!hit)
2551 { continue; }
2552 var dist = this.pointerDistToBlock(hit, raw, y);
2553 if (dist < bestDist)
2554 {
2555 bestDist = dist;
2556 best = hit;
2557 }
2558 }
2559 return best;
2560 };
2299 2561
2562 /** The draggable block that occupies grid cell (col, row), if any. */
2563 GameCore.prototype.draggableInCell = function (col, row)
2564 {
2565 var best = null;
2566 var bestOverlap = 0;
2567 var list = this.blocksInColumn(col);
2568 for (var i = 0; i < list.length; i++)
2569 {
2570 var block = list[i];
2571 if (!this.isDraggableBlock(block))
2572 { continue; }
2573 var lo = Math.max(block.y, row);
2574 var hi = Math.min(block.y + 1, row + 1);
2575 var overlap = hi - lo;
2576 if (overlap > bestOverlap + 1e-12)
2577 {
2578 bestOverlap = overlap;
2579 best = block;
2580 }
2581 }
2582 if (best && bestOverlap > 1e-9)
2583 { return best; }
2584 return null;
2585 };
2586
2587 /** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
2588 GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
2589 {
2300 2590 var best = null;
2301 2591 var bestDist = Infinity;
2302 for (var c = 0; c < candidates.length; c++)
2592 var list = this.blocksInColumn(col);
2593 for (var i = 0; i < list.length; i++)
2303 2594 {
2304 var cc = candidates[c];
2305 if (!this.isColumnStill(cc))
2595 var block = list[i];
2596 if (!this.isDraggableBlock(block))
2306 2597 { continue; }
2307 var list = this.blocksInColumn(cc);
2308 for (var i = 0; i < list.length; i++)
2598 var dist = this.pointerDistToBlock(block, col + 0.5, y);
2599 if (dist < bestDist)
2309 2600 {
2310 var block = list[i];
2311 if (block.state !== STATE_STILL || block.color < 0)
2312 { continue; }
2313 var dist = this.pointerDistToBlock(block, raw, y);
2314 // Prefer the column the pointer is actually in on a tie.
2315 if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))
2316 {
2317 bestDist = dist;
2318 best = block;
2319 }
2601 bestDist = dist;
2602 best = block;
2320 2603 }
2321 2604 }
2322 if (!best || bestDist > SNAP_Y)
2605 if (!best || bestDist > maxDist)
2323 2606 { return null; }
2324 2607 return best;
2325 2608 };
@@ -2348,12 +2631,12 @@ GameCore.prototype.moveDrag = function (y)
2348 2631 if (!this.drag)
2349 2632 { return; }
2350 2633 var block = this.blockById(this.drag.blockId);
2351 if (!block || block.state !== STATE_STILL)
2634 if (!block || !this.isDraggableBlock(block))
2352 2635 {
2353 2636 this.drag = null;
2354 2637 return;
2355 2638 }
2356 if (!this.isColumnStill(block.col))
2639 if (!this.columnAllowsDrag(block.col))
2357 2640 {
2358 2641 this.drag = null;
2359 2642 return;
@@ -2483,15 +2766,101 @@ GameCore.prototype.swapBlocks = function (a, b)
2483 2766 var y = a.y;
2484 2767 a.y = b.y;
2485 2768 b.y = y;
2769 this.transferLandedMembership(a, b);
2770 };
2771
2772 /**
2773 * A landed cluster (grey rockets or linked cargo resting on the ground)
2774 * is a swappable part of the contiguous grounded stack. Flying, falling
2775 * and manual blocks are not. A locked column is not.
2776 */
2777 GameCore.prototype.isDraggableBlock = function (block)
2778 {
2779 if (!block)
2780 { return false; }
2781 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
2782 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
2783 { return false; }
2784 if (block.clusterId != null)
2785 {
2786 var cluster = this.clusters[block.clusterId];
2787 // Flying (rising / descending) clusters stay non-draggable.
2788 if (cluster && cluster.phase !== 'landed')
2789 { return false; }
2790 }
2791 return block.state === STATE_STILL || block.state === STATE_SETTLING;
2792 };
2793
2794 /**
2795 * The grounded contiguous stack in this column can be dragged, even if a
2796 * flying cluster or a falling spawn occupies the air above it. Only a
2797 * locked column is blocked as a whole.
2798 */
2799 GameCore.prototype.columnAllowsDrag = function (col)
2800 {
2801 return !this.isColumnLocked(col);
2802 };
2803
2804 GameCore.prototype.landedClusterId = function (block)
2805 {
2806 if (!block || block.clusterId == null)
2807 { return null; }
2808 var cluster = this.clusters[block.clusterId];
2809 if (!cluster || cluster.phase !== 'landed')
2810 { return null; }
2811 return block.clusterId;
2812 };
2813
2814 /**
2815 * After a swap: leaving a landed cluster clears membership; joining one
2816 * makes the block part of that rigid group. Same-cluster swaps only
2817 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
2818 */
2819 GameCore.prototype.transferLandedMembership = function (a, b)
2820 {
2821 var ca = this.landedClusterId(a);
2822 var cb = this.landedClusterId(b);
2823 if (ca === cb)
2824 { return; }
2825 // Join first so leaveCluster does not delete a cluster that still
2826 // has the incoming member.
2827 this.applyLandedMembership(b, ca);
2828 this.applyLandedMembership(a, cb);
2829 };
2830
2831 GameCore.prototype.applyLandedMembership = function (block, clusterId)
2832 {
2833 if (clusterId == null)
2834 {
2835 var wasGrey = block.color === COLOR_GRAY;
2836 var wasSettling = block.state === STATE_SETTLING;
2837 this.leaveCluster(block);
2838 if (wasGrey && wasSettling)
2839 {
2840 // Keep settling and recolor on its own, same remaining timer.
2841 block.state = STATE_SETTLING;
2842 }
2843 else if (wasSettling)
2844 {
2845 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2846 }
2847 return;
2848 }
2849 if (!this.clusters[clusterId])
2850 { return; }
2851 block.clusterId = clusterId;
2852 block.flame = false;
2853 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
2854 { block.state = STATE_SETTLING; }
2486 2855 };
2487 2856
2488 2857 /**
2489 2858 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
2490 * Returns the moved block, or null if the column is not still.
2859 * Returns the moved block, or null if the column does not allow a drag.
2491 2860 */
2492 2861 GameCore.prototype.swapTo = function (col, fromRow, toRow)
2493 2862 {
2494 if (!this.isColumnStill(col))
2863 if (!this.columnAllowsDrag(col))
2495 2864 { return null; }
2496 2865 var block = this.blockAt(col, fromRow);
2497 2866 if (!block)
@@ -3196,6 +3565,9 @@ var app = {
3196 3565 flames: Object.create(null),
3197 3566 cells: [],
3198 3567 pointerId: null,
3568 pointerType: null,
3569 activeTouchId: null,
3570 debugDrag: false,
3199 3571 gameOverShown: false,
3200 3572 selectTween: null,
3201 3573 online: false,
@@ -3208,6 +3580,7 @@ var app = {
3208 3580
3209 3581 window.onload = function ()
3210 3582 {
3583 app.debugDrag = isDragDebugEnabled();
3211 3584 var play = document.getElementById('btn-play');
3212 3585 play.addEventListener('click', onPlay);
3213 3586 play.addEventListener('pointerup', function (e)
@@ -3360,10 +3733,25 @@ function placeTile (obj, col, y)
3360 3733 obj.transform.size = { x: t, y: t };
3361 3734 }
3362 3735
3736 function layoutIfNeeded ()
3737 {
3738 if (app.core && app.core.drag)
3739 { return; }
3740 var vw = window.innerWidth || 320;
3741 var vh = window.innerHeight || 480;
3742 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
3743 { return; }
3744 layout();
3745 }
3746
3363 3747 function layout ()
3364 3748 {
3749 if (app.core && app.core.drag)
3750 { return; }
3365 3751 var vw = window.innerWidth || 320;
3366 3752 var vh = window.innerHeight || 480;
3753 app._layoutVw = vw;
3754 app._layoutVh = vh;
3367 3755 var safeTop = 0;
3368 3756 try
3369 3757 {
@@ -3447,9 +3835,16 @@ function syncSprites ()
3447 3835 }
3448 3836 flame.renderer.visible = true;
3449 3837 var t = app.tile;
3838 // 3x as large (length and width, t1110). Keep the top of the
3839 // flame at the same overlap into the block so the extra length
3840 // extends downward under the rocket.
3841 var flameW = t * 0.85 * 3;
3842 var flameH = t * 0.85 * 3;
3843 var origCenter = app.fieldH - block.y * t + t * 0.15;
3844 var origTop = origCenter - (t * 0.85) / 2;
3450 3845 flame.transform.position.x = block.col * t + t / 2;
3451 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
3452 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
3846 flame.transform.position.y = origTop + flameH / 2;
3847 flame.transform.size = { x: flameW, y: flameH };
3453 3848 }
3454 3849 else if (app.flames[block.id])
3455 3850 { app.flames[block.id].renderer.visible = false; }
@@ -3589,7 +3984,11 @@ function tickView (dt)
3589 3984 if (app.mode !== 'playing' || !app.core)
3590 3985 { return; }
3591 3986
3592 layout();
3987 // Never resize the canvas mid-drag: a URL-bar hide would move the
3988 // field under the finger and jump the target row. Also skip work
3989 // when the viewport has not actually changed.
3990 if (!(app.core && app.core.drag))
3991 { layoutIfNeeded(); }
3593 3992 for (var i = 0; i < app.cells.length; i++)
3594 3993 {
3595 3994 var col = i % 10;
@@ -3619,15 +4018,58 @@ function tickView (dt)
3619 4018
3620 4019 /* ---------- pointer input (mouse + touch) --------------------------- */
3621 4020 /*
3622 * Both mouse and touch use Pointer Events. After pointerdown we listen
3623 * on window, so a drag that leaves the canvas (needed to launch a
3624 * block at the top of a full column) still reaches moveDrag. We do
3625 * not treat lostpointercapture as the end of a drag: on some touch
3626 * browsers that fires mid-gesture and would cancel a launch.
4021 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
4022 * on a real phone, pointer clientX/Y can disagree with the visual
4023 * finger (zoomed visual viewport, gesture takeover, capture cancel)
4024 * while changedTouches stays correct. When a touch is active, pointer
4025 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
4026 * walk the block to the top or bottom of the stack (t1106).
4027 *
4028 * After a down we also listen on the document, so a drag that leaves
4029 * the canvas (needed to launch a block at the top of a full column)
4030 * still reaches moveDrag. We do not call setPointerCapture: on mobile
4031 * that is often cancelled when the browser takes the gesture, which
4032 * would fire pointercancel mid-drag.
4033 *
4034 * A non-passive document touchstart/touchmove preventDefault during
4035 * play stops scrolling, rubber-banding and the pointercancel that
4036 * follows. pointercancel / touchcancel end the drag without launch.
4037 *
4038 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
3627 4039 */
3628 4040
3629 4041 var boundCanvas = null;
3630 4042 var windowListening = false;
4043 var touchListening = false;
4044 var lastDragDebug = null;
4045
4046 function isDragDebugEnabled ()
4047 {
4048 try
4049 {
4050 var q = window.location && window.location.search;
4051 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
4052 { return true; }
4053 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
4054 { return true; }
4055 }
4056 catch (err) { /* ignore */ }
4057 return false;
4058 }
4059
4060 function eventClient (e)
4061 {
4062 var t = null;
4063 if (e.changedTouches && e.changedTouches.length)
4064 { t = e.changedTouches[0]; }
4065 else if (e.touches && e.touches.length)
4066 { t = e.touches[0]; }
4067 if (t)
4068 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
4069 if (e.clientX != null && e.clientY != null)
4070 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
4071 return null;
4072 }
3631 4073
3632 4074 function addWindowPointer ()
3633 4075 {
@@ -3635,7 +4077,7 @@ function addWindowPointer ()
3635 4077 { return; }
3636 4078 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
3637 4079 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
3638 window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });
4080 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
3639 4081 windowListening = true;
3640 4082 }
3641 4083
@@ -3645,28 +4087,59 @@ function removeWindowPointer ()
3645 4087 { return; }
3646 4088 window.removeEventListener('pointermove', onPointerMove, { capture: true });
3647 4089 window.removeEventListener('pointerup', onPointerUp, { capture: true });
3648 window.removeEventListener('pointercancel', onPointerUp, { capture: true });
4090 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
3649 4091 windowListening = false;
3650 4092 }
3651 4093
4094 function addTouchListeners ()
4095 {
4096 if (touchListening)
4097 { return; }
4098 var opts = { capture: true, passive: false };
4099 document.addEventListener('touchstart', onTouchStart, opts);
4100 document.addEventListener('touchmove', onTouchMove, opts);
4101 document.addEventListener('touchend', onTouchEnd, opts);
4102 document.addEventListener('touchcancel', onTouchCancel, opts);
4103 touchListening = true;
4104 }
4105
4106 function removeTouchListeners ()
4107 {
4108 if (!touchListening)
4109 { return; }
4110 var opts = { capture: true };
4111 document.removeEventListener('touchstart', onTouchStart, opts);
4112 document.removeEventListener('touchmove', onTouchMove, opts);
4113 document.removeEventListener('touchend', onTouchEnd, opts);
4114 document.removeEventListener('touchcancel', onTouchCancel, opts);
4115 touchListening = false;
4116 }
4117
3652 4118 function bindPointer (canvas)
3653 4119 {
3654 4120 unbindPointer();
3655 4121 boundCanvas = canvas;
3656 4122 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
3657 4123 canvas.style.touchAction = 'none';
4124 canvas.style.position = 'fixed';
3658 4125 canvas.style.cursor = 'pointer';
3659 4126 canvas.style.webkitUserSelect = 'none';
3660 4127 canvas.style.userSelect = 'none';
4128 addTouchListeners();
4129 if (app.debugDrag)
4130 { ensureDragDebugOverlay(); }
3661 4131 }
3662 4132
3663 4133 function unbindPointer ()
3664 4134 {
3665 4135 removeWindowPointer();
4136 removeTouchListeners();
3666 4137 if (boundCanvas)
3667 4138 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
3668 4139 boundCanvas = null;
3669 4140 app.pointerId = null;
4141 app.pointerType = null;
4142 app.activeTouchId = null;
3670 4143 }
3671 4144
3672 4145 function fieldFromEvent (e)
@@ -3677,34 +4150,94 @@ function fieldFromEvent (e)
3677 4150 var rect = canvas.getBoundingClientRect();
3678 4151 if (rect.width <= 0 || rect.height <= 0)
3679 4152 { return null; }
4153 var pt = eventClient(e);
4154 if (!pt)
4155 { return null; }
3680 4156 // Map through the CSS box only. Using canvas.width / app.tile would
3681 4157 // scale the pointer by the backing-store ratio whenever that differs
3682 4158 // from the layout size (high-DPR devices), so a short finger move
3683 4159 // would look like a long swipe.
3684 4160 var width = Planet.FIELD_WIDTH;
3685 4161 var height = Planet.FIELD_HEIGHT;
3686 var col = ((e.clientX - rect.left) / rect.width) * width;
3687 var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;
3688 return { col: col, y: fieldY };
4162 var col = ((pt.x - rect.left) / rect.width) * width;
4163 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
4164 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
4165 }
4166
4167 function playingForDrag ()
4168 {
4169 return app.core && app.core.state === 'playing';
4170 }
4171
4172 function startDragFromEvent (e)
4173 {
4174 var pos = fieldFromEvent(e);
4175 if (!pos)
4176 { return; }
4177 if (app.core.drag)
4178 {
4179 app.core.moveDrag(pos.y);
4180 logDragDebug(e, pos, 'move-already');
4181 return;
4182 }
4183 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
4184 { startPressTween(app.core.drag.blockId); }
4185 logDragDebug(e, pos, 'down');
4186 }
4187
4188 function moveDragFromEvent (e)
4189 {
4190 if (!app.core || !app.core.drag)
4191 { return; }
4192 var pos = fieldFromEvent(e);
4193 if (pos)
4194 { app.core.moveDrag(pos.y); }
4195 logDragDebug(e, pos, 'move');
4196 }
4197
4198 function finishDrag (opts)
4199 {
4200 opts = opts || {};
4201 app.pointerId = null;
4202 app.pointerType = null;
4203 app.activeTouchId = null;
4204 removeWindowPointer();
4205 if (boundCanvas)
4206 {
4207 try
4208 {
4209 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
4210 { boundCanvas.releasePointerCapture(opts.pointerId); }
4211 }
4212 catch (err) { /* ignore */ }
4213 }
4214 startReleaseTween();
4215 if (app.core && app.core.drag)
4216 {
4217 if (opts.noLaunch)
4218 { app.core.drag.launchIntent = false; }
4219 app.core.endDrag();
4220 }
4221 else if (app.core)
4222 { app.core.endDrag(); }
4223 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
3689 4224 }
3690 4225
3691 4226 function onPointerDown (e)
3692 4227 {
3693 if (!app.core || app.core.state !== 'playing')
4228 if (!playingForDrag())
3694 4229 { return; }
3695 if (app.pointerId != null)
4230 if (app.pointerId != null && e.pointerId !== app.pointerId)
3696 4231 { return; }
3697 e.preventDefault();
4232 if (e.preventDefault)
4233 { e.preventDefault(); }
3698 4234 app.pointerId = e.pointerId;
3699 try
3700 { boundCanvas.setPointerCapture(e.pointerId); }
3701 catch (err) { /* ignore */ }
4235 app.pointerType = e.pointerType || 'mouse';
3702 4236 addWindowPointer();
3703 var pos = fieldFromEvent(e);
3704 // Instant grab, no long-press or hold delay: the block is taken on
3705 // pointerdown and the click tween starts in the same moment.
3706 if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
3707 { startPressTween(app.core.drag.blockId); }
4237 // If a touch is already in charge, do not reset the grab from pointerdown.
4238 if (app.activeTouchId != null)
4239 { return; }
4240 startDragFromEvent(e);
3708 4241 }
3709 4242
3710 4243 function onPointerMove (e)
@@ -3713,10 +4246,20 @@ function onPointerMove (e)
3713 4246 { return; }
3714 4247 if (!app.core || !app.core.drag)
3715 4248 { return; }
3716 e.preventDefault();
3717 var pos = fieldFromEvent(e);
3718 if (pos)
3719 { app.core.moveDrag(pos.y); }
4249 // Touch coordinates are the authority; ignore pointer moves for a
4250 // live touch so a wrong clientY cannot walk the whole column.
4251 // Only skip when touchstart has actually arrived — some environments
4252 // deliver touch-pointer events without a TouchEvent stream.
4253 if (app.activeTouchId != null)
4254 {
4255 if (e.preventDefault)
4256 { e.preventDefault(); }
4257 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
4258 return;
4259 }
4260 if (e.preventDefault)
4261 { e.preventDefault(); }
4262 moveDragFromEvent(e);
3720 4263 }
3721 4264
3722 4265 function onPointerUp (e)
@@ -3725,21 +4268,155 @@ function onPointerUp (e)
3725 4268 { return; }
3726 4269 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
3727 4270 { return; }
3728 if (e)
4271 if (app.activeTouchId != null)
4272 {
4273 // touchend will finish the drag.
4274 if (e && e.preventDefault)
4275 { e.preventDefault(); }
4276 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
4277 return;
4278 }
4279 if (e && e.preventDefault)
3729 4280 { e.preventDefault(); }
3730 app.pointerId = null;
3731 removeWindowPointer();
3732 if (boundCanvas)
4281 finishDrag({ pointerId: e && e.pointerId });
4282 }
4283
4284 function onPointerCancel (e)
4285 {
4286 if (app.pointerId == null)
4287 { return; }
4288 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
4289 { return; }
4290 if (app.activeTouchId != null)
3733 4291 {
3734 try
3735 { boundCanvas.releasePointerCapture(e && e.pointerId); }
3736 catch (err) { /* ignore */ }
4292 if (e && e.preventDefault)
4293 { e.preventDefault(); }
4294 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
4295 return;
3737 4296 }
3738 startReleaseTween();
3739 if (app.core)
3740 { app.core.endDrag(); }
4297 if (e && e.preventDefault)
4298 { e.preventDefault(); }
4299 // A cancelled gesture is not a launch pull.
4300 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
4301 }
4302
4303 function touchById (list, id)
4304 {
4305 if (!list)
4306 { return null; }
4307 for (var i = 0; i < list.length; i++)
4308 {
4309 if (list[i].identifier === id)
4310 { return list[i]; }
4311 }
4312 return null;
3741 4313 }
3742 4314
4315 function onTouchStart (e)
4316 {
4317 if (!playingForDrag())
4318 { return; }
4319 if (app.activeTouchId != null)
4320 {
4321 if (e.preventDefault)
4322 { e.preventDefault(); }
4323 return;
4324 }
4325 var t = e.changedTouches && e.changedTouches[0];
4326 if (!t)
4327 { return; }
4328 if (e.preventDefault)
4329 { e.preventDefault(); }
4330 app.activeTouchId = t.identifier;
4331 addWindowPointer();
4332 startDragFromEvent(e);
4333 }
4334
4335 function onTouchMove (e)
4336 {
4337 if (app.activeTouchId == null)
4338 { return; }
4339 if (!touchById(e.changedTouches, app.activeTouchId)
4340 && !touchById(e.touches, app.activeTouchId))
4341 { return; }
4342 if (e.preventDefault)
4343 { e.preventDefault(); }
4344 moveDragFromEvent(e);
4345 }
4346
4347 function onTouchEnd (e)
4348 {
4349 if (app.activeTouchId == null)
4350 { return; }
4351 if (!touchById(e.changedTouches, app.activeTouchId))
4352 { return; }
4353 if (e.preventDefault)
4354 { e.preventDefault(); }
4355 finishDrag({});
4356 }
4357
4358 function onTouchCancel (e)
4359 {
4360 if (app.activeTouchId == null)
4361 { return; }
4362 if (!touchById(e.changedTouches, app.activeTouchId))
4363 { return; }
4364 if (e.preventDefault)
4365 { e.preventDefault(); }
4366 finishDrag({ noLaunch: true });
4367 }
4368
4369 function ensureDragDebugOverlay ()
4370 {
4371 if (document.getElementById('drag-debug'))
4372 { return; }
4373 var el = document.createElement('div');
4374 el.id = 'drag-debug';
4375 el.setAttribute('aria-live', 'polite');
4376 document.body.appendChild(el);
4377 }
4378
4379 function logDragDebug (e, pos, phase)
4380 {
4381 if (!app.debugDrag)
4382 { return; }
4383 ensureDragDebugOverlay();
4384 var el = document.getElementById('drag-debug');
4385 if (!el)
4386 { return; }
4387 var block = null;
4388 if (app.core && app.core.drag)
4389 { block = app.core.blockById(app.core.drag.blockId); }
4390 var pt = e ? eventClient(e) : null;
4391 var evType = e ? e.type : phase;
4392 var info = {
4393 phase: phase,
4394 ev: evType,
4395 src: pos && pos.src,
4396 fieldY: pos && Math.round(pos.y * 100) / 100,
4397 col: pos && Math.round(pos.col * 100) / 100,
4398 cy: pt && Math.round(pt.y * 10) / 10,
4399 blockY: block && Math.round(block.y * 100) / 100,
4400 target: block && Math.floor((pos && pos.y) + 1e-12),
4401 launch: app.core && app.core.drag && app.core.drag.launchIntent,
4402 touchId: app.activeTouchId,
4403 pid: app.pointerId,
4404 ptype: app.pointerType
4405 };
4406 lastDragDebug = info;
4407 el.textContent = 'drag ' + phase
4408 + ' ev=' + evType
4409 + ' src=' + (info.src || '-')
4410 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
4411 + ' → ' + (info.target != null ? info.target : '-')
4412 + ' block=' + (info.blockY != null ? info.blockY : '-')
4413 + (info.launch ? ' LAUNCH' : '')
4414 + ' tId=' + info.touchId
4415 + ' pId=' + info.pid;
4416 el.hidden = false;
4417 }
4418
4419
3743 4420 function hideEl (id)
3744 4421 {
3745 4422 document.getElementById(id).hidden = true;
@@ -668,8 +668,8 @@ var LAUNCH_PULL = 0.35;
668// Minimal accumulated vertical pointer travel (tiles) to swap one step.
668// Minimal accumulated vertical pointer travel (tiles) to swap one step.
669// No hold delay: the first swap fires as soon as this distance is reached.
669// No hold delay: the first swap fires as soon as this distance is reached.
670var SWAP_DISTANCE = 0.25;
670var SWAP_DISTANCE = 0.25;
671// Grab a still block if the pointer is at most this far (tiles) from it.
671// Fallback snap (tiles) when the press cell is empty: nearest block in the column.
672var SNAP_Y = 0.65;
672var SNAP_Y = 0.5;
673// Horizontal slop (tiles) for snapping to a neighbouring column on press.
673// Horizontal slop (tiles) for snapping to a neighbouring column on press.
674var HORIZONTAL_SLOP = 0.35;
674var HORIZONTAL_SLOP = 0.35;
675
675
@@ -1073,12 +1073,29 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)
1073 if (other.y + 1 > roof)
1073 if (other.y + 1 > roof)
1074 { roof = other.y + 1; }
1074 { roof = other.y + 1; }
1075 }
1075 }
1076 var oldN = this.clusterMembers(cluster.id).length;
1077 var fallingVy = block.vy;
1076 block.y = roof;
1078 block.y = roof;
1077 block.state = STATE_FLYING;
1079 block.state = STATE_FLYING;
1078 block.clusterId = cluster.id;
1080 block.clusterId = cluster.id;
1079 block.vy = cluster.vy;
1080 block.flame = false;
1081 block.flame = false;
1081 block.settleTime = 0;
1082 block.settleTime = 0;
1083 // A cluster born from a thrown block averages in falling cargo
1084 // the same way two flying clusters merge (t1108). Other rockets
1085 // keep their velocity and just pick the cargo up.
1086 if (cluster.fromManual)
1087 {
1088 var newN = oldN + 1;
1089 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
1090 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
1091 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
1092 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
1093 var members = this.clusterMembers(cluster.id);
1094 for (var m = 0; m < members.length; m++)
1095 { members[m].vy = cluster.vy; }
1096 }
1097 else
1098 { block.vy = cluster.vy; }
1082 return true;
1099 return true;
1083};
1100};
1084
1101
@@ -1141,6 +1158,7 @@ GameCore.prototype.tick = function (dt)
1141 this.integrateClusters(step);
1158 this.integrateClusters(step);
1142 this.mergeFlyingClusters();
1159 this.mergeFlyingClusters();
1143 this.integrateManual(step);
1160 this.integrateManual(step);
1161 this.mergeAnyManualFallingOverlaps();
1144 this.cullOffTop();
1162 this.cullOffTop();
1145 left -= step;
1163 left -= step;
1146 }
1164 }
@@ -1222,6 +1240,12 @@ GameCore.prototype.integrateFalling = function (dt)
1222 { continue; }
1240 { continue; }
1223 this.accelerateFall(block, dt);
1241 this.accelerateFall(block, dt);
1224 var nextY = block.y + block.vy * dt;
1242 var nextY = block.y + block.vy * dt;
1243 var manual = this.manualInColumnHit(block, block.y, nextY);
1244 if (manual)
1245 {
1246 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
1247 continue;
1248 }
1225 var flyer = this.highestFlyingBelow(block);
1249 var flyer = this.highestFlyingBelow(block);
1226 if (flyer && nextY <= flyer.y + 1 + 1e-9)
1250 if (flyer && nextY <= flyer.y + 1 + 1e-9)
1227 {
1251 {
@@ -1622,6 +1646,8 @@ GameCore.prototype.integrateManual = function (dt)
1622 block.vy = proxy.vy;
1646 block.vy = proxy.vy;
1623 block.manualPhase = proxy.phase;
1647 block.manualPhase = proxy.phase;
1624 block.y = Math.min(nextY, block.manualTarget);
1648 block.y = Math.min(nextY, block.manualTarget);
1649 if (this.tryMergeManualWithFalling(block, oldY, block.y))
1650 { continue; }
1625 if (block.y >= block.manualTarget - 1e-12)
1651 if (block.y >= block.manualTarget - 1e-12)
1626 {
1652 {
1627 block.y = block.manualTarget;
1653 block.y = block.manualTarget;
@@ -1655,11 +1681,207 @@ GameCore.prototype.integrateManual = function (dt)
1655 else
1681 else
1656 {
1682 {
1657 block.y = Math.min(nextY, this.height - 1);
1683 block.y = Math.min(nextY, this.height - 1);
1684 if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))
1685 { continue; }
1658 }
1686 }
1659 }
1687 }
1660 }
1688 }
1661};
1689};
1662
1690
1691/**
1692 * If the manual throw (or its path this step) hits falling blocks, merge
1693 * them into a flying cluster with mass-weighted velocity, the same rule
1694 * as two flying clusters colliding (t1108). Returns true if merged.
1695 */
1696GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
1697{
1698 if (!manual || manual.state !== STATE_MANUAL)
1699 { return false; }
1700 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
1701 if (!hits.length)
1702 { return false; }
1703 this.mergeManualWithFalling(manual, hits);
1704 return true;
1705};
1706
1707GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
1708{
1709 var lo = Math.min(oldY, newY);
1710 var hi = Math.max(oldY, newY) + 1;
1711 for (var i = 0; i < this.blocks.length; i++)
1712 {
1713 var other = this.blocks[i];
1714 if (other === falling || other.col !== falling.col)
1715 { continue; }
1716 if (other.state !== STATE_MANUAL)
1717 { continue; }
1718 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1719 { return other; }
1720 }
1721 return null;
1722};
1723
1724GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
1725{
1726 var lo = Math.min(oldY, newY);
1727 var hi = Math.max(oldY, newY) + 1;
1728 var hits = [];
1729 for (var i = 0; i < this.blocks.length; i++)
1730 {
1731 var other = this.blocks[i];
1732 if (other === manual || other.col !== manual.col)
1733 { continue; }
1734 if (other.state !== STATE_FALLING)
1735 { continue; }
1736 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1737 { hits.push(other); }
1738 }
1739 if (!hits.length)
1740 { return hits; }
1741 return this.contiguousFallingInColumn(manual.col, manual, hits);
1742};
1743
1744/**
1745 * Every falling block in `col` that overlaps `anchor` or a hit already
1746 * in `seed`, plus a contiguous falling stack sitting on them.
1747 */
1748GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
1749{
1750 var falling = [];
1751 for (var i = 0; i < this.blocks.length; i++)
1752 {
1753 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
1754 { falling.push(this.blocks[i]); }
1755 }
1756 falling.sort(function (a, b) { return a.y - b.y; });
1757 var include = Object.create(null);
1758 var queue = [];
1759 function enqueue (b)
1760 {
1761 if (!b || include[b.id])
1762 { return; }
1763 include[b.id] = true;
1764 queue.push(b);
1765 }
1766 if (seed)
1767 {
1768 for (var s = 0; s < seed.length; s++)
1769 { enqueue(seed[s]); }
1770 }
1771 // Also include falling that already overlap the anchor.
1772 if (anchor)
1773 {
1774 for (var i = 0; i < falling.length; i++)
1775 {
1776 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
1777 { enqueue(falling[i]); }
1778 }
1779 }
1780 for (var q = 0; q < queue.length; q++)
1781 {
1782 var a = queue[q];
1783 for (var i = 0; i < falling.length; i++)
1784 {
1785 var b = falling[i];
1786 if (include[b.id])
1787 { continue; }
1788 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
1789 { enqueue(b); }
1790 }
1791 }
1792 var out = [];
1793 for (var i = 0; i < falling.length; i++)
1794 {
1795 if (include[falling[i].id])
1796 { out.push(falling[i]); }
1797 }
1798 return out;
1799};
1800
1801/**
1802 * Merge a thrown (manual) block with falling blocks into one flying
1803 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
1804 * averages by block count, identical to mergeClusterGroup. The thrown
1805 * block stops being manual and the group follows normal cluster physics.
1806 * fromManual marks the cluster so later falling cargo also averages in.
1807 */
1808GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1809{
1810 if (!manual || manual.state !== STATE_MANUAL)
1811 { return null; }
1812 var blocks = [manual];
1813 for (var i = 0; i < fallingList.length; i++)
1814 {
1815 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
1816 { blocks.push(fallingList[i]); }
1817 }
1818 if (blocks.length < 2)
1819 { return null; }
1820 var n = blocks.length;
1821 var vySum = 0;
1822 var decelSum = 0;
1823 var hSum = 0;
1824 for (var i = 0; i < n; i++)
1825 {
1826 var b = blocks[i];
1827 vySum += b.vy;
1828 if (b === manual)
1829 {
1830 decelSum += manual.manualDecel || 0;
1831 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
1832 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
1833 }
1834 }
1835 var cluster = {
1836 id: this.nextClusterId++,
1837 jumpHeight: hSum / n,
1838 vy: vySum / n,
1839 decel: decelSum / n,
1840 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
1841 fromManual: true
1842 };
1843 this.clusters[cluster.id] = cluster;
1844 for (var i = 0; i < n; i++)
1845 {
1846 var b = blocks[i];
1847 b.clusterId = cluster.id;
1848 b.state = STATE_FLYING;
1849 b.vy = cluster.vy;
1850 b.flame = b.color === COLOR_GRAY;
1851 b.manualPhase = null;
1852 b.manualTarget = null;
1853 b.manualDecel = 0;
1854 b.manualJumpHeight = 0;
1855 b.pushedClusters = null;
1856 b.settleTime = 0;
1857 }
1858 if (this.drag && this.drag.blockId === manual.id)
1859 { this.drag = null; }
1860 this.packClusterOverlaps(cluster);
1861 this.checkChainRelaunch(cluster);
1862 return cluster;
1863};
1864
1865/** Safety net: any remaining manual/falling overlaps after the substep. */
1866GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1867{
1868 var manuals = [];
1869 for (var i = 0; i < this.blocks.length; i++)
1870 {
1871 if (this.blocks[i].state === STATE_MANUAL)
1872 { manuals.push(this.blocks[i]); }
1873 }
1874 for (var m = 0; m < manuals.length; m++)
1875 {
1876 var manual = manuals[m];
1877 if (manual.state !== STATE_MANUAL)
1878 { continue; }
1879 var hits = this.contiguousFallingInColumn(manual.col, manual);
1880 if (hits.length)
1881 { this.mergeManualWithFalling(manual, hits); }
1882 }
1883};
1884
1663GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1885GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1664{
1886{
1665 if (!manual.pushedClusters)
1887 if (!manual.pushedClusters)
@@ -1791,10 +2013,12 @@ GameCore.prototype.startManualLaunch = function (block)
1791{
2013{
1792 var target = this.height - 1;
2014 var target = this.height - 1;
1793 var height = Math.max(0.05, target - block.y);
2015 var height = Math.max(0.05, target - block.y);
2016 this.leaveCluster(block);
1794 block.state = STATE_MANUAL;
2017 block.state = STATE_MANUAL;
1795 block.pushedClusters = Object.create(null);
2018 block.pushedClusters = Object.create(null);
1796 block.manualTarget = target;
2019 block.manualTarget = target;
1797 block.manualPhase = 'up';
2020 block.manualPhase = 'up';
2021 block.manualJumpHeight = height;
1798 block.vy = PlanetMod.launchVelocity(this.planet, height);
2022 block.vy = PlanetMod.launchVelocity(this.planet, height);
1799 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
2023 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
1800 block.flame = false;
2024 block.flame = false;
@@ -1968,7 +2192,11 @@ GameCore.prototype.findMatchLines = function ()
1968 for (var i = 0; i < this.blocks.length; i++)
2192 for (var i = 0; i < this.blocks.length; i++)
1969 {
2193 {
1970 var block = this.blocks[i];
2194 var block = this.blocks[i];
1971 if (block.state === STATE_STILL && block.color >= 0)
2195 // Coloured cargo in a just-landed cluster (SETTLING) can match
2196 // with already-resting blocks immediately (t1110). Greys have no
2197 // colour and wait until they recolor; after release they are STILL.
2198 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
2199 && block.color >= 0)
1972 { candidates.push(block); }
2200 { candidates.push(block); }
1973 }
2201 }
1974 return this.collectLines(candidates, true);
2202 return this.collectLines(candidates, true);
@@ -2278,48 +2506,103 @@ GameCore.prototype.beginDrag = function (col, y)
2278};
2506};
2279
2507
2280/**
2508/**
2281 * Instant grab: the nearest still, coloured block to (col, y), allowing
2509 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
2282 * a small vertical miss and a horizontal slop into a neighbouring
2510 * floor(col), floor(y); any press inside that cell — corners, padding,
2283 * column. `col` may be fractional (pointer x in tiles). No hold delay.
2511 * gaps between sprites, a visually tweened or bouncing sprite — grabs
2512 * the block that occupies it. This uses simulation cells, not the drawn
2513 * sprite bounds. If no block sits in that cell (mid-animation, a block
2514 * whose y is off the integer), fall back to the nearest grabbable block
2515 * in the same column within SNAP_Y (about half a tile). A small
2516 * horizontal slop still consults a neighbouring column when the press
2517 * is near the edge and the primary cell is empty.
2284 */
2518 */
2285GameCore.prototype.snapDragBlock = function (col, y)
2519GameCore.prototype.snapDragBlock = function (col, y)
2286{
2520{
2287 var raw = col;
2521 var raw = col;
2288 var c0 = Math.floor(raw + 1e-9);
2522 var c0 = Math.floor(raw + 1e-9);
2523 var row = Math.floor(y + 1e-9);
2289 var frac = raw - c0;
2524 var frac = raw - c0;
2290 var candidates = [];
2525
2291 if (c0 >= 0 && c0 < this.width)
2526 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
2292 { candidates.push(c0); }
2527 {
2293 // Only consult a neighbour when the pointer is actually near the edge
2528 var exact = this.draggableInCell(c0, row);
2294 // (a whole-number col, as in unit tests, stays in that column).
2529 if (exact)
2530 { return exact; }
2531 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
2532 if (near)
2533 { return near; }
2534 }
2535
2536 // Primary cell empty: allow a small horizontal slop into a neighbour.
2537 var neighbours = [];
2295 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
2538 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
2296 { candidates.push(c0 - 1); }
2539 { neighbours.push(c0 - 1); }
2297 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
2540 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
2298 { candidates.push(c0 + 1); }
2541 { neighbours.push(c0 + 1); }
2542 var best = null;
2543 var bestDist = Infinity;
2544 for (var n = 0; n < neighbours.length; n++)
2545 {
2546 var cc = neighbours[n];
2547 if (!this.columnAllowsDrag(cc))
2548 { continue; }
2549 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
2550 if (!hit)
2551 { continue; }
2552 var dist = this.pointerDistToBlock(hit, raw, y);
2553 if (dist < bestDist)
2554 {
2555 bestDist = dist;
2556 best = hit;
2557 }
2558 }
2559 return best;
2560};
2299
2561
2562/** The draggable block that occupies grid cell (col, row), if any. */
2563GameCore.prototype.draggableInCell = function (col, row)
2564{
2565 var best = null;
2566 var bestOverlap = 0;
2567 var list = this.blocksInColumn(col);
2568 for (var i = 0; i < list.length; i++)
2569 {
2570 var block = list[i];
2571 if (!this.isDraggableBlock(block))
2572 { continue; }
2573 var lo = Math.max(block.y, row);
2574 var hi = Math.min(block.y + 1, row + 1);
2575 var overlap = hi - lo;
2576 if (overlap > bestOverlap + 1e-12)
2577 {
2578 bestOverlap = overlap;
2579 best = block;
2580 }
2581 }
2582 if (best && bestOverlap > 1e-9)
2583 { return best; }
2584 return null;
2585};
2586
2587/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
2588GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
2589{
2300 var best = null;
2590 var best = null;
2301 var bestDist = Infinity;
2591 var bestDist = Infinity;
2302 for (var c = 0; c < candidates.length; c++)
2592 var list = this.blocksInColumn(col);
2593 for (var i = 0; i < list.length; i++)
2303 {
2594 {
2304 var cc = candidates[c];
2595 var block = list[i];
2305 if (!this.isColumnStill(cc))
2596 if (!this.isDraggableBlock(block))
2306 { continue; }
2597 { continue; }
2307 var list = this.blocksInColumn(cc);
2598 var dist = this.pointerDistToBlock(block, col + 0.5, y);
2308 for (var i = 0; i < list.length; i++)
2599 if (dist < bestDist)
2309 {
2600 {
2310 var block = list[i];
2601 bestDist = dist;
2311 if (block.state !== STATE_STILL || block.color < 0)
2602 best = block;
2312 { continue; }
2313 var dist = this.pointerDistToBlock(block, raw, y);
2314 // Prefer the column the pointer is actually in on a tie.
2315 if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))
2316 {
2317 bestDist = dist;
2318 best = block;
2319 }
2320 }
2603 }
2321 }
2604 }
2322 if (!best || bestDist > SNAP_Y)
2605 if (!best || bestDist > maxDist)
2323 { return null; }
2606 { return null; }
2324 return best;
2607 return best;
2325};
2608};
@@ -2348,12 +2631,12 @@ GameCore.prototype.moveDrag = function (y)
2348 if (!this.drag)
2631 if (!this.drag)
2349 { return; }
2632 { return; }
2350 var block = this.blockById(this.drag.blockId);
2633 var block = this.blockById(this.drag.blockId);
2351 if (!block || block.state !== STATE_STILL)
2634 if (!block || !this.isDraggableBlock(block))
2352 {
2635 {
2353 this.drag = null;
2636 this.drag = null;
2354 return;
2637 return;
2355 }
2638 }
2356 if (!this.isColumnStill(block.col))
2639 if (!this.columnAllowsDrag(block.col))
2357 {
2640 {
2358 this.drag = null;
2641 this.drag = null;
2359 return;
2642 return;
@@ -2483,15 +2766,101 @@ GameCore.prototype.swapBlocks = function (a, b)
2483 var y = a.y;
2766 var y = a.y;
2484 a.y = b.y;
2767 a.y = b.y;
2485 b.y = y;
2768 b.y = y;
2769 this.transferLandedMembership(a, b);
2770};
2771
2772/**
2773 * A landed cluster (grey rockets or linked cargo resting on the ground)
2774 * is a swappable part of the contiguous grounded stack. Flying, falling
2775 * and manual blocks are not. A locked column is not.
2776 */
2777GameCore.prototype.isDraggableBlock = function (block)
2778{
2779 if (!block)
2780 { return false; }
2781 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
2782 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
2783 { return false; }
2784 if (block.clusterId != null)
2785 {
2786 var cluster = this.clusters[block.clusterId];
2787 // Flying (rising / descending) clusters stay non-draggable.
2788 if (cluster && cluster.phase !== 'landed')
2789 { return false; }
2790 }
2791 return block.state === STATE_STILL || block.state === STATE_SETTLING;
2792};
2793
2794/**
2795 * The grounded contiguous stack in this column can be dragged, even if a
2796 * flying cluster or a falling spawn occupies the air above it. Only a
2797 * locked column is blocked as a whole.
2798 */
2799GameCore.prototype.columnAllowsDrag = function (col)
2800{
2801 return !this.isColumnLocked(col);
2802};
2803
2804GameCore.prototype.landedClusterId = function (block)
2805{
2806 if (!block || block.clusterId == null)
2807 { return null; }
2808 var cluster = this.clusters[block.clusterId];
2809 if (!cluster || cluster.phase !== 'landed')
2810 { return null; }
2811 return block.clusterId;
2812};
2813
2814/**
2815 * After a swap: leaving a landed cluster clears membership; joining one
2816 * makes the block part of that rigid group. Same-cluster swaps only
2817 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
2818 */
2819GameCore.prototype.transferLandedMembership = function (a, b)
2820{
2821 var ca = this.landedClusterId(a);
2822 var cb = this.landedClusterId(b);
2823 if (ca === cb)
2824 { return; }
2825 // Join first so leaveCluster does not delete a cluster that still
2826 // has the incoming member.
2827 this.applyLandedMembership(b, ca);
2828 this.applyLandedMembership(a, cb);
2829};
2830
2831GameCore.prototype.applyLandedMembership = function (block, clusterId)
2832{
2833 if (clusterId == null)
2834 {
2835 var wasGrey = block.color === COLOR_GRAY;
2836 var wasSettling = block.state === STATE_SETTLING;
2837 this.leaveCluster(block);
2838 if (wasGrey && wasSettling)
2839 {
2840 // Keep settling and recolor on its own, same remaining timer.
2841 block.state = STATE_SETTLING;
2842 }
2843 else if (wasSettling)
2844 {
2845 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2846 }
2847 return;
2848 }
2849 if (!this.clusters[clusterId])
2850 { return; }
2851 block.clusterId = clusterId;
2852 block.flame = false;
2853 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
2854 { block.state = STATE_SETTLING; }
2486};
2855};
2487
2856
2488/**
2857/**
2489 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
2858 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
2490 * Returns the moved block, or null if the column is not still.
2859 * Returns the moved block, or null if the column does not allow a drag.
2491 */
2860 */
2492GameCore.prototype.swapTo = function (col, fromRow, toRow)
2861GameCore.prototype.swapTo = function (col, fromRow, toRow)
2493{
2862{
2494 if (!this.isColumnStill(col))
2863 if (!this.columnAllowsDrag(col))
2495 { return null; }
2864 { return null; }
2496 var block = this.blockAt(col, fromRow);
2865 var block = this.blockAt(col, fromRow);
2497 if (!block)
2866 if (!block)
@@ -3196,6 +3565,9 @@ var app = {
3196 flames: Object.create(null),
3565 flames: Object.create(null),
3197 cells: [],
3566 cells: [],
3198 pointerId: null,
3567 pointerId: null,
3568 pointerType: null,
3569 activeTouchId: null,
3570 debugDrag: false,
3199 gameOverShown: false,
3571 gameOverShown: false,
3200 selectTween: null,
3572 selectTween: null,
3201 online: false,
3573 online: false,
@@ -3208,6 +3580,7 @@ var app = {
3208
3580
3209window.onload = function ()
3581window.onload = function ()
3210{
3582{
3583 app.debugDrag = isDragDebugEnabled();
3211 var play = document.getElementById('btn-play');
3584 var play = document.getElementById('btn-play');
3212 play.addEventListener('click', onPlay);
3585 play.addEventListener('click', onPlay);
3213 play.addEventListener('pointerup', function (e)
3586 play.addEventListener('pointerup', function (e)
@@ -3360,10 +3733,25 @@ function placeTile (obj, col, y)
3360 obj.transform.size = { x: t, y: t };
3733 obj.transform.size = { x: t, y: t };
3361}
3734}
3362
3735
3736function layoutIfNeeded ()
3737{
3738 if (app.core && app.core.drag)
3739 { return; }
3740 var vw = window.innerWidth || 320;
3741 var vh = window.innerHeight || 480;
3742 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
3743 { return; }
3744 layout();
3745}
3746
3363function layout ()
3747function layout ()
3364{
3748{
3749 if (app.core && app.core.drag)
3750 { return; }
3365 var vw = window.innerWidth || 320;
3751 var vw = window.innerWidth || 320;
3366 var vh = window.innerHeight || 480;
3752 var vh = window.innerHeight || 480;
3753 app._layoutVw = vw;
3754 app._layoutVh = vh;
3367 var safeTop = 0;
3755 var safeTop = 0;
3368 try
3756 try
3369 {
3757 {
@@ -3447,9 +3835,16 @@ function syncSprites ()
3447 }
3835 }
3448 flame.renderer.visible = true;
3836 flame.renderer.visible = true;
3449 var t = app.tile;
3837 var t = app.tile;
3838 // 3x as large (length and width, t1110). Keep the top of the
3839 // flame at the same overlap into the block so the extra length
3840 // extends downward under the rocket.
3841 var flameW = t * 0.85 * 3;
3842 var flameH = t * 0.85 * 3;
3843 var origCenter = app.fieldH - block.y * t + t * 0.15;
3844 var origTop = origCenter - (t * 0.85) / 2;
3450 flame.transform.position.x = block.col * t + t / 2;
3845 flame.transform.position.x = block.col * t + t / 2;
3451 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
3846 flame.transform.position.y = origTop + flameH / 2;
3452 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
3847 flame.transform.size = { x: flameW, y: flameH };
3453 }
3848 }
3454 else if (app.flames[block.id])
3849 else if (app.flames[block.id])
3455 { app.flames[block.id].renderer.visible = false; }
3850 { app.flames[block.id].renderer.visible = false; }
@@ -3589,7 +3984,11 @@ function tickView (dt)
3589 if (app.mode !== 'playing' || !app.core)
3984 if (app.mode !== 'playing' || !app.core)
3590 { return; }
3985 { return; }
3591
3986
3592 layout();
3987 // Never resize the canvas mid-drag: a URL-bar hide would move the
3988 // field under the finger and jump the target row. Also skip work
3989 // when the viewport has not actually changed.
3990 if (!(app.core && app.core.drag))
3991 { layoutIfNeeded(); }
3593 for (var i = 0; i < app.cells.length; i++)
3992 for (var i = 0; i < app.cells.length; i++)
3594 {
3993 {
3595 var col = i % 10;
3994 var col = i % 10;
@@ -3619,15 +4018,58 @@ function tickView (dt)
3619
4018
3620/* ---------- pointer input (mouse + touch) --------------------------- */
4019/* ---------- pointer input (mouse + touch) --------------------------- */
3621/*
4020/*
3622 * Both mouse and touch use Pointer Events. After pointerdown we listen
4021 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
3623 * on window, so a drag that leaves the canvas (needed to launch a
4022 * on a real phone, pointer clientX/Y can disagree with the visual
3624 * block at the top of a full column) still reaches moveDrag. We do
4023 * finger (zoomed visual viewport, gesture takeover, capture cancel)
3625 * not treat lostpointercapture as the end of a drag: on some touch
4024 * while changedTouches stays correct. When a touch is active, pointer
3626 * browsers that fires mid-gesture and would cancel a launch.
4025 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
4026 * walk the block to the top or bottom of the stack (t1106).
4027 *
4028 * After a down we also listen on the document, so a drag that leaves
4029 * the canvas (needed to launch a block at the top of a full column)
4030 * still reaches moveDrag. We do not call setPointerCapture: on mobile
4031 * that is often cancelled when the browser takes the gesture, which
4032 * would fire pointercancel mid-drag.
4033 *
4034 * A non-passive document touchstart/touchmove preventDefault during
4035 * play stops scrolling, rubber-banding and the pointercancel that
4036 * follows. pointercancel / touchcancel end the drag without launch.
4037 *
4038 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
3627 */
4039 */
3628
4040
3629var boundCanvas = null;
4041var boundCanvas = null;
3630var windowListening = false;
4042var windowListening = false;
4043var touchListening = false;
4044var lastDragDebug = null;
4045
4046function isDragDebugEnabled ()
4047{
4048 try
4049 {
4050 var q = window.location && window.location.search;
4051 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
4052 { return true; }
4053 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
4054 { return true; }
4055 }
4056 catch (err) { /* ignore */ }
4057 return false;
4058}
4059
4060function eventClient (e)
4061{
4062 var t = null;
4063 if (e.changedTouches && e.changedTouches.length)
4064 { t = e.changedTouches[0]; }
4065 else if (e.touches && e.touches.length)
4066 { t = e.touches[0]; }
4067 if (t)
4068 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
4069 if (e.clientX != null && e.clientY != null)
4070 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
4071 return null;
4072}
3631
4073
3632function addWindowPointer ()
4074function addWindowPointer ()
3633{
4075{
@@ -3635,7 +4077,7 @@ function addWindowPointer ()
3635 { return; }
4077 { return; }
3636 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
4078 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
3637 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
4079 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
3638 window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });
4080 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
3639 windowListening = true;
4081 windowListening = true;
3640}
4082}
3641
4083
@@ -3645,28 +4087,59 @@ function removeWindowPointer ()
3645 { return; }
4087 { return; }
3646 window.removeEventListener('pointermove', onPointerMove, { capture: true });
4088 window.removeEventListener('pointermove', onPointerMove, { capture: true });
3647 window.removeEventListener('pointerup', onPointerUp, { capture: true });
4089 window.removeEventListener('pointerup', onPointerUp, { capture: true });
3648 window.removeEventListener('pointercancel', onPointerUp, { capture: true });
4090 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
3649 windowListening = false;
4091 windowListening = false;
3650}
4092}
3651
4093
4094function addTouchListeners ()
4095{
4096 if (touchListening)
4097 { return; }
4098 var opts = { capture: true, passive: false };
4099 document.addEventListener('touchstart', onTouchStart, opts);
4100 document.addEventListener('touchmove', onTouchMove, opts);
4101 document.addEventListener('touchend', onTouchEnd, opts);
4102 document.addEventListener('touchcancel', onTouchCancel, opts);
4103 touchListening = true;
4104}
4105
4106function removeTouchListeners ()
4107{
4108 if (!touchListening)
4109 { return; }
4110 var opts = { capture: true };
4111 document.removeEventListener('touchstart', onTouchStart, opts);
4112 document.removeEventListener('touchmove', onTouchMove, opts);
4113 document.removeEventListener('touchend', onTouchEnd, opts);
4114 document.removeEventListener('touchcancel', onTouchCancel, opts);
4115 touchListening = false;
4116}
4117
3652function bindPointer (canvas)
4118function bindPointer (canvas)
3653{
4119{
3654 unbindPointer();
4120 unbindPointer();
3655 boundCanvas = canvas;
4121 boundCanvas = canvas;
3656 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
4122 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
3657 canvas.style.touchAction = 'none';
4123 canvas.style.touchAction = 'none';
4124 canvas.style.position = 'fixed';
3658 canvas.style.cursor = 'pointer';
4125 canvas.style.cursor = 'pointer';
3659 canvas.style.webkitUserSelect = 'none';
4126 canvas.style.webkitUserSelect = 'none';
3660 canvas.style.userSelect = 'none';
4127 canvas.style.userSelect = 'none';
4128 addTouchListeners();
4129 if (app.debugDrag)
4130 { ensureDragDebugOverlay(); }
3661}
4131}
3662
4132
3663function unbindPointer ()
4133function unbindPointer ()
3664{
4134{
3665 removeWindowPointer();
4135 removeWindowPointer();
4136 removeTouchListeners();
3666 if (boundCanvas)
4137 if (boundCanvas)
3667 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
4138 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
3668 boundCanvas = null;
4139 boundCanvas = null;
3669 app.pointerId = null;
4140 app.pointerId = null;
4141 app.pointerType = null;
4142 app.activeTouchId = null;
3670}
4143}
3671
4144
3672function fieldFromEvent (e)
4145function fieldFromEvent (e)
@@ -3677,34 +4150,94 @@ function fieldFromEvent (e)
3677 var rect = canvas.getBoundingClientRect();
4150 var rect = canvas.getBoundingClientRect();
3678 if (rect.width <= 0 || rect.height <= 0)
4151 if (rect.width <= 0 || rect.height <= 0)
3679 { return null; }
4152 { return null; }
4153 var pt = eventClient(e);
4154 if (!pt)
4155 { return null; }
3680 // Map through the CSS box only. Using canvas.width / app.tile would
4156 // Map through the CSS box only. Using canvas.width / app.tile would
3681 // scale the pointer by the backing-store ratio whenever that differs
4157 // scale the pointer by the backing-store ratio whenever that differs
3682 // from the layout size (high-DPR devices), so a short finger move
4158 // from the layout size (high-DPR devices), so a short finger move
3683 // would look like a long swipe.
4159 // would look like a long swipe.
3684 var width = Planet.FIELD_WIDTH;
4160 var width = Planet.FIELD_WIDTH;
3685 var height = Planet.FIELD_HEIGHT;
4161 var height = Planet.FIELD_HEIGHT;
3686 var col = ((e.clientX - rect.left) / rect.width) * width;
4162 var col = ((pt.x - rect.left) / rect.width) * width;
3687 var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;
4163 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
3688 return { col: col, y: fieldY };
4164 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
4165}
4166
4167function playingForDrag ()
4168{
4169 return app.core && app.core.state === 'playing';
4170}
4171
4172function startDragFromEvent (e)
4173{
4174 var pos = fieldFromEvent(e);
4175 if (!pos)
4176 { return; }
4177 if (app.core.drag)
4178 {
4179 app.core.moveDrag(pos.y);
4180 logDragDebug(e, pos, 'move-already');
4181 return;
4182 }
4183 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
4184 { startPressTween(app.core.drag.blockId); }
4185 logDragDebug(e, pos, 'down');
4186}
4187
4188function moveDragFromEvent (e)
4189{
4190 if (!app.core || !app.core.drag)
4191 { return; }
4192 var pos = fieldFromEvent(e);
4193 if (pos)
4194 { app.core.moveDrag(pos.y); }
4195 logDragDebug(e, pos, 'move');
4196}
4197
4198function finishDrag (opts)
4199{
4200 opts = opts || {};
4201 app.pointerId = null;
4202 app.pointerType = null;
4203 app.activeTouchId = null;
4204 removeWindowPointer();
4205 if (boundCanvas)
4206 {
4207 try
4208 {
4209 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
4210 { boundCanvas.releasePointerCapture(opts.pointerId); }
4211 }
4212 catch (err) { /* ignore */ }
4213 }
4214 startReleaseTween();
4215 if (app.core && app.core.drag)
4216 {
4217 if (opts.noLaunch)
4218 { app.core.drag.launchIntent = false; }
4219 app.core.endDrag();
4220 }
4221 else if (app.core)
4222 { app.core.endDrag(); }
4223 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
3689}
4224}
3690
4225
3691function onPointerDown (e)
4226function onPointerDown (e)
3692{
4227{
3693 if (!app.core || app.core.state !== 'playing')
4228 if (!playingForDrag())
3694 { return; }
4229 { return; }
3695 if (app.pointerId != null)
4230 if (app.pointerId != null && e.pointerId !== app.pointerId)
3696 { return; }
4231 { return; }
3697 e.preventDefault();
4232 if (e.preventDefault)
4233 { e.preventDefault(); }
3698 app.pointerId = e.pointerId;
4234 app.pointerId = e.pointerId;
3699 try
4235 app.pointerType = e.pointerType || 'mouse';
3700 { boundCanvas.setPointerCapture(e.pointerId); }
3701 catch (err) { /* ignore */ }
3702 addWindowPointer();
4236 addWindowPointer();
3703 var pos = fieldFromEvent(e);
4237 // If a touch is already in charge, do not reset the grab from pointerdown.
3704 // Instant grab, no long-press or hold delay: the block is taken on
4238 if (app.activeTouchId != null)
3705 // pointerdown and the click tween starts in the same moment.
4239 { return; }
3706 if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
4240 startDragFromEvent(e);
3707 { startPressTween(app.core.drag.blockId); }
3708}
4241}
3709
4242
3710function onPointerMove (e)
4243function onPointerMove (e)
@@ -3713,10 +4246,20 @@ function onPointerMove (e)
3713 { return; }
4246 { return; }
3714 if (!app.core || !app.core.drag)
4247 if (!app.core || !app.core.drag)
3715 { return; }
4248 { return; }
3716 e.preventDefault();
4249 // Touch coordinates are the authority; ignore pointer moves for a
3717 var pos = fieldFromEvent(e);
4250 // live touch so a wrong clientY cannot walk the whole column.
3718 if (pos)
4251 // Only skip when touchstart has actually arrived — some environments
3719 { app.core.moveDrag(pos.y); }
4252 // deliver touch-pointer events without a TouchEvent stream.
4253 if (app.activeTouchId != null)
4254 {
4255 if (e.preventDefault)
4256 { e.preventDefault(); }
4257 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
4258 return;
4259 }
4260 if (e.preventDefault)
4261 { e.preventDefault(); }
4262 moveDragFromEvent(e);
3720}
4263}
3721
4264
3722function onPointerUp (e)
4265function onPointerUp (e)
@@ -3725,21 +4268,155 @@ function onPointerUp (e)
3725 { return; }
4268 { return; }
3726 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
4269 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
3727 { return; }
4270 { return; }
3728 if (e)
4271 if (app.activeTouchId != null)
4272 {
4273 // touchend will finish the drag.
4274 if (e && e.preventDefault)
4275 { e.preventDefault(); }
4276 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
4277 return;
4278 }
4279 if (e && e.preventDefault)
3729 { e.preventDefault(); }
4280 { e.preventDefault(); }
3730 app.pointerId = null;
4281 finishDrag({ pointerId: e && e.pointerId });
3731 removeWindowPointer();
4282}
3732 if (boundCanvas)
4283
4284function onPointerCancel (e)
4285{
4286 if (app.pointerId == null)
4287 { return; }
4288 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
4289 { return; }
4290 if (app.activeTouchId != null)
3733 {
4291 {
3734 try
4292 if (e && e.preventDefault)
3735 { boundCanvas.releasePointerCapture(e && e.pointerId); }
4293 { e.preventDefault(); }
3736 catch (err) { /* ignore */ }
4294 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
4295 return;
3737 }
4296 }
3738 startReleaseTween();
4297 if (e && e.preventDefault)
3739 if (app.core)
4298 { e.preventDefault(); }
3740 { app.core.endDrag(); }
4299 // A cancelled gesture is not a launch pull.
4300 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
4301}
4302
4303function touchById (list, id)
4304{
4305 if (!list)
4306 { return null; }
4307 for (var i = 0; i < list.length; i++)
4308 {
4309 if (list[i].identifier === id)
4310 { return list[i]; }
4311 }
4312 return null;
3741}
4313}
3742
4314
4315function onTouchStart (e)
4316{
4317 if (!playingForDrag())
4318 { return; }
4319 if (app.activeTouchId != null)
4320 {
4321 if (e.preventDefault)
4322 { e.preventDefault(); }
4323 return;
4324 }
4325 var t = e.changedTouches && e.changedTouches[0];
4326 if (!t)
4327 { return; }
4328 if (e.preventDefault)
4329 { e.preventDefault(); }
4330 app.activeTouchId = t.identifier;
4331 addWindowPointer();
4332 startDragFromEvent(e);
4333}
4334
4335function onTouchMove (e)
4336{
4337 if (app.activeTouchId == null)
4338 { return; }
4339 if (!touchById(e.changedTouches, app.activeTouchId)
4340 && !touchById(e.touches, app.activeTouchId))
4341 { return; }
4342 if (e.preventDefault)
4343 { e.preventDefault(); }
4344 moveDragFromEvent(e);
4345}
4346
4347function onTouchEnd (e)
4348{
4349 if (app.activeTouchId == null)
4350 { return; }
4351 if (!touchById(e.changedTouches, app.activeTouchId))
4352 { return; }
4353 if (e.preventDefault)
4354 { e.preventDefault(); }
4355 finishDrag({});
4356}
4357
4358function onTouchCancel (e)
4359{
4360 if (app.activeTouchId == null)
4361 { return; }
4362 if (!touchById(e.changedTouches, app.activeTouchId))
4363 { return; }
4364 if (e.preventDefault)
4365 { e.preventDefault(); }
4366 finishDrag({ noLaunch: true });
4367}
4368
4369function ensureDragDebugOverlay ()
4370{
4371 if (document.getElementById('drag-debug'))
4372 { return; }
4373 var el = document.createElement('div');
4374 el.id = 'drag-debug';
4375 el.setAttribute('aria-live', 'polite');
4376 document.body.appendChild(el);
4377}
4378
4379function logDragDebug (e, pos, phase)
4380{
4381 if (!app.debugDrag)
4382 { return; }
4383 ensureDragDebugOverlay();
4384 var el = document.getElementById('drag-debug');
4385 if (!el)
4386 { return; }
4387 var block = null;
4388 if (app.core && app.core.drag)
4389 { block = app.core.blockById(app.core.drag.blockId); }
4390 var pt = e ? eventClient(e) : null;
4391 var evType = e ? e.type : phase;
4392 var info = {
4393 phase: phase,
4394 ev: evType,
4395 src: pos && pos.src,
4396 fieldY: pos && Math.round(pos.y * 100) / 100,
4397 col: pos && Math.round(pos.col * 100) / 100,
4398 cy: pt && Math.round(pt.y * 10) / 10,
4399 blockY: block && Math.round(block.y * 100) / 100,
4400 target: block && Math.floor((pos && pos.y) + 1e-12),
4401 launch: app.core && app.core.drag && app.core.drag.launchIntent,
4402 touchId: app.activeTouchId,
4403 pid: app.pointerId,
4404 ptype: app.pointerType
4405 };
4406 lastDragDebug = info;
4407 el.textContent = 'drag ' + phase
4408 + ' ev=' + evType
4409 + ' src=' + (info.src || '-')
4410 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
4411 + ' → ' + (info.target != null ? info.target : '-')
4412 + ' block=' + (info.blockY != null ? info.blockY : '-')
4413 + (info.launch ? ' LAUNCH' : '')
4414 + ' tId=' + info.touchId
4415 + ' pId=' + info.pid;
4416 el.hidden = false;
4417}
4418
4419
3743function hideEl (id)
4420function hideEl (id)
3744{
4421{
3745 document.getElementById(id).hidden = true;
4422 document.getElementById(id).hidden = true;
build/style.css +22 −0
@@ -11,6 +11,7 @@ html, body {
11 11 color: #e8eaf2;
12 12 font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
13 13 touch-action: none;
14 overscroll-behavior: none;
14 15 -webkit-user-select: none;
15 16 user-select: none;
16 17 -webkit-tap-highlight-color: transparent;
@@ -539,3 +540,24 @@ a.button:is(:hover, :focus-visible) {
539 540 .planet-card .planet-nums { font-size: 0.68rem; }
540 541 .planet-card { padding: 10px 8px 8px; }
541 542 }
543
544 /* t1106: on-screen log for ?debug=drag */
545 #drag-debug {
546 position: fixed;
547 left: 6px;
548 right: 6px;
549 bottom: 6px;
550 z-index: 50;
551 pointer-events: none;
552 background: rgba(8, 10, 22, 0.82);
553 color: #c6f6c8;
554 font: 11px/1.35 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
555 padding: 8px 10px;
556 border-radius: 6px;
557 border: 1px solid #3a6;
558 white-space: pre-wrap;
559 word-break: break-word;
560 max-height: 28vh;
561 overflow: hidden;
562 }
563
@@ -11,6 +11,7 @@ html, body {
11 color: #e8eaf2;
11 color: #e8eaf2;
12 font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
12 font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
13 touch-action: none;
13 touch-action: none;
14 overscroll-behavior: none;
14 -webkit-user-select: none;
15 -webkit-user-select: none;
15 user-select: none;
16 user-select: none;
16 -webkit-tap-highlight-color: transparent;
17 -webkit-tap-highlight-color: transparent;
@@ -539,3 +540,24 @@ a.button:is(:hover, :focus-visible) {
539 .planet-card .planet-nums { font-size: 0.68rem; }
540 .planet-card .planet-nums { font-size: 0.68rem; }
540 .planet-card { padding: 10px 8px 8px; }
541 .planet-card { padding: 10px 8px 8px; }
541}
542}
543
544/* t1106: on-screen log for ?debug=drag */
545#drag-debug {
546 position: fixed;
547 left: 6px;
548 right: 6px;
549 bottom: 6px;
550 z-index: 50;
551 pointer-events: none;
552 background: rgba(8, 10, 22, 0.82);
553 color: #c6f6c8;
554 font: 11px/1.35 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
555 padding: 8px 10px;
556 border-radius: 6px;
557 border: 1px solid #3a6;
558 white-space: pre-wrap;
559 word-break: break-word;
560 max-height: 28vh;
561 overflow: hidden;
562}
563
docs/ASSUMPTIONS.md +116 −0
@@ -318,3 +318,119 @@ Aanname:
318 318 dus op de planeetkiezer, in de HUD en in de lobby. 0 % miss is 100 %
319 319 Power; Aurel 0 %, Terra 44 %, Cinder 92 %.
320 320
321
322 ## t1106 — touch is leidend bij een echte aanraking
323
324 - De Playwright-tests van t1104 waren circulair: ze rekenden `field_to_client`
325 met dezelfde CSS-rectformule als `fieldFromEvent`, dus ze konden de bug
326 op Tims echte telefoon niet reproduceren. Onderzoek met CDP-touch op
327 emulated Android (DPR 2,625/3), live site, URL-balk-resize, pointercancel
328 en vallende kolommen liet zien dat correcte CSS-coördinaten wél 1:1
329 blijven. De echte fout zat in de gebeurtenissen zelf.
330 - Op mobiel kan `PointerEvent.clientX/Y` tijdens een touch verkeerd zijn
331 (onder andere bij een gezoomde visual viewport), terwijl
332 `TouchEvent.changedTouches` de juiste plek houdt. Een reeks
333 `pointermove`s die naar een ander veld-Y interpoleren, liep daardoor de
334 hele kolom af — precies “één vakje slepen, blokje helemaal naar boven
335 of beneden”.
336 - Aanvullend: `preventDefault` op een PointerEvent houdt op veel mobiele
337 browsers het touch-scrollen niet tegen (daarvoor is een niet-passieve
338 `touchmove` nodig). `setPointerCapture` eindigt daar vaak in
339 `pointercancel`. `layout()` draaide elke frame en kon het canvas
340 midden in een sleep verplaatsen (URL-balk).
341 - Oplossing: zolang een echte `touchstart` is binnengekomen
342 (`app.activeTouchId`), zijn Touch Events leidend. `pointermove` /
343 `pointerup` / `pointercancel` worden dan genegeerd. Als er geen
344 TouchEvent komt (pointer-only touch, zoals sommige Playwright-paden),
345 blijven de pointer-events gewoon werken. Document-listeners voor
346 touch staan tijdens het spel op `{capture:true, passive:false}` en
347 roepen `preventDefault` aan. Geen `setPointerCapture`. `pointercancel`
348 en `touchcancel` beëindigen de sleep zonder lancering. `layout()`
349 bevriest zolang er een sleep loopt en `layoutIfNeeded` slaat over als
350 de viewport niet veranderde. Canvas heeft `touch-action:none` en
351 `position:fixed`; `html,body` hebben `overscroll-behavior: none`.
352 - Debug: `?debug=drag` of `localStorage.meteors-debug-drag=1` toont een
353 overlay (`#drag-debug`) met fase, event, bron, fieldY, doelrij, blockY,
354 launch-intent, touchId en pointerId.
355 - Regressietest: vergiftigde `pointermove`s naar fieldY 9,5 plus
356 correcte `touchmove`s naar 1,5 laten het blokje op y=1 staan, niet
357 op de top. Die test faalde op het oude pointer-only pad.
358
359 ## t1107 — slepen onder een vliegende cluster en door een gelande
360
361 - `isColumnStill` blijft streng (false zodra er iets vliegt, valt of
362 settlet in de kolom). Alleen het sleep-pad gebruikt
363 `columnAllowsDrag` (`!isColumnLocked`) en `isDraggableBlock`.
364 - Blokjes die stil of settlend op de grond staan, zijn sleepbaar, ook
365 als er in dezelfde kolom een vliegende cluster boven hangt. De
366 vliegende cluster zelf is niet sleepbaar: in Meteos speel je op de
367 grond, raketten in de lucht herschik je niet.
368 - Een gelande cluster (fase `landed`: grijze raketblokjes en gekoppeld
369 cargo, state SETTLING) is wél sleepbaar, zolang de kolom een
370 aaneengesloten stapel is (geen gat). `swapToward` stopt bij een gat.
371 Hangende leden (SETTLING telt als grounded) horen bij de stapel-top.
372 - Van plaats wisselen *binnen* dezelfde gelande cluster verandert alleen
373 de posities. Een blokje *uit* de cluster wisselen haalt het eruit:
374 een grijs blokje blijft settlen op zijn eigen resterende timer en
375 recolored alleen; gekleurd cargo wordt STILL als het steun heeft,
376 anders FALLING. Een blokje *in* de cluster wisselen krijgt dat
377 `clusterId`, wordt SETTLING en `flame` uit. Een grijs blokje dat
378 instapt met `settleTime` 0 kan de groeps-release vertragen tot zijn
379 eigen 3 s om is. Lidmaatschap wordt pas ná de join van de ander
380 gewist, zodat `leaveCluster` een nog niet-lege cluster niet verwijdert.
381 - `startManualLaunch` roept eerst `leaveCluster` aan, zodat een gooien
382 vanuit een gelande groep het blokje losmaakt.
383
384 ## t1108 — een gegooid blokje botst met vallende blokjes
385
386 - Een handmatig omhoog gegooid blokje (state MANUAL) botst met vallende
387 blokjes op dezelfde manier als twee vliegende clusters: ze smelten
388 samen tot één vliegende cluster. Snelheid, vertraging en spronghoogte
389 zijn het massagemiddelde per blokje (zelfde regel als
390 `mergeClusterGroup`). Een stapel aaneengesloten vallende blokjes
391 gaat in één keer mee.
392 - Ze kunnen elkaar in één substep niet kruisen: zowel `integrateManual`
393 als `integrateFalling` kijken naar het hele pad van die stap
394 (swept overlap) en mergen vóór de posities elkaar passeren.
395 `packClusterOverlaps` legt ze naast elkaar.
396 - De cluster krijgt `fromManual: true`. Vallend cargo dat daarna op
397 zo'n cluster landt, wordt óók middeled (niet alleen “meegepakt” met
398 de clustersnelheid). Gewone match-raketten houden de oude regel:
399 cargo neemt `cluster.vy` over, zonder middelen. Dat pad is
400 onveranderd.
401 - De spronghoogte van de worp wordt bij lancering bewaard als
402 `manualJumpHeight`, zodat de merge die kan middelen.
403
404 ## t1109 — pakken per rooster-cel, niet per sprite
405
406 - Hit-testing keek naar de afstand tot de simulatie-rechthoek van het
407 blokje, met een drempel. Visueel staan sprites vaak iets naar binnen
408 (padding, bounce, scale, tween), en de speler moest precies op de
409 getekende sprite drukken.
410 - Nu: de druk wordt een cel `floor(col)`, `floor(y)`. Elke druk binnen
411 die cel — hoeken, kieren tussen sprites, een visueel verschoven
412 sprite — pakt het blokje dat die cel inneemt. Dat gebruikt
413 simulatiecellen, niet de getekende bounds (tweens blijven view-only).
414 - Staat er geen blokje in die cel (midden in een animatie, y niet
415 geheel), dan de dichtstbijzijnde sleepbare in dezelfde kolom binnen
416 een halve tegel (`SNAP_Y = 0,5`). Alleen als de primaire cel leeg is
417 en de druk dicht bij de rand zit, geldt nog een kleine horizontale
418 slop naar de buurkolom. Lanceren-door-optrekken blijft.
419
420 ## t1110 — match na landing van een cluster, en grotere vlammen
421
422 - Als een vliegende cluster landt en samen met al liggende blokjes een
423 geldige rij vormt (3 of meer dezelfde kleur, horizontaal of
424 verticaal), telt dat als een match en worden het raketten.
425 - Aanname: grijze raketblokjes hebben geen kleur en doen niet mee aan
426 een match zolang ze grijs zijn. Gekleurd cargo in de gelande cluster
427 (SETTLING) is wél matchbaar, meteen bij de landing, ook in een
428 gemengde rij met al stilliggende blokjes. Zodra de grijze blokjes
429 recoloren en de groep wordt losgelaten, geldt hetzelfde voor die
430 nieuwe kleuren: een gemengde rij met rustende buren lanceert in
431 dezelfde tick.
432 - `findMatchLines` neemt daarom STILL én SETTLING mee, zolang
433 `color >= 0`. Grijze SETTLING (geen kleur) blijft uitgesloten.
434 - De vlam onder raketten is 3× zo groot, in lengte én breedte
435 (`0,85 × 3` tegels). De bovenkant van de vlam blijft op dezelfde
436 overlap in het blokje; de extra lengte steekt naar beneden uit.
@@ -318,3 +318,119 @@ Aanname:
318 dus op de planeetkiezer, in de HUD en in de lobby. 0 % miss is 100 %
318 dus op de planeetkiezer, in de HUD en in de lobby. 0 % miss is 100 %
319 Power; Aurel 0 %, Terra 44 %, Cinder 92 %.
319 Power; Aurel 0 %, Terra 44 %, Cinder 92 %.
320
320
321
322## t1106 — touch is leidend bij een echte aanraking
323
324- De Playwright-tests van t1104 waren circulair: ze rekenden `field_to_client`
325 met dezelfde CSS-rectformule als `fieldFromEvent`, dus ze konden de bug
326 op Tims echte telefoon niet reproduceren. Onderzoek met CDP-touch op
327 emulated Android (DPR 2,625/3), live site, URL-balk-resize, pointercancel
328 en vallende kolommen liet zien dat correcte CSS-coördinaten wél 1:1
329 blijven. De echte fout zat in de gebeurtenissen zelf.
330- Op mobiel kan `PointerEvent.clientX/Y` tijdens een touch verkeerd zijn
331 (onder andere bij een gezoomde visual viewport), terwijl
332 `TouchEvent.changedTouches` de juiste plek houdt. Een reeks
333 `pointermove`s die naar een ander veld-Y interpoleren, liep daardoor de
334 hele kolom af — precies “één vakje slepen, blokje helemaal naar boven
335 of beneden”.
336- Aanvullend: `preventDefault` op een PointerEvent houdt op veel mobiele
337 browsers het touch-scrollen niet tegen (daarvoor is een niet-passieve
338 `touchmove` nodig). `setPointerCapture` eindigt daar vaak in
339 `pointercancel`. `layout()` draaide elke frame en kon het canvas
340 midden in een sleep verplaatsen (URL-balk).
341- Oplossing: zolang een echte `touchstart` is binnengekomen
342 (`app.activeTouchId`), zijn Touch Events leidend. `pointermove` /
343 `pointerup` / `pointercancel` worden dan genegeerd. Als er geen
344 TouchEvent komt (pointer-only touch, zoals sommige Playwright-paden),
345 blijven de pointer-events gewoon werken. Document-listeners voor
346 touch staan tijdens het spel op `{capture:true, passive:false}` en
347 roepen `preventDefault` aan. Geen `setPointerCapture`. `pointercancel`
348 en `touchcancel` beëindigen de sleep zonder lancering. `layout()`
349 bevriest zolang er een sleep loopt en `layoutIfNeeded` slaat over als
350 de viewport niet veranderde. Canvas heeft `touch-action:none` en
351 `position:fixed`; `html,body` hebben `overscroll-behavior: none`.
352- Debug: `?debug=drag` of `localStorage.meteors-debug-drag=1` toont een
353 overlay (`#drag-debug`) met fase, event, bron, fieldY, doelrij, blockY,
354 launch-intent, touchId en pointerId.
355- Regressietest: vergiftigde `pointermove`s naar fieldY 9,5 plus
356 correcte `touchmove`s naar 1,5 laten het blokje op y=1 staan, niet
357 op de top. Die test faalde op het oude pointer-only pad.
358
359## t1107 — slepen onder een vliegende cluster en door een gelande
360
361- `isColumnStill` blijft streng (false zodra er iets vliegt, valt of
362 settlet in de kolom). Alleen het sleep-pad gebruikt
363 `columnAllowsDrag` (`!isColumnLocked`) en `isDraggableBlock`.
364- Blokjes die stil of settlend op de grond staan, zijn sleepbaar, ook
365 als er in dezelfde kolom een vliegende cluster boven hangt. De
366 vliegende cluster zelf is niet sleepbaar: in Meteos speel je op de
367 grond, raketten in de lucht herschik je niet.
368- Een gelande cluster (fase `landed`: grijze raketblokjes en gekoppeld
369 cargo, state SETTLING) is wél sleepbaar, zolang de kolom een
370 aaneengesloten stapel is (geen gat). `swapToward` stopt bij een gat.
371 Hangende leden (SETTLING telt als grounded) horen bij de stapel-top.
372- Van plaats wisselen *binnen* dezelfde gelande cluster verandert alleen
373 de posities. Een blokje *uit* de cluster wisselen haalt het eruit:
374 een grijs blokje blijft settlen op zijn eigen resterende timer en
375 recolored alleen; gekleurd cargo wordt STILL als het steun heeft,
376 anders FALLING. Een blokje *in* de cluster wisselen krijgt dat
377 `clusterId`, wordt SETTLING en `flame` uit. Een grijs blokje dat
378 instapt met `settleTime` 0 kan de groeps-release vertragen tot zijn
379 eigen 3 s om is. Lidmaatschap wordt pas ná de join van de ander
380 gewist, zodat `leaveCluster` een nog niet-lege cluster niet verwijdert.
381- `startManualLaunch` roept eerst `leaveCluster` aan, zodat een gooien
382 vanuit een gelande groep het blokje losmaakt.
383
384## t1108 — een gegooid blokje botst met vallende blokjes
385
386- Een handmatig omhoog gegooid blokje (state MANUAL) botst met vallende
387 blokjes op dezelfde manier als twee vliegende clusters: ze smelten
388 samen tot één vliegende cluster. Snelheid, vertraging en spronghoogte
389 zijn het massagemiddelde per blokje (zelfde regel als
390 `mergeClusterGroup`). Een stapel aaneengesloten vallende blokjes
391 gaat in één keer mee.
392- Ze kunnen elkaar in één substep niet kruisen: zowel `integrateManual`
393 als `integrateFalling` kijken naar het hele pad van die stap
394 (swept overlap) en mergen vóór de posities elkaar passeren.
395 `packClusterOverlaps` legt ze naast elkaar.
396- De cluster krijgt `fromManual: true`. Vallend cargo dat daarna op
397 zo'n cluster landt, wordt óók middeled (niet alleen “meegepakt” met
398 de clustersnelheid). Gewone match-raketten houden de oude regel:
399 cargo neemt `cluster.vy` over, zonder middelen. Dat pad is
400 onveranderd.
401- De spronghoogte van de worp wordt bij lancering bewaard als
402 `manualJumpHeight`, zodat de merge die kan middelen.
403
404## t1109 — pakken per rooster-cel, niet per sprite
405
406- Hit-testing keek naar de afstand tot de simulatie-rechthoek van het
407 blokje, met een drempel. Visueel staan sprites vaak iets naar binnen
408 (padding, bounce, scale, tween), en de speler moest precies op de
409 getekende sprite drukken.
410- Nu: de druk wordt een cel `floor(col)`, `floor(y)`. Elke druk binnen
411 die cel — hoeken, kieren tussen sprites, een visueel verschoven
412 sprite — pakt het blokje dat die cel inneemt. Dat gebruikt
413 simulatiecellen, niet de getekende bounds (tweens blijven view-only).
414- Staat er geen blokje in die cel (midden in een animatie, y niet
415 geheel), dan de dichtstbijzijnde sleepbare in dezelfde kolom binnen
416 een halve tegel (`SNAP_Y = 0,5`). Alleen als de primaire cel leeg is
417 en de druk dicht bij de rand zit, geldt nog een kleine horizontale
418 slop naar de buurkolom. Lanceren-door-optrekken blijft.
419
420## t1110 — match na landing van een cluster, en grotere vlammen
421
422- Als een vliegende cluster landt en samen met al liggende blokjes een
423 geldige rij vormt (3 of meer dezelfde kleur, horizontaal of
424 verticaal), telt dat als een match en worden het raketten.
425- Aanname: grijze raketblokjes hebben geen kleur en doen niet mee aan
426 een match zolang ze grijs zijn. Gekleurd cargo in de gelande cluster
427 (SETTLING) is wél matchbaar, meteen bij de landing, ook in een
428 gemengde rij met al stilliggende blokjes. Zodra de grijze blokjes
429 recoloren en de groep wordt losgelaten, geldt hetzelfde voor die
430 nieuwe kleuren: een gemengde rij met rustende buren lanceert in
431 dezelfde tick.
432- `findMatchLines` neemt daarom STILL én SETTLING mee, zolang
433 `color >= 0`. Grijze SETTLING (geen kleur) blijft uitgesloten.
434- De vlam onder raketten is 3× zo groot, in lengte én breedte
435 (`0,85 × 3` tegels). De bovenkant van de vlam blijft op dezelfde
436 overlap in het blokje; de extra lengte steekt naar beneden uit.
src/gameCore.js +403 −34
@@ -27,8 +27,8 @@ var LAUNCH_PULL = 0.35;
27 27 // Minimal accumulated vertical pointer travel (tiles) to swap one step.
28 28 // No hold delay: the first swap fires as soon as this distance is reached.
29 29 var SWAP_DISTANCE = 0.25;
30 // Grab a still block if the pointer is at most this far (tiles) from it.
31 var SNAP_Y = 0.65;
30 // Fallback snap (tiles) when the press cell is empty: nearest block in the column.
31 var SNAP_Y = 0.5;
32 32 // Horizontal slop (tiles) for snapping to a neighbouring column on press.
33 33 var HORIZONTAL_SLOP = 0.35;
34 34
@@ -432,12 +432,29 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)
432 432 if (other.y + 1 > roof)
433 433 { roof = other.y + 1; }
434 434 }
435 var oldN = this.clusterMembers(cluster.id).length;
436 var fallingVy = block.vy;
435 437 block.y = roof;
436 438 block.state = STATE_FLYING;
437 439 block.clusterId = cluster.id;
438 block.vy = cluster.vy;
439 440 block.flame = false;
440 441 block.settleTime = 0;
442 // A cluster born from a thrown block averages in falling cargo
443 // the same way two flying clusters merge (t1108). Other rockets
444 // keep their velocity and just pick the cargo up.
445 if (cluster.fromManual)
446 {
447 var newN = oldN + 1;
448 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
449 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
450 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
451 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
452 var members = this.clusterMembers(cluster.id);
453 for (var m = 0; m < members.length; m++)
454 { members[m].vy = cluster.vy; }
455 }
456 else
457 { block.vy = cluster.vy; }
441 458 return true;
442 459 };
443 460
@@ -500,6 +517,7 @@ GameCore.prototype.tick = function (dt)
500 517 this.integrateClusters(step);
501 518 this.mergeFlyingClusters();
502 519 this.integrateManual(step);
520 this.mergeAnyManualFallingOverlaps();
503 521 this.cullOffTop();
504 522 left -= step;
505 523 }
@@ -581,6 +599,12 @@ GameCore.prototype.integrateFalling = function (dt)
581 599 { continue; }
582 600 this.accelerateFall(block, dt);
583 601 var nextY = block.y + block.vy * dt;
602 var manual = this.manualInColumnHit(block, block.y, nextY);
603 if (manual)
604 {
605 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
606 continue;
607 }
584 608 var flyer = this.highestFlyingBelow(block);
585 609 if (flyer && nextY <= flyer.y + 1 + 1e-9)
586 610 {
@@ -981,6 +1005,8 @@ GameCore.prototype.integrateManual = function (dt)
981 1005 block.vy = proxy.vy;
982 1006 block.manualPhase = proxy.phase;
983 1007 block.y = Math.min(nextY, block.manualTarget);
1008 if (this.tryMergeManualWithFalling(block, oldY, block.y))
1009 { continue; }
984 1010 if (block.y >= block.manualTarget - 1e-12)
985 1011 {
986 1012 block.y = block.manualTarget;
@@ -1014,11 +1040,207 @@ GameCore.prototype.integrateManual = function (dt)
1014 1040 else
1015 1041 {
1016 1042 block.y = Math.min(nextY, this.height - 1);
1043 if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))
1044 { continue; }
1017 1045 }
1018 1046 }
1019 1047 }
1020 1048 };
1021 1049
1050 /**
1051 * If the manual throw (or its path this step) hits falling blocks, merge
1052 * them into a flying cluster with mass-weighted velocity, the same rule
1053 * as two flying clusters colliding (t1108). Returns true if merged.
1054 */
1055 GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
1056 {
1057 if (!manual || manual.state !== STATE_MANUAL)
1058 { return false; }
1059 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
1060 if (!hits.length)
1061 { return false; }
1062 this.mergeManualWithFalling(manual, hits);
1063 return true;
1064 };
1065
1066 GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
1067 {
1068 var lo = Math.min(oldY, newY);
1069 var hi = Math.max(oldY, newY) + 1;
1070 for (var i = 0; i < this.blocks.length; i++)
1071 {
1072 var other = this.blocks[i];
1073 if (other === falling || other.col !== falling.col)
1074 { continue; }
1075 if (other.state !== STATE_MANUAL)
1076 { continue; }
1077 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1078 { return other; }
1079 }
1080 return null;
1081 };
1082
1083 GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
1084 {
1085 var lo = Math.min(oldY, newY);
1086 var hi = Math.max(oldY, newY) + 1;
1087 var hits = [];
1088 for (var i = 0; i < this.blocks.length; i++)
1089 {
1090 var other = this.blocks[i];
1091 if (other === manual || other.col !== manual.col)
1092 { continue; }
1093 if (other.state !== STATE_FALLING)
1094 { continue; }
1095 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1096 { hits.push(other); }
1097 }
1098 if (!hits.length)
1099 { return hits; }
1100 return this.contiguousFallingInColumn(manual.col, manual, hits);
1101 };
1102
1103 /**
1104 * Every falling block in `col` that overlaps `anchor` or a hit already
1105 * in `seed`, plus a contiguous falling stack sitting on them.
1106 */
1107 GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
1108 {
1109 var falling = [];
1110 for (var i = 0; i < this.blocks.length; i++)
1111 {
1112 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
1113 { falling.push(this.blocks[i]); }
1114 }
1115 falling.sort(function (a, b) { return a.y - b.y; });
1116 var include = Object.create(null);
1117 var queue = [];
1118 function enqueue (b)
1119 {
1120 if (!b || include[b.id])
1121 { return; }
1122 include[b.id] = true;
1123 queue.push(b);
1124 }
1125 if (seed)
1126 {
1127 for (var s = 0; s < seed.length; s++)
1128 { enqueue(seed[s]); }
1129 }
1130 // Also include falling that already overlap the anchor.
1131 if (anchor)
1132 {
1133 for (var i = 0; i < falling.length; i++)
1134 {
1135 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
1136 { enqueue(falling[i]); }
1137 }
1138 }
1139 for (var q = 0; q < queue.length; q++)
1140 {
1141 var a = queue[q];
1142 for (var i = 0; i < falling.length; i++)
1143 {
1144 var b = falling[i];
1145 if (include[b.id])
1146 { continue; }
1147 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
1148 { enqueue(b); }
1149 }
1150 }
1151 var out = [];
1152 for (var i = 0; i < falling.length; i++)
1153 {
1154 if (include[falling[i].id])
1155 { out.push(falling[i]); }
1156 }
1157 return out;
1158 };
1159
1160 /**
1161 * Merge a thrown (manual) block with falling blocks into one flying
1162 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
1163 * averages by block count, identical to mergeClusterGroup. The thrown
1164 * block stops being manual and the group follows normal cluster physics.
1165 * fromManual marks the cluster so later falling cargo also averages in.
1166 */
1167 GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1168 {
1169 if (!manual || manual.state !== STATE_MANUAL)
1170 { return null; }
1171 var blocks = [manual];
1172 for (var i = 0; i < fallingList.length; i++)
1173 {
1174 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
1175 { blocks.push(fallingList[i]); }
1176 }
1177 if (blocks.length < 2)
1178 { return null; }
1179 var n = blocks.length;
1180 var vySum = 0;
1181 var decelSum = 0;
1182 var hSum = 0;
1183 for (var i = 0; i < n; i++)
1184 {
1185 var b = blocks[i];
1186 vySum += b.vy;
1187 if (b === manual)
1188 {
1189 decelSum += manual.manualDecel || 0;
1190 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
1191 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
1192 }
1193 }
1194 var cluster = {
1195 id: this.nextClusterId++,
1196 jumpHeight: hSum / n,
1197 vy: vySum / n,
1198 decel: decelSum / n,
1199 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
1200 fromManual: true
1201 };
1202 this.clusters[cluster.id] = cluster;
1203 for (var i = 0; i < n; i++)
1204 {
1205 var b = blocks[i];
1206 b.clusterId = cluster.id;
1207 b.state = STATE_FLYING;
1208 b.vy = cluster.vy;
1209 b.flame = b.color === COLOR_GRAY;
1210 b.manualPhase = null;
1211 b.manualTarget = null;
1212 b.manualDecel = 0;
1213 b.manualJumpHeight = 0;
1214 b.pushedClusters = null;
1215 b.settleTime = 0;
1216 }
1217 if (this.drag && this.drag.blockId === manual.id)
1218 { this.drag = null; }
1219 this.packClusterOverlaps(cluster);
1220 this.checkChainRelaunch(cluster);
1221 return cluster;
1222 };
1223
1224 /** Safety net: any remaining manual/falling overlaps after the substep. */
1225 GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1226 {
1227 var manuals = [];
1228 for (var i = 0; i < this.blocks.length; i++)
1229 {
1230 if (this.blocks[i].state === STATE_MANUAL)
1231 { manuals.push(this.blocks[i]); }
1232 }
1233 for (var m = 0; m < manuals.length; m++)
1234 {
1235 var manual = manuals[m];
1236 if (manual.state !== STATE_MANUAL)
1237 { continue; }
1238 var hits = this.contiguousFallingInColumn(manual.col, manual);
1239 if (hits.length)
1240 { this.mergeManualWithFalling(manual, hits); }
1241 }
1242 };
1243
1022 1244 GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1023 1245 {
1024 1246 if (!manual.pushedClusters)
@@ -1150,10 +1372,12 @@ GameCore.prototype.startManualLaunch = function (block)
1150 1372 {
1151 1373 var target = this.height - 1;
1152 1374 var height = Math.max(0.05, target - block.y);
1375 this.leaveCluster(block);
1153 1376 block.state = STATE_MANUAL;
1154 1377 block.pushedClusters = Object.create(null);
1155 1378 block.manualTarget = target;
1156 1379 block.manualPhase = 'up';
1380 block.manualJumpHeight = height;
1157 1381 block.vy = PlanetMod.launchVelocity(this.planet, height);
1158 1382 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
1159 1383 block.flame = false;
@@ -1327,7 +1551,11 @@ GameCore.prototype.findMatchLines = function ()
1327 1551 for (var i = 0; i < this.blocks.length; i++)
1328 1552 {
1329 1553 var block = this.blocks[i];
1330 if (block.state === STATE_STILL && block.color >= 0)
1554 // Coloured cargo in a just-landed cluster (SETTLING) can match
1555 // with already-resting blocks immediately (t1110). Greys have no
1556 // colour and wait until they recolor; after release they are STILL.
1557 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
1558 && block.color >= 0)
1331 1559 { candidates.push(block); }
1332 1560 }
1333 1561 return this.collectLines(candidates, true);
@@ -1637,48 +1865,103 @@ GameCore.prototype.beginDrag = function (col, y)
1637 1865 };
1638 1866
1639 1867 /**
1640 * Instant grab: the nearest still, coloured block to (col, y), allowing
1641 * a small vertical miss and a horizontal slop into a neighbouring
1642 * column. `col` may be fractional (pointer x in tiles). No hold delay.
1868 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
1869 * floor(col), floor(y); any press inside that cell — corners, padding,
1870 * gaps between sprites, a visually tweened or bouncing sprite — grabs
1871 * the block that occupies it. This uses simulation cells, not the drawn
1872 * sprite bounds. If no block sits in that cell (mid-animation, a block
1873 * whose y is off the integer), fall back to the nearest grabbable block
1874 * in the same column within SNAP_Y (about half a tile). A small
1875 * horizontal slop still consults a neighbouring column when the press
1876 * is near the edge and the primary cell is empty.
1643 1877 */
1644 1878 GameCore.prototype.snapDragBlock = function (col, y)
1645 1879 {
1646 1880 var raw = col;
1647 1881 var c0 = Math.floor(raw + 1e-9);
1882 var row = Math.floor(y + 1e-9);
1648 1883 var frac = raw - c0;
1649 var candidates = [];
1650 if (c0 >= 0 && c0 < this.width)
1651 { candidates.push(c0); }
1652 // Only consult a neighbour when the pointer is actually near the edge
1653 // (a whole-number col, as in unit tests, stays in that column).
1884
1885 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
1886 {
1887 var exact = this.draggableInCell(c0, row);
1888 if (exact)
1889 { return exact; }
1890 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
1891 if (near)
1892 { return near; }
1893 }
1894
1895 // Primary cell empty: allow a small horizontal slop into a neighbour.
1896 var neighbours = [];
1654 1897 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
1655 { candidates.push(c0 - 1); }
1898 { neighbours.push(c0 - 1); }
1656 1899 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
1657 { candidates.push(c0 + 1); }
1900 { neighbours.push(c0 + 1); }
1901 var best = null;
1902 var bestDist = Infinity;
1903 for (var n = 0; n < neighbours.length; n++)
1904 {
1905 var cc = neighbours[n];
1906 if (!this.columnAllowsDrag(cc))
1907 { continue; }
1908 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
1909 if (!hit)
1910 { continue; }
1911 var dist = this.pointerDistToBlock(hit, raw, y);
1912 if (dist < bestDist)
1913 {
1914 bestDist = dist;
1915 best = hit;
1916 }
1917 }
1918 return best;
1919 };
1920
1921 /** The draggable block that occupies grid cell (col, row), if any. */
1922 GameCore.prototype.draggableInCell = function (col, row)
1923 {
1924 var best = null;
1925 var bestOverlap = 0;
1926 var list = this.blocksInColumn(col);
1927 for (var i = 0; i < list.length; i++)
1928 {
1929 var block = list[i];
1930 if (!this.isDraggableBlock(block))
1931 { continue; }
1932 var lo = Math.max(block.y, row);
1933 var hi = Math.min(block.y + 1, row + 1);
1934 var overlap = hi - lo;
1935 if (overlap > bestOverlap + 1e-12)
1936 {
1937 bestOverlap = overlap;
1938 best = block;
1939 }
1940 }
1941 if (best && bestOverlap > 1e-9)
1942 { return best; }
1943 return null;
1944 };
1658 1945
1946 /** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
1947 GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
1948 {
1659 1949 var best = null;
1660 1950 var bestDist = Infinity;
1661 for (var c = 0; c < candidates.length; c++)
1951 var list = this.blocksInColumn(col);
1952 for (var i = 0; i < list.length; i++)
1662 1953 {
1663 var cc = candidates[c];
1664 if (!this.isColumnStill(cc))
1954 var block = list[i];
1955 if (!this.isDraggableBlock(block))
1665 1956 { continue; }
1666 var list = this.blocksInColumn(cc);
1667 for (var i = 0; i < list.length; i++)
1957 var dist = this.pointerDistToBlock(block, col + 0.5, y);
1958 if (dist < bestDist)
1668 1959 {
1669 var block = list[i];
1670 if (block.state !== STATE_STILL || block.color < 0)
1671 { continue; }
1672 var dist = this.pointerDistToBlock(block, raw, y);
1673 // Prefer the column the pointer is actually in on a tie.
1674 if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))
1675 {
1676 bestDist = dist;
1677 best = block;
1678 }
1960 bestDist = dist;
1961 best = block;
1679 1962 }
1680 1963 }
1681 if (!best || bestDist > SNAP_Y)
1964 if (!best || bestDist > maxDist)
1682 1965 { return null; }
1683 1966 return best;
1684 1967 };
@@ -1707,12 +1990,12 @@ GameCore.prototype.moveDrag = function (y)
1707 1990 if (!this.drag)
1708 1991 { return; }
1709 1992 var block = this.blockById(this.drag.blockId);
1710 if (!block || block.state !== STATE_STILL)
1993 if (!block || !this.isDraggableBlock(block))
1711 1994 {
1712 1995 this.drag = null;
1713 1996 return;
1714 1997 }
1715 if (!this.isColumnStill(block.col))
1998 if (!this.columnAllowsDrag(block.col))
1716 1999 {
1717 2000 this.drag = null;
1718 2001 return;
@@ -1842,15 +2125,101 @@ GameCore.prototype.swapBlocks = function (a, b)
1842 2125 var y = a.y;
1843 2126 a.y = b.y;
1844 2127 b.y = y;
2128 this.transferLandedMembership(a, b);
2129 };
2130
2131 /**
2132 * A landed cluster (grey rockets or linked cargo resting on the ground)
2133 * is a swappable part of the contiguous grounded stack. Flying, falling
2134 * and manual blocks are not. A locked column is not.
2135 */
2136 GameCore.prototype.isDraggableBlock = function (block)
2137 {
2138 if (!block)
2139 { return false; }
2140 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
2141 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
2142 { return false; }
2143 if (block.clusterId != null)
2144 {
2145 var cluster = this.clusters[block.clusterId];
2146 // Flying (rising / descending) clusters stay non-draggable.
2147 if (cluster && cluster.phase !== 'landed')
2148 { return false; }
2149 }
2150 return block.state === STATE_STILL || block.state === STATE_SETTLING;
2151 };
2152
2153 /**
2154 * The grounded contiguous stack in this column can be dragged, even if a
2155 * flying cluster or a falling spawn occupies the air above it. Only a
2156 * locked column is blocked as a whole.
2157 */
2158 GameCore.prototype.columnAllowsDrag = function (col)
2159 {
2160 return !this.isColumnLocked(col);
2161 };
2162
2163 GameCore.prototype.landedClusterId = function (block)
2164 {
2165 if (!block || block.clusterId == null)
2166 { return null; }
2167 var cluster = this.clusters[block.clusterId];
2168 if (!cluster || cluster.phase !== 'landed')
2169 { return null; }
2170 return block.clusterId;
2171 };
2172
2173 /**
2174 * After a swap: leaving a landed cluster clears membership; joining one
2175 * makes the block part of that rigid group. Same-cluster swaps only
2176 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
2177 */
2178 GameCore.prototype.transferLandedMembership = function (a, b)
2179 {
2180 var ca = this.landedClusterId(a);
2181 var cb = this.landedClusterId(b);
2182 if (ca === cb)
2183 { return; }
2184 // Join first so leaveCluster does not delete a cluster that still
2185 // has the incoming member.
2186 this.applyLandedMembership(b, ca);
2187 this.applyLandedMembership(a, cb);
2188 };
2189
2190 GameCore.prototype.applyLandedMembership = function (block, clusterId)
2191 {
2192 if (clusterId == null)
2193 {
2194 var wasGrey = block.color === COLOR_GRAY;
2195 var wasSettling = block.state === STATE_SETTLING;
2196 this.leaveCluster(block);
2197 if (wasGrey && wasSettling)
2198 {
2199 // Keep settling and recolor on its own, same remaining timer.
2200 block.state = STATE_SETTLING;
2201 }
2202 else if (wasSettling)
2203 {
2204 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2205 }
2206 return;
2207 }
2208 if (!this.clusters[clusterId])
2209 { return; }
2210 block.clusterId = clusterId;
2211 block.flame = false;
2212 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
2213 { block.state = STATE_SETTLING; }
1845 2214 };
1846 2215
1847 2216 /**
1848 2217 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
1849 * Returns the moved block, or null if the column is not still.
2218 * Returns the moved block, or null if the column does not allow a drag.
1850 2219 */
1851 2220 GameCore.prototype.swapTo = function (col, fromRow, toRow)
1852 2221 {
1853 if (!this.isColumnStill(col))
2222 if (!this.columnAllowsDrag(col))
1854 2223 { return null; }
1855 2224 var block = this.blockAt(col, fromRow);
1856 2225 if (!block)
@@ -27,8 +27,8 @@ var LAUNCH_PULL = 0.35;
27// Minimal accumulated vertical pointer travel (tiles) to swap one step.
27// Minimal accumulated vertical pointer travel (tiles) to swap one step.
28// No hold delay: the first swap fires as soon as this distance is reached.
28// No hold delay: the first swap fires as soon as this distance is reached.
29var SWAP_DISTANCE = 0.25;
29var SWAP_DISTANCE = 0.25;
30// Grab a still block if the pointer is at most this far (tiles) from it.
30// Fallback snap (tiles) when the press cell is empty: nearest block in the column.
31var SNAP_Y = 0.65;
31var SNAP_Y = 0.5;
32// Horizontal slop (tiles) for snapping to a neighbouring column on press.
32// Horizontal slop (tiles) for snapping to a neighbouring column on press.
33var HORIZONTAL_SLOP = 0.35;
33var HORIZONTAL_SLOP = 0.35;
34
34
@@ -432,12 +432,29 @@ GameCore.prototype.attachToFlyingCluster = function (block, flyer)
432 if (other.y + 1 > roof)
432 if (other.y + 1 > roof)
433 { roof = other.y + 1; }
433 { roof = other.y + 1; }
434 }
434 }
435 var oldN = this.clusterMembers(cluster.id).length;
436 var fallingVy = block.vy;
435 block.y = roof;
437 block.y = roof;
436 block.state = STATE_FLYING;
438 block.state = STATE_FLYING;
437 block.clusterId = cluster.id;
439 block.clusterId = cluster.id;
438 block.vy = cluster.vy;
439 block.flame = false;
440 block.flame = false;
440 block.settleTime = 0;
441 block.settleTime = 0;
442 // A cluster born from a thrown block averages in falling cargo
443 // the same way two flying clusters merge (t1108). Other rockets
444 // keep their velocity and just pick the cargo up.
445 if (cluster.fromManual)
446 {
447 var newN = oldN + 1;
448 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
449 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
450 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
451 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
452 var members = this.clusterMembers(cluster.id);
453 for (var m = 0; m < members.length; m++)
454 { members[m].vy = cluster.vy; }
455 }
456 else
457 { block.vy = cluster.vy; }
441 return true;
458 return true;
442};
459};
443
460
@@ -500,6 +517,7 @@ GameCore.prototype.tick = function (dt)
500 this.integrateClusters(step);
517 this.integrateClusters(step);
501 this.mergeFlyingClusters();
518 this.mergeFlyingClusters();
502 this.integrateManual(step);
519 this.integrateManual(step);
520 this.mergeAnyManualFallingOverlaps();
503 this.cullOffTop();
521 this.cullOffTop();
504 left -= step;
522 left -= step;
505 }
523 }
@@ -581,6 +599,12 @@ GameCore.prototype.integrateFalling = function (dt)
581 { continue; }
599 { continue; }
582 this.accelerateFall(block, dt);
600 this.accelerateFall(block, dt);
583 var nextY = block.y + block.vy * dt;
601 var nextY = block.y + block.vy * dt;
602 var manual = this.manualInColumnHit(block, block.y, nextY);
603 if (manual)
604 {
605 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
606 continue;
607 }
584 var flyer = this.highestFlyingBelow(block);
608 var flyer = this.highestFlyingBelow(block);
585 if (flyer && nextY <= flyer.y + 1 + 1e-9)
609 if (flyer && nextY <= flyer.y + 1 + 1e-9)
586 {
610 {
@@ -981,6 +1005,8 @@ GameCore.prototype.integrateManual = function (dt)
981 block.vy = proxy.vy;
1005 block.vy = proxy.vy;
982 block.manualPhase = proxy.phase;
1006 block.manualPhase = proxy.phase;
983 block.y = Math.min(nextY, block.manualTarget);
1007 block.y = Math.min(nextY, block.manualTarget);
1008 if (this.tryMergeManualWithFalling(block, oldY, block.y))
1009 { continue; }
984 if (block.y >= block.manualTarget - 1e-12)
1010 if (block.y >= block.manualTarget - 1e-12)
985 {
1011 {
986 block.y = block.manualTarget;
1012 block.y = block.manualTarget;
@@ -1014,11 +1040,207 @@ GameCore.prototype.integrateManual = function (dt)
1014 else
1040 else
1015 {
1041 {
1016 block.y = Math.min(nextY, this.height - 1);
1042 block.y = Math.min(nextY, this.height - 1);
1043 if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))
1044 { continue; }
1017 }
1045 }
1018 }
1046 }
1019 }
1047 }
1020};
1048};
1021
1049
1050/**
1051 * If the manual throw (or its path this step) hits falling blocks, merge
1052 * them into a flying cluster with mass-weighted velocity, the same rule
1053 * as two flying clusters colliding (t1108). Returns true if merged.
1054 */
1055GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
1056{
1057 if (!manual || manual.state !== STATE_MANUAL)
1058 { return false; }
1059 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
1060 if (!hits.length)
1061 { return false; }
1062 this.mergeManualWithFalling(manual, hits);
1063 return true;
1064};
1065
1066GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
1067{
1068 var lo = Math.min(oldY, newY);
1069 var hi = Math.max(oldY, newY) + 1;
1070 for (var i = 0; i < this.blocks.length; i++)
1071 {
1072 var other = this.blocks[i];
1073 if (other === falling || other.col !== falling.col)
1074 { continue; }
1075 if (other.state !== STATE_MANUAL)
1076 { continue; }
1077 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1078 { return other; }
1079 }
1080 return null;
1081};
1082
1083GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
1084{
1085 var lo = Math.min(oldY, newY);
1086 var hi = Math.max(oldY, newY) + 1;
1087 var hits = [];
1088 for (var i = 0; i < this.blocks.length; i++)
1089 {
1090 var other = this.blocks[i];
1091 if (other === manual || other.col !== manual.col)
1092 { continue; }
1093 if (other.state !== STATE_FALLING)
1094 { continue; }
1095 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1096 { hits.push(other); }
1097 }
1098 if (!hits.length)
1099 { return hits; }
1100 return this.contiguousFallingInColumn(manual.col, manual, hits);
1101};
1102
1103/**
1104 * Every falling block in `col` that overlaps `anchor` or a hit already
1105 * in `seed`, plus a contiguous falling stack sitting on them.
1106 */
1107GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
1108{
1109 var falling = [];
1110 for (var i = 0; i < this.blocks.length; i++)
1111 {
1112 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
1113 { falling.push(this.blocks[i]); }
1114 }
1115 falling.sort(function (a, b) { return a.y - b.y; });
1116 var include = Object.create(null);
1117 var queue = [];
1118 function enqueue (b)
1119 {
1120 if (!b || include[b.id])
1121 { return; }
1122 include[b.id] = true;
1123 queue.push(b);
1124 }
1125 if (seed)
1126 {
1127 for (var s = 0; s < seed.length; s++)
1128 { enqueue(seed[s]); }
1129 }
1130 // Also include falling that already overlap the anchor.
1131 if (anchor)
1132 {
1133 for (var i = 0; i < falling.length; i++)
1134 {
1135 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
1136 { enqueue(falling[i]); }
1137 }
1138 }
1139 for (var q = 0; q < queue.length; q++)
1140 {
1141 var a = queue[q];
1142 for (var i = 0; i < falling.length; i++)
1143 {
1144 var b = falling[i];
1145 if (include[b.id])
1146 { continue; }
1147 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
1148 { enqueue(b); }
1149 }
1150 }
1151 var out = [];
1152 for (var i = 0; i < falling.length; i++)
1153 {
1154 if (include[falling[i].id])
1155 { out.push(falling[i]); }
1156 }
1157 return out;
1158};
1159
1160/**
1161 * Merge a thrown (manual) block with falling blocks into one flying
1162 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
1163 * averages by block count, identical to mergeClusterGroup. The thrown
1164 * block stops being manual and the group follows normal cluster physics.
1165 * fromManual marks the cluster so later falling cargo also averages in.
1166 */
1167GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1168{
1169 if (!manual || manual.state !== STATE_MANUAL)
1170 { return null; }
1171 var blocks = [manual];
1172 for (var i = 0; i < fallingList.length; i++)
1173 {
1174 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
1175 { blocks.push(fallingList[i]); }
1176 }
1177 if (blocks.length < 2)
1178 { return null; }
1179 var n = blocks.length;
1180 var vySum = 0;
1181 var decelSum = 0;
1182 var hSum = 0;
1183 for (var i = 0; i < n; i++)
1184 {
1185 var b = blocks[i];
1186 vySum += b.vy;
1187 if (b === manual)
1188 {
1189 decelSum += manual.manualDecel || 0;
1190 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
1191 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
1192 }
1193 }
1194 var cluster = {
1195 id: this.nextClusterId++,
1196 jumpHeight: hSum / n,
1197 vy: vySum / n,
1198 decel: decelSum / n,
1199 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
1200 fromManual: true
1201 };
1202 this.clusters[cluster.id] = cluster;
1203 for (var i = 0; i < n; i++)
1204 {
1205 var b = blocks[i];
1206 b.clusterId = cluster.id;
1207 b.state = STATE_FLYING;
1208 b.vy = cluster.vy;
1209 b.flame = b.color === COLOR_GRAY;
1210 b.manualPhase = null;
1211 b.manualTarget = null;
1212 b.manualDecel = 0;
1213 b.manualJumpHeight = 0;
1214 b.pushedClusters = null;
1215 b.settleTime = 0;
1216 }
1217 if (this.drag && this.drag.blockId === manual.id)
1218 { this.drag = null; }
1219 this.packClusterOverlaps(cluster);
1220 this.checkChainRelaunch(cluster);
1221 return cluster;
1222};
1223
1224/** Safety net: any remaining manual/falling overlaps after the substep. */
1225GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1226{
1227 var manuals = [];
1228 for (var i = 0; i < this.blocks.length; i++)
1229 {
1230 if (this.blocks[i].state === STATE_MANUAL)
1231 { manuals.push(this.blocks[i]); }
1232 }
1233 for (var m = 0; m < manuals.length; m++)
1234 {
1235 var manual = manuals[m];
1236 if (manual.state !== STATE_MANUAL)
1237 { continue; }
1238 var hits = this.contiguousFallingInColumn(manual.col, manual);
1239 if (hits.length)
1240 { this.mergeManualWithFalling(manual, hits); }
1241 }
1242};
1243
1022GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1244GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1023{
1245{
1024 if (!manual.pushedClusters)
1246 if (!manual.pushedClusters)
@@ -1150,10 +1372,12 @@ GameCore.prototype.startManualLaunch = function (block)
1150{
1372{
1151 var target = this.height - 1;
1373 var target = this.height - 1;
1152 var height = Math.max(0.05, target - block.y);
1374 var height = Math.max(0.05, target - block.y);
1375 this.leaveCluster(block);
1153 block.state = STATE_MANUAL;
1376 block.state = STATE_MANUAL;
1154 block.pushedClusters = Object.create(null);
1377 block.pushedClusters = Object.create(null);
1155 block.manualTarget = target;
1378 block.manualTarget = target;
1156 block.manualPhase = 'up';
1379 block.manualPhase = 'up';
1380 block.manualJumpHeight = height;
1157 block.vy = PlanetMod.launchVelocity(this.planet, height);
1381 block.vy = PlanetMod.launchVelocity(this.planet, height);
1158 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
1382 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
1159 block.flame = false;
1383 block.flame = false;
@@ -1327,7 +1551,11 @@ GameCore.prototype.findMatchLines = function ()
1327 for (var i = 0; i < this.blocks.length; i++)
1551 for (var i = 0; i < this.blocks.length; i++)
1328 {
1552 {
1329 var block = this.blocks[i];
1553 var block = this.blocks[i];
1330 if (block.state === STATE_STILL && block.color >= 0)
1554 // Coloured cargo in a just-landed cluster (SETTLING) can match
1555 // with already-resting blocks immediately (t1110). Greys have no
1556 // colour and wait until they recolor; after release they are STILL.
1557 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
1558 && block.color >= 0)
1331 { candidates.push(block); }
1559 { candidates.push(block); }
1332 }
1560 }
1333 return this.collectLines(candidates, true);
1561 return this.collectLines(candidates, true);
@@ -1637,48 +1865,103 @@ GameCore.prototype.beginDrag = function (col, y)
1637};
1865};
1638
1866
1639/**
1867/**
1640 * Instant grab: the nearest still, coloured block to (col, y), allowing
1868 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
1641 * a small vertical miss and a horizontal slop into a neighbouring
1869 * floor(col), floor(y); any press inside that cell — corners, padding,
1642 * column. `col` may be fractional (pointer x in tiles). No hold delay.
1870 * gaps between sprites, a visually tweened or bouncing sprite — grabs
1871 * the block that occupies it. This uses simulation cells, not the drawn
1872 * sprite bounds. If no block sits in that cell (mid-animation, a block
1873 * whose y is off the integer), fall back to the nearest grabbable block
1874 * in the same column within SNAP_Y (about half a tile). A small
1875 * horizontal slop still consults a neighbouring column when the press
1876 * is near the edge and the primary cell is empty.
1643 */
1877 */
1644GameCore.prototype.snapDragBlock = function (col, y)
1878GameCore.prototype.snapDragBlock = function (col, y)
1645{
1879{
1646 var raw = col;
1880 var raw = col;
1647 var c0 = Math.floor(raw + 1e-9);
1881 var c0 = Math.floor(raw + 1e-9);
1882 var row = Math.floor(y + 1e-9);
1648 var frac = raw - c0;
1883 var frac = raw - c0;
1649 var candidates = [];
1884
1650 if (c0 >= 0 && c0 < this.width)
1885 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
1651 { candidates.push(c0); }
1886 {
1652 // Only consult a neighbour when the pointer is actually near the edge
1887 var exact = this.draggableInCell(c0, row);
1653 // (a whole-number col, as in unit tests, stays in that column).
1888 if (exact)
1889 { return exact; }
1890 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
1891 if (near)
1892 { return near; }
1893 }
1894
1895 // Primary cell empty: allow a small horizontal slop into a neighbour.
1896 var neighbours = [];
1654 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
1897 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
1655 { candidates.push(c0 - 1); }
1898 { neighbours.push(c0 - 1); }
1656 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
1899 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
1657 { candidates.push(c0 + 1); }
1900 { neighbours.push(c0 + 1); }
1901 var best = null;
1902 var bestDist = Infinity;
1903 for (var n = 0; n < neighbours.length; n++)
1904 {
1905 var cc = neighbours[n];
1906 if (!this.columnAllowsDrag(cc))
1907 { continue; }
1908 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
1909 if (!hit)
1910 { continue; }
1911 var dist = this.pointerDistToBlock(hit, raw, y);
1912 if (dist < bestDist)
1913 {
1914 bestDist = dist;
1915 best = hit;
1916 }
1917 }
1918 return best;
1919};
1920
1921/** The draggable block that occupies grid cell (col, row), if any. */
1922GameCore.prototype.draggableInCell = function (col, row)
1923{
1924 var best = null;
1925 var bestOverlap = 0;
1926 var list = this.blocksInColumn(col);
1927 for (var i = 0; i < list.length; i++)
1928 {
1929 var block = list[i];
1930 if (!this.isDraggableBlock(block))
1931 { continue; }
1932 var lo = Math.max(block.y, row);
1933 var hi = Math.min(block.y + 1, row + 1);
1934 var overlap = hi - lo;
1935 if (overlap > bestOverlap + 1e-12)
1936 {
1937 bestOverlap = overlap;
1938 best = block;
1939 }
1940 }
1941 if (best && bestOverlap > 1e-9)
1942 { return best; }
1943 return null;
1944};
1658
1945
1946/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
1947GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
1948{
1659 var best = null;
1949 var best = null;
1660 var bestDist = Infinity;
1950 var bestDist = Infinity;
1661 for (var c = 0; c < candidates.length; c++)
1951 var list = this.blocksInColumn(col);
1952 for (var i = 0; i < list.length; i++)
1662 {
1953 {
1663 var cc = candidates[c];
1954 var block = list[i];
1664 if (!this.isColumnStill(cc))
1955 if (!this.isDraggableBlock(block))
1665 { continue; }
1956 { continue; }
1666 var list = this.blocksInColumn(cc);
1957 var dist = this.pointerDistToBlock(block, col + 0.5, y);
1667 for (var i = 0; i < list.length; i++)
1958 if (dist < bestDist)
1668 {
1959 {
1669 var block = list[i];
1960 bestDist = dist;
1670 if (block.state !== STATE_STILL || block.color < 0)
1961 best = block;
1671 { continue; }
1672 var dist = this.pointerDistToBlock(block, raw, y);
1673 // Prefer the column the pointer is actually in on a tie.
1674 if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))
1675 {
1676 bestDist = dist;
1677 best = block;
1678 }
1679 }
1962 }
1680 }
1963 }
1681 if (!best || bestDist > SNAP_Y)
1964 if (!best || bestDist > maxDist)
1682 { return null; }
1965 { return null; }
1683 return best;
1966 return best;
1684};
1967};
@@ -1707,12 +1990,12 @@ GameCore.prototype.moveDrag = function (y)
1707 if (!this.drag)
1990 if (!this.drag)
1708 { return; }
1991 { return; }
1709 var block = this.blockById(this.drag.blockId);
1992 var block = this.blockById(this.drag.blockId);
1710 if (!block || block.state !== STATE_STILL)
1993 if (!block || !this.isDraggableBlock(block))
1711 {
1994 {
1712 this.drag = null;
1995 this.drag = null;
1713 return;
1996 return;
1714 }
1997 }
1715 if (!this.isColumnStill(block.col))
1998 if (!this.columnAllowsDrag(block.col))
1716 {
1999 {
1717 this.drag = null;
2000 this.drag = null;
1718 return;
2001 return;
@@ -1842,15 +2125,101 @@ GameCore.prototype.swapBlocks = function (a, b)
1842 var y = a.y;
2125 var y = a.y;
1843 a.y = b.y;
2126 a.y = b.y;
1844 b.y = y;
2127 b.y = y;
2128 this.transferLandedMembership(a, b);
2129};
2130
2131/**
2132 * A landed cluster (grey rockets or linked cargo resting on the ground)
2133 * is a swappable part of the contiguous grounded stack. Flying, falling
2134 * and manual blocks are not. A locked column is not.
2135 */
2136GameCore.prototype.isDraggableBlock = function (block)
2137{
2138 if (!block)
2139 { return false; }
2140 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
2141 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
2142 { return false; }
2143 if (block.clusterId != null)
2144 {
2145 var cluster = this.clusters[block.clusterId];
2146 // Flying (rising / descending) clusters stay non-draggable.
2147 if (cluster && cluster.phase !== 'landed')
2148 { return false; }
2149 }
2150 return block.state === STATE_STILL || block.state === STATE_SETTLING;
2151};
2152
2153/**
2154 * The grounded contiguous stack in this column can be dragged, even if a
2155 * flying cluster or a falling spawn occupies the air above it. Only a
2156 * locked column is blocked as a whole.
2157 */
2158GameCore.prototype.columnAllowsDrag = function (col)
2159{
2160 return !this.isColumnLocked(col);
2161};
2162
2163GameCore.prototype.landedClusterId = function (block)
2164{
2165 if (!block || block.clusterId == null)
2166 { return null; }
2167 var cluster = this.clusters[block.clusterId];
2168 if (!cluster || cluster.phase !== 'landed')
2169 { return null; }
2170 return block.clusterId;
2171};
2172
2173/**
2174 * After a swap: leaving a landed cluster clears membership; joining one
2175 * makes the block part of that rigid group. Same-cluster swaps only
2176 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
2177 */
2178GameCore.prototype.transferLandedMembership = function (a, b)
2179{
2180 var ca = this.landedClusterId(a);
2181 var cb = this.landedClusterId(b);
2182 if (ca === cb)
2183 { return; }
2184 // Join first so leaveCluster does not delete a cluster that still
2185 // has the incoming member.
2186 this.applyLandedMembership(b, ca);
2187 this.applyLandedMembership(a, cb);
2188};
2189
2190GameCore.prototype.applyLandedMembership = function (block, clusterId)
2191{
2192 if (clusterId == null)
2193 {
2194 var wasGrey = block.color === COLOR_GRAY;
2195 var wasSettling = block.state === STATE_SETTLING;
2196 this.leaveCluster(block);
2197 if (wasGrey && wasSettling)
2198 {
2199 // Keep settling and recolor on its own, same remaining timer.
2200 block.state = STATE_SETTLING;
2201 }
2202 else if (wasSettling)
2203 {
2204 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2205 }
2206 return;
2207 }
2208 if (!this.clusters[clusterId])
2209 { return; }
2210 block.clusterId = clusterId;
2211 block.flame = false;
2212 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
2213 { block.state = STATE_SETTLING; }
1845};
2214};
1846
2215
1847/**
2216/**
1848 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
2217 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
1849 * Returns the moved block, or null if the column is not still.
2218 * Returns the moved block, or null if the column does not allow a drag.
1850 */
2219 */
1851GameCore.prototype.swapTo = function (col, fromRow, toRow)
2220GameCore.prototype.swapTo = function (col, fromRow, toRow)
1852{
2221{
1853 if (!this.isColumnStill(col))
2222 if (!this.columnAllowsDrag(col))
1854 { return null; }
2223 { return null; }
1855 var block = this.blockAt(col, fromRow);
2224 var block = this.blockAt(col, fromRow);
1856 if (!block)
2225 if (!block)
src/main.js +346 −38
@@ -58,6 +58,9 @@ var app = {
58 58 flames: Object.create(null),
59 59 cells: [],
60 60 pointerId: null,
61 pointerType: null,
62 activeTouchId: null,
63 debugDrag: false,
61 64 gameOverShown: false,
62 65 selectTween: null,
63 66 online: false,
@@ -70,6 +73,7 @@ var app = {
70 73
71 74 window.onload = function ()
72 75 {
76 app.debugDrag = isDragDebugEnabled();
73 77 var play = document.getElementById('btn-play');
74 78 play.addEventListener('click', onPlay);
75 79 play.addEventListener('pointerup', function (e)
@@ -222,10 +226,25 @@ function placeTile (obj, col, y)
222 226 obj.transform.size = { x: t, y: t };
223 227 }
224 228
229 function layoutIfNeeded ()
230 {
231 if (app.core && app.core.drag)
232 { return; }
233 var vw = window.innerWidth || 320;
234 var vh = window.innerHeight || 480;
235 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
236 { return; }
237 layout();
238 }
239
225 240 function layout ()
226 241 {
242 if (app.core && app.core.drag)
243 { return; }
227 244 var vw = window.innerWidth || 320;
228 245 var vh = window.innerHeight || 480;
246 app._layoutVw = vw;
247 app._layoutVh = vh;
229 248 var safeTop = 0;
230 249 try
231 250 {
@@ -309,9 +328,16 @@ function syncSprites ()
309 328 }
310 329 flame.renderer.visible = true;
311 330 var t = app.tile;
331 // 3x as large (length and width, t1110). Keep the top of the
332 // flame at the same overlap into the block so the extra length
333 // extends downward under the rocket.
334 var flameW = t * 0.85 * 3;
335 var flameH = t * 0.85 * 3;
336 var origCenter = app.fieldH - block.y * t + t * 0.15;
337 var origTop = origCenter - (t * 0.85) / 2;
312 338 flame.transform.position.x = block.col * t + t / 2;
313 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
314 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
339 flame.transform.position.y = origTop + flameH / 2;
340 flame.transform.size = { x: flameW, y: flameH };
315 341 }
316 342 else if (app.flames[block.id])
317 343 { app.flames[block.id].renderer.visible = false; }
@@ -451,7 +477,11 @@ function tickView (dt)
451 477 if (app.mode !== 'playing' || !app.core)
452 478 { return; }
453 479
454 layout();
480 // Never resize the canvas mid-drag: a URL-bar hide would move the
481 // field under the finger and jump the target row. Also skip work
482 // when the viewport has not actually changed.
483 if (!(app.core && app.core.drag))
484 { layoutIfNeeded(); }
455 485 for (var i = 0; i < app.cells.length; i++)
456 486 {
457 487 var col = i % 10;
@@ -481,15 +511,58 @@ function tickView (dt)
481 511
482 512 /* ---------- pointer input (mouse + touch) --------------------------- */
483 513 /*
484 * Both mouse and touch use Pointer Events. After pointerdown we listen
485 * on window, so a drag that leaves the canvas (needed to launch a
486 * block at the top of a full column) still reaches moveDrag. We do
487 * not treat lostpointercapture as the end of a drag: on some touch
488 * browsers that fires mid-gesture and would cancel a launch.
514 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
515 * on a real phone, pointer clientX/Y can disagree with the visual
516 * finger (zoomed visual viewport, gesture takeover, capture cancel)
517 * while changedTouches stays correct. When a touch is active, pointer
518 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
519 * walk the block to the top or bottom of the stack (t1106).
520 *
521 * After a down we also listen on the document, so a drag that leaves
522 * the canvas (needed to launch a block at the top of a full column)
523 * still reaches moveDrag. We do not call setPointerCapture: on mobile
524 * that is often cancelled when the browser takes the gesture, which
525 * would fire pointercancel mid-drag.
526 *
527 * A non-passive document touchstart/touchmove preventDefault during
528 * play stops scrolling, rubber-banding and the pointercancel that
529 * follows. pointercancel / touchcancel end the drag without launch.
530 *
531 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
489 532 */
490 533
491 534 var boundCanvas = null;
492 535 var windowListening = false;
536 var touchListening = false;
537 var lastDragDebug = null;
538
539 function isDragDebugEnabled ()
540 {
541 try
542 {
543 var q = window.location && window.location.search;
544 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
545 { return true; }
546 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
547 { return true; }
548 }
549 catch (err) { /* ignore */ }
550 return false;
551 }
552
553 function eventClient (e)
554 {
555 var t = null;
556 if (e.changedTouches && e.changedTouches.length)
557 { t = e.changedTouches[0]; }
558 else if (e.touches && e.touches.length)
559 { t = e.touches[0]; }
560 if (t)
561 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
562 if (e.clientX != null && e.clientY != null)
563 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
564 return null;
565 }
493 566
494 567 function addWindowPointer ()
495 568 {
@@ -497,7 +570,7 @@ function addWindowPointer ()
497 570 { return; }
498 571 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
499 572 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
500 window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });
573 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
501 574 windowListening = true;
502 575 }
503 576
@@ -507,28 +580,59 @@ function removeWindowPointer ()
507 580 { return; }
508 581 window.removeEventListener('pointermove', onPointerMove, { capture: true });
509 582 window.removeEventListener('pointerup', onPointerUp, { capture: true });
510 window.removeEventListener('pointercancel', onPointerUp, { capture: true });
583 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
511 584 windowListening = false;
512 585 }
513 586
587 function addTouchListeners ()
588 {
589 if (touchListening)
590 { return; }
591 var opts = { capture: true, passive: false };
592 document.addEventListener('touchstart', onTouchStart, opts);
593 document.addEventListener('touchmove', onTouchMove, opts);
594 document.addEventListener('touchend', onTouchEnd, opts);
595 document.addEventListener('touchcancel', onTouchCancel, opts);
596 touchListening = true;
597 }
598
599 function removeTouchListeners ()
600 {
601 if (!touchListening)
602 { return; }
603 var opts = { capture: true };
604 document.removeEventListener('touchstart', onTouchStart, opts);
605 document.removeEventListener('touchmove', onTouchMove, opts);
606 document.removeEventListener('touchend', onTouchEnd, opts);
607 document.removeEventListener('touchcancel', onTouchCancel, opts);
608 touchListening = false;
609 }
610
514 611 function bindPointer (canvas)
515 612 {
516 613 unbindPointer();
517 614 boundCanvas = canvas;
518 615 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
519 616 canvas.style.touchAction = 'none';
617 canvas.style.position = 'fixed';
520 618 canvas.style.cursor = 'pointer';
521 619 canvas.style.webkitUserSelect = 'none';
522 620 canvas.style.userSelect = 'none';
621 addTouchListeners();
622 if (app.debugDrag)
623 { ensureDragDebugOverlay(); }
523 624 }
524 625
525 626 function unbindPointer ()
526 627 {
527 628 removeWindowPointer();
629 removeTouchListeners();
528 630 if (boundCanvas)
529 631 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
530 632 boundCanvas = null;
531 633 app.pointerId = null;
634 app.pointerType = null;
635 app.activeTouchId = null;
532 636 }
533 637
534 638 function fieldFromEvent (e)
@@ -539,34 +643,94 @@ function fieldFromEvent (e)
539 643 var rect = canvas.getBoundingClientRect();
540 644 if (rect.width <= 0 || rect.height <= 0)
541 645 { return null; }
646 var pt = eventClient(e);
647 if (!pt)
648 { return null; }
542 649 // Map through the CSS box only. Using canvas.width / app.tile would
543 650 // scale the pointer by the backing-store ratio whenever that differs
544 651 // from the layout size (high-DPR devices), so a short finger move
545 652 // would look like a long swipe.
546 653 var width = Planet.FIELD_WIDTH;
547 654 var height = Planet.FIELD_HEIGHT;
548 var col = ((e.clientX - rect.left) / rect.width) * width;
549 var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;
550 return { col: col, y: fieldY };
655 var col = ((pt.x - rect.left) / rect.width) * width;
656 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
657 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
658 }
659
660 function playingForDrag ()
661 {
662 return app.core && app.core.state === 'playing';
663 }
664
665 function startDragFromEvent (e)
666 {
667 var pos = fieldFromEvent(e);
668 if (!pos)
669 { return; }
670 if (app.core.drag)
671 {
672 app.core.moveDrag(pos.y);
673 logDragDebug(e, pos, 'move-already');
674 return;
675 }
676 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
677 { startPressTween(app.core.drag.blockId); }
678 logDragDebug(e, pos, 'down');
679 }
680
681 function moveDragFromEvent (e)
682 {
683 if (!app.core || !app.core.drag)
684 { return; }
685 var pos = fieldFromEvent(e);
686 if (pos)
687 { app.core.moveDrag(pos.y); }
688 logDragDebug(e, pos, 'move');
689 }
690
691 function finishDrag (opts)
692 {
693 opts = opts || {};
694 app.pointerId = null;
695 app.pointerType = null;
696 app.activeTouchId = null;
697 removeWindowPointer();
698 if (boundCanvas)
699 {
700 try
701 {
702 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
703 { boundCanvas.releasePointerCapture(opts.pointerId); }
704 }
705 catch (err) { /* ignore */ }
706 }
707 startReleaseTween();
708 if (app.core && app.core.drag)
709 {
710 if (opts.noLaunch)
711 { app.core.drag.launchIntent = false; }
712 app.core.endDrag();
713 }
714 else if (app.core)
715 { app.core.endDrag(); }
716 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
551 717 }
552 718
553 719 function onPointerDown (e)
554 720 {
555 if (!app.core || app.core.state !== 'playing')
721 if (!playingForDrag())
556 722 { return; }
557 if (app.pointerId != null)
723 if (app.pointerId != null && e.pointerId !== app.pointerId)
558 724 { return; }
559 e.preventDefault();
725 if (e.preventDefault)
726 { e.preventDefault(); }
560 727 app.pointerId = e.pointerId;
561 try
562 { boundCanvas.setPointerCapture(e.pointerId); }
563 catch (err) { /* ignore */ }
728 app.pointerType = e.pointerType || 'mouse';
564 729 addWindowPointer();
565 var pos = fieldFromEvent(e);
566 // Instant grab, no long-press or hold delay: the block is taken on
567 // pointerdown and the click tween starts in the same moment.
568 if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
569 { startPressTween(app.core.drag.blockId); }
730 // If a touch is already in charge, do not reset the grab from pointerdown.
731 if (app.activeTouchId != null)
732 { return; }
733 startDragFromEvent(e);
570 734 }
571 735
572 736 function onPointerMove (e)
@@ -575,10 +739,20 @@ function onPointerMove (e)
575 739 { return; }
576 740 if (!app.core || !app.core.drag)
577 741 { return; }
578 e.preventDefault();
579 var pos = fieldFromEvent(e);
580 if (pos)
581 { app.core.moveDrag(pos.y); }
742 // Touch coordinates are the authority; ignore pointer moves for a
743 // live touch so a wrong clientY cannot walk the whole column.
744 // Only skip when touchstart has actually arrived — some environments
745 // deliver touch-pointer events without a TouchEvent stream.
746 if (app.activeTouchId != null)
747 {
748 if (e.preventDefault)
749 { e.preventDefault(); }
750 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
751 return;
752 }
753 if (e.preventDefault)
754 { e.preventDefault(); }
755 moveDragFromEvent(e);
582 756 }
583 757
584 758 function onPointerUp (e)
@@ -587,21 +761,155 @@ function onPointerUp (e)
587 761 { return; }
588 762 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
589 763 { return; }
590 if (e)
764 if (app.activeTouchId != null)
765 {
766 // touchend will finish the drag.
767 if (e && e.preventDefault)
768 { e.preventDefault(); }
769 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
770 return;
771 }
772 if (e && e.preventDefault)
591 773 { e.preventDefault(); }
592 app.pointerId = null;
593 removeWindowPointer();
594 if (boundCanvas)
774 finishDrag({ pointerId: e && e.pointerId });
775 }
776
777 function onPointerCancel (e)
778 {
779 if (app.pointerId == null)
780 { return; }
781 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
782 { return; }
783 if (app.activeTouchId != null)
595 784 {
596 try
597 { boundCanvas.releasePointerCapture(e && e.pointerId); }
598 catch (err) { /* ignore */ }
785 if (e && e.preventDefault)
786 { e.preventDefault(); }
787 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
788 return;
599 789 }
600 startReleaseTween();
601 if (app.core)
602 { app.core.endDrag(); }
790 if (e && e.preventDefault)
791 { e.preventDefault(); }
792 // A cancelled gesture is not a launch pull.
793 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
794 }
795
796 function touchById (list, id)
797 {
798 if (!list)
799 { return null; }
800 for (var i = 0; i < list.length; i++)
801 {
802 if (list[i].identifier === id)
803 { return list[i]; }
804 }
805 return null;
603 806 }
604 807
808 function onTouchStart (e)
809 {
810 if (!playingForDrag())
811 { return; }
812 if (app.activeTouchId != null)
813 {
814 if (e.preventDefault)
815 { e.preventDefault(); }
816 return;
817 }
818 var t = e.changedTouches && e.changedTouches[0];
819 if (!t)
820 { return; }
821 if (e.preventDefault)
822 { e.preventDefault(); }
823 app.activeTouchId = t.identifier;
824 addWindowPointer();
825 startDragFromEvent(e);
826 }
827
828 function onTouchMove (e)
829 {
830 if (app.activeTouchId == null)
831 { return; }
832 if (!touchById(e.changedTouches, app.activeTouchId)
833 && !touchById(e.touches, app.activeTouchId))
834 { return; }
835 if (e.preventDefault)
836 { e.preventDefault(); }
837 moveDragFromEvent(e);
838 }
839
840 function onTouchEnd (e)
841 {
842 if (app.activeTouchId == null)
843 { return; }
844 if (!touchById(e.changedTouches, app.activeTouchId))
845 { return; }
846 if (e.preventDefault)
847 { e.preventDefault(); }
848 finishDrag({});
849 }
850
851 function onTouchCancel (e)
852 {
853 if (app.activeTouchId == null)
854 { return; }
855 if (!touchById(e.changedTouches, app.activeTouchId))
856 { return; }
857 if (e.preventDefault)
858 { e.preventDefault(); }
859 finishDrag({ noLaunch: true });
860 }
861
862 function ensureDragDebugOverlay ()
863 {
864 if (document.getElementById('drag-debug'))
865 { return; }
866 var el = document.createElement('div');
867 el.id = 'drag-debug';
868 el.setAttribute('aria-live', 'polite');
869 document.body.appendChild(el);
870 }
871
872 function logDragDebug (e, pos, phase)
873 {
874 if (!app.debugDrag)
875 { return; }
876 ensureDragDebugOverlay();
877 var el = document.getElementById('drag-debug');
878 if (!el)
879 { return; }
880 var block = null;
881 if (app.core && app.core.drag)
882 { block = app.core.blockById(app.core.drag.blockId); }
883 var pt = e ? eventClient(e) : null;
884 var evType = e ? e.type : phase;
885 var info = {
886 phase: phase,
887 ev: evType,
888 src: pos && pos.src,
889 fieldY: pos && Math.round(pos.y * 100) / 100,
890 col: pos && Math.round(pos.col * 100) / 100,
891 cy: pt && Math.round(pt.y * 10) / 10,
892 blockY: block && Math.round(block.y * 100) / 100,
893 target: block && Math.floor((pos && pos.y) + 1e-12),
894 launch: app.core && app.core.drag && app.core.drag.launchIntent,
895 touchId: app.activeTouchId,
896 pid: app.pointerId,
897 ptype: app.pointerType
898 };
899 lastDragDebug = info;
900 el.textContent = 'drag ' + phase
901 + ' ev=' + evType
902 + ' src=' + (info.src || '-')
903 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
904 + ' → ' + (info.target != null ? info.target : '-')
905 + ' block=' + (info.blockY != null ? info.blockY : '-')
906 + (info.launch ? ' LAUNCH' : '')
907 + ' tId=' + info.touchId
908 + ' pId=' + info.pid;
909 el.hidden = false;
910 }
911
912
605 913 function hideEl (id)
606 914 {
607 915 document.getElementById(id).hidden = true;
@@ -58,6 +58,9 @@ var app = {
58 flames: Object.create(null),
58 flames: Object.create(null),
59 cells: [],
59 cells: [],
60 pointerId: null,
60 pointerId: null,
61 pointerType: null,
62 activeTouchId: null,
63 debugDrag: false,
61 gameOverShown: false,
64 gameOverShown: false,
62 selectTween: null,
65 selectTween: null,
63 online: false,
66 online: false,
@@ -70,6 +73,7 @@ var app = {
70
73
71window.onload = function ()
74window.onload = function ()
72{
75{
76 app.debugDrag = isDragDebugEnabled();
73 var play = document.getElementById('btn-play');
77 var play = document.getElementById('btn-play');
74 play.addEventListener('click', onPlay);
78 play.addEventListener('click', onPlay);
75 play.addEventListener('pointerup', function (e)
79 play.addEventListener('pointerup', function (e)
@@ -222,10 +226,25 @@ function placeTile (obj, col, y)
222 obj.transform.size = { x: t, y: t };
226 obj.transform.size = { x: t, y: t };
223}
227}
224
228
229function layoutIfNeeded ()
230{
231 if (app.core && app.core.drag)
232 { return; }
233 var vw = window.innerWidth || 320;
234 var vh = window.innerHeight || 480;
235 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
236 { return; }
237 layout();
238}
239
225function layout ()
240function layout ()
226{
241{
242 if (app.core && app.core.drag)
243 { return; }
227 var vw = window.innerWidth || 320;
244 var vw = window.innerWidth || 320;
228 var vh = window.innerHeight || 480;
245 var vh = window.innerHeight || 480;
246 app._layoutVw = vw;
247 app._layoutVh = vh;
229 var safeTop = 0;
248 var safeTop = 0;
230 try
249 try
231 {
250 {
@@ -309,9 +328,16 @@ function syncSprites ()
309 }
328 }
310 flame.renderer.visible = true;
329 flame.renderer.visible = true;
311 var t = app.tile;
330 var t = app.tile;
331 // 3x as large (length and width, t1110). Keep the top of the
332 // flame at the same overlap into the block so the extra length
333 // extends downward under the rocket.
334 var flameW = t * 0.85 * 3;
335 var flameH = t * 0.85 * 3;
336 var origCenter = app.fieldH - block.y * t + t * 0.15;
337 var origTop = origCenter - (t * 0.85) / 2;
312 flame.transform.position.x = block.col * t + t / 2;
338 flame.transform.position.x = block.col * t + t / 2;
313 flame.transform.position.y = app.fieldH - block.y * t + t * 0.15;
339 flame.transform.position.y = origTop + flameH / 2;
314 flame.transform.size = { x: t * 0.85, y: t * 0.85 };
340 flame.transform.size = { x: flameW, y: flameH };
315 }
341 }
316 else if (app.flames[block.id])
342 else if (app.flames[block.id])
317 { app.flames[block.id].renderer.visible = false; }
343 { app.flames[block.id].renderer.visible = false; }
@@ -451,7 +477,11 @@ function tickView (dt)
451 if (app.mode !== 'playing' || !app.core)
477 if (app.mode !== 'playing' || !app.core)
452 { return; }
478 { return; }
453
479
454 layout();
480 // Never resize the canvas mid-drag: a URL-bar hide would move the
481 // field under the finger and jump the target row. Also skip work
482 // when the viewport has not actually changed.
483 if (!(app.core && app.core.drag))
484 { layoutIfNeeded(); }
455 for (var i = 0; i < app.cells.length; i++)
485 for (var i = 0; i < app.cells.length; i++)
456 {
486 {
457 var col = i % 10;
487 var col = i % 10;
@@ -481,15 +511,58 @@ function tickView (dt)
481
511
482/* ---------- pointer input (mouse + touch) --------------------------- */
512/* ---------- pointer input (mouse + touch) --------------------------- */
483/*
513/*
484 * Both mouse and touch use Pointer Events. After pointerdown we listen
514 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
485 * on window, so a drag that leaves the canvas (needed to launch a
515 * on a real phone, pointer clientX/Y can disagree with the visual
486 * block at the top of a full column) still reaches moveDrag. We do
516 * finger (zoomed visual viewport, gesture takeover, capture cancel)
487 * not treat lostpointercapture as the end of a drag: on some touch
517 * while changedTouches stays correct. When a touch is active, pointer
488 * browsers that fires mid-gesture and would cancel a launch.
518 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
519 * walk the block to the top or bottom of the stack (t1106).
520 *
521 * After a down we also listen on the document, so a drag that leaves
522 * the canvas (needed to launch a block at the top of a full column)
523 * still reaches moveDrag. We do not call setPointerCapture: on mobile
524 * that is often cancelled when the browser takes the gesture, which
525 * would fire pointercancel mid-drag.
526 *
527 * A non-passive document touchstart/touchmove preventDefault during
528 * play stops scrolling, rubber-banding and the pointercancel that
529 * follows. pointercancel / touchcancel end the drag without launch.
530 *
531 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
489 */
532 */
490
533
491var boundCanvas = null;
534var boundCanvas = null;
492var windowListening = false;
535var windowListening = false;
536var touchListening = false;
537var lastDragDebug = null;
538
539function isDragDebugEnabled ()
540{
541 try
542 {
543 var q = window.location && window.location.search;
544 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
545 { return true; }
546 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
547 { return true; }
548 }
549 catch (err) { /* ignore */ }
550 return false;
551}
552
553function eventClient (e)
554{
555 var t = null;
556 if (e.changedTouches && e.changedTouches.length)
557 { t = e.changedTouches[0]; }
558 else if (e.touches && e.touches.length)
559 { t = e.touches[0]; }
560 if (t)
561 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
562 if (e.clientX != null && e.clientY != null)
563 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
564 return null;
565}
493
566
494function addWindowPointer ()
567function addWindowPointer ()
495{
568{
@@ -497,7 +570,7 @@ function addWindowPointer ()
497 { return; }
570 { return; }
498 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
571 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
499 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
572 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
500 window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false });
573 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
501 windowListening = true;
574 windowListening = true;
502}
575}
503
576
@@ -507,28 +580,59 @@ function removeWindowPointer ()
507 { return; }
580 { return; }
508 window.removeEventListener('pointermove', onPointerMove, { capture: true });
581 window.removeEventListener('pointermove', onPointerMove, { capture: true });
509 window.removeEventListener('pointerup', onPointerUp, { capture: true });
582 window.removeEventListener('pointerup', onPointerUp, { capture: true });
510 window.removeEventListener('pointercancel', onPointerUp, { capture: true });
583 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
511 windowListening = false;
584 windowListening = false;
512}
585}
513
586
587function addTouchListeners ()
588{
589 if (touchListening)
590 { return; }
591 var opts = { capture: true, passive: false };
592 document.addEventListener('touchstart', onTouchStart, opts);
593 document.addEventListener('touchmove', onTouchMove, opts);
594 document.addEventListener('touchend', onTouchEnd, opts);
595 document.addEventListener('touchcancel', onTouchCancel, opts);
596 touchListening = true;
597}
598
599function removeTouchListeners ()
600{
601 if (!touchListening)
602 { return; }
603 var opts = { capture: true };
604 document.removeEventListener('touchstart', onTouchStart, opts);
605 document.removeEventListener('touchmove', onTouchMove, opts);
606 document.removeEventListener('touchend', onTouchEnd, opts);
607 document.removeEventListener('touchcancel', onTouchCancel, opts);
608 touchListening = false;
609}
610
514function bindPointer (canvas)
611function bindPointer (canvas)
515{
612{
516 unbindPointer();
613 unbindPointer();
517 boundCanvas = canvas;
614 boundCanvas = canvas;
518 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
615 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
519 canvas.style.touchAction = 'none';
616 canvas.style.touchAction = 'none';
617 canvas.style.position = 'fixed';
520 canvas.style.cursor = 'pointer';
618 canvas.style.cursor = 'pointer';
521 canvas.style.webkitUserSelect = 'none';
619 canvas.style.webkitUserSelect = 'none';
522 canvas.style.userSelect = 'none';
620 canvas.style.userSelect = 'none';
621 addTouchListeners();
622 if (app.debugDrag)
623 { ensureDragDebugOverlay(); }
523}
624}
524
625
525function unbindPointer ()
626function unbindPointer ()
526{
627{
527 removeWindowPointer();
628 removeWindowPointer();
629 removeTouchListeners();
528 if (boundCanvas)
630 if (boundCanvas)
529 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
631 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
530 boundCanvas = null;
632 boundCanvas = null;
531 app.pointerId = null;
633 app.pointerId = null;
634 app.pointerType = null;
635 app.activeTouchId = null;
532}
636}
533
637
534function fieldFromEvent (e)
638function fieldFromEvent (e)
@@ -539,34 +643,94 @@ function fieldFromEvent (e)
539 var rect = canvas.getBoundingClientRect();
643 var rect = canvas.getBoundingClientRect();
540 if (rect.width <= 0 || rect.height <= 0)
644 if (rect.width <= 0 || rect.height <= 0)
541 { return null; }
645 { return null; }
646 var pt = eventClient(e);
647 if (!pt)
648 { return null; }
542 // Map through the CSS box only. Using canvas.width / app.tile would
649 // Map through the CSS box only. Using canvas.width / app.tile would
543 // scale the pointer by the backing-store ratio whenever that differs
650 // scale the pointer by the backing-store ratio whenever that differs
544 // from the layout size (high-DPR devices), so a short finger move
651 // from the layout size (high-DPR devices), so a short finger move
545 // would look like a long swipe.
652 // would look like a long swipe.
546 var width = Planet.FIELD_WIDTH;
653 var width = Planet.FIELD_WIDTH;
547 var height = Planet.FIELD_HEIGHT;
654 var height = Planet.FIELD_HEIGHT;
548 var col = ((e.clientX - rect.left) / rect.width) * width;
655 var col = ((pt.x - rect.left) / rect.width) * width;
549 var fieldY = (1 - (e.clientY - rect.top) / rect.height) * height;
656 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
550 return { col: col, y: fieldY };
657 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
658}
659
660function playingForDrag ()
661{
662 return app.core && app.core.state === 'playing';
663}
664
665function startDragFromEvent (e)
666{
667 var pos = fieldFromEvent(e);
668 if (!pos)
669 { return; }
670 if (app.core.drag)
671 {
672 app.core.moveDrag(pos.y);
673 logDragDebug(e, pos, 'move-already');
674 return;
675 }
676 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
677 { startPressTween(app.core.drag.blockId); }
678 logDragDebug(e, pos, 'down');
679}
680
681function moveDragFromEvent (e)
682{
683 if (!app.core || !app.core.drag)
684 { return; }
685 var pos = fieldFromEvent(e);
686 if (pos)
687 { app.core.moveDrag(pos.y); }
688 logDragDebug(e, pos, 'move');
689}
690
691function finishDrag (opts)
692{
693 opts = opts || {};
694 app.pointerId = null;
695 app.pointerType = null;
696 app.activeTouchId = null;
697 removeWindowPointer();
698 if (boundCanvas)
699 {
700 try
701 {
702 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
703 { boundCanvas.releasePointerCapture(opts.pointerId); }
704 }
705 catch (err) { /* ignore */ }
706 }
707 startReleaseTween();
708 if (app.core && app.core.drag)
709 {
710 if (opts.noLaunch)
711 { app.core.drag.launchIntent = false; }
712 app.core.endDrag();
713 }
714 else if (app.core)
715 { app.core.endDrag(); }
716 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
551}
717}
552
718
553function onPointerDown (e)
719function onPointerDown (e)
554{
720{
555 if (!app.core || app.core.state !== 'playing')
721 if (!playingForDrag())
556 { return; }
722 { return; }
557 if (app.pointerId != null)
723 if (app.pointerId != null && e.pointerId !== app.pointerId)
558 { return; }
724 { return; }
559 e.preventDefault();
725 if (e.preventDefault)
726 { e.preventDefault(); }
560 app.pointerId = e.pointerId;
727 app.pointerId = e.pointerId;
561 try
728 app.pointerType = e.pointerType || 'mouse';
562 { boundCanvas.setPointerCapture(e.pointerId); }
563 catch (err) { /* ignore */ }
564 addWindowPointer();
729 addWindowPointer();
565 var pos = fieldFromEvent(e);
730 // If a touch is already in charge, do not reset the grab from pointerdown.
566 // Instant grab, no long-press or hold delay: the block is taken on
731 if (app.activeTouchId != null)
567 // pointerdown and the click tween starts in the same moment.
732 { return; }
568 if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag)
733 startDragFromEvent(e);
569 { startPressTween(app.core.drag.blockId); }
570}
734}
571
735
572function onPointerMove (e)
736function onPointerMove (e)
@@ -575,10 +739,20 @@ function onPointerMove (e)
575 { return; }
739 { return; }
576 if (!app.core || !app.core.drag)
740 if (!app.core || !app.core.drag)
577 { return; }
741 { return; }
578 e.preventDefault();
742 // Touch coordinates are the authority; ignore pointer moves for a
579 var pos = fieldFromEvent(e);
743 // live touch so a wrong clientY cannot walk the whole column.
580 if (pos)
744 // Only skip when touchstart has actually arrived — some environments
581 { app.core.moveDrag(pos.y); }
745 // deliver touch-pointer events without a TouchEvent stream.
746 if (app.activeTouchId != null)
747 {
748 if (e.preventDefault)
749 { e.preventDefault(); }
750 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
751 return;
752 }
753 if (e.preventDefault)
754 { e.preventDefault(); }
755 moveDragFromEvent(e);
582}
756}
583
757
584function onPointerUp (e)
758function onPointerUp (e)
@@ -587,21 +761,155 @@ function onPointerUp (e)
587 { return; }
761 { return; }
588 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
762 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
589 { return; }
763 { return; }
590 if (e)
764 if (app.activeTouchId != null)
765 {
766 // touchend will finish the drag.
767 if (e && e.preventDefault)
768 { e.preventDefault(); }
769 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
770 return;
771 }
772 if (e && e.preventDefault)
591 { e.preventDefault(); }
773 { e.preventDefault(); }
592 app.pointerId = null;
774 finishDrag({ pointerId: e && e.pointerId });
593 removeWindowPointer();
775}
594 if (boundCanvas)
776
777function onPointerCancel (e)
778{
779 if (app.pointerId == null)
780 { return; }
781 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
782 { return; }
783 if (app.activeTouchId != null)
595 {
784 {
596 try
785 if (e && e.preventDefault)
597 { boundCanvas.releasePointerCapture(e && e.pointerId); }
786 { e.preventDefault(); }
598 catch (err) { /* ignore */ }
787 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
788 return;
599 }
789 }
600 startReleaseTween();
790 if (e && e.preventDefault)
601 if (app.core)
791 { e.preventDefault(); }
602 { app.core.endDrag(); }
792 // A cancelled gesture is not a launch pull.
793 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
794}
795
796function touchById (list, id)
797{
798 if (!list)
799 { return null; }
800 for (var i = 0; i < list.length; i++)
801 {
802 if (list[i].identifier === id)
803 { return list[i]; }
804 }
805 return null;
603}
806}
604
807
808function onTouchStart (e)
809{
810 if (!playingForDrag())
811 { return; }
812 if (app.activeTouchId != null)
813 {
814 if (e.preventDefault)
815 { e.preventDefault(); }
816 return;
817 }
818 var t = e.changedTouches && e.changedTouches[0];
819 if (!t)
820 { return; }
821 if (e.preventDefault)
822 { e.preventDefault(); }
823 app.activeTouchId = t.identifier;
824 addWindowPointer();
825 startDragFromEvent(e);
826}
827
828function onTouchMove (e)
829{
830 if (app.activeTouchId == null)
831 { return; }
832 if (!touchById(e.changedTouches, app.activeTouchId)
833 && !touchById(e.touches, app.activeTouchId))
834 { return; }
835 if (e.preventDefault)
836 { e.preventDefault(); }
837 moveDragFromEvent(e);
838}
839
840function onTouchEnd (e)
841{
842 if (app.activeTouchId == null)
843 { return; }
844 if (!touchById(e.changedTouches, app.activeTouchId))
845 { return; }
846 if (e.preventDefault)
847 { e.preventDefault(); }
848 finishDrag({});
849}
850
851function onTouchCancel (e)
852{
853 if (app.activeTouchId == null)
854 { return; }
855 if (!touchById(e.changedTouches, app.activeTouchId))
856 { return; }
857 if (e.preventDefault)
858 { e.preventDefault(); }
859 finishDrag({ noLaunch: true });
860}
861
862function ensureDragDebugOverlay ()
863{
864 if (document.getElementById('drag-debug'))
865 { return; }
866 var el = document.createElement('div');
867 el.id = 'drag-debug';
868 el.setAttribute('aria-live', 'polite');
869 document.body.appendChild(el);
870}
871
872function logDragDebug (e, pos, phase)
873{
874 if (!app.debugDrag)
875 { return; }
876 ensureDragDebugOverlay();
877 var el = document.getElementById('drag-debug');
878 if (!el)
879 { return; }
880 var block = null;
881 if (app.core && app.core.drag)
882 { block = app.core.blockById(app.core.drag.blockId); }
883 var pt = e ? eventClient(e) : null;
884 var evType = e ? e.type : phase;
885 var info = {
886 phase: phase,
887 ev: evType,
888 src: pos && pos.src,
889 fieldY: pos && Math.round(pos.y * 100) / 100,
890 col: pos && Math.round(pos.col * 100) / 100,
891 cy: pt && Math.round(pt.y * 10) / 10,
892 blockY: block && Math.round(block.y * 100) / 100,
893 target: block && Math.floor((pos && pos.y) + 1e-12),
894 launch: app.core && app.core.drag && app.core.drag.launchIntent,
895 touchId: app.activeTouchId,
896 pid: app.pointerId,
897 ptype: app.pointerType
898 };
899 lastDragDebug = info;
900 el.textContent = 'drag ' + phase
901 + ' ev=' + evType
902 + ' src=' + (info.src || '-')
903 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
904 + ' → ' + (info.target != null ? info.target : '-')
905 + ' block=' + (info.blockY != null ? info.blockY : '-')
906 + (info.launch ? ' LAUNCH' : '')
907 + ' tId=' + info.touchId
908 + ' pId=' + info.pid;
909 el.hidden = false;
910}
911
912
605function hideEl (id)
913function hideEl (id)
606{
914{
607 document.getElementById(id).hidden = true;
915 document.getElementById(id).hidden = true;
test/drag-cluster.test.js added +176 −0
@@ -0,0 +1,176 @@
1 'use strict';
2
3 const { describe, it } = require('node:test');
4 const assert = require('node:assert/strict');
5 const { makeGame, GameCore } = require('./helpers.js');
6
7 function flyingGrey (game, col, y)
8 {
9 const cluster = {
10 id: game.nextClusterId++,
11 jumpHeight: 3,
12 vy: 4,
13 decel: 2,
14 phase: 'up'
15 };
16 game.clusters[cluster.id] = cluster;
17 const b = game.createBlock(col, y, GameCore.COLOR_GRAY, 'flying');
18 b.clusterId = cluster.id;
19 b.vy = cluster.vy;
20 b.flame = true;
21 return { cluster, block: b };
22 }
23
24 function landedGroup (game, col, specs)
25 {
26 // specs: [{ color, y }]
27 const cluster = {
28 id: game.nextClusterId++,
29 jumpHeight: 3,
30 vy: 0,
31 decel: 0,
32 phase: 'landed'
33 };
34 game.clusters[cluster.id] = cluster;
35 const members = [];
36 for (const s of specs)
37 {
38 const state = 'settling';
39 const b = game.createBlock(col, s.y, s.color, state);
40 b.clusterId = cluster.id;
41 b.vy = 0;
42 b.flame = false;
43 b.settleTime = s.settleTime || 0;
44 members.push(b);
45 }
46 return { cluster, members };
47 }
48
49 describe('Blocks under a flying cluster are draggable (t1107)', () =>
50 {
51 it('a still stack under a flyer in the same column can be grabbed and swapped', () =>
52 {
53 const g = makeGame({ noSpawn: true });
54 const bottom = g.place(3, 0, 0);
55 const mid = g.place(3, 1, 1);
56 const { cluster, block: flyer } = flyingGrey(g, 3, 7);
57 assert.equal(g.isColumnStill(3), false, 'isColumnStill stays strict');
58 assert.equal(g.columnAllowsDrag(3), true);
59 assert.ok(g.isDraggableBlock(bottom));
60 assert.equal(g.isDraggableBlock(flyer), false, 'the flyer itself is not draggable');
61 assert.ok(g.beginDrag(3, 0.5));
62 assert.equal(g.drag.blockId, bottom.id);
63 g.moveDrag(1.5);
64 assert.equal(bottom.y, 1);
65 assert.equal(mid.y, 0);
66 g.endDrag();
67 assert.equal(flyer.state, 'flying');
68 assert.equal(flyer.clusterId, cluster.id);
69 assert.equal(flyer.y, 7, 'flyer was left alone');
70 });
71
72 it('pressing on a flying cluster does not grab it or a block below', () =>
73 {
74 const g = makeGame({ noSpawn: true });
75 g.place(1, 0, 2);
76 const { block: flyer } = flyingGrey(g, 1, 5);
77 assert.equal(g.beginDrag(1, 5.5), false);
78 assert.equal(g.drag, null);
79 assert.equal(flyer.state, 'flying');
80 });
81 });
82
83 describe('Dragging within, into and out of a landed cluster (t1107)', () =>
84 {
85 it('dragging within a landed cluster swaps members and keeps them in the group', () =>
86 {
87 const g = makeGame({ noSpawn: true });
88 const { cluster, members } = landedGroup(g, 4, [
89 { color: GameCore.COLOR_GRAY, y: 0 },
90 { color: 1, y: 1 },
91 { color: 2, y: 2 }
92 ]);
93 const [grey, cargo1, cargo2] = members;
94 assert.ok(g.isDraggableBlock(grey));
95 assert.ok(g.isDraggableBlock(cargo1));
96 assert.ok(g.beginDrag(4, 0.4));
97 assert.equal(g.drag.blockId, grey.id);
98 g.moveDrag(2.5);
99 g.endDrag();
100 assert.equal(grey.y, 2);
101 assert.equal(cargo1.y, 0);
102 assert.equal(cargo2.y, 1);
103 assert.equal(grey.clusterId, cluster.id);
104 assert.equal(cargo1.clusterId, cluster.id);
105 assert.equal(cargo2.clusterId, cluster.id);
106 assert.equal(g.clusters[cluster.id].phase, 'landed');
107 });
108
109 it('swapping a still block into a landed cluster makes it a member', () =>
110 {
111 const g = makeGame({ noSpawn: true });
112 const still = g.place(5, 0, 3);
113 const { cluster, members } = landedGroup(g, 5, [
114 { color: GameCore.COLOR_GRAY, y: 1 },
115 { color: 4, y: 2 }
116 ]);
117 assert.ok(g.beginDrag(5, 0.5));
118 assert.equal(g.drag.blockId, still.id);
119 // Stop on the top cell, short of LAUNCH_PULL, so endDrag does not throw.
120 g.moveDrag(2.2);
121 g.endDrag();
122 assert.equal(still.y, 2);
123 assert.equal(still.clusterId, cluster.id);
124 assert.equal(still.state, 'settling');
125 assert.equal(still.color, 3);
126 // The grey was swapped into the outside slot and left the cluster.
127 assert.equal(members[0].y, 0);
128 assert.equal(members[0].clusterId, null);
129 assert.equal(members[0].state, 'settling');
130 assert.equal(members[0].color, GameCore.COLOR_GRAY);
131 // Cargo only moved to another cluster slot, so it stays a member.
132 assert.equal(members[1].y, 1);
133 assert.equal(members[1].clusterId, cluster.id);
134 assert.equal(members[1].color, 4);
135 });
136
137 it('swapping a landed member out leaves the cluster; a grey keeps its settle timer', () =>
138 {
139 const g = makeGame({ noSpawn: true });
140 g.place(6, 0, 0);
141 const { cluster, members } = landedGroup(g, 6, [
142 { color: GameCore.COLOR_GRAY, y: 1, settleTime: 1.25 },
143 { color: 2, y: 2 }
144 ]);
145 const grey = members[0];
146 assert.ok(g.beginDrag(6, 1.4));
147 assert.equal(g.drag.blockId, grey.id);
148 g.moveDrag(0.4);
149 g.endDrag();
150 assert.equal(grey.y, 0);
151 assert.equal(grey.clusterId, null);
152 assert.equal(grey.state, 'settling', 'grey keeps settling on its own timer');
153 assert.equal(grey.settleTime, 1.25);
154 assert.equal(grey.color, GameCore.COLOR_GRAY);
155 // The still block that moved in joined the cluster.
156 const joined = g.blocks.find((b) => b.color === 0);
157 assert.equal(joined.clusterId, cluster.id);
158 assert.equal(joined.state, 'settling');
159 assert.equal(joined.y, 1);
160 });
161
162 it('a gap in the column stops the swap; hanging members are part of the stack', () =>
163 {
164 const g = makeGame({ noSpawn: true });
165 const bottom = g.place(2, 0, 1);
166 const { members } = landedGroup(g, 2, [
167 { color: 3, y: 2 }
168 ]);
169 // Gap at y=1: swapToward must stop, the hanging member stays at 2.
170 assert.ok(g.beginDrag(2, 0.5));
171 g.moveDrag(2.5);
172 g.endDrag();
173 assert.equal(bottom.y, 0);
174 assert.equal(members[0].y, 2);
175 });
176 });
@@ -0,0 +1,176 @@
1'use strict';
2
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
5const { makeGame, GameCore } = require('./helpers.js');
6
7function flyingGrey (game, col, y)
8{
9 const cluster = {
10 id: game.nextClusterId++,
11 jumpHeight: 3,
12 vy: 4,
13 decel: 2,
14 phase: 'up'
15 };
16 game.clusters[cluster.id] = cluster;
17 const b = game.createBlock(col, y, GameCore.COLOR_GRAY, 'flying');
18 b.clusterId = cluster.id;
19 b.vy = cluster.vy;
20 b.flame = true;
21 return { cluster, block: b };
22}
23
24function landedGroup (game, col, specs)
25{
26 // specs: [{ color, y }]
27 const cluster = {
28 id: game.nextClusterId++,
29 jumpHeight: 3,
30 vy: 0,
31 decel: 0,
32 phase: 'landed'
33 };
34 game.clusters[cluster.id] = cluster;
35 const members = [];
36 for (const s of specs)
37 {
38 const state = 'settling';
39 const b = game.createBlock(col, s.y, s.color, state);
40 b.clusterId = cluster.id;
41 b.vy = 0;
42 b.flame = false;
43 b.settleTime = s.settleTime || 0;
44 members.push(b);
45 }
46 return { cluster, members };
47}
48
49describe('Blocks under a flying cluster are draggable (t1107)', () =>
50{
51 it('a still stack under a flyer in the same column can be grabbed and swapped', () =>
52 {
53 const g = makeGame({ noSpawn: true });
54 const bottom = g.place(3, 0, 0);
55 const mid = g.place(3, 1, 1);
56 const { cluster, block: flyer } = flyingGrey(g, 3, 7);
57 assert.equal(g.isColumnStill(3), false, 'isColumnStill stays strict');
58 assert.equal(g.columnAllowsDrag(3), true);
59 assert.ok(g.isDraggableBlock(bottom));
60 assert.equal(g.isDraggableBlock(flyer), false, 'the flyer itself is not draggable');
61 assert.ok(g.beginDrag(3, 0.5));
62 assert.equal(g.drag.blockId, bottom.id);
63 g.moveDrag(1.5);
64 assert.equal(bottom.y, 1);
65 assert.equal(mid.y, 0);
66 g.endDrag();
67 assert.equal(flyer.state, 'flying');
68 assert.equal(flyer.clusterId, cluster.id);
69 assert.equal(flyer.y, 7, 'flyer was left alone');
70 });
71
72 it('pressing on a flying cluster does not grab it or a block below', () =>
73 {
74 const g = makeGame({ noSpawn: true });
75 g.place(1, 0, 2);
76 const { block: flyer } = flyingGrey(g, 1, 5);
77 assert.equal(g.beginDrag(1, 5.5), false);
78 assert.equal(g.drag, null);
79 assert.equal(flyer.state, 'flying');
80 });
81});
82
83describe('Dragging within, into and out of a landed cluster (t1107)', () =>
84{
85 it('dragging within a landed cluster swaps members and keeps them in the group', () =>
86 {
87 const g = makeGame({ noSpawn: true });
88 const { cluster, members } = landedGroup(g, 4, [
89 { color: GameCore.COLOR_GRAY, y: 0 },
90 { color: 1, y: 1 },
91 { color: 2, y: 2 }
92 ]);
93 const [grey, cargo1, cargo2] = members;
94 assert.ok(g.isDraggableBlock(grey));
95 assert.ok(g.isDraggableBlock(cargo1));
96 assert.ok(g.beginDrag(4, 0.4));
97 assert.equal(g.drag.blockId, grey.id);
98 g.moveDrag(2.5);
99 g.endDrag();
100 assert.equal(grey.y, 2);
101 assert.equal(cargo1.y, 0);
102 assert.equal(cargo2.y, 1);
103 assert.equal(grey.clusterId, cluster.id);
104 assert.equal(cargo1.clusterId, cluster.id);
105 assert.equal(cargo2.clusterId, cluster.id);
106 assert.equal(g.clusters[cluster.id].phase, 'landed');
107 });
108
109 it('swapping a still block into a landed cluster makes it a member', () =>
110 {
111 const g = makeGame({ noSpawn: true });
112 const still = g.place(5, 0, 3);
113 const { cluster, members } = landedGroup(g, 5, [
114 { color: GameCore.COLOR_GRAY, y: 1 },
115 { color: 4, y: 2 }
116 ]);
117 assert.ok(g.beginDrag(5, 0.5));
118 assert.equal(g.drag.blockId, still.id);
119 // Stop on the top cell, short of LAUNCH_PULL, so endDrag does not throw.
120 g.moveDrag(2.2);
121 g.endDrag();
122 assert.equal(still.y, 2);
123 assert.equal(still.clusterId, cluster.id);
124 assert.equal(still.state, 'settling');
125 assert.equal(still.color, 3);
126 // The grey was swapped into the outside slot and left the cluster.
127 assert.equal(members[0].y, 0);
128 assert.equal(members[0].clusterId, null);
129 assert.equal(members[0].state, 'settling');
130 assert.equal(members[0].color, GameCore.COLOR_GRAY);
131 // Cargo only moved to another cluster slot, so it stays a member.
132 assert.equal(members[1].y, 1);
133 assert.equal(members[1].clusterId, cluster.id);
134 assert.equal(members[1].color, 4);
135 });
136
137 it('swapping a landed member out leaves the cluster; a grey keeps its settle timer', () =>
138 {
139 const g = makeGame({ noSpawn: true });
140 g.place(6, 0, 0);
141 const { cluster, members } = landedGroup(g, 6, [
142 { color: GameCore.COLOR_GRAY, y: 1, settleTime: 1.25 },
143 { color: 2, y: 2 }
144 ]);
145 const grey = members[0];
146 assert.ok(g.beginDrag(6, 1.4));
147 assert.equal(g.drag.blockId, grey.id);
148 g.moveDrag(0.4);
149 g.endDrag();
150 assert.equal(grey.y, 0);
151 assert.equal(grey.clusterId, null);
152 assert.equal(grey.state, 'settling', 'grey keeps settling on its own timer');
153 assert.equal(grey.settleTime, 1.25);
154 assert.equal(grey.color, GameCore.COLOR_GRAY);
155 // The still block that moved in joined the cluster.
156 const joined = g.blocks.find((b) => b.color === 0);
157 assert.equal(joined.clusterId, cluster.id);
158 assert.equal(joined.state, 'settling');
159 assert.equal(joined.y, 1);
160 });
161
162 it('a gap in the column stops the swap; hanging members are part of the stack', () =>
163 {
164 const g = makeGame({ noSpawn: true });
165 const bottom = g.place(2, 0, 1);
166 const { members } = landedGroup(g, 2, [
167 { color: 3, y: 2 }
168 ]);
169 // Gap at y=1: swapToward must stop, the hanging member stays at 2.
170 assert.ok(g.beginDrag(2, 0.5));
171 g.moveDrag(2.5);
172 g.endDrag();
173 assert.equal(bottom.y, 0);
174 assert.equal(members[0].y, 2);
175 });
176});
test/drag-playwright.py +288 −2
@@ -1,5 +1,6 @@
1 1 #!/usr/bin/env python3
2 """1:1 drag tracking (t1104): mouse and real touch, including a high-DPR mobile viewport."""
2 """Drag tests (t1104/t1106/t1107/t1109/t1110): 1:1 tracking, poisoned-pointer
3 regression, cell-corner grabs, under-flyer / landed-cluster drags, flame size."""
3 4 from __future__ import annotations
4 5
5 6 import socket
@@ -299,11 +300,295 @@ def run_device(browser, device):
299 300 check(end == mid, f"after release: still at the pointer row, mid={mid} end={end}", name)
300 301 shot(page, f"t1104-drag-{name}.png")
301 302
303 # --- t1109: press at cell corners grabs the occupant (mouse and touch)
304 run_cell_corner_grabs(page, cdp, kind, name)
305
306 # --- t1107: still stack under a flying cluster is draggable
307 run_under_flyer_drag(page, cdp, kind, name)
308
309 # --- t1107: drag within a landed cluster
310 run_landed_cluster_drag(page, cdp, kind, name)
311
312 # --- t1110: flame is 3x, with a visual screenshot (once per device)
313 run_flame_size(page, name)
314
302 315 if bag:
303 316 print(f"console [{name}]: {bag[:8]}")
304 317 context.close()
305 318
306 319
320 def field_point(page, fx, fy):
321 """Map exact field coordinates (not cell-centres) to client pixels."""
322 return page.evaluate(
323 """([fx, fy]) => {
324 const c = app.scene.canvas;
325 const r = c.getBoundingClientRect();
326 return {
327 x: r.left + (fx / 10) * r.width,
328 y: r.top + (1 - fy / 13) * r.height
329 };
330 }""",
331 [fx, fy],
332 )
333
334
335 def grab_id(page):
336 return page.evaluate(
337 """() => {
338 const g = app.core;
339 if (!g.drag) return null;
340 const b = g.blockById(g.drag.blockId);
341 return b ? { id: b.id, col: b.col, y: b.y, color: b.color } : null;
342 }"""
343 )
344
345
346 def run_cell_corner_grabs(page, cdp, kind, name):
347 reset_board(page, {"2": [0, 1, 2]})
348 page.wait_for_timeout(50)
349 target = page.evaluate(
350 """() => {
351 const b = app.core.blocks.find((x) => x.col === 2 && Math.abs(x.y - 1) < 0.01);
352 return b ? b.id : null;
353 }"""
354 )
355 corners = [(2.05, 1.05, "bottom-left"), (2.05, 1.95, "top-left"),
356 (2.95, 1.05, "bottom-right"), (2.95, 1.95, "top-right")]
357 for fx, fy, label in corners:
358 pt = field_point(page, fx, fy)
359 pointer_down(page, cdp, kind, pt["x"], pt["y"])
360 page.wait_for_timeout(30)
361 grabbed = grab_id(page)
362 check(
363 grabbed is not None and grabbed["id"] == target,
364 f"t1109 corner {label} ({kind}) grabs cell occupant, grabbed={grabbed} want id={target}",
365 name,
366 )
367 pointer_up(page, cdp, kind)
368 page.wait_for_timeout(40)
369 shot(page, f"t1109-corners-{name}.png")
370
371
372 def run_under_flyer_drag(page, cdp, kind, name):
373 reset_board(page, {"3": [0, 1, 2]})
374 page.evaluate(
375 """() => {
376 const g = app.core;
377 const cluster = { id: g.nextClusterId++, jumpHeight: 3, vy: 0, decel: 0, phase: 'up' };
378 g.clusters[cluster.id] = cluster;
379 const b = g.createBlock(3, 8, g.constructor.COLOR_GRAY, 'flying');
380 b.clusterId = cluster.id;
381 b.vy = 0;
382 b.flame = true;
383 }"""
384 )
385 page.wait_for_timeout(40)
386 p0 = field_to_client(page, 3, 0.5)
387 p1 = field_to_client(page, 3, 1.5)
388 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
389 page.wait_for_timeout(60)
390 info = page.evaluate(
391 """() => {
392 const g = app.core;
393 const still = g.blocks.filter((b) => b.state === 'still' && b.col === 3)
394 .map((b) => ({ color: b.color, y: b.y }));
395 const flyer = g.blocks.find((b) => b.state === 'flying' && b.col === 3);
396 return { still, flyerY: flyer ? flyer.y : null, flyerState: flyer ? flyer.state : null };
397 }"""
398 )
399 ys = {b["color"]: b["y"] for b in info["still"]}
400 check(nearly(ys.get(0, -99), 1), f"t1107 under-flyer: color 0 moved to y=1, info={info}", name)
401 check(nearly(ys.get(1, -99), 0), f"t1107 under-flyer: color 1 swapped to y=0, info={info}", name)
402 check(info["flyerState"] == "flying" and info["flyerY"] is not None and info["flyerY"] > 6,
403 f"t1107 under-flyer: flyer left alone, info={info}", name)
404
405
406 def run_landed_cluster_drag(page, cdp, kind, name):
407 page.evaluate(
408 """() => {
409 const g = app.core;
410 g.spawnInterval = 1e9;
411 g.spawnTimer = 0;
412 g.blocks.length = 0;
413 g.clusters = Object.create(null);
414 g.drag = null;
415 g.state = 'playing';
416 g.nextBlockId = 1;
417 g.nextClusterId = 1;
418 const cluster = { id: g.nextClusterId++, jumpHeight: 3, vy: 0, decel: 0, phase: 'landed' };
419 g.clusters[cluster.id] = cluster;
420 const specs = [[0, -1], [1, 1], [2, 2]];
421 for (const [y, color] of specs) {
422 const b = g.createBlock(6, y, color, 'settling');
423 b.clusterId = cluster.id;
424 b.vy = 0;
425 b.settleTime = 0;
426 }
427 }"""
428 )
429 page.wait_for_timeout(50)
430 p0 = field_to_client(page, 6, 0.5)
431 p1 = field_to_client(page, 6, 2.2)
432 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=12, end=True)
433 page.wait_for_timeout(60)
434 info = page.evaluate(
435 """() => app.core.blocks.map((b) => ({
436 color: b.color, y: b.y, state: b.state, clusterId: b.clusterId
437 }))"""
438 )
439 by_y = {round(b["y"]): b for b in info}
440 check(
441 by_y.get(2) is not None and by_y[2]["color"] == -1 and by_y[2]["clusterId"] is not None,
442 f"t1107 landed: grey dragged within cluster to y=2, info={info}",
443 name,
444 )
445
446
447 def run_flame_size(page, name):
448 page.evaluate(
449 """() => {
450 const g = app.core;
451 g.spawnInterval = 1e9;
452 g.spawnTimer = 0;
453 g.blocks.length = 0;
454 g.clusters = Object.create(null);
455 g.drag = null;
456 g.state = 'playing';
457 g.nextBlockId = 1;
458 g.nextClusterId = 1;
459 g.place(1, 0, 2);
460 g.place(2, 0, 2);
461 g.place(3, 0, 2);
462 g.resolveMatches();
463 }"""
464 )
465 # Let the view sync and the rockets rise a little so the flames are visible.
466 page.wait_for_timeout(200)
467 info = page.evaluate(
468 """() => {
469 const t = app.tile;
470 const flames = Object.keys(app.flames).map((id) => {
471 const f = app.flames[id];
472 return {
473 visible: !!(f.renderer && f.renderer.visible),
474 sx: f.transform.size.x,
475 sy: f.transform.size.y
476 };
477 }).filter((f) => f.visible);
478 return {
479 t,
480 expected: t * 0.85 * 3,
481 flames,
482 flying: app.core.blocks.filter((b) => b.flame).length
483 };
484 }"""
485 )
486 ok = (
487 info
488 and info["flying"] >= 3
489 and info["flames"]
490 and all(abs(f["sx"] - info["expected"]) < 0.51 and abs(f["sy"] - info["expected"]) < 0.51
491 for f in info["flames"])
492 )
493 check(ok, f"t1110 flame is 3x (w and h), info={info}", name)
494 shot(page, f"t1110-flame-{name}.png")
495
496
497 def run_poisoned_pointer_regression(browser):
498 """t1106: pointermoves poisoned to fieldY 9.5, touchmoves correct to 1.5.
499 Before the fix the block teleported to y=9; after, it stops at y=1.
500 This is the regression that failed on the old pointer-only path.
501 """
502 name = "poisoned-pointer"
503 print(f"\n======== {name} ========")
504 kw = dict(
505 viewport={"width": 412, "height": 915},
506 device_scale_factor=2.625,
507 is_mobile=True,
508 has_touch=True,
509 user_agent=(
510 "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 "
511 "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
512 ),
513 )
514 context = browser.new_context(**kw)
515 page = context.new_page()
516 start_play(page, "touch")
517 reset_board(page, {"2": [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]})
518 page.wait_for_timeout(50)
519 result = page.evaluate(
520 """() => {
521 const c = app.scene.canvas;
522 const r = c.getBoundingClientRect();
523 const toClient = (fy) => ({
524 x: r.left + (2.5 / 10) * r.width,
525 y: r.top + (1 - fy / 13) * r.height
526 });
527 const p0 = toClient(0.5);
528 const pGood = toClient(1.5);
529 const pBad = toClient(9.5);
530 const fireP = (type, x, y) => {
531 const ev = new PointerEvent(type, {
532 bubbles: true, cancelable: true, composed: true,
533 pointerId: 42, pointerType: 'touch', isPrimary: true,
534 clientX: x, clientY: y, pageX: x, pageY: y,
535 buttons: type === 'pointerup' ? 0 : 1, width: 28, height: 28,
536 pressure: type === 'pointerup' ? 0 : 0.5
537 });
538 (type === 'pointerdown' ? c : window).dispatchEvent(ev);
539 };
540 const fireT = (type, x, y) => {
541 const t = new Touch({
542 identifier: 1, target: c, clientX: x, clientY: y,
543 pageX: x, pageY: y, screenX: x, screenY: y,
544 radiusX: 14, radiusY: 14, force: 0.5
545 });
546 const ev = new TouchEvent(type, {
547 bubbles: true, cancelable: true, composed: true,
548 touches: type.includes('end') || type.includes('cancel') ? [] : [t],
549 targetTouches: type.includes('end') || type.includes('cancel') ? [] : [t],
550 changedTouches: [t]
551 });
552 c.dispatchEvent(ev);
553 document.dispatchEvent(ev);
554 };
555 fireP('pointerdown', p0.x, p0.y);
556 fireT('touchstart', p0.x, p0.y);
557 const midYs = [];
558 const steps = 8;
559 for (let i = 1; i <= steps; i++) {
560 const t = i / steps;
561 fireP('pointermove', p0.x, p0.y + (pBad.y - p0.y) * t);
562 fireT('touchmove', p0.x, p0.y + (pGood.y - p0.y) * t);
563 const b = app.core.blockById(app.core.drag && app.core.drag.blockId);
564 if (b) midYs.push(Math.round(b.y * 100) / 100);
565 }
566 fireT('touchend', pGood.x, pGood.y);
567 fireP('pointerup', pGood.x, pGood.y);
568 const colors = app.core.blocks
569 .filter((b) => b.col === 2)
570 .sort((a, b) => a.y - b.y)
571 .map((b) => ({ color: b.color, y: Math.round(b.y * 100) / 100, state: b.state }));
572 const moved = colors.find((b) => b.color === 0);
573 return { moved, colors, midYs, drag: app.core.drag };
574 }"""
575 )
576 moved = result.get("moved") or {}
577 # Must end at y=1 (one tile up), never at the top (y=9).
578 ok = moved.get("y") is not None and abs(moved["y"] - 1) <= 0.15
579 check(
580 ok,
581 f"t1106 poisoned pointer + correct touch leaves color 0 at y=1, result={result}",
582 name,
583 )
584 check(
585 moved.get("y") is None or moved["y"] < 4,
586 f"t1106 must not teleport to the top, y={moved.get('y')}",
587 name,
588 )
589 context.close()
590
591
307 592 def main():
308 593 global URL
309 594 port = free_port()
@@ -324,6 +609,7 @@ def main():
324 609 )
325 610 for device in (DESKTOP, ANDROID, ANDROID_DPR3, IOS):
326 611 run_device(browser, device)
612 run_poisoned_pointer_regression(browser)
327 613 browser.close()
328 614 finally:
329 615 httpd.terminate()
@@ -338,7 +624,7 @@ def main():
338 624 for f in FAILURES:
339 625 print(" -", f)
340 626 return 1
341 print("all 1:1 drag tests passed")
627 print("all drag tests passed")
342 628 return 0
343 629
344 630
@@ -1,5 +1,6 @@
1#!/usr/bin/env python3
1#!/usr/bin/env python3
2"""1:1 drag tracking (t1104): mouse and real touch, including a high-DPR mobile viewport."""
2"""Drag tests (t1104/t1106/t1107/t1109/t1110): 1:1 tracking, poisoned-pointer
3regression, cell-corner grabs, under-flyer / landed-cluster drags, flame size."""
3from __future__ import annotations
4from __future__ import annotations
4
5
5import socket
6import socket
@@ -299,11 +300,295 @@ def run_device(browser, device):
299 check(end == mid, f"after release: still at the pointer row, mid={mid} end={end}", name)
300 check(end == mid, f"after release: still at the pointer row, mid={mid} end={end}", name)
300 shot(page, f"t1104-drag-{name}.png")
301 shot(page, f"t1104-drag-{name}.png")
301
302
303 # --- t1109: press at cell corners grabs the occupant (mouse and touch)
304 run_cell_corner_grabs(page, cdp, kind, name)
305
306 # --- t1107: still stack under a flying cluster is draggable
307 run_under_flyer_drag(page, cdp, kind, name)
308
309 # --- t1107: drag within a landed cluster
310 run_landed_cluster_drag(page, cdp, kind, name)
311
312 # --- t1110: flame is 3x, with a visual screenshot (once per device)
313 run_flame_size(page, name)
314
302 if bag:
315 if bag:
303 print(f"console [{name}]: {bag[:8]}")
316 print(f"console [{name}]: {bag[:8]}")
304 context.close()
317 context.close()
305
318
306
319
320def field_point(page, fx, fy):
321 """Map exact field coordinates (not cell-centres) to client pixels."""
322 return page.evaluate(
323 """([fx, fy]) => {
324 const c = app.scene.canvas;
325 const r = c.getBoundingClientRect();
326 return {
327 x: r.left + (fx / 10) * r.width,
328 y: r.top + (1 - fy / 13) * r.height
329 };
330 }""",
331 [fx, fy],
332 )
333
334
335def grab_id(page):
336 return page.evaluate(
337 """() => {
338 const g = app.core;
339 if (!g.drag) return null;
340 const b = g.blockById(g.drag.blockId);
341 return b ? { id: b.id, col: b.col, y: b.y, color: b.color } : null;
342 }"""
343 )
344
345
346def run_cell_corner_grabs(page, cdp, kind, name):
347 reset_board(page, {"2": [0, 1, 2]})
348 page.wait_for_timeout(50)
349 target = page.evaluate(
350 """() => {
351 const b = app.core.blocks.find((x) => x.col === 2 && Math.abs(x.y - 1) < 0.01);
352 return b ? b.id : null;
353 }"""
354 )
355 corners = [(2.05, 1.05, "bottom-left"), (2.05, 1.95, "top-left"),
356 (2.95, 1.05, "bottom-right"), (2.95, 1.95, "top-right")]
357 for fx, fy, label in corners:
358 pt = field_point(page, fx, fy)
359 pointer_down(page, cdp, kind, pt["x"], pt["y"])
360 page.wait_for_timeout(30)
361 grabbed = grab_id(page)
362 check(
363 grabbed is not None and grabbed["id"] == target,
364 f"t1109 corner {label} ({kind}) grabs cell occupant, grabbed={grabbed} want id={target}",
365 name,
366 )
367 pointer_up(page, cdp, kind)
368 page.wait_for_timeout(40)
369 shot(page, f"t1109-corners-{name}.png")
370
371
372def run_under_flyer_drag(page, cdp, kind, name):
373 reset_board(page, {"3": [0, 1, 2]})
374 page.evaluate(
375 """() => {
376 const g = app.core;
377 const cluster = { id: g.nextClusterId++, jumpHeight: 3, vy: 0, decel: 0, phase: 'up' };
378 g.clusters[cluster.id] = cluster;
379 const b = g.createBlock(3, 8, g.constructor.COLOR_GRAY, 'flying');
380 b.clusterId = cluster.id;
381 b.vy = 0;
382 b.flame = true;
383 }"""
384 )
385 page.wait_for_timeout(40)
386 p0 = field_to_client(page, 3, 0.5)
387 p1 = field_to_client(page, 3, 1.5)
388 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=10, end=True)
389 page.wait_for_timeout(60)
390 info = page.evaluate(
391 """() => {
392 const g = app.core;
393 const still = g.blocks.filter((b) => b.state === 'still' && b.col === 3)
394 .map((b) => ({ color: b.color, y: b.y }));
395 const flyer = g.blocks.find((b) => b.state === 'flying' && b.col === 3);
396 return { still, flyerY: flyer ? flyer.y : null, flyerState: flyer ? flyer.state : null };
397 }"""
398 )
399 ys = {b["color"]: b["y"] for b in info["still"]}
400 check(nearly(ys.get(0, -99), 1), f"t1107 under-flyer: color 0 moved to y=1, info={info}", name)
401 check(nearly(ys.get(1, -99), 0), f"t1107 under-flyer: color 1 swapped to y=0, info={info}", name)
402 check(info["flyerState"] == "flying" and info["flyerY"] is not None and info["flyerY"] > 6,
403 f"t1107 under-flyer: flyer left alone, info={info}", name)
404
405
406def run_landed_cluster_drag(page, cdp, kind, name):
407 page.evaluate(
408 """() => {
409 const g = app.core;
410 g.spawnInterval = 1e9;
411 g.spawnTimer = 0;
412 g.blocks.length = 0;
413 g.clusters = Object.create(null);
414 g.drag = null;
415 g.state = 'playing';
416 g.nextBlockId = 1;
417 g.nextClusterId = 1;
418 const cluster = { id: g.nextClusterId++, jumpHeight: 3, vy: 0, decel: 0, phase: 'landed' };
419 g.clusters[cluster.id] = cluster;
420 const specs = [[0, -1], [1, 1], [2, 2]];
421 for (const [y, color] of specs) {
422 const b = g.createBlock(6, y, color, 'settling');
423 b.clusterId = cluster.id;
424 b.vy = 0;
425 b.settleTime = 0;
426 }
427 }"""
428 )
429 page.wait_for_timeout(50)
430 p0 = field_to_client(page, 6, 0.5)
431 p1 = field_to_client(page, 6, 2.2)
432 drag_to(page, cdp, kind, p0["x"], p0["y"], p1["x"], p1["y"], steps=12, end=True)
433 page.wait_for_timeout(60)
434 info = page.evaluate(
435 """() => app.core.blocks.map((b) => ({
436 color: b.color, y: b.y, state: b.state, clusterId: b.clusterId
437 }))"""
438 )
439 by_y = {round(b["y"]): b for b in info}
440 check(
441 by_y.get(2) is not None and by_y[2]["color"] == -1 and by_y[2]["clusterId"] is not None,
442 f"t1107 landed: grey dragged within cluster to y=2, info={info}",
443 name,
444 )
445
446
447def run_flame_size(page, name):
448 page.evaluate(
449 """() => {
450 const g = app.core;
451 g.spawnInterval = 1e9;
452 g.spawnTimer = 0;
453 g.blocks.length = 0;
454 g.clusters = Object.create(null);
455 g.drag = null;
456 g.state = 'playing';
457 g.nextBlockId = 1;
458 g.nextClusterId = 1;
459 g.place(1, 0, 2);
460 g.place(2, 0, 2);
461 g.place(3, 0, 2);
462 g.resolveMatches();
463 }"""
464 )
465 # Let the view sync and the rockets rise a little so the flames are visible.
466 page.wait_for_timeout(200)
467 info = page.evaluate(
468 """() => {
469 const t = app.tile;
470 const flames = Object.keys(app.flames).map((id) => {
471 const f = app.flames[id];
472 return {
473 visible: !!(f.renderer && f.renderer.visible),
474 sx: f.transform.size.x,
475 sy: f.transform.size.y
476 };
477 }).filter((f) => f.visible);
478 return {
479 t,
480 expected: t * 0.85 * 3,
481 flames,
482 flying: app.core.blocks.filter((b) => b.flame).length
483 };
484 }"""
485 )
486 ok = (
487 info
488 and info["flying"] >= 3
489 and info["flames"]
490 and all(abs(f["sx"] - info["expected"]) < 0.51 and abs(f["sy"] - info["expected"]) < 0.51
491 for f in info["flames"])
492 )
493 check(ok, f"t1110 flame is 3x (w and h), info={info}", name)
494 shot(page, f"t1110-flame-{name}.png")
495
496
497def run_poisoned_pointer_regression(browser):
498 """t1106: pointermoves poisoned to fieldY 9.5, touchmoves correct to 1.5.
499 Before the fix the block teleported to y=9; after, it stops at y=1.
500 This is the regression that failed on the old pointer-only path.
501 """
502 name = "poisoned-pointer"
503 print(f"\n======== {name} ========")
504 kw = dict(
505 viewport={"width": 412, "height": 915},
506 device_scale_factor=2.625,
507 is_mobile=True,
508 has_touch=True,
509 user_agent=(
510 "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 "
511 "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"
512 ),
513 )
514 context = browser.new_context(**kw)
515 page = context.new_page()
516 start_play(page, "touch")
517 reset_board(page, {"2": [0, 1, 2, 3, 4, 0, 1, 2, 3, 4]})
518 page.wait_for_timeout(50)
519 result = page.evaluate(
520 """() => {
521 const c = app.scene.canvas;
522 const r = c.getBoundingClientRect();
523 const toClient = (fy) => ({
524 x: r.left + (2.5 / 10) * r.width,
525 y: r.top + (1 - fy / 13) * r.height
526 });
527 const p0 = toClient(0.5);
528 const pGood = toClient(1.5);
529 const pBad = toClient(9.5);
530 const fireP = (type, x, y) => {
531 const ev = new PointerEvent(type, {
532 bubbles: true, cancelable: true, composed: true,
533 pointerId: 42, pointerType: 'touch', isPrimary: true,
534 clientX: x, clientY: y, pageX: x, pageY: y,
535 buttons: type === 'pointerup' ? 0 : 1, width: 28, height: 28,
536 pressure: type === 'pointerup' ? 0 : 0.5
537 });
538 (type === 'pointerdown' ? c : window).dispatchEvent(ev);
539 };
540 const fireT = (type, x, y) => {
541 const t = new Touch({
542 identifier: 1, target: c, clientX: x, clientY: y,
543 pageX: x, pageY: y, screenX: x, screenY: y,
544 radiusX: 14, radiusY: 14, force: 0.5
545 });
546 const ev = new TouchEvent(type, {
547 bubbles: true, cancelable: true, composed: true,
548 touches: type.includes('end') || type.includes('cancel') ? [] : [t],
549 targetTouches: type.includes('end') || type.includes('cancel') ? [] : [t],
550 changedTouches: [t]
551 });
552 c.dispatchEvent(ev);
553 document.dispatchEvent(ev);
554 };
555 fireP('pointerdown', p0.x, p0.y);
556 fireT('touchstart', p0.x, p0.y);
557 const midYs = [];
558 const steps = 8;
559 for (let i = 1; i <= steps; i++) {
560 const t = i / steps;
561 fireP('pointermove', p0.x, p0.y + (pBad.y - p0.y) * t);
562 fireT('touchmove', p0.x, p0.y + (pGood.y - p0.y) * t);
563 const b = app.core.blockById(app.core.drag && app.core.drag.blockId);
564 if (b) midYs.push(Math.round(b.y * 100) / 100);
565 }
566 fireT('touchend', pGood.x, pGood.y);
567 fireP('pointerup', pGood.x, pGood.y);
568 const colors = app.core.blocks
569 .filter((b) => b.col === 2)
570 .sort((a, b) => a.y - b.y)
571 .map((b) => ({ color: b.color, y: Math.round(b.y * 100) / 100, state: b.state }));
572 const moved = colors.find((b) => b.color === 0);
573 return { moved, colors, midYs, drag: app.core.drag };
574 }"""
575 )
576 moved = result.get("moved") or {}
577 # Must end at y=1 (one tile up), never at the top (y=9).
578 ok = moved.get("y") is not None and abs(moved["y"] - 1) <= 0.15
579 check(
580 ok,
581 f"t1106 poisoned pointer + correct touch leaves color 0 at y=1, result={result}",
582 name,
583 )
584 check(
585 moved.get("y") is None or moved["y"] < 4,
586 f"t1106 must not teleport to the top, y={moved.get('y')}",
587 name,
588 )
589 context.close()
590
591
307def main():
592def main():
308 global URL
593 global URL
309 port = free_port()
594 port = free_port()
@@ -324,6 +609,7 @@ def main():
324 )
609 )
325 for device in (DESKTOP, ANDROID, ANDROID_DPR3, IOS):
610 for device in (DESKTOP, ANDROID, ANDROID_DPR3, IOS):
326 run_device(browser, device)
611 run_device(browser, device)
612 run_poisoned_pointer_regression(browser)
327 browser.close()
613 browser.close()
328 finally:
614 finally:
329 httpd.terminate()
615 httpd.terminate()
@@ -338,7 +624,7 @@ def main():
338 for f in FAILURES:
624 for f in FAILURES:
339 print(" -", f)
625 print(" -", f)
340 return 1
626 return 1
341 print("all 1:1 drag tests passed")
627 print("all drag tests passed")
342 return 0
628 return 0
343
629
344
630
test/landed-match.test.js added +136 −0
@@ -0,0 +1,136 @@
1 'use strict';
2
3 const { describe, it } = require('node:test');
4 const assert = require('node:assert/strict');
5 const { makeGame, GameCore } = require('./helpers.js');
6
7 function landClusterAt (game, members)
8 {
9 const cluster = {
10 id: game.nextClusterId++,
11 jumpHeight: 3,
12 vy: 0,
13 decel: 0,
14 phase: 'down'
15 };
16 game.clusters[cluster.id] = cluster;
17 const blocks = [];
18 for (const m of members)
19 {
20 const b = game.createBlock(m.col, m.y, m.color, 'flying');
21 b.clusterId = cluster.id;
22 b.vy = 0;
23 b.flame = m.color === GameCore.COLOR_GRAY;
24 blocks.push(b);
25 }
26 game.landCluster(cluster, blocks);
27 return { cluster, blocks };
28 }
29
30 describe('Landed clusters form mixed matches with resting blocks (t1110)', () =>
31 {
32 it('coloured cargo that lands next to two resting blocks of the same colour launches immediately', () =>
33 {
34 const g = makeGame({ noSpawn: true });
35 g.place(0, 0, 2);
36 g.place(1, 0, 2);
37 const { blocks } = landClusterAt(g, [
38 { col: 2, y: 0, color: 2 },
39 { col: 2, y: 1, color: GameCore.COLOR_GRAY }
40 ]);
41 const cargo = blocks[0];
42 assert.equal(cargo.state, 'settling');
43 assert.equal(cargo.color, 2);
44 const launched = g.resolveMatches();
45 assert.ok(launched.length >= 1, 'mixed horizontal row must launch, launched=' + launched.length);
46 assert.equal(cargo.state, 'flying');
47 assert.equal(cargo.color, GameCore.COLOR_GRAY, 'matched cargo is greyed');
48 const flying = g.blocks.filter((b) => b.state === 'flying');
49 assert.ok(flying.length >= 3, 'the two resting blocks and the cargo fly, got ' + flying.length);
50 const cluster = g.clusters[cargo.clusterId];
51 assert.ok(cluster && cluster.phase === 'up' && cluster.vy > 0);
52 });
53
54 it('a vertical mixed line of resting blocks and landed cargo also launches', () =>
55 {
56 const g = makeGame({ noSpawn: true });
57 g.place(4, 0, 1);
58 g.place(4, 1, 1);
59 const { blocks } = landClusterAt(g, [
60 { col: 4, y: 2, color: 1 }
61 ]);
62 const launched = g.resolveMatches();
63 assert.ok(launched.length >= 1, 'vertical mixed match must launch');
64 assert.equal(blocks[0].state, 'flying');
65 assert.equal(g.blocks.filter((b) => b.state === 'flying').length, 3);
66 });
67
68 it('grey cluster blocks have no colour and do not match until they recolor', () =>
69 {
70 const g = makeGame({ noSpawn: true });
71 g.place(1, 0, 0);
72 g.place(2, 0, 0);
73 g.place(0, 0, 3);
74 const { blocks } = landClusterAt(g, [
75 { col: 0, y: 1, color: GameCore.COLOR_GRAY }
76 ]);
77 assert.equal(blocks[0].color, GameCore.COLOR_GRAY);
78 assert.equal(g.resolveMatches().length, 0, 'greys cannot match');
79 assert.equal(blocks[0].state, 'settling');
80 });
81
82 it('after greys recolor on landing, a mixed line with resting blocks launches', () =>
83 {
84 const g = makeGame({ noSpawn: true, seed: 1 });
85 g.place(0, 0, 4);
86 g.place(1, 0, 3);
87 g.place(2, 0, 2);
88 g.place(1, 1, 0);
89 g.place(2, 1, 0);
90 landClusterAt(g, [
91 { col: 0, y: 1, color: GameCore.COLOR_GRAY }
92 ]);
93 g.randomColor = () => 0;
94 g.step(g.settleTime + 0.05, 1 / 120);
95 const flying = g.blocks.filter((b) => b.state === 'flying');
96 assert.ok(flying.length >= 3,
97 'recolored grey + two resting must launch, flying=' + flying.length
98 + '\n' + g.snapshot().picture
99 + '\n' + JSON.stringify(g.blocks.map((b) => ({
100 col: b.col, y: b.y, color: b.color, state: b.state
101 }))));
102 const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');
103 assert.ok(cluster && cluster.vy > 0);
104 });
105
106 it('a descending cluster that lands onto a mixed row launches through the tick', () =>
107 {
108 const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
109 g.place(5, 0, 3);
110 g.place(6, 0, 3);
111 const cluster = {
112 id: g.nextClusterId++,
113 jumpHeight: 3,
114 vy: -g.planet.fallSpeed,
115 decel: 0,
116 phase: 'down'
117 };
118 g.clusters[cluster.id] = cluster;
119 const cargo = g.createBlock(7, 4, 3, 'flying');
120 cargo.clusterId = cluster.id;
121 cargo.vy = cluster.vy;
122 const grey = g.createBlock(7, 5, GameCore.COLOR_GRAY, 'flying');
123 grey.clusterId = cluster.id;
124 grey.vy = cluster.vy;
125 grey.flame = true;
126 g.step(2.0, 1 / 120);
127 const up = Object.values(g.clusters).find((c) => c.phase === 'up');
128 assert.ok(up, 'landing then matching must launch a new rocket, clusters='
129 + JSON.stringify(Object.values(g.clusters).map((c) => ({ id: c.id, phase: c.phase, vy: c.vy })))
130 + ' blocks=' + JSON.stringify(g.blocks.map((b) => ({
131 col: b.col, y: Math.round(b.y * 100) / 100, color: b.color, state: b.state
132 }))));
133 assert.ok(up.vy > 0);
134 assert.ok(g.blocks.filter((b) => b.state === 'flying' && b.color === GameCore.COLOR_GRAY).length >= 3);
135 });
136 });
@@ -0,0 +1,136 @@
1'use strict';
2
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
5const { makeGame, GameCore } = require('./helpers.js');
6
7function landClusterAt (game, members)
8{
9 const cluster = {
10 id: game.nextClusterId++,
11 jumpHeight: 3,
12 vy: 0,
13 decel: 0,
14 phase: 'down'
15 };
16 game.clusters[cluster.id] = cluster;
17 const blocks = [];
18 for (const m of members)
19 {
20 const b = game.createBlock(m.col, m.y, m.color, 'flying');
21 b.clusterId = cluster.id;
22 b.vy = 0;
23 b.flame = m.color === GameCore.COLOR_GRAY;
24 blocks.push(b);
25 }
26 game.landCluster(cluster, blocks);
27 return { cluster, blocks };
28}
29
30describe('Landed clusters form mixed matches with resting blocks (t1110)', () =>
31{
32 it('coloured cargo that lands next to two resting blocks of the same colour launches immediately', () =>
33 {
34 const g = makeGame({ noSpawn: true });
35 g.place(0, 0, 2);
36 g.place(1, 0, 2);
37 const { blocks } = landClusterAt(g, [
38 { col: 2, y: 0, color: 2 },
39 { col: 2, y: 1, color: GameCore.COLOR_GRAY }
40 ]);
41 const cargo = blocks[0];
42 assert.equal(cargo.state, 'settling');
43 assert.equal(cargo.color, 2);
44 const launched = g.resolveMatches();
45 assert.ok(launched.length >= 1, 'mixed horizontal row must launch, launched=' + launched.length);
46 assert.equal(cargo.state, 'flying');
47 assert.equal(cargo.color, GameCore.COLOR_GRAY, 'matched cargo is greyed');
48 const flying = g.blocks.filter((b) => b.state === 'flying');
49 assert.ok(flying.length >= 3, 'the two resting blocks and the cargo fly, got ' + flying.length);
50 const cluster = g.clusters[cargo.clusterId];
51 assert.ok(cluster && cluster.phase === 'up' && cluster.vy > 0);
52 });
53
54 it('a vertical mixed line of resting blocks and landed cargo also launches', () =>
55 {
56 const g = makeGame({ noSpawn: true });
57 g.place(4, 0, 1);
58 g.place(4, 1, 1);
59 const { blocks } = landClusterAt(g, [
60 { col: 4, y: 2, color: 1 }
61 ]);
62 const launched = g.resolveMatches();
63 assert.ok(launched.length >= 1, 'vertical mixed match must launch');
64 assert.equal(blocks[0].state, 'flying');
65 assert.equal(g.blocks.filter((b) => b.state === 'flying').length, 3);
66 });
67
68 it('grey cluster blocks have no colour and do not match until they recolor', () =>
69 {
70 const g = makeGame({ noSpawn: true });
71 g.place(1, 0, 0);
72 g.place(2, 0, 0);
73 g.place(0, 0, 3);
74 const { blocks } = landClusterAt(g, [
75 { col: 0, y: 1, color: GameCore.COLOR_GRAY }
76 ]);
77 assert.equal(blocks[0].color, GameCore.COLOR_GRAY);
78 assert.equal(g.resolveMatches().length, 0, 'greys cannot match');
79 assert.equal(blocks[0].state, 'settling');
80 });
81
82 it('after greys recolor on landing, a mixed line with resting blocks launches', () =>
83 {
84 const g = makeGame({ noSpawn: true, seed: 1 });
85 g.place(0, 0, 4);
86 g.place(1, 0, 3);
87 g.place(2, 0, 2);
88 g.place(1, 1, 0);
89 g.place(2, 1, 0);
90 landClusterAt(g, [
91 { col: 0, y: 1, color: GameCore.COLOR_GRAY }
92 ]);
93 g.randomColor = () => 0;
94 g.step(g.settleTime + 0.05, 1 / 120);
95 const flying = g.blocks.filter((b) => b.state === 'flying');
96 assert.ok(flying.length >= 3,
97 'recolored grey + two resting must launch, flying=' + flying.length
98 + '\n' + g.snapshot().picture
99 + '\n' + JSON.stringify(g.blocks.map((b) => ({
100 col: b.col, y: b.y, color: b.color, state: b.state
101 }))));
102 const cluster = Object.values(g.clusters).find((c) => c.phase === 'up');
103 assert.ok(cluster && cluster.vy > 0);
104 });
105
106 it('a descending cluster that lands onto a mixed row launches through the tick', () =>
107 {
108 const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
109 g.place(5, 0, 3);
110 g.place(6, 0, 3);
111 const cluster = {
112 id: g.nextClusterId++,
113 jumpHeight: 3,
114 vy: -g.planet.fallSpeed,
115 decel: 0,
116 phase: 'down'
117 };
118 g.clusters[cluster.id] = cluster;
119 const cargo = g.createBlock(7, 4, 3, 'flying');
120 cargo.clusterId = cluster.id;
121 cargo.vy = cluster.vy;
122 const grey = g.createBlock(7, 5, GameCore.COLOR_GRAY, 'flying');
123 grey.clusterId = cluster.id;
124 grey.vy = cluster.vy;
125 grey.flame = true;
126 g.step(2.0, 1 / 120);
127 const up = Object.values(g.clusters).find((c) => c.phase === 'up');
128 assert.ok(up, 'landing then matching must launch a new rocket, clusters='
129 + JSON.stringify(Object.values(g.clusters).map((c) => ({ id: c.id, phase: c.phase, vy: c.vy })))
130 + ' blocks=' + JSON.stringify(g.blocks.map((b) => ({
131 col: b.col, y: Math.round(b.y * 100) / 100, color: b.color, state: b.state
132 }))));
133 assert.ok(up.vy > 0);
134 assert.ok(g.blocks.filter((b) => b.state === 'flying' && b.color === GameCore.COLOR_GRAY).length >= 3);
135 });
136});
test/manual-falling.test.js added +208 −0
@@ -0,0 +1,208 @@
1 'use strict';
2
3 const { describe, it } = require('node:test');
4 const assert = require('node:assert/strict');
5 const { makeGame, almost, GameCore } = require('./helpers.js');
6
7 describe('Thrown blocks collide with falling blocks (t1108)', () =>
8 {
9 it('mergeManualWithFalling averages velocity, decel and jumpHeight by block count', () =>
10 {
11 const g = makeGame({ noSpawn: true });
12 const thrown = g.place(4, 4, 1);
13 g.startManualLaunch(thrown);
14 thrown.vy = 10;
15 thrown.manualDecel = 6;
16 thrown.manualJumpHeight = 9;
17 const a = g.createBlock(4, 5, 2, 'falling');
18 a.vy = -4;
19 const b = g.createBlock(4, 6, 3, 'falling');
20 b.vy = -2;
21 const cluster = g.mergeManualWithFalling(thrown, [a, b]);
22 assert.ok(cluster);
23 assert.equal(cluster.fromManual, true);
24 assert.ok(almost(cluster.vy, (10 + -4 + -2) / 3, 1e-12), 'vy=' + cluster.vy);
25 assert.ok(almost(cluster.decel, 6 / 3, 1e-12), 'decel=' + cluster.decel);
26 assert.ok(almost(cluster.jumpHeight, 9 / 3, 1e-12), 'jumpHeight=' + cluster.jumpHeight);
27 assert.equal(thrown.state, 'flying');
28 assert.equal(a.state, 'flying');
29 assert.equal(b.state, 'flying');
30 assert.equal(a.clusterId, cluster.id);
31 assert.equal(b.clusterId, cluster.id);
32 assert.ok(almost(thrown.vy, cluster.vy, 1e-12));
33 assert.ok(almost(a.vy, cluster.vy, 1e-12));
34 });
35
36 it('a thrown block merges with a falling block and they never pass through', () =>
37 {
38 const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
39 const thrown = g.place(4, 1, 1);
40 g.startManualLaunch(thrown);
41 assert.equal(thrown.state, 'manual');
42 assert.ok(thrown.vy > 0);
43 const falling = g.createBlock(4, 8, 2, 'falling');
44 falling.vy = -g.planet.fallSpeed;
45 let merged = false;
46 for (let i = 0; i < 400; i++)
47 {
48 g.tick(1 / 120);
49 if (thrown.state === 'flying' && falling.state === 'flying')
50 {
51 assert.equal(thrown.clusterId, falling.clusterId);
52 const cluster = g.clusters[thrown.clusterId];
53 assert.ok(cluster, 'a flying cluster was created');
54 assert.equal(cluster.fromManual, true);
55 assert.ok(Math.abs(Math.abs(falling.y - thrown.y) - 1) < 0.05,
56 'members packed one tile apart, thrown=' + thrown.y + ' falling=' + falling.y);
57 merged = true;
58 break;
59 }
60 assert.notEqual(falling.state, 'still',
61 'falling must not land through the thrown block, y=' + falling.y + ' thrown=' + thrown.y);
62 }
63 assert.ok(merged, 'they must have merged, thrown=' + thrown.state + '@' + thrown.y
64 + ' falling=' + falling.state + '@' + falling.y);
65 });
66
67 it('a stack of two falling blocks merges with the thrown block as one cluster of three', () =>
68 {
69 const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
70 const thrown = g.place(3, 0, 0);
71 g.startManualLaunch(thrown);
72 const a = g.createBlock(3, 7, 1, 'falling');
73 const b = g.createBlock(3, 8, 2, 'falling');
74 a.vy = -g.planet.fallSpeed;
75 b.vy = -g.planet.fallSpeed;
76 let merged = false;
77 for (let i = 0; i < 400; i++)
78 {
79 g.tick(1 / 120);
80 if (thrown.state === 'flying' && a.state === 'flying' && b.state === 'flying')
81 {
82 assert.equal(a.clusterId, thrown.clusterId);
83 assert.equal(b.clusterId, thrown.clusterId);
84 const cluster = g.clusters[thrown.clusterId];
85 assert.equal(cluster.fromManual, true);
86 assert.equal(g.clusterMembers(cluster.id).length, 3);
87 merged = true;
88 break;
89 }
90 }
91 assert.ok(merged, 'all three must merge, states='
92 + [thrown, a, b].map((x) => x.state + '@' + x.y).join(', '));
93 });
94
95 it('later falling cargo on a fromManual cluster also averages and does not pass through', () =>
96 {
97 const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
98 const thrown = g.place(2, 2, 3);
99 g.startManualLaunch(thrown);
100 const first = g.createBlock(2, 6, 1, 'falling');
101 first.vy = -g.planet.fallSpeed;
102 for (let i = 0; i < 400 && thrown.state !== 'flying'; i++)
103 { g.tick(1 / 120); }
104 assert.equal(thrown.state, 'flying');
105 assert.equal(first.state, 'flying');
106 const cluster = g.clusters[thrown.clusterId];
107 assert.equal(cluster.fromManual, true);
108 const roof = Math.max(thrown.y, first.y);
109 const second = g.createBlock(2, roof + 2.5, 4, 'falling');
110 second.vy = -g.planet.fallSpeed;
111 let attached = false;
112 for (let i = 0; i < 400; i++)
113 {
114 const n0 = g.clusterMembers(cluster.id).length;
115 const v0 = cluster.vy;
116 const vFall = second.vy;
117 g.tick(1 / 120);
118 if (second.state === 'flying' && second.clusterId === cluster.id)
119 {
120 // Attach averages, then this same tick's later substeps / cluster
121 // integrate may ease vy a little. The new vy must be between the
122 // two inputs (or just after a small decel from that average).
123 const expected = (v0 * n0 + vFall) / (n0 + 1);
124 assert.ok(Math.abs(cluster.vy - expected) < 0.5
125 || (cluster.vy - expected) * Math.sign(cluster.decel || 1) <= 0,
126 'second cargo averages, vy=' + cluster.vy + ' expected ~' + expected
127 + ' from v0=' + v0 + ' n0=' + n0 + ' vFall=' + vFall);
128 assert.ok(second.y + 1e-6 >= Math.min(thrown.y, first.y) - 0.05,
129 'second cargo did not pass through, y=' + second.y);
130 assert.equal(g.clusterMembers(cluster.id).length, n0 + 1);
131 attached = true;
132 break;
133 }
134 assert.ok(second.y + 1e-6 >= Math.min(thrown.y, first.y) - 0.05,
135 'must not pass through before attach, second=' + second.y
136 + ' cluster min=' + Math.min(thrown.y, first.y));
137 }
138 assert.ok(attached, 'second falling block must attach, state=' + second.state + ' y=' + second.y);
139
140 // Direct attach average, isolated from integrate.
141 const g2 = makeGame({ noSpawn: true });
142 const cl = {
143 id: g2.nextClusterId++,
144 jumpHeight: 6,
145 vy: 8,
146 decel: 4,
147 phase: 'up',
148 fromManual: true
149 };
150 g2.clusters[cl.id] = cl;
151 const r = g2.createBlock(1, 4, GameCore.COLOR_GRAY, 'flying');
152 r.clusterId = cl.id;
153 r.vy = 8;
154 const c1 = g2.createBlock(1, 5, 1, 'flying');
155 c1.clusterId = cl.id;
156 c1.vy = 8;
157 const extra = g2.createBlock(1, 6.05, 2, 'falling');
158 extra.vy = -4;
159 assert.ok(g2.attachToFlyingCluster(extra, c1));
160 assert.ok(almost(cl.vy, (8 * 2 + -4) / 3, 1e-12), 'isolated average, vy=' + cl.vy);
161 assert.ok(almost(extra.vy, cl.vy, 1e-12));
162 assert.ok(almost(r.vy, cl.vy, 1e-12));
163 assert.ok(almost(cl.decel, 4 * 2 / 3, 1e-12));
164 assert.ok(almost(cl.jumpHeight, 6 * 2 / 3, 1e-12));
165 });
166
167 it('a fast substep that would cross still merges; they never pass through', () =>
168 {
169 const g = makeGame({ noSpawn: true });
170 const thrown = g.place(5, 5, 1);
171 g.startManualLaunch(thrown);
172 thrown.vy = 80;
173 thrown.manualDecel = 0;
174 const falling = g.createBlock(5, 6.2, 2, 'falling');
175 falling.vy = -80;
176 g.tick(1 / 120);
177 assert.equal(thrown.state, 'flying', 'merged, thrown=' + thrown.state);
178 assert.equal(falling.state, 'flying');
179 assert.equal(thrown.clusterId, falling.clusterId);
180 assert.ok(Math.abs(falling.y - thrown.y) >= 1 - 0.05,
181 'packed without overlapping, thrown=' + thrown.y + ' falling=' + falling.y);
182 });
183
184 it('a normal match-rocket does not average falling cargo (existing attach rule)', () =>
185 {
186 const g = makeGame({ noSpawn: true });
187 const cluster = {
188 id: g.nextClusterId++,
189 jumpHeight: 4,
190 vy: 6,
191 decel: 3,
192 phase: 'hold'
193 };
194 g.clusters[cluster.id] = cluster;
195 const rocket = g.createBlock(1, 4, GameCore.COLOR_GRAY, 'flying');
196 rocket.clusterId = cluster.id;
197 rocket.vy = 6;
198 rocket.flame = true;
199 const cargo = g.createBlock(1, 5.05, 3, 'falling');
200 cargo.vy = -g.planet.fallSpeed;
201 assert.ok(g.attachToFlyingCluster(cargo, rocket));
202 assert.equal(cargo.state, 'flying');
203 assert.equal(cargo.clusterId, cluster.id);
204 assert.ok(almost(cluster.vy, 6, 1e-12), 'rocket vy unchanged, vy=' + cluster.vy);
205 assert.ok(almost(cargo.vy, 6, 1e-12));
206 assert.equal(cluster.fromManual, undefined);
207 });
208 });
@@ -0,0 +1,208 @@
1'use strict';
2
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
5const { makeGame, almost, GameCore } = require('./helpers.js');
6
7describe('Thrown blocks collide with falling blocks (t1108)', () =>
8{
9 it('mergeManualWithFalling averages velocity, decel and jumpHeight by block count', () =>
10 {
11 const g = makeGame({ noSpawn: true });
12 const thrown = g.place(4, 4, 1);
13 g.startManualLaunch(thrown);
14 thrown.vy = 10;
15 thrown.manualDecel = 6;
16 thrown.manualJumpHeight = 9;
17 const a = g.createBlock(4, 5, 2, 'falling');
18 a.vy = -4;
19 const b = g.createBlock(4, 6, 3, 'falling');
20 b.vy = -2;
21 const cluster = g.mergeManualWithFalling(thrown, [a, b]);
22 assert.ok(cluster);
23 assert.equal(cluster.fromManual, true);
24 assert.ok(almost(cluster.vy, (10 + -4 + -2) / 3, 1e-12), 'vy=' + cluster.vy);
25 assert.ok(almost(cluster.decel, 6 / 3, 1e-12), 'decel=' + cluster.decel);
26 assert.ok(almost(cluster.jumpHeight, 9 / 3, 1e-12), 'jumpHeight=' + cluster.jumpHeight);
27 assert.equal(thrown.state, 'flying');
28 assert.equal(a.state, 'flying');
29 assert.equal(b.state, 'flying');
30 assert.equal(a.clusterId, cluster.id);
31 assert.equal(b.clusterId, cluster.id);
32 assert.ok(almost(thrown.vy, cluster.vy, 1e-12));
33 assert.ok(almost(a.vy, cluster.vy, 1e-12));
34 });
35
36 it('a thrown block merges with a falling block and they never pass through', () =>
37 {
38 const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
39 const thrown = g.place(4, 1, 1);
40 g.startManualLaunch(thrown);
41 assert.equal(thrown.state, 'manual');
42 assert.ok(thrown.vy > 0);
43 const falling = g.createBlock(4, 8, 2, 'falling');
44 falling.vy = -g.planet.fallSpeed;
45 let merged = false;
46 for (let i = 0; i < 400; i++)
47 {
48 g.tick(1 / 120);
49 if (thrown.state === 'flying' && falling.state === 'flying')
50 {
51 assert.equal(thrown.clusterId, falling.clusterId);
52 const cluster = g.clusters[thrown.clusterId];
53 assert.ok(cluster, 'a flying cluster was created');
54 assert.equal(cluster.fromManual, true);
55 assert.ok(Math.abs(Math.abs(falling.y - thrown.y) - 1) < 0.05,
56 'members packed one tile apart, thrown=' + thrown.y + ' falling=' + falling.y);
57 merged = true;
58 break;
59 }
60 assert.notEqual(falling.state, 'still',
61 'falling must not land through the thrown block, y=' + falling.y + ' thrown=' + thrown.y);
62 }
63 assert.ok(merged, 'they must have merged, thrown=' + thrown.state + '@' + thrown.y
64 + ' falling=' + falling.state + '@' + falling.y);
65 });
66
67 it('a stack of two falling blocks merges with the thrown block as one cluster of three', () =>
68 {
69 const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
70 const thrown = g.place(3, 0, 0);
71 g.startManualLaunch(thrown);
72 const a = g.createBlock(3, 7, 1, 'falling');
73 const b = g.createBlock(3, 8, 2, 'falling');
74 a.vy = -g.planet.fallSpeed;
75 b.vy = -g.planet.fallSpeed;
76 let merged = false;
77 for (let i = 0; i < 400; i++)
78 {
79 g.tick(1 / 120);
80 if (thrown.state === 'flying' && a.state === 'flying' && b.state === 'flying')
81 {
82 assert.equal(a.clusterId, thrown.clusterId);
83 assert.equal(b.clusterId, thrown.clusterId);
84 const cluster = g.clusters[thrown.clusterId];
85 assert.equal(cluster.fromManual, true);
86 assert.equal(g.clusterMembers(cluster.id).length, 3);
87 merged = true;
88 break;
89 }
90 }
91 assert.ok(merged, 'all three must merge, states='
92 + [thrown, a, b].map((x) => x.state + '@' + x.y).join(', '));
93 });
94
95 it('later falling cargo on a fromManual cluster also averages and does not pass through', () =>
96 {
97 const g = makeGame({ noSpawn: true, planetOpts: { jumpsToClear: 2, fallTime: 3, riseTime: 1.5 } });
98 const thrown = g.place(2, 2, 3);
99 g.startManualLaunch(thrown);
100 const first = g.createBlock(2, 6, 1, 'falling');
101 first.vy = -g.planet.fallSpeed;
102 for (let i = 0; i < 400 && thrown.state !== 'flying'; i++)
103 { g.tick(1 / 120); }
104 assert.equal(thrown.state, 'flying');
105 assert.equal(first.state, 'flying');
106 const cluster = g.clusters[thrown.clusterId];
107 assert.equal(cluster.fromManual, true);
108 const roof = Math.max(thrown.y, first.y);
109 const second = g.createBlock(2, roof + 2.5, 4, 'falling');
110 second.vy = -g.planet.fallSpeed;
111 let attached = false;
112 for (let i = 0; i < 400; i++)
113 {
114 const n0 = g.clusterMembers(cluster.id).length;
115 const v0 = cluster.vy;
116 const vFall = second.vy;
117 g.tick(1 / 120);
118 if (second.state === 'flying' && second.clusterId === cluster.id)
119 {
120 // Attach averages, then this same tick's later substeps / cluster
121 // integrate may ease vy a little. The new vy must be between the
122 // two inputs (or just after a small decel from that average).
123 const expected = (v0 * n0 + vFall) / (n0 + 1);
124 assert.ok(Math.abs(cluster.vy - expected) < 0.5
125 || (cluster.vy - expected) * Math.sign(cluster.decel || 1) <= 0,
126 'second cargo averages, vy=' + cluster.vy + ' expected ~' + expected
127 + ' from v0=' + v0 + ' n0=' + n0 + ' vFall=' + vFall);
128 assert.ok(second.y + 1e-6 >= Math.min(thrown.y, first.y) - 0.05,
129 'second cargo did not pass through, y=' + second.y);
130 assert.equal(g.clusterMembers(cluster.id).length, n0 + 1);
131 attached = true;
132 break;
133 }
134 assert.ok(second.y + 1e-6 >= Math.min(thrown.y, first.y) - 0.05,
135 'must not pass through before attach, second=' + second.y
136 + ' cluster min=' + Math.min(thrown.y, first.y));
137 }
138 assert.ok(attached, 'second falling block must attach, state=' + second.state + ' y=' + second.y);
139
140 // Direct attach average, isolated from integrate.
141 const g2 = makeGame({ noSpawn: true });
142 const cl = {
143 id: g2.nextClusterId++,
144 jumpHeight: 6,
145 vy: 8,
146 decel: 4,
147 phase: 'up',
148 fromManual: true
149 };
150 g2.clusters[cl.id] = cl;
151 const r = g2.createBlock(1, 4, GameCore.COLOR_GRAY, 'flying');
152 r.clusterId = cl.id;
153 r.vy = 8;
154 const c1 = g2.createBlock(1, 5, 1, 'flying');
155 c1.clusterId = cl.id;
156 c1.vy = 8;
157 const extra = g2.createBlock(1, 6.05, 2, 'falling');
158 extra.vy = -4;
159 assert.ok(g2.attachToFlyingCluster(extra, c1));
160 assert.ok(almost(cl.vy, (8 * 2 + -4) / 3, 1e-12), 'isolated average, vy=' + cl.vy);
161 assert.ok(almost(extra.vy, cl.vy, 1e-12));
162 assert.ok(almost(r.vy, cl.vy, 1e-12));
163 assert.ok(almost(cl.decel, 4 * 2 / 3, 1e-12));
164 assert.ok(almost(cl.jumpHeight, 6 * 2 / 3, 1e-12));
165 });
166
167 it('a fast substep that would cross still merges; they never pass through', () =>
168 {
169 const g = makeGame({ noSpawn: true });
170 const thrown = g.place(5, 5, 1);
171 g.startManualLaunch(thrown);
172 thrown.vy = 80;
173 thrown.manualDecel = 0;
174 const falling = g.createBlock(5, 6.2, 2, 'falling');
175 falling.vy = -80;
176 g.tick(1 / 120);
177 assert.equal(thrown.state, 'flying', 'merged, thrown=' + thrown.state);
178 assert.equal(falling.state, 'flying');
179 assert.equal(thrown.clusterId, falling.clusterId);
180 assert.ok(Math.abs(falling.y - thrown.y) >= 1 - 0.05,
181 'packed without overlapping, thrown=' + thrown.y + ' falling=' + falling.y);
182 });
183
184 it('a normal match-rocket does not average falling cargo (existing attach rule)', () =>
185 {
186 const g = makeGame({ noSpawn: true });
187 const cluster = {
188 id: g.nextClusterId++,
189 jumpHeight: 4,
190 vy: 6,
191 decel: 3,
192 phase: 'hold'
193 };
194 g.clusters[cluster.id] = cluster;
195 const rocket = g.createBlock(1, 4, GameCore.COLOR_GRAY, 'flying');
196 rocket.clusterId = cluster.id;
197 rocket.vy = 6;
198 rocket.flame = true;
199 const cargo = g.createBlock(1, 5.05, 3, 'falling');
200 cargo.vy = -g.planet.fallSpeed;
201 assert.ok(g.attachToFlyingCluster(cargo, rocket));
202 assert.equal(cargo.state, 'flying');
203 assert.equal(cargo.clusterId, cluster.id);
204 assert.ok(almost(cluster.vy, 6, 1e-12), 'rocket vy unchanged, vy=' + cluster.vy);
205 assert.ok(almost(cargo.vy, 6, 1e-12));
206 assert.equal(cluster.fromManual, undefined);
207 });
208});
test/snap-cell.test.js added +79 −0
@@ -0,0 +1,79 @@
1 'use strict';
2
3 const { describe, it } = require('node:test');
4 const assert = require('node:assert/strict');
5 const { makeGame, GameCore } = require('./helpers.js');
6
7 describe('Cell-based grab picking (t1109)', () =>
8 {
9 it('a press anywhere inside the cell, including each corner, grabs that block', () =>
10 {
11 const g = makeGame({ noSpawn: true });
12 const block = g.place(2, 3, 1);
13 g.place(2, 2, 0);
14 g.place(2, 4, 2);
15 const corners = [
16 [2.01, 3.01],
17 [2.01, 3.99],
18 [2.99, 3.01],
19 [2.99, 3.99],
20 [2.5, 3.5],
21 [2.15, 3.15],
22 [2.85, 3.85]
23 ];
24 for (const [col, y] of corners)
25 {
26 assert.ok(g.beginDrag(col, y), 'should grab at (' + col + ', ' + y + ')');
27 assert.equal(g.drag.blockId, block.id, 'wrong block at (' + col + ', ' + y + ')');
28 g.endDrag();
29 }
30 });
31
32 it('a press in the padding / gap of a cell still grabs the occupant (not the sprite box)', () =>
33 {
34 const g = makeGame({ noSpawn: true });
35 const block = g.place(4, 1, 3);
36 g.place(4, 0, 0);
37 // Near the edges — "gaps between sprites" if sprites are inset.
38 assert.ok(g.beginDrag(4.02, 1.02));
39 assert.equal(g.drag.blockId, block.id);
40 g.endDrag();
41 assert.ok(g.beginDrag(4.98, 1.98));
42 assert.equal(g.drag.blockId, block.id);
43 g.endDrag();
44 });
45
46 it('when a block is mid-animation (non-integer y), the nearest in the column within half a tile is grabbed', () =>
47 {
48 const g = makeGame({ noSpawn: true });
49 const block = g.place(1, 2, 2);
50 g.place(1, 0, 0);
51 // Simulate a bounce / settle offset: the block sits at 2.35.
52 block.y = 2.35;
53 // Press in cell 2 (overlaps the footprint [2.35, 3.35)).
54 assert.ok(g.beginDrag(1.4, 2.5));
55 assert.equal(g.drag.blockId, block.id);
56 g.endDrag();
57 // Press in cell 3, just above the footprint — fallback within 0.5.
58 // Footprint ends at 3.35; press at 3.55 is 0.20 away.
59 assert.ok(g.beginDrag(1.4, 3.55));
60 assert.equal(g.drag.blockId, block.id);
61 g.endDrag();
62 // Further than SNAP_Y (0.5) above 3.35: at 3.35+0.5+0.15=4.0, no grab.
63 assert.equal(g.beginDrag(1.4, 3.35 + GameCore.SNAP_Y + 0.15), false);
64 });
65
66 it('floor of the pointer chooses the cell; the cell above is a different block', () =>
67 {
68 const g = makeGame({ noSpawn: true });
69 const lower = g.place(0, 5, 1);
70 const upper = g.place(0, 6, 2);
71 g.place(0, 4, 0);
72 assert.ok(g.beginDrag(0.99, 5.99));
73 assert.equal(g.drag.blockId, lower.id);
74 g.endDrag();
75 assert.ok(g.beginDrag(0.01, 6.01));
76 assert.equal(g.drag.blockId, upper.id);
77 g.endDrag();
78 });
79 });
@@ -0,0 +1,79 @@
1'use strict';
2
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
5const { makeGame, GameCore } = require('./helpers.js');
6
7describe('Cell-based grab picking (t1109)', () =>
8{
9 it('a press anywhere inside the cell, including each corner, grabs that block', () =>
10 {
11 const g = makeGame({ noSpawn: true });
12 const block = g.place(2, 3, 1);
13 g.place(2, 2, 0);
14 g.place(2, 4, 2);
15 const corners = [
16 [2.01, 3.01],
17 [2.01, 3.99],
18 [2.99, 3.01],
19 [2.99, 3.99],
20 [2.5, 3.5],
21 [2.15, 3.15],
22 [2.85, 3.85]
23 ];
24 for (const [col, y] of corners)
25 {
26 assert.ok(g.beginDrag(col, y), 'should grab at (' + col + ', ' + y + ')');
27 assert.equal(g.drag.blockId, block.id, 'wrong block at (' + col + ', ' + y + ')');
28 g.endDrag();
29 }
30 });
31
32 it('a press in the padding / gap of a cell still grabs the occupant (not the sprite box)', () =>
33 {
34 const g = makeGame({ noSpawn: true });
35 const block = g.place(4, 1, 3);
36 g.place(4, 0, 0);
37 // Near the edges — "gaps between sprites" if sprites are inset.
38 assert.ok(g.beginDrag(4.02, 1.02));
39 assert.equal(g.drag.blockId, block.id);
40 g.endDrag();
41 assert.ok(g.beginDrag(4.98, 1.98));
42 assert.equal(g.drag.blockId, block.id);
43 g.endDrag();
44 });
45
46 it('when a block is mid-animation (non-integer y), the nearest in the column within half a tile is grabbed', () =>
47 {
48 const g = makeGame({ noSpawn: true });
49 const block = g.place(1, 2, 2);
50 g.place(1, 0, 0);
51 // Simulate a bounce / settle offset: the block sits at 2.35.
52 block.y = 2.35;
53 // Press in cell 2 (overlaps the footprint [2.35, 3.35)).
54 assert.ok(g.beginDrag(1.4, 2.5));
55 assert.equal(g.drag.blockId, block.id);
56 g.endDrag();
57 // Press in cell 3, just above the footprint — fallback within 0.5.
58 // Footprint ends at 3.35; press at 3.55 is 0.20 away.
59 assert.ok(g.beginDrag(1.4, 3.55));
60 assert.equal(g.drag.blockId, block.id);
61 g.endDrag();
62 // Further than SNAP_Y (0.5) above 3.35: at 3.35+0.5+0.15=4.0, no grab.
63 assert.equal(g.beginDrag(1.4, 3.35 + GameCore.SNAP_Y + 0.15), false);
64 });
65
66 it('floor of the pointer chooses the cell; the cell above is a different block', () =>
67 {
68 const g = makeGame({ noSpawn: true });
69 const lower = g.place(0, 5, 1);
70 const upper = g.place(0, 6, 2);
71 g.place(0, 4, 0);
72 assert.ok(g.beginDrag(0.99, 5.99));
73 assert.equal(g.drag.blockId, lower.id);
74 g.endDrag();
75 assert.ok(g.beginDrag(0.01, 6.01));
76 assert.equal(g.drag.blockId, upper.id);
77 g.endDrag();
78 });
79});