BlueGit

projects-timfalken-com meteors

Files

meteors / src / offline.js

offline.js

offline.js 13.4 KiB Download Raw
1'use strict';
2
3/**
4 * Offline Strijd: a client-side single-player mode that plays like
5 * multiplayer (shots, miss chance, opponent minis) against local bots
6 * (t1119). Pure simulation — no server.
7 */
8
9var Offline = (function ()
10{
11
12var BOT_INTERVAL = 0.5;
13var SKILL_START = 0.05;
14var SKILL_STEP = 0.01;
15var SKILL_CAP = 1;
16var FLIGHT_DURATION = 1.2;
17var ROUND_WON_DELAY = 1.5;
18
19/**
20 * N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.
21 * Documented in docs/ASSUMPTIONS.md (t1119).
22 */
23function roundsAtOpponentCount (n)
24{
25 if (n <= 1)
26 { return 1; }
27 return n - 1;
28}
29
30function skillForRound (round)
31{
32 var r = Math.max(1, Math.floor(Number(round) || 1));
33 var pct = 5 + (r - 1);
34 if (pct > 100)
35 { pct = 100; }
36 return pct / 100;
37}
38
39function scheduleForRound (round)
40{
41 var r = Math.max(1, Math.floor(Number(round) || 1));
42 var cursor = 1;
43 var n = 1;
44 for (;;)
45 {
46 var count = roundsAtOpponentCount(n);
47 if (r < cursor + count)
48 {
49 return {
50 round: r,
51 opponents: n,
52 skill: skillForRound(r),
53 roundsAtLevel: count,
54 indexInLevel: r - cursor + 1
55 };
56 }
57 cursor += count;
58 n++;
59 if (n > 10000)
60 {
61 return {
62 round: r,
63 opponents: n,
64 skill: SKILL_CAP,
65 roundsAtLevel: roundsAtOpponentCount(n),
66 indexInLevel: 1
67 };
68 }
69 }
70}
71
72function GameCoreCtor ()
73{
74 if (typeof GameCore !== 'undefined')
75 { return GameCore; }
76 if (typeof module !== 'undefined')
77 { return require('./gameCore.js').GameCore; }
78 return null;
79}
80
81function PlanetMod ()
82{
83 if (typeof Planet !== 'undefined')
84 { return Planet; }
85 if (typeof module !== 'undefined')
86 { return require('./planet.js'); }
87 return null;
88}
89
90/**
91 * Integer-row colour grid of grounded (still / settling / locked)
92 * blocks, including greys (color < 0) so a swap can shift them.
93 */
94function snapshotGrid (core)
95{
96 var width = core.width;
97 var height = core.height;
98 var grid = [];
99 for (var c = 0; c < width; c++)
100 {
101 grid[c] = [];
102 for (var r = 0; r < height; r++)
103 { grid[c][r] = null; }
104 }
105 for (var i = 0; i < core.blocks.length; i++)
106 {
107 var b = core.blocks[i];
108 if (!core.isGrounded(b))
109 { continue; }
110 var row = Math.round(b.y);
111 if (row < 0 || row >= height || b.col < 0 || b.col >= width)
112 { continue; }
113 if (Math.abs(b.y - row) > 0.2)
114 { continue; }
115 grid[b.col][row] = b.color;
116 }
117 return grid;
118}
119
120function cloneGrid (grid)
121{
122 var out = [];
123 for (var c = 0; c < grid.length; c++)
124 { out[c] = grid[c].slice(); }
125 return out;
126}
127
128/**
129 * Apply swapToward's net result: the block at fromRow moves to toRow,
130 * and the blocks it passed through each shift one cell toward fromRow.
131 */
132function applyColumnMove (grid, col, fromRow, toRow)
133{
134 if (fromRow === toRow)
135 { return; }
136 var moving = grid[col][fromRow];
137 if (toRow > fromRow)
138 {
139 for (var y = fromRow; y < toRow; y++)
140 { grid[col][y] = grid[col][y + 1]; }
141 grid[col][toRow] = moving;
142 }
143 else
144 {
145 for (var y = fromRow; y > toRow; y--)
146 { grid[col][y] = grid[col][y - 1]; }
147 grid[col][toRow] = moving;
148 }
149}
150
151function hasMatch (grid, width, height)
152{
153 var c, r, run, prev;
154 for (r = 0; r < height; r++)
155 {
156 run = 0;
157 prev = null;
158 for (c = 0; c < width; c++)
159 {
160 var color = grid[c][r];
161 if (color != null && color >= 0 && color === prev)
162 {
163 run++;
164 if (run >= 3)
165 { return true; }
166 }
167 else
168 {
169 run = (color != null && color >= 0) ? 1 : 0;
170 prev = (color != null && color >= 0) ? color : null;
171 }
172 }
173 }
174 for (c = 0; c < width; c++)
175 {
176 run = 0;
177 prev = null;
178 for (r = 0; r < height; r++)
179 {
180 var color = grid[c][r];
181 if (color != null && color >= 0 && color === prev)
182 {
183 run++;
184 if (run >= 3)
185 { return true; }
186 }
187 else
188 {
189 run = (color != null && color >= 0) ? 1 : 0;
190 prev = (color != null && color >= 0) ? color : null;
191 }
192 }
193 }
194 return false;
195}
196
197/**
198 * Contiguous segments of draggable, nearly-integer-y blocks in a
199 * column. Gaps break a segment the same way swapToward stops at gaps.
200 */
201function contiguousSegments (core, col)
202{
203 if (!core.columnAllowsDrag(col))
204 { return []; }
205 var list = core.blocksInColumn(col).filter(function (b)
206 {
207 return core.isDraggableBlock(b);
208 });
209 list.sort(function (a, b) { return a.y - b.y; });
210 var segs = [];
211 var cur = [];
212 for (var i = 0; i < list.length; i++)
213 {
214 var y = list[i].y;
215 if (Math.abs(y - Math.round(y)) > 0.15)
216 {
217 if (cur.length)
218 {
219 segs.push(cur);
220 cur = [];
221 }
222 continue;
223 }
224 if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)
225 {
226 segs.push(cur);
227 cur = [list[i]];
228 }
229 else
230 { cur.push(list[i]); }
231 }
232 if (cur.length)
233 { segs.push(cur); }
234 return segs;
235}
236
237/**
238 * The shortest vertical move that would create a 3+ match, or null.
239 * Ties break on lowest column, then lowest fromY, then lowest toY.
240 */
241function findBotMove (core)
242{
243 var grid = snapshotGrid(core);
244 if (hasMatch(grid, core.width, core.height))
245 { return null; }
246 var best = null;
247 for (var col = 0; col < core.width; col++)
248 {
249 var segs = contiguousSegments(core, col);
250 for (var s = 0; s < segs.length; s++)
251 {
252 var seg = segs[s];
253 if (seg.length < 2)
254 { continue; }
255 for (var i = 0; i < seg.length; i++)
256 {
257 var fromY = Math.round(seg[i].y);
258 for (var j = 0; j < seg.length; j++)
259 {
260 if (i === j)
261 { continue; }
262 var toY = Math.round(seg[j].y);
263 var dist = Math.abs(toY - fromY);
264 if (best && dist > best.dist)
265 { continue; }
266 var trial = cloneGrid(grid);
267 applyColumnMove(trial, col, fromY, toY);
268 if (!hasMatch(trial, core.width, core.height))
269 { continue; }
270 var cand = {
271 col: col,
272 fromY: fromY,
273 toY: toY,
274 dist: dist,
275 blockId: seg[i].id
276 };
277 if (!best || dist < best.dist
278 || (dist === best.dist && col < best.col)
279 || (dist === best.dist && col === best.col && fromY < best.fromY)
280 || (dist === best.dist && col === best.col && fromY === best.fromY
281 && toY < best.toY))
282 { best = cand; }
283 }
284 }
285 }
286 }
287 return best;
288}
289
290function executeBotMove (core, move)
291{
292 if (!core || !move)
293 { return false; }
294 var list = core.blocksInColumn(move.col);
295 var block = null;
296 for (var i = 0; i < list.length; i++)
297 {
298 if (move.blockId != null && list[i].id === move.blockId)
299 {
300 block = list[i];
301 break;
302 }
303 if (Math.abs(list[i].y - move.fromY) < 0.2)
304 { block = list[i]; }
305 }
306 if (!block || !core.isDraggableBlock(block))
307 { return false; }
308 core.swapToward(block, move.toY);
309 return true;
310}
311
312/**
313 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
314 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
315 */
316function tryBotRoll (core, skill, rng)
317{
318 rng = rng || Math.random;
319 var roll = rng();
320 if (!(roll < skill))
321 {
322 return { rolled: true, success: false, moved: false, roll: roll, move: null };
323 }
324 var move = findBotMove(core);
325 if (!move)
326 {
327 return { rolled: true, success: true, moved: false, roll: roll, move: null };
328 }
329 var ok = executeBotMove(core, move);
330 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
331}
332
333function pickPlanet (rng, P)
334{
335 var all = P.allPlanets();
336 if (!all.length)
337 { return P.defaultPlanet(); }
338 var i = Math.floor(rng() * all.length) % all.length;
339 return all[i];
340}
341
342function OfflineBattle (opts)
343{
344 opts = opts || {};
345 var P = PlanetMod();
346 this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());
347 this.rng = opts.rng || Math.random;
348 this.round = opts.round || 1;
349 this.schedule = scheduleForRound(this.round);
350 this.clock = 0;
351 this.state = 'playing';
352 this.pending = [];
353 this.flightResults = [];
354 this.shotLocals = [];
355 this.bots = [];
356 this.playerId = 'player';
357 this._initBots();
358}
359
360OfflineBattle.prototype._initBots = function ()
361{
362 var P = PlanetMod();
363 var Ctor = GameCoreCtor();
364 var n = this.schedule.opponents;
365 this.bots = [];
366 for (var i = 0; i < n; i++)
367 {
368 var planet = pickPlanet(this.rng, P);
369 var miss = P.missChance(planet);
370 var core = new Ctor(planet, this.rng, miss);
371 this.bots.push({
372 id: 'bot-' + (i + 1),
373 name: 'Bot ' + (i + 1),
374 planet: planet,
375 core: core,
376 eliminated: false,
377 score: 0,
378 aiAcc: 0
379 });
380 }
381};
382
383OfflineBattle.prototype.aliveBots = function ()
384{
385 var out = [];
386 for (var i = 0; i < this.bots.length; i++)
387 {
388 if (!this.bots[i].eliminated && this.bots[i].core
389 && this.bots[i].core.state !== 'gameover')
390 { out.push(this.bots[i]); }
391 }
392 return out;
393};
394
395OfflineBattle.prototype.coreFor = function (id, playerCore)
396{
397 if (id === this.playerId)
398 { return playerCore; }
399 for (var i = 0; i < this.bots.length; i++)
400 {
401 if (this.bots[i].id === id)
402 { return this.bots[i].core; }
403 }
404 return null;
405};
406
407OfflineBattle.prototype._targetsFor = function (fromId, playerCore)
408{
409 var targets = [];
410 if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')
411 { targets.push({ id: this.playerId, core: playerCore }); }
412 for (var i = 0; i < this.bots.length; i++)
413 {
414 var bot = this.bots[i];
415 if (bot.id === fromId || bot.eliminated)
416 { continue; }
417 if (bot.core && bot.core.state === 'playing')
418 { targets.push({ id: bot.id, core: bot.core }); }
419 }
420 return targets;
421};
422
423OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)
424{
425 if (!core || !core.consumeOutgoingShots)
426 { return; }
427 var shots = core.consumeOutgoingShots();
428 if (!shots.length)
429 { return; }
430 var P = PlanetMod();
431 var missChance = (P && planet) ? P.missChance(planet) : 0.30;
432 var targets = this._targetsFor(fromId, playerCore);
433 for (var i = 0; i < shots.length; i++)
434 {
435 var shot = shots[i];
436 var miss = targets.length === 0 || this.rng() < missChance;
437 var target = null;
438 if (!miss)
439 {
440 var idx = Math.floor(this.rng() * targets.length) % targets.length;
441 target = targets[idx];
442 }
443 var clientId = fromId + '-' + shot.id + '-' + this.clock;
444 var landCol = null;
445 if (!miss && target && target.core && target.core.pickGarbageColumn)
446 { landCol = target.core.pickGarbageColumn(); }
447 var result = {
448 client_id: clientId,
449 miss: miss,
450 target_id: target ? target.id : null,
451 color: shot.color,
452 flight_duration: FLIGHT_DURATION,
453 from_id: fromId,
454 col: shot.col,
455 y: shot.y,
456 land_col: landCol
457 };
458 this.flightResults.push(result);
459 this.shotLocals.push({
460 client_id: clientId,
461 col: shot.col,
462 y: shot.y,
463 color: shot.color,
464 from_id: fromId,
465 land_col: landCol
466 });
467 if (!miss && target)
468 {
469 this.pending.push({
470 at: this.clock + FLIGHT_DURATION,
471 targetId: target.id,
472 color: shot.color,
473 fromId: fromId,
474 landCol: landCol
475 });
476 }
477 }
478};
479
480OfflineBattle.prototype._deliver = function (playerCore)
481{
482 var keep = [];
483 for (var i = 0; i < this.pending.length; i++)
484 {
485 var ev = this.pending[i];
486 if (this.clock + 1e-9 < ev.at)
487 {
488 keep.push(ev);
489 continue;
490 }
491 var core = this.coreFor(ev.targetId, playerCore);
492 if (core && core.state === 'playing' && core.ingestGarbage)
493 { core.ingestGarbage(ev.landCol); }
494 }
495 this.pending = keep;
496};
497
498OfflineBattle.prototype.tick = function (dt, playerCore)
499{
500 this.flightResults = [];
501 this.shotLocals = [];
502 if (this.state !== 'playing')
503 { return { flights: [], locals: [] }; }
504 if (dt < 0)
505 { dt = 0; }
506 this.clock += dt;
507
508 var skill = this.schedule.skill;
509 for (var i = 0; i < this.bots.length; i++)
510 {
511 var bot = this.bots[i];
512 if (bot.eliminated)
513 { continue; }
514 if (bot.core.state === 'gameover')
515 {
516 bot.eliminated = true;
517 bot.score = bot.core.score;
518 continue;
519 }
520 bot.core.tick(dt);
521 bot.score = bot.core.score;
522 bot.aiAcc += dt;
523 while (bot.aiAcc >= BOT_INTERVAL)
524 {
525 bot.aiAcc -= BOT_INTERVAL;
526 if (bot.core.state === 'playing' && !bot.core.drag)
527 { tryBotRoll(bot.core, skill, this.rng); }
528 }
529 }
530
531 this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);
532 for (var i = 0; i < this.bots.length; i++)
533 {
534 var bot = this.bots[i];
535 if (bot.eliminated)
536 { continue; }
537 this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);
538 }
539 this._deliver(playerCore);
540
541 for (var i = 0; i < this.bots.length; i++)
542 {
543 if (this.bots[i].core && this.bots[i].core.state === 'gameover')
544 {
545 this.bots[i].eliminated = true;
546 this.bots[i].score = this.bots[i].core.score;
547 }
548 }
549
550 if (playerCore && playerCore.state === 'gameover')
551 { this.state = 'lost'; }
552 else if (this.aliveBots().length === 0 && this.bots.length > 0)
553 { this.state = 'round_won'; }
554
555 return { flights: this.flightResults, locals: this.shotLocals };
556};
557
558/**
559 * Start the next round (fresh bots, new skill and opponent count).
560 * The caller must also give the player a fresh GameCore.
561 */
562OfflineBattle.prototype.advanceRound = function ()
563{
564 this.round += 1;
565 this.schedule = scheduleForRound(this.round);
566 this.state = 'playing';
567 this.pending = [];
568 this.flightResults = [];
569 this.shotLocals = [];
570 this.clock = 0;
571 this._initBots();
572 return this.schedule;
573};
574
575function createBattle (opts)
576{
577 return new OfflineBattle(opts);
578}
579
580var api = {
581 BOT_INTERVAL: BOT_INTERVAL,
582 SKILL_START: SKILL_START,
583 SKILL_STEP: SKILL_STEP,
584 SKILL_CAP: SKILL_CAP,
585 FLIGHT_DURATION: FLIGHT_DURATION,
586 ROUND_WON_DELAY: ROUND_WON_DELAY,
587 roundsAtOpponentCount: roundsAtOpponentCount,
588 skillForRound: skillForRound,
589 scheduleForRound: scheduleForRound,
590 findBotMove: findBotMove,
591 tryBotRoll: tryBotRoll,
592 executeBotMove: executeBotMove,
593 snapshotGrid: snapshotGrid,
594 applyColumnMove: applyColumnMove,
595 hasMatch: hasMatch,
596 createBattle: createBattle,
597 OfflineBattle: OfflineBattle
598};
599
600if (typeof module !== 'undefined' && module.exports)
601{ module.exports = api; }
602else if (typeof globalThis !== 'undefined')
603{ globalThis.Offline = api; }
604
605return api;
606
607})();
608
609if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')
610{ module.exports = Offline; }