import: the bot code from yugioh-legacy-unity dev at 19c6158197a0a8f0817dd0924bb9a6a987c2bfc5

Verbatim copies, new layout, no edits:

  Assets/Scripts/Windbot/** (minus BotWrapper.cs)       -> src/YGOLegacy.Bots/WindBot/
  Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper.Enums/*   -> src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/
  Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper/{Card,NamedCard,NamedCardsManager,CardsManager}.cs
                                                        -> src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/
  Assets/Scripts/YGOSharp/YGOSharp.Network/{BinaryClient,NetworkClient,YGOClient}.cs, Enums/*, Utils/BinaryExtensions.cs
                                                        -> src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/
  Assets/YGOLegacy/Scripts/Core/Bot/{SmartExecutor,BoardEvaluator,BattlePredictor,BrainRules,EffectSimulator,
    DuelStateBus,LocalDuelHost,LoopbackBotSeat,Lookahead,ArenaReport}.cs -> src/YGOLegacy.Bots/Bot/
  Assets/YGOLegacy/Scripts/Core/Identity/Characters/{Character,CharacterRegistry}.cs -> src/YGOLegacy.Bots/Characters/
  Assets/YGOLegacy/Scripts/Features/Solo/BotRoster.cs   -> src/YGOLegacy.Bots/Services/
  Tools/BotArena/**                                     -> src/BotArena/

Commit: 19c6158 (2026-10-19T15:29:54-07:00) duel: 8 prompt and bot fixes from duel bug hunt round 2
This commit is contained in:
donny committed 2026-10-19 18:08:01 -07:00
commit 6dbc9e78d8
152 files changed
+96107

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Standalone, parallel Bot Arena (TICKET-035). Compiles the in-tree WindBot
and the fork's brain by LINKING the sources (no copies), so the tool always
plays with exactly the code the game ships. See README.md.
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<AssemblyName>BotArena</AssemblyName>
<RootNamespace>YGOLegacy.Tools.BotArena</RootNamespace>
<StartupObject>YGOLegacy.Tools.BotArena.Program</StartupObject>
<!-- Linked Unity sources are not nullable-annotated and rely on explicit usings. -->
<Nullable>disable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<!-- Compiles out the UniTask surface of CharacterRegistry (see that file). -->
<DefineConstants>$(DefineConstants);YGOL_STANDALONE</DefineConstants>
<!-- Upstream code is noisy; keep the build output readable. -->
<NoWarn>$(NoWarn);CS0108;CS0114;CS0162;CS0164;CS0168;CS0169;CS0219;CS0414;CS0618;CS0649;CS0659;CS0661;CS1522;CS1570;CS1572;CS1573;CS1587;CS1591;CS8981;SYSLIB0011;CA1416</NoWarn>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<!-- Mono.Data.Sqlite shim (Shims/MonoDataSqlite.cs) sits on top of this. -->
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.8" />
</ItemGroup>
<!-- The engine release's C# binding (TICKET-400): EngineApi externs, MessageScan,
the wire protocol. Fetched by Tools/YGOLegacy/fetch-engine.ps1 with the engine. -->
<ItemGroup>
<Reference Include="YGOLegacy.Engine">
<HintPath>..\..\Assets\Plugins\Managed\YGOLegacy.Engine.dll</HintPath>
</Reference>
</ItemGroup>
<!-- ===================== WindBot (upstream, in-tree) ===================== -->
<ItemGroup>
<Compile Include="../../Assets/Scripts/Windbot/**/*.cs" Link="Linked/Windbot/%(RecursiveDir)%(Filename)%(Extension)" />
<!-- Excluded: BotWrapper.cs is an unused upstream launcher stub with a second
Main() and no callers; nothing else in WindBot references it. -->
<Compile Remove="../../Assets/Scripts/Windbot/BotWrapper.cs" />
</ItemGroup>
<!-- ============== YGOSharp: only what WindBot itself needs ============== -->
<ItemGroup>
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper.Enums/*.cs" Link="Linked/YGOSharp/OCGWrapper.Enums/%(Filename)%(Extension)" />
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper/Card.cs" Link="Linked/YGOSharp/OCGWrapper/Card.cs" />
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper/NamedCard.cs" Link="Linked/YGOSharp/OCGWrapper/NamedCard.cs" />
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper/NamedCardsManager.cs" Link="Linked/YGOSharp/OCGWrapper/NamedCardsManager.cs" />
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.OCGWrapper/CardsManager.cs" Link="Linked/YGOSharp/OCGWrapper/CardsManager.cs" />
<!-- Not linked: Api.cs/Duel.cs/MtRandom.cs (ocgcore P/Invoke — the game's
in-process core; the arena talks to ygoserver over TCP). -->
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.Network/BinaryClient.cs" Link="Linked/YGOSharp/Network/BinaryClient.cs" />
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.Network/NetworkClient.cs" Link="Linked/YGOSharp/Network/NetworkClient.cs" />
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.Network/YGOClient.cs" Link="Linked/YGOSharp/Network/YGOClient.cs" />
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.Network/Enums/*.cs" Link="Linked/YGOSharp/Network/Enums/%(Filename)%(Extension)" />
<Compile Include="../../Assets/Scripts/YGOSharp/YGOSharp.Network/Utils/BinaryExtensions.cs" Link="Linked/YGOSharp/Network/Utils/BinaryExtensions.cs" />
<!-- Not linked: the Async*/NetworkServer/YGOSharp (server) files — unused by WindBot. -->
</ItemGroup>
<!-- ==================== YGOLegacy: brain + characters ==================== -->
<ItemGroup>
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/SmartExecutor.cs" Link="Linked/YGOLegacy/Bot/SmartExecutor.cs" />
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/BoardEvaluator.cs" Link="Linked/YGOLegacy/Bot/BoardEvaluator.cs" />
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/BattlePredictor.cs" Link="Linked/YGOLegacy/Bot/BattlePredictor.cs" />
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/BrainRules.cs" Link="Linked/YGOLegacy/Bot/BrainRules.cs" />
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/EffectSimulator.cs" Link="Linked/YGOLegacy/Bot/EffectSimulator.cs" />
<!-- Duel state bus + Insight (TICKET-042): Unity-free, so both bots of an
arena duel mirror each other exactly as they do in the game. -->
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/DuelStateBus.cs" Link="Linked/YGOLegacy/Bot/DuelStateBus.cs" />
<!-- In-process duel host (TICKET-045): ocgcore driven straight from this
process, with two WindBot clients on a loopback seam. Unity-free. -->
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/LocalDuelHost.cs" Link="Linked/YGOLegacy/Bot/LocalDuelHost.cs" />
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/LoopbackBotSeat.cs" Link="Linked/YGOLegacy/Bot/LoopbackBotSeat.cs" />
<!-- TICKET-050: the lookahead interfaces. The oracle that implements
ILookaheadOracle is arena-only (ReplayOracle.cs) — the game installs
none, which is what keeps SmartExecutor's planner inert there. -->
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/Lookahead.cs" Link="Linked/YGOLegacy/Bot/Lookahead.cs" />
<!-- The report model + pure helpers shared with the in-editor arena (same JSON). -->
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Bot/ArenaReport.cs" Link="Linked/YGOLegacy/Bot/ArenaReport.cs" />
<!-- Not linked: BotArena.cs (the in-editor runner: UniTask, OcgCore, TcpHelper). -->
<!-- Path constants: WindBot's own Program.cs reads Expansions/ through them. -->
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/GamePaths.cs" Link="Linked/YGOLegacy/GamePaths.cs" />
<Compile Include="../../Assets/YGOLegacy/Scripts/Core/Identity/Characters/*.cs" Link="Linked/YGOLegacy/Characters/%(Filename)%(Extension)" />
<!-- Excluded: VoiceLineStore.cs is playback (UnityEngine.Random, Language) and
nothing in the arena speaks. -->
<Compile Remove="../../Assets/YGOLegacy/Scripts/Core/Identity/Characters/VoiceLineStore.cs" />
<!-- The deck size caps WindBot's own Deck.cs reads (TICKET-059: extra deck is 99 here). -->
<Compile Include="../../Assets/YGOLegacy/Scripts/Features/DeckEditor/DeckLimits.cs" Link="Linked/YGOLegacy/Services/DeckLimits.cs" />
<Compile Include="../../Assets/YGOLegacy/Scripts/Features/Solo/BotRoster.cs" Link="Linked/YGOLegacy/Services/BotRoster.cs" />
</ItemGroup>
</Project>
+191
View File
@@ -0,0 +1,191 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Runtime.InteropServices;
using YGOLegacy.Bot;
using YGOLegacy.Engine;
using YGOSharp.OCGWrapper;
namespace YGOLegacy.Tools.BotArena
{
/// <summary>
/// TICKET-045: everything <see cref="LocalDuelHost"/> needs from the game's
/// data folders — the native core, the card table and the Lua scripts.
///
/// Cards do NOT get a second database reader. WindBot's
/// <c>NamedCardsManager</c> is already loaded with exactly the cdbs the game
/// feeds it (<c>Setup.InitWindBot</c>: the locale cards.cdb, every .cdb
/// inside <c>Expansions/*.ypk</c>, then <c>Expansions/*.cdb</c>, later files
/// winning), read-only through the Mono.Data.Sqlite shim, and
/// <c>YGOSharp.OCGWrapper.Card.Data</c> is that row already shaped like
/// ocgcore's <c>card_data</c>. Reusing it means the core and the brains can
/// never disagree about a card, and there is one card-loading path to keep
/// working instead of two.
///
/// Scripts follow the order the game resolves them in (PercyOCG's [YGOL]
/// comment and ygoserver both prefer the exploded pack): loose
/// <c>Expansions/script/</c>, then the <c>script/</c> entries of every
/// <c>Expansions/*.ypk|*.zip</c>, then <c>Data/script.zip</c>, then a loose
/// <c>script/</c> under the root. That is what keeps the loose
/// <c>Expansions/script/procedure.lua</c> override in charge.
/// </summary>
internal static class LocalHost
{
private static bool installed;
private static readonly Dictionary<string, byte[]> scriptCache = new(StringComparer.OrdinalIgnoreCase);
private static readonly List<ZipArchive> archives = new();
private static readonly List<Dictionary<string, ZipArchiveEntry>> archiveIndex = new();
private static string root;
/// <summary>
/// Point the runtime at ygol-engine.dll and install the process-global card
/// and script readers. Idempotent; call once per worker.
/// </summary>
public static void Install(string gameRoot)
{
if (installed) return;
root = gameRoot;
var dll = LocateCore(gameRoot);
NativeLibrary.SetDllImportResolver(typeof(EngineApi).Assembly, (name, asm, path) =>
name == "ygol-engine" ? NativeLibrary.Load(dll) : IntPtr.Zero);
IndexScriptArchives(gameRoot);
LocalDuelHost.InstallReaders(ReadCard, ReadScript);
installed = true;
Worker.Log("local host: engine=" + dll + ", script archives=" + archives.Count);
}
private static string LocateCore(string gameRoot)
{
var candidates = new[]
{
Environment.GetEnvironmentVariable("YGOL_ENGINE_DLL"),
Path.Combine(gameRoot, "Assets", "Plugins", "Windows", "ygol-engine.dll"),
Path.Combine(gameRoot, "YGOLegacy_Data", "Plugins", "x86_64", "ygol-engine.dll"),
Path.Combine(gameRoot, "MDPro3_Data", "Plugins", "x86_64", "ygol-engine.dll"),
Path.Combine(AppContext.BaseDirectory, "ygol-engine.dll"),
};
foreach (var c in candidates)
if (!string.IsNullOrEmpty(c) && File.Exists(c)) return Path.GetFullPath(c);
throw new FileNotFoundException("ygol-engine.dll not found (looked under --root in Assets/Plugins/Windows, a built player's Plugins/x86_64, next to the exe, and $YGOL_ENGINE_DLL)");
}
// ------------------------------------------------------------------
// Cards
// ------------------------------------------------------------------
private static LocalCardData? ReadCard(int code)
{
var card = NamedCard.Get(code);
if (card == null) return null;
var d = card.Data;
var data = new LocalCardData
{
Code = d.Code,
Alias = d.Alias,
Type = d.Type,
Level = d.Level,
Attribute = d.Attribute,
Race = d.Race,
Attack = d.Attack,
Defense = d.Defense,
LScale = d.LScale,
RScale = d.RScale,
LinkMarker = d.LinkMarker,
};
data.SetSetcode(d.Setcode);
return data;
}
// ------------------------------------------------------------------
// Scripts
// ------------------------------------------------------------------
private static void IndexScriptArchives(string gameRoot)
{
var files = new List<string>();
var expansions = Path.Combine(gameRoot, "Expansions");
if (Directory.Exists(expansions))
{
files.AddRange(Directory.GetFiles(expansions, "*.ypk"));
files.AddRange(Directory.GetFiles(expansions, "*.zip"));
files.Sort(StringComparer.OrdinalIgnoreCase);
}
var scriptZip = Path.Combine(gameRoot, "Data", "script.zip");
if (File.Exists(scriptZip)) files.Add(scriptZip); // last: the stock library
foreach (var file in files)
{
try
{
var zip = ZipFile.OpenRead(file);
var index = new Dictionary<string, ZipArchiveEntry>(StringComparer.OrdinalIgnoreCase);
foreach (var entry in zip.Entries)
{
if (entry.Length == 0) continue;
var name = entry.FullName.Replace('\\', '/');
if (!name.StartsWith("script/", StringComparison.OrdinalIgnoreCase)) continue;
index[name] = entry;
}
if (index.Count == 0) { zip.Dispose(); continue; }
archives.Add(zip);
archiveIndex.Add(index);
}
catch (Exception e)
{
Worker.Log("local host: skipping " + file + " (" + e.Message + ")");
}
}
}
/// <summary>
/// The core asks for names like <c>./script/c12345.lua</c> (and, once per
/// duel, constant/utility/procedure). Null = "no such script", which the
/// core treats as an empty file.
/// </summary>
private static byte[] ReadScript(string name)
{
if (string.IsNullOrEmpty(name)) return null;
var rel = name.Replace('\\', '/').TrimStart('.', '/');
if (scriptCache.TryGetValue(rel, out var cached)) return cached;
byte[] content = null;
// 1. the exploded custom pack (the documented source of truth)
var loose = Path.Combine(root, "Expansions", rel.Replace('/', Path.DirectorySeparatorChar));
if (File.Exists(loose)) content = TryRead(loose);
// 2. the .ypk archives, then Data/script.zip
if (content == null)
{
for (var i = 0; i < archiveIndex.Count && content == null; i++)
{
if (!archiveIndex[i].TryGetValue(rel, out var entry)) continue;
try
{
using var stream = entry.Open();
using var buffer = new MemoryStream();
stream.CopyTo(buffer);
content = buffer.ToArray();
}
catch (Exception) { }
}
}
// 3. a loose script/ folder under the root (ygoserver reads ./script)
if (content == null)
{
var rootScript = Path.Combine(root, rel.Replace('/', Path.DirectorySeparatorChar));
if (File.Exists(rootScript)) content = TryRead(rootScript);
}
scriptCache[rel] = content;
return content;
}
private static byte[] TryRead(string path)
{
try { return File.ReadAllBytes(path); }
catch (Exception) { return null; }
}
}
}
+627
View File
@@ -0,0 +1,627 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using YGOLegacy.Bot;
using YGOLegacy.Characters;
using YGOLegacy.Engine;
using YGOLegacy.Services;
namespace YGOLegacy.Tools.BotArena
{
/// <summary>
/// Standalone, parallel Bot Arena (TICKET-035). No Unity in the loop: the
/// exe compiles the in-tree WindBot + the fork's brain, loads the engine
/// (ygol-engine.dll) itself and runs N bot-vs-bot duels across `--parallel` worker PROCESSES
/// (WindBot.Config is process-global, so one duel at a time per process).
///
/// Two modes in one exe:
/// parent — parses the CLI, resolves seats, spawns workers (this exe
/// with `--worker`), hands out duel indices over their stdin,
/// collects one JSON line per duel from their stdout, tallies
/// and writes the same report the in-editor arena writes.
/// worker — see Worker.cs.
/// Exit codes: 0 = at least one duel played, 1 = none, 2 = bad arguments.
/// </summary>
internal static class Program
{
private const string LogPrefix = "[arena] ";
private static Stopwatch wall;
private static int Main(string[] args)
{
Options opts;
try
{
opts = Options.Parse(args);
}
catch (ArgumentException e)
{
Console.Error.WriteLine("error: " + e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine(Options.Usage);
return 2;
}
if (opts.help)
{
Console.WriteLine(Options.Usage);
return 0;
}
if (opts.worker)
return Worker.Run(opts);
return RunParent(opts);
}
// ------------------------------------------------------------------
// Parent
// ------------------------------------------------------------------
private static int RunParent(Options opts)
{
wall = Stopwatch.StartNew();
Directory.SetCurrentDirectory(opts.root);
try
{
YgoServer.Locate(opts.root);
Log("engine " + EngineBinding.CheckNative() + " (" + YgoServer.DllPath + ")");
}
catch (Exception e)
{
Console.Error.WriteLine(LogPrefix + e.Message);
return 1;
}
var result = new StandaloneArenaResult
{
startedAt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
config = opts.ToConfig(),
workers = opts.parallel,
status = "starting",
};
var workers = new List<WorkerHandle>();
try
{
if (!ValidateDeck(opts.deckA, out var whyA)) { result.status = "bad deck A: " + whyA; }
else if (!ValidateDeck(opts.deckB, out var whyB)) { result.status = "bad deck B: " + whyB; }
else
{
// Seats: the deck decides the brain (BotRoster.ForDeck), the
// executor override rewrites Deck= — identical to BotArena.cs.
Setup.LoadGameData(opts);
var botA = BotRoster.ForDeck(opts.deckA);
var botB = BotRoster.ForDeck(opts.deckB);
result.nameA = ArenaReport.SeatName(botA, 0);
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);
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))
{
if (opts.hostMode == "local")
Log("--replays is server-only: the in-process host has no ygoserver to send STOC_REPLAY, so no .yrp will be written (use --host server)");
Directory.CreateDirectory(opts.replaysDir);
}
if (!string.IsNullOrEmpty(opts.journalDir))
{
// The run's own config next to the journals, so blunders.py
// (and a human) can tell what produced them.
Directory.CreateDirectory(opts.journalDir);
var runInfo = new
{
startedAt = result.startedAt, config = result.config, workers = opts.parallel,
nameA = result.nameA, nameB = result.nameB, commandA = result.commandA, commandB = result.commandB,
journalFiles = "duel-<n>-<seat>.jsonl (Smart seats only)",
};
File.WriteAllText(Path.Combine(opts.journalDir, "run.json"), JsonConvert.SerializeObject(runInfo, Formatting.Indented));
}
RunDuels(opts, result, workers);
result.status = "done";
}
}
catch (Exception e)
{
Console.Error.WriteLine(LogPrefix + "failed: " + e);
result.status = "failed: " + e.Message;
}
finally
{
foreach (var w in workers) w.Kill();
result.totalSeconds = (float)wall.Elapsed.TotalSeconds;
result.wallClockSeconds = result.totalSeconds;
result.done = true;
result.summary = ArenaReport.Summary(result);
try { result.reportPath = WriteReport(result, opts.outPath); }
catch (Exception e) { Console.Error.WriteLine(LogPrefix + "could not write report: " + e.Message); }
Console.WriteLine(result.summary + (result.reportPath != null ? " -> " + result.reportPath : string.Empty));
}
return result.Played > 0 ? 0 : 1;
}
/// <summary>
/// Dynamic scheduling: every worker gets one duel index at a time and
/// the next as soon as it reports, so a slow duel or a dead worker never
/// stalls the run. A worker that dies mid-duel gets that duel re-queued
/// once; with no worker left, what remains is recorded as errors.
/// </summary>
private static void RunDuels(Options opts, StandaloneArenaResult result, List<WorkerHandle> workers)
{
var pending = new Queue<int>();
for (var i = 1; i <= opts.n; i++) pending.Enqueue(i);
if (pending.Count == 0) return;
var count = Math.Min(opts.parallel, opts.n);
var received = new Dictionary<int, DuelRecord>();
var retried = new HashSet<int>();
var gate = new object();
var lastLog = 0;
var respawns = 0;
for (var w = 0; w < count; w++)
{
var handle = new WorkerHandle(w, opts, result, opts.portBase + w * 4, 0);
handle.OnRecord = record =>
{
lock (gate)
{
received[record.index] = record;
Monitor.PulseAll(gate);
}
};
handle.Start();
workers.Add(handle);
}
// Assign / collect loop.
var deadline = DateTime.UtcNow.AddSeconds(Math.Max(60, opts.timeoutSeconds + 120) * (double)Math.Max(1, (opts.n + count - 1) / count) + 120);
while (true)
{
lock (gate)
{
// Feed idle, live workers.
foreach (var w in workers)
{
if (!w.Alive || w.Busy != 0 || !w.Ready) continue;
if (pending.Count == 0) break;
var idx = pending.Dequeue();
w.Assign(idx);
}
// Collect anything that arrived.
foreach (var w in workers)
{
if (w.Busy != 0 && received.TryGetValue(w.Busy, out var rec))
{
received.Remove(w.Busy);
w.Busy = 0;
ArenaReport.Tally(result, rec);
result.totalSeconds = (float)wall.Elapsed.TotalSeconds;
Log("duel " + rec.index + " [w" + w.Index + "]: " + rec.winner
+ (rec.winnerName != null ? " (" + rec.winnerName + ")" : string.Empty)
+ " turns=" + rec.turns + " " + rec.durationSeconds.ToString("0.0", CultureInfo.InvariantCulture) + "s"
+ (rec.error != null ? " error=" + rec.error : string.Empty)
+ " | " + result.nameA + " " + result.winsA + " - " + result.winsB + " " + result.nameB
+ " (" + result.completed + "/" + opts.n + ")");
}
}
// Dead workers: requeue their duel once (else record an
// error) and start a replacement while there is work left —
// the engine's server can abort the whole process on a rare
// teardown race, and one crash must not cost a seat.
for (var i = 0; i < workers.Count; i++)
{
var w = workers[i];
if (w.Alive || w.Retired) continue;
w.Retired = true;
if (w.Busy != 0)
{
var idx = w.Busy;
w.Busy = 0;
if (retried.Add(idx)) pending.Enqueue(idx);
else ArenaReport.Tally(result, new DuelRecord { index = idx, winner = "error", error = "worker " + w.Index + " died" });
}
if (pending.Count > 0 && respawns < opts.parallel * 2)
{
respawns++;
Log("worker " + w.Index + " died (see " + WorkerHandle.LogDir + "); starting a replacement");
var again = new WorkerHandle(w.Index, opts, result, w.Port, w.Generation + 1) { OnRecord = w.OnRecord };
again.Start();
workers.Add(again);
}
}
var anyAlive = false;
var anyBusy = false;
foreach (var w in workers) { anyAlive |= w.Alive; anyBusy |= w.Busy != 0; }
if (pending.Count == 0 && !anyBusy) break;
if (!anyAlive)
{
while (pending.Count > 0)
ArenaReport.Tally(result, new DuelRecord { index = pending.Dequeue(), winner = "error", error = "no worker alive (see " + WorkerHandle.LogDir + ")" });
break;
}
if (DateTime.UtcNow > deadline)
{
Log("global deadline hit; abandoning " + pending.Count + " pending duel(s)");
while (pending.Count > 0)
ArenaReport.Tally(result, new DuelRecord { index = pending.Dequeue(), winner = "error", error = "run deadline" });
break;
}
if (++lastLog % 600 == 0 && result.completed == 0)
Log("waiting for the first result (workers load the card databases and index Expansions/ first)...");
Monitor.Wait(gate, 100);
}
}
result.duels.Sort((a, b) => a.index.CompareTo(b.index));
foreach (var w in workers) w.Quit();
}
private static string WriteReport(ArenaResult result, string extra)
{
Directory.CreateDirectory(ArenaReport.OutputDir);
var file = ArenaReport.ReportFileName(result, DateTime.Now);
var json = JsonConvert.SerializeObject(result, Formatting.Indented);
File.WriteAllText(file, json);
if (!string.IsNullOrWhiteSpace(extra))
{
var dir = Path.GetDirectoryName(Path.GetFullPath(extra));
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(extra, json);
}
return file;
}
/// Same resolution WindBot's Program.ReadFile("Decks", …, "ydk") does at
/// join time, so a deck the tool accepts is a deck the bot will load.
private static bool ValidateDeck(string path, out string why)
{
why = null;
if (string.IsNullOrWhiteSpace(path)) { why = "empty"; return false; }
if (Setup.ResolveDeckFile(path) != null) return true;
why = "not found under Deck/ or Data/Windbot/Decks/: " + path;
return false;
}
internal static void Log(string message) => Console.Error.WriteLine(LogPrefix + message);
}
/// The editor arena's report plus what only a parallel run knows.
/// (JsonProperty Order keeps the two extra fields AFTER the shared ones,
/// so a report diff against Data/BotArena/*.json is append-only.)
public class StandaloneArenaResult : ArenaResult
{
[JsonProperty(Order = 1)] public int workers;
[JsonProperty(Order = 1)] public float wallClockSeconds;
}
// ----------------------------------------------------------------------
// Worker process handle (parent side)
// ----------------------------------------------------------------------
internal sealed class WorkerHandle
{
// Per-run folder (pid-stamped) so concurrent arena runs never share a worker-N.log
// (a shared name made a second run fail to open the log while another was live).
public static string LogDir = Path.Combine(ArenaReport.OutputDir, "logs",
"run-" + DateTime.Now.ToString("yyyyMMdd-HHmmss") + "-" + Environment.ProcessId);
public int Index { get; }
public int Port { get; }
/// 0 for the first process on this seat, +1 per replacement.
public int Generation { get; }
public int Busy; // duel index in flight, 0 = idle
public volatile bool Ready; // worker finished loading and said so
public bool Retired; // death already handled by the parent
public Action<DuelRecord> OnRecord;
private readonly Options opts;
private readonly ArenaResult result;
private readonly int port;
private Process process;
private StreamWriter log;
public WorkerHandle(int index, Options opts, ArenaResult result, int port, int generation)
{
Index = index;
Port = port;
Generation = generation;
this.opts = opts;
this.result = result;
this.port = port;
}
public bool Alive => process != null && !process.HasExited;
public void Start()
{
Directory.CreateDirectory(LogDir);
var logName = "worker-" + Index + (Generation > 0 ? "-r" + Generation : string.Empty) + ".log";
log = new StreamWriter(Path.Combine(LogDir, logName), false, new UTF8Encoding(false)) { AutoFlush = true };
var psi = new ProcessStartInfo
{
FileName = Environment.ProcessPath ?? Process.GetCurrentProcess().MainModule.FileName,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
WorkingDirectory = opts.root,
StandardOutputEncoding = new UTF8Encoding(false),
StandardErrorEncoding = new UTF8Encoding(false),
};
// ArgumentList quotes for us — the commands carry Name="…" tokens.
var a = psi.ArgumentList;
a.Add("--worker"); a.Add(Index.ToString());
a.Add("--root"); a.Add(opts.root);
a.Add("--port"); a.Add(port.ToString());
a.Add("--nameA"); a.Add(result.nameA);
a.Add("--nameB"); a.Add(result.nameB);
a.Add("--commandA"); a.Add(result.commandA);
a.Add("--commandB"); a.Add(result.commandB);
a.Add("--seed"); a.Add(opts.seed.ToString());
a.Add("--timeout"); a.Add(opts.timeoutSeconds.ToString());
a.Add("--locale"); a.Add(opts.locale);
a.Add("--host"); a.Add(opts.hostMode);
if (opts.verbose) a.Add("--verbose");
if (!string.IsNullOrEmpty(opts.replaysDir)) { a.Add("--replays"); a.Add(opts.replaysDir); }
if (!string.IsNullOrEmpty(opts.journalDir)) { a.Add("--journal"); a.Add(opts.journalDir); }
if (opts.insightA.HasValue) { a.Add("--insightA"); a.Add(Insight.LevelName(opts.insightA.Value)); }
if (opts.insightB.HasValue) { a.Add("--insightB"); a.Add(Insight.LevelName(opts.insightB.Value)); }
if (opts.knobsA != null) { a.Add("--knobsA"); a.Add(Options.FormatKnobs(opts.knobsA)); }
if (opts.knobsB != null) { a.Add("--knobsB"); a.Add(Options.FormatKnobs(opts.knobsB)); }
process = new Process { StartInfo = psi, EnableRaisingEvents = true };
process.OutputDataReceived += (_, e) => { if (e.Data != null) OnLine(e.Data); };
process.ErrorDataReceived += (_, e) => { if (e.Data != null) log.WriteLine(e.Data); };
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
}
private void OnLine(string line)
{
// Anything not JSON is the native server's own printf (it prints the
// port it bound) or stray chatter — log it, don't parse it.
if (line.Length == 0 || line[0] != '{') { log.WriteLine("[stdout] " + line); return; }
WorkerMessage msg;
try { msg = JsonConvert.DeserializeObject<WorkerMessage>(line); }
catch (Exception e) { log.WriteLine("[stdout?] " + line + " (" + e.Message + ")"); return; }
if (msg == null) return;
switch (msg.type)
{
case "ready": Ready = true; break;
case "duel": if (msg.record != null) OnRecord?.Invoke(msg.record); break;
case "fatal": log.WriteLine("[fatal] " + msg.error); Program.Log("worker " + Index + " failed: " + msg.error); break;
default: log.WriteLine("[stdout] " + line); break;
}
}
public void Assign(int duelIndex)
{
Busy = duelIndex;
try { process.StandardInput.WriteLine(duelIndex.ToString()); process.StandardInput.Flush(); }
catch (Exception e) { log.WriteLine("[parent] could not assign duel " + duelIndex + ": " + e.Message); }
}
public void Quit()
{
try { if (Alive) { process.StandardInput.WriteLine("quit"); process.StandardInput.Flush(); } } catch { }
try { if (process != null && !process.WaitForExit(5000)) process.Kill(true); } catch { }
}
public void Kill()
{
try { if (Alive) process.Kill(true); } catch { }
try { log?.Dispose(); } catch { }
}
}
/// One stdout line from a worker.
public class WorkerMessage
{
public string type; // ready | duel | fatal
public DuelRecord record;
public string error;
}
// ----------------------------------------------------------------------
// CLI
// ----------------------------------------------------------------------
internal sealed class Options
{
public const string Usage = @"BotArena — headless, parallel bot-vs-bot duels (no Unity).
BotArena --deckA ""group/name"" --deckB ""group/name"" [options]
Decks are Deck/ paths without .ydk (root-group decks are just ""name"");
Data/Windbot/Decks/ names work too. The DECK decides the brain (the owning
character in Data/Characters/); --execA/--execB force a WindBot executor.
Options:
--root <dir> game/repo root (Deck/, Data/, Expansions/ live here). Default: cwd
--execA <name> WindBot Deck= override for seat A (Smart, Lucky, ...). Default: the deck's own
--execB <name> same for seat B
--n <count> duels to play. Default 10
--parallel <k> worker processes (one server + two bots each). Default 1
--seed <int> base of the per-duel SmartExecutor noise seed (0 = brains seed themselves)
--timeout <sec> per-duel timeout. Default 300
--out <file> extra copy of the JSON report (canonical copy: Data/BotArena/)
--replays <dir> save every duel's .yrp there
--journal <dir> SmartExecutor decision journal: <dir>/duel-<n>-<A|B>.jsonl per Smart seat + run.json
(feed the dir to .claude/skills/bot-brain/blunders.py)
--port <base> first server port (workers take base, base+4, ...). Default 7920
--locale <lang> Data/locales/<lang>/ for cards.cdb + bot.conf. Default en-US
--verbose keep [YGOL bot] decision logging (goes to Data/BotArena/logs/run-<stamp>-<pid>/worker-N.log)
--insightA <lvl> duel state bus insight for seat A: none | hand | full (TICKET-042).
Overrides that deck brain's `insight` knob. Default: the knob (none)
--insightB <lvl> same for seat B
--host local|server in-process core (default) or the engine's server over TCP (TICKET-045)
--knobsA <list> per-seat SmartExecutor knob overrides for seat A, applied ON TOP of the
deck brain's knobs: ""name=value,name=value"" (e.g. ""lookahead=8,lookaheadTurns=6"").
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
-h, --help
Exit codes: 0 = at least one duel played, 1 = none played, 2 = bad arguments.";
public bool help;
public string root = Directory.GetCurrentDirectory();
public string deckA, deckB, execA, execB;
public int n = 10;
public int parallel = 1;
public int seed;
public int timeoutSeconds = 300;
public string outPath;
public string replaysDir;
public string journalDir;
public int portBase = 7920;
public string locale = "en-US";
public bool verbose;
/// TICKET-045: "local" = YGOLegacy.Bot.LocalDuelHost drives the engine's core
/// in this process (no server, no sockets); "server" = the original
/// start_server path, kept for A/B comparisons.
public string hostMode = "local";
/// TICKET-042 per-seat insight override; null = the deck brain decides.
public InsightLevel? insightA, insightB;
/// TICKET-050 per-seat knob overrides (--knobsA/--knobsB); null = none.
public Dictionary<string, float> knobsA, knobsB;
/// <summary>TICKET-050: does this seat's override switch lookahead on?</summary>
public bool LookaheadOn(Dictionary<string, float> knobs)
=> knobs != null && knobs.TryGetValue("lookahead", out var v) && v > 0f && hostMode == "local";
/// <summary>"a=1,b=2" -> a dictionary; empty/null -> null.</summary>
public static Dictionary<string, float> ParseKnobs(string flag, string value)
{
if (string.IsNullOrWhiteSpace(value)) return null;
var map = new Dictionary<string, float>(StringComparer.Ordinal);
foreach (var part in value.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
{
var eq = part.IndexOf('=');
if (eq <= 0) throw new ArgumentException(flag + " expects name=value pairs, got '" + part.Trim() + "'");
var name = part.Substring(0, eq).Trim();
if (!float.TryParse(part.Substring(eq + 1).Trim(), System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out var v))
throw new ArgumentException(flag + ": '" + part.Trim() + "' is not a number");
map[name] = v;
}
return map.Count == 0 ? null : map;
}
/// <summary>Round-trip form for the worker command line.</summary>
public static string FormatKnobs(Dictionary<string, float> knobs)
{
if (knobs == null || knobs.Count == 0) return string.Empty;
var parts = new List<string>(knobs.Count);
foreach (var kv in knobs)
parts.Add(kv.Key + "=" + kv.Value.ToString(System.Globalization.CultureInfo.InvariantCulture));
return string.Join(",", parts);
}
// worker-only
public bool worker;
public int workerIndex;
public int port;
public string nameA, nameB, commandA, commandB;
public ArenaConfig ToConfig() => new()
{
deckA = deckA, deckB = deckB, executorA = execA ?? string.Empty, executorB = execB ?? string.Empty,
n = n, seed = seed, timeoutSeconds = timeoutSeconds, verboseBots = verbose, outPath = outPath ?? string.Empty,
journalDir = journalDir ?? string.Empty,
insightA = insightA.HasValue ? Insight.LevelName(insightA.Value) : string.Empty,
insightB = insightB.HasValue ? Insight.LevelName(insightB.Value) : string.Empty,
hostMode = hostMode,
};
private static InsightLevel ParseInsight(string flag, string value)
{
if (!Insight.TryParseLevel(value, out var level))
throw new ArgumentException(flag + " expects none|hand|full, got '" + value + "'");
return level;
}
public static Options Parse(string[] args)
{
var o = new Options();
for (var i = 0; i < args.Length; i++)
{
var a = args[i];
string Next()
{
if (i + 1 >= args.Length) throw new ArgumentException(a + " needs a value");
return args[++i];
}
int NextInt()
{
var v = Next();
if (!int.TryParse(v, NumberStyles.Integer, CultureInfo.InvariantCulture, out var n)) throw new ArgumentException(a + " expects an integer, got '" + v + "'");
return n;
}
switch (a)
{
case "-h": case "--help": case "/?": o.help = true; break;
case "--root": o.root = Next(); break;
case "--deckA": o.deckA = Next(); break;
case "--deckB": o.deckB = Next(); break;
case "--execA": o.execA = Next(); break;
case "--execB": o.execB = Next(); break;
case "--n": o.n = NextInt(); break;
case "--parallel": o.parallel = NextInt(); break;
case "--seed": o.seed = NextInt(); break;
case "--timeout": o.timeoutSeconds = NextInt(); break;
case "--out": o.outPath = Next(); break;
case "--replays": o.replaysDir = Next(); break;
case "--journal": o.journalDir = Next(); break;
case "--port": o.portBase = NextInt(); break;
case "--locale": o.locale = Next(); break;
case "--verbose": o.verbose = true; break;
case "--host": o.hostMode = Next().Trim().ToLowerInvariant(); break;
case "--insightA": o.insightA = ParseInsight(a, Next()); break;
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 "--worker": o.worker = true; o.workerIndex = NextInt(); break;
case "--nameA": o.nameA = Next(); break;
case "--nameB": o.nameB = Next(); break;
case "--commandA": o.commandA = Next(); break;
case "--commandB": o.commandB = Next(); break;
default: throw new ArgumentException("unknown argument '" + a + "'");
}
}
if (o.help) return o;
o.root = Path.GetFullPath(o.root);
if (!Directory.Exists(o.root)) throw new ArgumentException("--root does not exist: " + o.root);
if (o.hostMode != "local" && o.hostMode != "server") throw new ArgumentException("--host expects local|server, got '" + o.hostMode + "'");
if (o.worker)
{
o.port = o.portBase;
if (string.IsNullOrEmpty(o.commandA) || string.IsNullOrEmpty(o.commandB)) throw new ArgumentException("worker needs --commandA/--commandB");
if (!string.IsNullOrEmpty(o.journalDir)) o.journalDir = Path.GetFullPath(o.journalDir);
return o;
}
if (string.IsNullOrEmpty(o.deckA)) throw new ArgumentException("--deckA is required");
if (string.IsNullOrEmpty(o.deckB)) throw new ArgumentException("--deckB is required");
if (o.n < 0) throw new ArgumentException("--n must be >= 0");
if (o.parallel < 1) throw new ArgumentException("--parallel must be >= 1");
if (o.timeoutSeconds < 10) throw new ArgumentException("--timeout must be >= 10");
if (o.portBase < 1024 || o.portBase > 60000) throw new ArgumentException("--port must be in 1024..60000");
if (o.hostMode != "local" && o.hostMode != "server") throw new ArgumentException("--host expects local|server, got '" + o.hostMode + "'");
if (!string.IsNullOrEmpty(o.replaysDir)) o.replaysDir = Path.GetFullPath(o.replaysDir);
if (!string.IsNullOrEmpty(o.journalDir)) o.journalDir = Path.GetFullPath(o.journalDir);
if (!string.IsNullOrEmpty(o.outPath)) o.outPath = Path.GetFullPath(o.outPath);
return o;
}
}
}
+365
View File
@@ -0,0 +1,365 @@
# BotArena — standalone, parallel bot-vs-bot duels (TICKET-035)
Runs hundreds (thousands) of WindBot-vs-WindBot duels from a terminal with **no
Unity in the loop**, using exactly the code the game ships: the in-tree WindBot,
the fork's SmartExecutor brain, the character registry and the game's own
`ocgcore.dll`. Same JSON report as the in-editor Bot Arena (TICKET-030), so
anything that reads `Data/BotArena/*.json` reads either.
Two duel hosts, `--host local` (the default) and `--host server`:
| | `local` (TICKET-045) | `server` (TICKET-035) |
|---|---|---|
| what runs the duel | `YGOLegacy.Bot.LocalDuelHost` — ocgcore.dll driven from this process | `ygoserver.dll`, one room per worker |
| transport | none: a loopback seam into `BinaryClient` | TCP on 127.0.0.1 |
| threads per worker | one (host + both bots + both brains) | four (server, two bots, the worker) |
| 1000 Weevil duels, 8 workers | **~20 s** (10–40 ms per duel) | ~4 min (~1.6 s per duel) |
| `--replays` | not available (no STOC_REPLAY) | yes |
Measured on the dev machine: **1000 Weevil-vs-Weevil duels, 8 workers, 33 s wall
clock with journals on, 0 errors** (`--host local --n 1000 --parallel 8`). The
same run on `--host server` takes ~4 minutes; the editor arena needs 10–25 s per
duel, serially. Almost all of the old cost was transport — WindBot's 500 ms
end-of-duel pause, the per-duel server start/stop, and the bot threads polling
their sockets — none of which the in-process host has.
## Build
```
dotnet build Tools/BotArena # dev machine or the CI runner (dotnet 8 SDK)
```
Output: `Tools/BotArena/bin/Debug/net8.0/win-x64/BotArena.exe` (gitignored).
Windows only, like the game (ygoserver.dll is a Windows plugin).
Sources are **linked**, not copied — see `BotArena.csproj`. There is nothing
to sync: change `SmartExecutor.cs` in the Unity project, rebuild, run.
## Run
```
BotArena --deckA "Duelist Kingdom/Weevil Underwood DK" ^
--deckB "Duelist Kingdom/Weevil Underwood DK" ^
--execA Smart --execB Lucky --n 100 --parallel 8 --seed 1 ^
--out C:\tmp\arena.json
```
Run it from the repo root, or pass `--root <repo>` (`Deck/`, `Data/`,
`Expansions/`, `Assets/Plugins/Windows/ygol-engine.dll` are resolved under it;
the working directory of every worker IS the root, because ygoserver reads
`./expansions`, `./script` and writes `./replay`, `./error.log` there).
| Option | Meaning |
|---|---|
| `--deckA/--deckB "group/name"` | Deck/ path without `.ydk` (root-group decks: just `name`); `Data/Windbot/Decks/` names work too. Required. |
| `--execA/--execB Smart\|Lucky\|…` | force the seat's WindBot executor (rewrites the `Deck=` token). Default: the deck's own brain (the owning character's `brain.executor`, else Dovphin/Lucky). |
| `--n 200` | duels (default 10) |
| `--parallel 8` | worker processes (default 1) |
| `--seed 1` | base of every per-duel seed. Each Smart seat gets `seed*1000 + duel*2 + seat` for its decision noise; the duel itself (deck shuffle, `create_duel`, WindBot's `Program.Rand`) gets `ArenaReport.CoreSeedFor` = `(seed*7919 + duel*104729) & 0x7fffffff \| 1`. Both depend on the duel INDEX only, so `--host local` replays the same duels for the same command line — see "Repeatability" below. `0` = nothing is seeded (brains seed themselves, the run is not repeatable). |
| `--timeout 300` | per-duel timeout in seconds |
| `--out file.json` | extra copy of the report (the canonical one always lands in `Data/BotArena/`) |
| `--replays dir` | save every duel's `.yrp` as `duel-0001.yrp`, … **`--host server` only** — the in-process host is not a ygoserver and never sends STOC_REPLAY, so a `local` run warns and writes nothing. |
| `--journal dir` | SmartExecutor decision journal (TICKET-036): `duel-0001-A.jsonl` per **Smart** seat (Lucky seats write nothing) + `run.json` (the run's config and seat commands). Feed the dir to `python .claude/skills/bot-brain/blunders.py <dir>`. Kinds are listed at the top of the journal region in `SmartExecutor.cs`; 2026-08-18 added `flipHeld` (a Flip Summon the executor chose NOT to take, with its reason — deduped per card + turn) and the `positionWhy: "flip default set"` value on `summon`/`set` lines, plus `positionWhy: "flip from hand beats weak body"` when a weak face-up summon was held so a FLIP monster could be Set instead. |
| `--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). |
| `--host local\|server` | which duel host plays the duels. `local` (default) = ocgcore in-process (TICKET-045); `server` = ygoserver.dll over a TCP loopback, kept for A/B. |
| `--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. |
Exit codes: **0** at least one duel played, **1** none played (bad deck, no
worker could start, …), **2** bad arguments. The one-line summary is printed
last (`Weevil A 56 - 44 Weevil B (0 errors, avg 12.8 turns, 0m54s) -> Data/BotArena/…json`);
progress lines go to stderr.
Per-worker logs (WindBot chatter, `[YGOL bot]` lines, ygoserver's own output)
land in `Data/BotArena/logs/run-<stamp>-<pid>/worker-N.log` (one folder per run, so concurrent runs are safe; `-rK` suffix for a respawned worker).
### Report
`Data/BotArena/<yyyyMMdd-HHmmss>-<deckA>-vs-<deckB>.json`, the editor arena's
schema exactly (`config`, `nameA/B`, `commandA/B`, `winsA/B`, `draws`,
`errors`, `completed`, `totalSeconds`, `averageTurns`, `summary`, `status`,
`duels[]` with `winner`, `winnerName`, `turns`, `durationSeconds`, `error`,
`verdictA/B`, `seedA/B`, `Played`) plus two trailing fields: `workers` and
`wallClockSeconds`. `totalSeconds` is the run's wall clock too;
`durationSeconds` per duel is that duel's own clock (server start → teardown).
The model and the helpers that fill it (`Summary`, `SeatCommand`, `Resolve`,
`Tally`) are ONE file shared with the game:
`Assets/YGOLegacy/Scripts/Bot/ArenaReport.cs`.
## How it works
```
BotArena.exe (parent)
├─ validates decks the way WindBot's Program.ReadFile resolves DeckFile=
├─ CharacterRegistry.LoadFromDisk + Data/locales/<lang>/bot.conf → BotRoster.ForDeck
│ → seat names "<name> A"/"<name> B" + WindBot commands (ArenaReport.SeatCommand)
├─ spawns --parallel copies of ITSELF with --worker k (ProcessStartInfo.ArgumentList)
├─ hands each idle worker one duel index over stdin (dynamic scheduling)
├─ reads one JSON line per duel from the worker's stdout, tallies, prints progress
├─ a dead worker's duel is re-queued once and a replacement worker is started
└─ writes the report, prints the summary, kills what is left (try/finally)
BotArena.exe --worker k (one duel at a time)
├─ cwd = root
├─ once: characters, bot.conf, WindBot.Program.InitDatas (cards.cdb + every .cdb
│ inside Expansions/*.ypk, extracted to %TEMP%/YGOLBotArena/cdb/, + Expansions/*.cdb),
│ then per --host: LocalHost.Install (ocgcore.dll + readers) or YgoServer.Locate
└─ per duel: Worker.RunOneLocal / Worker.RunOneServer (below)
→ ArenaReport.Resolve → {"type":"duel","record":{…}} on stdout
```
**`--host local` (`Worker.RunOneLocal`)** — one thread, no server, no sockets:
```
1. two seats, built strictly one after the other (WindBot.Config and the
SmartExecutor seed/journal statics are process-global and are consumed inside
the GameBehavior constructor):
Bot.PrepareInfo(command) → new GameClient(info) → new LoopbackBotSeat(...)
LoopbackBotSeat calls the [YGOL] GameClient.YGOL_StartLoopback: same
GameBehavior, same SmartExecutor, same DuelStateBus tap — but Send() lands in
an outbox instead of a socket and the host injects STOC packets directly.
2. WindBot.Game.Deck.Load for each seat (the same list the bot uploads).
3. YGOLegacy.Bot.LocalDuelHost.Run():
room handshake (JoinGame → TypeChange → HsPlayerEnter/Change → RPS/TP →
DuelStart) so _room.Position / _room.Names / Duel.IsFirst are right
create_duel → set_player_info ×2 → shuffled new_card ×N → MSG_START →
start_duel(opt 0x50000 = master rule 5) → loop process()/get_message():
split the batch into messages, route each one (broadcast / one player /
prompt), blank what that recipient may not see, inject, let the seat
answer inside its own packet handler, set_responseb.
4. the verdict is the usual GameBehavior.YGOL_DuelResult from MSG_WIN.
```
**`--host server` (`Worker.RunOneServer`)** — the TICKET-035 path, unchanged:
```
1. free port from base → start_server("<port> -1 5 0 F F F 8000 5 1 180 0") on a
thread (identical args to MultiplayerService.HostLocal); wait until it accepts
2. bot A: Config.Load(args) → GameClient(...).Start() on the worker thread (so the
process-global WindBot.Config, SmartExecutor.SeedOverride and SmartExecutor.JournalPath
are consumed before B's), tick loop on its own thread; wait for the socket; then bot B
the same way
3. both bots auto-ready, the host bot sends HsStart; wait for both YGOL_DuelResult
verdicts (or one + 5 s, or both sockets/server gone + 3 s, or --timeout)
4. teardown: let the server leave on its own (it stops itself after DuelEnd),
stop_server() only if it is still up, join the bot threads
```
Why processes and not threads: `WindBot.Config`, `WindBot.Program.Rand`,
`NamedCardsManager` and `SmartExecutor.SeedOverride` are process-wide statics
(that is also why the editor arena is serial). Why the server is not an exe:
the game's ygoserver is a DLL (`MDPro3.Net.YgoServer` P/Invokes
`start_server`/`stop_server`); we do the same, so a worker's exit takes its
server with it — there is no orphan `ygoserver` process to kill.
### Duel state bus (TICKET-042)
Both bots are `GameClient`s in this process, so the `[YGOL]` tap in
`GameClient.OnPacketReceived` publishes each seat's raw packets to
`YGOLegacy.Bot.DuelStateBus` (linked into this project), which mirrors them with
WindBot's own parser. That is how `--insightA/--insightB` can hand a brain the
other seat's hand. The bus is **off** until a brain resolves an insight level
above `none`, and the worker calls `DuelStateBus.Reset()` before every duel, so a
normal measurement run allocates nothing extra and behaves byte-for-byte as before.
### The in-process host (TICKET-045)
`YGOLegacy.Bot.LocalDuelHost` (`Assets/YGOLegacy/Scripts/Bot/`, Unity-free, also
compiled by the game) is ygoserver's duel loop rewritten in C# for exactly two
seats and one duel, and `LoopbackBotSeat` is the WindBot adapter. Both are
linked, not copied.
* **Where the byte layouts come from.** `Percy.Ygopro.Analyse`
(`Assets/Scripts/MDPro3/Duel/CoreWrapper.cs`) is the fork's own single-seat
host and already encodes the length of every `MSG_*` and how to blank hidden
information; `LocalDuelHost.Scan` is that switch, message for message, plus
the ones a single-seat client never sees. An unknown message id throws rather
than desyncing the batch — the duel is recorded as an error and the id is
named in it.
* **What each seat is allowed to see.** Prompts (`SELECT_*`, `ANNOUNCE_*`,
`SORT_*`, `ROCK_PAPER_SCISSORS`) go to one player and block; `MSG_HINT` types
1/2/3/5 go to the hinted player, the rest is public; everything else is
broadcast. Blanked: `MSG_DRAW` and `MSG_SHUFFLE_HAND`/`SHUFFLE_EXTRA` (codes
to the owner, zeros to the opponent), `MSG_SET` (code to nobody) and
`MSG_MOVE` (a card that lands in a deck/hand or face-down keeps its code for
its NEW CONTROLLER and loses it for the other seat — you know the monster you
just set). Refreshes (`MSG_UPDATE_DATA`) re-query every zone for both players:
face-down monsters/spells collapse to an empty record for the opponent, hands
and extra decks lose their codes.
* **Card data** is not read a second time: WindBot's `NamedCardsManager` is
already loaded with the same cdbs in the same order, and
`YGOSharp.OCGWrapper.Card.Data` is that row in ocgcore's `card_data` shape, so
the core and the brains cannot disagree about a card
(`LocalHost.ReadCard`). **Scripts** resolve in the game's order
(`LocalHost.ReadScript`): loose `Expansions/script/`, then the `script/`
entries of each `Expansions/*.ypk|*.zip`, then `Data/script.zip` — which is
what keeps the loose `Expansions/script/procedure.lua` override in charge.
* **Duel options** are `0x50000` (master rule 5, LP 8000, 5 cards, draw 1),
read off a real ygoserver duel's replay header, not guessed.
* **Two `[YGOL]` seams**, both additive: `BinaryClient.{YGOL_SendHook,
YGOL_Inject,YGOL_MarkConnected}` and `GameClient.{YGOL_StartLoopback,
YGOL_Receive}`. Everything else — `GameBehavior`, `SmartExecutor`, the
journal, `DuelStateBus`, `YGOL_DuelResult`, `YGOL_Replay` — is untouched, and
the injected packets go through `OnPacketReceived`, so the bus taps still see
them.
* **Not covered**: tag duels (`MSG_TAG_SWAP`), `MSG_RELOAD_FIELD` (puzzles),
match/side decking, spectators, replays. Those throw or are absent; single
duels never produce them.
### Rollout lookahead (TICKET-050, prototype)
`--knobsA "lookahead=N"` switches a Smart seat from "answer the idle prompt with
the executor list's first preference" to "enumerate the executor's top
`lookaheadCandidates` (default 4) preferences, play each of them out `N` times,
and blend the rollout win rate into the choice". It is **off by default and off
in the game**: the knob does nothing without an `ILookaheadOracle`, and the only
implementation of that interface is `Tools/BotArena/ReplayOracle.cs`.
How a rollout is possible at all: ocgcore cannot clone a live duel, but this
arena's per-duel seed drives BOTH `create_duel` and the host's own deck shuffle,
so a fresh `LocalDuelHost` with the same seed deals the identical game. The
oracle replays every answer both seats have given so far
(`LocalDuelHost.Options.ScriptedResponses`, recorded by `RecordResponses`),
imposes the same turn order (`ForcedFirstSeat` — rock-paper-scissors is answered
from WindBot's RNG, not from the response log), answers the prompt under test
with the candidate, and lets two Lucky bots play on to
`StopAfterTurn = turn + lookaheadTurns`.
**It peeks.** The copy is dealt from the same shuffle, so the rollouts see the
enemy's hand and both deck orders. That is the point: it measures the CEILING of
rollout planning on this engine. A shippable version would have to rebuild the
public state and sample the hidden part instead (Phase B in the ticket).
Knobs (all read once, at executor construction):
| knob | default | meaning |
|---|---|---|
| `lookahead` | 0 | rollouts per candidate; 0 = off, and the whole feature is inert |
| `lookaheadCandidates` | 4 | how many of the executor's own preferences to consider |
| `lookaheadTurns` | 6 | horizon; 0 = play every rollout to MSG_WIN |
| `lookaheadWeight` | 1.0 | `score += weight * (winRate - 0.5) * 2000` |
| `lookaheadRankPoints` | 300 | what one place of the executor's own preference order is worth, since the walk yields an ORDER and not a score |
| `lookaheadMs` | 1500 | wall-clock ceiling per decision (all candidates together) |
Cost, measured on Weevil DK: a plain duel is ~6 ms; at `lookahead=8` it is
~14 s of CPU (one rollout ≈ 21 ms, ~20 planned decisions per duel, up to 32
rollouts each). `--verbose` prints one `lookahead:` line per planned decision
with every candidate's rollout value and blended score, and the worker log gets a
`lookahead seat A duel N: R rollouts, X abandoned, T ms` summary per duel.
The two seams this needed, both `[YGOL]`-tagged and both inert without a planner:
`GameAI.OnSelectIdleCmd` now delegates to `YGOL_WalkIdle(main, allow)` (its own
original body plus an "is this action allowed" predicate checked where it used to
`return`), and `SmartExecutor` implements `YGOLegacy.Bot.IIdlePlanner`.
Verified: `Weevil DK Smart vs Lucky --seed 7 --n 1000` gives 654-346 and
`avg 12.924` turns both before and after the change, with **0 of 1000 duels
differing**.
### Differences from the editor arena
* No observer/spectator client, no duel scene, no replay auto-save by the game;
the bots' own MSG_WIN (`GameBehavior.YGOL_DuelResult`) is the whole verdict.
Turn count = max of the two verdicts' turns (no `OcgCore.turns` backstop).
* `.yrp` files come from `GameBehavior.YGOL_Replay` (STOC_REPLAY as the server
sent it to the players), only with `--replays` and only on `--host server`.
* On `--host server` the bots tick on their own threads (1 ms, adaptive); on
`--host local` there are no bot threads at all — the host ticks each client
inline and the answer is in the outbox when the tick returns.
* Card databases: WindBot's `InitDatas` is run ONCE per worker, not once per
bot as `WindBot.Program.Main` would.
## Shims and exclusions (`Shims/`, `BotArena.csproj`)
| Shim | Stands in for | Why |
|---|---|---|
| `Shims/UnityEngine.Debug.cs` | `UnityEngine.Debug.Log/LogWarning/LogError/LogException` | SmartExecutor and CharacterRegistry log through it. Routed to stderr (→ worker log). |
| `Shims/MDPro3.cs` — `MDPro3.Program.PATH_EXPANSIONS`, `MDPro3.IO.ResourceManager.GetAllCdbInZipPaths`, `MDPro3.Utility.Language.GetConfig`, `MDPro3.Servant.SoloSelector.{BotInfo,bots}` | the four MDPro3 statics `WindBot/Program.cs` (InitDatas) and `BotRoster.cs` (Dovphin's bot.conf line) touch | data holders the tool fills in; the game's classes drag in Unity |
| `Shims/MonoDataSqlite.cs` — `Mono.Data.Sqlite.SqliteConnection/SqliteCommand` | Unity's Mono.Data.Sqlite used by `NamedCardsManager`/`CardsManager` | thin subclasses of `Microsoft.Data.Sqlite` (NuGet), opened read-only/shared |
| NuGet `Newtonsoft.Json` | Unity's Newtonsoft package | `Character.cs`, `BrainRules.cs`, the report |
| define `YGOL_STANDALONE` | — | `CharacterRegistry.cs` compiles its UniTask surface (`Loaded`, `Init`) out; the tool uses `LoadFromDisk` |
Excluded from the link, each documented in the csproj: `Windbot/BotWrapper.cs`
(unused upstream stub with a second `Main`); YGOSharp `Api.cs`/`Duel.cs`/
`MtRandom.cs` and the `YGOSharp/` + `Async*`/`NetworkServer` files (ocgcore
P/Invoke and the server side — WindBot only needs the client, the card
managers and the enums); `Bot/BotArena.cs` (the editor runner: UniTask,
OcgCore, TcpHelper).
Shared-source changes made for this tool (all still compile in Unity):
`ArenaReport.cs` (new, model + helpers extracted from `BotArena.cs`, plus
`ArenaConfig.hostMode` and `DuelRecord.coreMs`),
`CharacterRegistry.LoadFromDisk` + `#if !YGOL_STANDALONE`, the `[YGOL]`
`GameBehavior.YGOL_Replay` event, and (TICKET-045) the loopback seams
`BinaryClient.{YGOL_SendHook,YGOL_Inject,YGOL_MarkConnected}` +
`GameClient.{YGOL_StartLoopback,YGOL_Receive}`.
## Caveats
* **Repeatability: `--host local` with `--seed N` (N ≠ 0) is deterministic; one
run is still one sample.** Three streams used to be unseeded and are now all
derived from (`--seed`, duel index) — the host's own deck shuffle and
ocgcore's `create_duel(seed)` (`LocalDuelHost.Options.Seed`), and WindBot's
process-global `Program.Rand`, reseeded before every duel (rock-paper-scissors,
`LuckyExecutor`'s coin flips, every `Rand.Next` inside a deck executor). The
index, not the worker, is the input, so `--parallel 1` and `--parallel 8` give
the same duels. Verified 2026-08-16: two back-to-back `--n 300 --seed 7` runs
on Weevil DK, and a third at `--parallel 7`, all `187 - 113`, `avg 13.177`
turns, identical winner and turn count for every duel index; and 2 × 500 duels
on each of Weevil DK, Yuma Zxl, Alister ORI, Modern/Pegasus, Yugi BC and Zane
GX — **0 differing duels out of 500** on all six.
**One known exception, and it is not the seeding.** `Zexal/Kite Tenjo Zxl`
diverges in 3–5 duels per 500 (~0.8 %), at `--parallel 1` as much as at
`--parallel 4`, so it is not scheduling and not cross-duel leakage: it is
address-space dependent behaviour below us (ocgcore.dll iterates some
containers of pointers, and heap addresses move with ASLR). The same deck is
the only one of the seven that also throws a `NullReferenceException` mid-duel
(4 duels per 500) — the errored duel indices ARE stable across runs, so the
two are separate. Practical effect: on such a deck a pooled 2000-duel figure
can wobble by ~2 duels (0.1 points). If a deck's A/B refuses to reproduce,
check its `errors` count before blaming the change.
What this buys is a **paired A/B**: two binaries (or two brain.json files) on
the same seed face the identical openings, so the difference between them is
the change. What it does not buy is a smaller error bar on a single number —
1000 duels are still one draw, so the deck's true win rate still carries the
usual ±3 points at `--n 1000`. Use a **second seed** to see that spread and
quote the pooled figure (sum `winsA` and `completed` across the reports);
before the fix the same command line gave **63.0 % and 68.0 %** on Weevil DK.
`--seed 0` pins nothing and is not repeatable, as before. `--host server` is
never repeatable: `ygoserver.dll` shuffles the decks itself with a seed this
process cannot reach (the per-duel `Program.Rand` reseed still happens there,
so at least no state leaks from the previous duel).
* **A duel that ends in `error` is not measured — check `errors` before trusting a
deck's number.** Three shapes, all seen:
* **MSG_RETRY** (the core rejected a bot's answer). The message NAMES what was
rejected — `prompt 11 SELECT_IDLECMD, seat 0, answer 07 00 00 00 (int32 7 =
idle command ToEndPhase index 0)` — because `LocalDuelHost` records the last
prompt and the last answer and reads them back before handing the packet to
the seat (WindBot's own `OnRetry` throws first otherwise, and its
"Last message is SelectIdleCmd" says nothing about WHICH command). That is
how the one known instance was found and fixed (`GameAI.OnSelectIdleCmd`
answered `ToEndPhase` without checking `CanEndPhase`): `Orichalcos/Leon
Wilson ORI` went from 85-86 errors per 1000 to **0**.
* **`turn limit reached (200)`** — a handful of boards never resolve. About
3-5 % on `5Ds/Misty Tredwell 5Ds` and `Zexal/Quattro Zxl`; expected, see
`LocalDuelHost.Options.TurnLimit`.
* **`message limit reached`** — a prompt the core keeps re-asking.
**`Orichalcos/Valon ORI` hits this in 171 of 200 duels** (measured
2026-08-16), so that deck cannot currently be measured at all. Not
diagnosed; the first step is a `--verbose` run of one failing duel index.
* `Deck/`, `Expansions/`, `Puzzle/` are junctions into the Syncthing share —
the tool only READS them. Reports go to `Data/BotArena/`, replays wherever
`--replays` says, the cdb cache to `%TEMP%`.
* ygoserver.dll writes `error.log` and `replay/` in the root, as the game does
(`--host server` only; the in-process host writes nothing outside
`Data/BotArena/`).
* Both hosts use the same process-global statics, so it is still ONE duel per
worker process — including ocgcore's `set_card_reader`/`set_script_reader`,
which are installed once per worker.
* `--host server` only: very rarely the DLL aborts a worker on teardown (a libevent assertion when a
`stop_server` races the server's own post-duel shutdown). The parent
re-queues that duel and starts a replacement worker, so the run still
completes; the crash is visible in the worker log.
* One `.yrp` per duel is 0.5–1 KB (LZMA); the server caps the buffer it sends
at 8 KB, so an extremely long duel's replay may be truncated by the server.
+207
View File
@@ -0,0 +1,207 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using YGOLegacy.Bot;
namespace YGOLegacy.Tools.BotArena
{
/// <summary>
/// TICKET-050 — the PERFECT-INFORMATION rollout oracle (Phase A).
///
/// ocgcore cannot clone a live duel, so the only way to get a "future" out
/// of one is to build a second duel that IS this one and then diverge:
///
/// * the in-process host seeds ocgcore's <c>create_duel</c> AND its own
/// deck shuffle from one number (<c>ArenaReport.CoreSeedFor</c>), so a
/// fresh host with the same seed and the same two deck lists deals the
/// identical game;
/// * <see cref="LocalDuelHost.Options.ForcedFirstSeat"/> imposes the turn
/// order the real duel rolled for (rock-paper-scissors is answered from
/// WindBot's RNG, which the response log does not cover);
/// * <see cref="LocalDuelHost.Options.ScriptedResponses"/> replays every
/// answer BOTH seats have given so far, walking the copy to exactly the
/// prompt being decided;
/// * the candidate idle command is appended as the last scripted answer;
/// * from there two Lucky bots play on to a horizon and the position is
/// scored.
///
/// This PEEKS: the copy is dealt from the same shuffle, so a rollout knows
/// the enemy's hand and the order of both decks. That is deliberate — it is
/// the CEILING of what any rollout planner could be worth on this engine.
/// If lookahead does not pay here it cannot pay with an honest determinized
/// rebuild either. Nothing in the shipped game may use it, and nothing does:
/// <c>SmartExecutor.Oracle</c> is null everywhere except this tool.
///
/// Isolation: one duel at a time on one thread (ocgcore's card/script
/// readers are process-global and already installed by
/// <see cref="LocalHost"/>); <c>WindBot.Program.Rand</c> is swapped for an
/// oracle-owned stream and put back, so the real duel's randomness is
/// untouched and an A/B stays paired; and the rollout seats are named apart
/// from the real ones so their MSG_WIN verdicts cannot be counted as the
/// duel's.
/// </summary>
internal sealed class ReplayOracle : ILookaheadOracle
{
/// <summary>
/// Builds one rollout seat. The worker owns the WindBot statics, so it
/// supplies this rather than the oracle reaching for them.
/// </summary>
internal delegate ILoopbackSeat SeatFactory(string username, int seatIndex);
/// Seat index (0 = A) this oracle answers for.
private readonly int mySeat;
private readonly Action<string> log;
private LocalDuelHost host;
private SeatFactory makeSeat;
private IList<int> mainA, extraA, mainB, extraB;
private int coreSeed;
private Random rolloutRng;
private int rolloutCounter;
public string LastNote { get; private set; }
/// <summary>Run totals, for the worker log.</summary>
public int Rollouts { get; private set; }
public int Abandoned { get; private set; }
public long RolloutMs { get; private set; }
internal ReplayOracle(int seat, Action<string> log)
{
mySeat = seat;
this.log = log;
}
/// <summary>
/// Hand the oracle the duel it is to copy. Called after both seats and
/// both decks exist and before the host runs, so nothing can roll out
/// before it is complete.
/// </summary>
internal void Attach(LocalDuelHost liveHost, SeatFactory factory,
IList<int> mainA, IList<int> extraA,
IList<int> mainB, IList<int> extraB, int coreSeed)
{
host = liveHost;
makeSeat = factory;
this.mainA = mainA; this.extraA = extraA;
this.mainB = mainB; this.extraB = extraB;
this.coreSeed = coreSeed;
// Deterministic per duel and independent of the duel's own stream,
// so two arms on the same --seed face identical rollout noise.
rolloutRng = new Random(unchecked(coreSeed * 31 + 17));
rolloutCounter = 0;
}
public bool Available => host != null && makeSeat != null && host.Live.Responses != null;
public float Evaluate(int idleResponse, int rollouts, int horizonTurns, int msBudget)
{
LastNote = null;
if (!Available || rollouts <= 0) return float.NaN;
var live = host.Live;
// The child host holds the list for the length of its duel, so give
// it a copy: the real duel keeps appending to its own.
var script = new List<byte[]>(live.Responses.Count + 1);
script.AddRange(live.Responses);
script.Add(BitConverter.GetBytes(idleResponse));
int stopAfter = horizonTurns > 0 ? live.Turns + horizonTurns : 0;
var sw = Stopwatch.StartNew();
float sum = 0f;
int done = 0, failed = 0;
string firstWhy = null;
var savedRand = WindBot.Program.Rand;
try
{
for (var i = 0; i < rollouts; i++)
{
if (msBudget > 0 && sw.ElapsedMilliseconds >= msBudget) break;
WindBot.Program.Rand = new Random(unchecked(rolloutRng.Next() ^ (++rolloutCounter * 7919)));
var value = PlayOne(script, stopAfter, out var why);
if (float.IsNaN(value)) { failed++; firstWhy ??= why; continue; }
sum += value;
done++;
}
}
finally
{
WindBot.Program.Rand = savedRand;
RolloutMs += sw.ElapsedMilliseconds;
}
Rollouts += done;
Abandoned += failed;
if (failed > 0) LastNote = failed + " abandoned" + (firstWhy != null ? ": " + firstWhy : string.Empty);
return done == 0 ? float.NaN : sum / done;
}
/// <summary>One playout. 0..1, or NaN when it could not be played.</summary>
private float PlayOne(IList<byte[]> script, int stopAfter, out string why)
{
why = null;
try
{
var child = new LocalDuelHost(new LocalDuelHost.Options
{
SeatA = makeSeat("LookA", 0),
SeatB = makeSeat("LookB", 1),
MainA = mainA, ExtraA = extraA,
MainB = mainB, ExtraB = extraB,
Seed = coreSeed,
ForcedFirstSeat = host.Live.FirstSeat,
ScriptedResponses = script,
StopAfterTurn = stopAfter,
// A rollout that will not converge is worth nothing: give up
// early rather than spend the decision's whole budget on it.
TurnLimit = stopAfter > 0 ? stopAfter + 4 : 200,
MessageLimit = 200000,
});
var outcome = child.Run();
if (outcome.Error != null) { why = outcome.Error; return float.NaN; }
return Value(outcome);
}
catch (Exception e)
{
why = e.GetType().Name + ": " + e.Message;
return float.NaN;
}
}
/// <summary>
/// 1 = we won, 0 = we lost, 0.5 = a draw. At the horizon the position is
/// mapped into 0.1..0.9 (never as certain as a real result) from the
/// life-point difference plus a small board term — the host has no
/// ClientCard view, so monster COUNT is all the board it can see.
/// Deliberately crude: the prototype asks whether a rollout signal
/// exists at all, not how finely it can be scored.
/// </summary>
private float Value(LocalDuelOutcome outcome)
{
int myPlayer = host.Live.FirstSeat == mySeat ? 0 : 1;
if (!outcome.Horizon)
{
if (outcome.Winner < 0) return float.NaN;
if (outcome.Winner == 2) return 0.5f;
return outcome.Winner == myPlayer ? 1f : 0f;
}
int mine = outcome.Lp[myPlayer], theirs = outcome.Lp[1 - myPlayer];
if (mine <= 0) return 0f;
if (theirs <= 0) return 1f;
float v = 0.5f + (mine - theirs) / 16000f
+ 0.04f * (outcome.Monsters[myPlayer] - outcome.Monsters[1 - myPlayer]);
if (v < 0.1f) v = 0.1f;
if (v > 0.9f) v = 0.9f;
return v;
}
internal void LogSummary(int duelIndex)
{
if (Rollouts == 0 && Abandoned == 0) return;
log?.Invoke("lookahead seat " + (mySeat == 0 ? "A" : "B") + " duel " + duelIndex + ": "
+ Rollouts + " rollouts, " + Abandoned + " abandoned, " + RolloutMs + " ms");
}
}
}
+137
View File
@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using MDPro3.Servant;
using YGOLegacy.Characters;
namespace YGOLegacy.Tools.BotArena
{
/// <summary>
/// Everything the game does at boot that WindBot + the brain need, redone
/// here without Unity: locale, characters, bot.conf, and (workers only) the
/// card databases WindBot's NamedCardsManager reads.
/// </summary>
internal static class Setup
{
/// Parent + worker: locale, Data/Characters, bot.conf → BotRoster's
/// Dovphin line. Everything relative to the current directory (= root).
public static void LoadGameData(Options o)
{
MDPro3.Utility.Language.Current = o.locale;
CharacterRegistry.LoadFromDisk();
ReadBots(Path.Combine("Data", "locales", o.locale, "bot.conf"));
}
/// The game's SoloSelector.ReadBots, minus the deck-cover lookup.
private static void ReadBots(string confPath)
{
SoloSelector.bots.Clear();
if (!File.Exists(confPath))
{
Program.Log("no " + confPath + " — using the built-in Dovphin command");
return;
}
using var reader = new StreamReader(confPath);
while (!reader.EndOfStream)
{
var line = (reader.ReadLine() ?? string.Empty).Trim();
if (line.Length == 0 || line[0] != '!') continue;
var bot = new SoloSelector.BotInfo
{
name = line.TrimStart('!'),
command = (reader.ReadLine() ?? string.Empty).Trim(),
desc = (reader.ReadLine() ?? string.Empty).Trim(),
};
bot.flags = (reader.ReadLine() ?? string.Empty).Trim().Split(' ');
SoloSelector.bots.Add(bot);
}
}
/// <summary>
/// Worker: the card databases, in the order the game feeds WindBot
/// (Program.InitDatas): Data/locales/<lang>/cards.cdb, every .cdb inside
/// Expansions/*.ypk (extracted to a per-user cache — WindBot needs real
/// files for sqlite), then Expansions/*.cdb. Later files win per id.
/// </summary>
public static void InitWindBot(Options o)
{
var localeCdb = Path.Combine("Data", "locales", o.locale, "cards.cdb");
if (!File.Exists(localeCdb))
throw new FileNotFoundException("card database not found: " + Path.GetFullPath(localeCdb) + " (wrong --root or --locale?)");
MDPro3.IO.ResourceManager.ZipCdbPaths = ExtractZipCdbs(MDPro3.Program.PATH_EXPANSIONS);
WindBot.Program.InitDatas("cards.cdb");
}
/// .cdb entries of Expansions/*.ypk|*.zip, extracted once per archive
/// version into %TEMP%/YGOLBotArena/cdb/. Concurrent workers race for
/// the same file: write to a temp name and move into place, first wins.
private static List<string> ExtractZipCdbs(string expansions)
{
var result = new List<string>();
if (!Directory.Exists(expansions)) return result;
var cacheRoot = Path.Combine(Path.GetTempPath(), "YGOLBotArena", "cdb");
var archives = new List<string>();
archives.AddRange(Directory.GetFiles(expansions, "*.ypk"));
archives.AddRange(Directory.GetFiles(expansions, "*.zip"));
archives.Sort(StringComparer.OrdinalIgnoreCase);
foreach (var archive in archives)
{
FileInfo info;
try { info = new FileInfo(archive); } catch { continue; }
var key = Path.GetFileNameWithoutExtension(archive) + "-" + info.Length + "-" + info.LastWriteTimeUtc.Ticks;
var dir = Path.Combine(cacheRoot, Sanitize(key));
try
{
using var zip = ZipFile.OpenRead(archive);
foreach (var entry in zip.Entries)
{
if (!entry.FullName.EndsWith(".cdb", StringComparison.OrdinalIgnoreCase) || entry.Length == 0)
continue;
var target = Path.Combine(dir, Sanitize(entry.FullName.Replace('/', '_')));
if (!File.Exists(target))
{
Directory.CreateDirectory(dir);
var tmp = target + "." + Environment.ProcessId + ".tmp";
entry.ExtractToFile(tmp, true);
try { File.Move(tmp, target); }
catch (IOException) { File.Delete(tmp); /* another worker won */ }
}
result.Add(target);
}
}
catch (Exception e)
{
Program.Log("skipping " + archive + ": " + e.Message);
}
}
return result;
}
private static string Sanitize(string s)
{
var bad = Path.GetInvalidFileNameChars();
var chars = s.ToCharArray();
for (var i = 0; i < chars.Length; i++)
if (Array.IndexOf(bad, chars[i]) >= 0) chars[i] = '_';
return new string(chars);
}
/// The file WindBot's Program.ReadFile("Decks", name, "ydk") would open
/// for a DeckFile= value, or null. Relative to the current directory.
public static string ResolveDeckFile(string name)
{
var withExt = name + ".ydk";
foreach (var candidate in new[]
{
Path.Combine("Decks", withExt), name, Path.Combine("../", name), Path.Combine("../deck/", name),
Path.Combine("../", withExt), Path.Combine("../deck/", withExt),
Path.Combine("Data/Windbot/Decks", withExt), Path.Combine("Deck/", withExt),
})
{
if (File.Exists(candidate)) return candidate;
}
return null;
}
}
}
+63
View File
@@ -0,0 +1,63 @@
using System.Collections.Generic;
// Shims: the handful of MDPro3 statics that WindBot's Program.cs and the fork's
// BotRoster.cs touch. Each is a data holder the arena fills in before use; the
// game's own classes are NOT compiled here (they drag in Unity).
namespace MDPro3
{
/// WindBot.Program.InitDatas scans MDPro3.Program.PATH_EXPANSIONS for *.cdb.
public static class Program
{
public const string PATH_EXPANSIONS = "Expansions/";
}
/// Data/config.conf. The arena never writes one, so every key falls back to
/// its default -- which is what DeckLimits wants: the shipped cap, not a
/// local override.
public static class Config
{
public const string EMPTY_STRING = "";
public static string Get(string key, string fallback) => fallback;
}
}
namespace MDPro3.IO
{
/// WindBot.Program.InitDatas adds every .cdb the game extracted out of the
/// Expansions/*.ypk archives. The arena worker extracts them itself
/// (Worker.ExtractZipCdbs) and parks the paths here.
public static class ResourceManager
{
public static List<string> ZipCdbPaths = new();
public static List<string> GetAllCdbInZipPaths() => ZipCdbPaths;
}
}
namespace MDPro3.Utility
{
/// The active locale: picks Data/locales/<lang>/cards.cdb and bot.conf.
public static class Language
{
public static string Current = "en-US";
public static string GetConfig() => Current;
}
}
namespace MDPro3.Servant
{
/// BotRoster reads the "use your deck" (Dovphin) bot.conf line from here.
/// The arena parses Data/locales/<lang>/bot.conf into it (Program.ReadBots)
/// — same shape as the game's SoloSelector.BotInfo/bots.
public static class SoloSelector
{
public class BotInfo
{
public string name;
public string command;
public string desc;
public string[] flags;
}
public static readonly List<BotInfo> bots = new();
}
}
+22
View File
@@ -0,0 +1,22 @@
// Shim: YGOSharp's NamedCardsManager is written against Mono.Data.Sqlite
// (Unity ships it). Outside Unity we sit the same two type names on top of
// Microsoft.Data.Sqlite, whose connection/command surface is identical for the
// SELECT it runs. Read-only, shared: several worker processes open the same
// .cdb files (some through the Expansions/ junction) at once.
namespace Mono.Data.Sqlite
{
public class SqliteConnection : Microsoft.Data.Sqlite.SqliteConnection
{
public SqliteConnection(string connectionString)
: base(ReadOnly(connectionString)) { }
private static string ReadOnly(string cs)
=> cs.Contains("Mode=") ? cs : cs.TrimEnd(';') + ";Mode=ReadOnly;Cache=Shared";
}
public class SqliteCommand : Microsoft.Data.Sqlite.SqliteCommand
{
public SqliteCommand(string commandText, SqliteConnection connection)
: base(commandText, connection) { }
}
}
+23
View File
@@ -0,0 +1,23 @@
using System;
// Shim: UnityEngine.Debug for code linked from the game (SmartExecutor,
// CharacterRegistry log via UnityEngine.Debug.Log*). Routes to the sink the
// arena installs (stderr in a worker, or a per-worker log file); nothing else
// of UnityEngine exists here on purpose — if a linked file needs more, that
// file is the wrong thing to link.
namespace UnityEngine
{
public static class Debug
{
/// Where log lines go; the worker points this at its log writer.
public static Action<string> Sink = s => Console.Error.WriteLine(s);
public static void Log(object message) => Sink?.Invoke(Text(message));
public static void LogWarning(object message) => Sink?.Invoke("[warn] " + Text(message));
public static void LogError(object message) => Sink?.Invoke("[error] " + Text(message));
public static void LogException(Exception e) => Sink?.Invoke("[exception] " + e);
public static void LogFormat(string format, params object[] args) => Log(string.Format(format, args));
private static string Text(object message) => message?.ToString() ?? "null";
}
}
+561
View File
@@ -0,0 +1,561 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using WindBot;
using WindBot.Game;
using YGOLegacy.Bot;
namespace YGOLegacy.Tools.BotArena
{
/// <summary>
/// One worker process = one ygoserver + two in-process WindBot clients at a
/// time, duel after duel. Protocol with the parent:
/// stdout : one JSON line per event — {"type":"ready"}, then
/// {"type":"duel","record":{...DuelRecord...}} per duel,
/// {"type":"fatal","error":"..."} if it cannot start.
/// stdin : one duel index per line; "quit" (or EOF) ends the worker.
/// Everything else (WindBot's Logger, [YGOL bot] lines, the native server's
/// printf) goes to stderr, which the parent writes to Data/BotArena/logs/.
///
/// Why sequential inside a worker: WindBot.Config is a process-wide static
/// that Program-style bot start-up reads (Name/Deck/DeckFile/…), and
/// SmartExecutor.SeedOverride is read once in the executor's ctor — so bot
/// A is fully constructed and connecting before bot B's config is loaded,
/// exactly like the editor arena.
/// </summary>
internal static class Worker
{
// WindBot.Program.Run sleeps 30 ms per tick. The arena ticks every 1 ms and
// only sleeps when the packet queue is empty (a duel is hundreds of prompt
// round-trips per bot; the old fixed 10 ms sleep was ~60 % of the wall clock:
// 100 Weevil duels 57 s -> 25 s, 0 errors). Env BOTARENA_TICKMS /
// BOTARENA_FIXEDTICK=1 exist for timing experiments only.
private static readonly int TickMs = int.TryParse(Environment.GetEnvironmentVariable("BOTARENA_TICKMS"), out var t) ? Math.Max(1, t) : 1;
private static readonly bool AdaptiveTick = Environment.GetEnvironmentVariable("BOTARENA_FIXEDTICK") != "1";
private static string prefix;
private static TextWriter proto;
/// Verdicts/replays arrive on bot threads keyed by Username (= seat name).
private static readonly ConcurrentDictionary<string, BotVerdict> verdicts = new(StringComparer.Ordinal);
private static readonly ConcurrentDictionary<string, byte[]> replays = new(StringComparer.Ordinal);
public static int Run(Options o)
{
prefix = "[w" + o.workerIndex + "] ";
// stdout is the protocol channel; everything chatty goes to stderr.
proto = Console.Out;
Console.SetOut(Console.Error);
UnityEngine.Debug.Sink = s => Console.Error.WriteLine(s);
try
{
Directory.SetCurrentDirectory(o.root);
Setup.LoadGameData(o);
Setup.InitWindBot(o);
// TICKET-045: --host local drives the engine's core in this process and
// never starts its server (nor a socket, nor a port).
if (o.hostMode == "local") LocalHost.Install(o.root);
else YgoServer.Locate(o.root);
}
catch (Exception e)
{
Send(new WorkerMessage { type = "fatal", error = e.GetType().Name + ": " + e.Message });
Console.Error.WriteLine(prefix + e);
return 3;
}
SmartExecutor.Muted = !o.verbose;
SmartExecutor.Verbose = o.verbose; // --verbose = the [YGOL bot] decision log, no knob needed
// TICKET-042: --insightA/--insightB force a seat's duel-state-bus
// insight regardless of that deck brain's `insight` knob. Keyed by
// the seat's WindBot Name=, which is the executor's Username.
DuelStateBus.SetOverride(o.nameA, o.insightA);
DuelStateBus.SetOverride(o.nameB, o.insightB);
// (Tried: skipping WindBot's 500 ms pause before Close at duel end. It
// makes 5-33 % of duels end "both bots claim the win" — the early close
// races the server's result — so it stays. The pause is ~0.5 s/duel.)
GameBehavior.YGOL_DuelResult += OnVerdict;
GameBehavior.YGOL_Replay += OnReplay;
Log("ready: host=" + o.hostMode + (o.hostMode == "server" ? " ygoserver=" + YgoServer.DllPath + " port>=" + o.port : string.Empty));
Send(new WorkerMessage { type = "ready" });
try
{
string line;
while ((line = Console.In.ReadLine()) != null)
{
line = line.Trim();
if (line.Length == 0) continue;
if (line.Equals("quit", StringComparison.OrdinalIgnoreCase)) break;
if (!int.TryParse(line, out var index)) { Log("ignoring '" + line + "'"); continue; }
var record = RunOne(o, index);
Send(new WorkerMessage { type = "duel", record = record });
}
}
finally
{
if (o.hostMode == "server") YgoServer.Stop();
}
return 0;
}
// ------------------------------------------------------------------
// One duel
// ------------------------------------------------------------------
private static DuelRecord RunOne(Options o, int index)
=> o.hostMode == "local" ? RunOneLocal(o, index) : RunOneServer(o, index);
/// <summary>
/// TICKET-045: one duel with no server and no sockets. The host, both
/// WindBot parsers and both brains run on THIS thread — inject a packet,
/// let the bot answer inside its own handler, push the answer into the
/// core — so a duel is a straight-line call with nothing to wait for.
/// </summary>
private static DuelRecord RunOneLocal(Options o, int index)
{
var sw = Stopwatch.StartNew();
var cfg = new ArenaConfig { seed = o.seed, timeoutSeconds = o.timeoutSeconds };
var record = new DuelRecord
{
index = index,
seedA = ArenaReport.SeedFor(cfg, index - 1, 0),
seedB = ArenaReport.SeedFor(cfg, index - 1, 1),
};
var names = new ArenaResult { nameA = o.nameA, nameB = o.nameB };
verdicts.Clear();
replays.Clear();
DuelStateBus.Reset();
SmartExecutor.JournalDuel = index;
// Determinism (--seed != 0): everything random in this duel is
// derived from (--seed, duel index) alone, so duel k plays out the
// same however the parent scheduled it. Program.Rand is
// process-global and is consumed by rock-paper-scissors, the Lucky
// executor and every deck executor's Rand.Next; reseed it per duel
// or the previous duel's leftover state leaks into this one.
int coreSeed = ArenaReport.CoreSeedFor(cfg, index - 1);
if (coreSeed != 0) WindBot.Program.Rand = new Random(coreSeed);
// TICKET-050: --knobsA/--knobsB may switch a seat's `lookahead` on.
// The oracle object has to exist BEFORE the seat's executor is
// built (SmartExecutor reads the static once, in its ctor), but it
// has nothing to copy until the host and both decks exist, so it is
// created empty here and Attach()ed below.
var oracleA = o.LookaheadOn(o.knobsA) ? new ReplayOracle(0, m => Console.Error.WriteLine(prefix + m)) : null;
var oracleB = o.LookaheadOn(o.knobsB) ? new ReplayOracle(1, m => Console.Error.WriteLine(prefix + m)) : null;
try
{
// Seats are built strictly one after the other: WindBot.Config
// and the SmartExecutor journal/seed statics are process-global
// and are consumed inside the GameBehavior constructor, which
// YGOL_StartLoopback runs.
SmartExecutor.KnobOverrides = o.knobsA;
SmartExecutor.Oracle = oracleA;
var infoA = Bot.PrepareInfo(o.commandA, 0, record.seedA, o.seed != 0, JournalFile(o, index, "A"));
var seatA = new LoopbackBotSeat(new GameClient(infoA), o.nameA);
SmartExecutor.JournalPath = null;
SmartExecutor.KnobOverrides = o.knobsB;
SmartExecutor.Oracle = oracleB;
var infoB = Bot.PrepareInfo(o.commandB, 0, record.seedB, o.seed != 0, JournalFile(o, index, "B"));
var seatB = new LoopbackBotSeat(new GameClient(infoB), o.nameB);
SmartExecutor.JournalPath = null;
SmartExecutor.KnobOverrides = null;
SmartExecutor.Oracle = null;
var deckA = LoadDeck(infoA);
var deckB = LoadDeck(infoB);
var mainA = Ids(deckA.Cards); var extraA = Ids(deckA.ExtraCards);
var mainB = Ids(deckB.Cards); var extraB = Ids(deckB.ExtraCards);
var host = new LocalDuelHost(new LocalDuelHost.Options
{
SeatA = seatA,
SeatB = seatB,
MainA = mainA, ExtraA = extraA,
MainB = mainB, ExtraB = extraB,
// Seeds the host's own deck shuffle AND ocgcore's
// create_duel(seed). 0 = --seed 0 = not repeatable.
Seed = coreSeed,
// TICKET-050: only a lookahead run pays for the response log.
RecordResponses = oracleA != null || oracleB != null,
Log = o.verbose ? (Action<string>)(m => Console.Error.WriteLine(prefix + m)) : null,
});
if (oracleA != null || oracleB != null)
{
ReplayOracle.SeatFactory factory = (name, seat) => RolloutSeat(name, seat == 0 ? infoA : infoB);
oracleA?.Attach(host, factory, mainA, extraA, mainB, extraB, coreSeed);
oracleB?.Attach(host, factory, mainA, extraA, mainB, extraB, coreSeed);
}
var outcome = host.Run();
record.coreMs = outcome.Milliseconds;
if (outcome.Error != null)
{
record.winner = "error";
record.error = outcome.Error;
}
}
catch (Exception e)
{
record.winner = "error";
record.error = e.GetType().Name + ": " + e.Message;
Log("duel " + index + " failed: " + e);
}
finally
{
SmartExecutor.KnobOverrides = null;
SmartExecutor.Oracle = null;
record.durationSeconds = (float)sw.Elapsed.TotalSeconds;
oracleA?.LogSummary(index);
oracleB?.LogSummary(index);
}
if (record.winner == null)
{
verdicts.TryGetValue(o.nameA, out record.verdictA);
verdicts.TryGetValue(o.nameB, out record.verdictB);
ArenaReport.Resolve(record, names, 0, "in-process host");
}
Log("duel " + index + ": " + record.winner + " turns=" + record.turns + " " + record.coreMs + "ms"
+ (record.error != null ? " error=" + record.error : string.Empty));
return record;
}
/// <summary>
/// TICKET-050: one rollout seat — a Lucky bot on the same deck file,
/// built straight from a WindBotInfo so that nothing touches the
/// process-global WindBot.Config the real seats were built from. The
/// name is deliberately not either real seat's: GameBehavior's
/// YGOL_DuelResult is a static event and the worker tallies verdicts by
/// username.
/// </summary>
private static ILoopbackSeat RolloutSeat(string username, WindBotInfo template)
{
var info = new WindBotInfo
{
Name = username,
Deck = "Lucky",
DeckFile = template.DeckFile,
Host = template.Host,
Port = template.Port,
HostInfo = template.HostInfo,
Version = template.Version,
Hand = template.Hand,
Debug = false,
};
// A rollout seat must never plan: no oracle, no journal, no seed
// override, no knob overrides (it is a LuckyExecutor anyway, but a
// deck whose brain names Smart would otherwise recurse).
SmartExecutor.Oracle = null;
SmartExecutor.JournalPath = null;
SmartExecutor.SeedOverride = null;
SmartExecutor.KnobOverrides = null;
return new LoopbackBotSeat(new GameClient(info), username);
}
private static WindBot.Game.Deck LoadDeck(WindBotInfo info)
{
var name = !string.IsNullOrEmpty(info.DeckFile) ? info.DeckFile : info.Deck;
var deck = WindBot.Game.Deck.Load(name);
if (deck == null) throw new Exception("could not load deck '" + name + "'");
return deck;
}
private static List<int> Ids(IList<YGOSharp.OCGWrapper.NamedCard> cards)
{
var ids = new List<int>(cards.Count);
foreach (var card in cards) ids.Add(card.Id);
return ids;
}
private static DuelRecord RunOneServer(Options o, int index)
{
var sw = Stopwatch.StartNew();
var cfg = new ArenaConfig { seed = o.seed, timeoutSeconds = o.timeoutSeconds };
var record = new DuelRecord
{
index = index,
seedA = ArenaReport.SeedFor(cfg, index - 1, 0),
seedB = ArenaReport.SeedFor(cfg, index - 1, 1),
};
var names = new ArenaResult { nameA = o.nameA, nameB = o.nameB };
verdicts.Clear();
replays.Clear();
// TICKET-042: a worker plays many duels; each starts from an empty
// bus (this also switches the taps back off until a brain with
// insight is built again). Overrides survive — they are the run's.
DuelStateBus.Reset();
SmartExecutor.JournalDuel = index;
// Same per-duel reseed as the local host. It does NOT make this host
// repeatable — the engine's server shuffles the decks itself with a seed
// we cannot reach — it only stops the previous duel's Program.Rand
// state from leaking into this one.
int serverCoreSeed = ArenaReport.CoreSeedFor(cfg, index - 1);
if (serverCoreSeed != 0) WindBot.Program.Rand = new Random(serverCoreSeed);
Bot botA = null, botB = null;
var note = string.Empty;
try
{
// 1. Server.
var port = YgoServer.FreePort(o.port);
if (!YgoServer.Start(port, 60, out var why))
throw new Exception(why);
// 2. Bots, strictly one after the other (see class doc).
// The journal statics are read once in SmartExecutor's ctor
// (inside Spawn), so each seat gets its own file.
botA = Bot.Spawn(o.commandA, port, record.seedA, o.seed != 0, JournalFile(o, index, "A"));
if (!WaitFor(() => botA.Connected || botA.Dead, 15000))
throw new Exception("bot A never connected");
if (botA.Dead) throw new Exception("bot A dropped before joining (" + (botA.Error ?? "see log") + ")");
botB = Bot.Spawn(o.commandB, port, record.seedB, o.seed != 0, JournalFile(o, index, "B"));
if (!WaitFor(() => botB.Connected || botB.Dead, 15000))
throw new Exception("bot B never connected");
if (botB.Dead) throw new Exception("bot B dropped before joining (" + (botB.Error ?? "see log") + ")");
// 3. Both bots auto-ready; the host bot sends HsStart. Watch.
var deadline = TimeSpan.FromSeconds(Math.Max(30, o.timeoutSeconds));
TimeSpan? firstVerdictAt = null, endedAt = null;
while (true)
{
var now = sw.Elapsed;
var haveA = verdicts.ContainsKey(o.nameA);
var haveB = verdicts.ContainsKey(o.nameB);
if (haveA && haveB) break;
if ((haveA || haveB) && firstVerdictAt == null) firstVerdictAt = now;
// One bot spoke, the other has had 5s: its verdict is implied.
if (firstVerdictAt != null && now - firstVerdictAt.Value > TimeSpan.FromSeconds(5)) break;
var over = (botA.Dead && botB.Dead) || !YgoServer.Running;
if (over)
{
endedAt ??= now;
if (now - endedAt.Value > TimeSpan.FromSeconds(3)) break;
}
if (now > deadline)
{
record.winner = "error";
record.error = "timeout after " + o.timeoutSeconds + "s (turns seen: A=" + botA.Turn + " B=" + botB.Turn + ")";
record.turns = Math.Max(botA.Turn, botB.Turn);
return record;
}
Thread.Sleep(50);
}
note = "server running=" + YgoServer.Running + ", bot A alive=" + !botA.Dead + (botA.Error != null ? " (" + botA.Error + ")" : "")
+ ", bot B alive=" + !botB.Dead + (botB.Error != null ? " (" + botB.Error + ")" : "");
}
catch (Exception e)
{
record.winner = "error";
record.error = e.GetType().Name + ": " + e.Message;
Log("duel " + index + " failed: " + e);
}
finally
{
// Teardown: server down (drops both sockets → the bot loops end), then join.
try { YgoServer.Stop(); } catch (Exception e) { Log("stop server: " + e.Message); }
botA?.Join(10000);
botB?.Join(10000);
record.durationSeconds = (float)sw.Elapsed.TotalSeconds;
}
if (record.winner == null)
{
verdicts.TryGetValue(o.nameA, out record.verdictA);
verdicts.TryGetValue(o.nameB, out record.verdictB);
ArenaReport.Resolve(record, names, Math.Max(botA?.Turn ?? 0, botB?.Turn ?? 0), note);
}
SaveReplay(o, index);
Log("duel " + index + ": " + record.winner + " turns=" + record.turns + " " + record.durationSeconds.ToString("0.0") + "s"
+ (record.error != null ? " error=" + record.error : string.Empty));
return record;
}
/// `<journalDir>/duel-<n>-<seat>.jsonl`, or null when --journal is off.
private static string JournalFile(Options o, int index, string seat)
=> string.IsNullOrEmpty(o.journalDir) ? null : Path.Combine(o.journalDir, "duel-" + index.ToString("D4") + "-" + seat + ".jsonl");
private static void SaveReplay(Options o, int index)
{
if (string.IsNullOrEmpty(o.replaysDir) || replays.IsEmpty) return;
try
{
byte[] data = null;
if (!replays.TryGetValue(o.nameA, out data)) replays.TryGetValue(o.nameB, out data);
if (data == null || data.Length == 0) return;
Directory.CreateDirectory(o.replaysDir);
var file = Path.Combine(o.replaysDir, "duel-" + index.ToString("D4") + ".yrp");
File.WriteAllBytes(file, data);
}
catch (Exception e) { Log("replay " + index + ": " + e.Message); }
}
// ------------------------------------------------------------------
// Bot seams
// ------------------------------------------------------------------
private static void OnVerdict(string username, int result, int turn)
{
if (string.IsNullOrEmpty(username)) return;
verdicts[username] = ArenaReport.Verdict(username, result, turn);
}
private static void OnReplay(string username, byte[] data)
{
if (string.IsNullOrEmpty(username) || data == null) return;
replays[username] = data;
}
private static bool WaitFor(Func<bool> condition, int timeoutMs)
{
var deadline = Environment.TickCount64 + timeoutMs;
while (!condition())
{
if (Environment.TickCount64 > deadline) return false;
Thread.Sleep(20);
}
return true;
}
private static void Send(WorkerMessage msg)
{
var line = JsonConvert.SerializeObject(msg, Formatting.None);
lock (proto) { proto.WriteLine(line); proto.Flush(); }
}
internal static void Log(string message) => Console.Error.WriteLine(prefix + message);
/// <summary>
/// One in-process WindBot: DuelLauncher.StartWindBot's argument
/// massaging + WindBot.Program.RunFromArgs/Run, minus the per-bot
/// InitDatas (done once per worker) — the client is built and connected
/// on the caller's thread so the process-global Config is free again the
/// moment Spawn returns; only the tick loop runs on the bot thread.
/// </summary>
private sealed class Bot
{
public GameClient Client;
public Thread Thread;
public volatile string Error;
public bool Connected => Client?.Connection != null && Client.Connection.IsConnected;
public bool Dead => Thread == null || !Thread.IsAlive;
public int Turn => 0; // WindBot's Duel is private to GameBehavior; the verdict carries the turn.
private static string[] BuildArgs(string command, int port)
{
command = command.Replace("'", "\"");
command += " Host=127.0.0.1";
command += " Port=" + port;
command += " HostInfo=";
return SplitWithPreservedQuotes(command);
}
public static Bot Spawn(string command, int port, int seed, bool applySeed, string journalFile)
{
var args = BuildArgs(command, port);
// Read once by SmartExecutor's ctor (inside client.Start below).
SmartExecutor.SeedOverride = applySeed ? seed : null;
SmartExecutor.JournalPath = journalFile;
Config.Load(args);
var info = ReadInfo();
var bot = new Bot();
Log("spawning: " + string.Join(" ", args) + (applySeed ? " (seed " + seed + ")" : string.Empty));
bot.Client = new GameClient(info);
bot.Client.Start();
SmartExecutor.JournalPath = null;
bot.Thread = new Thread(bot.Loop) { IsBackground = true, Name = "bot " + info.Name };
bot.Thread.Start();
return bot;
}
/// <summary>
/// TICKET-045: Spawn's argument massaging and process-global static
/// setup, without building a client — the in-process host builds its
/// own (loopback) one from this.
/// </summary>
public static WindBotInfo PrepareInfo(string command, int port, int seed, bool applySeed, string journalFile)
{
var args = BuildArgs(command, port);
SmartExecutor.SeedOverride = applySeed ? seed : null;
SmartExecutor.JournalPath = journalFile;
Config.Load(args);
Log("seat: " + string.Join(" ", args) + (applySeed ? " (seed " + seed + ")" : string.Empty));
return ReadInfo();
}
private static WindBotInfo ReadInfo()
{
var info = new WindBotInfo();
info.Name = Config.GetString("Name", info.Name);
info.Deck = Config.GetString("Deck", info.Deck);
info.DeckFile = Config.GetString("DeckFile", info.DeckFile);
info.Host = Config.GetString("Host", info.Host);
info.Port = Config.GetInt("Port", info.Port);
info.HostInfo = Config.GetString("HostInfo", info.HostInfo);
info.Version = Config.GetInt("Version", info.Version);
info.Hand = Config.GetInt("Hand", info.Hand);
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
return info;
}
private void Loop()
{
try
{
while (Client.Connection.IsConnected)
{
try { Client.Tick(); }
catch (Exception ex) { Error = "tick: " + ex.Message; Logger.WriteErrorLine("Tick Error: " + ex); }
// Only pause when nothing is queued: a duel is hundreds of
// prompt round-trips and a fixed sleep per tick was most of
// the wall clock (10 ms x hundreds x two bots).
if (!AdaptiveTick || !Client.Connection.HasPendingPackets) Thread.Sleep(TickMs);
}
}
catch (Exception ex)
{
Error = ex.Message;
Logger.WriteErrorLine("Run Error: " + ex);
}
}
public void Join(int ms)
{
if (Thread == null) return;
if (!Thread.Join(ms))
{
try { Client?.Connection?.Close(); } catch { }
if (!Thread.Join(2000)) Log("bot thread '" + Thread.Name + "' still alive after teardown");
}
}
/// MDPro3 Tools.SplitWithPreservedQuotes: split on spaces outside
/// double quotes, then strip the quotes.
private static string[] SplitWithPreservedQuotes(string input)
{
var result = new List<string>();
var start = 0;
var inQuotes = false;
for (var i = 0; i < input.Length; i++)
{
if (input[i] == '"') inQuotes = !inQuotes;
else if (input[i] == ' ' && !inQuotes)
{
result.Add(input.Substring(start, i - start));
start = i + 1;
}
}
result.Add(input.Substring(start));
for (var i = 0; i < result.Count; i++)
result[i] = result[i].Replace("\"", string.Empty);
return result.ToArray();
}
}
}
}
+138
View File
@@ -0,0 +1,138 @@
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using YGOLegacy.Engine;
namespace YGOLegacy.Tools.BotArena
{
/// <summary>
/// The game's server is not an exe: it is <c>ygol-engine.dll</c>
/// (Assets/Plugins/Windows/), driven exactly as MDPro3.Net.YgoServer drives
/// it — <c>start_server(args)</c> blocks on a thread until the duel ends
/// (the server-mode build stops itself after DuelEnd) or <c>stop_server()</c>
/// is called. It reads <c>./expansions</c> (Expansions/ on the Windows FS),
/// <c>./script</c> and writes <c>./replay</c>/<c>error.log</c> relative to
/// the current directory, so a worker's cwd is the game root.
///
/// The args string is positional, the same layout MultiplayerService.HostLocal
/// (the editor arena's host) builds: port, banlist(-1 = none), card pool,
/// mode(0 = Single), priority, check-deck, shuffle-deck, LP, hand, draw,
/// time limit, replay-mode.
/// </summary>
internal static class YgoServer
{
public const int DefaultTime = 180; // OnlineServant.DEFAULT_TIME
private static Thread serverThread;
private static string dllPath;
public static bool Running => serverThread != null && serverThread.IsAlive;
public static string DllPath => dllPath;
/// Find ygol-engine.dll and teach the runtime where it is. Order: env
/// YGOL_ENGINE_DLL, the project's plugin folder, a built player's
/// plugin folder, next to this exe.
public static void Locate(string root)
{
var candidates = new[]
{
Environment.GetEnvironmentVariable("YGOL_ENGINE_DLL"),
Path.Combine(root, "Assets", "Plugins", "Windows", "ygol-engine.dll"),
Path.Combine(root, "YGOLegacy_Data", "Plugins", "x86_64", "ygol-engine.dll"),
Path.Combine(root, "MDPro3_Data", "Plugins", "x86_64", "ygol-engine.dll"),
Path.Combine(AppContext.BaseDirectory, "ygol-engine.dll"),
};
foreach (var c in candidates)
if (!string.IsNullOrEmpty(c) && File.Exists(c)) { dllPath = Path.GetFullPath(c); break; }
if (dllPath == null)
throw new FileNotFoundException("ygol-engine.dll not found (looked in Assets/Plugins/Windows under --root, a built player's Plugins/x86_64, next to the exe, and $YGOL_ENGINE_DLL)");
NativeLibrary.SetDllImportResolver(typeof(EngineApi).Assembly, (name, asm, path) =>
name == "ygol-engine" ? NativeLibrary.Load(dllPath) : IntPtr.Zero);
}
/// A port nothing is listening on, from `from` upward.
public static int FreePort(int from)
{
for (var port = from; port < from + 200 && port < 65535; port++)
{
TcpListener probe = null;
try
{
probe = new TcpListener(IPAddress.Any, port);
probe.Start();
return port;
}
catch (SocketException) { }
finally { try { probe?.Stop(); } catch { } }
}
throw new Exception("no free port from " + from + " on");
}
/// <summary>
/// Start a Single-mode room on `port` (8000 LP, 5 cards, draw 1, no
/// banlist, decks not checked, decks shuffled by the server) and wait
/// until it accepts connections. Returns false if the server never came
/// up (its thread ended — port taken, or the DLL failed to init).
/// </summary>
public static bool Start(int port, int readySeconds, out string why)
{
why = null;
Stop();
var args = string.Format("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11}",
port, -1, 5, 0, "F", "T", "F", 8000, 5, 1, DefaultTime, "0"); // no deck check, same as the game's launch paths
serverThread = new Thread(() =>
{
try { EngineApi.start_server(args); }
catch (Exception e) { Console.Error.WriteLine("[ygoserver] " + e); }
}) { IsBackground = true, Name = "ygoserver" };
serverThread.Start();
var deadline = DateTime.UtcNow.AddSeconds(readySeconds);
while (DateTime.UtcNow < deadline)
{
if (!serverThread.IsAlive) { why = "server thread ended before it accepted connections (port " + port + " taken?)"; return false; }
if (Accepting(port)) return true;
Thread.Sleep(50);
}
why = "server did not accept connections on port " + port + " within " + readySeconds + "s";
return false;
}
private static bool Accepting(int port)
{
try
{
using var probe = new TcpClient();
var task = probe.ConnectAsync(IPAddress.Loopback, port);
if (!task.Wait(300)) return false;
return probe.Connected;
}
catch { return false; }
}
/// <summary>
/// Take the server down and wait for its thread (bounded). Idempotent.
/// After a finished duel the server-mode build stops ITSELF
/// (DuelEndProc → StopServer), and a second stop_server racing that
/// self-teardown trips a libevent assertion inside the DLL (which
/// aborts the whole process) — so give it `graceMs` to leave on its own
/// first and only then call stop_server for the cases (timeouts, bots
/// that never joined) where it would run forever.
/// </summary>
public static void Stop(int graceMs = 3000, int waitMs = 10000)
{
if (serverThread == null) return;
if (serverThread.IsAlive && !serverThread.Join(graceMs))
{
try { EngineApi.stop_server(); } catch (Exception e) { Console.Error.WriteLine("[ygoserver] stop: " + e.Message); }
if (!serverThread.Join(waitMs))
Console.Error.WriteLine("[ygoserver] thread still alive " + waitMs + "ms after stop_server");
}
serverThread = null;
}
}
}
+270
View File
@@ -0,0 +1,270 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using YGOLegacy.Services;
namespace YGOLegacy.Bot
{
// ------------------------------------------------------------------------
// The Bot Arena report model + the pure helpers that build it. This file is
// deliberately Unity-free (no UnityEngine, no UniTask, no MDPro3): it is
// compiled BOTH by the game (BotArena.cs, the in-editor arena of TICKET-030)
// and by Tools/BotArena (the standalone parallel arena of TICKET-035), so
// the two produce byte-compatible JSON. Keep it that way — anything that
// needs Unity belongs in BotArena.cs.
// ------------------------------------------------------------------------
/// <summary>
/// What one arena run is asked to do. Decks are "group/name" paths under
/// Deck/ (root-group decks are just "name"); the DECK decides the brain
/// (BotRoster.ForDeck), so there is no character input — but a seat may
/// force its WindBot executor ("Lucky", "Smart", ...) to pit two brains
/// against each other on the same deck.
/// </summary>
[Serializable]
public class ArenaConfig
{
public string deckA;
public string deckB;
/// WindBot `Deck=` token override for seat A; null/empty = the deck's own brain.
public string executorA;
public string executorB;
public int n = 10;
/// Base of the per-duel SmartExecutor noise seed (0 = leave the brains
/// to their own seeding). The core's shuffle is NOT seeded by this.
public int seed;
public int timeoutSeconds = 300;
/// Keep `[YGOL bot]` decision logging on during the run.
public bool verboseBots;
/// Extra copy of the JSON report (the canonical one always lands under
/// Data/BotArena/).
public string outPath;
/// SmartExecutor decision journal directory (TICKET-036): one
/// `duel-<n>-<seat>.jsonl` per Smart seat. Null/empty = off.
public string journalDir;
/// Duel state bus insight forced on seat A (TICKET-042):
/// "none" | "hand" | "full". Null/empty = the deck brain's own
/// `insight` knob decides. Recorded so a run says what it measured.
public string insightA;
public string insightB;
/// TICKET-045: which duel host played the run — "local" (the engine's core driven
/// in-process by YGOLegacy.Bot.LocalDuelHost, the default) or "server"
/// (the engine's start_server over a TCP loopback, kept for A/B). The in-editor
/// arena leaves this empty; it is always the server.
public string hostMode;
}
/// One bot's own verdict on a duel, as raised from GameBehavior.OnWin.
[Serializable]
public class BotVerdict
{
public string username;
/// win | lose | draw
public string result;
public int turn;
}
[Serializable]
public class DuelRecord
{
public int index;
/// A | B | draw | error
public string winner;
public string winnerName;
public int turns;
public float durationSeconds;
public string error;
public BotVerdict verdictA;
public BotVerdict verdictB;
public int seedA;
public int seedB;
/// TICKET-045: milliseconds spent inside the duel itself (with
/// hostMode "local" that is the whole duel — core plus both brains;
/// with "server" it is not filled in, durationSeconds covers it).
public int coreMs;
}
/// <summary>
/// The live tally of a run. The same instance is reported through
/// IProgress after every duel and returned at the end (`done` = true).
/// </summary>
[Serializable]
public class ArenaResult
{
public string startedAt;
public ArenaConfig config;
public string nameA;
public string nameB;
public string commandA;
public string commandB;
public int winsA;
public int winsB;
public int draws;
public int errors;
public int completed;
public float totalSeconds;
public float averageTurns;
public bool done;
public bool cancelled;
public string reportPath;
public string summary;
public string status;
public List<DuelRecord> duels = new();
public int Played => winsA + winsB + draws;
}
/// <summary>
/// Pure helpers shared by both arenas: seat naming/commands, verdict
/// resolution, tallying, the one-line summary and report file naming.
/// </summary>
public static class ArenaReport
{
/// Where every arena run's report lands (relative to the game root).
public const string OutputDir = "Data/BotArena/";
/// The Deck= token of a WindBot command line (NOT DeckFile=).
private static readonly Regex DeckToken = new(@"(?<![A-Za-z])Deck=(""[^""]*""|'[^']*'|\S+)");
/// "<display name> A" / "... B": unique per run even when both decks
/// resolve to the same character, and exactly what the bot's Username
/// (hence its verdict key) will be.
public static string SeatName(BotDef bot, int seat)
=> bot.displayName + (seat == 0 ? " A" : " B");
/// BotRoster's command for the seat, with the Deck= token rewritten
/// when the caller forces an executor. Kept here on purpose: BotRoster's
/// contract stays "the deck decides".
public static string SeatCommand(BotDef bot, string deckPath, string executorOverride, string seatName)
{
var command = BotRoster.CommandFor(bot, deckPath, seatName);
if (string.IsNullOrWhiteSpace(executorOverride) || executorOverride.Equals("Auto", StringComparison.OrdinalIgnoreCase))
return command;
var token = "Deck=" + executorOverride.Trim();
return DeckToken.IsMatch(command)
? DeckToken.Replace(command, token, 1)
: command + " " + token;
}
/// The SmartExecutor noise seed for one seat of one duel (0 = none).
public static int SeedFor(ArenaConfig cfg, int duelIndex, int seat)
=> cfg.seed == 0 ? 0 : unchecked(cfg.seed * 1000 + duelIndex * 2 + seat);
/// <summary>
/// The seed for everything in duel <paramref name="duelIndex"/> that is
/// NOT a brain: the in-process host's deck shuffle, ocgcore's own
/// <c>create_duel(seed)</c> and WindBot's process-global
/// <c>Program.Rand</c> (rock-paper-scissors, LuckyExecutor's coin flips,
/// every `Rand.Next` inside a deck executor). Derived from the run seed
/// and the duel index ONLY, so a duel plays the same however the parent
/// happened to hand it to a worker — which is what makes a whole run
/// repeatable. 0 (= <c>--seed 0</c>) means "seed yourself": nothing is
/// pinned and the run is not repeatable, as before.
/// The odd multiplier keeps this stream clear of
/// <see cref="SeedFor"/>'s (seed*1000 + duel*2 + seat).
/// </summary>
public static int CoreSeedFor(ArenaConfig cfg, int duelIndex)
=> cfg.seed == 0 ? 0 : unchecked(((cfg.seed * 7919 + duelIndex * 104729) & 0x7FFFFFFF) | 1);
/// A GameBehavior.YGOL_DuelResult payload as a verdict row.
public static BotVerdict Verdict(string username, int result, int turn)
=> new()
{
username = username,
result = result == 0 ? "win" : result == 1 ? "lose" : "draw",
turn = turn,
};
/// <summary>
/// Turn two bot verdicts (either may be missing) into a winner row.
/// `observerTurns` is a lower bound from whoever else counted turns
/// (0 when nobody did); `noVerdictNote` is appended to the error when
/// neither bot reported.
/// </summary>
public static void Resolve(DuelRecord r, ArenaResult result, int observerTurns, string noVerdictNote = null)
{
r.turns = Math.Max(Math.Max(r.verdictA?.turn ?? 0, r.verdictB?.turn ?? 0), observerTurns);
// What each verdict implies about the duel: "A", "B" or "draw".
var fromA = r.verdictA == null ? null
: r.verdictA.result == "win" ? "A" : r.verdictA.result == "lose" ? "B" : "draw";
var fromB = r.verdictB == null ? null
: r.verdictB.result == "win" ? "B" : r.verdictB.result == "lose" ? "A" : "draw";
string winner;
if (fromA != null && fromB != null)
winner = fromA == fromB ? fromA : "conflict";
else
winner = fromA ?? fromB;
switch (winner)
{
case "A": r.winner = "A"; r.winnerName = result.nameA; break;
case "B": r.winner = "B"; r.winnerName = result.nameB; break;
case "draw": r.winner = "draw"; break;
case "conflict":
r.winner = "error";
r.error = "verdicts disagree: A=" + r.verdictA.result + " B=" + r.verdictB.result;
break;
default:
r.winner = "error";
r.error = "no bot verdict (duel ended without MSG_WIN reaching a bot"
+ (string.IsNullOrEmpty(noVerdictNote) ? string.Empty : "; " + noVerdictNote) + ")";
break;
}
}
/// Add a finished duel to the tally and refresh the derived counters.
public static void Tally(ArenaResult result, DuelRecord record)
{
result.duels.Add(record);
switch (record.winner)
{
case "A": result.winsA++; break;
case "B": result.winsB++; break;
case "draw": result.draws++; break;
default: result.errors++; break;
}
result.completed = result.duels.Count;
var played = 0; var turns = 0;
foreach (var d in result.duels)
if (d.winner != "error") { played++; turns += d.turns; }
result.averageTurns = played > 0 ? (float)turns / played : 0f;
}
/// The one-line summary the ticket asks for:
/// `A 13 - 7 B (0 errors, avg 11.2 turns, 4m02s)`.
public static string Summary(ArenaResult r)
{
var mins = (int)(r.totalSeconds / 60);
var secs = (int)(r.totalSeconds % 60);
var sb = new StringBuilder();
sb.Append(r.nameA ?? "A").Append(' ').Append(r.winsA).Append(" - ").Append(r.winsB).Append(' ').Append(r.nameB ?? "B");
sb.Append(" (");
if (r.draws > 0) sb.Append(r.draws).Append(r.draws == 1 ? " draw, " : " draws, ");
sb.Append(r.errors).Append(r.errors == 1 ? " error, " : " errors, ");
sb.Append("avg ").Append(r.averageTurns.ToString("0.0")).Append(" turns, ");
sb.Append(mins).Append('m').Append(secs.ToString("00")).Append('s').Append(')');
if (r.cancelled) sb.Append(" [cancelled]");
else if (r.status != null && r.status.StartsWith("bad deck")) sb.Append(" [").Append(r.status).Append(']');
else if (r.status != null && r.status.StartsWith("failed")) sb.Append(" [").Append(r.status).Append(']');
return sb.ToString();
}
/// `Data/BotArena/<yyyyMMdd-HHmmss>-<deckA>-vs-<deckB>.json`.
public static string ReportFileName(ArenaResult result, DateTime now)
=> OutputDir + now.ToString("yyyyMMdd-HHmmss")
+ "-" + FileToken(result.config?.deckA) + "-vs-" + FileToken(result.config?.deckB) + ".json";
public static string FileToken(string deckPath)
{
if (string.IsNullOrEmpty(deckPath)) return "none";
var sb = new StringBuilder();
foreach (var c in deckPath)
sb.Append(char.IsLetterOrDigit(c) || c == '-' || c == '.' ? c : '_');
var s = sb.ToString().Trim('_');
return s.Length > 40 ? s[..40] : (s.Length == 0 ? "deck" : s);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
using System;
using WindBot.Game;
namespace YGOLegacy.Bot
{
/// <summary>
/// What one declared attack does, predicted from ATK/DEF/position alone
/// (no effects, no piercing). Face-down defenders are guessed at
/// <see cref="Uncertain"/> = true.
/// </summary>
public struct BattleOutcome
{
public bool Allowed;
public bool Direct;
public bool AttackerDies;
public bool DefenderDies;
public int BotLpDelta;
public int EnemyLpDelta;
public bool Uncertain;
/// The attacker is lost and the defender stays: the trade the bot never
/// takes on its own initiative.
public bool IsLosingTrade => AttackerDies && !DefenderDies;
public bool IsEvenTrade => AttackerDies && DefenderDies;
public override string ToString()
{
if (!Allowed) return "forbidden";
if (Direct) return "direct " + (-EnemyLpDelta);
var s = AttackerDies && DefenderDies ? "both die"
: DefenderDies ? "defender dies"
: AttackerDies ? "attacker dies"
: "bounce";
if (EnemyLpDelta != 0) s += " enemy " + EnemyLpDelta;
if (BotLpDelta != 0) s += " bot " + BotLpDelta;
if (Uncertain) s += " (guess)";
return s;
}
}
/// <summary>
/// Deterministic one-step battle prediction. Given an attacker and a
/// defender (null = direct attack) it computes who dies and the LP change
/// using RealPower — which the caller's pre-battle hook (DefaultExecutor's
/// OnPreBattleBetween: Honest, Utopia, protection rules...) may adjust or
/// veto — and applies the result to a BoardView copy for scoring.
/// </summary>
public static class BattlePredictor
{
/// <param name="preBattle">DefaultExecutor.OnPreBattleBetween or null; sets
/// RealPower on both cards and returns false when the attack must not happen.</param>
/// <param name="unknownDefense">Guessed DEF of a face-down defender.</param>
public static BattleOutcome Predict(ClientCard attacker, ClientCard defender,
Func<ClientCard, ClientCard, bool> preBattle, int unknownDefense)
{
var o = new BattleOutcome { Allowed = true };
if (attacker == null)
{
o.Allowed = false;
return o;
}
if (defender == null)
{
o.Direct = true;
o.EnemyLpDelta = -Math.Max(0, attacker.Attack);
return o;
}
bool hidden = defender.Id == 0 || defender.IsFacedown();
attacker.RealPower = attacker.Attack;
defender.RealPower = hidden ? unknownDefense : defender.GetDefensePower();
if (preBattle != null && !preBattle(attacker, defender))
{
o.Allowed = false;
return o;
}
int atk = attacker.RealPower;
int def = defender.RealPower;
o.Uncertain = hidden;
if (!hidden && defender.IsAttack())
{
if (atk > def) { o.DefenderDies = true; o.EnemyLpDelta = -(atk - def); }
else if (atk == def) { o.AttackerDies = true; o.DefenderDies = true; }
else { o.AttackerDies = true; o.BotLpDelta = -(def - atk); }
}
else
{
if (atk > def) o.DefenderDies = true;
else if (atk < def) o.BotLpDelta = -(def - atk);
// equal: nothing happens
}
return o;
}
/// The board after the outcome (a copy; the input is untouched).
public static BoardView Apply(BoardView board, ClientCard attacker, ClientCard defender, BattleOutcome o)
{
var next = board.Clone();
if (!o.Allowed) return next;
next.BotLp += o.BotLpDelta;
next.EnemyLp += o.EnemyLpDelta;
if (o.AttackerDies)
{
int i = next.IndexOfBot(attacker);
if (i >= 0) next.Bot.RemoveAt(i);
}
if (o.DefenderDies && defender != null)
{
int i = next.IndexOfEnemy(defender);
if (i >= 0) next.Enemy.RemoveAt(i);
}
return next;
}
}
}
+382
View File
@@ -0,0 +1,382 @@
using System;
using System.Collections.Generic;
using WindBot.Game;
using WindBot.Game.AI;
using YGOSharp.OCGWrapper.Enums;
namespace YGOLegacy.Bot
{
/// <summary>
/// One monster as the evaluator sees it. Built from a ClientCard but holds
/// plain numbers so predictions can edit copies without touching the live
/// duel state. <see cref="Card"/> is only an identity handle for the
/// predictor (which monster did what) — the score never reads it.
/// </summary>
public struct MonsterView
{
public ClientCard Card;
public int Atk;
public int Def;
public bool AttackPos;
public bool FaceUp;
/// False = the card is hidden from the bot (Id == 0): stats are estimates.
public bool Known;
/// 0..1: how much of a problem the card is beyond its stats (floodgate,
/// battle-invincible, "dangerous to attack" per WindBot's lists).
public float Threat;
/// Battle-relevant power: ATK in attack position, DEF otherwise.
public int Power => AttackPos ? Atk : Def;
public static MonsterView Of(ClientCard card, int unknownPower)
{
bool known = card.Id != 0;
var view = new MonsterView
{
Card = card,
Known = known,
FaceUp = card.IsFaceup(),
AttackPos = card.IsAttack(),
Atk = known ? card.Attack : unknownPower,
Def = known ? card.Defense : unknownPower,
Threat = known && !card.IsDisabled() ? BoardEvaluator.ThreatOf(card) : 0f,
};
return view;
}
}
/// <summary>
/// A copyable snapshot of everything the evaluator scores. Built from the two
/// ClientFields with public information only: the bot's own cards are known,
/// enemy hidden cards (Id == 0) are counted, never read.
/// </summary>
public class BoardView
{
public int BotLp;
public int EnemyLp;
public List<MonsterView> Bot = new();
public List<MonsterView> Enemy = new();
public int BotBackrow;
public int EnemyBackrow;
public int BotFloodgateSpells;
public int EnemyFloodgateSpells;
public int BotHand;
public int EnemyHand;
/// Intangibles a simulation wants scored but the fields cannot carry
/// (card quality from a draw, a search's pick, an effect negated on
/// the stack) — added to the score as-is. 0 for a live board.
public float Bonus;
public static BoardView From(ClientField bot, ClientField enemy, int unknownPower = BoardEvaluator.DefaultUnknownPower)
{
var view = new BoardView
{
BotLp = bot.LifePoints,
EnemyLp = enemy.LifePoints,
BotHand = bot.GetHandCount(),
EnemyHand = enemy.GetHandCount(),
};
foreach (var m in bot.GetMonsters())
view.Bot.Add(MonsterView.Of(m, unknownPower));
foreach (var m in enemy.GetMonsters())
view.Enemy.Add(MonsterView.Of(m, unknownPower));
foreach (var s in bot.GetSpells())
{
view.BotBackrow++;
if (s.IsFaceup() && s.Id != 0 && s.IsFloodgate() && !s.IsDisabled())
view.BotFloodgateSpells++;
}
foreach (var s in enemy.GetSpells())
{
view.EnemyBackrow++;
if (s.IsFaceup() && s.Id != 0 && s.IsFloodgate() && !s.IsDisabled())
view.EnemyFloodgateSpells++;
}
return view;
}
public BoardView Clone()
{
var copy = (BoardView)MemberwiseClone();
copy.Bot = new List<MonsterView>(Bot);
copy.Enemy = new List<MonsterView>(Enemy);
return copy;
}
public int IndexOfBot(ClientCard card) => IndexOf(Bot, card);
public int IndexOfEnemy(ClientCard card) => IndexOf(Enemy, card);
private static int IndexOf(List<MonsterView> list, ClientCard card)
{
for (int i = 0; i < list.Count; i++)
if (ReferenceEquals(list[i].Card, card))
return i;
return -1;
}
}
/// <summary>
/// The scoring brain's value function: a single float for "how good is this
/// board for the bot", positive = bot ahead. Pure and deterministic; scale
/// is roughly LP/2, so 1000 LP ≈ 500 points and one average monster ≈ 700.
///
/// Reads nothing hidden: enemy face-down monsters and hand cards enter only
/// as counts and estimates. Aggression skews how LP damage dealt vs. taken
/// is weighed; CounterAttackAware (hard difficulty) additionally charges the
/// bot for what the enemy's best attacker could do next turn.
/// </summary>
public class BoardEvaluator
{
public const int DefaultUnknownPower = 1500;
public const float Lethal = 100000f;
/// 0..1, default 0.5: >0.5 values enemy LP damage over own LP safety.
public float Aggression = 0.5f;
/// Hard difficulty: subtract the damage the enemy's best attacker threatens.
/// What one card in hand is worth (default 130). SmartExecutor sets it from knob `handCardValue`.
public float HandCardValue = 130f;
public float CounterAttackWeight = 0f;
public static readonly BoardEvaluator Default = new();
public float Score(ClientField bot, ClientField enemy) => Score(BoardView.From(bot, enemy));
public float Score(BoardView v)
{
if (v.EnemyLp <= 0 && v.BotLp > 0) return Lethal;
if (v.BotLp <= 0) return -Lethal;
float aggression = Clamp01(Aggression);
float wBotLp = 0.5f * (1.5f - aggression);
float wEnemyLp = 0.5f * (0.5f + aggression);
float score = v.BotLp * wBotLp - v.EnemyLp * wEnemyLp;
int botBestAtk = 0, botBestPower = 0, enemyBestAtk = 0, enemyBestPower = 0;
int botWeakestAtkPos = int.MaxValue;
foreach (var m in v.Bot)
{
score += MonsterValue(m);
if (m.AttackPos && m.FaceUp) botBestAtk = Math.Max(botBestAtk, m.Atk);
botBestPower = Math.Max(botBestPower, m.Power);
if (m.AttackPos) botWeakestAtkPos = Math.Min(botWeakestAtkPos, m.Atk);
}
foreach (var m in v.Enemy)
{
score -= MonsterValue(m);
if (m.AttackPos && m.FaceUp) enemyBestAtk = Math.Max(enemyBestAtk, m.Atk);
enemyBestPower = Math.Max(enemyBestPower, m.Power);
}
// Tempo: owning the biggest body on the table.
if (v.Bot.Count > 0 && (v.Enemy.Count == 0 || botBestAtk > enemyBestPower)) score += 200f;
if (v.Enemy.Count > 0 && (v.Bot.Count == 0 || enemyBestAtk > botBestPower)) score -= 200f;
score += (v.BotBackrow - v.EnemyBackrow) * 140f;
score += (v.BotFloodgateSpells - v.EnemyFloodgateSpells) * 400f;
score += (v.BotHand - v.EnemyHand) * HandCardValue;
score += v.Bonus;
if (CounterAttackWeight > 0f && enemyBestAtk > 0)
{
// What the enemy's best attacker takes from us next turn if nothing changes.
float threatened;
if (v.Bot.Count == 0)
threatened = enemyBestAtk;
else if (botWeakestAtkPos != int.MaxValue && botWeakestAtkPos < enemyBestAtk)
threatened = enemyBestAtk - botWeakestAtkPos;
else
threatened = 0f;
score -= threatened * wBotLp * CounterAttackWeight;
}
return score;
}
/// The standalone worth of one monster on either side (always positive;
/// the caller applies the sign).
public static float MonsterValue(MonsterView m)
{
float value = 250f + 0.35f * Math.Max(0, m.Power);
if (!m.Known)
value += 50f; // a set card the enemy bothered to set is worth a little more than its estimate
value += m.Threat * 600f;
return value;
}
/// 0..1 threat beyond stats, from WindBot's curated lists (public info only).
public static float ThreatOf(ClientCard card)
{
if (card == null || card.Id == 0) return 0f;
float threat = 0f;
if (card.IsFloodgate()) threat = Math.Max(threat, 1f);
if (card.IsMonsterInvincible()) threat = Math.Max(threat, 0.8f);
if (card.IsMonsterDangerous()) threat = Math.Max(threat, 0.7f);
if (card.IsShouldNotBeTarget()) threat = Math.Max(threat, 0.3f);
return threat;
}
/// The board with one more bot monster (a summon about to happen).
public static BoardView WithBotMonster(BoardView board, int atk, int def, bool attackPos, bool faceUp, float threat = 0f)
{
var next = board.Clone();
next.Bot.Add(new MonsterView
{
Card = null,
Atk = atk,
Def = def,
AttackPos = attackPos,
FaceUp = faceUp,
Known = true,
Threat = threat,
});
return next;
}
/// The board minus the bot's N least valuable monsters (tributes / materials).
public static BoardView WithoutCheapestBotMonsters(BoardView board, int count)
{
var next = board.Clone();
for (int n = 0; n < count && next.Bot.Count > 0; n++)
{
int worst = 0;
float worstValue = float.MaxValue;
for (int i = 0; i < next.Bot.Count; i++)
{
float value = MonsterValue(next.Bot[i]);
if (value < worstValue) { worstValue = value; worst = i; }
}
next.Bot.RemoveAt(worst);
}
return next;
}
/// The board minus the enemy monster at <paramref name="index"/> (a removal about to resolve).
public static BoardView WithoutEnemyMonster(BoardView board, int index)
{
var next = board.Clone();
if (index >= 0 && index < next.Enemy.Count) next.Enemy.RemoveAt(index);
return next;
}
/// The board minus the enemy's N most valuable monsters (a "destroy N" with no target yet).
public static BoardView WithoutBestEnemyMonsters(BoardView board, int count)
{
var next = board.Clone();
for (int n = 0; n < count && next.Enemy.Count > 0; n++)
next.Enemy.RemoveAt(MostValuable(next.Enemy));
return next;
}
/// Index of the most valuable monster of a list (-1 when empty).
public static int MostValuable(List<MonsterView> list)
{
int best = -1;
float bestValue = float.MinValue;
for (int i = 0; i < list.Count; i++)
{
float value = MonsterValue(list[i]);
if (value > bestValue) { bestValue = value; best = i; }
}
return best;
}
/// Index of the least valuable monster of a list (-1 when empty).
public static int LeastValuable(List<MonsterView> list)
{
int worst = -1;
float worstValue = float.MaxValue;
for (int i = 0; i < list.Count; i++)
{
float value = MonsterValue(list[i]);
if (value < worstValue) { worstValue = value; worst = i; }
}
return worst;
}
/// Sum of the enemy's face-up attack-position ATK: what they swing for next turn if nothing changes.
public static int EnemyAttackTotal(ClientField enemy)
{
int total = 0;
foreach (var m in enemy.GetMonsters())
if (m.Id != 0 && m.IsFaceup() && m.IsAttack())
total += Math.Max(0, m.Attack);
return total;
}
/// Highest face-up enemy ATK the bot can see (0 when none).
public static int BestEnemyAttack(ClientField enemy)
{
int best = 0;
foreach (var m in enemy.GetMonsters())
if (m.Id != 0 && m.IsFaceup() && m.IsAttack())
best = Math.Max(best, m.Attack);
return best;
}
/// Highest battle power (ATK or DEF, by position) among face-up enemy monsters.
public static int BestEnemyPower(ClientField enemy)
{
int best = 0;
foreach (var m in enemy.GetMonsters())
if (m.Id != 0 && m.IsFaceup())
best = Math.Max(best, m.GetDefensePower());
return best;
}
/// <summary>
/// Life Points OUR board could take off the enemy if every monster we
/// control attacked right now. The mirror of
/// <see cref="EnemyAttackTotal"/>, but the enemy's monsters block:
/// each of their face-up monsters eats one of our attackers (the
/// smallest one that can be spared), so only the surplus is damage.
/// Deliberately optimistic-but-bounded — it is a gate ("could this
/// swing win the duel?"), not a battle simulation: attack negation,
/// piercing, effect damage and face-down monsters are not modelled, and
/// a face-down enemy monster is counted as one blocker of unknown size
/// (<see cref="DefaultUnknownPower"/>).
/// </summary>
public static int SwingDamage(ClientField bot, ClientField enemy, int unknownPower = DefaultUnknownPower)
{
var attackers = new List<int>();
foreach (var m in bot.GetMonsters())
if (m != null && m.IsFaceup() && m.IsAttack())
attackers.Add(Math.Max(0, m.Attack));
var blockers = new List<int>();
foreach (var m in enemy.GetMonsters())
if (m != null)
blockers.Add(m.Id == 0 || !m.IsFaceup() ? unknownPower : Math.Max(0, m.GetDefensePower()));
return SwingDamage(attackers, blockers);
}
/// <summary>The same sum on a predicted board.</summary>
public static int SwingDamage(BoardView view)
{
var attackers = new List<int>();
foreach (var m in view.Bot)
if (m.FaceUp && m.AttackPos) attackers.Add(Math.Max(0, m.Atk));
var blockers = new List<int>();
foreach (var m in view.Enemy)
blockers.Add(Math.Max(0, m.Power));
return SwingDamage(attackers, blockers);
}
/// Biggest attacker against biggest blocker: what gets through.
private static int SwingDamage(List<int> attackers, List<int> blockers)
{
if (attackers.Count == 0) return 0;
attackers.Sort();
attackers.Reverse();
blockers.Sort();
blockers.Reverse();
int damage = 0;
for (int i = 0; i < attackers.Count; i++)
{
if (i < blockers.Count) damage += Math.Max(0, attackers[i] - blockers[i]);
else damage += attackers[i]; // nothing left to block: straight to the face
}
return damage;
}
public static float Clamp01(float f) => f < 0f ? 0f : f > 1f ? 1f : f;
}
}
+808
View File
@@ -0,0 +1,808 @@
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using WindBot.Game;
using YGOSharp.OCGWrapper.Enums;
namespace YGOLegacy.Bot
{
// YGOLegacy.Duel is a namespace (Scripts/Duel/) and would shadow WindBot's
// Duel type from inside YGOLegacy.Bot; alias the type explicitly.
using Duel = WindBot.Game.Duel;
/// <summary>
/// The per-character rule layer of SmartExecutor, loaded from
/// <c>Data/Characters/&lt;id&gt;/brain.json</c> (schema: README, "SmartExecutor
/// brain.json"; documented example: <c>Data/Characters/_template/brain.json</c>).
/// Everything here is optional — a missing or empty file yields
/// <see cref="Empty"/> and the executor plays on its evaluator alone.
///
/// Newtonsoft POCO: fields only, every collection defaulted, unknown keys
/// (including "_comment"-style documentation keys) ignored. Card ids are the
/// ygopro passcodes; JSON object keys are strings ("12345678") and Newtonsoft
/// converts them to the int keys used here.
/// </summary>
public class BrainRules
{
/// Card id -> weight. Positive = prefer summoning/activating/searching it,
/// negative = avoid. Unlisted = 0. One unit is worth roughly one monster
/// on the evaluator's scale.
public Dictionary<int, float> priorities = new();
/// Cards the bot must never summon, set or activate itself (Exodia
/// pieces, hand traps it should hold, cards a human wants to keep as bait).
public List<int> never = new();
/// Ordered scripted lines. Combos are tried in file order and each one
/// walks its steps in order; while a combo is viable its cards are
/// reserved for it and the generic layer leaves them alone.
public List<Combo> combos = new();
/// Card id -> "attack" | "defense" | "set" | "faceup": the position to put
/// that card in whenever the core asks (special summons, flips) or a
/// summon-or-set choice arises. On a NORMAL summon "defense" means Set
/// (there is no face-up-defence normal summon); "faceup" = normal summon
/// face-up but otherwise behave like "defense" (self-switching monsters
/// such as "If this card is Summoned: change it to Defense Position").
/// Unlisted = evaluator decides.
public Dictionary<int, string> positions = new();
public Responses responses = new();
public BattleRules battle = new();
/// Card id -> what its effect does to the board (TICKET-040). The
/// executor simulates a modelled effect with EffectSimulator and scores
/// the predicted board; a card without a model keeps the flat scoring.
public Dictionary<int, EffectModel> effects = new();
/// TICKET-046 (E4, 2026-08-18): cards the discard/tribute/cost picker
/// must give up LAST — a deck's one-of finisher, so a mill combo cannot
/// feed it to the GY. Consulted ONLY by cost-shaped `select` prompts
/// (discard / tribute / release / to-grave / material); it changes no
/// other score, which is exactly what makes it different from
/// <see cref="priorities"/> (priority doubles as OwnCardValue
/// everywhere and is measured-poisonous on some decks). A kept card is
/// still paid when nothing else is legal — this is an ordering, not a
/// veto.
public List<int> keep = new();
/// Path the rules were read from; null for Empty. Not JSON.
[JsonIgnore] public string source;
/// Human-readable notes from Normalize (models dropped for an unknown
/// kind etc.); the executor logs them once at construction. Not JSON.
[JsonIgnore] public List<string> warnings = new();
public static readonly BrainRules Empty = new() { source = null };
[JsonIgnore]
public bool IsEmpty =>
priorities.Count == 0 && never.Count == 0 && combos.Count == 0 && positions.Count == 0
&& responses.IsEmpty && battle.IsEmpty && effects.Count == 0 && keep.Count == 0;
public float PriorityOf(int cardId)
=> cardId != 0 && priorities.TryGetValue(cardId, out var p) ? p : 0f;
public bool IsForbidden(int cardId) => cardId != 0 && never.Contains(cardId);
/// E4 (2026-08-18): this id is on the `keep` list — pay it LAST at a
/// discard/tribute/cost prompt. No other scoring path asks.
public bool IsKept(int cardId) => cardId != 0 && keep.Count > 0 && keep.Contains(cardId);
/// The effect model for a card, or null. <paramref name="desc"/> is the
/// effect description being asked about (-1 = unknown/any); a model
/// pinned to one desc only answers for that desc.
public EffectModel EffectFor(int cardId, int desc = -1)
{
if (cardId == 0 || !effects.TryGetValue(cardId, out var m) || m == null) return null;
if (m.desc >= 0 && desc >= 0 && m.desc != desc) return null;
return m;
}
/// "attack" | "defense" | "set" | "faceup" for a card, or null.
public string PositionFor(int cardId)
=> cardId != 0 && positions.TryGetValue(cardId, out var p) && !string.IsNullOrEmpty(p)
? p.Trim().ToLowerInvariant()
: null;
/// <summary>
/// Read <c>&lt;directory&gt;/&lt;fileName&gt;</c> (default
/// <c>brain.json</c>). A per-deck file name that does not exist falls
/// back to <c>brain.json</c>. Missing file -> Empty; a malformed file ->
/// Empty plus an error string for the caller to log.
/// Pure file IO + JSON: safe on the WindBot thread.
/// </summary>
public static BrainRules Load(string directory, out string error, string fileName = null)
{
error = null;
if (string.IsNullOrEmpty(directory))
return Empty;
var wanted = string.IsNullOrWhiteSpace(fileName) ? "brain.json" : fileName.Trim();
var path = Path.Combine(directory, wanted).Replace('\\', '/');
if (!File.Exists(path) && wanted != "brain.json")
path = Path.Combine(directory, "brain.json").Replace('\\', '/');
if (!File.Exists(path))
return Empty;
try
{
var rules = JsonConvert.DeserializeObject<BrainRules>(File.ReadAllText(path));
if (rules == null)
return Empty;
rules.Normalize();
rules.source = path;
return rules;
}
catch (Exception e)
{
error = path + ": " + e.Message;
return Empty;
}
}
private void Normalize()
{
priorities ??= new Dictionary<int, float>();
never ??= new List<int>();
combos ??= new List<Combo>();
combos.RemoveAll(c => c == null);
foreach (var combo in combos)
combo.Normalize();
positions ??= new Dictionary<int, string>();
responses ??= new Responses();
responses.Normalize();
battle ??= new BattleRules();
battle.Normalize();
effects ??= new Dictionary<int, EffectModel>();
keep ??= new List<int>();
keep.RemoveAll(id => id == 0);
warnings ??= new List<string>();
var dropped = new List<int>();
foreach (var kv in effects)
{
if (kv.Value == null) { dropped.Add(kv.Key); continue; }
kv.Value.Normalize();
if (kv.Value.Kind == EffectKind.Unknown)
{
warnings.Add("effects." + kv.Key + ": unknown kind '" + kv.Value.kind + "' (model ignored)");
dropped.Add(kv.Key);
}
}
foreach (var id in dropped) effects.Remove(id);
}
}
// =====================================================================
// Effect model (TICKET-040)
// =====================================================================
public enum EffectKind
{
Unknown, Destroy, Bounce, Banish, Negate, Draw, Search, Burn, Gain, Boost, Protect, Summon, Fusion, Position, LevelChange, Other,
}
public enum EffectScope { Enemy, Self, Any, Both }
public enum EffectWhat { Monsters, Backrow, Any, Hand, Deck }
public enum EffectTrigger { Own, EnemySummon, EnemyAttack, EnemyActivate, Standby, End, Any }
/// Where a summon/fusion takes its materials from. <see cref="Any"/> = the
/// cheapest legal source: hand first, then the field.
public enum EffectFrom { Any, Hand, Field, Grave }
/// <summary>
/// What one card's effect does to the board, declared in brain.json
/// (<c>effects</c> block; README "SmartExecutor brain.json", template
/// <c>Data/Characters/_template/brain.json</c>) and generated by
/// /bot-brain from the card text. Read by <see cref="EffectSimulator"/>.
/// Every field is optional; the raw JSON strings stay for logging and
/// the parsed enums live in the PascalCase properties.
/// </summary>
public class EffectModel
{
/// destroy | bounce | banish | negate | draw | search | burn | gain | boost | protect | summon | position | other
public string kind = "other";
/// enemy (default) | self | any (we choose a side, treated as enemy) | both (symmetric)
public string scope = "enemy";
/// monsters (default) | backrow | any | hand | deck — the affected zone
/// (for summon: where the body comes from).
public string what = "monsters";
/// 1 (default) or "all".
public string count = "1";
public EffectFilter filter;
/// Draws / LP / ATK boost / summoned body ATK.
public float amount;
/// Multiply <see cref="amount"/> by a public count (see
/// EffectSimulator.PerCount): ownGraveMonsters | ownGraveInsects |
/// ownMonsters | enemyMonsters | enemyBackrow | ownHand | enemyHand.
public string per;
/// own (default) | enemySummon | enemyAttack | enemyActivate | standby | end | any
public string trigger = "own";
public EffectCost cost;
/// Pin to one effect description of a multi-effect card; -1 = any.
public int desc = -1;
/// Summoned body stats (summon kind); default = amount / amount.
public int? atk, def;
/// <c>levelChange</c> only: the Level the affected monsters BECOME
/// ("its Level becomes 6"). Unset + <see cref="amount"/> non-zero = a
/// Level SHIFT of that many ("gain 1 Level", "-2"); unset with amount 0
/// = the monster may become ANY Level, i.e. a declared Level (Gagaga
/// Magician). Only our own Levels are scored — see EffectSimulator.
public int? level;
/// True: this card punishes whoever attacks it (it zeroes or negates the
/// attacker — Sanga of the Thunder / Kazejin / Suijin). The attack
/// chooser then refuses to attack this card while the ENEMY controls it
/// face-up, exactly like a losing trade (so only
/// <see cref="BattleRules.attackInto"/> can override it). It says
/// nothing about what the card does when WE own it — that is the rest
/// of the model. Simplification: "once per turn" is not tracked, so the
/// card is treated as always able to punish.
public bool onAttacked;
/// <c>summon</c> / <c>fusion</c>: how many cards of ours the summon
/// SPENDS (Fusion Materials, tributes a `cost` does not already cover).
/// 0 = unset; a <c>fusion</c> with no value pays for 2, the usual
/// Polymerization cost. Where they come from is <see cref="from"/>.
public int materials;
/// any (default: hand first, then the field) | hand | field | grave.
/// Only <c>grave</c> costs the board nothing — Miracle Fusion banishing
/// its materials out of the GY is free, Polymerization out of the hand
/// is two cards, a contact fusion off the field is two monsters.
public string from;
/// A cost the card only charges LATER in the same turn: Power Bond's
/// "take damage equal to the original ATK" in the End Phase. Scored on
/// the predicted board unless the swing it buys ends the duel first —
/// see EffectSimulator.ApplyDelayedCost.
public DelayedCost delayed;
/// True: what this effect boosted or summoned is destroyed at the end of
/// the turn (Limiter Removal). Same End-Phase rule as
/// <see cref="delayed"/>: the monsters the model matches are taken off
/// the predicted board, after the extra damage they buy this turn is
/// credited.
public bool endTurnDestroy;
// =================================================================
// E1 / E3 (2026-08-18) — the opponent's half of the card
// =================================================================
/// True: resolving this effect HURTS US on balance whatever the board
/// looks like — Mimighoul Dragon's FLIP destroys our own face-up
/// monsters and then hands the card to the opponent; Chewbone's FLIP
/// gives the opponent three tokens. The executor never activates such a
/// card voluntarily and never Flip Summons it, but — unlike
/// <see cref="BrainRules.never"/> — it may still be Set or Summoned as a
/// body, and a combo step may still fire it deliberately. (Measured on
/// skipper: a `never` on Mimighoul Dragon produced 13 passive-endturn
/// blunders, because the bot then sat on an empty board holding it.)
public bool selfHarm;
/// Cards the OPPONENT draws when this resolves (Spellbook Inside the
/// Pot 3, The Gift of Greed 2, Upstart Goblin 1 — the half the schema
/// used to leave free). Priced as enemy hand size + their dig, minus
/// what the draw burns out of their Deck (see EffectSimulator).
public int enemyDraw;
/// Cards this sends from the OPPONENT'S Deck to their GY (a mill).
/// Pure deck burn: it does not change their hand.
public int enemyMill;
/// Cards the OPPONENT discards from hand (good for us).
public int enemyDiscard;
/// LP the OPPONENT gains (Upstart Goblin 1000). Use
/// <c>kind: "gain", scope: "enemy"</c> when the gain IS the effect;
/// this field is for the rider on some other effect.
public int enemyGain;
/// A body this hands the OPPONENT (Mimighoul Dragon summons itself to
/// their field; a token-giver). Their side of the board, so the
/// evaluator subtracts it.
public EnemySummon enemySummon;
/// True when any opponent-side term is set: the model prices both halves.
[JsonIgnore] public bool HasEnemySide
=> enemyDraw != 0 || enemyMill != 0 || enemyDiscard != 0 || enemyGain != 0 || enemySummon != null;
[JsonIgnore] public EffectKind Kind { get; private set; }
[JsonIgnore] public EffectFrom From { get; private set; }
[JsonIgnore] public EffectScope Scope { get; private set; }
[JsonIgnore] public EffectWhat What { get; private set; }
[JsonIgnore] public EffectTrigger Trigger { get; private set; }
[JsonIgnore] public bool CountAll { get; private set; }
[JsonIgnore] public int Count { get; private set; } = 1;
/// How many of our cards this summon/fusion spends (a fusion with no
/// explicit count pays the usual two).
[JsonIgnore] public int MaterialCount => materials > 0 ? materials : (Kind == EffectKind.Fusion ? 2 : 0);
/// A body arrives: summon and fusion are the same thing to the board.
[JsonIgnore] public bool IsSummon => Kind == EffectKind.Summon || Kind == EffectKind.Fusion;
[JsonIgnore] public bool HasDelayedCost => (delayed != null && delayed.lp > 0) || endTurnDestroy;
[JsonIgnore] public bool IsRemoval => Kind == EffectKind.Destroy || Kind == EffectKind.Bounce || Kind == EffectKind.Banish;
/// A one-shot pick-one removal: the removalPatience knob applies.
[JsonIgnore] public bool IsSingleRemoval => IsRemoval && !CountAll && Count == 1;
public void Normalize()
{
Kind = ParseKind(kind);
Scope = ParseScope(scope);
What = ParseWhat(what);
Trigger = ParseTrigger(trigger);
From = ParseFrom(from);
if (materials < 0) materials = 0;
if (enemyDraw < 0) enemyDraw = 0;
if (enemyMill < 0) enemyMill = 0;
if (enemyDiscard < 0) enemyDiscard = 0;
if (enemyGain < 0) enemyGain = 0;
enemySummon?.Normalize();
delayed?.Normalize();
var c = (count ?? "1").Trim().ToLowerInvariant();
if (c == "all" || c == "*")
{
CountAll = true;
Count = 0;
}
else
{
CountAll = false;
Count = int.TryParse(c, out var n) && n > 0 ? n : 1;
}
filter?.Normalize();
cost?.Normalize();
}
public static EffectKind ParseKind(string s)
{
switch ((s ?? string.Empty).Trim().ToLowerInvariant())
{
case "destroy": return EffectKind.Destroy;
case "bounce":
case "return": return EffectKind.Bounce;
case "banish":
case "remove": return EffectKind.Banish;
case "negate": return EffectKind.Negate;
case "draw": return EffectKind.Draw;
case "search": return EffectKind.Search;
case "burn":
case "damage": return EffectKind.Burn;
case "gain":
case "heal": return EffectKind.Gain;
case "boost":
case "equip": return EffectKind.Boost;
case "protect": return EffectKind.Protect;
case "summon":
case "spsummon": return EffectKind.Summon;
case "fusion":
case "fusionsummon": return EffectKind.Fusion;
case "position": return EffectKind.Position;
case "levelchange":
case "level": return EffectKind.LevelChange;
case "other":
case "": return EffectKind.Other;
default: return EffectKind.Unknown;
}
}
public static EffectScope ParseScope(string s)
{
switch ((s ?? string.Empty).Trim().ToLowerInvariant())
{
case "self":
case "own": return EffectScope.Self;
case "any":
case "either": return EffectScope.Any;
case "both":
case "all":
case "symmetric": return EffectScope.Both;
default: return EffectScope.Enemy;
}
}
public static EffectWhat ParseWhat(string s)
{
switch ((s ?? string.Empty).Trim().ToLowerInvariant())
{
case "backrow":
case "spells":
case "traps":
case "spelltrap": return EffectWhat.Backrow;
case "any":
case "cards":
case "field": return EffectWhat.Any;
case "hand": return EffectWhat.Hand;
case "deck":
case "grave":
case "graveyard": return EffectWhat.Deck;
default: return EffectWhat.Monsters;
}
}
public static EffectFrom ParseFrom(string s)
{
switch ((s ?? string.Empty).Trim().ToLowerInvariant())
{
case "hand": return EffectFrom.Hand;
case "field": return EffectFrom.Field;
case "grave":
case "graveyard":
case "gy":
case "deck": return EffectFrom.Grave; // off-field: costs the board nothing
default: return EffectFrom.Any;
}
}
public static EffectTrigger ParseTrigger(string s)
{
switch ((s ?? string.Empty).Trim().ToLowerInvariant())
{
case "enemysummon": return EffectTrigger.EnemySummon;
case "enemyattack": return EffectTrigger.EnemyAttack;
case "enemyactivate": return EffectTrigger.EnemyActivate;
case "standby": return EffectTrigger.Standby;
case "end": return EffectTrigger.End;
case "any": return EffectTrigger.Any;
default: return EffectTrigger.Own;
}
}
public override string ToString()
=> Kind.ToString().ToLowerInvariant() + " " + Scope.ToString().ToLowerInvariant() + " " + What.ToString().ToLowerInvariant()
+ " x" + (CountAll ? "all" : Count.ToString()) + (amount != 0 ? " amount " + amount : string.Empty)
+ (per != null ? " per " + per : string.Empty)
+ (level.HasValue ? " level " + level.Value : string.Empty)
+ (MaterialCount > 0 ? " materials " + MaterialCount + " from " + From.ToString().ToLowerInvariant() : string.Empty)
+ (delayed != null && delayed.lp > 0 ? " delayed lp " + delayed.lp : string.Empty)
+ (endTurnDestroy ? " endTurnDestroy" : string.Empty)
+ (onAttacked ? " onAttacked" : string.Empty);
}
/// A cost the card charges later in the same turn (see EffectModel.delayed).
/// <summary>
/// A body this effect hands the OPPONENT (E3, 2026-08-18): Mimighoul
/// Dragon Special Summoning itself to their field, a card that gives them
/// tokens. Stats are the printed ones; <c>count</c> defaults to 1.
/// </summary>
public class EnemySummon
{
public int atk;
public int def;
public int count = 1;
public void Normalize()
{
if (atk < 0) atk = 0;
if (def < 0) def = 0;
if (count < 1) count = 1;
}
}
public class DelayedCost
{
/// Life Points we lose in the End Phase (Power Bond: the original ATK).
public int lp;
public void Normalize() { if (lp < 0) lp = 0; }
}
/// Which cards an effect touches; every field optional, all must hold.
/// Hidden cards (enemy face-downs) never match a stat filter.
public class EffectFilter
{
public int? levelEq, levelMin, levelMax;
public int? atkMin, atkMax;
/// Race name (Insect, Dragon, ...) — case-insensitive, WindBot's CardRace names plus common aliases.
public string race;
public bool? faceup;
/// Exactly these card ids. The only way to say "archetype" — a race or a
/// Level cannot express "Chronomaly". A hidden card never matches.
public List<int> ids;
[JsonIgnore] public int RaceMask { get; private set; }
public void Normalize()
{
RaceMask = ParseRace(race);
if (ids != null && ids.Count == 0) ids = null;
}
[JsonIgnore] public bool IsEmpty => !HasStatFilter && !faceup.HasValue;
[JsonIgnore] private bool HasStatFilter => levelEq.HasValue || levelMin.HasValue || levelMax.HasValue || atkMin.HasValue || atkMax.HasValue || RaceMask != 0 || ids != null;
public static int ParseRace(string s)
{
if (string.IsNullOrWhiteSpace(s)) return 0;
var t = s.Trim().Replace("-Type", string.Empty).Replace(" ", string.Empty).Replace("-", string.Empty).ToLowerInvariant();
switch (t)
{
case "spellcaster": return (int)CardRace.SpellCaster;
case "wingedbeast": case "windbeast": return (int)CardRace.WindBeast;
case "psychic": case "psycho": return (int)CardRace.Psycho;
case "beastwarrior": return (int)CardRace.BeastWarrior;
case "seaserpent": return (int)CardRace.SeaSerpent;
case "divinebeast": return (int)CardRace.DivineBeast;
}
foreach (CardRace r in Enum.GetValues(typeof(CardRace)))
if (r.ToString().ToLowerInvariant() == t) return (int)r;
return 0;
}
/// True when a KNOWN card passes; a hidden card (Id == 0 / face-down)
/// passes only when nothing about its stats is required.
public bool Matches(ClientCard c)
{
if (c == null) return false;
bool hidden = c.Id == 0 || c.IsFacedown();
if (faceup == true && hidden) return false;
if (faceup == false && !hidden) return false;
if (hidden) return !HasStatFilter;
if (ids != null && !ids.Contains(c.Id)) return false;
int level = c.Level > 0 || c.Data == null ? c.Level : c.Data.Level;
int atk = c.Location == CardLocation.MonsterZone || c.Data == null ? c.Attack : c.Data.Attack;
if (levelEq.HasValue && level != levelEq.Value) return false;
if (levelMin.HasValue && level < levelMin.Value) return false;
if (levelMax.HasValue && level > levelMax.Value) return false;
if (atkMin.HasValue && atk < atkMin.Value) return false;
if (atkMax.HasValue && atk > atkMax.Value) return false;
if (RaceMask != 0 && (c.Race & RaceMask) == 0 && (c.Data == null || (c.Data.Race & RaceMask) == 0)) return false;
return true;
}
}
public class EffectCost
{
public int lp;
public int tribute;
public int discard;
public void Normalize()
{
if (lp < 0) lp = 0;
if (tribute < 0) tribute = 0;
if (discard < 0) discard = 0;
}
[JsonIgnore] public bool IsEmpty => lp == 0 && tribute == 0 && discard == 0;
}
/// One scripted line: steps executed in order, at most once per turn (or duel).
public class Combo
{
public string name;
/// Preconditions checked when the first step is about to fire.
public Condition when;
public List<ComboStep> steps = new();
/// Default true: once the last step fired the combo rests until next turn.
public bool oncePerTurn = true;
public bool oncePerDuel;
public void Normalize()
{
steps ??= new List<ComboStep>();
steps.RemoveAll(s => s == null || s.card == 0);
foreach (var step in steps)
step.Normalize();
}
}
public class ComboStep
{
public int card;
/// "Summon" | "SpSummon" | "Activate" | "Set" | "Repos" (case-insensitive).
public string action = "Activate";
/// For Activate: only fire for this effect description (-1 = any). Effect
/// descriptions are card-id*16+n; check the log with Verbose on.
public int desc = -1;
/// Extra preconditions checked when this step is about to fire.
public Condition when;
/// True: the combo may continue past this step even if it never became
/// possible (e.g. an optional extender).
public bool optional;
[JsonIgnore] public RuleAction Action { get; private set; }
public void Normalize()
{
Action = ParseAction(action);
}
public static RuleAction ParseAction(string s)
{
switch ((s ?? string.Empty).Trim().ToLowerInvariant())
{
case "summon": return RuleAction.Summon;
case "spsummon":
case "specialsummon": return RuleAction.SpSummon;
case "set": return RuleAction.Set;
case "repos":
case "reposition":
case "flip": return RuleAction.Repos;
default: return RuleAction.Activate;
}
}
}
public enum RuleAction { Summon, SpSummon, Activate, Set, Repos }
/// <summary>
/// A small conjunction of board tests. Every listed field must hold; an
/// omitted field is not tested. Only public information is read (the bot's
/// own cards, face-up enemy cards, counts, LP, turn, phase).
/// </summary>
public class Condition
{
public int[] handHas;
public int[] handLacks;
public int[] fieldHas;
public int[] fieldLacks;
/// Every id is in our hand OR face-up on our field. The pieces of a
/// contact-fusion line (Valkyrion's three Magnet Warriors) are sent
/// "from your hand or field", and the executor Normal Summons each one
/// the turn it is drawn, so neither <see cref="handHas"/> (all three in
/// hand at once) nor <see cref="fieldHas"/> (all three face-up) is ever
/// true — the combo could never fire.
public int[] handOrFieldHas;
public int[] graveHas;
public int[] graveLacks;
public int[] banishedHas;
public int[] extraHas;
public int[] enemyFieldHas;
public int[] enemyFieldLacks;
public int? handMin, handMax;
public int? botMonstersMin, botMonstersMax;
public int? enemyMonstersMin, enemyMonstersMax;
public int? enemyBackrowMax;
public int? turnMin, turnMax;
/// "main1" | "main2" | "main" | "battle" | "enemy" (enemy turn); omitted = any.
public string phase;
public int? lpBelow, enemyLpBelow;
public bool? goingFirst;
/// True: no monster of the bot's was summoned yet this phase
/// (Duel.LastSummonPlayer != 0) — the closest public proxy for "normal
/// summon still available".
public bool? noSummonYet;
/// True: the monsters we control could take the enemy's Life Points to
/// 0 this turn if they all attacked now (each enemy face-up monster
/// blocks the attacker nearest its own power — see
/// <see cref="BoardEvaluator.SwingDamage(ClientField, ClientField)"/>).
/// False: they could not. The gate for a line that is only worth its
/// cost as a finisher (Limiter Removal, Power Bond).
public bool? lethal;
public bool Holds(ClientField bot, ClientField enemy, Duel duel)
{
if (!All(handHas, id => bot.HasInHand(id))) return false;
if (!None(handLacks, id => bot.HasInHand(id))) return false;
if (!All(fieldHas, id => OnField(bot, id))) return false;
if (!None(fieldLacks, id => OnField(bot, id))) return false;
if (!All(handOrFieldHas, id => bot.HasInHand(id) || OnField(bot, id))) return false;
if (!All(graveHas, id => bot.HasInGraveyard(id))) return false;
if (!None(graveLacks, id => bot.HasInGraveyard(id))) return false;
if (!All(banishedHas, id => bot.HasInBanished(id))) return false;
if (!All(extraHas, id => bot.HasInExtra(id))) return false;
if (!All(enemyFieldHas, id => OnField(enemy, id))) return false;
if (!None(enemyFieldLacks, id => OnField(enemy, id))) return false;
int hand = bot.GetHandCount();
if (handMin.HasValue && hand < handMin.Value) return false;
if (handMax.HasValue && hand > handMax.Value) return false;
int botMonsters = bot.GetMonsterCount();
if (botMonstersMin.HasValue && botMonsters < botMonstersMin.Value) return false;
if (botMonstersMax.HasValue && botMonsters > botMonstersMax.Value) return false;
int enemyMonsters = enemy.GetMonsterCount();
if (enemyMonstersMin.HasValue && enemyMonsters < enemyMonstersMin.Value) return false;
if (enemyMonstersMax.HasValue && enemyMonsters > enemyMonstersMax.Value) return false;
if (enemyBackrowMax.HasValue && enemy.GetSpellCount() > enemyBackrowMax.Value) return false;
if (turnMin.HasValue && duel.Turn < turnMin.Value) return false;
if (turnMax.HasValue && duel.Turn > turnMax.Value) return false;
if (lpBelow.HasValue && bot.LifePoints >= lpBelow.Value) return false;
if (enemyLpBelow.HasValue && enemy.LifePoints >= enemyLpBelow.Value) return false;
if (goingFirst.HasValue && duel.IsFirst != goingFirst.Value) return false;
if (noSummonYet == true && duel.LastSummonPlayer == 0) return false;
if (lethal.HasValue && (BoardEvaluator.SwingDamage(bot, enemy) >= enemy.LifePoints) != lethal.Value) return false;
if (!string.IsNullOrEmpty(phase))
{
switch (phase.Trim().ToLowerInvariant())
{
case "main1": if (!(duel.Player == 0 && duel.Phase == DuelPhase.Main1)) return false; break;
case "main2": if (!(duel.Player == 0 && duel.Phase == DuelPhase.Main2)) return false; break;
case "main": if (!(duel.Player == 0 && (duel.Phase == DuelPhase.Main1 || duel.Phase == DuelPhase.Main2))) return false; break;
case "battle": if (!IsBattle(duel.Phase)) return false; break;
case "enemy": if (duel.Player != 1) return false; break;
}
}
return true;
}
private static bool IsBattle(DuelPhase p)
=> p == DuelPhase.BattleStart || p == DuelPhase.BattleStep || p == DuelPhase.Damage
|| p == DuelPhase.DamageCal || p == DuelPhase.Battle;
private static bool OnField(ClientField field, int id)
=> field.HasInMonstersZone(id) || field.HasInSpellZone(id);
private static bool All(int[] ids, Func<int, bool> test)
{
if (ids == null) return true;
foreach (var id in ids)
if (!test(id)) return false;
return true;
}
private static bool None(int[] ids, Func<int, bool> test)
{
if (ids == null) return true;
foreach (var id in ids)
if (test(id)) return false;
return true;
}
}
public class Responses
{
/// Card id -> "always" | "never" | "problematic" | "enemyTurn" | "default".
/// always: activate whenever legal; never: hold it; problematic: only when
/// the enemy shows a problematic card (AIUtil) or is chaining/summoning;
/// enemyTurn: any time during the enemy's turn or in response to them.
public Dictionary<int, string> chain = new();
/// Yes/no prompts: key = effect description (card id*16+n) or the bare
/// card id (matches every prompt of that card). Unlisted = yes.
public Dictionary<int, bool> yesNo = new();
/// Option prompts: card id -> zero-based index to pick for that card.
public Dictionary<int, int> options = new();
/// Option prompts: effect descriptions to prefer whenever offered.
public List<int> preferOptions = new();
[JsonIgnore]
public bool IsEmpty => chain.Count == 0 && yesNo.Count == 0 && options.Count == 0 && preferOptions.Count == 0;
public void Normalize()
{
chain ??= new Dictionary<int, string>();
yesNo ??= new Dictionary<int, bool>();
options ??= new Dictionary<int, int>();
preferOptions ??= new List<int>();
}
public ChainPolicy ChainPolicyOf(int cardId)
{
if (cardId == 0 || !chain.TryGetValue(cardId, out var s) || string.IsNullOrEmpty(s))
return ChainPolicy.Default;
switch (s.Trim().ToLowerInvariant())
{
case "always": return ChainPolicy.Always;
case "never": return ChainPolicy.Never;
case "problematic": return ChainPolicy.Problematic;
case "enemyturn": return ChainPolicy.EnemyTurn;
default: return ChainPolicy.Default;
}
}
/// The yes/no answer configured for a prompt, or null.
public bool? YesNoFor(int desc)
{
if (yesNo.TryGetValue(desc, out var v)) return v;
int cardId = desc >> 4;
if (cardId != 0 && yesNo.TryGetValue(cardId, out v)) return v;
return null;
}
}
public enum ChainPolicy { Default, Always, Never, Problematic, EnemyTurn }
public class BattleRules
{
/// Enemy card ids the bot may attack into even when the trade is losing
/// (suicide into a floodgate monster the deck cannot otherwise remove).
public List<int> attackInto = new();
/// The mirror of <see cref="attackInto"/>: enemy card ids the bot must
/// NEVER attack, however good the ATK/DEF arithmetic looks — a monster
/// that cannot be destroyed by battle, or one whose effect punishes the
/// attacker in a way BattlePredictor cannot see. Matched on FACE-UP
/// enemy cards only (a face-down is unknown). A HARD veto: it wins over
/// <see cref="attackInto"/> and over <see cref="alwaysAttackWith"/>.
/// For a punish that is the card's own quick effect, prefer
/// <c>effects.&lt;id&gt;.onAttacked</c> — same veto, one place.
public List<int> avoidAttackInto = new();
/// Bot monsters that must never declare an attack (Exodia bait, walls).
public List<int> neverAttackWith = new();
/// Bot monsters that attack whenever they legally can (battle-trigger effects).
public List<int> alwaysAttackWith = new();
/// False: never attack face-down monsters (default true, subject to the evaluator).
public bool attackFacedown = true;
[JsonIgnore]
public bool IsEmpty => attackInto.Count == 0 && avoidAttackInto.Count == 0 && neverAttackWith.Count == 0
&& alwaysAttackWith.Count == 0 && attackFacedown;
public void Normalize()
{
attackInto ??= new List<int>();
avoidAttackInto ??= new List<int>();
neverAttackWith ??= new List<int>();
alwaysAttackWith ??= new List<int>();
}
}
}
+584
View File
@@ -0,0 +1,584 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using YGOSharp.OCGWrapper.Enums;
namespace YGOLegacy.Bot
{
// YGOLegacy.Duel is a namespace (Scripts/Duel/) and would shadow WindBot's
// Duel type from inside YGOLegacy.Bot; alias the type explicitly.
using Duel = WindBot.Game.Duel;
/// <summary>
/// How much of the enemy's private state a brain may read (TICKET-042).
/// Per-deck knob <c>knobs.insight</c> (0/1/2), default <see cref="None"/>.
/// </summary>
public enum InsightLevel
{
/// Nothing — the brain sees exactly what its own seat is told (default).
None = 0,
/// The enemy's hand (ids) and what they drew this turn.
Hand = 1,
/// Hand plus their set backrow and face-down monsters.
Full = 2,
}
/// <summary>Which client a tapped stream belongs to.</summary>
public enum SeatRole
{
Player = 0,
Observer = 1,
}
/// <summary>
/// Duel state bus (TICKET-042). Both duel clients of a local duel run in
/// ONE process — the human's <c>TcpHelper</c> pump in the game, WindBot's
/// <c>GameClient</c> on its own thread, and in the standalone arena both
/// bots. Two additive <c>[YGOL]</c> receive-side taps publish
/// <c>(seatKey, packetBytes)</c> here; the bus feeds each stream into a
/// PASSIVE MIRROR — a private <see cref="Duel"/>/<see cref="ClientField"/>
/// pair driven by WindBot's own packet parser (<see cref="GameBehavior"/>
/// in its <c>[YGOL]</c> mirror mode: no connection, no answers, no AI of
/// its own). Reading another seat's mirror is reading exactly what THAT
/// seat was told, so a brain can see the human's hand without a new parser
/// and without any server change.
///
/// Nothing here touches UnityEngine, so it compiles into
/// <c>Tools/BotArena</c> as well as the game.
///
/// Cost when nobody listens: <see cref="Active"/> is false, so both taps
/// are one static bool read per packet and allocate nothing. The bus only
/// wakes up when a <see cref="SmartExecutor"/> asks for an insight level
/// above <see cref="InsightLevel.None"/>.
///
/// Threading: the human pump runs on Unity's main thread, each bot on its
/// own; every stream is guarded by its own lock, the registry by
/// <see cref="gate"/>. Locks are never held across a call back out.
///
/// Where it works: Solo (human vs bot), Bot Duel, in-editor and standalone
/// arena. Where it does NOT: remote online play — the opponent's client is
/// on another machine, there is no stream to tap, and
/// <c>Insight.Available</c> stays false so the brain behaves as today.
/// </summary>
public static class DuelStateBus
{
/// Seat key of the game's own (human) client; the role is appended
/// (<c>human:p0</c>, <c>human:p1</c>, <c>human:obs</c>) so a spectator
/// is never mistaken for a duelist.
public const string HumanSeatPrefix = "human";
private const string LogPrefix = "[YGOL bus] ";
/// <summary>
/// False (the default) = the taps do nothing at all. Set the moment a
/// brain asks for insight; cleared by <see cref="Reset"/>. Read on
/// every received packet, so it is a plain volatile field.
/// </summary>
public static volatile bool Active;
private static readonly object gate = new object();
private static readonly Dictionary<string, Stream> streams = new Dictionary<string, Stream>(StringComparer.Ordinal);
private static readonly Dictionary<string, string> deckPaths = new Dictionary<string, string>(StringComparer.Ordinal);
private static readonly Dictionary<string, InsightLevel> overrides = new Dictionary<string, InsightLevel>(StringComparer.Ordinal);
// ==================================================================
// Session
// ==================================================================
/// <summary>
/// Forget every stream, mirror and registered decklist. Call once per
/// duel, BEFORE the clients are spawned (the arena worker, Solo and Bot
/// Duel do). Insight OVERRIDES survive a reset — they are a property of
/// the run, not of the duel — clear them with <see cref="ClearOverrides"/>.
/// </summary>
public static void Reset()
{
lock (gate)
{
streams.Clear();
deckPaths.Clear();
Active = false;
}
}
/// <summary>
/// Force a seat's insight level regardless of its brain knob (the
/// arena's <c>--insightA/--insightB</c>). Null removes the override.
/// The key is the seat's WindBot <c>Name=</c> (its Username).
/// </summary>
public static void SetOverride(string seatKey, InsightLevel? level)
{
if (string.IsNullOrEmpty(seatKey)) return;
lock (gate)
{
if (level.HasValue) overrides[seatKey] = level.Value;
else overrides.Remove(seatKey);
}
}
public static void ClearOverrides()
{
lock (gate) overrides.Clear();
}
/// The forced level for a seat, or null when the brain's knob decides.
public static InsightLevel? OverrideFor(string seatKey)
{
if (string.IsNullOrEmpty(seatKey)) return null;
lock (gate)
return overrides.TryGetValue(seatKey, out var level) ? level : (InsightLevel?)null;
}
/// <summary>
/// Tell the bus which deck a seat is playing, so
/// <see cref="Insight.Decklist"/> and
/// <see cref="Insight.RemainingInDeck"/> work. The path is a
/// <c>Deck/</c> path without <c>.ydk</c> — exactly WindBot's
/// <c>DeckFile=</c> — and is resolved lazily, read-only, by WindBot's
/// own loader. Bot seats register themselves from the GameClient tap;
/// the human seat is registered by whoever launched the duel.
/// </summary>
public static void RegisterSeatDeck(string seatKey, string deckPath)
{
if (string.IsNullOrEmpty(seatKey) || string.IsNullOrEmpty(deckPath)) return;
lock (gate) deckPaths[seatKey] = deckPath;
}
// ==================================================================
// Taps ([YGOL] seams call these)
// ==================================================================
/// <summary>
/// The game's own client received a packet ([YGOL] seam in
/// <c>TcpHelper.PerFrameFunction</c>). <paramref name="selfType"/> is
/// <c>RoomServant.SelfType</c>: 0/1 are the duelists, anything else
/// (7) is a spectator.
/// </summary>
public static void OnHumanPacket(int selfType, byte[] packet)
{
if (!Active || packet == null || packet.Length < 2) return;
var player = selfType == 0 || selfType == 1;
var key = HumanSeatPrefix + ":" + (player ? "p" + selfType : "obs");
Feed(key, player ? SeatRole.Player : SeatRole.Observer, packet, null);
}
/// <summary>
/// A WindBot client received a packet ([YGOL] seam in
/// <c>GameClient.OnPacketReceived</c>). The client itself is passed so
/// the mirror can be built with that seat's identity (name, deck)
/// without a second registration call.
/// </summary>
public static void OnBotPacket(GameClient client, byte[] packet)
{
if (!Active || client == null || packet == null || packet.Length < 2) return;
if (string.IsNullOrEmpty(client.Username)) return;
Feed(client.Username, SeatRole.Player, packet, client.DeckFile);
}
/// <summary>
/// Generic tap: publish a raw STOC packet for a seat key. Kept public
/// for callers that have neither a GameClient nor the human pump.
/// </summary>
public static void OnPacket(string seatKey, byte[] packet)
{
if (!Active || string.IsNullOrEmpty(seatKey) || packet == null || packet.Length < 2) return;
Feed(seatKey, SeatRole.Player, packet, null);
}
private static void Feed(string seatKey, SeatRole role, byte[] packet, string deckPath)
{
Stream stream;
lock (gate)
{
if (!streams.TryGetValue(seatKey, out stream))
{
stream = new Stream(seatKey, role);
streams[seatKey] = stream;
}
stream.Role = role;
if (!string.IsNullOrEmpty(deckPath) && !deckPaths.ContainsKey(seatKey))
deckPaths[seatKey] = deckPath;
}
stream.Feed(packet);
}
// ==================================================================
// Reading
// ==================================================================
/// <summary>
/// The insight a seat gets on its opponent. <paramref name="level"/> is
/// what the seat's brain resolved (override, else knob). A level above
/// <see cref="InsightLevel.None"/> ACTIVATES the taps — that is the only
/// thing that ever does. Never returns null; a bus with no opposing
/// stream simply reports <c>Available == false</c>.
/// </summary>
public static Insight InsightFor(string seatKey, InsightLevel level)
{
if (level != InsightLevel.None) Active = true;
return new Insight(seatKey, level);
}
/// <summary>
/// The opposing stream of <paramref name="seatKey"/>: the one other
/// player stream in the session (observers never count). Null while
/// nobody else has spoken, or when the seating is ambiguous.
/// </summary>
internal static Stream OpponentOf(string seatKey)
{
lock (gate)
{
Stream found = null;
foreach (var pair in streams)
{
if (string.Equals(pair.Key, seatKey, StringComparison.Ordinal)) continue;
if (pair.Value.Role != SeatRole.Player) continue;
if (found != null) return null; // more than one candidate: don't guess
found = pair.Value;
}
return found;
}
}
/// The deck path registered for a seat (exact key, else the human one).
internal static string DeckPathOf(string seatKey)
{
if (string.IsNullOrEmpty(seatKey)) return null;
lock (gate)
{
if (deckPaths.TryGetValue(seatKey, out var path)) return path;
if (seatKey.StartsWith(HumanSeatPrefix, StringComparison.Ordinal)
&& deckPaths.TryGetValue(HumanSeatPrefix, out var human)) return human;
return null;
}
}
internal static void Warn(string message)
{
try { UnityEngine.Debug.LogWarning(LogPrefix + message); } catch (Exception) { }
}
// ==================================================================
// One tapped stream + its passive mirror
// ==================================================================
/// <summary>
/// One client's packet stream and the mirror it drives. All mirror
/// mutation and every read of it happen under <see cref="sync"/>, so a
/// brain on another thread never sees a half-applied message.
/// </summary>
internal sealed class Stream
{
internal readonly string Key;
internal SeatRole Role;
private readonly object sync = new object();
private GameBehavior mirror;
private bool mirrorFailed;
private int turnSeen = -1;
private List<int> handAtTurnStart = new List<int>();
internal Stream(string key, SeatRole role)
{
Key = key;
Role = role;
}
internal void Feed(byte[] packet)
{
lock (sync)
{
var behavior = Mirror();
if (behavior == null) return;
try
{
using (var ms = new MemoryStream(packet, false))
using (var reader = new BinaryReader(ms))
behavior.YGOL_MirrorPacket(reader);
}
catch (Exception e)
{
// A mirror is best-effort: one malformed message must
// never touch the real client that is sharing this
// process. Keep going; the state self-heals on the next
// full board update.
Warn(Key + ": mirror packet: " + e.GetType().Name + ": " + e.Message);
return;
}
TrackDraws(behavior);
}
}
/// Snapshot the hand at the start of each turn so "drawn this turn"
/// is a real diff rather than a guess.
private void TrackDraws(GameBehavior behavior)
{
var duel = behavior.YGOL_MirrorDuel;
if (duel == null || duel.Turn == turnSeen) return;
turnSeen = duel.Turn;
handAtTurnStart = Ids(duel.Fields[0]?.Hand);
}
private GameBehavior Mirror()
{
if (mirror != null || mirrorFailed) return mirror;
try
{
var info = new WindBotInfo
{
Name = "mirror:" + Key,
Debug = false,
Hand = 0,
};
var client = new GameClient(info); // Connection stays null: never started
mirror = GameBehavior.YGOL_CreateMirror(client, (ai, duel) => new MirrorExecutor(ai, duel));
}
catch (Exception e)
{
mirrorFailed = true;
Warn(Key + ": no mirror (" + e.GetType().Name + ": " + e.Message + ") — insight unavailable for this seat");
}
return mirror;
}
// ---- reads (all under the same lock as the writes) -------------
internal bool Started
{
get { lock (sync) return mirror != null && mirror.YGOL_MirrorDuel?.Fields[0]?.Hand != null; }
}
/// This seat's own field in its own mirror — i.e. everything it was told.
private ClientField Own => mirror?.YGOL_MirrorDuel?.Fields[0];
internal int[] Hand()
{
lock (sync) return Ids(Own?.Hand).ToArray();
}
internal int[] Grave()
{
lock (sync) return Ids(Own?.Graveyard).ToArray();
}
internal int[] Banished()
{
lock (sync) return Ids(Own?.Banished).ToArray();
}
internal int[] SetBackrow()
{
lock (sync)
{
var field = Own;
if (field?.SpellZone == null) return Array.Empty<int>();
return field.SpellZone
.Where(c => c != null && c.Id != 0 && c.IsFacedown())
.Select(c => c.Id).ToArray();
}
}
internal int[] SetMonsters()
{
lock (sync)
{
var field = Own;
if (field?.MonsterZone == null) return Array.Empty<int>();
return field.MonsterZone
.Where(c => c != null && c.Id != 0 && c.IsFacedown())
.Select(c => c.Id).ToArray();
}
}
/// Hand ids that were not in hand when this turn began.
internal int[] DrawnThisTurn()
{
lock (sync)
{
var now = Ids(Own?.Hand);
var before = new List<int>(handAtTurnStart);
var drawn = new List<int>();
foreach (var id in now)
{
var at = before.IndexOf(id);
if (at >= 0) before.RemoveAt(at);
else drawn.Add(id);
}
return drawn.ToArray();
}
}
/// Every id this seat has publicly or privately shown us: hand,
/// field, grave, banished, extra deck. Used for RemainingInDeck.
internal List<int> Seen()
{
lock (sync)
{
var field = Own;
var seen = new List<int>();
if (field == null) return seen;
seen.AddRange(Ids(field.Hand));
seen.AddRange(Ids(field.Graveyard));
seen.AddRange(Ids(field.Banished));
seen.AddRange(Ids(field.ExtraDeck));
if (field.MonsterZone != null) seen.AddRange(Ids(field.MonsterZone));
if (field.SpellZone != null) seen.AddRange(Ids(field.SpellZone));
return seen;
}
}
private static List<int> Ids(IEnumerable<ClientCard> cards)
{
var list = new List<int>();
if (cards == null) return list;
foreach (var card in cards)
if (card != null && card.Id != 0) list.Add(card.Id);
return list;
}
}
/// <summary>
/// The mirror's executor. A <see cref="GameBehavior"/> forwards a
/// handful of state messages to <c>GameAI</c>, which forwards them to
/// its executor — so a mirror needs one, and it must do nothing at all.
/// (WindBot's own <c>DefaultExecutor</c> has a protected constructor
/// and would register card handlers we never want to run.)
/// </summary>
internal sealed class MirrorExecutor : Executor
{
internal MirrorExecutor(GameAI ai, Duel duel) : base(ai, duel) { }
}
}
/// <summary>
/// What one seat may read about its opponent (TICKET-042). Obtained by
/// <see cref="SmartExecutor"/>'s constructor via
/// <see cref="DuelStateBus.InsightFor"/>; every property is a live read of
/// the opponent's mirror, so it always answers for "right now".
///
/// Gating: at <see cref="InsightLevel.None"/> nothing is available at all.
/// <see cref="InsightLevel.Hand"/> adds the hand, the draws of this turn,
/// the decklist and the public grave/banish lists.
/// <see cref="InsightLevel.Full"/> adds the set backrow and face-down
/// monsters. Nothing here can ever reveal deck ORDER: the server never
/// tells any client that, so no mirror has it either.
/// </summary>
public sealed class Insight
{
private readonly string seatKey;
private int[] decklist;
internal Insight(string seatKey, InsightLevel level)
{
this.seatKey = seatKey;
Level = level;
}
/// The level this seat resolved (override, else its brain's knob).
public InsightLevel Level { get; }
/// True only when insight is switched on AND an opposing stream is
/// actually being mirrored (false for remote online play, always).
public bool Available
{
get
{
if (Level == InsightLevel.None) return false;
var stream = DuelStateBus.OpponentOf(seatKey);
return stream != null && stream.Started;
}
}
/// The enemy's hand, as ids. Empty unless the level is hand or full.
public int[] Hand => AtLeast(InsightLevel.Hand)?.Hand() ?? Array.Empty<int>();
/// Ids the enemy drew (or otherwise added to hand) this turn.
public int[] DrawnThisTurn => AtLeast(InsightLevel.Hand)?.DrawnThisTurn() ?? Array.Empty<int>();
/// Ids in the enemy graveyard (public information; needs insight on).
public int[] SeenInGrave => AtLeast(InsightLevel.Hand)?.Grave() ?? Array.Empty<int>();
/// Ids the enemy has banished.
public int[] SeenBanished => AtLeast(InsightLevel.Hand)?.Banished() ?? Array.Empty<int>();
/// The enemy's face-down spells/traps, as ids. Full insight only.
public int[] SetBackrow => AtLeast(InsightLevel.Full)?.SetBackrow() ?? Array.Empty<int>();
/// The enemy's face-down monsters, as ids. Full insight only.
public int[] SetMonsters => AtLeast(InsightLevel.Full)?.SetMonsters() ?? Array.Empty<int>();
/// <summary>
/// The enemy's registered decklist (main deck ids, with duplicates), or
/// empty when the launcher did not tell the bus which deck that seat
/// plays. Read once, from the .ydk, through WindBot's own loader.
/// </summary>
public int[] Decklist
{
get
{
if (Level == InsightLevel.None) return Array.Empty<int>();
if (decklist != null) return decklist;
var stream = DuelStateBus.OpponentOf(seatKey);
var path = stream == null ? null : DuelStateBus.DeckPathOf(stream.Key);
if (path == null) return Array.Empty<int>();
try
{
var deck = WindBot.Game.Deck.Load(path);
decklist = deck.Cards.Select(c => c.Id).ToArray();
}
catch (Exception e)
{
DuelStateBus.Warn("decklist for '" + path + "': " + e.Message);
decklist = Array.Empty<int>();
}
return decklist;
}
}
/// <summary>
/// How many copies of <paramref name="cardId"/> can still be in the
/// enemy's deck: their decklist count minus every copy we have seen
/// (hand, field, grave, banish, extra). Never negative; 0 when no
/// decklist is registered.
/// </summary>
public int RemainingInDeck(int cardId)
{
var list = Decklist;
if (list.Length == 0) return 0;
var total = list.Count(id => id == cardId);
var stream = DuelStateBus.OpponentOf(seatKey);
if (stream == null) return total;
var seen = stream.Seen().Count(id => id == cardId);
return Math.Max(0, total - seen);
}
private DuelStateBus.Stream AtLeast(InsightLevel need)
{
if (Level < need) return null;
var stream = DuelStateBus.OpponentOf(seatKey);
return stream != null && stream.Started ? stream : null;
}
/// <summary>Parse "none" | "hand" | "full" (case-insensitive).</summary>
public static bool TryParseLevel(string text, out InsightLevel level)
{
level = InsightLevel.None;
if (string.IsNullOrWhiteSpace(text)) return false;
switch (text.Trim().ToLowerInvariant())
{
case "none": case "0": level = InsightLevel.None; return true;
case "hand": case "1": level = InsightLevel.Hand; return true;
case "full": case "2": level = InsightLevel.Full; return true;
default: return false;
}
}
/// "none" | "hand" | "full".
public static string LevelName(InsightLevel level)
=> level == InsightLevel.Full ? "full" : level == InsightLevel.Hand ? "hand" : "none";
}
}
+903
View File
@@ -0,0 +1,903 @@
using System;
using System.Collections.Generic;
using WindBot.Game;
using WindBot.Game.AI;
using YGOSharp.OCGWrapper.Enums;
namespace YGOLegacy.Bot
{
/// <summary>
/// What the simulator is allowed to know about the moment an effect is
/// being considered. Everything is public information: the card being
/// activated (for hand/backrow accounting), the target the caller has in
/// mind (or null = "pick for me"), and the enemy attack in progress when
/// the prompt is a battle window (so a negate/protect/removal can be
/// scored against the battle it prevents).
/// </summary>
public sealed class EffectContext
{
/// The card whose effect is simulated; null = don't charge a source.
public ClientCard Source;
/// The chosen target (destroy/bounce/banish/negate/boost/position/protect); null = simulator picks.
public ClientCard Target;
/// Enemy monster attacking us right now (Bot.UnderAttack ? Enemy.BattlingMonster : null).
public ClientCard Attacker;
/// Our monster being attacked (Bot.BattlingMonster); null with Attacker set = direct attack.
public ClientCard Defender;
/// The enemy card we would be chaining to (negate: what gets wasted); null = none.
public ClientCard EnemyChainCard;
/// Guessed DEF/ATK of a hidden card.
public int UnknownPower = BoardEvaluator.DefaultUnknownPower;
}
/// <summary>
/// Pure, deterministic prediction of the board after one modelled effect
/// (TICKET-040): removes / bounces / banishes the affected cards from a
/// <see cref="BoardView"/> copy (best enemy monsters first when no target
/// is given, honouring the model's filter; a symmetric scope removes ours
/// too), applies draws / LP / boosts / summoned bodies / costs and the
/// source card's own departure, resolves a pending enemy attack unless the
/// effect stops it, and returns the predicted board for
/// <see cref="BoardEvaluator.Score(BoardView)"/>. No hidden information is
/// read: enemy face-downs are counted, never matched against a stat filter,
/// and a face-down backrow is just "one backrow".
/// </summary>
public static class EffectSimulator
{
/// Score credited per drawn card beyond the hand-size term (card quality / digging).
public const float DrawDigBonus = 60f;
/// Score credited for a search on top of the hand-size term (you pick the card).
public const float SearchBonus = 100f;
/// Threat added to a monster a "protect" effect covers.
public const float ProtectThreat = 0.3f;
/// What a Level change is worth when it assembles a Rank we can actually
/// summon: one monster unit (see ApplyLevelChange).
public const float XyzEnableBonus = 700f;
/// What a Level change is worth when it reaches nothing TODAY: exactly
/// what an UNMODELLED activation is worth on our own turn (the flat 100
/// in ActivationScore). These effects are free and once per turn, and a
/// Level moved now pairs with the next monster we draw, so the model must
/// never make the executor keener to hold the card than it was with no
/// model at all — it may only ADD the Rank information on top. Measured:
/// scoring "no Rank today" as 0 makes Trey hold Chronomaly Golden Jet and
/// costs about 4 points of win rate against firing it blindly.
public const float LevelChangeSetupValue = 100f;
/// <summary>The board after the effect (spec signature): target may be null.</summary>
public static BoardView Apply(BoardView view, EffectModel m, ClientField bot, ClientField enemy, ClientCard chosenTarget = null)
=> Apply(view, m, bot, enemy, new EffectContext { Target = chosenTarget });
/// <summary>The board after the effect, with full context.</summary>
public static BoardView Apply(BoardView view, EffectModel m, ClientField bot, ClientField enemy, EffectContext ctx)
{
ctx ??= new EffectContext();
var after = view.Clone();
if (m == null) return ResolvePendingAttack(after, ctx, false, false);
PaySource(after, ctx.Source);
PayCosts(after, m);
bool stopsAttack = false; // the pending enemy attack does not happen
bool savesDefender = false; // the attack happens but our defender survives
switch (m.Kind)
{
case EffectKind.Destroy:
case EffectKind.Bounce:
case EffectKind.Banish:
stopsAttack = ApplyRemoval(after, m, ctx);
break;
case EffectKind.Negate:
stopsAttack = ApplyNegate(after, m, ctx);
break;
case EffectKind.Draw:
{
int n = m.amount > 0 ? (int)Math.Round(m.amount * PerCount(m.per, bot, enemy)) : Math.Max(1, m.Count);
after.BotHand += n;
after.Bonus += n * DrawDigBonus;
break;
}
case EffectKind.Search:
{
int n = m.amount > 0 ? (int)Math.Round(m.amount) : Math.Max(1, m.Count);
after.BotHand += n;
after.Bonus += SearchBonus;
break;
}
case EffectKind.Burn:
{
int dmg = (int)Math.Round(m.amount * PerCount(m.per, bot, enemy));
if (dmg <= 0) break;
if (m.Scope != EffectScope.Self) after.EnemyLp -= dmg;
if (m.Scope == EffectScope.Self || m.Scope == EffectScope.Both) after.BotLp -= dmg;
break;
}
case EffectKind.Gain:
{
int lp = (int)Math.Round(m.amount * PerCount(m.per, bot, enemy));
if (lp <= 0) break;
if (m.Scope == EffectScope.Enemy) after.EnemyLp += lp;
else after.BotLp += lp;
if (m.Scope == EffectScope.Both) after.EnemyLp += lp;
break;
}
case EffectKind.Boost:
ApplyBoost(after, m, ctx, bot, enemy);
break;
case EffectKind.Protect:
savesDefender = ApplyProtect(after, m, ctx);
break;
case EffectKind.Summon:
case EffectKind.Fusion:
{
int n = m.CountAll ? 1 : Math.Max(1, m.Count);
int atk = Math.Max(0, m.atk ?? (int)Math.Round(m.amount));
int def = Math.Max(0, m.def ?? atk);
// Where the BODY comes from (a hand card that summons itself
// leaves the hand) and, separately, what the summon SPENDS.
if (m.What == EffectWhat.Hand) after.BotHand = Math.Max(0, after.BotHand - n);
PayMaterials(after, m);
for (int i = 0; i < n; i++)
after = BoardEvaluator.WithBotMonster(after, atk, def, atk >= def, true);
break;
}
case EffectKind.Position:
stopsAttack = ApplyPosition(after, m, ctx);
break;
case EffectKind.LevelChange:
ApplyLevelChange(after, m, bot);
break;
default:
break; // other: nothing to simulate
}
ApplyEnemySide(after, m, enemy);
ApplyDelayedCost(after, m, view);
if (after.BotHand < 0) after.BotHand = 0;
if (after.EnemyHand < 0) after.EnemyHand = 0;
if (after.BotBackrow < 0) after.BotBackrow = 0;
if (after.EnemyBackrow < 0) after.EnemyBackrow = 0;
if (after.BotFloodgateSpells > after.BotBackrow) after.BotFloodgateSpells = after.BotBackrow;
if (after.EnemyFloodgateSpells > after.EnemyBackrow) after.EnemyFloodgateSpells = after.EnemyBackrow;
return ResolvePendingAttack(after, ctx, stopsAttack, savesDefender);
}
// =====================================================================
// E3 (2026-08-18) — the opponent's half of a symmetric card
// =====================================================================
//
// Upstart Goblin, Spellbook Inside the Pot, The Gift of Greed and Cup of
// Ace all used to be scored by OUR half alone (or by nothing at all),
// so they were fired the first turn they were legal — 31, 32, 31 and 31
// times in a 60-duel run that was then lost on LP. The model's
// `enemyDraw` / `enemyGain` / `enemyMill` / `enemyDiscard` /
// `enemySummon` fields let the simulator subtract what the card gives
// them, so the card is scored by the NET difference.
//
// Deck counts are the reason this is not just "enemy draws are bad": a
// draw also burns a card out of their Deck, which is exactly how a
// deck-out plan wins. The burn is priced against how close that Deck is
// to empty, so the same model reads negative at 35 cards left and
// strongly positive at 3. It lives on `Bonus` rather than in
// BoardEvaluator.Score because deck size is not part of the board every
// other path is scored on — nothing without one of these fields moves.
/// What burning ONE card out of the enemy's Deck is worth to us, given
/// how many they have left AFTER the burn. Hyperbolic, so it is noise
/// at a fresh 40-card Deck (~100 points) and a monster unit or more
/// once the deck-out is in sight (~700 at 6 left); emptying the Deck is
/// the duel (they lose on their next draw).
public const float DeckBurnScale = 4000f;
/// The whole opponent-side rider of a model: hand, LP, board and Deck.
private static void ApplyEnemySide(BoardView after, EffectModel m, ClientField enemy)
{
if (m == null || !m.HasEnemySide) return;
int deck = enemy?.Deck?.Count ?? 40;
if (m.enemyDraw > 0)
{
after.EnemyHand += m.enemyDraw;
after.Bonus -= m.enemyDraw * DrawDigBonus; // they pick the good half too
after.Bonus += DeckBurn(deck, m.enemyDraw);
deck = Math.Max(0, deck - m.enemyDraw);
}
if (m.enemyMill > 0)
{
after.Bonus += DeckBurn(deck, m.enemyMill);
deck = Math.Max(0, deck - m.enemyMill);
}
if (m.enemyDiscard > 0) after.EnemyHand -= m.enemyDiscard;
if (m.enemyGain > 0) after.EnemyLp += m.enemyGain;
if (m.enemySummon != null)
{
int atk = m.enemySummon.atk, def = m.enemySummon.def;
for (int i = 0; i < m.enemySummon.count; i++)
after.Enemy.Add(new MonsterView
{
Card = null,
Atk = atk,
Def = def,
AttackPos = atk >= def,
FaceUp = true,
Known = true,
});
}
}
/// Value of taking <paramref name="n"/> cards out of a Deck that holds
/// <paramref name="remaining"/> right now. Emptying it wins the duel.
public static float DeckBurn(int remaining, int n)
{
if (n <= 0) return 0f;
if (remaining <= n) return BoardEvaluator.Lethal * 0.5f;
float total = 0f;
for (int i = 0; i < n; i++)
total += DeckBurnScale / Math.Max(1, remaining - i);
return total;
}
/// <summary>
/// The board if we do nothing: the pending enemy attack (if any) resolves
/// as predicted. Compare an <see cref="Apply"/> result against THIS, not
/// the raw view, when the prompt is a battle window.
/// </summary>
public static BoardView Baseline(BoardView view, EffectContext ctx)
=> ResolvePendingAttack(view.Clone(), ctx, false, false);
// ---- targets --------------------------------------------------------
/// Enemy cards this pick-one effect could legally hit right now (public info, filter honoured).
public static List<ClientCard> EnemyTargets(EffectModel m, ClientField enemy)
{
var list = new List<ClientCard>();
if (m == null || m.Scope == EffectScope.Self) return list;
if (m.What == EffectWhat.Monsters || m.What == EffectWhat.Any)
foreach (var c in enemy.GetMonsters())
if (c != null && (m.filter == null || m.filter.Matches(c))) list.Add(c);
if (m.What == EffectWhat.Backrow || m.What == EffectWhat.Any)
foreach (var c in enemy.GetSpells())
if (c != null) list.Add(c);
return list;
}
/// Our own cards this effect could hit (self/both/any scope: costs, own-side picks).
public static List<ClientCard> OwnTargets(EffectModel m, ClientField bot, ClientCard exceptSource = null)
{
var list = new List<ClientCard>();
if (m == null || m.Scope == EffectScope.Enemy) return list;
if (m.What == EffectWhat.Monsters || m.What == EffectWhat.Any)
foreach (var c in bot.GetMonsters())
if (c != null && (m.filter == null || m.filter.Matches(c))) list.Add(c);
if (m.What == EffectWhat.Backrow || m.What == EffectWhat.Any)
foreach (var c in bot.GetSpells())
if (c != null && !ReferenceEquals(c, exceptSource)) list.Add(c);
return list;
}
/// The multiplier named by <see cref="EffectModel.per"/> (1 when unset/unknown).
public static int PerCount(string per, ClientField bot, ClientField enemy)
{
switch ((per ?? string.Empty).Trim().ToLowerInvariant())
{
case "": return 1;
case "owngravemonsters": return bot.GetGraveyardMonsters().Count;
case "owngraveinsects": return CountRace(bot.GetGraveyardMonsters(), CardRace.Insect);
case "owngravedragons": return CountRace(bot.GetGraveyardMonsters(), CardRace.Dragon);
case "owngravespells": return bot.GetGraveyardSpells().Count;
case "owngravetraps": return bot.GetGraveyardTraps().Count;
case "owngrave": return bot.Graveyard.Count;
case "ownmonsters": return bot.GetMonsterCount();
case "enemymonsters": return enemy.GetMonsterCount();
case "ownbackrow": return bot.GetSpellCount();
case "enemybackrow": return enemy.GetSpellCount();
case "ownhand": return bot.GetHandCount();
case "enemyhand": return enemy.GetHandCount();
case "enemygravemonsters": return enemy.GetGraveyardMonsters().Count;
default: return 1;
}
}
private static int CountRace(List<ClientCard> cards, CardRace race)
{
int n = 0;
foreach (var c in cards)
if (c != null && c.Id != 0 && (c.HasRace(race) || (c.Data != null && (c.Data.Race & (int)race) != 0))) n++;
return n;
}
// ---- pieces ---------------------------------------------------------
/// The activated card leaves where it was: a hand card is spent, a set
/// spell/trap leaves the backrow — unless it stays on the field
/// (continuous / equip / field / a monster's own effect).
private static void PaySource(BoardView after, ClientCard source)
{
if (source == null) return;
bool stays = source.HasType(CardType.Continuous) || source.HasType(CardType.Equip) || source.HasType(CardType.Field);
if (source.Location == CardLocation.Hand)
{
after.BotHand--;
if (stays && !source.IsMonster()) after.BotBackrow++;
}
else if (source.Location == CardLocation.SpellZone && !stays)
{
after.BotBackrow--;
}
}
/// <summary>
/// What a summon/fusion SPENDS (Fusion Materials): <c>materials</c>
/// cards out of <c>from</c>. Hand cards are hand cards; field material
/// takes our CHEAPEST monsters, which is what the selection layer picks
/// too; GY/Deck material is free — nothing on the board or in the hand
/// pays for it (Miracle Fusion). <c>any</c> spends the hand first and
/// only then the field, the same "off-field material costs nothing"
/// preference the selection layer applies.
/// </summary>
private static void PayMaterials(BoardView after, EffectModel m)
{
int n = m.MaterialCount;
if (n <= 0) return;
switch (m.From)
{
case EffectFrom.Grave:
return;
case EffectFrom.Hand:
after.BotHand -= n;
return;
case EffectFrom.Field:
{
var stripped = BoardEvaluator.WithoutCheapestBotMonsters(after, n);
after.Bot = stripped.Bot;
return;
}
default:
{
int fromHand = Math.Min(n, Math.Max(0, after.BotHand));
after.BotHand -= fromHand;
int fromField = n - fromHand;
if (fromField > 0)
{
var stripped = BoardEvaluator.WithoutCheapestBotMonsters(after, fromField);
after.Bot = stripped.Bot;
}
return;
}
}
}
/// <summary>
/// A cost the card only charges later in the same turn: Power Bond's
/// End-Phase damage equal to the original ATK, Limiter Removal
/// destroying everything it doubled.
///
/// It is a real cost and is charged on the predicted board — with one
/// exception, which is the whole point of these cards: if the board the
/// effect leaves can take the enemy to 0 this turn
/// (<see cref="BoardEvaluator.SwingDamage(BoardView)"/>), the End Phase
/// never arrives and the cost is free. A second, softer case: when the
/// enemy controls no monster at all every attack connects, so the swing
/// is worth about twice what it is into a board — the charge is halved
/// rather than waived, because they still get a turn.
///
/// <c>endTurnDestroy</c> takes the monsters the model matched off the
/// board (all of ours when it has no filter), but first credits the
/// EXTRA damage the effect buys this turn — otherwise doubling our ATK
/// and then losing the monsters always scores worse than doing nothing
/// and the card would never be played.
/// </summary>
private static void ApplyDelayedCost(BoardView after, EffectModel m, BoardView before)
{
if (m == null || !m.HasDelayedCost) return;
int swingAfter = BoardEvaluator.SwingDamage(after);
if (swingAfter >= after.EnemyLp) return; // it wins the duel this turn: there is no End Phase
bool unopposed = after.Enemy.Count == 0;
if (m.delayed != null && m.delayed.lp > 0)
after.BotLp -= unopposed ? m.delayed.lp / 2 : m.delayed.lp;
if (m.endTurnDestroy)
{
after.EnemyLp -= Math.Max(0, swingAfter - BoardEvaluator.SwingDamage(before));
var filter = m.filter;
for (int i = after.Bot.Count - 1; i >= 0; i--)
if (filter == null || filter.IsEmpty || (after.Bot[i].Card != null && filter.Matches(after.Bot[i].Card)))
after.Bot.RemoveAt(i);
}
}
private static void PayCosts(BoardView after, EffectModel m)
{
var cost = m.cost;
if (cost == null) return;
if (cost.lp > 0) after.BotLp -= cost.lp;
if (cost.discard > 0) after.BotHand -= cost.discard;
if (cost.tribute > 0)
{
var stripped = BoardEvaluator.WithoutCheapestBotMonsters(after, cost.tribute);
after.Bot = stripped.Bot;
}
}
/// Removal on the sides the scope names. Returns true when the pending
/// enemy attacker was among the removed (the attack no longer happens).
private static bool ApplyRemoval(BoardView after, EffectModel m, EffectContext ctx)
{
bool attackerGone = false;
bool hitEnemy = m.Scope != EffectScope.Self;
bool hitBot = m.Scope == EffectScope.Self || m.Scope == EffectScope.Both;
// "any" = we pick a side; a target of ours makes it a self pick.
if (m.Scope == EffectScope.Any && ctx.Target != null && ctx.Target.Controller == 0) { hitEnemy = false; hitBot = true; }
if (hitEnemy)
{
int gone = 0;
if (m.What == EffectWhat.Monsters || m.What == EffectWhat.Any)
attackerGone |= RemoveMonsters(after.Enemy, m, ctx.Target, ctx.Attacker, best: true, out gone);
if (m.What == EffectWhat.Backrow || m.What == EffectWhat.Any)
gone += RemoveBackrow(after, m, ctx.Target, enemySide: true);
if (m.What == EffectWhat.Hand)
after.EnemyHand -= m.CountAll ? after.EnemyHand : Math.Min(m.Count, after.EnemyHand);
// A bounce hands the cards back: they keep the card, lose the tempo.
if (m.Kind == EffectKind.Bounce) after.EnemyHand += gone;
}
if (hitBot)
{
int gone = 0;
if (m.What == EffectWhat.Monsters || m.What == EffectWhat.Any)
RemoveMonsters(after.Bot, m, ctx.Target, null, best: false, out gone);
if (m.What == EffectWhat.Backrow || m.What == EffectWhat.Any)
gone += RemoveBackrow(after, m, ctx.Target, enemySide: false);
if (m.What == EffectWhat.Hand)
after.BotHand -= m.CountAll ? after.BotHand : Math.Min(m.Count, after.BotHand);
if (m.Kind == EffectKind.Bounce) after.BotHand += gone;
}
return attackerGone;
}
/// Removes matching monsters from a side; the chosen target first, else
/// the best (enemy) / cheapest (ours) N, or every match for count:all.
/// Returns true if <paramref name="attacker"/> was removed.
private static bool RemoveMonsters(List<MonsterView> side, EffectModel m, ClientCard target, ClientCard attacker, bool best, out int removed)
{
removed = 0;
bool attackerGone = false;
var filter = m.filter;
bool Matches(MonsterView v) => filter == null || filter.IsEmpty || (v.Card != null && filter.Matches(v.Card));
if (m.CountAll)
{
for (int i = side.Count - 1; i >= 0; i--)
{
if (!Matches(side[i])) continue;
if (attacker != null && ReferenceEquals(side[i].Card, attacker)) attackerGone = true;
side.RemoveAt(i);
removed++;
}
}
else
{
int want = Math.Max(1, m.Count);
if (target != null && target.Location == CardLocation.MonsterZone)
{
for (int i = 0; i < side.Count; i++)
{
if (!ReferenceEquals(side[i].Card, target)) continue;
if (attacker != null && ReferenceEquals(target, attacker)) attackerGone = true;
side.RemoveAt(i);
removed++;
want--;
break;
}
}
while (want > 0 && side.Count > 0)
{
int pick = -1;
float pickValue = best ? float.MinValue : float.MaxValue;
for (int i = 0; i < side.Count; i++)
{
if (!Matches(side[i])) continue;
float value = BoardEvaluator.MonsterValue(side[i]);
if (best ? value > pickValue : value < pickValue) { pickValue = value; pick = i; }
}
if (pick < 0) break;
if (attacker != null && ReferenceEquals(side[pick].Card, attacker)) attackerGone = true;
side.RemoveAt(pick);
removed++;
want--;
}
}
return attackerGone;
}
/// Removes backrow on one side; returns how many left.
private static int RemoveBackrow(BoardView after, EffectModel m, ClientCard target, bool enemySide)
{
int have = enemySide ? after.EnemyBackrow : after.BotBackrow;
if (have <= 0) return 0;
int n;
if (m.CountAll) n = have;
else if (target != null && target.Location == CardLocation.SpellZone && (target.Controller == 1) == enemySide) n = 1;
else if (target != null && target.Location == CardLocation.MonsterZone) return 0; // the pick went to a monster
else n = Math.Min(Math.Max(1, m.Count), have);
if (enemySide)
{
after.EnemyBackrow -= n;
// We choose the face-up floodgate first when picking; a wipe takes them all.
after.EnemyFloodgateSpells = Math.Max(0, after.EnemyFloodgateSpells - n);
// A face-up equip we blow up takes its boost with it.
if (target != null && target.IsFaceup() && target.HasType(CardType.Equip) && target.EquipTarget != null)
RevertEquip(after.Enemy, target.EquipTarget);
}
else
{
after.BotBackrow -= n;
after.BotFloodgateSpells = Math.Max(0, after.BotFloodgateSpells - n);
if (m.CountAll)
for (int i = 0; i < after.Bot.Count; i++) RevertEquip(after.Bot, after.Bot[i].Card);
}
return n;
}
/// A monster losing its equip cards goes back to its printed stats
/// (only monsters that actually carry equips: a conditional-ATK body
/// like Arsenal Bug is not an equip boost).
private static void RevertEquip(List<MonsterView> side, ClientCard equipped)
{
if (equipped == null || equipped.EquipCards == null || equipped.EquipCards.Count == 0) return;
for (int i = 0; i < side.Count; i++)
{
if (!ReferenceEquals(side[i].Card, equipped)) continue;
var v = side[i];
if (equipped.BaseAttack > 0 || equipped.BaseDefense > 0)
{
v.Atk = equipped.BaseAttack;
v.Def = equipped.BaseDefense;
side[i] = v;
}
return;
}
}
/// A negate: stops the pending attack when it answers one; otherwise
/// nullifies the target's threat (monster) or wastes the enemy's
/// chained card (their backrow / hand card is gone for nothing).
private static bool ApplyNegate(BoardView after, EffectModel m, EffectContext ctx)
{
if (ctx.Attacker != null && (m.Trigger == EffectTrigger.EnemyAttack || m.Trigger == EffectTrigger.Any || m.What == EffectWhat.Monsters))
{
if (ctx.Target == null || ReferenceEquals(ctx.Target, ctx.Attacker) || ctx.Target.Location != CardLocation.MonsterZone)
return true;
}
var target = ctx.Target ?? ctx.EnemyChainCard;
if (target != null && target.Controller == 1)
{
if (target.Location == CardLocation.MonsterZone)
{
int i = after.IndexOfEnemy(target);
if (i >= 0)
{
var v = after.Enemy[i];
// Their effect is nullified: the body stays, the threat goes,
// and a card they spent activating it is wasted.
after.Bonus += 200f + v.Threat * 400f;
v.Threat = 0f;
after.Enemy[i] = v;
}
return false;
}
// Spell/trap on the stack: it resolves as nothing = they lost a card.
after.Bonus += 250f;
if (target.Location == CardLocation.SpellZone && after.EnemyBackrow > 0) after.EnemyBackrow--;
return false;
}
// Nothing identifiable to negate: a generic monster-effect negate on
// their biggest threat.
if (m.What != EffectWhat.Backrow)
{
int best = -1;
float bestThreat = 0f;
for (int i = 0; i < after.Enemy.Count; i++)
if (after.Enemy[i].Threat > bestThreat) { bestThreat = after.Enemy[i].Threat; best = i; }
if (best >= 0)
{
var v = after.Enemy[best];
v.Threat = 0f;
after.Enemy[best] = v;
}
}
return false;
}
private static void ApplyBoost(BoardView after, EffectModel m, EffectContext ctx, ClientField bot, ClientField enemy)
{
int atk = (int)Math.Round(m.amount * PerCount(m.per, bot, enemy));
int def = m.def ?? 0;
if (atk == 0 && def == 0) return;
bool ours = m.Scope == EffectScope.Self || m.Scope == EffectScope.Both || m.Scope == EffectScope.Any;
bool theirs = m.Scope == EffectScope.Enemy || m.Scope == EffectScope.Both;
if (m.Scope == EffectScope.Any && ctx.Target != null && ctx.Target.Controller == 1) { ours = false; theirs = true; }
// "boost enemy" = a debuff of that much (their monsters lose ATK).
int theirAtk = m.Scope == EffectScope.Both ? atk : -atk;
int theirDef = m.Scope == EffectScope.Both ? def : -def;
if (ours) BoostSide(after.Bot, m, ctx.Target, atk, def, preferAttackers: true);
if (theirs) BoostSide(after.Enemy, m, ctx.Target, theirAtk, theirDef, preferAttackers: true);
}
private static void BoostSide(List<MonsterView> side, EffectModel m, ClientCard target, int atk, int def, bool preferAttackers)
{
var filter = m.filter;
bool Matches(MonsterView v) => filter == null || filter.IsEmpty || (v.Card != null && filter.Matches(v.Card));
void Bump(int i)
{
var v = side[i];
// An ATK boost only pays on a monster that is face-up in attack
// position: a defender (or a face-down) will not swing with it
// and is usually the weak body about to die — so an equip on it
// is a wasted card. Keep a sliver (it might switch next turn)
// and the DEF part in full. Debuffs (negative atk) on the enemy
// count in full: they matter when the enemy attacks with it.
int effAtk = atk;
if (atk > 0 && !(v.AttackPos && v.FaceUp)) effAtk = atk / 8;
v.Atk = Math.Max(0, v.Atk + effAtk);
v.Def = Math.Max(0, v.Def + def);
side[i] = v;
}
if (m.CountAll)
{
for (int i = 0; i < side.Count; i++) if (Matches(side[i])) Bump(i);
return;
}
if (target != null)
{
for (int i = 0; i < side.Count; i++)
if (ReferenceEquals(side[i].Card, target)) { Bump(i); return; }
}
// No target: the monster that gets the most out of it — the strongest
// face-up attacker, else the strongest body.
int pick = -1;
int pickPower = -1;
for (int pass = 0; pass < 2 && pick < 0; pass++)
{
for (int i = 0; i < side.Count; i++)
{
var v = side[i];
if (!Matches(v)) continue;
if (pass == 0 && preferAttackers && !(v.AttackPos && v.FaceUp)) continue;
if (v.Atk > pickPower) { pickPower = v.Atk; pick = i; }
}
}
if (pick >= 0) Bump(pick);
}
/// Protect: our attacked monster survives the pending battle; outside a
/// battle the covered monster is worth a little more (harder to remove).
private static bool ApplyProtect(BoardView after, EffectModel m, EffectContext ctx)
{
if (ctx.Attacker != null && ctx.Defender != null)
{
var target = ctx.Target ?? ctx.Defender;
if (ReferenceEquals(target, ctx.Defender) || target.Controller != 0) return true;
}
var pick = ctx.Target != null && ctx.Target.Controller == 0 ? after.IndexOfBot(ctx.Target) : BoardEvaluator.MostValuable(after.Bot);
if (pick >= 0)
{
var v = after.Bot[pick];
v.Threat = Math.Min(1f, v.Threat + ProtectThreat);
after.Bot[pick] = v;
}
return false;
}
/// Position change (to defence / face-down): the affected monsters lose
/// their attack; the pending attacker turned = attack stops.
private static bool ApplyPosition(BoardView after, EffectModel m, EffectContext ctx)
{
bool stops = false;
bool ours = m.Scope == EffectScope.Self || m.Scope == EffectScope.Both;
bool theirs = m.Scope != EffectScope.Self;
if (m.Scope == EffectScope.Any && ctx.Target != null && ctx.Target.Controller == 0) { ours = true; theirs = false; }
var filter = m.filter;
bool Matches(MonsterView v) => filter == null || filter.IsEmpty || (v.Card != null && filter.Matches(v.Card));
void Turn(List<MonsterView> side, bool enemySide)
{
if (m.CountAll)
{
for (int i = 0; i < side.Count; i++)
{
if (!Matches(side[i])) continue;
if (enemySide && ctx.Attacker != null && ReferenceEquals(side[i].Card, ctx.Attacker)) stops = true;
var v = side[i]; v.AttackPos = false; side[i] = v;
}
return;
}
int pick = -1;
if (ctx.Target != null)
for (int i = 0; i < side.Count; i++)
if (ReferenceEquals(side[i].Card, ctx.Target)) { pick = i; break; }
if (pick < 0 && enemySide && ctx.Attacker != null) pick = after.IndexOfEnemy(ctx.Attacker);
if (pick < 0)
{
// The attacker whose ATK hurts most.
int bestAtk = -1;
for (int i = 0; i < side.Count; i++)
if (Matches(side[i]) && side[i].AttackPos && side[i].Atk > bestAtk) { bestAtk = side[i].Atk; pick = i; }
}
if (pick < 0) return;
if (enemySide && ctx.Attacker != null && ReferenceEquals(side[pick].Card, ctx.Attacker)) stops = true;
var t = side[pick]; t.AttackPos = false; side[pick] = t;
}
if (theirs) Turn(after.Enemy, true);
if (ours) Turn(after.Bot, false);
return stops;
}
/// <summary>
/// A Level change (Chronomaly Golden Jet's "+1 Level to every Chronomaly
/// you control", Sol Monolith's "its Level becomes 6", Gagaga Magician's
/// declared Level). Levels are not part of the board score, so the only
/// thing simulated is what the change BUYS: the best Xyz body our Extra
/// Deck can put down from the Levels we control. A Rank counts as
/// reachable when two or more of our face-up main-deck monsters sit on
/// it, and it is worth the ATK of the best Xyz we own at that Rank.
///
/// So the score is the UPGRADE, not a boolean: assembling a Rank where
/// there was none is worth <see cref="XyzEnableBonus"/> (one monster
/// unit); turning a Rank we already had into a higher-ATK one is worth
/// half the ATK it adds, capped at the same unit; a forced change that
/// LOWERS our best Rank is charged the same way, so the card is held.
/// Reaching nothing new is worth <see cref="LevelChangeSetupValue"/> —
/// small but positive, because these effects are free and once per turn
/// (measured: scoring "no Rank today" as 0 makes Trey hold Golden Jet and
/// costs ~2 points of win rate against firing it blindly).
///
/// Deliberately not modelled: Synchro Level sums, Ranks needing three or
/// more materials, and enemy-side Level changes (their Levels never help
/// us — an `enemy` scope is ignored).
/// </summary>
private static void ApplyLevelChange(BoardView after, EffectModel m, ClientField bot)
{
if (bot == null || m.Scope == EffectScope.Enemy) return;
var ranks = ExtraXyzRanks(bot);
if (ranks.Count == 0) return;
// Our face-up main-deck monsters and their Levels; an Xyz already on
// the field has a Rank, not a Level, and is never material here.
var levels = new List<int>();
var affected = new List<int>();
foreach (var c in bot.GetMonsters())
{
if (c == null || c.Id == 0 || !c.IsFaceup() || c.HasType(CardType.Xyz)) continue;
int lv = c.Level > 0 || c.Data == null ? c.Level : c.Data.Level;
if (lv <= 0) continue;
if (m.filter == null || m.filter.IsEmpty || m.filter.Matches(c)) affected.Add(levels.Count);
levels.Add(lv);
}
// Nothing to pair up yet (or nothing this model touches): free set-up.
if (levels.Count < 2 || affected.Count == 0) { after.Bonus += LevelChangeSetupValue; return; }
int before = BestXyzAtk(levels, ranks);
int best;
if (m.CountAll)
{
// Forced on everything it matches: it can also LOWER our best Rank
// (two Level 3s -> two Level 4s is a downgrade when the Rank-3 body
// is the bigger one). Score that honestly so the card is held.
var next = new List<int>(levels);
foreach (var i in affected) next[i] = ShiftedLevel(levels[i], m);
best = BestXyzAtk(next, ranks);
if (best < before)
{
after.Bonus -= Math.Min(XyzEnableBonus, (before - best) * 0.5f);
return;
}
}
else
{
best = before;
// Pick-one: try every monster the model may touch and keep the
// best result (count > 1 is treated as one change — no card in
// any deck here needs more).
foreach (var i in affected)
{
var next = new List<int>(levels);
if (m.level.HasValue || m.amount != 0f)
{
next[i] = ShiftedLevel(levels[i], m);
best = Math.Max(best, BestXyzAtk(next, ranks));
}
else
{
// A declared Level: it may become anything, so every Rank
// we own is on the table.
foreach (var r in ranks.Keys)
{
next[i] = r;
best = Math.Max(best, BestXyzAtk(next, ranks));
}
}
}
}
if (best <= before) { after.Bonus += LevelChangeSetupValue; return; }
after.Bonus += before == 0 ? XyzEnableBonus : Math.Min(XyzEnableBonus, (best - before) * 0.5f);
}
/// The Level one monster ends up on: an absolute `level`, else a shift by
/// `amount`. Clamped to a real Level (1-12).
private static int ShiftedLevel(int level, EffectModel m)
{
int next = m.level ?? level + (int)Math.Round(m.amount);
return Math.Max(1, Math.Min(12, next));
}
/// ATK of the best Xyz we could summon from these Levels (0 = no Rank has
/// two bodies on it).
private static int BestXyzAtk(List<int> levels, Dictionary<int, int> ranks)
{
int best = 0;
foreach (var kv in ranks)
{
if (kv.Value <= best) continue;
int n = 0;
for (int i = 0; i < levels.Count; i++)
if (levels[i] == kv.Key) n++;
if (n >= 2) best = kv.Value;
}
return best;
}
/// Rank -> ATK of the best Xyz monster we own at that Rank (the cdb
/// stores a Rank in the Level column).
private static Dictionary<int, int> ExtraXyzRanks(ClientField bot)
{
var map = new Dictionary<int, int>();
if (bot.ExtraDeck == null) return map;
foreach (var c in bot.ExtraDeck)
{
if (c == null || c.Id == 0) continue;
var data = c.Data ?? YGOSharp.OCGWrapper.NamedCard.Get(c.Id);
if (data == null || (data.Type & (int)CardType.Xyz) == 0 || data.Level <= 0) continue;
int atk = Math.Max(0, data.Attack);
if (!map.TryGetValue(data.Level, out var have) || atk > have) map[data.Level] = atk;
}
return map;
}
/// The enemy attack in <paramref name="ctx"/> resolves on the view (our
/// monster and LP by ATK/DEF alone) unless it was stopped; a saved
/// defender takes the LP hit but stays.
private static BoardView ResolvePendingAttack(BoardView view, EffectContext ctx, bool stopped, bool saveDefender)
{
if (ctx?.Attacker == null || stopped) return view;
int ai = view.IndexOfEnemy(ctx.Attacker);
if (ai < 0) return view; // removed by the effect
int atk = Math.Max(0, ctx.Attacker.Attack);
if (ctx.Defender == null)
{
view.BotLp -= atk;
return view;
}
int di = view.IndexOfBot(ctx.Defender);
if (di < 0) return view; // our defender is gone already (effect moved it)
var d = view.Bot[di];
int power = d.Power;
if (d.AttackPos)
{
if (atk > power) { view.BotLp -= atk - power; if (!saveDefender) view.Bot.RemoveAt(di); }
else if (atk == power) { if (!saveDefender) view.Bot.RemoveAt(di); view.Enemy.RemoveAt(ai); }
else { view.EnemyLp -= power - atk; view.Enemy.RemoveAt(ai); }
}
else
{
if (atk > power) { if (!saveDefender) view.Bot.RemoveAt(di); }
else if (atk < power) view.EnemyLp -= power - atk;
}
return view;
}
}
}
+992
View File
@@ -0,0 +1,992 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using YGOLegacy.Protocol.Codecs;
using YGOLegacy.Protocol.Contracts;
using EngineApi = YGOLegacy.Engine.EngineApi;
using MessageScan = YGOLegacy.Engine.MessageScan;
namespace YGOLegacy.Bot
{
// ------------------------------------------------------------------------
// TICKET-045 — the ygoserver duel loop, in C#, in this process.
//
// The engine's start_server is a native black box that hosts a room, drives the core and
// splits the core's MSG_* stream per seat. This file does the same job for
// exactly two seats and one duel: create_duel -> set_player_info -> new_card
// -> start_duel -> loop process()/get_message(), route every message to the
// seat(s) that may see it (blanking what they may not), and feed prompt
// answers back with set_responseb.
//
// Deliberately Unity-free (Assembly-CSharp compiles it, Tools/BotArena links
// it) and deliberately transport-free: a seat is an ILoopbackSeat, so the
// standalone arena can plug two WindBot GameClients in with no socket at all
// (LoopbackBotSeat). Nothing in the game uses this yet.
//
// Reference for the byte layout of every message and for the hidden-info
// blanking: Percy.Ygopro (Assets/Scripts/MDPro3/Duel/CoreWrapper.cs), the
// fork's own single-seat host, generalised here to two seats the way
// ygopro's single_duel.cpp does it.
// ------------------------------------------------------------------------
/// <summary>ocgcore's CardData, byte-identical to Percy.CardData.</summary>
[StructLayout(LayoutKind.Sequential)]
public unsafe struct LocalCardData
{
public int Code;
public int Alias;
public fixed short Setcode[16];
public int Type;
public int Level;
public int Attribute;
public int Race;
public int Attack;
public int Defense;
public int LScale;
public int RScale;
public int LinkMarker;
public void SetSetcode(long value)
{
Setcode[0] = (short)(value & 0xFFFF);
Setcode[1] = (short)((value >> 16) & 0xFFFF);
Setcode[2] = (short)((value >> 32) & 0xFFFF);
Setcode[3] = (short)((value >> 48) & 0xFFFF);
}
}
/// <summary>
/// One duelist as far as the host is concerned: something you can hand a
/// STOC packet to, run until it has finished reacting, and collect CTOS
/// packets from. Synchronous on purpose — the host, both parsers and both
/// brains all run on one thread, so a duel is a single call with no locks,
/// no sockets and no sleeps.
/// </summary>
public interface ILoopbackSeat
{
/// The seat's display name (goes into the room handshake).
string SeatName { get; }
/// Queue one STOC packet (unframed: first byte is the StocMessage id).
void Deliver(byte[] packet);
/// Run the seat until it has consumed everything queued.
void Pump();
/// Take the next CTOS packet the seat produced, if any.
bool TryTakeCtos(out byte[] packet);
/// Non-null once the seat has broken down (a thrown MSG_RETRY, say);
/// the host aborts the duel with this as the error.
string Failed { get; }
}
/// <summary>What a finished (or abandoned) duel looked like.</summary>
public sealed class LocalDuelOutcome
{
/// Core player index that won (0/1), 2 for a draw, -1 when the duel
/// never reached MSG_WIN.
public int Winner = -1;
/// Reason byte from MSG_WIN.
public int Reason;
/// Which seat went first (0 = seat A).
public int FirstSeat;
/// Set when the duel could not be played out; null on success.
public string Error;
/// Wall clock of the whole duel, milliseconds.
public int Milliseconds;
/// Messages routed (a cheap sanity/perf number).
public int Messages;
/// MSG_NEW_TURN seen (the host's own turn counter; the verdicts carry
/// each bot's).
public int Turns;
/// TICKET-050: life points per CORE PLAYER index, tracked off
/// MSG_DAMAGE/RECOVER/LP_UPDATE/PAY_LPCOST. Only meaningful when the
/// duel was stopped at a horizon (a finished duel says who won).
public readonly int[] Lp = new int[2];
/// TICKET-050: monsters on each core player's field when the duel
/// stopped (query_field_count, so face-down bodies count too).
public readonly int[] Monsters = new int[2];
/// TICKET-050: true when Options.StopAfterTurn ended the duel rather
/// than MSG_WIN. Not an error.
public bool Horizon;
/// TICKET-050: the response bytes every seat gave, in order, when
/// Options.RecordResponses is on. Replaying these into a fresh host
/// with the same seed reproduces this duel exactly.
public List<byte[]> Responses;
}
public sealed unsafe class LocalDuelHost
{
// ==================================================================
// ocgcore
// ==================================================================
// The two readers ocgcore keeps are PROCESS-GLOBAL (set_card_reader /
// set_script_reader take a raw function pointer), so they are installed
// once per process and the delegates must outlive every duel — hence the
// statics. One duel at a time per process; arena workers are processes.
private static YGOLegacy.Engine.CardReader cardReaderFn;
private static YGOLegacy.Engine.ScriptReader scriptReaderFn;
private static Func<int, LocalCardData?> cardLookup;
private static Func<string, byte[]> scriptLookup;
private static IntPtr scriptBuffer;
private static int scriptBufferSize;
/// <summary>
/// Install the process-global card/script readers. Call once, before the
/// first duel. <paramref name="cards"/> returns null for an unknown code
/// (the core gets a zeroed CardData, exactly as the game's reader does);
/// <paramref name="scripts"/> returns null when a script does not exist.
/// </summary>
public static void InstallReaders(Func<int, LocalCardData?> cards, Func<string, byte[]> scripts)
{
cardLookup = cards ?? throw new ArgumentNullException(nameof(cards));
scriptLookup = scripts ?? throw new ArgumentNullException(nameof(scripts));
if (cardReaderFn != null) return;
cardReaderFn = OnCardReader;
scriptReaderFn = OnScriptReader;
GrowScriptBuffer(1 << 20);
EngineApi.set_card_reader(cardReaderFn);
EngineApi.set_script_reader(scriptReaderFn);
}
private static void GrowScriptBuffer(int size)
{
if (scriptBuffer != IntPtr.Zero && scriptBufferSize >= size) return;
if (scriptBuffer != IntPtr.Zero) Marshal.FreeHGlobal(scriptBuffer);
scriptBufferSize = size;
scriptBuffer = Marshal.AllocHGlobal(size);
}
private static uint OnCardReader(uint code, IntPtr pData)
{
LocalCardData? found = null;
try { found = cardLookup((int)code); }
catch (Exception) { }
*(LocalCardData*)pData = found ?? default;
return code;
}
private static IntPtr OnScriptReader(string scriptName, int* len)
{
*len = 0;
byte[] content = null;
try { content = scriptLookup(scriptName); }
catch (Exception) { }
if (content == null || content.Length == 0) return IntPtr.Zero;
GrowScriptBuffer(Math.Max(content.Length + 16, scriptBufferSize));
Marshal.Copy(content, 0, scriptBuffer, content.Length);
*len = content.Length;
return scriptBuffer;
}
// ==================================================================
// Protocol constants (kept local so this file has no upstream deps)
// ==================================================================
private const byte STOC_GAME_MSG = 0x1;
private const byte STOC_SELECT_TP = 0x4;
private const byte STOC_TP_RESULT = 0x6;
private const byte STOC_JOIN_GAME = 0x12;
private const byte STOC_TYPE_CHANGE = 0x13;
private const byte STOC_DUEL_START = 0x15;
private const byte STOC_HS_PLAYER_ENTER = 0x20;
private const byte STOC_HS_PLAYER_CHANGE = 0x21;
// ygoserver patch 0017: { version, chooser seat, face, choose seconds }, no sender stamp
private const byte STOC_COIN_TOSS = 0x5B;
private const byte COIN_TOSS_VERSION = 1;
private const byte COIN_FACE_HEADS = 0;
private const byte COIN_FACE_TAILS = 1;
private const byte COIN_CHOOSE_SECONDS = 10;
private const byte CTOS_RESPONSE = 0x1;
private const byte CTOS_UPDATE_DECK = 0x2;
private const byte CTOS_HAND_RESULT = 0x3;
private const byte CTOS_TP_RESULT = 0x4;
private const byte CTOS_JOIN_GAME = 0x12;
private const byte CTOS_SURRENDER = 0x14;
private const int LOCATION_DECK = 0x01;
private const int LOCATION_HAND = 0x02;
private const int LOCATION_MZONE = 0x04;
private const int LOCATION_SZONE = 0x08;
private const int LOCATION_GRAVE = 0x10;
private const int LOCATION_REMOVED = 0x20;
private const int LOCATION_EXTRA = 0x40;
private const int POS_FACEDOWN = 0xA;
private const int POS_FACEDOWN_DEFENCE = 0x8;
// Query flags, verbatim from Percy.Ygopro's Refresh* methods.
private const int QUERY_MZONE = 0x81fff | 0x10000;
private const int QUERY_SZONE = 0x681fff;
private const int QUERY_HAND = 0x181fff;
private const int QUERY_PILE = 0x81fff;
/// The only duel option the fork's rooms ever use: master rule 5 in the
/// high half, no extra flags. Confirmed against a real ygoserver duel's
/// replay header (opt = 0x00050000) — the byte the client reads out of
/// MSG_START as `duel_rule` is (opt >> 16), and WindBot turns it into
/// Duel.IsNewRule / IsNewRule2020.
public const uint DefaultDuelOptions = 0x50000;
// ==================================================================
// Configuration
// ==================================================================
public sealed class Options
{
public ILoopbackSeat SeatA;
public ILoopbackSeat SeatB;
/// Main deck card ids per seat, in ydk order (shuffled by the host).
public IList<int> MainA, MainB;
public IList<int> ExtraA, ExtraB;
public int StartLp = 8000;
public int StartHand = 5;
public int DrawCount = 1;
public uint DuelOptions = DefaultDuelOptions;
/// Seeds the core AND the host's own deck shuffle.
public int Seed;
/// <summary>
/// Give up after this many turns. A duel is ~10-20 turns; a handful
/// of Yu-Gi-Oh boards simply never resolve (measured: about 2 in
/// 1000 Yuma mirrors reach turn 9000+ with both players stuck), and
/// ygoserver ends those on its per-player clock, which an
/// in-process host has no equivalent of. The duel is written off as
/// an error instead — better a named error than a hang.
/// </summary>
public int TurnLimit = 200;
/// Backstop for a loop that is not turn-shaped (a prompt the core
/// keeps re-asking). A normal duel routes a few thousand messages.
public int MessageLimit = 500000;
/// Optional trace sink; null = silent.
public Action<string> Log;
// ---- TICKET-050 (rollout lookahead) --------------------------
/// <summary>
/// Force who goes first instead of letting the coin toss decide
/// (-1 = toss, as ygoserver does). The toss and SELECT_TP packets
/// are still exchanged so both bots stay in protocol; only the
/// verdict is imposed. A replay host MUST force it: the chooser's
/// answer comes from the bot, which the recorded response log does
/// not cover.
/// </summary>
public int ForcedFirstSeat = -1;
/// <summary>
/// Record every prompt answer into LocalDuelOutcome.Responses. Off
/// by default: a normal measurement run must not pay for it.
/// </summary>
public bool RecordResponses;
/// <summary>
/// Prompt answers to impose instead of asking the seats, in order.
/// The seats still SEE every prompt and answer it (that is how they
/// build their own state) - the answer is simply discarded while
/// the script lasts. Once it runs out the seats are in charge again.
/// </summary>
public IList<byte[]> ScriptedResponses;
/// <summary>
/// Stop (not error) once this many MSG_NEW_TURNs have been seen;
/// 0 = play to MSG_WIN. The outcome then has Horizon = true, LP and
/// monster counts filled in and Winner = -1.
/// </summary>
public int StopAfterTurn;
}
private readonly Options opt;
private readonly ILoopbackSeat[] seats = new ILoopbackSeat[2];
private readonly Random rng;
private readonly byte[] queryBuffer = new byte[0x20000];
private IntPtr duel;
/// Core player index -> seat index. players[0] is the seat going first.
private readonly int[] seatOfPlayer = new int[2];
private readonly int[] playerOfSeat = new int[2];
private readonly LocalDuelOutcome outcome = new LocalDuelOutcome();
private byte[] pendingResponse;
private int pendingResponsePlayer = -1;
/// TICKET-050: how far into Options.ScriptedResponses we are.
private int scriptedIndex;
/// The last prompt we asked and the answer the seat gave, kept only so
/// that MSG_RETRY can NAME what the core rejected (see the Loop).
private int lastPromptId = -1;
private byte[] lastAnswer;
private bool surrendered;
private int surrenderSeat = -1;
public LocalDuelHost(Options options)
{
opt = options ?? throw new ArgumentNullException(nameof(options));
seats[0] = opt.SeatA;
seats[1] = opt.SeatB;
rng = opt.Seed != 0 ? new Random(opt.Seed) : new Random();
if (opt.RecordResponses) outcome.Responses = new List<byte[]>();
}
// ==================================================================
// The duel
// ==================================================================
/// <summary>
/// TICKET-050: the outcome object as it stands RIGHT NOW — the response
/// log, the turn counter and the life points of a duel still in
/// progress. A rollout oracle reads it from inside a prompt.
/// </summary>
public LocalDuelOutcome Live => outcome;
private bool ran;
/// <summary>Play the duel. One host plays ONE duel; call it once.</summary>
public LocalDuelOutcome Run()
{
if (ran) throw new InvalidOperationException("a LocalDuelHost plays one duel; build a new one");
ran = true;
var started = DateTime.UtcNow;
try
{
Handshake();
StartDuel();
Loop();
}
catch (Exception e)
{
outcome.Error ??= e.GetType().Name + ": " + e.Message;
opt.Log?.Invoke("[local host] " + e);
}
finally
{
if (duel != IntPtr.Zero)
{
try { EngineApi.end_duel(duel); } catch (Exception) { }
duel = IntPtr.Zero;
}
outcome.Milliseconds = (int)(DateTime.UtcNow - started).TotalMilliseconds;
}
return outcome;
}
// ------------------------------------------------------------------
// Room handshake — what GameBehavior needs before MSG_START so that
// _room.Position / _room.Names / Duel.IsFirst are right.
// ------------------------------------------------------------------
private void Handshake()
{
// Each seat's first Pump() fires OnConnected, which sends
// ExternalAddress + PlayerInfo + JoinGame through the loopback hook.
for (var s = 0; s < 2; s++) DrainSeat(s);
for (var s = 0; s < 2; s++)
{
Send(s, JoinGamePacket());
DrainSeat(s); // -> CTOS_UpdateDeck
Send(s, TypeChangePacket(s));
DrainSeat(s); // -> CTOS_HsReady
}
// Both seats learn both names, then that both are ready.
Broadcast(PlayerEnterPacket(seats[0].SeatName, 0));
Broadcast(PlayerEnterPacket(seats[1].SeatName, 1));
Broadcast(PlayerChangePacket(0, 9 /* Ready */));
Broadcast(PlayerChangePacket(1, 9 /* Ready */));
DrainAll(); // -> CTOS_HsStart from the host seat (ignored)
CoinToss();
Broadcast(new[] { STOC_DUEL_START });
DrainAll();
}
/// ygoserver's coin toss (patch 0017): heads = seat 0 chooses, tails =
/// seat 1. Everyone gets STOC_COIN_TOSS, the chooser gets SELECT_TP; a
/// chooser that has not answered by the end of the drain goes FIRST,
/// the way the server's choose timer decides it.
private void CoinToss()
{
var face = rng.Next(2) == 0 ? COIN_FACE_HEADS : COIN_FACE_TAILS;
var winner = face == COIN_FACE_HEADS ? 0 : 1;
Broadcast(new[] { STOC_COIN_TOSS, COIN_TOSS_VERSION, (byte)winner, face, COIN_CHOOSE_SECONDS });
DrainAll();
tpChoice = -1;
Send(winner, new[] { STOC_SELECT_TP });
DrainSeat(winner);
if (tpChoice < 0)
{
opt.Log?.Invoke("[local host] seat " + winner + " did not choose a turn order; FIRST, as the server's timer would");
tpChoice = 1;
}
var firstSeat = opt.ForcedFirstSeat >= 0 ? opt.ForcedFirstSeat
: tpChoice != 0 ? winner : 1 - winner;
seatOfPlayer[0] = firstSeat;
seatOfPlayer[1] = 1 - firstSeat;
playerOfSeat[firstSeat] = 0;
playerOfSeat[1 - firstSeat] = 1;
outcome.FirstSeat = firstSeat;
Broadcast(new[] { STOC_TP_RESULT, (byte)(tpChoice != 0 ? 1 : 0) });
}
private int tpChoice = -1;
private byte[] JoinGamePacket()
{
// The hand-written version was 19 bytes (a 2-byte pad where HostInfo
// has 3); the bot read only the first 7 bytes, so nothing noticed.
var w = NewPacket(STOC_JOIN_GAME);
StocCodecs.JoinGame.Write(w, new HostInfo(
lflist: 0,
rule: 5, // card pool (MultiplayerService.HostLocal)
mode: 0, // Single
duelRule: (byte)(opt.DuelOptions >> 16),
noCheckDeck: false,
noShuffleDeck: false,
startLp: opt.StartLp,
startHand: (byte)opt.StartHand,
drawCount: (byte)opt.DrawCount,
timeLimit: 180));
return Finish(w);
}
private byte[] TypeChangePacket(int seat)
{
var w = NewPacket(STOC_TYPE_CHANGE);
StocCodecs.TypeChange.Write(w, new TypeChange((byte)seat, seat == 0));
return Finish(w);
}
private byte[] PlayerEnterPacket(string name, int pos)
{
var w = NewPacket(STOC_HS_PLAYER_ENTER);
StocCodecs.HsPlayerEnter.Write(w, new PlayerEnter(name, (byte)pos));
return Finish(w);
}
private byte[] PlayerChangePacket(int pos, int state)
{
var w = NewPacket(STOC_HS_PLAYER_CHANGE);
StocCodecs.HsPlayerChange.Write(w, new PlayerChange((byte)pos, (byte)state));
return Finish(w);
}
// ------------------------------------------------------------------
// Core setup
// ------------------------------------------------------------------
private void StartDuel()
{
duel = EngineApi.create_duel((uint)rng.Next(100, 99999));
if (duel == IntPtr.Zero) throw new Exception("create_duel returned null");
EngineApi.set_player_info(duel, 0, opt.StartLp, opt.StartHand, opt.DrawCount);
EngineApi.set_player_info(duel, 1, opt.StartLp, opt.StartHand, opt.DrawCount);
outcome.Lp[0] = outcome.Lp[1] = opt.StartLp;
for (var player = 0; player < 2; player++)
{
var seat = seatOfPlayer[player];
var main = new List<int>(seat == 0 ? opt.MainA : opt.MainB);
var extra = seat == 0 ? opt.ExtraA : opt.ExtraB;
Shuffle(main);
// ygoserver adds the main deck back to front so that index 0 of
// the shuffled list ends up on top of the deck.
for (var i = main.Count - 1; i >= 0; i--)
EngineApi.new_card(duel, (uint)main[i], (byte)player, (byte)player, LOCATION_DECK, 0, POS_FACEDOWN_DEFENCE);
if (extra != null)
foreach (var code in extra)
EngineApi.new_card(duel, (uint)code, (byte)player, (byte)player, LOCATION_EXTRA, 0, POS_FACEDOWN_DEFENCE);
}
// MSG_START is synthesised by the host (the core never emits it) and
// differs between the seats only in its first byte.
var start = new byte[18];
var ms = new MemoryStream(start);
var w = new BinaryWriter(ms);
w.Write((byte)0); // type: 0 = you are first
w.Write((byte)(opt.DuelOptions >> 16)); // duel_rule
w.Write(opt.StartLp);
w.Write(opt.StartLp);
w.Write((ushort)EngineApi.query_field_count(duel, 0, LOCATION_DECK));
w.Write((ushort)EngineApi.query_field_count(duel, 0, LOCATION_EXTRA));
w.Write((ushort)EngineApi.query_field_count(duel, 1, LOCATION_DECK));
w.Write((ushort)EngineApi.query_field_count(duel, 1, LOCATION_EXTRA));
SendGameMsg(seatOfPlayer[0], 4, start);
start[0] = 1;
SendGameMsg(seatOfPlayer[1], 4, start);
EngineApi.start_duel(duel, opt.DuelOptions);
RefreshAll();
DrainAll();
}
private void Shuffle(List<int> cards)
{
for (var i = cards.Count - 1; i > 0; i--)
{
var j = rng.Next(i + 1);
(cards[i], cards[j]) = (cards[j], cards[i]);
}
}
// ------------------------------------------------------------------
// The message loop
// ------------------------------------------------------------------
private void Loop()
{
var raw = new byte[0x20000];
var guard = 0;
while (true)
{
if (surrendered)
{
// ygoserver ends the duel with the surrendering player as the
// loser; the core is not involved.
var winnerPlayer = 1 - playerOfSeat[surrenderSeat];
Broadcast(GameMsgPacket(5, new[] { (byte)winnerPlayer, (byte)4 }));
DrainAll();
outcome.Winner = winnerPlayer;
outcome.Reason = 4;
return;
}
var result = (int)EngineApi.process(duel);
var len = result & 0xFFFF;
if (len <= 0)
{
if (++guard > 1000) throw new Exception("the core stopped producing messages");
continue;
}
guard = 0;
if (len > raw.Length) throw new Exception("core message buffer overflow (" + len + " bytes)");
EngineApi.get_message(duel, raw);
var verdict = Route(raw, len);
if (verdict == Verdict.Finished) return;
if (verdict == Verdict.Prompt)
{
AnswerPrompt();
if (surrendered) continue;
}
}
}
private enum Verdict { Continue, Prompt, Finished }
/// <summary>
/// TICKET-050: keep outcome.Lp current. All four messages are
/// player(1) + amount(int32); LP_UPDATE sets, the others move.
/// </summary>
private void TrackLifePoints(int id, byte[] buf, int bodyStart, int bodyEnd)
{
if (id != 91 && id != 92 && id != 94 && id != 100) return;
if (bodyEnd - bodyStart < 5) return;
int player = buf[bodyStart];
if (player < 0 || player > 1) return;
int amount = BitConverter.ToInt32(buf, bodyStart + 1);
switch (id)
{
case 91: case 100: outcome.Lp[player] -= amount; break; // DAMAGE / PAY_LPCOST
case 92: outcome.Lp[player] += amount; break; // RECOVER
case 94: outcome.Lp[player] = amount; break; // LP_UPDATE (authoritative)
}
if (outcome.Lp[player] < 0) outcome.Lp[player] = 0;
}
/// <summary>TICKET-050: monsters on the field when the duel stopped.</summary>
private void SnapshotPosition()
{
if (duel == IntPtr.Zero) return;
for (var p = 0; p < 2; p++)
{
try { outcome.Monsters[p] = EngineApi.query_field_count(duel, (byte)p, LOCATION_MZONE); }
catch (Exception) { outcome.Monsters[p] = 0; }
}
}
private Verdict Route(byte[] buf, int len)
{
var pos = 0;
while (pos < len)
{
var start = pos;
var id = buf[pos++];
var info = MessageScan.Scan(buf, ref pos, id, len);
var msg = new byte[pos - start - 1];
Buffer.BlockCopy(buf, start + 1, msg, 0, msg.Length);
if (++outcome.Messages > opt.MessageLimit)
throw new Exception("message limit reached — the duel is not converging");
if (info.NewTurn)
{
outcome.Turns++;
// TICKET-050: a rollout stops here and scores the position.
if (opt.StopAfterTurn > 0 && outcome.Turns > opt.StopAfterTurn)
{
outcome.Horizon = true;
SnapshotPosition();
return Verdict.Finished;
}
if (outcome.Turns > opt.TurnLimit)
throw new Exception("turn limit reached (" + opt.TurnLimit + ") — the board is not resolving");
}
TrackLifePoints(id, buf, start + 1, pos);
switch (id)
{
case 1: // MSG_RETRY — the core rejected the last response.
{
// Name what was rejected BEFORE handing the packet on:
// WindBot's own OnRetry throws out of DrainAll, and its
// message ("Last message is SelectIdleCmd") is the one
// that would otherwise reach the report.
var detail = RetryDetail();
try
{
SendGameMsg(seatOfPlayer[pendingResponsePlayer < 0 ? 0 : pendingResponsePlayer], id, msg);
DrainAll();
}
catch (Exception seat)
{
throw new Exception("MSG_RETRY (the core rejected a bot's answer): " + detail
+ " [seat threw: " + seat.Message + "]", seat);
}
throw new Exception("MSG_RETRY (the core rejected a bot's answer): " + detail);
}
case 5: // MSG_WIN
SnapshotPosition();
Broadcast(GameMsgPacket(id, msg));
DrainAll();
outcome.Winner = msg.Length > 0 ? msg[0] : -1;
outcome.Reason = msg.Length > 1 ? msg[1] : 0;
return Verdict.Finished;
default:
Dispatch(id, info, msg);
break;
}
PostRefresh(id);
if (info.Prompt)
{
pendingResponsePlayer = info.Player;
lastPromptId = id;
return Verdict.Prompt;
}
}
return Verdict.Continue;
}
private void Dispatch(int id, MessageScan.MsgInfo info, byte[] msg)
{
if (info.Prompt || info.ToPlayerOnly)
{
if (info.Prompt) pendingResponse = null;
SendGameMsg(seatOfPlayer[info.Player], id, MessageScan.Blank(id, msg, info, info.Player));
DrainSeat(seatOfPlayer[info.Player]);
return;
}
if (id == 2 && msg.Length >= 2) // MSG_HINT: u8 type, u8 player, i32 data
{
// [YGOL] Route hints like ygopro's SingleDuel (single_duel.cpp MSG_HINT):
// OPSELECTED/RACE/ATTRIB/CODE/NUMBER/ZONE (4,6,7,8,9,11) tell the OTHER
// player what `player` chose, so the chooser never gets its own; CARD and
// the music/sound hints (10,21-24) go to both; any other type to nobody.
// MessageScan has no "other player only" class, so it is decided here.
var type = msg[0];
if (type == 4 || type == 6 || type == 7 || type == 8 || type == 9 || type == 11)
{
var other = 1 - (msg[1] & 1);
SendGameMsg(seatOfPlayer[other], id, MessageScan.Blank(id, msg, info, other));
DrainSeat(seatOfPlayer[other]);
return;
}
if (type != 10 && (type < 21 || type > 24))
return;
}
for (var player = 0; player < 2; player++)
SendGameMsg(seatOfPlayer[player], id, MessageScan.Blank(id, msg, info, player));
DrainAll();
}
/// <summary>
/// What the core rejected, for the MSG_RETRY message: the prompt it was
/// answering and the raw answer bytes. For MSG_SELECT_IDLECMD (11) the
/// answer is one int32, `command | (index &lt;&lt; 16)` — command 0..5 =
/// summon / special summon / reposition / monster set / spell set /
/// activate — so the pair names exactly which idle command was illegal.
/// </summary>
private string RetryDetail()
{
var sb = new StringBuilder();
sb.Append("prompt ").Append(lastPromptId).Append(' ').Append(MessageScan.PromptName(lastPromptId));
sb.Append(", seat ").Append(pendingResponsePlayer < 0 ? -1 : seatOfPlayer[pendingResponsePlayer]);
if (lastAnswer == null || lastAnswer.Length == 0)
{
sb.Append(", answer <none>");
return sb.ToString();
}
sb.Append(", answer");
for (var i = 0; i < lastAnswer.Length && i < 16; i++) sb.Append(' ').Append(lastAnswer[i].ToString("x2"));
if (lastAnswer.Length >= 4)
{
var value = BitConverter.ToInt32(lastAnswer, 0);
sb.Append(" (int32 ").Append(value);
if (lastPromptId == 11)
sb.Append(" = idle command ").Append(IdleCommandName(value & 0xFFFF)).Append(" index ").Append((value >> 16) & 0xFFFF);
sb.Append(')');
}
return sb.ToString();
}
private static string IdleCommandName(int command)
{
switch (command)
{
case 0: return "Summon";
case 1: return "SpSummon";
case 2: return "Reposition";
case 3: return "MonsterSet";
case 4: return "SpellSet";
case 5: return "Activate";
case 6: return "ToBattle";
case 7: return "ToEndPhase";
default: return "cmd" + command;
}
}
private void AnswerPrompt()
{
// TICKET-050: while the script lasts the seats' own answers are
// thrown away and the recorded one is used, which is what walks a
// fresh duel back to a position reached in another one.
if (opt.ScriptedResponses != null && scriptedIndex < opt.ScriptedResponses.Count)
{
pendingResponse = opt.ScriptedResponses[scriptedIndex++];
if (pendingResponse == null)
throw new Exception("scripted response " + (scriptedIndex - 1) + " is null");
}
if (pendingResponse == null)
{
if (surrendered) return;
throw new Exception("seat " + seatOfPlayer[pendingResponsePlayer] + " did not answer a prompt");
}
outcome.Responses?.Add(pendingResponse);
// ygoserver always uses set_responseb with a zero-padded buffer, whatever the
// payload length was; the core copies SIZE_RETURN_VALUE (256) bytes from it.
var payload = pendingResponse;
pendingResponse = null;
lastAnswer = payload;
var scratch = new byte[256];
Buffer.BlockCopy(payload, 0, scratch, 0, Math.Min(payload.Length, 64));
EngineApi.set_responseb(duel, scratch);
}
/// <summary>
/// Which messages make the host re-query the field: the set
/// Percy.Ygopro.Analyse refreshes on, plus MSG_NEW_PHASE and MSG_CHAINED
/// so an ATK change from a continuous effect or a cost cannot go unseen
/// until the next event.
///
/// Measured (TICKET-045, 400 Weevil mirrors per arm): refresh FREQUENCY
/// barely matters — refreshing after literally every message, after this
/// set, or after Analyse's shorter set all land within noise of each
/// other (15.0 / 15.2 / 15.1 average turns, 49-53 % win rate). What did
/// matter was WHAT each refresh reveals, i.e. the blanking above. So
/// this set is chosen to be safe rather than minimal.
/// </summary>
private void PostRefresh(int id)
{
switch (id)
{
case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39:
case 41:
case 54:
case 61: case 63: case 65:
case 71: case 73: case 74: case 75: case 76:
case 90:
case 111: case 114:
RefreshAll();
DrainAll();
break;
}
}
// ------------------------------------------------------------------
// Refresh (MSG_UPDATE_DATA), per zone, per recipient
// ------------------------------------------------------------------
private void RefreshAll()
{
for (var p = 0; p < 2; p++) RefreshField(p, LOCATION_MZONE, QUERY_MZONE, 7);
for (var p = 0; p < 2; p++) RefreshField(p, LOCATION_SZONE, QUERY_SZONE, 8);
for (var p = 0; p < 2; p++) RefreshPile(p, LOCATION_HAND, QUERY_HAND, PileHiding.NonPublic);
for (var p = 0; p < 2; p++) RefreshPile(p, LOCATION_GRAVE, QUERY_PILE, PileHiding.None);
for (var p = 0; p < 2; p++) RefreshPile(p, LOCATION_REMOVED, QUERY_PILE, PileHiding.None);
for (var p = 0; p < 2; p++) RefreshPile(p, LOCATION_EXTRA, QUERY_PILE, PileHiding.All);
}
private enum PileHiding { None, NonPublic, All }
private byte[] Query(int player, int location, int flag)
{
var len = EngineApi.query_field_card(duel, (byte)player, (byte)location, (uint)flag, queryBuffer, 0);
var result = new byte[len];
if (len > 0) Buffer.BlockCopy(queryBuffer, 0, result, 0, len);
return result;
}
/// Monster/spell zones: fixed slot count; a face-down card is replaced by
/// an 8-byte "nothing changed" record for the opponent.
private void RefreshField(int player, int location, int flag, int slots)
{
var raw = Query(player, location, flag);
for (var recipient = 0; recipient < 2; recipient++)
{
var body = new MemoryStream();
var w = new BinaryWriter(body);
w.Write((byte)player);
w.Write((byte)location);
var o = 0;
for (var i = 0; i < slots; i++)
{
if (o + 4 > raw.Length) { w.Write(4); continue; }
var recLen = BitConverter.ToInt32(raw, o);
if (recLen == 4 || o + recLen > raw.Length) { w.Write(4); o += 4; continue; }
// Record layout: len(4) flag(4) code(4) position(4); the
// position field is controller/location/sequence/position,
// so the byte that carries POS_* is the record's 16th.
var pos = recLen > 15 ? raw[o + 15] : 0;
if (recipient != player && (pos & POS_FACEDOWN) != 0)
{
w.Write(8);
w.Write(0);
}
else
{
w.Write(raw, o, recLen);
}
o += recLen;
}
SendGameMsg(seatOfPlayer[recipient], 6 /* MSG_UPDATE_DATA */, body.ToArray());
}
}
/// Hand/grave/banished/extra: a flat run of records, hidden per rule.
private void RefreshPile(int player, int location, int flag, PileHiding hiding)
{
var raw = Query(player, location, flag);
for (var recipient = 0; recipient < 2; recipient++)
{
byte[] payload;
if (recipient == player || hiding == PileHiding.None)
{
payload = raw;
}
else
{
payload = (byte[])raw.Clone();
MessageScan.BlankPileCodes(payload, hiding == PileHiding.All);
}
var body = new byte[payload.Length + 2];
body[0] = (byte)player;
body[1] = (byte)location;
Buffer.BlockCopy(payload, 0, body, 2, payload.Length);
SendGameMsg(seatOfPlayer[recipient], 6 /* MSG_UPDATE_DATA */, body);
}
}
// ------------------------------------------------------------------
// Seat plumbing
// ------------------------------------------------------------------
private void Send(int seat, byte[] packet) => seats[seat].Deliver(packet);
private void Broadcast(byte[] packet)
{
seats[0].Deliver(packet);
seats[1].Deliver(packet);
}
private static byte[] GameMsgPacket(int id, byte[] body)
{
var packet = new byte[body.Length + 2];
packet[0] = STOC_GAME_MSG;
packet[1] = (byte)id;
Buffer.BlockCopy(body, 0, packet, 2, body.Length);
return packet;
}
private void SendGameMsg(int seat, int id, byte[] body) => seats[seat].Deliver(GameMsgPacket(id, body));
private void DrainAll()
{
DrainSeat(0);
DrainSeat(1);
}
private void DrainSeat(int seat)
{
seats[seat].Pump();
while (seats[seat].TryTakeCtos(out var packet))
HandleCtos(seat, packet);
var failed = seats[seat].Failed;
if (failed != null)
throw new Exception("seat " + seat + " (" + seats[seat].SeatName + ") failed: " + failed);
}
private void HandleCtos(int seat, byte[] packet)
{
if (packet == null || packet.Length == 0) return;
switch (packet[0])
{
case CTOS_RESPONSE:
{
var payload = new byte[packet.Length - 1];
Buffer.BlockCopy(packet, 1, payload, 0, payload.Length);
pendingResponse = payload;
break;
}
case CTOS_HAND_RESULT:
break; // rock-paper-scissors is gone (patch 0017): the server rolls, an answer is ignored
case CTOS_TP_RESULT:
if (packet.Length > 1) tpChoice = packet[1];
break;
case CTOS_SURRENDER:
surrendered = true;
surrenderSeat = seat;
break;
case CTOS_JOIN_GAME:
case CTOS_UPDATE_DECK:
default:
// PlayerInfo / ExternalAddress / JoinGame / UpdateDeck /
// HsReady / HsStart / Chat / TimeConfirm: the host does not
// need any of them — the decks come from the ydk files and
// the room is fixed.
break;
}
}
// ------------------------------------------------------------------
// Small writers
// ------------------------------------------------------------------
private static BinaryWriter NewPacket(byte stocId)
{
var w = new BinaryWriter(new MemoryStream());
w.Write(stocId);
return w;
}
private static byte[] Finish(BinaryWriter w) => ((MemoryStream)w.BaseStream).ToArray();
}
}
+82
View File
@@ -0,0 +1,82 @@
using System;
using WindBot.Game;
namespace YGOLegacy.Bot
{
// ------------------------------------------------------------------------
// TICKET-050 — rollout ("lookahead") planning for the idle command.
//
// The two halves of the hook live here so that neither the WindBot seam nor
// SmartExecutor has to know which oracle (if any) is installed:
//
// IIdlePlanner what the [YGOL] seam in GameAI.OnSelectIdleCmd looks
// for on the executor. SmartExecutor implements it.
// ILookaheadOracle what can actually produce a "future" for the duel
// currently in progress. NOTHING implements it inside the
// game: ocgcore cannot clone a live duel, so the only
// implementation is the arena's perfect-information
// ReplayOracle (Tools/BotArena/ReplayOracle.cs).
//
// With no oracle installed — every in-game duel today — SmartExecutor's
// planner declines and the executor walk runs exactly once, unchanged.
// ------------------------------------------------------------------------
/// <summary>
/// An executor that wants to choose its idle command by re-running the
/// WindBot executor walk under a veto set (see the [YGOL] seam in
/// <c>GameAI.OnSelectIdleCmd</c>).
/// </summary>
public interface IIdlePlanner
{
/// <summary>
/// Cheap gate asked before anything is copied or walked: false = the
/// seam behaves exactly as upstream.
/// </summary>
bool YGOL_WantsPlan();
/// <summary>
/// Pick an idle action. <paramref name="walk"/> runs the executor walk
/// with an "is this action allowed" predicate; returning a growing veto
/// set enumerates the executor's own top-K preferences in order.
/// </summary>
/// <returns>
/// The chosen <c>MainPhaseAction.ToValue()</c>, or null to fall back to
/// the plain walk. The caller re-runs the walk restricted to the chosen
/// value, so this method must not leave side effects behind.
/// </returns>
int? YGOL_PlanIdle(MainPhase main, Func<Func<MainPhaseAction, bool>, MainPhaseAction> walk);
}
/// <summary>
/// Something that can play the current duel forward from the prompt being
/// answered right now and say how a candidate answer turned out.
/// </summary>
public interface ILookaheadOracle
{
/// <summary>False = do not even try (no host attached, budget spent, …).</summary>
bool Available { get; }
/// <summary>
/// Value of answering the CURRENT idle prompt with
/// <paramref name="idleResponse"/> (a <c>MainPhaseAction.ToValue()</c>),
/// in 0..1 — 1 = we won every rollout, 0 = we lost every rollout.
/// <see cref="float.NaN"/> = could not be evaluated (the rollout
/// desynced, the budget ran out, …), which the caller treats as
/// "evaluator only".
/// </summary>
/// <param name="rollouts">playouts to average (knob <c>lookahead</c>).</param>
/// <param name="horizonTurns">
/// stop this many turns past the current one and score the position
/// instead of playing to the end (knob <c>lookaheadTurns</c>; 0 = play
/// to the end).
/// </param>
/// <param name="msBudget">
/// wall-clock ceiling for this whole call (knob <c>lookaheadMs</c>);
/// the oracle returns what it has when the budget is gone.
/// </param>
float Evaluate(int idleResponse, int rollouts, int horizonTurns, int msBudget);
/// <summary>Human-readable note about the last <see cref="Evaluate"/> (for the log).</summary>
string LastNote { get; }
}
}
+77
View File
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using WindBot.Game;
namespace YGOLegacy.Bot
{
/// <summary>
/// TICKET-045: a WindBot <see cref="GameClient"/> wired into
/// <see cref="LocalDuelHost"/> with no socket.
///
/// The client is built through the <c>[YGOL]</c> loopback seam
/// (<c>GameClient.YGOL_StartLoopback</c>): its <c>Send</c> lands in
/// <see cref="outbox"/> instead of a socket, and the host injects STOC
/// packets straight into the receive queue. Everything between those two
/// points is stock WindBot — the same <c>GameBehavior</c>, the same
/// <c>SmartExecutor</c>, the same <c>DuelStateBus</c> tap in
/// <c>OnPacketReceived</c>, the same <c>YGOL_DuelResult</c>.
///
/// Host and bot share one thread: <see cref="Pump"/> runs the client's
/// packet handlers inline, and WindBot answers a prompt from inside the
/// handler, so the answer is already in the outbox when Pump returns.
/// </summary>
public sealed class LoopbackBotSeat : ILoopbackSeat
{
private readonly Queue<byte[]> outbox = new Queue<byte[]>();
public GameClient Client { get; }
public string SeatName { get; }
/// <summary>Non-null once the client threw (a MSG_RETRY, mostly).</summary>
public Exception Failure { get; private set; }
/// <inheritdoc/>
public string Failed => Failure == null ? null : Failure.GetType().Name + ": " + Failure.Message;
/// <param name="client">
/// A GameClient that has NOT been Start()ed — this constructor starts it
/// on the loopback transport instead.
/// </param>
public LoopbackBotSeat(GameClient client, string seatName)
{
Client = client ?? throw new ArgumentNullException(nameof(client));
SeatName = seatName ?? client.Username;
Client.YGOL_StartLoopback(packet => outbox.Enqueue(packet));
}
public void Deliver(byte[] packet) => Client.YGOL_Receive(packet);
public void Pump()
{
if (Failure != null) return;
try
{
Client.Tick();
// Update() drains the whole queue, but a handler that queued
// more work (or a Connected event on the first tick) is cheap to
// finish here rather than waiting for the next Deliver.
var guard = 0;
while (Client.Connection.HasPendingPackets && ++guard < 64)
Client.Tick();
}
catch (Exception e)
{
// WindBot's OnRetry closes and rethrows; a broken bot must fail
// the duel, not the process.
Failure = e;
}
}
public bool TryTakeCtos(out byte[] packet)
{
if (outbox.Count == 0) { packet = null; return false; }
packet = outbox.Dequeue();
return true;
}
}
}
File diff suppressed because it is too large. Load diff
+286
View File
@@ -0,0 +1,286 @@
using System.Collections.Generic;
using Newtonsoft.Json;
namespace YGOLegacy.Characters
{
/// <summary>
/// A show duelist the fork can seat in a duel: art, lines, the decks they
/// pilot and the brain that pilots them. Loaded verbatim from
/// <c>Data/Characters/&lt;id&gt;/character.json</c> by CharacterRegistry —
/// this is a POCO for Newtonsoft, so keep it fields-only and default every
/// collection so a sparse JSON file never yields nulls downstream.
///
/// Decks are REFERENCED by "group/name" (the Deck/ path without ".ydk"),
/// never copied: Deck/ is the Syncthing-synced source of truth.
/// </summary>
public class Character
{
/// Stable key: the folder name. Never shown to the player.
public string id;
/// Display name (also the WindBot in-room name).
public string name;
/// Series the character is from ("Duel Monsters", "GX", ...).
public string show;
public string bio;
/// Optional card ground colour "#RRGGBB"; unset or invalid = the id-hash colour.
public string color;
/// Portrait for deck tiles / pickers: an image file relative to the
/// character folder (e.g. "portrait.png"), or "addressable:&lt;key&gt;"
/// for art already shipped in the game's Addressables (e.g.
/// "addressable:sn0001_2" — the Duel Links sprites). Null = no art;
/// the deck browser's character view falls back to deck-case tiles.
public string portrait;
/// Square (1:1) head-and-shoulders close-up for the in-duel LP
/// nameplate, relative to the character folder. A different asset
/// from `portrait` on purpose: that one is a full-body render, which
/// reads as an unrecognisable speck in a small icon. Unset = the duel
/// crops `portrait` to its head instead, and failing that keeps the
/// game's own placeholder face.
public string avatar;
public string angled;
/// How the Holo plate fits `angled`: `scale` multiplies the plate's slot
/// scale, `x`/`y` shift the art in plate px (y down). Missing = the slot's
/// own fit. Written back by the new HUD's dev nudge (TICKET-327).
public AngledFit angledFit = new();
/// Tall key art for the vs-screen / duel intro, relative to the character folder.
public string art;
/// Optional 3D model: a `Characters/<id>` folder name; unset = this character's own id.
public string model;
/// The decks this character owns, each with an optional brain of its
/// own. Empty = the character owns no deck (Dovphin). In JSON an entry
/// is either an object {"path","brain"} or a bare "group/name" string.
public DeckRef[] decks = System.Array.Empty<DeckRef>();
/// The default brain: used for every deck whose own `brain` is null.
public BrainConfig brain = new();
/// What this duelist calls a face-down monster when they attack one
/// ("that face-down monster" if unset). A face-down's real name is
/// never used: the attacker cannot know it, and printing it would
/// leak the board. Mirrors WindBot's facedownmonstername.
public string facedownName;
/// <summary>
/// Which Duel Links dialogue file(s) speak for this character —
/// "SN0403", or a LIST for a seat that is two duelists in the source
/// material (`umbra-lumis` is Lumis SN0032 and Umbra SN0033, and
/// their lines interleave). Written by
/// <c>Tools/CharacterVoice/map_voice_ids.py</c>, deliberately
/// explicit: matching our `name` against the Duel Links roster at
/// runtime would silently mis-seat Leon Wilson onto Leo.
///
/// Unset = no corpus; the character speaks from <see cref="lines"/>
/// alone, and is silent if it has none.
/// </summary>
[JsonProperty("voiceId")]
[JsonConverter(typeof(StringOrArrayConverter))]
public string[] voiceIds = System.Array.Empty<string>();
/// <summary>
/// <see cref="voiceIds"/> as the plain numbers the corpus uses to
/// point at an opponent ("SN0011" -> 11, matching a line's
/// `duelist: [11]`). Computed once on first use.
/// </summary>
[JsonIgnore]
public int[] VoiceNumbers
{
get
{
if (voiceNumbers != null)
return voiceNumbers;
var numbers = new List<int>(voiceIds.Length);
foreach (var id in voiceIds)
{
if (string.IsNullOrWhiteSpace(id))
continue;
var digits = id.Trim().TrimStart('S', 's', 'N', 'n');
if (int.TryParse(digits, out var number))
numbers.Add(number);
}
return voiceNumbers = numbers.ToArray();
}
}
[JsonIgnore] private int[] voiceNumbers;
/// Text lines keyed by event: welcome, duelstart, newturn, endturn,
/// attack, directattack, activate, summon, chaining, surrender, win, lose.
/// The OVERRIDE for the corpus, and the only source for a character
/// the corpus does not cover.
public Dictionary<string, string[]> lines = new();
/// Optional voice clips (relative paths), same keys as `lines`.
public Dictionary<string, string[]> voice = new();
/// Folder the file was read from (`Data/Characters/<id>`, forward
/// slashes); resolve `portrait`, `art` and `voice` against it. Not JSON.
[JsonIgnore] public string directory;
/// The brain that pilots one of this character's decks: the deck's own
/// if it declares one, else the character default. Null if the deck is
/// not this character's.
public BrainConfig BrainFor(string deckPath)
{
var deck = DeckFor(deckPath);
return deck == null ? null : deck.brain ?? brain;
}
public DeckRef DeckFor(string deckPath)
{
var key = NormalizeDeckPath(deckPath);
foreach (var deck in decks)
{
if (deck != null && string.Equals(NormalizeDeckPath(deck.path), key,
System.StringComparison.OrdinalIgnoreCase))
return deck;
}
return null;
}
/// The deck-reference form used for lookups: forward slashes, no
/// ".ydk", no surrounding whitespace (compared case-insensitively).
public static string NormalizeDeckPath(string path)
{
if (string.IsNullOrEmpty(path))
return string.Empty;
path = path.Trim().Replace('\\', '/').TrimStart('/');
if (path.EndsWith(".ydk", System.StringComparison.OrdinalIgnoreCase))
path = path.Substring(0, path.Length - 4);
return path;
}
}
/// <summary>
/// Reads `"SN0403"` or `["SN0032", "SN0033"]` into the same array, so a
/// caller never has to know which characters are pairs. Writes the short
/// form back when there is only one.
/// </summary>
public class StringOrArrayConverter : JsonConverter<string[]>
{
public override string[] ReadJson(JsonReader reader, System.Type objectType, string[] existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.Null:
return System.Array.Empty<string>();
case JsonToken.String:
return new[] { (string)reader.Value };
case JsonToken.StartArray:
return Newtonsoft.Json.Linq.JArray.Load(reader).ToObject<string[]>(serializer)
?? System.Array.Empty<string>();
default:
throw new JsonSerializationException(
"voiceId must be a string or an array of strings, got " + reader.TokenType);
}
}
public override void WriteJson(JsonWriter writer, string[] value, JsonSerializer serializer)
{
if (value == null || value.Length == 0) { writer.WriteNull(); return; }
if (value.Length == 1) { writer.WriteValue(value[0]); return; }
writer.WriteStartArray();
foreach (var id in value)
writer.WriteValue(id);
writer.WriteEndArray();
}
}
/// <summary>
/// One deck a character owns: its Deck/ path ("group/name", no ".ydk")
/// and, optionally, a brain that overrides the character default for this
/// deck only. Serialized either as an object or as a bare path string.
/// </summary>
[JsonConverter(typeof(DeckRefConverter))]
public class AngledFit
{
public float scale = 1f;
public float x;
public float y;
}
public class DeckRef
{
public string path;
/// Null = use the character's `brain`.
public BrainConfig brain;
// Empty = master only.
public string[] rulesets = System.Array.Empty<string>();
// Equals Ruleset.MasterId; BotArena links this file without Ruleset.cs.
public const string DefaultRuleset = "master";
public bool Plays(string rulesetId)
{
if (string.IsNullOrWhiteSpace(rulesetId))
rulesetId = DefaultRuleset;
if (rulesets == null || rulesets.Length == 0)
return string.Equals(rulesetId.Trim(), DefaultRuleset,
System.StringComparison.OrdinalIgnoreCase);
foreach (var id in rulesets)
if (string.Equals(id?.Trim(), rulesetId.Trim(), System.StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
}
/// Accepts `"group/name"` or `{ "path": "...", "brain": {...} | null, "rulesets": [...] }`.
public class DeckRefConverter : JsonConverter<DeckRef>
{
public override DeckRef ReadJson(JsonReader reader, System.Type objectType, DeckRef existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.Null:
return null;
case JsonToken.String:
return new DeckRef { path = (string)reader.Value };
case JsonToken.StartObject:
var obj = Newtonsoft.Json.Linq.JObject.Load(reader);
var brainToken = obj["brain"];
var hasBrain = brainToken != null && brainToken.Type != Newtonsoft.Json.Linq.JTokenType.Null;
var rulesetsToken = obj["rulesets"];
var hasRulesets = rulesetsToken != null && rulesetsToken.Type == Newtonsoft.Json.Linq.JTokenType.Array;
return new DeckRef
{
path = obj.Value<string>("path"),
brain = hasBrain ? brainToken.ToObject<BrainConfig>(serializer) : null,
rulesets = hasRulesets
? rulesetsToken.ToObject<string[]>(serializer) ?? System.Array.Empty<string>()
: System.Array.Empty<string>(),
};
default:
throw new JsonSerializationException(
"deck entry must be a \"group/name\" string or a {path, brain, rulesets} object, got " + reader.TokenType);
}
}
public override void WriteJson(JsonWriter writer, DeckRef value, JsonSerializer serializer)
{
if (value == null) { writer.WriteNull(); return; }
var hasRulesets = value.rulesets != null && value.rulesets.Length > 0;
if (value.brain == null && !hasRulesets) { writer.WriteValue(value.path); return; }
writer.WriteStartObject();
writer.WritePropertyName("path"); writer.WriteValue(value.path);
writer.WritePropertyName("brain"); serializer.Serialize(writer, value.brain);
if (hasRulesets)
{
writer.WritePropertyName("rulesets"); serializer.Serialize(writer, value.rulesets);
}
writer.WriteEndObject();
}
}
/// <summary>
/// Which AI pilots the character and how. `executor` is the WindBot
/// executor name (the `Deck=` token — "Lucky" is MDPro3's "play any deck"
/// brain); `difficulty` and `knobs` are read by the character-aware
/// executors of TICKET-029 and ignored by everything else.
/// </summary>
public class BrainConfig
{
public string executor = "Lucky";
public string difficulty;
public Dictionary<string, float> knobs = new();
/// Rule file for this brain, relative to the character folder
/// (e.g. "brain.battle-city.json"). Null/missing file -> "brain.json".
public string rules;
}
}
@@ -0,0 +1,282 @@
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using UnityEngine;
#if !YGOL_STANDALONE
using Cysharp.Threading.Tasks;
#endif
namespace YGOLegacy.Characters
{
/// <summary>
/// Every character on disk, read once at boot from
/// <c>Data/Characters/*/character.json</c>. Folders whose name starts with
/// "_" are templates and skipped. A file that fails to parse is logged as
/// <c>[YGOL characters] &lt;path&gt;: &lt;error&gt;</c> and skipped — a
/// broken character never breaks boot.
///
/// The scan runs on the thread pool; the results are published on the
/// main thread. Before Init completes (or if it was never called) the
/// registry is simply empty, and BotRoster falls back to its built-in
/// Dovphin, so callers need not await Loaded unless they need everyone.
///
/// Outside Unity (Tools/BotArena, compiled with YGOL_STANDALONE) the
/// UniTask surface is compiled out and <see cref="LoadFromDisk"/> — the
/// same scan + publish, synchronous — is the entry point. Both paths share
/// Scan/Publish, so the two never drift.
/// </summary>
public static class CharacterRegistry
{
public const string Root = "Data/Characters";
public const string FileName = "character.json";
private static readonly List<Character> all = new();
private static readonly Dictionary<string, Character> byId =
new(StringComparer.OrdinalIgnoreCase);
private static readonly Dictionary<string, Character> byDeck =
new(StringComparer.OrdinalIgnoreCase);
#if !YGOL_STANDALONE
private static UniTaskCompletionSource loadedSource;
/// Completes when the first Init() has published its results.
public static UniTask Loaded => (loadedSource ??= new UniTaskCompletionSource()).Task;
#endif
public static bool IsLoaded { get; private set; }
public static IReadOnlyList<Character> All() => all;
public static Character ById(string id)
=> !string.IsNullOrEmpty(id) && byId.TryGetValue(id, out var c) ? c : null;
/// <summary>
/// Does this character actually have art on disk (a portrait or an
/// avatar)? A character.json can name one that was never made, and a
/// good few characters have no art at all — so a UI that shows a
/// portrait needs to know BEFORE it decides between the portrait and
/// its own fallback (a deck case, an initial). Asking the texture
/// loader is no good: it returns null both for "no art" and for "still
/// loading". Cached, because callers ask per row per render.
/// </summary>
public static bool HasArt(string characterId)
{
var c = ById(characterId);
if (c == null)
return false;
lock (artCache)
{
if (artCache.TryGetValue(c.id, out var known))
return known;
var has = ArtExists(c, c.portrait) || ArtExists(c, c.avatar);
artCache[c.id] = has;
return has;
}
}
private static readonly Dictionary<string, bool> artCache =
new(StringComparer.OrdinalIgnoreCase);
private static bool ArtExists(Character c, string reference)
{
if (string.IsNullOrEmpty(reference))
return false;
// "addressable:<key>" points at art already shipped in the game;
// taking it on trust is right — the loader has its own fallback.
if (reference.StartsWith("addressable:", StringComparison.Ordinal))
return true;
return File.Exists(c.directory + "/" + reference.Replace('\\', '/'));
}
/// Reverse lookup: the character that owns a deck ("group/name" or
/// "name" for the root group; ".ydk" tolerated), or null.
public static Character ForDeck(string deckPath)
{
var key = Character.NormalizeDeckPath(deckPath);
return key.Length > 0 && byDeck.TryGetValue(key, out var c) ? c : null;
}
#if !YGOL_STANDALONE
/// <summary>
/// Scan the characters folder off the main thread and publish. Safe to
/// call again (a rescan replaces the tables); the first call is what
/// Program.Initialize awaits via Loaded.
/// </summary>
public static async UniTask Init()
{
loadedSource ??= new UniTaskCompletionSource();
List<Character> found;
List<string> problems;
try
{
(found, problems) = await UniTask.RunOnThreadPool(() => Scan(Root));
}
catch (Exception e)
{
found = new List<Character>();
problems = new List<string> { Root + ": " + e.Message };
}
await UniTask.SwitchToMainThread();
Publish(found, problems);
loadedSource.TrySetResult();
}
#endif
/// <summary>
/// Synchronous scan + publish on the calling thread, for hosts without
/// a player loop (Tools/BotArena). `charactersRoot` defaults to
/// <see cref="Root"/> relative to the current directory; pass an
/// absolute path to read another game root. Safe to call again.
/// </summary>
/// The root the last scan used (so <see cref="GroupKnobs"/> reads the
/// same tree, whether Unity or the standalone arena did the loading).
public static string LoadedRoot { get; private set; } = Root;
/// <summary>
/// Deck-GROUP base knobs: <c>&lt;root&gt;/_groups/&lt;Group&gt;.json</c>
/// (<c>{ "knobs": { ... } }</c>). A deck's own brain knobs override
/// these; these override the code defaults. Files under a leading
/// underscore are skipped by the character scan, so the folder is free.
/// Read once per group and cached; missing / unreadable = empty.
/// </summary>
public static IReadOnlyDictionary<string, float> GroupKnobs(string deckPath)
{
var key = Character.NormalizeDeckPath(deckPath);
int slash = key.IndexOf('/');
var group = slash > 0 ? key.Substring(0, slash) : string.Empty;
if (group.Length == 0) return Empty;
lock (groupKnobs)
{
if (groupKnobs.TryGetValue(group, out var cached)) return cached;
var result = Empty;
try
{
var file = Path.Combine(LoadedRoot, "_groups", group + ".json");
if (File.Exists(file))
{
var g = JsonConvert.DeserializeObject<GroupBase>(File.ReadAllText(file));
if (g?.knobs != null && g.knobs.Count > 0) result = g.knobs;
}
}
catch (Exception) { result = Empty; }
groupKnobs[group] = result;
return result;
}
}
private static readonly Dictionary<string, IReadOnlyDictionary<string, float>> groupKnobs =
new(StringComparer.OrdinalIgnoreCase);
private static readonly IReadOnlyDictionary<string, float> Empty = new Dictionary<string, float>();
private class GroupBase
{
public Dictionary<string, float> knobs;
}
public static void LoadFromDisk(string charactersRoot = null)
{
var root = string.IsNullOrEmpty(charactersRoot) ? Root : charactersRoot;
LoadedRoot = root;
lock (groupKnobs) groupKnobs.Clear();
List<Character> found;
List<string> problems;
try
{
(found, problems) = Scan(root);
}
catch (Exception e)
{
found = new List<Character>();
problems = new List<string> { root + ": " + e.Message };
}
Publish(found, problems);
}
/// Replace the tables with a scan's results and log its problems.
/// Main thread in Unity (readers are main-thread callers).
private static void Publish(List<Character> found, List<string> problems)
{
all.Clear();
byId.Clear();
byDeck.Clear();
lock (artCache) artCache.Clear(); // a rescan can add or remove art
foreach (var c in found)
{
if (byId.ContainsKey(c.id))
{
problems.Add(c.directory + "/" + FileName + ": duplicate id '" + c.id + "', skipped");
continue;
}
all.Add(c);
byId[c.id] = c;
foreach (var deck in c.decks)
{
var key = deck == null ? string.Empty : Character.NormalizeDeckPath(deck.path);
if (key.Length == 0)
continue;
// First owner wins; a shared deck is a data problem worth a line.
if (byDeck.TryGetValue(key, out var owner) && owner != c)
problems.Add(c.directory + "/" + FileName + ": deck '" + deck.path
+ "' already belongs to '" + owner.id + "'");
else
byDeck[key] = c;
}
}
foreach (var problem in problems)
Debug.LogError("[YGOL characters] " + problem);
IsLoaded = true;
}
/// Worker-thread part: pure file IO + JSON, no Unity API.
private static (List<Character>, List<string>) Scan(string root)
{
var found = new List<Character>();
var problems = new List<string>();
if (!Directory.Exists(root))
return (found, problems);
var dirs = Directory.GetDirectories(root);
Array.Sort(dirs, StringComparer.OrdinalIgnoreCase);
foreach (var dir in dirs)
{
var folder = Path.GetFileName(dir);
if (folder.StartsWith("_"))
continue;
var path = Path.Combine(dir, FileName).Replace('\\', '/');
if (!File.Exists(path))
continue;
try
{
var c = JsonConvert.DeserializeObject<Character>(File.ReadAllText(path));
if (c == null)
throw new JsonException("file is empty");
// The folder is the identity; the field is documentation.
if (!string.IsNullOrEmpty(c.id)
&& !string.Equals(c.id, folder, StringComparison.OrdinalIgnoreCase))
problems.Add(path + ": id '" + c.id + "' differs from folder '" + folder
+ "'; using the folder name");
c.id = folder;
if (string.IsNullOrEmpty(c.name))
c.name = folder;
c.decks ??= Array.Empty<DeckRef>();
c.decks = Array.FindAll(c.decks, d => d != null && !string.IsNullOrWhiteSpace(d.path));
c.brain ??= new BrainConfig();
if (string.IsNullOrEmpty(c.brain.executor))
c.brain.executor = "Lucky";
c.brain.knobs ??= new Dictionary<string, float>();
c.lines ??= new Dictionary<string, string[]>();
c.voice ??= new Dictionary<string, string[]>();
c.directory = dir.Replace('\\', '/');
found.Add(c);
}
catch (Exception e)
{
problems.Add(path + ": " + e.Message);
}
}
return (found, problems);
}
}
}
+278
View File
@@ -0,0 +1,278 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
using MDPro3.Utility;
using YGOLegacy.Characters;
using YGOLegacy.Core;
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";
#if !YGOL_STANDALONE
public static void Reload() => YGOLegacy.Core.Bot.SoloLoader.Reload();
private static IReadOnlyList<YGOLegacy.Core.Bot.SoloLoader.BotInfo> Conf()
{
if (!YGOLegacy.Core.Bot.SoloLoader.IsReady)
YGOLegacy.Core.Bot.SoloLoader.Initialize();
return YGOLegacy.Core.Bot.SoloLoader.Catalog;
}
#else
// Tools/BotArena parses the locale's bot.conf into this shim (Setup.ReadBots).
public static void Reload() { }
private static IReadOnlyList<MDPro3.Servant.SoloSelector.BotInfo> Conf() => MDPro3.Servant.SoloSelector.bots;
#endif
/// 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;
}
}
}
+141
View File
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace WindBot
{
public static class Config
{
private static string CONFIG_FILE_OPTION = "Config";
private static char SEPARATOR_CHAR = '=';
private static char COMMENT_CHAR = '#';
private static Dictionary<string, string> _fields;
private static Dictionary<string, int> _integerCache;
private static Dictionary<string, bool> _booleanCache;
public static void Load(string[] args)
{
_integerCache = new Dictionary<string, int>();
_booleanCache = new Dictionary<string, bool>();
_fields = LoadArgs(args);
string filename = GetString(CONFIG_FILE_OPTION);
if (filename != null)
{
Dictionary<string, string> fileFields = LoadFile(filename);
foreach (var pair in fileFields)
{
if (!_fields.ContainsKey(pair.Key))
_fields.Add(pair.Key, pair.Value);
}
}
}
private static Dictionary<string, string> LoadArgs(string[] args)
{
Dictionary<string, string> fields = new Dictionary<string, string>();
for (int i = 0; i < args.Length; ++i)
{
string option = args[i];
int position = option.IndexOf(SEPARATOR_CHAR);
if (position == -1)
throw new Exception("Invalid argument '" + option + "': no key/value separator");
string key = option.Substring(0, position).Trim().ToUpper();
string value = option.Substring(position + 1).Trim();
if (fields.ContainsKey(key))
throw new Exception("Invalid argument '" + option + "': duplicate key '" + key + "'");
fields.Add(key, value);
}
return fields;
}
private static Dictionary<string, string> LoadFile(string filename)
{
Dictionary<string, string> fields = new Dictionary<string, string>();
using (StreamReader reader = new StreamReader(filename))
{
int lineNumber = 0;
while (!reader.EndOfStream)
{
string line = reader.ReadLine().Trim();
++lineNumber;
// Ignore empty lines and comments
if (line.Length == 0 || line[0] == COMMENT_CHAR)
continue;
int position = line.IndexOf(SEPARATOR_CHAR);
if (position == -1)
throw new Exception("Invalid configuration file: no key/value separator line " + lineNumber);
string key = line.Substring(0, position).Trim().ToUpper();
string value = line.Substring(position + 1).Trim();
if (fields.ContainsKey(key))
throw new Exception("Invalid configuration file: duplicate key '" + key + "' line " + lineNumber);
fields.Add(key, value);
}
}
return fields;
}
public static string GetString(string key, string defaultValue = null)
{
key = key.ToUpper();
if (_fields.ContainsKey(key))
return _fields[key];
return defaultValue;
}
public static int GetInt(string key, int defaultValue = 0)
{
key = key.ToUpper();
// Use a cache to prevent doing the string to int conversion over and over
if (_integerCache.ContainsKey(key))
return _integerCache[key];
int value = defaultValue;
if (_fields.ContainsKey(key))
{
if (_fields[key].StartsWith("0x"))
value = Convert.ToInt32(_fields[key], 16);
else
value = Convert.ToInt32(_fields[key]);
}
_integerCache.Add(key, value);
return value;
}
public static uint GetUInt(string key, uint defaultValue = 0)
{
return (uint)GetInt(key, (int)defaultValue);
}
public static bool GetBool(string key, bool defaultValue = false)
{
key = key.ToUpper();
// Same here, prevent from redoing the string to bool conversion
if (_booleanCache.ContainsKey(key))
return _booleanCache[key];
bool value = defaultValue;
if (_fields.ContainsKey(key))
{
value = Convert.ToBoolean(_fields[key]);
}
_booleanCache.Add(key, value);
return value;
}
}
}
@@ -0,0 +1,565 @@
using System;
using System.Collections.Generic;
using System.Linq;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game.AI
{
public class AIUtil
{
public Duel Duel { get; private set; }
public ClientField Bot { get; private set; }
public ClientField Enemy { get; private set; }
public AIUtil(Duel duel)
{
Duel = duel;
Bot = Duel.Fields[0];
Enemy = Duel.Fields[1];
}
/// <summary>
/// Get the total ATK Monster of the player.
/// </summary>
public int GetTotalAttackingMonsterAttack(int player)
{
return Duel.Fields[player].GetMonsters().Where(m => m.IsAttack()).Sum(m => (int?)m.Attack) ?? 0;
}
/// <summary>
/// Get the best ATK or DEF power of the field.
/// </summary>
/// <param name="field">Bot or Enemy.</param>
/// <param name="onlyATK">Only calculate attack.</param>
public int GetBestPower(ClientField field, bool onlyATK = false)
{
return field.MonsterZone.GetMonsters()
.Where(card => !onlyATK || card.IsAttack())
.Max(card => (int?)card.GetDefensePower()) ?? -1;
}
public int GetBestAttack(ClientField field)
{
return GetBestPower(field, true);
}
public bool IsOneEnemyBetterThanValue(int value, bool onlyATK)
{
return Enemy.MonsterZone.GetMonsters()
.Any(card => card.GetDefensePower() > value && (!onlyATK || card.IsAttack()));
}
public bool IsAllEnemyBetterThanValue(int value, bool onlyATK)
{
List<ClientCard> monsters = Enemy.MonsterZone.GetMonsters();
return monsters.Count > 0 && monsters
.All(card => card.GetDefensePower() > value && (!onlyATK || card.IsAttack()));
}
/// <summary>
/// Deprecated, use IsOneEnemyBetter and IsAllEnemyBetter instead.
/// </summary>
public bool IsEnemyBetter(bool onlyATK, bool all)
{
if (all)
return IsAllEnemyBetter(onlyATK);
else
return IsOneEnemyBetter(onlyATK);
}
/// <summary>
/// Is there an enemy monster who has better power than the best power of the bot's?
/// </summary>
/// <param name="onlyATK">Only calculate attack.</param>
public bool IsOneEnemyBetter(bool onlyATK = false)
{
int bestBotPower = GetBestPower(Bot, onlyATK);
return IsOneEnemyBetterThanValue(bestBotPower, onlyATK);
}
/// <summary>
/// Do all enemy monsters have better power than the best power of the bot's?
/// </summary>
/// <param name="onlyATK">Only calculate attack.</param>
public bool IsAllEnemyBetter(bool onlyATK = false)
{
int bestBotPower = GetBestPower(Bot, onlyATK);
return IsAllEnemyBetterThanValue(bestBotPower, onlyATK);
}
public ClientCard GetBestBotMonster(bool onlyATK = false)
{
return Bot.MonsterZone.GetMonsters()
.Where(card => !onlyATK || card.IsAttack())
.OrderByDescending(card => card.GetDefensePower())
.FirstOrDefault();
}
public ClientCard GetWorstBotMonster(bool onlyATK = false)
{
return Bot.MonsterZone.GetMonsters()
.Where(card => !onlyATK || card.IsAttack())
.OrderBy(card => card.GetDefensePower())
.FirstOrDefault();
}
public ClientCard GetOneEnemyBetterThanValue(int value, bool onlyATK = false, bool canBeTarget = false)
{
return Enemy.MonsterZone.GetMonsters()
.FirstOrDefault(card => card.GetDefensePower() >= value && (!onlyATK || card.IsAttack()) && (!canBeTarget || !card.IsShouldNotBeTarget()));
}
public ClientCard GetOneEnemyBetterThanMyBest(bool onlyATK = false, bool canBeTarget = false)
{
int bestBotPower = GetBestPower(Bot, onlyATK);
return GetOneEnemyBetterThanValue(bestBotPower, onlyATK, canBeTarget);
}
public ClientCard GetProblematicEnemyCard(int attack = 0, bool canBeTarget = false)
{
ClientCard card = Enemy.MonsterZone.GetFloodgate(canBeTarget);
if (card != null)
return card;
card = Enemy.SpellZone.GetFloodgate(canBeTarget);
if (card != null)
return card;
card = Enemy.MonsterZone.GetDangerousMonster(canBeTarget);
if (card != null)
return card;
card = Enemy.MonsterZone.GetInvincibleMonster(canBeTarget);
if (card != null)
return card;
if (attack == 0)
attack = GetBestAttack(Bot);
return GetOneEnemyBetterThanValue(attack, true, canBeTarget);
}
public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false)
{
ClientCard card = Enemy.MonsterZone.GetFloodgate(canBeTarget);
if (card != null)
return card;
card = Enemy.MonsterZone.GetDangerousMonster(canBeTarget);
if (card != null)
return card;
card = Enemy.MonsterZone.GetInvincibleMonster(canBeTarget);
if (card != null)
return card;
if (attack == 0)
attack = GetBestAttack(Bot);
return GetOneEnemyBetterThanValue(attack, true, canBeTarget);
}
public ClientCard GetProblematicEnemySpell()
{
ClientCard card = Enemy.SpellZone.GetFloodgate();
return card;
}
public ClientCard GetBestEnemyCard(bool onlyFaceup = false, bool canBeTarget = false)
{
ClientCard card = GetBestEnemyMonster(onlyFaceup, canBeTarget);
if (card != null)
return card;
card = GetBestEnemySpell(onlyFaceup);
if (card != null)
return card;
return null;
}
public ClientCard GetBestEnemyMonster(bool onlyFaceup = false, bool canBeTarget = false)
{
ClientCard card = GetProblematicEnemyMonster(0, canBeTarget);
if (card != null)
return card;
card = Enemy.MonsterZone.GetHighestAttackMonster(canBeTarget);
if (card != null)
return card;
List<ClientCard> monsters = Enemy.GetMonsters();
// after GetHighestAttackMonster, the left monsters must be face-down.
if (monsters.Count > 0 && !onlyFaceup)
return monsters[0];
return null;
}
public ClientCard GetWorstEnemyMonster(bool onlyATK = false)
{
return Enemy.MonsterZone.GetMonsters()
.Where(card => !onlyATK || card.IsAttack())
.OrderBy(card => card.GetDefensePower())
.FirstOrDefault();
}
public ClientCard GetBestEnemySpell(bool onlyFaceup = false)
{
ClientCard card = GetProblematicEnemySpell();
if (card != null)
return card;
var spells = Enemy.GetSpells();
card = spells.FirstOrDefault(ecard => ecard.IsFaceup() && (ecard.HasType(CardType.Continuous) || ecard.HasType(CardType.Field)));
if (card != null)
return card;
if (spells.Count > 0 && !onlyFaceup)
return spells[0];
return null;
}
public ClientCard GetPZone(int player, int id)
{
if (Duel.IsNewRule)
{
return Duel.Fields[player].SpellZone[id * 4];
}
else
{
return Duel.Fields[player].SpellZone[6 + id];
}
}
public int GetStringId(int id, int option)
{
return id * 16 + option;
}
public bool IsTurn1OrMain2()
{
return Duel.Turn == 1 || Duel.Phase == DuelPhase.Main2;
}
public int GetBotAvailZonesFromExtraDeck(IList<ClientCard> remove)
{
ClientCard[] BotMZone = (ClientCard[])Bot.MonsterZone.Clone();
ClientCard[] EnemyMZone = (ClientCard[])Enemy.MonsterZone.Clone();
for (int i = 0; i < 7; i++)
{
if (remove.Contains(BotMZone[i])) BotMZone[i] = null;
if (remove.Contains(EnemyMZone[i])) EnemyMZone[i] = null;
}
if (!Duel.IsNewRule || Duel.IsNewRule2020)
return Zones.MainMonsterZones;
int result = 0;
if (BotMZone[5] == null && BotMZone[6] == null)
{
if (EnemyMZone[5] == null)
result |= Zones.z6;
if (EnemyMZone[6] == null)
result |= Zones.z5;
}
if (BotMZone[0] == null &&
((BotMZone[1]?.HasLinkMarker(CardLinkMarker.Left) ?? false) ||
(BotMZone[5]?.HasLinkMarker(CardLinkMarker.BottomLeft) ?? false) ||
(EnemyMZone[6]?.HasLinkMarker(CardLinkMarker.TopRight) ?? false)))
result |= Zones.z0;
if (BotMZone[1] == null &&
((BotMZone[0]?.HasLinkMarker(CardLinkMarker.Right) ?? false) ||
(BotMZone[2]?.HasLinkMarker(CardLinkMarker.Left) ?? false) ||
(BotMZone[5]?.HasLinkMarker(CardLinkMarker.Bottom) ?? false) ||
(EnemyMZone[6]?.HasLinkMarker(CardLinkMarker.Top) ?? false)))
result |= Zones.z1;
if (BotMZone[2] == null &&
((BotMZone[1]?.HasLinkMarker(CardLinkMarker.Right) ?? false) ||
(BotMZone[3]?.HasLinkMarker(CardLinkMarker.Left) ?? false) ||
(BotMZone[5]?.HasLinkMarker(CardLinkMarker.BottomRight) ?? false) ||
(EnemyMZone[6]?.HasLinkMarker(CardLinkMarker.TopLeft) ?? false) ||
(BotMZone[6]?.HasLinkMarker(CardLinkMarker.BottomLeft) ?? false) ||
(EnemyMZone[5]?.HasLinkMarker(CardLinkMarker.TopRight) ?? false)))
result |= Zones.z2;
if (BotMZone[3] == null &&
((BotMZone[2]?.HasLinkMarker(CardLinkMarker.Right) ?? false) ||
(BotMZone[4]?.HasLinkMarker(CardLinkMarker.Left) ?? false) ||
(BotMZone[6]?.HasLinkMarker(CardLinkMarker.Bottom) ?? false) ||
(EnemyMZone[5]?.HasLinkMarker(CardLinkMarker.Top) ?? false)))
result |= Zones.z3;
if (BotMZone[4] == null &&
((BotMZone[3]?.HasLinkMarker(CardLinkMarker.Right) ?? false) ||
(BotMZone[6]?.HasLinkMarker(CardLinkMarker.BottomRight) ?? false) ||
(EnemyMZone[5]?.HasLinkMarker(CardLinkMarker.TopLeft) ?? false)))
result |= Zones.z4;
return result;
}
public int GetBotAvailZonesFromExtraDeck(ClientCard remove)
{
return GetBotAvailZonesFromExtraDeck(new[] { remove });
}
public int GetBotAvailZonesFromExtraDeck()
{
return GetBotAvailZonesFromExtraDeck(new List<ClientCard>());
}
public bool IsChainTarget(ClientCard card)
{
return Duel.ChainTargets.Any(card.Equals);
}
public bool IsChainTargetOnly(ClientCard card)
{
return Duel.ChainTargetOnly.Count == 1 && card.Equals(Duel.ChainTargetOnly[0]);
}
public bool ChainContainsCard(int id)
{
return Duel.CurrentChain.Any(card => card.IsCode(id));
}
public bool ChainContainsCard(int[] ids)
{
return Duel.CurrentChain.Any(card => card.IsCode(ids));
}
public int ChainCountPlayer(int player)
{
return Duel.CurrentChain.Count(card => card.Controller == player);
}
public bool ChainContainPlayer(int player)
{
return Duel.CurrentChain.Any(card => card.Controller == player);
}
public bool HasChainedTrap(int player)
{
return Duel.CurrentChain.Any(card => card.Controller == player && card.HasType(CardType.Trap));
}
public ClientCard GetLastChainCard()
{
return Duel.CurrentChain.LastOrDefault();
}
/// <summary>
/// Select cards listed in preferred.
/// </summary>
public IList<ClientCard> SelectPreferredCards(ClientCard preferred, IList<ClientCard> cards, int min, int max)
{
IList<ClientCard> selected = new List<ClientCard>();
if (cards.IndexOf(preferred) > 0 && selected.Count < max)
{
selected.Add(preferred);
}
return selected;
}
/// <summary>
/// Select cards listed in preferred.
/// </summary>
public IList<ClientCard> SelectPreferredCards(int preferred, IList<ClientCard> cards, int min, int max)
{
IList<ClientCard> selected = new List<ClientCard>();
foreach (ClientCard card in cards)
{
if (card.IsCode(preferred) && selected.Count < max)
selected.Add(card);
}
return selected;
}
/// <summary>
/// Select cards listed in preferred.
/// </summary>
public IList<ClientCard> SelectPreferredCards(IList<ClientCard> preferred, IList<ClientCard> cards, int min, int max)
{
IList<ClientCard> selected = new List<ClientCard>();
IList<ClientCard> avail = cards.ToList(); // clone
while (preferred.Count > 0 && avail.IndexOf(preferred[0]) > 0 && selected.Count < max)
{
ClientCard card = preferred[0];
preferred.Remove(card);
avail.Remove(card);
selected.Add(card);
}
return selected;
}
/// <summary>
/// Select cards listed in preferred.
/// </summary>
public IList<ClientCard> SelectPreferredCards(IList<int> preferred, IList<ClientCard> cards, int min, int max)
{
IList<ClientCard> selected = new List<ClientCard>();
foreach (int id in preferred)
{
foreach (ClientCard card in cards)
{
if (card.IsCode(id) && selected.Count < max && selected.IndexOf(card) <= 0)
selected.Add(card);
}
if (selected.Count >= max)
break;
}
return selected;
}
/// <summary>
/// Check and fix selected to make sure it meet the count requirement.
/// </summary>
public IList<ClientCard> CheckSelectCount(IList<ClientCard> _selected, IList<ClientCard> cards, int min, int max)
{
var selected = _selected.Distinct().ToList();
if (selected.Count < min)
{
foreach (ClientCard card in cards)
{
if (!selected.Contains(card))
selected.Add(card);
if (selected.Count >= max)
break;
}
if (selected.Count < min)
{
#if DEBUG
throw new Exception("Not enough cards to CheckSelectCount");
#else
Logger.WriteErrorLine("Not enough cards to CheckSelectCount, using default");
return null;
#endif
}
}
while (selected.Count > max)
{
selected.RemoveAt(selected.Count - 1);
}
return selected;
}
/// <summary>
/// Get all xyz materials lists that xyz monster required level in the 'pre_materials' list
/// </summary>
/// <param name="param_pre_materials">Original materials</param>
/// <param name="level">Xyz monster required level</param>
/// <param name="material_count">SpSummon rule:number of xyz materials</param>
/// <param name="material_count_above">More xyz materials</param>
/// <param name="material_func">Filter xyz materials func</param>
/// <returns></returns>
public List<List<ClientCard>> GetXyzMaterials(IList<ClientCard> param_pre_materials, int level, int material_count, bool material_count_above = false, Func<ClientCard, bool> material_func = null)
{
List<List<ClientCard>> result = new List<List<ClientCard>>();
List<ClientCard> pre_materials = param_pre_materials?.Where(card => card != null && !(card.IsFacedown() & card.Location == CardLocation.MonsterZone) && card.Level == level && !card.IsMonsterNotBeXyzMaterial()).ToList();
if (pre_materials?.Count() < material_count) return result;
Func<ClientCard, bool> default_func = card => true;
material_func = material_func ?? default_func;
for (int i = 1; i < Math.Pow(2, pre_materials.Count); i++)
{
List<ClientCard> temp_materials = new List<ClientCard>();
string binaryString = Convert.ToString(i, 2).PadLeft(pre_materials.Count, '0');
char[] reversedBinaryChars = binaryString.Reverse().ToArray();
for (int j = 0; j < pre_materials.Count; j++)
{
if (reversedBinaryChars[j] == '1' && material_func(pre_materials[j]))
{
temp_materials.Add(pre_materials[j]);
}
}
if (material_count_above ? temp_materials.Count >= material_count : temp_materials.Count == material_count)
{
result.Add(temp_materials);
}
}
return result;
}
/// <summary>
/// Get all synchro materials lists that synchro monster level == param 'level' in the 'pre_materials' list
/// </summary>
/// <param name="pre_materials">Original materials</param>
/// <param name="level">Synchro monster level</param>
/// <param name="tuner_count">SpSummon rule:number of tuner monsters </param>
/// <param name="n_tuner_count">SpSummon rule:number of non-tuner monsters count</param>
/// <param name="tuner_count_above">More tuner monsters</param>
/// <param name="n_tuner_count_above">More non-tuner monsters</param>
/// <param name="tuner_func">Filter tuner monsters func</param>
/// <param name="n_tuner_func">Filter non-tuner monsters func</param>
/// <returns></returns>
public List<List<ClientCard>> GetSynchroMaterials(IList<ClientCard> param_pre_materials, int level, int tuner_count, int n_tuner_count, bool tuner_count_above = false, bool n_tuner_count_above = true, Func<ClientCard, bool> tuner_func = null, Func<ClientCard, bool> n_tuner_func = null)
{
List<List<ClientCard>> t_result = new List<List<ClientCard>>();
List<ClientCard> pre_materials = param_pre_materials?.Where(card => card != null && !(card.IsFacedown() & card.Location == CardLocation.MonsterZone) && card.Level > 0 && !card.IsMonsterNotBeSynchroMaterial()).ToList();
if (pre_materials?.Count() < tuner_count + n_tuner_count) return t_result;
Func<ClientCard, bool> default_func = card => true;
tuner_func = tuner_func ?? default_func;
n_tuner_func = n_tuner_func ?? default_func;
pre_materials.Sort(CardContainer.CompareCardLevel);
Stack<object[]> materials_stack = new Stack<object[]>();
for (var i = 0; i < pre_materials.Count; i++)
{
if (pre_materials[i].Level > level) break;
materials_stack.Push(new object[] { pre_materials[i].Level, i, pre_materials[i].Level, new List<ClientCard> { pre_materials[i] } });
}
while (materials_stack.Count > 0)
{
object[] data = materials_stack.Pop();
int num = (int)data[0];
int index = (int)data[1];
int sum = (int)data[2];
List<ClientCard> temp_materials = (List<ClientCard>)data[3];
if (sum == level)
{
t_result.Add(temp_materials);
}
else if (sum < level)
{
for (var i = index + 1; i < pre_materials.Count; i++)
{
if (pre_materials[i].Level > level - sum) break;
if (i > index + 1 && pre_materials[i].Level == pre_materials[i - 1].Level) continue;
var new_temp_materials = new List<ClientCard>(temp_materials);
new_temp_materials.Add(pre_materials[i]);
materials_stack.Push(new object[] { pre_materials[i].Level, i, sum + pre_materials[i].Level, new_temp_materials });
}
}
}
List<List<ClientCard>> result = new List<List<ClientCard>>();
for (int i = 0; i < t_result.Count; i++)
{
List<ClientCard> materials = t_result[i];
List<ClientCard> tuner_materials = new List<ClientCard>();
List<ClientCard> n_tuner_materials = new List<ClientCard>();
foreach (ClientCard material in materials)
{
if (material.HasType(CardType.Tuner) && tuner_func(material))
{
tuner_materials.Add(material);
}
else if (material.Level > 0 && n_tuner_func(material))
{
n_tuner_materials.Add(material);
}
}
if ((tuner_count_above ? tuner_materials.Count >= tuner_count : tuner_materials.Count == tuner_count)
&& (n_tuner_count_above ? n_tuner_materials.Count >= n_tuner_count : n_tuner_materials.Count == n_tuner_count))
result.Add(materials);
}
return result;
}
}
}
@@ -0,0 +1,168 @@
using System.Collections.Generic;
using YGOSharp.OCGWrapper.Enums;
using System;
using System.Linq;
namespace WindBot.Game.AI
{
public static class CardContainer
{
public static int CompareCardAttack(ClientCard cardA, ClientCard cardB)
{
if (cardA.Attack < cardB.Attack)
return -1;
if (cardA.Attack == cardB.Attack)
return 0;
return 1;
}
public static int CompareCardLevel(ClientCard cardA, ClientCard cardB)
{
if (cardA.Level < cardB.Level)
return -1;
if (cardA.Level == cardB.Level)
return 0;
return 1;
}
public static int CompareCardLink(ClientCard cardA, ClientCard cardB)
{
if (cardA.LinkCount < cardB.LinkCount)
return -1;
if (cardA.LinkCount == cardB.LinkCount)
return 0;
return 1;
}
public static int CompareDefensePower(ClientCard cardA, ClientCard cardB)
{
if (cardA == null && cardB == null)
return 0;
if (cardA == null)
return -1;
if (cardB == null)
return 1;
int powerA = cardA.GetDefensePower();
int powerB = cardB.GetDefensePower();
if (powerA < powerB)
return -1;
if (powerA == powerB)
return 0;
return 1;
}
public static ClientCard GetHighestAttackMonster(this IEnumerable<ClientCard> cards, bool canBeTarget = false)
{
return cards
.Where(card => card?.Data != null && card.HasType(CardType.Monster) && card.IsFaceup() && !(canBeTarget && card.IsShouldNotBeTarget()))
.OrderByDescending(card => card.Attack)
.FirstOrDefault();
}
public static ClientCard GetHighestDefenseMonster(this IEnumerable<ClientCard> cards, bool canBeTarget = false)
{
return cards
.Where(card => card?.Data != null && card.HasType(CardType.Monster) && card.IsFaceup() && !(canBeTarget && card.IsShouldNotBeTarget()))
.OrderByDescending(card => card.Defense)
.FirstOrDefault();
}
public static ClientCard GetLowestAttackMonster(this IEnumerable<ClientCard> cards, bool canBeTarget = false)
{
return cards
.Where(card => card?.Data != null && card.HasType(CardType.Monster) && card.IsFaceup() && !(canBeTarget && card.IsShouldNotBeTarget()))
.OrderBy(card => card.Attack)
.FirstOrDefault();
}
public static ClientCard GetLowestDefenseMonster(this IEnumerable<ClientCard> cards, bool canBeTarget = false)
{
return cards
.Where(card => card?.Data != null && card.HasType(CardType.Monster) && card.IsFaceup() && !(canBeTarget && card.IsShouldNotBeTarget()))
.OrderBy(card => card.Defense)
.FirstOrDefault();
}
public static bool ContainsMonsterWithLevel(this IEnumerable<ClientCard> cards, int level)
{
return cards.Where(card => card?.Data != null).Any(card => !card.HasType(CardType.Xyz) && card.Level == level);
}
public static bool ContainsMonsterWithRank(this IEnumerable<ClientCard> cards, int rank)
{
return cards.Where(card => card?.Data != null).Any(card => card.HasType(CardType.Xyz) && card.Rank == rank);
}
public static bool ContainsCardWithId(this IEnumerable<ClientCard> cards, int id)
{
return cards.Where(card => card?.Data != null).Any(card => card.IsCode(id));
}
public static int GetCardCount(this IEnumerable<ClientCard> cards, int id)
{
return cards.Where(card => card?.Data != null).Count(card => card.IsCode(id));
}
public static List<ClientCard> GetMonsters(this IEnumerable<ClientCard> cards)
{
return cards.Where(card => card?.Data != null && card.HasType(CardType.Monster)).ToList();
}
public static List<ClientCard> GetFaceupPendulumMonsters(this IEnumerable<ClientCard> cards)
{
return cards.Where(card => card?.Data != null && card.HasType(CardType.Monster) && card.IsFaceup() && card.HasType(CardType.Pendulum)).ToList();
}
public static ClientCard GetInvincibleMonster(this IEnumerable<ClientCard> cards, bool canBeTarget = false)
{
return cards.FirstOrDefault(card => card?.Data != null && card.IsMonsterInvincible() && card.IsFaceup() && (!canBeTarget || !card.IsShouldNotBeTarget()));
}
public static ClientCard GetDangerousMonster(this IEnumerable<ClientCard> cards, bool canBeTarget = false)
{
return cards.FirstOrDefault(card => card?.Data != null && card.IsMonsterDangerous() && card.IsFaceup() && (!canBeTarget || !card.IsShouldNotBeTarget()));
}
public static ClientCard GetFloodgate(this IEnumerable<ClientCard> cards, bool canBeTarget = false)
{
return cards.FirstOrDefault(card => card?.Data != null && card.IsFloodgate() && card.IsFaceup() && (!canBeTarget || !card.IsShouldNotBeTarget()));
}
public static ClientCard GetFirstMatchingCard(this IEnumerable<ClientCard> cards, Func<ClientCard, bool> filter)
{
return cards.FirstOrDefault(card => card?.Data != null && filter.Invoke(card));
}
public static ClientCard GetFirstMatchingFaceupCard(this IEnumerable<ClientCard> cards, Func<ClientCard, bool> filter)
{
return cards.FirstOrDefault(card => card?.Data != null && card.IsFaceup() && filter.Invoke(card));
}
public static IList<ClientCard> GetMatchingCards(this IEnumerable<ClientCard> cards, Func<ClientCard, bool> filter)
{
return cards.Where(card => card?.Data != null && filter.Invoke(card)).ToList();
}
public static int GetMatchingCardsCount(this IEnumerable<ClientCard> cards, Func<ClientCard, bool> filter)
{
return cards.Count(card => card?.Data != null && filter.Invoke(card));
}
public static bool IsExistingMatchingCard(this IEnumerable<ClientCard> cards, Func<ClientCard, bool> filter, int count = 1)
{
return cards.GetMatchingCardsCount(filter) >= count;
}
public static ClientCard GetShouldBeDisabledBeforeItUseEffectMonster(this IEnumerable<ClientCard> cards, bool canBeTarget = true)
{
return cards.FirstOrDefault(card => card?.Data != null && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && (!canBeTarget || !card.IsShouldNotBeTarget()));
}
public static IEnumerable<IEnumerable<T>> GetCombinations<T>(this IEnumerable<T> elements, int k)
{
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).GetCombinations(k - 1).Select(c => (new[] { e }).Concat(c)));
}
}
}
@@ -0,0 +1,18 @@
using System;
namespace WindBot.Game.AI
{
public class CardExecutor
{
public int CardId { get; private set; }
public ExecutorType Type { get; private set; }
public Func<bool> Func { get; private set; }
public CardExecutor(ExecutorType type, int cardId, Func<bool> func)
{
CardId = cardId;
Type = type;
Func = func;
}
}
}
@@ -0,0 +1,103 @@
using System;
using System.Linq;
using WindBot.Game.AI.Enums;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game.AI
{
public static class CardExtension
{
/// <summary>
/// Is this monster is invincible to battle?
/// </summary>
public static bool IsMonsterInvincible(this ClientCard card)
{
return !card.IsDisabled() &&
(card.Controller == 0 && Enum.IsDefined(typeof(InvincibleBotMonster), card.Id) ||
card.Controller == 1 && Enum.IsDefined(typeof(InvincibleEnemyMonster), card.Id));
}
/// <summary>
/// Is this monster is dangerous to attack?
/// </summary>
public static bool IsMonsterDangerous(this ClientCard card)
{
return !card.IsDisabled() &&
(Enum.IsDefined(typeof(DangerousMonster), card.Id) || (card.HasSetcode(0x18d) && (card.HasType(CardType.Ritual) || card.EquipCards.Count > 0)));
}
/// <summary>
/// Do this monster prevents activation of opponent's effect monsters in battle?
/// </summary>
public static bool IsMonsterHasPreventActivationEffectInBattle(this ClientCard card)
{
return !card.IsDisabled() && Enum.IsDefined(typeof(PreventActivationEffectInBattle), card.Id);
}
/// <summary>
/// Is this card shouldn't be tried to be selected as target?
/// </summary>
public static bool IsShouldNotBeTarget(this ClientCard card)
{
return !card.IsDisabled() && !card.HasType(CardType.Normal)
&& (Enum.IsDefined(typeof(ShouldNotBeTarget), card.Id) || card.Overlays.Any(code => code == 91025875));
}
/// <summary>
/// Is this card shouldn't be tried to be selected as target of monster?
/// </summary>
public static bool IsShouldNotBeMonsterTarget(this ClientCard card)
{
return !card.IsDisabled() && Enum.IsDefined(typeof(ShouldNotBeMonsterTarget), card.Id)
|| card.EquipCards.Any(c => c.IsCode(89812483) && !c.IsDisabled());
}
/// <summary>
/// Is this card shouldn't be tried to be selected as target of spell & trap?
/// </summary>
public static bool IsShouldNotBeSpellTrapTarget(this ClientCard card)
{
return !card.IsDisabled() && Enum.IsDefined(typeof(ShouldNotBeSpellTrapTarget), card.Id)
|| card.EquipCards.Any(c => c.IsCode(89812483) && !c.IsDisabled());
}
/// <summary>
/// Is this monster should be disabled (with Breakthrough Skill) before it use effect and release or banish itself?
/// </summary>
public static bool IsMonsterShouldBeDisabledBeforeItUseEffect(this ClientCard card)
{
return !card.IsDisabled() && Enum.IsDefined(typeof(ShouldBeDisabledBeforeItUseEffectMonster), card.Id);
}
public static bool IsFloodgate(this ClientCard card)
{
return Enum.IsDefined(typeof(Floodgate), card.Id);
}
public static bool IsOneForXyz(this ClientCard card)
{
return Enum.IsDefined(typeof(OneForXyz), card.Id);
}
public static bool IsFusionSpell(this ClientCard card)
{
return Enum.IsDefined(typeof(FusionSpell), card.Id);
}
/// <summary>
/// Is this monster not be synchro material?
/// </summary>
public static bool IsMonsterNotBeSynchroMaterial(this ClientCard card)
{
return Enum.IsDefined(typeof(NotBeSynchroMaterialMonster), card.Id);
}
/// <summary>
/// Is this monster not be xyz material?
/// </summary>
public static bool IsMonsterNotBeXyzMaterial(this ClientCard card)
{
return Enum.IsDefined(typeof(NotBeXyzMaterialMonster), card.Id);
}
}
}
@@ -0,0 +1,104 @@
using System.Collections.Generic;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game.AI
{
public class CardSelector
{
private enum SelectType
{
Card,
Cards,
Id,
Ids,
Location
}
private SelectType _type;
private ClientCard _card;
private IList<ClientCard> _cards;
private int _id;
private IList<int> _ids;
private CardLocation _location;
public CardSelector(ClientCard card)
{
_type = SelectType.Card;
_card = card;
}
public CardSelector(IList<ClientCard> cards)
{
_type = SelectType.Cards;
_cards = cards;
}
public CardSelector(int cardId)
{
_type = SelectType.Id;
_id = cardId;
}
public CardSelector(IList<int> ids)
{
_type = SelectType.Ids;
_ids = ids;
}
public CardSelector(CardLocation location)
{
_type = SelectType.Location;
_location = location;
}
public IList<ClientCard> Select(IList<ClientCard> cards, int min, int max)
{
IList<ClientCard> result = new List<ClientCard>();
switch (_type)
{
case SelectType.Card:
if (cards.Contains(_card))
result.Add(_card);
break;
case SelectType.Cards:
foreach (ClientCard card in _cards)
if (cards.Contains(card) && !result.Contains(card))
result.Add(card);
break;
case SelectType.Id:
foreach (ClientCard card in cards)
if (card.IsCode(_id))
result.Add(card);
break;
case SelectType.Ids:
foreach (int id in _ids)
foreach (ClientCard card in cards)
if (card.IsCode(id) && !result.Contains(card))
result.Add(card);
break;
case SelectType.Location:
foreach (ClientCard card in cards)
if (card.Location == _location)
result.Add(card);
break;
}
if (result.Count < min)
{
foreach (ClientCard card in cards)
{
if (!result.Contains(card))
result.Add(card);
if (result.Count >= min)
break;
}
}
while (result.Count > max)
result.RemoveAt(result.Count - 1);
return result;
}
}
}
@@ -0,0 +1,22 @@
using System;
namespace WindBot.Game.AI
{
[AttributeUsage(AttributeTargets.Class)]
public class DeckAttribute : Attribute
{
public string Name { get; private set; }
public string File { get; private set; }
public string Level { get; private set; }
public DeckAttribute(string name, string file = null, string level = "Normal")
{
if (String.IsNullOrEmpty(file))
file = name;
Name = name;
File = file;
Level = level;
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,173 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
// NOT FINISHED YET
[Deck("Blackwing", "AI_Blackwing", "NotFinished")]
public class BlackwingExecutor : DefaultExecutor
{
public class CardId
{
public const int KrisTheCrackOfDawn = 81105204;
public const int SiroccoTheDawn = 75498415;
public const int ShuraTheBlueFlame = 58820853;
public const int BoraTheSpear = 49003716;
public const int KalutTheMoonShadow = 85215458;
public const int GaleTheWhirlwind = 2009101;
public const int BlizzardTheFarNorth = 22835145;
public const int MistralTheSilverShield = 46710683;
public const int Raigeki = 12580477;
public const int DarkHole = 53129443;
public const int MysticalSpaceTyphoon = 5318639;
public const int BlackWhirlwind = 91351370;
public const int MirrorForce = 44095762;
public const int DeltaCrowAntiReverse = 59839761;
public const int DimensionalPrison = 70342110;
public const int SilverwindTheAscendant = 33236860;
public const int BlackWingedDragon = 9012916;
public const int ArmorMaster = 69031175;
public const int ArmedWing = 76913983;
public const int GramTheShiningStar = 17377751;
}
public BlackwingExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.Raigeki, DefaultRaigeki);
AddExecutor(ExecutorType.Activate, CardId.BlackWhirlwind, BlackWhirlwindEffect);
AddExecutor(ExecutorType.SpSummon, CardId.KrisTheCrackOfDawn);
AddExecutor(ExecutorType.SummonOrSet, CardId.KrisTheCrackOfDawn);
AddExecutor(ExecutorType.Summon, CardId.SiroccoTheDawn, SiroccoTheDawnSummon);
AddExecutor(ExecutorType.Summon, CardId.ShuraTheBlueFlame, ShuraTheBlueFlameSummon);
AddExecutor(ExecutorType.SummonOrSet, CardId.ShuraTheBlueFlame);
AddExecutor(ExecutorType.SpSummon, CardId.BoraTheSpear);
AddExecutor(ExecutorType.SummonOrSet, CardId.BoraTheSpear);
AddExecutor(ExecutorType.SummonOrSet, CardId.KalutTheMoonShadow, KalutTheMoonShadowSummon);
AddExecutor(ExecutorType.SpSummon, CardId.GaleTheWhirlwind);
AddExecutor(ExecutorType.SummonOrSet, CardId.GaleTheWhirlwind);
AddExecutor(ExecutorType.Summon, CardId.BlizzardTheFarNorth, BlizzardTheFarNorthSummon);
AddExecutor(ExecutorType.MonsterSet, CardId.MistralTheSilverShield);
AddExecutor(ExecutorType.SpSummon, CardId.SilverwindTheAscendant);
AddExecutor(ExecutorType.SpSummon, CardId.ArmorMaster);
AddExecutor(ExecutorType.SpSummon, CardId.GramTheShiningStar);
AddExecutor(ExecutorType.SpSummon, CardId.ArmedWing);
AddExecutor(ExecutorType.SpSummon, CardId.BlackWingedDragon);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.DimensionalPrison, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.DeltaCrowAntiReverse, DeltaCrowAntiReverseEffect);
AddExecutor(ExecutorType.Activate, CardId.BlizzardTheFarNorth);
AddExecutor(ExecutorType.Activate, CardId.ShuraTheBlueFlame);
AddExecutor(ExecutorType.Activate, CardId.BoraTheSpear, BoraTheSpearEffect);
AddExecutor(ExecutorType.Activate, CardId.KalutTheMoonShadow, AttackUpEffect);
AddExecutor(ExecutorType.Activate, CardId.SiroccoTheDawn, AttackUpEffect);
AddExecutor(ExecutorType.Activate, CardId.GaleTheWhirlwind, GaleTheWhirlwindEffect);
AddExecutor(ExecutorType.Activate, CardId.SilverwindTheAscendant);
AddExecutor(ExecutorType.Activate, CardId.BlackWingedDragon);
AddExecutor(ExecutorType.Activate, CardId.ArmorMaster);
AddExecutor(ExecutorType.Activate, CardId.ArmedWing);
AddExecutor(ExecutorType.Activate, CardId.GramTheShiningStar);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
private bool ShuraTheBlueFlameSummon()
{
if (Bot.HasInMonstersZone(CardId.SiroccoTheDawn) && Bot.GetMonsters().GetHighestAttackMonster().Attack < 3800)
return true;
return false;
}
private bool BlackWhirlwindEffect()
{
if (Card.Location == CardLocation.Hand && Bot.HasInSpellZone(Card.Id))
return false;
if (ActivateDescription == Util.GetStringId((int)Card.Id,0))
AI.SelectCard(CardId.GaleTheWhirlwind);
return true;
}
private bool SiroccoTheDawnSummon()
{
int OpponentMonster = Enemy.GetMonsterCount();
int AIMonster = Bot.GetMonsterCount();
if (OpponentMonster != 0 && AIMonster == 0)
return true;
return false;
}
private bool BoraTheSpearEffect()
{
List<ClientCard> monster = Bot.GetMonsters();
foreach (ClientCard card in monster)
if (card != null && card.IsCode(CardId.KrisTheCrackOfDawn, CardId.KalutTheMoonShadow, CardId.GaleTheWhirlwind, CardId.BoraTheSpear, CardId.SiroccoTheDawn, CardId.ShuraTheBlueFlame, CardId.BlizzardTheFarNorth))
return true;
return false;
}
private bool KalutTheMoonShadowSummon()
{
foreach (ClientCard card in Bot.Hand)
if (card != null && card.IsCode(CardId.KrisTheCrackOfDawn, CardId.GaleTheWhirlwind, CardId.BoraTheSpear, CardId.SiroccoTheDawn, CardId.ShuraTheBlueFlame, CardId.BlizzardTheFarNorth))
return false;
return true;
}
private bool BlizzardTheFarNorthSummon()
{
foreach (ClientCard card in Bot.Graveyard)
if (card != null && card.IsCode(CardId.KalutTheMoonShadow, CardId.BoraTheSpear, CardId.ShuraTheBlueFlame, CardId.KrisTheCrackOfDawn))
return true;
return false;
}
private bool DeltaCrowAntiReverseEffect()
{
int Count = 0;
List<ClientCard> monster = Bot.GetMonsters();
foreach (ClientCard card in monster)
if (card != null && card.IsCode(CardId.KrisTheCrackOfDawn, CardId.KalutTheMoonShadow, CardId.GaleTheWhirlwind, CardId.BoraTheSpear, CardId.SiroccoTheDawn, CardId.ShuraTheBlueFlame, CardId.BlizzardTheFarNorth))
Count++;
if (Count == 3)
return true;
return false;
}
private bool GaleTheWhirlwindEffect()
{
if (Card.Position == (int)CardPosition.FaceUp)
{
AI.SelectCard(Enemy.GetMonsters().GetHighestAttackMonster());
return true;
}
return false;
}
private bool AttackUpEffect()
{
ClientCard bestMy = Bot.GetMonsters().GetHighestAttackMonster();
ClientCard bestEnemyATK = Enemy.GetMonsters().GetHighestAttackMonster();
ClientCard bestEnemyDEF = Enemy.GetMonsters().GetHighestDefenseMonster();
if (bestMy == null || (bestEnemyATK == null && bestEnemyDEF == null))
return false;
if (bestEnemyATK != null && bestMy.Attack < bestEnemyATK.Attack)
return true;
if (bestEnemyDEF != null && bestMy.Attack < bestEnemyDEF.Defense)
return true;
return false;
}
}
}
@@ -0,0 +1,923 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using System.Linq;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Blue-Eyes", "AI_BlueEyes")]
class BlueEyesExecutor : DefaultExecutor
{
public class CardId
{
public const int WhiteDragon = 89631139;
public const int AlternativeWhiteDragon = 38517737;
public const int DragonSpiritOfWhite = 45467446;
public const int WhiteStoneOfAncients = 71039903;
public const int WhiteStoneOfLegend = 79814787;
public const int SageWithEyesOfBlue = 8240199;
public const int EffectVeiler = 97268402;
public const int GalaxyCyclone = 5133471;
public const int HarpiesFeatherDuster = 18144506;
public const int ReturnOfTheDragonLords = 6853254;
public const int PotOfDesires = 35261759;
public const int TradeIn = 38120068;
public const int CardsOfConsonance = 39701395;
public const int DragonShrine = 41620959;
public const int MelodyOfAwakeningDragon = 48800175;
public const int SoulCharge = 54447022;
public const int MonsterReborn = 83764718;
public const int SilversCry = 87025064;
public const int Giganticastle = 63422098;
public const int AzureEyesSilverDragon = 40908371;
public const int BlueEyesSpiritDragon = 59822133;
public const int GalaxyEyesDarkMatterDragon = 58820923;
public const int GalaxyEyesCipherBladeDragon = 2530830;
public const int GalaxyEyesFullArmorPhotonDragon = 39030163;
public const int GalaxyEyesPrimePhotonDragon = 31801517;
public const int GalaxyEyesCipherDragon = 18963306;
public const int HopeHarbingerDragonTitanicGalaxy = 63767246;
public const int SylvanPrincessprite = 33909817;
}
private List<ClientCard> UsedAlternativeWhiteDragon = new List<ClientCard>();
ClientCard UsedGalaxyEyesCipherDragon;
bool AlternativeWhiteDragonSummoned = false;
bool SoulChargeUsed = false;
public BlueEyesExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// destroy traps
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, CardId.GalaxyCyclone, DefaultGalaxyCyclone);
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster);
AddExecutor(ExecutorType.Activate, CardId.DragonShrine, DragonShrineEffect);
// Sage search
AddExecutor(ExecutorType.Summon, CardId.SageWithEyesOfBlue, SageWithEyesOfBlueSummon);
// search Alternative White Dragon
AddExecutor(ExecutorType.Activate, CardId.MelodyOfAwakeningDragon, MelodyOfAwakeningDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.CardsOfConsonance, CardsOfConsonanceEffect);
AddExecutor(ExecutorType.Activate, CardId.TradeIn, TradeInEffect);
AddExecutor(ExecutorType.Activate, CardId.PotOfDesires, DefaultPotOfDesires);
// spsummon Alternative White Dragon if possible
AddExecutor(ExecutorType.SpSummon, CardId.AlternativeWhiteDragon, AlternativeWhiteDragonSummon);
// reborn
AddExecutor(ExecutorType.Activate, CardId.ReturnOfTheDragonLords, RebornEffect);
AddExecutor(ExecutorType.Activate, CardId.SilversCry, RebornEffect);
AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, RebornEffect);
// monster effects
AddExecutor(ExecutorType.Activate, CardId.AlternativeWhiteDragon, AlternativeWhiteDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.SageWithEyesOfBlue, SageWithEyesOfBlueEffect);
AddExecutor(ExecutorType.Activate, CardId.WhiteStoneOfAncients, WhiteStoneOfAncientsEffect);
AddExecutor(ExecutorType.Activate, CardId.DragonSpiritOfWhite, DragonSpiritOfWhiteEffect);
AddExecutor(ExecutorType.Activate, CardId.BlueEyesSpiritDragon, BlueEyesSpiritDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.HopeHarbingerDragonTitanicGalaxy, HopeHarbingerDragonTitanicGalaxyEffect);
AddExecutor(ExecutorType.Activate, CardId.GalaxyEyesCipherDragon, GalaxyEyesCipherDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.GalaxyEyesPrimePhotonDragon, GalaxyEyesPrimePhotonDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.GalaxyEyesFullArmorPhotonDragon, GalaxyEyesFullArmorPhotonDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.GalaxyEyesCipherBladeDragon, GalaxyEyesCipherBladeDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.GalaxyEyesDarkMatterDragon, GalaxyEyesDarkMatterDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.AzureEyesSilverDragon, AzureEyesSilverDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.SylvanPrincessprite, SylvanPrincesspriteEffect);
// normal summon
AddExecutor(ExecutorType.Summon, CardId.SageWithEyesOfBlue, WhiteStoneSummon);
AddExecutor(ExecutorType.Summon, CardId.WhiteStoneOfAncients, WhiteStoneSummon);
AddExecutor(ExecutorType.Summon, CardId.WhiteStoneOfLegend, WhiteStoneSummon);
// special summon from extra
AddExecutor(ExecutorType.SpSummon, CardId.GalaxyEyesCipherDragon, GalaxyEyesCipherDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.GalaxyEyesPrimePhotonDragon, GalaxyEyesPrimePhotonDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.GalaxyEyesFullArmorPhotonDragon, GalaxyEyesFullArmorPhotonDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.GalaxyEyesCipherBladeDragon, GalaxyEyesCipherBladeDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.GalaxyEyesDarkMatterDragon, GalaxyEyesDarkMatterDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.Giganticastle, GiganticastleSummon);
AddExecutor(ExecutorType.SpSummon, CardId.BlueEyesSpiritDragon, BlueEyesSpiritDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.HopeHarbingerDragonTitanicGalaxy, HopeHarbingerDragonTitanicGalaxySummon);
AddExecutor(ExecutorType.SpSummon, CardId.SylvanPrincessprite, SylvanPrincesspriteSummon);
// if we don't have other things to do...
AddExecutor(ExecutorType.Activate, CardId.SoulCharge, SoulChargeEffect);
AddExecutor(ExecutorType.Repos, Repos);
// summon White Stone to use the hand effect of Sage
AddExecutor(ExecutorType.Summon, CardId.WhiteStoneOfLegend, WhiteStoneSummonForSage);
AddExecutor(ExecutorType.Summon, CardId.WhiteStoneOfAncients, WhiteStoneSummonForSage);
AddExecutor(ExecutorType.Summon, CardId.SageWithEyesOfBlue, WhiteStoneSummonForSage);
AddExecutor(ExecutorType.Activate, CardId.SageWithEyesOfBlue, SageWithEyesOfBlueEffectInHand);
// set White Stone of Legend frist
AddExecutor(ExecutorType.MonsterSet, CardId.WhiteStoneOfLegend);
AddExecutor(ExecutorType.MonsterSet, CardId.WhiteStoneOfAncients);
AddExecutor(ExecutorType.SpellSet, SpellSet);
}
public override void OnNewTurn()
{
// reset
UsedAlternativeWhiteDragon.Clear();
UsedGalaxyEyesCipherDragon = null;
AlternativeWhiteDragonSummoned = false;
SoulChargeUsed = false;
base.OnNewTurn();
}
public override IList<ClientCard> OnSelectCard(IList<ClientCard> cards, int min, int max, int hint, bool cancelable)
{
Logger.DebugWriteLine("OnSelectCard " + cards.Count + " " + min + " " + max);
if (max == 2 && cards[0].Location == CardLocation.Deck)
{
Logger.DebugWriteLine("OnSelectCard MelodyOfAwakeningDragon");
List<ClientCard> result = new List<ClientCard>();
if (!Bot.HasInHand(CardId.WhiteDragon))
result.AddRange(cards.Where(card => card.IsCode(CardId.WhiteDragon)).Take(1));
result.AddRange(cards.Where(card => card.IsCode(CardId.AlternativeWhiteDragon)));
return Util.CheckSelectCount(result, cards, min, max);
}
Logger.DebugWriteLine("Use default.");
return base.OnSelectCard(cards, min, max, hint, cancelable);
}
public override IList<ClientCard> OnSelectXyzMaterial(IList<ClientCard> cards, int min, int max)
{
Logger.DebugWriteLine("OnSelectXyzMaterial " + cards.Count + " " + min + " " + max);
IList<ClientCard> result = Util.SelectPreferredCards(UsedAlternativeWhiteDragon, cards, min, max);
return Util.CheckSelectCount(result, cards, min, max);
}
public override IList<ClientCard> OnSelectSynchroMaterial(IList<ClientCard> cards, int sum, int min, int max)
{
Logger.DebugWriteLine("OnSelectSynchroMaterial " + cards.Count + " " + sum + " " + min + " " + max);
if (sum != 8)
return null;
foreach (ClientCard AlternativeWhiteDragon in UsedAlternativeWhiteDragon)
{
if (cards.IndexOf(AlternativeWhiteDragon) > 0)
{
UsedAlternativeWhiteDragon.Remove(AlternativeWhiteDragon);
Logger.DebugWriteLine("select UsedAlternativeWhiteDragon");
return new[] { AlternativeWhiteDragon };
}
}
return null;
}
public override void OnSpSummoned()
{
// not special summoned by chain
if (Duel.GetCurrentSolvingChainCard() == null)
{
foreach (ClientCard card in Duel.LastSummonedCards)
{
if (card.Controller == 0 && card.IsCode(CardId.AlternativeWhiteDragon))
{
AlternativeWhiteDragonSummoned = true;
}
}
}
base.OnSpSummoned();
}
private bool DragonShrineEffect()
{
AI.SelectCard(
CardId.DragonSpiritOfWhite,
CardId.WhiteDragon,
CardId.WhiteStoneOfAncients,
CardId.WhiteStoneOfLegend
);
if (!Bot.HasInHand(CardId.WhiteDragon))
{
AI.SelectNextCard(CardId.WhiteStoneOfLegend);
}
else
{
AI.SelectNextCard(
CardId.WhiteStoneOfAncients,
CardId.DragonSpiritOfWhite,
CardId.WhiteStoneOfLegend
);
}
return true;
}
private bool MelodyOfAwakeningDragonEffect()
{
AI.SelectCard(
CardId.WhiteStoneOfAncients,
CardId.DragonSpiritOfWhite,
CardId.WhiteStoneOfLegend,
CardId.GalaxyCyclone,
CardId.EffectVeiler,
CardId.TradeIn,
CardId.SageWithEyesOfBlue
);
return true;
}
private bool CardsOfConsonanceEffect()
{
if (!Bot.HasInHand(CardId.WhiteDragon))
{
AI.SelectCard(CardId.WhiteStoneOfLegend);
}
else if (Bot.HasInHand(CardId.TradeIn))
{
AI.SelectCard(CardId.WhiteStoneOfLegend);
}
else
{
AI.SelectCard(CardId.WhiteStoneOfAncients);
}
return true;
}
private bool TradeInEffect()
{
if (Bot.HasInHand(CardId.DragonSpiritOfWhite))
{
AI.SelectCard(CardId.DragonSpiritOfWhite);
return true;
}
else if (HasTwoInHand(CardId.WhiteDragon))
{
AI.SelectCard(CardId.WhiteDragon);
return true;
}
else if (HasTwoInHand(CardId.AlternativeWhiteDragon))
{
AI.SelectCard(CardId.AlternativeWhiteDragon);
return true;
}
else if (!Bot.HasInHand(CardId.WhiteDragon) || !Bot.HasInHand(CardId.AlternativeWhiteDragon))
{
AI.SelectCard(CardId.WhiteDragon, CardId.AlternativeWhiteDragon);
return true;
}
else
{
return false;
}
}
private bool AlternativeWhiteDragonEffect()
{
ClientCard target = Util.GetProblematicEnemyMonster(Card.GetDefensePower());
if (target != null)
{
AI.SelectCard(target);
UsedAlternativeWhiteDragon.Add(Card);
return true;
}
if (Util.GetBotAvailZonesFromExtraDeck(Card) > 0
&& (Bot.HasInMonstersZone(new[]
{
CardId.SageWithEyesOfBlue,
CardId.WhiteStoneOfAncients,
CardId.WhiteStoneOfLegend,
CardId.WhiteDragon,
CardId.DragonSpiritOfWhite
}) || Bot.GetCountCardInZone(Bot.MonsterZone, CardId.AlternativeWhiteDragon) >= 2))
{
target = Util.GetBestEnemyMonster(false, true);
AI.SelectCard(target);
UsedAlternativeWhiteDragon.Add(Card);
return true;
}
return false;
}
private bool RebornEffect()
{
if (Duel.Player == 0 && Duel.CurrentChain.Count > 0)
{
// Silver's Cry spsummon Dragon Spirit at chain 2 will miss the timing
return false;
}
if (Duel.Player == 0 && (Duel.Phase == DuelPhase.Draw || Duel.Phase == DuelPhase.Standby))
{
// Let Azure-Eyes spsummon first
return false;
}
IList<int> targets = new[] {
CardId.HopeHarbingerDragonTitanicGalaxy,
CardId.GalaxyEyesDarkMatterDragon,
CardId.AlternativeWhiteDragon,
CardId.AzureEyesSilverDragon,
CardId.BlueEyesSpiritDragon,
CardId.WhiteDragon,
CardId.DragonSpiritOfWhite
};
if (!Bot.HasInGraveyard(targets))
{
return false;
}
ClientCard floodgate = Enemy.SpellZone.GetFloodgate();
if (floodgate != null && Bot.HasInGraveyard(CardId.DragonSpiritOfWhite))
{
AI.SelectCard(CardId.DragonSpiritOfWhite);
}
else
{
AI.SelectCard(targets);
}
return true;
}
private bool AzureEyesSilverDragonEffect()
{
if (Enemy.GetSpellCount() > 0)
{
AI.SelectCard(CardId.DragonSpiritOfWhite);
}
else
{
AI.SelectCard(CardId.WhiteDragon);
}
return true;
}
private bool SageWithEyesOfBlueSummon()
{
return !Bot.HasInHand(new[]
{
CardId.WhiteStoneOfAncients,
CardId.WhiteStoneOfLegend
});
}
private bool SageWithEyesOfBlueEffect()
{
if (Card.Location == CardLocation.Hand)
{
return false;
}
AI.SelectCard(
CardId.WhiteStoneOfAncients,
CardId.EffectVeiler,
CardId.WhiteStoneOfLegend
);
return true;
}
private bool WhiteStoneSummonForSage()
{
return Bot.HasInHand(CardId.SageWithEyesOfBlue);
}
private bool SageWithEyesOfBlueEffectInHand()
{
if (Card.Location != CardLocation.Hand)
{
return false;
}
if (!Bot.HasInMonstersZone(new[]
{
CardId.WhiteStoneOfLegend,
CardId.WhiteStoneOfAncients
}) || Bot.HasInMonstersZone(new[]
{
CardId.AlternativeWhiteDragon,
CardId.WhiteDragon,
CardId.DragonSpiritOfWhite
}))
{
return false;
}
AI.SelectCard(CardId.WhiteStoneOfLegend, CardId.WhiteStoneOfAncients);
if (Enemy.GetSpellCount() > 0)
{
AI.SelectNextCard(CardId.DragonSpiritOfWhite);
}
else
{
AI.SelectNextCard(CardId.WhiteDragon);
}
return true;
}
private bool DragonSpiritOfWhiteEffect()
{
if (ActivateDescription == -1)
{
ClientCard target = Util.GetBestEnemySpell();
AI.SelectCard(target);
return true;
}
else if (HaveEnoughWhiteDragonInHand())
{
if (Duel.Player == 0 && Duel.Phase == DuelPhase.BattleStart)
{
return Card.Attacked;
}
if (Duel.Player == 1 && Duel.Phase == DuelPhase.End)
{
return Bot.HasInMonstersZone(CardId.AzureEyesSilverDragon, true)
&& !Bot.HasInGraveyard(CardId.DragonSpiritOfWhite)
&& !Bot.HasInGraveyard(CardId.WhiteDragon);
}
if (Util.IsChainTarget(Card))
{
return true;
}
}
return false;
}
private bool BlueEyesSpiritDragonEffect()
{
if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.BlueEyesSpiritDragon, 0))
{
return Duel.LastChainPlayer == 1;
}
else if (Duel.Player == 1 && (Duel.Phase == DuelPhase.BattleStart || Duel.Phase == DuelPhase.End))
{
AI.SelectCard(CardId.AzureEyesSilverDragon);
return true;
}
else
{
if (Util.IsChainTarget(Card))
{
AI.SelectCard(CardId.AzureEyesSilverDragon);
return true;
}
return false;
}
}
private bool HopeHarbingerDragonTitanicGalaxyEffect()
{
if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.HopeHarbingerDragonTitanicGalaxy, 0))
{
return Duel.LastChainPlayer == 1;
}
return true;
}
private bool WhiteStoneOfAncientsEffect()
{
if (ActivateDescription == Util.GetStringId(CardId.WhiteStoneOfAncients, 0))
{
if (Bot.HasInHand(CardId.TradeIn)
&& !Bot.HasInHand(CardId.WhiteDragon)
&& !Bot.HasInHand(CardId.AlternativeWhiteDragon))
{
AI.SelectCard(CardId.WhiteDragon);
return true;
}
if (AlternativeWhiteDragonSummoned)
{
return false;
}
if (Bot.HasInHand(CardId.WhiteDragon)
&& !Bot.HasInHand(CardId.AlternativeWhiteDragon)
&& Bot.HasInGraveyard(CardId.AlternativeWhiteDragon))
{
AI.SelectCard(CardId.AlternativeWhiteDragon);
return true;
}
if (Bot.HasInHand(CardId.AlternativeWhiteDragon)
&& !Bot.HasInHand(CardId.WhiteDragon)
&& Bot.HasInGraveyard(CardId.WhiteDragon))
{
AI.SelectCard(CardId.WhiteDragon);
return true;
}
return false;
}
else
{
if (Enemy.GetSpellCount() > 0)
{
AI.SelectCard(CardId.DragonSpiritOfWhite);
}
else
{
AI.SelectCard(CardId.WhiteDragon);
}
return true;
}
}
private bool AlternativeWhiteDragonSummon()
{
return true;
}
private bool WhiteStoneSummon()
{
return Bot.HasInMonstersZone(new[]
{
CardId.SageWithEyesOfBlue,
CardId.WhiteStoneOfAncients,
CardId.WhiteStoneOfLegend,
CardId.AlternativeWhiteDragon,
CardId.WhiteDragon,
CardId.DragonSpiritOfWhite
});
}
private bool GalaxyEyesCipherDragonSummon()
{
if (Duel.Turn == 1 || SoulChargeUsed)
{
return false;
}
List<ClientCard> monsters = Enemy.GetMonsters();
if (monsters.Count == 1 && !monsters[0].IsFacedown() && ((monsters[0].IsDefense() && monsters[0].GetDefensePower() >= 3000) && monsters[0].HasType(CardType.Xyz)))
{
return true;
}
if (monsters.Count >= 3)
{
foreach (ClientCard monster in monsters)
{
if (!monster.IsFacedown() && ((monster.IsDefense() && monster.GetDefensePower() >= 3000) || monster.HasType(CardType.Xyz)))
{
return true;
}
}
}
return false;
}
private bool GalaxyEyesPrimePhotonDragonSummon()
{
if (Duel.Turn == 1)
{
return false;
}
if (Util.IsOneEnemyBetterThanValue(2999, false))
{
return true;
}
return false;
}
private bool GalaxyEyesFullArmorPhotonDragonSummon()
{
if (Bot.HasInMonstersZone(CardId.GalaxyEyesCipherDragon))
{
foreach (ClientCard monster in Bot.GetMonsters())
{
if ((monster.IsDisabled() && monster.HasType(CardType.Xyz) && !monster.Equals(UsedGalaxyEyesCipherDragon))
|| (Duel.Phase == DuelPhase.Main2 && monster.Equals(UsedGalaxyEyesCipherDragon)))
{
AI.SelectCard(monster);
return true;
}
}
}
if (Bot.HasInMonstersZone(CardId.GalaxyEyesPrimePhotonDragon))
{
if (!Util.IsOneEnemyBetterThanValue(4000, false))
{
AI.SelectCard(CardId.GalaxyEyesPrimePhotonDragon);
return true;
}
}
return false;
}
private bool GalaxyEyesCipherBladeDragonSummon()
{
if (Bot.HasInMonstersZone(CardId.GalaxyEyesFullArmorPhotonDragon) && Util.GetProblematicEnemyCard() != null)
{
AI.SelectCard(CardId.GalaxyEyesFullArmorPhotonDragon);
return true;
}
return false;
}
private bool GalaxyEyesDarkMatterDragonSummon()
{
if (Bot.HasInMonstersZone(CardId.GalaxyEyesFullArmorPhotonDragon))
{
AI.SelectCard(CardId.GalaxyEyesFullArmorPhotonDragon);
return true;
}
return false;
}
private bool GalaxyEyesPrimePhotonDragonEffect()
{
return true;
}
private bool GalaxyEyesCipherDragonEffect()
{
List<ClientCard> monsters = Enemy.GetMonsters();
foreach (ClientCard monster in monsters)
{
if (monster.HasType(CardType.Xyz))
{
AI.SelectCard(monster);
UsedGalaxyEyesCipherDragon = Card;
return true;
}
}
foreach (ClientCard monster in monsters)
{
if (monster.IsDefense())
{
AI.SelectCard(monster);
UsedGalaxyEyesCipherDragon = Card;
return true;
}
}
UsedGalaxyEyesCipherDragon = Card;
return true;
}
private bool GalaxyEyesFullArmorPhotonDragonEffect()
{
ClientCard target = Util.GetProblematicEnemySpell();
if (target != null)
{
AI.SelectCard(target);
return true;
}
target = Util.GetProblematicEnemyMonster();
if (target != null)
{
AI.SelectCard(target);
return true;
}
foreach (ClientCard spell in Enemy.GetSpells())
{
if (spell.IsFaceup())
{
AI.SelectCard(spell);
return true;
}
}
List<ClientCard> monsters = Enemy.GetMonsters();
if (monsters.Count >= 2)
{
foreach (ClientCard monster in monsters)
{
if (monster.IsDefense())
{
AI.SelectCard(monster);
return true;
}
}
return true;
}
if (monsters.Count == 2)
{
foreach (ClientCard monster in monsters)
{
if (monster.IsMonsterInvincible() || monster.IsMonsterDangerous() || monster.GetDefensePower() > 4000)
{
AI.SelectCard(monster);
return true;
}
}
}
if (monsters.Count == 1)
{
return true;
}
return false;
}
private bool GalaxyEyesCipherBladeDragonEffect()
{
if (Card.Location == CardLocation.Grave)
{
return true;
}
ClientCard target = Util.GetProblematicEnemyCard();
if (target != null)
{
AI.SelectCard(target);
return true;
}
List<ClientCard> monsters = Enemy.GetMonsters();
foreach (ClientCard monster in monsters)
{
if (monster.IsDefense())
{
AI.SelectCard(monster);
return true;
}
}
foreach (ClientCard monster in monsters)
{
AI.SelectCard(monster);
return true;
}
List<ClientCard> spells = Enemy.GetSpells();
foreach (ClientCard spell in spells)
{
if (spell.IsFacedown())
{
AI.SelectCard(spell);
return true;
}
}
foreach (ClientCard spell in spells)
{
AI.SelectCard(spell);
return true;
}
return false;
}
private bool GalaxyEyesDarkMatterDragonEffect()
{
AI.SelectCard(
CardId.WhiteStoneOfAncients,
CardId.WhiteStoneOfLegend,
CardId.DragonSpiritOfWhite,
CardId.WhiteDragon
);
AI.SelectNextCard(
CardId.WhiteStoneOfAncients,
CardId.WhiteStoneOfLegend,
CardId.DragonSpiritOfWhite,
CardId.WhiteDragon
);
return true;
}
private bool GiganticastleSummon()
{
if (Duel.Phase != DuelPhase.Main1 || Duel.Turn == 1 || SoulChargeUsed)
return false;
int bestSelfAttack = Util.GetBestAttack(Bot);
int bestEnemyAttack = Util.GetBestPower(Enemy);
return bestSelfAttack <= bestEnemyAttack && bestEnemyAttack > 2500 && bestEnemyAttack <= 3100;
}
private bool BlueEyesSpiritDragonSummon()
{
if (Duel.Phase == DuelPhase.Main1)
{
if (UsedAlternativeWhiteDragon.Count > 0)
{
return true;
}
if (Duel.Turn == 1 || SoulChargeUsed)
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
}
if (Duel.Phase == DuelPhase.Main2)
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool HopeHarbingerDragonTitanicGalaxySummon()
{
if (Duel.Phase == DuelPhase.Main1)
{
if (UsedAlternativeWhiteDragon.Count > 0)
{
return true;
}
if (Duel.Turn == 1 || SoulChargeUsed)
{
return true;
}
}
if (Duel.Phase == DuelPhase.Main2)
{
return true;
}
return false;
}
private bool SylvanPrincesspriteSummon()
{
if (Duel.Turn == 1)
{
return true;
}
if (Duel.Phase == DuelPhase.Main1 && !Bot.HasInMonstersZone(new[]
{
CardId.AlternativeWhiteDragon,
CardId.WhiteDragon,
CardId.DragonSpiritOfWhite
}))
{
return true;
}
if (Duel.Phase == DuelPhase.Main2 || SoulChargeUsed)
{
return true;
}
return false;
}
private bool SylvanPrincesspriteEffect()
{
AI.SelectCard(CardId.WhiteStoneOfLegend, CardId.WhiteStoneOfAncients);
return true;
}
private bool SoulChargeEffect()
{
if (Bot.HasInMonstersZone(CardId.BlueEyesSpiritDragon, true))
return false;
int count = Bot.GetGraveyardMonsters().Count;
int space = 5 - Bot.GetMonstersInMainZone().Count;
if (count < space)
count = space;
if (count < 2 || Bot.LifePoints < count*1000)
return false;
if (Duel.Turn != 1)
{
int attack = 0;
int defence = 0;
foreach (ClientCard monster in Bot.GetMonsters())
{
if (!monster.IsDefense())
{
attack += monster.Attack;
}
}
foreach (ClientCard monster in Enemy.GetMonsters())
{
defence += monster.GetDefensePower();
}
if (attack - defence > Enemy.LifePoints)
return false;
}
AI.SelectCard(
CardId.BlueEyesSpiritDragon,
CardId.HopeHarbingerDragonTitanicGalaxy,
CardId.AlternativeWhiteDragon,
CardId.WhiteDragon,
CardId.DragonSpiritOfWhite,
CardId.AzureEyesSilverDragon,
CardId.WhiteStoneOfAncients,
CardId.WhiteStoneOfLegend
);
SoulChargeUsed = true;
return true;
}
private bool Repos()
{
bool enemyBetter = Util.IsAllEnemyBetter(true);
if (Card.IsAttack() && enemyBetter)
return true;
if (Card.IsFacedown())
return true;
if (Card.IsDefense() && !enemyBetter && Card.Attack >= Card.Defense)
return true;
if (Card.IsDefense() && Card.IsCode(CardId.BlueEyesSpiritDragon, CardId.AzureEyesSilverDragon))
return true;
if (Card.IsAttack() && Card.IsCode(CardId.SageWithEyesOfBlue, CardId.WhiteStoneOfAncients, CardId.WhiteStoneOfLegend))
return true;
return false;
}
private bool SpellSet()
{
return (Card.IsTrap() || Card.IsCode(CardId.SilversCry)) && Bot.GetSpellCountWithoutField() < 4;
}
private bool HasTwoInHand(int id)
{
int num = 0;
foreach (ClientCard card in Bot.Hand)
{
if (card != null && card.IsCode(id))
num++;
}
return num >= 2;
}
private bool HaveEnoughWhiteDragonInHand()
{
return HasTwoInHand(CardId.WhiteDragon) || (
Bot.HasInGraveyard(CardId.WhiteDragon)
&& Bot.HasInGraveyard(CardId.WhiteStoneOfAncients)
);
}
}
}
@@ -0,0 +1,620 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("BlueEyesMaxDragon", "AI_BlueEyesMaxDragon")]
public class BlueEyesMaxDragonExecutor : DefaultExecutor
{
public class CardId
{
public const int BlueEyesWhiteDragon = 89631139;
public const int BlueEyesAlternativeWhiteDragon = 38517737;
public const int DeviritualTalismandra = 80701178;
public const int ManguOfTheTenTousandHands = 95492061;
public const int DevirrtualCandoll = 53303460;
public const int AshBlossom = 14558127;
public const int MaxxC = 23434538;
public const int BlueEyesChaosMaxDragon = 55410871;
public const int CreatureSwap= 31036355;
public const int TheMelodyOfAwakeningDragon = 48800175;
public const int UpstartGoblin = 70368879;
public const int ChaosForm = 21082832;
public const int AdvancedRitualArt = 46052429;
public const int CalledByTheGrave = 24224830;
public const int Scapegoat = 73915051;
public const int InfiniteImpermanence = 10045474;
public const int RecklessGreed = 37576645;
public const int BorreloadDragon = 31833038;
public const int BirrelswordDragon = 85289965;
public const int KnightmareGryphon = 65330383;
public const int MissusRadiant = 3987233;
public const int LinkSpider = 98978921;
public const int Linkuriboh = 41999284;
public const int LockBird = 94145021;
public const int Ghost = 59438930;
}
public BlueEyesMaxDragonExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
//counter
AddExecutor(ExecutorType.Activate, CardId.AshBlossom, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, CardId.MaxxC, MaxxCeff);
AddExecutor(ExecutorType.Activate, CardId.InfiniteImpermanence, DefaultInfiniteImpermanence);
AddExecutor(ExecutorType.Activate, CardId.CalledByTheGrave, CalledByTheGraveeff);
//first
AddExecutor(ExecutorType.Activate, CardId.UpstartGoblin);
AddExecutor(ExecutorType.Activate, CardId.BlueEyesAlternativeWhiteDragon, BlueEyesAlternativeWhiteDragoneff);
AddExecutor(ExecutorType.Activate, CardId.CreatureSwap, CreatureSwapeff);
AddExecutor(ExecutorType.Activate, CardId.TheMelodyOfAwakeningDragon, TheMelodyOfAwakeningDragoneff);
//summon
AddExecutor(ExecutorType.Summon, CardId.ManguOfTheTenTousandHands);
AddExecutor(ExecutorType.Activate, CardId.ManguOfTheTenTousandHands, TenTousandHandseff);
AddExecutor(ExecutorType.Activate, DeviritualCheck);
//ritual summon
AddExecutor(ExecutorType.Activate, CardId.AdvancedRitualArt);
AddExecutor(ExecutorType.Activate, CardId.ChaosForm, ChaosFormeff);
//sp summon
AddExecutor(ExecutorType.SpSummon, CardId.MissusRadiant, MissusRadiantsp);
AddExecutor(ExecutorType.Activate, CardId.MissusRadiant, MissusRadianteff);
AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, Linkuriboheff);
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp);
AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider);
AddExecutor(ExecutorType.SpSummon, CardId.BirrelswordDragon, BirrelswordDragonsp);
AddExecutor(ExecutorType.Activate, CardId.BirrelswordDragon, BirrelswordDragoneff);
//set
AddExecutor(ExecutorType.Activate, CardId.TheMelodyOfAwakeningDragon, TheMelodyOfAwakeningDragoneffsecond);
AddExecutor(ExecutorType.SpellSet, SpellSet);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
//
AddExecutor(ExecutorType.Activate, CardId.RecklessGreed, RecklessGreedeff);
AddExecutor(ExecutorType.Activate, CardId.Scapegoat, Scapegoateff);
}
int Talismandra_count = 0;
int Candoll_count = 0;
bool Talismandra_used = false;
bool Candoll_used = false;
int RitualArt_count = 0;
int ChaosForm_count = 0;
int MaxDragon_count = 0;
int TheMelody_count = 0;
public override void OnNewTurn()
{
Talismandra_used = false;
Candoll_used = false;
base.OnNewTurn();
}
private void Count_check()
{
TheMelody_count = 0;
Talismandra_count = 0;
Candoll_count = 0;
RitualArt_count = 0;
ChaosForm_count = 0;
MaxDragon_count = 0;
foreach (ClientCard check in Bot.Hand)
{
if (check.IsCode(CardId.AdvancedRitualArt))
RitualArt_count++;
if (check.IsCode(CardId.ChaosForm))
ChaosForm_count++;
if (check.IsCode(CardId.DevirrtualCandoll))
Candoll_count++;
if (check.IsCode(CardId.DeviritualTalismandra))
Talismandra_count++;
if (check.IsCode(CardId.BlueEyesChaosMaxDragon))
MaxDragon_count++;
if (check.IsCode(CardId.TheMelodyOfAwakeningDragon))
TheMelody_count++;
}
}
private bool MaxxCeff()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
return Duel.Player == 1;
}
private bool CalledByTheGraveeff()
{
if(Duel.LastChainPlayer==1)
{
ClientCard lastCard = Util.GetLastChainCard();
if (lastCard.IsCode(CardId.MaxxC))
{
AI.SelectCard(CardId.MaxxC);
if(Util.ChainContainsCard(CardId.TheMelodyOfAwakeningDragon))
AI.SelectNextCard(CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesAlternativeWhiteDragon);
return UniqueFaceupSpell();
}
if (lastCard.IsCode(CardId.LockBird))
{
AI.SelectCard(CardId.LockBird);
if (Util.ChainContainsCard(CardId.TheMelodyOfAwakeningDragon))
AI.SelectNextCard(CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesAlternativeWhiteDragon);
return UniqueFaceupSpell();
}
if (lastCard.IsCode(CardId.Ghost))
{
AI.SelectCard(CardId.Ghost);
if (Util.ChainContainsCard(CardId.TheMelodyOfAwakeningDragon))
AI.SelectNextCard(CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesAlternativeWhiteDragon);
return UniqueFaceupSpell();
}
if (lastCard.IsCode(CardId.AshBlossom))
{
AI.SelectCard(CardId.AshBlossom);
if (Util.ChainContainsCard(CardId.TheMelodyOfAwakeningDragon))
AI.SelectNextCard(CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesAlternativeWhiteDragon);
return UniqueFaceupSpell();
}
}
return false;
}
private bool BlueEyesAlternativeWhiteDragoneff()
{
if(Card.Location==CardLocation.Hand)
{
if (Duel.Turn == 1)
return false;
return true;
}
else
{
if(Util.GetProblematicEnemyMonster(3000,true)!=null)
{
AI.SelectCard(Util.GetProblematicEnemyMonster(3000, true));
return true;
}
}
return false;
}
private bool CreatureSwapeff()
{
if(Bot.HasInMonstersZone(CardId.BlueEyesChaosMaxDragon,true) && Duel.Phase==DuelPhase.Main1 &&
(Bot.HasInMonstersZone(CardId.DeviritualTalismandra) || Bot.HasInMonstersZone(CardId.DevirrtualCandoll)))
{
AI.SelectCard(CardId.DevirrtualCandoll, CardId.DeviritualTalismandra);
return true;
}
return false;
}
private bool TheMelodyOfAwakeningDragoneff()
{
Count_check();
if(TheMelody_count>=2 && Bot.GetRemainingCount(CardId.BlueEyesChaosMaxDragon,3)>0)
{
AI.SelectCard(CardId.TheMelodyOfAwakeningDragon);
AI.SelectNextCard(CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesAlternativeWhiteDragon);
return true;
}
if(Bot.HasInHand(CardId.BlueEyesWhiteDragon) && Bot.GetRemainingCount(CardId.BlueEyesChaosMaxDragon, 3) > 0)
{
AI.SelectCard(CardId.BlueEyesWhiteDragon);
AI.SelectNextCard(CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesAlternativeWhiteDragon);
return true;
}
return false;
}
private bool TheMelodyOfAwakeningDragoneffsecond()
{
Count_check();
if (RitualArtCanUse() && Bot.GetRemainingCount(CardId.BlueEyesChaosMaxDragon, 3) > 0 &&
!Bot.HasInHand(CardId.BlueEyesChaosMaxDragon) && Bot.Hand.Count>=3)
{
if(RitualArt_count>=2)
{
foreach (ClientCard m in Bot.Hand)
{
if (m.IsCode(CardId.AdvancedRitualArt))
AI.SelectCard(m);
}
}
foreach(ClientCard m in Bot.Hand)
{
if (!m.IsCode(CardId.AdvancedRitualArt))
AI.SelectCard(m);
}
AI.SelectNextCard(CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesAlternativeWhiteDragon);
return true;
}
return false;
}
private bool TenTousandHandseff()
{
Count_check();
if(Talismandra_count>=2 && Bot.GetRemainingCount(CardId.BlueEyesChaosMaxDragon,3)>0)
{
AI.SelectCard(CardId.BlueEyesChaosMaxDragon);
return true;
}
if(Candoll_count>=2 || MaxDragon_count >= 2)
{
if(RitualArtCanUse() && Bot.GetRemainingCount(CardId.AdvancedRitualArt,3)>0)
{
AI.SelectCard(CardId.AdvancedRitualArt);
return true;
}
if(ChaosFormCanUse() && Bot.GetRemainingCount(CardId.ChaosForm,1)>0)
{
AI.SelectCard(CardId.ChaosForm);
return true;
}
}
if(RitualArt_count+ChaosForm_count>=2)
{
AI.SelectCard(CardId.BlueEyesChaosMaxDragon);
return true;
}
if(Candoll_count+Talismandra_count>1)
{
if (MaxDragon_count >= 1)
{
if (RitualArtCanUse() && Bot.GetRemainingCount(CardId.AdvancedRitualArt, 3) > 0)
{
AI.SelectCard(CardId.AdvancedRitualArt);
return true;
}
if (ChaosFormCanUse() && Bot.GetRemainingCount(CardId.ChaosForm, 1) > 0)
{
AI.SelectCard(CardId.ChaosForm);
return true;
}
}
if(Bot.HasInHand(CardId.AdvancedRitualArt) || Bot.HasInHand(CardId.ChaosForm))
{
AI.SelectCard(CardId.BlueEyesChaosMaxDragon);
return true;
}
}
if (ChaosForm_count >= 1)
{
if (RitualArtCanUse() && Bot.GetRemainingCount(CardId.AdvancedRitualArt, 3) > 0)
{
AI.SelectCard(CardId.AdvancedRitualArt);
return true;
}
if (ChaosFormCanUse() && Bot.GetRemainingCount(CardId.ChaosForm, 1) > 0)
{
AI.SelectCard(CardId.ChaosForm);
return true;
}
}
if (Talismandra_count>=1)
{
AI.SelectCard(CardId.BlueEyesChaosMaxDragon);
return true;
}
if(MaxDragon_count>=1)
{
if (RitualArtCanUse() && Bot.GetRemainingCount(CardId.AdvancedRitualArt, 3) > 0)
{
AI.SelectCard(CardId.AdvancedRitualArt);
return true;
}
if (ChaosFormCanUse() && Bot.GetRemainingCount(CardId.ChaosForm, 1) > 0)
{
AI.SelectCard(CardId.ChaosForm);
return true;
}
}
if (RitualArtCanUse() && Bot.GetRemainingCount(CardId.AdvancedRitualArt, 3) > 0)
{
AI.SelectCard(CardId.AdvancedRitualArt);
}
if (ChaosFormCanUse() && Bot.GetRemainingCount(CardId.ChaosForm, 1) > 0)
{
AI.SelectCard(CardId.ChaosForm);
}
return true;
}
private bool RitualArtCanUse()
{
return Bot.GetRemainingCount(CardId.BlueEyesWhiteDragon,2)>0;
}
private bool ChaosFormCanUse()
{
ClientCard check = null;
foreach (ClientCard m in Bot.GetGraveyardMonsters())
{
if (m.IsCode(CardId.BlueEyesAlternativeWhiteDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesWhiteDragon))
check = m;
}
foreach (ClientCard m in Bot.Hand)
{
if (m.IsCode(CardId.BlueEyesWhiteDragon))
check = m;
}
if (check != null)
{
return true;
}
return false;
}
private bool DeviritualCheck()
{
Count_check();
if(Card.IsCode(CardId.DeviritualTalismandra, CardId.DevirrtualCandoll))
{
if (Card.Location == CardLocation.MonsterZone)
{
if(RitualArtCanUse())
{
AI.SelectCard(CardId.AdvancedRitualArt);
}
else
{
AI.SelectCard(CardId.ChaosForm);
}
return true;
}
if(Card.Location==CardLocation.Hand)
{
if(Card.IsCode(CardId.DevirrtualCandoll))
{
if (MaxDragon_count >= 2 && Talismandra_count >= 1 || Candoll_used)
return false;
}
if(Card.IsCode(CardId.DeviritualTalismandra))
{
if (RitualArt_count + ChaosForm_count >= 2 && Candoll_count >= 1 || Talismandra_used)
return false;
Talismandra_used = true;
return true;
}
if(RitualArtCanUse())
{
Candoll_used = true;
AI.SelectCard(CardId.AdvancedRitualArt);
return true;
}
if (ChaosFormCanUse())
{
Candoll_used = true;
AI.SelectCard(CardId.ChaosForm);
return true;
}
return true;
}
}
return false;
}
private bool ChaosFormeff()
{
ClientCard check = null;
foreach(ClientCard m in Bot.Graveyard)
{
if (m.IsCode(CardId.BlueEyesAlternativeWhiteDragon, CardId.BlueEyesChaosMaxDragon, CardId.BlueEyesWhiteDragon))
check = m;
}
if(check != null)
{
AI.SelectCard(CardId.BlueEyesChaosMaxDragon);
AI.SelectNextCard(check);
return true;
}
foreach(ClientCard m in Bot.Hand)
{
if (m.IsCode(CardId.BlueEyesWhiteDragon))
check = m;
}
if (check != null)
{
AI.SelectCard(CardId.BlueEyesChaosMaxDragon);
AI.SelectNextCard(check);
return true;
}
return false;
}
private bool MissusRadiantsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Earth) && monster.Level == 1)
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.MissusRadiant)) return false;
AI.SelectMaterials(material_list);
if (Bot.MonsterZone[0] == null && Bot.MonsterZone[2] == null && Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool MissusRadianteff()
{
AI.SelectCard(CardId.MaxxC, CardId.MissusRadiant);
return true;
}
private bool Linkuribohsp()
{
foreach (ClientCard c in Bot.GetMonsters())
{
if (!c.IsCode(CardId.Linkuriboh) && c.Level == 1)
{
AI.SelectMaterials(c);
return true;
}
}
return false;
}
private bool Linkuriboheff()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.Linkuriboh)) return false;
return true;
}
private bool BirrelswordDragonsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard m in Bot.GetMonsters())
{
if (m.IsCode(CardId.MissusRadiant))
{
material_list.Add(m);
break;
}
}
foreach (ClientCard m in Bot.GetMonsters())
{
if (m.IsCode(CardId.Linkuriboh) || m.Level==1)
{
material_list.Add(m);
if (material_list.Count == 3)
break;
}
}
if (material_list.Count == 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
private bool BirrelswordDragoneff()
{
if (ActivateDescription == Util.GetStringId(CardId.BirrelswordDragon, 0))
{
if (Util.IsChainTarget(Card) && Util.GetBestEnemyMonster(true, true) != null)
{
AI.SelectCard(Util.GetBestEnemyMonster(true, true));
return true;
}
if (Duel.Player == 1 && Bot.BattlingMonster == Card)
{
AI.SelectCard(Enemy.BattlingMonster);
return true;
}
if (Duel.Player == 1 && Bot.BattlingMonster != null &&
(Enemy.BattlingMonster.Attack - Bot.BattlingMonster.Attack) >= Bot.LifePoints)
{
AI.SelectCard(Enemy.BattlingMonster);
return true;
}
if (Duel.Player == 0 && Duel.Phase == DuelPhase.BattleStart)
{
foreach (ClientCard check in Enemy.GetMonsters())
{
if (check.IsAttack())
{
AI.SelectCard(check);
return true;
}
}
}
return false;
}
return true;
}
private bool SpellSet()
{
if (Card.IsCode(CardId.InfiniteImpermanence))
return !Bot.IsFieldEmpty();
if (Card.IsCode(CardId.RecklessGreed))
return true;
if (Card.IsCode(CardId.Scapegoat))
return true;
return false;
}
private bool RecklessGreedeff()
{
int count = 0;
foreach (ClientCard card in Bot.GetSpells())
{
if (card.IsCode(CardId.RecklessGreed))
count++;
}
if (DefaultOnBecomeTarget()) return true;
if(Duel.Player==0 && Duel.Phase>=DuelPhase.Main1)
{
if (Bot.LifePoints <= 4000 || count>=2)
return true;
}
return false;
}
private bool Scapegoateff()
{
if (Duel.Player == 0) return false;
if (Duel.Phase == DuelPhase.End) return true;
if (Duel.LastChainPlayer == 1 && DefaultOnBecomeTarget()) return true;
if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2)
{
int total_atk = 0;
List<ClientCard> enemy_monster = Enemy.GetMonsters();
foreach (ClientCard m in enemy_monster)
{
if (m.IsAttack() && !m.Attacked) total_atk += m.Attack;
}
if (total_atk >= Bot.LifePoints) return true;
}
return false;
}
public override ClientCard OnSelectAttacker(IList<ClientCard> attackers, IList<ClientCard> defenders)
{
for (int i = 0; i < attackers.Count; ++i)
{
ClientCard attacker = attackers[i];
if (attacker.IsCode(CardId.BlueEyesChaosMaxDragon))
{
Logger.DebugWriteLine(attacker.Name);
return attacker;
}
}
return base.OnSelectAttacker(attackers, defenders);
}
public override BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList<ClientCard> defenders)
{
if(attacker.IsCode(CardId.BlueEyesChaosMaxDragon) && !attacker.IsDisabled() &&
Enemy.HasInMonstersZone(new[] {CardId.DeviritualTalismandra,CardId.DevirrtualCandoll }))
{
for (int i = 0; i < defenders.Count; i++)
{
ClientCard defender = defenders[i];
attacker.RealPower = attacker.Attack;
defender.RealPower = defender.GetDefensePower();
if (!OnPreBattleBetween(attacker, defender))
continue;
if (defender.IsCode(CardId.DevirrtualCandoll, CardId.DeviritualTalismandra))
{
return AI.Attack(attacker, defender);
}
}
}
return base.OnSelectAttackTarget(attacker, defenders);
}
public override bool OnSelectHand()
{
return false;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,146 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Burn", "AI_Burn", "Easy")]
public class BurnExecutor : DefaultExecutor
{
public class CardId
{
public const int LavaGolem = 102380;
public const int ReflectBounder = 2851070;
public const int FencingFireFerret = 97396380;
public const int BlastSphere = 26302522;
public const int Marshmallon = 31305911;
public const int SpiritReaper = 23205979;
public const int NaturiaBeans = 44789585;
public const int ThunderShort = 20264508;
public const int Ookazi = 19523799;
public const int GoblinThief = 45311864;
public const int TremendousFire = 46918794;
public const int SwordsOfRevealingLight = 72302403;
public const int SupremacyBerry = 98380593;
public const int ChainEnergy = 79323590;
public const int DarkRoomofNightmare = 85562745;
public const int PoisonOfTheOldMan = 8842266;
public const int OjamaTrio = 29843091;
public const int Ceasefire = 36468556;
public const int MagicCylinder = 62279055;
public const int MinorGoblinOfficial = 1918087;
public const int ChainBurst = 48276469;
public const int SkullInvitation = 98139712;
}
public BurnExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// Set traps
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
// Activate Spells
AddExecutor(ExecutorType.Activate, CardId.DarkRoomofNightmare);
AddExecutor(ExecutorType.Activate, CardId.Ookazi);
AddExecutor(ExecutorType.Activate, CardId.GoblinThief);
AddExecutor(ExecutorType.Activate, CardId.TremendousFire);
AddExecutor(ExecutorType.Activate, CardId.SwordsOfRevealingLight, SwordsOfRevealingLight);
AddExecutor(ExecutorType.Activate, CardId.SupremacyBerry, SupremacyBerry);
AddExecutor(ExecutorType.Activate, CardId.PoisonOfTheOldMan, PoisonOfTheOldMan);
AddExecutor(ExecutorType.Activate, CardId.ThunderShort, ThunderShort);
// Hello, my name is Lava Golem
AddExecutor(ExecutorType.SpSummon, CardId.LavaGolem, LavaGolem);
// Set an invincible monster
AddExecutor(ExecutorType.MonsterSet, CardId.Marshmallon, SetInvincibleMonster);
AddExecutor(ExecutorType.MonsterSet, CardId.SpiritReaper, SetInvincibleMonster);
AddExecutor(ExecutorType.MonsterSet, CardId.BlastSphere);
// Set other monsters
AddExecutor(ExecutorType.SummonOrSet, CardId.FencingFireFerret);
AddExecutor(ExecutorType.Summon, CardId.ReflectBounder);
AddExecutor(ExecutorType.MonsterSet, CardId.NaturiaBeans);
// We're a coward
AddExecutor(ExecutorType.Repos, ReposEverything);
// Chain traps
AddExecutor(ExecutorType.Activate, CardId.MagicCylinder, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.Ceasefire, Ceasefire);
AddExecutor(ExecutorType.Activate, CardId.OjamaTrio);
AddExecutor(ExecutorType.Activate, CardId.MinorGoblinOfficial);
AddExecutor(ExecutorType.Activate, CardId.ChainBurst);
AddExecutor(ExecutorType.Activate, CardId.SkullInvitation);
AddExecutor(ExecutorType.Activate, CardId.ChainEnergy);
}
public override bool OnSelectHand()
{
return true;
}
private bool SwordsOfRevealingLight()
{
int count = Bot.SpellZone.GetCardCount(CardId.SwordsOfRevealingLight);
return count == 0;
}
private bool SupremacyBerry()
{
return Bot.LifePoints < Enemy.LifePoints;
}
private bool PoisonOfTheOldMan()
{
AI.SelectOption(1);
return true;
}
private bool ThunderShort()
{
return Enemy.GetMonsterCount() >= 3;
}
private bool SetInvincibleMonster()
{
foreach (ClientCard card in Bot.GetMonsters())
{
if (card.IsCode(CardId.Marshmallon, CardId.SpiritReaper))
{
return false;
}
}
return true;
}
private bool LavaGolem()
{
bool found = false;
foreach (ClientCard card in Enemy.GetMonsters())
{
if (card.Attack > 2000)
found = true;
}
return found;
}
private bool Ceasefire()
{
return Bot.GetMonsterCount() + Enemy.GetMonsterCount() >= 3;
}
private bool ReposEverything()
{
if (Card.IsCode(CardId.ReflectBounder))
return Card.IsDefense();
if (Card.IsCode(CardId.FencingFireFerret))
return DefaultMonsterRepos();
if (Card.IsAttack())
return true;
return false;
}
}
}
@@ -0,0 +1,875 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("ChainBurn", "AI_ChainBurn")]
public class ChainBurnExecutor : DefaultExecutor
{
public class CardId
{
public const int SandaionTheTimelord = 33015627;
public const int MichionTimelord = 7733560;
public const int Mathematician = 41386308;
public const int DiceJar = 3549275;
public const int CardcarD = 45812361;
public const int BattleFader = 19665973;
public const int AbouluteKingBackJack = 60990740;
public const int PotOfDesires = 35261759;
public const int CardOfDemise = 59750328;
public const int PotOfDuality = 98645731;
public const int ChainStrike = 91623717;
public const int Waboku = 12607053;
public const int SecretBlast = 18252559;
public const int JustDesserts = 24068492;
public const int SectetBarrel = 27053506;
public const int OjamaTrio = 29843091;
public const int ThreateningRoar = 36361633;
public const int Ceasefire = 36468556;
public const int RecklessGreed = 37576645;
public const int MagicCylinder = 62279055;
public const int BalanceOfJudgment = 67443336;
public const int BlazingMirrorForce = 75249652;
public const int RingOfDestruction = 83555666;
public const int AccuulatedFortune = 98444741;
public const int Linkuriboh = 41999284;
public const int HarpiesFeatherDuster = 18144506;
}
public ChainBurnExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
//first add
AddExecutor(ExecutorType.Activate, CardId.PotOfDesires);
AddExecutor(ExecutorType.Activate, CardId.PotOfDuality, PotOfDualityeff);
//normal summon
AddExecutor(ExecutorType.Summon, CardId.MichionTimelord, MichionTimelordsummon);
AddExecutor(ExecutorType.Summon, CardId.SandaionTheTimelord, SandaionTheTimelord_summon);
AddExecutor(ExecutorType.Summon, CardId.Mathematician);
AddExecutor(ExecutorType.Activate, CardId.Mathematician, Mathematicianeff);
AddExecutor(ExecutorType.MonsterSet, CardId.DiceJar);
AddExecutor(ExecutorType.Activate, CardId.DiceJar);
AddExecutor(ExecutorType.Summon, CardId.CardcarD);
AddExecutor(ExecutorType.Summon, CardId.AbouluteKingBackJack, AbouluteKingBackJacksummon);
AddExecutor(ExecutorType.MonsterSet, CardId.AbouluteKingBackJack);
AddExecutor(ExecutorType.Activate, CardId.MichionTimelord);
AddExecutor(ExecutorType.Activate, CardId.SandaionTheTimelord, SandaionTheTimelordeff);
// Set traps
AddExecutor(ExecutorType.SpellSet, CardId.Waboku);
AddExecutor(ExecutorType.SpellSet, CardId.ThreateningRoar);
AddExecutor(ExecutorType.SpellSet, CardId.BlazingMirrorForce);
AddExecutor(ExecutorType.SpellSet, CardId.OjamaTrio, OjamaTrioset);
AddExecutor(ExecutorType.SpellSet, BrunSpellSet);
//afer set
AddExecutor(ExecutorType.Activate, CardId.CardcarD);
AddExecutor(ExecutorType.Activate, CardId.CardOfDemise, CardOfDemiseeff);
//activate trap
AddExecutor(ExecutorType.Activate, CardId.BalanceOfJudgment, BalanceOfJudgmenteff);
AddExecutor(ExecutorType.Activate, CardId.AccuulatedFortune);
//battle
AddExecutor(ExecutorType.Activate, CardId.BlazingMirrorForce, BlazingMirrorForceeff);
AddExecutor(ExecutorType.Activate, CardId.MagicCylinder, MagicCylindereff);
AddExecutor(ExecutorType.Activate, CardId.ThreateningRoar, ThreateningRoareff);
AddExecutor(ExecutorType.Activate, CardId.Waboku, Wabokueff);
AddExecutor(ExecutorType.Activate, CardId.BattleFader, BattleFadereff);
AddExecutor(ExecutorType.Activate, CardId.RingOfDestruction, Ring_act);
//chain
AddExecutor(ExecutorType.Activate, CardId.JustDesserts, JustDessertseff);
AddExecutor(ExecutorType.Activate, CardId.Ceasefire, Ceasefireeff);
AddExecutor(ExecutorType.Activate, CardId.SecretBlast, SecretBlasteff);
AddExecutor(ExecutorType.Activate, CardId.SectetBarrel, SectetBarreleff);
AddExecutor(ExecutorType.Activate, CardId.RecklessGreed, RecklessGreedeff);
AddExecutor(ExecutorType.Activate, CardId.OjamaTrio, OjamaTrioeff);
AddExecutor(ExecutorType.Activate, CardId.AbouluteKingBackJack, AbouluteKingBackJackeff);
AddExecutor(ExecutorType.Activate, CardId.ChainStrike, ChainStrikeeff);
//sp
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh);
AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, Linkuriboheff);
AddExecutor(ExecutorType.Repos, MonsterRepos);
}
public int[] all_List()
{
return new[]
{
CardId.SandaionTheTimelord,
CardId.MichionTimelord,
CardId.Mathematician,
CardId.DiceJar,
CardId.CardcarD,
CardId.BattleFader,
CardId.AbouluteKingBackJack,
CardId.PotOfDesires,
CardId.CardOfDemise,
CardId.PotOfDuality,
CardId.ChainStrike,
CardId.Waboku,
CardId.SecretBlast,
CardId.JustDesserts,
CardId.OjamaTrio,
CardId.SectetBarrel,
CardId.ThreateningRoar,
CardId.Ceasefire,
CardId.RecklessGreed,
CardId.MagicCylinder,
CardId.BalanceOfJudgment,
CardId.BlazingMirrorForce,
CardId.RingOfDestruction,
CardId.AccuulatedFortune,
};
}
public int[] AbouluteKingBackJack_List_1()
{
return new[] {
CardId.BlazingMirrorForce,
CardId.Waboku,
CardId.ThreateningRoar,
CardId.MagicCylinder,
CardId.RingOfDestruction,
CardId.RecklessGreed,
CardId.SecretBlast,
CardId.JustDesserts,
CardId.OjamaTrio,
CardId.SectetBarrel,
CardId.Ceasefire,
CardId.BalanceOfJudgment,
CardId.AccuulatedFortune,
};
}
public int[] AbouluteKingBackJack_List_2()
{
return new[] {
CardId.MichionTimelord,
CardId.SandaionTheTimelord,
CardId.PotOfDesires,
CardId.Mathematician,
CardId.DiceJar,
CardId.CardcarD,
CardId.BattleFader,
CardId.BlazingMirrorForce,
CardId.Waboku,
CardId.ThreateningRoar,
CardId.MagicCylinder,
CardId.RingOfDestruction,
CardId.RecklessGreed,
CardId.SecretBlast,
CardId.JustDesserts,
CardId.OjamaTrio,
CardId.SectetBarrel,
CardId.Ceasefire,
CardId.BalanceOfJudgment,
CardId.AccuulatedFortune,
};
}
public int[] now_List()
{
return new[]
{
CardId.Waboku,
CardId.SecretBlast,
CardId.JustDesserts,
CardId.SectetBarrel,
CardId.ThreateningRoar,
CardId.Ceasefire,
CardId.RecklessGreed,
CardId.RingOfDestruction,
};
}
public int[] pot_list()
{
return new[]
{
CardId.PotOfDesires,
CardId.MichionTimelord,
CardId.SandaionTheTimelord,
CardId.BattleFader,
CardId.Waboku,
CardId.ThreateningRoar,
CardId.MagicCylinder,
CardId.BlazingMirrorForce,
CardId.RingOfDestruction,
};
}
public int GetTotalATK(IList<ClientCard> list)
{
int atk = 0;
foreach (ClientCard c in list)
{
if (c == null) continue;
atk += c.Attack;
}
return atk;
}
public bool Has_prevent_list_0(int id)
{
return (
id == CardId.Waboku ||
id == CardId.ThreateningRoar||
id == CardId.MagicCylinder||
id == CardId.BlazingMirrorForce||
id == CardId.RingOfDestruction
);
}
public bool Has_prevent_list_1(int id)
{
return (id == CardId.SandaionTheTimelord ||
id == CardId.BattleFader ||
id == CardId.MichionTimelord
);
}
bool no_sp = false;
bool one_turn_kill = false;
bool one_turn_kill_1 = false;
int expected_blood = 0;
bool prevent_used = false;
int preventcount = 0;
bool OjamaTrioused = false;
bool OjamaTrioused_draw = false;
bool OjamaTrioused_do = false;
bool drawfirst = false;
bool Linkuribohused = true;
bool Timelord_check = false;
int Waboku_count = 0;
int Roar_count = 0;
int strike_count = 0;
int greed_count = 0;
int blast_count = 0;
int barrel_count = 0;
int just_count = 0;
int Ojama_count = 0;
int HasAccuulatedFortune = 0;
public override bool OnSelectHand()
{
return true;
}
public override void OnNewTurn()
{
if (Bot.HasInHand(CardId.SandaionTheTimelord) ||Bot.HasInHand(CardId.MichionTimelord))
Logger.DebugWriteLine("2222222222222222SandaionTheTimelord");
no_sp = false;
prevent_used = false;
Linkuribohused = true;
Timelord_check = false;
base.OnNewTurn();
}
public override void OnNewPhase()
{
preventcount = 0;
OjamaTrioused = false;
IList<ClientCard> trap = Bot.GetSpells();
IList<ClientCard> monster = Bot.GetMonsters();
foreach (ClientCard card in trap)
{
if (Has_prevent_list_0(card.Id))
{
preventcount++;
}
}
foreach (ClientCard card in monster)
{
if (Has_prevent_list_1(card.Id))
{
preventcount++;
}
}
foreach (ClientCard card in monster)
{
if (Bot.HasInMonstersZone(CardId.SandaionTheTimelord) ||
Bot.HasInMonstersZone(CardId.MichionTimelord))
{
prevent_used = true;
Timelord_check = true;
}
}
if(prevent_used && Timelord_check)
{
if (!Bot.HasInMonstersZone(CardId.SandaionTheTimelord) ||
!Bot.HasInMonstersZone(CardId.MichionTimelord))
prevent_used = false;
}
expected_blood = 0;
one_turn_kill = false;
one_turn_kill_1 = false;
OjamaTrioused_draw = false;
OjamaTrioused_do = false;
drawfirst = false;
HasAccuulatedFortune = 0;
strike_count = 0;
greed_count = 0;
blast_count = 0;
barrel_count = 0;
just_count = 0;
Waboku_count = 0;
Roar_count = 0;
Ojama_count = 0;
IList<ClientCard> check = Bot.GetSpells();
foreach (ClientCard card in check)
{
if (card.IsCode(CardId.AccuulatedFortune))
HasAccuulatedFortune++;
}
foreach (ClientCard card in check)
{
if (card.IsCode(CardId.SecretBlast))
blast_count++;
}
foreach (ClientCard card in check)
{
if (card.IsCode(CardId.SectetBarrel))
barrel_count++;
}
foreach (ClientCard card in check)
{
if (card.IsCode(CardId.JustDesserts))
just_count++;
}
foreach (ClientCard card in check)
{
if (card.IsCode(CardId.ChainStrike))
strike_count++;
}
foreach (ClientCard card in Bot.GetSpells())
{
if (card.IsCode(CardId.RecklessGreed))
greed_count++;
}
foreach (ClientCard card in check)
{
if (card.IsCode(CardId.Waboku))
Waboku_count++;
}
foreach (ClientCard card in check)
{
if (card.IsCode(CardId.ThreateningRoar))
Roar_count++;
}
expected_blood = (Enemy.GetMonsterCount() * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count);
if (Enemy.LifePoints <= expected_blood && Duel.Player == 1)
{
Logger.DebugWriteLine(" one_turn_kill");
one_turn_kill = true;
}
expected_blood = 0;
if (greed_count >= 2) greed_count = 1;
if (blast_count >= 2) blast_count = 1;
if (just_count >= 2) just_count = 1;
if (barrel_count >= 2) barrel_count = 1;
if (Waboku_count >= 2) Waboku_count = 1;
if (Roar_count >= 2) Roar_count = 1;
int currentchain = 0;
if (OjamaTrioused_do)
currentchain = Duel.CurrentChain.Count + blast_count + just_count + barrel_count + Waboku_count + Waboku_count + Roar_count + greed_count + Ojama_count;
else
currentchain = Duel.CurrentChain.Count + blast_count + just_count + barrel_count + Waboku_count + Waboku_count + greed_count + Roar_count;
//if (currentchain >= 3 && Duel.Player == 1) drawfirst = true;
if (Bot.HasInSpellZone(CardId.ChainStrike))
{
if (strike_count == 1)
{
if (OjamaTrioused_do)
expected_blood = ((Enemy.GetMonsterCount() + 3) * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count + (currentchain + 1) * 400);
else
expected_blood = (Enemy.GetMonsterCount() * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count + (currentchain + 1) * 400);
}
else
{
if (OjamaTrioused_do)
expected_blood = ((Enemy.GetMonsterCount() + 3) * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count + (currentchain + 1 + currentchain + 2) * 400);
else
expected_blood = (Enemy.GetMonsterCount() * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count + (currentchain + 1 + currentchain + 2) * 400);
}
if (!one_turn_kill && Enemy.LifePoints <= expected_blood && Duel.Player == 1)
{
Logger.DebugWriteLine(" %%%%%%%%%%%%%%%%%one_turn_kill_1");
one_turn_kill_1 = true;
OjamaTrioused = true;
}
}
}
private bool must_chain()
{
if (Util.IsChainTarget(Card)) return true;
foreach (ClientCard card in Enemy.GetSpells())
{
if (card.IsCode(CardId.HarpiesFeatherDuster)&&card.IsFaceup())
{
return true;
}
}
return false;
}
private bool OjamaTrioset()
{
if (Bot.HasInSpellZone(CardId.OjamaTrio)) return false;
return true;
}
private bool BrunSpellSet()
{
if (Card.IsCode(CardId.OjamaTrio) && Bot.HasInSpellZone(CardId.OjamaTrio))return false;
return (Card.IsTrap() || Card.HasType(CardType.QuickPlay)) && Bot.GetSpellCountWithoutField() < 5;
}
private bool MichionTimelordsummon()
{
if (Duel.Turn == 1)
return false;
return true;
}
private bool SandaionTheTimelord_summon()
{
Logger.DebugWriteLine("&&&&&&&&&SandaionTheTimelord_summon");
return true;
}
private bool AbouluteKingBackJacksummon()
{
return !no_sp;
}
private bool AbouluteKingBackJackeff()
{
if (ActivateDescription == -1)
{
AI.SelectCard(AbouluteKingBackJack_List_1());
AI.SelectNextCard(AbouluteKingBackJack_List_2());
}
return true;
}
private bool PotOfDualityeff()
{
no_sp = true;
AI.SelectCard(pot_list());
return true;
}
private bool ThreateningRoareff()
{
if (one_turn_kill_1) return UniqueFaceupSpell();
if (drawfirst) return true;
if (DefaultOnBecomeTarget())
{
prevent_used = true;
return true;
}
if (prevent_used || Duel.Phase != DuelPhase.BattleStart) return false;
prevent_used = true;
return DefaultUniqueTrap();
}
private bool SandaionTheTimelordeff()
{
Logger.DebugWriteLine("***********SandaionTheTimelordeff");
return true;
}
private bool Wabokueff()
{
if (one_turn_kill_1) return UniqueFaceupSpell();
if (drawfirst)
{
Linkuribohused = false;
return true;
}
if (DefaultOnBecomeTarget())
{
Linkuribohused = false;
prevent_used = true;
return true;
}
if (prevent_used||Duel.Player == 0||Duel.Phase!=DuelPhase.BattleStart) return false;
prevent_used = true;
Linkuribohused = false;
return DefaultUniqueTrap();
}
private bool BattleFadereff()
{
if (Util.ChainContainsCard(CardId.BlazingMirrorForce) || Util.ChainContainsCard(CardId.MagicCylinder))
return false;
if (prevent_used || Duel.Player == 0) return false;
AI.SelectPosition(CardPosition.FaceUpDefence);
prevent_used = true;
return true;
}
private bool BlazingMirrorForceeff()
{
if (prevent_used) return false;
IList<ClientCard> list = new List<ClientCard>();
foreach (ClientCard monster in Enemy.GetMonsters())
{
if (monster.IsAttack())
list.Add(monster);
}
if (GetTotalATK(list) / 2 >= Bot.LifePoints) return false;
Logger.DebugWriteLine("!!!!!!!!BlazingMirrorForceeff" + GetTotalATK(list) / 2);
if (GetTotalATK(list) / 2 >= Enemy.LifePoints) return DefaultUniqueTrap();
if (GetTotalATK(list) < 3000) return false;
prevent_used = true;
return DefaultUniqueTrap();
}
private bool MagicCylindereff()
{
if (prevent_used) return false;
if (Bot.LifePoints <= Enemy.BattlingMonster.Attack) return DefaultUniqueTrap();
if (Enemy.LifePoints <= Enemy.BattlingMonster.Attack) return DefaultUniqueTrap();
if (Enemy.BattlingMonster.Attack>1800) return DefaultUniqueTrap();
return false;
}
public bool Ring_act()
{
if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard() != null ) return false;
ClientCard target = Util.GetProblematicEnemyMonster();
if (target == null && Util.IsChainTarget(Card))
{
target = Util.GetBestEnemyMonster(true, true);
}
if (target != null)
{
if (Bot.LifePoints <= target.Attack) return false;
AI.SelectCard(target);
return true;
}
return false;
}
private bool RecklessGreedeff()
{
if (one_turn_kill_1) return UniqueFaceupSpell();
int count=0;
foreach (ClientCard card in Bot.GetSpells())
{
if (card.IsCode(CardId.RecklessGreed))
count++;
}
bool Demiseused = Util.ChainContainsCard(CardId.CardOfDemise);
if (drawfirst) return UniqueFaceupSpell();
if (DefaultOnBecomeTarget() && count > 1) return true;
if (Demiseused) return false;
if (count > 1) return true;
if (Bot.LifePoints <= 3000) return true;
if (Bot.GetHandCount() <1 && Duel.Player==0 && Duel.Phase!=DuelPhase.Standby) return true;
return false;
}
private bool SectetBarreleff()
{
if (DefaultOnBecomeTarget()) return true;
if (Duel.Player == 0) return false;
if (drawfirst) return true;
if (one_turn_kill_1) return UniqueFaceupSpell();
if (one_turn_kill) return true;
if (DefaultOnBecomeTarget()) return true;
int count = Enemy.GetFieldHandCount();
int monster_count = Enemy.GetMonsterCount() - Enemy.GetMonstersExtraZoneCount();
if (Enemy.LifePoints < count * 200) return true;
if (Bot.HasInSpellZone(CardId.OjamaTrio) && monster_count <= 2 && monster_count >= 1)
{
if (count + 3 >= 8)
{
OjamaTrioused = true;
return true;
}
}
if (count >= 8) return true;
return false;
}
private bool SecretBlasteff()
{
if (DefaultOnBecomeTarget()) return true;
if (Duel.Player == 0) return false;
if (drawfirst) return UniqueFaceupSpell();
if (one_turn_kill_1) return UniqueFaceupSpell();
if (one_turn_kill) return true;
int count = Enemy.GetFieldCount();
int monster_count = Enemy.GetMonsterCount() - Enemy.GetMonstersExtraZoneCount();
if (Enemy.LifePoints < count * 300) return true;
if(Bot.HasInSpellZone(CardId.OjamaTrio) && monster_count <= 2 && monster_count >= 1 )
{
if(count+3>=5)
{
OjamaTrioused = true;
return true;
}
}
if (count >= 5) return true;
return false;
}
private bool OjamaTrioeff()
{
return OjamaTrioused||OjamaTrioused_draw;
}
private bool JustDessertseff()
{
if (DefaultOnBecomeTarget()) return true;
if (Duel.Player == 0) return false;
if (drawfirst) return UniqueFaceupSpell();
if (one_turn_kill_1) return UniqueFaceupSpell();
if (one_turn_kill) return true;
int count = Enemy.GetMonsterCount()-Enemy.GetMonstersExtraZoneCount();
if (Enemy.LifePoints <= count * 500) return true;
if (Bot.HasInSpellZone(CardId.OjamaTrio) && count <= 2 && count >= 1)
{
OjamaTrioused = true;
return true;
}
if (count >= 3) return true;
return false;
}
private bool ChainStrikeeff()
{
if (one_turn_kill) return true;
if (one_turn_kill_1) return true;
if (drawfirst) return true;
if (DefaultOnBecomeTarget()) return true;
int chain = Duel.CurrentChain.Count;
if (strike_count >= 2 && chain >= 2) return true;
if (Enemy.LifePoints <= (chain + 1) * 400) return true;
if (Duel.CurrentChain.Count >= 3) return true;
return false;
}
private bool BalanceOfJudgmenteff()
{
if (DefaultOnBecomeTarget()) return true;
int count = (Enemy.GetFieldCount() - Bot.GetFieldHandCount());
if ( count>= 2)return true;
return false;
}
private bool CardOfDemiseeff()
{
foreach (ClientCard card in Bot.GetMonsters())
{
if (card.IsCode(CardId.CardcarD) && card.IsFaceup())
return false;
}
if (Bot.GetHandCount() == 1 && Bot.GetSpellCountWithoutField() <= 3)
{
no_sp = true;
return true;
}
return false;
}
private bool Mathematicianeff()
{
if (Card.Location == CardLocation.MonsterZone)
{
AI.SelectCard(CardId.AbouluteKingBackJack);
return true;
}
return true;
}
private bool DiceJarfacedown()
{
foreach (ClientCard card in Bot.GetMonsters())
{
if (card.IsCode(CardId.DiceJar) && card.IsFacedown())
return true;
break;
}
return false;
}
private bool Ceasefireeff()
{
if (Enemy.GetMonsterCount() >= 3) return true;
if (DiceJarfacedown()) return false;
if ((Bot.GetMonsterCount() + Enemy.GetMonsterCount()) >= 4) return true;
return false;
}
private bool Linkuriboheff()
{
IList<ClientCard> newlist = new List<ClientCard>();
foreach (ClientCard newmonster in Enemy.GetMonsters())
{
if (newmonster.IsAttack())
newlist.Add(newmonster);
}
if (!Linkuribohused) return false;
if(Enemy.BattlingMonster!=null)
{
if (Enemy.BattlingMonster.Attack > 1800 && Bot.HasInSpellZone(CardId.MagicCylinder)) return false;
}
if (GetTotalATK(newlist) / 2 >= Bot.LifePoints && Bot.HasInSpellZone(CardId.BlazingMirrorForce))
return true;
if (GetTotalATK(newlist) / 2 >= Enemy.LifePoints && Bot.HasInSpellZone(CardId.BlazingMirrorForce))
return false;
if (Util.GetLastChainCard() == null) return true;
if (Util.GetLastChainCard().IsCode(CardId.Linkuriboh)) return false;
return true;
}
public bool MonsterRepos()
{
if (Card.IsFacedown() && !Card.IsCode(CardId.DiceJar))
return true;
return base.DefaultMonsterRepos();
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (attacker.IsCode(CardId.Linkuriboh) && defender.IsFacedown()) return false;
if (attacker.IsCode(CardId.SandaionTheTimelord) && !attacker.IsDisabled())
{
attacker.RealPower = 9999;
return true;
}
if(attacker.IsCode(CardId.MichionTimelord) && !attacker.IsDisabled())
{
attacker.RealPower = 9999;
return true;
}
return base.OnPreBattleBetween(attacker,defender);
}
public override void OnChaining(int player, ClientCard card)
{
expected_blood = 0;
one_turn_kill = false;
one_turn_kill_1 = false;
OjamaTrioused_draw = false;
OjamaTrioused_do = false;
drawfirst = false;
HasAccuulatedFortune = 0;
strike_count = 0;
greed_count = 0;
blast_count = 0;
barrel_count = 0;
just_count = 0;
Waboku_count = 0;
Roar_count = 0;
Ojama_count = 0;
IList<ClientCard> check = Bot.GetSpells();
foreach (ClientCard card1 in check)
{
if (card1.IsCode(CardId.AccuulatedFortune))
HasAccuulatedFortune++;
}
foreach (ClientCard card1 in check)
{
if (card1.IsCode(CardId.SecretBlast))
blast_count++;
}
foreach (ClientCard card1 in check)
{
if (card1.IsCode(CardId.SectetBarrel))
barrel_count++;
}
foreach (ClientCard card1 in check)
{
if (card1.IsCode(CardId.JustDesserts))
just_count++;
}
foreach (ClientCard card1 in check)
{
if (card1.IsCode(CardId.ChainStrike))
strike_count++;
}
foreach (ClientCard card1 in Bot.GetSpells())
{
if (card1.IsCode(CardId.RecklessGreed))
greed_count++;
}
foreach (ClientCard card1 in check)
{
if (card1.IsCode(CardId.Waboku))
Waboku_count++;
}
foreach (ClientCard card1 in check)
{
if (card1.IsCode(CardId.ThreateningRoar))
Roar_count++;
}
/*if (Bot.HasInSpellZone(CardId.OjamaTrio) && Enemy.GetMonsterCount() <= 2 && Enemy.GetMonsterCount() >= 1)
{
if (HasAccuulatedFortune > 0) OjamaTrioused_draw = true;
}*/
if (Bot.HasInSpellZone(CardId.OjamaTrio) && (Enemy.GetMonsterCount() - Enemy.GetMonstersExtraZoneCount()) <= 2 &&
(Enemy.GetMonsterCount() - Enemy.GetMonstersExtraZoneCount()) >= 1)
{
OjamaTrioused_do = true;
}
expected_blood = (Enemy.GetMonsterCount() * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count);
if (Enemy.LifePoints <= expected_blood && Duel.Player == 1)
{
Logger.DebugWriteLine(" %%%%%%%%%%%%%%%%%one_turn_kill");
one_turn_kill = true;
}
expected_blood = 0;
if (greed_count >= 2) greed_count = 1;
if (blast_count >= 2) blast_count = 1;
if (just_count >= 2) just_count = 1;
if (barrel_count >= 2) barrel_count = 1;
if (Waboku_count >= 2) Waboku_count = 1;
if (Roar_count >= 2) Roar_count = 1;
int currentchain = 0;
if (OjamaTrioused_do)
currentchain = Duel.CurrentChain.Count + blast_count + just_count + barrel_count + Waboku_count + Waboku_count + Roar_count + greed_count + Ojama_count;
else
currentchain = Duel.CurrentChain.Count + blast_count + just_count + barrel_count + Waboku_count + Waboku_count + greed_count + Roar_count ;
//if (currentchain >= 3 && Duel.Player == 1) drawfirst = true;
if(Bot.HasInSpellZone(CardId.ChainStrike))
{
if (strike_count == 1)
{
if (OjamaTrioused_do)
expected_blood = ((Enemy.GetMonsterCount() + 3) * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count + (currentchain + 1) * 400);
else
expected_blood = (Enemy.GetMonsterCount() * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count + (currentchain + 1) * 400);
}
else
{
if (OjamaTrioused_do)
expected_blood = ((Enemy.GetMonsterCount() + 3) * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count + (currentchain + 1 + currentchain + 2) * 400);
else
expected_blood = (Enemy.GetMonsterCount() * 500 * just_count + Enemy.GetFieldHandCount() * 200 * barrel_count + Enemy.GetFieldCount() * 300 * blast_count + (currentchain + 1 + currentchain + 2) * 400);
}
if (!one_turn_kill && Enemy.LifePoints <= expected_blood && Duel.Player == 1)
{
Logger.DebugWriteLine(" %%%%%%%%%%%%%%%%%one_turn_kill_1");
one_turn_kill_1 = true;
OjamaTrioused = true;
}
}
base.OnChaining(player, card);
}
}
}
@@ -0,0 +1,188 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
// NOT FINISHED YET
[Deck("CyberDragon", "AI_CyberDragon", "NotFinished")]
public class CyberDragonExecutor : DefaultExecutor
{
bool PowerBondUsed = false;
public class CardId
{
public const int CyberLaserDragon = 4162088;
public const int CyberBarrierDragon = 68774379;
public const int CyberDragon = 70095154;
public const int CyberDragonDrei = 59281922;
public const int CyberPhoenix = 3370104;
public const int ArmoredCybern = 67159705;
public const int ProtoCyberDragon = 26439287;
public const int CyberKirin = 76986005;
public const int CyberDragonCore = 23893227;
public const int CyberValley = 3657444;
public const int Raigeki = 12580477;
public const int DarkHole = 53129443;
public const int DifferentDimensionCapsule = 11961740;
public const int Polymerization = 24094653;
public const int PowerBond = 37630732;
public const int EvolutionBurst = 52875873;
public const int PhotonGeneratorUnit = 66607691;
public const int DeFusion = 95286165;
public const int BottomlessTrapHole = 29401950;
public const int MirrorForce = 44095762;
public const int AttackReflectorUnit = 91989718;
public const int CyberneticHiddenTechnology = 92773018;
public const int CallOfTheHaunted = 97077563;
public const int SevenToolsOfTheBandit = 3819470;
public const int CyberTwinDragon = 74157028;
public const int CyberEndDragon = 1546123;
public const int CyberDragonNova = 58069384;
}
public CyberDragonExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpellSet, CardId.DeFusion);
AddExecutor(ExecutorType.Activate, CardId.DifferentDimensionCapsule, Capsule);
AddExecutor(ExecutorType.Activate, CardId.Raigeki, DefaultRaigeki);
AddExecutor(ExecutorType.Activate, CardId.Polymerization, PolymerizationEffect);
AddExecutor(ExecutorType.Activate, CardId.PowerBond, PowerBondEffect);
AddExecutor(ExecutorType.Activate, CardId.EvolutionBurst, EvolutionBurstEffect);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.PhotonGeneratorUnit);
AddExecutor(ExecutorType.Activate, CardId.DeFusion, DeFusionEffect);
AddExecutor(ExecutorType.Activate, CardId.BottomlessTrapHole, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.AttackReflectorUnit);
AddExecutor(ExecutorType.Activate, CardId.SevenToolsOfTheBandit, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.CallOfTheHaunted, DefaultCallOfTheHaunted);
AddExecutor(ExecutorType.SummonOrSet, CardId.CyberDragonDrei, NoCyberDragonSpsummon);
AddExecutor(ExecutorType.SummonOrSet, CardId.CyberPhoenix, NoCyberDragonSpsummon);
AddExecutor(ExecutorType.Summon, CardId.CyberValley, NoCyberDragonSpsummon);
AddExecutor(ExecutorType.MonsterSet, CardId.CyberDragonCore, NoCyberDragonSpsummon);
AddExecutor(ExecutorType.MonsterSet, CardId.ArmoredCybern, ArmoredCybernSet);
AddExecutor(ExecutorType.SummonOrSet, CardId.ProtoCyberDragon, ProtoCyberDragonSummon);
AddExecutor(ExecutorType.Summon, CardId.CyberKirin, CyberKirinSummon);
AddExecutor(ExecutorType.SpSummon, CardId.CyberDragon);
AddExecutor(ExecutorType.SpSummon, CardId.CyberEndDragon);
AddExecutor(ExecutorType.SpSummon, CardId.CyberTwinDragon);
AddExecutor(ExecutorType.SpSummon, CardId.CyberBarrierDragon);
AddExecutor(ExecutorType.SpSummon, CardId.CyberLaserDragon);
AddExecutor(ExecutorType.Activate, CardId.CyberBarrierDragon);
AddExecutor(ExecutorType.Activate, CardId.CyberLaserDragon);
AddExecutor(ExecutorType.Activate, CardId.CyberDragonDrei);
AddExecutor(ExecutorType.Activate, CardId.CyberPhoenix);
AddExecutor(ExecutorType.Activate, CardId.CyberKirin);
AddExecutor(ExecutorType.Activate, CardId.ArmoredCybern, ArmoredCybernEffect);
AddExecutor(ExecutorType.Activate, CardId.CyberValley);
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
private bool CyberDragonInHand() { return Bot.HasInHand(CardId.CyberDragon); }
private bool CyberDragonInGraveyard() { return Bot.HasInGraveyard(CardId.CyberDragon); }
private bool CyberDragonInMonsterZone() { return Bot.HasInMonstersZone(CardId.CyberDragon); }
private bool CyberDragonIsBanished() { return Bot.HasInBanished(CardId.CyberDragon); }
private bool Capsule()
{
IList<int> SelectedCard = new List<int>();
SelectedCard.Add(CardId.PowerBond);
SelectedCard.Add(CardId.DarkHole);
SelectedCard.Add(CardId.Raigeki);
AI.SelectCard(SelectedCard);
return true;
}
private bool PolymerizationEffect()
{
if (Bot.GetCountCardInZone(Bot.MonsterZone, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.MonsterZone, CardId.ProtoCyberDragon) + Bot.GetCountCardInZone(Bot.MonsterZone, CardId.CyberDragonDrei) + Bot.GetCountCardInZone(Bot.MonsterZone, CardId.CyberDragonDrei) + Bot.GetCountCardInZone(Bot.Hand, CardId.CyberDragon) >= 3)
AI.SelectCard(CardId.CyberEndDragon);
else
AI.SelectCard(CardId.CyberTwinDragon);
return true;
}
private bool PowerBondEffect()
{
PowerBondUsed = true;
if (Bot.GetCountCardInZone(Bot.MonsterZone, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.MonsterZone, CardId.ProtoCyberDragon) + Bot.GetCountCardInZone(Bot.Hand, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.Graveyard, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.Hand, CardId.CyberDragonCore) + Bot.GetCountCardInZone(Bot.Graveyard, CardId.CyberDragonCore) + Bot.GetCountCardInZone(Bot.Graveyard, CardId.CyberDragonDrei) + Bot.GetCountCardInZone(Bot.MonsterZone, CardId.CyberDragonDrei) >= 3)
AI.SelectCard(CardId.CyberEndDragon);
else
AI.SelectCard(CardId.CyberTwinDragon);
return true;
}
private bool EvolutionBurstEffect()
{
ClientCard bestMy = Bot.GetMonsters().GetHighestAttackMonster();
if (bestMy == null || !Util.IsOneEnemyBetterThanValue(bestMy.Attack, false))
return false;
else
AI.SelectCard(Enemy.MonsterZone.GetHighestAttackMonster());
return true;
}
private bool NoCyberDragonSpsummon()
{
if (CyberDragonInHand() && (Bot.GetMonsterCount() == 0 && Enemy.GetMonsterCount() != 0))
return false;
return true;
}
private bool ArmoredCybernSet()
{
if (CyberDragonInHand() && (Bot.GetMonsterCount() == 0 && Enemy.GetMonsterCount() != 0) || (Bot.HasInHand(CardId.CyberDragonDrei) || Bot.HasInHand(CardId.CyberPhoenix)) && !Util.IsOneEnemyBetterThanValue(1800,true))
return false;
return true;
}
private bool ProtoCyberDragonSummon()
{
if (Bot.GetCountCardInZone(Bot.Hand, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.MonsterZone, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.MonsterZone, CardId.CyberDragonCore) >= 1 && Bot.HasInHand(CardId.Polymerization) || Bot.GetCountCardInZone(Bot.Hand, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.MonsterZone, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.Graveyard, CardId.CyberDragon) + Bot.GetCountCardInZone(Bot.Graveyard, CardId.CyberDragonCore) >= 1 && Bot.HasInHand(CardId.PowerBond))
return true;
if (CyberDragonInHand() && (Bot.GetMonsterCount() == 0 && Enemy.GetMonsterCount() != 0) || (Bot.HasInHand(CardId.CyberDragonDrei) || Bot.HasInHand(CardId.CyberPhoenix)) && !Util.IsOneEnemyBetterThanValue(1800, true))
return false;
return true;
}
private bool CyberKirinSummon()
{
return PowerBondUsed;
}
private bool ArmoredCybernEffect()
{
if (Card.Location == CardLocation.Hand)
return true;
else if (Card.Location == CardLocation.SpellZone)
{
if (Util.IsOneEnemyBetterThanValue(Bot.GetMonsters().GetHighestAttackMonster().Attack, true))
if (ActivateDescription == Util.GetStringId(CardId.ArmoredCybern, 2))
return true;
return false;
}
return false;
}
private bool DeFusionEffect()
{
if (Duel.Phase == DuelPhase.Battle)
{
if (!Bot.HasAttackingMonster())
return true;
}
return false;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,48 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Test", "AI_Test", "Test")]
public class DoEverythingExecutor : DefaultExecutor
{
public class CardId
{
public const int LeoWizard = 4392470;
public const int Bunilla = 69380702;
}
public DoEverythingExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpSummon);
AddExecutor(ExecutorType.Activate, DefaultDontChainMyself);
AddExecutor(ExecutorType.SummonOrSet, DefaultMonsterSummon);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.SpellSet);
}
public override IList<ClientCard> OnSelectCard(IList<ClientCard> cards, int min, int max, int hint, bool cancelable)
{
if (Duel.Phase == DuelPhase.BattleStart)
return null;
IList<ClientCard> selected = new List<ClientCard>();
// select the last cards
for (int i = 1; i <= max; ++i)
selected.Add(cards[cards.Count-i]);
return selected;
}
public override int OnSelectOption(IList<int> options)
{
return Program.Rand.Next(options.Count);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,515 @@
using System;
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using System.Linq;
namespace WindBot.Game.AI.Decks
{
[Deck("Dragun", "AI_Dragun")]
class DragunExecutor : DefaultExecutor
{
public class CardId
{
public const int DarkMagician = 46986414;
public const int RedEyesBDragon = 74677422;
public const int RedEyesWyvern = 67300516;
public const int TourGuideFromTheUnderworld = 10802915;
public const int Sangan = 26202165;
public const int CrusadiaArboria = 91646304;
public const int AshBlossomJoyousSpring = 14558127;
public const int MechaPhantomBeastOLion = 72291078;
public const int MechaPhantomBeastOLionToken = 72291079;
public const int MaxxC = 23434538;
public const int MagiciansSouls = 97631303;
public const int InstantFusion = 1845204;
public const int RedEyesFusion = 6172122;
public const int MagicalizedFusion = 11827244;
public const int HarpiesFeatherDuster = 18144506;
public const int FoolishBurial = 81439173;
public const int MonsterReborn = 83764718;
public const int RedEyesInsight = 92353449;
public const int CalledbyTheGrave = 24224830;
public const int InfiniteImpermanence = 10045474;
public const int SolemnStrike = 40605147;
public const int DragunofRedEyes = 37818794;
public const int SeaMonsterofTheseus = 96334243;
public const int ThousandEyesRestrict = 63519819;
public const int CrystronHalqifibrax = 50588353;
public const int PredaplantVerteAnaconda = 70369116;
public const int LinkSpider = 98978921;
public const int ImdukTheWorldChaliceDragon = 31226177;
public const int SalamangreatAlmiraj = 60303245;
}
public DragunExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// counter
AddExecutor(ExecutorType.Activate, CardId.AshBlossomJoyousSpring, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, CardId.CalledbyTheGrave, DefaultCalledByTheGrave);
AddExecutor(ExecutorType.Activate, CardId.InfiniteImpermanence, DefaultInfiniteImpermanence);
AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, CardId.DragunofRedEyes, DragunofRedEyesCounter);
AddExecutor(ExecutorType.Activate, CardId.MaxxC, DefaultMaxxC);
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster);
AddExecutor(ExecutorType.Activate, CardId.DragunofRedEyes, DragunofRedEyesDestroy);
AddExecutor(ExecutorType.Activate, CardId.ThousandEyesRestrict, ThousandEyesRestrictEffect);
AddExecutor(ExecutorType.Activate, CardId.RedEyesInsight, RedEyesInsightEffect);
AddExecutor(ExecutorType.Activate, CardId.RedEyesFusion, RedEyesFusionEffect);
AddExecutor(ExecutorType.Repos, MonsterRepos);
AddExecutor(ExecutorType.Summon, CardId.TourGuideFromTheUnderworld, TourGuideFromTheUnderworldSummon);
AddExecutor(ExecutorType.Activate, CardId.TourGuideFromTheUnderworld, TourGuideFromTheUnderworldEffect);
AddExecutor(ExecutorType.Summon, CardId.Sangan, SanganSummon);
AddExecutor(ExecutorType.Activate, CardId.Sangan, SanganEffect);
AddExecutor(ExecutorType.Summon, CardId.MechaPhantomBeastOLion);
AddExecutor(ExecutorType.Activate, CardId.MechaPhantomBeastOLion, MechaPhantomBeastOLionEffect);
AddExecutor(ExecutorType.SpSummon, CardId.SalamangreatAlmiraj, SalamangreatAlmirajSummon);
AddExecutor(ExecutorType.SpSummon, CardId.ImdukTheWorldChaliceDragon, ImdukTheWorldChaliceDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider, LinkSpiderSummon);
AddExecutor(ExecutorType.SpSummon, CardId.CrusadiaArboria);
AddExecutor(ExecutorType.Activate, CardId.InstantFusion, InstantFusionEffect);
AddExecutor(ExecutorType.Summon, CardId.RedEyesWyvern);
AddExecutor(ExecutorType.Summon, CardId.CrusadiaArboria, SummonForMaterial);
AddExecutor(ExecutorType.Summon, CardId.AshBlossomJoyousSpring, SummonForMaterial);
AddExecutor(ExecutorType.Summon, CardId.MaxxC, SummonForMaterial);
AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialEffect);
AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, MonsterRebornEffect);
AddExecutor(ExecutorType.Activate, CardId.MagiciansSouls, MagiciansSoulsEffect);
AddExecutor(ExecutorType.Summon, CardId.MagiciansSouls, SummonForMaterial);
AddExecutor(ExecutorType.SpSummon, CardId.CrystronHalqifibrax, CrystronNeedlefiberSummon);
AddExecutor(ExecutorType.Activate, CardId.CrystronHalqifibrax, CrystronNeedlefiberEffect);
AddExecutor(ExecutorType.SpSummon, CardId.PredaplantVerteAnaconda, PredaplantVerteAnacondaSummon);
AddExecutor(ExecutorType.Activate, CardId.MagicalizedFusion, MagicalizedFusionEffect);
AddExecutor(ExecutorType.Activate, CardId.PredaplantVerteAnaconda, PredaplantVerteAnacondaEffect);
AddExecutor(ExecutorType.SpellSet, CardId.InfiniteImpermanence, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, TrapSet);
AddExecutor(ExecutorType.MonsterSet, CardId.Sangan);
}
private bool BeastOLionUsed = false;
private bool RedEyesFusionUsed = false;
public override bool OnSelectHand()
{
// go first
return true;
}
public override void OnNewTurn()
{
BeastOLionUsed = false;
RedEyesFusionUsed = false;
base.OnNewTurn();
}
public override CardPosition OnSelectPosition(int cardId, IList<CardPosition> positions)
{
YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId);
if (cardData != null)
{
if (cardData.Attack <= 1000)
return CardPosition.FaceUpDefence;
}
return 0;
}
public override int OnSelectPlace(int cardId, int player, CardLocation location, int available)
{
if (location == CardLocation.MonsterZone)
{
return available & ~Bot.GetLinkedZones();
}
return 0;
}
private bool DragunofRedEyesCounter()
{
if (ActivateDescription != -1 && ActivateDescription != Util.GetStringId(CardId.DragunofRedEyes, 1))
return false;
if (Duel.LastChainPlayer != 1)
return false;
AI.SelectCard(new[] {
CardId.RedEyesWyvern,
CardId.MechaPhantomBeastOLion
});
return true;
}
private bool DragunofRedEyesDestroy()
{
if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.DragunofRedEyes, 1))
return false;
AI.SelectCard(Util.GetBestEnemyMonster());
return true;
}
private bool ThousandEyesRestrictEffect()
{
AI.SelectCard(Util.GetBestEnemyMonster());
return true;
}
private bool RedEyesInsightEffect()
{
if (Bot.HasInHand(CardId.RedEyesFusion))
return false;
if (Bot.GetRemainingCount(CardId.RedEyesWyvern, 1) == 0 && Bot.GetRemainingCount(CardId.RedEyesBDragon, 2) == 1 && !Bot.HasInHand(CardId.RedEyesBDragon))
return false;
AI.SelectCard(CardId.RedEyesWyvern);
return true;
}
private bool RedEyesFusionEffect()
{
if (Bot.HasInMonstersZone(new[] { CardId.DragunofRedEyes, CardId.RedEyesBDragon }))
{ // you don't want to use DragunofRedEyes which is treated as RedEyesBDragon as fusion material
if (Util.GetBotAvailZonesFromExtraDeck() == 0)
return false;
if (Bot.GetRemainingCount(CardId.RedEyesBDragon, 2) == 0 && !Bot.HasInHand(CardId.RedEyesBDragon))
return false;
}
AI.SelectMaterials(CardLocation.Deck);
RedEyesFusionUsed = true;
return true;
}
private bool TourGuideFromTheUnderworldSummon()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (Bot.GetRemainingCount(CardId.TourGuideFromTheUnderworld, 2) == 0 && Bot.GetRemainingCount(CardId.Sangan, 2) == 0)
return false;
return true;
}
private bool TourGuideFromTheUnderworldEffect()
{
AI.SelectCard(CardId.Sangan);
return true;
}
private bool SanganSummon()
{
return true;
}
private bool SanganEffect()
{
if (Bot.HasInMonstersZone(CardId.SalamangreatAlmiraj) && !Bot.HasInHand(CardId.CrusadiaArboria))
AI.SelectCard(CardId.CrusadiaArboria);
else if (!Bot.HasInHand(CardId.MaxxC))
AI.SelectCard(CardId.MaxxC);
else if (!Bot.HasInHand(CardId.AshBlossomJoyousSpring))
AI.SelectCard(CardId.AshBlossomJoyousSpring);
else if (!Bot.HasInHand(CardId.MagiciansSouls))
AI.SelectCard(CardId.MagiciansSouls);
else if (!Bot.HasInHand(CardId.CrusadiaArboria))
AI.SelectCard(CardId.CrusadiaArboria);
else
AI.SelectCard(new[] {
CardId.AshBlossomJoyousSpring,
CardId.MaxxC,
CardId.CrusadiaArboria
});
return true;
}
private bool SalamangreatAlmirajSummon()
{
int[] materials = new[] {
CardId.Sangan,
CardId.MechaPhantomBeastOLion
};
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials) && !card.IsSpecialSummoned) == 0)
return false;
AI.SelectMaterials(materials);
return true;
}
private bool ImdukTheWorldChaliceDragonSummon()
{
if (Bot.HasInMonstersZone(CardId.PredaplantVerteAnaconda, true) || !Bot.HasInExtra(CardId.PredaplantVerteAnaconda))
return false;
if (Bot.Graveyard.GetMatchingCardsCount(card => (card.Race & (int)CardRace.Dragon) > 0) >= 0)
return false;
if (Bot.GetMonsterCount() == 1 && Bot.Hand.GetMatchingCardsCount(card => card.Level <= 4) == 0 && !Util.IsTurn1OrMain2())
return false;
if (Bot.GetMonsterCount() >= 2 && Bot.MonsterZone.GetMatchingCardsCount(card => card.Level >= 8) > 0)
return false;
return true;
}
private bool LinkSpiderSummon()
{
if (!Bot.HasInMonstersZone(CardId.MechaPhantomBeastOLionToken))
return false;
AI.SelectMaterials(CardId.MechaPhantomBeastOLionToken);
return true;
}
private bool NeedMonster()
{
if (Bot.HasInMonstersZone(CardId.PredaplantVerteAnaconda, true) || !Bot.HasInExtra(CardId.PredaplantVerteAnaconda))
return false;
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.Level >= 8) > 0)
return false;
if (Bot.GetMonsterCount() == 0 && Bot.Hand.GetMatchingCardsCount(card => card.Level <= 4) == 0)
return false;
if (Bot.GetMonsterCount() >= 2)
return false;
return true;
}
private bool InstantFusionEffect()
{
if (!NeedMonster())
return false;
if (Enemy.GetMonsterCount() > 0)
AI.SelectCard(CardId.ThousandEyesRestrict);
else
AI.SelectCard(CardId.SeaMonsterofTheseus);
return true;
}
private bool SummonForMaterial()
{
if (Bot.HasInMonstersZone(CardId.PredaplantVerteAnaconda, true) || !Bot.HasInExtra(CardId.PredaplantVerteAnaconda))
return false;
if (Bot.MonsterZone.GetMatchingCardsCount(card => (card.HasType(CardType.Effect) || card.IsTuner()) && card.Level < 8) == 1)
return true;
if (Bot.HasInHand(CardId.MagiciansSouls))
return true;
return false;
}
private bool MagiciansSoulsEffect()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (Card.Location == CardLocation.Hand)
{
if (RedEyesFusionUsed)
return false;
if (Bot.GetMonsterCount() >= 2)
return false;
AI.SelectOption(1);
AI.SelectYesNo(true);
return true;
}
else
{
int[] costs = new[] {
CardId.RedEyesInsight,
CardId.RedEyesFusion
};
if (Bot.HasInHand(costs))
{
AI.SelectCard(costs);
return true;
}
return false;
}
}
private bool PredaplantVerteAnacondaSummon()
{
if (Bot.HasInMonstersZone(CardId.PredaplantVerteAnaconda, true))
return false;
int[] materials = new[] {
CardId.ImdukTheWorldChaliceDragon,
CardId.Sangan,
CardId.TourGuideFromTheUnderworld,
CardId.CrusadiaArboria,
CardId.MechaPhantomBeastOLion,
CardId.MagiciansSouls,
CardId.SalamangreatAlmiraj,
CardId.LinkSpider,
CardId.ThousandEyesRestrict,
CardId.AshBlossomJoyousSpring,
CardId.MaxxC,
CardId.RedEyesWyvern,
CardId.CrystronHalqifibrax
};
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2)
{
AI.SelectMaterials(materials);
return true;
}
return false;
}
private bool MagicalizedFusionEffect()
{
if (Bot.HasInMonstersZone(new[] { CardId.DragunofRedEyes, CardId.RedEyesBDragon }))
{ // you don't want to use DragunofRedEyes which is treated as RedEyesBDragon as fusion material
if (Util.GetBotAvailZonesFromExtraDeck() == 0)
return false;
if (Bot.Graveyard.GetMatchingCardsCount(card => (card.Race & (int)CardRace.Dragon) > 0) == 0)
return false;
}
AI.SelectMaterials(CardLocation.Grave);
return true;
}
private bool PredaplantVerteAnacondaEffect()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (ActivateDescription == Util.GetStringId(CardId.PredaplantVerteAnaconda, 0))
return false;
AI.SelectCard(CardId.RedEyesFusion);
AI.SelectMaterials(CardLocation.Deck);
return true;
}
private bool FoolishBurialEffect()
{
if (RedEyesFusionUsed)
return false;
if (Bot.HasInHand(CardId.MagicalizedFusion))
{
if (Bot.HasInGraveyard(CardId.DarkMagician) && Bot.Graveyard.GetMatchingCardsCount(card => (card.Race & (int)CardRace.Dragon) > 0) == 0)
{
AI.SelectCard(new[]
{
CardId.RedEyesWyvern,
CardId.RedEyesBDragon
});
return true;
}
if (!Bot.HasInGraveyard(CardId.DarkMagician) && Bot.Graveyard.GetMatchingCardsCount(card => (card.Race & (int)CardRace.Dragon) > 0) > 0)
{
AI.SelectCard(CardId.DarkMagician);
return true;
}
}
if (!NeedMonster())
return false;
AI.SelectCard(new[] {
CardId.MechaPhantomBeastOLion
});
return true;
}
private bool MonsterRebornEffect()
{
if (Bot.HasInGraveyard(CardId.DragunofRedEyes))
{
AI.SelectCard(CardId.DragunofRedEyes);
return true;
}
else
{
if (!NeedMonster())
return false;
AI.SelectCard(new[] {
CardId.PredaplantVerteAnaconda,
CardId.Sangan,
CardId.ThousandEyesRestrict,
CardId.MechaPhantomBeastOLion,
CardId.CrusadiaArboria,
CardId.AshBlossomJoyousSpring
});
return true;
}
}
private bool MechaPhantomBeastOLionEffect()
{
if (ActivateDescription == -1)
{
BeastOLionUsed = true;
return true;
}
return !BeastOLionUsed;
}
private bool CrystronNeedlefiberSummon()
{
if (Bot.HasInMonstersZone(CardId.PredaplantVerteAnaconda, true))
return false;
int[] materials = new[] {
CardId.CrusadiaArboria,
CardId.MechaPhantomBeastOLion,
CardId.AshBlossomJoyousSpring,
CardId.SeaMonsterofTheseus,
CardId.MechaPhantomBeastOLionToken,
CardId.DarkMagician,
CardId.ImdukTheWorldChaliceDragon,
CardId.Sangan,
CardId.TourGuideFromTheUnderworld,
CardId.MagiciansSouls,
CardId.SalamangreatAlmiraj,
CardId.LinkSpider,
CardId.ThousandEyesRestrict,
CardId.SeaMonsterofTheseus,
CardId.MaxxC,
CardId.RedEyesWyvern
};
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2)
{
AI.SelectMaterials(materials);
return true;
}
return false;
}
private bool CrystronNeedlefiberEffect()
{
if (Duel.Player == 0)
{
AI.SelectCard(CardId.MechaPhantomBeastOLion);
return true;
}
else
{
return true;
}
}
private bool TrapSet()
{
if (Bot.HasInMonstersZone(new[] { CardId.DragunofRedEyes, CardId.RedEyesBDragon }) && Bot.GetHandCount() == 1)
return false;
AI.SelectPlace(Zones.z0 + Zones.z1 + Zones.z3 + Zones.z4);
return true;
}
private bool MonsterRepos()
{
if (Card.IsFacedown())
return true;
return DefaultMonsterRepos();
}
}
}
@@ -0,0 +1,482 @@
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game.AI.Decks
{
[Deck("Dragunity", "AI_Dragunity")]
public class DragunityExecutor : DefaultExecutor
{
public class CardId
{
public const int StardustDragonAssaultMode = 61257789;
public const int DragunityArmaMysletainn = 876330;
public const int AssaultBeast = 3431737;
public const int DragunityDux = 28183605;
public const int DragunityPhalanx = 59755122;
public const int AssaultTeleport = 29863101;
public const int CardsOfConsonance = 39701395;
public const int UpstartGoblin = 70368879;
public const int DragonsMirror = 71490127;
public const int Terraforming = 73628505;
public const int FoolishBurial = 81439173;
public const int MonsterReborn = 83764718;
public const int MysticalSpaceTyphoon = 5318639;
public const int FireFormationTenki = 57103969;
public const int DragunitySpearOfDestiny = 60004971;
public const int DragonRavine = 62265044;
public const int MirrorForce = 44095762;
public const int StarlightRoad = 58120309;
public const int DimensionalPrison = 70342110;
public const int AssaultModeActivate = 80280737;
public const int FiveHeadedDragon = 99267150;
public const int CrystalWingSynchroDragon = 50954680;
public const int ScrapDragon = 76774528;
public const int StardustDragon = 44508094;
public const int DragunityKnightGaeDearg = 34116027;
public const int DragunityKnightVajrayana = 21249921;
}
public DragunityExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// Set traps
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
// Execute spells
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, CardId.AssaultTeleport);
AddExecutor(ExecutorType.Activate, CardId.UpstartGoblin);
AddExecutor(ExecutorType.Activate, CardId.DragonRavine, DragonRavineField);
AddExecutor(ExecutorType.Activate, CardId.Terraforming, Terraforming);
AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurial);
AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, MonsterReborn);
// Execute monsters
AddExecutor(ExecutorType.Activate, CardId.ScrapDragon, ScrapDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.DragunityPhalanx);
AddExecutor(ExecutorType.Activate, CardId.DragunityKnightVajrayana);
AddExecutor(ExecutorType.Activate, CardId.DragunityArmaMysletainn, DragunityArmaMysletainnEffect);
AddExecutor(ExecutorType.Activate, CardId.DragunityDux);
// Summon
AddExecutor(ExecutorType.Activate, CardId.DragonsMirror, DragonsMirror);
AddExecutor(ExecutorType.SpSummon, CardId.ScrapDragon, ScrapDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.StardustDragon);
AddExecutor(ExecutorType.SpSummon, CardId.DragunityKnightVajrayana);
AddExecutor(ExecutorType.SpSummon, CardId.DragunityKnightGaeDearg);
AddExecutor(ExecutorType.Summon, CardId.DragunityPhalanx, DragunityPhalanxSummon);
AddExecutor(ExecutorType.SpSummon, CardId.DragunityArmaMysletainn, DragunityArmaMysletainn);
AddExecutor(ExecutorType.Summon, CardId.DragunityArmaMysletainn, DragunityArmaMysletainnTribute);
// Use draw effects if we can't do anything else
AddExecutor(ExecutorType.Activate, CardId.CardsOfConsonance);
AddExecutor(ExecutorType.Activate, CardId.DragonRavine, DragonRavineEffect);
AddExecutor(ExecutorType.Activate, CardId.FireFormationTenki, FireFormationTenki);
AddExecutor(ExecutorType.Activate, CardId.DragunitySpearOfDestiny);
// Summon
AddExecutor(ExecutorType.Summon, CardId.DragunityDux, DragunityDux);
AddExecutor(ExecutorType.MonsterSet, CardId.DragunityPhalanx, DragunityPhalanxSet);
AddExecutor(ExecutorType.SummonOrSet, CardId.AssaultBeast);
// Draw assault mode if we don't have one
AddExecutor(ExecutorType.Activate, CardId.AssaultBeast, AssaultBeast);
// Set useless cards
AddExecutor(ExecutorType.SpellSet, CardId.DragonsMirror, SetUselessCards);
AddExecutor(ExecutorType.SpellSet, CardId.Terraforming, SetUselessCards);
AddExecutor(ExecutorType.SpellSet, CardId.AssaultTeleport, SetUselessCards);
AddExecutor(ExecutorType.SpellSet, CardId.CardsOfConsonance, SetUselessCards);
// Chain traps and monsters
AddExecutor(ExecutorType.Activate, CardId.StardustDragonAssaultMode, DefaultStardustDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.StardustDragon, DefaultStardustDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.StarlightRoad, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.DimensionalPrison, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.AssaultModeActivate, AssaultModeActivate);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
private bool DragonRavineField()
{
if (Card.Location == CardLocation.Hand)
return DefaultField();
return false;
}
private bool DragonRavineEffect()
{
if (Card.Location != CardLocation.SpellZone)
return false;
int tributeId = -1;
if (Bot.HasInHand(CardId.DragunityPhalanx))
tributeId = CardId.DragunityPhalanx;
else if (Bot.HasInHand(CardId.FireFormationTenki))
tributeId = CardId.FireFormationTenki;
else if (Bot.HasInHand(CardId.Terraforming))
tributeId = CardId.Terraforming;
else if (Bot.HasInHand(CardId.DragonRavine))
tributeId = CardId.DragonRavine;
else if (Bot.HasInHand(CardId.AssaultTeleport))
tributeId = CardId.AssaultTeleport;
else if (Bot.HasInHand(CardId.AssaultBeast))
tributeId = CardId.AssaultBeast;
else if (Bot.HasInHand((int) CardId.DragunityArmaMysletainn))
tributeId = CardId.DragunityArmaMysletainn;
else
{
int count = 0;
foreach (ClientCard card in Bot.Hand)
{
if (card.IsCode(CardId.DragunityDux))
++count;
}
if (count >= 2)
tributeId = CardId.DragunityDux;
}
if (tributeId == -1 && Bot.HasInHand(CardId.StardustDragonAssaultMode))
tributeId = CardId.StardustDragonAssaultMode;
if (tributeId == -1 && Bot.HasInHand(CardId.DragunitySpearOfDestiny))
tributeId = CardId.StardustDragonAssaultMode;
if (tributeId == -1 && Bot.HasInHand(CardId.DragonsMirror)
&& Bot.GetMonsterCount() == 0)
tributeId = CardId.StardustDragonAssaultMode;
if (tributeId == -1)
return false;
int needId = -1;
if (!Bot.HasInMonstersZone(CardId.DragunityPhalanx) &&
!Bot.HasInGraveyard(CardId.DragunityPhalanx))
needId = CardId.DragunityPhalanx;
else if (Bot.GetMonsterCount() == 0)
needId = CardId.DragunityDux;
else
{
/*bool hasRealMonster = false;
foreach (ClientCard card in Bot.GetMonsters())
{
if (!card.IsCode(CardId.AssaultBeast))
{
hasRealMonster = true;
break;
}
}
if (!hasRealMonster || Util.GetProblematicCard() != null)*/
needId = CardId.DragunityDux;
}
if (needId == -1)
return false;
int option;
if (tributeId == CardId.DragunityPhalanx)
needId = CardId.DragunityDux;
int remaining = 3;
foreach (ClientCard card in Bot.Hand)
if (card.IsCode(needId))
remaining--;
foreach (ClientCard card in Bot.Graveyard)
if (card.IsCode(needId))
remaining--;
foreach (ClientCard card in Bot.Banished)
if (card.IsCode(needId))
remaining--;
if (remaining <= 0)
return false;
if (needId == CardId.DragunityPhalanx)
option = 2;
else
option = 1;
if (ActivateDescription != Util.GetStringId(CardId.DragonRavine, option))
return false;
AI.SelectCard(tributeId);
AI.SelectNextCard(needId);
return true;
}
private bool Terraforming()
{
if (Bot.HasInHand(CardId.DragonRavine))
return false;
if (Bot.SpellZone[5] != null)
return false;
return true;
}
private bool SetUselessCards()
{
ClientField field = Bot;
if (field.HasInSpellZone(CardId.FireFormationTenki))
return false;
if (field.HasInSpellZone(CardId.AssaultTeleport))
return false;
if (field.HasInSpellZone(CardId.CardsOfConsonance))
return false;
if (field.HasInSpellZone(CardId.DragonsMirror))
return false;
return Bot.GetSpellCountWithoutField() < 4;
}
private bool FireFormationTenki()
{
if (Card.Location == CardLocation.Hand)
return Bot.GetSpellCountWithoutField() < 4;
return true;
}
private bool FoolishBurial()
{
AI.SelectCard(
CardId.DragunityPhalanx,
CardId.AssaultBeast,
CardId.StardustDragonAssaultMode
);
return true;
}
private bool MonsterReborn()
{
List<ClientCard> cards = new List<ClientCard>(Bot.Graveyard.GetMatchingCards(card => card.IsCanRevive()));
cards.Sort(CardContainer.CompareCardAttack);
ClientCard selectedCard = null;
for (int i = cards.Count - 1; i >= 0; --i)
{
ClientCard card = cards[i];
if (card.Attack < 2000)
break;
if (card.IsCode(CardId.StardustDragonAssaultMode, CardId.FiveHeadedDragon))
continue;
if (card.IsMonster())
{
selectedCard = card;
break;
}
}
cards = new List<ClientCard>(Enemy.Graveyard.GetMatchingCards(card => card.IsCanRevive()));
cards.Sort(CardContainer.CompareCardAttack);
for (int i = cards.Count - 1; i >= 0; --i)
{
ClientCard card = cards[i];
if (card.Attack < 2000)
break;
if (card.IsMonster() && card.HasType(CardType.Normal) && (selectedCard == null || card.Attack > selectedCard.Attack))
{
selectedCard = card;
break;
}
}
if (selectedCard != null)
{
AI.SelectCard(selectedCard);
return true;
}
return false;
}
private bool DragonsMirror()
{
IList<ClientCard> tributes = new List<ClientCard>();
int phalanxCount = 0;
foreach (ClientCard card in Bot.Graveyard)
{
if (card.IsCode(CardId.DragunityPhalanx))
{
phalanxCount++;
break;
}
if (card.Race == (int) CardRace.Dragon)
tributes.Add(card);
if (tributes.Count == 5)
break;
}
// We can tribute one or two phalanx if needed, but only
// if we have more than one in the graveyard.
if (tributes.Count < 5 && phalanxCount > 1)
{
foreach (ClientCard card in Bot.Graveyard)
{
if (card.IsCode(CardId.DragunityPhalanx))
{
phalanxCount--;
tributes.Add(card);
if (phalanxCount <= 1)
break;
}
}
}
if (tributes.Count < 5)
return false;
AI.SelectCard(CardId.FiveHeadedDragon);
AI.SelectNextCard(tributes);
return true;
}
private bool ScrapDragonSummon()
{
//if (Util.IsOneEnemyBetterThanValue(2500, true))
// return true;
ClientCard invincible = Util.GetProblematicEnemyCard(3000);
return invincible != null;
}
private bool ScrapDragonEffect()
{
ClientCard invincible = Util.GetProblematicEnemyCard(3000);
if (invincible == null && !Util.IsOneEnemyBetterThanValue(2800 - 1, false))
return false;
int tributeId = -1;
if (Bot.HasInSpellZone(CardId.FireFormationTenki))
tributeId = CardId.FireFormationTenki;
else if (Bot.HasInSpellZone(CardId.Terraforming))
tributeId = CardId.Terraforming;
else if (Bot.HasInSpellZone(CardId.DragonsMirror))
tributeId = CardId.DragonsMirror;
else if (Bot.HasInSpellZone(CardId.CardsOfConsonance))
tributeId = CardId.CardsOfConsonance;
else if (Bot.HasInSpellZone(CardId.AssaultTeleport))
tributeId = CardId.AssaultTeleport;
else if (Bot.HasInSpellZone(CardId.AssaultModeActivate))
tributeId = CardId.AssaultModeActivate;
else if (Bot.HasInSpellZone(CardId.DragonRavine))
tributeId = CardId.DragonRavine;
List<ClientCard> monsters = Enemy.GetMonsters();
monsters.Sort(CardContainer.CompareCardAttack);
ClientCard destroyCard = invincible;
if (destroyCard == null)
{
for (int i = monsters.Count - 1; i >= 0; --i)
{
if (monsters[i].IsAttack())
{
destroyCard = monsters[i];
break;
}
}
}
if (destroyCard == null)
return false;
AI.SelectCard(tributeId);
AI.SelectNextCard(destroyCard);
return true;
}
private bool CrystalWingSynchroDragonSummon()
{
return !Bot.HasInHand(CardId.AssaultModeActivate)
&& !Bot.HasInHand(CardId.AssaultBeast)
&& !Bot.HasInSpellZone(CardId.AssaultModeActivate);
}
private bool CrystalWingSynchroDragonEffect()
{
return Duel.LastChainPlayer != 0;
}
private bool DragunityPhalanxSummon()
{
return Bot.HasInHand(CardId.DragunityArmaMysletainn);
}
private bool DragunityArmaMysletainn()
{
if (Bot.HasInMonstersZone(CardId.DragunityPhalanx))
{
AI.SelectCard(CardId.DragunityPhalanx);
return true;
}
if (Bot.HasInMonstersZone(CardId.DragunityDux))
{
AI.SelectCard(CardId.DragunityDux);
return true;
}
return false;
}
private bool DragunityArmaMysletainnEffect()
{
AI.SelectCard(CardId.DragunityPhalanx);
return true;
}
private bool DragunityArmaMysletainnTribute()
{
if ((Bot.HasInMonstersZone(CardId.AssaultBeast)
&& Bot.HasInGraveyard(CardId.DragunityPhalanx))
|| Bot.HasInMonstersZone(CardId.DragunityPhalanx)
|| Bot.HasInHand(CardId.DragunitySpearOfDestiny))
{
List<ClientCard> monster_sorted = Bot.GetMonsters();
monster_sorted.Sort(CardContainer.CompareCardAttack);
foreach (ClientCard monster in monster_sorted)
{
AI.SelectMaterials(monster);
return true;
}
}
return false;
}
private bool DragunityDux()
{
return Bot.HasInGraveyard(CardId.DragunityPhalanx) ||
(Bot.GetMonsterCount() == 0 && Bot.HasInHand(CardId.DragunityArmaMysletainn) ||
Bot.HasInHand(CardId.DragunitySpearOfDestiny));
}
private bool DragunityPhalanxSet()
{
return Bot.GetMonsterCount() == 0 || !Bot.HasInGraveyard(CardId.DragunityPhalanx);
}
private bool AssaultBeast()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (!Bot.HasInSpellZone(CardId.AssaultModeActivate))
return true;
return false;
}
private bool AssaultModeActivate()
{
if (Duel.Player == 0 && Duel.Phase == DuelPhase.BattleStart)
{
List<ClientCard> monsters = Bot.GetMonsters();
foreach (ClientCard monster in monsters)
{
if (monster.IsCode(CardId.StardustDragon) && monster.Attacked)
{
AI.SelectCard(monster);
return true;
}
}
}
return Duel.Player == 1;
}
}
}
@@ -0,0 +1,41 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
// NOT FINISHED YET
[Deck("Evilswarm", "AI_Evilswarm", "NotFinished")]
public class EvilswarmExecutor : DefaultExecutor
{
public class CardId
{
public const int DarkHole = 53129443;
public const int CosmicCyclone = 8267140;
public const int InfestationPandemic = 27541267;
public const int SolemnJudgment = 41420027;
public const int SolemnWarning = 84749824;
public const int SolemnStrike = 40605147;
}
public EvilswarmExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.CosmicCyclone, DefaultCosmicCyclone);
AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.SpellSet, CardId.InfestationPandemic);
AddExecutor(ExecutorType.Activate, DefaultDontChainMyself);
AddExecutor(ExecutorType.Summon);
AddExecutor(ExecutorType.SpSummon);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.SpellSet);
}
// will be added soon...?
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,629 @@
using YGOSharp.OCGWrapper;
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using System.Linq;
namespace WindBot.Game.AI.Decks
{
[Deck("FamiliarPossessed", "AI_FamiliarPossessed")]
public class FamiliarPossessedExecutor : DefaultExecutor
{
public class CardId
{
public const int MetalSnake = 71197066;
public const int InspectBoarder = 15397015;
public const int AshBlossomAndJoyousSpring = 14558127;
public const int GrenMajuDaEizo = 36584821;
public const int MaxxC = 23434538;
public const int Aussa = 31887906;
public const int Eria = 68881650;
public const int Wynn = 31764354;
public const int Hiita = 4376659;
public const int Lyna = 40542825;
public const int Awakening = 62256492;
public const int Unpossessed = 25704359;
public const int NaturalExterio = 99916754;
public const int NaturalBeast = 33198837;
public const int SwordsmanLV7 = 37267041;
public const int RoyalDecreel = 51452091;
public const int HarpieFeatherDuster = 18144506;
public const int PotOfDesires = 35261759;
public const int PotofExtravagance = 49238328;
public const int Scapegoat = 73915051;
public const int MacroCosmos = 30241314;
public const int Crackdown = 36975314;
public const int ImperialOrder = 61740673;
public const int SolemnWarning = 84749824;
public const int SolemStrike = 40605147;
public const int SolemnJudgment = 41420027;
public const int SkillDrain = 82732705;
public const int Mistake = 59305593;
public const int BorreloadDragon = 31833038;
public const int BirrelswordDragon = 85289965;
public const int KnightmareGryphon = 65330383;
public const int KnightmareUnicorn = 38342335;
public const int KnightmarePhoenix = 2857636;
public const int KnightmareCerberus = 75452921;
public const int LinkSpider = 98978921;
public const int Linkuriboh = 41999284;
public const int GagagaCowboy = 12014404;
public const int AussaP = 97661969;
public const int EriaP = 73309655;
public const int WynnP = 30674956;
public const int HiitaP = 48815792;
public const int LynaP = 9839945;
}
public FamiliarPossessedExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// do first
AddExecutor(ExecutorType.Activate, CardId.PotofExtravagance, PotofExtravaganceActivate);
// burn if enemy's LP is below 800
AddExecutor(ExecutorType.SpSummon, CardId.GagagaCowboy, GagagaCowboySummon);
AddExecutor(ExecutorType.Activate, CardId.GagagaCowboy);
//Sticker
AddExecutor(ExecutorType.Activate, CardId.MacroCosmos, MacroCosmoseff);
//counter
AddExecutor(ExecutorType.Activate, CardId.AshBlossomAndJoyousSpring, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, CardId.MaxxC, DefaultMaxxC);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.SolemStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, CardId.ImperialOrder, ImperialOrderfirst);
AddExecutor(ExecutorType.Activate, CardId.ImperialOrder, ImperialOrdereff);
AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, CardId.SkillDrain, SkillDrainEffect);
AddExecutor(ExecutorType.Activate, CardId.Mistake, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.Awakening);
AddExecutor(ExecutorType.Activate, CardId.Unpossessed, UnpossessedEffect);
//first do
AddExecutor(ExecutorType.Activate, CardId.HarpieFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, CardId.PotOfDesires, PotOfDesireseff);
//sp
AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, Linkuriboheff);
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp);
AddExecutor(ExecutorType.SpSummon, CardId.KnightmareCerberus, Knightmaresp);
AddExecutor(ExecutorType.SpSummon, CardId.KnightmarePhoenix, Knightmaresp);
AddExecutor(ExecutorType.SpSummon, CardId.AussaP, AussaPsp);
AddExecutor(ExecutorType.Activate, CardId.AussaP, AussaPeff);
AddExecutor(ExecutorType.SpSummon, CardId.EriaP, EriaPsp);
AddExecutor(ExecutorType.Activate, CardId.EriaP, EriaPeff);
AddExecutor(ExecutorType.SpSummon, CardId.WynnP, WynnPsp);
AddExecutor(ExecutorType.Activate, CardId.WynnP, WynnPeff);
AddExecutor(ExecutorType.SpSummon, CardId.HiitaP, HiitaPsp);
AddExecutor(ExecutorType.Activate, CardId.HiitaP, HiitaPeff);
AddExecutor(ExecutorType.SpSummon, CardId.LynaP, LynaPsp);
AddExecutor(ExecutorType.Activate, CardId.LynaP, LynaPeff);
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp);
AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider);
AddExecutor(ExecutorType.SpSummon, CardId.BorreloadDragon, BorreloadDragonsp);
AddExecutor(ExecutorType.Activate, CardId.BorreloadDragon, BorreloadDragoneff);
AddExecutor(ExecutorType.SpSummon, CardId.BirrelswordDragon, BirrelswordDragonsp);
AddExecutor(ExecutorType.Activate, CardId.BirrelswordDragon, BirrelswordDragoneff);
// normal summon
AddExecutor(ExecutorType.Summon, CardId.InspectBoarder, InspectBoardersummon);
AddExecutor(ExecutorType.Summon, CardId.GrenMajuDaEizo, GrenMajuDaEizosummon);
AddExecutor(ExecutorType.SpSummon, CardId.BorreloadDragon, BorreloadDragonspsecond);
AddExecutor(ExecutorType.Summon, CardId.Aussa, FamiliarPossessedsummon);
AddExecutor(ExecutorType.Summon, CardId.Eria, FamiliarPossessedsummon);
AddExecutor(ExecutorType.Summon, CardId.Wynn, FamiliarPossessedsummon);
AddExecutor(ExecutorType.Summon, CardId.Hiita, FamiliarPossessedsummon);
AddExecutor(ExecutorType.Summon, CardId.Lyna, FamiliarPossessedsummon);
AddExecutor(ExecutorType.Activate, CardId.MetalSnake, MetalSnakesp);
AddExecutor(ExecutorType.Activate, CardId.MetalSnake, MetalSnakeeff);
//spell
AddExecutor(ExecutorType.Activate, CardId.Crackdown, Crackdowneff);
AddExecutor(ExecutorType.Activate, CardId.Scapegoat, DefaultScapegoat);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
//set
AddExecutor(ExecutorType.SpellSet, SpellSet);
}
public void SelectSTPlace(ClientCard card = null, bool avoid_Impermanence = false, List<int> avoid_list = null)
{
List<int> list = new List<int> { 0, 1, 2, 3, 4 };
int n = list.Count;
while (n-- > 1)
{
int index = Program.Rand.Next(n + 1);
int temp = list[index];
list[index] = list[n];
list[n] = temp;
}
foreach (int seq in list)
{
int zone = (int)System.Math.Pow(2, seq);
if (Bot.SpellZone[seq] == null)
{
if (card != null && card.Location == CardLocation.Hand && avoid_Impermanence) continue;
if (avoid_list != null && avoid_list.Contains(seq)) continue;
AI.SelectPlace(zone);
return;
};
}
AI.SelectPlace(0);
}
public bool SpellNegatable(bool isCounter = false, ClientCard target = null)
{
// target default set
if (target == null) target = Card;
// won't negate if not on field
if (target.Location != CardLocation.SpellZone && target.Location != CardLocation.Hand) return false;
// negate judge
if (Enemy.HasInMonstersZone(CardId.NaturalExterio, true) && !isCounter) return true;
if (target.IsSpell())
{
if (Enemy.HasInMonstersZone(CardId.NaturalBeast, true)) return true;
if (Enemy.HasInSpellZone(CardId.ImperialOrder, true) || Bot.HasInSpellZone(CardId.ImperialOrder, true)) return true;
if (Enemy.HasInMonstersZone(CardId.SwordsmanLV7, true) || Bot.HasInMonstersZone(CardId.SwordsmanLV7, true)) return true;
}
if (target.IsTrap())
{
if (Enemy.HasInSpellZone(CardId.RoyalDecreel, true) || Bot.HasInSpellZone(CardId.RoyalDecreel, true)) return true;
}
// how to get here?
return false;
}
private bool MacroCosmoseff()
{
return (Duel.LastChainPlayer == 1 || Duel.LastSummonPlayer == 1 || Duel.Player == 0) && UniqueFaceupSpell();
}
private bool ImperialOrderfirst()
{
if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.PotOfDesires))
return false;
return DefaultOnBecomeTarget() && Util.GetLastChainCard().HasType(CardType.Spell);
}
private bool ImperialOrdereff()
{
if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.PotOfDesires))
return false;
if (Duel.LastChainPlayer == 1)
{
foreach (ClientCard check in Enemy.GetSpells())
{
if (Util.GetLastChainCard() == check)
return true;
}
}
return false;
}
private bool PotOfDesireseff()
{
return Bot.Deck.Count > 14 && !DefaultSpellWillBeNegated();
}
// activate of PotofExtravagance
public bool PotofExtravaganceActivate()
{
// won't activate if it'll be negate
if (SpellNegatable()) return false;
SelectSTPlace(Card, true);
AI.SelectOption(1);
return true;
}
private bool Crackdowneff()
{
if (Util.GetOneEnemyBetterThanMyBest(true, true) != null && Bot.UnderAttack)
AI.SelectCard(Util.GetOneEnemyBetterThanMyBest(true, true));
return Util.GetOneEnemyBetterThanMyBest(true, true) != null && Bot.UnderAttack;
}
private bool SkillDrainEffect()
{
return (Bot.LifePoints > 1000) && DefaultUniqueTrap();
}
private bool UnpossessedEffect()
{
AI.SelectCard(new List<int>() {
CardId.Lyna,
CardId.Hiita,
CardId.Wynn,
CardId.Eria,
CardId.Aussa
});
return true;
}
private bool InspectBoardersummon()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return true;
}
private bool GrenMajuDaEizosummon()
{
if (Duel.Turn == 1) return false;
if (Bot.HasInSpellZone(CardId.SkillDrain) || Enemy.HasInSpellZone(CardId.SkillDrain)) return false;
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return Bot.Banished.Count >= 6;
}
private bool FamiliarPossessedsummon()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return true;
}
private bool BorreloadDragonsp()
{
if (!(Bot.HasInMonstersZone(new[] { CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP }))) return false;
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.IsCode(CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP, CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LinkSpider, CardId.Linkuriboh))
material_list.Add(monster);
if (material_list.Count == 3) break;
}
if (material_list.Count >= 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
private bool BorreloadDragonspsecond()
{
if (!(Bot.HasInMonstersZone(new[] { CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP }))) return false;
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.IsCode(CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP, CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LinkSpider, CardId.Linkuriboh))
material_list.Add(monster);
if (material_list.Count == 3) break;
}
if (material_list.Count >= 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
public bool BorreloadDragoneff()
{
if (ActivateDescription == -1 && (Duel.Phase == DuelPhase.BattleStart || Duel.Phase == DuelPhase.End))
{
ClientCard enemy_monster = Enemy.BattlingMonster;
if (enemy_monster != null && enemy_monster.HasPosition(CardPosition.Attack))
{
return (Card.Attack - enemy_monster.Attack < Enemy.LifePoints);
}
return true;
};
ClientCard BestEnemy = Util.GetBestEnemyMonster(true);
ClientCard WorstBot = Bot.GetMonsters().GetLowestAttackMonster();
if (BestEnemy == null || BestEnemy.HasPosition(CardPosition.FaceDown)) return false;
if (WorstBot == null || WorstBot.HasPosition(CardPosition.FaceDown)) return false;
if (BestEnemy.Attack >= WorstBot.RealPower)
{
AI.SelectCard(BestEnemy);
return true;
}
return false;
}
private bool BirrelswordDragonsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard m in Bot.GetMonsters())
{
if (m.IsCode(CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP))
{
material_list.Add(m);
break;
}
}
foreach (ClientCard m in Bot.GetMonsters())
{
if (m.IsCode(CardId.Linkuriboh) || m.Level == 1)
{
material_list.Add(m);
if (material_list.Count == 3)
break;
}
}
if (material_list.Count == 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
private bool BirrelswordDragoneff()
{
if (ActivateDescription == Util.GetStringId(CardId.BirrelswordDragon, 0))
{
if (Util.IsChainTarget(Card) && Util.GetBestEnemyMonster(true, true) != null)
{
AI.SelectCard(Util.GetBestEnemyMonster(true, true));
return true;
}
if (Duel.Player == 1 && Bot.BattlingMonster == Card)
{
AI.SelectCard(Enemy.BattlingMonster);
return true;
}
if (Duel.Player == 1 && Bot.BattlingMonster != null &&
(Enemy.BattlingMonster.Attack - Bot.BattlingMonster.Attack) >= Bot.LifePoints)
{
AI.SelectCard(Enemy.BattlingMonster);
return true;
}
if (Duel.Player == 0 && Duel.Phase == DuelPhase.BattleStart)
{
foreach (ClientCard check in Enemy.GetMonsters())
{
if (check.IsAttack())
{
AI.SelectCard(check);
return true;
}
}
}
return false;
}
return true;
}
private bool MetalSnakesp()
{
if (ActivateDescription == Util.GetStringId(CardId.MetalSnake, 0) && !Bot.HasInMonstersZone(CardId.MetalSnake))
{
if (Duel.Player == 1 && Duel.Phase >= DuelPhase.BattleStart)
return Bot.Deck.Count >= 12;
if (Duel.Player == 0 && Duel.Phase >= DuelPhase.Main1)
return Bot.Deck.Count >= 12;
}
return false;
}
private bool MetalSnakeeff()
{
ClientCard target = Util.GetOneEnemyBetterThanMyBest(true, true);
if (ActivateDescription == Util.GetStringId(CardId.MetalSnake, 1) && target != null)
{
AI.SelectCard(new[]
{
CardId.LynaP,
CardId.HiitaP,
CardId.WynnP,
CardId.EriaP,
CardId.KnightmareGryphon
});
AI.SelectNextCard(target);
return true;
}
return false;
}
private bool AussaPsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Earth) && !monster.IsCode(CardId.KnightmareCerberus, CardId.InspectBoarder, CardId.GrenMajuDaEizo, CardId.KnightmarePhoenix, CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP, CardId.KnightmareUnicorn, CardId.KnightmareGryphon, CardId.BorreloadDragon, CardId.BirrelswordDragon))
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.AussaP)) return false;
AI.SelectMaterials(material_list);
if (Bot.MonsterZone[0] == null && Bot.MonsterZone[2] == null && Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool AussaPeff()
{
AI.SelectCard(CardId.MaxxC, CardId.Aussa);
return true;
}
private bool EriaPsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Water) && !monster.IsCode(CardId.KnightmareCerberus, CardId.InspectBoarder, CardId.GrenMajuDaEizo, CardId.KnightmarePhoenix, CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP, CardId.KnightmareUnicorn, CardId.KnightmareGryphon, CardId.BorreloadDragon, CardId.BirrelswordDragon))
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.EriaP)) return false;
AI.SelectMaterials(material_list);
if (Bot.MonsterZone[0] == null && Bot.MonsterZone[2] == null && Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool EriaPeff()
{
AI.SelectCard(CardId.Eria);
return true;
}
private bool WynnPsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Wind) && !monster.IsCode(CardId.KnightmareCerberus, CardId.InspectBoarder, CardId.GrenMajuDaEizo, CardId.KnightmarePhoenix, CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP, CardId.KnightmareUnicorn, CardId.KnightmareGryphon, CardId.BorreloadDragon, CardId.BirrelswordDragon))
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.WynnP)) return false;
AI.SelectMaterials(material_list);
if (Bot.MonsterZone[0] == null && Bot.MonsterZone[2] == null && Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool WynnPeff()
{
AI.SelectCard(CardId.Wynn);
return true;
}
private bool HiitaPsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Fire) && !monster.IsCode(CardId.KnightmareCerberus, CardId.InspectBoarder, CardId.GrenMajuDaEizo, CardId.KnightmarePhoenix, CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP, CardId.KnightmareUnicorn, CardId.KnightmareGryphon, CardId.BorreloadDragon, CardId.BirrelswordDragon))
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.HiitaP)) return false;
AI.SelectMaterials(material_list);
if (Bot.MonsterZone[0] == null && Bot.MonsterZone[2] == null && Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool HiitaPeff()
{
AI.SelectCard(CardId.Hiita);
return true;
}
private bool LynaPsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Light) && !monster.IsCode(CardId.KnightmareCerberus, CardId.InspectBoarder, CardId.GrenMajuDaEizo, CardId.KnightmarePhoenix, CardId.LynaP, CardId.HiitaP, CardId.WynnP, CardId.EriaP, CardId.AussaP, CardId.KnightmareUnicorn, CardId.KnightmareGryphon, CardId.BorreloadDragon, CardId.BirrelswordDragon))
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.LynaP)) return false;
AI.SelectMaterials(material_list);
if (Bot.MonsterZone[0] == null && Bot.MonsterZone[2] == null && Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool LynaPeff()
{
AI.SelectCard(CardId.Lyna);
return true;
}
private bool Linkuribohsp()
{
foreach (ClientCard c in Bot.GetMonsters())
{
if (c.Level == 1)
{
AI.SelectMaterials(c);
return true;
}
}
return false;
}
private bool Knightmaresp()
{
int[] firstMats = new[] {
CardId.KnightmareCerberus,
CardId.KnightmarePhoenix
};
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(firstMats)) >= 1) return false;
foreach (ClientCard c in Bot.GetMonsters())
{
if (c.Level == 1)
{
AI.SelectMaterials(c);
return true;
}
}
return false;
}
private bool Linkuriboheff()
{
if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.Linkuriboh)) return false;
return true;
}
private bool GagagaCowboySummon()
{
if (Enemy.LifePoints <= 800 || (Bot.GetMonsterCount() >= 4 && Enemy.LifePoints <= 1600))
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool SpellSet()
{
if (Card.IsCode(CardId.MacroCosmos) && Bot.HasInSpellZone(CardId.MacroCosmos)) return false;
if (Card.IsCode(CardId.Unpossessed) && Bot.HasInSpellZone(CardId.Unpossessed)) return false;
if (Card.IsCode(CardId.Crackdown) && Bot.HasInSpellZone(CardId.Crackdown)) return false;
if (Card.IsCode(CardId.SkillDrain) && Bot.HasInSpellZone(CardId.SkillDrain)) return false;
if (Card.IsCode(CardId.Mistake) && Bot.HasInSpellZone(CardId.Mistake)) return false;
if (Card.IsCode(CardId.Scapegoat))
return true;
if (Card.HasType(CardType.Trap))
return Bot.GetSpellCountWithoutField() < 4;
return false;
}
public override ClientCard OnSelectAttacker(IList<ClientCard> attackers, IList<ClientCard> defenders)
{
for (int i = 0; i < attackers.Count; ++i)
{
ClientCard attacker = attackers[i];
if (attacker.IsCode(CardId.BirrelswordDragon, CardId.BorreloadDragon)) return attacker;
}
return null;
}
public override bool OnSelectHand()
{
return true;
}
}
}
@@ -0,0 +1,259 @@
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game.AI.Decks
{
[Deck("Frog", "AI_Frog", "Easy")]
public class FrogExecutor : DefaultExecutor
{
public class CardId
{
public const int CryomancerOfTheIceBarrier = 23950192;
public const int DewdarkOfTheIceBarrier = 90311614;
public const int SubmarineFrog = 63948258;
public const int SwapFrog = 9126351;
public const int FlipFlopFrog = 81278754;
public const int Unifrog = 56052205;
public const int Ronintoadin = 1357146;
public const int DupeFrog = 46239604;
public const int Tradetoad = 23408872;
public const int TreebornFrog = 12538374;
public const int DarkHole = 53129443;
public const int Raigeki = 12580477;
public const int Terraforming = 73628505;
public const int PotOfDuality = 98645731;
public const int Solidarity = 86780027;
public const int Wetlands = 2084239;
public const int FroggyForcefield = 34351849;
public const int GravityBind = 85742772;
public const int TheHugeRevolutionIsOver = 99188141;
}
public FrogExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Activate, CardId.Solidarity, Solidarity);
AddExecutor(ExecutorType.Activate, CardId.Terraforming, Terraforming);
AddExecutor(ExecutorType.Activate, CardId.Wetlands, DefaultField);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.Raigeki, DefaultRaigeki);
AddExecutor(ExecutorType.Activate, CardId.PotOfDuality, PotOfDuality);
AddExecutor(ExecutorType.SpSummon, CardId.SwapFrog, SwapFrogSummon);
AddExecutor(ExecutorType.Activate, CardId.SwapFrog, SwapFrogActivate);
AddExecutor(ExecutorType.Activate, CardId.DupeFrog, DupeFrog);
AddExecutor(ExecutorType.Activate, CardId.FlipFlopFrog, FlipFlopFrog);
AddExecutor(ExecutorType.Activate, CardId.Ronintoadin, Ronintoadin);
AddExecutor(ExecutorType.Activate, CardId.TreebornFrog, TreebornFrog);
AddExecutor(ExecutorType.Activate, CardId.Unifrog);
AddExecutor(ExecutorType.Summon, CardId.CryomancerOfTheIceBarrier, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.DewdarkOfTheIceBarrier, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.SubmarineFrog, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.SwapFrog, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.Unifrog, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.Ronintoadin, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.DupeFrog, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.Tradetoad, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.TreebornFrog, SummonFrog);
AddExecutor(ExecutorType.Summon, CardId.FlipFlopFrog, SummonFrog);
AddExecutor(ExecutorType.MonsterSet, CardId.FlipFlopFrog);
AddExecutor(ExecutorType.MonsterSet, CardId.DupeFrog);
AddExecutor(ExecutorType.MonsterSet, CardId.Tradetoad);
AddExecutor(ExecutorType.MonsterSet, CardId.Ronintoadin);
AddExecutor(ExecutorType.MonsterSet, CardId.TreebornFrog);
AddExecutor(ExecutorType.MonsterSet, CardId.Unifrog);
AddExecutor(ExecutorType.MonsterSet, CardId.SwapFrog);
AddExecutor(ExecutorType.MonsterSet, CardId.SubmarineFrog);
AddExecutor(ExecutorType.MonsterSet, CardId.DewdarkOfTheIceBarrier);
AddExecutor(ExecutorType.MonsterSet, CardId.CryomancerOfTheIceBarrier);
AddExecutor(ExecutorType.Repos, FrogMonsterRepos);
AddExecutor(ExecutorType.Activate, CardId.FroggyForcefield, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.TheHugeRevolutionIsOver, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.GravityBind, GravityBind);
}
private int m_swapFrogSummoned;
private int m_flipFlopFrogSummoned;
private bool TreebornFrog()
{
return true;
}
private bool SwapFrogSummon()
{
int atk = Card.Attack + GetSpellBonus();
if (Util.IsAllEnemyBetterThanValue(atk, true))
return false;
AI.SelectCard(CardId.Ronintoadin);
m_swapFrogSummoned = Duel.Turn;
return true;
}
private bool SwapFrogActivate()
{
if (m_swapFrogSummoned != Duel.Turn)
return false;
m_swapFrogSummoned = -1;
if (Bot.GetRemainingCount(CardId.Ronintoadin, 2) == 0)
return false;
AI.SelectCard(CardId.Ronintoadin);
return true;
}
private bool DupeFrog()
{
AI.SelectCard(CardLocation.Deck);
return true;
}
private bool FlipFlopFrog()
{
if (Card.IsDefense() || m_flipFlopFrogSummoned == Duel.Turn || Duel.Phase == DuelPhase.Main2)
{
m_flipFlopFrogSummoned = -1;
List<ClientCard> monsters = Enemy.GetMonsters();
monsters.Sort(CardContainer.CompareCardAttack);
monsters.Reverse();
AI.SelectCard(monsters);
return true;
}
return false;
}
private bool Ronintoadin()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
List<ClientCard> monsters = Bot.GetGraveyardMonsters();
if (monsters.Count > 2)
{
if (GetSpellBonus() == 0)
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool SummonFrog()
{
int atk = Card.Attack + GetSpellBonus();
if (Util.IsOneEnemyBetterThanValue(atk, true))
return false;
if (Card.IsCode(CardId.SwapFrog))
m_swapFrogSummoned = Duel.Turn;
return true;
}
private bool PotOfDuality()
{
List<int> cards = new List<int>();
if (Util.IsOneEnemyBetter())
{
cards.Add(CardId.FlipFlopFrog);
}
if (Bot.SpellZone[5] == null)
{
cards.Add(CardId.Terraforming);
cards.Add(CardId.Wetlands);
}
cards.Add(CardId.DarkHole);
cards.Add(CardId.SwapFrog);
cards.Add(CardId.GravityBind);
if (cards.Count > 0)
{
AI.SelectCard(cards);
return true;
}
return false;
}
private bool Terraforming()
{
if (Bot.HasInHand(CardId.Wetlands))
return false;
if (Bot.SpellZone[5] != null)
return false;
return true;
}
private bool Solidarity()
{
List<ClientCard> monsters = Bot.GetGraveyardMonsters();
return monsters.Count != 0;
}
private bool GravityBind()
{
List<ClientCard> spells = Bot.GetSpells();
foreach (ClientCard spell in spells)
{
if (spell.IsCode(CardId.GravityBind) && !spell.IsFacedown())
return false;
}
return true;
}
private bool FrogMonsterRepos()
{
if (Card.IsCode(CardId.Unifrog))
return Card.IsDefense();
if (Card.IsCode(CardId.DewdarkOfTheIceBarrier))
return Card.IsDefense();
bool enemyBetter = Util.IsOneEnemyBetterThanValue(Card.Attack + (Card.IsFacedown() ? GetSpellBonus() : 0), true);
if (Card.Attack < 800)
enemyBetter = true;
bool result = false;
if (Card.IsAttack() && enemyBetter)
result = true;
if (Card.IsDefense() && !enemyBetter)
result = true;
if (!result && Card.IsCode(CardId.FlipFlopFrog) && Enemy.GetMonsterCount() > 0 && Card.IsFacedown())
result = true;
if (Card.IsCode(CardId.FlipFlopFrog) && Card.IsFacedown() && result)
m_flipFlopFrogSummoned = Duel.Turn;
return result;
}
private int GetSpellBonus()
{
int atk = 0;
if (Bot.SpellZone[5] != null)
atk += 1200;
List<ClientCard> monsters = Bot.GetGraveyardMonsters();
if (monsters.Count != 0)
{
foreach (ClientCard card in Bot.GetSpells())
{
if (card.IsCode(CardId.Solidarity))
atk += 800;
}
}
return atk;
}
}
}
@@ -0,0 +1,147 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
// NOT FINISHED YET
[Deck("Gravekeeper", "AI_Gravekeeper", "NotFinished")]
public class GravekeeperExecutor : DefaultExecutor
{
public class CardId
{
public const int GravekeepersOracle = 25524823;
public const int MaleficStardustDragon = 36521459;
public const int GravekeepersVisionary = 3825890;
public const int GravekeepersChief = 62473983;
public const int ThunderKingRaiOh = 71564252;
public const int GravekeepersCommandant = 17393207;
public const int GravekeepersAssailant = 25262697;
public const int GravekeepersDescendant = 30213599;
public const int GravekeepersSpy = 24317029;
public const int GravekeepersRecruiter = 93023479;
public const int AllureOfDarkness = 1475311;
public const int DarkHole = 53129443;
public const int RoyalTribute = 72405967;
public const int GravekeepersStele = 99523325;
public const int MysticalSpaceTyphoon = 5318639;
public const int BookofMoon = 14087893;
public const int HiddenTemplesOfNecrovalley = 70000776;
public const int Necrovalley = 47355498;
public const int BottomlessTrapHole = 29401950;
public const int RiteOfSpirit = 30450531;
public const int TorrentialTribute = 53582587;
public const int DimensionalPrison = 70342110;
public const int SolemnWarning = 84749824;
public const int ImperialTombsOfNecrovalley = 90434657;
}
public GravekeeperExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Activate, CardId.AllureOfDarkness);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.RoyalTribute);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersStele);
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, CardId.BookofMoon, DefaultBookOfMoon);
AddExecutor(ExecutorType.Activate, CardId.HiddenTemplesOfNecrovalley, HiddenTemplesOfNecrovalleyEffect);
AddExecutor(ExecutorType.Activate, CardId.Necrovalley, NecrovalleyActivate);
AddExecutor(ExecutorType.Activate, CardId.BottomlessTrapHole, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.DimensionalPrison, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.RiteOfSpirit, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.ImperialTombsOfNecrovalley, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.TorrentialTribute, DefaultTorrentialTribute);
AddExecutor(ExecutorType.Summon, CardId.GravekeepersOracle);
AddExecutor(ExecutorType.SpSummon, CardId.MaleficStardustDragon, MaleficStardustDragonSummon);
AddExecutor(ExecutorType.Summon, CardId.GravekeepersVisionary);
AddExecutor(ExecutorType.Summon, CardId.GravekeepersChief);
AddExecutor(ExecutorType.Summon, CardId.ThunderKingRaiOh);
AddExecutor(ExecutorType.Summon, CardId.GravekeepersCommandant, GravekeepersCommandantSummon);
AddExecutor(ExecutorType.Summon, CardId.GravekeepersAssailant);
AddExecutor(ExecutorType.Summon, CardId.GravekeepersDescendant);
AddExecutor(ExecutorType.MonsterSet, CardId.GravekeepersSpy);
AddExecutor(ExecutorType.MonsterSet, CardId.GravekeepersRecruiter);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersOracle);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersVisionary);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersChief);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersCommandant, GravekeepersCommandantEffect);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersAssailant, GravekeepersAssailantEffect);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersDescendant, GravekeepersDescendantEffect);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersSpy, SearchForDescendant);
AddExecutor(ExecutorType.Activate, CardId.GravekeepersRecruiter, SearchForDescendant);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
private bool HiddenTemplesOfNecrovalleyEffect()
{
if (Card.Location == CardLocation.Hand && Bot.HasInSpellZone((int)Card.Id))
return false;
return true;
}
private bool NecrovalleyActivate()
{
if (Bot.SpellZone[5] != null)
return false;
return true;
}
private bool MaleficStardustDragonSummon()
{
if (Bot.SpellZone[5] != null)
return true;
return false;
}
private bool GravekeepersCommandantEffect()
{
if (!Bot.HasInHand(CardId.Necrovalley) && !Bot.HasInSpellZone(CardId.Necrovalley))
return true;
return false;
}
private bool GravekeepersCommandantSummon()
{
return !GravekeepersCommandantEffect();
}
private bool GravekeepersAssailantEffect()
{
if (!Card.IsAttack())
return false;
foreach (ClientCard card in Enemy.GetMonsters())
{
if (card.IsDefense() && card.Defense > 1500 && card.Attack < 1500 || card.Attack > 1500 && card.Defense < 1500)
return true;
}
return false;
}
private bool GravekeepersDescendantEffect()
{
int bestatk = Bot.GetMonsters().GetHighestAttackMonster().Attack;
if (Util.IsOneEnemyBetterThanValue(bestatk, true))
{
AI.SelectCard(Enemy.GetMonsters().GetHighestAttackMonster());
return true;
}
return false;
}
private bool SearchForDescendant()
{
AI.SelectCard(CardId.GravekeepersDescendant);
return true;
}
}
}
@@ -0,0 +1,39 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
// NOT FINISHED YET
[Deck("Graydle", "AI_Graydle", "NotFinished")]
public class GraydleExecutor : DefaultExecutor
{
public class CardId
{
public const int DarkHole = 53129443;
public const int CosmicCyclone = 8267140;
public const int SolemnJudgment = 41420027;
public const int SolemnWarning = 84749824;
public const int SolemnStrike = 40605147;
}
public GraydleExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.CosmicCyclone, DefaultCosmicCyclone);
AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, DefaultDontChainMyself);
AddExecutor(ExecutorType.MonsterSet);
AddExecutor(ExecutorType.SpSummon);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.SpellSet);
}
// will be added soon...?
}
}
@@ -0,0 +1,733 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("GrenMajuThunderBoarder", "AI_GrenMajuThunderBoarder")]
public class GrenMajuThunderBoarderExecutor : DefaultExecutor
{
public class CardId
{
public const int MetalSnake = 71197066;
public const int InspectBoarder = 15397015;
public const int ThunderKingRaiOh = 71564252;
public const int AshBlossomAndJoyousSpring =14558127;
public const int GhostReaperAndWinterCherries = 62015408;
public const int GrenMajuDaEizo = 36584821;
public const int MaxxC = 23434538;
public const int EaterOfMillions = 63845230;
public const int HarpieFeatherDuster = 18144506;
public const int PotOfDesires = 35261759;
public const int CardOfDemise = 59750328;
public const int UpstartGoblin = 70368879;
public const int PotOfDuality = 98645731;
public const int Scapegoat = 73915051;
public const int MoonMirrorShield = 19508728;
public const int InfiniteImpermanence = 10045474;
public const int WakingTheDragon = 10813327;
public const int EvenlyMatched = 15693423;
public const int HeavyStormDuster = 23924608;
public const int DrowningMirrorForce = 47475363;
public const int MacroCosmos = 30241314;
public const int Crackdown = 36975314;
public const int AntiSpellFragrance = 58921041;
public const int ImperialOrder = 61740673;
public const int PhatomKnightsSword = 61936647;
public const int UnendingNightmare= 69452756;
public const int SolemnWarning = 84749824;
public const int SolemStrike= 40605147;
public const int SolemnJudgment = 41420027;
public const int DarkBribe = 77538567;
public const int RaidraptorUltimateFalcon = 86221741;
public const int BorreloadDragon = 31833038;
public const int BirrelswordDragon = 85289965;
public const int FirewallDragon = 5043010;
public const int NingirsuTheWorldChaliceWarrior = 30194529;
public const int TopologicTrisbaena = 72529749;
public const int KnightmareUnicorn = 38342335;
public const int KnightmarePhoenix = 2857636;
public const int HeavymetalfoesElectrumite= 24094258;
public const int KnightmareCerberus = 75452921;
public const int CrystronNeedlefiber = 50588353;
public const int MissusRadiant= 3987233;
public const int BrandishMaidenKagari= 63288573;
public const int LinkSpider = 98978921;
public const int Linkuriboh = 41999284;
public const int KnightmareGryphon = 65330383;
}
public GrenMajuThunderBoarderExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.GoToBattlePhase, GoToBattlePhase);
AddExecutor(ExecutorType.Activate, CardId.EvenlyMatched, EvenlyMatchedeff);
//Sticker
AddExecutor(ExecutorType.Activate, CardId.MacroCosmos, MacroCosmoseff);
AddExecutor(ExecutorType.Activate, CardId.AntiSpellFragrance, AntiSpellFragranceeff);
//counter
AddExecutor(ExecutorType.Activate, CardId.AshBlossomAndJoyousSpring, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, CardId.MaxxC, DefaultMaxxC);
AddExecutor(ExecutorType.Activate, CardId.InfiniteImpermanence, DefaultInfiniteImpermanence);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.SolemStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, CardId.ImperialOrder, ImperialOrderfirst);
AddExecutor(ExecutorType.Activate, CardId.HeavyStormDuster, HeavyStormDustereff);
AddExecutor(ExecutorType.Activate, CardId.UnendingNightmare, UnendingNightmareeff);
AddExecutor(ExecutorType.Activate, CardId.DarkBribe, DarkBribeeff);
AddExecutor(ExecutorType.Activate, CardId.ImperialOrder, ImperialOrdereff);
AddExecutor(ExecutorType.Activate, CardId.ThunderKingRaiOh, ThunderKingRaiOheff);
AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, CardId.DrowningMirrorForce, DrowningMirrorForceeff);
//first do
AddExecutor(ExecutorType.Activate, CardId.UpstartGoblin, UpstartGoblineff);
AddExecutor(ExecutorType.Activate, CardId.HarpieFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, CardId.PotOfDuality, PotOfDualityeff);
AddExecutor(ExecutorType.Activate, CardId.PotOfDesires, PotOfDesireseff);
AddExecutor(ExecutorType.Activate, CardId.CardOfDemise, CardOfDemiseeff);
//sp
AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, Linkuriboheff);
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp);
AddExecutor(ExecutorType.SpSummon, CardId.KnightmareCerberus,Knightmaresp);
AddExecutor(ExecutorType.SpSummon, CardId.KnightmarePhoenix, Knightmaresp);
AddExecutor(ExecutorType.SpSummon, CardId.MissusRadiant, MissusRadiantsp);
AddExecutor(ExecutorType.Activate, CardId.MissusRadiant, MissusRadianteff);
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp);
AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider);
AddExecutor(ExecutorType.SpSummon, CardId.BorreloadDragon, BorreloadDragonsp);
AddExecutor(ExecutorType.Activate, CardId.BorreloadDragon, BorreloadDragoneff);
AddExecutor(ExecutorType.Activate, CardId.EaterOfMillions, EaterOfMillionseff);
AddExecutor(ExecutorType.Activate, CardId.WakingTheDragon, WakingTheDragoneff);
// normal summon
AddExecutor(ExecutorType.Summon, CardId.InspectBoarder, InspectBoardersummon);
AddExecutor(ExecutorType.Summon, CardId.GrenMajuDaEizo, GrenMajuDaEizosummon);
AddExecutor(ExecutorType.Summon, CardId.ThunderKingRaiOh, ThunderKingRaiOhsummon);
AddExecutor(ExecutorType.SpSummon, CardId.BorreloadDragon, BorreloadDragonspsecond);
AddExecutor(ExecutorType.SpSummon, CardId.EaterOfMillions, EaterOfMillionssp);
AddExecutor(ExecutorType.Activate, CardId.MetalSnake, MetalSnakesp);
AddExecutor(ExecutorType.Activate, CardId.MetalSnake, MetalSnakeeff);
//spell
AddExecutor(ExecutorType.Activate, CardId.Crackdown, Crackdowneff);
AddExecutor(ExecutorType.Activate, CardId.MoonMirrorShield, MoonMirrorShieldeff);
AddExecutor(ExecutorType.Activate, CardId.Scapegoat, DefaultScapegoat);
AddExecutor(ExecutorType.Activate, CardId.PhatomKnightsSword, PhatomKnightsSwordeff);
AddExecutor(ExecutorType.Repos, MonsterRepos);
//set
AddExecutor(ExecutorType.SpellSet, SpellSet);
}
bool CardOfDemiseeff_used = false;
bool eater_eff = false;
public override void OnNewTurn()
{
eater_eff = false;
CardOfDemiseeff_used = false;
base.OnNewTurn();
}
public override void OnNewPhase()
{
foreach (ClientCard check in Bot.GetMonsters())
{
if (check.HasType(CardType.Fusion) || check.HasType(CardType.Xyz) ||
check.HasType(CardType.Synchro) || check.HasType(CardType.Link) ||
check.HasType(CardType.Ritual))
{
eater_eff = true;
break;
}
}
foreach (ClientCard check in Enemy.GetMonsters())
{
if (check.HasType(CardType.Fusion) || check.HasType(CardType.Xyz) ||
check.HasType(CardType.Synchro) || check.HasType(CardType.Link) ||
check.HasType(CardType.Ritual))
{
eater_eff = true;
break;
}
}
base.OnNewPhase();
}
private bool GoToBattlePhase()
{
return Bot.HasInHand(CardId.EvenlyMatched) && Duel.Turn >= 2 && Enemy.GetFieldCount() >= 2 && Bot.GetFieldCount() == 0;
}
private bool MacroCosmoseff()
{
return (Duel.LastChainPlayer == 1 || Duel.LastSummonPlayer == 1 || Duel.Player == 0) && UniqueFaceupSpell();
}
private bool AntiSpellFragranceeff()
{
int spell_count = 0;
foreach(ClientCard check in Bot.Hand)
{
if (check.HasType(CardType.Spell))
spell_count++;
}
if (spell_count >= 2) return false;
return Duel.Player == 1 && UniqueFaceupSpell();
}
private bool EvenlyMatchedeff()
{
return Enemy.GetFieldCount()-Bot.GetFieldCount() > 1;
}
private bool HeavyStormDustereff()
{
IList<ClientCard> targets = new List<ClientCard>();
foreach (ClientCard check in Enemy.GetSpells())
{
if (check.HasType(CardType.Continuous) || check.HasType(CardType.Field))
targets.Add(check);
}
if (Util.GetPZone(1, 0) != null && Util.GetPZone(1, 0).Type == 16777218)
{
targets.Add(Util.GetPZone(1, 0));
}
if (Util.GetPZone(1, 1) != null && Util.GetPZone(1, 1).Type == 16777218)
{
targets.Add(Util.GetPZone(1, 1));
}
foreach (ClientCard check in Enemy.GetSpells())
{
if (!check.HasType(CardType.Continuous) && !check.HasType(CardType.Field))
targets.Add(check);
}
if(DefaultOnBecomeTarget())
{
AI.SelectCard(targets);
return true;
}
int count = 0;
foreach(ClientCard check in Enemy.GetSpells())
{
if (check.Type == 16777218)
count++;
}
if(Util.GetLastChainCard()!=null &&
(Util.GetLastChainCard().HasType(CardType.Continuous)||
Util.GetLastChainCard().HasType(CardType.Field) || count==2) &&
Duel.LastChainPlayer==1)
{
AI.SelectCard(targets);
return true;
}
return false;
}
private bool UnendingNightmareeff()
{
if (Card.IsDisabled()){
return false;
}
ClientCard card = null;
foreach(ClientCard check in Enemy.GetSpells())
{
if (check.HasType(CardType.Continuous) || check.HasType(CardType.Field))
card = check;
break;
}
int count = 0;
foreach (ClientCard check in Enemy.GetSpells())
{
if (check.Type == 16777218)
count++;
}
if(count==2)
{
if (Util.GetPZone(1, 1) != null && Util.GetPZone(1, 1).Type == 16777218)
{
card=Util.GetPZone(1, 1);
}
}
if (card!=null && Bot.LifePoints>1000)
{
AI.SelectCard(card);
return true;
}
return false;
}
private bool DarkBribeeff()
{
if (Util.GetLastChainCard()!=null && Util.GetLastChainCard().IsCode(CardId.UpstartGoblin))
return false;
return true;
}
private bool ImperialOrderfirst()
{
if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.UpstartGoblin))
return false;
return DefaultOnBecomeTarget() && Util.GetLastChainCard().HasType(CardType.Spell);
}
private bool ImperialOrdereff()
{
if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.UpstartGoblin))
return false;
if (Duel.LastChainPlayer == 1)
{
foreach(ClientCard check in Enemy.GetSpells())
{
if (Util.GetLastChainCard() == check)
return true;
}
}
return false;
}
private bool DrowningMirrorForceeff()
{
if(Enemy.GetMonsterCount() ==1)
{
if(Enemy.BattlingMonster.Attack-Bot.LifePoints>=1000)
return DefaultUniqueTrap();
}
if (Util.GetTotalAttackingMonsterAttack(1) >= Bot.LifePoints)
return DefaultUniqueTrap();
if (Enemy.GetMonsterCount() >= 2)
return DefaultUniqueTrap();
return false;
}
private bool UpstartGoblineff()
{
return !DefaultSpellWillBeNegated();
}
private bool PotOfDualityeff()
{
if (DefaultSpellWillBeNegated())
return false;
int count = 0;
if (Bot.GetMonsterCount() > 0)
count = 1;
foreach(ClientCard card in Bot.Hand)
{
if (card.HasType(CardType.Monster))
count++;
}
if(Util.GetBestEnemyMonster()!=null && Util.GetBestEnemyMonster().Attack>=1900)
AI.SelectCard(
CardId.EaterOfMillions,
CardId.PotOfDesires,
CardId.GrenMajuDaEizo,
CardId.InspectBoarder,
CardId.ThunderKingRaiOh,
CardId.Scapegoat,
CardId.SolemnJudgment,
CardId.SolemnWarning,
CardId.SolemStrike,
CardId.InfiniteImpermanence
);
if (count == 0)
AI.SelectCard(
CardId.PotOfDesires,
CardId.InspectBoarder,
CardId.ThunderKingRaiOh,
CardId.EaterOfMillions,
CardId.GrenMajuDaEizo,
CardId.Scapegoat
);
else
{
AI.SelectCard(
CardId.PotOfDesires,
CardId.CardOfDemise,
CardId.SolemnJudgment,
CardId.SolemnWarning,
CardId.SolemStrike,
CardId.InfiniteImpermanence,
CardId.Scapegoat
);
}
return true;
}
private bool PotOfDesireseff()
{
if (CardOfDemiseeff_used) return false;
return Bot.Deck.Count > 14 && !DefaultSpellWillBeNegated();
}
private bool CardOfDemiseeff()
{
if (Bot.Hand.Count == 1 && Bot.GetSpellCountWithoutField() <= 3 && !DefaultSpellWillBeNegated())
{
CardOfDemiseeff_used = true;
return true;
}
return false;
}
private bool Crackdowneff()
{
if (Util.GetOneEnemyBetterThanMyBest(true, true) != null && Bot.UnderAttack)
AI.SelectCard(Util.GetOneEnemyBetterThanMyBest(true, true));
return Util.GetOneEnemyBetterThanMyBest(true, true) != null && Bot.UnderAttack;
}
private bool MoonMirrorShieldeff()
{
if(Card.Location==CardLocation.Hand)
{
if (Bot.GetMonsterCount() == 0) return false;
return !DefaultSpellWillBeNegated();
}
if(Card.Location==CardLocation.Grave)
{
return true;
}
return false;
}
private bool PhatomKnightsSwordeff()
{
if (Card.IsFaceup())
return true;
if(Duel.Phase==DuelPhase.BattleStart && Bot.BattlingMonster!=null && Enemy.BattlingMonster!=null)
{
if (Bot.BattlingMonster.Attack + 800 >= Enemy.BattlingMonster.GetDefensePower())
{
AI.SelectCard(Bot.BattlingMonster);
return DefaultUniqueTrap();
}
}
return false;
}
private bool InspectBoardersummon()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return true;
}
private bool GrenMajuDaEizosummon()
{
if (Duel.Turn == 1) return false;
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return Bot.Banished.Count >= 6;
}
private bool ThunderKingRaiOhsummon()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return true;
}
private bool ThunderKingRaiOheff()
{
if (DefaultOnlyHorusSpSummoning()) return false;
if(Duel.SummoningCards.Count > 0)
{
foreach(ClientCard m in Duel.SummoningCards)
{
if (m.Attack >= 1900)
return true;
}
}
return false;
}
private bool BorreloadDragonsp()
{
if (!(Bot.HasInMonstersZone(CardId.MissusRadiant) || Bot.HasInMonstersZone(new[] { CardId.KnightmareCerberus, CardId.KnightmarePhoenix }))) return false;
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.IsCode(CardId.MissusRadiant, CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LinkSpider, CardId.Linkuriboh))
material_list.Add(monster);
if (material_list.Count == 3) break;
}
if (material_list.Count >= 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
private bool BorreloadDragonspsecond()
{
if (!(Bot.HasInMonstersZone(CardId.MissusRadiant) || Bot.HasInMonstersZone(new[] { CardId.KnightmareCerberus,CardId.KnightmarePhoenix }))) return false;
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.IsCode(CardId.MissusRadiant, CardId.KnightmareCerberus, CardId.KnightmarePhoenix, CardId.LinkSpider, CardId.Linkuriboh))
material_list.Add(monster);
if (material_list.Count == 3) break;
}
if (material_list.Count >= 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
public bool BorreloadDragoneff()
{
if (ActivateDescription == -1 && (Duel.Phase==DuelPhase.BattleStart||Duel.Phase==DuelPhase.End))
{
ClientCard enemy_monster = Enemy.BattlingMonster;
if (enemy_monster != null && enemy_monster.HasPosition(CardPosition.Attack))
{
return (Card.Attack - enemy_monster.Attack < Enemy.LifePoints);
}
return true;
};
ClientCard BestEnemy = Util.GetBestEnemyMonster(true);
ClientCard WorstBot = Bot.GetMonsters().GetLowestAttackMonster();
if (BestEnemy == null || BestEnemy.HasPosition(CardPosition.FaceDown)) return false;
if (WorstBot == null || WorstBot.HasPosition(CardPosition.FaceDown)) return false;
if (BestEnemy.Attack >= WorstBot.RealPower)
{
AI.SelectCard(BestEnemy);
return true;
}
return false;
}
private bool EaterOfMillionssp()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
if (Enemy.HasInMonstersZone(CardId.KnightmareGryphon, true)) return false;
if (Bot.HasInMonstersZone(CardId.InspectBoarder) && !eater_eff) return false;
if (Util.GetProblematicEnemyMonster() == null && Bot.ExtraDeck.Count < 5) return false;
if (Bot.GetMonstersInMainZone().Count >= 5) return false;
if (Util.IsTurn1OrMain2()) return false;
AI.SelectPosition(CardPosition.FaceUpAttack);
IList<ClientCard> targets = new List<ClientCard>();
foreach (ClientCard e_c in Bot.ExtraDeck)
{
targets.Add(e_c);
if (targets.Count >= 5)
{
AI.SelectMaterials(targets, HintMsg.Remove);
/*AI.SelectCard(new[] {
CardId.BingirsuTheWorldChaliceWarrior,
CardId.TopologicTrisbaena,
CardId.KnightmareCerberus,
CardId.KnightmarePhoenix,
CardId.KnightmareUnicorn,
CardId.BrandishMaidenKagari,
CardId.HeavymetalfoesElectrumite,
CardId.CrystronNeedlefiber,
CardId.FirewallDragon,
CardId.BirrelswordDragon,
CardId.RaidraptorUltimateFalcon,
});*/
AI.SelectPlace(Zones.z4 | Zones.z0);
return true;
}
}
Logger.DebugWriteLine("*** Eater use up the extra deck.");
foreach (ClientCard s_c in Bot.GetSpells())
{
targets.Add(s_c);
if (targets.Count >= 5)
{
AI.SelectMaterials(targets, HintMsg.Remove);
return true;
}
}
return false;
}
private bool EaterOfMillionseff()
{
if (Enemy.BattlingMonster.HasPosition(CardPosition.Attack) && (Bot.BattlingMonster.Attack - Enemy.BattlingMonster.GetDefensePower() >= Enemy.LifePoints)) return false;
return true;
}
private bool WakingTheDragoneff()
{
AI.SelectCard(new[] { CardId.RaidraptorUltimateFalcon });
return true;
}
private bool MetalSnakesp()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (ActivateDescription == Util.GetStringId(CardId.MetalSnake, 0) && !Bot.HasInMonstersZone(CardId.MetalSnake))
{
if(Duel.Player == 1 && Duel.Phase >= DuelPhase.BattleStart )
return Bot.Deck.Count >= 12;
if(Duel.Player == 0 && Duel.Phase >= DuelPhase.Main1)
return Bot.Deck.Count >= 12;
}
return false;
}
private bool MetalSnakeeff()
{
ClientCard target = Util.GetOneEnemyBetterThanMyBest(true, true);
if (ActivateDescription == Util.GetStringId(CardId.MetalSnake, 1) && target != null)
{
AI.SelectCard(new[]
{
CardId.HeavymetalfoesElectrumite,
CardId.BrandishMaidenKagari,
CardId.CrystronNeedlefiber,
CardId.RaidraptorUltimateFalcon,
CardId.NingirsuTheWorldChaliceWarrior
});
AI.SelectNextCard(target);
return true;
}
return false;
}
private bool MissusRadiantsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Earth) && monster.Level==1 && !monster.IsCode(CardId.EaterOfMillions))
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.MissusRadiant)) return false;
AI.SelectMaterials(material_list);
if (Bot.MonsterZone[0] == null && Bot.MonsterZone[2] == null && Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool MissusRadianteff()
{
AI.SelectCard(CardId.MaxxC, CardId.MissusRadiant);
return true;
}
private bool Linkuribohsp()
{
foreach (ClientCard c in Bot.GetMonsters())
{
if (!c.IsCode(CardId.EaterOfMillions, CardId.Linkuriboh) && c.Level==1)
{
AI.SelectMaterials(c);
return true;
}
}
return false;
}
private bool Knightmaresp()
{
int[] firstMats = new[] {
CardId.KnightmareCerberus,
CardId.KnightmarePhoenix
};
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(firstMats)) >= 1)return false;
foreach (ClientCard c in Bot.GetMonsters())
{
if (!c.IsCode(CardId.EaterOfMillions) && c.Level == 1)
{
AI.SelectMaterials(c);
return true;
}
}
return false;
}
private bool Linkuriboheff()
{
if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.Linkuriboh)) return false;
return true;
}
private bool MonsterRepos()
{
if (Card.IsCode(CardId.EaterOfMillions) && Card.IsAttack()) return false;
return DefaultMonsterRepos();
}
private bool SpellSet()
{
int count = 0;
foreach(ClientCard check in Bot.Hand)
{
if (check.IsCode(CardId.CardOfDemise))
count++;
}
if (count == 2 && Bot.Hand.Count == 2 && Bot.GetSpellCountWithoutField() <= 2)
return true;
if (Card.IsCode(CardId.MacroCosmos) && Bot.HasInSpellZone(CardId.MacroCosmos)) return false;
if (Card.IsCode(CardId.AntiSpellFragrance) && Bot.HasInSpellZone(CardId.AntiSpellFragrance)) return false;
if (CardOfDemiseeff_used)return true;
if (Card.IsCode(CardId.EvenlyMatched) && (Enemy.GetFieldCount() - Bot.GetFieldCount()) < 0) return false;
if (Card.IsCode(CardId.AntiSpellFragrance) && Bot.HasInSpellZone(CardId.AntiSpellFragrance)) return false;
if (Card.IsCode(CardId.MacroCosmos) && Bot.HasInSpellZone(CardId.MacroCosmos)) return false;
if (Duel.Turn > 1 && Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster())
return false;
if (Card.IsCode(CardId.InfiniteImpermanence))
return Bot.GetFieldCount() > 0 && Bot.GetSpellCountWithoutField() < 4;
if (Card.IsCode(CardId.Scapegoat))
return true;
if (Card.HasType(CardType.Trap))
return Bot.GetSpellCountWithoutField() < 4;
if(Bot.HasInSpellZone(CardId.AntiSpellFragrance,true))
{
if (Card.IsCode(CardId.UpstartGoblin, CardId.PotOfDesires, CardId.PotOfDuality)) return true;
if (Card.IsCode(CardId.CardOfDemise) && Bot.HasInSpellZone(CardId.CardOfDemise)) return false;
if (Card.HasType(CardType.Spell))
return Bot.GetSpellCountWithoutField() < 4;
}
return false;
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (attacker.IsCode(_CardId.EaterOfMillions) && (Bot.HasInMonstersZone(CardId.InspectBoarder) && eater_eff) && !attacker.IsDisabled())
{
attacker.RealPower = 9999;
return true;
}
if (attacker.IsCode(_CardId.EaterOfMillions) && !Bot.HasInMonstersZone(CardId.InspectBoarder) && !attacker.IsDisabled())
{
attacker.RealPower = 9999;
return true;
}
return base.OnPreBattleBetween(attacker, defender);
}
public override ClientCard OnSelectAttacker(IList<ClientCard> attackers, IList<ClientCard> defenders)
{
for (int i = 0; i < attackers.Count; ++i)
{
ClientCard attacker = attackers[i];
if (attacker.IsCode(CardId.BirrelswordDragon, CardId.EaterOfMillions)) return attacker;
}
return null;
}
public override bool OnSelectHand()
{
return true;
}
}
}
@@ -0,0 +1,216 @@
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game.AI.Decks
{
[Deck("Horus", "AI_Horus", "Easy")]
public class HorusExecutor : DefaultExecutor
{
public class CardId
{
public const int AlexandriteDragon = 43096270;
public const int LusterDragon = 11091375;
public const int WhiteNightDragon = 79473793;
public const int HorusTheBlackFlameDragonLv8 = 48229808;
public const int HorusTheBlackFlameDragonLv6 = 11224103;
public const int CyberDragon = 70095154;
public const int AxeDragonute = 84914462;
public const int DodgerDragon = 47013502;
public const int GolemDragon = 9666558;
public const int Raigeki = 12580477;
public const int HammerShot = 26412047;
public const int DarkHole = 53129443;
public const int Fissure = 66788016;
public const int StampingDestruction = 81385346;
public const int FoolishBurial = 81439173;
public const int MonsterReborn = 83764718;
public const int MysticalSpaceTyphoon = 5318639;
public const int BellowOfTheSilverDragon = 80600103;
public const int Mountain = 50913601;
public const int DragonsRebirth = 20638610;
public const int MirrorForce = 44095762;
public const int DimensionalPrison = 70342110;
}
public HorusExecutor(GameAI ai, Duel duel) : base(ai, duel)
{
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Activate, CardId.HorusTheBlackFlameDragonLv6);
AddExecutor(ExecutorType.Activate, CardId.StampingDestruction, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurial);
AddExecutor(ExecutorType.Activate, CardId.Mountain, DefaultField);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.SpSummon, CardId.CyberDragon);
AddExecutor(ExecutorType.Activate, CardId.Raigeki, DefaultRaigeki);
AddExecutor(ExecutorType.Activate, CardId.HammerShot, DefaultHammerShot);
AddExecutor(ExecutorType.Activate, CardId.Fissure);
AddExecutor(ExecutorType.Activate, CardId.BellowOfTheSilverDragon, BellowOfTheSilverDragon);
AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, MonsterReborn);
AddExecutor(ExecutorType.Summon, CardId.WhiteNightDragon, WhiteNightDragon);
AddExecutor(ExecutorType.Summon, CardId.HorusTheBlackFlameDragonLv6, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.AlexandriteDragon);
AddExecutor(ExecutorType.SummonOrSet, CardId.AxeDragonute);
AddExecutor(ExecutorType.SummonOrSet, CardId.DodgerDragon);
AddExecutor(ExecutorType.MonsterSet, CardId.GolemDragon);
AddExecutor(ExecutorType.SummonOrSet, CardId.LusterDragon);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.Activate, CardId.HorusTheBlackFlameDragonLv8, HorusTheBlackFlameDragonLv8);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.DimensionalPrison, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.DragonsRebirth, DragonsRebirth);
}
private bool FoolishBurial()
{
if (Bot.HasInGraveyard(CardId.WhiteNightDragon))
return false;
if (Bot.HasInHand(CardId.WhiteNightDragon))
return false;
int remaining = 2;
foreach (ClientCard card in Bot.Banished)
if (card.IsCode(CardId.WhiteNightDragon))
remaining--;
if (remaining > 0)
{
AI.SelectCard(CardId.WhiteNightDragon);
return true;
}
return false;
}
private bool BellowOfTheSilverDragon()
{
if (Duel.Player == 0 && (Duel.Phase == DuelPhase.Draw || Duel.Phase == DuelPhase.Standby))
return false;
if (Duel.Player == 1 && Duel.Phase == DuelPhase.End)
return false;
List<ClientCard> cards = new List<ClientCard>(Bot.Graveyard);
cards.Sort(CardContainer.CompareCardAttack);
for (int i = cards.Count - 1; i >= 0; --i)
{
ClientCard card = cards[i];
if (card.Attack < 1000)
return false;
if (card.IsMonster() && card.HasType(CardType.Normal))
{
AI.SelectCard(card);
return true;
}
}
return false;
}
private bool MonsterReborn()
{
List<ClientCard> cards = new List<ClientCard>(Bot.Graveyard.GetMatchingCards(card => card.IsCanRevive()));
cards.Sort(CardContainer.CompareCardAttack);
ClientCard selectedCard = null;
for (int i = cards.Count - 1; i >= 0; --i)
{
ClientCard card = cards[i];
if (card.Attack < 1000)
break;
if (card.IsMonster())
{
selectedCard = card;
break;
}
}
cards = new List<ClientCard>(Enemy.Graveyard.GetMatchingCards(card => card.IsCanRevive()));
cards.Sort(CardContainer.CompareCardAttack);
for (int i = cards.Count - 1; i >= 0; --i)
{
ClientCard card = cards[i];
if (card.Attack < 1000)
break;
if (card.IsMonster() && card.HasType(CardType.Normal) && (selectedCard == null || card.Attack > selectedCard.Attack))
{
selectedCard = card;
break;
}
}
if (selectedCard != null)
{
AI.SelectCard(selectedCard);
return true;
}
return false;
}
private bool WhiteNightDragon()
{
// We should summon Horus the Black Flame Dragon LV6 if he can lvlup.
if (Enemy.GetMonsterCount() != 0 && !Util.IsAllEnemyBetterThanValue(2300 - 1, false))
foreach (ClientCard card in Duel.MainPhase.SummonableCards)
if (card.IsCode(11224103))
return false;
return DefaultMonsterSummon();
}
private bool HorusTheBlackFlameDragonLv8()
{
return Duel.LastChainPlayer == 1;
}
private bool DragonsRebirth()
{
List<ClientCard> cards = new List<ClientCard>(Bot.GetMonsters());
if (cards.Count == 0)
return false;
cards.Sort(CardContainer.CompareCardAttack);
ClientCard tributeCard = null;
foreach (ClientCard monster in cards)
{
if (monster.Attack > 2000)
return false;
if (!monster.IsFacedown() && monster.Race == (int)CardRace.Dragon)
{
tributeCard = monster;
break;
}
}
if (tributeCard == null)
return false;
cards = new List<ClientCard>(Bot.Hand);
cards.AddRange(Bot.Graveyard);
if (cards.Count == 0)
return false;
cards.Sort(CardContainer.CompareCardAttack);
ClientCard summonCard = null;
for (int i = cards.Count - 1; i >= 0; --i)
{
ClientCard monster = cards[i];
if (monster.Attack < 2300)
return false;
if (monster.Race == (int)CardRace.Dragon && !monster.IsCode(CardId.HorusTheBlackFlameDragonLv8))
{
summonCard = monster;
break;
}
}
if (summonCard == null)
return false;
AI.SelectCard(tributeCard);
AI.SelectNextCard(summonCard);
return true;
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,877 @@
using System;
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using System.Linq;
namespace WindBot.Game.AI.Decks
{
[Deck("Level VIII", "AI_Level8")]
class Level8Executor : DefaultExecutor
{
public class CardId
{
public const int AngelTrumpeter = 87979586;
public const int ScrapGolem = 82012319;
public const int PhotonThrasher = 65367484;
public const int WorldCarrotweightChampion = 44928016;
public const int RaidenHandofTheLightsworn = 77558536;
public const int ScrapBeast = 19139516;
public const int PerformageTrickClown = 67696066;
public const int MaskedChameleon = 53573406;
public const int Goblindbergh = 25259669;
public const int WhiteRoseDragon = 12213463;
public const int RedRoseDragon = 26118970;
public const int ScrapRecycler = 4334811;
public const int MechaPhantomBeastOLion = 72291078;
public const int MechaPhantomBeastOLionToken = 72291079;
public const int JetSynchron = 9742784;
public const int UnexpectedDai = 911883;
public const int Raigeki = 12580477;
public const int HarpiesFeatherDuster = 18144506;
public const int ReinforcementofTheArmy = 32807846;
public const int FoolishBurial = 81439173;
public const int MonsterReborn = 83764718;
public const int ChargeofTheLightBrigade = 94886282;
public const int CalledbyTheGrave = 24224830;
public const int SolemnStrike = 40605147;
public const int WhiteAuraBihamut = 89907227;
public const int BorreloadSavageDragon = 27548199;
public const int CrystalWingSynchroDragon = 50954680;
public const int ScarlightRedDragonArchfiend = 80666118;
public const int PSYFramelordOmega = 74586817;
public const int ScrapDragon = 76774528;
public const int BlackRoseMoonlightDragon = 33698022;
public const int ShootingRiserDragon = 68431965;
public const int CoralDragon = 42566602;
public const int GardenRoseMaiden = 53325667;
public const int Number41BagooskaTheTerriblyTiredTapir = 90590303;
public const int MekkKnightCrusadiaAstram = 21887175;
public const int ScrapWyvern = 47363932;
public const int CrystronNeedlefiber = 50588353;
}
public Level8Executor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.CalledbyTheGrave, DefaultCalledByTheGrave);
AddExecutor(ExecutorType.Activate, CardId.Raigeki);
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster);
AddExecutor(ExecutorType.Repos, CardId.Number41BagooskaTheTerriblyTiredTapir, MonsterRepos);
AddExecutor(ExecutorType.Activate, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.BorreloadSavageDragon, BorreloadSavageDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.ScrapGolem, ScrapGolemEffect);
// empty field
AddExecutor(ExecutorType.Activate, CardId.UnexpectedDai, UnexpectedDaiFirst);
AddExecutor(ExecutorType.SpSummon, CardId.PhotonThrasher, PhotonThrasherSummonFirst);
AddExecutor(ExecutorType.Activate, CardId.UnexpectedDai);
AddExecutor(ExecutorType.SpSummon, CardId.PhotonThrasher);
//
AddExecutor(ExecutorType.Activate, CardId.ReinforcementofTheArmy, ReinforcementofTheArmyEffect);
AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialEffect);
AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, DefaultCallOfTheHaunted);
// scrap combo
AddExecutor(ExecutorType.Summon, CardId.ScrapRecycler, ScrapRecyclerSummonFirst);
AddExecutor(ExecutorType.Activate, CardId.ScrapRecycler, ScrapRecyclerEffect);
AddExecutor(ExecutorType.Activate, CardId.MechaPhantomBeastOLion, MechaPhantomBeastOLionEffect);
AddExecutor(ExecutorType.SpSummon, CardId.ScrapWyvern, ScrapWyvernSummon);
AddExecutor(ExecutorType.Activate, CardId.ScrapWyvern, ScrapWyvernEffect);
AddExecutor(ExecutorType.Activate, CardId.JetSynchron, JetSynchronEffect);
AddExecutor(ExecutorType.SpSummon, CardId.CrystronNeedlefiber, CrystronNeedlefiberSummon);
AddExecutor(ExecutorType.Activate, CardId.CrystronNeedlefiber, CrystronNeedlefiberEffect);
AddExecutor(ExecutorType.SpSummon, CardId.MekkKnightCrusadiaAstram, MekkKnightCrusadiaAstramSummon);
AddExecutor(ExecutorType.Activate, CardId.MekkKnightCrusadiaAstram, MekkKnightCrusadiaAstramEffect);
//
AddExecutor(ExecutorType.Activate, CardId.ChargeofTheLightBrigade);
// other summon
AddExecutor(ExecutorType.Summon, CardId.Goblindbergh, GoblindberghSummonFirst);
AddExecutor(ExecutorType.Activate, CardId.Goblindbergh, GoblindberghEffect);
AddExecutor(ExecutorType.Summon, CardId.MaskedChameleon, MaskedChameleonSummonFirst);
AddExecutor(ExecutorType.Activate, CardId.MaskedChameleon, MaskedChameleonEffect);
AddExecutor(ExecutorType.SpSummon, CardId.WhiteRoseDragon);
AddExecutor(ExecutorType.Summon, CardId.WhiteRoseDragon, WhiteRoseDragonSummonFirst);
AddExecutor(ExecutorType.Activate, CardId.WhiteRoseDragon, WhiteRoseDragonEffect);
//
AddExecutor(ExecutorType.Summon, CardId.RaidenHandofTheLightsworn, L4TunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.ScrapBeast, L4TunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.AngelTrumpeter, L4TunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.MaskedChameleon, L4TunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.PerformageTrickClown, L4NonTunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.Goblindbergh, L4NonTunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.WorldCarrotweightChampion, L4NonTunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.WhiteRoseDragon, L4NonTunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.RedRoseDragon, OtherTunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.JetSynchron, OtherTunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.MechaPhantomBeastOLion, OtherTunerSummonFirst);
AddExecutor(ExecutorType.Summon, CardId.RaidenHandofTheLightsworn);
AddExecutor(ExecutorType.Summon, CardId.Goblindbergh);
AddExecutor(ExecutorType.Summon, CardId.ScrapBeast);
AddExecutor(ExecutorType.Summon, CardId.PerformageTrickClown);
AddExecutor(ExecutorType.Summon, CardId.AngelTrumpeter);
AddExecutor(ExecutorType.Summon, CardId.WorldCarrotweightChampion);
AddExecutor(ExecutorType.Summon, CardId.MaskedChameleon);
AddExecutor(ExecutorType.Summon, CardId.WhiteRoseDragon);
AddExecutor(ExecutorType.Summon, CardId.RedRoseDragon);
AddExecutor(ExecutorType.Summon, CardId.JetSynchron);
AddExecutor(ExecutorType.Summon, CardId.MechaPhantomBeastOLion);
AddExecutor(ExecutorType.Summon, CardId.ScrapRecycler);
AddExecutor(ExecutorType.Activate, CardId.RedRoseDragon);
AddExecutor(ExecutorType.Activate, CardId.RaidenHandofTheLightsworn);
AddExecutor(ExecutorType.Activate, CardId.PerformageTrickClown, PerformageTrickClownEffect);
AddExecutor(ExecutorType.Activate, CardId.WorldCarrotweightChampion, WorldCarrotweightChampionEffect);
// extra monsters
AddExecutor(ExecutorType.SpSummon, CardId.BorreloadSavageDragon, BorreloadSavageDragonSummon);
AddExecutor(ExecutorType.SpSummon, CardId.ScrapDragon, ScrapDragonSummon);
AddExecutor(ExecutorType.Activate, CardId.ScrapDragon, ScrapDragonEffect);
AddExecutor(ExecutorType.SpSummon, CardId.CrystalWingSynchroDragon);
AddExecutor(ExecutorType.SpSummon, CardId.ScarlightRedDragonArchfiend, DefaultScarlightRedDragonArchfiendSummon);
AddExecutor(ExecutorType.Activate, CardId.ScarlightRedDragonArchfiend, DefaultScarlightRedDragonArchfiendEffect);
AddExecutor(ExecutorType.SpSummon, CardId.PSYFramelordOmega);
AddExecutor(ExecutorType.Activate, CardId.PSYFramelordOmega, PSYFramelordOmegaEffect);
AddExecutor(ExecutorType.SpSummon, CardId.WhiteAuraBihamut);
AddExecutor(ExecutorType.Activate, CardId.WhiteAuraBihamut);
AddExecutor(ExecutorType.SpSummon, CardId.GardenRoseMaiden);
AddExecutor(ExecutorType.Activate, CardId.GardenRoseMaiden);
AddExecutor(ExecutorType.SpSummon, CardId.CoralDragon);
AddExecutor(ExecutorType.Activate, CardId.CoralDragon, CoralDragonEffect);
AddExecutor(ExecutorType.SpSummon, CardId.ShootingRiserDragon, ShootingRiserDragonSummon);
AddExecutor(ExecutorType.Activate, CardId.ShootingRiserDragon, ShootingRiserDragonEffect);
AddExecutor(ExecutorType.SpSummon, CardId.BlackRoseMoonlightDragon);
AddExecutor(ExecutorType.SpSummon, CardId.Number41BagooskaTheTerriblyTiredTapir, Number41BagooskaTheTerriblyTiredTapirSummon);
AddExecutor(ExecutorType.Summon, CardId.ScrapGolem, ScrapGolemSummon);
AddExecutor(ExecutorType.SpellSet, CardId.CalledbyTheGrave);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike);
AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Repos, MonsterRepos);
}
private bool BeastOLionUsed = false;
private bool JetSynchronUsed = false;
private bool ScrapWyvernUsed = false;
private bool MaskedChameleonUsed = false;
private int[] HandCosts = new[]
{
CardId.PerformageTrickClown,
CardId.JetSynchron,
CardId.MechaPhantomBeastOLion,
CardId.ScrapGolem,
CardId.WorldCarrotweightChampion
};
private int[] L4NonTuners = new[]
{
CardId.PhotonThrasher,
CardId.WorldCarrotweightChampion,
CardId.PerformageTrickClown,
CardId.Goblindbergh,
CardId.WhiteRoseDragon
};
private int[] L4Tuners = new[]
{
CardId.RaidenHandofTheLightsworn,
CardId.ScrapBeast,
CardId.AngelTrumpeter,
CardId.MaskedChameleon
};
public override void OnNewTurn()
{
BeastOLionUsed = false;
JetSynchronUsed = false;
ScrapWyvernUsed = false;
MaskedChameleonUsed = false;
base.OnNewTurn();
}
public override void OnChainEnd()
{
base.OnChainEnd();
}
public override CardPosition OnSelectPosition(int cardId, IList<CardPosition> positions)
{
YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId);
if (cardData != null)
{
if (cardData.Attack <= 1000)
return CardPosition.FaceUpDefence;
}
return 0;
}
public override int OnSelectPlace(int cardId, int player, CardLocation location, int available)
{
if (location == CardLocation.SpellZone)
{
if (cardId == CardId.MekkKnightCrusadiaAstram || cardId == CardId.ScrapWyvern || cardId == CardId.CrystronNeedlefiber)
{
ClientCard b = Bot.MonsterZone.GetFirstMatchingCard(card => card.Id == CardId.BorreloadSavageDragon);
int zone = (1 << (b?.Sequence ?? 0)) & available;
if (zone > 0)
return zone;
}
if ((available & Zones.z4) > 0)
return Zones.z4;
if ((available & Zones.z3) > 0)
return Zones.z3;
if ((available & Zones.z2) > 0)
return Zones.z2;
if ((available & Zones.z1) > 0)
return Zones.z1;
if ((available & Zones.z0) > 0)
return Zones.z0;
}
if (location == CardLocation.MonsterZone)
{
if ((available & Zones.z6) > 0)
return Zones.z6;
if ((available & Zones.z5) > 0)
return Zones.z5;
if ((available & Zones.z0) > 0)
return Zones.z0;
if ((available & Zones.z2) > 0)
return Zones.z2;
if ((available & Zones.z4) > 0)
return Zones.z4;
if ((available & Zones.z1) > 0)
return Zones.z1;
if ((available & Zones.z3) > 0)
return Zones.z3;
}
return 0;
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (!defender.IsMonsterHasPreventActivationEffectInBattle())
{
if (!attacker.IsDisabled() && (attacker.IsCode(CardId.MekkKnightCrusadiaAstram) && defender.IsSpecialSummoned
|| attacker.IsCode(CardId.CrystalWingSynchroDragon) && defender.Level>=5))
{
attacker.RealPower = attacker.RealPower + defender.Attack;
}
}
return base.OnPreBattleBetween(attacker, defender);
}
private bool UnexpectedDaiFirst()
{
if (Bot.HasInHand(CardId.ScrapRecycler))
return true;
if (Bot.HasInHand(new[] {
CardId.WorldCarrotweightChampion,
CardId.PerformageTrickClown,
CardId.Goblindbergh,
CardId.WhiteRoseDragon
}))
return true;
return false;
}
private bool PhotonThrasherSummonFirst()
{
if (Bot.HasInHand(CardId.ScrapRecycler))
return true;
if (Bot.HasInHand(L4Tuners))
return true;
return false;
}
private bool ReinforcementofTheArmyEffect()
{
if (Bot.GetMonsterCount() == 0 && PhotonThrasherSummonFirst() && !Bot.HasInHand(CardId.PhotonThrasher))
{
AI.SelectCard(CardId.PhotonThrasher);
return true;
}
if (GoblindberghSummonFirst() && !Bot.HasInHand(CardId.Goblindbergh))
{
AI.SelectCard(CardId.Goblindbergh);
return true;
}
AI.SelectCard(new[] {
CardId.Goblindbergh,
CardId.RaidenHandofTheLightsworn,
CardId.PhotonThrasher
});
return true;
}
private bool FoolishBurialEffect()
{
if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.ScrapRecycler))
{
AI.SelectCard(CardId.ScrapRecycler);
return true;
}
if (L4NonTunerSummonFirst() && Bot.GetRemainingCount(CardId.PerformageTrickClown, 1) > 0)
{
AI.SelectCard(CardId.PerformageTrickClown);
return true;
}
AI.SelectCard(new[] {
CardId.JetSynchron,
CardId.MechaPhantomBeastOLion,
CardId.ScrapBeast,
CardId.PhotonThrasher
});
return true;
}
private bool ScrapRecyclerSummonFirst()
{
return Bot.GetRemainingCount(CardId.ScrapGolem, 2) > 0 && Bot.GetRemainingCount(CardId.MechaPhantomBeastOLion, 2) > 0 && Bot.GetRemainingCount(CardId.JetSynchron, 2) > 0;
}
private bool ScrapRecyclerEffect()
{
if ((Bot.HasInMonstersZone(CardId.ScrapGolem) && !JetSynchronUsed) || BeastOLionUsed)
{
AI.SelectCard(new[] { CardId.JetSynchron, CardId.MechaPhantomBeastOLion });
}
else
{
AI.SelectCard(new[] { CardId.MechaPhantomBeastOLion, CardId.JetSynchron });
}
return true;
}
private bool MechaPhantomBeastOLionEffect()
{
if (ActivateDescription == -1)
{
BeastOLionUsed = true;
return true;
}
// todo: need tuner check
return !BeastOLionUsed;
}
private bool ScrapWyvernSummon()
{
if (ScrapWyvernUsed || MaskedChameleonUsed || Bot.HasInMonstersZone(CardId.ScrapWyvern))
return false;
if (!Bot.HasInMonstersZone(new[] {
CardId.ScrapBeast,
CardId.ScrapGolem,
CardId.ScrapRecycler,
}) || !Bot.HasInMonstersZoneOrInGraveyard(CardId.ScrapRecycler))
return false;
AI.SelectMaterials(new[] {
CardId.MechaPhantomBeastOLionToken,
CardId.PhotonThrasher,
CardId.Goblindbergh,
CardId.AngelTrumpeter,
CardId.PerformageTrickClown,
CardId.WorldCarrotweightChampion,
CardId.WhiteRoseDragon,
CardId.ScrapBeast,
CardId.ScrapGolem,
CardId.ScrapRecycler
});
return true;
}
private bool ScrapWyvernEffect()
{
if(ActivateDescription != -1)
{
int[] targets = new[]
{
CardId.ScrapRecycler,
CardId.ScrapBeast,
CardId.ScrapGolem,
CardId.ScrapDragon
};
AI.SelectCard(targets);
AI.SelectNextCard(targets);
ScrapWyvernUsed = true;
return true;
}
else
{
AI.SelectCard(new[]
{
CardId.ScrapGolem,
CardId.ScrapBeast
});
ClientCard target = Util.GetBestEnemyCard();
if (target != null)
AI.SelectNextCard(target);
else
AI.SelectNextCard(new[]
{
CardId.CalledbyTheGrave,
CardId.PhotonThrasher,
CardId.PerformageTrickClown,
CardId.MechaPhantomBeastOLionToken,
CardId.WorldCarrotweightChampion,
CardId.WhiteRoseDragon,
CardId.Goblindbergh,
CardId.AngelTrumpeter,
CardId.ScrapWyvern
});
return true;
}
}
private bool ScrapGolemEffect()
{
if (Bot.GetMonstersInMainZone().Count == 5)
return false;
AI.SelectCard(CardId.ScrapRecycler);
AI.SelectOption(0);
return true;
}
private bool JetSynchronEffect()
{
if (!Bot.HasInMonstersZone(CardId.BlackRoseMoonlightDragon)
&& Bot.MonsterZone.GetMatchingCardsCount(card => card.IsFaceup() && card.Level >= 2 && card.Level <= 5) < 2)
return false;
AI.SelectCard(HandCosts);
return true;
}
private bool CrystronNeedlefiberSummon()
{
if (MaskedChameleonUsed)
return false;
int nonTunerCount = Bot.MonsterZone.GetMatchingCardsCount(card => card.IsFaceup() && !card.IsTuner());
if (Bot.GetMonsterCount() < 3 || nonTunerCount == 0)
return false;
if (nonTunerCount == 1)
{
AI.SelectMaterials(new[] {
CardId.JetSynchron,
CardId.MechaPhantomBeastOLion,
CardId.AngelTrumpeter,
CardId.RaidenHandofTheLightsworn,
CardId.ScrapBeast,
CardId.MaskedChameleon,
CardId.PerformageTrickClown,
CardId.MechaPhantomBeastOLionToken,
CardId.ScrapRecycler,
CardId.WhiteRoseDragon,
CardId.PhotonThrasher,
CardId.Goblindbergh,
CardId.WorldCarrotweightChampion
});
}
else
{
AI.SelectMaterials(new[] {
CardId.MechaPhantomBeastOLionToken,
CardId.ScrapRecycler,
CardId.WhiteRoseDragon,
CardId.PhotonThrasher,
CardId.Goblindbergh,
CardId.WorldCarrotweightChampion,
CardId.PerformageTrickClown,
CardId.JetSynchron,
CardId.MechaPhantomBeastOLion,
CardId.AngelTrumpeter,
CardId.RaidenHandofTheLightsworn,
CardId.ScrapBeast,
CardId.MaskedChameleon
});
}
return true;
}
private bool CrystronNeedlefiberEffect()
{
if (Duel.Player == 0)
{
AI.SelectCard(CardId.RedRoseDragon);
return true;
}
else
{
if (Bot.HasInExtra(CardId.ShootingRiserDragon) && Bot.MonsterZone.IsExistingMatchingCard(card => card.Level >= 3 && card.Level <= 5 && card.IsFaceup() && !card.IsTuner()))
{
AI.SelectCard(CardId.ShootingRiserDragon);
return true;
}
if (Util.IsOneEnemyBetterThanValue(1500, true) || DefaultOnBecomeTarget())
{
AI.SelectCard(CardId.CoralDragon);
return true;
}
return false;
}
}
private bool MekkKnightCrusadiaAstramSummon()
{
int[] matcodes = new[] {
CardId.ScrapWyvern,
CardId.CrystronNeedlefiber
};
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(matcodes)) < 2)
return false;
AI.SelectMaterials(matcodes);
return true;
}
private bool MekkKnightCrusadiaAstramEffect()
{
if (Card.Location == CardLocation.MonsterZone)
{
return true;
}
else
{
ClientCard target = Util.GetBestEnemyCard();
if (target == null)
return false;
AI.SelectCard(target);
return true;
}
}
private bool GoblindberghSummonFirst()
{
if (Bot.HasInHand(L4Tuners))
return true;
return false;
}
private bool GoblindberghEffect()
{
AI.SelectCard(L4Tuners);
return true;
}
private bool MaskedChameleonSummonFirst()
{
if (Bot.HasInGraveyard(new[] {
CardId.PhotonThrasher,
CardId.WorldCarrotweightChampion,
CardId.Goblindbergh
}))
return true;
return false;
}
private bool MaskedChameleonEffect()
{
if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsFaceup() && !card.IsTuner()) == 0)
{
MaskedChameleonUsed = true;
AI.SelectCard(L4NonTuners);
return true;
}
return false;
}
private bool WhiteRoseDragonSummonFirst()
{
if (Bot.HasInGraveyard(new[] {
CardId.RedRoseDragon
}))
return true;
return false;
}
private bool WhiteRoseDragonEffect()
{
if (Card.Location == CardLocation.Grave)
{
if (Bot.GetRemainingCount(CardId.WorldCarrotweightChampion, 1) > 0)
{
AI.SelectCard(CardId.WorldCarrotweightChampion);
return true;
}
return false;
}
return true;
}
private bool L4TunerSummonFirst()
{
return Bot.HasInMonstersZone(L4NonTuners, faceUp: true);
}
private bool L4NonTunerSummonFirst()
{
return Bot.HasInMonstersZone(L4Tuners, faceUp: true);
}
private bool OtherTunerSummonFirst()
{
return Bot.HasInMonstersZone(L4NonTuners, faceUp: true);
}
private bool PerformageTrickClownEffect()
{
if (Bot.LifePoints <= 1000)
return false;
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool WorldCarrotweightChampionEffect()
{
return !Bot.HasInMonstersZone(L4NonTuners);
}
private bool ScrapGolemSummon()
{
return Bot.GetMonsterCount() <= 2 && Bot.HasInMonstersZoneOrInGraveyard(CardId.ScrapRecycler);
}
private bool BorreloadSavageDragonSummon()
{
if (!Bot.HasInGraveyard(new[] {
CardId.ScrapWyvern,
CardId.CrystronNeedlefiber,
CardId.MekkKnightCrusadiaAstram
}))
return false;
return true;
}
private bool BorreloadSavageDragonEffect()
{
if (ActivateDescription == -1)
{
AI.SelectCard(new[] { CardId.MekkKnightCrusadiaAstram, CardId.CrystronNeedlefiber, CardId.ScrapWyvern });
return true;
}
else
{
return true;
}
}
private bool ScrapDragonSummon()
{
if (Util.GetProblematicEnemyCard(3000) != null)
{
return true;
}
if (Bot.HasInGraveyard(new[] { CardId.ScrapBeast, CardId.ScrapRecycler, CardId.ScrapGolem, CardId.ScrapWyvern }))
{
return true;
}
return false;
}
private bool ScrapDragonEffect()
{
ClientCard invincible = Util.GetProblematicEnemyCard(3000);
if (invincible == null && !Util.IsOneEnemyBetterThanValue(2800 - 1, false))
return false;
List<ClientCard> monsters = Enemy.GetMonsters();
monsters.Sort(CardContainer.CompareCardAttack);
ClientCard destroyCard = invincible;
if (destroyCard == null)
{
for (int i = monsters.Count - 1; i >= 0; --i)
{
if (monsters[i].IsAttack())
{
destroyCard = monsters[i];
break;
}
}
}
if (destroyCard == null)
return false;
AI.SelectCard(new[] {
CardId.CalledbyTheGrave,
CardId.MechaPhantomBeastOLionToken,
CardId.ScrapRecycler,
CardId.WhiteRoseDragon,
CardId.PhotonThrasher,
CardId.Goblindbergh,
CardId.WorldCarrotweightChampion,
CardId.PerformageTrickClown,
CardId.JetSynchron,
CardId.MechaPhantomBeastOLion,
CardId.AngelTrumpeter,
CardId.RaidenHandofTheLightsworn,
CardId.ScrapBeast,
CardId.MaskedChameleon
});
AI.SelectNextCard(destroyCard);
return true;
}
private bool CrystalWingSynchroDragonEffect()
{
return Duel.LastChainPlayer != 0;
}
private bool PSYFramelordOmegaEffect()
{
if (Card.Location == CardLocation.Grave)
{
// todo
return false;
}
if (Duel.Player == 0)
{
return DefaultOnBecomeTarget();
}
if (Duel.Player == 1)
{
if (Duel.Phase == DuelPhase.Standby)
{
if (Bot.HasInBanished(CardId.JetSynchron) && !Bot.HasInGraveyard(CardId.JetSynchron))
{
AI.SelectCard(CardId.JetSynchron);
return true;
}
if (Bot.HasInBanished(CardId.CrystronNeedlefiber))
{
AI.SelectCard(CardId.CrystronNeedlefiber);
return true;
}
}
else
{
if (Enemy.MonsterZone.GetMatchingCards(card => card.IsAttack()).Sum(card => card.Attack) >= Bot.LifePoints)
return false;
return true;// DefaultOnBecomeTarget() || Util.IsOneEnemyBetterThanValue(2800, true);
}
}
return false;
}
private bool CoralDragonEffect()
{
if (Card.Location == CardLocation.Grave)
return true;
ClientCard target = Util.GetProblematicEnemyCard(canBeTarget: true);
if (target != null)
{
AI.SelectCard(HandCosts);
AI.SelectNextCard(target);
return true;
}
return false;
}
private bool ShootingRiserDragonSummon()
{
return Bot.MonsterZone.GetMatchingCardsCount(card => card.IsFaceup() && !card.IsTuner()) >= 2;
}
private bool ShootingRiserDragonEffect()
{
if (ActivateDescription == -1 || (ActivateDescription == Util.GetStringId(CardId.ShootingRiserDragon, 0)))
{
int targetLevel = 8;
if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == targetLevel - 5 && card.IsFaceup() && !card.IsTuner()) && Bot.GetRemainingCount(CardId.MechaPhantomBeastOLion, 2) > 0)
{
AI.SelectCard(CardId.MechaPhantomBeastOLion);
}
else if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == targetLevel - 4 && card.IsFaceup() && !card.IsTuner()))
{
AI.SelectCard(new[] {
CardId.ScrapRecycler,
CardId.RedRoseDragon
});
}
else if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == targetLevel - 3 && card.IsFaceup() && !card.IsTuner()))
{
AI.SelectCard(new[] {
CardId.ScrapBeast,
CardId.PhotonThrasher,
CardId.Goblindbergh,
CardId.WorldCarrotweightChampion,
CardId.WhiteRoseDragon,
CardId.RaidenHandofTheLightsworn,
CardId.AngelTrumpeter,
CardId.PerformageTrickClown,
CardId.MaskedChameleon
});
}
else
{
FoolishBurialEffect();
}
return true;
}
else
{
if (Duel.LastChainPlayer == 0)
return false;
AI.SelectCard(new[] {
CardId.BlackRoseMoonlightDragon,
CardId.ScrapDragon,
CardId.PSYFramelordOmega
});
return true;
}
}
private bool Number41BagooskaTheTerriblyTiredTapirSummon()
{
if (!Util.IsTurn1OrMain2())
return false;
if (Bot.GetMonsterCount() > 3)
return false;
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool MonsterRepos()
{
if (Card.IsFacedown())
return true;
if (Card.IsCode(CardId.Number41BagooskaTheTerriblyTiredTapir) && Card.IsDefense())
return Card.Overlays.Count == 0;
return DefaultMonsterRepos();
}
}
}
@@ -0,0 +1,255 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
// NOT FINISHED YET
[Deck("Lightsworn", "AI_Lightsworn", "NotFinished")]
public class LightswornExecutor : DefaultExecutor
{
public class CardId
{
public const int JudgmentDragon = 57774843;
public const int Wulf = 58996430;
public const int Garoth = 59019082;
public const int Raiden = 77558536;
public const int Lyla = 22624373;
public const int Felis = 73176465;
public const int Lumina = 95503687;
public const int Minerva = 40164421;
public const int Ryko = 21502796;
public const int PerformageTrickClown = 67696066;
public const int Goblindbergh = 25259669;
public const int ThousandBlades = 1833916;
public const int Honest = 37742478;
public const int GlowUpBulb = 67441435;
public const int SolarRecharge = 691925;
public const int GalaxyCyclone = 5133471;
public const int HarpiesFeatherDuster = 18144506;
public const int ReinforcementOfTheArmy = 32807846;
public const int MetalfoesFusion = 73594093;
public const int ChargeOfTheLightBrigade = 94886282;
public const int Michael = 4779823;
public const int MinervaTheExalted = 30100551;
public const int TrishulaDragonOfTheIceBarrier = 52687916;
public const int ScarlightRedDragonArchfiend = 80666118;
public const int PSYFramelordOmega = 74586817;
public const int PSYFramelordZeta = 37192109;
public const int NumberS39UtopiatheLightning = 56832966;
public const int Number39Utopia = 84013237;
public const int CastelTheSkyblasterMusketeer = 82633039;
public const int EvilswarmExcitonKnight = 46772449;
public const int DanteTravelerOfTheBurningAbyss = 83531441;
public const int DecodeTalker = 1861629;
public const int MissusRadiant = 3987233;
}
bool ClownUsed = false;
public LightswornExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, CardId.GalaxyCyclone, DefaultGalaxyCyclone);
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster);
AddExecutor(ExecutorType.Activate, CardId.MetalfoesFusion);
AddExecutor(ExecutorType.Activate, CardId.GlowUpBulb);
AddExecutor(ExecutorType.Activate, CardId.JudgmentDragon, DefaultDarkHole);
AddExecutor(ExecutorType.SpSummon, CardId.JudgmentDragon);
AddExecutor(ExecutorType.Activate, CardId.ReinforcementOfTheArmy, ReinforcementOfTheArmyEffect);
AddExecutor(ExecutorType.Activate, CardId.ChargeOfTheLightBrigade, ChargeOfTheLightBrigadeEffect);
AddExecutor(ExecutorType.Activate, CardId.SolarRecharge, SolarRechargeEffect);
AddExecutor(ExecutorType.Summon, CardId.Goblindbergh, GoblindberghSummon);
AddExecutor(ExecutorType.Activate, CardId.Goblindbergh, GoblindberghEffect);
AddExecutor(ExecutorType.SpSummon, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightSummon);
AddExecutor(ExecutorType.Activate, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect);
AddExecutor(ExecutorType.SpSummon, CardId.CastelTheSkyblasterMusketeer, DefaultCastelTheSkyblasterMusketeerSummon);
AddExecutor(ExecutorType.Activate, CardId.CastelTheSkyblasterMusketeer, DefaultCastelTheSkyblasterMusketeerEffect);
AddExecutor(ExecutorType.SpSummon, CardId.ScarlightRedDragonArchfiend, DefaultScarlightRedDragonArchfiendSummon);
AddExecutor(ExecutorType.Activate, CardId.ScarlightRedDragonArchfiend, DefaultScarlightRedDragonArchfiendEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Number39Utopia, DefaultNumberS39UtopiaTheLightningSummon);
AddExecutor(ExecutorType.SpSummon, CardId.NumberS39UtopiatheLightning);
AddExecutor(ExecutorType.Activate, CardId.NumberS39UtopiatheLightning, DefaultNumberS39UtopiaTheLightningEffect);
AddExecutor(ExecutorType.Activate, CardId.PerformageTrickClown, PerformageTrickClownEffect);
AddExecutor(ExecutorType.Activate, CardId.ThousandBlades);
AddExecutor(ExecutorType.Activate, CardId.Honest, DefaultHonestEffect);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
public override void OnNewTurn()
{
ClownUsed = false;
base.OnNewTurn();
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (!defender.IsMonsterHasPreventActivationEffectInBattle())
{
if (attacker.Attribute == (int)CardAttribute.Light && Bot.HasInHand(CardId.Honest))
attacker.RealPower = attacker.RealPower + defender.Attack;
}
return base.OnPreBattleBetween(attacker, defender);
}
public override IList<ClientCard> OnSelectXyzMaterial(IList<ClientCard> cards, int min, int max)
{
Logger.DebugWriteLine("OnSelectXyzMaterial " + cards.Count + " " + min + " " + max);
IList<ClientCard> result = new List<ClientCard>();
foreach (ClientCard card in cards)
{
if (!result.Contains(card) && (!ClownUsed || !card.IsCode(CardId.PerformageTrickClown)))
result.Add(card);
if (result.Count >= max)
break;
}
return Util.CheckSelectCount(result, cards, min, max);
}
private bool ReinforcementOfTheArmyEffect()
{
if (!Bot.HasInHand(CardId.Raiden))
{
AI.SelectCard(CardId.Raiden);
return true;
}
else if (!Bot.HasInHand(CardId.Goblindbergh))
{
AI.SelectCard(CardId.Goblindbergh);
return true;
}
return false;
}
private bool ChargeOfTheLightBrigadeEffect()
{
if (!Bot.HasInHand(CardId.Lumina))
AI.SelectCard(CardId.Lumina);
else
AI.SelectCard(
CardId.Raiden,
CardId.Lumina,
CardId.Minerva,
CardId.Lyla
);
return true;
}
private bool SolarRechargeEffect()
{
AI.SelectCard(
CardId.Wulf,
CardId.Felis,
CardId.Minerva,
CardId.Lyla,
CardId.Raiden
);
return true;
}
private bool GoblindberghSummon()
{
foreach (ClientCard card in Bot.Hand.GetMonsters())
{
if (!card.Equals(Card) && card.Level == 4)
return true;
}
return false;
}
private bool GoblindberghEffect()
{
AI.SelectCard(
CardId.Felis,
CardId.Wulf,
CardId.Raiden,
CardId.PerformageTrickClown,
CardId.ThousandBlades
);
return true;
}
private bool LuminaEffect()
{
if (!Bot.HasInGraveyard(CardId.Raiden) && Bot.HasInHand(CardId.Raiden))
{
AI.SelectCard(CardId.Raiden);
}
else if (!ClownUsed && Bot.HasInHand(CardId.PerformageTrickClown))
{
AI.SelectCard(CardId.PerformageTrickClown);
}
else
{
AI.SelectCard(
CardId.Wulf,
CardId.Felis,
CardId.Minerva,
CardId.ThousandBlades
);
}
AI.SelectNextCard(CardId.Raiden, CardId.Felis);
return true;
}
private bool PerformageTrickClownEffect()
{
ClownUsed = true;
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool MinervaTheExaltedEffect()
{
if (Card.Location == CardLocation.MonsterZone)
{
return true;
}
else
{
IList<ClientCard> targets = new List<ClientCard>();
ClientCard target1 = Util.GetBestEnemyMonster();
if (target1 != null)
targets.Add(target1);
ClientCard target2 = Util.GetBestEnemySpell();
if (target2 != null)
targets.Add(target2);
foreach (ClientCard target in Enemy.GetMonsters())
{
if (targets.Count >= 3)
break;
if (!targets.Contains(target))
targets.Add(target);
}
foreach (ClientCard target in Enemy.GetSpells())
{
if (targets.Count >= 3)
break;
if (!targets.Contains(target))
targets.Add(target);
}
if (targets.Count == 0)
return false;
AI.SelectNextCard(targets);
return true;
}
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,244 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using System.Linq;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Lucky", "AI_Test", "Test")]
public class LuckyExecutor : DefaultExecutor
{
public LuckyExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, ImFeelingLucky);
AddExecutor(ExecutorType.SpSummon, ImFeelingLucky);
AddExecutor(ExecutorType.SpSummon, ImFeelingUnlucky);
AddExecutor(ExecutorType.Activate, ImFeelingUnlucky);
AddExecutor(ExecutorType.SummonOrSet, ImFeelingLazy);
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.Activate, _CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, _CardId.CosmicCyclone, DefaultCosmicCyclone);
AddExecutor(ExecutorType.Activate, _CardId.GalaxyCyclone, DefaultGalaxyCyclone);
AddExecutor(ExecutorType.Activate, _CardId.BookOfMoon, DefaultBookOfMoon);
AddExecutor(ExecutorType.Activate, _CardId.CompulsoryEvacuationDevice, DefaultCompulsoryEvacuationDevice);
AddExecutor(ExecutorType.Activate, _CardId.CallOfTheHaunted, DefaultCallOfTheHaunted);
AddExecutor(ExecutorType.Activate, _CardId.Scapegoat, DefaultScapegoat);
AddExecutor(ExecutorType.Activate, _CardId.MaxxC, DefaultMaxxC);
AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, _CardId.GhostOgreAndSnowRabbit, DefaultGhostOgreAndSnowRabbit);
AddExecutor(ExecutorType.Activate, _CardId.GhostBelle, DefaultGhostBelleAndHauntedMansion);
AddExecutor(ExecutorType.Activate, _CardId.EffectVeiler, DefaultEffectVeiler);
AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, DefaultCalledByTheGrave);
AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, DefaultInfiniteImpermanence);
AddExecutor(ExecutorType.Activate, _CardId.BreakthroughSkill, DefaultBreakthroughSkill);
AddExecutor(ExecutorType.Activate, _CardId.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, _CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, _CardId.SolemnStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, _CardId.TorrentialTribute, DefaultTorrentialTribute);
AddExecutor(ExecutorType.Activate, _CardId.HeavyStorm, DefaultHeavyStorm);
AddExecutor(ExecutorType.Activate, _CardId.HarpiesFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, _CardId.HammerShot, DefaultHammerShot);
AddExecutor(ExecutorType.Activate, _CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, _CardId.Raigeki, DefaultRaigeki);
AddExecutor(ExecutorType.Activate, _CardId.SmashingGround, DefaultSmashingGround);
AddExecutor(ExecutorType.Activate, _CardId.PotOfDesires, DefaultPotOfDesires);
AddExecutor(ExecutorType.Activate, _CardId.AllureofDarkness, DefaultAllureofDarkness);
AddExecutor(ExecutorType.Activate, _CardId.DimensionalBarrier, DefaultDimensionalBarrier);
AddExecutor(ExecutorType.Activate, _CardId.InterruptedKaijuSlumber, DefaultInterruptedKaijuSlumber);
AddExecutor(ExecutorType.SpSummon, _CardId.JizukirutheStarDestroyingKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, _CardId.GadarlatheMysteryDustKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, _CardId.GamecieltheSeaTurtleKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, _CardId.RadiantheMultidimensionalKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, _CardId.KumongoustheStickyStringKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, _CardId.ThunderKingtheLightningstrikeKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, _CardId.DogorantheMadFlameKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, _CardId.SuperAntiKaijuWarMachineMechaDogoran, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, _CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightSummon);
AddExecutor(ExecutorType.Activate, _CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect);
AddExecutor(ExecutorType.Summon, _CardId.SandaionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.GabrionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.MichionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.ZaphionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.HailonTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.RaphionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.SadionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.MetaionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.KamionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.LazionTheTimelord, DefaultTimelordSummon);
AddExecutor(ExecutorType.Summon, _CardId.LeftArmofTheForbiddenOne, JustDontIt);
AddExecutor(ExecutorType.Summon, _CardId.RightLegofTheForbiddenOne, JustDontIt);
AddExecutor(ExecutorType.Summon, _CardId.LeftLegofTheForbiddenOne, JustDontIt);
AddExecutor(ExecutorType.Summon, _CardId.RightArmofTheForbiddenOne, JustDontIt);
AddExecutor(ExecutorType.Summon, _CardId.ExodiaTheForbiddenOne, JustDontIt);
}
private List<int> HintMsgForEnemy = new List<int>
{
HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck,
HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Disable
};
private List<int> HintMsgForDeck = new List<int>
{
HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.Remove, HintMsg.AddToHand, HintMsg.FusionMaterial
};
private List<int> HintMsgForSelf = new List<int>
{
HintMsg.Equip
};
private List<int> HintMsgForMaterial = new List<int>
{
HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Release
};
private List<int> HintMsgForMaxSelect = new List<int>
{
HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.AddToHand, HintMsg.FusionMaterial, HintMsg.Destroy
};
public override IList<ClientCard> OnSelectCard(IList<ClientCard> _cards, int min, int max, int hint, bool cancelable)
{
if (Duel.Phase == DuelPhase.BattleStart)
return null;
if (AI.HaveSelectedCards())
return null;
IList<ClientCard> selected = new List<ClientCard>();
IList<ClientCard> cards = new List<ClientCard>(_cards);
if (max > cards.Count)
max = cards.Count;
if (HintMsgForEnemy.Contains(hint))
{
IList<ClientCard> enemyCards = cards.Where(card => card.Controller == 1).ToList();
// select enemy's card first
while (enemyCards.Count > 0 && selected.Count < max)
{
ClientCard card = enemyCards[Program.Rand.Next(enemyCards.Count)];
selected.Add(card);
enemyCards.Remove(card);
cards.Remove(card);
}
}
if (HintMsgForDeck.Contains(hint))
{
IList<ClientCard> deckCards = cards.Where(card => card.Location == CardLocation.Deck).ToList();
// select deck's card first
while (deckCards.Count > 0 && selected.Count < max)
{
ClientCard card = deckCards[Program.Rand.Next(deckCards.Count)];
selected.Add(card);
deckCards.Remove(card);
cards.Remove(card);
}
}
if (HintMsgForSelf.Contains(hint))
{
IList<ClientCard> botCards = cards.Where(card => card.Controller == 0).ToList();
// select bot's card first
while (botCards.Count > 0 && selected.Count < max)
{
ClientCard card = botCards[Program.Rand.Next(botCards.Count)];
selected.Add(card);
botCards.Remove(card);
cards.Remove(card);
}
}
if (HintMsgForMaterial.Contains(hint))
{
IList<ClientCard> materials = cards.OrderBy(card => card.Attack).ToList();
// select low attack first
while (materials.Count > 0 && selected.Count < min)
{
ClientCard card = materials[0];
selected.Add(card);
materials.Remove(card);
cards.Remove(card);
}
}
// select random cards
while (selected.Count < min)
{
ClientCard card = cards[Program.Rand.Next(cards.Count)];
selected.Add(card);
cards.Remove(card);
}
if (HintMsgForMaxSelect.Contains(hint))
{
// select max cards
while (selected.Count < max)
{
ClientCard card = cards[Program.Rand.Next(cards.Count)];
selected.Add(card);
cards.Remove(card);
}
}
return selected;
}
public override int OnSelectOption(IList<int> options)
{
return Program.Rand.Next(options.Count);
}
public override CardPosition OnSelectPosition(int cardId, IList<CardPosition> positions)
{
YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId);
if (cardData != null)
{
if (cardData.Attack < 0)
return CardPosition.FaceUpAttack;
if (cardData.Attack <= 1000)
return CardPosition.FaceUpDefence;
}
return 0;
}
private bool ImFeelingLucky()
{
if (Type == ExecutorType.Activate && DefaultCheckWhetherCardIsNegated(Card)) return false;
return Program.Rand.Next(10) >= 5 && DefaultDontChainMyself();
}
private bool ImFeelingUnlucky()
{
if (Type == ExecutorType.Activate && DefaultCheckWhetherCardIsNegated(Card)) return false;
return DefaultDontChainMyself();
}
private bool ImFeelingLazy()
{
if (Executors.Any(exec => (exec.Type == ExecutorType.SummonOrSet || exec.Type == ExecutorType.Summon || exec.Type == ExecutorType.MonsterSet) && exec.CardId == Card.Id))
return false;
return DefaultMonsterSummon();
}
private bool JustDontIt()
{
return false;
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,379 @@
using System;
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using System.Diagnostics;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using System.Linq;
namespace WindBot.Game.AI.Decks
{
[Deck("MathMech", "AI_Mathmech")]
public class MathmechExecutor : DefaultExecutor
{
public class CardId
{
public const int MathmechNebla = 53577438;
public const int MathmechSigma = 27182739;
public const int MathmechDivision = 89743495;
public const int MathmechAddition = 80965043;
public const int MathmechSubtra = 16360142;
public const int Mathmechdouble = 52354896;
public const int MathmechFinalSigma = 42632209;
public const int Mathmechalem = 85692042;
public const int MathmechMagma = 15248594;
public const int BalancerLord = 08567955;
public const int LightDragon = 61399402;
// spells
public const int upstartGoblin = 70368879;
public const int raigeki = 12580477;
public const int cynetmining = 57160136;
public const int PotOfDesires= 35261759;
public const int lightningStorm = 14532163;
public const int cosmicCyclone = 08267140;
public const int foolishBurial = 81439173;
public const int OneTimePasscode = 93104632;
public const int mathmechEquation = 14025912;
//traps
public const int threanteningRoar = 36361633;
//tokens
public const int securitytoken = 93104633;
}
public MathmechExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.raigeki ,when_raigeki);
AddExecutor(ExecutorType.Activate, CardId.upstartGoblin);
AddExecutor(ExecutorType.Activate, CardId.OneTimePasscode);
AddExecutor(ExecutorType.SpellSet, CardId.threanteningRoar);
AddExecutor(ExecutorType.Activate,CardId.cosmicCyclone , when_cosmic);
AddExecutor(ExecutorType.Activate,CardId.lightningStorm ,lightstorm_target);
AddExecutor(ExecutorType.Activate,CardId.foolishBurial,foolish_burial_target);
AddExecutor(ExecutorType.Activate,CardId.mathmechEquation,mathmech_equation_target);
AddExecutor(ExecutorType.Activate,CardId.PotOfDesires);
AddExecutor(ExecutorType.Summon, CardId.MathmechNebla);
AddExecutor(ExecutorType.Summon,CardId.BalancerLord );
AddExecutor(ExecutorType.Summon, CardId.Mathmechdouble);
AddExecutor(ExecutorType.Summon, CardId.MathmechSubtra);
AddExecutor(ExecutorType.Summon, CardId.MathmechAddition);
AddExecutor(ExecutorType.Summon, CardId.MathmechDivision);
AddExecutor(ExecutorType.Summon, CardId.MathmechDivision);
AddExecutor(ExecutorType.Activate, CardId.MathmechSigma);
AddExecutor(ExecutorType.Activate,CardId.threanteningRoar);
//xyz summons
AddExecutor(ExecutorType.SpSummon, CardId.Mathmechalem, when_Mathmechalem);
//xyz effects
AddExecutor(ExecutorType.Activate, CardId.Mathmechalem, mathchalenEffect);
//Synchro
AddExecutor(ExecutorType.SpSummon, CardId.MathmechFinalSigma , FinalSigmaSummon);
AddExecutor(ExecutorType.Activate, CardId.Mathmechdouble, doubleEffect);
//normal effects
AddExecutor(ExecutorType.Activate, CardId.MathmechNebla, NeblaEffect);
AddExecutor(ExecutorType.Activate,CardId.MathmechDivision , divisionEffect);
AddExecutor(ExecutorType.Activate,CardId.BalancerLord , active_balancer);
AddExecutor(ExecutorType.Activate, CardId.MathmechSubtra , whom_subtra);
AddExecutor(ExecutorType.Activate, CardId.MathmechAddition , whom_addition);
//spell effects
AddExecutor(ExecutorType.Activate, CardId.cynetmining , how_to_cynet_mine);
AddExecutor(ExecutorType.SpSummon, CardId.MathmechMagma, MagmaSummon);
AddExecutor(ExecutorType.Activate,CardId.MathmechFinalSigma);
AddExecutor(ExecutorType.Activate,CardId.MathmechMagma);
//function
}
public override bool OnSelectHand()
{
return false;
}
private bool when_cosmic()
{
if (Enemy.GetSpellCount() > 1)
{
AI.SelectCard(Util.GetBestEnemySpell());
return true;
}
else
{
return false;
}
}
private bool divisionEffect()
{
if (Enemy.GetMonsterCount() > 0)
{
AI.SelectCard(Util.GetBestEnemyMonster(canBeTarget:true,onlyFaceup:true));
return true;
}
else
{
return false;
}
}
private bool when_raigeki()
{
if (Enemy.GetMonsterCount() > 3)
{
return true;
}
else
{
return false;
}
}
private bool whom_addition()
{
AI.SelectCard(Util.GetBestBotMonster(onlyATK:true));
return true;
}
private bool whom_subtra()
{
try
{
AI.SelectCard(Util.GetBestEnemyMonster(onlyFaceup: true, canBeTarget: true));
return true;
}
catch (Exception e)
{
return true;
}
}
private bool active_balancer()
{
if (Bot.HasInHand(CardId.MathmechNebla))
{
AI.SelectCard(CardId.MathmechNebla);
return true;
}
else
{
return true;
}
}
private bool lightstorm_target()
{
if ((Enemy.MonsterZone.ToList().Count > Enemy.SpellZone.ToList().Count ) && Enemy.MonsterZone.ToList().Count>3)
{
AI.SelectPlace(Zones.MonsterZones);
return true;
}
else
{
AI.SelectPlace(Zones.SpellZones);
return true;
}
}
private bool mathmech_equation_target()
{
if (Bot.HasInGraveyard(CardId.MathmechNebla))
{
AI.SelectCard(CardId.MathmechNebla);
return true;
}
else
{
AI.SelectCard((Util.GetBestBotMonster(onlyATK: true)));
return true;
}
}
private bool foolish_burial_target()
{
AI.SelectCard(CardId.MathmechNebla);
return true;
}
private bool how_to_cynet_mine()
{
AI.SelectCard(Util.GetWorstBotMonster());
if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.MathmechSigma))
{
AI.SelectNextCard(CardId.MathmechSigma);
return true;
}
return true;
}
private bool when_Mathmechalem()
{
if (Bot.HasInMonstersZone(CardId.MathmechNebla)){
return false;
}
else if(Bot.HasInMonstersZone(CardId.MathmechSigma) && Bot.HasInMonstersZone(CardId.Mathmechdouble))
{
return false;
}
else if (Bot.HasInMonstersZone(CardId.Mathmechalem))
{
return false;
}
else
{
return true;
}
}
private bool FinalSigmaSummon()
{
if (Duel.Turn < 1)
{
return false;
}
if ((Bot.HasInMonstersZone(CardId.Mathmechdouble) && (( Bot.HasInMonstersZone(CardId.MathmechSigma)) || Bot.HasInMonstersZone(CardId.MathmechNebla))))
{
AI.SelectPosition(CardPosition.Attack);
try { AI.SelectPlace(Zones.ExtraMonsterZones); }
catch { }
return true;
}
else
{
return true;
}
}
private bool NeblaEffect()
{
bool a = Bot.HasInMonstersZone(CardId.MathmechSubtra) || Bot.HasInMonstersZone(CardId.securitytoken) || Bot.HasInMonstersZone(CardId.MathmechSigma) || Bot.HasInMonstersZone(CardId.MathmechAddition) || Bot.HasInMonstersZone(CardId.Mathmechalem) || Bot.HasInMonstersZone(CardId.MathmechDivision);
if (a)
{
List<int> cards = new List<int>();
cards.Add(CardId.MathmechSigma);
cards.Add(CardId.MathmechSubtra);
cards.Add(CardId.MathmechAddition);
cards.Add(item:CardId.MathmechDivision);
cards.Add(item:CardId.Mathmechalem);
cards.Add(CardId.securitytoken);
int u = 0;
List<ClientCard> monsters = Bot.GetMonstersInMainZone();
for (int i = 0; i < monsters.Count; i++)
{
if (cards.Contains(monsters[i].Id))
{
u = monsters[i].Id;
break;
}
else
{
u = CardId.securitytoken;
}
}
AI.SelectCard(CardId.securitytoken);
AI.SelectNextCard(CardId.Mathmechdouble);
return true;
}
if (Card.Location == CardLocation.Grave)
{
return true;
}
else
{
return false;
}
}
private bool doubleEffect()
{
if (Bot.HasInMonstersZone(CardId.MathmechNebla) || Bot.HasInMonstersZone(CardId.MathmechSigma))
{
return true;
};
if (Card.Location == CardLocation.Grave )
{
return true;
}
else
{
return false;
}
}
private bool mathchalenEffect()
{
if (Duel.Turn < 1)
{
return false;
}
if ( (Bot.HasInHandOrInGraveyard(CardId.MathmechNebla) && !Bot.HasInMonstersZone(CardId.MathmechNebla)) && (Card.Location == CardLocation.FieldZone && Card.HasXyzMaterial(0)) )
{
AI.SelectCard(CardId.Mathmechalem);
AI.SelectNextCard(CardId.MathmechNebla);
return true;
}
if (Bot.HasInHandOrInGraveyard(CardId.Mathmechdouble) &&
(Bot.HasInMonstersZone(CardId.MathmechNebla) || Bot.HasInMonstersZone(CardId.MathmechSigma)) &&
Card.Location == CardLocation.FieldZone && Card.HasXyzMaterial(0))
{
AI.SelectCard(CardId.Mathmechalem);
AI.SelectNextCard(CardId.Mathmechdouble);
return true;
}
if (!Bot.HasInHandOrInGraveyard(CardId.MathmechNebla) && Card.HasXyzMaterial(2))
{
AI.SelectCard(CardId.MathmechNebla);
AI.SelectThirdCard(CardId.MathmechNebla);
return true;
}
if (!Bot.HasInHandOrInGraveyard(CardId.MathmechSigma) && Card.HasXyzMaterial(2))
{
AI.SelectCard(CardId.MathmechSigma);
AI.SelectThirdCard(CardId.MathmechSigma);
return true;
}
else
{
return false;
};
}
private bool MagmaSummon()
{
if (Bot.HasInMonstersZone(CardId.MathmechNebla))
{
return false;
}
if (Bot.HasInMonstersZone(CardId.MathmechSigma) && Bot.HasInMonstersZone(CardId.Mathmechdouble))
{
return false;
}
else
{
return true;
}
}
public override int OnSelectPlace(int cardId, int player, CardLocation location, int available)
{
if (cardId == CardId.MathmechFinalSigma)
{
if ((Zones.z5 & available) > 0) return Zones.z5;
if ((Zones.z6 & available) > 0) return Zones.z6;
}
return base.OnSelectPlace(cardId, player, location, available);
}
}
}
@@ -0,0 +1,37 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("MokeyMokey", "AI_MokeyMokey", "Easy")]
public class MokeyMokeyExecutor : DefaultExecutor
{
public class CardId
{
public const int LeoWizard = 4392470;
public const int Bunilla = 69380702;
}
private int RockCount = 0;
public MokeyMokeyExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Summon);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.SpellSet);
}
public override int OnRockPaperScissors()
{
RockCount++;
if (RockCount <= 3)
return 2;
else
return base.OnRockPaperScissors();
}
}
}
@@ -0,0 +1,38 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("MokeyMokeyKing", "AI_MokeyMokeyKing", "Easy")]
public class MokeyMokeyKingExecutor : DefaultExecutor
{
public class CardId
{
public const int LeoWizard = 4392470;
public const int Bunilla = 69380702;
}
private int RockCount = 0;
public MokeyMokeyKingExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpSummon);
AddExecutor(ExecutorType.SummonOrSet);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.Activate, DefaultField);
}
public override int OnRockPaperScissors()
{
RockCount++;
if (RockCount <= 3)
return 2;
else
return base.OnRockPaperScissors();
}
}
}
@@ -0,0 +1,326 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
// NOT FINISHED YET
[Deck("Nekroz", "AI_Nekroz", "NotFinished")]
public class NekrozExecutor : DefaultExecutor
{
public class CardId
{
public const int DancePrincess = 52738610;
public const int ThousandHands = 23401839;
public const int TenThousandHands = 95492061;
public const int Shurit = 90307777;
public const int MaxxC = 23434538;
public const int DecisiveArmor = 88240999;
public const int Trishula = 52068432;
public const int Valkyrus = 25857246;
public const int Gungnir = 74122412;
public const int Brionac = 26674724;
public const int Unicore = 89463537;
public const int Clausolas = 99185129;
public const int PhantomOfChaos = 30312361;
public const int DarkHole = 53129443;
public const int ReinforcementOfTheArmy = 32807846;
public const int TradeIn = 38120068;
public const int PreparationOfRites = 96729612;
public const int Mirror = 14735698;
public const int Kaleidoscope = 51124303;
public const int Cycle = 97211663;
public const int MysticalSpaceTyphoon = 5318639;
public const int RoyalDecree = 51452091;
public const int EvilswarmExcitonKnight = 46772449;
public const int HeraldOfTheArcLight = 79606837;
}
List<int> NekrozRituelCard = new List<int>();
List<int> NekrozSpellCard = new List<int>();
public NekrozExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
NekrozRituelCard.Add(CardId.Clausolas);
NekrozRituelCard.Add(CardId.Unicore);
NekrozRituelCard.Add(CardId.DecisiveArmor);
NekrozRituelCard.Add(CardId.Brionac);
NekrozRituelCard.Add(CardId.Trishula);
NekrozRituelCard.Add(CardId.Gungnir);
NekrozRituelCard.Add(CardId.Valkyrus);
NekrozSpellCard.Add(CardId.Mirror);
NekrozSpellCard.Add(CardId.Kaleidoscope);
NekrozSpellCard.Add(CardId.Cycle);
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.ReinforcementOfTheArmy, ReinforcementOfTheArmyEffect);
AddExecutor(ExecutorType.Activate, CardId.TradeIn);
AddExecutor(ExecutorType.Activate, CardId.PreparationOfRites);
AddExecutor(ExecutorType.Activate, CardId.Mirror);
AddExecutor(ExecutorType.Activate, CardId.Kaleidoscope);
AddExecutor(ExecutorType.Activate, CardId.Cycle);
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, CardId.RoyalDecree);
AddExecutor(ExecutorType.SummonOrSet, CardId.DancePrincess, DancePrincessSummon);
AddExecutor(ExecutorType.MonsterSet, CardId.Shurit, ShuritSet);
AddExecutor(ExecutorType.Summon, CardId.ThousandHands, ThousandHandsSummon);
AddExecutor(ExecutorType.Summon, CardId.TenThousandHands, TenThousandHandsSummon);
AddExecutor(ExecutorType.Summon, CardId.PhantomOfChaos, PhantomOfChaosSummon);
AddExecutor(ExecutorType.Activate, CardId.Unicore, UnicoreEffect);
AddExecutor(ExecutorType.Activate, CardId.DecisiveArmor, DecisiveArmorEffect);
AddExecutor(ExecutorType.Activate, CardId.Valkyrus, ValkyrusEffect);
AddExecutor(ExecutorType.Activate, CardId.Gungnir, GungnirEffect);
AddExecutor(ExecutorType.Activate, CardId.Brionac, BrionacEffect);
AddExecutor(ExecutorType.Activate, CardId.Clausolas, ClausolasEffect);
AddExecutor(ExecutorType.Activate, CardId.Trishula);
AddExecutor(ExecutorType.Activate, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect);
AddExecutor(ExecutorType.Activate, CardId.PhantomOfChaos, PhantomOfChaosEffect);
AddExecutor(ExecutorType.Activate, CardId.MaxxC);
AddExecutor(ExecutorType.Activate, CardId.ThousandHands, ThousandHandsEffect);
AddExecutor(ExecutorType.Activate, CardId.TenThousandHands, BrionacEffect);
AddExecutor(ExecutorType.Activate, CardId.HeraldOfTheArcLight);
AddExecutor(ExecutorType.Activate, CardId.Shurit);
AddExecutor(ExecutorType.SpSummon, CardId.Trishula);
AddExecutor(ExecutorType.SpSummon, CardId.DecisiveArmor);
AddExecutor(ExecutorType.SpSummon, CardId.Valkyrus);
AddExecutor(ExecutorType.SpSummon, CardId.Gungnir);
AddExecutor(ExecutorType.SpSummon, CardId.Brionac);
AddExecutor(ExecutorType.SpSummon, CardId.Unicore);
AddExecutor(ExecutorType.SpSummon, CardId.Clausolas);
AddExecutor(ExecutorType.SpSummon, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightSummon);
}
private bool ThousandHandsSummon()
{
if (!Bot.HasInHand(NekrozRituelCard) || Bot.HasInHand(CardId.Shurit) || !Bot.HasInHand(NekrozSpellCard))
return true;
foreach (ClientCard Card in Bot.Hand)
if (Card != null && Card.IsCode(CardId.Kaleidoscope) && !Bot.HasInHand(CardId.Unicore))
return true;
else if (Card.IsCode(CardId.Trishula) || Card.IsCode(CardId.DecisiveArmor) && !Bot.HasInHand(CardId.Mirror) || !Bot.HasInHand(CardId.Shurit))
return true;
return false;
}
private bool ReinforcementOfTheArmyEffect()
{
if (!Bot.HasInGraveyard(CardId.Shurit) && !Bot.HasInHand(CardId.Shurit))
{
AI.SelectCard(CardId.Shurit);
return true;
}
return false;
}
private bool TenThousandHandsSummon()
{
if (!Bot.HasInHand(CardId.ThousandHands) || !Bot.HasInHand(CardId.Shurit))
return true;
return false;
}
private bool DancePrincessSummon()
{
if (!Bot.HasInHand(CardId.ThousandHands) && !Bot.HasInHand(CardId.TenThousandHands))
return true;
return false;
}
private bool PhantomOfChaosSummon()
{
if (Bot.HasInGraveyard(CardId.Shurit) && Bot.HasInHand(NekrozSpellCard) && Bot.HasInHand(NekrozRituelCard))
return true;
return false;
}
private bool PhantomOfChaosEffect()
{
AI.SelectCard(CardId.Shurit);
return true;
}
private bool ShuritSet()
{
if (!Bot.HasInHand(CardId.ThousandHands) && !Bot.HasInHand(CardId.TenThousandHands) && !Bot.HasInHand(CardId.DancePrincess))
return true;
return false;
}
private bool DecisiveArmorEffect()
{
if (Util.IsAllEnemyBetterThanValue(3300, true))
{
AI.SelectCard(CardId.DecisiveArmor);
return true;
}
return false;
}
private bool ValkyrusEffect()
{
if (Duel.Phase == DuelPhase.Battle)
return true;
return false;
}
private bool GungnirEffect()
{
if (Util.IsOneEnemyBetter(true) && Duel.Phase == DuelPhase.Main1)
{
AI.SelectCard(Enemy.GetMonsters().GetHighestAttackMonster());
return true;
}
return false;
}
private bool BrionacEffect()
{
if (!Bot.HasInHand(CardId.Shurit))
{
AI.SelectCard(CardId.Shurit);
return true;
}
else if (!Bot.HasInHand(NekrozSpellCard))
{
AI.SelectCard(CardId.Mirror);
return true;
}
else if (Util.IsOneEnemyBetterThanValue(3300, true) && !Bot.HasInHand(CardId.Trishula))
{
AI.SelectCard(CardId.Trishula);
return true;
}
else if (Util.IsAllEnemyBetterThanValue(2700,true) && !Bot.HasInHand(CardId.DecisiveArmor))
{
AI.SelectCard(CardId.DecisiveArmor);
return true;
}
else if (Bot.HasInHand(CardId.Unicore) && !Bot.HasInHand(CardId.Kaleidoscope))
{
AI.SelectCard(CardId.Kaleidoscope);
return true;
}
else if (!Bot.HasInHand(CardId.Unicore) && Bot.HasInHand(CardId.Kaleidoscope))
{
AI.SelectCard(CardId.Unicore);
return true;
}
return true;
}
private bool ThousandHandsEffect()
{
if (Util.IsOneEnemyBetterThanValue(3300, true) && !Bot.HasInHand(CardId.Trishula))
{
AI.SelectCard(CardId.Trishula);
return true;
}
else if (Util.IsAllEnemyBetterThanValue(2700, true) && !Bot.HasInHand(CardId.DecisiveArmor))
{
AI.SelectCard(CardId.DecisiveArmor);
return true;
}
else if (!Bot.HasInHand(CardId.Unicore) && Bot.HasInHand(CardId.Kaleidoscope))
{
AI.SelectCard(CardId.Unicore);
return true;
}
return true;
}
private bool UnicoreEffect()
{
if (Bot.HasInGraveyard(CardId.Shurit))
{
AI.SelectCard(CardId.Shurit);
return true;
}
return false;
}
private bool ClausolasEffect()
{
if (!Bot.HasInHand(NekrozSpellCard))
{
AI.SelectCard(CardId.Mirror);
return true;
}
return false;
}
private bool IsTheLastPossibility()
{
if (!Bot.HasInHand(CardId.DecisiveArmor) && !Bot.HasInHand(CardId.Trishula))
return true;
return false;
}
private bool SelectNekrozWhoInvoke()
{
List<int> NekrozCard = new List<int>();
try
{
foreach (ClientCard card in Bot.Hand)
if (card != null && card.IsCode(NekrozRituelCard))
NekrozCard.Add(card.Id);
foreach (int Id in NekrozCard)
{
if (Id == CardId.Trishula && Util.IsAllEnemyBetterThanValue(2700, true) && Bot.HasInHand(CardId.DecisiveArmor))
{
AI.SelectCard(CardId.Trishula);
return true;
}
else if (Id == CardId.DecisiveArmor)
{
AI.SelectCard(CardId.DecisiveArmor);
return true;
}
else if (Id == CardId.Unicore && Bot.HasInHand(CardId.Kaleidoscope) && !Bot.HasInGraveyard(CardId.Shurit))
{
AI.SelectCard(CardId.Unicore);
return true;
}
else if (Id == CardId.Valkyrus)
{
if (IsTheLastPossibility())
{
AI.SelectCard(CardId.Valkyrus);
return true;
}
}
else if (Id == CardId.Gungnir)
{
if (IsTheLastPossibility())
{
AI.SelectCard(CardId.Gungnir);
return true;
}
}
else if (Id == CardId.Clausolas)
{
if (IsTheLastPossibility())
{
AI.SelectCard(CardId.Clausolas);
return true;
}
}
}
return false;
}
catch
{ return false; }
}
}
}
@@ -0,0 +1,110 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("OldSchool", "AI_OldSchool", "Easy")]
public class OldSchoolExecutor : DefaultExecutor
{
public class CardId
{
public const int AncientGearGolem = 83104731;
public const int Frostosaurus = 6631034;
public const int AlexandriteDragon = 43096270;
public const int GeneWarpedWarwolf = 69247929;
public const int GearGolemTheMovingFortress = 30190809;
public const int EvilswarmHeliotrope = 77542832;
public const int LusterDragon = 11091375;
public const int InsectKnight = 35052053;
public const int ArchfiendSoldier = 49881766;
public const int HeavyStorm = 19613556;
public const int DarkHole = 53129443;
public const int Raigeki = 12580477;
public const int HammerShot = 26412047;
public const int Fissure = 66788016;
public const int SwordsOfRevealingLight = 72302403;
public const int DoubleSummon = 43422537;
public const int MirrorForce = 44095762;
public const int DimensionalPrison = 70342110;
}
public OldSchoolExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.HeavyStorm, DefaultHeavyStorm);
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.Raigeki, DefaultRaigeki);
AddExecutor(ExecutorType.Activate, CardId.HammerShot, DefaultHammerShot);
AddExecutor(ExecutorType.Activate, CardId.Fissure);
AddExecutor(ExecutorType.Activate, CardId.SwordsOfRevealingLight, SwordsOfRevealingLight);
AddExecutor(ExecutorType.Activate, CardId.DoubleSummon, DoubleSummon);
AddExecutor(ExecutorType.Summon, CardId.AncientGearGolem, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.Frostosaurus, DefaultMonsterSummon);
AddExecutor(ExecutorType.SummonOrSet, CardId.AlexandriteDragon);
AddExecutor(ExecutorType.SummonOrSet, CardId.GeneWarpedWarwolf);
AddExecutor(ExecutorType.MonsterSet, CardId.GearGolemTheMovingFortress);
AddExecutor(ExecutorType.SummonOrSet, CardId.EvilswarmHeliotrope);
AddExecutor(ExecutorType.SummonOrSet, CardId.LusterDragon);
AddExecutor(ExecutorType.SummonOrSet, CardId.InsectKnight);
AddExecutor(ExecutorType.SummonOrSet, CardId.ArchfiendSoldier);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.DimensionalPrison, DefaultTrap);
}
private int _lastDoubleSummon;
private bool DoubleSummon()
{
if (_lastDoubleSummon == Duel.Turn)
return false;
if (Duel.MainPhase.SummonableCards.Count == 0)
return false;
if (Duel.MainPhase.SummonableCards.Count == 1 && Duel.MainPhase.SummonableCards[0].Level < 5)
{
bool canTribute = false;
foreach (ClientCard handCard in Bot.Hand)
{
if (handCard.IsMonster() && handCard.Level > 4 && handCard.Level < 6)
canTribute = true;
}
if (!canTribute)
return false;
}
int monsters = 0;
foreach (ClientCard handCard in Bot.Hand)
{
if (handCard.IsMonster())
monsters++;
}
if (monsters <= 1)
return false;
_lastDoubleSummon = Duel.Turn;
return true;
}
private bool SwordsOfRevealingLight()
{
foreach (ClientCard handCard in Enemy.GetMonsters())
{
if (handCard.IsFacedown())
return true;
}
return Util.IsOneEnemyBetter(true);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,734 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Phantasm", "AI_Phantasm")]
public class PhantasmExecutor : DefaultExecutor
{
public class CardId
{
public const int MegalosmasherX = 81823360;
public const int AshBlossom = 14558127;
public const int EaterOfMillions = 63845230;
public const int HarpieFeatherDuster = 18144506;
public const int PotOfDesires = 35261759;
public const int FossilDig = 47325505;
public const int CardOfDemise = 59750328;
public const int Terraforming = 73628505;
public const int PotOfDuality = 98645731;
public const int Scapegoat = 73915051;
public const int PacifisThePhantasmCity = 2819435;
public const int InfiniteImpermanence = 10045474;
public const int PhantasmSprialBattle = 34302287;
public const int DrowningMirrorForce = 47475363;
public const int StarlightRoad = 58120309;
public const int PhantasmSpiralPower = 61397885;
public const int Metaverse = 89208725;
public const int SeaStealthAttack = 19089195;
public const int GozenMatch = 53334471;
public const int SkillDrain = 82732705;
public const int TheHugeRevolutionIsOver = 99188141;
public const int StardustDragon = 44508094;
public const int TopologicBomberDragon = 5821478;
public const int BorreloadDragon = 31833038;
public const int BorrelswordDragon = 85289965;
public const int KnightmareGryphon = 65330383;
public const int TopologicTrisbaena = 72529749;
public const int SummonSorceress = 61665245;
public const int KnightmareUnicorn = 38342335;
public const int KnightmarePhoenix = 2857636;
public const int KnightmareCerberus = 75452921;
public const int CrystronNeedlefiber = 50588353;
public const int MissusRadiant = 3987233;
public const int LinkSpider = 98978921;
public const int Linkuriboh = 41999284;
public const int ElShaddollWinda = 94977269;
public const int BrandishSkillJammingWave = 25955749;
public const int BrandishSkillAfterburner = 99550630;
public const int EternalSoul = 48680970;
public const int SuperboltThunderDragon = 15291624;
}
public PhantasmExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
//counter
AddExecutor(ExecutorType.GoToBattlePhase, GoToBattlePhase);
AddExecutor(ExecutorType.Activate, CardId.StarlightRoad, PreventFeatherDustereff);
AddExecutor(ExecutorType.Activate, CardId.TheHugeRevolutionIsOver, PreventFeatherDustereff);
AddExecutor(ExecutorType.Activate, _CardId.GhostBelle, DefaultGhostBelleAndHauntedMansion);
AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, DefaultCalledByTheGrave);
AddExecutor(ExecutorType.Activate, _CardId.EffectVeiler, DefaultEffectVeiler);
AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, DefaultInfiniteImpermanence);
AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, _CardId.GhostOgreAndSnowRabbit, DefaultGhostOgreAndSnowRabbit);
//trap activate
AddExecutor(ExecutorType.Activate, CardId.SeaStealthAttack, SeaStealthAttackeff);
AddExecutor(ExecutorType.Activate, CardId.PhantasmSprialBattle, PhantasmSprialBattleeff);
AddExecutor(ExecutorType.Activate, CardId.PhantasmSpiralPower, PhantasmSpiralPowereff);
AddExecutor(ExecutorType.Activate, CardId.DrowningMirrorForce, DrowningMirrorForceeff);
AddExecutor(ExecutorType.Activate, CardId.GozenMatch, GozenMatcheff);
AddExecutor(ExecutorType.Activate, CardId.SkillDrain, SkillDraineff);
AddExecutor(ExecutorType.Activate, CardId.Metaverse, Metaverseeff);
//sp
AddExecutor(ExecutorType.SpSummon, CardId.BorrelswordDragon, BorrelswordDragonsp);
AddExecutor(ExecutorType.Activate, CardId.BorrelswordDragon, BorrelswordDragoneff);
AddExecutor(ExecutorType.SpSummon, CardId.MissusRadiant, MissusRadiantsp);
AddExecutor(ExecutorType.Activate, CardId.MissusRadiant, MissusRadianteff);
AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, Linkuriboheff);
AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp);
//first
AddExecutor(ExecutorType.Activate, CardId.HarpieFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, CardId.FossilDig, FossilDigeff);
AddExecutor(ExecutorType.Activate, CardId.Terraforming, Terraformingeff);
AddExecutor(ExecutorType.Activate, CardId.PotOfDuality, PotOfDualityeff);
AddExecutor(ExecutorType.Activate, CardId.PotOfDesires, PotOfDesireseff);
AddExecutor(ExecutorType.Activate, CardId.PacifisThePhantasmCity, PacifisThePhantasmCityeff);
//summon
AddExecutor(ExecutorType.Summon, CardId.MegalosmasherX, MegalosmasherXsummon);
//sp
AddExecutor(ExecutorType.SpSummon, CardId.EaterOfMillions, EaterOfMillionssp);
AddExecutor(ExecutorType.Activate, CardId.EaterOfMillions, EaterOfMillionseff);
//other
AddExecutor(ExecutorType.Activate, CardId.Scapegoat, DefaultScapegoat);
AddExecutor(ExecutorType.SpellSet, CardId.SeaStealthAttack, NoSetAlreadyDone);
AddExecutor(ExecutorType.SpellSet, CardId.StarlightRoad, StarlightRoadset);
AddExecutor(ExecutorType.SpellSet, CardId.TheHugeRevolutionIsOver, TheHugeRevolutionIsOverset);
AddExecutor(ExecutorType.SpellSet, CardId.DrowningMirrorForce);
AddExecutor(ExecutorType.SpellSet, CardId.InfiniteImpermanence, InfiniteImpermanenceset);
AddExecutor(ExecutorType.SpellSet, CardId.Scapegoat, NoSetAlreadyDone);
AddExecutor(ExecutorType.SpellSet, CardId.GozenMatch, NoSetAlreadyDone);
AddExecutor(ExecutorType.SpellSet, CardId.SkillDrain, NoSetAlreadyDone);
AddExecutor(ExecutorType.SpellSet, CardId.Metaverse);
AddExecutor(ExecutorType.SpellSet, SpellSeteff);
AddExecutor(ExecutorType.Activate, CardId.CardOfDemise, CardOfDemiseeff);
AddExecutor(ExecutorType.Repos, MonsterRepos);
}
bool summon_used = false;
bool CardOfDemiseeff_used = false;
bool SeaStealthAttackeff_used = false;
public override void OnNewTurn()
{
summon_used = false;
CardOfDemiseeff_used = false;
SeaStealthAttackeff_used = false;
base.OnNewTurn();
}
private bool PreventFeatherDustereff()
{
return Duel.LastChainPlayer == 1;
}
private bool GoToBattlePhase()
{
if (Enemy.GetMonsterCount() == 0)
{
if (Util.GetTotalAttackingMonsterAttack(0) >= Enemy.LifePoints)
{
return true;
}
}
return false;
}
private bool PhantasmSprialBattleeff()
{
if (DefaultOnBecomeTarget() && Card.Location==CardLocation.SpellZone)
{
AI.SelectCard(Util.GetBestEnemyCard(false,true));
return true;
}
if(Enemy.HasInSpellZone(CardId.EternalSoul))
{
AI.SelectCard(CardId.EternalSoul);
return UniqueFaceupSpell();
}
if(Bot.UnderAttack && Bot.BattlingMonster != null && Bot.BattlingMonster.IsCode(CardId.MegalosmasherX))
{
AI.SelectCard(Enemy.BattlingMonster);
return UniqueFaceupSpell();
}
if (Bot.GetMonsterCount() > 0 && !Bot.HasInSpellZone(CardId.SeaStealthAttack) &&
Util.IsOneEnemyBetterThanValue(2000, false) && Duel.Phase==DuelPhase.BattleStart)
{
AI.SelectCard(Util.GetBestEnemyMonster(true,true));
return UniqueFaceupSpell();
}
if (Util.GetProblematicEnemyCard(9999,true)!=null)
{
if (Util.GetProblematicEnemyCard(9999, true).IsCode(CardId.ElShaddollWinda) &&
!Util.GetProblematicEnemyCard(9999, true).IsDisabled())
return false;
AI.SelectCard(Util.GetProblematicEnemyCard(9999, true));
return UniqueFaceupSpell();
}
return false;
}
private bool PhantasmSpiralPowereff()
{
if (DefaultOnBecomeTarget() && Card.Location == CardLocation.SpellZone) return true;
if(Duel.Player == 0 || (Duel.Player==1 && Bot.BattlingMonster!=null))
{
if(Enemy.HasInMonstersZone(CardId.ElShaddollWinda))
{
AI.SelectCard(CardId.ElShaddollWinda);
return UniqueFaceupSpell();
}
if(Enemy.HasInMonstersZone(CardId.SuperboltThunderDragon))
{
AI.SelectCard(CardId.SuperboltThunderDragon);
return UniqueFaceupSpell();
}
}
return DefaultInfiniteImpermanence() && UniqueFaceupSpell();
}
private bool DrowningMirrorForceeff()
{
int count = 0;
foreach(ClientCard m in Enemy.GetMonsters())
{
if (m.IsAttack()) count++;
}
if (Util.GetTotalAttackingMonsterAttack(1) >= Bot.LifePoints)
return true;
return count >= 2;
}
private bool GozenMatcheff()
{
if (Bot.GetMonsterCount() >= 4 || Bot.HasInSpellZone(CardId.Scapegoat)) return false;
if (DefaultOnBecomeTarget()) return true;
int dark_count = 0;
int Divine_count = 0;
int Earth_count = 0;
int Fire_count = 0;
int Light_count = 0;
int Water_count = 0;
int Wind_count = 0;
foreach (ClientCard m in Enemy.GetMonsters())
{
if (m.HasAttribute(CardAttribute.Dark)) dark_count++;
if (m.HasAttribute(CardAttribute.Divine)) Divine_count++;
if (m.HasAttribute(CardAttribute.Earth)) Earth_count++;
if (m.HasAttribute(CardAttribute.Fire)) Fire_count++;
if (m.HasAttribute(CardAttribute.Light)) Light_count++;
if (m.HasAttribute(CardAttribute.Water)) Water_count++;
if (m.HasAttribute(CardAttribute.Wind)) Wind_count++;
}
if (dark_count > 1) dark_count = 1;
if (Divine_count > 1) Divine_count = 1;
if (Earth_count > 1) Earth_count = 1;
if (Fire_count > 1) Fire_count = 1;
if (Light_count > 1) Light_count = 1;
if (Water_count > 1) Water_count = 1;
if (Wind_count > 1) Wind_count = 1;
return ((dark_count + Divine_count + Earth_count + Fire_count + Light_count + Water_count + Wind_count) >= 2 && UniqueFaceupSpell());
}
private bool SkillDraineff()
{
if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard().Location == CardLocation.MonsterZone)
return UniqueFaceupSpell();
return false;
}
private bool Metaverseeff()
{
if (Duel.LastChainPlayer == 0) return false;
if (!Bot.HasInSpellZone(CardId.PacifisThePhantasmCity))
{
AI.SelectOption(1);
return UniqueFaceupSpell();
}
else
{
AI.SelectOption(0);
return UniqueFaceupSpell();
}
}
private bool CardOfDemiseeff()
{
if (DefaultSpellWillBeNegated()) return false;
AI.SelectPlace(Zones.z2);
if(Card.Location==CardLocation.Hand)
{
if (Bot.Hand.Count <= 1 && Bot.GetSpellCountWithoutField() <= 3)
{
CardOfDemiseeff_used = true;
return true;
}
}
else
{
if (Bot.Hand.Count <= 1 && Bot.GetSpellCountWithoutField() <= 4)
{
CardOfDemiseeff_used = true;
return true;
}
}
return false;
}
private bool FossilDigeff()
{
if (DefaultSpellWillBeNegated()) return false;
if (CardOfDemiseeff_used && summon_used) return false;
return true;
}
private bool PotOfDualityeff()
{
if(!Bot.HasInHandOrInSpellZone(CardId.PacifisThePhantasmCity) &&
!Bot.HasInHandOrInSpellZone(CardId.Metaverse))
{
if(Bot.HasInGraveyard(CardId.PacifisThePhantasmCity) && !Bot.HasInHandOrInSpellZone(CardId.SeaStealthAttack))
{
AI.SelectCard(
CardId.SeaStealthAttack,
CardId.PacifisThePhantasmCity,
CardId.Terraforming,
CardId.Metaverse,
CardId.CardOfDemise,
CardId.Scapegoat
);
}
else
{
AI.SelectCard(
CardId.PacifisThePhantasmCity,
CardId.Terraforming,
CardId.Metaverse,
CardId.CardOfDemise,
CardId.Scapegoat
);
}
}
else if(!Bot.HasInHandOrInSpellZone(CardId.SeaStealthAttack))
{
AI.SelectCard(
CardId.SeaStealthAttack,
CardId.CardOfDemise,
CardId.PotOfDesires,
CardId.Scapegoat
);
}
else
{
AI.SelectCard(
CardId.CardOfDemise,
CardId.PotOfDesires,
CardId.Scapegoat
);
}
return true;
}
private bool Terraformingeff()
{
if (DefaultSpellWillBeNegated()) return false;
if (CardOfDemiseeff_used && Bot.HasInSpellZone(CardId.PacifisThePhantasmCity)) return false;
return true;
}
private bool PacifisThePhantasmCityeff()
{
if (DefaultSpellWillBeNegated()) return false;
if(Card.Location==CardLocation.Hand)
{
if (Bot.HasInSpellZone(CardId.PacifisThePhantasmCity))
return false;
return true;
}
else
{
ClientCard target = null;
foreach(ClientCard s in Bot.GetSpells())
{
if(s.IsCode(CardId.SeaStealthAttack) && Card.IsFaceup())
{
target = s;
break;
}
}
foreach(ClientCard m in Bot.GetMonsters())
{
if(m.HasAttribute(CardAttribute.Water))
{
if (target != null && !SeaStealthAttackeff_used)
{
if (Util.IsChainTarget(Card) || Util.IsChainTarget(target))
return false;
}
break;
}
}
AI.SelectPlace(Zones.z1 | Zones.z3);
AI.SelectCard(CardId.PhantasmSprialBattle);
return true;
}
}
private bool MegalosmasherXsummon()
{
AI.SelectPlace(Zones.z1 | Zones.z3);
summon_used = true;
return true;
}
private bool BorrelswordDragonsp()
{
if (!Bot.HasInMonstersZone(CardId.MissusRadiant))
return false;
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard m in Bot.GetMonsters())
{
if (m.IsCode(CardId.MissusRadiant))
{
material_list.Add(m);
break;
}
}
foreach (ClientCard m in Bot.GetMonsters())
{
if (m.IsCode(CardId.Linkuriboh, CardId.LinkSpider))
{
material_list.Add(m);
if (material_list.Count == 3)
break;
}
}
if (material_list.Count == 3)
{
AI.SelectMaterials(material_list);
return true;
}
return false;
}
private bool BorrelswordDragoneff()
{
if (ActivateDescription == Util.GetStringId(CardId.BorrelswordDragon, 0))
{
if (Util.IsChainTarget(Card) && Util.GetBestEnemyMonster(true, true) != null)
{
AI.SelectCard(Util.GetBestEnemyMonster(true, true));
return true;
}
if (Duel.Player == 1 && Bot.BattlingMonster == Card)
{
AI.SelectCard(Enemy.BattlingMonster);
return true;
}
if (Duel.Player == 1 && Bot.BattlingMonster != null &&
(Enemy.BattlingMonster.Attack - Bot.BattlingMonster.Attack) >= Bot.LifePoints)
{
AI.SelectCard(Enemy.BattlingMonster);
return true;
}
if (Duel.Player == 0 && Duel.Phase == DuelPhase.BattleStart)
{
foreach (ClientCard check in Enemy.GetMonsters())
{
if (check.IsAttack() && !check.HasType(CardType.Link))
{
AI.SelectCard(check);
return true;
}
}
}
return false;
}
return true;
}
private bool EaterOfMillionssp()
{
if (Bot.MonsterZone[1] == null)
AI.SelectPlace(Zones.z1);
else
AI.SelectPlace(Zones.z3);
if (Enemy.HasInMonstersZone(CardId.KnightmareGryphon, true)) return false;
if (Util.GetProblematicEnemyMonster() == null && Bot.ExtraDeck.Count < 5) return false;
if (Bot.GetMonstersInMainZone().Count >= 5) return false;
if (Util.IsTurn1OrMain2()) return false;
AI.SelectPosition(CardPosition.FaceUpAttack);
IList<ClientCard> material_list = new List<ClientCard>();
if(Bot.HasInExtra(CardId.BorreloadDragon))
{
AI.SelectMaterials(new[] {
CardId.TopologicBomberDragon,
CardId.TopologicTrisbaena,
CardId.KnightmareGryphon,
CardId.SummonSorceress,
CardId.BorreloadDragon
}, HintMsg.Remove);
}
else
{
foreach(ClientCard m in Bot.ExtraDeck)
{
if (material_list.Count == 5) break;
material_list.Add(m);
}
AI.SelectMaterials(material_list, HintMsg.Remove);
}
return true;
}
private bool EaterOfMillionseff()
{
if (Enemy.BattlingMonster.HasPosition(CardPosition.Attack) && (Bot.BattlingMonster.Attack - Enemy.BattlingMonster.GetDefensePower() >= Enemy.LifePoints)) return false;
return true;
}
private bool MissusRadiantsp()
{
IList<ClientCard> material_list = new List<ClientCard>();
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasAttribute(CardAttribute.Earth) && monster.Level == 1 && !monster.IsCode(CardId.EaterOfMillions))
material_list.Add(monster);
if (material_list.Count == 2) break;
}
if (material_list.Count < 2) return false;
if (Bot.HasInMonstersZone(CardId.MissusRadiant)) return false;
AI.SelectMaterials(material_list);
if ((Bot.MonsterZone[0] == null || Bot.MonsterZone[0].Level==1) &&
(Bot.MonsterZone[2] == null || Bot.MonsterZone[2].Level == 1)&&
Bot.MonsterZone[5] == null)
AI.SelectPlace(Zones.z5);
else
AI.SelectPlace(Zones.z6);
return true;
}
private bool MissusRadianteff()
{
AI.SelectCard(new[]
{
CardId.MissusRadiant,
});
return true;
}
private bool Linkuribohsp()
{
foreach (ClientCard c in Bot.GetMonsters())
{
if (!c.IsCode(CardId.EaterOfMillions, CardId.Linkuriboh) && c.Level == 1)
{
AI.SelectMaterials(c);
return true;
}
}
return false;
}
private bool Linkuriboheff()
{
if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.Linkuriboh)) return false;
return true;
}
private bool SeaStealthAttackeff()
{
if (DefaultOnBecomeTarget())
{
AI.SelectCard(CardId.MegalosmasherX);
SeaStealthAttackeff_used = true;
return true;
}
if ((Card.IsFacedown() && Bot.HasInHandOrInSpellZoneOrInGraveyard(CardId.PacifisThePhantasmCity)))
{
if (!Bot.HasInSpellZone(CardId.PacifisThePhantasmCity))
{
if(Bot.HasInGraveyard(CardId.PacifisThePhantasmCity))
{
foreach (ClientCard s in Bot.GetGraveyardSpells())
{
if (s.IsCode(CardId.PacifisThePhantasmCity))
{
AI.SelectYesNo(true);
AI.SelectCard(s);
break;
}
}
}
else
{
foreach (ClientCard s in Bot.Hand)
{
if (s.IsCode(CardId.PacifisThePhantasmCity))
{
AI.SelectYesNo(true);
AI.SelectCard(s);
break;
}
}
}
}
else
AI.SelectYesNo(false);
return UniqueFaceupSpell();
}
else if(Card.IsFaceup())
{
ClientCard target = null;
foreach(ClientCard s in Bot.GetSpells())
{
if (s.IsCode(CardId.PacifisThePhantasmCity))
target = s;
}
if (target != null && Util.IsChainTarget(target))
{
SeaStealthAttackeff_used = true;
return true;
}
target = Util.GetLastChainCard();
if(target!=null)
{
if(target.IsCode(CardId.BrandishSkillAfterburner))
{
AI.SelectCard(CardId.MegalosmasherX);
SeaStealthAttackeff_used = true;
return true;
}
if(Enemy.GetGraveyardSpells().Count>=3 && target.IsCode(CardId.BrandishSkillJammingWave))
{
AI.SelectCard(CardId.MegalosmasherX);
SeaStealthAttackeff_used = true;
return true;
}
}
}
return false;
}
private bool PotOfDesireseff()
{
return Bot.Deck.Count >= 18;
}
private bool StarlightRoadset()
{
if (Duel.Turn > 1 && Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster())
return false;
if (Bot.HasInSpellZone(CardId.TheHugeRevolutionIsOver)) return false;
return true;
}
private bool TheHugeRevolutionIsOverset()
{
if (Duel.Turn > 1 && Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster())
return false;
if (Bot.HasInSpellZone(CardId.StarlightRoad)) return false;
return true;
}
private bool InfiniteImpermanenceset()
{
return !Bot.IsFieldEmpty();
}
private bool NoSetAlreadyDone()
{
if (Duel.Turn > 1 && Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster())
return false;
if (Bot.HasInSpellZone(Card.Id)) return false;
return true;
}
private bool SpellSeteff()
{
if (Card.HasType(CardType.Field)) return false;
if (CardOfDemiseeff_used) return true;
if(Bot.HasInHandOrInSpellZone(CardId.CardOfDemise) && !CardOfDemiseeff_used)
{
int hand_spell_count = 0;
foreach(ClientCard s in Bot.Hand)
{
if (s.HasType(CardType.Trap) || s.HasType(CardType.Spell) && !s.HasType(CardType.Field))
hand_spell_count++;
}
int zone_count = 5 - Bot.GetSpellCountWithoutField();
return zone_count- hand_spell_count >= 1;
}
if(Card.IsCode(CardId.PhantasmSprialBattle, CardId.PhantasmSpiralPower))
{
if (Bot.HasInMonstersZone(CardId.MegalosmasherX) &&
!Bot.HasInHandOrInSpellZone(CardId.PacifisThePhantasmCity) &&
!Bot.HasInHandOrInSpellZone(CardId.Metaverse))
return true;
}
return false;
}
private bool MonsterRepos()
{
if (Card.Level >= 5)
{
foreach (ClientCard s in Bot.GetSpells())
{
if (s.IsFaceup() && s.IsCode(CardId.SeaStealthAttack) &&
Bot.HasInSpellZone(CardId.PacifisThePhantasmCity) &&
Card.IsAttack())
return false;
}
}
if (Card.IsCode(CardId.EaterOfMillions) && !Card.IsDisabled() && Card.IsAttack())
return false;
return DefaultMonsterRepos();
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if(attacker.IsCode(CardId.PacifisThePhantasmCity+1) && defender.IsCode(CardId.EaterOfMillions))
{
if (attacker.RealPower >= defender.RealPower) return true;
}
if(attacker.Level>=5)
{
foreach(ClientCard s in Bot.GetSpells())
{
if (s.IsFaceup() && s.IsCode(CardId.SeaStealthAttack) && Bot.HasInSpellZone(CardId.PacifisThePhantasmCity))
{
attacker.RealPower = 9999;
if (defender.IsCode(CardId.EaterOfMillions)) return true;
}
}
}
return base.OnPreBattleBetween(attacker, defender);
}
public override ClientCard OnSelectAttacker(IList<ClientCard> attackers, IList<ClientCard> defenders)
{
for (int i = 0; i < attackers.Count; ++i)
{
ClientCard attacker = attackers[i];
if (attacker.IsCode(CardId.EaterOfMillions)) return attacker;
}
return null;
}
public override bool OnSelectHand()
{
return true;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,377 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Qliphort", "AI_Qliphort")]
public class QliphortExecutor : DefaultExecutor
{
public class CardId
{
public const int Scout = 65518099;
public const int Stealth = 13073850;
public const int Shell = 90885155;
public const int Helix = 37991342;
public const int Carrier = 91907707;
public const int DarkHole = 53129443;
public const int CardOfDemise = 59750328;
public const int SummonersArt = 79816536;
public const int PotOfDuality = 98645731;
public const int Saqlifice = 17639150;
public const int MirrorForce = 44095762;
public const int TorrentialTribute = 53582587;
public const int DimensionalBarrier = 83326048;
public const int CompulsoryEvacuationDevice = 94192409;
public const int VanitysEmptiness = 5851097;
public const int SkillDrain = 82732705;
public const int SolemnStrike = 40605147;
public const int TheHugeRevolutionIsOver = 99188141;
}
bool CardOfDemiseUsed = false;
IList<int> LowScaleCards = new[]
{
CardId.Stealth,
CardId.Carrier
};
IList<int> HighScaleCards = new[]
{
CardId.Scout,
CardId.Shell,
CardId.Helix
};
public QliphortExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.SummonersArt);
AddExecutor(ExecutorType.Activate, CardId.Scout, ScoutActivate);
AddExecutor(ExecutorType.Activate, CardId.Scout, ScoutEffect);
AddExecutor(ExecutorType.Activate, CardId.Stealth, ScaleActivate);
AddExecutor(ExecutorType.Activate, CardId.Shell, ScaleActivate);
AddExecutor(ExecutorType.Activate, CardId.Helix, ScaleActivate);
AddExecutor(ExecutorType.Activate, CardId.Carrier, ScaleActivate);
AddExecutor(ExecutorType.Summon, NormalSummon);
AddExecutor(ExecutorType.SpSummon);
AddExecutor(ExecutorType.Activate, CardId.Saqlifice, SaqlificeEffect);
AddExecutor(ExecutorType.Activate, CardId.Stealth, StealthEffect);
AddExecutor(ExecutorType.Activate, CardId.Helix, HelixEffect);
AddExecutor(ExecutorType.Activate, CardId.Carrier, CarrierEffect);
AddExecutor(ExecutorType.SpellSet, CardId.SkillDrain, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.VanitysEmptiness, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.DimensionalBarrier, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.TorrentialTribute, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.MirrorForce, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.CompulsoryEvacuationDevice, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.TheHugeRevolutionIsOver, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.Saqlifice, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.SkillDrain, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.VanitysEmptiness, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.DimensionalBarrier, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.TorrentialTribute, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.MirrorForce, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.CompulsoryEvacuationDevice, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.TheHugeRevolutionIsOver, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.DarkHole, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.SummonersArt, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.PotOfDuality, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.Activate, CardId.PotOfDuality, PotOfDualityEffect);
AddExecutor(ExecutorType.SpellSet, CardId.CardOfDemise);
AddExecutor(ExecutorType.Activate, CardId.CardOfDemise, CardOfDemiseEffect);
AddExecutor(ExecutorType.SpellSet, CardId.Saqlifice, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.SkillDrain, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.VanitysEmptiness, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.DimensionalBarrier, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.TorrentialTribute, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.MirrorForce, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.CompulsoryEvacuationDevice, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.TheHugeRevolutionIsOver, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.DarkHole, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.SummonersArt, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.PotOfDuality, CardOfDemiseAcivated);
AddExecutor(ExecutorType.Activate, CardId.TheHugeRevolutionIsOver, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, CardId.SkillDrain, SkillDrainEffect);
AddExecutor(ExecutorType.Activate, CardId.VanitysEmptiness, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.CompulsoryEvacuationDevice, DefaultCompulsoryEvacuationDevice);
AddExecutor(ExecutorType.Activate, CardId.DimensionalBarrier, DefaultDimensionalBarrier);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.TorrentialTribute, DefaultTorrentialTribute);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
public override bool OnSelectHand()
{
return true;
}
public override void OnNewTurn()
{
CardOfDemiseUsed = false;
base.OnNewTurn();
}
public override IList<ClientCard> OnSelectPendulumSummon(IList<ClientCard> cards, int max)
{
Logger.DebugWriteLine("OnSelectPendulumSummon");
// select the last cards
IList<ClientCard> selected = new List<ClientCard>();
for (int i = 1; i <= max; ++i)
{
ClientCard card = cards[cards.Count - i];
if (!card.IsCode(CardId.Scout) || (card.Location == CardLocation.Extra && !Duel.IsNewRule))
selected.Add(card);
}
if (selected.Count == 0)
selected.Add(cards[cards.Count - 1]);
return selected;
}
private bool NormalSummon()
{
if (Card.IsCode(CardId.Scout))
return false;
if (Card.Level < 8)
AI.SelectOption(1);
return true;
}
private bool SkillDrainEffect()
{
return (Bot.LifePoints > 1000) && DefaultUniqueTrap();
}
private bool PotOfDualityEffect()
{
AI.SelectCard(
CardId.Scout,
CardId.SkillDrain,
CardId.VanitysEmptiness,
CardId.DimensionalBarrier,
CardId.Stealth,
CardId.Shell,
CardId.Helix,
CardId.Carrier,
CardId.SolemnStrike,
CardId.CardOfDemise
);
return !ShouldPendulum();
}
private bool CardOfDemiseEffect()
{
if (Util.IsTurn1OrMain2() && !ShouldPendulum())
{
CardOfDemiseUsed = true;
return true;
}
return false;
}
private bool TrapSetUnique()
{
foreach (ClientCard card in Bot.GetSpells())
{
if (card.IsCode(Card.Id))
return false;
}
return TrapSetWhenZoneFree();
}
private bool TrapSetWhenZoneFree()
{
return Bot.GetSpellCountWithoutField() < 4;
}
private bool CardOfDemiseAcivated()
{
return CardOfDemiseUsed;
}
private bool SaqlificeEffect()
{
if (Card.Location == CardLocation.Grave)
{
ClientCard l = Util.GetPZone(0, 0);
ClientCard r = Util.GetPZone(0, 1);
if (l == null && r == null)
AI.SelectCard(CardId.Scout);
}
return true;
}
private bool ScoutActivate()
{
if (Card.Location != CardLocation.Hand)
return false;
ClientCard l = Util.GetPZone(0, 0);
ClientCard r = Util.GetPZone(0, 1);
if (l == null && r == null)
return true;
if (l == null && r.RScale != Card.LScale)
return true;
if (r == null && l.LScale != Card.RScale)
return true;
return false;
}
private bool ScaleActivate()
{
if (!Card.HasType(CardType.Pendulum) || Card.Location != CardLocation.Hand)
return false;
int count = 0;
foreach (ClientCard card in Bot.Hand.GetMonsters())
{
if (!Card.Equals(card))
count++;
}
foreach (ClientCard card in Bot.ExtraDeck.GetFaceupPendulumMonsters())
{
count++;
}
ClientCard l = Util.GetPZone(0, 0);
ClientCard r = Util.GetPZone(0, 1);
if (l == null && r == null)
{
if (CardOfDemiseUsed)
return true;
bool pair = false;
foreach (ClientCard card in Bot.Hand.GetMonsters())
{
if (card.RScale != Card.LScale)
{
pair = true;
count--;
break;
}
}
return pair && count>1;
}
if (l == null && r.RScale != Card.LScale)
return count > 1 || CardOfDemiseUsed;
if (r == null && l.LScale != Card.RScale)
return count > 1 || CardOfDemiseUsed;
return false;
}
private bool ScoutEffect()
{
if (Card.Location == CardLocation.Hand)
return false;
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
int count = 0;
int handcount = 0;
int fieldcount = 0;
foreach (ClientCard card in Bot.Hand.GetMonsters())
{
count++;
handcount++;
}
foreach (ClientCard card in Bot.MonsterZone.GetMonsters())
{
fieldcount++;
}
foreach (ClientCard card in Bot.ExtraDeck.GetFaceupPendulumMonsters())
{
count++;
}
if (count>0 && !Bot.HasInHand(LowScaleCards))
{
AI.SelectCard(LowScaleCards);
}
else if (handcount>0 || fieldcount>0)
{
AI.SelectCard(CardId.Saqlifice, CardId.Shell, CardId.Helix);
}
else
{
AI.SelectCard(HighScaleCards);
}
return Bot.LifePoints > 800;
}
private bool StealthEffect()
{
if (Card.Location == CardLocation.Hand)
return false;
ClientCard target = Util.GetBestEnemyCard();
if (target != null)
{
AI.SelectCard(target);
return true;
}
return false;
}
private bool CarrierEffect()
{
if (Card.Location == CardLocation.Hand)
return false;
ClientCard target = Util.GetBestEnemyMonster();
if (target != null)
{
AI.SelectCard(target);
return true;
}
return false;
}
private bool HelixEffect()
{
if (Card.Location == CardLocation.Hand)
return false;
ClientCard target = Util.GetBestEnemySpell();
if (target != null)
{
AI.SelectCard(target);
return true;
}
return false;
}
private bool ShouldPendulum()
{
ClientCard l = Util.GetPZone(0, 0);
ClientCard r = Util.GetPZone(0, 1);
if (l != null && r != null && l.LScale != r.RScale)
{
int count = 0;
foreach (ClientCard card in Bot.Hand.GetMonsters())
{
count++;
}
foreach (ClientCard card in Bot.ExtraDeck.GetFaceupPendulumMonsters())
{
count++;
}
return count > 1;
}
return false;
}
}
}
@@ -0,0 +1,442 @@
using System;
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Rainbow", "AI_Rainbow")]
class RainbowExecutor : DefaultExecutor
{
public class CardId
{
public const int MysteryShellDragon = 18108166;
public const int PhantomGryphon = 74852097;
public const int MasterPendulumTheDracoslayer = 75195825;
public const int AngelTrumpeter = 87979586;
public const int MetalfoesGoldriver = 33256280;
public const int MegalosmasherX = 81823360;
public const int RescueRabbit = 85138716;
public const int UnexpectedDai = 911883;
public const int HarpiesFeatherDuster = 18144506;
public const int PotOfDesires = 35261759;
public const int MonsterReborn = 83764718;
public const int SmashingGround = 97169186;
public const int QuakingMirrorForce = 40838625;
public const int DrowningMirrorForce = 47475363;
public const int BlazingMirrorForce = 75249652;
public const int StormingMirrorForce = 5650082;
public const int MirrorForce = 44095762;
public const int DarkMirrorForce = 20522190;
public const int BottomlessTrapHole = 29401950;
public const int TraptrixTrapHoleNightmare = 29616929;
public const int StarlightRoad = 58120309;
public const int ScarlightRedDragonArchfiend = 80666118;
public const int IgnisterProminenceTheBlastingDracoslayer = 18239909;
public const int StardustDragon = 44508094;
public const int NumberS39UtopiatheLightning = 56832966;
public const int Number37HopeWovenDragonSpiderShark = 37279508;
public const int Number39Utopia = 84013237;
public const int EvolzarLaggia = 74294676;
public const int Number59CrookedCook = 82697249;
public const int CastelTheSkyblasterMusketeer = 82633039;
public const int StarliegePaladynamo = 61344030;
public const int LightningChidori = 22653490;
public const int EvilswarmExcitonKnight = 46772449;
public const int GagagaCowboy = 12014404;
public const int EvilswarmNightmare = 359563;
public const int TraptrixRafflesia = 6511113;
}
private bool NormalSummoned = false;
public RainbowExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster);
AddExecutor(ExecutorType.Activate, CardId.UnexpectedDai, UnexpectedDaiEffect);
AddExecutor(ExecutorType.Summon, CardId.RescueRabbit, RescueRabbitSummon);
AddExecutor(ExecutorType.Activate, CardId.RescueRabbit, RescueRabbitEffect);
AddExecutor(ExecutorType.Activate, CardId.PotOfDesires, DefaultPotOfDesires);
AddExecutor(ExecutorType.Summon, CardId.AngelTrumpeter, AngelTrumpeterSummon);
AddExecutor(ExecutorType.Summon, CardId.MegalosmasherX, MegalosmasherXSummon);
AddExecutor(ExecutorType.Summon, CardId.MasterPendulumTheDracoslayer, MasterPendulumTheDracoslayerSummon);
AddExecutor(ExecutorType.Summon, CardId.MysteryShellDragon, MysteryShellDragonSummon);
AddExecutor(ExecutorType.Summon, CardId.PhantomGryphon, PhantomGryphonSummon);
AddExecutor(ExecutorType.Summon, CardId.MetalfoesGoldriver, MetalfoesGoldriverSummon);
AddExecutor(ExecutorType.Summon, NormalSummon);
AddExecutor(ExecutorType.SpSummon, CardId.IgnisterProminenceTheBlastingDracoslayer, IgnisterProminenceTheBlastingDracoslayerSummon);
AddExecutor(ExecutorType.Activate, CardId.IgnisterProminenceTheBlastingDracoslayer, IgnisterProminenceTheBlastingDracoslayerEffect);
AddExecutor(ExecutorType.SpSummon, CardId.GagagaCowboy, GagagaCowboySummon);
AddExecutor(ExecutorType.Activate, CardId.GagagaCowboy);
AddExecutor(ExecutorType.SpSummon, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightSummon);
AddExecutor(ExecutorType.Activate, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect);
AddExecutor(ExecutorType.SpSummon, CardId.EvolzarLaggia, EvolzarLaggiaSummon);
AddExecutor(ExecutorType.Activate, CardId.EvolzarLaggia, EvolzarLaggiaEffect);
AddExecutor(ExecutorType.SpSummon, CardId.EvilswarmNightmare, EvilswarmNightmareSummon);
AddExecutor(ExecutorType.Activate, CardId.EvilswarmNightmare);
AddExecutor(ExecutorType.SpSummon, CardId.StarliegePaladynamo, StarliegePaladynamoSummon);
AddExecutor(ExecutorType.Activate, CardId.StarliegePaladynamo, StarliegePaladynamoEffect);
AddExecutor(ExecutorType.SpSummon, CardId.LightningChidori, LightningChidoriSummon);
AddExecutor(ExecutorType.Activate, CardId.LightningChidori, LightningChidoriEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Number37HopeWovenDragonSpiderShark, Number37HopeWovenDragonSpiderSharkSummon);
AddExecutor(ExecutorType.Activate, CardId.Number37HopeWovenDragonSpiderShark);
AddExecutor(ExecutorType.SpSummon, CardId.TraptrixRafflesia, TraptrixRafflesiaSummon);
AddExecutor(ExecutorType.Activate, CardId.TraptrixRafflesia);
AddExecutor(ExecutorType.Activate, CardId.SmashingGround, DefaultSmashingGround);
AddExecutor(ExecutorType.SpSummon, CardId.CastelTheSkyblasterMusketeer, DefaultCastelTheSkyblasterMusketeerSummon);
AddExecutor(ExecutorType.Activate, CardId.CastelTheSkyblasterMusketeer, DefaultCastelTheSkyblasterMusketeerEffect);
AddExecutor(ExecutorType.SpSummon, CardId.IgnisterProminenceTheBlastingDracoslayer, IgnisterProminenceTheBlastingDracoslayerSummon);
AddExecutor(ExecutorType.Activate, CardId.IgnisterProminenceTheBlastingDracoslayer, IgnisterProminenceTheBlastingDracoslayerEffect);
AddExecutor(ExecutorType.SpSummon, CardId.ScarlightRedDragonArchfiend, DefaultScarlightRedDragonArchfiendSummon);
AddExecutor(ExecutorType.Activate, CardId.ScarlightRedDragonArchfiend, DefaultScarlightRedDragonArchfiendEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Number39Utopia, DefaultNumberS39UtopiaTheLightningSummon);
AddExecutor(ExecutorType.SpSummon, CardId.NumberS39UtopiatheLightning);
AddExecutor(ExecutorType.Activate, CardId.NumberS39UtopiatheLightning, DefaultNumberS39UtopiaTheLightningEffect);
AddExecutor(ExecutorType.SpSummon, CardId.StardustDragon, DefaultStardustDragonSummon);
AddExecutor(ExecutorType.Activate, CardId.StardustDragon, DefaultStardustDragonEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Number59CrookedCook, Number59CrookedCookSummon);
AddExecutor(ExecutorType.Activate, CardId.Number59CrookedCook, Number59CrookedCookEffect);
AddExecutor(ExecutorType.SpellSet, CardId.StarlightRoad, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.QuakingMirrorForce, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.DrowningMirrorForce, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.BlazingMirrorForce, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.StormingMirrorForce, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.MirrorForce, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.DarkMirrorForce, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.BottomlessTrapHole, TrapSet);
AddExecutor(ExecutorType.SpellSet, CardId.TraptrixTrapHoleNightmare, TrapSet);
AddExecutor(ExecutorType.Activate, CardId.StarlightRoad, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.QuakingMirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.DrowningMirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.BlazingMirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.StormingMirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.DarkMirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.BottomlessTrapHole, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.TraptrixTrapHoleNightmare, DefaultUniqueTrap);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
public override void OnNewTurn()
{
NormalSummoned = false;
base.OnNewTurn();
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (!defender.IsMonsterHasPreventActivationEffectInBattle())
{
if (Bot.HasInMonstersZone(CardId.Number37HopeWovenDragonSpiderShark, true, true))
attacker.RealPower = attacker.RealPower + 1000;
}
return base.OnPreBattleBetween(attacker, defender);
}
public override IList<ClientCard> OnSelectXyzMaterial(IList<ClientCard> cards, int min, int max)
{
// select cards with same name (summoned by rescue rabbit)
Logger.DebugWriteLine("OnSelectXyzMaterial " + cards.Count + " " + min + " " + max);
IList<ClientCard> result = new List<ClientCard>();
foreach (ClientCard card1 in cards)
{
foreach (ClientCard card2 in cards)
{
if (card1.IsCode(card2.Id) && !card1.Equals(card2))
{
result.Add(card1);
result.Add(card2);
break;
}
}
if (result.Count > 0)
break;
}
return Util.CheckSelectCount(result, cards, min, max);
}
private bool UnexpectedDaiEffect()
{
if (Bot.HasInHand(CardId.RescueRabbit) || NormalSummoned)
AI.SelectCard(
CardId.MysteryShellDragon,
CardId.PhantomGryphon,
CardId.MegalosmasherX
);
else if (Util.IsTurn1OrMain2())
{
if (Bot.HasInHand(CardId.MysteryShellDragon))
AI.SelectCard(CardId.MysteryShellDragon);
else if (Bot.HasInHand(CardId.MegalosmasherX))
AI.SelectCard(CardId.MegalosmasherX);
else if (Bot.HasInHand(CardId.AngelTrumpeter))
AI.SelectCard(CardId.AngelTrumpeter);
}
else
{
if (Bot.HasInHand(CardId.MegalosmasherX))
AI.SelectCard(CardId.MegalosmasherX);
else if (Bot.HasInHand(CardId.MasterPendulumTheDracoslayer))
AI.SelectCard(CardId.MasterPendulumTheDracoslayer);
else if (Bot.HasInHand(CardId.PhantomGryphon))
AI.SelectCard(CardId.PhantomGryphon);
else if (Bot.HasInHand(CardId.AngelTrumpeter))
AI.SelectCard(CardId.MetalfoesGoldriver, CardId.MasterPendulumTheDracoslayer);
}
return true;
}
private bool RescueRabbitSummon()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
return Util.GetBotAvailZonesFromExtraDeck() > 0
|| !Enemy.MonsterZone.IsExistingMatchingCard(card => card.GetDefensePower() >= 1900)
|| Enemy.MonsterZone.GetMatchingCardsCount(card => card.GetDefensePower() < 1900) > Bot.MonsterZone.GetMatchingCardsCount(card => card.Attack >= 1900);
}
private bool RescueRabbitEffect()
{
if (Util.IsTurn1OrMain2())
{
AI.SelectCard(
CardId.MegalosmasherX,
CardId.MysteryShellDragon
);
}
else
{
AI.SelectCard(
CardId.MasterPendulumTheDracoslayer,
CardId.PhantomGryphon,
CardId.MegalosmasherX,
CardId.MetalfoesGoldriver,
CardId.AngelTrumpeter
);
}
return true;
}
private bool MysteryShellDragonSummon()
{
return Bot.HasInMonstersZone(CardId.MysteryShellDragon);
}
private bool PhantomGryphonSummon()
{
return Bot.HasInMonstersZone(CardId.PhantomGryphon);
}
private bool MasterPendulumTheDracoslayerSummon()
{
return Bot.HasInMonstersZone(CardId.MasterPendulumTheDracoslayer);
}
private bool AngelTrumpeterSummon()
{
return Bot.HasInMonstersZone(CardId.AngelTrumpeter);
}
private bool MetalfoesGoldriverSummon()
{
return Bot.HasInMonstersZone(CardId.MetalfoesGoldriver);
}
private bool MegalosmasherXSummon()
{
return Bot.HasInMonstersZone(CardId.MegalosmasherX);
}
private bool NormalSummon()
{
return Card.Id != CardId.RescueRabbit;
}
private bool GagagaCowboySummon()
{
if (Enemy.LifePoints <= 800)
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool IgnisterProminenceTheBlastingDracoslayerSummon()
{
return Util.GetProblematicEnemyCard() != null;
}
private bool IgnisterProminenceTheBlastingDracoslayerEffect()
{
if (ActivateDescription == Util.GetStringId(CardId.IgnisterProminenceTheBlastingDracoslayer, 1))
return true;
ClientCard target1 = null;
ClientCard target2 = Util.GetProblematicEnemyCard();
List<ClientCard> spells = Enemy.GetSpells();
foreach (ClientCard spell in spells)
{
if (spell.HasType(CardType.Pendulum) && !spell.Equals(target2))
{
target1 = spell;
break;
}
}
List<ClientCard> monsters = Enemy.GetMonsters();
foreach (ClientCard monster in monsters)
{
if (monster.HasType(CardType.Pendulum) && !monster.Equals(target2))
{
target1 = monster;
break;
}
}
if (target2 == null && target1 != null)
{
foreach (ClientCard spell in spells)
{
if (!spell.Equals(target1))
{
target2 = spell;
break;
}
}
foreach (ClientCard monster in monsters)
{
if (!monster.Equals(target1))
{
target2 = monster;
break;
}
}
}
if (target2 == null)
return false;
AI.SelectCard(target1);
AI.SelectNextCard(target2);
return true;
}
private bool Number37HopeWovenDragonSpiderSharkSummon()
{
return Util.IsAllEnemyBetterThanValue(1700, false) && !Util.IsOneEnemyBetterThanValue(3600, true);
}
private bool LightningChidoriSummon()
{
foreach (ClientCard monster in Enemy.GetMonsters())
{
if (monster.IsFacedown())
{
return true;
}
}
foreach (ClientCard spell in Enemy.GetSpells())
{
if (spell.IsFacedown())
{
return true;
}
}
return Util.GetProblematicEnemyCard() != null;
}
private bool LightningChidoriEffect()
{
ClientCard problematicCard = Util.GetProblematicEnemyCard();
AI.SelectCard(0);
AI.SelectNextCard(problematicCard);
return true;
}
private bool EvolzarLaggiaSummon()
{
return (Util.IsAllEnemyBetterThanValue(2000, false) && !Util.IsOneEnemyBetterThanValue(2400, true)) || Util.IsTurn1OrMain2();
}
private bool EvilswarmNightmareSummon()
{
if (Util.IsTurn1OrMain2())
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool TraptrixRafflesiaSummon()
{
if (Util.IsTurn1OrMain2() && (Bot.GetRemainingCount(CardId.BottomlessTrapHole, 1) + Bot.GetRemainingCount(CardId.TraptrixTrapHoleNightmare, 1)) > 0)
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool Number59CrookedCookSummon()
{
return ((Bot.GetMonsterCount() + Bot.GetSpellCount() - 2) <= 1) &&
((Util.IsOneEnemyBetter() && !Util.IsOneEnemyBetterThanValue(2300, true)) || Util.IsTurn1OrMain2());
}
private bool Number59CrookedCookEffect()
{
if (Duel.Player == 0)
{
if (Util.IsChainTarget(Card))
return true;
}
else
{
if ((Bot.GetMonsterCount() + Bot.GetSpellCount() -1) <= 1)
return true;
}
return false;
}
private bool EvolzarLaggiaEffect()
{
return DefaultTrap();
}
private bool StarliegePaladynamoSummon()
{
return StarliegePaladynamoEffect();
}
private bool StarliegePaladynamoEffect()
{
ClientCard result = Util.GetOneEnemyBetterThanValue(2000, true);
if (result != null)
{
AI.SelectCard(0);
AI.SelectNextCard(result);
return true;
}
return false;
}
private bool TrapSet()
{
return !Bot.HasInMonstersZone(CardId.Number59CrookedCook, true, true);
}
}
}
@@ -0,0 +1,399 @@
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game.AI.Decks
{
[Deck("Rank V", "AI_Rank5")]
public class Rank5Executor : DefaultExecutor
{
public class CardId
{
public const int MistArchfiend = 28601770;
public const int CyberDragon = 70095154;
public const int ZWEagleClaw = 29353756;
public const int SolarWindJammer = 33911264;
public const int QuickdrawSynchron = 20932152;
public const int WindUpSoldier = 12299841;
public const int StarDrawing = 24610207;
public const int ChronomalyGoldenJet = 88552992;
public const int InstantFusion = 1845204;
public const int DoubleSummon = 43422537;
public const int MysticalSpaceTyphoon = 5318639;
public const int BookOfMoon = 14087893;
public const int XyzUnit = 13032689;
public const int XyzReborn = 26708437;
public const int MirrorForce = 44095762;
public const int TorrentialTribute = 53582587;
public const int XyzVeil = 96457619;
public const int PanzerDragon = 72959823;
public const int GaiaDragonTheThunderCharger = 91949988;
public const int CyberDragonInfinity = 10443957;
public const int TirasKeeperOfGenesis = 31386180;
public const int Number61Volcasaurus = 29669359;
public const int SharkFortress = 50449881;
public const int CyberDragonNova = 58069384;
}
private bool NormalSummoned = false;
private bool InstantFusionUsed = false;
private bool DoubleSummonUsed = false;
private bool CyberDragonInfinitySummoned = false;
private bool Number61VolcasaurusUsed = false;
public Rank5Executor(GameAI ai, Duel duel)
: base(ai, duel)
{
// Quick spells
AddExecutor(ExecutorType.Activate, CardId.BookOfMoon, DefaultBookOfMoon);
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
// Cyber Dragon Infinity first
AddExecutor(ExecutorType.SpSummon, CardId.CyberDragonNova, CyberDragonNovaSummon);
AddExecutor(ExecutorType.Activate, CardId.CyberDragonNova, CyberDragonNovaEffect);
AddExecutor(ExecutorType.SpSummon, CardId.CyberDragonInfinity, CyberDragonInfinitySummon);
AddExecutor(ExecutorType.Activate, CardId.CyberDragonInfinity, CyberDragonInfinityEffect);
// Level 5 monsters without side effects
AddExecutor(ExecutorType.SpSummon, CardId.CyberDragon);
AddExecutor(ExecutorType.SpSummon, CardId.ZWEagleClaw);
AddExecutor(ExecutorType.Summon, CardId.ChronomalyGoldenJet, NormalSummon);
AddExecutor(ExecutorType.Activate, CardId.ChronomalyGoldenJet, ChronomalyGoldenJetEffect);
AddExecutor(ExecutorType.Summon, CardId.StarDrawing, NormalSummon);
AddExecutor(ExecutorType.Summon, CardId.WindUpSoldier, NormalSummon);
AddExecutor(ExecutorType.Activate, CardId.WindUpSoldier, WindUpSoldierEffect);
// XYZ Monsters: Summon
AddExecutor(ExecutorType.SpSummon, CardId.Number61Volcasaurus, Number61VolcasaurusSummon);
AddExecutor(ExecutorType.Activate, CardId.Number61Volcasaurus, Number61VolcasaurusEffect);
AddExecutor(ExecutorType.SpSummon, CardId.TirasKeeperOfGenesis);
AddExecutor(ExecutorType.Activate, CardId.TirasKeeperOfGenesis, TirasKeeperOfGenesisEffect);
AddExecutor(ExecutorType.SpSummon, CardId.SharkFortress);
AddExecutor(ExecutorType.Activate, CardId.SharkFortress);
AddExecutor(ExecutorType.SpSummon, CardId.GaiaDragonTheThunderCharger, GaiaDragonTheThunderChargerSummon);
// Level 5 monsters with side effects
AddExecutor(ExecutorType.SpSummon, CardId.SolarWindJammer, SolarWindJammerSummon);
AddExecutor(ExecutorType.SpSummon, CardId.QuickdrawSynchron, QuickdrawSynchronSummon);
AddExecutor(ExecutorType.Summon, CardId.MistArchfiend, MistArchfiendSummon);
AddExecutor(ExecutorType.Activate, CardId.InstantFusion, InstantFusionEffect);
// Useful spells
AddExecutor(ExecutorType.Activate, CardId.DoubleSummon, DoubleSummonEffect);
AddExecutor(ExecutorType.Activate, CardId.XyzUnit, XyzUnitEffect);
AddExecutor(ExecutorType.Activate, CardId.XyzReborn, XyzRebornEffect);
AddExecutor(ExecutorType.Activate, CardId.PanzerDragon, PanzerDragonEffect);
// Reposition
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
// Set and activate traps
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Activate, CardId.XyzVeil, XyzVeilEffect);
AddExecutor(ExecutorType.Activate, CardId.TorrentialTribute, DefaultTorrentialTribute);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultTrap);
}
public override bool OnSelectHand()
{
return false;
}
public override void OnNewTurn()
{
NormalSummoned = false;
InstantFusionUsed = false;
DoubleSummonUsed = false;
CyberDragonInfinitySummoned = false;
Number61VolcasaurusUsed = false;
base.OnNewTurn();
}
public override IList<ClientCard> OnSelectXyzMaterial(IList<ClientCard> cards, int min, int max)
{
IList<ClientCard> result = Util.SelectPreferredCards(new[] {
CardId.MistArchfiend,
CardId.PanzerDragon,
CardId.SolarWindJammer,
CardId.StarDrawing
}, cards, min, max);
return Util.CheckSelectCount(result, cards, min, max);
}
private bool NormalSummon()
{
NormalSummoned = true;
return true;
}
private bool SolarWindJammerSummon()
{
if (!NeedLV5())
return false;
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool QuickdrawSynchronSummon()
{
if (!NeedLV5())
return false;
AI.SelectCard(
CardId.QuickdrawSynchron,
CardId.ZWEagleClaw,
CardId.SolarWindJammer,
CardId.CyberDragon,
CardId.MistArchfiend,
CardId.WindUpSoldier,
CardId.StarDrawing,
CardId.ChronomalyGoldenJet
);
return true;
}
private bool MistArchfiendSummon()
{
if (!NeedLV5())
return false;
AI.SelectOption(1);
NormalSummoned = true;
return true;
}
private bool InstantFusionEffect()
{
if (!NeedLV5())
return false;
InstantFusionUsed = true;
return true;
}
private bool NeedLV5()
{
if (HaveOtherLV5OnField())
return true;
if (Util.GetBotAvailZonesFromExtraDeck() == 0)
return false;
int lv5Count = 0;
foreach (ClientCard card in Bot.Hand)
{
if (card.IsCode(CardId.SolarWindJammer) && Bot.GetMonsterCount() == 0)
++lv5Count;
if (card.IsCode(CardId.InstantFusion) && !InstantFusionUsed)
++lv5Count;
if (card.IsCode(CardId.QuickdrawSynchron) && Bot.Hand.ContainsMonsterWithLevel(4))
++lv5Count;
if (card.IsCode(CardId.MistArchfiend) && !NormalSummoned)
++lv5Count;
if (card.IsCode(CardId.DoubleSummon) && DoubleSummonEffect())
++lv5Count;
}
if (lv5Count >= 2)
return true;
return false;
}
private bool WindUpSoldierEffect()
{
return HaveOtherLV5OnField();
}
private bool ChronomalyGoldenJetEffect()
{
return Card.Level == 4;
}
private bool DoubleSummonEffect()
{
if (!NormalSummoned || DoubleSummonUsed)
return false;
if (Bot.HasInHand(new[]
{
CardId.WindUpSoldier,
CardId.StarDrawing,
CardId.ChronomalyGoldenJet,
CardId.MistArchfiend
}))
{
NormalSummoned = false;
DoubleSummonUsed = true;
return true;
}
return false;
}
private bool CyberDragonNovaSummon()
{
return !CyberDragonInfinitySummoned;
}
private bool CyberDragonNovaEffect()
{
if (ActivateDescription == Util.GetStringId(CardId.CyberDragonNova, 0))
{
return true;
}
else if (Card.Location == CardLocation.Grave)
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
else
{
return false;
}
}
private bool CyberDragonInfinitySummon()
{
CyberDragonInfinitySummoned = true;
return true;
}
private bool CyberDragonInfinityEffect()
{
if (Duel.CurrentChain.Count > 0)
{
return Duel.LastChainPlayer == 1;
}
else
{
ClientCard bestmonster = null;
foreach (ClientCard monster in Enemy.GetMonsters())
{
if (monster.IsAttack() && (bestmonster == null || monster.Attack >= bestmonster.Attack))
bestmonster = monster;
}
if (bestmonster != null)
{
AI.SelectCard(bestmonster);
return true;
}
}
return false;
}
private bool Number61VolcasaurusSummon()
{
return Util.IsOneEnemyBetterThanValue(2000, false);
}
private bool Number61VolcasaurusEffect()
{
ClientCard target = Util.GetProblematicEnemyMonster(2000);
if (target != null)
{
AI.SelectCard(CardId.CyberDragon);
AI.SelectNextCard(target);
Number61VolcasaurusUsed = true;
return true;
}
return false;
}
private bool TirasKeeperOfGenesisEffect()
{
ClientCard target = Util.GetProblematicEnemyCard();
if (target == null)
target = Util.GetBestEnemyCard();
if (target != null)
{
AI.SelectCard(target);
}
return true;
}
private bool GaiaDragonTheThunderChargerSummon()
{
if (Number61VolcasaurusUsed && Bot.HasInMonstersZone(CardId.Number61Volcasaurus))
{
AI.SelectCard(CardId.Number61Volcasaurus);
return true;
}
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasType(CardType.Xyz) && !monster.HasXyzMaterial())
{
AI.SelectCard(monster);
return true;
}
}
return false;
}
private bool XyzRebornEffect()
{
if (!UniqueFaceupSpell())
return false;
AI.SelectCard(
CardId.CyberDragonInfinity,
CardId.CyberDragonNova,
CardId.TirasKeeperOfGenesis,
CardId.SharkFortress,
CardId.Number61Volcasaurus
);
return true;
}
private bool XyzUnitEffect()
{
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasType(CardType.Xyz))
{
AI.SelectCard(monster);
return true;
}
}
return false;
}
private bool PanzerDragonEffect()
{
ClientCard target = Util.GetBestEnemyCard();
if (target != null)
{
AI.SelectCard(target);
return true;
}
return false;
}
private bool XyzVeilEffect()
{
if (!UniqueFaceupSpell())
return false;
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasType(CardType.Xyz))
return true;
}
return false;
}
private bool HaveOtherLV5OnField()
{
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.HasType(CardType.Monster) &&
!monster.HasType(CardType.Xyz) &&
Util.GetBotAvailZonesFromExtraDeck(monster) > 0 &&
(monster.Level == 5
|| monster.IsCode(CardId.StarDrawing)
|| monster.IsCode(CardId.WindUpSoldier) && !monster.Equals(Card)))
return true;
}
return false;
}
}
}
@@ -0,0 +1,332 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using System.Linq;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using System;
namespace WindBot.Game.AI.Decks
{
[Deck("RushDinocarriageDynarmix", "AI_RushDinocarriageDynarmix")]
public class RushDinocarriageDynarmixExecutor : DefaultExecutor
{
public class CardId
{
public const int 超级恐龙王 = 120130029;
public const int 巨身多角龙 = 120130005;
public const int 荒野盗龙 = 120151012;
public const int 名流雷龙 = 120151013;
public const int 抑龙 = 120151011;
public const int 机械镰刀盗龙 = 120151009;
public const int 成金恐龙王 = 120151010;
public const int 侏罗纪世界 = 120151015;
public const int 奇迹的共进化 = 120151016;
public const int 成金哥布林 = 120151018;
public const int 恐龙粉碎 = 120151017;
public const int 超越进化 = 120151019;
public const int 恐力重压 = 120151020;
public const int 大恐龙驾L = 120151005;
public const int 大恐龙驾R = 120151007;
public const int 大恐龙驾 = 120151006;
}
public RushDinocarriageDynarmixExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpSummon, CardId.大恐龙驾, MAXsummon);
AddExecutor(ExecutorType.Activate, CardId.大恐龙驾, 大恐龙驾Effect);
AddExecutor(ExecutorType.Activate, CardId.成金哥布林);
AddExecutor(ExecutorType.Activate, CardId.抑龙);
AddExecutor(ExecutorType.Activate, CardId.成金恐龙王, 成金恐龙王Effect);
AddExecutor(ExecutorType.Activate, CardId.机械镰刀盗龙, 机械镰刀盗龙Effect);
AddExecutor(ExecutorType.Activate, CardId.奇迹的共进化, 奇迹的共进化Effect);
AddExecutor(ExecutorType.Summon, CardId.巨身多角龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.Activate, CardId.超级恐龙王, 超级恐龙王Effect);
AddExecutor(ExecutorType.Summon, CardId.机械镰刀盗龙);
AddExecutor(ExecutorType.Summon, CardId.抑龙, 抑龙Summon);
AddExecutor(ExecutorType.Summon, CardId.成金恐龙王, 成金恐龙王Summon);
AddExecutor(ExecutorType.Activate, CardId.恐龙粉碎, 恐龙粉碎Effect);
AddExecutor(ExecutorType.SummonOrSet, CardId.荒野盗龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.SummonOrSet, CardId.名流雷龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.超级恐龙王, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.大恐龙驾L, MAXLsummon);
AddExecutor(ExecutorType.Summon, CardId.大恐龙驾R, MAXRsummon);
AddExecutor(ExecutorType.MonsterSet, CardId.大恐龙驾L, MAXLset);
AddExecutor(ExecutorType.MonsterSet, CardId.大恐龙驾R, MAXRset);
AddExecutor(ExecutorType.MonsterSet, CardId.抑龙);
AddExecutor(ExecutorType.MonsterSet, CardId.成金恐龙王);
AddExecutor(ExecutorType.MonsterSet, CardId.名流雷龙, monsterset);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.Activate, CardId.侏罗纪世界);
AddExecutor(ExecutorType.Activate, CardId.恐力重压);
AddExecutor(ExecutorType.Activate, CardId.超越进化, 超越进化Effect);
AddExecutor(ExecutorType.SpellSet);
//AddExecutor(ExecutorType.Activate, DefaultDontChainMyself);
}
private bool 大恐龙驾Effect()
{
{
IList<ClientCard> targets = new List<ClientCard>();
foreach (ClientCard target in Enemy.GetMonsters())
{
if (target.IsFacedown())
targets.Add(target);
if (targets.Count >= 2)
break;
}
if (targets.Count < 2)
{
foreach (ClientCard target in Enemy.GetMonsters())
{
if (target.IsFaceup())
targets.Add(target);
if (targets.Count >= 2)
break;
}
}
if (targets.Count > 0)
{
AI.SelectCard(
CardId.抑龙,
CardId.名流雷龙,
CardId.荒野盗龙,
CardId.巨身多角龙,
CardId.成金恐龙王,
CardId.机械镰刀盗龙,
CardId.超级恐龙王,
CardId.大恐龙驾,
CardId.大恐龙驾L,
CardId.大恐龙驾R
);
AI.SelectNextCard(targets);
return true;
}
return false;
}
}
private bool MAXsummon()
{
if (Bot.HasInMonstersZone(CardId.大恐龙驾))
{
return false;
}
else
AI.SelectCard(CardId.大恐龙驾L);
AI.SelectNextCard(CardId.大恐龙驾R);
return true;
}
private List<int> HintMsgForEnemy = new List<int>
{
HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck,
HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Disable
};
private List<int> HintMsgForMaxSelect = new List<int>
{
HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.AddToHand, HintMsg.ToDeck, HintMsg.Destroy
};
public override IList<ClientCard> OnSelectCard(IList<ClientCard> _cards, int min, int max, int hint, bool cancelable)
{
if (Duel.Phase == DuelPhase.BattleStart)
return null;
if (AI.HaveSelectedCards())
return null;
IList<ClientCard> selected = new List<ClientCard>();
IList<ClientCard> cards = new List<ClientCard>(_cards);
if (max > cards.Count)
max = cards.Count;
if (HintMsgForEnemy.Contains(hint))
{
IList<ClientCard> enemyCards = cards.Where(card => card.Controller == 1).ToList();
// select enemy's card first
while (enemyCards.Count > 0 && selected.Count < max)
{
ClientCard card = enemyCards[Program.Rand.Next(enemyCards.Count)];
selected.Add(card);
enemyCards.Remove(card);
cards.Remove(card);
}
}
if (HintMsgForMaxSelect.Contains(hint))
{
// select max cards
while (selected.Count < max)
{
ClientCard card = cards[Program.Rand.Next(cards.Count)];
selected.Add(card);
cards.Remove(card);
}
}
return selected;
}
public override bool OnSelectHand()
{
// go first
return true;
}
public bool monsterset()
{
if (Duel.Turn == 1)
{
return true;
}
else if (Bot.HasInHand(new[] {
CardId.巨身多角龙,
CardId.超级恐龙王,
}))
return false;
return true;
}
private bool 抑龙Summon()
{
if (Duel.Turn == 1) return false;
if (Enemy.GetHandCount() > 1) return true;
return false;
}
private bool 成金恐龙王Summon()
{
if (Enemy.GetHandCount() < 1) return true;
return false;
}
private bool 成金恐龙王Effect()
{
AI.SelectCard(CardId.成金哥布林);
return true;
}
private bool 奇迹的共进化Effect()
{
if (Bot.HasInHand(CardId.超级恐龙王))
{
if (Bot.HasInMonstersZone(CardId.大恐龙驾))
{
return false;
}
else
AI.SelectCard(
CardId.大恐龙驾L,
CardId.大恐龙驾R,
CardId.抑龙,
CardId.名流雷龙,
CardId.荒野盗龙,
CardId.巨身多角龙
);
AI.SelectNextCard(CardId.超级恐龙王);
return true;
}
return false;
}
private bool 机械镰刀盗龙Effect()
{
if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾) >= 2) AI.SelectCard(CardId.大恐龙驾);
else
if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾L) >= 2) AI.SelectCard(CardId.大恐龙驾L);
else
if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾R) >= 2) AI.SelectCard(CardId.大恐龙驾R);
else
if (Bot.GetCountCardInZone(Bot.Hand, CardId.超级恐龙王) >= 2) AI.SelectCard(CardId.超级恐龙王);
else
AI.SelectCard(
CardId.抑龙,
CardId.名流雷龙,
CardId.荒野盗龙,
CardId.巨身多角龙,
CardId.成金恐龙王,
CardId.机械镰刀盗龙
);
return true;
}
private bool 恐龙粉碎Effect()
{
ClientCard check = null;
List<ClientCard> spells = Enemy.GetSpells(); List<ClientCard> mons = Enemy.GetMonsters();
foreach (ClientCard spell in spells) foreach (ClientCard mon in mons)
{
if (Bot.HasInMonstersZone(CardId.大恐龙驾) && mon.IsFacedown()) check = mon;
else if (Bot.HasInMonstersZone(CardId.大恐龙驾) && spell.IsFacedown()) check = spell;
else if (spell.IsFacedown()) check = spell;
else check = mon;
}
if (Bot.GetCountCardInZone(Bot.Hand, CardId.侏罗纪世界) >= 2)
{
AI.SelectCard(CardId.侏罗纪世界); AI.SelectNextCard(check);
}
else if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾) >= 2)
{
AI.SelectCard(CardId.大恐龙驾); AI.SelectNextCard(check);
}
else if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾R) >= 2)
{
AI.SelectCard(CardId.大恐龙驾R); AI.SelectNextCard(check);
}
else if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾L) >= 2)
{
AI.SelectCard(CardId.大恐龙驾L); AI.SelectNextCard(check);
}
else if (Bot.GetCountCardInZone(Bot.Hand, CardId.巨身多角龙) >= 2)
{
AI.SelectCard(CardId.巨身多角龙); AI.SelectNextCard(check);
}
else
AI.SelectCard(
CardId.成金恐龙王,CardId.抑龙,CardId.奇迹的共进化,CardId.名流雷龙,CardId.超级恐龙王,CardId.恐力重压,CardId.超越进化,CardId.恐龙粉碎,CardId.荒野盗龙);
AI.SelectNextCard(check);
return true;
}
private bool 超越进化Effect()
{
AI.SelectCard(
CardId.大恐龙驾,
CardId.超级恐龙王
);
return true;
}
private bool 超级恐龙王Effect()
{
AI.SelectCard(
CardId.巨身多角龙,
CardId.荒野盗龙,
CardId.名流雷龙
);
return true;
}
private bool MAXLsummon()
{
if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾L) >= 2 && Bot.GetCountCardInZone(Bot.Hand, CardId.奇迹的共进化) >= 1 && Bot.GetCountCardInZone(Bot.Hand, CardId.超级恐龙王) >= 1)
return true;
return false;
}
private bool MAXRsummon()
{
if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾R) >= 2 && Bot.GetCountCardInZone(Bot.Hand, CardId.奇迹的共进化) >= 1 && Bot.GetCountCardInZone(Bot.Hand, CardId.超级恐龙王) >= 1)
return true;
return false;
}
private bool MAXLset()
{
if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾L) < 2) return false;
return true;
}
private bool MAXRset()
{
if (Bot.GetCountCardInZone(Bot.Hand, CardId.大恐龙驾R) < 2) return false;
return true;
}
}
}
@@ -0,0 +1,211 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using System.Linq;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using System;
namespace WindBot.Game.AI.Decks
{
[Deck("RushMokeyMokey", "AI_RushMokeyMokey")]
public class RushMokeyMokeyExecutor : DefaultExecutor
{
public class CardId
{
public const int 青眼白龙 = 120120000;
public const int 破坏之剑士 = 120170000;
public const int 黑魔术师 = 120130000;
public const int 真红眼黑龙 = 120125001;
public const int 恶魔召唤 = 120145000;
public const int 人造人 = 120155000;
public const int 连击龙 = 120110001;
public const int 七星道魔术师 = 120105001;
public const int 雅灭鲁拉 = 120120029;
public const int 耳语妖精 = 120120018;
public const int 神秘庄家 = 120105006;
public const int 火星心少女 = 120145014;
public const int 斗牛士 = 120170035;
public const int 凤凰龙 = 120110009;
public const int 七星道法师 = 120130016;
public const int sionmax = 120150007;
public const int 对死者的供奉 = 120151023;
public const int 落穴 = 120150019;
public const int 暗黑释放 = 120105013;
}
public RushMokeyMokeyExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpSummon);
AddExecutor(ExecutorType.Activate, CardId.七星道法师,七星道法师Effect);
AddExecutor(ExecutorType.Summon, CardId.青眼白龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.破坏之剑士, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.恶魔召唤, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.连击龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.雅灭鲁拉, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.黑魔术师, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.真红眼黑龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.七星道魔术师, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.人造人, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.神秘庄家);
AddExecutor(ExecutorType.Activate, CardId.神秘庄家);
AddExecutor(ExecutorType.SpellSet, CardId.暗黑释放);
AddExecutor(ExecutorType.SpellSet, CardId.落穴);
AddExecutor(ExecutorType.Activate, CardId.落穴, 落穴Effect);
AddExecutor(ExecutorType.Activate, CardId.对死者的供奉, 死供Effect);
AddExecutor(ExecutorType.SpellSet, CardId.对死者的供奉);
AddExecutor(ExecutorType.MonsterSet, CardId.凤凰龙, monsterset);
AddExecutor(ExecutorType.MonsterSet, CardId.火星心少女, monsterset);
AddExecutor(ExecutorType.MonsterSet, CardId.七星道法师, monsterset);
AddExecutor(ExecutorType.MonsterSet, CardId.耳语妖精, monsterset);
AddExecutor(ExecutorType.Summon, CardId.七星道法师);
AddExecutor(ExecutorType.Summon, CardId.凤凰龙);
AddExecutor(ExecutorType.Activate, CardId.凤凰龙);
AddExecutor(ExecutorType.SummonOrSet, DefaultMonsterSummon);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.SpellSet);
//AddExecutor(ExecutorType.Activate, CardId.sionmax, sionmaxEffect);
AddExecutor(ExecutorType.Activate, CardId.耳语妖精, 耳语妖精Effect);
AddExecutor(ExecutorType.Activate, CardId.火星心少女, 火星心少女Effect);
AddExecutor(ExecutorType.Activate, CardId.连击龙);
AddExecutor(ExecutorType.Activate, CardId.七星道魔术师);
//AddExecutor(ExecutorType.Activate, CardId.斗牛士, 斗牛士Effect);
AddExecutor(ExecutorType.Activate, DefaultDontChainMyself);
}
private List<int> HintMsgForEnemy = new List<int>
{
HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck,
HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Disable
};
private List<int> HintMsgForMaxSelect = new List<int>
{
HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.AddToHand, HintMsg.ToDeck, HintMsg.Destroy
};
public override IList<ClientCard> OnSelectCard(IList<ClientCard> _cards, int min, int max, int hint, bool cancelable)
{
if (Duel.Phase == DuelPhase.BattleStart)
return null;
if (AI.HaveSelectedCards())
return null;
IList<ClientCard> selected = new List<ClientCard>();
IList<ClientCard> cards = new List<ClientCard>(_cards);
if (max > cards.Count)
max = cards.Count;
if (HintMsgForEnemy.Contains(hint))
{
IList<ClientCard> enemyCards = cards.Where(card => card.Controller == 1).ToList();
// select enemy's card first
while (enemyCards.Count > 0 && selected.Count < max)
{
ClientCard card = enemyCards[Program.Rand.Next(enemyCards.Count)];
selected.Add(card);
enemyCards.Remove(card);
cards.Remove(card);
}
}
if (HintMsgForMaxSelect.Contains(hint))
{
// select max cards
while (selected.Count < max)
{
ClientCard card = cards[Program.Rand.Next(cards.Count)];
selected.Add(card);
cards.Remove(card);
}
}
return selected;
}
public override bool OnSelectHand()
{
// go first
return true;
}
public bool monsterset()
{
if (Duel.Turn == 1)
{
return true;
}
else if (Bot.HasInHand(new[] {
CardId.七星道魔术师,
CardId.连击龙,
CardId.青眼白龙,
CardId.人造人,
CardId.恶魔召唤,
CardId.雅灭鲁拉,
CardId.破坏之剑士,
CardId.真红眼黑龙,
CardId.黑魔术师
}))
return false;
return true;
}
private bool 耳语妖精Effect()
{
IList<ClientCard> targets = new List<ClientCard>();
foreach (ClientCard card in Enemy.GetGraveyardMonsters())
{
if (card.Level <= 4)
targets.Add(card);
}
return true;
}
private bool 落穴Effect()
{
foreach (ClientCard n in Duel.LastSummonedCards)
{
if (n.Attack >= 1900)
return true;
}
return false;
}
private bool 火星心少女Effect()
{
foreach (ClientCard m in Bot.Hand)
AI.SelectCard(m);
AI.SelectNextCard(Enemy.GetMonsters().GetHighestAttackMonster());
AI.SelectYesNo(true);
return true;
}
private bool 死供Effect()
{
if (Util.IsOneEnemyBetterThanValue(1900, true))
{
foreach (ClientCard m in Bot.Hand)
AI.SelectCard(m);
AI.SelectNextCard(Enemy.GetMonsters().GetHighestAttackMonster());
return true;
}
return false;
}
private bool 七星道法师Effect()
{
AI.SelectCard(Enemy.GetMonsters().GetHighestAttackMonster());
return true;
}
}
}
@@ -0,0 +1,211 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using System.Linq;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using System;
namespace WindBot.Game.AI.Decks
{
[Deck("RushMokeyMokeyKing", "AI_RushMokeyMokeyKing")]
public class RushMokeyMokeyKingExecutor : DefaultExecutor
{
public class CardId
{
public const int 青眼白龙 = 120120000;
public const int 破坏之剑士 = 120170000;
public const int 黑魔术师 = 120130000;
public const int 真红眼黑龙 = 120125001;
public const int 恶魔召唤 = 120145000;
public const int 人造人 = 120155000;
public const int 连击龙 = 120110001;
public const int 七星道魔术师 = 120105001;
public const int 雅灭鲁拉 = 120120029;
public const int 耳语妖精 = 120120018;
public const int 神秘庄家 = 120105006;
public const int 火星心少女 = 120145014;
public const int 斗牛士 = 120170035;
public const int 凤凰龙 = 120110009;
public const int 七星道法师 = 120130016;
public const int sionmax = 120150007;
public const int 对死者的供奉 = 120151023;
public const int 落穴 = 120150019;
public const int 暗黑释放 = 120105013;
}
public RushMokeyMokeyKingExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.SpSummon);
AddExecutor(ExecutorType.Activate, CardId.七星道法师, 七星道法师Effect);
AddExecutor(ExecutorType.Summon, CardId.青眼白龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.破坏之剑士, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.恶魔召唤, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.连击龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.雅灭鲁拉, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.黑魔术师, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.真红眼黑龙, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.七星道魔术师, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.人造人, DefaultMonsterSummon);
AddExecutor(ExecutorType.Summon, CardId.神秘庄家);
AddExecutor(ExecutorType.Activate, CardId.神秘庄家);
AddExecutor(ExecutorType.SpellSet, CardId.暗黑释放);
AddExecutor(ExecutorType.SpellSet, CardId.落穴);
AddExecutor(ExecutorType.Activate, CardId.落穴, 落穴Effect);
AddExecutor(ExecutorType.Activate, CardId.对死者的供奉, 死供Effect);
AddExecutor(ExecutorType.SpellSet, CardId.对死者的供奉);
AddExecutor(ExecutorType.MonsterSet, CardId.凤凰龙, monsterset);
AddExecutor(ExecutorType.MonsterSet, CardId.火星心少女, monsterset);
AddExecutor(ExecutorType.MonsterSet, CardId.七星道法师, monsterset);
AddExecutor(ExecutorType.MonsterSet, CardId.耳语妖精, monsterset);
AddExecutor(ExecutorType.Summon, CardId.七星道法师);
AddExecutor(ExecutorType.Summon, CardId.凤凰龙);
AddExecutor(ExecutorType.Activate, CardId.凤凰龙);
AddExecutor(ExecutorType.SummonOrSet, DefaultMonsterSummon);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
AddExecutor(ExecutorType.SpellSet);
//AddExecutor(ExecutorType.Activate, CardId.sionmax, sionmaxEffect);
AddExecutor(ExecutorType.Activate, CardId.耳语妖精, 耳语妖精Effect);
AddExecutor(ExecutorType.Activate, CardId.火星心少女, 火星心少女Effect);
AddExecutor(ExecutorType.Activate, CardId.连击龙);
AddExecutor(ExecutorType.Activate, CardId.七星道魔术师);
//AddExecutor(ExecutorType.Activate, CardId.斗牛士, 斗牛士Effect);
AddExecutor(ExecutorType.Activate, DefaultDontChainMyself);
}
private List<int> HintMsgForEnemy = new List<int>
{
HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck,
HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Disable
};
private List<int> HintMsgForMaxSelect = new List<int>
{
HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.AddToHand, HintMsg.ToDeck, HintMsg.Destroy
};
public override IList<ClientCard> OnSelectCard(IList<ClientCard> _cards, int min, int max, int hint, bool cancelable)
{
if (Duel.Phase == DuelPhase.BattleStart)
return null;
if (AI.HaveSelectedCards())
return null;
IList<ClientCard> selected = new List<ClientCard>();
IList<ClientCard> cards = new List<ClientCard>(_cards);
if (max > cards.Count)
max = cards.Count;
if (HintMsgForEnemy.Contains(hint))
{
IList<ClientCard> enemyCards = cards.Where(card => card.Controller == 1).ToList();
// select enemy's card first
while (enemyCards.Count > 0 && selected.Count < max)
{
ClientCard card = enemyCards[Program.Rand.Next(enemyCards.Count)];
selected.Add(card);
enemyCards.Remove(card);
cards.Remove(card);
}
}
if (HintMsgForMaxSelect.Contains(hint))
{
// select max cards
while (selected.Count < max)
{
ClientCard card = cards[Program.Rand.Next(cards.Count)];
selected.Add(card);
cards.Remove(card);
}
}
return selected;
}
public override bool OnSelectHand()
{
// go first
return true;
}
public bool monsterset()
{
if (Duel.Turn == 1)
{
return true;
}
else if (Bot.HasInHand(new[] {
CardId.七星道魔术师,
CardId.连击龙,
CardId.青眼白龙,
CardId.人造人,
CardId.恶魔召唤,
CardId.雅灭鲁拉,
CardId.破坏之剑士,
CardId.真红眼黑龙,
CardId.黑魔术师
}))
return false;
return true;
}
private bool 耳语妖精Effect()
{
IList<ClientCard> targets = new List<ClientCard>();
foreach (ClientCard card in Enemy.GetGraveyardMonsters())
{
if (card.Level <= 4)
targets.Add(card);
}
return true;
}
private bool 七星道法师Effect()
{
AI.SelectCard(Enemy.GetMonsters().GetHighestAttackMonster());
return true;
}
private bool 落穴Effect()
{
foreach (ClientCard n in Duel.LastSummonedCards)
{
if (n.Attack >= 1900)
return true;
}
return false;
}
private bool 死供Effect()
{
if (Util.IsOneEnemyBetterThanValue(1900, true))
{
foreach (ClientCard m in Bot.Hand)
AI.SelectCard(m);
AI.SelectNextCard(Enemy.GetMonsters().GetHighestAttackMonster());
return true;
}
return false;
}
private bool 火星心少女Effect()
{
foreach (ClientCard m in Bot.Hand)
AI.SelectCard(m);
AI.SelectNextCard(Enemy.GetMonsters().GetHighestAttackMonster());
AI.SelectYesNo(true);
return true;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,469 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("ST1732", "AI_ST1732")]
public class ST1732Executor : DefaultExecutor
{
public class CardId
{
public const int Digitron = 32295838;
public const int Bitron = 36211150;
public const int DualAssembloom = 7445307;
public const int BootStagguard = 70950698;
public const int Linkslayer = 35595518;
public const int RAMClouder = 9190563;
public const int ROMCloudia = 44956694;
public const int BalancerLord = 8567955;
public const int Backlinker = 71172240;
public const int Kleinant = 45778242;
public const int Draconnet = 62706865;
public const int DotScaper = 18789533;
public const int MindControl = 37520316;
public const int DarkHole = 53129443;
public const int MonsterReborn = 83764718;
public const int MysticalSpaceTyphoon = 5318639;
public const int CosmicCyclone = 8267140;
public const int BookOfMoon = 14087893;
public const int CynetBackdoor = 43839002;
public const int MoonMirrorShield = 19508728;
public const int CynetUniverse = 61583217;
public const int BottomlessTrapHole = 29401950;
public const int MirrorForce = 44095762;
public const int TorrentialTribute = 53582587;
public const int RecodedAlive = 70238111;
public const int DimensionalBarrier = 83326048;
public const int CompulsoryEvacuationDevice = 94192409;
public const int SolemnStrike = 40605147;
public const int DecodeTalker = 1861629;
public const int EncodeTalker = 6622715;
public const int TriGateWizard = 32617464;
public const int Honeybot = 34472920;
public const int BinarySorceress = 79016563;
public const int LinkSpider = 98978921;
public const int StagToken = 70950699;
}
bool BalancerLordUsed = false;
public ST1732Executor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.CosmicCyclone, DefaultCosmicCyclone);
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.BookOfMoon, DefaultBookOfMoon);
AddExecutor(ExecutorType.Activate, CardId.CynetUniverse, CynetUniverseEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Linkslayer);
AddExecutor(ExecutorType.Activate, CardId.Linkslayer, LinkslayerEffect);
AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider);
AddExecutor(ExecutorType.Activate, CardId.LinkSpider);
AddExecutor(ExecutorType.Activate, CardId.MindControl, MindControlEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Backlinker);
AddExecutor(ExecutorType.Activate, CardId.Backlinker, BacklinkerEffect);
AddExecutor(ExecutorType.Activate, CardId.BootStagguard, BootStagguardEffect);
AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, MonsterRebornEffect);
AddExecutor(ExecutorType.Activate, CardId.MoonMirrorShield, MoonMirrorShieldEffect);
AddExecutor(ExecutorType.Activate, CardId.CynetBackdoor, CynetBackdoorEffect);
AddExecutor(ExecutorType.Activate, CardId.RecodedAlive);
AddExecutor(ExecutorType.Summon, CardId.BalancerLord, BalancerLordSummon);
AddExecutor(ExecutorType.Summon, CardId.ROMCloudia, ROMCloudiaSummon);
AddExecutor(ExecutorType.Activate, CardId.ROMCloudia, ROMCloudiaEffect);
AddExecutor(ExecutorType.Summon, CardId.Draconnet, DraconnetSummon);
AddExecutor(ExecutorType.Activate, CardId.Draconnet, DraconnetEffect);
AddExecutor(ExecutorType.Summon, CardId.Kleinant);
AddExecutor(ExecutorType.Activate, CardId.Kleinant, KleinantEffect);
AddExecutor(ExecutorType.Summon, CardId.RAMClouder);
AddExecutor(ExecutorType.Activate, CardId.RAMClouder, RAMClouderEffect);
AddExecutor(ExecutorType.SummonOrSet, CardId.DotScaper);
AddExecutor(ExecutorType.Activate, CardId.DotScaper, DotScaperEffect);
AddExecutor(ExecutorType.Summon, CardId.BalancerLord);
AddExecutor(ExecutorType.Summon, CardId.ROMCloudia);
AddExecutor(ExecutorType.Summon, CardId.Draconnet);
AddExecutor(ExecutorType.SummonOrSet, CardId.Backlinker);
AddExecutor(ExecutorType.SummonOrSet, CardId.Digitron);
AddExecutor(ExecutorType.SummonOrSet, CardId.Bitron);
AddExecutor(ExecutorType.Activate, CardId.BalancerLord, BalancerLordEffect);
AddExecutor(ExecutorType.SpSummon, CardId.DecodeTalker, LinkSummon);
AddExecutor(ExecutorType.Activate, CardId.DecodeTalker);
AddExecutor(ExecutorType.SpSummon, CardId.TriGateWizard, LinkSummon);
AddExecutor(ExecutorType.Activate, CardId.TriGateWizard);
AddExecutor(ExecutorType.SpSummon, CardId.EncodeTalker, LinkSummon);
AddExecutor(ExecutorType.Activate, CardId.EncodeTalker);
AddExecutor(ExecutorType.SpSummon, CardId.Honeybot, LinkSummon);
AddExecutor(ExecutorType.SpSummon, CardId.BinarySorceress, LinkSummon);
AddExecutor(ExecutorType.Activate, CardId.BinarySorceress);
AddExecutor(ExecutorType.SpellSet, CardId.CynetBackdoor, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.RecodedAlive, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.CompulsoryEvacuationDevice, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.DimensionalBarrier, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.TorrentialTribute, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.MirrorForce, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.BottomlessTrapHole, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.BookOfMoon, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.CosmicCyclone, DefaultSpellSet);
AddExecutor(ExecutorType.SpellSet, CardId.MysticalSpaceTyphoon, DefaultSpellSet);
AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, CardId.CompulsoryEvacuationDevice, DefaultCompulsoryEvacuationDevice);
AddExecutor(ExecutorType.Activate, CardId.DimensionalBarrier, DefaultDimensionalBarrier);
AddExecutor(ExecutorType.Activate, CardId.TorrentialTribute, DefaultTorrentialTribute);
AddExecutor(ExecutorType.Activate, CardId.MirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.BottomlessTrapHole, DefaultUniqueTrap);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
public override bool OnSelectHand()
{
// go second
return false;
}
public override void OnNewTurn()
{
// reset
BalancerLordUsed = false;
base.OnNewTurn();
}
public override int OnSelectOption(IList<int> options)
{
// put Moon Mirror Shield to the bottom of deck
return options.Count == 2 ? 1 : 0;
}
public override bool OnSelectYesNo(int desc)
{
if (desc == 210) // Continue selecting? (Link Summoning)
return false;
if (desc == 31) // Direct Attack?
return true;
return base.OnSelectYesNo(desc);
}
private bool LinkslayerEffect()
{
IList<ClientCard> targets = Enemy.GetSpells();
if (targets.Count > 0)
{
AI.SelectCard(
CardId.DualAssembloom,
CardId.Bitron,
CardId.Digitron,
CardId.RecodedAlive
);
AI.SelectNextCard(targets);
return true;
}
return false;
}
private bool MindControlEffect()
{
ClientCard target = Util.GetBestEnemyMonster();
if (target != null)
{
AI.SelectCard(target);
return true;
}
return false;
}
private bool BacklinkerEffect()
{
return (Bot.MonsterZone[5] == null) && (Bot.MonsterZone[6] == null);
}
private bool BootStagguardEffect()
{
if (Card.Location != CardLocation.Hand)
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool MonsterRebornEffect()
{
IList<int> targets = new[] {
CardId.DecodeTalker,
CardId.EncodeTalker,
CardId.TriGateWizard,
CardId.BinarySorceress,
CardId.Honeybot,
CardId.DualAssembloom,
CardId.BootStagguard,
CardId.BalancerLord,
CardId.ROMCloudia,
CardId.Linkslayer,
CardId.RAMClouder,
CardId.Backlinker,
CardId.Kleinant
};
if (!Bot.HasInGraveyard(targets))
{
return false;
}
AI.SelectCard(targets);
return true;
}
private bool MoonMirrorShieldEffect()
{
foreach (ClientCard monster in Bot.GetMonsters())
{
AI.SelectCard(monster);
return true;
}
return false;
}
private bool CynetUniverseEffect()
{
if (Card.Location == CardLocation.Hand)
return DefaultField();
foreach (ClientCard card in Enemy.Graveyard)
{
if (card.IsMonster())
{
AI.SelectCard(card);
return true;
}
}
return false;
}
private bool CynetBackdoorEffect()
{
if (!(Duel.Player == 0 && Duel.Phase == DuelPhase.Main2) &&
!(Duel.Player == 1 && (Duel.Phase == DuelPhase.BattleStart || Duel.Phase == DuelPhase.End)))
{
return false;
}
if (!UniqueFaceupSpell())
return false;
bool selected = false;
foreach (ClientCard monster in Bot.GetMonstersInExtraZone())
{
if (monster.Attack > 1000)
{
AI.SelectCard(monster);
selected = true;
break;
}
}
if (!selected)
{
List<ClientCard> monsters = Bot.GetMonsters();
foreach (ClientCard monster in monsters)
{
if (monster.IsCode(CardId.BalancerLord))
{
AI.SelectCard(monster);
selected = true;
break;
}
}
if (!selected)
{
foreach (ClientCard monster in monsters)
{
if (monster.Attack >= 1700)
{
AI.SelectCard(monster);
selected = true;
break;
}
}
}
}
if (selected)
{
AI.SelectNextCard(
CardId.ROMCloudia,
CardId.BalancerLord,
CardId.Kleinant,
CardId.Draconnet,
CardId.Backlinker
);
return true;
}
return false;
}
private bool BalancerLordSummon()
{
return !BalancerLordUsed;
}
private bool BalancerLordEffect()
{
if (Card.Location == CardLocation.Removed)
return true;
bool hastarget = Bot.HasInHand(new[] {
CardId.Draconnet,
CardId.Kleinant,
CardId.BalancerLord,
CardId.ROMCloudia,
CardId.RAMClouder,
CardId.DotScaper
});
if (hastarget && !BalancerLordUsed)
{
BalancerLordUsed = true;
return true;
}
return false;
}
private bool ROMCloudiaSummon()
{
return Bot.HasInGraveyard(new[] {
CardId.BootStagguard,
CardId.BalancerLord,
CardId.Kleinant,
CardId.Linkslayer,
CardId.Draconnet,
CardId.RAMClouder
});
}
private bool ROMCloudiaEffect()
{
if (Card.Location == CardLocation.MonsterZone)
{
AI.SelectCard(
CardId.BootStagguard,
CardId.BalancerLord,
CardId.Kleinant,
CardId.Linkslayer,
CardId.Draconnet,
CardId.RAMClouder
);
return true;
}
else
{
AI.SelectCard(
CardId.BalancerLord,
CardId.Kleinant,
CardId.RAMClouder,
CardId.DotScaper
);
return true;
}
}
private bool DraconnetSummon()
{
return Bot.GetRemainingCount(CardId.Digitron, 1) > 0
|| Bot.GetRemainingCount(CardId.Bitron, 1) > 0;
}
private bool DraconnetEffect()
{
AI.SelectCard(CardId.Bitron);
return true;
}
private bool KleinantEffect()
{
IList<int> targets = new[] {
CardId.DualAssembloom,
CardId.Bitron,
CardId.Digitron,
CardId.DotScaper
};
foreach (ClientCard monster in Bot.Hand)
{
if (monster.IsCode(targets))
{
AI.SelectCard(targets);
return true;
}
}
IList<int> targets2 = new[] {
CardId.StagToken,
CardId.Bitron,
CardId.Digitron,
CardId.DotScaper
};
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.IsCode(targets2))
{
AI.SelectCard(targets2);
return true;
}
}
return false;
}
private bool RAMClouderEffect()
{
AI.SelectCard(
CardId.StagToken,
CardId.Bitron,
CardId.Digitron,
CardId.DotScaper,
CardId.Draconnet,
CardId.Backlinker,
CardId.RAMClouder
);
AI.SelectNextCard(
CardId.DecodeTalker,
CardId.EncodeTalker,
CardId.TriGateWizard,
CardId.BinarySorceress,
CardId.Honeybot,
CardId.DualAssembloom,
CardId.BootStagguard,
CardId.BalancerLord,
CardId.ROMCloudia,
CardId.Linkslayer,
CardId.RAMClouder
);
return true;
}
private bool DotScaperEffect()
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool LinkSummon()
{
return (Util.IsTurn1OrMain2() || Util.IsOneEnemyBetter())
&& Util.GetBestAttack(Bot) < Card.Attack;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,766 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("SkyStriker", "AI_SkyStriker")]
public class SkyStrikerExecutor : DefaultExecutor
{
public class CardId
{
public const int Raye = 26077387;
public const int Kagari = 63288573;
public const int Shizuku = 90673288;
public const int Hayate = 8491308;
public const int Token = 52340445;
public const int Engage = 63166095;
public const int HornetDrones = 52340444;
public const int WidowAnchor = 98338152;
public const int Afterburners = 99550630;
public const int JammingWave = 25955749;
public const int Multirole = 24010609;
public const int HerculesBase = 97616504;
public const int AreaZero = 50005218;
public const int AshBlossom = 14558127;
public const int GhostRabbit = 59438930;
public const int MaxxC = 23434538;
public const int JetSynchron = 9742784;
public const int EffectVeiler = 97268402;
public const int ReinforcementOfTheArmy = 32807846;
public const int FoolishBurialGoods = 35726888;
public const int UpstartGoblin = 70368879;
public const int MetalfoesFusion = 73594093;
public const int TwinTwisters = 43898403;
public const int SolemnJudgment = 41420027;
public const int SolemnWarning = 84749824;
public const int HiSpeedroidChanbara = 42110604;
public const int TopologicBomberDragon = 5821478;
public const int TopologicTrisbaena = 72529749;
public const int SummonSorceress = 61665245;
public const int TroymareUnicorn = 38342335;
public const int TroymarePhoenix = 2857636;
public const int CrystronNeedlefiber = 50588353;
public const int Linkuriboh = 41999284;
}
bool KagariSummoned = false;
bool ShizukuSummoned = false;
bool HayateSummoned = false;
ClientCard WidowAnchorTarget = null;
public SkyStrikerExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.AshBlossom, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, CardId.GhostRabbit, DefaultGhostOgreAndSnowRabbit);
AddExecutor(ExecutorType.Activate, CardId.EffectVeiler, DefaultBreakthroughSkill);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, CardId.MaxxC, MaxxCEffect);
AddExecutor(ExecutorType.Activate, CardId.ReinforcementOfTheArmy);
AddExecutor(ExecutorType.Activate, CardId.UpstartGoblin);
AddExecutor(ExecutorType.Activate, CardId.FoolishBurialGoods, FoolishBurialGoodsEffect);
AddExecutor(ExecutorType.Activate, CardId.TwinTwisters, TwinTwistersEffect);
//
AddExecutor(ExecutorType.Activate, CardId.Multirole, MultiroleHandEffect);
AddExecutor(ExecutorType.Activate, CardId.WidowAnchor, WidowAnchorEffectFirst);
AddExecutor(ExecutorType.Activate, CardId.Afterburners, AfterburnersEffect);
AddExecutor(ExecutorType.Activate, CardId.JammingWave, JammingWaveEffect);
AddExecutor(ExecutorType.Activate, CardId.Engage, EngageEffectFirst);
AddExecutor(ExecutorType.Activate, CardId.HornetDrones, HornetDronesEffect);
AddExecutor(ExecutorType.Activate, CardId.WidowAnchor, WidowAnchorEffect);
AddExecutor(ExecutorType.Activate, CardId.HerculesBase, HerculesBaseEffect);
AddExecutor(ExecutorType.Activate, CardId.AreaZero, AreaZeroEffect);
AddExecutor(ExecutorType.Activate, CardId.Multirole, MultiroleEffect);
AddExecutor(ExecutorType.Activate, CardId.Engage, EngageEffect);
//
AddExecutor(ExecutorType.Summon, CardId.JetSynchron, TunerSummon);
AddExecutor(ExecutorType.Summon, CardId.EffectVeiler, TunerSummon);
AddExecutor(ExecutorType.Summon, CardId.GhostRabbit, TunerSummon);
AddExecutor(ExecutorType.Summon, CardId.AshBlossom, TunerSummon);
AddExecutor(ExecutorType.Activate, CardId.Raye, RayeEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Kagari, KagariSummon);
AddExecutor(ExecutorType.Activate, CardId.Kagari, KagariEffect);
AddExecutor(ExecutorType.SpSummon, CardId.CrystronNeedlefiber, CrystronNeedlefiberSummon);
AddExecutor(ExecutorType.Activate, CardId.CrystronNeedlefiber, CrystronNeedlefiberEffect);
AddExecutor(ExecutorType.SpSummon, CardId.SummonSorceress);
AddExecutor(ExecutorType.Activate, CardId.SummonSorceress, SummonSorceressEffect);
AddExecutor(ExecutorType.Activate, CardId.JetSynchron, JetSynchronEffect);
AddExecutor(ExecutorType.SpSummon, CardId.HiSpeedroidChanbara);
AddExecutor(ExecutorType.SpSummon, CardId.Shizuku, ShizukuSummon);
AddExecutor(ExecutorType.Activate, CardId.Shizuku, ShizukuEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Hayate, HayateSummon);
AddExecutor(ExecutorType.Activate, CardId.Hayate, HayateEffect);
AddExecutor(ExecutorType.SpSummon, CardId.TopologicBomberDragon, Util.IsTurn1OrMain2);
AddExecutor(ExecutorType.Summon, CardId.Raye, RayeSummon);
//
AddExecutor(ExecutorType.SpellSet, CardId.SolemnJudgment);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnWarning);
AddExecutor(ExecutorType.SpellSet, CardId.WidowAnchor);
AddExecutor(ExecutorType.SpellSet, CardId.HerculesBase);
AddExecutor(ExecutorType.SpellSet, CardId.TwinTwisters, HandFull);
AddExecutor(ExecutorType.SpellSet, CardId.HornetDrones, HandFull);
//
AddExecutor(ExecutorType.Activate, CardId.MetalfoesFusion);
AddExecutor(ExecutorType.Activate, CardId.Multirole, MultiroleEPEffect);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
public override bool OnSelectHand()
{
// go first
return true;
}
public override void OnNewTurn()
{
KagariSummoned = false;
ShizukuSummoned = false;
HayateSummoned = false;
WidowAnchorTarget = null;
base.OnNewTurn();
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (!defender.IsMonsterHasPreventActivationEffectInBattle())
{
if (attacker.IsCode(CardId.HiSpeedroidChanbara) && !attacker.IsDisabled())
attacker.RealPower = attacker.RealPower + 200;
}
return base.OnPreBattleBetween(attacker, defender);
}
public override bool OnSelectYesNo(int desc)
{
if (desc == Util.GetStringId(CardId.SummonSorceress, 2)) // summon to the field of opponent?
return false;
if (desc == Util.GetStringId(CardId.Engage, 0)) // draw card?
return true;
if (desc == Util.GetStringId(CardId.WidowAnchor, 0)) // get control?
return true;
if (desc == Util.GetStringId(CardId.JammingWave, 0)) // destroy monster?
{
ClientCard target = Util.GetBestEnemyMonster();
if (target != null)
{
AI.SelectCard(target);
return true;
}
else
return false;
}
if (desc == Util.GetStringId(CardId.Afterburners, 0)) // destroy spell & trap?
{
ClientCard target = Util.GetBestEnemySpell();
if (target != null)
{
AI.SelectCard(target);
return true;
}
else
return false;
}
return base.OnSelectYesNo(desc);
}
private bool MaxxCEffect()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
return Duel.Player == 1;
}
private bool TwinTwistersEffect()
{
if (Util.ChainContainsCard(CardId.TwinTwisters))
return false;
IList<ClientCard> targets = new List<ClientCard>();
foreach (ClientCard target in Enemy.GetSpells())
{
if (target.IsFloodgate())
targets.Add(target);
if (targets.Count >= 2)
break;
}
if (targets.Count < 2)
{
foreach (ClientCard target in Enemy.GetSpells())
{
if (target.IsFacedown() || target.HasType(CardType.Continuous) || target.HasType(CardType.Pendulum))
targets.Add(target);
if (targets.Count >= 2)
break;
}
}
if (targets.Count > 0)
{
AI.SelectCard(GetDiscardHand());
AI.SelectNextCard(targets);
return true;
}
return false;
}
private bool FoolishBurialGoodsEffect()
{
AI.SelectCard(
CardId.MetalfoesFusion,
CardId.WidowAnchor,
CardId.Engage,
CardId.HornetDrones
);
return true;
}
private bool MultiroleHandEffect()
{
return Card.Location == CardLocation.Hand;
}
private bool MultiroleEPEffect()
{
if (Duel.Phase != DuelPhase.End)
return false;
IList<int> targets = new[] {
CardId.Engage,
CardId.HornetDrones,
CardId.WidowAnchor
};
AI.SelectCard(targets);
AI.SelectNextCard(targets);
AI.SelectThirdCard(targets);
return true;
}
private bool AfterburnersEffect()
{
ClientCard target = Util.GetBestEnemyMonster(true, true);
if (target != null)
{
AI.SelectCard(target);
return true;
}
return false;
}
private bool JammingWaveEffect()
{
ClientCard target = null;
foreach(ClientCard card in Enemy.GetSpells())
{
if (card.IsFacedown())
{
target = card;
break;
}
}
if (target != null)
{
AI.SelectCard(target);
return true;
}
return false;
}
private bool WidowAnchorEffectFirst()
{
if (Util.ChainContainsCard(CardId.WidowAnchor))
return false;
ClientCard target = Util.GetProblematicEnemyMonster(0, true);
if (target != null)
{
WidowAnchorTarget = target;
AI.SelectCard(target);
return true;
}
return false;
}
private bool EngageEffectFirst()
{
if (!HaveThreeSpellsInGrave())
return false;
int target = GetCardToSearch();
if (target > 0)
AI.SelectCard(target);
else
AI.SelectCard(
CardId.Multirole,
CardId.AreaZero,
CardId.Afterburners,
CardId.JammingWave,
CardId.Raye
);
return true;
}
private bool EngageEffect()
{
int target = GetCardToSearch();
if (target > 0)
AI.SelectCard(target);
else
AI.SelectCard(
CardId.Multirole,
CardId.AreaZero,
CardId.Afterburners,
CardId.JammingWave,
CardId.Raye
);
return true;
}
private bool HornetDronesEffect()
{
if (Duel.Player == 1)
{
return Duel.Phase == DuelPhase.End;
}
else
{
if (Duel.Phase != DuelPhase.Main1)
return false;
if (Duel.CurrentChain.Count > 0)
return false;
if (Bot.GetMonstersExtraZoneCount() == 0)
return true;
if (Bot.HasInMonstersZone(CardId.SummonSorceress))
return true;
if (Bot.HasInMonstersZone(CardId.TopologicBomberDragon) && Enemy.GetMonsterCount() > 1)
return true;
if (!Util.IsTurn1OrMain2())
{
foreach (ClientCard card in Bot.Hand)
{
if (card.IsTuner())
return true;
}
}
}
return false;
}
private bool WidowAnchorEffect()
{
if (DefaultBreakthroughSkill())
{
WidowAnchorTarget = Util.GetLastChainCard();
return true;
}
if (!HaveThreeSpellsInGrave() || Duel.Player == 1 || Duel.Phase < DuelPhase.Main1 || Duel.Phase >= DuelPhase.Main2 || Util.ChainContainsCard(CardId.WidowAnchor))
return false;
ClientCard target = Util.GetBestEnemyMonster(true, true);
if (target != null && !target.IsDisabled() && !target.HasType(CardType.Normal))
{
WidowAnchorTarget = target;
AI.SelectCard(target);
return true;
}
return false;
}
private bool HerculesBaseEffect()
{
if (Card.Location == CardLocation.Grave)
{
IList<ClientCard> targets = new List<ClientCard>();
foreach(ClientCard card in Bot.GetGraveyardMonsters())
{
if (card.IsCode(CardId.Hayate, CardId.Kagari, CardId.Shizuku))
targets.Add(card);
}
if (targets.Count > 0)
{
AI.SelectCard(targets);
return true;
}
}
else
{
if (Util.IsTurn1OrMain2())
return false;
ClientCard bestBotMonster = Util.GetBestBotMonster(true);
if (bestBotMonster != null)
{
int bestPower = bestBotMonster.Attack;
int count = 0;
bool have3 = HaveThreeSpellsInGrave();
foreach (ClientCard target in Enemy.GetMonsters())
{
if (target.GetDefensePower() < bestPower && !target.IsMonsterInvincible())
{
count++;
if (count > 1 || have3)
{
AI.SelectCard(bestBotMonster);
return true;
}
}
}
}
}
return false;
}
private bool AreaZeroEffect()
{
if (Card.Location == CardLocation.Hand || Card.Location == CardLocation.Grave)
{
return true;
}
foreach (ClientCard target in Bot.GetMonsters())
{
if (target == WidowAnchorTarget && Duel.Phase == DuelPhase.Main2)
{
AI.SelectCard(target);
return true;
}
}
foreach (ClientCard target in Bot.GetMonsters())
{
if (target.IsCode(CardId.Raye) && Bot.GetMonstersExtraZoneCount() == 0)
{
AI.SelectCard(target);
return true;
}
}
foreach (ClientCard target in Bot.GetSpells())
{
if (!target.IsCode(CardId.AreaZero, CardId.Multirole, CardId.WidowAnchor) && target.IsSpell())
{
AI.SelectCard(target);
return true;
}
}
return false;
}
private bool MultiroleEffect()
{
if (Card.Location == CardLocation.SpellZone)
{
foreach (ClientCard target in Bot.GetMonsters())
{
if (target == WidowAnchorTarget && Duel.Phase == DuelPhase.Main2)
{
AI.SelectCard(target);
return true;
}
}
foreach (ClientCard target in Bot.GetMonsters())
{
if (target.IsCode(CardId.Raye) && Bot.GetMonstersExtraZoneCount() == 0)
{
AI.SelectCard(target);
return true;
}
}
foreach (ClientCard target in Bot.GetSpells())
{
if (target.IsCode(CardId.AreaZero))
{
AI.SelectCard(target);
return true;
}
}
foreach (ClientCard target in Bot.GetSpells())
{
if (!target.IsCode(CardId.Multirole, CardId.WidowAnchor) && target.IsSpell())
{
AI.SelectCard(target);
return true;
}
}
}
return false;
}
private bool RayeSummon()
{
if (Bot.GetMonstersExtraZoneCount() == 0)
{
return true;
}
return false;
}
private bool RayeEffect()
{
if (Card.Location == CardLocation.Grave)
{
return true;
}
if (Card.IsDisabled())
{
return false;
}
if (Util.IsChainTarget(Card))
{
RayeSelectTarget();
return true;
}
if (Card.Attacked && Duel.Phase == DuelPhase.BattleStart)
{
RayeSelectTarget();
return true;
}
if (Card == Bot.BattlingMonster && Duel.Player == 1)
{
RayeSelectTarget();
return true;
}
if (Duel.Phase == DuelPhase.Main2)
{
RayeSelectTarget();
return true;
}
return false;
}
private void RayeSelectTarget()
{
if (!KagariSummoned && Bot.HasInGraveyard(new[] {
CardId.Engage,
CardId.HornetDrones,
CardId.WidowAnchor
}))
{
AI.SelectCard(CardId.Kagari);
}
else
{
AI.SelectCard(CardId.Shizuku, CardId.Kagari, CardId.Hayate);
}
}
private bool KagariSummon()
{
if (Bot.HasInGraveyard(new[] {
CardId.Engage,
CardId.HornetDrones,
CardId.WidowAnchor
}))
{
KagariSummoned = true;
return true;
}
return false;
}
private bool KagariEffect()
{
if (EmptyMainMonsterZone() && Util.GetProblematicEnemyMonster() != null && Bot.HasInGraveyard(CardId.Afterburners))
{
AI.SelectCard(CardId.Afterburners);
}
else if (EmptyMainMonsterZone() && Util.GetProblematicEnemySpell() != null && Bot.HasInGraveyard(CardId.JammingWave))
{
AI.SelectCard(CardId.JammingWave);
}
else
AI.SelectCard(CardId.Engage, CardId.HornetDrones, CardId.WidowAnchor);
return true;
}
private bool ShizukuSummon()
{
if (Util.IsTurn1OrMain2())
{
ShizukuSummoned = true;
return true;
}
return false;
}
private bool ShizukuEffect()
{
int target = GetCardToSearch();
if (target != 0)
AI.SelectCard(target);
else
AI.SelectCard(CardId.Engage, CardId.HornetDrones, CardId.WidowAnchor);
return true;
}
private bool HayateSummon()
{
if (Util.IsTurn1OrMain2())
return false;
HayateSummoned = true;
return true;
}
private bool HayateEffect()
{
if (!Bot.HasInGraveyard(CardId.Raye))
AI.SelectCard(CardId.Raye);
else if (!Bot.HasInGraveyard(CardId.HornetDrones))
AI.SelectCard(CardId.HornetDrones);
else if (!Bot.HasInGraveyard(CardId.WidowAnchor))
AI.SelectCard(CardId.WidowAnchor);
return true;
}
private bool TunerSummon()
{
return !Bot.HasInMonstersZone(new[] {
CardId.AshBlossom,
CardId.EffectVeiler,
CardId.GhostRabbit,
CardId.JetSynchron
}) && !Util.IsTurn1OrMain2()
&& Bot.GetMonsterCount() > 0
&& Bot.HasInExtra(CardId.CrystronNeedlefiber);
}
private bool CrystronNeedlefiberSummon()
{
return !Util.IsTurn1OrMain2();
}
private bool CrystronNeedlefiberEffect()
{
AI.SelectCard(CardId.JetSynchron);
return true;
}
private bool SummonSorceressEffect()
{
if (ActivateDescription == -1)
return false;
return true;
}
private bool JetSynchronEffect()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (Bot.HasInMonstersZone(CardId.Raye) || Bot.HasInMonstersZone(CardId.CrystronNeedlefiber))
{
AI.SelectCard(GetDiscardHand());
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool HandFull()
{
return Bot.GetSpellCountWithoutField() < 4 && Bot.Hand.Count > 4;
}
private int GetDiscardHand()
{
if (Bot.HasInHand(CardId.MetalfoesFusion))
return CardId.MetalfoesFusion;
if (Bot.HasInHand(CardId.Raye) && !Bot.HasInGraveyard(CardId.Raye))
return CardId.Raye;
if (Bot.HasInHand(CardId.JetSynchron))
return CardId.JetSynchron;
if (Bot.HasInHand(CardId.ReinforcementOfTheArmy))
return CardId.ReinforcementOfTheArmy;
if (Bot.HasInHand(CardId.FoolishBurialGoods))
return CardId.FoolishBurialGoods;
return 0;
}
private int GetCardToSearch()
{
if (!Bot.HasInHand(CardId.HornetDrones) && Bot.GetRemainingCount(CardId.HornetDrones, 3) > 0)
{
return CardId.HornetDrones;
}
else if (Util.GetProblematicEnemyMonster() != null && Bot.GetRemainingCount(CardId.WidowAnchor, 3) > 0)
{
return CardId.WidowAnchor;
}
else if (EmptyMainMonsterZone() && Util.GetProblematicEnemyMonster() != null && Bot.GetRemainingCount(CardId.Afterburners, 1) > 0)
{
return CardId.Afterburners;
}
else if (EmptyMainMonsterZone() && Util.GetProblematicEnemySpell() != null && Bot.GetRemainingCount(CardId.JammingWave, 1) > 0)
{
return CardId.JammingWave;
}
else if (!Bot.HasInHand(CardId.Raye) && !Bot.HasInMonstersZone(CardId.Raye) && Bot.GetRemainingCount(CardId.Raye, 3) > 0)
{
return CardId.Raye;
}
else if (!Bot.HasInHand(CardId.WidowAnchor) && !Bot.HasInSpellZone(CardId.WidowAnchor) && Bot.GetRemainingCount(CardId.WidowAnchor, 3) > 0)
{
return CardId.WidowAnchor;
}
return 0;
}
private bool EmptyMainMonsterZone()
{
for (int i = 0; i < 5; i++)
{
if (Bot.MonsterZone[i] != null)
return false;
}
return true;
}
private bool HaveThreeSpellsInGrave()
{
int count = 0;
foreach(ClientCard card in Bot.Graveyard)
{
if (card.IsSpell())
{
count++;
}
}
return count >= 3;
}
private bool DefaultNoExecutor()
{
foreach (CardExecutor exec in Executors)
{
if (exec.Type == Type && exec.CardId == Card.Id)
return false;
}
return true;
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,409 @@
using YGOSharp.OCGWrapper;
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using System.Linq;
namespace WindBot.Game.AI.Decks
{
[Deck("TimeThief", "AI_Timethief")]
public class TimeThiefExecutor : DefaultExecutor
{
public class Monsters
{
//monsters
public const int TimeThiefWinder = 56308388;
public const int TimeThiefBezelShip = 82496079;
public const int TimeThiefCronocorder = 74578720;
public const int TimeThiefRegulator = 19891131;
public const int PhotonTrasher = 65367484;
public const int PerformTrickClown = 67696066;
public const int ThunderKingRaiOh = 71564252;
public const int MaxxC = 23434538;
public const int AshBlossomAndJoyousSpring = 14558127;
}
public class CardId
{
public const int ImperialOrder = 61740673;
public const int NaturalExterio = 99916754;
public const int NaturalBeast = 33198837;
public const int SwordsmanLV7 = 37267041;
public const int RoyalDecreel = 51452091;
}
public class Spells
{
// spells
public const int Raigeki = 12580477;
public const int FoolishBurial = 81439173;
public const int TimeThiefStartup = 10877309;
public const int TimeThiefHack = 81670445;
public const int HarpieFeatherDuster = 18144506;
public const int PotOfDesires = 35261759;
public const int PotofExtravagance = 49238328;
}
public class Traps
{
//traps
public const int SolemnWarning = 84749824;
public const int SolemStrike = 40605147;
public const int SolemnJudgment = 41420027;
public const int TimeThiefRetrograte = 76587747;
public const int PhantomKnightsShade = 98827725;
public const int TimeThiefFlyBack = 18678554;
public const int Crackdown = 36975314;
}
public class XYZs
{
//xyz
public const int TimeThiefRedoer = 55285840;
public const int TimeThiefPerpetua = 59208943;
public const int CrazyBox = 42421606;
public const int GagagaCowboy = 12014404;
public const int Number39Utopia = 84013237;
public const int NumberS39UtopiatheLightning = 56832966;
public const int NumberS39UtopiaOne = 86532744;
public const int DarkRebellionXyzDragon = 16195942;
public const int EvilswarmExcitonKnight = 46772449;
}
public TimeThiefExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// executors
//Spell activate
AddExecutor(ExecutorType.Activate, Spells.Raigeki, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, Spells.FoolishBurial, FoolishBurialTarget);
AddExecutor(ExecutorType.Activate, Spells.TimeThiefStartup, TimeThiefStartupEffect);
AddExecutor(ExecutorType.Activate, Spells.TimeThiefHack);
AddExecutor(ExecutorType.Activate, Spells.PotofExtravagance, PotofExtravaganceActivate);
AddExecutor(ExecutorType.Activate, Spells.HarpieFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, Spells.PotOfDesires, PotOfDesireseff);
// trap executors set
AddExecutor(ExecutorType.SpellSet, Traps.PhantomKnightsShade);
AddExecutor(ExecutorType.SpellSet, Traps.TimeThiefRetrograte);
AddExecutor(ExecutorType.SpellSet, Traps.TimeThiefFlyBack);
AddExecutor(ExecutorType.SpellSet, Traps.SolemnWarning);
AddExecutor(ExecutorType.SpellSet, Traps.SolemStrike);
AddExecutor(ExecutorType.SpellSet, Traps.SolemnJudgment);
AddExecutor(ExecutorType.SpellSet, Traps.Crackdown);
//normal summons
AddExecutor(ExecutorType.Summon, Monsters.TimeThiefRegulator);
AddExecutor(ExecutorType.SpSummon, Monsters.PhotonTrasher, SummonToDef);
AddExecutor(ExecutorType.Summon, Monsters.TimeThiefWinder);
AddExecutor(ExecutorType.Summon, Monsters.TimeThiefBezelShip);
AddExecutor(ExecutorType.Summon, Monsters.PerformTrickClown);
AddExecutor(ExecutorType.Summon, Monsters.TimeThiefCronocorder);
AddExecutor(ExecutorType.Summon, Monsters.ThunderKingRaiOh, ThunderKingRaiOhsummon);
//xyz summons
AddExecutor(ExecutorType.SpSummon, XYZs.TimeThiefRedoer);
AddExecutor(ExecutorType.SpSummon, XYZs.TimeThiefPerpetua);
AddExecutor(ExecutorType.SpSummon, XYZs.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightSummon);
AddExecutor(ExecutorType.SpSummon, XYZs.GagagaCowboy, GagagaCowboySummon);
AddExecutor(ExecutorType.SpSummon, XYZs.Number39Utopia, DefaultNumberS39UtopiaTheLightningSummon);
AddExecutor(ExecutorType.SpSummon, XYZs.NumberS39UtopiaOne);
AddExecutor(ExecutorType.SpSummon, XYZs.NumberS39UtopiatheLightning);
AddExecutor(ExecutorType.SpSummon, XYZs.DarkRebellionXyzDragon, DarkRebellionXyzDragonSummon);
//activate trap
AddExecutor(ExecutorType.Activate, Traps.PhantomKnightsShade);
AddExecutor(ExecutorType.Activate, Traps.TimeThiefRetrograte, RetrograteEffect);
AddExecutor(ExecutorType.Activate, Traps.TimeThiefFlyBack);
AddExecutor(ExecutorType.Activate, Traps.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, Traps.SolemStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, Traps.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, Traps.Crackdown, Crackdowneff);
//xyz effects
AddExecutor(ExecutorType.Activate, XYZs.TimeThiefRedoer, RedoerEffect);
AddExecutor(ExecutorType.Activate, XYZs.TimeThiefPerpetua, PerpertuaEffect);
AddExecutor(ExecutorType.Activate, XYZs.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect);
AddExecutor(ExecutorType.Activate, XYZs.GagagaCowboy);
AddExecutor(ExecutorType.Activate, XYZs.NumberS39UtopiatheLightning, DefaultNumberS39UtopiaTheLightningEffect);
AddExecutor(ExecutorType.Activate, XYZs.DarkRebellionXyzDragon, DarkRebellionXyzDragonEffect);
//monster effects
AddExecutor(ExecutorType.Activate, Monsters.TimeThiefRegulator, RegulatorEffect);
AddExecutor(ExecutorType.Activate, Monsters.TimeThiefWinder);
AddExecutor(ExecutorType.Activate, Monsters.TimeThiefCronocorder);
AddExecutor(ExecutorType.Activate, Monsters.PerformTrickClown, TrickClownEffect);
AddExecutor(ExecutorType.Activate, Monsters.TimeThiefBezelShip);
AddExecutor(ExecutorType.Activate, Monsters.ThunderKingRaiOh, ThunderKingRaiOheff);
AddExecutor(ExecutorType.Activate, Monsters.AshBlossomAndJoyousSpring, DefaultAshBlossomAndJoyousSpring);
AddExecutor(ExecutorType.Activate, Monsters.MaxxC, DefaultMaxxC);
}
public void SelectSTPlace(ClientCard card = null, bool avoid_Impermanence = false, List<int> avoid_list = null)
{
List<int> list = new List<int> { 0, 1, 2, 3, 4 };
int n = list.Count;
while (n-- > 1)
{
int index = Program.Rand.Next(n + 1);
int temp = list[index];
list[index] = list[n];
list[n] = temp;
}
foreach (int seq in list)
{
int zone = (int)System.Math.Pow(2, seq);
if (Bot.SpellZone[seq] == null)
{
if (card != null && card.Location == CardLocation.Hand && avoid_Impermanence) continue;
if (avoid_list != null && avoid_list.Contains(seq)) continue;
AI.SelectPlace(zone);
return;
};
}
AI.SelectPlace(0);
}
public bool SpellNegatable(bool isCounter = false, ClientCard target = null)
{
// target default set
if (target == null) target = Card;
// won't negate if not on field
if (target.Location != CardLocation.SpellZone && target.Location != CardLocation.Hand) return false;
// negate judge
if (Enemy.HasInMonstersZone(CardId.NaturalExterio, true) && !isCounter) return true;
if (target.IsSpell())
{
if (Enemy.HasInMonstersZone(CardId.NaturalBeast, true)) return true;
if (Enemy.HasInSpellZone(CardId.ImperialOrder, true) || Bot.HasInSpellZone(CardId.ImperialOrder, true)) return true;
if (Enemy.HasInMonstersZone(CardId.SwordsmanLV7, true) || Bot.HasInMonstersZone(CardId.SwordsmanLV7, true)) return true;
}
if (target.IsTrap())
{
if (Enemy.HasInSpellZone(CardId.RoyalDecreel, true) || Bot.HasInSpellZone(CardId.RoyalDecreel, true)) return true;
}
// how to get here?
return false;
}
private bool SummonToDef()
{
AI.SelectPosition(CardPosition.Defence);
return true;
}
private bool RegulatorEffect()
{
if (Card.Location == CardLocation.MonsterZone)
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
AI.SelectCard(Monsters.TimeThiefCronocorder);
AI.SelectCard(Monsters.TimeThiefWinder);
return true;
}
if (Card.Location == CardLocation.Grave)
{
return true;
}
return false;
}
private bool PerpertuaEffect()
{
if (Bot.HasInGraveyard(XYZs.TimeThiefRedoer))
{
AI.SelectCard(XYZs.TimeThiefRedoer);
return true;
}
if (Bot.HasInMonstersZone(XYZs.TimeThiefRedoer))
{
AI.SelectCard(Monsters.TimeThiefBezelShip);
AI.SelectNextCard(XYZs.TimeThiefRedoer);
return true;
}
return false;
}
private int _totalAttack;
private int _totalBotAttack;
private bool RedoerEffect()
{
List<ClientCard> enemy = Enemy.GetMonstersInMainZone();
List<int> units = Card.Overlays;
if (Duel.Phase == DuelPhase.Standby && (AI.Executor.Util.GetStringId(XYZs.TimeThiefRedoer, 0) ==
ActivateDescription))
{
return true;
}
try
{
for (int i = 0; i < enemy.Count; i++)
{
_totalAttack += enemy[i].Attack;
}
foreach (var t in Bot.GetMonsters())
{
_totalBotAttack += t.Attack;
}
if (_totalAttack > Bot.LifePoints + _totalBotAttack)
{
return false;
}
foreach (var t in enemy)
{
if (t.Attack < 2400 || !t.IsAttack()) continue;
try
{
AI.SelectCard(t.Id);
AI.SelectCard(t.Id);
}
catch { }
return true;
}
}
catch { }
if (Bot.UnderAttack)
{
//AI.SelectCard(Util.GetBestEnemyMonster());
return true;
}
return false;
}
private bool RetrograteEffect()
{
if (Card.Owner == 1)
{
return true;
}
return false;
}
private bool TimeThiefStartupEffect()
{
if (Card.Location == CardLocation.Hand)
{
if (Bot.HasInHand(Monsters.TimeThiefRegulator) && !(Bot.GetMonsterCount() > 0))
{
AI.SelectCard(Monsters.TimeThiefRegulator);
return true;
}
if (Bot.HasInHand(Monsters.TimeThiefWinder) && Bot.GetMonsterCount() > 1)
{
AI.SelectCard(Monsters.TimeThiefWinder);
return true;
}
return true;
}
if (Card.Location == CardLocation.Grave)
{
AI.SelectCard(Monsters.TimeThiefCronocorder);
AI.SelectCard(Spells.TimeThiefHack);
AI.SelectCard(Traps.TimeThiefFlyBack);
return true;
}
return false;
}
private bool FoolishBurialTarget()
{
AI.SelectCard(Monsters.PerformTrickClown);
return true;
}
private bool TrickClownEffect()
{
if (Bot.LifePoints <= 1000)
{
return false;
}
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool GagagaCowboySummon()
{
if (Enemy.LifePoints <= 800 || (Bot.GetMonsterCount() >= 4 && Enemy.LifePoints <= 1600))
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool DarkRebellionXyzDragonSummon()
{
int selfBestAttack = Util.GetBestAttack(Bot);
int oppoBestAttack = Util.GetBestAttack(Enemy);
return selfBestAttack <= oppoBestAttack;
}
private bool DarkRebellionXyzDragonEffect()
{
int oppoBestAttack = Util.GetBestAttack(Enemy);
ClientCard target = Util.GetOneEnemyBetterThanValue(oppoBestAttack, true);
if (target != null)
{
AI.SelectCard(0);
AI.SelectNextCard(target);
}
return true;
}
private bool ThunderKingRaiOhsummon()
{
if (Bot.MonsterZone[0] == null)
AI.SelectPlace(Zones.z0);
else
AI.SelectPlace(Zones.z4);
return true;
}
private bool ThunderKingRaiOheff()
{
if (DefaultOnlyHorusSpSummoning()) return false;
if (Duel.SummoningCards.Count > 0)
{
foreach (ClientCard m in Duel.SummoningCards)
{
if (m.Attack >= 1900)
return true;
}
}
return false;
}
private bool Crackdowneff()
{
if (Util.GetOneEnemyBetterThanMyBest(true, true) != null && Bot.UnderAttack)
AI.SelectCard(Util.GetOneEnemyBetterThanMyBest(true, true));
return Util.GetOneEnemyBetterThanMyBest(true, true) != null && Bot.UnderAttack;
}
private bool PotOfDesireseff()
{
return Bot.Deck.Count > 14 && !DefaultSpellWillBeNegated();
}
// activate of PotofExtravagance
public bool PotofExtravaganceActivate()
{
// won't activate if it'll be negate
if (SpellNegatable()) return false;
SelectSTPlace(Card, true);
AI.SelectOption(1);
return true;
}
}
}
@@ -0,0 +1,574 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Toadally Awesome", "AI_ToadallyAwesome")]
public class ToadallyAwesomeExecutor : DefaultExecutor
{
public class CardId
{
public const int CryomancerOfTheIceBarrier = 23950192;
public const int DewdarkOfTheIceBarrier = 90311614;
public const int SwapFrog = 9126351;
public const int PriorOfTheIceBarrier = 50088247;
public const int Ronintoadin = 1357146;
public const int DupeFrog = 46239604;
public const int GraydleSlimeJr = 80250319;
public const int GalaxyCyclone = 5133471;
public const int HarpiesFeatherDuster = 18144506;
public const int Surface = 33057951;
public const int DarkHole = 53129443;
public const int CardDestruction = 72892473;
public const int FoolishBurial = 81439173;
public const int MonsterReborn = 83764718;
public const int MedallionOfTheIceBarrier = 84206435;
public const int Salvage = 96947648;
public const int AquariumStage = 29047353;
public const int HeraldOfTheArcLight = 79606837;
public const int ToadallyAwesome = 90809975;
public const int SkyCavalryCentaurea = 36776089;
public const int DaigustoPhoenix = 2766877;
public const int CatShark = 84224627;
public const int MysticalSpaceTyphoon = 5318639;
public const int BookOfMoon = 14087893;
public const int CallOfTheHaunted = 97077563;
public const int TorrentialTribute = 53582587;
}
public ToadallyAwesomeExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, CardId.GalaxyCyclone, DefaultGalaxyCyclone);
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.AquariumStage, AquariumStageEffect);
AddExecutor(ExecutorType.Activate, CardId.MedallionOfTheIceBarrier, MedallionOfTheIceBarrierEffect);
AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialEffect);
AddExecutor(ExecutorType.SpSummon, CardId.PriorOfTheIceBarrier);
AddExecutor(ExecutorType.Summon, CardId.GraydleSlimeJr, GraydleSlimeJrSummon);
AddExecutor(ExecutorType.SpSummon, CardId.SwapFrog, SwapFrogSpsummon);
AddExecutor(ExecutorType.Activate, CardId.SwapFrog, SwapFrogEffect);
AddExecutor(ExecutorType.Activate, CardId.GraydleSlimeJr, GraydleSlimeJrEffect);
AddExecutor(ExecutorType.Activate, CardId.Ronintoadin, RonintoadinEffect);
AddExecutor(ExecutorType.Activate, CardId.PriorOfTheIceBarrier);
AddExecutor(ExecutorType.Activate, CardId.DupeFrog);
AddExecutor(ExecutorType.Activate, CardId.Surface, SurfaceEffect);
AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, SurfaceEffect);
AddExecutor(ExecutorType.Activate, CardId.Salvage, SalvageEffect);
AddExecutor(ExecutorType.Summon, CardId.SwapFrog);
AddExecutor(ExecutorType.Summon, CardId.DewdarkOfTheIceBarrier, IceBarrierSummon);
AddExecutor(ExecutorType.Summon, CardId.CryomancerOfTheIceBarrier, IceBarrierSummon);
AddExecutor(ExecutorType.Activate, CardId.CardDestruction);
AddExecutor(ExecutorType.Summon, CardId.GraydleSlimeJr, NormalSummon);
AddExecutor(ExecutorType.Summon, CardId.PriorOfTheIceBarrier, NormalSummon);
AddExecutor(ExecutorType.Summon, CardId.Ronintoadin, NormalSummon);
AddExecutor(ExecutorType.Summon, CardId.DupeFrog, NormalSummon);
AddExecutor(ExecutorType.Summon, CardId.PriorOfTheIceBarrier, PriorOfTheIceBarrierSummon);
AddExecutor(ExecutorType.SpSummon, CardId.CatShark, CatSharkSummon);
AddExecutor(ExecutorType.Activate, CardId.CatShark, CatSharkEffect);
AddExecutor(ExecutorType.SpSummon, CardId.SkyCavalryCentaurea, SkyCavalryCentaureaSummon);
AddExecutor(ExecutorType.Activate, CardId.SkyCavalryCentaurea);
AddExecutor(ExecutorType.SpSummon, CardId.DaigustoPhoenix, DaigustoPhoenixSummon);
AddExecutor(ExecutorType.Activate, CardId.DaigustoPhoenix);
AddExecutor(ExecutorType.SpSummon, CardId.ToadallyAwesome);
AddExecutor(ExecutorType.Activate, CardId.ToadallyAwesome, ToadallyAwesomeEffect);
AddExecutor(ExecutorType.SpSummon, CardId.HeraldOfTheArcLight, HeraldOfTheArcLightSummon);
AddExecutor(ExecutorType.Activate, CardId.HeraldOfTheArcLight);
AddExecutor(ExecutorType.MonsterSet, CardId.GraydleSlimeJr);
AddExecutor(ExecutorType.MonsterSet, CardId.DupeFrog);
AddExecutor(ExecutorType.MonsterSet, CardId.Ronintoadin);
AddExecutor(ExecutorType.Repos, Repos);
// cards got by Toadally Awesome
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
AddExecutor(ExecutorType.Activate, CardId.BookOfMoon, DefaultBookOfMoon);
AddExecutor(ExecutorType.Activate, CardId.CallOfTheHaunted, SurfaceEffect);
AddExecutor(ExecutorType.Activate, CardId.TorrentialTribute, DefaultTorrentialTribute);
AddExecutor(ExecutorType.Activate, OtherSpellEffect);
AddExecutor(ExecutorType.Activate, OtherTrapEffect);
AddExecutor(ExecutorType.Activate, OtherMonsterEffect);
}
public override bool OnSelectHand()
{
return true;
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (!defender.IsMonsterHasPreventActivationEffectInBattle())
{
if (attacker.IsCode(CardId.SkyCavalryCentaurea) && !attacker.IsDisabled() && attacker.HasXyzMaterial())
attacker.RealPower = Bot.LifePoints + attacker.Attack;
}
return base.OnPreBattleBetween(attacker, defender);
}
private bool MedallionOfTheIceBarrierEffect()
{
if (Bot.HasInHand(new[]
{
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier
}) || Bot.HasInMonstersZone(new[]
{
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier
}))
{
AI.SelectCard(CardId.PriorOfTheIceBarrier);
}
else
{
AI.SelectCard(
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier
);
}
return true;
}
private bool SurfaceEffect()
{
AI.SelectCard(
CardId.ToadallyAwesome,
CardId.HeraldOfTheArcLight,
CardId.SwapFrog,
CardId.DewdarkOfTheIceBarrier,
CardId.CryomancerOfTheIceBarrier,
CardId.DupeFrog,
CardId.Ronintoadin,
CardId.GraydleSlimeJr
);
return true;
}
private bool AquariumStageEffect()
{
if (Card.Location == CardLocation.Grave)
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return SurfaceEffect();
}
return true;
}
private bool FoolishBurialEffect()
{
if (Bot.HasInHand(CardId.GraydleSlimeJr) && !Bot.HasInGraveyard(CardId.GraydleSlimeJr))
AI.SelectCard(CardId.GraydleSlimeJr);
else if (Bot.HasInGraveyard(CardId.Ronintoadin) && !Bot.HasInGraveyard(CardId.DupeFrog))
AI.SelectCard(CardId.DupeFrog);
else if (Bot.HasInGraveyard(CardId.DupeFrog) && !Bot.HasInGraveyard(CardId.Ronintoadin))
AI.SelectCard(CardId.Ronintoadin);
else
AI.SelectCard(
CardId.GraydleSlimeJr,
CardId.Ronintoadin,
CardId.DupeFrog,
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier,
CardId.PriorOfTheIceBarrier,
CardId.SwapFrog
);
return true;
}
private bool SalvageEffect()
{
AI.SelectCard(
CardId.SwapFrog,
CardId.PriorOfTheIceBarrier,
CardId.GraydleSlimeJr
);
return true;
}
private bool SwapFrogSpsummon()
{
if (Bot.GetCountCardInZone(Bot.Hand, CardId.GraydleSlimeJr)>=2 && !Bot.HasInGraveyard(CardId.GraydleSlimeJr))
AI.SelectCard(CardId.GraydleSlimeJr);
else if (Bot.HasInGraveyard(CardId.Ronintoadin) && !Bot.HasInGraveyard(CardId.DupeFrog))
AI.SelectCard(CardId.DupeFrog);
else if (Bot.HasInGraveyard(CardId.DupeFrog) && !Bot.HasInGraveyard(CardId.Ronintoadin))
AI.SelectCard(CardId.Ronintoadin);
else
AI.SelectCard(
CardId.Ronintoadin,
CardId.DupeFrog,
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier,
CardId.PriorOfTheIceBarrier,
CardId.GraydleSlimeJr,
CardId.SwapFrog
);
return true;
}
private bool SwapFrogEffect()
{
if (ActivateDescription == -1)
{
return FoolishBurialEffect();
}
else
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (Bot.HasInHand(CardId.DupeFrog))
{
AI.SelectCard(
CardId.PriorOfTheIceBarrier,
CardId.GraydleSlimeJr,
CardId.SwapFrog
);
return true;
}
}
return false;
}
private bool GraydleSlimeJrSummon()
{
return Bot.HasInGraveyard(CardId.GraydleSlimeJr);
}
private bool GraydleSlimeJrEffect()
{
AI.SelectCard(CardId.GraydleSlimeJr);
AI.SelectPosition(CardPosition.FaceUpDefence);
AI.SelectNextCard(
CardId.SwapFrog,
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier,
CardId.Ronintoadin,
CardId.DupeFrog,
CardId.PriorOfTheIceBarrier,
CardId.GraydleSlimeJr
);
return true;
}
private bool RonintoadinEffect()
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool NormalSummon()
{
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.Level==2)
{
return true;
}
}
return false;
}
private bool IceBarrierSummon()
{
return Bot.GetCountCardInZone(Bot.Hand, CardId.PriorOfTheIceBarrier) > 0;
}
private bool PriorOfTheIceBarrierSummon()
{
return Bot.GetCountCardInZone(Bot.Hand, CardId.PriorOfTheIceBarrier) >= 2;
}
private bool ToadallyAwesomeEffect()
{
if (Duel.CurrentChain.Count > 0)
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
// negate effect, select a cost for it
List<ClientCard> monsters = Bot.GetMonsters();
IList<int> suitableCost = new[] {
CardId.SwapFrog,
CardId.Ronintoadin,
CardId.GraydleSlimeJr,
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier
};
foreach (ClientCard monster in monsters)
{
if (monster.IsCode(suitableCost))
{
AI.SelectCard(monster);
return true;
}
}
if (!Bot.HasInSpellZone(CardId.AquariumStage, true))
{
foreach (ClientCard monster in monsters)
{
if (monster.IsCode(CardId.DupeFrog))
{
AI.SelectCard(monster);
return true;
}
}
}
List<ClientCard> hands = Bot.Hand.GetMonsters();
if (Bot.GetCountCardInZone(Bot.Hand, CardId.GraydleSlimeJr) >= 2)
{
foreach (ClientCard monster in hands)
{
if (monster.IsCode(CardId.GraydleSlimeJr))
{
AI.SelectCard(monster);
return true;
}
}
}
if (Bot.HasInGraveyard(CardId.Ronintoadin) && !Bot.HasInGraveyard(CardId.DupeFrog) && !Bot.HasInGraveyard(CardId.SwapFrog))
{
foreach (ClientCard monster in hands)
{
if (monster.IsCode(CardId.DupeFrog))
{
AI.SelectCard(monster);
return true;
}
}
}
foreach (ClientCard monster in hands)
{
if (monster.IsCode(CardId.Ronintoadin, CardId.DupeFrog))
{
AI.SelectCard(monster);
return true;
}
}
foreach (ClientCard monster in hands)
{
AI.SelectCard(monster);
return true;
}
return true;
}
else if (Card.Location == CardLocation.Grave)
{
if (!Bot.HasInExtra(CardId.ToadallyAwesome))
{
AI.SelectCard(CardId.ToadallyAwesome);
}
else
{
AI.SelectCard(
CardId.SwapFrog,
CardId.PriorOfTheIceBarrier,
CardId.GraydleSlimeJr
);
}
return true;
}
else if (Duel.Phase == DuelPhase.Standby)
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
SelectXYZDetach(Card.Overlays);
if (Duel.Player == 0)
{
AI.SelectNextCard(
CardId.SwapFrog,
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier,
CardId.Ronintoadin,
CardId.DupeFrog,
CardId.GraydleSlimeJr
);
}
else
{
AI.SelectNextCard(
CardId.DupeFrog,
CardId.SwapFrog,
CardId.Ronintoadin,
CardId.GraydleSlimeJr,
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier
);
AI.SelectPosition(CardPosition.FaceUpDefence);
}
return true;
}
return true;
}
private bool CatSharkSummon()
{
if (Bot.HasInMonstersZone(CardId.ToadallyAwesome)
&& ((Util.IsOneEnemyBetter(true)
&& !Bot.HasInMonstersZone(new[]
{
CardId.CatShark,
CardId.SkyCavalryCentaurea
}, true, true))
|| !Bot.HasInExtra(CardId.ToadallyAwesome)))
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool CatSharkEffect()
{
List<ClientCard> monsters = Bot.GetMonsters();
foreach (ClientCard monster in monsters)
{
if (monster.IsCode(CardId.ToadallyAwesome) && monster.Attack <= 2200)
{
SelectXYZDetach(Card.Overlays);
AI.SelectNextCard(monster);
return true;
}
}
foreach (ClientCard monster in monsters)
{
if (monster.IsCode(CardId.SkyCavalryCentaurea) && monster.Attack <= 2000)
{
SelectXYZDetach(Card.Overlays);
AI.SelectNextCard(monster);
return true;
}
}
foreach (ClientCard monster in monsters)
{
if (monster.IsCode(CardId.DaigustoPhoenix) && monster.Attack <= 1500)
{
SelectXYZDetach(Card.Overlays);
AI.SelectNextCard(monster);
return true;
}
}
return false;
}
private bool SkyCavalryCentaureaSummon()
{
int num = 0;
foreach (ClientCard monster in Bot.GetMonsters())
{
if (monster.Level ==2)
{
num++;
}
}
return Util.IsOneEnemyBetter(true)
&& Util.GetBestAttack(Enemy) > 2200
&& num < 4
&& !Bot.HasInMonstersZone(new[]
{
CardId.SkyCavalryCentaurea
}, true, true);
}
private bool DaigustoPhoenixSummon()
{
if (Duel.Turn != 1)
{
int attack = 0;
int defence = 0;
foreach (ClientCard monster in Bot.GetMonsters())
{
if (!monster.IsDefense())
{
attack += monster.Attack;
}
}
foreach (ClientCard monster in Enemy.GetMonsters())
{
defence += monster.GetDefensePower();
}
if (attack - 2000 - defence > Enemy.LifePoints && !Util.IsOneEnemyBetter(true))
return true;
}
return false;
}
private bool HeraldOfTheArcLightSummon()
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool Repos()
{
if (Card.IsFacedown())
return true;
if (Card.IsDefense() && !Util.IsAllEnemyBetter(true) && Card.Attack >= Card.Defense)
return true;
return false;
}
private bool OtherSpellEffect()
{
foreach (CardExecutor exec in Executors)
{
if (exec.Type == Type && exec.CardId == Card.Id)
return false;
}
return Card.IsSpell();
}
private bool OtherTrapEffect()
{
foreach (CardExecutor exec in Executors)
{
if (exec.Type == Type && exec.CardId == Card.Id)
return false;
}
return Card.IsTrap() && DefaultTrap();
}
private bool OtherMonsterEffect()
{
foreach (CardExecutor exec in Executors)
{
if (exec.Type == Type && exec.CardId == Card.Id)
return false;
}
return Card.IsMonster();
}
private void SelectXYZDetach(List<int> Overlays)
{
if (Overlays.Contains(CardId.GraydleSlimeJr) && Bot.HasInHand(CardId.GraydleSlimeJr) && !Bot.HasInGraveyard(CardId.GraydleSlimeJr))
AI.SelectCard(CardId.GraydleSlimeJr);
else if (Overlays.Contains(CardId.DupeFrog) && Bot.HasInGraveyard(CardId.Ronintoadin) && !Bot.HasInGraveyard(CardId.DupeFrog))
AI.SelectCard(CardId.DupeFrog);
else if (Overlays.Contains(CardId.Ronintoadin) && Bot.HasInGraveyard(CardId.DupeFrog) && !Bot.HasInGraveyard(CardId.Ronintoadin))
AI.SelectCard(CardId.Ronintoadin);
else
AI.SelectCard(
CardId.GraydleSlimeJr,
CardId.Ronintoadin,
CardId.DupeFrog,
CardId.CryomancerOfTheIceBarrier,
CardId.DewdarkOfTheIceBarrier,
CardId.PriorOfTheIceBarrier,
CardId.SwapFrog
);
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,313 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Yosenju", "AI_Yosenju")]
public class YosenjuExecutor : DefaultExecutor
{
public class CardId
{
public const int YosenjuKama1 = 65247798;
public const int YosenjuKama2 = 92246806;
public const int YosenjuKama3 = 28630501;
public const int YosenjuTsujik = 25244515;
public const int HarpiesFeatherDuster = 18144507;
public const int DarkHole = 53129443;
public const int CardOfDemise = 59750328;
public const int PotOfDuality = 98645731;
public const int CosmicCyclone = 8267140;
public const int QuakingMirrorForce = 40838625;
public const int DrowningMirrorForce = 47475363;
public const int StarlightRoad = 58120309;
public const int VanitysEmptiness = 5851097;
public const int MacroCosmos = 30241314;
public const int SolemnStrike = 40605147;
public const int SolemnWarning = 84749824;
public const int SolemnJudgment = 41420027;
public const int MagicDrain = 59344077;
public const int StardustDragon = 44508094;
public const int NumberS39UtopiatheLightning = 56832966;
public const int NumberS39UtopiaOne = 86532744;
public const int DarkRebellionXyzDragon = 16195942;
public const int Number39Utopia = 84013237;
public const int Number103Ragnazero = 94380860;
public const int BrotherhoodOfTheFireFistTigerKing = 96381979;
public const int Number106GiantHand = 63746411;
public const int CastelTheSkyblasterMusketeer = 82633039;
public const int DiamondDireWolf = 95169481;
public const int LightningChidori = 22653490;
public const int EvilswarmExcitonKnight = 46772449;
public const int AbyssDweller = 21044178;
public const int GagagaCowboy = 12014404;
}
bool CardOfDemiseUsed = false;
public YosenjuExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// do the end phase effect of Card Of Demise before Yosenjus return to hand
AddExecutor(ExecutorType.Activate, CardId.CardOfDemise, CardOfDemiseEPEffect);
// burn if enemy's LP is below 800
AddExecutor(ExecutorType.SpSummon, CardId.GagagaCowboy, GagagaCowboySummon);
AddExecutor(ExecutorType.Activate, CardId.GagagaCowboy);
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster, DefaultHarpiesFeatherDusterFirst);
AddExecutor(ExecutorType.Activate, CardId.CosmicCyclone, DefaultCosmicCyclone);
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.PotOfDuality, PotOfDualityEffect);
AddExecutor(ExecutorType.Summon, CardId.YosenjuKama1, HaveAnotherYosenjuWithSameNameInHand);
AddExecutor(ExecutorType.Summon, CardId.YosenjuKama2, HaveAnotherYosenjuWithSameNameInHand);
AddExecutor(ExecutorType.Summon, CardId.YosenjuKama3, HaveAnotherYosenjuWithSameNameInHand);
AddExecutor(ExecutorType.Summon, CardId.YosenjuKama1);
AddExecutor(ExecutorType.Summon, CardId.YosenjuKama2);
AddExecutor(ExecutorType.Summon, CardId.YosenjuKama3);
AddExecutor(ExecutorType.Summon, CardId.YosenjuTsujik);
AddExecutor(ExecutorType.Activate, CardId.YosenjuKama1, YosenjuEffect);
AddExecutor(ExecutorType.Activate, CardId.YosenjuKama2, YosenjuEffect);
AddExecutor(ExecutorType.Activate, CardId.YosenjuKama3, YosenjuEffect);
AddExecutor(ExecutorType.Activate, CardId.YosenjuTsujik, YosenjuEffect);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnJudgment, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnWarning, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.MacroCosmos, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.VanitysEmptiness, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.MagicDrain, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.DrowningMirrorForce, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.QuakingMirrorForce, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.StarlightRoad, TrapSetUnique);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnJudgment, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnWarning, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.MacroCosmos, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.VanitysEmptiness, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.MagicDrain, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.DrowningMirrorForce, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.QuakingMirrorForce, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.StarlightRoad, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.HarpiesFeatherDuster, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.DarkHole, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.PotOfDuality, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.CosmicCyclone, TrapSetWhenZoneFree);
AddExecutor(ExecutorType.SpellSet, CardId.CardOfDemise);
AddExecutor(ExecutorType.Activate, CardId.CardOfDemise, CardOfDemiseEffect);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnJudgment, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.SolemnWarning, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.MacroCosmos, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.VanitysEmptiness, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.MagicDrain, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.DrowningMirrorForce, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.QuakingMirrorForce, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.StarlightRoad, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.HarpiesFeatherDuster, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.DarkHole, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.PotOfDuality, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpellSet, CardId.CosmicCyclone, CardOfDemiseAcivated);
AddExecutor(ExecutorType.SpSummon, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightSummon);
AddExecutor(ExecutorType.Activate, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect);
AddExecutor(ExecutorType.SpSummon, CardId.DarkRebellionXyzDragon, DarkRebellionXyzDragonSummon);
AddExecutor(ExecutorType.Activate, CardId.DarkRebellionXyzDragon, DarkRebellionXyzDragonEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Number39Utopia, DefaultNumberS39UtopiaTheLightningSummon);
AddExecutor(ExecutorType.SpSummon, CardId.NumberS39UtopiaOne);
AddExecutor(ExecutorType.SpSummon, CardId.NumberS39UtopiatheLightning);
AddExecutor(ExecutorType.Activate, CardId.NumberS39UtopiatheLightning, DefaultNumberS39UtopiaTheLightningEffect);
AddExecutor(ExecutorType.Activate, CardId.StardustDragon, DefaultStardustDragonEffect);
AddExecutor(ExecutorType.Activate, CardId.StarlightRoad, DefaultTrap);
AddExecutor(ExecutorType.Activate, CardId.MagicDrain);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike);
AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, DefaultSolemnJudgment);
AddExecutor(ExecutorType.Activate, CardId.MacroCosmos, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.VanitysEmptiness, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.DrowningMirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Activate, CardId.QuakingMirrorForce, DefaultUniqueTrap);
AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
}
public override bool OnSelectHand()
{
// go first
return true;
}
public override void OnNewTurn()
{
CardOfDemiseUsed = false;
base.OnNewTurn();
}
public override bool OnSelectYesNo(int desc)
{
// Yosenju Kama 2 shouldn't attack directly at most times
if (Card == null)
return true;
// Logger.DebugWriteLine(Card.Name);
if (Card.IsCode(CardId.YosenjuKama2))
return Card.ShouldDirectAttack;
else
return true;
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (!defender.IsMonsterHasPreventActivationEffectInBattle())
{
if (attacker.Attribute == (int)CardAttribute.Wind && Bot.HasInHand(CardId.YosenjuTsujik))
attacker.RealPower = attacker.RealPower + 1000;
}
return base.OnPreBattleBetween(attacker, defender);
}
public override IList<ClientCard> OnSelectXyzMaterial(IList<ClientCard> cards, int min, int max)
{
IList<ClientCard> result = Util.SelectPreferredCards(CardId.YosenjuTsujik, cards, min, max);
return Util.CheckSelectCount(result, cards, min, max);
}
private bool PotOfDualityEffect()
{
if (CardOfDemiseUsed)
{
AI.SelectCard(
CardId.StarlightRoad,
CardId.MagicDrain,
CardId.SolemnJudgment,
CardId.VanitysEmptiness,
CardId.HarpiesFeatherDuster,
CardId.DrowningMirrorForce,
CardId.QuakingMirrorForce,
CardId.SolemnStrike,
CardId.SolemnWarning,
CardId.MacroCosmos,
CardId.CardOfDemise
);
}
else
{
AI.SelectCard(
CardId.YosenjuKama3,
CardId.YosenjuKama1,
CardId.YosenjuKama2,
CardId.StarlightRoad,
CardId.MagicDrain,
CardId.VanitysEmptiness,
CardId.HarpiesFeatherDuster,
CardId.DrowningMirrorForce,
CardId.QuakingMirrorForce,
CardId.SolemnStrike,
CardId.SolemnJudgment,
CardId.SolemnWarning,
CardId.MacroCosmos,
CardId.CardOfDemise
);
}
return true;
}
private bool CardOfDemiseEffect()
{
if (Util.IsTurn1OrMain2())
{
CardOfDemiseUsed = true;
return true;
}
return false;
}
private bool HaveAnotherYosenjuWithSameNameInHand()
{
foreach (ClientCard card in Bot.Hand.GetMonsters())
{
if (!card.Equals(Card) && card.IsCode(Card.Id))
return true;
}
return false;
}
private bool TrapSetUnique()
{
foreach (ClientCard card in Bot.GetSpells())
{
if (card.IsCode(Card.Id))
return false;
}
return TrapSetWhenZoneFree();
}
private bool TrapSetWhenZoneFree()
{
return Bot.GetSpellCountWithoutField() < 4;
}
private bool CardOfDemiseAcivated()
{
return CardOfDemiseUsed;
}
private bool YosenjuEffect()
{
// Don't activate the return to hand effect first
if (Duel.Phase == DuelPhase.End)
return false;
AI.SelectCard(CardId.YosenjuKama1, CardId.YosenjuKama2, CardId.YosenjuKama3);
return true;
}
private bool CardOfDemiseEPEffect()
{
// do the end phase effect of Card Of Demise before Yosenjus return to hand
return Duel.Phase == DuelPhase.End;
}
private bool GagagaCowboySummon()
{
if (Enemy.LifePoints <= 800 || (Bot.GetMonsterCount()>=4 && Enemy.LifePoints <= 1600))
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool DarkRebellionXyzDragonSummon()
{
int selfBestAttack = Util.GetBestAttack(Bot);
int oppoBestAttack = Util.GetBestAttack(Enemy);
return selfBestAttack <= oppoBestAttack;
}
private bool DarkRebellionXyzDragonEffect()
{
int oppoBestAttack = Util.GetBestAttack(Enemy);
ClientCard target = Util.GetOneEnemyBetterThanValue(oppoBestAttack, true);
if (target != null)
{
AI.SelectCard(0);
AI.SelectNextCard(target);
}
return true;
}
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,290 @@
using System;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
using YGOSharp.OCGWrapper.Enums;
namespace WindBot.Game.AI.Decks
{
[Deck("Zexal Weapons", "AI_ZexalWeapons")]
class ZexalWeaponsExecutor : DefaultExecutor
{
public class CardId
{
public const int CyberDragon = 70095155;
public const int ZwTornadoBringer = 81471108;
public const int ZwLightningBlade = 45082499;
public const int ZwAsuraStrike = 40941889;
public const int SolarWindJammer = 33911264;
public const int PhotonTrasher = 65367484;
public const int StarDrawing = 24610207;
public const int SacredCrane = 30914564;
public const int Goblindbergh = 25259669;
public const int Honest = 37742478;
public const int Kagetokage = 94656263;
public const int HeroicChallengerExtraSword = 34143852;
public const int TinGoldfish = 18063928;
public const int SummonerMonk = 423585;
public const int InstantFusion = 1845204;
public const int Raigeki = 12580477;
public const int ReinforcementOfTheArmy = 32807846;
public const int DarkHole = 53129443;
public const int MysticalSpaceTyphoon = 5318639;
public const int BreakthroughSkill = 78474168;
public const int SolemnWarning = 84749824;
public const int SolemnStrike = 40605147;
public const int XyzChangeTactics = 11705261;
public const int FlameSwordsman = 45231177;
public const int DarkfireDragon = 17881964;
public const int GaiaDragonTheThunderCharger = 91949988;
public const int ZwLionArms = 60992364;
public const int AdreusKeeperOfArmageddon = 94119480;
public const int Number61Volcasaurus = 29669359;
public const int GemKnightPearl = 71594310;
public const int Number39Utopia = 84013237;
public const int NumberS39UtopiaOne = 86532744;
public const int NumberS39UtopiatheLightning = 56832966;
public const int MaestrokeTheSymphonyDjinn = 25341652;
public const int GagagaCowboy = 12014404;
}
public ZexalWeaponsExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// Quick spells
AddExecutor(ExecutorType.Activate, CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon);
// Spell cards
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.Activate, CardId.Raigeki, DefaultRaigeki);
AddExecutor(ExecutorType.Activate, CardId.ReinforcementOfTheArmy, ReinforcementOfTheArmy);
AddExecutor(ExecutorType.Activate, CardId.XyzChangeTactics, XyzChangeTactics);
// XYZ summons
AddExecutor(ExecutorType.SpSummon, CardId.Number39Utopia);
AddExecutor(ExecutorType.SpSummon, CardId.NumberS39UtopiaOne);
AddExecutor(ExecutorType.SpSummon, CardId.NumberS39UtopiatheLightning);
AddExecutor(ExecutorType.SpSummon, CardId.Number61Volcasaurus, Number61Volcasaurus);
AddExecutor(ExecutorType.SpSummon, CardId.ZwLionArms);
AddExecutor(ExecutorType.SpSummon, CardId.AdreusKeeperOfArmageddon);
// XYZ effects
AddExecutor(ExecutorType.Activate, CardId.Number39Utopia, Number39Utopia);
AddExecutor(ExecutorType.Activate, CardId.NumberS39UtopiaOne);
AddExecutor(ExecutorType.Activate, CardId.NumberS39UtopiatheLightning, DefaultNumberS39UtopiaTheLightningEffect);
AddExecutor(ExecutorType.Activate, CardId.ZwLionArms, ZwLionArms);
AddExecutor(ExecutorType.Activate, CardId.AdreusKeeperOfArmageddon);
AddExecutor(ExecutorType.Activate, CardId.Number61Volcasaurus);
// Weapons
AddExecutor(ExecutorType.Activate, CardId.ZwTornadoBringer, ZwWeapon);
AddExecutor(ExecutorType.Activate, CardId.ZwLightningBlade, ZwWeapon);
AddExecutor(ExecutorType.Activate, CardId.ZwAsuraStrike, ZwWeapon);
// Special summons
AddExecutor(ExecutorType.SpSummon, CardId.PhotonTrasher);
AddExecutor(ExecutorType.SpSummon, CardId.CyberDragon);
AddExecutor(ExecutorType.SpSummon, CardId.SolarWindJammer, SolarWindJammer);
AddExecutor(ExecutorType.Activate, CardId.InstantFusion, InstantFusion);
// Normal summons
AddExecutor(ExecutorType.Summon, CardId.Goblindbergh, GoblindberghFirst);
AddExecutor(ExecutorType.Summon, CardId.TinGoldfish, GoblindberghFirst);
AddExecutor(ExecutorType.Summon, CardId.StarDrawing);
AddExecutor(ExecutorType.Summon, CardId.SacredCrane);
AddExecutor(ExecutorType.Summon, CardId.HeroicChallengerExtraSword);
AddExecutor(ExecutorType.Summon, CardId.Goblindbergh);
AddExecutor(ExecutorType.Summon, CardId.TinGoldfish);
AddExecutor(ExecutorType.Summon, CardId.SummonerMonk);
AddExecutor(ExecutorType.Summon, CardId.Honest);
// Summons: Effects
AddExecutor(ExecutorType.Activate, CardId.Goblindbergh, GoblindberghEffect);
AddExecutor(ExecutorType.Activate, CardId.TinGoldfish, GoblindberghEffect);
AddExecutor(ExecutorType.Activate, CardId.Kagetokage, KagetokageEffect);
AddExecutor(ExecutorType.Activate, CardId.SummonerMonk, SummonerMonkEffect);
AddExecutor(ExecutorType.Activate, CardId.Honest, DefaultHonestEffect);
// Reposition
AddExecutor(ExecutorType.Repos, MonsterRepos);
// Spummon GaiaDragonTheThunderCharger if Volcasaurus or ZwLionArms had been used
AddExecutor(ExecutorType.SpSummon, CardId.GaiaDragonTheThunderCharger);
// Set and activate traps
AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
AddExecutor(ExecutorType.Activate, CardId.BreakthroughSkill, DefaultBreakthroughSkill);
AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, DefaultSolemnWarning);
AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike);
}
public override bool OnSelectHand()
{
return false;
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (!defender.IsMonsterHasPreventActivationEffectInBattle())
{
if (attacker.Attribute == (int)CardAttribute.Light && Bot.HasInHand(CardId.Honest))
attacker.RealPower = attacker.RealPower + defender.Attack;
}
return base.OnPreBattleBetween(attacker, defender);
}
public override IList<ClientCard> OnSelectXyzMaterial(IList<ClientCard> cards, int min, int max)
{
IList<ClientCard> result = Util.SelectPreferredCards(new[] {
CardId.StarDrawing,
CardId.SolarWindJammer,
CardId.Goblindbergh
}, cards, min, max);
return Util.CheckSelectCount(result, cards, min, max);
}
private bool Number39Utopia()
{
if (!Util.HasChainedTrap(0) && Duel.Player == 1 && Duel.Phase == DuelPhase.BattleStart && Card.HasXyzMaterial(2))
return true;
return false;
}
private bool Number61Volcasaurus()
{
return Util.IsOneEnemyBetterThanValue(2000, false);
}
private bool ZwLionArms()
{
if (ActivateDescription == Util.GetStringId(CardId.ZwLionArms, 0))
return true;
if (ActivateDescription == Util.GetStringId(CardId.ZwLionArms, 1))
return !Card.IsDisabled() && ZwWeapon();
return false;
}
private bool ZwWeapon()
{
return true;
}
private bool ReinforcementOfTheArmy()
{
AI.SelectCard(
CardId.Goblindbergh,
CardId.TinGoldfish,
CardId.StarDrawing,
CardId.Kagetokage,
CardId.SacredCrane
);
return true;
}
private bool InstantFusion()
{
if (Bot.LifePoints <= 1000)
return false;
int count4 = 0;
int count5 = 0;
foreach (ClientCard card in Bot.GetMonsters())
{
if (card.Level == 5)
++count5;
if (card.Level == 4)
++count4;
}
if (count5 == 1)
{
AI.SelectCard(CardId.FlameSwordsman);
return true;
}
else if (count4 == 1)
{
AI.SelectCard(CardId.DarkfireDragon);
return true;
}
return false;
}
private bool XyzChangeTactics()
{
return Bot.LifePoints > 500;
}
private bool GoblindberghFirst()
{
foreach (ClientCard card in Bot.Hand.GetMonsters())
{
if (!card.Equals(Card) && card.Level == 4)
return true;
}
return false;
}
private bool GoblindberghEffect()
{
AI.SelectCard(
CardId.SacredCrane,
CardId.HeroicChallengerExtraSword,
CardId.StarDrawing,
CardId.SummonerMonk
);
return true;
}
private bool KagetokageEffect()
{
var lastChainCard = Util.GetLastChainCard();
if (lastChainCard == null) return true;
return !lastChainCard.IsCode(CardId.Goblindbergh, CardId.TinGoldfish);
}
private bool SummonerMonkEffect()
{
IList<int> costs = new[]
{
CardId.XyzChangeTactics,
CardId.DarkHole,
CardId.MysticalSpaceTyphoon,
CardId.InstantFusion
};
if (Bot.HasInHand(costs))
{
AI.SelectCard(costs);
AI.SelectNextCard(
CardId.SacredCrane,
CardId.StarDrawing,
CardId.Goblindbergh,
CardId.TinGoldfish
);
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool SolarWindJammer()
{
if (!Bot.HasInHand(new[] {
CardId.StarDrawing,
CardId.InstantFusion
}))
return false;
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool MonsterRepos()
{
if (Card.IsCode(CardId.NumberS39UtopiatheLightning) && Card.IsAttack())
return false;
return base.DefaultMonsterRepos();
}
}
}
@@ -0,0 +1,594 @@
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
namespace WindBot.Game.AI.Decks
{
[Deck("Zoodiac", "AI_Zoodiac")]
class ZoodiacExecutor : DefaultExecutor
{
public class CardId
{
public const int JizukirutheStarDestroyingKaiju = 63941210;
public const int GadarlatheMysteryDustKaiju = 36956512;
public const int GamecieltheSeaTurtleKaiju = 55063751;
public const int RadiantheMultidimensionalKaiju = 28674152;
public const int KumongoustheStickyStringKaiju = 29726552;
public const int PhotonThrasher = 65367484;
public const int Thoroughblade = 77150143;
public const int Whiptail = 31755044;
public const int Ratpier = 78872731;
public const int AleisterTheInvoker = 86120751;
public const int HarpiesFeatherDuster = 18144506;
public const int DarkHole = 53129443;
public const int Terraforming = 73628505;
public const int Invocation = 74063034;
public const int MonsterReborn = 83764718;
public const int InterruptedKaijuSlumber = 99330325;
public const int ZoodiacBarrage = 46060017;
public const int FireFormationTenki = 57103969;
public const int MagicalMeltdown = 47679935;
public const int ZoodiacCombo = 73881652;
public const int InvokedMechaba = 75286621;
public const int InvokedMagellanica = 48791583;
public const int NumberS39UtopiatheLightning = 56832966;
public const int Number39Utopia = 84013237;
public const int DaigustoEmeral = 581014;
public const int Tigermortar = 11510448;
public const int Chakanine = 41375811;
public const int Drident = 48905153;
public const int Broadbull = 85115440;
}
bool TigermortarSpsummoned = false;
bool ChakanineSpsummoned = false;
bool BroadbullSpsummoned = false;
public ZoodiacExecutor(GameAI ai, Duel duel)
: base(ai, duel)
{
// Quick spells
AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster);
AddExecutor(ExecutorType.Activate, CardId.InterruptedKaijuSlumber, DefaultInterruptedKaijuSlumber);
AddExecutor(ExecutorType.Activate, CardId.DarkHole, DefaultDarkHole);
AddExecutor(ExecutorType.SpSummon, CardId.GamecieltheSeaTurtleKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, CardId.KumongoustheStickyStringKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, CardId.GadarlatheMysteryDustKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, CardId.RadiantheMultidimensionalKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.SpSummon, CardId.JizukirutheStarDestroyingKaiju, DefaultKaijuSpsummon);
AddExecutor(ExecutorType.Activate, CardId.Terraforming);
AddExecutor(ExecutorType.Activate, CardId.MagicalMeltdown);
AddExecutor(ExecutorType.Activate, CardId.FireFormationTenki, FireFormationTenkiEffect);
AddExecutor(ExecutorType.Activate, CardId.ZoodiacBarrage, ZoodiacBarrageEffect);
AddExecutor(ExecutorType.Activate, CardId.DaigustoEmeral, DaigustoEmeralEffect);
AddExecutor(ExecutorType.SpSummon, CardId.PhotonThrasher, PhotonThrasherSummon);
AddExecutor(ExecutorType.SpSummon, CardId.Number39Utopia, DefaultNumberS39UtopiaTheLightningSummon);
AddExecutor(ExecutorType.SpSummon, CardId.NumberS39UtopiatheLightning);
AddExecutor(ExecutorType.Activate, CardId.NumberS39UtopiatheLightning, DefaultNumberS39UtopiaTheLightningEffect);
AddExecutor(ExecutorType.Activate, CardId.InvokedMechaba, DefaultTrap);
AddExecutor(ExecutorType.Activate, RatpierMaterialEffect);
AddExecutor(ExecutorType.Activate, CardId.Drident, DridentEffect);
AddExecutor(ExecutorType.Activate, CardId.Broadbull, BroadbullEffect);
AddExecutor(ExecutorType.Activate, CardId.Tigermortar, TigermortarEffect);
AddExecutor(ExecutorType.Activate, CardId.Chakanine, ChakanineEffect);
AddExecutor(ExecutorType.SpSummon, CardId.Chakanine, ChakanineSummon);
AddExecutor(ExecutorType.SpSummon, CardId.Tigermortar, TigermortarSummon);
AddExecutor(ExecutorType.SpSummon, CardId.Broadbull, BroadbullSummon);
AddExecutor(ExecutorType.SpSummon, CardId.Drident, DridentSummon);
AddExecutor(ExecutorType.Summon, CardId.Ratpier);
AddExecutor(ExecutorType.Activate, CardId.Ratpier, RatpierEffect);
AddExecutor(ExecutorType.Summon, CardId.Thoroughblade);
AddExecutor(ExecutorType.Activate, CardId.Thoroughblade, RatpierEffect);
AddExecutor(ExecutorType.Summon, CardId.AleisterTheInvoker);
AddExecutor(ExecutorType.Activate, CardId.AleisterTheInvoker, AleisterTheInvokerEffect);
AddExecutor(ExecutorType.SpSummon, CardId.DaigustoEmeral, DaigustoEmeralSummon);
AddExecutor(ExecutorType.SpSummon, CardId.Broadbull, BroadbullXYZSummon);
AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, MonsterRebornEffect);
AddExecutor(ExecutorType.SpSummon, CardId.PhotonThrasher);
AddExecutor(ExecutorType.Summon, CardId.Whiptail);
AddExecutor(ExecutorType.Activate, CardId.Invocation, InvocationEffect);
AddExecutor(ExecutorType.Activate, CardId.Whiptail, WhiptailEffect);
AddExecutor(ExecutorType.Activate, CardId.ZoodiacCombo, ZoodiacComboEffect);
AddExecutor(ExecutorType.SpellSet, CardId.ZoodiacCombo);
AddExecutor(ExecutorType.Repos, MonsterRepos);
}
public override bool OnSelectHand()
{
// go first
return true;
}
public override void OnNewTurn()
{
// reset
TigermortarSpsummoned = false;
ChakanineSpsummoned = false;
BroadbullSpsummoned = false;
base.OnNewTurn();
}
public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender)
{
if (!defender.IsMonsterHasPreventActivationEffectInBattle())
{
if (attacker.HasType(CardType.Fusion) && Bot.HasInHand(CardId.AleisterTheInvoker))
attacker.RealPower = attacker.RealPower + 1000;
}
return base.OnPreBattleBetween(attacker, defender);
}
private bool PhotonThrasherSummon()
{
return Bot.HasInHand(CardId.AleisterTheInvoker)
&& !Bot.HasInHand(CardId.Ratpier)
&& !Bot.HasInHand(CardId.Thoroughblade);
}
private bool AleisterTheInvokerEffect()
{
if (Card.Location == CardLocation.Hand)
{
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
if (!(Duel.Phase == DuelPhase.BattleStep
|| Duel.Phase == DuelPhase.BattleStart
|| Duel.Phase == DuelPhase.Damage))
return false;
return Duel.Player==0
|| Util.IsOneEnemyBetter();
}
return true;
}
private bool InvocationEffect()
{
if (Card.Location == CardLocation.Grave)
return true;
IList<ClientCard> materials0 = Bot.Graveyard;
IList<ClientCard> materials1 = Enemy.Graveyard;
IList<ClientCard> mats = new List<ClientCard>();
ClientCard aleister = GetAleisterInGrave();
if (aleister != null)
{
mats.Add(aleister);
}
ClientCard mat = null;
foreach (ClientCard card in materials0)
{
if (card.HasAttribute(CardAttribute.Light))
{
mat = card;
break;
}
}
foreach (ClientCard card in materials1)
{
if (card.HasAttribute(CardAttribute.Light))
{
mat = card;
break;
}
}
if (mat != null)
{
mats.Add(mat);
AI.SelectCard(CardId.InvokedMechaba);
AI.SelectMaterials(mats);
AI.SelectPosition(CardPosition.FaceUpAttack);
return true;
}
foreach (ClientCard card in materials0)
{
if (card.HasAttribute(CardAttribute.Earth))
{
mat = card;
break;
}
}
foreach (ClientCard card in materials1)
{
if (card.HasAttribute(CardAttribute.Earth))
{
mat = card;
break;
}
}
if (mat != null)
{
mats.Add(mat);
AI.SelectCard(CardId.InvokedMagellanica);
AI.SelectMaterials(mats);
AI.SelectPosition(CardPosition.FaceUpAttack);
return true;
}
return false;
}
private ClientCard GetAleisterInGrave()
{
foreach (ClientCard card in Enemy.Graveyard)
{
if (card.IsCode(CardId.AleisterTheInvoker))
{
return card;
}
}
foreach (ClientCard card in Bot.Graveyard)
{
if (card.IsCode(CardId.AleisterTheInvoker))
{
return card;
}
}
return null;
}
private bool ChakanineSummon()
{
if (Bot.HasInMonstersZone(CardId.Ratpier) && !ChakanineSpsummoned)
{
AI.SelectMaterials(CardId.Ratpier);
AI.SelectYesNo(true);
AI.SelectPosition(CardPosition.FaceUpDefence);
ChakanineSpsummoned = true;
return true;
}
if (Bot.HasInMonstersZone(CardId.Broadbull) && !ChakanineSpsummoned)
{
AI.SelectMaterials(CardId.Broadbull);
AI.SelectYesNo(true);
AI.SelectPosition(CardPosition.FaceUpDefence);
ChakanineSpsummoned = true;
return true;
}
return false;
}
private bool ChakanineEffect()
{
if (Bot.HasInGraveyard(CardId.Whiptail) || Bot.HasInGraveyard(CardId.Thoroughblade))
{
AI.SelectCard(
CardId.Broadbull,
CardId.Tigermortar,
CardId.Chakanine,
CardId.Thoroughblade,
CardId.Ratpier,
CardId.Whiptail
);
AI.SelectNextCard(
CardId.Whiptail,
CardId.Thoroughblade
);
return true;
}
return false;
}
private bool TigermortarSummon()
{
if (Bot.HasInMonstersZone(CardId.Chakanine) && !TigermortarSpsummoned)
{
AI.SelectMaterials(CardId.Chakanine);
AI.SelectYesNo(true);
AI.SelectPosition(CardPosition.FaceUpDefence);
TigermortarSpsummoned = true;
return true;
}
if (Bot.HasInMonstersZone(CardId.Ratpier) && !TigermortarSpsummoned)
{
AI.SelectMaterials(CardId.Ratpier);
AI.SelectYesNo(true);
AI.SelectPosition(CardPosition.FaceUpDefence);
TigermortarSpsummoned = true;
return true;
}
if (Bot.HasInMonstersZone(CardId.Thoroughblade) && !TigermortarSpsummoned
&& Bot.HasInGraveyard(new[]
{
CardId.Whiptail,
CardId.Ratpier
}))
{
AI.SelectMaterials(CardId.Thoroughblade);
AI.SelectYesNo(true);
TigermortarSpsummoned = true;
return true;
}
if (Bot.HasInMonstersZone(CardId.Whiptail) && !TigermortarSpsummoned
&& Bot.HasInGraveyard(CardId.Ratpier))
{
AI.SelectMaterials(CardId.Whiptail);
AI.SelectYesNo(true);
TigermortarSpsummoned = true;
return true;
}
return false;
}
private bool TigermortarEffect()
{
//if (Card.HasXyzMaterial(CardId.Ratpier) || !Bot.HasInGraveyard(CardId.Ratpier))
// return false;
AI.SelectCard(CardId.Chakanine);
AI.SelectNextCard(CardId.Tigermortar);
AI.SelectThirdCard(CardId.Ratpier, CardId.Whiptail, CardId.Thoroughblade);
return true;
}
private bool BroadbullSummon()
{
if (Bot.HasInMonstersZone(CardId.Tigermortar) && !BroadbullSpsummoned)
{
AI.SelectMaterials(CardId.Tigermortar);
AI.SelectYesNo(true);
AI.SelectPosition(CardPosition.FaceUpDefence);
BroadbullSpsummoned = true;
return true;
}
if (Bot.HasInMonstersZone(CardId.Chakanine) && !BroadbullSpsummoned)
{
AI.SelectMaterials(CardId.Chakanine);
AI.SelectYesNo(true);
AI.SelectPosition(CardPosition.FaceUpDefence);
BroadbullSpsummoned = true;
return true;
}
if (Bot.HasInMonstersZone(CardId.Ratpier) && !BroadbullSpsummoned)
{
AI.SelectMaterials(CardId.Ratpier);
AI.SelectYesNo(true);
AI.SelectPosition(CardPosition.FaceUpDefence);
BroadbullSpsummoned = true;
return true;
}
if (Bot.HasInMonstersZone(CardId.Thoroughblade) && !BroadbullSpsummoned)
{
AI.SelectMaterials(CardId.Thoroughblade);
AI.SelectYesNo(true);
AI.SelectPosition(CardPosition.FaceUpDefence);
BroadbullSpsummoned = true;
return true;
}
return false;
}
private bool BroadbullEffect()
{
AI.SelectCard(
CardId.Tigermortar,
CardId.Chakanine,
CardId.Drident,
CardId.AleisterTheInvoker,
CardId.PhotonThrasher
);
if (Bot.HasInHand(CardId.Whiptail) && !Bot.HasInHand(CardId.Ratpier))
AI.SelectNextCard(CardId.Ratpier);
else
AI.SelectNextCard(CardId.Whiptail);
return true;
}
private bool BroadbullXYZSummon()
{
AI.SelectYesNo(false);
AI.SelectPosition(CardPosition.FaceUpDefence);
AI.SelectMaterials(new[]
{
CardId.Ratpier,
CardId.PhotonThrasher,
CardId.Whiptail,
CardId.AleisterTheInvoker
});
return true;
}
private bool DridentSummon()
{
AI.SelectMaterials(new[]
{
CardId.Broadbull,
CardId.Tigermortar,
CardId.Chakanine,
CardId.Thoroughblade
});
return true;
}
private bool RatpierMaterialEffect()
{
if (ActivateDescription == Util.GetStringId(CardId.Ratpier, 1))
{
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
return false;
}
private bool WhiptailEffect()
{
if (Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2)
return false;
if (DefaultCheckWhetherCardIsNegated(Card)) return false;
ClientCard target = null;
List<ClientCard> monsters = Bot.GetMonsters();
foreach (ClientCard monster in monsters)
{
if (monster.IsFaceup() && monster.IsCode(CardId.Drident) && !monster.HasXyzMaterial())
{
target = monster;
break;
}
}
/*if (target == null)
{
foreach (ClientCard monster in monsters)
{
if (monster.IsFaceup() && monster.Type == (int)CardType.Xyz && !monster.IsCode(CardId.DaigustoEmeral) && !monster.HasXyzMaterial())
{
target = monster;
break;
}
}
}*/
if (target == null)
{
AI.SelectCard(new[]
{
CardId.Drident
});
}
return true;
}
private bool RatpierEffect()
{
AI.SelectCard(
CardId.ZoodiacCombo,
CardId.Thoroughblade,
CardId.ZoodiacBarrage
);
return true;
}
private bool DridentEffect()
{
if (Duel.LastChainPlayer == 0)
return false;
ClientCard target = Util.GetBestEnemyCard(true);
if (target == null)
return false;
AI.SelectCard(
CardId.Broadbull,
CardId.Tigermortar,
CardId.Chakanine,
CardId.Thoroughblade,
CardId.Ratpier,
CardId.Whiptail
);
AI.SelectNextCard(target);
return true;
}
private bool DaigustoEmeralSummon()
{
AI.SelectMaterials(new[]
{
CardId.PhotonThrasher,
CardId.AleisterTheInvoker
});
return Bot.GetGraveyardMonsters().Count >= 3;
}
private bool DaigustoEmeralEffect()
{
AI.SelectCard(
CardId.Ratpier,
CardId.AleisterTheInvoker,
CardId.Whiptail
);
AI.SelectNextCard(
CardId.Ratpier,
CardId.DaigustoEmeral
);
return true;
}
private bool FireFormationTenkiEffect()
{
if (Bot.HasInHand(CardId.ZoodiacBarrage)
|| Bot.HasInSpellZone(CardId.ZoodiacBarrage)
|| Bot.HasInHand(CardId.Ratpier))
{
AI.SelectCard(CardId.Whiptail);
}
else
{
AI.SelectCard(CardId.Ratpier);
}
AI.SelectYesNo(true);
return true;
}
private bool ZoodiacBarrageEffect()
{
foreach (ClientCard spell in Bot.GetSpells())
{
if (spell.IsCode(CardId.ZoodiacBarrage) && !Card.Equals(spell))
return false;
}
AI.SelectCard(
CardId.FireFormationTenki,
CardId.MagicalMeltdown,
CardId.ZoodiacBarrage
);
AI.SelectNextCard(
CardId.Ratpier,
CardId.Whiptail,
CardId.Thoroughblade
);
AI.SelectPosition(CardPosition.FaceUpDefence);
return true;
}
private bool ZoodiacComboEffect()
{
if (Duel.CurrentChain.Count > 0)
return false;
if (Card.Location != CardLocation.Grave)
{
AI.SelectCard(CardId.Drident);
AI.SelectNextCard(
CardId.Whiptail,
CardId.Ratpier,
CardId.Thoroughblade
);
}
return true;
}
private bool MonsterRebornEffect()
{
AI.SelectCard(
CardId.Ratpier,
CardId.Whiptail,
CardId.InvokedMechaba,
CardId.JizukirutheStarDestroyingKaiju,
CardId.InvokedMagellanica,
CardId.Tigermortar,
CardId.Chakanine,
CardId.Broadbull
);
return true;
}
private bool MonsterRepos()
{
if (Card.IsCode(CardId.NumberS39UtopiatheLightning) && Card.IsAttack())
return false;
return base.DefaultMonsterRepos();
}
}
}
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Reflection;
namespace WindBot.Game.AI
{
public static class DecksManager
{
private class DeckInstance
{
public string Deck { get; private set; }
public Type Type { get; private set; }
public string Level { get; private set; }
public DeckInstance(string deck, Type type, string level)
{
Deck = deck;
Type = type;
Level = level;
}
}
private static Dictionary<string, DeckInstance> _decks;
private static List<DeckInstance> _list;
private static Random _rand;
public static void Init()
{
_decks = new Dictionary<string, DeckInstance>();
_rand = new Random();
Assembly asm = Assembly.GetExecutingAssembly();
Type[] types = asm.GetTypes();
foreach (Type type in types)
{
MemberInfo info = type;
object[] attributes = info.GetCustomAttributes(false);
foreach (object attribute in attributes)
{
if (attribute is DeckAttribute)
{
DeckAttribute deck = (DeckAttribute)attribute;
_decks.Add(deck.Name, new DeckInstance(deck.File, type, deck.Level));
}
}
}
_list = new List<DeckInstance>();
_list.AddRange(_decks.Values);
Logger.WriteLine("Decks initialized, " + _decks.Count + " found.");
}
public static Executor Instantiate(GameAI ai, Duel duel)
{
DeckInstance infos;
string deck = ai.Game.Deck;
if (deck != null && _decks.ContainsKey(deck))
infos = _decks[deck];
else
{
do
{
infos = _list[_rand.Next(_list.Count)];
}
while (infos.Level != "Normal");
}
Executor executor = (Executor)Activator.CreateInstance(infos.Type, ai, duel);
executor.Deck = infos.Deck;
return executor;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,34 @@
namespace WindBot.Game.AI.Enums
{
/// <summary>
/// Cards that are dangerous to attack.
/// </summary>
public enum DangerousMonster
{
LionHeart = 54366836,
Yubel = 78371393,
YubelIncarnate = 4779091,
YubelNightmare = 31764700,
ZaphionTheTimelord = 28929131,
SadionTheTimelord = 65314286,
MetaionTheTimelord = 74530899,
KamionTheTimelord = 91712985,
LazionTheTimelord = 92435533,
MichionTheTimelord = 7733560,
HailonTheTimelord = 34137269,
RaphionTheTimelord = 60222213,
GabrionTheTimelord = 6616912,
SandaionTheTimelord = 33015627,
EaterOfMillions = 63845230,
ElShaddollConstruct = 20366274,
ZushintheSleepingGiant = 67547370,
Heart_eartHDragon = 97403510,
DaigustoSphreeze = 29552709,
OhimetheManifestedMikanko = 81260679,
ArahimetheManifestedMikanko = 75771170,
YubelDasEwigLiebeWachter = 47172959,
UzuhimeTheManifestedMikanko = 57566760,
MaidenInLove = 8445808,
ArchfiendMatador = 7622360
}
}
@@ -0,0 +1,277 @@
namespace WindBot.Game.AI.Enums
{
/// <summary>
/// Cards that restrict player from performing some action. Bot will preferentially destroy them.
/// </summary>
public enum Floodgate
{
BarrierStatueoftheTorrent = 10963799,
BarrierStatueoftheDrought = 19740112,
BarrierStatueoftheHeavens = 46145256,
BarrierStatueoftheInferno = 47961808,
BarrierStatueoftheStormwinds = 73356503,
BarrierStatueoftheAbyss = 84478195,
ThunderKingRaiOh = 71564252,
FossilDynaPachycephalo = 42009836,
VanitysFiend = 47084486,
MajestysFiend = 33746252,
VanitysRuler = 72634965,
KycootheGhostDestroyer = 88240808,
ConsecratedLight = 2980764,
ArchlordKristya = 59509952,
KoakiMeiruDrago = 12435193,
DenkoSekka = 13974207,
ZapMustung = 29951323,
Jinzo = 77585513,
SpellCanceller = 84636823,
LevelLimitAreaB = 3136426,
DimensionalFissure = 81674782,
Necrovalley = 47355498,
SavageColosseum = 32391631,
SecretVillageoftheSpellcasters = 68462976,
SwordsofRevealingLight = 72302403,
MessengerofPeace = 44656491,
KaiserColosseum = 35059553,
DomainoftheTrueMonarchs = 84171830,
ZombieWorld = 4064256,
ImperialOrder = 61740673,
MacroCosmos = 30241314,
MindDrain = 68937720,
SoulDrain = 73599290,
SkillDrain = 82732705,
Eisbahn = 54059040,
GozenMatch = 53334471,
RivalryofWarlords = 90846359,
AntiSpellFragrance = 58921041,
LightImprisoningMirror = 53341729,
ShadowImprisoningMirror = 99735427,
WallofRevealingLight = 17078030,
GravityBind = 85742772,
VanitysEmptiness = 5851097,
Lose1Turn = 24348804,
Reqliate = 20426907,
SummonLimit = 23516703,
AndtheBandPlayedOn = 47594939,
StygianDirge = 81489939,
RoyalDecree = 51452091,
ImperialIronWall = 30459350,
DNASurgery = 74701381,
NaturiaExterio = 99916754,
TheLastWarriorfromAnotherPlanet = 86099788,
ThousandEyesRestrict = 63519819,
MaskedHERODarkLaw = 58481572,
NaturiaBeast = 33198837,
NaturiaBarkion = 2956282,
EvilswarmOphion = 91279700,
MermailAbyssgaios = 74371660,
AbyssDweller = 21044178,
ZoodiacDrident = 48905153,
InvokedMechaba = 75286621,
ElShaddollShekhinaga = 74822425,
ElShaddollConstruct = 20366274,
ElShaddollGrysra = 48424886,
ElShaddollWinda = 94977269,
HotRedDragonArchfiendAbyss = 9753964,
UltimateConductorTytanno = 18940556,
OvertexCoatls = 41782653,
FirePrison = 269510,
LairOfDarkness = 59160188,
SuperboltThunderDragon = 15291624,
ThunderDragonLord = 41685633,
CyberDragonInfinity = 10443957,
ImperialCustom = 9995766,
InspectorBoarder = 15397015,
Mashoudou = 76375976,
EternalSoul = 48680970,
MarincessBattleOcean = 91027843,
TopologicZeroboros = 66403530,
GladiatorBeastDomitianus = 33652635,
SerzielWatcheroftheEvilEye = 82466274,
ZerrzielRuleroftheEvilEyed = 17739335,
GorgonEmpressoftheEvilEyed = 29357687,
UnchainedSoulofRage = 67680512,
DracoBerserkeroftheTenyi = 5041348,
NidhoggGeneraiderBossofIce = 49275969,
UtgardaGeneraiderBossofDelusion = 744887,
FrodiGeneraiderBossofSwords = 40998517,
HoarrGeneraiderBossofRumbling = 68199168,
GodPhoenixGearfried = 22091647,
BrotherhoodoftheFireFistEland = 61472381,
PredaplantVerteAnaconda = 70369116,
RedSupernovaDragon = 99585850,
NumberF0UtopicFutureDragon = 26973555,
InvokedAugoeides = 97300502,
DragonmaidStrahl = 24799107,
RavenousCrocodragonArchethys = 87188910,
AdamancipatorRisenRaptite = 73079836,
AdamancipatorRisenDragite = 9464441,
TeardroptheRikkaQueen = 33779875,
CeruleanSkyFire = 54828837,
SacredBeastAwakening = 53701259,
GrandSpiritualArtIchirin = 38057522,
DualAvatarFeetArmoredUnGyo = 7631534,
VirtualWorldKyubiShenshen = 92519087,
VirtualWorldGateChuche = 13364097,
DragunityKnightAreadbhair = 88234821,
AiwasstheMagistusSpellSpirit = 35877582,
OneirostheDreamMirrorErlking = 35187185,
PlunderPatrollshipBrann = 94253655,
PlunderPatrollshipMoerk = 20248754,
PlunderPatrollshipLys = 18832779,
HollowGiants = 15462014,
GrozaTyrantofThunder = 45420955,
SpringansCaptainSargas = 29601381,
S_ForceOrrafist = 95974848,
AncientWarriors_RebelliousLuFeng = 82791472,
OneirostheDreamMirrorTormentor = 37678339,
SacredTreeBeastHyperyton = 9349094,
S_ForceJustify = 35334193,
UnderworldGoddessoftheClosedWorld = 98127546,
VampireVoivode = 4918855,
NekrozofAreadbhair = 39468724,
NekrozofUnicore = 89463537,
BenghalancertheResurgent = 73345237,
UrsarcticSeptentrion = 53087962,
TheIrisSwordsoul = 62849088,
AntihumanIntelligenceME_PSY_YA = 58844135,
MagikeyMechmortar_Garesglasser = 45877457,
ShootingMajesticStarDragon = 40939228,
StellarWindWolfrayet = 3322931,
ChronomalyVimana = 2609443,
CyberdarknessDragon = 18967507,
ClearWingSynchroDragon = 82044279,
CrystalClearWingSynchroDragon = 59765225,
BaronnedeFleur = 84815190,
Lyrilusc_EnsemblueRobin = 72971064,
Number4StealthKragen = 67557908,
Floowandereeze_Snowl = 53212882,
Floowandereeze_Empen = 80611581,
MasqueradetheBlazingDragon = 6855503,
DestinyHERO_DestroyerPhoenixEnforcer = 60461804,
SwordsoulGrandmaster_Chixiao = 69248256,
ZoroatheMagistusConflagrantCalamity = 95911373,
MasterflareHyperion = 63101468,
FallenSanctuary = 90312154,
MyutantBeast = 34695290,
MyutantArsenal = 7574904,
MyutantUltimus = 6182103,
Underdog = 5779502,
IcejadeKosmochlor = 3355732,
IllusionofChaos = 12266229,
SwordsoulSinisterSovereign_QixingLongyuan = 47710198,
DDDDeviserKingDeusMachinex = 46593546,
IcejadeErosion = 46593546,
NordicRelicSvalinn = 64797746,
OceanDragonLord_Kairyu_Shin = 23931679,
MarincessAquaArgonaut = 20934852,
MirrorjadetheIcebladeDragon = 44146295,
WitchcrafterVice_Madame = 9603252,
Therion_King_Regulus = 10604644,
StarvingVenomPredapowerFusionDragon = 39915560,
DinomorphiaRexterm = 92798873,
ExosistersMagnifica = 59242457,
IcejadeCurse = 83670388,
MamonakatheVaylantzUnited = 40680521,
LabrynthLabyrinth = 33407125,
RunickFountain = 92107604,
SprightRed = 75922381,
SprightCarrot = 2311090,
RikkaKonkon = 76869711,
PowerToolBraverDragon = 63265554,
MagikeyDeity_Ashtartu = 26988374,
RainbowOverdragon = 37440988,
TheBystialAlbaLos = 69120785,
KashtiraFenrir = 32909498,
MitsutheInsectNinja = 67282505,
VeratheVernusylphGoddess = 55125728,
TearlamentsRulkallos = 84330567,
Black_WingedAssaultDragon = 73218989,
BrandedBeast = 32756828,
GraphaDragonOverlordofDarkWorld = 39552584,
EpurrelyBeauty = 98049934,
ExpurrelyNoir = 83827392,
BeetrooperScaleBomber = 39041550,
EvigishkiNeremanas = 88926295,
ArktosXII_ChronochasmVaylantz = 50687050,
IcejadeGymirAegirine = 86682165,
KashtiraArise_Heart = 48626373,
LaevateinGeneraiderBossofShadows = 74615388,
SynchroZone = 60306277,
BystialDisPater = 27572350,
DespianLuluwalilith = 53971455,
FirewallDragonSingularity = 21637210,
BrandedEtude = 45675980,
EvolzarLars = 35103106,
AltergeistAdminia = 61470213,
EmperorCharlesTheGreat = 97864322,
YouReFinished = 88346805,
VolcanicEmperor = 46412900,
VolcanicInferno = 84138874,
RedZone = 50056656,
TGGlaiveBlaster = 95973569,
StellarNemesisTPHON_DoomsdayStar = 93039339,
SPLittleKnight = 29301450,
AngelRing = 40678060,
SkullGuardianProtectorOfTheVoicelessVoice = 10774240,
FloweringEtoileTheMelodiousMagnificat = 83793721,
EnlightenmentDragon = 46186135,
GoldPrideEradicator = 45464587,
VarudrasTheFinalBringerOfTheEndTimes = 70636044,
RagnaraikaStagSovereign = 42307760,
DrytronMeteonisAlphaDraconids = 56863746,
TheUnstoppableExodiaIncarnate = 83257450,
LightAndDarknessDragonLord = 19652159,
FiendsmithDiesIrae = 82135803,
MementomictlanTecuhtlicaCombinedConqueror = 14529511,
MadolcheQueenTiaraalaFraise = 49689480,
XYZHyperDragonCannon = 75748977,
ClearViciousKnight = 70095046,
Red_EyesBlackFullmetalDragon = 80870883,
MetalzoaX = 27268998,
AzaminaIliaSilvia = 46396218,
HeosvarogTheMechanicalDawn = 8963089,
LegendaryLordSixSamurai_ShiEn = 34235530,
NumberC32SharkDrakeLeVeiss = 7628844,
RyzealDetonator = 34909328,
MalissQHeartsCrypter = 21848500,
Blue_EyesUltimateSpiritDragon = 89604813,
TheiaThePrimalBeing = 85687952,
ArcanaForceEX_TheChaosRuler = 12686296,
SaintAzamina = 85065943,
CrystalClearWingOverSynchroDragon = 84343351,
JurracAstero = 52553102,
NekrozOfMetaltron = 13408726,
ZoroaTheMagistusVerethragna = 37260677,
DiabellstarVengeance = 23151193,
RegenesisWarrior = 96540807,
RegenesisSage = 22938501,
RegenesisDragon = 59323650,
Snake_EyesVengeanceDragon = 79415624,
LegendaryLordSixSamurai_Kizan = 42209438,
JuraishinTheCursedThunderGod = 78693036,
EclipseDragonRulerOfCatastrophes = 30350202,
AlliedCodeTalkerIgnister = 39138610,
EternalSunshine = 28903523,
RegenesisBirth = 27781371,
Ryu_GeEnd = 90664684,
SoulOfGaiaTheFierceKnight = 73129314,
K9_XWerewolf = 90303227,
ArtmageFinmel = 34541940,
LeoWizardTheDarkFiend = 55423549,
LunalightLigerDancer = 54701958,
ArtmageDiactorus = 27184601,
PsychicBlasterMk_II = 88139289,
NumberF0UtopicFutureZexal = 41522092,
VallonTheSuperPsySkyblaster = 40673853,
MasterPeaceTheTrueDracoverlord = 12800564,
MegalithNotrahPlura = 44293356,
AxonKickerOracle = 33171768,
DoomZXIIEnd_Drastrius = 95626382,
DDDSkyKingZeusRagnarok = 30998403,
DarkContractWithTheDifferentDimension = 54936778,
KillerTuneRedSeal = 15665977,
RBGa10Driller = 6043161,
RBGa10Cutter = 33438265,
RBLambdaBlade = 17188206
}
}
@@ -0,0 +1,112 @@
namespace WindBot.Game.AI.Enums
{
public enum FusionSpell
{
GemKnightFusion = 1264319,
TheEyeofTimaeus = 1784686,
InstantFusion = 1845204,
OverloadFusion = 3659803,
FrightfurFusion = 6077601,
RedEyesFusion = 6172122,
Ostinato = 9113513,
MagicalizeFusion = 11827244,
DarkCalling = 12071500,
VehicroidConnectionZone = 23299957,
Polymerization = 24094653,
MiracleSynchroFusion = 36484016,
PowerBond = 37630732,
ParticleFusion = 39261576,
ShaddollFusion = 44394295,
TheTerminusoftheBurningAbyss = 44771289,
MiracleFusion = 45906428,
OddEyesFusion = 48144509,
ParallelWorldFusion = 54283059,
AncientGearFusion = 64061284,
PendulumFusion = 65646587,
CynetFusion = 65801012,
AbsorbFusion = 71422989,
DragonsMirror = 71490127,
MetalfoesFusion = 73594093,
EidolonSummoningMagic = 74063034,
FusionSubstitute = 74335036,
TranscendentalPolymerization = 76647978,
CyberdarkImpact = 80033124,
DarkFusion = 94820406,
ThunderDragonFusion = 95238394,
TheBookoftheLaw = 458748,
ElShaddollFusion = 6417578,
FlashFusion = 17236839,
FullmetalfoesFusion = 39564736,
DestructionSwordsmanFusion = 41940225,
SuperPolymerization = 48130397,
CyberloadFusion = 55704856,
RelinquishedFusion = 78063197,
BrilliantFusion = 7394770,
ForbiddenDarkContractwiththeSwampKing = 10833828,
Fortissimo = 11493868,
VoidImagination = 31444249,
FrightfurFactory = 43698897,
DarkContractwiththeSwampKing = 73360025,
NepheShaddollFusion = 60226558,
FusionGate = 33550694,
DFusion = 26841274,
FusionDestiny = 52947044,
PyroxeneFusion = 55824220,
FragmentFusion = 72029628,
NecroFusion = 81223446,
PredaplantVerteAnaconda = 70369116,
DreamMirrorofChaos = 98570539,
PlunderPatrollShipshapeShipsShipping = 44227727,
FireFormationIngen = 29143457,
ParametalfoesFusion = 58549532,
ReadyFusion = 63854005,
BrandedinWhite = 34995106,
BrandedinRed = 82738008,
FaceCardFusion = 29062925,
MyutantFusion = 42577802,
MyutantCry = 31855260,
FallenOfAlbaz = 68468459,
GreaterPolymerization = 7614732,
UltimateFusion = 71143015,
BrandedFusion = 44362883,
GhostFusion = 35705817,
WitchcrafterConfusionConfession = 35098357,
BrandedBanishment = 6763530,
DinomorphiaDomain = 26631975,
DinomorphiaFrenzy = 78420796,
SouloftheSupremeKing = 92428405,
InstantContact = 16169772,
ScatterFusion = 40597694,
FavoriteContact = 75047173,
AmazonessSecretArts = 86758746,
DarkWorldAccession = 65956182,
BeetrooperLanding = 13234975,
FusionReproduction = 43331750,
ChimeraFusion = 63136489,
HarmonicSynchroFusion = 7473735,
SouloftheSupremeCelestialKing = 76840111,
MelodiousConcerto = 31458630,
MementotlanFusion = 66518509,
TheHallowedAzamina = 94845588,
AzaminaDebtors = 20934683,
AzaminaDetermination = 42201897,
HeavyPolymerization = 58570206,
DoubleFusion = 10218411,
DarkContact = 77124096,
GemKnightMasterDiamondDispersion = 25342956,
GemKnightDispersion = 24220368,
DracotailFaimena = 1498449,
DracotailMululu = 7375867,
KetuDracotail = 6153210,
RahuDracotail = 32548318,
ArtmagePowerPatron = 23829452,
ArtmageMasterworkSuccession = 37517035,
TeleportFusion = 36494597,
PrimiteFusion = 99161253,
TheGazeOfTimaeus = 22283204,
MutinyInTheSky = 71593652,
HuntingHorn = 55421040
}
}
@@ -0,0 +1,145 @@
namespace WindBot.Game.AI.Enums
{
/// <summary>
/// Cards that are invincible to battle and should always attack to use effect.
/// </summary>
public enum InvincibleBotMonster
{
YubelTheUltimateNightmare = 31764700,
YubelTerrorIncarnate = 4779091,
SandaionTheTimelord = 33015627,
GabrionTheTimelord = 6616912,
MichionTheTimelord = 7733560,
ZaphionTheTimelord = 28929131,
HailonTheTimelord = 34137269,
RaphionTheTimelord = 60222213,
SadionTheTimelord = 65314286,
MetaionTheTimelord = 74530899,
KamionTheTimelord = 91712985,
LazionTheTimelord = 92435533,
TimelordProgenitorVorpgate = 67508932,
RocketWarrior = 30860696,
GoDDDDivineZeroKingRage = 40227329,
BloomDivaTheMelodiousChoir = 84988419,
BlackwingArmorMaster = 69031175,
DaigustoSphreez = 29552709,
Number92HearteartHDragon = 97403510,
NumberC96DarkStorm = 77205367,
Number54LionHeart = 54366836,
Number2NinjaShadowMosquito = 32453837,
OhimetheManifestedMikanko = 81260679,
NightmareMagician = 40221691,
ArahimetheManifestedMikanko = 75771170,
UzuhimeTheManifestedMikanko = 57566760,
ArchfiendMatador = 7622360
}
/// <summary>
/// Cards that are invincible to battle.
/// </summary>
public enum InvincibleEnemyMonster
{
SpiritReaper = 23205979,
YubelTheUltimateNightmare = 31764700,
YubelTerrorIncarnate = 4779091,
SandaionTheTimelord = 33015627,
DarknessNeosphere = 60417395,
GabrionTheTimelord = 6616912,
MichionTheTimelord = 7733560,
ZaphionTheTimelord = 28929131,
HailonTheTimelord = 34137269,
RaphionTheTimelord = 60222213,
SadionTheTimelord = 65314286,
MetaionTheTimelord = 74530899,
Yubel = 78371393,
KamionTheTimelord = 91712985,
LazionTheTimelord = 92435533,
CloudianEyeofTheTyphoon = 57610714,
GimmickPuppetShadowFeeler = 34620088,
TheLegendaryFishermanIII = 44968687,
CastleGate = 36931229,
CloudianNimbusman = 20003527,
ExodiaNecross = 12600382,
Gellenduo = 11662742,
CloudianAltus = 79703905,
CloudianStormDragon = 13474291,
CloudianCirrostratus = 43318266,
CloudianTurbulence = 16197610,
CloudianAcidCloud = 17810268,
SuperheavySamuraiBlueBrawler = 41628550,
DinoSewing = 27143874,
Marshmallon = 31305911,
ShibaWarriorTaro = 27416701,
XSaberPashuul = 23093604,
SuperheavySamuraiBlowtorch = 7864030,
VijamTheCubicSeed = 15610297,
ArcanaForce0TheFool = 62892347,
ReptilianneNaga = 79491903,
AbyssStungray = 97232518,
ArmityleTheChaosPhantom = 43378048,
BlueEyesTwinBurstDragon = 2129638,
GladiatorBeastNerokius = 29357956,
MaskedHERODivineWind = 22093873,
ElementalHEROShiningPhoenixEnforcer = 88820235,
LunalightCatDancer = 51777272,
ElementalHEROPhoenixEnforcer = 41436536,
BloomDivaTheMelodiousChoir = 84988419,
ReaperonTheNightmare = 85684223,
BeelzeusofTheDiabolicDragons = 8763963,
DragocytosCorruptedNethersoulDragon = 21435914,
BeelzeofTheDiabolicDragons = 34408491,
BlackwingArmorMaster = 69031175,
DaigustoSphreeze = 29552709,
DarkDiviner = 31919988,
NumberC92HearteartHChaosDragon = 47017574,
Number92HearteartHDragon = 97403510,
Number51FinisherTheStrongArm = 56292140,
NumberC96DarkStorm = 77205367,
NumberF0UtopicFutureFutureSlash = 43490025,
NumberF0UtopicFuture = 65305468,
GoukiTheGiantOgre = 47946130,
BorrelswordDragon = 85289965,
NumberF0UtopicFutureDragon = 26973555,
BorrelendDragon = 98630720,
MimickingMan_EaterBug = 72427512,
ShiningPiecephilia = 49776811,
BrigrandtheGloryDragon = 34848821,
AmazonessQueen = 15951532,
Number2NinjaShadowMosquito = 32453837,
OhimetheManifestedMikanko = 81260679,
CornfieldCoatl = 92565383,
MirrorSwordknight = 28954097,
NightmareMagician = 40221691,
ArahimetheManifestedMikanko = 75771170,
UFOLight = 9275482,
TaotheGreatChanter = 34541543,
SpiritOfYubel = 90829280,
DarkGuardian = 26746975,
EnvoyOfTheWaxState = 87462901,
Fluffyfluff = 85401123,
YubelDasEwigLiebeWachter = 47172959,
TenpaiDragonFadra = 65326118,
GolgoilTheSteelSeismicSmasher = 59369430,
TalonsOfShurilane = 74150658,
NightmareApprentice = 58143852,
MillenniumoonMaiden = 37552929,
MillenniumFiendReflection = 63947968,
HereticalPhoboscobos = 76078185,
TopHatHareTheSilhouetteMagician = 1528054,
Silhouhatte = 24440742,
TheDukeofDemise = 45445571,
EvilHERONeosLord = 13708888,
GladiatorBeastDareios = 72246674,
Number69HeraldryCrest_DarkMatterDemolition = 77571454,
FirstOfTheDragonlords = 53466722,
UzuhimeTheManifestedMikanko = 57566760,
HecahandsIbel = 95365081,
HecahandsYadel = 32759190,
HecahandsGoddus = 68144894,
HecahandsGygas = 95132593,
HecahandsBreus = 21637502,
HecahandsJawza = 67021206,
HecahandsXeno = 94410955,
MaidenInLove = 8445808,
ArchfiendMatador = 7622360
}
}
@@ -0,0 +1,33 @@
namespace WindBot.Game.AI.Enums
{
public enum NotBeSynchroMaterialMonster
{
Ronintoadin = 1357146,
GagagaCaesar = 9583383,
VagueShadowToken = 9929399,
TourGuideFromtheUnderworld = 10802915,
PhotonToken = 17418745,
KagemuchaKnight = 19353570,
SharkStickers = 20838380,
GagagaMagician = 26082117,
RadianToken = 28674153,
Kurivolt = 40817915,
BlueMountainButterspy = 54582424,
Lightserpent = 55501446,
SaberShark = 63193879,
ConstellarKaus = 70908596,
CeremonialToken = 82340057,
HeroicChallenger_DoubleLance = 89774530,
SteelswarmScout = 90727556,
Kagetokage = 94656263,
YellowDuston = 16366810,
BlueDuston = 40217358,
Centerfrog = 47346782,
GreenDuston = 52182715,
RedDuston = 61019812,
EaterofMillions = 63845230,
PutridPuddingBodyBuddies = 85101097,
Click_Echo = 2992467
}
}
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more