Files
yugioh-legacy-bots/src/YGOLegacy.Bots/Decisions/Decisions.cs
T
donnyandClaude Opus 5.5 c034354d12
CI / build (push) Successful in 57s
feat(decisions): host default, first brain, every choice through the seam; v0.2.0
BotHost.Decisions is the default decision maker for seats without a Decisions= token (builtin overrides it).
'first' answers from the request's JSON alone, sums and counters included. MSG_SORT_CHAIN, the field-first card
prompt and the effect prompt of an unknown card now ask the maker too (built-in answers unchanged); only
prompts with no choice are answered without asking, and seats with a maker log their counts per duel.

Tests: the built-in --seed 7 report equals the v0.1.0 release's (tests/fixture/expected, clocks aside); first vs
first, 100 duels: 15952 prompts asked, 0 handed back, 0 errors, unasked only 'chain: nothing to chain'.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 18:38:00 -07:00

271 lines
13 KiB
C#

using System;
using System.Collections.Generic;
namespace YGOLegacy.Bots.Decisions
{
/// <summary>
/// The decision seam. At every prompt the engine sends a seat (summon or attack, pick cards, chain or not,
/// yes or no, ...) WindBot's GameBehavior asks the seat's decision maker before it asks the seat's own brain
/// (its WindBot executor: SmartExecutor for character decks, Lucky for Dovphin, a deck executor otherwise).
/// The question is a <see cref="DecisionRequest"/> (what the seat sees plus the legal options), the answer a
/// <see cref="Decision"/> (which options). Both are plain data, so a maker can live in another process or on
/// another machine (an LLM, a model on a GPU box) behind JSON.
///
/// A seat with no maker (the default) is answered by its executor exactly as before: no request is built.
/// A maker that returns null, throws, or answers something illegal for a prompt hands that prompt to the
/// executor too, so a maker can take over some prompt kinds and leave the rest.
/// </summary>
public interface IDecisionMaker
{
/// The answer to one prompt, or null to let the seat's built-in brain answer it. Called on the bot's
/// thread, and the duel waits for it.
Decision Decide(DecisionRequest request);
}
/// <summary>
/// Which seats get a maker. A seat names one with the WindBot token <c>Decisions=&lt;name&gt;</c> (the arena:
/// <c>--decisionsA/--decisionsB</c>); a seat without the token gets <see cref="BotHost.Decisions"/> (default
/// none). The host or a plug-in registers the names. <see cref="BuiltIn"/> is the seat's own executor.
/// </summary>
public static class DecisionMakers
{
/// The seat's WindBot executor (SmartExecutor for character decks): no maker at all.
public const string BuiltIn = "builtin";
/// A uniformly random legal option at every prompt it can answer safely (never sums or counters). A
/// baseline for measuring brains, and the seam's own end-to-end test. Seeded from WindBot's
/// Program.Rand when the seat is built, so a seeded arena run repeats.
public const string Random = "random";
/// The first legal option at every prompt, read from the request alone (sums and counters solved from the
/// options' values). The test brain: deterministic, never hands a prompt back.
public const string First = "first";
private static readonly Dictionary<string, Func<DecisionSeat, IDecisionMaker>> factories =
new Dictionary<string, Func<DecisionSeat, IDecisionMaker>>(StringComparer.OrdinalIgnoreCase)
{
[Random] = seat => new RandomDecisions(WindBot.Program.Rand?.Next() ?? 0),
[First] = seat => new FirstDecisions(),
};
/// Register (or replace) a maker by name. Safe from any thread.
public static void Register(string name, Func<DecisionSeat, IDecisionMaker> factory)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentException("a decision maker needs a name", nameof(name));
if (string.Equals(name, BuiltIn, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException("'" + BuiltIn + "' is the seat's own executor");
lock (factories) factories[name] = factory ?? throw new ArgumentNullException(nameof(factory));
}
public static bool Unregister(string name)
{
lock (factories) return factories.Remove(name);
}
/// The maker for a seat, or null for its built-in brain. An unknown name is logged and gets the built-in.
public static IDecisionMaker For(DecisionSeat seat)
{
var name = string.IsNullOrEmpty(seat?.decisions) ? BotHost.Decisions : seat.decisions;
if (string.IsNullOrEmpty(name) || string.Equals(name, BuiltIn, StringComparison.OrdinalIgnoreCase))
return null;
Func<DecisionSeat, IDecisionMaker> factory;
lock (factories) factories.TryGetValue(name, out factory);
if (factory == null)
{
BotHost.Log.Warning("[YGOL decisions] seat '" + seat.name + "': no decision maker named '" + name + "'; its own brain decides");
return null;
}
return factory(seat);
}
}
/// The seat a maker is built for.
[Serializable]
public class DecisionSeat
{
public string name;
/// The WindBot executor that answers whatever the maker leaves (Deck= token: Smart, Lucky, ...).
public string executor;
public string deck;
public string character;
/// The Decisions= token.
public string decisions;
}
/// The prompt kinds (<see cref="DecisionRequest.kind"/>).
public static class DecisionKind
{
/// Main phase: one option (summon, special summon, reposition, set, activate, to battle, to end).
public const string Idle = "idle";
/// Battle phase: one option (activate, attack, to main 2, to end).
public const string Battle = "battle";
/// Choose min..max cards; none = cancel when cancelable.
public const string Card = "card";
/// Same, for tributes.
public const string Tribute = "tribute";
/// Choose one more card or none (finish) when cancelable.
public const string UnselectCard = "unselectCard";
/// Chain one of the options, or none.
public const string Chain = "chain";
/// Use an optional effect: option 0 = no, 1 = yes.
public const string EffectYesNo = "effectYesNo";
/// A yes/no question (description = the string id): option 0 = no, 1 = yes.
public const string YesNo = "yesNo";
/// Pick one of several effect texts (option description = the string id).
public const string Option = "option";
/// A battle position for card <see cref="DecisionRequest.code"/>.
public const string Position = "position";
/// A zone (option value = the zone bit, option player = whose field).
public const string Place = "place";
/// Choose cards whose values (option value / value2) make <see cref="DecisionRequest.value"/>, exactly
/// when <see cref="DecisionRequest.exact"/>, else at least.
public const string Sum = "sum";
/// Remove <see cref="DecisionRequest.value"/> counters of type <see cref="DecisionRequest.code"/>: answer
/// <see cref="Decision.counts"/>, one count per option (option value = counters on it).
public const string Counter = "counter";
/// Declare min..max attributes (option value = the attribute bit).
public const string Attribute = "attribute";
/// Declare min..max types (option value = the race bit).
public const string Race = "race";
/// Declare a number (option value).
public const string Number = "number";
/// Declare a card name (option card code).
public const string AnnounceCard = "announceCard";
/// Order these cards: choose every option, first to last.
public const string Sort = "sort";
/// Order chain links the engine lets this seat order: choose every option, in the new order.
public const string SortChain = "sortChain";
/// Rock-paper-scissors (option value 1 scissors, 2 rock, 3 paper).
public const string RockPaperScissors = "rockPaperScissors";
/// Go first (option 0) or second (option 1).
public const string TurnOrder = "turnOrder";
}
/// <summary>One prompt. Plain data: every field is JSON-friendly.</summary>
[Serializable]
public class DecisionRequest
{
/// The request/answer format; bumped when a field changes meaning.
public int version = 1;
public string kind;
/// The seat being asked (its name in the room).
public string seat;
/// The prompt's number in this duel, from 1, for this seat.
public int prompt;
/// How many options to choose.
public int min = 1;
public int max = 1;
/// Choosing nothing is allowed (cancel, finish, no chain).
public bool cancelable;
/// The engine's select hint (HINTMSG_* string id) for card prompts, 0 = none.
public int hint;
/// The effect description (string id: card code * 16 + index, or a system string) of a yes/no prompt.
public long description;
/// Kind-specific: the card asked about (position), the counter type (counter).
public int code;
/// Kind-specific: the sum to reach (sum), how many counters to remove (counter), the chain timing (chain).
public int value;
/// Sum: exactly `value` (true) or at least (false).
public bool exact;
public List<DecisionOption> options = new List<DecisionOption>();
/// What this seat sees of the duel when it is asked.
public DuelView duel;
}
[Serializable]
public class DecisionOption
{
/// The option's position in <see cref="DecisionRequest.options"/>; the answer names options by it.
public int index;
/// What choosing it does (idle and battle: summon, spSummon, reposition, setMonster, setSpell, activate,
/// attack, toBattle, toMain2, toEnd; yes/no: no, yes; turn order: first, second), else the kind's noun.
public string action;
/// The card the option is about, or null.
public CardView card;
/// The effect description (string id) of an activation or a text option, 0 = none.
public long description;
/// Kind-specific number (zone bit, attribute/race bit, declared number, counters, sum value).
public int value;
/// Sum: the card's second value (0 = none).
public int value2;
/// Place: whose field (0 = this seat, 1 = the opponent).
public int player;
/// Chain: the engine requires this activation.
public bool forced;
/// Battle attack: the monster can attack directly.
public bool direct;
}
/// <summary>The answer to one prompt.</summary>
[Serializable]
public class Decision
{
/// The chosen options' indices, in order (for sort: every option, first to last). Empty = nothing (cancel,
/// finish, no chain) where the request is cancelable.
public List<int> choose = new List<int>();
/// Counter prompts only: how many counters to remove from each option, in option order.
public List<int> counts;
public static Decision Of(params int[] indices) => new Decision { choose = new List<int>(indices) };
}
/// <summary>What one seat sees of the duel: its own hand and Extra Deck, both fields, public piles, LP.
/// Cards it may not see have code 0.</summary>
[Serializable]
public class DuelView
{
public int turn;
/// draw, standby, main1, battleStart, battleStep, damage, damageCalculation, battle, main2, end.
public string phase;
/// It is this seat's turn.
public bool myTurn;
public PlayerView me;
public PlayerView opponent;
/// The chain being built, first link first.
public List<CardView> chain = new List<CardView>();
}
[Serializable]
public class PlayerView
{
public int lp;
public List<CardView> hand = new List<CardView>();
/// Main Monster Zones 0-4 and the Extra Monster Zones 5-6; empty zones are left out (see sequence).
public List<CardView> monsters = new List<CardView>();
/// Spell & Trap Zones 0-4, the Field Zone 5 and the Pendulum Zones 6-7; empty zones left out.
public List<CardView> spells = new List<CardView>();
public List<CardView> graveyard = new List<CardView>();
public List<CardView> banished = new List<CardView>();
/// This seat's own Extra Deck (the opponent's is only counted).
public List<CardView> extra = new List<CardView>();
public int deckCount;
public int extraCount;
}
[Serializable]
public class CardView
{
/// The card's code (0 = not visible to this seat).
public int code;
public string name;
/// 0 = this seat, 1 = the opponent.
public int controller;
/// deck, hand, monster, spell, graveyard, banished, extra, overlay.
public string location;
public int sequence;
/// faceUpAttack, faceDownAttack, faceUpDefense, faceDownDefense, or null off the field.
public string position;
/// The card's type bits (TYPE_*), attribute bit and race bit, as in the card database.
public int type;
public int attribute;
public int race;
public int level;
public int rank;
public int link;
public int attack;
public int defense;
/// Xyz materials attached.
public int overlays;
public bool disabled;
}
}