Files
yugioh-legacy-bots/src/BotArena/ReplayOracle.cs
T
donny 6dbc9e78d8 import: the bot code from yugioh-legacy-unity dev at 19c6158197a0a8f0817dd0924bb9a6a987c2bfc5
Verbatim copies, new layout, no edits:

  Assets/Scripts/Windbot/** (minus BotWrapper.cs)       -> src/YGOLegacy.Bots/WindBot/
  Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper.Enums/*   -> src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/
  Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper/{Card,NamedCard,NamedCardsManager,CardsManager}.cs
                                                        -> src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/
  Assets/Scripts/YGOSharp/YGOSharp.Network/{BinaryClient,NetworkClient,YGOClient}.cs, Enums/*, Utils/BinaryExtensions.cs
                                                        -> src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/
  Assets/YGOLegacy/Scripts/Core/Bot/{SmartExecutor,BoardEvaluator,BattlePredictor,BrainRules,EffectSimulator,
    DuelStateBus,LocalDuelHost,LoopbackBotSeat,Lookahead,ArenaReport}.cs -> src/YGOLegacy.Bots/Bot/
  Assets/YGOLegacy/Scripts/Core/Identity/Characters/{Character,CharacterRegistry}.cs -> src/YGOLegacy.Bots/Characters/
  Assets/YGOLegacy/Scripts/Features/Solo/BotRoster.cs   -> src/YGOLegacy.Bots/Services/
  Tools/BotArena/**                                     -> src/BotArena/

Commit: 19c6158 (2026-10-19T15:29:54-07:00) duel: 8 prompt and bot fixes from duel bug hunt round 2
2026-10-19 18:08:01 -07:00

208 lines
8.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using YGOLegacy.Bot;
namespace YGOLegacy.Tools.BotArena
{
/// <summary>
/// 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 <c>create_duel</c> AND its own
/// deck shuffle from one number (<c>ArenaReport.CoreSeedFor</c>), so a
/// fresh host with the same seed and the same two deck lists deals the
/// identical game;
/// * <see cref="LocalDuelHost.Options.ForcedFirstSeat"/> 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);
/// * <see cref="LocalDuelHost.Options.ScriptedResponses"/> 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:
/// <c>SmartExecutor.Oracle</c> 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
/// <see cref="LocalHost"/>); <c>WindBot.Program.Rand</c> 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.
/// </summary>
internal sealed class ReplayOracle : ILookaheadOracle
{
/// <summary>
/// Builds one rollout seat. The worker owns the WindBot statics, so it
/// supplies this rather than the oracle reaching for them.
/// </summary>
internal delegate ILoopbackSeat SeatFactory(string username, int seatIndex);
/// Seat index (0 = A) this oracle answers for.
private readonly int mySeat;
private readonly Action<string> log;
private LocalDuelHost host;
private SeatFactory makeSeat;
private IList<int> mainA, extraA, mainB, extraB;
private int coreSeed;
private Random rolloutRng;
private int rolloutCounter;
public string LastNote { get; private set; }
/// <summary>Run totals, for the worker log.</summary>
public int Rollouts { get; private set; }
public int Abandoned { get; private set; }
public long RolloutMs { get; private set; }
internal ReplayOracle(int seat, Action<string> log)
{
mySeat = seat;
this.log = log;
}
/// <summary>
/// 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.
/// </summary>
internal void Attach(LocalDuelHost liveHost, SeatFactory factory,
IList<int> mainA, IList<int> extraA,
IList<int> mainB, IList<int> 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<byte[]>(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;
}
/// <summary>One playout. 0..1, or NaN when it could not be played.</summary>
private float PlayOne(IList<byte[]> 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;
}
}
/// <summary>
/// 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.
/// </summary>
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");
}
}
}