Compare commits

2 Commits
Author SHA1 Message Date
donnyandClaude Opus 5.5 c034354d12 feat(decisions): host default, first brain, every choice through the seam; v0.2.0
CI / build (push) Successful in 57s
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
donnyandClaude Opus 5.5 0fd327e933 feat(decisions): the decision seam, one IDecisionMaker asked at every prompt
CI / build (push) Successful in 48s
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
18 changed files with 3422 additions and 36 deletions

No files matched your search

+7
View File
@@ -9,6 +9,13 @@ Instructions for any coding agent. `README.md` has the layout, the contract, the
Microsoft.Data reference, no package it would ship (Newtonsoft is compile-time only). Anything it needs from the
game goes through `BotHost` (`src/YGOLegacy.Bots/Host/BotHost.cs`); a new need is a new member there, written
in `README.md`'s contract table and filed for the Unity repo.
- **Every bot decision goes through the decision seam** (`IDecisionMaker`, `src/YGOLegacy.Bots/Decisions/`, asked
by `GameBehavior.YGOL_Decide`). A new prompt handler asks `YGOL_Decide`, never the GameAI directly. With no
decision maker the seam must do nothing but call the GameAI, so the built-in brain plays as before. Request and
answer types stay plain, JSON-friendly data; a field that changes meaning bumps `DecisionRequest.version`.
Remote brains (LLM, ML) are decision makers registered by name, never edits to WindBot or the hosts. The
built-in brain's `--seed 7` report must stay equal to `tests/fixture/expected/v0.1.0-seed7-n100.json` (a test
checks); a change that alters it changes how the game plays and needs the owner.
- **Keep the namespaces the game uses** (`WindBot.*`, `YGOSharp.*`, `YGOLegacy.Bot`, `YGOLegacy.Characters`,
`YGOLegacy.Services`) and WindBot's `[YGOL]` markers on fork changes.
- **Everything builds in Docker** (`Dockerfile`); there is no `dotnet` on the hosts. `docker build --target test .`
+16
View File
@@ -3,6 +3,22 @@
One section per release; the section is the release's body. Each names the engine release it was built and
tested against (`bots.json`'s `engine`).
## v0.2.0 — 2026-10-19
The decision seam. Engine `v1.4.1`. No change to how the bots play: a seat with no decision maker is answered by
its executor exactly as before (the `--seed 7` 100-duel report equals v0.1.0's apart from its clocks).
- `YGOLegacy.Bots.Decisions`: `IDecisionMaker.Decide(DecisionRequest) -> Decision`, asked at every prompt of
every seat (`GameBehavior.YGOL_Decide`) before the seat's WindBot executor; null, an exception or an illegal
answer hands the prompt to the executor. Requests (kind, legal options, what the seat sees as a `DuelView`) and
answers (option indices) are plain JSON-friendly data.
- A seat picks a maker with the WindBot token `Decisions=<name>`, else gets `BotHost.Decisions` (default none);
`DecisionMakers.Register` names one. Built in: `builtin` (the executor), `first` (the first legal answer, the
test brain) and `random` (a random legal answer), both from the request's JSON alone.
- Every prompt with a choice is asked, including `MSG_SORT_CHAIN` and the "field first" card prompt (their
built-in answers unchanged); only no-choice prompts are not. Seats with a maker log their counts per duel.
- `BotArena --decisionsA/--decisionsB <name>`.
## v0.1.0 — 2026-10-19
The bots leave the Unity repo. Engine `v1.4.1`.
+58 -4
View File
@@ -12,7 +12,7 @@ The code came from the Unity repo (`donny/yugioh-legacy-unity`, branch `dev`, co
| Path | What |
|---|---|
| `src/YGOLegacy.Bots/` | The library: .NET Standard 2.1, C# 9, no Unity reference (Unity compiles against it). `WindBot/`, `YGOSharp/` (the client, the card managers, the enums), `Bot/` (SmartExecutor, BoardEvaluator, BrainRules, EffectSimulator, BattlePredictor, DuelStateBus, LocalDuelHost, LoopbackBotSeat, Lookahead, ArenaReport), `Characters/`, `Services/BotRoster.cs`, and `Host/BotHost.cs`, the contract. |
| `src/YGOLegacy.Bots/` | The library: .NET Standard 2.1, C# 9, no Unity reference (Unity compiles against it). `WindBot/`, `YGOSharp/` (the client, the card managers, the enums), `Bot/` (SmartExecutor, BoardEvaluator, BrainRules, EffectSimulator, BattlePredictor, DuelStateBus, LocalDuelHost, LoopbackBotSeat, Lookahead, ArenaReport), `Characters/`, `Services/BotRoster.cs`, `Host/BotHost.cs` (the contract with the host) and `Decisions/` (the decision seam). |
| `src/BotArena/` | The headless arena, .NET 8, `linux-x64` and `win-x64`. Its own `README.md` has the options, the report and how it works. |
| `tests/YGOLegacy.Bots.Tests/` | NUnit: the library through its contract, and the Linux arena end to end. |
| `tests/fixture/` | `game/`, the smallest game root the tests duel on, and `make-fixture.py`, which builds it (see its `README.md`). |
@@ -61,6 +61,56 @@ The game references `YGOLegacy.Bots.dll` beside the engine's `YGOLegacy.Engine.d
`bots.json`'s `engine`) and its own Newtonsoft.Json (Unity's `com.unity.nuget.newtonsoft-json`, 13.x). Neither is
in `bots-lib.zip`.
## The decision seam: who answers a seat's prompts
One bot plays the same everywhere a duel runs: a solo duel in the game (engine and bots in the game's process, no
network, offline), a LAN room on a player's PC, a dedicated-server room, the headless arena. Every one of them
feeds the seat's WindBot `GameBehavior`, and every prompt the engine sends that seat (main phase or battle phase
action, cards to pick, chain or not, yes or no, a zone, a position, a declaration, sort, rock-paper-scissors, turn
order) goes through one point before WindBot's AI: `GameBehavior.YGOL_Decide`
(`src/YGOLegacy.Bots/WindBot/Game/GameBehavior.YGOL_Decisions.cs`).
```csharp
namespace YGOLegacy.Bots.Decisions
public interface IDecisionMaker
{
Decision Decide(DecisionRequest request); // null = let the seat's own brain answer
}
```
- **The built-in brain** is the seat's WindBot executor: SmartExecutor for character decks, Lucky for Dovphin, a
deck executor otherwise. A seat without a decision maker (the default, and every seat today) is answered by it
exactly as before: `YGOL_Decide` calls the GameAI and builds nothing else.
- **Another decision maker** is chosen per seat by the WindBot token `Decisions=<name>` (the arena:
`--decisionsA/--decisionsB <name>`); a seat without the token gets the host's default, `BotHost.Decisions`
(null: the executor). Names are registered with `DecisionMakers.Register(name, seat => maker)` by the host or a
plug-in. `builtin` is the executor (also over a host default); an unknown name is logged and gets the executor.
Built in, both reading only each request's JSON: `first` (the first legal option; sums and counters solved from
the options' values; deterministic, the test brain) and `random` (a uniformly random legal option; a baseline;
leaves sums and counters to the executor).
- **The question** is a `DecisionRequest`: `kind` (`DecisionKind`: idle, battle, card, tribute, unselectCard,
chain, effectYesNo, yesNo, option, position, place, sum, counter, attribute, race, number, announceCard, sort,
rockPaperScissors, turnOrder), the seat, `min`/`max`/`cancelable`, the engine's `hint` and `description`, the
legal `options` (each with its `action`, its card as a `CardView`, its description and value), and `duel`, a
`DuelView` of what this seat sees (turn, phase, LP, its hand and Extra Deck, both fields, graveyards, banished,
deck counts, the chain; hidden cards have code 0). **The answer** is a `Decision`: the chosen option indices
(counter prompts: one count per option). All plain public fields: Newtonsoft (or any JSON) round-trips them;
`version` names the format.
- **Fallback.** A maker that returns null, throws, or answers something illegal (an index that is not an option,
a count outside `min`..`max`) gets a `[YGOL decisions]` warning and the executor answers that prompt; the duel
goes on. So a maker can take over some kinds and leave the rest (`random` leaves sums and counters). The
executor's own plans assume it made the earlier choices; mixing is legal, not necessarily good play.
- **Prompts that are not asked** are the ones with no choice: a chain prompt with nothing to chain, a chain whose
only option is one forced activation, a position prompt with one position, rock-paper-scissors fixed by the
`Hand=` token. Everything else is asked, including the prompts WindBot's AI never decides (the chain order of
`MSG_SORT_CHAIN`, a "field first" card prompt), whose built-in answer stays WindBot's fixed one. A seat with a
decision maker logs, at the end of each duel, `[YGOL decisions] counts <seat>: asked=N (kind xN, ...)
handedBack=N unasked=N (kind: reason xN, ...)`.
- **A remote brain** (OpenRouter Jev or Claude through our server, a model on a RunPod box) is an `IDecisionMaker`
that sends the request as JSON and waits for the answer: `Decide` is called on the bot's thread and the duel
waits for it, the same in all four places. Its time limit, retries and fallback are its own; returning null
hands the prompt back. No remote maker is built yet.
## Build and test
```bash
@@ -73,9 +123,13 @@ With a dotnet 8 SDK instead: `build/fetch-engine.sh`, then `dotnet build src/YGO
src/BotArena -r linux-x64 --self-contained`, `BOTARENA_EXE=<that>/BotArena dotnet test tests/YGOLegacy.Bots.Tests`.
The tests: the library through `BotHost` (cards, deck caps and `#ruleset`, the roster's deck → character → brain
and its Dovphin fallback, a broken character logged, the game's scan-then-publish), and the published Linux arena
on the fixture: 100 duels of `AI_OldSchool` against itself (both seats the Smart brain) with 0 errors, and the
same `--seed` giving the same report at `--parallel 4` and `--parallel 2` (clocks aside).
and its Dovphin fallback, a broken character logged, the game's scan-then-publish), the decision seam (the
registry, JSON round trips, the random maker's ranges), and the published Linux arena on the fixture: 100 duels
of `AI_OldSchool` against itself (both seats the Smart brain) with 0 errors; the same `--seed` giving the same
report at `--parallel 4` and `--parallel 2` (clocks aside); the built-in brain's `--seed 7` report equal to the
v0.1.0 release's (`tests/fixture/expected/v0.1.0-seed7-n100.json`, clocks aside); 100 duels with both seats
answered by `first`, every choice asked (none handed back, only no-choice prompts unasked); the same with `random`;
`Decisions=builtin` giving the same duels as no token; and the Smart brain beating `random`.
## Engine pin
+10
View File
@@ -100,6 +100,9 @@ namespace YGOLegacy.Tools.BotArena
result.nameB = ArenaReport.SeatName(botB, 1);
result.commandA = ArenaReport.SeatCommand(botA, opts.deckA, opts.execA, result.nameA);
result.commandB = ArenaReport.SeatCommand(botB, opts.deckB, opts.execB, result.nameB);
// The decision seam: another decision maker answers the seat's prompts (the command records it).
if (!string.IsNullOrEmpty(opts.decisionsA)) result.commandA += " Decisions=" + opts.decisionsA;
if (!string.IsNullOrEmpty(opts.decisionsB)) result.commandB += " Decisions=" + opts.decisionsB;
Log("run: " + opts.n + " duel(s) on " + opts.parallel + " worker(s), host=" + opts.hostMode + ", A=" + result.commandA + " | B=" + result.commandB);
if (!string.IsNullOrEmpty(opts.replaysDir))
{
@@ -471,6 +474,9 @@ Options:
Setting `lookahead` above 0 also installs the arena's perfect-information
rollout oracle for that seat (TICKET-050, --host local only)
--knobsB <list> same for seat B
--decisionsA <name> the decision maker that answers seat A's prompts instead of its executor (the
decision seam): ""random"" or a name a plug-in registered. Default: the executor
--decisionsB <name> same for seat B
-h, --help
Exit codes: 0 = at least one duel played, 1 = none played, 2 = bad arguments.";
@@ -496,6 +502,8 @@ Exit codes: 0 = at least one duel played, 1 = none played, 2 = bad arguments.";
public InsightLevel? insightA, insightB;
/// TICKET-050 per-seat knob overrides (--knobsA/--knobsB); null = none.
public Dictionary<string, float> knobsA, knobsB;
/// The decision seam: a named decision maker per seat; null = the seat's executor.
public string decisionsA, decisionsB;
/// <summary>TICKET-050: does this seat's override switch lookahead on?</summary>
public bool LookaheadOn(Dictionary<string, float> knobs)
@@ -592,6 +600,8 @@ Exit codes: 0 = at least one duel played, 1 = none played, 2 = bad arguments.";
case "--insightB": o.insightB = ParseInsight(a, Next()); break;
case "--knobsA": o.knobsA = ParseKnobs(a, Next()); break;
case "--knobsB": o.knobsB = ParseKnobs(a, Next()); break;
case "--decisionsA": o.decisionsA = Next().Trim(); break;
case "--decisionsB": o.decisionsB = Next().Trim(); break;
case "--worker": o.worker = true; o.workerIndex = NextInt(); break;
case "--nameA": o.nameA = Next(); break;
case "--nameB": o.nameB = Next(); break;
+1
View File
@@ -63,6 +63,7 @@ plugin folder, and the copy next to the exe.
| `--port 7920` | first server port; worker *k* starts at `port + 4k` and takes the next free one (`--host server` only) |
| `--locale en-US` | `Data/locales/<lang>/` for `cards.cdb` and `bot.conf` |
| `--knobsA/--knobsB "name=value,..."` | per-seat SmartExecutor knob overrides, applied ON TOP of that deck brain's knobs (and the group's) — e.g. `--knobsA "lookahead=8,lookaheadTurns=6"`. Lets one deck be measured at two settings without editing `brain.json`. Setting `lookahead` above 0 also installs the perfect-information rollout oracle for that seat (TICKET-050; `--host local` only). |
| `--decisionsA/--decisionsB <name>` | the decision maker that answers that seat's prompts instead of its executor (the decision seam, repo README): `random`, or a name a plug-in registered. Appends `Decisions=<name>` to the seat's command (so the report records it). Default: the executor. |
| `--host local\|server` | which duel host plays the duels. `local` (default) = the engine's core in-process (TICKET-045); `server` = the engine's server over a TCP loopback, kept for A/B, Windows only. |
| `--insightA/--insightB <none\|hand\|full>` | force that seat's duel-state-bus insight (TICKET-042), overriding the deck brain's `insight` knob. Default: the knob (none). Recorded in the report's `config.insightA/insightB`; at `hand` or above the journal's `turn` lines gain `enemyHandKnown` (the enemy's real hand ids). Both bots of a duel run in this process, so each mirrors the other's stream. |
| `--verbose` | `[YGOL bot]` decision logging on for every Smart seat (sets `SmartExecutor.Verbose`; no `verbose: 1` knob needed — the executor is otherwise muted for the run). Lines land in the worker logs. |
+1
View File
@@ -501,6 +501,7 @@ namespace YGOLegacy.Tools.BotArena
info.Debug = Config.GetBool("Debug", info.Debug);
info.Character = Config.GetString("Character", info.Character); // TICKET-171
info.Group = Config.GetString("Group", info.Group); // TICKET-171
info.Decisions = Config.GetString("Decisions", info.Decisions); // the decision seam
return info;
}
+270
View File
@@ -0,0 +1,270 @@
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;
}
}
@@ -0,0 +1,94 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace YGOLegacy.Bots.Decisions
{
/// <summary>
/// <see cref="DecisionMakers.First"/>: the first legal answer, from the request's JSON alone. Card prompts take
/// the first `min` options (at least one), yes/no says no, sorts keep the order; sums pick the first options
/// whose values reach the target the way the engine checks it, counters take from the first options first.
/// Deterministic. It hands a prompt back only when it finds no legal answer in the options (a sum with none).
/// </summary>
public sealed class FirstDecisions : IDecisionMaker
{
public Decision Decide(DecisionRequest request)
{
var r = JsonConvert.DeserializeObject<DecisionRequest>(JsonConvert.SerializeObject(request));
var n = r.options.Count;
switch (r.kind)
{
case DecisionKind.Sort:
case DecisionKind.SortChain:
return new Decision { choose = Range(n) };
case DecisionKind.Counter:
{
var counts = new List<int>();
var left = r.value;
foreach (var option in r.options)
{
var take = Math.Min(option.value, left);
counts.Add(take);
left -= take;
}
return left == 0 ? new Decision { counts = counts } : null;
}
case DecisionKind.Sum:
{
var chosen = new List<int>();
return Sum(r, 0, chosen) ? new Decision { choose = chosen } : null;
}
default:
{
var count = Math.Min(Math.Max(r.min, 1), Math.Min(r.max, n));
if (count == 0 && !r.cancelable) return null;
return new Decision { choose = Range(count) };
}
}
}
private static List<int> Range(int n)
{
var list = new List<int>(n);
for (int i = 0; i < n; ++i) list.Add(i);
return list;
}
// The engine's checks (select_with_sum_limit): with exact, some value of each chosen card adds up to the
// target; without, the chosen cards' larger values reach it and dropping the smallest falls short.
private static bool Sum(DecisionRequest r, int from, List<int> chosen)
{
if (chosen.Count >= Math.Max(r.min, 1) && Fits(r, chosen)) return true;
if (chosen.Count >= r.max) return false;
for (int i = from; i < r.options.Count; ++i)
{
chosen.Add(i);
if (Sum(r, i + 1, chosen)) return true;
chosen.RemoveAt(chosen.Count - 1);
}
return false;
}
private static bool Fits(DecisionRequest r, List<int> chosen)
{
if (r.exact) return Exact(r, chosen, 0, r.value);
int sum = 0, mx = 0, mn = int.MaxValue;
foreach (var i in chosen)
{
int o1 = r.options[i].value, o2 = r.options[i].value2;
int ms = o2 > 0 && o2 < o1 ? o2 : o1;
sum += ms;
mx += Math.Max(o1, o2);
mn = Math.Min(mn, ms);
}
return mx >= r.value && sum - mn < r.value;
}
private static bool Exact(DecisionRequest r, List<int> chosen, int at, int left)
{
if (at == chosen.Count) return left == 0;
var o = r.options[chosen[at]];
return Exact(r, chosen, at + 1, left - o.value) || (o.value2 > 0 && Exact(r, chosen, at + 1, left - o.value2));
}
}
}
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace YGOLegacy.Bots.Decisions
{
/// <summary>
/// <see cref="DecisionMakers.Random"/>: a uniformly random legal answer. It reads only the JSON of each request,
/// never the live objects, so it also proves the request carries what a remote decision maker would get. Sums
/// and counters (whose legal answers it cannot tell from the options alone) are left to the seat's brain.
/// </summary>
public sealed class RandomDecisions : IDecisionMaker
{
private readonly Random random;
public RandomDecisions(int seed)
{
random = new Random(seed);
}
public Decision Decide(DecisionRequest request)
{
var copy = JsonConvert.DeserializeObject<DecisionRequest>(JsonConvert.SerializeObject(request));
if (copy.kind == DecisionKind.Sum || copy.kind == DecisionKind.Counter)
return null;
var n = copy.options.Count;
var order = new List<int>(n);
for (int i = 0; i < n; ++i) order.Add(i);
for (int i = n - 1; i > 0; --i)
{
int j = random.Next(i + 1);
(order[i], order[j]) = (order[j], order[i]);
}
if (copy.kind == DecisionKind.Sort || copy.kind == DecisionKind.SortChain)
return new Decision { choose = order };
int min = Math.Min(copy.min, n);
int max = Math.Min(copy.max, n);
if (max < min) return null;
// A cancelable prompt: nothing is one more answer beside every legal count.
int count = random.Next(min, max + 1 + (copy.cancelable ? 1 : 0));
return new Decision { choose = count > max ? new List<int>() : order.GetRange(0, count) };
}
}
}
+4
View File
@@ -26,6 +26,10 @@ namespace YGOLegacy.Bots
/// The active locale's bot.conf. Default: empty (BotRoster then uses its built-in Dovphin command).
public static IBotConf BotConf { get; set; } = new EmptyBotConf();
/// The decision maker (YGOLegacy.Bots.Decisions.DecisionMakers name) for seats whose command has no
/// Decisions= token. Default: null, the seat's own executor (SmartExecutor for character decks).
public static string Decisions { get; set; }
internal static ICardDatabase RequireCards()
=> Cards ?? throw new InvalidOperationException("YGOLegacy.Bots: BotHost.Cards is not set; the host must set it before the card databases load");
}
@@ -0,0 +1,505 @@
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());
}
}
}
+49 -29
View File
@@ -14,7 +14,7 @@ using YGOLegacy.Protocol.Codecs; // [YGOL] TICKET-161
namespace WindBot.Game
{
public class GameBehavior
public partial class GameBehavior
{
public GameClient Game { get; private set; }
public YGOClient Connection { get; private set; }
@@ -53,6 +53,7 @@ namespace WindBot.Game
Game.YGOL_HasDeck = Deck != null;
_select_hint = 0;
YGOL_InitDecisions(); // [YGOL] the decision seam (GameBehavior.YGOL_Decisions.cs)
}
#region [YGOL] read-only mirror mode (TICKET-042 duel state bus)
@@ -489,9 +490,12 @@ namespace WindBot.Game
{
int result;
if (_hand > 0)
{
result = _hand;
YGOL_Unasked(YGOLegacy.Bots.Decisions.DecisionKind.RockPaperScissors, "fixed by Hand="); // [YGOL] the command decided
}
else
result = _ai.OnRockPaperScissors();
result = YGOL_RockPaperScissors(); // [YGOL] decision seam
Connection.Send(CtosMessage.HandResult, (byte)result);
}
@@ -500,7 +504,7 @@ namespace WindBot.Game
private void OnSelectTp(BinaryReader packet)
{
bool start = _ai.OnSelectHand();
bool start = YGOL_TurnOrder(); // [YGOL] decision seam
YGOL_TurnChosen?.Invoke(start); // [YGOL]
Connection.Send(CtosMessage.TpResult, (byte)(start ? 1 : 0));
}
@@ -682,6 +686,7 @@ namespace WindBot.Game
Logger.DebugWriteLine("Duel finished against " + otherName + ", result: " + textResult);
// [YGOL] see YGOL_DuelResult.
try { YGOL_DuelResult?.Invoke(Game.Username, result, _duel.Turn); } catch (Exception) { }
YGOL_LogDecisionCounts(); // [YGOL] decision seam
}
private void OnDraw(BinaryReader packet)
@@ -1121,7 +1126,7 @@ namespace WindBot.Game
cards.Add(card);
}
IList<ClientCard> selected = _ai.OnCardSorting(cards);
IList<ClientCard> selected = YGOL_Sort(cards); // [YGOL] decision seam
byte[] result = new byte[count];
for (int i = 0; i < count; ++i)
{
@@ -1145,7 +1150,8 @@ namespace WindBot.Game
private void OnChainSorting(BinaryReader packet)
{
Connection.Send(CtosMessage.Response, -1);
// [YGOL] decision seam: the built-in brain keeps the default order (-1); a decision maker may order it.
YGOL_SortChain(packet);
}
private void OnUpdateCard(BinaryReader packet)
@@ -1279,7 +1285,7 @@ namespace WindBot.Game
battle.CanMainPhaseTwo = packet.ReadByte() != 0;
battle.CanEndPhase = packet.ReadByte() != 0;
Connection.Send(CtosMessage.Response, _ai.OnSelectBattleCmd(battle).ToValue());
Connection.Send(CtosMessage.Response, YGOL_Battle(battle).ToValue()); // [YGOL] decision seam
}
private void InternalOnSelectCard(BinaryReader packet, Func<IList<ClientCard>, int, int, int, bool, IList<ClientCard>> func, bool tribute = false)
@@ -1318,14 +1324,21 @@ namespace WindBot.Game
cards.Add(card);
}
var kind = tribute ? YGOLegacy.Bots.Decisions.DecisionKind.Tribute : YGOLegacy.Bots.Decisions.DecisionKind.Card; // [YGOL] decision seam
IList<ClientCard> selected;
if (_select_hint == 575 && cancelable) // HINTMSG_FIELD_FIRST
{
_select_hint = 0;
Connection.Send(CtosMessage.Response, -1);
return;
// [YGOL] decision seam: the built-in brain always declines here; a decision maker may pick.
selected = YGOL_SelectCards(kind, (c, n, x, h, can) => new List<ClientCard>(), cards, min, max, _select_hint, cancelable);
if (selected.Count == 0)
{
_select_hint = 0;
Connection.Send(CtosMessage.Response, -1);
return;
}
}
IList<ClientCard> selected = func(cards, min, max, _select_hint, cancelable);
else
selected = YGOL_SelectCards(kind, func, cards, min, max, _select_hint, cancelable); // [YGOL] decision seam
_select_hint = 0;
// [YGOL] a min-0 tribute (the continuation after YESNO 210) is answered by
@@ -1405,7 +1418,7 @@ namespace WindBot.Game
}
if (count2 == 0) cancelable = false;
IList<ClientCard> selected = func(cards, (finishable ? 0 : 1), 1, _select_hint, cancelable);
IList<ClientCard> selected = YGOL_SelectCards(YGOLegacy.Bots.Decisions.DecisionKind.UnselectCard, func, cards, (finishable ? 0 : 1), 1, _select_hint, cancelable); // [YGOL] decision seam
if (selected.Count == 0 && cancelable)
{
@@ -1486,17 +1499,19 @@ namespace WindBot.Game
if (cards.Count == 0)
{
YGOL_Unasked(YGOLegacy.Bots.Decisions.DecisionKind.Chain, "nothing to chain"); // [YGOL] no choice
Connection.Send(CtosMessage.Response, -1);
return;
}
if (cards.Count == 1 && forces[0])
{
YGOL_Unasked(YGOLegacy.Bots.Decisions.DecisionKind.Chain, "one forced activation"); // [YGOL] one legal answer
Connection.Send(CtosMessage.Response, 0);
return;
}
Connection.Send(CtosMessage.Response, _ai.OnSelectChain(cards, descs, forces, hint1 | hint2));
Connection.Send(CtosMessage.Response, YGOL_Chain(cards, descs, forces, hint1 | hint2)); // [YGOL] decision seam
}
private void OnSelectCounter(BinaryReader packet)
@@ -1519,7 +1534,7 @@ namespace WindBot.Game
counters.Add(num);
}
IList<int> used = _ai.OnSelectCounter(type, quantity, cards, counters);
IList<int> used = YGOL_Counter(type, quantity, cards, counters); // [YGOL] decision seam
byte[] result = new byte[used.Count * 2];
for (int i = 0; i < used.Count; ++i)
{
@@ -1595,7 +1610,7 @@ namespace WindBot.Game
filter = (field >> 30) & Zones.PendulumZones;
}
int selected = _ai.OnSelectPlace(_select_hint, player, location, filter);
int selected = YGOL_Place(_select_hint, player, location, filter); // [YGOL] decision seam
int o = n * 3;
resp[o] = (byte)GetLocalPlayer(player);
@@ -1656,14 +1671,15 @@ namespace WindBot.Game
ClientCard card = _duel.GetCard(player, loc, seq);
if (card == null)
{
Connection.Send(CtosMessage.Response, 0);
// [YGOL] decision seam: the built-in brain says no to a card it cannot place.
Connection.Send(CtosMessage.Response, YGOL_YesNo(YGOLegacy.Bots.Decisions.DecisionKind.EffectYesNo, null, desc, () => false) ? 1 : 0);
return;
}
if (card.Id == 0)
card.SetId(cardId);
int reply = _ai.OnSelectEffectYn(card, desc) ? (1) : (0);
int reply = YGOL_YesNo(YGOLegacy.Bots.Decisions.DecisionKind.EffectYesNo, card, desc, () => _ai.OnSelectEffectYn(card, desc)) ? (1) : (0); // [YGOL] decision seam
Connection.Send(CtosMessage.Response, reply);
}
@@ -1729,7 +1745,7 @@ namespace WindBot.Game
main.CanEndPhase = packet.ReadByte() != 0;
packet.ReadByte(); // CanShuffle
Connection.Send(CtosMessage.Response, _ai.OnSelectIdleCmd(main).ToValue());
Connection.Send(CtosMessage.Response, YGOL_Idle(main).ToValue()); // [YGOL] decision seam
}
private void OnSelectOption(BinaryReader packet)
@@ -1739,7 +1755,7 @@ namespace WindBot.Game
int count = packet.ReadByte();
for (int i = 0; i < count; ++i)
options.Add(packet.ReadInt32());
Connection.Send(CtosMessage.Response, _ai.OnSelectOption(options));
Connection.Send(CtosMessage.Response, YGOL_TextOption(options)); // [YGOL] decision seam
}
private void OnSelectPlace(BinaryReader packet)
@@ -1807,7 +1823,7 @@ namespace WindBot.Game
filter = (field >> 30) & Zones.PendulumZones;
}
int selected = _ai.OnSelectPlace(_select_hint, player, location, filter);
int selected = YGOL_Place(_select_hint, player, location, filter); // [YGOL] decision seam
int o = n * 3;
resp[o] = (byte)GetLocalPlayer(player);
@@ -1868,6 +1884,7 @@ namespace WindBot.Game
int pos = packet.ReadByte();
if (pos == 0x1 || pos == 0x2 || pos == 0x4 || pos == 0x8)
{
YGOL_Unasked(YGOLegacy.Bots.Decisions.DecisionKind.Position, "one position"); // [YGOL] one legal answer
Connection.Send(CtosMessage.Response, pos);
return;
}
@@ -1880,7 +1897,7 @@ namespace WindBot.Game
positions.Add(CardPosition.FaceUpDefence);
if ((pos & (int)CardPosition.FaceDownDefence) != 0)
positions.Add(CardPosition.FaceDownDefence);
Connection.Send(CtosMessage.Response, (int)_ai.OnSelectPosition(cardId, positions));
Connection.Send(CtosMessage.Response, (int)YGOL_Position(cardId, positions)); // [YGOL] decision seam
}
private void OnSelectSum(BinaryReader packet)
@@ -1940,7 +1957,7 @@ namespace WindBot.Game
sumval -= mandatoryCards[k].OpParam1;
}
IList<ClientCard> selected = _ai.OnSelectSum(cards, sumval, min, max, _select_hint, mode);
IList<ClientCard> selected = YGOL_Sum(cards, sumval, min, max, _select_hint, mode); // [YGOL] decision seam
_select_hint = 0;
byte[] result = new byte[mandatoryCards.Count + selected.Count + 1];
@@ -1974,9 +1991,9 @@ namespace WindBot.Game
int desc = packet.ReadInt32();
int reply;
if (desc == 30)
reply = _ai.OnSelectBattleReplay() ? 1 : 0;
reply = YGOL_YesNo(YGOLegacy.Bots.Decisions.DecisionKind.YesNo, null, desc, () => _ai.OnSelectBattleReplay()) ? 1 : 0; // [YGOL] decision seam
else
reply = _ai.OnSelectYesNo(desc) ? 1 : 0;
reply = YGOL_YesNo(YGOLegacy.Bots.Decisions.DecisionKind.YesNo, null, desc, () => _ai.OnSelectYesNo(desc)) ? 1 : 0; // [YGOL] decision seam
Connection.Send(CtosMessage.Response, reply);
}
@@ -1993,7 +2010,7 @@ namespace WindBot.Game
attributes.Add((CardAttribute) filter);
filter <<= 1;
}
attributes = _ai.OnAnnounceAttrib(count, attributes);
attributes = YGOL_Declare(YGOLegacy.Bots.Decisions.DecisionKind.Attribute, count, attributes, a => (int)a, () => _ai.OnAnnounceAttrib(count, attributes)); // [YGOL] decision seam
int reply = 0;
for (int i = 0; i < count; ++i)
reply += (int)attributes[i];
@@ -2151,7 +2168,7 @@ namespace WindBot.Game
}
if (avail.Count == 0)
throw new Exception("No avail card found for announce!");
Connection.Send(CtosMessage.Response, _ai.OnAnnounceCard(avail));
Connection.Send(CtosMessage.Response, YGOL_AnnounceCard(avail)); // [YGOL] decision seam
}
private void OnAnnounceNumber(BinaryReader packet)
@@ -2161,7 +2178,7 @@ namespace WindBot.Game
int count = packet.ReadByte();
for (int i = 0; i < count; ++i)
numbers.Add(packet.ReadInt32());
Connection.Send(CtosMessage.Response, _ai.OnAnnounceNumber(numbers));
Connection.Send(CtosMessage.Response, YGOL_Number(numbers)); // [YGOL] decision seam
}
private void OnAnnounceRace(BinaryReader packet)
@@ -2177,7 +2194,7 @@ namespace WindBot.Game
races.Add((CardRace)filter);
filter <<= 1;
}
races = _ai.OnAnnounceRace(count, races);
races = YGOL_Declare(YGOLegacy.Bots.Decisions.DecisionKind.Race, count, races, a => (int)a, () => _ai.OnAnnounceRace(count, races)); // [YGOL] decision seam
int reply = 0;
for (int i = 0; i < count; ++i)
reply += (int)races[i];
@@ -2189,9 +2206,12 @@ namespace WindBot.Game
packet.ReadByte(); // player
int result;
if (_hand > 0)
{
result = _hand;
YGOL_Unasked(YGOLegacy.Bots.Decisions.DecisionKind.RockPaperScissors, "fixed by Hand="); // [YGOL] the command decided
}
else
result = _ai.OnRockPaperScissors();
result = YGOL_RockPaperScissors(); // [YGOL] decision seam
Connection.Send(CtosMessage.Response, result);
}
@@ -31,6 +31,7 @@ namespace WindBot.Game
// [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>();
@@ -59,6 +60,7 @@ namespace WindBot.Game
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;
+1
View File
@@ -123,6 +123,7 @@ namespace WindBot
Info.Difficulty = Config.GetString("Difficulty", Info.Difficulty);
Info.RestartId = Config.GetString("RestartId", Info.RestartId); // [YGOL] TICKET-286
Info.HoldReady = Config.GetBool("HoldReady", Info.HoldReady);
Info.Decisions = Config.GetString("Decisions", Info.Decisions); // [YGOL] the decision seam
Run(Info);
}
@@ -23,6 +23,7 @@ namespace WindBot
public string Difficulty { get; set; } // [YGOL] TICKET-285: per-seat difficulty (null = the brain's)
public string RestartId { get; set; } // [YGOL] TICKET-286: the rules restart this bot returns for (hex); its claim carries it
public bool HoldReady { get; set; } // [YGOL] TICKET-286: upload the deck, send SeatResume Complete, and leave READY to the host's START
public string Decisions { get; set; } // [YGOL] the decision maker that answers this seat's prompts (YGOLegacy.Bots.Decisions; null = its executor)
public WindBotInfo()
{
Name = "WindBot";
@@ -44,6 +45,7 @@ namespace WindBot
Difficulty = null;
RestartId = null; // [YGOL] TICKET-286
HoldReady = false;
Decisions = null; // [YGOL]
}
}
}
+106 -3
View File
@@ -51,11 +51,13 @@ namespace YGOLegacy.Bots.Tests
return (p.ExitCode, stdout, stderr.Result);
}
private static JObject Duel(string root, int n, int parallel, int seed, string outFile)
private static JObject Duel(string root, int n, int parallel, int seed, string outFile, params string[] more)
{
var (code, stdout, stderr) = Run(root, "--deckA", "AI_OldSchool", "--deckB", "AI_OldSchool",
var args = new List<string> { "--deckA", "AI_OldSchool", "--deckB", "AI_OldSchool",
"--n", n.ToString(), "--parallel", parallel.ToString(), "--seed", seed.ToString(), "--host", "local",
"--out", outFile);
"--out", outFile };
args.AddRange(more);
var (code, stdout, stderr) = Run(root, args.ToArray());
Assert.That(code, Is.EqualTo(0), "exit code; stderr:\n" + stderr);
return JObject.Parse(File.ReadAllText(outFile));
}
@@ -98,6 +100,107 @@ namespace YGOLegacy.Bots.Tests
Assert.That(JToken.DeepEquals(a["duels"], other["duels"]), Is.False, "another seed plays other duels");
}
private static IEnumerable<string> WorkerLog(string root)
=> Directory.GetFiles(Path.Combine(root, "Data", "BotArena", "logs"), "worker-*.log", SearchOption.AllDirectories)
.SelectMany(File.ReadLines);
private static string[] SeamWarnings(string root)
=> WorkerLog(root).Where(l => l.Contains("[warn] [YGOL decisions]")).ToArray();
// "[YGOL decisions] counts <seat>: asked=N (kind xN, ...) handedBack=N unasked=N (kind: reason xN, ...)",
// one line per seat with a decision maker, at the end of each duel.
private static (int asked, int handedBack, Dictionary<string, int> askedKinds, Dictionary<string, int> unasked) SeamCounts(string root)
{
int asked = 0, handedBack = 0;
var askedKinds = new Dictionary<string, int>();
var unasked = new Dictionary<string, int>();
var line = new System.Text.RegularExpressions.Regex(@"\[YGOL decisions\] counts .*?: asked=(\d+)(?: \(([^)]*)\))? handedBack=(\d+) unasked=\d+(?: \(([^)]*)\))?$");
void Add(Dictionary<string, int> into, string list)
{
if (string.IsNullOrEmpty(list)) return;
foreach (var part in list.Split(", "))
{
var cut = part.LastIndexOf(" x", StringComparison.Ordinal);
into.TryGetValue(part.Substring(0, cut), out var n);
into[part.Substring(0, cut)] = n + int.Parse(part.Substring(cut + 2));
}
}
foreach (var l in WorkerLog(root))
{
var m = line.Match(l);
if (!m.Success) continue;
asked += int.Parse(m.Groups[1].Value);
Add(askedKinds, m.Groups[2].Value);
handedBack += int.Parse(m.Groups[3].Value);
Add(unasked, m.Groups[4].Value);
}
return (asked, handedBack, askedKinds, unasked);
}
// Prompts the seam answers without asking: they offer no choice at all.
private static readonly HashSet<string> NoChoice = new()
{
"chain: nothing to chain", "chain: one forced activation", "position: one position", "rockPaperScissors: fixed by Hand=",
};
[Test]
public void TheBuiltInBrainPlaysExactlyAsInV010()
{
// tests/fixture/expected/v0.1.0-seed7-n100.json is the v0.1.0 release arena's report for this command line.
var root = Fixture.CopyRoot();
var now = Duel(root, Duels, 4, Seed, Path.Combine(root, "now.json"));
var then = JObject.Parse(File.ReadAllText(Path.Combine(Path.GetDirectoryName(Fixture.Source), "expected", "v0.1.0-seed7-n100.json")));
Assert.That(JToken.DeepEquals(WithoutClocks(now), WithoutClocks(then)), Is.True, "the report differs from v0.1.0's beyond its clocks");
}
[Test]
public void EveryChoiceGoesThroughTheSeam()
{
// Both seats answered by `first`, which reads only each request's JSON. Every prompt with a choice is
// asked; none is handed back; the only prompts not asked are ones with no choice.
var root = Fixture.CopyRoot();
var report = Duel(root, Duels, 4, Seed, Path.Combine(root, "first.json"), "--decisionsA", "first", "--decisionsB", "first");
Assert.That((int)report["completed"], Is.EqualTo(Duels));
Assert.That((int)report["errors"], Is.EqualTo(0));
Assert.That(SeamWarnings(root), Is.Empty);
var (asked, handedBack, askedKinds, unasked) = SeamCounts(root);
TestContext.Progress.WriteLine("first vs first: asked " + asked + " (" + string.Join(", ", askedKinds.Select(p => p.Key + " " + p.Value)) + "), handed back "
+ handedBack + ", not asked " + string.Join(", ", unasked.Select(p => p.Key + " " + p.Value)));
Assert.That(asked, Is.GreaterThan(1000));
Assert.That(handedBack, Is.EqualTo(0));
Assert.That(unasked.Keys.Where(k => !NoChoice.Contains(k)), Is.Empty, "a prompt with a choice bypassed the seam");
}
[Test]
public void TheDecisionSeamAnswersEveryPromptFromPlainData()
{
// Both seats answered by the random maker, which reads only each request's JSON: every prompt of 100
// duels goes through the seam, and every answer it gives is legal.
var root = Fixture.CopyRoot();
var report = Duel(root, Duels, 4, Seed, Path.Combine(root, "random.json"), "--decisionsA", "random", "--decisionsB", "random");
Assert.That((int)report["completed"], Is.EqualTo(Duels));
Assert.That((int)report["errors"], Is.EqualTo(0));
Assert.That((string)report["commandA"], Does.EndWith(" Decisions=random"));
Assert.That(SeamWarnings(root), Is.Empty, "no prompt fell back to the brain over a bad request or answer");
Assert.That(SeamCounts(root).unasked.Keys.Where(k => !NoChoice.Contains(k)), Is.Empty);
var again = Duel(root, Duels, 2, Seed, Path.Combine(root, "random-2.json"), "--decisionsA", "random", "--decisionsB", "random");
Assert.That(JToken.DeepEquals(WithoutClocks(report), WithoutClocks(again)), Is.True, "a seeded run with makers repeats too");
}
[Test]
public void TheSeamDecidesAndTheBuiltInBrainIsUnchanged()
{
var root = Fixture.CopyRoot();
var plain = Duel(root, Duels, 4, Seed, Path.Combine(root, "plain.json"));
var builtIn = Duel(root, Duels, 4, Seed, Path.Combine(root, "builtin.json"), "--decisionsA", "builtin");
Assert.That(JToken.DeepEquals(WithoutClocks(plain)["duels"], WithoutClocks(builtIn)["duels"]), Is.True,
"Decisions=builtin is the executor: the same duels");
var mixed = Duel(root, Duels, 4, Seed, Path.Combine(root, "mixed.json"), "--decisionsA", "random");
TestContext.Progress.WriteLine("random A vs Smart B: " + mixed["winsA"] + " - " + mixed["winsB"]);
Assert.That((int)mixed["errors"], Is.EqualTo(0));
Assert.That((int)mixed["winsB"], Is.GreaterThan((int)mixed["winsA"] * 3), "the Smart brain beats random answers");
}
[Test]
public void HelpAndBadArguments()
{
+113
View File
@@ -0,0 +1,113 @@
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using NUnit.Framework;
using YGOLegacy.Bots.Decisions;
namespace YGOLegacy.Bots.Tests
{
[TestFixture, NonParallelizable]
public class DecisionTests
{
private sealed class First : IDecisionMaker
{
public Decision Decide(DecisionRequest request) => Decision.Of(0);
}
[Test]
public void NoTokenAndBuiltInAreTheSeatsOwnBrain()
{
Assert.That(DecisionMakers.For(new DecisionSeat { name = "A" }), Is.Null);
Assert.That(DecisionMakers.For(new DecisionSeat { name = "A", decisions = "BuiltIn" }), Is.Null);
}
[Test]
public void AnUnknownNameIsLoggedAndGetsTheBuiltInBrain()
{
var host = new TestHost();
var log = BotHost.Log;
BotHost.Log = host;
try
{
Assert.That(DecisionMakers.For(new DecisionSeat { name = "A", decisions = "nosuch" }), Is.Null);
Assert.That(host.Lines, Has.Some.Contains("no decision maker named 'nosuch'"));
}
finally { BotHost.Log = log; }
}
[Test]
public void ARegisteredMakerIsBuiltPerSeat()
{
var seats = new List<string>();
DecisionMakers.Register("test-first", seat => { seats.Add(seat.name); return new First(); });
try
{
Assert.That(DecisionMakers.For(new DecisionSeat { name = "A", decisions = "test-first" }), Is.InstanceOf<First>());
Assert.That(seats, Is.EqualTo(new[] { "A" }));
Assert.Throws<System.ArgumentException>(() => DecisionMakers.Register("builtin", seat => new First()));
}
finally { DecisionMakers.Unregister("test-first"); }
}
[Test]
public void TheHostDefaultAppliesUnlessTheSeatSaysOtherwise()
{
try
{
BotHost.Decisions = DecisionMakers.First;
Assert.That(DecisionMakers.For(new DecisionSeat { name = "A" }), Is.InstanceOf<FirstDecisions>(), "no token: the host default");
Assert.That(DecisionMakers.For(new DecisionSeat { name = "A", decisions = "random" }), Is.InstanceOf<RandomDecisions>(), "the token wins");
Assert.That(DecisionMakers.For(new DecisionSeat { name = "A", decisions = "builtin" }), Is.Null, "builtin: the executor despite the default");
}
finally { BotHost.Decisions = null; }
}
[Test]
public void FirstSolvesSumsAndCountersFromTheOptions()
{
var first = new FirstDecisions();
var sum = new DecisionRequest { kind = DecisionKind.Sum, value = 8, exact = true, min = 1, max = 3 };
foreach (var (v1, v2) in new[] { (4, 0), (3, 0), (2, 6), (4, 0) })
sum.options.Add(new DecisionOption { index = sum.options.Count, value = v1, value2 = v2 });
Assert.That(first.Decide(sum).choose, Is.EqualTo(new[] { 0, 3 }), "the first options, in order, that make exactly 8");
sum.exact = false;
sum.value = 9;
Assert.That(first.Decide(sum).choose, Is.EqualTo(new[] { 0, 1, 2 }), "at least 9, and dropping the smallest falls short");
var counter = new DecisionRequest { kind = DecisionKind.Counter, value = 3 };
counter.options.Add(new DecisionOption { index = 0, value = 2 });
counter.options.Add(new DecisionOption { index = 1, value = 5 });
Assert.That(first.Decide(counter).counts, Is.EqualTo(new[] { 2, 1 }));
}
[Test]
public void RequestsAndAnswersAreJson()
{
var request = new DecisionRequest
{
kind = DecisionKind.Idle, seat = "A", prompt = 3,
options = { new DecisionOption { index = 0, action = "summon", card = new CardView { code = 11091375, location = "hand" } },
new DecisionOption { index = 1, action = "toEnd" } },
duel = new DuelView { turn = 1, phase = "main1", myTurn = true, me = new PlayerView { lp = 8000 }, opponent = new PlayerView { lp = 8000 } },
};
var back = JsonConvert.DeserializeObject<DecisionRequest>(JsonConvert.SerializeObject(request));
Assert.That(JsonConvert.SerializeObject(back), Is.EqualTo(JsonConvert.SerializeObject(request)));
Assert.That(back.options[0].card.code, Is.EqualTo(11091375));
var answer = JsonConvert.DeserializeObject<Decision>("{\"choose\":[1]}");
Assert.That(answer.choose, Is.EqualTo(new[] { 1 }));
}
[Test]
public void RandomAnswersAreInRange()
{
var random = new RandomDecisions(1);
var request = new DecisionRequest { kind = DecisionKind.Tribute, min = 2, max = 2, cancelable = true };
for (int i = 0; i < 4; ++i) request.options.Add(new DecisionOption { index = i, action = "card" });
for (int i = 0; i < 200; ++i)
{
var n = random.Decide(request).choose.Count;
Assert.That(n == 0 || n == 2, "cancel or exactly two, got " + n);
}
Assert.That(random.Decide(new DecisionRequest { kind = DecisionKind.Sum }), Is.Null, "sums are left to the brain");
}
}
}
File diff suppressed because it is too large. Load diff