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>
This commit is contained in:
donnyandClaude Opus 5.5 committed 2026-10-19 18:38:00 -07:00
1 parent 0fd327e933
commit c034354d12
12 files changed
+2480 -33

No files matched your search

+3 -1
View File
@@ -13,7 +13,9 @@ Instructions for any coding agent. `README.md` has the layout, the contract, the
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.
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 .`
+7 -4
View File
@@ -3,17 +3,20 @@
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
## 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 (same 100-duel report).
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>`; `DecisionMakers.Register` names one. Built in:
`builtin` (the executor) and `random` (a random legal answer from the request's JSON).
- 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
+20 -11
View File
@@ -82,10 +82,12 @@ public interface IDecisionMaker
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).
`--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
@@ -98,10 +100,16 @@ public interface IDecisionMaker
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.
- **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
@@ -118,9 +126,10 @@ The tests: the library through `BotHost` (cards, deck caps and `#ruleset`, the r
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`.
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 -3
View File
@@ -24,8 +24,8 @@ namespace YGOLegacy.Bots.Decisions
/// <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>); the host or a plug-in registers the name. No token, or
/// <see cref="BuiltIn"/>, is the seat's own executor.
/// <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
{
@@ -37,10 +37,15 @@ namespace YGOLegacy.Bots.Decisions
/// 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.
@@ -59,7 +64,7 @@ namespace YGOLegacy.Bots.Decisions
/// 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;
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;
@@ -127,6 +132,8 @@ namespace YGOLegacy.Bots.Decisions
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).
@@ -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));
}
}
}
@@ -31,7 +31,7 @@ namespace YGOLegacy.Bots.Decisions
int j = random.Next(i + 1);
(order[i], order[j]) = (order[j], order[i]);
}
if (copy.kind == DecisionKind.Sort)
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);
+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");
}
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using YGOLegacy.Bots;
using YGOLegacy.Bots.Decisions;
@@ -17,6 +18,12 @@ namespace WindBot.Game
{
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()
{
@@ -39,6 +46,7 @@ namespace WindBot.Game
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;
@@ -56,9 +64,72 @@ namespace WindBot.Game
{
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;
@@ -77,7 +148,7 @@ namespace WindBot.Game
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 (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;
}
@@ -490,7 +490,10 @@ 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 = YGOL_RockPaperScissors(); // [YGOL] decision seam
Connection.Send(CtosMessage.HandResult, (byte)result);
@@ -683,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)
@@ -1146,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)
@@ -1319,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 = YGOL_SelectCards(tribute ? YGOLegacy.Bots.Decisions.DecisionKind.Tribute : YGOLegacy.Bots.Decisions.DecisionKind.Card, func, cards, min, max, _select_hint, cancelable); // [YGOL] decision seam
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
@@ -1487,12 +1499,14 @@ 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;
}
@@ -1657,7 +1671,8 @@ 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;
}
@@ -1869,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;
}
@@ -2190,7 +2206,10 @@ 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 = YGOL_RockPaperScissors(); // [YGOL] decision seam
Connection.Send(CtosMessage.Response, result);
+70 -2
View File
@@ -100,9 +100,76 @@ 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)
private static IEnumerable<string> WorkerLog(string root)
=> Directory.GetFiles(Path.Combine(root, "Data", "BotArena", "logs"), "worker-*.log", SearchOption.AllDirectories)
.SelectMany(File.ReadLines).Where(l => l.Contains("[YGOL decisions]")).ToArray();
.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()
@@ -115,6 +182,7 @@ namespace YGOLegacy.Bots.Tests
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");
}
+34 -3
View File
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using NUnit.Framework;
using YGOLegacy.Bots.Decisions;
@@ -38,14 +39,44 @@ namespace YGOLegacy.Bots.Tests
public void ARegisteredMakerIsBuiltPerSeat()
{
var seats = new List<string>();
DecisionMakers.Register("first", seat => { seats.Add(seat.name); return new First(); });
DecisionMakers.Register("test-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(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("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]
File diff suppressed because it is too large. Load diff