Files
yugioh-legacy-bots/src/YGOLegacy.Bots/WindBot/Game/GameBehavior.YGOL_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

506 lines
23 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using YGOLegacy.Bots;
using YGOLegacy.Bots.Decisions;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game
{
// [YGOL] The decision seam (YGOLegacy.Bots.Decisions). Every prompt handler asks YGOL_Decide instead of the
// GameAI directly: with no decision maker for this seat (the default) that is the GameAI call itself and
// nothing else, so the built-in brain plays exactly as before. With one, the prompt goes out as plain data,
// the answer comes back as option indices and is turned into what the GameAI would have returned, and the
// handler sends it the usual way. Whatever the maker leaves (null, an exception, an illegal answer) the
// GameAI answers.
public partial class GameBehavior
{
private IDecisionMaker _ygolDecisions;
private int _ygolPrompt;
// What the seam did this duel (logged at MSG_WIN when the seat has a decision maker): prompts asked, prompts
// the maker handed back (null, illegal, threw), and prompts answered without asking because they offer no
// choice (nothing to chain, one forced activation, one position, Hand= fixed the hand).
private int _ygolHandedBack;
private readonly Dictionary<string, int> _ygolAsked = new Dictionary<string, int>();
private readonly Dictionary<string, int> _ygolUnasked = new Dictionary<string, int>();
private void YGOL_InitDecisions()
{
_ygolDecisions = DecisionMakers.For(new DecisionSeat
{
name = Game.Username,
executor = Game.Deck,
deck = Game.DeckFile,
character = Game.Character,
decisions = Game.YGOL_Decisions,
});
}
/// The GameAI's answer (`builtIn`), or the decision maker's. `build` fills the request and returns how an
/// accepted answer becomes the GameAI's answer type.
private T YGOL_Decide<T>(string kind, Func<DecisionRequest, Func<Decision, T>> build, Func<T> builtIn)
{
if (_ygolDecisions == null)
return builtIn();
try
{
var request = new DecisionRequest { kind = kind, seat = Game.Username, prompt = ++_ygolPrompt };
YGOL_Count(_ygolAsked, kind);
var apply = build(request);
for (int i = 0; i < request.options.Count; ++i)
request.options[i].index = i;
request.duel = YGOL_View();
var answer = _ygolDecisions.Decide(request);
if (answer != null)
{
var why = YGOL_Illegal(request, answer);
if (why == null)
return apply(answer);
BotHost.Log.Warning("[YGOL decisions] " + Game.Username + " prompt " + request.prompt + " (" + kind + "): " + why + "; its own brain answers");
}
}
catch (Exception e)
{
BotHost.Log.Warning("[YGOL decisions] " + Game.Username + " " + kind + ": " + e.GetType().Name + ": " + e.Message + "; its own brain answers");
}
_ygolHandedBack++;
return builtIn();
}
/// A prompt answered without asking anyone: it offers no choice.
private void YGOL_Unasked(string kind, string reason)
{
if (_ygolDecisions == null) return;
YGOL_Count(_ygolUnasked, kind + ": " + reason);
}
private static void YGOL_Count(Dictionary<string, int> counts, string key)
{
counts.TryGetValue(key, out var n);
counts[key] = n + 1;
}
private static string YGOL_Counts(Dictionary<string, int> counts)
=> counts.Count == 0 ? string.Empty : " (" + string.Join(", ", counts.OrderBy(p => p.Key, StringComparer.Ordinal).Select(p => p.Key + " x" + p.Value)) + ")";
private void YGOL_LogDecisionCounts()
{
if (_ygolDecisions == null) return;
BotHost.Log.Info("[YGOL decisions] counts " + Game.Username + ": asked=" + _ygolPrompt + YGOL_Counts(_ygolAsked)
+ " handedBack=" + _ygolHandedBack + " unasked=" + _ygolUnasked.Values.Sum() + YGOL_Counts(_ygolUnasked));
}
/// MSG_SORT_CHAIN: the built-in brain keeps the engine's order (-1) and reads nothing; a decision maker may
/// order the chain links.
private void YGOL_SortChain(BinaryReader packet)
{
if (_ygolDecisions == null)
{
Connection.Send(YGOSharp.Network.Enums.CtosMessage.Response, -1);
return;
}
packet.ReadByte(); // player
int count = packet.ReadByte();
var links = new List<CardView>();
for (int i = 0; i < count; ++i)
{
int code = packet.ReadInt32();
int controller = GetLocalPlayer(packet.ReadByte());
var location = (CardLocation)packet.ReadByte();
int sequence = packet.ReadByte();
links.Add(new CardView { code = code, name = YGOSharp.OCGWrapper.NamedCard.Get(code)?.Name, controller = controller, location = YGOL_Location(location), sequence = sequence });
}
var order = YGOL_Decide<List<int>>(DecisionKind.SortChain, r =>
{
r.min = r.max = count;
foreach (var link in links) r.options.Add(new DecisionOption { action = "link", card = link });
return d => d.choose;
}, () => null);
if (order == null)
{
Connection.Send(YGOSharp.Network.Enums.CtosMessage.Response, -1);
return;
}
var result = new byte[count];
for (int j = 0; j < order.Count; ++j)
result[order[j]] = (byte)j;
var reply = YGOLegacy.Protocol.Codecs.CtosPacket.Begin(YGOLegacy.Protocol.Codecs.DuelCodecs.Response.Id);
YGOLegacy.Protocol.Codecs.DuelCodecs.Response.Write(reply, new YGOLegacy.Protocol.Contracts.Response(result));
Connection.Send(reply);
}
private static string YGOL_Illegal(DecisionRequest request, Decision answer)
{
var n = request.options.Count;
if (request.kind == DecisionKind.Counter)
{
if (answer.counts == null || answer.counts.Count != n) return "counter answers need one count per option";
var total = 0;
for (int i = 0; i < n; ++i)
{
if (answer.counts[i] < 0 || answer.counts[i] > request.options[i].value) return "option " + i + " has " + request.options[i].value + " counters";
total += answer.counts[i];
}
return total == request.value ? null : "removes " + total + " counters, not " + request.value;
}
var chosen = answer.choose ?? new List<int>();
if (chosen.Any(i => i < 0 || i >= n)) return "an index is not an option";
if (chosen.Distinct().Count() != chosen.Count) return "an option is chosen twice";
if (chosen.Count == 0 && request.cancelable) return null;
if (request.kind == DecisionKind.Sort || request.kind == DecisionKind.SortChain) return chosen.Count == n ? null : "sort orders every option";
if (chosen.Count < request.min || chosen.Count > request.max) return "chose " + chosen.Count + ", needs " + request.min + "-" + request.max;
return null;
}
// ---------------------------------------------------------------- what the seat sees
private DuelView YGOL_View()
{
var view = new DuelView
{
turn = _duel.Turn,
phase = YGOL_Phase(_duel.Phase),
myTurn = _duel.Player == 0,
me = YGOL_Player(_duel.Fields[0], true),
opponent = YGOL_Player(_duel.Fields[1], false),
};
foreach (var card in _duel.CurrentChain ?? (IList<ClientCard>)Array.Empty<ClientCard>())
view.chain.Add(YGOL_Card(card));
return view;
}
// Before MSG_START (rock-paper-scissors, turn order) the fields are not set up yet: empty piles.
private PlayerView YGOL_Player(ClientField field, bool me)
{
var none = Array.Empty<ClientCard>();
var player = new PlayerView { lp = field.LifePoints, deckCount = field.Deck?.Count ?? 0, extraCount = field.ExtraDeck?.Count ?? 0 };
foreach (var card in field.Hand ?? none) player.hand.Add(YGOL_Card(card));
foreach (var card in field.MonsterZone ?? none) if (card != null) player.monsters.Add(YGOL_Card(card));
foreach (var card in field.SpellZone ?? none) if (card != null) player.spells.Add(YGOL_Card(card));
foreach (var card in field.Graveyard ?? none) player.graveyard.Add(YGOL_Card(card));
foreach (var card in field.Banished ?? none) player.banished.Add(YGOL_Card(card));
if (me) foreach (var card in field.ExtraDeck ?? none) player.extra.Add(YGOL_Card(card));
return player;
}
private static CardView YGOL_Card(ClientCard card)
{
if (card == null) return null;
var onField = card.Location == CardLocation.MonsterZone || card.Location == CardLocation.SpellZone;
return new CardView
{
code = card.Id,
name = card.Id == 0 ? null : card.Name,
controller = card.Controller,
location = YGOL_Location(card.Location),
sequence = card.Sequence,
position = onField ? YGOL_PositionName(card.Position) : null,
type = card.Type,
attribute = card.Attribute,
race = card.Race,
level = card.Level,
rank = card.Rank,
link = card.LinkCount,
attack = card.Attack,
defense = card.Defense,
overlays = card.Overlays?.Count ?? 0,
disabled = card.Disabled != 0,
};
}
private static string YGOL_Location(CardLocation location)
{
switch (location)
{
case CardLocation.Deck: return "deck";
case CardLocation.Hand: return "hand";
case CardLocation.MonsterZone: return "monster";
case CardLocation.SpellZone: return "spell";
case CardLocation.Grave: return "graveyard";
case CardLocation.Removed: return "banished";
case CardLocation.Extra: return "extra";
case CardLocation.Overlay: return "overlay";
default: return ((int)location).ToString();
}
}
private static string YGOL_PositionName(int position)
{
switch ((CardPosition)position)
{
case CardPosition.FaceUpAttack: return "faceUpAttack";
case CardPosition.FaceDownAttack: return "faceDownAttack";
case CardPosition.FaceUpDefence: return "faceUpDefense";
case CardPosition.FaceDownDefence: return "faceDownDefense";
default: return position.ToString();
}
}
private static string YGOL_Phase(DuelPhase phase)
{
switch (phase)
{
case DuelPhase.Draw: return "draw";
case DuelPhase.Standby: return "standby";
case DuelPhase.Main1: return "main1";
case DuelPhase.BattleStart: return "battleStart";
case DuelPhase.BattleStep: return "battleStep";
case DuelPhase.Damage: return "damage";
case DuelPhase.DamageCal: return "damageCalculation";
case DuelPhase.Battle: return "battle";
case DuelPhase.Main2: return "main2";
case DuelPhase.End: return "end";
default: return ((int)phase).ToString();
}
}
// ---------------------------------------------------------------- one builder per prompt shape
private static DecisionOption YGOL_Option(string action, ClientCard card = null, long description = 0, int value = 0)
=> new DecisionOption { action = action, card = YGOL_Card(card), description = description, value = value };
private Func<Decision, IList<ClientCard>> YGOL_Cards(DecisionRequest r, IList<ClientCard> cards, string action)
{
foreach (var card in cards) r.options.Add(YGOL_Option(action, card));
return d => d.choose.Select(i => cards[i]).ToList();
}
private MainPhaseAction YGOL_Idle(MainPhase main)
{
return YGOL_Decide(DecisionKind.Idle, r =>
{
var actions = new List<MainPhaseAction>();
void Add(string name, MainPhaseAction.MainAction action, IList<ClientCard> cards)
{
foreach (var card in cards)
{
r.options.Add(YGOL_Option(name, card));
actions.Add(new MainPhaseAction(action, card.ActionIndex));
}
}
Add("summon", MainPhaseAction.MainAction.Summon, main.SummonableCards);
Add("spSummon", MainPhaseAction.MainAction.SpSummon, main.SpecialSummonableCards);
Add("reposition", MainPhaseAction.MainAction.Repos, main.ReposableCards);
Add("setMonster", MainPhaseAction.MainAction.SetMonster, main.MonsterSetableCards);
Add("setSpell", MainPhaseAction.MainAction.SetSpell, main.SpellSetableCards);
for (int i = 0; i < main.ActivableCards.Count; ++i)
{
var card = main.ActivableCards[i];
r.options.Add(YGOL_Option("activate", card, main.ActivableDescs[i]));
actions.Add(new MainPhaseAction(MainPhaseAction.MainAction.Activate, card.ActionActivateIndex[main.ActivableDescs[i]]));
}
if (main.CanBattlePhase)
{
r.options.Add(YGOL_Option("toBattle"));
actions.Add(new MainPhaseAction(MainPhaseAction.MainAction.ToBattlePhase));
}
if (main.CanEndPhase)
{
r.options.Add(YGOL_Option("toEnd"));
actions.Add(new MainPhaseAction(MainPhaseAction.MainAction.ToEndPhase));
}
return d => actions[d.choose[0]];
}, () => _ai.OnSelectIdleCmd(main));
}
private BattlePhaseAction YGOL_Battle(BattlePhase battle)
{
return YGOL_Decide(DecisionKind.Battle, r =>
{
var actions = new List<BattlePhaseAction>();
for (int i = 0; i < battle.ActivableCards.Count; ++i)
{
r.options.Add(YGOL_Option("activate", battle.ActivableCards[i], battle.ActivableDescs[i]));
actions.Add(new BattlePhaseAction(BattlePhaseAction.BattleAction.Activate, battle.ActivableIndexes[i]));
}
foreach (var card in battle.AttackableCards)
{
var option = YGOL_Option("attack", card);
option.direct = card.CanDirectAttack;
r.options.Add(option);
actions.Add(new BattlePhaseAction(BattlePhaseAction.BattleAction.Attack, card.ActionIndex));
}
if (battle.CanMainPhaseTwo)
{
r.options.Add(YGOL_Option("toMain2"));
actions.Add(new BattlePhaseAction(BattlePhaseAction.BattleAction.ToMainPhaseTwo));
}
if (battle.CanEndPhase)
{
r.options.Add(YGOL_Option("toEnd"));
actions.Add(new BattlePhaseAction(BattlePhaseAction.BattleAction.ToEndPhase));
}
return d => actions[d.choose[0]];
}, () => _ai.OnSelectBattleCmd(battle));
}
private IList<ClientCard> YGOL_SelectCards(string kind, Func<IList<ClientCard>, int, int, int, bool, IList<ClientCard>> func,
IList<ClientCard> cards, int min, int max, int hint, bool cancelable)
{
return YGOL_Decide(kind, r =>
{
r.min = min;
r.max = max;
r.hint = hint;
r.cancelable = cancelable;
return YGOL_Cards(r, cards, "card");
}, () => func(cards, min, max, hint, cancelable));
}
private IList<ClientCard> YGOL_Sort(IList<ClientCard> cards)
{
return YGOL_Decide(DecisionKind.Sort, r =>
{
r.min = r.max = cards.Count;
return YGOL_Cards(r, cards, "card");
}, () => _ai.OnCardSorting(cards));
}
private int YGOL_Chain(IList<ClientCard> cards, IList<int> descs, IList<bool> forces, int timing)
{
return YGOL_Decide(DecisionKind.Chain, r =>
{
r.cancelable = !forces.Any(f => f);
r.value = timing;
for (int i = 0; i < cards.Count; ++i)
{
var option = YGOL_Option("activate", cards[i], descs[i]);
option.forced = forces[i];
r.options.Add(option);
}
return d => d.choose.Count == 0 ? -1 : d.choose[0];
}, () => _ai.OnSelectChain(cards, descs, forces, timing));
}
private IList<int> YGOL_Counter(int type, int quantity, IList<ClientCard> cards, IList<int> counters)
{
return YGOL_Decide(DecisionKind.Counter, r =>
{
r.code = type;
r.value = quantity;
r.min = 0;
r.max = cards.Count;
for (int i = 0; i < cards.Count; ++i)
r.options.Add(YGOL_Option("card", cards[i], value: counters[i]));
return d => (IList<int>)d.counts.ToList();
}, () => _ai.OnSelectCounter(type, quantity, cards, counters));
}
private int YGOL_Place(int hint, int player, CardLocation location, int filter)
{
return YGOL_Decide(DecisionKind.Place, r =>
{
r.hint = hint;
for (int bit = 0; bit < 32; ++bit)
{
if ((filter & (1 << bit)) == 0) continue;
var option = YGOL_Option("zone", value: 1 << bit);
option.player = player;
r.options.Add(option);
}
return d => r.options[d.choose[0]].value;
}, () => _ai.OnSelectPlace(hint, player, location, filter));
}
private bool YGOL_YesNo(string kind, ClientCard card, long description, Func<bool> builtIn)
{
return YGOL_Decide(kind, r =>
{
r.description = description;
r.options.Add(YGOL_Option("no", card, description));
r.options.Add(YGOL_Option("yes", card, description));
return d => d.choose[0] == 1;
}, builtIn);
}
private int YGOL_TextOption(IList<int> options)
{
return YGOL_Decide(DecisionKind.Option, r =>
{
foreach (var desc in options) r.options.Add(YGOL_Option("option", description: desc));
return d => d.choose[0];
}, () => _ai.OnSelectOption(options));
}
private CardPosition YGOL_Position(int cardId, IList<CardPosition> positions)
{
return YGOL_Decide(DecisionKind.Position, r =>
{
r.code = cardId;
foreach (var position in positions) r.options.Add(YGOL_Option(YGOL_PositionName((int)position), value: (int)position));
return d => positions[d.choose[0]];
}, () => _ai.OnSelectPosition(cardId, positions));
}
private IList<ClientCard> YGOL_Sum(IList<ClientCard> cards, int sum, int min, int max, int hint, bool exact)
{
return YGOL_Decide(DecisionKind.Sum, r =>
{
r.value = sum;
r.exact = exact;
r.hint = hint;
r.min = Math.Max(min, 0);
r.max = Math.Min(max, cards.Count);
foreach (var card in cards)
{
var option = YGOL_Option("card", card, value: card.OpParam1);
option.value2 = card.OpParam2;
r.options.Add(option);
}
return d => d.choose.Select(i => cards[i]).ToList();
}, () => _ai.OnSelectSum(cards, sum, min, max, hint, exact));
}
private IList<T> YGOL_Declare<T>(string kind, int count, IList<T> available, Func<T, int> bit, Func<IList<T>> builtIn)
{
return YGOL_Decide(kind, r =>
{
r.min = r.max = count;
foreach (var a in available) r.options.Add(YGOL_Option(kind, value: bit(a)));
return d => (IList<T>)d.choose.Select(i => available[i]).ToList();
}, builtIn);
}
private int YGOL_AnnounceCard(IList<int> avail)
{
return YGOL_Decide(DecisionKind.AnnounceCard, r =>
{
foreach (var code in avail)
r.options.Add(new DecisionOption { action = "card", card = new CardView { code = code, name = YGOSharp.OCGWrapper.NamedCard.Get(code)?.Name } });
return d => avail[d.choose[0]];
}, () => _ai.OnAnnounceCard(avail));
}
private int YGOL_Number(IList<int> numbers)
{
return YGOL_Decide(DecisionKind.Number, r =>
{
foreach (var n in numbers) r.options.Add(YGOL_Option("number", value: n));
return d => d.choose[0];
}, () => _ai.OnAnnounceNumber(numbers));
}
private int YGOL_RockPaperScissors()
{
return YGOL_Decide(DecisionKind.RockPaperScissors, r =>
{
r.options.Add(YGOL_Option("scissors", value: 1));
r.options.Add(YGOL_Option("rock", value: 2));
r.options.Add(YGOL_Option("paper", value: 3));
return d => d.choose[0] + 1;
}, () => _ai.OnRockPaperScissors());
}
private bool YGOL_TurnOrder()
{
return YGOL_Decide(DecisionKind.TurnOrder, r =>
{
r.options.Add(YGOL_Option("first"));
r.options.Add(YGOL_Option("second"));
return d => d.choose[0] == 0;
}, () => _ai.OnSelectHand());
}
}
}