using System; using System.Collections.Generic; using System.Diagnostics; using YGOLegacy.Bot; namespace YGOLegacy.Tools.BotArena { /// /// TICKET-050 — the PERFECT-INFORMATION rollout oracle (Phase A). /// /// ocgcore cannot clone a live duel, so the only way to get a "future" out /// of one is to build a second duel that IS this one and then diverge: /// /// * the in-process host seeds ocgcore's create_duel AND its own /// deck shuffle from one number (ArenaReport.CoreSeedFor), so a /// fresh host with the same seed and the same two deck lists deals the /// identical game; /// * imposes the turn /// order the real duel rolled for (rock-paper-scissors is answered from /// WindBot's RNG, which the response log does not cover); /// * replays every /// answer BOTH seats have given so far, walking the copy to exactly the /// prompt being decided; /// * the candidate idle command is appended as the last scripted answer; /// * from there two Lucky bots play on to a horizon and the position is /// scored. /// /// This PEEKS: the copy is dealt from the same shuffle, so a rollout knows /// the enemy's hand and the order of both decks. That is deliberate — it is /// the CEILING of what any rollout planner could be worth on this engine. /// If lookahead does not pay here it cannot pay with an honest determinized /// rebuild either. Nothing in the shipped game may use it, and nothing does: /// SmartExecutor.Oracle is null everywhere except this tool. /// /// Isolation: one duel at a time on one thread (ocgcore's card/script /// readers are process-global and already installed by /// ); WindBot.Program.Rand is swapped for an /// oracle-owned stream and put back, so the real duel's randomness is /// untouched and an A/B stays paired; and the rollout seats are named apart /// from the real ones so their MSG_WIN verdicts cannot be counted as the /// duel's. /// internal sealed class ReplayOracle : ILookaheadOracle { /// /// Builds one rollout seat. The worker owns the WindBot statics, so it /// supplies this rather than the oracle reaching for them. /// internal delegate ILoopbackSeat SeatFactory(string username, int seatIndex); /// Seat index (0 = A) this oracle answers for. private readonly int mySeat; private readonly Action log; private LocalDuelHost host; private SeatFactory makeSeat; private IList mainA, extraA, mainB, extraB; private int coreSeed; private Random rolloutRng; private int rolloutCounter; public string LastNote { get; private set; } /// Run totals, for the worker log. public int Rollouts { get; private set; } public int Abandoned { get; private set; } public long RolloutMs { get; private set; } internal ReplayOracle(int seat, Action log) { mySeat = seat; this.log = log; } /// /// Hand the oracle the duel it is to copy. Called after both seats and /// both decks exist and before the host runs, so nothing can roll out /// before it is complete. /// internal void Attach(LocalDuelHost liveHost, SeatFactory factory, IList mainA, IList extraA, IList mainB, IList extraB, int coreSeed) { host = liveHost; makeSeat = factory; this.mainA = mainA; this.extraA = extraA; this.mainB = mainB; this.extraB = extraB; this.coreSeed = coreSeed; // Deterministic per duel and independent of the duel's own stream, // so two arms on the same --seed face identical rollout noise. rolloutRng = new Random(unchecked(coreSeed * 31 + 17)); rolloutCounter = 0; } public bool Available => host != null && makeSeat != null && host.Live.Responses != null; public float Evaluate(int idleResponse, int rollouts, int horizonTurns, int msBudget) { LastNote = null; if (!Available || rollouts <= 0) return float.NaN; var live = host.Live; // The child host holds the list for the length of its duel, so give // it a copy: the real duel keeps appending to its own. var script = new List(live.Responses.Count + 1); script.AddRange(live.Responses); script.Add(BitConverter.GetBytes(idleResponse)); int stopAfter = horizonTurns > 0 ? live.Turns + horizonTurns : 0; var sw = Stopwatch.StartNew(); float sum = 0f; int done = 0, failed = 0; string firstWhy = null; var savedRand = WindBot.Program.Rand; try { for (var i = 0; i < rollouts; i++) { if (msBudget > 0 && sw.ElapsedMilliseconds >= msBudget) break; WindBot.Program.Rand = new Random(unchecked(rolloutRng.Next() ^ (++rolloutCounter * 7919))); var value = PlayOne(script, stopAfter, out var why); if (float.IsNaN(value)) { failed++; firstWhy ??= why; continue; } sum += value; done++; } } finally { WindBot.Program.Rand = savedRand; RolloutMs += sw.ElapsedMilliseconds; } Rollouts += done; Abandoned += failed; if (failed > 0) LastNote = failed + " abandoned" + (firstWhy != null ? ": " + firstWhy : string.Empty); return done == 0 ? float.NaN : sum / done; } /// One playout. 0..1, or NaN when it could not be played. private float PlayOne(IList script, int stopAfter, out string why) { why = null; try { var child = new LocalDuelHost(new LocalDuelHost.Options { SeatA = makeSeat("LookA", 0), SeatB = makeSeat("LookB", 1), MainA = mainA, ExtraA = extraA, MainB = mainB, ExtraB = extraB, Seed = coreSeed, ForcedFirstSeat = host.Live.FirstSeat, ScriptedResponses = script, StopAfterTurn = stopAfter, // A rollout that will not converge is worth nothing: give up // early rather than spend the decision's whole budget on it. TurnLimit = stopAfter > 0 ? stopAfter + 4 : 200, MessageLimit = 200000, }); var outcome = child.Run(); if (outcome.Error != null) { why = outcome.Error; return float.NaN; } return Value(outcome); } catch (Exception e) { why = e.GetType().Name + ": " + e.Message; return float.NaN; } } /// /// 1 = we won, 0 = we lost, 0.5 = a draw. At the horizon the position is /// mapped into 0.1..0.9 (never as certain as a real result) from the /// life-point difference plus a small board term — the host has no /// ClientCard view, so monster COUNT is all the board it can see. /// Deliberately crude: the prototype asks whether a rollout signal /// exists at all, not how finely it can be scored. /// private float Value(LocalDuelOutcome outcome) { int myPlayer = host.Live.FirstSeat == mySeat ? 0 : 1; if (!outcome.Horizon) { if (outcome.Winner < 0) return float.NaN; if (outcome.Winner == 2) return 0.5f; return outcome.Winner == myPlayer ? 1f : 0f; } int mine = outcome.Lp[myPlayer], theirs = outcome.Lp[1 - myPlayer]; if (mine <= 0) return 0f; if (theirs <= 0) return 1f; float v = 0.5f + (mine - theirs) / 16000f + 0.04f * (outcome.Monsters[myPlayer] - outcome.Monsters[1 - myPlayer]); if (v < 0.1f) v = 0.1f; if (v > 0.9f) v = 0.9f; return v; } internal void LogSummary(int duelIndex) { if (Rollouts == 0 && Abandoned == 0) return; log?.Invoke("lookahead seat " + (mySeat == 0 ? "A" : "B") + " duel " + duelIndex + ": " + Rollouts + " rollouts, " + Abandoned + " abandoned, " + RolloutMs + " ms"); } } }