Files
yugioh-legacy-bots/src/YGOLegacy.Bots/WindBot/Game/GameClient.cs
T
donnyandClaude Opus 5.5 0fd327e933
CI / build (push) Successful in 48s
feat(decisions): the decision seam, one IDecisionMaker asked at every prompt
GameBehavior asks YGOL_Decide at every prompt (idle, battle, cards, chain, yes/no, option, position, place,
sum, counter, declarations, sort, RPS, turn order). With no decision maker for the seat (the default) that is
the GameAI call and nothing else: the built-in brain plays as before (same 100-duel report, 67-33, avg 18.5).
With one, the prompt goes out as a plain-data DecisionRequest (kind, legal options, the seat's DuelView) and
comes back as option indices; null, an exception or an illegal answer falls back to the executor.

A seat picks a maker with Decisions=<name> (arena: --decisionsA/--decisionsB); DecisionMakers.Register names
one. Built in: builtin and random (a random legal answer read from the request's JSON). Tests: 100 random-vs-
random duels through the seam with 0 errors and no fallback, builtin == no token, Smart beats random 100-0.

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

214 lines
8.9 KiB
C#

using System;
using System.IO;
using System.Linq;
using System.Net;
using YGOSharp.Network;
using YGOSharp.Network.Enums;
using YGOSharp.Network.Utils;
using YGOLegacy.Protocol.Codecs; // [YGOL] TICKET-161
namespace WindBot.Game
{
public class GameClient
{
public YGOClient Connection { get; private set; }
public string Username;
public string Deck;
public string DeckFile;
// [YGOL] TICKET-349
public int Hand;
public bool Debug;
// [YGOL] TICKET-349
public string Character; // [YGOL] TICKET-171
public string Group; // [YGOL] TICKET-171
// [YGOL] TICKET-285: chosen seat, deferred deck, per-seat difficulty and the host's in-process orders.
public int YGOL_Seat = -1;
public byte[] YGOL_SeatToken;
public bool YGOL_DeferDeck;
public string YGOL_Difficulty;
// [YGOL] S5: the Room host's per-seat brain knobs, on top of the deck's brain.
public System.Collections.Generic.IReadOnlyDictionary<string, float> YGOL_Knobs;
// [YGOL] TICKET-286: a restart's returning CPU claims with the restart id and holds READY for the host's START.
public byte[] YGOL_RestartId;
public volatile bool YGOL_HoldReady;
public string YGOL_Decisions; // [YGOL] the Decisions= token: who answers this seat's prompts (null = its executor)
public volatile int YGOL_Position = -1;
public volatile bool YGOL_HasDeck;
private readonly System.Collections.Concurrent.ConcurrentQueue<Action> YGOL_orders = new System.Collections.Concurrent.ConcurrentQueue<Action>();
private string _serverHost;
private int _serverPort;
private short _proVersion;
private string _roomInfo;
private GameBehavior _behavior;
public GameClient(WindBotInfo Info)
{
Username = Info.Name;
Deck = Info.Deck;
DeckFile = Info.DeckFile;
// [YGOL] TICKET-349
Hand = Info.Hand;
Debug = Info.Debug;
// [YGOL] TICKET-349
Character = Info.Character; // [YGOL] TICKET-171
Group = Info.Group; // [YGOL] TICKET-171
YGOL_Seat = Info.Seat; // [YGOL] TICKET-285
YGOL_SeatToken = YGOLegacy.Protocol.Contracts.SeatIds.FromHex(Info.SeatToken);
YGOL_DeferDeck = Info.DeferDeck;
YGOL_Difficulty = string.IsNullOrEmpty(Info.Difficulty) ? null : Info.Difficulty;
YGOL_RestartId = YGOLegacy.Protocol.Contracts.SeatIds.FromHex(Info.RestartId); // [YGOL] TICKET-286
YGOL_HoldReady = Info.HoldReady;
YGOL_Decisions = Info.Decisions; // [YGOL]
_serverHost = Info.Host;
_serverPort = Info.Port;
_roomInfo = Info.HostInfo;
_proVersion = (short)Info.Version;
}
public void Start()
{
Connection = new YGOClient();
_behavior = new GameBehavior(this);
Connection.Connected += OnConnected;
Connection.PacketReceived += OnPacketReceived;
IPAddress target_address;
try
{
target_address = IPAddress.Parse(_serverHost);
}
catch (System.Exception)
{
IPHostEntry _hostEntry = Dns.GetHostEntry(_serverHost);
target_address = _hostEntry.AddressList.FirstOrDefault(findIPv4 => findIPv4.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
}
Connection.Connect(target_address, _serverPort);
}
private void OnConnected()
{
// [YGOL] TICKET-161: the shared lobby codecs write the payloads; CtosPacket writes the id byte.
BinaryWriter packet = CtosPacket.Begin(LobbyCodecs.ExternalAddress.Id);
LobbyCodecs.ExternalAddress.Write(packet, new YGOLegacy.Protocol.Contracts.ExternalAddress(_serverHost));
Connection.Send(packet);
packet = CtosPacket.Begin(LobbyCodecs.PlayerInfo.Id);
LobbyCodecs.PlayerInfo.Write(packet, new YGOLegacy.Protocol.Contracts.PlayerInfo(Username));
Connection.Send(packet);
// [YGOL] TICKET-285: claim the host's chosen seat before JoinGame; only sent to a server that has chosen seats.
if (YGOL_Seat >= 0 && YGOL_SeatToken != null)
{
packet = CtosPacket.Begin(LobbyCodecs.SeatRequest.Id);
LobbyCodecs.SeatRequest.Write(packet, new YGOLegacy.Protocol.Contracts.SeatRequest(
YGOLegacy.Protocol.Contracts.Capability.ProtocolVersion, YGOL_RestartId, (byte)YGOL_Seat, YGOL_SeatToken)); // [YGOL] TICKET-286: the restart id rides along
Connection.Send(packet);
}
packet = CtosPacket.Begin(LobbyCodecs.JoinGame.Id);
LobbyCodecs.JoinGame.Write(packet, new YGOLegacy.Protocol.Contracts.JoinGame((ushort)_proVersion, _roomInfo));
Connection.Send(packet);
}
/// <summary>
/// [YGOL] In-process duel host (TICKET-045): build exactly what Start()
/// builds, but on a loopback transport — no DNS lookup, no socket, no
/// Connect. OnConnected still runs (on the first Tick), so
/// ExternalAddress/PlayerInfo/JoinGame go out through <paramref
/// name="sendHook"/> and the host answers them the way ygoserver would.
/// Everything downstream is untouched: GameBehavior, the DuelStateBus
/// tap in OnPacketReceived, YGOL_DuelResult and YGOL_Replay.
/// </summary>
public void YGOL_StartLoopback(Action<byte[]> sendHook)
{
Connection = new YGOClient();
_behavior = new GameBehavior(this);
Connection.Connected += OnConnected;
Connection.PacketReceived += OnPacketReceived;
Connection.YGOL_SendHook = sendHook;
Connection.YGOL_MarkConnected();
}
/// [YGOL] Push one STOC packet into this client's receive queue (loopback).
public void YGOL_Receive(byte[] packet)
{
Connection.YGOL_Inject(packet);
}
public void Tick()
{
// [YGOL] TICKET-285: the host's orders run here, on the bot thread, between packets.
while (YGOL_orders.TryDequeue(out Action order))
order();
Connection.Update();
}
// [YGOL] TICKET-285: change this bot's deck (and the brain it picks) without a respawn. Dropped once the duel started.
public void YGOL_AssignDeck(string deckFile, string executor, string character, string group)
{
YGOL_orders.Enqueue(() => _behavior.YGOL_ApplyDeck(deckFile, executor, character, group));
}
// [YGOL] TICKET-285: a per-seat difficulty; the executor is rebuilt, the brain file is never touched.
public void YGOL_SetDifficulty(string difficulty)
{
YGOL_orders.Enqueue(() => _behavior.YGOL_ApplyDifficulty(difficulty));
}
// [YGOL] S5: per-seat brain and debug log from the Room's CPU settings; the executor is rebuilt.
public void YGOL_SetBrain(string executor, System.Collections.Generic.IReadOnlyDictionary<string, float> knobs, bool debug)
{
YGOL_orders.Enqueue(() => _behavior.YGOL_ApplyBrain(executor, knobs, debug));
}
// [YGOL] TICKET-286: the host's START readies a CPU that came back from a restart unready.
public void YGOL_Ready()
{
YGOL_orders.Enqueue(() => _behavior.YGOL_ReleaseReady());
}
// [YGOL] TICKET-285: leave the room; the bot thread ends with the connection.
public void YGOL_Leave()
{
YGOL_orders.Enqueue(() =>
{
if (Connection.IsConnected)
Connection.Send(CtosMessage.LeaveGame);
Connection.Close();
});
}
// [YGOL] TICKET-349
public void Surrender()
{
Connection.Send(CtosMessage.Surrender);
}
private void OnPacketReceived(BinaryReader reader)
{
// [YGOL] Duel state bus (TICKET-042): publish a COPY of the raw
// packet before it is parsed, so YGOLegacy.Bot.DuelStateBus can
// mirror this seat's view for the other bot. The reader is not
// touched (ToArray() ignores the stream position), and when no
// brain asked for insight `Active` is false, so this is one static
// bool read and no allocation.
if (YGOLegacy.Bot.DuelStateBus.Active)
{
try
{
MemoryStream buffer = reader.BaseStream as MemoryStream;
if (buffer != null)
YGOLegacy.Bot.DuelStateBus.OnBotPacket(this, buffer.ToArray());
}
catch (Exception) { }
}
_behavior.OnPacket(reader);
}
}
}