BlueGit

projects-timfalken-com meteors

Merge branch 'feature/t1144-bot-lookahead'

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
541b26dcb09f8dd316fb8d8d039913e83cb03d86
Pipeline
Passed
4 files changed +948 −13
build/game.js +327 −6
@@ -10569,11 +10569,263 @@ function executeBotMove (core, move)
10569 10569 return true;
10570 10570 }
10571 10571
10572 /**
10573 * Max board evaluations (apply + hasMatch + undo) for a depth-2 search
10574 * in one AI tick. A 10×13 field with typical stacks stays well under this.
10575 */
10576 var PLAN_BUDGET = 4000;
10577 /** Skill at or below this: never start a 2-step setup (early rounds). */
10578 var LOOKAHEAD_START = 0.10;
10579 /** Skill at or above this: always look for a 2-step setup when no immediate match. */
10580 var LOOKAHEAD_FULL = 0.40;
10581
10582 /**
10583 * Probability of searching a 2-step setup after a successful roll
10584 * that found no immediate match. 0 through 10% skill (rondes 1–6),
10585 * then linear up to 1 at 40% skill (ronde 36).
10586 */
10587 function lookaheadChance (skill)
10588 {
10589 skill = Number(skill) || 0;
10590 if (skill <= LOOKAHEAD_START)
10591 { return 0; }
10592 if (skill >= LOOKAHEAD_FULL)
10593 { return 1; }
10594 return (skill - LOOKAHEAD_START) / (LOOKAHEAD_FULL - LOOKAHEAD_START);
10595 }
10596
10597 function copyMove (m)
10598 {
10599 return {
10600 col: m.col,
10601 fromY: m.fromY,
10602 toY: m.toY,
10603 dist: m.dist,
10604 blockId: m.blockId
10605 };
10606 }
10607
10608 function movesEqual (a, b)
10609 {
10610 return a && b && a.col === b.col && a.fromY === b.fromY && a.toY === b.toY;
10611 }
10612
10613 function betterImmediate (cand, best)
10614 {
10615 if (!best)
10616 { return true; }
10617 if (cand.dist !== best.dist)
10618 { return cand.dist < best.dist; }
10619 if (cand.col !== best.col)
10620 { return cand.col < best.col; }
10621 if (cand.fromY !== best.fromY)
10622 { return cand.fromY < best.fromY; }
10623 return cand.toY < best.toY;
10624 }
10625
10626 function betterPlan (cand, best)
10627 {
10628 if (!best)
10629 { return true; }
10630 if (cand.total !== best.total)
10631 { return cand.total < best.total; }
10632 var a0 = cand.steps[0];
10633 var b0 = best.steps[0];
10634 if (a0.dist !== b0.dist)
10635 { return a0.dist < b0.dist; }
10636 if (a0.col !== b0.col || a0.fromY !== b0.fromY || a0.toY !== b0.toY)
10637 { return betterImmediate(a0, b0); }
10638 return betterImmediate(cand.steps[1], best.steps[1]);
10639 }
10640
10641 /**
10642 * Legal vertical swaps from a colour grid: contiguous non-null cells
10643 * in a column (gaps break a segment, same as swapToward).
10644 */
10645 function listMovesFromGrid (grid, width, height)
10646 {
10647 var moves = [];
10648 for (var col = 0; col < width; col++)
10649 {
10650 var start = -1;
10651 for (var r = 0; r <= height; r++)
10652 {
10653 var filled = r < height && grid[col][r] != null;
10654 if (filled)
10655 {
10656 if (start < 0)
10657 { start = r; }
10658 }
10659 else if (start >= 0)
10660 {
10661 var end = r;
10662 if (end - start >= 2)
10663 {
10664 for (var i = start; i < end; i++)
10665 {
10666 for (var j = start; j < end; j++)
10667 {
10668 if (i === j)
10669 { continue; }
10670 moves.push({
10671 col: col,
10672 fromY: i,
10673 toY: j,
10674 dist: Math.abs(j - i),
10675 blockId: null
10676 });
10677 }
10678 }
10679 }
10680 start = -1;
10681 }
10682 }
10683 }
10684 return moves;
10685 }
10686
10687 function listMovesFromCore (core)
10688 {
10689 var moves = [];
10690 for (var col = 0; col < core.width; col++)
10691 {
10692 var segs = contiguousSegments(core, col);
10693 for (var s = 0; s < segs.length; s++)
10694 {
10695 var seg = segs[s];
10696 if (seg.length < 2)
10697 { continue; }
10698 for (var i = 0; i < seg.length; i++)
10699 {
10700 var fromY = Math.round(seg[i].y);
10701 for (var j = 0; j < seg.length; j++)
10702 {
10703 if (i === j)
10704 { continue; }
10705 var toY = Math.round(seg[j].y);
10706 moves.push({
10707 col: col,
10708 fromY: fromY,
10709 toY: toY,
10710 dist: Math.abs(toY - fromY),
10711 blockId: seg[i].id
10712 });
10713 }
10714 }
10715 }
10716 }
10717 return moves;
10718 }
10719
10720 /**
10721 * A 2-step setup: first swap creates no match, second swap does.
10722 * Prefers smaller total distance, then shorter first step, then the
10723 * same column / fromY / toY ties as findBotMove. First moves come
10724 * from the live core (legal segments only). Budget-capped.
10725 */
10726 function findSetupPlan (core, budget)
10727 {
10728 if (!core)
10729 { return null; }
10730 var width = core.width;
10731 var height = core.height;
10732 var grid = snapshotGrid(core);
10733 if (hasMatch(grid, width, height))
10734 { return null; }
10735 budget = budget == null ? PLAN_BUDGET : budget;
10736 var firstMoves = listMovesFromCore(core);
10737 firstMoves.sort(function (a, b)
10738 {
10739 if (a.dist !== b.dist)
10740 { return a.dist - b.dist; }
10741 if (a.col !== b.col)
10742 { return a.col - b.col; }
10743 if (a.fromY !== b.fromY)
10744 { return a.fromY - b.fromY; }
10745 return a.toY - b.toY;
10746 });
10747 var best = null;
10748 var evals = 0;
10749 for (var i = 0; i < firstMoves.length; i++)
10750 {
10751 var first = firstMoves[i];
10752 if (best && first.dist + 1 > best.total)
10753 { break; }
10754 applyColumnMove(grid, first.col, first.fromY, first.toY);
10755 if (hasMatch(grid, width, height))
10756 {
10757 applyColumnMove(grid, first.col, first.toY, first.fromY);
10758 continue;
10759 }
10760 var seconds = listMovesFromGrid(grid, width, height);
10761 for (var j = 0; j < seconds.length; j++)
10762 {
10763 var second = seconds[j];
10764 var total = first.dist + second.dist;
10765 if (best && total > best.total)
10766 { continue; }
10767 if (evals++ >= budget)
10768 { break; }
10769 applyColumnMove(grid, second.col, second.fromY, second.toY);
10770 var ok = hasMatch(grid, width, height);
10771 applyColumnMove(grid, second.col, second.toY, second.fromY);
10772 if (!ok)
10773 { continue; }
10774 var cand = {
10775 steps: [copyMove(first), copyMove(second)],
10776 total: total
10777 };
10778 if (betterPlan(cand, best))
10779 { best = cand; }
10780 }
10781 applyColumnMove(grid, first.col, first.toY, first.fromY);
10782 if (evals >= budget)
10783 { break; }
10784 // 1+1 is the shortest possible setup; firstMoves is sorted so
10785 // the first such plan is already the tie-break winner.
10786 if (best && best.total === 2)
10787 { break; }
10788 }
10789 return best;
10790 }
10791
10792 /**
10793 * True when `step` is still a legal vertical swap on this core, and
10794 * (when mustMatch) would create a 3+ match.
10795 */
10796 function stepIsValid (core, step, mustMatch)
10797 {
10798 if (!core || !step)
10799 { return false; }
10800 var moves = listMovesFromCore(core);
10801 var found = null;
10802 for (var i = 0; i < moves.length; i++)
10803 {
10804 if (movesEqual(moves[i], step))
10805 {
10806 found = moves[i];
10807 break;
10808 }
10809 }
10810 if (!found)
10811 { return false; }
10812 step.blockId = found.blockId;
10813 if (!mustMatch)
10814 { return true; }
10815 var grid = snapshotGrid(core);
10816 applyColumnMove(grid, step.col, step.fromY, step.toY);
10817 return hasMatch(grid, core.width, core.height);
10818 }
10819
10572 10820 /**
10573 10821 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
10574 10822 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
10823 * `memory` is an optional object that stores a 2-step plan across ticks
10824 * (`memory.plan`). On a later successful roll the bot follows the
10825 * remaining step if it is still legal and still makes a match; otherwise
10826 * it re-plans.
10575 10827 */
10576 function tryBotRoll (core, skill, rng)
10828 function tryBotRoll (core, skill, rng, memory)
10577 10829 {
10578 10830 rng = rng || Math.random;
10579 10831 var roll = rng();
@@ -10581,13 +10833,73 @@ function tryBotRoll (core, skill, rng)
10581 10833 {
10582 10834 return { rolled: true, success: false, moved: false, roll: roll, move: null };
10583 10835 }
10836 var grid = snapshotGrid(core);
10837 if (hasMatch(grid, core.width, core.height))
10838 {
10839 if (memory)
10840 { memory.plan = null; }
10841 return { rolled: true, success: true, moved: false, roll: roll, move: null };
10842 }
10843 if (memory && memory.plan && memory.plan.steps
10844 && memory.plan.index < memory.plan.steps.length)
10845 {
10846 var step = memory.plan.steps[memory.plan.index];
10847 var last = memory.plan.index === memory.plan.steps.length - 1;
10848 if (stepIsValid(core, step, last))
10849 {
10850 var followed = executeBotMove(core, step);
10851 if (followed)
10852 {
10853 memory.plan.index++;
10854 if (memory.plan.index >= memory.plan.steps.length)
10855 { memory.plan = null; }
10856 return {
10857 rolled: true,
10858 success: true,
10859 moved: true,
10860 roll: roll,
10861 move: step,
10862 followed: true
10863 };
10864 }
10865 }
10866 memory.plan = null;
10867 }
10584 10868 var move = findBotMove(core);
10585 if (!move)
10869 if (move)
10870 {
10871 if (memory)
10872 { memory.plan = null; }
10873 var ok = executeBotMove(core, move);
10874 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
10875 }
10876 var chance = lookaheadChance(skill);
10877 if (chance <= 0 || !(rng() < chance))
10878 {
10879 return { rolled: true, success: true, moved: false, roll: roll, move: null };
10880 }
10881 var plan = findSetupPlan(core);
10882 if (!plan || !plan.steps || !plan.steps[0])
10586 10883 {
10587 10884 return { rolled: true, success: true, moved: false, roll: roll, move: null };
10588 10885 }
10589 var ok = executeBotMove(core, move);
10590 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
10886 var first = plan.steps[0];
10887 var started = executeBotMove(core, first);
10888 if (started && memory)
10889 {
10890 memory.plan = { steps: plan.steps, index: 1, total: plan.total };
10891 }
10892 else if (memory)
10893 { memory.plan = null; }
10894 return {
10895 rolled: true,
10896 success: true,
10897 moved: !!started,
10898 roll: roll,
10899 move: first,
10900 planned: true,
10901 plan: plan
10902 };
10591 10903 }
10592 10904
10593 10905 function pickPlanet (rng, P)
@@ -10635,7 +10947,8 @@ OfflineBattle.prototype._initBots = function ()
10635 10947 core: core,
10636 10948 eliminated: false,
10637 10949 score: 0,
10638 aiAcc: 0
10950 aiAcc: 0,
10951 plan: null
10639 10952 });
10640 10953 }
10641 10954 };
@@ -10784,7 +11097,7 @@ OfflineBattle.prototype.tick = function (dt, playerCore)
10784 11097 {
10785 11098 bot.aiAcc -= BOT_INTERVAL;
10786 11099 if (bot.core.state === 'playing' && !bot.core.drag)
10787 { tryBotRoll(bot.core, skill, this.rng); }
11100 { tryBotRoll(bot.core, skill, this.rng, bot); }
10788 11101 }
10789 11102 }
10790 11103
@@ -10848,8 +11161,16 @@ var api = {
10848 11161 skillForRound: skillForRound,
10849 11162 scheduleForRound: scheduleForRound,
10850 11163 findBotMove: findBotMove,
11164 findSetupPlan: findSetupPlan,
10851 11165 tryBotRoll: tryBotRoll,
10852 11166 executeBotMove: executeBotMove,
11167 stepIsValid: stepIsValid,
11168 lookaheadChance: lookaheadChance,
11169 listMovesFromCore: listMovesFromCore,
11170 listMovesFromGrid: listMovesFromGrid,
11171 PLAN_BUDGET: PLAN_BUDGET,
11172 LOOKAHEAD_START: LOOKAHEAD_START,
11173 LOOKAHEAD_FULL: LOOKAHEAD_FULL,
10853 11174 snapshotGrid: snapshotGrid,
10854 11175 applyColumnMove: applyColumnMove,
10855 11176 hasMatch: hasMatch,
@@ -10569,11 +10569,263 @@ function executeBotMove (core, move)
10569 return true;
10569 return true;
10570}
10570}
10571
10571
10572/**
10573 * Max board evaluations (apply + hasMatch + undo) for a depth-2 search
10574 * in one AI tick. A 10×13 field with typical stacks stays well under this.
10575 */
10576var PLAN_BUDGET = 4000;
10577/** Skill at or below this: never start a 2-step setup (early rounds). */
10578var LOOKAHEAD_START = 0.10;
10579/** Skill at or above this: always look for a 2-step setup when no immediate match. */
10580var LOOKAHEAD_FULL = 0.40;
10581
10582/**
10583 * Probability of searching a 2-step setup after a successful roll
10584 * that found no immediate match. 0 through 10% skill (rondes 1–6),
10585 * then linear up to 1 at 40% skill (ronde 36).
10586 */
10587function lookaheadChance (skill)
10588{
10589 skill = Number(skill) || 0;
10590 if (skill <= LOOKAHEAD_START)
10591 { return 0; }
10592 if (skill >= LOOKAHEAD_FULL)
10593 { return 1; }
10594 return (skill - LOOKAHEAD_START) / (LOOKAHEAD_FULL - LOOKAHEAD_START);
10595}
10596
10597function copyMove (m)
10598{
10599 return {
10600 col: m.col,
10601 fromY: m.fromY,
10602 toY: m.toY,
10603 dist: m.dist,
10604 blockId: m.blockId
10605 };
10606}
10607
10608function movesEqual (a, b)
10609{
10610 return a && b && a.col === b.col && a.fromY === b.fromY && a.toY === b.toY;
10611}
10612
10613function betterImmediate (cand, best)
10614{
10615 if (!best)
10616 { return true; }
10617 if (cand.dist !== best.dist)
10618 { return cand.dist < best.dist; }
10619 if (cand.col !== best.col)
10620 { return cand.col < best.col; }
10621 if (cand.fromY !== best.fromY)
10622 { return cand.fromY < best.fromY; }
10623 return cand.toY < best.toY;
10624}
10625
10626function betterPlan (cand, best)
10627{
10628 if (!best)
10629 { return true; }
10630 if (cand.total !== best.total)
10631 { return cand.total < best.total; }
10632 var a0 = cand.steps[0];
10633 var b0 = best.steps[0];
10634 if (a0.dist !== b0.dist)
10635 { return a0.dist < b0.dist; }
10636 if (a0.col !== b0.col || a0.fromY !== b0.fromY || a0.toY !== b0.toY)
10637 { return betterImmediate(a0, b0); }
10638 return betterImmediate(cand.steps[1], best.steps[1]);
10639}
10640
10641/**
10642 * Legal vertical swaps from a colour grid: contiguous non-null cells
10643 * in a column (gaps break a segment, same as swapToward).
10644 */
10645function listMovesFromGrid (grid, width, height)
10646{
10647 var moves = [];
10648 for (var col = 0; col < width; col++)
10649 {
10650 var start = -1;
10651 for (var r = 0; r <= height; r++)
10652 {
10653 var filled = r < height && grid[col][r] != null;
10654 if (filled)
10655 {
10656 if (start < 0)
10657 { start = r; }
10658 }
10659 else if (start >= 0)
10660 {
10661 var end = r;
10662 if (end - start >= 2)
10663 {
10664 for (var i = start; i < end; i++)
10665 {
10666 for (var j = start; j < end; j++)
10667 {
10668 if (i === j)
10669 { continue; }
10670 moves.push({
10671 col: col,
10672 fromY: i,
10673 toY: j,
10674 dist: Math.abs(j - i),
10675 blockId: null
10676 });
10677 }
10678 }
10679 }
10680 start = -1;
10681 }
10682 }
10683 }
10684 return moves;
10685}
10686
10687function listMovesFromCore (core)
10688{
10689 var moves = [];
10690 for (var col = 0; col < core.width; col++)
10691 {
10692 var segs = contiguousSegments(core, col);
10693 for (var s = 0; s < segs.length; s++)
10694 {
10695 var seg = segs[s];
10696 if (seg.length < 2)
10697 { continue; }
10698 for (var i = 0; i < seg.length; i++)
10699 {
10700 var fromY = Math.round(seg[i].y);
10701 for (var j = 0; j < seg.length; j++)
10702 {
10703 if (i === j)
10704 { continue; }
10705 var toY = Math.round(seg[j].y);
10706 moves.push({
10707 col: col,
10708 fromY: fromY,
10709 toY: toY,
10710 dist: Math.abs(toY - fromY),
10711 blockId: seg[i].id
10712 });
10713 }
10714 }
10715 }
10716 }
10717 return moves;
10718}
10719
10720/**
10721 * A 2-step setup: first swap creates no match, second swap does.
10722 * Prefers smaller total distance, then shorter first step, then the
10723 * same column / fromY / toY ties as findBotMove. First moves come
10724 * from the live core (legal segments only). Budget-capped.
10725 */
10726function findSetupPlan (core, budget)
10727{
10728 if (!core)
10729 { return null; }
10730 var width = core.width;
10731 var height = core.height;
10732 var grid = snapshotGrid(core);
10733 if (hasMatch(grid, width, height))
10734 { return null; }
10735 budget = budget == null ? PLAN_BUDGET : budget;
10736 var firstMoves = listMovesFromCore(core);
10737 firstMoves.sort(function (a, b)
10738 {
10739 if (a.dist !== b.dist)
10740 { return a.dist - b.dist; }
10741 if (a.col !== b.col)
10742 { return a.col - b.col; }
10743 if (a.fromY !== b.fromY)
10744 { return a.fromY - b.fromY; }
10745 return a.toY - b.toY;
10746 });
10747 var best = null;
10748 var evals = 0;
10749 for (var i = 0; i < firstMoves.length; i++)
10750 {
10751 var first = firstMoves[i];
10752 if (best && first.dist + 1 > best.total)
10753 { break; }
10754 applyColumnMove(grid, first.col, first.fromY, first.toY);
10755 if (hasMatch(grid, width, height))
10756 {
10757 applyColumnMove(grid, first.col, first.toY, first.fromY);
10758 continue;
10759 }
10760 var seconds = listMovesFromGrid(grid, width, height);
10761 for (var j = 0; j < seconds.length; j++)
10762 {
10763 var second = seconds[j];
10764 var total = first.dist + second.dist;
10765 if (best && total > best.total)
10766 { continue; }
10767 if (evals++ >= budget)
10768 { break; }
10769 applyColumnMove(grid, second.col, second.fromY, second.toY);
10770 var ok = hasMatch(grid, width, height);
10771 applyColumnMove(grid, second.col, second.toY, second.fromY);
10772 if (!ok)
10773 { continue; }
10774 var cand = {
10775 steps: [copyMove(first), copyMove(second)],
10776 total: total
10777 };
10778 if (betterPlan(cand, best))
10779 { best = cand; }
10780 }
10781 applyColumnMove(grid, first.col, first.toY, first.fromY);
10782 if (evals >= budget)
10783 { break; }
10784 // 1+1 is the shortest possible setup; firstMoves is sorted so
10785 // the first such plan is already the tie-break winner.
10786 if (best && best.total === 2)
10787 { break; }
10788 }
10789 return best;
10790}
10791
10792/**
10793 * True when `step` is still a legal vertical swap on this core, and
10794 * (when mustMatch) would create a 3+ match.
10795 */
10796function stepIsValid (core, step, mustMatch)
10797{
10798 if (!core || !step)
10799 { return false; }
10800 var moves = listMovesFromCore(core);
10801 var found = null;
10802 for (var i = 0; i < moves.length; i++)
10803 {
10804 if (movesEqual(moves[i], step))
10805 {
10806 found = moves[i];
10807 break;
10808 }
10809 }
10810 if (!found)
10811 { return false; }
10812 step.blockId = found.blockId;
10813 if (!mustMatch)
10814 { return true; }
10815 var grid = snapshotGrid(core);
10816 applyColumnMove(grid, step.col, step.fromY, step.toY);
10817 return hasMatch(grid, core.width, core.height);
10818}
10819
10572/**
10820/**
10573 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
10821 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
10574 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
10822 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
10823 * `memory` is an optional object that stores a 2-step plan across ticks
10824 * (`memory.plan`). On a later successful roll the bot follows the
10825 * remaining step if it is still legal and still makes a match; otherwise
10826 * it re-plans.
10575 */
10827 */
10576function tryBotRoll (core, skill, rng)
10828function tryBotRoll (core, skill, rng, memory)
10577{
10829{
10578 rng = rng || Math.random;
10830 rng = rng || Math.random;
10579 var roll = rng();
10831 var roll = rng();
@@ -10581,13 +10833,73 @@ function tryBotRoll (core, skill, rng)
10581 {
10833 {
10582 return { rolled: true, success: false, moved: false, roll: roll, move: null };
10834 return { rolled: true, success: false, moved: false, roll: roll, move: null };
10583 }
10835 }
10836 var grid = snapshotGrid(core);
10837 if (hasMatch(grid, core.width, core.height))
10838 {
10839 if (memory)
10840 { memory.plan = null; }
10841 return { rolled: true, success: true, moved: false, roll: roll, move: null };
10842 }
10843 if (memory && memory.plan && memory.plan.steps
10844 && memory.plan.index < memory.plan.steps.length)
10845 {
10846 var step = memory.plan.steps[memory.plan.index];
10847 var last = memory.plan.index === memory.plan.steps.length - 1;
10848 if (stepIsValid(core, step, last))
10849 {
10850 var followed = executeBotMove(core, step);
10851 if (followed)
10852 {
10853 memory.plan.index++;
10854 if (memory.plan.index >= memory.plan.steps.length)
10855 { memory.plan = null; }
10856 return {
10857 rolled: true,
10858 success: true,
10859 moved: true,
10860 roll: roll,
10861 move: step,
10862 followed: true
10863 };
10864 }
10865 }
10866 memory.plan = null;
10867 }
10584 var move = findBotMove(core);
10868 var move = findBotMove(core);
10585 if (!move)
10869 if (move)
10870 {
10871 if (memory)
10872 { memory.plan = null; }
10873 var ok = executeBotMove(core, move);
10874 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
10875 }
10876 var chance = lookaheadChance(skill);
10877 if (chance <= 0 || !(rng() < chance))
10878 {
10879 return { rolled: true, success: true, moved: false, roll: roll, move: null };
10880 }
10881 var plan = findSetupPlan(core);
10882 if (!plan || !plan.steps || !plan.steps[0])
10586 {
10883 {
10587 return { rolled: true, success: true, moved: false, roll: roll, move: null };
10884 return { rolled: true, success: true, moved: false, roll: roll, move: null };
10588 }
10885 }
10589 var ok = executeBotMove(core, move);
10886 var first = plan.steps[0];
10590 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
10887 var started = executeBotMove(core, first);
10888 if (started && memory)
10889 {
10890 memory.plan = { steps: plan.steps, index: 1, total: plan.total };
10891 }
10892 else if (memory)
10893 { memory.plan = null; }
10894 return {
10895 rolled: true,
10896 success: true,
10897 moved: !!started,
10898 roll: roll,
10899 move: first,
10900 planned: true,
10901 plan: plan
10902 };
10591}
10903}
10592
10904
10593function pickPlanet (rng, P)
10905function pickPlanet (rng, P)
@@ -10635,7 +10947,8 @@ OfflineBattle.prototype._initBots = function ()
10635 core: core,
10947 core: core,
10636 eliminated: false,
10948 eliminated: false,
10637 score: 0,
10949 score: 0,
10638 aiAcc: 0
10950 aiAcc: 0,
10951 plan: null
10639 });
10952 });
10640 }
10953 }
10641};
10954};
@@ -10784,7 +11097,7 @@ OfflineBattle.prototype.tick = function (dt, playerCore)
10784 {
11097 {
10785 bot.aiAcc -= BOT_INTERVAL;
11098 bot.aiAcc -= BOT_INTERVAL;
10786 if (bot.core.state === 'playing' && !bot.core.drag)
11099 if (bot.core.state === 'playing' && !bot.core.drag)
10787 { tryBotRoll(bot.core, skill, this.rng); }
11100 { tryBotRoll(bot.core, skill, this.rng, bot); }
10788 }
11101 }
10789 }
11102 }
10790
11103
@@ -10848,8 +11161,16 @@ var api = {
10848 skillForRound: skillForRound,
11161 skillForRound: skillForRound,
10849 scheduleForRound: scheduleForRound,
11162 scheduleForRound: scheduleForRound,
10850 findBotMove: findBotMove,
11163 findBotMove: findBotMove,
11164 findSetupPlan: findSetupPlan,
10851 tryBotRoll: tryBotRoll,
11165 tryBotRoll: tryBotRoll,
10852 executeBotMove: executeBotMove,
11166 executeBotMove: executeBotMove,
11167 stepIsValid: stepIsValid,
11168 lookaheadChance: lookaheadChance,
11169 listMovesFromCore: listMovesFromCore,
11170 listMovesFromGrid: listMovesFromGrid,
11171 PLAN_BUDGET: PLAN_BUDGET,
11172 LOOKAHEAD_START: LOOKAHEAD_START,
11173 LOOKAHEAD_FULL: LOOKAHEAD_FULL,
10853 snapshotGrid: snapshotGrid,
11174 snapshotGrid: snapshotGrid,
10854 applyColumnMove: applyColumnMove,
11175 applyColumnMove: applyColumnMove,
10855 hasMatch: hasMatch,
11176 hasMatch: hasMatch,
docs/ASSUMPTIONS.md +36 −0
@@ -858,3 +858,39 @@ Aanname:
858 858 - Solo-game-over roept `play_finish` aan; verdiende punten gaan bij een
859 859 ingelogde speler naar het levenslange totaal (anti-cheat: o.a. min. 3 s
860 860 bij score > 0, max. 4 punten/s).
861
862
863 ## t1144 — bots kijken 1 of 2 zetten vooruit
864
865 - Alleen in **Offline Strijd**. Online is PvP: er zijn geen server-side
866 bots, en die zijn ook niet toegevoegd.
867 - Als een bot zijn kansrol haalt (`roll < skill`) en er ligt al een
868 match op het veld, doet hij niets (zoals in t1119) en vergeet hij
869 een eventueel onthouden plan.
870 - Anders zoekt hij eerst een **onmiddellijke** match: dezelfde kortste
871 verticale zet als in t1119 (daarna laagste kolom / fromY / toY). Die
872 gaat altijd voor, ongeacht de skill.
873 - Is er geen onmiddellijke match, dan kan hij tot **diepte 2** zoeken:
874 een eerste verschuiving die zelf geen match maakt, maar een tweede
875 mogelijk maakt. Hij voert alleen de eerste zet van het beste plan uit
876 en onthoudt de rest (`bot.plan`).
877 - Het **beste** plan is dat met de kleinste som van de twee afstanden,
878 dan de kortste eerste zet, daarna dezelfde kolom/fromY/toY-volgorde
879 als t1119 (eerst voor de eerste zet, dan voor de tweede).
880 - Op de volgende geslaagde rol volgt hij de onthouden tweede zet als
881 die nog legaal is en (als laatste stap) nog een match maakt — ook
882 als de skill dan te laag is om een *nieuw* plan te starten. Een
883 gevolgde zet vereist nog steeds een gewonnen rol die tick. Is het
884 plan ongeldig geworden, dan plant hij opnieuw (eerst onmiddellijk,
885 dan eventueel een nieuwe setup).
886 - De kans om een **nieuw** 2-stapsplan te zoeken hangt van de skill af:
887 **0 % bij skill ≤ 10 %** (rondes 1–6), daarna lineair naar **100 %
888 bij skill ≥ 40 %** (ronde 36 en verder). Zo blijven vroege rondes
889 makkelijk en worden late bots slimmer.
890 - De zoektocht blijft goedkoop op een veld van 10×13: alleen legale
891 verticale zetten binnen aaneengesloten segmenten (geen sprong over
892 een gat, geen vergrendelde kolom, geen enkel blokje alleen),
893 apply+undo op één rooster, korte zetten eerst, stop bij het eerste
894 1+1-plan (dat is door de sorteervolgorde al de winnaar), en een
895 plafond van **4000** bord-evaluaties per tick. Als dat plafond wordt
896 bereikt kan een zeldzame langere setup worden gemist.
@@ -858,3 +858,39 @@ Aanname:
858- Solo-game-over roept `play_finish` aan; verdiende punten gaan bij een
858- Solo-game-over roept `play_finish` aan; verdiende punten gaan bij een
859 ingelogde speler naar het levenslange totaal (anti-cheat: o.a. min. 3 s
859 ingelogde speler naar het levenslange totaal (anti-cheat: o.a. min. 3 s
860 bij score > 0, max. 4 punten/s).
860 bij score > 0, max. 4 punten/s).
861
862
863## t1144 — bots kijken 1 of 2 zetten vooruit
864
865- Alleen in **Offline Strijd**. Online is PvP: er zijn geen server-side
866 bots, en die zijn ook niet toegevoegd.
867- Als een bot zijn kansrol haalt (`roll < skill`) en er ligt al een
868 match op het veld, doet hij niets (zoals in t1119) en vergeet hij
869 een eventueel onthouden plan.
870- Anders zoekt hij eerst een **onmiddellijke** match: dezelfde kortste
871 verticale zet als in t1119 (daarna laagste kolom / fromY / toY). Die
872 gaat altijd voor, ongeacht de skill.
873- Is er geen onmiddellijke match, dan kan hij tot **diepte 2** zoeken:
874 een eerste verschuiving die zelf geen match maakt, maar een tweede
875 mogelijk maakt. Hij voert alleen de eerste zet van het beste plan uit
876 en onthoudt de rest (`bot.plan`).
877- Het **beste** plan is dat met de kleinste som van de twee afstanden,
878 dan de kortste eerste zet, daarna dezelfde kolom/fromY/toY-volgorde
879 als t1119 (eerst voor de eerste zet, dan voor de tweede).
880- Op de volgende geslaagde rol volgt hij de onthouden tweede zet als
881 die nog legaal is en (als laatste stap) nog een match maakt — ook
882 als de skill dan te laag is om een *nieuw* plan te starten. Een
883 gevolgde zet vereist nog steeds een gewonnen rol die tick. Is het
884 plan ongeldig geworden, dan plant hij opnieuw (eerst onmiddellijk,
885 dan eventueel een nieuwe setup).
886- De kans om een **nieuw** 2-stapsplan te zoeken hangt van de skill af:
887 **0 % bij skill ≤ 10 %** (rondes 1–6), daarna lineair naar **100 %
888 bij skill ≥ 40 %** (ronde 36 en verder). Zo blijven vroege rondes
889 makkelijk en worden late bots slimmer.
890- De zoektocht blijft goedkoop op een veld van 10×13: alleen legale
891 verticale zetten binnen aaneengesloten segmenten (geen sprong over
892 een gat, geen vergrendelde kolom, geen enkel blokje alleen),
893 apply+undo op één rooster, korte zetten eerst, stop bij het eerste
894 1+1-plan (dat is door de sorteervolgorde al de winnaar), en een
895 plafond van **4000** bord-evaluaties per tick. Als dat plafond wordt
896 bereikt kan een zeldzame langere setup worden gemist.
src/offline.js +327 −6
@@ -309,11 +309,263 @@ function executeBotMove (core, move)
309 309 return true;
310 310 }
311 311
312 /**
313 * Max board evaluations (apply + hasMatch + undo) for a depth-2 search
314 * in one AI tick. A 10×13 field with typical stacks stays well under this.
315 */
316 var PLAN_BUDGET = 4000;
317 /** Skill at or below this: never start a 2-step setup (early rounds). */
318 var LOOKAHEAD_START = 0.10;
319 /** Skill at or above this: always look for a 2-step setup when no immediate match. */
320 var LOOKAHEAD_FULL = 0.40;
321
322 /**
323 * Probability of searching a 2-step setup after a successful roll
324 * that found no immediate match. 0 through 10% skill (rondes 1–6),
325 * then linear up to 1 at 40% skill (ronde 36).
326 */
327 function lookaheadChance (skill)
328 {
329 skill = Number(skill) || 0;
330 if (skill <= LOOKAHEAD_START)
331 { return 0; }
332 if (skill >= LOOKAHEAD_FULL)
333 { return 1; }
334 return (skill - LOOKAHEAD_START) / (LOOKAHEAD_FULL - LOOKAHEAD_START);
335 }
336
337 function copyMove (m)
338 {
339 return {
340 col: m.col,
341 fromY: m.fromY,
342 toY: m.toY,
343 dist: m.dist,
344 blockId: m.blockId
345 };
346 }
347
348 function movesEqual (a, b)
349 {
350 return a && b && a.col === b.col && a.fromY === b.fromY && a.toY === b.toY;
351 }
352
353 function betterImmediate (cand, best)
354 {
355 if (!best)
356 { return true; }
357 if (cand.dist !== best.dist)
358 { return cand.dist < best.dist; }
359 if (cand.col !== best.col)
360 { return cand.col < best.col; }
361 if (cand.fromY !== best.fromY)
362 { return cand.fromY < best.fromY; }
363 return cand.toY < best.toY;
364 }
365
366 function betterPlan (cand, best)
367 {
368 if (!best)
369 { return true; }
370 if (cand.total !== best.total)
371 { return cand.total < best.total; }
372 var a0 = cand.steps[0];
373 var b0 = best.steps[0];
374 if (a0.dist !== b0.dist)
375 { return a0.dist < b0.dist; }
376 if (a0.col !== b0.col || a0.fromY !== b0.fromY || a0.toY !== b0.toY)
377 { return betterImmediate(a0, b0); }
378 return betterImmediate(cand.steps[1], best.steps[1]);
379 }
380
381 /**
382 * Legal vertical swaps from a colour grid: contiguous non-null cells
383 * in a column (gaps break a segment, same as swapToward).
384 */
385 function listMovesFromGrid (grid, width, height)
386 {
387 var moves = [];
388 for (var col = 0; col < width; col++)
389 {
390 var start = -1;
391 for (var r = 0; r <= height; r++)
392 {
393 var filled = r < height && grid[col][r] != null;
394 if (filled)
395 {
396 if (start < 0)
397 { start = r; }
398 }
399 else if (start >= 0)
400 {
401 var end = r;
402 if (end - start >= 2)
403 {
404 for (var i = start; i < end; i++)
405 {
406 for (var j = start; j < end; j++)
407 {
408 if (i === j)
409 { continue; }
410 moves.push({
411 col: col,
412 fromY: i,
413 toY: j,
414 dist: Math.abs(j - i),
415 blockId: null
416 });
417 }
418 }
419 }
420 start = -1;
421 }
422 }
423 }
424 return moves;
425 }
426
427 function listMovesFromCore (core)
428 {
429 var moves = [];
430 for (var col = 0; col < core.width; col++)
431 {
432 var segs = contiguousSegments(core, col);
433 for (var s = 0; s < segs.length; s++)
434 {
435 var seg = segs[s];
436 if (seg.length < 2)
437 { continue; }
438 for (var i = 0; i < seg.length; i++)
439 {
440 var fromY = Math.round(seg[i].y);
441 for (var j = 0; j < seg.length; j++)
442 {
443 if (i === j)
444 { continue; }
445 var toY = Math.round(seg[j].y);
446 moves.push({
447 col: col,
448 fromY: fromY,
449 toY: toY,
450 dist: Math.abs(toY - fromY),
451 blockId: seg[i].id
452 });
453 }
454 }
455 }
456 }
457 return moves;
458 }
459
460 /**
461 * A 2-step setup: first swap creates no match, second swap does.
462 * Prefers smaller total distance, then shorter first step, then the
463 * same column / fromY / toY ties as findBotMove. First moves come
464 * from the live core (legal segments only). Budget-capped.
465 */
466 function findSetupPlan (core, budget)
467 {
468 if (!core)
469 { return null; }
470 var width = core.width;
471 var height = core.height;
472 var grid = snapshotGrid(core);
473 if (hasMatch(grid, width, height))
474 { return null; }
475 budget = budget == null ? PLAN_BUDGET : budget;
476 var firstMoves = listMovesFromCore(core);
477 firstMoves.sort(function (a, b)
478 {
479 if (a.dist !== b.dist)
480 { return a.dist - b.dist; }
481 if (a.col !== b.col)
482 { return a.col - b.col; }
483 if (a.fromY !== b.fromY)
484 { return a.fromY - b.fromY; }
485 return a.toY - b.toY;
486 });
487 var best = null;
488 var evals = 0;
489 for (var i = 0; i < firstMoves.length; i++)
490 {
491 var first = firstMoves[i];
492 if (best && first.dist + 1 > best.total)
493 { break; }
494 applyColumnMove(grid, first.col, first.fromY, first.toY);
495 if (hasMatch(grid, width, height))
496 {
497 applyColumnMove(grid, first.col, first.toY, first.fromY);
498 continue;
499 }
500 var seconds = listMovesFromGrid(grid, width, height);
501 for (var j = 0; j < seconds.length; j++)
502 {
503 var second = seconds[j];
504 var total = first.dist + second.dist;
505 if (best && total > best.total)
506 { continue; }
507 if (evals++ >= budget)
508 { break; }
509 applyColumnMove(grid, second.col, second.fromY, second.toY);
510 var ok = hasMatch(grid, width, height);
511 applyColumnMove(grid, second.col, second.toY, second.fromY);
512 if (!ok)
513 { continue; }
514 var cand = {
515 steps: [copyMove(first), copyMove(second)],
516 total: total
517 };
518 if (betterPlan(cand, best))
519 { best = cand; }
520 }
521 applyColumnMove(grid, first.col, first.toY, first.fromY);
522 if (evals >= budget)
523 { break; }
524 // 1+1 is the shortest possible setup; firstMoves is sorted so
525 // the first such plan is already the tie-break winner.
526 if (best && best.total === 2)
527 { break; }
528 }
529 return best;
530 }
531
532 /**
533 * True when `step` is still a legal vertical swap on this core, and
534 * (when mustMatch) would create a 3+ match.
535 */
536 function stepIsValid (core, step, mustMatch)
537 {
538 if (!core || !step)
539 { return false; }
540 var moves = listMovesFromCore(core);
541 var found = null;
542 for (var i = 0; i < moves.length; i++)
543 {
544 if (movesEqual(moves[i], step))
545 {
546 found = moves[i];
547 break;
548 }
549 }
550 if (!found)
551 { return false; }
552 step.blockId = found.blockId;
553 if (!mustMatch)
554 { return true; }
555 var grid = snapshotGrid(core);
556 applyColumnMove(grid, step.col, step.fromY, step.toY);
557 return hasMatch(grid, core.width, core.height);
558 }
559
312 560 /**
313 561 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
314 562 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
563 * `memory` is an optional object that stores a 2-step plan across ticks
564 * (`memory.plan`). On a later successful roll the bot follows the
565 * remaining step if it is still legal and still makes a match; otherwise
566 * it re-plans.
315 567 */
316 function tryBotRoll (core, skill, rng)
568 function tryBotRoll (core, skill, rng, memory)
317 569 {
318 570 rng = rng || Math.random;
319 571 var roll = rng();
@@ -321,13 +573,73 @@ function tryBotRoll (core, skill, rng)
321 573 {
322 574 return { rolled: true, success: false, moved: false, roll: roll, move: null };
323 575 }
576 var grid = snapshotGrid(core);
577 if (hasMatch(grid, core.width, core.height))
578 {
579 if (memory)
580 { memory.plan = null; }
581 return { rolled: true, success: true, moved: false, roll: roll, move: null };
582 }
583 if (memory && memory.plan && memory.plan.steps
584 && memory.plan.index < memory.plan.steps.length)
585 {
586 var step = memory.plan.steps[memory.plan.index];
587 var last = memory.plan.index === memory.plan.steps.length - 1;
588 if (stepIsValid(core, step, last))
589 {
590 var followed = executeBotMove(core, step);
591 if (followed)
592 {
593 memory.plan.index++;
594 if (memory.plan.index >= memory.plan.steps.length)
595 { memory.plan = null; }
596 return {
597 rolled: true,
598 success: true,
599 moved: true,
600 roll: roll,
601 move: step,
602 followed: true
603 };
604 }
605 }
606 memory.plan = null;
607 }
324 608 var move = findBotMove(core);
325 if (!move)
609 if (move)
610 {
611 if (memory)
612 { memory.plan = null; }
613 var ok = executeBotMove(core, move);
614 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
615 }
616 var chance = lookaheadChance(skill);
617 if (chance <= 0 || !(rng() < chance))
326 618 {
327 619 return { rolled: true, success: true, moved: false, roll: roll, move: null };
328 620 }
329 var ok = executeBotMove(core, move);
330 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
621 var plan = findSetupPlan(core);
622 if (!plan || !plan.steps || !plan.steps[0])
623 {
624 return { rolled: true, success: true, moved: false, roll: roll, move: null };
625 }
626 var first = plan.steps[0];
627 var started = executeBotMove(core, first);
628 if (started && memory)
629 {
630 memory.plan = { steps: plan.steps, index: 1, total: plan.total };
631 }
632 else if (memory)
633 { memory.plan = null; }
634 return {
635 rolled: true,
636 success: true,
637 moved: !!started,
638 roll: roll,
639 move: first,
640 planned: true,
641 plan: plan
642 };
331 643 }
332 644
333 645 function pickPlanet (rng, P)
@@ -375,7 +687,8 @@ OfflineBattle.prototype._initBots = function ()
375 687 core: core,
376 688 eliminated: false,
377 689 score: 0,
378 aiAcc: 0
690 aiAcc: 0,
691 plan: null
379 692 });
380 693 }
381 694 };
@@ -524,7 +837,7 @@ OfflineBattle.prototype.tick = function (dt, playerCore)
524 837 {
525 838 bot.aiAcc -= BOT_INTERVAL;
526 839 if (bot.core.state === 'playing' && !bot.core.drag)
527 { tryBotRoll(bot.core, skill, this.rng); }
840 { tryBotRoll(bot.core, skill, this.rng, bot); }
528 841 }
529 842 }
530 843
@@ -588,8 +901,16 @@ var api = {
588 901 skillForRound: skillForRound,
589 902 scheduleForRound: scheduleForRound,
590 903 findBotMove: findBotMove,
904 findSetupPlan: findSetupPlan,
591 905 tryBotRoll: tryBotRoll,
592 906 executeBotMove: executeBotMove,
907 stepIsValid: stepIsValid,
908 lookaheadChance: lookaheadChance,
909 listMovesFromCore: listMovesFromCore,
910 listMovesFromGrid: listMovesFromGrid,
911 PLAN_BUDGET: PLAN_BUDGET,
912 LOOKAHEAD_START: LOOKAHEAD_START,
913 LOOKAHEAD_FULL: LOOKAHEAD_FULL,
593 914 snapshotGrid: snapshotGrid,
594 915 applyColumnMove: applyColumnMove,
595 916 hasMatch: hasMatch,
@@ -309,11 +309,263 @@ function executeBotMove (core, move)
309 return true;
309 return true;
310}
310}
311
311
312/**
313 * Max board evaluations (apply + hasMatch + undo) for a depth-2 search
314 * in one AI tick. A 10×13 field with typical stacks stays well under this.
315 */
316var PLAN_BUDGET = 4000;
317/** Skill at or below this: never start a 2-step setup (early rounds). */
318var LOOKAHEAD_START = 0.10;
319/** Skill at or above this: always look for a 2-step setup when no immediate match. */
320var LOOKAHEAD_FULL = 0.40;
321
322/**
323 * Probability of searching a 2-step setup after a successful roll
324 * that found no immediate match. 0 through 10% skill (rondes 1–6),
325 * then linear up to 1 at 40% skill (ronde 36).
326 */
327function lookaheadChance (skill)
328{
329 skill = Number(skill) || 0;
330 if (skill <= LOOKAHEAD_START)
331 { return 0; }
332 if (skill >= LOOKAHEAD_FULL)
333 { return 1; }
334 return (skill - LOOKAHEAD_START) / (LOOKAHEAD_FULL - LOOKAHEAD_START);
335}
336
337function copyMove (m)
338{
339 return {
340 col: m.col,
341 fromY: m.fromY,
342 toY: m.toY,
343 dist: m.dist,
344 blockId: m.blockId
345 };
346}
347
348function movesEqual (a, b)
349{
350 return a && b && a.col === b.col && a.fromY === b.fromY && a.toY === b.toY;
351}
352
353function betterImmediate (cand, best)
354{
355 if (!best)
356 { return true; }
357 if (cand.dist !== best.dist)
358 { return cand.dist < best.dist; }
359 if (cand.col !== best.col)
360 { return cand.col < best.col; }
361 if (cand.fromY !== best.fromY)
362 { return cand.fromY < best.fromY; }
363 return cand.toY < best.toY;
364}
365
366function betterPlan (cand, best)
367{
368 if (!best)
369 { return true; }
370 if (cand.total !== best.total)
371 { return cand.total < best.total; }
372 var a0 = cand.steps[0];
373 var b0 = best.steps[0];
374 if (a0.dist !== b0.dist)
375 { return a0.dist < b0.dist; }
376 if (a0.col !== b0.col || a0.fromY !== b0.fromY || a0.toY !== b0.toY)
377 { return betterImmediate(a0, b0); }
378 return betterImmediate(cand.steps[1], best.steps[1]);
379}
380
381/**
382 * Legal vertical swaps from a colour grid: contiguous non-null cells
383 * in a column (gaps break a segment, same as swapToward).
384 */
385function listMovesFromGrid (grid, width, height)
386{
387 var moves = [];
388 for (var col = 0; col < width; col++)
389 {
390 var start = -1;
391 for (var r = 0; r <= height; r++)
392 {
393 var filled = r < height && grid[col][r] != null;
394 if (filled)
395 {
396 if (start < 0)
397 { start = r; }
398 }
399 else if (start >= 0)
400 {
401 var end = r;
402 if (end - start >= 2)
403 {
404 for (var i = start; i < end; i++)
405 {
406 for (var j = start; j < end; j++)
407 {
408 if (i === j)
409 { continue; }
410 moves.push({
411 col: col,
412 fromY: i,
413 toY: j,
414 dist: Math.abs(j - i),
415 blockId: null
416 });
417 }
418 }
419 }
420 start = -1;
421 }
422 }
423 }
424 return moves;
425}
426
427function listMovesFromCore (core)
428{
429 var moves = [];
430 for (var col = 0; col < core.width; col++)
431 {
432 var segs = contiguousSegments(core, col);
433 for (var s = 0; s < segs.length; s++)
434 {
435 var seg = segs[s];
436 if (seg.length < 2)
437 { continue; }
438 for (var i = 0; i < seg.length; i++)
439 {
440 var fromY = Math.round(seg[i].y);
441 for (var j = 0; j < seg.length; j++)
442 {
443 if (i === j)
444 { continue; }
445 var toY = Math.round(seg[j].y);
446 moves.push({
447 col: col,
448 fromY: fromY,
449 toY: toY,
450 dist: Math.abs(toY - fromY),
451 blockId: seg[i].id
452 });
453 }
454 }
455 }
456 }
457 return moves;
458}
459
460/**
461 * A 2-step setup: first swap creates no match, second swap does.
462 * Prefers smaller total distance, then shorter first step, then the
463 * same column / fromY / toY ties as findBotMove. First moves come
464 * from the live core (legal segments only). Budget-capped.
465 */
466function findSetupPlan (core, budget)
467{
468 if (!core)
469 { return null; }
470 var width = core.width;
471 var height = core.height;
472 var grid = snapshotGrid(core);
473 if (hasMatch(grid, width, height))
474 { return null; }
475 budget = budget == null ? PLAN_BUDGET : budget;
476 var firstMoves = listMovesFromCore(core);
477 firstMoves.sort(function (a, b)
478 {
479 if (a.dist !== b.dist)
480 { return a.dist - b.dist; }
481 if (a.col !== b.col)
482 { return a.col - b.col; }
483 if (a.fromY !== b.fromY)
484 { return a.fromY - b.fromY; }
485 return a.toY - b.toY;
486 });
487 var best = null;
488 var evals = 0;
489 for (var i = 0; i < firstMoves.length; i++)
490 {
491 var first = firstMoves[i];
492 if (best && first.dist + 1 > best.total)
493 { break; }
494 applyColumnMove(grid, first.col, first.fromY, first.toY);
495 if (hasMatch(grid, width, height))
496 {
497 applyColumnMove(grid, first.col, first.toY, first.fromY);
498 continue;
499 }
500 var seconds = listMovesFromGrid(grid, width, height);
501 for (var j = 0; j < seconds.length; j++)
502 {
503 var second = seconds[j];
504 var total = first.dist + second.dist;
505 if (best && total > best.total)
506 { continue; }
507 if (evals++ >= budget)
508 { break; }
509 applyColumnMove(grid, second.col, second.fromY, second.toY);
510 var ok = hasMatch(grid, width, height);
511 applyColumnMove(grid, second.col, second.toY, second.fromY);
512 if (!ok)
513 { continue; }
514 var cand = {
515 steps: [copyMove(first), copyMove(second)],
516 total: total
517 };
518 if (betterPlan(cand, best))
519 { best = cand; }
520 }
521 applyColumnMove(grid, first.col, first.toY, first.fromY);
522 if (evals >= budget)
523 { break; }
524 // 1+1 is the shortest possible setup; firstMoves is sorted so
525 // the first such plan is already the tie-break winner.
526 if (best && best.total === 2)
527 { break; }
528 }
529 return best;
530}
531
532/**
533 * True when `step` is still a legal vertical swap on this core, and
534 * (when mustMatch) would create a 3+ match.
535 */
536function stepIsValid (core, step, mustMatch)
537{
538 if (!core || !step)
539 { return false; }
540 var moves = listMovesFromCore(core);
541 var found = null;
542 for (var i = 0; i < moves.length; i++)
543 {
544 if (movesEqual(moves[i], step))
545 {
546 found = moves[i];
547 break;
548 }
549 }
550 if (!found)
551 { return false; }
552 step.blockId = found.blockId;
553 if (!mustMatch)
554 { return true; }
555 var grid = snapshotGrid(core);
556 applyColumnMove(grid, step.col, step.fromY, step.toY);
557 return hasMatch(grid, core.width, core.height);
558}
559
312/**
560/**
313 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
561 * 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.
562 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
563 * `memory` is an optional object that stores a 2-step plan across ticks
564 * (`memory.plan`). On a later successful roll the bot follows the
565 * remaining step if it is still legal and still makes a match; otherwise
566 * it re-plans.
315 */
567 */
316function tryBotRoll (core, skill, rng)
568function tryBotRoll (core, skill, rng, memory)
317{
569{
318 rng = rng || Math.random;
570 rng = rng || Math.random;
319 var roll = rng();
571 var roll = rng();
@@ -321,13 +573,73 @@ function tryBotRoll (core, skill, rng)
321 {
573 {
322 return { rolled: true, success: false, moved: false, roll: roll, move: null };
574 return { rolled: true, success: false, moved: false, roll: roll, move: null };
323 }
575 }
576 var grid = snapshotGrid(core);
577 if (hasMatch(grid, core.width, core.height))
578 {
579 if (memory)
580 { memory.plan = null; }
581 return { rolled: true, success: true, moved: false, roll: roll, move: null };
582 }
583 if (memory && memory.plan && memory.plan.steps
584 && memory.plan.index < memory.plan.steps.length)
585 {
586 var step = memory.plan.steps[memory.plan.index];
587 var last = memory.plan.index === memory.plan.steps.length - 1;
588 if (stepIsValid(core, step, last))
589 {
590 var followed = executeBotMove(core, step);
591 if (followed)
592 {
593 memory.plan.index++;
594 if (memory.plan.index >= memory.plan.steps.length)
595 { memory.plan = null; }
596 return {
597 rolled: true,
598 success: true,
599 moved: true,
600 roll: roll,
601 move: step,
602 followed: true
603 };
604 }
605 }
606 memory.plan = null;
607 }
324 var move = findBotMove(core);
608 var move = findBotMove(core);
325 if (!move)
609 if (move)
610 {
611 if (memory)
612 { memory.plan = null; }
613 var ok = executeBotMove(core, move);
614 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
615 }
616 var chance = lookaheadChance(skill);
617 if (chance <= 0 || !(rng() < chance))
326 {
618 {
327 return { rolled: true, success: true, moved: false, roll: roll, move: null };
619 return { rolled: true, success: true, moved: false, roll: roll, move: null };
328 }
620 }
329 var ok = executeBotMove(core, move);
621 var plan = findSetupPlan(core);
330 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
622 if (!plan || !plan.steps || !plan.steps[0])
623 {
624 return { rolled: true, success: true, moved: false, roll: roll, move: null };
625 }
626 var first = plan.steps[0];
627 var started = executeBotMove(core, first);
628 if (started && memory)
629 {
630 memory.plan = { steps: plan.steps, index: 1, total: plan.total };
631 }
632 else if (memory)
633 { memory.plan = null; }
634 return {
635 rolled: true,
636 success: true,
637 moved: !!started,
638 roll: roll,
639 move: first,
640 planned: true,
641 plan: plan
642 };
331}
643}
332
644
333function pickPlanet (rng, P)
645function pickPlanet (rng, P)
@@ -375,7 +687,8 @@ OfflineBattle.prototype._initBots = function ()
375 core: core,
687 core: core,
376 eliminated: false,
688 eliminated: false,
377 score: 0,
689 score: 0,
378 aiAcc: 0
690 aiAcc: 0,
691 plan: null
379 });
692 });
380 }
693 }
381};
694};
@@ -524,7 +837,7 @@ OfflineBattle.prototype.tick = function (dt, playerCore)
524 {
837 {
525 bot.aiAcc -= BOT_INTERVAL;
838 bot.aiAcc -= BOT_INTERVAL;
526 if (bot.core.state === 'playing' && !bot.core.drag)
839 if (bot.core.state === 'playing' && !bot.core.drag)
527 { tryBotRoll(bot.core, skill, this.rng); }
840 { tryBotRoll(bot.core, skill, this.rng, bot); }
528 }
841 }
529 }
842 }
530
843
@@ -588,8 +901,16 @@ var api = {
588 skillForRound: skillForRound,
901 skillForRound: skillForRound,
589 scheduleForRound: scheduleForRound,
902 scheduleForRound: scheduleForRound,
590 findBotMove: findBotMove,
903 findBotMove: findBotMove,
904 findSetupPlan: findSetupPlan,
591 tryBotRoll: tryBotRoll,
905 tryBotRoll: tryBotRoll,
592 executeBotMove: executeBotMove,
906 executeBotMove: executeBotMove,
907 stepIsValid: stepIsValid,
908 lookaheadChance: lookaheadChance,
909 listMovesFromCore: listMovesFromCore,
910 listMovesFromGrid: listMovesFromGrid,
911 PLAN_BUDGET: PLAN_BUDGET,
912 LOOKAHEAD_START: LOOKAHEAD_START,
913 LOOKAHEAD_FULL: LOOKAHEAD_FULL,
593 snapshotGrid: snapshotGrid,
914 snapshotGrid: snapshotGrid,
594 applyColumnMove: applyColumnMove,
915 applyColumnMove: applyColumnMove,
595 hasMatch: hasMatch,
916 hasMatch: hasMatch,
test/offline.test.js +258 −1
@@ -2,7 +2,7 @@
2 2
3 3 const { describe, it } = require('node:test');
4 4 const assert = require('node:assert/strict');
5 const { makeGame, Planet, Rng, GameCore } = require('./helpers.js');
5 const { makeGame, fillColumn, Planet, Rng, GameCore } = require('./helpers.js');
6 6 const Offline = require('../src/offline.js');
7 7
8 8 describe('Offline Strijd progression (t1119)', () =>
@@ -206,3 +206,260 @@ describe('Offline battle flow (t1119)', () =>
206 206 assert.equal(battle.round, 3);
207 207 });
208 208 });
209
210 function setupTwoStep (g)
211 {
212 // No immediate 3-match. After col0: 0→1 ([1,0,2,0]) a second
213 // adjacent swap on col2 (7 at y=1 → y=2) makes row 1 = 0,0,0.
214 g.place(0, 0, 0);
215 g.place(0, 1, 1);
216 g.place(0, 2, 2);
217 g.place(0, 3, 0);
218 g.place(1, 0, 3);
219 g.place(1, 1, 0);
220 g.place(1, 2, 4);
221 g.place(1, 3, 5);
222 g.place(2, 0, 6);
223 g.place(2, 1, 7);
224 g.place(2, 2, 0);
225 g.place(2, 3, 8);
226 return g;
227 }
228
229 function inSameSegment (grid, height, move)
230 {
231 if (move.fromY === move.toY)
232 { return false; }
233 const lo = Math.min(move.fromY, move.toY);
234 const hi = Math.max(move.fromY, move.toY);
235 for (let y = lo; y <= hi; y++)
236 {
237 if (grid[move.col][y] == null)
238 { return false; }
239 }
240 return lo >= 0 && hi < height;
241 }
242
243 describe('Bot lookahead planner (t1144)', () =>
244 {
245 it('lookaheadChance is 0 through 10% skill, then linear to 1 at 40%', () =>
246 {
247 assert.equal(Offline.lookaheadChance(0), 0);
248 assert.equal(Offline.lookaheadChance(0.05), 0);
249 assert.equal(Offline.lookaheadChance(0.10), 0);
250 assert.ok(Math.abs(Offline.lookaheadChance(0.25) - 0.5) < 1e-12);
251 assert.equal(Offline.lookaheadChance(0.40), 1);
252 assert.equal(Offline.lookaheadChance(1), 1);
253 });
254
255 it('finds a 1-step immediate match and prefers it over a setup', () =>
256 {
257 const g = makeGame({ noSpawn: true });
258 // Immediate: col0 [0,0,1,0] — also leave a 2-step shape on the right
259 // that must not be chosen while the 1-step exists.
260 g.place(0, 0, 0);
261 g.place(0, 1, 0);
262 g.place(0, 2, 1);
263 g.place(0, 3, 0);
264 g.place(1, 0, 3);
265 g.place(1, 1, 0);
266 g.place(1, 2, 4);
267 g.place(1, 3, 5);
268 g.place(2, 0, 6);
269 g.place(2, 1, 7);
270 g.place(2, 2, 0);
271 g.place(2, 3, 8);
272 const move = Offline.findBotMove(g);
273 assert.ok(move, 'expected an immediate move');
274 assert.equal(move.col, 0);
275 assert.equal(move.dist, 1);
276 const memory = { plan: null };
277 const r = Offline.tryBotRoll(g, 1, () => 0, memory);
278 assert.equal(r.success, true);
279 assert.equal(r.moved, true);
280 assert.equal(r.planned, undefined);
281 assert.equal(memory.plan, null);
282 assert.equal(r.move.col, 0);
283 assert.equal(r.move.dist, 1);
284 const launched = g.resolveMatches();
285 assert.ok(launched.length >= 1, 'immediate move must create a match');
286 });
287
288 it('finds a 2-step setup when no immediate match exists', () =>
289 {
290 const g = setupTwoStep(makeGame({ noSpawn: true }));
291 assert.equal(Offline.findBotMove(g), null, 'fixture must have no 1-step');
292 const plan = Offline.findSetupPlan(g);
293 assert.ok(plan && plan.steps && plan.steps.length === 2, 'expected a 2-step plan');
294 assert.equal(plan.steps[0].dist + plan.steps[1].dist, plan.total);
295 assert.ok(plan.total >= 2);
296 const firstLegal = Offline.listMovesFromCore(g).some((m) =>
297 m.col === plan.steps[0].col
298 && m.fromY === plan.steps[0].fromY
299 && m.toY === plan.steps[0].toY);
300 assert.ok(firstLegal, 'first step must be a legal core move');
301 assert.ok(Offline.executeBotMove(g, plan.steps[0]));
302 assert.equal(Offline.hasMatch(Offline.snapshotGrid(g), g.width, g.height), false,
303 'first step itself is a setup, not a match');
304 assert.ok(Offline.stepIsValid(g, plan.steps[1], true),
305 'second step must still be legal and create a match');
306 assert.ok(Offline.executeBotMove(g, plan.steps[1]));
307 const launched = g.resolveMatches();
308 assert.ok(launched.length >= 1, 'second step must create a match');
309 });
310
311 it('performs the first step and follows the plan on the next successful roll', () =>
312 {
313 const g = setupTwoStep(makeGame({ noSpawn: true }));
314 const memory = { plan: null };
315 const r1 = Offline.tryBotRoll(g, 1, () => 0, memory);
316 assert.equal(r1.success, true);
317 assert.equal(r1.moved, true);
318 assert.equal(r1.planned, true);
319 assert.ok(memory.plan && memory.plan.steps.length === 2);
320 assert.equal(memory.plan.index, 1);
321 assert.equal(Offline.hasMatch(Offline.snapshotGrid(g), g.width, g.height), false);
322
323 const r2 = Offline.tryBotRoll(g, 1, () => 0, memory);
324 assert.equal(r2.success, true);
325 assert.equal(r2.moved, true);
326 assert.equal(r2.followed, true);
327 assert.equal(memory.plan, null);
328 const launched = g.resolveMatches();
329 assert.ok(launched.length >= 1, 'followed step must create a match');
330 });
331
332 it('follows a committed plan even below the lookahead threshold', () =>
333 {
334 const g = setupTwoStep(makeGame({ noSpawn: true }));
335 const memory = { plan: null };
336 assert.ok(Offline.tryBotRoll(g, 1, () => 0, memory).planned);
337 // skill 5% is below the 10% lookahead floor, but the roll succeeds
338 // (0 < 0.05) and the stored second step is still valid.
339 assert.equal(Offline.lookaheadChance(0.05), 0);
340 const r = Offline.tryBotRoll(g, 0.05, () => 0, memory);
341 assert.equal(r.followed, true);
342 assert.equal(r.moved, true);
343 });
344
345 it('re-plans when the stored next step is no longer valid', () =>
346 {
347 const g = setupTwoStep(makeGame({ noSpawn: true }));
348 const memory = { plan: null };
349 const r1 = Offline.tryBotRoll(g, 1, () => 0, memory);
350 assert.ok(r1.planned && memory.plan);
351 const next = memory.plan.steps[1];
352 // After the first step, row 1 is a pair of 0s waiting for the
353 // third 0 from the second step. Recolor the middle 0 so that
354 // following the stored step no longer makes a match.
355 const mid = g.blockAt(1, 1);
356 assert.ok(mid);
357 assert.equal(mid.color, 0);
358 mid.color = 9;
359 const r2 = Offline.tryBotRoll(g, 1, () => 0, memory);
360 assert.notEqual(r2.followed, true);
361 // Plan was dropped; a new plan may or may not exist after the
362 // recolor, but the invalid step must not have been executed.
363 if (r2.moved)
364 {
365 assert.ok(
366 r2.move.col !== next.col
367 || r2.move.fromY !== next.fromY
368 || r2.move.toY !== next.toY
369 || r2.planned === true,
370 'must not blindly follow an invalid step'
371 );
372 }
373 });
374
375 it('does not start a new 2-step plan at or below 10% skill', () =>
376 {
377 const g = setupTwoStep(makeGame({ noSpawn: true }));
378 const memory = { plan: null };
379 // Successful roll (0 < 0.10) but lookaheadChance is 0, so no
380 // second rng() and no setup.
381 const r = Offline.tryBotRoll(g, 0.10, () => 0, memory);
382 assert.equal(r.success, true);
383 assert.equal(r.moved, false);
384 assert.equal(memory.plan, null);
385 assert.equal(Offline.findBotMove(g), null);
386 });
387
388 it('does not propose illegal swaps (gap, locked column, or off-segment)', () =>
389 {
390 const g = makeGame({ noSpawn: true });
391 // Gapped column 0: segments [0,1] and [3,4] — a cross-gap swap
392 // is illegal. Locked full column 1 is also illegal.
393 g.place(0, 0, 0);
394 g.place(0, 1, 1);
395 g.place(0, 3, 0);
396 g.place(0, 4, 2);
397 fillColumn(g, 1, 13, [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2]);
398 g.checkLocks();
399 assert.equal(g.isColumnLocked(1), true);
400 // Legal 2-step fixture on cols 2–4 (same shape, shifted).
401 g.place(2, 0, 0);
402 g.place(2, 1, 1);
403 g.place(2, 2, 2);
404 g.place(2, 3, 0);
405 g.place(3, 0, 3);
406 g.place(3, 1, 0);
407 g.place(3, 2, 4);
408 g.place(3, 3, 5);
409 g.place(4, 0, 6);
410 g.place(4, 1, 7);
411 g.place(4, 2, 0);
412 g.place(4, 3, 8);
413
414 const grid = Offline.snapshotGrid(g);
415 const coreMoves = Offline.listMovesFromCore(g);
416 for (const m of coreMoves)
417 {
418 assert.notEqual(m.col, 1, 'locked column must have no moves: ' + JSON.stringify(m));
419 assert.ok(inSameSegment(grid, g.height, m), 'core move crossed a gap: ' + JSON.stringify(m));
420 if (m.col === 0)
421 {
422 const low = m.fromY <= 1 && m.toY <= 1;
423 const high = m.fromY >= 3 && m.toY >= 3;
424 assert.ok(low || high, 'col 0 move crossed the gap: ' + JSON.stringify(m));
425 }
426 }
427
428 assert.equal(Offline.findBotMove(g), null);
429 const plan = Offline.findSetupPlan(g);
430 assert.ok(plan, 'expected a legal 2-step on cols 2–4');
431 assert.notEqual(plan.steps[0].col, 1);
432 assert.ok(inSameSegment(grid, g.height, plan.steps[0]));
433 const firstLegal = coreMoves.some((m) =>
434 m.col === plan.steps[0].col
435 && m.fromY === plan.steps[0].fromY
436 && m.toY === plan.steps[0].toY);
437 assert.ok(firstLegal, 'first plan step must be in listMovesFromCore');
438 assert.ok(Offline.executeBotMove(g, plan.steps[0]), 'first step must be executable');
439 const grid2 = Offline.snapshotGrid(g);
440 assert.ok(inSameSegment(grid2, g.height, plan.steps[1]),
441 'second step crossed a gap: ' + JSON.stringify(plan.steps[1]));
442 assert.ok(Offline.stepIsValid(g, plan.steps[1], true));
443 assert.ok(Offline.executeBotMove(g, plan.steps[1]));
444 });
445
446 it('finishes a full 10×13 search quickly and within budget', () =>
447 {
448 const g = makeGame({ noSpawn: true });
449 for (let c = 0; c < g.width; c++)
450 {
451 for (let r = 0; r < g.height; r++)
452 { g.place(c, r, (c + r) % 3); }
453 }
454 const t0 = Date.now();
455 const plan = Offline.findSetupPlan(g);
456 const ms = Date.now() - t0;
457 assert.ok(ms < 200, 'planner took ' + ms + ' ms on a full board');
458 if (plan)
459 {
460 const grid = Offline.snapshotGrid(g);
461 assert.ok(inSameSegment(grid, g.height, plan.steps[0]));
462 assert.ok(Offline.executeBotMove(g, plan.steps[0]));
463 }
464 });
465 });
@@ -2,7 +2,7 @@
2
2
3const { describe, it } = require('node:test');
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
4const assert = require('node:assert/strict');
5const { makeGame, Planet, Rng, GameCore } = require('./helpers.js');
5const { makeGame, fillColumn, Planet, Rng, GameCore } = require('./helpers.js');
6const Offline = require('../src/offline.js');
6const Offline = require('../src/offline.js');
7
7
8describe('Offline Strijd progression (t1119)', () =>
8describe('Offline Strijd progression (t1119)', () =>
@@ -206,3 +206,260 @@ describe('Offline battle flow (t1119)', () =>
206 assert.equal(battle.round, 3);
206 assert.equal(battle.round, 3);
207 });
207 });
208});
208});
209
210function setupTwoStep (g)
211{
212 // No immediate 3-match. After col0: 0→1 ([1,0,2,0]) a second
213 // adjacent swap on col2 (7 at y=1 → y=2) makes row 1 = 0,0,0.
214 g.place(0, 0, 0);
215 g.place(0, 1, 1);
216 g.place(0, 2, 2);
217 g.place(0, 3, 0);
218 g.place(1, 0, 3);
219 g.place(1, 1, 0);
220 g.place(1, 2, 4);
221 g.place(1, 3, 5);
222 g.place(2, 0, 6);
223 g.place(2, 1, 7);
224 g.place(2, 2, 0);
225 g.place(2, 3, 8);
226 return g;
227}
228
229function inSameSegment (grid, height, move)
230{
231 if (move.fromY === move.toY)
232 { return false; }
233 const lo = Math.min(move.fromY, move.toY);
234 const hi = Math.max(move.fromY, move.toY);
235 for (let y = lo; y <= hi; y++)
236 {
237 if (grid[move.col][y] == null)
238 { return false; }
239 }
240 return lo >= 0 && hi < height;
241}
242
243describe('Bot lookahead planner (t1144)', () =>
244{
245 it('lookaheadChance is 0 through 10% skill, then linear to 1 at 40%', () =>
246 {
247 assert.equal(Offline.lookaheadChance(0), 0);
248 assert.equal(Offline.lookaheadChance(0.05), 0);
249 assert.equal(Offline.lookaheadChance(0.10), 0);
250 assert.ok(Math.abs(Offline.lookaheadChance(0.25) - 0.5) < 1e-12);
251 assert.equal(Offline.lookaheadChance(0.40), 1);
252 assert.equal(Offline.lookaheadChance(1), 1);
253 });
254
255 it('finds a 1-step immediate match and prefers it over a setup', () =>
256 {
257 const g = makeGame({ noSpawn: true });
258 // Immediate: col0 [0,0,1,0] — also leave a 2-step shape on the right
259 // that must not be chosen while the 1-step exists.
260 g.place(0, 0, 0);
261 g.place(0, 1, 0);
262 g.place(0, 2, 1);
263 g.place(0, 3, 0);
264 g.place(1, 0, 3);
265 g.place(1, 1, 0);
266 g.place(1, 2, 4);
267 g.place(1, 3, 5);
268 g.place(2, 0, 6);
269 g.place(2, 1, 7);
270 g.place(2, 2, 0);
271 g.place(2, 3, 8);
272 const move = Offline.findBotMove(g);
273 assert.ok(move, 'expected an immediate move');
274 assert.equal(move.col, 0);
275 assert.equal(move.dist, 1);
276 const memory = { plan: null };
277 const r = Offline.tryBotRoll(g, 1, () => 0, memory);
278 assert.equal(r.success, true);
279 assert.equal(r.moved, true);
280 assert.equal(r.planned, undefined);
281 assert.equal(memory.plan, null);
282 assert.equal(r.move.col, 0);
283 assert.equal(r.move.dist, 1);
284 const launched = g.resolveMatches();
285 assert.ok(launched.length >= 1, 'immediate move must create a match');
286 });
287
288 it('finds a 2-step setup when no immediate match exists', () =>
289 {
290 const g = setupTwoStep(makeGame({ noSpawn: true }));
291 assert.equal(Offline.findBotMove(g), null, 'fixture must have no 1-step');
292 const plan = Offline.findSetupPlan(g);
293 assert.ok(plan && plan.steps && plan.steps.length === 2, 'expected a 2-step plan');
294 assert.equal(plan.steps[0].dist + plan.steps[1].dist, plan.total);
295 assert.ok(plan.total >= 2);
296 const firstLegal = Offline.listMovesFromCore(g).some((m) =>
297 m.col === plan.steps[0].col
298 && m.fromY === plan.steps[0].fromY
299 && m.toY === plan.steps[0].toY);
300 assert.ok(firstLegal, 'first step must be a legal core move');
301 assert.ok(Offline.executeBotMove(g, plan.steps[0]));
302 assert.equal(Offline.hasMatch(Offline.snapshotGrid(g), g.width, g.height), false,
303 'first step itself is a setup, not a match');
304 assert.ok(Offline.stepIsValid(g, plan.steps[1], true),
305 'second step must still be legal and create a match');
306 assert.ok(Offline.executeBotMove(g, plan.steps[1]));
307 const launched = g.resolveMatches();
308 assert.ok(launched.length >= 1, 'second step must create a match');
309 });
310
311 it('performs the first step and follows the plan on the next successful roll', () =>
312 {
313 const g = setupTwoStep(makeGame({ noSpawn: true }));
314 const memory = { plan: null };
315 const r1 = Offline.tryBotRoll(g, 1, () => 0, memory);
316 assert.equal(r1.success, true);
317 assert.equal(r1.moved, true);
318 assert.equal(r1.planned, true);
319 assert.ok(memory.plan && memory.plan.steps.length === 2);
320 assert.equal(memory.plan.index, 1);
321 assert.equal(Offline.hasMatch(Offline.snapshotGrid(g), g.width, g.height), false);
322
323 const r2 = Offline.tryBotRoll(g, 1, () => 0, memory);
324 assert.equal(r2.success, true);
325 assert.equal(r2.moved, true);
326 assert.equal(r2.followed, true);
327 assert.equal(memory.plan, null);
328 const launched = g.resolveMatches();
329 assert.ok(launched.length >= 1, 'followed step must create a match');
330 });
331
332 it('follows a committed plan even below the lookahead threshold', () =>
333 {
334 const g = setupTwoStep(makeGame({ noSpawn: true }));
335 const memory = { plan: null };
336 assert.ok(Offline.tryBotRoll(g, 1, () => 0, memory).planned);
337 // skill 5% is below the 10% lookahead floor, but the roll succeeds
338 // (0 < 0.05) and the stored second step is still valid.
339 assert.equal(Offline.lookaheadChance(0.05), 0);
340 const r = Offline.tryBotRoll(g, 0.05, () => 0, memory);
341 assert.equal(r.followed, true);
342 assert.equal(r.moved, true);
343 });
344
345 it('re-plans when the stored next step is no longer valid', () =>
346 {
347 const g = setupTwoStep(makeGame({ noSpawn: true }));
348 const memory = { plan: null };
349 const r1 = Offline.tryBotRoll(g, 1, () => 0, memory);
350 assert.ok(r1.planned && memory.plan);
351 const next = memory.plan.steps[1];
352 // After the first step, row 1 is a pair of 0s waiting for the
353 // third 0 from the second step. Recolor the middle 0 so that
354 // following the stored step no longer makes a match.
355 const mid = g.blockAt(1, 1);
356 assert.ok(mid);
357 assert.equal(mid.color, 0);
358 mid.color = 9;
359 const r2 = Offline.tryBotRoll(g, 1, () => 0, memory);
360 assert.notEqual(r2.followed, true);
361 // Plan was dropped; a new plan may or may not exist after the
362 // recolor, but the invalid step must not have been executed.
363 if (r2.moved)
364 {
365 assert.ok(
366 r2.move.col !== next.col
367 || r2.move.fromY !== next.fromY
368 || r2.move.toY !== next.toY
369 || r2.planned === true,
370 'must not blindly follow an invalid step'
371 );
372 }
373 });
374
375 it('does not start a new 2-step plan at or below 10% skill', () =>
376 {
377 const g = setupTwoStep(makeGame({ noSpawn: true }));
378 const memory = { plan: null };
379 // Successful roll (0 < 0.10) but lookaheadChance is 0, so no
380 // second rng() and no setup.
381 const r = Offline.tryBotRoll(g, 0.10, () => 0, memory);
382 assert.equal(r.success, true);
383 assert.equal(r.moved, false);
384 assert.equal(memory.plan, null);
385 assert.equal(Offline.findBotMove(g), null);
386 });
387
388 it('does not propose illegal swaps (gap, locked column, or off-segment)', () =>
389 {
390 const g = makeGame({ noSpawn: true });
391 // Gapped column 0: segments [0,1] and [3,4] — a cross-gap swap
392 // is illegal. Locked full column 1 is also illegal.
393 g.place(0, 0, 0);
394 g.place(0, 1, 1);
395 g.place(0, 3, 0);
396 g.place(0, 4, 2);
397 fillColumn(g, 1, 13, [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2]);
398 g.checkLocks();
399 assert.equal(g.isColumnLocked(1), true);
400 // Legal 2-step fixture on cols 2–4 (same shape, shifted).
401 g.place(2, 0, 0);
402 g.place(2, 1, 1);
403 g.place(2, 2, 2);
404 g.place(2, 3, 0);
405 g.place(3, 0, 3);
406 g.place(3, 1, 0);
407 g.place(3, 2, 4);
408 g.place(3, 3, 5);
409 g.place(4, 0, 6);
410 g.place(4, 1, 7);
411 g.place(4, 2, 0);
412 g.place(4, 3, 8);
413
414 const grid = Offline.snapshotGrid(g);
415 const coreMoves = Offline.listMovesFromCore(g);
416 for (const m of coreMoves)
417 {
418 assert.notEqual(m.col, 1, 'locked column must have no moves: ' + JSON.stringify(m));
419 assert.ok(inSameSegment(grid, g.height, m), 'core move crossed a gap: ' + JSON.stringify(m));
420 if (m.col === 0)
421 {
422 const low = m.fromY <= 1 && m.toY <= 1;
423 const high = m.fromY >= 3 && m.toY >= 3;
424 assert.ok(low || high, 'col 0 move crossed the gap: ' + JSON.stringify(m));
425 }
426 }
427
428 assert.equal(Offline.findBotMove(g), null);
429 const plan = Offline.findSetupPlan(g);
430 assert.ok(plan, 'expected a legal 2-step on cols 2–4');
431 assert.notEqual(plan.steps[0].col, 1);
432 assert.ok(inSameSegment(grid, g.height, plan.steps[0]));
433 const firstLegal = coreMoves.some((m) =>
434 m.col === plan.steps[0].col
435 && m.fromY === plan.steps[0].fromY
436 && m.toY === plan.steps[0].toY);
437 assert.ok(firstLegal, 'first plan step must be in listMovesFromCore');
438 assert.ok(Offline.executeBotMove(g, plan.steps[0]), 'first step must be executable');
439 const grid2 = Offline.snapshotGrid(g);
440 assert.ok(inSameSegment(grid2, g.height, plan.steps[1]),
441 'second step crossed a gap: ' + JSON.stringify(plan.steps[1]));
442 assert.ok(Offline.stepIsValid(g, plan.steps[1], true));
443 assert.ok(Offline.executeBotMove(g, plan.steps[1]));
444 });
445
446 it('finishes a full 10×13 search quickly and within budget', () =>
447 {
448 const g = makeGame({ noSpawn: true });
449 for (let c = 0; c < g.width; c++)
450 {
451 for (let r = 0; r < g.height; r++)
452 { g.place(c, r, (c + r) % 3); }
453 }
454 const t0 = Date.now();
455 const plan = Offline.findSetupPlan(g);
456 const ms = Date.now() - t0;
457 assert.ok(ms < 200, 'planner took ' + ms + ' ms on a full board');
458 if (plan)
459 {
460 const grid = Offline.snapshotGrid(g);
461 assert.ok(inSameSegment(grid, g.height, plan.steps[0]));
462 assert.ok(Offline.executeBotMove(g, plan.steps[0]));
463 }
464 });
465});