feat(decisions): the decision seam, one IDecisionMaker asked at every prompt
CI / build (push) Successful in 48s
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>
This commit is contained in:
1 parent
ac80760e00
commit
0fd327e933
15 files changed
+969
-30
No files matched your search
@@ -9,6 +9,11 @@ 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.
|
||||
- **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 .`
|
||||
|
||||
@@ -3,6 +3,19 @@
|
||||
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`).
|
||||
|
||||
## Unreleased
|
||||
|
||||
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 (same 100-duel report).
|
||||
|
||||
- `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>`; `DecisionMakers.Register` names one. Built in:
|
||||
`builtin` (the executor) and `random` (a random legal answer from the request's JSON).
|
||||
- `BotArena --decisionsA/--decisionsB <name>`.
|
||||
|
||||
## v0.1.0 — 2026-10-19
|
||||
|
||||
The bots leave the Unity repo. Engine `v1.4.1`.
|
||||
|
||||
@@ -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,48 @@ 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>`) and registered by name with `DecisionMakers.Register(name, seat => maker)`
|
||||
by the host or a plug-in. `builtin` (or no token) is the executor; an unknown name is logged and gets the
|
||||
executor. Built in: `random`, a uniformly random legal answer that reads only each request's JSON (a baseline,
|
||||
and the seam's own end-to-end test).
|
||||
- **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.
|
||||
- **A remote brain** (an LLM through OpenRouter, a model on a GPU box) is an `IDecisionMaker` that sends the request
|
||||
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 +115,12 @@ 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); 100 duels with both seats answered through the seam
|
||||
by `random` (0 errors, no fallback); `Decisions=builtin` giving the same duels as no token; and the Smart brain
|
||||
beating `random`.
|
||||
|
||||
## Engine pin
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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. |
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
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=<name></c> (the arena:
|
||||
/// <c>--decisionsA/--decisionsB</c>); the host or a plug-in registers the name. No token, or
|
||||
/// <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";
|
||||
|
||||
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),
|
||||
};
|
||||
|
||||
/// 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 = 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";
|
||||
/// 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,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)
|
||||
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) };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
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;
|
||||
|
||||
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 };
|
||||
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");
|
||||
}
|
||||
return builtIn();
|
||||
}
|
||||
|
||||
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) 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -491,7 +492,7 @@ namespace WindBot.Game
|
||||
if (_hand > 0)
|
||||
result = _hand;
|
||||
else
|
||||
result = _ai.OnRockPaperScissors();
|
||||
result = YGOL_RockPaperScissors(); // [YGOL] decision seam
|
||||
Connection.Send(CtosMessage.HandResult, (byte)result);
|
||||
}
|
||||
|
||||
@@ -500,7 +501,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));
|
||||
}
|
||||
@@ -1121,7 +1122,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)
|
||||
{
|
||||
@@ -1279,7 +1280,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)
|
||||
@@ -1325,7 +1326,7 @@ namespace WindBot.Game
|
||||
return;
|
||||
}
|
||||
|
||||
IList<ClientCard> selected = func(cards, min, max, _select_hint, cancelable);
|
||||
IList<ClientCard> selected = YGOL_SelectCards(tribute ? YGOLegacy.Bots.Decisions.DecisionKind.Tribute : YGOLegacy.Bots.Decisions.DecisionKind.Card, 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 +1406,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)
|
||||
{
|
||||
@@ -1496,7 +1497,7 @@ namespace WindBot.Game
|
||||
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 +1520,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 +1596,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);
|
||||
@@ -1663,7 +1664,7 @@ namespace WindBot.Game
|
||||
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 +1730,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 +1740,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 +1808,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);
|
||||
@@ -1880,7 +1881,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 +1941,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 +1975,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 +1994,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 +2152,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 +2162,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 +2178,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];
|
||||
@@ -2191,7 +2192,7 @@ namespace WindBot.Game
|
||||
if (_hand > 0)
|
||||
result = _hand;
|
||||
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;
|
||||
|
||||
@@ -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]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,39 @@ namespace YGOLegacy.Bots.Tests
|
||||
Assert.That(JToken.DeepEquals(a["duels"], other["duels"]), Is.False, "another seed plays other duels");
|
||||
}
|
||||
|
||||
private static string[] SeamWarnings(string root)
|
||||
=> Directory.GetFiles(Path.Combine(root, "Data", "BotArena", "logs"), "worker-*.log", SearchOption.AllDirectories)
|
||||
.SelectMany(File.ReadLines).Where(l => l.Contains("[YGOL decisions]")).ToArray();
|
||||
|
||||
[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");
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Collections.Generic;
|
||||
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("first", seat => { seats.Add(seat.name); return new First(); });
|
||||
try
|
||||
{
|
||||
Assert.That(DecisionMakers.For(new DecisionSeat { name = "A", decisions = "first" }), Is.InstanceOf<First>());
|
||||
Assert.That(seats, Is.EqualTo(new[] { "A" }));
|
||||
Assert.Throws<System.ArgumentException>(() => DecisionMakers.Register("builtin", seat => new First()));
|
||||
}
|
||||
finally { DecisionMakers.Unregister("first"); }
|
||||
}
|
||||
|
||||
[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");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user