What came from the game now comes through YGOLegacy.Bots.BotHost (Host/BotHost.cs): Log (was UnityEngine.Debug), Cards (the SQLite connection; was Mono.Data.Sqlite), Files (locale and the expansions' .cdb; was MDPro3 Language/ResourceManager, GamePaths.PATH_EXPANSIONS), DeckLimits (#ruleset -> caps; was the game's DeckLimits/Rulesets) and BotConf (bot.conf; was SoloLoader). CharacterRegistry loses its UniTask surface and keeps Scan/Publish (now public) and LoadFromDisk. No YGOL_STANDALONE branches are left. Internals stay internal, visible to Assembly-CSharp(-Editor), BotArena and the tests. References the engine release's binding (engine.json pins v1.4.1). No change to how the bots play. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
267 lines
13 KiB
C#
267 lines
13 KiB
C#
using System.Collections.Generic;
|
|
using System.Text.RegularExpressions;
|
|
using YGOLegacy.Bots;
|
|
using YGOLegacy.Characters;
|
|
|
|
namespace YGOLegacy.Services
|
|
{
|
|
// Assets/Scripts/MasterDuel/Character.cs is a global-namespace MonoBehaviour
|
|
// of the same name and would win the lookup from a top-level using, so the
|
|
// model is aliased inside the namespace, where the alias is found first.
|
|
using Character = YGOLegacy.Characters.Character;
|
|
|
|
/// <summary>
|
|
/// One AI the fork can put in a duel seat: a display name plus the WindBot
|
|
/// command that summons it. This is deliberately NOT MDPro3's bot.conf
|
|
/// roster model (difficulty tiers, random pools, per-bot flag lists) — it is
|
|
/// what a deck resolves to (deck → owning Character → that deck's brain),
|
|
/// so nothing downstream has to know about characters at all.
|
|
/// </summary>
|
|
public class BotDef
|
|
{
|
|
/// Stable key the UI/config store; never shown to the player.
|
|
public string id;
|
|
/// The Character this bot is a view of; null for the built-in Dovphin
|
|
/// fallback (no character owns the deck, or the registry isn't loaded).
|
|
public string characterId;
|
|
/// Name for the seat card, and the basis of the in-room player name.
|
|
public string displayName;
|
|
/// bot.conf-style argument line ("Name=… Deck=…").
|
|
public string windBotCommand;
|
|
/// True when the command carries no deck and WindBot must be handed one
|
|
/// via DeckFile= (always true today: the seat's deck IS the deck played,
|
|
/// whether Dovphin or a character-owned brain pilots it).
|
|
public bool needsDeckFile;
|
|
public string deckPath;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Deck → brain resolution. There is NO bot picker: a seat is given a deck,
|
|
/// and the deck decides who plays it. If a Character (Data/Characters/)
|
|
/// owns the deck, the seat gets that character's name and that deck's
|
|
/// brain; otherwise it gets Dovphin, the "use your deck" bot from the
|
|
/// active language's bot.conf, exactly as before.
|
|
///
|
|
/// All()/ById()/Default() survive for callers, but the roster is one entry
|
|
/// (Dovphin) — it is not something the UI chooses from. Do NOT resurrect
|
|
/// MDPro3's bot list UI.
|
|
/// </summary>
|
|
public static class BotRoster
|
|
{
|
|
public const string DovphinId = "dovphin";
|
|
|
|
/// Every locale's bot.conf marks its "use your deck" entry with this
|
|
/// flag, so the roster is read out of the active language file.
|
|
private const string UseYourDeckFlag = "SELECT_DECKFILE";
|
|
private const string DovphinFallbackCommand = "Name=Dovphin Deck=Lucky";
|
|
|
|
// The host reads the locale's bot.conf (the game: SoloLoader; BotArena: Setup.ReadBots).
|
|
public static void Reload() => BotHost.BotConf.Reload();
|
|
|
|
private static IReadOnlyList<BotConfEntry> Conf() => BotHost.BotConf.Entries();
|
|
|
|
/// The Name= token in a bot.conf command line, quoted or bare.
|
|
private static readonly Regex NameToken =
|
|
new("Name=('([^']*)'|\"([^\"]*)\"|(\\S+))");
|
|
|
|
// TICKET-171: the two tokens the bot announces over Appearance; matched so a caller-supplied command is never double-tokened.
|
|
private static readonly Regex CharacterToken =
|
|
new("Character=('([^']*)'|\"([^\"]*)\"|(\\S+))");
|
|
|
|
private static readonly Regex GroupToken =
|
|
new("Group=('([^']*)'|\"([^\"]*)\"|(\\S+))");
|
|
|
|
private static readonly Regex ExecutorToken =
|
|
new("(?<![A-Za-z])Deck=('([^']*)'|\"([^\"]*)\"|(\\S+))");
|
|
|
|
/// <summary>
|
|
/// The bot that plays a deck: the owning character's brain for that
|
|
/// deck, or Dovphin when no character owns it (or the path is empty).
|
|
/// The returned BotDef always needsDeckFile — pass the same path to
|
|
/// CommandFor so WindBot loads it.
|
|
/// </summary>
|
|
public static BotDef ForDeck(string deckPath)
|
|
{
|
|
var character = CharacterRegistry.ForDeck(deckPath);
|
|
if (character == null || character.id == DovphinId)
|
|
return Dovphin();
|
|
var brain = character.BrainFor(deckPath) ?? character.brain;
|
|
return FromCharacter(character, brain);
|
|
}
|
|
|
|
public static IReadOnlyList<BotDef> ForRuleset(string rulesetId)
|
|
{
|
|
var bots = new List<BotDef>();
|
|
foreach (var character in CharacterRegistry.All())
|
|
{
|
|
if (character == null || character.id == DovphinId)
|
|
continue;
|
|
foreach (var deck in character.decks)
|
|
{
|
|
if (deck == null || string.IsNullOrEmpty(deck.path) || !deck.Plays(rulesetId))
|
|
continue;
|
|
var bot = FromCharacter(character, deck.brain ?? character.brain);
|
|
bot.deckPath = Character.NormalizeDeckPath(deck.path);
|
|
bots.Add(bot);
|
|
}
|
|
}
|
|
return bots;
|
|
}
|
|
|
|
public static bool DeckPlays(string deckPath, string rulesetId)
|
|
{
|
|
var deck = CharacterRegistry.ForDeck(deckPath)?.DeckFor(deckPath);
|
|
return (deck ?? new DeckRef()).Plays(rulesetId);
|
|
}
|
|
|
|
/// The fallback bot alone; the UI has nothing to choose from.
|
|
public static IReadOnlyList<BotDef> All() => new[] { Default() };
|
|
|
|
/// The bot used when a seat has no deck yet: Dovphin.
|
|
public static BotDef Default() => Dovphin();
|
|
|
|
/// Kept for callers holding a stored id; the id no longer selects
|
|
/// anything (the deck does), so this is the default.
|
|
public static BotDef ById(string id) => Default();
|
|
|
|
/// A character-owned deck's bot: `Name="<name>" Deck=<executor>`.
|
|
private static BotDef FromCharacter(Character character, BrainConfig brain)
|
|
{
|
|
var name = (character.name ?? character.id).Replace("\"", string.Empty).Replace("'", string.Empty);
|
|
// ygopro player names are 20 UTF-16 units max (WriteUnicode throws
|
|
// past that, and WindBot then never joins). Leave 2 for the arena's
|
|
// " A"/" B" seat suffix: "Maximillion Pegasus" (19) was the first
|
|
// to overflow as "Maximillion Pegasus A".
|
|
name = ClipName(name, MaxWindBotName);
|
|
var executor = string.IsNullOrEmpty(brain?.executor) ? "Lucky" : brain.executor;
|
|
return new BotDef
|
|
{
|
|
id = character.id,
|
|
characterId = character.id,
|
|
displayName = name,
|
|
windBotCommand = "Name=\"" + name + "\" Deck=" + executor,
|
|
needsDeckFile = true,
|
|
};
|
|
}
|
|
|
|
/// ygopro's 20-char name cap minus the arena seat suffix (" A"/" B").
|
|
public const int MaxWindBotName = 18;
|
|
|
|
/// <see cref="MaxWindBotName"/>: a too-long "First Last" becomes
|
|
/// "F. Last" (keeps the recognisable surname); anything else is hard-cut.
|
|
public static string ClipName(string name, int max)
|
|
{
|
|
if (string.IsNullOrEmpty(name) || name.Length <= max) return name;
|
|
var words = name.Split(' ', System.StringSplitOptions.RemoveEmptyEntries);
|
|
if (words.Length >= 2)
|
|
{
|
|
var initials = words[0].Substring(0, 1) + ". " + words[words.Length - 1];
|
|
if (initials.Length <= max) return initials;
|
|
}
|
|
return name.Substring(0, max).TrimEnd();
|
|
}
|
|
|
|
private static BotDef Dovphin()
|
|
{
|
|
var command = DovphinCommand();
|
|
return new BotDef
|
|
{
|
|
id = DovphinId,
|
|
characterId = CharacterRegistry.ById(DovphinId)?.id,
|
|
displayName = NameOf(command, "Dovphin"),
|
|
windBotCommand = command,
|
|
// The Lucky executor has no cards of its own — without a
|
|
// DeckFile it sits down with nothing.
|
|
needsDeckFile = true,
|
|
};
|
|
}
|
|
|
|
/// bot.conf's "use your deck" line in the active language, falling back
|
|
/// to the en-US text when the roster has not been read (or lost it).
|
|
private static string DovphinCommand()
|
|
{
|
|
foreach (var bot in Conf())
|
|
{
|
|
if (System.Array.IndexOf(bot.flags, UseYourDeckFlag) >= 0)
|
|
return bot.command;
|
|
}
|
|
return DovphinFallbackCommand;
|
|
}
|
|
|
|
/// The Name= value of a command line.
|
|
public static string NameOf(string command, string fallback)
|
|
{
|
|
var match = NameToken.Match(command ?? string.Empty);
|
|
var name = match.Success ? match.Groups[1].Value.Trim('\'', '"') : string.Empty;
|
|
return string.IsNullOrEmpty(name) ? fallback : name;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The command line that actually starts this bot: its roster command
|
|
/// with the deck it must play and, optionally, a seat-specific name so
|
|
/// two copies of the same bot are told apart in the room.
|
|
///
|
|
/// The name is quoted because seat names contain a space ("Dovphin 1");
|
|
/// DuelLauncher.StartWindBot splits on spaces outside quotes and strips
|
|
/// the quotes afterwards, so the bot receives the name whole. WindBot's
|
|
/// DeckFile= resolves under Deck/, so "group/name" works as-is.
|
|
/// </summary>
|
|
// TICKET-285: a Room CPU always sits down deckless and is handed its deck in-process (WindBot DeferDeck).
|
|
public static string CpuCommand(int number, int seat, byte[] token, string difficulty, byte[] restartId = null)
|
|
{
|
|
var command = CommandFor(Default(), null, "CPU " + number) + " DeferDeck=true";
|
|
if (seat >= 0 && token != null)
|
|
command += " Seat=" + seat + " SeatToken=" + YGOLegacy.Protocol.Contracts.SeatIds.ToHex(token);
|
|
if (!string.IsNullOrEmpty(difficulty))
|
|
command += " Difficulty=" + difficulty.ToLowerInvariant();
|
|
// TICKET-286: a CPU returning after a rules restart claims with the restart id and comes back unready.
|
|
if (restartId != null)
|
|
command += " RestartId=" + YGOLegacy.Protocol.Contracts.SeatIds.ToHex(restartId) + " HoldReady=true";
|
|
return command;
|
|
}
|
|
|
|
// The Deck= executor of the bot that plays this deck: the brain follows the deck.
|
|
public static string ExecutorFor(string deckPath)
|
|
{
|
|
var match = ExecutorToken.Match(ForDeck(deckPath).windBotCommand ?? string.Empty);
|
|
if (!match.Success) return null;
|
|
for (int g = 2; g <= 4; g++)
|
|
if (match.Groups[g].Success && match.Groups[g].Value.Length > 0)
|
|
return match.Groups[g].Value;
|
|
return null;
|
|
}
|
|
|
|
// S5: what a CPU on this deck plays with before the host changes anything; keys are the Room's CPU settings keys.
|
|
public static Dictionary<string, string> BrainValues(string deckPath)
|
|
{
|
|
var values = new Dictionary<string, string>();
|
|
var executor = string.IsNullOrEmpty(deckPath) ? null : ExecutorFor(deckPath);
|
|
values["executor"] = (string.IsNullOrEmpty(executor) ? "Lucky" : executor).ToLowerInvariant();
|
|
if (string.IsNullOrEmpty(deckPath)) return values;
|
|
foreach (var pair in CharacterRegistry.GroupKnobs(deckPath))
|
|
values[pair.Key] = pair.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
var character = CharacterRegistry.ForDeck(deckPath);
|
|
var brain = character == null ? null : character.BrainFor(deckPath) ?? character.brain;
|
|
if (brain?.knobs != null)
|
|
foreach (var pair in brain.knobs)
|
|
values[pair.Key] = pair.Value.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
|
return values;
|
|
}
|
|
|
|
public static string CommandFor(BotDef bot, string deckPath, string seatName)
|
|
{
|
|
var command = bot.windBotCommand;
|
|
if (!string.IsNullOrEmpty(seatName))
|
|
command = NameToken.Replace(command, "Name=\"" + seatName + "\"", 1);
|
|
if (bot.needsDeckFile && !string.IsNullOrEmpty(deckPath))
|
|
command += " DeckFile=\"" + deckPath + "\"";
|
|
if (!string.IsNullOrEmpty(bot.characterId) && !CharacterToken.IsMatch(command))
|
|
command += " Character=\"" + bot.characterId + "\"";
|
|
var cut = string.IsNullOrEmpty(deckPath) ? -1 : deckPath.LastIndexOf('/');
|
|
if (cut > 0 && !GroupToken.IsMatch(command))
|
|
command += " Group=\"" + deckPath.Substring(0, cut) + "\"";
|
|
return command;
|
|
}
|
|
}
|
|
}
|