BlueGit

projects-timfalken-com meteors

Merge branch 'feature/t1192-garbage-queue'

timfa Grok Bot · pushed by timfa

Authored 2026-11-14 · 3 days ago

Hash
735c5d81978ad3525bc8b6e8ca489b60a6cd66f7
Pipeline
Passed
7 files changed +594 −18
README.md +8 −0
@@ -209,6 +209,14 @@ op het podium en daarna ga je terug naar de lobby.
209 209 korter (minimum 0,1 s, na ca. 767 blokken / 5 minuten). Elk spel en elke
210 210 ronde begint weer bij 0 s, ook voor bots en online.
211 211
212 ### Ontvangen blokken
213
214 Blokken die je van een tegenstander (of bot) krijgt gaan nooit verloren.
215 Ze komen in een wachtrij en vallen pas als er plek is: het vorige blok in
216 die kolom moet een hele cel onder de bovenste rij zitten. Is de gewenste
217 kolom vol, geblokkeerd of bezet door een vertrekkende raket, dan kiest het
218 blok een andere open kolom; is er geen enkele open, dan wacht het.
219
212 220 ### Raketvlam
213 221
214 222 De vlam onder een raketblok wisselt 25 keer per seconde naar een willekeurig
@@ -209,6 +209,14 @@ op het podium en daarna ga je terug naar de lobby.
209 korter (minimum 0,1 s, na ca. 767 blokken / 5 minuten). Elk spel en elke
209 korter (minimum 0,1 s, na ca. 767 blokken / 5 minuten). Elk spel en elke
210 ronde begint weer bij 0 s, ook voor bots en online.
210 ronde begint weer bij 0 s, ook voor bots en online.
211
211
212### Ontvangen blokken
213
214Blokken die je van een tegenstander (of bot) krijgt gaan nooit verloren.
215Ze komen in een wachtrij en vallen pas als er plek is: het vorige blok in
216die kolom moet een hele cel onder de bovenste rij zitten. Is de gewenste
217kolom vol, geblokkeerd of bezet door een vertrekkende raket, dan kiest het
218blok een andere open kolom; is er geen enkele open, dan wacht het.
219
212### Raketvlam
220### Raketvlam
213
221
214De vlam onder een raketblok wisselt 25 keer per seconde naar een willekeurig
222De vlam onder een raketblok wisselt 25 keer per seconde naar een willekeurig
build/game.js +93 −7
@@ -5179,6 +5179,8 @@ function GameCore (planet, rng)
5179 5179 this.drag = null;
5180 5180 this.gameOverTime = 0;
5181 5181 this.outgoingShots = [];
5182 /** Received garbage waiting for room (t1192). */
5183 this.garbageQueue = [];
5182 5184 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
5183 5185 this.missChance = optsMissChance(arguments);
5184 5186 // t1112: invariant checker. strictInvariants throws (tests);
@@ -5683,6 +5685,9 @@ GameCore.prototype.tick = function (dt)
5683 5685
5684 5686 // t1189: spawn timeline by elapsed play time (intro burst, ramp, then
5685 5687 // the per-spawn speed-up). Interval is re-read after every spawn.
5688 // t1192: waiting received blocks drop first, as soon as there is room.
5689 if (this.garbageQueue.length)
5690 { this.drainGarbageQueue(); }
5686 5691 this.spawnTimer += dt;
5687 5692 var iv = this.currentSpawnInterval();
5688 5693 while (this.spawnTimer >= iv)
@@ -7387,17 +7392,98 @@ GameCore.prototype.pickGarbageColumn = function (preferred)
7387 7392 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
7388 7393 };
7389 7394
7395 /**
7396 * Receive one garbage block (t1192). It is queued and dropped as soon as
7397 * there is room; received blocks are never lost. Returns the block when
7398 * it could drop right away, otherwise null (it waits in garbageQueue).
7399 *
7400 * Before t1192 every received block was created at once at the spawn
7401 * row of its column. Several blocks aimed at the same column overlapped
7402 * there: the second one "landed" on the first at y ≥ 13, was culled off
7403 * the top and even counted as the receiver's own shot.
7404 */
7390 7405 GameCore.prototype.ingestGarbage = function (col)
7391 7406 {
7392 7407 if (this.state !== 'playing')
7393 7408 { return null; }
7394 var chosen = this.pickGarbageColumn(col);
7395 if (chosen == null)
7396 { return null; }
7397 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
7398 block.vy = -this.planet.fallSpeed;
7399 block.flame = false;
7400 return block;
7409 var want = (col != null && isFinite(col)) ? (col | 0) : null;
7410 var item = { col: want, block: null };
7411 this.garbageQueue.push(item);
7412 this.drainGarbageQueue();
7413 return item.block;
7414 };
7415
7416 /**
7417 * Can a block enter `col` at the spawn row now? Same rule as the opening
7418 * burst: every block already in the column must be at least a full cell
7419 * below the spawn row (no overlap).
7420 */
7421 GameCore.prototype.spawnCellClear = function (col)
7422 {
7423 for (var i = 0; i < this.blocks.length; i++)
7424 {
7425 var b = this.blocks[i];
7426 if (b.col === col && b.y > this.height - 1 + 1e-9)
7427 { return false; }
7428 }
7429 return true;
7430 };
7431
7432 /** Columns a queued garbage block can drop into right now (t1192). */
7433 GameCore.prototype.garbageDropColumns = function ()
7434 {
7435 var open = this.eligibleGarbageColumns();
7436 var departing = this.departingColumns();
7437 var out = [];
7438 for (var i = 0; i < open.length; i++)
7439 {
7440 var c = open[i];
7441 if (departing[c])
7442 { continue; }
7443 // Room left for one more block once everything in flight lands.
7444 if (this.groundedCount(c) + this.fallingCount(c) >= this.height)
7445 { continue; }
7446 if (!this.spawnCellClear(c))
7447 { continue; }
7448 out.push(c);
7449 }
7450 return out;
7451 };
7452
7453 /**
7454 * Drop queued garbage in arrival order while there is room. The wanted
7455 * column (server land_col / bot pick) wins when it can take a block,
7456 * otherwise a random open one. When nothing is open the rest waits.
7457 * Returns how many blocks dropped.
7458 */
7459 GameCore.prototype.drainGarbageQueue = function ()
7460 {
7461 var dropped = 0;
7462 while (this.garbageQueue.length && this.state === 'playing')
7463 {
7464 var cols = this.garbageDropColumns();
7465 if (!cols.length)
7466 { break; }
7467 var item = this.garbageQueue[0];
7468 var chosen = null;
7469 if (item.col != null && cols.indexOf(item.col) >= 0)
7470 { chosen = item.col; }
7471 else
7472 { chosen = cols[Math.floor(this.rng() * cols.length) % cols.length]; }
7473 this.garbageQueue.shift();
7474 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
7475 block.vy = -this.planet.fallSpeed;
7476 block.flame = false;
7477 item.block = block;
7478 dropped++;
7479 }
7480 return dropped;
7481 };
7482
7483 /** Received blocks still waiting for room (t1192). */
7484 GameCore.prototype.pendingGarbage = function ()
7485 {
7486 return this.garbageQueue.length;
7401 7487 };
7402 7488
7403 7489 GameCore.prototype.advanceSettle = function (dt)
@@ -5179,6 +5179,8 @@ function GameCore (planet, rng)
5179 this.drag = null;
5179 this.drag = null;
5180 this.gameOverTime = 0;
5180 this.gameOverTime = 0;
5181 this.outgoingShots = [];
5181 this.outgoingShots = [];
5182 /** Received garbage waiting for room (t1192). */
5183 this.garbageQueue = [];
5182 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
5184 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
5183 this.missChance = optsMissChance(arguments);
5185 this.missChance = optsMissChance(arguments);
5184 // t1112: invariant checker. strictInvariants throws (tests);
5186 // t1112: invariant checker. strictInvariants throws (tests);
@@ -5683,6 +5685,9 @@ GameCore.prototype.tick = function (dt)
5683
5685
5684 // t1189: spawn timeline by elapsed play time (intro burst, ramp, then
5686 // t1189: spawn timeline by elapsed play time (intro burst, ramp, then
5685 // the per-spawn speed-up). Interval is re-read after every spawn.
5687 // the per-spawn speed-up). Interval is re-read after every spawn.
5688 // t1192: waiting received blocks drop first, as soon as there is room.
5689 if (this.garbageQueue.length)
5690 { this.drainGarbageQueue(); }
5686 this.spawnTimer += dt;
5691 this.spawnTimer += dt;
5687 var iv = this.currentSpawnInterval();
5692 var iv = this.currentSpawnInterval();
5688 while (this.spawnTimer >= iv)
5693 while (this.spawnTimer >= iv)
@@ -7387,17 +7392,98 @@ GameCore.prototype.pickGarbageColumn = function (preferred)
7387 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
7392 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
7388};
7393};
7389
7394
7395/**
7396 * Receive one garbage block (t1192). It is queued and dropped as soon as
7397 * there is room; received blocks are never lost. Returns the block when
7398 * it could drop right away, otherwise null (it waits in garbageQueue).
7399 *
7400 * Before t1192 every received block was created at once at the spawn
7401 * row of its column. Several blocks aimed at the same column overlapped
7402 * there: the second one "landed" on the first at y ≥ 13, was culled off
7403 * the top and even counted as the receiver's own shot.
7404 */
7390GameCore.prototype.ingestGarbage = function (col)
7405GameCore.prototype.ingestGarbage = function (col)
7391{
7406{
7392 if (this.state !== 'playing')
7407 if (this.state !== 'playing')
7393 { return null; }
7408 { return null; }
7394 var chosen = this.pickGarbageColumn(col);
7409 var want = (col != null && isFinite(col)) ? (col | 0) : null;
7395 if (chosen == null)
7410 var item = { col: want, block: null };
7396 { return null; }
7411 this.garbageQueue.push(item);
7397 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
7412 this.drainGarbageQueue();
7398 block.vy = -this.planet.fallSpeed;
7413 return item.block;
7399 block.flame = false;
7414};
7400 return block;
7415
7416/**
7417 * Can a block enter `col` at the spawn row now? Same rule as the opening
7418 * burst: every block already in the column must be at least a full cell
7419 * below the spawn row (no overlap).
7420 */
7421GameCore.prototype.spawnCellClear = function (col)
7422{
7423 for (var i = 0; i < this.blocks.length; i++)
7424 {
7425 var b = this.blocks[i];
7426 if (b.col === col && b.y > this.height - 1 + 1e-9)
7427 { return false; }
7428 }
7429 return true;
7430};
7431
7432/** Columns a queued garbage block can drop into right now (t1192). */
7433GameCore.prototype.garbageDropColumns = function ()
7434{
7435 var open = this.eligibleGarbageColumns();
7436 var departing = this.departingColumns();
7437 var out = [];
7438 for (var i = 0; i < open.length; i++)
7439 {
7440 var c = open[i];
7441 if (departing[c])
7442 { continue; }
7443 // Room left for one more block once everything in flight lands.
7444 if (this.groundedCount(c) + this.fallingCount(c) >= this.height)
7445 { continue; }
7446 if (!this.spawnCellClear(c))
7447 { continue; }
7448 out.push(c);
7449 }
7450 return out;
7451};
7452
7453/**
7454 * Drop queued garbage in arrival order while there is room. The wanted
7455 * column (server land_col / bot pick) wins when it can take a block,
7456 * otherwise a random open one. When nothing is open the rest waits.
7457 * Returns how many blocks dropped.
7458 */
7459GameCore.prototype.drainGarbageQueue = function ()
7460{
7461 var dropped = 0;
7462 while (this.garbageQueue.length && this.state === 'playing')
7463 {
7464 var cols = this.garbageDropColumns();
7465 if (!cols.length)
7466 { break; }
7467 var item = this.garbageQueue[0];
7468 var chosen = null;
7469 if (item.col != null && cols.indexOf(item.col) >= 0)
7470 { chosen = item.col; }
7471 else
7472 { chosen = cols[Math.floor(this.rng() * cols.length) % cols.length]; }
7473 this.garbageQueue.shift();
7474 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
7475 block.vy = -this.planet.fallSpeed;
7476 block.flame = false;
7477 item.block = block;
7478 dropped++;
7479 }
7480 return dropped;
7481};
7482
7483/** Received blocks still waiting for room (t1192). */
7484GameCore.prototype.pendingGarbage = function ()
7485{
7486 return this.garbageQueue.length;
7401};
7487};
7402
7488
7403GameCore.prototype.advanceSettle = function (dt)
7489GameCore.prototype.advanceSettle = function (dt)
docs/ASSUMPTIONS.md +39 −0
@@ -1116,3 +1116,42 @@ seconde, en daarna pas de rate increase doen die we nu hebben." Daarna
1116 1116 Tests: `test/spawn-timeline.test.js`; browser:
1117 1117 `test/t1189-spawn-timeline-playwright.py URL TAG`.
1118 1118
1119 ## t1192 — ontvangen blokken gaan nooit verloren
1120
1121 Tim: bij ~5 blokken tegelijk naar iemand met nog maar twee vrije kolommen
1122 viel soms alleen het eerste blok en verdwenen de rest.
1123
1124 **Oorzaak.** `GameCore.ingestGarbage` maakte elk ontvangen blok meteen aan
1125 op de spawnrij (y = 13) van de gekozen kolom, zonder te kijken of daar al
1126 een blok zat; de gewenste kolom (`land_col`) won altijd. Meerdere blokken
1127 in dezelfde kolom lagen dus op elkaar. In de volgende tik "landde" het
1128 tweede blok op het eerste (`highestFallingBelow` → y = 13,99), waarna
1129 `cullOffTop` het als boven het scherm uit verwijderde. Erger: het telde als
1130 schot van de **ontvanger** (punt erbij en terug naar de verzender). Online
1131 en offline (bots) gebruiken dezelfde `GameCore`, dus beide hadden dit. De
1132 server en `online.js` gooien niets weg: de server markeert schoten als
1133 afgeleverd en `Online.onIncoming` roept per blok `ingestGarbage` aan.
1134
1135 **Oplossing (gedeelde `GameCore`).**
1136 - `ingestGarbage(col)` zet het blok in `garbageQueue` (volgorde van
1137 binnenkomst) en probeert meteen te droppen; geeft het blok terug als het
1138 direct viel, anders `null` (het wacht).
1139 - `drainGarbageQueue()` draait bij elke `tick` vóór het gewone spawnen.
1140 Een kolom kan een blok nemen (`garbageDropColumns`) als hij niet
1141 vergrendeld/vol is, niet vertrekkend (t1184), er na alles wat nog valt
1142 nog plek is (vast + vallend < 13), en de spawnrij vrij is
1143 (`spawnCellClear`: elk blok in de kolom minstens een hele cel onder de
1144 spawnrij — dezelfde regel als de openingsburst, nooit overlap).
1145 - De gewenste kolom wint als die kan; anders een willekeurige open kolom.
1146 Is er geen open kolom, dan blijft het blok wachten (ook als alle open
1147 kolommen door vertrekkende raketten bezet zijn — dat verving de oude
1148 terugval naar de gewenste kolom).
1149 - Na game over worden geen blokken meer aangenomen (zoals voorheen).
1150 - Online bepaalt het eigen apparaat van de ontvanger de plaatsing. De
1151 vluchtanimatie mikt nog op `land_col`; een blok dat moet wachten of
1152 uitwijkt verschijnt daarna bovenaan in de gekozen kolom.
1153
1154 Tests: `test/garbage-queue.test.js` (o.a. exact scenario: 5 tegelijk, 2
1155 open kolommen → alle 5 landen; ook via offline bots);
1156 `test/t1192-garbage-queue-playwright.py ROOT TAG` (twee browsers lokaal).
1157
@@ -1116,3 +1116,42 @@ seconde, en daarna pas de rate increase doen die we nu hebben." Daarna
1116Tests: `test/spawn-timeline.test.js`; browser:
1116Tests: `test/spawn-timeline.test.js`; browser:
1117`test/t1189-spawn-timeline-playwright.py URL TAG`.
1117`test/t1189-spawn-timeline-playwright.py URL TAG`.
1118
1118
1119## t1192 — ontvangen blokken gaan nooit verloren
1120
1121Tim: bij ~5 blokken tegelijk naar iemand met nog maar twee vrije kolommen
1122viel soms alleen het eerste blok en verdwenen de rest.
1123
1124**Oorzaak.** `GameCore.ingestGarbage` maakte elk ontvangen blok meteen aan
1125op de spawnrij (y = 13) van de gekozen kolom, zonder te kijken of daar al
1126een blok zat; de gewenste kolom (`land_col`) won altijd. Meerdere blokken
1127in dezelfde kolom lagen dus op elkaar. In de volgende tik "landde" het
1128tweede blok op het eerste (`highestFallingBelow` → y = 13,99), waarna
1129`cullOffTop` het als boven het scherm uit verwijderde. Erger: het telde als
1130schot van de **ontvanger** (punt erbij en terug naar de verzender). Online
1131en offline (bots) gebruiken dezelfde `GameCore`, dus beide hadden dit. De
1132server en `online.js` gooien niets weg: de server markeert schoten als
1133afgeleverd en `Online.onIncoming` roept per blok `ingestGarbage` aan.
1134
1135**Oplossing (gedeelde `GameCore`).**
1136- `ingestGarbage(col)` zet het blok in `garbageQueue` (volgorde van
1137 binnenkomst) en probeert meteen te droppen; geeft het blok terug als het
1138 direct viel, anders `null` (het wacht).
1139- `drainGarbageQueue()` draait bij elke `tick` vóór het gewone spawnen.
1140 Een kolom kan een blok nemen (`garbageDropColumns`) als hij niet
1141 vergrendeld/vol is, niet vertrekkend (t1184), er na alles wat nog valt
1142 nog plek is (vast + vallend < 13), en de spawnrij vrij is
1143 (`spawnCellClear`: elk blok in de kolom minstens een hele cel onder de
1144 spawnrij — dezelfde regel als de openingsburst, nooit overlap).
1145- De gewenste kolom wint als die kan; anders een willekeurige open kolom.
1146 Is er geen open kolom, dan blijft het blok wachten (ook als alle open
1147 kolommen door vertrekkende raketten bezet zijn — dat verving de oude
1148 terugval naar de gewenste kolom).
1149- Na game over worden geen blokken meer aangenomen (zoals voorheen).
1150- Online bepaalt het eigen apparaat van de ontvanger de plaatsing. De
1151 vluchtanimatie mikt nog op `land_col`; een blok dat moet wachten of
1152 uitwijkt verschijnt daarna bovenaan in de gekozen kolom.
1153
1154Tests: `test/garbage-queue.test.js` (o.a. exact scenario: 5 tegelijk, 2
1155open kolommen → alle 5 landen; ook via offline bots);
1156`test/t1192-garbage-queue-playwright.py ROOT TAG` (twee browsers lokaal).
1157
src/gameCore.js +93 −7
@@ -87,6 +87,8 @@ function GameCore (planet, rng)
87 87 this.drag = null;
88 88 this.gameOverTime = 0;
89 89 this.outgoingShots = [];
90 /** Received garbage waiting for room (t1192). */
91 this.garbageQueue = [];
90 92 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
91 93 this.missChance = optsMissChance(arguments);
92 94 // t1112: invariant checker. strictInvariants throws (tests);
@@ -591,6 +593,9 @@ GameCore.prototype.tick = function (dt)
591 593
592 594 // t1189: spawn timeline by elapsed play time (intro burst, ramp, then
593 595 // the per-spawn speed-up). Interval is re-read after every spawn.
596 // t1192: waiting received blocks drop first, as soon as there is room.
597 if (this.garbageQueue.length)
598 { this.drainGarbageQueue(); }
594 599 this.spawnTimer += dt;
595 600 var iv = this.currentSpawnInterval();
596 601 while (this.spawnTimer >= iv)
@@ -2295,17 +2300,98 @@ GameCore.prototype.pickGarbageColumn = function (preferred)
2295 2300 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2296 2301 };
2297 2302
2303 /**
2304 * Receive one garbage block (t1192). It is queued and dropped as soon as
2305 * there is room; received blocks are never lost. Returns the block when
2306 * it could drop right away, otherwise null (it waits in garbageQueue).
2307 *
2308 * Before t1192 every received block was created at once at the spawn
2309 * row of its column. Several blocks aimed at the same column overlapped
2310 * there: the second one "landed" on the first at y ≥ 13, was culled off
2311 * the top and even counted as the receiver's own shot.
2312 */
2298 2313 GameCore.prototype.ingestGarbage = function (col)
2299 2314 {
2300 2315 if (this.state !== 'playing')
2301 2316 { return null; }
2302 var chosen = this.pickGarbageColumn(col);
2303 if (chosen == null)
2304 { return null; }
2305 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2306 block.vy = -this.planet.fallSpeed;
2307 block.flame = false;
2308 return block;
2317 var want = (col != null && isFinite(col)) ? (col | 0) : null;
2318 var item = { col: want, block: null };
2319 this.garbageQueue.push(item);
2320 this.drainGarbageQueue();
2321 return item.block;
2322 };
2323
2324 /**
2325 * Can a block enter `col` at the spawn row now? Same rule as the opening
2326 * burst: every block already in the column must be at least a full cell
2327 * below the spawn row (no overlap).
2328 */
2329 GameCore.prototype.spawnCellClear = function (col)
2330 {
2331 for (var i = 0; i < this.blocks.length; i++)
2332 {
2333 var b = this.blocks[i];
2334 if (b.col === col && b.y > this.height - 1 + 1e-9)
2335 { return false; }
2336 }
2337 return true;
2338 };
2339
2340 /** Columns a queued garbage block can drop into right now (t1192). */
2341 GameCore.prototype.garbageDropColumns = function ()
2342 {
2343 var open = this.eligibleGarbageColumns();
2344 var departing = this.departingColumns();
2345 var out = [];
2346 for (var i = 0; i < open.length; i++)
2347 {
2348 var c = open[i];
2349 if (departing[c])
2350 { continue; }
2351 // Room left for one more block once everything in flight lands.
2352 if (this.groundedCount(c) + this.fallingCount(c) >= this.height)
2353 { continue; }
2354 if (!this.spawnCellClear(c))
2355 { continue; }
2356 out.push(c);
2357 }
2358 return out;
2359 };
2360
2361 /**
2362 * Drop queued garbage in arrival order while there is room. The wanted
2363 * column (server land_col / bot pick) wins when it can take a block,
2364 * otherwise a random open one. When nothing is open the rest waits.
2365 * Returns how many blocks dropped.
2366 */
2367 GameCore.prototype.drainGarbageQueue = function ()
2368 {
2369 var dropped = 0;
2370 while (this.garbageQueue.length && this.state === 'playing')
2371 {
2372 var cols = this.garbageDropColumns();
2373 if (!cols.length)
2374 { break; }
2375 var item = this.garbageQueue[0];
2376 var chosen = null;
2377 if (item.col != null && cols.indexOf(item.col) >= 0)
2378 { chosen = item.col; }
2379 else
2380 { chosen = cols[Math.floor(this.rng() * cols.length) % cols.length]; }
2381 this.garbageQueue.shift();
2382 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2383 block.vy = -this.planet.fallSpeed;
2384 block.flame = false;
2385 item.block = block;
2386 dropped++;
2387 }
2388 return dropped;
2389 };
2390
2391 /** Received blocks still waiting for room (t1192). */
2392 GameCore.prototype.pendingGarbage = function ()
2393 {
2394 return this.garbageQueue.length;
2309 2395 };
2310 2396
2311 2397 GameCore.prototype.advanceSettle = function (dt)
@@ -87,6 +87,8 @@ function GameCore (planet, rng)
87 this.drag = null;
87 this.drag = null;
88 this.gameOverTime = 0;
88 this.gameOverTime = 0;
89 this.outgoingShots = [];
89 this.outgoingShots = [];
90 /** Received garbage waiting for room (t1192). */
91 this.garbageQueue = [];
90 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
92 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
91 this.missChance = optsMissChance(arguments);
93 this.missChance = optsMissChance(arguments);
92 // t1112: invariant checker. strictInvariants throws (tests);
94 // t1112: invariant checker. strictInvariants throws (tests);
@@ -591,6 +593,9 @@ GameCore.prototype.tick = function (dt)
591
593
592 // t1189: spawn timeline by elapsed play time (intro burst, ramp, then
594 // t1189: spawn timeline by elapsed play time (intro burst, ramp, then
593 // the per-spawn speed-up). Interval is re-read after every spawn.
595 // the per-spawn speed-up). Interval is re-read after every spawn.
596 // t1192: waiting received blocks drop first, as soon as there is room.
597 if (this.garbageQueue.length)
598 { this.drainGarbageQueue(); }
594 this.spawnTimer += dt;
599 this.spawnTimer += dt;
595 var iv = this.currentSpawnInterval();
600 var iv = this.currentSpawnInterval();
596 while (this.spawnTimer >= iv)
601 while (this.spawnTimer >= iv)
@@ -2295,17 +2300,98 @@ GameCore.prototype.pickGarbageColumn = function (preferred)
2295 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2300 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2296};
2301};
2297
2302
2303/**
2304 * Receive one garbage block (t1192). It is queued and dropped as soon as
2305 * there is room; received blocks are never lost. Returns the block when
2306 * it could drop right away, otherwise null (it waits in garbageQueue).
2307 *
2308 * Before t1192 every received block was created at once at the spawn
2309 * row of its column. Several blocks aimed at the same column overlapped
2310 * there: the second one "landed" on the first at y ≥ 13, was culled off
2311 * the top and even counted as the receiver's own shot.
2312 */
2298GameCore.prototype.ingestGarbage = function (col)
2313GameCore.prototype.ingestGarbage = function (col)
2299{
2314{
2300 if (this.state !== 'playing')
2315 if (this.state !== 'playing')
2301 { return null; }
2316 { return null; }
2302 var chosen = this.pickGarbageColumn(col);
2317 var want = (col != null && isFinite(col)) ? (col | 0) : null;
2303 if (chosen == null)
2318 var item = { col: want, block: null };
2304 { return null; }
2319 this.garbageQueue.push(item);
2305 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2320 this.drainGarbageQueue();
2306 block.vy = -this.planet.fallSpeed;
2321 return item.block;
2307 block.flame = false;
2322};
2308 return block;
2323
2324/**
2325 * Can a block enter `col` at the spawn row now? Same rule as the opening
2326 * burst: every block already in the column must be at least a full cell
2327 * below the spawn row (no overlap).
2328 */
2329GameCore.prototype.spawnCellClear = function (col)
2330{
2331 for (var i = 0; i < this.blocks.length; i++)
2332 {
2333 var b = this.blocks[i];
2334 if (b.col === col && b.y > this.height - 1 + 1e-9)
2335 { return false; }
2336 }
2337 return true;
2338};
2339
2340/** Columns a queued garbage block can drop into right now (t1192). */
2341GameCore.prototype.garbageDropColumns = function ()
2342{
2343 var open = this.eligibleGarbageColumns();
2344 var departing = this.departingColumns();
2345 var out = [];
2346 for (var i = 0; i < open.length; i++)
2347 {
2348 var c = open[i];
2349 if (departing[c])
2350 { continue; }
2351 // Room left for one more block once everything in flight lands.
2352 if (this.groundedCount(c) + this.fallingCount(c) >= this.height)
2353 { continue; }
2354 if (!this.spawnCellClear(c))
2355 { continue; }
2356 out.push(c);
2357 }
2358 return out;
2359};
2360
2361/**
2362 * Drop queued garbage in arrival order while there is room. The wanted
2363 * column (server land_col / bot pick) wins when it can take a block,
2364 * otherwise a random open one. When nothing is open the rest waits.
2365 * Returns how many blocks dropped.
2366 */
2367GameCore.prototype.drainGarbageQueue = function ()
2368{
2369 var dropped = 0;
2370 while (this.garbageQueue.length && this.state === 'playing')
2371 {
2372 var cols = this.garbageDropColumns();
2373 if (!cols.length)
2374 { break; }
2375 var item = this.garbageQueue[0];
2376 var chosen = null;
2377 if (item.col != null && cols.indexOf(item.col) >= 0)
2378 { chosen = item.col; }
2379 else
2380 { chosen = cols[Math.floor(this.rng() * cols.length) % cols.length]; }
2381 this.garbageQueue.shift();
2382 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2383 block.vy = -this.planet.fallSpeed;
2384 block.flame = false;
2385 item.block = block;
2386 dropped++;
2387 }
2388 return dropped;
2389};
2390
2391/** Received blocks still waiting for room (t1192). */
2392GameCore.prototype.pendingGarbage = function ()
2393{
2394 return this.garbageQueue.length;
2309};
2395};
2310
2396
2311GameCore.prototype.advanceSettle = function (dt)
2397GameCore.prototype.advanceSettle = function (dt)
test/departing.test.js +7 −4
@@ -105,7 +105,7 @@ describe('Departing rocket columns (t1184)', () =>
105 105 assert.deepEqual(Object.keys(g.departingColumns()), []);
106 106 });
107 107
108 it('if every open column is departing, garbage still arrives (never lost)', () =>
108 it('if every open column is departing, garbage waits and arrives later (never lost)', () =>
109 109 {
110 110 const g = makeGame({ noSpawn: true });
111 111 const all = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
@@ -113,9 +113,12 @@ describe('Departing rocket columns (t1184)', () =>
113 113 riseUntil(g, row, cluster, 10);
114 114 assert.equal(Object.keys(g.departingColumns()).length, 10);
115 115 assert.equal(g.trySpawn(), null, 'no new block while every column is departing');
116 const b = g.ingestGarbage(4);
117 assert.ok(b, 'garbage kept');
118 assert.equal(b.col, 4);
116 // t1192: it waits in the queue (not dropped into the rocket, not lost).
117 assert.equal(g.ingestGarbage(4), null);
118 assert.equal(g.pendingGarbage(), 1);
119 for (let i = 0; i < 600 && g.pendingGarbage(); i++) g.step(1 / 120, 1 / 120);
120 assert.equal(g.pendingGarbage(), 0, 'dropped once the rocket left');
121 assert.ok(g.blocks.some((x) => x.color === -1 && x.state === 'falling' && x.col === 4), 'in the wanted column');
119 122 });
120 123
121 124 it('the stack really leaves and the columns open up again', () =>
@@ -105,7 +105,7 @@ describe('Departing rocket columns (t1184)', () =>
105 assert.deepEqual(Object.keys(g.departingColumns()), []);
105 assert.deepEqual(Object.keys(g.departingColumns()), []);
106 });
106 });
107
107
108 it('if every open column is departing, garbage still arrives (never lost)', () =>
108 it('if every open column is departing, garbage waits and arrives later (never lost)', () =>
109 {
109 {
110 const g = makeGame({ noSpawn: true });
110 const g = makeGame({ noSpawn: true });
111 const all = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
111 const all = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
@@ -113,9 +113,12 @@ describe('Departing rocket columns (t1184)', () =>
113 riseUntil(g, row, cluster, 10);
113 riseUntil(g, row, cluster, 10);
114 assert.equal(Object.keys(g.departingColumns()).length, 10);
114 assert.equal(Object.keys(g.departingColumns()).length, 10);
115 assert.equal(g.trySpawn(), null, 'no new block while every column is departing');
115 assert.equal(g.trySpawn(), null, 'no new block while every column is departing');
116 const b = g.ingestGarbage(4);
116 // t1192: it waits in the queue (not dropped into the rocket, not lost).
117 assert.ok(b, 'garbage kept');
117 assert.equal(g.ingestGarbage(4), null);
118 assert.equal(b.col, 4);
118 assert.equal(g.pendingGarbage(), 1);
119 for (let i = 0; i < 600 && g.pendingGarbage(); i++) g.step(1 / 120, 1 / 120);
120 assert.equal(g.pendingGarbage(), 0, 'dropped once the rocket left');
121 assert.ok(g.blocks.some((x) => x.color === -1 && x.state === 'falling' && x.col === 4), 'in the wanted column');
119 });
122 });
120
123
121 it('the stack really leaves and the columns open up again', () =>
124 it('the stack really leaves and the columns open up again', () =>
test/garbage-queue.test.js added +166 −0
@@ -0,0 +1,166 @@
1 'use strict';
2
3 // t1192: received blocks queue and are never lost.
4
5 const { describe, it } = require('node:test');
6 const assert = require('node:assert/strict');
7 const { makeGame } = require('./helpers.js');
8 const { GameCore } = require('../src/gameCore.js');
9
10 const GRAY = GameCore.COLOR_GRAY;
11
12 function lockedExcept (g, open)
13 {
14 for (let c = 0; c < g.width; c++)
15 {
16 if (open.includes(c)) continue;
17 for (let r = 0; r < g.height; r++) g.place(c, r, (r + c) % 5, 'locked');
18 }
19 }
20
21 function run (g, seconds, onShot)
22 {
23 let shots = 0;
24 for (let i = 0; i < Math.round(seconds * 120); i++)
25 {
26 g.step(1 / 120, 1 / 120);
27 shots += g.consumeOutgoingShots().length;
28 }
29 return shots;
30 }
31
32 function grayCount (g, cols)
33 {
34 return g.blocks.filter((b) => cols.includes(b.col) && (b.color === GRAY || b.garbage)).length;
35 }
36
37 describe('Received garbage queue (t1192)', () =>
38 {
39 it('exact scenario: 5 blocks at once, 2 open columns, all aimed at one → all 5 land', () =>
40 {
41 for (const seed of [1, 2, 3, 4, 5, 6])
42 {
43 const g = makeGame({ noSpawn: true, seed });
44 lockedExcept(g, [3, 7]);
45 const before = g.blocks.length;
46 for (let i = 0; i < 5; i++) g.ingestGarbage(3);
47 const shots = run(g, 8);
48 assert.equal(g.pendingGarbage(), 0, 'queue drained (seed ' + seed + ')');
49 assert.equal(g.blocks.length - before, 5, 'all 5 on the field (seed ' + seed + ')');
50 assert.equal(shots, 0, 'none culled off the top / sent back');
51 assert.equal(g.score, 0, 'receiver gains no points from them');
52 // Stacked without overlap in columns 3 and 7.
53 for (const c of [3, 7])
54 {
55 const ys = g.blocksInColumn(c).map((b) => b.y);
56 ys.forEach((y, k) => assert.equal(y, k, 'col ' + c + ' row ' + k));
57 }
58 }
59 });
60
61 it('random aims with 2 open columns: still all 5 land', () =>
62 {
63 const g = makeGame({ noSpawn: true, seed: 9 });
64 lockedExcept(g, [0, 9]);
65 const before = g.blocks.length;
66 for (const c of [0, 9, 0, 4, 9]) g.ingestGarbage(c);
67 run(g, 8);
68 assert.equal(g.blocks.length - before, 5);
69 assert.equal(g.pendingGarbage(), 0);
70 });
71
72 it('blocks in one column never overlap and drop only after a full cell of clearance', () =>
73 {
74 const g = makeGame({ noSpawn: true, seed: 2 });
75 lockedExcept(g, [5]);
76 for (let i = 0; i < 3; i++) g.ingestGarbage(5);
77 assert.equal(g.pendingGarbage(), 2, 'one drops now, two wait');
78 let minGap = Infinity;
79 for (let i = 0; i < 120 * 6; i++)
80 {
81 g.step(1 / 120, 1 / 120);
82 const col = g.blocksInColumn(5);
83 for (let k = 1; k < col.length; k++) minGap = Math.min(minGap, col[k].y - col[k - 1].y);
84 }
85 assert.ok(minGap >= 1 - 1e-6, 'min gap ' + minGap);
86 assert.equal(g.blocksInColumn(5).length, 3);
87 });
88
89 it('no open column: garbage waits (not dropped, not lost) and lands when room appears', () =>
90 {
91 const g = makeGame({ noSpawn: true, seed: 3 });
92 lockedExcept(g, [2]);
93 // The only open column holds a rocket that is leaving (t1184).
94 const r = g.place(2, 0, 1);
95 const cluster = g.launchCluster([r], 30);
96 for (let i = 0; i < 400 && r.y < 10; i++) g.step(1 / 120, 1 / 120);
97 assert.ok(g.departingColumns()[2]);
98 assert.equal(g.ingestGarbage(2), null);
99 assert.equal(g.ingestGarbage(7), null);
100 assert.equal(g.pendingGarbage(), 2, 'both wait');
101 run(g, 5);
102 assert.equal(g.state, 'playing');
103 assert.equal(g.pendingGarbage(), 0, 'dropped after the rocket left');
104 assert.equal(g.blocksInColumn(2).filter((b) => b.color === GRAY).length, 2);
105 assert.ok(cluster);
106 });
107
108 it('a full column (counting blocks still falling) is skipped for another open one', () =>
109 {
110 const g = makeGame({ noSpawn: true, seed: 4 });
111 lockedExcept(g, [1, 6]);
112 for (let r = 0; r < 12; r++) g.place(1, r, r % 5, 'still'); // one cell left in col 1
113 const before = g.blocks.length;
114 for (let i = 0; i < 4; i++) g.ingestGarbage(1);
115 run(g, 10);
116 assert.equal(g.blocks.length - before, 4);
117 assert.equal(g.blocksInColumn(1).length, 13, 'col 1 filled to the top, not beyond');
118 assert.equal(g.blocksInColumn(6).length, 3, 'rest went to col 6');
119 assert.equal(g.pendingGarbage(), 0);
120 });
121
122 it('open wanted column wins; a free field takes all at once in distinct columns', () =>
123 {
124 const g = makeGame({ noSpawn: true, seed: 5 });
125 const a = g.ingestGarbage(4);
126 assert.equal(a.col, 4);
127 const b = g.ingestGarbage(4);
128 assert.ok(b && b.col !== 4, 'second picks another column instead of overlapping');
129 assert.equal(g.pendingGarbage(), 0);
130 });
131
132 it('garbage is not accepted after game over (as before)', () =>
133 {
134 const g = makeGame({ noSpawn: true });
135 g.state = 'gameover';
136 assert.equal(g.ingestGarbage(1), null);
137 assert.equal(g.pendingGarbage(), 0);
138 });
139 });
140
141 describe('Received garbage queue — offline bots (t1192)', () =>
142 {
143 it('5 shots at once to a bot with 2 open columns: all 5 land on the bot', () =>
144 {
145 const { Planet, Rng } = require('./helpers.js');
146 const Offline = require('../src/offline.js');
147 const battle = Offline.createBattle({ playerPlanet: Planet.defaultPlanet(), rng: Rng.create(7), round: 1 });
148 const bot = battle.bots[0];
149 const core = bot.core;
150 core.spawnInterval = 1e9;
151 lockedExcept(core, [2, 8]);
152 const before = core.blocks.length;
153 for (let i = 0; i < 5; i++)
154 { battle.pending.push({ at: battle.clock, targetId: bot.id, color: 1, fromId: 'me', landCol: 2 }); }
155 const player = makeGame({ noSpawn: true });
156 for (let i = 0; i < 120 * 8; i++)
157 {
158 battle.clock += 1 / 120;
159 battle._deliver(player);
160 core.step(1 / 120, 1 / 120);
161 core.consumeOutgoingShots();
162 }
163 assert.equal(core.pendingGarbage(), 0);
164 assert.equal(core.blocks.length - before, 5, 'all 5 on the bot field');
165 });
166 });
@@ -0,0 +1,166 @@
1'use strict';
2
3// t1192: received blocks queue and are never lost.
4
5const { describe, it } = require('node:test');
6const assert = require('node:assert/strict');
7const { makeGame } = require('./helpers.js');
8const { GameCore } = require('../src/gameCore.js');
9
10const GRAY = GameCore.COLOR_GRAY;
11
12function lockedExcept (g, open)
13{
14 for (let c = 0; c < g.width; c++)
15 {
16 if (open.includes(c)) continue;
17 for (let r = 0; r < g.height; r++) g.place(c, r, (r + c) % 5, 'locked');
18 }
19}
20
21function run (g, seconds, onShot)
22{
23 let shots = 0;
24 for (let i = 0; i < Math.round(seconds * 120); i++)
25 {
26 g.step(1 / 120, 1 / 120);
27 shots += g.consumeOutgoingShots().length;
28 }
29 return shots;
30}
31
32function grayCount (g, cols)
33{
34 return g.blocks.filter((b) => cols.includes(b.col) && (b.color === GRAY || b.garbage)).length;
35}
36
37describe('Received garbage queue (t1192)', () =>
38{
39 it('exact scenario: 5 blocks at once, 2 open columns, all aimed at one → all 5 land', () =>
40 {
41 for (const seed of [1, 2, 3, 4, 5, 6])
42 {
43 const g = makeGame({ noSpawn: true, seed });
44 lockedExcept(g, [3, 7]);
45 const before = g.blocks.length;
46 for (let i = 0; i < 5; i++) g.ingestGarbage(3);
47 const shots = run(g, 8);
48 assert.equal(g.pendingGarbage(), 0, 'queue drained (seed ' + seed + ')');
49 assert.equal(g.blocks.length - before, 5, 'all 5 on the field (seed ' + seed + ')');
50 assert.equal(shots, 0, 'none culled off the top / sent back');
51 assert.equal(g.score, 0, 'receiver gains no points from them');
52 // Stacked without overlap in columns 3 and 7.
53 for (const c of [3, 7])
54 {
55 const ys = g.blocksInColumn(c).map((b) => b.y);
56 ys.forEach((y, k) => assert.equal(y, k, 'col ' + c + ' row ' + k));
57 }
58 }
59 });
60
61 it('random aims with 2 open columns: still all 5 land', () =>
62 {
63 const g = makeGame({ noSpawn: true, seed: 9 });
64 lockedExcept(g, [0, 9]);
65 const before = g.blocks.length;
66 for (const c of [0, 9, 0, 4, 9]) g.ingestGarbage(c);
67 run(g, 8);
68 assert.equal(g.blocks.length - before, 5);
69 assert.equal(g.pendingGarbage(), 0);
70 });
71
72 it('blocks in one column never overlap and drop only after a full cell of clearance', () =>
73 {
74 const g = makeGame({ noSpawn: true, seed: 2 });
75 lockedExcept(g, [5]);
76 for (let i = 0; i < 3; i++) g.ingestGarbage(5);
77 assert.equal(g.pendingGarbage(), 2, 'one drops now, two wait');
78 let minGap = Infinity;
79 for (let i = 0; i < 120 * 6; i++)
80 {
81 g.step(1 / 120, 1 / 120);
82 const col = g.blocksInColumn(5);
83 for (let k = 1; k < col.length; k++) minGap = Math.min(minGap, col[k].y - col[k - 1].y);
84 }
85 assert.ok(minGap >= 1 - 1e-6, 'min gap ' + minGap);
86 assert.equal(g.blocksInColumn(5).length, 3);
87 });
88
89 it('no open column: garbage waits (not dropped, not lost) and lands when room appears', () =>
90 {
91 const g = makeGame({ noSpawn: true, seed: 3 });
92 lockedExcept(g, [2]);
93 // The only open column holds a rocket that is leaving (t1184).
94 const r = g.place(2, 0, 1);
95 const cluster = g.launchCluster([r], 30);
96 for (let i = 0; i < 400 && r.y < 10; i++) g.step(1 / 120, 1 / 120);
97 assert.ok(g.departingColumns()[2]);
98 assert.equal(g.ingestGarbage(2), null);
99 assert.equal(g.ingestGarbage(7), null);
100 assert.equal(g.pendingGarbage(), 2, 'both wait');
101 run(g, 5);
102 assert.equal(g.state, 'playing');
103 assert.equal(g.pendingGarbage(), 0, 'dropped after the rocket left');
104 assert.equal(g.blocksInColumn(2).filter((b) => b.color === GRAY).length, 2);
105 assert.ok(cluster);
106 });
107
108 it('a full column (counting blocks still falling) is skipped for another open one', () =>
109 {
110 const g = makeGame({ noSpawn: true, seed: 4 });
111 lockedExcept(g, [1, 6]);
112 for (let r = 0; r < 12; r++) g.place(1, r, r % 5, 'still'); // one cell left in col 1
113 const before = g.blocks.length;
114 for (let i = 0; i < 4; i++) g.ingestGarbage(1);
115 run(g, 10);
116 assert.equal(g.blocks.length - before, 4);
117 assert.equal(g.blocksInColumn(1).length, 13, 'col 1 filled to the top, not beyond');
118 assert.equal(g.blocksInColumn(6).length, 3, 'rest went to col 6');
119 assert.equal(g.pendingGarbage(), 0);
120 });
121
122 it('open wanted column wins; a free field takes all at once in distinct columns', () =>
123 {
124 const g = makeGame({ noSpawn: true, seed: 5 });
125 const a = g.ingestGarbage(4);
126 assert.equal(a.col, 4);
127 const b = g.ingestGarbage(4);
128 assert.ok(b && b.col !== 4, 'second picks another column instead of overlapping');
129 assert.equal(g.pendingGarbage(), 0);
130 });
131
132 it('garbage is not accepted after game over (as before)', () =>
133 {
134 const g = makeGame({ noSpawn: true });
135 g.state = 'gameover';
136 assert.equal(g.ingestGarbage(1), null);
137 assert.equal(g.pendingGarbage(), 0);
138 });
139});
140
141describe('Received garbage queue — offline bots (t1192)', () =>
142{
143 it('5 shots at once to a bot with 2 open columns: all 5 land on the bot', () =>
144 {
145 const { Planet, Rng } = require('./helpers.js');
146 const Offline = require('../src/offline.js');
147 const battle = Offline.createBattle({ playerPlanet: Planet.defaultPlanet(), rng: Rng.create(7), round: 1 });
148 const bot = battle.bots[0];
149 const core = bot.core;
150 core.spawnInterval = 1e9;
151 lockedExcept(core, [2, 8]);
152 const before = core.blocks.length;
153 for (let i = 0; i < 5; i++)
154 { battle.pending.push({ at: battle.clock, targetId: bot.id, color: 1, fromId: 'me', landCol: 2 }); }
155 const player = makeGame({ noSpawn: true });
156 for (let i = 0; i < 120 * 8; i++)
157 {
158 battle.clock += 1 / 120;
159 battle._deliver(player);
160 core.step(1 / 120, 1 / 120);
161 core.consumeOutgoingShots();
162 }
163 assert.equal(core.pendingGarbage(), 0);
164 assert.equal(core.blocks.length - before, 5, 'all 5 on the bot field');
165 });
166});
test/t1192-garbage-queue-playwright.py added +188 −0
@@ -0,0 +1,188 @@
1 #!/usr/bin/env python3
2 """t1192: 5 blocks at once to an opponent with 2 open columns — none may be lost.
3
4 Usage: t1181-flights-playwright.py [ROOT] [TAG]
5 ROOT defaults to /workspace/meteors (its build/ is served by php -S).
6 Desktop (1280x800) is the sender; mobile (390x844, touch, DPR 3) is the receiver.
7 Writes /workspace/meteors-shots/t1181-<TAG>-*.png and prints JSON metrics.
8 """
9 from __future__ import annotations
10
11 import json
12 import os
13 import socket
14 import subprocess
15 import sys
16 import tempfile
17 import time
18 from pathlib import Path
19
20 from playwright.sync_api import sync_playwright
21
22 ROOT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/workspace/meteors")
23 TAG = sys.argv[2] if len(sys.argv) > 2 else "after"
24 ROUNDS = 3
25 SHOTS = Path("/workspace/meteors-shots")
26 SHOTS.mkdir(parents=True, exist_ok=True)
27 PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
28 CHROME = "/usr/bin/google-chrome"
29 ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
30 FAILURES = []
31 URL = None
32
33 # Records, per frame, every flight element's on-screen centre, plus the
34 # Date.now() when each of my shots left the field (cull).
35 PROBE = """() => {
36 if (window.__probe) return;
37 const P = window.__probe = { culls: {}, tracks: {}, frames: 0 };
38 const orig = GameCore.prototype.consumeOutgoingShots;
39 GameCore.prototype.consumeOutgoingShots = function () {
40 const shots = orig.call(this);
41 if (this === app.core) for (const s of shots) P.culls[String(s.id)] = Date.now();
42 return shots;
43 };
44 let ids = new WeakMap(); let next = 1;
45 function f() {
46 P.frames++;
47 const now = Date.now();
48 for (const el of document.querySelectorAll('#flights .flight, #flights-back .flight')) {
49 if (!ids.has(el)) ids.set(el, 'el' + (next++));
50 const k = ids.get(el);
51 const r = el.getBoundingClientRect();
52 if (!r.width) continue;
53 (P.tracks[k] = P.tracks[k] || []).push([now, r.left + r.width / 2, r.top + r.height / 2]);
54 }
55 requestAnimationFrame(f);
56 }
57 requestAnimationFrame(f);
58 }"""
59
60 SHOOT = """(n) => {
61 const out = [];
62 for (let i = 0; i < n; i++) {
63 const b = app.core.createBlock(2 + 2 * i, 13.0, i % 5, 'flying');
64 b.vy = 6;
65 out.push(b.id);
66 }
67 return out;
68 }"""
69
70
71 def check(cond, msg):
72 print(("OK " if cond else "FAIL") + " " + msg)
73 if not cond:
74 FAILURES.append(msg)
75 return cond
76
77
78 def free_port():
79 s = socket.socket(); s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]; s.close(); return port
80
81
82 def start_php(port, data):
83 env = os.environ.copy(); env["METEORS_DATA_DIR"] = str(data)
84 log = open(f"/tmp/t1192-php-{TAG}.log", "w")
85 proc = subprocess.Popen([PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
86 cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log)
87 time.sleep(0.5)
88 return proc
89
90
91 def login(page, n):
92 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded")
93 page.wait_for_timeout(300)
94 page.goto(f"{URL}index.html?online=1", wait_until="domcontentloaded")
95 page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)
96 page.locator("#online-panel").wait_for(state="visible", timeout=8000)
97
98
99
100 SETUP_RECEIVER = """() => {
101 const g = app.core;
102 g.spawnInterval = 1e9; g.playTime = 99;
103 for (const b of g.blocks.slice()) g.removeBlock(b);
104 for (let c = 0; c < 10; c++) { if (c === 3 || c === 7) continue; for (let r = 0; r < 13; r++) g.place(c, r, (r + c) % 5, 'locked'); }
105 const R = window.__recv = { incoming: 0, ownShots: 0 };
106 const origIn = Online.onIncoming;
107 Online.onIncoming = function (list) { R.incoming += list.length; return origIn.apply(this, arguments); };
108 const origC = GameCore.prototype.consumeOutgoingShots;
109 GameCore.prototype.consumeOutgoingShots = function () { const s = origC.call(this); if (this === app.core) R.ownShots += s.length; return s; };
110 }"""
111
112 COUNT = """() => {
113 const g = app.core;
114 const gray = g.blocks.filter(b => (b.col === 3 || b.col === 7)).length;
115 return { inOpen: gray, pending: g.pendingGarbage ? g.pendingGarbage() : null, incoming: window.__recv.incoming,
116 ownShots: window.__recv.ownShots, state: g.state, score: g.score };
117 }"""
118
119 SHOOT5 = """() => { for (let i = 0; i < 5; i++) { const b = app.core.createBlock(i * 2, 13.0, i % 5, 'flying'); b.vy = 6; } }"""
120
121
122 def main():
123 global URL
124 port = free_port(); URL = f"http://127.0.0.1:{port}/"
125 proc = start_php(port, Path(tempfile.mkdtemp(prefix="meteors-t1192-")))
126 m = {"rounds": []}
127 try:
128 with sync_playwright() as p:
129 b = p.chromium.launch(executable_path=CHROME, args=ARGS, headless=True)
130 c1 = b.new_context(viewport={"width": 1280, "height": 800})
131 c2 = b.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=3)
132 p1, p2 = c1.new_page(), c2.new_page()
133 errs = []
134 for pg, tag in ((p1, "desktop"), (p2, "mobile")):
135 pg.on("pageerror", lambda e, tag=tag: errs.append(f"{tag}: {e}"))
136 login(p1, 1); login(p2, 2)
137 p1.locator("#btn-create").click()
138 p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000)
139 code = p1.locator("#lobby-code").inner_text().strip()
140 p2.locator("#join-code").fill(code); p2.locator("#btn-join").click()
141 p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
142 p1.locator("#btn-ready").click(); p2.locator("#btn-ready").click()
143 start = p1.locator("#btn-start")
144 for _ in range(20):
145 if start.is_visible() and start.is_enabled():
146 break
147 p1.wait_for_timeout(400)
148 start.click()
149 for pg in (p1, p2):
150 pg.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
151 p1.evaluate("() => { app.core.spawnInterval = 1e9; app.core.playTime = 99; for (const b of app.core.blocks.slice()) app.core.removeBlock(b); }")
152 p2.evaluate(SETUP_RECEIVER)
153 p1.wait_for_timeout(500)
154 for rnd in range(ROUNDS):
155 before = p2.evaluate(COUNT)
156 p1.evaluate(SHOOT5)
157 if rnd == 0:
158 p2.wait_for_timeout(1500)
159 p2.screenshot(path=str(SHOTS / f"t1192-{TAG}-mobile-receiving.png"))
160 p1.screenshot(path=str(SHOTS / f"t1192-{TAG}-desktop-sender.png"))
161 p2.wait_for_timeout(5000)
162 else:
163 p2.wait_for_timeout(6500)
164 after = p2.evaluate(COUNT)
165 got = after["incoming"] - before["incoming"]
166 landed = after["inOpen"] - before["inOpen"]
167 m["rounds"].append({"incoming": got, "landed": landed, "pending": after["pending"], "own_shots": after["ownShots"]})
168 print("round", rnd, m["rounds"][-1])
169 p2.screenshot(path=str(SHOTS / f"t1192-{TAG}-mobile-after.png"))
170 m["final"] = p2.evaluate(COUNT)
171 m["errors"] = errs
172 b.close()
173 finally:
174 proc.terminate()
175 (SHOTS / f"t1192-{TAG}-metrics.json").write_text(json.dumps(m, indent=1))
176 tot_in = sum(r["incoming"] for r in m["rounds"]); tot_land = sum(r["landed"] for r in m["rounds"])
177 print(json.dumps({"incoming": tot_in, "landed": tot_land, "final": m["final"]}))
178 if TAG != "before":
179 check(tot_in >= 8, f"receiver got {tot_in} incoming blocks over {ROUNDS} volleys of 5")
180 check(tot_land == tot_in, f"all received blocks landed ({tot_land}/{tot_in})")
181 check(m["final"]["ownShots"] == 0, "none culled off the top as the receiver's own shot")
182 check(m["final"]["pending"] == 0, "queue empty at the end")
183 check(not m["errors"], f"no page errors {m['errors'][:2]}")
184 sys.exit(1 if FAILURES else 0)
185
186
187 if __name__ == "__main__":
188 main()
@@ -0,0 +1,188 @@
1#!/usr/bin/env python3
2"""t1192: 5 blocks at once to an opponent with 2 open columns — none may be lost.
3
4Usage: t1181-flights-playwright.py [ROOT] [TAG]
5ROOT defaults to /workspace/meteors (its build/ is served by php -S).
6Desktop (1280x800) is the sender; mobile (390x844, touch, DPR 3) is the receiver.
7Writes /workspace/meteors-shots/t1181-<TAG>-*.png and prints JSON metrics.
8"""
9from __future__ import annotations
10
11import json
12import os
13import socket
14import subprocess
15import sys
16import tempfile
17import time
18from pathlib import Path
19
20from playwright.sync_api import sync_playwright
21
22ROOT = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/workspace/meteors")
23TAG = sys.argv[2] if len(sys.argv) > 2 else "after"
24ROUNDS = 3
25SHOTS = Path("/workspace/meteors-shots")
26SHOTS.mkdir(parents=True, exist_ok=True)
27PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
28CHROME = "/usr/bin/google-chrome"
29ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
30FAILURES = []
31URL = None
32
33# Records, per frame, every flight element's on-screen centre, plus the
34# Date.now() when each of my shots left the field (cull).
35PROBE = """() => {
36 if (window.__probe) return;
37 const P = window.__probe = { culls: {}, tracks: {}, frames: 0 };
38 const orig = GameCore.prototype.consumeOutgoingShots;
39 GameCore.prototype.consumeOutgoingShots = function () {
40 const shots = orig.call(this);
41 if (this === app.core) for (const s of shots) P.culls[String(s.id)] = Date.now();
42 return shots;
43 };
44 let ids = new WeakMap(); let next = 1;
45 function f() {
46 P.frames++;
47 const now = Date.now();
48 for (const el of document.querySelectorAll('#flights .flight, #flights-back .flight')) {
49 if (!ids.has(el)) ids.set(el, 'el' + (next++));
50 const k = ids.get(el);
51 const r = el.getBoundingClientRect();
52 if (!r.width) continue;
53 (P.tracks[k] = P.tracks[k] || []).push([now, r.left + r.width / 2, r.top + r.height / 2]);
54 }
55 requestAnimationFrame(f);
56 }
57 requestAnimationFrame(f);
58}"""
59
60SHOOT = """(n) => {
61 const out = [];
62 for (let i = 0; i < n; i++) {
63 const b = app.core.createBlock(2 + 2 * i, 13.0, i % 5, 'flying');
64 b.vy = 6;
65 out.push(b.id);
66 }
67 return out;
68}"""
69
70
71def check(cond, msg):
72 print(("OK " if cond else "FAIL") + " " + msg)
73 if not cond:
74 FAILURES.append(msg)
75 return cond
76
77
78def free_port():
79 s = socket.socket(); s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]; s.close(); return port
80
81
82def start_php(port, data):
83 env = os.environ.copy(); env["METEORS_DATA_DIR"] = str(data)
84 log = open(f"/tmp/t1192-php-{TAG}.log", "w")
85 proc = subprocess.Popen([PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
86 cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log)
87 time.sleep(0.5)
88 return proc
89
90
91def login(page, n):
92 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded")
93 page.wait_for_timeout(300)
94 page.goto(f"{URL}index.html?online=1", wait_until="domcontentloaded")
95 page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000)
96 page.locator("#online-panel").wait_for(state="visible", timeout=8000)
97
98
99
100SETUP_RECEIVER = """() => {
101 const g = app.core;
102 g.spawnInterval = 1e9; g.playTime = 99;
103 for (const b of g.blocks.slice()) g.removeBlock(b);
104 for (let c = 0; c < 10; c++) { if (c === 3 || c === 7) continue; for (let r = 0; r < 13; r++) g.place(c, r, (r + c) % 5, 'locked'); }
105 const R = window.__recv = { incoming: 0, ownShots: 0 };
106 const origIn = Online.onIncoming;
107 Online.onIncoming = function (list) { R.incoming += list.length; return origIn.apply(this, arguments); };
108 const origC = GameCore.prototype.consumeOutgoingShots;
109 GameCore.prototype.consumeOutgoingShots = function () { const s = origC.call(this); if (this === app.core) R.ownShots += s.length; return s; };
110}"""
111
112COUNT = """() => {
113 const g = app.core;
114 const gray = g.blocks.filter(b => (b.col === 3 || b.col === 7)).length;
115 return { inOpen: gray, pending: g.pendingGarbage ? g.pendingGarbage() : null, incoming: window.__recv.incoming,
116 ownShots: window.__recv.ownShots, state: g.state, score: g.score };
117}"""
118
119SHOOT5 = """() => { for (let i = 0; i < 5; i++) { const b = app.core.createBlock(i * 2, 13.0, i % 5, 'flying'); b.vy = 6; } }"""
120
121
122def main():
123 global URL
124 port = free_port(); URL = f"http://127.0.0.1:{port}/"
125 proc = start_php(port, Path(tempfile.mkdtemp(prefix="meteors-t1192-")))
126 m = {"rounds": []}
127 try:
128 with sync_playwright() as p:
129 b = p.chromium.launch(executable_path=CHROME, args=ARGS, headless=True)
130 c1 = b.new_context(viewport={"width": 1280, "height": 800})
131 c2 = b.new_context(viewport={"width": 390, "height": 844}, is_mobile=True, has_touch=True, device_scale_factor=3)
132 p1, p2 = c1.new_page(), c2.new_page()
133 errs = []
134 for pg, tag in ((p1, "desktop"), (p2, "mobile")):
135 pg.on("pageerror", lambda e, tag=tag: errs.append(f"{tag}: {e}"))
136 login(p1, 1); login(p2, 2)
137 p1.locator("#btn-create").click()
138 p1.wait_for_function("() => (document.getElementById('lobby-code')||{}).textContent.trim().length >= 4", timeout=8000)
139 code = p1.locator("#lobby-code").inner_text().strip()
140 p2.locator("#join-code").fill(code); p2.locator("#btn-join").click()
141 p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
142 p1.locator("#btn-ready").click(); p2.locator("#btn-ready").click()
143 start = p1.locator("#btn-start")
144 for _ in range(20):
145 if start.is_visible() and start.is_enabled():
146 break
147 p1.wait_for_timeout(400)
148 start.click()
149 for pg in (p1, p2):
150 pg.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
151 p1.evaluate("() => { app.core.spawnInterval = 1e9; app.core.playTime = 99; for (const b of app.core.blocks.slice()) app.core.removeBlock(b); }")
152 p2.evaluate(SETUP_RECEIVER)
153 p1.wait_for_timeout(500)
154 for rnd in range(ROUNDS):
155 before = p2.evaluate(COUNT)
156 p1.evaluate(SHOOT5)
157 if rnd == 0:
158 p2.wait_for_timeout(1500)
159 p2.screenshot(path=str(SHOTS / f"t1192-{TAG}-mobile-receiving.png"))
160 p1.screenshot(path=str(SHOTS / f"t1192-{TAG}-desktop-sender.png"))
161 p2.wait_for_timeout(5000)
162 else:
163 p2.wait_for_timeout(6500)
164 after = p2.evaluate(COUNT)
165 got = after["incoming"] - before["incoming"]
166 landed = after["inOpen"] - before["inOpen"]
167 m["rounds"].append({"incoming": got, "landed": landed, "pending": after["pending"], "own_shots": after["ownShots"]})
168 print("round", rnd, m["rounds"][-1])
169 p2.screenshot(path=str(SHOTS / f"t1192-{TAG}-mobile-after.png"))
170 m["final"] = p2.evaluate(COUNT)
171 m["errors"] = errs
172 b.close()
173 finally:
174 proc.terminate()
175 (SHOTS / f"t1192-{TAG}-metrics.json").write_text(json.dumps(m, indent=1))
176 tot_in = sum(r["incoming"] for r in m["rounds"]); tot_land = sum(r["landed"] for r in m["rounds"])
177 print(json.dumps({"incoming": tot_in, "landed": tot_land, "final": m["final"]}))
178 if TAG != "before":
179 check(tot_in >= 8, f"receiver got {tot_in} incoming blocks over {ROUNDS} volleys of 5")
180 check(tot_land == tot_in, f"all received blocks landed ({tot_land}/{tot_in})")
181 check(m["final"]["ownShots"] == 0, "none culled off the top as the receiver's own shot")
182 check(m["final"]["pending"] == 0, "queue empty at the end")
183 check(not m["errors"], f"no page errors {m['errors'][:2]}")
184 sys.exit(1 if FAILURES else 0)
185
186
187if __name__ == "__main__":
188 main()