commit 6dbc9e78d8d1de816932de606c8f5499da004e01 Author: Angel Mankel Date: Mon Oct 19 18:08:01 2026 -0700 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 diff --git a/src/BotArena/BotArena.csproj b/src/BotArena/BotArena.csproj new file mode 100644 index 0000000..5d430e8 --- /dev/null +++ b/src/BotArena/BotArena.csproj @@ -0,0 +1,101 @@ + + + + + Exe + net8.0 + win-x64 + false + BotArena + YGOLegacy.Tools.BotArena + YGOLegacy.Tools.BotArena.Program + + disable + disable + latest + true + true + + $(DefineConstants);YGOL_STANDALONE + + $(NoWarn);CS0108;CS0114;CS0162;CS0164;CS0168;CS0169;CS0219;CS0414;CS0618;CS0649;CS0659;CS0661;CS1522;CS1570;CS1572;CS1573;CS1587;CS1591;CS8981;SYSLIB0011;CA1416 + false + en + + + + + + + + + + + + ..\..\Assets\Plugins\Managed\YGOLegacy.Engine.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/BotArena/LocalHost.cs b/src/BotArena/LocalHost.cs new file mode 100644 index 0000000..27738f7 --- /dev/null +++ b/src/BotArena/LocalHost.cs @@ -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 +{ + /// + /// TICKET-045: everything 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 + /// NamedCardsManager is already loaded with exactly the cdbs the game + /// feeds it (Setup.InitWindBot: the locale cards.cdb, every .cdb + /// inside Expansions/*.ypk, then Expansions/*.cdb, later files + /// winning), read-only through the Mono.Data.Sqlite shim, and + /// YGOSharp.OCGWrapper.Card.Data is that row already shaped like + /// ocgcore's card_data. 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 + /// Expansions/script/, then the script/ entries of every + /// Expansions/*.ypk|*.zip, then Data/script.zip, then a loose + /// script/ under the root. That is what keeps the loose + /// Expansions/script/procedure.lua override in charge. + /// + internal static class LocalHost + { + private static bool installed; + private static readonly Dictionary scriptCache = new(StringComparer.OrdinalIgnoreCase); + private static readonly List archives = new(); + private static readonly List> archiveIndex = new(); + private static string root; + + /// + /// Point the runtime at ygol-engine.dll and install the process-global card + /// and script readers. Idempotent; call once per worker. + /// + 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(); + 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(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 + ")"); + } + } + } + + /// + /// The core asks for names like ./script/c12345.lua (and, once per + /// duel, constant/utility/procedure). Null = "no such script", which the + /// core treats as an empty file. + /// + 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; } + } + } +} diff --git a/src/BotArena/Program.cs b/src/BotArena/Program.cs new file mode 100644 index 0000000..96df01c --- /dev/null +++ b/src/BotArena/Program.cs @@ -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 +{ + /// + /// 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. + /// + 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(); + 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--.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; + } + + /// + /// 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. + /// + private static void RunDuels(Options opts, StandaloneArenaResult result, List workers) + { + var pending = new Queue(); + 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(); + var retried = new HashSet(); + 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 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(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 game/repo root (Deck/, Data/, Expansions/ live here). Default: cwd + --execA WindBot Deck= override for seat A (Smart, Lucky, ...). Default: the deck's own + --execB same for seat B + --n duels to play. Default 10 + --parallel worker processes (one server + two bots each). Default 1 + --seed base of the per-duel SmartExecutor noise seed (0 = brains seed themselves) + --timeout per-duel timeout. Default 300 + --out extra copy of the JSON report (canonical copy: Data/BotArena/) + --replays save every duel's .yrp there + --journal SmartExecutor decision journal: /duel--.jsonl per Smart seat + run.json + (feed the dir to .claude/skills/bot-brain/blunders.py) + --port first server port (workers take base, base+4, ...). Default 7920 + --locale Data/locales// for cards.cdb + bot.conf. Default en-US + --verbose keep [YGOL bot] decision logging (goes to Data/BotArena/logs/run--/worker-N.log) + --insightA duel state bus insight for seat A: none | hand | full (TICKET-042). + Overrides that deck brain's `insight` knob. Default: the knob (none) + --insightB same for seat B + --host local|server in-process core (default) or the engine's server over TCP (TICKET-045) + --knobsA 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 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 knobsA, knobsB; + + /// TICKET-050: does this seat's override switch lookahead on? + public bool LookaheadOn(Dictionary knobs) + => knobs != null && knobs.TryGetValue("lookahead", out var v) && v > 0f && hostMode == "local"; + + /// "a=1,b=2" -> a dictionary; empty/null -> null. + public static Dictionary ParseKnobs(string flag, string value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + var map = new Dictionary(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; + } + + /// Round-trip form for the worker command line. + public static string FormatKnobs(Dictionary knobs) + { + if (knobs == null || knobs.Count == 0) return string.Empty; + var parts = new List(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; + } + } +} diff --git a/src/BotArena/README.md b/src/BotArena/README.md new file mode 100644 index 0000000..1456fa2 --- /dev/null +++ b/src/BotArena/README.md @@ -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 ` (`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 `. 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//` 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 ` | 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--/worker-N.log` (one folder per run, so concurrent runs are safe; `-rK` suffix for a respawned worker). + +### Report + +`Data/BotArena/--vs-.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//bot.conf → BotRoster.ForDeck + │ → seat names " A"/" 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(" -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. diff --git a/src/BotArena/ReplayOracle.cs b/src/BotArena/ReplayOracle.cs new file mode 100644 index 0000000..c948337 --- /dev/null +++ b/src/BotArena/ReplayOracle.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using YGOLegacy.Bot; + +namespace YGOLegacy.Tools.BotArena +{ + /// + /// 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 create_duel AND its own + /// deck shuffle from one number (ArenaReport.CoreSeedFor), so a + /// fresh host with the same seed and the same two deck lists deals the + /// identical game; + /// * 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); + /// * 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: + /// SmartExecutor.Oracle 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 + /// ); WindBot.Program.Rand 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. + /// + internal sealed class ReplayOracle : ILookaheadOracle + { + /// + /// Builds one rollout seat. The worker owns the WindBot statics, so it + /// supplies this rather than the oracle reaching for them. + /// + internal delegate ILoopbackSeat SeatFactory(string username, int seatIndex); + + /// Seat index (0 = A) this oracle answers for. + private readonly int mySeat; + private readonly Action log; + + private LocalDuelHost host; + private SeatFactory makeSeat; + private IList mainA, extraA, mainB, extraB; + private int coreSeed; + private Random rolloutRng; + private int rolloutCounter; + + public string LastNote { get; private set; } + + /// Run totals, for the worker log. + public int Rollouts { get; private set; } + public int Abandoned { get; private set; } + public long RolloutMs { get; private set; } + + internal ReplayOracle(int seat, Action log) + { + mySeat = seat; + this.log = log; + } + + /// + /// 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. + /// + internal void Attach(LocalDuelHost liveHost, SeatFactory factory, + IList mainA, IList extraA, + IList mainB, IList 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(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; + } + + /// One playout. 0..1, or NaN when it could not be played. + private float PlayOne(IList 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; + } + } + + /// + /// 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. + /// + 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"); + } + } +} diff --git a/src/BotArena/Setup.cs b/src/BotArena/Setup.cs new file mode 100644 index 0000000..577e7c0 --- /dev/null +++ b/src/BotArena/Setup.cs @@ -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 +{ + /// + /// 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. + /// + 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); + } + } + + /// + /// Worker: the card databases, in the order the game feeds WindBot + /// (Program.InitDatas): Data/locales//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. + /// + 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 ExtractZipCdbs(string expansions) + { + var result = new List(); + if (!Directory.Exists(expansions)) return result; + var cacheRoot = Path.Combine(Path.GetTempPath(), "YGOLBotArena", "cdb"); + var archives = new List(); + 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; + } + } +} diff --git a/src/BotArena/Shims/MDPro3.cs b/src/BotArena/Shims/MDPro3.cs new file mode 100644 index 0000000..4489ca4 --- /dev/null +++ b/src/BotArena/Shims/MDPro3.cs @@ -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 ZipCdbPaths = new(); + public static List GetAllCdbInZipPaths() => ZipCdbPaths; + } +} + +namespace MDPro3.Utility +{ + /// The active locale: picks Data/locales//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//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 bots = new(); + } +} diff --git a/src/BotArena/Shims/MonoDataSqlite.cs b/src/BotArena/Shims/MonoDataSqlite.cs new file mode 100644 index 0000000..86d21c8 --- /dev/null +++ b/src/BotArena/Shims/MonoDataSqlite.cs @@ -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) { } + } +} diff --git a/src/BotArena/Shims/UnityEngine.Debug.cs b/src/BotArena/Shims/UnityEngine.Debug.cs new file mode 100644 index 0000000..e425faf --- /dev/null +++ b/src/BotArena/Shims/UnityEngine.Debug.cs @@ -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 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"; + } +} diff --git a/src/BotArena/Worker.cs b/src/BotArena/Worker.cs new file mode 100644 index 0000000..df5cb59 --- /dev/null +++ b/src/BotArena/Worker.cs @@ -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 +{ + /// + /// 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. + /// + 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 verdicts = new(StringComparer.Ordinal); + private static readonly ConcurrentDictionary 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); + + /// + /// 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. + /// + 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)(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; + } + + /// + /// 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. + /// + 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 Ids(IList cards) + { + var ids = new List(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; + } + + /// `/duel--.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 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); + + /// + /// 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. + /// + 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; + } + + /// + /// 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. + /// + 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(); + 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(); + } + } + } +} diff --git a/src/BotArena/YgoServer.cs b/src/BotArena/YgoServer.cs new file mode 100644 index 0000000..165df3b --- /dev/null +++ b/src/BotArena/YgoServer.cs @@ -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 +{ + /// + /// The game's server is not an exe: it is ygol-engine.dll + /// (Assets/Plugins/Windows/), driven exactly as MDPro3.Net.YgoServer drives + /// it — start_server(args) blocks on a thread until the duel ends + /// (the server-mode build stops itself after DuelEnd) or stop_server() + /// is called. It reads ./expansions (Expansions/ on the Windows FS), + /// ./script and writes ./replay/error.log 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. + /// + 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"); + } + + /// + /// 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). + /// + 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; } + } + + /// + /// 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. + /// + 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; + } + } +} diff --git a/src/YGOLegacy.Bots/Bot/ArenaReport.cs b/src/YGOLegacy.Bots/Bot/ArenaReport.cs new file mode 100644 index 0000000..174f2ab --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/ArenaReport.cs @@ -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. + // ------------------------------------------------------------------------ + + /// + /// 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. + /// + [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--.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; + } + + /// + /// The live tally of a run. The same instance is reported through + /// IProgress after every duel and returned at the end (`done` = true). + /// + [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 duels = new(); + + public int Played => winsA + winsB + draws; + } + + /// + /// Pure helpers shared by both arenas: seat naming/commands, verdict + /// resolution, tallying, the one-line summary and report file naming. + /// + 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" / "... 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); + + /// + /// The seed for everything in duel that is + /// NOT a brain: the in-process host's deck shuffle, ocgcore's own + /// create_duel(seed) and WindBot's process-global + /// Program.Rand (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 (= --seed 0) means "seed yourself": nothing is + /// pinned and the run is not repeatable, as before. + /// The odd multiplier keeps this stream clear of + /// 's (seed*1000 + duel*2 + seat). + /// + 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, + }; + + /// + /// 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. + /// + 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/--vs-.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); + } + } +} diff --git a/src/YGOLegacy.Bots/Bot/BattlePredictor.cs b/src/YGOLegacy.Bots/Bot/BattlePredictor.cs new file mode 100644 index 0000000..300658f --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/BattlePredictor.cs @@ -0,0 +1,116 @@ +using System; +using WindBot.Game; + +namespace YGOLegacy.Bot +{ + /// + /// What one declared attack does, predicted from ATK/DEF/position alone + /// (no effects, no piercing). Face-down defenders are guessed at + /// = true. + /// + 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; + } + } + + /// + /// 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. + /// + public static class BattlePredictor + { + /// DefaultExecutor.OnPreBattleBetween or null; sets + /// RealPower on both cards and returns false when the attack must not happen. + /// Guessed DEF of a face-down defender. + public static BattleOutcome Predict(ClientCard attacker, ClientCard defender, + Func 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; + } + } +} diff --git a/src/YGOLegacy.Bots/Bot/BoardEvaluator.cs b/src/YGOLegacy.Bots/Bot/BoardEvaluator.cs new file mode 100644 index 0000000..63b9917 --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/BoardEvaluator.cs @@ -0,0 +1,382 @@ +using System; +using System.Collections.Generic; +using WindBot.Game; +using WindBot.Game.AI; +using YGOSharp.OCGWrapper.Enums; + +namespace YGOLegacy.Bot +{ + /// + /// 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. is only an identity handle for the + /// predictor (which monster did what) — the score never reads it. + /// + 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; + } + } + + /// + /// 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. + /// + public class BoardView + { + public int BotLp; + public int EnemyLp; + public List Bot = new(); + public List 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(Bot); + copy.Enemy = new List(Enemy); + return copy; + } + + public int IndexOfBot(ClientCard card) => IndexOf(Bot, card); + public int IndexOfEnemy(ClientCard card) => IndexOf(Enemy, card); + + private static int IndexOf(List list, ClientCard card) + { + for (int i = 0; i < list.Count; i++) + if (ReferenceEquals(list[i].Card, card)) + return i; + return -1; + } + } + + /// + /// 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. + /// + 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 (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 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 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; + } + + /// + /// Life Points OUR board could take off the enemy if every monster we + /// control attacked right now. The mirror of + /// , 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 + /// (). + /// + public static int SwingDamage(ClientField bot, ClientField enemy, int unknownPower = DefaultUnknownPower) + { + var attackers = new List(); + foreach (var m in bot.GetMonsters()) + if (m != null && m.IsFaceup() && m.IsAttack()) + attackers.Add(Math.Max(0, m.Attack)); + var blockers = new List(); + 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); + } + + /// The same sum on a predicted board. + public static int SwingDamage(BoardView view) + { + var attackers = new List(); + foreach (var m in view.Bot) + if (m.FaceUp && m.AttackPos) attackers.Add(Math.Max(0, m.Atk)); + var blockers = new List(); + 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 attackers, List 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; + } +} diff --git a/src/YGOLegacy.Bots/Bot/BrainRules.cs b/src/YGOLegacy.Bots/Bot/BrainRules.cs new file mode 100644 index 0000000..68f95d7 --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/BrainRules.cs @@ -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; + + /// + /// The per-character rule layer of SmartExecutor, loaded from + /// Data/Characters/<id>/brain.json (schema: README, "SmartExecutor + /// brain.json"; documented example: Data/Characters/_template/brain.json). + /// Everything here is optional — a missing or empty file yields + /// 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. + /// + 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 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 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 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 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 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 + /// (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 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 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. 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; + + /// + /// Read <directory>/<fileName> (default + /// brain.json). A per-deck file name that does not exist falls + /// back to brain.json. 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. + /// + 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(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(); + never ??= new List(); + combos ??= new List(); + combos.RemoveAll(c => c == null); + foreach (var combo in combos) + combo.Normalize(); + positions ??= new Dictionary(); + responses ??= new Responses(); + responses.Normalize(); + battle ??= new BattleRules(); + battle.Normalize(); + effects ??= new Dictionary(); + keep ??= new List(); + keep.RemoveAll(id => id == 0); + warnings ??= new List(); + var dropped = new List(); + 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. = the + /// cheapest legal source: hand first, then the field. + public enum EffectFrom { Any, Hand, Field, Grave } + + /// + /// What one card's effect does to the board, declared in brain.json + /// (effects block; README "SmartExecutor brain.json", template + /// Data/Characters/_template/brain.json) and generated by + /// /bot-brain from the card text. Read by . + /// Every field is optional; the raw JSON strings stay for logging and + /// the parsed enums live in the PascalCase properties. + /// + 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 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; + /// levelChange only: the Level the affected monsters BECOME + /// ("its Level becomes 6"). Unset + 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 + /// 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; + /// summon / fusion: how many cards of ours the summon + /// SPENDS (Fusion Materials, tributes a `cost` does not already cover). + /// 0 = unset; a fusion with no value pays for 2, the usual + /// Polymerization cost. Where they come from is . + public int materials; + /// any (default: hand first, then the field) | hand | field | grave. + /// Only grave 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 + /// : 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 + /// — 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 + /// kind: "gain", scope: "enemy" 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). + /// + /// 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; count defaults to 1. + /// + 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 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 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(); + 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 } + + /// + /// 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). + /// + 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 (all three in + /// hand at once) nor (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 + /// ). + /// 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 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 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 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 yesNo = new(); + /// Option prompts: card id -> zero-based index to pick for that card. + public Dictionary options = new(); + /// Option prompts: effect descriptions to prefer whenever offered. + public List preferOptions = new(); + + [JsonIgnore] + public bool IsEmpty => chain.Count == 0 && yesNo.Count == 0 && options.Count == 0 && preferOptions.Count == 0; + + public void Normalize() + { + chain ??= new Dictionary(); + yesNo ??= new Dictionary(); + options ??= new Dictionary(); + preferOptions ??= new List(); + } + + 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 attackInto = new(); + /// The mirror of : 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 + /// and over . + /// For a punish that is the card's own quick effect, prefer + /// effects.<id>.onAttacked — same veto, one place. + public List avoidAttackInto = new(); + /// Bot monsters that must never declare an attack (Exodia bait, walls). + public List neverAttackWith = new(); + /// Bot monsters that attack whenever they legally can (battle-trigger effects). + public List 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(); + avoidAttackInto ??= new List(); + neverAttackWith ??= new List(); + alwaysAttackWith ??= new List(); + } + } +} diff --git a/src/YGOLegacy.Bots/Bot/DuelStateBus.cs b/src/YGOLegacy.Bots/Bot/DuelStateBus.cs new file mode 100644 index 0000000..18d314e --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/DuelStateBus.cs @@ -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; + + /// + /// How much of the enemy's private state a brain may read (TICKET-042). + /// Per-deck knob knobs.insight (0/1/2), default . + /// + 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, + } + + /// Which client a tapped stream belongs to. + public enum SeatRole + { + Player = 0, + Observer = 1, + } + + /// + /// Duel state bus (TICKET-042). Both duel clients of a local duel run in + /// ONE process — the human's TcpHelper pump in the game, WindBot's + /// GameClient on its own thread, and in the standalone arena both + /// bots. Two additive [YGOL] receive-side taps publish + /// (seatKey, packetBytes) here; the bus feeds each stream into a + /// PASSIVE MIRROR — a private / + /// pair driven by WindBot's own packet parser ( + /// in its [YGOL] 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 + /// Tools/BotArena as well as the game. + /// + /// Cost when nobody listens: is false, so both taps + /// are one static bool read per packet and allocate nothing. The bus only + /// wakes up when a asks for an insight level + /// above . + /// + /// 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 + /// . 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 + /// Insight.Available stays false so the brain behaves as today. + /// + public static class DuelStateBus + { + /// Seat key of the game's own (human) client; the role is appended + /// (human:p0, human:p1, human:obs) so a spectator + /// is never mistaken for a duelist. + public const string HumanSeatPrefix = "human"; + + private const string LogPrefix = "[YGOL bus] "; + + /// + /// False (the default) = the taps do nothing at all. Set the moment a + /// brain asks for insight; cleared by . Read on + /// every received packet, so it is a plain volatile field. + /// + public static volatile bool Active; + + private static readonly object gate = new object(); + private static readonly Dictionary streams = new Dictionary(StringComparer.Ordinal); + private static readonly Dictionary deckPaths = new Dictionary(StringComparer.Ordinal); + private static readonly Dictionary overrides = new Dictionary(StringComparer.Ordinal); + + // ================================================================== + // Session + // ================================================================== + + /// + /// 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 . + /// + public static void Reset() + { + lock (gate) + { + streams.Clear(); + deckPaths.Clear(); + Active = false; + } + } + + /// + /// Force a seat's insight level regardless of its brain knob (the + /// arena's --insightA/--insightB). Null removes the override. + /// The key is the seat's WindBot Name= (its Username). + /// + 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; + } + + /// + /// Tell the bus which deck a seat is playing, so + /// and + /// work. The path is a + /// Deck/ path without .ydk — exactly WindBot's + /// DeckFile= — 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. + /// + 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) + // ================================================================== + + /// + /// The game's own client received a packet ([YGOL] seam in + /// TcpHelper.PerFrameFunction). is + /// RoomServant.SelfType: 0/1 are the duelists, anything else + /// (7) is a spectator. + /// + 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); + } + + /// + /// A WindBot client received a packet ([YGOL] seam in + /// GameClient.OnPacketReceived). The client itself is passed so + /// the mirror can be built with that seat's identity (name, deck) + /// without a second registration call. + /// + 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); + } + + /// + /// Generic tap: publish a raw STOC packet for a seat key. Kept public + /// for callers that have neither a GameClient nor the human pump. + /// + 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 + // ================================================================== + + /// + /// The insight a seat gets on its opponent. is + /// what the seat's brain resolved (override, else knob). A level above + /// ACTIVATES the taps — that is the only + /// thing that ever does. Never returns null; a bus with no opposing + /// stream simply reports Available == false. + /// + public static Insight InsightFor(string seatKey, InsightLevel level) + { + if (level != InsightLevel.None) Active = true; + return new Insight(seatKey, level); + } + + /// + /// The opposing stream of : the one other + /// player stream in the session (observers never count). Null while + /// nobody else has spoken, or when the seating is ambiguous. + /// + 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 + // ================================================================== + + /// + /// One client's packet stream and the mirror it drives. All mirror + /// mutation and every read of it happen under , so a + /// brain on another thread never sees a half-applied message. + /// + 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 handAtTurnStart = new List(); + + 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(); + 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(); + 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(handAtTurnStart); + var drawn = new List(); + 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 Seen() + { + lock (sync) + { + var field = Own; + var seen = new List(); + 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 Ids(IEnumerable cards) + { + var list = new List(); + if (cards == null) return list; + foreach (var card in cards) + if (card != null && card.Id != 0) list.Add(card.Id); + return list; + } + } + + /// + /// The mirror's executor. A forwards a + /// handful of state messages to GameAI, which forwards them to + /// its executor — so a mirror needs one, and it must do nothing at all. + /// (WindBot's own DefaultExecutor has a protected constructor + /// and would register card handlers we never want to run.) + /// + internal sealed class MirrorExecutor : Executor + { + internal MirrorExecutor(GameAI ai, Duel duel) : base(ai, duel) { } + } + } + + /// + /// What one seat may read about its opponent (TICKET-042). Obtained by + /// 's constructor via + /// ; every property is a live read of + /// the opponent's mirror, so it always answers for "right now". + /// + /// Gating: at nothing is available at all. + /// adds the hand, the draws of this turn, + /// the decklist and the public grave/banish lists. + /// 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. + /// + 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(); + + /// Ids the enemy drew (or otherwise added to hand) this turn. + public int[] DrawnThisTurn => AtLeast(InsightLevel.Hand)?.DrawnThisTurn() ?? Array.Empty(); + + /// Ids in the enemy graveyard (public information; needs insight on). + public int[] SeenInGrave => AtLeast(InsightLevel.Hand)?.Grave() ?? Array.Empty(); + + /// Ids the enemy has banished. + public int[] SeenBanished => AtLeast(InsightLevel.Hand)?.Banished() ?? Array.Empty(); + + /// The enemy's face-down spells/traps, as ids. Full insight only. + public int[] SetBackrow => AtLeast(InsightLevel.Full)?.SetBackrow() ?? Array.Empty(); + + /// The enemy's face-down monsters, as ids. Full insight only. + public int[] SetMonsters => AtLeast(InsightLevel.Full)?.SetMonsters() ?? Array.Empty(); + + /// + /// 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. + /// + public int[] Decklist + { + get + { + if (Level == InsightLevel.None) return Array.Empty(); + 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(); + 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(); + } + return decklist; + } + } + + /// + /// How many copies of 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. + /// + 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; + } + + /// Parse "none" | "hand" | "full" (case-insensitive). + 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"; + } +} diff --git a/src/YGOLegacy.Bots/Bot/EffectSimulator.cs b/src/YGOLegacy.Bots/Bot/EffectSimulator.cs new file mode 100644 index 0000000..00a40f0 --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/EffectSimulator.cs @@ -0,0 +1,903 @@ +using System; +using System.Collections.Generic; +using WindBot.Game; +using WindBot.Game.AI; +using YGOSharp.OCGWrapper.Enums; + +namespace YGOLegacy.Bot +{ + /// + /// 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). + /// + 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; + } + + /// + /// Pure, deterministic prediction of the board after one modelled effect + /// (TICKET-040): removes / bounces / banishes the affected cards from a + /// 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 + /// . 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". + /// + 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; + + /// The board after the effect (spec signature): target may be null. + public static BoardView Apply(BoardView view, EffectModel m, ClientField bot, ClientField enemy, ClientCard chosenTarget = null) + => Apply(view, m, bot, enemy, new EffectContext { Target = chosenTarget }); + + /// The board after the effect, with full context. + 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 cards out of a Deck that holds + /// 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; + } + + /// + /// The board if we do nothing: the pending enemy attack (if any) resolves + /// as predicted. Compare an result against THIS, not + /// the raw view, when the prompt is a battle window. + /// + 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 EnemyTargets(EffectModel m, ClientField enemy) + { + var list = new List(); + 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 OwnTargets(EffectModel m, ClientField bot, ClientCard exceptSource = null) + { + var list = new List(); + 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 (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 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--; + } + } + + /// + /// What a summon/fusion SPENDS (Fusion Materials): materials + /// cards out of from. 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). any spends the hand first and + /// only then the field, the same "off-field material costs nothing" + /// preference the selection layer applies. + /// + 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; + } + } + } + + /// + /// 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 + /// (), 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. + /// + /// endTurnDestroy 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. + /// + 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 was removed. + private static bool RemoveMonsters(List 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 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 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 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; + } + + /// + /// 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 (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 — + /// 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). + /// + 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(); + var affected = new List(); + 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(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(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 levels, Dictionary 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 ExtraXyzRanks(ClientField bot) + { + var map = new Dictionary(); + 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 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; + } + } +} diff --git a/src/YGOLegacy.Bots/Bot/LocalDuelHost.cs b/src/YGOLegacy.Bots/Bot/LocalDuelHost.cs new file mode 100644 index 0000000..de014d6 --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/LocalDuelHost.cs @@ -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. + // ------------------------------------------------------------------------ + + /// ocgcore's CardData, byte-identical to Percy.CardData. + [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); + } + } + + /// + /// 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. + /// + 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; } + } + + /// What a finished (or abandoned) duel looked like. + 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 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 cardLookup; + private static Func scriptLookup; + private static IntPtr scriptBuffer; + private static int scriptBufferSize; + + /// + /// Install the process-global card/script readers. Call once, before the + /// first duel. returns null for an unknown code + /// (the core gets a zeroed CardData, exactly as the game's reader does); + /// returns null when a script does not exist. + /// + public static void InstallReaders(Func cards, Func 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 MainA, MainB; + public IList 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; + /// + /// 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. + /// + 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 Log; + + // ---- TICKET-050 (rollout lookahead) -------------------------- + /// + /// 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. + /// + public int ForcedFirstSeat = -1; + + /// + /// Record every prompt answer into LocalDuelOutcome.Responses. Off + /// by default: a normal measurement run must not pay for it. + /// + public bool RecordResponses; + + /// + /// 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. + /// + public IList ScriptedResponses; + + /// + /// 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. + /// + 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(); + } + + // ================================================================== + // The duel + // ================================================================== + + /// + /// 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. + /// + public LocalDuelOutcome Live => outcome; + + private bool ran; + + /// Play the duel. One host plays ONE duel; call it once. + 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(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 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 } + + /// + /// TICKET-050: keep outcome.Lp current. All four messages are + /// player(1) + amount(int32); LP_UPDATE sets, the others move. + /// + 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; + } + + /// TICKET-050: monsters on the field when the duel stopped. + 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(); + } + + /// + /// 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 << 16)` — command 0..5 = + /// summon / special summon / reposition / monster set / spell set / + /// activate — so the pair names exactly which idle command was illegal. + /// + 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 "); + 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); + } + + /// + /// 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. + /// + 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(); + + } +} diff --git a/src/YGOLegacy.Bots/Bot/Lookahead.cs b/src/YGOLegacy.Bots/Bot/Lookahead.cs new file mode 100644 index 0000000..1ffdb4a --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/Lookahead.cs @@ -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. + // ------------------------------------------------------------------------ + + /// + /// 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 + /// GameAI.OnSelectIdleCmd). + /// + public interface IIdlePlanner + { + /// + /// Cheap gate asked before anything is copied or walked: false = the + /// seam behaves exactly as upstream. + /// + bool YGOL_WantsPlan(); + + /// + /// Pick an idle action. 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. + /// + /// + /// The chosen MainPhaseAction.ToValue(), 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. + /// + int? YGOL_PlanIdle(MainPhase main, Func, MainPhaseAction> walk); + } + + /// + /// Something that can play the current duel forward from the prompt being + /// answered right now and say how a candidate answer turned out. + /// + public interface ILookaheadOracle + { + /// False = do not even try (no host attached, budget spent, …). + bool Available { get; } + + /// + /// Value of answering the CURRENT idle prompt with + /// (a MainPhaseAction.ToValue()), + /// in 0..1 — 1 = we won every rollout, 0 = we lost every rollout. + /// = could not be evaluated (the rollout + /// desynced, the budget ran out, …), which the caller treats as + /// "evaluator only". + /// + /// playouts to average (knob lookahead). + /// + /// stop this many turns past the current one and score the position + /// instead of playing to the end (knob lookaheadTurns; 0 = play + /// to the end). + /// + /// + /// wall-clock ceiling for this whole call (knob lookaheadMs); + /// the oracle returns what it has when the budget is gone. + /// + float Evaluate(int idleResponse, int rollouts, int horizonTurns, int msBudget); + + /// Human-readable note about the last (for the log). + string LastNote { get; } + } +} diff --git a/src/YGOLegacy.Bots/Bot/LoopbackBotSeat.cs b/src/YGOLegacy.Bots/Bot/LoopbackBotSeat.cs new file mode 100644 index 0000000..20f7fd3 --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/LoopbackBotSeat.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using WindBot.Game; + +namespace YGOLegacy.Bot +{ + /// + /// TICKET-045: a WindBot wired into + /// with no socket. + /// + /// The client is built through the [YGOL] loopback seam + /// (GameClient.YGOL_StartLoopback): its Send lands in + /// 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 GameBehavior, the same + /// SmartExecutor, the same DuelStateBus tap in + /// OnPacketReceived, the same YGOL_DuelResult. + /// + /// Host and bot share one thread: 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. + /// + public sealed class LoopbackBotSeat : ILoopbackSeat + { + private readonly Queue outbox = new Queue(); + + public GameClient Client { get; } + public string SeatName { get; } + + /// Non-null once the client threw (a MSG_RETRY, mostly). + public Exception Failure { get; private set; } + + /// + public string Failed => Failure == null ? null : Failure.GetType().Name + ": " + Failure.Message; + + /// + /// A GameClient that has NOT been Start()ed — this constructor starts it + /// on the loopback transport instead. + /// + 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; + } + } +} diff --git a/src/YGOLegacy.Bots/Bot/SmartExecutor.cs b/src/YGOLegacy.Bots/Bot/SmartExecutor.cs new file mode 100644 index 0000000..efe8e72 --- /dev/null +++ b/src/YGOLegacy.Bots/Bot/SmartExecutor.cs @@ -0,0 +1,3146 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Newtonsoft.Json; +using WindBot.Game; +using WindBot.Game.AI; +using YGOLegacy.Characters; +using YGOSharp.OCGWrapper.Enums; + +namespace YGOLegacy.Bot +{ + // Assets/Scripts/MasterDuel/Character.cs is a global-namespace MonoBehaviour + // of the same name; alias the model inside the namespace so it wins. + using Character = YGOLegacy.Characters.Character; + // 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; + + /// + /// The fork's scoring brain for WindBot (TICKET-029). Picked when a + /// character's deck brain says "executor": "Smart" (BotRoster emits + /// Deck=Smart). Instead of a fixed rule order it ranks every candidate + /// action with (+ one-step + /// for battle) and layers per-character + /// (combos, priorities, response policies) on top. + /// + /// How it knows who it is: WindBot runs in-process, and the seat's deck path + /// travels as DeckFile="group/name" -> GameClient.DeckFile, + /// which is set before the executor is constructed. The ctor resolves + /// CharacterRegistry.ForDeck(deckPath) (static, loaded at boot) and + /// character.BrainFor(deckPath) for difficulty/knobs, then reads + /// Data/Characters/<id>/<brain.rules | brain.json>. No character, no file, or a + /// broken file -> empty rules -> DefaultExecutor-grade play, never a crash. + /// + /// Threading: everything here runs on the WindBot thread. No UnityEngine + /// objects are touched; logging is UnityEngine.Debug.Log only, prefixed + /// [YGOL bot], and gated by (or knob + /// verbose: 1) except for the one line at construction. + /// + /// Idle decisions still go through WindBot's AddExecutor list because + /// GameAI.OnSelectIdleCmd walks it in order — so registration order IS the + /// priority order: rule-layer combo steps first, then WindBot's staple + /// handlers (Ash, Solemn, MST...), then one generic gate per action type. + /// A generic gate ranks every candidate of its type for the current prompt + /// and returns true only when the card being asked about is the best one, + /// which turns the linear walk into an argmax. + /// + [Deck("Smart", null, "Normal")] + public class SmartExecutor : DefaultExecutor, IIdlePlanner + { + /// Global switch: log every decision path (chosen rule + top-3 scores). + public static bool Verbose; + + /// Global gag: while true, no decision logging at all — not even a + /// brain whose knob says `verbose: 1`. The Bot Arena (TICKET-030) sets + /// it for the length of a run so N duels do not flood the console. + public static bool Muted; + + /// When set, wins over the brain's `seed` knob and the WindBot draw: + /// the Bot Arena assigns one per seat per duel so a run's noise is + /// reproducible from its recorded seed. Read once, at construction. + public static int? SeedOverride; + + /// Decision journal (TICKET-036): when non-null, every decision and + /// its outcome is appended as one JSON object per line to this file + /// (JSONL). Read ONCE at construction, like SeedOverride — the arena + /// sets it per seat right before spawning that bot. Null = off, and + /// off costs nothing (every hook checks + /// before building a string). Writes are locked process-wide, so two + /// bots may share a file. + public static string JournalPath; + + /// Arena duel index stamped on every journal line (0 outside a run). + public static int JournalDuel; + + /// TICKET-050: the rollout oracle for the seat being built, read ONCE at + /// construction like and + /// (the arena sets it immediately before creating that seat's GameClient + /// and clears it after). Null — always, in the game — means the + /// lookahead knobs are inert and the idle walk is the stock one. + public static ILookaheadOracle Oracle; + + /// TICKET-050: per-seat knob overrides applied ON TOP of the character + /// brain's knobs (the arena's --knobsA/--knobsB). Read once at + /// construction; null = nothing overridden. + public static IReadOnlyDictionary KnobOverrides; + + private const string LogPrefix = "[YGOL bot] "; + + public enum DifficultyLevel { Easy, Normal, Hard } + + // ---- identity / config ------------------------------------------------- + public string DeckPath { get; } + public string CharacterId { get; } + public BrainConfig Config { get; } + public BrainRules Rules { get; } + public DifficultyLevel Difficulty { get; } + public float Aggression { get; } + public float TradeTolerance { get; } + public int Seed { get; } + /// TICKET-040: a pick-one removal waits while its best legal target is + /// worth less than this many monster units (evaluator: 1 unit = 700), + /// unless the enemy has lethal on board. Knob `removalPatience`, default 0.5. + public float RemovalPatience { get; } + + /// An ATK boost / equip only goes on a monster with at least this much + /// ATK — unless the boost lets a weaker one beat an enemy face-up + /// monster it could not beat before. Knob `boostMinAtk`, default 1000 + /// (a 500-ATK token with +300 is still a 800-ATK token). + public int BoostMinAtk { get; } + + /// Knob `summonBias` (default 80): flat eagerness added to every normal + /// summon score (special summons get +20 more). Knob `handCardValue` + /// (default 130): what the evaluator pays for one card in hand. + public float SummonBias { get; } + public float HandCardValue { get; } + /// Knob `extraSummonBias` (default 0): extra points for summoning from + /// the Extra Deck. The evaluator charges an Xyz/Synchro its materials + /// (two bodies) and credits one body back, so it under-rates going tall; + /// this pays for the effect / tempo the stats do not show. + public float ExtraSummonBias { get; } + + /// E2 (2026-08-18): a face-up summon scoring below this many evaluator + /// points is a WEAK BODY — the 0-900 ATK utility monster the next + /// beater eats for free. When one wins the summon prompt and a FLIP + /// monster is settable from hand, the Set is scored against it and the + /// better option wins. Knob `weakBodyThreshold`, default 700 = one + /// monster unit; 0 switches the comparison off. + public float WeakBodyThreshold { get; } + + /// TICKET-042: what this brain may read about the enemy's private state + /// (knob `insight`: 0 none / 1 hand / 2 full, default none; the arena's + /// --insightA/--insightB override it). NEVER null. No decision code + /// reads it yet — it only shows up in the boot line and, at level + /// >= hand, as `enemyHandKnown` on the journal's `turn` line. + public Insight Insight { get; } + + /// TICKET-050 lookahead knobs. `lookahead` is the master switch: 0 + /// (the default, and every brain in Data/Characters/) = the planner + /// declines and this class behaves exactly as it did before the + /// prototype. See docs/tickets/backlog/TICKET-050-bot-lookahead-rollouts.md. + public int Lookahead { get; } + public int LookaheadCandidates { get; } + public int LookaheadTurns { get; } + public float LookaheadWeight { get; } + public int LookaheadMs { get; } + /// What one place of the executor's OWN preference order is worth when + /// it is blended against the rollout value. The walk gives an order, + /// not a score, so rank k is scored (K-1-k) * this. + public float LookaheadRankPoints { get; } + + private readonly ILookaheadOracle lookaheadOracle; + /// True while the planner is re-walking the executor list to enumerate + /// candidates: every gate must be side-effect free (no combo progress, + /// no journal lines, no "prompt answered" latch). + private bool plannerProbe; + + private readonly bool verboseKnob; + private readonly Random rng; + private readonly BoardEvaluator evaluator; + private readonly int unknownDefense; + private readonly float noiseSigma; + + // ---- rule layer state ------------------------------------------------- + private bool rulesActiveThisTurn = true; + private readonly int[] comboProgress; + private readonly bool[] comboDoneTurn; + private readonly bool[] comboDoneDuel; + /// Card ids WindBot's staple handlers own (registered with a specific id): + /// the generic gates leave those to their handler, like Lucky does. + private readonly HashSet<(int id, ExecutorType type)> staples = new(); + + // ---- prompt bookkeeping ----------------------------------------------- + private MainPhase seenMain; + private bool idleStale; + private BattlePhase seenBattle; + private bool battleStale; + private IList chainCandidates; + private readonly Dictionary noiseCache = new(); + + private static readonly int[] BuiltinNever = + { + _CardId.LeftArmofTheForbiddenOne, _CardId.RightLegofTheForbiddenOne, _CardId.LeftLegofTheForbiddenOne, + _CardId.RightArmofTheForbiddenOne, _CardId.ExodiaTheForbiddenOne, + }; + + public SmartExecutor(GameAI ai, Duel duel) : base(ai, duel) + { + // Everything WindBot's DefaultExecutor registered in its own ctor + // (Chicken Game etc.) plus what we add below counts as a staple. + foreach (var exec in Executors) + if (exec.CardId > 0) staples.Add((exec.CardId, exec.Type)); + + // --- who am I --------------------------------------------------- + DeckPath = ai?.Game?.DeckFile; + Character character = null; + BrainConfig config = null; + BrainRules rules = BrainRules.Empty; + string rulesError = null; + try + { + character = CharacterRegistry.ForDeck(DeckPath); + if (character != null) + { + config = character.BrainFor(DeckPath) ?? character.brain; + rules = BrainRules.Load(character.directory, out rulesError, config?.rules); + } + } + catch (Exception e) + { + rulesError = "character lookup failed: " + e.Message; + } + CharacterId = character?.id; + Config = config ?? new BrainConfig(); + Config.knobs ??= new Dictionary(); + knobOverrides = Merge(KnobOverrides, ai?.Game?.YGOL_Knobs); + try { groupKnobs = CharacterRegistry.GroupKnobs(DeckPath); } catch (Exception) { groupKnobs = null; } + Rules = rules ?? BrainRules.Empty; + + // A Room seat's difficulty wins over the brain's; the shared BrainConfig is never written. + Difficulty = ParseDifficulty(ai?.Game?.YGOL_Difficulty ?? Config.difficulty); + Aggression = BoardEvaluator.Clamp01(Knob("aggression", 0.5f)); + TradeTolerance = BoardEvaluator.Clamp01(Knob("tradeTolerance", 0.3f)); + RemovalPatience = Math.Max(0f, Knob("removalPatience", 0.5f)); + BoostMinAtk = Math.Max(0, (int)Knob("boostMinAtk", 1000f)); + EmptyFieldUrgency = Knob("emptyFieldUrgency", 350f); // evaluator points; 0 = off + SummonBias = Knob("summonBias", 80f); // added to every summon/spsummon score + HandCardValue = Knob("handCardValue", 130f); // evaluator: one card in hand + ExtraSummonBias = Knob("extraSummonBias", 0f); // added to extra-deck (Xyz/Synchro/Fusion/Link) summon scores + WeakBodyThreshold = Math.Max(0f, Knob("weakBodyThreshold", 700f)); // E2: below this a face-up body loses to setting a FLIP monster + // TICKET-042: an explicit per-seat override (arena) wins over the + // deck's knob. A level above `none` is what wakes the duel state + // bus up — with every brain on `none` the taps stay switched off. + var myName = ai?.Game?.Username; + var insightLevel = DuelStateBus.OverrideFor(myName) + ?? (InsightLevel)Math.Min(2, Math.Max(0, (int)Knob("insight", 0f))); + Insight = DuelStateBus.InsightFor(myName, insightLevel); + verboseKnob = Knob("verbose", 0f) >= 1f; + // TICKET-050. Default 0 everywhere = off; the oracle is null in the + // game, so even a brain that set the knob would fall straight back + // to the stock walk. + Lookahead = Math.Max(0, (int)Knob("lookahead", 0f)); + LookaheadCandidates = Math.Max(2, (int)Knob("lookaheadCandidates", 4f)); + LookaheadTurns = Math.Max(0, (int)Knob("lookaheadTurns", 6f)); + LookaheadWeight = Knob("lookaheadWeight", 1f); + LookaheadMs = Math.Max(0, (int)Knob("lookaheadMs", 1500f)); + LookaheadRankPoints = Knob("lookaheadRankPoints", 300f); + lookaheadOracle = Lookahead > 0 ? Oracle : null; + // Reproducible noise: an explicit seed knob, else one drawn from + // WindBot's own RNG and logged so a run can be replayed. + Seed = SeedOverride ?? (knobOverrides != null && knobOverrides.TryGetValue("seed", out var seatSeed) ? (int)seatSeed + : Config.knobs.TryGetValue("seed", out var seedKnob) ? (int)seedKnob : (WindBot.Program.Rand?.Next() ?? 12345)); + rng = new Random(Seed); + + evaluator = new BoardEvaluator + { + Aggression = Aggression, + HandCardValue = HandCardValue, + CounterAttackWeight = Difficulty == DifficultyLevel.Hard ? 1f : Difficulty == DifficultyLevel.Normal ? 0.5f : 0f, + }; + noiseSigma = Difficulty == DifficultyLevel.Easy ? 250f : 0f; + // A face-down monster is guessed bolder the more aggressive the brain. + // What a face-down monster is assumed to be worth in a fight. + // Measured (Weevil DK, 1000 duels per setting): 1000 -> 61.0 %, + // 1300 -> 66.3 %, 1500 -> 67.4 %, 1600 -> 63.7 %. Guess too low and + // the bot charges into walls; too high and it never attacks a set + // monster and just takes chip damage. 1500 at aggression 0.5. + // Knob `unknownDefense` (0 = use this formula) overrides per deck. + unknownDefense = (int)Knob("unknownDefense", 0f); + if (unknownDefense <= 0) unknownDefense = (int)(900 + 1200 * (1f - Aggression)); + + comboProgress = new int[Rules.combos.Count]; + comboDoneTurn = new bool[Rules.combos.Count]; + comboDoneDuel = new bool[Rules.combos.Count]; + + journalFile = JournalPath; + journalDuel = JournalDuel; + if (journalFile != null) JournalOpen(); + + UnityEngine.Debug.Log(LogPrefix + "SmartExecutor for deck '" + (DeckPath ?? "?") + "'" + + (character != null ? " as character '" + character.id + "'" : " (no owning character)") + + " difficulty=" + Difficulty + " aggression=" + Aggression + " tradeTolerance=" + TradeTolerance + + " seed=" + Seed + " insight=" + YGOLegacy.Bot.Insight.LevelName(Insight.Level) + " rules=" + (Rules.IsEmpty ? "none" : Rules.source + " (" + Rules.combos.Count + " combos, " + Rules.effects.Count + " effect models)") + + (rulesError != null ? " RULES ERROR: " + rulesError : string.Empty) + + (Rules.warnings.Count > 0 ? " RULES WARN: " + string.Join("; ", Rules.warnings) : string.Empty)); + + RegisterRuleLayer(); + RegisterStaples(); + RegisterGenericGates(); + } + + // ===================================================================== + // Registration + // ===================================================================== + + private void RegisterRuleLayer() + { + for (int ci = 0; ci < Rules.combos.Count; ci++) + { + var combo = Rules.combos[ci]; + for (int si = 0; si < combo.steps.Count; si++) + { + var step = combo.steps[si]; + int cIdx = ci, sIdx = si; + Func gate = () => ComboStepGate(cIdx, sIdx); + switch (step.Action) + { + case RuleAction.Summon: AddExecutor(ExecutorType.Summon, step.card, gate); break; + case RuleAction.SpSummon: AddExecutor(ExecutorType.SpSummon, step.card, gate); break; + case RuleAction.Repos: AddExecutor(ExecutorType.Repos, step.card, gate); break; + case RuleAction.Set: + { + var data = YGOSharp.OCGWrapper.NamedCard.Get(step.card); + bool monster = data != null && data.HasType(CardType.Monster); + bool spell = data != null && !monster; + if (monster || data == null) AddExecutor(ExecutorType.MonsterSet, step.card, gate); + if (spell || data == null) AddExecutor(ExecutorType.SpellSet, step.card, gate); + break; + } + default: AddExecutor(ExecutorType.Activate, step.card, gate); break; + } + } + } + } + + /// WindBot's generic library, same set LuckyExecutor trusts. + private void RegisterStaples() + { + void Staple(ExecutorType type, int id, Func func) + { + AddExecutor(type, id, func); + staples.Add((id, type)); + } + + Staple(ExecutorType.Activate, _CardId.MysticalSpaceTyphoon, DefaultMysticalSpaceTyphoon); + Staple(ExecutorType.Activate, _CardId.CosmicCyclone, DefaultCosmicCyclone); + Staple(ExecutorType.Activate, _CardId.GalaxyCyclone, DefaultGalaxyCyclone); + Staple(ExecutorType.Activate, _CardId.BookOfMoon, DefaultBookOfMoon); + Staple(ExecutorType.Activate, _CardId.CompulsoryEvacuationDevice, DefaultCompulsoryEvacuationDevice); + Staple(ExecutorType.Activate, _CardId.CallOfTheHaunted, DefaultCallOfTheHaunted); + Staple(ExecutorType.Activate, _CardId.Scapegoat, DefaultScapegoat); + Staple(ExecutorType.Activate, _CardId.MaxxC, DefaultMaxxC); + Staple(ExecutorType.Activate, _CardId.AshBlossom, DefaultAshBlossomAndJoyousSpring); + Staple(ExecutorType.Activate, _CardId.GhostOgreAndSnowRabbit, DefaultGhostOgreAndSnowRabbit); + Staple(ExecutorType.Activate, _CardId.GhostBelle, DefaultGhostBelleAndHauntedMansion); + Staple(ExecutorType.Activate, _CardId.EffectVeiler, DefaultEffectVeiler); + Staple(ExecutorType.Activate, _CardId.CalledByTheGrave, DefaultCalledByTheGrave); + Staple(ExecutorType.Activate, _CardId.InfiniteImpermanence, DefaultInfiniteImpermanence); + Staple(ExecutorType.Activate, _CardId.BreakthroughSkill, DefaultBreakthroughSkill); + Staple(ExecutorType.Activate, _CardId.SolemnJudgment, DefaultSolemnJudgment); + Staple(ExecutorType.Activate, _CardId.SolemnWarning, DefaultSolemnWarning); + Staple(ExecutorType.Activate, _CardId.SolemnStrike, DefaultSolemnStrike); + Staple(ExecutorType.Activate, _CardId.TorrentialTribute, DefaultTorrentialTribute); + Staple(ExecutorType.Activate, _CardId.HeavyStorm, DefaultHeavyStorm); + Staple(ExecutorType.Activate, _CardId.HarpiesFeatherDuster, DefaultHarpiesFeatherDusterFirst); + Staple(ExecutorType.Activate, _CardId.HammerShot, DefaultHammerShot); + Staple(ExecutorType.Activate, _CardId.DarkHole, DefaultDarkHole); + Staple(ExecutorType.Activate, _CardId.Raigeki, DefaultRaigeki); + Staple(ExecutorType.Activate, _CardId.SmashingGround, DefaultSmashingGround); + Staple(ExecutorType.Activate, _CardId.PotOfDesires, DefaultPotOfDesires); + Staple(ExecutorType.Activate, _CardId.AllureofDarkness, DefaultAllureofDarkness); + Staple(ExecutorType.Activate, _CardId.DimensionalBarrier, DefaultDimensionalBarrier); + Staple(ExecutorType.Activate, _CardId.InterruptedKaijuSlumber, DefaultInterruptedKaijuSlumber); + + Staple(ExecutorType.SpSummon, _CardId.JizukirutheStarDestroyingKaiju, DefaultKaijuSpsummon); + Staple(ExecutorType.SpSummon, _CardId.GadarlatheMysteryDustKaiju, DefaultKaijuSpsummon); + Staple(ExecutorType.SpSummon, _CardId.GamecieltheSeaTurtleKaiju, DefaultKaijuSpsummon); + Staple(ExecutorType.SpSummon, _CardId.RadiantheMultidimensionalKaiju, DefaultKaijuSpsummon); + Staple(ExecutorType.SpSummon, _CardId.KumongoustheStickyStringKaiju, DefaultKaijuSpsummon); + Staple(ExecutorType.SpSummon, _CardId.ThunderKingtheLightningstrikeKaiju, DefaultKaijuSpsummon); + Staple(ExecutorType.SpSummon, _CardId.DogorantheMadFlameKaiju, DefaultKaijuSpsummon); + Staple(ExecutorType.SpSummon, _CardId.SuperAntiKaijuWarMachineMechaDogoran, DefaultKaijuSpsummon); + + Staple(ExecutorType.SpSummon, _CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightSummon); + Staple(ExecutorType.Activate, _CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect); + + Staple(ExecutorType.Summon, _CardId.SandaionTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.GabrionTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.MichionTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.ZaphionTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.HailonTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.RaphionTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.SadionTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.MetaionTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.KamionTheTimelord, DefaultTimelordSummon); + Staple(ExecutorType.Summon, _CardId.LazionTheTimelord, DefaultTimelordSummon); + } + + private void RegisterGenericGates() + { + AddExecutor(ExecutorType.Activate, ActivateGate); + AddExecutor(ExecutorType.SpSummon, SpSummonGate); + AddExecutor(ExecutorType.SummonOrSet, SummonGate); + AddExecutor(ExecutorType.MonsterSet, MonsterSetGate); + AddExecutor(ExecutorType.Repos, ReposGate); + AddExecutor(ExecutorType.SpellSet, SpellSetGate); + } + + // ===================================================================== + // Turn / prompt lifecycle + // ===================================================================== + + public override void OnNewTurn() + { + base.OnNewTurn(); + if (Journaling) JournalTurn(); + for (int i = 0; i < comboProgress.Length; i++) + { + comboProgress[i] = 0; + comboDoneTurn[i] = false; + } + // Easy: half the turns the scripted lines are simply forgotten. + rulesActiveThisTurn = Difficulty != DifficultyLevel.Easy || rng.NextDouble() >= 0.5; + if (Duel.Player == 0) + Log("turn " + Duel.Turn + " rules " + (rulesActiveThisTurn ? "on" : "off (easy)") + + " board=" + evaluator.Score(Bot, Enemy).ToString("0")); + } + + public override void OnNewPhase() + { + base.OnNewPhase(); + noiseCache.Clear(); + chainCandidates = null; + openActivation = null; + if (Journaling) JournalPhase(); + } + + public override void OnChaining(int player, ClientCard card) + { + base.OnChaining(player, card); + idleStale = true; + battleStale = true; + if (Journaling) JournalChaining(player, card); + } + + public override void OnChainSolved(int chainIndex) + { + base.OnChainSolved(chainIndex); + if (Journaling) JournalChainSolved(chainIndex); + } + + public override void OnChainEnd() + { + base.OnChainEnd(); + openActivation = null; + if (Journaling) JournalChainEnd(); + } + + public override void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + base.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + idleStale = true; + battleStale = true; + if (Journaling) JournalMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + public override void OnSelectChain(IList cards) + { + base.OnSelectChain(cards); + chainCandidates = cards; + if (Journaling) JournalOffered(cards); + } + + /// The idle prompt's card lists are still the ones being answered. + private bool IdleFresh() + { + var main = Duel.MainPhase; + if (!ReferenceEquals(main, seenMain)) + { + seenMain = main; + idleStale = false; + } + return main != null && !idleStale && Duel.Player == 0 + && (Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2); + } + + private bool BattleFresh() + { + var battle = Duel.BattlePhase; + if (!ReferenceEquals(battle, seenBattle)) + { + seenBattle = battle; + battleStale = false; + } + return battle != null && !battleStale && Duel.Player == 0; + } + + /// A gate said yes: the prompt is answered, later calls (effect yes/no, + /// chain windows) must not rank against these stale lists. + private void MarkAnswered() + { + // TICKET-050: a planner probe is asking the SAME prompt again, so + // the lists are still fresh and nothing has been answered yet. + if (plannerProbe) return; + idleStale = true; + battleStale = true; + noiseCache.Clear(); + } + + // ===================================================================== + // Rule layer + // ===================================================================== + + private bool ComboStepGate(int ci, int si) + { + if (!rulesActiveThisTurn || Card == null) return false; + var combo = Rules.combos[ci]; + if (comboDoneTurn[ci] || comboDoneDuel[ci]) return false; + int progress = comboProgress[ci]; + if (si < progress) return false; + for (int k = progress; k < si; k++) + if (!combo.steps[k].optional) return false; + var step = combo.steps[si]; + if (!Card.IsCode(step.card)) return false; + if (step.Action == RuleAction.Activate && step.desc >= 0 && ActivateDescription != step.desc) return false; + if (progress == 0 && combo.when != null && !combo.when.Holds(Bot, Enemy, Duel)) return false; + if (step.when != null && !step.when.Holds(Bot, Enemy, Duel)) return false; + if (step.Action == RuleAction.Activate && DefaultCheckWhetherCardIsNegated(Card)) return false; + + // TICKET-050: a planner probe only wants the VERDICT. Advancing the + // combo (and the summon intent, and the log) here would run the + // combo forward once per candidate walk. + if (plannerProbe) return true; + + if (step.Action == RuleAction.Activate) + openActivation = new EffectPlan { Card = Card, Model = Rules.EffectFor(Card.Id, ActivateDescription) }; + comboProgress[ci] = si + 1; + if (si + 1 >= combo.steps.Count) + { + if (combo.oncePerDuel) comboDoneDuel[ci] = true; + if (combo.oncePerTurn) comboDoneTurn[ci] = true; + else comboProgress[ci] = 0; + } + MarkAnswered(); + // The core asks summon-or-set right after; honour the step's verb. + comboSummonIntent = step.Action == RuleAction.Summon ? Card.Id + : step.Action == RuleAction.Set ? -Card.Id : 0; + Log("rule: combo '" + (combo.name ?? ("#" + (ci + 1))) + "' step " + (si + 1) + "/" + combo.steps.Count + + ": " + step.Action + " " + Name(Card)); + if (Journaling) + { + string why = "combo '" + (combo.name ?? ("#" + (ci + 1))) + "' step " + (si + 1); + switch (step.Action) + { + case RuleAction.Summon: case RuleAction.SpSummon: case RuleAction.Set: + if (Card.IsMonster() || Card.Data == null) JournalPendingSummon(step.Action == RuleAction.SpSummon ? "spsummon" : step.Action == RuleAction.Set ? "set" : "summon", Card, null, why); + else JournalSet(Card, null, why); + break; + case RuleAction.Repos: JournalRepos(Card, why); break; + default: JournalActivate(Card, ActivateDescription, null, why); break; + } + } + return true; + } + + /// +id = a combo step just chose Summon (face-up) for that card, -id = Set; 0 = none. + private int comboSummonIntent; + + /// A combo that can still run this turn and wants this action later. + private bool ReservedByCombo(int cardId, RuleAction action) + { + if (!rulesActiveThisTurn || cardId == 0) return false; + for (int ci = 0; ci < Rules.combos.Count; ci++) + { + if (comboDoneTurn[ci] || comboDoneDuel[ci]) continue; + var combo = Rules.combos[ci]; + int progress = comboProgress[ci]; + for (int si = progress; si < combo.steps.Count; si++) + { + var step = combo.steps[si]; + if (step.card != cardId || step.Action != action) continue; + if (progress == 0 && combo.when != null && !combo.when.Holds(Bot, Enemy, Duel)) break; + return true; + } + } + return false; + } + + /// A WindBot staple handler owns this (card, action): the generic gate + /// abstains so the handler's own verdict stands (as LuckyExecutor does). + private bool IsStaple(ClientCard card, ExecutorType type) + => card != null && card.Id != 0 && (staples.Contains((card.Id, type)) || (card.Alias != 0 && staples.Contains((card.Alias, type)))); + + private bool Forbidden(ClientCard card) + => card == null || Rules.IsForbidden(card.Id) || Array.IndexOf(BuiltinNever, card.Id) >= 0; + + // ===================================================================== + // Generic gates (idle / chain prompts) + // ===================================================================== + + private struct Candidate + { + public ClientCard Card; + public int Desc; + public float Score; + public string Why; + /// TICKET-040: the simulated effect (null for an unmodelled card). + public EffectPlan Plan; + } + + /// + /// One simulated activation (TICKET-040): the model, the target the + /// simulation preferred, the predicted board delta and — for pick-one + /// removals — how much the best legal target is worth on its own. + /// + private sealed class EffectPlan + { + public ClientCard Card; + public EffectModel Model; + public ClientCard Target; + public float Delta; + public float BestTargetWorth; + public int Candidates; + /// Set when the plan refuses outright (Delta = -inf): the reason to log. + public string Why; + } + + /// The activation being resolved or just chosen (its selections use the model). + private EffectPlan openActivation; + + private bool ActivateGate() + { + if (Card == null) return false; + var candidates = ActivateCandidates(); + var ranked = Rank(candidates, (ref Candidate c) => ActivationScore(c.Card, c.Desc, out c.Why, out c.Plan) + Noise(c.Card)); + if (ranked.Count == 0) return false; + var best = ranked[0]; + bool isFirstAsked = AskedFirst(candidates); + if (best.Score <= 0f) + { + if (isFirstAsked) LogRanked("activate: hold", ranked); + return false; + } + bool chosen = ReferenceEquals(best.Card, Card) && (best.Desc == -1 || best.Desc == ActivateDescription); + if (chosen) + { + MarkAnswered(); + // TICKET-050: a probe must not leave a pending activation behind + // (the confirming walk sets it for the action actually taken). + if (!plannerProbe) openActivation = best.Plan ?? new EffectPlan { Card = Card, Model = null }; + LogRanked("activate " + Name(Card) + (best.Why != null ? " [" + best.Why + "]" : string.Empty), ranked); + if (Journaling) JournalActivate(Card, ActivateDescription, best.Score, best.Why, best.Plan); + } + return chosen; + } + + private List ActivateCandidates() + { + var list = new List(); + if (Journaling) + { + JournalOffered(chainCandidates); + JournalOffered(Duel.MainPhase?.ActivableCards); + JournalOffered(Duel.BattlePhase?.ActivableCards); + } + if (CurrentTiming >= 0 && chainCandidates != null && chainCandidates.Contains(Card)) + { + foreach (var c in chainCandidates) list.Add(new Candidate { Card = c, Desc = -1 }); + } + else if (IdleFresh() && Duel.MainPhase.ActivableCards.Contains(Card)) + { + var main = Duel.MainPhase; + for (int i = 0; i < main.ActivableCards.Count; i++) + list.Add(new Candidate { Card = main.ActivableCards[i], Desc = i < main.ActivableDescs.Count ? main.ActivableDescs[i] : -1 }); + } + else if (BattleFresh() && Duel.BattlePhase.ActivableCards.Contains(Card)) + { + var battle = Duel.BattlePhase; + for (int i = 0; i < battle.ActivableCards.Count; i++) + list.Add(new Candidate { Card = battle.ActivableCards[i], Desc = i < battle.ActivableDescs.Count ? battle.ActivableDescs[i] : -1 }); + } + if (list.Count == 0 || !list.Any(c => ReferenceEquals(c.Card, Card))) + { + list.Clear(); + list.Add(new Candidate { Card = Card, Desc = ActivateDescription }); + } + return list; + } + + /// How much the brain wants to activate this card right now; <= 0 = hold. + private float ActivationScore(ClientCard card, int desc, out string why) + => ActivationScore(card, desc, out why, out _); + + /// + /// Activation score. A card with an effect model (TICKET-040) is scored by + /// its predicted board delta (EffectSimulator + BoardEvaluator, plus + /// priority, plus the reactive-context bonuses); a card without one keeps + /// the flat "own turn" score and TICKET-036's removal scope guard. + /// + private float ActivationScore(ClientCard card, int desc, out string why, out EffectPlan plan) + { + why = null; + plan = null; + if (Forbidden(card)) { why = "never"; return float.NegativeInfinity; } + if (IsStaple(card, ExecutorType.Activate)) { why = "staple"; return float.NegativeInfinity; } + if (ReservedByCombo(card.Id, RuleAction.Activate)) { why = "reserved"; return float.NegativeInfinity; } + if (DefaultCheckWhetherCardIsNegated(card)) { why = "negated"; return float.NegativeInfinity; } + var policy = Rules.responses.ChainPolicyOf(card.Id); + if (policy == ChainPolicy.Never) { why = "policy never"; return float.NegativeInfinity; } + if (card.HasType(CardType.Equip) && Bot.GetMonsterCount() == 0) { why = "no equip target"; return float.NegativeInfinity; } + // An unmodelled equip is assumed to be an ATK boost: without a + // face-up attacker to carry it, it is a wasted card (a modelled + // equip is scored by the simulator instead, which discounts + // defenders itself; a rule `chain: always` still overrides). + if (card.HasType(CardType.Equip) && Rules.EffectFor(card.Id, -1) == null + && !Bot.GetMonsters().Any(mo => mo.IsFaceup() && mo.IsAttack() && WorthBoosting(mo, UnknownBoostAmount))) + { why = "equip: no face-up attacker worth it"; return float.NegativeInfinity; } + var model = Rules.EffectFor(card.Id, desc); + // E1 (2026-08-18): `selfHarm` = resolving this helps the opponent + // whatever the board looks like (Mimighoul Dragon gives itself + // away). Never fired by the generic layer; a combo step still can. + if (model != null && model.selfHarm) { why = "selfHarm"; return float.NegativeInfinity; } + if (model == null && !RemovalScopeOk(card, out var scopeWhy)) { why = scopeWhy; return float.NegativeInfinity; } + if (!SummonBodyWorthIt(model, out var bodyWhy)) { why = bodyWhy; return float.NegativeInfinity; } + + float prio = Rules.PriorityOf(card.Id) * 100f; + if (policy == ChainPolicy.Always) { why = "policy always"; return 1100f + prio; } + + bool myTurn = Duel.Player == 0; + bool chainPrompt = CurrentTiming >= 0; + bool ownAction = myTurn && !chainPrompt; + + float s; + var reasons = new StringBuilder(); + if (model != null) + { + plan = SimulateEffect(card, model); + if (float.IsNegativeInfinity(plan.Delta)) { why = plan.Why ?? "effect: no sensible target"; return float.NegativeInfinity; } + s = plan.Delta + prio; + reasons.Append("effect ").Append(model.Kind.ToString().ToLowerInvariant()).Append(" delta ").Append(plan.Delta.ToString("0")); + if (plan.Target != null) reasons.Append(" -> ").Append(Name(plan.Target)); + if (model.IsSingleRemoval && plan.Candidates > 0) + { + float floor = RemovalPatience * 700f; + if (plan.BestTargetWorth < floor && !EnemyHasLethal()) + { + why = "removal: waiting (best target worth " + plan.BestTargetWorth.ToString("0") + " < " + floor.ToString("0") + ")"; + return float.NegativeInfinity; + } + } + reasons.Append(' '); + } + else + { + s = 100f + prio; + reasons.Append(ownAction ? "own turn" : string.Empty); + } + + if (card.HasType(CardType.Field) && card.Location == CardLocation.Hand && Bot.SpellZone[5] != null) + s -= Bot.SpellZone[5].IsCode(card.Id) ? 500f : 200f; + + if (ownAction) + { + if (model != null && model.Trigger != EffectTrigger.Own && model.Trigger != EffectTrigger.Any) + { + s -= 300f; + reasons.Append("saving for ").Append(model.trigger); + } + why = reasons.ToString().Trim(); + return s; + } + + // Reactive context: enemy turn, or a chain window on our own turn. + bool responding = Duel.LastChainPlayer == 1; + bool enemySummoned = Duel.LastSummonPlayer == 1; + bool threat = Util.GetProblematicEnemyCard() != null; + bool underAttack = Bot.UnderAttack; + bool enemyEnd = !myTurn && Duel.Phase == DuelPhase.End; + float trigger = 0f; + if (model != null) + { + // The delta already prices the situation (the attack it stops, the + // summon it answers); the model's trigger says whether this is the + // window the author meant. + bool matched; + switch (model.Trigger) + { + case EffectTrigger.EnemySummon: matched = enemySummoned; break; + case EffectTrigger.EnemyAttack: matched = underAttack; break; + case EffectTrigger.EnemyActivate: matched = responding; break; + case EffectTrigger.Standby: matched = Duel.Phase == DuelPhase.Standby; break; + case EffectTrigger.End: matched = Duel.Phase == DuelPhase.End; break; + case EffectTrigger.Any: matched = true; break; + default: matched = false; break; // "own": reactively only with a generic trigger + } + if (model.Trigger == EffectTrigger.Own || model.Trigger == EffectTrigger.Any) + { + if (responding || enemySummoned || threat || underAttack || enemyEnd) { trigger += 100f; reasons.Append("reactive "); } + else if (model.Trigger == EffectTrigger.Own) { s -= 200f; reasons.Append("no trigger "); } + } + else if (matched) { trigger += 150f; reasons.Append("trigger ").Append(model.trigger).Append(' '); } + else { s -= 300f; reasons.Append("waiting for ").Append(model.trigger).Append(' '); } + if (threat) { trigger += 100f; reasons.Append("threat "); } + if (policy == ChainPolicy.EnemyTurn && !myTurn) { trigger += 200f; reasons.Append("policy-enemy-turn "); } + if (policy == ChainPolicy.Problematic && !threat && !responding && !enemySummoned && !underAttack) { why = "policy problematic: quiet"; return float.NegativeInfinity; } + if (chainPrompt && Duel.LastChainPlayer == 0) { s -= 400f; reasons.Append("self-chain "); } + // Gap G (2026-08-18): the reactive/threat bonuses used to be + // added on top of the effect delta with no floor, so a card + // whose OWN simulation says it makes the board worse still + // cleared the activation threshold (17 Desert Sunlight + // activations at a negative delta in one 60-duel run). A + // position/protect effect IS its board change — there is no + // card advantage hiding behind it — so a negative delta gets no + // window bonus. Deliberately NOT applied to every kind: the + // broad version also muted removals and summons whose delta is + // momentarily negative and cost Wicked Gods 1.7 points + // (65.2 -> 63.5, n=2000) for no gain elsewhere. + if (plan.Delta < 0f && (model.Kind == EffectKind.Position || model.Kind == EffectKind.Protect)) + { trigger = 0f; reasons.Append("negative delta: no window bonus "); } + s += trigger; + why = reasons.ToString().Trim(); + return s; + } + if (responding) { trigger += 250f; reasons.Append("respond "); } + if (enemySummoned) { trigger += 150f; reasons.Append("enemy-summon "); } + if (threat) { trigger += 150f; reasons.Append("threat "); } + if (underAttack) { trigger += 200f; reasons.Append("under-attack "); } + if (enemyEnd) { trigger += 150f; reasons.Append("enemy-end "); } + if (policy == ChainPolicy.EnemyTurn && !myTurn) { trigger += 200f; reasons.Append("policy-enemy-turn "); } + if (policy == ChainPolicy.Problematic && trigger <= 0f) { why = "policy problematic: quiet"; return float.NegativeInfinity; } + if (chainPrompt && Duel.LastChainPlayer == 0) { s -= 400f; reasons.Append("self-chain "); } + if (trigger <= 0f) { s -= 200f; reasons.Append("no trigger"); } + else s += trigger; + why = reasons.ToString().Trim(); + return s; + } + + // ===================================================================== + // Effect simulation (TICKET-040) + // ===================================================================== + + /// The moment as the simulator may know it: the enemy attack in progress + /// (battle windows) and the enemy card we would chain to. + private EffectContext EffectContextNow(ClientCard source, ClientCard target = null) + { + var ctx = new EffectContext { Source = source, Target = target, UnknownPower = unknownDefense }; + if (Bot.UnderAttack && Enemy.BattlingMonster != null && Enemy.BattlingMonster.Controller == 1) + { + ctx.Attacker = Enemy.BattlingMonster; + ctx.Defender = Bot.BattlingMonster; + } + if (Duel.LastChainPlayer == 1 && Duel.CurrentChain.Count > 0) + { + var last = Duel.CurrentChain[Duel.CurrentChain.Count - 1]; + if (last != null && last.Controller == 1) ctx.EnemyChainCard = last; + } + return ctx; + } + + /// + /// Predict what activating does to the board: for a + /// pick-one effect every legal enemy target is tried and the best kept + /// (its worth on its own feeds the removalPatience test); otherwise the + /// simulator picks (best enemy monsters first / all matches). + /// Delta = Score(after) - Score(if we do nothing), both including a + /// pending enemy attack. + /// + private EffectPlan SimulateEffect(ClientCard card, EffectModel model) + { + var plan = new EffectPlan { Card = card, Model = model }; + var view = BoardView.From(Bot, Enemy, unknownDefense); + var ctx = EffectContextNow(card); + float before = evaluator.Score(EffectSimulator.Baseline(view, ctx)); + float raw = evaluator.Score(view); + + bool single = !model.CountAll && model.Count == 1; + bool picksEnemy = single && (model.IsRemoval || model.Kind == EffectKind.Negate || model.Kind == EffectKind.Position + || (model.Kind == EffectKind.Boost && model.Scope == EffectScope.Enemy)); + // Equips / protection: which of OUR monsters gets the most out of it. + bool picksOwn = single && !picksEnemy && (model.Kind == EffectKind.Boost || model.Kind == EffectKind.Protect); + if (picksEnemy || picksOwn) + { + var targets = picksEnemy ? EffectSimulator.EnemyTargets(model, Enemy) : EffectSimulator.OwnTargets(model, Bot, card); + if (picksOwn) targets.RemoveAll(t => t.Location != CardLocation.MonsterZone); + // A (mainly) ATK boost belongs on a face-up attacker; on a defender + // it is a wasted card (it will not swing, and it is usually the + // weak body about to die). No attacker -> hold the card. + if (picksOwn && model.Kind == EffectKind.Boost && model.amount > 0 + && (model.def ?? 0) < Math.Max(500, (int)model.amount)) + { + targets.RemoveAll(t => !(t.IsFaceup() && t.IsAttack())); + if (targets.Count == 0) + { + plan.Delta = float.NegativeInfinity; + plan.Why = "boost: no face-up attacker to carry it"; + return plan; + } + // ...and not on a weakling: below `boostMinAtk` the card is + // wasted unless the boost makes it beat an enemy monster. + targets.RemoveAll(t => !WorthBoosting(t, (int)model.amount)); + if (targets.Count == 0) + { + plan.Delta = float.NegativeInfinity; + plan.Why = "boost: wins no fight for anyone (and no real body >= " + BoostMinAtk + " to bank it on)"; + return plan; + } + } + if (targets.Count > 0) + { + plan.Candidates = targets.Count; + float bestDelta = float.MinValue; + foreach (var t in targets) + { + ctx.Target = t; + float delta = evaluator.Score(EffectSimulator.Apply(view, model, Bot, Enemy, ctx)) - before; + if (delta > bestDelta) { bestDelta = delta; plan.Target = t; } + } + plan.Delta = bestDelta; + // Worth of the best target on its own: the effect with no + // source charged and no battle pending. + var worthCtx = new EffectContext { Target = plan.Target, UnknownPower = unknownDefense }; + plan.BestTargetWorth = evaluator.Score(EffectSimulator.Apply(view, model, Bot, Enemy, worthCtx)) - raw; + return plan; + } + } + ctx.Target = null; + plan.Delta = evaluator.Score(EffectSimulator.Apply(view, model, Bot, Enemy, ctx)) - before; + return plan; + } + + /// How badly the brain wants a body on an empty board (evaluator points; + /// ~half a monster unit). Not a knob yet: it is a rule of the game, not + /// a taste — an empty board takes every attack to the face. + private readonly float EmptyFieldUrgency; + + /// What an unmodelled equip is assumed to add (only used to ask + /// whether a weak carrier could win a fight). + private const int UnknownBoostAmount = 500; + + /// Core rule for every deck: a boost has to DO something. + /// 2 = it flips a fight — the carrier now beats an enemy face-up monster + /// it could not beat before (any ATK, even a token; that is the + /// boost doing real work). Best use, so it is preferred. + /// 1 = a real body (>= `boostMinAtk`) that already beats every enemy + /// face-up monster, or the enemy has none: the boost is only extra + /// damage, but on a monster worth investing in. + /// 0 = wasted: a weakling that still beats nothing new, or a body that + /// even boosted stays under something and beats nothing new. + private int BoostValue(ClientCard carrier, int amount) + { + if (carrier == null) return 0; + if (amount <= 0) return carrier.Attack >= BoostMinAtk ? 1 : 0; // DEF / protection: just the body bar + int boosted = carrier.Attack + amount; + bool flips = false, anyEnemy = false, beatsAll = true; + foreach (var e in Enemy.GetMonsters()) + { + if (e == null || !e.IsFaceup()) continue; + anyEnemy = true; + int power = e.IsAttack() ? e.Attack : e.Defense; + if (carrier.Attack <= power && boosted > power) flips = true; + if (carrier.Attack <= power) beatsAll = false; + } + if (flips) return 2; + if (carrier.Attack >= BoostMinAtk && (!anyEnemy || beatsAll)) return 1; + return 0; + } + + private bool WorthBoosting(ClientCard carrier, int amount) => BoostValue(carrier, amount) > 0; + + /// The enemy's face-up attackers add up to our LP: no time to be patient. + private bool EnemyHasLethal() => BoardEvaluator.EnemyAttackTotal(Enemy) >= Bot.LifePoints; + + /// The modelled activation a selection prompt belongs to: the chain link + /// of ours being resolved, else the activation a gate/combo just chose. + private EffectPlan OpenModelledActivation() + { + var solving = Duel.GetCurrentSolvingChainCard(); + if (solving != null && solving.Controller == 0) + { + if (openActivation != null && ReferenceEquals(openActivation.Card, solving)) return openActivation.Model != null ? openActivation : null; + var m = Rules.EffectFor(solving.Id); + return m != null ? new EffectPlan { Card = solving, Model = m } : null; + } + return openActivation != null && openActivation.Model != null ? openActivation : null; + } + + private bool SpSummonGate() + { + if (Card == null) return false; + var candidates = IdleCandidates(Duel.MainPhase?.SpecialSummonableCards); + var ranked = Rank(candidates, (ref Candidate c) => SpSummonScore(c.Card, out c.Why) + Noise(c.Card)); + if (ranked.Count == 0) return false; + var best = ranked[0]; + bool isFirstAsked = AskedFirst(candidates); + if (best.Score <= 0f) + { + if (isFirstAsked) LogRanked("spsummon: hold", ranked); + return false; + } + bool chosen = ReferenceEquals(best.Card, Card); + if (chosen) + { + MarkAnswered(); + LogRanked("spsummon " + Name(Card) + (best.Why != null ? " [" + best.Why + "]" : string.Empty), ranked); + if (Journaling) JournalPendingSummon("spsummon", Card, best.Score, best.Why); + } + return chosen; + } + + private float SpSummonScore(ClientCard card, out string why) + { + why = null; + if (Forbidden(card)) { why = "never"; return float.NegativeInfinity; } + if (IsStaple(card, ExecutorType.SpSummon)) { why = "staple"; return float.NegativeInfinity; } + if (ReservedByCombo(card.Id, RuleAction.SpSummon)) { why = "reserved"; return float.NegativeInfinity; } + // A card that Special Summons ITSELF is described by its own summon + // model, and the same hopeless-body gate applies (this is the path + // Infernal Prodigy takes — it is never "activated"). + var selfSummon = Rules.EffectFor(card.Id, -1); + if (selfSummon != null && selfSummon.IsSummon + && !SummonBodyWorthIt(selfSummon, out var bodyWhy)) { why = bodyWhy; return float.NegativeInfinity; } + + var view = BoardView.From(Bot, Enemy, unknownDefense); + float before = evaluator.Score(view); + int atk = Math.Max(0, Atk(card)), def = Math.Max(0, Def(card)); + int materials = card.IsExtraCard() || (card.Data != null && card.Data.IsExtraCard()) ? EstimateMaterials(card) : 0; + var after = BoardEvaluator.WithoutCheapestBotMonsters(view, materials); + after = BoardEvaluator.WithBotMonster(after, atk, def, PreferAttack(atk, def), true, BoardEvaluator.ThreatOf(card)); + if (card.Location == CardLocation.Hand) after.BotHand--; + float delta = evaluator.Score(after) - before; + delta += SummonBias + 20f + Rules.PriorityOf(card.Id) * 100f; + if (materials > 0) delta += ExtraSummonBias; + why = "delta " + delta.ToString("0") + (materials > 0 ? " materials~" + materials : string.Empty); + return delta; + } + + private bool SummonGate() + { + if (Card == null) return false; + var candidates = IdleCandidates(Duel.MainPhase?.SummonableCards); + var ranked = Rank(candidates, (ref Candidate c) => SummonScore(c.Card, out c.Why) + Noise(c.Card)); + if (ranked.Count == 0) return false; + var best = ranked[0]; + bool isFirstAsked = AskedFirst(candidates); + if (best.Score <= 0f) + { + if (isFirstAsked) LogRanked("summon: hold", ranked); + if (Journaling) JournalRejectedSummon(best); + return false; + } + // E2 (2026-08-18): a WEAK winning body loses to setting a FLIP + // monster from hand. Declining here is not passing the turn — the + // MonsterSet gate runs straight after this one and sets the flip. + if (best.Score < WeakBodyThreshold && FlipSetBeatsWeakBody(best, out var flipWhy)) + { + if (isFirstAsked) LogRanked("summon: hold [" + flipWhy + "]", ranked); + if (Journaling) pendingPositionWhy = "flip from hand beats weak body"; + return false; + } + bool chosen = ReferenceEquals(best.Card, Card); + if (chosen) + { + MarkAnswered(); + LogRanked("summon " + Name(Card) + (best.Why != null ? " [" + best.Why + "]" : string.Empty), ranked); + if (Journaling) JournalPendingSummon("summon", Card, best.Score, best.Why); + } + return chosen; + } + + /// + /// E2 (2026-08-18) — "Set the best FLIP monster in hand" as a rival to a + /// weak face-up summon. + /// + /// The summon prompt only ranks face-up-summonable bodies: printed FLIP + /// monsters were already dropped from it (`flip: set instead`), so on an + /// empty enemy board the winner is whatever 0-ATK utility monster is in + /// hand and it goes face-up into ATTACK. In a 60-duel review that + /// happened 22 times (Rubble King x8, Warm Worm x7, A/D Changer x6) and + /// was the free 2800 the opponent needed. So when the winner scores + /// below , price the Set of the best FLIP + /// monster in hand on the same evaluator scale and take the better one. + /// Nothing happens for a deck holding no settable FLIP monster, and a + /// strong body never reaches this test. + /// + private bool FlipSetBeatsWeakBody(Candidate best, out string why) + { + why = null; + if (WeakBodyThreshold <= 0f || best.Card == null) return false; + var setable = Duel.MainPhase?.MonsterSetableCards; + if (setable == null || setable.Count == 0) return false; + + var view = BoardView.From(Bot, Enemy, unknownDefense); + float before = evaluator.Score(view); + ClientCard bestFlip = null; + float bestScore = float.NegativeInfinity; + foreach (var c in setable) + { + if (c == null || !IsFlipMonster(c)) continue; + if (Forbidden(c) || ReservedByCombo(c.Id, RuleAction.Set) || Level(c) > 4) continue; + var stripped = view.Clone(); + stripped.BotHand--; + float score = evaluator.Score(BoardEvaluator.WithBotMonster(stripped, Math.Max(0, Atk(c)), Math.Max(0, Def(c)), false, false, 0f)) + - before + SummonBias + Rules.PriorityOf(c.Id) * 100f; + if (score > bestScore) { bestScore = score; bestFlip = c; } + } + if (bestFlip == null || bestScore <= best.Score) return false; + why = "set " + Name(bestFlip) + " " + bestScore.ToString("0") + " beats weak body " + + Name(best.Card) + " " + best.Score.ToString("0"); + Log("summon held: " + why); + return true; + } + + private float SummonScore(ClientCard card, out string why) + { + why = null; + if (Forbidden(card)) { why = "never"; return float.NegativeInfinity; } + if (IsStaple(card, ExecutorType.Summon)) { why = "staple"; return float.NegativeInfinity; } + if (ReservedByCombo(card.Id, RuleAction.Summon)) { why = "reserved"; return float.NegativeInfinity; } + if (card.HasType(CardType.Flip)) { why = "flip: set instead"; return float.NegativeInfinity; } + if (!UniqueFaceupMonsterOk(card)) { why = "already face-up"; return float.NegativeInfinity; } + + var view = BoardView.From(Bot, Enemy, unknownDefense); + float before = evaluator.Score(view); + int atk = Math.Max(0, Atk(card)), def = Math.Max(0, Def(card)); + int level = Level(card); + int tributes = level <= 4 ? 0 : level <= 6 ? 1 : 2; + var stripped = BoardEvaluator.WithoutCheapestBotMonsters(view, tributes); + stripped.BotHand--; + float asAttack = evaluator.Score(BoardEvaluator.WithBotMonster(stripped, atk, def, true, true, BoardEvaluator.ThreatOf(card))); + float asSet = evaluator.Score(BoardEvaluator.WithBotMonster(stripped, atk, def, false, false, 0f)); + float delta = Math.Max(asAttack, asSet) - before; + delta += SummonBias + Rules.PriorityOf(card.Id) * 100f; + // An EMPTY board is the worst board: every enemy attacker swings at + // our LP, and even a body that dies eats one attack. Half a monster + // unit of urgency, so a summon the evaluator dislikes still happens + // rather than ending the turn wide open. Tribute summons are exempt + // (they cost bodies we do not have). + if (tributes == 0 && Bot.GetMonsterCount() == 0 && BoardEvaluator.EnemyAttackTotal(Enemy) > 0) + { + delta += EmptyFieldUrgency; + why = "empty field, delta " + delta.ToString("0"); + return delta; + } + why = "delta " + delta.ToString("0") + (tributes > 0 ? " tributes " + tributes : string.Empty); + return delta; + } + + private bool UniqueFaceupMonsterOk(ClientCard card) + => Level(card) <= 4 || !Bot.GetMonsters().Any(m => m.IsCode(card.Id) && m.IsFaceup()); + + // ===================================================================== + // FLIP monsters (2026-08-18) + // ===================================================================== + // + // A FLIP monster's whole payoff is the flip: face-down it is a wall AND + // a trap, face-up in attack it is usually a 0-900 ATK body the next + // 1900 beater eats for free. So the default for one is SET, whatever + // the enemy board looks like — an empty enemy field is the WORST reason + // to summon it face-up, because nothing is stopping the enemy from + // summoning a beater next turn. Rule pins (`positions`) and combo verbs + // still win; see IsFlipMonster / WantsFlipSummon. + + /// True for a monster whose value is its flip trigger. The printed + /// TYPE_FLIP bit is the primary test, but the card database does not + /// carry it for every card whose text is a flip trigger (Tsukuyomi + /// 0x221, Snowman Eater 0x21), so PSCT text is the fallback: "FLIP:" or + /// "flipped face-up". Cached per id — the answer never changes. + private static readonly Dictionary flipMonsterCache = new Dictionary(); + + private static bool IsFlipMonster(int cardId) + { + if (cardId == 0) return false; + lock (flipMonsterCache) + { + if (flipMonsterCache.TryGetValue(cardId, out var known)) return known; + } + var data = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + bool flip = data != null + && (data.HasType(CardType.Flip) + || (data.HasType(CardType.Monster) && TextIsFlipTrigger(data.Description))); + lock (flipMonsterCache) + { + flipMonsterCache[cardId] = flip; + } + return flip; + } + + private static bool IsFlipMonster(ClientCard card) + => card != null && (card.HasType(CardType.Flip) || IsFlipMonster(card.Id)); + + private static bool TextIsFlipTrigger(string text) + { + if (string.IsNullOrEmpty(text)) return false; + return text.StartsWith("FLIP:", StringComparison.Ordinal) + || text.IndexOf("flipped face-up", StringComparison.OrdinalIgnoreCase) >= 0; + } + + /// True = Set (face-down defence), false = Normal Summon (face-up attack; + /// a normal summon has no face-up-defence option, so a "defense" rule + /// means Set here — "faceup" is the value for self-switching monsters). + public override bool OnSelectMonsterSummonOrSet(ClientCard card) + { + bool set = SummonOrSet(card, out var why); + if (Journaling) pendingPositionWhy = why; // lands on the journal's summon/set line + return set; + } + + private bool SummonOrSet(ClientCard card, out string why) + { + if (comboSummonIntent != 0 && Math.Abs(comboSummonIntent) == card.Id) + { + bool set = comboSummonIntent < 0; + comboSummonIntent = 0; + why = "combo verb " + (set ? "Set" : "Summon"); + return set; + } + comboSummonIntent = 0; + var pref = Rules.PositionFor(card.Id); + if (pref == "set" || pref == "defense") { why = "rule position " + pref; return true; } + if (pref == "attack" || pref == "faceup") { why = "rule position " + pref; return false; } + if (IsFlipMonster(card)) { why = "flip default set"; return true; } + if (Enemy.GetMonsterCount() == 0) { why = "open field"; return false; } + int enemyAtk = BoardEvaluator.BestEnemyAttack(Enemy); + int enemyPower = BoardEvaluator.BestEnemyPower(Enemy); + int atk = Atk(card), def = Def(card); + if (enemyPower > 0 && atk > enemyPower) { why = "beats " + enemyPower; return false; } // it can fight + if (enemyAtk == 0) { why = "no enemy attacker"; return false; } // only face-downs / defenders: no pressure + if (def >= enemyAtk && def > atk) { why = "walls " + enemyAtk; Log("set " + Name(card) + ": walls " + enemyAtk); return true; } + if (atk < enemyAtk) { why = "would die in attack to " + enemyAtk; Log("set " + Name(card) + ": would die in attack to " + enemyAtk); return true; } + why = "evaluator: attack"; + return false; + } + + private bool MonsterSetGate() + { + if (Card == null) return false; + var candidates = IdleCandidates(Duel.MainPhase?.MonsterSetableCards); + var ranked = Rank(candidates, (ref Candidate c) => MonsterSetScore(c.Card, out c.Why) + Noise(c.Card)); + if (ranked.Count == 0) return false; + var best = ranked[0]; + if (best.Score <= 0f) return false; + bool chosen = ReferenceEquals(best.Card, Card); + if (chosen) + { + MarkAnswered(); + LogRanked("set monster " + Name(Card) + (best.Why != null ? " [" + best.Why + "]" : string.Empty), ranked); + if (Journaling) JournalPendingSummon("set", Card, best.Score, best.Why); + } + return chosen; + } + + private float MonsterSetScore(ClientCard card, out string why) + { + why = null; + if (Forbidden(card)) { why = "never"; return float.NegativeInfinity; } + if (ReservedByCombo(card.Id, RuleAction.Set)) { why = "reserved"; return float.NegativeInfinity; } + if (Level(card) > 4) { why = "tribute set"; return float.NegativeInfinity; } + float prio = Rules.PriorityOf(card.Id) * 100f; + if (Rules.PositionFor(card.Id) == "set") { why = "rule position set"; return 300f + prio; } + if (IsFlipMonster(card)) { why = "flip effect"; return 200f + prio; } + int enemyAtk = BoardEvaluator.BestEnemyAttack(Enemy); + int atk = Atk(card), def = Def(card); + if (Bot.GetMonsterCount() == 0 && enemyAtk > atk) + { + // Empty board vs an attacker: ANY set body is worth it — it + // walls if DEF is high enough, and otherwise still eats one + // attack instead of our LP. + why = def >= enemyAtk ? "wall vs " + enemyAtk : "body vs " + enemyAtk; + return 100f + prio + def * 0.05f; + } + why = "no reason"; + return float.NegativeInfinity; + } + + private bool ReposGate() + { + var card = Card; + if (card == null || ReservedByCombo(card.Id, RuleAction.Repos)) return false; + bool result = WantsRepos(card, out var why); + if (result) + { + MarkAnswered(); + Log("repos " + Name(card) + " [" + why + "]"); + if (Journaling) JournalRepos(card, why); + } + return result; + } + + private bool WantsRepos(ClientCard card, out string why) + { + why = null; + var pref = Rules.PositionFor(card.Id); + int enemyAtk = BoardEvaluator.BestEnemyAttack(Enemy); + int enemyPower = BoardEvaluator.BestEnemyPower(Enemy); + int enemyCount = Enemy.GetMonsterCount(); + + if (card.IsFacedown()) + { + // Flip summon (lands face-up attack). + if (pref == "defense" || pref == "set" || pref == "faceup") return false; + if (IsFlipMonster(card)) return WantsFlipSummon(card, pref, out why); + if (enemyCount == 0 && card.Attack > 0) { why = "open field"; return true; } + if (card.Attack > enemyPower && card.Attack >= enemyAtk) { why = "beats " + enemyPower; return true; } + return false; + } + if (pref == "attack") { why = "rule position attack"; return card.IsDefense(); } + if (pref == "defense" || pref == "faceup") { why = "rule position " + pref; return card.IsAttack(); } + if (card.IsMonsterInvincible()) { why = "invincible"; return card.IsDefense(); } + if (card.Attack == 0 && card.IsAttack()) { why = "0 atk"; return true; } + + bool main1 = Duel.Phase == DuelPhase.Main1; + bool wantAttack = enemyCount == 0 + || (main1 && (card.Attack > enemyPower || card.Attack >= enemyAtk)) + || (!main1 && card.Attack >= enemyAtk && enemyAtk > 0) + || (!main1 && enemyAtk == 0 && card.Attack >= card.Defense); + if (card.IsAttack() && !wantAttack && (card.Defense >= card.Attack || card.Defense >= enemyAtk)) + { + why = "to defense vs " + enemyAtk; + return true; + } + if (card.IsDefense() && wantAttack && card.Attack > 0) + { + why = "to attack"; + return true; + } + return false; + } + + /// + /// FLIP monsters (2026-08-18) — should we Flip Summon this face-down FLIP monster? + /// + /// A Flip Summon lands the body face-up in ATTACK by rule, so it trades + /// a wall (that still triggers when attacked, for free) for a usually + /// tiny attacker. Take it only when it pays: + /// (i) the flip effect is MODELLED (`effects`) and its simulated + /// board delta beats what losing the body would cost us; + /// (ii) the body survives anyway — the enemy has no monster, no + /// attacker, or our ATK beats their best attacker; + /// (iii) the swing including this body is lethal, or a `positions` + /// rule pinned the card to attack. + /// Otherwise hold it face-down: the flip still fires when it is attacked. + /// + private bool WantsFlipSummon(ClientCard card, string pref, out string why) + { + why = null; + // (iii) a rule pin is the owner talking: it wins, as everywhere else. + if (pref == "attack") { why = "rule position attack"; return true; } + + int enemyAtk = BoardEvaluator.BestEnemyAttack(Enemy); + int body = Math.Max(0, card.Attack); + var model = Rules.EffectFor(card.Id); + + // E1 (2026-08-18): a flip the brain has flagged as self-harming is + // never taken voluntarily. Mimighoul Dragon's FLIP destroys our own + // face-up monsters and hands the card to the opponent; Chewbone + // gives them three tokens. `never` cannot say this (it would also + // stop us SETTING the card as a wall, which measured worse). + if (model != null && model.selfHarm) return HoldFlip(card, "flip held: selfHarm — the flip helps the opponent"); + + // (ii) nothing can punish the body this turn cycle... AND the flip + // is actually good for us. That second half is E1: the old branch + // took 44 of 118 Flip Summons in a review run purely because the + // board looked safe, which is how a mandatory "destroy 1 face-up + // monster" with no enemy target ate our own beater. + string safeWhy = null; + if (Enemy.GetMonsterCount() == 0) safeWhy = "open field"; + else if (enemyAtk == 0) safeWhy = "no enemy attacker"; + else if (body > enemyAtk) safeWhy = "body beats " + enemyAtk; + if (safeWhy != null) + { + if (FlipPaysOff(card, model, out var badWhy)) { why = "flip effect (" + safeWhy + ")"; return true; } + return HoldFlip(card, "flip held: " + badWhy + " (" + safeWhy + ")"); + } + + var view = BoardView.From(Bot, Enemy, unknownDefense); + + // (iii) lethal: the body face-up in attack finishes the duel. + if (Duel.Phase == DuelPhase.Main1) + { + var swung = view.Clone(); + int i = swung.IndexOfBot(card); + if (i >= 0) + { + var m = swung.Bot[i]; + m.FaceUp = true; + m.AttackPos = true; + swung.Bot[i] = m; + if (BoardEvaluator.SwingDamage(swung) >= Enemy.LifePoints) + { + why = "flip for lethal"; + return true; + } + } + } + + // The body dies to the enemy's best attacker before it swings again. + // What is it worth to us? (the evaluator's own answer, so LP weight, + // threat and board count are all priced the way everything else is) + float bodyLoss = evaluator.Score(view) - evaluator.Score(WithoutBotMonster(view, card)); + + // (i) a modelled flip effect that out-earns the body. + if (model != null) + { + var plan = SimulateEffect(card, model); + if (plan.Delta > bodyLoss) + { + why = "flip effect worth " + plan.Delta.ToString("0") + " vs body " + bodyLoss.ToString("0"); + return true; + } + why = "flip held: effect " + plan.Delta.ToString("0") + " < body " + bodyLoss.ToString("0") + + " (dies to " + enemyAtk + ")"; + } + else + { + why = "flip held: body would die to " + enemyAtk + " and the flip is not modelled"; + } + if (Journaling) JournalFlipHeld(card, why); + Log("hold flip " + Name(card) + " [" + why + "]"); + why = null; // ReposGate only logs the positive answer + return false; + } + + /// + /// E1 (2026-08-18) — is turning this card face-up actually GOOD for us? + /// Asked only on the "the body survives anyway" branch, where the old + /// code flipped whatever was face-down without ever reading what the + /// flip does. + /// + /// A MODELLED flip must simulate to a non-negative board delta, and a + /// `scope: enemy` effect must have at least one legal enemy target + /// right now (Snowman Eater's mandatory "destroy 1 face-up monster" + /// with nothing of theirs face-up destroys OUR monster instead — model + /// it with `filter: { "faceup": true }` and this test sees that). + /// An UNMODELLED flip is allowed, exactly as before, unless the brain + /// flagged it `selfHarm` (checked by the caller). + /// + private bool FlipPaysOff(ClientCard card, EffectModel model, out string why) + { + why = null; + if (model == null) return true; // unmodelled: unchanged behaviour + if (model.Scope == EffectScope.Enemy && EffectSimulator.EnemyTargets(model, Enemy).Count == 0) + { + why = "no legal enemy target for a scope-enemy flip"; + return false; + } + var plan = SimulateEffect(card, model); + if (float.IsNegativeInfinity(plan.Delta) || plan.Delta < 0f) + { + why = "modelled flip delta " + (float.IsNegativeInfinity(plan.Delta) ? "refused" : plan.Delta.ToString("0")); + return false; + } + return true; + } + + /// Journal + log a Flip Summon we decline, and answer "no" to ReposGate. + private bool HoldFlip(ClientCard card, string why) + { + if (Journaling) JournalFlipHeld(card, why); + Log("hold flip " + Name(card) + " [" + why + "]"); + return false; + } + + /// The board without one of OUR monsters (the body a flip would expose). + private static BoardView WithoutBotMonster(BoardView board, ClientCard card) + { + var next = board.Clone(); + int i = next.IndexOfBot(card); + if (i >= 0) next.Bot.RemoveAt(i); + return next; + } + + private bool SpellSetGate() + { + if (Card == null || Forbidden(Card) || ReservedByCombo(Card.Id, RuleAction.Set)) return false; + bool result = DefaultSpellSet(); + if (result) + { + MarkAnswered(); + Log("set " + Name(Card)); + if (Journaling) JournalSet(Card, null, "DefaultSpellSet"); + } + return result; + } + + // ===================================================================== + // Battle + // ===================================================================== + + private class AttackPlan + { + public ClientCard Attacker; + public ClientCard Defender; + public BattleOutcome Outcome; + public float Delta; + public string Label => Name(Attacker) + " -> " + (Defender == null ? "direct" : Name(Defender)) + " (" + Outcome + ")"; + } + + public override BattlePhaseAction OnBattle(IList attackers, IList defenders) + { + if (attackers == null || attackers.Count == 0) return null; + var plan = BestAttack(attackers, defenders, "battle"); + if (plan != null) + { + if (Journaling) JournalAttack(plan); + return AI.Attack(plan.Attacker, plan.Defender); + } + var battle = Duel.BattlePhase; + if (battle != null && battle.CanMainPhaseTwo) return AI.ToMainPhase2(); + if (battle != null && battle.CanEndPhase) return AI.ToEndPhase(); + return null; + } + + public override ClientCard OnSelectAttacker(IList attackers, IList defenders) + { + if (attackers == null || attackers.Count == 0) return null; + return BestAttack(attackers, defenders, null)?.Attacker; + } + + public override BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList defenders) + { + if (attacker == null) return null; + var plan = BestAttack(new List { attacker }, defenders, "target for " + Name(attacker)); + if (plan == null) return null; + if (Journaling) JournalAttack(plan); + return AI.Attack(plan.Attacker, plan.Defender); + } + + /// True when our brain models this card as one that punishes whoever + /// attacks it (`effects.<id>.onAttacked`). The model is written for + /// the card as WE own it; this reads it from the other side. + private bool PunishesAttacker(int cardId) + { + var model = Rules.EffectFor(cardId); + return model != null && model.onAttacked; + } + + /// The single best attack available now, or null when every option is + /// worse than not attacking. Losing trades (attacker dies, defender + /// stays) are only allowed when battle.attackInto lists the defender; + /// a face-up defender in battle.avoidAttackInto is never attacked at all, + /// and one modelled `onAttacked` counts as a losing trade. + private AttackPlan BestAttack(IList attackers, IList defenders, string logTag) + { + if (Journaling) JournalFlushLp(); + var view = BoardView.From(Bot, Enemy, unknownDefense); + float before = evaluator.Score(view); + var plans = new List(); + var battleRules = Rules.battle; + + foreach (var attacker in attackers) + { + if (attacker == null || battleRules.neverAttackWith.Contains(attacker.Id)) continue; + bool eager = battleRules.alwaysAttackWith.Contains(attacker.Id); + + if (attacker.CanDirectAttack || defenders == null || defenders.Count == 0) + { + var o = BattlePredictor.Predict(attacker, null, null, unknownDefense); + var after = BattlePredictor.Apply(view, attacker, null, o); + float delta = evaluator.Score(after) - before + Noise(attacker) + (eager ? 500f : 0f); + if (delta > 0f) + plans.Add(new AttackPlan { Attacker = attacker, Defender = null, Outcome = o, Delta = delta }); + } + if (defenders == null) continue; + foreach (var defender in defenders) + { + if (defender == null) continue; + var o = BattlePredictor.Predict(attacker, defender, OnPreBattleBetween, unknownDefense); + if (!o.Allowed) continue; + if (o.Uncertain && !battleRules.attackFacedown) continue; + bool known = defender.Id != 0 && defender.IsFaceup(); + // Hard veto: this face-up enemy card is never attacked, whatever + // the arithmetic says (battle-proof bodies). Beats attackInto. + if (known && battleRules.avoidAttackInto.Contains(defender.Id)) continue; + bool ruleSaysAttack = battleRules.attackInto.Contains(defender.Id); + // A face-up enemy card modelled with `onAttacked` punishes + // whoever attacks it (Sanga/Kazejin/Suijin zero the attacker's + // ATK): the predictor cannot see that, so treat the attack as + // the losing trade it is. + bool punishes = known && PunishesAttacker(defender.Id); + // The one hard rule: never a losing trade on our own initiative. + if ((o.IsLosingTrade || punishes) && !ruleSaysAttack) continue; + var after = BattlePredictor.Apply(view, attacker, defender, o); + float delta = evaluator.Score(after) - before + Noise(attacker) + (eager ? 500f : 0f); + // Clearly good attacks only; even trades and chip damage taken + // pass within tradeTolerance; guesses at face-downs need a margin. + float floor = 0f; + if (o.IsEvenTrade || o.BotLpDelta < 0) floor = -TradeTolerance * 400f; + if (o.Uncertain) floor = Math.Max(floor, 100f * (1f - Aggression)); + if (delta <= floor && !ruleSaysAttack) continue; + plans.Add(new AttackPlan { Attacker = attacker, Defender = defender, Outcome = o, Delta = delta }); + } + } + + if (plans.Count == 0) + { + if (logTag != null) Log(logTag + ": no attack worth taking (board " + before.ToString("0") + ")"); + return null; + } + plans.Sort((a, b) => b.Delta.CompareTo(a.Delta)); + if (logTag != null) + { + var sb = new StringBuilder(logTag + ": " + plans[0].Label + " delta " + plans[0].Delta.ToString("0")); + for (int i = 1; i < Math.Min(3, plans.Count); i++) + sb.Append(" | ").Append(plans[i].Label).Append(' ').Append(plans[i].Delta.ToString("0")); + Log(sb.ToString()); + } + return plans[0]; + } + + // ===================================================================== + // Positions, prompts, selections + // ===================================================================== + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + var pref = Rules.PositionFor(cardId); + if (pref == "attack" && positions.Contains(CardPosition.FaceUpAttack)) return JournalPosition(cardId, CardPosition.FaceUpAttack, "rule position attack"); + if ((pref == "defense" || pref == "faceup") && positions.Contains(CardPosition.FaceUpDefence)) return JournalPosition(cardId, CardPosition.FaceUpDefence, "rule position " + pref); + if (pref == "set" && positions.Contains(CardPosition.FaceDownDefence)) return JournalPosition(cardId, CardPosition.FaceDownDefence, "rule position set"); + + // FLIP monsters (2026-08-18): a FLIP monster wants to be face-down whenever the + // prompt allows it (the arithmetic below would happily stand a + // 0 ATK Snowman Eater up in attack against an empty enemy field). + if (pref == null && IsFlipMonster(cardId) && positions.Contains(CardPosition.FaceDownDefence)) + return JournalPosition(cardId, CardPosition.FaceDownDefence, "flip default set"); + + var data = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (data == null) return base.OnSelectPosition(cardId, positions); + int atk = Math.Max(0, data.Attack), def = Math.Max(0, data.Defense); + int enemyAtk = BoardEvaluator.BestEnemyAttack(Enemy); + int enemyPower = BoardEvaluator.BestEnemyPower(Enemy); + + // Printed ATK is a placeholder for a variable-ATK body (see + // VariableAtk): its real stats are decided by its materials and the + // core only reports them once it exists. Prefer a live copy of ours + // that the core HAS reported; failing that, refuse to let a 0 pick + // the position — these are the deck's boss bodies (Chimeratech + // Overdragon lands at 1600-8000, printed "?"), and lying to the + // arithmetic below is how 1371 of them ended up in defence. + if (VariableAtk(data)) + { + int liveAtk = LiveAtkOf(cardId, out var liveDef); + if (liveAtk > 0) + { + atk = liveAtk; + def = Math.Max(0, liveDef); + } + else if (positions.Contains(CardPosition.FaceUpAttack)) + { + Log("position " + (data.Name ?? cardId.ToString()) + ": FaceUpAttack (variable ATK, not reported yet)"); + return JournalPosition(cardId, CardPosition.FaceUpAttack, "variable ATK (printed placeholder, no live copy)"); + } + } + + bool attack; + if (Enemy.GetMonsterCount() == 0) attack = atk > 0; + else if (atk > enemyPower && atk >= enemyAtk) attack = true; // wins fights and survives + else if (atk >= enemyAtk && enemyAtk > 0) attack = atk >= def; // safe either way + else if (def >= enemyAtk && def > atk) attack = false; // only defense survives + else attack = Aggression >= 0.6f && atk > 0; // both lose: attitude decides + var pos = attack ? CardPosition.FaceUpAttack : CardPosition.FaceUpDefence; + if (!positions.Contains(pos)) pos = attack ? CardPosition.FaceUpDefence : CardPosition.FaceUpAttack; + if (!positions.Contains(pos)) return base.OnSelectPosition(cardId, positions); + Log("position " + (data.Name ?? cardId.ToString()) + ": " + pos + " (enemy atk " + enemyAtk + ")"); + return JournalPosition(cardId, pos, "evaluator (enemy atk " + enemyAtk + ")"); + } + + public override bool OnSelectYesNo(int desc) + { + var answer = Rules.responses.YesNoFor(desc); + if (answer.HasValue) + { + Log("yes/no " + desc + ": rule says " + answer.Value); + return answer.Value; + } + if (desc == 210) + { + // "Continue selecting tributes?": the minimum is already met. Yes would + // spend an extra monster (and used to lead to a cancelled summon loop). + Log("yes/no 210: no more tributes"); + return false; + } + return base.OnSelectYesNo(desc); + } + + public override int OnSelectOption(IList options) + { + if (options == null || options.Count == 0) return -1; + for (int i = 0; i < options.Count; i++) + { + if (Rules.responses.preferOptions.Contains(options[i])) + { + Log("option " + options[i] + ": preferred by rule"); + return i; + } + } + int cardId = options[0] >> 4; + if (Rules.responses.options.TryGetValue(cardId, out var index) && index >= 0 && index < options.Count) + { + Log("option for " + cardId + ": rule index " + index); + return index; + } + return base.OnSelectOption(options); + } + + private static readonly int[] HintsForEnemy = + { + HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck, HintMsg.Disable, + }; + private static readonly int[] HintsForOwnCost = + { + HintMsg.Release, HintMsg.Discard, HintMsg.ToGrave, HintMsg.Remove, HintMsg.ToDeck, HintMsg.Tribute, + HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.ReturnToHand, + }; + private static readonly int[] HintsForGain = + { + HintMsg.SpSummon, HintMsg.AddToHand, HintMsg.Summon, HintMsg.ToField, HintMsg.Equip, + }; + private static readonly int[] HintsForMax = + { + HintMsg.SpSummon, HintMsg.AddToHand, HintMsg.Destroy, + }; + + /// Deterministic, evaluator-shaped selection: hurt the enemy's best card, + /// pay with our cheapest, fetch our highest-priority. Anything WindBot + /// already pre-selected (AI.SelectCard) or handles itself passes through. + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + var handled = base.OnSelectCard(cards, min, max, hint, cancelable); + if (handled != null) return handled; + if (Duel.Phase == DuelPhase.BattleStart) return null; + if (AI.HaveSelectedCards()) return null; + if (hint == HintMsg.AttackTarget) return null; // GameAI owns attack targeting (Attack() pre-selects) + if (cards == null || cards.Count == 0) return null; + // TICKET-040: a modelled effect picks the target that maximises the + // simulated board delta (enemy side) or minimises the loss (our side); + // an equip/protect goes to the monster the simulation chose. + var open = OpenModelledActivation(); + // Gap H (2026-08-18): a POSITION prompt is normally "untyped" to us + // and left to WindBot, which is how A/D Changer's scope-enemy model + // ended up standing OUR defender up in attack at 1050 LP. Claim it — + // but only while a `position` model is actually open, so every deck + // without one keeps WindBot's answer byte for byte. + bool positionPrompt = hint == HintMsg.PosChange && open?.Model != null && open.Model.Kind == EffectKind.Position; + bool known = Array.IndexOf(HintsForEnemy, hint) >= 0 || Array.IndexOf(HintsForGain, hint) >= 0 + || Array.IndexOf(HintsForOwnCost, hint) >= 0 || positionPrompt; + if (!known) return null; // untyped prompts (Target, Effect...): WindBot's default is as good a guess + if (max > cards.Count) max = cards.Count; + if (min > max) min = max; + + var pool = new List(cards); + var selected = new List(); + bool takeMax = Array.IndexOf(HintsForMax, hint) >= 0; + + if (open != null && (positionPrompt || Array.IndexOf(HintsForEnemy, hint) >= 0 || Array.IndexOf(HintsForOwnCost, hint) >= 0)) + { + var simulated = SimulatedSelection(open, cards, min, max, hint, cancelable, positionPrompt); + if (simulated != null) return simulated; + } + if (positionPrompt) return null; // nothing sensible: WindBot's default, as before + if (open != null && open.Target != null && open.Target.Controller == 0 && min <= 1 && Array.IndexOf(HintsForGain, hint) >= 0 + && (open.Model.Kind == EffectKind.Boost || open.Model.Kind == EffectKind.Protect) && cards.Contains(open.Target)) + { + selected.Add(open.Target); + Log("select hint " + hint + " for " + Name(open.Card) + ": simulated target " + Name(open.Target)); + if (Journaling) JournalSelect(hint, selected, open); + return selected; + } + + if (Array.IndexOf(HintsForEnemy, hint) >= 0) + { + var enemyCards = pool.Where(c => c.Controller == 1).OrderByDescending(EnemyCardValue).ToList(); + foreach (var c in enemyCards) + { + if (selected.Count >= max) break; + selected.Add(c); + pool.Remove(c); + } + if (selected.Count > 0 && selected.Count >= min) + { + LogSelection(hint, selected); + return selected; + } + } + + if (hint == HintMsg.Equip) + { + // Equip = ATK boost until told otherwise: the strongest face-up + // attacker of ours; a defender only if nothing else is legal. + // Best use first: a carrier the boost lets beat a new enemy + // monster (BoostValue 2), else a real body (1); ATK breaks ties. + var carrier = pool.Where(c => c.Controller == 0 && c.IsFaceup() && c.IsAttack() && WorthBoosting(c, UnknownBoostAmount)) + .OrderByDescending(c => BoostValue(c, UnknownBoostAmount)).ThenByDescending(c => c.Attack).FirstOrDefault(); + // No worthy carrier in the LEGAL pool (an equip's own restriction, + // e.g. Insects only, can leave only defenders / weaklings even + // though the activation check saw a good attacker): back out of + // the activation when the prompt lets us, rather than waste it. + if (carrier == null && cancelable && min <= 1) + { + if (Verbose) Log("equip: no worthy carrier among the legal targets, cancelling"); + return selected; // empty + cancelable = cancel (GameBehavior sends -1) + } + carrier = carrier + ?? pool.Where(c => c.Controller == 0 && c.IsFaceup() && c.IsAttack()) + .OrderByDescending(c => c.Attack).FirstOrDefault() + ?? pool.Where(c => c.Controller == 0).OrderByDescending(OwnCardValue).FirstOrDefault(); + if (carrier != null && min <= 1) + { + selected.Add(carrier); + LogSelection(hint, selected); + return selected; + } + } + + if (Array.IndexOf(HintsForGain, hint) >= 0) + { + foreach (var c in pool.OrderByDescending(OwnCardValue).ToList()) + { + if (selected.Count >= (takeMax ? max : min)) break; + selected.Add(c); + pool.Remove(c); + } + if (selected.Count >= min) + { + LogSelection(hint, selected); + return selected; + } + } + + if (Array.IndexOf(HintsForOwnCost, hint) >= 0) + { + // Field bosses go last: a cost is paid from the GY / hand / Deck + // while anything there is legal (see ExpensiveFieldMaterial). + foreach (var c in pool.Where(c => c.Controller == 0) + .OrderBy(c => KeptCost(hint, c)).ThenBy(c => ExpensiveFieldMaterial(c) ? 1 : 0).ThenBy(OwnCardValue).ToList()) + { + if (selected.Count >= min) break; + selected.Add(c); + pool.Remove(c); + } + } + + // Fill to the minimum with the cheapest remaining (ours) or the best (theirs). + foreach (var c in pool.OrderBy(c => KeptCost(hint, c)).ThenBy(c => c.Controller == 0 ? OwnCardValue(c) : -EnemyCardValue(c)).ToList()) + { + if (selected.Count >= min) break; + selected.Add(c); + pool.Remove(c); + } + if (selected.Count < min) return null; + LogSelection(hint, selected); + return selected; + } + + /// Worth of every candidate of the last simulated selection (journal: wasted-removal). + private Dictionary selectionWorths; + + /// + /// Rank the prompt's cards by the simulated delta of the open effect with + /// that card as its target. Enemy-side prompts take up to max + /// enemy cards, best delta first, but never one that makes the board + /// worse than the next-best when a better one exists; own-side (cost) + /// prompts take min of ours, least loss first. Returns null when + /// nothing sensible came out (the caller falls back to the heuristics). + /// + private IList SimulatedSelection(EffectPlan open, IList cards, int min, int max, int hint, bool cancelable = false, bool positionPrompt = false) + { + var model = open.Model; + bool anyEnemy = cards.Any(o => o != null && o.Controller == 1); + bool enemyHint = Array.IndexOf(HintsForEnemy, hint) >= 0 || positionPrompt; + // Enemy-side hint with only our cards offered = a cost in disguise. + bool enemyPrompt = enemyHint && anyEnemy; + if (enemyPrompt && model.Scope == EffectScope.Self) return null; + // ...unless the model says the effect can ONLY hit the enemy. Then + // there is no cost to pay here: the effect simply has no target, and + // every card offered is ours. Decline while the prompt lets us; when + // the core forces a pick, give up the cheapest thing we own and mark + // the line `forcedSelfPick` so the blunder detector knows we had no + // say. (Refusing to FIRE such a card instead was tried and measured + // to be worse — see the "scope enemy, no target" note next to + // RemovalScopeOk: the activation itself is what those decks want.) + // Gap H (2026-08-18): `position` joins the removals here. The escape + // is the same — decline while we may, else give up the least bad + // card — but "least bad" for a position change is not "cheapest": + // it is the monster the flip costs us least, which keeps a defender + // defending (duel 49 T22 stood our own Hane-Hane up at 1050 LP). + if (enemyHint && !anyEnemy && (model.IsRemoval || model.Kind == EffectKind.Position) && model.Scope == EffectScope.Enemy) + { + if (cancelable && min <= 1) + { + Log("select hint " + hint + " for " + Name(open.Card) + " (" + model + "): scope enemy, no enemy target, cancelling"); + return new List(); // empty + cancelable = cancel (GameBehavior sends -1) + } + var ours = cards.Where(c => c != null && c.Controller == 0); + List forced; + if (model.Kind == EffectKind.Position) + { + var board = BoardView.From(Bot, Enemy, unknownDefense); + float baseline = evaluator.Score(board); + forced = ours.OrderByDescending(c => PositionFlipDelta(board, baseline, c)).ThenBy(OwnCardValue).Take(min).ToList(); + } + else forced = ours.OrderBy(OwnCardValue).Take(min).ToList(); + if (forced.Count < min) return null; + Log("select hint " + hint + " for " + Name(open.Card) + " (" + model + "): scope enemy, no enemy target, FORCED onto our own " + + string.Join(", ", forced.Select(Name))); + if (Journaling) JournalSelect(hint, forced, open, true); + return forced; + } + var view = BoardView.From(Bot, Enemy, unknownDefense); + var ctx = EffectContextNow(null); + float before = evaluator.Score(EffectSimulator.Baseline(view, ctx)); + float raw = evaluator.Score(view); + var scored = new List<(ClientCard card, float delta)>(); + foreach (var c in cards) + { + if (c == null) continue; + bool ours = c.Controller == 0; + if (enemyPrompt && ours) continue; // never our own when theirs are offered + if (!enemyPrompt && !ours) continue; + // Enemy side: only what stands on their board. Our side (a cost + // or Fusion/Xyz material): the GY, the banished pile and the Deck + // are legal payment too and cost the board nothing — they used to + // be dropped here, which is how Miracle Fusion came to banish our + // own face-up bodies while its GY copies sat unused. + if (enemyPrompt && c.Location != CardLocation.MonsterZone && c.Location != CardLocation.SpellZone && c.Location != CardLocation.Hand) continue; + float delta; + if (enemyPrompt) + { + ctx.Target = c; + delta = evaluator.Score(EffectSimulator.Apply(view, model, Bot, Enemy, ctx)) - before; + } + else + { + // A cost / own-side pick: what the board loses without that card. + delta = evaluator.Score(WithoutOwnCard(view, c)) - raw; + } + // Ties: the heuristics decide (threat lists, priorities). + delta += ours ? -OwnCardValue(c) * 0.001f : EnemyCardValue(c) * 0.001f; + // E4 (2026-08-18): a `keep` id is paid LAST at a cost prompt. + // Big enough to lose to every real candidate, finite so the + // card is still given up when nothing else is legal. + if (KeptCost(hint, c) > 0) delta -= KeepPenalty; + scored.Add((c, delta)); + } + if (scored.Count == 0) return null; + // Pay off the field first: while enough off-field candidates are + // legal, a face-up monster the brain values (priority >= + // FieldMaterialFloor) is not material (Supreme King's Dark Contact + // shuffling a face-up Malicious Bane into the Deck). + if (!enemyPrompt && scored.Count > min && scored.Count(s => !OnOurField(s.card)) >= min) + scored.RemoveAll(s => ExpensiveFieldMaterial(s.card)); + scored.Sort((a, b) => b.delta.CompareTo(a.delta)); + // Enemy side: as many as allowed, but only picks that help (delta > worst + // acceptable = the best one's sign); our side: the minimum. + int take = enemyPrompt ? Math.Max(max, min) : min; + var picked = new List(); + for (int i = 0; i < scored.Count && picked.Count < take; i++) + { + if (enemyPrompt && picked.Count >= min && scored[i].delta < 0f) break; + picked.Add(scored[i].card); + } + if (picked.Count == 0 || picked.Count < min) return null; + selectionWorths = new Dictionary(); + foreach (var (c, d) in scored) selectionWorths[c] = d; + if (open.Target == null || !picked.Contains(open.Target)) open.Target = picked[0]; + Log("select hint " + hint + " for " + Name(open.Card) + " (" + model + "): " + string.Join(", ", picked.Select(c => Name(c) + " " + selectionWorths[c].ToString("0")))); + if (Journaling) JournalSelect(hint, picked, open); + selectionWorths = null; + return picked; + } + + /// E4 (2026-08-18): how far back a `keep` id is pushed at a cost prompt + /// (evaluator points). Larger than any real candidate's worth, so a kept + /// card is paid only when nothing else is legal. + private const float KeepPenalty = 1000000f; + + /// 1 when this card of ours is on the brain's `keep` list AND the prompt + /// is a discard / tribute / release / to-grave / material cost; 0 + /// otherwise. No other scoring path asks — that is the whole point of + /// `keep` existing next to `priorities`. + private int KeptCost(int hint, ClientCard c) + => c != null && c.Controller == 0 && Array.IndexOf(HintsForOwnCost, hint) >= 0 && Rules.IsKept(c.Id) ? 1 : 0; + + /// Gap H: what turning one of OUR monsters around would cost (negative = + /// worse for us). Face-down monsters flip face-up in attack; a face-up + /// one just swaps position. + private float PositionFlipDelta(BoardView board, float baseline, ClientCard c) + { + if (c == null) return float.NegativeInfinity; + int i = board.IndexOfBot(c); + if (i < 0) return 0f; // not a monster of ours on the board: nothing to lose + var flipped = board.Clone(); + var m = flipped.Bot[i]; + if (!m.FaceUp) { m.FaceUp = true; m.AttackPos = true; } + else m.AttackPos = !m.AttackPos; + flipped.Bot[i] = m; + return evaluator.Score(flipped) - baseline; + } + + /// The board with one of our cards gone (a cost about to be paid). + private static BoardView WithoutOwnCard(BoardView view, ClientCard c) + { + var next = view.Clone(); + if (c.Location == CardLocation.MonsterZone) + { + int i = next.IndexOfBot(c); + if (i >= 0) next.Bot.RemoveAt(i); + } + else if (c.Location == CardLocation.SpellZone) + { + next.BotBackrow = Math.Max(0, next.BotBackrow - 1); + if (c.IsFaceup() && c.Id != 0 && c.IsFloodgate()) next.BotFloodgateSpells = Math.Max(0, next.BotFloodgateSpells - 1); + } + else if (c.Location == CardLocation.Hand) + { + next.BotHand = Math.Max(0, next.BotHand - 1); + } + return next; + } + + /// A card of ours the brain values this much is not material while + /// anything else is legal (`priorities` scale: 2 = a real boss). + private const float FieldMaterialFloor = 2f; + + private static bool OnOurField(ClientCard c) + => c != null && c.Controller == 0 && (c.Location == CardLocation.MonsterZone || c.Location == CardLocation.SpellZone); + + /// A face-up monster of ours the brain calls a boss, standing on the + /// field: the most expensive thing we could possibly pay a cost with. + private bool ExpensiveFieldMaterial(ClientCard c) + => c != null && c.Controller == 0 && c.Location == CardLocation.MonsterZone && c.IsFaceup() + && c.IsMonster() && Rules.PriorityOf(c.Id) >= FieldMaterialFloor; + + /// What one of our own cards is worth (higher = keep / prefer to fetch). + private float OwnCardValue(ClientCard c) + { + float v = Rules.PriorityOf(c.Id) * 1000f; + if (c.IsMonster()) + { + v += Math.Max(Atk(c), Def(c)) * 0.5f; + if (c.Location == CardLocation.MonsterZone) v += 200f + BoardEvaluator.ThreatOf(c) * 500f; + if (c.HasType(CardType.Token)) v -= 400f; + } + else + { + v += 300f; + if (c.Location == CardLocation.SpellZone && c.IsFaceup() && (c.HasType(CardType.Continuous) || c.HasType(CardType.Field))) + v += 200f; + } + if (c.Location == CardLocation.Deck) v -= 150f; + if (c.Location == CardLocation.Grave || c.Location == CardLocation.Removed) v -= 500f; + return v; + } + + /// How much we want an enemy card gone. + private static float EnemyCardValue(ClientCard c) + { + float v = 0f; + if (c.Id == 0) return c.Location == CardLocation.MonsterZone ? 700f : 350f; + v += BoardEvaluator.ThreatOf(c) * 3000f; + if (c.IsMonster()) + v += 300f + c.GetDefensePower() * 0.5f; + else if (c.IsFaceup() && (c.HasType(CardType.Continuous) || c.HasType(CardType.Field) || c.HasType(CardType.Equip))) + v += 500f; + else + v += 350f; + if (c.Location == CardLocation.Hand) v = 250f; + return v; + } + + // ===================================================================== + // Helpers + // ===================================================================== + + /// The prompt's full list of this action type when it is still fresh + /// (so the gate can rank the asked card against its rivals), else just + /// the asked card. + private List IdleCandidates(IList source) + { + var list = new List(); + if (source != null && IdleFresh() && source.Contains(Card)) + foreach (var c in source) list.Add(new Candidate { Card = c, Desc = -1 }); + if (list.Count == 0) + list.Add(new Candidate { Card = Card, Desc = -1 }); + return list; + } + + /// True for the first candidate the prompt asks about: "hold" lines are + /// logged once per prompt instead of once per card. + private bool AskedFirst(List candidates) + => candidates.Count > 0 && ReferenceEquals(candidates[0].Card, Card); + + private delegate float Scorer(ref Candidate c); + + private static List Rank(List candidates, Scorer score) + { + var ranked = new List(candidates.Count); + foreach (var c in candidates) + { + var copy = c; + copy.Score = score(ref copy); + ranked.Add(copy); + } + ranked.Sort((a, b) => b.Score.CompareTo(a.Score)); + return ranked; + } + + /// Easy-only gaussian noise, stable per card within a prompt. + private float Noise(ClientCard card) + { + if (noiseSigma <= 0f || card == null) return 0f; + if (!noiseCache.TryGetValue(card, out var n)) + { + double u1 = 1.0 - rng.NextDouble(); + double u2 = rng.NextDouble(); + n = (float)(Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Cos(2.0 * Math.PI * u2)) * noiseSigma; + noiseCache[card] = n; + } + return n; + } + + /// deck brain knob > deck-GROUP base (`Data/Characters/_groups/.json`) + /// > code default. The group base is what an unowned deck plays with. + // ===================================================================== + // TICKET-050 — rollout lookahead for the idle command + // ===================================================================== + + /// + public bool YGOL_WantsPlan() + { + if (Lookahead <= 0 || lookaheadOracle == null || !lookaheadOracle.Available) return false; + // Our Main Phase 1 only: that is where the branching that a rollout + // could possibly resolve lives, and it keeps the cost bounded. + if (Duel == null || Duel.Player != 0 || Duel.Phase != DuelPhase.Main1) return false; + var main = Duel.MainPhase; + if (main == null) return false; + // At least two things to choose between (an action + "go to battle" + // or "end turn" counts). + int actions = main.ActivableCards.Count + main.SummonableCards.Count + main.SpecialSummonableCards.Count + + main.MonsterSetableCards.Count + main.SpellSetableCards.Count + main.ReposableCards.Count; + return actions >= 1 && (actions >= 2 || main.CanBattlePhase || main.CanEndPhase); + } + + /// + public int? YGOL_PlanIdle(MainPhase main, Func, MainPhaseAction> walk) + { + if (!YGOL_WantsPlan() || walk == null) return null; + + // --- 1. the executor's own top-K, in its own order --------------- + var order = new List(); + var veto = new HashSet(); + plannerProbe = true; + try + { + for (int k = 0; k < LookaheadCandidates; k++) + { + // Every probe re-asks the SAME prompt, so the idle lists are + // fresh again (MarkAnswered is a no-op while probing, but a + // gate may have latched before the planner was reached). + idleStale = false; + var act = walk(a => !veto.Contains(a.ToValue())); + if (act == null) break; + int value = act.ToValue(); + // The walk's last-resort answers ignore the veto; that is the + // end of the enumerable list. + if (!veto.Add(value)) break; + order.Add(value); + if (act.Action == MainPhaseAction.MainAction.ToEndPhase) break; + } + } + finally + { + plannerProbe = false; + idleStale = false; + noiseCache.Clear(); + } + if (order.Count < 2) return null; + + // --- 2. score each candidate ------------------------------------ + // The walk yields an ORDER, not a score, so rank k is worth + // (K-1-k) * lookaheadRankPoints; the rollout value is blended on top + // exactly as the ticket specifies. + int budget = LookaheadMs; + var started = DateTime.UtcNow; + int bestIndex = 0; + float bestScore = float.NegativeInfinity; + var trace = Chatty ? new StringBuilder() : null; + for (int k = 0; k < order.Count; k++) + { + float rankScore = (order.Count - 1 - k) * LookaheadRankPoints; + float total = rankScore; + float value = float.NaN; + int left = budget <= 0 ? 0 : budget - (int)(DateTime.UtcNow - started).TotalMilliseconds; + if (budget <= 0 || left > 0) + { + value = lookaheadOracle.Evaluate(order[k], Lookahead, LookaheadTurns, budget <= 0 ? 0 : left); + if (!float.IsNaN(value)) total += LookaheadWeight * (value - 0.5f) * 2000f; + } + trace?.Append(k == 0 ? string.Empty : ", ").Append(IdleActionName(order[k])) + .Append(' ').Append(float.IsNaN(value) ? "-" : value.ToString("0.00")) + .Append('/').Append(total.ToString("0")); + if (total > bestScore) { bestScore = total; bestIndex = k; } + } + if (trace != null) + Log("lookahead: " + trace + " -> " + IdleActionName(order[bestIndex]) + + (lookaheadOracle.LastNote != null ? " (" + lookaheadOracle.LastNote + ")" : string.Empty)); + lookaheadDecisions++; + if (bestIndex != 0) lookaheadOverrides++; + return order[bestIndex]; + } + + /// How often the planner ran, and how often it moved off the executor's + /// own first choice. Logged once per duel (verbose only). + private int lookaheadDecisions, lookaheadOverrides; + + private static string IdleActionName(int value) + { + var action = (MainPhaseAction.MainAction)(value & 0xFFFF); + return action + "#" + ((value >> 16) & 0xFFFF); + } + + private float Knob(string name, float fallback) + { + // TICKET-050: an explicit per-seat override (arena --knobsA/--knobsB) + // beats the brain and the group, so one deck can be measured at two + // settings in the same session without editing brain.json. + if (knobOverrides != null && knobOverrides.TryGetValue(name, out var o)) return o; + if (Config.knobs != null && Config.knobs.TryGetValue(name, out var v)) return v; + if (groupKnobs != null && groupKnobs.TryGetValue(name, out var g)) return g; + return fallback; + } + private readonly IReadOnlyDictionary groupKnobs; + /// Snapshot of taken at construction, so a + /// later seat's overrides cannot leak into this one. + private readonly IReadOnlyDictionary knobOverrides; + + // A Room seat's own values beat the arena's shared ones. + private static IReadOnlyDictionary Merge(IReadOnlyDictionary shared, IReadOnlyDictionary seat) + { + if (seat == null || seat.Count == 0) return shared; + var merged = new Dictionary(); + if (shared != null) foreach (var pair in shared) merged[pair.Key] = pair.Value; + foreach (var pair in seat) merged[pair.Key] = pair.Value; + return merged; + } + + private static DifficultyLevel ParseDifficulty(string s) + { + switch ((s ?? string.Empty).Trim().ToLowerInvariant()) + { + case "easy": return DifficultyLevel.Easy; + case "hard": return DifficultyLevel.Hard; + default: return DifficultyLevel.Normal; + } + } + + /// + /// True when this card's PRINTED ATK is a placeholder rather than a + /// stat, so reading it as a number is a mistake: + /// * -2 — the cdb's encoding of a printed "?" (Chimeratech + /// Overdragon is -2/-2 and lands at 800 x materials, i.e. 1600-8000); + /// * 0/0 on an EXTRA DECK body — the same card printed with a + /// zero instead of a "?" (Chimeratech Fortress Dragon is 0/0 in the + /// cdb and 1000 x materials live). Restricted to Fusion/Synchro/Xyz/ + /// Link so that an honest 0/0 main-deck monster (a Token, a wall) is + /// still read as the 0 it really is. + /// The live number exists only once the core has the monster on a field + /// and has reported it — see . + /// + private static bool VariableAtk(YGOSharp.OCGWrapper.NamedCard data) + { + if (data == null) return false; + if (data.Attack < 0) return true; + if (data.Attack != 0 || data.Defense != 0) return false; + const int extra = (int)CardType.Fusion | (int)CardType.Synchro | (int)CardType.Xyz | (int)CardType.Link; + return (data.Type & (int)CardType.Monster) != 0 && (data.Type & extra) != 0; + } + + private static bool VariableAtk(ClientCard c) + => c != null && (c.Data != null ? VariableAtk(c.Data) : false); + + /// + /// The ATK/DEF the core actually reports for a face-up copy of this card + /// we control, or -1. ClientCard.Attack is filled in by MSG_UPDATE_DATA, + /// so it is the post-material number for a variable-ATK body; it is 0 + /// until the first refresh, which is why only a positive value counts. + /// + private int LiveAtkOf(int cardId, out int liveDef) + { + liveDef = -1; + if (cardId == 0) return -1; + foreach (var c in Bot.GetMonsters()) + { + if (c == null || c.Id != cardId || !c.IsFaceup() || c.Attack <= 0) continue; + liveDef = c.Defense; + return c.Attack; + } + return -1; + } + + private static int Atk(ClientCard c) + => c.Location == CardLocation.MonsterZone || c.Data == null ? c.Attack : c.Data.Attack; + + private static int Def(ClientCard c) + => c.Location == CardLocation.MonsterZone || c.Data == null ? c.Defense : c.Data.Defense; + + private static int Level(ClientCard c) + => c.Level > 0 || c.Data == null ? c.Level : c.Data.Level; + + private static bool PreferAttack(int atk, int def) => atk >= def; + + /// Materials an extra-deck summon probably eats from our field. + private static int EstimateMaterials(ClientCard c) + { + var data = c.Data; + if (c.HasType(CardType.Link) || (data != null && data.HasType(CardType.Link))) + { + int rating = c.LinkCount > 0 ? c.LinkCount : data != null ? data.Level : 2; + return Math.Max(1, rating); + } + if (c.HasType(CardType.Xyz) || (data != null && data.HasType(CardType.Xyz))) return 2; + if (c.HasType(CardType.Synchro) || (data != null && data.HasType(CardType.Synchro))) return 2; + if (c.HasType(CardType.Fusion) || (data != null && data.HasType(CardType.Fusion))) return 2; + if (c.HasType(CardType.Ritual) || (data != null && data.HasType(CardType.Ritual))) return 1; + return 0; + } + + private static string Name(ClientCard c) + => c == null ? "null" : c.Name ?? (c.Id != 0 ? c.Id.ToString() : "?"); + + private bool Chatty => !Muted && (Verbose || verboseKnob); + + private void Log(string message) + { + if (!Chatty) return; + UnityEngine.Debug.Log(LogPrefix + (CharacterId ?? "smart") + " T" + Duel.Turn + " " + Duel.Phase + ": " + message); + } + + private void LogRanked(string head, List ranked) + { + if (!Chatty) return; + var sb = new StringBuilder(head); + sb.Append(" | top:"); + for (int i = 0; i < Math.Min(3, ranked.Count); i++) + { + var c = ranked[i]; + sb.Append(' ').Append(Name(c.Card)); + if (c.Desc > 0) sb.Append('#').Append(c.Desc & 0xf); + sb.Append('=').Append(float.IsNegativeInfinity(c.Score) ? "x" : c.Score.ToString("0")); + if (c.Why != null) sb.Append('(').Append(c.Why).Append(')'); + } + Log(sb.ToString()); + } + + private void LogSelection(int hint, List selected) + { + if (Journaling) JournalSelect(hint, selected); + if (!Chatty) return; + Log("select hint " + hint + ": " + string.Join(", ", selected.Select(Name))); + } + + // ===================================================================== + // Decision journal (TICKET-036) + // ===================================================================== + + // The journal is the blunder detector's input (.claude/skills/bot-brain/ + // blunders.py): one JSON object per line, decisions AND what became of + // them, all from the bot's own public view of the duel. Off unless + // JournalPath was set when this executor was built; every hook checks + // Journaling first so an idle journal costs one bool per event. + // + // Line kinds (all carry the common block: id, duel, turn, phase, + // player, botLp, enemyLp, botHand, botMonsters, enemyMonsters, + // enemyBestAtk, enemyBestPower): + // start deck, character, difficulty, seed, rules — construction (no board yet) + // turn whose (bot|enemy) — OnNewTurn + // summon | set | spsummon — our monster arrives on the field (OnMove); + // card, cardName, position (attack|defense|set), positionWhy (who chose it: + // rule / combo verb / evaluator; null = an effect fixed it), atk, def, level, + // from, score, why, via (gate|combo|effect) + // set (spell/trap) card, cardType — SpellSetGate / combo Set + // activate | chain card, desc, tags[], selfScoped, score, why — a gate/combo chose the + // activation (chain = inside a chain window; selfScoped = the printed text + // can only ever remove OUR cards, so a payment is the card's cost) + // select hint, hintName, cards[{card,name,owner,location}], targetOwner, forCard, + // forCardSelfScoped — our own card selection + // resolved card, targets[], targetOwner, ourLost[], enemyLost[], tags[] — our chain link resolved + // attack card (attacker), atk, target/targetName/targetAtk/targetDef/targetPos (null = direct), + // outcome, expectedAttackerDies/expectedDefenderDies, score (= evaluator delta) + // position card, position, why — special-summon position prompt + // repos card, from, to, why — flip summon / position change we chose + // flipHeld card, cardName, atk, def, why — a Flip Summon we chose NOT to take + // (2026-08-18; deduped per card+turn, the prompt repeats) + // endturn rejected{card,name,score,why}, summonedThisTurn — our End Phase + // destroyed card, owner (bot|enemy), reason (battle|effect|other), by, byName, byOwner, position, to + // (any monster leaving a monster zone, ours or theirs) + // material card, cardName, owner (bot), holder, holderName — one of OUR monsters + // left the monster zone with no move of its own: it became Xyz material + // (see JournalVanished). It did NOT die; the detector must stop reading + // that card id as "the body we summoned" from here on. + // lpDelta botDelta, enemyDelta, inBattle, attacker/attackerName/attackerOwner, defender/defenderName + // duelEnd result (win|lose|draw), field[{card,name,position,atk,setTurn}], backrow[{card,name,faceup,cardType,setTurn}] + + private readonly string journalFile; + private readonly int journalDuel; + private static readonly object journalLock = new object(); + private int journalSeq; + private int journalBotLp = -1, journalEnemyLp = -1; + private DuelPhase journalPhase; + private bool journalSummonedThisTurn; + private bool journalDuelEnded; + + private struct PendingSummon { public string Kind; public int CardId; public float? Score; public string Why; public string Via; } + private PendingSummon? pendingSummon; + /// Why the last summon-or-set / position prompt chose what it chose. + private string pendingPositionWhy; + private Dictionary rejectedSummon; + + private sealed class ActivationTrack + { + public ClientCard Card; + public int ChainIndex; + public readonly List OurLost = new List(); + public readonly List EnemyLost = new List(); + } + private readonly List activationTracks = new List(); + /// Turn on which each of our face-down cards was set (by ClientCard). + private readonly Dictionary setTurns = new Dictionary(); + /// Every card of ours the core ever offered us as an activation this + /// duel (chain windows + the idle/battle activable lists). Stamped on + /// the duelEnd line as `offered`: blunders.py's `held-trap` only counts + /// a trap that was legal to fire at least once, so a trap whose + /// condition the duel never met is not read as a decision of ours. + private readonly HashSet journalOffered = new HashSet(); + + private bool Journaling => journalFile != null && !plannerProbe; + + private void JournalOffered(IList cards) + { + if (cards == null) return; + for (int i = 0; i < cards.Count; i++) + if (cards[i] != null && cards[i].Controller == 0 && cards[i].Id != 0) journalOffered.Add(cards[i].Id); + } + + private void JournalOpen() + { + try + { + var dir = Path.GetDirectoryName(Path.GetFullPath(journalFile)); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + } + catch (Exception e) + { + UnityEngine.Debug.LogWarning(LogPrefix + "journal: cannot create " + journalFile + ": " + e.Message); + } + GameBehavior.YGOL_DuelResult += OnJournalDuelResult; + // The fields are not initialised until the duel starts: the start + // line only carries what the ctor knows. + var line = new Dictionary + { + ["id"] = (CharacterId ?? "smart") + "-" + journalDuel + "-" + (++journalSeq), + ["duel"] = journalDuel, + ["turn"] = 0, + ["phase"] = null, + ["player"] = AI?.Game?.Username ?? CharacterId ?? "smart", + ["kind"] = "start", + ["deck"] = DeckPath, + ["character"] = CharacterId, + ["difficulty"] = Difficulty.ToString(), + ["seed"] = Seed, + ["rules"] = Rules.IsEmpty ? null : Rules.source, + }; + JournalWrite(line); + } + + private void OnJournalDuelResult(string username, int result, int turn) + { + if (!Journaling || journalDuelEnded) return; + var mine = AI?.Game?.Username; + if (mine == null || !string.Equals(mine, username, StringComparison.Ordinal)) return; + journalDuelEnded = true; + GameBehavior.YGOL_DuelResult -= OnJournalDuelResult; + try + { + JournalFlushLp(); + var line = JournalLine("duelEnd"); + line["result"] = result == 0 ? "win" : result == 1 ? "lose" : "draw"; + line["turns"] = turn; + var field = new List(); + foreach (var m in Bot.GetMonsters()) + field.Add(new Dictionary + { + ["card"] = m.Id, ["name"] = m.Name, ["position"] = PositionWord(m.Position), + ["atk"] = JAtk(m), ["setTurn"] = setTurns.TryGetValue(m, out var st) ? st : (object)null, + }); + line["field"] = field; + var backrow = new List(); + foreach (var c in Bot.GetSpells()) + backrow.Add(new Dictionary + { + ["card"] = c.Id, ["name"] = c.Name, ["faceup"] = c.IsFaceup(), ["cardType"] = CardTypeWord(c), + ["setTurn"] = setTurns.TryGetValue(c, out var st2) ? st2 : (object)null, + }); + line["backrow"] = backrow; + line["offered"] = new List(journalOffered); + JournalWrite(line); + } + catch (Exception e) { UnityEngine.Debug.LogWarning(LogPrefix + "journal duelEnd: " + e.Message); } + } + + private Dictionary JournalLine(string kind) + { + var d = new Dictionary + { + ["id"] = (CharacterId ?? "smart") + "-" + journalDuel + "-" + (++journalSeq), + ["duel"] = journalDuel, + ["turn"] = Duel.Turn, + ["phase"] = Duel.Phase.ToString(), + ["player"] = AI?.Game?.Username ?? CharacterId ?? "smart", + ["kind"] = kind, + ["botLp"] = Bot.LifePoints, + ["enemyLp"] = Enemy.LifePoints, + ["botHand"] = Bot.GetHandCount(), + ["botMonsters"] = Bot.GetMonsterCount(), + ["enemyMonsters"] = Enemy.GetMonsterCount(), + ["enemyBestAtk"] = BoardEvaluator.BestEnemyAttack(Enemy), + ["enemyBestPower"] = BoardEvaluator.BestEnemyPower(Enemy), + }; + return d; + } + + private void JournalWrite(Dictionary line) + { + string text; + try { text = JsonConvert.SerializeObject(line, Formatting.None); } + catch (Exception e) { UnityEngine.Debug.LogWarning(LogPrefix + "journal serialize: " + e.Message); return; } + lock (journalLock) + { + try { File.AppendAllText(journalFile, text + "\n"); } + catch (Exception e) { UnityEngine.Debug.LogWarning(LogPrefix + "journal write: " + e.Message); } + } + } + + private static object JScore(float? score) + => score.HasValue && !float.IsInfinity(score.Value) && !float.IsNaN(score.Value) ? (object)(float)Math.Round(score.Value, 1) : null; + + private static int JAtk(ClientCard c) => c == null ? 0 : c.Attack > 0 || c.Data == null ? c.Attack : c.Data.Attack; + private static int JDef(ClientCard c) => c == null ? 0 : c.Defense > 0 || c.Data == null ? c.Defense : c.Data.Defense; + + private static string PositionWord(int position) + { + if ((position & (int)CardPosition.FaceDown) != 0) return "set"; + if ((position & (int)CardPosition.Attack) != 0) return "attack"; + return "defense"; + } + + private static string CardTypeWord(ClientCard c) + => c == null ? null : c.IsTrap() ? "trap" : c.IsSpell() ? "spell" : c.IsMonster() ? "monster" : "other"; + + /// + /// Who does this removal hit? Read from the card text (public info): + /// "…your opponent controls" = enemy-only, "all … on the field" = + /// symmetric, "target 1 … on the field" = either side. Refuse to fire + /// a removal that has no enemy target of the affected kind, or a + /// symmetric one that would cost us as much or more than the enemy + /// (Eradicating Aerosol into an empty board, Giant Trunade on our own + /// backrow). Cards whose text says only "you control" are costs, not + /// removal, and pass. Non-removal cards pass. + /// + private bool RemovalScopeOk(ClientCard card, out string why) + { + why = null; + var text = card?.Data?.Description; + if (string.IsNullOrEmpty(text)) return true; + text = text.ToLowerInvariant(); + bool removal = text.Contains("destroy") || text.Contains("return") || text.Contains("banish"); + if (!removal) return true; + bool enemyScoped = text.Contains("your opponent controls") || text.Contains("opponent's") || text.Contains("they control"); + bool symmetric = !enemyScoped && text.Contains("all ") && text.Contains("on the field"); + bool either = !enemyScoped && !symmetric && text.Contains("on the field"); + if (!enemyScoped && !symmetric && !either) return true; // "you control" / graveyard / hand: a cost, not removal + + bool hitsMonsters = text.Contains("monster"); + bool hitsBackrow = text.Contains("spell") || text.Contains("trap"); + if (!hitsMonsters && !hitsBackrow) hitsMonsters = hitsBackrow = true; + int enemyN = (hitsMonsters ? Enemy.GetMonsterCount() : 0) + (hitsBackrow ? Enemy.GetSpellCount() : 0); + int botN = (hitsMonsters ? Bot.GetMonsterCount() : 0) + (hitsBackrow ? Bot.GetSpellCount() : 0); + // The card itself may sit in our backrow while resolving. + if (hitsBackrow && card.Location == CardLocation.SpellZone && botN > 0) botN--; + + if (enemyN == 0) { why = "removal: no enemy target"; return false; } + if (symmetric && botN >= enemyN) { why = "removal: hits us " + botN + " vs " + enemyN; return false; } + return true; + } + + // A modelled removal that can only ever hit the ENEMY (`scope: enemy`) + // has nothing to do while the enemy side holds no card of the affected + // kind — but refusing to FIRE it is NOT the answer, and was tried and + // dropped here. The activation itself is what such decks want: Flying + // Launcher's detach sheds Xyz material and keeps Number 27 alive whether + // or not the destroy finds a target, and Anna Kaboom's brain-history + // already records (iteration 4) that taking that activation away costs + // more than the self-hits do. Measured with the hold in place, Anna and + // Alister both looked several points worse and both recovered when it + // came out; single arena runs are +-3 points at n=1000, so treat those + // numbers as "no evidence it helps" rather than a precise cost. + // So the executor fires the card as before and defends itself one step + // later, in SimulatedSelection: the effect may fizzle, but it will not + // aim at our own board. See the `forcedSelfPick` branch there. + + /// How far below the enemy's best attacker a body is simply dead on + /// arrival: one monster unit of ATK. Below that line nothing it does — + /// attack, wall, trade — happens; it is a card handed over for nothing. + private const int HopelessBodyMargin = 1000; + + /// + /// A modelled summon whose body cannot survive contact with the + /// board it lands on is held (Evil HERO Infernal Prodigy, 300/600, 29 of + /// Supreme King's 61 suicide-summons: its own text puts it in ATTACK + /// position in front of 2500+ boards). "Cannot survive" = its better + /// stat is below the enemy's best + /// attacker, so neither position saves it. + /// + /// Two carve-outs keep the rule honest: + /// - if the enemy's attackers add up to our LP, a chump block is still + /// right — the body buys the turn that a card in hand cannot; + /// - a body that comes from the DECK or the GY is card advantage from a + /// zone that cost us no hand card, so it is worth having even as a + /// speed bump; only a body we PAY for (hand / field) is held. + /// + /// (Deliberate deviation from the brief that asked for this: it also + /// wanted "and we already control a monster", but Infernal Prodigy may + /// only summon itself while we control NONE, so that clause would make + /// the rule inert exactly where it was asked for. The lethal check + /// covers what it was guarding against — never leaving ourselves open + /// when the open board loses the duel.) + /// + private bool SummonBodyWorthIt(EffectModel m, out string why) + { + why = null; + if (m == null || !m.IsSummon) return true; + if (m.What == EffectWhat.Deck) return true; + int atk = Math.Max(0, m.atk ?? (int)Math.Round(m.amount)); + int def = Math.Max(0, m.def ?? atk); + int body = Math.Max(atk, def); + if (body <= 0) return true; // no stats modelled: nothing to judge + int best = BoardEvaluator.BestEnemyAttack(Enemy); + if (best <= 0 || body > best - HopelessBodyMargin) return true; + if (BoardEvaluator.EnemyAttackTotal(Enemy) >= Bot.LifePoints) return true; // chump-block or die + why = "summon: body " + body + " is hopeless against " + best + " (and we are not facing lethal)"; + return false; + } + + /// Effect-text tags for the analyzer (self-target pattern): which of + /// the removal verbs the card's own text uses. + private static readonly string[] EffectVerbs = { "destroy", "return", "banish", "negate", "discard", "tribute", "shuffle" }; + private static List EffectTags(ClientCard c) + { + var tags = new List(); + var text = c?.Data?.Description; + if (string.IsNullOrEmpty(text)) return tags; + text = text.ToLowerInvariant(); + foreach (var v in EffectVerbs) + if (text.Contains(v)) tags.Add(v); + return tags; + } + + /// + /// The card's own text scopes its removal verbs to OUR side only: + /// "Banish 1 Level 7 monster from your hand or face-up field; draw 2 + /// cards" — nothing here can ever leave the ENEMY's field, so what + /// leaves is the card's printed COST, not a misfired removal. Same + /// reading as : a text that names the + /// opponent's side, or a generic "on the field", is NOT self-scoped. + /// blunders.py's `self-target` skips the cards this flags. + /// + private static bool SelfScopedRemoval(ClientCard card) + { + var text = card?.Data?.Description; + if (string.IsNullOrEmpty(text)) return false; + text = text.ToLowerInvariant(); + bool removal = text.Contains("destroy") || text.Contains("return") || text.Contains("banish"); + if (!removal) return false; + return !text.Contains("your opponent controls") && !text.Contains("opponent's") + && !text.Contains("they control") && !text.Contains("on the field"); + } + + private static string OwnerWord(int controller) => controller == 0 ? "bot" : "enemy"; + + private static Dictionary CardRef(ClientCard c) + => new Dictionary + { + ["card"] = c?.Id ?? 0, ["name"] = c?.Name, ["owner"] = c == null ? null : OwnerWord(c.Controller), + ["location"] = c?.Location.ToString(), + ["position"] = c == null || c.Location != CardLocation.MonsterZone ? null + : c.IsFacedown() ? "set" : c.IsAttack() ? "attack" : "defense", + ["atk"] = c == null || c.Location != CardLocation.MonsterZone || c.IsFacedown() ? (int?)null : c.Attack, + }; + + // ---- decision hooks --------------------------------------------------- + + private void JournalTurn() + { + JournalFlushLp(); + journalSummonedThisTurn = false; + rejectedSummon = null; + pendingSummon = null; + var line = JournalLine("turn"); + line["whose"] = Duel.Player == 0 ? "bot" : "enemy"; + // TICKET-042 proof: at insight >= hand, the enemy's real hand ids. + if (Insight.Level >= InsightLevel.Hand && Insight.Available) + line["enemyHandKnown"] = Insight.Hand; + JournalWrite(line); + } + + private void JournalPhase() + { + var previous = journalPhase; + journalPhase = Duel.Phase; + JournalFlushLp(previous); + if (Duel.Phase == DuelPhase.End && Duel.Player == 0) + { + var line = JournalLine("endturn"); + line["rejected"] = rejectedSummon; + line["summonedThisTurn"] = journalSummonedThisTurn; + JournalWrite(line); + } + } + + private void JournalRejectedSummon(Candidate best) + { + if (best.Card == null) return; + rejectedSummon = new Dictionary + { + ["card"] = best.Card.Id, ["name"] = best.Card.Name, ["score"] = JScore(best.Score), ["why"] = best.Why, + ["atk"] = JAtk(best.Card), ["def"] = JDef(best.Card), + }; + } + + private void JournalPendingSummon(string kind, ClientCard card, float? score, string why) + { + if (card == null) return; + pendingSummon = new PendingSummon { Kind = kind, CardId = card.Id, Score = score, Why = why, Via = score.HasValue ? "gate" : "combo" }; + } + + /// Spell/trap set (monster sets are journaled when the card lands, see JournalMove). + private void JournalSet(ClientCard card, float? score, string why) + { + if (card == null) return; + var line = JournalLine("set"); + line["card"] = card.Id; + line["cardName"] = card.Name; + line["cardType"] = CardTypeWord(card); + line["score"] = JScore(score); + line["why"] = why; + JournalWrite(line); + } + + private void JournalActivate(ClientCard card, int desc, float? score, string why, EffectPlan plan = null) + { + if (card == null) return; + var line = JournalLine(CurrentTiming >= 0 ? "chain" : "activate"); + line["card"] = card.Id; + line["cardName"] = card.Name; + line["cardType"] = CardTypeWord(card); + line["desc"] = desc; + line["location"] = card.Location.ToString(); + line["tags"] = EffectTags(card); + // TICKET-036: the card's own text only ever removes OUR cards, so the + // payment is its printed cost (blunders.py `self-target` skips it). + line["selfScoped"] = SelfScopedRemoval(card); + line["score"] = JScore(score); + line["why"] = why; + // TICKET-040: effect model fields (modelled = the delta path scored it). + var model = plan?.Model ?? Rules.EffectFor(card.Id, desc); + line["modelled"] = model != null; + line["effect"] = model?.ToString(); + line["effectKind"] = model?.Kind.ToString().ToLowerInvariant(); + line["effectDelta"] = plan == null ? null : JScore(plan.Delta); + line["effectTarget"] = plan?.Target == null ? null : CardRef(plan.Target); + line["effectTargetWorth"] = plan == null || plan.Target == null ? null : JScore(plan.BestTargetWorth); + line["effectCandidates"] = plan?.Candidates; + JournalWrite(line); + } + + private void JournalRepos(ClientCard card, string why) + { + if (card == null) return; + var line = JournalLine("repos"); + line["card"] = card.Id; + line["cardName"] = card.Name; + line["from"] = PositionWord(card.Position); + line["to"] = card.IsFacedown() ? "attack" : card.IsAttack() ? "defense" : "attack"; + line["why"] = why; + JournalWrite(line); + } + + /// FLIP monsters (2026-08-18): a Flip Summon we chose NOT to take. The Repos prompt is + /// re-asked for the same card many times in one turn, so this is + /// deduped per (card, turn) — one line per decision, not per prompt. + private void JournalFlipHeld(ClientCard card, string why) + { + if (card == null) return; + long key = (long)card.Id * 10000 + Duel.Turn; + if (!flipHeldLogged.Add(key)) return; + var line = JournalLine("flipHeld"); + line["card"] = card.Id; + line["cardName"] = card.Name; + line["atk"] = JAtk(card); + line["def"] = JDef(card); + line["why"] = why; + JournalWrite(line); + } + + private readonly HashSet flipHeldLogged = new HashSet(); + + private CardPosition JournalPosition(int cardId, CardPosition pos, string why) + { + if (!Journaling) return pos; + pendingPositionWhy = why; + var line = JournalLine("position"); + line["card"] = cardId; + line["cardName"] = YGOSharp.OCGWrapper.NamedCard.Get(cardId)?.Name; + line["position"] = PositionWord((int)pos); + line["why"] = why; + JournalWrite(line); + return pos; + } + + private void JournalAttack(AttackPlan plan) + { + if (plan?.Attacker == null) return; + JournalFlushLp(); + var line = JournalLine("attack"); + line["card"] = plan.Attacker.Id; + line["cardName"] = plan.Attacker.Name; + line["atk"] = JAtk(plan.Attacker); + line["target"] = plan.Defender?.Id; + line["targetName"] = plan.Defender?.Name; + line["targetOwner"] = plan.Defender == null ? null : "enemy"; + line["targetAtk"] = plan.Defender == null ? (object)null : JAtk(plan.Defender); + line["targetDef"] = plan.Defender == null ? (object)null : JDef(plan.Defender); + line["targetPos"] = plan.Defender == null ? null : PositionWord(plan.Defender.Position); + line["outcome"] = plan.Outcome.ToString(); + line["expectedAttackerDies"] = plan.Outcome.AttackerDies; + line["expectedDefenderDies"] = plan.Outcome.DefenderDies; + line["score"] = JScore(plan.Delta); + JournalWrite(line); + } + + private void JournalSelect(int hint, List selected, EffectPlan plan = null, bool forcedSelfPick = false) + { + if (selected == null || selected.Count == 0) return; + var line = JournalLine("select"); + line["hint"] = hint; + line["hintName"] = HintWord(hint); + var cards = new List(); + bool anyBot = false, anyEnemy = false; + foreach (var c in selected) + { + var r = CardRef(c); + if (selectionWorths != null && selectionWorths.TryGetValue(c, out var w)) r["worth"] = JScore(w); + cards.Add(r); + if (c.Controller == 0) anyBot = true; else anyEnemy = true; + } + line["cards"] = cards; + line["targetOwner"] = anyBot && anyEnemy ? "both" : anyBot ? "bot" : "enemy"; + var open = activationTracks.Count > 0 ? activationTracks[activationTracks.Count - 1] : null; + var forCard = plan?.Card ?? open?.Card; + line["forCard"] = forCard?.Id; + line["forCardName"] = forCard?.Name; + line["forCardSelfScoped"] = forCard != null && SelfScopedRemoval(forCard); + // A scope-enemy removal the core would not let us decline: our own + // card was the only legal pick (blunders.py `self-target` skips it). + line["forcedSelfPick"] = forcedSelfPick ? (object)true : null; + // TICKET-040: which effect model drove the pick and what every legal + // candidate was worth (wasted-removal reads these). + line["modelled"] = plan != null; + line["effect"] = plan?.Model?.ToString(); + line["effectKind"] = plan?.Model?.Kind.ToString().ToLowerInvariant(); + line["singleRemoval"] = plan?.Model?.IsSingleRemoval; + // Boost carrier verdict (blunders.py `boost-on-weakling` reads it): + // strong = at/above boostMinAtk; wins-fight = weaker but the boost + // beats an enemy monster; self = a monster equipping itself (Cocoon + // of Evolution: a mechanic, not a choice); forced = a weak carrier + // the pool left us no way around. + bool boostPick = hint == (int)HintMsg.Equip || plan?.Model?.Kind == EffectKind.Boost; + if (boostPick && selected.Count == 1 && selected[0].Controller == 0 && selected[0].Location == CardLocation.MonsterZone) + { + var carrier = selected[0]; + int amount = plan?.Model != null ? (int)plan.Model.amount : UnknownBoostAmount; + int value = BoostValue(carrier, amount); + line["boostCarrier"] = forCard != null && forCard.HasType(CardType.Monster) ? "self" + : value >= 2 ? "wins-fight" : value == 1 ? "strong" : "forced"; + } + if (selectionWorths != null) + { + var candidates = new List(); + foreach (var kv in selectionWorths) + { + var r = CardRef(kv.Key); + r["worth"] = JScore(kv.Value); + r["picked"] = selected.Contains(kv.Key); + candidates.Add(r); + } + line["candidates"] = candidates; + } + JournalWrite(line); + } + + private static string HintWord(int hint) + { + if (hint == HintMsg.Destroy) return "destroy"; + if (hint == HintMsg.Remove) return "banish"; + if (hint == HintMsg.ReturnToHand) return "return"; + if (hint == HintMsg.ToDeck) return "toDeck"; + if (hint == HintMsg.ToGrave) return "toGrave"; + if (hint == HintMsg.Release) return "release"; + if (hint == HintMsg.Discard) return "discard"; + if (hint == HintMsg.Disable) return "negate"; + if (hint == HintMsg.SpSummon) return "spsummon"; + if (hint == HintMsg.AddToHand) return "addToHand"; + if (hint == HintMsg.Tribute) return "tribute"; + if (hint == HintMsg.Equip) return "equip"; + return hint.ToString(); + } + + // ---- outcome hooks ----------------------------------------------------- + + private void JournalChaining(int player, ClientCard card) + { + JournalFlushLp(); + if (player != 0 || card == null) return; + // GameBehavior adds the card to CurrentChain right after this hook. + activationTracks.Add(new ActivationTrack { Card = card, ChainIndex = Duel.CurrentChain.Count + 1 }); + } + + private void JournalChainSolved(int chainIndex) + { + JournalFlushLp(); + for (int i = activationTracks.Count - 1; i >= 0; i--) + { + var t = activationTracks[i]; + if (t.ChainIndex != chainIndex) continue; + activationTracks.RemoveAt(i); + var line = JournalLine("resolved"); + line["card"] = t.Card.Id; + line["cardName"] = t.Card.Name; + line["cardType"] = CardTypeWord(t.Card); + line["tags"] = EffectTags(t.Card); + var targets = new List(); + bool anyBot = false, anyEnemy = false; + foreach (var c in Duel.LastChainTargets) + { + if (c == null || ReferenceEquals(c, t.Card)) continue; + targets.Add(CardRef(c)); + if (c.Controller == 0) anyBot = true; else anyEnemy = true; + } + line["targets"] = targets; + line["targetOwner"] = anyBot && anyEnemy ? "both" : anyBot ? "bot" : anyEnemy ? "enemy" : null; + line["ourLost"] = t.OurLost; + line["enemyLost"] = t.EnemyLost; + JournalWrite(line); + return; + } + } + + private void JournalChainEnd() + { + JournalFlushLp(); + activationTracks.Clear(); + } + + /// + /// Our monster zone as of the previous move, so a monster that leaves it + /// WITHOUT a move of its own can be spotted — see + /// . + /// + private readonly List journalOurMonsters = new List(); + + /// + /// An Xyz Summon does not move its materials anywhere the bot can see: + /// ygopro sends one MSG_MOVE per material whose destination is the + /// OVERLAY of the new monster, and WindBot's OnMove hands the AI the + /// Xyz monster (the holder) — the material is simply gone from the + /// monster zone with no event naming it. Diff our zone against the + /// previous move to name it, and journal it as `material`. Everything + /// else that leaves the field (Fusion/Synchro material to the GY, a + /// tribute, a battle) has a move of its own and is journalled as + /// `destroyed`; blunders.py needs the difference, because a body that + /// became material did not die (Kite Tenjo: the suicide-summon pattern + /// matches on CARD ID, so a Photon Vanisher that was Xyz'd away was + /// being blamed for the next copy's death). + /// + private void JournalVanished(ClientCard movedCard) + { + for (int i = 0; i < journalOurMonsters.Count; i++) + { + var gone = journalOurMonsters[i]; + // NB the material's own ClientCard still SAYS MonsterZone — the + // overlay branch of GameBehavior.OnMove reassigns `card` to the + // holder before AddCard, so nothing ever rewrites it. The zone + // itself is the only truth here. + if (gone == null || ReferenceEquals(gone, movedCard)) continue; + bool stillThere = false; + foreach (var m in Bot.GetMonsters()) + if (ReferenceEquals(m, gone)) { stillThere = true; break; } + if (stillThere) continue; + setTurns.Remove(gone); + var line = JournalLine("material"); + line["card"] = gone.Id; + line["cardName"] = gone.Name; + line["owner"] = "bot"; + line["holder"] = movedCard?.Id; + line["holderName"] = movedCard?.Name; + JournalWrite(line); + } + journalOurMonsters.Clear(); + foreach (var m in Bot.GetMonsters()) + if (m != null) journalOurMonsters.Add(m); + } + + private void JournalMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + JournalFlushLp(); + JournalVanished(card); + const int field = (int)CardLocation.MonsterZone | (int)CardLocation.SpellZone; + bool wasOnField = (previousLocation & field) != 0; + bool isOnField = (currentLocation & field) != 0; + + // Our monster arrives: the summon/set/spsummon decision line. + if (card != null && currentControler == 0 && (currentLocation & (int)CardLocation.MonsterZone) != 0 + && (previousLocation & (int)CardLocation.MonsterZone) == 0) + { + var pending = pendingSummon; + bool planned = pending.HasValue && pending.Value.CardId == card.Id; + if (planned) pendingSummon = null; + bool faceDown = card.IsFacedown(); + string kind = planned ? pending.Value.Kind : "spsummon"; + if (kind == "summon" && faceDown) kind = "set"; + if (kind == "set" && !faceDown) kind = "summon"; + if (faceDown) setTurns[card] = Duel.Turn; + journalSummonedThisTurn = true; + var line = JournalLine(kind); + line["card"] = card.Id; + line["cardName"] = card.Name; + line["position"] = PositionWord(card.Position); + // A card that just arrived has no ATK from the core yet + // (MSG_UPDATE_DATA follows MSG_MOVE), so JAtk falls back to the + // printed value. For a variable-ATK body that value is a + // placeholder, not a stat: use a live copy of ours if the core + // reported one, and otherwise say so, because a "0 ATK" that is + // really 1000 x materials is a blunder the detector would + // invent (Zane: 111 Chimeratech Fortress Dragons journalled at + // atk 0 that attacked for 2000-4000). + int summonAtk = JAtk(card), summonDef = JDef(card); + bool atkKnown = true; + if (card.Attack <= 0 && VariableAtk(card)) + { + int live = LiveAtkOf(card.Id, out var liveDef); + if (live > 0) { summonAtk = live; summonDef = Math.Max(0, liveDef); } + else atkKnown = false; + } + line["atk"] = summonAtk; + line["def"] = summonDef; + if (!atkKnown) line["atkKnown"] = false; + line["level"] = Level(card); + line["from"] = ((CardLocation)previousLocation).ToString(); + line["score"] = planned ? JScore(pending.Value.Score) : null; + line["why"] = planned ? pending.Value.Why : "not chosen by a gate (effect / WindBot default)"; + line["via"] = planned ? pending.Value.Via : "effect"; + line["positionWhy"] = pendingPositionWhy; + pendingPositionWhy = null; + JournalWrite(line); + return; + } + if (card != null && currentControler == 0 && (currentLocation & (int)CardLocation.SpellZone) != 0 && card.IsFacedown()) + setTurns[card] = Duel.Turn; + + // Something leaves the field: destroyed / lost lines. + if (card == null || !wasOnField || isOnField) return; + setTurns.Remove(card); + var open = activationTracks.Count > 0 ? activationTracks[activationTracks.Count - 1] : null; + if (open != null && !ReferenceEquals(open.Card, card)) + (previousControler == 0 ? open.OurLost : open.EnemyLost).Add(new Dictionary + { + ["card"] = card.Id, ["name"] = card.Name, ["cardType"] = CardTypeWord(card), ["to"] = ((CardLocation)currentLocation).ToString(), + }); + if ((previousLocation & (int)CardLocation.MonsterZone) == 0) return; + + var d = JournalLine("destroyed"); + d["card"] = card.Id; + d["cardName"] = card.Name; + d["owner"] = OwnerWord(previousControler); + d["position"] = PositionWord(card.Position); + d["to"] = ((CardLocation)currentLocation).ToString(); + var ownField = previousControler == 0 ? Bot : Enemy; + var otherField = previousControler == 0 ? Enemy : Bot; + // A chain being solved wins over "it was in a battle": a flip effect + // in the damage step is an effect kill, not a battle one. + if (Duel.CurrentChain.Count > 0) + { + var link = Duel.SolvingChainIndex > 0 && Duel.SolvingChainIndex <= Duel.CurrentChain.Count + ? Duel.CurrentChain[Duel.SolvingChainIndex - 1] : Duel.CurrentChain[Duel.CurrentChain.Count - 1]; + d["reason"] = "effect"; + d["by"] = link?.Id; + d["byName"] = link?.Name; + d["byOwner"] = link == null ? null : OwnerWord(link.Controller); + } + else if (ReferenceEquals(ownField.BattlingMonster, card) && otherField.BattlingMonster != null) + { + d["reason"] = "battle"; + d["by"] = otherField.BattlingMonster.Id; + d["byName"] = otherField.BattlingMonster.Name; + d["byOwner"] = OwnerWord(1 - previousControler); + } + else + { + d["reason"] = "other"; + d["by"] = null; + d["byName"] = null; + d["byOwner"] = null; + } + JournalWrite(d); + } + + /// LP changes reach the executor only through the field's LifePoints; + /// compare on every hook and write one lpDelta per observed change. + private void JournalFlushLp() => JournalFlushLp(Duel.Phase); + + private void JournalFlushLp(DuelPhase phaseHint) + { + int bot = Bot.LifePoints, enemy = Enemy.LifePoints; + if (journalBotLp < 0 && journalEnemyLp < 0) { journalBotLp = bot; journalEnemyLp = enemy; return; } + if (bot == journalBotLp && enemy == journalEnemyLp) return; + var line = JournalLine("lpDelta"); + line["phase"] = phaseHint.ToString(); + line["botDelta"] = bot - journalBotLp; + line["enemyDelta"] = enemy - journalEnemyLp; + journalBotLp = bot; + journalEnemyLp = enemy; + var turnField = Duel.Player == 0 ? Bot : Enemy; + var otherField = Duel.Player == 0 ? Enemy : Bot; + bool inBattle = turnField.BattlingMonster != null; + line["inBattle"] = inBattle; + line["attacker"] = inBattle ? turnField.BattlingMonster.Id : (object)null; + line["attackerName"] = inBattle ? turnField.BattlingMonster.Name : null; + line["attackerOwner"] = inBattle ? OwnerWord(Duel.Player) : null; + line["defender"] = inBattle && otherField.BattlingMonster != null ? otherField.BattlingMonster.Id : (object)null; + line["defenderName"] = inBattle && otherField.BattlingMonster != null ? otherField.BattlingMonster.Name : null; + JournalWrite(line); + } + } +} diff --git a/src/YGOLegacy.Bots/Characters/Character.cs b/src/YGOLegacy.Bots/Characters/Character.cs new file mode 100644 index 0000000..3584026 --- /dev/null +++ b/src/YGOLegacy.Bots/Characters/Character.cs @@ -0,0 +1,286 @@ +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace YGOLegacy.Characters +{ + /// + /// 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 + /// Data/Characters/<id>/character.json 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. + /// + 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:<key>" + /// 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/` 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(); + /// 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; + /// + /// 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 + /// Tools/CharacterVoice/map_voice_ids.py, 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 + /// alone, and is silent if it has none. + /// + [JsonProperty("voiceId")] + [JsonConverter(typeof(StringOrArrayConverter))] + public string[] voiceIds = System.Array.Empty(); + + /// + /// 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. + /// + [JsonIgnore] + public int[] VoiceNumbers + { + get + { + if (voiceNumbers != null) + return voiceNumbers; + var numbers = new List(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 lines = new(); + /// Optional voice clips (relative paths), same keys as `lines`. + public Dictionary voice = new(); + + /// Folder the file was read from (`Data/Characters/`, 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; + } + } + + /// + /// 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. + /// + public class StringOrArrayConverter : JsonConverter + { + 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(); + case JsonToken.String: + return new[] { (string)reader.Value }; + case JsonToken.StartArray: + return Newtonsoft.Json.Linq.JArray.Load(reader).ToObject(serializer) + ?? System.Array.Empty(); + 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(); + } + } + + /// + /// 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. + /// + [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(); + + // 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 + { + 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("path"), + brain = hasBrain ? brainToken.ToObject(serializer) : null, + rulesets = hasRulesets + ? rulesetsToken.ToObject(serializer) ?? System.Array.Empty() + : System.Array.Empty(), + }; + 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(); + } + } + + /// + /// 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. + /// + public class BrainConfig + { + public string executor = "Lucky"; + public string difficulty; + public Dictionary 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; + } +} diff --git a/src/YGOLegacy.Bots/Characters/CharacterRegistry.cs b/src/YGOLegacy.Bots/Characters/CharacterRegistry.cs new file mode 100644 index 0000000..594887e --- /dev/null +++ b/src/YGOLegacy.Bots/Characters/CharacterRegistry.cs @@ -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 +{ + /// + /// Every character on disk, read once at boot from + /// Data/Characters/*/character.json. Folders whose name starts with + /// "_" are templates and skipped. A file that fails to parse is logged as + /// [YGOL characters] <path>: <error> 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 — the + /// same scan + publish, synchronous — is the entry point. Both paths share + /// Scan/Publish, so the two never drift. + /// + public static class CharacterRegistry + { + public const string Root = "Data/Characters"; + public const string FileName = "character.json"; + + private static readonly List all = new(); + private static readonly Dictionary byId = + new(StringComparer.OrdinalIgnoreCase); + private static readonly Dictionary 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 All() => all; + + public static Character ById(string id) + => !string.IsNullOrEmpty(id) && byId.TryGetValue(id, out var c) ? c : null; + + /// + /// 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. + /// + 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 artCache = + new(StringComparer.OrdinalIgnoreCase); + + private static bool ArtExists(Character c, string reference) + { + if (string.IsNullOrEmpty(reference)) + return false; + // "addressable:" 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 + /// + /// 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. + /// + public static async UniTask Init() + { + loadedSource ??= new UniTaskCompletionSource(); + List found; + List problems; + try + { + (found, problems) = await UniTask.RunOnThreadPool(() => Scan(Root)); + } + catch (Exception e) + { + found = new List(); + problems = new List { Root + ": " + e.Message }; + } + + await UniTask.SwitchToMainThread(); + Publish(found, problems); + loadedSource.TrySetResult(); + } +#endif + + /// + /// Synchronous scan + publish on the calling thread, for hosts without + /// a player loop (Tools/BotArena). `charactersRoot` defaults to + /// relative to the current directory; pass an + /// absolute path to read another game root. Safe to call again. + /// + /// The root the last scan used (so reads the + /// same tree, whether Unity or the standalone arena did the loading). + public static string LoadedRoot { get; private set; } = Root; + + /// + /// Deck-GROUP base knobs: <root>/_groups/<Group>.json + /// ({ "knobs": { ... } }). 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. + /// + public static IReadOnlyDictionary 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(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> groupKnobs = + new(StringComparer.OrdinalIgnoreCase); + private static readonly IReadOnlyDictionary Empty = new Dictionary(); + + private class GroupBase + { + public Dictionary knobs; + } + + public static void LoadFromDisk(string charactersRoot = null) + { + var root = string.IsNullOrEmpty(charactersRoot) ? Root : charactersRoot; + LoadedRoot = root; + lock (groupKnobs) groupKnobs.Clear(); + List found; + List problems; + try + { + (found, problems) = Scan(root); + } + catch (Exception e) + { + found = new List(); + problems = new List { 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 found, List 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, List) Scan(string root) + { + var found = new List(); + var problems = new List(); + 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(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(); + 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(); + c.lines ??= new Dictionary(); + c.voice ??= new Dictionary(); + c.directory = dir.Replace('\\', '/'); + found.Add(c); + } + catch (Exception e) + { + problems.Add(path + ": " + e.Message); + } + } + return (found, problems); + } + } +} diff --git a/src/YGOLegacy.Bots/Services/BotRoster.cs b/src/YGOLegacy.Bots/Services/BotRoster.cs new file mode 100644 index 0000000..f335101 --- /dev/null +++ b/src/YGOLegacy.Bots/Services/BotRoster.cs @@ -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; + + /// + /// 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. + /// + 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; + } + + /// + /// 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. + /// + 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 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 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("(? + /// 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. + /// + 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 ForRuleset(string rulesetId) + { + var bots = new List(); + 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 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="" Deck=`. + 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; + + /// : 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; + } + + /// + /// 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. + /// + // 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 BrainValues(string deckPath) + { + var values = new Dictionary(); + 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; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Config.cs b/src/YGOLegacy.Bots/WindBot/Config.cs new file mode 100644 index 0000000..3587bde --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Config.cs @@ -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 _fields; + private static Dictionary _integerCache; + private static Dictionary _booleanCache; + + public static void Load(string[] args) + { + _integerCache = new Dictionary(); + _booleanCache = new Dictionary(); + + _fields = LoadArgs(args); + + string filename = GetString(CONFIG_FILE_OPTION); + if (filename != null) + { + Dictionary fileFields = LoadFile(filename); + foreach (var pair in fileFields) + { + if (!_fields.ContainsKey(pair.Key)) + _fields.Add(pair.Key, pair.Value); + } + } + } + + private static Dictionary LoadArgs(string[] args) + { + Dictionary fields = new Dictionary(); + 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 LoadFile(string filename) + { + Dictionary fields = new Dictionary(); + 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; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/AIUtil.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/AIUtil.cs new file mode 100644 index 0000000..ce1a9cf --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/AIUtil.cs @@ -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]; + } + + /// + /// Get the total ATK Monster of the player. + /// + public int GetTotalAttackingMonsterAttack(int player) + { + return Duel.Fields[player].GetMonsters().Where(m => m.IsAttack()).Sum(m => (int?)m.Attack) ?? 0; + } + /// + /// Get the best ATK or DEF power of the field. + /// + /// Bot or Enemy. + /// Only calculate attack. + 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 monsters = Enemy.MonsterZone.GetMonsters(); + return monsters.Count > 0 && monsters + .All(card => card.GetDefensePower() > value && (!onlyATK || card.IsAttack())); + } + + /// + /// Deprecated, use IsOneEnemyBetter and IsAllEnemyBetter instead. + /// + public bool IsEnemyBetter(bool onlyATK, bool all) + { + if (all) + return IsAllEnemyBetter(onlyATK); + else + return IsOneEnemyBetter(onlyATK); + } + + /// + /// Is there an enemy monster who has better power than the best power of the bot's? + /// + /// Only calculate attack. + public bool IsOneEnemyBetter(bool onlyATK = false) + { + int bestBotPower = GetBestPower(Bot, onlyATK); + return IsOneEnemyBetterThanValue(bestBotPower, onlyATK); + } + + /// + /// Do all enemy monsters have better power than the best power of the bot's? + /// + /// Only calculate attack. + 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 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 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()); + } + + 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(); + } + + /// + /// Select cards listed in preferred. + /// + public IList SelectPreferredCards(ClientCard preferred, IList cards, int min, int max) + { + IList selected = new List(); + if (cards.IndexOf(preferred) > 0 && selected.Count < max) + { + selected.Add(preferred); + } + + return selected; + } + + /// + /// Select cards listed in preferred. + /// + public IList SelectPreferredCards(int preferred, IList cards, int min, int max) + { + IList selected = new List(); + foreach (ClientCard card in cards) + { + if (card.IsCode(preferred) && selected.Count < max) + selected.Add(card); + } + + return selected; + } + + /// + /// Select cards listed in preferred. + /// + public IList SelectPreferredCards(IList preferred, IList cards, int min, int max) + { + IList selected = new List(); + IList 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; + } + + /// + /// Select cards listed in preferred. + /// + public IList SelectPreferredCards(IList preferred, IList cards, int min, int max) + { + IList selected = new List(); + 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; + } + + /// + /// Check and fix selected to make sure it meet the count requirement. + /// + public IList CheckSelectCount(IList _selected, IList 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; + } + + /// + /// Get all xyz materials lists that xyz monster required level in the 'pre_materials' list + /// + /// Original materials + /// Xyz monster required level + /// SpSummon rule:number of xyz materials + /// More xyz materials + /// Filter xyz materials func + /// + public List> GetXyzMaterials(IList param_pre_materials, int level, int material_count, bool material_count_above = false, Func material_func = null) + { + List> result = new List>(); + List 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 default_func = card => true; + material_func = material_func ?? default_func; + for (int i = 1; i < Math.Pow(2, pre_materials.Count); i++) + { + List temp_materials = new List(); + 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; + } + + /// + /// Get all synchro materials lists that synchro monster level == param 'level' in the 'pre_materials' list + /// + /// Original materials + /// Synchro monster level + /// SpSummon rule:number of tuner monsters + /// SpSummon rule:number of non-tuner monsters count + /// More tuner monsters + /// More non-tuner monsters + /// Filter tuner monsters func + /// Filter non-tuner monsters func + /// + public List> GetSynchroMaterials(IList param_pre_materials, int level, int tuner_count, int n_tuner_count, bool tuner_count_above = false, bool n_tuner_count_above = true, Func tuner_func = null, Func n_tuner_func = null) + { + List> t_result = new List>(); + List 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 default_func = card => true; + tuner_func = tuner_func ?? default_func; + n_tuner_func = n_tuner_func ?? default_func; + pre_materials.Sort(CardContainer.CompareCardLevel); + Stack materials_stack = new Stack(); + 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 { 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 temp_materials = (List)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(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> result = new List>(); + for (int i = 0; i < t_result.Count; i++) + { + List materials = t_result[i]; + List tuner_materials = new List(); + List n_tuner_materials = new List(); + 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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/CardContainer.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/CardContainer.cs new file mode 100644 index 0000000..a187b4b --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/CardContainer.cs @@ -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 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 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 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 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 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 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 cards, int id) + { + return cards.Where(card => card?.Data != null).Any(card => card.IsCode(id)); + } + + public static int GetCardCount(this IEnumerable cards, int id) + { + return cards.Where(card => card?.Data != null).Count(card => card.IsCode(id)); + } + + public static List GetMonsters(this IEnumerable cards) + { + return cards.Where(card => card?.Data != null && card.HasType(CardType.Monster)).ToList(); + } + + public static List GetFaceupPendulumMonsters(this IEnumerable 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 cards, bool canBeTarget = false) + { + return cards.FirstOrDefault(card => card?.Data != null && card.IsMonsterInvincible() && card.IsFaceup() && (!canBeTarget || !card.IsShouldNotBeTarget())); + } + + public static ClientCard GetDangerousMonster(this IEnumerable cards, bool canBeTarget = false) + { + return cards.FirstOrDefault(card => card?.Data != null && card.IsMonsterDangerous() && card.IsFaceup() && (!canBeTarget || !card.IsShouldNotBeTarget())); + } + + public static ClientCard GetFloodgate(this IEnumerable cards, bool canBeTarget = false) + { + return cards.FirstOrDefault(card => card?.Data != null && card.IsFloodgate() && card.IsFaceup() && (!canBeTarget || !card.IsShouldNotBeTarget())); + } + + public static ClientCard GetFirstMatchingCard(this IEnumerable cards, Func filter) + { + return cards.FirstOrDefault(card => card?.Data != null && filter.Invoke(card)); + } + + public static ClientCard GetFirstMatchingFaceupCard(this IEnumerable cards, Func filter) + { + return cards.FirstOrDefault(card => card?.Data != null && card.IsFaceup() && filter.Invoke(card)); + } + + public static IList GetMatchingCards(this IEnumerable cards, Func filter) + { + return cards.Where(card => card?.Data != null && filter.Invoke(card)).ToList(); + } + + public static int GetMatchingCardsCount(this IEnumerable cards, Func filter) + { + return cards.Count(card => card?.Data != null && filter.Invoke(card)); + } + + public static bool IsExistingMatchingCard(this IEnumerable cards, Func filter, int count = 1) + { + return cards.GetMatchingCardsCount(filter) >= count; + } + + public static ClientCard GetShouldBeDisabledBeforeItUseEffectMonster(this IEnumerable cards, bool canBeTarget = true) + { + return cards.FirstOrDefault(card => card?.Data != null && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && (!canBeTarget || !card.IsShouldNotBeTarget())); + } + + public static IEnumerable> GetCombinations(this IEnumerable 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))); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/CardExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/CardExecutor.cs new file mode 100644 index 0000000..d5ec43d --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/CardExecutor.cs @@ -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 Func { get; private set; } + + public CardExecutor(ExecutorType type, int cardId, Func func) + { + CardId = cardId; + Type = type; + Func = func; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/CardExtension.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/CardExtension.cs new file mode 100644 index 0000000..a6c3ed2 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/CardExtension.cs @@ -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 + { + /// + /// Is this monster is invincible to battle? + /// + 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)); + } + + /// + /// Is this monster is dangerous to attack? + /// + 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))); + } + + /// + /// Do this monster prevents activation of opponent's effect monsters in battle? + /// + public static bool IsMonsterHasPreventActivationEffectInBattle(this ClientCard card) + { + return !card.IsDisabled() && Enum.IsDefined(typeof(PreventActivationEffectInBattle), card.Id); + } + + /// + /// Is this card shouldn't be tried to be selected as target? + /// + 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)); + } + + /// + /// Is this card shouldn't be tried to be selected as target of monster? + /// + 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()); + } + + /// + /// Is this card shouldn't be tried to be selected as target of spell & trap? + /// + 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()); + } + + /// + /// Is this monster should be disabled (with Breakthrough Skill) before it use effect and release or banish itself? + /// + 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); + } + + /// + /// Is this monster not be synchro material? + /// + public static bool IsMonsterNotBeSynchroMaterial(this ClientCard card) + { + return Enum.IsDefined(typeof(NotBeSynchroMaterialMonster), card.Id); + } + + /// + /// Is this monster not be xyz material? + /// + public static bool IsMonsterNotBeXyzMaterial(this ClientCard card) + { + return Enum.IsDefined(typeof(NotBeXyzMaterialMonster), card.Id); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/CardSelector.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/CardSelector.cs new file mode 100644 index 0000000..fda0bb5 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/CardSelector.cs @@ -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 _cards; + private int _id; + private IList _ids; + private CardLocation _location; + + public CardSelector(ClientCard card) + { + _type = SelectType.Card; + _card = card; + } + + public CardSelector(IList cards) + { + _type = SelectType.Cards; + _cards = cards; + } + + public CardSelector(int cardId) + { + _type = SelectType.Id; + _id = cardId; + } + + public CardSelector(IList ids) + { + _type = SelectType.Ids; + _ids = ids; + } + + public CardSelector(CardLocation location) + { + _type = SelectType.Location; + _location = location; + } + + public IList Select(IList cards, int min, int max) + { + IList result = new List(); + + 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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/DeckAttribute.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/DeckAttribute.cs new file mode 100644 index 0000000..89a87a9 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/DeckAttribute.cs @@ -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; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/AlbazExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/AlbazExecutor.cs new file mode 100644 index 0000000..3483497 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/AlbazExecutor.cs @@ -0,0 +1,5861 @@ +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using System.Linq; +using System; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Albaz", "AI_Albaz")] + public class AlbazExecutor : DefaultExecutor + { + public class CardId + { + public const int TheBystialLubellion = 32731036; + public const int AlbionTheShroudedDragon = 25451383; + public const int BystialSaronir = 60242223; + public const int AluberTheJesterOfDespia = 62962630; + public const int FallenOfAlbaz = 68468459; + public const int SpringansKitt = 45484331; + public const int GuidingQuemTheVirtuous = 45883110; + public const int BlazingCartesiaTheVirtuous = 95515789; + public const int TriBrigadeMercourier = 19096726; + // _CardId.AshBlossom = 14558127; + // _CardId.MaxxC = 23434538; + public const int DespianTragedy = 36577931; + + public const int NadirServant = 1984618; + public const int FusionDeployment = 6498706; + public const int BrandedInWhite = 34995106; + public const int BrandedFusion = 44362883; + public const int GoldSarcophagus = 75500286; + public const int FoolishBurial = 81439173; + // _CardId.CalledByTheGrave = 24224830; + public const int BrandedInHighSpirits = 29948294; + public const int BrandedOpening = 36637374; + // _CardId.CrossoutDesignator = 65681983; + public const int BrandedInRed = 82738008; + public const int BrandedLost = 18973184; + + // _CardId.InfiniteImpermanence = 10045474; + public const int BrightestBlazingBrandedKing = 19271881; + public const int BrandedBeast = 32756828; + public const int BrandedRetribution = 17751597; + + public const int GuardianChimera = 11321089; + public const int AlbionTheSanctifireDragon = 38811586; + public const int MirrorjadeTheIcebladeDragon = 44146295; + public const int BorreloadFuriousDragon = 92892239; + public const int LubellionTheSearingDragon = 70534340; + public const int AlbaLenatusTheAbyssDragon = 3410461; + public const int GranguignolTheDuskDragon = 24915933; + public const int DespianQuaeritis = 72272462; + public const int SprindTheIrondashDragon = 1906812; + public const int TitanikladTheAshDragon = 41373230; + public const int RindbrummTheStrikingDragon = 51409648; + public const int AlbionTheBrandedDragon = 87746184; + public const int DespianLuluwalilith = 53971455; + + public const int NaturalExterio = 99916754; + public const int NaturalBeast = 33198837; + public const int ImperialOrder = 61740673; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecree = 51452091; + public const int Number41BagooskatheTerriblyTiredTapir = 90590303; + public const int InspectorBoarder = 15397015; + public const int SkillDrain = 82732705; + + public const int DimensionShifter = 91800273; + public const int MacroCosmos = 30241314; + public const int DimensionalFissure = 81674782; + public const int BanisheroftheRadiance = 94853057; + public const int BanisheroftheLight = 61528025; + public const int KashtiraAriseHeart = 48626373; + public const int AccesscodeTalker = 86066372; + public const int GhostMournerMoonlitChill = 52038441; + public const int NibiruThePrimalBeing = 27204311; + } + + public AlbazExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + + // + AddExecutor(ExecutorType.Summon, AdvanceSummon); + AddExecutor(ExecutorType.SpSummon, CardId.AlbaLenatusTheAbyssDragon, AlbaLenatusTheAbyssDragonSpSummon); + AddExecutor(ExecutorType.MonsterSet, CardId.FallenOfAlbaz, FallenOfAlbazSet); + AddExecutor(ExecutorType.Activate, CardId.BlazingCartesiaTheVirtuous, BlazingCartesiaTheVirtuousActivateInGrave); + + // quick effect + AddExecutor(ExecutorType.Activate, CardId.BrandedRetribution, BrandedRetributionActivate); + AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, CalledbytheGraveActivate); + AddExecutor(ExecutorType.Activate, _CardId.CrossoutDesignator, CrossoutDesignatorActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossomActivate); + AddExecutor(ExecutorType.Activate, CardId.BrandedBeast, BrandedBeastActivate); + AddExecutor(ExecutorType.Activate, CardId.BrightestBlazingBrandedKing, BrightestBlazingBrandedKingActivate); + AddExecutor(ExecutorType.Activate, CardId.BrandedOpening, BrandedOpeningActivate); + AddExecutor(ExecutorType.Activate, CardId.BrandedInHighSpirits, BrandedInHighSpiritsActivate); + AddExecutor(ExecutorType.Activate, CardId.RindbrummTheStrikingDragon, RindbrummTheStrikingDragonActivate); + + // remove + AddExecutor(ExecutorType.Activate, CardId.GuardianChimera, GuardianChimeraActivate); + AddExecutor(ExecutorType.Activate, CardId.BorreloadFuriousDragon, BorreloadFuriousDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.TriBrigadeMercourier, TriBrigadeMercourierActivate); + AddExecutor(ExecutorType.Activate, CardId.DespianQuaeritis, DespianQuaeritisActivate); + AddExecutor(ExecutorType.Activate, CardId.MirrorjadeTheIcebladeDragon, MirrorjadeTheIcebladeDragonActivate); + + // search + AddExecutor(ExecutorType.Activate, CardId.TheBystialLubellion, TheBystialLubellionActivate); + AddExecutor(ExecutorType.SpSummon, CardId.TheBystialLubellion, TheBystialLubellionSpSummon); + AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialActivate); + AddExecutor(ExecutorType.Activate, CardId.GoldSarcophagus, GoldSarcophagusActivate); + AddExecutor(ExecutorType.Activate, CardId.AluberTheJesterOfDespia, AluberTheJesterOfDespiaActivate); + + AddExecutor(ExecutorType.Activate, CardId.AlbionTheSanctifireDragon, AlbionTheSanctifireDragonActivate); + + // blazing + AddExecutor(ExecutorType.Activate, CardId.FusionDeployment, FusionDeploymentActivate); + + AddExecutor(ExecutorType.Activate, CardId.AlbionTheShroudedDragon, AlbionTheShroudedDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.BystialSaronir, BystialSaronirActivate); + + // summon for search + AddExecutor(ExecutorType.Summon, CardId.AluberTheJesterOfDespia, AluberTheJesterOfDespiaSummon); + AddExecutor(ExecutorType.Summon, CardId.GuidingQuemTheVirtuous, GuidingQuemTheVirtuousSummonForSearch); + AddExecutor(ExecutorType.Activate, CardId.SpringansKitt, SpringansKittActivate); + AddExecutor(ExecutorType.Summon, CardId.SpringansKitt, SpringansKittSummon); + + // fusion & lost + AddExecutor(ExecutorType.Activate, CardId.BrandedLost, BrandedLostCardActivate); + AddExecutor(ExecutorType.Activate, CardId.GranguignolTheDuskDragon, GranguignolTheDuskDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.AlbaLenatusTheAbyssDragon, AlbaLenatusTheAbyssDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.SprindTheIrondashDragon, SprindTheIrondashDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.TitanikladTheAshDragon, TitanikladTheAshDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.AlbionTheBrandedDragon, AlbionTheBrandedDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.LubellionTheSearingDragon, LubellionTheSearingDragonActivate); + AddExecutor(ExecutorType.Summon, CardId.BlazingCartesiaTheVirtuous, BlazingCartesiaTheVirtuousSummon); + AddExecutor(ExecutorType.Activate, CardId.FallenOfAlbaz, FallenOfAlbazActivate); + AddExecutor(ExecutorType.Activate, CardId.BrandedFusion, BrandedFusionActivate); + AddExecutor(ExecutorType.Activate, CardId.BlazingCartesiaTheVirtuous, BlazingCartesiaTheVirtuousActivate); + AddExecutor(ExecutorType.Activate, CardId.BrandedInWhite, BrandedInWhiteActivate); + AddExecutor(ExecutorType.Activate, CardId.BrandedInRed, BrandedInRedActivate); + AddExecutor(ExecutorType.Activate, CardId.BrandedLost, BrandedLostActivate); + + // albaz summon + AddExecutor(ExecutorType.Summon, CardId.FallenOfAlbaz, FallenOfAlbazSummon); + AddExecutor(ExecutorType.Summon, CardId.GuidingQuemTheVirtuous, GuidingQuemTheVirtuousSummon); + + // delay + AddExecutor(ExecutorType.Activate, CardId.DespianTragedy, DespianTragedyActivate); + AddExecutor(ExecutorType.Activate, CardId.TriBrigadeMercourier, TriBrigadeMercourierActivateForSearch); + AddExecutor(ExecutorType.Activate, CardId.NadirServant, NadirServantActivate); + + AddExecutor(ExecutorType.MonsterSet, SetForChimera); + AddExecutor(ExecutorType.MonsterSet, CardId.DespianTragedy, DespianTragedySet); + AddExecutor(ExecutorType.Repos, DefaultMonsterRepos); + AddExecutor(ExecutorType.SpellSet, SpellSetCheck); + AddExecutor(ExecutorType.Activate, CardId.GuidingQuemTheVirtuous, GuidingQuemTheVirtuousActivate); + AddExecutor(ExecutorType.Activate, CardId.DespianLuluwalilith, DespianLuluwalilithActivate); + + AddExecutor(ExecutorType.Activate, FloogateActivate); + + } + + const int SetcodeTimeLord = 0x4a; + const int SetcodePhantom = 0xdb; + const int SetcodeOrcust = 0x11b; + const int SetcodeBranded = 0x15d; + const int SetcodeDespain = 0x164; + const int SetcodeBystial = 0x188; + const int SetcodeHorus = 0x19d; + const int hintTimingMainEnd = 0x4; + const int hintBattleStart = 0x8; + List notToNegateIdList = new List{ + 58699500, 20343502, CardId.AlbionTheShroudedDragon, 19403423 + }; + List cannotBeFusionMaterialIdList = new List + { + CardId.AlbaLenatusTheAbyssDragon, CardId.AlbionTheSanctifireDragon, 79229522, 65029288, 30864377, 33964637, 87116928, 13735899, 28226490, 80453041, + _CardId.EaterOfMillions, 2992467, 16366810, 40217358, 47346782, 50893987, 71459017, 84433295, 85101097 + }; + List albazFusionMonster = new List + { + CardId.TitanikladTheAshDragon, CardId.SprindTheIrondashDragon, CardId.AlbionTheBrandedDragon, CardId.LubellionTheSearingDragon, CardId.AlbaLenatusTheAbyssDragon, + CardId.MirrorjadeTheIcebladeDragon, CardId.RindbrummTheStrikingDragon, CardId.AlbionTheSanctifireDragon + }; + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.AluberTheJesterOfDespia, _CardId.AshBlossom, _CardId.MaxxC, _CardId.InfiniteImpermanence }}, + {2, new List { CardId.FallenOfAlbaz, CardId.NadirServant, CardId.FusionDeployment, _CardId.CalledByTheGrave }}, + {1, new List { CardId.TheBystialLubellion, CardId.AlbionTheShroudedDragon, CardId.BystialSaronir, CardId.SpringansKitt, CardId.GuidingQuemTheVirtuous, + CardId.BlazingCartesiaTheVirtuous, CardId.TriBrigadeMercourier, CardId.DespianTragedy, CardId.BrandedInWhite, + CardId.BrandedFusion, CardId.GoldSarcophagus, CardId.FoolishBurial, CardId.BrandedInHighSpirits, CardId.BrandedOpening, + _CardId.CrossoutDesignator, CardId.BrandedInRed, CardId.BrandedLost, CardId.BrightestBlazingBrandedKing, + CardId.BrandedBeast, CardId.BrandedRetribution }} + }; + List dangerousDragonIdList = new List { 27548199, 92892239, 98630720, 9753964, 99585850, 24361622, 27572350, 69120785, 96402918, 74294676, 42752141, 18511599, 35103106, 26268488 }; + List notToDestroySpellTrap = new List { 50005218, 6767771 }; + List targetNegateIdList = new List { + _CardId.EffectVeiler, _CardId.InfiniteImpermanence, CardId.GhostMournerMoonlitChill, _CardId.BreakthroughSkill, 74003290, 67037924, + 9753964, 66192538, 23204029, 73445448, 35103106, 30286474, 45002991, 5795980, 38511382, 53742162, 30430448 + }; + + bool summoned = false; + bool enemyActivateMaxxC = false; + bool enemyActivateLockBird = false; + int dimensionShifterCount = 0; + bool enemyActivateInfiniteImpermanenceFromHand = false; + bool theBystialLubellionSelecting = false; + bool albionTheShroudedDragonSelecting = false; + bool nadirActivated = false; + bool fusionToGYFlag = false; + bool spSummoningAlbaz = false; + int cartesiaSummonGoal = 0; + int sanctifireSelectPositionCount = 0; + int quemSummonFlag = 0; + List cartesiaMaterialList = new List(); + List brandedInRedMaterialList = new List(); + List infiniteImpermanenceList = new List(); + List currentNegateCardList = new List(); + List currentDestroyCardList = new List(); + List sendToGYThisTurn = new List(); + List activatedCardIdList = new List(); + ClientCard fusionTarget = null; + List selectedFusionMaterial = new List(); + List enemyPlaceThisTurn = new List(); + + /// + /// Shuffle List and return a random-order card list + /// + public List ShuffleList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(result.Count); + int nextIndex = (index + Program.Rand.Next(result.Count - 1)) % result.Count; + T tempCard = result[index]; + result[index] = result[nextIndex]; + result[nextIndex] = tempCard; + } + return result; + } + + public bool CheckCanBeTargeted(ClientCard card, bool canBeTarget, CardType selfType) + { + if (card == null) return true; + if (canBeTarget) + { + if (card.IsShouldNotBeTarget()) return false; + if (((int)selfType & (int)CardType.Monster) > 0 && card.IsShouldNotBeMonsterTarget()) return false; + if (((int)selfType & (int)CardType.Spell) > 0 && card.IsShouldNotBeSpellTrapTarget()) return false; + if (((int)selfType & (int)CardType.Trap) > 0 + && (card.IsShouldNotBeSpellTrapTarget() && !card.IsDisabled())) return false; + } + return true; + } + + /// + /// Check remain cards in deck + /// + /// Card's ID + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + + public int CheckRemainInDeck(params int[] ids) + { + int sum = 0; + foreach (int id in ids) + { + sum += CheckRemainInDeck(id); + } + return sum; + } + + /// + /// Check whether'll be negated + /// + /// check whether card itself is disabled. + public bool CheckWhetherNegated(bool disablecheck = true, bool toFieldCheck = false, CardType type = 0) + { + bool isMonster = type == 0 && Card.IsMonster(); + isMonster |= ((int)type & (int)CardType.Monster) != 0; + bool isSpellOrTrap = type == 0 && (Card.IsSpell() || Card.IsTrap()); + isSpellOrTrap |= (((int)type & (int)CardType.Spell) != 0) || (((int)type & (int)CardType.Trap) != 0); + bool isCounter = ((int)type & (int)CardType.Counter) != 0; + if (isSpellOrTrap && toFieldCheck && CheckSpellWillBeNegate(isCounter)) + return true; + if (DefaultCheckWhetherCardIsNegated(Card)) return true; + if (isMonster && (toFieldCheck || Card.Location == CardLocation.MonsterZone)) + { + if ((toFieldCheck && (((int)type & (int)CardType.Link) != 0)) || Card.IsDefense()) + { + if (Enemy.MonsterZone.Any(card => CheckNumber41(card)) || Bot.MonsterZone.Any(card => CheckNumber41(card))) return true; + } + if (Enemy.HasInSpellZone(CardId.SkillDrain, true, true)) return true; + } + if (disablecheck) return (Card.Location == CardLocation.MonsterZone || Card.Location == CardLocation.SpellZone) && Card.IsDisabled() && Card.IsFaceup(); + return false; + } + + public bool CheckNumber41(ClientCard card) + { + return card != null && card.IsFaceup() && card.IsCode(CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled(); + } + + /// + /// Whether spell or trap will be negate. If so, return true. + /// + /// is counter trap + /// check target + /// + public bool CheckSpellWillBeNegate(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() && (Enemy.HasInSpellZone(CardId.RoyalDecree, true) || Bot.HasInSpellZone(CardId.RoyalDecree, true))) return true; + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceList.Contains(selfSeq)) return true; + } + // how to get here? + return false; + } + + /// + /// Check whether last chain card should be disabled. + /// + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + if (lastcard.IsMonster() && lastcard.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (notToNegateIdList.Contains(lastcard.Id)) return false; + if (DefaultCheckWhetherCardIsNegated(lastcard)) return false; + if (Duel.Turn == 1 && lastcard.IsCode(_CardId.MaxxC)) return false; + + return true; + } + + /// + /// Check whether bot is at advantage. + /// + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && (Duel.Player == 0 || Bot.GetMonsterCount() > 0)) return true; + return false; + } + + public bool CheckShouldNoMoreSpSummon() + { + if (CheckAtAdvantage() && enemyActivateMaxxC && !enemyActivateLockBird && (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2)) + { + return true; + } + return false; + } + + public bool CheckWhetherCanSummon() + { + return Duel.Player == 0 && Duel.Phase < DuelPhase.End && !summoned; + } + + /// + /// Check whether cards will be removed. If so, do not send cards to grave. + /// + public bool CheckWhetherWillbeRemoved() + { + if (dimensionShifterCount > 0) return true; + List checkIdList = new List { CardId.BanisheroftheRadiance, CardId.BanisheroftheLight, CardId.MacroCosmos, CardId.DimensionalFissure, + CardId.KashtiraAriseHeart, 58481572 }; + foreach (int cardid in checkIdList) + { + List fields = new List { Bot, Enemy }; + foreach (ClientField cf in fields) + { + if (cf.HasInMonstersZone(cardid, true, false, true) || cf.HasInSpellZone(cardid, true, true)) + { + return true; + } + } + } + return false; + } + + /// + /// Check whether it should be kept in grave to activate effect. + /// If should, return true. + /// + /// + /// + public bool CheckWhetherShouldKeepInGrave(ClientCard c) + { + if (c.IsCode(CardId.GranguignolTheDuskDragon) && c.Location == CardLocation.Grave) return true; + if (!c.IsCode(new int[] { CardId.AlbaLenatusTheAbyssDragon, CardId.AlbionTheBrandedDragon, CardId.TitanikladTheAshDragon, CardId.DespianLuluwalilith, + CardId.SprindTheIrondashDragon})) + { + return false; + } + return sendToGYThisTurn.Contains(c) && c.Location == CardLocation.Grave; + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + ClientCard floodagateCard = Enemy.GetMonsters().Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsFloodgate() && c.IsFaceup() + && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (floodagateCard != null) return floodagateCard; + + ClientCard dangerCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (dangerCard != null) return dangerCard; + + ClientCard invincibleCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (invincibleCard != null) return invincibleCard; + + ClientCard equippedCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.EquipCards.Count > 0 && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (equippedCard != null) return equippedCard; + + ClientCard enemyExtraMonster = Enemy.MonsterZone.Where(c => c != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && (c.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) || (c.HasType(CardType.Link) && c.LinkCount >= 2)) + && CheckCanBeTargeted(c, canBeTarget, selfType) && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (enemyExtraMonster != null) return enemyExtraMonster; + + ClientCard activatingAlbaz = Enemy.MonsterZone.FirstOrDefault(c => c != null && c.IsCode(CardId.FallenOfAlbaz) && !c.IsDisabled() + && !currentDestroyCardList.Contains(c) && !currentNegateCardList.Contains(c) && Duel.CurrentChain.Contains(c)); + if (activatingAlbaz != null) return activatingAlbaz; + + if (attack >= 0) + { + if (attack == 0) + attack = Util.GetBestAttack(Bot); + ClientCard betterCard = Enemy.MonsterZone.Where(card => card != null + && card.GetDefensePower() >= attack && card.GetDefensePower() > 0 && card.IsAttack() && CheckCanBeTargeted(card, canBeTarget, selfType) + && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (betterCard != null) return betterCard; + } + return null; + } + + public bool CheckShouldNotIgnore(ClientCard cards, bool ignore = false) + { + return !ignore || (!currentDestroyCardList.Contains(cards) && !currentNegateCardList.Contains(cards)); + } + + /// + /// check enemy's dangerous card in grave + /// + public List GetDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && (card.HasSetcode(SetcodeOrcust) || card.HasSetcode(SetcodePhantom) || card.HasSetcode(SetcodeHorus))).ToList(); + List dangerMonsterIdList = new List{ + 99937011, 63542003, 9411399, 28954097, 30680659 + }; + result.AddRange(Enemy.Graveyard.GetMatchingCards(card => dangerMonsterIdList.Contains(card.Id))); + return result; + } + + public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreSpells = false, CardType selfType = 0) + { + List resultList = new List(); + + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (floodagateList.Count > 0) resultList.AddRange(floodagateList); + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).ToList(); + if (problemEnemySpellList.Count > 0) resultList.AddRange(ShuffleList(problemEnemySpellList)); + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (dangerList.Count > 0 + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) resultList.AddRange(dangerList); + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (invincibleList.Count > 0) resultList.AddRange(invincibleList); + + List enemyMonsters = Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c)).OrderByDescending(card => card.Attack).ToList(); + if (enemyMonsters.Count > 0) + { + foreach (ClientCard target in enemyMonsters) + { + if ((target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2)) + && !resultList.Contains(target) && CheckCanBeTargeted(target, canBeTarget, selfType) + ) + { + resultList.Add(target); + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() && !currentDestroyCardList.Contains(c) + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous) && CheckCanBeTargeted(c, canBeTarget, selfType) + && !notToDestroySpellTrap.Contains(c.Id)).ToList(); + if (spells.Count > 0 && !ignoreSpells) resultList.AddRange(ShuffleList(spells)); + + return resultList; + } + + public List GetNormalEnemyTargetList(bool canBeTarget = true, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + List targetList = GetProblematicEnemyCardList(canBeTarget, selfType: selfType); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => + (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && enemyPlaceThisTurn.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => + (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && !enemyPlaceThisTurn.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetMonsters().Where(card => card.IsFacedown() && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList())); + + return targetList; + } + + public List GetMonsterListForTargetNegate(bool canBeTarget = false, CardType selfType = 0) + { + List resultList = new List(); + if (CheckWhetherNegated()) + { + return resultList; + } + + // negate before used + ClientCard target = Enemy.MonsterZone.FirstOrDefault(card => card?.Data != null + && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && !card.IsShouldNotBeTarget() + && CheckCanBeTargeted(card, canBeTarget, selfType) + && !currentNegateCardList.Contains(card)); + if (target != null) + { + resultList.Add(target); + } + + // negate monster effect on the field + foreach (ClientCard chainingCard in Duel.CurrentChain) + { + if (chainingCard.Location == CardLocation.MonsterZone && chainingCard.Controller == 1 && !chainingCard.IsDisabled() + && CheckCanBeTargeted(chainingCard, canBeTarget, selfType) && !currentNegateCardList.Contains(chainingCard)) + { + resultList.Add(chainingCard); + } + } + + return resultList; + } + + public override BattlePhaseAction OnBattle(IList attackers, IList defenders) + { + if (attackers.Count() > 0 && defenders.Count() > 0) + { + List sortedAttacker = attackers.OrderBy(card => card.Attack).ToList(); + ClientCard abyssDragon = attackers.FirstOrDefault(c => c.IsCode(CardId.AlbaLenatusTheAbyssDragon) && !c.IsDisabled()); + if (abyssDragon != null) + { + sortedAttacker.Remove(abyssDragon); + sortedAttacker.Insert(0, abyssDragon); + } + for (int k = 0; k < sortedAttacker.Count; ++k) + { + ClientCard attacker = sortedAttacker[k]; + attacker.IsLastAttacker = k == sortedAttacker.Count - 1; + BattlePhaseAction result = OnSelectAttackTarget(attacker, defenders); + if (result != null) + return result; + } + } + + return base.OnBattle(attackers, defenders); + } + + /// + /// go first + /// + public override bool OnSelectHand() + { + return true; + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + ClientCard currentSolvingChain = Duel.GetCurrentSolvingChainCard(); + if (currentSolvingChain != null) + { + if (currentSolvingChain.Controller == 1 && currentSolvingChain.IsCode(_CardId.EvenlyMatched)) + { + Logger.DebugWriteLine("=== Evenly Matched activated."); + List banishList = new List(); + List botMonsters = Bot.GetMonsters().Where(card => !card.HasType(CardType.Token)).ToList(); + + // monster + List faceDownMonsters = botMonsters.Where(card => card.IsFacedown()).ToList(); + banishList.AddRange(faceDownMonsters); + List dumpMainMonsterList = botMonsters.Where(card => !banishList.Contains(card) + && CheckRemainInDeck(card.Id) > 0).ToList(); + dumpMainMonsterList.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(dumpMainMonsterList); + + // spells + List faceUpSpells = Bot.GetSpells().Where(c => c.IsFaceup()).ToList(); + banishList.AddRange(ShuffleList(faceUpSpells)); + List faceDownSpells = Bot.GetSpells().Where(c => c.IsFacedown()).ToList(); + banishList.AddRange(ShuffleList(faceDownSpells)); + + List uniqueMainMonster = botMonsters.Where(card => !banishList.Contains(card) + && !card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && CheckRemainInDeck(card.Id) == 0).ToList(); + uniqueMainMonster.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(uniqueMainMonster); + + List dumpExtraMonsterList = botMonsters.Where(card => !banishList.Contains(card) + && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && Bot.HasInExtra(card.Id)).ToList(); + dumpExtraMonsterList.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(dumpExtraMonsterList); + + List uniqueExtraMonsterList = botMonsters.Where(card => !banishList.Contains(card) + && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && !Bot.HasInExtra(card.Id)).ToList(); + uniqueExtraMonsterList.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(uniqueExtraMonsterList); + + return Util.CheckSelectCount(banishList, cards, min, max); + } + + // search operation + if (hint == HintMsg.AddToHand) + { + Dictionary> checkDict = new Dictionary>(); + + switch (currentSolvingChain.Id) + { + case CardId.AluberTheJesterOfDespia: + case CardId.AluberTheJesterOfDespia + 1: + case CardId.SpringansKitt: + checkDict = new Dictionary> { + {CardId.BrandedFusion, () => BrandedFusionActivateCheck()}, + {CardId.BrandedLost, () => { + if (Duel.Player == 0 && Duel.Phase >= DuelPhase.End) return false; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedFusion) && BrandedFusionActivateCheck()) return true; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedInWhite) && BrandedInWhiteActivateCheck()) return true; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedInRed) && BrandedInRedActivateCheck() != null) return true; + if (!summoned && Bot.HasInHand(CardId.FallenOfAlbaz) && CheckAlbazFusion()) return true; + if ((Bot.HasInMonstersZone(CardId.BlazingCartesiaTheVirtuous) || (!summoned && Bot.HasInHand(CardId.BlazingCartesiaTheVirtuous)))) return true; + return false; + } + }, + {CardId.BrandedInHighSpirits, BrandedInHighSpiritsActivateCheck}, + {CardId.BrandedInRed, () => (Duel.Phase == DuelPhase.End && nadirActivated) || BrandedInRedActivateCheck() != null }, + {CardId.BrandedInWhite, BrandedInWhiteActivateCheck }, + {CardId.BrandedRetribution, () => cards.Any(c => c.IsCode(CardId.BrandedRetribution) && c.Location == CardLocation.Removed) }, + {CardId.BrightestBlazingBrandedKing, () => Bot.GetMonsters().Any(c => c.IsFaceup() && c.IsCode(albazFusionMonster)) }, + {CardId.BrandedOpening, () => Bot.Hand.Count > 2 } + }; + break; + case CardId.NadirServant: + if (!summoned) + { + ClientCard quem = cards.FirstOrDefault(c => c.IsCode(CardId.GuidingQuemTheVirtuous)); + if (quem != null) + { + return Util.CheckSelectCount(new List { quem }, cards, min, max); + } + } + List locList = new List { CardLocation.Grave, CardLocation.Deck }; + if (Bot.HasInGraveyard(CardId.RindbrummTheStrikingDragon) && cards.Where(c => c.IsOriginalCode(CardId.FallenOfAlbaz) && c.Location == CardLocation.Grave).Count() == 1) + { + locList = new List { CardLocation.Deck, CardLocation.Grave }; + } + foreach (int checkId in new[] { CardId.FallenOfAlbaz, CardId.GuidingQuemTheVirtuous }) + { + foreach (CardLocation loc in locList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsOriginalCode(checkId) && c.Location == loc); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + case CardId.BrandedLost: + case CardId.TriBrigadeMercourier: + case CardId.BrandedInHighSpirits: + checkDict = new Dictionary>{ + {CardId.TriBrigadeMercourier, () => Bot.GetMonsters().Any(c => c.IsFaceup() && c.IsCode(albazFusionMonster)) + || (Bot.HasInMonstersZone(CardId.BlazingCartesiaTheVirtuous) && Bot.HasInHandOrHasInMonstersZone(CardId.FallenOfAlbaz))}, + {CardId.SpringansKitt, () => CheckWhetherCanSummon() && !activatedCardIdList.Contains(CardId.SpringansKitt + 1) }, + {CardId.FallenOfAlbaz, () => (CheckWhetherCanSummon() && CheckAlbazFusion()) || Bot.HasInMonstersZone(CardId.BlazingCartesiaTheVirtuous) }, + {CardId.GuidingQuemTheVirtuous, () => CheckWhetherCanSummon() }, + {CardId.BlazingCartesiaTheVirtuous, () => CheckWhetherCanSummon() || (!CheckShouldNoMoreSpSummon() && Bot.HasInMonstersZoneOrInGraveyard(CardId.FallenOfAlbaz))}, + {CardId.AlbionTheShroudedDragon, () => !CheckWhetherWillbeRemoved() && !activatedCardIdList.Contains(CardId.AlbionTheShroudedDragon) }, + }; + break; + case CardId.AlbaLenatusTheAbyssDragon: + checkDict = new Dictionary>{ + {CardId.BrandedFusion, () => BrandedFusionActivateCheck(false)}, + {CardId.FusionDeployment, () => true} + }; + break; + default: + break; + } + + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + + switch (currentSolvingChain.Id) + { + // for lubellion + case CardId.TheBystialLubellion: + { + Dictionary> lubellionCheckDict = new Dictionary>(); + if (hint == HintMsg.ToField) + { + lubellionCheckDict.Add(CardId.BrandedLost, () => { + bool fusionFlag = Bot.HasInHandOrHasInMonstersZone(CardId.BlazingCartesiaTheVirtuous); + if (!activatedCardIdList.Contains(CardId.BrandedFusion)) + { + if (Bot.HasInHand(CardId.BrandedFusion) || (!summoned && CheckRemainInDeck(CardId.BrandedFusion) > 0 && Bot.HasInHand(new int[] { + CardId.AluberTheJesterOfDespia, CardId.SpringansKitt + }))) + { + fusionFlag = true; + } + } + fusionFlag |= !summoned && Bot.HasInHand(CardId.FallenOfAlbaz) && CheckAlbazFusion(); + fusionFlag |= Bot.HasInHandOrInSpellZone(CardId.BrandedInWhite) && BrandedInWhiteActivateCheck(); + fusionFlag |= Bot.HasInHandOrInSpellZone(CardId.BrandedInRed) && BrandedInRedActivateCheck() != null; + + return fusionFlag; + }); + lubellionCheckDict.Add(CardId.BrandedBeast, () => true); + } + else if (hint == HintMsg.AddToHand) + { + lubellionCheckDict.Add(CardId.BystialSaronir, () => true); + } + + foreach (KeyValuePair> pair in lubellionCheckDict) + { + ClientCard target = cards.FirstOrDefault(c => c.Id == pair.Key); + if (target != null && pair.Value()) + { + SelectSTPlace(target, false); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for albaz + case CardId.FallenOfAlbaz: + case CardId.FallenOfAlbaz + 1: + if (hint == HintMsg.SpSummon) + { + List fusionTargetIdList = new List { + CardId.MirrorjadeTheIcebladeDragon, CardId.AlbaLenatusTheAbyssDragon, CardId.AlbionTheBrandedDragon, CardId.AlbionTheSanctifireDragon, + CardId.LubellionTheSearingDragon, CardId.BorreloadFuriousDragon, CardId.TitanikladTheAshDragon, CardId.RindbrummTheStrikingDragon + }; + foreach (int targetId in fusionTargetIdList) + { + if (targetId == CardId.LubellionTheSearingDragon && Bot.Hand.Count == 0) continue; + ClientCard target = cards.FirstOrDefault(c => c.IsCode(targetId)); + if (target != null) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + if (hint == HintMsg.FusionMaterial) + { + if (cards.Count == 1) + { + selectedFusionMaterial.AddRange(cards); + return Util.CheckSelectCount(cards, cards, min, max); + } + // select best enemy monster + List sortedResult = cards.OrderByDescending(card => card.GetDefensePower()).ToList(); + selectedFusionMaterial.Add(sortedResult[0]); + return Util.CheckSelectCount(sortedResult, cards, min, max); + } + break; + + // for quem + case CardId.GuidingQuemTheVirtuous: + { + Dictionary> quemCheckDict = new Dictionary> + { + {CardId.BlazingCartesiaTheVirtuous, () => sendToGYThisTurn.Any(c => c.IsCode(CardId.AlbionTheBrandedDragon)) && CheckRemainInDeck(CardId.BrandedInHighSpirits) > 0 }, + {CardId.BrandedFusion, () => Bot.HasInGraveyard(CardId.BrandedRetribution) }, + {CardId.FallenOfAlbaz, () => !Bot.HasInGraveyard(CardId.FallenOfAlbaz) }, + {CardId.TriBrigadeMercourier, () => Bot.HasInHandOrInSpellZone(CardId.BrandedInWhite) }, + {CardId.BrandedRetribution, () => true }, + {CardId.BrightestBlazingBrandedKing, () => !Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.IsCode(albazFusionMonster) && fusionToGYFlag) }, + {CardId.BrandedInHighSpirits, () => fusionToGYFlag }, + {CardId.AlbionTheShroudedDragon, () => true }, + }; + + foreach (KeyValuePair> pair in quemCheckDict) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for cartesia + case CardId.BlazingCartesiaTheVirtuous: + case CardId.BlazingCartesiaTheVirtuous + 1: + if (hint == HintMsg.SpSummon) + { + // fix material list + cartesiaMaterialList = cartesiaMaterialList.Where(c => c != null && (c.Location == CardLocation.MonsterZone || c.Location == CardLocation.Hand)).ToList(); + + // filter normal material + List materialList = Bot.MonsterZone.Where(c => c != null && c.GetDefensePower() <= 2500 && !c.IsCode(cannotBeFusionMaterialIdList)).ToList(); + materialList.AddRange(Bot.Hand.Where(c => c.IsMonster() + && !(CheckWhetherCanSummon() && + ((!activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && c.IsCode(CardId.AluberTheJesterOfDespia)) + || (!activatedCardIdList.Contains(CardId.SpringansKitt) && c.IsCode(CardId.SpringansKitt))) + ) + ) + ); + + if (cartesiaSummonGoal > 0) + { + BlazingCartesiaTheVirtuousFusionCheck(cards, cartesiaSummonGoal, materialList, cartesiaMaterialList, out ClientCard _fusionTarget1, out _); + if (_fusionTarget1 != null) + { + fusionTarget = _fusionTarget1; + return Util.CheckSelectCount(new List { fusionTarget }, cards, min, max); + } + } + BlazingCartesiaTheVirtuousFusionCheck(cards, 0, materialList, cartesiaMaterialList, out ClientCard _fusionTarget2, out _); + if (_fusionTarget2 != null) + { + fusionTarget = _fusionTarget2; + return Util.CheckSelectCount(new List { fusionTarget }, cards, min, max); + } + + } + if (hint == HintMsg.FusionMaterial) + { + List mustSelectMaterialList = cartesiaMaterialList.Intersect(cards).ToList(); + if (mustSelectMaterialList != null && mustSelectMaterialList.Count > 0) + { + selectedFusionMaterial.Add(mustSelectMaterialList[0]); + return Util.CheckSelectCount(mustSelectMaterialList, cards, min, max); + } + + ClientCard lubellion = cards.FirstOrDefault(c => c != null && c.IsCode(CardId.TheBystialLubellion) && c.Location == CardLocation.MonsterZone); + if (lubellion != null && !Bot.HasInHandOrInSpellZone(CardId.BrandedBeast)) + { + if (activatedCardIdList.Contains(CardId.TheBystialLubellion + 1) || CheckRemainInDeck(CardId.BrandedLost, CardId.BrandedBeast) == 0) + { + if (Util.IsTurn1OrMain2() || Enemy.MonsterZone.Count(c => c != null && c.GetDefensePower() < 2500) > 0) + { + return Util.CheckSelectCount(new List { lubellion }, cards, min, max); + } + } + } + + ClientCard selectTarget = cards + .Where(c => c.Attack <= 2500 && !(CheckWhetherCanSummon() && + ((!activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && c.IsCode(CardId.AluberTheJesterOfDespia)) + || (!activatedCardIdList.Contains(CardId.SpringansKitt) && c.IsCode(CardId.SpringansKitt))) + ) + ) + .OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (selectTarget != null) + { + selectedFusionMaterial.Add(selectTarget); + return Util.CheckSelectCount(new List { selectTarget }, cards, min, max); + } + selectTarget = cards.OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (selectTarget != null) + { + selectedFusionMaterial.Add(selectTarget); + return Util.CheckSelectCount(new List { selectTarget }, cards, min, max); + } + } + break; + + // for nadir + case CardId.NadirServant: + if (hint == HintMsg.ToGrave) + { + if (summoned) + { + if (CheckRemainInDeck(CardId.BlazingCartesiaTheVirtuous) > 0) + { + ClientCard lulu = cards.FirstOrDefault(c => c.IsOriginalCode(CardId.DespianLuluwalilith)); + if (lulu != null) + { + return Util.CheckSelectCount(new List { lulu }, cards, min, max); + } + } + if (!Bot.MonsterZone.Any(c => c != null && c.HasType(CardType.Fusion)) && CheckRemainInDeck(CardId.SpringansKitt) > 0) + { + ClientCard ironDragon = cards.FirstOrDefault(c => c.IsOriginalCode(CardId.SprindTheIrondashDragon)); + if (ironDragon != null) + { + return Util.CheckSelectCount(new List { ironDragon }, cards, min, max); + } + } + } + NadirServantActivateCheck(cards, true, out ClientCard target); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + + // for deployment + case CardId.FusionDeployment: + { + int summonId = FusionDeploymentSpSummonTarget(); + if (summonId > 0) + { + if (hint == HintMsg.Confirm) + { + if (summonId == CardId.BlazingCartesiaTheVirtuous) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(CardId.GranguignolTheDuskDragon)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + else if (summonId == CardId.FallenOfAlbaz) + { + List shuffleList = ShuffleList(new List(cards)); + foreach (ClientCard target in shuffleList) + { + if (target.IsCode(albazFusionMonster)) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + } + if (hint == HintMsg.SpSummon) + { + foreach (ClientCard target in cards) + { + if (target.IsCode(summonId)) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + } + } + break; + + // for branded in white + case CardId.BrandedInWhite: + if (hint == HintMsg.SpSummon) + { + BrandedInWhiteFusionTarget(cards, out ClientCard target); + if (target != null) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + if (hint == HintMsg.FusionMaterial && fusionTarget != null) + { + if (fusionTarget.IsCode(CardId.BorreloadFuriousDragon)) + { + // select 2 dark dragon monster + foreach (CardLocation loc in new[] { CardLocation.Grave, CardLocation.Hand, CardLocation.MonsterZone }) + { + List cardsInLoc = cards.Where(c => c.Location == loc).OrderBy(c => c.GetDefensePower()).ToList(); + int banishedAlbazCount = Bot.Banished.Where(c => c.IsOriginalCode(CardId.FallenOfAlbaz)).Count(); + banishedAlbazCount += selectedFusionMaterial.Where(c => c.IsOriginalCode(CardId.FallenOfAlbaz)).Count(); + foreach (ClientCard target in cardsInLoc) + { + // keep albaz + if (target.IsOriginalCode(CardId.FallenOfAlbaz) && banishedAlbazCount > 0) + { + continue; + } + selectedFusionMaterial.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + if (fusionTarget.IsCode(CardId.DespianQuaeritis)) + { + // select despain + if (selectedFusionMaterial.Count == 0) + { + foreach (CardLocation loc in new[] { CardLocation.Grave, CardLocation.Hand, CardLocation.MonsterZone }) + { + List cardsInLoc = cards.Where(c => c.Location == loc && c.HasSetcode(SetcodeDespain) && (loc != CardLocation.Grave || !CheckWhetherShouldKeepInGrave(c))) + .OrderBy(c => c.GetDefensePower()).ToList(); + if (cardsInLoc.Count > 0) + { + selectedFusionMaterial.Add(cardsInLoc[0]); + return Util.CheckSelectCount(cardsInLoc, cards, min, max); + } + } + } + // select light/dark + else + { + foreach (CardLocation loc in new[] { CardLocation.Grave, CardLocation.Hand, CardLocation.MonsterZone }) + { + List cardsInLoc = cards.Where(c => c.Location == loc && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark) && (loc != CardLocation.Grave || !CheckWhetherShouldKeepInGrave(c))) + .OrderBy(c => c.GetDefensePower()).ToList(); + if (cardsInLoc.Count > 0) + { + if (!activatedCardIdList.Contains(CardId.TriBrigadeMercourier + 1)) + { + ClientCard mercourier = cardsInLoc.FirstOrDefault(c => c.IsCode(CardId.TriBrigadeMercourier)); + if (mercourier != null) + { + selectedFusionMaterial.Add(mercourier); + return Util.CheckSelectCount(new List { mercourier }, cards, min, max); + } + } + if (!activatedCardIdList.Contains(CardId.DespianTragedy) && CheckRemainInDeck(CardId.AluberTheJesterOfDespia, CardId.GuidingQuemTheVirtuous) > 0) + { + ClientCard tragedy = cardsInLoc.FirstOrDefault(c => c.IsCode(CardId.DespianTragedy)); + if (tragedy != null) + { + selectedFusionMaterial.Add(tragedy); + return Util.CheckSelectCount(new List { tragedy }, cards, min, max); + } + } + + selectedFusionMaterial.Add(cardsInLoc[0]); + return Util.CheckSelectCount(cardsInLoc, cards, min, max); + } + } + } + } + if (fusionTarget.IsCode(CardId.GuardianChimera)) + { + List goalMaterialList = ChimeraFusionMaterialList().Intersect(cards).ToList(); + if (goalMaterialList.Count > 0) + { + return Util.CheckSelectCount(goalMaterialList, cards, min, max); + } + } + if (fusionTarget.IsCode(albazFusionMonster)) + { + // selecting albaz + if (selectedFusionMaterial.Count == 0) + { + foreach (CardLocation loc in new[] { CardLocation.Grave, CardLocation.MonsterZone, CardLocation.Hand }) + { + ClientCard albaz = cards.Where(c => c.IsCode(CardId.FallenOfAlbaz)).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (albaz != null) + { + selectedFusionMaterial.Add(albaz); + return Util.CheckSelectCount(new List { albaz }, cards, min, max); + } + } + } + else + { + if (fusionTarget.IsOriginalCode(CardId.AlbaLenatusTheAbyssDragon) && cancelable) + { + return null; + } + if (Util.IsTurn1OrMain2() && !CheckWhetherWillbeRemoved()) + { + ClientCard duskDragon = cards.FirstOrDefault(c => c.IsCode(CardId.GranguignolTheDuskDragon) && c.Location == CardLocation.MonsterZone); + if (duskDragon != null) + { + selectedFusionMaterial.Add(duskDragon); + return Util.CheckSelectCount(new List { duskDragon }, cards, min, max); + } + } + List> funcList = new List> + { + (c) => c.Location == CardLocation.Grave && !CheckWhetherShouldKeepInGrave(c), + (c) => c.Location == CardLocation.MonsterZone && c.GetDefensePower() <= 2000, + (c) => c.Location == CardLocation.Hand, + (c) => c.Location == CardLocation.Grave, + (c) => c.Location == CardLocation.MonsterZone + }; + foreach (Func func in funcList) + { + List targetList = cards.Where(c => func(c)).OrderBy(c => c.GetDefensePower()).ToList(); + if (targetList.Count > 0) + { + selectedFusionMaterial.Add(targetList[0]); + return Util.CheckSelectCount(new List { targetList[0] }, cards, min, max); + } + } + } + } + } + break; + + // for branded fusion + case CardId.BrandedFusion: + if (hint == HintMsg.SpSummon) + { + Dictionary> brandedFusionCheckDict = new Dictionary> + { + {CardId.TitanikladTheAshDragon, () => Enemy.HasInMonstersZone(CardId.KashtiraAriseHeart) }, + {CardId.RindbrummTheStrikingDragon, () => CheckWhetherWillbeRemoved() && CheckRemainInDeck(CardId.TriBrigadeMercourier) > 0}, + {CardId.AlbionTheSanctifireDragon, () => CheckShouldNoMoreSpSummon()}, + {CardId.AlbionTheBrandedDragon, () => { + bool checkFlag = Bot.Graveyard.Any(c => c != null && c.IsMonster() && c.HasAttribute(CardAttribute.Dark) && !c.IsCode(cannotBeFusionMaterialIdList)); + checkFlag |= Bot.HasInHandOrHasInMonstersZone(CardId.TriBrigadeMercourier); + checkFlag |= Bot.GetMonsters().Any(c => c.GetDefensePower() <= 1800 && c.HasAttribute(CardAttribute.Dark) && !c.IsCode(cannotBeFusionMaterialIdList)); + return checkFlag; + } }, + {CardId.LubellionTheSearingDragon, () => !CheckWhetherNegated(true, true, CardType.Monster) && Bot.Hand.Count > 0 }, + {CardId.MirrorjadeTheIcebladeDragon, () => Bot.HasInMonstersZone(new List{ + CardId.GranguignolTheDuskDragon, CardId.AlbionTheBrandedDragon, CardId.LubellionTheSearingDragon}) } + }; + + foreach (KeyValuePair> pair in brandedFusionCheckDict) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + if (hint == HintMsg.FusionMaterial) + { + // selecting albaz + if (selectedFusionMaterial.Count == 0) + { + foreach (CardLocation loc in new[] { CardLocation.Deck, CardLocation.Hand, CardLocation.MonsterZone }) + { + ClientCard target = cards.FirstOrDefault(c => c.IsOriginalCode(CardId.FallenOfAlbaz) && c.Location == loc); + if (target != null) + { + selectedFusionMaterial.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + // selecting another material + if (fusionTarget != null) + { + Dictionary> materialDict = new Dictionary> + { + { CardId.AlbionTheSanctifireDragon, new List{CardId.BlazingCartesiaTheVirtuous, _CardId.EffectVeiler, CardId.GuidingQuemTheVirtuous} }, + { CardId.MirrorjadeTheIcebladeDragon, new List{CardId.GranguignolTheDuskDragon, CardId.AlbionTheBrandedDragon, CardId.DespianLuluwalilith } }, + { CardId.LubellionTheSearingDragon, new List{ + CardId.DespianTragedy, CardId.BystialSaronir, CardId.AlbionTheShroudedDragon, CardId.AluberTheJesterOfDespia, CardId.TriBrigadeMercourier } }, + { CardId.TitanikladTheAshDragon, new List{CardId.TheBystialLubellion, CardId.AlbionTheShroudedDragon, CardId.BystialSaronir} }, + { CardId.RindbrummTheStrikingDragon, new List{CardId.TriBrigadeMercourier, CardId.SpringansKitt } }, + { CardId.AlbionTheBrandedDragon, new List{CardId.TheBystialLubellion, CardId.BlazingCartesiaTheVirtuous, CardId.GuidingQuemTheVirtuous } } + }; + materialDict.TryGetValue(fusionTarget.GetOriginCode(), out List checkIdList); + if (checkIdList != null && checkIdList.Count > 0) + { + foreach (CardLocation location in new List { CardLocation.Deck, CardLocation.Hand, CardLocation.MonsterZone }) + { + foreach (int checkId in checkIdList) + { + ClientCard target = cards.FirstOrDefault(c => c.Location == location && c.IsCode(checkId)); + if (target != null) + { + selectedFusionMaterial.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + } + } + } + break; + + // for Sarcophagus + case CardId.GoldSarcophagus: + { + GoldSarcophagusTarget(cards, out ClientCard sarcophagusTarget); + if (sarcophagusTarget != null) + { + return Util.CheckSelectCount(new List { sarcophagusTarget }, cards, min, max); + } + } + break; + + // for burial + case CardId.FoolishBurial: + case CardId.FoolishBurial + 1: + { + FoolishBurialTarget(cards, out ClientCard burialTarget); + if (burialTarget != null) + { + return Util.CheckSelectCount(new List { burialTarget }, cards, min, max); + } + } + break; + + // for high spirit + case CardId.BrandedInHighSpirits: + // confirm + if (hint == HintMsg.Confirm) + { + if (Duel.Phase == DuelPhase.End && Bot.HasInMonstersZone(CardId.GuidingQuemTheVirtuous)) + { + ClientCard cartesia = cards.FirstOrDefault(c => c.IsOriginalCode(CardId.BlazingCartesiaTheVirtuous)); + if (cartesia != null) + { + fusionTarget = cartesia; + return Util.CheckSelectCount(new List { cartesia }, cards, min, max); + } + } + bool activatingShroudedFlag = Duel.CurrentChain.Any(c => c.IsOriginalCode(CardId.AlbionTheShroudedDragon) && c.Location == CardLocation.Hand); + if (activatingShroudedFlag) + { + ClientCard shrouded = cards.FirstOrDefault(c => c.IsOriginalCode(CardId.AlbionTheShroudedDragon)); + if (shrouded != null) + { + fusionTarget = shrouded; + return Util.CheckSelectCount(new List { shrouded }, cards, min, max); + } + } + List discardIdList = new List { + CardId.BystialSaronir, CardId.AlbionTheShroudedDragon, CardId.TheBystialLubellion, CardId.BlazingCartesiaTheVirtuous, + CardId.FallenOfAlbaz, CardId.TriBrigadeMercourier + }; + foreach (int discardId in discardIdList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsOriginalCode(discardId)); + if (target != null) + { + // lubellion check + if (discardId == CardId.TheBystialLubellion && Duel.Player == 0 && (Duel.Phase <= DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2) + && CheckRemainInDeck(CardId.BystialSaronir) > 0 && !activatedCardIdList.Contains(CardId.TheBystialLubellion)) + { + continue; + } + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + // discard + if (hint == HintMsg.ToGrave) + { + List discardIdList = new List { + CardId.AlbionTheBrandedDragon, CardId.TitanikladTheAshDragon, CardId.RindbrummTheStrikingDragon, CardId.AlbaLenatusTheAbyssDragon, + CardId.GranguignolTheDuskDragon + }; + foreach (int discardId in discardIdList) + { + if (sendToGYThisTurn.Any(c => c.IsOriginalCode(discardId))) continue; + ClientCard target = cards.FirstOrDefault(c => c.IsOriginalCode(discardId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for opening + case CardId.BrandedOpening: + if (hint == HintMsg.OperateCard) + { + Dictionary> openingCheckDict = new Dictionary>{ + {CardId.AluberTheJesterOfDespia, () => !activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && !DefaultCheckWhetherCardIdIsNegated(CardId.AluberTheJesterOfDespia) + && !(CheckWhetherCanSummon() && Bot.HasInHand(CardId.AluberTheJesterOfDespia))}, + {CardId.GuidingQuemTheVirtuous, () => true }, + {CardId.DespianTragedy, () => true } + }; + foreach (KeyValuePair> pair in openingCheckDict) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for branded in red + case CardId.BrandedInRed: + if (hint == HintMsg.SpSummon) + { + // filter normal material + List materialList = Bot.MonsterZone.Where(c => c != null && c.GetDefensePower() <= 2500 && !c.IsCode(cannotBeFusionMaterialIdList)).ToList(); + materialList.AddRange(Bot.Hand.Where(c => c.IsMonster() + && !(CheckWhetherCanSummon() && + ((!activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && c.IsCode(CardId.AluberTheJesterOfDespia)) + || (!activatedCardIdList.Contains(CardId.SpringansKitt) && c.IsCode(CardId.SpringansKitt))) + ) + ) + ); + + BrandedInRedFusionCheck(cards, 0, materialList, brandedInRedMaterialList, out ClientCard _fusionTarget, out _); + if (_fusionTarget != null) + { + fusionTarget = _fusionTarget; + return Util.CheckSelectCount(new List { fusionTarget }, cards, min, max); + } + + } + if (hint == HintMsg.FusionMaterial) + { + List mustSelectMaterialList = brandedInRedMaterialList.Intersect(cards).ToList(); + if (mustSelectMaterialList != null && mustSelectMaterialList.Count > 0) + { + selectedFusionMaterial.Add(mustSelectMaterialList[0]); + return Util.CheckSelectCount(mustSelectMaterialList, cards, min, max); + } + + ClientCard selectTarget = cards + .Where(c => c.Attack <= 2500 && !(CheckWhetherCanSummon() && + ((!activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && c.IsCode(CardId.AluberTheJesterOfDespia)) + || (!activatedCardIdList.Contains(CardId.SpringansKitt) && c.IsCode(CardId.SpringansKitt))) + ) + ) + .OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (selectTarget != null) + { + selectedFusionMaterial.Add(selectTarget); + return Util.CheckSelectCount(new List { selectTarget }, cards, min, max); + } + selectTarget = cards.OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (selectTarget != null) + { + selectedFusionMaterial.Add(selectTarget); + return Util.CheckSelectCount(new List { selectTarget }, cards, min, max); + } + } + break; + + // for branded king + case CardId.BrightestBlazingBrandedKing: + if (hint == HintMsg.Faceup) + { + List targetIdList = new List + { + CardId.MirrorjadeTheIcebladeDragon, CardId.AlbionTheSanctifireDragon, CardId.RindbrummTheStrikingDragon + }; + List> funcList = new List> + { + (c) => Duel.CurrentChain.Contains(c), + (c) => true + }; + foreach (Func func in funcList) + { + List chainedList = cards.Where(c => func(c)).ToList(); + if (chainedList.Count > 0) + { + foreach (int checkId in targetIdList) + { + ClientCard target = chainedList.FirstOrDefault(c => c.IsOriginalCode(checkId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + ClientCard otherChainTarget = chainedList.FirstOrDefault(c => Duel.CurrentChain.Contains(c)); + if (otherChainTarget != null) + { + return Util.CheckSelectCount(new List { otherChainTarget }, cards, min, max); + } + } + } + } + break; + + // for retribution + case CardId.BrandedRetribution: + { + ClientCard searing = cards.FirstOrDefault(c => c.IsCode(CardId.LubellionTheSearingDragon)); + if (searing != null) + { + selectedFusionMaterial.Add(searing); + return Util.CheckSelectCount(new List { searing }, cards, min, max); + } + List checkIdList = new List { CardId.AlbionTheBrandedDragon, CardId.MirrorjadeTheIcebladeDragon, CardId.TitanikladTheAshDragon, CardId.AlbaLenatusTheAbyssDragon, + CardId.AlbionTheSanctifireDragon, CardId.SprindTheIrondashDragon}; + foreach (int checkId in checkIdList) + { + List gravePriorityList = cards.Where(c => c != null && c.IsCode(checkId) && c.Location == CardLocation.Grave && !CheckWhetherShouldKeepInGrave(c)).ToList(); + if (gravePriorityList.Count > 0) + { + selectedFusionMaterial.Add(gravePriorityList[0]); + return Util.CheckSelectCount(new List { gravePriorityList[0] }, cards, min, max); + } + } + List graveList = cards.Where(c => c != null && c.Location == CardLocation.Grave).ToList(); + if (graveList.Count > 0) + { + selectedFusionMaterial.Add(graveList[0]); + return Util.CheckSelectCount(new List { graveList[0] }, cards, min, max); + } + ClientCard monsterOnField = cards.Where(c => c != null && c.Location == CardLocation.MonsterZone).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (monsterOnField != null) + { + selectedFusionMaterial.Add(monsterOnField); + return Util.CheckSelectCount(new List { monsterOnField }, cards, min, max); + } + } + break; + + // for chimera + case CardId.GuardianChimera: + { + List targetList = new List(); + + targetList.AddRange(GetProblematicEnemyCardList(false, false, CardType.Monster)); + int bestBotPower = Util.GetBestPower(Bot); + targetList.AddRange(Enemy.MonsterZone.Where(c => c != null && !targetList.Contains(c) && c.GetDefensePower() >= bestBotPower).OrderByDescending(c => c.GetDefensePower())); + targetList.AddRange(ShuffleList(enemyPlaceThisTurn)); + + return Util.CheckSelectCount(targetList, cards, min, max); + } + break; + + // for sanctifire + case CardId.AlbionTheSanctifireDragon: + if (hint == Util.GetStringId(CardId.AlbionTheSanctifireDragon, 1)) + { + ClientCard albaz = cards.FirstOrDefault(c => c.IsOriginalCode(CardId.FallenOfAlbaz)); + if (albaz != null && CheckAlbazFusion()) + { + return Util.CheckSelectCount(new List { albaz }, cards, min, max); + } + + ClientCard floogate = cards.Where(c => c.IsFloodgate()).OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (floogate != null) + { + return Util.CheckSelectCount(new List { floogate }, cards, min, max); + } + + return Util.CheckSelectCount(cards.OrderByDescending(c => c.GetDefensePower()).ToList(), cards, min, max); + } + break; + + // for mirrorjade + case CardId.MirrorjadeTheIcebladeDragon: + { + List floodgateList = ShuffleList(cards.Where(c => c.Controller == 1 && c.IsFloodgate()).ToList()); + if (floodgateList.Count > 0) + { + return Util.CheckSelectCount(floodgateList, cards, min, max); + } + + List extraMonsterList = cards.Where(c => c.Controller == 1 && ( + c.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (c.HasType(CardType.Link) && c.LinkCount >= 2))).OrderByDescending(c => c.GetDefensePower()).ToList(); + if (extraMonsterList.Count > 0) + { + return Util.CheckSelectCount(extraMonsterList, cards, min, max); + } + + ClientCard worstBotMonster = Util.GetWorstBotMonster(); + int worstBotPower = worstBotMonster == null ? 0 : worstBotMonster.GetDefensePower(); + List betterMonsterList = cards.Where(c => c.Controller == 1 && c.GetDefensePower() >= worstBotPower).OrderByDescending(c => c.GetDefensePower()).ToList(); + if (betterMonsterList.Count > 0) + { + return Util.CheckSelectCount(betterMonsterList, cards, min, max); + } + + List dangerMonsterList = cards.Where(c => c.Controller == 1 && (c.IsMonsterDangerous() || c.IsMonsterInvincible())) + .OrderByDescending(c => c.GetDefensePower()).ToList(); + if (dangerMonsterList.Count > 0) + { + return Util.CheckSelectCount(dangerMonsterList, cards, min, max); + } + + List allEnemyMonsterList = cards.Where(c => c.Controller == 1).OrderByDescending(c => c.IsFacedown() ? 0 : c.GetDefensePower()).ToList(); + if (allEnemyMonsterList.Count > 0) + { + return Util.CheckSelectCount(allEnemyMonsterList, cards, min, max); + } + + ClientCard botMonsterWithEffect = cards.FirstOrDefault(c => c.Controller == 0 && c.IsCode(new[] { CardId.DespianTragedy, CardId.TriBrigadeMercourier })); + if (botMonsterWithEffect != null) + { + return Util.CheckSelectCount(new List { botMonsterWithEffect }, cards, min, max); + } + ClientCard botLubellion = cards.FirstOrDefault(c => c.Controller == 0 && c.IsCode(CardId.TheBystialLubellion)); + if (botLubellion != null) + { + return Util.CheckSelectCount(new List { botLubellion }, cards, min, max); + } + + + List allBotMonster = cards.Where(c => c.Controller == 0).OrderBy(c => c.IsFacedown() ? 0 : c.GetDefensePower()).ToList(); + if (allBotMonster.Count > 0) + { + return Util.CheckSelectCount(allBotMonster, cards, min, max); + } + } + break; + + // for searing dragon + case CardId.LubellionTheSearingDragon: + if (hint == HintMsg.SpSummon) + { + LubellionTheSearingDragonFusionTarget(cards, out ClientCard target); + if (target != null) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + if (hint == HintMsg.FusionMaterial && fusionTarget != null) + { + if (fusionTarget.IsCode(CardId.BorreloadFuriousDragon)) + { + // select 2 dark dragon monster + List> furiousFuncList = new List> + { + (c) => c.IsFaceup() && c.Location == CardLocation.Removed && c.IsCode(CardId.AlbionTheBrandedDragon), + (c) => c.IsFaceup() && c.Location == CardLocation.Removed && c.IsCode(CardId.FallenOfAlbaz), + (c) => c.Location == CardLocation.Grave && c.IsCode(CardId.AlbionTheBrandedDragon) && !CheckWhetherShouldKeepInGrave(c), + (c) => c.IsFaceup() && c.Location == CardLocation.Removed && c.IsCode(CardId.TitanikladTheAshDragon), + (c) => c.IsFaceup() && c.Location == CardLocation.Removed, + (c) => c.Location == CardLocation.Grave && !CheckWhetherShouldKeepInGrave(c), + (c) => c.Location == CardLocation.Grave, + (c) => c.Location == CardLocation.Hand || c.Location == CardLocation.MonsterZone + }; + + foreach (Func func in furiousFuncList) + { + List cardWithFunc = cards.Where(c => func(c)).OrderBy(c => c.GetDefensePower()).ToList(); + if (cardWithFunc.Count > 0) + { + selectedFusionMaterial.Add(cardWithFunc[0]); + return Util.CheckSelectCount(new List { cardWithFunc[0] }, cards, min, max); + } + } + } + List> funcList = new List> + { + (c) => c.IsFaceup() && c.Location == CardLocation.Removed, + (c) => c.Location == CardLocation.Grave && !CheckWhetherShouldKeepInGrave(c), + (c) => c.IsCode(CardId.LubellionTheSearingDragon), + (c) => c.Location == CardLocation.Grave, + (c) => c.Location == CardLocation.MonsterZone, + (c) => c.Location == CardLocation.Hand, + }; + if (selectedFusionMaterial.Count == 0) + { + if (fusionTarget.IsOriginalCode(CardId.DespianQuaeritis)) + { + foreach (Func func in funcList) + { + List cardsWithFunc = cards.Where(c => func(c) && c.HasSetcode(SetcodeDespain)).OrderBy(c => c.GetDefensePower()).ToList(); + if (cardsWithFunc.Count > 0) + { + selectedFusionMaterial.Add(cardsWithFunc[0]); + return Util.CheckSelectCount(cardsWithFunc, cards, min, max); + } + } + } + if (fusionTarget.IsCode(albazFusionMonster)) + { + foreach (Func func in funcList) + { + List cardsWithFunc = cards.Where(c => func(c) && c.IsCode(CardId.FallenOfAlbaz)).OrderBy(c => c.GetDefensePower()).ToList(); + if (cardsWithFunc.Count > 0) + { + selectedFusionMaterial.Add(cardsWithFunc[0]); + return Util.CheckSelectCount(cardsWithFunc, cards, min, max); + } + } + } + } + if (fusionTarget.IsCode(CardId.AlbaLenatusTheAbyssDragon)) + { + // select non-albaz + if (selectedFusionMaterial.Count > 0) + { + funcList = new List> + { + (c) => c.IsFaceup() && c.Location == CardLocation.Removed, + (c) => c.Location == CardLocation.Grave && !CheckWhetherShouldKeepInGrave(c), + (c) => c.IsCode(CardId.LubellionTheSearingDragon), + }; + } + } + foreach (Func func in funcList) + { + List cardsWithFunc = cards.Where(c => func(c)).OrderBy(c => c.GetDefensePower()).ToList(); + if (cardsWithFunc.Count > 0) + { + selectedFusionMaterial.Add(cardsWithFunc[0]); + return Util.CheckSelectCount(cardsWithFunc, cards, min, max); + } + } + if (fusionTarget.IsOriginalCode(CardId.AlbaLenatusTheAbyssDragon) && cancelable) + { + return null; + } + } + break; + + // for granguignol + case CardId.GranguignolTheDuskDragon: + if (hint == HintMsg.ToGrave) + { + GranguignolTheDuskDragonSendToGYTarget(cards, out ClientCard target); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + if (hint == HintMsg.SpSummon) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.DespianQuaeritis, () => Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && c.Attack >= Util.GetBestPower(Bot) && !(c.HasType(CardType.Fusion) && c.Level >= 8)) }, + {CardId.GuidingQuemTheVirtuous, () => Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon) || Util.GetOneEnemyBetterThanValue(1500) == null }, + {CardId.DespianLuluwalilith, () => !(Duel.Player == 0 && Bot.HasInHandOrInSpellZone(CardId.BrandedFusion)) } + }; + + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = cards.FirstOrDefault(c => c.IsOriginalCode(pair.Key)); + if (target != null && pair.Value()) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for Quaeritis + case CardId.DespianQuaeritis: + { + Dictionary> checkDict = new Dictionary> + { + {CardId.FallenOfAlbaz, () => CheckAlbazFusion() }, + {CardId.GuidingQuemTheVirtuous, () => !DefaultCheckWhetherCardIdIsNegated(CardId.GuidingQuemTheVirtuous) }, + {CardId.AluberTheJesterOfDespia, () => !DefaultCheckWhetherCardIdIsNegated(CardId.AluberTheJesterOfDespia) }, + {CardId.DespianTragedy, () => true } + }; + + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for irondash dragon + case CardId.SprindTheIrondashDragon: + { + Dictionary> checkDict = new Dictionary> + { + {CardId.FallenOfAlbaz, () => CheckAlbazFusion() }, + {CardId.SpringansKitt, () => !DefaultCheckWhetherCardIdIsNegated(CardId.SpringansKitt) } + }; + + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for ash dragon + case CardId.TitanikladTheAshDragon: + { + Dictionary> checkDict = new Dictionary> + { + {CardId.FallenOfAlbaz, () => CheckAlbazFusion() }, + {CardId.GuidingQuemTheVirtuous, () => !DefaultCheckWhetherCardIdIsNegated(CardId.GuidingQuemTheVirtuous) } + }; + + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for rindrumm + case CardId.RindbrummTheStrikingDragon: + if (hint == HintMsg.SpSummon) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.FallenOfAlbaz, () => CheckAlbazFusion() }, + {CardId.RindbrummTheStrikingDragon, () => true }, + {CardId.AlbionTheShroudedDragon, () => true } + }; + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = cards.FirstOrDefault(c => c.IsOriginalCode(pair.Key)); + if (target != null && pair.Value()) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + if (hint == HintMsg.ReturnToHand) + { + List problemList = GetProblematicEnemyCardList(false, true, CardType.Monster).Intersect(cards).OrderByDescending(c => c.GetDefensePower()).ToList(); + if (problemList.Count > 0) + { + return Util.CheckSelectCount(problemList, cards, min, max); + } + ClientCard worstBotMonster = Util.GetWorstBotMonster(); + int worstBotPower = worstBotMonster == null ? 0 : worstBotMonster.GetDefensePower(); + List dangerList = cards.Where(c => c.IsFaceup() && c.Controller == 1 && c.GetDefensePower() > worstBotPower).OrderByDescending(c => c.GetDefensePower()).ToList(); + if (dangerList.Count > 0) + { + return Util.CheckSelectCount(dangerList, cards, min, max); + } + List checkIdList = new List { CardId.AluberTheJesterOfDespia, CardId.SpringansKitt }; + foreach (int checkId in checkIdList) + { + ClientCard target = cards.FirstOrDefault(c => c.Controller == 0 && c.IsCode(checkId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + List enemyMonsterList = cards.Where(c => c.Controller == 1).OrderByDescending(c => c.GetDefensePower()).ToList(); + if (enemyMonsterList.Count > 0) + { + return Util.CheckSelectCount(enemyMonsterList, cards, min, max); + } + return Util.CheckSelectCount(cards.Where(c => c.Controller == 0).OrderByDescending(c => c.GetDefensePower()).ToList(), cards, min, max); + } + break; + + // for branded dragon + case CardId.AlbionTheBrandedDragon: + if (hint == HintMsg.SpSummon) + { + AlbionTheBrandedDragonFusionTarget(cards, out ClientCard target); + if (target != null) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + if (hint == HintMsg.FusionMaterial && fusionTarget != null) + { + if (fusionTarget.IsCode(CardId.BorreloadFuriousDragon)) + { + // select 2 dark dragon monster + foreach (CardLocation loc in new[] { CardLocation.Grave, CardLocation.Hand, CardLocation.MonsterZone }) + { + List cardsInLoc = cards.Where(c => c.Location == loc).OrderBy(c => c.GetDefensePower()).ToList(); + int banishedAlbazCount = Bot.Banished.Where(c => c.IsOriginalCode(CardId.FallenOfAlbaz)).Count(); + banishedAlbazCount += selectedFusionMaterial.Where(c => c.IsOriginalCode(CardId.FallenOfAlbaz)).Count(); + foreach (ClientCard target in cardsInLoc) + { + // keep albaz + if (target.IsOriginalCode(CardId.FallenOfAlbaz) && banishedAlbazCount > 0) + { + continue; + } + selectedFusionMaterial.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + if (fusionTarget.IsCode(CardId.DespianQuaeritis)) + { + // select despain + if (selectedFusionMaterial.Count == 0) + { + foreach (CardLocation loc in new[] { CardLocation.Grave, CardLocation.Hand, CardLocation.MonsterZone }) + { + List cardsInLoc = cards.Where(c => c.Location == loc && c.HasSetcode(SetcodeDespain) && (loc != CardLocation.Grave || !CheckWhetherShouldKeepInGrave(c))) + .OrderBy(c => c.GetDefensePower()).ToList(); + if (cardsInLoc.Count > 0) + { + selectedFusionMaterial.Add(cardsInLoc[0]); + return Util.CheckSelectCount(cardsInLoc, cards, min, max); + } + } + } + // select light/dark + else + { + foreach (CardLocation loc in new[] { CardLocation.Grave, CardLocation.Hand, CardLocation.MonsterZone }) + { + List cardsInLoc = cards.Where(c => c.Location == loc && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark) && (loc != CardLocation.Grave || !CheckWhetherShouldKeepInGrave(c))) + .OrderBy(c => c.GetDefensePower()).ToList(); + if (cardsInLoc.Count > 0) + { + if (!activatedCardIdList.Contains(CardId.TriBrigadeMercourier + 1)) + { + ClientCard mercourier = cardsInLoc.FirstOrDefault(c => c.IsCode(CardId.TriBrigadeMercourier)); + if (mercourier != null) + { + selectedFusionMaterial.Add(mercourier); + return Util.CheckSelectCount(new List { mercourier }, cards, min, max); + } + } + if (!activatedCardIdList.Contains(CardId.DespianTragedy) && CheckRemainInDeck(CardId.AluberTheJesterOfDespia, CardId.GuidingQuemTheVirtuous) > 0) + { + ClientCard tragedy = cardsInLoc.FirstOrDefault(c => c.IsCode(CardId.DespianTragedy)); + if (tragedy != null) + { + selectedFusionMaterial.Add(tragedy); + return Util.CheckSelectCount(new List { tragedy }, cards, min, max); + } + } + + selectedFusionMaterial.Add(cardsInLoc[0]); + return Util.CheckSelectCount(cardsInLoc, cards, min, max); + } + } + } + } + if (fusionTarget.IsCode(albazFusionMonster)) + { + // selecting albaz + if (selectedFusionMaterial.Count == 0) + { + foreach (CardLocation loc in new[] { CardLocation.Grave, CardLocation.MonsterZone, CardLocation.Hand }) + { + ClientCard albaz = cards.Where(c => c.IsCode(CardId.FallenOfAlbaz) && c.Location == loc).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (albaz != null) + { + selectedFusionMaterial.Add(albaz); + return Util.CheckSelectCount(new List { albaz }, cards, min, max); + } + } + } + else + { + if (fusionTarget.IsOriginalCode(CardId.AlbaLenatusTheAbyssDragon) && cancelable) + { + return null; + } + List> funcList = new List> + { + (c) => c.Location == CardLocation.Grave && !CheckWhetherShouldKeepInGrave(c), + (c) => c.Location == CardLocation.MonsterZone && c.GetDefensePower() <= 2000, + (c) => c.Location == CardLocation.Grave, + (c) => c.Location == CardLocation.Hand, + (c) => c.Location == CardLocation.MonsterZone + }; + foreach (Func func in funcList) + { + List targetList = cards.Where(c => func(c)).OrderBy(c => c.GetDefensePower()).ToList(); + if (targetList.Count > 0) + { + selectedFusionMaterial.Add(targetList[0]); + return Util.CheckSelectCount(new List { targetList[0] }, cards, min, max); + } + } + } + } + } + if (hint == HintMsg.OperateCard) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.BrandedInHighSpirits, () => Bot.HasInMonstersZone(CardId.GuidingQuemTheVirtuous) && BrandedInHighSpiritsActivateCheck() }, + {CardId.BrightestBlazingBrandedKing, () => Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.IsCode(albazFusionMonster)) }, + {CardId.BrandedInRed, () => Bot.Graveyard.Any(c => c != null && (c.HasSetcode(SetcodeDespain) || c.IsCode(CardId.FallenOfAlbaz))) }, + {CardId.BrandedRetribution, () => Bot.Graveyard.Where(c => c != null && c.IsCode(albazFusionMonster)).Count() > 1 }, + {CardId.BrandedFusion, () => CheckRemainInDeck(CardId.FallenOfAlbaz) > 0 }, + {CardId.BrandedBeast, () => Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeBystial)) }, + {CardId.BrandedLost, () => true }, + {CardId.BrandedInWhite, () => true } + }; + + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = cards.FirstOrDefault(c => c.IsOriginalCode(pair.Key)); + if (target != null && pair.Value()) + { + fusionTarget = target; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + + // for luluwa + case CardId.DespianLuluwalilith: + if (hint == HintMsg.Disable) + { + List enemyCardList = cards.Where(c => c.IsFaceup() && c.Controller == 1).ToList(); + List problemCardList = GetProblematicEnemyCardList(false, false, 0).Intersect(enemyCardList).ToList(); + if (problemCardList.Count > 0) + { + return Util.CheckSelectCount(ShuffleList(problemCardList), cards, min, max); + } + List monsterList = GetMonsterListForTargetNegate(false, 0).Intersect(enemyCardList).ToList(); + if (monsterList.Count > 0) + { + return Util.CheckSelectCount(ShuffleList(monsterList), cards, min, max); + } + if (enemyCardList.Count > 0) + { + return Util.CheckSelectCount(ShuffleList(enemyCardList), cards, min, max); + } + } + if (hint == HintMsg.SpSummon) + { + foreach (CardLocation loc in new[] { CardLocation.Deck, CardLocation.Hand }) + { + foreach (int checkId in new List { CardId.BlazingCartesiaTheVirtuous, CardId.GuidingQuemTheVirtuous }) + { + ClientCard target = cards.FirstOrDefault(c => c.Location == loc && c.IsOriginalCode(checkId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + } + break; + + default: + break; + } + } + + // drop 1 hand + bool discardHand = hint == HintMsg.Discard; + bool handToDeck = hint == HintMsg.ToDeck && cards.All(c => c.Location == CardLocation.Hand); + if (min == 1 && max == 1 && (discardHand || handToDeck)) + { + if (currentSolvingChain != null && currentSolvingChain.IsCode(CardId.BrandedOpening)) + { + ClientCard tragedy = cards.FirstOrDefault(card => card.IsCode(CardId.DespianTragedy)); + if (tragedy != null) + { + return Util.CheckSelectCount(new List { tragedy }, cards, min, max); + } + } + if (discardHand) + { + // discard activating shrouded + foreach (ClientCard target in cards) + { + if (target.IsCode(CardId.AlbionTheShroudedDragon) && Duel.CurrentChain.Contains(target)) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + + List discardList = new List { + CardId.BrandedRetribution, CardId.AlbionTheShroudedDragon, CardId.BystialSaronir, CardId.BrightestBlazingBrandedKing, + CardId.BrandedInHighSpirits, CardId.BlazingCartesiaTheVirtuous, CardId.DespianTragedy }; + foreach (int id in discardList) + { + ClientCard card = cards.FirstOrDefault(c => c.IsCode(id)); + if (card != null) + { + return Util.CheckSelectCount(new List { card }, cards, min, max); + } + } + } + // return dump card + foreach (ClientCard card in cards) + { + if (cards.Where(c => c.IsCode(card.Id)).Count() > 1) + { + return Util.CheckSelectCount(new List { card }, cards, min, max); + } + } + List improperCardIdList = new List + { + CardId.BrandedRetribution, CardId.BrandedInHighSpirits, CardId.DespianTragedy, CardId.FusionDeployment, CardId.BrandedBeast, + CardId.AlbionTheShroudedDragon, CardId.BrandedOpening, CardId.GoldSarcophagus, CardId.FoolishBurial, CardId.FallenOfAlbaz, + CardId.BrandedInRed, _CardId.InfiniteImpermanence, CardId.TheBystialLubellion, CardId.BrandedLost, CardId.SpringansKitt, + CardId.GuidingQuemTheVirtuous, _CardId.CrossoutDesignator, _CardId.CalledByTheGrave, CardId.TriBrigadeMercourier, _CardId.AshBlossom, _CardId.MaxxC + }; + foreach (int id in improperCardIdList) + { + if (id == CardId.BrandedLost && Bot.HasInHand(CardId.BrandedFusion) && BrandedFusionActivateCheck()) continue; + ClientCard target = cards.FirstOrDefault(c => c.IsCode(id)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + else if (discardHand && min > 0 && min == max) + { + List discardList = new List(); + List graveEffectIdList = new List { CardId.AlbionTheShroudedDragon, CardId.BrandedRetribution, CardId.BrandedInHighSpirits, + CardId.BrightestBlazingBrandedKing, CardId.DespianTragedy }; + discardList.AddRange(ShuffleList(cards.Where(c => c.IsCode(graveEffectIdList)).ToList())); + List remainHandList = cards.Except(discardList).ToList(); + + HashSet seenIds = new HashSet(); + for (int idx = remainHandList.Count - 1; idx >= 0; idx --) + { + ClientCard currentCard = remainHandList[idx]; + if (!seenIds.Add(currentCard.Id)) + { + discardList.Add(currentCard); + remainHandList.Remove(currentCard); + } + } + + List improperCardIdList = new List + { + CardId.FusionDeployment, CardId.BrandedBeast, CardId.AlbionTheShroudedDragon, CardId.BrandedOpening, CardId.GoldSarcophagus, + CardId.FoolishBurial, CardId.FallenOfAlbaz, CardId.BrandedInRed, _CardId.InfiniteImpermanence, CardId.TheBystialLubellion, + CardId.BrandedLost, CardId.SpringansKitt, CardId.GuidingQuemTheVirtuous, _CardId.CrossoutDesignator, _CardId.CalledByTheGrave, + CardId.TriBrigadeMercourier, _CardId.AshBlossom, _CardId.MaxxC + }; + foreach (int id in improperCardIdList) + { + ClientCard target = remainHandList.FirstOrDefault(c => c.IsCode(id)); + if (target != null) + { + discardList.Add(target); + } + } + if (discardList.Count > min) + { + discardList = discardList.Take(min).ToList(); + } + + return Util.CheckSelectCount(discardList, cards, min, max); + } + + // for The Bystial Lubellion + if (theBystialLubellionSelecting) + { + theBystialLubellionSelecting = false; + ClientCard target = TheBystialLubellionSpSummonCost(cards); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } else + { + List targetList = new List(cards); + targetList.Sort(CardContainer.CompareCardAttack); + return Util.CheckSelectCount(targetList, cards, min, max); + } + } + + // for shrouded/saronir + if (albionTheShroudedDragonSelecting || (currentSolvingChain != null && currentSolvingChain.IsCode(CardId.BystialSaronir))) + { + // send retribution first + ClientCard retribution = cards.FirstOrDefault(c => c.IsCode(CardId.BrandedRetribution)); + if (retribution != null) + { + if (retribution.Location == CardLocation.Deck || Bot.GetGraveyardMonsters().Where(c => c.IsCode(albazFusionMonster)).Count() < 2) + { + return Util.CheckSelectCount(new List { retribution }, cards, min, max); + } + } + // send spells to recycle + if (Bot.HasInGraveyard(CardId.BrandedRetribution) || (Bot.HasInGraveyard(CardId.DespianTragedy) && !activatedCardIdList.Contains(CardId.DespianTragedy))) + { + Dictionary> deckCheckDict = new Dictionary>{ + {CardId.BrandedFusion, () => BrandedFusionActivateCheck()}, + {CardId.BrandedLost, () => { + if (Duel.Player == 0 && Duel.Phase >= DuelPhase.End) return false; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedFusion) && BrandedFusionActivateCheck()) return true; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedInWhite) && BrandedInWhiteActivateCheck()) return true; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedInRed) && BrandedInRedActivateCheck() != null) return true; + if (!summoned && Bot.HasInHand(CardId.FallenOfAlbaz) && CheckAlbazFusion()) return true; + if ((Bot.HasInMonstersZone(CardId.BlazingCartesiaTheVirtuous) || (!summoned && Bot.HasInHand(CardId.BlazingCartesiaTheVirtuous)))) return true; + return false; + } }, + {CardId.BrandedInHighSpirits, BrandedInHighSpiritsActivateCheck}, + {CardId.BrandedInRed, () => BrandedInRedActivateCheck() != null }, + {CardId.BrandedInWhite, BrandedInWhiteActivateCheck }, + {CardId.BrandedRetribution, () => cards.Any(c => c.IsCode(CardId.BrandedRetribution) && c.Location == CardLocation.Removed) }, + {CardId.BrightestBlazingBrandedKing, () => Bot.GetMonsters().Any(c => c.IsFaceup() && c.IsCode(albazFusionMonster)) }, + {CardId.BrandedOpening, () => Bot.Hand.Count > 2 } + }; + foreach (KeyValuePair> pair in deckCheckDict) + { + ClientCard target = cards.FirstOrDefault(card => card.Location == CardLocation.Deck && card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + + // for abyss dragon + if (albionTheShroudedDragonSelecting && + FallenOfAlbazSetCheck() && (summoned || !Bot.HasInHand(new List { CardId.FallenOfAlbaz, CardId.BrandedInHighSpirits }))) + { + List checkIdList = new List { + CardId.BrandedRetribution, CardId.BrandedInHighSpirits, CardId.BrightestBlazingBrandedKing, CardId.BrandedInWhite, CardId.BrandedOpening, + CardId.BrandedInRed, CardId.BrandedBeast, CardId.BrandedLost + }; + if (!BrandedFusionActivateCheck()) + { + checkIdList.Add(CardId.BrandedFusion); + } + foreach (int checkId in checkIdList) + { + ClientCard target = cards.FirstOrDefault(c => c.Id == checkId); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + + // send from deck + List checkList = new List { CardId.BrandedInHighSpirits, CardId.BrandedOpening, CardId.BrightestBlazingBrandedKing, CardId.BrandedBeast, CardId.BrandedLost }; + foreach (int checkId in checkList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(checkId) && c.Location == CardLocation.Deck); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + return Util.CheckSelectCount(ShuffleList(new List(cards)), cards, min, max); + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + public override int OnSelectOption(IList options) + { + ChainInfo currentSolvingChain = Duel.GetCurrentSolvingChainInfo(); + if (currentSolvingChain != null) + { + // 1190=Add to Hand, 1152=Special Summon + if (options.Count == 2 && options.Contains(1190) && options.Contains(1152)) + { + if (currentSolvingChain.IsCode(CardId.BrandedOpening)) + { + return (CheckShouldNoMoreSpSummon() && !summoned && Duel.Player == 0) ? options.IndexOf(1190) : options.IndexOf(1152); + } + + if (fusionTarget != null && ( + currentSolvingChain.IsCode(CardId.DespianQuaeritis) + || currentSolvingChain.IsCode(CardId.TitanikladTheAshDragon) + || currentSolvingChain.IsCode(CardId.SprindTheIrondashDragon) + )) + { + if (fusionTarget.IsCode(CardId.FallenOfAlbaz)) + { + return CheckAlbazFusion() ? options.IndexOf(1152) : options.IndexOf(1190); + } + if (fusionTarget.IsCode(CardId.GuidingQuemTheVirtuous, CardId.SpringansKitt)) + { + return CheckShouldNoMoreSpSummon() ? options.IndexOf(1190) : options.IndexOf(1152); + } + if (fusionTarget.IsCode(CardId.AluberTheJesterOfDespia)) + { + return activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) ? options.IndexOf(1190) : options.IndexOf(1152); + } + return (CheckShouldNoMoreSpSummon() && !summoned) ? options.IndexOf(1190) : options.IndexOf(1152); + } + } + + // 1190=Add to Hand, 1153=Set + if (currentSolvingChain.IsCode(CardId.AlbionTheBrandedDragon) && fusionTarget != null) + { + if (fusionTarget.IsOriginalCode(CardId.BrandedInHighSpirits) && Duel.Player == 0) + { + return BrandedInHighSpiritsActivateCheck() ? options.IndexOf(1190) : options.IndexOf(1153); + } + if (fusionTarget.IsOriginalCode(CardId.BrandedInRed) && Duel.Player == 0) + { + if (nadirActivated) return options.IndexOf(1153); + return BrandedInRedActivateCheck() != null ? options.IndexOf(1190) : options.IndexOf(1153); + } + if (fusionTarget.Data != null) + { + bool setFlag = fusionTarget.Data.HasType(CardType.Trap); + setFlag |= fusionTarget.Data.HasType(CardType.QuickPlay) && Duel.Player == 0; + setFlag |= Bot.Hand.Count >= 6 && Duel.Player == 0; + return setFlag ? options.IndexOf(1153) : options.IndexOf(1190); + } + } + } + + return base.OnSelectOption(options); + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + ChainInfo currentSovingChain = Duel.GetCurrentSolvingChainInfo(); + if (currentSovingChain != null && currentSovingChain.ActivatePlayer == 0 && currentSovingChain.IsCode(CardId.SprindTheIrondashDragon)) + { + return SprindTheIrondashDragonMoveZone(available, null); + } + + if (player == 0 && location == CardLocation.MonsterZone) + { + List zoneIdList = ShuffleList(new List { 5, 6 }); + zoneIdList.AddRange(ShuffleList(new List { 0, 2, 4 })); + zoneIdList.AddRange(ShuffleList(new List { 1, 3 })); + foreach (int zoneId in zoneIdList) + { + int zone = (int)System.Math.Pow(2, zoneId); + if ((available & zone) != 0 && Bot.MonsterZone[zoneId] == null) + { + return zone; + } + } + } + return base.OnSelectPlace(cardId, player, location, available); + } + + public override bool OnSelectYesNo(int desc) + { + if (desc == Util.GetStringId(CardId.BrandedInHighSpirits, 2)) + { + if (CheckWhetherWillbeRemoved()) return false; + if (fusionTarget != null && fusionTarget.IsOriginalCode(CardId.TriBrigadeMercourier)) + { + return !Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.IsCode(albazFusionMonster)); + } + } + + if (desc == Util.GetStringId(CardId.RindbrummTheStrikingDragon, 2)) + { + bool checkFlag = Enemy.MonsterZone.Any(c => c != null); + checkFlag |= Bot.MonsterZone.Any(c => c != null && (c.IsOriginalCode(CardId.AluberTheJesterOfDespia) || c.IsOriginalCode(CardId.SpringansKitt))); + return checkFlag; + } + + if (desc == Util.GetStringId(CardId.DespianLuluwalilith, 2)) + { + bool checkFlag = Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && !c.IsDisabled()); + checkFlag |= Enemy.SpellZone.Any(c => c != null && c.IsFaceup() && !c.IsDisabled()); + return checkFlag; + } + + if (desc == Util.GetStringId(CardId.BrandedInRed, 0)) + { + // fix material list + brandedInRedMaterialList = brandedInRedMaterialList.Where(c => c != null && (c.Location == CardLocation.MonsterZone || c.Location == CardLocation.Hand)).ToList(); + + List materialList = Bot.MonsterZone.Where(c => c != null && c.Attack <= 2500 && !c.IsCode(cannotBeFusionMaterialIdList)).ToList(); + materialList.AddRange(Bot.Hand.Where(c => c.IsMonster() + && !(CheckWhetherCanSummon() && + ((!activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && c.IsCode(CardId.AluberTheJesterOfDespia)) + || (!activatedCardIdList.Contains(CardId.SpringansKitt) && c.IsCode(CardId.SpringansKitt))) + ) + ) + ); + + BrandedInRedFusionCheck(Bot.ExtraDeck, 0, + materialList, brandedInRedMaterialList, + out ClientCard _fusionTarget, out _); + + return _fusionTarget != null; + } + + if (desc == Util.GetStringId(CardId.SprindTheIrondashDragon, 2)) + { + ClientCard currentSolvingChain = Duel.GetCurrentSolvingChainCard(); + if (currentSolvingChain != null) + { + int value = SprindTheIrondashDragonDestroyValue(currentSolvingChain.Sequence); + return value > 0; + } + } + + return base.OnSelectYesNo(desc); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + ClientCard currentSolvingChain = Duel.GetCurrentSolvingChainCard(); + if (currentSolvingChain != null && currentSolvingChain.IsCode(CardId.AlbionTheSanctifireDragon)) + { + sanctifireSelectPositionCount++; + if (sanctifireSelectPositionCount >= 2) + { + if (Duel.Phase <= DuelPhase.Main2) + { + return CardPosition.FaceUpDefence; + } + } + } + + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2) + { + bool turnDefense = false; + if (cardData.Attack <= cardData.Defense) + { + turnDefense = true; + } + if (turnDefense) + { + return CardPosition.FaceUpDefence; + } + } + if (Duel.Player == 1) + { + if (cardData.Defense >= cardData.Attack || Util.IsOneEnemyBetterThanValue(cardData.Attack, true)) + { + return CardPosition.FaceUpDefence; + } + } + int cardAttack = cardData.Attack; + int bestBotAttack = Math.Max(Util.GetBestAttack(Bot), cardAttack); + if (Util.IsAllEnemyBetterThanValue(bestBotAttack, true)) + { + return CardPosition.FaceUpDefence; + } + } + return base.OnSelectPosition(cardId, positions); + } + + public override void OnNewTurn() + { + if (Duel.Turn <= 1) + { + dimensionShifterCount = 0; + } + + summoned = false; + enemyActivateMaxxC = false; + enemyActivateLockBird = false; + enemyActivateInfiniteImpermanenceFromHand = false; + nadirActivated = false; + fusionToGYFlag = false; + spSummoningAlbaz = false; + cartesiaSummonGoal = 0; + sanctifireSelectPositionCount = 0; + quemSummonFlag = 0; + if (dimensionShifterCount > 0) dimensionShifterCount--; + cartesiaMaterialList.Clear(); + brandedInRedMaterialList.Clear(); + infiniteImpermanenceList.Clear(); + currentNegateCardList.Clear(); + currentDestroyCardList.Clear(); + sendToGYThisTurn.Clear(); + activatedCardIdList.Clear(); + enemyPlaceThisTurn.Clear(); + base.OnNewTurn(); + } + + public override void OnChaining(int player, ClientCard card) + { + Duel.LastChainTargets.Clear(); + if (card == null) return; + + if (player == 1) + { + if (card.IsCode(_CardId.InfiniteImpermanence)) + { + if (enemyActivateInfiniteImpermanenceFromHand) + { + enemyActivateInfiniteImpermanenceFromHand = false; + } + else + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == card) + { + infiniteImpermanenceList.Add(4 - i); + break; + } + } + } + } + } + base.OnChaining(player, card); + } + + public override void OnChainSolved(int chainIndex) + { + ChainInfo currentCard = Duel.GetCurrentSolvingChainInfo(); + if (currentCard != null) + { + // if activation is negated, it can activate again. + if (currentCard.ActivatePlayer == 0) + { + List activateCheck = new List { CardId.NadirServant, CardId.FusionDeployment, CardId.BrandedFusion, CardId.BrandedInRed }; + if (currentCard.IsCode(activateCheck)) + { + activatedCardIdList.Add(currentCard.ActivateId); + } + } + if (!Duel.IsCurrentSolvingChainNegated()) + { + if (currentCard.ActivatePlayer == 1) + { + if (currentCard.IsCode(_CardId.MaxxC)) + enemyActivateMaxxC = true; + if (currentCard.IsCode(_CardId.LockBird)) + enemyActivateLockBird = true; + if (currentCard.IsCode(CardId.DimensionShifter)) + dimensionShifterCount = 2; + } + if (currentCard.ActivatePlayer == 0 && currentCard.IsCode(CardId.NadirServant)) + { + nadirActivated = true; + } + } + } + fusionTarget = null; + selectedFusionMaterial.Clear(); + sanctifireSelectPositionCount = 0; + + base.OnChainSolved(chainIndex); + } + + public override void OnChainEnd() + { + cartesiaSummonGoal = 0; + cartesiaMaterialList.Clear(); + brandedInRedMaterialList.Clear(); + currentNegateCardList.Clear(); + currentDestroyCardList.Clear(); + enemyActivateInfiniteImpermanenceFromHand = false; + theBystialLubellionSelecting = false; + albionTheShroudedDragonSelecting = false; + spSummoningAlbaz = false; + for (int idx = enemyPlaceThisTurn.Count - 1; idx >= 0; idx--) + { + ClientCard checkTarget = enemyPlaceThisTurn[idx]; + if (checkTarget == null || (checkTarget.Location != CardLocation.SpellZone && checkTarget.Location != CardLocation.MonsterZone)) + { + enemyPlaceThisTurn.RemoveAt(idx); + } + } + if (quemSummonFlag > 0) quemSummonFlag--; + base.OnChainEnd(); + } + + public override void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + if (previousControler == 1) + { + if (card != null) + { + if (card.IsCode(_CardId.InfiniteImpermanence) && previousLocation == (int)CardLocation.Hand && currentLocation == (int)CardLocation.SpellZone) + enemyActivateInfiniteImpermanenceFromHand = true; + } + } + if (card != null) + { + if (currentControler == 1 && (currentLocation == (int)CardLocation.MonsterZone || currentLocation == (int)CardLocation.SpellZone)) + { + enemyPlaceThisTurn.Add(card); + } + if (currentControler == 0) + { + ClientCard currentSolvingChain = Duel.GetCurrentSolvingChainCard(); + if (previousLocation == (int)CardLocation.Grave && currentLocation != (int)CardLocation.Grave) + { + sendToGYThisTurn.Remove(card); + } + if (currentLocation == (int)CardLocation.Grave) + { + if (card.HasType(CardType.Fusion)) fusionToGYFlag = true; + sendToGYThisTurn.Add(card); + } + if (currentLocation == (int)CardLocation.MonsterZone && card != null && card.IsCode(CardId.GuidingQuemTheVirtuous)) + { + quemSummonFlag = 2; + } + } + } + + base.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + /// + /// Select spell/trap's place randomly to avoid InfiniteImpermanence and so on. + /// + /// Card to set(default current card) + /// Whether need to avoid InfiniteImpermanence + /// Whether need to avoid set in this place + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceList.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public bool TheBystialLubellionSpSummon() + { + if (Card.Location == CardLocation.Hand) + { + return false; + } + ClientCard costTarget = TheBystialLubellionSpSummonCost(Bot.GetMonsters()); + if (costTarget != null) + { + theBystialLubellionSelecting = true; + activatedCardIdList.Add(Card.Id - 1); + return true; + } + return false; + } + + public ClientCard TheBystialLubellionSpSummonCost(IList costList) + { + Dictionary> checkDict = new Dictionary>{ + {CardId.AlbionTheBrandedDragon, (card) => sendToGYThisTurn.All(c => !c.IsCode(CardId.AlbionTheBrandedDragon))}, + {CardId.BystialSaronir, (card) => !activatedCardIdList.Contains(CardId.BystialSaronir + 1) && !CheckWhetherWillbeRemoved() }, + {CardId.TitanikladTheAshDragon, (card) => Util.IsTurn1OrMain2() || card.GetDefensePower() < 2500 }, + {CardId.AlbaLenatusTheAbyssDragon, (card) => Util.IsTurn1OrMain2() || card.IsDisabled() || card.GetDefensePower() < 2500 }, + {CardId.AlbionTheShroudedDragon, (card) => Util.IsTurn1OrMain2() || card.GetDefensePower() < 2500 }, + {CardId.BorreloadFuriousDragon, (card) => card.IsDisabled() && CheckRemainInDeck(CardId.BrandedBeast, CardId.BrandedLost) > 0 }, + }; + + foreach (KeyValuePair> pair in checkDict) + { + List targetList = costList.Where(card => card.IsCode(pair.Key)).ToList(); + foreach (ClientCard target in targetList) + { + if (target != null && pair.Value(target)) + { + return target; + } + } + } + return null; + } + + public bool TheBystialLubellionActivate() + { + if (CheckWhetherNegated(true, Card.Location == CardLocation.MonsterZone, CardType.Monster)) return false; + if (Card.Location == CardLocation.Hand) + { + activatedCardIdList.Add(Card.Id); + } else + { + activatedCardIdList.Add(Card.Id + 1); + } + return true; + } + + public bool AlbionTheShroudedDragonActivate() + { + if (CheckWhetherNegated(true, false, CardType.Monster) || CheckWhetherWillbeRemoved()) return false; + bool checkFlag = CheckRemainInDeck(CardId.BrandedRetribution, CardId.BrandedOpening, CardId.BrightestBlazingBrandedKing, CardId.BrandedInHighSpirits) > 0; + if (Bot.HasInGraveyard(CardId.BrandedRetribution)) + { + checkFlag |= CheckRemainInDeck(CardId.BrandedFusion, CardId.BrandedBeast, CardId.BrandedInRed, CardId.BrandedInWhite, CardId.BrandedLost) > 0; + } + if (Bot.HasInSpellZone(CardId.BrandedBeast)) + { + checkFlag |= CheckRemainInDeck(CardId.BrandedLost) > 0; + } + if (Card.Location == CardLocation.Grave) + { + checkFlag |= CheckRemainInDeck(CardId.BrandedInWhite) > 0; + } + // for abyss dragon + if (FallenOfAlbazSetCheck() && (summoned || !Bot.HasInHand(new List { CardId.FallenOfAlbaz, CardId.BrandedInHighSpirits }))) + { + checkFlag |= Bot.HasInHand(new List { CardId.BrandedBeast, CardId.BrandedInHighSpirits, CardId.BrandedInWhite, CardId.BrandedInRed, CardId.BrandedLost, CardId.BrandedOpening, CardId.BrandedRetribution, CardId.BrightestBlazingBrandedKing }); + } + + if (checkFlag) + { + activatedCardIdList.Add(Card.Id); + albionTheShroudedDragonSelecting = true; + return true; + } + return false; + } + + public bool BystialSaronirActivate() + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + // banish & spsummon + if (Card.Location == CardLocation.Hand) + { + // banish enemy target + if (Util.GetLastChainCard() != null && Duel.LastChainPlayer == 1) + { + List chainTargetList = Duel.LastChainTargets.Where(c => CheckBystialCanBanish(c)).ToList(); + if (chainTargetList.Count > 0) + { + AI.SelectCard(chainTargetList); + currentDestroyCardList.Add(chainTargetList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + List enemyChainList = Duel.CurrentChain.Where(c => c != null && c.Controller == 1 && CheckBystialCanBanish(c) && !currentDestroyCardList.Contains(c)) + .OrderByDescending(c => c.GetDefensePower()).ToList(); + if (enemyChainList.Count > 0) + { + AI.SelectCard(enemyChainList); + currentDestroyCardList.Add(enemyChainList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + + // banish cards with effect + if (!CheckShouldNoMoreSpSummon()) + { + ClientCard mercourier = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsCode(CardId.TriBrigadeMercourier)); + if (mercourier != null && !activatedCardIdList.Contains(CardId.TriBrigadeMercourier + 1)) + { + AI.SelectCard(mercourier); + currentDestroyCardList.Add(mercourier); + activatedCardIdList.Add(Card.Id); + return true; + } + ClientCard tragedy = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsCode(CardId.DespianTragedy)); + if (tragedy != null && !activatedCardIdList.Contains(CardId.DespianTragedy)) + { + AI.SelectCard(tragedy); + currentDestroyCardList.Add(tragedy); + activatedCardIdList.Add(Card.Id); + return true; + } + if (Bot.HasInGraveyard(CardId.TheBystialLubellion) && !activatedCardIdList.Contains(CardId.TheBystialLubellion) + && Duel.Player == 0 && CheckRemainInDeck(CardId.BrandedLost, CardId.BrandedBeast) > 0 + && CurrentTiming == -1) + { + List targetList = Enemy.Graveyard.Where(c => c != null && CheckBystialCanBanish(c)).OrderByDescending(card => card.Attack).ToList(); + targetList.AddRange(Bot.Graveyard + .Where(c => c != null && CheckBystialCanBanish(c) && !c.IsCode(CardId.TheBystialLubellion) && !CheckWhetherShouldKeepInGrave(c)) + .OrderBy(card => card.Attack).ToList() + ); + if (targetList.Count > 0) + { + AI.SelectCard(targetList); + currentDestroyCardList.Add(targetList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + + // defense + if (Bot.UnderAttack && Bot.BattlingMonster == null) + { + List targetList = Enemy.Graveyard.Where(c => CheckBystialCanBanish(c)).OrderByDescending(c => c.GetDefensePower()).ToList(); + targetList.AddRange(Bot.Graveyard.Where(c => CheckBystialCanBanish(c)).OrderBy(c => c.GetDefensePower())); + if (targetList.Count > 0) + { + AI.SelectCard(targetList); + currentDestroyCardList.Add(targetList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + // trigger beast + if (Duel.Player == 1 && (Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2) + && !activatedCardIdList.Contains(CardId.BrandedBeast) && Bot.SpellZone.Any(c => c != null && c.IsCode(CardId.BrandedBeast) && (c.IsFacedown() || !c.IsDisabled())) + && !Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeBystial))) + { + List dangerList = GetProblematicEnemyCardList(true, false, CardType.Trap); + if (dangerList.Count > 0) + { + List targetList = Enemy.Graveyard.Where(c => CheckBystialCanBanish(c)).OrderByDescending(c => c.GetDefensePower()).ToList(); + targetList.AddRange(Bot.Graveyard.Where(c => CheckBystialCanBanish(c)).OrderBy(c => c.GetDefensePower())); + if (targetList.Count > 0) + { + AI.SelectCard(targetList); + currentDestroyCardList.Add(targetList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + + } + // send to GY + if (Card.Location == CardLocation.Grave && !CheckWhetherWillbeRemoved()) + { + if (Bot.HasInGraveyard(CardId.BrandedRetribution)) + { + activatedCardIdList.Add(Card.Id + 1); + return true; + } else if (CheckRemainInDeck(CardId.TheBystialLubellion, CardId.BrandedRetribution, CardId.BrandedInHighSpirits, CardId.BrightestBlazingBrandedKing, CardId.BrandedOpening) > 0) + { + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + return false; + } + + public bool CheckBystialCanBanish(ClientCard c) + { + return c != null && c.Location == CardLocation.Grave && c.IsMonster() && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark); + } + + public bool AluberTheJesterOfDespiaSummon() + { + if (CheckWhetherNegated(true, true, CardType.Monster) || enemyActivateLockBird || activatedCardIdList.Contains(Card.Id)) return false; + summoned = true; + return true; + } + + public bool AluberTheJesterOfDespiaActivate() + { + // search + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + // spsummon + else + { + List targetCardList = GetMonsterListForTargetNegate(true, CardType.Monster); + ClientCard lastChainCard = Util.GetLastChainCard(); + // chain to protect + if (lastChainCard != null && lastChainCard.Controller == 0) + { + AI.SelectCard(targetCardList); + activatedCardIdList.Add(Card.Id); + return true; + } + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + AI.SelectCard(targetCardList); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + public bool FallenOfAlbazSummon() + { + if (CheckAlbazFusion(Card)) + { + summoned = true; + return true; + } + return false; + } + + public bool FallenOfAlbazSet() + { + if (FallenOfAlbazSetCheck()) + { + summoned = true; + return true; + } + return false; + } + + public bool FallenOfAlbazSetCheck() + { + if (!Bot.HasInExtra(CardId.AlbaLenatusTheAbyssDragon) || nadirActivated) return false; + // check dangerous dragon + if (!Bot.HasInSpellZone(CardId.BrandedLost, true, true) || Bot.GetHandCount() < 2) + { + foreach (int dangerId in dangerousDragonIdList) + { + if (Enemy.HasInMonstersZone(dangerId, true, false, true)) + { + return true; + } + } + } + // check dragon count + int dragonCount = Enemy.GetMonsters().Where(c => c != null && c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasRace(CardRace.Dragon)).Count(); + if (dragonCount > 1) + { + return true; + } + return false; + } + + /// + /// Check whether should call albaz. + /// + /// + /// + public bool CheckAlbazFusion(ClientCard exceptCost = null) { + return CheckAlbazFusion(exceptCost, out _); + } + + public bool CheckAlbazFusion(ClientCard exceptCost, out List enemyMonsterList) + { + enemyMonsterList = null; + int costHandCount = Bot.Hand.Where(c => c != exceptCost).Count(); + if (costHandCount <= 0 || Enemy.GetMonsterCount() == 0) return false; + if (CheckWhetherNegated(true, true, CardType.Monster) || activatedCardIdList.Contains(CardId.FallenOfAlbaz) || nadirActivated) return false; + if (!Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) && !Bot.HasInSpellZone(CardId.MirrorjadeTheIcebladeDragon) + && Bot.HasInExtra(CardId.MirrorjadeTheIcebladeDragon)) + { + ClientCard target = Enemy.GetMonsters() + .Where(c => c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (target != null) + { + enemyMonsterList = new List { target }; + return true; + } + } + if (Bot.HasInExtra(CardId.AlbaLenatusTheAbyssDragon)) + { + List targetList = Enemy.GetMonsters().Where(c => c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasRace(CardRace.Dragon)) + .OrderByDescending(c => c.GetDefensePower()).ToList(); + if (targetList.Count > 0) + { + enemyMonsterList = targetList; + return true; + } + } + if (Bot.HasInExtra(CardId.AlbionTheBrandedDragon)) + { + ClientCard target = Enemy.GetMonsters() + .Where(c => c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Light)) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (target != null) + { + enemyMonsterList = new List { target }; + return true; + } + } + if (Bot.HasInExtra(CardId.AlbionTheSanctifireDragon)) + { + ClientCard target = Enemy.GetMonsters() + .Where(c => c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Light) && c.HasRace(CardRace.SpellCaster)) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (target != null) + { + enemyMonsterList = new List { target }; + return true; + } + } + if (Bot.HasInExtra(CardId.LubellionTheSearingDragon)) + { + ClientCard target = Enemy.GetMonsters() + .Where(c => c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Dark)) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (costHandCount >= 2 && target != null) + { + enemyMonsterList = new List { target }; + return true; + } + } + if (Bot.HasInExtra(CardId.BorreloadFuriousDragon)) + { + ClientCard target = Enemy.GetMonsters() + .Where(c => c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasRace(CardRace.Dragon) && c.HasAttribute(CardAttribute.Dark)) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (target != null) + { + enemyMonsterList = new List { target }; + return true; + } + } + if (Bot.HasInExtra(CardId.TitanikladTheAshDragon)) + { + ClientCard target = Enemy.GetMonsters() + .Where(c => c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.Attack >= 2500) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (target != null) + { + enemyMonsterList = new List { target }; + return true; + } + } + if (Bot.HasInExtra(CardId.RindbrummTheStrikingDragon)) + { + ClientCard target = Enemy.GetMonsters() + .Where(c => c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasRace(CardRace.Beast | CardRace.BeastWarrior | CardRace.WindBeast)) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (target != null) + { + enemyMonsterList = new List { target }; + return true; + } + } + if (Bot.HasInExtra(CardId.SprindTheIrondashDragon)) + { + ClientCard target = Enemy.GetMonsters() + .Where(c => c != null && c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && enemyPlaceThisTurn.Contains(c) && c.IsSpecialSummoned + && c.GetDefensePower() >= Util.GetBestPower(Bot)) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (target != null) + { + enemyMonsterList = new List { target }; + return true; + } + } + + return false; + } + + public bool FallenOfAlbazActivate() + { + if (Bot.HasInExtra(CardId.AlbaLenatusTheAbyssDragon) && Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && c.IsCode(dangerousDragonIdList))) return false; + if (CheckAlbazFusion()) + { + activatedCardIdList.Add(Card.Id); + return true; + } + return false; + } + + public bool SpringansKittSummon() + { + if (CheckWhetherNegated(true, true, CardType.Monster) || enemyActivateLockBird || activatedCardIdList.Contains(Card.Id + 1)) return false; + summoned = true; + return true; + } + + public bool SpringansKittActivate() + { + // spsummon + if (Card.Location == CardLocation.Hand) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + if (CheckShouldNoMoreSpSummon()) + { + bool skipFlag = !summoned; + skipFlag |= activatedCardIdList.Contains(CardId.BrandedFusion); + skipFlag |= Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)); + if (skipFlag) + { + return false; + } + } + activatedCardIdList.Add(Card.Id); + return true; + } + // search + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public bool GuidingQuemTheVirtuousSummon() + { + if (CheckWhetherNegated(true, true, CardType.Monster) || CheckWhetherWillbeRemoved()) return false; + if (activatedCardIdList.Contains(Card.Id)) return false; + summoned = true; + return true; + } + + public bool GuidingQuemTheVirtuousSummonForSearch() + { + if (CheckWhetherNegated(true, true, CardType.Monster) || CheckWhetherWillbeRemoved()) return false; + if (activatedCardIdList.Contains(Card.Id)) return false; + if (Bot.HasInGraveyard(CardId.BrandedRetribution) && CheckRemainInDeck(CardId.BrandedFusion, CardId.BrandedLost, CardId.BrandedInWhite, CardId.BrandedInRed) > 0) + { + summoned = true; + return true; + } + if (Bot.HasInGraveyard(new[] { CardId.BrandedFusion, CardId.BrandedLost, CardId.BrandedBeast }) && CheckRemainInDeck(CardId.BrandedRetribution) > 0) + { + summoned = true; + return true; + } + return false; + } + + public bool GuidingQuemTheVirtuousActivate() + { + int desc = -1; + if (ActivateDescription >= Util.GetStringId(CardId.GuidingQuemTheVirtuous, 0)) + { + desc = ActivateDescription - Util.GetStringId(CardId.GuidingQuemTheVirtuous, 0); + } + Logger.DebugWriteLine("Guiding desc: " + desc.ToString()); + Logger.DebugWriteLine("Guiding timing: " + CurrentTiming.ToString()); + Logger.DebugWriteLine("Guiding flag: " + quemSummonFlag.ToString()); + + // spsummon + if ((ActivateDescription == -1 && quemSummonFlag == 0) || ActivateDescription == Util.GetStringId(CardId.GuidingQuemTheVirtuous, 1)) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + List>> checkList = new List>> + { + new KeyValuePair>(CardId.AlbionTheSanctifireDragon, (c) => c.IsCanRevive() && !activatedCardIdList.Contains(CardId.AlbionTheSanctifireDragon) ), + new KeyValuePair>(CardId.MirrorjadeTheIcebladeDragon, (c) => c.IsCanRevive() ), + new KeyValuePair>(CardId.FallenOfAlbaz, (c) => + { + bool albazCanFusionFlag = CheckAlbazFusion(null, out List materialList); + if (albazCanFusionFlag && !Util.ChainContainsCard(new[] {CardId.AlbionTheBrandedDragon, CardId.LubellionTheSearingDragon}) && !spSummoningAlbaz) + { + bool albazFlag = materialList.Count > 1; + if (materialList.Count > 0) + { + ClientCard material = materialList[0]; + albazFlag |= material.HasType(CardType.Ritual | CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link); + albazFlag |= material.IsFloodgate() || material.IsOneForXyz() || Util.GetWorstBotMonster().GetDefensePower() < material.Attack; + } + return albazFlag; + } + return false; + } ), + new KeyValuePair>(CardId.AlbionTheBrandedDragon, (c) => c.IsCanRevive() && Bot.HasInSpellZone(CardId.BrandedBeast) + && Bot.MonsterZone.Any(oc => oc != null && oc.IsFaceup() && oc.HasSetcode(SetcodeBystial)) ), + new KeyValuePair>(CardId.BlazingCartesiaTheVirtuous, (c) => Duel.Player == 0 || !activatedCardIdList.Contains(CardId.BlazingCartesiaTheVirtuous + 1) ), + new KeyValuePair>(CardId.TriBrigadeMercourier, (c) => Bot.MonsterZone.Any(oc => oc != null && oc.IsFaceup() && oc.IsCode(albazFusionMonster)) ), + new KeyValuePair>(CardId.AlbionTheSanctifireDragon, (c) => c.IsCanRevive() ), + new KeyValuePair>(CardId.SpringansKitt, (c) => true ) + }; + foreach (KeyValuePair> pair in checkList) + { + ClientCard target = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsOriginalCode(pair.Key) && pair.Value(c)); + if (target != null) + { + if (target.IsOriginalCode(CardId.FallenOfAlbaz)) + { + spSummoningAlbaz = true; + } + AI.SelectCard(target); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + // send to GY + if ((ActivateDescription == -1 && quemSummonFlag > 0) || ActivateDescription == Util.GetStringId(CardId.GuidingQuemTheVirtuous, 0)) + { + if (CheckWhetherNegated(true, true, CardType.Monster) || CheckWhetherWillbeRemoved()) return false; + quemSummonFlag = 0; + activatedCardIdList.Add(Card.Id); + return true; + } + return false; + } + + public bool BlazingCartesiaTheVirtuousSummon() + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + bool checkFlag = Bot.HasInHandOrInSpellZone(CardId.BrandedOpening) && !activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && CheckRemainInDeck(CardId.AluberTheJesterOfDespia) > 0; + checkFlag |= Bot.HasInHand(CardId.AlbionTheShroudedDragon) && !activatedCardIdList.Contains(CardId.AlbionTheShroudedDragon); + checkFlag |= Bot.HasInHandOrHasInMonstersZone(CardId.BystialSaronir) && !activatedCardIdList.Contains(CardId.BystialSaronir + 1); + if (Bot.HasInExtra(CardId.GranguignolTheDuskDragon)) + { + bool hasMaterial = Bot.Hand.Any(c => c != Card && c.Attack < 2000 && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark)); + hasMaterial |= Bot.MonsterZone.Any(c => c != null && !c.IsCode(cannotBeFusionMaterialIdList) && c.Attack < 2000 && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark)); + checkFlag |= hasMaterial; + } + + if (checkFlag) + { + summoned = true; + return true; + } + + return false; + } + + public bool BlazingCartesiaTheVirtuousActivate() + { + // sp summon + if (Card.Location == CardLocation.Hand) + { + if (CheckShouldNoMoreSpSummon() || CheckWhetherNegated(true, true, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + // fusion + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + if (Duel.CurrentChain.Any(c => c != null && c.Controller == 0 && c.IsCode(CardId.BrandedInRed))) return false; + List materialList = Bot.MonsterZone.Where(c => c != null && c.Attack <= 2500 && !c.IsCode(cannotBeFusionMaterialIdList)).ToList(); + materialList.AddRange(Bot.Hand.Where(c => c.IsMonster() + && !(CheckWhetherCanSummon() && + ((!activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && c.IsCode(CardId.AluberTheJesterOfDespia)) + || (!activatedCardIdList.Contains(CardId.SpringansKitt) && c.IsCode(CardId.SpringansKitt))) + ) + ) + ); + + // escape target + ClientCard lastCahinCard = Util.GetLastChainCard(); + if (lastCahinCard != null && Duel.LastChainPlayer == 1) + { + List chainTargetList = Duel.LastChainTargets.Where(c => c.Controller == 0 && c.Location == CardLocation.MonsterZone + && (!c.IsCode(cannotBeFusionMaterialIdList) || c.Attack <= 2500)).ToList(); + if (chainTargetList.Count > 0) + { + if (lastCahinCard.IsCode(targetNegateIdList)) + { + chainTargetList = chainTargetList.Where(c => c.Attack <= 2500).ToList(); + } + BlazingCartesiaTheVirtuousFusionCheck(Bot.ExtraDeck, 0, materialList, chainTargetList, + out ClientCard _fusionTarget, out List usedMaterialList); + + if (_fusionTarget != null) + { + Logger.DebugWriteLine("cartesia prepare fusion1: " + _fusionTarget.Name); + cartesiaMaterialList.AddRange(usedMaterialList.Intersect(chainTargetList)); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + + // fusion shrouded + bool skipShroudedFlag = CheckWhetherCanSummon() && !activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && Bot.HasInHand(CardId.AluberTheJesterOfDespia); + skipShroudedFlag |= CheckWhetherCanSummon() && !activatedCardIdList.Contains(CardId.SpringansKitt) && Bot.HasInHand(CardId.SpringansKitt); + if (!skipShroudedFlag) + { + ClientCard shrouded = Duel.CurrentChain.FirstOrDefault(c => c.Controller == 0 && c.Location == CardLocation.Hand && c.IsOriginalCode(CardId.AlbionTheShroudedDragon)); + if (shrouded != null) + { + BlazingCartesiaTheVirtuousFusionCheck(Bot.ExtraDeck, 0, materialList, new List { shrouded }, + out ClientCard _fusionTarget, out List usedMaterialList); + + if (_fusionTarget != null) + { + Logger.DebugWriteLine("cartesia prepare fusion2: " + _fusionTarget.Name); + cartesiaMaterialList.AddRange(usedMaterialList.Intersect(new List { shrouded })); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + + bool shouldActivateFlag = Duel.Player == 0 && !CheckShouldNoMoreSpSummon() || Duel.Player == 1; + + // summon mirrorjade + bool checkMirrorJadeFlag = !(Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) || Bot.HasInSpellZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true)) + && shouldActivateFlag; + if (checkMirrorJadeFlag) + { + BlazingCartesiaTheVirtuousFusionCheck(Bot.ExtraDeck, CardId.MirrorjadeTheIcebladeDragon, materialList, null, + out ClientCard _fusionTarget, out _); + + if (_fusionTarget != null) + { + Logger.DebugWriteLine("cartesia prepare fusion3: " + _fusionTarget.Name); + cartesiaSummonGoal = CardId.MirrorjadeTheIcebladeDragon; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + + // summon dusk dragon + if (shouldActivateFlag && Duel.Player == 0) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.BystialSaronir, () => !activatedCardIdList.Contains(CardId.BystialSaronir + 1) && !DefaultCheckWhetherCardIdIsNegated(CardId.BystialSaronir) }, + {CardId.DespianTragedy, () => !activatedCardIdList.Contains(CardId.DespianTragedy) && !DefaultCheckWhetherCardIdIsNegated(CardId.DespianTragedy) } + }; + foreach (KeyValuePair> pair in checkDict) + { + ClientCard targetMaterial = materialList.FirstOrDefault(c => c.IsCode(pair.Key)); + if (targetMaterial != null && pair.Value()) + { + BlazingCartesiaTheVirtuousFusionCheck(Bot.ExtraDeck, CardId.GranguignolTheDuskDragon, materialList, new List { targetMaterial }, + out ClientCard _fusionTarget, out List usedMaterialList); + if (_fusionTarget != null) + { + Logger.DebugWriteLine("cartesia prepare fusion4: " + _fusionTarget.Name); + cartesiaSummonGoal = CardId.GranguignolTheDuskDragon; + cartesiaMaterialList.Add(targetMaterial); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + } + + // summon sanctifire + if (shouldActivateFlag) + { + BlazingCartesiaTheVirtuousFusionCheck(Bot.ExtraDeck, CardId.AlbionTheSanctifireDragon, materialList, new List { Card}, + out ClientCard _fusionTarget, out List usedMaterialList); + if (_fusionTarget != null) + { + Logger.DebugWriteLine("cartesia prepare fusion5: " + _fusionTarget.Name); + cartesiaSummonGoal = CardId.AlbionTheSanctifireDragon; + cartesiaMaterialList.Add(Card); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + + if (shouldActivateFlag && GetProblematicEnemyMonster(0, true, true, CardType.Monster) != null) + { + BlazingCartesiaTheVirtuousFusionCheck(Bot.ExtraDeck, CardId.BorreloadFuriousDragon, materialList, null, + out ClientCard _fusionTarget, out _); + + if (_fusionTarget != null) + { + Logger.DebugWriteLine("cartesia prepare fusion6: " + _fusionTarget.Name); + cartesiaSummonGoal = CardId.BorreloadFuriousDragon; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + + if (shouldActivateFlag) + { + bool checkFlag = Duel.Player == 0 && CurrentTiming == -1; + checkFlag |= Duel.Player == 1 && (CurrentTiming & hintTimingMainEnd) != 0; + if (checkFlag) + { + BlazingCartesiaTheVirtuousFusionCheck(Bot.ExtraDeck, 0, materialList, null, + out ClientCard _fusionTarget, out _); + + if (_fusionTarget != null) + { + Logger.DebugWriteLine("cartesia prepare fusion7: " + _fusionTarget.Name); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + } + return false; + } + + public bool BlazingCartesiaTheVirtuousActivateInGrave() + { + // recycle + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id + 2); + return true; + } + return false; + } + + public void BlazingCartesiaTheVirtuousFusionCheck( + IList canSummonList, int mustSummonId, + List materialList, List mustMaterialList, + out ClientCard fusionTarget, out List selectedFusionMaterialList) + { + fusionTarget = null; + selectedFusionMaterialList = new List(); + + Dictionary>> checkDict = new Dictionary>> + { + {CardId.GranguignolTheDuskDragon, new List>{ + (c) => c.IsCode(CardId.BlazingCartesiaTheVirtuous), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark) + } }, + {CardId.AlbionTheSanctifireDragon, new List>{ + (c) => c.IsCode(CardId.FallenOfAlbaz), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Light) && c.HasRace(CardRace.SpellCaster) + } }, + {CardId.MirrorjadeTheIcebladeDragon, new List> + { + (c) => c.IsCode(CardId.FallenOfAlbaz), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) + } }, + {CardId.AlbionTheBrandedDragon, new List> + { + (c) => c.IsCode(CardId.FallenOfAlbaz), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Light) + } }, + {CardId.LubellionTheSearingDragon, new List> + { + (c) => c.IsCode(CardId.FallenOfAlbaz), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Dark) + } }, + {CardId.DespianQuaeritis, new List> + { + (c) => c.HasSetcode(SetcodeDespain), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark) + } }, + {CardId.BorreloadFuriousDragon, new List> + { + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Dark) && c.HasRace(CardRace.Dragon), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Dark) && c.HasRace(CardRace.Dragon) + } } + }; + Dictionary> extraCheckDict = new Dictionary> + { + {CardId.AlbionTheSanctifireDragon, (c1, c2) => + { + int reviveCount = Bot.Graveyard.Count(c => c != null && c.IsMonster() && c.IsCanRevive()); + reviveCount += Enemy.Graveyard.Count(c => c != null && c.IsMonster() && c.IsCanRevive()); + if (!CheckWhetherWillbeRemoved() || + (CurrentTiming & hintTimingMainEnd) > 0 && Util.GetOneEnemyBetterThanValue(Card.GetDefensePower()) != null + && Util.GetOneEnemyBetterThanValue(3000) == null) + { + reviveCount += 2; + } + return reviveCount >= 2; + } }, + {CardId.LubellionTheSearingDragon, (c1, c2) => Bot.Hand.Count(c => c != c1 && c != c2) > 0 }, + {CardId.MirrorjadeTheIcebladeDragon, (c1, c2) => !CheckWhetherWillbeRemoved() && + !Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) && !Bot.HasInSpellZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) } + }; + + foreach (KeyValuePair>> pair in checkDict) + { + if (mustSummonId > 0 && mustSummonId != pair.Key) continue; + ClientCard currentFusionTarget = canSummonList.FirstOrDefault(c => c != null && c.IsCode(pair.Key)); + if (currentFusionTarget == null) continue; + Func fusionFunc1 = pair.Value[0]; + Func fusionFunc2 = pair.Value[1]; + + if (mustMaterialList != null && mustMaterialList.Count > 0) + { + foreach (ClientCard mustMaterial in mustMaterialList) + { + if (!fusionFunc1(mustMaterial) && !fusionFunc2(mustMaterial)) continue; + foreach (ClientCard anotherMaterial in materialList) + { + if (anotherMaterial == mustMaterial) continue; + bool checkFlag = fusionFunc1(mustMaterial) && fusionFunc2(anotherMaterial); + checkFlag |= fusionFunc2(mustMaterial) && fusionFunc1(anotherMaterial); + extraCheckDict.TryGetValue(pair.Key, out Func extraCheckFunc); + checkFlag &= (extraCheckFunc == null || extraCheckFunc(mustMaterial, anotherMaterial)); + if (checkFlag) + { + fusionTarget = currentFusionTarget; + selectedFusionMaterialList.Add(mustMaterial); + selectedFusionMaterialList.Add(anotherMaterial); + return; + } + } + } + } + else + { + for (int index1 = 0; index1 < materialList.Count - 1; ++index1) + { + ClientCard material1 = materialList[index1]; + if (!fusionFunc1(material1) && !fusionFunc2(material1)) continue; + for (int index2 = index1 + 1; index2 < materialList.Count; ++index2) + { + ClientCard material2 = materialList[index2]; + bool checkFlag = fusionFunc1(material1) && fusionFunc2(material2); + checkFlag |= fusionFunc2(material1) && fusionFunc1(material2); + extraCheckDict.TryGetValue(pair.Key, out Func extraCheckFunc); + checkFlag &= (extraCheckFunc == null || extraCheckFunc(material1, material2)); + if (checkFlag) + { + fusionTarget = currentFusionTarget; + selectedFusionMaterial.Add(material1); + selectedFusionMaterial.Add(material2); + return; + } + } + } + } + } + } + + public bool TriBrigadeMercourierActivate() + { + // negate + if (Card.Location == CardLocation.Hand || Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, false, CardType.Monster) || !CheckLastChainShouldNegated()) return false; + if (Util.GetLastChainCard().Location == CardLocation.MonsterZone) currentNegateCardList.Add(Util.GetLastChainCard()); + activatedCardIdList.Add(Card.Id); + return true; + } + // search + if (Card.Location == CardLocation.Removed) + { + return false; + } + return false; + } + + public bool TriBrigadeMercourierActivateForSearch() + { + // negate + if (Card.Location == CardLocation.Hand || Card.Location == CardLocation.MonsterZone) + { + return false; + } + // search + if (Card.Location == CardLocation.Removed) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + return false; + } + + public bool AshBlossomActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (Util.GetLastChainCard().IsCode(_CardId.MaxxC)) return false; + if (DefaultAshBlossomAndJoyousSpring()) + { + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard.Location == CardLocation.MonsterZone || lastChainCard.Location == CardLocation.SpellZone) currentNegateCardList.Add(Util.GetLastChainCard()); + return true; + } + return false; + } + + public bool MaxxCActivate() + { + if (CheckWhetherNegated(true) || Duel.LastChainPlayer == 0) return false; + return DefaultMaxxC(); + } + + public bool DespianTragedyActivate() + { + // search + if (ActivateDescription != Util.GetStringId(Card.Id, 1)) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + // set + else { + if (CheckWhetherNegated(true, false, CardType.Trap)) return false; + Dictionary> checkDict = new Dictionary>{ + {CardId.BrandedFusion, () => BrandedFusionActivateCheck()}, + {CardId.BrandedLost, () => { + if (Duel.Player == 0 && Duel.Phase >= DuelPhase.End) return false; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedFusion) && BrandedFusionActivateCheck()) return true; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedInWhite) && BrandedInWhiteActivateCheck()) return true; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedInRed) && BrandedInRedActivateCheck() != null) return true; + if (!summoned && Bot.HasInHand(CardId.FallenOfAlbaz) && CheckAlbazFusion()) return true; + if ((Bot.HasInMonstersZone(CardId.BlazingCartesiaTheVirtuous) || (!summoned && Bot.HasInHand(CardId.BlazingCartesiaTheVirtuous)))) return true; + return false; + } }, + {CardId.BrandedInHighSpirits, BrandedInHighSpiritsActivateCheck}, + {CardId.BrandedInRed, () => BrandedInRedActivateCheck() != null }, + {CardId.BrandedInWhite, BrandedInWhiteActivateCheck }, + {CardId.BrightestBlazingBrandedKing, () => Bot.GetMonsters().Any(c => c.IsFaceup() && c.IsCode(albazFusionMonster)) }, + {CardId.BrandedOpening, () => Bot.Hand.Count > 2 && !activatedCardIdList.Contains(CardId.BrandedOpening) } + }; + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = Bot.Graveyard.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + activatedCardIdList.Add(Card.Id); + AI.SelectCard(target); + SelectSTPlace(target, true); + return true; + } + } + } + return false; + } + + public bool DespianTragedySet() + { + if (Bot.Graveyard.Any(c => c != null && c.HasType(CardType.Spell | CardType.Trap) && c.HasSetcode(SetcodeBranded))) + { + summoned = true; + return true; + } + + return false; + } + + public bool NadirServantActivate() + { + if (CheckWhetherNegated(true, true, CardType.Spell) || CheckWhetherWillbeRemoved()) return false; + bool checkResult = NadirServantActivateCheck(null, false, out _); + if (checkResult) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public bool NadirServantActivateCheck(IList cards, bool force, out ClientCard target) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.AlbionTheBrandedDragon, () => !sendToGYThisTurn.Any(c => c.IsCode(CardId.AlbionTheBrandedDragon)) }, + {CardId.DespianLuluwalilith, () => CheckRemainInDeck(CardId.BlazingCartesiaTheVirtuous, CardId.GuidingQuemTheVirtuous) > 0 }, + {CardId.TitanikladTheAshDragon, () => CheckRemainInDeck(CardId.GuidingQuemTheVirtuous) > 0 }, + {CardId.SprindTheIrondashDragon, () => CheckRemainInDeck(CardId.SpringansKitt) > 0 }, + {CardId.RindbrummTheStrikingDragon, () => Bot.Graveyard.Any(c => c != null && c.IsOriginalCode(CardId.FallenOfAlbaz)) }, + {CardId.AlbaLenatusTheAbyssDragon, () => force && CheckRemainInDeck(CardId.FusionDeployment, CardId.BrandedFusion) > 0 }, + {CardId.GranguignolTheDuskDragon, () => force}, + }; + + foreach (KeyValuePair> pair in checkDict) + { + if (cards == null) + { + if (Bot.HasInExtra(pair.Key) && pair.Value()) + { + target = null; + return true; + } + } else + { + ClientCard tg = cards.FirstOrDefault(c => c.IsOriginalCode(pair.Key)); + if (tg != null && pair.Value()) + { + target = tg; + return true; + } + } + } + + target = null; + return false; + } + + public bool FusionDeploymentActivate() + { + if (CheckWhetherNegated(true, true, CardType.Spell)) return false; + if (FusionDeploymentSpSummonTarget() > 0 && !Bot.HasInHand(CardId.BrandedLost)) + { + SelectSTPlace(Card, true); + return true; + } + + return false; + } + + public int FusionDeploymentSpSummonTarget() + { + if (CheckRemainInDeck(CardId.FallenOfAlbaz) > 0 && CheckAlbazFusion(Card) && GetProblematicEnemyMonster(0, false, false, CardType.Monster) != null) + { + return CardId.FallenOfAlbaz; + } + if (CheckRemainInDeck(CardId.BlazingCartesiaTheVirtuous) > 0 && Bot.HasInExtra(CardId.GranguignolTheDuskDragon)) + { + if (Bot.Hand.Any(c => c.IsMonster() && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark)) + || Bot.GetMonsters().Any(c => c.IsMonster() && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark) && !c.IsCode(cannotBeFusionMaterialIdList))) + { + return CardId.BlazingCartesiaTheVirtuous; + } + } + if (CheckRemainInDeck(CardId.FallenOfAlbaz) > 0 && CheckAlbazFusion(Card)) + { + return CardId.FallenOfAlbaz; + } + return 0; + } + + public bool BrandedInWhiteActivate() + { + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Spell)) return false; + activatedCardIdList.Add(Card.Id + 1); + SelectSTPlace(Card); + return true; + } else + { + if (_BrandedInWhiteActivateCheck(true)) + { + activatedCardIdList.Add(Card.Id); + SelectSTPlace(Card, true); + return true; + } + } + return false; + } + + public bool BrandedInWhiteActivateCheck() + { + return _BrandedInWhiteActivateCheck(false); + } + + public bool _BrandedInWhiteActivateCheck(bool activate = false) + { + if (CheckWhetherNegated(true, true, CardType.Spell) || activatedCardIdList.Contains(CardId.BrandedInWhite) || nadirActivated) return false; + if (CheckShouldNoMoreSpSummon() && Bot.MonsterZone.Any(c => c != null && c.GetDefensePower() >= 2000)) return false; + if (BrandedInWhiteFusionTarget(Bot.ExtraDeck, out ClientCard _fusionTarget) > 0) + { + if (activate) Logger.DebugWriteLine("White prepare fusion: " + _fusionTarget?.Name); + return true; + } + + return false; + } + + public int BrandedInWhiteFusionTarget(IList cards, out ClientCard target) + { + target = null; + Dictionary> checkDict = new Dictionary> + { + {CardId.MirrorjadeTheIcebladeDragon, () => { + if (Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) || Bot.HasInSpellZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true)) return false; + bool albazFlag = Bot.Graveyard.Any(c => c.IsCode(CardId.FallenOfAlbaz)); + albazFlag |= Bot.MonsterZone.Any(c => c != null && c.IsOriginalCode(CardId.FallenOfAlbaz)); + albazFlag |= Bot.Hand.Any(c => c.IsOriginalCode(CardId.FallenOfAlbaz)); + if (!albazFlag) return false; + + bool checkFlag = Bot.Graveyard.Any(c => c != null && !sendToGYThisTurn.Contains(c) && !c.IsCode(cannotBeFusionMaterialIdList) + && c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)); + checkFlag |= Bot.MonsterZone.Any(c => c != null && !c.IsCode(cannotBeFusionMaterialIdList) + && (c.IsCode(albazFusionMonster) || c.IsCode(CardId.GranguignolTheDuskDragon))); + return checkFlag; + } }, + {CardId.BorreloadFuriousDragon, () => { + if (Enemy.GetMonsterCount() + Enemy.GetSpellCount() > 0) + { + List darkDragonList = Bot.Hand.Where(c => c != null && c.IsMonster() && c.HasAttribute(CardAttribute.Dark) && c.HasRace(CardRace.Dragon)).ToList(); + darkDragonList.AddRange(Bot.MonsterZone.Where(c => c != null && c.IsMonster() && c.HasAttribute(CardAttribute.Dark) && c.HasRace(CardRace.Dragon) && !c.IsCode(cannotBeFusionMaterialIdList)).ToList()); + List graveDarkDragonList = Bot.Graveyard.Where(c => c.HasRace(CardRace.Dragon) && c.HasAttribute(CardAttribute.Dark) + && !c.IsCode(cannotBeFusionMaterialIdList) && !CheckWhetherShouldKeepInGrave(c) ).ToList(); + + bool hasAlbaz = darkDragonList.Any(c => c.IsCode(CardId.FallenOfAlbaz)) || graveDarkDragonList.Any(c => c.IsCode(CardId.FallenOfAlbaz)); + int darkDragonCount = darkDragonList.Count; + if (hasAlbaz) + { + darkDragonCount += graveDarkDragonList.Count; + } + return darkDragonCount >= 2; + } + return false; + } }, + {CardId.GuardianChimera, () => + { + if (CheckWhetherNegated(true, true, CardType.Monster) || DefaultCheckWhetherCardIdIsNegated(CardId.GuardianChimera)) return false; + int enemyCardCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount(); + if (enemyCardCount == 0) return false; + + return ChimeraFusionMaterialList().Count > 0; + } }, + {CardId.LubellionTheSearingDragon, () => + { + if (activatedCardIdList.Contains(CardId.LubellionTheSearingDragon) + || DefaultCheckWhetherCardIdIsNegated(CardId.LubellionTheSearingDragon) + || CheckWhetherNegated(true, true, CardType.Monster)) + { + return false; + } + List checkMaterialList = new List(Bot.Graveyard.Where(c => c != null && c.IsMonster()).OrderBy(c => c.GetDefensePower())).ToList(); + checkMaterialList.AddRange(Bot.GetMonsters().OrderBy(c => c.GetDefensePower())); + checkMaterialList.AddRange(Bot.Hand); + ClientCard albaz = checkMaterialList.Where(c => c.IsCode(CardId.FallenOfAlbaz)).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + ClientCard darkMonster = checkMaterialList.Where(c => c != albaz && c.HasAttribute(CardAttribute.Dark)).FirstOrDefault(); + if (albaz == null || darkMonster == null) return false; + if (Bot.Hand.Count(c => c != albaz && c != darkMonster && !c.IsCode(CardId.BrandedInWhite)) == 0) return false; + + return true; + } }, + {CardId.AlbionTheSanctifireDragon, () => + { + List checkMaterialList = new List(Bot.Graveyard.Where(c => c != null && c.IsMonster()).OrderBy(c => c.GetDefensePower())).ToList(); + checkMaterialList.AddRange(Bot.GetMonsters().OrderBy(c => c.GetDefensePower())); + checkMaterialList.AddRange(Bot.Hand); + ClientCard albaz = checkMaterialList.FirstOrDefault(c => c.IsCode(CardId.FallenOfAlbaz)); + ClientCard lightSpellcaster = checkMaterialList.FirstOrDefault(c => c.HasRace(CardRace.SpellCaster) && c.HasAttribute(CardAttribute.Light)); + if (albaz == null || lightSpellcaster == null) return false; + + int remainMonsterCount = Enemy.GetGraveyardMonsters().Count; + remainMonsterCount += Bot.Graveyard.Where(c => c.IsMonster() && c != albaz && c != lightSpellcaster).Count(); + remainMonsterCount += Bot.HasInHand(_CardId.MaxxC) ? 1 : 0; + return remainMonsterCount >= 2; + } }, + {CardId.RindbrummTheStrikingDragon, () => { + if (!Bot.HasInGraveyard(CardId.TriBrigadeMercourier)) return false; + bool albazCheck = Bot.HasInHandOrHasInMonstersZone(CardId.FallenOfAlbaz); + albazCheck |= Bot.HasInGraveyard(CardId.FallenOfAlbaz); + return albazCheck; + } }, + {CardId.DespianQuaeritis, () => + { + bool checkFlag = Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && c.Attack >= 2500 && !(c.HasType(CardType.Fusion) && c.Level >= 8)); + if (checkFlag) + { + ClientCard despianInGrave = Bot.Graveyard.Where(c => c != null && c.HasSetcode(SetcodeDespain) && !CheckWhetherShouldKeepInGrave(c)) + .OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (despianInGrave != null) + { + bool albazCheck = Bot.HasInHandOrHasInMonstersZone(CardId.FallenOfAlbaz); + albazCheck |= Bot.HasInGraveyard(CardId.FallenOfAlbaz); + return albazCheck; + } + List fusionMaterialList = Bot.Hand.Where(c => c.IsMonster()).OrderBy(c => c.GetDefensePower()).ToList(); + fusionMaterialList.AddRange(Bot.MonsterZone.Where(c => c != null && !c.IsCode(cannotBeFusionMaterialIdList)).OrderBy(c => c.GetDefensePower()).ToList()); + ClientCard despian = fusionMaterialList.FirstOrDefault(c => c.HasSetcode(SetcodeDespain)); + if (despian != null) + { + checkFlag = fusionMaterialList.Any(c => c != despian && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark)); + checkFlag |= Bot.HasInGraveyard(CardId.FallenOfAlbaz); + return checkFlag; + } + } + + return false; + } }, + {CardId.TitanikladTheAshDragon, () => + { + List checkMaterialList = new List(Bot.Graveyard.Where(c => c != null && c.IsMonster()).OrderBy(c => c.GetDefensePower())).ToList(); + checkMaterialList.AddRange(Bot.GetMonsters().OrderBy(c => c.GetDefensePower())); + checkMaterialList.AddRange(Bot.Hand); + ClientCard albaz = checkMaterialList.Where(c => c.IsCode(CardId.FallenOfAlbaz)).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + + foreach (ClientCard material in checkMaterialList) + { + if (material != albaz && material.IsMonster() && material.Attack >= 2500 && !material.IsCode(cannotBeFusionMaterialIdList) && !Util.IsTurn1OrMain2()) + { + bool checkFlag = Enemy.GetMonsterCount() == 0 && !CheckWhetherShouldKeepInGrave(material) && (material.IsFacedown() || material.Location != CardLocation.MonsterZone); + + int expectedAttack = 2900 + material.Level * 100; + int botBestPower = Util.GetBestPower(Bot); + int beforeBetterCount = Enemy.MonsterZone.Count(c => c != null && c.GetDefensePower() >= botBestPower); + int afterBetterCount = Enemy.MonsterZone.Count(c => c != null && c.GetDefensePower() >= expectedAttack); + checkFlag |= afterBetterCount < beforeBetterCount; + + return checkFlag; + } + } + return false; + } }, + {CardId.AlbaLenatusTheAbyssDragon, () => + { + if (Util.GetOneEnemyBetterThanMyBest() == null && Duel.MainPhase.CanBattlePhase) + { + ClientCard albaz = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsOriginalCode(CardId.FallenOfAlbaz)); + if (albaz == null) + { + albaz = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsCode(CardId.FallenOfAlbaz)); + } + if (albaz == null) return false; + foreach (ClientCard material in Bot.Graveyard) + { + if (material != null && material != albaz && material.IsMonster() && material.HasRace(CardRace.Dragon) && !material.IsCode(cannotBeFusionMaterialIdList)) + { + return true; + } + } + } + return false; + } } + }; + + foreach (KeyValuePair> pair in checkDict) + { + target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return pair.Key; + } + } + + target = null; + return 0; + } + + public List ChimeraFusionMaterialList(bool dragonCheck = true) + { + int enemyCardCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount(); + + List fieldMonsterList = Bot.MonsterZone.Where(c => c != null && c.GetDefensePower() <= 2500 && !c.IsCode(cannotBeFusionMaterialIdList)) + .OrderBy(c => c.GetDefensePower()).ToList(); + List handMonsterList = Bot.Hand.Where(c => c.IsMonster()) + .OrderBy(c => c.GetDefensePower()).ToList(); + // 2 monsters on field + 1 monster in hand + if (enemyCardCount >= 2 && fieldMonsterList.Count >= 2) + { + if (fieldMonsterList.Count < 2 || handMonsterList.Count < 1) return new List() ; + foreach (ClientCard handMonster in handMonsterList) + { + for (int fieldIndex1 = 0; fieldIndex1 < fieldMonsterList.Count - 1; ++fieldIndex1) + { + ClientCard fieldMonster1 = fieldMonsterList[fieldIndex1]; + if (fieldMonster1.IsCode(handMonster.Id) || handMonster.IsCode(fieldMonster1.Id)) continue; + for (int fieldIndex2 = fieldIndex1 + 1; fieldIndex2 < fieldMonsterList.Count; ++fieldIndex2) + { + ClientCard fieldMonster2 = fieldMonsterList[fieldIndex2]; + if (fieldMonster2.IsCode(handMonster.Id) || handMonster.IsCode(fieldMonster2.Id)) continue; + if (fieldMonster2.IsCode(fieldMonster1.Id) || fieldMonster1.IsCode(fieldMonster2.Id)) continue; + + List materialList = new List { handMonster, fieldMonster1, fieldMonster2 }; + bool checkFlag = dragonCheck && materialList.Any(c => c.HasRace(CardRace.Dragon)); + if (checkFlag) + { + return materialList; + } + } + } + } + } + // 1 monster on field + 2 monsters in hand + if (enemyCardCount == 1 || fieldMonsterList.Count == 1) + { + if (fieldMonsterList.Count < 1 || handMonsterList.Count < 2) return new List(); + foreach (ClientCard fieldMonster in fieldMonsterList) + { + for (int handIndex1 = 0; handIndex1 < handMonsterList.Count - 1; ++handIndex1) + { + ClientCard handMonster1 = handMonsterList[handIndex1]; + if (handMonster1.IsCode(fieldMonster.Id) || fieldMonster.IsCode(handMonster1.Id)) continue; + for (int handIndex2 = handIndex1 + 1; handIndex2 < handMonsterList.Count; ++handIndex2) + { + ClientCard handMonster2 = handMonsterList[handIndex2]; + if (handMonster2.IsCode(fieldMonster.Id) || fieldMonster.IsCode(handMonster2.Id)) continue; + if (handMonster2.IsCode(handMonster1.Id) || handMonster1.IsCode(handMonster2.Id)) continue; + + List materialList = new List { fieldMonster, handMonster1, handMonster2 }; + bool checkFlag = dragonCheck && materialList.Any(c => c.HasRace(CardRace.Dragon)); + if (checkFlag) + { + return materialList; + } + } + } + } + } + + return new List(); + } + + public bool BrandedFusionActivate() + { + if (BrandedFusionActivateCheck()) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public bool BrandedFusionActivateCheck(bool endPhaseCheck = true) + { + if (CheckWhetherNegated(true, true, CardType.Spell) || activatedCardIdList.Contains(CardId.BrandedFusion)) return false; + if (!Bot.HasInHandOrHasInMonstersZone(CardId.FallenOfAlbaz) && CheckRemainInDeck(CardId.FallenOfAlbaz) == 0) return false; + if (endPhaseCheck && Duel.Phase >= DuelPhase.End) return false; + return true; + } + + public bool GoldSarcophagusActivate() + { + if (CheckWhetherNegated(true, true, CardType.Spell)) return false; + if (GoldSarcophagusTarget(null, out _) > 0) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public int GoldSarcophagusTarget(IList cards, out ClientCard target) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.DespianTragedy, () => !activatedCardIdList.Contains(CardId.DespianTragedy) && !DefaultCheckWhetherCardIdIsNegated(CardId.DespianTragedy) }, + {CardId.TriBrigadeMercourier, () => !activatedCardIdList.Contains(CardId.TriBrigadeMercourier + 1) && !DefaultCheckWhetherCardIdIsNegated(CardId.TriBrigadeMercourier) } + }; + foreach (KeyValuePair> pair in checkDict) + { + int cardId = pair.Key; + if (pair.Value()) + { + if (cards != null) + { + target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return cardId; + } + } + else if (CheckRemainInDeck(cardId) > 0) + { + target = null; + return cardId; + } + } + } + + target = null; + return 0; + } + + public bool FoolishBurialActivate() + { + if (CheckWhetherNegated(true, true, CardType.Spell) || CheckWhetherWillbeRemoved()) return false; + if (FoolishBurialTarget(null, out _) > 0) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public int FoolishBurialTarget(IList cards, out ClientCard target) + { + // tragedy + if (!activatedCardIdList.Contains(CardId.DespianTragedy) && !DefaultCheckWhetherCardIdIsNegated(CardId.DespianTragedy)) + { + if (cards != null) + { + target = cards.FirstOrDefault(c => c.IsCode(CardId.DespianTragedy)); + if (target != null) + { + return CardId.DespianTragedy; + } + } else + { + if (CheckRemainInDeck(CardId.DespianTragedy) > 0) + { + target = null; + return CardId.DespianTragedy; + } + } + } + + // send to GY check + bool sendToGYFlag = CheckRemainInDeck(CardId.BrandedRetribution) > 0; + sendToGYFlag |= Bot.HasInGraveyard(CardId.BrandedRetribution) && CheckRemainInDeck(CardId.BrandedFusion) > 0; + if (sendToGYFlag) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.BystialSaronir, () => !activatedCardIdList.Contains(CardId.BystialSaronir + 1) && !DefaultCheckWhetherCardIdIsNegated(CardId.BystialSaronir) }, + {CardId.AlbionTheShroudedDragon, () => !activatedCardIdList.Contains(CardId.AlbionTheShroudedDragon) && !DefaultCheckWhetherCardIdIsNegated(CardId.AlbionTheShroudedDragon) } + }; + + foreach (KeyValuePair> pair in checkDict) + { + int cardId = pair.Key; + if (pair.Value()) + { + if (cards != null) + { + target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return cardId; + } + } else if (CheckRemainInDeck(cardId) > 0) + { + target = null; + return cardId; + } + } + } + } + + // albaz + if (!Bot.HasInGraveyard(CardId.FallenOfAlbaz)) + { + bool albazCheckFlag = Bot.HasInHand(new List { CardId.BrandedInRed, CardId.BrandedInWhite }); + albazCheckFlag |= Bot.HasInHand(CardId.BlazingCartesiaTheVirtuous) && Bot.MonsterZone.Count(c => c != null && c.Sequence < 5) < 5; + if (albazCheckFlag) + { + int albazCountCheck = Bot.HasInHandOrInSpellZone(CardId.BrandedFusion) ? 2 : 1; + if (cards != null) + { + List albazList = cards.Where(c => c.IsCode(CardId.FallenOfAlbaz)).ToList(); + if (albazList.Count >= albazCountCheck) + { + target = albazList.First(); + return CardId.FallenOfAlbaz; + } + } else + { + if (CheckRemainInDeck(CardId.FallenOfAlbaz) >= albazCountCheck) + { + target = null; + return CardId.FallenOfAlbaz; + } + } + } + } + + target = null; + return 0; + } + + public bool CalledbytheGraveActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (CheckAtAdvantage() && Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + return false; + } + if (Duel.LastChainPlayer == 1) + { + // negate + if (Util.GetLastChainCard().IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + if (Util.GetLastChainCard().IsCode(_CardId.MaxxC) && CheckAtAdvantage()) + { + return false; + } + ClientCard graveTarget = Enemy.Graveyard.GetFirstMatchingCard(card => card.IsMonster() && card.GetOriginCode() == code); + if (graveTarget != null) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(graveTarget); + currentDestroyCardList.Add(graveTarget); + return true; + } + } + + // banish target + foreach (ClientCard graveCard in Enemy.Graveyard) + { + if (Duel.ChainTargets.Contains(graveCard) && graveCard.IsMonster()) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + int code = graveCard.Id; + AI.SelectCard(graveCard); + currentDestroyCardList.Add(graveCard); + return true; + } + } + + // become targets + if (Duel.ChainTargets.Contains(Card)) + { + List enemyMonsters = Enemy.Graveyard.GetMatchingCards(card => card.IsMonster()).ToList(); + if (enemyMonsters.Count > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + int code = enemyMonsters[0].Id; + AI.SelectCard(code); + currentDestroyCardList.Add(enemyMonsters[0]); + return true; + } + } + } + + // avoid danger monster in grave + if (Duel.LastChainPlayer == 1) return false; + List targets = GetDangerousCardinEnemyGrave(true); + if (targets.Count > 0) + { + int code = targets[0].Id; + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(code); + currentDestroyCardList.Add(targets[0]); + return true; + } + + return false; + } + + public bool BrandedInHighSpiritsActivate() + { + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Spell)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } else + { + if (BrandedInHighSpiritsActivateCheck()) + { + activatedCardIdList.Add(Card.Id); + SelectSTPlace(Card, true); + return true; + } + } + return false; + } + + public bool BrandedInHighSpiritsActivateCheck() + { + bool lubellionCheck = Bot.HasInHand(CardId.TheBystialLubellion) && CheckRemainInDeck(CardId.BystialSaronir) > 0 && !activatedCardIdList.Contains(CardId.TheBystialLubellion) + && Duel.Player == 0 && (Duel.Phase <= DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2) && !CheckWhetherWillbeRemoved(); + + if (CheckWhetherNegated(true, true, CardType.Spell) || activatedCardIdList.Contains(CardId.BrandedInHighSpirits) || CheckWhetherWillbeRemoved()) return false; + Dictionary> checkDict = new Dictionary> + { + {CardId.AlbionTheBrandedDragon, () => !sendToGYThisTurn.Any(c => c.IsCode(CardId.AlbionTheBrandedDragon)) && !lubellionCheck + && Bot.Hand.Any(c => BrandedInHighSpiritDiscardDragonCheck(c) ) }, + {CardId.TitanikladTheAshDragon, () => !sendToGYThisTurn.Any(c => c.IsCode(CardId.TitanikladTheAshDragon)) && !lubellionCheck + && Bot.Hand.Any(c => BrandedInHighSpiritDiscardDragonCheck(c) ) + && CheckRemainInDeck(CardId.GuidingQuemTheVirtuous, CardId.FallenOfAlbaz) > 0}, + {CardId.GranguignolTheDuskDragon, () => Bot.Hand.Any(c => c.HasRace(CardRace.SpellCaster) && !(CheckWhetherCanSummon() && c.IsOriginalCode(CardId.GuidingQuemTheVirtuous))) }, + {CardId.RindbrummTheStrikingDragon, () => Bot.Hand.Any(c => c.HasRace(CardRace.WindBeast) + && (!c.IsCode(CardId.TriBrigadeMercourier) || !Bot.MonsterZone.Any(c2 => c2 != null && c2.IsFaceup() && c2.IsCode(albazFusionMonster)))) } + }; + + foreach (KeyValuePair> pair in checkDict) + { + if (Bot.HasInExtra(pair.Key) && pair.Value()) + { + return true; + } + } + return false; + } + + public bool BrandedInHighSpiritDiscardDragonCheck(ClientCard card) + { + if (!card.HasRace(CardRace.Dragon)) return false; + if (Duel.Player == 0 && (Duel.Phase <= DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2)) + { + if (card.IsOriginalCode(CardId.AlbionTheShroudedDragon) && !activatedCardIdList.Contains(CardId.AlbionTheShroudedDragon)) return false; + if (card.IsOriginalCode(CardId.TheBystialLubellion) && !activatedCardIdList.Contains(CardId.TheBystialLubellion) && CheckRemainInDeck(CardId.BystialSaronir) > 0) return false; + } + + return true; + } + + public bool BrandedOpeningActivate() + { + if (CheckWhetherNegated(true, true, CardType.Spell)) return false; + if (Duel.Player == 0) + { + if (Bot.HasInHand(CardId.AlbionTheShroudedDragon) && !CheckWhetherWillbeRemoved() && !activatedCardIdList.Contains(CardId.AlbionTheShroudedDragon)) return false; + bool canCallCartesia = Bot.HasInHand(CardId.BlazingCartesiaTheVirtuous) && !summoned; + canCallCartesia |= !activatedCardIdList.Contains(CardId.FusionDeployment) && Bot.HasInHandOrInSpellZone(CardId.FusionDeployment) + && !CheckShouldNoMoreSpSummon() && Bot.HasInExtra(CardId.GranguignolTheDuskDragon) && CheckRemainInDeck(CardId.BlazingCartesiaTheVirtuous) > 0; + if (canCallCartesia) return false; + } + bool goal = CheckRemainInDeck(CardId.AluberTheJesterOfDespia) > 0 && !activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && !enemyActivateLockBird; + goal |= CheckRemainInDeck(CardId.GuidingQuemTheVirtuous) > 0; + if (goal) + { + SelectSTPlace(Card, true); + activatedCardIdList.Add(Card.Id); + return true; + } + return false; + } + + public bool CrossoutDesignatorActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + // negate + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard() != null) + { + int code = Util.GetLastChainCard().Id; + int alias = Util.GetLastChainCard().Alias; + if (alias != 0 && alias - code < 10) code = alias; + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + if (CheckRemainInDeck(code) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectAnnounceID(code); + return true; + } + } + return false; + } + + public bool BrandedInRedActivate() + { + ClientCard targetCard = BrandedInRedActivateCheck(true); + if (targetCard != null) + { + AI.SelectCard(targetCard); + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public ClientCard BrandedInRedActivateCheck(bool updateMaterialList = false) + { + if (CheckWhetherNegated(true, true, CardType.Spell) || activatedCardIdList.Contains(CardId.BrandedInRed)) return null; + if (Duel.CurrentChain.Any(c => c != null && c.Controller == 0 && c.IsCode(CardId.BlazingCartesiaTheVirtuous))) return null; + if (Duel.CurrentChain.Any(c => c != null && c.Controller == 0 && c.IsCode(CardId.AlbionTheBrandedDragon)) + && !Util.ChainContainPlayer(1)) return null; + if (nadirActivated) return null; + + List materialList = Bot.MonsterZone.Where(c => c != null && c.Attack <= 2500 && !c.IsCode(cannotBeFusionMaterialIdList)).ToList(); + materialList.AddRange(Bot.Hand.Where(c => c.IsMonster() + && !(CheckWhetherCanSummon() && + ((!activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) && c.IsCode(CardId.AluberTheJesterOfDespia)) + || (!activatedCardIdList.Contains(CardId.SpringansKitt) && c.IsCode(CardId.SpringansKitt))) + ) + ) + ); + + List graveTargetList = Bot.Graveyard.Where(c => c != null && c.IsMonster() && !c.HasType(CardType.Fusion | CardType.Synchro) + && (c.IsCode(CardId.FallenOfAlbaz) || c.HasSetcode(SetcodeDespain))).ToList(); + + // select targeted monster + if (Duel.LastChainPlayer == 1) + { + // escape grave monster + List targetedList = Duel.LastChainTargets.Where(c => c != null && c.Location == CardLocation.Grave && c.Controller == 0 + && !c.HasType(CardType.Fusion | CardType.Synchro) && (c.IsCode(CardId.FallenOfAlbaz) || c.HasSetcode(SetcodeDespain))).ToList(); + + if (targetedList.Count > 0) + { + foreach (ClientCard target in targetedList) + { + List newMaterialList = new List(materialList) { target }; + BrandedInRedFusionCheck(Bot.ExtraDeck, 0, newMaterialList, new List { target }, out ClientCard _fusionTarget, out _); + if (_fusionTarget != null) + { + if (updateMaterialList) Logger.DebugWriteLine("Red prepare fusion 1: " + _fusionTarget.Name); + return target; + } + } + } + + // escape target + ClientCard lastCahinCard = Util.GetLastChainCard(); + if (lastCahinCard != null) + { + List chainTargetList = Duel.LastChainTargets.Where(c => c.Controller == 0 && c.Location == CardLocation.MonsterZone + && (!c.IsCode(cannotBeFusionMaterialIdList) || c.Attack <= 2500)).ToList(); + if (chainTargetList.Count > 0) + { + if (lastCahinCard.IsCode(targetNegateIdList)) + { + chainTargetList = chainTargetList.Where(c => c.Attack <= 2500 && !c.IsCode(CardId.AlbionTheBrandedDragon)).ToList(); + } + + foreach (ClientCard target in graveTargetList) + { + List newMaterialList = new List(materialList) { target }; + BrandedInRedFusionCheck(Bot.ExtraDeck, 0, newMaterialList, chainTargetList, + out ClientCard _fusionTarget, out List usedMaterialList); + + if (_fusionTarget != null) + { + if (updateMaterialList) + { + Logger.DebugWriteLine("Red prepare fusion 2: " + _fusionTarget.Name); + brandedInRedMaterialList.AddRange(usedMaterialList.Intersect(chainTargetList)); + } + return target; + } + } + } + } + } + + bool shouldSummonFirst = Duel.Player == 0 && (Duel.Phase <= DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2) && !summoned + && (Bot.HasInHand(new int[] { CardId.AluberTheJesterOfDespia, CardId.GuidingQuemTheVirtuous, CardId.SpringansKitt }) + || Bot.HasInHand(CardId.FallenOfAlbaz) && CheckAlbazFusion(Card)); + bool idleFlag = Duel.Player == 1 || CurrentTiming == -1; + + if (shouldSummonFirst || !idleFlag) return null; + + // for fusion searing dragon + if (!Bot.MonsterZone.Any(c => c != null && c.HasType(CardType.Fusion)) && Duel.LastChainPlayer != 0 + && !CheckWhetherNegated(true, true, CardType.Monster) && !activatedCardIdList.Contains(CardId.LubellionTheSearingDragon)) + { + foreach (ClientCard target in graveTargetList) + { + List newMaterialList = new List(materialList) { target }; + BrandedInRedFusionCheck(Bot.ExtraDeck, CardId.LubellionTheSearingDragon, newMaterialList, new List { target }, out ClientCard _fusionTarget, out _); + if (_fusionTarget != null) + { + return target; + } + } + } + + // remove cards + List problemCardList = GetProblematicEnemyCardList(false, false, CardType.Monster); + if (problemCardList.Count > 0 || (Duel.Phase == DuelPhase.End && Duel.Player == 1)) + { + if (!enemyActivateLockBird) + { + foreach (ClientCard target in graveTargetList) + { + List newMaterialList = new List(materialList) { target }; + BrandedInRedFusionCheck(Bot.ExtraDeck, CardId.GuardianChimera, newMaterialList, new List { target }, out ClientCard _fusionTarget, out _); + if (_fusionTarget != null) + { + if (updateMaterialList) Logger.DebugWriteLine("Red prepare fusion 3: " + _fusionTarget.Name); + return target; + } + } + } + + foreach (ClientCard target in graveTargetList) + { + List newMaterialList = new List(materialList) { target }; + BrandedInRedFusionCheck(Bot.ExtraDeck, CardId.BorreloadFuriousDragon, newMaterialList, new List { target }, out ClientCard _fusionTarget, out _); + if (_fusionTarget != null) + { + if (updateMaterialList) Logger.DebugWriteLine("Red prepare fusion 4: " + _fusionTarget.Name); + return target; + } + } + } + + return null; + } + + public void BrandedInRedFusionCheck( + IList canSummonList, int mustSummonId, + List materialList, List mustMaterialList, + out ClientCard fusionTarget, out List selectedFusionMaterialList) + { + fusionTarget = null; + selectedFusionMaterialList = new List(); + + // fusion id + // material condition + // extra check function + // search material function + List>, + Func, bool>, + Func, List, List>, Func, bool>, List> + >> checkTupleList = new List>, Func, bool>, + Func, List, List>, Func, bool>, List> + >> + { + new Tuple>, Func, bool>, + Func, List, List>, Func, bool>, List>>( + CardId.MirrorjadeTheIcebladeDragon, new List> + { + (c) => c.IsCode(CardId.FallenOfAlbaz), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) + }, + (l) => !Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) && !Bot.HasInSpellZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true), + BrandedInRedUsing2SubFunc + ), + new Tuple>, Func, bool>, + Func, List, List>, Func, bool>, List>>( + CardId.LubellionTheSearingDragon, new List> + { + (c) => c.IsCode(CardId.FallenOfAlbaz), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Dark) + }, + (l) => !Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) && !Bot.HasInSpellZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) + && Bot.Hand.Count(c => !l.Contains(c)) > 0 && !activatedCardIdList.Contains(CardId.LubellionTheSearingDragon), + BrandedInRedUsing2SubFunc + ), + new Tuple>, Func, bool>, + Func, List, List>, Func, bool>, List>>( + CardId.GuardianChimera, + null, + null, + BrandedInRedForChimeraFunc + ), + new Tuple>, Func, bool>, + Func, List, List>, Func, bool>, List>>( + CardId.DespianQuaeritis, new List> + { + (c) => c.HasSetcode(SetcodeDespain), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Light | CardAttribute.Dark) + }, + null, + BrandedInRedUsing2SubFunc + ), + new Tuple>, Func, bool>, + Func, List, List>, Func, bool>, List>>( + CardId.BorreloadFuriousDragon, new List> + { + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Dark) && c.HasRace(CardRace.Dragon), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Dark) && c.HasRace(CardRace.Dragon) + }, + null, + BrandedInRedUsing2SubFunc + ), + new Tuple>, Func, bool>, + Func, List, List>, Func, bool>, List>>( + CardId.AlbionTheSanctifireDragon, new List> + { + (c) => c.IsCode(CardId.FallenOfAlbaz), + (c) => !c.IsCode(cannotBeFusionMaterialIdList) && c.HasAttribute(CardAttribute.Light) && c.HasRace(CardRace.SpellCaster) + }, + (l) => Enemy.Graveyard.Count(c => c != null && c.IsMonster() && c.IsCanRevive()) + + Bot.Graveyard.Count(c => c != null && !l.Contains(c)) >= 2, + BrandedInRedUsing2SubFunc + ), + }; + + foreach (Tuple>, Func, bool>, + Func, List, List>, Func, bool>, List>> tuple in checkTupleList) + { + if (mustSummonId > 0 && mustSummonId != tuple.Item1) continue; + ClientCard currentFusionTarget = canSummonList.FirstOrDefault(c => c != null && c.IsCode(tuple.Item1)); + if (currentFusionTarget == null) continue; + Func, List, List>, Func, bool>, List> materialFunc = tuple.Item4; + + List currentMaterialList = materialFunc(materialList, mustMaterialList, tuple.Item2, tuple.Item3); + if (currentMaterialList.Count > 0) + { + fusionTarget = currentFusionTarget; + selectedFusionMaterialList = currentMaterialList; + return; + } + } + } + + public List BrandedInRedUsing2SubFunc(List materialList, List mustMaterialList, + List> checkFuncList, Func, bool> extraCheckFunc) + { + List selectedFusionMaterialList = new List(); + + Func fusionFunc1 = checkFuncList[0]; + Func fusionFunc2 = checkFuncList[1]; + + if (mustMaterialList != null && mustMaterialList.Count > 0) + { + foreach (ClientCard mustMaterial in mustMaterialList) + { + if (!fusionFunc1(mustMaterial) && !fusionFunc2(mustMaterial)) continue; + foreach (ClientCard anotherMaterial in materialList) + { + if (anotherMaterial == mustMaterial) continue; + bool checkFlag = fusionFunc1(mustMaterial) && fusionFunc2(anotherMaterial); + checkFlag |= fusionFunc2(mustMaterial) && fusionFunc1(anotherMaterial); + checkFlag &= (extraCheckFunc == null || extraCheckFunc(new List { mustMaterial, anotherMaterial })); + if (checkFlag) + { + selectedFusionMaterialList.Add(mustMaterial); + selectedFusionMaterialList.Add(anotherMaterial); + return selectedFusionMaterialList; + } + } + } + } + else + { + for (int index1 = 0; index1 < materialList.Count - 1; ++index1) + { + ClientCard material1 = materialList[index1]; + if (!fusionFunc1(material1) && !fusionFunc2(material1)) continue; + for (int index2 = index1 + 1; index2 < materialList.Count; ++index2) + { + ClientCard material2 = materialList[index2]; + bool checkFlag = fusionFunc1(material1) && fusionFunc2(material2); + checkFlag |= fusionFunc2(material1) && fusionFunc1(material2); + checkFlag &= (extraCheckFunc == null || extraCheckFunc(new List { material1, material2 })); + if (checkFlag) + { + selectedFusionMaterial.Add(material1); + selectedFusionMaterial.Add(material2); + return selectedFusionMaterialList; + } + } + } + } + + return selectedFusionMaterial; + } + + public List BrandedInRedForChimeraFunc(List materialList, List mustMaterialList, + List> checkFuncList, Func, bool> extraCheckFunc) + { + List selectedFusionMaterialList = new List(); + + int enemyCardCount = Enemy.MonsterZone.Count(c => c != null); + enemyCardCount += Enemy.SpellZone.Count(c => c != null && c.Type != (int)CardType.Spell && c.Type != (int)CardType.Trap); + if (enemyCardCount == 0 || CheckWhetherNegated(true, true, CardType.Monster)) + { + return selectedFusionMaterialList; + } + + List fieldMaterialList = materialList.Where(c => c.Location == CardLocation.MonsterZone).OrderBy(c => c.Attack).ToList(); + List handMaterialList = materialList.Where(c => c.Location == CardLocation.Hand || c.Location == CardLocation.Grave).OrderBy(c => c.Attack).ToList(); + + // 2 field monster + 1 hand monster + if (enemyCardCount >= 2) + { + foreach (ClientCard handMonster in handMaterialList) + { + for (int fieldIndex1 = 0; fieldIndex1 < fieldMaterialList.Count - 1; ++fieldIndex1) + { + ClientCard fieldMonster1 = fieldMaterialList[fieldIndex1]; + if (fieldMonster1.IsCode(handMonster.Id) || handMonster.IsCode(fieldMonster1.Id)) continue; + for (int fieldIndex2 = fieldIndex1 + 1; fieldIndex2 < fieldMaterialList.Count; ++fieldIndex2) + { + ClientCard fieldMonster2 = fieldMaterialList[fieldIndex2]; + if (fieldMonster2.IsCode(fieldMonster1.Id) || fieldMonster1.IsCode(fieldMonster2.Id)) continue; + if (fieldMonster2.IsCode(handMonster.Id) || handMonster.IsCode(fieldMonster2.Id)) continue; + + return new List { handMonster, fieldMonster1, fieldMonster2 }; + } + } + } + } + + // 1 field monster + 2 hand monster + foreach (ClientCard fieldMonster in fieldMaterialList) + { + for (int handIndex1 = 0; handIndex1 < handMaterialList.Count - 1; ++ handIndex1) + { + ClientCard handMonster1 = handMaterialList[handIndex1]; + if (handMonster1.IsCode(fieldMonster.Id) || fieldMonster.IsCode(handMonster1.Id)) continue; + for (int handIndex2 = handIndex1 + 1; handIndex2 < handMaterialList.Count; ++handIndex2) + { + ClientCard handMonster2 = handMaterialList[handIndex2]; + if (handMonster2.IsCode(handMonster1.Id) || handMonster1.IsCode(handMonster2.Id)) continue; + if (handMonster2.IsCode(fieldMonster.Id) || fieldMonster.IsCode(handMonster2.Id)) continue; + + return new List { fieldMonster, handMonster1, handMonster2 }; + } + } + } + + return selectedFusionMaterialList; + } + + public bool BrandedLostActivate() + { + // search + if (Card.Location == CardLocation.SpellZone && Card.IsFaceup()) + { + return true; + } + + return false; + } + + public bool BrandedLostCardActivate() + { + // search + if (Card.Location == CardLocation.SpellZone && Card.IsFaceup()) return false; + + // activate + if (CheckWhetherNegated(true, true, CardType.Spell)) return false; + if (!summoned && Bot.HasInHand(CardId.FallenOfAlbaz) && CheckAlbazFusion() && Bot.Hand.Count < 3) return false; + SelectSTPlace(Card, true); + return true; + } + + public bool InfiniteImpermanenceActivate() + { + if (CheckWhetherNegated()) return false; + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || Util.IsChainTarget(Card) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true); + if (target != null) + { + AI.SelectCard(target); + } + else + { + AI.SelectCard(Enemy.GetMonsters()); + } + infiniteImpermanenceList.Add(this_seq); + return true; + } + } + + // negate monster + List shouldNegateList = GetMonsterListForTargetNegate(true, CardType.Trap); + if (shouldNegateList.Count > 0) + { + ClientCard negateTarget = shouldNegateList[0]; + currentNegateCardList.Add(negateTarget); + + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(negateTarget); + return true; + } + + return false; + } + + public bool BrightestBlazingBrandedKingActivate() + { + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Trap)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + if (Card.Location == CardLocation.SpellZone) + { + if (Duel.CurrentChain.Any(c => c.Controller == 0 && c.IsFaceup() && (c.Location == CardLocation.MonsterZone || c.Location == CardLocation.SpellZone) + && !c.IsCode(albazFusionMonster))) + { + return false; + } + if (Duel.CurrentChain.Any(c => c.Controller == 1 && c.IsFaceup() && !currentNegateCardList.Contains(c) && !currentDestroyCardList.Contains(c) + && (c.Location == CardLocation.MonsterZone || c.Location == CardLocation.SpellZone))) + { + currentNegateCardList.AddRange(Enemy.MonsterZone.Where(c => c != null && c.IsFaceup())); + currentNegateCardList.AddRange(Enemy.SpellZone.Where(c => c != null && c.IsFaceup())); + activatedCardIdList.Add(Card.Id); + return true; + } + } + return false; + } + + public bool BrandedBeastActivate() + { + if (CheckWhetherNegated(true, true, CardType.Trap)) return false; + + int desc = -1; + if (ActivateDescription >= Util.GetStringId(CardId.BrandedBeast, 0)) + { + desc = ActivateDescription - Util.GetStringId(CardId.BrandedBeast, 0); + } + Logger.DebugWriteLine("Beast: " + desc.ToString()); + + // destroy + if (ActivateDescription == Util.GetStringId(Card.Id, 0)) + { + ClientCard destroyTarget = null; + ClientCard releaseMonster = null; + List dangerCardList = GetProblematicEnemyCardList(true, false, CardType.Trap); + if (dangerCardList.Count > 0) + { + destroyTarget = dangerCardList[0]; + } + if (destroyTarget == null) + { + if (Duel.Player == 1) + { + if ((CurrentTiming & hintTimingMainEnd) > 0) + { + List targetList = GetNormalEnemyTargetList(true, true, CardType.Trap); + if (targetList.Count > 0) + { + destroyTarget = targetList[0]; + } + } + } + else + { + destroyTarget = Util.GetOneEnemyBetterThanMyBest(true, true); + } + } + + bool forceActivateFlag = DefaultOnBecomeTarget(); + int bystialCount = Bot.MonsterZone.Count(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeBystial)); + forceActivateFlag |= bystialCount > 0 && Duel.ChainTargets.Count(c => c.Controller == 0 && c.Location == CardLocation.MonsterZone && c.IsFaceup() && c.HasSetcode(SetcodeBystial)) == bystialCount; + forceActivateFlag |= Duel.CurrentChain.Any(c => c.Controller == 1 && c.Location == CardLocation.SpellZone && c.IsCode(_CardId.Raigeki)); + if (destroyTarget == null && forceActivateFlag) + { + releaseMonster = Duel.ChainTargets.FirstOrDefault(c => c.Controller == 0 && c.Location == CardLocation.MonsterZone && c.IsFaceup() && c.HasSetcode(SetcodeBystial)); + if (releaseMonster == null) + { + if (!activatedCardIdList.Contains(CardId.AlbionTheBrandedDragon + 1) && !sendToGYThisTurn.Any(c => c.IsCode(CardId.AlbionTheBrandedDragon))) + { + List brandedDragonList = Bot.MonsterZone.Where(c => c != null && c.IsCode(CardId.AlbionTheBrandedDragon)).OrderBy(c => c.GetDefensePower()).ToList(); + if (brandedDragonList.Count > 0) + { + releaseMonster = brandedDragonList[0]; + } + } + if (releaseMonster == null) + { + releaseMonster = Bot.MonsterZone.Where(c => c != null && c.HasRace(CardRace.Dragon) + && !(c.IsOriginalCode(CardId.FallenOfAlbaz) && Util.ChainContainsCard(CardId.FallenOfAlbaz))).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + } + } + + List targetList = GetNormalEnemyTargetList(true, true, CardType.Trap); + if (targetList.Count > 0) + { + destroyTarget = targetList[0]; + } + } + + if (destroyTarget != null) + { + if (!activatedCardIdList.Contains(CardId.AlbionTheBrandedDragon + 1) && !sendToGYThisTurn.Any(c => c.IsCode(CardId.AlbionTheBrandedDragon))) + { + List brandedDragonList = Bot.MonsterZone.Where(c => c != null && c.IsCode(CardId.AlbionTheBrandedDragon)).OrderBy(c => c.GetDefensePower()).ToList(); + if (brandedDragonList.Count > 0) + { + releaseMonster = brandedDragonList[0]; + } + } + if (releaseMonster == null) + { + releaseMonster = Bot.MonsterZone.Where(c => c != null && c.HasRace(CardRace.Dragon) + && !(c.IsOriginalCode(CardId.FallenOfAlbaz) && Util.ChainContainsCard(CardId.FallenOfAlbaz))).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + } + } + + if (releaseMonster != null && destroyTarget != null) + { + activatedCardIdList.Add(Card.Id); + AI.SelectCard(releaseMonster); + AI.SelectNextCard(destroyTarget); + currentDestroyCardList.Add(destroyTarget); + return true; + } + } + + // place + if (Duel.Phase == DuelPhase.End && Bot.HasInGraveyard(CardId.BrandedLost)) + { + activatedCardIdList.Add(Card.Id + 1); + AI.SelectCard(CardId.BrandedLost); + return true; + } + + return false; + } + + public bool BrandedRetributionActivate() + { + if (Card.Location == CardLocation.SpellZone && Duel.LastChainPlayer == 1) + { + if (CheckWhetherNegated(true, true, CardType.Trap)) return false; + bool checkFlag = Bot.Graveyard.Where(c => c != null && c.IsCode(albazFusionMonster)).Count() > 1; + checkFlag |= Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.IsCode(new[] { CardId.LubellionTheSearingDragon, CardId.SprindTheIrondashDragon, CardId.AlbaLenatusTheAbyssDragon })); + if (checkFlag) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Trap)) return false; + Dictionary> checkDict = new Dictionary>{ + {CardId.BrandedFusion, () => BrandedFusionActivateCheck()}, + {CardId.BrandedLost, () => { + if (Duel.Player == 0 && Duel.Phase >= DuelPhase.End) return false; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedFusion) && BrandedFusionActivateCheck()) return true; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedInWhite) && BrandedInWhiteActivateCheck()) return true; + if (Bot.HasInHandOrInSpellZone(CardId.BrandedInRed) && BrandedInRedActivateCheck() != null) return true; + if (!summoned && Bot.HasInHand(CardId.FallenOfAlbaz) && CheckAlbazFusion()) return true; + if ((Bot.HasInMonstersZone(CardId.BlazingCartesiaTheVirtuous) || (!summoned && Bot.HasInHand(CardId.BlazingCartesiaTheVirtuous)))) return true; + return false; + } }, + {CardId.BrandedInHighSpirits, () => !(Duel.Player == 1 && (fusionToGYFlag || Duel.Phase != DuelPhase.End)) && BrandedInHighSpiritsActivateCheck()}, + {CardId.BrandedInRed, () => BrandedInRedActivateCheck() != null }, + {CardId.BrandedInWhite, BrandedInWhiteActivateCheck }, + {CardId.BrightestBlazingBrandedKing, () => !(Duel.Player == 1 && (fusionToGYFlag || Duel.Phase != DuelPhase.End)) && Bot.GetMonsters().Any(c => c.IsFaceup() && c.IsCode(albazFusionMonster)) }, + {CardId.BrandedOpening, () => Bot.Hand.Count > 2 && !activatedCardIdList.Contains(CardId.BrandedOpening) } + }; + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = Bot.Graveyard.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + activatedCardIdList.Add(Card.Id); + AI.SelectCard(target); + return true; + } + } + } + return false; + } + + public bool GuardianChimeraActivate() + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + return true; + } + + public bool AlbionTheSanctifireDragonActivate() + { + // spsummon from grave + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + List allTargetList = Enemy.Graveyard.Where(c => c != null && c.IsMonster() && c.IsCanRevive()).ToList(); + allTargetList.AddRange(Bot.Graveyard.Where(c => c != null && c.IsMonster() && c.IsCanRevive()).ToList()); + + List targetList = new List(); + + // spsummon albaz + if (CheckAlbazFusion(null, out List materialList) && !spSummoningAlbaz) + { + bool albazFlag = materialList.Count > 1; + if (materialList.Count > 0) + { + ClientCard material = materialList[0]; + albazFlag |= material.HasType(CardType.Ritual | CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link); + albazFlag |= material.IsFloodgate() || material.IsOneForXyz() || Util.GetWorstBotMonster().GetDefensePower() < material.Attack; + albazFlag |= Duel.Player == 1 && Duel.Phase == DuelPhase.End && Duel.LastChainPlayer == -1; + } + + if (albazFlag) + { + ClientCard albaz = allTargetList.FirstOrDefault(c => c.IsOriginalCode(CardId.FallenOfAlbaz)); + ClientCard worstMonster = allTargetList.Where(c => c != albaz && !currentDestroyCardList.Contains(c)).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (albaz != null && worstMonster != null + && (GetProblematicEnemyMonster(0, false, false, CardType.Monster) != null || Math.Max(worstMonster.Attack, worstMonster.Defense) <= albaz.Defense)) + { + Logger.DebugWriteLine("Sanctifire 1"); + targetList.AddRange(new[] { albaz, worstMonster }); + spSummoningAlbaz = true; + } + } + } + + // spsummon floogate + if (targetList.Count == 0) + { + ClientCard floogateCard = allTargetList.Where(c => c.IsFloodgate()).OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (floogateCard != null) + { + // select worst monster + ClientCard worstMonster = allTargetList.Where(c => c != floogateCard).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (worstMonster != null) + { + Logger.DebugWriteLine("Sanctifire 2"); + targetList.AddRange(new[] { floogateCard, worstMonster }); + } + } + } + + // spsummon target + if (targetList.Count == 0 && Duel.LastChainPlayer == 1) + { + List targetedList = Duel.LastChainTargets.Intersect(allTargetList).ToList(); + if (targetedList.Count > 0) + { + ClientCard target = ShuffleList(targetedList)[0]; + ClientCard anotherTarget = null; + if (target.GetDefensePower() >= 2000) + { + // select worst + anotherTarget = allTargetList.Where(c => c != target).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + } else + { + // select best + anotherTarget = allTargetList.Where(c => c != target).OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + } + if (anotherTarget != null) + { + Logger.DebugWriteLine("Sanctifire 3"); + targetList.AddRange(new[] { target, anotherTarget }); + } + } + } + + // spsummon useful monster + if (targetList.Count == 0 && Duel.Player == 1 && Duel.Phase == DuelPhase.End) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.BorreloadFuriousDragon, () => Enemy.GetSpellCount() > 0 }, + {CardId.MirrorjadeTheIcebladeDragon, () => !Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) && !Bot.HasInSpellZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) }, + {CardId.AluberTheJesterOfDespia, () => !activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) }, + {CardId.SpringansKitt, () => !activatedCardIdList.Contains(CardId.SpringansKitt + 1) }, + }; + + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = allTargetList.FirstOrDefault(c => c.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + // select worst + ClientCard anotherTarget = allTargetList.Where(c => c != target).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + targetList.Add(target); + targetList.Add(anotherTarget); + Logger.DebugWriteLine("Sanctifire 4"); + break; + } + } + } + + // avoid evenly match + if (targetList.Count == 0 && Duel.Player == 1 && Enemy.Hand.Count > 0 && Enemy.GetMonsterCount() + Enemy.GetSpellCount() == 0 && (CurrentTiming & hintBattleStart) > 0) + { + ClientCard summonTarget = allTargetList.OrderByDescending(c => c.Attack).FirstOrDefault(); + Dictionary> checkDict = new Dictionary> + { + {CardId.MirrorjadeTheIcebladeDragon, () => !Bot.HasInMonstersZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) && !Bot.HasInSpellZone(CardId.MirrorjadeTheIcebladeDragon, faceUp: true) }, + {CardId.AluberTheJesterOfDespia, () => !activatedCardIdList.Contains(CardId.AluberTheJesterOfDespia) }, + }; + foreach (KeyValuePair> pair in checkDict) + { + ClientCard target = allTargetList.FirstOrDefault(c => c.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + summonTarget = target; + break; + } + } + if (summonTarget != null) + { + // select worst + ClientCard anotherTarget = allTargetList.Where(c => c != summonTarget).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + targetList.Add(summonTarget); + targetList.Add(anotherTarget); + Logger.DebugWriteLine("Sanctifire 5"); + } + } + + if (targetList.Count > 0) + { + AI.SelectMaterials(targetList, HintMsg.SpSummon); + currentDestroyCardList.AddRange(targetList); + activatedCardIdList.Add(Card.Id); + return true; + } + } + // spsummon itself + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + List botCards = new List { Bot.MonsterZone[2], Bot.MonsterZone[5], Bot.MonsterZone[6] }; + List enemyCards = new List { Enemy.MonsterZone[2], Enemy.MonsterZone[5], Enemy.MonsterZone[6] }; + if (enemyCards.Any(c => c != null && (c.IsFloodgate() || c.IsMonsterDangerous()))) return true; + return botCards.Select(c => c == null ? 0 : c.GetDefensePower()).Sum() < enemyCards.Select(c => c == null ? 0 : c.GetDefensePower()).Sum(); + } + return false; + } + + public bool MirrorjadeTheIcebladeDragonActivate() + { + if (Card.Location != CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + return true; + } + if (Card.Location == CardLocation.MonsterZone) + { + bool checkFlag = GetProblematicEnemyMonster(0, false, false, CardType.Monster) != null; + if (Enemy.GetMonsterCount() > 0) + { + checkFlag |= Duel.Player == 1 && Duel.Phase == DuelPhase.End && Duel.LastChainPlayer != 0; + int enemyBattlePower = Enemy.BattlingMonster == null ? 0 : Enemy.BattlingMonster.GetDefensePower(); + int botBattlePower = Bot.BattlingMonster == null ? 0 : Bot.BattlingMonster.GetDefensePower(); + checkFlag |= enemyBattlePower > 0 && enemyBattlePower > botBattlePower && Duel.LastChainPlayer != 0 && !currentDestroyCardList.Contains(Enemy.BattlingMonster); + checkFlag |= DefaultOnBecomeTarget() && Duel.LastChainPlayer != 0; + } + if (Duel.CurrentChain.Any(c => c.IsCode(CardId.NibiruThePrimalBeing) && !DefaultCheckWhetherCardIdIsNegated(CardId.NibiruThePrimalBeing))) + { + checkFlag |= Enemy.GetMonsterCount() > 0; + checkFlag |= Bot.HasInMonstersZone(new[] { CardId.TheBystialLubellion, CardId.DespianTragedy, CardId.TriBrigadeMercourier }); + } + + if (checkFlag) + { + Dictionary> checkDict = new Dictionary> + { + {CardId.AlbionTheBrandedDragon, + () =>!sendToGYThisTurn.Any(c => c.IsCode(CardId.AlbionTheBrandedDragon)) && !DefaultCheckWhetherCardIdIsNegated(CardId.AlbionTheBrandedDragon) + && !(Duel.Player == 0 && Bot.HasInMonstersZone(CardId.AlbionTheBrandedDragon) && Bot.HasInGraveyard(CardId.TheBystialLubellion))}, + {CardId.RindbrummTheStrikingDragon, + () => Duel.Player == 1 && Bot.Graveyard.Any(c => c.IsOriginalCode(CardId.FallenOfAlbaz)) && Bot.Hand.Count > 0 + && !activatedCardIdList.Contains(CardId.FallenOfAlbaz) && !DefaultCheckWhetherCardIdIsNegated(CardId.FallenOfAlbaz)}, + {CardId.TitanikladTheAshDragon, () => CheckRemainInDeck(CardId.GuidingQuemTheVirtuous) > 0}, + {CardId.SprindTheIrondashDragon, () => CheckRemainInDeck(CardId.SpringansKitt) > 0}, + {CardId.AlbaLenatusTheAbyssDragon, () => CheckRemainInDeck(CardId.FusionDeployment, CardId.BrandedFusion) > 0 }, + {CardId.LubellionTheSearingDragon, () => true }, + {CardId.AlbionTheSanctifireDragon, () => true } + }; + + foreach (KeyValuePair> pair in checkDict) + { + if (Bot.HasInExtra(pair.Key) && pair.Value()) + { + AI.SelectCard(pair.Key); + return true; + } + } + } + } + return false; + } + + public bool BorreloadFuriousDragonActivate() + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + + // destroy dangerous card + List dangerList = GetProblematicEnemyCardList(true, false, CardType.Monster); + if (dangerList.Count > 0) + { + ClientCard botTarget = Bot.GetMonsters().OrderBy(c => c.GetDefensePower() + (c.IsCode(albazFusionMonster) ? 1 : 0)).FirstOrDefault(); + if (botTarget != null) + { + AI.SelectCard(botTarget); + AI.SelectNextCard(dangerList); + currentDestroyCardList.Add(botTarget); + currentDestroyCardList.Add(dangerList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + List enemyTargetList = GetNormalEnemyTargetList(true, true, CardType.Monster); + + // become target + if (Duel.LastChainPlayer == 1) + { + List targetedBotMonsterList = Duel.LastChainTargets.Where(c => c.Location == CardLocation.MonsterZone && c.Controller == 0).ToList(); + ClientCard lastChainCard = Util.GetLastChainCard(); + // if it's a negate effect, only destroy not important monster + if (lastChainCard != null && lastChainCard.IsCode(targetNegateIdList)) + { + targetedBotMonsterList = targetedBotMonsterList.Where(c => !c.IsCode(CardId.BlazingCartesiaTheVirtuous) || c.Attack < 2500).OrderBy(c => c.Attack).ToList(); + } + if (targetedBotMonsterList.Count > 0) + { + AI.SelectCard(targetedBotMonsterList); + AI.SelectNextCard(enemyTargetList); + currentDestroyCardList.Add(targetedBotMonsterList[0]); + currentDestroyCardList.Add(enemyTargetList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + // end phase + if (Duel.Player == 1 && Duel.Phase == DuelPhase.End) + { + List botTargetList = Bot.MonsterZone.Where(c => c != null && c.GetDefensePower() <= 2500).OrderBy(c => c.GetDefensePower()).ToList(); + if (botTargetList.Count > 0) + { + AI.SelectCard(botTargetList); + AI.SelectNextCard(enemyTargetList); + currentDestroyCardList.Add(botTargetList[0]); + currentDestroyCardList.Add(enemyTargetList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + return false; + } + + public bool LubellionTheSearingDragonActivate() + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + if (Card.Location == CardLocation.MonsterZone) + { + int fusionTarget = LubellionTheSearingDragonFusionTarget(Bot.ExtraDeck, out _); + if (fusionTarget > 0) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } + return false; + } + + public int LubellionTheSearingDragonFusionTarget(IList cards, out ClientCard target) + { + target = null; + bool hasAlbaz = Bot.Banished.Any(c => c != null && c.IsFaceup() && c.IsOriginalCode(CardId.FallenOfAlbaz)); + hasAlbaz |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.IsOriginalCode(CardId.FallenOfAlbaz)); + Dictionary> checkDict = new Dictionary> + { + {CardId.MirrorjadeTheIcebladeDragon, () => hasAlbaz && !DefaultCheckWhetherCardIdIsNegated(CardId.MirrorjadeTheIcebladeDragon) }, + {CardId.GranguignolTheDuskDragon, () => Bot.HasInBanished(CardId.BlazingCartesiaTheVirtuous) }, + {CardId.BorreloadFuriousDragon, () => + { + int darkDragonCount = Bot.Banished.Where(c => c.IsFaceup() && c.HasRace(CardRace.Dragon) && c.HasAttribute(CardAttribute.Dark) + && !c.IsCode(cannotBeFusionMaterialIdList) ).Count(); + darkDragonCount += Bot.Graveyard.Where(c => c.HasRace(CardRace.Dragon) && c.HasAttribute(CardAttribute.Dark) + && !c.IsCode(cannotBeFusionMaterialIdList) + && (Duel.Player == 1 || !CheckWhetherShouldKeepInGrave(c)) ).Count(); + return darkDragonCount >= 2; + } }, + {CardId.RindbrummTheStrikingDragon, () => hasAlbaz && Bot.HasInBanished(CardId.TriBrigadeMercourier) }, + {CardId.TitanikladTheAshDragon, () => + { + if (!hasAlbaz) return false; + ClientCard enemyMonster = Util.GetBestEnemyMonster(true); + ClientCard botMonster = Util.GetBestBotMonster(true); + int enemyPower = enemyMonster == null ? 0 : enemyMonster.GetDefensePower(); + int botPower = botMonster == null ? 0 : botMonster.Attack; + if (enemyPower > 0 && enemyPower >= botPower) + { + List materialList = new List(Bot.Banished); + materialList.AddRange(Bot.Graveyard); + foreach (ClientCard material in materialList) + { + if (material != null && material.IsFaceup() && material.Attack >= 2500 && (2900 + material.Level >= enemyPower)) + { + return true; + } + } + } + return false; + } }, + {CardId.DespianQuaeritis, () => { + if (!Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && c.Attack > 2500 && !(c.HasType(CardType.Fusion) && c.Level >= 8))) return false; + bool checkFlag = Bot.Banished.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeDespain)); + checkFlag |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeDespain)); + + return checkFlag; + } }, + {CardId.AlbaLenatusTheAbyssDragon, () => hasAlbaz && !Bot.HasInExtra(CardId.AlbionTheBrandedDragon) }, + {CardId.AlbionTheBrandedDragon, () => { + if (activatedCardIdList.Contains(CardId.AlbionTheBrandedDragon) || DefaultCheckWhetherCardIdIsNegated(CardId.AlbionTheBrandedDragon)) return false; + bool checkFlag = Bot.Banished.Any(c => c != null && c.IsFaceup() && c.HasAttribute(CardAttribute.Light)); + checkFlag |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.HasAttribute(CardAttribute.Light)); + + return checkFlag; + }} + }; + + foreach (KeyValuePair> pair in checkDict) + { + target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return pair.Key; + } + } + + target = null; + return 0; + } + + public bool AlbaLenatusTheAbyssDragonSpSummon() + { + // use albaz + enemy's dragon monster + List enemyDragon = Enemy.GetMonsters().Where(c => c != null && c.IsFaceup() && !c.IsCode(cannotBeFusionMaterialIdList) && c.HasRace(CardRace.Dragon)).ToList(); + if (enemyDragon.Count > 0) + { + bool successFlag = enemyDragon.Count > 1; + int bestBotPower = Util.GetBestAttack(Bot); + successFlag |= enemyDragon.Any(c => c.GetDefensePower() >= bestBotPower); + if (successFlag) + { + if (!enemyDragon.Any(c => c.IsCode(CardId.FallenOfAlbaz))) + { + ClientCard botAlbaz = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsCode(CardId.FallenOfAlbaz)); + if (botAlbaz != null) + { + enemyDragon.Add(botAlbaz); + } + } + AI.SelectMaterials(enemyDragon); + return true; + } + } + + return false; + } + + public bool AlbaLenatusTheAbyssDragonActivate() + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool GranguignolTheDuskDragonActivate() + { + int desc = -1; + if (ActivateDescription >= Util.GetStringId(CardId.GranguignolTheDuskDragon, 0)) + { + desc = ActivateDescription - Util.GetStringId(CardId.GranguignolTheDuskDragon, 0); + } + Logger.DebugWriteLine("granguignol: " + desc.ToString()); + + // send to GY + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.GranguignolTheDuskDragon, 0)) + { + if (CheckWhetherNegated(true, true, CardType.Monster) || CheckWhetherWillbeRemoved()) return false; + int checkId = GranguignolTheDuskDragonSendToGYTarget(null, out _); + if (checkId > 0) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } + // spsummon + if (ActivateDescription == Util.GetStringId(CardId.GranguignolTheDuskDragon, 1)) + { + if (CheckWhetherNegated(true, Card.Location == CardLocation.MonsterZone, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public int GranguignolTheDuskDragonSendToGYTarget(IList cards, out ClientCard target) + { + bool needSendBranded = Bot.HasInGraveyard(CardId.BrandedRetribution) && CheckRemainInDeck(CardId.BrandedFusion) > 0; + if (CheckRemainInDeck(CardId.BrandedRetribution) > 0) + { + needSendBranded |= Bot.Graveyard.Any(c => c != null && c.HasType(CardType.Spell | CardType.Trap) && c.HasSetcode(SetcodeBranded) + && !(fusionToGYFlag && c.IsCode(CardId.BrightestBlazingBrandedKing, CardId.BrandedInHighSpirits))); + needSendBranded |= !activatedCardIdList.Contains(CardId.AlbionTheShroudedDragon) && !CheckWhetherWillbeRemoved() && Bot.HasInHandOrInGraveyard(CardId.AlbionTheShroudedDragon); + needSendBranded |= Duel.CurrentChain.Any(c => c.Controller == 0 && c.Location == CardLocation.Grave && c.IsCode(CardId.BystialSaronir)); + } + List>> checkList = new List>> + { + new KeyValuePair>(CardId.BystialSaronir, () => !activatedCardIdList.Contains(CardId.BystialSaronir) && needSendBranded), + new KeyValuePair>(CardId.AlbionTheShroudedDragon, () => !activatedCardIdList.Contains(CardId.AlbionTheShroudedDragon) && needSendBranded ), + new KeyValuePair>(CardId.AlbionTheBrandedDragon, () => !activatedCardIdList.Contains(CardId.AlbionTheBrandedDragon + 1) && !sendToGYThisTurn.Any(c => c.IsCode(CardId.AlbionTheBrandedDragon)) ), + new KeyValuePair>(CardId.TitanikladTheAshDragon, () => !activatedCardIdList.Contains(CardId.TitanikladTheAshDragon) && !sendToGYThisTurn.Any(c => c.IsCode(CardId.TitanikladTheAshDragon)) + && CheckRemainInDeck(CardId.GuidingQuemTheVirtuous, CardId.FallenOfAlbaz) > 0), + new KeyValuePair>(CardId.TheBystialLubellion, () => Bot.HasInMonstersZone(new[] {CardId.AlbionTheBrandedDragon, CardId.TitanikladTheAshDragon}) + && CheckRemainInDeck(CardId.BrandedLost, CardId.BrandedBeast) > 0 ), + new KeyValuePair>(CardId.SprindTheIrondashDragon, () => !activatedCardIdList.Contains(CardId.SprindTheIrondashDragon) && !sendToGYThisTurn.Any(c => c.IsCode(CardId.SprindTheIrondashDragon)) + && CheckRemainInDeck(CardId.SpringansKitt) > 0), + new KeyValuePair>(CardId.DespianLuluwalilith, () => CheckRemainInDeck(CardId.BlazingCartesiaTheVirtuous, CardId.GuidingQuemTheVirtuous) > 0 ), + new KeyValuePair>(CardId.AlbionTheShroudedDragon, () => true ), + }; + + foreach (KeyValuePair> pair in checkList) + { + if (cards == null) + { + if ((CheckRemainInDeck(pair.Key) > 0 || Bot.HasInExtra(pair.Key)) && pair.Value()) + { + target = null; + return pair.Key; + } + } else + { + ClientCard tg = cards.FirstOrDefault(c => c.IsOriginalCode(pair.Key)); + if (tg != null && pair.Value()) + { + target = tg; + return pair.Key; + } + } + } + + target = null; + return 0; + } + + public bool DespianQuaeritisActivate() + { + if (Card.Location == CardLocation.MonsterZone && Duel.Phase == DuelPhase.Main1 && !CheckWhetherNegated(true, true, CardType.Monster)) + { + if ((CurrentTiming & hintTimingMainEnd) != 0 && Duel.Player == 1) + { + int bestBotPower = Util.GetBestPower(Bot, false); + if (Enemy.GetMonsters().Any(c => c.GetDefensePower() >= bestBotPower && c.IsAttack() && !(c.HasType(CardType.Fusion) && c.Level >= 8))) { + activatedCardIdList.Add(Card.Id); + return true; + } + } + if (Duel.Player == 0 && Enemy.GetMonsters().Any(c => c.IsAttack() && !(c.HasType(CardType.Fusion) && c.Level >= 8))) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } + if (Card.Location != CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return true; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + return false; + } + + public bool SprindTheIrondashDragonActivate() + { + // search + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + // destroy + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + int moveDest = SprindTheIrondashDragonMoveZone(0, Card); + if (moveDest > 0) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } + return false; + } + + public int SprindTheIrondashDragonMoveZone(int available = 0, ClientCard selfCard = null) + { + int maxZone = -1; + int maxValue = 0; + for (int zoneId = 0; zoneId < 5; ++zoneId) + { + // check whether can move + if (Bot.MonsterZone[zoneId] != null) continue; + int zone = (int)System.Math.Pow(2, zoneId); + if (available > 0 && (available & zone) == 0) continue; + + int currentValue = SprindTheIrondashDragonDestroyValue(zoneId, selfCard); + if (currentValue > maxValue) + { + maxZone = zone; + maxValue = currentValue; + } + } + return maxZone; + } + + public int SprindTheIrondashDragonDestroyValue(int zoneId, ClientCard selfCard = null) + { + int value = 0; + if (zoneId == 1 || zoneId == 3) + { + ClientCard botMonsterInExtraZone = Bot.MonsterZone[(zoneId + 9) / 2]; + if (botMonsterInExtraZone != null && botMonsterInExtraZone != selfCard && botMonsterInExtraZone.IsFaceup()) value -= 5; + + ClientCard enemyMonserInExtraZone = Enemy.MonsterZone[(11 - zoneId) / 2]; + if (enemyMonserInExtraZone != null && enemyMonserInExtraZone.IsFaceup()) value += 2; + } + ClientCard botSpell = Bot.SpellZone[zoneId]; + if (botSpell != null && botSpell.IsFaceup()) value--; + ClientCard enemyMonster = Enemy.MonsterZone[5 - zoneId]; + if (enemyMonster != null && enemyMonster.IsFaceup()) + { + value++; + if (enemyMonster.IsFloodgate() || enemyMonster.IsMonsterDangerous()) value += 5; + } + ClientCard enemySpell = Enemy.SpellZone[5 - zoneId]; + if (enemySpell != null && enemySpell.IsFaceup()) + { + value++; + if (enemySpell.IsFloodgate()) value += 5; + } + + return value; + } + + public bool TitanikladTheAshDragonActivate() + { + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + return false; + } + + public bool RindbrummTheStrikingDragonActivate() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + bool checkFlag = false; + + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null) + { + checkFlag = Duel.LastChainPlayer == 1; + checkFlag |= Duel.LastChainPlayer == 0 && lastChainCard.IsCode(CardId.MirrorjadeTheIcebladeDragon) && lastChainCard.Location == CardLocation.MonsterZone && Enemy.GetMonsterCount() == 0; + } + + if (checkFlag) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, true, CardType.Monster) || Duel.CurrentChain.Any(c => c.Controller == 0 && c.IsCode(CardId.GuidingQuemTheVirtuous))) return false; + + ClientCard albaz = Bot.Graveyard.FirstOrDefault(c => c.IsOriginalCode(CardId.FallenOfAlbaz)); + bool checkFlag = Card.IsCanRevive() && Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)); + bool albazFlag = CheckAlbazFusion(null, out List materialList) && albaz != null && !spSummoningAlbaz; + if (albazFlag) + { + checkFlag |= materialList.Count > 1; + if (materialList.Count > 0) + { + ClientCard material = materialList[0]; + checkFlag |= material.HasType(CardType.Ritual | CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link); + checkFlag |= material.IsFloodgate() || material.IsOneForXyz() || Util.GetWorstBotMonster()?.GetDefensePower() < material.Attack; + checkFlag |= Duel.Player == 1 && Duel.Phase == DuelPhase.End && Duel.LastChainPlayer == -1; + } + } + + if (checkFlag) + { + albaz = Bot.Graveyard.Where(c => c.IsCode(CardId.FallenOfAlbaz)).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + + if (checkFlag && albaz != null) + { + spSummoningAlbaz = true; + activatedCardIdList.Add(Card.Id + 1); + AI.SelectCard(albaz); + return true; + } + } + } + return false; + } + + public bool AlbionTheBrandedDragonActivate() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + int fusionTarget = AlbionTheBrandedDragonFusionTarget(Bot.ExtraDeck, out _); + if (fusionTarget > 0) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + return false; + } + + public int AlbionTheBrandedDragonFusionTarget(IList cards, out ClientCard target) + { + target = null; + Dictionary> checkDict = new Dictionary> + { + {CardId.MirrorjadeTheIcebladeDragon, () => { + bool checkFlag = !CheckWhetherNegated() && CheckShouldNoMoreSpSummon(); + checkFlag |= Bot.Graveyard.Any(c => c != null && !sendToGYThisTurn.Contains(c) && !c.IsCode(cannotBeFusionMaterialIdList) + && c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)); + return checkFlag; + } }, + {CardId.LubellionTheSearingDragon, () => + { + if (!activatedCardIdList.Contains(CardId.LubellionTheSearingDragon)) + { + List checkMaterialList = new List(Bot.GetMonsters()); + checkMaterialList.AddRange(Bot.Graveyard); + bool albazChecked = false; + bool hasOriginalAlbaz = checkMaterialList.Any(c => c.IsOriginalCode(CardId.FallenOfAlbaz)); + foreach (ClientCard checkCard in checkMaterialList) + { + if (!albazChecked && checkCard.IsCode(CardId.FallenOfAlbaz) && (!hasOriginalAlbaz || !checkCard.IsOriginalCode(CardId.AlbionTheShroudedDragon))) + { + albazChecked = true; + continue; + } + if (checkCard.HasAttribute(CardAttribute.Dark)) return true; + } + if (Bot.HasInHand(CardId.TriBrigadeMercourier) && Bot.Hand.Count >= 2) return true; + } + return false; + } }, + {CardId.BorreloadFuriousDragon, () => { + if (Enemy.GetMonsterCount() + Enemy.GetSpellCount() > 0) + { + int darkDragonCount = Bot.Graveyard.Where(c => c.HasRace(CardRace.Dragon) && c.HasAttribute(CardAttribute.Dark) + && !c.IsCode(cannotBeFusionMaterialIdList) + && (Duel.Player == 1 || !CheckWhetherShouldKeepInGrave(c)) ).Count(); + if (Duel.Player == 1 && Bot.GetMonsters().Any(c => c.HasRace(CardRace.Dragon) && c.HasAttribute(CardAttribute.Dark) && !c.IsCode(cannotBeFusionMaterialIdList))) { + darkDragonCount ++; + } + return darkDragonCount >= 2; + } + return false; + } }, + {CardId.AlbionTheSanctifireDragon, () => + { + ClientCard albaz = Bot.Graveyard.FirstOrDefault(c => c.IsCode(CardId.FallenOfAlbaz)); + ClientCard lightSpellcaster = Bot.Graveyard.FirstOrDefault(c => c.HasRace(CardRace.SpellCaster) && c.HasAttribute(CardAttribute.Light)); + int remainMonsterCount = Enemy.GetGraveyardMonsters().Count; + remainMonsterCount += Bot.Graveyard.Where(c => c.IsMonster() && c != albaz && c != lightSpellcaster).Count(); + remainMonsterCount += Bot.HasInHand(_CardId.MaxxC) ? 1 : 0; + return remainMonsterCount >= 2; + } }, + {CardId.RindbrummTheStrikingDragon, () => Bot.HasInGraveyard(CardId.TriBrigadeMercourier) }, + {CardId.DespianQuaeritis, () => + { + bool checkFlag = Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && c.Attack >= 2500 && !(c.HasType(CardType.Fusion) && c.Level >= 8)); + if (checkFlag) + { + ClientCard despian = Bot.Graveyard.Where(c => c != null && c.HasSetcode(SetcodeDespain) && !CheckWhetherShouldKeepInGrave(c)) + .OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (despian == null) + { + despian = Bot.MonsterZone.Where(c => c != null && c.HasSetcode(SetcodeDespain)).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + } + if (despian != null) + { + return Bot.Graveyard.Any(c => c.HasAttribute(CardAttribute.Light | CardAttribute.Dark) && !CheckWhetherShouldKeepInGrave(c) && c != despian); + } + } + + return false; + } }, + {CardId.TitanikladTheAshDragon, () => + { + ClientCard albaz = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsOriginalCode(CardId.FallenOfAlbaz)); + if (albaz == null) + { + albaz = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsCode(CardId.FallenOfAlbaz)); + } + foreach (ClientCard material in Bot.Graveyard) + { + if (material != null && material != albaz && material.IsMonster() && material.Attack >= 2500 && !material.IsCode(cannotBeFusionMaterialIdList)) + { + bool checkFlag = !Util.IsTurn1OrMain2() && Enemy.GetMonsterCount() == 0; + checkFlag |= !CheckWhetherShouldKeepInGrave(material); + return checkFlag; + } + } + return false; + } }, + {CardId.AlbaLenatusTheAbyssDragon, () => + { + if (Util.GetOneEnemyBetterThanMyBest() == null) + { + ClientCard albaz = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsOriginalCode(CardId.FallenOfAlbaz)); + if (albaz == null) + { + albaz = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsCode(CardId.FallenOfAlbaz)); + } + foreach (ClientCard material in Bot.Graveyard) + { + if (material != null && material != albaz && material.IsMonster() && material.HasRace(CardRace.Dragon) && !material.IsCode(cannotBeFusionMaterialIdList)) + { + return true; + } + } + } + return false; + } }, + {CardId.GranguignolTheDuskDragon, () => + { + if (cards == null) return false; + return true; + } } + }; + + foreach (KeyValuePair> pair in checkDict) + { + target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + return pair.Key; + } + } + + target = null; + return 0; + } + + public bool DespianLuluwalilithActivate() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated(true, false, CardType.Monster)) return false; + if (CheckRemainInDeck(CardId.GuidingQuemTheVirtuous, CardId.BlazingCartesiaTheVirtuous) > 0) + { + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + return false; + } + + public bool SetForChimera() + { + if (Card.Level <= 4) return false; + if (Bot.GetMonsterCount() > 0 || !Bot.HasInHandOrInSpellZone(CardId.BrandedInWhite) || !Bot.HasInExtra(CardId.GuardianChimera)) return false; + if (DefaultCheckWhetherCardIdIsNegated(CardId.GuardianChimera) || CheckWhetherNegated(true, true, CardType.Monster)) return false; + if (Enemy.MonsterZone.All(c => c == null) && Enemy.SpellZone.All(c => c == null)) return false; + + for (int handIndex1 = 0; handIndex1 < Bot.Hand.Count - 1; ++ handIndex1) + { + ClientCard hand1 = Bot.Hand[handIndex1]; + if (!hand1.IsMonster() || hand1.IsCode(Card.Id) || Card.IsCode(hand1.Id)) continue; + for (int handIndex2 = handIndex1 + 1; handIndex2 < Bot.Hand.Count; ++ handIndex2) + { + ClientCard hand2 = Bot.Hand[handIndex2]; + if (!hand2.IsMonster()) continue; + if (hand2.IsCode(Card.Id) || Card.IsCode(hand2.Id) || hand2.IsCode(hand1.Id) || hand1.IsCode(hand2.Id)) continue; + bool checkFlag = Card.HasRace(CardRace.Dragon) || hand1.HasRace(CardRace.Dragon) || hand2.HasRace(CardRace.Dragon); + if (checkFlag) + { + summoned = true; + return true; + } + } + } + + return false; + } + + public bool AdvanceSummon() + { + if (Card.Level < 5) return false; + + List releaseGoal = Bot.MonsterZone.Where(c => c != null && c.IsFaceup() && !c.IsDisabled() && c.IsCode(10158145)).ToList(); + if (releaseGoal.Count > 0) + { + if (Card.Level <= 6) + { + AI.SelectMaterials(releaseGoal); + summoned = true; + return true; + } + + if (Card.Level >= 7) + { + if (releaseGoal.Count < 2) + { + ClientCard anotherMaterial = Bot.MonsterZone.Where(c => c != null && !releaseGoal.Contains(c)).OrderBy(c => c.GetDefensePower()).FirstOrDefault(); + if (anotherMaterial.GetDefensePower() > Card.Attack) return false; + releaseGoal.Add(anotherMaterial); + } + if (releaseGoal.Count >= 2) + { + AI.SelectMaterials(releaseGoal); + summoned = true; + return true; + } + } + } + return false; + } + + public bool SpellSetCheck() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + switch (Card.Id) + { + case CardId.BrandedInHighSpirits: + { + bool checkFlag = (Bot.HasInMonstersZone(CardId.GuidingQuemTheVirtuous) + || (CheckRemainInDeck(CardId.GuidingQuemTheVirtuous) > 0 && sendToGYThisTurn.Any(c => c.IsCode(CardId.TitanikladTheAshDragon)))); + if (!checkFlag) return false; + } + break; + case CardId.BrandedOpening: + { + bool checkFlag = CheckRemainInDeck(CardId.AluberTheJesterOfDespia, CardId.GuidingQuemTheVirtuous) > 0; + if (!checkFlag) return false; + } + break; + case CardId.BrightestBlazingBrandedKing: + { + bool checkFlag = Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.IsCode(albazFusionMonster)); + if (!checkFlag) return false; + } + break; + case CardId.BrandedBeast: + { + bool checkFlag = Bot.HasInGraveyard(CardId.BrandedLost) || Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeBystial)); + checkFlag |= Bot.HasInHand(CardId.BystialSaronir) && (Enemy.Graveyard.Any(c => CheckBystialCanBanish(c)) || Bot.Graveyard.Any(c => CheckBystialCanBanish(c))); + if (!checkFlag) return false; + } + break; + case CardId.BrandedRetribution: + { + bool checkFlag = Bot.Graveyard.Where(c => c.IsCode(albazFusionMonster)).Count() > 1; + checkFlag |= Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.IsCode(albazFusionMonster)); + if (!checkFlag) return false; + } + break; + default: + break; + } + + // select place + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay))) + { + List avoid_list = new List(); + int setForInfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + setForInfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setForInfiniteImpermanence); + return true; + } + else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } + else + { + SelectSTPlace(); + } + return true; + } + + else if (Enemy.HasInSpellZone(_CardId.AntiSpellFragrance, true) || Bot.HasInSpellZone(_CardId.AntiSpellFragrance, true)) + { + if (Card.IsSpell() && !Bot.HasInSpellZone(Card.Id)) + { + SelectSTPlace(); + return true; + } + } + + return false; + } + + protected override bool DefaultSetForDiabellze() + { + if (base.DefaultSetForDiabellze()) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + // for Sanctifire Dragon spsummoned monster + public bool FloogateActivate() + { + if (Card.Owner != 1 && !Card.IsFloodgate()) return false; + if (CheckWhetherNegated()) return false; + if (Executors.Any(e => e != null && e.Type == ExecutorType.Activate && e.CardId == Card.Id)) return false; + if (Duel.LastChainPlayer == 1) + { + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && lastChainCard.IsFaceup() && CheckCanBeTargeted(lastChainCard, true, CardType.Monster) + && (lastChainCard.Location == CardLocation.MonsterZone || lastChainCard.Location == CardLocation.SpellZone)) + { + AI.SelectCard(lastChainCard); + } + } + + return Duel.LastChainPlayer == 1; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/AltergeistExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/AltergeistExecutor.cs new file mode 100644 index 0000000..bd320cf --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/AltergeistExecutor.cs @@ -0,0 +1,2930 @@ +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("Altergeist", "AI_Altergeist")] + public class AltergeistExecutor : DefaultExecutor + { + + public class CardId + { + public const int Kunquery = 52927340; + public const int Marionetter = 53143898; + public const int Multifaker = 42790071; + public const int AB_JS = 14558127; + public const int GO_SR = 59438930; + public const int GR_WC = 62015408; + public const int GB_HM = 73642296; + public const int Silquitous = 89538537; + public const int MaxxC = 23434538; + public const int Meluseek = 25533642; + public const int OneForOne = 2295440; + public const int PotofDesires = 35261759; + public const int PotofIndulgence = 49238328; + public const int Impermanence = 10045474; + public const int WakingtheDragon = 10813327; + public const int EvenlyMatched = 15693423; + public const int Storm = 23924608; + public const int Manifestation = 35146019; + public const int Protocol = 27541563; + public const int Spoofing = 53936268; + public const int ImperialOrder = 61740673; + public const int SolemnStrike = 40605147; + public const int SolemnJudgment = 41420027; + public const int NaturalExterio = 99916754; + public const int UltimateFalcon = 86221741; + public const int Borrelsword = 85289965; + public const int FWD = 05043010; + public const int TripleBurstDragon = 49725936; + public const int HeavymetalfoesElectrumite = 24094258; + public const int Isolde = 59934749; + public const int Hexstia = 1508649; + public const int Needlefiber = 50588353; + public const int Kagari = 63288573; + public const int Shizuku = 90673288; + public const int Linkuriboh = 41999284; + public const int Anima = 94259633; + + public const int SecretVillage = 68462976; + + public const int DarkHole = 53129443; + public const int NaturalBeast = 33198837; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecreel = 51452091; + public const int Anti_Spell = 58921041; + public const int Hayate = 8491308; + public const int Raye = 26077387; + public const int Drones_Token = 52340445; + public const int Iblee = 10158145; + } + + List Impermanence_list = new List(); + bool Multifaker_ssfromhand = false; + bool Multifaker_ssfromdeck = false; + bool Marionetter_reborn = false; + bool Hexstia_searched = false; + bool Meluseek_searched = false; + bool summoned = false; + bool Silquitous_bounced = false; + bool Silquitous_recycled = false; + bool ss_other_monster = false; + List attacked_Meluseek = new List(); + + List SkyStrike_list = new List { + CardId.Raye, CardId.Hayate, CardId.Kagari, CardId.Shizuku, + 21623008, 25955749, 63166095, 99550630, + 25733157, 51227866, CardId.Drones_Token-1,98338152, + 24010609, 97616504, 50005218 + }; + + List cards_improper = new List + { + 0,CardId.WakingtheDragon, CardId.SolemnStrike, CardId.Spoofing, CardId.OneForOne, CardId.PotofDesires, + CardId.Manifestation, CardId.SecretVillage, CardId.ImperialOrder, _CardId.HarpiesFeatherDuster, CardId.GR_WC, + CardId.Protocol, CardId.SolemnJudgment, CardId.Storm, CardId.GO_SR, CardId.Silquitous, + CardId.MaxxC, CardId.Impermanence, CardId.Meluseek, CardId.AB_JS, CardId.Kunquery, + CardId.Marionetter, CardId.Multifaker + }; + + List normal_counter = new List + { + 53262004, 98338152, 32617464, 45041488, CardId.SolemnStrike, + 61257789, 23440231, 27354732, 12408276, 82419869, CardId.Impermanence, + 49680980, 18621798, 38814750, 17266660, 94689635,CardId.AB_JS, + 74762582, 75286651, 4810828, 44665365, 21123811, _CardId.CrystalWingSynchroDragon, + 82044279, 82044280, 79606837, 10443957, 1621413, CardId.Protocol, + 90809975, 8165596, 9753964, 53347303, 88307361, _CardId.GamecieltheSeaTurtleKaiju, + 5818294, 2948263, 6150044, 26268488, 51447164, _CardId.JizukirutheStarDestroyingKaiju, + 97268402 + }; + + List should_not_negate = new List + { + 81275020, 28985331 + }; + + public AltergeistExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // negate + AddExecutor(ExecutorType.Activate, _CardId.ChickenGame, ChickenGame); + AddExecutor(ExecutorType.Repos, EvenlyMatched_Repos); + + AddExecutor(ExecutorType.Activate, CardId.MaxxC, G_activate); + AddExecutor(ExecutorType.Activate, CardId.Anti_Spell, Anti_Spell_activate); + AddExecutor(ExecutorType.Activate, CardId.PotofIndulgence, PotofIndulgence_activate); + + AddExecutor(ExecutorType.Activate, field_activate); + AddExecutor(ExecutorType.Activate, CardId.SecretVillage, SecretVillage_activate); + + AddExecutor(ExecutorType.Activate, CardId.Hexstia, Hexstia_eff); + AddExecutor(ExecutorType.Activate, CardId.NaturalExterio, NaturalExterio_eff); + AddExecutor(ExecutorType.Activate, CardId.TripleBurstDragon, TripleBurstDragon_eff); + AddExecutor(ExecutorType.Activate, CardId.ImperialOrder, ImperialOrder_activate); + AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, SolemnStrike_activate); + AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, SolemnJudgment_activate); + AddExecutor(ExecutorType.Activate, CardId.Protocol, Protocol_negate_better); + AddExecutor(ExecutorType.Activate, CardId.Impermanence, Impermanence_activate); + AddExecutor(ExecutorType.Activate, CardId.Protocol, Protocol_negate); + AddExecutor(ExecutorType.Activate, CardId.Protocol, Protocol_activate_not_use); + AddExecutor(ExecutorType.Activate, CardId.AB_JS, Hand_act_eff); + AddExecutor(ExecutorType.Activate, CardId.GB_HM, Hand_act_eff); + AddExecutor(ExecutorType.Activate, CardId.GO_SR, Hand_act_eff); + + AddExecutor(ExecutorType.Activate, CardId.GR_WC, GR_WC_activate); + AddExecutor(ExecutorType.Activate, CardId.WakingtheDragon, WakingtheDragon_eff); + + // clear + AddExecutor(ExecutorType.Activate, CardId.EvenlyMatched, EvenlyMatched_activate); + AddExecutor(ExecutorType.Activate, _CardId.HarpiesFeatherDuster, Feather_activate); + AddExecutor(ExecutorType.Activate, CardId.Storm, Storm_activate); + + AddExecutor(ExecutorType.Activate, CardId.Meluseek, Meluseek_eff); + AddExecutor(ExecutorType.Activate, CardId.Silquitous, Silquitous_eff); + + AddExecutor(ExecutorType.Activate, CardId.Borrelsword, Borrelsword_eff); + + // spsummon + AddExecutor(ExecutorType.Activate, CardId.Multifaker, Multifaker_handss); + AddExecutor(ExecutorType.Activate, CardId.Manifestation, Manifestation_eff); + AddExecutor(ExecutorType.SpSummon, CardId.Anima, Anima_ss); + AddExecutor(ExecutorType.Activate, CardId.Anima); + AddExecutor(ExecutorType.Activate, CardId.Needlefiber, Needlefiber_eff); + + // effect + AddExecutor(ExecutorType.Activate, CardId.Spoofing, Spoofing_eff); + AddExecutor(ExecutorType.Activate, CardId.Kunquery, Kunquery_eff); + AddExecutor(ExecutorType.Activate, CardId.Multifaker, Multifaker_deckss); + + // summon + AddExecutor(ExecutorType.SpSummon, CardId.Hexstia, Hexstia_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuriboh_ss); + AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, Linkuriboh_eff); + AddExecutor(ExecutorType.Activate, CardId.Marionetter, Marionetter_eff); + AddExecutor(ExecutorType.Activate, CardId.OneForOne, OneForOne_activate); + AddExecutor(ExecutorType.Summon, CardId.Meluseek, Meluseek_summon); + AddExecutor(ExecutorType.Summon, CardId.Marionetter, Marionetter_summon); + AddExecutor(ExecutorType.Summon, CardId.GR_WC, tuner_summon); + AddExecutor(ExecutorType.SpSummon, CardId.Needlefiber, Needlefiber_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Borrelsword, Borrelsword_ss); + AddExecutor(ExecutorType.SpSummon, CardId.TripleBurstDragon, TripleBurstDragon_ss); + + // normal + AddExecutor(ExecutorType.Activate, CardId.PotofDesires, PotofDesires_activate); + AddExecutor(ExecutorType.Summon, CardId.Silquitous, Silquitous_summon); + AddExecutor(ExecutorType.Summon, CardId.Multifaker, Multifaker_summon); + AddExecutor(ExecutorType.Repos, MonsterRepos); + AddExecutor(ExecutorType.Summon, MonsterSummon); + AddExecutor(ExecutorType.MonsterSet, MonsterSet); + AddExecutor(ExecutorType.SpellSet, SpellSet); + } + + public bool EvenlyMatched_ready() + { + if (Bot.HasInHand(CardId.EvenlyMatched) && Bot.GetSpellCount() == 0) + { + if (Duel.Phase < DuelPhase.Main2 && Enemy.GetFieldCount() >= 3 + && Bot.HasInMonstersZone(CardId.Iblee)) return true; + } + return false; + } + + public bool has_altergeist_left() + { + return (Bot.GetRemainingCount(CardId.Marionetter, 3) > 0 + || Bot.GetRemainingCount(CardId.Multifaker, 2) > 0 + || Bot.GetRemainingCount(CardId.Meluseek,3) > 0 + || Bot.GetRemainingCount(CardId.Silquitous,2) > 0 + || Bot.GetRemainingCount(CardId.Kunquery,1) > 0); + } + + public bool EvenlyMatched_Repos() + { + if (EvenlyMatched_ready()) + { + return (!Card.HasPosition(CardPosition.Attack)); + } + return false; + } + + public bool isAltergeist(int id) + { + return (id == CardId.Marionetter || id == CardId.Hexstia || id == CardId.Protocol + || id == CardId.Multifaker || id == CardId.Meluseek || id == CardId.Kunquery + || id == CardId.Manifestation || id == CardId.Silquitous); + } + + public bool isAltergeist(ClientCard card) + { + return card != null && card.HasSetcode(0x103); + } + + public int GetSequence(ClientCard card) + { + if (Card.Location != CardLocation.MonsterZone) return -1; + for (int i = 0; i < 7; ++i) + { + if (Bot.MonsterZone[i] == card) return i; + } + return -1; + } + + public bool trap_can_activate(int id) + { + if (id == CardId.WakingtheDragon || id == CardId.EvenlyMatched) return false; + if (id == CardId.SolemnStrike && Bot.LifePoints <= 1500) return false; + return true; + } + + public bool Should_counter() + { + if (Duel.CurrentChain.Count < 2) return true; + if (!Protocol_activing()) return true; + ClientCard self_card = Duel.CurrentChain[Duel.CurrentChain.Count - 2]; + if (self_card?.Controller != 0 + || !(self_card.Location == CardLocation.MonsterZone || self_card.Location == CardLocation.SpellZone) + || !isAltergeist(self_card)) return true; + ClientCard enemy_card = Duel.CurrentChain[Duel.CurrentChain.Count - 1]; + if (enemy_card?.Controller != 1 + || !enemy_card.IsCode(normal_counter)) return true; + return false; + } + + public bool Should_activate_Protocol() + { + if (Duel.CurrentChain.Count < 2) return false; + if (Protocol_activing()) return false; + ClientCard self_card = Duel.CurrentChain[Duel.CurrentChain.Count - 2]; + if (self_card?.Controller != 0 + || !(self_card.Location == CardLocation.MonsterZone || self_card.Location == CardLocation.SpellZone) + || !isAltergeist(self_card)) return false; + ClientCard enemy_card = Duel.CurrentChain[Duel.CurrentChain.Count - 1]; + if (enemy_card?.Controller != 1 + || !enemy_card.IsCode(normal_counter)) return false; + return true; + } + + public bool is_should_not_negate() + { + ClientCard last_card = Util.GetLastChainCard(); + if (last_card != null + && last_card.Controller == 1 && last_card.IsCode(should_not_negate)) + return true; + return false; + } + + public bool Multifaker_can_ss() + { + foreach (ClientCard sp in Bot.GetSpells()) + { + if (sp.IsTrap() && sp.IsFacedown() && trap_can_activate(sp.Id)) + { + return true; + } + } + foreach (ClientCard h in Bot.Hand) + { + if (h.IsTrap() && trap_can_activate(h.Id)) + { + return true; + } + } + return false; + } + + public bool Multifaker_candeckss() + { + return (!Multifaker_ssfromdeck && !ss_other_monster); + } + + public bool Protocol_activing() + { + foreach(ClientCard card in Bot.GetSpells()) + { + if (card.IsCode(CardId.Protocol) && card.IsFaceup() && !card.IsDisabled() && !Duel.CurrentChain.Contains(card)) return true; + } + return false; + } + + public int GetTotalATK(IList list) + { + int atk = 0; + foreach (ClientCard c in list) + { + if (c == null) continue; + atk += c.Attack; + } + return atk; + } + + public int SelectSTPlace(ClientCard card=null, bool avoid_Impermanence = false) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoid_Impermanence && Impermanence_list.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoid_Impermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + return (int)System.Math.Pow(2, seq); + } + } + foreach (int seq in list) + { + return (int)System.Math.Pow(2, seq); + } + return 0; + } + + public int SelectSetPlace(List avoid_list=null) + { + List list = new List(); + list.Add(0); + list.Add(1); + list.Add(2); + list.Add(3); + list.Add(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 (avoid_list != null && avoid_list.Contains(seq)) continue; + return zone; + }; + } + return 0; + } + + public bool spell_trap_activate(bool isCounter = false, ClientCard target = null) + { + if (target == null) target = Card; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (target.Location != CardLocation.SpellZone && target.Location != CardLocation.Hand) return true; + if (Enemy.HasInMonstersZone(CardId.NaturalExterio, true) && !Bot.HasInHandOrHasInMonstersZone(CardId.GO_SR) && !isCounter && !Bot.HasInSpellZone(CardId.SolemnStrike)) return false; + if (target.IsSpell()) + { + if (Enemy.HasInMonstersZone(CardId.NaturalBeast, true) && !Bot.HasInHandOrHasInMonstersZone(CardId.GO_SR) && !isCounter && !Bot.HasInSpellZone(CardId.SolemnStrike)) return false; + if (Enemy.HasInSpellZone(CardId.ImperialOrder, true) || Bot.HasInSpellZone(CardId.ImperialOrder, true)) return false; + if (Enemy.HasInMonstersZone(CardId.SwordsmanLV7, true) || Bot.HasInMonstersZone(CardId.SwordsmanLV7, true)) return false; + return true; + } + if (target.IsTrap()) + { + if (Enemy.HasInSpellZone(CardId.RoyalDecreel, true) || Bot.HasInSpellZone(CardId.RoyalDecreel, true)) return false; + return true; + } + // how to get here? + return false; + } + + public void RandomSort(List list) + { + + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(n + 1); + ClientCard temp = list[index]; + list[index] = list[n]; + list[n] = temp; + } + } + + public int get_Hexstia_linkzone(int zone) + { + if (zone >= 0 && zone < 4) return zone + 1; + if (zone == 5) return 1; + if (zone == 6) return 3; + return -1; + } + + public bool get_linked_by_Hexstia(int place) + { + if (place == 0) return false; + if (place == 2 || place == 4) + { + int last_place = place - 1; + return (Bot.MonsterZone[last_place] != null && Bot.MonsterZone[last_place].IsCode(CardId.Hexstia)); + } + if (place == 1 || place == 3) + { + int last_place_1, last_place_2; + if (place == 1) + { + last_place_1 = 0; + last_place_2 = 5; + } else + { + last_place_1 = 2; + last_place_2 = 6; + } + if (Bot.MonsterZone[last_place_1] != null && Bot.MonsterZone[last_place_1].IsCode(CardId.Hexstia)) return true; + if (Bot.MonsterZone[last_place_2] != null && Bot.MonsterZone[last_place_2].IsCode(CardId.Hexstia)) return true; + return false; + } + return false; + } + + public ClientCard GetFloodgate_Alter(bool canBeTarget = false, bool is_bounce = true) + { + foreach (ClientCard card in Enemy.GetSpells()) + { + if (card != null && card.IsFloodgate() && card.IsFaceup() && + !card.IsCode(CardId.Anti_Spell, CardId.ImperialOrder) + && (!is_bounce || card.IsTrap()) + && (!canBeTarget || !card.IsShouldNotBeTarget())) + return card; + } + return null; + } + + public ClientCard GetProblematicEnemyCard_Alter(bool canBeTarget = false, bool is_bounce = true) + { + ClientCard card = Enemy.MonsterZone.GetFloodgate(canBeTarget); + if (card != null) + return card; + + card = GetFloodgate_Alter(canBeTarget, is_bounce); + if (card != null) + return card; + + card = Enemy.MonsterZone.GetDangerousMonster(canBeTarget); + if (card != null + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) + return card; + + card = Enemy.MonsterZone.GetInvincibleMonster(canBeTarget); + if (card != null) + return card; + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach(ClientCard target in enemy_monsters) + { + if (target.HasType(CardType.Fusion) || target.HasType(CardType.Ritual) || target.HasType(CardType.Synchro) || target.HasType(CardType.Xyz) || (target.HasType(CardType.Link) && target.LinkCount >= 2) ) + { + if (target.IsCode(CardId.Kagari, CardId.Shizuku)) continue; + if (!canBeTarget || !(target.IsShouldNotBeTarget() || target.IsShouldNotBeMonsterTarget())) return target; + } + } + + return null; + } + + public ClientCard GetBestEnemyCard_random() + { + // monsters + ClientCard card = Util.GetProblematicEnemyMonster(0, true); + if (card != null) + return card; + if (Util.GetOneEnemyBetterThanMyBest() != null) + { + card = Enemy.MonsterZone.GetHighestAttackMonster(true); + if (card != null) + return card; + } + + // spells + List enemy_spells = Enemy.GetSpells(); + RandomSort(enemy_spells); + foreach(ClientCard sp in enemy_spells) + { + if (sp.IsFaceup() && !sp.IsDisabled()) return sp; + } + if (enemy_spells.Count > 0) return enemy_spells[0]; + + List monsters = Enemy.GetMonsters(); + if (monsters.Count > 0) + { + RandomSort(monsters); + return monsters[0]; + } + + return null; + } + + public bool bot_can_s_Meluseek() + { + if (Duel.Player != 0) return false; + foreach(ClientCard card in Bot.GetMonsters()) + { + if (card.IsCode(CardId.Meluseek) && !card.IsDisabled() && !card.Attacked) return true; + } + if (Bot.HasInMonstersZone(CardId.Meluseek)) return true; + if (Bot.HasInMonstersZone(CardId.Marionetter) && !Marionetter_reborn && Bot.HasInGraveyard(CardId.Meluseek)) return true; + if (!summoned + && (Bot.HasInHand(CardId.Meluseek) + || (Bot.HasInHand(CardId.Marionetter) && Bot.HasInGraveyard(CardId.Meluseek))) + )return true; + return false; + } + + public bool SpellSet() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + if (Card.IsCode(CardId.EvenlyMatched) && !Bot.HasInHandOrInSpellZone(CardId.Spoofing) + && !Bot.HasInHandOrInSpellZone(CardId.Protocol) && !Bot.HasInHandOrInSpellZone(CardId.ImperialOrder)) return false; + if (Card.IsCode(CardId.EvenlyMatched) && Bot.HasInSpellZone(CardId.EvenlyMatched)) return false; + if (Card.IsCode(CardId.SolemnStrike) && Bot.LifePoints <= 1500) return false; + if (Card.IsCode(CardId.Spoofing) && Bot.HasInSpellZone(CardId.Spoofing)) return false; + if (Card.IsCode(CardId.Manifestation) && Bot.HasInHandOrInSpellZone(CardId.Spoofing)) + { + bool can_activate = false; + foreach(ClientCard g in Bot.GetGraveyardMonsters()) + { + if (g.IsMonster() && isAltergeist(g)) + { + can_activate = true; + break; + } + } + Logger.DebugWriteLine("Manifestation_set: " + can_activate.ToString()); + if (!can_activate) return false; + } + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay))) + { + List avoid_list = new List(); + int Impermanence_set = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + Impermanence_set += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(CardId.Impermanence)) + { + if (Card.IsCode(CardId.Impermanence)) + { + AI.SelectPlace(Impermanence_set); + return true; + } else + { + AI.SelectPlace(SelectSetPlace(avoid_list)); + return true; + } + } else + { + AI.SelectPlace(SelectSTPlace()); + } + return true; + } + else if (Enemy.HasInSpellZone(CardId.Anti_Spell, true) || Bot.HasInSpellZone(CardId.Anti_Spell, true)) + { + if (Card.IsSpell() && (!Card.IsCode(CardId.OneForOne) || Bot.GetRemainingCount(CardId.Meluseek,3) > 0)) + { + AI.SelectPlace(SelectSTPlace()); + return true; + } + } + return false; + } + + public bool field_activate() + { + if (Card.HasPosition(CardPosition.FaceDown) && Card.HasType(CardType.Field) && Card.Location == CardLocation.SpellZone) + { + // field spells that forbid other fields' activate + return !Card.IsCode(71650854, 78082039); + } + return false; + } + + public bool ChickenGame() + { + Logger.DebugWriteLine("Use override"); + if (!spell_trap_activate()) return false; + if (Bot.LifePoints <= 1000) + return false; + if (Bot.LifePoints - 1000 <= Enemy.LifePoints && ActivateDescription == Util.GetStringId(_CardId.ChickenGame, 0)) + { + return true; + } + if (Bot.LifePoints - 1000 > Enemy.LifePoints && ActivateDescription == Util.GetStringId(_CardId.ChickenGame, 1)) + { + return true; + } + return false; + } + + public bool Anti_Spell_activate() + { + foreach(ClientCard card in Bot.GetSpells()) + { + if (card.IsCode(CardId.Anti_Spell) && card.IsFaceup() && Duel.LastChainPlayer == 0) return false; + } + return true; + } + + public bool SecretVillage_activate() + { + if (!spell_trap_activate()) return false; + if (Bot.SpellZone[5] != null && Bot.SpellZone[5].IsFaceup() && Bot.SpellZone[5].IsCode(CardId.SecretVillage) && Bot.SpellZone[5].Disabled==0) return false; + + if (Multifaker_can_ss() && Bot.HasInHand(CardId.Multifaker)) return true; + foreach(ClientCard card in Bot.GetMonsters()) + { + if (card != null && card.IsFaceup() && (card.Race & (int)CardRace.SpellCaster) != 0 && !card.IsCode(CardId.Meluseek)) return true; + } + return false; + } + + public bool G_activate() + { + return (Duel.Player == 1) && !DefaultCheckWhetherCardIsNegated(Card); + } + + public bool NaturalExterio_eff() + { + if (Duel.LastChainPlayer != 0) + { + AI.SelectCard( + _CardId.HarpiesFeatherDuster, + CardId.PotofDesires, + CardId.OneForOne, + CardId.GO_SR, + CardId.AB_JS, + CardId.GR_WC, + CardId.MaxxC, + CardId.Spoofing, + CardId.SolemnJudgment, + CardId.SolemnStrike, + CardId.ImperialOrder, + CardId.Spoofing, + CardId.Storm, + CardId.EvenlyMatched, + CardId.WakingtheDragon, + CardId.Impermanence, + CardId.Marionetter + ); + return true; + } + return false; + } + + public bool SolemnStrike_activate() + { + if (!Should_counter()) return false; + return (DefaultSolemnStrike() && spell_trap_activate(true)); + } + + public bool SolemnJudgment_activate() + { + if (Util.IsChainTargetOnly(Card) && (Bot.HasInHand(CardId.Multifaker) || Multifaker_candeckss())) return false; + if (!Should_counter()) return false; + if ((DefaultSolemnJudgment() && spell_trap_activate(true))) + { + ClientCard target = Util.GetLastChainCard(); + if (target != null && !target.IsMonster() && !spell_trap_activate(false, target)) return false; + return true; + } + return false; + } + + public bool Impermanence_activate() + { + if (!Should_counter()) return false; + if (!spell_trap_activate()) return false; + // negate before effect used + foreach(ClientCard m in Enemy.GetMonsters()) + { + if (m.IsMonsterShouldBeDisabledBeforeItUseEffect() && !m.IsDisabled() && Duel.LastChainPlayer != 0) + { + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++ i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + AI.SelectCard(m); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + if (LastChainCard == null + && !(Duel.Player == 1 && Duel.Phase > DuelPhase.Main2 && Bot.HasInHand(CardId.Multifaker) && Multifaker_candeckss() && !Multifaker_ssfromhand)) + return false; + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ( (this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || (Util.IsChainTarget(Card)) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster)) + || (Duel.Player == 1 && Duel.Phase > DuelPhase.Main2 && Bot.HasInHand(CardId.Multifaker) && Multifaker_candeckss() && !Multifaker_ssfromhand)) + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach(ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + Impermanence_list.Add(this_seq); + return true; + } + } + } + } + if ( (LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || LastChainCard.IsDisabled() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget()) + && !(Duel.Player == 1 && Duel.Phase > DuelPhase.Main2 && Bot.HasInHand(CardId.Multifaker) && Multifaker_candeckss() && !Multifaker_ssfromhand) ) + return false; + // negate monsters + if (is_should_not_negate() && LastChainCard.Location == CardLocation.MonsterZone) return false; + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + return true; + } + } + } + return true; + } + + public bool Hand_act_eff() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.IsCode(CardId.AB_JS) && Util.GetLastChainCard().HasSetcode(0x11e) && Util.GetLastChainCard().Location == CardLocation.Hand) // Danger! archtype hand effect + return false; + if (Card.IsCode(CardId.GO_SR) && Card.Location == CardLocation.Hand && Bot.HasInMonstersZone(CardId.GO_SR)) return false; + return (Duel.LastChainPlayer == 1); + } + + public bool WakingtheDragon_eff() + { + if (Bot.HasInExtra(CardId.NaturalExterio) && !Multifaker_ssfromdeck) + { + bool has_skystriker = false; + foreach(ClientCard card in Enemy.Graveyard) + { + if (card != null && card.IsCode(SkyStrike_list)) + { + has_skystriker = true; + break; + } + } + if (!has_skystriker) + { + foreach (ClientCard card in Enemy.GetSpells()) + { + if (card != null && card.IsCode(SkyStrike_list)) + { + has_skystriker = true; + break; + } + } + } + if (!has_skystriker) + { + foreach (ClientCard card in Enemy.GetSpells()) + { + if (card != null && card.IsCode(SkyStrike_list)) + { + has_skystriker = true; + break; + } + } + } + if (has_skystriker) + { + AI.SelectCard(CardId.NaturalExterio); + ss_other_monster = true; + return true; + } + } + IList ex_list = new[] { + CardId.UltimateFalcon, + CardId.Borrelsword, + CardId.NaturalExterio, + CardId.FWD, + CardId.TripleBurstDragon, + CardId.HeavymetalfoesElectrumite, + CardId.Isolde, + CardId.Hexstia, + CardId.Needlefiber, + CardId.Multifaker, + CardId.Kunquery + }; + foreach(int id in ex_list) + { + if (Bot.HasInExtra(id)) + { + if (!isAltergeist(id)) + { + if (Multifaker_ssfromdeck) continue; + ss_other_monster = true; + } + Logger.DebugWriteLine(id.ToString()); + AI.SelectCard(id); + return true; + } + } + return true; + } + + public bool GR_WC_activate() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + int warrior_count = 0; + int pendulum_count = 0; + int link_count = 0; + int altergeis_count = 0; + bool has_skystriker_acer = false; + bool has_tuner = false; + bool has_level_1 = false; + foreach (ClientCard card in Enemy.MonsterZone) + { + if (card == null) continue; + if (card.IsCode(CardId.Kagari, CardId.Shizuku, CardId.Hayate, CardId.Raye, CardId.Drones_Token)) has_skystriker_acer = true; + if (card.HasType(CardType.Pendulum)) pendulum_count ++; + if ((card.Race & (int)CardRace.Warrior) != 0) warrior_count ++; + if (card.IsTuner() && (Enemy.GetMonsterCount() >= 2)) has_tuner = true; + if (isAltergeist(card)) altergeis_count++; + if (!card.HasType(CardType.Link) && !card.HasType(CardType.Xyz) && card.Level == 1) has_level_1 = true; + link_count += (card.HasType(CardType.Link) ? card.LinkCount : 1); + } + if (has_skystriker_acer) + { + if (!Enemy.HasInBanished(CardId.Kagari) && Bot.HasInExtra(CardId.Kagari)) + { + AI.SelectCard(CardId.Kagari); + return true; + } else if (!Enemy.HasInBanished(CardId.Shizuku) && Bot.HasInExtra(CardId.Shizuku)) + { + AI.SelectCard(CardId.Shizuku); + return true; + } + } + if (pendulum_count >= 2 && !(Enemy.HasInMonstersZoneOrInGraveyard(CardId.HeavymetalfoesElectrumite) || Enemy.HasInBanished(CardId.HeavymetalfoesElectrumite)) && Bot.HasInExtra(CardId.HeavymetalfoesElectrumite)) + { + AI.SelectCard(CardId.HeavymetalfoesElectrumite); + return true; + } + if (warrior_count >= 2 && !(Enemy.HasInMonstersZoneOrInGraveyard(CardId.Isolde) || Enemy.HasInBanished(CardId.Isolde)) && Bot.HasInExtra(CardId.Isolde)) + { + AI.SelectCard(CardId.Isolde); + return true; + } + if (has_tuner && !Enemy.HasInBanished(CardId.Needlefiber) && Bot.HasInExtra(CardId.Needlefiber) && !Enemy.HasInMonstersZone(CardId.Needlefiber)) + { + AI.SelectCard(CardId.Needlefiber); + return true; + } + if (has_level_1 && !Enemy.HasInHandOrInMonstersZoneOrInGraveyard(CardId.Linkuriboh) && !Enemy.HasInBanished(CardId.Linkuriboh) && Bot.HasInExtra(CardId.Linkuriboh)) + { + AI.SelectCard(CardId.Linkuriboh); + return true; + } + if (altergeis_count > 0 && !Enemy.HasInBanished(CardId.Hexstia) && Bot.HasInExtra(CardId.Hexstia)) + { + AI.SelectCard(CardId.Hexstia); + return true; + } + if (link_count >= 4) + { + if ((Bot.HasInMonstersZone(CardId.UltimateFalcon) || Bot.HasInMonstersZone(CardId.NaturalExterio)) && !(Enemy.HasInMonstersZoneOrInGraveyard(CardId.Borrelsword) || Enemy.HasInBanished(CardId.Borrelsword)) && Bot.HasInExtra(CardId.Borrelsword)) + { + AI.SelectCard(CardId.Borrelsword); + return true; + } + if (!(Enemy.HasInMonstersZoneOrInGraveyard(CardId.FWD) || Enemy.HasInBanished(CardId.FWD)) && Bot.HasInExtra(CardId.FWD)) + { + AI.SelectCard(CardId.FWD); + return true; + } + } + + return false; + } + + public bool ImperialOrder_activate() + { + if (!Card.HasPosition(CardPosition.FaceDown)) return true; + foreach (ClientCard card in Enemy.GetSpells()) + { + if (card.IsSpell() && spell_trap_activate()) return true; + } + if (Duel.Player == 1 && Duel.Phase > DuelPhase.Main2 && Bot.HasInHand(CardId.Multifaker) && (!Multifaker_ssfromhand && Multifaker_candeckss())) return true; + return false; + } + + public bool EvenlyMatched_activate() + { + if (!spell_trap_activate()) return false; + return true; + + // use after ToBattle fix + int bot_count = Bot.GetFieldCount(); + if (Card.Location == CardLocation.Hand) bot_count += 1; + int enemy_count = Enemy.GetFieldCount(); + if (enemy_count - bot_count < 2) return false; + + if (Card.Location == CardLocation.Hand) AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + + public bool Feather_activate() + { + if (!spell_trap_activate()) return false; + if (Util.GetProblematicEnemySpell() != null) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + // activate when more than 2 cards + if (Enemy.GetSpellCount() <= 1) + return false; + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + + public bool Storm_activate() + { + if (!spell_trap_activate()) return false; + List select_list = new List(); + int activate_immediately = 0; + List spells = Enemy.GetSpells(); + RandomSort(spells); + foreach(ClientCard card in spells) + { + if (card != null) + { + if (card.IsFaceup()) + { + if (card.HasType(CardType.Equip) || card.HasType(CardType.Pendulum) || card.HasType(CardType.Field) || card.HasType(CardType.Continuous)) + { + select_list.Add(card); + activate_immediately += 1; + } + } + } + } + foreach (ClientCard card in spells) + { + if (card != null && card.IsFacedown()) + { + select_list.Add(card); + } + } + foreach (ClientCard card in spells) + { + if (card != null && card.IsFaceup() && !select_list.Contains(card)) + { + select_list.Add(card); + } + } + if (Duel.Phase == DuelPhase.End + || activate_immediately >= 2 + || (Util.IsChainTarget(Card) + || (Util.GetLastChainCard() != null && Util.GetLastChainCard().Controller == 1 && Util.GetLastChainCard().IsCode(_CardId.HarpiesFeatherDuster)))) + { + if (select_list.Count > 0) + { + AI.SelectCard(select_list); + return true; + } + } + return false; + } + + public bool Kunquery_eff() + { + if (Card.Location == CardLocation.Hand) + { + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + if (Util.ChainContainsCard(CardId.Linkuriboh)) return false; + if (Bot.BattlingMonster == null || (Enemy.BattlingMonster.Attack >= Bot.BattlingMonster.GetDefensePower()) || Enemy.BattlingMonster.IsMonsterDangerous()) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + } + return false; + } else + { + ClientCard target = GetProblematicEnemyCard_Alter(true, false); + if (target != null) + { + AI.SelectCard(target); + return true; + } + List spells = Enemy.GetSpells(); + RandomSort(spells); + foreach(ClientCard card in spells) + { + if (card.IsFaceup() && !card.IsDisabled()) + { + AI.SelectCard(card); + return true; + } + } + List monsters = Enemy.GetMonsters(); + RandomSort(monsters); + foreach (ClientCard card in monsters) + { + if (card.IsFaceup() && !card.IsDisabled() + && !(card.IsShouldNotBeMonsterTarget() || card.IsShouldNotBeTarget())) + { + AI.SelectCard(card); + return true; + } + } + return false; + } + } + + public bool Marionetter_eff() + { + if (ActivateDescription == -1) + { + if (!Bot.HasInHandOrInSpellZone(CardId.Protocol) && Bot.GetRemainingCount(CardId.Protocol,2) > 0) + { + AI.SelectCard(CardId.Protocol, CardId.Manifestation); + AI.SelectPlace(SelectSetPlace()); + return true; + } else + { + AI.SelectCard(CardId.Manifestation, CardId.Protocol); + AI.SelectPlace(SelectSetPlace()); + return true; + } + } + else + { + if (Card.IsDisabled() && !Protocol_activing()) return false; + int next_card = 0; + bool choose_other = false; + bool can_choose_other = false; + foreach(ClientCard card in Bot.GetSpells()) + { + if (card.IsFaceup() && isAltergeist(card)) + { + can_choose_other = true; + break; + } + } + if (!can_choose_other){ + foreach(ClientCard card in Bot.GetMonsters()) + { + if (card.IsFaceup() && card != Card && isAltergeist(card)) + { + can_choose_other = true; + } + } + } + if (!Util.IsTurn1OrMain2()) + { + ClientCard self_best = Util.GetBestBotMonster(); + ClientCard enemy_best = Util.GetProblematicEnemyCard(self_best.Attack, true); + ClientCard enemy_target = GetProblematicEnemyCard_Alter(true,false); + + if ((enemy_best != null || enemy_target != null) + && Bot.HasInGraveyard(CardId.Meluseek)) next_card = CardId.Meluseek; + else if (Enemy.GetMonsterCount() <= 1 && Bot.HasInGraveyard(CardId.Meluseek) && Enemy.GetFieldCount() > 0) next_card = CardId.Meluseek; + else if (Bot.HasInGraveyard(CardId.Hexstia) && Util.GetProblematicEnemySpell() == null && Util.GetOneEnemyBetterThanValue(3100, true) == null && can_choose_other) + { + next_card = CardId.Hexstia; + choose_other = (Util.GetOneEnemyBetterThanMyBest(true) != null); + } + } + else + { + if (!Meluseek_searched && !Bot.HasInMonstersZone(CardId.Meluseek) && Bot.HasInGraveyard(CardId.Meluseek)) + { + if (Multifaker_candeckss() && Bot.HasInGraveyard(CardId.Multifaker) && Bot.GetRemainingCount(CardId.Meluseek,3) > 0) + { + next_card = CardId.Multifaker; + } else + { + next_card = CardId.Meluseek; + } + } + else if (Multifaker_candeckss() && Bot.HasInGraveyard(CardId.Multifaker) && has_altergeist_left()) + { + next_card = CardId.Multifaker; + } + else if (Bot.HasInGraveyard(CardId.Hexstia)) + { + next_card = CardId.Hexstia; + choose_other = !(Bot.GetMonsterCount() > 1 || Bot.HasInHand(CardId.Multifaker)); + } + else if (Bot.HasInGraveyard(CardId.Silquitous)) + { + int alter_count = 0; + foreach (ClientCard card in Bot.Hand) + { + if (isAltergeist(card) && (card.IsTrap() || (!summoned && card.IsMonster()))) alter_count ++; + } + foreach (ClientCard s in Bot.GetSpells()) + { + if (isAltergeist(s)) alter_count++; + } + foreach(ClientCard m in Bot.GetMonsters()) + { + if (isAltergeist(m) && m != Card) alter_count++; + } + if (alter_count > 0) + { + next_card = CardId.Silquitous; + } + } + } + if (next_card != 0) + { + int Protocol_count = 0; + foreach (ClientCard h in Bot.Hand) + { + if (h.IsCode(CardId.Protocol)) Protocol_count++; + } + foreach (ClientCard s in Bot.GetSpells()) + { + if (s.IsCode(CardId.Protocol)) Protocol_count += (s.IsFaceup() ? 11 : 1); + } + if (Protocol_count >= 12) + { + AI.SelectCard(CardId.Protocol); + AI.SelectNextCard(next_card); + Marionetter_reborn = true; + if (next_card == CardId.Meluseek && Util.IsTurn1OrMain2()) AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + List list = Bot.GetMonsters(); + list.Sort(CardContainer.CompareCardAttack); + foreach (ClientCard card in list) + { + if (isAltergeist(card) && !(choose_other && card == Card)) + { + AI.SelectCard(card); + AI.SelectNextCard(next_card); + if (next_card == CardId.Meluseek && Util.IsTurn1OrMain2()) AI.SelectPosition(CardPosition.FaceUpDefence); + Marionetter_reborn = true; + return true; + } + } + } + else + { + return false; + }; + } + return false; + } + + public bool Hexstia_eff() + { + if (Card.Location == CardLocation.MonsterZone && Duel.LastChainPlayer != 0 && (Protocol_activing() || !Card.IsDisabled())) + { + ClientCard target = Util.GetLastChainCard(); + if (target != null && !spell_trap_activate(false, target)) return false; + if (!Should_counter()) return false; + // check + int this_seq = GetSequence(Card); + if (this_seq != -1) this_seq = get_Hexstia_linkzone(this_seq); + if (this_seq != -1) + { + ClientCard linked_card = Bot.MonsterZone[this_seq]; + if (linked_card != null && linked_card.IsCode(CardId.Hexstia)) + { + int next_seq = get_Hexstia_linkzone(this_seq); + if (next_seq != -1 && Bot.MonsterZone[next_seq] != null && isAltergeist(Bot.MonsterZone[next_seq])) return false; + } + } + return true; + } + if (ActivateDescription == Util.GetStringId(CardId.Hexstia,0)) return false; + if (Enemy.HasInSpellZone(82732705) && Bot.GetRemainingCount(CardId.Protocol,3) > 0 && !Bot.HasInHandOrInSpellZone(CardId.Protocol)) + { + AI.SelectCard(CardId.Protocol); + return true; + } + if (Duel.Player == 0 && !summoned && Bot.GetRemainingCount(CardId.Marionetter, 3) > 0) + { + AI.SelectCard(CardId.Marionetter); + return true; + } + if (!Bot.HasInHandOrHasInMonstersZone(CardId.Multifaker) && Bot.GetRemainingCount(CardId.Multifaker, 2) > 0 && Multifaker_can_ss()) + { + AI.SelectCard(CardId.Multifaker); + return true; + } + if (!Bot.HasInHand(CardId.Marionetter) && Bot.GetRemainingCount(CardId.Marionetter,3) > 0) + { + AI.SelectCard(CardId.Marionetter); + return true; + } + if (!Bot.HasInHandOrInSpellZone(CardId.Manifestation) && Bot.GetRemainingCount(CardId.Manifestation,2) > 0) + { + AI.SelectCard(CardId.Manifestation); + return true; + } + if (!Bot.HasInHandOrInSpellZone(CardId.Protocol) && Bot.GetRemainingCount(CardId.Protocol, 2) > 0) + { + AI.SelectCard(CardId.Protocol); + return true; + } + AI.SelectCard( + CardId.Meluseek, + CardId.Kunquery, + CardId.Marionetter, + CardId.Multifaker, + CardId.Manifestation, + CardId.Protocol, + CardId.Silquitous + ); + return true; + } + + public bool Meluseek_eff() + { + if (ActivateDescription == Util.GetStringId(CardId.Meluseek,0) + || (ActivateDescription == -1 && Card.Location == CardLocation.MonsterZone)) + { + attacked_Meluseek.Add(Card); + ClientCard target = GetProblematicEnemyCard_Alter(true); + if (target != null) + { + AI.SelectCard(target); + return true; + } + target = Util.GetOneEnemyBetterThanMyBest(true, true); + if (target != null) + { + AI.SelectCard(target); + return true; + } + List targets = Enemy.GetSpells(); + RandomSort(targets); + if (targets.Count > 0) + { + AI.SelectCard(targets[0]); + return true; + } + target = GetBestEnemyCard_random(); + if (target != null) + { + AI.SelectCard(target); + return true; + } + } else + { + if (Duel.Player == 1) + { + if (!Bot.HasInHandOrHasInMonstersZone(CardId.Multifaker) && Bot.GetRemainingCount(CardId.Multifaker, 2) > 0 && Multifaker_candeckss() && Multifaker_can_ss()) + { + foreach(ClientCard set_card in Bot.GetSpells()) + { + if (set_card.IsFacedown() && !set_card.IsCode(CardId.WakingtheDragon)) + { + AI.SelectCard(CardId.Multifaker); + return true; + } + } + } + if (Bot.GetRemainingCount(CardId.Marionetter, 3) > 0) + { + AI.SelectCard(CardId.Marionetter); + return true; + } + } + else + { + if (!summoned && !Bot.HasInHand(CardId.Marionetter) && Bot.GetRemainingCount(CardId.Marionetter, 3) > 0) + { + AI.SelectCard(CardId.Marionetter); + return true; + } + if (!Bot.HasInHandOrHasInMonstersZone(CardId.Multifaker) && Bot.GetRemainingCount(CardId.Multifaker, 2) > 0 && Multifaker_can_ss()) + { + AI.SelectCard(CardId.Multifaker); + return true; + } + if (!Bot.HasInHand(CardId.Marionetter) && Bot.GetRemainingCount(CardId.Marionetter,3) > 0) + { + AI.SelectCard(CardId.Marionetter); + return true; + } + } + AI.SelectCard( + CardId.Kunquery, + CardId.Marionetter, + CardId.Multifaker, + CardId.Silquitous + ); + return true; + } + return false; + } + + public bool Multifaker_handss() + { + if (!Multifaker_candeckss() || Card.Location != CardLocation.Hand) return false; + Multifaker_ssfromhand = true; + if (Duel.Player != 0 && Util.GetOneEnemyBetterThanMyBest() != null) AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + + public bool Multifaker_deckss() + { + if (Card.Location != CardLocation.Hand) + { + ClientCard Silquitous_target = GetProblematicEnemyCard_Alter(true); + if (Duel.Player == 1 && Duel.Phase >= DuelPhase.Main2 && GetProblematicEnemyCard_Alter(true) == null && Bot.GetRemainingCount(CardId.Meluseek,3) > 0) + { + AI.SelectCard(CardId.Meluseek); + Multifaker_ssfromdeck = true; + return true; + } + else if (!Silquitous_bounced && !Bot.HasInMonstersZone(CardId.Silquitous) && Bot.GetRemainingCount(CardId.Silquitous,2) > 0 + && !(Duel.Player == 0 && Silquitous_target==null)) + { + AI.SelectCard(CardId.Silquitous); + Multifaker_ssfromdeck = true; + return true; + } + else if (!Meluseek_searched && !Bot.HasInMonstersZone(CardId.Meluseek) && Bot.GetRemainingCount(CardId.Meluseek, 3) > 0) + { + AI.SelectCard(CardId.Meluseek); + Multifaker_ssfromdeck = true; + return true; + } + else if (Bot.GetRemainingCount(CardId.Kunquery,1) > 0) + { + AI.SelectCard(CardId.Kunquery); + Multifaker_ssfromdeck = true; + return true; + } else + { + AI.SelectCard(CardId.Marionetter); + Multifaker_ssfromdeck = true; + return true; + } + } + return false; + } + + public bool Silquitous_eff() + { + if (ActivateDescription != Util.GetStringId(CardId.Silquitous,0)) + { + if (!Bot.HasInHandOrInSpellZone(CardId.Manifestation) && Bot.HasInGraveyard(CardId.Manifestation)) + { + AI.SelectCard(CardId.Manifestation); + } else + { + AI.SelectCard(CardId.Protocol); + } + Silquitous_recycled = true; + return true; + } + else { + ClientCard bounce_self = null; + int Protocol_count = 0; + ClientCard faceup_Protocol = null; + ClientCard faceup_Manifestation = null; + ClientCard selected_target = null; + foreach (ClientCard spell in Bot.GetSpells()) + { + if (spell.IsCode(CardId.Protocol)) + { + if (spell.IsFaceup()) + { + faceup_Protocol = spell; + Protocol_count += 11; + } else + { + Protocol_count++; + } + } + if (spell.IsCode(CardId.Manifestation) && spell.IsFaceup()) faceup_Manifestation = spell; + if (Duel.LastChainPlayer != 0 && Util.IsChainTarget(spell) && spell.IsFaceup() && isAltergeist(spell)) + { + selected_target = spell; + } + } + if (Protocol_count >= 12) + { + bounce_self = faceup_Protocol; + } else if (Duel.Player == 0 && faceup_Protocol != null) + { + bounce_self = faceup_Protocol; + } else if (faceup_Manifestation != null) + { + bounce_self = faceup_Manifestation; + } + ClientCard faceup_Multifaker = null; + ClientCard faceup_monster = null; + List monster_list = Bot.GetMonsters(); + monster_list.Sort(CardContainer.CompareCardAttack); + foreach(ClientCard card in monster_list) + { + if (card.IsFaceup() && isAltergeist(card) && card != Card) + { + if (Duel.LastChainPlayer != 0 && Util.IsChainTarget(card) && card.IsFaceup()) + { + selected_target = card; + } + if (faceup_Multifaker == null && card.IsCode(CardId.Multifaker)) faceup_Multifaker = card; + if (faceup_monster == null && !card.IsCode(CardId.Hexstia)) faceup_monster = card; + } + } + if (bounce_self == null) + { + if (selected_target != null && selected_target != Card) bounce_self = selected_target; + else if (faceup_Multifaker != null) bounce_self = faceup_Multifaker; + else bounce_self = faceup_monster; + } + + ClientCard card_should_bounce_immediately = GetProblematicEnemyCard_Alter(true); + if (card_should_bounce_immediately != null && Duel.LastChainPlayer != 0 && !bot_can_s_Meluseek()) + { + Logger.DebugWriteLine("Silquitous: dangerous"); + AI.SelectCard(bounce_self); + AI.SelectNextCard(card_should_bounce_immediately); + return true; + } + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + if (Duel.LastChainPlayer != 0) + { + Logger.DebugWriteLine("Silquitous: battle"); + if (Util.ChainContainsCard(CardId.Linkuriboh) || Bot.HasInHand(CardId.Kunquery)) return false; + if (Enemy.BattlingMonster != null && Bot.BattlingMonster != null && Enemy.BattlingMonster.GetDefensePower() >= Bot.BattlingMonster.GetDefensePower()) + { + if (Bot.HasInMonstersZone(CardId.Kunquery)) AI.SelectCard(CardId.Kunquery); + else AI.SelectCard(bounce_self); + List enemy_list = Enemy.GetMonsters(); + enemy_list.Sort(CardContainer.CompareCardAttack); + enemy_list.Reverse(); + foreach(ClientCard target in enemy_list) + { + if (target.IsAttack() && !target.IsShouldNotBeMonsterTarget() && !target.IsShouldNotBeTarget()) + { + AI.SelectNextCard(target); + return true; + } + } + AI.SelectNextCard(Enemy.BattlingMonster); + return true; + } + } + } + else if (Duel.Phase > DuelPhase.Main2) + { + if (Duel.LastChainPlayer != 0) + { + Logger.DebugWriteLine("Silquitous: end"); + ClientCard enemy_card = GetBestEnemyCard_random(); + if (enemy_card != null) + { + AI.SelectCard(bounce_self); + AI.SelectNextCard(enemy_card); + return true; + } + } + } else if (Duel.Player == 0) + { + Logger.DebugWriteLine("Silquitous: orenoturn"); + if (Duel.Phase < DuelPhase.Main2 && summoned && bounce_self.IsMonster()) return false; + ClientCard enemy_card = GetBestEnemyCard_random(); + if (enemy_card != null) + { + Logger.DebugWriteLine("Silquitous decide:" + bounce_self?.Name); + AI.SelectCard(bounce_self); + AI.SelectNextCard(enemy_card); + return true; + } + } + } + return false; + } + + public bool Manifestation_eff() + { + if (Card.Location == CardLocation.Grave) + { + if (Util.ChainContainsCard(CardId.Silquitous)) return false; + if (!Bot.HasInHandOrInSpellZone(CardId.Protocol) && !Util.ChainContainsCard(CardId.Protocol)) + { + AI.SelectCard(CardId.Protocol); + return true; + } + return false; + } + else + { + if (Util.ChainContainsCard(CardId.Manifestation) || Util.ChainContainsCard(CardId.Spoofing)) return false; + if (Duel.LastChainPlayer == 0 && !(Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.Hexstia))) return false; + + if (Bot.HasInMonstersZone(CardId.Hexstia)) + { + bool has_position = false; + for (int i = 0; i < 7; ++i) + { + ClientCard target = Bot.MonsterZone[i]; + if (target != null && target.IsCode(CardId.Hexstia)) + { + int next_id = get_Hexstia_linkzone(i); + if (next_id != -1) + { + ClientCard next_card = Bot.MonsterZone[next_id]; + if (next_card == null) + { + has_position = true; + break; + } + } + } + } + if (!has_position) return false; + } + + if (Enemy.HasInMonstersZone(94977269) && Bot.HasInGraveyard(CardId.Silquitous)) + { + AI.SelectCard(CardId.Silquitous); + return true; + } + + if (Multifaker_candeckss() && Bot.HasInGraveyard(CardId.Multifaker) && has_altergeist_left()) + { + if (Bot.HasInHand(CardId.Multifaker) && Bot.HasInGraveyard(CardId.Silquitous) && Bot.GetRemainingCount(CardId.Silquitous,2) == 0) + { + AI.SelectCard(CardId.Silquitous); + return true; + } else + { + AI.SelectCard(CardId.Multifaker); + return true; + } + } + List choose_list = new List(); + choose_list.Add(CardId.Hexstia); + choose_list.Add(CardId.Silquitous); + choose_list.Add(CardId.Meluseek); + choose_list.Add(CardId.Marionetter); + choose_list.Add(CardId.Kunquery); + foreach(int id in choose_list) + { + if (Bot.HasInGraveyard(id)){ + if (id == CardId.Kunquery + && (!Bot.HasInHand(CardId.Multifaker) || !Multifaker_candeckss())) continue; + AI.SelectCard(id); + return true; + } + } + + } + return false; + } + + public bool Protocol_negate_better() + { + // skip if no one of enemy's monsters is better + if (ActivateDescription == Util.GetStringId(CardId.Protocol, 1)) + { + if (Util.GetOneEnemyBetterThanMyBest(true) == null) return false; + } + return Protocol_negate(); + } + + public bool Protocol_negate() + { + // negate + if (ActivateDescription == Util.GetStringId(CardId.Protocol, 1) && (!Card.IsDisabled() || Protocol_activing())) + { + if (!Should_counter()) return false; + if (is_should_not_negate()) return false; + if (Should_activate_Protocol()) return false; + foreach (ClientCard card in Bot.GetSpells()) + { + if (card.IsCode(CardId.Protocol) && card.IsFaceup() && card != Card + && (Card.IsFacedown() || !Card.IsDisabled())) + { + AI.SelectCard(card); + return true; + } + } + if (Bot.HasInMonstersZone(CardId.Hexstia)) + { + for (int i = 0; i < 7; ++i) + { + ClientCard target = Bot.MonsterZone[i]; + if (target != null && isAltergeist(target) && target.IsFaceup()) + { + if (target.IsCode(CardId.Hexstia)) + { + int next_index = get_Hexstia_linkzone(i); + if (next_index != -1 && Bot.MonsterZone[next_index] != null && Bot.MonsterZone[next_index].IsFaceup() && isAltergeist(Bot.MonsterZone[next_index])) continue; + } + if (!get_linked_by_Hexstia(i)) + { + Logger.DebugWriteLine("negate_index: " + i.ToString()); + AI.SelectCard(target); + return true; + } + } + } + } + List cost_list = new List(); + if (Util.ChainContainsCard(CardId.Manifestation)) cost_list.Add(CardId.Manifestation); + if (!Card.IsDisabled()) cost_list.Add(CardId.Protocol); + cost_list.Add(CardId.Multifaker); + cost_list.Add(CardId.Marionetter); + cost_list.Add(CardId.Kunquery); + if (Meluseek_searched) cost_list.Add(CardId.Meluseek); + if (Silquitous_bounced) cost_list.Add(CardId.Silquitous); + for (int i = 0; i < 7; ++i) + { + ClientCard card = Bot.MonsterZone[i]; + if (card != null && card.IsCode(CardId.Hexstia)) + { + int nextzone = get_Hexstia_linkzone(i); + if (nextzone != -1) + { + ClientCard linkedcard = Bot.MonsterZone[nextzone]; + if (linkedcard == null || !isAltergeist(linkedcard)) + { + cost_list.Add(CardId.Hexstia); + } + } else + { + cost_list.Add(CardId.Hexstia); + } + } + } + if (!Silquitous_bounced) cost_list.Add(CardId.Silquitous); + if (!Meluseek_searched) cost_list.Add(CardId.Meluseek); + if (!Util.ChainContainsCard(CardId.Manifestation)) cost_list.Add(CardId.Manifestation); + AI.SelectCard(cost_list); + return true; + } + return false; + } + + public bool Protocol_activate_not_use() + { + if (Util.GetLastChainCard() != null && Util.GetLastChainCard().Controller == 0 && Util.GetLastChainCard().IsTrap()) return false; + if (ActivateDescription != Util.GetStringId(CardId.Protocol, 1)) + { + if (Util.IsChainTarget(Card) && Card.IsFacedown()) return true; + if (Should_activate_Protocol()) return true; + if (!Multifaker_ssfromhand && Multifaker_candeckss() && (Bot.HasInHand(CardId.Multifaker) || Bot.HasInSpellZone(CardId.Spoofing))) + { + if (!Bot.HasInMonstersZone(CardId.Hexstia)) return true; + for (int i = 0; i < 7; ++i) + { + if (i == 4) continue; + if (Bot.MonsterZone[i] != null && Bot.MonsterZone[i].IsCode(CardId.Hexstia)) + { + int next_id = get_Hexstia_linkzone(i); + if (next_id != -1) + { + if (Bot.MonsterZone[next_id] == null) return true; + } + } + } + } + int can_bounce = 0; + bool should_disnegate = false; + foreach(ClientCard card in Bot.GetMonsters()) + { + if (isAltergeist(card)) + { + if (card.IsCode(CardId.Silquitous) && card.IsFaceup() && !Silquitous_bounced) can_bounce += 10; + else if (card.IsFaceup() && !card.IsCode(CardId.Hexstia)) can_bounce++; + if (card.IsDisabled() && !Protocol_activing()) should_disnegate = true; + } + } + if (can_bounce == 10 || should_disnegate) return true; + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2 && Bot.HasInHand(CardId.Kunquery) && Util.GetOneEnemyBetterThanMyBest() != null) return true; + } + return false; + } + + public void Spoofing_select(IList list) + { + foreach(ClientCard card in Duel.CurrentChain) + { + if (card != null + && card.Location == CardLocation.SpellZone && card.Controller == 0 && card.IsFaceup()) + { + if (card.IsCode(CardId.Manifestation)) + { + AI.SelectCard(card); + return; + } + } + } + foreach (ClientCard card in Bot.Hand) + { + foreach (int id in list) + { + if (card.IsCode(id) && !(id == CardId.Multifaker && Util.GetLastChainCard() == card)) + { + AI.SelectCard(card); + return; + } + } + } + foreach(ClientCard card in Bot.GetSpells()) + { + foreach (int id in list) + { + if (card.IsFaceup() && card.IsCode(id)) + { + AI.SelectCard(card); + return; + } + } + } + foreach (ClientCard card in Bot.GetMonsters()) + { + foreach (int id in list) + { + if (card.IsFaceup() && card.IsCode(id)) + { + AI.SelectCard(card); + return; + } + } + } + AI.SelectCard((ClientCard)null); + } + + public bool Spoofing_eff() + { + if (Util.ChainContainsCard(CardId.Spoofing)) return false; + if (Card.IsDisabled()) return false; + if (!Util.ChainContainPlayer(0) && !Multifaker_ssfromhand && Multifaker_candeckss() && Bot.HasInHand(CardId.Multifaker) && Card.HasPosition(CardPosition.FaceDown)) + { + AI.SelectYesNo(false); + return true; + } + bool has_cost = false; + bool can_ss_Multifaker = Multifaker_can_ss() || Card.IsFacedown(); + // cost check(not select) + if (Card.IsFacedown()) + { + foreach(ClientCard card in Bot.Hand) + { + if (isAltergeist(card)) + { + has_cost = true; + break; + } + } + if (!has_cost) + { + foreach(ClientCard card in Bot.GetSpells()) + { + if (isAltergeist(card) && card.IsFaceup()) + { + has_cost = true; + break; + } + } + } + if (!has_cost) + { + foreach(ClientCard card in Bot.GetMonsters()) + { + if (isAltergeist(card) && card.IsFaceup()) + { + has_cost = true; + break; + } + } + } + if (!has_cost) + { + foreach (ClientCard card in Bot.GetSpells()) + { + if (isAltergeist(card) && card.IsFaceup()) + { + has_cost = true; + break; + } + } + } + if (!has_cost) return false; + } + if (Duel.Player == 1) + { + if (!Multifaker_ssfromhand && Multifaker_candeckss() && !Bot.HasInHand(CardId.Multifaker) && can_ss_Multifaker) + { + if (Bot.HasInHand(CardId.Silquitous)) + { + foreach (ClientCard card in Bot.Hand) + { + if (card.IsCode(CardId.Silquitous)) + { + AI.SelectCard(card); + AI.SelectNextCard(CardId.Multifaker, CardId.Kunquery); + return true; + } + } + } + else + { + Spoofing_select(new[] + { + CardId.Silquitous, + CardId.Manifestation, + CardId.Kunquery, + CardId.Marionetter, + CardId.Multifaker, + CardId.Protocol, + CardId.Meluseek + }); + AI.SelectNextCard( + CardId.Multifaker, + CardId.Marionetter, + CardId.Meluseek, + CardId.Kunquery, + CardId.Silquitous + ); + return true; + } + } + } + else + { + ClientCard self_best = Util.GetBestBotMonster(); + int best_atk = self_best == null ? 0 : self_best.Attack; + ClientCard enemy_best = Util.GetProblematicEnemyCard(best_atk, true); + ClientCard enemy_target = GetProblematicEnemyCard_Alter(true, false); + + if (!Multifaker_ssfromhand && Multifaker_candeckss() && can_ss_Multifaker) + { + Spoofing_select(new[]{ + CardId.Silquitous, + CardId.Manifestation, + CardId.Kunquery, + CardId.Marionetter, + CardId.Multifaker, + CardId.Protocol, + CardId.Meluseek + }); + AI.SelectNextCard( + CardId.Multifaker, + CardId.Marionetter, + CardId.Meluseek, + CardId.Kunquery, + CardId.Silquitous + ); + } + else if (!summoned && !Bot.HasInGraveyard(CardId.Meluseek) && Bot.GetRemainingCount(CardId.Meluseek,3) > 0 && !Bot.HasInHand(CardId.Meluseek) + && (enemy_best != null || enemy_target != null) ) + { + if (Bot.HasInHand(CardId.Silquitous)) + { + foreach (ClientCard card in Bot.Hand) + { + if (card.IsCode(CardId.Silquitous)) + { + AI.SelectCard(card); + AI.SelectNextCard( + CardId.Meluseek, + CardId.Marionetter + ); + return true; + } + } + } + else + { + Spoofing_select(new[] + { + CardId.Silquitous, + CardId.Manifestation, + CardId.Kunquery, + CardId.Multifaker, + CardId.Protocol, + CardId.Meluseek, + CardId.Marionetter, + }); + AI.SelectNextCard( + CardId.Meluseek, + CardId.Marionetter, + CardId.Multifaker, + CardId.Kunquery + ); + return true; + } + } + else if (!summoned && !Bot.HasInHand(CardId.Marionetter) && Bot.GetRemainingCount(CardId.Marionetter,3) > 0) + { + if (Bot.HasInHand(CardId.Silquitous)) + { + foreach (ClientCard card in Bot.Hand) + { + if (card.IsCode(CardId.Silquitous)) + { + AI.SelectCard(card); + AI.SelectNextCard( + CardId.Marionetter, + CardId.Meluseek + ); + return true; + } + } + } + else + { + Spoofing_select(new[] + { + CardId.Silquitous, + CardId.Manifestation, + CardId.Kunquery, + CardId.Multifaker, + CardId.Protocol, + CardId.Meluseek, + CardId.Marionetter, + }); + AI.SelectNextCard( + CardId.Marionetter, + CardId.Meluseek, + CardId.Multifaker, + CardId.Kunquery + ); + return true; + } + } + } + // target protect + bool go = false; + foreach(ClientCard card in Bot.GetSpells()) + { + if ( (Util.ChainContainsCard(_CardId.HarpiesFeatherDuster) || Util.IsChainTarget(card)) + && card.IsFaceup() && Duel.LastChainPlayer != 0 && isAltergeist(card)) + { + AI.SelectCard(card); + go = true; + break; + } + } + if (!go) + { + foreach (ClientCard card in Bot.GetMonsters()) + { + if ( (Util.IsChainTarget(card) || Util.ChainContainsCard(CardId.DarkHole) || (!Protocol_activing() && card.IsDisabled())) + && card.IsFaceup() && Duel.LastChainPlayer != 0 && isAltergeist(card)) + { + Logger.DebugWriteLine("Spoofing target:" + card?.Name); + AI.SelectCard(card); + go = true; + break; + } + } + } + if (go) + { + AI.SelectNextCard( + CardId.Marionetter, + CardId.Meluseek, + CardId.Multifaker, + CardId.Kunquery + ); + return true; + } + return false; + } + + public bool OneForOne_activate() + { + if (!spell_trap_activate()) return false; + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.Meluseek) && !Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.Multifaker)) + { + AI.SelectCard( + CardId.GR_WC, + CardId.MaxxC, + CardId.Kunquery, + CardId.GO_SR + ); + if (Util.IsTurn1OrMain2()) AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + if (!summoned && !Meluseek_searched && !Bot.HasInHand(CardId.Marionetter)) + { + AI.SelectCard( + CardId.GR_WC, + CardId.MaxxC, + CardId.Kunquery, + CardId.GO_SR + ); + return true; + } + return false; + } + + public bool Meluseek_summon() + { + if (EvenlyMatched_ready()) return false; + if (Bot.HasInHand(CardId.Marionetter) && Bot.HasInGraveyard(CardId.Meluseek) && !Marionetter_reborn) return false; + summoned = true; + return true; + } + + public bool Marionetter_summon() + { + if (EvenlyMatched_ready()) return false; + summoned = true; + return true; + } + + public bool Silquitous_summon() + { + if (EvenlyMatched_ready()) return false; + bool can_summon = false; + if (Enemy.GetMonsterCount() == 0 && Enemy.LifePoints <= 800) return true; + foreach (ClientCard card in Bot.Hand) + { + if (isAltergeist(card) && card.IsTrap()) + { + can_summon = true; + break; + } + } + foreach(ClientCard card in Bot.GetMonstersInMainZone()) + { + if (isAltergeist(card)) + { + can_summon = true; + break; + } + } + foreach(ClientCard card in Bot.GetSpells()) + { + if (isAltergeist(card)) + { + can_summon = true; + break; + } + } + if (can_summon) + { + summoned = true; + return true; + } else + { + return false; + } + } + + public bool Multifaker_summon() + { + if (EvenlyMatched_ready()) return false; + if (Enemy.GetMonsterCount() == 0 && Enemy.LifePoints <= 1200) return true; + if (Bot.HasInMonstersZone(CardId.Silquitous) || Bot.HasInHandOrInSpellZone(CardId.Spoofing)) + { + summoned = true; + return true; + } + return false; + } + + public bool PotofDesires_activate() + { + if (Bot.Deck.Count > 15 && spell_trap_activate()) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + return false; + } + + public bool PotofIndulgence_activate() + { + if (!spell_trap_activate()) return false; + if (!Bot.HasInGraveyard(CardId.Linkuriboh) && !Bot.HasInGraveyard(CardId.Hexstia)) + { + int important_count = 0; + foreach (ClientCard card in Bot.ExtraDeck) + { + if (card.Id == CardId.Linkuriboh || card.Id == CardId.Hexstia) + { + important_count++; + } + } + if (important_count > 0) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + AI.SelectOption(1); + return true; + } + return false; + } + AI.SelectPlace(SelectSTPlace(Card, true)); + AI.SelectOption(1); + return true; + } + + public bool Anima_ss() + { + if (Duel.Phase != DuelPhase.Main2) return false; + ClientCard card_ex_left = Enemy.MonsterZone[6]; + ClientCard card_ex_right = Enemy.MonsterZone[5]; + if (card_ex_left != null && card_ex_left.HasLinkMarker((int)CardLinkMarker.Top)) + { + ClientCard self_card_1 = Bot.MonsterZone[1]; + if (self_card_1 == null) + { + AI.SelectMaterials(CardId.Meluseek); + AI.SelectPlace(Zones.z1); + ss_other_monster = true; + return true; + } else if (self_card_1.IsCode(CardId.Meluseek)) + { + AI.SelectMaterials(self_card_1); + AI.SelectPlace(Zones.z1); + ss_other_monster = true; + return true; + } + } + if (card_ex_right != null && card_ex_right.HasLinkMarker((int)CardLinkMarker.Top)) + { + ClientCard self_card_2 = Bot.MonsterZone[3]; + if (self_card_2 == null) + { + AI.SelectMaterials(CardId.Meluseek); + AI.SelectPlace(Zones.z3); + ss_other_monster = true; + return true; + } + else if (self_card_2.IsCode(CardId.Meluseek)) + { + AI.SelectMaterials(self_card_2); + AI.SelectPlace(Zones.z3); + ss_other_monster = true; + return true; + } + } + ClientCard card_left = Enemy.MonsterZone[3]; + ClientCard card_right = Enemy.MonsterZone[1]; + if (card_left != null && card_left.IsFacedown()) card_left = null; + if (card_right != null && card_right.IsFacedown()) card_right = null; + if (card_left != null && (card_left.IsShouldNotBeMonsterTarget() || card_left.IsShouldNotBeTarget())) card_left = null; + if (card_right != null && (card_right.IsShouldNotBeMonsterTarget() || card_right.IsShouldNotBeTarget())) card_right = null; + if (Enemy.MonsterZone[6] != null) card_left = null; + if (Enemy.MonsterZone[5] != null) card_right = null; + if (card_left == null && card_right != null) + { + if (Bot.MonsterZone[6] == null) + { + AI.SelectMaterials(CardId.Meluseek); + AI.SelectPlace(Zones.z6); + ss_other_monster = true; + return true; + } + } + if (card_left != null && card_right == null) + { + if (Bot.MonsterZone[5] == null) + { + AI.SelectMaterials(CardId.Meluseek); + AI.SelectPlace(Zones.z5); + ss_other_monster = true; + return true; + } + } + if (card_left != null && card_right != null && Bot.GetMonstersExtraZoneCount() == 0) + { + int selection = 0; + if (card_left.IsFloodgate() && !card_right.IsFloodgate()) selection = Zones.z5; + else if (!card_left.IsFloodgate() && card_right.IsFloodgate()) selection = Zones.z6; + else + { + if (card_left.GetDefensePower() >= card_right.GetDefensePower()) selection = Zones.z5; + else selection = Zones.z6; + } + AI.SelectPlace(selection); + AI.SelectMaterials(CardId.Meluseek); + ss_other_monster = true; + return true; + } + return false; + } + + public bool Linkuriboh_ss() + { + if (Bot.GetMonstersExtraZoneCount() > 0) return false; + if (Util.IsTurn1OrMain2() && !Meluseek_searched) + { + AI.SelectPlace(Zones.z5); + ss_other_monster = true; + return true; + } + return false; + } + + public bool Linkuriboh_eff() + { + if (Util.ChainContainsCard(CardId.Linkuriboh)) return false; + if (Util.ChainContainsCard(CardId.Multifaker)) return false; + if (Duel.Player == 1) + { + if (Card.Location == CardLocation.Grave) + { + AI.SelectCard(new[] { CardId.Meluseek }); + ss_other_monster = true; + return true; + } else + { + if (Card.IsDisabled() && !Enemy.HasInSpellZone(82732705, true)) return false; + ClientCard enemy_card = Enemy.BattlingMonster; + if (enemy_card == null) return false; + ClientCard self_card = Bot.BattlingMonster; + if (self_card == null) return (!enemy_card.IsCode(CardId.Hayate)); + return (enemy_card.Attack > self_card.GetDefensePower()); + } + } + else + { + if (!summoned && !Bot.HasInHand(CardId.Marionetter) && !Meluseek_searched && (Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2)) + { + AI.SelectCard(new[] { CardId.Meluseek }); + ss_other_monster = true; + AI.SelectPlace(Zones.z0 | Zones.z4); + return true; + } + else if (Util.IsTurn1OrMain2()) + { + AI.SelectCard(new[] { CardId.Meluseek }); + ss_other_monster = true; + AI.SelectPlace(Zones.z0 | Zones.z4); + return true; + } + else if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + if (Duel.Player != 0 || attacked_Meluseek.Count == 0 || Enemy.GetMonsterCount() > 0) return false; + foreach (ClientCard card in attacked_Meluseek) + { + if (card != null && card.Location == CardLocation.MonsterZone) + { + + ss_other_monster = true; + AI.SelectPlace(Zones.z0 | Zones.z4); + return true; + } + } + } + } + return false; + } + + public bool Hexstia_ss() + { + List targets = new List(); + List list = Bot.GetMonsters(); + list.Sort(CardContainer.CompareCardAttack); + //list.Reverse(); + bool Meluseek_selected = false; + bool Silquitous_selected = false; + bool Hexstia_selected = false; + int altergeist_count = 0; + foreach (ClientCard card in list) + { + if (isAltergeist(card)) altergeist_count++; + if (card.IsCode(CardId.Meluseek) && targets.Count < 2 && card.IsFaceup()) + { + if ((!Meluseek_searched || !Meluseek_selected) && (!summoned || Duel.Phase == DuelPhase.Main2)) + { + Meluseek_selected = true; + targets.Add(card); + } + } + else if (card.IsCode(CardId.Silquitous) && targets.Count < 2 && card.IsFaceup() && !Bot.HasInGraveyard(CardId.Silquitous)) + { + if (!Silquitous_recycled || !Silquitous_selected) + { + Silquitous_selected = true; + targets.Add(card); + } + } + else if (card.IsCode(CardId.Hexstia) && targets.Count < 2 && card.IsFaceup()) + { + if ((!Hexstia_searched || !Hexstia_selected) && !summoned && !Bot.HasInHand(CardId.Marionetter) && Bot.GetRemainingCount(CardId.Marionetter, 3) > 0) + { + Hexstia_selected = true; + targets.Add(card); + } + } + else if (isAltergeist(card) && targets.Count < 2 && card.IsFaceup()) targets.Add(card); + else if (card.IsCode(CardId.Silquitous) && targets.Count < 2 && card.IsFaceup()) + { + if (!Silquitous_recycled || !Silquitous_selected) + { + Silquitous_selected = true; + targets.Add(card); + } + } + } + if (targets.Count >= 2) + { + if (Duel.Phase < DuelPhase.Main2) + { + if (GetTotalATK(targets) >= 1500 && (summoned || (!Meluseek_selected && !Hexstia_selected))) return false; + } + bool can_have_Multifaker = (Bot.HasInHand(CardId.Multifaker) + || (Bot.GetRemainingCount(CardId.Multifaker, 2) > 0 + && ( (Meluseek_selected && !Meluseek_searched) + || (Hexstia_selected && !Hexstia_searched) ))); + if (can_have_Multifaker && Multifaker_can_ss()) altergeist_count++; + if (Bot.HasInHandOrInSpellZone(CardId.Manifestation)) altergeist_count++; + Logger.DebugWriteLine("Multifaker_ss_check: count = " + altergeist_count.ToString()); + if (altergeist_count <= 2) return false; + AI.SelectMaterials(targets); + return true; + } + return false; + } + + public bool TripleBurstDragon_eff() + { + if (ActivateDescription != Util.GetStringId(CardId.TripleBurstDragon,0)) return false; + return (Duel.LastChainPlayer != 0); + } + + public bool TripleBurstDragon_ss() + { + if (!Enemy.HasInGraveyard(CardId.Raye)) + { + ClientCard self_best = Util.GetBestBotMonster(true); + int self_power = (self_best != null) ? self_best.Attack : 0; + ClientCard enemy_best = Util.GetBestEnemyMonster(true); + int enemy_power = (enemy_best != null) ? enemy_best.GetDefensePower() : 0; + if (enemy_power <= self_power) return false; + Logger.DebugWriteLine("Three: enemy: " + enemy_power.ToString() + ", bot: " + self_power.ToString()); + if (enemy_power >= 2401) return false; + }; + foreach (ClientCard card in Bot.GetMonstersInExtraZone()) + { + if (!card.HasType(CardType.Link)) return false; + } + int link_count = 0; + if (Enemy.HasInMonstersZone(CardId.Shizuku) && Enemy.GetGraveyardSpells().Count >= 9) return false; + List list = new List(); + if (Bot.HasInMonstersZone(CardId.Needlefiber)) + { + foreach(ClientCard card in Bot.GetMonsters()) + { + if (card.IsCode(CardId.Needlefiber)) + { + list.Add(card); + link_count += 2; + } + } + } + List monsters = Bot.GetMonsters(); + monsters.Sort(CardContainer.CompareCardAttack); + //monsters.Reverse(); + foreach(ClientCard card in monsters) + { + if (!list.Contains(card) && card.LinkCount < 3) + { + list.Add(card); + link_count += (card.HasType(CardType.Link) ? card.LinkCount : 1); + if (link_count >= 3) break; + } + } + if (link_count >= 3) + { + AI.SelectMaterials(list); + ss_other_monster = true; + return true; + } + return false; + + } + + public bool Needlefiber_ss() + { + if (!Enemy.HasInGraveyard(CardId.Raye)) + { + ClientCard self_best = Util.GetBestBotMonster(true); + int self_power = (self_best != null) ? self_best.Attack : 0; + ClientCard enemy_best = Util.GetBestEnemyMonster(true); + int enemy_power = (enemy_best != null) ? enemy_best.GetDefensePower() : 0; + if (enemy_power < self_power) return false; + if (Bot.GetMonsterCount() <= 2 && enemy_power >= 2401) return false; + } + foreach(ClientCard card in Bot.GetMonstersInExtraZone()) + { + if (!card.HasType(CardType.Link)) return false; + } + List material_list = new List(); + List monsters = Bot.GetMonsters(); + monsters.Sort(CardContainer.CompareCardAttack); + //monsters.Reverse(); + foreach(ClientCard t in monsters) + { + if (t.IsTuner()) + { + material_list.Add(t); + break; + } + } + foreach(ClientCard m in monsters) + { + if (!material_list.Contains(m) && m.LinkCount <= 2) + { + material_list.Add(m); + if (material_list.Count >= 2) break; + } + } + AI.SelectMaterials(material_list); + ss_other_monster = true; + return true; + } + + public bool Needlefiber_eff() + { + AI.SelectCard( + CardId.GR_WC, + CardId.GO_SR, + CardId.AB_JS + ); + return true; + } + + public bool Borrelsword_ss() + { + if (Duel.Phase != DuelPhase.Main1) return false; + + ClientCard self_best = Util.GetBestBotMonster(true); + int self_power = (self_best != null) ? self_best.Attack : 0; + ClientCard enemy_best = Util.GetBestEnemyMonster(true); + int enemy_power = (enemy_best != null) ? enemy_best.GetDefensePower() : 0; + if (enemy_power < self_power) return false; + + foreach (ClientCard card in Bot.GetMonstersInExtraZone()) + { + if (!card.HasType(CardType.Link)) return false; + } + + List material_list = new List(); + List bot_monster = Bot.GetMonsters(); + bot_monster.Sort(CardContainer.CompareCardAttack); + //bot_monster.Reverse(); + int link_count = 0; + foreach(ClientCard card in bot_monster) + { + if (card.IsFacedown()) continue; + if (!material_list.Contains(card) && card.LinkCount < 3) + { + material_list.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 4) break; + } + } + if (link_count >= 4) + { + AI.SelectMaterials(material_list); + ss_other_monster = true; + return true; + } + return false; + } + + public bool Borrelsword_eff() + { + if (ActivateDescription == -1) return true; + else if ((Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) || Util.IsChainTarget(Card)) + { + List enemy_list = Enemy.GetMonsters(); + enemy_list.Sort(CardContainer.CompareCardAttack); + enemy_list.Reverse(); + foreach(ClientCard card in enemy_list) + { + if (card.HasPosition(CardPosition.Attack) && !card.HasType(CardType.Link)) + { + AI.SelectCard(card); + return true; + } + } + List bot_list = Bot.GetMonsters(); + bot_list.Sort(CardContainer.CompareCardAttack); + //bot_list.Reverse(); + foreach (ClientCard card in bot_list) + { + if (card.HasPosition(CardPosition.Attack) && !card.HasType(CardType.Link)) + { + AI.SelectCard(card); + return true; + } + } + } + return false; + } + + public bool tuner_summon() + { + if (EvenlyMatched_ready()) return false; + foreach (ClientCard card in Bot.GetMonstersInExtraZone()) + { + if (card != null && !card.HasType(CardType.Link)) return false; + } + if (!Enemy.HasInGraveyard(CardId.Raye)) + { + ClientCard self_best = Util.GetBestBotMonster(true); + int self_power = (self_best != null) ? self_best.Attack : 0; + ClientCard enemy_best = Util.GetBestEnemyMonster(true); + int enemy_power = (enemy_best != null) ? enemy_best.GetDefensePower() : 0; + Logger.DebugWriteLine("Tuner: enemy: " + enemy_power.ToString() + ", bot: " + self_power.ToString()); + if (enemy_power < self_power || enemy_power == 0) return false; + int real_count = (Bot.HasInExtra(CardId.Needlefiber)) ? Bot.GetMonsterCount() + 2 : Bot.GetMonsterCount() + 1; + if ((real_count <= 3 && enemy_power >= 2400) + || !(Bot.HasInExtra(CardId.TripleBurstDragon) || Bot.HasInExtra(CardId.Borrelsword)) ) return false; + } + if (Multifaker_ssfromdeck) return false; + foreach(ClientCard card in Bot.GetMonsters()) + { + if (card.IsFaceup()) + { + summoned = true; + AI.SelectPlace(Zones.z5); + return true; + } + } + return false; + } + + public override ClientCard OnSelectAttacker(IList attackers, IList defenders) + { + List Meluseek_list = new List(); + for (int i = 0; i < attackers.Count; ++i) + { + ClientCard attacker = attackers[i]; + if (attacker.IsCode(CardId.Meluseek) && !attacker.IsDisabled()) + { + if (Enemy.GetMonsterCount() > 0) return attacker; + // Meluseek attack first even in direct attack + else Meluseek_list.Add(attacker); + } + if (attacker.IsCode(CardId.Borrelsword) && !attacker.IsDisabled()) return attacker; + } + if (Meluseek_list.Count > 0) + { + foreach(ClientCard card in Meluseek_list) + { + attackers.Remove(card); + attackers.Add(card); + } + } + return null; + } + + public override bool OnSelectHand() + { + // go first + return true; + } + + public override void OnNewTurn() + { + Multifaker_ssfromhand = false; + Multifaker_ssfromdeck = false; + Marionetter_reborn = false; + Hexstia_searched = false; + Meluseek_searched = false; + summoned = false; + Silquitous_bounced = false; + Silquitous_recycled = false; + ss_other_monster = false; + Impermanence_list.Clear(); + attacked_Meluseek.Clear(); + base.OnNewTurn(); + } + + public override void OnChaining(int player, ClientCard card) + { + if (card == null) return; + + if (player == 1) + { + if (card.IsCode(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == card) + { + Impermanence_list.Add(4-i); + break; + } + } + } + } + base.OnChaining(player, card); + } + + public bool MonsterRepos() + { + if (Card.Attack == 0) return (Card.IsAttack()); + + if (Card.IsCode(CardId.Meluseek) || Bot.HasInMonstersZone(CardId.Meluseek)) + { + return Card.HasPosition(CardPosition.Defence); + } + + if (isAltergeist(Card) && Bot.HasInHandOrInSpellZone(CardId.Protocol) && Card.IsFacedown()) + return true; + + bool enemyBetter = Util.IsAllEnemyBetter(true); + if (Card.IsAttack() && enemyBetter) + return true; + if (Card.IsDefense() && !enemyBetter) + return true; + return false; + } + + public bool MonsterSet() + { + if (Util.GetOneEnemyBetterThanMyBest() == null && Bot.GetMonsterCount() > 0) return false; + if (Card.Level > 4) return false; + int rest_lp = Bot.LifePoints; + int count = Bot.GetMonsterCount(); + List list = Enemy.GetMonsters(); + list.Sort(CardContainer.CompareCardAttack); + foreach(ClientCard card in list) + { + if (!card.HasPosition(CardPosition.Attack)) continue; + if (count-- > 0) continue; + rest_lp -= card.Attack; + } + if (rest_lp < 1700) + { + AI.SelectPosition(CardPosition.FaceDownDefence); + return true; + } + return false; + } + + public bool MonsterSummon() + { + if (Enemy.GetMonsterCount() + Bot.GetMonsterCount() > 0) return false; + return Card.Attack >= Enemy.LifePoints; + } + + public override BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList defenders) + { + if (EvenlyMatched_ready()) + { + List enemy_m = Enemy.GetMonsters(); + enemy_m.Sort(CardContainer.CompareCardAttack); + //enemy_m.Reverse(); + foreach (ClientCard e_card in enemy_m) + { + if (e_card.HasPosition(CardPosition.Attack)) + { + return AI.Attack(attacker, e_card); + } + } + } + for (int i = 0; i < defenders.Count; ++i) + { + ClientCard defender = defenders[i]; + attacker.RealPower = attacker.Attack; + defender.RealPower = defender.GetDefensePower(); + if (attacker.IsCode(CardId.Borrelsword) && !attacker.IsDisabled()) + return AI.Attack(attacker, defender); + if (!OnPreBattleBetween(attacker, defender)) + continue; + if (attacker.RealPower == defender.RealPower && Bot.GetMonsterCount() < Enemy.GetMonsterCount()) + continue; + if (attacker.RealPower > defender.RealPower || (attacker.RealPower >= defender.RealPower && attacker.IsLastAttacker && defender.IsAttack())) + return AI.Attack(attacker, defender); + } + + if (attacker.CanDirectAttack && (Enemy.GetMonsterCount() == 0 || !attacker.IsDisabled())) + return AI.Attack(attacker, null); + + return null; + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (max == 1 && cards[0].Location == CardLocation.Deck + && Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(23002292) && Bot.GetRemainingCount(CardId.WakingtheDragon,1) > 0) + { + IList result = new List(); + foreach (ClientCard card in cards) + { + if (card.IsCode(CardId.WakingtheDragon)) + { + result.Add(card); + AI.SelectPlace(SelectSetPlace()); + break; + } + } + if (result.Count > 0) return result; + } + else if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.EvenlyMatched) && Duel.LastChainPlayer != 0) + { + Logger.DebugWriteLine("EvenlyMatched: min=" + min.ToString() + ", max=" + max.ToString()); + } + else if (cards[0].Location == CardLocation.Hand && cards[cards.Count - 1].Location == CardLocation.Hand + && (hint == HintMsg.Discard || hint == HintMsg.ToGrave) && min == max) + { + if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.OneForOne)) return null; + Logger.DebugWriteLine("Hand drop except OneForOne"); + int todrop = min; + IList result = new List(); + IList ToRemove = new List(cards); + // throw redundance + List record = new List(); + foreach(ClientCard card in ToRemove) + { + if (card?.Id != 0 && !record.Contains(card.Id)) record.Add(card.Id); + else + { + result.Add(card); + if (--todrop <= 0) break; + } + } + if (todrop <= 0) return result; + foreach (ClientCard card in result) ToRemove.Remove(card); + // throw improper + foreach (int throw_id in cards_improper) + { + foreach(ClientCard card in ToRemove) + { + if (card.IsCode(throw_id)) + { + result.Add(card); + if (--todrop <= 0) return result; + } + } + } + // throw all?? + return null; + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + if (Util.IsTurn1OrMain2() + && (cardId == CardId.Meluseek || cardId == CardId.Silquitous)) + { + return CardPosition.FaceUpDefence; + } + return 0; + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0) + { + if (location == CardLocation.SpellZone) + { + // unfinished + } + else if (location == CardLocation.MonsterZone) + { + if(cardId == CardId.Linkuriboh) + { + if ((Zones.z5 & available) > 0) return Zones.z5; + if ((Zones.z6 & available) > 0) return Zones.z6; + for (int i = 4; i >= 0; --i) + { + if (Bot.MonsterZone[i] == null) + { + int place = (int)System.Math.Pow(2, i); + return place; + } + } + } + if (isAltergeist(cardId)) + { + if (Bot.HasInMonstersZone(CardId.Hexstia)) + { + for (int i = 0; i < 7; ++i) + { + if (i == 4) continue; + if (Bot.MonsterZone[i] != null && Bot.MonsterZone[i].IsCode(CardId.Hexstia)) + { + int next_index = get_Hexstia_linkzone(i); + if (next_index != -1 && (available & (int)(System.Math.Pow(2, next_index))) > 0) + { + return (int)(System.Math.Pow(2, next_index)); + } + } + } + } + if (cardId == CardId.Hexstia) + { + // ex zone + if ((Zones.z5 & available) > 0 && Bot.MonsterZone[1] != null && isAltergeist(Bot.MonsterZone[1])) return Zones.z5; + if ((Zones.z6 & available) > 0 && Bot.MonsterZone[3] != null && isAltergeist(Bot.MonsterZone[3])) return Zones.z6; + if ( ((Zones.z6 & available) > 0 && Bot.MonsterZone[3] != null && !isAltergeist(Bot.MonsterZone[3])) + || ((Zones.z5 & available) > 0 && Bot.MonsterZone[1] == null) ) return Zones.z5; + if (((Zones.z5 & available) > 0 && Bot.MonsterZone[1] != null && !isAltergeist(Bot.MonsterZone[1])) + || ((Zones.z6 & available) > 0 && Bot.MonsterZone[3] == null)) return Zones.z6; + // main zone + for (int i = 1; i < 5; ++i) + { + if (Bot.MonsterZone[i] != null && isAltergeist(Bot.MonsterZone[i])) + { + if ((available & (int)System.Math.Pow(2, i - 1)) > 0) return (int)System.Math.Pow(2, i - 1); + } + } + } + // 1 or 3 + if ((Zones.z1 & available) > 0) return Zones.z1; + if ((Zones.z3 & available) > 0) return Zones.z3; + } + } + } + return base.OnSelectPlace(cardId, player, location, available); + } + + protected override bool DefaultSetForDiabellze() + { + if (base.DefaultSetForDiabellze()) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ApophisExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ApophisExecutor.cs new file mode 100644 index 0000000..5c4ca8a --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ApophisExecutor.cs @@ -0,0 +1,3076 @@ +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; +using System; +using System.Linq; +using System.Diagnostics; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Apophis", "AI_Apophis")] + public class ApophisExecutor : DefaultExecutor + { + public class CardId + { + public const int LabradoriteDragon = 62514770; + public const int AnubisTheLastJudge = 60411677; + public const int PrimiteDragonEtherBeryl = 63198739; + public const int TheManWithTheMark = 97522863; + // PotOfExtravagance = 49238328; + public const int Terraforming = 73628505; + public const int PrimiteDrillbeam = 29095457; + public const int PrimiteLordlyLode = 56506740; + public const int TreasuresOfTheKings = 69299029; + public const int DominusSpark = 6325660; + // InfiniteImpermanence = 10045474; + public const int DominusImpulse = 40366667; + public const int SongsOfTheDominators = 58053438; + public const int DominusPurge = 97045737; + public const int ApophisTheSwampDeity = 85888377; + public const int ApophisTheSerpent = 95561146; + public const int VerdictOfAnubis = 59576447; + public const int SolemnReport = 78114463; + public const int DivineSerpentApophis = 97800311; + public const int SwordsoulSupremeSovereignChengying = 96633955; + public const int BaronneDeFleur = 84815190; + public const int SuperdreadnoughtRailCannonJuggernautLiebe = 26096328; + public const int SuperdreadnoughtRailCannonFlyingLauncher = 38354018; + public const int EvilswarmExcitonKnight = 46772449; + public const int SPLittleKnight = 46772449; + public const int SilhouhatteRabbit = 1528054; + public const int LinkSpider = 98978921; + } + + public ApophisExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // counter + AddExecutor(ExecutorType.Activate, CardId.SolemnReport, SolemnReportBanishActivate); + AddExecutor(ExecutorType.Activate, CardId.ApophisTheSwampDeity, ApophisTheSwampDeityActivate); + AddExecutor(ExecutorType.Activate, CardId.SongsOfTheDominators, SongsOfTheDominatorsActivateFirst); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, CardId.SongsOfTheDominators, DominusNegateTrapActivate); + AddExecutor(ExecutorType.Activate, CardId.DominusPurge, DominusNegateTrapActivate); + AddExecutor(ExecutorType.Activate, CardId.DominusImpulse, DominusNegateTrapActivate); + AddExecutor(ExecutorType.Activate, CardId.BaronneDeFleur, BaronneDeFleurNegateEffect); + AddExecutor(ExecutorType.Activate, CardId.PrimiteDrillbeam, PrimiteDrillbeamActivate); + AddExecutor(ExecutorType.Activate, CardId.VerdictOfAnubis, SpellNegateActivate); + AddExecutor(ExecutorType.Activate, CardId.SolemnReport, SpellNegateActivate); + AddExecutor(ExecutorType.Activate, CardId.SPLittleKnight, SPLittleKnightActivate); + AddExecutor(ExecutorType.Activate, CardId.DominusSpark, DominusSparkActivate); + + // first in main phase + AddExecutor(ExecutorType.Activate, _CardId.PotOfExtravagance, PotOfExtravaganceActivate); + AddExecutor(ExecutorType.Repos, MonstetReposForImportantMonsters); + + // startup effect + AddExecutor(ExecutorType.Activate, CardId.BaronneDeFleur, BaronneDeFleurActivate); + AddExecutor(ExecutorType.Activate, CardId.SuperdreadnoughtRailCannonJuggernautLiebe, SuperdreadnoughtRailCannonJuggernautLiebeActivate); + AddExecutor(ExecutorType.Activate, CardId.SuperdreadnoughtRailCannonFlyingLauncher, SuperdreadnoughtRailCannonFlyingLauncherActivate); + AddExecutor(ExecutorType.Activate, CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect); + AddExecutor(ExecutorType.SpellSet, SpellSetFirst); + AddExecutor(ExecutorType.Activate, CardId.SilhouhatteRabbit, SilhouhatteRabbitActivate); + AddExecutor(ExecutorType.Activate, CardId.DivineSerpentApophis, DivineSerpentApophisActivate); + AddExecutor(ExecutorType.Activate, CardId.SwordsoulSupremeSovereignChengying, SwordsoulSupremeSovereignChengyingActivate); + AddExecutor(ExecutorType.Activate, CardId.TheManWithTheMark, TheManWithTheMarkActivate); + + // spsummon + AddExecutor(ExecutorType.SpSummon, CardId.EvilswarmExcitonKnight, EvilswarmExcitonKnightSummon); + AddExecutor(ExecutorType.SpSummon, CardId.AnubisTheLastJudge, AnubisTheLastJudgeSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SuperdreadnoughtRailCannonJuggernautLiebe, SuperdreadnoughtRailCannonJuggernautLiebeSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SuperdreadnoughtRailCannonFlyingLauncher, SuperdreadnoughtRailCannonFlyingLauncherSpSummon); + AddExecutor(ExecutorType.SpSummon, Level10SynchroSummon); + AddExecutor(ExecutorType.SpSummon, CardId.DivineSerpentApophis, DivineSerpentApophisSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider, LinkSpiderSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SPLittleKnight, SPLittleKnightSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SilhouhatteRabbit, SilhouhatteRabbitSummon); + AddExecutor(ExecutorType.Activate, CardId.ApophisTheSerpent, ApophisTheSerpentActivate); + + // search + AddExecutor(ExecutorType.Activate, CardId.Terraforming, TerraformingActivate); + AddExecutor(ExecutorType.Activate, CardId.TreasuresOfTheKings, TreasuresOfTheKingsActivate); + AddExecutor(ExecutorType.Activate, CardId.PrimiteLordlyLode, PrimiteLordlyLodeActivate); + AddExecutor(ExecutorType.Summon, Level4MonsterSummon); + AddExecutor(ExecutorType.Activate, CardId.AnubisTheLastJudge, AnubisTheLastJudgeActivate); + AddExecutor(ExecutorType.Activate, CardId.PrimiteDragonEtherBeryl, PrimiteDragonEtherBerylActivate); + AddExecutor(ExecutorType.Activate, CardId.PrimiteLordlyLode, PrimiteLordlyLodeSpSummon); + AddExecutor(ExecutorType.Activate, CardId.ApophisTheSwampDeity, ApophisTheSwampDeityActivateForAttack); + + // next turn prepare + AddExecutor(ExecutorType.Repos, MonsterRepos); + AddExecutor(ExecutorType.SpellSet, SpellSet); + } + + List NotToNegateIdList = new List + { + 58699500, 20343502, 25451383, 19403423 + }; + List solemnReportBanishIdList = new List { + _CardId.MysticalSpaceTyphoon, 63166095, 9726840, 5380979, 92714517, 6153210, 32548318, 30271097, 45171524, 81560239 + }; + + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.TheManWithTheMark, CardId.PrimiteLordlyLode, CardId.TreasuresOfTheKings, CardId.DominusSpark, + _CardId.InfiniteImpermanence, CardId.SongsOfTheDominators, CardId.DominusPurge, CardId.ApophisTheSerpent}}, + {2, new List { CardId.AnubisTheLastJudge, CardId.PrimiteDragonEtherBeryl, _CardId.PotOfExtravagance, CardId.DominusImpulse, + CardId.ApophisTheSwampDeity, CardId.SolemnReport}}, + {1, new List { CardId.LabradoriteDragon, CardId.Terraforming, CardId.PrimiteDrillbeam, CardId.VerdictOfAnubis }} + }; + const int hintTimingMainEnd = 0x4; + const int hintToHand = 0x200000; + + int maxSummonCount = 1; + int summonCount = 1; + bool enemyActivateMonsterEffectFromHandGrave = false; + int dimensionShifterCount = 0; + int songsOfTheDominatorsResolvedCount = 0; + bool activatingLodeSpSummonEffect = false; + bool lodeSpSummonEffectResolved = false; + bool songsOfTheDominatorsActivatedFromHand = false; + List currentNegateCardList = new List(); + List activatedCardIdList = new List(); + List enemyPlaceThisTurn = new List(); + List summonThisTurn = new List(); + List placedThisTurn = new List(); + List activatedDivineSerpent1stList = new List(); + List activatedDivineSerpent2ndList = new List(); + + int anubisTheLastJudgeSpSummoningStep = 0; + int SPLittleKnightRemoveStep = 0; + int currentSummoningCount = 0; + + /// + /// Shuffle List and return a random-order card list + /// + public List ShuffleList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(result.Count); + int nextIndex = (index + Program.Rand.Next(result.Count - 1)) % result.Count; + T tempCard = result[index]; + result[index] = result[nextIndex]; + result[nextIndex] = tempCard; + } + return result; + } + + public bool CheckCanBeTargeted(ClientCard card, bool canBeTarget, CardType selfType) + { + if (card == null) return true; + if (canBeTarget) + { + if (card.IsShouldNotBeTarget()) return false; + if (((int)selfType & (int)CardType.Monster) > 0 && card.IsShouldNotBeMonsterTarget()) return false; + if (((int)selfType & (int)CardType.Spell) > 0 && card.IsShouldNotBeSpellTrapTarget()) return false; + if (((int)selfType & (int)CardType.Trap) > 0 && card.IsShouldNotBeSpellTrapTarget() + && !card.IsDisabled()) return false; + } + return true; + } + + /// + /// Check remain cards in deck + /// + /// Card's ID + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + + public int CheckRemainInDeck(params int[] ids) + { + int sum = 0; + foreach (int id in ids) + { + sum += CheckRemainInDeck(id); + } + return sum; + } + + /// + /// Check whether'll be negated + /// + /// check whether card itself is disabled. + public bool CheckWhetherNegated(bool disablecheck = true, bool toFieldCheck = false, CardType type = 0, bool ignore41 = false) + { + bool isMonster = type == 0 && Card.IsMonster(); + isMonster |= (type & CardType.Monster) != 0; + bool isSpellOrTrap = type == 0 && (Card.IsSpell() || Card.IsTrap()); + isSpellOrTrap |= (type & (CardType.Spell | CardType.Trap)) != 0; + bool isCounter = (type & CardType.Counter) != 0; + if (isSpellOrTrap && toFieldCheck) + { + if (CheckSpellWillBeNegate(isCounter)) return true; + if (DefaultCheckWhetherSpellActivateWillBeNegated(Card)) return true; + } + if (DefaultCheckWhetherCardIsNegated(Card)) return true; + if (isMonster && (toFieldCheck || Card.Location == CardLocation.MonsterZone)) + { + if ((toFieldCheck && ((type & CardType.Link) != 0)) || Card.IsDefense()) + { + if (Enemy.MonsterZone.Any(card => CheckNumber41(card, ignore41)) || Bot.MonsterZone.Any(card => CheckNumber41(card, ignore41))) return true; + } + if (Enemy.HasInSpellZone(_CardId.SkillDrain, true, true)) return true; + } + if (disablecheck) return (Card.Location == CardLocation.MonsterZone || Card.Location == CardLocation.SpellZone) && Card.IsDisabled() && Card.IsFaceup(); + return false; + } + + public bool CheckNumber41(ClientCard card, bool ignoreSelf41 = false) + { + return card != null && card.IsFaceup() && card.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled() + && (!ignoreSelf41 || card.Controller == 0); + } + + /// + /// Whether spell or trap will be negate. If so, return true. + /// + /// is counter trap + /// check target + /// + public bool CheckSpellWillBeNegate(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.NaturiaBeast, 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() && (Enemy.HasInSpellZone(_CardId.RoyalDecreel, true) || Bot.HasInSpellZone(_CardId.RoyalDecreel, true))) return true; + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceNegatedColumns.Contains(selfSeq)) return true; + } + // how to get here? + return false; + } + + /// + /// Check whether last chain card should be disabled. + /// + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + return CheckCardShouldNegate(lastcard); + } + + public bool CheckCardShouldNegate(ClientCard card) + { + if (card == null) return false; + if (card.IsMonster() && card.HasSetcode(_Setcode.TimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (NotToNegateIdList.Contains(card.Id)) return false; + if (card.HasSetcode(_Setcode.Danger) && card.Location == CardLocation.Hand) return false; + if (card.IsMonster() && card.Location == CardLocation.MonsterZone && card.HasPosition(CardPosition.Defence)) + { + if (Enemy.MonsterZone.Any(c => CheckNumber41(c)) || Bot.MonsterZone.Any(c => CheckNumber41(c))) return false; + } + if (DefaultCheckWhetherCardIsNegated(card)) return false; + if (card.Location == CardLocation.SpellZone) + { + int sequence = card.Sequence; + if (card.Controller == 1) sequence = 4 - sequence; + if (infiniteImpermanenceNegatedColumns.Contains(sequence)) return false; + } + if (card.IsCode(_CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, _CardId.MulcharmyNyalus, _CardId.MaxxC)) return false; + if (card.IsDisabled()) return false; + + return true; + } + + public bool CheckCardShouldNegate(ChainInfo chainInfo) + { + if (chainInfo == null) return false; + ClientCard card = chainInfo.RelatedCard; + + if (card == null) return false; + if (card.IsMonster() && card.HasSetcode(_Setcode.TimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (NotToNegateIdList.Contains(card.Id)) return false; + if (card.HasSetcode(_Setcode.Danger) && card.Location == CardLocation.Hand) return false; + if (card.IsMonster() && chainInfo.HasLocation(CardLocation.MonsterZone) && chainInfo.HasPosition(CardPosition.Defence)) + { + if (Enemy.MonsterZone.Any(c => CheckNumber41(c)) || Bot.MonsterZone.Any(c => CheckNumber41(c))) return false; + } + if (DefaultCheckWhetherCardIsNegated(card)) return false; + if (Duel.Player == 1 && card.IsCode(_CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, _CardId.MulcharmyNyalus)) return false; + if (card.IsDisabled()) return false; + + return true; + } + + /// + /// Check whether bot is at advantage. + /// + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && (Duel.Player == 0 || Bot.GetMonsterCount() > 0)) return true; + return false; + } + + public bool CheckShouldNoMoreSpSummon() + { + if (CheckAtAdvantage() && enemyResolvedEffectIdList.Contains(_CardId.MaxxC) && DefaultCheckWhetherEnemyCanDraw() && (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2)) + { + return true; + } + return false; + } + + public bool CheckShouldNoMoreSpSummon(CardLocation loc) + { + if (CheckShouldNoMoreSpSummon()) return true; + if (!DefaultCheckWhetherEnemyCanDraw() || (Duel.Turn > 1 && Duel.Phase < DuelPhase.Main2)) return false; + if (enemyResolvedEffectIdList.Contains(_CardId.MulcharmyPurulia) && (loc & CardLocation.Hand) != 0) return true; + if (enemyResolvedEffectIdList.Contains(_CardId.MulcharmyFuwalos) && (loc & (CardLocation.Deck | CardLocation.Extra)) != 0) return true; + if (enemyResolvedEffectIdList.Contains(_CardId.MulcharmyNyalus) && (loc & (CardLocation.Grave | CardLocation.Removed)) != 0) return true; + + return false; + } + + public bool CheckWhetherCanSummon() + { + return Duel.Player == 0 && Duel.Phase < DuelPhase.End && summonCount > 0; + } + + /// + /// Check whether cards will be removed. If so, do not send cards to grave. + /// + public bool CheckWhetherWillbeRemoved() + { + if (dimensionShifterCount > 0) return true; + List checkIdList = new List { _CardId.BanisheroftheRadiance, _CardId.BanisheroftheLight, _CardId.MacroCosmos, _CardId.DimensionalFissure, + _CardId.KashtiraAriseHeart, _CardId.MaskedHERODarkLaw }; + foreach (int cardid in checkIdList) + { + List fields = new List { Bot, Enemy }; + foreach (ClientField cf in fields) + { + if (cf.HasInMonstersZone(cardid, true, false, true) || cf.HasInSpellZone(cardid, true, true)) + { + return true; + } + } + } + return false; + } + + public bool CheckWhetherCanActivateMonsterEffect(CardAttribute attribute) + { + if (Bot.HintDescriptions.Contains(Util.GetStringId(CardId.DominusSpark, 3)) + && (attribute & (CardAttribute.Earth | CardAttribute.Water | CardAttribute.Fire | CardAttribute.Wind)) != 0) + { + return false; + } + if (Bot.HintDescriptions.Contains(Util.GetStringId(CardId.DominusImpulse, 2)) + && (attribute & (CardAttribute.Light | CardAttribute.Earth | CardAttribute.Wind)) != 0) + { + return false; + } + if (Bot.HintDescriptions.Contains(Util.GetStringId(CardId.DominusPurge, 2)) + && (attribute & (CardAttribute.Dark | CardAttribute.Water | CardAttribute.Fire)) != 0) + { + return false; + } + return true; + } + + public int CompareUsableAttack(ClientCard cardA, ClientCard cardB) + { + if (cardA == null && cardB == null) + return 0; + if (cardA == null) + return -1; + if (cardB == null) + return 1; + int powerA = (cardA.IsDefense() && summonThisTurn.Contains(cardA)) ? 0 : cardA.Attack; + int powerB = (cardB.IsDefense() && summonThisTurn.Contains(cardB)) ? 0 : cardB.Attack; + if (powerA < powerB) + return -1; + if (powerA == powerB) + return CardContainer.CompareCardLevel(cardA, cardB); + return 1; + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false, bool ignoreCurrentDestroy = true, CardType selfType = 0) + { + ClientCard floodagateCard = Enemy.GetMonsters().Where(c => c?.Data != null && (!ignoreCurrentDestroy || !currentNegateCardList.Contains(c)) + && c.IsFloodgate() && c.IsFaceup() + && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (floodagateCard != null) return floodagateCard; + + ClientCard dangerCard = Enemy.MonsterZone.Where(c => c?.Data != null && (!ignoreCurrentDestroy || !currentNegateCardList.Contains(c)) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (dangerCard != null) return dangerCard; + + ClientCard invincibleCard = Enemy.MonsterZone.Where(c => c?.Data != null && (!ignoreCurrentDestroy || !currentNegateCardList.Contains(c)) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (invincibleCard != null) return invincibleCard; + + ClientCard equippedCard = Enemy.MonsterZone.Where(c => c?.Data != null && (!ignoreCurrentDestroy || !currentNegateCardList.Contains(c)) + && c.EquipCards.Count > 0 && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (equippedCard != null) return equippedCard; + + ClientCard enemyExtraMonster = Enemy.MonsterZone.Where(c => c != null && (!ignoreCurrentDestroy || !currentNegateCardList.Contains(c)) + && (c.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) || (c.HasType(CardType.Link) && c.LinkCount >= 2)) + && CheckCanBeTargeted(c, canBeTarget, selfType) && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (enemyExtraMonster != null) return enemyExtraMonster; + + ClientCard activatingAlbaz = Enemy.MonsterZone.FirstOrDefault(c => c != null && c.IsCode(68468459) && !c.IsDisabled() + && !currentNegateCardList.Contains(c) && Duel.CurrentChain.Contains(c)); + if (activatingAlbaz != null) return activatingAlbaz; + + if (attack >= 0) + { + if (attack == 0) + attack = GetBotBestPower(); + ClientCard betterCard = Enemy.MonsterZone.Where(card => card != null + && card.GetDefensePower() >= attack && card.GetDefensePower() > 0 && card.IsAttack() && CheckCanBeTargeted(card, canBeTarget, selfType) + && (!ignoreCurrentDestroy || !currentNegateCardList.Contains(card))).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (betterCard != null) return betterCard; + } + return null; + } + + public bool CheckShouldNotIgnore(ClientCard cards, bool ignore = false) + { + return !ignore || (!currentNegateCardList.Contains(cards) && !currentNegateCardList.Contains(cards)); + } + + public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreSpells = false, CardType selfType = 0) + { + List resultList = new List(); + + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null && !currentNegateCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (floodagateList.Count > 0) resultList.AddRange(floodagateList); + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentNegateCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).ToList(); + if (problemEnemySpellList.Count > 0) resultList.AddRange(ShuffleList(problemEnemySpellList)); + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentNegateCardList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (dangerList.Count > 0 + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) resultList.AddRange(dangerList); + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentNegateCardList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (invincibleList.Count > 0) resultList.AddRange(invincibleList); + + List enemyMonsters = Enemy.GetMonsters().Where(c => !currentNegateCardList.Contains(c)).OrderByDescending(card => card.Attack).ToList(); + if (enemyMonsters.Count > 0) + { + foreach (ClientCard target in enemyMonsters) + { + if ((target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2)) + && !resultList.Contains(target) && CheckCanBeTargeted(target, canBeTarget, selfType) + ) + { + resultList.Add(target); + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() && !currentNegateCardList.Contains(c) + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous) && CheckCanBeTargeted(c, canBeTarget, selfType)).ToList(); + if (spells.Count > 0 && !ignoreSpells) resultList.AddRange(ShuffleList(spells)); + + return resultList; + } + + public List GetNormalEnemyTargetList(bool canBeTarget = true, bool ignoreCurrentDestroy = true, CardType selfType = 0, bool forNegate = false) + { + List targetList = GetProblematicEnemyCardList(canBeTarget, selfType: selfType); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && (!ignoreCurrentDestroy || !currentNegateCardList.Contains(card)) + && (!forNegate || (!card.IsDisabled() && card.HasType(CardType.Effect))) + ).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => + (!ignoreCurrentDestroy || !currentNegateCardList.Contains(card)) && enemyPlaceThisTurn.Contains(card) && card.IsFacedown()).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => + (!ignoreCurrentDestroy || !currentNegateCardList.Contains(card)) && !enemyPlaceThisTurn.Contains(card) && card.IsFacedown()).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetMonsters().Where(card => card.IsFacedown() + && (!ignoreCurrentDestroy || !currentNegateCardList.Contains(card)) + && (!forNegate || (!card.IsDisabled() && card.HasType(CardType.Effect) && card.IsFaceup())) + ).ToList())); + + return targetList; + } + + public List GetNormalEnemySpellTargetList(bool canBeTarget = true, bool ignoreCurrentDestroy = true, CardType selfType = 0, bool forNegate = false) + { + List targetList = GetNormalEnemyTargetList(canBeTarget, ignoreCurrentDestroy, selfType, forNegate); + return targetList.Where(card => card.HasType(CardType.Spell | CardType.Trap) || card.Location == CardLocation.SpellZone).ToList(); + } + + public List GetMonsterListForTargetNegate(bool canBeTarget = false, CardType selfType = 0) + { + List resultList = new List(); + if (CheckWhetherNegated()) + { + return resultList; + } + + // negate before used + ClientCard target = Enemy.MonsterZone.FirstOrDefault(card => card?.Data != null + && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && !card.IsShouldNotBeTarget() + && CheckCanBeTargeted(card, canBeTarget, selfType) + && !currentNegateCardList.Contains(card)); + if (target != null) + { + resultList.Add(target); + } + + // negate monster effect on the field + foreach (ClientCard chainingCard in Duel.CurrentChain) + { + if (chainingCard.Location == CardLocation.MonsterZone && chainingCard.Controller == 1 && !chainingCard.IsDisabled() + && CheckCanBeTargeted(chainingCard, canBeTarget, selfType) && !currentNegateCardList.Contains(chainingCard)) + { + if (chainingCard.HasPosition(CardPosition.Defence)) + { + bool have41 = Bot.MonsterZone.Any(c => CheckNumber41(c)) | Enemy.MonsterZone.Any(c => CheckNumber41(c)); + } + resultList.Add(chainingCard); + } + } + + return resultList; + } + + public int GetSpecialSummonDrawCount(CardLocation loc) + { + int res = 0; + if (!DefaultCheckWhetherEnemyCanDraw()) + { + return 0; + } + if (enemyResolvedEffectIdList.Contains(_CardId.MaxxC)) + { + res++; + } + + if ((loc & CardLocation.Hand) != 0) + { + res += enemyResolvedEffectIdList.Count(id => id == _CardId.MulcharmyPurulia); + } + if ((loc & (CardLocation.Deck | CardLocation.Extra)) != 0) + { + res += enemyResolvedEffectIdList.Count(id => id == _CardId.MulcharmyFuwalos); + } + if ((loc & (CardLocation.Grave | CardLocation.Removed)) != 0) + { + res += enemyResolvedEffectIdList.Count(id => id == _CardId.MulcharmyNyalus); + } + + return res; + } + + public int GetBotBestPower(bool onlyATK = false) + { + return Bot.MonsterZone.GetMonsters() + .Where(card => !onlyATK || (!summonThisTurn.Contains(card) && Duel.Player == 0) || card.IsAttack()) + .Max(card => (int?)card.GetDefensePower()) ?? -1; + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + ChainInfo currentChain = Duel.GetCurrentSolvingChainInfo(); + if (currentChain == null) { + if (anubisTheLastJudgeSpSummoningStep > 0) { + List cardIdList = new List { + CardId.VerdictOfAnubis, CardId.ApophisTheSwampDeity, CardId.SongsOfTheDominators, CardId.DominusSpark, CardId.DominusImpulse, + CardId.ApophisTheSerpent, CardId.DominusPurge, _CardId.InfiniteImpermanence, CardId.SolemnReport }; + foreach (int cardId in cardIdList) { + ClientCard card = cards.FirstOrDefault(c => c.IsCode(cardId)); + if (card != null) { + if (anubisTheLastJudgeSpSummoningStep == 1) + { + anubisTheLastJudgeSpSummoningStep = 2; + } else + { + anubisTheLastJudgeSpSummoningStep = 0; + } + return Util.CheckSelectCount(new List { card }, cards, min, max); + } + } + } + + // for activating target + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && lastChainCard.Controller == 0) + { + switch (lastChainCard.Id) + { + case CardId.AnubisTheLastJudge: + { + List targetList = GetNormalEnemyTargetList(canBeTarget: true, ignoreCurrentDestroy: true, selfType: CardType.Monster, forNegate: false); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + // destroy set this turn + foreach (ClientCard target in cards) + { + if (enemyPlaceThisTurn.Contains(target)) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + } + case CardId.PrimiteDrillbeam: + { + // negate cards on chain + foreach (ClientCard card in Duel.CurrentChain) { + if (card.Controller == 1 && card.IsOnField() && card.IsFaceup() && !card.IsDisabled() && !currentNegateCardList.Contains(card) + && CheckCanBeTargeted(card, true, CardType.Spell) && CheckCardShouldNegate(card) && cards.Contains(card)) { + currentNegateCardList.Add(card); + return Util.CheckSelectCount(new List { card }, cards, min, max); + } + } + // remove problematic enemy cards + List targetList = GetNormalEnemyTargetList(canBeTarget: true, ignoreCurrentDestroy: true, selfType: CardType.Monster, forNegate: false); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + // select enemy cards + List enemyCards = ShuffleList(cards.Where(c => c.Controller == 1).ToList()); + foreach (ClientCard target in enemyCards) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + } + case CardId.DominusSpark: + { + List targetList = GetNormalEnemyTargetList(ignoreCurrentDestroy: false); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + } + case _CardId.InfiniteImpermanence: + { + int sequence = lastChainCard.Sequence; + List targetList = GetMonsterListForTargetNegate(true, CardType.Trap); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + if (sequence >= 0) + { + ClientCard spell = Enemy.SpellZone[sequence]; + if (spell != null && spell.IsFaceup()) + { + currentNegateCardList.Add(spell); + } + } + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + targetList = GetProblematicEnemyCardList(canBeTarget: true, ignoreSpells: false, selfType: CardType.Trap); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + if (sequence >= 0) + { + ClientCard spell = Enemy.SpellZone[sequence]; + if (spell != null && spell.IsFaceup()) + { + currentNegateCardList.Add(spell); + } + } + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + } + case CardId.DivineSerpentApophis: + { + if (hint == HintMsg.Destroy) + { + List targetList = GetNormalEnemyTargetList(); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + if (hint == HintMsg.Set) + { + int targetId = CardId.ApophisTheSwampDeity; + // if no other continuous trap can be found, then use ApophisTheSerpent + bool hasOtherContinuousTrap = false; + if (Bot.GetSpellCountWithoutField() <= 3 && Bot.HasInGraveyard(CardId.ApophisTheSerpent)) + { + hasOtherContinuousTrap = true; + } + if (Bot.GetSpells().Any(c => c.HasType(CardType.Continuous)) || Bot.GetMonsters().Any(c => c.HasType(CardType.Continuous))) + { + hasOtherContinuousTrap = true; + } + if (!hasOtherContinuousTrap) + { + targetId = CardId.ApophisTheSerpent; + } + ClientCard target = cards.FirstOrDefault(c => c.IsCode(targetId)); + if (target != null) + { + currentNegateCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + // select remaining cards + return Util.CheckSelectCount(cards, cards, min, max); + } + break; + } + case CardId.BaronneDeFleur: + { + if (hint == HintMsg.Destroy) + { + List targetList = GetNormalEnemyTargetList(); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + } + case CardId.SuperdreadnoughtRailCannonFlyingLauncher: + { + List targetList = GetNormalEnemySpellTargetList(true, false, CardType.Monster); + if (hint == HintMsg.RemoveXyz) + { + return Util.CheckSelectCount(cards, cards, min, Math.Min(targetList.Count, max)); + } + if (hint == HintMsg.Destroy) + { + List destroyList = new List(); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + destroyList.Add(target); + if (destroyList.Count >= max) + { + currentNegateCardList.AddRange(destroyList); + return Util.CheckSelectCount(destroyList, cards, min, Math.Min(targetList.Count, max)); + } + } + } + } + break; + } + case CardId.SPLittleKnight: + { + if (Duel.CurrentChainInfo.Count > 0) + { + ChainInfo lastChain = Duel.CurrentChainInfo[Duel.CurrentChainInfo.Count - 1]; + if (lastChain.ActivateDescription == -1 || lastChain.ActivateDescription == Util.GetStringId(CardId.SPLittleKnight, 0)) + { + // remove enemy cards + List problemCardList = GetProblematicEnemyCardList(true, selfType: CardType.Monster); + problemCardList.AddRange(GetNormalEnemyTargetList(true, true, CardType.Monster)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => card.HasType(CardType.Monster)).OrderByDescending(card => card.Attack)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => !card.HasType(CardType.Monster))); + foreach (ClientCard target in problemCardList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } else if (lastChain.ActivateDescription == Util.GetStringId(CardId.SPLittleKnight, 1)) + { + switch (SPLittleKnightRemoveStep) + { + case 1: + // remove target + foreach (ClientCard target in Bot.GetMonsters()) + { + if (target.HasType(CardType.Continuous)) + { + continue; + } + if (Duel.ChainTargets.Contains(target) && cards.Contains(target)) + { + SPLittleKnightRemoveStep = 2; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + // remove weak monster + if (Duel.Player == 1) + { + foreach (ClientCard card in Bot.GetMonsters().Where(c => c.IsAttack() && !c.HasType(CardType.Continuous) && !c.IsCode(new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity })).OrderBy(c => c.Attack)) + { + if (Util.IsOneEnemyBetterThanValue(card.Attack, true) && cards.Contains(card)) + { + SPLittleKnightRemoveStep = 2; + return Util.CheckSelectCount(new List { card }, cards, min, max); + } + } + } + break; + case 2: + { + // select problematic enemy monster + if (Enemy.GetMonsterCount() > 0) + { + List problemList = GetProblematicEnemyCardList(true, true, CardType.Monster); + if (problemList.Count() > 0) + { + foreach (ClientCard target in problemList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + SPLittleKnightRemoveStep = 0; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + } + // remove bot's target + foreach (ClientCard target in Duel.ChainTargets) + { + if (target.IsCode(new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity })) + { + continue; + } + if (cards.Contains(target)) + { + SPLittleKnightRemoveStep = 0; + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + // remove bot's monster + if (Enemy.GetMonsterCount() == 0) + { + List otherOwn = Bot.GetMonsters().Where(c => !c.HasType(CardType.Continuous)).ToList(); + otherOwn.Sort(CompareUsableAttack); + foreach (ClientCard c in otherOwn) + { + if (cards.Contains(c)) + { + SPLittleKnightRemoveStep = 0; + return Util.CheckSelectCount(new List { c }, cards, min, max); + } + } + } + } + break; + default: + SPLittleKnightRemoveStep = 0; + break; + } + } + } + break; + } + case CardId.SilhouhatteRabbit: + { + if (hint == HintMsg.Destroy) + { + List targetList = GetNormalEnemySpellTargetList(true, false, CardType.Monster, false); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + currentNegateCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + } + default: + break; + } + } + } + + if (currentChain != null) + { + if (currentChain.ActivateController == 0) + { + // for solving chain + switch (currentChain.ActivateId) + { + case CardId.PrimiteDragonEtherBeryl: + if (hint == HintMsg.Set) + { + int targetId = CardId.PrimiteLordlyLode; + if (activatedCardIdList.Contains(CardId.PrimiteLordlyLode) || !DefaultCheckWhetherBotCanSearch() || Bot.HasInSpellZone(CardId.PrimiteLordlyLode)) + { + targetId = CardId.PrimiteDrillbeam; + } + ClientCard target = cards.FirstOrDefault(c => c.IsCode(targetId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + case CardId.TheManWithTheMark: + if (hint == HintMsg.OperateCard) + { + int targetId = CardId.TreasuresOfTheKings; + if (activatedCardIdList.Contains(CardId.TreasuresOfTheKings) || Bot.HasInHandOrInSpellZone(CardId.TreasuresOfTheKings)) + { + targetId = CardId.VerdictOfAnubis; + } + ClientCard target = cards.FirstOrDefault(c => c.IsCode(targetId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + case CardId.TreasuresOfTheKings: + { + List targetIdList = new List(); + if (hint == HintMsg.Set) + { + targetIdList.AddRange(new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity }); + } else if (hint == HintMsg.AddToHand) { + if (songsOfTheDominatorsResolvedCount > 0) + { + targetIdList.AddRange(new List { CardId.TheManWithTheMark, CardId.AnubisTheLastJudge }); + } else + { + targetIdList.AddRange(new List { CardId.AnubisTheLastJudge, CardId.TheManWithTheMark }); + } + } + foreach (int targetId in targetIdList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(targetId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + } + case CardId.PrimiteLordlyLode: + { + if (hint == HintMsg.AddToHand) + { + List targetIdList = new List { CardId.PrimiteDragonEtherBeryl, CardId.PrimiteDrillbeam }; + if (summonCount == 0 || !CheckWhetherCanActivateMonsterEffect(CardAttribute.Earth)) + { + // whether need to search drillbeam + bool canTriggerPrimiteBeam = Bot.Hand.Any(c => c.IsCode(CardId.PrimiteDragonEtherBeryl, CardId.PrimiteLordlyLode, CardId.LabradoriteDragon)); + canTriggerPrimiteBeam |= Bot.HasInMonstersZone(new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity, CardId.LabradoriteDragon }, faceUp: true); + canTriggerPrimiteBeam |= Bot.GetSpells().Any(c => c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity) && (c.IsFacedown() || Duel.CurrentChain.Contains(c))); + if (canTriggerPrimiteBeam) + { + targetIdList.Insert(0, CardId.PrimiteDrillbeam); + } + } + foreach (int targetId in targetIdList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(targetId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + break; + } + case CardId.SongsOfTheDominators: + { + List checkIdList = new List { CardId.DominusPurge, CardId.DominusImpulse, CardId.DominusSpark }; + // 1. Prefer a card NOT in activatedCardIdList and not in hand / spell&trap of bot + foreach (int checkId in checkIdList) + { + if (!activatedCardIdList.Contains(checkId) && !Bot.HasInHandOrInSpellZone(checkId) && !Duel.CurrentChain.Any(c => c != null && c.Controller == 0 && c.IsCode(checkId))) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(checkId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + // 2. Next, prefer a card not in hand/spell&trap + foreach (int checkId in checkIdList) + { + if (!Bot.HasInHandOrInSpellZone(checkId)) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(checkId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + // 3. Finally, pick by id order if any exists + foreach (int checkId in checkIdList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(checkId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + } + case CardId.ApophisTheSwampDeity: + { + List negateCardList = new List(); + // select cards to negate + for (int i = Duel.CurrentChain.Count - 1; i >= 0; i--) + { + ClientCard card = Duel.CurrentChain[i]; + if (card != null && card.IsFaceup() && cards.Contains(card)) + { + negateCardList.Add(card); + } + } + // negate other face-up cards + foreach (ClientCard card in cards) + { + if (card != null && card.IsFaceup() && !negateCardList.Contains(card)) + { + negateCardList.Add(card); + } + } + return Util.CheckSelectCount(negateCardList, cards, min, max); + } + case CardId.SwordsoulSupremeSovereignChengying: + { + List fieldTargetList = GetNormalEnemyTargetList(false); + foreach (ClientCard target in fieldTargetList) + { + if (cards.Contains(target)) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + // banish fron grave + List graveTargetList = Duel.CurrentChain.Where(c => c != null && c.Controller == 1 && c.Location == CardLocation.Grave).ToList(); + graveTargetList.AddRange(Duel.ChainTargets.Where(c => c != null && c.Controller == 1 && c.Location == CardLocation.Grave).ToList()); + graveTargetList.AddRange(Enemy.Graveyard.Where(c => c.IsMonster()).OrderByDescending(c => c.Attack).ToList()); + return Util.CheckSelectCount(graveTargetList, cards, min, max); + } + case CardId.SilhouhatteRabbit: + { + List targetIdList = new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity }; + foreach (int targetId in targetIdList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(targetId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + break; + } + default: + break; + } + } + if (currentChain.ActivateController == 1) + { + switch (currentChain.ActivateId) + { + case _CardId.EvenlyMatched: + { + Logger.DebugWriteLine("=== Evenly Matched activated."); + List banishList = new List(); + List botMonsters = Bot.GetMonsters().Where(card => !card.HasType(CardType.Token)).ToList(); + // monster + List faceDownMonsters = botMonsters.Where(card => card.IsFacedown()).ToList(); + banishList.AddRange(faceDownMonsters); + List dumpMainMonsterList = botMonsters.Where(card => !banishList.Contains(card) + && CheckRemainInDeck(card.Id) > 0).ToList(); + dumpMainMonsterList.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(dumpMainMonsterList); + // spells + List faceUpSpells = Bot.GetSpells().Where(c => c.IsFaceup()).ToList(); + banishList.AddRange(ShuffleList(faceUpSpells)); + // other monster + List otherMonsters = botMonsters.Where(card => !banishList.Contains(card)).ToList(); + otherMonsters.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(otherMonsters); + List faceDownSpells = Bot.GetSpells().Where(c => c.IsFacedown()).ToList(); + banishList.AddRange(ShuffleList(faceDownSpells)); + return Util.CheckSelectCount(banishList, cards, min, max); + } + default: + break; + } + } + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + public override bool OnSelectHand() + { + return true; + } + + public override int OnSelectOption(IList options) + { + if (options.Contains(Util.GetStringId(_CardId.PotOfExtravagance, 1))) + { + return options.IndexOf(Util.GetStringId(_CardId.PotOfExtravagance, 1)); + } + if (options.Contains(Util.GetStringId(CardId.SolemnReport, 1)) && options.Contains(Util.GetStringId(CardId.SolemnReport, 2))) + { + int destroyOpt = options.IndexOf(Util.GetStringId(CardId.SolemnReport, 1)); + int banishOpt = options.IndexOf(Util.GetStringId(CardId.SolemnReport, 2)); + bool avoidDestroyFlag = false; + if (Duel.CurrentChain.Count >= 2) + { + ClientCard secondLastChainCard = Duel.CurrentChain[Duel.CurrentChain.Count - 2]; + if (secondLastChainCard != null) + { + // avoid destroy if bot have the same cards that can activate + switch (secondLastChainCard.Id) + { + case CardId.DominusSpark: + { + bool canActivateFlag = !activatedCardIdList.Contains(CardId.DominusSpark) && !Duel.CurrentChain.Any(c => c != null && c.Controller == 0 && c.IsCode(CardId.DominusSpark)); + if (canActivateFlag) + { + canActivateFlag &= Bot.HasInHand(CardId.DominusSpark) && enemyActivateMonsterEffectFromHandGrave + || Bot.GetSpells().Any(c => c.IsCode(CardId.DominusSpark) && !placedThisTurn.Contains(c)); + } + avoidDestroyFlag |= canActivateFlag; + break; + } + case CardId.DominusImpulse: + case CardId.DominusPurge: + { + bool canActivateFlag = !activatedCardIdList.Contains(secondLastChainCard.Id) && !Duel.CurrentChain.Any(c => c != null && c.Controller == 0 && c.IsCode(secondLastChainCard.Id)); + if (canActivateFlag) + { + canActivateFlag &= Bot.HasInHand(secondLastChainCard.Id) || Bot.GetSpells().Any(c => c.IsCode(secondLastChainCard.Id) && !placedThisTurn.Contains(c)); + } + avoidDestroyFlag |= canActivateFlag; + break; + } + case CardId.SongsOfTheDominators: + { + bool canActivateFlag = !activatedCardIdList.Contains(secondLastChainCard.Id) && !Duel.CurrentChain.Any(c => c != null && c.Controller == 0 && c.IsCode(secondLastChainCard.Id)); + if (canActivateFlag) + { + canActivateFlag &= Bot.HasInHand(secondLastChainCard.Id) && Bot.Graveyard.Count(c => c.IsMonster()) == 0 + || Bot.GetSpells().Any(c => c.IsCode(secondLastChainCard.Id) && !placedThisTurn.Contains(c)); + } + avoidDestroyFlag |= canActivateFlag; + break; + } + case _CardId.InfiniteImpermanence: + case CardId.ApophisTheSwampDeity: + avoidDestroyFlag |= Bot.GetSpells().Any(c => c.IsCode(secondLastChainCard.Id) && !placedThisTurn.Contains(c)); + break; + case CardId.ApophisTheSerpent: + avoidDestroyFlag |= Bot.GetSpells().Any(c => c.IsCode(secondLastChainCard.Id) && !placedThisTurn.Contains(c)) && !activatedCardIdList.Contains(secondLastChainCard.Id); + break; + } + + if (avoidDestroyFlag) + { + return banishOpt; + } + if (secondLastChainCard.IsCode(solemnReportBanishIdList)) + { + return banishOpt; + } + } + } + + return destroyOpt; + } + + ChainInfo currentChain = Duel.GetCurrentSolvingChainInfo(); + if (currentChain != null) + { + if (currentChain.ActivateController == 0) + { + switch (currentChain.ActivateId) + { + case CardId.TheManWithTheMark: + if (options.Contains(1190)) + { + return options.IndexOf(1190); + } + break; + default: + break; + } + } + } + + return base.OnSelectOption(options); + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location == CardLocation.MonsterZone) + { + List zoneIdList = ShuffleList(new List { 5, 6 }); + zoneIdList.AddRange(ShuffleList(new List { 0, 2, 4 })); + zoneIdList.AddRange(ShuffleList(new List { 1, 3 })); + foreach (int zoneId in zoneIdList) + { + int zone = (int)System.Math.Pow(2, zoneId); + if ((available & zone) != 0 && Bot.MonsterZone[zoneId] == null) + { + List infiniteImpermanenceList = Bot.GetSpells().Where(c => c.IsCode(_CardId.InfiniteImpermanence)).Select(c => c.Sequence).ToList(); + infiniteImpermanenceList.AddRange(infiniteImpermanenceNegatedColumns); + // trap monster do not summon to infinite permanence negated columns + if ((cardId == CardId.ApophisTheSerpent || cardId == CardId.ApophisTheSwampDeity) + && infiniteImpermanenceList.Contains(zoneId)) + { + continue; + } + if (cardId == CardId.ApophisTheSerpent || cardId == CardId.ApophisTheSwampDeity) + { + Logger.DebugWriteLine("Apophis select zone: " + zoneId); + Logger.DebugWriteLine("infiniteImpermanenceNegatedColumns: " + string.Join(", ", infiniteImpermanenceList)); + } + return zone; + } + } + } + ChainInfo currentChain = Duel.GetCurrentSolvingChainInfo(); + if (currentChain != null && currentChain.ActivateController == 0) + { + switch (currentChain.ActivateId) + { + case CardId.TreasuresOfTheKings: + { + List zoneIdList = ShuffleList(new List { 0, 1, 2, 3, 4 }); + foreach (int zoneId in zoneIdList) + { + int zone = (int)System.Math.Pow(2, zoneId); + if ((available & zone) != 0 && Bot.MonsterZone[zoneId] == null) + { + return zone; + } + } + break; + } + case CardId.ApophisTheSerpent: + { + List zoneIdList = ShuffleList(new List { 0, 1, 2, 3, 4 }); + foreach (int zoneId in zoneIdList) + { + int zone = (int)System.Math.Pow(2, zoneId); + if ((available & zone) != 0 && Bot.MonsterZone[zoneId] == null && !infiniteImpermanenceNegatedColumns.Contains(zoneId)) + { + return zone; + } + } + break; + } + default: + break; + } + } + return base.OnSelectPlace(cardId, player, location, available); + } + + public override bool OnSelectYesNo(int desc) + { + if (desc == Util.GetStringId(CardId.PrimiteDrillbeam, 0)) + { + return false; + } + + return base.OnSelectYesNo(desc); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2) + { + bool turnDefense = false; + if (cardData.Attack <= cardData.Defense) + { + turnDefense = true; + } + if (turnDefense) + { + return CardPosition.FaceUpDefence; + } + } + if (Duel.Player == 1) + { + if (cardData.Defense >= cardData.Attack || Util.IsOneEnemyBetterThanValue(cardData.Attack, true)) + { + return CardPosition.FaceUpDefence; + } + } + int cardAttack = cardData.Attack; + if (cardId == CardId.SuperdreadnoughtRailCannonJuggernautLiebe && CheckWhetherCanActivateMonsterEffect(CardAttribute.Earth)) + { + cardAttack += 2000; + } + if (cardId == CardId.SwordsoulSupremeSovereignChengying) + { + int removeCount = Bot.Banished.Count() + Enemy.Banished.Count(); + cardAttack += removeCount * 200; + } + int bestBotAttack = Math.Max(GetBotBestPower(true), cardAttack); + + if (Util.IsAllEnemyBetterThanValue(bestBotAttack, true)) + { + return CardPosition.FaceUpDefence; + } + } + return base.OnSelectPosition(cardId, positions); + } + + public override void OnNewTurn() + { + if (Duel.Turn <= 1) + { + dimensionShifterCount = 0; + songsOfTheDominatorsResolvedCount = 0; + // for doom bot + maxSummonCount = 1; + } + + summonCount = maxSummonCount; + enemyActivateMonsterEffectFromHandGrave = false; + anubisTheLastJudgeSpSummoningStep = 0; + SPLittleKnightRemoveStep = 0; + activatingLodeSpSummonEffect = false; + lodeSpSummonEffectResolved = false; + songsOfTheDominatorsActivatedFromHand = false; + if (dimensionShifterCount > 0) dimensionShifterCount--; + if (songsOfTheDominatorsResolvedCount > 0) songsOfTheDominatorsResolvedCount--; + currentNegateCardList.Clear(); + activatedCardIdList.Clear(); + enemyPlaceThisTurn.Clear(); + summonThisTurn.Clear(); + placedThisTurn.Clear(); + activatedDivineSerpent1stList.Clear(); + activatedDivineSerpent2ndList.Clear(); + currentSummoningCount = 0; + + base.OnNewTurn(); + } + + public override void OnChaining(int player, ClientCard card) + { + if (player == 1 && card != null && card.IsMonster() && (card.Location == CardLocation.Hand || card.Location == CardLocation.Grave)) + { + enemyActivateMonsterEffectFromHandGrave = true; + } + + base.OnChaining(player, card); + } + + public override void OnChainSolved(int chainIndex) + { + ChainInfo currentChain = Duel.GetCurrentSolvingChainInfo(); + if (currentChain != null) + { + if (currentChain.ActivateController == 0) + { + switch (currentChain.ActivateId) + { + case CardId.DominusSpark: + case CardId.DominusImpulse: + case CardId.DominusPurge: + case CardId.SongsOfTheDominators: + activatedCardIdList.Add(currentChain.ActivateId); + break; + case CardId.TreasuresOfTheKings: + if (currentChain.ActivateDescription != Util.GetStringId(CardId.TreasuresOfTheKings, 0)) + { + activatedCardIdList.Add(currentChain.ActivateId); + } + break; + } + } + if (!Duel.IsCurrentSolvingChainNegated()) + { + if (currentChain.ActivateController == 0) + { + switch (currentChain.ActivateId) + { + case CardId.PrimiteLordlyLode: + { + if (activatingLodeSpSummonEffect) + { + lodeSpSummonEffectResolved = true; + } + break; + } + case CardId.SongsOfTheDominators: + { + if (songsOfTheDominatorsActivatedFromHand) + { + songsOfTheDominatorsResolvedCount = 2; + } + break; + } + default: + break; + } + } + if (currentChain.IsActivateCode(_CardId.DimensionShifter)) + dimensionShifterCount = 2; + } + } + + base.OnChainSolved(chainIndex); + } + + public override void OnChainEnd() + { + currentSummoningCount = 0; + currentNegateCardList.Clear(); + activatingLodeSpSummonEffect = false; + songsOfTheDominatorsActivatedFromHand = false; + for (int idx = enemyPlaceThisTurn.Count - 1; idx >= 0; idx--) + { + ClientCard checkTarget = enemyPlaceThisTurn[idx]; + if (checkTarget == null || !checkTarget.IsOnField()) + { + enemyPlaceThisTurn.RemoveAt(idx); + } + } + base.OnChainEnd(); + } + + public override void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + if (card != null) + { + if (currentControler == 1 && (currentLocation == (int)CardLocation.MonsterZone || currentLocation == (int)CardLocation.SpellZone)) + { + enemyPlaceThisTurn.Add(card); + } + + if (previousControler == 0 && previousLocation == (int)CardLocation.MonsterZone && currentLocation != (int)CardLocation.MonsterZone) + { + if (summonThisTurn.Contains(card)) + summonThisTurn.Remove(card); + if (activatedDivineSerpent1stList.Contains(card)) + activatedDivineSerpent1stList.Remove(card); + if (activatedDivineSerpent2ndList.Contains(card)) + activatedDivineSerpent2ndList.Remove(card); + } + if (currentControler == 0 && currentLocation == (int)CardLocation.MonsterZone) + { + summonThisTurn.Add(card); + } + if (currentControler == 0 && previousLocation == (int)CardLocation.SpellZone && currentLocation != (int)CardLocation.SpellZone && placedThisTurn.Contains(card)) + { + placedThisTurn.Remove(card); + } + if (currentControler == 0 && currentLocation == (int)CardLocation.SpellZone) + { + ChainInfo currentChain = Duel.GetCurrentSolvingChainInfo(); + if (currentChain != null && currentChain.ActivateController == 0 && currentChain.ActivateId == CardId.ApophisTheSerpent && card.IsCode(CardId.ApophisTheSwampDeity)) + { + placedThisTurn.Remove(card); + } else + { + placedThisTurn.Add(card); + } + } + } + + base.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + /// + /// Select spell/trap's place randomly to avoid InfiniteImpermanence and so on. + /// + /// Card to set(default current card) + /// Whether need to avoid InfiniteImpermanence + /// Whether need to avoid set in this place + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + if (card.Location == CardLocation.SpellZone) + { + return; + } + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceNegatedColumns.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public bool AnubisTheLastJudgeActivate() + { + if (Card.Location == CardLocation.Hand) + { + if (CheckWhetherNegated()) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + + // select target on enemy field + List targetList = GetNormalEnemyTargetList(canBeTarget: true, ignoreCurrentDestroy: false, selfType: CardType.Monster, forNegate: false); + if (targetList.Count > 0) + { + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public bool AnubisTheLastJudgeSpSummon() { + if (CheckShouldNoMoreSpSummon(CardLocation.Grave)) + { + return false; + } + + if (Duel.MainPhase.ActivableCards.Contains(Card)) + { + // whether should activate + if (!CheckWhetherNegated() || !CheckWhetherWillbeRemoved()) + { + return false; + } + } + + anubisTheLastJudgeSpSummoningStep = 1; + return true; + } + + public bool PrimiteDragonEtherBerylActivate() + { + if (Card.Location == CardLocation.Grave) + { + return !CheckWhetherNegated(); + } + // to grave + if (ActivateDescription == Util.GetStringId(CardId.PrimiteDragonEtherBeryl, 1)) + { + if (!Util.IsTurn1OrMain2()) + { + return false; + } + + // summoning Labradorite instead? + bool notCalledLode = !activatedCardIdList.Contains(CardId.PrimiteLordlyLode + 1); + if (notCalledLode) + { + // can summon? + bool enabledLodeFlag = Bot.GetSpells().Any(c => c.IsCode(CardId.PrimiteLordlyLode) && c.IsFaceup() && !c.IsDisabled()); + bool existsLode = Bot.GetSpells().Any(c => c.IsCode(CardId.PrimiteLordlyLode) && c.IsFacedown()); + existsLode = Bot.HasInHand(CardId.PrimiteLordlyLode) && Bot.GetSpellCount() < 5; + enabledLodeFlag |= existsLode && !activatedCardIdList.Contains(CardId.PrimiteLordlyLode); + + if (enabledLodeFlag) + { + return false; + } + } + + // whether can recycle next turn? + List apophisCardIdList = new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity }; + bool recycleFlag = Bot.HasInHand(apophisCardIdList) + || Bot.HasInSpellZone(apophisCardIdList) + || Bot.GetMonsters().Any(c => c.IsFaceup() && apophisCardIdList.Contains(c.Id)); + return !CheckWhetherWillbeRemoved() && (!CheckWhetherNegated() || recycleFlag); + } else + { + // search + return !CheckWhetherNegated(); + } + } + + public bool TheManWithTheMarkActivate() + { + return !CheckWhetherNegated() && DefaultCheckWhetherBotCanSearch(); + } + + public bool Level4MonsterSummon() + { + if (!Card.IsCode(CardId.PrimiteDragonEtherBeryl, CardId.TheManWithTheMark)) + { + return false; + } + + bool canSummonDragon = Bot.HasInHand(CardId.PrimiteDragonEtherBeryl); + if (!activatedCardIdList.Contains(CardId.PrimiteLordlyLode) && DefaultCheckWhetherBotCanSearch()) + { + canSummonDragon |= Bot.HasInHand(CardId.PrimiteLordlyLode) && Bot.GetSpellCountWithoutField() < 5; + canSummonDragon |= Bot.GetSpells().Any(c => c.IsCode(CardId.PrimiteLordlyLode) && c.IsFacedown()); + } + if (canSummonDragon) + { + bool summonFlag = false; + // summon to search? + if (!CheckWhetherNegated(true, true) && CheckWhetherCanActivateMonsterEffect(CardAttribute.Earth)) + { + summonFlag |= !activatedCardIdList.Contains(CardId.PrimiteLordlyLode) && !Bot.HasInHandOrInSpellZone(CardId.PrimiteLordlyLode) && CheckRemainInDeck(CardId.PrimiteLordlyLode) > 0; + summonFlag |= CheckRemainInDeck(CardId.PrimiteDrillbeam) > 0; + } + + // summon to recycle beam + if (!Bot.HasInMonstersZone(CardId.PrimiteDragonEtherBeryl, faceUp: true) && !activatedCardIdList.Contains(CardId.PrimiteDrillbeam + 1) + && Bot.HasInGraveyard(CardId.PrimiteDrillbeam) && Bot.GetSpellCountWithoutField() < 5) + { + summonFlag = true; + } + + if (summonFlag && Card.IsCode(CardId.PrimiteDragonEtherBeryl)) + { + summonCount --; + return true; + } + } + + bool canSummonMan = Bot.HasInHand(CardId.TheManWithTheMark); + canSummonMan |= Bot.HasInHand(CardId.AnubisTheLastJudge) && DefaultCheckWhetherBotCanSearch() && CheckRemainInDeck(CardId.TheManWithTheMark) > 0 && !activatedCardIdList.Contains(CardId.AnubisTheLastJudge); + if (Bot.HasInHandOrInSpellZone(CardId.TreasuresOfTheKings) && !activatedCardIdList.Contains(CardId.TreasuresOfTheKings + 1) && DefaultCheckWhetherBotCanSearch() && CheckRemainInDeck(CardId.TheManWithTheMark) > 0) + { + canSummonMan |= Bot.Graveyard.Any(c => c.IsTrap()); + int facedownCardCount = Bot.GetSpells().Count(c => c.IsFacedown()); + facedownCardCount += Bot.GetMonsters().Count(c => c.IsFacedown()); + facedownCardCount += GetCanSetSpells().Count(); + canSummonMan |= facedownCardCount >= 2; + } + if (canSummonMan && Card.IsCode(CardId.TheManWithTheMark)) + { + summonCount --; + return true; + } + + // summon for synchro level 10 monster + if (Bot.ExtraDeck.Any(c => c.HasType(CardType.Synchro) && c.Level == 10)) + { + // have labradorite dragon + bool haveTunerFlag = Bot.GetMonsters().Any(c => c.IsFaceup() && c.IsCode(CardId.LabradoriteDragon) && c.IsTuner()); + haveTunerFlag |= !activatedCardIdList.Contains(CardId.PrimiteLordlyLode + 1) && Bot.HasInSpellZone(CardId.PrimiteLordlyLode, true, true); + if (haveTunerFlag) + { + summonCount --; + return true; + } + } + + return false; + } + + public bool PotOfExtravaganceActivate() + { + if (CheckWhetherNegated()) return false; + SelectSTPlace(Card, true); + AI.SelectOption(1); + return true; + } + + public bool TerraformingActivate() + { + if (CheckWhetherNegated()) return false; + SelectSTPlace(Card, true); + return true; + } + + public bool PrimiteDrillbeamActivate() + { + if (Card.Location == CardLocation.Grave) + { + if (CheckWhetherNegated()) return false; + + // check whether can active + bool canActivate = Bot.HasInHand(CardId.PrimiteLordlyLode) || Bot.HasInHand(CardId.PrimiteDragonEtherBeryl); + canActivate |= Bot.HasInSpellZone(CardId.ApophisTheSerpent) || Bot.HasInSpellZone(CardId.ApophisTheSwampDeity); + canActivate |= Bot.GetMonsters().Any(c => c.IsFaceup() && c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity, CardId.LabradoriteDragon)); + canActivate |= Bot.HasInHand(CardId.ApophisTheSwampDeity) && Bot.GetSpellCountWithoutField() <= 3; + + if (canActivate) { + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + // cannot activate + return false; + } + + // negate + if (CheckWhetherNegated(true, true, CardType.Spell)) + { + return false; + } + + bool activateFlag = false; + + // negate problematic enemy card + List problematicEnemyCardList = GetProblematicEnemyCardList(true, false, CardType.Spell); + if (problematicEnemyCardList.Count(c => !c.IsDisabled()) > 0) { + problematicEnemyCardList.RemoveAll(c => currentNegateCardList.Contains(c)); + if (problematicEnemyCardList.Count > 0) { + activateFlag = true; + } + } + + // negate cards on chain + foreach (ClientCard card in Duel.CurrentChain) { + if (card.Controller == 1 && card.IsOnField() && card.IsFaceup() && !card.IsDisabled() && !currentNegateCardList.Contains(card) + && CheckCanBeTargeted(card, true, CardType.Spell) && CheckCardShouldNegate(card)) { + activateFlag = true; + } + } + + // can recycle, so activate it + if (Bot.HasInMonstersZone(CardId.PrimiteDragonEtherBeryl, faceUp: true) && !activatedCardIdList.Contains(CardId.PrimiteDrillbeam + 1) + && (CurrentTiming & hintToHand) == 0) + { + List targetList = GetNormalEnemyTargetList(true, true, CardType.Spell, true); + if (targetList.Count > 0) { + activateFlag = true; + } + } + + // become target + if (DefaultOnBecomeTarget()) { + activateFlag |= Enemy.GetSpells().Any(c => c.IsFaceup() && !c.IsDisabled() && CheckCanBeTargeted(c, true, CardType.Spell)); + activateFlag |= Enemy.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled() && CheckCanBeTargeted(c, true, CardType.Spell)); + } + + if (Duel.Phase == DuelPhase.BattleStep) + { + // remove problematic enemy monster + ClientCard problematicEnemyMonster = GetProblematicEnemyMonster(0, true, true, CardType.Spell); + if (problematicEnemyMonster != null && !problematicEnemyMonster.IsDisabled()) + { + activateFlag = true; + } + } + + if (activateFlag) + { + activatedCardIdList.Add(Card.Id); + SelectSTPlace(Card, true); + return true; + } + + return false; + } + + public bool PrimiteLordlyLodeActivate() + { + if (Card.Location == CardLocation.SpellZone && Card.IsFaceup()) + { + return false; + } + + // activate + bool activateFlag = PrimiteLordlyLodeActivateCheck(); + Logger.DebugWriteLine("PrimiteLordlyLodeActivate: " + activateFlag); + if (activateFlag) + { + SelectSTPlace(Card, true); + activatedCardIdList.Add(Card.Id); + return true; + } + return false; + } + + public bool PrimiteLordlyLodeActivateCheck() + { + if (CheckWhetherNegated(true, true, CardType.Spell)) return false; + bool activateFlag = false; + if (Bot.HasInHandOrHasInMonstersZone(CardId.PrimiteDragonEtherBeryl) && DefaultCheckWhetherBotCanSearch()) + { + // for search drillbeam + activateFlag |= CheckRemainInDeck(CardId.PrimiteDrillbeam) > 0; + activateFlag |= summonCount <= 0 && Card.Location == CardLocation.SpellZone && Card.IsFacedown(); + } + if (summonCount > 0 && !Bot.HasInHand(CardId.PrimiteDragonEtherBeryl) && CheckRemainInDeck(CardId.PrimiteDragonEtherBeryl) > 0 && DefaultCheckWhetherBotCanSearch()) + { + // for search ether beryl + activateFlag |= Bot.HasInGraveyard(CardId.PrimiteDrillbeam); + activateFlag |= CheckWhetherCanActivateMonsterEffect(CardAttribute.Earth) && !CheckWhetherNegated(true, true, CardType.Monster); + } + if (!Bot.HasInSpellZone(CardId.PrimiteLordlyLode, true, true)) + { + // for activate it + activateFlag |= DefaultCheckWhetherBotCanSearch(); + + // for special summon + CardLocation loc; + if (Bot.HasInHand(CardId.LabradoriteDragon)) + { + loc = CardLocation.Hand; + } + else if (CheckRemainInDeck(CardId.LabradoriteDragon) > 0) + { + loc = CardLocation.Deck; + } + else if (Bot.HasInGraveyard(CardId.LabradoriteDragon)) + { + loc = CardLocation.Grave; + } else { + return false; + } + int drawCount = GetSpecialSummonDrawCount(loc); + if (drawCount < 2) + { + activateFlag |= Bot.GetMonsters().Any(c => c.IsFaceup() && c.Level == 4 && !c.HasType(CardType.Xyz | CardType.Link)) + && Bot.ExtraDeck.Any(c => c.IsFaceup() && c.Level == 10 && c.HasType(CardType.Synchro)); + } + } + if (Card.Location == CardLocation.SpellZone && Card.IsFacedown()) + { + activateFlag |= DefaultCheckWhetherBotCanSearch(); + } + return activateFlag; + } + + public bool PrimiteLordlyLodeSpSummon() + { + if (Card.Location == CardLocation.SpellZone && Card.IsFaceup()) + { + // add activating flag + if (CheckWhetherNegated()) return false; + if (!PrimiteLordlyLodeSpSummonCheck()) return false; + activatingLodeSpSummonEffect = true; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public bool PrimiteLordlyLodeSpSummonCheck() + { + // special summon + CardLocation loc; + if (Bot.HasInHand(CardId.LabradoriteDragon)) + { + loc = CardLocation.Hand; + } + else if (CheckRemainInDeck(CardId.LabradoriteDragon) > 0) + { + loc = CardLocation.Deck; + } + else if (Bot.HasInGraveyard(CardId.LabradoriteDragon)) + { + loc = CardLocation.Grave; + } else { + return false; + } + int drawCount = GetSpecialSummonDrawCount(loc); + return drawCount < 2; + } + + public bool TreasuresOfTheKingsActivate() + { + if (CheckWhetherNegated()) return false; + + // search + if (ActivateDescription == Util.GetStringId(CardId.TreasuresOfTheKings, 0)) + { + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + // activate + bool activateFlag = false; + if (Bot.GetSpellCountWithoutField() == 5) + { + // for search + if (!DefaultCheckWhetherBotCanSearch() || CheckRemainInDeck(CardId.TheManWithTheMark, CardId.AnubisTheLastJudge) == 0) + { + activateFlag = false; + } + else + { + bool hasOtherSpellTrapInHand = + Bot.Hand.Any(c => (c.IsSpell() || c.IsTrap()) && c != Card); + + bool gyHasTrap = + Bot.Graveyard.Any(c => c.IsTrap()); + + int otherFacedownOnField = + Bot.GetMonsters().Count(m => m.IsFacedown()) + + Bot.GetSpells().Count(s => s.IsFacedown() && s != Card); + + activateFlag = gyHasTrap || hasOtherSpellTrapInHand || otherFacedownOnField >= 2; + } + } + else + { + // for set + if (CheckRemainInDeck(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity) > 0) + activateFlag = true; + } + + return activateFlag; + } + + public bool DominusSparkActivate() + { + if (CheckWhetherNegated()) return false; + // activate from field first + if (Duel.MainPhase.ActivableCards.Any(c => c.IsCode(CardId.DominusSpark) && c.IsOnField() && c != Card + && !infiniteImpermanenceNegatedColumns.Contains(c.Sequence))) + { + return false; + } + + bool shouldActivate = false; + // check whether there is a dangerous monster + ClientCard dangerousMonster = GetProblematicEnemyMonster(-1, true, false, CardType.Trap); + shouldActivate |= dangerousMonster != null; + + if (Duel.Phase == DuelPhase.BattleStep && Duel.Player == 1) + { + dangerousMonster = GetProblematicEnemyMonster(0, true, false, CardType.Trap); + shouldActivate |= dangerousMonster != null; + } + + // check whether it is the end phase and there is a monster on the enemy field + if (Duel.Phase == DuelPhase.End && Duel.Player == 1 && Duel.Turn == 1) + { + List endPhaseTargets = GetNormalEnemyTargetList(canBeTarget: true, ignoreCurrentDestroy: true, selfType: CardType.Trap); + shouldActivate |= endPhaseTargets.Any(c => c.IsMonster() && c.IsFaceup()); + } + + shouldActivate |= DefaultOnBecomeTarget() && !CheckWhetherNegated(); + + if (shouldActivate) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public bool InfiniteImpermanenceActivate() + { + if (CheckWhetherNegated()) return false; + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = Card.Sequence; + int that_seq = -1; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone) that_seq = LastChainCard.Sequence; + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || Util.IsChainTarget(Card) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + return true; + } + } + + // negate monster + List shouldNegateList = GetMonsterListForTargetNegate(true, CardType.Trap); + if (shouldNegateList.Count > 0) + { + SelectSTPlace(Card, true); + return true; + } + + return false; + } + + public bool DominusNegateTrapActivate() + { + if (CheckWhetherNegated()) return false; + // activate from field first + if (Duel.MainPhase.ActivableCards.Any(c => c.IsCode(Card.Id) && c.IsOnField() && c != Card + && !infiniteImpermanenceNegatedColumns.Contains(c.Sequence))) + { + return false; + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + if (LastChainCard != null && LastChainCard.Controller == 1 && CheckCardShouldNegate(LastChainCard)) + { + currentNegateCardList.Add(LastChainCard); + SelectSTPlace(Card, true); + if (Card.IsCode(CardId.SongsOfTheDominators) && Card.Location == CardLocation.Hand) + { + songsOfTheDominatorsActivatedFromHand = true; + } + return true; + } + + return false; + } + + public bool SongsOfTheDominatorsActivateFirst() + { + return Bot.Graveyard.Any(c => c.HasType(CardType.Trap)) && DominusNegateTrapActivate(); + } + + public bool ApophisTheSwampDeityActivate() + { + return ApophisTheSwampDeityActivateCheck(1); + } + + public bool ApophisTheSwampDeityActivateForAttack() + { + return ApophisTheSwampDeityActivateCheck(2); + } + + public bool ApophisTheSwampDeityActivateCheck(int activatePriority = 0) + { + if (CheckWhetherNegated()) return false; + if (currentSummoningCount + Bot.GetMonsters().Count(c => c.Sequence < 5) >= 5) return false; + + int canNegateCount = Bot.GetSpells().Count(c => c != Card && + (c.IsCode(CardId.ApophisTheSwampDeity) + || (c.IsCode(CardId.ApophisTheSerpent) && + (c.IsFaceup() || !activatedCardIdList.Contains(CardId.ApophisTheSerpent))))); + canNegateCount += Bot.GetMonsters().Count(c => c.IsCode(new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity }) && c.IsFaceup()); + + bool shouldActivate = false; + // for negate + if (Duel.CurrentChain.Count > 0 && canNegateCount > 0) + { + // exists cards to negate? + foreach (ClientCard chain in Duel.CurrentChain) + { + if (chain.IsFaceup() && chain.IsOnField() && chain.Controller == 1 && !currentNegateCardList.Contains(chain)) + { + Logger.DebugWriteLine("[ApophisTheSwampDeity] Negate card on chain: " + chain.Name); + shouldActivate = true; + break; + } + } + } + + // for summon divine serpent + if (DivineSerpentApophisSpSummonCheck()) { + int newApophisCount = Duel.MainPhase.ActivableCards.Count(c => c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity)); + int currentApophisCount = Bot.GetMonsters().Count(c => c.IsFaceup() && + (c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity) || (c.IsCode(CardId.DivineSerpentApophis) && activatedDivineSerpent1stList.Contains(c)))); + bool checkResult = currentApophisCount < 2 && currentApophisCount + newApophisCount >= 2; + if (checkResult) + { + Logger.DebugWriteLine("[ApophisTheSwampDeity] DivineSerpentApophisSpSummonCheck: " + checkResult); + } + shouldActivate |= checkResult; + } + + // for little knight + if (Bot.ExtraDeck.Any(c => c.IsCode(CardId.SPLittleKnight)) && !SPLittleKnightSummonCheck() && SPLittleKnightSummonCheck(true) + && Duel.Player == 0 && Bot.ExtraDeck.Any(c => c.IsCode(CardId.LinkSpider))) + { + bool checkResult = Bot.GetMonsters().Count(c => c.IsFaceup() && c.HasType(CardType.Effect)) == 1; + if (checkResult) + { + Logger.DebugWriteLine("[ApophisTheSwampDeity] SPSmallKnightSummonCheck: " + checkResult); + } + shouldActivate |= checkResult; + } + + // for triggering divine serpent apophis + if (CheckWhetherCanActivateMonsterEffect(CardAttribute.Earth) && !CheckWhetherNegated(true, true, CardType.Monster) + && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled() && c.IsCode(CardId.DivineSerpentApophis) && !activatedDivineSerpent2ndList.Contains(c))) + { + bool checkResult = GetProblematicEnemyCardList(true, false, CardType.Monster).Count() > 0 + && !Duel.CurrentChain.Any(c => c.Controller == 0 && c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity)) + && !Duel.MainPhase.ActivableCards.Any(c => c.IsCode(CardId.ApophisTheSerpent)); + if ((CurrentTiming & hintTimingMainEnd) != 0 && Duel.Player == 1) + { + checkResult |= GetNormalEnemyTargetList(true, true, CardType.Monster).Count() > 0 + && !Duel.CurrentChain.Any(c => c.Controller == 0 && c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity)) + && !Duel.MainPhase.ActivableCards.Any(c => c.IsCode(CardId.ApophisTheSerpent)); + } + if (checkResult) + { + Logger.DebugWriteLine("[ApophisTheSwampDeity] DivineSerpentApophisActivate: " + checkResult); + } + shouldActivate |= checkResult; + } + + // for triggering silhouette hat rabbit + if (CheckWhetherCanActivateMonsterEffect(CardAttribute.Light) && !CheckWhetherNegated(true, true, CardType.Monster, true) + && !activatedCardIdList.Contains(CardId.SilhouhatteRabbit + 1) + && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled() && c.IsCode(CardId.SilhouhatteRabbit))) + { + bool checkResult = GetProblematicEnemyCardList(true, false, CardType.Monster).Count(c => c.HasType(CardType.Spell | CardType.Trap)) > 0 + && !Duel.CurrentChain.Any(c => c.Controller == 0 && c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity)) + && !Duel.MainPhase.ActivableCards.Any(c => c.IsCode(CardId.ApophisTheSerpent)); + if ((CurrentTiming & hintTimingMainEnd) != 0 && Duel.Player == 1) + { + checkResult |= GetNormalEnemySpellTargetList(true, true, CardType.Monster).Count() > 0 + && !Duel.CurrentChain.Any(c => c.Controller == 0 && c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity)) + && !Duel.MainPhase.ActivableCards.Any(c => c.IsCode(CardId.ApophisTheSerpent)); + } + if (checkResult) + { + Logger.DebugWriteLine("[ApophisTheSwampDeity] SilhouhatteRabbitSummonCheck: " + checkResult); + } + shouldActivate |= checkResult; + } + + // for triggering primite drillbeam + if (Bot.HasInHandOrInSpellZone(CardId.PrimiteDrillbeam) && !activatedCardIdList.Contains(CardId.PrimiteDrillbeam)) + { + // whether have other cards to trigger primite beam + bool canTriggerPrimiteBeam = Bot.Hand.Any(c => c.IsCode(CardId.PrimiteDragonEtherBeryl, CardId.PrimiteLordlyLode, CardId.LabradoriteDragon)); + canTriggerPrimiteBeam |= Bot.HasInMonstersZone(new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity, CardId.LabradoriteDragon }, faceUp: true); + canTriggerPrimiteBeam |= Bot.GetSpells().Any(c => c != Card && c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity) && (c.IsFacedown() || Duel.CurrentChain.Contains(c))); + + bool checkResult = !canTriggerPrimiteBeam; + if (checkResult) + { + Logger.DebugWriteLine("[ApophisTheSwampDeity] PrimiteDrillbeamSummonCheck: " + checkResult); + } + shouldActivate |= !canTriggerPrimiteBeam; + } + + // TODO for other summon + + // for attack + if (Duel.Turn > 1 && Duel.Phase == DuelPhase.Main1 && Enemy.GetMonsterCount() == 0 && Duel.Player == 0 && Duel.CurrentChain.Count == 0 + && activatePriority >= 2) + { + Logger.DebugWriteLine("[ApophisTheSwampDeity] Attack: " + true); + shouldActivate |= true; + } + + // for defense + if (Duel.Phase == DuelPhase.Main1 && Bot.GetMonsterCount() == 0 && Enemy.GetMonsters().Sum(c => c.Attack) >= Bot.LifePoints + && (CurrentTiming & hintTimingMainEnd) != 0) + { + Logger.DebugWriteLine("[ApophisTheSwampDeity] Defense: " + true); + shouldActivate |= true; + } + + if (shouldActivate) + { + // mark cards to negate + int negateCount = Bot.GetSpells().Count(c => c != Card && c.IsFaceup() && c.HasType(CardType.Continuous) && c.HasType(CardType.Trap)); + negateCount += Bot.GetMonsters().Count(c => c.IsFaceup() && c.HasType(CardType.Continuous) && c.HasType(CardType.Trap)); + // negate cards on chain fist + if (negateCount > 0) + { + foreach (ClientCard chain in Duel.CurrentChain) + { + if (chain.IsFaceup() && chain.IsOnField() && !currentNegateCardList.Contains(chain) && CheckCardShouldNegate(chain)) + { + negateCount--; + currentNegateCardList.Add(chain); + if (negateCount <= 0) break; + } + } + } + + if (negateCount > 0) + { + // Find negatable enemy spell/trap cards on field that are not yet negated + List negatableSpellsTraps = Enemy.GetSpells().Where(c => + c.IsFaceup() && + !c.IsDisabled() && + !currentNegateCardList.Contains(c) + ).ToList(); + + // Mark negatable spell/trap cards as negated, up to the available count + foreach (ClientCard card in negatableSpellsTraps) + { + currentNegateCardList.Add(card); + negateCount--; + if (negateCount <= 0) break; + } + } + + if (negateCount > 0) + { + // Find negatable enemy monsters on field that are not yet negated + List negatableMonsters = Enemy.GetMonsters().Where(c => + c.IsFaceup() && + !c.IsDisabled() && + !currentNegateCardList.Contains(c) + ).ToList(); + + // Mark negatable monsters as negated, up to the remaining count + foreach (ClientCard card in negatableMonsters) + { + currentNegateCardList.Add(card); + negateCount--; + if (negateCount <= 0) break; + } + } + + currentSummoningCount++; + return true; + } + + return false; + } + + public bool ApophisTheSerpentActivate() + { + if (CheckWhetherNegated()) return false; + if (currentSummoningCount + Bot.GetMonsters().Count(c => c.Sequence < 5) >= 5) return false; + if (Bot.GetSpells().Any(c => c.IsFacedown() && c.IsCode(CardId.ApophisTheSwampDeity) && !infiniteImpermanenceNegatedColumns.Contains(c.Sequence))) + { + if (!(Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2)) + { + return false; + } + } + currentSummoningCount++; + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool SpellNegateActivate() + { + if (CheckWhetherNegated() || Duel.LastChainPlayer != 1) return false; + + ClientCard prevChainCard = Util.GetLastChainCard(); + if (prevChainCard != null && !CheckCardShouldNegate(prevChainCard)) + { + return false; + } + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool SolemnReportBanishActivate() + { + if (SpellNegateActivate()) + { + ClientCard prevChainCard = Util.GetLastChainCard(); + if (prevChainCard != null && prevChainCard.IsCode(solemnReportBanishIdList)) + { + return true; + } + } + return false; + } + + public bool DivineSerpentApophisSpSummonCheck() + { + if (Duel.Player != 0) return false; + bool checkFlag = false; + // recycle + if (CheckWhetherCanActivateMonsterEffect(CardAttribute.Earth) && !CheckWhetherNegated(true, true, CardType.Monster) + && Bot.GetSpellCountWithoutField() < 5) + { + checkFlag |= Bot.HasInGraveyard(new List { CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity }); + checkFlag |= !CheckWhetherWillbeRemoved(); + } + + // for attack + checkFlag |= GetBotBestPower(true) <= Util.GetBestPower(Enemy) && Util.GetBestPower(Enemy) < 2800; + + return checkFlag; + } + + public bool DivineSerpentApophisSpSummon() + { + if (!DivineSerpentApophisSpSummonCheck()) return false; + // select material with different name + ClientCard apophisTheSerpent = Bot.GetMonsters().FirstOrDefault(c => c.IsFaceup() && c.IsCode(CardId.ApophisTheSerpent)); + ClientCard apophisTheSwampDeity = Bot.GetMonsters().FirstOrDefault(c => c.IsFaceup() && c.IsCode(CardId.ApophisTheSwampDeity)); + AI.SelectMaterials(new List { apophisTheSerpent, apophisTheSwampDeity }, HintMsg.Release); + return true; + } + + public bool DivineSerpentApophisActivate() + { + if (CheckWhetherNegated()) return false; + if (ActivateDescription == Util.GetStringId(CardId.DivineSerpentApophis, 0)) + { + // set trap + activatedDivineSerpent1stList.Add(Card); + } + else + { + // destroy + List targetList = GetNormalEnemyTargetList(true, false, CardType.Monster); + if (targetList.Count() == 0) + { + return false; + } + activatedDivineSerpent2ndList.Add(Card); + } + return true; + } + + public bool Level10SynchroSummon() + { + if (!Level10SynchroSummonCheck()) return false; + if (!Card.IsCode(new List { CardId.BaronneDeFleur, CardId.SwordsoulSupremeSovereignChengying })) + { + return false; + } + + int decideSummonId = 0; + // select which to summon + if (GetBotBestPower(true) < Util.GetBestPower(Enemy) && Util.GetBestPower(Enemy) > 3000 + && (!CheckWhetherCanActivateMonsterEffect(CardAttribute.Wind) || lodeSpSummonEffectResolved) + && Duel.Phase == DuelPhase.Main1 && Duel.Turn > 1) + { + int banishCount = Bot.Banished.Count() + Enemy.Banished.Count(); + if (3000 + banishCount * 200 >= Util.GetBestPower(Enemy) + && Duel.MainPhase.SummonableCards.Any(c => c.IsCode(CardId.SwordsoulSupremeSovereignChengying)) + && !Card.IsCode(CardId.SwordsoulSupremeSovereignChengying)) + { + return false; + } + decideSummonId = CardId.SwordsoulSupremeSovereignChengying; + } + if (decideSummonId == 0 && CheckWhetherCanActivateMonsterEffect(CardAttribute.Wind) + && Duel.MainPhase.SummonableCards.Any(c => c.IsCode(CardId.BaronneDeFleur)) + && !Card.IsCode(CardId.BaronneDeFleur)) + { + return false; + } + if (decideSummonId == 0 && !CheckWhetherCanActivateMonsterEffect(CardAttribute.Wind) + && Duel.MainPhase.SummonableCards.Any(c => c.IsCode(CardId.SwordsoulSupremeSovereignChengying)) + && !Card.IsCode(CardId.SwordsoulSupremeSovereignChengying)) + { + return false; + } + + ClientCard level4Monster = Bot.GetMonsters().FirstOrDefault(c => c.IsFaceup() && c.Level == 4 && c.IsCode(CardId.PrimiteDragonEtherBeryl)); + + if (level4Monster == null) + { + // find level4 monster with lowest power + level4Monster = Bot.GetMonsters().OrderBy(c => c.GetDefensePower()).FirstOrDefault(c => c.IsFaceup() && c.Level == 4 && !c.HasType(CardType.Xyz | CardType.Link)); + } + if (level4Monster == null) + { + return false; + } + + ClientCard level6Tuner = Bot.GetMonsters().OrderBy(c => c.GetDefensePower()).FirstOrDefault(c => c.IsFaceup() && c.Level == 6 && c.IsTuner()); + if (level6Tuner == null) + { + return false; + } + AI.SelectMaterials(new List { level4Monster, level6Tuner }); + return true; + } + + public bool Level10SynchroSummonCheck() + { + if (CheckShouldNoMoreSpSummon()) return false; + if (GetSpecialSummonDrawCount(CardLocation.Extra) > 1 && CheckAtAdvantage()) return false; + + return true; + } + + public bool SwordsoulSupremeSovereignChengyingActivate() + { + if (CheckWhetherNegated()) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool BaronneDeFleurNegateEffect() + { + if (ActivateDescription != Util.GetStringId(CardId.BaronneDeFleur, 1)) + { + return false; + } + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + ClientCard lastChainCard = Util.GetLastChainCard(); + if (Duel.LastChainPlayer == 1 && lastChainCard != null) + { + if (CheckAtAdvantage() && lastChainCard.IsCode(new List {_CardId.MaxxC, _CardId.MulcharmyFuwalos, _CardId.MulcharmyNyalus, _CardId.MulcharmyPurulia})) + { + return false; + } + if (Duel.LastChainTargets.Contains(Card) && lastChainCard.IsCode(_CardId.EffectVeiler, _CardId.InfiniteImpermanence, _CardId.BreakthroughSkill)) + { + return false; + } + } + currentNegateCardList.Add(lastChainCard); + return true; + } + + public bool BaronneDeFleurActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.BaronneDeFleur, 1)) + { + // negate + return false; + } else if (Duel.Phase == DuelPhase.Standby) + { + // special summon + // TODO waiting for handle OnCardHint + return false; + } else { + // destroy + List targetList = GetNormalEnemyTargetList(); + if (targetList.Count() > 0) + { + return true; + } + } + + return false; + } + + public bool SuperdreadnoughtRailCannonJuggernautLiebeActivate() + { + if (CheckWhetherNegated()) return false; + return true; + } + + public bool SuperdreadnoughtRailCannonJuggernautLiebeSpSummon() + { + if (!SuperdreadnoughtRailCannonJuggernautLiebeSpSummonCheck()) return false; + return true; + } + + public bool SuperdreadnoughtRailCannonJuggernautLiebeSpSummonCheck() + { + int enemyPower = Util.GetBestPower(Enemy); + int botPower = GetBotBestPower(true); + if (botPower < enemyPower) + { + int currentAttack = 4000; + if (!CheckWhetherNegated(true, true, CardType.Monster) && CheckWhetherCanActivateMonsterEffect(CardAttribute.Earth) && !lodeSpSummonEffectResolved) + { + currentAttack += 2000; + } + if (currentAttack >= enemyPower) + { + return true; + } + } + return false; + } + + public bool SuperdreadnoughtRailCannonFlyingLauncherActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.SuperdreadnoughtRailCannonFlyingLauncher, 2)) + { + List targetList = GetNormalEnemySpellTargetList(true, false, CardType.Monster); + if (targetList.Count() > 0) + { + return true; + } + } + return false; + } + + public bool SuperdreadnoughtRailCannonFlyingLauncherSpSummon() + { + bool hasLiebeInExtra = Bot.ExtraDeck.Any(c => c.IsCode(CardId.SuperdreadnoughtRailCannonJuggernautLiebe)); + int enemyPower = Util.GetBestPower(Enemy); + int botPower = GetBotBestPower(true); + bool needSummonLiebe = SuperdreadnoughtRailCannonJuggernautLiebeSpSummonCheck(); + + if ((hasLiebeInExtra && needSummonLiebe) + || (!hasLiebeInExtra && botPower < enemyPower && enemyPower <= 3800) + || (CheckWhetherCanActivateMonsterEffect(CardAttribute.Earth) + && !CheckWhetherNegated(true, true, CardType.Monster) + && !lodeSpSummonEffectResolved + && GetNormalEnemySpellTargetList(true, false, CardType.Monster).Count() > 0)) + { + return true; + } + return false; + } + + public bool EvilswarmExcitonKnightSummon() + { + if (CheckWhetherNegated(true, true, CardType.Monster) || !CheckWhetherCanActivateMonsterEffect(CardAttribute.Light)) return false; + int selfCount = Bot.GetMonsterCount() + Bot.GetSpellCount() + Bot.GetHandCount(); + int oppoCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount() + Enemy.GetHandCount(); + return (selfCount - 1 < oppoCount) && DefaultEvilswarmExcitonKnightEffect(); + } + + public bool SPLittleKnightActivate() + { + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.SPLittleKnight, 0)) + { + // banish card + List problemCardList = GetProblematicEnemyCardList(true, selfType: CardType.Monster); + problemCardList.AddRange(GetNormalEnemyTargetList(true, true, CardType.Monster)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => card.HasType(CardType.Monster)).OrderByDescending(card => card.Attack)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => !card.HasType(CardType.Monster))); + if (problemCardList.Count() > 0) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } else if (ActivateDescription == Util.GetStringId(CardId.SPLittleKnight, 1)) + { + ClientCard selfMonster = null; + foreach (ClientCard target in Bot.GetMonsters()) + { + if (Duel.ChainTargets.Contains(target)) + { + selfMonster = target; + break; + } + } + if (selfMonster == null) + { + if (Duel.Player == 1) + { + selfMonster = Bot.GetMonsters().Where(card => card.IsAttack()).OrderBy(card => card.Attack).FirstOrDefault(); + if (!Util.IsOneEnemyBetterThanValue(selfMonster.Attack, true)) selfMonster = null; + } + } + if (selfMonster != null) + { + ClientCard nextMonster = null; + List selfTargetList = Bot.GetMonsters().Where(card => card != selfMonster).ToList(); + if (Enemy.GetMonsterCount() == 0 && selfTargetList.Count() > 0) + { + selfTargetList.Sort(CompareUsableAttack); + nextMonster = selfTargetList[0]; + } + if (Enemy.GetMonsterCount() > 0) + { + nextMonster = GetProblematicEnemyMonster(0, true, false, CardType.Monster); + } + if (nextMonster != null) + { + SPLittleKnightRemoveStep = 1; + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + + return false; + } + + public bool SPLittleKnightSummon() + { + if (CheckWhetherNegated(true, true, CardType.Monster, true) || !CheckWhetherCanActivateMonsterEffect(CardAttribute.Dark)) return false; + + List effectMonsters = Bot.GetMonsters().Where(c => c.IsFaceup() && c.HasType(CardType.Effect) + && (!c.IsCode(CardId.SilhouhatteRabbit) || !summonThisTurn.Contains(c)) + ).OrderBy(c => c.GetDefensePower()).ToList(); + + // summon to remove problem cards + if (SPLittleKnightSummonCheck() || Util.IsTurn1OrMain2() && (Enemy.GetMonsterCount() + Enemy.GetSpellCount() + Enemy.Graveyard.Count > 0)) + { + ClientCard extraMonster = null; + ClientCard otherMonster = null; + foreach (ClientCard monster in effectMonsters) + { + // skip important monster if needed + if (Util.IsTurn1OrMain2() && monster.IsCode(new List { CardId.BaronneDeFleur, CardId.SwordsoulSupremeSovereignChengying, CardId.DivineSerpentApophis })) + { + continue; + } + + if (monster.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)) + { + if (extraMonster != null) + { + otherMonster = monster; + } + else + { + extraMonster = monster; + } + } + else + { + otherMonster = monster; + } + + if (extraMonster != null && otherMonster != null) + { + break; + } + } + + if (extraMonster != null && otherMonster != null) + { + AI.SelectMaterials(new List { extraMonster, otherMonster }); + return true; + } + } + + return false; + } + + public bool SPLittleKnightSummonCheck(bool ignoreMaterialCheck = false) + { + if (CheckWhetherNegated(true, true, CardType.Monster, true) + || !CheckWhetherCanActivateMonsterEffect(CardAttribute.Dark) + || lodeSpSummonEffectResolved) return false; + // banish card + List problemCardList = GetProblematicEnemyCardList(true, selfType: CardType.Monster, ignoreSpells: !Util.IsTurn1OrMain2()); + bool summonFlag = problemCardList.Count() > 0; + ClientCard problematicEnemyMonster = GetProblematicEnemyMonster(0, true, false, CardType.Monster); + if (problematicEnemyMonster != null) + { + summonFlag = true; + } + if (summonFlag) + { + if (ignoreMaterialCheck) + { + return true; + } + // check material + return Bot.GetMonsters().Any(c => c.IsFaceup() && c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) + && (!c.IsCode(CardId.SilhouhatteRabbit) || !summonThisTurn.Contains(c))) + && Bot.GetMonsters().Count(c => c.IsFaceup() && c.HasType(CardType.Effect)) >= 2; + } + + return false; + } + + public bool SilhouhatteRabbitActivate() + { + if (CheckWhetherNegated()) return false; + if (ActivateDescription == Util.GetStringId(CardId.SilhouhatteRabbit, 0) || ActivateDescription == -1) + { + // set + // default to true + activatedCardIdList.Add(Card.Id); + return true; + } else + { + // destroy + List targetList = GetNormalEnemySpellTargetList(true, false, CardType.Monster, false); + if (targetList.Count() > 0) + { + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + return false; + } + + public bool SilhouhatteRabbitSummon() + { + if (CheckWhetherNegated(true, true, CardType.Monster, true) || !CheckWhetherCanActivateMonsterEffect(CardAttribute.Light)) return false; + if (!SilhouhatteRabbitSummonCheck()) return false; + // select material + ClientCard anubis = Bot.GetMonsters().FirstOrDefault(c => c.IsFaceup() && c.IsCode(CardId.AnubisTheLastJudge)); + List materialList = new List { }; + if (anubis != null) + { + materialList.Add(anubis); + } + // select remain material + List effectMonsters = Bot.GetMonsters().Where(c => c.IsFaceup() && c.HasType(CardType.Effect) + && (!c.IsCode(CardId.SilhouhatteRabbit) || !summonThisTurn.Contains(c)) + ).OrderBy(c => c.GetDefensePower()).ToList(); + if (effectMonsters.Count() > 0) + { + foreach (ClientCard monster in effectMonsters) + { + // skip important monster if needed + if (monster.IsCode(new List { CardId.BaronneDeFleur, CardId.SwordsoulSupremeSovereignChengying, CardId.DivineSerpentApophis, CardId.SPLittleKnight })) + { + continue; + } + materialList.Add(monster); + if (materialList.Count() >= 2) + { + break; + } + } + } + + if (materialList.Count() >= 2) + { + AI.SelectMaterials(materialList); + return true; + } + return false; + } + + public bool SilhouhatteRabbitSummonCheck(bool ignoreMaterialCheck = false) + { + if (CheckWhetherNegated(true, true, CardType.Monster, true) + || !CheckWhetherCanActivateMonsterEffect(CardAttribute.Light) + || lodeSpSummonEffectResolved) return false; + + List problemCardList = GetProblematicEnemyCardList(true, selfType: CardType.Monster); + if (problemCardList.Count() > 0) + { + return false; + } + int remainApophisCount = CheckRemainInDeck(CardId.ApophisTheSwampDeity); + if (remainApophisCount == 0) + { + return false; + } + if (Bot.Hand.Any(c => c.IsCode(CardId.ApophisTheSwampDeity)) || Bot.GetSpells().Any(c => c.IsCode(CardId.ApophisTheSwampDeity) && c.IsFacedown())) + { + return false; + } + if (activatedCardIdList.Contains(CardId.SilhouhatteRabbit)) + { + return false; + } + if (ignoreMaterialCheck) + { + return true; + } + return Bot.GetMonsters().Count(c => c.IsFaceup() && c.HasType(CardType.Effect) + && (!c.IsCode(CardId.SilhouhatteRabbit) || !summonThisTurn.Contains(c))) >= 2; + } + + public bool LinkSpiderSummon() + { + // check whether monster is enough + int monsterCount = Bot.GetMonsterCount() + Duel.MainPhase.ActivableCards.Count(c => c.IsOnField() && c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity)); + if (monsterCount < 2) + { + return false; + } + + // summon little knight check + if (Bot.ExtraDeck.Any(c => c.IsCode(CardId.SPLittleKnight))) + { + if (SPLittleKnightSummonCheck()) + { + return false; + } + if (SPLittleKnightSummonCheck(true)) + { + return true; + } + } + // summon silhouhatte rabbit check + if (Bot.ExtraDeck.Any(c => c.IsCode(CardId.SilhouhatteRabbit))) + { + if (SilhouhatteRabbitSummonCheck()) + { + return false; + } + if (SilhouhatteRabbitSummonCheck(true)) + { + return true; + } + } + return false; + } + + public bool MonsterRepos() + { + int selfAttack = Card.Attack + 1; + + if (selfAttack <= 1) + return !Card.IsDefense(); + + int bestAttack = 0; + foreach (ClientCard card in Bot.GetMonsters()) + { + int attack = card.Attack; + if (attack >= bestAttack) + { + bestAttack = attack; + } + } + + bool enemyBetter = Util.IsAllEnemyBetterThanValue(bestAttack, true); + + if (Card.IsAttack() && enemyBetter) + return true; + if (Card.IsDefense() && !enemyBetter) + return true; + return false; + } + + public bool MonstetReposForImportantMonsters() + { + if (!Card.IsFacedown()) + { + return false; + } + return Card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz); + } + + public bool SpellSetFirst() + { + // pretend to have solemn report + int setCount = Bot.GetSpells().Count(c => c.IsFacedown() && c.Sequence < 5); + if (setCount < 2 && Bot.LifePoints > 1500) + { + if (setCount == 1 && !Bot.HasInSpellZone(CardId.SolemnReport) && Bot.HasInHand(CardId.SolemnReport) && Bot.GetSpells().Any(c => c.IsTrap() && c.IsFacedown())) + { + if (!Card.IsCode(CardId.SolemnReport)) + { + return false; + } + SelectSTPlace(Card, true); + return true; + } + // if card should set + List canSetSpells = GetCanSetSpells(); + if (setCount + canSetSpells.Count() > 0 && canSetSpells.Contains(Card) && (!Bot.HasInHand(CardId.SolemnReport) || Card.IsTrap())) + { + bool avoidImpermanence = Card.IsCode(CardId.SolemnReport); + SelectSTPlace(Card, avoidImpermanence); + return true; + } + } + return false; + } + + public List GetCanSetSpells() + { + List canSetSpells = new List(); + foreach (ClientCard card in Bot.Hand) + { + bool setFlag = false; + switch (Card.Id) + { + case CardId.Terraforming: + setFlag |= CheckRemainInDeck(CardId.TreasuresOfTheKings) > 0 && DefaultCheckWhetherBotCanSearch(); + break; + case CardId.PrimiteLordlyLode: + setFlag |= PrimiteLordlyLodeActivateCheck() && !canSetSpells.Any(c => c.IsCode(CardId.PrimiteLordlyLode)); + break; + case CardId.DominusSpark: + setFlag |= !enemyActivateMonsterEffectFromHandGrave; + break; + case _CardId.InfiniteImpermanence: + case CardId.VerdictOfAnubis: + case CardId.SolemnReport: + setFlag = true; + break; + case CardId.DominusPurge: + case CardId.DominusImpulse: + setFlag |= Enemy.GetMonsterCount() + Enemy.GetSpellCount() == 0; + break; + case CardId.SongsOfTheDominators: + setFlag |= !Bot.Graveyard.Any(c => c.IsMonster()); + break; + case CardId.ApophisTheSwampDeity: + setFlag |= Bot.Hand.Any(c => c != card && c.HasType(CardType.Continuous) && c.HasType(CardType.Trap)); + setFlag |= Bot.GetSpells().Any(c => c != card && c.HasType(CardType.Continuous) && c.HasType(CardType.Trap)); + setFlag |= Bot.GetMonsters().Any(c => c != card && c.HasType(CardType.Continuous) && c.HasType(CardType.Trap)); + break; + case CardId.ApophisTheSerpent: + setFlag |= CheckRemainInDeck(CardId.ApophisTheSwampDeity) > 0; + setFlag |= Bot.HasInHandOrInSpellZone(CardId.ApophisTheSwampDeity); + break; + default: + setFlag = false; + break; + } + if (setFlag) + { + canSetSpells.Add(card); + } + } + return canSetSpells; + } + + public bool SpellSet() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + + // select place + if (Card.IsTrap() || Card.HasType(CardType.QuickPlay)) + { + switch (Card.Id) + { + case _CardId.InfiniteImpermanence: + // do not set infinite impermanence if don't need to set other cards + if (Bot.GetMonsterCount() == 0 && Bot.GetSpellCount() == 0 + && !Bot.Hand.Any(c => !c.IsCode(_CardId.InfiniteImpermanence) && (c.IsTrap() || c.HasType(CardType.QuickPlay))) + && Bot.Hand.Count() <= 6) + { + return false; + } + break; + case CardId.SongsOfTheDominators: + // do not set songs of the dominators if don't need to set + if (!Bot.Graveyard.Any(c => c.IsMonster()) && Bot.GetMonsterCount() == 0) + { + return false; + } + if (Bot.GetSpells().Any(c => c.IsCode(CardId.SongsOfTheDominators) && c.IsFacedown())) + { + return false; + } + break; + case CardId.ApophisTheSwampDeity: + // do not set swamp deity if don't need to set + if ( + !Bot.Hand.Any(c => c != Card && c.HasType(CardType.Continuous) && c.HasType(CardType.Trap)) && + !Bot.GetSpells().Any(c => c != Card && c.HasType(CardType.Continuous) && c.HasType(CardType.Trap)) && + !Bot.GetMonsters().Any(c => c != Card && c.HasType(CardType.Continuous) && c.HasType(CardType.Trap)) && + !Bot.HasInHandOrInSpellZone(CardId.PrimiteDrillbeam) && + !(Bot.GetMonsterCount() == 0 + && !Bot.Hand.Any(c => c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity) && c != Card) + && !Bot.GetSpells().Any(c => c.IsCode(CardId.ApophisTheSerpent, CardId.ApophisTheSwampDeity) && c != Card && c.IsFacedown()) + ) + ) + { + return false; + } + break; + case CardId.SolemnReport: + { + if (Bot.LifePoints <= 1500) + { + return false; + } + break; + } + case CardId.ApophisTheSerpent: + case CardId.DominusImpulse: + case CardId.DominusPurge: + case CardId.DominusSpark: + if (Bot.GetSpells().Any(c => c.IsCode(Card.Id) && c.IsFacedown())) + { + return false; + } + break; + default: + break; + } + + List avoid_list = new List(); + int setForInfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + setForInfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setForInfiniteImpermanence); + return true; + } + else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } + else + { + SelectSTPlace(); + } + return true; + } + + else if (Enemy.HasInSpellZone(_CardId.AntiSpellFragrance, true) || Bot.HasInSpellZone(_CardId.AntiSpellFragrance, true)) + { + if (Card.IsSpell() && !Bot.HasInSpellZone(Card.Id)) + { + SelectSTPlace(); + return true; + } + } + + return false; + } + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlackwingExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlackwingExecutor.cs new file mode 100644 index 0000000..4aa2d6c --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlackwingExecutor.cs @@ -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 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 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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlueEyesExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlueEyesExecutor.cs new file mode 100644 index 0000000..1abf3b4 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlueEyesExecutor.cs @@ -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 UsedAlternativeWhiteDragon = new List(); + 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 OnSelectCard(IList 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 result = new List(); + 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 OnSelectXyzMaterial(IList cards, int min, int max) + { + Logger.DebugWriteLine("OnSelectXyzMaterial " + cards.Count + " " + min + " " + max); + IList result = Util.SelectPreferredCards(UsedAlternativeWhiteDragon, cards, min, max); + return Util.CheckSelectCount(result, cards, min, max); + } + + public override IList OnSelectSynchroMaterial(IList 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 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 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 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 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 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 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) + ); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlueEyesMaxDragonExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlueEyesMaxDragonExecutor.cs new file mode 100644 index 0000000..6b26c1a --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BlueEyesMaxDragonExecutor.cs @@ -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 material_list = new List(); + 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 material_list = new List(); + 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 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 attackers, IList 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 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; + } + + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BraveExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BraveExecutor.cs new file mode 100644 index 0000000..8a04acc --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BraveExecutor.cs @@ -0,0 +1,1043 @@ +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("Brave", "AI_Brave")] + class BraveExecutor : DefaultExecutor + { + public class CardId + { + public const int WanderingGryphonRider = 2563463; + public const int DestinyHeroDasher = 81866673; + public const int NemesesCorridor = 72090076; + public const int DestinyHeroCelestial = 63362460; + public const int AquamancerOfTheSanctuary = 30680659; + public const int Sangan = 26202165; + public const int CrusadiaArboria = 91646304; + public const int AshBlossomJoyousSpring = 14558127; + public const int MechaPhantomBeastOLion = 72291078; + public const int MaxxC = 23434538; + public const int JetSynchron = 9742784; + public const int EffectVeiler = 97268402; + public const int RiteofAramesia = 3285551; + public const int HarpiesFeatherDuster = 18144506; + public const int FusionDestiny = 52947044; + public const int FoolishBurial = 81439173; + public const int MonsterReborn = 83764718; + public const int CalledByTheGrave = 24224830; + public const int CrossoutDesignator = 65681983; + public const int JourneyOfDestiny = 39568067; + public const int DracobackTheDragonSteed = 38745520; + public const int InfiniteImpermanence = 10045474; + public const int SolemnStrike = 40605147; + public const int ThunderDragonColossus = 15291624; + public const int DestinyHeroDestroyPhoenixEnforcer = 60461804; + public const int BaronessDeFleur = 84815190; + public const int VirtualWorldKyubiShenshen = 92519087; + public const int BorreloadSavageDragon = 27548199; + public const int CoralDragon = 42566602; + public const int TGHyperLibrarian = 90953320; + public const int TGWonderMagician = 98558751; + public const int CupidPitch = 21915012; + public const int MechaPhantomBeastAuroradon = 44097050; + public const int CrystronHalqifibrax = 50588353; + public const int PredaplantVerteAnaconda = 70369116; + public const int LinkSpider = 98978921; + public const int SalamangreatAlmiraj = 60303245; + + public const int BraveToken = 3285552; + public const int MechaPhantomBeastToken = 31533705; + public const int PrimalBeingToken = 27204312; + } + + public BraveExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, CardId.WanderingGryphonRider, WanderingGryphonRiderCounter); + AddExecutor(ExecutorType.Activate, CardId.AshBlossomJoyousSpring, DefaultAshBlossomAndJoyousSpring); + AddExecutor(ExecutorType.Activate, CardId.CalledByTheGrave, DefaultCalledByTheGrave); + AddExecutor(ExecutorType.Activate, CardId.CrossoutDesignator, CrossoutDesignatorEffect); + AddExecutor(ExecutorType.Activate, CardId.EffectVeiler, DefaultEffectVeiler); + AddExecutor(ExecutorType.Activate, CardId.InfiniteImpermanence, DefaultInfiniteImpermanence); + AddExecutor(ExecutorType.Activate, CardId.BorreloadSavageDragon, BorreloadSavageDragonEffect); + AddExecutor(ExecutorType.Activate, CardId.BaronessDeFleur, BaronessDeFleurEffect); + AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, DefaultSolemnStrike); + + AddExecutor(ExecutorType.Activate, CardId.MaxxC, DefaultMaxxC); + AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster); + + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonColossus); + + AddExecutor(ExecutorType.Activate, CardId.DracobackTheDragonSteed, DracobackTheDragonSteedBounce); + + AddExecutor(ExecutorType.Activate, CardId.DestinyHeroDestroyPhoenixEnforcer, DestinyHeroDestroyPhoenixEnforcerEffect); + + AddExecutor(ExecutorType.Activate, CardId.RiteofAramesia, RiteofAramesiaEffect); + AddExecutor(ExecutorType.Activate, CardId.AquamancerOfTheSanctuary, AquamancerOfTheSanctuarySearchEffect); + AddExecutor(ExecutorType.Activate, CardId.JourneyOfDestiny, JourneyOfDestinyActivate); + AddExecutor(ExecutorType.Activate, CardId.WanderingGryphonRider, WanderingGryphonRiderSummon); + + AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialFirst); + + AddExecutor(ExecutorType.Summon, CardId.Sangan); + + AddExecutor(ExecutorType.Summon, CardId.MechaPhantomBeastOLion); + AddExecutor(ExecutorType.Activate, CardId.MechaPhantomBeastOLion, MechaPhantomBeastOLionEffect); + AddExecutor(ExecutorType.Summon, CardId.JetSynchron); + + AddExecutor(ExecutorType.Activate, CardId.JourneyOfDestiny, JourneyOfDestinyEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.SalamangreatAlmiraj, SalamangreatAlmirajSummonFirst); + + AddExecutor(ExecutorType.SpSummon, CardId.CrusadiaArboria, CrusadiaArboriaSummon); + + AddExecutor(ExecutorType.SpSummon, CardId.CrystronHalqifibrax, CrystronNeedlefiberSummon); + AddExecutor(ExecutorType.Activate, CardId.CrystronHalqifibrax, CrystronNeedlefiberEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.MechaPhantomBeastAuroradon, MechaPhantomBeastAuroradonSummon); + AddExecutor(ExecutorType.Activate, CardId.MechaPhantomBeastAuroradon, MechaPhantomBeastAuroradonEffect); + + AddExecutor(ExecutorType.Activate, CardId.AquamancerOfTheSanctuary, AquamancerOfTheSanctuarySummonEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.TGHyperLibrarian, TGHyperLibrarianSummon); + AddExecutor(ExecutorType.Activate, CardId.TGHyperLibrarian); + + AddExecutor(ExecutorType.SpSummon, CardId.CupidPitch, CupidPitchSummon); + AddExecutor(ExecutorType.Activate, CardId.CupidPitch, CupidPitchEffect); + + AddExecutor(ExecutorType.Activate, CardId.JetSynchron, JetSynchronEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.SalamangreatAlmiraj, SalamangreatAlmirajSummon); + AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider, LinkSpiderSummon); + + AddExecutor(ExecutorType.Activate, CardId.DracobackTheDragonSteed, DracobackTheDragonSteedEquip); + + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadSavageDragon, BorreloadSavageDragonSummon); + + AddExecutor(ExecutorType.Activate, CardId.NemesesCorridor); + AddExecutor(ExecutorType.SpSummon, CardId.ThunderDragonColossus); + + AddExecutor(ExecutorType.Summon, CardId.CrusadiaArboria, SummonForMaterial); + AddExecutor(ExecutorType.Summon, CardId.AshBlossomJoyousSpring, SummonForMaterial); + AddExecutor(ExecutorType.Summon, CardId.EffectVeiler, SummonForMaterial); + AddExecutor(ExecutorType.Summon, CardId.AquamancerOfTheSanctuary, SummonForMaterial); + AddExecutor(ExecutorType.Summon, CardId.MaxxC, SummonForMaterial); + + AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialEffect); + AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, MonsterRebornEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.BaronessDeFleur, BaronessDeFleurSummon); + AddExecutor(ExecutorType.SpSummon, CardId.VirtualWorldKyubiShenshen, VirtualWorldKyubiShenshenSummon); + AddExecutor(ExecutorType.Activate, CardId.VirtualWorldKyubiShenshen, VirtualWorldKyubiShenshenEffect); + AddExecutor(ExecutorType.SpSummon, CardId.CoralDragon); + AddExecutor(ExecutorType.Activate, CardId.CoralDragon, CoralDragonEffect); + AddExecutor(ExecutorType.Activate, CardId.TGWonderMagician, TGWonderMagicianEffect); + + AddExecutor(ExecutorType.Activate, CardId.FusionDestiny, FusionDestinyEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.PredaplantVerteAnaconda, PredaplantVerteAnacondaSummon); + AddExecutor(ExecutorType.Activate, CardId.PredaplantVerteAnaconda, PredaplantVerteAnacondaEffect); + + AddExecutor(ExecutorType.Summon, CardId.NemesesCorridor, SummonForMaterial); + AddExecutor(ExecutorType.Summon, CardId.DestinyHeroCelestial, SummonForMaterial); + + AddExecutor(ExecutorType.Activate, CardId.DestinyHeroDasher, DestinyHeroDasherEffect); + AddExecutor(ExecutorType.Activate, CardId.DestinyHeroCelestial, DestinyHeroCelestialEffect); + + AddExecutor(ExecutorType.Repos, MonsterRepos); + + AddExecutor(ExecutorType.SpellSet, CardId.InfiniteImpermanence, TrapSet); + AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike, TrapSet); + AddExecutor(ExecutorType.SpellSet, CardId.CrossoutDesignator, TrapSet); + + AddExecutor(ExecutorType.MonsterSet, CardId.Sangan); + AddExecutor(ExecutorType.SpellSet, SetForCelestial); + } + + private bool BeastOLionUsed = false; + private bool JetSynchronUsed = false; + private bool FusionDestinyUsed = false; + private bool BaronessDeFleurUsed = false; + private ClientCard PhoenixTarget = null; + private int PhoenixSelectingTarget = 0; + + public override bool OnSelectHand() + { + // go first + return true; + } + + public override void OnNewTurn() + { + BeastOLionUsed = false; + JetSynchronUsed = false; + FusionDestinyUsed = false; + PhoenixTarget = null; + PhoenixSelectingTarget = 0; + base.OnNewTurn(); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (cardData.Attack <= 1000) + return CardPosition.FaceUpDefence; + if (Util.IsTurn1OrMain2() && cardData.Attack <= 2500) + return CardPosition.FaceUpDefence; + } + return 0; + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (location == CardLocation.MonsterZone) + { + if (cardId == CardId.SalamangreatAlmiraj) + { + return available & Zones.ExtraMonsterZones; + } + if (cardId == CardId.TGHyperLibrarian && Bot.GetMonsterCount() >= 3) + { + return available & Zones.ExtraMonsterZones; + } + return available & Zones.MainMonsterZones & ~Bot.GetLinkedZones() & ~(Zones.z2 + Zones.z4); // preserve place for arboria + } + return 0; + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (hint != HintMsg.Destroy) + PhoenixSelectingTarget = 0; + + if (hint == HintMsg.AddToHand && max == 1) + { + foreach (ClientCard card in cards) + { + if (card.IsCode(CardId.CrusadiaArboria)) + return new List(new[] { card }); + if (card.IsCode(CardId.NemesesCorridor)) + return new List(new[] { card }); + } + foreach (ClientCard card in cards) + { + if (card.IsCode(CardId.MaxxC) && !Bot.HasInHand(CardId.MaxxC)) + return new List(new[] { card }); + if (card.IsCode(CardId.AshBlossomJoyousSpring) && !Bot.HasInHand(CardId.AshBlossomJoyousSpring)) + return new List(new[] { card }); + if (card.IsCode(CardId.EffectVeiler) && !Bot.HasInHand(CardId.EffectVeiler)) + return new List(new[] { card }); + } + } + if (hint == HintMsg.SpSummon && max == 1) + { + foreach (ClientCard card in cards) + { + if (card.IsCode(CardId.DestinyHeroDestroyPhoenixEnforcer)) + return new List(new[] { card }); + } + } + if (hint == HintMsg.Destroy && max == 1) + { + PhoenixSelectingTarget++; + if (PhoenixSelectingTarget >= 2 && !cards.Contains(PhoenixTarget)) + { + ClientCard target = Util.GetProblematicEnemyCard(); + if (target == null || !cards.Contains(target)) + target = Util.GetBestEnemyCard(); + if (target != null && cards.Contains(target)) + return new List(new[] { target }); + } + } + if (hint == HintMsg.LinkMaterial && cancelable && min == 0) + { + // TODO: not working + return new List(); + } + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + public override int OnSelectOption(IList options) + { + if (options.Count == 2 && options[0] == Util.GetStringId(CardId.CupidPitch, 1)) + return 0; + else return base.OnSelectOption(options); + } + + private IList GetHandCost() + { + List result = new List { }; + if (Bot.HasInMonstersZone(CardId.BraveToken)) + result.Add(CardId.DracobackTheDragonSteed); + if (Bot.Hand.Count(card => card.IsCode(CardId.FusionDestiny)) >= 2) + result.Add(CardId.FusionDestiny); + if (Bot.Hand.Count(card => card.IsCode(CardId.Sangan)) >= 2) + result.Add(CardId.Sangan); + if (Bot.Hand.Count(card => card.IsCode(CardId.RiteofAramesia)) >= 2) + result.Add(CardId.RiteofAramesia); + if (Bot.Hand.Count(card => card.IsCode(CardId.AquamancerOfTheSanctuary)) >= 2) + result.Add(CardId.AquamancerOfTheSanctuary); + if (Bot.HasInGraveyardOrInBanished(CardId.DestinyHeroCelestial) || !Bot.HasInExtra(CardId.DestinyHeroDestroyPhoenixEnforcer)) + result.Add(CardId.DestinyHeroDasher); + if (Bot.HasInGraveyardOrInBanished(CardId.DestinyHeroDasher) || !Bot.HasInExtra(CardId.DestinyHeroDestroyPhoenixEnforcer)) + result.Add(CardId.DestinyHeroCelestial); + if (Bot.Hand.Count(card => card.IsCode(CardId.AshBlossomJoyousSpring)) >= 2) + result.Add(CardId.AshBlossomJoyousSpring); + if (Bot.Hand.Count(card => card.IsCode(CardId.CrossoutDesignator)) >= 2) + result.Add(CardId.CrossoutDesignator); + if (Bot.HasInHand(result)) + return result; + result.AddRange(new int[]{ + CardId.HarpiesFeatherDuster, + CardId.MechaPhantomBeastOLion, + CardId.Sangan, + CardId.AshBlossomJoyousSpring, + CardId.MaxxC, + CardId.EffectVeiler, + CardId.CrossoutDesignator, + CardId.CalledByTheGrave, + CardId.RiteofAramesia, + CardId.AquamancerOfTheSanctuary, + CardId.InfiniteImpermanence, + CardId.SolemnStrike + }); + return result; + } + + private bool WanderingGryphonRiderCounter() + { + if (Card.Location == CardLocation.Hand) + return false; + return Duel.LastChainPlayer == 1; + } + + private bool CrossoutDesignatorEffect() + { + ClientCard LastChainCard = Util.GetLastChainCard(); + if (LastChainCard == null || Duel.LastChainPlayer != 1) return false; + return CrossoutDesignatorCheck(LastChainCard, CardId.AquamancerOfTheSanctuary, 3) + || CrossoutDesignatorCheck(LastChainCard, CardId.Sangan, 3) + || CrossoutDesignatorCheck(LastChainCard, CardId.AshBlossomJoyousSpring, 3) + || CrossoutDesignatorCheck(LastChainCard, CardId.MaxxC, 2) + || CrossoutDesignatorCheck(LastChainCard, CardId.EffectVeiler, 1) + || CrossoutDesignatorCheck(LastChainCard, CardId.RiteofAramesia, 3) + || CrossoutDesignatorCheck(LastChainCard, CardId.HarpiesFeatherDuster, 1) + || CrossoutDesignatorCheck(LastChainCard, CardId.FusionDestiny, 3) + || CrossoutDesignatorCheck(LastChainCard, CardId.FoolishBurial, 1) + || CrossoutDesignatorCheck(LastChainCard, CardId.MonsterReborn, 1) + || CrossoutDesignatorCheck(LastChainCard, CardId.CalledByTheGrave, 2) + || CrossoutDesignatorCheck(LastChainCard, CardId.CrossoutDesignator, 3) + || CrossoutDesignatorCheck(LastChainCard, CardId.InfiniteImpermanence, 3) + ; + } + + private bool CrossoutDesignatorCheck(ClientCard LastChainCard, int id, int count) + { + if (LastChainCard.IsCode(id) && Bot.GetRemainingCount(id, count) > 0) + { + AI.SelectAnnounceID(id); + return true; + } + return false; + } + + private bool DestinyHeroDestroyPhoenixEnforcerEffect() + { + if (Card.Location == CardLocation.Grave) + return true; + else + { + ClientCard target = Util.GetProblematicEnemyCard(2500); + if (target != null && !Util.ChainContainPlayer(0)) + { + AI.SelectCard(CardId.DestinyHeroDestroyPhoenixEnforcer); + AI.SelectNextCard(target); + return true; + } + target = Util.GetBestEnemyCard(); + if (target == null) + return false; + if (DefaultOnBecomeTarget() || Bot.UnderAttack || Duel.Phase == DuelPhase.End + || (Duel.Player == 0 && Util.IsTurn1OrMain2()) + || (Duel.Player == 1 && Enemy.GetMonsterCount() >= 2)) + { + PhoenixTarget = target; + AI.SelectCard(CardId.DestinyHeroDestroyPhoenixEnforcer); + AI.SelectNextCard(target); + return true; + } + return false; + } + } + + private bool DracobackTheDragonSteedBounce() + { + if (Card.Location != CardLocation.SpellZone) + return false; + ClientCard target = Util.GetProblematicEnemyCard(); + AI.SelectCard(target); + return true; + } + + private bool DracobackTheDragonSteedEquip() + { + if (Card.Location == CardLocation.SpellZone) + return false; + if (Card.Location == CardLocation.Grave) + return true; + if (Bot.HasInMonstersZone(CardId.BraveToken, faceUp: true)) + { + AI.SelectCard(CardId.BraveToken); + return true; + } + return false; + } + + private bool BorreloadSavageDragonSummon() + { + int[] materials = new[] { + CardId.CupidPitch, + + CardId.MechaPhantomBeastToken, + CardId.AquamancerOfTheSanctuary + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2) + { + AI.SelectMaterials(materials); + return true; + } + return false; + } + + private bool BorreloadSavageDragonEffect() + { + if (ActivateDescription == -1) + { + AI.SelectCard(new[] { CardId.MechaPhantomBeastAuroradon, CardId.CrystronHalqifibrax, CardId.PredaplantVerteAnaconda }); + return true; + } + else + { + return true; + } + } + + private bool RiteofAramesiaEffect() + { + AI.SelectYesNo(true); + return true; + } + + private bool WanderingGryphonRiderSummon() + { + if (Card.Location != CardLocation.Hand) + return false; + return Bot.HasInMonstersZone(CardId.BraveToken) || (Duel.Player == 0 && (Duel.LastChainPlayer == -1 || Bot.HasInSpellZone(CardId.JourneyOfDestiny))); + } + + private bool JourneyOfDestinyActivate() + { + return Card.Location == CardLocation.Hand; + } + + private bool JourneyOfDestinyEffect() + { + if (Card.Location == CardLocation.Hand) + return false; + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.JourneyOfDestiny, 1)) + { + // search equip to hand + AI.SelectOption(0); + return true; + } + else + { + // search rider or aquamancer + if (Bot.GetRemainingCount(CardId.WanderingGryphonRider, 1) == 0 || Bot.GetHandCount() == 0 || !Bot.HasInMonstersZone(CardId.BraveToken)) + { + AI.SelectCard(CardId.AquamancerOfTheSanctuary); + if (Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.AquamancerOfTheSanctuary)) + AI.SelectNextCard(CardId.AquamancerOfTheSanctuary); + else + AI.SelectNextCard(GetHandCost()); + } + else + { + AI.SelectCard(CardId.WanderingGryphonRider); + AI.SelectNextCard(GetHandCost()); + } + return true; + } + } + + private bool AquamancerOfTheSanctuarySearchEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Location == CardLocation.Grave) + { + AI.SelectCard(CardLocation.Deck); + return true; + } + if (ActivateDescription == Util.GetStringId(CardId.AquamancerOfTheSanctuary, 0)) + { + // summon + return false; + } + else + { + // search + return !Bot.HasInHand(CardId.RiteofAramesia) && !Bot.HasInMonstersZone(CardId.BraveToken); + } + } + + private bool AquamancerOfTheSanctuarySummonEffect() + { + if (ActivateDescription == Util.GetStringId(CardId.AquamancerOfTheSanctuary, 0)) + { + // summon + return Bot.GetMonsterCount() <= 3; + } + return false; + } + + private bool MechaPhantomBeastOLionEffect() + { + if (Bot.GetMonsterCount() >= 3 + && ((Bot.HasInExtra(CardId.MechaPhantomBeastAuroradon) && Bot.HasInMonstersZone(CardId.CrystronHalqifibrax)) + || Bot.HasInMonstersZone(CardId.MechaPhantomBeastAuroradon))) + return false; + if (ActivateDescription == -1) + { + BeastOLionUsed = true; + return true; + } + return !BeastOLionUsed; + } + + private bool CrusadiaArboriaSummon() + { + return !Bot.GetMonsters().Any(card => card.IsFaceup() && card.IsTuner()); + } + + private bool CrystronNeedlefiberSummon() + { + if (JetSynchronUsed && !Bot.HasInMonstersZone(CardId.MechaPhantomBeastOLion)) + return false; + List materials = new List{ + CardId.Sangan, + _CardId.GamecieltheSeaTurtleKaiju, + CardId.PredaplantVerteAnaconda, + CardId.SalamangreatAlmiraj, + CardId.LinkSpider, + CardId.MaxxC, + CardId.MechaPhantomBeastToken, + CardId.AquamancerOfTheSanctuary, + + CardId.CrusadiaArboria, + CardId.MechaPhantomBeastOLion, + CardId.JetSynchron, + CardId.AshBlossomJoyousSpring, + CardId.EffectVeiler + }; + if (!Bot.HasInMonstersZone(CardId.BraveToken) || !Bot.HasInMonstersZone(CardId.WanderingGryphonRider)) + { + materials.Add(CardId.BraveToken); + materials.Add(CardId.WanderingGryphonRider); + } + 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.JetSynchron, CardId.MechaPhantomBeastOLion, CardId.EffectVeiler); + return true; + } + else + { + if (Enemy.GetSpells().Any(card => card.IsFacedown() || card.HasType(CardType.Continuous) || card.HasType(CardType.Field) || card.HasType(CardType.Equip))) + { + AI.SelectCard(CardId.TGWonderMagician); + } + else + { + AI.SelectCard(CardId.CoralDragon); + } + return true; + } + } + + private bool TGWonderMagicianEffect() + { + ClientCard target = Util.GetProblematicEnemySpell(); + if (target == null) + target = Enemy.GetSpells().Find(card => card.IsFacedown() || card.HasType(CardType.Continuous) || card.HasType(CardType.Field) || card.HasType(CardType.Equip)); + if (target == null) + return false; + AI.SelectCard(target); + return true; + } + + private bool MechaPhantomBeastAuroradonSummon() + { + return Bot.GetMonsterCount() <= 4; // has 3 field for tokens + } + + private bool MechaPhantomBeastAuroradonEffect() + { + if (ActivateDescription == -1) + return true; + else + { + AI.SelectOption(1); // release 2 monsters + AI.SelectCard(CardId.MechaPhantomBeastAuroradon); + AI.SelectNextCard(CardId.MechaPhantomBeastToken); + return true; + } + } + + private bool TGHyperLibrarianSummon() + { + int[] materials = new[] { + CardId.MechaPhantomBeastOLion, + + CardId.MechaPhantomBeastToken, + CardId.AquamancerOfTheSanctuary + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 3) + { + AI.SelectMaterials(materials); + return true; + } + return false; + } + + private bool JetSynchronEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + int[] materials = new[] { + CardId.MechaPhantomBeastToken + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2 || Bot.GetMonsterCount() <= 3) + { + JetSynchronUsed = true; + AI.SelectCard(GetHandCost()); + return true; + } + return false; + } + + private bool CupidPitchSummon() + { + int[] materials = new[] { + CardId.JetSynchron, + CardId.EffectVeiler, + + CardId.MechaPhantomBeastToken, + CardId.AquamancerOfTheSanctuary, + + CardId.Sangan, + CardId.TGHyperLibrarian, + CardId.BraveToken + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 3) + { + AI.SelectMaterials(materials); + return true; + } + return false; + } + + private bool CupidPitchEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + AI.SelectOption(1); // level up + } + else + { + AI.SelectCard(CardId.NemesesCorridor); + } + return true; + } + + private bool SalamangreatAlmirajSummonFirst() + { + int[] materials = new[] { + CardId.Sangan + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials) && !card.IsSpecialSummoned) == 0) + return false; + AI.SelectMaterials(materials); + return true; + } + + private bool SalamangreatAlmirajSummon() + { + if (PhoenixNotAvail()) + return false; + int[] materials = new[] { + CardId.MechaPhantomBeastOLion, + CardId.JetSynchron + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials) && !card.IsSpecialSummoned) == 0) + return false; + AI.SelectMaterials(materials); + return true; + } + + private bool LinkSpiderSummon() + { + if (PhoenixNotAvail()) + return false; + List materials = new List{ + CardId.MechaPhantomBeastToken + }; + if (!Bot.HasInMonstersZone(CardId.BraveToken) || !Bot.HasInMonstersZone(CardId.WanderingGryphonRider)) + { + materials.Add(CardId.BraveToken); + } + if (Bot.GetMonsters().Any(card => card.IsCode(CardId.PrimalBeingToken) && card.Attack <= 4000)) + { + materials.Add(CardId.PrimalBeingToken); + } + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) == 0) + return false; + AI.SelectMaterials(materials); + return true; + } + + private bool NeedMonster() + { + if (Bot.HasInMonstersZone(CardId.PredaplantVerteAnaconda, true) || PhoenixNotAvail()) + 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 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; + return false; + } + + private bool PhoenixNotAvail() + { + return Bot.LifePoints <= 2000 || Bot.GetRemainingCount(CardId.FusionDestiny, 3) == 0 || Bot.HasInHand(CardId.FusionDestiny) + || !Bot.HasInExtra(CardId.PredaplantVerteAnaconda) || !Bot.HasInExtra(CardId.DestinyHeroDestroyPhoenixEnforcer) + || (Bot.GetRemainingCount(CardId.DestinyHeroCelestial, 1) == 0 && !Bot.HasInHand(CardId.DestinyHeroCelestial)) + || (Bot.GetRemainingCount(CardId.DestinyHeroDasher, 1) == 0 && !Bot.HasInHand(CardId.DestinyHeroDasher)); + } + + private bool PredaplantVerteAnacondaSummon() + { + if (PhoenixNotAvail()) + return false; + + List materials = new List{ + _CardId.GamecieltheSeaTurtleKaiju, + CardId.AquamancerOfTheSanctuary, + CardId.Sangan, + CardId.SalamangreatAlmiraj, + CardId.LinkSpider, + CardId.NemesesCorridor, + CardId.DestinyHeroCelestial, + CardId.DestinyHeroDasher, + CardId.CrusadiaArboria, + CardId.AshBlossomJoyousSpring, + CardId.MechaPhantomBeastOLion, + CardId.MaxxC, + CardId.JetSynchron, + CardId.EffectVeiler, + CardId.CrystronHalqifibrax, + CardId.TGHyperLibrarian + }; + if (!Bot.HasInMonstersZone(CardId.BraveToken) || !Bot.HasInMonstersZone(CardId.WanderingGryphonRider)) + { + materials.Add(CardId.WanderingGryphonRider); + } + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2) + { + AI.SelectMaterials(materials); + return true; + } + return false; + } + + private bool PredaplantVerteAnacondaEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (ActivateDescription == Util.GetStringId(CardId.PredaplantVerteAnaconda, 0)) + return false; + FusionDestinyUsed = true; + AI.SelectCard(CardId.FusionDestiny); + AI.SelectMaterials(CardLocation.Deck); + return true; + } + + private bool FusionDestinyEffect() + { + FusionDestinyUsed = true; + return true; + } + + private bool FoolishBurialFirst() + { + if (!Bot.HasInHand(CardId.RiteofAramesia) && !Bot.HasInHandOrInGraveyard(CardId.AquamancerOfTheSanctuary) && !Bot.HasInMonstersZone(CardId.BraveToken)) + { + AI.SelectCard(CardId.AquamancerOfTheSanctuary); + return true; + } + return false; + } + + private bool FoolishBurialEffect() + { + if (FusionDestinyUsed) + return false; + + if (!NeedMonster()) + return false; + + AI.SelectCard(new[] { + CardId.MechaPhantomBeastOLion + }); + return true; + } + + private bool MonsterRebornEffect() + { + if (Bot.HasInGraveyard(CardId.BaronessDeFleur)) + { + AI.SelectCard(CardId.BaronessDeFleur); + return true; + } + else if (Bot.HasInGraveyard(CardId.WanderingGryphonRider)) + { + AI.SelectCard(CardId.WanderingGryphonRider); + return true; + } + else + { + if (!NeedMonster()) + return false; + + AI.SelectCard(new[] { + CardId.Sangan, + CardId.MechaPhantomBeastOLion, + CardId.CrusadiaArboria, + CardId.AshBlossomJoyousSpring + }); + return true; + } + } + + private bool DestinyHeroDasherEffect() + { + return Bot.Hand.Count(card => card.IsMonster()) > 1; + } + + private bool DestinyHeroCelestialEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (!Bot.HasInGraveyard(CardId.DestinyHeroDasher)) + return false; + AI.SelectCard(CardId.DestinyHeroDasher); + return true; + } + + private bool BaronessDeFleurSummon() + { + int[] materials = new[] { + CardId.CupidPitch, + CardId.TGWonderMagician, + + CardId.TGHyperLibrarian + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2) + { + AI.SelectMaterials(materials); + return true; + } + if (!Bot.HasInMonstersZone(CardId.BraveToken)) + { + materials = new[] { + CardId.AshBlossomJoyousSpring, + CardId.CrusadiaArboria, + + CardId.WanderingGryphonRider + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2) + { + AI.SelectMaterials(materials); + return true; + } + } + if (!Bot.HasInMonstersZone(CardId.WanderingGryphonRider) || Bot.HasInHand(CardId.RiteofAramesia)) + { + materials = new[] { + CardId.CoralDragon, + + CardId.BraveToken + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2) + { + AI.SelectMaterials(materials); + return true; + } + } + return false; + } + + private bool BaronessDeFleurEffect() + { + if (Duel.LastChainPlayer == 0) + { + return false; + } + if (Duel.LastChainPlayer == 1) + { + BaronessDeFleurUsed = true; + return true; + } + if (Duel.Phase == DuelPhase.Standby && BaronessDeFleurUsed) + { + BaronessDeFleurUsed = false; + return true; + } + if (Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2) + { + ClientCard target = Util.GetProblematicEnemyCard(canBeTarget: true); + if (target == null) + target = Util.GetBestEnemyCard(canBeTarget: true); + if (target != null) + { + AI.SelectCard(target); + return true; + } + } + return false; + } + + private bool VirtualWorldKyubiShenshenSummon() + { + if (Bot.HasInMonstersZone(CardId.DestinyHeroDestroyPhoenixEnforcer)) + return false; + + int[] materials = new[] { + CardId.CoralDragon, + + CardId.AquamancerOfTheSanctuary, + CardId.Sangan + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2) + { + AI.SelectMaterials(materials); + return true; + } + if (!Bot.HasInMonstersZone(CardId.BraveToken)) + { + materials = new[] { + CardId.MechaPhantomBeastOLion, + + CardId.WanderingGryphonRider + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2) + { + AI.SelectMaterials(materials); + return true; + } + } + return false; + } + + private bool VirtualWorldKyubiShenshenEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Location == CardLocation.MonsterZone && Bot.HasInBanished(CardId.AquamancerOfTheSanctuary)) + { + AI.SelectCard(CardId.AquamancerOfTheSanctuary); + return true; + } + else + { + int[] costs = new[] { + CardId.NemesesCorridor, + CardId.Sangan, + CardId.CrusadiaArboria, + CardId.AshBlossomJoyousSpring, + CardId.MechaPhantomBeastOLion, + CardId.MaxxC, + CardId.EffectVeiler, + CardId.ThunderDragonColossus, + CardId.BorreloadSavageDragon, + CardId.CoralDragon, + CardId.TGHyperLibrarian, + CardId.TGWonderMagician, + CardId.CupidPitch, + CardId.CrystronHalqifibrax, + CardId.PredaplantVerteAnaconda, + CardId.LinkSpider, + CardId.SalamangreatAlmiraj + }; + AI.SelectCard(costs); + AI.SelectNextCard(costs); + return true; + } + } + + private bool CoralDragonEffect() + { + if (Card.Location == CardLocation.Grave) + return true; + ClientCard target = Util.GetProblematicEnemyCard(canBeTarget: true); + if (target != null) + { + AI.SelectCard(target); + return true; + } + return false; + } + + private bool TrapSet() + { + AI.SelectPlace(Zones.z0 + Zones.z1 + Zones.z3 + Zones.z4); + return true; + } + + private bool SetForCelestial() + { + return !FusionDestinyUsed && Bot.HasInGraveyard(CardId.DestinyHeroCelestial) && Bot.HasInGraveyard(CardId.DestinyHeroDasher) && TrapSet(); + } + + private bool MonsterRepos() + { + if (Card.IsFacedown()) + return true; + return DefaultMonsterRepos(); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BurnExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BurnExecutor.cs new file mode 100644 index 0000000..6e4cdaf --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/BurnExecutor.cs @@ -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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ChainBurnExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ChainBurnExecutor.cs new file mode 100644 index 0000000..3d10626 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ChainBurnExecutor.cs @@ -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 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 trap = Bot.GetSpells(); + IList 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 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 list = new List(); + 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 newlist = new List(); + 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 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); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/CyberDragonExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/CyberDragonExecutor.cs new file mode 100644 index 0000000..cd1c0ea --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/CyberDragonExecutor.cs @@ -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 SelectedCard = new List(); + 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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DarkMagicianExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DarkMagicianExecutor.cs new file mode 100644 index 0000000..0e988e4 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DarkMagicianExecutor.cs @@ -0,0 +1,1865 @@ +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; + +namespace WindBot.Game.AI.Decks +{ + [Deck("DarkMagician", "AI_DarkMagician")] + public class DarkMagicianExecutor : DefaultExecutor + { + public class CardId + { + public const int DarkMagician = 46986414; + public const int GrinderGolem = 75732622; + public const int MagicianOfLllusion = 35191415; + public const int ApprenticeLllusionMagician = 30603688; + public const int WindwitchGlassBell = 71007216; + public const int MagiciansRod = 7084129; + public const int WindwitchIceBell = 43722862; + public const int AshBlossom = 14558127; + public const int SpellbookMagicianOfProphecy = 14824019; + public const int MaxxC = 23434538; + public const int WindwitchSnowBell = 70117860; + + public const int TheEyeOfTimaeus = 1784686; + public const int DarkMagicAttack = 2314238; + public const int SpellbookOfKnowledge = 23314220; + public const int UpstartGoblin = 70368879; + public const int SpellbookOfSecrets = 89739383; + public const int DarkMagicInheritance = 41735184; + public const int LllusionMagic = 73616671; + //public const int Scapegoat = 73915051; + public const int DarkMagicalCircle = 47222536; + public const int WonderWand = 67775894; + public const int MagicianNavigation = 7922915; + public const int EternalSoul = 48680970; + public const int SolemnStrike = 40605147; + + public const int DarkMagicianTheDragonKnight = 41721210; + public const int CrystalWingSynchroDragon = 50954680; + public const int OddEyesWingDragon = 58074177; + public const int ClearWingFastDragon = 90036274; + public const int WindwitchWinterBell = 14577226; + public const int OddEyesAbsoluteDragon = 16691074; + public const int Dracossack = 22110647; + public const int BigEye = 80117527; + public const int TroymarePhoenix = 2857636; + public const int TroymareCerberus = 75452921; + public const int ApprenticeWitchling = 71384012; + public const int VentriloauistsClaraAndLucika = 1482001; + /*public const int EbonLllusionMagician = 96471335; + public const int BorreloadDragon = 31833038; + public const int SaryujaSkullDread = 74997493; + public const int Hidaruma = 64514892; + public const int AkashicMagician = 28776350; + public const int SecurityDragon = 99111753; + public const int LinkSpider = 98978921; + public const int Linkuriboh = 41999284;*/ + + public const int HarpiesFeatherDuster = 18144506; + public const int ElShaddollWinda = 94977269; + public const int DarkHole = 53129443; + public const int Ultimate = 86221741; + public const int LockBird = 94145021; + public const int Ghost = 59438930; + public const int GiantRex = 80280944; + public const int UltimateConductorTytanno = 18940556; + public const int SummonSorceress = 61665245; + public const int CrystronNeedlefiber = 50588353; + public const int FirewallDragon = 5043010; + public const int JackKnightOfTheLavenderDust = 28692962; + public const int JackKnightOfTheCobaltDepths = 92204263; + public const int JackKnightOfTheCrimsonLotus = 56809158; + public const int JackKnightOfTheGoldenBlossom = 29415459; + public const int JackKnightOfTheVerdantGale = 66022706; + public const int JackKnightOfTheAmberShade = 93020401; + public const int JackKnightOfTheAzureSky = 20537097; + public const int MekkKnightMorningStar = 72006609; + public const int JackKnightOfTheWorldScar = 38502358; + public const int WhisperOfTheWorldLegacy = 62530723; + public const int TrueDepthsOfTheWorldLegacy = 98935722; + public const int KeyToTheWorldLegacy = 2930675; + } + + public DarkMagicianExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + //counter + AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, SolemnStrikeeff); + AddExecutor(ExecutorType.Activate, CardId.AshBlossom, ChainEnemy); + AddExecutor(ExecutorType.Activate, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragoneff); + AddExecutor(ExecutorType.Activate, CardId.MaxxC, MaxxCeff); + //AddExecutor(ExecutorType.Activate, CardId.Scapegoat,Scapegoateff); + //first do + AddExecutor(ExecutorType.Activate, CardId.UpstartGoblin, UpstartGoblineff); + AddExecutor(ExecutorType.Activate, CardId.DarkMagicalCircle, DarkMagicalCircleeff); + AddExecutor(ExecutorType.Activate, CardId.SpellbookOfSecrets, SpellbookOfSecreteff); + AddExecutor(ExecutorType.Activate, CardId.DarkMagicInheritance, DarkMagicInheritanceeff); + AddExecutor(ExecutorType.Activate, CardId.DarkMagicAttack, DarkMagicAttackeff); + //trap set + AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike); + AddExecutor(ExecutorType.SpellSet, CardId.MagicianNavigation, MagicianNavigationset); + AddExecutor(ExecutorType.SpellSet, CardId.EternalSoul, EternalSoulset); + /*AddExecutor(ExecutorType.SpellSet, CardId.Scapegoat, Scapegoatset); + //sheep + AddExecutor(ExecutorType.SpSummon, CardId.Hidaruma, Hidarumasp); + AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp); + AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, Linkuriboheff); + AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider, Linkuribohsp); + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadDragon, BorreloadDragonsp); + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadDragon, BorreloadDragoneff);*/ + //plan A + AddExecutor(ExecutorType.Activate, CardId.WindwitchIceBell, WindwitchIceBelleff); + AddExecutor(ExecutorType.Activate, CardId.WindwitchGlassBell, WindwitchGlassBelleff); + AddExecutor(ExecutorType.Activate, CardId.WindwitchSnowBell, WindwitchSnowBellsp); + AddExecutor(ExecutorType.SpSummon, CardId.WindwitchWinterBell, WindwitchWinterBellsp); + AddExecutor(ExecutorType.Activate, CardId.WindwitchWinterBell, WindwitchWinterBelleff); + + AddExecutor(ExecutorType.SpSummon, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragonsp); + // if fail + AddExecutor(ExecutorType.SpSummon, CardId.ClearWingFastDragon, ClearWingFastDragonsp); + AddExecutor(ExecutorType.Activate, CardId.ClearWingFastDragon, ClearWingFastDragoneff); + // plan B + //AddExecutor(ExecutorType.Activate, CardId.GrinderGolem, GrinderGolemeff); + // AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, Linkuribohsp); + //AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider, LinkSpidersp); + //AddExecutor(ExecutorType.SpSummon, CardId.AkashicMagician); + //plan C + AddExecutor(ExecutorType.SpSummon, CardId.OddEyesAbsoluteDragon, OddEyesAbsoluteDragonsp); + AddExecutor(ExecutorType.Activate, CardId.OddEyesAbsoluteDragon, OddEyesAbsoluteDragoneff); + AddExecutor(ExecutorType.Activate, CardId.OddEyesWingDragon); + //summon + AddExecutor(ExecutorType.Summon, CardId.WindwitchGlassBell, WindwitchGlassBellsummonfirst); + AddExecutor(ExecutorType.Summon, CardId.SpellbookMagicianOfProphecy, SpellbookMagicianOfProphecysummon); + AddExecutor(ExecutorType.Activate, CardId.SpellbookMagicianOfProphecy, SpellbookMagicianOfProphecyeff); + AddExecutor(ExecutorType.Summon, CardId.MagiciansRod, MagiciansRodsummon); + AddExecutor(ExecutorType.Activate, CardId.MagiciansRod, MagiciansRodeff); + AddExecutor(ExecutorType.Summon, CardId.WindwitchGlassBell, WindwitchGlassBellsummon); + //activate + AddExecutor(ExecutorType.Activate, CardId.LllusionMagic, LllusionMagiceff); + AddExecutor(ExecutorType.SpellSet, CardId.LllusionMagic, LllusionMagicset); + AddExecutor(ExecutorType.Activate, CardId.SpellbookOfKnowledge, SpellbookOfKnowledgeeff); + AddExecutor(ExecutorType.Activate, CardId.WonderWand, WonderWandeff); + AddExecutor(ExecutorType.Activate, CardId.TheEyeOfTimaeus, TheEyeOfTimaeuseff); + AddExecutor(ExecutorType.SpSummon, CardId.ApprenticeLllusionMagician, ApprenticeLllusionMagiciansp); + AddExecutor(ExecutorType.Activate, CardId.ApprenticeLllusionMagician, ApprenticeLllusionMagicianeff); + //other thing + AddExecutor(ExecutorType.Activate, CardId.MagicianOfLllusion); + AddExecutor(ExecutorType.Activate, CardId.MagicianNavigation, MagicianNavigationeff); + AddExecutor(ExecutorType.Activate, CardId.EternalSoul, EternalSouleff); + AddExecutor(ExecutorType.SpSummon, CardId.BigEye, BigEyesp); + AddExecutor(ExecutorType.Activate, CardId.BigEye, BigEyeeff); + AddExecutor(ExecutorType.SpSummon, CardId.Dracossack, Dracossacksp); + AddExecutor(ExecutorType.Activate, CardId.Dracossack, Dracossackeff); + AddExecutor(ExecutorType.SpSummon, CardId.ApprenticeWitchling, ApprenticeWitchlingsp); + AddExecutor(ExecutorType.Activate, CardId.ApprenticeWitchling, ApprenticeWitchlingeff); + AddExecutor(ExecutorType.SpSummon, CardId.VentriloauistsClaraAndLucika, VentriloauistsClaraAndLucikasp); + AddExecutor(ExecutorType.Repos, MonsterRepos); + } + private void EternalSoulSelect() + { + AI.SelectPosition(CardPosition.FaceUpAttack); + /* + if (Enemy.HasInMonstersZone(CardId.MekkKnightMorningStar)) + { + int MekkKnightZone = 0; + int BotZone = 0; + for (int i = 0; i <= 6; i++) + { + if (Enemy.MonsterZone[i] != null && Enemy.MonsterZone[i].IsCode(CardId.MekkKnightMorningStar)) + { + MekkKnightZone = i; + break; + } + } + if (Bot.MonsterZone[GetReverseColumnMainZone(MekkKnightZone)] == null) + { + BotZone = GetReverseColumnMainZone(MekkKnightZone); + AI.SelectPlace(ReverseZoneTo16bit(BotZone)); + } + else + { + for (int i = 0; i <= 6; i++) + { + if (!NoJackKnightColumn(i)) + { + if (Bot.MonsterZone[GetReverseColumnMainZone(i)] == null) + { + AI.SelectPlace(ReverseZoneTo16bit(GetReverseColumnMainZone(i))); + break; + } + } + } + } + Logger.DebugWriteLine("******************MekkKnightMorningStar"); + } + else + { + for (int i = 0; i <= 6; i++) + { + if (!NoJackKnightColumn(i)) + { + if (Bot.MonsterZone[GetReverseColumnMainZone(i)] == null) + { + AI.SelectPlace(ReverseZoneTo16bit(GetReverseColumnMainZone(i))); + break; + } + } + } + } + */ + } + int attackerzone = -1; + int defenderzone = -1; + bool Secret_used = false; + bool plan_A = false; + bool plan_C = false; + int maxxc_done = 0; + int lockbird_done = 0; + int ghost_done = 0; + bool maxxc_used = false; + bool lockbird_used = false; + bool ghost_used = false; + bool WindwitchGlassBelleff_used = false; + int ApprenticeLllusionMagician_count = 0; + bool Spellbook_summon = false; + bool Rod_summon = false; + bool GlassBell_summon = false; + bool magician_sp = false; + bool soul_used = false; + bool big_attack = false; + bool big_attack_used = false; + bool CrystalWingSynchroDragon_used = false; + public override void OnNewPhase() + { + //Util.UpdateLinkedZone(); + //Logger.DebugWriteLine("Zones.CheckLinkedPointZones= " + Zones.CheckLinkedPointZones); + //Logger.DebugWriteLine("Zones.CheckMutualEnemyZoneCount= " + Zones.CheckMutualEnemyZoneCount); + plan_C = false; + ApprenticeLllusionMagician_count = 0; + foreach (ClientCard count in Bot.GetMonsters()) + { + if (count.IsCode(CardId.ApprenticeLllusionMagician) && count.IsFaceup()) + ApprenticeLllusionMagician_count++; + } + foreach (ClientCard dangerous in Enemy.GetMonsters()) + { + if (dangerous != null && dangerous.IsShouldNotBeTarget() && dangerous.Attack > 2500 && + !Bot.HasInHandOrHasInMonstersZone(CardId.ApprenticeLllusionMagician)) + { + plan_C = true; + Logger.DebugWriteLine("*********dangerous = " + dangerous.Id); + } + } + if (Bot.HasInHand(CardId.SpellbookMagicianOfProphecy) && + Bot.HasInHand(CardId.MagiciansRod) && + Bot.HasInHand(CardId.WindwitchGlassBell)) + { + if (Bot.HasInHand(CardId.SpellbookOfKnowledge) || + Bot.HasInHand(CardId.WonderWand)) + Rod_summon = true; + else + Spellbook_summon = true; + } + else if + (Bot.HasInHand(CardId.SpellbookMagicianOfProphecy) && + Bot.HasInHand(CardId.MagiciansRod)) + { + if (Bot.HasInSpellZone(CardId.EternalSoul) && + !(Bot.HasInHand(CardId.DarkMagician) || Bot.HasInHand(CardId.DarkMagician))) + Rod_summon = true; + else if (Bot.HasInHand(CardId.SpellbookOfKnowledge) || + Bot.HasInHand(CardId.WonderWand)) + Rod_summon = true; + else + Spellbook_summon = true; + } + else if + (Bot.HasInHand(CardId.SpellbookMagicianOfProphecy) && + Bot.HasInHand(CardId.WindwitchGlassBell)) + { + if (plan_A) + Rod_summon = true; + else + GlassBell_summon = true; + } + else if + (Bot.HasInHand(CardId.MagiciansRod) && + Bot.HasInHand(CardId.WindwitchGlassBell)) + { + if (plan_A) + Rod_summon = true; + else + GlassBell_summon = true; + } + else + { + Spellbook_summon = true; + Rod_summon = true; + GlassBell_summon = true; + } + } + public override void OnNewTurn() + { + CrystalWingSynchroDragon_used = false; + Secret_used = false; + maxxc_used = false; + lockbird_used = false; + ghost_used = false; + WindwitchGlassBelleff_used = false; + Spellbook_summon = false; + Rod_summon = false; + GlassBell_summon = false; + magician_sp = false; + big_attack = false; + big_attack_used = false; + soul_used = false; + base.OnNewTurn(); + } + public int GetTotalATK(IList list) + { + + int atk = 0; + foreach (ClientCard c in list) + { + if (c == null) continue; + atk += c.Attack; + } + return atk; + } + + private bool WindwitchIceBelleff() + { + if (lockbird_used) return false; + if (Enemy.HasInMonstersZone(CardId.ElShaddollWinda)) return false; + if (maxxc_used) return false; + if (WindwitchGlassBelleff_used) return false; + //AI.SelectPlace(Zones.z2, 1); + if (Bot.GetRemainingCount(CardId.WindwitchGlassBell, 2) >= 1) + AI.SelectCard(CardId.WindwitchGlassBell); + else if (Bot.HasInHand(CardId.WindwitchGlassBell)) + AI.SelectCard(CardId.WindwitchSnowBell); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + + private bool WindwitchGlassBelleff() + { + if (Bot.HasInMonstersZone(CardId.WindwitchIceBell)) + { + int ghost_count = 0; + foreach (ClientCard check in Enemy.Graveyard) + { + if (check.IsCode(CardId.Ghost)) + ghost_count++; + } + if (ghost_count != ghost_done) + AI.SelectCard(CardId.WindwitchIceBell); + else + AI.SelectCard(CardId.WindwitchSnowBell); + } + else + AI.SelectCard(CardId.WindwitchIceBell); + WindwitchGlassBelleff_used = true; + return true; + } + + private bool WindwitchSnowBellsp() + { + if (maxxc_used) return false; + if (Bot.HasInMonstersZone(CardId.WindwitchIceBell) && + Bot.HasInMonstersZone(CardId.WindwitchGlassBell)) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + return false; + } + + private bool WindwitchWinterBellsp() + { + if (maxxc_used) return false; + if (Bot.HasInMonstersZone(CardId.WindwitchIceBell) && + Bot.HasInMonstersZone(CardId.WindwitchGlassBell) && + Bot.HasInMonstersZone(CardId.WindwitchSnowBell)) + { + //AI.SelectPlace(Zones.z5, Zones.ExtraMonsterZones); + AI.SelectCard(CardId.WindwitchIceBell, CardId.WindwitchGlassBell); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + + return false; + } + + private bool WindwitchWinterBelleff() + { + AI.SelectCard(CardId.WindwitchGlassBell); + return true; + } + + private bool ClearWingFastDragonsp() + { + if (Bot.HasInMonstersZone(CardId.WindwitchIceBell) && + Bot.HasInMonstersZone(CardId.WindwitchGlassBell)) + { + + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + + return false; + } + + private bool ClearWingFastDragoneff() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (Duel.Player == 1) + return DefaultTrap(); + return true; + } + return false; + } + private bool CrystalWingSynchroDragonsp() + { + if (Bot.HasInMonstersZone(CardId.WindwitchSnowBell) && Bot.HasInMonstersZone(CardId.WindwitchWinterBell)) + { + //AI.SelectPlace(Zones.z5, Zones.ExtraMonsterZones); + plan_A = true; + return true; + } + return false; + } + + /* private bool GrinderGolemeff() + { + + if (plan_A) return false; + AI.SelectPosition(CardPosition.FaceUpDefence); + if (Bot.GetMonstersExtraZoneCount() == 0) + return true; + if (Bot.HasInMonstersZone(CardId.AkashicMagician) || + Bot.HasInMonstersZone(CardId.SecurityDragon)) + return true; + return false; + }*/ + + /* private bool Linkuribohsp() + { + if (Bot.HasInMonstersZone(CardId.GrinderGolem + 1)) + { + AI.SelectCard(CardId.GrinderGolem + 1); + return true; + } + return false; + } + + private bool LinkSpidersp() + { + if(Bot.HasInMonstersZone(CardId.GrinderGolem+1)) + { + AI.SelectCard(CardId.GrinderGolem + 1); + return true; + } + return false; + }*/ + + private bool OddEyesAbsoluteDragonsp() + { + if (plan_C) + { + return true; + } + return false; + } + + private bool OddEyesAbsoluteDragoneff() + { + Logger.DebugWriteLine("OddEyesAbsoluteDragonef 1"); + if (Card.Location == CardLocation.MonsterZone/*ActivateDescription == Util.GetStringId(CardId.OddEyesAbsoluteDragon, 0)*/) + { + Logger.DebugWriteLine("OddEyesAbsoluteDragonef 2"); + return Duel.Player == 1; + } + else if (Card.Location == CardLocation.Grave/*ActivateDescription == Util.GetStringId(CardId.OddEyesAbsoluteDragon, 0)*/) + { + Logger.DebugWriteLine("OddEyesAbsoluteDragonef 3"); + AI.SelectCard(CardId.OddEyesWingDragon); + return true; + } + return false; + } + + private bool SolemnStrikeeff() + { + if (Bot.LifePoints > 1500 && Duel.LastChainPlayer == 1) + return true; + if (DefaultOnlyHorusSpSummoning()) return false; + return false; + } + + private bool ChainEnemy() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Util.GetLastChainCard() != null && + Util.GetLastChainCard().IsCode(CardId.UpstartGoblin)) + return false; + return Duel.LastChainPlayer == 1; + } + + private bool CrystalWingSynchroDragoneff() + { + if (Duel.LastChainPlayer == 1) + { + CrystalWingSynchroDragon_used = true; + return true; + } + return false; + } + + private bool MaxxCeff() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return Duel.Player == 1; + } + /* + private bool Scapegoatset() + { + if (Bot.HasInSpellZone(CardId.Scapegoat)) return false; + return (Bot.GetMonsterCount() - Bot.GetMonstersExtraZoneCount()) < 2; + } + + public bool Scapegoateff() + { + if (Duel.Player == 0) return false; + if (DefaultOnBecomeTarget() && !Enemy.HasInMonstersZone(CardId.UltimateConductorTytanno)) + { + Logger.DebugWriteLine("*************************sheepeff"); + return true; + } + if (Bot.HasInMonstersZone(CardId.CrystalWingSynchroDragon)) return false; + if(Duel.Phase == DuelPhase.End) + { + Logger.DebugWriteLine("*************************sheepeff"); + return true; + } + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + + int total_atk = 0; + List enemy_monster = Enemy.GetMonsters(); + foreach (ClientCard m in enemy_monster) + { + if (m.IsAttack() && !m.Attacked) total_atk += m.Attack; + } + if (total_atk >= Bot.LifePoints && !Enemy.HasInMonstersZone(CardId.UltimateConductorTytanno)) return true; + } + return false; + } + + private bool Hidarumasp() + { + if (!Bot.HasInMonstersZone(CardId.Scapegoat + 1)) return false; + if(Bot.MonsterZone[5]==null) + { + AI.SelectCard(new[] { CardId.Scapegoat + 1, CardId.Scapegoat + 1 }); + return true; + } + if (Bot.MonsterZone[6] == null) + { + AI.SelectCard(new[] { CardId.Scapegoat + 1, CardId.Scapegoat + 1 }); + return true; + } + return false; + + } + + private bool Linkuribohsp() + { + foreach (ClientCard c in Bot.GetMonsters()) + { + if (!c.IsCode(CardId.WindwitchSnowBell) && c.Level == 1 && !c.IsCode(CardId.LinkSpider) && !c.IsCode(CardId.Linkuriboh)) + { + AI.SelectCard(c); + return true; + } + } + return false; + } + + + private bool Linkuriboheff() + { + if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.Linkuriboh)) return false; + if (Bot.HasInMonstersZone(CardId.WindwitchSnowBell)) return false; + return true; + } + private bool BorreloadDragonsp() + { + if(Bot.HasInMonstersZone(CardId.Hidaruma)&& + Bot.HasInMonstersZone(CardId.Linkuriboh)) + { + AI.SelectCard(new[] { CardId.Hidaruma, CardId.Linkuriboh, CardId.LinkSpider ,CardId.Linkuriboh}); + return true; + } + + return false; + } + + + private bool BorreloadDragoneff() + { + if (ActivateDescription == -1) + { + ClientCard enemy_monster = Enemy.BattlingMonster; + if (enemy_monster != null && enemy_monster.HasPosition(CardPosition.Attack)) + { + return enemy_monster.Attack > 2000; + } + return true; + }; + ClientCard BestEnemy = Util.GetBestEnemyMonster(true,true); + if (BestEnemy == null || BestEnemy.HasPosition(CardPosition.FaceDown)) return false; + AI.SelectCard(BestEnemy); + return true; + }*/ + private bool EternalSoulset() + { + if (Bot.GetHandCount() > 6) return true; + if (!Bot.HasInSpellZone(CardId.EternalSoul)) + return true; + return false; + } + + private bool EternalSouleff() + { + IList grave = Bot.Graveyard; + IList magician = new List(); + foreach (ClientCard check in grave) + { + if (check.IsCode(CardId.DarkMagician)) + { + magician.Add(check); + } + } + if (Util.IsChainTarget(Card) && Bot.GetMonsterCount() == 0) + { + AI.SelectYesNo(false); + return true; + } + if (Util.ChainCountPlayer(0) > 0) return false; + + if (Enemy.HasInSpellZone(CardId.HarpiesFeatherDuster) && Card.IsFacedown()) + return false; + + foreach (ClientCard target in Duel.ChainTargets) + { + if ((target.IsCode(CardId.DarkMagician, CardId.DarkMagicianTheDragonKnight)) + && Card.IsFacedown()) + { + AI.SelectYesNo(false); + return true; + } + } + + if (Enemy.HasInSpellZone(CardId.DarkHole) && Card.IsFacedown() && + (Bot.HasInMonstersZone(CardId.DarkMagician) || Bot.HasInMonstersZone(CardId.DarkMagicianTheDragonKnight))) + { + AI.SelectYesNo(false); + return true; + } + if (Bot.HasInGraveyard(CardId.DarkMagicianTheDragonKnight) && + !Bot.HasInMonstersZone(CardId.DarkMagicianTheDragonKnight) && !plan_C) + { + EternalSoulSelect(); + AI.SelectCard(CardId.DarkMagicianTheDragonKnight); + return true; + } + if (Duel.Player == 1 && Bot.HasInSpellZone(CardId.DarkMagicalCircle) && + (Enemy.HasInMonstersZone(CardId.SummonSorceress) || Enemy.HasInMonstersZone(CardId.FirewallDragon))) + { + soul_used = true; + magician_sp = true; + EternalSoulSelect(); + AI.SelectCard(magician); + return true; + } + if (Duel.Player == 1 && Duel.Phase == DuelPhase.BattleStart && Enemy.GetMonsterCount() > 0) + { + if (Card.IsFacedown() && Bot.HasInMonstersZone(CardId.VentriloauistsClaraAndLucika)) + { + AI.SelectYesNo(false); + return true; + } + if (Card.IsFacedown() && + (Bot.HasInMonstersZone(CardId.DarkMagician) || Bot.HasInMonstersZone(CardId.DarkMagicianTheDragonKnight))) + { + AI.SelectYesNo(false); + return true; + } + if (Bot.HasInGraveyard(CardId.DarkMagicianTheDragonKnight) || + Bot.HasInGraveyard(CardId.DarkMagician)) + { + soul_used = true; + magician_sp = true; + EternalSoulSelect(); + AI.SelectCard(magician); + return true; + } + if (Bot.HasInHand(CardId.DarkMagician)) + { + soul_used = true; + magician_sp = true; + AI.SelectCard(CardId.DarkMagician); + EternalSoulSelect(); + return true; + } + } + if (Duel.Player == 0 && Duel.Phase == DuelPhase.Main1) + { + if (Bot.HasInHand(CardId.DarkMagicalCircle) && !Bot.HasInSpellZone(CardId.DarkMagicalCircle)) + return false; + if (Bot.HasInGraveyard(CardId.DarkMagicianTheDragonKnight) || + Bot.HasInGraveyard(CardId.DarkMagician)) + { + soul_used = true; + magician_sp = true; + AI.SelectCard(magician); + EternalSoulSelect(); + return true; + } + if (Bot.HasInHand(CardId.DarkMagician)) + { + soul_used = true; + magician_sp = true; + AI.SelectCard(CardId.DarkMagician); + EternalSoulSelect(); + return true; + } + } + if (Duel.Phase == DuelPhase.End) + { + if (Card.IsFacedown() && Bot.HasInMonstersZone(CardId.VentriloauistsClaraAndLucika)) + { + AI.SelectYesNo(false); + return true; + } + if (Bot.HasInGraveyard(CardId.DarkMagicianTheDragonKnight) || + Bot.HasInGraveyard(CardId.DarkMagician)) + { + soul_used = true; + magician_sp = true; + AI.SelectCard(magician); + EternalSoulSelect(); + return true; + } + if (Bot.HasInHand(CardId.DarkMagician)) + { + soul_used = true; + magician_sp = true; + AI.SelectCard(CardId.DarkMagician); + EternalSoulSelect(); + return true; + } + return true; + } + return false; + } + + private bool MagicianNavigationset() + { + if (Bot.GetHandCount() > 6) return true; + if (Bot.HasInSpellZone(CardId.LllusionMagic)) return true; + if (Bot.HasInHand(CardId.DarkMagician) && !Bot.HasInSpellZone(CardId.MagicianNavigation)) + return true; + return false; + } + + private bool MagicianNavigationeff() + { + bool spell_act = false; + IList spell = new List(); + if (Duel.LastChainPlayer == 1) + { + foreach (ClientCard check in Enemy.GetSpells()) + { + if (Util.GetLastChainCard() == check) + { + spell.Add(check); + spell_act = true; + break; + } + } + } + bool soul_faceup = false; + foreach (ClientCard check in Bot.GetSpells()) + { + if (check.IsCode(CardId.EternalSoul) && check.IsFaceup()) + { + soul_faceup = true; + } + } + if (Card.Location == CardLocation.Grave && spell_act) + { + Logger.DebugWriteLine("**********************Navigationeff***********"); + AI.SelectCard(spell); + return true; + } + if (Util.IsChainTarget(Card)) + { + AI.SelectPlace(Zones.z0 | Zones.z4); + AI.SelectCard(CardId.DarkMagician); + ClientCard check = Util.GetOneEnemyBetterThanValue(2500, true); + if (check != null) + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + else + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + magician_sp = true; + return UniqueFaceupSpell(); + } + if (DefaultOnBecomeTarget() && !soul_faceup) + { + AI.SelectPlace(Zones.z0 | Zones.z4); + AI.SelectCard(CardId.DarkMagician); + ClientCard check = Util.GetOneEnemyBetterThanValue(2500, true); + if (check != null) + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + else + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + magician_sp = true; + return true; + } + if (Duel.Player == 0 && Card.Location == CardLocation.SpellZone && !maxxc_used && Bot.HasInHand(CardId.DarkMagician)) + { + AI.SelectPlace(Zones.z0 | Zones.z4); + AI.SelectCard(CardId.DarkMagician); + ClientCard check = Util.GetOneEnemyBetterThanValue(2500, true); + if (check != null) + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + else + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + magician_sp = true; + return UniqueFaceupSpell(); + } + if (Duel.Player == 1 && Bot.HasInSpellZone(CardId.DarkMagicalCircle) && + (Enemy.HasInMonstersZone(CardId.SummonSorceress) || Enemy.HasInMonstersZone(CardId.FirewallDragon)) + && Card.Location == CardLocation.SpellZone) + { + AI.SelectPlace(Zones.z0 | Zones.z4); + AI.SelectCard(CardId.DarkMagician); + ClientCard check = Util.GetOneEnemyBetterThanValue(2500, true); + if (check != null) + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + else + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + magician_sp = true; + return UniqueFaceupSpell(); + } + if (Enemy.GetFieldCount() > 0 && + (Duel.Phase == DuelPhase.BattleStart || Duel.Phase == DuelPhase.End) && + Card.Location == CardLocation.SpellZone && !maxxc_used) + { + AI.SelectPlace(Zones.z0 | Zones.z4); + AI.SelectCard(CardId.DarkMagician); + ClientCard check = Util.GetOneEnemyBetterThanValue(2500, true); + if (check != null) + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + else + AI.SelectNextCard(CardId.ApprenticeLllusionMagician, CardId.DarkMagician, CardId.MagicianOfLllusion); + magician_sp = true; + return UniqueFaceupSpell(); + } + + return false; + } + private bool DarkMagicalCircleeff() + { + if (Card.Location == CardLocation.Hand) + { + //AI.SelectPlace(Zones.z2, 2); + if (Bot.LifePoints <= 4000) + return true; + return UniqueFaceupSpell(); + } + else + { + if (magician_sp) + { + AI.SelectCard(Util.GetBestEnemyCard(false, true)); + if (Util.GetBestEnemyCard(false, true) != null) + Logger.DebugWriteLine("*************SelectCard= " + Util.GetBestEnemyCard(false, true).Id); + magician_sp = false; + } + } + return true; + } + private bool LllusionMagicset() + { + if (Bot.GetMonsterCount() >= 1 && + !(Bot.GetMonsterCount() == 1 && Bot.HasInMonstersZone(CardId.CrystalWingSynchroDragon)) && + !(Bot.GetMonsterCount() == 1 && Bot.HasInMonstersZone(CardId.ClearWingFastDragon)) && + !(Bot.GetMonsterCount() == 1 && Bot.HasInMonstersZone(CardId.VentriloauistsClaraAndLucika))) + return true; + return false; + } + private bool LllusionMagiceff() + { + if (lockbird_used) return false; + if (Duel.LastChainPlayer == 0) return false; + ClientCard target = null; + bool soul_exist = false; + //AI.SelectPlace(Zones.z2, 2); + foreach (ClientCard m in Bot.GetSpells()) + { + if (m.IsCode(CardId.EternalSoul) && m.IsFaceup()) + soul_exist = true; + } + if (!soul_used && soul_exist) + { + if (Bot.HasInMonstersZone(CardId.MagiciansRod)) + { + AI.SelectCard(CardId.MagiciansRod); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + } + if (Duel.Player == 0) + { + int ghost_count = 0; + foreach (ClientCard check in Enemy.Graveyard) + { + if (check.IsCode(CardId.Ghost)) + ghost_count++; + } + if (ghost_count != ghost_done) + { + if (Duel.CurrentChain.Count >= 2 && Util.GetLastChainCard().IsCode(0)) + { + AI.SelectCard(CardId.MagiciansRod); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + } + int count = 0; + foreach (ClientCard m in Bot.GetMonsters()) + { + if (Util.IsChainTarget(m)) + { + count++; + target = m; + Logger.DebugWriteLine("************IsChainTarget= " + target.Id); + break; + } + } + if (count == 0) return false; + if ((target.IsCode(CardId.WindwitchGlassBell, CardId.WindwitchIceBell)) && + Bot.HasInMonstersZone(CardId.WindwitchIceBell) && + Bot.HasInMonstersZone(CardId.WindwitchGlassBell)) + return false; + AI.SelectCard(target); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + + if (Bot.HasInMonstersZone(CardId.MagiciansRod) || Bot.HasInMonstersZone(CardId.SpellbookMagicianOfProphecy)) + { + AI.SelectCard(CardId.MagiciansRod, CardId.SpellbookMagicianOfProphecy); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + if (Duel.Player == 1 && Bot.HasInMonstersZone(CardId.WindwitchGlassBell)) + { + AI.SelectCard(CardId.WindwitchGlassBell); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + if (Duel.Player == 1 && Bot.HasInMonstersZone(CardId.WindwitchIceBell)) + { + AI.SelectCard(CardId.WindwitchIceBell); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + if (Duel.Player == 1 && Bot.HasInMonstersZone(CardId.WindwitchSnowBell)) + { + AI.SelectCard(CardId.WindwitchSnowBell); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + if (Duel.Player == 1 && Bot.HasInMonstersZone(CardId.SpellbookMagicianOfProphecy)) + { + AI.SelectCard(CardId.SpellbookMagicianOfProphecy); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + if (Duel.Player == 1 && Bot.HasInMonstersZone(CardId.ApprenticeLllusionMagician) && + (Bot.HasInSpellZone(CardId.EternalSoul) || Bot.HasInSpellZone(CardId.MagicianNavigation))) + { + AI.SelectCard(CardId.ApprenticeLllusionMagician); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + + if ((Bot.GetRemainingCount(CardId.DarkMagician, 3) > 1 || Bot.HasInGraveyard(CardId.DarkMagician)) && + Bot.HasInSpellZone(CardId.MagicianNavigation) && + (Bot.HasInMonstersZone(CardId.DarkMagician) || Bot.HasInMonstersZone(CardId.ApprenticeLllusionMagician)) && + Duel.Player == 1 && !Bot.HasInHand(CardId.DarkMagician)) + { + AI.SelectCard(CardId.DarkMagician, CardId.ApprenticeLllusionMagician); + AI.SelectNextCard(CardId.DarkMagician, CardId.DarkMagician); + return true; + } + return false; + } + private bool SpellbookMagicianOfProphecyeff() + { + Logger.DebugWriteLine("*********Secret_used= " + Secret_used); + if (Secret_used) + AI.SelectCard(CardId.SpellbookOfKnowledge); + else + AI.SelectCard(CardId.SpellbookOfSecrets, CardId.SpellbookOfKnowledge); + return true; + } + + private bool TheEyeOfTimaeuseff() + { + //AI.SelectPlace(Zones.z2, 2); + return true; + } + + private bool UpstartGoblineff() + { + //AI.SelectPlace(Zones.z2, 2); + return true; + } + private bool SpellbookOfSecreteff() + { + if (lockbird_used) return false; + //AI.SelectPlace(Zones.z2, 2); + Secret_used = true; + if (Bot.HasInHand(CardId.SpellbookMagicianOfProphecy)) + AI.SelectCard(CardId.SpellbookOfKnowledge); + else + AI.SelectCard(CardId.SpellbookMagicianOfProphecy); + return true; + } + + private bool SpellbookOfKnowledgeeff() + { + int count = 0; + foreach (ClientCard check in Bot.GetMonsters()) + { + if (!check.IsCode(CardId.CrystalWingSynchroDragon)) + count++; + } + Logger.DebugWriteLine("%%%%%%%%%%%%%%%%SpellCaster= " + count); + if (lockbird_used) return false; + if (Bot.HasInSpellZone(CardId.LllusionMagic) && count < 2) + return false; + //AI.SelectPlace(Zones.z2, 2); + if (Bot.HasInMonstersZone(CardId.SpellbookMagicianOfProphecy) || + Bot.HasInMonstersZone(CardId.MagiciansRod) || + Bot.HasInMonstersZone(CardId.WindwitchGlassBell) || + Bot.HasInMonstersZone(CardId.WindwitchIceBell)) + { + AI.SelectCard(CardId.SpellbookMagicianOfProphecy, CardId.MagiciansRod, CardId.WindwitchGlassBell); + return true; + } + if (Bot.HasInMonstersZone(CardId.ApprenticeLllusionMagician) && Bot.GetSpellCount() < 2 && Duel.Phase == DuelPhase.Main2) + { + AI.SelectCard(CardId.ApprenticeLllusionMagician); + return true; + } + if (Bot.HasInMonstersZone(CardId.DarkMagician) && + Bot.HasInSpellZone(CardId.EternalSoul) && Duel.Phase == DuelPhase.Main2) + { + AI.SelectCard(CardId.DarkMagician); + return true; + } + return false; + } + + private bool WonderWandeff() + { + if (lockbird_used) return false; + int count = 0; + foreach (ClientCard check in Bot.GetMonsters()) + { + if (!check.IsCode(CardId.CrystalWingSynchroDragon)) + count++; + } + Logger.DebugWriteLine("%%%%%%%%%%%%%%%%SpellCaster= " + count); + if (Card.Location == CardLocation.Hand) + { + if (Bot.HasInSpellZone(CardId.LllusionMagic) && count < 2) + return false; + //AI.SelectPlace(Zones.z2, 2); + if (Bot.HasInMonstersZone(CardId.SpellbookMagicianOfProphecy) || + Bot.HasInMonstersZone(CardId.MagiciansRod) || + Bot.HasInMonstersZone(CardId.WindwitchGlassBell) || + Bot.HasInMonstersZone(CardId.WindwitchIceBell)) + { + AI.SelectCard( + CardId.SpellbookMagicianOfProphecy, + CardId.MagiciansRod, + CardId.WindwitchGlassBell, + CardId.WindwitchIceBell + ); + return UniqueFaceupSpell(); + } + + if (Bot.HasInMonstersZone(CardId.DarkMagician) && + Bot.HasInSpellZone(CardId.EternalSoul) && Duel.Phase == DuelPhase.Main2) + { + AI.SelectCard(CardId.DarkMagician); + return UniqueFaceupSpell(); + } + if (Bot.HasInMonstersZone(CardId.ApprenticeLllusionMagician) && Bot.GetSpellCount() < 2 && Duel.Phase == DuelPhase.Main2) + { + AI.SelectCard(CardId.ApprenticeLllusionMagician); + return UniqueFaceupSpell(); + } + if (Bot.HasInMonstersZone(CardId.ApprenticeLllusionMagician) && Bot.GetHandCount() <= 3 && Duel.Phase == DuelPhase.Main2) + { + AI.SelectCard(CardId.ApprenticeLllusionMagician); + return UniqueFaceupSpell(); + } + } + else + { + if (Duel.Turn != 1) + { + if (Duel.Phase == DuelPhase.Main1 && Enemy.GetSpellCountWithoutField() == 0 && + Util.GetBestEnemyMonster(true, true) == null) + return false; + if (Duel.Phase == DuelPhase.Main1 && Enemy.GetSpellCountWithoutField() == 0 && + Util.GetBestEnemyMonster().IsFacedown()) + return true; + if (Duel.Phase == DuelPhase.Main1 && Enemy.GetSpellCountWithoutField() == 0 && + Util.GetBestBotMonster(true) != null && + Util.GetBestBotMonster(true).Attack > Util.GetBestEnemyMonster(true).Attack) + return false; + } + return true; + } + return false; + } + + private bool ApprenticeLllusionMagiciansp() + { + //AI.SelectPlace(Zones.z2, 1); + if (Bot.HasInHand(CardId.DarkMagician) && !Bot.HasInSpellZone(CardId.MagicianNavigation)) + { + if (Bot.GetRemainingCount(CardId.DarkMagician, 3) > 0) + { + AI.SelectCard(CardId.DarkMagician); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + return false; + } + if ((Bot.HasInHand(CardId.SpellbookOfSecrets) || + Bot.HasInHand(CardId.DarkMagicAttack))) + { + AI.SelectPosition(CardPosition.FaceUpAttack); + AI.SelectCard(CardId.SpellbookOfSecrets, CardId.DarkMagicAttack); + return true; + } + if (Bot.HasInMonstersZone(CardId.ApprenticeLllusionMagician)) + return false; + int count = 0; + foreach (ClientCard check in Bot.Hand) + { + if (check.IsCode(CardId.WonderWand)) + count++; + } + if (count >= 2) + { + AI.SelectPosition(CardPosition.FaceUpAttack); + AI.SelectCard(CardId.WonderWand); + return true; + } + if(!Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && + Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation)&& + !Bot.HasInHand(CardId.DarkMagician) && Bot.GetHandCount()>2&& + Bot.GetMonsterCount()==0) + { + AI.SelectPosition(CardPosition.FaceUpAttack); + AI.SelectCard(CardId.MagicianOfLllusion, CardId.ApprenticeLllusionMagician, CardId.TheEyeOfTimaeus, CardId.DarkMagicInheritance, CardId.WonderWand); + return true; + } + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.DarkMagician)) + { + if (Bot.HasInHandOrInSpellZone(CardId.LllusionMagic) && Bot.GetMonsterCount() >= 1) + return false; + AI.SelectPosition(CardPosition.FaceUpAttack); + int Navigation_count = 0; + foreach (ClientCard Navigation in Bot.Hand) + { + if (Navigation.IsCode(CardId.MagicianNavigation)) + Navigation_count++; + } + if (Navigation_count >= 2) + { + AI.SelectCard(CardId.MagicianNavigation); + return true; + } + AI.SelectCard(CardId.MagicianOfLllusion, CardId.ApprenticeLllusionMagician, CardId.TheEyeOfTimaeus, CardId.DarkMagicInheritance, CardId.WonderWand); + return true; + } + return false; + } + private bool ApprenticeLllusionMagicianeff() + { + if (Util.ChainContainsCard(CardId.ApprenticeLllusionMagician)) return false; + if (Duel.Phase == DuelPhase.Battle || + Duel.Phase == DuelPhase.BattleStart || + Duel.Phase == DuelPhase.BattleStep || + Duel.Phase == DuelPhase.Damage || + Duel.Phase == DuelPhase.DamageCal + ) + { + if (ActivateDescription == -1) + { + Logger.DebugWriteLine("ApprenticeLllusionMagicianadd"); + return true; + } + if (Card.IsDisabled()) return false; + if ((Bot.BattlingMonster == null)) return false; + if ((Enemy.BattlingMonster == null)) return false; + if (Bot.BattlingMonster.Attack < Enemy.BattlingMonster.Attack) + return true; + else + return false; + } + else + return true; + } + private bool SpellbookMagicianOfProphecysummon() + { + //AI.SelectPlace(Zones.z2, 1); + if (lockbird_used) return false; + if (Spellbook_summon) + { + if (Secret_used) + AI.SelectCard(CardId.SpellbookOfKnowledge); + else + AI.SelectCard(CardId.SpellbookOfSecrets, CardId.SpellbookOfKnowledge); + return true; + } + return false; + } + private bool MagiciansRodsummon() + { + if (lockbird_used) return false; + //AI.SelectPlace(Zones.z2, 1); + if (Rod_summon) return true; + return true; + } + + private bool DarkMagicAttackeff() + { + //AI.SelectPlace(Zones.z1, 2); + return DefaultHarpiesFeatherDusterFirst(); + } + private bool DarkMagicInheritanceeff() + { + if (lockbird_used) return false; + IList grave = Bot.Graveyard; + IList spell = new List(); + int count = 0; + foreach (ClientCard check in grave) + { + if (Card.HasType(CardType.Spell)) + { + spell.Add(check); + count++; + } + } + if (count >= 2) + { + //AI.SelectPlace(Zones.z2, 2); + AI.SelectCard(spell); + if (Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && Bot.HasInHandOrInSpellZone(CardId.DarkMagicalCircle)) + if (Bot.GetRemainingCount(CardId.DarkMagician, 3) >= 2 && !Bot.HasInHandOrInSpellZoneOrInGraveyard(CardId.LllusionMagic)) + { + AI.SelectNextCard(CardId.LllusionMagic); + return true; + } + + if (Bot.HasInHand(CardId.ApprenticeLllusionMagician) && + (!Bot.HasInHandOrInSpellZone(CardId.EternalSoul) || !Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation))) + { + AI.SelectNextCard(CardId.MagicianNavigation); + return true; + } + if (Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && !Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.DarkMagician) && + !Bot.HasInHandOrInSpellZoneOrInGraveyard(CardId.LllusionMagic)) + { + AI.SelectNextCard(CardId.LllusionMagic); + return true; + } + + if (Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation) && + !Bot.HasInHand(CardId.DarkMagician) && + !Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && + Bot.GetRemainingCount(CardId.LllusionMagic, 1) > 0) + { + AI.SelectNextCard(CardId.LllusionMagic); + return true; + } + + if ((Bot.HasInHandOrInSpellZone(CardId.EternalSoul) || Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation)) && + !Bot.HasInHandOrInSpellZone(CardId.DarkMagicalCircle)) + { + AI.SelectNextCard(CardId.DarkMagicalCircle); + return true; + } + if (Bot.HasInHandOrInSpellZone(CardId.DarkMagicalCircle)) + { + if (Bot.HasInGraveyard(CardId.MagicianNavigation)) + { + AI.SelectNextCard(CardId.EternalSoul, CardId.MagicianNavigation, CardId.DarkMagicalCircle); + } + else + AI.SelectNextCard(CardId.EternalSoul, CardId.MagicianNavigation, CardId.DarkMagicalCircle); + return true; + } + if (Bot.HasInGraveyard(CardId.MagicianNavigation)) + { + AI.SelectNextCard(CardId.EternalSoul, CardId.DarkMagicalCircle, CardId.MagicianNavigation); + } + else + AI.SelectNextCard(CardId.MagicianNavigation, CardId.DarkMagicalCircle, CardId.EternalSoul); + return true; + } + return false; + } + private bool MagiciansRodeff() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && Bot.HasInHandOrInSpellZone(CardId.DarkMagicalCircle)) + if (Bot.GetRemainingCount(CardId.DarkMagician, 3) >= 2 && Bot.GetRemainingCount(CardId.LllusionMagic, 1) > 0) + { + AI.SelectCard(CardId.LllusionMagic); + return true; + } + + if (Bot.HasInHand(CardId.ApprenticeLllusionMagician) && + !Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation) && + Bot.GetRemainingCount(CardId.MagicianNavigation, 3) > 0) + { + AI.SelectCard(CardId.MagicianNavigation); + return true; + } + + if (Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && + !Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.DarkMagician) && + Bot.GetRemainingCount(CardId.LllusionMagic, 1) > 0) + { + AI.SelectCard(CardId.LllusionMagic); + return true; + } + + if (Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation) && + !Bot.HasInHand(CardId.DarkMagician) && + !Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && + Bot.GetRemainingCount(CardId.LllusionMagic, 1) > 0) + { + AI.SelectCard(CardId.LllusionMagic); + return true; + } + if (!Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && + Bot.HasInHandOrInSpellZone(CardId.DarkMagicalCircle) && + Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation) && + Bot.GetRemainingCount(CardId.EternalSoul, 3) > 0) + { + AI.SelectCard(CardId.EternalSoul); + return true; + } + if ((Bot.HasInHandOrInSpellZone(CardId.EternalSoul) || Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation)) && + !Bot.HasInHandOrInSpellZone(CardId.DarkMagicalCircle) && + Bot.GetRemainingCount(CardId.DarkMagicalCircle, 3) > 0) + { + AI.SelectCard(CardId.DarkMagicalCircle); + return true; + } + if (!Bot.HasInHandOrInSpellZone(CardId.EternalSoul) && + !Bot.HasInHandOrInSpellZone(CardId.MagicianNavigation)) + { + if (Bot.HasInHand(CardId.DarkMagician) && + !Bot.HasInGraveyard(CardId.MagicianNavigation) && + Bot.GetRemainingCount(CardId.MagicianNavigation, 3) > 0 + ) + AI.SelectCard(CardId.MagicianNavigation); + else if (!Bot.HasInHandOrInSpellZone(CardId.DarkMagicalCircle)) + AI.SelectCard(CardId.DarkMagicalCircle); + else + AI.SelectCard(CardId.EternalSoul); + return true; + } + if (!Bot.HasInHand(CardId.MagicianNavigation)) + { + AI.SelectCard(CardId.MagicianNavigation); + return true; + } + if (!Bot.HasInHand(CardId.DarkMagicalCircle)) + { + AI.SelectCard(CardId.DarkMagicalCircle); + return true; + } + if (!Bot.HasInHand(CardId.EternalSoul)) + { + AI.SelectCard(CardId.EternalSoul); + return true; + } + AI.SelectCard(CardId.LllusionMagic, CardId.EternalSoul, CardId.DarkMagicalCircle, CardId.MagicianNavigation); + return true; + } + else + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Bot.HasInMonstersZone(CardId.VentriloauistsClaraAndLucika)) + { + AI.SelectCard(CardId.VentriloauistsClaraAndLucika); + return true; + } + int Enemy_atk = 0; + IList list = new List(); + foreach (ClientCard monster in Enemy.GetMonsters()) + { + if (monster.IsAttack()) + list.Add(monster); + } + Enemy_atk = GetTotalATK(list); + int bot_atk = 0; + IList list_1 = new List(); + foreach (ClientCard monster in Bot.GetMonsters()) + { + if (Util.GetWorstBotMonster(true) != null) + { + if (monster.IsAttack() && monster.Id != Util.GetWorstBotMonster(true).Id) + list_1.Add(monster); + } + } + bot_atk = GetTotalATK(list); + if (Bot.HasInHand(CardId.MagiciansRod)) return false; + if (Bot.HasInMonstersZone(CardId.ApprenticeWitchling) && Bot.GetMonsterCount() == 1 && Bot.HasInSpellZone(CardId.EternalSoul)) + return false; + if (Bot.LifePoints <= (Enemy_atk - bot_atk) && + Bot.GetMonsterCount() > 1) return false; + if ((Bot.LifePoints - Enemy_atk <= 1000) && + Bot.GetMonsterCount() == 1) return false; + AI.SelectCard(CardId.VentriloauistsClaraAndLucika, CardId.SpellbookMagicianOfProphecy, CardId.WindwitchGlassBell, CardId.WindwitchIceBell, CardId.MagiciansRod, CardId.DarkMagician, CardId.MagicianOfLllusion); + return true; + } + } + + private bool WindwitchGlassBellsummonfirst() + { + if (Bot.HasInMonstersZone(CardId.WindwitchIceBell) && + Bot.HasInMonstersZone(CardId.WindwitchSnowBell) && + !Bot.HasInMonstersZone(CardId.WindwitchGlassBell)) + return true; + return false; + } + private bool WindwitchGlassBellsummon() + { + if (lockbird_used) return false; + if (!plan_A && (Bot.HasInGraveyard(CardId.WindwitchGlassBell) || Bot.HasInMonstersZone(CardId.WindwitchGlassBell))) + return false; + //AI.SelectPlace(Zones.z2, 1); + if (GlassBell_summon && Bot.HasInMonstersZone(CardId.WindwitchIceBell) && + !Bot.HasInMonstersZone(CardId.WindwitchGlassBell)) + return true; + if (WindwitchGlassBelleff_used) return false; + if (GlassBell_summon) return true; + return false; + } + private bool BigEyesp() + { + if (plan_C) return false; + if (Util.IsOneEnemyBetterThanValue(2500, false) && + !Bot.HasInHandOrHasInMonstersZone(CardId.ApprenticeLllusionMagician)) + { + //AI.SelectPlace(Zones.z5, Zones.ExtraMonsterZones); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + return false; + } + + private bool BigEyeeff() + { + ClientCard target = Util.GetBestEnemyMonster(false, true); + if (target != null && target.Attack >= 2500) + { + AI.SelectCard(CardId.DarkMagician); + AI.SelectNextCard(target); + return true; + } + return false; + + } + private bool Dracossacksp() + { + if (plan_C) return false; + if (Util.IsOneEnemyBetterThanValue(2500, false) && + !Bot.HasInHandOrHasInMonstersZone(CardId.ApprenticeLllusionMagician)) + { + //AI.SelectPlace(Zones.z5, Zones.ExtraMonsterZones); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + return false; + } + + private bool Dracossackeff() + { + if (ActivateDescription == Util.GetStringId(CardId.Dracossack, 0)) + { + AI.SelectCard(CardId.DarkMagician); + return true; + + } + ClientCard target = Util.GetBestEnemyCard(false, true); + if (target != null) + { + AI.SelectCard(CardId.Dracossack + 1); + AI.SelectNextCard(target); + return true; + } + return false; + } + + private bool ApprenticeWitchlingsp() + { + int rod_count = 0; + foreach (ClientCard rod in Bot.GetMonsters()) + { + if (rod.IsCode(CardId.MagiciansRod)) + rod_count++; + } + if (rod_count >= 2) + { + AI.SelectCard(CardId.MagiciansRod, CardId.MagiciansRod); + return true; + } + if (Bot.HasInMonstersZone(CardId.DarkMagician) && + Bot.HasInMonstersZone(CardId.MagiciansRod) && + (Bot.HasInSpellZone(CardId.EternalSoul) || Bot.GetMonsterCount() >= 4) + && Duel.Phase == DuelPhase.Main2) + { + if (rod_count >= 2) + AI.SelectCard(CardId.MagiciansRod, CardId.MagiciansRod); + else + AI.SelectCard(CardId.MagiciansRod, CardId.DarkMagician); + return true; + } + if (Bot.HasInMonstersZone(CardId.MagiciansRod) && + Bot.HasInMonstersZone(CardId.ApprenticeLllusionMagician) && + (Bot.HasInSpellZone(CardId.EternalSoul) || Bot.HasInSpellZone(CardId.MagicianNavigation)) + && Duel.Phase == DuelPhase.Main2) + { + if (rod_count >= 2) + AI.SelectCard(CardId.MagiciansRod, CardId.MagiciansRod); + else + AI.SelectCard(CardId.MagiciansRod, CardId.DarkMagician); + return true; + } + return false; + } + + private bool ApprenticeWitchlingeff() + { + AI.SelectCard(CardId.MagiciansRod, CardId.DarkMagician, CardId.ApprenticeLllusionMagician); + return true; + } + public override bool OnSelectHand() + { + return true; + } + + private bool VentriloauistsClaraAndLucikasp() + { + if (Bot.HasInSpellZone(CardId.LllusionMagic)) return false; + if (Bot.HasInMonstersZone(CardId.MagiciansRod) && !Bot.HasInGraveyard(CardId.MagiciansRod) && + (Bot.HasInSpellZone(CardId.EternalSoul) || Bot.HasInSpellZone(CardId.MagicianNavigation))) + { + AI.SelectCard(CardId.MagiciansRod); + return true; + } + return false; + } + public override void OnChaining(int player, ClientCard card) + { + base.OnChaining(player, card); + } + + + public override void OnChainEnd() + { + /*if (Enemy.MonsterZone[5] != null) + { + Logger.DebugWriteLine("%%%%%%%%%%%%%%%%Enemy.MonsterZone[5].LinkMarker= " + Enemy.MonsterZone[5].LinkMarker); + Logger.DebugWriteLine("%%%%%%%%%%%%%%%%Enemy.MonsterZone[5].LinkLevel= " + Enemy.MonsterZone[5].LinkLevel); + } + + if (Enemy.MonsterZone[6] != null) + { + Logger.DebugWriteLine("%%%%%%%%%%%%%%%%Enemy.MonsterZone[6].LinkMarker= " + Enemy.MonsterZone[6].LinkMarker); + Logger.DebugWriteLine("%%%%%%%%%%%%%%%%Enemy.MonsterZone[6].LinkLevel= " + Enemy.MonsterZone[6].LinkLevel); + } + for (int i = 0; i < 6; i++) + { + if (Enemy.MonsterZone[i] != null) + Logger.DebugWriteLine("++++++++MONSTER ZONE[" + i + "]= " + Enemy.MonsterZone[i].Attack); + } + for (int i = 0; i < 6; i++) + { + if (Bot.MonsterZone[i] != null) + Logger.DebugWriteLine("++++++++MONSTER ZONE[" + i + "]= " + Bot.MonsterZone[i].Id); + } + for (int i = 0; i < 4; i++) + { + if (Bot.SpellZone[i] != null) + Logger.DebugWriteLine("++++++++SpellZone[" + i + "]= " + Bot.SpellZone[i].Id); + }*/ + if (Util.ChainContainsCard(CardId.MaxxC)) + maxxc_used = true; + if ((Duel.CurrentChain.Count >= 1 && Util.GetLastChainCard().Id == 0) || + (Duel.CurrentChain.Count == 2 && !Util.ChainContainPlayer(0) && Duel.CurrentChain[0].Id == 0)) + { + Logger.DebugWriteLine("current chain = " + Duel.CurrentChain.Count); + Logger.DebugWriteLine("******last chain card= " + Util.GetLastChainCard().Id); + int maxxc_count = 0; + foreach (ClientCard check in Enemy.Graveyard) + { + if (check.IsCode(CardId.MaxxC)) + maxxc_count++; + } + if (maxxc_count != maxxc_done) + { + Logger.DebugWriteLine("************************last chain card= " + Util.GetLastChainCard().Id); + maxxc_used = true; + } + int lockbird_count = 0; + foreach (ClientCard check in Enemy.Graveyard) + { + if (check.IsCode(CardId.LockBird)) + lockbird_count++; + } + if (lockbird_count != lockbird_done) + { + Logger.DebugWriteLine("************************last chain card= " + Util.GetLastChainCard().Id); + lockbird_used = true; + } + int ghost_count = 0; + foreach (ClientCard check in Enemy.Graveyard) + { + if (check.IsCode(CardId.Ghost)) + ghost_count++; + } + if (ghost_count != ghost_done) + { + Logger.DebugWriteLine("************************last chain card= " + Util.GetLastChainCard().Id); + ghost_used = true; + } + if (ghost_used && Util.ChainContainsCard(CardId.WindwitchGlassBell)) + { + AI.SelectCard(CardId.WindwitchIceBell); + Logger.DebugWriteLine("***********WindwitchGlassBell*********************"); + } + + } + foreach (ClientCard dangerous in Enemy.GetMonsters()) + { + if (dangerous != null && dangerous.IsShouldNotBeTarget() && + (dangerous.Attack > 2500 || dangerous.Defense > 2500) && + !Bot.HasInHandOrHasInMonstersZone(CardId.ApprenticeLllusionMagician)) + { + plan_C = true; + Logger.DebugWriteLine("*********dangerous = " + dangerous.Id); + } + } + int count = 0; + foreach (ClientCard check in Enemy.Graveyard) + { + if (check.IsCode(CardId.MaxxC)) + count++; + } + maxxc_done = count; + count = 0; + foreach (ClientCard check in Enemy.Graveyard) + { + if (check.IsCode(CardId.LockBird)) + count++; + } + lockbird_done = count; + count = 0; + foreach (ClientCard check in Enemy.Graveyard) + { + if (check.IsCode(CardId.Ghost)) + count++; + } + ghost_done = count; + base.OnChainEnd(); + } + + + public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + /* + if (Enemy.HasInMonstersZone(CardId.MekkKnightMorningStar)) + { + attackerzone = -1; + defenderzone = -1; + for (int a = 0; a <= 6; a++) + for (int b = 0; b <= 6; b++) + { + if (Bot.MonsterZone[a] != null && Enemy.MonsterZone[b] != null && + SameMonsterColumn(a, b) && + Bot.MonsterZone[a].IsCode(attacker.Id) && Enemy.MonsterZone[b].IsCode(defender.Id)) + { + attackerzone = a; + defenderzone = b; + } + } + Logger.DebugWriteLine("**********attack_zone= " + attackerzone + " defender_zone= " + defenderzone); + if (!SameMonsterColumn(attackerzone, defenderzone) && IsJackKnightMonster(defenderzone)) + { + Logger.DebugWriteLine("**********cant attack "); + return false; + } + } + */ + //Logger.DebugWriteLine("@@@@@@@@@@@@@@@@@@@ApprenticeLllusionMagician= " + ApprenticeLllusionMagician_count); + if (Bot.HasInSpellZone(CardId.OddEyesWingDragon)) + big_attack = true; + if (Duel.Player == 0 && Bot.GetMonsterCount() >= 2 && plan_C) + { + Logger.DebugWriteLine("*********dangerous********************* "); + if (attacker.IsCode(CardId.OddEyesAbsoluteDragon, CardId.OddEyesWingDragon)) + attacker.RealPower = 9999; + } + if ((attacker.IsCode(CardId.DarkMagician, CardId.MagiciansRod, CardId.BigEye, CardId.ApprenticeWitchling)) && + Bot.HasInHandOrHasInMonstersZone(CardId.ApprenticeLllusionMagician)) + { + attacker.RealPower += 2000; + } + if (attacker.IsCode(CardId.ApprenticeLllusionMagician) && ApprenticeLllusionMagician_count >= 2) + { + attacker.RealPower += 2000; + } + if (attacker.IsCode(CardId.DarkMagician, CardId.DarkMagicianTheDragonKnight) && Bot.HasInSpellZone(CardId.EternalSoul)) + { + return true; + } + if (attacker.IsCode(CardId.CrystalWingSynchroDragon)) + { + if (defender.Level >= 5) + attacker.RealPower = 9999; + if (CrystalWingSynchroDragon_used == false) + return true; + } + if (!big_attack_used && big_attack) + { + attacker.RealPower = 9999; + big_attack_used = true; + return true; + } + if (attacker.IsCode(CardId.ApprenticeLllusionMagician)) + Logger.DebugWriteLine("@@@@@@@@@@@@@@@@@@@ApprenticeLllusionMagician= " + attacker.RealPower); + if (Bot.HasInSpellZone(CardId.EternalSoul) && attacker.IsCode(CardId.DarkMagician, CardId.DarkMagicianTheDragonKnight, CardId.MagicianOfLllusion)) + return true; + return base.OnPreBattleBetween(attacker, defender); + } + /* + public override BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList defenders) + { + for (int i = 0; i < defenders.Count; ++i) + { + ClientCard defender = defenders[i]; + if (Enemy.HasInMonstersZone(CardId.MekkKnightMorningStar)) + { + for (int b = 0; b <= 6; b++) + { + if (Enemy.MonsterZone[b] != null && + SameMonsterColumn(attackerzone, b) && + Bot.MonsterZone[attackerzone].IsCode(attacker.Id) && Enemy.MonsterZone[b].IsCode(defender.Id)) + { + defenderzone = b; + } + } + if (defenderzone == -1) + { + Logger.DebugWriteLine("**********firstattackerzone= " + attackerzone + " firstTargetzone= " + defenderzone); + + return null; + } + } + } + defenderzone = -1; + return base.OnSelectAttackTarget(attacker,defenders); + } + */ + /* + public override ClientCard OnSelectAttacker(IList attackers, IList defenders) + { + for (int i = 0; i < attackers.Count; ++i) + { + ClientCard attacker = attackers[i]; + for(int j = 0;j < defenders.Count;++j) + { + ClientCard defender = defenders[j]; + if (Enemy.HasInMonstersZone(CardId.MekkKnightMorningStar)) + { + attackerzone = -1; + defenderzone = -1; + for(int a = 0;a <= 6;a++) + for(int b = 0;b <= 6;b++) + { + if (Bot.MonsterZone[a] != null && Enemy.MonsterZone[b]!=null && + SameMonsterColumn(a,b) && + Bot.MonsterZone[a].IsCode(attacker.Id) && Enemy.MonsterZone[b].IsCode(defender.Id)) + { + attackerzone = a; + defenderzone = b; + } + } + + if (defenderzone != -1) + { + Logger.DebugWriteLine("**********firstattackerzone= " + attackerzone + " firstdefenderzone= " + defenderzone); + return attacker; + } + } + } + } + return base.OnSelectAttacker(attackers,defenders); + } + */ + public bool MonsterRepos() + { + if (Bot.HasInMonstersZone(CardId.OddEyesWingDragon) || + Bot.HasInSpellZone(CardId.OddEyesWingDragon) || + Bot.HasInMonstersZone(CardId.OddEyesAbsoluteDragon)) + { + if (Card.IsAttack()) + return false; + } + if (Bot.HasInMonstersZone(CardId.ApprenticeLllusionMagician) || (Bot.HasInHand(CardId.ApprenticeLllusionMagician))) + { + if (Card.IsAttack()) + return false; + } + if (Card.IsFacedown()) + return true; + return base.DefaultMonsterRepos(); + } + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DoEveryThingExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DoEveryThingExecutor.cs new file mode 100644 index 0000000..8699807 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DoEveryThingExecutor.cs @@ -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 OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (Duel.Phase == DuelPhase.BattleStart) + return null; + + IList selected = new List(); + + // select the last cards + for (int i = 1; i <= max; ++i) + selected.Add(cards[cards.Count-i]); + + return selected; + } + + public override int OnSelectOption(IList options) + { + return Program.Rand.Next(options.Count); + } + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DogmatikaExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DogmatikaExecutor.cs new file mode 100644 index 0000000..967c9a1 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DogmatikaExecutor.cs @@ -0,0 +1,2902 @@ +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using System.Linq; +using System; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Dogmatika", "AI_Dogmatika")] + + public class DogmatikaExecutor : DefaultExecutor + { + public class CardId + { + public const int DogmatikaAlbaZoa = 51522296; + public const int ThesIrisSwordsoul = 62849088; + public const int DogmatikaFleurdelis = 69680031; + public const int DogmatikaMaximus = 95679145; + public const int DiabellstarTheBlackWitch = 72270339; + public const int DogmatikaEcclesia = 60303688; + // _CardId.AshBlossom = 14558127; + // _CardId.MaxxC = 23434538; + public const int KnightmareCorruptorIblee = 10158145; + + public const int NadirServant = 1984618; + public const int DogmatikaLamity = 31002402; + public const int DogmatikaMacabre = 60921537; + public const int SinfulSpoilsOfDoom_Rciela = 16240772; + // _CardId.CalledByTheGrave = 24224830; + // _CardId.CrossoutDesignator = 65681983; + public const int WANTED_SeekerOfSinfulSpoils = 80845034; + public const int DogmatikaMatrix = 35569555; + + // _CardId.InfiniteImpermanence = 10045474; + public const int DogmatikaPunishment = 82956214; + + public const int GranguignolTheDuskDragon = 24915933; + public const int TitanikladTheAshDragon = 41373230; + public const int GaruraWingsOfResonantLife = 11765832; + public const int ElderEntityNtss = 80532587; + public const int DespianLuluwalilith = 53971455; + public const int PSYFramelordOmega = 74586817; + public const int HeraldOfTheArcLight = 79606837; + public const int SuperStarslayerTYPHON = 93039339; + public const int SPLittleKnight = 29301450; + public const int SecureGardna = 2220237; + public const int Linguriboh = 24842059; + public const int SalamangreatAlmiraj = 60303245; + + public const int NaturalExterio = 99916754; + public const int NaturalBeast = 33198837; + public const int ImperialOrder = 61740673; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecree = 51452091; + public const int Number41BagooskatheTerriblyTiredTapir = 90590303; + public const int InspectorBoarder = 15397015; + public const int SkillDrain = 82732705; + + public const int DimensionShifter = 91800273; + public const int MacroCosmos = 30241314; + public const int DimensionalFissure = 81674782; + public const int BanisheroftheRadiance = 94853057; + public const int BanisheroftheLight = 61528025; + public const int GhostMournerMoonlitChill = 52038441; + } + + public DogmatikaExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // startup effect + AddExecutor(ExecutorType.Activate, CardId.WANTED_SeekerOfSinfulSpoils, WANTED_SeekerOfSinfulSpoilsActivate); + AddExecutor(ExecutorType.Activate, CardId.SalamangreatAlmiraj, SalamangreatAlmirajActivate); + + AddExecutor(ExecutorType.Activate, CardId.PSYFramelordOmega, PSYFramelordOmegaActivate); + AddExecutor(ExecutorType.Activate, CardId.DogmatikaAlbaZoa, DogmatikaAlbaZoaActivate); + AddExecutor(ExecutorType.Activate, CardId.DogmatikaMaximus, DogmatikaMaximusActivate); + AddExecutor(ExecutorType.Activate, CardId.DiabellstarTheBlackWitch, DiabellstarTheBlackWitchActivate); + + // quick effect + AddExecutor(ExecutorType.Activate, CardId.ThesIrisSwordsoul, ThesIrisSwordsoulActivate); + AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, CalledbytheGraveActivate); + AddExecutor(ExecutorType.Activate, _CardId.CrossoutDesignator, CrossoutDesignatorActivate); + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossomActivate); + AddExecutor(ExecutorType.Activate, CardId.Linguriboh, LinguribohActivate); + AddExecutor(ExecutorType.Activate, CardId.DogmatikaPunishment, DogmatikaPunishmentActivate); + AddExecutor(ExecutorType.Activate, CardId.DogmatikaFleurdelis, DogmatikaFleurdelisActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, CardId.SinfulSpoilsOfDoom_Rciela, SinfulSpoilsOfDoom_RcielaActivate); + AddExecutor(ExecutorType.Activate, ClearIrisFlag); + + AddExecutor(ExecutorType.Activate, CardId.HeraldOfTheArcLight, HeraldOfTheArcLightActivate); + AddExecutor(ExecutorType.Activate, CardId.ElderEntityNtss, ElderEntityNtssActivate); + AddExecutor(ExecutorType.Activate, CardId.GranguignolTheDuskDragon, GranguignolTheDuskDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.GaruraWingsOfResonantLife, GaruraWingsOfResonantLifeActivate); + AddExecutor(ExecutorType.Activate, CardId.KnightmareCorruptorIblee, KnightmareCorruptorIbleeActivate); + AddExecutor(ExecutorType.Activate, CardId.TitanikladTheAshDragon, TitanikladTheAshDragonActivate); + AddExecutor(ExecutorType.Activate, CardId.DespianLuluwalilith, DespianLuluwalilithActivate); + + // free chain + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + AddExecutor(ExecutorType.Activate, CardId.SuperStarslayerTYPHON, SuperStarslayerTYPHONActivate); + + // spsummon + AddExecutor(ExecutorType.SpSummon, CardId.Linguriboh, LinguribohSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SalamangreatAlmiraj, SalamangreatAlmirajSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SecureGardna, SecureGardnaSpSummon); + + // startup effect + AddExecutor(ExecutorType.Summon, CardId.KnightmareCorruptorIblee, KnightmareCorruptorIbleeSummon); + AddExecutor(ExecutorType.Activate, CardId.NadirServant, NadirServantActivate); + + // summon + AddExecutor(ExecutorType.Summon, CardId.DogmatikaEcclesia, DogmatikaEcclesiaSummon); + AddExecutor(ExecutorType.Activate, CardId.DogmatikaEcclesia, DogmatikaEcclesiaActivate); + + // ritual + AddExecutor(ExecutorType.Activate, CardId.DogmatikaMatrix, DogmatikaMatrixActivate); + AddExecutor(ExecutorType.Activate, CardId.DogmatikaLamity, DogmatikaLamityActivate); + AddExecutor(ExecutorType.Activate, CardId.DogmatikaMacabre, DogmatikaMacabreActivate); + + // other + AddExecutor(ExecutorType.Activate, CardId.DogmatikaFleurdelis, DogmatikaFleurdelisDelayActivate); + AddExecutor(ExecutorType.Repos, MonsterRepos); + AddExecutor(ExecutorType.Summon, SummonForTYPHONCheck); + AddExecutor(ExecutorType.SpSummon, CardId.DiabellstarTheBlackWitch, DiabellstarTheBlackWitchSpSummon); + AddExecutor(ExecutorType.Activate, CardId.DogmatikaLamity, DogmatikaLamityDelayActivate); + AddExecutor(ExecutorType.SpSummon, CardId.SuperStarslayerTYPHON, SuperStarslayerTYPHONSpSummon); + AddExecutor(ExecutorType.SpellSet, SpellSetCheck); + } + + const int SetcodeTimeLord = 0x4a; + const int SetcodePhantom = 0xdb; + const int SetcodeOrcust = 0x11b; + const int SetcodeDogmatika = 0x145; + const int hintTimingMainEnd = 0x4; + const int hintDamageStep = 0x2000; + + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.DogmatikaEcclesia, _CardId.AshBlossom, _CardId.MaxxC, CardId.KnightmareCorruptorIblee, CardId.NadirServant, + CardId.WANTED_SeekerOfSinfulSpoils, CardId.DogmatikaMatrix, _CardId.InfiniteImpermanence, CardId.DogmatikaPunishment }}, + {2, new List { CardId.DogmatikaAlbaZoa, CardId.DogmatikaFleurdelis, _CardId.CalledByTheGrave }}, + {1, new List { CardId.ThesIrisSwordsoul, CardId.DogmatikaMaximus, CardId.DiabellstarTheBlackWitch, CardId.DogmatikaLamity, CardId.DogmatikaMacabre, + CardId.SinfulSpoilsOfDoom_Rciela, _CardId.CrossoutDesignator }}, + }; + List notToNegateIdList = new List{ + 58699500, 20343502 + }; + List discardEnemyExtraIdList = new List{ + _CardId.DivineArsenalAAZEUS_SkyThunder, CardId.SPLittleKnight, CardId.Number41BagooskatheTerriblyTiredTapir, + 70534340, 60465049, 24094258, 86066372 + }; + + List currentNegatingIdList = new List(); + bool enemyActivateMaxxC = false; + bool enemyActivateLockBird = false; + List infiniteImpermanenceList = new List(); + bool summoned = false; + List activatedCardIdList = new List(); + List currentNegateMonsterList = new List(); + List currentDestroyCardList = new List(); + List discardExtraThisTurn = new List(); + int banSpSummonFromExTurn = 0; + List activatedMatrixList = new List(); + List maximusDiscardExtraIdList = new List(); + bool checkedEnemyExtra = false; + bool matrixActivating = false; + bool avoid2Monster = true; + bool confirmLink2 = false; + int omegaActivateCount = 0; + int dimensionShifterCount = 0; + + int enemySpSummonFromExLastTurn = 0; + int enemySpSummonFromExThisTurn = 0; + bool enemySpSummonFromDeck = false; + bool enemySpSummonFromExtra = false; + + /// + /// Shuffle List and return a random-order card list + /// + public List ShuffleCardList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(result.Count); + int nextIndex = (index + Program.Rand.Next(result.Count - 1)) % result.Count; + ClientCard tempCard = result[index]; + result[index] = result[nextIndex]; + result[nextIndex] = tempCard; + } + return result; + } + + public void UpdateBanSpSummonFromExTurn(int newTurn) + { + if (Duel.Player == 1) newTurn -= 1; + banSpSummonFromExTurn = Math.Max(banSpSummonFromExTurn, newTurn); + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false, bool ignoreCurrentDestroy = false) + { + List floodagateList = Enemy.GetMonsters().Where(c => c?.Data != null && + c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget()) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(c))).ToList(); + if (floodagateList.Count() > 0) + { + floodagateList.Sort(CardContainer.CompareCardAttack); + floodagateList.Reverse(); + return floodagateList[0]; + } + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.IsMonsterDangerous() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget()) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(c))).ToList(); + if (dangerList.Count() > 0) + { + dangerList.Sort(CardContainer.CompareCardAttack); + dangerList.Reverse(); + return dangerList[0]; + } + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.IsMonsterInvincible() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget()) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(c))).ToList(); + if (invincibleList.Count() > 0) + { + invincibleList.Sort(CardContainer.CompareCardAttack); + invincibleList.Reverse(); + return invincibleList[0]; + } + + if (attack >= 0) + { + if (attack == 0) + attack = Util.GetBestAttack(Bot); + List betterList = Enemy.MonsterZone.GetMonsters() + .Where(card => card.GetDefensePower() >= attack && card.GetDefensePower() > 0 && card.IsAttack() && (!canBeTarget || !card.IsShouldNotBeTarget()) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList(); + if (betterList.Count() > 0) + { + betterList.Sort(CardContainer.CompareCardAttack); + betterList.Reverse(); + return betterList[0]; + } + } + return null; + } + + public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreNormalSpell = false) + { + List resultList = new List(); + + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (floodagateList.Count() > 0) + { + floodagateList.Sort(CardContainer.CompareCardAttack); + floodagateList.Reverse(); + resultList.AddRange(floodagateList); + } + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !resultList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (problemEnemySpellList.Count() > 0) + { + resultList.AddRange(ShuffleCardList(problemEnemySpellList)); + } + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (dangerList.Count() > 0 + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) + { + dangerList.Sort(CardContainer.CompareCardAttack); + dangerList.Reverse(); + resultList.AddRange(dangerList); + } + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (invincibleList.Count() > 0) + { + invincibleList.Sort(CardContainer.CompareCardAttack); + invincibleList.Reverse(); + resultList.AddRange(invincibleList); + } + + List enemyMonsters = Enemy.GetMonsters().ToList(); + if (enemyMonsters.Count() > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + foreach(ClientCard target in enemyMonsters) + { + if (target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2) ) + { + if (!canBeTarget || !(target.IsShouldNotBeTarget() || target.IsShouldNotBeMonsterTarget())) + { + if (!resultList.Contains(target)) + { + resultList.Add(target); + } + } + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous)).ToList(); + if (spells.Count() > 0 && !ignoreNormalSpell) + { + resultList.AddRange(ShuffleCardList(spells)); + } + + return resultList; + } + + public ClientCard GetBestEnemyMonster(bool onlyFaceup = false, bool canBeTarget = false, bool ignoreCurrentDestroy = false) + { + ClientCard card = GetProblematicEnemyMonster(0, canBeTarget, ignoreCurrentDestroy); + if (card != null) + return card; + + card = Enemy.MonsterZone.Where(c => c?.Data != null && c.HasType(CardType.Monster) && c.IsFaceup() + && !(canBeTarget && c.IsShouldNotBeTarget()) && (!ignoreCurrentDestroy || currentDestroyCardList.Contains(c))) + .OrderByDescending(c => c.Attack).FirstOrDefault(); + if (card != null) + return card; + + List monsters = Enemy.GetMonsters().Where(c => !ignoreCurrentDestroy || currentDestroyCardList.Contains(c)).ToList(); + + // after GetHighestAttackMonster, the left monsters must be face-down. + if (monsters.Count() > 0 && !onlyFaceup) + return ShuffleCardList(monsters)[0]; + + return null; + } + + public ClientCard GetBestEnemySpell(bool onlyFaceup = false, bool canBeTarget = false) + { + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (problemEnemySpellList.Count() > 0) + { + return ShuffleCardList(problemEnemySpellList)[0]; + } + + List spells = Enemy.GetSpells().Where(card => !(card.IsFaceup() && card.IsCode(_CardId.EvenlyMatched))).ToList(); + + List faceUpList = spells.Where(ecard => ecard.IsFaceup() && + ecard.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous)).ToList(); + if (faceUpList.Count() > 0) + { + return ShuffleCardList(faceUpList)[0]; + } + + if (spells.Count() > 0 && !onlyFaceup) + { + return ShuffleCardList(spells)[0]; + } + + return null; + } + + public ClientCard GetBestEnemyCard(bool onlyFaceup = false, bool canBeTarget = false, bool checkGrave = false) + { + ClientCard card = GetBestEnemyMonster(onlyFaceup, canBeTarget); + if (card != null) + { + return card; + } + + card = GetBestEnemySpell(onlyFaceup, canBeTarget); + if (card != null) + { + return card; + } + + if (checkGrave && Enemy.Graveyard.Count() > 0) + { + List graveMonsterList = Enemy.Graveyard.GetMatchingCards(c => c.IsMonster()).ToList(); + if (graveMonsterList.Count() > 0) + { + graveMonsterList.Sort(CardContainer.CompareCardAttack); + graveMonsterList.Reverse(); + return graveMonsterList[0]; + } + return ShuffleCardList(Enemy.Graveyard.ToList())[0]; + } + + return null; + } + + /// + /// check enemy's dangerous card in grave + /// + public List GetDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && (card.HasSetcode(SetcodeOrcust) || card.HasSetcode(SetcodePhantom))).ToList(); + List dangerMonsterIdList = new List{ + 99937011, 63542003, 9411399, 28954097, 30680659, CardId.PSYFramelordOmega + }; + result.AddRange(Enemy.Graveyard.GetMatchingCards(card => dangerMonsterIdList.Contains(card.Id))); + return result; + } + + public List GetNormalEnemyTargetList(bool canBeTarget = true, bool targetKnightmare = true, bool ignoreCurrentDestroy = false) + { + List targetList = GetProblematicEnemyCardList(canBeTarget); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && !card.IsCode(CardId.KnightmareCorruptorIblee) && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleCardList(Enemy.GetSpells().Where(card => !ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)).ToList())); + targetList.AddRange(ShuffleCardList(Enemy.GetMonsters().Where(card => card.IsFacedown() && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList())); + if (targetKnightmare) + { + List enemyKnightmare = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) && card.IsCode(CardId.KnightmareCorruptorIblee) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList(); + targetList.AddRange(enemyKnightmare); + } + + return targetList; + } + + public List GetMonsterListForTargetNegate(bool canBeMonsterTarget = false, bool canBeTrapTarget = false) + { + List resultList = new List(); + if (CheckWhetherNegated()) + { + return resultList; + } + + // negate before used + ClientCard target = Enemy.MonsterZone.FirstOrDefault(card => card?.Data != null + && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && !card.IsShouldNotBeTarget() + && (!canBeMonsterTarget || !card.IsShouldNotBeMonsterTarget()) && (!canBeTrapTarget || !card.IsShouldNotBeSpellTrapTarget()) + && !currentNegateMonsterList.Contains(card)); + if (target != null) + { + resultList.Add(target); + } + + // negate monster effect on the field + foreach (ClientCard chainingCard in Duel.CurrentChain) + { + if (chainingCard.Location == CardLocation.MonsterZone && chainingCard.Controller == 1 && !chainingCard.IsDisabled() + && (!canBeMonsterTarget || !chainingCard.IsShouldNotBeMonsterTarget()) && (!canBeTrapTarget || !chainingCard.IsShouldNotBeSpellTrapTarget()) + && !chainingCard.IsShouldNotBeTarget() && !currentNegateMonsterList.Contains(chainingCard)) + { + resultList.Add(chainingCard); + } + } + + return resultList; + } + + /// + /// Get ritual monster/spell's ids that need to search, in order to perform ritual summon. + /// + public List GetNeedSearchRitualCardIdList() + { + List result = new List(); + + bool canSearchAlbaZoa = !Bot.HasInHand(CardId.DogmatikaAlbaZoa) && CheckRemainInDeck(CardId.DogmatikaAlbaZoa) > 0; + int totalLevelInGY = Bot.Graveyard.Where(card => card != null && card.HasType(CardType.Fusion | CardType.Synchro)).Sum(c => (int?)c.Level ?? 0); + + bool needSearchAlbaZoa = Bot.HasInHandOrInSpellZone(CardId.DogmatikaLamity) && Bot.HasInExtra(CardId.DespianLuluwalilith) && canSearchAlbaZoa; + if (Bot.HasInHandOrInGraveyard(CardId.DogmatikaMacabre)) + { + needSearchAlbaZoa |= totalLevelInGY >= 12 && canSearchAlbaZoa; + } + if (needSearchAlbaZoa) + { + result.Add(CardId.DogmatikaAlbaZoa); + } + + if (Bot.HasInHand(CardId.DogmatikaAlbaZoa) && Bot.HasInExtra(CardId.DespianLuluwalilith) && !Bot.HasInHandOrInSpellZone(CardId.DogmatikaLamity) + && CheckRemainInDeck(CardId.DogmatikaLamity) > 0) + { + result.Add(CardId.DogmatikaLamity); + } + + if (Bot.HasInHand(CardId.DogmatikaAlbaZoa) && !Bot.HasInHandOrInSpellZone(CardId.DogmatikaMacabre) && CheckRemainInDeck(CardId.DogmatikaMacabre) > 0 + && totalLevelInGY >= 12) + { + result.Add(CardId.DogmatikaMacabre); + } + + return result; + } + + public ClientCard GetExtraToDiscard(int baseAtk = 0, ClientCard avoidDestroyEnemyCard = null) + { + ClientCard selectResult = null; + // Ntss + if (baseAtk <= 2500 && Bot.HasInExtra(CardId.ElderEntityNtss) && CheckCalledbytheGrave(CardId.ElderEntityNtss) == 0) + { + List destroyList = GetNormalEnemyTargetList(true, false); + if (destroyList.Count() > 0) + { + if (!(destroyList.Count() == 1 && destroyList[0] == avoidDestroyEnemyCard)) + { + selectResult = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ElderEntityNtss)); + if (selectResult != null) + { + return selectResult; + } + } + } + } + + // Garura + if (baseAtk <= 1500 && Bot.HasInExtra(CardId.GaruraWingsOfResonantLife) && CheckCalledbytheGrave(CardId.GaruraWingsOfResonantLife) == 0 + && !activatedCardIdList.Contains(CardId.GaruraWingsOfResonantLife) && !enemyActivateLockBird) + { + selectResult = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.GaruraWingsOfResonantLife)); + if (selectResult != null) + { + return selectResult; + } + } + + // Ash Dragon + if (baseAtk <= 2500 && Bot.HasInExtra(CardId.TitanikladTheAshDragon) && CheckCalledbytheGrave(CardId.TitanikladTheAshDragon) == 0 + && !discardExtraThisTurn.Contains(CardId.TitanikladTheAshDragon) && !enemyActivateLockBird) + { + bool successFlag = !activatedCardIdList.Contains(CardId.DogmatikaEcclesia) && CheckRemainInDeck(CardId.DogmatikaEcclesia) > 0; + successFlag |= Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika)) && !Bot.HasInHand(CardId.DogmatikaFleurdelis) && CheckRemainInDeck(CardId.DogmatikaFleurdelis) > 0; + if (successFlag) + { + selectResult = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.TitanikladTheAshDragon)); + if (selectResult != null) + { + return selectResult; + } + } + } + + // dusk dragon + if (baseAtk <= 2500 && Bot.HasInExtra(CardId.GranguignolTheDuskDragon)) + { + bool successFlag = Bot.HasInExtra(CardId.DespianLuluwalilith); + successFlag |= CheckRemainInDeck(CardId.DogmatikaEcclesia, CardId.DogmatikaFleurdelis, CardId.DogmatikaMaximus) > 0; + if (successFlag) + { + selectResult = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.GranguignolTheDuskDragon)); + if (selectResult != null) + { + return selectResult; + } + } + } + + if (baseAtk <= 600 && Bot.HasInExtra(CardId.HeraldOfTheArcLight) && !enemyActivateLockBird) + { + if (GetNeedSearchRitualCardIdList().Count() > 0) + { + selectResult = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.HeraldOfTheArcLight)); + if (selectResult != null) + { + return selectResult; + } + } + } + + if (baseAtk <= 2800 && Bot.HasInExtra(CardId.PSYFramelordOmega)) + { + selectResult = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.PSYFramelordOmega)); + if (selectResult != null) + { + return selectResult; + } + } + + List discardableList = Bot.ExtraDeck.Where(card => card != null && card.Attack >= baseAtk).ToList(); + if (discardableList.Count() > 0) + { + discardableList.Sort(CardContainer.CompareCardAttack); + return discardableList[0]; + } + + return selectResult; + } + + /// + /// Check whether negate opposite's effect and clear flag + /// + public void CheckDeactiveFlag() + { + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && Duel.LastChainPlayer == 1) + { + if (lastChainCard.IsCode(_CardId.MaxxC)) enemyActivateMaxxC = false; + if (lastChainCard.IsCode(_CardId.LockBird)) enemyActivateLockBird = false; + if (lastChainCard.IsCode(CardId.DimensionShifter)) dimensionShifterCount = 0; + if (lastChainCard.Controller == 1 && lastChainCard.Location == CardLocation.MonsterZone) + { + currentNegateMonsterList.Add(lastChainCard); + } + } + } + + /// + /// Check negated turn count of id + /// + public int CheckCalledbytheGrave(int id) + { + if (currentNegatingIdList.Contains(id)) return 1; + if (DefaultCheckWhetherCardIdIsNegated(id)) return 1; + return 0; + } + + /// + /// Check remain cards in deck + /// + /// Card's ID + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + + public int CheckRemainInDeck(params int[] ids) + { + int sumResult = 0; + foreach (int id in ids) + { + sumResult += CheckRemainInDeck(id); + } + + return sumResult; + } + + /// + /// Whether spell or trap will be negate. If so, return true. + /// + /// is counter trap + /// check target + /// + public bool CheckSpellWillBeNegate(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.RoyalDecree, true) || Bot.HasInSpellZone(CardId.RoyalDecree, true)) return true; + } + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceList.Contains(selfSeq)) { + return true; + } + } + // how to get here? + return false; + } + + /// + /// Check whether'll be negated + /// + /// check whether card itself is disabled. + public bool CheckWhetherNegated(bool toFieldCheck = false) + { + if ((Card.IsSpell() || Card.IsTrap()) && CheckSpellWillBeNegate()){ + return true; + } + if (DefaultCheckWhetherCardIsNegated(Card)) + { + return true; + } + if (Card.IsMonster() && (toFieldCheck || Card.Location == CardLocation.MonsterZone)) + { + if (toFieldCheck || Card.IsDefense()) + { + if (Enemy.MonsterZone.Any(card => CheckNumber41(card)) || Bot.MonsterZone.Any(card => CheckNumber41(card))) + { + return true; + } + } + if (Enemy.HasInSpellZone(CardId.SkillDrain, true, true)) + { + return true; + } + } + return false; + } + + public bool CheckNumber41(ClientCard card) + { + return card != null && card.IsFaceup() && card.IsCode(CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled(); + } + + /// + /// Check whether cards will be removed. If so, do not send cards to grave. + /// + public bool CheckWhetherWillbeRemoved() + { + if (dimensionShifterCount > 0) return true; + List checkIdList = new List { CardId.BanisheroftheRadiance, CardId.BanisheroftheLight, CardId.MacroCosmos, CardId.DimensionalFissure }; + foreach (int cardid in checkIdList) + { + List fields = new List { Bot, Enemy }; + foreach (ClientField cf in fields) + { + if (cf.HasInMonstersZone(cardid, true) || cf.HasInSpellZone(cardid, true)) + { + return true; + } + } + } + return false; + } + + /// + /// Check whether bot is at advantage. + /// + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && + (!Bot.GetMonsters().Any(card => card.IsFaceup() && !card.IsCode(CardId.KnightmareCorruptorIblee)) || (Duel.Player == 0 && Duel.Turn == 1))) + { + return true; + } + return false; + } + + public bool CheckShouldNoMoreSpSummon() + { + if (CheckAtAdvantage() && enemyActivateMaxxC && Util.IsTurn1OrMain2()) + { + bool successFlag = false; + successFlag |= Bot.HasInHandOrInSpellZone(CardId.DogmatikaPunishment); + successFlag |= Bot.GetMonsters().Any(card => card.IsFaceup() && card.Level >= 7 && card.HasRace(CardRace.SpellCaster)); + successFlag |= Bot.HasInHand(CardId.DogmatikaFleurdelis) + && Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika)); + return successFlag; + } + return false; + } + + /// + /// Check whether last chain card should be disabled. + /// + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + if (lastcard.IsMonster() && lastcard.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (notToNegateIdList.Contains(lastcard.Id)) return false; + if (lastcard.IsCode(_CardId.LockBird)) + { + bool needToSearch = false; + List searchEffectIdList = new List{ CardId.DogmatikaEcclesia, CardId.NadirServant }; + foreach (int checkId in searchEffectIdList) + { + if (Bot.HasInHandOrInSpellZone(checkId) && !activatedCardIdList.Contains(checkId)) needToSearch = true; + } + if (discardExtraThisTurn.Contains(CardId.TitanikladTheAshDragon)) needToSearch = true; + + if (!needToSearch) return false; + } + + return true; + } + + public bool CheckHasExtraOnField(ClientCard exceptCard = null) + { + List fieldMonsterList = Bot.GetMonsters(); + fieldMonsterList.AddRange(Enemy.GetMonsters()); + bool hasExtraOnField = fieldMonsterList.Any(card => card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && card != exceptCard); + return hasExtraOnField; + } + + /// + /// go first + /// + public override bool OnSelectHand() + { + return true; + } + + public override int OnSelectOption(IList options) + { + // override for iris + List checkOptionList = new List{Util.GetStringId(CardId.ThesIrisSwordsoul, 4), Util.GetStringId(CardId.ThesIrisSwordsoul, 2)}; + foreach (int checkOption in checkOptionList) + { + for (int i = 0; i < options.Count(); ++ i) + { + if (options[i] == checkOption) return i; + } + } + return base.OnSelectOption(options); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2) + { + bool turnDefense = false; + if (cardData.Attack <= cardData.Defense) + { + turnDefense = true; + } + if (turnDefense) + { + return CardPosition.FaceUpDefence; + } + } + if (Duel.Player == 1) + { + if (!cardData.HasType(CardType.Ritual) || cardData.Defense >= cardData.Attack || Util.IsOneEnemyBetterThanValue(cardData.Attack, true)) + { + return CardPosition.FaceUpDefence; + } + } else if (cardData.HasType(CardType.Ritual)) + { + return CardPosition.FaceUpAttack; + } + int cardAttack = cardData.Attack; + if (cardId == CardId.DogmatikaFleurdelis && !activatedCardIdList.Contains(cardId + 1) && Duel.Player == 0) cardAttack += 500; + int bestBotAttack = Math.Max(Util.GetBestAttack(Bot), cardAttack); + if (Util.IsAllEnemyBetterThanValue(bestBotAttack, true)) + { + return CardPosition.FaceUpDefence; + } + } + return base.OnSelectPosition(cardId, positions); + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (Util.ChainContainPlayer(1) && hint == HintMsg.Remove && Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + int botCount = Bot.GetMonsterCount() + Bot.GetSpellCount(); + int oppositeCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount(); + if (botCount - oppositeCount == min && min == max) + { + Logger.DebugWriteLine("=== Evenly Matched activated."); + List banishList = new List(); + List botMonsters = Bot.GetMonsters().Where(card => !card.HasType(CardType.Token)).ToList(); + + // non-ritual monster + List faceDownMonsters = botMonsters.Where(card => card.IsFacedown()).ToList(); + banishList.AddRange(faceDownMonsters); + List nonSynchroMonsters = botMonsters.Where(card => !card.HasType(CardType.Ritual) && !banishList.Contains(card)).ToList(); + nonSynchroMonsters.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(nonSynchroMonsters); + + // spells + List spells = Bot.GetSpells(); + banishList.AddRange(ShuffleCardList(spells)); + + // ritual monster + List synchroMonsters = botMonsters.Where(card => card.HasType(CardType.Ritual) && !banishList.Contains(card)).ToList(); + synchroMonsters.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(synchroMonsters); + + return Util.CheckSelectCount(banishList, cards, min, max); + } + } + if (maximusDiscardExtraIdList.Count() > 0 && min == 1 && max == 1 && hint == HintMsg.ToGrave) + { + List discardList = new List(); + foreach (int checkId in maximusDiscardExtraIdList) + { + ClientCard discardTarget = cards.FirstOrDefault(card => card.IsCode(checkId)); + if (discardTarget != null) discardList.Add(discardTarget); + } + if (discardList.Count() >= max) + { + if (discardList.Count() > 0) discardExtraThisTurn.Add(discardList[0]?.Id ?? 0); + return Util.CheckSelectCount(discardList, cards, min, max); + } + } + if (matrixActivating && hint == HintMsg.ToGrave && min == 1 && max == 1) + { + bool extraFlag = true; + // 0=not yet, 1=only bot, 2=only enemy, 3=mixed & skip + int enemyFlag = 0; + foreach (ClientCard card in cards) + { + extraFlag &= card.Location == CardLocation.Extra; + if (enemyFlag == 0) enemyFlag = card.Controller + 1; + else if (enemyFlag < 3 && enemyFlag != card.Controller + 1) enemyFlag = 3; + } + Logger.DebugWriteLine("===Matrix: extraFlag = " + extraFlag.ToString() + ", enemyFlag = " + enemyFlag.ToString()); + if (extraFlag && enemyFlag < 3) + { + List discardList = new List(); + // discard bot's extra + if (enemyFlag == 1) + { + ClientCard elder = null; + ClientCard ashDragon = null; + ClientCard garura = null; + ClientCard arcLight = null; + ClientCard psy = null; + ClientCard duskDragon = null; + ClientCard lilith = null; + foreach (ClientCard card in cards) + { + if (card.Id == CardId.ElderEntityNtss) elder = card; + if (card.Id == CardId.TitanikladTheAshDragon) ashDragon = card; + if (card.Id == CardId.GaruraWingsOfResonantLife) garura = card; + if (card.Id == CardId.HeraldOfTheArcLight) arcLight = card; + if (card.Id == CardId.PSYFramelordOmega) psy = card; + if (card.Id == CardId.GranguignolTheDuskDragon) duskDragon = card; + if (card.Id == CardId.DespianLuluwalilith) lilith = card; + } + + List destroyList = GetNormalEnemyTargetList(true, true, true); + if (elder != null && destroyList.Count() > 0) discardList.Add(elder); + if (ashDragon != null && !activatedCardIdList.Contains(CardId.TitanikladTheAshDragon) && !discardEnemyExtraIdList.Contains(CardId.TitanikladTheAshDragon)) + { + bool checkFlag = !activatedCardIdList.Contains(CardId.DogmatikaEcclesia) && CheckRemainInDeck(CardId.DogmatikaEcclesia) > 0 + && CheckCalledbytheGrave(CardId.DogmatikaEcclesia) == 0; + checkFlag |= CheckRemainInDeck(CardId.DogmatikaFleurdelis) > 0 && !Bot.HasInHand(CardId.DogmatikaFleurdelis) && !enemyActivateLockBird; + if (checkFlag) discardList.Add(ashDragon); + } + if (garura != null && !activatedCardIdList.Contains(CardId.GaruraWingsOfResonantLife) && !enemyActivateLockBird) discardList.Add(garura); + if (arcLight != null && GetNeedSearchRitualCardIdList().Count() > 0) discardList.Add(arcLight); + if (psy != null) discardList.Add(psy); + if (duskDragon != null) discardList.Add(duskDragon); + if (lilith != null && !activatedCardIdList.Contains(CardId.DespianLuluwalilith) && !discardEnemyExtraIdList.Contains(CardId.DespianLuluwalilith)) + { + discardList.Add(lilith); + } + + if (discardList.Count() > 0) discardExtraThisTurn.Add(discardList[0]?.Id ?? 0); + } + // discard enemy's extra + if (enemyFlag == 2) + { + checkedEnemyExtra = true; + avoid2Monster = false; + confirmLink2 = false; + List discardIfKnightmare = new List{ 96380700, 48068378, 14812471, 32995276, 30342076, CardId.Linguriboh, 3679218 }; + foreach (ClientCard card in cards) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(card.Id); + if (cardData != null) + { + confirmLink2 |= cardData.HasType(CardType.Link) && cardData.Level <= 2; + avoid2Monster |= (cardData.HasType(CardType.Link) && cardData.Level <= 2) || cardData.HasType(CardType.Synchro | CardType.Xyz); + if (Enemy.HasInMonstersZone(CardId.KnightmareCorruptorIblee)) + { + if (discardIfKnightmare.Contains(card.Id)) discardList.Add(card); + } + } + } + discardList = ShuffleCardList(discardList); + + // avoid link summon + foreach (ClientCard card in cards) + { + if (discardList.Contains(card)) continue; + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(card.Id); + if (cardData != null && Enemy.HasInMonstersZone(CardId.KnightmareCorruptorIblee) + && cardData.HasType(CardType.Link) && cardData.Level <= Enemy.GetMonsterCount()) + { + discardList.Add(card); + } + } + + // discard important card + foreach (ClientCard card in cards) + { + if (discardList.Contains(card)) continue; + if (discardEnemyExtraIdList.Contains(card.Id)) discardList.Add(card); + } + + // discard single card first + List singleCardList = new List(); + List multiCardList = new List(); + foreach (ClientCard card in cards) + { + if (discardList.Contains(card)) continue; + if (cards.Any(oc => card != oc && card.IsCode(oc.Id))) multiCardList.Add(card); + else singleCardList.Add(card); + } + + discardList.AddRange(singleCardList.OrderByDescending(c => { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(c.Id); + return cardData?.Attack ?? 0; + })); + discardList.AddRange(multiCardList.OrderByDescending(c => { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(c.Id); + return cardData?.Attack ?? 0; + })); + } + + if (discardList.Count() > 0) return Util.CheckSelectCount(discardList, cards, min, max); + } + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + public override void OnNewTurn() + { + if (Duel.Turn <= 1) + { + banSpSummonFromExTurn = 0; + checkedEnemyExtra = false; + avoid2Monster = true; + dimensionShifterCount = 0; + + enemySpSummonFromExLastTurn = 0; + enemySpSummonFromExThisTurn = 0; + } + enemyActivateMaxxC = false; + enemyActivateLockBird = false; + omegaActivateCount = 0; + enemySpSummonFromExLastTurn = enemySpSummonFromExThisTurn; + enemySpSummonFromExThisTurn = 0; + currentNegatingIdList.Clear(); + + if (dimensionShifterCount > 0) dimensionShifterCount--; + infiniteImpermanenceList.Clear(); + + summoned = false; + activatedCardIdList.Clear(); + discardExtraThisTurn.Clear(); + activatedMatrixList.Clear(); + if (Duel.Player == 1 && banSpSummonFromExTurn > 0) + { + banSpSummonFromExTurn -= 1; + } + base.OnNewTurn(); + } + + public override void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + if (previousControler == 1 && currentLocation == (int)CardLocation.MonsterZone) + { + if (previousLocation == (int)CardLocation.Deck) enemySpSummonFromDeck = true; + if (previousLocation == (int)CardLocation.Extra) + { + enemySpSummonFromExtra = true; + enemySpSummonFromExThisTurn ++; + } + } + + base.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + public override BattlePhaseAction OnBattle(IList attackers, IList defenders) + { + if (attackers.Count() == 1 && defenders.Count() == 1) + { + if (defenders[0].IsCode(CardId.KnightmareCorruptorIblee) && !confirmLink2) return new BattlePhaseAction(BattlePhaseAction.BattleAction.ToMainPhaseTwo); + } + if (attackers.Count() > 0 && defenders.Count() > 0) + { + List sortedAttacker = attackers.OrderBy(card => card.Attack).ToList(); + for (int k = 0; k < sortedAttacker.Count; ++k) + { + ClientCard attacker = sortedAttacker[k]; + attacker.IsLastAttacker = k == sortedAttacker.Count - 1; + BattlePhaseAction result = OnSelectAttackTarget(attacker, defenders); + if (result != null) + return result; + } + } + + return base.OnBattle(attackers, defenders); + } + + public override BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList defenders) + { + foreach (ClientCard defender in defenders) + { + attacker.RealPower = attacker.Attack; + defender.RealPower = defender.GetDefensePower(); + if (!OnPreBattleBetween(attacker, defender)) + continue; + + if (attacker.RealPower > defender.RealPower) + return AI.Attack(attacker, defender); + + if (attacker.RealPower == defender.RealPower && defender.IsAttack() && Bot.GetMonsterCount() >= Enemy.GetMonsterCount()) + return AI.Attack(attacker, defender); + } + + if (attacker.CanDirectAttack) + return AI.Attack(attacker, null); + + return null; + } + + public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + if (!defender.IsMonsterHasPreventActivationEffectInBattle()) + { + if (!activatedCardIdList.Contains(CardId.DogmatikaFleurdelis + 1) && Bot.HasInMonstersZone(CardId.DogmatikaFleurdelis, true, false, true) + && attacker.HasSetcode(SetcodeDogmatika)) + { + attacker.RealPower += 500; + } + } + return base.OnPreBattleBetween(attacker, defender); + } + + public override void OnChaining(int player, ClientCard card) + { + if (card == null) return; + + if (player == 1) + { + if (card.IsCode(_CardId.InfiniteImpermanence) && !DefaultCheckWhetherCardIdIsNegated(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == card) + { + infiniteImpermanenceList.Add(4-i); + break; + } + } + } + } + base.OnChaining(player, card); + } + + public override void OnChainSolved(int chainIndex) + { + ChainInfo currentCard = Duel.GetCurrentSolvingChainInfo(); + if (currentCard != null && !Duel.IsCurrentSolvingChainNegated() && currentCard.ActivatePlayer == 1) + { + if (currentCard.IsCode(_CardId.MaxxC)) + enemyActivateMaxxC = true; + if (currentCard.IsCode(_CardId.LockBird)) + enemyActivateLockBird = true; + if (currentCard.IsCode(CardId.DimensionShifter)) + dimensionShifterCount = 2; + if (currentCard.IsCode(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == currentCard.RelatedCard) + { + infiniteImpermanenceList.Add(4 - i); + break; + } + } + } + } + } + + public override void OnChainEnd() + { + currentNegateMonsterList.Clear(); + currentDestroyCardList.Clear(); + maximusDiscardExtraIdList.Clear(); + matrixActivating = false; + base.OnChainEnd(); + } + + /// + /// Select spell/trap's place randomly to avoid InfiniteImpermanence and so on. + /// + /// Card to set(default current card) + /// Whether need to avoid InfiniteImpermanence + /// Whether need to avoid set in this place + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceList.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public bool DogmatikaAlbaZoaActivate() + { + if (CheckWhetherNegated()) return false; + if (Enemy.GetMonsters().Any(card => card != null && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)) + && Duel.Phase == DuelPhase.Main1 && Enemy.ExtraDeck.Count() > 1) + { + return false; + } + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool ThesIrisSwordsoulActivate() + { + if (CheckWhetherNegated()) return false; + if (Card.Location == CardLocation.Hand) + { + if (CheckShouldNoMoreSpSummon()) + { + return false; + } + return true; + } + if (enemySpSummonFromDeck || enemySpSummonFromExtra) return true; + + return false; + } + + public bool ClearIrisFlag() + { + enemySpSummonFromDeck = false; + enemySpSummonFromExtra = false; + + return false; + } + + public bool DogmatikaFleurdelisActivate() + { + if (CheckWhetherNegated()) return false; + if (Card.Location == CardLocation.Hand) + { + bool canNegate = Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika)) && Enemy.GetMonsters().Any(card => card.IsFaceup()); + if (canNegate) + { + // for negate effect + List shouldNegateList = GetMonsterListForTargetNegate(true); + if (shouldNegateList.Count() > 0) + { + ClientCard target = shouldNegateList[0]; + currentNegateMonsterList.Add(target); + AI.SelectYesNo(true); + AI.SelectCard(target); + activatedCardIdList.Add(CardId.DogmatikaFleurdelis); + return true; + } + // for iris + if (Bot.HasInHand(CardId.ThesIrisSwordsoul)) + { + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true); + if (target != null) + { + AI.SelectYesNo(true); + AI.SelectCard(target); + } else { + List enemyTargetList = ShuffleCardList(Enemy.GetMonsters().Where(card => card.IsFaceup() && !card.IsDisabled()).ToList()); + if (enemyTargetList.Count() > 0) + { + AI.SelectYesNo(true); + AI.SelectCard(enemyTargetList); + } else AI.SelectYesNo(false); + } + activatedCardIdList.Add(CardId.DogmatikaFleurdelis); + return true; + } + } + // for total attack + if (Duel.Player == 0 && Enemy.GetMonsterCount() == 0) { + int totalAttack = Util.GetTotalAttackingMonsterAttack(0); + if (totalAttack < Enemy.LifePoints) + { + totalAttack += Bot.GetMonsters().Where(card => card.HasSetcode(SetcodeDogmatika)).Count() * 500 + 3000; + if (totalAttack >= Enemy.LifePoints) + { + activatedCardIdList.Add(CardId.DogmatikaFleurdelis); + AI.SelectYesNo(false); + return true; + } + } + } + // for avoid lose + if (Duel.Player == 1 && Bot.GetMonsterCount() == 0 && Util.GetTotalAttackingMonsterAttack(1) >= Bot.LifePoints + && Duel.Phase == DuelPhase.Main1 && (CurrentTiming & hintTimingMainEnd) != 0 && Duel.Turn > 1) + { + activatedCardIdList.Add(CardId.DogmatikaFleurdelis); + List enemyTargetList = ShuffleCardList(Enemy.GetMonsters().Where(card => card.IsFaceup() && !card.IsDisabled()).ToList()); + if (enemyTargetList.Count() > 0) + { + AI.SelectYesNo(true); + AI.SelectCard(enemyTargetList); + } + else + { + AI.SelectYesNo(false); + } + return true; + } + } + if (Card.Location == CardLocation.MonsterZone) + { + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public bool DogmatikaFleurdelisDelayActivate() + { + if (CheckWhetherNegated()) return false; + if (Card.Location == CardLocation.Hand) + { + bool checkFlag = false; + bool notQuickTiming = Duel.LastChainPlayer == -1 && CurrentTiming <= 0; + if (Duel.Player == 0 && Duel.Phase == DuelPhase.Main1 && notQuickTiming && Duel.Turn > 1) + { + Logger.DebugWriteLine("=== timing: " + CurrentTiming.ToString()); + int attack = Util.GetBestAttack(Bot); + List currentBetterList = Enemy.MonsterZone.GetMonsters().Where(card => card.GetDefensePower() >= attack).ToList(); + List newBetterList = Enemy.MonsterZone.GetMonsters().Where(card => card.GetDefensePower() >= 3000).ToList(); + if (currentBetterList.Count() > newBetterList.Count()) checkFlag = true; + } + if ((Bot.HasInHandOrInSpellZone(CardId.SinfulSpoilsOfDoom_Rciela) && Duel.Player == 0 && notQuickTiming) + || Bot.GetSpells().Any(card => card.IsCode(CardId.SinfulSpoilsOfDoom_Rciela) && card.IsFacedown())) + { + if (!Bot.GetMonsters().Any(card => card.IsFaceup() && card.Level >= 7 && card.HasRace(CardRace.SpellCaster))) checkFlag = true; + } + if (checkFlag) + { + List enemyTargetList = ShuffleCardList(Enemy.GetMonsters().Where(card => card.IsFaceup() && !card.IsDisabled()).ToList()); + if (enemyTargetList.Count() > 0) + { + AI.SelectYesNo(true); + AI.SelectCard(enemyTargetList); + } + else AI.SelectYesNo(false); + activatedCardIdList.Add(CardId.DogmatikaFleurdelis); + return true; + } + } + return false; + } + + public bool DogmatikaMaximusActivate() + { + if (CheckWhetherNegated()) return false; + if (Card.Location == CardLocation.Hand) + { + if (CheckShouldNoMoreSpSummon()) return false; + // banish dump extra + List dumpIdCheck = new List{ CardId.ElderEntityNtss, CardId.GaruraWingsOfResonantLife, CardId.DespianLuluwalilith }; + foreach (int dumpId in dumpIdCheck) + { + IEnumerable checkList = Bot.GetGraveyardMonsters().Where(card => card.IsCode(dumpId)); + if (checkList.Count() > 1) + { + IEnumerable notSummonList = checkList.Where(card => card.ProcCompleted == 0); + if (notSummonList.Count() > 0) + { + AI.SelectCard(notSummonList.ToList()); + return true; + } + AI.SelectCard(checkList.ToList()); + return true; + } + } + + // find not summoned card + List notSummonedList = ShuffleCardList(Bot.Graveyard.Where(card => card != null && card.IsMonster() && card.ProcCompleted == 0 + && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)).ToList()); + if (notSummonedList.Count() > 0) + { + AI.SelectCard(notSummonedList); + return true; + } + + // sort by attack + List graveTargetList = Bot.Graveyard.Where(card => card != null && card.IsMonster() + && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)).OrderBy(card => card.Attack).ToList(); + if (graveTargetList.Count() > 0) + { + AI.SelectCard(graveTargetList); + return true; + } + } + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherWillbeRemoved()) return false; + List decidedToDiscard = new List(); + List checkDiscardIdList = new List{ CardId.ElderEntityNtss, CardId.HeraldOfTheArcLight, CardId.GaruraWingsOfResonantLife, + CardId.TitanikladTheAshDragon, CardId.GranguignolTheDuskDragon, CardId.PSYFramelordOmega, CardId.DespianLuluwalilith }; + foreach (int checkId in checkDiscardIdList) + { + if (Bot.HasInExtra(checkId) && !activatedCardIdList.Contains(checkId)) + { + if (checkId == CardId.ElderEntityNtss) + { + List destroyList = GetNormalEnemyTargetList(true, false); + if (destroyList.Count() == 0) continue; + } + if (enemyActivateLockBird && (checkId == CardId.HeraldOfTheArcLight || checkId == CardId.GaruraWingsOfResonantLife)) + { + continue; + } + if (checkId == CardId.HeraldOfTheArcLight) + { + if (Bot.HasInMonstersZone(CardId.DogmatikaAlbaZoa)) continue; + if (GetNeedSearchRitualCardIdList().Count() == 0) continue; + } + if (checkId == CardId.GaruraWingsOfResonantLife && activatedCardIdList.Contains(CardId.GaruraWingsOfResonantLife)) + { + continue; + } + if (discardExtraThisTurn.Contains(checkId) && (checkId == CardId.TitanikladTheAshDragon || checkId == CardId.DespianLuluwalilith)) + { + continue; + } + decidedToDiscard.Add(checkId); + } + } + + maximusDiscardExtraIdList.AddRange(decidedToDiscard); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + return true; + } + + return false; + } + + public bool DiabellstarTheBlackWitchSpSummon() + { + bool hasEmptyMonsterZone = false; + for (int i = 0; i < 5; ++ i) + { + if (Bot.MonsterZone[i] == null) + { + hasEmptyMonsterZone = true; + break; + } + } + if (hasEmptyMonsterZone) + { + if (Bot.HasInHandOrInSpellZone(CardId.WANTED_SeekerOfSinfulSpoils)) + { + AI.SelectCard(CardId.WANTED_SeekerOfSinfulSpoils); + return true; + } + if (activatedMatrixList.Count() > 0) + { + AI.SelectCard(activatedMatrixList); + return true; + } + if (Bot.GetSpells().Where(card => card.IsCode(CardId.DogmatikaMatrix)).Count() > 1) + { + AI.SelectCard(CardId.DogmatikaMatrix); + return true; + } + } + if (!Bot.HasInHand(CardId.DogmatikaFleurdelis) || Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika)).Count() > 1) + { + List checkIdList = new List{ CardId.DogmatikaEcclesia, CardId.DogmatikaMaximus}; + foreach (int checkId in checkIdList) + { + ClientCard costMonster = null; + if (activatedCardIdList.Contains(checkId)) costMonster = Bot.GetMonsters().FirstOrDefault(card => card.IsCode(checkId)); + if (costMonster == null) costMonster = Bot.GetMonsters().FirstOrDefault(card => card.IsCode(checkId) && card.IsDisabled()); + if (costMonster != null) + { + AI.SelectCard(costMonster); + return true; + } + } + } + if (hasEmptyMonsterZone) + { + List checkIdList = new List { CardId.KnightmareCorruptorIblee, CardId.ThesIrisSwordsoul }; + foreach (int checkId in checkIdList) + { + if (Bot.HasInHand(checkId)) + { + AI.SelectCard(checkId); + return true; + } + } + } + List faceDownMonsters = Bot.GetMonsters().Where(card => card.IsFacedown()).OrderBy(card => { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(card.Id); + if (cardData != null) + { + return cardData.Attack; + } + return card.Attack; + }).ToList(); + if (faceDownMonsters.Count() > 0) + { + AI.SelectCard(faceDownMonsters); + return true; + } + if (hasEmptyMonsterZone) + { + if (Bot.HasInHand(CardId.DogmatikaFleurdelis) && Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika)).Count() == 0) + { + AI.SelectCard(CardId.DogmatikaFleurdelis); + return true; + } + if (CheckRemainInDeck(CardId.DogmatikaMacabre) > 0) + { + ClientCard albaZoaInHand = Bot.Hand.FirstOrDefault(card => card.IsCode(CardId.DogmatikaAlbaZoa)); + if (albaZoaInHand != null) + { + AI.SelectCard(albaZoaInHand); + return true; + } + } + List dumpIdList = new List{ CardId.DogmatikaPunishment, _CardId.InfiniteImpermanence, _CardId.CalledByTheGrave, _CardId.AshBlossom, _CardId.MaxxC }; + foreach (int dumpId in dumpIdList) + { + int checkCount = Bot.Hand.Where(card => card.IsCode(dumpId)).Count(); + checkCount += Bot.SpellZone.Where(card => card != null && card.IsCode(dumpId)).Count(); + if (checkCount > 1) + { + AI.SelectCard(dumpId); + return true; + } + } + List extraCheckList = Bot.GetMonsters().Where(card => card.HasType(CardType.Fusion | CardType.Synchro | CardType.Link)) + .OrderBy(card => card.Attack).ToList(); + foreach (ClientCard checkCard in extraCheckList) + { + if (!Bot.HasInHand(CardId.DogmatikaFleurdelis) || CheckHasExtraOnField(checkCard)) + { + AI.SelectCard(checkCard); + return true; + } + } + } + if (Bot.GetMonsterCount() == 0 || CheckRemainInDeck(CardId.SinfulSpoilsOfDoom_Rciela) > 0) + { + List spellIdList = new List{ _CardId.CrossoutDesignator, _CardId.InfiniteImpermanence, _CardId.CalledByTheGrave, + CardId.DogmatikaPunishment, CardId.DogmatikaMacabre, CardId.DogmatikaLamity }; + foreach (int spellId in spellIdList) + { + if (Bot.HasInHandOrInSpellZone(spellId)) + { + AI.SelectCard(spellId); + return true; + } + } + } + + return false; + } + + public bool DiabellstarTheBlackWitchActivate() + { + if (CheckWhetherNegated()) return false; + if (Card.Location == CardLocation.MonsterZone) + { + AI.SelectCard(CardId.SinfulSpoilsOfDoom_Rciela, CardId.WANTED_SeekerOfSinfulSpoils); + SelectSTPlace(); + activatedCardIdList.Add(Card.Id); + return true; + } + + return false; + } + + public bool DogmatikaEcclesiaSummon() + { + if (enemyActivateLockBird) return false; + if (CheckWhetherNegated()) return false; + if (activatedCardIdList.Contains(Card.Id)) return false; + + summoned = true; + return true; + } + + public bool DogmatikaEcclesiaActivate() + { + if (CheckWhetherNegated()) return false; + // sp summon + if (Card.Location == CardLocation.Hand) + { + if (activatedCardIdList.Contains(Card.Id)) return false; + if (CheckShouldNoMoreSpSummon()) + { + if (!Bot.HasInHand(CardId.DogmatikaFleurdelis) || Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika))) + { + return false; + } + } + if (enemyActivateLockBird) + { + if (Bot.HasInHand(CardId.DogmatikaFleurdelis) && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika))) + { + return true; + } + return false; + } + return true; + } + // search + if (Card.Location == CardLocation.MonsterZone) + { + if ((Duel.Player == 0 && Duel.Phase == DuelPhase.End) || (Duel.Player == 1 && Duel.Phase < DuelPhase.End)) + { + if (!Bot.HasInHand(CardId.DogmatikaFleurdelis) && CheckRemainInDeck(CardId.DogmatikaFleurdelis) > 0) + { + AI.SelectCard(CardId.DogmatikaFleurdelis); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + return true; + } + } + + // for maxxc + if (CheckAtAdvantage() && enemyActivateMaxxC) + { + List checkIdListFirstPart = new List{ CardId.DogmatikaPunishment, CardId.DogmatikaFleurdelis }; + if (DogmatikaMatrixCanActivate()) + { + checkIdListFirstPart.Add(CardId.DogmatikaMatrix); + } + checkIdListFirstPart.AddRange(new List{ CardId.DogmatikaMaximus, CardId.DogmatikaAlbaZoa, CardId.DogmatikaMacabre, CardId.DogmatikaLamity }); + checkIdListFirstPart.Add(CardId.DogmatikaMatrix); + foreach (int checkId in checkIdListFirstPart) + { + if (!Bot.HasInHandOrInSpellZone(checkId) && CheckRemainInDeck(checkId) > 0) + { + AI.SelectCard(checkId); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + return true; + } + } + } + + // search matrix + bool canSearchMatrix = DogmatikaMatrixCanActivate() && !activatedCardIdList.Contains(CardId.DogmatikaMatrix) + && CheckRemainInDeck(CardId.DogmatikaMatrix) > 0 && !Bot.HasInHand(CardId.DogmatikaMatrix); + if (canSearchMatrix && Enemy.GetMonsterCount() > 0) + { + AI.SelectCard(CardId.DogmatikaMatrix); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + return true; + } + + // search for ritual + List needSearchRitualIdList = GetNeedSearchRitualCardIdList(); + bool canSearchMaximus = CheckRemainInDeck(CardId.DogmatikaMaximus) > 0 && !activatedCardIdList.Contains(CardId.DogmatikaMaximus) + && Bot.Graveyard.Where(card => card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)).Count() > 0; + if (needSearchRitualIdList.Count() > 0) + { + // matrix + if (canSearchMatrix) + { + AI.SelectCard(CardId.DogmatikaMatrix); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + return true; + } + // maximus + if (canSearchMaximus && Bot.HasInExtra(CardId.HeraldOfTheArcLight)) + { + AI.SelectCard(CardId.DogmatikaMaximus); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + return true; + } + + } + + // search maximus + if (canSearchMaximus) + { + AI.SelectCard(CardId.DogmatikaMaximus); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + return true; + } + + List checkIdListSecondPart = new List{ CardId.DogmatikaPunishment, CardId.DogmatikaFleurdelis }; + if (DogmatikaMatrixCanActivate()) + { + checkIdListSecondPart.Add(CardId.DogmatikaMatrix); + } + checkIdListSecondPart.AddRange(new List{ CardId.DogmatikaMaximus, CardId.DogmatikaAlbaZoa, CardId.DogmatikaMacabre, CardId.DogmatikaLamity }); + checkIdListSecondPart.Add(CardId.DogmatikaMatrix); + foreach (int checkId in checkIdListSecondPart) + { + if (!Bot.HasInHandOrInSpellZone(checkId) && CheckRemainInDeck(checkId) > 0) + { + AI.SelectCard(checkId); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + return true; + } + } + } + + return false; + } + + public bool AshBlossomActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (CheckAtAdvantage() && Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + return false; + } + if (DefaultAshBlossomAndJoyousSpring()) + { + CheckDeactiveFlag(); + return true; + } + return false; + } + + public bool MaxxCActivate() + { + if (CheckWhetherNegated() || Duel.LastChainPlayer == 0) return false; + if (Enemy.HasInMonstersZone(CardId.KnightmareCorruptorIblee, true, false, true) && !confirmLink2) return false; + return DefaultMaxxC(); + } + + public bool KnightmareCorruptorIbleeSummon() + { + if (banSpSummonFromExTurn > 0) return false; + if (CheckWhetherWillbeRemoved()) return false; + if (activatedCardIdList.Contains(CardId.KnightmareCorruptorIblee)) return false; + if (Bot.HasInExtra(CardId.SalamangreatAlmiraj) || Bot.HasInExtra(CardId.Linguriboh)) + { + summoned = true; + return true; + } + + if (Bot.HasInExtra(CardId.SPLittleKnight)) + { + // TODO + } + + return false; + } + + public bool KnightmareCorruptorIbleeActivate() + { + if (Util.IsTurn1OrMain2()) return true; + if (Duel.Turn > 1) + { + if (Bot.HasInHand(CardId.DogmatikaMatrix) && DogmatikaMatrixCanActivate()) + { + return true; + } + if (Enemy.GetMonsterCount() > 0) + { + return true; + } + } + return false; + } + + public bool NadirServantActivate() + { + if (CheckWhetherNegated() || CheckWhetherWillbeRemoved()) return false; + ClientCard discardExtra = null; + int searchId = 0; + + // search ecclesia + if (!activatedCardIdList.Contains(CardId.DogmatikaEcclesia) && CheckCalledbytheGrave(CardId.DogmatikaEcclesia) == 0 && !Bot.HasInHand(CardId.DogmatikaEcclesia)) + { + if (CheckHasExtraOnField() || !summoned) + { + if (Bot.HasInGraveyard(CardId.DogmatikaEcclesia) || CheckRemainInDeck(CardId.DogmatikaEcclesia) > 0) + { + searchId = CardId.DogmatikaEcclesia; + discardExtra = GetExtraToDiscard(1500, null); + } + } + } + + // search maximus + if (searchId == 0 || discardExtra == null) + { + if (!activatedCardIdList.Contains(CardId.DogmatikaMaximus) && CheckCalledbytheGrave(CardId.DogmatikaMaximus) == 0 + && Bot.HasInGraveyard(CardId.DogmatikaMaximus) || CheckRemainInDeck(CardId.DogmatikaMaximus) > 0) + { + searchId = CardId.DogmatikaMaximus; + discardExtra = GetExtraToDiscard(1500, null); + } + } + + // search Fleurdelis + if (searchId == 0 || discardExtra == null) + { + if (!Bot.HasInHand(CardId.DogmatikaFleurdelis) && Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika)) + && Bot.HasInGraveyard(CardId.DogmatikaFleurdelis) || CheckRemainInDeck(CardId.DogmatikaFleurdelis) > 0) + { + searchId = CardId.DogmatikaFleurdelis; + discardExtra = GetExtraToDiscard(2500, null); + } + } + + // search ecclesia for next turn + if (searchId == 0 || discardExtra == null) + { + if (Bot.HasInGraveyard(CardId.DogmatikaEcclesia) || CheckRemainInDeck(CardId.DogmatikaEcclesia) > 0) + { + searchId = CardId.DogmatikaEcclesia; + discardExtra = GetExtraToDiscard(1500, null); + } + } + + if (discardExtra != null && searchId > 0) + { + discardExtraThisTurn.Add(discardExtra?.Id ?? 0); + AI.SelectCard(discardExtra); + ClientCard targetInGY = Bot.Graveyard.FirstOrDefault(card => card != null && card.IsCode(searchId)); + if (targetInGY != null) + { + AI.SelectNextCard(targetInGY); + } else { + AI.SelectNextCard(searchId); + } + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + SelectSTPlace(null, true); + return true; + } + + return false; + } + + public bool DogmatikaLamityActivate() + { + if (CheckWhetherNegated()) return false; + // use lilith + if (Bot.HasInExtra(CardId.DespianLuluwalilith)) + { + AI.SelectYesNo(true); + AI.SelectCard(CardId.DogmatikaAlbaZoa); + AI.SelectNextCard(CardId.DespianLuluwalilith); + discardExtraThisTurn.Add(CardId.DespianLuluwalilith); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + SelectSTPlace(null, true); + return true; + } + + return false; + } + + public bool DogmatikaLamityDelayActivate() + { + if (CheckWhetherNegated() || Bot.HasInExtra(CardId.DespianLuluwalilith)) return false; + if (Bot.HasInMonstersZone(CardId.DogmatikaAlbaZoa, false, false, true)) return false; + List materialList = new List(); + int totalLevel = 0; + List faceDownMonsterList = Bot.GetMonsters().Where(card => !card.HasType(CardType.Xyz) && card.IsFacedown()).OrderByDescending(card => card.Level).ToList(); + foreach (ClientCard faceDownMonster in faceDownMonsterList) + { + materialList.Add(faceDownMonster); + totalLevel += faceDownMonster.Level; + if (totalLevel >= 12) break; + } + + ClientCard handSummonTarget = Bot.Hand.FirstOrDefault(card => card.IsCode(CardId.DogmatikaAlbaZoa)); + if (handSummonTarget == null) return false; + int extraUseCount = 0; + List extraMonsterList = Bot.GetMonsters().Where(card => !card.HasType(CardType.Xyz | CardType.Link) && card.IsFaceup()) + .OrderByDescending(card => card.Level).ToList(); + extraMonsterList.AddRange(Bot.Hand.Where(card => card.IsMonster() && card != handSummonTarget).OrderByDescending(card => card.Level).ToList()); + foreach (ClientCard faceUpMonster in extraMonsterList) + { + if (totalLevel >= 12 || extraUseCount >= 1) break; + materialList.Add(faceUpMonster); + totalLevel += faceUpMonster.Level; + extraUseCount ++; + } + + if (totalLevel >= 12) + { + AI.SelectYesNo(false); + AI.SelectCard(CardId.DogmatikaAlbaZoa); + AI.SelectNextCard(materialList); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(1); + SelectSTPlace(null, true); + return true; + } + + return false; + } + + public bool DogmatikaMacabreActivate() + { + if (Bot.HasInMonstersZone(CardId.DogmatikaAlbaZoa)) return false; + if (CheckWhetherNegated()) return false; + List gyMaterialList = Bot.Graveyard.Where(card => card != null && card.HasType(CardType.Fusion | CardType.Synchro)) + .OrderByDescending(card => card.Level).ToList(); + List selectMaterialList = new List(); + int totalLevel = 0; + List checkDiscardThisTurnIdList = new List { CardId.DespianLuluwalilith, CardId.TitanikladTheAshDragon }; + foreach (ClientCard material in gyMaterialList) + { + if (material.IsCode(CardId.PSYFramelordOmega)) continue; + if (CheckAtAdvantage()) + { + foreach (int checkId in checkDiscardThisTurnIdList) + { + if (material.IsCode(checkId) && discardExtraThisTurn.Contains(checkId)) continue; + } + } + totalLevel += material.Level; + selectMaterialList.Add(material); + if (totalLevel >= 12) break; + } + if (totalLevel >= 12) + { + ClientCard graveAlbaZoa = Bot.Graveyard.FirstOrDefault(card => card.IsCode(CardId.DogmatikaAlbaZoa)); + if (graveAlbaZoa != null) + { + AI.SelectCard(graveAlbaZoa); + } else { + AI.SelectCard(CardId.DogmatikaAlbaZoa); + } + AI.SelectMaterials(selectMaterialList, HintMsg.Release); + SelectSTPlace(null, true); + return true; + } + + return false; + } + + public bool SinfulSpoilsOfDoom_RcielaActivate() + { + // select self target + ClientCard selfTarget = null; + bool activateFlag = false; + List selfCasterList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.Level >= 7 && card.HasRace(CardRace.SpellCaster)) + .OrderByDescending(card => card.Attack).ThenByDescending(card => card.Level).ToList(); + bool onlyAlbaZoa = selfCasterList.Count() == 1 && selfCasterList[0].IsCode(CardId.DogmatikaAlbaZoa); + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && lastChainCard.Controller == 1 && lastChainCard.IsMonster()) + { + bool negateFlag = lastChainCard.IsCode(_CardId.EffectVeiler, CardId.GhostMournerMoonlitChill); + if (Duel.Turn > 1 || !negateFlag) + { + foreach (ClientCard chainTarget in Duel.LastChainTargets) + { + if (selfCasterList.Contains(chainTarget) && (!negateFlag || !chainTarget.IsCode(CardId.DiabellstarTheBlackWitch))) + { + selfTarget = chainTarget; + activateFlag = true; + break; + } + } + } + } + if (selfTarget == null && !onlyAlbaZoa) + { + selfTarget = selfCasterList.FirstOrDefault(card => !card.IsCode(CardId.DogmatikaAlbaZoa)); + } + if (DefaultOnBecomeTarget() && !onlyAlbaZoa) + { + activateFlag = true; + } + + if (selfTarget != null) + { + int targetAttack = selfTarget.Attack; + // destroy danger monster + ClientCard dangerCard = GetProblematicEnemyMonster(-1, true, true); + if (dangerCard != null) + { + activateFlag = true; + } + + // destroy multi monster + if (!onlyAlbaZoa) + { + List toDestroyMonsterList = Enemy.GetMonsters().Where(card => card.IsFaceup() + && card.Attack > 0 && card.Attack <= targetAttack && !currentDestroyCardList.Contains(card) + && (Duel.Player == 1 || card != Enemy.BattlingMonster)).ToList(); + if (toDestroyMonsterList.Count() > 1) + { + activateFlag = true; + currentDestroyCardList.AddRange(toDestroyMonsterList); + } + } + + // decrease attack + int botWorstPower = Util.GetWorstBotMonster()?.GetDefensePower() ?? 0; + bool decreaseFlag = Duel.Player == 1 && Enemy.GetMonsters().Any(card => card.Attack >= botWorstPower + && card.IsMonsterHasPreventActivationEffectInBattle()) && Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2; + decreaseFlag |= (!onlyAlbaZoa || (Bot.BattlingMonster?.IsCode(CardId.DogmatikaAlbaZoa) ?? false)) + && (Bot.BattlingMonster?.GetDefensePower() ?? 0) <= (Enemy.BattlingMonster?.GetDefensePower() ?? 0) + && Duel.LastChainPlayer != 0 && (CurrentTiming & hintDamageStep) != 0 && CurrentTiming > 0; + if (decreaseFlag) + { + activateFlag = true; + } + } + + if (activateFlag) + { + SelectSTPlace(null, true); + AI.SelectCard(selfTarget); + return true; + } + + return false; + } + + public bool CalledbytheGraveActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (CheckAtAdvantage() && Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + return false; + } + if (Duel.LastChainPlayer == 1) + { + // negate + if (Util.GetLastChainCard().IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (CheckCalledbytheGrave(code) > 0) return false; + if (Util.GetLastChainCard().IsCode(_CardId.MaxxC) && CheckAtAdvantage()) + { + return false; + } + if (Enemy.Graveyard.GetFirstMatchingCard(card => card.IsMonster() && card.IsOriginalCode(code)) != null) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(code); + currentNegatingIdList.Add(code); + CheckDeactiveFlag(); + return true; + } + } + + // banish target + foreach (ClientCard cards in Enemy.Graveyard) + { + if (Duel.ChainTargets.Contains(cards) && cards.IsMonster()) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + int code = cards.GetOriginCode(); + AI.SelectCard(cards); + currentNegatingIdList.Add(code); + return true; + } + } + + // become targets + if (Duel.ChainTargets.Contains(Card)) + { + List enemyMonsters = Enemy.Graveyard.GetMatchingCards(card => card.IsMonster()).ToList(); + if (enemyMonsters.Count() > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + int code = enemyMonsters[0].Id; + AI.SelectCard(enemyMonsters); + currentNegatingIdList.Add(code); + return true; + } + } + } + + // avoid danger monster in grave + if (Duel.LastChainPlayer == 1) return false; + List targets = GetDangerousCardinEnemyGrave(true); + if (targets.Count() > 0) { + int code = targets[0].Id; + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(targets); + currentNegatingIdList.Add(code); + return true; + } + + return false; + } + + public bool CrossoutDesignatorActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + // negate + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard() != null) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + // do not negate black witch + if (code == CardId.DiabellstarTheBlackWitch) return false; + if (CheckCalledbytheGrave(code) > 0) return false; + if (CheckRemainInDeck(code) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectAnnounceID(code); + currentNegatingIdList.Add(code); + CheckDeactiveFlag(); + return true; + } + } + return false; + } + + public bool WANTED_SeekerOfSinfulSpoilsActivate() + { + if (Card.Location == CardLocation.Hand || (Card.Location == CardLocation.SpellZone && Card.HasPosition(CardPosition.FaceDown))) + { + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + + return true; + } + + public bool DogmatikaMatrixCanActivate() + { + return CheckRemainInDeck(CardId.DogmatikaAlbaZoa, CardId.DogmatikaLamity, CardId.DogmatikaMacabre) > 0; + } + + public bool DogmatikaMatrixActivate() + { + if (CheckWhetherNegated()) return false; + + // activate for search + if (Card.Location == CardLocation.Hand || (Card.Location == CardLocation.SpellZone && Card.HasPosition(CardPosition.FaceDown))) + { + List neededRitualCardIdList = GetNeedSearchRitualCardIdList(); + // can only search ritual + if (Enemy.GetMonsterCount() == 0) + { + if (!Bot.MonsterZone.Any(card => card != null && card.IsFaceup() && card.HasType(CardType.Ritual) && card.HasSetcode(SetcodeDogmatika)) + && neededRitualCardIdList.Count() <= 0) + { + return false; + } + SelectSTPlace(null, true); + AI.SelectCard(neededRitualCardIdList); + // in case enemy summon monster after activated + AI.SelectYesNo(true); + activatedCardIdList.Add(Card.Id); + return true; + } + // can search both + else + { + if (neededRitualCardIdList.Count() <= 0) + { + SelectSTPlace(null, true); + AI.SelectYesNo(true); + // search both monster and spell + if (CheckRemainInDeck(CardId.DogmatikaAlbaZoa) > 0 && CheckRemainInDeck(CardId.DogmatikaLamity, CardId.DogmatikaMacabre) > 0) + { + AI.SelectCard(CardId.DogmatikaAlbaZoa); + AI.SelectNextCard(CardId.DogmatikaLamity, CardId.DogmatikaMacabre); + } + else + { + AI.SelectCard(CardId.DogmatikaAlbaZoa, CardId.DogmatikaLamity, CardId.DogmatikaMacabre); + DogmatikaMatrixNextSearch(); + } + activatedCardIdList.Add(Card.Id); + return true; + } + else + { + SelectSTPlace(null, true); + AI.SelectCard(neededRitualCardIdList); + AI.SelectYesNo(true); + DogmatikaMatrixNextSearch(); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + // discard extra + else + { + int option = 0; + if (CheckWhetherWillbeRemoved()) option = 1; + if (!checkedEnemyExtra && Enemy.ExtraDeck.Count() > 0) option = 1; + if (Enemy.HasInMonstersZone(CardId.KnightmareCorruptorIblee) && avoid2Monster) option = 1; + if (!Bot.HasInExtra(CardId.ElderEntityNtss) || GetNormalEnemyTargetList(true, false, false).Count() <= 0) + { + List checkActivatedIdList = new List{ CardId.GaruraWingsOfResonantLife, CardId.DespianLuluwalilith, + CardId.TitanikladTheAshDragon, CardId.GranguignolTheDuskDragon, CardId.PSYFramelordOmega }; + bool checkFlag = false; + foreach (int checkId in checkActivatedIdList) + { + checkFlag |= !discardExtraThisTurn.Contains(checkId) && !activatedCardIdList.Contains(checkId) && Bot.HasInExtra(checkId); + } + if (!checkFlag) + { + option = 1; + } + } + + Logger.DebugWriteLine("===Matrix option: " + option.ToString()); + matrixActivating = true; + AI.SelectOption(option); + activatedMatrixList.Add(Card); + return true; + } + } + + public void DogmatikaMatrixNextSearch() + { + List fieldMonsterList = Bot.GetMonsters(); + fieldMonsterList.AddRange(Enemy.GetMonsters()); + bool hasExtraOnField = fieldMonsterList.Any(card => card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)); + + // search ecclesia + if (!activatedCardIdList.Contains(CardId.DogmatikaEcclesia) && CheckCalledbytheGrave(CardId.DogmatikaEcclesia) == 0) + { + if (hasExtraOnField || !summoned) + { + if (CheckRemainInDeck(CardId.DogmatikaEcclesia) > 0) + { + AI.SelectNextCard(CardId.DogmatikaEcclesia); + return; + } + } + } + + // seach Maximus + if (CheckRemainInDeck(CardId.DogmatikaMaximus) > 0 && !activatedCardIdList.Contains(CardId.DogmatikaMaximus) + && Bot.Graveyard.Where(card => card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)).Count() > 0) + { + AI.SelectNextCard(CardId.DogmatikaMaximus); + return; + } + + // search Fleurdelis + if (CheckRemainInDeck(CardId.DogmatikaFleurdelis) > 0 && !Bot.HasInHand(CardId.DogmatikaFleurdelis) && hasExtraOnField + && Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika))) + { + AI.SelectNextCard(CardId.DogmatikaFleurdelis); + return; + } + + List searchIdList = new List{ CardId.DogmatikaPunishment, CardId.DogmatikaEcclesia, CardId.DogmatikaMatrix, + CardId.DogmatikaMaximus, CardId.DogmatikaFleurdelis, CardId.DogmatikaAlbaZoa, CardId.DogmatikaLamity, CardId.DogmatikaMacabre }; + foreach (int searchId in searchIdList) + { + if (CheckRemainInDeck(searchId) > 0) + { + AI.SelectNextCard(searchId); + return; + } + } + } + + public bool InfiniteImpermanenceActivate() + { + if (CheckWhetherNegated()) return false; + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ( (this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || Util.IsChainTarget(Card) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + CheckDeactiveFlag(); + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true); + if (target != null) + { + AI.SelectCard(target); + } else { + AI.SelectCard(Enemy.GetMonsters()); + } + infiniteImpermanenceList.Add(this_seq); + return true; + } + } + + // negate monster + List shouldNegateList = GetMonsterListForTargetNegate(false, true); + if (shouldNegateList.Count() > 0) + { + ClientCard negateTarget = shouldNegateList[0]; + currentNegateMonsterList.Add(negateTarget); + + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++ i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(negateTarget); + return true; + } + + return false; + } + + public bool DogmatikaPunishmentActivate() + { + if (CheckWhetherNegated() || CheckWhetherWillbeRemoved()) return false; + + ClientCard targetCard = null; + ClientCard extraToDiscard = null; + + // destroy problem card by ntss + List targetList = GetProblematicEnemyCardList(true, true); + if (targetList.Count() > 0 && Duel.LastChainPlayer != 0 && Bot.HasInExtra(CardId.ElderEntityNtss)) + { + foreach (ClientCard target in targetList) + { + if (target.IsFaceup() && target.IsMonster() && target.Attack <= 2500) + { + targetCard = target; + extraToDiscard = GetExtraToDiscard(2500, target); + if (extraToDiscard != null) + { + break; + } + } + } + if (targetCard == null || extraToDiscard == null) + { + List enemyMonsterList = Enemy.GetMonsters().Where(card => card.IsFaceup() + && !card.IsShouldNotBeTarget() && card.IsShouldNotBeSpellTrapTarget()).ToList(); + enemyMonsterList.Sort(CardContainer.CompareCardAttack); + foreach (ClientCard target in enemyMonsterList) + { + if (target.IsFaceup() && target.IsMonster() && target.Attack <= 2500) + { + targetCard = target; + extraToDiscard = GetExtraToDiscard(2500, target); + if (extraToDiscard != null) + { + break; + } + } + } + } + } + + if (targetCard == null || extraToDiscard == null) + { + targetCard = GetProblematicEnemyMonster(0, true, true); + if (targetCard != null) + { + extraToDiscard = GetExtraToDiscard(targetCard.Attack, targetCard); + } + } + + if (targetCard == null || extraToDiscard == null) + { + bool check1 = DefaultOnBecomeTarget(); + bool check2 = Bot.UnderAttack && (Bot.BattlingMonster?.GetDefensePower() ?? 0) <= (Enemy.BattlingMonster?.GetDefensePower() ?? 0) && Duel.LastChainPlayer != 0;; + bool check3 = Duel.Player == 1 && Duel.Phase == DuelPhase.End && Duel.LastChainPlayer != 0; + bool check4 = Duel.Player == 1 && avoid2Monster && Enemy.GetMonsterCount() >= 2 && Duel.LastChainPlayer != 0; + Logger.DebugWriteLine("===punishment check flag: " + check1 + " " + check2 + " " + check3 + " " + check4); + if (check1 || check2 || check3 || check4) + { + List checkList = Enemy.GetMonsters().Where(card => card.IsFaceup() && !card.IsShouldNotBeTarget() && !currentDestroyCardList.Contains(card)) + .OrderByDescending(c => c.Attack).ToList(); + foreach (ClientCard checkTarget in checkList) + { + extraToDiscard = GetExtraToDiscard(checkTarget.Attack, checkTarget); + if (extraToDiscard != null) + { + targetCard = checkTarget; + break; + } + } + } + } + + if (targetCard != null && extraToDiscard != null) + { + AI.SelectCard(targetCard); + AI.SelectNextCard(extraToDiscard); + currentDestroyCardList.Add(targetCard); + discardExtraThisTurn.Add(extraToDiscard?.Id ?? 0); + activatedCardIdList.Add(Card.Id); + UpdateBanSpSummonFromExTurn(2); + return true; + } + + return false; + } + + + public bool GranguignolTheDuskDragonActivate() + { + if (Card.Location == CardLocation.Grave) + { + AI.SelectCard(CardId.DespianLuluwalilith, CardId.DogmatikaEcclesia, CardId.DogmatikaMaximus, CardId.DogmatikaFleurdelis); + return true; + } + return false; + } + + public bool TitanikladTheAshDragonActivate() + { + if (!activatedCardIdList.Contains(CardId.DogmatikaEcclesia) && CheckRemainInDeck(CardId.DogmatikaEcclesia) > 0 && CheckCalledbytheGrave(CardId.DogmatikaEcclesia) == 0) + { + AI.SelectOption(1); + AI.SelectCard(CardId.DogmatikaEcclesia); + return true; + } + if (CheckRemainInDeck(CardId.DogmatikaFleurdelis) > 0) + { + if (!Bot.HasInHand(CardId.DogmatikaFleurdelis) && !enemyActivateLockBird) + { + if (Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika))) + { + AI.SelectOption(0); + AI.SelectCard(CardId.DogmatikaFleurdelis); + return true; + } + } + if (Duel.Player == 1 && Enemy.GetMonsterCount() == 0) + { + AI.SelectOption(1); + AI.SelectCard(CardId.DogmatikaFleurdelis); + return true; + } + } + if (CheckRemainInDeck(CardId.DogmatikaMaximus) > 0) + { + AI.SelectOption(1); + AI.SelectCard(CardId.DogmatikaMaximus); + return true; + } + + return false; + } + + public bool GaruraWingsOfResonantLifeActivate() + { + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool ElderEntityNtssActivate() + { + if (Card.Location == CardLocation.Grave) + { + List destroyList = GetNormalEnemyTargetList(true, true, true); + if (destroyList.Count() > 0) + { + currentDestroyCardList.Add(destroyList[0]); + AI.SelectCard(destroyList); + return true; + } + } + + return false; + } + + public bool DespianLuluwalilithActivate() + { + // spsummon + if (Card.Location == CardLocation.Grave) + { + if (!activatedCardIdList.Contains(CardId.DogmatikaEcclesia) && CheckRemainInDeck(CardId.DogmatikaEcclesia) > 0 + && CheckCalledbytheGrave(CardId.DogmatikaEcclesia) == 0 && !enemyActivateLockBird) + { + AI.SelectCard(CardId.DogmatikaEcclesia); + return true; + } + if (CheckRemainInDeck(CardId.ThesIrisSwordsoul) > 0) + { + AI.SelectCard(CardId.ThesIrisSwordsoul); + return true; + } + if (Duel.Turn > 1 && Enemy.GetMonsterCount() == 0 && CheckRemainInDeck(CardId.DogmatikaFleurdelis) > 0) + { + AI.SelectCard(CardId.DogmatikaFleurdelis); + return true; + } + if (Bot.HasInHand(CardId.DogmatikaFleurdelis) && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeDogmatika))) + { + List checkIdList = new List{ CardId.DogmatikaMaximus, CardId.DogmatikaEcclesia, CardId.DogmatikaFleurdelis }; + foreach (int checkId in checkIdList) + { + if (CheckRemainInDeck(checkId) > 0) + { + AI.SelectCard(checkId); + return true; + } + } + } + } + // increase atk & negate + if (Card.Location == CardLocation.MonsterZone) + { + List currentChainEnemyCard = Duel.CurrentChain.Where(card => card.Controller == 1 && !currentNegateMonsterList.Contains(card) + && (card.Location == CardLocation.MonsterZone || card.Location == CardLocation.SpellZone)).ToList(); + currentChainEnemyCard.AddRange(GetProblematicEnemyCardList(false, false)); + currentChainEnemyCard.AddRange(ShuffleCardList(Enemy.GetSpells().Where(card => card.IsFaceup()).ToList())); + currentChainEnemyCard.AddRange(ShuffleCardList(Enemy.GetMonsters().Where(card => card.IsFaceup()).ToList())); + if (currentChainEnemyCard.Count() > 0) + { + currentNegateMonsterList.Add(currentChainEnemyCard[0]); + AI.SelectYesNo(true); + AI.SelectCard(currentChainEnemyCard); + } + else AI.SelectYesNo(false); + return true; + } + return false; + } + + public bool PSYFramelordOmegaActivate() + { + if (Card.Location == CardLocation.Grave && omegaActivateCount <= 5) + { + if (CheckWhetherNegated()) return false; + List targets = GetDangerousCardinEnemyGrave(true); + if (targets.Count() > 0) { + AI.SelectCard(targets); + omegaActivateCount ++; + return true; + } + + List recycleExtraIdList = new List{ CardId.GaruraWingsOfResonantLife, CardId.ElderEntityNtss }; + foreach (int checkId in recycleExtraIdList) + { + if (!Bot.HasInExtra(checkId) && Bot.HasInGraveyard(checkId)) + { + AI.SelectCard(checkId); + omegaActivateCount ++; + return true; + } + } + + List recycleMainIdList = new List{ CardId.DogmatikaMacabre, CardId.DogmatikaLamity, CardId.DogmatikaAlbaZoa, CardId.DogmatikaPunishment, + CardId.DogmatikaEcclesia, CardId.DogmatikaFleurdelis, CardId.DogmatikaMatrix }; + foreach (int checkId in recycleMainIdList) + { + if (CheckRemainInDeck(checkId) <= 0 && Bot.HasInGraveyard(checkId)) + { + AI.SelectCard(checkId); + omegaActivateCount ++; + return true; + } + } + + recycleExtraIdList.AddRange(new List { + CardId.SuperStarslayerTYPHON, CardId.TitanikladTheAshDragon, CardId.HeraldOfTheArcLight, CardId.DespianLuluwalilith, CardId.Linguriboh, + CardId.SalamangreatAlmiraj, CardId.SecureGardna + }); + foreach (int checkId in recycleExtraIdList) + { + if (!Bot.HasInExtra(checkId) && Bot.HasInGraveyard(checkId)) + { + AI.SelectCard(checkId); + omegaActivateCount ++; + return true; + } + } + } + + return false; + } + + public bool HeraldOfTheArcLightActivate() + { + AI.SelectCard(GetNeedSearchRitualCardIdList()); + return true; + } + + public bool SuperStarslayerTYPHONSpSummon() + { + ClientCard material = Bot.GetMonsters().Where(card => card.IsFaceup()).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (material == null || material.Attack >= 3000) return false; + + bool checkFlag = GetProblematicEnemyMonster(material.Attack) != null; + checkFlag |= material.HasType(CardType.Link); + checkFlag |= material.Level <= 4; + if (checkFlag) + { + AI.SelectMaterials(material); + return true; + } + + return false; + } + + public bool SuperStarslayerTYPHONActivate() + { + if (CheckWhetherNegated()) return false; + List targetList = new List(); + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.IsFloodgate() && c.IsFaceup()).OrderByDescending(card => card.Attack)); + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.IsMonsterDangerous() && c.IsFaceup()).OrderByDescending(card => card.Attack)); + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.IsMonsterInvincible() && c.IsFaceup()).OrderByDescending(card => card.Attack)); + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.GetDefensePower() >= Util.GetBestAttack(Bot) && c.IsAttack()).OrderByDescending(card => card.Attack)); + if (Duel.Phase >= DuelPhase.Main2) + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link | CardType.SpSummon)).OrderByDescending(card => card.Attack)); + + if (targetList.Count() > 0) + { + targetList.AddRange(Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card)).OrderByDescending(card => card.Attack)); + targetList.AddRange(ShuffleCardList(Enemy.GetMonsters().Where(card => card.IsFacedown() && !targetList.Contains(card)).ToList())); + targetList.AddRange(ShuffleCardList(Bot.GetMonsters().Where(card => card.IsFacedown() && !targetList.Contains(card)).ToList())); + targetList.AddRange(Bot.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card)).OrderBy(card => card.Attack)); + AI.SelectCard(Card.Overlays); + AI.SelectNextCard(targetList); + return true; + } + + return false; + } + + public bool SPLittleKnightActivate() + { + // TODO + return false; + } + + public bool SecureGardnaSpSummon() + { + if (Bot.HasInHand(CardId.DogmatikaMaximus)) + { + if (!Bot.Graveyard.Any(card => card.IsMonster() && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link))) + { + return true; + } + } + return false; + } + + public bool LinguribohSpSummon() + { + if (Enemy.GetSpells().Any(card => card.IsFacedown())) return true; + if (!Bot.HasInExtra(CardId.SalamangreatAlmiraj)) return true; + return false; + } + + public bool LinguribohActivate() + { + if (CheckLastChainShouldNegated()) return true; + return false; + } + + public bool SalamangreatAlmirajSpSummon() + { + if (Bot.HasInMonstersZone(CardId.KnightmareCorruptorIblee, faceUp: true)) + { + AI.SelectMaterials(CardId.KnightmareCorruptorIblee); + return true; + } + if (Bot.HasInHand(new List{ CardId.DogmatikaEcclesia, CardId.DogmatikaMaximus, CardId.NadirServant })) + { + List materialList = Bot.MonsterZone.Where(card => card != null && card.IsFaceup() && card.Attack <= 1000 + && !card.HasType(CardType.Ritual | CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)).ToList(); + if (materialList.Count() > 0) + { + materialList.Sort(CardContainer.CompareCardAttack); + AI.SelectMaterials(materialList); + return true; + } + } + + return false; + } + + public bool SalamangreatAlmirajActivate() + { + if (Card.Location == CardLocation.Grave) return true; + bool checkFlag = Duel.Player == 1 && (!Bot.HasInHand(CardId.DogmatikaFleurdelis) || activatedCardIdList.Contains(CardId.DogmatikaFleurdelis)); + checkFlag |= DefaultOnBecomeTarget(); + checkFlag |= Bot.UnderAttack && Bot.BattlingMonster == Card; + if (checkFlag) + { + AI.SelectCard(Util.GetBestBotMonster()); + return true; + } + if (!Util.ChainContainsCard(CardId.SinfulSpoilsOfDoom_Rciela)) + { + List checkList = Bot.GetMonsters().Where(card => card.IsFaceup() && card != Card).OrderByDescending(card => card.Attack).ToList(); + checkList.AddRange(Bot.GetMonsters().GetMatchingCards(card => card.IsFacedown())); + foreach (ClientCard card in checkList) + { + if (Util.IsChainTarget(card)) + { + AI.SelectCard(card); + return true; + } + } + } + + return false; + } + + + public bool SummonForTYPHONCheck() + { + if (!Bot.HasInExtra(CardId.SuperStarslayerTYPHON) || Bot.GetMonsters().Any(card => card.IsFaceup()) || banSpSummonFromExTurn > 0) return false; + if (enemySpSummonFromExLastTurn < 2 && enemySpSummonFromExThisTurn < 2) return false; + if (Card.IsCode(CardId.KnightmareCorruptorIblee) && !CheckWhetherNegated()) return false; + if (Card.Level > 4) return false; + + int currentAttack = 0; + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(Card.Id); + if (cardData != null) currentAttack = cardData.Attack; + List summonList = Bot.Hand.Where(card => card.IsMonster() && card.Level <= 4).ToList(); + foreach (ClientCard checkCard in summonList) + { + cardData = YGOSharp.OCGWrapper.NamedCard.Get(checkCard.Id); + if (cardData != null && cardData.Attack < currentAttack) return false; + } + + return true; + } + + public bool MonsterRepos() + { + int selfAttack = Card.Attack + 1; + int extraAttackForDogmatika = 0; + if (!activatedCardIdList.Contains(CardId.DogmatikaFleurdelis + 1) && Bot.HasInMonstersZone(CardId.DogmatikaFleurdelis, true, false, true)) extraAttackForDogmatika += 500; + if (Card.HasSetcode(SetcodeDogmatika)) + { + selfAttack += extraAttackForDogmatika; + } + + if (Card.IsFaceup() && Card.IsDefense() && selfAttack <= 1) + return false; + + int bestAttack = 0; + foreach (ClientCard card in Bot.GetMonsters()) + { + int attack = card.Attack; + if (card.HasSetcode(SetcodeDogmatika)) + { + attack += extraAttackForDogmatika; + } + if (attack >= bestAttack) + { + bestAttack = attack; + } + } + + bool enemyBetter = Util.IsAllEnemyBetterThanValue(bestAttack, true); + + if (Card.IsAttack() && enemyBetter) + return true; + if (Card.IsDefense() && !enemyBetter) + return true; + return false; + } + + public bool SpellSetCheck() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + if (Card.IsCode(CardId.DogmatikaPunishment) && Bot.HasInSpellZone(Card.Id)) return false; + if (Card.IsCode(CardId.SinfulSpoilsOfDoom_Rciela)) + { + if (!Bot.HasInHand(CardId.DogmatikaFleurdelis) && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.Level >= 7 && card.HasRace(CardRace.SpellCaster))) + { + return false; + } + } + + // select place + if (Card.IsTrap() || Card.HasType(CardType.QuickPlay)) + { + List avoid_list = new List(); + int setFornfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + setFornfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setFornfiniteImpermanence); + return true; + } else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } else + { + SelectSTPlace(); + } + return true; + } + + else if (Enemy.HasInSpellZone(_CardId.AntiSpellFragrance, true) || Bot.HasInSpellZone(_CardId.AntiSpellFragrance, true)) + { + if (Card.IsSpell() && !Bot.HasInSpellZone(Card.Id)) + { + SelectSTPlace(); + return true; + } + } + + return false; + } + + protected override bool DefaultSetForDiabellze() + { + if (base.DefaultSetForDiabellze()) + { + SelectSTPlace(null, true); + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DragunExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DragunExecutor.cs new file mode 100644 index 0000000..1cfbbc6 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DragunExecutor.cs @@ -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 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(); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DragunityExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DragunityExecutor.cs new file mode 100644 index 0000000..0c65e32 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/DragunityExecutor.cs @@ -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 cards = new List(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(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 tributes = new List(); + 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 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 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 monsters = Bot.GetMonsters(); + foreach (ClientCard monster in monsters) + { + if (monster.IsCode(CardId.StardustDragon) && monster.Attacked) + { + AI.SelectCard(monster); + return true; + } + } + } + return Duel.Player == 1; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/EvilswarmExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/EvilswarmExecutor.cs new file mode 100644 index 0000000..48ad37c --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/EvilswarmExecutor.cs @@ -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...? + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ExosisterExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ExosisterExecutor.cs new file mode 100644 index 0000000..932d187 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ExosisterExecutor.cs @@ -0,0 +1,2990 @@ +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; +using System.Linq; +using System; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Exosister", "AI_Exosister")] + + class ExosisterExecutor : DefaultExecutor + { + public class CardId + { + public const int ExosisterElis = 16474916; + public const int ExosisterStella = 43863925; + public const int ExosisterIrene = 79858629; + public const int ExosisterSophia = 5352328; + public const int ExosisterMartha = 37343995; + public const int Aratama = 16889337; + public const int Sakitama = 67972302; + // _CardId.MaxxC = 23434538; + // _CardId.AshBlossom = 14558127; + + public const int ExosisterPax = 77913594; + public const int ExosisterArment = 4408198; + public const int PotofExtravagance = 84211599; + // _CardId.CalledByTheGrave = 24224830; + + public const int ExosisterVadis = 77891946; + public const int ExosisterReturnia = 197042; + // _CardId.InfiniteImpermanence = 10045474; + + public const int ExosisterMikailis = 42741437; + public const int ExosisterKaspitell = 78135071; + public const int ExosisterGibrine = 5530780; + public const int ExosisterAsophiel = 41524885; + public const int ExosistersMagnifica = 59242457; + public const int TellarknightConstellarCaduceus = 58858807; + public const int StellarknightConstellarDiamond = 9272381; + public const int DivineArsenalAAZEUS_SkyThunder = 90448279; + public const int DonnerDaggerFurHire = 8728498; + // _CardId.EvilswarmExcitonKnight = 46772449; + + public const int NaturalExterio = 99916754; + public const int NaturalBeast = 33198837; + public const int ImperialOrder = 61740673; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecree = 51452091; + public const int Number41BagooskatheTerriblyTiredTapir = 90590303; + public const int InspectorBoarder = 15397015; + public const int DimensionShifter = 91800273; + } + + public ExosisterExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // trigger + AddExecutor(ExecutorType.Activate, CardId.ExosistersMagnifica, ExosistersMagnificaActivateTrigger); + + // quick effect + AddExecutor(ExecutorType.Activate, CardId.ExosisterMikailis, ExosisterMikailisActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosistersMagnifica, ExosistersMagnificaActivateBanish); + AddExecutor(ExecutorType.Activate, CardId.ExosisterReturnia, ExosisterReturniaActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosisterVadis, ExosisterVadisActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, CardId.StellarknightConstellarDiamond); + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossomActivate); + AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, CalledbytheGraveActivate); + AddExecutor(ExecutorType.Activate, DefaultExosisterTransform); + AddExecutor(ExecutorType.Activate, CardId.ExosisterArment, ExosisterArmentActivate); + + // free chain + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + + // search + AddExecutor(ExecutorType.Activate, CardId.PotofExtravagance, PotofExtravaganceActivate); + + // field effect + AddExecutor(ExecutorType.Activate, CardId.Aratama); + AddExecutor(ExecutorType.Activate, CardId.DonnerDaggerFurHire, DonnerDaggerFurHireActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosisterKaspitell, ExosisterKaspitellActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosisterGibrine, ExosisterGibrineActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosisterAsophiel, ExosisterAsophielActivate); + + AddExecutor(ExecutorType.Activate, CardId.ExosisterSophia, ExosisterSophiaActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosisterIrene, ExosisterIreneActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosisterStella, ExosisterStellaActivate); + + // addition monster summmon + AddExecutor(ExecutorType.Activate, CardId.ExosisterElis, ExosisterElisActivate); + AddExecutor(ExecutorType.Activate, CardId.Sakitama, SakitamaActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosisterPax, ExosisterPaxActivate); + AddExecutor(ExecutorType.Activate, CardId.ExosisterStella, ExosisterStellaSecondActivate); + + // xyz summon + AddExecutor(ExecutorType.SpSummon, CardId.StellarknightConstellarDiamond); + AddExecutor(ExecutorType.SpSummon, CardId.DonnerDaggerFurHire, DonnerDaggerFurHireSpSummonCheck); + AddExecutor(ExecutorType.SpSummon, CardId.ExosisterMikailis, ExosisterMikailisAdvancedSpSummonCheck); + AddExecutor(ExecutorType.SpSummon, CardId.ExosisterKaspitell, ExosisterKaspitellAdvancedSpSummonCheck); + + AddExecutor(ExecutorType.SpSummon, CardId.ExosisterKaspitell, ExosisterKaspitellSpSummonCheck); + AddExecutor(ExecutorType.SpSummon, CardId.ExosisterMikailis, ExosisterMikailisSpSummonCheck); + AddExecutor(ExecutorType.SpSummon, CardId.TellarknightConstellarCaduceus, TellarknightConstellarCaduceusSpSummonCheck); + + AddExecutor(ExecutorType.SpSummon, CardId.ExosistersMagnifica, ExosistersMagnificaSpSummonCheck); + + AddExecutor(ExecutorType.SpSummon, _CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightSummon); + AddExecutor(ExecutorType.Activate, _CardId.EvilswarmExcitonKnight, DefaultEvilswarmExcitonKnightEffect); + + // normal summon for xyz(avoiding MaxxC) + AddExecutor(ExecutorType.Summon, CardId.ExosisterStella, ExosisterAvoidMaxxCSummonCheck); + AddExecutor(ExecutorType.Summon, CardId.ExosisterSophia, ExosisterAvoidMaxxCSummonCheck); + AddExecutor(ExecutorType.Summon, CardId.ExosisterIrene, ExosisterAvoidMaxxCSummonCheck); + AddExecutor(ExecutorType.Summon, CardId.ExosisterElis, ExosisterAvoidMaxxCSummonCheck); + + // activate martha + AddExecutor(ExecutorType.Activate, CardId.ExosisterMartha, ExosisterMarthaActivate); + + // normal summon for xyz + AddExecutor(ExecutorType.Summon, CardId.ExosisterStella, ExosisterStellaSummonCheck); + AddExecutor(ExecutorType.Summon, CardId.Aratama, AratamaSummonCheck); + AddExecutor(ExecutorType.Summon, ExosisterForElisSummonCheck); + AddExecutor(ExecutorType.Summon, ForSakitamaSummonCheck); + AddExecutor(ExecutorType.Summon, CardId.ExosisterIrene, ExosisterIreneSummonCheck); + AddExecutor(ExecutorType.Summon, Level4SummonCheck); + AddExecutor(ExecutorType.Summon, ExosisterForArmentSummonCheck); + AddExecutor(ExecutorType.Summon, ForDonnerSummonCheck); + + AddExecutor(ExecutorType.Activate, CardId.ExosisterPax, ExosisterPaxActivateForEndSearch); + + // other + AddExecutor(ExecutorType.Repos, DefaultMonsterRepos); + AddExecutor(ExecutorType.SpellSet, SpellSetCheck); + } + + const int SetcodeTimeLord = 0x4a; + const int SetcodeShadoll = 0x9d; + const int SetcodeInferoid = 0xbb; + const int SetcodeOrcust = 0x11b; + const int SetcodeExosister = 0x172; + const int SetcodeTearlaments = 0x181; + List SetcodeForDiamond = new List{SetcodeShadoll, SetcodeInferoid, SetcodeTearlaments}; + + List affectGraveCardIdList = new List{ + 71344451, 40975243, 87746184, 70534340, 45906428, 71490127, 3659803, 12071500, 6077601, 11827244, 95238394, 81223446, 40003819, + 72490637, 21011044, 59419719, 14735698, 45410988 + }; + + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.ExosisterElis, CardId.ExosisterStella, CardId.ExosisterMartha, CardId.Aratama, CardId.Sakitama, + _CardId.MaxxC, _CardId.AshBlossom, CardId.ExosisterPax, CardId.ExosisterVadis }}, + {2, new List { CardId.ExosisterIrene, CardId.ExosisterSophia, CardId.PotofExtravagance, _CardId.CalledByTheGrave, + CardId.ExosisterReturnia, _CardId.InfiniteImpermanence }}, + {1, new List { CardId.ExosisterArment }}, + }; + Dictionary ExosisterMentionTable = new Dictionary{ + {CardId.ExosisterElis, CardId.ExosisterStella}, {CardId.ExosisterStella, CardId.ExosisterElis}, + {CardId.ExosisterIrene, CardId.ExosisterSophia}, {CardId.ExosisterSophia, CardId.ExosisterIrene}, + {CardId.ExosisterMartha, CardId.ExosisterElis} + }; + List ExosisterSpellTrapList = new List{CardId.ExosisterPax, CardId.ExosisterArment, CardId.ExosisterVadis, CardId.ExosisterReturnia}; + + List currentNegatingIdList = new List(); + bool enemyActivateMaxxC = false; + bool enemyActivateLockBird = false; + bool enemyMoveGrave = false; + bool paxCallToField = false; + List infiniteImpermanenceList = new List(); + + bool summoned = false; + bool elisEffect1Activated = false; + bool stellaEffect1Activated = false; + bool irenaEffect1Activated = false; + bool sophiaEffect1Activated = false; + bool marthaEffect1Activated = false; + bool mikailisEffect1Activated = false; + bool mikailisEffect3Activated = false; + bool kaspitellEffect1Activated = false; + bool kaspitellEffect3Activated = false; + bool gibrineEffect1Activated = false; + bool gibrineEffect3Activated = false; + bool asophielEffect1Activated = false; + bool asophielEffect3Activated = false; + bool sakitamaEffect1Activated = false; + List exosisterTransformEffectList = new List(); + List oncePerTurnEffectActivatedList = new List(); + List activatedMagnificaList = new List(); + List targetedMagnificaList = new List(); + List transformDestList = new List(); + List spSummonThisTurn = new List(); + bool potActivate = false; + List removeChosenList = new List(); + + /// + /// Shuffle List and return a random-order card list + /// + public List ShuffleCardList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(n + 1); + ClientCard temp = result[index]; + result[index] = result[n]; + result[n] = temp; + } + return result; + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false) + { + List floodagateList = Enemy.GetMonsters().Where(c => c?.Data != null && + c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (floodagateList.Count > 0) + { + floodagateList.Sort(CardContainer.CompareCardAttack); + floodagateList.Reverse(); + return floodagateList[0]; + } + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.IsMonsterDangerous() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (dangerList.Count > 0) + { + dangerList.Sort(CardContainer.CompareCardAttack); + dangerList.Reverse(); + return dangerList[0]; + } + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.IsMonsterInvincible() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (invincibleList.Count > 0) + { + invincibleList.Sort(CardContainer.CompareCardAttack); + invincibleList.Reverse(); + return invincibleList[0]; + } + + if (attack == 0) + attack = Util.GetBestAttack(Bot); + List betterList = Enemy.MonsterZone.GetMonsters() + .Where(card => card.GetDefensePower() >= attack && card.IsAttack() && (!canBeTarget || !card.IsShouldNotBeTarget())).ToList(); + if (betterList.Count > 0) + { + betterList.Sort(CardContainer.CompareCardAttack); + betterList.Reverse(); + return betterList[0]; + } + return null; + } + + public ClientCard GetProblematicEnemyCard(bool canBeTarget = false) + { + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null && !removeChosenList.Contains(c) && + c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (floodagateList.Count > 0) + { + floodagateList.Sort(CardContainer.CompareCardAttack); + floodagateList.Reverse(); + return floodagateList[0]; + } + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !removeChosenList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (problemEnemySpellList.Count > 0) + { + return ShuffleCardList(problemEnemySpellList)[0]; + } + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !removeChosenList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (dangerList.Count > 0 + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) + { + dangerList.Sort(CardContainer.CompareCardAttack); + dangerList.Reverse(); + return dangerList[0]; + } + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !removeChosenList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (invincibleList.Count > 0) + { + invincibleList.Sort(CardContainer.CompareCardAttack); + invincibleList.Reverse(); + return invincibleList[0]; + } + + List enemyMonsters = Enemy.GetMonsters().Where(c => !removeChosenList.Contains(c)).ToList(); + if (enemyMonsters.Count > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + foreach(ClientCard target in enemyMonsters) + { + if (target.HasType(CardType.Fusion) || target.HasType(CardType.Ritual) || target.HasType(CardType.Synchro) || target.HasType(CardType.Xyz) || (target.HasType(CardType.Link) && target.LinkCount >= 2) ) + { + if (!canBeTarget || !(target.IsShouldNotBeTarget() || target.IsShouldNotBeMonsterTarget())) return target; + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() && !removeChosenList.Contains(c) + && (c.HasType(CardType.Equip) || c.HasType(CardType.Pendulum) || c.HasType(CardType.Field) || c.HasType(CardType.Continuous))) + .ToList(); + if (spells.Count > 0) + { + return ShuffleCardList(spells)[0]; + } + + 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 monsters = Enemy.GetMonsters(); + + // after GetHighestAttackMonster, the left monsters must be face-down. + if (monsters.Count > 0 && !onlyFaceup) + return ShuffleCardList(monsters)[0]; + + return null; + } + + public ClientCard GetBestEnemySpell(bool onlyFaceup = false, bool canBeTarget = false) + { + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (problemEnemySpellList.Count > 0) + { + return ShuffleCardList(problemEnemySpellList)[0]; + } + + List spells = Enemy.GetSpells().Where(card => !(card.IsFaceup() && card.IsCode(_CardId.EvenlyMatched))).ToList(); + + List faceUpList = spells.Where(ecard => ecard.IsFaceup() && + (ecard.HasType(CardType.Continuous) || ecard.HasType(CardType.Field) || ecard.HasType(CardType.Pendulum))).ToList(); + if (faceUpList.Count > 0) + { + return ShuffleCardList(faceUpList)[0]; + } + + if (spells.Count > 0 && !onlyFaceup) + { + return ShuffleCardList(spells)[0]; + } + + return null; + } + + public ClientCard GetBestEnemyCard(bool onlyFaceup = false, bool canBeTarget = false, bool checkGrave = false) + { + ClientCard card = GetBestEnemyMonster(onlyFaceup, canBeTarget); + if (card != null) + { + return card; + } + + card = GetBestEnemySpell(onlyFaceup, canBeTarget); + if (card != null) + { + return card; + } + + if (checkGrave && Enemy.Graveyard.Count > 0) + { + List graveMonsterList = Enemy.Graveyard.GetMatchingCards(c => c.IsMonster()).ToList(); + if (graveMonsterList.Count > 0) + { + graveMonsterList.Sort(CardContainer.CompareCardAttack); + graveMonsterList.Reverse(); + return graveMonsterList[0]; + } + return ShuffleCardList(Enemy.Graveyard.ToList())[0]; + } + + return null; + } + + /// + /// Check remain cards in deck + /// + /// Card's ID + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + + /// + /// Check negated turn count of id + /// + public int CheckCalledbytheGrave(int id) + { + if (currentNegatingIdList.Contains(id)) return 1; + if (DefaultCheckWhetherCardIdIsNegated(id)) return 1; + return 0; + } + + public void CheckEnemyMoveGrave() + { + if (Duel.LastChainPlayer == 1) + { + ClientCard card = Util.GetLastChainCard(); + if (Duel.LastChainLocation == CardLocation.Grave && card.Location == CardLocation.Grave) + { + Logger.DebugWriteLine("===Exosister: enemy activate effect from GY."); + enemyMoveGrave = true; + } + else if (affectGraveCardIdList.Contains(card.Id)) + { + Logger.DebugWriteLine("===Exosister: enemy activate effect that affect GY."); + enemyMoveGrave = true; + } + else + { + foreach (ClientCard targetCard in Duel.LastChainTargets) + { + if (targetCard.Location == CardLocation.Grave) + { + Logger.DebugWriteLine("===Exosister: enemy target cards of GY."); + enemyMoveGrave = true; + break; + } + } + } + } + } + + /// + /// Check exosister's relative card. 0 for error. + /// + public int CheckExosisterMentionCard(int id) + { + if (!ExosisterMentionTable.ContainsKey(id)) + { + return 0; + } + return ExosisterMentionTable[id]; + } + + /// + /// Check whether last chain card should be disabled. + /// + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + if (lastcard.IsMonster() && lastcard.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + return true; + } + + /// + /// Check whether opposite use Maxx-C, and thus make less operation. + /// + public bool CheckLessOperation() + { + if (!enemyActivateMaxxC) + { + return false; + } + return CheckAtAdvantage(); + } + + /// + /// Check whether bot is at advantage. + /// + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && Bot.GetMonsters().Any(card => card.IsFaceup())) + { + return true; + } + return false; + } + + /// + /// Check whether bot is in danger and need to summon monster to defense. + /// + public bool CheckInDanger() + { + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + int totalAtk = 0; + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (m.IsAttack() && !m.Attacked) totalAtk += m.Attack; + } + if (totalAtk >= Bot.LifePoints) return true; + } + return false; + } + + /// + /// Check whether can be used for xyz summon. + /// + public bool CheckAbleForXyz(ClientCard card) + { + return card.IsFaceup() && !card.HasType(CardType.Xyz) && !card.HasType(CardType.Link) && !card.HasType(CardType.Token) && card.Level == 4; + } + + /// + /// Check whether bot can activate martha. + /// + public bool CheckMarthaActivatable() + { + return !marthaEffect1Activated && CheckCalledbytheGrave(CardId.ExosisterMartha) == 0 && CheckRemainInDeck(CardId.ExosisterElis) > 0 + && !Bot.GetMonsters().Any(card => card.IsFacedown() || !card.HasType(CardType.Xyz)); + } + + /// + /// check enemy's dangerous card in grave + /// + public List CheckDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && card.HasSetcode(SetcodeOrcust)).ToList(); + return result; + } + + /// + /// Whether spell or trap will be negate. If so, return true. + /// + /// is counter trap + /// check target + /// + 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.RoyalDecree, true) || Bot.HasInSpellZone(CardId.RoyalDecree, true)) return true; + } + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceList.Contains(selfSeq)) { + return true; + } + } + // how to get here? + return false; + } + + /// + /// Check whether'll be negated + /// + /// check whether card itself is disabled. + public bool CheckWhetherNegated(bool disablecheck = true){ + if (Card.IsSpell() || Card.IsTrap()){ + if (SpellNegatable()) return true; + } + if (CheckCalledbytheGrave(Card.Id) > 0){ + return true; + } + if (Card.IsMonster() && Card.Location == CardLocation.MonsterZone && Card.IsDefense()) + { + if (Enemy.MonsterZone.GetFirstMatchingFaceupCard(card => card.IsCode(CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled()) != null + || Bot.MonsterZone.GetFirstMatchingFaceupCard(card => card.IsCode(CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled()) != null) + { + return true; + } + } + if (disablecheck){ + return Card.IsDisabled(); + } + return false; + } + + /// + /// Select spell/trap's place randomly to avoid InfiniteImpermanence and so on. + /// + /// Card to set(default current card) + /// Whether need to avoid InfiniteImpermanence + /// Whether need to avoid set in this place + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceList.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public void SelectXyzMaterial(int num = 2, bool needExosister = false) + { + List materialList = Bot.GetMonsters().Where(card => CheckAbleForXyz(card)).ToList(); + if (materialList?.Count() < num) + { + return; + } + if (needExosister && !materialList.Any(card => card.HasSetcode(SetcodeExosister))) + { + return; + } + List selectedList = new List(); + + // if needed, select exosister with less atk first + if (needExosister) + { + List exosisterList = materialList.Where(card => card.HasSetcode(SetcodeExosister)).ToList(); + exosisterList.Sort(CardContainer.CompareCardAttack); + ClientCard firstSelect = exosisterList[0]; + selectedList.Add(firstSelect); + materialList.Remove(firstSelect); + } + + // select non-exosister or effecte used's exosister first + // never use martha first + List sortMaterialList = materialList.Where(card => + (card?.Data != null && !card.HasSetcode(SetcodeExosister)) || (exosisterTransformEffectList.Contains(card.Id) && card.Id != CardId.ExosisterMartha)).ToList(); + sortMaterialList.Sort(CardContainer.CompareCardAttack); + foreach (ClientCard card in sortMaterialList) + { + selectedList.Add(card); + if (selectedList.Count() >= num) + { + AI.SelectMaterials(selectedList); + return; + } + } + + List valuableMaterialList = materialList.Where(card => card.Id == CardId.ExosisterMartha || !exosisterTransformEffectList.Contains(card.Id)).ToList(); + valuableMaterialList.Sort(CardContainer.CompareCardAttack); + foreach (ClientCard card in valuableMaterialList) + { + selectedList.Add(card); + if (selectedList.Count() >= num) + { + AI.SelectMaterials(selectedList); + return; + } + } + } + + public void SelectDetachMaterial(ClientCard activateCard) + { + // TODO + AI.SelectCard(0); + } + + /// + /// go first + /// + public override bool OnSelectHand() + { + return true; + } + + /// + /// check whether enemy activate important card + /// + public override void OnChaining(int player, ClientCard card) + { + if (card == null) return; + + if (player == 1) + { + if (card.IsCode(_CardId.MaxxC) && CheckCalledbytheGrave(_CardId.MaxxC) == 0) + { + enemyActivateMaxxC = true; + } + if (card.IsCode(_CardId.LockBird) && CheckCalledbytheGrave(_CardId.LockBird) == 0) + { + enemyActivateLockBird = true; + } + if (card.IsCode(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == card) + { + infiniteImpermanenceList.Add(4-i); + break; + } + } + } + if (Duel.LastChainLocation == CardLocation.Grave && card.Location == CardLocation.Grave) + { + Logger.DebugWriteLine("===Exosister: enemy activate effect from GY."); + enemyMoveGrave = true; + } + } + base.OnChaining(player, card); + } + + public override void OnSelectChain(IList cards) + { + int player = Duel.LastChainPlayer; + ClientCard card = Util.GetLastChainCard(); + if (player == 1) + { + foreach (ClientCard targetCard in Duel.LastChainTargets) { + if (targetCard.Location == CardLocation.Grave) + { + Logger.DebugWriteLine("===Exosister: enemy target cards of GY."); + enemyMoveGrave = true; + break; + } + } + } + base.OnSelectChain(cards); + } + + public override void OnChainSolved(int chainIndex) + { + ChainInfo currentCard = Duel.GetCurrentSolvingChainInfo(); + if (currentCard != null && !Duel.IsCurrentSolvingChainNegated() && currentCard.ActivatePlayer == 1) + { + if (currentCard.IsCode(_CardId.MaxxC)) + enemyActivateMaxxC = true; + if (currentCard.IsCode(_CardId.LockBird)) + enemyActivateLockBird = true; + if (currentCard.IsCode(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == currentCard.RelatedCard) + { + infiniteImpermanenceList.Add(4 - i); + break; + } + } + } + } + } + + + /// + /// clear chain information + /// + public override void OnChainEnd() + { + enemyMoveGrave = false; + paxCallToField = false; + potActivate = false; + transformDestList.Clear(); + targetedMagnificaList.Clear(); + if (activatedMagnificaList.Count() > 0) + { + for (int idx = activatedMagnificaList.Count() - 1; idx >= 0; -- idx) + { + ClientCard checkTarget = activatedMagnificaList[idx]; + if (checkTarget == null || checkTarget.IsFacedown() || checkTarget.Location != CardLocation.MonsterZone) + { + activatedMagnificaList.RemoveAt(idx); + } + } + } + if (spSummonThisTurn.Count() > 0) + { + for (int idx = spSummonThisTurn.Count() - 1; idx >= 0; -- idx) + { + ClientCard checkTarget = spSummonThisTurn[idx]; + if (checkTarget == null || checkTarget.IsFacedown() || checkTarget.Location != CardLocation.MonsterZone) + { + spSummonThisTurn.RemoveAt(idx); + } + } + } + base.OnChainEnd(); + } + + public override void OnNewTurn() + { + enemyActivateMaxxC = false; + enemyActivateLockBird = false; + infiniteImpermanenceList.Clear(); + currentNegatingIdList.Clear(); + + summoned = false; + elisEffect1Activated = false; + stellaEffect1Activated = false; + irenaEffect1Activated = false; + sophiaEffect1Activated = false; + marthaEffect1Activated = false; + mikailisEffect1Activated = false; + mikailisEffect3Activated = false; + kaspitellEffect1Activated = false; + kaspitellEffect3Activated = false; + gibrineEffect1Activated = false; + gibrineEffect3Activated = false; + asophielEffect1Activated = false; + asophielEffect3Activated = false; + sakitamaEffect1Activated = false; + exosisterTransformEffectList.Clear(); + oncePerTurnEffectActivatedList.Clear(); + activatedMagnificaList.Clear(); + spSummonThisTurn.Clear(); + } + + /// + /// override for exosister's transform + /// + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + bool beginTransformCheck = false; + // transform for main monster + if (hint == HintMsg.SpSummon && min == 1 && max == 1 && transformDestList.Count() > 0) + { + // check whether for transform + if (cards.All(card => card.Location == CardLocation.Extra && card.Rank == 4 && card.HasSetcode(SetcodeExosister))) + { + beginTransformCheck = true; + } + } + // transform for magnifica + if (hint == HintMsg.ToDeck && min == 1 && max == 1 && transformDestList.Count() > 0) + { + if (cards.All(card => card.Location == CardLocation.Overlay)) + { + beginTransformCheck = true; + } + } + if (beginTransformCheck) + { + for (int idx = 0; idx < transformDestList.Count(); ++ idx) + { + int targetId = transformDestList[idx]; + ClientCard targetCard = cards.FirstOrDefault(card => card.IsCode(targetId)); + if (targetCard != null) + { + List result = new List(); + result.Add(targetCard); + transformDestList.RemoveAt(idx); + spSummonThisTurn.AddRange(result); + return Util.CheckSelectCount(result, cards, min, max); + } + } + } + + if (Util.ChainContainsCard(_CardId.EvenlyMatched) && Util.ChainContainPlayer(1) && hint == HintMsg.Remove) + { + int botCount = Bot.GetMonsterCount() + Bot.GetSpellCount(); + int oppositeCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount(); + if (botCount - oppositeCount == min && min == max) + { + Logger.DebugWriteLine("===Exosister: Evenly Matched activated."); + List allBotCards = new List(); + allBotCards.AddRange(Bot.GetMonsters()); + allBotCards.AddRange(Bot.GetSpells()); + List importantList = new List(); + + List magnificaList = allBotCards.Where(card => card.IsCode(CardId.ExosistersMagnifica)).ToList(); + if (magnificaList.Count > 0) + { + allBotCards.RemoveAll(c => magnificaList.Contains(c)); + importantList.AddRange(magnificaList); + } + if (!mikailisEffect1Activated) + { + List mikailisList = allBotCards.Where(card => spSummonThisTurn.Contains(card) + && card.IsCode(CardId.ExosisterMikailis) && card.IsFaceup()).ToList(); + if (mikailisList.Count > 0) + { + allBotCards.RemoveAll(c => mikailisList.Contains(c)); + importantList.AddRange(mikailisList); + } + } + if (!gibrineEffect1Activated) + { + List gibrineList = allBotCards.Where(card => spSummonThisTurn.Contains(card) + && card.IsCode(CardId.ExosisterGibrine) && card.IsFaceup()).ToList(); + if (gibrineList.Count > 0) + { + allBotCards.RemoveAll(c => gibrineList.Contains(c)); + importantList.AddRange(gibrineList); + } + } + if (!oncePerTurnEffectActivatedList.Contains(CardId.ExosisterVadis)) + { + List vadisList = allBotCards.Where(card => card.IsCode(CardId.ExosisterVadis) && card.IsFacedown()).ToList(); + if (vadisList.Count > 0) + { + allBotCards.RemoveAll(c => vadisList.Contains(c)); + importantList.AddRange(vadisList); + } + } + List xyzList = allBotCards.Where(card => card.IsMonster() && card.HasType(CardType.Xyz)).ToList(); + if (xyzList.Count > 0) + { + xyzList.Sort(CardContainer.CompareCardAttack); + xyzList.Reverse(); + allBotCards.RemoveAll(c => xyzList.Contains(c)); + importantList.AddRange(xyzList); + } + List monsterList = allBotCards.Where(card => card.IsMonster()).ToList(); + if (monsterList.Count > 0) + { + monsterList.Sort(CardContainer.CompareCardAttack); + monsterList.Reverse(); + allBotCards.RemoveAll(c => monsterList.Contains(c)); + importantList.AddRange(monsterList); + } + List faceDownList = allBotCards.Where(card => card.IsFacedown()).ToList(); + if (faceDownList.Count > 0) + { + allBotCards.RemoveAll(c => faceDownList.Contains(c)); + importantList.AddRange(ShuffleCardList(faceDownList)); + } + + importantList.Reverse(); + return Util.CheckSelectCount(importantList, cards, min, max); + } + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (Util.IsTurn1OrMain2()) + { + bool turnDefense = false; + if (cardId == CardId.DivineArsenalAAZEUS_SkyThunder || cardId == CardId.ExosistersMagnifica) + { + turnDefense = true; + } + if (!cardData.HasType(CardType.Xyz)) + { + turnDefense = true; + } + if (turnDefense) + { + return CardPosition.FaceUpDefence; + } + } + if (Duel.Player == 1) + { + if (!cardData.HasType(CardType.Xyz) || cardData.Defense >= cardData.Attack || Util.IsOneEnemyBetterThanValue(cardData.Attack, true)) + { + return CardPosition.FaceUpDefence; + } + } + int bestBotAttack = Math.Max(Util.GetBestAttack(Bot), cardData.Attack); + if (Util.IsAllEnemyBetterThanValue(bestBotAttack, true)) + { + return CardPosition.FaceUpDefence; + } + } + return base.OnSelectPosition(cardId, positions); + } + + /// + /// override for magnifica's spsummon + /// + public override bool OnSelectYesNo(int desc) + { + // magnifica spsummon + if (desc == Util.GetStringId(CardId.ExosistersMagnifica, 2)) + { + return true; + } + // pax spsummon + if (desc == Util.GetStringId(CardId.ExosisterPax, 1)) + { + return paxCallToField; + } + + return base.OnSelectYesNo(desc); + } + + /// + /// override for returnia's option + /// + public override int OnSelectOption(IList options) + { + // check retunia + int spSummonOption = -1; + int banishOption = -1; + int doNothingOption = -1; + for (int idx = 0; idx < options.Count(); ++ idx) + { + int option = options[idx]; + if (option == Util.GetStringId(CardId.ExosisterReturnia, 0)) + { + spSummonOption = idx; + } else if (option == Util.GetStringId(CardId.ExosisterReturnia, 1)) + { + banishOption = idx; + } else if (option == Util.GetStringId(CardId.ExosisterReturnia, 2)) + { + doNothingOption = idx; + } + } + + if (spSummonOption >= 0 || banishOption >= 0 || doNothingOption >= 0) + { + if (spSummonOption < 0 && banishOption < 0) + { + return doNothingOption; + } + if (banishOption >= 0) + { + // banish problem card + ClientCard target = GetProblematicEnemyCard(true); + if (target != null) + { + AI.SelectCard(target); + return banishOption; + } + + // dump banish + target = GetBestEnemyCard(false, false); + if (target != null) + { + AI.SelectCard(target); + return banishOption; + } + } + if (spSummonOption >= 0) + { + // TODO + } + } + + // check pot + int potBanish6Option = -1; + int potBanish3Option = -1; + for (int idx = 0; idx < options.Count(); ++idx) + { + int option = options[idx]; + if (option == Util.GetStringId(CardId.PotofExtravagance, 0)) + { + potBanish3Option = idx; + } + else if (option == Util.GetStringId(CardId.PotofExtravagance, 1)) + { + potBanish6Option = idx; + } + } + if (potBanish3Option >= 0 || potBanish6Option >= 0) + { + if (Bot.ExtraDeck.Count() > 9 && potBanish6Option >= 0) + { + return potBanish6Option; + } + return potBanish3Option; + } + + return base.OnSelectOption(options); + } + + public bool AshBlossomActivate() + { + if (CheckWhetherNegated(true) || !CheckLastChainShouldNegated()) return false; + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + if (CheckAtAdvantage()) + { + return false; + } + } + return DefaultAshBlossomAndJoyousSpring(); + } + + public bool MaxxCActivate() + { + if (CheckWhetherNegated(true) || Duel.LastChainPlayer == 0) return false; + return DefaultMaxxC(); + } + + public bool InfiniteImpermanenceActivate() + { + if (CheckWhetherNegated()) return false; + // negate before effect used + foreach(ClientCard m in Enemy.GetMonsters()) + { + if (m.IsMonsterShouldBeDisabledBeforeItUseEffect() && !m.IsDisabled() && Duel.LastChainPlayer != 0) + { + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++ i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(m); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ( (this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || (Util.IsChainTarget(Card)) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true); + List enemyMonsters = Enemy.GetMonsters(); + AI.SelectCard(target); + infiniteImpermanenceList.Add(this_seq); + return true; + } + } + if ( (LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || LastChainCard.IsDisabled() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget()) ) + return false; + // negate monsters + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemyMonsters = Enemy.GetMonsters(); + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + foreach (ClientCard card in enemyMonsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + return true; + } + } + } + return true; + } + + public bool CalledbytheGraveActivate() + { + if (CheckWhetherNegated(true)) return false; + if (Duel.LastChainPlayer == 1) + { + // negate + if (Util.GetLastChainCard().IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (CheckCalledbytheGrave(code) > 0) return false; + if (Util.GetLastChainCard().IsCode(_CardId.MaxxC) && CheckAtAdvantage()) + { + return false; + } + if (code == CardId.DimensionShifter) + { + return false; + } + ClientCard targetCard = Enemy.Graveyard.GetFirstMatchingCard(card => card.IsMonster() && card.IsOriginalCode(code)); + if (targetCard != null) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(targetCard); + currentNegatingIdList.Add(code); + return true; + } + } + + // banish target + foreach (ClientCard cards in Enemy.Graveyard) + { + if (Duel.ChainTargets.Contains(cards)) + { + int code = cards.Id; + AI.SelectCard(cards); + currentNegatingIdList.Add(code); + return true; + } + } + + // become targets + if (Duel.ChainTargets.Contains(Card)) + { + List enemyMonsters = Enemy.Graveyard.GetMatchingCards(card => card.IsMonster()).ToList(); + if (enemyMonsters.Count > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + int code = enemyMonsters[0].Id; + AI.SelectCard(code); + currentNegatingIdList.Add(code); + return true; + } + } + } + + // avoid danger monster in grave + if (Duel.LastChainPlayer == 1) return false; + List targets = CheckDangerousCardinEnemyGrave(true); + if (targets.Count() > 0) { + int code = targets[0].GetOriginCode(); + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(targets); + currentNegatingIdList.Add(code); + return true; + } + + return false; + } + + public List GetPotofExtravaganceBanish() + { + List banishList = new List(); + ClientCard aaZeus = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.DivineArsenalAAZEUS_SkyThunder)); + if (aaZeus != null) + { + banishList.Add(aaZeus); + } + + ClientCard diamond = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.StellarknightConstellarDiamond)); + if (diamond != null) + { + banishList.Add(diamond); + } + + ClientCard caduceus = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.TellarknightConstellarCaduceus)); + if (caduceus != null) + { + banishList.Add(caduceus); + } + + ClientCard evilswarm = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(_CardId.EvilswarmExcitonKnight)); + if (evilswarm != null) + { + banishList.Add(evilswarm); + } + + // second asophiel + if (Bot.ExtraDeck.Count(card => card.IsCode(CardId.ExosisterAsophiel)) > 1) + { + ClientCard asophiel2 = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosisterAsophiel)); + banishList.Add(asophiel2); + } + + ClientCard gibrine = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosisterGibrine)); + if (gibrine != null) + { + banishList.Add(gibrine); + } + + // 6 done + + // third mikailis + if (Bot.ExtraDeck.Count(card => card.IsCode(CardId.ExosisterMikailis)) > 2) + { + ClientCard mikailis3 = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosisterMikailis)); + banishList.Add(mikailis3); + } + + // first asophiel + ClientCard asophiel1 = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosisterAsophiel) && !banishList.Contains(card)); + if (asophiel1 != null) + { + banishList.Add(asophiel1); + } + + ClientCard donner = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.DonnerDaggerFurHire)); + if (donner != null) + { + banishList.Add(donner); + } + + // 9 done + + // second kaspitell + if (Bot.ExtraDeck.Count(card => card.IsCode(CardId.ExosisterKaspitell)) > 1) + { + ClientCard kaspitell = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosisterKaspitell)); + banishList.Add(kaspitell); + } + + // second magnifica + if (Bot.ExtraDeck.Count(card => card.IsCode(CardId.ExosistersMagnifica)) > 1) + { + ClientCard magnifica2 = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosistersMagnifica)); + banishList.Add(magnifica2); + } + + // second mikailis + if (Bot.ExtraDeck.Count(card => card.IsCode(CardId.ExosisterMikailis)) > 1) + { + ClientCard mikailis2 = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosisterMikailis) && !banishList.Contains(card)); + banishList.Add(mikailis2); + } + + // first magnifica + ClientCard magnifica1 = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosistersMagnifica) && !banishList.Contains(card)); + if (magnifica1 != null) + { + banishList.Add(magnifica1); + } + + // first kaspitell + ClientCard kaspitell1 = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosisterKaspitell) && !banishList.Contains(card)); + if (kaspitell1 != null) + { + banishList.Add(kaspitell1); + } + + // first mikailis1 + ClientCard mikailis1 = Bot.ExtraDeck.FirstOrDefault(card => card.IsCode(CardId.ExosisterMikailis) && !banishList.Contains(card)); + if (mikailis1 != null) + { + banishList.Add(mikailis1); + } + + return banishList; + } + + public bool PotofExtravaganceActivate() + { + if (CheckWhetherNegated()) + { + return false; + } + List banishList = GetPotofExtravaganceBanish(); + + List addToHandOrderList = new List(); + + bool marthaActivatable = CheckMarthaActivatable(); + if (marthaActivatable) + { + if (!Bot.HasInHand(CardId.ExosisterMartha)) + { + addToHandOrderList.Add(CardId.ExosisterMartha); + } + if (Bot.HasInHand(CardId.ExosisterMartha) && !Bot.HasInHandOrInSpellZone(_CardId.CalledByTheGrave)) + { + addToHandOrderList.Add(_CardId.CalledByTheGrave); + } + } + int exosisterCount = Bot.Hand.Count(card => card?.Data != null && card.HasSetcode(SetcodeExosister)); + if (!stellaEffect1Activated && CheckCalledbytheGrave(CardId.ExosisterStella) == 0) + { + if (!Bot.HasInHand(CardId.ExosisterStella) && exosisterCount > 0) + { + addToHandOrderList.Add(CardId.ExosisterStella); + } + if (Bot.HasInHand(CardId.ExosisterStella) && exosisterCount == 0) + { + addToHandOrderList.AddRange(new List{ + CardId.ExosisterSophia, CardId.ExosisterIrene, CardId.ExosisterStella, CardId.ExosisterMartha, CardId.ExosisterElis}); + } + } + if (exosisterCount >= 0 && !Bot.HasInHandOrInSpellZone(CardId.ExosisterReturnia)) + { + addToHandOrderList.Add(CardId.ExosisterReturnia); + } + List remainOrderList = new List{ + CardId.Aratama, CardId.Sakitama, _CardId.MaxxC, _CardId.AshBlossom, _CardId.InfiniteImpermanence, + _CardId.CalledByTheGrave, CardId.ExosisterVadis, CardId.ExosisterReturnia, CardId.ExosisterPax + }; + addToHandOrderList.AddRange(remainOrderList); + + AI.SelectCard(banishList); + AI.SelectNextCard(addToHandOrderList); + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + + potActivate = true; + return true; + } + + public bool SakitamaActivate() + { + // summon + if (Card.Location == CardLocation.Hand) + { + // summon for xyz + if (Bot.GetMonsters().Count(card => CheckAbleForXyz(card)) == 1) + { + AI.SelectCard(CardId.Aratama, CardId.Sakitama); + sakitamaEffect1Activated = true; + return true; + } + + // summon for summon donner + if (!CheckLessOperation() && Bot.HasInExtra(CardId.DonnerDaggerFurHire) && + !Bot.HasInHand(CardId.ExosisterMartha) || Bot.HasInHandOrInSpellZone(CardId.ExosisterReturnia)) + { + List illegalList = Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Xyz) && card.Level != 4 + && (card.Data == null || !card.HasSetcode(SetcodeExosister))).ToList(); + if (illegalList.Count() > 0) + { + if (illegalList.Count() == 1) + { + List otherMaterialList = Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Xyz)).ToList(); + otherMaterialList.Sort(CardContainer.CompareCardAttack); + illegalList.AddRange(otherMaterialList); + } + if (illegalList.Count() == 1) + { + Logger.DebugWriteLine("===Exosister: activate sakitama for donner"); + AI.SelectCard(CardId.Aratama, CardId.Sakitama); + sakitamaEffect1Activated = true; + return true; + } + } + } + return false; + } + // add to hand + if (Card.Location == CardLocation.Grave) + { + AI.SelectCard(CardId.Sakitama, CardId.Aratama); + return true; + } + return true; + } + + public bool DonnerDaggerFurHireActivate() + { + if (CheckAtAdvantage() && !Bot.HasInHand(CardId.ExosisterMartha) && !Bot.HasInHandOrInSpellZone(CardId.ExosisterReturnia)) + { + return false; + } + + ClientCard targetCard = Util.GetProblematicEnemyMonster(canBeTarget: true); + if (targetCard == null) + { + List enemyMonsters = Enemy.GetMonsters(); + if (enemyMonsters.Count() > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + targetCard = enemyMonsters[0]; + } + } + + if (targetCard != null) + { + AI.SelectCard(Card); + AI.SelectNextCard(targetCard); + return true; + } + + return false; + } + + public bool ExosisterElisActivate() + { + if (ActivateDescription != Util.GetStringId(CardId.ExosisterElis, 0)) + { + return false; + } + + if (Bot.GetMonsters().Count(card => CheckAbleForXyz(card)) == 1) + { + elisEffect1Activated = true; + return true; + } + + return false; + } + + public bool ExosisterStellaActivate() + { + return ExosisterStellaActivateInner(true); + } + + public bool ExosisterStellaSecondActivate() + { + return ExosisterStellaActivateInner(false); + } + + public bool ExosisterStellaActivateInner(bool checkMartha = false) + { + if (ActivateDescription != Util.GetStringId(CardId.ExosisterStella, 0) || CheckWhetherNegated(true)) + { + return false; + } + + bool ableToXyz = Bot.GetMonsters().Count(card => CheckAbleForXyz(card)) >= 2; + + if (CheckLessOperation() && ableToXyz) + { + return false; + } + if (checkMartha && Bot.HasInHand(CardId.ExosisterMartha) && ableToXyz + && Bot.Hand.Count(card => card.IsMonster() && card.HasSetcode(CardId.ExosisterMartha)) == 1) + { + return false; + } + + AI.SelectCard(CardId.ExosisterSophia, CardId.ExosisterIrene, CardId.ExosisterStella, CardId.ExosisterElis); + stellaEffect1Activated = true; + return true; + } + + public bool ExosisterIreneActivate() + { + if (ActivateDescription != Util.GetStringId(CardId.ExosisterIrene, 0) || CheckWhetherNegated(true)) + { + return false; + } + + List shuffleList = new List(); + foreach (int cardId in new List{CardId.ExosisterIrene, CardId.ExosisterSophia, CardId.ExosisterArment}) + { + if (Bot.HasInHand(cardId)) + { + shuffleList.Add(cardId); + } + } + if (elisEffect1Activated || Bot.Hand.Count(card => card.IsCode(CardId.ExosisterElis)) > 1) + { + shuffleList.Add(CardId.ExosisterElis); + } + foreach (int cardId in new List{CardId.ExosisterPax, CardId.ExosisterReturnia, CardId.ExosisterVadis}) + { + if ((oncePerTurnEffectActivatedList.Contains(cardId) && Bot.HasInHand(cardId)) || Bot.Hand.Count(card => card.IsCode(cardId)) > 1) + { + shuffleList.Add(cardId); + } + } + + if (shuffleList.Count() > 0) + { + Logger.DebugWriteLine("===Exosister: irene return " + shuffleList[0]); + AI.SelectCard(shuffleList); + return true; + } + return false; + } + + public bool ExosisterSophiaActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.ExosisterSophia, 0) && !CheckWhetherNegated(true)) + { + sophiaEffect1Activated = true; + return true; + } + return false; + } + + public bool ExosisterMarthaActivate() + { + if (ActivateDescription != Util.GetStringId(CardId.ExosisterMartha, 0)) { + return false; + } + if (CheckLessOperation() && Bot.GetMonsterCount() > 0) + { + return false; + } + + marthaEffect1Activated = true; + return true; + } + + public bool DefaultExosisterTransform() + { + List canTransformList = new List + { + CardId.ExosisterElis, CardId.ExosisterStella, CardId.ExosisterIrene, CardId.ExosisterSophia, CardId.ExosisterMartha + }; + if (Card.IsDisabled() || !canTransformList.Contains(Card.Id)) + { + return false; + } + List checkTransformCode = new List{ + Util.GetStringId(CardId.ExosisterElis, 1), + Util.GetStringId(CardId.ExosisterStella, 1), + Util.GetStringId(CardId.ExosisterIrene, 1), + Util.GetStringId(CardId.ExosisterSophia, 1), + Util.GetStringId(CardId.ExosisterMartha, 1) + }; + if (!checkTransformCode.Contains(ActivateDescription) && ActivateDescription != -1) + { + return false; + } + + // mikailis + if (!Bot.HasInMonstersZone(CardId.ExosisterMikailis) && !mikailisEffect1Activated && (Duel.Player == 1 || !mikailisEffect3Activated) + && !transformDestList.Contains(CardId.ExosisterMikailis) && Bot.HasInExtra(CardId.ExosisterMikailis)) + { + exosisterTransformEffectList.Add(Card.Id); + transformDestList.Add(CardId.ExosisterMikailis); + return true; + } + + // kaspitell on bot's turn + if (!Bot.HasInMonstersZone(CardId.ExosisterKaspitell) && !kaspitellEffect3Activated && Duel.Player == 0 + && !transformDestList.Contains(CardId.ExosisterKaspitell) && Bot.HasInExtra(CardId.ExosisterKaspitell)) + { + exosisterTransformEffectList.Add(Card.Id); + transformDestList.Add(CardId.ExosisterKaspitell); + return true; + } + + // gibrine + if (!Bot.HasInMonstersZone(CardId.ExosisterGibrine) && !gibrineEffect1Activated + && !transformDestList.Contains(CardId.ExosisterGibrine) && Bot.HasInExtra(CardId.ExosisterGibrine)) + { + exosisterTransformEffectList.Add(Card.Id); + transformDestList.Add(CardId.ExosisterGibrine); + return true; + } + + // asophiel + if (!Bot.HasInMonstersZone(CardId.ExosisterAsophiel) && !asophielEffect1Activated + && !transformDestList.Contains(CardId.ExosisterAsophiel) && Bot.HasInExtra(CardId.ExosisterAsophiel)) + { + exosisterTransformEffectList.Add(Card.Id); + transformDestList.Add(CardId.ExosisterAsophiel); + return true; + } + + // kaspitell on bot's turn + if (!Bot.HasInMonstersZone(CardId.ExosisterKaspitell) && !kaspitellEffect1Activated + && !transformDestList.Contains(CardId.ExosisterKaspitell) && Bot.HasInExtra(CardId.ExosisterKaspitell)) + { + exosisterTransformEffectList.Add(Card.Id); + transformDestList.Add(CardId.ExosisterKaspitell); + return true; + } + + return false; + } + + public bool ExosisterMikailisActivate() + { + // banish + if (ActivateDescription == Util.GetStringId(CardId.ExosisterMikailis, 0)) + { + // activate after search + if (Duel.Player == 0 && !mikailisEffect3Activated && Duel.Phase < DuelPhase.End && !DefaultOnBecomeTarget()) + { + return false; + } + + // banish problem card + ClientCard target = GetProblematicEnemyCard(true); + if (target != null && Duel.LastChainPlayer != 0) + { + removeChosenList.Add(target); + mikailisEffect1Activated = true; + AI.SelectCard(target); + return true; + } + + // banish target + if (Duel.LastChainPlayer == 1) + { + List targetList = Duel.LastChainTargets.Where(card => card.Controller == 1 && + (card.Location == CardLocation.Grave || card.Location == CardLocation.MonsterZone || card.Location == CardLocation.SpellZone || card.Location == CardLocation.FieldZone)).ToList(); + if (targetList.Count() > 0) + { + mikailisEffect1Activated = true; + AI.SelectCard(ShuffleCardList(targetList)); + return true; + } + } + + // dump banish + target = GetBestEnemyCard(false, true, true); + if ((DefaultOnBecomeTarget() && !Util.ChainContainsCard(_CardId.EvenlyMatched)) || Bot.UnderAttack || (Duel.Phase == DuelPhase.End && Duel.LastChainPlayer != 0) + || (Duel.Player == 0 && Bot.GetMonsters().Count(card => card.HasType(CardType.Xyz) && card.Rank == 4 && card.HasSetcode(SetcodeExosister)) == 2 && Duel.LastChainPlayer != 0) + || (Duel.Player == 1 && Enemy.GetMonsterCount() >= 2)) + { + mikailisEffect1Activated = true; + AI.SelectCard(target); + return true; + } + return false; + } + + // search + if (CheckWhetherNegated(true)) + { + return false; + } + + List searchTarget = new List{ + CardId.ExosisterReturnia, + CardId.ExosisterVadis, + CardId.ExosisterPax, + CardId.ExosisterArment + }; + List firstSearchList = new List(); + List lastSearchList = new List(); + foreach (int cardId in searchTarget) + { + if (Bot.HasInHandOrInSpellZone(cardId) || CheckRemainInDeck(cardId) == 0) + { + lastSearchList.Add(cardId); + continue; + } + if (cardId == CardId.ExosisterReturnia && Bot.GetMonsters().Any(card => card.IsFacedown() || !card.HasSetcode(SetcodeExosister))) + { + lastSearchList.Add(cardId); + continue; + } + firstSearchList.Add(cardId); + } + firstSearchList.AddRange(lastSearchList); + + mikailisEffect3Activated = true; + SelectDetachMaterial(Card); + AI.SelectNextCard(firstSearchList); + return true; + } + + public bool ExosisterKaspitellActivate() + { + // block spsummon from GY + if (ActivateDescription == Util.GetStringId(CardId.ExosisterKaspitell, 0) || ActivateDescription == -1) + { + if (Enemy.HasInMonstersZone(CardId.InspectorBoarder, true)) + { + return false; + } + kaspitellEffect1Activated = true; + return true; + } + + // search + if (CheckWhetherNegated(true)) + { + return false; + } + + // search martha for activate + if (CheckMarthaActivatable() && CheckRemainInDeck(CardId.ExosisterMartha) > 0 && !Bot.HasInHand(CardId.ExosisterMartha)) + { + kaspitellEffect3Activated = true; + SelectDetachMaterial(Card); + AI.SelectNextCard(CardId.ExosisterMartha); + return true; + } + // search sophia for draw + if (!summoned && !sophiaEffect1Activated && CheckCalledbytheGrave(CardId.ExosisterSophia) == 0 && !Bot.HasInHand(CardId.ExosisterSophia) + && (Bot.GetMonsters().Count(card => CheckAbleForXyz(card)) == 1 || (Bot.HasInHand(CardId.ExosisterElis) && !elisEffect1Activated))) + { + kaspitellEffect3Activated = true; + SelectDetachMaterial(Card); + AI.SelectNextCard(CardId.ExosisterSophia); + return true; + } + // search stella for next xyz + if (!summoned && !Bot.HasInHand(CardId.ExosisterStella) && !stellaEffect1Activated && CheckCalledbytheGrave(CardId.ExosisterStella) == 0 + && CheckRemainInDeck(CardId.ExosisterStella) > 0 && Bot.Hand.Any(card => card?.Data != null && card.IsMonster() && card.HasSetcode(SetcodeExosister))) + { + kaspitellEffect3Activated = true; + SelectDetachMaterial(Card); + AI.SelectNextCard(CardId.ExosisterStella); + return true; + } + kaspitellEffect3Activated = true; + SelectDetachMaterial(Card); + AI.SelectNextCard(CardId.ExosisterMartha, CardId.ExosisterStella, CardId.ExosisterElis, CardId.ExosisterSophia, CardId.ExosisterIrene); + return true; + } + + public bool ExosisterGibrineActivate() + { + // negate + if (ActivateDescription == Util.GetStringId(CardId.ExosisterGibrine, 0)) + { + if (Duel.Player == 1) + { + ClientCard target = Enemy.MonsterZone.GetShouldBeDisabledBeforeItUseEffectMonster(); + if (target != null) + { + gibrineEffect1Activated = true; + AI.SelectCard(target); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + if (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.MonsterZone && + !LastChainCard.IsDisabled() && !LastChainCard.IsShouldNotBeTarget() && !LastChainCard.IsShouldNotBeMonsterTarget()) + { + gibrineEffect1Activated = true; + AI.SelectCard(LastChainCard); + return true; + } + + return false; + } + + // gain atk + if (CheckWhetherNegated(true)) + { + return false; + } + gibrineEffect3Activated = true; + SelectDetachMaterial(Card); + return true; + } + + public bool ExosisterAsophielActivate() + { + // block activate from GY + if (ActivateDescription == Util.GetStringId(CardId.ExosisterAsophiel, 0) || ActivateDescription == -1) + { + if (Enemy.HasInMonstersZone(CardId.InspectorBoarder, true)) + { + return false; + } + asophielEffect1Activated = true; + return true; + } + + // return hand + if (CheckWhetherNegated(true)) + { + return false; + } + ClientCard targetCard = Util.GetProblematicEnemyMonster(0, true); + if (targetCard != null) + { + asophielEffect3Activated = true; + SelectDetachMaterial(Card); + AI.SelectNextCard(targetCard); + return true; + } + + return false; + } + + public bool ExosistersMagnificaActivateTrigger() + { + // sp summon + if (ActivateDescription == Util.GetStringId(CardId.ExosistersMagnifica, 1)) + { + // return after effect used + if (activatedMagnificaList.Contains(Card)) + { + // return to Mikailis for danger card + if (Card.Overlays.Contains(CardId.ExosisterMikailis) && !mikailisEffect1Activated) + { + ClientCard target = GetProblematicEnemyCard(true); + if (target != null && !Duel.CurrentChain.Any(card => card == Card)) + { + transformDestList.Add(CardId.ExosisterMikailis); + return true; + } + } + + // negate important card + if (Card.Overlays.Contains(CardId.ExosisterGibrine) && !gibrineEffect1Activated) + { + ClientCard target = Enemy.MonsterZone.GetShouldBeDisabledBeforeItUseEffectMonster(); + if (target != null) + { + transformDestList.Add(CardId.ExosisterGibrine); + return true; + } + } + } + + // become target + if ((DefaultOnBecomeTarget() && !Util.ChainContainsCard(_CardId.EvenlyMatched)) || (Duel.CurrentChain.Any(c => c == Card) && Duel.LastChainPlayer != 0)) + { + targetedMagnificaList.Add(Card); + transformDestList.AddRange(new List{CardId.ExosistersMagnifica, CardId.ExosisterMikailis, CardId.ExosisterGibrine, CardId.ExosisterKaspitell, CardId.ExosisterAsophiel}); + return true; + } + } + return false; + } + public bool ExosistersMagnificaActivateBanish() + { + // banish + if (ActivateDescription == Util.GetStringId(CardId.ExosistersMagnifica, 0)) + { + if (CheckWhetherNegated()) + { + return false; + } + // banish problem card + ClientCard target = GetProblematicEnemyCard(); + bool isProblemCard = false; + if (target != null) + { + isProblemCard = true; + Logger.DebugWriteLine("===Exosister: magnifica target 1: " + target?.Name); + } + + // banish target + if (Duel.LastChainPlayer == 1 && target == null) + { + List currentTargetList = Duel.LastChainTargets.Where(card => card.Controller == 1 && + (card.Location == CardLocation.MonsterZone || card.Location == CardLocation.SpellZone || card.Location == CardLocation.FieldZone)).ToList(); + if (currentTargetList.Count() > 0) + { + target = ShuffleCardList(currentTargetList)[0]; + Logger.DebugWriteLine("===Exosister: magnifica target 2: " + target?.Name); + } + } + + // dump banish + if (target == null) + { + target = GetBestEnemyCard(false, false); + bool check1 = !DefaultOnBecomeTarget() || Util.ChainContainsCard(_CardId.EvenlyMatched); + bool check2 = !targetedMagnificaList.Contains(Card); + bool check3 = !Bot.UnderAttack; + bool check4 = Duel.Phase != DuelPhase.End; + bool check5 = Duel.Player == 0 || Enemy.GetMonsterCount() < 2; + Logger.DebugWriteLine("===Exosister: magnifica check flag: " + check1 + " " + check2 + " " + check3 + " " + check4 + " " + check5); + if (check1 && check2 && check3 && check4 && check5) + { + target = null; + } + } + + if (target != null && (Duel.LastChainPlayer != 0 || Util.GetLastChainCard() == Card)) + { + if (isProblemCard) + { + removeChosenList.Add(target); + } + Logger.DebugWriteLine("===Exosister: magnifica target final: " + target?.Name); + activatedMagnificaList.Add(Card); + AI.SelectCard(CardId.ExosisterGibrine, CardId.ExosisterAsophiel, CardId.ExosisterKaspitell, CardId.ExosisterMikailis); + AI.SelectNextCard(target); + return true; + } + + return false; + } + return false; + } + + public bool ExosisterPaxActivate() + { + if (potActivate || Bot.LifePoints <= 800) + { + return false; + } + + List checkListForSpSummon = new List{ + CardId.ExosisterSophia, CardId.ExosisterIrene, CardId.ExosisterStella, CardId.ExosisterMartha, CardId.ExosisterElis + }; + List checkListForSearch = new List{ + CardId.ExosisterMartha, CardId.ExosisterStella, CardId.ExosisterVadis, CardId.ExosisterReturnia, CardId.ExosisterSophia, + CardId.ExosisterIrene, CardId.ExosisterArment, CardId.ExosisterElis + }; + if (Duel.Player == 0 && Duel.LastChainPlayer != 0) + { + // search returnia for banish + if (CheckAtAdvantage() && GetProblematicEnemyCard(true) != null && CheckRemainInDeck(CardId.ExosisterReturnia) > 0 && !Bot.HasInHandOrInSpellZone(CardId.ExosisterReturnia)) + { + if (Bot.GetMonsterCount() > 0 && Bot.GetMonsters().All(card => card.IsFaceup() && card.HasSetcode(SetcodeExosister))) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + oncePerTurnEffectActivatedList.Add(Card.Id); + AI.SelectCard(CardId.ExosisterReturnia); + paxCallToField = false; + return true; + } + } + + // search martha for activate + if (CheckMarthaActivatable() && CheckRemainInDeck(CardId.ExosisterMartha) > 0 && !Bot.HasInHand(CardId.ExosisterMartha)) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + oncePerTurnEffectActivatedList.Add(Card.Id); + AI.SelectCard(CardId.ExosisterMartha); + paxCallToField = false; + return true; + } + + // stella relative + if (!stellaEffect1Activated && CheckCalledbytheGrave(CardId.ExosisterStella) == 0) + { + // try to search stella + if (Bot.Hand.Count(card => card.IsCode(CardId.ExosisterStella)) == 0 && CheckRemainInDeck(CardId.ExosisterStella) > 0) + { + bool shouldSpSummon = !CheckLessOperation() && summoned && Bot.HasInMonstersZoneOrInGraveyard(CardId.ExosisterElis); + if (Bot.Hand.Any(card => card?.Data != null && card.IsMonster() && card.HasSetcode(SetcodeExosister))) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + oncePerTurnEffectActivatedList.Add(Card.Id); + AI.SelectCard(CardId.ExosisterStella); + paxCallToField = shouldSpSummon; + return true; + } + } + + // search monster for stella to summon + bool searchExosisterMonster = false; + if (Bot.HasInHand(CardId.ExosisterStella) && Bot.Hand.Count(card => card?.Data != null && card.IsMonster() && card.HasSetcode(SetcodeExosister)) == 1) + { + searchExosisterMonster = true; + } + if (Bot.HasInMonstersZone(CardId.ExosisterStella) && Bot.Hand.Count(card => card?.Data != null && card.IsMonster() && card.HasSetcode(SetcodeExosister)) == 0) + { + searchExosisterMonster = true; + } + if (searchExosisterMonster) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + oncePerTurnEffectActivatedList.Add(Card.Id); + AI.SelectCard(CardId.ExosisterSophia, CardId.ExosisterIrene, CardId.ExosisterMartha, CardId.ExosisterStella, CardId.ExosisterElis); + paxCallToField = false; + return true; + } + } + + // addition summon + if (Bot.GetMonsters().Count(card => CheckAbleForXyz(card)) == 1 && summoned && !CheckLessOperation()) + { + if ( (sakitamaEffect1Activated || !Bot.HasInHand(CardId.Sakitama)) + && (stellaEffect1Activated || !Bot.HasInMonstersZone(CardId.ExosisterStella)) + && (elisEffect1Activated || !Bot.HasInHand(CardId.ExosisterElis)) + ) + { + foreach (int checkId in checkListForSpSummon) + { + int checkTarget = CheckExosisterMentionCard(checkId); + if (checkTarget > 0 && Bot.HasInMonstersZoneOrInGraveyard(checkId) && CheckRemainInDeck(checkTarget) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + oncePerTurnEffectActivatedList.Add(Card.Id); + AI.SelectCard(checkId); + paxCallToField = true; + return true; + } + } + } + } + } + + // in danger + bool inDanger = CheckInDanger(); + + // trigger transform + CheckEnemyMoveGrave(); + + bool forReturnia = false; + if (!oncePerTurnEffectActivatedList.Contains(CardId.ExosisterReturnia) && Bot.HasInSpellZone(CardId.ExosisterReturnia) && Bot.GetMonsters().Count() == 0) + { + forReturnia = true; + } + + // become target + if (enemyMoveGrave || DefaultOnBecomeTarget() || inDanger || forReturnia) + { + List checkList = checkListForSpSummon; + bool shouldSpSummon = enemyMoveGrave || inDanger || forReturnia; + if (!shouldSpSummon && !Bot.HasInMonstersZone(new List{ + CardId.ExosisterElis, CardId.ExosisterStella, CardId.ExosisterIrene, CardId.ExosisterSophia, CardId.ExosisterMartha})) + { + shouldSpSummon = true; + } + if (CheckAtAdvantage() && !enemyMoveGrave) + { + shouldSpSummon = false; + checkList = checkListForSearch; + } + foreach (int checkId in checkList) + { + bool checkSuccessFlag = false; + + if (shouldSpSummon) + { + int checkTarget = CheckExosisterMentionCard(checkId); + checkSuccessFlag = checkTarget > 0 && Bot.HasInMonstersZoneOrInGraveyard(checkTarget) && CheckRemainInDeck(checkId) > 0 + && !exosisterTransformEffectList.Contains(checkId) && !Bot.HasInMonstersZone(checkId); + } else + { + checkSuccessFlag = !Bot.HasInHandOrHasInMonstersZone(checkId) && !Bot.HasInSpellZone(checkId) && CheckRemainInDeck(checkId) > 0; + } + + if (checkSuccessFlag) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + oncePerTurnEffectActivatedList.Add(Card.Id); + AI.SelectCard(checkId); + paxCallToField = shouldSpSummon; + return true; + } + } + } + + return false; + } + + public bool ExosisterPaxActivateForEndSearch() + { + if (potActivate || Bot.LifePoints <= 800) + { + return false; + } + + if (Duel.Player == 0 || Duel.Phase >= DuelPhase.End) + { + // search spell/trap + List checkSpellTrapListForSearch = new List{ + CardId.ExosisterVadis, CardId.ExosisterMartha, CardId.ExosisterReturnia, CardId.ExosisterStella, CardId.ExosisterSophia, + CardId.ExosisterIrene, CardId.ExosisterArment, CardId.ExosisterElis + }; + foreach (int checkId in checkSpellTrapListForSearch) + { + if (!Bot.HasInHandOrHasInMonstersZone(checkId) && !Bot.HasInSpellZone(checkId) && CheckRemainInDeck(checkId) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + oncePerTurnEffectActivatedList.Add(Card.Id); + AI.SelectCard(CardId.ExosisterSophia, CardId.ExosisterIrene, CardId.ExosisterMartha, CardId.ExosisterStella, CardId.ExosisterElis); + paxCallToField = false; + return true; + } + } + } + return false; + } + + public bool ExosisterArmentActivate() + { + if (Bot.LifePoints <= 800) + { + return false; + } + ClientCard activateTarget = null; + + if (Duel.Player == 0) + { + bool decided = false; + + // addition summon + if (Bot.GetMonsters().Count(card => CheckAbleForXyz(card)) == 1 && summoned && !CheckLessOperation()) + { + if ( (sakitamaEffect1Activated || !Bot.HasInHand(CardId.Sakitama)) + && (stellaEffect1Activated || !Bot.HasInMonstersZone(CardId.ExosisterStella)) + && (elisEffect1Activated || !Bot.HasInHand(CardId.ExosisterElis)) + ) + { + decided = true; + } + } + + if (Duel.LastChainPlayer == 1) + { + foreach (ClientCard target in Duel.LastChainTargets) + { + if (target.Controller == 0 && target.Location == CardLocation.MonsterZone && target.IsFaceup() && target.HasSetcode(SetcodeExosister)) + { + activateTarget = target; + decided = true; + break; + } + } + } + + if (!decided) + { + return false; + } + } + + if (activateTarget == null && Duel.LastChainPlayer == 1) + { + { + foreach (ClientCard target in Duel.LastChainTargets) + { + if (target.Controller == 0 && target.Location == CardLocation.MonsterZone && target.IsFaceup() && target.HasSetcode(SetcodeExosister)) + { + activateTarget = target; + break; + } + } + } + } + + if (activateTarget == null) + { + List targetList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasSetcode(SetcodeExosister) && !card.HasType(CardType.Xyz)).ToList(); + if (targetList.Count() > 0) + { + targetList.Sort(CardContainer.CompareCardAttack); + activateTarget = targetList[0]; + } + } + + if (activateTarget == null) + { + return false; + } + + // mikailis + if (!Bot.HasInMonstersZone(CardId.ExosisterMikailis) && !mikailisEffect1Activated && (Duel.Player == 1 || !mikailisEffect3Activated) + && !transformDestList.Contains(CardId.ExosisterMikailis) && Bot.HasInExtra(CardId.ExosisterMikailis)) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(activateTarget); + transformDestList.Add(CardId.ExosisterMikailis); + return true; + } + + // kaspitell on bot's turn + if (!Bot.HasInMonstersZone(CardId.ExosisterKaspitell) && !kaspitellEffect3Activated && Duel.Player == 0 + && !transformDestList.Contains(CardId.ExosisterKaspitell) && Bot.HasInExtra(CardId.ExosisterKaspitell)) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(activateTarget); + transformDestList.Add(CardId.ExosisterKaspitell); + return true; + } + + // gibrine + if (!Bot.HasInMonstersZone(CardId.ExosisterGibrine) && !gibrineEffect1Activated + && !transformDestList.Contains(CardId.ExosisterGibrine) && Bot.HasInExtra(CardId.ExosisterGibrine)) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(activateTarget); + transformDestList.Add(CardId.ExosisterGibrine); + return true; + } + + // asophiel + if (!Bot.HasInMonstersZone(CardId.ExosisterAsophiel) && !asophielEffect1Activated + && !transformDestList.Contains(CardId.ExosisterAsophiel) && Bot.HasInExtra(CardId.ExosisterAsophiel)) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(activateTarget); + transformDestList.Add(CardId.ExosisterAsophiel); + return true; + } + + // kaspitell on bot's turn + if (!Bot.HasInMonstersZone(CardId.ExosisterKaspitell) && !kaspitellEffect1Activated + && !transformDestList.Contains(CardId.ExosisterKaspitell) && Bot.HasInExtra(CardId.ExosisterKaspitell)) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(activateTarget); + transformDestList.Add(CardId.ExosisterKaspitell); + return true; + } + + return false; + } + + public bool ExosisterVadisActivate() + { + if (Bot.LifePoints <= 800) + { + return false; + } + + List checkListForSpSummon = new List{ + CardId.ExosisterSophia, CardId.ExosisterIrene, CardId.ExosisterStella, CardId.ExosisterMartha, CardId.ExosisterElis + }; + + bool decideToActivate = false; + bool checkTransform = false; + + // special summon for xyz + if (Duel.Player == 0 && Duel.Phase > DuelPhase.Draw && !CheckLessOperation()) + { + decideToActivate = true; + } + + // move grave + CheckEnemyMoveGrave(); + if (enemyMoveGrave) + { + decideToActivate = true; + checkTransform = true; + } + + // for returia + if (!oncePerTurnEffectActivatedList.Contains(CardId.ExosisterReturnia) && Bot.HasInSpellZone(CardId.ExosisterReturnia) && Bot.GetMonsters().Count() == 0) + { + decideToActivate = true; + } + + if (CheckInDanger() || (DefaultOnBecomeTarget() && !Util.ChainContainsCard(_CardId.EvenlyMatched))) + { + decideToActivate = true; + } + + if (decideToActivate) + { + foreach (int checkId in checkListForSpSummon) + { + int checkTarget = CheckExosisterMentionCard(checkId); + if (checkTarget > 0 && CheckRemainInDeck(checkId) > 0 && CheckRemainInDeck(checkTarget) > 0) + { + if (checkTransform) + { + int canTransformCount = 0; + foreach (int transformCheckId in new List{checkId, checkTarget}) + { + if (!Bot.HasInMonstersZone(checkId) && !exosisterTransformEffectList.Contains(checkId)) + { + canTransformCount ++; + } + } + + if (canTransformCount == 0) + { + continue; + } + } + oncePerTurnEffectActivatedList.Add(Card.Id); + Logger.DebugWriteLine("Exosiseter Vadis decide: " + checkId); + AI.SelectCard(checkId); + AI.SelectNextCard(checkTarget); + return true; + } + } + } + + return false; + } + + public bool ExosisterReturniaActivate() + { + if (Bot.LifePoints <= 800) + { + return false; + } + + // banish problem card + ClientCard target = GetProblematicEnemyCard(true); + if (target != null && Duel.LastChainPlayer != 0) + { + Logger.DebugWriteLine("===Exosister: returnia target 1: " + target?.Name); + removeChosenList.Add(target); + oncePerTurnEffectActivatedList.Add(Card.Id); + AI.SelectCard(target); + return true; + } + + // banish target + if (Duel.LastChainPlayer == 1) + { + List targetList = Duel.LastChainTargets.Where(card => card.Controller == 1 && + (card.Location == CardLocation.Grave || card.Location == CardLocation.MonsterZone || card.Location == CardLocation.SpellZone || card.Location == CardLocation.FieldZone)).ToList(); + if (targetList.Count() > 0) + { + oncePerTurnEffectActivatedList.Add(Card.Id); + List shuffleTargetList = ShuffleCardList(targetList); + Logger.DebugWriteLine("===Exosister: returnia target 2: " + shuffleTargetList[0]?.Name); + AI.SelectCard(shuffleTargetList); + return true; + } + } + + // dump banish + target = GetBestEnemyCard(false, true, true); + bool check1 = DefaultOnBecomeTarget() && target != null && (target.Location != CardLocation.Onfield || target.Id != _CardId.EvenlyMatched); + bool check2 = Bot.UnderAttack; + bool check3 = (Duel.Player == 1 && Duel.Phase == DuelPhase.End && Duel.LastChainPlayer != 0 && target != null && target.Location != CardLocation.Grave); + bool check4 = (Duel.Player == 1 && Enemy.GetMonsterCount() >= 2 && Duel.LastChainPlayer != 0); + Logger.DebugWriteLine("===Exosister: returnia check flag: " + check1 + " " + check2 + " " + check3 + " " + check4); + if (check1 || check2 || check3 || check4) + { + oncePerTurnEffectActivatedList.Add(Card.Id); + Logger.DebugWriteLine("===Exosister: returnia target 3: " + target?.Name); + AI.SelectCard(target); + return true; + } + + return false; + } + + /// + /// Check hand like exosister + elis + martha + /// + public bool ExosisterAvoidMaxxCSummonCheck() + { + if (!Bot.HasInHand(CardId.ExosisterMartha) || !Bot.HasInHand(CardId.ExosisterElis) || elisEffect1Activated || marthaEffect1Activated) + { + return false; + } + if (enemyActivateLockBird && CheckAtAdvantage()) + { + return false; + } + // normal summon non-elis exosister + if (Card.Id != CardId.ExosisterElis && Card.Id != CardId.ExosisterMartha) + { + summoned = true; + return true; + } + // normal summon elis + if (Card.IsCode(CardId.ExosisterElis)) + { + int otherExosisterCount = Bot.Hand.Count(card => card?.Data != null && !card.IsCode(CardId.ExosisterElis) && !card.IsCode(CardId.ExosisterMartha) + && card.IsMonster() && card.HasSetcode(SetcodeExosister)); + if (otherExosisterCount > 0) + { + return false; + } + if (Bot.Hand.Count(card => card?.Data != null && card.IsCode(CardId.ExosisterElis)) > 1) + { + summoned = true; + return true; + } + } + + return false; + } + + /// + /// Check hand like exosister + stella + /// + public bool ExosisterStellaSummonCheck() + { + if (stellaEffect1Activated || Bot.HasInMonstersZone(CardId.ExosisterStella, true) || CheckWhetherNegated(true) || CheckLessOperation()) + { + return false; + } + if (enemyActivateLockBird && CheckAtAdvantage()) + { + return false; + } + + int summonableCount = Bot.Hand.Count(card => card != Card && card?.Data != null && card.IsMonster() + && card.HasSetcode(SetcodeExosister)); + + if (summonableCount > 0) + { + summoned = true; + return true; + } + return false; + } + + /// + /// Check whether need Irene's redraw effect to search elis for xyz + /// + public bool ExosisterIreneSummonCheck() + { + if (irenaEffect1Activated || CheckLessOperation() + || CheckWhetherNegated(true) || CheckCalledbytheGrave(CardId.ExosisterElis) > 0 || CheckCalledbytheGrave(CardId.ExosisterIrene) > 0) + { + return false; + } + if (enemyActivateLockBird && CheckAtAdvantage()) + { + return false; + } + + if (CheckRemainInDeck(CardId.ExosisterElis) > 0) + { + summoned = true; + return true; + } + return false; + } + + /// + /// Check hand like exosister + elis + /// + public bool ExosisterForElisSummonCheck() + { + if (elisEffect1Activated || CheckCalledbytheGrave(CardId.ExosisterElis) > 0 || CheckLessOperation()) + { + return false; + } + if (Card?.Data == null) + { + return false; + } + if (!Card.HasSetcode(SetcodeExosister) || (Card.IsCode(CardId.ExosisterMartha) && CheckRemainInDeck(CardId.ExosisterElis) > 0)) + { + return false; + } + if (enemyActivateLockBird && CheckAtAdvantage()) + { + return false; + } + + if (Bot.Hand.Count(card => card != Card && card?.Data != null && card.IsCode(CardId.ExosisterElis)) > 0) + { + summoned = true; + return true; + } + + return false; + } + + public bool AratamaSummonCheck() + { + if (sakitamaEffect1Activated || CheckCalledbytheGrave(CardId.Aratama) > 0 || CheckCalledbytheGrave(CardId.Sakitama) > 0) + { + return false; + } + if (enemyActivateLockBird && CheckAtAdvantage()) + { + return false; + } + if (CheckRemainInDeck(CardId.Sakitama) > 0) + { + summoned = true; + return true; + } + return false; + } + + public bool ForSakitamaSummonCheck() + { + if (sakitamaEffect1Activated || CheckCalledbytheGrave(CardId.Sakitama) > 0 || CheckLessOperation()) + { + return false; + } + if (Bot.Hand.Count(card => card?.Data != null && Card != card && card.IsCode(CardId.Sakitama)) == 0) + { + return false; + } + if (enemyActivateLockBird && CheckAtAdvantage()) + { + return false; + } + if (Card?.Data != null && !Card.IsCode(CardId.ExosisterMartha) && Card.Level == 4) + { + summoned = true; + return true; + } + + return false; + } + + public bool Level4SummonCheck() + { + if (Card.Id == CardId.ExosisterMartha) + { + return false; + } + if (Bot.GetMonsters().Count(card => CheckAbleForXyz(card)) == 1) + { + summoned = true; + return true; + } + return false; + } + + public bool ForDonnerSummonCheck() + { + if (!Bot.HasInExtra(CardId.DonnerDaggerFurHire) || (!Bot.HasInHand(CardId.ExosisterMartha) && !Bot.HasInHandOrInSpellZone(CardId.ExosisterReturnia))) + { + return false; + } + if (CheckLessOperation()) + { + return false; + } + + List illegalList = Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Xyz) && card.Level != 4 + && (card.Data == null || !card.HasSetcode(SetcodeExosister))).ToList(); + if (illegalList.Count() == 0) + { + return false; + } + + if (illegalList.Count() == 1) + { + List otherMaterialList = Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Xyz)).ToList(); + otherMaterialList.Sort(CardContainer.CompareCardAttack); + illegalList.AddRange(otherMaterialList); + } + if (illegalList.Count() == 1) + { + List hands = Bot.Hand.Where(card => card?.Data != null && card.IsMonster()).ToList(); + if (hands.Count() > 0) + { + hands.Sort(CardContainer.CompareCardAttack); + if (Card != hands[0]) + { + return false; + } + } + Logger.DebugWriteLine("===Exosister: summon for donner"); + summoned = true; + return true; + } + + return false; + } + + public bool ExosisterForArmentSummonCheck() + { + if (!Bot.HasInHandOrInSpellZone(CardId.ExosisterArment)) + { + return false; + } + if (Card?.Data == null) + { + return false; + } + if (!Card.HasSetcode(SetcodeExosister)) + { + return false; + } + + if (!Bot.GetMonsters().Any(card => card?.Data != null && card.IsFaceup() && card.HasSetcode(SetcodeExosister))) + { + summoned = true; + return true; + } + + return false; + } + + public bool ExosisterMikailisSpSummonCheck() + { + return ExosisterMikailisSpSummonCheckInner(true); + } + + public bool ExosisterMikailisAdvancedSpSummonCheck() + { + if (!CheckLessOperation() || enemyActivateLockBird) + { + return false; + } + + return ExosisterMikailisSpSummonCheckInner(false); + } + + public bool ExosisterMikailisSpSummonCheckInner(bool shouldCheckLessOperation = true) + { + if (Bot.HasInMonstersZone(CardId.ExosisterMikailis) || mikailisEffect3Activated || (CheckLessOperation() && shouldCheckLessOperation)) + { + return false; + } + + // check searched spell/trap + if (!enemyActivateLockBird) + { + foreach (int cardId in ExosisterSpellTrapList) + { + if (!Bot.HasInHandOrInSpellZone(cardId)) + { + SelectXyzMaterial(2); + return true; + } + } + } + + // clear enemy card + if (!mikailisEffect1Activated && !Bot.HasInMonstersZone(CardId.ExosisterMikailis)) + { + ClientCard target = GetProblematicEnemyCard(true); + if (target != null) + { + List exosisterMaterialList = Bot.GetMonsters().Where(card => CheckAbleForXyz(card) && card.HasSetcode(SetcodeExosister)).ToList(); + if (exosisterMaterialList?.Count() > 0) + { + SelectXyzMaterial(2, true); + return true; + } + } + } + + return false; + } + + public bool ExosisterKaspitellSpSummonCheck() + { + return ExosisterKaspitellSpSummonCheckInner(true); + } + + public bool ExosisterKaspitellAdvancedSpSummonCheck() + { + if (!CheckLessOperation() || enemyActivateLockBird) + { + return false; + } + return ExosisterKaspitellSpSummonCheckInner(false); + } + + public bool ExosisterKaspitellSpSummonCheckInner(bool shouldCheckLessOperation = true) + { + if (Bot.HasInMonstersZone(CardId.ExosisterKaspitell) || kaspitellEffect3Activated || (shouldCheckLessOperation && CheckLessOperation())) + { + return false; + } + + bool searchMartha = true; + bool searchStella = true; + bool forMagnifica = false; + if (marthaEffect1Activated || CheckCalledbytheGrave(CardId.ExosisterMartha) > 0 + || CheckRemainInDeck(CardId.ExosisterMartha) == 0 || CheckRemainInDeck(CardId.ExosisterElis) == 0) + { + searchMartha = false; + } + if (Bot.GetMonsters().Any(card => card.HasType(CardType.Link) || card.HasType(CardType.Token))) + { + searchMartha = false; + } + if (stellaEffect1Activated || CheckCalledbytheGrave(CardId.ExosisterStella) > 0 || CheckRemainInDeck(CardId.ExosisterStella) == 0 + || !Bot.Hand.Any(card => card?.Data != null && card.IsMonster() && card.HasSetcode(SetcodeExosister))) + { + searchStella = false; + } + if (Bot.GetMonsters().Count(card => card?.Data != null + && card.HasType(CardType.Xyz) && card.HasType(CardType.Xyz) && !card.IsCode(CardId.ExosistersMagnifica)) == 1) + { + forMagnifica = true; + } + if (enemyActivateLockBird) + { + searchMartha = false; + searchStella = false; + } + + if (!searchMartha && !searchStella && !forMagnifica) + { + return false; + } + + List materialCheckList = Bot.GetMonsters().Where(card => + !card.HasType(CardType.Xyz) && !card.HasType(CardType.Token) && !card.HasType(CardType.Link)).ToList(); + if (materialCheckList.Count() == 2 && materialCheckList.All(card => card.Level == 4)) + { + SelectXyzMaterial(2); + return true; + } + + return false; + } + + public bool ExosistersMagnificaSpSummonCheck() + { + if (CheckLessOperation()) + { + return false; + } + + List materialList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasType(CardType.Xyz) + && card.Rank == 4 && card.HasSetcode(SetcodeExosister)).ToList(); + materialList.Sort(CardContainer.CompareCardAttack); + + AI.SelectMaterials(materialList); + return true; + } + + public bool CheckCaduceusInner(ClientCard card) + { + if (card?.Data == null) + { + return false; + } + foreach (int setcode in SetcodeForDiamond) + { + if (card.HasSetcode(setcode)) + { + return true; + } + } + return false; + } + + public bool TellarknightConstellarCaduceusSpSummonCheck() + { + if (Duel.Turn == 1 || !Bot.HasInExtra(CardId.StellarknightConstellarDiamond)) + { + return false; + } + + // check whether need to call Diamond + if (Enemy.Graveyard.Any(card => CheckCaduceusInner(card))) + { + SelectXyzMaterial(2); + return true; + } + + return false; + } + + public bool DonnerDaggerFurHireSpSummonCheck() + { + if (!Bot.HasInHand(CardId.ExosisterMartha) && !Bot.HasInHandOrInSpellZone(CardId.ExosisterReturnia)) + { + return false; + } + + if (CheckLessOperation()) + { + return false; + } + + List illegalList = Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Xyz) && card.Level != 4 + && (card.Data == null || !card.HasSetcode(SetcodeExosister))).ToList(); + + if (illegalList.Count() == 1) + { + + List otherMaterialList = Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Xyz)).ToList(); + otherMaterialList.Sort(CardContainer.CompareCardAttack); + illegalList.AddRange(otherMaterialList); + } + if (illegalList.Count() > 1) + { + AI.SelectMaterials(illegalList); + return true; + } + + return false; + } + + public bool SpellSetCheck() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + List onlyOneSetList = new List{ + CardId.ExosisterPax, CardId.ExosisterArment, CardId.ExosisterVadis, CardId.ExosisterReturnia + }; + if (onlyOneSetList.Contains(Card.Id) && Bot.HasInSpellZone(Card.Id)) + { + return false; + } + + // select place + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay))) + { + List avoid_list = new List(); + int setFornfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + setFornfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setFornfiniteImpermanence); + return true; + } else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } else + { + SelectSTPlace(); + } + return true; + } + + return false; + } + + protected override bool DefaultSetForDiabellze() + { + if (base.DefaultSetForDiabellze()) + { + SelectSTPlace(null, true); + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/FamiliarPossessedExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/FamiliarPossessedExecutor.cs new file mode 100644 index 0000000..525e994 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/FamiliarPossessedExecutor.cs @@ -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 avoid_list = null) + { + List list = new List { 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() { + 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 material_list = new List(); + 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 material_list = new List(); + 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 material_list = new List(); + 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 material_list = new List(); + 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 material_list = new List(); + 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 material_list = new List(); + 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 material_list = new List(); + 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 material_list = new List(); + 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 attackers, IList 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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/FrogExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/FrogExecutor.cs new file mode 100644 index 0000000..49667fa --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/FrogExecutor.cs @@ -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 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 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 cards = new List(); + + 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 monsters = Bot.GetGraveyardMonsters(); + return monsters.Count != 0; + } + + private bool GravityBind() + { + List 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 monsters = Bot.GetGraveyardMonsters(); + if (monsters.Count != 0) + { + foreach (ClientCard card in Bot.GetSpells()) + { + if (card.IsCode(CardId.Solidarity)) + atk += 800; + } + } + + return atk; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GravekeeperExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GravekeeperExecutor.cs new file mode 100644 index 0000000..084c676 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GravekeeperExecutor.cs @@ -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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GraydleExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GraydleExecutor.cs new file mode 100644 index 0000000..e82d27a --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GraydleExecutor.cs @@ -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...? + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GrenMajuThunderBoarderExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GrenMajuThunderBoarderExecutor.cs new file mode 100644 index 0000000..c3be275 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/GrenMajuThunderBoarderExecutor.cs @@ -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 targets = new List(); + 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 material_list = new List(); + 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 material_list = new List(); + 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 targets = new List(); + 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 material_list = new List(); + 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 attackers, IList 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; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/HorusExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/HorusExecutor.cs new file mode 100644 index 0000000..1a6644b --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/HorusExecutor.cs @@ -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 cards = new List(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 cards = new List(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(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 cards = new List(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(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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/KashtiraExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/KashtiraExecutor.cs new file mode 100644 index 0000000..32db521 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/KashtiraExecutor.cs @@ -0,0 +1,1378 @@ +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("Kashtira", "AI_Kashtira")] + class KashtiraExecutor : DefaultExecutor + { + public class CardId + { + public const int Nibiru = 27204311; + public const int KashtiraUnicorn = 68304193; + public const int KashtiraFenrir = 32909498; + public const int KashtiraTearlaments = 4928565; + public const int KashtiraScareclaw = 78534861; + public const int DimensionShifter = 91800273; + public const int NemesesCorridor = 72090076; + public const int KashtiraRiseheart = 31149212; + public const int G = 23434538; + public const int AshBlossom = 14558127; + public const int MechaPhantom = 31480215; + public const int Terraforming = 73628505; + public const int PotofProsperity = 84211599; + public const int KashtiraPapiyas = 34447918; + public const int CalledbytheGrave = 24224830; + public const int CrossoutDesignator = 65681983; + public const int KashtiraBirth = 69540484; + public const int PrimePlanetParaisos = 71832012; + public const int KashtiraBigBang = 33925864; + public const int InfiniteImpermanence = 10045474; + + public const int ThunderDragonColossus = 15291624; + public const int BorreloadSavageDragon = 27548199; + public const int CupidPitch = 21915012; + public const int KashtiraAriseHeart = 48626373; + public const int DiablosistheMindHacker = 95474755; + public const int KashtiraShangriIra = 73542331; + public const int GalaxyTomahawk = 10389142; + public const int BagooskatheTerriblyTiredTapir = 90590303; + public const int MekkKnightCrusadiaAvramax = 21887175; + public const int MechaPhantomBeastAuroradon = 44097050; + public const int QliphortGenius = 22423493; + public const int IP = 65741786; + + public const int Token = 10389143; + public const int Token_2 = 44097051; + } + bool isSummoned = false; + bool onlyXyzSummon = false; + bool activate_KashtiraUnicorn_1 = false; + bool activate_KashtiraFenrir_1 = false; + bool activate_KashtiraRiseheart_1 = false; + bool activate_KashtiraRiseheart_2 = false; + bool activate_PrimePlanetParaisos = false; + bool activate_KashtiraScareclaw_1 = false; + bool activate_KashtiraShangriIra = false; + bool activate_KashtiraTearlaments_1 = false; + bool activate_DimensionShifter = false; + bool activate_pre_PrimePlanetParaisos = false; + bool activate_pre_PrimePlanetParaisos_2 = false; + bool active_KashtiraPapiyas_1 = false; + bool active_KashtiraPapiyas_2 = false; + bool active_KashtiraBirth = false; + bool active_NemesesCorridor = false; + bool select_CalledbytheGrave = false; + bool summon_KashtiraUnicorn = false; + bool summon_KashtiraFenrir = false; + bool link_mode = false; + bool opt_0 = false; + bool opt_1 = false; + bool opt_2 = false; + + int flag = -1; + int pre_link_mode = -1; + List select_Cards = new List(); + List Impermanence_list = new List(); + List should_not_negate = new List + { + 81275020, 28985331 + }; + public KashtiraExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonColossus); + AddExecutor(ExecutorType.SpSummon, CardId.ThunderDragonColossus); + AddExecutor(ExecutorType.Activate, CardId.Nibiru, NibiruEffect); + AddExecutor(ExecutorType.Activate, CardId.InfiniteImpermanence, Impermanence_activate); + AddExecutor(ExecutorType.Activate, CardId.DimensionShifter, DimensionShifterEffect); + AddExecutor(ExecutorType.Activate, CardId.G, DefaultMaxxC); + AddExecutor(ExecutorType.Activate, CardId.AshBlossom, DefaultAshBlossomAndJoyousSpring); + AddExecutor(ExecutorType.Activate, CardId.CalledbytheGrave, CalledbytheGraveEffect); + AddExecutor(ExecutorType.Activate, CardId.BorreloadSavageDragon, BorreloadSavageDragonEffect); + AddExecutor(ExecutorType.Activate, CardId.CrossoutDesignator, CrossoutDesignatorEffect); + AddExecutor(ExecutorType.Activate, CardId.Terraforming, TerraformingEffect); + AddExecutor(ExecutorType.Activate, CardId.PotofProsperity, PotofProsperityEffect); + AddExecutor(ExecutorType.Activate, CardId.KashtiraUnicorn, KashtiraUnicornEffect); + AddExecutor(ExecutorType.Activate, CardId.KashtiraFenrir, KashtiraFenrirEffect); + AddExecutor(ExecutorType.Activate, CardId.PrimePlanetParaisos, PrimePlanetParaisosEffect); + AddExecutor(ExecutorType.Activate, CardId.KashtiraBirth, KashtiraBirthEffect); + AddExecutor(ExecutorType.Activate, CardId.DiablosistheMindHacker, DiablosistheMindHackerEffect); + AddExecutor(ExecutorType.SpSummon, CardId.KashtiraFenrir, KashtiraFenrirSummon); + AddExecutor(ExecutorType.SpSummon, CardId.KashtiraUnicorn,() => { summon_KashtiraUnicorn = true; return true; }); + AddExecutor(ExecutorType.SpSummon, CardId.KashtiraFenrir, () => { summon_KashtiraFenrir = true; return true; }); + AddExecutor(ExecutorType.Summon, CardId.KashtiraUnicorn, DefaultSummon); + AddExecutor(ExecutorType.Summon, CardId.KashtiraFenrir, DefaultSummon); + AddExecutor(ExecutorType.Activate, CardId.KashtiraPapiyas, KashtiraPapiyasEffect); + AddExecutor(ExecutorType.Activate, CardId.KashtiraTearlaments, KashtiraTearlamentsEffect); + AddExecutor(ExecutorType.Activate, CardId.KashtiraScareclaw, KashtiraScareclawEffect); + AddExecutor(ExecutorType.Activate, CardId.KashtiraBirth, KashtiraBirthEffect_2); + AddExecutor(ExecutorType.Activate, CardId.GalaxyTomahawk); + AddExecutor(ExecutorType.SpSummon, CardId.GalaxyTomahawk, GalaxyTomahawkSummon); + AddExecutor(ExecutorType.SpSummon, CardId.KashtiraShangriIra, KashtiraShangriIraSummon); + AddExecutor(ExecutorType.Activate, CardId.KashtiraShangriIra, KashtiraShangriIraEffect); + AddExecutor(ExecutorType.SpSummon, CardId.KashtiraAriseHeart, KashtiraAriseHeartSummon_2); + AddExecutor(ExecutorType.SpSummon, CardId.DiablosistheMindHacker, DiablosistheMindHackerSummon_2); + AddExecutor(ExecutorType.Activate, CardId.KashtiraAriseHeart, KashtiraAriseHeartEffect); + AddExecutor(ExecutorType.SpSummon, CardId.KashtiraAriseHeart, KashtiraAriseHeartSummon); + AddExecutor(ExecutorType.SpSummon, CardId.DiablosistheMindHacker, DiablosistheMindHackerSummon); + //link mode + AddExecutor(ExecutorType.SpSummon, CardId.QliphortGenius, QliphortGeniusSummon); + AddExecutor(ExecutorType.SpSummon, CardId.IP, IPSummon); + AddExecutor(ExecutorType.Activate, CardId.IP, IPEffect); + AddExecutor(ExecutorType.SpSummon, CardId.MechaPhantomBeastAuroradon, MechaPhantomBeastAuroradonSummon); + AddExecutor(ExecutorType.Activate, CardId.MechaPhantomBeastAuroradon, MechaPhantomBeastAuroradonEffect); + AddExecutor(ExecutorType.SpSummon, CardId.CupidPitch, CupidPitchSummon); + AddExecutor(ExecutorType.Activate, CardId.CupidPitch); + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadSavageDragon, BorreloadSavageDragonSummon); + AddExecutor(ExecutorType.Activate, CardId.NemesesCorridor, NemesesCorridorEffect); + AddExecutor(ExecutorType.SpSummon, CardId.MekkKnightCrusadiaAvramax, MekkKnightCrusadiaAvramaxSummon); + AddExecutor(ExecutorType.Activate, CardId.MekkKnightCrusadiaAvramax, MekkKnightCrusadiaAvramaxEffect); + //link mode + AddExecutor(ExecutorType.Activate, CardId.KashtiraRiseheart, KashtiraRiseheartEffect_2); + AddExecutor(ExecutorType.Activate, CardId.KashtiraRiseheart, KashtiraRiseheartEffect); + AddExecutor(ExecutorType.Activate, CardId.KashtiraBigBang, KashtiraBigBangEffect); + AddExecutor(ExecutorType.Activate, CardId.KashtiraPapiyas, KashtiraPapiyasEffect_2); + AddExecutor(ExecutorType.Activate, CardId.KashtiraBirth, KashtiraBirthEffect_3); + AddExecutor(ExecutorType.Summon, CardId.KashtiraRiseheart, KashtiraRiseheartSummon); + AddExecutor(ExecutorType.Summon, CardId.KashtiraTearlaments, DefaultSummon); + AddExecutor(ExecutorType.SpellSet, SpellSet); + AddExecutor(ExecutorType.Repos, DefaultRepos); + } + + public override bool OnSelectHand() + { + // go first + return true; + } + + public override void OnNewTurn() + { + if (pre_link_mode < 0) pre_link_mode = Program.Rand.Next(2); + isSummoned = false; + onlyXyzSummon = false; + activate_KashtiraUnicorn_1 = false; + activate_KashtiraFenrir_1 = false; + activate_KashtiraRiseheart_1 = false; + activate_KashtiraRiseheart_2 = false; + activate_PrimePlanetParaisos = false; + activate_KashtiraScareclaw_1 = false; + activate_KashtiraTearlaments_1 = false; + activate_KashtiraShangriIra = false; + activate_pre_PrimePlanetParaisos_2 = false; + active_KashtiraPapiyas_1 = false; + active_KashtiraPapiyas_2 = false; + active_KashtiraBirth = false; + active_NemesesCorridor = false; + link_mode = false; + summon_KashtiraUnicorn = false; + summon_KashtiraFenrir = false; + opt_0 = false; + opt_1 = false; + opt_2 = false; + if (flag >= 0) ++flag; + if (flag >= 2) { flag = -1; activate_DimensionShifter = false; } + base.OnNewTurn(); + } + public override bool OnSelectYesNo(int desc) + { + if (desc == 1149312192) + { + activate_pre_PrimePlanetParaisos = true; + } + return base.OnSelectYesNo(desc); + } + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + if (cardId == 27204312|| cardId==CardId.MechaPhantom) + { + return CardPosition.FaceUpDefence; + } + return base.OnSelectPosition(cardId, positions); + } + public override int OnSelectOption(IList options) + { + if (options.Count == 2 && options[1] == Util.GetStringId(CardId.KashtiraBirth, 0)) + return 1; + if (options.Count == 2 && options.Contains(Util.GetStringId(CardId.KashtiraTearlaments, 1))) + { + return (isEffectByRemove() || Enemy.Deck.Count <= 3) ? 1 : 0; + } + if (options.Contains(Util.GetStringId(CardId.MechaPhantomBeastAuroradon, 3))) + { + if (opt_1) return options.IndexOf(Util.GetStringId(CardId.MechaPhantomBeastAuroradon, 3)); + else if (opt_0) return 0; + return options[options.Count - 1]; + } + return base.OnSelectOption(options); + } + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (cardId == 0 && player == 1) + { + int zone = 0; + for (int i = 4; i >= 0; --i) + { + zone = (int)System.Math.Pow(2, i); + if ((available & zone) > 0) return zone; + } + } + if (cardId == CardId.GalaxyTomahawk) + { + if ((available & Zones.z5) > 0) return Zones.z5; + if ((available & Zones.z6) > 0) return Zones.z6; + } + return base.OnSelectPlace(cardId, player, location, available); + } + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (cards.Any(card => card != null && card.Location == CardLocation.Extra + && hint == HintMsg.Remove && min == 1 && max == 1)) + { + //Can't get card info in enemy extral. + int index = Program.Rand.Next(cards.Count()); + if (index < 0 || index >= cards.Count()) return null; + IList res = new List(); + res.Add(cards.ElementAtOrDefault(index)); + return Util.CheckSelectCount(res, cards, min, max); + } + if (cards.Any(card => card != null && card.Location == CardLocation.Grave && card.Controller == 1) + && hint == HintMsg.Remove && ((min == 1 && max == 1) || (min == 3 && max == 3))) + { + if (select_CalledbytheGrave) { select_CalledbytheGrave = false; return null; } + List copyCards = new List(cards); + List keyCardsId = new List() + { + 44097050,15291624,63288573,70369116,83152482,72329844, + 24094258,86066372,74997493,85289965,21887175,11738489, + 98127546,50588353,10389142,90590303,27548199, + }; + List preCards = new List(); + List resCards = new List(); + foreach (var card in copyCards) + { + if (card != null && (keyCardsId.Contains(card.Id) || (card.Alias != 0 && keyCardsId.Contains(card.Alias)))) + preCards.Add(card); + else resCards.Add(card); + } + if (preCards.Count > 0) return Util.CheckSelectCount(preCards, cards, min, max); + resCards = FilterdRepeatIdCards(resCards); + if (resCards != null) + { + resCards.Sort(CardContainer.CompareCardAttack); + resCards.Reverse(); + return Util.CheckSelectCount(resCards, cards, min, max); + } + copyCards.Sort(CardContainer.CompareCardAttack); + copyCards.Reverse(); + return Util.CheckSelectCount(copyCards, cards, min, max); + } + if (cards.Any(card => card != null && card.Location == CardLocation.Extra && card.Controller == 0) + && hint == HintMsg.Remove && min == 3 && max == 3) + { + //pre_link_mode == 0 xyz_mode + //pre_link_mode == 1 link_mode + List repeatIdCards = FilterdRepeatIdCards(cards); + if (repeatIdCards?.Count >= 3) + { + if (pre_link_mode == 1) return Util.CheckSelectCount(repeatIdCards, cards, min, max); + } + List resCards = new List(); + List cardsId = new List() + { + CardId.BagooskatheTerriblyTiredTapir,CardId.BorreloadSavageDragon,CardId.CupidPitch, + CardId.QliphortGenius,CardId.IP,CardId.MechaPhantomBeastAuroradon,CardId.MekkKnightCrusadiaAvramax, + CardId.ThunderDragonColossus + }; + List filterCards = CardsIdToClientCards(cardsId, cards).ToList(); + if (repeatIdCards?.Count > 0 && pre_link_mode == 0) resCards.AddRange(repeatIdCards); + if (filterCards?.Count > 0) resCards.AddRange(filterCards); + if (repeatIdCards?.Count > 0 && pre_link_mode == 1) resCards.AddRange(repeatIdCards); + if (resCards.Count > 0) + { + return Util.CheckSelectCount(resCards, cards, min, max); + } + return null; + } + if (hint == HintMsg.Remove && cards.Any(card => card != null && (card.Location == CardLocation.Hand || card.Location == CardLocation.Grave) && card.Controller == 0) && min == 1 && max == 1) + { + if (select_Cards.Count > 0) + { + return Util.CheckSelectCount(select_Cards, cards, min, max); + } + else + { + IList grave_cards = cards.GetMatchingCards(card => card != null && card.Location == CardLocation.Grave); + if (grave_cards.Count > 0) return Util.CheckSelectCount(grave_cards, cards, min, max); + return null; + } + + } + if (hint == HintMsg.XyzMaterial && cards.Any(card => card != null && card.Location == CardLocation.Removed) && min == 1 && max == 1) + { + List m_cards = new List(); + List e_cards_u = new List(); + List e_cards_d = new List(); + foreach (var card in cards) + { + if (card != null && card.Controller == 0) + m_cards.Add(card); + if (card != null && card.Controller == 1 && card.IsFaceup()) + e_cards_u.Add(card); + if (card != null && card.Controller == 1 && card.IsFacedown()) + e_cards_d.Add(card); + } + List res = new List(); + if (e_cards_u.Count >= 0) + { + e_cards_u.Sort(CardContainer.CompareCardAttack); + e_cards_u.Reverse(); + res.AddRange(e_cards_u); + } + IList cardsId = new List() { CardId.KashtiraBigBang, CardId.KashtiraPapiyas }; + IList m_pre_cards = CardsIdToClientCards(cardsId, m_cards, false); + if (m_pre_cards?.Count >= 0) res.AddRange(m_pre_cards); + else if (m_cards.Count >= 0) res.AddRange(m_cards); + if (e_cards_d.Count >= 0) res.AddRange(e_cards_d); + if (res.Count <= 0) return null; + return Util.CheckSelectCount(res, cards, min, max); + } + if (hint == HintMsg.Release && cards.Any(card => card != null && card.Location == CardLocation.MonsterZone)) + { + List tRelease = new List(); + List nRelease = new List(); + foreach (var card in cards) + { + if (card == null || (card.IsExtraCard() && card.Id != CardId.DiablosistheMindHacker) || card.IsFacedown()) continue; + if (card.Id == CardId.Token || card.Id == CardId.Token_2) + tRelease.Add(card); + else nRelease.Add(card); + } + if (opt_1) + { + IList cardsId = new List() { CardId.Token, CardId.Token_2 }; + tRelease = CardsIdToClientCards(cardsId, tRelease, false).ToList(); + if(tRelease?.Count > 0) nRelease.AddRange(tRelease); + if (nRelease.Count <= 0) return null; + return Util.CheckSelectCount(nRelease, cards, min, max); + } + else + { + tRelease.AddRange(nRelease); + if(tRelease.Count <= 0) return null; + return Util.CheckSelectCount(tRelease, cards, min, max); + } + } + if (hint == HintMsg.Destroy && cards.Any(card => card != null && card.Controller == 1 && (card.Location & CardLocation.Onfield) > 0) && min==1 && max==1) + { + ClientCard card = Util.GetBestEnemyCard(); + List res = new List(); + if (card != null && cards.Contains(card)) + { + res.Add(card); + return Util.CheckSelectCount(res, cards, min, max); + } + res = cards.Where(_card => _card != null && _card.Controller == 1).ToList(); + if (res.Count <= 0) return null; + res.Sort(CardContainer.CompareCardAttack); + res.Reverse(); + return Util.CheckSelectCount(res, cards, min, max); + } + if (activate_pre_PrimePlanetParaisos) + { + activate_pre_PrimePlanetParaisos = false; + IList cardsId = new List(); + if (!Bot.HasInHand(CardId.KashtiraUnicorn) && !activate_KashtiraUnicorn_1 && CheckRemainInDeck(CardId.KashtiraUnicorn) > 0) cardsId.Add(CardId.KashtiraUnicorn); + if (!Bot.HasInHand(CardId.KashtiraFenrir) && !activate_KashtiraFenrir_1 && CheckRemainInDeck(CardId.KashtiraFenrir) > 0) cardsId.Add(CardId.KashtiraFenrir); + if (!Bot.HasInHand(CardId.KashtiraScareclaw) && !activate_KashtiraScareclaw_1 && CheckRemainInDeck(CardId.KashtiraScareclaw) > 0) cardsId.Add(CardId.KashtiraScareclaw); + if (!Bot.HasInHand(CardId.KashtiraTearlaments) && !activate_KashtiraTearlaments_1 && CheckRemainInDeck(CardId.KashtiraTearlaments) > 0) cardsId.Add(CardId.KashtiraTearlaments); + if (!Bot.HasInHand(CardId.KashtiraRiseheart) && (!activate_KashtiraRiseheart_2 || !activate_KashtiraRiseheart_1) && CheckRemainInDeck(CardId.KashtiraRiseheart) > 0) cardsId.Add(CardId.KashtiraRiseheart); + IList copyCards = new List(cards); + IList res = CardsIdToClientCards(cardsId, copyCards); + if (res?.Count <= 0) return null; + return Util.CheckSelectCount(res, cards, min, max); + + } + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + private int CheckRemainInDeck(int id) + { + switch (id) + { + case CardId.Nibiru: + return Bot.GetRemainingCount(CardId.Nibiru, 1); + case CardId.KashtiraUnicorn: + return Bot.GetRemainingCount(CardId.KashtiraUnicorn, 3); + case CardId.KashtiraFenrir: + return Bot.GetRemainingCount(CardId.KashtiraFenrir, 3); + case CardId.KashtiraTearlaments: + return Bot.GetRemainingCount(CardId.KashtiraTearlaments, 1); + case CardId.KashtiraScareclaw: + return Bot.GetRemainingCount(CardId.KashtiraScareclaw, 2); + case CardId.DimensionShifter: + return Bot.GetRemainingCount(CardId.DimensionShifter, 2); + case CardId.NemesesCorridor: + return Bot.GetRemainingCount(CardId.NemesesCorridor, 1); + case CardId.KashtiraRiseheart: + return Bot.GetRemainingCount(CardId.KashtiraRiseheart, 3); + case CardId.G: + return Bot.GetRemainingCount(CardId.G, 2); + case CardId.AshBlossom: + return Bot.GetRemainingCount(CardId.AshBlossom, 3); + case CardId.MechaPhantom: + return Bot.GetRemainingCount(CardId.MechaPhantom, 1); + case CardId.Terraforming: + return Bot.GetRemainingCount(CardId.Terraforming, 1); + case CardId.PotofProsperity: + return Bot.GetRemainingCount(CardId.PotofProsperity, 2); + case CardId.KashtiraPapiyas: + return Bot.GetRemainingCount(CardId.KashtiraPapiyas, 3); + case CardId.CalledbytheGrave: + return Bot.GetRemainingCount(CardId.CalledbytheGrave, 2); + case CardId.CrossoutDesignator: + return Bot.GetRemainingCount(CardId.CrossoutDesignator, 1); + case CardId.KashtiraBirth: + return Bot.GetRemainingCount(CardId.KashtiraBirth, 3); + case CardId.PrimePlanetParaisos: + return Bot.GetRemainingCount(CardId.PrimePlanetParaisos, 3); + case CardId.KashtiraBigBang: + return Bot.GetRemainingCount(CardId.KashtiraBigBang, 1); + case CardId.InfiniteImpermanence: + return Bot.GetRemainingCount(CardId.InfiniteImpermanence, 2); + default: + return 0; + } + } + #region CopyImpermanence + public bool Impermanence_activate() + { + // negate before effect used + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (m.IsMonsterShouldBeDisabledBeforeItUseEffect() && !m.IsDisabled() && Duel.LastChainPlayer != 0) + { + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + AI.SelectCard(m); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || (Util.IsChainTarget(Card)) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + Impermanence_list.Add(this_seq); + return true; + } + } + } + } + if ((LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || LastChainCard.IsDisabled() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget())) + return false; + // negate monsters + if (is_should_not_negate() && LastChainCard.Location == CardLocation.MonsterZone) return false; + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + return true; + } + } + } + return true; + } + public int SelectSTPlace(ClientCard card = null, bool avoid_Impermanence = false) + { + List list = new List { 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 && Impermanence_list.Contains(seq)) continue; + return zone; + }; + } + return 0; + } + public bool is_should_not_negate() + { + ClientCard last_card = Util.GetLastChainCard(); + if (last_card != null + && last_card.Controller == 1 && last_card.IsCode(should_not_negate)) + return true; + return false; + } + #endregion + private List FilterdRepeatIdCards(IList cards) + { + IList temp = new List(); + List res = new List(); + foreach (var card in cards) + { + if (card == null) continue; + if (temp.Count(_card => _card != null && _card.Id == card.Id) > 0 && res.Count(_card=>_card != null && _card.Id == card.Id) <= 0) + res.Add(card); + else + temp.Add(card); + } + return res.Count < 0 ? null : res; + } + private IList CardsIdToClientCards(IList cardsId, IList cardsList, bool uniqueId = true, bool alias = true) + { + if (cardsList?.Count() <= 0 || cardsId?.Count() <= 0) return new List(); + List res = new List(); + foreach (var cardid in cardsId) + { + List cards = cardsList.Where(card => card != null && (card.Id == cardid || ((card.Alias != 0 && cardid == card.Alias) & alias))).ToList(); + if (cards?.Count <= 0) continue; + cards.Sort(CardContainer.CompareCardAttack); + if (uniqueId) res.Add(cards.First()); + else res.AddRange(cards); + } + return res; + } + private IList ClientCardsToCardsId(IList cardsList, bool uniqueId = false, bool alias = false) + { + if (cardsList == null) return null; + if (cardsList.Count <= 0) return new List(); + IList res = new List(); + foreach (var card in cardsList) + { + if (card == null) continue; + if (card.Alias != 0 && alias && !(res.Contains(card.Alias) & uniqueId)) res.Add(card.Alias); + else if (card.Id != 0 && !(res.Contains(card.Id) & uniqueId)) res.Add(card.Id); + } + return res.Count < 0 ? null : res; + } + private bool DefaultRepos() + { + if (Card.Id == CardId.KashtiraScareclaw || (Card.Id == CardId.KashtiraShangriIra && Card.Attack<2000)) return false; + return DefaultMonsterRepos(); + } + private bool CrossoutDesignatorCheck(ClientCard LastChainCard, int id) + { + if (LastChainCard.IsCode(id) && CheckRemainInDeck(id) > 0) + { + AI.SelectAnnounceID(id); + return true; + } + return false; + } + private bool CrossoutDesignatorEffect() + { + ClientCard LastChainCard = Util.GetLastChainCard(); + if (LastChainCard == null || Duel.LastChainPlayer != 1) return false; + if (CrossoutDesignatorCheck(LastChainCard, CardId.Nibiru) + || CrossoutDesignatorCheck(LastChainCard, CardId.AshBlossom) + || CrossoutDesignatorCheck(LastChainCard, CardId.G) + || CrossoutDesignatorCheck(LastChainCard, CardId.NemesesCorridor) + || CrossoutDesignatorCheck(LastChainCard, CardId.InfiniteImpermanence) + || CrossoutDesignatorCheck(LastChainCard, CardId.CalledbytheGrave) + || CrossoutDesignatorCheck(LastChainCard, CardId.Terraforming) + || CrossoutDesignatorCheck(LastChainCard, CardId.PotofProsperity) + || CrossoutDesignatorCheck(LastChainCard, CardId.KashtiraPapiyas) + || CrossoutDesignatorCheck(LastChainCard, CardId.KashtiraUnicorn) + || CrossoutDesignatorCheck(LastChainCard, CardId.KashtiraFenrir) + || CrossoutDesignatorCheck(LastChainCard, CardId.KashtiraBirth)) + { + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + return true; + } + return false; + } + private bool MekkKnightCrusadiaAvramaxEffect() + { + if (Card.Location == CardLocation.Grave) + { + List cards = Enemy.GetMonsters(); + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + cards.AddRange(Enemy.GetSpells()); + if (cards.Count <= 0) return false; + AI.SelectCard(cards); + return true; + } + else return true; + } + private bool SpellSet() + { + return Card.HasType(CardType.QuickPlay) || Card.HasType(CardType.Trap); + } + private bool NibiruEffect() + { + if (Bot.HasInMonstersZone(CardId.KashtiraAriseHeart, true, false, true) && Util.GetBestAttack(Bot) > Util.GetBestAttack(Enemy)) return false; + return Bot.GetMonsterCount() <= 0 || Bot.GetMonsterCount() < Enemy.GetMonsterCount(); + } + private bool CalledbytheGraveEffect() + { + ClientCard card = Util.GetLastChainCard(); + if (card == null) return false; + int id = card.Id; + List g_cards = Enemy.GetGraveyardMonsters().Where(g_card => g_card != null && g_card.Id == id).ToList(); + if (Duel.LastChainPlayer != 0 && card != null) + { + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + if (card.Location == CardLocation.Grave && card.HasType(CardType.Monster)) + { + AI.SelectCard(card); + } + else if (g_cards.Count() > 0 && card.HasType(CardType.Monster)) + { + AI.SelectCard(g_cards); + } + else return false; + select_CalledbytheGrave = true; + return true; + } + return false; + } + private bool CupidPitchSummon() + { + if (!Bot.HasInMonstersZone(CardId.Token_2) && !Bot.HasInMonstersZone(CardId.MechaPhantom)) return false; + IList cardsId = new List() { CardId.MechaPhantom, CardId.Token_2 }; + IList cards = CardsIdToClientCards(cardsId, Bot.GetMonsters(), false); + if (cards?.Count <= 0) return false; + AI.SelectMaterials(cards); + return true; + + } + private bool BorreloadSavageDragonSummon() + { + if (!Bot.HasInMonstersZone(CardId.Token_2) && !Bot.HasInMonstersZone(CardId.CupidPitch)) return false; + IList cardsId = new List() { CardId.CupidPitch, CardId.Token_2 }; + IList cards = CardsIdToClientCards(cardsId, Bot.GetMonsters(), false); + if (cards?.Count <= 0) return false; + AI.SelectMaterials(cards); + link_mode = false; + return true; + } + private bool BorreloadSavageDragonEffect() + { + if (ActivateDescription == -1) + { + AI.SelectCard(new[] { CardId.MekkKnightCrusadiaAvramax, CardId.MechaPhantomBeastAuroradon, CardId.IP, CardId.QliphortGenius}); + return true; + } + return true; + + } + private bool IPSummon() + { + if (!Bot.HasInMonstersZone(CardId.Token) && !Bot.HasInMonstersZone(CardId.Token_2)) return false; + if (!Bot.HasInExtra(CardId.MechaPhantomBeastAuroradon) || !(Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax) && (Bot.HasInExtra(CardId.QliphortGenius) || Bot.HasInMonstersZone(CardId.QliphortGenius, false, false, true)))) return false; + List cards = Bot.GetMonsters().Where(card => card != null && !card.HasType(CardType.Link) && card.IsFaceup() && card.HasType(CardType.Monster) && !card.HasType(CardType.Xyz)).ToList(); + if (cards?.Count < 2 && !link_mode) return false; + IList cardsId = new List { CardId.GalaxyTomahawk, CardId.Token }; + IList pre_cards = CardsIdToClientCards(cardsId, cards, false); + if (pre_cards?.Count >= 2) { AI.SelectMaterials(pre_cards); return true; } + cards.Sort(CardContainer.CompareCardAttack); + AI.SelectMaterials(cards); + return true; + } + private bool IPEffect() + { + if (!Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax) && !(Bot.HasInMonstersZone(CardId.QliphortGenius,false,false,true) || + Bot.HasInMonstersZone(CardId.MechaPhantomBeastAuroradon, false, false, true))) return false; + AI.SelectCard(CardId.MekkKnightCrusadiaAvramax); + IList cardsId = new List {CardId.MechaPhantomBeastAuroradon,CardId.IP,CardId.QliphortGenius}; + List m = new List(); + IList pre_m = CardsIdToClientCards(cardsId,Bot.GetMonsters()); + if (pre_m?.Count <= 0) return false; + int link_count = 0; + foreach (var card in pre_m) + { + m.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 4) break; + } + if (link_count < 4) return false; + AI.SelectMaterials(m); + return true; + + } + private bool MechaPhantomBeastAuroradonEffect() + { + if (ActivateDescription == -1) return true; + else + { + if (CheckRemainInDeck(CardId.MechaPhantom) <= 0 + && GetEnemyOnFields().Count <= 0 && Bot.Graveyard.Count(card => card != null && card.HasType(CardType.Trap))<=0) return false; + List tRelease = new List(); + List nRelease = new List(); + foreach (var card in Bot.GetMonsters()) + { + if (card == null || (card.IsExtraCard() && card.Id != CardId.DiablosistheMindHacker) || card.IsFacedown()) continue; + if (card.Id == CardId.Token || card.Id == CardId.Token_2) + tRelease.Add(card); + else nRelease.Add(card); + } + int count = tRelease.Count() + nRelease.Count(); + opt_0 = false; + opt_1 = false; + opt_2 = false; + if (count >= 3 && Bot.Graveyard.Count(card => card != null && card.HasType(CardType.Trap)) >0 ) opt_2 = true; + if (count >= 2 && CheckRemainInDeck(CardId.MechaPhantom) > 0) opt_1 = true; + if (count >= 1 && GetEnemyOnFields().Count > 0) opt_0 = true; + if (!opt_0 && !opt_1 && !opt_2) return false; + return true; + } + + } + private bool QliphortGeniusSummon() + { + List cards = Bot.GetMonsters().Where(card => card != null && card.Id==CardId.Token).ToList(); + if (cards.Count <= 2) return false; + AI.SelectMaterials(cards); + return true; + } + private bool MekkKnightCrusadiaAvramaxSummon() + { + IList cardsId = new List() {CardId.MechaPhantomBeastAuroradon,CardId.IP,CardId.QliphortGenius}; + List cards = CardsIdToClientCards(cardsId,Bot.GetMonsters()).ToList(); + if (cards.Count <= 0) return false; + List m = new List(); + int link_count = 0; + foreach (var card in cards) + { + m.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 4) break; + } + if (link_count < 4 || m.Count<2) return false; + AI.SelectMaterials(m); + return true; + } + private bool MechaPhantomBeastAuroradonSummon() + { + if (!Bot.HasInMonstersZone(CardId.QliphortGenius,false,false,true) && !Bot.HasInMonstersZone(CardId.Token, false, false, true)) return false; + List m = new List(); + List m1 = Bot.GetMonsters().Where(card => card != null && card.Id == CardId.QliphortGenius).ToList(); + List m2 = Bot.GetMonsters().Where(card => card != null && card.Id == CardId.Token).ToList(); + if (m1.Count > 0) m.AddRange(m1); + if (m2.Count > 0) m.AddRange(m2); + m1.Clear(); + int link_count = 0; + foreach (var card in m) + { + m1.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 3) break; + } + if (link_count < 3) return false; + AI.SelectMaterials(m1); + return true; + } + private bool KashtiraFenrirSummon() + { + if (Bot.HasInHandOrInSpellZone(CardId.KashtiraBirth) && Bot.HasInHandOrInSpellZone(CardId.KashtiraPapiyas)) { summon_KashtiraFenrir = true; return true; } + return false; + } + private bool DiablosistheMindHackerEffect() + { + AI.SelectCard(CardId.KashtiraFenrir, CardId.KashtiraUnicorn, CardId.KashtiraScareclaw, CardId.KashtiraTearlaments); + return true; + } + private bool KashtiraRiseheartSummon() + { + isSummoned = true; + return !activate_KashtiraRiseheart_2; + } + private bool DimensionShifterEffect() + { + if (activate_DimensionShifter) return false; + flag = -1; + ++flag; + activate_DimensionShifter = true; + return true; + } + private bool KashtiraBigBangEffect() + { + if (Card.Location == CardLocation.Removed) + { + AI.SelectCard(CardId.KashtiraShangriIra); + AI.SelectNextCard(CardId.KashtiraUnicorn,CardId.KashtiraFenrir,CardId.KashtiraTearlaments,CardId.KashtiraScareclaw); + return true; + } + else if(Card.Location==CardLocation.SpellZone) + { + if (Enemy.GetMonsterCount() <= 0) return false; + if (Bot.GetMonsterCount() <= 1) return true; + return Bot.GetMonsterCount()< Enemy.GetMonsterCount(); + } + return false; + } + private bool SpellActivate() + { + return Card.Location == CardLocation.Hand || (Card.IsFacedown() && (Card.Location == CardLocation.SpellZone || Card.Location == CardLocation.FieldZone)); + } + private bool PrimePlanetParaisosEffect() + { + if (SpellActivate()) { activate_pre_PrimePlanetParaisos_2 = true; return true; } + if (activate_pre_PrimePlanetParaisos_2 || activate_pre_PrimePlanetParaisos) return false; + List cards = GetEnemyOnFields().Where(card => card != null && !card.IsShouldNotBeTarget()).ToList(); + if (cards == null || cards.Count <= 0) return false; + return true; + } + private bool DiablosistheMindHackerSummon() + { + List cards = Bot.GetMonsters(); + cards.Sort(CardContainer.CompareCardAttack); + AI.SelectMaterials(cards); + return true; + } + private bool XyzCheck() + { + if (Bot.GetMonsters().Count(card => card != null && card.IsFaceup() && card.Level == 7) >= 4 && Bot.HasInExtra(CardId.KashtiraShangriIra)) return false; + if ((active_KashtiraPapiyas_1 || !Bot.HasInHandOrInSpellZone(CardId.KashtiraPapiyas)) + && (activate_KashtiraUnicorn_1 || !Bot.HasInHand(CardId.KashtiraUnicorn) || isSummoned || !Bot.HasInSpellZone(CardId.KashtiraBirth, true, true)) + && (activate_KashtiraFenrir_1 || !Bot.HasInHand(CardId.KashtiraFenrir) || isSummoned || !Bot.HasInSpellZone(CardId.KashtiraBirth, true, true)) + && (activate_KashtiraScareclaw_1 || !Bot.HasInHand(CardId.KashtiraScareclaw) || isSummoned || !Bot.HasInSpellZone(CardId.KashtiraBirth, true, true)) + && (activate_KashtiraTearlaments_1 || !Bot.HasInHand(CardId.KashtiraTearlaments) || isSummoned || !Bot.HasInSpellZone(CardId.KashtiraBirth, true, true)) + && (activate_KashtiraRiseheart_2 || !Bot.HasInHand(CardId.KashtiraRiseheart) || activate_KashtiraRiseheart_1 || isSummoned)) return true; + return false; + + } + private bool GalaxyTomahawkSummon() + { + if (CheckRemainInDeck(CardId.MechaPhantom) <= 0) return false; + if (Bot.GetMonsterCount() >= 4) return false; + if (onlyXyzSummon || activate_DimensionShifter || Bot.HasInMonstersZone(CardId.KashtiraAriseHeart,true,false,true)) return false; + if (!Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax) && !(Bot.HasInExtra(CardId.CupidPitch) || Bot.HasInExtra(CardId.BorreloadSavageDragon))) return false; + //if (!XyzCheck()) return false; + link_mode = true; + return DiablosistheMindHackerSummon(); + } + private bool DiablosistheMindHackerSummon_2() + { + if (Bot.HasInMonstersZone(CardId.DiablosistheMindHacker)) return false; + return DiablosistheMindHackerSummon(); + } + private bool isEffectByRemove() + { + return activate_DimensionShifter || Bot.HasInMonstersZone(CardId.KashtiraAriseHeart, true, false, true) || Enemy.HasInMonstersZone(CardId.KashtiraAriseHeart, true, false, true); + } + private bool NemesesCorridorEffect() + { + if (Card.Location == CardLocation.Hand) + { + if(Bot.GetMonsterCount()<=0) return true; + if (onlyXyzSummon || !Bot.HasInExtra(CardId.ThunderDragonColossus)) return false; + else return true; + } + return false; + } + private bool KashtiraTearlamentsEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (Duel.Player != 0) return false; + if (Duel.CurrentChain.Count > 0) return false; + if (!ActivateLimit(Card.Id)) return false; + activate_KashtiraTearlaments_1 = true; + return true; + } + if (Card.Location == CardLocation.MonsterZone) + { + if (isEffectByRemove() && Enemy.Deck.Count >= 3) return true; + if (!isEffectByRemove() && Bot.Deck.Count > 10) return true; + return false; + } + if (Card.Location == CardLocation.Grave) + { + if (isEffectByRemove()) return false; + return Bot.Deck.Count > 10; + } + return false; + } + private bool ActivateLimit(int cardId) + { + if (Bot.MonsterZone.Count() <= 0 + && ((Bot.HasInHand(CardId.KashtiraFenrir) && !activate_KashtiraFenrir_1) + || (Bot.HasInHand(CardId.KashtiraUnicorn) && !activate_KashtiraUnicorn_1))) return false; + if (Bot.HasInHand(CardId.PrimePlanetParaisos) && !activate_pre_PrimePlanetParaisos_2) return false; + List cards = new List(); + List hand_cards = Bot.Hand.GetMatchingCards(card=>card!=null && card.HasSetcode(0x189)).ToList(); + List grave_cards = Bot.Graveyard.GetMatchingCards(card => card != null && card.HasSetcode(0x189)).ToList(); + List cardsid = new List(); + if (grave_cards.Count <= 0) + { + if ((Bot.HasInSpellZone(CardId.KashtiraBirth, true, true) && hand_cards.Count(card=>card!=null && card.Id == CardId.KashtiraBirth)>0) + || hand_cards.Count(card => card != null && card.Id == CardId.KashtiraBirth) > 1) + cardsid.Add(CardId.KashtiraBirth); + if ((active_KashtiraPapiyas_1 && hand_cards.Count(card => card != null && card.Id == CardId.KashtiraPapiyas) > 0) + || hand_cards.Count(card => card != null && card.Id == CardId.KashtiraPapiyas) > 1) + cardsid.Add(CardId.KashtiraPapiyas); + if (((activate_KashtiraFenrir_1 || summon_KashtiraFenrir) && hand_cards.Count(card => card != null && card.Id == CardId.KashtiraFenrir) > 0) + || hand_cards.Count(card => card != null && card.Id == CardId.KashtiraFenrir) > 1) + cardsid.Add(CardId.KashtiraFenrir); + if (((activate_KashtiraUnicorn_1 || summon_KashtiraUnicorn) && hand_cards.Count(card => card != null && card.Id == CardId.KashtiraUnicorn) > 0) + || hand_cards.Count(card => card != null && card.Id == CardId.KashtiraUnicorn) > 1) + cardsid.Add(CardId.KashtiraUnicorn); + if ((cardId != CardId.KashtiraScareclaw && hand_cards.Count(card => card != null && card.Id == CardId.KashtiraScareclaw) > 0) + || (hand_cards.Count(card => card != null && card.Id == CardId.KashtiraScareclaw) > 1)) + cardsid.Add(CardId.KashtiraScareclaw); + if ((activate_KashtiraRiseheart_2 && hand_cards.Count(card => card != null && card.Id == CardId.KashtiraRiseheart) > 0) + || hand_cards.Count(card => card != null && card.Id == CardId.KashtiraRiseheart) > 1) + cardsid.Add(CardId.KashtiraRiseheart); + if (cardId != CardId.KashtiraTearlaments && hand_cards.Count(card => card != null && card.Id == CardId.KashtiraTearlaments) > 0) + cardsid.Add(CardId.KashtiraTearlaments); + if(hand_cards.Count(card => card != null && card.Id == CardId.KashtiraBigBang) > 0) + cardsid.Add(CardId.KashtiraBigBang); + if (cardsid.Count <= 0) return false; + } + if (Bot.HasInHand(CardId.KashtiraFenrir) && !activate_KashtiraFenrir_1 && Bot.GetMonsterCount() <= 0) return false; + if (Bot.HasInHand(CardId.KashtiraUnicorn) && !activate_KashtiraUnicorn_1 && Bot.GetMonsterCount() <= 0) return false; + select_Cards.Clear(); + select_Cards.AddRange(grave_cards); + select_Cards.AddRange(CardsIdToClientCards(cardsid, hand_cards,false)); + return true; + } + private bool KashtiraScareclawEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (Duel.Player != 0) return false; + if (Duel.CurrentChain.Count > 0) return false; + if (!ActivateLimit(Card.Id)) return false; + activate_KashtiraScareclaw_1 = true; + return true; + } + return false; + + } + private bool KashtiraAriseHeartEffect() + { + if (Card.IsDisabled()) return false; + if (ActivateDescription == Util.GetStringId(CardId.KashtiraAriseHeart, 1)) + { + return true; + } + else + { + return SelectEnemyCard(false,true); + } + } + private bool KashtiraAriseHeartSummon_2() + { + int xcount = 0; + int xcount_2 = 0; + int xcount_3 = 0; + foreach (var card in Bot.GetMonsters()) + { + if (card == null || card.IsFacedown()) continue; + if (card.Level == 7) ++xcount; + if (card.Level == 7 && card.HasSetcode(0x189))++xcount_2; + if (card.Level != 7 && card.HasSetcode(0x189) && !card.HasType(CardType.Xyz)) ++xcount_3; + } + if (xcount >= 2 && (xcount_3 > 0 || xcount - xcount_2 > 0)) return KashtiraAriseHeartSummon(); + return false; + } + private bool KashtiraAriseHeartSummon() + { + if (Bot.HasInMonstersZone(CardId.KashtiraShangriIra,false,false,true) && !activate_KashtiraShangriIra) return false; + if (activate_KashtiraShangriIra) + { + List materials = Bot.GetMonsters().GetMatchingCards(card => !card.IsExtraCard() && card.IsFaceup() && Card.HasSetcode(0x189)).ToList(); + if (materials.Count() <= 0) return false; + materials.Sort(CardContainer.CompareCardAttack); + materials.Sort(CardContainer.CompareCardLevel); + AI.SelectMaterials(materials); + return true; + } + else + { + return DiablosistheMindHackerSummon(); + } + } + private bool DefaultSummon() + { + if (Bot.HasInSpellZone(CardId.KashtiraBirth, true, true) && Bot.GetMonstersInMainZone().Count<5) + { + isSummoned = true; + if (Card.Id == CardId.KashtiraUnicorn) summon_KashtiraUnicorn = true; + else if(Card.Id == CardId.KashtiraFenrir) summon_KashtiraFenrir = true; + return true; + } + return false; + } + private bool KashtiraShangriIraSummon() + { + if (Bot.HasInMonstersZone(CardId.KashtiraShangriIra, true, false, true)) return false; + List materials = new List(); + foreach (var card in Bot.GetMonsters()) + { + if (materials.Count() >= 2) break; + if (card != null && card.IsFaceup() && card.Level == 7) + { + materials.Add(card); + } + } + if (materials.Count() < 2) return false; + materials.Sort(CardContainer.CompareCardAttack); + AI.SelectMaterials(materials); + return true; + } + private List GetEnemyOnFields() + { + List res = new List(); + List m_cards = Enemy.GetMonsters(); + List s_cards = Enemy.GetSpells(); + if (m_cards.Count > 0) res.AddRange(m_cards); + if(s_cards.Count > 0) res.AddRange(s_cards); + return res; + } + private bool KashtiraShangriIraEffect() + { + if (!Bot.HasInMonstersZone(CardId.KashtiraUnicorn, true, false, true) && Enemy.ExtraDeck.Count > 0 && CheckRemainInDeck(CardId.KashtiraUnicorn) > 0) + { + AI.SelectCard(CardId.KashtiraUnicorn); + } + else if (!Bot.HasInMonstersZone(CardId.KashtiraFenrir, true, false, true) && CheckRemainInDeck(CardId.KashtiraFenrir) > 0) + { + AI.SelectCard(CardId.KashtiraFenrir); + } + else if (!Bot.HasInMonstersZone(CardId.KashtiraScareclaw, true, false, true) && CheckRemainInDeck(CardId.KashtiraScareclaw) > 0) + { + AI.SelectCard(CardId.KashtiraScareclaw); + } + else + { + AI.SelectCard(CardId.KashtiraTearlaments, CardId.KashtiraUnicorn, CardId.KashtiraFenrir, CardId.KashtiraScareclaw); + } + activate_KashtiraShangriIra = true; + return true; + + } + private void DefaultAddCardId(List cardsid) + { + if (!Bot.HasInHand(CardId.KashtiraUnicorn) && !activate_KashtiraUnicorn_1) cardsid.Add(CardId.KashtiraUnicorn); + if (!Bot.HasInHand(CardId.KashtiraFenrir) && !activate_KashtiraFenrir_1) cardsid.Add(CardId.KashtiraFenrir); + if (!Bot.HasInHand(CardId.KashtiraRiseheart) && !activate_KashtiraRiseheart_2) cardsid.Add(CardId.KashtiraRiseheart); + if (!Bot.HasInHand(CardId.KashtiraTearlaments) && !activate_KashtiraTearlaments_1) cardsid.Add(CardId.KashtiraTearlaments); + if (!Bot.HasInHand(CardId.KashtiraScareclaw) && !activate_KashtiraScareclaw_1) cardsid.Add(CardId.KashtiraScareclaw); + } + private bool KashtiraPapiyasEffect_2() + { + if (Card.Location == CardLocation.Removed) + { + List cardsid = new List(); + DefaultAddCardId(cardsid); + if (!Bot.HasInExtra(CardId.KashtiraAriseHeart)) cardsid.Add(CardId.KashtiraAriseHeart); + if (!Bot.HasInExtra(CardId.KashtiraShangriIra)) cardsid.Add(CardId.KashtiraShangriIra); + cardsid.AddRange(new List() { CardId.KashtiraBigBang, CardId.KashtiraUnicorn, CardId.KashtiraFenrir, CardId.KashtiraRiseheart, CardId.KashtiraScareclaw, CardId.KashtiraTearlaments }); + AI.SelectCard(cardsid); + active_KashtiraPapiyas_2 = true; + return true; + } + else + { + AI.SelectCard(CardId.KashtiraFenrir); + List cardsid = new List(); + DefaultAddCardId(cardsid); + cardsid.AddRange(new List() { CardId.KashtiraUnicorn, CardId.KashtiraFenrir, CardId.KashtiraRiseheart, CardId.KashtiraScareclaw, CardId.KashtiraTearlaments }); + AI.SelectNextCard(cardsid); + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + active_KashtiraPapiyas_1 = true; + onlyXyzSummon = true; + return true; + } + } + private bool KashtiraPapiyasEffect() + { + if (link_mode) return false; + return KashtiraPapiyasEffect_2(); + } + private bool SelectEnemyCard(bool faceUp = true, bool isXyz= false) + { + ClientCard card = Util.GetLastChainCard(); + if (card != null && card.Controller == 1 && card.IsFaceup() && (card.HasType(CardType.Monster) + || card.HasType(CardType.Continuous) || card.HasType(CardType.Equip) || card.HasType(CardType.Field)) + && (card.Location & CardLocation.Onfield)>0 && !card.IsShouldNotBeTarget()) + { AI.SelectCard(card);if (isXyz)AI.SelectNextCard(card); return true; } + if (GetEnemyOnFields().Count(_card => _card != null && !_card.IsShouldNotBeTarget() && !(faceUp & !_card.IsFaceup()) && !_card.HasType(CardType.Token)) <= 0) return false; + ClientCard dcard = GetEnemyOnFields().GetDangerousMonster(true); + if (Duel.Phase >= DuelPhase.BattleStart || Util.GetBestAttack(Enemy) >= Util.GetBestAttack(Bot) || dcard != null) + { + if (dcard != null) { AI.SelectCard(dcard); if(isXyz)AI.SelectNextCard(dcard) ; return true; } + List cards = GetEnemyOnFields().Where(_card => _card != null && !_card.IsShouldNotBeTarget() && !(!_card.IsFaceup() & faceUp)).ToList(); + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + if (cards.Count <= 0) return false; + AI.SelectCard(cards); + if (isXyz) AI.SelectNextCard(cards); + return true; + } + return false; + } + private bool KashtiraFenrirEffect() + { + if (Card.IsDisabled()) return false; + if (ActivateDescription == Util.GetStringId(CardId.KashtiraFenrir, 1)) + { + IList cardsId = new List(); + if ((!Bot.HasInHandOrInSpellZone(CardId.KashtiraBirth) || isSummoned) + && !Bot.HasInHand(CardId.KashtiraRiseheart) && (!activate_KashtiraRiseheart_2 && (!activate_KashtiraRiseheart_1 || !isSummoned)) && CheckRemainInDeck(CardId.KashtiraRiseheart) > 0) + cardsId.Add(CardId.KashtiraRiseheart); + if (Bot.HasInHandOrInSpellZone(CardId.KashtiraBirth) && !isSummoned && !Bot.HasInHand(CardId.KashtiraUnicorn) && !activate_KashtiraUnicorn_1 && CheckRemainInDeck(CardId.KashtiraUnicorn) > 0) + cardsId.Add(CardId.KashtiraUnicorn); + if (!Bot.HasInHand(CardId.KashtiraTearlaments) && !activate_KashtiraTearlaments_1 && CheckRemainInDeck(CardId.KashtiraTearlaments) > 0) + cardsId.Add(CardId.KashtiraTearlaments); + if (!Bot.HasInHand(CardId.KashtiraScareclaw) && !activate_KashtiraScareclaw_1 && CheckRemainInDeck(CardId.KashtiraScareclaw) > 0) + cardsId.Add(CardId.KashtiraScareclaw); + cardsId.Add(CardId.KashtiraUnicorn); + cardsId.Add(CardId.KashtiraRiseheart); + activate_KashtiraFenrir_1 = true; + AI.SelectCard(cardsId); + return true; + } + else + { + if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard() != null && + Util.GetLastChainCard().Id == CardId.PrimePlanetParaisos) return false; + List cards = GetEnemyOnFields().Where(card => card != null && card.IsFaceup()).ToList(); + if (cards.Count > 0) + { + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + AI.SelectCard(cards); + } + return true; + } + } + + private bool TerraformingEffect() + { + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + return true; + } + + private bool PotofProsperityEffect() + { + if (Bot.ExtraDeck.Count <= 3) return false; + List cardsId = new List(); + if (!Bot.HasInHandOrInSpellZone(CardId.PrimePlanetParaisos) && !activate_PrimePlanetParaisos) + cardsId.Add(CardId.PrimePlanetParaisos); + if (!Bot.HasInHandOrInSpellZone(CardId.PrimePlanetParaisos) && !activate_PrimePlanetParaisos && CheckRemainInDeck(CardId.PrimePlanetParaisos) > 0) + cardsId.Add(CardId.Terraforming); + if (!Bot.HasInHand(CardId.KashtiraUnicorn) && !activate_KashtiraUnicorn_1) + cardsId.Add(CardId.KashtiraUnicorn); + if(!Bot.HasInHand(CardId.KashtiraFenrir) && !activate_KashtiraFenrir_1) + cardsId.Add(CardId.KashtiraFenrir); + if (!Bot.HasInHand(CardId.KashtiraPapiyas) && !active_KashtiraPapiyas_1) + cardsId.Add(CardId.KashtiraPapiyas); + if (!Bot.HasInHand(CardId.KashtiraRiseheart) && !activate_KashtiraRiseheart_2) + cardsId.Add(CardId.KashtiraRiseheart); + if(!Bot.HasInHandOrInSpellZone(CardId.KashtiraBirth)) + cardsId.Add(CardId.KashtiraBirth); + if(!Bot.HasInHand(CardId.KashtiraScareclaw) && !activate_KashtiraScareclaw_1) + cardsId.Add(CardId.KashtiraScareclaw); + if(!Bot.HasInHand(CardId.KashtiraTearlaments) && !activate_KashtiraTearlaments_1) + cardsId.Add(CardId.KashtiraTearlaments); + if (Bot.HasInExtra(CardId.ThunderDragonColossus) && Bot.Banished.Count(card=>card!=null && card.IsFaceup() && card.HasType(CardType.Monster))>0) + cardsId.Add(CardId.NemesesCorridor); + if (!Bot.HasInHand(CardId.G)) + cardsId.Add(CardId.G); + if (!Bot.HasInHand(CardId.AshBlossom)) + cardsId.Add(CardId.AshBlossom); + cardsId.AddRange(new List() { CardId.CrossoutDesignator, CardId.CalledbytheGrave, CardId.Nibiru, CardId.InfiniteImpermanence }); + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + AI.SelectCard(cardsId); + return true; + } + private bool KashtiraRiseheartEffect_2() + { + if (Card.Location != CardLocation.Hand) + { + if (CheckRemainInDeck(CardId.KashtiraBigBang) > 0 && Bot.GetMonsters().GetMatchingCards(card => card != null && card.HasType(CardType.Xyz) + && card.HasSetcode(0x189) && card.IsFaceup() && card.Overlays.Count > 0).Count > 0) + { + AI.SelectCard(CardId.KashtiraBigBang); + } + else if (Bot.HasInHandOrInSpellZone(CardId.KashtiraBirth) && !active_KashtiraBirth) + { + if (!Bot.HasInGraveyardOrInBanished(CardId.KashtiraUnicorn) && !activate_KashtiraUnicorn_1 + && CheckRemainInDeck(CardId.KashtiraUnicorn) > 0 && !active_KashtiraPapiyas_1 + && !Bot.HasInHand(CardId.KashtiraPapiyas) && CheckRemainInDeck(CardId.KashtiraPapiyas) > 0) + AI.SelectCard(CardId.KashtiraUnicorn); + else if (!Bot.HasInGraveyardOrInBanished(CardId.KashtiraFenrir) && !activate_KashtiraFenrir_1 + && CheckRemainInDeck(CardId.KashtiraFenrir) > 0) + AI.SelectCard(CardId.KashtiraFenrir); + else if (!Bot.HasInGraveyardOrInBanished(CardId.KashtiraUnicorn) && !activate_KashtiraUnicorn_1 + && CheckRemainInDeck(CardId.KashtiraUnicorn) > 0) + AI.SelectCard(CardId.KashtiraFenrir); + else if (Bot.Graveyard.Count(card => card != null && card.HasType(CardType.Monster) && card.HasSetcode(0x189) && !card.HasType(CardType.Xyz)) + + Bot.Banished.Count(card_2 => card_2 != null && card_2.HasType(CardType.Monster) && card_2.HasSetcode(0x189) && !card_2.HasType(CardType.Xyz)) <= 0) + AI.SelectCard(CardId.KashtiraFenrir, CardId.KashtiraUnicorn, CardId.KashtiraScareclaw, CardId.KashtiraTearlaments, CardId.KashtiraRiseheart); + else + AI.SelectCard(CardId.KashtiraFenrir, CardId.KashtiraUnicorn, CardId.KashtiraScareclaw, CardId.KashtiraTearlaments, CardId.KashtiraRiseheart); + } + else if (Bot.HasInHand(CardId.NemesesCorridor) && !active_NemesesCorridor && + Bot.Banished.Count(card_2 => card_2 != null && card_2.HasType(CardType.Monster)) <= 0 && Bot.HasInExtra(CardId.ThunderDragonColossus)) + { + AI.SelectCard(CardId.KashtiraFenrir, CardId.KashtiraUnicorn, CardId.KashtiraScareclaw, CardId.KashtiraTearlaments, CardId.KashtiraRiseheart); + } + else if (!active_KashtiraPapiyas_2 && CheckRemainInDeck(CardId.KashtiraPapiyas) > 0 && Bot.Banished.GetMatchingCardsCount(card => card != null && card.IsFaceup() && card.HasSetcode(0x189) && card.Id != CardId.KashtiraPapiyas) > 0) + { + AI.SelectCard(CardId.KashtiraPapiyas, CardId.KashtiraFenrir, CardId.KashtiraUnicorn, CardId.KashtiraScareclaw, CardId.KashtiraTearlaments, CardId.KashtiraRiseheart); + } + else + { + AI.SelectCard(CardId.KashtiraFenrir, CardId.KashtiraUnicorn, CardId.KashtiraScareclaw, CardId.KashtiraTearlaments, CardId.KashtiraRiseheart); + } + activate_KashtiraRiseheart_2 = true; + return true; + } + return false; + } + private bool KashtiraRiseheartEffect() + { + if (Card.Location == CardLocation.Hand) + { + activate_KashtiraRiseheart_1 = true; + onlyXyzSummon = true; + return true; + } + return false; + } + private bool KashtiraBirthEffect() + { + if ((Card.Location == CardLocation.Hand || (Card.Location==CardLocation.SpellZone && Card.IsFacedown())) + && !Bot.HasInSpellZone(CardId.KashtiraBirth, true, true)) + { + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + return true; + } + return false; + } + private bool KashtiraBirthEffect_2() + { + if (link_mode) return false; + return KashtiraBirthEffect_3(); + } + private bool KashtiraBirthEffect_3() + { + if (Card.Location == CardLocation.Hand || (Card.Location == CardLocation.SpellZone && Card.IsFacedown())) return false; + List cardsid = new List(); + if (!activate_KashtiraUnicorn_1 && !active_KashtiraPapiyas_1 && (Bot.HasInHand(CardId.KashtiraPapiyas) || CheckRemainInDeck(CardId.KashtiraPapiyas) > 0)) cardsid.Add(CardId.KashtiraPapiyas); + if (!activate_KashtiraFenrir_1) cardsid.Add(CardId.KashtiraFenrir); + if (!activate_KashtiraUnicorn_1) cardsid.Add(CardId.KashtiraUnicorn); + if (!activate_KashtiraRiseheart_2) cardsid.Add(CardId.KashtiraRiseheart); + cardsid.Add(CardId.KashtiraFenrir); + cardsid.Add(CardId.KashtiraUnicorn); + cardsid.Add(CardId.KashtiraTearlaments); + cardsid.Add(CardId.KashtiraScareclaw); + cardsid.Add(CardId.KashtiraRiseheart); + AI.SelectCard(cardsid); + return true; + } + private bool KashtiraUnicornEffect() + { + if (Card.IsDisabled()) return false; + if (ActivateDescription == Util.GetStringId(CardId.KashtiraUnicorn, 1)) + { + if ((!Bot.HasInHand(CardId.KashtiraPapiyas) && !active_KashtiraPapiyas_1) + ||(Bot.HasInHandOrInSpellZone(CardId.KashtiraBirth) && !Bot.HasInHand(CardId.KashtiraPapiyas))) + AI.SelectCard(CardId.KashtiraPapiyas, CardId.KashtiraBirth); + else + AI.SelectCard(CardId.KashtiraBirth, CardId.KashtiraPapiyas); + activate_KashtiraUnicorn_1 = true; + return true; + } + else + { + return true; + } + } + } + +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LabrynthExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LabrynthExecutor.cs new file mode 100644 index 0000000..436bca6 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LabrynthExecutor.cs @@ -0,0 +1,4356 @@ +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using System.Linq; +using System; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Labrynth", "AI_Labrynth")] + public class LabrynthExecutor : DefaultExecutor + { + public class CardId + { + public const int LadyLabrynthOfTheSilverCastle = 81497285; + public const int LovelyLabrynthOfTheSilverCastle = 2347656; + public const int UnchainedSoulOfSharvara = 41165831; + public const int AriasTheLabrynthButler = 73602965; + public const int ArianeTheLabrynthServant = 75730490; + public const int AriannaTheLabrynthServant = 1225009; + public const int LabrynthChandraglier = 37629703; + // _CardId.AshBlossom = 14558127; + // _CardId.MaxxC = 23434538; + public const int LabrynthStovieTorbie = 74018812; + public const int LabrynthCooclock = 2511; + + public const int PotOfExtravagance = 49238328; + + public const int WelcomeLabrynth = 5380979; + public const int TransactionRollback = 6351147; + // _CardId.InfiniteImpermanence = 10045474; + public const int DestructiveDarumaKarmaCannon = 30748475; + public const int EscapeOfTheUnchained = 53417695; + // _CardId.DimensionalBarrier = 83326048; + public const int BigWelcomeLabrynth = 92714517; + + public const int ChaosAngel = 22850702; + public const int SuperStarslayerTYPHON = 93039339; + public const int UnchainedAbomination = 29479265; + public const int UnchainedSoulOfAnguish = 93084621; + public const int UnchainedSoulLordOfYama = 24269961; + public const int UnchainedSoulOfRage = 67680512; + public const int SPLittleKnight = 29301450; + public const int MuckrakerFromTheUnderworld = 71607202; + public const int RelinquishedAnima = 94259633; + + public const int NaturalExterio = 99916754; + public const int NaturalBeast = 33198837; + public const int ImperialOrder = 61740673; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecree = 51452091; + public const int Number41BagooskatheTerriblyTiredTapir = 90590303; + public const int InspectorBoarder = 15397015; + public const int SkillDrain = 82732705; + + public const int DimensionShifter = 91800273; + public const int MacroCosmos = 30241314; + public const int DimensionalFissure = 81674782; + public const int BanisheroftheRadiance = 94853057; + public const int BanisheroftheLight = 61528025; + public const int KashtiraAriseHeart = 48626373; + public const int AccesscodeTalker = 86066372; + public const int GhostMournerMoonlitChill = 52038441; + } + + public LabrynthExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // startup effect/triggered chain + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + AddExecutor(ExecutorType.Activate, CardId.PotOfExtravagance, PotOfExtravaganceActivate); + AddExecutor(ExecutorType.Repos, CardId.LovelyLabrynthOfTheSilverCastle, ReposForLabrynth); + AddExecutor(ExecutorType.Activate, CardId.ChaosAngel, ChaosAngelActivate); + AddExecutor(ExecutorType.Activate, CardId.LovelyLabrynthOfTheSilverCastle, LovelyLabrynthOfTheSilverCastleActivate); + AddExecutor(ExecutorType.Activate, CardId.RelinquishedAnima, RelinquishedAnimaActivate); + AddExecutor(ExecutorType.Activate, CardId.AriannaTheLabrynthServant, AriannaTheLabrynthServantActivate); + AddExecutor(ExecutorType.Activate, CardId.ArianeTheLabrynthServant, ArianeTheLabrynthServantActivate); + AddExecutor(ExecutorType.Activate, CardId.LabrynthChandraglier, RecycleActivate); + AddExecutor(ExecutorType.Activate, CardId.LabrynthStovieTorbie, RecycleActivate); + AddExecutor(ExecutorType.Activate, CardId.LabrynthCooclock, RecycleActivate); + AddExecutor(ExecutorType.Activate, CardId.UnchainedSoulLordOfYama, UnchainedSoulLordOfYamaActivate); + AddExecutor(ExecutorType.Activate, CardId.WelcomeLabrynth, RecycleActivate); + AddExecutor(ExecutorType.Activate, CardId.SuperStarslayerTYPHON, SuperStarslayerTYPHONActivate); + AddExecutor(ExecutorType.Activate, CardId.UnchainedAbomination, UnchainedAbominationActivate); + + // repos + AddExecutor(ExecutorType.Repos, CardId.ArianeTheLabrynthServant, ReposForLabrynth); + AddExecutor(ExecutorType.Repos, CardId.AriannaTheLabrynthServant, ReposForLabrynth); + + // negate/chain + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossomActivate); + AddExecutor(ExecutorType.Activate, CardId.LadyLabrynthOfTheSilverCastle, LadyLabrynthOfTheSilverCastleFieldActivate); + AddExecutor(ExecutorType.Activate, CardId.AriasTheLabrynthButler, RecycleActivate); + AddExecutor(ExecutorType.Activate, CardId.SPLittleKnight, SPLittleKnightActivate); + AddExecutor(ExecutorType.Activate, _CardId.DimensionalBarrier, DimensionalBarrierActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + + AddExecutor(ExecutorType.Activate, CardId.MuckrakerFromTheUnderworld, MuckrakerFromTheUnderworldActivate); + AddExecutor(ExecutorType.Activate, CardId.UnchainedSoulOfRage, UnchainedSoulOfRageActivate); + AddExecutor(ExecutorType.Activate, CardId.TransactionRollback, TransactionRollbackActivate); + AddExecutor(ExecutorType.Activate, CardId.DestructiveDarumaKarmaCannon, DestructiveDarumaKarmaCannonActivate); + AddExecutor(ExecutorType.Activate, CardId.EscapeOfTheUnchained, EscapeOfTheUnchainedActivate); + + // sp summon + AddExecutor(ExecutorType.Activate, CardId.LadyLabrynthOfTheSilverCastle, LadyLabrynthOfTheSilverCastleHandActivate); + AddExecutor(ExecutorType.Activate, CardId.BigWelcomeLabrynth, BigWelcomeLabrynthBecomeTargetActivate); + AddExecutor(ExecutorType.Activate, CardId.WelcomeLabrynth, WelcomeLabrynthActivate); + AddExecutor(ExecutorType.Activate, CardId.BigWelcomeLabrynth, BigWelcomeLabrynthActivate); + + // clock + AddExecutor(ExecutorType.Activate, CardId.AriasTheLabrynthButler, AriasTheLabrynthButlerActivate); + AddExecutor(ExecutorType.Activate, CardId.LabrynthCooclock, LabrynthCooclockActivate); + AddExecutor(ExecutorType.Activate, CardId.BigWelcomeLabrynth, BigWelcomeLabrynthGraveActivate); + AddExecutor(ExecutorType.Activate, CardId.UnchainedSoulOfAnguish, UnchainedSoulOfAnguishActivate); + + // summon step + AddExecutor(ExecutorType.SpellSet, SpellSetForCooClockCheck); + AddExecutor(ExecutorType.Summon, CardId.ArianeTheLabrynthServant, ArianeTheLabrynthServantForRollbackSummon); + AddExecutor(ExecutorType.Summon, CardId.AriannaTheLabrynthServant, AriannaTheLabrynthServantSummon); + AddExecutor(ExecutorType.Summon, CardId.ArianeTheLabrynthServant, ArianeTheLabrynthServantSummon); + AddExecutor(ExecutorType.Summon, LabrynthForCooClockSummon); + AddExecutor(ExecutorType.Summon, ForLinkSummon); + AddExecutor(ExecutorType.Summon, ForSynchroSummon); + AddExecutor(ExecutorType.Summon, CardId.LabrynthCooclock, ForAnimaSummon); + + // furniture set + AddExecutor(ExecutorType.Activate, CardId.LabrynthChandraglier, FurnitureSetWelcomeActivate); + AddExecutor(ExecutorType.Activate, CardId.LabrynthStovieTorbie, FurnitureSetWelcomeActivate); + + // sp summon from extra + AddExecutor(ExecutorType.SpSummon, CardId.ChaosAngel, ChaosAngelSpSummonWith2Monster); + AddExecutor(ExecutorType.SpSummon, CardId.RelinquishedAnima, RelinquishedAnimaSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.UnchainedSoulLordOfYama, UnchainedSoulLordOfYamaSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.UnchainedSoulOfAnguish, UnchainedSoulOfAnguishSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.UnchainedSoulOfRage, UnchainedSoulOfRageSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.UnchainedAbomination, UnchainedAbominationSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SPLittleKnight, SPLittleKnightSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.ChaosAngel, ChaosAngelSpSummonWith3Monster); + AddExecutor(ExecutorType.SpSummon, CardId.MuckrakerFromTheUnderworld, MuckrakerFromTheUnderworldSpSummon); + + // hand eff + AddExecutor(ExecutorType.Activate, CardId.UnchainedSoulOfSharvara, UnchainedSoulOfSharvaraActivate); + + AddExecutor(ExecutorType.SpSummon, CardId.SuperStarslayerTYPHON, SuperStarslayerTYPHONSpSummon); + AddExecutor(ExecutorType.Repos, MonsterRepos); + AddExecutor(ExecutorType.Summon, SummonForTYPHONCheck); + AddExecutor(ExecutorType.SummonOrSet, ForBigWelcomeSummon); + AddExecutor(ExecutorType.SpellSet, SpellSetCheck); + } + + const int SetcodeTimeLord = 0x4a; + const int SetcodePhantom = 0xdb; + const int SetcodeOrcust = 0x11b; + const int SetcodeUnchained = 0x130; + const int SetcodeLabrynth = 0x17e; + const int SetcodeHorus = 0x19d; + const int hintTimingMainEnd = 0x4; + const int hintBattleStart = 0x8; + + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.AriannaTheLabrynthServant, CardId.LabrynthChandraglier, _CardId.AshBlossom, _CardId.MaxxC, + CardId.LabrynthStovieTorbie, CardId.LabrynthCooclock, _CardId.InfiniteImpermanence, CardId.BigWelcomeLabrynth }}, + {2, new List { CardId.LadyLabrynthOfTheSilverCastle, CardId.AriasTheLabrynthButler, CardId.PotOfExtravagance, CardId.WelcomeLabrynth, + CardId.TransactionRollback }}, + {1, new List { CardId.LovelyLabrynthOfTheSilverCastle, CardId.UnchainedSoulOfSharvara, CardId.ArianeTheLabrynthServant, + CardId.DestructiveDarumaKarmaCannon, CardId.EscapeOfTheUnchained, _CardId.DimensionalBarrier }} + }; + List notToNegateIdList = new List{ + 58699500, 20343502 + }; + List notToBeTrapTargetList = new List{ + 72144675, 86188410, 41589166, 11443677, 72566043, 1688285, 59071624, 6511113, 48183890, 952523, 22423493, 73639099 + }; + List targetNegateIdList = new List { + _CardId.EffectVeiler, _CardId.InfiniteImpermanence, CardId.GhostMournerMoonlitChill, _CardId.BreakthroughSkill, 74003290, 67037924, + 9753964, 66192538, 23204029, 73445448, 35103106, 30286474, 45002991, 5795980, 38511382, 53742162, 30430448 + }; + List notToDestroySpellTrap = new List { 50005218, 6767771 }; + + bool enemyActivateMaxxC = false; + List infiniteImpermanenceList = new List(); + bool summoned = false; + List activatedCardIdList = new List(); + List currentNegateMonsterList = new List(); + List currentDestroyCardList = new List(); + List setTrapThisTurn = new List(); + List summonThisTurn = new List(); + List enemySetThisTurn = new List(); + List escapeTargetList = new List(); + List summonInChainList = new List(); + bool cooclockAffected = false; + bool cooclockActivating = false; + bool furnitureActivating = false; + bool dimensionBarrierAnnouncing = false; + int banSpSummonExceptFiendCount = 0; + int dimensionShifterCount = 0; + int enemySpSummonFromExLastTurn = 0; + int enemySpSummonFromExThisTurn = 0; + bool enemyActivateInfiniteImpermanenceFromHand = false; + int rollbackCopyCardId = 0; + List dimensionalBarrierAnnouced = new List(); + List chainSummoningIdList = new List(3); + ClientCard bigwelcomeEscaseTarget = null; + + /// + /// Shuffle List and return a random-order card list + /// + public List ShuffleList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(result.Count); + int nextIndex = (index + Program.Rand.Next(result.Count - 1)) % result.Count; + T tempCard = result[index]; + result[index] = result[nextIndex]; + result[nextIndex] = tempCard; + } + return result; + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + List floodagateList = Enemy.GetMonsters().Where(c => c?.Data != null && + c.IsFloodgate() && c.IsFaceup() + && CheckCanBeTargeted(c, canBeTarget, selfType) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(c))).OrderByDescending(card => card.Attack).ToList(); + if (floodagateList.Count() > 0) return floodagateList[0]; + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(c))).OrderByDescending(card => card.Attack).ToList(); + if (dangerList.Count() > 0) return dangerList[0]; + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(c))).OrderByDescending(card => card.Attack).ToList(); + if (invincibleList.Count() > 0) return invincibleList[0]; + + List equippedList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.EquipCards.Count() > 0 && CheckCanBeTargeted(c, canBeTarget, selfType) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(c))).OrderByDescending(card => card.Attack).ToList(); + if (equippedList.Count() > 0) return equippedList[0]; + + List enemyMonsters = Enemy.GetMonsters().OrderByDescending(card => card.Attack).ToList(); + if (enemyMonsters.Count() > 0) + { + foreach (ClientCard target in enemyMonsters) + { + if ((target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2)) + && CheckCanBeTargeted(target, canBeTarget, selfType) && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(target)) + ) return target; + } + } + + if (attack >= 0) + { + if (attack == 0) + attack = Util.GetBestAttack(Bot); + List betterList = Enemy.MonsterZone.GetMonsters() + .Where(card => card.GetDefensePower() >= attack && card.GetDefensePower() > 0 && card.IsAttack() && CheckCanBeTargeted(card, canBeTarget, selfType) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).OrderByDescending(card => card.Attack).ToList(); + if (betterList.Count() > 0) return betterList[0]; + } + return null; + } + + public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreSpells = false, CardType selfType = 0) + { + List resultList = new List(); + + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (floodagateList.Count() > 0) resultList.AddRange(floodagateList); + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).ToList(); + if (problemEnemySpellList.Count() > 0) resultList.AddRange(ShuffleList(problemEnemySpellList)); + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (dangerList.Count() > 0 + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) resultList.AddRange(dangerList); + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (invincibleList.Count() > 0) resultList.AddRange(invincibleList); + + List enemyMonsters = Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c)).OrderByDescending(card => card.Attack).ToList(); + if (enemyMonsters.Count() > 0) + { + foreach(ClientCard target in enemyMonsters) + { + if ( (target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2)) + && !resultList.Contains(target) && CheckCanBeTargeted(target, canBeTarget, selfType) + ) + { + resultList.Add(target); + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() && !currentDestroyCardList.Contains(c) + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous) && CheckCanBeTargeted(c, canBeTarget, selfType) + && !notToDestroySpellTrap.Contains(c.Id)).ToList(); + if (spells.Count() > 0 && !ignoreSpells) resultList.AddRange(ShuffleList(spells)); + + return resultList; + } + + public ClientCard GetBestEnemyMonster(bool onlyFaceup = false, bool canBeTarget = false, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + ClientCard card = GetProblematicEnemyMonster(0, canBeTarget, ignoreCurrentDestroy, selfType); + if (card != null) + return card; + + card = Enemy.MonsterZone.Where(c => c?.Data != null && c.HasType(CardType.Monster) && c.IsFaceup() + && CheckCanBeTargeted(c, canBeTarget, selfType) && (!ignoreCurrentDestroy || currentDestroyCardList.Contains(c))) + .OrderByDescending(c => c.Attack).FirstOrDefault(); + if (card != null) + return card; + + List monsters = Enemy.GetMonsters().Where(c => !ignoreCurrentDestroy || currentDestroyCardList.Contains(c)).ToList(); + + // after GetHighestAttackMonster, the left monsters must be face-down. + if (monsters.Count() > 0 && !onlyFaceup) + return ShuffleList(monsters)[0]; + + return null; + } + + /// + /// check enemy's dangerous card in grave + /// + public List GetDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && (card.HasSetcode(SetcodeOrcust) || card.HasSetcode(SetcodePhantom) || card.HasSetcode(SetcodeHorus))).ToList(); + List dangerMonsterIdList = new List{ + 99937011, 63542003, 9411399, 28954097, 30680659 + }; + result.AddRange(Enemy.Graveyard.GetMatchingCards(card => dangerMonsterIdList.Contains(card.Id))); + return result; + } + + public int GetEmptyMainMonsterZoneCount() + { + int remainCount = 0; + for (int idx = 0; idx < 5; ++idx) + { + if (Bot.MonsterZone[idx] == null) remainCount++; + } + return remainCount; + } + + public List GetNormalEnemyTargetList(bool canBeTarget = true, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + List targetList = GetProblematicEnemyCardList(canBeTarget, selfType: selfType); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => + (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && enemySetThisTurn.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => + (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && !enemySetThisTurn.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetMonsters().Where(card => card.IsFacedown() && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList())); + + return targetList; + } + + public List GetMonsterListForTargetNegate(bool canBeTarget = false, CardType selfType = 0) + { + List resultList = new List(); + if (CheckWhetherNegated()) + { + return resultList; + } + + // negate before used + ClientCard target = Enemy.MonsterZone.FirstOrDefault(card => card?.Data != null + && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && !card.IsShouldNotBeTarget() + && CheckCanBeTargeted(card, canBeTarget, selfType) + && !currentNegateMonsterList.Contains(card)); + if (target != null) + { + resultList.Add(target); + } + + // negate monster effect on the field + foreach (ClientCard chainingCard in Duel.CurrentChain) + { + if (chainingCard.Location == CardLocation.MonsterZone && chainingCard.Controller == 1 && !chainingCard.IsDisabled() + && CheckCanBeTargeted(chainingCard, canBeTarget, selfType) && !currentNegateMonsterList.Contains(chainingCard)) + { + resultList.Add(chainingCard); + } + } + + return resultList; + } + + public int GetMaterialAttack(List materials) + { + if (Util.IsTurn1OrMain2()) return 0; + int result = 0; + foreach (ClientCard material in materials) + { + if (material.IsAttack() || !summonThisTurn.Contains(material)) result += material.Attack; + } + return result; + } + + public int GetBotCurrentTotalAttack(List exceptList = null) + { + if (Util.IsTurn1OrMain2()) return 0; + int result = 0; + foreach (ClientCard monster in Bot.GetMonsters()) + { + if (exceptList != null && exceptList.Contains(monster)) continue; + if (monster.IsAttack() || !summonThisTurn.Contains(monster)) result += monster.Attack; + } + return result; + } + + public List GetCanBeUsedForLinkMaterial(bool useAdvancedMonster = false, Func exceptRule = null) + { + List materialList = Bot.GetMonsters().Where(card => { + if (card.IsFacedown() || (exceptRule != null && exceptRule(card))) return false; + if (card.IsCode(CardId.MuckrakerFromTheUnderworld) && summonThisTurn.Contains(card)) return false; + if (card.IsCode(CardId.LovelyLabrynthOfTheSilverCastle) && !card.IsDisabled() && Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth)) return false; + if ((card.IsCode(CardId.ChaosAngel) || card.IsCode(CardId.LadyLabrynthOfTheSilverCastle)) + && !useAdvancedMonster && (card.IsAttack() || !summonThisTurn.Contains(card))) return false; + + return true; + }).ToList(); + materialList.Sort(CompareUsableAttack); + return materialList; + } + + public bool CheckCanDirectAttack() + { + return Enemy.GetMonsterCount() == 0 && !activatedCardIdList.Contains(CardId.SPLittleKnight) && Duel.Turn > 1 && Duel.Player == 0 && Duel.Phase < DuelPhase.Main2; + } + + /// + /// Check negated turn count of id + /// + public int CheckCalledbytheGrave(int id) + { + if (DefaultCheckWhetherCardIdIsNegated(id)) return 1; + return 0; + } + + public bool CheckCanBeTargeted(ClientCard card, bool canBeTarget, CardType selfType) + { + if (card == null) return true; + if (canBeTarget) + { + if (card.IsShouldNotBeTarget()) return false; + if (((int)selfType & (int)CardType.Monster) > 0 && card.IsShouldNotBeMonsterTarget()) return false; + if (((int)selfType & (int)CardType.Spell) > 0 && card.IsShouldNotBeSpellTrapTarget()) return false; + if (((int)selfType & (int)CardType.Trap) > 0 + && (card.IsShouldNotBeSpellTrapTarget() || (!card.IsDisabled() && notToBeTrapTargetList.Contains(card.Id)))) return false; + } + return true; + } + + /// + /// Check remain cards in deck + /// + /// Card's ID + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + public int CheckRemainInDeck(params int[] ids) + { + int sumResult = 0; + foreach (int id in ids) + { + sumResult += CheckRemainInDeck(id); + } + + return sumResult; + } + + /// + /// Whether spell or trap will be negate. If so, return true. + /// + /// is counter trap + /// check target + /// + public bool CheckSpellWillBeNegate(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() && (Enemy.HasInSpellZone(CardId.RoyalDecree, true) || Bot.HasInSpellZone(CardId.RoyalDecree, true))) return true; + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceList.Contains(selfSeq)) return true; + } + // how to get here? + return false; + } + + /// + /// Check whether'll be negated + /// + /// check whether card itself is disabled. + public bool CheckWhetherNegated(bool disablecheck = true, bool toFieldCheck = false, CardType type = 0) + { + if ((Card.IsSpell() || Card.IsTrap() || (((int)type & (int)CardType.Spell) == 0) || (((int)type & (int)CardType.Trap) == 0)) && CheckSpellWillBeNegate()) + return true; + if (CheckCalledbytheGrave(Card.Id) > 0) return true; + if ((Card.IsMonster() || (((int)type & (int)CardType.Monster) == 0)) && (toFieldCheck || Card.Location == CardLocation.MonsterZone)) + { + if ((toFieldCheck && (((int)type & (int)CardType.Link) == 0)) || Card.IsDefense()) + { + if (Enemy.MonsterZone.Any(card => CheckNumber41(card)) || Bot.MonsterZone.Any(card => CheckNumber41(card))) return true; + } + if (Enemy.HasInSpellZone(CardId.SkillDrain, true, true)) return true; + } + if (disablecheck) return Card.IsDisabled(); + return false; + } + + public bool CheckNumber41(ClientCard card) + { + return card != null && card.IsFaceup() && card.IsCode(CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled(); + } + + /// + /// Check whether cards will be removed. If so, do not send cards to grave. + /// + public bool CheckWhetherWillbeRemoved() + { + if (dimensionShifterCount > 0) return true; + List checkIdList = new List { CardId.BanisheroftheRadiance, CardId.BanisheroftheLight, CardId.MacroCosmos, CardId.DimensionalFissure, + CardId.KashtiraAriseHeart, 58481572 }; + foreach (int cardid in checkIdList) + { + List fields = new List { Bot, Enemy }; + foreach (ClientField cf in fields) + { + if (cf.HasInMonstersZone(cardid, true, false, true) || cf.HasInSpellZone(cardid, true, true)) + { + return true; + } + } + } + return false; + } + + /// + /// Check whether bot is at advantage. + /// + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && (Duel.Player == 0 || Bot.GetMonsterCount() > 0)) return true; + return false; + } + + public bool CheckShouldNoMoreSpSummon(bool isLabrynth = true) + { + if (CheckAtAdvantage() && enemyActivateMaxxC && (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2)) + { + if (!isLabrynth) return true; + if (cooclockAffected) + { + if (Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth))) return true; + if (Duel.Player == 0 && !summoned) return true; + if (setTrapThisTurn.Count() == 0) return true; + return false; + } + return true; + } + return false; + } + + /// + /// Check whether last chain card should be disabled. + /// + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + if (lastcard.IsMonster() && lastcard.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (notToNegateIdList.Contains(lastcard.Id)) return false; + + return true; + } + + public bool CheckChainContainEnemyMaxxC() + { + foreach (ClientCard card in Duel.CurrentChain) + { + if (card.Controller == 1 && card.IsCode(_CardId.MaxxC)) return true; + } + + return false; + } + + public bool CheckBigWelcomeCanSpSummon(int cardId) + { + return Bot.HasInHandOrInGraveyard(cardId) || CheckRemainInDeck(cardId) > 0; + } + + public int CompareUsableAttack(ClientCard cardA, ClientCard cardB) + { + if (cardA == null && cardB == null) + return 0; + if (cardA == null) + return -1; + if (cardB == null) + return 1; + int powerA = (cardA.IsDefense() && summonThisTurn.Contains(cardA)) ? 0 : cardA.Attack; + int powerB = (cardB.IsDefense() && summonThisTurn.Contains(cardB)) ? 0 : cardB.Attack; + if (powerA < powerB) + return -1; + if (powerA == powerB) + return CardContainer.CompareCardLevel(cardA, cardB); + return 1; + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + ClientCard currentSolvingChain = Duel.GetCurrentSolvingChainCard(); + if (currentSolvingChain != null) + { + if (currentSolvingChain.Controller == 1 && currentSolvingChain.IsCode(_CardId.EvenlyMatched)) + { + Logger.DebugWriteLine("=== Evenly Matched activated."); + List banishList = new List(); + List botMonsters = Bot.GetMonsters().Where(card => !card.HasType(CardType.Token)).ToList(); + + // monster + List faceDownMonsters = botMonsters.Where(card => card.IsFacedown()).ToList(); + banishList.AddRange(faceDownMonsters); + List notImportantMonster = botMonsters.Where(card => !banishList.Contains(card) + && ((card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && Bot.HasInExtra(card.Id)) + || CheckRemainInDeck(card.Id) > 0)).ToList(); + notImportantMonster.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(notImportantMonster); + + // spells + List faceUpSpells = Bot.GetSpells().Where(c => c.IsFaceup()).ToList(); + banishList.AddRange(ShuffleList(faceUpSpells)); + List faceDownSpells = Bot.GetSpells().Where(c => c.IsFacedown()).ToList(); + banishList.AddRange(ShuffleList(faceDownSpells)); + + List importantMonster = botMonsters.Where(card => !banishList.Contains(card) && !card.IsCode(CardId.LovelyLabrynthOfTheSilverCastle) + && ((card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && !Bot.HasInExtra(card.Id)) + || CheckRemainInDeck(card.Id) == 0)).ToList(); + importantMonster.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(importantMonster); + + // lovely + List lovelyList = botMonsters.Where(card => !banishList.Contains(card) && card.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)).ToList(); + lovelyList.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(lovelyList); + + return Util.CheckSelectCount(banishList, cards, min, max); + } + + if (currentSolvingChain.IsCode(CardId.LadyLabrynthOfTheSilverCastle) && min == 1 && max == 1 && hint == HintMsg.Set) + { + SortedDictionary> trapCheckDict = new SortedDictionary>{ + {_CardId.DimensionalBarrier, DimensionalBarrierActivate}, + {CardId.DestructiveDarumaKarmaCannon, DestructiveDarumaKarmaCannonSetCheck}, + {_CardId.InfiniteImpermanence, InfiniteImpermanenceSetCheck} + }; + foreach (KeyValuePair> pair in trapCheckDict) + { + ClientCard target = cards.FirstOrDefault(card => card.IsCode(pair.Key)); + if (target != null && pair.Value()) + { + SelectSTPlace(null, true); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + + ClientCard rollback = cards.FirstOrDefault(card => card.IsCode(CardId.TransactionRollback)); + if (rollback != null) + { + bool haveUnchainSoul = false; + if (!activatedCardIdList.Contains(CardId.UnchainedSoulOfSharvara)) + { + haveUnchainSoul |= Bot.HasInHand(CardId.UnchainedSoulOfSharvara); + haveUnchainSoul |= Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2 + && Bot.HasInExtra(CardId.UnchainedSoulLordOfYama) && !activatedCardIdList.Contains(CardId.UnchainedSoulLordOfYama) + && (CheckRemainInDeck(CardId.UnchainedSoulOfSharvara) > 0 || Bot.HasInGraveyard(CardId.UnchainedSoulOfSharvara)) + && Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasRace(CardRace.Fiend) && card.Level <= 4).Count() >= 2; + } + bool haveAriane = false; + if (!activatedCardIdList.Contains(CardId.ArianeTheLabrynthServant) && Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2) + { + haveAriane |= Bot.HasInMonstersZone(CardId.ArianeTheLabrynthServant); + haveAriane |= Bot.HasInHand(CardId.ArianeTheLabrynthServant) && !summoned; + haveAriane |= Bot.GetSpells().Any(card => card.IsFacedown() && + ( + (card.IsCode(CardId.WelcomeLabrynth) && !activatedCardIdList.Contains(CardId.WelcomeLabrynth) && (cooclockAffected || !setTrapThisTurn.Contains(card))) + || + (card.IsCode(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) && (cooclockAffected || !setTrapThisTurn.Contains(card))) + ) + ); + } + + if (haveUnchainSoul || haveAriane) + { + return Util.CheckSelectCount(new List { rollback }, cards, min, max); + } + } + + // welcome check + SortedDictionary welcomeCheck = new SortedDictionary { + {CardId.BigWelcomeLabrynth, cards.FirstOrDefault(card => card.IsCode(CardId.BigWelcomeLabrynth))}, + {CardId.WelcomeLabrynth, cards.FirstOrDefault(card => card.IsCode(CardId.WelcomeLabrynth))} + }; + List welcomeCheckIdList = new List { CardId.BigWelcomeLabrynth, CardId.WelcomeLabrynth }; + foreach (KeyValuePair checkPair in welcomeCheck) + { + if (checkPair.Value != null && !Bot.HasInHand(checkPair.Key) && !Bot.HasInGraveyard(checkPair.Key) + && !Bot.GetSpells().Any(card => card.IsCode(checkPair.Key) && card.IsFacedown())) + { + SelectSTPlace(null, true); + return Util.CheckSelectCount(new List { checkPair.Value }, cards, min, max); + } + } + if (welcomeCheck[CardId.BigWelcomeLabrynth] != null && + !Bot.HasInHand(CardId.BigWelcomeLabrynth) && !Bot.GetSpells().Any(card => card.IsCode(CardId.BigWelcomeLabrynth) && card.IsFacedown())) + { + SelectSTPlace(null, true); + return Util.CheckSelectCount(new List { welcomeCheck[CardId.BigWelcomeLabrynth] }, cards, min, max); + } + + // normal set + List checkIdList = new List{_CardId.InfiniteImpermanence, _CardId.DimensionalBarrier, CardId.DestructiveDarumaKarmaCannon, + CardId.BigWelcomeLabrynth, CardId.TransactionRollback, CardId.WelcomeLabrynth}; + foreach (int checkId in checkIdList) + { + ClientCard checkCard = cards.FirstOrDefault(card => card.IsCode(checkId)); + if (checkCard != null) + { + SelectSTPlace(null, true); + return Util.CheckSelectCount(new List { checkCard }, cards, min, max); + } + } + } + + if (currentSolvingChain.IsCode(CardId.WelcomeLabrynth)) + { + banSpSummonExceptFiendCount = 2; + } + + if (currentSolvingChain.IsCode(CardId.WelcomeLabrynth) || (currentSolvingChain.IsCode(CardId.TransactionRollback) && rollbackCopyCardId == CardId.WelcomeLabrynth)) + { + Logger.DebugWriteLine("rewrite welcome's select."); + List selection = new List(); + + ClientCard ariane = GetWelcomeOrBigWelcomeTarget(cards, CardId.ArianeTheLabrynthServant); + if (ariane != null && !summonInChainList.Any(card => card.IsCode(CardId.ArianeTheLabrynthServant))) + { + if ((Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2 || Duel.Player == 1 && Duel.Phase >= DuelPhase.Main2) + && Bot.HasInHandOrInSpellZone(CardId.TransactionRollback)) + { + selection.Add(ariane); + } + } + + ClientCard arianna = GetWelcomeOrBigWelcomeTarget(cards, CardId.AriannaTheLabrynthServant); + if (arianna != null && !summonInChainList.Any(card => card.IsCode(CardId.AriannaTheLabrynthServant))) + { + bool canActivateCheck = !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && !CheckWhetherNegated(true, true, CardType.Monster); + if (canActivateCheck) + { + bool checkFlag = !(!activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) && + (Bot.HasInGraveyard(CardId.BigWelcomeLabrynth) || Bot.GetSpells().Any(card => card.IsFacedown() && card.IsCode(CardId.BigWelcomeLabrynth)))); + checkFlag |= !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) + && (CheckBigWelcomeCanSpSummon(CardId.LovelyLabrynthOfTheSilverCastle) || Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true)) + && Bot.GetSpells().Any(card => card.IsFacedown() && card.IsCode(CardId.BigWelcomeLabrynth) + && (!setTrapThisTurn.Contains(card) || cooclockAffected)); + checkFlag |= !(Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) + || CheckBigWelcomeCanSpSummon(CardId.LovelyLabrynthOfTheSilverCastle)); + if (checkFlag) + { + selection.Add(arianna); + } + } + } + + ClientCard arias = GetWelcomeOrBigWelcomeTarget(cards, CardId.AriasTheLabrynthButler); + if (arias != null && !summonInChainList.Any(card => card.IsCode(CardId.AriasTheLabrynthButler)) && !Bot.HasInHandOrHasInMonstersZone(CardId.AriasTheLabrynthButler)) + { + bool canActivateCheck = !activatedCardIdList.Contains(CardId.AriasTheLabrynthButler) && !CheckWhetherNegated(true, true, CardType.Monster); + if (canActivateCheck && Bot.HasInHand(CardId.LovelyLabrynthOfTheSilverCastle)) + { + selection.Add(arias); + } + } + + ClientCard lovely = GetWelcomeOrBigWelcomeTarget(cards, CardId.LovelyLabrynthOfTheSilverCastle); + if (lovely != null && !summonInChainList.Any(card => card.IsCode(CardId.LovelyLabrynthOfTheSilverCastle))) + { + if (Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth)) + { + selection.Add(lovely); + } + } + + ClientCard lady = GetWelcomeOrBigWelcomeTarget(cards, CardId.LadyLabrynthOfTheSilverCastle); + if (lady != null) + { + if (Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) + && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasRace(CardRace.Fiend) && card.Level >= 8 && !card.HasType(CardType.Xyz | CardType.Link))) + { + selection.Add(lady); + } + } + + bool attackFlag = CheckCanDirectAttack(); + bool defenseFlag = Bot.UnderAttack && Bot.GetMonsterCount() == 0; + if (attackFlag || defenseFlag) + { + ClientCard bestPowerMonster = null; + int bestPower = -1; + foreach (ClientCard target in cards) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(target.Id); + if (cardData != null) + { + int power = attackFlag ? cardData.Attack : Math.Max(cardData.Attack, cardData.Defense); + if (bestPowerMonster == null || power > bestPower) + { + bestPowerMonster = target; + bestPower = power; + } + } + } + if (defenseFlag || GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack() + bestPower >= Enemy.LifePoints) + { + ClientCard realTarget = GetWelcomeOrBigWelcomeTarget(cards, bestPowerMonster.Id); + if (realTarget != null) selection.Add(realTarget); + } + } + + List checkIdList = new List{CardId.LabrynthStovieTorbie, CardId.LabrynthChandraglier, CardId.LabrynthCooclock, CardId.AriasTheLabrynthButler}; + foreach (int checkId in checkIdList) + { + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(checkId)) + { + ClientCard target = GetWelcomeOrBigWelcomeTarget(cards, checkId); + if (target != null) selection.Add(target); + } + } + + List fullCheckIdList = new List{ + CardId.LadyLabrynthOfTheSilverCastle, CardId.LabrynthStovieTorbie, CardId.LabrynthChandraglier, CardId.LabrynthCooclock, + CardId.AriasTheLabrynthButler, CardId.ArianeTheLabrynthServant, CardId.AriannaTheLabrynthServant + }; + foreach (int checkId in fullCheckIdList) + { + ClientCard target = GetWelcomeOrBigWelcomeTarget(cards, checkId); + if (target != null && !selection.Contains(target)) selection.Add(target); + } + + if (selection.Count() > 0) return Util.CheckSelectCount(selection, cards, min, max); + } + + bool searchFlag = currentSolvingChain.IsCode(CardId.AriannaTheLabrynthServant) && hint == HintMsg.AddToHand; + bool bigwelcomeSoving = currentSolvingChain.IsCode(CardId.BigWelcomeLabrynth) || (currentSolvingChain.IsCode(CardId.TransactionRollback) && rollbackCopyCardId == CardId.BigWelcomeLabrynth); + searchFlag |= bigwelcomeSoving && hint == HintMsg.SpSummon && Bot.GetMonsterCount() == 0; + if (searchFlag) + { + Logger.DebugWriteLine("rewrite search."); + List selection = new List(); + + List furnitureCheckIdList = new List { CardId.LabrynthStovieTorbie, CardId.LabrynthCooclock, CardId.LabrynthChandraglier }; + ClientCard bigWelcome = GetWelcomeOrBigWelcomeTarget(cards, CardId.BigWelcomeLabrynth); + ClientCard welcome = GetWelcomeOrBigWelcomeTarget(cards, CardId.WelcomeLabrynth); + ClientCard arianna = GetWelcomeOrBigWelcomeTarget(cards, CardId.AriannaTheLabrynthServant); + + // search big welcome to activate this turn + if (Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2) + { + if (!summoned && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && !CheckWhetherNegated(true, true, CardType.Monster) + && CheckCalledbytheGrave(CardId.AriannaTheLabrynthServant) == 0 && arianna != null && !Bot.HasInHand(CardId.AriannaTheLabrynthServant)) + { + return Util.CheckSelectCount(new List { arianna }, cards, min, max); + } + if (!CheckShouldNoMoreSpSummon()) + { + if (bigWelcome != null && !activatedCardIdList.Contains(CardId.AriasTheLabrynthButler) + && Bot.HasInHandOrHasInMonstersZone(CardId.AriasTheLabrynthButler)) + { + return Util.CheckSelectCount(new List { bigWelcome }, cards, min, max); + } + + bool canActivateSetTrap = (cooclockAffected || Bot.HasInHand(CardId.LabrynthCooclock)) + && Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth)); + if (canActivateSetTrap && !Bot.HasInHandOrInSpellZone(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth)) + { + return Util.CheckSelectCount(new List { AriannaSearchWelcomeTrap(cards, CardId.BigWelcomeLabrynth) }, cards, min, max); + } + } + } + + // search cooclock/bulter to activate trap + ClientCard arias = null; + ClientCard cooclock = null; + if (!activatedCardIdList.Contains(CardId.AriasTheLabrynthButler) && CheckRemainInDeck(CardId.AriasTheLabrynthButler) > 0 + && !Bot.HasInHand(CardId.AriasTheLabrynthButler)) + { + arias = GetWelcomeOrBigWelcomeTarget(cards, CardId.AriasTheLabrynthButler); + } + if (!activatedCardIdList.Contains(CardId.LabrynthCooclock) && CheckRemainInDeck(CardId.LabrynthCooclock) > 0 + && !Bot.HasInHand(CardId.LabrynthCooclock)) + { + cooclock = GetWelcomeOrBigWelcomeTarget(cards, CardId.LabrynthCooclock); + } + if (arias != null || cooclock != null) + { + SortedDictionary> trapCheckDict = new SortedDictionary> { + {CardId.BigWelcomeLabrynth, BigWelcomeLabrynthSetCheck}, + {_CardId.DimensionalBarrier, DimensionalBarrierActivate}, + {CardId.DestructiveDarumaKarmaCannon, DestructiveDarumaKarmaCannonSetCheck}, + {CardId.WelcomeLabrynth, WelcomeLabrynthSetCheck} + }; + foreach (KeyValuePair> checkPair in trapCheckDict) + { + if (Bot.GetSpells().Any(card => card.IsFacedown() && !setTrapThisTurn.Contains(card) && card.IsCode(checkPair.Key))) continue; + if (!activatedCardIdList.Contains(checkPair.Key)) + { + if (Bot.GetSpells().Any(card => card.IsFacedown() && setTrapThisTurn.Contains(card) && card.IsCode(checkPair.Key)) + && cooclock != null) + { + return Util.CheckSelectCount(new List { cooclock }, cards, min, max); + } + else if (Bot.HasInHand(checkPair.Key)) + { + if (checkPair.Value()) + { + if (arias != null) + { + return Util.CheckSelectCount(new List { arias }, cards, min, max); + } + if (Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2 && cooclock != null) + { + return Util.CheckSelectCount(new List { cooclock }, cards, min, max); + } + } + } + } + } + } + + bool lackUnimportantCost = !Bot.GetSpells().Any(card => card.IsFacedown() && card.IsCode(CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth)); + if (lackUnimportantCost) + { + List handCost = Bot.Hand.Where(card => card != Card).ToList(); + lackUnimportantCost &= handCost.Count() <= 2 && !handCost.Any(card => !card.IsCode(_CardId.MaxxC, _CardId.AshBlossom, CardId.LabrynthCooclock)); + } + if (!lackUnimportantCost && cooclock != null && bigWelcome != null) + { + foreach (int furnitureId in furnitureCheckIdList) + { + if (furnitureId == CardId.LabrynthCooclock) continue; + if (CheckCalledbytheGrave(furnitureId) == 0 && !activatedCardIdList.Contains(furnitureId) && Bot.HasInHand(furnitureId)) + { + return Util.CheckSelectCount(new List { cooclock }, cards, min, max); + } + } + } + + if (Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2) + { + // search not exist furniture + if (!lackUnimportantCost) + { + foreach (int checkId in furnitureCheckIdList) + { + ClientCard furniture = GetWelcomeOrBigWelcomeTarget(cards, checkId); + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(checkId) && furniture != null) + { + if (checkId == CardId.LabrynthCooclock) + { + if (Enemy.GetMonsterCount() > 0 && !Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.LabrynthChandraglier)) continue; + } + return Util.CheckSelectCount(new List { furniture }, cards, min, max); + } + } + } + + // search big welcome + if (bigWelcome != null) + { + bool needSpSummonLovely = !Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) + && !Bot.HasInHandOrInSpellZone(CardId.BigWelcomeLabrynth) && cards.Any(c => c.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)); + needSpSummonLovely |= Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) && !Bot.HasInHandOrInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth); + if (needSpSummonLovely) + { + return Util.CheckSelectCount(new List { AriannaSearchWelcomeTrap(cards, CardId.BigWelcomeLabrynth) }, cards, min, max); + } + } + // search welcome + if (welcome != null && Bot.HasInHandOrInSpellZone(CardId.BigWelcomeLabrynth) && !Bot.HasInHandOrInSpellZone(CardId.WelcomeLabrynth)) + { + return Util.CheckSelectCount(new List { AriannaSearchWelcomeTrap(cards, CardId.WelcomeLabrynth) }, cards, min, max); + } + } + + // search big welcome/arias + if (Duel.Player == 1 && (Duel.Phase <= DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2) + && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.AriasTheLabrynthButler) + && !Bot.HasInSpellZone(CardId.BigWelcomeLabrynth)) + { + if (Bot.HasInHand(CardId.BigWelcomeLabrynth) && !Bot.HasInHandOrHasInMonstersZone(CardId.AriasTheLabrynthButler) && arias != null) + { + return Util.CheckSelectCount(new List { arias }, cards, min, max); + } + if (Bot.HasInHand(CardId.AriasTheLabrynthButler) && !Bot.HasInHandOrHasInMonstersZone(CardId.BigWelcomeLabrynth) && bigWelcome != null) + { + return Util.CheckSelectCount(new List { bigWelcome }, cards, min, max); + } + } + + // search lady + ClientCard lady = GetWelcomeOrBigWelcomeTarget(cards, CardId.LadyLabrynthOfTheSilverCastle); + bool haveTrap = Duel.Player == 0 && Bot.Hand.Any(card => card.Type == (int)CardType.Trap) && Duel.Phase <= DuelPhase.Main2; + haveTrap |= Bot.GetSpells().Any(card => card.IsFacedown() && card.Type == (int)CardType.Trap); + if (!Bot.HasInHandOrHasInMonstersZone(CardId.LadyLabrynthOfTheSilverCastle) && !activatedCardIdList.Contains(CardId.LadyLabrynthOfTheSilverCastle) + && haveTrap && lady != null) + { + return Util.CheckSelectCount(new List { lady }, cards, min, max); + } + + if (!activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && !CheckWhetherNegated(true, true, CardType.Monster) + && CheckCalledbytheGrave(CardId.AriannaTheLabrynthServant) == 0 && arianna != null && !Bot.HasInHand(CardId.AriannaTheLabrynthServant)) + { + return Util.CheckSelectCount(new List { arianna }, cards, min, max); + } + + // search not exist furniture + if (!lackUnimportantCost) + { + foreach (int checkId in furnitureCheckIdList) + { + ClientCard furniture = GetWelcomeOrBigWelcomeTarget(cards, checkId); + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(checkId) && furniture != null) + { + if (checkId == CardId.LabrynthCooclock) + { + if (Enemy.GetMonsterCount() > 0 && !Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.LabrynthChandraglier)) continue; + } + return Util.CheckSelectCount(new List { furniture }, cards, min, max); + } + } + } + + // search not exist card + List uniqueCheckIdList = new List{ + CardId.BigWelcomeLabrynth, CardId.LabrynthStovieTorbie, CardId.LabrynthCooclock, CardId.LabrynthChandraglier, + CardId.LadyLabrynthOfTheSilverCastle, CardId.AriasTheLabrynthButler, CardId.ArianeTheLabrynthServant, CardId.WelcomeLabrynth}; + foreach (int checkId in uniqueCheckIdList) + { + ClientCard targetCard = GetWelcomeOrBigWelcomeTarget(cards, checkId); + if (!Bot.HasInMonstersZone(checkId) && !Bot.HasInHandOrInSpellZone(checkId) && targetCard != null) + { + if (checkId == CardId.BigWelcomeLabrynth || checkId == CardId.WelcomeLabrynth) + { + return Util.CheckSelectCount(new List { AriannaSearchWelcomeTrap(cards, checkId) }, cards, min, max); + } + else + { + return Util.CheckSelectCount(new List { targetCard }, cards, min, max); + } + } + } + + foreach (int checkId in uniqueCheckIdList) + { + ClientCard targetCard = GetWelcomeOrBigWelcomeTarget(cards, checkId); + if (CheckRemainInDeck(checkId) > 0) + { + if (checkId == CardId.BigWelcomeLabrynth || checkId == CardId.WelcomeLabrynth) + { + return Util.CheckSelectCount(new List { AriannaSearchWelcomeTrap(cards, checkId) }, cards, min, max); + } + else + { + return Util.CheckSelectCount(new List { targetCard }, cards, min, max); + } + } + } + } + + // solved when have more than 1 monster + if (bigwelcomeSoving && hint == HintMsg.SpSummon) + { + bool activateTimingFlag = Duel.Phase > DuelPhase.Main2 || (Card.IsCode(CardId.AriasTheLabrynthButler) && (CurrentTiming & hintTimingMainEnd) > 0); + + bool needDestroyFlag = GetProblematicEnemyCardList(false).Count() > 0; + needDestroyFlag |= activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && activateTimingFlag; + needDestroyFlag |= Bot.UnderAttack && (Bot.BattlingMonster?.GetDefensePower() ?? 0) <= (Enemy.BattlingMonster?.GetDefensePower() ?? 0) && Duel.LastChainPlayer != 0; + needDestroyFlag |= Duel.Turn == 1 && Duel.Player == 0 && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1); + needDestroyFlag |= Duel.Turn == 1 && Enemy.GetMonsterCount() == 0 && Enemy.GetSpellCount() == 0 && Enemy.Hand.Count > 0 + && (CurrentTiming & hintTimingMainEnd) > 0; + + if (needDestroyFlag && cards.Any(c => c.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)) + && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1)) + { + return Util.CheckSelectCount(new List { GetWelcomeOrBigWelcomeTarget(cards, CardId.LovelyLabrynthOfTheSilverCastle) }, cards, min, max); + } + if (cards.Any(c => c.IsCode(CardId.AriannaTheLabrynthServant)) + && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && !Bot.HasInMonstersZone(CardId.AriannaTheLabrynthServant)) + { + return Util.CheckSelectCount(new List { GetWelcomeOrBigWelcomeTarget(cards, CardId.AriannaTheLabrynthServant) }, cards, min, max); + } + if (cards.Any(c => c.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)) + && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1)) + { + return Util.CheckSelectCount(new List { GetWelcomeOrBigWelcomeTarget(cards, CardId.LovelyLabrynthOfTheSilverCastle) }, cards, min, max); + } + if (cards.Any(c => c.IsCode(CardId.AriannaTheLabrynthServant)) + && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && !chainSummoningIdList.Contains(CardId.AriannaTheLabrynthServant)) + { + return Util.CheckSelectCount(new List { GetWelcomeOrBigWelcomeTarget(cards, CardId.AriannaTheLabrynthServant) }, cards, min, max); + } + if (cards.Any(c => c.IsCode(CardId.LadyLabrynthOfTheSilverCastle)) + && Duel.Turn > 1 && Duel.Phase < DuelPhase.Main2 && Duel.Player == 0 && Enemy.GetMonsterCount() == 0) + { + return Util.CheckSelectCount(new List { GetWelcomeOrBigWelcomeTarget(cards, CardId.LadyLabrynthOfTheSilverCastle) }, cards, min, max); + } + List furnitureCheckIdList = new List { CardId.LabrynthStovieTorbie, CardId.LabrynthCooclock, CardId.LabrynthChandraglier, CardId.AriasTheLabrynthButler }; + foreach (int furniture in furnitureCheckIdList) + { + if (cards.Any(c => c.IsCode(furniture)) && !Bot.HasInHandOrInMonstersZoneOrInGraveyard(furniture)) + { + return Util.CheckSelectCount(new List { GetWelcomeOrBigWelcomeTarget(cards, furniture) }, cards, min, max); + } + } + List checkIdList = new List{CardId.ArianeTheLabrynthServant, CardId.LadyLabrynthOfTheSilverCastle, CardId.AriannaTheLabrynthServant, + CardId.LabrynthStovieTorbie, CardId.LabrynthCooclock, CardId.LabrynthChandraglier, CardId.AriasTheLabrynthButler}; + foreach (int checkId in checkIdList) + { + if (cards.Any(c => c.IsCode(checkId))) + { + return Util.CheckSelectCount(new List { GetWelcomeOrBigWelcomeTarget(cards, checkId) }, cards, min, max); + } + } + // should not get here + Logger.DebugWriteLine("[warning] call BigWelcomeSpSummon with no select."); + } + + if (bigwelcomeSoving && hint == HintMsg.ReturnToHand) + { + if (bigwelcomeEscaseTarget != null && cards.Contains(bigwelcomeEscaseTarget)) + { + return Util.CheckSelectCount(new List { bigwelcomeEscaseTarget }, cards, min, max); + } + + ClientCard cooclock = cards.FirstOrDefault(c => c.IsCode(CardId.LabrynthCooclock)); + bool canSearchWelcome = CheckRemainInDeck(CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth) > 0 + && (Bot.HasInHandOrHasInMonstersZone(new List { CardId.LabrynthChandraglier, CardId.LabrynthStovieTorbie }) + || summonInChainList.Any(c => c.IsCode(CardId.AriannaTheLabrynthServant)) + || (Duel.Player == 0 && !summoned && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && Bot.HasInHand(CardId.AriannaTheLabrynthServant))); + if (cooclock != null) + { + if (setTrapThisTurn.Count() > 0 + || (Duel.Turn == 1 && ( + (!activatedCardIdList.Contains(CardId.LadyLabrynthOfTheSilverCastle) && Bot.HasInHandOrHasInMonstersZone(CardId.LadyLabrynthOfTheSilverCastle)) + || canSearchWelcome + ) + ) + || Duel.Turn == 0 && canSearchWelcome + ) + return Util.CheckSelectCount(new List { cooclock }, cards, min, max); + } + + ClientCard defenseLady = cards.FirstOrDefault(c => c.IsDefense() && c.IsCode(CardId.LadyLabrynthOfTheSilverCastle)); + ClientCard attackLady = cards.FirstOrDefault(c => c.IsAttack() && c.IsCode(CardId.LadyLabrynthOfTheSilverCastle)); + if (Bot.GetMonsters().Any(card => (Duel.Player == 1 || card.IsDefense()) && card.IsCode(CardId.LadyLabrynthOfTheSilverCastle)) + && (!activatedCardIdList.Contains(CardId.LadyLabrynthOfTheSilverCastle) || activatedCardIdList.Contains(CardId.LadyLabrynthOfTheSilverCastle + 1))) + { + if (defenseLady != null) return Util.CheckSelectCount(new List { defenseLady }, cards, min, max); + if (attackLady != null) return Util.CheckSelectCount(new List { attackLady }, cards, min, max); + } + if (summonInChainList.Any(c => c.IsCode(CardId.LovelyLabrynthOfTheSilverCastle))) + { + List returnCheckIdList = new List{ + _CardId.MaxxC, CardId.AriannaTheLabrynthServant, _CardId.AshBlossom, CardId.LabrynthCooclock, CardId.LadyLabrynthOfTheSilverCastle, + CardId.LabrynthChandraglier, CardId.LabrynthStovieTorbie, CardId.AriasTheLabrynthButler, CardId.UnchainedSoulOfSharvara, CardId.ArianeTheLabrynthServant + }; + foreach (int checkId in returnCheckIdList) + { + ClientCard returnTarget = cards.FirstOrDefault(c => c.IsCode(checkId)); + if (returnTarget != null) return Util.CheckSelectCount(new List { returnTarget }, cards, min, max); + } + return Util.CheckSelectCount(cards.OrderBy(card => card.Attack).ToList(), cards, min, max); + } + if (cards.Count() == 1) return Util.CheckSelectCount(cards.OrderBy(card => card.Attack).ToList(), cards, min, max); + ClientCard ariannaNotSummon = cards.FirstOrDefault(c => c.IsCode(CardId.AriannaTheLabrynthServant) && !summonInChainList.Contains(c)); + if (ariannaNotSummon != null) return Util.CheckSelectCount(new List { ariannaNotSummon }, cards, min, max); + else + { + // compare which have lower attack + ClientCard fieldTarget = Bot.GetMonsters().Where(card => !card.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)) + .OrderBy(card => card.Attack).FirstOrDefault(); + if (fieldTarget != null) return Util.CheckSelectCount(new List { fieldTarget }, cards, min, max); + } + } + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + public ClientCard GetWelcomeOrBigWelcomeTarget(IList cards, int cardId) + { + ClientCard graveTarget = cards.FirstOrDefault(card => card.IsCode(cardId) && card.Location == CardLocation.Grave); + if (graveTarget != null) return graveTarget; + ClientCard deckTarget = cards.FirstOrDefault(card => card.IsCode(cardId) && card.Location == CardLocation.Deck); + if (deckTarget != null) return deckTarget; + ClientCard handTarget = cards.FirstOrDefault(card => card.IsCode(cardId) && card.Location == CardLocation.Hand); + if (handTarget != null) return handTarget; + return null; + } + + public ClientCard AriannaSearchWelcomeTrap(IList cards, int welcomeId) + { + bool haveCostToSolve = Bot.HasInHand(new List { CardId.LovelyLabrynthOfTheSilverCastle, CardId.TransactionRollback, CardId.AriasTheLabrynthButler }); + if (haveCostToSolve) + { + List checkIdList = new List { CardId.LabrynthStovieTorbie, CardId.LabrynthChandraglier }; + foreach (int checkId in checkIdList) + { + ClientCard targetCard = GetWelcomeOrBigWelcomeTarget(cards, checkId); + if (targetCard != null && !Bot.HasInHandOrInMonstersZoneOrInGraveyard(checkId) && CheckCalledbytheGrave(checkId) == 0 && !activatedCardIdList.Contains(checkId)) + { + return targetCard; + } + } + foreach (int checkId in checkIdList) + { + ClientCard targetCard = GetWelcomeOrBigWelcomeTarget(cards, checkId); + if (targetCard != null && CheckCalledbytheGrave(checkId) == 0 && !activatedCardIdList.Contains(checkId)) + { + return targetCard; + } + } + } + + return GetWelcomeOrBigWelcomeTarget(cards, welcomeId); + } + + /// + /// go first + /// + public override bool OnSelectHand() + { + return true; + } + + public override bool OnSelectMonsterSummonOrSet(ClientCard card) + { + if (card.Attack > 0 && CheckCanDirectAttack()) return false; + if (card.Attack <= 1000) return true; + + return base.OnSelectMonsterSummonOrSet(card); + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location == CardLocation.MonsterZone) + { + // selected in summon process + if (cardId == CardId.RelinquishedAnima) + { + return base.OnSelectPlace(cardId, player, location, available); + } + if (cardId == CardId.UnchainedSoulLordOfYama || cardId == CardId.UnchainedSoulOfAnguish) + { + if (Bot.MonsterZone[0] != null && Bot.MonsterZone[2] != null && (Zones.z6 & available) != 0) return Zones.z6; + if (Bot.MonsterZone[2] != null && Bot.MonsterZone[4] != null && (Zones.z5 & available) != 0) return Zones.z5; + } + if (cardId == CardId.MuckrakerFromTheUnderworld || cardId == CardId.UnchainedSoulOfRage) + { + if (Bot.MonsterZone[1] != null && (Zones.z6 & available) != 0) return Zones.z6; + if (Bot.MonsterZone[3] != null && (Zones.z5 & available) != 0) return Zones.z5; + } + + List zoneIdList = ShuffleList(new List { 0, 2, 4 }); + zoneIdList.AddRange(ShuffleList(new List { 1, 3 })); + zoneIdList.AddRange(ShuffleList(new List { 5, 6 })); + foreach (int zoneId in zoneIdList) + { + int zone = (int)System.Math.Pow(2, zoneId); + if ((available & zone) != 0 && Bot.MonsterZone[zoneId] == null) + { + return zone; + } + } + } + return base.OnSelectPlace(cardId, player, location, available); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2) + { + bool turnDefense = false; + if (cardData.Attack <= cardData.Defense) + { + turnDefense = true; + } + if (turnDefense) + { + return CardPosition.FaceUpDefence; + } + } + if (Duel.Player == 1) + { + if (cardData.Defense >= cardData.Attack || Util.IsOneEnemyBetterThanValue(cardData.Attack, true)) + { + return CardPosition.FaceUpDefence; + } + } + int cardAttack = cardData.Attack; + int bestBotAttack = Math.Max(Util.GetBestAttack(Bot), cardAttack); + if (Util.IsAllEnemyBetterThanValue(bestBotAttack, true)) + { + return CardPosition.FaceUpDefence; + } + } + return base.OnSelectPosition(cardId, positions); + } + + public override int OnSelectOption(IList options) + { + // override for cooclock + if (options.Count() == 2 && options.Contains(1190) && options.Contains(1152)) + { + // 1190=Add to Hand, 1152=Special Summon + // return to hand to activate trap set this turn + bool canLink = Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2; + if (!canLink && !Bot.HasInHand(CardId.LabrynthCooclock) && Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth)) + && !activatedCardIdList.Contains(CardId.LabrynthCooclock) && !CheckWhetherWillbeRemoved() + && (activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) || Bot.GetSpells().All(card => setTrapThisTurn.Contains(card) || !card.IsCode(CardId.BigWelcomeLabrynth))) + && setTrapThisTurn.Any(card => card.IsFacedown() && card.IsCode(CardId.BigWelcomeLabrynth, _CardId.DimensionalBarrier, _CardId.InfiniteImpermanence, CardId.DestructiveDarumaKarmaCannon))) + { + return options.IndexOf(1190); + } + if (!enemyActivateMaxxC) return options.IndexOf(1152); + if (activatedCardIdList.Contains(CardId.LabrynthCooclock)) + { + if (!CheckShouldNoMoreSpSummon()) return options.IndexOf(1152); + } + return options.IndexOf(1190); + } + + // overrride for lovely + if (options.Contains(Util.GetStringId(CardId.LovelyLabrynthOfTheSilverCastle, 3)) && options.Contains(Util.GetStringId(CardId.LovelyLabrynthOfTheSilverCastle, 4))) + { + int botWorstAttack = 0; + ClientCard botWorstMonster = Util.GetWorstBotMonster(true); + if (botWorstMonster != null) + { + botWorstAttack = botWorstMonster.Attack; + } + List targetList = GetProblematicEnemyCardList(false); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && card.GetDefensePower() >= botWorstAttack && !currentDestroyCardList.Contains(card)).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => !currentDestroyCardList.Contains(card) && card.IsFacedown()).ToList())); + if (targetList.Count() > 0) + { + currentDestroyCardList.Add(targetList[0]); + AI.SelectCard(targetList); + return options.IndexOf(Util.GetStringId(CardId.LovelyLabrynthOfTheSilverCastle, 4)); + } + else + { + return options.IndexOf(Util.GetStringId(CardId.LovelyLabrynthOfTheSilverCastle, 3)); + } + } + + // override for dimensional barrier + if (options.IndexOf(HintMsg.RITUAL) >= 0 || options.IndexOf(HintMsg.FUSION) >= 0 || options.IndexOf(HintMsg.SYNCHRO) >= 0 + || options.IndexOf(HintMsg.XYZ) >= 0 || options.IndexOf(HintMsg.PENDULUM) >= 0) + { + Dictionary> barrierCheckDict = new Dictionary> + { + {HintMsg.RITUAL, DimensionalBarrierForRitual}, + {HintMsg.FUSION, DimensionalBarrierForFusion}, + {HintMsg.SYNCHRO, DimensionalBarrierForSynchro}, + {HintMsg.XYZ, DimensionalBarrierForXyz}, + {HintMsg.PENDULUM, DimensionalBarrierForPendulum}, + }; + dimensionBarrierAnnouncing = true; + foreach (KeyValuePair> checkPair in barrierCheckDict) + { + if (options.Contains(checkPair.Key) && checkPair.Value()) + { + dimensionBarrierAnnouncing = false; + dimensionalBarrierAnnouced.Add(checkPair.Key); + return options.IndexOf(checkPair.Key); + } + } + dimensionBarrierAnnouncing = false; + List enemyMonsterList = new List(Enemy.GetMonsters()); + enemyMonsterList.AddRange(Enemy.GetGraveyardMonsters()); + Dictionary barrierCheckSecondark = new Dictionary + { + {HintMsg.RITUAL, enemyMonsterList.Any(card => card.HasType(CardType.Ritual))}, + {HintMsg.FUSION, enemyMonsterList.Any(card => card.HasType(CardType.Fusion))}, + {HintMsg.SYNCHRO, enemyMonsterList.Any(card => card.HasType(CardType.Synchro))}, + {HintMsg.XYZ, enemyMonsterList.Any(card => card.HasType(CardType.Xyz))}, + {HintMsg.PENDULUM, enemyMonsterList.Any(card => card.HasType(CardType.Pendulum))}, + }; + foreach (KeyValuePair checkPair in barrierCheckSecondark) + { + if (options.Contains(checkPair.Key) && checkPair.Value) + { + dimensionBarrierAnnouncing = false; + dimensionalBarrierAnnouced.Add(checkPair.Key); + return options.IndexOf(checkPair.Key); + } + } + List annouceList = new List { HintMsg.XYZ, HintMsg.SYNCHRO, HintMsg.FUSION, HintMsg.PENDULUM, HintMsg.RITUAL }; + foreach (int annouce in annouceList) + { + if (options.Contains(annouce)) + { + return options.IndexOf(annouce); + } + } + } + + // override for servant + // sp summon + if (options.Contains(Util.GetStringId(CardId.AriannaTheLabrynthServant, 2)) || options.Contains(Util.GetStringId(CardId.ArianeTheLabrynthServant, 2))) + { + if (GetEmptyMainMonsterZoneCount() > chainSummoningIdList.Count()) + { + bool checkFlag = false; + if (!activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && Bot.HasInHand(CardId.AriannaTheLabrynthServant) + && !CheckWhetherNegated(true, true, CardType.Monster) && !chainSummoningIdList.Contains(CardId.AriannaTheLabrynthServant)) + { + checkFlag = true; + AI.SelectCard(CardId.AriannaTheLabrynthServant); + } + if (!checkFlag) + { + List checkIdList = new List { CardId.LovelyLabrynthOfTheSilverCastle, CardId.LadyLabrynthOfTheSilverCastle }; + foreach (int checkId in checkIdList) + { + if (Bot.HasInHand(checkId)) + { + checkFlag = true; + AI.SelectCard(checkId); + break; + } + } + } + if (!checkFlag && Duel.Player == 0 && Duel.Phase < DuelPhase.End) + { + List linkMaterialList = GetCanBeUsedForLinkMaterial(true, card => !card.HasRace(CardRace.Fiend)); + if (linkMaterialList.Count() + chainSummoningIdList.Count() == 2) + { + // summon less atk for link + ClientCard selected = null; + int attack = 0; + foreach (ClientCard hand in Bot.Hand) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(hand.Id); + if (cardData == null || cardData.Race != (int)CardRace.Fiend) continue; + if (selected == null || attack > hand.Attack) + { + selected = hand; + attack = hand.Attack; + } + } + if (selected != null) + { + checkFlag = true; + AI.SelectCard(selected); + } + } + } + if (!checkFlag && CheckCanDirectAttack()) + { + // summon best attack for attack + ClientCard selected = null; + int attack = 0; + foreach (ClientCard hand in Bot.Hand) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(hand.Id); + if (cardData == null || cardData.Race != (int)CardRace.Fiend) continue; + if (selected == null || attack < hand.Attack) + { + selected = hand; + attack = hand.Attack; + } + } + if (selected != null) + { + checkFlag = true; + AI.SelectCard(selected); + } + } + + if (checkFlag) + { + if (options.Contains(Util.GetStringId(CardId.AriannaTheLabrynthServant, 2))) return options.IndexOf(Util.GetStringId(CardId.AriannaTheLabrynthServant, 2)); + if (options.Contains(Util.GetStringId(CardId.ArianeTheLabrynthServant, 2))) return options.IndexOf(Util.GetStringId(CardId.ArianeTheLabrynthServant, 2)); + } + } + } + + // set + if (options.Contains(Util.GetStringId(CardId.AriannaTheLabrynthServant, 3)) || options.Contains(Util.GetStringId(CardId.ArianeTheLabrynthServant, 3))) + { + if (!Util.ChainContainsCard(CardId.WelcomeLabrynth) || Bot.GetSpellCountWithoutField() < 4) + { + List checkIdList = new List { CardId.BigWelcomeLabrynth, CardId.WelcomeLabrynth, _CardId.InfiniteImpermanence, _CardId.DimensionalBarrier, CardId.DestructiveDarumaKarmaCannon }; + foreach (int checkId in checkIdList) + { + if (Bot.HasInHand(checkId) && (checkId == _CardId.InfiniteImpermanence || !Bot.HasInSpellZone(checkId, faceUp:false))) + { + AI.SelectCard(checkId); + if (options.Contains(Util.GetStringId(CardId.AriannaTheLabrynthServant, 3))) return options.IndexOf(Util.GetStringId(CardId.AriannaTheLabrynthServant, 3)); + if (options.Contains(Util.GetStringId(CardId.ArianeTheLabrynthServant, 3))) return options.IndexOf(Util.GetStringId(CardId.ArianeTheLabrynthServant, 3)); + } + } + } + } + + // do nothing + if (options.Contains(Util.GetStringId(CardId.AriannaTheLabrynthServant, 4))) return options.IndexOf(Util.GetStringId(CardId.AriannaTheLabrynthServant, 4)); + if (options.Contains(Util.GetStringId(CardId.ArianeTheLabrynthServant, 4))) return options.IndexOf(Util.GetStringId(CardId.ArianeTheLabrynthServant, 4)); + + return base.OnSelectOption(options); + } + + public override bool OnSelectYesNo(int desc) + { + if (desc == 96) + { + Logger.DebugWriteLine("*** muckraker replace."); + AI.SelectCard(Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasRace(CardRace.Fiend)).OrderBy(card => card.Attack).ToList()); + return true; + } + return base.OnSelectYesNo(desc); + } + + public override void OnNewTurn() + { + if (Duel.Turn <= 1) + { + dimensionShifterCount = 0; + + enemySpSummonFromExLastTurn = 0; + enemySpSummonFromExThisTurn = 0; + banSpSummonExceptFiendCount = 0; + } + enemyActivateMaxxC = false; + enemySpSummonFromExLastTurn = enemySpSummonFromExThisTurn; + enemySpSummonFromExThisTurn = 0; + rollbackCopyCardId = 0; + + if (dimensionShifterCount > 0) dimensionShifterCount--; + if (banSpSummonExceptFiendCount > 0) banSpSummonExceptFiendCount--; + infiniteImpermanenceList.Clear(); + + summoned = false; + cooclockAffected = false; + activatedCardIdList.Clear(); + setTrapThisTurn.Clear(); + summonThisTurn.Clear(); + enemySetThisTurn.Clear(); + dimensionalBarrierAnnouced.Clear(); + summonInChainList.Clear(); + base.OnNewTurn(); + } + + public override void OnChaining(int player, ClientCard card) + { + if (card == null) return; + if (chainSummoningIdList.Count() > 0) + Logger.DebugWriteLine("[Welcome] Summoning: " + string.Join(",", chainSummoningIdList) + "\n"); + + if (player == 1) + { + if (card.IsCode(_CardId.InfiniteImpermanence)) + { + if (enemyActivateInfiniteImpermanenceFromHand) + { + enemyActivateInfiniteImpermanenceFromHand = false; + } + else { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == card) + { + infiniteImpermanenceList.Add(4-i); + break; + } + } + } + } + } + base.OnChaining(player, card); + } + + public override void OnChainSolved(int chainIndex) + { + ChainInfo currentCard = Duel.GetCurrentSolvingChainInfo(); + if (currentCard != null && !Duel.IsCurrentSolvingChainNegated()) + { + if (currentCard.ActivatePlayer == 1) + { + if (currentCard.IsCode(_CardId.MaxxC)) + enemyActivateMaxxC = true; + if (currentCard.IsCode(CardId.DimensionShifter)) + dimensionShifterCount = 2; + } + if (currentCard.ActivatePlayer == 0) + { + if (currentCard.IsCode(CardId.LabrynthCooclock)) + cooclockAffected = true; + } + } + + base.OnChainSolved(chainIndex); + } + + public override void OnChainEnd() + { + rollbackCopyCardId = 0; + currentNegateMonsterList.Clear(); + currentDestroyCardList.Clear(); + escapeTargetList.Clear(); + chainSummoningIdList.Clear(); + summonInChainList.Clear(); + enemyActivateInfiniteImpermanenceFromHand = false; + for (int idx = enemySetThisTurn.Count() - 1; idx >= 0; idx --) + { + ClientCard checkTarget = enemySetThisTurn[idx]; + if (checkTarget == null || checkTarget.Location != CardLocation.SpellZone || checkTarget.HasPosition(CardPosition.FaceUp)) + { + enemySetThisTurn.RemoveAt(idx); + } + } + if (cooclockActivating) + cooclockActivating = false; + furnitureActivating = false; + dimensionBarrierAnnouncing = false; + bigwelcomeEscaseTarget = null; + base.OnChainEnd(); + } + + public override void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + if (previousControler == 1) + { + if (previousLocation == (int)CardLocation.Extra && currentLocation == (int)CardLocation.MonsterZone) enemySpSummonFromExThisTurn ++; + if (card != null) + { + if (card.IsCode(_CardId.InfiniteImpermanence) && previousLocation == (int)CardLocation.Hand && currentLocation == (int)CardLocation.SpellZone) + enemyActivateInfiniteImpermanenceFromHand = true; + if (card.Location == CardLocation.SpellZone && card.HasPosition(CardPosition.FaceDown)) + enemySetThisTurn.Add(card); + } + } + if (card != null) + { + if (previousControler == 0) + { + if (previousLocation == (int)CardLocation.MonsterZone && currentLocation != (int)CardLocation.MonsterZone) + { + if (summonThisTurn.Contains(card)) summonThisTurn.Remove(card); + if (summonInChainList.Contains(card)) summonInChainList.Remove(card); + } + if (previousLocation == (int)CardLocation.SpellZone && currentLocation != (int)CardLocation.SpellZone) + { + if (setTrapThisTurn.Contains(card)) setTrapThisTurn.Remove(card); + } + } + if (currentControler == 0) + { + ClientCard currentSolvingChain = Duel.GetCurrentSolvingChainCard(); + if (currentLocation == (int)CardLocation.SpellZone && (currentSolvingChain == null || !currentSolvingChain.IsCode(CardId.AriasTheLabrynthButler)) + && (card.HasType(CardType.Trap) || card.IsCode(CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth)) + ) + { + Logger.DebugWriteLine("[setTrapThisTurn]set " + card.Name ?? "UnknowCard"); + setTrapThisTurn.Add(card); + } + if (currentLocation == (int)CardLocation.MonsterZone) + { + summonThisTurn.Add(card); + if (currentSolvingChain != null) summonInChainList.Add(card); + } + } + } + + base.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + public override BattlePhaseAction OnBattle(IList attackers, IList defenders) + { + if (attackers.Count() > 0 && defenders.Count() > 0) + { + List sortedAttacker = attackers.OrderBy(card => card.Attack).ToList(); + for (int k = 0; k < sortedAttacker.Count; ++k) + { + ClientCard attacker = sortedAttacker[k]; + attacker.IsLastAttacker = k == sortedAttacker.Count - 1; + BattlePhaseAction result = OnSelectAttackTarget(attacker, defenders); + if (result != null) + return result; + } + } + + return base.OnBattle(attackers, defenders); + } + + /// + /// Select spell/trap's place randomly to avoid InfiniteImpermanence and so on. + /// + /// Card to set(default current card) + /// Whether need to avoid InfiniteImpermanence + /// Whether need to avoid set in this place + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceList.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public void ResetCooclockEffect(bool onlyCheck) + { + if (!onlyCheck && cooclockAffected && setTrapThisTurn.Contains(Card)) + { + cooclockAffected = false; + setTrapThisTurn.Remove(Card); + } + } + + + + + + public bool LadyLabrynthOfTheSilverCastleFieldActivate() + { + if (Card.Location == CardLocation.MonsterZone && (Util.GetLastChainCard() == null || !Util.GetLastChainCard().IsCode(_CardId.EvenlyMatched)) + && (!CheckWhetherNegated() || Enemy.HasInMonstersZone(CardId.LadyLabrynthOfTheSilverCastle))) + { + activatedCardIdList.Add(Card.Id + 1); + return true; + } + return false; + } + + public bool LadyLabrynthOfTheSilverCastleHandActivate() + { + if (Card.Location == CardLocation.Hand) + { + // sp summon from hand + if (CheckShouldNoMoreSpSummon(true) || Util.ChainContainsCard(_CardId.EvenlyMatched)) return false; + bool activateFlag = false; + activateFlag |= CheckChainContainEnemyMaxxC(); + if (!activateFlag && GetEmptyMainMonsterZoneCount() + chainSummoningIdList.Count() <= 0) + { + return false; + } + activateFlag |= cooclockAffected && setTrapThisTurn.Count() > 0 && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth)); + activateFlag |= Bot.GetSpells().Any(card => card.IsFacedown() && card.HasType(CardType.Trap) && !setTrapThisTurn.Contains(card)) + && !Bot.HasInMonstersZone(Card.Id, true, faceUp: true); + activateFlag |= Duel.Player == 1 && Duel.Phase >= DuelPhase.End; + activateFlag |= setTrapThisTurn.Count() > 0 && Duel.Phase >= DuelPhase.End; + activateFlag |= Bot.UnderAttack && Bot.GetMonsterCount() == 0 && !Util.ChainContainsCard(CardId.DestructiveDarumaKarmaCannon); + // for link + if (Bot.HasInExtra(CardId.UnchainedSoulLordOfYama) && Duel.Player == 0 && Duel.Phase < DuelPhase.End) + { + // check whether need summon for material count + List materialList = GetCanBeUsedForLinkMaterial(true, card => !card.HasRace(CardRace.Fiend)); + int materialCount = materialList.Count(); + if (!activatedCardIdList.Contains(CardId.UnchainedSoulOfSharvara) && Bot.GetSpells().Any(card => card.IsFacedown()) + && (!activatedCardIdList.Contains(CardId.UnchainedSoulLordOfYama) || Bot.HasInHand(CardId.UnchainedSoulOfSharvara))) materialCount++; + if ( (materialCount == 2 || materialCount == 1 && materialList.Any(card => card.IsCode(CardId.UnchainedSoulLordOfYama))) + && Bot.HasInExtra(CardId.UnchainedSoulLordOfYama) || materialList.Any(card => card.HasSetcode(SetcodeUnchained))) + { + activateFlag |= Enemy.GetMonsterCount() > 0 && Bot.HasInExtra(CardId.UnchainedSoulOfAnguish); + activateFlag |= Bot.HasInExtra(CardId.UnchainedSoulOfRage); + } + } + + if (activateFlag) + { + activatedCardIdList.Add(Card.Id); + chainSummoningIdList.Add(Card.Id); + return true; + } + } + return false; + } + + public bool LovelyLabrynthOfTheSilverCastleActivate() + { + if (CheckWhetherNegated()) return false; + if (ActivateDescription == Util.GetStringId(CardId.LovelyLabrynthOfTheSilverCastle, 0)) + { + // set from GY + List checkIdList = new List{CardId.BigWelcomeLabrynth, _CardId.InfiniteImpermanence, _CardId.DimensionalBarrier, + CardId.DestructiveDarumaKarmaCannon, CardId.WelcomeLabrynth}; + foreach (int checkId in checkIdList) + { + if (Bot.HasInGraveyard(checkId) && !Bot.HasInHandOrInSpellZone(checkId)) + { + AI.SelectCard(checkId); + activatedCardIdList.Add(Card.Id); + return true; + } + } + foreach (int checkId in checkIdList) + { + if (Bot.HasInGraveyard(checkId)) + { + AI.SelectCard(checkId); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + if (GetCanBeUsedForLinkMaterial(true, card => !card.HasRace(CardRace.Fiend)).Count() == 2 + && !activatedCardIdList.Contains(CardId.UnchainedSoulLordOfYama) + && (Bot.HasInGraveyard(CardId.UnchainedSoulOfSharvara) || CheckRemainInDeck(CardId.UnchainedSoulOfSharvara) > 0)) + { + activatedCardIdList.Add(Card.Id); + return true; + } + } + else + { + // destroy + if (Enemy.GetHandCount() == 0) + { + int botWorstAttack = 0; + ClientCard botWorstMonster = Util.GetWorstBotMonster(true); + if (botWorstMonster != null) + { + botWorstAttack = botWorstMonster.Attack; + } + List targetList = GetProblematicEnemyCardList(false); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && card.GetDefensePower() >= botWorstAttack && !currentDestroyCardList.Contains(card)).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => !currentDestroyCardList.Contains(card)).ToList())); + + if (targetList.Count() > 0) + { + currentDestroyCardList.Add(targetList[0]); + AI.SelectCard(targetList); + AI.SelectOption(1); + } + else + { + AI.SelectOption(0); + } + } + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public bool UnchainedSoulOfSharvaraActivate() + { + // search + if (Card.Location == CardLocation.Grave) + { + activatedCardIdList.Add(Card.Id + 1); + SelectSTPlace(null, false); + return true; + } + + // sp summon + if (Bot.HasInSpellZone(CardId.TransactionRollback) && GetEmptyMainMonsterZoneCount() > chainSummoningIdList.Count() + && !CheckWhetherWillbeRemoved() && !CheckShouldNoMoreSpSummon(false)) + { + AI.SelectCard(CardId.TransactionRollback); + activatedCardIdList.Add(Card.Id); + return true; + } + + // escape target + if (Duel.LastChainPlayer == 1) + { + ClientCard chainCard = Util.GetLastChainCard(); + if (chainCard != null && chainCard.IsCode(targetNegateIdList)) + { + if (Duel.LastChainTargets.Any(card => card.Controller == 0 && card.IsFaceup() && card.HasRace(CardRace.Fiend) + && Duel.CurrentChain.Any(chain => chain == card) && !card.IsCode(CardId.UnchainedSoulOfRage, CardId.UnchainedSoulOfAnguish))) + { + escapeTargetList.AddRange(Duel.LastChainTargets); + AI.SelectCard(Duel.LastChainTargets); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + + // for link + bool destroySpells = Duel.Player == 0 && GetEmptyMainMonsterZoneCount() > chainSummoningIdList.Count() && Bot.GetMonsterCount() > 0 && CurrentTiming <= 0; + if (destroySpells) + { + List materialList = GetCanBeUsedForLinkMaterial(true, card => !card.HasRace(CardRace.Fiend)); + destroySpells = CheckAtAdvantage() && !Bot.HasInMonstersZone(CardId.UnchainedSoulOfRage) + && Bot.HasInExtra(CardId.UnchainedSoulOfRage) && materialList.Count() == 1; + if (Bot.HasInExtra(CardId.UnchainedSoulOfAnguish) && !Bot.HasInMonstersZone(CardId.UnchainedSoulOfAnguish) + && !activatedCardIdList.Contains(CardId.UnchainedSoulOfAnguish) && Enemy.GetMonsters().Where(card => card.IsFaceup()).Count() > 0) + { + destroySpells |= materialList.Count() == 2; + destroySpells |= materialList.Count() == 1 && materialList.Any(card => card.HasType(CardType.Link) && card.LinkCount == 2); + } + } + // for attack + destroySpells |= CheckCanDirectAttack() && GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack() + 2000 >= Enemy.LifePoints + && GetEmptyMainMonsterZoneCount() > chainSummoningIdList.Count(); + // for avoid lose + destroySpells |= Duel.Player == 1 && Duel.Phase == DuelPhase.Main1 && Bot.GetMonsterCount() == 0 && (CurrentTiming & hintTimingMainEnd) != 0 + && Util.GetTotalAttackingMonsterAttack(1) >= Bot.LifePoints; + if (destroySpells) + { + List destroyIdList = new List{_CardId.InfiniteImpermanence, CardId.TransactionRollback, CardId.WelcomeLabrynth, + _CardId.DimensionalBarrier, CardId.DestructiveDarumaKarmaCannon, CardId.BigWelcomeLabrynth}; + foreach (int checkId in destroyIdList) + { + ClientCard target = Bot.GetSpells().FirstOrDefault(card => card.IsFacedown() && card.IsCode(checkId)); + if (target != null) + { + AI.SelectCard(target); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + + return false; + } + + public bool AriasTheLabrynthButlerActivate() + { + if (Card.Location != CardLocation.Grave) + { + if (Util.ChainContainsCard(new int[] { _CardId.DivineArsenalAAZEUS_SkyThunder, _CardId.EvenlyMatched, _CardId.EvilswarmExcitonKnight })) return false; + if (Duel.CurrentChain.Any(card => card.Controller == 0 && card.IsCode(CardId.AriannaTheLabrynthServant))) return false; + + // set trap to activate + SortedList> checkList = new SortedList> { + {CardId.BigWelcomeLabrynth, BigWelcomeLabrynthSetCheck}, + {CardId.WelcomeLabrynth, WelcomeLabrynthSetCheck}, + {CardId.DestructiveDarumaKarmaCannon, DestructiveDarumaKarmaCannonSetCheck}, + {_CardId.DimensionalBarrier, DimensionalBarrierActivate} + }; + foreach (KeyValuePair> pair in checkList) + { + ClientCard setTarget = Bot.Hand.FirstOrDefault(card => card.IsCode(pair.Key)); + if (setTarget != null && !activatedCardIdList.Contains(pair.Key) && pair.Value()) + { + AI.SelectOption(1); + AI.SelectCard(pair.Key); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(setTarget, true); + return true; + } + } + + // special summon monster + if (Bot.HasInHand(CardId.LovelyLabrynthOfTheSilverCastle)) + { + // before main end + if (Duel.Player == 0 || (CurrentTiming & hintTimingMainEnd) != 0) + { + AI.SelectOption(0); + AI.SelectCard(CardId.LovelyLabrynthOfTheSilverCastle); + chainSummoningIdList.Add(CardId.LovelyLabrynthOfTheSilverCastle); + activatedCardIdList.Add(Card.Id); + return true; + } + } + if (Bot.HasInHand(CardId.AriannaTheLabrynthServant) && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) + && !CheckWhetherNegated(true, true) && !chainSummoningIdList.Contains(CardId.AriannaTheLabrynthServant)) + { + bool searchFlag = false; + if (Duel.Player == 1) + { + searchFlag |= (CurrentTiming & hintTimingMainEnd) != 0; + searchFlag |= GetProblematicEnemyCardList(false).Count() > 0 + && (Bot.HasInMonstersZoneOrInGraveyard(CardId.LovelyLabrynthOfTheSilverCastle) || CheckRemainInDeck(CardId.LovelyLabrynthOfTheSilverCastle) > 0) + && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1); + } + if (Duel.Player == 0) searchFlag |= summoned && !CheckShouldNoMoreSpSummon(); + if (searchFlag) + { + AI.SelectOption(0); + AI.SelectCard(CardId.AriannaTheLabrynthServant); + chainSummoningIdList.Add(CardId.AriannaTheLabrynthServant); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + return false; + } + + public bool ArianeTheLabrynthServantSummon() + { + // for attack + if (Duel.Turn > 1 && Enemy.GetMonsterCount() == 0) + { + summoned = true; + return true; + } + // for activate effect + if (!activatedCardIdList.Contains(Card.Id) && !CheckWhetherNegated(true, true) && !CheckWhetherWillbeRemoved()) + { + bool haveCost = Bot.Hand.Any(card => card.Type == (int)CardType.Trap) || Bot.GetSpells().Any(card => card.IsFacedown() && card.Type == (int)CardType.Trap); + if (haveCost && !CheckShouldNoMoreSpSummon(true)) + { + summoned = true; + return true; + } + } + + return false; + } + public bool ArianeTheLabrynthServantForRollbackSummon() + { + if (activatedCardIdList.Contains(Card.Id)) return false; + if (Bot.HasInHandOrInSpellZone(CardId.TransactionRollback) && !CheckWhetherWillbeRemoved()) + { + summoned = true; + return true; + } + + return false; + } + public bool ArianeTheLabrynthServantActivate() + { + // special summon + if (ActivateDescription == Util.GetStringId(Card.Id, 0)) + { + bool haveRollback = Bot.HasInHandOrInSpellZone(CardId.TransactionRollback); + if (CheckWhetherNegated() && !haveRollback) return false; + if (CheckShouldNoMoreSpSummon() && !(haveRollback && Bot.Graveyard.Any(card => card.IsCode(CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth)))) return false; + int specialSummonId = 0; + // arianna + if (!activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && CheckRemainInDeck(CardId.AriannaTheLabrynthServant) > 0) + { + specialSummonId = CardId.AriannaTheLabrynthServant; + } + // sp summon not used furniture + if (specialSummonId == 0) + { + List checkIdList = new List{CardId.LabrynthStovieTorbie, CardId.LabrynthChandraglier, CardId.LabrynthCooclock}; + foreach (int checkId in checkIdList) + { + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(checkId) && CheckRemainInDeck(checkId) > 0) + { + specialSummonId = checkId; + break; + } + } + } + // for attack/link + if (specialSummonId == 0) + { + List checkIdList = new List(); + if (Enemy.GetMonsterCount() == 0) checkIdList.AddRange(new List{ + CardId.AriannaTheLabrynthServant, CardId.LabrynthChandraglier, CardId.LabrynthStovieTorbie, CardId.LabrynthCooclock + }); + else checkIdList.AddRange(new List{ + CardId.LabrynthChandraglier, CardId.LabrynthStovieTorbie, CardId.LabrynthCooclock, CardId.AriannaTheLabrynthServant + }); + foreach (int checkId in checkIdList) + { + if (CheckRemainInDeck(checkId) > 0) + { + specialSummonId = checkId; + break; + } + } + } + + if (specialSummonId > 0) + { + bool costSelected = false; + if (haveRollback) + { + AI.SelectCard(CardId.TransactionRollback); + costSelected = true; + } + if (!costSelected) { + ClientCard welcome = Bot.GetSpells().FirstOrDefault(card => card.IsCode(CardId.WelcomeLabrynth)); + if (welcome != null) + { + AI.SelectCard(welcome); + costSelected = true; + } + } + List costCheckList = Bot.Hand.Where(card => card.IsFacedown() && card.Type == (int)CardType.Trap).ToList(); + costCheckList.AddRange(Bot.GetSpells().Where(card => card.IsFacedown() && card.Type == (int)CardType.Trap).ToList()); + if (!costSelected) + { + List checkIdList = new List{_CardId.InfiniteImpermanence, CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth}; + foreach (int checkId in checkIdList) + { + ClientCard dumpCard = costCheckList.FirstOrDefault(card => card.IsCode(checkId)); + if (costCheckList.Count(card => card.IsCode(checkId)) > 1 && dumpCard != null) + { + AI.SelectCard(dumpCard); + costSelected = true; + break; + } + } + } + if (!costSelected) + { + List checkIdList = new List{_CardId.InfiniteImpermanence, _CardId.DimensionalBarrier, CardId.DestructiveDarumaKarmaCannon, + CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth}; + foreach (int checkId in checkIdList) + { + ClientCard checkCard = costCheckList.FirstOrDefault(card => card.IsCode(checkId)); + if (checkCard != null) + { + AI.SelectCard(checkCard); + costSelected = true; + break; + } + } + } + } + } else { + // draw + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public bool AriannaTheLabrynthServantSummon() + { + // summon for search + if (!CheckWhetherNegated(true, true) && !activatedCardIdList.Contains(Card.Id)) + { + summoned = true; + return true; + } + + // summon for attack + if (Duel.Turn > 1 && Duel.Player == 0 && Duel.Phase < DuelPhase.Main2 && Enemy.GetMonsterCount() == 0 && !Bot.HasInHand(CardId.ArianeTheLabrynthServant)) + { + summoned = true; + return true; + } + + return false; + } + public bool AriannaTheLabrynthServantActivate() + { + if (CheckWhetherNegated()) return false; + // search or draw + // search target is overrided in OnSelectCard() + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool AshBlossomActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (Util.GetLastChainCard().IsCode(_CardId.MaxxC)) return false; + if (DefaultAshBlossomAndJoyousSpring()) + { + if (Util.GetLastChainCard().Location == CardLocation.MonsterZone) currentNegateMonsterList.Add(Util.GetLastChainCard()); + return true; + } + return false; + } + + public bool MaxxCActivate() + { + if (CheckWhetherNegated(true) || Duel.LastChainPlayer == 0) return false; + return DefaultMaxxC(); + } + + public bool FurnitureSetWelcomeActivate() + { + if (furnitureActivating && (Card.Location == CardLocation.Hand || !DefaultOnBecomeTarget())) return false; + if (Util.ChainContainsCard(new int[]{ _CardId.DivineArsenalAAZEUS_SkyThunder, _CardId.EvenlyMatched, _CardId.EvilswarmExcitonKnight })) return false; + + if (CheckWhetherNegated()) return false; + if (Card.Location != CardLocation.Grave) + { + bool becomeTarget = Card.Location == CardLocation.MonsterZone && DefaultOnBecomeTarget() && !escapeTargetList.Contains(Card); + bool lackUnimportantCost = Bot.GetSpells().Any(card => card.IsFacedown() && card.IsCode(CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth)); + if (lackUnimportantCost) + { + List handCost = Bot.Hand.Where(card => card != Card).ToList(); + lackUnimportantCost &= handCost.Count() <= 2 && handCost.All(card => card.IsCode(_CardId.MaxxC, _CardId.AshBlossom)); + } + bool activateFlag = becomeTarget; + // set big welcome for lovely + bool canActivateSetBigWelcomeThisTurn = CheckRemainInDeck(CardId.BigWelcomeLabrynth) > 0 && cooclockAffected && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) + && (Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) || CheckBigWelcomeCanSpSummon(CardId.LovelyLabrynthOfTheSilverCastle)) + && (!Bot.GetSpells().Any(card => card.IsFacedown() && card.IsCode(CardId.BigWelcomeLabrynth) && !setTrapThisTurn.Contains(card))) + && ( + Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth)) + || (Bot.HasInGraveyard(CardId.LabrynthCooclock) && !activatedCardIdList.Contains(CardId.LabrynthCooclock + 1)) + || (Bot.HasInHand(CardId.LadyLabrynthOfTheSilverCastle) && !activatedCardIdList.Contains(CardId.LadyLabrynthOfTheSilverCastle)) + ); + if (canActivateSetBigWelcomeThisTurn && ShouldSetBigWelcome()) + { + bool force = becomeTarget | GetProblematicEnemyCardList(false).Count() > 0; + ClientCard cost = FurnitureGetCost(force); + if (cost != null) + { + AI.SelectCard(cost); + AI.SelectNextCard(CardId.BigWelcomeLabrynth); + activatedCardIdList.Add(Card.Id); + furnitureActivating = true; + SelectSTPlace(null, true); + return true; + } + } + bool keepOnField = (cooclockActivating || cooclockAffected) && activatedCardIdList.Contains(CardId.LabrynthCooclock + 1) + && Card.Location == CardLocation.MonsterZone && !Bot.GetMonsters().Any(card => card.IsFaceup() && card != Card && card.HasSetcode(SetcodeLabrynth)) + && setTrapThisTurn.Count() > 0; + // normal set + activateFlag |= Duel.Phase > DuelPhase.Main2 && !lackUnimportantCost && !keepOnField; + activateFlag |= Bot.HasInGraveyard(new List { CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth }) + && Bot.HasInHand(CardId.TransactionRollback) && !activatedCardIdList.Contains(CardId.TransactionRollback); + if (Duel.CurrentChain.Any(card => card != null && card.Controller == 0 && card.IsCode(CardId.BigWelcomeLabrynth) && card.Location == CardLocation.SpellZone) + && !(Bot.GetMonsterCount() == 1 && Card.Location == CardLocation.MonsterZone)) + { + activateFlag |= !lackUnimportantCost && Bot.GetMonsters().Any(card => card != Card) && !Bot.HasInGraveyard(Card.Id) && !activatedCardIdList.Contains(Card.Id + 1); + } + // trigger cooclock to defense + activateFlag |= !Util.ChainContainPlayer(0) && Duel.Player == 1 && Bot.UnderAttack && Bot.GetMonsterCount() == 0 + && Bot.HasInGraveyard(CardId.LabrynthCooclock) && !activatedCardIdList.Contains(CardId.LabrynthCooclock + 1) + && !(Bot.HasInHand(CardId.LadyLabrynthOfTheSilverCastle) && !activatedCardIdList.Contains(CardId.LadyLabrynthOfTheSilverCastle)); + + if (activateFlag) + { + ClientCard cost = FurnitureGetCost(becomeTarget); + if (cost != null) + { + AI.SelectCard(cost); + activatedCardIdList.Add(Card.Id); + furnitureActivating = true; + bool setWelcome = Bot.GetSpells().Any(card => card.IsFacedown() && card.IsCode(CardId.BigWelcomeLabrynth)); + setWelcome |= Bot.GetMonsterCount() == 0 && !Bot.HasInHandOrInSpellZone(CardId.WelcomeLabrynth) + && (!Bot.HasInGraveyard(CardId.LabrynthCooclock) || activatedCardIdList.Contains(CardId.LabrynthCooclock + 1)) + && ((Duel.Player == 0 && Duel.Phase > DuelPhase.Main2) || !Bot.Hand.Any(card => card != Card && card.Level <= 4)); + if (setWelcome) + { + AI.SelectNextCard(CardId.WelcomeLabrynth); + } else { + AI.SelectNextCard(CardId.BigWelcomeLabrynth); + } + SelectSTPlace(null, true); + return true; + } + } + } + + return false; + } + + public ClientCard FurnitureGetCost(bool force = false, List ignoreList = null) + { + if (ignoreList == null) ignoreList = new List(); + // advance cost + List advancedCostIdList = new List{ + CardId.TransactionRollback, CardId.LovelyLabrynthOfTheSilverCastle, CardId.AriasTheLabrynthButler, CardId.LabrynthChandraglier, CardId.LabrynthStovieTorbie, + CardId.WelcomeLabrynth + }; + foreach (int checkId in advancedCostIdList) + { + ClientCard cost = Bot.Hand.FirstOrDefault(card => !ignoreList.Contains(card) && card.IsCode(checkId) && card != Card); + if (cost != null) return cost; + } + // dump cost + List canCostHand = Bot.Hand.Where(card => !ignoreList.Contains(card)).ToList(); + List appearedCode = new List(canCostHand.Count()); + foreach (ClientCard hand in canCostHand) + { + if (Duel.CurrentChain.Contains(hand)) continue; + if (appearedCode.Contains(hand.Id)) return hand; + appearedCode.Add(hand.Id); + } + List costIdList = new List{ + _CardId.InfiniteImpermanence, _CardId.DimensionalBarrier, CardId.UnchainedSoulOfSharvara, CardId.EscapeOfTheUnchained, CardId.DestructiveDarumaKarmaCannon, + CardId.LabrynthCooclock, CardId.ArianeTheLabrynthServant, CardId.WelcomeLabrynth, CardId.PotOfExtravagance, CardId.LadyLabrynthOfTheSilverCastle + }; + if (force) costIdList.AddRange(new List{CardId.AriannaTheLabrynthServant, _CardId.AshBlossom, CardId.BigWelcomeLabrynth, _CardId.MaxxC}); + foreach (int checkId in costIdList) + { + ClientCard target = canCostHand.FirstOrDefault(card => !Duel.CurrentChain.Contains(card) && card.IsCode(checkId) && !Duel.CurrentChain.Contains(card)); + if (target != null) return target; + } + foreach (int checkId in costIdList) + { + ClientCard target = canCostHand.FirstOrDefault(card => card.IsCode(checkId) && !Duel.CurrentChain.Contains(card)); + if (target != null) return target; + } + + return null; + } + + public bool ShouldSetBigWelcome(bool checkArianna = true) + { + if (CheckWhetherWillbeRemoved()) return false; + bool shouldTriggerBigWelcomeFlag = GetProblematicEnemyCardList(false).Count() > 0; + shouldTriggerBigWelcomeFlag |= Duel.Player == 1 && Duel.Phase > DuelPhase.Main2; + shouldTriggerBigWelcomeFlag |= Duel.Player == 1 && GetProblematicEnemyCardList(false).Count() == 0 && GetProblematicEnemyMonster(selfType: CardType.Monster) == null + && Enemy.Hand.Count() == 1; + if (checkArianna) shouldTriggerBigWelcomeFlag |= Duel.Player == 0 && !summoned && Bot.HasInHandOrHasInMonstersZone(CardId.AriannaTheLabrynthServant) + && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant); + shouldTriggerBigWelcomeFlag |= Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2; + return shouldTriggerBigWelcomeFlag; + } + + public bool LabrynthCooclockActivate() + { + if (Card.Location == CardLocation.Hand) + { + bool shouldTriggerBigWelcomeFlag = false; + if (Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) || CheckBigWelcomeCanSpSummon(CardId.LovelyLabrynthOfTheSilverCastle)) { + shouldTriggerBigWelcomeFlag |= ShouldSetBigWelcome(); + } + shouldTriggerBigWelcomeFlag &= !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth); + if (shouldTriggerBigWelcomeFlag && !Bot.GetSpells().Any(card => card.IsFacedown() && !setTrapThisTurn.Contains(card) && card.IsCode(CardId.BigWelcomeLabrynth))) + { + // whether have labrynth to trigger cooclock + bool haveBigWelcome = Duel.Player == 0 && Bot.HasInHand(CardId.BigWelcomeLabrynth) + && (Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth)) || (!summoned && Bot.Hand.Any(card => card != Card && card.HasType(CardType.Monster) && card.Level <= 4 && card.HasSetcode(SetcodeLabrynth)))); + if (CheckRemainInDeck(CardId.BigWelcomeLabrynth) > 0) + { + foreach (int checkId in new List { CardId.LabrynthChandraglier, CardId.LabrynthStovieTorbie }) + { + if (activatedCardIdList.Contains(checkId) || CheckCalledbytheGrave(checkId) > 0) continue; + if (Bot.HasInHand(checkId) && Bot.Hand.Count > 2 || Bot.GetMonsters().Any(card => card.IsFaceup() && !card.IsDisabled() && card.IsCode(checkId)) && Bot.Hand.Count > 1) + { + haveBigWelcome = true; + break; + } + } + } + if (haveBigWelcome) + { + activatedCardIdList.Add(Card.Id); + cooclockActivating = true; + return true; + } + } + + bool haveLabrynth = Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth)); + bool triggerFlag = Duel.Player == 1 && Duel.Phase <= DuelPhase.Main2 && setTrapThisTurn.Any(card => !activatedCardIdList.Contains(card.Id)) && haveLabrynth; + triggerFlag |= Duel.Player == 1 && activatedCardIdList.Contains(CardId.LadyLabrynthOfTheSilverCastle + 1) + && (Bot.GetSpells().Any(card => card.IsFacedown() && card.Type == (int)CardType.Trap) || Util.ChainContainsCard(CardId.LadyLabrynthOfTheSilverCastle)); + triggerFlag |= setTrapThisTurn.Any(card => card.IsFacedown() && card.IsCode(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth)) && haveLabrynth; + triggerFlag |= setTrapThisTurn.Any(card => card.IsFacedown() && card.IsCode(CardId.WelcomeLabrynth) && !activatedCardIdList.Contains(CardId.WelcomeLabrynth)) && haveLabrynth; + + if (triggerFlag) + { + activatedCardIdList.Add(Card.Id); + cooclockActivating = true; + return true; + } + } + + return false; + } + + public bool RecycleActivate() + { + if (Card.Location == CardLocation.Grave) + { + if (Card.IsCode(CardId.LabrynthStovieTorbie, CardId.AriasTheLabrynthButler)) + { + if (CheckShouldNoMoreSpSummon() || GetEmptyMainMonsterZoneCount() + chainSummoningIdList.Count() <= 0) return false; + chainSummoningIdList.Add(Card.Id); + } + if (Card.IsCode(CardId.WelcomeLabrynth)) SelectSTPlace(Card, false); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public bool ForLinkSummon() + { + if (Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained))) return false; + if (Card.Level > 4) return false; + if (CheckShouldNoMoreSpSummon()) return false; + if (!Bot.HasInExtra(CardId.UnchainedSoulLordOfYama)) return false; + + // check whether need summon for material count + List materialList = GetCanBeUsedForLinkMaterial(true, card => !card.HasRace(CardRace.Fiend)); + int materialCount = materialList.Count(); + if (!activatedCardIdList.Contains(CardId.UnchainedSoulOfSharvara) && Bot.GetSpells().Any(card => card.IsFacedown()) + && (!activatedCardIdList.Contains(CardId.UnchainedSoulLordOfYama) || Bot.HasInHand(CardId.UnchainedSoulOfSharvara))) materialCount++; + if (materialCount != 2) + { + if (materialCount != 1 || !materialList.Any(card => card.IsCode(CardId.UnchainedSoulLordOfYama))) return false; + } + + if (!Bot.HasInExtra(CardId.UnchainedSoulLordOfYama) && !materialList.Any(card => card.HasSetcode(SetcodeUnchained))) return false; + bool needSummon = false; + needSummon |= Enemy.GetMonsterCount() > 0 && Bot.HasInExtra(CardId.UnchainedSoulOfAnguish); + needSummon |= Bot.HasInExtra(CardId.UnchainedSoulOfRage); + if (needSummon) + { + // use monster with least attack + YGOSharp.OCGWrapper.NamedCard thisCardData = YGOSharp.OCGWrapper.NamedCard.Get(Card.Id); + if (thisCardData == null) return false; + if (thisCardData.Race != (int)CardRace.Fiend) return false; + foreach (ClientCard hand in Bot.Hand) + { + YGOSharp.OCGWrapper.NamedCard compareCardData = YGOSharp.OCGWrapper.NamedCard.Get(hand.Id); + if (compareCardData == null) continue; + if (!compareCardData.HasType(CardType.Monster) || compareCardData.Level > 4) continue; + if (compareCardData.Attack < thisCardData.Attack) return false; + } + summoned = true; + return true; + } + + return false; + } + public bool ForSynchroSummon() + { + if (Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained))) return false; + if (!Card.IsCode(new List { CardId.LabrynthStovieTorbie, CardId.ArianeTheLabrynthServant, CardId.AriannaTheLabrynthServant })) return false; + if (CheckShouldNoMoreSpSummon()) return false; + if (!Bot.HasInExtra(CardId.ChaosAngel) || dimensionalBarrierAnnouced.Contains(HintMsg.SYNCHRO)) return false; + + bool checkFlag = GetProblematicEnemyCardList(true, selfType: CardType.Monster).Count() > 0 && !CheckWhetherNegated(true, true, CardType.Monster); + if (Card.IsCode(CardId.LabrynthStovieTorbie)) + { + if (!Bot.GetMonsters().Any(card => card.IsFaceup() && !card.HasType(CardType.Xyz | CardType.Link) + && card.Level == 8 && card.HasAttribute(CardAttribute.Light | CardAttribute.Dark))) return false; + summoned = true; + return true; + } + else + { + if (!Bot.GetMonsters().Any(card => card.IsFaceup() && !card.HasType(CardType.Xyz | CardType.Link) + && card.Level == 6 && card.HasAttribute(CardAttribute.Light | CardAttribute.Dark))) return false; + summoned = true; + return true; + } + } + public bool ForAnimaSummon() + { + if (banSpSummonExceptFiendCount > 0 || !Bot.HasInExtra(CardId.RelinquishedAnima)) return false; + if (CheckWhetherNegated() || Duel.Turn == 1) return false; + + bool checkFlag = Bot.MonsterZone[1] == null && Enemy.MonsterZone[6] != null && Enemy.MonsterZone[6].HasType(CardType.Link) && Enemy.MonsterZone[6].HasLinkMarker(CardLinkMarker.Top); + checkFlag |= Bot.MonsterZone[3] == null && Enemy.MonsterZone[5] != null && Enemy.MonsterZone[5].HasType(CardType.Link) && Enemy.MonsterZone[5].HasLinkMarker(CardLinkMarker.Top); + if (Bot.GetMonstersExtraZoneCount() == 0) checkFlag |= Enemy.MonsterZone[1] != null || Enemy.MonsterZone[3] != null; + + return checkFlag; + } + + public bool LabrynthForCooClockSummon() + { + if (!cooclockAffected) return false; + if (Card.Level > 4 || !Card.HasSetcode(SetcodeLabrynth)) return false; + bool welcomeFlag = Bot.Hand.Any(card => (card.IsCode(CardId.WelcomeLabrynth) && !activatedCardIdList.Contains(CardId.WelcomeLabrynth)) + || (card.IsCode(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth))); + welcomeFlag |= Bot.GetSpells().Any(card => card.IsFacedown() && setTrapThisTurn.Contains(card) && ( + (card.IsCode(CardId.WelcomeLabrynth) && !activatedCardIdList.Contains(CardId.WelcomeLabrynth)) + || (card.IsCode(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth)))); + if (welcomeFlag && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth))) + { + // summon highest attack + int currentAttack = 0; + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(Card.Id); + if (cardData != null) currentAttack = cardData.Attack; + List summonList = Bot.Hand.Where(card => card.IsMonster() && card.Level <= 4 && card.HasSetcode(SetcodeLabrynth)).ToList(); + foreach (ClientCard checkCard in summonList) + { + cardData = YGOSharp.OCGWrapper.NamedCard.Get(checkCard.Id); + if (cardData != null && cardData.Attack < currentAttack) return false; + } + + return true; + } + return false; + } + + public bool ForBigWelcomeSummon() + { + if (Bot.HasInSpellZone(CardId.BigWelcomeLabrynth) && Bot.GetMonsterCount() == 0 && Card.Level <= 4) + { + summoned = true; + return true; + } + return false; + } + + public bool PotOfExtravaganceActivate() + { + if (CheckWhetherNegated()) return false; + SelectSTPlace(Card, true); + activatedCardIdList.Add(Card.Id); + AI.SelectOption(1); + return true; + } + + public bool WelcomeLabrynthActivate() + { + return WelcomeLabrynthActivateCheck(false); + } + public bool WelcomeLabrynthActivateCopy() + { + return WelcomeLabrynthActivateCheck(true); + } + public bool WelcomeLabrynthSetCheck() + { + return !CheckShouldNoMoreSpSummon() && WelcomeLabrynthActivateCheck(true, true); + } + public bool WelcomeLabrynthActivateCheck(bool onlyCheck = false, bool noSelect = false) + { + if (Card.Location == CardLocation.SpellZone || onlyCheck) + { + if (GetEmptyMainMonsterZoneCount() == 0) return false; + if (CheckShouldNoMoreSpSummon()) return false; + bool activateTimingFlag = Duel.Phase > DuelPhase.Main2 || (Card.IsCode(CardId.AriasTheLabrynthButler) && (CurrentTiming & hintTimingMainEnd) > 0); + + bool becomeTarget = Card.Location == CardLocation.SpellZone && DefaultOnBecomeTarget(); + if ((Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2 || Duel.Player == 1 && activateTimingFlag) + && CheckRemainInDeck(CardId.ArianeTheLabrynthServant) > 0 && Bot.HasInHandOrInSpellZone(CardId.TransactionRollback) + && !chainSummoningIdList.Contains(CardId.ArianeTheLabrynthServant)) + { + if (!noSelect) + { + chainSummoningIdList.Add(CardId.ArianeTheLabrynthServant); + activatedCardIdList.Add(Card.Id); + } + return true; + } + bool ariannaCheck = !Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth) + || !(Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) || CheckBigWelcomeCanSpSummon(CardId.LovelyLabrynthOfTheSilverCastle)); + ariannaCheck |= Duel.Player == 1 && activateTimingFlag; + ariannaCheck |= Duel.Player == 0; + if (ariannaCheck) + { + if (CheckRemainInDeck(CardId.AriannaTheLabrynthServant) > 0 && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) + && !CheckWhetherNegated(true, true, CardType.Monster) && !chainSummoningIdList.Contains(CardId.AriannaTheLabrynthServant)) + { + if (!noSelect) + { + chainSummoningIdList.Add(CardId.AriannaTheLabrynthServant); + activatedCardIdList.Add(Card.Id); + } + return true; + } + } + if (Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth)) + { + if (Bot.HasInHand(CardId.LovelyLabrynthOfTheSilverCastle) && CheckRemainInDeck(CardId.AriasTheLabrynthButler) > 0 + && !chainSummoningIdList.Contains(CardId.AriasTheLabrynthButler) && !Bot.HasInMonstersZone(CardId.AriasTheLabrynthButler, true, false, true)) + { + if (!noSelect) + { + chainSummoningIdList.Add(CardId.AriasTheLabrynthButler); + activatedCardIdList.Add(Card.Id); + } + return true; + } + } + + bool activateFlag = becomeTarget; + activateFlag |= Bot.UnderAttack && Bot.GetMonsterCount() == 0; + activateFlag |= ShouldSetBigWelcome(false); + if (activateFlag) + { + if (!noSelect) + { + if (Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) + && CheckRemainInDeck(CardId.LovelyLabrynthOfTheSilverCastle) > 0 && !chainSummoningIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle)) + { + chainSummoningIdList.Add(CardId.LovelyLabrynthOfTheSilverCastle); + } + else if (!activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && CheckRemainInDeck(CardId.AriannaTheLabrynthServant) > 0 + && !CheckWhetherNegated(true, true, CardType.Monster) && !chainSummoningIdList.Contains(CardId.AriannaTheLabrynthServant)) + { + chainSummoningIdList.Add(CardId.AriannaTheLabrynthServant); + } + else if (Bot.HasInGraveyard(CardId.BigWelcomeLabrynth) && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) + && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasRace(CardRace.Fiend) && card.Level >= 8) + && CheckRemainInDeck(CardId.LadyLabrynthOfTheSilverCastle) > 0 && !chainSummoningIdList.Contains(CardId.LadyLabrynthOfTheSilverCastle)) + { + chainSummoningIdList.Add(CardId.LadyLabrynthOfTheSilverCastle); + } + else { + int selectId = 0; + List checkIdList = new List{CardId.LabrynthStovieTorbie, CardId.LabrynthChandraglier, CardId.LabrynthCooclock}; + foreach (int checkId in checkIdList) + { + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(checkId) && CheckRemainInDeck(checkId) > 0 + && !chainSummoningIdList.Contains(checkId)) + { + selectId = checkId; + break; + } + } + List fullCheckIdList = new List{ + CardId.LadyLabrynthOfTheSilverCastle, CardId.LabrynthStovieTorbie, CardId.LabrynthChandraglier, CardId.LabrynthCooclock, + CardId.AriasTheLabrynthButler, CardId.ArianeTheLabrynthServant, CardId.AriannaTheLabrynthServant + }; + if (selectId == 0) + { + foreach (int checkId in fullCheckIdList) + { + if (CheckRemainInDeck(checkId) > 0 && !chainSummoningIdList.Contains(checkId)) + { + selectId = checkId; + break; + } + } + } + if (selectId > 0) { + chainSummoningIdList.Add(selectId); + } + } + ResetCooclockEffect(onlyCheck); + + activatedCardIdList.Add(Card.Id); + } + return true; + } + + } + + return false; + } + + public bool TransactionRollbackActivate() + { + if (Card.Location == CardLocation.Grave) + { + SortedList> checkList = new SortedList> { + {CardId.BigWelcomeLabrynth, BigWelcomeLabrynthActivateCopy}, + {_CardId.DimensionalBarrier, DimensionalBarrierActivate}, + {CardId.EscapeOfTheUnchained, EscapeOfTheUnchainedActivateCopy}, + {_CardId.InfiniteImpermanence, InfiniteImpermanenceActivateCopy}, + {CardId.WelcomeLabrynth, WelcomeLabrynthActivateCopy}, + {CardId.DestructiveDarumaKarmaCannon, DestructiveDarumaKarmaCannonActivate} + }; + foreach (KeyValuePair> pair in checkList) + { + if (Bot.HasInGraveyard(pair.Key) && pair.Value()) + { + rollbackCopyCardId = pair.Key; + AI.SelectCard(pair.Key); + return true; + } + } + } + if (Card.Location == CardLocation.SpellZone) + { + if (CheckWhetherNegated()) return false; + SortedList> checkList = new SortedList> { + {CardId.WelcomeLabrynth, WelcomeLabrynthActivateCopy}, + {_CardId.CompulsoryEvacuationDevice, DefaultCompulsoryEvacuationDevice }, + {CardId.DestructiveDarumaKarmaCannon, DestructiveDarumaKarmaCannonActivate}, + {_CardId.DimensionalBarrier, DimensionalBarrierActivate}, + {CardId.EscapeOfTheUnchained, EscapeOfTheUnchainedActivateCopy}, + {_CardId.InfiniteImpermanence, InfiniteImpermanenceActivateCopy}, + {_CardId.BreakthroughSkill, DefaultBreakthroughSkill}, + {CardId.BigWelcomeLabrynth, BigWelcomeLabrynthActivateCopy} + }; + foreach (KeyValuePair> pair in checkList) + { + if (Enemy.HasInGraveyard(pair.Key) && pair.Value()) + { + rollbackCopyCardId = pair.Key; + AI.SelectCard(pair.Key); + ResetCooclockEffect(false); + return true; + } + } + } + return false; + } + + public bool InfiniteImpermanenceActivate() + { + return InfiniteImpermanenceActivateCheck(false); + } + public bool InfiniteImpermanenceActivateCopy() + { + return InfiniteImpermanenceActivateCheck(true); + } + public bool InfiniteImpermanenceSetCheck() + { + return InfiniteImpermanenceActivateCheck(true, true); + } + public bool InfiniteImpermanenceActivateCheck(bool onlyCheck = false, bool noSelect = false) + { + if (CheckWhetherNegated()) return false; + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int thisSeq = -1; + int thatSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) thisSeq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) thatSeq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) thatSeq = i; + } + if ( (thisSeq * thatSeq >= 0 && thisSeq + thatSeq == 4) + || Util.IsChainTarget(Card) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true, selfType: CardType.Trap); + if (!noSelect) + { + if (target != null) + { + AI.SelectCard(target); + } else { + AI.SelectCard(Enemy.GetMonsters()); + } + } + if (!onlyCheck) + { + infiniteImpermanenceList.Add(thatSeq); + if (cooclockAffected && setTrapThisTurn.Contains(Card)) + { + cooclockAffected = false; + setTrapThisTurn.Remove(Card); + } + } + return true; + } + } + + // negate monster + List shouldNegateList = GetMonsterListForTargetNegate(true, CardType.Trap); + if (shouldNegateList.Count() > 0) + { + ClientCard negateTarget = shouldNegateList[0]; + currentNegateMonsterList.Add(negateTarget); + + if (Card.Location == CardLocation.SpellZone && !onlyCheck) + { + for (int i = 0; i < 5; ++ i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + if (!noSelect) AI.SelectCard(negateTarget); + currentDestroyCardList.Add(negateTarget); + ResetCooclockEffect(onlyCheck); + return true; + } + + return false; + } + + public bool DestructiveDarumaKarmaCannonActivate() + { + return DestructiveDarumaKarmaCannonActivateCheck(false); + } + public bool DestructiveDarumaKarmaCannonSetCheck() + { + return DestructiveDarumaKarmaCannonActivateCheck(true); + } + public bool DestructiveDarumaKarmaCannonActivateCheck(bool noSelect = false) + { + bool becomeTarget = Card.Location == CardLocation.SpellZone && DefaultOnBecomeTarget(); + bool activateFlag = becomeTarget && Util.IsOneEnemyBetter(true); + bool canTriggerLovely = + (!activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) && Bot.GetSpells().Any(card => card.IsFacedown() && card.IsCode(CardId.BigWelcomeLabrynth) && (!cooclockAffected || !setTrapThisTurn.Contains(card))) + || Util.ChainContainsCard(CardId.BigWelcomeLabrynth)) + && (Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) || (CheckBigWelcomeCanSpSummon(CardId.LovelyLabrynthOfTheSilverCastle) && Bot.GetMonsterCount() > 0)) + && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1); + + activateFlag |= Bot.UnderAttack && (Bot.BattlingMonster?.GetDefensePower() ?? 0) <= (Enemy.BattlingMonster?.GetDefensePower() ?? 0) && !Util.ChainContainPlayer(0) && !canTriggerLovely; + activateFlag |= Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2 && Bot.GetMonsterCount() == 0 && Enemy.GetMonsterCount() > 0; + activateFlag |= Enemy.HasInMonstersZone(CardId.AccesscodeTalker, true) && !Util.ChainContainPlayer(0); + int linkCount = 0; + foreach (ClientCard monster in Enemy.GetMonsters()) + { + if (monster.IsFacedown()) continue; + if (!monster.HasType(CardType.Link)) linkCount++; + else linkCount += monster.LinkCount; + } + activateFlag |= linkCount >= 6 && Util.IsOneEnemyBetter(true); + if (activateFlag) + { + if (!noSelect) + { + currentDestroyCardList.AddRange(Enemy.GetMonsters()); + escapeTargetList.AddRange(Bot.GetMonsters()); + } + return true; + } + + return false; + } + + public bool EscapeOfTheUnchainedActivate() + { + return EscapeOfTheUnchainedActivateCheck(false); + } + public bool EscapeOfTheUnchainedActivateCopy() + { + return EscapeOfTheUnchainedActivateCheck(true); + } + public bool EscapeOfTheUnchainedActivateCheck(bool onlyCheck = false, bool noSelect = false) + { + if (Card.Location == CardLocation.SpellZone || onlyCheck) + { + // select targeted unchained + ClientCard selfTarget = Bot.GetMonsters().FirstOrDefault(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained) + && Duel.ChainTargets.Contains(card) && !escapeTargetList.Contains(card)); + if (selfTarget == null) + { + selfTarget = Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained)) + .OrderBy(card => card.Attack).FirstOrDefault(); + } + if (selfTarget == null) return false; + // destroy danger card + List dangerList = GetProblematicEnemyCardList(true, selfType: CardType.Trap); + if (dangerList.Count() > 0 && Duel.LastChainPlayer != 0) + { + if (!noSelect) + { + AI.SelectCard(selfTarget); + AI.SelectNextCard(dangerList); + escapeTargetList.Add(selfTarget); + currentDestroyCardList.Add(dangerList[0]); + activatedCardIdList.Add(Card.Id); + } + return true; + } + + // best monster + int botBestPower = Util.GetBestPower(Bot); + if (Duel.Player == 1 && Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + List dangerMonsters = Enemy.GetMonsters().Where(card => card.IsFaceup() && card.Attack >= botBestPower + && !currentDestroyCardList.Contains(card) && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + .OrderByDescending(card => card.Attack).ToList(); + if (dangerMonsters.Count() > 0) + { + if (!noSelect) + { + AI.SelectCard(selfTarget); + AI.SelectNextCard(dangerMonsters); + escapeTargetList.Add(selfTarget); + currentDestroyCardList.Add(dangerMonsters[0]); + activatedCardIdList.Add(Card.Id); + } + return true; + } + } + + // end phase + bool activateFlag = Duel.Player == 1 && Duel.Phase > DuelPhase.Main2 + && ((Bot.HasInGraveyard(CardId.UnchainedSoulLordOfYama) && !activatedCardIdList.Contains(CardId.UnchainedSoulLordOfYama + 1)) + || (Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1))); + activateFlag |= DefaultOnBecomeTarget() && Card.Location == CardLocation.SpellZone && !Util.ChainContainsCard(_CardId.EvenlyMatched); + if (activateFlag) + { + List destroyTarget = GetNormalEnemyTargetList(true, true, CardType.Trap); + if (destroyTarget.Count() > 0) + { + if (!noSelect) + { + AI.SelectCard(selfTarget); + AI.SelectNextCard(destroyTarget); + escapeTargetList.Add(selfTarget); + currentDestroyCardList.Add(destroyTarget[0]); + activatedCardIdList.Add(Card.Id); + } + return true; + } + } + + } else { + if (!noSelect) + { + AI.SelectCard(CardId.UnchainedSoulOfSharvara); + activatedCardIdList.Add(Card.Id + 1); + } + return true; + } + + return false; + } + + public bool DimensionalBarrierActivate() + { + if (Duel.Player == 0 && Duel.Turn == 1) return false; + if (CheckWhetherNegated()) return false; + Dictionary> checkDict = new Dictionary> + { + {HintMsg.RITUAL, DimensionalBarrierForRitual}, + {HintMsg.FUSION, DimensionalBarrierForFusion}, + {HintMsg.SYNCHRO, DimensionalBarrierForSynchro}, + {HintMsg.XYZ, DimensionalBarrierForXyz}, + {HintMsg.PENDULUM, DimensionalBarrierForPendulum}, + }; + foreach (KeyValuePair> checkType in checkDict) + { + if (dimensionalBarrierAnnouced.Contains(checkType.Key)) continue; + if (checkType.Value()) { + ResetCooclockEffect(false); + return true; + } + } + + return DefaultOnBecomeTarget(); + } + public bool DimensionalBarrierForRitual() + { + foreach (ClientCard chainCard in Duel.CurrentChain) + { + if (chainCard != null && chainCard.Controller == 1 && !chainCard.IsDisabled() && chainCard.HasType(CardType.Ritual) + && (chainCard.HasType(CardType.Spell) || (chainCard.Location == CardLocation.MonsterZone && !currentNegateMonsterList.Contains(chainCard)))) + { + if (dimensionBarrierAnnouncing) currentNegateMonsterList.Add(chainCard); + return true; + } + } + + return false; + } + public bool DimensionalBarrierForFusion() + { + foreach (ClientCard chainCard in Duel.CurrentChain) + { + if (chainCard != null && chainCard.Controller == 1 && !chainCard.IsDisabled() && (chainCard.IsFusionSpell() + || (chainCard.HasType(CardType.Fusion) && chainCard.Location == CardLocation.MonsterZone && !currentNegateMonsterList.Contains(chainCard)))) + { + if (dimensionBarrierAnnouncing) currentNegateMonsterList.Add(chainCard); + return true; + } + } + + return false; + } + public bool DimensionalBarrierForSynchro() + { + foreach (ClientCard chainCard in Duel.CurrentChain) + { + if (chainCard != null && chainCard.Controller == 1 && !chainCard.IsDisabled() + && chainCard.HasType(CardType.Synchro) && chainCard.Location == CardLocation.MonsterZone && !currentNegateMonsterList.Contains(chainCard)) + { + if (dimensionBarrierAnnouncing) currentNegateMonsterList.Add(chainCard); + return true; + } + } + if (Duel.Player == 1 && !Util.ChainContainsCard(CardId.DestructiveDarumaKarmaCannon) && Enemy.ExtraDeck.Count() > 0) + { + bool tunerCheck = false; + bool nontunerCheck = false; + foreach (ClientCard monster in Enemy.GetMonsters()) + { + if (monster.IsFacedown() || monster.HasType(CardType.Xyz | CardType.Link)) continue; + if (monster.HasType(CardType.Tuner)) tunerCheck = true; + else nontunerCheck = true; + } + if (tunerCheck && nontunerCheck) return true; + } + + return false; + } + public bool DimensionalBarrierForXyz() + { + foreach (ClientCard chainCard in Duel.CurrentChain) + { + if (chainCard != null && chainCard.Controller == 1 && !chainCard.IsDisabled() + && chainCard.HasType(CardType.Xyz) && chainCard.Location == CardLocation.MonsterZone && !currentNegateMonsterList.Contains(chainCard)) + { + if (dimensionBarrierAnnouncing) currentNegateMonsterList.Add(chainCard); + return true; + } + } + if (Duel.Player == 1 && !Util.ChainContainsCard(CardId.DestructiveDarumaKarmaCannon) && Enemy.ExtraDeck.Count() > 0) + { + List existsLevel = new List(6); + foreach (ClientCard monster in Enemy.GetMonsters()) + { + if (monster.IsFacedown()) continue; + if (monster.IsOneForXyz()) return true; + if (monster.HasType(CardType.Xyz | CardType.Token)) continue; + int level = monster.Level; + if (level != 2 && monster.HasType(CardType.Link)) continue; + if (existsLevel.Contains(level)) return true; + existsLevel.Add(level); + } + } + + return false; + } + public bool DimensionalBarrierForPendulum() + { + foreach (ClientCard chainCard in Duel.CurrentChain) + { + if (chainCard != null && chainCard.Controller == 1 && !chainCard.IsDisabled() + && chainCard.HasType(CardType.Pendulum) && chainCard.Location == CardLocation.MonsterZone && !currentNegateMonsterList.Contains(chainCard)) + { + if (dimensionBarrierAnnouncing) currentNegateMonsterList.Add(chainCard); + return true; + } + } + + ClientCard l = Enemy.SpellZone[6]; + ClientCard r = Enemy.SpellZone[7]; + if (l != null && r != null && l.LScale != r.RScale) return true; + + return false; + } + + public bool BigWelcomeLabrynthActivate() + { + return BigWelcomeLabrynthActivateCheck(false); + } + public bool BigWelcomeLabrynthBecomeTargetActivate() + { + if (DefaultOnBecomeTarget()) return BigWelcomeLabrynthActivateCheck(false); + return false; + } + public bool BigWelcomeLabrynthActivateCopy() + { + return BigWelcomeLabrynthActivateCheck(true); + } + public bool BigWelcomeLabrynthSetCheck() + { + return !CheckShouldNoMoreSpSummon() && BigWelcomeLabrynthActivateCheck(true, true); + } + public bool BigWelcomeLabrynthActivateCheck(bool onlyCheck = false, bool noSelect = false) + { + if (CheckWhetherNegated()) return false; + if (Card.Location != CardLocation.SpellZone && !onlyCheck) return false; + if (GetEmptyMainMonsterZoneCount() == 0) return false; + bool activateTimingFlag = Duel.Phase > DuelPhase.Main2 || (Card.IsCode(CardId.AriasTheLabrynthButler) && (CurrentTiming & hintTimingMainEnd) > 0); + + bool needDestroyFlag = GetProblematicEnemyCardList(false).Count() > 0; + needDestroyFlag |= activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && activateTimingFlag; + needDestroyFlag |= Bot.UnderAttack && (Bot.BattlingMonster?.GetDefensePower() ?? 0) <= (Enemy.BattlingMonster?.GetDefensePower() ?? 0) && Duel.LastChainPlayer != 0; + needDestroyFlag |= Duel.Turn == 1 && Duel.Player == 0 && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1); + needDestroyFlag |= Duel.Turn == 1 && Enemy.GetMonsterCount() == 0 && Enemy.GetSpellCount() == 0 && Enemy.Hand.Count > 0 + && (CurrentTiming & hintTimingMainEnd) > 0; + + // do not activate when welcome is activating + bool haveEnemyChain = false; + bool haveWelcome = false; + foreach (ClientCard chain in Duel.CurrentChain) + { + if (chain != null) + { + if (chain.Controller == 1) + { + haveEnemyChain = true; + break; + } + if (chain.IsCode(CardId.WelcomeLabrynth, CardId.TransactionRollback, CardId.LadyLabrynthOfTheSilverCastle)) haveWelcome = true; + } + } + if (haveWelcome && !haveEnemyChain) return false; + + // escape target + List targetList = Bot.GetMonsters(); + foreach (ClientCard target in targetList) + { + if (Duel.ChainTargets.Contains(target) && !escapeTargetList.Contains(target) + && !(target.IsCode(CardId.UnchainedSoulOfRage, CardId.UnchainedSoulOfAnguish) && Duel.CurrentChain.Contains(target))) + { + Logger.DebugWriteLine("[BigWelcome]escape target"); + if (!noSelect) + { + bigwelcomeEscaseTarget = target; + escapeTargetList.Add(target); + activatedCardIdList.Add(Card.Id); + } + return true; + } + } + + if (Bot.GetMonsterCount() > 0) + { + bool flag1 = needDestroyFlag && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1) && (Util.ChainContainPlayer(1) || Duel.LastChainPlayer != 0); + bool flag2 = DefaultOnBecomeTarget(); + bool flag3 = Duel.Player == 1 && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) && activateTimingFlag; + bool flag4 = Duel.Player == 0 && Duel.LastChainPlayer != 0 && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth); + Logger.DebugWriteLine("[BigWelcome count>0]flag: "+ flag1 + " " + flag2 + " " + flag3 + " " + flag4); + needDestroyFlag |= flag3; + if (flag1 || flag2 || flag3 || flag4) + { + bool spSummonLovely = CheckBigWelcomeCanSpSummon(CardId.LovelyLabrynthOfTheSilverCastle) && !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1); + bool haveLovely = Bot.GetMonsters().Any(card => card.IsFaceup() && card.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)); + if (!noSelect) + { + activatedCardIdList.Add(Card.Id); + } + ResetCooclockEffect(onlyCheck); + return true; + } + } + else { + bool activateFlag = DefaultOnBecomeTarget(); + activateFlag |= Duel.Player == 1 && !activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) && activateTimingFlag; + activateFlag |= Duel.Player == 0 && !summoned && !Bot.HasInHand(CardId.AriannaTheLabrynthServant) && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) + && !(Duel.Phase < DuelPhase.Main1 && Bot.HasInHand(CardId.PotOfExtravagance) && Bot.ExtraDeck.Count() >= 3) + && !(Duel.CurrentChain.Any(card => card.IsCode(CardId.PotOfExtravagance) && card.Controller == 0)); + if (activateFlag && !noSelect) + { + activatedCardIdList.Add(Card.Id); + ResetCooclockEffect(onlyCheck); + return true; + } + } + + return false; + } + + public bool BigWelcomeLabrynthGraveActivate() + { + if (Card.Location == CardLocation.Grave) + { + // bounce enemy + if (Bot.GetMonsters().Any(card => card.Level >= 8 && card.IsFaceup() && card.HasRace(CardRace.Fiend) && !card.HasType(CardType.Xyz | CardType.Link))) + { + // danger monster + ClientCard problemCard = GetProblematicEnemyMonster(-1, true, true, CardType.Trap); + if (problemCard != null) + { + AI.SelectCard(problemCard); + currentDestroyCardList.Add(problemCard); + activatedCardIdList.Add(Card.Id); + return true; + } + // problem spell + if (!Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) || + activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle) && activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle + 1)) + { + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && c.IsFaceup() + && c.IsFloodgate() + && !c.IsShouldNotBeTarget() && (c.HasType(CardType.Trap) || Duel.Player == 0)).ToList(); + + problemEnemySpellList.AddRange(Enemy.SpellZone.Where(c => c?.Data != null && c.IsFaceup() && !problemEnemySpellList.Contains(c) + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous) + && !c.IsShouldNotBeTarget() && (c.HasType(CardType.Trap) || Duel.Player == 0)).ToList()); + + if (problemEnemySpellList.Count() > 0) + { + AI.SelectCard(problemEnemySpellList); + currentDestroyCardList.Add(problemEnemySpellList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + // best monster + int botBestPower = Util.GetBestPower(Bot); + if (Duel.Player == 1 && Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + List dangerMonsters = Enemy.GetMonsters().Where(card => card.IsFaceup() && card.Attack >= botBestPower + && !currentDestroyCardList.Contains(card) && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + .OrderByDescending(card => card.Attack).ToList(); + if (dangerMonsters.Count() > 0) + { + AI.SelectCard(dangerMonsters); + currentDestroyCardList.Add(dangerMonsters[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + // end phase + if (Duel.Phase > DuelPhase.Main2) + { + List returnList = GetNormalEnemyTargetList(true, true, CardType.Trap); + if (returnList.Count() > 0) + { + AI.SelectCard(returnList); + currentDestroyCardList.Add(returnList[0]); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + + // escape target + List targetList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasRace(CardRace.Fiend)).ToList(); + foreach (ClientCard target in targetList) + { + if (Duel.ChainTargets.Contains(target) && !escapeTargetList.Contains(target) + && !(target.IsCode(CardId.UnchainedSoulOfRage, CardId.UnchainedSoulOfAnguish) && Duel.CurrentChain.Contains(target))) + { + AI.SelectCard(target); + escapeTargetList.Add(target); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + // bounce arianna + if (Duel.Player == 0 && Duel.Phase <= DuelPhase.Main2 && !summoned && !Bot.HasInHand(CardId.AriannaTheLabrynthServant) + && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant) && !chainSummoningIdList.Contains(CardId.AriannaTheLabrynthServant)) + { + ClientCard target = targetList.FirstOrDefault(card => card.IsCode(CardId.AriannaTheLabrynthServant)); + if (target != null) + { + AI.SelectCard(target); + escapeTargetList.Add(target); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + // trigger furniture/welcome + List checkFurnitureList = new List(Bot.Hand); + checkFurnitureList.AddRange(Bot.GetMonsters()); + if ((CheckRemainInDeck(CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth) == 0 + || !checkFurnitureList.Any(card => card.IsCode(CardId.LabrynthChandraglier, CardId.LabrynthStovieTorbie))) + && Duel.LastChainPlayer < 0 && Duel.Player == 0 && !Bot.HasInMonstersZone(CardId.LovelyLabrynthOfTheSilverCastle, true, false, true) + && !(cooclockAffected && Bot.HasInHandOrInSpellZone(CardId.BigWelcomeLabrynth))) + { + int checkCount = 0; + List checkIdList = new List { CardId.LabrynthChandraglier, CardId.LabrynthStovieTorbie, CardId.WelcomeLabrynth }; + foreach (int checkId in checkIdList) + { + if (Bot.HasInGraveyard(checkId) && !activatedCardIdList.Contains(checkId + 1)) checkCount++; + } + if (checkCount > 0) + { + ClientCard target = targetList.FirstOrDefault(card => card.IsFaceup() && card.HasRace(CardRace.Fiend) && + ((card.Level <= 4 && !card.HasType(CardType.Link | CardType.Xyz | CardType.Synchro)) || card.IsCode(CardId.LadyLabrynthOfTheSilverCastle))); + if (target != null) + { + AI.SelectCard(target); + escapeTargetList.Add(target); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + } + + return false; + } + + public bool ChaosAngelSpSummonWith2Monster() + { + if (CheckShouldNoMoreSpSummon(false)) return false; + + List level2MonsterList = new List(); + List level4MonsterList = new List(); + List level6MonsterList = new List(); + List level8MonsterList = new List(); + foreach (ClientCard monster in Bot.GetMonsters()) + { + if (monster.IsFaceup() && !monster.HasType(CardType.Xyz | CardType.Link) && monster.HasAttribute(CardAttribute.Light | CardAttribute.Dark)) + { + if (monster.Level == 2) level2MonsterList.Add(monster); + if (monster.Level == 4) level4MonsterList.Add(monster); + if (monster.Level == 6) level6MonsterList.Add(monster); + if (monster.Level == 8) level8MonsterList.Add(monster); + } + } + level2MonsterList.Sort(CompareUsableAttack); + level4MonsterList.Sort(CompareUsableAttack); + level6MonsterList.Sort(CompareUsableAttack); + level8MonsterList.Sort(CompareUsableAttack); + bool checkFlag = GetProblematicEnemyCardList(true, selfType: CardType.Monster).Count() > 0 && !CheckWhetherNegated(true, true, CardType.Monster); + ClientCard BestEnemyMonster = Util.GetBestEnemyMonster(); + if (BestEnemyMonster != null && Util.GetBestPower(Bot, true) <= Util.GetBestPower(Enemy)) + { + checkFlag |= Util.GetBestPower(Enemy) <= 3500; + checkFlag |= !BestEnemyMonster.IsShouldNotBeTarget() && !BestEnemyMonster.IsShouldNotBeMonsterTarget(); + } + // 4+6 + if (level4MonsterList.Count() > 0 && level6MonsterList.Count() > 0) + { + List materials = new List{level4MonsterList[0], level6MonsterList[0]}; + bool summonFlag = checkFlag; + if (Enemy.GetMonsterCount() == 0 && Duel.Phase < DuelPhase.Main2) + summonFlag |= GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack(materials) + 3500 >= Enemy.LifePoints; + if (summonFlag) + { + AI.SelectMaterials(materials); + return true; + } + } + // 2+8 + if (level2MonsterList.Count() > 0 && level8MonsterList.Count() > 0) + { + foreach (ClientCard level2 in level2MonsterList) + { + foreach (ClientCard level8 in level8MonsterList) + { + List materials = new List{level2, level8}; + if (checkFlag && !(level8.IsCode(CardId.LovelyLabrynthOfTheSilverCastle) && !level8.IsDisabled() && Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth))) + { + AI.SelectMaterials(materials); + return true; + } + if (Enemy.GetMonsterCount() == 0 && GetMaterialAttack(materials) < 3500 && Duel.Phase < DuelPhase.Main2) + { + if (GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack(materials) + 3500 >= Enemy.LifePoints) + { + AI.SelectMaterials(materials); + return true; + } + } + } + } + } + return false; + } + public bool ChaosAngelSpSummonWith3Monster() + { + if (CheckShouldNoMoreSpSummon(false)) return false; + + List level2MonsterList = new List(); + List level4MonsterList = new List(); + foreach (ClientCard monster in Bot.GetMonsters()) + { + if (monster.IsFaceup() && !monster.HasType(CardType.Xyz | CardType.Link) && monster.HasAttribute(CardAttribute.Light | CardAttribute.Dark)) + { + if (monster.Level == 2) level2MonsterList.Add(monster); + if (monster.Level == 4) level4MonsterList.Add(monster); + } + } + level2MonsterList.Sort(CompareUsableAttack); + level4MonsterList.Sort(CompareUsableAttack); + bool checkFlag = GetProblematicEnemyCardList(true, selfType: CardType.Monster).Count() > 0 && !CheckWhetherNegated(true, true, CardType.Monster); + ClientCard BestEnemyMonster = Util.GetBestEnemyMonster(); + if (BestEnemyMonster != null && Util.GetBestPower(Bot, true) <= Util.GetBestPower(Enemy)) + { + checkFlag |= Util.GetBestPower(Enemy) <= 3500; + checkFlag |= !BestEnemyMonster.IsShouldNotBeTarget() && !BestEnemyMonster.IsShouldNotBeMonsterTarget(); + } + // 2+4+4 + if (level2MonsterList.Count() >= 1 && level4MonsterList.Count() >= 2) + { + foreach (ClientCard level2 in level2MonsterList) + { + for (int level4Index1 = 0; level4Index1 < level4MonsterList.Count() - 1; ++level4Index1) + { + ClientCard level41 = level4MonsterList[level4Index1]; + for (int level4Index2 = level4Index1 + 1; level4Index2 < level4MonsterList.Count(); ++level4Index2) + { + ClientCard level42 = level4MonsterList[level4Index2]; + List materials = new List { level2, level41, level42 }; + bool summonFlag = checkFlag; + if (Enemy.GetMonsterCount() == 0 && Duel.Phase < DuelPhase.Main2) + summonFlag |= GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack(materials) + 3500 >= Enemy.LifePoints; + if (summonFlag) + { + AI.SelectMaterials(materials); + return true; + } + } + } + } + } + return false; + } + public bool ChaosAngelActivate() + { + List targetList = GetNormalEnemyTargetList(true, true, CardType.Monster); + if (targetList.Count() > 0) + { + AI.SelectCard(targetList); + currentDestroyCardList.Add(targetList[0]); + return true; + } + + return false; + } + + public bool SummonForTYPHONCheck() + { + if (!Bot.HasInExtra(CardId.SuperStarslayerTYPHON) || Bot.GetMonsters().Any(card => card.IsFaceup())) return false; + if (enemySpSummonFromExLastTurn < 2 && enemySpSummonFromExThisTurn < 2) return false; + if (Card.Level > 4) return false; + + int currentAttack = 0; + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(Card.Id); + if (cardData != null) currentAttack = cardData.Attack; + List summonList = Bot.Hand.Where(card => card.IsMonster() && card.Level <= 4).ToList(); + foreach (ClientCard checkCard in summonList) + { + cardData = YGOSharp.OCGWrapper.NamedCard.Get(checkCard.Id); + if (cardData != null && cardData.Attack < currentAttack) return false; + } + + return true; + } + public bool SuperStarslayerTYPHONSpSummon() + { + ClientCard material = Bot.GetMonsters().Where(card => card.IsFaceup()).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (material == null || (material.Attack >= 2900 && material.Owner == 0)) return false; + + bool checkFlag = GetProblematicEnemyMonster(material.Attack) != null; + checkFlag |= material.Level <= 4; + checkFlag &= !(material.HasType(CardType.Link) && Duel.Phase >= DuelPhase.Main2); + if (checkFlag) + { + Logger.DebugWriteLine("*** TYPHON select: " + material.Name ?? "UnkonwCard"); + AI.SelectMaterials(material); + return true; + } + + return false; + } + public bool SuperStarslayerTYPHONActivate() + { + if (CheckWhetherNegated()) return false; + List targetList = new List(); + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.IsFloodgate() && c.IsFaceup()).OrderByDescending(card => card.Attack)); + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.IsMonsterDangerous() && c.IsFaceup()).OrderByDescending(card => card.Attack)); + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.IsMonsterInvincible() && c.IsFaceup()).OrderByDescending(card => card.Attack)); + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.GetDefensePower() >= Util.GetBestAttack(Bot) && c.IsAttack()).OrderByDescending(card => card.Attack)); + if (Duel.Phase >= DuelPhase.Main2) + targetList.AddRange(Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c) && + c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link | CardType.SpSummon)).OrderByDescending(card => card.Attack)); + + if (targetList.Count() > 0) + { + targetList.AddRange(Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card)).OrderByDescending(card => card.Attack)); + targetList.AddRange(ShuffleList(Enemy.GetMonsters().Where(card => card.IsFacedown() && !targetList.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Bot.GetMonsters().Where(card => card.IsFacedown() && !targetList.Contains(card)).ToList())); + targetList.AddRange(Bot.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card)).OrderBy(card => card.Attack)); + AI.SelectCard(Card.Overlays); + Logger.DebugWriteLine("TYPHON first target: " + targetList[0]?.Name ?? "UNKNOWN"); + AI.SelectNextCard(targetList); + return true; + } + + return false; + } + + public bool UnchainedAbominationSpSummon() + { + if (CheckShouldNoMoreSpSummon(false)) return false; + if (Enemy.GetMonsterCount() > 0 && Bot.HasInMonstersZone(CardId.UnchainedSoulOfAnguish) && !activatedCardIdList.Contains(CardId.UnchainedSoulOfAnguish)) return false; + List> usableMaterialMultiList = new List>(); + // anguish + 1 + ClientCard anguish = Bot.GetMonsters().FirstOrDefault(card => card.IsCode(CardId.UnchainedSoulOfAnguish)); + if (anguish != null) + { + List materials = GetCanBeUsedForLinkMaterial(true, card => card == anguish); + if (materials.Count() > 0) + { + usableMaterialMultiList.Add(new List { anguish, materials[0] }); + } + } + // link2 + 1 + 1 or link2 + link2 + List link2List = Bot.GetMonsters().Where(card => card.HasType(CardType.Link) && card.LinkCount == 2 + && !(card.IsCode(CardId.MuckrakerFromTheUnderworld) && summonThisTurn.Contains(card))).OrderBy(card => card.Attack).ToList(); + if (link2List.Count() > 0) + { + ClientCard link2Material = null; + ClientCard littleKnight = link2List.FirstOrDefault(card => card.Sequence >= 5 && card.IsCode(CardId.SPLittleKnight)); + if (littleKnight != null) link2Material = littleKnight; + else link2Material = link2List[0]; + if (link2List.Count() >= 2) + { + usableMaterialMultiList.Add(new List { link2Material, link2List.FirstOrDefault(card => card != link2Material) }); + } + List remainList = GetCanBeUsedForLinkMaterial(false, card => card != link2Material && !(card.HasType(CardType.Link) && card.LinkMarker > 2)); + if (remainList.Count() >= 2) + { + usableMaterialMultiList.Add(new List { link2Material, remainList[0], remainList[1] }); + } + } + + // check material list + foreach (List currMaterials in usableMaterialMultiList) + { + bool summonFlag = CheckCanDirectAttack() && GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack(currMaterials) + 3000 >= Enemy.LifePoints; + summonFlag |= GetProblematicEnemyMonster(0) != null && GetProblematicEnemyMonster(3000) == null; + + if (summonFlag) + { + AI.SelectMaterials(currMaterials); + return true; + } + } + + return false; + } + public bool UnchainedAbominationActivate() + { + if (CheckWhetherNegated()) return false; + List targetList = GetNormalEnemyTargetList(true, true, CardType.Monster); + if (targetList.Count() == 0) return false; + int logDesc = ActivateDescription; + if (logDesc >= Util.GetStringId(CardId.UnchainedAbomination, 0)) + { + logDesc = Util.GetStringId(CardId.UnchainedAbomination, 0) - 10; + } + Logger.DebugWriteLine("[UnchainedAbomination]desc: " + logDesc + ", timing = " + CurrentTiming); + if (ActivateDescription == Util.GetStringId(CardId.UnchainedAbomination, 0)) activatedCardIdList.Add(Card.Id); + if (ActivateDescription == Util.GetStringId(CardId.UnchainedAbomination, 1) || ActivateDescription == -1) activatedCardIdList.Add(Card.Id + 1); + if (ActivateDescription == Util.GetStringId(CardId.UnchainedAbomination, 2)) activatedCardIdList.Add(Card.Id + 2); + AI.SelectCard(targetList); + + return true; + } + + public bool UnchainedSoulOfAnguishSpSummon() + { + if (CheckShouldNoMoreSpSummon(false)) return false; + + ClientCard unchainedNonLink = Bot.GetMonsters().FirstOrDefault(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained) && !card.HasType(CardType.Link)); + ClientCard unchainedLink2 = Bot.GetMonsters().FirstOrDefault(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained) && card.HasType(CardType.Link) && card.LinkCount == 2); + Logger.DebugWriteLine("[Anguish summon] unchainedNonLink = " + unchainedNonLink?.Name + ", unchainedLink2 = " + unchainedLink2?.Name); + if (unchainedNonLink == null && unchainedLink2 == null) return false; + int needMonsterCount = 2; + if (unchainedLink2 != null) needMonsterCount = 1; + if (needMonsterCount == 2 && Bot.HasInExtra(CardId.UnchainedSoulLordOfYama)) return false; + bool needAnguish = !Bot.HasInMonstersZone(CardId.UnchainedSoulOfAnguish) && !activatedCardIdList.Contains(CardId.UnchainedSoulOfAnguish) + && Enemy.GetMonsters().Any(card => card.IsFaceup()); + if (needAnguish) + { + needAnguish = Bot.HasInExtra(CardId.UnchainedSoulOfRage); + needAnguish |= Bot.HasInExtra(CardId.UnchainedAbomination); + needAnguish |= Bot.HasInExtra(CardId.SPLittleKnight) && banSpSummonExceptFiendCount == 0; + } + Logger.DebugWriteLine("[Anguish summon] needAnguish = " + needAnguish.ToString()); + + // check material + if (needMonsterCount == 1) + { + List materialList = GetCanBeUsedForLinkMaterial(needAnguish, card => card == unchainedLink2); + Logger.DebugWriteLine("[Anguish summon 1] material count = " + materialList.Count().ToString()); + if (materialList.Count() == 0) return false; + List selectMaterials = new List{ unchainedLink2, materialList[0]}; + bool summonFlag = needAnguish; + summonFlag |= CheckCanDirectAttack() && GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack(selectMaterials) + 2400 >= Enemy.LifePoints; + Logger.DebugWriteLine("[Anguish summon 1] summon flag " + summonFlag.ToString()); + if (summonFlag) + { + AI.SelectMaterials(selectMaterials); + return true; + } + } + if (needMonsterCount == 2) + { + List materialList = GetCanBeUsedForLinkMaterial(needAnguish, card => card == unchainedNonLink); + Logger.DebugWriteLine("[Anguish summon 2] material count = " + materialList.Count().ToString()); + if (materialList.Count() >= 2) + { + List selectMaterials = new List { unchainedNonLink, materialList[0], materialList[1] }; + if (needAnguish || GetMaterialAttack(selectMaterials) < 2400) + { + AI.SelectMaterials(selectMaterials); + return true; + } + } + } + + return false; + } + public bool UnchainedSoulOfAnguishActivate() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated()) return false; + List targetList = Enemy.GetMonsters().Where(card => card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeMonsterTarget()).OrderByDescending(card => card.Attack).ToList(); + if (targetList.Count() > 0) + { + currentDestroyCardList.Add(targetList[0]); + int summonId = 0; + if (Bot.HasInExtra(CardId.UnchainedAbomination) && GetProblematicEnemyMonster(3000, ignoreCurrentDestroy:true) == null) + summonId = CardId.UnchainedAbomination; + else if (banSpSummonExceptFiendCount == 0 && Bot.HasInExtra(CardId.SPLittleKnight) && GetProblematicEnemyCardList(true, false, CardType.Monster).Count() > 0) + summonId = CardId.SPLittleKnight; + else if (Bot.HasInExtra(CardId.UnchainedSoulOfRage)) summonId = CardId.UnchainedSoulOfRage; + if (summonId > 0) + { + List materialList = new List(targetList){Card}; + Logger.DebugWriteLine("*** Anguish select: " + summonId.ToString()); + + AI.SelectCard(targetList); + AI.SelectNextCard(summonId); + AI.SelectMaterials(materialList); + activatedCardIdList.Add(Card.Id); + } + return true; + } + } + if (Card.Location == CardLocation.Grave) + { + return UnchainRecycleActivate(); + } + + return false; + } + + public bool UnchainedSoulLordOfYamaSpSummon() + { + if (CheckShouldNoMoreSpSummon(false)) return false; + if (Bot.HasInMonstersZone(CardId.UnchainedSoulLordOfYama) || activatedCardIdList.Contains(CardId.UnchainedSoulLordOfYama)) return false; + + bool need3Monster = Bot.HasInExtra(CardId.UnchainedSoulOfAnguish) && !Bot.HasInMonstersZone(CardId.UnchainedSoulOfAnguish) + && !activatedCardIdList.Contains(CardId.UnchainedSoulOfAnguish) && GetProblematicEnemyMonster(canBeTarget:true, selfType: CardType.Monster) != null; + need3Monster |= CheckAtAdvantage() && Duel.Phase == DuelPhase.Main2 + && Bot.HasInExtra(CardId.UnchainedSoulOfRage) && !Bot.HasInMonstersZone(CardId.UnchainedSoulOfRage); + bool haveUnchainSoul = Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained)); + if (need3Monster) + { + need3Monster = Bot.HasInExtra(CardId.UnchainedSoulOfRage); + need3Monster |= Bot.HasInExtra(CardId.UnchainedAbomination); + need3Monster |= Bot.HasInExtra(CardId.SPLittleKnight) && banSpSummonExceptFiendCount == 0; + } + // check material + List materialList = GetCanBeUsedForLinkMaterial(need3Monster, + card => !card.HasRace(CardRace.Fiend) || (card.HasType(CardType.Link) && card.HasSetcode(SetcodeUnchained))); + Logger.DebugWriteLine("[Yama Summon]need3Monster = " + need3Monster.ToString() + ", material count = " + materialList.Count()); + for (int index1 = 0; index1 < materialList.Count() - 1; ++ index1) + { + ClientCard material1 = materialList[index1]; + for (int index2 = index1 + 1; index2 < materialList.Count(); ++ index2) + { + ClientCard material2 = materialList[index2]; + List selectMaterials = new List{material1, material2}; + if (need3Monster && materialList.Count() == 2 && (activatedCardIdList.Contains(CardId.UnchainedSoulOfSharvara) || Bot.GetSpells().Count() == 0)) + { + // only for attack + if (GetProblematicEnemyMonster() != null || !CheckCanDirectAttack() || GetMaterialAttack(selectMaterials) >= 2000) return false; + } + bool summonFlag = need3Monster; + summonFlag |= Enemy.GetMonsterCount() == 0 && GetMaterialAttack(selectMaterials) < 2000; + summonFlag |= CheckAtAdvantage() && !haveUnchainSoul; + if (summonFlag) + { + AI.SelectMaterials(selectMaterials); + return true; + } + } + } + + return false; + } + public bool UnchainedSoulLordOfYamaActivate() + { + if (Card.Location == CardLocation.MonsterZone && (ActivateDescription == Util.GetStringId(CardId.UnchainedSoulLordOfYama, 0) || ActivateDescription == -1)) + { + // search + if (CheckWhetherNegated()) return false; + AI.SelectCard(CardId.UnchainedSoulOfSharvara, CardId.UnchainedAbomination, CardId.UnchainedSoulOfAnguish, CardId.UnchainedSoulOfRage); + activatedCardIdList.Add(Card.Id); + return true; + } + else if (Card.Location == CardLocation.Grave) + { + // spsummon & destroy + ClientCard chaosAngel = null; + ClientCard abomination = null; + ClientCard lady = null; + ClientCard lovely = null; + ClientCard arianna = null; + ClientCard bestAttack = null; + ClientCard rage = null; + foreach (ClientCard grave in Bot.Graveyard) + { + if (grave.IsCode(CardId.ChaosAngel) && grave.ProcCompleted != 0 && !dimensionalBarrierAnnouced.Contains(HintMsg.SYNCHRO)) chaosAngel = grave; + if (grave.IsCode(CardId.UnchainedSoulOfRage) && grave.ProcCompleted != 0) rage = grave; + if (grave.IsCode(CardId.UnchainedAbomination) && grave.ProcCompleted != 0) abomination = grave; + if (grave.IsCode(CardId.LadyLabrynthOfTheSilverCastle)) lady = grave; + if (grave.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)) lovely = grave; + if (grave.IsCode(CardId.AriannaTheLabrynthServant)) arianna = grave; + if (Card != grave && grave.IsMonster() && grave.HasRace(CardRace.Fiend)) + { + if (!grave.IsCanRevive()) continue; + if (bestAttack == null || grave.Attack > bestAttack.Attack) bestAttack = grave; + } + } + + ClientCard select = null; + bool destroyWelcome = false; + if (chaosAngel != null && (GetProblematicEnemyCardList(selfType: CardType.Monster).Count() > 0 || + (Bot.GetMonsterCount() == 0 && Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) + { + select = chaosAngel; + } + if (select == null && abomination != null && (GetProblematicEnemyCardList(selfType: CardType.Monster).Count() > 0 || + (Bot.GetMonsterCount() == 0 && Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) + { + select = abomination; + Logger.DebugWriteLine("[Yama] timing: " + CurrentTiming.ToString()); + if (Bot.HasInSpellZone(CardId.WelcomeLabrynth) && !(Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + && !activatedCardIdList.Contains(CardId.UnchainedAbomination)) + { + destroyWelcome = true; + } + } + if (select == null && rage != null && (Duel.Player == 0 || (!activatedCardIdList.Contains(CardId.UnchainedSoulOfRage) && (Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2))) + && Bot.HasInExtra(new List { CardId.UnchainedSoulOfAnguish, CardId.SPLittleKnight })) select = rage; + if (select == null && arianna != null && Duel.Player == 0 && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant)) select = arianna; + if (select == null && lovely != null && Duel.Player == 1 && Util.GetBestAttack(Enemy) < 2900) select = lovely; + if (select == null && lady != null && Duel.Player == 1 && Util.GetBestAttack(Enemy) < 3000) select = lady; + if (select == null && arianna != null && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant)) select = arianna; + if (select == null && bestAttack != null) select = bestAttack; + + if (select != null) + { + activatedCardIdList.Add(Card.Id + 1); + AI.SelectCard(select); + if (destroyWelcome) + { + AI.SelectYesNo(true); + AI.SelectNextCard(CardId.WelcomeLabrynth); + } else { + AI.SelectYesNo(false); + } + return true; + } + } + + return false; + } + + public bool UnchainedSoulOfRageSpSummon() + { + if (CheckShouldNoMoreSpSummon(false) || CheckWhetherNegated(true, true, CardType.Monster | CardType.Link)) return false; + if (Bot.HasInMonstersZone(CardId.UnchainedSoulOfRage)) return false; + + ClientCard unchained = Bot.GetMonsters().FirstOrDefault(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained) + && !card.IsCode(CardId.UnchainedSoulOfAnguish, CardId.UnchainedAbomination)); + if (unchained == null) return false; + + bool summonFlag = CheckAtAdvantage() && Util.IsTurn1OrMain2(); + summonFlag |= !(Bot.HasInExtra(CardId.UnchainedSoulOfAnguish) && !activatedCardIdList.Contains(CardId.UnchainedSoulOfAnguish)) && Util.IsTurn1OrMain2(); + if (summonFlag) + { + summonFlag = Bot.HasInExtra(CardId.UnchainedSoulOfAnguish); + summonFlag |= Bot.HasInExtra(CardId.SPLittleKnight) && banSpSummonExceptFiendCount == 0; + } + + List materialList = GetCanBeUsedForLinkMaterial(Util.IsTurn1OrMain2(), + card => !card.HasRace(CardRace.Fiend) || card == unchained); + if (materialList.Count() > 0) + { + List selectMaterials = new List{unchained, materialList[0]}; + summonFlag |= Enemy.GetMonsterCount() == 0 && GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack(selectMaterials) + 1800 >= Enemy.LifePoints; + if (summonFlag) + { + AI.SelectMaterials(selectMaterials); + return true; + } + } + + return false; + } + public bool UnchainedSoulOfRageActivate() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (CheckWhetherNegated()) return false; + bool activateFlag = DefaultOnBecomeTarget() && !Util.ChainContainsCard(CardId.EscapeOfTheUnchained); + ClientCard problemMonster = GetProblematicEnemyMonster(-1, true, true, CardType.Monster); + List targetList = Enemy.GetMonsters().Where(card => card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeTarget()).OrderBy(card => card.Attack).ToList(); + if (problemMonster != null) targetList.Insert(0, problemMonster); + + activateFlag |= (CurrentTiming & hintTimingMainEnd) > 0 && Util.IsOneEnemyBetterThanValue(Card.Attack, true); + activateFlag |= problemMonster != null; + + if (activateFlag && targetList.Count() > 0) + { + ClientCard target = targetList[0]; + int summonId = 0; + if (Bot.HasInExtra(CardId.UnchainedAbomination) && GetProblematicEnemyMonster(3000) == null + && target.HasType(CardType.Link) && target.LinkCount == 2) summonId = CardId.UnchainedSoulOfAnguish; + else if (banSpSummonExceptFiendCount == 0 && Bot.HasInExtra(CardId.SPLittleKnight)) summonId = CardId.SPLittleKnight; + else if (Bot.HasInExtra(CardId.UnchainedSoulOfAnguish) && GetProblematicEnemyMonster(2400) == null) summonId = CardId.UnchainedSoulOfAnguish; + List materialList = new List(targetList){Card}; + + AI.SelectCard(targetList); + AI.SelectNextCard(summonId); + AI.SelectMaterials(materialList); + activatedCardIdList.Add(Card.Id); + escapeTargetList.Add(Card); + currentDestroyCardList.Add(target); + return true; + } + } + if (Card.Location == CardLocation.Grave) + { + return UnchainRecycleActivate(); + } + + return false; + } + + public bool UnchainRecycleActivate() + { + AI.SelectCard(CardId.UnchainedSoulOfSharvara, CardId.LovelyLabrynthOfTheSilverCastle, CardId.AriannaTheLabrynthServant, + CardId.UnchainedAbomination, CardId.LabrynthStovieTorbie, CardId.LabrynthChandraglier, CardId.LabrynthCooclock, + CardId.AriasTheLabrynthButler, CardId.ArianeTheLabrynthServant); + activatedCardIdList.Add(Card.Id + 1); + + return true; + } + + public bool SPLittleKnightSpSummon() + { + if (CheckCanDirectAttack()) + { + // for attack + List materialList = SPLittleKnightSelectMaterial(); + if (materialList.Count() >= 2 && GetMaterialAttack(materialList) < 1600) + { + AI.SelectMaterials(materialList); + return true; + } + } else if (!CheckWhetherNegated(true, true, CardType.Monster | CardType.Link) && GetProblematicEnemyCardList(true, selfType: CardType.Monster).Count() > 0) + { + // for remove + List materialList = SPLittleKnightSelectMaterial(true); + if (materialList.Count() >= 2 && materialList.Any(card => card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link))) + { + AI.SelectMaterials(materialList); + return true; + } + } + return false; + } + public List SPLittleKnightSelectMaterial(bool needToUseEffect = false) + { + List usedMaterialList = new List(); + if (Bot.GetMonstersExtraZoneCount() > 0) + { + ClientCard botMonsterExtraZome = Bot.GetMonstersInExtraZone()[0]; + if (botMonsterExtraZome.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Pendulum) || botMonsterExtraZome.IsCode(CardId.RelinquishedAnima)) + { + usedMaterialList.Add(botMonsterExtraZome); + if (botMonsterExtraZome.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)) needToUseEffect = false; + } + List materialList = GetCanBeUsedForLinkMaterial(true, card => card == botMonsterExtraZome); + if (materialList.Count() > 0) + { + foreach (ClientCard card in materialList) + { + if (!needToUseEffect || card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz) || (card.HasType(CardType.Link) && card.LinkCount <= 2)) + { + usedMaterialList.Add(card); + if (card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link)) needToUseEffect = false; + } + if (usedMaterialList.Count() >= 2) break; + } + } + if (usedMaterialList.Count() < 2) usedMaterialList.Clear(); + } else { + List materialList = GetCanBeUsedForLinkMaterial(true, card => !needToUseEffect + || card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz) || (card.HasType(CardType.Link) && card.LinkCount <= 2)); + if (materialList.Count() >= 2) + { + for (int idx1 = 0; idx1 < materialList.Count() - 1; ++ idx1) + { + ClientCard material1 = materialList[idx1]; + if (material1.HasType(CardType.Link) && material1.LinkCount >= 3) continue; + bool flag1 = !needToUseEffect || material1.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link); + for (int idx2 = 0; idx2 < materialList.Count(); ++ idx2) + { + ClientCard material2 = materialList[idx2]; + if (material2.HasType(CardType.Link) && material2.LinkCount >= 3) continue; + bool flag2 = !needToUseEffect || material2.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link); + if (flag1 || flag2) + { + return new List{material1, material2}; + } + } + } + } + } + + return usedMaterialList; + } + + public bool SPLittleKnightActivate() + { + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.SPLittleKnight, 0)) + { + // banish card + List problemCardList = GetProblematicEnemyCardList(true, selfType: CardType.Monster); + problemCardList.AddRange(GetDangerousCardinEnemyGrave(false)); + problemCardList.AddRange(GetNormalEnemyTargetList(true, true, CardType.Monster)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => card.HasType(CardType.Monster)).OrderByDescending(card => card.Attack)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => !card.HasType(CardType.Monster))); + if (problemCardList.Count() > 0) + { + AI.SelectCard(problemCardList); + activatedCardIdList.Add(Card.Id); + return true; + } + } else if (ActivateDescription == Util.GetStringId(CardId.SPLittleKnight, 1)) + { + ClientCard selfMonster = null; + foreach (ClientCard target in Bot.GetMonsters()) + { + if (Duel.ChainTargets.Contains(target) && !escapeTargetList.Contains(target)) + { + selfMonster = target; + break; + } + } + if (selfMonster == null) + { + if (Duel.Player == 1) + { + selfMonster = Bot.GetMonsters().Where(card => card.IsAttack()).OrderBy(card => card.Attack).FirstOrDefault(); + if (!Util.IsOneEnemyBetterThanValue(selfMonster.Attack, true)) selfMonster = null; + } + } + if (selfMonster != null) + { + ClientCard nextMonster = null; + List selfTargetList = Bot.GetMonsters().Where(card => card != selfMonster).ToList(); + if (Enemy.GetMonsterCount() == 0 && selfTargetList.Count() > 0) + { + selfTargetList.Sort(CompareUsableAttack); + nextMonster = selfTargetList[0]; + escapeTargetList.Add(nextMonster); + } + if (Enemy.GetMonsterCount() > 0) + { + nextMonster = GetBestEnemyMonster(false, true, true); + currentDestroyCardList.Add(nextMonster); + } + if (nextMonster != null) + { + AI.SelectCard(selfMonster); + AI.SelectNextCard(nextMonster); + escapeTargetList.Add(selfMonster); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + + return false; + } + + public bool MuckrakerFromTheUnderworldSpSummon() + { + List materialList = GetCanBeUsedForLinkMaterial(true, card => card.HasType(CardType.Link)); + if (materialList.Count() < 2) return false; + bool willBeNegated = CheckWhetherNegated(true, true, CardType.Monster | CardType.Link) && Bot.Hand.Count() > 0; + bool canRebornAngel = Bot.Graveyard.Any(card => card.IsCanRevive() && card.IsCode(CardId.ChaosAngel)) && !willBeNegated; + bool canRebornLovely = Bot.Graveyard.Any(card => card.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)) && !willBeNegated; + int bestAttackGrave = 0; + bool chaosAngelFlag = GetProblematicEnemyCardList(true, selfType: CardType.Monster).Count() > 0 && !CheckWhetherNegated(true, true, CardType.Monster); + foreach (ClientCard grave in Bot.Graveyard) + { + if (grave.IsMonster() && grave.HasRace(CardRace.Fiend)) + { + if (!grave.IsCanRevive()) continue; + if (grave.Attack > bestAttackGrave) bestAttackGrave = grave.Attack; + } + } + for (int idx1 = 0; idx1 < materialList.Count() - 1; ++ idx1) + { + ClientCard material1 = materialList[idx1]; + for (int idx2 = idx1 + 1; idx2 < materialList.Count(); ++ idx2) + { + ClientCard material2 = materialList[idx1]; + List currentList = new List { material1, material2 }; + bool summonFlag = chaosAngelFlag && (canRebornAngel || (currentList.Any(card => card.IsCode(CardId.ChaosAngel)) && !willBeNegated)); + summonFlag |= Enemy.GetMonsterCount() == 0 && canRebornLovely; + summonFlag |= !activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle) && Bot.Graveyard.Any(card => card.Type == (int)CardType.Trap) + && currentList.Any(card => card.IsDisabled() && card.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)); + if (CheckCanDirectAttack()) + { + summonFlag |= GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack(currentList) + bestAttackGrave >= Enemy.LifePoints; + summonFlag |= GetMaterialAttack(currentList) < 1000; + } + if (summonFlag) + { + AI.SelectMaterials(currentList); + return true; + } + } + } + return false; + } + public bool MuckrakerFromTheUnderworldActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.MuckrakerFromTheUnderworld, 0)) + { + if (CheckWhetherNegated()) return false; + ClientCard chaosAngel = null; + ClientCard lovely = null; + ClientCard arianna = null; + ClientCard bestAttack = null; + foreach (ClientCard grave in Bot.Graveyard) + { + if (grave.IsCode(CardId.ChaosAngel) && grave.ProcCompleted != 0 && !dimensionalBarrierAnnouced.Contains(HintMsg.SYNCHRO)) chaosAngel = grave; + if (grave.IsCode(CardId.LovelyLabrynthOfTheSilverCastle)) lovely = grave; + if (grave.IsCode(CardId.AriannaTheLabrynthServant)) arianna = grave; + if (Card != grave && grave.IsMonster() && grave.HasRace(CardRace.Fiend)) + { + if (!grave.IsCanRevive()) continue; + if (bestAttack == null || grave.Attack > bestAttack.Attack) bestAttack = grave; + } + } + + ClientCard rebornTarget = null; + if (chaosAngel != null && (GetProblematicEnemyCardList(true, selfType: CardType.Monster).Count() > 0)) rebornTarget = chaosAngel; + if (rebornTarget == null && lovely != null && Util.GetBestAttack(Enemy) < 2900 && + (!activatedCardIdList.Contains(CardId.LovelyLabrynthOfTheSilverCastle) || Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth))) rebornTarget = lovely; + if (rebornTarget == null && bestAttack != null && CheckCanDirectAttack() + && GetBotCurrentTotalAttack() < Enemy.LifePoints && GetBotCurrentTotalAttack() + bestAttack.Attack >= Enemy.LifePoints) rebornTarget = bestAttack; + if (rebornTarget == null && arianna != null && Duel.Player == 0 && !activatedCardIdList.Contains(CardId.AriannaTheLabrynthServant)) rebornTarget = arianna; + if (rebornTarget == null && bestAttack != null) rebornTarget = bestAttack; + if (rebornTarget != null) + { + AI.SelectCard(rebornTarget); + AI.SelectNextCard(FurnitureGetCost()); + activatedCardIdList.Contains(Card.Id); + banSpSummonExceptFiendCount = Math.Max(1, banSpSummonExceptFiendCount); + return true; + } + } + + return false; + } + + public bool RelinquishedAnimaSpSummon() + { + if (CheckWhetherNegated()) return false; + // summon to use effect + ClientCard enemyLeftEx = Enemy.MonsterZone[6]; + if (enemyLeftEx != null && enemyLeftEx.HasLinkMarker((int)CardLinkMarker.Top) && !enemyLeftEx.IsShouldNotBeTarget() && !enemyLeftEx.IsShouldNotBeMonsterTarget()) + { + ClientCard selfMonsterZone1 = Bot.MonsterZone[1]; + if (selfMonsterZone1 == null) + { + AI.SelectMaterials(CardId.LabrynthCooclock); + AI.SelectPlace(Zones.z1); + return true; + } + else if (!selfMonsterZone1.HasType(CardType.Xyz | CardType.Link | CardType.Token) && selfMonsterZone1.Level == 1) + { + AI.SelectMaterials(selfMonsterZone1); + AI.SelectPlace(Zones.z1); + return true; + } + } + ClientCard enemyRightEx = Enemy.MonsterZone[5]; + if (enemyRightEx != null && enemyRightEx.HasLinkMarker((int)CardLinkMarker.Top) && !enemyRightEx.IsShouldNotBeTarget() && !enemyRightEx.IsShouldNotBeMonsterTarget()) + { + ClientCard selfMonsterZone3 = Bot.MonsterZone[3]; + if (selfMonsterZone3 == null) + { + AI.SelectMaterials(CardId.LabrynthCooclock); + AI.SelectPlace(Zones.z3); + return true; + } + else if (!selfMonsterZone3.HasType(CardType.Xyz | CardType.Link | CardType.Token) && selfMonsterZone3.Level == 1) + { + AI.SelectMaterials(selfMonsterZone3); + AI.SelectPlace(Zones.z3); + return true; + } + } + + if (Bot.MonsterZone[5] != null || Bot.MonsterZone[6] != null) return false; + ClientCard enemyMonsterLeft = Enemy.MonsterZone[3]; + ClientCard enemyMonsterRight = Enemy.MonsterZone[1]; + if (Enemy.MonsterZone[6] != null) enemyMonsterLeft = null; + if (enemyMonsterLeft != null && enemyMonsterLeft.IsFacedown()) enemyMonsterLeft = null; + if (enemyMonsterLeft != null && (enemyMonsterLeft.IsShouldNotBeMonsterTarget() || enemyMonsterLeft.IsShouldNotBeTarget())) enemyMonsterLeft = null; + + if (Enemy.MonsterZone[5] != null) enemyMonsterRight = null; + if (enemyMonsterRight != null && (enemyMonsterRight.IsShouldNotBeMonsterTarget() || enemyMonsterRight.IsShouldNotBeTarget())) enemyMonsterRight = null; + if (enemyMonsterRight != null && enemyMonsterRight.IsFacedown()) enemyMonsterRight = null; + + int place = -1; + if (enemyMonsterLeft != null && enemyMonsterRight == null) place = Zones.z5; + if (enemyMonsterLeft == null && enemyMonsterRight != null) place = Zones.z6; + if (enemyMonsterLeft != null && enemyMonsterRight != null) + { + if (enemyMonsterLeft.IsFloodgate() && !enemyMonsterRight.IsFloodgate()) place = Zones.z5; + else if (!enemyMonsterLeft.IsFloodgate() && enemyMonsterRight.IsFloodgate()) place = Zones.z6; + else + { + if (enemyMonsterLeft.GetDefensePower() >= enemyMonsterRight.GetDefensePower()) place = Zones.z5; + else place = Zones.z6; + } + } + if (place >= 0) + { + AI.SelectMaterials(Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Xyz | CardType.Link | CardType.Token) && card.Level == 1) + .OrderBy(card => card.Attack).ToList()); + AI.SelectPlace(place); + return true; + } + + // summon for little knight + if (Bot.HasInExtra(CardId.SPLittleKnight) && Bot.GetMonsters().Count(card => card.IsFaceup()) >= 2 + && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link))) + { + if (GetProblematicEnemyCardList(true, selfType: CardType.Monster).Count() > 0) + { + AI.SelectMaterials(Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Xyz | CardType.Link | CardType.Token) && card.Level == 1) + .OrderBy(card => card.Attack).ToList()); + return true; + } + } + return false; + } + public bool RelinquishedAnimaActivate() + { + if (CheckWhetherNegated()) return false; + activatedCardIdList.Add(Card.Id); + Dictionary placeList = new Dictionary{ {1, 6}, {3, 5}, {5, 3}, {6, 1} }; + foreach (KeyValuePair placePair in placeList) + { + if (Bot.MonsterZone[placePair.Key] == Card && Enemy.MonsterZone[placePair.Value] != null) + { + currentDestroyCardList.Add(Enemy.MonsterZone[placePair.Value]); + break; + } + } + return true; + } + + public bool MonsterRepos() + { + int selfAttack = Card.Attack + 1; + + if (selfAttack <= 1) + return !Card.IsDefense(); + + int bestAttack = 0; + foreach (ClientCard card in Bot.GetMonsters()) + { + int attack = card.Attack; + if (attack >= bestAttack) + { + bestAttack = attack; + } + } + + bool enemyBetter = Util.IsAllEnemyBetterThanValue(bestAttack, true); + + if (Card.IsAttack() && enemyBetter) + return true; + if (Card.IsDefense() && !enemyBetter) + return true; + return false; + } + + public bool ReposForLabrynth() + { + if (!activatedCardIdList.Contains(CardId.BigWelcomeLabrynth) && Bot.HasInSpellZoneOrInGraveyard(CardId.BigWelcomeLabrynth)) + return Card.IsFacedown(); + return false; + } + + public bool SpellSetCheck() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + if (Card.IsCode(CardId.BigWelcomeLabrynth) && Bot.HasInSpellZone(Card.Id)) return false; + if (Card.IsCode(CardId.TransactionRollback) && !Bot.HasInSpellZone(CardId.TransactionRollback)) + { + // check enemy grave trap + bool haveCopyTrap = false; + if (Enemy.Graveyard.Any(card => card.IsCode( + CardId.WelcomeLabrynth, CardId.BigWelcomeLabrynth, _CardId.InfiniteImpermanence, _CardId.DimensionalBarrier, CardId.DestructiveDarumaKarmaCannon, + _CardId.CompulsoryEvacuationDevice, _CardId.BreakthroughSkill + ))) + { + haveCopyTrap = true; + } + + if (!haveCopyTrap && !Bot.HasInHand(CardId.UnchainedSoulOfSharvara)) return false; + } + if (Card.IsCode(CardId.EscapeOfTheUnchained) && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeUnchained))) return false; + + // select place + if (Card.IsTrap() || Card.HasType(CardType.QuickPlay)) + { + List avoidList = new List(); + int setFornfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoidList.Add(4 - i); + setFornfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setFornfiniteImpermanence); + return true; + } else + { + SelectSTPlace(Card, false, avoidList); + return true; + } + } else + { + SelectSTPlace(); + } + return true; + } + + else if (Enemy.HasInSpellZone(_CardId.AntiSpellFragrance, true) || Bot.HasInSpellZone(_CardId.AntiSpellFragrance, true)) + { + if (Card.IsSpell() && !Bot.HasInSpellZone(Card.Id)) + { + SelectSTPlace(); + return true; + } + } + + return false; + } + + public bool SpellSetForCooClockCheck() + { + // set to destroy for Sharvara + if (Card.IsCode(CardId.PotOfExtravagance, CardId.TransactionRollback, CardId.WelcomeLabrynth) && Bot.HasInHand(CardId.UnchainedSoulOfSharvara) + && !activatedCardIdList.Contains(CardId.UnchainedSoulOfSharvara)) + { + SelectSTPlace(Card, false); + return true; + } + // set to activate by cooclock + bool haveLabrynth = Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasSetcode(SetcodeLabrynth)); + if (!cooclockAffected || (haveLabrynth && Bot.HasInHand(CardId.LabrynthCooclock) && !activatedCardIdList.Contains(CardId.LabrynthCooclock))) return false; + if (!Card.IsCode(CardId.BigWelcomeLabrynth, CardId.WelcomeLabrynth, _CardId.InfiniteImpermanence, _CardId.DimensionalBarrier)) return false; + if (haveLabrynth) + { + SelectSTPlace(Card, true); + return true; + } + if (!Card.IsCode(CardId.BigWelcomeLabrynth, CardId.WelcomeLabrynth)) return false; + if (!summoned && Bot.Hand.Any(card => card.IsMonster() && card.Level <= 4 && card.HasSetcode(SetcodeLabrynth))) + { + SelectSTPlace(Card, true); + return true; + } + + return false; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/Level8Executor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/Level8Executor.cs new file mode 100644 index 0000000..be5d60b --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/Level8Executor.cs @@ -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 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 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(); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LightswornExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LightswornExecutor.cs new file mode 100644 index 0000000..8340d5a --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LightswornExecutor.cs @@ -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 OnSelectXyzMaterial(IList cards, int min, int max) + { + Logger.DebugWriteLine("OnSelectXyzMaterial " + cards.Count + " " + min + " " + max); + IList result = new List(); + 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 targets = new List(); + + 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; + } + } + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LightswornShaddoldinosourExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LightswornShaddoldinosourExecutor.cs new file mode 100644 index 0000000..9b91d73 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LightswornShaddoldinosourExecutor.cs @@ -0,0 +1,1283 @@ +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; + +namespace WindBot.Game.AI.Decks +{ + [Deck("LightswornShaddoldinosour", "AI_LightswornShaddoldinosour")] + public class LightswornShaddoldinosour : DefaultExecutor + { + public class CardId + { + //monster + public const int UltimateConductorTytanno = 18940556; + public const int DogorantheMadFlameKaiju = 93332803; + public const int GamecieltheSeaTurtleKaiju = 55063751; + public const int RadiantheMultidimensionalKaiju = 28674152; + public const int OvertexCoatls = 41782653; + public const int ShaddollBeast = 3717252; + public const int GiantRex = 80280944; + public const int ShaddollDragon = 77723643; + public const int FairyTailSnow = 55623480; + public const int KeeperOfDragonicMagic = 48048590; + public const int ShaddollSquamata = 30328508; + public const int SouleatingOviraptor = 44335251; + public const int Raiden = 77558536; + public const int Lumina = 95503687; + public const int ShaddollHedgehog = 4939890; + public const int AshBlossom = 14558127; + public const int GhostOgre = 59438930; + public const int ShaddollFalco = 37445295; + public const int MaxxC = 23434538; + public const int PlaguespreaderZombie = 33420078; + public const int GlowUpBulb = 67441435; + + //spell + public const int AllureofDarkness = 1475311; + public const int ThatGrassLooksgreener = 11110587; + public const int HarpiesFeatherDuster = 18144506; + public const int DoubleEvolutionPill = 38179121; + public const int ShaddollFusion = 44394295; + public const int PotOfAvarice = 67169062; + public const int FoolishBurial = 81439173; + public const int MonsterReborn = 83764718; + public const int ChargeOfTheLightBrigade = 94886282; + public const int InterruptedKaijuSlumber = 99330325; + //public const int ElShaddollFusion = 6417578; + + //trap + public const int infiniteTransience = 10045474; + public const int LostWind = 74003290; + public const int SinisterShadowGames = 77505534; + public const int ShaddollCore = 4904633; + + //extra + public const int ElShaddollShekhinaga = 74822425; + public const int ElShaddollConstruct = 20366274; + public const int ElShaddollGrysra = 48424886; + public const int ElShaddollWinda = 94977269; + public const int CrystalWingSynchroDragon = 50954680; + public const int ScarlightRedDragon = 80666118; + public const int Michael = 4779823; + public const int BlackRoseMoonlightDragon = 33698022; + public const int RedWyvern = 76547525; + public const int CoralDragon = 42566602; + public const int TG_WonderMagician = 98558751; + public const int MinervaTheExalte = 30100551; + public const int Sdulldeat = 74997493; + public const int CrystronNeedlefiber = 50588353; + } + + + + public LightswornShaddoldinosour(GameAI ai, Duel duel) + : base(ai, duel) + { + //counter + AddExecutor(ExecutorType.Activate, CardId.GhostOgre, Hand_act_eff); + AddExecutor(ExecutorType.Activate, CardId.AshBlossom, Hand_act_eff); + AddExecutor(ExecutorType.Activate, CardId.MaxxC,MaxxC); + //first do + AddExecutor(ExecutorType.Activate, CardId.HarpiesFeatherDuster, DefaultHarpiesFeatherDusterFirst); + AddExecutor(ExecutorType.Activate, CardId.infiniteTransience, DefaultBreakthroughSkill); + AddExecutor(ExecutorType.Activate, CardId.ThatGrassLooksgreener); + AddExecutor(ExecutorType.Summon, CardId.SouleatingOviraptor); + AddExecutor(ExecutorType.Activate, CardId.SouleatingOviraptor, SouleatingOviraptoreff); + AddExecutor(ExecutorType.Activate, CardId.AllureofDarkness, DefaultAllureofDarkness); + AddExecutor(ExecutorType.Activate, CardId.PotOfAvarice, PotofAvariceeff); + AddExecutor(ExecutorType.Activate, CardId.ChargeOfTheLightBrigade, ChargeOfTheLightBrigadeEffect); + AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialEffect); + AddExecutor(ExecutorType.Activate, CardId.InterruptedKaijuSlumber, InterruptedKaijuSlumbereff); + AddExecutor(ExecutorType.Activate, CardId.ShaddollFusion, ShaddollFusioneff); + //Normal Summon + AddExecutor(ExecutorType.Summon, CardId.Raiden); + AddExecutor(ExecutorType.Activate, CardId.Raiden); + AddExecutor(ExecutorType.Summon , CardId.KeeperOfDragonicMagic); + AddExecutor(ExecutorType.Activate, CardId.KeeperOfDragonicMagic, KeeperOfDragonicMagiceff); + AddExecutor(ExecutorType.MonsterSet, CardId.ShaddollSquamata); + AddExecutor(ExecutorType.MonsterSet, CardId.GlowUpBulb); + AddExecutor(ExecutorType.Summon, CardId.Lumina, Luminasummon); + AddExecutor(ExecutorType.MonsterSet, CardId.ShaddollHedgehog); + AddExecutor(ExecutorType.MonsterSet, CardId.ShaddollDragon); + AddExecutor(ExecutorType.Summon, CardId.FairyTailSnow,FairyTailSnowsummon); + AddExecutor(ExecutorType.Activate, CardId.FairyTailSnow, FairyTailSnoweff); + AddExecutor(ExecutorType.Activate, CardId.Lumina, Luminaeff); + //activate + AddExecutor(ExecutorType.Activate, CardId.GlowUpBulb, GlowUpBulbeff); + AddExecutor(ExecutorType.Activate, CardId.TG_WonderMagician, TG_WonderMagicianeff); + AddExecutor(ExecutorType.Activate, CardId.CoralDragon, CoralDragoneff); + AddExecutor(ExecutorType.Activate, CardId.RedWyvern, RedWyverneff); + AddExecutor(ExecutorType.Activate, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragoneff); + AddExecutor(ExecutorType.Activate, CardId.BlackRoseMoonlightDragon, BlackRoseMoonlightDragoneff); + AddExecutor(ExecutorType.Activate, CardId.Sdulldeat, Sdulldeateff); + AddExecutor(ExecutorType.Activate, CardId.Michael, Michaeleff); + AddExecutor(ExecutorType.Activate, CardId.ScarlightRedDragon, ScarlightRedDragoneff); + //Sp Summon + + AddExecutor(ExecutorType.Activate, CardId.CrystronNeedlefiber, CrystronNeedlefibereff); + AddExecutor(ExecutorType.SpSummon, CardId.UltimateConductorTytanno, UltimateConductorTytannosp); + AddExecutor(ExecutorType.Activate, CardId.UltimateConductorTytanno, UltimateConductorTytannoeff); + AddExecutor(ExecutorType.Activate, CardId.DoubleEvolutionPill, DoubleEvolutionPilleff); + //extra + AddExecutor(ExecutorType.SpSummon, CardId.CrystalWingSynchroDragon); + AddExecutor(ExecutorType.Activate, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragoneff); + AddExecutor(ExecutorType.SpSummon, CardId.ScarlightRedDragon, ScarlightRedDragonsp); + AddExecutor(ExecutorType.Activate, CardId.ScarlightRedDragon, ScarlightRedDragoneff); + AddExecutor(ExecutorType.SpSummon, CardId.Michael, Michaelsp); + AddExecutor(ExecutorType.Activate, CardId.Michael, Michaeleff); + AddExecutor(ExecutorType.SpSummon, CardId.RedWyvern, RedWyvernsp); + AddExecutor(ExecutorType.Activate, CardId.RedWyvern, RedWyverneff); + AddExecutor(ExecutorType.SpSummon, CardId.MinervaTheExalte); + AddExecutor(ExecutorType.Activate, CardId.MinervaTheExalte, MinervaTheExaltedEffect); + AddExecutor(ExecutorType.SpSummon, CardId.CrystronNeedlefiber, CrystronNeedlefibersp); + //Kaiju + AddExecutor(ExecutorType.SpSummon, CardId.GamecieltheSeaTurtleKaiju, GamecieltheSeaTurtleKaijusp); + AddExecutor(ExecutorType.SpSummon, CardId.RadiantheMultidimensionalKaiju, RadiantheMultidimensionalKaijusp); + AddExecutor(ExecutorType.SpSummon, CardId.DogorantheMadFlameKaiju, DogorantheMadFlameKaijusp); + //Reborn + AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, Reborneff); + //activate chain + AddExecutor(ExecutorType.Activate, CardId.OvertexCoatls, OvertexCoatlseff); + AddExecutor(ExecutorType.Activate, CardId.ShaddollCore, ShaddollCoreeff); + AddExecutor(ExecutorType.Activate, CardId.ShaddollBeast, ShaddollBeasteff); + AddExecutor(ExecutorType.Activate, CardId.ShaddollFalco, ShaddollFalcoeff); + AddExecutor(ExecutorType.Activate, CardId.ShaddollDragon, ShaddollDragoneff); + AddExecutor(ExecutorType.Activate, CardId.ShaddollHedgehog, ShaddollHedgehogeff); + AddExecutor(ExecutorType.Activate, CardId.ShaddollSquamata, ShaddollSquamataeff); + AddExecutor(ExecutorType.Activate, CardId.GiantRex); + AddExecutor(ExecutorType.Activate, CardId.ElShaddollConstruct, ElShaddollConstructeff); + AddExecutor(ExecutorType.Activate, CardId.ElShaddollGrysra, ElShaddollGrysraeff); + AddExecutor(ExecutorType.Activate, CardId.ElShaddollShekhinaga, ElShaddollShekhinagaeff); + AddExecutor(ExecutorType.Activate, CardId.ElShaddollWinda); + //spellset + AddExecutor(ExecutorType.SpellSet, CardId.ThatGrassLooksgreener, SpellSetZone); + AddExecutor(ExecutorType.SpellSet, SpellSetZone); + //trapset + AddExecutor(ExecutorType.SpellSet, CardId.LostWind); + AddExecutor(ExecutorType.SpellSet, CardId.SinisterShadowGames); + AddExecutor(ExecutorType.SpellSet, CardId.ShaddollCore); + AddExecutor(ExecutorType.SpellSet, CardId.infiniteTransience, SetIsFieldEmpty); + //trap activate + AddExecutor(ExecutorType.Activate, CardId.LostWind, LostWindeff); + AddExecutor(ExecutorType.Activate, CardId.SinisterShadowGames, SinisterShadowGameseff); + + AddExecutor(ExecutorType.Repos, MonsterRepos); + } + public int[] all_List() + { + return new[] + { + CardId.UltimateConductorTytanno, + CardId.DogorantheMadFlameKaiju, + CardId.GamecieltheSeaTurtleKaiju, + CardId.RadiantheMultidimensionalKaiju, + CardId.OvertexCoatls, + CardId.ShaddollBeast, + CardId.GiantRex, + CardId.ShaddollDragon, + CardId.FairyTailSnow, + CardId.KeeperOfDragonicMagic, + CardId.ShaddollSquamata, + CardId.SouleatingOviraptor, + CardId.Raiden, + CardId.Lumina, + CardId.ShaddollHedgehog, + CardId.AshBlossom, + CardId.GhostOgre, + CardId.ShaddollFalco, + CardId.MaxxC, + CardId.PlaguespreaderZombie, + CardId.GlowUpBulb, + + CardId.AllureofDarkness, + CardId.ThatGrassLooksgreener, + CardId.HarpiesFeatherDuster, + CardId.DoubleEvolutionPill, + CardId.ShaddollFusion, + CardId.PotOfAvarice, + CardId.FoolishBurial, + CardId.MonsterReborn, + CardId.ChargeOfTheLightBrigade, + CardId.InterruptedKaijuSlumber, + //CardId.ElShaddollFusion, + + CardId.infiniteTransience, + CardId.LostWind, + CardId.SinisterShadowGames, + CardId.ShaddollCore, + + + }; + } + public int[] Useless_List() + { + return new[] + { + CardId.GlowUpBulb, + CardId.PlaguespreaderZombie, + CardId.ChargeOfTheLightBrigade, + CardId.ThatGrassLooksgreener, + CardId.HarpiesFeatherDuster, + CardId.FairyTailSnow, + CardId.GiantRex, + CardId.Lumina, + CardId.OvertexCoatls, + CardId.InterruptedKaijuSlumber, + CardId.FoolishBurial, + }; + } + int Ultimate_ss = 0; + int Enemy_atk = 0; + bool Pillused = false; + bool CrystronNeedlefibereff_used = false; + bool OvertexCoatlseff_used = false; + bool ShaddollBeast_used = false; + bool ShaddollFalco_used = false; + bool ShaddollSquamata_used = false; + bool ShaddollDragon_used = false; + bool ShaddollHedgehog_used = false; + + public int GetTotalATK(IList list) + { + + int atk = 0; + foreach (ClientCard c in list) + { + if (c == null) continue; + atk += c.Attack; + } + return atk; + } + + public override void OnNewPhase() + { + Enemy_atk = 0; + IList list = new List(); + foreach (ClientCard monster in Enemy.GetMonsters()) + { + if(monster.IsAttack()) + list.Add(monster); + } + //if (GetTotalATK(list) / 2 >= Bot.LifePoints) return false; + Enemy_atk = GetTotalATK(list); + //SLogger.DebugWriteLine("++++++++++++++++++" + Enemy_atk + "++++++++++++"); + } + public override void OnNewTurn() + { + Pillused = false; + OvertexCoatlseff_used = false; + CrystronNeedlefibereff_used = false; + ShaddollBeast_used = false; + ShaddollFalco_used = false; + ShaddollSquamata_used = false; + ShaddollDragon_used = false; + ShaddollHedgehog_used = false; + base.OnNewTurn(); + } + + private bool Luminasummon() + { + if (Bot.Deck.Count >= 20) return true; + IList extra = Bot.GetMonstersInExtraZone(); + if (extra != null) + foreach (ClientCard monster in extra) + if (!monster.HasType(CardType.Link)) + return false; + if (Bot.LifePoints <= 3000) return true; + if (Bot.HasInGraveyard(CardId.Raiden)) return true; + return false; + } + private bool Luminaeff() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Bot.HasInGraveyard(CardId.Raiden)) + { + AI.SelectCard(Useless_List()); + AI.SelectNextCard(CardId.Raiden); + return true; + } + return false; + } + + + private bool UltimateConductorTytannoeff() + { + IList targets = new[] { + CardId.OvertexCoatls, + CardId.ShaddollBeast, + CardId.ShaddollSquamata, + CardId.ShaddollHedgehog, + CardId.ShaddollDragon, + CardId.ShaddollFalco, + CardId.GlowUpBulb, + CardId.PlaguespreaderZombie, + CardId.FairyTailSnow, + CardId.KeeperOfDragonicMagic, + CardId.DogorantheMadFlameKaiju, + CardId.GamecieltheSeaTurtleKaiju, + CardId.RadiantheMultidimensionalKaiju, + CardId.GiantRex, + CardId.ShaddollCore, + CardId.SouleatingOviraptor, + CardId.Raiden, + CardId.Lumina, + CardId.AshBlossom, + CardId.GhostOgre, + CardId.MaxxC, + }; + + if (Duel.Phase == DuelPhase.Main1) + { + if(Duel.Player==0) + { + int count = 0; + IList check = Enemy.GetMonsters(); + foreach (ClientCard monster in check) + if (monster.Attack > 2500 || monster == Enemy.MonsterZone.GetDangerousMonster()) + count++; + if(count==0)return false; + } + if (!Bot.HasInHand(targets)) + { + if(!Bot.HasInMonstersZone(targets)) + return false; + } + AI.SelectCard(targets); + return true; + } + if (Duel.Phase == DuelPhase.BattleStart) + { + AI.SelectYesNo(true); + return true; + } + return false; + + } + + private bool GamecieltheSeaTurtleKaijusp() + { + if (!Bot.HasInMonstersZone(CardId.UltimateConductorTytanno)) + return DefaultKaijuSpsummon(); + return false; + } + + private bool RadiantheMultidimensionalKaijusp() + { + if (Enemy.HasInMonstersZone(CardId.GamecieltheSeaTurtleKaiju)) return true; + if (Bot.HasInHand(CardId.DogorantheMadFlameKaiju) && !Bot.HasInMonstersZone(CardId.UltimateConductorTytanno)) return DefaultKaijuSpsummon(); + return false; + } + + + private bool DogorantheMadFlameKaijusp() + { + if (Enemy.HasInMonstersZone(CardId.GamecieltheSeaTurtleKaiju)) return true; + if (Enemy.HasInMonstersZone(CardId.RadiantheMultidimensionalKaiju)) return true; + return false; + } + + + private bool InterruptedKaijuSlumbereff() + { + if (Enemy.GetMonsterCount() - Bot.GetMonsterCount() >= 2 ) + return DefaultInterruptedKaijuSlumber(); + return false; + } + private bool UltimateConductorTytannosp() + { + + Pillused = true; + foreach (ClientCard card in Bot.GetMonsters()) + { + if (card.IsCode(CardId.UltimateConductorTytanno) && card.IsFaceup()) + return false; + } + Ultimate_ss++; + return true; + + } + + private bool KeeperOfDragonicMagiceff() + { + if (ActivateDescription == -1) + { + AI.SelectCard(Useless_List()); + return true; + } + return true; + } + + private bool MonsterRepos() + { + if (Card.IsCode(CardId.UltimateConductorTytanno) && Card.IsFacedown()) return true; + if (Card.IsCode(CardId.ElShaddollConstruct) && Card.IsFacedown()) return true; + if (Card.IsCode(CardId.ElShaddollConstruct) && Card.IsAttack()) return false; + if (Card.IsCode(CardId.GlowUpBulb) && Card.IsDefense()) return false; + if (Card.IsCode(CardId.ShaddollDragon) && Card.IsFacedown() && Enemy.GetMonsterCount() >= 0) return true; + if (Card.IsCode(CardId.ShaddollSquamata) && Card.IsFacedown() && Enemy.GetMonsterCount() >= 0) return true; + return base.DefaultMonsterRepos(); + } + + private bool OvertexCoatlseff() + { + if (Card.Location == CardLocation.MonsterZone) return false; + OvertexCoatlseff_used = true; + return true; + } + + private bool DoubleEvolutionPilleff() + { + foreach (ClientCard card in Bot.GetMonsters()) + { + if (card.IsCode(CardId.UltimateConductorTytanno) && card.IsFaceup()) + return false; + } + if (Pillused == true) return false; + Pillused = true; + IList targets = new[] { + CardId.GiantRex, + CardId.DogorantheMadFlameKaiju, + CardId.GamecieltheSeaTurtleKaiju, + CardId.RadiantheMultidimensionalKaiju, + CardId.OvertexCoatls, + CardId.SouleatingOviraptor, + CardId.UltimateConductorTytanno, + }; + if (Bot.HasInGraveyard(targets)) + { + AI.SelectCard(CardId.GiantRex, CardId.DogorantheMadFlameKaiju, CardId.OvertexCoatls, CardId.GamecieltheSeaTurtleKaiju, CardId.RadiantheMultidimensionalKaiju, CardId.SouleatingOviraptor, CardId.UltimateConductorTytanno); + } + else + { + AI.SelectCard(CardId.GiantRex, CardId.DogorantheMadFlameKaiju, CardId.GamecieltheSeaTurtleKaiju, CardId.RadiantheMultidimensionalKaiju, CardId.OvertexCoatls, CardId.SouleatingOviraptor, CardId.UltimateConductorTytanno); + } + IList targets2 = new[] { + CardId.GiantRex, + CardId.DogorantheMadFlameKaiju, + CardId.GamecieltheSeaTurtleKaiju, + CardId.RadiantheMultidimensionalKaiju, + CardId.OvertexCoatls, + CardId.SouleatingOviraptor, + CardId.UltimateConductorTytanno, + }; + if (Bot.HasInGraveyard(targets)) + { + AI.SelectNextCard(CardId.ShaddollBeast, CardId.ShaddollDragon, CardId.KeeperOfDragonicMagic, CardId.ShaddollSquamata, CardId.SouleatingOviraptor, CardId.Raiden, CardId.Lumina, CardId.ShaddollHedgehog, CardId.AshBlossom, CardId.GhostOgre, CardId.ShaddollFalco, CardId.MaxxC, CardId.PlaguespreaderZombie, CardId.GlowUpBulb, CardId.FairyTailSnow); + } + else + AI.SelectNextCard(CardId.ShaddollBeast, CardId.ShaddollDragon, CardId.KeeperOfDragonicMagic, CardId.ShaddollSquamata, CardId.SouleatingOviraptor, CardId.Raiden, CardId.Lumina, CardId.ShaddollHedgehog, CardId.AshBlossom, CardId.GhostOgre, CardId.ShaddollFalco, CardId.MaxxC, CardId.PlaguespreaderZombie, CardId.GlowUpBulb, CardId.FairyTailSnow); + + AI.SelectThirdCard(new[] { + CardId.UltimateConductorTytanno, + + }); + + return Enemy.GetMonsterCount() >= 1; + } + + + private bool FairyTailSnowsummon() + { + ClientCard target = Util.GetBestEnemyMonster(true, true); + if(target != null) + { + return true; + } + return false; + } + + + private bool FairyTailSnoweff() + { + + if (Card.Location == CardLocation.MonsterZone) + { + AI.SelectCard(Util.GetBestEnemyMonster(true, true)); + return true; + } + else + { + + int spell_count = 0; + IList grave = Bot.Graveyard; + IList all = new List(); + foreach (ClientCard check in grave) + { + if (check.IsCode(CardId.GiantRex)) + { + all.Add(check); + } + } + foreach (ClientCard check in grave) + { + if(check.HasType(CardType.Spell)||check.HasType(CardType.Trap)) + { + spell_count++; + all.Add(check); + } + } + foreach (ClientCard check in grave) + { + if (check.HasType(CardType.Monster)) + { + all.Add(check); + } + } + if (Util.ChainContainsCard(CardId.FairyTailSnow)) return false; + + if ( Duel.Player == 1 && Duel.Phase == DuelPhase.BattleStart && Bot.BattlingMonster == null && Enemy_atk >=Bot.LifePoints || + Duel.Player == 0 && Duel.Phase==DuelPhase.BattleStart && Enemy.BattlingMonster == null && Enemy.LifePoints<=1850 + ) + { + AI.SelectCard(all); + AI.SelectNextCard(Util.GetBestEnemyMonster()); + return true; + } + } + return false; + } + + + private bool SouleatingOviraptoreff() + { + if (!OvertexCoatlseff_used && Bot.GetRemainingCount(CardId.OvertexCoatls, 3) > 0) + { + AI.SelectCard(CardId.OvertexCoatls); + AI.SelectOption(0); + } + else + { + AI.SelectCard(CardId.UltimateConductorTytanno); + AI.SelectOption(1); + } + return true; + } + + private bool GlowUpBulbeff() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + IList check = Bot.GetMonstersInExtraZone(); + foreach (ClientCard monster in check) + if (monster.HasType(CardType.Fusion)) return false; + if (Bot.HasInMonstersZone(CardId.Lumina) || + Bot.HasInMonstersZone(CardId.FairyTailSnow) || + Bot.HasInMonstersZone(CardId.KeeperOfDragonicMagic) || + Bot.HasInMonstersZone(CardId.SouleatingOviraptor) || + Bot.HasInMonstersZone(CardId.GiantRex) || + Bot.HasInMonstersZone(CardId.Raiden) + ) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + return false; + } + + private bool TG_WonderMagicianeff() + { + return true; + } + private bool AllureofDarkness() + { + IList materials = Bot.Hand; + // IList check = new List(); + ClientCard mat = null; + foreach (ClientCard card in materials) + { + if (card.HasAttribute(CardAttribute.Dark)) + { + mat = card; + break; + } + } + if (mat != null) + { + return true; + } + return false; + } + + + private bool Reborneff() + { + if(Bot.HasInGraveyard(CardId.UltimateConductorTytanno)&&Ultimate_ss>0) + { + AI.SelectCard(CardId.UltimateConductorTytanno); + return true; + } + if (!Util.IsOneEnemyBetter(true)) return false; + IList targets = new[] { + CardId.ElShaddollConstruct, + CardId.DogorantheMadFlameKaiju, + CardId.GamecieltheSeaTurtleKaiju, + CardId.SouleatingOviraptor, + }; + if (!Bot.HasInGraveyard(targets)) + { + return false; + } + AI.SelectCard(targets); + return true; + } + + + private bool PotofAvariceeff() + { + return true; + } + + private bool MaxxC() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return Duel.Player == 1; + } + + + private bool SetIsFieldEmpty() + { + return !Bot.IsFieldEmpty(); + } + + + private bool SpellSetZone() + { + return (Bot.GetHandCount()>6 && Duel.Phase==DuelPhase.Main2); + } + + private bool ChargeOfTheLightBrigadeEffect() + { + if (Bot.HasInGraveyard(CardId.Raiden) || Bot.HasInHand(CardId.Raiden)) + AI.SelectCard(CardId.Lumina); + else + AI.SelectCard(CardId.Raiden); + return true; + } + + + // all Shaddoll + private bool SinisterShadowGameseff() + { + if (Bot.HasInGraveyard(CardId.ShaddollFusion)) + AI.SelectCard(CardId.ShaddollCore); + else + AI.SelectCard(new[] + { + CardId.ShaddollBeast, + }); + return true; + } + + + private bool ShaddollCoreeff() + { + if (Card.Location == CardLocation.SpellZone) + { + + if (Duel.Player == 1 && Bot.BattlingMonster == null && Duel.Phase==DuelPhase.BattleStart|| DefaultOnBecomeTarget()) + { + Logger.DebugWriteLine("+++++++++++ShaddollCoreeffdododoo++++++++++"); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + return false; + } + return true; + } + + + private bool ShaddollFusioneff() + { + List extra_zone_check = Bot.GetMonstersInExtraZone(); + foreach (ClientCard extra_monster in extra_zone_check) + if (extra_monster.HasType(CardType.Xyz) || extra_monster.HasType(CardType.Fusion) || extra_monster.HasType(CardType.Synchro)) return false; + + bool deck_check = false; + List monsters = Enemy.GetMonsters(); + foreach (ClientCard monster in monsters) + { + if (monster.HasType(CardType.Synchro) || monster.HasType(CardType.Fusion) || monster.HasType(CardType.Xyz) || monster.HasType(CardType.Link)) + deck_check = true; + } + + if (deck_check) + { + AI.SelectCard( + CardId.ElShaddollConstruct, + CardId.ElShaddollShekhinaga, + CardId.ElShaddollGrysra, + CardId.ElShaddollWinda + ); + AI.SelectNextCard( + CardId.ShaddollSquamata, + CardId.ShaddollBeast, + CardId.ShaddollHedgehog, + CardId.ShaddollDragon, + CardId.ShaddollFalco, + CardId.FairyTailSnow + ); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + + if (Enemy.GetMonsterCount() == 0) + { + int dark_count = 0; + IList m0 = Bot.Hand; + IList m1 = Bot.MonsterZone; + IList all = new List(); + foreach (ClientCard monster in m0) + { + if (dark_count == 2) break; + if (monster.HasAttribute(CardAttribute.Dark)) + { + dark_count++; + all.Add(monster); + } + } + foreach (ClientCard monster in m1) + { + if (dark_count == 2) break; + if (monster != null) + { + if (monster.HasAttribute(CardAttribute.Dark)) + { + dark_count++; + all.Add(monster); + } + } + + + } + if (dark_count == 2) + { + AI.SelectCard(CardId.ElShaddollWinda); + AI.SelectMaterials(all); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + } + if (!Util.IsOneEnemyBetter()) return false; + + + foreach (ClientCard monster in Bot.Hand) + { + if (monster.HasAttribute(CardAttribute.Light)) + { + AI.SelectCard(CardId.ElShaddollConstruct); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + + } + List material_1 = Bot.GetMonsters(); + foreach (ClientCard monster in material_1) + { + if (monster == null) break; + if (monster.HasAttribute(CardAttribute.Light)) + { + AI.SelectCard(CardId.ElShaddollConstruct); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + + } + return false; + + } + + + private bool ElShaddollShekhinagaeff() + { + if (Card.Location != CardLocation.MonsterZone) + return true; + else + { + if (DefaultBreakthroughSkill()) + { + AI.SelectCard( + CardId.ShaddollBeast, + CardId.ShaddollSquamata, + CardId.ShaddollHedgehog, + CardId.ShaddollDragon, + CardId.ShaddollFalco + ); + } + else + return false; + } + return true; + } + + + private bool ElShaddollGrysraeff() + { + if (Card.Location != CardLocation.MonsterZone) + return true; + return true; + } + + + private bool ElShaddollConstructeff() + { + + if (!ShaddollBeast_used) + AI.SelectCard(CardId.ShaddollBeast); + else + AI.SelectCard(CardId.ShaddollFalco); + + return true; + } + + + private bool ShaddollSquamataeff() + { + ShaddollSquamata_used = true; + if (Card.Location != CardLocation.MonsterZone) + { + if(Util.ChainContainsCard(CardId.ElShaddollConstruct)) + { + if (!Bot.HasInHand(CardId.ShaddollFusion) && Bot.HasInGraveyard(CardId.ShaddollFusion)) + AI.SelectNextCard(CardId.ShaddollCore); + if (!ShaddollBeast_used) AI.SelectNextCard(CardId.ShaddollBeast); + else if (!ShaddollFalco_used) AI.SelectNextCard(CardId.ShaddollFalco); + else if(!ShaddollHedgehog_used) AI.SelectNextCard(CardId.ShaddollHedgehog); + } + else + { + if (!Bot.HasInHand(CardId.ShaddollFusion) && Bot.HasInGraveyard(CardId.ShaddollFusion)) + AI.SelectCard(CardId.ShaddollCore); + if (!ShaddollBeast_used) AI.SelectCard(CardId.ShaddollBeast); + else if (!ShaddollFalco_used) AI.SelectCard(CardId.ShaddollFalco); + else if (!ShaddollHedgehog_used) AI.SelectCard(CardId.ShaddollHedgehog); + } + + } + else + { + if (Enemy.GetMonsterCount() == 0) return false; + ClientCard target = Util.GetBestEnemyMonster(); + AI.SelectCard(target); + } + return true; + } + + + private bool ShaddollBeasteff() + { + ShaddollBeast_used = true; + return true; + } + + + private bool ShaddollFalcoeff() + { + ShaddollFalco_used = true; + if (Card.Location != CardLocation.MonsterZone) + return true; + else + { + AI.SelectCard( + CardId.ElShaddollConstruct, + CardId.ElShaddollShekhinaga, + CardId.ElShaddollGrysra, + CardId.ElShaddollWinda, + CardId.ShaddollSquamata + ); + + } + return true; + } + + + private bool ShaddollHedgehogeff() + { + ShaddollHedgehog_used = true; + if (Card.Location != CardLocation.MonsterZone) + { + if (Util.ChainContainsCard(CardId.ElShaddollConstruct)) + { + AI.SelectNextCard( + CardId.ShaddollFalco, + CardId.ShaddollSquamata, + CardId.ShaddollDragon + ); + + } + else + { + AI.SelectCard( + CardId.ShaddollSquamata, + CardId.ShaddollDragon + ); + } + + } + else + { + AI.SelectCard( + CardId.ShaddollFusion, + CardId.SinisterShadowGames + ); + } + return true; + } + + + private bool ShaddollDragoneff() + { + ShaddollDragon_used = true; + if (Card.Location == CardLocation.MonsterZone) + { + ClientCard target = Util.GetBestEnemyCard(); + AI.SelectCard(target); + return true; + } + else + { + if (Enemy.GetSpellCount() == 0) return false; + ClientCard target = Util.GetBestEnemySpell(); + AI.SelectCard(target); + return true; + } + } + + + private bool LostWindeff() + { + if (Card.Location == CardLocation.Grave) + return true; + List check = Enemy.GetMonsters(); + foreach (ClientCard m in check) + { + if (m.Attack>=2000) return DefaultBreakthroughSkill(); + } + return false; + } + + private bool FoolishBurialEffect() + { + if (Bot.GetRemainingCount(CardId.DoubleEvolutionPill, 3) > 0) + { + if (!OvertexCoatlseff_used) + { + AI.SelectCard(new[] + { + CardId.OvertexCoatls, + }); + return true; + } + return false; + } + else + { + AI.SelectCard(CardId.ShaddollSquamata, CardId.FairyTailSnow); + } + return true; + } + + + public bool Hand_act_eff() + { + //if (Card.IsCode(CardId.Urara) && Bot.HasInHand(CardId.LockBird) && Bot.HasInSpellZone(CardId.Re)) return false; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.IsCode(CardId.GhostOgre) && Card.Location == CardLocation.Hand && Bot.HasInMonstersZone(CardId.GhostOgre)) return false; + return (Duel.LastChainPlayer == 1); + } + //other extra + + private bool Michaelsp() + { + IList targets = new[] { + CardId.Raiden, + CardId.Lumina + }; + if (!Bot.HasInMonstersZone(targets)) + return false; + AI.SelectCard(targets); + return true; + } + private bool Michaeleff() + { + if (Card.Location == CardLocation.Grave) + return true; + if (Bot.LifePoints <= 1000) return false; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + ClientCard select = Util.GetBestEnemyCard(); + if (select == null) return false; + if(select!=null) + { + + AI.SelectCard(select); + return true; + } + return false; + } + + private bool MinervaTheExaltedEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (Bot.Deck.Count <= 10) return false; + return true; + } + else + { + IList targets = new List(); + + 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.SelectCard(0); + AI.SelectNextCard(targets); + return true; + } + } + + + public bool CrystronNeedlefibersp() + { + if (Bot.HasInMonstersZone(CardId.ElShaddollConstruct) || + Bot.HasInMonstersZone(CardId.ElShaddollGrysra) || + Bot.HasInMonstersZone(CardId.ElShaddollShekhinaga) || + Bot.HasInMonstersZone(CardId.ElShaddollWinda)) + return false; + + if (CrystronNeedlefibereff_used) return false; + if (Bot.HasInMonstersZone(CardId.CrystronNeedlefiber)) return false; + IList check = new[] + { + CardId.GlowUpBulb, + CardId.FairyTailSnow, + CardId.KeeperOfDragonicMagic, + CardId.SouleatingOviraptor, + CardId.GiantRex, + CardId.Lumina, + CardId.Raiden, + + }; + int count=0; + foreach (ClientCard monster in Bot.GetMonsters()) + if (monster.IsCode(CardId.GlowUpBulb, CardId.FairyTailSnow, CardId.KeeperOfDragonicMagic, + CardId.SouleatingOviraptor, CardId.GiantRex, CardId.Lumina, CardId.Raiden)) + count++; + if (!Bot.HasInMonstersZone(CardId.GlowUpBulb) || count<2) + return false; + AI.SelectCard(check); + AI.SelectNextCard(check); + + return true; + } + + public bool CrystronNeedlefibereff() + { + bool DarkHole = false; + foreach (ClientCard card in Enemy.GetSpells()) + { + if (card.IsCode(53129443) && card.IsFaceup()) + { + DarkHole = true; + } + } + if (Duel.Player == 0) + { + + CrystronNeedlefibereff_used = true; + AI.SelectCard( + CardId.GhostOgre, + CardId.GlowUpBulb, + CardId.PlaguespreaderZombie, + CardId.ShaddollFalco + ); + return true; + } + + else if (DarkHole || Util.IsChainTarget(Card) || Util.GetProblematicEnemySpell() != null) + { + AI.SelectCard(CardId.TG_WonderMagician); + return true; + } + + else if (Duel.Player == 1 && Duel.Phase == DuelPhase.BattleStart && Util.IsOneEnemyBetterThanValue(1500, true)) + { + AI.SelectCard(CardId.TG_WonderMagician); + if (Util.IsOneEnemyBetterThanValue(1900, true)) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + } + else + { + AI.SelectPosition(CardPosition.FaceUpAttack); + } + return true; + } + return false; + } + + private bool ScarlightRedDragonsp() + { + return false; + } + + private bool ScarlightRedDragoneff() + { + IList targets = new List(); + ClientCard target1 = Util.GetBestEnemyMonster(); + if (target1 != null) + { + targets.Add(target1); + AI.SelectCard(targets); + return true; + } + return false; + } + + + private bool CrystalWingSynchroDragoneff() + { + return Duel.LastChainPlayer != 0; + } + + private bool Sdulldeateff() + { + /* if (snake_four_s) + { + snake_four_s = false; + AI.SelectCard(Useless_List()); + return true; + } + //if (ActivateDescription == Util.GetStringId(CardId.snake, 2)) return true; + if (ActivateDescription == Util.GetStringId(CardId.snake, 1)) + { + foreach (ClientCard hand in Bot.Hand) + { + if (hand.IsCode(CardId.Red, CardId.Pink)) + { + AI.SelectCard(hand); + return true; + } + if (hand.IsCode(CardId.Urara, CardId.Ghost)) + { + if (Tuner_ss()) + { + AI.SelectCard(hand); + return true; + } + } + } + }*/ + return false; + } + + private bool BlackRoseMoonlightDragoneff() + { + IList targets = new List(); + ClientCard target1 = Util.GetBestEnemyMonster(); + if (target1 != null) + { + targets.Add(target1); + AI.SelectCard(targets); + return true; + } + return false; + + } + + private bool RedWyvernsp() + { + return false; + } + + private bool RedWyverneff() + { + IList check = Enemy.GetMonsters(); + ClientCard best = null; + foreach (ClientCard monster in check) + { + if (monster.Attack >= 2400) best = monster; + } + if (best != null) + { + AI.SelectCard(best); + return true; + } + return false; + } + + private bool CoralDragoneff() + { + if (Card.Location != CardLocation.MonsterZone) + return true; + IList targets = new List(); + + ClientCard target1 = Util.GetBestEnemyMonster(); + if (target1 != null) + targets.Add(target1); + ClientCard target2 = Util.GetBestEnemySpell(); + if (target2 != null) + targets.Add(target2); + else if (Util.IsChainTarget(Card) || Util.GetProblematicEnemySpell() != null) + { + AI.SelectCard(targets); + return true; + } + else if (Duel.Player == 1 && Duel.Phase == DuelPhase.BattleStart && Util.IsOneEnemyBetterThanValue(2400, true)) + { + AI.SelectCard(targets); + return true; + } + return false; + } + + public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + if (!defender.IsMonsterHasPreventActivationEffectInBattle()) + { + if (attacker.IsCode(CardId.ElShaddollConstruct) && !attacker.IsDisabled()) // TODO: && defender.IsSpecialSummoned + attacker.RealPower = 9999; + if (attacker.IsCode(CardId.UltimateConductorTytanno) && !attacker.IsDisabled() && defender.IsDefense()) + attacker.RealPower = 9999; + } + return base.OnPreBattleBetween(attacker, defender); + } + + public override bool OnSelectHand() + { + return true; + } + /* + private bool GoblindberghSummon() + { + foreach (ClientCard card in Bot.Hand.GetMonsters()) + { + if (!card.Equals(Card) && card.Level == 4) + return true; + } + return false; + }*/ + + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LuckyExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LuckyExecutor.cs new file mode 100644 index 0000000..d467454 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/LuckyExecutor.cs @@ -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 HintMsgForEnemy = new List + { + HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck, + HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Disable + }; + + private List HintMsgForDeck = new List + { + HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.Remove, HintMsg.AddToHand, HintMsg.FusionMaterial + }; + + private List HintMsgForSelf = new List + { + HintMsg.Equip + }; + + private List HintMsgForMaterial = new List + { + HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Release + }; + + private List HintMsgForMaxSelect = new List + { + HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.AddToHand, HintMsg.FusionMaterial, HintMsg.Destroy + }; + + public override IList OnSelectCard(IList _cards, int min, int max, int hint, bool cancelable) + { + if (Duel.Phase == DuelPhase.BattleStart) + return null; + if (AI.HaveSelectedCards()) + return null; + + IList selected = new List(); + IList cards = new List(_cards); + if (max > cards.Count) + max = cards.Count; + + if (HintMsgForEnemy.Contains(hint)) + { + IList 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 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 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 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 options) + { + return Program.Rand.Next(options.Count); + } + + public override CardPosition OnSelectPosition(int cardId, IList 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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MalissExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MalissExecutor.cs new file mode 100644 index 0000000..de28b2e --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MalissExecutor.cs @@ -0,0 +1,4216 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; +using YGOSharp.Network.Enums; +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Maliss", "AI_Maliss")] + public class MalissExecutor : DefaultExecutor + { + public class CardId + { + public const int DominusImpulse = 40366667; + public const int TERRAFORMING = 73628505; + //public const int AllureOfDarkness = 1475311; + public const int GoldSarcophagus = 75500286; + + // Cyberse / utility + public const int BackupIgnister = 30118811; + public const int WizardIgnister = 3723262; + + // Main Maliss pieces + public const int MalissP_Dormouse = 32061192; // Maliss

Dormouse + public const int MalissP_WhiteRabbit = 69272449; // Maliss

White Rabbit + public const int MalissP_ChessyCat = 96676583; // Maliss

Chessy Cat + public const int MalissP_MarchHare = 20938824; // Maliss

March Hare + public const int MalissC_GWC06 = 20726052; // Maliss GWC-06 + //public const int MalissC_TB11 = 57111661; // Maliss TB-11 + public const int MalissC_MTP07 = 94722358; // Maliss MTP-07 + public const int MalissQ_RedRansom = 68059897; // Maliss Red Ransom + public const int MalissQ_WhiteBinder = 95454996; // Maliss White Binder + public const int MalissQ_HeartsCrypter = 21848500; // Maliss Hearts Crypter + public const int MalissInTheMirror = 93453053; // Maliss in the Mirror (Spell) + public const int MalissInUnderground = 68337209; // Maliss in Underground + + + // === Extra Deck === + public const int Linguriboh = 24842059; + public const int LinkDecoder = 30342076; + public const int SP_LITTLE_KNIGHT = 29301450; + public const int SALAMANGREAT_ALMIRAJ = 60303245; + public const int SplashMage = 59859086; // Splash Mage + public const int CyberseWicckid = 52698008; // Cyberse Wicckid + public const int TranscodeTalker = 46947713; // Transcode Talker + public const int AlliedCodeTalkerIgnister = 39138610; // Allied Code Talker @Ignister + public const int FirewallDragon = 5043010; // Firewall Dragon + public const int LinkSpider = 98978921; // Link Spider + public const int HaggardLizardose = 9763474; // Haggard Lizardose + public const int AccesscodeTalker = 86066372; // Accesscode Talker + public const int Apollousa = 4280258; + + // === Handtraps / Others (blacklist/targets etc.) === + public const int Lancea = 34267821; + public const int Fuwalos = 42141493; + public const int NaturalExterio = 99916754; + public const int NaturalBeast = 33198837; + public const int ImperialOrder = 61740673; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecree = 51452091; + public const int Number41BagooskatheTerriblyTiredTapir = 90590303; + public const int InspectorBoarder = 15397015; + public const int SkillDrain = 82732705; + public const int DivineArsenalAAZEUS_SkyThunder = 90448279; + public const int DimensionShifter = 91800273; + public const int MacroCosmos = 30241314; + public const int DimensionalFissure = 81674782; + public const int BanisheroftheRadiance = 94853057; + public const int BanisheroftheLight = 61528025; + public const int KashtiraAriseHeart = 48626373; + public const int GhostMournerMoonlitChill = 52038441; + public const int NibiruThePrimalBeing = 27204311; + } + const int SetcodeMaliss = 0x1bf; + const int SetcodeTimeLord = 0x4a; + const int SetcodePhantom = 0xdb; + const int SetcodeOrcust = 0x11b; + const int SetcodeHorus = 0x19d; + const int SetcodeDarkWorld = 0x6; + const int SetcodeSkyStriker = 0x115; + + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.MalissP_ChessyCat, CardId.MalissP_MarchHare,CardId.MalissP_WhiteRabbit,CardId.MalissInUnderground, + CardId.BackupIgnister, CardId.MalissP_Dormouse, + _CardId.AshBlossom,_CardId.InfiniteImpermanence,CardId.DominusImpulse } }, + {2, new List { _CardId.MaxxC, _CardId.CalledByTheGrave}}, + {1, new List { CardId.GoldSarcophagus, CardId.TERRAFORMING, + CardId.MalissC_GWC06, CardId.Lancea, CardId.MalissC_MTP07, + _CardId.CrossoutDesignator, CardId.MalissInTheMirror, CardId.WizardIgnister, + CardId.NibiruThePrimalBeing }} + }; + + List notToNegateIdList = new List { 58699500, 20343502, 19403423 }; + List notToDestroySpellTrap = new List { 50005218, 6767771 }; + List targetNegateIdList = new List { + _CardId.EffectVeiler, _CardId.InfiniteImpermanence, CardId.GhostMournerMoonlitChill, _CardId.BreakthroughSkill, 74003290, 67037924, + 9753964, 66192538, 23204029, 73445448, 35103106, 30286474, 45002991, 5795980, 38511382, 53742162, 30430448 + }; + + public MalissExecutor(GameAI ai, Duel duel) : base(ai, duel) + { + // Must Set First + AddExecutor(ExecutorType.SpellSet, CardId.MalissC_GWC06, SpellSetCheck); + AddExecutor(ExecutorType.SpellSet, CardId.MalissC_MTP07, SpellSetCheck); + + + AddExecutor(ExecutorType.Activate, CardId.AccesscodeTalker, Accesscode_OnSummon_AtkUp); + AddExecutor(ExecutorType.Activate, CardId.AccesscodeTalker, Accesscode_Destroy_Ignition); + + // ===== Generic counters ===== + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossomActivate); + AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, CalledbytheGraveActivate); + AddExecutor(ExecutorType.Activate, _CardId.CrossoutDesignator, CrossoutDesignatorActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, CardId.Apollousa, DontSelfNG); + AddExecutor(ExecutorType.Activate, CardId.DominusImpulse, DontSelfNG); + AddExecutor(ExecutorType.Activate, CardId.AlliedCodeTalkerIgnister, Allied_NegateBanish); + AddExecutor(ExecutorType.Activate, CardId.FirewallDragon, FirewallBounce_OnOppSummon); + AddExecutor(ExecutorType.Activate, CardId.MalissC_MTP07, MTP07_OppTurn_RemoveEnemyOnly); + AddExecutor(ExecutorType.Activate, CardId.MalissQ_HeartsCrypter, HC_Quick_ReturnBanished_AndBanishField); + AddExecutor(ExecutorType.Activate, CardId.MalissC_GWC06, GWC06_OppTurn_ReviveWB_HC); + AddExecutor(ExecutorType.Activate, CardId.SP_LITTLE_KNIGHT, ActLittleKnight); + + + AddExecutor(ExecutorType.Activate, CardId.MalissQ_RedRansom, RR_SS_FromBanished); + AddExecutor(ExecutorType.Activate, CardId.MalissQ_HeartsCrypter, HC_OnBanished_SpecialSummon); + AddExecutor(ExecutorType.Activate, CardId.MalissInTheMirror, Mirror_Banish); + + // Plan#1 + // --- Start with Dormouse --- + AddExecutor(ExecutorType.Summon, CardId.MalissP_Dormouse, Step1_Dormouse_NormalSummon); + AddExecutor(ExecutorType.Summon, CardId.MalissP_WhiteRabbit, Step1_WhiteRabbit_NormalSummon); + AddExecutor(ExecutorType.Summon, CardId.MalissP_ChessyCat, TwoCC_NormalSummon); + AddExecutor(ExecutorType.Summon, CardId.MalissP_ChessyCat, Emergency_NormalCat); + AddExecutor(ExecutorType.Summon, CardId.MalissP_MarchHare, NSMH); + AddExecutor(ExecutorType.Summon, CardId.BackupIgnister, NSBackup_L); + AddExecutor(ExecutorType.Summon, CardId.BackupIgnister, NSBackup); + AddExecutor(ExecutorType.Activate, CardId.MalissP_Dormouse, Dormouse_SS_FromBanished); + AddExecutor(ExecutorType.Activate, CardId.MalissP_Dormouse, Dormouse_ForMH); + AddExecutor(ExecutorType.Activate, CardId.MalissP_Dormouse, Dormouse_Banish_Anytime); + AddExecutor(ExecutorType.Activate, CardId.MalissP_WhiteRabbit, Step1_WhiteRabbit_SS_FromBanished); + AddExecutor(ExecutorType.Activate, CardId.MalissP_WhiteRabbit, Step1_WhiteRabbit_SetTrapOnSummon); + AddExecutor(ExecutorType.Activate, CardId.MalissP_MarchHare, Step1_MH_FromHand); + AddExecutor(ExecutorType.Activate, CardId.MalissP_MarchHare, returnFromBanish); + AddExecutor(ExecutorType.SpSummon, CardId.Linguriboh, LinguribohMHLine); + AddExecutor(ExecutorType.SpSummon, CardId.LinkDecoder, Step1_SSLinkDecoder); + AddExecutor(ExecutorType.SpSummon, CardId.MalissQ_RedRansom, Step2N_LinkSummon_RedRansom); + AddExecutor(ExecutorType.SpSummon, CardId.MalissQ_RedRansom, Step2_LinkSummon_RedRansom); + AddExecutor(ExecutorType.Activate, CardId.MalissQ_RedRansom, Step2_RedRansom_Search); + AddExecutor(ExecutorType.Activate, CardId.MalissP_ChessyCat, AnyDraw); + AddExecutor(ExecutorType.SpSummon, CardId.Apollousa, Link_Apo); + AddExecutor(ExecutorType.SpSummon, CardId.CyberseWicckid, Step2N_RRtoWicckid); + AddExecutor(ExecutorType.SpSummon, CardId.LinkDecoder, Step_SummonLinkDecoderToWicckid); + AddExecutor(ExecutorType.Activate, CardId.CyberseWicckid, Wicckid_SearchTuner); + AddExecutor(ExecutorType.SpSummon, CardId.SplashMage, Step_SplashToWB); + AddExecutor(ExecutorType.Activate, CardId.SplashMage, Step2N_SplashMage_ReviveP); + AddExecutor(ExecutorType.Activate, CardId.BackupIgnister, Flow3_BackupIgnister_AfterMakeIt3); + AddExecutor(ExecutorType.Activate, CardId.BackupIgnister, OneBody_Backup_SearchWizard); + AddExecutor(ExecutorType.SpSummon, CardId.MalissQ_WhiteBinder, Step2N_LinkSummon_WB); + AddExecutor(ExecutorType.Activate, CardId.MalissQ_WhiteBinder, WB_OnSummon_BanishGY); + AddExecutor(ExecutorType.Activate, CardId.MalissC_GWC06, GWC06_MyTurn_Extend); + AddExecutor(ExecutorType.Activate, CardId.MalissQ_WhiteBinder, WB_SetMalissTrap); + + // === STEP2: 2 bodies -> Splash Mage -> revive P -> Red Ransom -> search === + AddExecutor(ExecutorType.Activate, CardId.WizardIgnister, Step2_Fallback_Wizard_AfterSplashNegated); + AddExecutor(ExecutorType.Activate, CardId.BackupIgnister, Step2_Fallback_Backup_AfterSplashNegated); + + AddExecutor(ExecutorType.Activate, CardId.WizardIgnister, Flow3_WizardIgnister_AfterMakeIt3); + AddExecutor(ExecutorType.Activate, CardId.MalissQ_WhiteBinder, WB_OnBanished_SelfSS); + AddExecutor(ExecutorType.Activate, CardId.MalissP_MarchHare, ssFromHandMH); + AddExecutor(ExecutorType.SpSummon, CardId.MalissQ_HeartsCrypter, Step_LinkSummon_HeartsCrypter); + AddExecutor(ExecutorType.SpSummon, CardId.AlliedCodeTalkerIgnister, Flow3_Link_Allied); + AddExecutor(ExecutorType.Activate, CardId.AlliedCodeTalkerIgnister, Allied_OnSummonTrigger); + + // Plan#2 White Rabbit --- + AddExecutor(ExecutorType.Activate, CardId.MalissC_MTP07, MTP07_ForMH); + AddExecutor(ExecutorType.SpSummon, CardId.FirewallDragon, Flow3_Link_Firewall); + AddExecutor(ExecutorType.SpSummon, CardId.MalissQ_WhiteBinder, Step_WicckidPlusOneToWB); + AddExecutor(ExecutorType.Activate, CardId.MalissP_ChessyCat, ChessyCat_SS_FromBanished); + + + AddExecutor(ExecutorType.SpSummon, CardId.CyberseWicckid, Step_RRtoWicckid); + AddExecutor(ExecutorType.Activate, CardId.MalissInUnderground, Flow3_UnderGround_Available_SSAnyPawn); + AddExecutor(ExecutorType.Activate, CardId.LinkDecoder, LinkDecoder_ReviveFromGY); + + // Fallback Lancea + AddExecutor(ExecutorType.SpSummon, CardId.TranscodeTalker, SummonTranscode); + AddExecutor(ExecutorType.Activate, CardId.TranscodeTalker, Transcode_ReviveLink3OrLower); + + // Emergency Start + AddExecutor(ExecutorType.Activate, CardId.TERRAFORMING, Terra_GrabUnderground); + AddExecutor(ExecutorType.Activate, CardId.GoldSarcophagus, GoldSarc_StartPiece); + AddExecutor(ExecutorType.Activate, CardId.MalissInUnderground, Underground_ActivateStarter); + + AddExecutor(ExecutorType.SpSummon, CardId.SplashMage, Step_SplashToRR); + AddExecutor(ExecutorType.Activate, CardId.SplashMage, Step2_SplashMage_ReviveP); + + // Fallback: Try to Start + AddExecutor(ExecutorType.SpSummon, CardId.LinkSpider); + AddExecutor(ExecutorType.Summon, _CardId.AshBlossom, Emergency_NS); + AddExecutor(ExecutorType.Summon, _CardId.MaxxC, Emergency_NS); + AddExecutor(ExecutorType.SpSummon, CardId.Linguriboh, OneBody_Link1_Linguriboh); + AddExecutor(ExecutorType.SpSummon, CardId.SALAMANGREAT_ALMIRAJ, OneBody_Link1_Almiraj); + AddExecutor(ExecutorType.Activate, CardId.BackupIgnister, OneBody_Backup_SS); + AddExecutor(ExecutorType.Activate, CardId.BackupIgnister, OneBody_Backup_SearchWizard); + AddExecutor(ExecutorType.Activate, CardId.WizardIgnister, OneBody_Wizard_SS); + + + //Finisher + AddExecutor(ExecutorType.SpSummon, CardId.AccesscodeTalker, Flow3_Link_Accesscode); + + // Turn3 or More + AddExecutor(ExecutorType.SpSummon, CardId.Linguriboh, T3Allow); + AddExecutor(ExecutorType.SpSummon, CardId.SALAMANGREAT_ALMIRAJ, T3Allow); + AddExecutor(ExecutorType.SpSummon, CardId.TranscodeTalker, EmerTranscode); + AddExecutor(ExecutorType.SpSummon, CardId.AlliedCodeTalkerIgnister, Emer_Allied); + AddExecutor(ExecutorType.SpSummon, CardId.AlliedCodeTalkerIgnister, Emer_Allied2); + + // >>> Fallback: S:P Little Knight + AddExecutor(ExecutorType.SpSummon, CardId.SP_LITTLE_KNIGHT, SummonLittleKnightFast); + AddExecutor(ExecutorType.SpSummon, CardId.SP_LITTLE_KNIGHT, SPEmer); + + AddExecutor(ExecutorType.SpellSet, SpellSetCheck); + AddExecutor(ExecutorType.Repos, MonsterRepos); + + } + // Maliss Flags + bool usedNormalSummon = false; + bool ssDormouse = false; + bool ssWhiteRabbit = false; + bool ssChessyCat = false; + bool ssMarchHare = false; + bool ActiveMarchHare = false; + bool ssRRThisTurn = false; + bool ssWBThisTurn = false; + bool ssHCThisTurn = false; + bool enemyActivateLancea = false; + bool enemyActivateFuwalos = false; + bool ActiveUnderground = false; + bool blockWicckid = false; + bool mtp07SetThisTurn = false; + bool gwc06SetThisTurn = false; + bool splashNegatedThisTurn = false; + bool Allied_End = false; + bool fullBoard1 = false; + bool goldstart = false; + bool undergroundstart = false; + bool nsplan = false; + bool nsBackupplan = false; + bool NSDorMouse = false; + bool nsLanceaplan = false; + + int myTurnCount = 0; + bool avoidLinkedZones = false; + bool wantLinkedToWicckid = false; + private int? _wicckidEmzIndex = null; + private int _transcodeZoneMask = 0; + + const int MZ0 = 1 << 0; + const int MZ1 = 1 << 1; + const int MZ2 = 1 << 2; + const int MZ3 = 1 << 3; + const int MZ4 = 1 << 4; + const int EMZ_L = (1 << 5); + const int EMZ_R = (1 << 6); + const int EMZ_ALL = EMZ_L | EMZ_R; + int _wicckidEmzBit = 0; + int _forceTranscodeBit = 0; + + // Step Flag + bool step1Done = false; + bool step2Done = false; + int lastRevivedIdBySplash = 0; + bool coreSetupComplete = false; + bool madeIt3 = false; + bool resultSuccessFlag = false; + private bool _didSplashToRR; + private bool _didRRtoWicckid; + private bool _didSummonToWicckidArrow; + private bool _didWBFromWicckid; + private bool _finishPlanDecided; + private bool _preferWicckidArrows; + private bool _rrSelfSSPlacing = false; + private enum FinishPlan { FW_HC_Allied, HC_Allied, AlliedOnly } + private FinishPlan _finishPlan; + static bool IsEmzSeq(int seq) => seq >= 5; + static int BitOfSeq(int seq) => (1 << seq); + static int LowestBit(int m) => m & -m; + + private bool _oppJustActivatedPersistentSpell; + private bool _oppJustSummoned; + private bool _oppJustSet; + private int _prefWindowTTL; + + private int _enemyMonsterCountSnap; + private int _enemyFacedownSTSnap; + + //==================== Default code ==================== + #region Default Code Start Here + private int _totalAttack; + private int _totalBotAttack; + bool enemyActivateMaxxC = false; + bool enemyActivateLockBird = false; + int dimensionShifterCount = 0; + bool enemyActivateInfiniteImpermanenceFromHand = false; + List infiniteImpermanenceList = new List(); + List currentNegateCardList = new List(); + List currentDestroyCardList = new List(); + List sendToGYThisTurn = new List(); + List activatedCardIdList = new List(); + List enemyPlaceThisTurn = new List(); + List escapeTargetList = new List(); + List summonThisTurn = new List(); + + + public List ShuffleList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(result.Count); + int nextIndex = (index + Program.Rand.Next(result.Count - 1)) % result.Count; + T tempCard = result[index]; + result[index] = result[nextIndex]; + result[nextIndex] = tempCard; + } + return result; + } + + public override bool OnSelectHand() { return true; } + + public List ShuffleCardList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(n + 1); + ClientCard temp = result[index]; + result[index] = result[n]; + result[n] = temp; + } + return result; + } + + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) + { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + public bool MonsterRepos() + { + int selfAttack = Card.Attack + 1; + + if (selfAttack <= 1) + return !Card.IsDefense(); + + int bestAttack = 0; + foreach (ClientCard card in Bot.GetMonsters()) + { + int attack = card.Attack; + if (attack >= bestAttack) + { + bestAttack = attack; + } + } + + bool enemyBetter = Util.IsAllEnemyBetterThanValue(bestAttack, true); + + if (Card.IsAttack() && enemyBetter) + return true; + if (Card.IsDefense() && !enemyBetter) + return true; + return false; + } + + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && Bot.GetMonsters().Any(card => card.IsFaceup())) + { + return true; + } + return false; + } + + public bool CheckInDanger() + { + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + int totalAtk = 0; + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (m.IsAttack() && !m.Attacked) totalAtk += m.Attack; + } + if (totalAtk >= Bot.LifePoints) return true; + } + return false; + } + private int GetMyLinkedMMZMask() + { + int mask = 0; + foreach (var m in Bot.GetMonsters()) + { + if (m == null || !m.IsFaceup() || !m.HasType(CardType.Link)) continue; + mask |= m.GetLinkedZones(); + } + mask &= 0x1F; + return mask; + } + private bool IsPawnId(int id) + { + return id == CardId.MalissP_Dormouse + || id == CardId.MalissP_WhiteRabbit + || id == CardId.MalissP_ChessyCat + || id == CardId.MalissP_MarchHare; + } + private int GetQueenLinkedMMZMask() + { + int mask = 0; + foreach (var m in Bot.GetMonsters()) + { + if (m == null || !m.IsFaceup()) continue; + + if (m.IsCode(CardId.MalissQ_RedRansom) + || m.IsCode(CardId.MalissQ_WhiteBinder) + || m.IsCode(CardId.MalissQ_HeartsCrypter)) + { + mask |= m.GetLinkedZones(); + } + } + mask &= 0x1F; + return mask; + } + + private int LinkValOf(ClientCard c) + { + return c.HasType(CardType.Link) ? Math.Max(1, c.LinkCount) : 1; + } + + private bool IsOneVal(ClientCard c) + { + return !c.HasType(CardType.Link) || Math.Max(1, c.LinkCount) == 1; + } + + private bool IsMaliss(ClientCard c) + { + return c.HasSetcode(0x1bf); + } + + private int ScoreForBanishedMaliss(ClientCard c) + { + if (c.IsCode(CardId.MalissInTheMirror)) return 100; + if (c.IsCode(CardId.MalissC_MTP07)) return 95; + if (c.IsCode(CardId.MalissC_GWC06)) return 90; + if (c.IsCode(CardId.MalissInUnderground)) return 85; + if (c.IsCode(CardId.MalissP_MarchHare)) return 80; + if (c.IsCode(CardId.MalissP_ChessyCat)) return 75; + if (c.IsCode(CardId.MalissP_WhiteRabbit)) return 70; + if (c.IsCode(CardId.MalissP_Dormouse)) return 65; + return 50; + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location == CardLocation.MonsterZone) + { + int MAIN_MASK = + (int)Zones.z0 | + (int)Zones.z1 | + (int)Zones.z2 | + (int)Zones.z3 | + (int)Zones.z4; + + int emzMask = available & ~MAIN_MASK; + int mainMask = available & MAIN_MASK; + if (IsPawnId(cardId)) + { + int queenMask = GetQueenLinkedMMZMask(); + int queenChoices = queenMask & available & MAIN_MASK; + + if (queenChoices != 0) + { + int pick = FirstBitFromOrder( + queenChoices, + new[] { (int)Zones.z2, (int)Zones.z1, (int)Zones.z3, (int)Zones.z0, (int)Zones.z4 } + ); + AI.SelectPlace(pick); + return pick; + } + } + if (cardId == CardId.AlliedCodeTalkerIgnister) + { + var fw = Bot.MonsterZone.GetFirstMatchingCard(m => m != null && m.IsCode(CardId.FirewallDragon)); + int emzAvail = available & EMZ_ALL; + + if (fw != null && fw.IsFaceup()) + { + bool firewallCenter = fw.Controller == 0 && fw.Location == CardLocation.MonsterZone && fw.Sequence == 2; + + int linkedAll = fw.GetLinkedZones(); + int linkedChoices = linkedAll & available; + + int linkedEmzChoices = linkedChoices & EMZ_ALL; + int pick; + + if (linkedEmzChoices != 0) + { + if (firewallCenter && (linkedEmzChoices & EMZ_L) != 0 && (linkedEmzChoices & EMZ_R) != 0) + { + int leftFree = 0; + if ((available & (int)Zones.z0) != 0) leftFree++; + if ((available & (int)Zones.z1) != 0) leftFree++; + + int rightFree = 0; + if ((available & (int)Zones.z3) != 0) rightFree++; + if ((available & (int)Zones.z4) != 0) rightFree++; + + if (leftFree > rightFree) + pick = EMZ_L; + else if (rightFree > leftFree) + pick = EMZ_R; + else + pick = FirstBitFromOrder(linkedEmzChoices, new[] { EMZ_L, EMZ_R }); + } + else + { + pick = FirstBitFromOrder(linkedEmzChoices, new[] { EMZ_L, EMZ_R }); + } + AI.SelectPlace(pick); + return pick; + } + if (emzAvail != 0) + { + if (firewallCenter && (emzAvail & EMZ_L) != 0 && (emzAvail & EMZ_R) != 0) + { + int leftFree = 0; + if ((available & (int)Zones.z0) != 0) leftFree++; + if ((available & (int)Zones.z1) != 0) leftFree++; + + int rightFree = 0; + if ((available & (int)Zones.z3) != 0) rightFree++; + if ((available & (int)Zones.z4) != 0) rightFree++; + + if (leftFree > rightFree) + pick = EMZ_L; + else if (rightFree > leftFree) + pick = EMZ_R; + else + pick = FirstBitFromOrder(emzAvail, new[] { EMZ_L, EMZ_R }); + } + else + { + pick = FirstBitFromOrder(emzAvail, new[] { EMZ_L, EMZ_R }); + } + + AI.SelectPlace(pick); + return pick; + } + if (linkedChoices != 0) + { + pick = FirstBitFromOrder( + linkedChoices, + new[] { (int)Zones.z2, (int)Zones.z1, (int)Zones.z3, (int)Zones.z0, (int)Zones.z4 } + ); + AI.SelectPlace(pick); + return pick; + } + } + int emzOnly = available & EMZ_ALL; + if (emzOnly != 0) + { + int pick = FirstBitFromOrder(emzOnly, new[] { EMZ_L, EMZ_R }); + AI.SelectPlace(pick); + return pick; + } + return PreferSafeSummonZones(available); + } + if (cardId == CardId.CyberseWicckid) + { + int picked = ChooseAndRememberWicckidEmz(available); + if (picked != 0) return picked; + return 0; + } + if (cardId == CardId.TranscodeTalker) + { + int wanted = _forceTranscodeBit != 0 ? _forceTranscodeBit : _wicckidEmzBit; + + if (wanted != 0 && (available & wanted) != 0) + return wanted; + + int anyEmz = available & EMZ_ALL; + if (anyEmz != 0) + return (anyEmz & EMZ_L) != 0 ? EMZ_L : EMZ_R; + + return 0; + } + if (cardId == CardId.MalissQ_RedRansom && _rrSelfSSPlacing) + { + int prefer = (int)Zones.z1 | (int)Zones.z3; + int wmask = GetLinkedMaskFor(GetWicckid()); + int choices = (available & prefer) & ~wmask; + if (choices != 0) + { + int pick = FirstBitFromOrder(choices, new[] { (int)Zones.z1, (int)Zones.z3 }); + AI.SelectPlace(pick); + _rrSelfSSPlacing = false; + return pick; + } + } + if (cardId == CardId.LinkDecoder) + { + var trans = Bot.MonsterZone.GetFirstMatchingCard(m => m != null && m.IsCode(CardId.TranscodeTalker)); + int tmask = GetLinkedMaskFor(trans) & 0x1F; + int safe = (available & 0x1F) & ~tmask; + if (safe != 0) + { + int pick = FirstBitFromOrder(safe, new[] { (int)Zones.z2, (int)Zones.z1, (int)Zones.z3, (int)Zones.z0, (int)Zones.z4 }); + AI.SelectPlace(pick); + return pick; + } + } + if (cardId == CardId.FirewallDragon) + { + var trans = Bot.MonsterZone.GetFirstMatchingCard(m => m != null && m.IsCode(CardId.TranscodeTalker)); + int underTrans = 0; + if (trans != null) + { + int tmask = GetLinkedMaskFor(trans) & 0x1F; + if ((tmask & (int)Zones.z1) != 0) underTrans |= (int)Zones.z1; + if ((tmask & (int)Zones.z3) != 0) underTrans |= (int)Zones.z3; + } + int choices = (available & underTrans); + if (choices != 0) + { + int pick = FirstBitFromOrder(choices, new[] { (int)Zones.z1, (int)Zones.z3 }); + AI.SelectPlace(pick); + return pick; + } + } + + if (cardId == CardId.TranscodeTalker || + cardId == CardId.AccesscodeTalker || + cardId == CardId.AlliedCodeTalkerIgnister || + cardId == CardId.MalissQ_WhiteBinder || + cardId == CardId.MalissQ_HeartsCrypter) + { + return PreferSafeSummonZones(available); + } + int linked = (GetMyLinkedMMZMask() & available) & 0x1F; + int unlinked = (available & 0x1F) & ~linked; + + int choose; + if (avoidLinkedZones && unlinked != 0) + choose = LowestBit(unlinked); // Not linked zone + else if (linked != 0) + choose = LowestBit(linked); // Default + else + choose = LowestBit(available & 0x1F); + + AI.SelectPlace(choose); + return choose; + } + SelectSTPlace(Card, true); + return base.OnSelectPlace(cardId, player, location, available); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2) + { + bool turnDefense = false; + if (cardData.Attack <= cardData.Defense) + { + turnDefense = true; + } + if (turnDefense) + { + return CardPosition.FaceUpDefence; + } + } + if (Duel.Player == 1) + { + if (cardData.Defense >= cardData.Attack || Util.IsOneEnemyBetterThanValue(cardData.Attack, true)) + { + return CardPosition.FaceUpDefence; + } + } + int cardAttack = cardData.Attack; + int bestBotAttack = Math.Max(Util.GetBestAttack(Bot), cardAttack); + if (Util.IsAllEnemyBetterThanValue(bestBotAttack, true)) + { + return CardPosition.FaceUpDefence; + } + } + return base.OnSelectPosition(cardId, positions); + } + + public bool AshBlossomActivate() + { + if (CheckWhetherNegated(true) || !CheckLastChainShouldNegated()) return false; + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + if (CheckAtAdvantage() && Duel.Turn > 1) + { + return false; + } + } + return DefaultAshBlossomAndJoyousSpring(); + } + + public bool MaxxCActivate() + { + if (CheckWhetherNegated(true) || Duel.LastChainPlayer == 0) return false; + return DefaultMaxxC(); + } + + public bool InfiniteImpermanenceActivate() + { + if (CheckWhetherNegated()) return false; + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (m.IsMonsterShouldBeDisabledBeforeItUseEffect() && !m.IsDisabled() && Duel.LastChainPlayer != 0) + { + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(m); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || (Util.IsChainTarget(Card)) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true); + List enemyMonsters = Enemy.GetMonsters(); + AI.SelectCard(target); + infiniteImpermanenceList.Add(this_seq); + return true; + } + } + if ((LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || LastChainCard.IsDisabled() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget())) + return false; + + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemyMonsters = Enemy.GetMonsters(); + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + foreach (ClientCard card in enemyMonsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + return true; + } + } + } + return true; + } + + public bool CrossoutDesignatorActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard() != null) + { + int code = Util.GetLastChainCard().Id; + int alias = Util.GetLastChainCard().Alias; + if (alias != 0 && alias - code < 10) code = alias; + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + if (CheckRemainInDeck(code) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectAnnounceID(code); + currentNegateCardList.AddRange(Enemy.MonsterZone.Where(c => c != null && c.IsFaceup() && c.IsCode(code))); + return true; + } + } + return false; + } + + public bool CalledbytheGraveActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) + { + return false; + } + if (Duel.LastChainPlayer == 1) + { + if (Util.GetLastChainCard().IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + if (Util.GetLastChainCard().IsCode(_CardId.MaxxC) && CheckAtAdvantage() && Duel.Turn > 1) + { + return false; + } + ClientCard graveTarget = Enemy.Graveyard.GetFirstMatchingCard(card => card.IsMonster() && card.GetOriginCode() == code); + if (graveTarget != null) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(graveTarget); + currentDestroyCardList.Add(graveTarget); + return true; + } + } + + foreach (ClientCard graveCard in Enemy.Graveyard) + { + if (Duel.ChainTargets.Contains(graveCard) && graveCard.IsMonster()) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + int code = graveCard.Id; + AI.SelectCard(graveCard); + currentDestroyCardList.Add(graveCard); + return true; + } + } + + if (Duel.ChainTargets.Contains(Card)) + { + List enemyMonsters = Enemy.Graveyard.GetMatchingCards(card => card.IsMonster()).ToList(); + if (enemyMonsters.Count > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + int code = enemyMonsters[0].Id; + AI.SelectCard(code); + currentDestroyCardList.Add(enemyMonsters[0]); + return true; + } + } + } + + if (Duel.LastChainPlayer == 1) return false; + List targets = GetDangerousCardinEnemyGrave(true); + if (targets.Count > 0) + { + int code = targets[0].Id; + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(code); + currentDestroyCardList.Add(targets[0]); + return true; + } + + return false; + } + + public bool SpellSetCheck() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + List onlyOneSetList = new List { }; + if (onlyOneSetList.Contains(Card.Id) && Bot.HasInSpellZone(Card.Id)) + { + return false; + } + + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay))) + { + + List avoid_list = new List(); + int setFornfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + setFornfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setFornfiniteImpermanence); + return true; + } + else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } + else + { + SelectSTPlace(); + } + if (Card.IsCode(CardId.MalissC_MTP07)) mtp07SetThisTurn = true; + if (Card.IsCode(CardId.MalissC_GWC06)) gwc06SetThisTurn = true; + return true; + } + + return false; + } + + public List GetDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && (card.HasSetcode(SetcodeOrcust) || card.HasSetcode(SetcodePhantom) || card.HasSetcode(SetcodeHorus) || card.HasSetcode(SetcodeDarkWorld) || card.HasSetcode(SetcodeSkyStriker))).ToList(); + List dangerMonsterIdList = new List { 99937011, 63542003, 9411399, 28954097, 30680659, 32731036 }; + result.AddRange(Enemy.Graveyard.GetMatchingCards(card => dangerMonsterIdList.Contains(card.Id))); + return result; + } + + public bool CheckWhetherNegated(bool disablecheck = true, bool toFieldCheck = false, CardType type = 0) + { + bool isMonster = type == 0 && Card.IsMonster(); + isMonster |= ((int)type & (int)CardType.Monster) != 0; + bool isSpellOrTrap = type == 0 && (Card.IsSpell() || Card.IsTrap()); + isSpellOrTrap |= (((int)type & (int)CardType.Spell) != 0) || (((int)type & (int)CardType.Trap) != 0); + bool isCounter = ((int)type & (int)CardType.Counter) != 0; + if (isSpellOrTrap && toFieldCheck && CheckSpellWillBeNegate(isCounter)) + return true; + if (DefaultCheckWhetherCardIsNegated(Card)) return true; + if (isMonster && (toFieldCheck || Card.Location == CardLocation.MonsterZone)) + { + if ((toFieldCheck && (((int)type & (int)CardType.Link) != 0)) || Card.IsDefense()) + { + if (Enemy.MonsterZone.Any(card => CheckNumber41(card)) || Bot.MonsterZone.Any(card => CheckNumber41(card))) return true; + } + if (Enemy.HasInSpellZone(CardId.SkillDrain, true)) return true; + } + if (disablecheck) return (Card.Location == CardLocation.MonsterZone || Card.Location == CardLocation.SpellZone) && Card.IsDisabled() && Card.IsFaceup(); + return false; + } + + public bool CheckNumber41(ClientCard card) + { + return card != null && card.IsFaceup() && card.IsCode(CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled(); + } + + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceList.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public bool CheckSpellWillBeNegate(bool isCounter = false, ClientCard target = null) + { + if (target == null) target = Card; + if (target.Location != CardLocation.SpellZone && target.Location != CardLocation.Hand) return false; + + 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() && (Enemy.HasInSpellZone(CardId.RoyalDecree, true) || Bot.HasInSpellZone(CardId.RoyalDecree, true))) return true; + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceList.Contains(selfSeq)) return true; + } + return false; + } + + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + if (lastcard.IsMonster() && lastcard.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (notToNegateIdList.Contains(lastcard.Id)) return false; + if (DefaultCheckWhetherCardIsNegated(lastcard)) return false; + if (Duel.Turn == 1 && lastcard.IsCode(_CardId.MaxxC)) return false; + + return true; + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + ClientCard floodagateCard = Enemy.GetMonsters().Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsFloodgate() && c.IsFaceup() + && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (floodagateCard != null) return floodagateCard; + + ClientCard dangerCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (dangerCard != null) return dangerCard; + + ClientCard invincibleCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (invincibleCard != null) return invincibleCard; + + ClientCard equippedCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.EquipCards.Count > 0 && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (equippedCard != null) return equippedCard; + + ClientCard enemyExtraMonster = Enemy.MonsterZone.Where(c => c != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && (c.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) || (c.HasType(CardType.Link) && c.LinkCount >= 2)) + && CheckCanBeTargeted(c, canBeTarget, selfType) && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (enemyExtraMonster != null) return enemyExtraMonster; + + if (attack >= 0) + { + if (attack == 0) + attack = Util.GetBestAttack(Bot); + ClientCard betterCard = Enemy.MonsterZone.Where(card => card != null + && card.GetDefensePower() >= attack && card.GetDefensePower() > 0 && card.IsAttack() && CheckCanBeTargeted(card, canBeTarget, selfType) + && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (betterCard != null) return betterCard; + } + return null; + } + + public bool CheckCanBeTargeted(ClientCard card, bool canBeTarget, CardType selfType) + { + if (card == null) return true; + if (canBeTarget) + { + if (card.IsShouldNotBeTarget()) return false; + if (((int)selfType & (int)CardType.Monster) > 0 && card.IsShouldNotBeMonsterTarget()) return false; + if (((int)selfType & (int)CardType.Spell) > 0 && card.IsShouldNotBeSpellTrapTarget()) return false; + if (((int)selfType & (int)CardType.Trap) > 0 && (card.IsShouldNotBeSpellTrapTarget() && !card.IsDisabled())) return false; + } + return true; + } + + public bool CheckShouldNotIgnore(ClientCard cards, bool ignore = false) + { + return !ignore || (!currentDestroyCardList.Contains(cards) && !currentNegateCardList.Contains(cards)); + } + + public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreSpells = false, CardType selfType = 0) + { + List resultList = new List(); + + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (floodagateList.Count > 0) resultList.AddRange(floodagateList); + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).ToList(); + if (problemEnemySpellList.Count > 0) resultList.AddRange(ShuffleList(problemEnemySpellList)); + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (dangerList.Count > 0 && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) resultList.AddRange(dangerList); + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (invincibleList.Count > 0) resultList.AddRange(invincibleList); + + List enemyMonsters = Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c)).OrderByDescending(card => card.Attack).ToList(); + if (enemyMonsters.Count > 0) + { + foreach (ClientCard target in enemyMonsters) + { + if ((target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2)) + && !resultList.Contains(target) && CheckCanBeTargeted(target, canBeTarget, selfType)) + { + resultList.Add(target); + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() && !currentDestroyCardList.Contains(c) + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous) && CheckCanBeTargeted(c, canBeTarget, selfType) + && !notToDestroySpellTrap.Contains(c.Id)).ToList(); + if (spells.Count > 0 && !ignoreSpells) resultList.AddRange(ShuffleList(spells)); + + return resultList; + } + + public List GetNormalEnemyTargetList(bool canBeTarget = true, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + List targetList = GetProblematicEnemyCardList(canBeTarget, selfType: selfType); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && enemyPlaceThisTurn.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && !enemyPlaceThisTurn.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetMonsters().Where(card => card.IsFacedown() && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList())); + + return targetList; + } + + public List GetMonsterListForTargetNegate(bool canBeTarget = false, CardType selfType = 0) + { + List resultList = new List(); + if (CheckWhetherNegated()) + { + return resultList; + } + + ClientCard target = Enemy.MonsterZone.FirstOrDefault(card => card?.Data != null + && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && !card.IsShouldNotBeTarget() + && CheckCanBeTargeted(card, canBeTarget, selfType) + && !currentNegateCardList.Contains(card)); + if (target != null) + { + resultList.Add(target); + } + + foreach (ClientCard chainingCard in Duel.CurrentChain) + { + if (chainingCard.Location == CardLocation.MonsterZone && chainingCard.Controller == 1 && !chainingCard.IsDisabled() + && CheckCanBeTargeted(chainingCard, canBeTarget, selfType) && !currentNegateCardList.Contains(chainingCard)) + { + resultList.Add(chainingCard); + } + } + + return resultList; + } + + 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 monsters = Enemy.GetMonsters(); + if (monsters.Count > 0 && !onlyFaceup) return ShuffleCardList(monsters)[0]; + return null; + } + + public ClientCard GetBestEnemySpell(bool onlyFaceup = false, bool canBeTarget = false) + { + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (problemEnemySpellList.Count > 0) + { + return ShuffleCardList(problemEnemySpellList)[0]; + } + + List spells = Enemy.GetSpells().Where(card => !(card.IsFaceup() && card.IsCode(_CardId.EvenlyMatched))).ToList(); + + List faceUpList = spells.Where(ecard => ecard.IsFaceup() && (ecard.HasType(CardType.Continuous) || ecard.HasType(CardType.Field) || ecard.HasType(CardType.Pendulum))).ToList(); + if (faceUpList.Count > 0) + { + return ShuffleCardList(faceUpList)[0]; + } + + if (spells.Count > 0 && !onlyFaceup) + { + return ShuffleCardList(spells)[0]; + } + + return null; + } + + public ClientCard GetBestEnemyCard(bool onlyFaceup = false, bool canBeTarget = false, bool checkGrave = false) + { + ClientCard card = GetBestEnemyMonster(onlyFaceup, canBeTarget); + if (card != null) return card; + + card = GetBestEnemySpell(onlyFaceup, canBeTarget); + if (card != null) return card; + + if (checkGrave && Enemy.Graveyard.Count > 0) + { + List graveMonsterList = Enemy.Graveyard.GetMatchingCards(c => c.IsMonster()).ToList(); + if (graveMonsterList.Count > 0) + { + graveMonsterList.Sort(CardContainer.CompareCardAttack); + graveMonsterList.Reverse(); + return graveMonsterList[0]; + } + return ShuffleCardList(Enemy.Graveyard.ToList())[0]; + } + + return null; + } + + private int LinkVal(ClientCard c) => (c != null && c.HasType(CardType.Link)) ? Math.Max(1, c.LinkCount) : 1; + private static readonly int EMZ_LEFT = 5; + private static readonly int EMZ_RIGHT = 6; + private bool IsInEMZ(ClientCard c) + { + var mz = Bot.MonsterZone; + return (mz.Length > 5 && mz[5] == c) || (mz.Length > 6 && mz[6] == c); + } + + private bool HasFreeEMZ() + { + var mz = Bot.MonsterZone; + bool slot5Free = mz.Length > 5 && mz[5] == null; + bool slot6Free = mz.Length > 6 && mz[6] == null; + return slot5Free || slot6Free; + } + #endregion + + #region work space #1 + public override void OnChainSolved(int chainIndex) + { + ClientCard currentCard = Duel.GetCurrentSolvingChainCard(); + var solving = Duel.GetCurrentSolvingChainCard(); + bool neg = Duel.IsCurrentSolvingChainNegated(); + if (currentCard != null && !Duel.IsCurrentSolvingChainNegated() && currentCard.Controller == 1) + { + if (currentCard.IsCode(CardId.Lancea)) enemyActivateLancea = true; + if (currentCard.IsCode(_CardId.MaxxC)) enemyActivateMaxxC = true; + if (currentCard.IsCode(CardId.Fuwalos)) enemyActivateFuwalos = true; + if (currentCard.IsCode(_CardId.LockBird)) enemyActivateLockBird = true; + if (currentCard.IsCode(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == currentCard) + { + infiniteImpermanenceList.Add(4 - i); + break; + } + } + } + var last = Duel.GetCurrentSolvingChainCard(); + if (last != null) + { + if (last.IsSpell() && (last.HasType(CardType.Field) || last.HasType(CardType.Continuous) || last.HasType(CardType.Equip))) + _oppJustActivatedPersistentSpell = true; + _prefWindowTTL = Math.Max(_prefWindowTTL, 2); + } + } + if (currentCard != null && currentCard.Controller == 0 && currentCard.IsCode(CardId.SplashMage)) + { + if (Duel.IsCurrentSolvingChainNegated()) + splashNegatedThisTurn = true; + } + } + public override void OnChainEnd() + { + escapeTargetList.Clear(); + currentNegateCardList.Clear(); + currentDestroyCardList.Clear(); + enemyActivateInfiniteImpermanenceFromHand = false; + _oppJustActivatedPersistentSpell = false; + int curMon = Enemy.GetMonsterCount(); + if (curMon > _enemyMonsterCountSnap) _oppJustSummoned = true; + _enemyMonsterCountSnap = curMon; + int curFD = Enemy.SpellZone.Count(c => c != null && c.IsFacedown()); + if (curFD > _enemyFacedownSTSnap) _oppJustSet = true; + _enemyFacedownSTSnap = curFD; + for (int idx = enemyPlaceThisTurn.Count - 1; idx >= 0; idx--) + { + ClientCard checkTarget = enemyPlaceThisTurn[idx]; + if (checkTarget == null || (checkTarget.Location != CardLocation.SpellZone && checkTarget.Location != CardLocation.MonsterZone)) + { + enemyPlaceThisTurn.RemoveAt(idx); + } + } + base.OnChainEnd(); + } + public override void OnNewTurn() + { + if (Duel.Player == 0) + { + myTurnCount++; + } + enemyActivateLancea = false; //added for Maliss + enemyActivateFuwalos = false; //added + enemyActivateMaxxC = false; + enemyActivateLockBird = false; + enemyActivateInfiniteImpermanenceFromHand = false; + if (dimensionShifterCount > 0) dimensionShifterCount--; + infiniteImpermanenceList.Clear(); + currentNegateCardList.Clear(); + currentDestroyCardList.Clear(); + sendToGYThisTurn.Clear(); + activatedCardIdList.Clear(); + enemyPlaceThisTurn.Clear(); + summonThisTurn.Clear(); + + // reset Maliss flags + usedNormalSummon = false; + ssChessyCat = false; + ssDormouse = false; + ssMarchHare = false; + ssWhiteRabbit = false; + ActiveMarchHare = false; + ActiveUnderground = false; + step1Done = false; + step2Done = false; + lastRevivedIdBySplash = 0; + mtp07SetThisTurn = false; + gwc06SetThisTurn = false; + splashNegatedThisTurn = false; + ssRRThisTurn = false; + ssWBThisTurn = false; + ssHCThisTurn = false; + _didSplashToRR = _didRRtoWicckid = _didSummonToWicckidArrow = _didWBFromWicckid = false; + _finishPlanDecided = false; + _preferWicckidArrows = false; + _rrSelfSSPlacing = false; + _forceTranscodeBit = 0; + _oppJustActivatedPersistentSpell = false; + _oppJustSummoned = false; + _oppJustSet = false; + _enemyMonsterCountSnap = Enemy.GetMonsterCount(); + _enemyFacedownSTSnap = Enemy.SpellZone.Count(c => c != null && c.IsFacedown()); + _prefWindowTTL = 0; + fullBoard1 = false; + Allied_End = false; + nsplan = false; + nsBackupplan = false; + NSDorMouse = false; + nsLanceaplan = false; + base.OnNewTurn(); + } + public override bool OnSelectYesNo(int desc) + { + if (desc == Util.GetStringId(CardId.MalissQ_WhiteBinder, 0)) + { + bool anyGY = (Bot.Graveyard.Count > 0) || (Enemy.Graveyard.Count > 0); + return anyGY; + } + return base.OnSelectYesNo(desc); + } + private bool DontSelfNG() { return Duel.LastChainPlayer != 0; } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + var solving = Duel.GetCurrentSolvingChainCard(); + if (cards != null && cards.Count > 0 && solving != null) + { + if (solving.IsCode(CardId.MalissQ_RedRansom)) + { + var searchPool = cards + .Where(c => c != null && + (c.IsCode(CardId.MalissInUnderground) || + c.IsCode(CardId.MalissInTheMirror))) + .ToList(); + + if (searchPool.Count > 0) + { + bool shouldUG = ShouldSearchUnderground(); + int chooseId = 0; + if (shouldUG && searchPool.Any(c => c.IsCode(CardId.MalissInUnderground))) + { + chooseId = CardId.MalissInUnderground; + } + else if (searchPool.Any(c => c.IsCode(CardId.MalissInTheMirror))) + { + chooseId = CardId.MalissInTheMirror; + } + if (chooseId != 0) + { + var pick = searchPool.First(c => c.IsCode(chooseId)); + return new List { pick }; + } + } + } + if (hint == HintMsg.Set && solving.IsCode(CardId.MalissQ_WhiteBinder)) + { + ClientCard pick = null; + pick = cards.FirstOrDefault(c => c.Id == CardId.MalissC_GWC06 && c.Location == CardLocation.Deck); + if (pick == null) + { + pick = cards.FirstOrDefault(c => c.Id == CardId.MalissC_GWC06); + } + if (pick == null) + { + pick = cards.FirstOrDefault(c => c.Id == CardId.MalissC_MTP07); + } + if (pick != null) + { + if (pick.Id == CardId.MalissC_GWC06) + gwc06SetThisTurn = true; + else if (pick.Id == CardId.MalissC_MTP07) + mtp07SetThisTurn = true; + + return new List { pick }; + } + + } + } + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + #endregion + + + #region work space #2 + private int GetMMZCount() => Bot.MonsterZone.Take(5).Count(c => c != null); + private bool HasFreeMMZ() => GetMMZCount() < 5; + private bool HaveTwoBodies() => Bot.GetMonsterCount() >= 2; + private bool ShouldFastEndToSPLK() => + enemyActivateMaxxC || enemyActivateFuwalos; + private bool Step1Complete() + { + return Bot.HasInMonstersZone(CardId.MalissP_Dormouse) + && Bot.HasInMonstersZone(CardId.MalissP_WhiteRabbit); + } + private bool CanStartStep1() + { + if (enemyActivateLancea || ShouldFastEndToSPLK()) return false; + if (HaveTwoBodies()) return false; + if (!HasFreeMMZ()) return false; + bool haveStarterInHand = + Bot.HasInHand(CardId.MalissP_Dormouse) || + Bot.HasInHand(CardId.MalissP_WhiteRabbit) || + Bot.HasInHand(CardId.GoldSarcophagus) || + Bot.HasInHand(CardId.TERRAFORMING) || + Bot.HasInHand(CardId.MalissInUnderground); + return haveStarterInHand; + } + private bool CanContinueStep1() + { + if (enemyActivateLancea) return false; + return !HaveTwoBodies() && HasFreeMMZ(); + } + private int PickMalissTrapToSet() + { + int pref; + if (Duel.Player == 0 && Bot.HasInMonstersZone(CardId.MalissP_Dormouse) && Bot.HasInMonstersZone(CardId.MalissP_WhiteRabbit)) + { + pref = CardId.MalissC_GWC06; + } + else if (Duel.Player == 0 && (Bot.HasInMonstersZoneOrInGraveyard(CardId.MalissQ_RedRansom) || Bot.HasInBanished(CardId.MalissQ_RedRansom))) + { + pref = CardId.MalissC_GWC06; + } + else if (Duel.Player == 0 && Bot.HasInHand(CardId.MalissP_MarchHare) && !ActiveMarchHare && !ssWhiteRabbit) + { + pref = CardId.MalissC_GWC06; + } + else if (Duel.Player == 0 && nsBackupplan) + { + pref = CardId.MalissC_GWC06; + } + else if (Duel.Player == 1) + { + pref = CardId.MalissC_MTP07; + } + else + { + pref = CardId.MalissC_MTP07; + } + if (CheckRemainInDeck(pref) > 0) + { + return pref; + } + + return 0; + } + + private bool ActLittleKnight() + { + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.SP_LITTLE_KNIGHT, 0)) + { + List problemCardList = GetProblematicEnemyCardList(true, selfType: CardType.Monster); + problemCardList.AddRange(GetDangerousCardinEnemyGrave(false)); + problemCardList.AddRange(GetNormalEnemyTargetList(true, true, CardType.Monster)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => card.HasType(CardType.Monster)).OrderByDescending(card => card.Attack)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => !card.HasType(CardType.Monster))); + if (problemCardList.Count() > 0) + { + AI.SelectCard(problemCardList); + activatedCardIdList.Add(Card.Id); + return true; + } + } + else if (ActivateDescription == Util.GetStringId(CardId.SP_LITTLE_KNIGHT, 1)) + { + ClientCard selfMonster = null; + foreach (ClientCard target in Bot.GetMonsters()) + { + if (Duel.ChainTargets.Contains(target) && !escapeTargetList.Contains(target)) + { + selfMonster = target; + break; + } + } + if (selfMonster == null) + { + if (Duel.Player == 1) + { + selfMonster = Bot.GetMonsters().Where(card => card.IsAttack()).OrderBy(card => card.Attack).FirstOrDefault(); + if (!Util.IsOneEnemyBetterThanValue(selfMonster.Attack, true)) selfMonster = null; + } + } + if (selfMonster != null) + { + ClientCard nextMonster = null; + List selfTargetList = Bot.GetMonsters().Where(card => card != selfMonster).ToList(); + if (Enemy.GetMonsterCount() == 0 && selfTargetList.Count() > 0) + { + selfTargetList.Sort(CompareUsableAttack); + nextMonster = selfTargetList[0]; + escapeTargetList.Add(nextMonster); + } + if (Enemy.GetMonsterCount() > 0) + { + nextMonster = GetBestEnemyMonster(true, true); + currentDestroyCardList.Add(nextMonster); + } + if (nextMonster != null) + { + AI.SelectCard(selfMonster); + AI.SelectNextCard(nextMonster); + escapeTargetList.Add(selfMonster); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + + return false; + } + public int CompareUsableAttack(ClientCard cardA, ClientCard cardB) + { + if (cardA == null && cardB == null) + return 0; + if (cardA == null) + return -1; + if (cardB == null) + return 1; + int powerA = (cardA.IsDefense() && summonThisTurn.Contains(cardA)) ? 0 : cardA.Attack; + int powerB = (cardB.IsDefense() && summonThisTurn.Contains(cardB)) ? 0 : cardB.Attack; + if (powerA < powerB) + return -1; + if (powerA == powerB) + return CardContainer.CompareCardLevel(cardA, cardB); + return 1; + } + + private bool Step1_Dormouse_NormalSummon() + { + if (!CanStartStep1()) return false; + if (usedNormalSummon) return false; + usedNormalSummon = true; + NSDorMouse = true; + return true; + } + private bool Dormouse_ForMH() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (!CanContinueStep1()) return false; + if (Card.Location != CardLocation.MonsterZone) return false; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + int pick = 0; + if (goldstart || undergroundstart) + { + pick = (CheckRemainInDeck(CardId.MalissP_WhiteRabbit) > 0) + ? CardId.MalissP_WhiteRabbit + : CardId.MalissP_ChessyCat; + } + else + { + pick = (CheckRemainInDeck(CardId.MalissP_MarchHare) > 0) + ? CardId.MalissP_MarchHare + : (CheckRemainInDeck(CardId.MalissP_WhiteRabbit) > 0) + ? CardId.MalissP_WhiteRabbit + : CardId.MalissP_ChessyCat; + } + if (pick == 0) return false; + AI.SelectCard(pick); + return true; + } + + private bool Step1_WhiteRabbit_SS_FromBanished() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (enemyActivateLancea) return false; + if (Card.Id != CardId.MalissP_WhiteRabbit) return false; + if (Card.Location != CardLocation.Removed) return false; + if (Bot.LifePoints <= 300) + { + return false; + } + ssWhiteRabbit = true; + return true; + } + + private bool Step1_WhiteRabbit_SetTrapOnSummon() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Id != CardId.MalissP_WhiteRabbit) return false; + if (Card.Location != CardLocation.MonsterZone) return false; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + + int trapToSet = PickMalissTrapToSet(); + if (trapToSet == 0) return false; + + if (trapToSet == CardId.MalissC_GWC06) + gwc06SetThisTurn = true; + + if (trapToSet == CardId.MalissC_MTP07) + mtp07SetThisTurn = true; + + AI.SelectCard(trapToSet); + SelectSafeSTZoneAwayFromImperm(); + if (Step1Complete()) step1Done = true; + return true; + } + + private bool Step1_WhiteRabbit_NormalSummon() + { + if (!CanStartStep1()) return false; + if (Bot.HasInHand(CardId.MalissP_Dormouse)) return false; + if (usedNormalSummon) return false; + usedNormalSummon = true; + return true; + } + + private bool Dormouse_SS_FromBanished() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Id != CardId.MalissP_Dormouse) return false; + if (Card.Location != CardLocation.Removed) return false; + if (enemyActivateLancea) return false; + if (Bot.LifePoints <= 300) + { + return false; + } + ssDormouse = true; + return true; + } + private bool ChessyCat_SS_FromBanished() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Id != CardId.MalissP_ChessyCat) return false; + if (Card.Location != CardLocation.Removed) return false; + if (enemyActivateLancea) return false; + if (Bot.LifePoints <= 300) + { + return false; + } + ssChessyCat = true; + return true; + } + + private bool SummonLittleKnightFast() + { + if (!(Bot.HasInMonstersZone(CardId.LinkSpider)|| Bot.HasInMonstersZone(CardId.Linguriboh))) return false; + if (!HaveTwoBodies()) return false; + + var mats = Bot.GetMonsters() + .Where(c => c != null && c.IsFaceup() && c.HasType(CardType.Effect)) + .OrderBy(c => c.Attack) + .Take(2).ToList(); + + if (mats.Count < 2) return false; + + AI.SelectMaterials(mats); + step1Done = true; + return true; + } + private bool SPEmer() + { + if (Bot.HasInMonstersZone(CardId.FirewallDragon) || + Bot.HasInMonstersZone(CardId.AlliedCodeTalkerIgnister) || + Bot.HasInMonstersZone(CardId.Apollousa) || + Bot.HasInMonstersZone(CardId.AccesscodeTalker)) + { + return false; + } + if (!HaveTwoBodies()) return false; + + var mats = PickLinkMatsMinCount( + targetLink: 2, + isEligible: m => m.HasType(CardType.Effect), + minCount: 2, + maxCount: 2, + avoidIds: new[] { CardId.Apollousa, CardId.AlliedCodeTalkerIgnister, CardId.AccesscodeTalker } + ); + if (mats.Count != 2) + { + return false; + } + + AI.SelectMaterials(mats); + return true; + } + + private bool GoldSarc_StartPiece() + { + if (CheckSpellWillBeNegate()) return false; + if (enemyActivateLancea) { return false; } + if (Bot.HasInHand(CardId.MalissP_Dormouse) || Bot.HasInHand(CardId.MalissP_WhiteRabbit)) { return false; } + int pick = 0; + if (!Bot.HasInMonstersZone(CardId.MalissP_Dormouse) && CheckRemainInDeck(CardId.MalissP_Dormouse) > 0 && !ssDormouse) + { pick = CardId.MalissP_Dormouse; } + else if (!Bot.HasInMonstersZone(CardId.MalissP_WhiteRabbit) && CheckRemainInDeck(CardId.MalissP_WhiteRabbit) > 0 && !ssWhiteRabbit) + { pick = CardId.MalissP_WhiteRabbit; } + else if (madeIt3 && !ssChessyCat) + { pick = CardId.MalissP_ChessyCat; } + else { return false; } + if (pick == 0) return false; + + + AI.SelectCard(pick); + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + goldstart = true; + return true; + } + private bool ExistsForUnderground(int id) + { + return CheckRemainInDeck(id) > 0 + || Bot.HasInHand(id) + || Bot.HasInGraveyard(id); + } + private bool Underground_ActivateStarter() + { + if (enemyActivateLancea) return false; + if (Bot.GetMonsterCount() != 0) return false; + if (step1Done) return false; + + int pick = 0; + if (ExistsForUnderground(CardId.MalissP_Dormouse)) + pick = CardId.MalissP_Dormouse; + else if (ExistsForUnderground(CardId.MalissP_WhiteRabbit)) + pick = CardId.MalissP_WhiteRabbit; + else if (ExistsForUnderground(CardId.MalissP_ChessyCat)) + pick = CardId.MalissP_ChessyCat; + + if (pick == 0) return false; + + AI.SelectYesNo(true); + AI.SelectCard(pick); + ActiveUnderground = true; + undergroundstart = true; + return true; + } + + private bool Terra_GrabUnderground() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (CheckSpellWillBeNegate()) return false; + if (ActiveUnderground) return false; + if (Bot.HasInHand(CardId.MalissInUnderground) || Bot.HasInSpellZone(CardId.MalissInUnderground)) + return false; + AI.SelectCard(CardId.MalissInUnderground); + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + return true; + } + private bool HaveBackupOrWizardInHand() + { + return Bot.HasInHand(CardId.BackupIgnister) || Bot.HasInHand(CardId.WizardIgnister); + } + private bool HaveMHInHand() + { + return Bot.HasInHand(CardId.MalissP_MarchHare); + } + private bool IsMalissBody(ClientCard c) + { + return c != null && c.IsFaceup() && c.HasSetcode(SetcodeMaliss) + && c.IsCode(CardId.MalissP_Dormouse, + CardId.MalissP_WhiteRabbit, + CardId.MalissP_ChessyCat, + CardId.MalissP_MarchHare); + } + private bool Emergency_NormalCat() + { + if (Bot.GetMonsterCount() != 0) return false; + if (usedNormalSummon) return false; + if (Bot.HasInHand(CardId.MalissP_Dormouse) || Bot.HasInHand(CardId.MalissP_WhiteRabbit) || + Bot.HasInHand(CardId.MalissInUnderground) || Bot.HasInHand(CardId.TERRAFORMING) || + Bot.HasInHand(CardId.GoldSarcophagus)) return false; + if (!HaveMHInHand()) + { + return false; + } + + usedNormalSummon = true; + return true; + } + private bool OneBody_Link1_Linguriboh() + { + if (!HaveBackupOrWizardInHand()) return false; + if (Bot.HasInMonstersZone(CardId.Linguriboh)) return false; + if (Bot.GetMonsterCount() != 1) return false; + return true; + } + private bool OneBody_Link1_Almiraj() + { + if (!HaveBackupOrWizardInHand()) return false; + if (Bot.HasInMonstersZone(CardId.SALAMANGREAT_ALMIRAJ)) return false; + if (Bot.GetMonsterCount() != 1) return false; + return true; + } + private bool OneBody_Backup_SS() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + bool haveLinkAnchor = Bot.HasInMonstersZone(CardId.Linguriboh) || Bot.HasInMonstersZone(CardId.SplashMage); + if (!haveLinkAnchor) return false; + if (Card.Location != CardLocation.Hand) return false; + + avoidLinkedZones = true; + return true; + } + private bool OneBody_Backup_SearchWizard() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (!Card.IsCode(CardId.BackupIgnister)) return false; + + if (Bot.Hand.Count == 0) return false; + + bool haveWizard = Bot.HasInHand(CardId.WizardIgnister); + + int searchId = 0; + if (haveWizard && CheckRemainInDeck(CardId.MalissP_MarchHare) > 0 && Bot.Hand.Count > 0) + searchId = CardId.MalissP_MarchHare; + else if (CheckRemainInDeck(CardId.MalissP_Dormouse) > 0 && nsplan && Bot.HasInMonstersZone(CardId.SALAMANGREAT_ALMIRAJ)) + searchId = CardId.MalissP_Dormouse; + else if (CheckRemainInDeck(CardId.MalissP_WhiteRabbit) > 0 && nsBackupplan) + searchId = CardId.MalissP_WhiteRabbit; + else if (!haveWizard && CheckRemainInDeck(CardId.WizardIgnister) > 0 && Bot.Hand.Count > 0) + searchId = CardId.WizardIgnister; + else if (CheckRemainInDeck(CardId.MalissP_WhiteRabbit) > 0) + searchId = CardId.MalissP_WhiteRabbit; + else + return false; + + AI.SelectCard(searchId); + + var hand = Bot.Hand.Where(h => h != null).ToList(); + var candidates = hand.Where(h => h.Id != CardId.WizardIgnister).ToList(); + var discards = new List(hand.Count); + if (searchId == CardId.MalissP_Dormouse) + { + discards.AddRange(candidates.Where(c => c.Id == CardId.MalissP_Dormouse)); + } + Func> OthersExcludingTarget = () => + { + if (searchId == CardId.MalissP_MarchHare) + return candidates.Where(c => c.Id != CardId.MalissP_MarchHare); + return candidates; + }; + var othersExcludingTarget = OthersExcludingTarget().ToList(); + var dupGroups = othersExcludingTarget.GroupBy(c => c.Id) + .Where(g => g.Count() >= 2); + + discards.AddRange(dupGroups.SelectMany(g => g)); + + int[] lowValueSinglesOrder = { CardId.NibiruThePrimalBeing, + CardId.Lancea, + CardId.TERRAFORMING, + CardId.GoldSarcophagus + }; + + foreach (var id in lowValueSinglesOrder) + { + discards.AddRange(othersExcludingTarget + .Where(c => c.Id == id && dupGroups.All(g => g.Key != id))); + } + + var already = new HashSet(discards); + discards.AddRange(othersExcludingTarget.Where(c => !already.Contains(c))); + + discards = discards.Where(c => c != null).Distinct().ToList(); + + if (searchId == CardId.MalissP_Dormouse) + { + AI.SelectNextCard(searchId); + } + if (searchId == CardId.MalissP_WhiteRabbit) + { + AI.SelectNextCard(searchId); + } + else if (discards != null) + { + AI.SelectNextCard(discards); + } + else + { + return false; + } + + avoidLinkedZones = true; + if (Bot.HasInMonstersZone(CardId.Linguriboh)) blockWicckid = true; + if (GetMMZCount() >= 5 && Bot.HasInHand(CardId.WizardIgnister)) { fullBoard1 = true; } + return true; + } + private bool OneBody_Wizard_SS() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (!Bot.HasInMonstersZone(CardId.Linguriboh) && !Bot.HasInMonstersZone(CardId.SALAMANGREAT_ALMIRAJ)) return false; + if (Card.Location != CardLocation.Hand) return false; + + var revive = PickGYCybersePriority(); + if (revive == null) return false; + + avoidLinkedZones = true; + blockWicckid = true; + + AI.SelectCard(revive); + return true; + } + private ClientCard PickGYCybersePriority() + { + var m = PickGYMalissPriority(); + if (m != null) return m; + + var list = Bot.Graveyard.GetMatchingCards(c => + c != null && c.IsMonster() && c.HasRace(CardRace.Cyberse) && c.Level <= 4).ToList(); + return list.FirstOrDefault(); + } + private ClientCard PickGYMalissPriority() + { + int[] pref = { + CardId.MalissP_Dormouse, + CardId.MalissP_WhiteRabbit, + CardId.MalissP_ChessyCat, + CardId.MalissP_MarchHare + }; + foreach (var id in pref) + { + var c = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(id) && g.IsMonster()); + if (c != null) return c; + } + return null; + } + private bool TwoCC_NormalSummon() + { + if (usedNormalSummon) return false; + if (Bot.GetMonsterCount() != 0) return false; + + bool haveOtherStarter = + Bot.HasInHand(CardId.MalissP_Dormouse) || + Bot.HasInHand(CardId.MalissP_WhiteRabbit) || + Bot.HasInHand(CardId.GoldSarcophagus) || + Bot.HasInHand(CardId.MalissInUnderground); + + if (haveOtherStarter) return false; + + if (Bot.Hand.GetMatchingCards(c => c != null && c.IsCode(CardId.MalissP_ChessyCat)).Count >= 2) + { + usedNormalSummon = true; + return true; + } + return false; + } + private bool IsMalissCost(ClientCard card) + { + if (card == null) return false; + + if (card.IsCode(CardId.MalissP_ChessyCat)) + return true; + if (card.IsCode(CardId.MalissP_WhiteRabbit) && NSDorMouse && !ssWhiteRabbit) + return true; + if (card.IsCode(CardId.MalissP_WhiteRabbit) && ssWhiteRabbit) + return true; + if (card.IsCode(CardId.MalissP_Dormouse) && ssDormouse) + return true; + if (card.IsCode(CardId.MalissP_MarchHare) && ActiveMarchHare) + return true; + + return false; + } + private bool IsMalissCost2(ClientCard card) + { + if (card == null) return false; + + return + card.IsCode(CardId.MalissP_ChessyCat) || + card.IsCode(CardId.MalissP_WhiteRabbit) || + card.IsCode(CardId.MalissP_MarchHare) || + card.IsCode(CardId.MalissInUnderground); + } + private bool AnyDraw() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Id != CardId.MalissP_ChessyCat) return false; + if (Card.Location != CardLocation.MonsterZone) return false; + if (CheckWhetherNegated()) return false; + + ClientCard target = null; + + target = Bot.Hand.FirstOrDefault(c => c != null && c.IsCode(CardId.MalissInTheMirror)); + if (target == null) + { + target = Bot.Hand.FirstOrDefault(IsMalissCost); + } + if (target == null) + { + var malissDupGroup = Bot.Hand + .Where(IsMalissCost2) + .GroupBy(c => c.Id) + .FirstOrDefault(g => g.Count() >= 2); + + if (malissDupGroup != null) + { + target = malissDupGroup.First(); + } + } + if (target == null) + { + return false; + } + AI.SelectCard(target); + return true; + } + private int PickTB11CostCandidateId() + { + var field = Bot.GetMonsters() + .Where(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeMaliss)) + .ToList(); + + field = field.Where(c => + !(c.IsCode(CardId.MalissP_WhiteRabbit) && ssWhiteRabbit) && + !(c.IsCode(CardId.MalissP_ChessyCat) && ssChessyCat) && + !(c.IsCode(CardId.MalissP_MarchHare) && ssMarchHare) && + !(c.IsCode(CardId.MalissP_Dormouse) && ssDormouse) && + !(c.IsCode(CardId.MalissQ_RedRansom) && ssRRThisTurn) && + !(c.IsCode(CardId.MalissQ_WhiteBinder) && ssWBThisTurn) && + !(c.IsCode(CardId.MalissQ_HeartsCrypter) && ssHCThisTurn) + ).ToList(); + + int[] pref = { + CardId.MalissP_WhiteRabbit, + CardId.MalissP_ChessyCat, + CardId.MalissP_MarchHare, + CardId.MalissP_Dormouse, + CardId.MalissQ_RedRansom, + CardId.MalissQ_WhiteBinder, + CardId.MalissQ_HeartsCrypter + }; + foreach (var id in pref) + if (field.Any(c => c.IsCode(id))) return id; + + return 0; + } + private int PickPFromGYForSplash() + { + if (enemyActivateLancea) + { + int[] pref2 = { + CardId.MalissP_Dormouse, + CardId.MalissP_WhiteRabbit, + CardId.MalissP_ChessyCat, + CardId.MalissP_MarchHare, + CardId.BackupIgnister, + CardId.WizardIgnister + }; + foreach (var id in pref2) + if (Bot.HasInGraveyard(id)) return id; + } + int[] pref = { + CardId.MalissP_Dormouse, + CardId.MalissP_WhiteRabbit, + CardId.MalissP_ChessyCat, + CardId.MalissP_MarchHare + }; + foreach (var id in pref) + if (Bot.HasInGraveyard(id)) return id; + return 0; + } + private bool HaveUndergroundOnHandOrField() + { + return Bot.HasInHand(CardId.MalissInUnderground) || Bot.HasInSpellZone(CardId.MalissInUnderground); + } + private bool ShouldSearchUnderground() + { + if (ActiveUnderground) return false; + if (HaveUndergroundOnHandOrField()) return false; + return CheckRemainInDeck(CardId.MalissInUnderground) > 0; + } + private bool Step2_RedRansom_Search() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + int chooseId = 0; + bool shouldUG = ShouldSearchUnderground(); + if (shouldUG) + { + chooseId = CardId.MalissInUnderground; + } + else if (CheckRemainInDeck(CardId.MalissInTheMirror) > 0) + { + chooseId = CardId.MalissInTheMirror; + } + if (chooseId == 0) return false; + + //AI.SelectCard(chooseId); go to onselectcard + step2Done = true; + avoidLinkedZones = false; + coreSetupComplete = true; + return true; + } + private List PickMaterialsForRedRansom() + { + var splash = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(CardId.SplashMage)); + if (splash == null) return new List(); + + ClientCard revived = null; + if (lastRevivedIdBySplash != 0) + revived = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(lastRevivedIdBySplash)); + + if (revived == null) + revived = Bot.MonsterZone.FirstOrDefault(c => + c != null && c.IsFaceup() && c.HasSetcode(0x1bf) && c != splash && !c.HasType(CardType.Link)); + + if (revived == null) return new List(); + return new List { splash, revived }; + } + private bool Step2_SplashMage_ReviveP() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (step2Done) return false; + + if (!Bot.HasInMonstersZone(CardId.SplashMage)) return false; + + int pick = PickPFromGYForSplash(); + if (pick == 0) return false; + + AI.SelectCard(pick); + lastRevivedIdBySplash = pick; + return true; + } + private bool Step2N_SplashMage_ReviveP() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (!Bot.HasInMonstersZone(CardId.SplashMage)) return false; + + int pick = PickPFromGYForSplash(); + if (pick == 0) return false; + + AI.SelectCard(pick); + lastRevivedIdBySplash = pick; + return true; + } + private bool Step2_LinkSummon_RedRansom() + { + if (step2Done) return false; + + var mats = PickMaterialsForRedRansom(); + if (mats.Count != 2) return false; + + if (Util.GetBotAvailZonesFromExtraDeck(mats) == 0) return false; + + AI.SelectMaterials(mats); + madeIt3 = true; + return true; + } + private bool Step2N_LinkSummon_WB() + { + var mats = PickMaterialsForRedRansom(); + if (mats.Count != 2) return false; + + if (Util.GetBotAvailZonesFromExtraDeck(mats) == 0) return false; + + AI.SelectMaterials(mats); + return true; + } + private bool Step2N_LinkSummon_RedRansom() + { + if (!Bot.HasInMonstersZone(CardId.MalissP_MarchHare) || Bot.GetMonsterCount() < 3) + { + return false; + } + madeIt3 = true; + return true; + } + private bool Step2_Fallback_Wizard_AfterSplashNegated() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (!splashNegatedThisTurn) return false; + if (Card.Location != CardLocation.Hand) return false; + + var revive = PickGYMalissPriority(); + if (revive == null) return false; + + avoidLinkedZones = true; + blockWicckid = true; + AI.SelectCard(revive); + return true; + } + private bool Step2_Fallback_Backup_AfterSplashNegated() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (!splashNegatedThisTurn) return false; + if (Card.Location != CardLocation.Hand) return false; + + if (GetMMZCount() >= 5) return false; + + int want = !Bot.HasInHand(CardId.WizardIgnister) && CheckRemainInDeck(CardId.WizardIgnister) > 0 + ? CardId.WizardIgnister + : (CheckRemainInDeck(CardId.MalissP_MarchHare) > 0 ? CardId.MalissP_MarchHare : 0); + if (want == 0) return false; + + AI.SelectCard(want); + + var discard = Bot.Hand.FirstOrDefault(h => h != null && h.Id != CardId.WizardIgnister && h != Card); + if (discard != null) AI.SelectNextCard(discard); + + avoidLinkedZones = true; + blockWicckid = true; + return true; + } + #endregion + + #region FLOW 3: Core → Results (UG / Mirror / TP11 → Make it 3!! → Finishers) + private bool HaveUG() => Bot.HasInHand(CardId.MalissInUnderground) || Bot.HasInSpellZone(CardId.MalissInUnderground); + private bool HasSelfSSAvailable(int id) + { + if (id == CardId.MalissP_Dormouse) return !ssDormouse; + if (id == CardId.MalissP_WhiteRabbit) return !ssWhiteRabbit; + if (id == CardId.MalissP_ChessyCat) return !ssChessyCat; + if (id == CardId.MalissP_MarchHare) return !ActiveMarchHare; + return true; + } + private int PickUG_DHG_DormouseFirst() + { + int[] pref = { + CardId.MalissP_Dormouse, + CardId.MalissP_WhiteRabbit, + CardId.MalissP_ChessyCat, + CardId.MalissP_MarchHare + }; + + foreach (var id in pref) + { + if (!HasSelfSSAvailable(id)) continue; + if (ExistsForUnderground(id)) + return id; + } + return 0; + } + + private bool Flow3_UnderGround_Available_SSAnyPawn() + { + if (!step2Done) return false; + if (!HaveUG()) return false; + if (Card.Id != CardId.MalissInUnderground) return false; + if (resultSuccessFlag) return false; + if (GetMMZCount() >= 5) + { + AI.SelectYesNo(false); + return true; + } + if (enemyActivateLancea) + { + AI.SelectYesNo(false); + return true; + } + + int pick = 0; + + if (CheckRemainInDeck(CardId.MalissInTheMirror) > 0 && nsplan) + { + pick = CardId.MalissInTheMirror; + } + else if (CheckRemainInDeck(CardId.MalissInTheMirror) > 0 && NSDorMouse) + { + pick = CardId.MalissInTheMirror; + } + else + { + pick = PickUG_DHG_DormouseFirst(); + } + + if (pick == 0) + { + AI.SelectYesNo(false); + return true; + } + + AI.SelectYesNo(true); + AI.SelectCard(pick); + resultSuccessFlag = true; + return true; + } + private bool Mirror_Banish() + { + if (DescIs(CardId.MalissInTheMirror, 1)) + { + var gy = PickMirrorGYTargetForSearch(); + if (gy == null) return false; + + AI.SelectCard(gy); + + var wants = Mirror_SearchOrderForType(false, gy.IsMonster()); + AI.SelectNextCard(wants); + return true; + } + + if (CheckSpellWillBeNegate()) return false; + if (CheckWhetherNegated()) return false; + var cost = PickMirrorCostCandidate(); + if (cost == null) return false; + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (m.IsMonsterShouldBeDisabledBeforeItUseEffect() && !m.IsDisabled() && Duel.LastChainPlayer != 0) + { + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(m); + AI.SelectNextCard(cost); + return true; + } + } + ClientCard LastChainCard = Util.GetLastChainCard(); + if ((LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || LastChainCard.IsDisabled() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget())) + return false; + + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemyMonsters = Enemy.GetMonsters(); + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + foreach (ClientCard card in enemyMonsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + } + } + } + AI.SelectNextCard(cost); + return true; + } + private bool Flow3_Link_Accesscode() + { + if (Bot.HasInExtra(CardId.AlliedCodeTalkerIgnister)) return false; + if (BlockAccesscodeOnT1()) return false; + + var avoid = new[] { CardId.AlliedCodeTalkerIgnister, CardId.FirewallDragon }; + + var mats = PickLinkMatsMinCount( + targetLink: 4, + isEligible: m => m.HasType(CardType.Effect), + minCount: 2, + maxCount: 4, + avoidIds: avoid + ); + + if (mats.Count < 2) return false; + AI.SelectMaterials(mats); + return true; + } + private bool Flow3_BackupIgnister_AfterMakeIt3() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (!madeIt3) return false; + if (Card.Location != CardLocation.Hand) return false; + + avoidLinkedZones = true; + return true; + } + private bool Flow3_WizardIgnister_AfterMakeIt3() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (!madeIt3) return false; + if (Card.Location != CardLocation.Hand) return false; + + var revive = PickGYMalissPriority(); + if (revive == null) return false; + + avoidLinkedZones = true; + AI.SelectCard(revive); + return true; + } + private bool RR_SS_FromBanished() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Id != CardId.MalissQ_RedRansom) return false; + if (Card.Location != CardLocation.Removed) return false; + if (GetMMZCount() >= 5) return false; + if (Bot.LifePoints <= 900) + { + return false; + } + + int pickId = 0; + + int[] pawnOrder = { + CardId.MalissP_ChessyCat, + CardId.MalissP_MarchHare, + CardId.MalissP_WhiteRabbit, + CardId.MalissP_Dormouse + }; + + foreach (var id in pawnOrder) + { + if (CheckRemainInDeck(id) > 0 && PawnSelfSS_AvailableId(id)) + { + pickId = id; + break; + } + } + + + bool canBanish = (pickId != 0); + AI.SelectYesNo(canBanish); + if (canBanish) + { + AI.SelectCard(pickId); + } + _rrSelfSSPlacing = true; + ssRRThisTurn = true; + return true; + } + private bool Wicckid_SearchTuner() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (CheckRemainInDeck(CardId.BackupIgnister) <= 0) return false; + var cost = PickGYCyberseForWicckidCost_Safe(); + if (cost == null) + { + return false; + } + + AI.SelectCard(cost); + AI.SelectNextCard(CardId.BackupIgnister); + avoidLinkedZones = false; + return true; + } + private bool LinkDecoder_ReviveFromGY() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Location != CardLocation.Grave) { return false; } + if (Allied_End) { return false; } + return true; + } + private bool Transcode_ReviveLink3OrLower() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Location != CardLocation.MonsterZone) return false; + + var prefer = Bot.Graveyard.GetFirstMatchingCard(c => c.IsCode(CardId.CyberseWicckid)) + ?? Bot.Graveyard.GetFirstMatchingCard(c => c.IsCode(CardId.SplashMage)) + ?? Bot.Graveyard.GetFirstMatchingCard(c => c.IsCode(CardId.MalissQ_RedRansom)) + ?? Bot.Graveyard.GetFirstMatchingCard(c => c.IsCode(CardId.MalissQ_WhiteBinder)) + ?? Bot.Graveyard + .GetMatchingCards(c => c.IsMonster() && c.HasType(CardType.Link) && c.LinkCount <= 3 && !c.IsCode(CardId.TranscodeTalker)) + .OrderByDescending(c => c.Attack).FirstOrDefault(); + + if (prefer == null) return false; + AI.SelectCard(prefer); + avoidLinkedZones = false; + return true; + } + private bool Allied_NegateBanish() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (CheckWhetherNegated(true) || !CheckLastChainShouldNegated()) return false; + var allied = Bot.MonsterZone.GetFirstMatchingCard(m => m != null && m.IsCode(CardId.AlliedCodeTalkerIgnister)); + if (allied == null || allied.IsDisabled()) return false; + bool haveAnyLink = Bot.GetMonsters().Any(m => m != null && m.HasType(CardType.Link) && !m.IsCode(CardId.AlliedCodeTalkerIgnister)); + if (!haveAnyLink) return false; + + var cheapLinks = new List { + CardId.CyberseWicckid, + CardId.MalissQ_WhiteBinder, + CardId.TranscodeTalker, + CardId.MalissQ_RedRansom + }; + AI.SelectCard(cheapLinks.ToArray()); + return true; + } + private ClientCard GetWicckid() + { + return Bot.MonsterZone.GetFirstMatchingFaceupCard(c => c != null && c.IsCode(CardId.CyberseWicckid)); + } + private int GetLinkedMaskFor(ClientCard link) + { + if (link == null || !link.IsFaceup() || !link.HasType(CardType.Link)) return 0; + return link.GetLinkedZones() & 0x1F; + } + private bool PawnSelfSS_AvailableId(int id) + { + if (id == CardId.MalissP_Dormouse) return !ssDormouse; + if (id == CardId.MalissP_WhiteRabbit) return !ssWhiteRabbit; + if (id == CardId.MalissP_ChessyCat) return !ssChessyCat; + if (id == CardId.MalissP_MarchHare) return !ActiveMarchHare; + return false; + } + private bool QueenSelfSS_AvailableId(int id) + { + if (id == CardId.MalissQ_HeartsCrypter) return !ssHCThisTurn; + if (id == CardId.MalissQ_WhiteBinder) return !ssWBThisTurn; + if (id == CardId.MalissQ_RedRansom) return !ssRRThisTurn; + return false; + } + private bool Dormouse_Banish_Anytime() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Id != CardId.MalissP_Dormouse) return false; + if (Card.Location != CardLocation.MonsterZone) return false; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (enemyActivateLancea) return false; + if (!HasFreeMMZ()) return false; + + int pick = 0; + + if (CheckRemainInDeck(CardId.MalissP_WhiteRabbit) > 0 && PawnSelfSS_AvailableId(CardId.MalissP_WhiteRabbit)) + pick = CardId.MalissP_WhiteRabbit; + else if (CheckRemainInDeck(CardId.MalissP_ChessyCat) > 0 && PawnSelfSS_AvailableId(CardId.MalissP_ChessyCat)) + pick = CardId.MalissP_ChessyCat; + + if (pick == 0) return false; + + AI.SelectCard(pick); + return true; + } + private bool IsCyberse(ClientCard c) => c != null && c.HasType(CardType.Monster) && c.HasRace(CardRace.Cyberse); + private bool RR_HOPT_Spent_ThisTurn() => ssRRThisTurn; + private bool RR_CanStillSS_ThisTurn() + { + if (RR_HOPT_Spent_ThisTurn()) return false; + return true; + } + private int Score_WicckidCost(ClientCard c) + { + if (c == null) return int.MinValue; + if (c.IsCode(CardId.MalissQ_RedRansom) && RR_HOPT_Spent_ThisTurn()) return -999; + if (c.IsCode(CardId.MalissQ_RedRansom) && RR_CanStillSS_ThisTurn()) return 1000; + + if (c.IsCode(CardId.Linguriboh) || c.IsCode(CardId.SALAMANGREAT_ALMIRAJ)) return 120; + + if (c.IsCode(CardId.MalissP_Dormouse) && ssDormouse) return 90; + if (c.IsCode(CardId.MalissP_WhiteRabbit) && ssWhiteRabbit) return 70; + if (c.IsCode(CardId.MalissP_ChessyCat) && ssChessyCat) return 60; + if (c.IsCode(CardId.MalissP_MarchHare) && ssMarchHare) return 60; + + if (c.IsCode(CardId.BackupIgnister)) return 20; + if (c.IsCode(CardId.WizardIgnister)) return 20; + return 30; + } + private ClientCard PickGYCyberseForWicckidCost_Safe() + { + var gy = (Bot.Graveyard ?? new List()) + .Where(IsCyberse) + .ToList(); + if (gy.Count == 0) return null; + + ClientCard best = null; + int bestScore = int.MinValue; + foreach (var c in gy) + { + int sc = Score_WicckidCost(c); + if (sc > bestScore) { best = c; bestScore = sc; } + } + return best; + } + private bool BlockAccesscodeOnT1() + { + bool blocked = (Duel.Player == 0 && Duel.Turn == 1); + return blocked; + } + private bool Allied_OnSummonTrigger() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + var me = Bot.MonsterZone.GetFirstMatchingCard(m => m != null && m.IsCode(CardId.AlliedCodeTalkerIgnister)); + if (me == null) return false; + + bool has2300 = Bot.Graveyard.Any(c => c != null && c.IsMonster() && c.HasRace(CardRace.Cyberse) && c.Attack == 2300); + if (!has2300) return false; + + var prefer = new List { + CardId.MalissQ_RedRansom, + CardId.MalissQ_WhiteBinder, + CardId.TranscodeTalker + }; + AI.SelectCard(prefer.ToArray()); + return true; + } + private bool ShouldSummonTranscode() + { + bool haveSplashGY = Bot.HasInGraveyard(CardId.SplashMage); + bool haveRR = Bot.HasInMonstersZone(CardId.MalissQ_RedRansom); + bool haveL1 = Bot.HasInMonstersZone(CardId.LinkDecoder) || Bot.HasInGraveyard(CardId.LinkDecoder); + + return haveSplashGY && (haveRR || haveL1); + } + private bool Step_SplashToRR() + { + if (_didSplashToRR) return false; + if (Bot.HasInMonstersZone(CardId.LinkDecoder)) return false; + + if (!Bot.HasInExtra(CardId.MalissQ_RedRansom)) return false; + + var mats = PickLinkMatsMinCount( + targetLink: 2, + isEligible: m => m.HasType(CardType.Effect), + minCount: 2, + maxCount: 2, + avoidIds: new[] { CardId.CyberseWicckid } + ); + if (mats.Count == 0) + { + return false; + } + + AI.SelectMaterials(mats); + + _didSplashToRR = true; + return true; + } + private bool Step_SplashToWB() + { + if (_didSplashToRR) return false; + + if (!Bot.HasInExtra(CardId.MalissQ_WhiteBinder)) return false; + + var mats = PickLinkMatsMinCount( + targetLink: 2, + isEligible: m => m.HasType(CardType.Effect), + minCount: 2, + maxCount: 2, + avoidIds: new[] { CardId.CyberseWicckid } + ); + if (mats.Count == 0) + { + return false; + } + + AI.SelectMaterials(mats); + + _didSplashToRR = true; + return true; + } + private bool Step_RRtoWicckid() + { + if(enemyActivateLancea) return false; + if (blockWicckid) return true; + if (!_didSplashToRR || _didRRtoWicckid) return false; + if (!Bot.HasInExtra(CardId.CyberseWicckid)) return false; + + var rr = Bot.MonsterZone.GetFirstMatchingCard(m => m != null && m.IsCode(CardId.MalissQ_RedRansom)); + if (rr == null) return false; + var emzOccupant = Bot.GetMonsters().FirstOrDefault(m => m != null && m != rr && IsInEMZ(m)); + var buddy = emzOccupant ?? Bot.MonsterZone.FirstOrDefault(m => m != null && m != rr); + if (buddy == null) return false; + bool emzWillBeFree = HasFreeEMZ() || IsInEMZ(rr) || IsInEMZ(buddy); + if (!emzWillBeFree) return false; + AI.SelectCard(CardId.CyberseWicckid); + AI.SelectMaterials(new List { rr, buddy }); + wantLinkedToWicckid = true; + _preferWicckidArrows = true; + _didRRtoWicckid = true; + return true; + } + private bool Step2N_RRtoWicckid() + { + if (enemyActivateLancea) return false; + if (blockWicckid) return false; + var rr = Bot.MonsterZone.GetFirstMatchingCard(m => m != null && m.IsCode(CardId.MalissQ_RedRansom)); + if (rr == null) return false; + var emzOccupant = Bot.GetMonsters().FirstOrDefault(m => m != null && m != rr && IsInEMZ(m)); + var buddy = emzOccupant ?? Bot.MonsterZone.FirstOrDefault(m => m != null && m != rr); + if (buddy == null) return false; + bool emzWillBeFree = HasFreeEMZ() || IsInEMZ(rr) || IsInEMZ(buddy); + if (!emzWillBeFree) return false; + AI.SelectCard(CardId.CyberseWicckid); + AI.SelectMaterials(new List { rr, buddy }); + wantLinkedToWicckid = true; + _preferWicckidArrows = true; + _didRRtoWicckid = true; + return true; + } + private bool Step_SummonLinkDecoderToWicckid() + { + if (!_didRRtoWicckid || _didSummonToWicckidArrow) return false; + + var wic = Bot.MonsterZone.GetFirstMatchingCard(m => m != null && m.IsCode(CardId.CyberseWicckid)); + if (wic == null) return false; + + _preferWicckidArrows = true; + avoidLinkedZones = false; + + return true; + } + private bool Step1_SSLinkDecoder() + { + if ((Bot.HasInMonstersZone(CardId.MalissP_Dormouse) || + Bot.HasInMonstersZone(CardId.MalissP_WhiteRabbit) || + Bot.HasInMonstersZone(CardId.MalissP_ChessyCat) || + Bot.HasInMonstersZone(CardId.BackupIgnister)) && Bot.GetMonsterCount() == 1 && Bot.HasInHand(CardId.MalissP_MarchHare)) + { + return true; + } + return false; + } + private bool IsMalissMonster(ClientCard c) => c != null && c.IsMonster() && c.HasSetcode(0x1bf); + private bool CanMakeLinkNWithFlexibleTwo(ClientCard a, ClientCard b, int target) + { + int a1 = 1, aL = (a != null && a.HasType(CardType.Link)) ? Math.Max(1, a.LinkCount) : 1; + int b1 = 1, bL = (b != null && b.HasType(CardType.Link)) ? Math.Max(1, b.LinkCount) : 1; + return (a1 + b1 == target) || (a1 + bL == target) || (aL + b1 == target) || (aL + bL == target); + } + private bool Step_WicckidPlusOneToWB() + { + const int WB_LINK = 3; + if (!Bot.HasInExtra(CardId.MalissQ_WhiteBinder)) return false; + + var wic = GetWicckid(); + if (wic != null) + { + var partners = Bot.GetMonsters() + .Where(m => m != null && m.IsFaceup() && m != wic && m.HasType(CardType.Effect)) + .ToList(); + + Func okPair = p => (IsMalissMonster(p) || IsMalissMonster(wic)) && CanMakeLinkNWithFlexibleTwo(wic, p, WB_LINK); + + var p2 = partners.FirstOrDefault(p => !p.IsCode(CardId.MalissQ_RedRansom) && okPair(p)) + ?? partners.FirstOrDefault(p => p.IsCode(CardId.MalissQ_RedRansom) && okPair(p)); + + if (p2 != null) + { + AI.SelectMaterials(new List { wic, p2 }); + _didWBFromWicckid = true; + EnsureFinishPlanAfterWB(); + return true; + } + } + + var mats = PickLinkMatsMinCount( + targetLink: WB_LINK, + isEligible: m => m.HasType(CardType.Effect), + minCount: 2, + maxCount: 3, + avoidIds: new[] { CardId.Apollousa, CardId.FirewallDragon, CardId.AlliedCodeTalkerIgnister }, + requireMaliss: true + ); + if (mats.Count == 0) return false; + + AI.SelectMaterials(mats); + _didWBFromWicckid = true; + EnsureFinishPlanAfterWB(); + return true; + } + private void EnsureFinishPlanAfterWB() + { + if (_finishPlanDecided) return; + + int free = Bot.MonsterZone.Count(m => m != null && !m.IsCode(CardId.MalissQ_RedRansom)); + bool canFW = Bot.HasInExtra(CardId.FirewallDragon); + bool canHC = Bot.HasInExtra(CardId.MalissQ_HeartsCrypter); + bool canAll = Bot.HasInExtra(CardId.AlliedCodeTalkerIgnister); + bool reachAllied = CanReachAlliedNow(); + + if (canFW && canHC && canAll && free >= 3 && reachAllied) + _finishPlan = FinishPlan.FW_HC_Allied; + else if (canHC && canAll && free >= 2 && reachAllied) + _finishPlan = FinishPlan.HC_Allied; + else + _finishPlan = FinishPlan.AlliedOnly; + + _finishPlanDecided = true; + } + private bool ssFromHandMH() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Location != CardLocation.Hand) return false; + if (GetMMZCount() > 3) return false; + if (enemyActivateLancea) return false; + + if (Duel.Player == 0) + { + var gy = Bot.Graveyard.GetMatchingCards(c => c != null && c.HasSetcode(0x1bf) && c != Card).ToList(); + + Func, ClientCard> pickP1 = (src) => + { + int[] pref = { + CardId.MalissQ_WhiteBinder, + CardId.MalissQ_HeartsCrypter, + CardId.MalissQ_RedRansom + }; + foreach (var id in pref) + { + var c = src.FirstOrDefault(x => x.HasType(CardType.Monster) && x.Id == id && QueenSelfSS_AvailableId(x.Id)); + if (c != null) return c; + } + return src.FirstOrDefault(x => x.HasType(CardType.Monster) && QueenSelfSS_AvailableId(x.Id)); + }; + ClientCard pick = pickP1(gy); + if (pick == null) return false; + AI.SelectCard(pick); + ssMarchHare = true; + return DontSelfNG(); + } + else + { + if (Bot.HasInGraveyard(CardId.MalissQ_WhiteBinder) && !ssWBThisTurn) + { + var Target = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(CardId.MalissQ_WhiteBinder)); + if (Target == null) return false; + AI.SelectCard(Target); + } + else if (Bot.HasInGraveyard(CardId.MalissQ_HeartsCrypter) && !ssHCThisTurn) + { + var Target = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(CardId.MalissQ_HeartsCrypter)); + if (Target == null) return false; + AI.SelectCard(Target); + } + else if (Bot.HasInGraveyard(CardId.MalissQ_RedRansom) && !ssRRThisTurn) + { + var Target = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(CardId.MalissQ_RedRansom)); + if (Target == null) return false; + AI.SelectCard(Target); + } + else + { + return false; + } + + ssMarchHare = true; + return DontSelfNG(); + } + } + private bool Step1_MH_FromHand() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Location != CardLocation.Hand) return false; + if (Bot.GetMonsterCount() > 1) return false; + if (enemyActivateLancea) return false; + + if (Bot.HasInMonstersZone(CardId.MalissP_WhiteRabbit) && Bot.HasInGraveyard(CardId.MalissC_MTP07)) + { + var target = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(CardId.MalissC_MTP07)); + if (target == null) return false; + AI.SelectCard(target); + ssMarchHare = true; + return DontSelfNG(); + } + if (Bot.HasInMonstersZone(CardId.LinkDecoder) && Bot.HasInGraveyard(CardId.MalissP_Dormouse)) + { + var target = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(CardId.MalissP_Dormouse)); + if (target == null) return false; + AI.SelectCard(target); + ssMarchHare = true; + return DontSelfNG(); + } + if (Bot.HasInMonstersZone(CardId.LinkDecoder) && Bot.HasInGraveyard(CardId.MalissP_WhiteRabbit)) + { + var target = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(CardId.MalissP_WhiteRabbit)); + if (target == null) return false; + AI.SelectCard(target); + ssMarchHare = true; + return DontSelfNG(); + } + if (Bot.HasInMonstersZone(CardId.LinkDecoder) && Bot.HasInGraveyard(CardId.MalissP_ChessyCat)) + { + var target = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(CardId.MalissP_ChessyCat)); + if (target == null) return false; + AI.SelectCard(target); + ssMarchHare = true; + return DontSelfNG(); + } + if (Bot.HasInMonstersZone(CardId.Linguriboh) && Bot.HasInGraveyard(CardId.MalissP_MarchHare)) + { + var target = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(CardId.MalissP_MarchHare)); + if (target == null) return false; + AI.SelectCard(target); + ssMarchHare = true; + return DontSelfNG(); + } + + return false; + } + private bool returnFromBanish() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Location != CardLocation.Removed) return false; + + var mh = Bot.Banished.GetFirstMatchingCard( + c => c.IsFaceup() && c.IsCode(CardId.MalissP_MarchHare)); + + if (mh == null) return false; + + AI.SelectCard(mh); + ActiveMarchHare = true; + return true; + } + private bool WB_OnSummon_BanishGY() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Location != CardLocation.MonsterZone) return false; + + const int MAX_PICKS = 3; + var picks = new List(); + + if (Duel.Player == 0) + { + int freeMMZ = Math.Max(0, 5 - GetMMZCount()); + int myPawnCount = Bot.Graveyard + .GetMatchingCards(g => IsMalissPawn(g)) + .Count; + bool canUseOwnPawn = myPawnCount > 1; + + if (!ActiveMarchHare && canUseOwnPawn) + { + var mh = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissP_MarchHare)); + if (mh != null) picks.Add(mh); + } + + if (freeMMZ > 0 && !ssRRThisTurn && !Allied_End) + { + var rr = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissQ_RedRansom)); + if (rr != null && !picks.Contains(rr) && !ShouldSkipBanishing(rr)) + { picks.Add(rr); freeMMZ--; } + } + + if (freeMMZ > 0 && !ssHCThisTurn && !Allied_End) + { + var hc = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissQ_HeartsCrypter)); + if (hc != null && !picks.Contains(hc) && !ShouldSkipBanishing(hc)) + { picks.Add(hc); freeMMZ--; } + } + + if (freeMMZ > 0 && !ssWhiteRabbit && !Allied_End && canUseOwnPawn) + { + var wr = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissP_WhiteRabbit)); + if (wr != null && !picks.Contains(wr) && !ShouldSkipBanishing(wr)) + { picks.Add(wr); freeMMZ--; } + } + + if (freeMMZ > 0 && !ssDormouse && !Allied_End && canUseOwnPawn) + { + var dm = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissP_Dormouse)); + if (dm != null && !picks.Contains(dm) && !ShouldSkipBanishing(dm)) + { picks.Add(dm); freeMMZ--; } + } + + if (freeMMZ > 0 && !ssChessyCat && !Allied_End && canUseOwnPawn) + { + var cc = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissP_ChessyCat)); + if (cc != null && !picks.Contains(cc) && !ShouldSkipBanishing(cc)) + { picks.Add(cc); freeMMZ--; } + } + + if (freeMMZ >= 0 && canUseOwnPawn) + { + var target = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissP_ChessyCat) || g.IsCode(CardId.MalissP_Dormouse)); + picks.Add(target); + } + + picks = picks.Where(c => c != null).Distinct().Take(MAX_PICKS).ToList(); + + var threats = PickEnemyGYThreats(MAX_PICKS - picks.Count); + foreach (var t in threats) + { + if (picks.Count >= MAX_PICKS) break; + if (!picks.Contains(t)) picks.Add(t); + } + } + else + { + int freeMMZ = Math.Max(0, 5 - GetMMZCount()); + + if (!Bot.HasInSpellZone(CardId.MalissC_MTP07) && freeMMZ > 0 && !ssWhiteRabbit) + { + var wr = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissP_WhiteRabbit)); + if (wr != null) { picks.Add(wr); freeMMZ--; } + } + + if (picks.Count >= 0 && !Bot.HasInHand(CardId.MalissP_MarchHare) && !ActiveMarchHare) + { + var mh = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissP_MarchHare)); + if (mh != null) picks.Add(mh); + } + + if (freeMMZ > 0 && !ssRRThisTurn) + { + var rr = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissQ_RedRansom)); + if (rr != null && !picks.Contains(rr) && !ShouldSkipBanishing(rr)) + { picks.Add(rr); freeMMZ--; } + } + + if (freeMMZ > 0 && !ssHCThisTurn) + { + var hc = Bot.Graveyard.GetFirstMatchingCard(g => g.IsCode(CardId.MalissQ_HeartsCrypter)); + if (hc != null && !picks.Contains(hc) && !ShouldSkipBanishing(hc)) + { picks.Add(hc); freeMMZ--; } + } + + var threats = PickEnemyGYThreats(MAX_PICKS - picks.Count); + foreach (var t in threats) + { + if (picks.Count >= MAX_PICKS) break; + if (!picks.Contains(t)) picks.Add(t); + } + } + + if (picks.Count == 0) return false; + + if (picks.Count > MAX_PICKS) picks = picks.Take(MAX_PICKS).ToList(); + if (picks.Count < MAX_PICKS) + { + var more = PickEnemyGYThreats(MAX_PICKS - picks.Count); + foreach (var t in more) + if (!picks.Contains(t)) picks.Add(t); + } + AI.SelectCard(picks); + return true; + } + private bool IsMalissPawn(ClientCard c) + { + return c != null && ( + c.IsCode(CardId.MalissP_ChessyCat) || + c.IsCode(CardId.MalissP_WhiteRabbit) || + c.IsCode(CardId.MalissP_Dormouse) || + c.IsCode(CardId.MalissP_MarchHare) + ); + } + private List PickEnemyGYThreats(int need) + { + var result = new List(); + if (need <= 0) return result; + + var danger = GetDangerousCardinEnemyGrave(false); + foreach (var c in danger) + { + if (result.Count >= need) break; + if (!result.Contains(c)) result.Add(c); + } + + if (result.Count < need) + { + for (int i = Enemy.Graveyard.Count - 1; i >= 0 && result.Count < need; i--) + { + var c = Enemy.Graveyard[i]; + if (c == null) continue; + if (!result.Contains(c)) result.Add(c); + } + } + + if (result.Count < need) + { + foreach (var c in Enemy.Graveyard) + { + if (result.Count >= need) break; + if (!result.Contains(c)) result.Add(c); + } + } + + return result; + } + private bool WB_OnBanished_SelfSS() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Location != CardLocation.Removed) return false; + if (GetMMZCount() >= 5) return false; + if (Bot.LifePoints <= 900) + { + return false; + } + AI.SelectYesNo(true); + ssWBThisTurn = true; + return true; + } + private int PickMalissTrapForWB() + { + if (CheckRemainInDeck(CardId.MalissC_GWC06) > 0 || Bot.HasInGraveyard(CardId.MalissC_GWC06)) + return CardId.MalissC_GWC06; + + if (CheckRemainInDeck(CardId.MalissC_MTP07) > 0 || Bot.HasInGraveyard(CardId.MalissC_MTP07)) + return CardId.MalissC_MTP07; + + return 0; + } + private bool WB_SetMalissTrap() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (ActivateDescription != Util.GetStringId(CardId.MalissQ_WhiteBinder, 1)) return false; + if (Card.Location != CardLocation.MonsterZone) return false; + + + SelectSafeSTZoneAwayFromImperm(); + return true; + } + private List PickLinkMatsMinCount(int targetLink, + Func isEligible, + int minCount, + int maxCount, + IEnumerable avoidIds = null, + bool requireMaliss = false) + { + var all = Bot.GetMonsters() + .Where(m => m != null && m.IsFaceup() && isEligible(m)) + .ToList(); + if (all.Count < minCount) return new List(); + + var avoid = new HashSet(avoidIds ?? Enumerable.Empty()); + + Func, List> OrderForFirst = (src) => src.OrderByDescending(LinkValOf) + .ThenBy(m => avoid.Contains(m.Id) ? 1 : 0) + .ThenBy(m => m.Attack) + .ToList(); + + Func, List> OrderForLater = (src) => src.OrderBy(m => IsOneVal(m) ? 0 : 1) + .ThenBy(m => m.HasType(CardType.Link) ? (Math.Max(1, m.LinkCount) == 1 ? 0 : 1) : -1) + .ThenBy(LinkValOf) + .ThenBy(m => avoid.Contains(m.Id) ? 1 : 0) + .ThenBy(m => m.Attack) + .ToList(); + + var poolPreferred = all.Where(m => !avoid.Contains(m.Id)).ToList(); + var poolFallback = all.ToList(); + + int firstMaxAllowed = targetLink - Math.Max(0, minCount - 1); + + Func, List> TryPick = (pool) => + { + var chosen = new List(); + Func, int, bool> Dfs = null; + Dfs = (avail, sum) => + { + if (sum > targetLink || chosen.Count > maxCount) return false; + + if (chosen.Count >= minCount && sum == targetLink) + { + if (requireMaliss && !chosen.Any(IsMalissBody)) return false; + if (Util.GetBotAvailZonesFromExtraDeck(chosen) == 0) return false; + return true; + } + + int need = Math.Max(0, minCount - chosen.Count); + if (sum + need > targetLink) return false; + + var ordered = (chosen.Count == 0) + ? OrderForFirst(avail) + : OrderForLater(avail); + + for (int i = 0; i < ordered.Count; i++) + { + var m = ordered[i]; + var nextAvail = ordered.Where((x, idx) => idx != i).ToList(); + int lv = LinkValOf(m); + + int[] values = (chosen.Count == 0) + ? (lv > 1 ? new[] { Math.Min(lv, firstMaxAllowed), 1 } : new[] { 1 }) + : (lv > 1 ? new[] { 1, lv } : new[] { 1 }); + + foreach (var v in values.Distinct()) + { + int newSum = sum + v; + if (newSum > targetLink) continue; + + int remMin = Math.Max(0, minCount - (chosen.Count + 1)); + if (newSum + remMin > targetLink) continue; + + chosen.Add(m); + if (Dfs(nextAvail, newSum)) return true; + chosen.RemoveAt(chosen.Count - 1); + } + } + return false; + }; + + if (Dfs(OrderForFirst(pool), 0)) return chosen; + return null; + }; + + var pick = TryPick(poolPreferred); + if (pick != null && pick.Count > 0) return pick; + + pick = TryPick(poolFallback); + return pick ?? new List(); + } + private bool Link_Apo() + { + if (!(Bot.HasInMonstersZone(CardId.MalissQ_RedRansom) && + Bot.HasInMonstersZone(CardId.LinkDecoder))) return false; + + + var mats = PickLinkMatsMinCount( + targetLink: 4, + isEligible: m => m.HasType(CardType.Monster), + minCount: 2, + maxCount: 2, + avoidIds: new[] { CardId.TranscodeTalker, CardId.AlliedCodeTalkerIgnister, CardId.AccesscodeTalker } + ); + if (mats.Count == 0) return false; + AI.SelectMaterials(mats); + blockWicckid = true; + return true; + } + private bool Flow3_Link_Firewall() + { + if (Bot.HasInMonstersZone(CardId.MalissQ_HeartsCrypter) && Bot.HasInMonstersZone(CardId.LinkDecoder) && Bot.HasInMonstersZone(CardId.CyberseWicckid)) + { + var mats = PickLinkMatsMinCount( + targetLink: 4, + isEligible: m => m.HasType(CardType.Monster), + minCount: 2, + maxCount: 2, + avoidIds: new[] { CardId.CyberseWicckid, CardId.Apollousa, CardId.TranscodeTalker, CardId.AlliedCodeTalkerIgnister, CardId.AccesscodeTalker } + ); + if (mats.Count == 0) return false; + AI.SelectMaterials(mats); + return true; + } + return false; + } + private bool Step_LinkSummon_HeartsCrypter() + { + if((Bot.HasInMonstersZone(CardId.MalissQ_WhiteBinder) && Bot.HasInMonstersZone(CardId.MalissQ_RedRansom) && + Bot.HasInMonstersZone(CardId.Apollousa) && Bot.GetMonsterCount() < 5)) return false; + var cand = Bot.GetMonsters() + .Where(c => c != null && c.IsFaceup() && c.HasType(CardType.Effect)) + .ToList(); + if (cand.Count < 3) return false; + + var avoid = new HashSet { CardId.CyberseWicckid, CardId.Apollousa, CardId.AlliedCodeTalkerIgnister, CardId.AccesscodeTalker, CardId.FirewallDragon, CardId.TranscodeTalker }; + + var ordered = cand + .OrderBy(m => avoid.Contains(m.Id) ? 2 : 0) + .ThenBy(m => m.HasType(CardType.Link) ? 1 : 0) + .ThenBy(m => m.Attack) + .ToList(); + + List mats = ordered.Take(3).ToList(); + if (!mats.Any(IsMaliss)) + { + var maliss = ordered.FirstOrDefault(IsMaliss); + if (maliss == null) return false; + mats[2] = maliss; + } + + if (Util.GetBotAvailZonesFromExtraDeck(mats) == 0) return false; + AI.SelectMaterials(mats); + return true; + } + private bool HC_Quick_ReturnBanished_AndBanishField() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (ActivateDescription != Util.GetStringId(CardId.MalissQ_HeartsCrypter, 0)) return false; + if (Card.Location != CardLocation.MonsterZone) return false; + if (CheckWhetherNegated()) return false; + + RefreshNoChainWindows(); + + var banishedMaliss = GetBanishedMaliss(); + if (banishedMaliss.Count == 0) return false; + bool haveReturn = banishedMaliss.Count > 0; + + bool mustNow = GetProblematicEnemyCardList( + canBeTarget: true, + selfType: CardType.Monster | CardType.Spell | CardType.Trap + ).Count > 0; + + if (Duel.Player == 0) + { + if (!haveReturn && !mustNow) return false; + } + else + { + if (!mustNow && !IsPreferredRemovalTiming()) return false; + } + + if (!haveReturn) return false; + var ret = PickBanishedMalissForHC(banishedMaliss); + if (ret == null) return false; + + var fieldTargets = GetProblematicEnemyCardList(true, selfType: CardType.Monster | CardType.Spell | CardType.Trap); + if (fieldTargets.Count == 0) + { + var any = GetBestEnemyCard(false, true); + if (any != null) fieldTargets.Add(any); + } + if (fieldTargets.Count == 0) return false; + + AI.SelectCard(ret); + AI.SelectNextCard(fieldTargets); + ConsumePreferredWindow(); + return DontSelfNG(); + } + private List GetBanishedMaliss() + { + return Bot.Banished.GetMatchingCards(c => + c != null && c.IsFaceup() && c.HasSetcode(0x1bf)).ToList(); + } + private ClientCard PickBanishedMalissForHC(List cand) + { + cand = cand + .Where(c => !c.IsCode(CardId.MalissQ_WhiteBinder) && !c.IsCode(CardId.MalissQ_RedRansom)) + .ToList(); + if (cand.Count == 0) return null; + + return cand.OrderByDescending(ScoreForBanishedMaliss).First(); + } + private bool HC_OnBanished_SpecialSummon() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Card.Location != CardLocation.Removed) return false; + + if (GetMMZCount() >= 5) + { + return false; + } + + if (Bot.LifePoints <= 900) + { + return false; + } + + AI.SelectYesNo(true); + ssHCThisTurn = true; + return true; + } + private bool HasMalissLinkFaceup() + { + return Bot.GetMonsters().Any(c => c != null && c.IsFaceup() && c.HasSetcode(0x1bf) && c.HasType(CardType.Link)); + } + private bool CanReachAlliedNow() + { + var mats = PickLinkMatsMinCount( + targetLink: 5, + isEligible: m => m.HasType(CardType.Effect), + minCount: 3, + maxCount: 5, + avoidIds: new[] { CardId.Apollousa, CardId.FirewallDragon, CardId.AccesscodeTalker } + ); + return mats.Count > 0; + } + private bool Flow3_Link_Allied() + { + if (!(Bot.HasInMonstersZoneOrInGraveyard(CardId.MalissQ_RedRansom) && Bot.HasInMonstersZoneOrInGraveyard(CardId.MalissQ_WhiteBinder))) return false; + var mats = PickLinkMatsMinCount( + targetLink: 5, + isEligible: m => m.HasType(CardType.Effect), + minCount: 3, + maxCount: 5, + avoidIds: new[] { CardId.Apollousa, CardId.FirewallDragon, CardId.AccesscodeTalker } + ); + if (mats.Count == 0) + { + return false; + } + + AI.SelectMaterials(mats); + Allied_End = true; + return true; + } + private bool Emer_Allied() + { + if(!enemyActivateLancea) return false; + if (!(Bot.HasInMonstersZone(CardId.TranscodeTalker) && Bot.HasInMonstersZone(CardId.SplashMage))) return false; + var mats = PickLinkMatsMinCount( + targetLink: 5, + isEligible: m => m.HasType(CardType.Effect), + minCount: 3, + maxCount: 3 + ); + if (mats.Count == 0) + { + return false; + } + + AI.SelectMaterials(mats); + Allied_End = true; + return true; + } + private bool Emer_Allied2() + { + var myMonsters = Bot.GetMonsters().Where(m => m != null).ToList(); + if (myMonsters.Count != 3) return false; + + var link3List = myMonsters + .Where(m => m.HasType(CardType.Link) && m.LinkCount == 3) + .ToList(); + + if (link3List.Count != 1) return false; + + bool haveKeyInGY = + Bot.HasInGraveyard(CardId.MalissQ_RedRansom) || + Bot.HasInGraveyard(CardId.MalissQ_WhiteBinder) || + Bot.HasInGraveyard(CardId.TranscodeTalker); + + if (!haveKeyInGY) return false; + + var mats = PickLinkMatsMinCount( + targetLink: 5, + isEligible: m => m.HasType(CardType.Effect), + minCount: 3, + maxCount: 3 + ); + if (mats.Count == 0) + { + return false; + } + + AI.SelectMaterials(mats); + Allied_End = true; + return true; + } + private ClientCard FindGWC06TargetByOrder(params int[] ids) + { + foreach (var id in ids) + { + var gy = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(id)); + if (gy != null) return gy; + + var ban = Bot.Banished.GetFirstMatchingCard(c => c != null && c.IsCode(id) && c.IsFaceup()); + if (ban != null) return ban; + } + return null; + } + private int PickGWC06CostCandidateId() + { + if (Bot.HasInMonstersZone(CardId.MalissQ_WhiteBinder) && !ssWBThisTurn) + return CardId.MalissQ_WhiteBinder; + if (Bot.HasInMonstersZone(CardId.MalissQ_RedRansom) && !ssRRThisTurn) + return CardId.MalissQ_RedRansom; + + int card = PickTB11CostCandidateId(); + if (card != 0) return card; + + return 0; + } + private ClientCard PickGWC06TargetExtend() + { + if (Duel.Turn > 2) + { + return FindGWC06TargetByOrder( + CardId.MalissQ_HeartsCrypter, + CardId.MalissQ_RedRansom, + CardId.MalissQ_WhiteBinder + ); + } + else { + return FindGWC06TargetByOrder( + CardId.MalissQ_WhiteBinder, + CardId.MalissQ_RedRansom, + CardId.MalissQ_HeartsCrypter, + CardId.MalissP_WhiteRabbit, + CardId.MalissP_Dormouse, + CardId.MalissP_ChessyCat, + CardId.MalissP_MarchHare + ); + } + } + private bool GWC06_MyTurn_Extend() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (Duel.Player == 0 && + GetMMZCount() >= 4 && + Bot.HasInMonstersZone(CardId.FirewallDragon) && + (Bot.HasInMonstersZoneOrInGraveyard(CardId.MalissQ_RedRansom) || + Bot.HasInMonstersZoneOrInGraveyard(CardId.MalissQ_WhiteBinder) || + Bot.HasInMonstersZoneOrInGraveyard(CardId.MalissQ_HeartsCrypter))) return false; + if (Duel.Player != 0) return false; + if (!(Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2)) return false; + if (CheckSpellWillBeNegate()) return false; + if (GetMMZCount() >= 5) return false; + if (!Bot.HasInMonstersZone(CardId.MalissQ_WhiteBinder) && !(Bot.HasInMonstersZone(CardId.MalissQ_RedRansom) && Bot.GetMonsterCount() == 1)) return false; + var target = PickGWC06TargetExtend(); + if (target == null) return false; + if (gwc06SetThisTurn) + { + int costId = PickGWC06CostCandidateId(); + if (costId == 0) return false; + AI.SelectCard(costId); + AI.SelectNextCard(target); + return DontSelfNG(); + } + AI.SelectCard(target); + return DontSelfNG(); + } + private bool GWC06_OppTurn_ReviveWB_HC() + { + if (Duel.Player != 1) return false; + if (!Bot.HasInSpellZone(CardId.MalissC_GWC06)) return false; + if (CheckSpellWillBeNegate()) return false; + if (GetMMZCount() >= 5) return false; + + var target = FindGWC06TargetByOrder( + CardId.MalissQ_WhiteBinder, + CardId.MalissQ_HeartsCrypter + ); + if (target == null) return false; + + if (gwc06SetThisTurn) + { + int costId = PickGWC06CostCandidateId(); + if (costId == 0) return false; + AI.SelectCard(costId); + AI.SelectNextCard(target); + return DontSelfNG(); + } + + AI.SelectCard(target); + return DontSelfNG(); + } + private static int FirstBit(int mask) + { + for (int i = 0; i < 32; i++) + { + int b = 1 << i; + if ((mask & b) != 0) return b; + } + return 0; + } + private static int FirstBitFromOrder(int mask, int[] order) + { + foreach (var b in order) + if ((mask & b) != 0) return b; + return FirstBit(mask); + } + private int PreferSafeSummonZones(int available) + { + int MAIN_MASK = + (int)Zones.z0 | + (int)Zones.z1 | + (int)Zones.z2 | + (int)Zones.z3 | + (int)Zones.z4; + + int emzMask = available & ~MAIN_MASK; + + if (emzMask != 0) + return FirstBit(emzMask); + + int enemyPointed = 0; + try + { + enemyPointed = Enemy.GetLinkedZones(); + } + catch { } + + int safeMain = (available & MAIN_MASK) & ~enemyPointed; + + if (safeMain != 0) + { + return FirstBitFromOrder( + safeMain, + new[] { (int)Zones.z2, (int)Zones.z1, (int)Zones.z3, (int)Zones.z0, (int)Zones.z4 } + ); + } + + return FirstBit(available); + } + private int PickMTP07CostCandidateId() + { + return PickTB11CostCandidateId(); + } + private ClientCard PickMTP07EnemyRemovalTarget() + { + var list = GetProblematicEnemyCardList(canBeTarget: true, ignoreSpells: false, selfType: CardType.Trap); + if (list.Count > 0) return list[0]; + + var m = GetBestEnemyMonster(onlyFaceup: false, canBeTarget: true); + if (m != null) return m; + + var s = GetBestEnemySpell(onlyFaceup: false, canBeTarget: true); + if (s != null) return s; + + return Enemy.GetMonsters().FirstOrDefault(c => c != null) + ?? Enemy.GetSpells().FirstOrDefault(c => c != null); + } + private bool MTP07_ForMH() + { + if (!(Bot.GetMonsterCount() == 1 && Bot.HasInMonstersZone(CardId.MalissP_WhiteRabbit))) return false; + if (CheckSpellWillBeNegate()) return false; + if (CheckWhetherNegated()) return false; + + int searchId = PickMTP07SearchId(); + if (searchId == 0) return false; + + if (mtp07SetThisTurn) + { + int costId = PickMTP07CostCandidateId(); + if (costId == 0) return false; + AI.SelectCard(costId); + } + AI.SelectNextCard(searchId); + return DontSelfNG(); + } + private bool MTP07_OppTurn_RemoveEnemyOnly() + { + if (Duel.Player != 1) return false; + if (!HasMalissLinkFaceup()) return false; + if (CheckSpellWillBeNegate()) return false; + if (CheckWhetherNegated()) return false; + var urgent = GetProblematicEnemyCardList(canBeTarget: true, ignoreSpells: false, selfType: CardType.Trap); + if (urgent.Count == 0 && !IsPreferredRemovalTiming()) return false; + bool preBattle = Duel.Phase == DuelPhase.Main1 && Enemy.GetMonsterCount() > 0; + if (urgent.Count == 0 && !(IsPreferredRemovalTiming() || preBattle)) return false; + int searchId = PickMTP07SearchId(); + if (searchId == 0) return false; + ClientCard target = null; + if (urgent.Count > 0) + { + target = urgent[0]; + } + else if (preBattle) + { + target = Enemy.MonsterZone + .Where(c => c != null && c.IsFaceup()) + .OrderByDescending(c => c.Attack) + .FirstOrDefault(); + } + else + { + target = PickMTP07EnemyRemovalTarget(); + } + if (target == null) return false; + if (mtp07SetThisTurn) + { + int costId = PickMTP07CostCandidateId(); + if (costId == 0) return false; + AI.SelectCard(costId); + AI.SelectNextCard(searchId); + AI.SelectNextCard(target); + ConsumePreferredWindow(); + return DontSelfNG(); + } + AI.SelectCard(searchId); + AI.SelectNextCard(target); + ConsumePreferredWindow(); + return DontSelfNG(); + } + private bool Emergency_NS() + { + if (usedNormalSummon) return false; + if (Bot.GetMonsterCount() != 0) return false; + if (Bot.HasInHand(CardId.MalissP_Dormouse) || Bot.HasInHand(CardId.MalissP_WhiteRabbit) + || Bot.HasInHand(CardId.MalissP_ChessyCat) + || Bot.HasInHand(CardId.GoldSarcophagus) || Bot.HasInHand(CardId.MalissInUnderground)) return false; + if (!Bot.HasInHand(CardId.BackupIgnister)) return false; + usedNormalSummon = true; + nsplan = true; + return true; + } + private bool IsWicInEMZ(ClientCard wic) + { + return wic != null + && wic.Location == CardLocation.MonsterZone + && (wic.Sequence == EMZ_LEFT || wic.Sequence == EMZ_RIGHT); + } + private IEnumerable GetWicDownSeq(ClientCard wic) + { + if (!IsWicInEMZ(wic)) yield break; + if (wic.Sequence == EMZ_LEFT) { yield return 1; yield return 2; } + if (wic.Sequence == EMZ_RIGHT) { yield return 3; yield return 4; } + } + private bool IsUnderWic(ClientCard wic, ClientCard m) + { + if (wic == null || m == null) return false; + if (m.Controller != wic.Controller) return false; + if (m.Location != CardLocation.MonsterZone) return false; + if (m.Sequence < 0 || m.Sequence > 4) return false; + return GetWicDownSeq(wic).Contains(m.Sequence); + } + private ClientCard PickUnderlingForTranscode(ClientCard wic, System.Collections.Generic.IList pool) + { + if (!IsWicInEMZ(wic)) return null; + var underlings = pool.Where(x => x != null && x != wic && x.IsFaceup() + && x.Location == CardLocation.MonsterZone + && x.Controller == wic.Controller + && x.Sequence >= 0 && x.Sequence <= 4 + && IsUnderWic(wic, x) + && (x.HasType(CardType.Link) || x.HasType(CardType.Effect)) + && !x.HasType(CardType.Token)) + .ToList(); + + if (underlings.Count == 0) return null; + + var preferLD = underlings.FirstOrDefault(x => x.IsCode(CardId.LinkDecoder)); + if (preferLD != null) return preferLD; + return underlings + .OrderByDescending(x => x.HasType(CardType.Link) ? 2 : 1) + .ThenByDescending(x => x.Attack) + .FirstOrDefault(); + } + private static readonly int[] PreferCenterMainSeq = new[] { 2, 1, 3, 0, 4 }; + + private bool SummonTranscode() + { + if (!enemyActivateLancea) return false; + var wic = Bot.GetMonsters().FirstOrDefault( + x => x != null && x.IsFaceup() && x.IsCode(CardId.CyberseWicckid)); + + if (!IsWicInEMZ(wic)) return false; + + var under = PickUnderlingForTranscode(wic, Bot.GetMonsters()); + if (under == null) return false; + + SelectLinkMaterialsPair(wic, under); + + int emz = EmzBitFor(wic); + if (emz != 0) AI.SelectPlace(emz); + + return true; + } + private void SelectLinkMaterialsPair(ClientCard a, ClientCard b) + { + try + { + var mats = new System.Collections.Generic.List { a, b }; + AI.SelectMaterials(mats); + return; + } + catch { } + + AI.SelectCard(a); + AI.SelectNextCard(b); + } + private int EmzBitFor(ClientCard link) + { + if (link == null || link.Location != CardLocation.MonsterZone) return 0; + if (link.Sequence == EMZ_LEFT) return 1 << EMZ_LEFT; // 1<<5 + if (link.Sequence == EMZ_RIGHT) return 1 << EMZ_RIGHT; // 1<<6 + return 0; + } + int ChooseAndRememberWicckidEmz(int available) + { + int emzAvail = available & EMZ_ALL; + if (emzAvail == 0) return 0; + + int best = 0; + int bestScore = int.MinValue; + + foreach (int emz in new[] { EMZ_L, EMZ_R }) + { + if ((emzAvail & emz) == 0) continue; + + int score = 0; + int down = DownBitOfEmz(emz); + + if (down == MZ1 && IsMainFreeSeq(1)) score += 10; + if (down == MZ3 && IsMainFreeSeq(3)) score += 10; + + if (score > bestScore) + { + bestScore = score; + best = emz; + } + } + + if (best == 0) + best = (emzAvail & EMZ_L) != 0 ? EMZ_L : EMZ_R; + + _wicckidEmzBit = best; + return best; + } + bool IsMainFreeSeq(int seq) + { + var ms = Bot.MonsterZone.GetMonsters(); + var occupied = ms.Any(m => m != null && m.Controller == 0 && m.Sequence == seq); + return !occupied; + } + int DownBitOfEmz(int emzBit) + { + if (emzBit == EMZ_L) return MZ1; + if (emzBit == EMZ_R) return MZ3; + return 0; + } + private bool IsPreferredRemovalTiming() + { + if (Duel.Player != 1) return false; + if (_prefWindowTTL > 0) return true; + if (_oppJustActivatedPersistentSpell || _oppJustSummoned || _oppJustSet) return true; + + return false; + } + private void ConsumePreferredWindow() + { + _prefWindowTTL = 0; + _oppJustActivatedPersistentSpell = false; + _oppJustSummoned = false; + _oppJustSet = false; + } + private void RefreshNoChainWindows() + { + bool oppMain = (Duel.Player == 1) && (Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2); + + int curMon = Enemy.GetMonsterCount(); + if (curMon > _enemyMonsterCountSnap) + { + _oppJustSummoned = true; + if (oppMain) _prefWindowTTL = Math.Max(_prefWindowTTL, 2); + } + _enemyMonsterCountSnap = curMon; + + int curFD = Enemy.SpellZone.Count(c => c != null && c.IsFacedown()); + if (curFD > _enemyFacedownSTSnap) + { + _oppJustSet = true; + if (oppMain) _prefWindowTTL = Math.Max(_prefWindowTTL, 2); + } + _enemyFacedownSTSnap = curFD; + + if (oppMain) + { + if (_prefWindowTTL > 0) _prefWindowTTL--; + if (_prefWindowTTL == 0) + { + _oppJustActivatedPersistentSpell = false; + _oppJustSummoned = false; + _oppJustSet = false; + } + } + else + { + _prefWindowTTL = 0; + _oppJustActivatedPersistentSpell = false; + _oppJustSummoned = false; + _oppJustSet = false; + } + } + private bool FirewallBounce_OnOppSummon() + { + if (DefaultCheckWhetherCardIdIsNegated(Card.Id)) return false; + if (ActivateDescription != Util.GetStringId(CardId.FirewallDragon, 0)) + return false; + + if (Duel.LastSummonPlayer != 1) + return false; + + var picks = new List(); + + var negateList = GetMonsterListForTargetNegate(); + if (negateList != null) + { + foreach (var c in negateList) + { + if (c == null) continue; + if (c.Controller != 1) continue; + if (!c.IsMonster()) continue; + if (!c.IsFaceup()) continue; + if (!picks.Contains(c)) + picks.Add(c); + } + } + foreach (var m in Enemy.GetMonsters().OrderByDescending(x => x.Attack)) + { + if (m == null) continue; + if (!m.IsMonster()) continue; + if (!m.IsFaceup()) continue; + if (!picks.Contains(m)) + picks.Add(m); + } + + if (picks.Count == 0) + return false; + + AI.SelectCard(picks); + return true; + } + private bool Accesscode_OnSummon_AtkUp() + { + var list = new List(); + int[] prefer = { + CardId.MalissQ_HeartsCrypter, + CardId.MalissQ_WhiteBinder, + CardId.MalissQ_RedRansom, + CardId.TranscodeTalker + }; + foreach (var id in prefer) + { + var hit = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(id)); + if (hit != null) list.Add(hit); + } + + AI.SelectCard(list); + return true; + } + + private bool Accesscode_Destroy_Ignition() + { + if (ActivateDescription != Util.GetStringId(CardId.AccesscodeTalker, 1)) + return false; + + if (Enemy.GetFieldCount() == 0) + return false; + + IEnumerable costPool = + (Bot.GetGraveyardMonsters() ?? Enumerable.Empty()) + .Where(c => c.HasType(CardType.Link)) + .Concat((Bot.GetMonsters() ?? Enumerable.Empty()) + .Where(c => c.HasType(CardType.Link) && c != Card)); + + var costList = costPool + .OrderBy(c => c.Location != CardLocation.Grave) + .ThenBy(c => c.LinkCount) + .ThenBy(c => c.Attack) + .ToList(); + + if (costList.Count == 0) + return false; + + var targets = new List(); + + targets.AddRange(Enemy.GetSpells() + .Where(s => s != null && s.IsFacedown())); + targets.AddRange(Enemy.GetSpells() + .Where(s => s != null && !s.IsFacedown())); + targets.AddRange(Enemy.GetMonsters() + .OrderByDescending(m => m.Attack)); + + if (targets.Count == 0) + return false; + + AI.SelectCard(costList); + AI.SelectNextCard(targets); + + return true; + } + private bool AlreadySSFromBanishThisTurn(ClientCard c) + { + if (c == null) return false; + if (c.Controller != 0) return false; + + if (c.IsCode(CardId.MalissP_Dormouse)) return ssDormouse; + if (c.IsCode(CardId.MalissP_WhiteRabbit)) return ssWhiteRabbit; + if (c.IsCode(CardId.MalissP_ChessyCat)) return ssChessyCat; + + if (c.IsCode(CardId.MalissQ_RedRansom)) return ssRRThisTurn; + if (c.IsCode(CardId.MalissQ_HeartsCrypter)) return ssHCThisTurn; + if (c.IsCode(CardId.MalissQ_WhiteBinder)) return ssWBThisTurn; + + return false; + } + private bool ShouldSkipBanishing(ClientCard c) + { + if (c == null) return true; + if (c.Controller != 0) return false; + if (AlreadySSFromBanishThisTurn(c)) return true; + if (c.IsCode(CardId.MalissP_MarchHare) && ActiveMarchHare) return true; + return false; + } + private bool DescIs(int cardId, params int[] idx) + { + if (ActivateDescription == -1) return true; + foreach (var i in idx) + if (ActivateDescription == Util.GetStringId(cardId, i)) return true; + return false; + } + + private ClientCard PickMirrorCostCandidate() + { + int[] handPref = { + CardId.MalissP_WhiteRabbit, + CardId.MalissP_ChessyCat, + CardId.MalissP_Dormouse, + CardId.MalissP_MarchHare + }; + foreach (var id in handPref) + { + var h = Bot.Hand.GetFirstMatchingCard(c => c != null && c.IsCode(id)); + if (h != null) return h; + } + + var fieldP = Bot.GetMonsters() + .Where(c => c != null && c.HasSetcode(0x1bf) && !c.HasType(CardType.Link)) + .OrderBy(c => c.Attack).FirstOrDefault(); + if (fieldP != null) return fieldP; + + int[] avoid = { + CardId.MalissQ_HeartsCrypter, CardId.MalissQ_WhiteBinder, CardId.MalissQ_RedRansom + }; + var weakLink = Bot.GetMonsters() + .Where(c => c != null && c.HasSetcode(0x1bf) && c.HasType(CardType.Link) && !avoid.Contains(c.Id)) + .OrderBy(c => c.Attack).FirstOrDefault(); + return weakLink; + } + + private int[] Mirror_SearchOrderForType(bool isTrap, bool isMon) + { + if (isTrap) + return new[] { CardId.MalissC_GWC06, CardId.MalissC_MTP07 }; + if (isMon) + { + if (!Bot.HasInHand(CardId.MalissP_WhiteRabbit) && NSDorMouse) + { + return new[] { CardId.MalissP_WhiteRabbit, CardId.MalissP_MarchHare, CardId.MalissP_Dormouse, CardId.MalissP_ChessyCat }; + } + else + { + return new[] { CardId.MalissP_MarchHare, CardId.MalissP_Dormouse, CardId.MalissP_WhiteRabbit, CardId.MalissP_ChessyCat }; + } + } + return new[] { CardId.MalissP_MarchHare, CardId.MalissP_Dormouse, CardId.MalissP_WhiteRabbit, CardId.MalissP_ChessyCat }; + } + + private ClientCard PickMirrorGYTargetForSearch() + { + if (NSDorMouse && !ssRRThisTurn) + { + var rr = Bot.Graveyard.GetFirstMatchingCard( + c => c != null && c.IsCode(CardId.MalissQ_RedRansom)); + + if (rr != null) + return rr; + } + int[] monPref = { CardId.MalissP_MarchHare, CardId.MalissP_Dormouse, CardId.MalissP_WhiteRabbit, CardId.MalissP_ChessyCat }; + foreach (var id in monPref) + { + var m = Bot.Graveyard.GetFirstMatchingCard(c => c != null && c.IsCode(id)); + if (m != null && CheckRemainInDeck(id) > 0) return m; + } + return null; + } + private int PickMTP07SearchId() + { + if (CheckRemainInDeck(CardId.MalissP_MarchHare) > 0) + return CardId.MalissP_MarchHare; + + int[] pawnPref = { + CardId.MalissP_Dormouse, + CardId.MalissP_WhiteRabbit, + CardId.MalissP_ChessyCat + }; + foreach (var id in pawnPref) + if (CheckRemainInDeck(id) > 0) return id; + + return 0; + } + private void SelectSafeSTZoneAwayFromImperm() + { + var safeCols = Enumerable.Range(0, 5) + .Where(seq => + { + if (Bot.SpellZone[seq] != null) return false; + if (infiniteImpermanenceList.Contains(seq)) return false; + return true; + }) + .ToList(); + + if (safeCols.Count == 0) + { + safeCols = Enumerable.Range(0, 5) + .Where(seq => Bot.SpellZone[seq] == null) + .ToList(); + } + + int mask = 0; + foreach (int seq in safeCols) mask |= (1 << seq); + AI.SelectPlace(mask); + } + private bool T3Allow() + { + if (Duel.Player != 0) return false; + if (myTurnCount < 2) return false; + if (!HaveBackupOrWizardInHand() || !Bot.HasInHand(CardId.MalissP_MarchHare)) return false; + return true; + } + private bool NSBackup() + { + if (Bot.GetMonsterCount() != 0) return false; + if (usedNormalSummon) return false; + if (Bot.HasInHand(CardId.MalissP_Dormouse) || Bot.HasInHand(CardId.MalissP_WhiteRabbit) || Bot.HasInHand(CardId.MalissP_ChessyCat) || + Bot.HasInHand(CardId.MalissInUnderground) || Bot.HasInHand(CardId.TERRAFORMING) || + Bot.HasInHand(CardId.GoldSarcophagus)) return false; + nsBackupplan = true; + return true; + } + private bool NSBackup_L() + { + if (Bot.GetMonsterCount() != 0) return false; + if (usedNormalSummon) return false; + if (Bot.HasInHand(CardId.MalissP_Dormouse) || Bot.HasInHand(CardId.MalissP_WhiteRabbit) || Bot.HasInHand(CardId.MalissP_ChessyCat) || + Bot.HasInHand(CardId.MalissP_MarchHare) || Bot.HasInHand(CardId.MalissInUnderground) || Bot.HasInHand(CardId.TERRAFORMING) || + Bot.HasInHand(CardId.GoldSarcophagus)) return false; + nsLanceaplan = true; + return true; + } + + private bool NSMH() + { + int mhCount = Bot.Hand.GetMatchingCards(c => c != null && c.IsCode(CardId.MalissP_MarchHare)).Count; + if (mhCount <2 ) return false; + if (Bot.GetMonsterCount() != 0) return false; + if (usedNormalSummon) return false; + if (Bot.HasInHand(CardId.MalissP_Dormouse) || Bot.HasInHand(CardId.MalissP_WhiteRabbit) || Bot.HasInHand(CardId.MalissP_ChessyCat) || + Bot.HasInHand(CardId.MalissInUnderground) || Bot.HasInHand(CardId.TERRAFORMING) || + Bot.HasInHand(CardId.GoldSarcophagus)) return false; + return true; + } + private bool LinguribohMHLine() + { + if (!(Bot.HasInHand(CardId.MalissP_MarchHare) && Bot.HasInMonstersZone(CardId.MalissP_MarchHare))) return false; + if (Bot.GetMonsterCount() != 1) return false; + return true; + } + private bool EmerTranscode() + { + if (!enemyActivateLancea) return false; + if (Bot.GetMonsterCount() < 3) return false; + var mats = PickLinkMatsMinCount( + targetLink: 3, + isEligible: m => m.HasType(CardType.Effect), + minCount: 2, + maxCount: 2 + ); + if (mats.Count == 0) + { + return false; + } + + AI.SelectMaterials(mats); + return true; + } + #endregion + + // ======================= END OF LIFE ==================== + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MalissOCGExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MalissOCGExecutor.cs new file mode 100644 index 0000000..73b804e --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MalissOCGExecutor.cs @@ -0,0 +1,1492 @@ +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using System.Linq; +using System; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; + +namespace WindBot.Game.AI.Decks +{ + [Deck("MalissOCG", "AI_MalissOCG")] + public class MalissOCGExecutor : DefaultExecutor + { + public class SetCode + { + public const int Maliss = 0x1bf; + } + public class CardId + { + public const int Artifact_Lancea = 34267821;//古遗物-圣枪 + public const int Dimension_Shifter = 91800273; //大宇宙人 + public const int MaxxG = 23434538; //增殖的G + public const int Mulcharmy_Fuwalos = 42141493; //欢聚友伴·茸茸长尾山雀 + public const int Infinite_Impermanence = 10045474; //无限泡影 + public const int Dominus_Impulse = 40366667; //灵王的波动 + public const int AshBlossom = 14558127; //灰流丽 + public const int CalledbytheGrave = 24224830; //墓穴的指名 + public const int Gold_Sarcophagus = 75500286; //封印之黄金柜 + public const int Wizard_Ignister = 3723262; //男巫@火灵天星 + public const int Backup_Ignister = 30118811; //备份员@火灵天星 + public const int Maliss_Chessy_Cat = 96676583; //码丽丝<兵卒>柴郡猫 + public const int Maliss_White_Rabbit = 69272449; //码丽丝<兵卒>白兔 + public const int Maliss_Dormouse = 32061192; //码丽丝<兵卒>睡鼠 + public const int Maliss_March_Hare = 20938824; //码丽丝<兵卒>三月兔 + public const int Maliss_in_the_Mirror = 93453053; //码丽丝镜中奇像 + public const int Maliss_in_Underground = 68337209; //码丽丝梦游地下界 + public const int Maliss_GWC_06 = 20726052; //码丽丝<代码>GWC-06 + public const int Maliss_TB_11 = 57111661; //码丽丝<代码>TB-11 + public const int Maliss_MTP_07 = 94722358; //码丽丝<代码>MTP-07 + + public const int Mereologic_Aggregator = 9940036; + public const int Cyberse_Desavewurm = 92422871; + public const int Allied_Code_Talker_Ignister = 39138610; //协心代码语者@火灵天星 + public const int Firewall_Dragon = 64211118; //防火龙·暗流体-新电磁泄密风 + public const int Accesscode_Talker = 86066372; //访问码语者 + public const int Maliss_Hearts_Crypter = 21848500; //码丽丝<王后>红心加密 + public const int Maliss_Red_Ransom = 68059897; //码丽丝<王后>红棋勒索 + public const int Maliss_White_Binder = 95454996; //码丽丝<王后>白棋捆绑 + public const int Transcode_Talker = 46947713; //转码语者 + public const int Splash_Mage = 59859086; //飞溅闪屏法师 + public const int Haggard_Lizardose = 9763474; //盛悴之致命毒蜥 + public const int Cyberse_Wicckid = 52698008; //电子界小男巫 + public const int Link_Decoder = 30342076; //连接解码员 + } + + public CardCount Count = new CardCount(); + public MalissOCGExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Repos, MonsterRepos); + AddExecutor(ExecutorType.GoToBattlePhase, GoToBattlePhase); + AddExecutor(ExecutorType.Activate, CardId.Dimension_Shifter, Effect_Enemy_Turn); + AddExecutor(ExecutorType.Activate, CardId.Mulcharmy_Fuwalos, Effect_Enemy_Turn); + AddExecutor(ExecutorType.Activate, CardId.MaxxG, Effect_Enemy_Turn); + AddExecutor(ExecutorType.Activate, CardId.Infinite_Impermanence, Effect_Infinite_Impermanence); + AddExecutor(ExecutorType.Activate, CardId.AshBlossom, DefaultAshBlossomAndJoyousSpring); + AddExecutor(ExecutorType.Activate, CardId.Dominus_Impulse, Effect_Enemy_Chain); + AddExecutor(ExecutorType.Activate, CardId.CalledbytheGrave, DefaultCalledByTheGrave); + AddExecutor(ExecutorType.Activate, CardId.Maliss_White_Rabbit, Effect_White_Rabbit); + AddExecutor(ExecutorType.Activate, CardId.Haggard_Lizardose, Effect_Haggard_Lizardose); + AddExecutor(ExecutorType.Activate, CardId.Splash_Mage); + AddExecutor(ExecutorType.Activate, CardId.Cyberse_Wicckid); + AddExecutor(ExecutorType.Activate, CardId.Cyberse_Desavewurm); + AddExecutor(ExecutorType.Activate, CardId.Transcode_Talker); + AddExecutor(ExecutorType.Activate, CardId.Mereologic_Aggregator, Effect_Mereologic_Aggregator); + AddExecutor(ExecutorType.Activate, CardId.Firewall_Dragon, Effect_Firewall_Dragon); + AddExecutor(ExecutorType.Activate, CardId.Allied_Code_Talker_Ignister, Effect_Allied_Code_Talker_Ignister); + AddExecutor(ExecutorType.Activate, CardId.Maliss_White_Binder, Effect_Maliss_Link); + AddExecutor(ExecutorType.Activate, CardId.Maliss_Red_Ransom, Effect_Maliss_Link); + AddExecutor(ExecutorType.Activate, CardId.Maliss_Hearts_Crypter, Effect_Maliss_Hearts_Crypter); + AddExecutor(ExecutorType.Activate, CardId.Link_Decoder); + + AddExecutor(ExecutorType.Summon, CardId.Maliss_Dormouse, Summon_Maliss_Dormouse); + AddExecutor(ExecutorType.Summon, CardId.Maliss_White_Rabbit, Summon_Maliss_White_Rabbit); + AddExecutor(ExecutorType.Summon, CardId.Maliss_Chessy_Cat, Summon_Maliss_Chessy_Cat); + AddExecutor(ExecutorType.Summon, CardId.Backup_Ignister, Summon_Backup_Ignister); + + AddExecutor(ExecutorType.Activate, CardId.Maliss_Dormouse, Effect_Maliss_Dormouse); + + AddExecutor(ExecutorType.SpSummon, CardId.Maliss_Red_Ransom, SP_Maliss_Link); + AddExecutor(ExecutorType.SpellSet, SpellSet_Maliss); + AddExecutor(ExecutorType.Activate, CardId.Maliss_Chessy_Cat, Effect_Maliss_Chessy_Cat); + + AddExecutor(ExecutorType.SpSummon, CardId.Splash_Mage, SP_Splash_Mage); + AddExecutor(ExecutorType.SpSummon, CardId.Haggard_Lizardose, SP_Haggard_Lizardose); + AddExecutor(ExecutorType.SpSummon, CardId.Link_Decoder, SP_Link_Decoder); + + AddExecutor(ExecutorType.SpSummon, CardId.Cyberse_Wicckid, SP_Cyberse_Wicckid); + + AddExecutor(ExecutorType.Activate, CardId.Maliss_in_Underground, Effect_Remove); + AddExecutor(ExecutorType.Activate, CardId.Gold_Sarcophagus, Effect_Remove); + + AddExecutor(ExecutorType.Activate, CardId.Maliss_TB_11, Effect_Maliss_TB_11); + AddExecutor(ExecutorType.Activate, CardId.Maliss_MTP_07, Effect_Maliss_MTP_07); + + AddExecutor(ExecutorType.Activate, CardId.Maliss_March_Hare, Effect_Maliss_March_Hare); + AddExecutor(ExecutorType.Activate, CardId.Backup_Ignister); + AddExecutor(ExecutorType.Activate, CardId.Wizard_Ignister, Effect_Wizard_Ignister); + + AddExecutor(ExecutorType.Activate, CardId.Maliss_in_the_Mirror, Effect_Maliss_in_the_Mirror); + + AddExecutor(ExecutorType.SpSummon, CardId.Maliss_Hearts_Crypter, SP_Maliss_Hearts_Crypter); + AddExecutor(ExecutorType.SpSummon, CardId.Maliss_White_Binder, SP_Maliss_White_Binder); + AddExecutor(ExecutorType.Activate, CardId.Maliss_GWC_06, Effect_Maliss_GWC_06); + AddExecutor(ExecutorType.SpSummon, CardId.Firewall_Dragon, SP_Firewall_Dragon); + AddExecutor(ExecutorType.SpSummon, CardId.Allied_Code_Talker_Ignister, SP_Allied_Code_Talker_Ignister); + AddExecutor(ExecutorType.SpellSet, CardId.Maliss_in_the_Mirror); + AddExecutor(ExecutorType.SpSummon, CardId.Transcode_Talker, SP_Transcode_Talker); + AddExecutor(ExecutorType.SpellSet, SpellSet); + } + + public class CardCount + { + public int Dimension_Shifter = 0; + public int Summon = 0; + public int Phase = 0; + public List Activate = new List(); + public List ActivateRemoved = new List(); + public List Position = new List(); + public List Set = new List(); + public List Oppo = new List(); + public void Clear() + { + Activate.Clear(); + ActivateRemoved.Clear(); + Position.Clear(); + Set.Clear(); + Oppo.Clear(); + if (Dimension_Shifter > 0) + Dimension_Shifter --; + if (Summon > 0) + Summon --; + } + public void AddActivateOppo(int id) + { + Oppo.Add(id); + } + public bool CheckActivateOppo(int id) + { + return !Oppo.Contains(id); + } + public void AddSummon() + { + Summon = 1; + } + public void AddCard(int id) + { + if (id == CardId.Dimension_Shifter) + Dimension_Shifter = 2; + else + Activate.Add(id); + } + public void AddSet(int id) + { + Set.Add(id); + } + public bool CheckSet(int id) + { + return !Set.Contains(id); + } + public void AddCardRemoved(int id) + { + ActivateRemoved.Add(id); + } + public void AddPosition(int id) + { + Position.Add(id); + } + public void AddPhase() + { + Phase ++; + } + public bool CheckCard(int id) + { + if (id == CardId.Dimension_Shifter) + return Dimension_Shifter == 0; + else + return !Activate.Contains(id); + } + public bool CheckCardRemoved(int id) + { + return !ActivateRemoved.Contains(id); + } + public bool CheckPosition(int id) + { + return !Position.Contains(id); + } + public int CheckPhase() + { + return Phase; + } + public bool CheckSummon() + { + return Summon == 0; + } + } + + private struct ZoneData + { + public int Zone; + public ClientCard[] CheckZone; + } + + public override void OnNewTurn() + { + Count.AddPhase(); + Count.Clear(); + base.OnNewTurn(); + } + public override void OnChaining(int player, ClientCard card) + { + if (card.Id == CardId.Dimension_Shifter || card.Id == CardId.Artifact_Lancea) + Count.AddCard(card.Id); + else if (player == 0) + if (card.Location == CardLocation.Removed) + Count.AddCardRemoved(card.Id); + else + Count.AddCard(card.Id); + if (player == 1) + Count.AddActivateOppo(card.Id); + } + public override void OnChainEnd() + { + if (DefaultCheckWhetherCardIdIsNegated(CardId.Dimension_Shifter) && !Count.CheckCard(Card.Id)) + Count.Dimension_Shifter = 0; + Count.Oppo.Clear(); + } + public override bool OnSelectYesNo(int desc) + { + if (desc == Util.GetStringId(CardId.Maliss_White_Binder, 3)) + return true; + if (desc == Util.GetStringId(CardId.Maliss_MTP_07, 3)) + return Enemy.GetMonsters().Count(i => !i.IsShouldNotBeTarget()) + Enemy.GetSpells().Count(i => !i.IsShouldNotBeTarget() && (i.HasType(CardType.Field | CardType.Continuous | CardType.Equip) || i.IsFacedown())) > 0; + return base.OnSelectYesNo(desc); + } + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location == CardLocation.MonsterZone) + { + // [YGOL] TICKET-349 + + if (new List{CardId.Cyberse_Wicckid, CardId.Allied_Code_Talker_Ignister}.Contains(cardId)) + { + if ((Zones.z6 & available) > 0 && (Bot.MonsterZone[3] == null || Bot.MonsterZone[4] == null)) return Zones.z6; + if ((Zones.z5 & available) > 0 && (Bot.MonsterZone[0] == null || Bot.MonsterZone[1] == null)) return Zones.z5; + } + if (Bot.HasInMonstersZone(CardId.Cyberse_Wicckid) && Count.CheckCard(CardId.Cyberse_Wicckid)) + { + int seq = 0; + for (int i = 0; i < 7; ++i) + if (Bot.MonsterZone[i] != null && Bot.MonsterZone[i].IsCode(CardId.Cyberse_Wicckid)) seq = i; + if (seq == 5) + { + if ((Zones.z1 & available) > 0) return Zones.z1; + if ((Zones.z2 & available) > 0) return Zones.z2; + } + else if (seq == 6) + { + if ((Zones.z3 & available) > 0) return Zones.z3; + if ((Zones.z4 & available) > 0) return Zones.z4; + } + } + if (cardId == CardId.Transcode_Talker) + { + if ((Zones.z6 & available) > 0 && Bot.MonsterZone[3] == null) return Zones.z6; + if ((Zones.z5 & available) > 0 && Bot.MonsterZone[1] == null) return Zones.z5; + if ((Zones.z0 & available) > 0 && Bot.MonsterZone[1] == null) return Zones.z0; + if ((Zones.z1 & available) > 0 && Bot.MonsterZone[2] == null) return Zones.z1; + if ((Zones.z2 & available) > 0 && Bot.MonsterZone[3] == null) return Zones.z2; + if ((Zones.z3 & available) > 0 && Bot.MonsterZone[4] == null) return Zones.z3; + } + if (cardId == CardId.Allied_Code_Talker_Ignister) + { + ZoneData[] zoneData = new ZoneData[] { + new ZoneData { Zone = Zones.z0, CheckZone = new ClientCard[] { Bot.MonsterZone[1] } }, + new ZoneData { Zone = Zones.z1, CheckZone = new ClientCard[] { Bot.MonsterZone[0], Bot.MonsterZone[2] } }, + new ZoneData { Zone = Zones.z2, CheckZone = new ClientCard[] { Bot.MonsterZone[1], Bot.MonsterZone[3] } }, + new ZoneData { Zone = Zones.z3, CheckZone = new ClientCard[] { Bot.MonsterZone[2], Bot.MonsterZone[4] } }, + new ZoneData { Zone = Zones.z4, CheckZone = new ClientCard[] { Bot.MonsterZone[3] } }, + new ZoneData { Zone = Zones.z5, CheckZone = new ClientCard[] { Bot.MonsterZone[0], Bot.MonsterZone[1], Bot.MonsterZone[2] } }, + new ZoneData { Zone = Zones.z6, CheckZone = new ClientCard[] { Bot.MonsterZone[2], Bot.MonsterZone[3], Bot.MonsterZone[4] } } + }; + + int maxNullCount = -1; + int selectedZone = 0; + + foreach (ZoneData data in zoneData) + { + if ((data.Zone & available) == 0) + continue; + + int nullCount = data.CheckZone.Count(card => card == null); + if (nullCount > maxNullCount) + { + maxNullCount = nullCount; + selectedZone = data.Zone; + } + } + + if (maxNullCount >= 0) + { + return selectedZone; + } + } + if ((Zones.z6 & available) > 0) return Zones.z6; + if ((Zones.z5 & available) > 0) return Zones.z5; + } + return base.OnSelectPlace(cardId, player, location, available); + } + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (AI.HaveSelectedCards()) return null; + ClientCard card = Duel.GetCurrentSolvingChainCard(); + if (card == null) + card = Card; + switch (card.Id) + { + case CardId.Maliss_White_Rabbit: + if (cards.Any(i => i.Id == CardId.Maliss_TB_11) && Count.CheckCard(CardId.Maliss_TB_11)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_TB_11).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_GWC_06) && Count.CheckCard(CardId.Maliss_GWC_06)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_GWC_06).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_MTP_07) && Count.CheckCard(CardId.Maliss_MTP_07)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_MTP_07).ToList(), cards, min, max); + break; + case CardId.Maliss_in_Underground: + if (Count.CheckSummon()) + { + if (cards.Any(i => i.Id == CardId.Maliss_Dormouse && i.Location == CardLocation.Deck) + && !Bot.HasInHand(CardId.Maliss_Dormouse) + && Check_Maliss_Dormouse() + && Count.CheckCardRemoved(CardId.Maliss_Dormouse)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Dormouse && i.Location == CardLocation.Deck).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit && i.Location == CardLocation.Deck) + && !Bot.HasInHand(CardId.Maliss_White_Rabbit) + && Check_Maliss_White_Rabbit() + && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit && i.Location == CardLocation.Deck).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_March_Hare && i.Location == CardLocation.Deck) && Check_Maliss_March_Hare(CardLocation.Removed) && Count.CheckCard(CardId.Maliss_March_Hare)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat && i.Location == CardLocation.Deck) + && !Bot.HasInHand(CardId.Maliss_Chessy_Cat) + && Count.CheckCardRemoved(CardId.Maliss_Chessy_Cat)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat && i.Location == CardLocation.Deck).ToList(), cards, min, max); + } + else + { + if (cards.Any(i => i.Id == CardId.Maliss_Dormouse && i.Location == CardLocation.Deck) + && Count.CheckCardRemoved(CardId.Maliss_Dormouse) && Check_Maliss_Dormouse()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Dormouse).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit && i.Location == CardLocation.Deck) + && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit) && Check_Maliss_White_Rabbit()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_March_Hare && i.Location == CardLocation.Deck) && Check_Maliss_March_Hare(CardLocation.Removed) && Count.CheckCard(CardId.Maliss_March_Hare)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat && i.Location == CardLocation.Deck) + && Count.CheckCardRemoved(CardId.Maliss_Chessy_Cat)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + + } + return Util.CheckSelectCount(cards.Where(i => i.Location == CardLocation.Deck).ToList(), cards, min, max); + case CardId.Gold_Sarcophagus: + if (Count.CheckSummon()) + { + if (cards.Any(i => i.Id == CardId.Maliss_Dormouse) + && !Bot.HasInHand(CardId.Maliss_Dormouse) + && Check_Maliss_Dormouse() + && Count.CheckCardRemoved(CardId.Maliss_Dormouse)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Dormouse).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit) + && !Bot.HasInHand(CardId.Maliss_White_Rabbit) + && Check_Maliss_White_Rabbit() + && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat) + && !Bot.HasInHand(CardId.Maliss_Chessy_Cat) + && Check_Maliss_Chessy_Cat() + && Count.CheckCardRemoved(CardId.Maliss_Chessy_Cat)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_March_Hare) + && Check_Maliss_March_Hare(CardLocation.Removed)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + } + else + { + if (cards.Any(i => i.Id == CardId.Maliss_Dormouse) + && Count.CheckCardRemoved(CardId.Maliss_Dormouse) && Check_Maliss_Dormouse()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Dormouse).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit) + && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit) && Check_Maliss_White_Rabbit()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat) + && Count.CheckCardRemoved(CardId.Maliss_Chessy_Cat) && Check_Maliss_Chessy_Cat()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_March_Hare) && Check_Maliss_March_Hare(CardLocation.Removed)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + } + break; + case CardId.Maliss_Dormouse: + if (Count.CheckSummon()) + { + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit) + && !Bot.HasInHand(CardId.Maliss_White_Rabbit) + && Check_Maliss_White_Rabbit() + && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat) + && !Bot.HasInHand(CardId.Maliss_Chessy_Cat) + && Check_Maliss_Chessy_Cat() + && Count.CheckCardRemoved(CardId.Maliss_Chessy_Cat)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_March_Hare) && Check_Maliss_March_Hare(CardLocation.Removed)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + } + else + { + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit) + && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit) && Check_Maliss_White_Rabbit()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat) + && Count.CheckCardRemoved(CardId.Maliss_Chessy_Cat) && Check_Maliss_Chessy_Cat()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_March_Hare) && Check_Maliss_March_Hare(CardLocation.Removed)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + } + break; + case CardId.Maliss_TB_11: + if (hint == HintMsg.SpSummon) + { + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + { + if (cards.Any(i => i.Id == CardId.Maliss_Dormouse) && Count.CheckCardRemoved(CardId.Maliss_Dormouse)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Dormouse).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit) && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_March_Hare) && Count.CheckCardRemoved(CardId.Maliss_March_Hare)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss)).ToList(), cards, min, max); + } + if (cards.Any(i => i.Id == CardId.Maliss_Dormouse) && Count.CheckCard(CardId.Maliss_Dormouse)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Dormouse).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit) && Count.CheckCard(CardId.Maliss_White_Rabbit)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat) && Count.CheckCard(CardId.Maliss_Chessy_Cat)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + } + else if (hint == HintMsg.Remove) + { + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Link))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id) && i.HasType(CardType.Link)).ToList(), cards, min, max); + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + } + break; + case CardId.Maliss_MTP_07: + if (hint == HintMsg.AddToHand) + { + if (Duel.Player == 1 && cards.Any(i => i.Id == CardId.Maliss_March_Hare) && Count.CheckCard(CardId.Maliss_March_Hare) && Check_Maliss_March_Hare(CardLocation.Hand)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Dormouse) && Count.CheckCard(CardId.Maliss_Dormouse)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Dormouse).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit) && Count.CheckCard(CardId.Maliss_White_Rabbit)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat) && Count.CheckCard(CardId.Maliss_Chessy_Cat)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + } + else if (hint == HintMsg.Remove) + { + if (cards.Any(i => i.Controller == 1)) + return Util.CheckSelectCount(cards.Where(i => i.Controller == 1).ToList(), cards, min, max); + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Link))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id) && i.HasType(CardType.Link)).ToList(), cards, min, max); + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + } + break; + case CardId.Splash_Mage: + case CardId.Haggard_Lizardose: + case CardId.Cyberse_Wicckid: + if (hint == HintMsg.Remove) + { + if (cards.Any(i => Count.CheckCard(i.Id) && Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss) && i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCard(i.Id) && Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss) && i.Location == CardLocation.Grave).ToList(), cards, min, max); + if (cards.Any(i => i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => i.Location == CardLocation.Grave).ToList(), cards, min, max); + } + else if (hint == HintMsg.SpSummon) + { + if (cards.Any(i => i.HasSetcode(SetCode.Maliss))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss)).ToList(), cards, min, max); + } + else if (hint == HintMsg.Target) + { + if (cards.Any(i => i.IsCode(CardId.Haggard_Lizardose))) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Haggard_Lizardose)).ToList(), cards, min, max); + } + break; + case CardId.Maliss_Red_Ransom: + if (hint == HintMsg.AddToHand) + { + List chk_cards = Bot.Graveyard.ToList(); + chk_cards.AddRange(Bot.GetSpells()); + chk_cards.AddRange(Bot.Hand); + if (cards.Any(i => i.IsCode(CardId.Maliss_in_the_Mirror)) + && Check_Maliss_in_the_Mirror(CardLocation.Removed) + && chk_cards.Any(i => i.HasType(CardType.Trap)) + && (((Bot.HasInHand(CardId.Maliss_Chessy_Cat) && Count.CheckSummon()) || Bot.HasInMonstersZone(CardId.Maliss_Chessy_Cat)) && Count.CheckCard(CardId.Maliss_Chessy_Cat) + || Bot.HasInHand(CardId.Maliss_March_Hare) && Count.CheckCard(CardId.Maliss_March_Hare) + ) && Count.CheckCard(CardId.Maliss_in_the_Mirror) + ) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_in_the_Mirror)).ToList(), cards, min, max); + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_in_the_Mirror)).ToList(), cards, min, max); + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_in_Underground)).ToList(), cards, min, max); + } + else if (hint == HintMsg.Remove) + { + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + { + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat) && Count.CheckCardRemoved(CardId.Maliss_Chessy_Cat)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + if (cards.Any(i => !i.IsCode(CardId.Maliss_Chessy_Cat) && Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss))) + return Util.CheckSelectCount(cards.Where(i => !i.IsCode(CardId.Maliss_Chessy_Cat) && Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss)).ToList(), cards, min, max); + } + if (cards.Any(i => i.Id == CardId.Maliss_March_Hare) && Check_Maliss_March_Hare(CardLocation.Removed)) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_March_Hare).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Dormouse) + && Count.CheckCardRemoved(CardId.Maliss_Dormouse) && Check_Maliss_Dormouse()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Dormouse).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_White_Rabbit) + && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit) && Check_Maliss_White_Rabbit()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_White_Rabbit).ToList(), cards, min, max); + if (cards.Any(i => i.Id == CardId.Maliss_Chessy_Cat) + && Count.CheckCardRemoved(CardId.Maliss_Chessy_Cat) && Check_Maliss_Chessy_Cat()) + return Util.CheckSelectCount(cards.Where(i => i.Id == CardId.Maliss_Chessy_Cat).ToList(), cards, min, max); + } + break; + case CardId.Maliss_Chessy_Cat: + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + { + if (cards.Any(i => i.IsCode(CardId.Maliss_March_Hare)) && !Bot.Graveyard.Any(i => i.HasSetcode(SetCode.Maliss)) && !Bot.Hand.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id) && !i.IsCode(CardId.Maliss_March_Hare))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && !i.IsCode(CardId.Maliss_March_Hare))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + } + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && i.IsCode(CardId.Maliss_in_the_Mirror)) && Check_Maliss_in_the_Mirror(CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id) && i.IsCode(CardId.Maliss_in_the_Mirror)).ToList(), cards, min, max); + if (cards.Any(i => Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + break; + case CardId.Maliss_White_Binder: + if (hint == HintMsg.Remove) + { + List result = new List(); + int ct = 5 - Bot.GetMonstersInMainZone().Count; + if (ct > 0 && Count.CheckCard(CardId.Allied_Code_Talker_Ignister)) + { + result.AddRange(cards.Where(i => i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id) && i.Controller == 0 && i.HasType(CardType.Link))); + if (Duel.Player == 1) + result.AddRange(cards.Where(i => i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id) && i.Controller == 0 && i.IsCode(CardId.Maliss_White_Rabbit))); + result.AddRange(cards.Where(i => i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id) && i.Controller == 0 && i.HasType(CardType.Monster))); + result.AddRange(cards.Where(i => i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id) && i.Controller == 0 && i.HasType(CardType.Spell))); + } + result.AddRange(cards.Where(i => i.Controller == 1)); + result.AddRange(cards.Where(i => TrashCards(i.Id, CardLocation.Grave))); + result.AddRange(cards.Where(i => !i.HasSetcode(SetCode.Maliss) && !i.HasType(CardType.Trap))); + result.AddRange(cards.Where(i => !i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Trap))); + if (result.Count() > max) + result = result.Take(max).ToList(); + if (result.Count() > 0) + return Util.CheckSelectCount(result, cards, result.Count(), result.Count()); + if (cards.Any(i => TrashCards(i.Id, CardLocation.Grave))) + return Util.CheckSelectCount(cards.Where(i => TrashCards(i.Id, CardLocation.Grave)).ToList(), cards, min, min); + + return Util.CheckSelectCount(cards, cards, min, min); + } + else if (hint == HintMsg.Set) + { + if (cards.Any(i => i.IsCode(CardId.Maliss_GWC_06))) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_GWC_06)).ToList(), cards, min, max); + } + break; + case CardId.Maliss_March_Hare: + if (hint == HintMsg.AddToHand) + { + if (cards.Any(i => Count.CheckCard(i.Id) && i.IsCode(CardId.Maliss_March_Hare))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCard(i.Id) && i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (cards.Any(i => Count.CheckCard(i.Id) && !i.HasType(CardType.Link))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCard(i.Id) && !i.HasType(CardType.Link)).ToList(), cards, min, max); + if (cards.Any(i => !i.HasType(CardType.Link))) + return Util.CheckSelectCount(cards.Where(i => !i.HasType(CardType.Link)).ToList(), cards, min, max); + } + else if (hint == HintMsg.Remove) + { + if (Duel.Player == 1) + { + if (Bot.GetMonstersInMainZone().Count() > 3) + { + if (cards.Any(i => i.HasType(CardType.Spell) && i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => i.HasType(CardType.Spell) && i.Location == CardLocation.Grave).ToList(), cards, min, max); + if (cards.Any(i => !i.HasType(CardType.Link) && i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => !i.HasType(CardType.Link) && i.Location == CardLocation.Grave).ToList(), cards, min, max); + } + else + { + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && i.HasType(CardType.Link) && i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id) && i.HasType(CardType.Link) && i.Location == CardLocation.Grave).ToList(), cards, min, max); + } + } + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && !i.HasType(CardType.Trap) && i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id) && !i.HasType(CardType.Trap) && i.Location == CardLocation.Grave).ToList(), cards, min, max); + if (cards.Any(i => !i.HasType(CardType.Trap) && i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => !i.HasType(CardType.Trap) && i.Location == CardLocation.Grave).ToList(), cards, min, max); + if (cards.Any(i => Count.CheckCardRemoved(i.Id) && !i.HasType(CardType.Trap))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id) && !i.HasType(CardType.Trap)).ToList(), cards, min, max); + } + break; + case CardId.Maliss_in_the_Mirror: + if (hint == HintMsg.Remove) + { + if (!cards.Any(i => i.Location != CardLocation.Grave)) + { + if (cards.Any(i => i.HasType(CardType.Trap)) && !Bot.HasInHandOrInSpellZoneOrInGraveyard(CardId.Maliss_GWC_06) && !Bot.HasInBanished(CardId.Maliss_GWC_06)) + return Util.CheckSelectCount(cards.Where(i => i.HasType(CardType.Trap)).ToList(), cards, min, max); + } + else + { + if (cards.Any(i => i.IsCode(CardId.Maliss_Red_Ransom)) && Count.CheckCardRemoved(CardId.Maliss_Red_Ransom)) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_Red_Ransom)).ToList(), cards, min, max); + if (cards.Any(i => i.HasType(CardType.Link) && i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.HasType(CardType.Link) && i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + } + } + else if (hint == HintMsg.AddToHand) + { + if (cards.Any(i => i.IsCode(CardId.Maliss_GWC_06))) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_GWC_06)).ToList(), cards, min, max); + } + else if (hint == HintMsg.Disable) + { + if (cards.Contains(Util.GetLastChainCard())) + return Util.CheckSelectCount(new List() { Util.GetLastChainCard() }, cards, min, max); + } + break; + case CardId.Maliss_GWC_06: + if (hint == HintMsg.Remove) + { + if (cards.Any(i => Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + } + else if (hint == HintMsg.SpSummon) + { + if (cards.Any(i => i.IsCode(CardId.Maliss_White_Binder) && i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_White_Binder) && i.Location == CardLocation.Grave).ToList(), cards, min, max); + if (cards.Any(i => i.HasType(CardType.Link) && !Count.CheckCardRemoved(i.Id) && i.Location == CardLocation.Grave)) + return Util.CheckSelectCount(cards.Where(i => i.HasType(CardType.Link) && !Count.CheckCardRemoved(i.Id) && i.Location == CardLocation.Grave).ToList(), cards, min, max); + } + break; + case CardId.Mereologic_Aggregator: + if (cards.Any(i => i.Controller == 1 && Count.CheckActivateOppo(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.Controller == 1 && Count.CheckActivateOppo(i.Id)).ToList(), cards, min, max); + return Util.CheckSelectCount(cards.Where(i => i.Controller == 1).ToList(), cards, min, max); + case CardId.Firewall_Dragon: + if (Enemy.GetMonsters().Count(i => !i.IsShouldNotBeTarget() && i.IsFaceup()) + Enemy.GetSpells().Count(i => !i.IsShouldNotBeTarget() && i.HasType(CardType.Field | CardType.Continuous | CardType.Equip)) > 0 + && Duel.Player == 1 && cards.Any(i => i.IsCode(CardId.Mereologic_Aggregator)) + ) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Mereologic_Aggregator)).ToList(), cards, min, max); + if (cards.Any(i => i.IsCode(CardId.Cyberse_Desavewurm))) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Cyberse_Desavewurm)).ToList(), cards, min, max); + return Util.CheckSelectCount(cards.Where(i => i.Location == CardLocation.Deck).ToList(), cards, min, max); + case CardId.Allied_Code_Talker_Ignister: + if (hint == HintMsg.SpSummon) + { + if (cards.Any(i => !i.IsCode(CardId.Maliss_White_Binder))) + return Util.CheckSelectCount(cards.Where(i => !i.IsCode(CardId.Maliss_White_Binder)).ToList(), cards, max, max); + return base.OnSelectCard(cards, max, max, hint, false); + } + else if (hint == HintMsg.Release) + { + if (cards.Any(i => i.LinkCount < 4)) + return Util.CheckSelectCount(cards.Where(i => i.LinkCount < 4).ToList(), cards, max, max); + } + break; + case CardId.Backup_Ignister: + if (hint == HintMsg.AddToHand) + { + if (card.Id == CardId.Dimension_Shifter || card.Id == CardId.Artifact_Lancea) + { + if (!Bot.Hand.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)) + && cards.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)) + ) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (!Bot.Hand.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)) + && cards.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)) + ) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + } + if (cards.Any(i => i.IsCode(CardId.Wizard_Ignister)) && Bot.Hand.Count() > 0 + && (Bot.Graveyard.Any(i => i.HasRace(CardRace.Cyberse)) + || (Bot.HasInExtra(CardId.Link_Decoder) && Bot.GetMonsters().Any(i => i.Level <= 4 && i.HasRace(CardRace.Cyberse)) && Count.CheckCard(CardId.Dimension_Shifter)) + || (Bot.HasInExtra(CardId.Haggard_Lizardose) + && !Count.CheckCard(CardId.Dimension_Shifter) + && Count.CheckCard(CardId.Artifact_Lancea) + && Bot.GetMonsters() + .Where(i => i.IsFaceup() && (!i.HasType(CardType.Link) || i.LinkCount < 2)).ToList() + .GroupBy(i => i.Id) + .Select(i => i.First()) + .Count() >= 2) + ) + ) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Wizard_Ignister)).ToList(), cards, min, max); + if (Bot.HasInHand(CardId.Maliss_March_Hare)) + { + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare) && Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare) && Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + } + else + if (cards.Any(i => i.IsCode(CardId.Maliss_March_Hare))) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss)).ToList(), cards, min, max); + } + else if (hint == HintMsg.Discard) + { + if (card.Id == CardId.Dimension_Shifter || card.Id == CardId.Artifact_Lancea) + { + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id) && !i.IsCode(CardId.Maliss_March_Hare))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && !i.IsCode(CardId.Maliss_March_Hare))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && !i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + } + if (Bot.HasInHand(CardId.Maliss_March_Hare) && !Bot.Graveyard.Any(i => i.HasSetcode(SetCode.Maliss))) + { + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare) && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare) && Count.CheckCardRemoved(i.Id))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare) && Count.CheckCardRemoved(i.Id)).ToList(), cards, min, max); + if (cards.Any(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss) && !i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + if (cards.Count(i => i.IsCode(CardId.Maliss_March_Hare)) > 1) + return Util.CheckSelectCount(cards.Where(i => i.IsCode(CardId.Maliss_March_Hare)).ToList(), cards, min, max); + } + if (cards.Any(i => TrashCards(i.Id, CardLocation.Hand))) + return Util.CheckSelectCount(cards.Where(i => TrashCards(i.Id, CardLocation.Hand)).ToList(), cards, min, max); + if (cards.Any(i => !i.HasType(CardType.Monster))) + return Util.CheckSelectCount(cards.Where(i => !i.HasType(CardType.Monster)).ToList(), cards, min, max); + if (cards.Any(i => !i.HasRace(CardRace.Cyberse))) + return Util.CheckSelectCount(cards.Where(i => !i.HasRace(CardRace.Cyberse)).ToList(), cards, min, max); + } + break; + case CardId.Wizard_Ignister: + if (cards.Any(i => i.HasSetcode(SetCode.Maliss))) + return Util.CheckSelectCount(cards.Where(i => i.HasSetcode(SetCode.Maliss)).ToList(), cards, min, max); + break; + case CardId.Maliss_Hearts_Crypter: + if (hint == HintMsg.Remove && cards.Any(i => i.Controller == 1)) + return Util.CheckSelectCount(cards.Where(i => i.Controller == 1).ToList(), cards, min, max); + break; + } + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + private bool TrashCards(int code, CardLocation loc) + { + if (loc == CardLocation.Grave) + { + List list = new List{ + CardId.MaxxG, + CardId.Artifact_Lancea, + CardId.Dimension_Shifter, + CardId.Mulcharmy_Fuwalos, + CardId.Infinite_Impermanence, + CardId.Dominus_Impulse, + CardId.AshBlossom, + CardId.CalledbytheGrave, + CardId.Gold_Sarcophagus, + + }; + return list.Contains(code); + } + else if (loc == CardLocation.Hand) + { + if (Bot.GetFieldCount() > 0 && code == CardId.Mulcharmy_Fuwalos) + return true; + if (Bot.Graveyard.Count > 0 && code == CardId.Dimension_Shifter) + return true; + } + return false; + } + private bool MonsterRepos() + { + if (!Enemy.GetMonsters().Any(i => i.IsDefense()) + && Util.GetTotalAttackingMonsterAttack(0) + Card.Attack >= Enemy.LifePoints + Util.GetTotalAttackingMonsterAttack(1) + && Card.IsDefense() + ) + return true; + return Card.IsFacedown(); + } + private bool SpellSet() + { + return Card.HasType(CardType.Trap | CardType.QuickPlay); + } + private bool SpellSet_Maliss() + { + return Card.HasType(CardType.Trap) && Card.HasSetcode(SetCode.Maliss) && Bot.GetMonsters().Any(i => i.HasSetcode(SetCode.Maliss)); + } + private bool Effect_Enemy_Turn() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Id == CardId.Dimension_Shifter) + { + if (Duel.Player == 1 && Count.CheckCard(Card.Id)) + { + Count.AddCard(Card.Id); + return true; + } + } + return Duel.Player == 1; + } + private bool Effect_Enemy_Chain() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + ClientCard LastChainCard = Util.GetLastChainCard(); + return LastChainCard != null && LastChainCard.Controller == 1; + } + private bool Effect_Infinite_Impermanence() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + + ClientCard LastChainCard = Util.GetLastChainCard(); + + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (Count.CheckPosition(this_seq)) return false; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || Util.IsChainTarget(Card) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + Count.AddPosition(this_seq); + return true; + } + } + else + { + if (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.MonsterZone) + { + AI.SelectCard(LastChainCard); + return true; + } + } + return false; + } + private bool Effect_Maliss_Removed(int lp = 300) + { + int ct = 5 - Bot.GetMonstersInMainZone().Count; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.HasType(CardType.Monster) && !Card.IsCode(CardId.Maliss_March_Hare) + && ct - Duel.CurrentChain.Count(i => i.HasSetcode(SetCode.Maliss) + && i.Location == CardLocation.Removed + && i.HasType(CardType.Monster) + ) <= 0 + ) return false; + if (Bot.LifePoints > lp && Card.Location == CardLocation.Removed) + { + Count.AddCardRemoved(Card.Id); + return true; + } + return false; + } + private bool Effect_Maliss_Chessy_Cat() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (ActivateDescription == Util.GetStringId(CardId.Maliss_Chessy_Cat, 0)) + { + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + { + if (Bot.Hand.Any(i => i.HasSetcode(SetCode.Maliss) + && Count.CheckCardRemoved(i.Id) + && !i.HasType(CardType.Trap) + && (!i.IsCode(CardId.Maliss_in_the_Mirror) || Check_Maliss_in_the_Mirror(CardLocation.Removed)) + )) + { + Count.AddCard(Card.Id); + return true; + } + if (Bot.HasInHand(CardId.Maliss_March_Hare) && !Bot.Graveyard.Any(i => i.HasSetcode(SetCode.Maliss))) + { + Count.AddCard(Card.Id); + return true; + } + return false; + } + + if (Bot.Hand.Any(i => i.HasSetcode(SetCode.Maliss) + && Count.CheckCardRemoved(i.Id) + && !i.HasType(CardType.Trap) + )) + { + Count.AddCard(Card.Id); + return true; + } + return false; + } + else + return Effect_Maliss_Removed(); + } + private bool Effect_Maliss_March_Hare() + { + if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.Allied_Code_Talker_Ignister)) return false; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Location == CardLocation.Hand) + { + if (Duel.Player == 1 + && (!Bot.Graveyard.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Link)) + || Bot.GetMonstersInMainZone().Count() > 3) + ) + return false; + if (Bot.HasInMonstersZone(CardId.Maliss_Chessy_Cat) && Count.CheckCard(CardId.Maliss_Chessy_Cat)) + return false; + if (Check_Maliss_March_Hare(CardLocation.Hand)) + { + Count.AddCard(Card.Id); + return true; + } + return false; + } + else + return Effect_Maliss_Removed(); + } + private bool Effect_Maliss_Dormouse() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Location == CardLocation.MonsterZone) + { + Count.AddCard(Card.Id); + return true; + } + else + return Effect_Maliss_Removed(); + } + private bool Summon_Maliss_Chessy_Cat() + { + if (Check_Maliss_Chessy_Cat()) + { + Count.AddSummon(); + return true; + } + return false; + } + private bool Effect_White_Rabbit() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Location == CardLocation.MonsterZone) + { + Count.AddCard(Card.Id); + return true; + } + else + return Effect_Maliss_Removed(); + } + private bool Summon_Maliss_Dormouse() + { + if (Check_Maliss_Dormouse()) + { + Count.AddSummon(); + return true; + } + return false; + } + private bool Summon_Maliss_White_Rabbit() + { + if (Check_Maliss_White_Rabbit()) + { + Count.AddSummon(); + return true; + } + return false; + } + private bool Check_Maliss_in_the_Mirror(CardLocation loc) + { + if (loc == CardLocation.Removed) + { + if (!Count.CheckCard(CardId.Artifact_Lancea) || !Count.CheckCardRemoved(CardId.Maliss_March_Hare)) + return false; + List cards = Bot.Hand.ToList(); + cards.AddRange(Bot.GetMonsters()); + cards.AddRange(Bot.GetSpells()); + cards.AddRange(Bot.Graveyard); + cards.AddRange(Bot.Banished); + return Bot.Graveyard.Any(i => i.HasSetcode(SetCode.Maliss) + && ( + (i.HasType(CardType.Monster) && cards.Count(j => j.HasType(CardType.Monster)) < 10) + || (i.HasType(CardType.Spell) && cards.Count(j => j.HasType(CardType.Spell)) < 4) + || (i.HasType(CardType.Trap) && cards.Count(j => j.HasType(CardType.Trap)) < 3) + ) + ); + } + else + { + List cards = Bot.Hand.GetMonsters(); + cards.AddRange(Bot.GetMonsters()); + return cards.Any(i => Count.CheckCardRemoved(i.Id)); + } + } + private bool Check_Maliss_Chessy_Cat() + { + return Bot.Hand.Any(i => i.HasSetcode(SetCode.Maliss) + && !i.HasType(CardType.Trap) + && i != Card && Count.CheckCardRemoved(i.Id) + ) && Count.CheckCard(CardId.Maliss_Chessy_Cat); + } + private bool Check_Maliss_White_Rabbit() + { + return Bot.Graveyard.Count(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Trap)) < 3 + && Count.CheckCard(CardId.Maliss_White_Rabbit); + } + private bool Check_Maliss_Dormouse() + { + List cards = Bot.Hand.ToList(); + cards.AddRange(Bot.GetMonsters()); + cards.AddRange(Bot.GetSpells()); + cards.AddRange(Bot.Graveyard); + cards.AddRange(Bot.Banished); + return cards.Count(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster)) < 9 + && Count.CheckCard(CardId.Maliss_Dormouse); + } + private bool Check_Maliss_March_Hare(CardLocation loc) + { + if (loc == CardLocation.Removed) + { + if (!Count.CheckCard(CardId.Artifact_Lancea)) + return false; + return (Bot.Banished.Any(i => i.HasSetcode(SetCode.Maliss) + && i.HasType(CardType.Monster) + ) || Count.CheckCard(CardId.Maliss_March_Hare)) && Count.CheckCardRemoved(CardId.Maliss_March_Hare); + } + else + { + if (!Count.CheckCard(CardId.Artifact_Lancea)) + return false; + return Bot.Graveyard.GetMonsters().Any(i => i.HasSetcode(SetCode.Maliss)); + } + } + private bool Effect_Maliss_TB_11() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Bot.GetMonsterCount() > 1 + && (!Bot.HasInMonstersZone(CardId.Maliss_Red_Ransom) || !Bot.HasInMonstersZone(CardId.Maliss_White_Binder)) + ) + return false; + if (Bot.GetMonsters().Any(i => Count.CheckCardRemoved(i.Id))) + { + Count.AddCard(Card.Id); + return true; + } + if (Bot.HasInMonstersZone(CardId.Maliss_Red_Ransom) && Count.CheckCardRemoved(CardId.Maliss_Red_Ransom)) + { + Count.AddCard(Card.Id); + return true; + } + return false; + } + private bool Effect_Maliss_MTP_07() + { + if (Duel.LastChainPlayer == 0) return false; + if (DefaultCheckWhetherCardIsNegated(Card) || Duel.Player == 0 || Enemy.GetMonsters().Count(i => !i.IsShouldNotBeTarget()) + Enemy.GetSpells().Count(i => !i.IsShouldNotBeTarget() && (i.HasType(CardType.Field | CardType.Continuous | CardType.Equip) || i.IsFacedown())) == 0 || !Bot.GetMonsters().Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Link))) return false; + if (Bot.GetMonsterCount() > 1 + && (!Bot.HasInMonstersZone(CardId.Maliss_Red_Ransom) || !Bot.HasInMonstersZone(CardId.Maliss_White_Binder)) + ) + return false; + if (Bot.GetMonsters().Any(i => Count.CheckCardRemoved(i.Id)) + && ((Count.CheckCard(CardId.Maliss_March_Hare) && !Bot.HasInHand(CardId.Maliss_March_Hare) && Check_Maliss_March_Hare(CardLocation.Hand)) + || (Count.CheckSummon() && ( + (Count.CheckCard(CardId.Maliss_Dormouse) && !Bot.HasInMonstersZone(CardId.Maliss_Dormouse) && Check_Maliss_Dormouse()) + || (Count.CheckCard(CardId.Maliss_White_Rabbit) && !Bot.HasInMonstersZone(CardId.Maliss_White_Rabbit) && Check_Maliss_White_Rabbit()) + || (Count.CheckCard(CardId.Maliss_Chessy_Cat) && !Bot.HasInMonstersZone(CardId.Maliss_Chessy_Cat) && Check_Maliss_Chessy_Cat()) + ) + ) + ) + ) + { + Count.AddCard(Card.Id); + return true; + } + if (Bot.HasInMonstersZone(CardId.Maliss_Red_Ransom) && Count.CheckCardRemoved(CardId.Maliss_Red_Ransom)) + { + Count.AddCard(Card.Id); + return true; + } + return false; + } + private bool Effect_Maliss_GWC_06() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Duel.Player == 0 && Bot.HasInGraveyard(CardId.Maliss_White_Binder)) + return false; + if (Bot.GetMonsters().Any(i => Count.CheckCardRemoved(i.Id)) && Bot.Graveyard.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Link))) + { + Count.AddCard(Card.Id); + return true; + } + return false; + } + private bool Effect_Remove() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return ( + (!Bot.HasInMonstersZone(CardId.Maliss_Dormouse) && Count.CheckCard(CardId.Maliss_Dormouse) && Count.CheckCardRemoved(CardId.Maliss_Dormouse) && Check_Maliss_Dormouse()) + || (!Bot.HasInMonstersZone(CardId.Maliss_White_Rabbit) && Count.CheckCard(CardId.Maliss_White_Rabbit) && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit) && Check_Maliss_White_Rabbit()) + || (!Bot.HasInMonstersZone(CardId.Maliss_Chessy_Cat) && Count.CheckCard(CardId.Maliss_Chessy_Cat) && Count.CheckCardRemoved(CardId.Maliss_White_Rabbit) && Check_Maliss_Chessy_Cat()) + || (Count.CheckCardRemoved(CardId.Maliss_March_Hare) && Check_Maliss_March_Hare(CardLocation.Removed) && Bot.Banished.Any(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Monster))) + ); + } + private bool SP_Splash_Mage() + { + if (Bot.GetMonsters().Count(i => !i.HasType(CardType.Link) || i.LinkCount < 2) < 2 + && !(Bot.HasInMonstersZone(CardId.Maliss_Red_Ransom) + && Count.CheckCardRemoved(CardId.Maliss_Red_Ransom) + && Bot.GetMonsters().Count() == 2 + && Count.CheckCard(CardId.Maliss_White_Binder)) + ) + return false; + + bool chk = false; + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + chk = Bot.Graveyard.Any(i => i.HasType(CardType.Monster) && i.HasRace(CardRace.Cyberse) && !i.HasType(CardType.Link)); + else + chk = true; + + if (chk) + { + List materials = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && !card.HasType(CardType.Link)).ToList(); + AI.SelectMaterials(materials); + } + return chk; + } + private bool SP_Cyberse_Wicckid() + { + if (!Count.CheckCard(CardId.Artifact_Lancea)) + return false; + if (!Count.CheckCard(CardId.Dimension_Shifter) && !Bot.Graveyard.Any(i => i.HasRace(CardRace.Cyberse))) + return false; + if (Bot.HasInHand(CardId.Backup_Ignister) || !Count.CheckCard(CardId.Backup_Ignister)) + return false; + if (Bot.GetMonsters().Any(i => i.IsFaceup() && i.Level <= 4 && i.HasRace(CardRace.Cyberse)) + && Bot.GetMonsterCount() == 3 && Count.CheckCard(CardId.Backup_Ignister) && Bot.Hand.Count > 0 + && Bot.HasInExtra(CardId.Maliss_Hearts_Crypter) && Bot.HasInExtra(CardId.Link_Decoder)) + { + List materials = Bot.GetMonsters().Where(card => card.IsFaceup() && card.Sequence > 4).ToList(); + materials.AddRange(Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Link)).ToList()); + AI.SelectMaterials(materials); + return true; + } + if (Bot.GetMonsters().Count(i => !i.HasType(CardType.Link) || i.LinkCount < 2) < 2 + || (Bot.MonsterZone[5] != null && Bot.MonsterZone[5].HasType(CardType.Link) && Bot.MonsterZone[5].LinkCount > 3) + || (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].HasType(CardType.Link) && Bot.MonsterZone[6].LinkCount > 3) + ) + return false; + if ((Bot.HasInHand(CardId.Backup_Ignister) && Count.CheckCard(CardId.Backup_Ignister) && Bot.GetMonstersInMainZone().Count() < 5) + || (Bot.HasInHand(CardId.Wizard_Ignister) && Count.CheckCard(CardId.Wizard_Ignister) + && Bot.Graveyard.Any(i => i.HasRace(CardRace.Cyberse) && i.HasAttribute(CardAttribute.Dark)) + && Bot.Graveyard.Count(i => i.HasRace(CardRace.Cyberse)) > 1 + && Bot.GetMonstersInMainZone().Count() < 4) + || (Bot.HasInHand(CardId.Maliss_March_Hare) && Count.CheckCard(CardId.Maliss_March_Hare) + && Check_Maliss_March_Hare(CardLocation.Hand) + && Bot.Graveyard.Count(i => i.HasRace(CardRace.Cyberse)) > 1 + && Bot.GetMonstersInMainZone().Count() < 4) + ) + { + List materials = Bot.GetMonsters().Where(card => card.IsFaceup() && card.Sequence > 4).ToList(); + materials.AddRange(Bot.GetMonsters().Where(card => card.IsFaceup() && !card.HasType(CardType.Link)).ToList()); + AI.SelectMaterials(materials); + return true; + } + return false; + } + private bool Effect_Haggard_Lizardose() + { + return Bot.Graveyard.Any(i => i.HasType(CardType.Monster) && i.Attack <= 2000); + } + private bool SP_Haggard_Lizardose() + { + List cards = Bot.GetMonsters().Where(i => i.IsFaceup() && (!i.HasType(CardType.Link) || i.LinkCount < 2)).ToList() + .GroupBy(i => i.Id) + .Select(i => i.First()) + .ToList(); + if (cards.Count < 2) + return false; + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea) && cards.Any(i => i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id))) + { + List materials = cards.Where(i => Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss)).ToList(); + materials.AddRange(cards.Where(i => !Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss))); + materials.AddRange(cards.Where(i => ! i.HasSetcode(SetCode.Maliss))); + AI.SelectMaterials(materials); + return true; + } + if (Bot.HasInExtra(CardId.Splash_Mage)) + return false; + bool chk = false; + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + chk = Bot.Graveyard.Any(i => i.HasType(CardType.Monster) && i.BaseAttack <= 2000 && Count.CheckCardRemoved(i.Id) && Count.CheckCard(i.Id) && i.HasSetcode(SetCode.Maliss)); + else + chk = Bot.GetMonsters().Any(i => i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && i.BaseAttack <= 2000 && i.HasSetcode(SetCode.Maliss)) + || Bot.Graveyard.Any(i => i.HasType(CardType.Monster) && Count.CheckCardRemoved(i.Id) && i.BaseAttack <= 2000 && i.HasSetcode(SetCode.Maliss)); + if (chk) + { + List materials = cards.Where(i => i.BaseAttack <= 2000 && Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss)).ToList(); + materials.AddRange(cards.Where(i => !materials.Contains(i))); + AI.SelectMaterials(materials); + } + return chk; + } + private bool SP_Maliss_Link() + { + if (Bot.GetMonsters().Any(i => i.HasType(CardType.Link) && i.LinkCount == 2) && Bot.GetMonsters().Any(i => !i.HasType(CardType.Link) && i.HasSetcode(SetCode.Maliss)) + || (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea) + && !(Bot.HasInExtra(new int[] {CardId.Cyberse_Wicckid, CardId.Splash_Mage}) + && Bot.Graveyard.Any(i => i.HasRace(CardRace.Cyberse)) + ) && !(Bot.HasInExtra(CardId.Haggard_Lizardose) + && Bot.Graveyard.Any(i => i.HasSetcode(SetCode.Maliss) + && i.HasType(CardType.Monster) + && Count.CheckCardRemoved(i.Id) + ) + ) + ) + ) + { + List materials = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && card.LinkCount == 2).ToList(); + List cards = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && card.LinkCount < 2 && card.HasSetcode(SetCode.Maliss)).ToList(); + foreach (var card in cards) + { + if (materials.Count == 2) + break; + if (card.LinkCount > 2) + continue; + materials.Add(card); + } + AI.SelectMaterials(materials); + return true; + } + return false; + } + private bool Effect_Maliss_Link() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Location == CardLocation.MonsterZone) + { + if (Card.IsCode(CardId.Maliss_White_Binder)) + { + if (ActivateDescription == Util.GetStringId(Card.Id, 1)) + { + Count.AddCard(Card.Id); + return true; + } + else if(!Bot.Graveyard.Any(i => i.HasSetcode(SetCode.Maliss) && Count.CheckCardRemoved(i.Id)) + && Enemy.Graveyard.Count() < 3) + { + Count.AddCard(Card.Id); + return true; + } + } + Count.AddCard(Card.Id); + return true; + } + else + return Effect_Maliss_Removed(900); + } + private bool SP_Link_Decoder() + { + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + { + if (Bot.GetMonsters().Any(i => i.HasSetcode(SetCode.Maliss) && i.Level <= 4 && Count.CheckCardRemoved(i.Id))){ + AI.SelectMaterials(Bot.GetMonsters().Where(i => i.HasSetcode(SetCode.Maliss) && i.Level <= 4 && Count.CheckCardRemoved(i.Id)).ToList()); + return true; + } + return false; + } + if (Bot.HasInHand(CardId.Maliss_March_Hare) && Count.CheckCard(CardId.Maliss_March_Hare) && Bot.GetMonsters().Any(i => i.HasSetcode(SetCode.Maliss) && i.Level <= 4 && Count.CheckCardRemoved(i.Id))) + { + AI.SelectMaterials(Bot.GetMonsters().Where(i => i.HasSetcode(SetCode.Maliss) && i.Level <= 4 && Count.CheckCardRemoved(i.Id)).ToList()); + return true; + } + if (Bot.GetMonsters().Any(i => i.LinkCount < 3 && i.HasSetcode(SetCode.Maliss)) && Bot.GetMonsters().Count(i => i.LinkCount < 3) >= 3) + { + AI.SelectMaterials(Bot.GetMonsters().Where(i => i.LinkCount < 3 && i.HasSetcode(SetCode.Maliss)).ToList()); + return true; + } + if (Bot.HasInMonstersZone(CardId.Cyberse_Wicckid)) + { + AI.SelectMaterials(CardId.Cyberse_Wicckid); + return true; + } + if (Bot.HasInMonstersZone(CardId.Backup_Ignister) && Bot.HasInHand(CardId.Wizard_Ignister)) + { + AI.SelectMaterials(CardId.Backup_Ignister); + return true; + } + + return false; + } + private bool Effect_Maliss_in_the_Mirror() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (ActivateDescription == Util.GetStringId(CardId.Maliss_in_the_Mirror, 0)) + { + ClientCard LastChainCard = Util.GetLastChainCard(); + return Duel.Player == 1 && LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.MonsterZone; + } + else + return Effect_Maliss_Removed(0); + } + private bool SP_Maliss_Hearts_Crypter() + { + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + { + if (Bot.HasInExtra(CardId.Maliss_Red_Ransom) || Bot.GetMonsters().Count(i => !i.HasType(CardType.Link) || i.LinkCount < 2) < (Bot.GetMonsters().Any(i => i.HasType(CardType.Link) && i.LinkCount == 2) ? 1 : 3)) + return false; + AI.SelectMaterials(Bot.GetMonsters().Where(i => !i.HasType(CardType.Link) || i.LinkCount < 2).ToList()); + return true; + } + if ((Bot.HasInMonstersZone(CardId.Link_Decoder) && Bot.GetMonsters().Count(i => !i.HasType(CardType.Link) || i.LinkCount <= 2) > 2) + || Bot.GetMonsters().Count(i => !i.HasType(CardType.Link) || i.LinkCount <= 2) > 4 + ) + { + AI.SelectMaterials(Bot.GetMonsters().Where(i => !i.HasType(CardType.Link) || i.LinkCount < 2).ToList()); + return true; + } + return false; + } + private bool SP_Maliss_White_Binder() + { + if (Bot.GetMonsters().Any(i => i.HasSetcode(SetCode.Maliss) && i.LinkCount == 3 && Count.CheckCardRemoved(i.Id))) + { + AI.SelectMaterials(Bot.GetMonsters().Where(i => Count.CheckCardRemoved(i.Id) && i.HasSetcode(SetCode.Maliss) || i.LinkCount < 3).ToList()); + return true; + } + return false; + } + private bool Effect_Maliss_Hearts_Crypter() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Location == CardLocation.MonsterZone) + { + if (Enemy.GetMonsters().Count(i => !i.IsShouldNotBeTarget()) + Enemy.GetSpells().Count(i => !i.IsShouldNotBeTarget() && (i.HasType(CardType.Field | CardType.Continuous | CardType.Equip) || i.IsFacedown())) > 0 && Duel.LastChainPlayer != 0) + { + Count.AddCard(Card.Id); + return true; + } + return false; + } + else + return Effect_Maliss_Removed(900); + } + private bool SP_Firewall_Dragon() + { + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + return false; + List materials = Bot.GetMonsters().Where(i => i.IsCode(CardId.Maliss_White_Binder)).ToList(); + materials.AddRange(Bot.GetMonsters().Where(i => i.Sequence > 4 && i.HasType(CardType.Link) && i.LinkCount <= 3)); + materials.AddRange(Bot.GetMonsters().Where(i => i.HasSetcode(SetCode.Maliss) && !i.HasType(CardType.Link))); + materials.AddRange(Bot.GetMonsters().Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Link))); + materials.AddRange(Bot.GetMonsters().Where(i => i.Sequence < 5 && i.HasType(CardType.Link) && i.LinkCount <= 3)); + materials.AddRange(Bot.GetMonsters().Where(i => !i.HasType(CardType.Link))); + if (materials.Count > 3) + materials = materials.Take(3).ToList(); + AI.SelectMaterials(materials); + return true; + } + private bool SP_Allied_Code_Talker_Ignister() + { + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + return false; + if (Bot.GetMonsters().Count(i => i.LinkCount <= 3) < 3) return false; + List materials = Bot.GetMonsters().Where(i => i.IsCode(CardId.Maliss_White_Binder)).ToList(); + materials.AddRange(Bot.GetMonsters().Where(i => i.Sequence > 4 && i.HasType(CardType.Link) && i.LinkCount <= 3)); + materials.AddRange(Bot.GetMonsters().Where(i => i.HasSetcode(SetCode.Maliss) && !i.HasType(CardType.Link))); + materials.AddRange(Bot.GetMonsters().Where(i => i.HasSetcode(SetCode.Maliss) && i.HasType(CardType.Link))); + materials.AddRange(Bot.GetMonsters().Where(i => i.Sequence < 5 && i.HasType(CardType.Link) && i.LinkCount <= 3)); + materials.AddRange(Bot.GetMonsters().Where(i => !i.HasType(CardType.Link))); + if (materials.Count > 3) + materials = materials.Take(3).ToList(); + AI.SelectMaterials(materials); + return true; + } + private bool Effect_Allied_Code_Talker_Ignister() + { + if (ActivateDescription == Util.GetStringId(CardId.Allied_Code_Talker_Ignister, 1) && Duel.LastChainPlayer == 1) + { + if (Card.Sequence > 4) + { + return Bot.GetMonsters().Any(i => i.Sequence < 3 && (!i.HasType(CardType.Link) || (i.LinkCount <= 3 && Count.CheckCard(i.Id)))); + } + else + { + return Bot.GetMonsters().Any(i => i.Sequence < 5 && (i.Sequence - Card.Sequence == 1 || Card.Sequence - i.Sequence == 1) && (!i.HasType(CardType.Link) || (i.LinkCount <= 3 && Count.CheckCard(i.Id)))); + } + } + return true; + } + private bool Effect_Mereologic_Aggregator() + { + if (Enemy.GetMonsters().Count(i => !i.IsShouldNotBeTarget()) + Enemy.GetSpells().Count(i => !i.IsShouldNotBeTarget() && (i.HasType(CardType.Field | CardType.Continuous | CardType.Equip) || i.IsFacedown())) > 0) + { + ClientCard LastChainCard = Util.GetLastChainCard(); + if (LastChainCard != null && LastChainCard.Controller == 1 && (LastChainCard.Location == CardLocation.MonsterZone || LastChainCard.Location == CardLocation.SpellZone)) + AI.SelectCard(LastChainCard); + Count.AddCard(Card.Id); + return true; + } + return false; + } + private bool Effect_Firewall_Dragon() + { + if (!Count.CheckCard(CardId.Dimension_Shifter) && Count.CheckCard(CardId.Artifact_Lancea)) + return false; + return Duel.Player == 0 || ( + Enemy.GetMonsters().Count(i => !i.IsShouldNotBeTarget() && i.IsFaceup()) + Enemy.GetSpells().Count(i => !i.IsShouldNotBeTarget() && i.HasType(CardType.Field | CardType.Continuous | CardType.Equip)) > 0 + && Duel.LastChainPlayer != 0 + ); + } + private bool Summon_Backup_Ignister() + { + if (Bot.GetMonsters().Any(i => i.HasType(CardType.Link))) + return false; + Count.AddSummon(); + return true; + } + private bool SP_Transcode_Talker() + { + if (Bot.GetMonsters().Any(i => i.HasSetcode(SetCode.Maliss))) + return false; + if (!Bot.GetMonsters().Any(i => !i.HasType(CardType.Link) || i.LinkCount < 2)) + return false; + if (!Bot.GetMonsters().Any(i => i.HasType(CardType.Link) && i.LinkCount == 2)) + return false; + List materials = Bot.GetMonsters().Where(i => i.HasType(CardType.Link) && i.LinkCount == 2).ToList(); + materials.AddRange(Bot.GetMonsters().Where(i => i.IsCode(CardId.Link_Decoder))); + materials.AddRange(Bot.GetMonsters().Where(i => !i.HasType(CardType.Link) || i.LinkCount < 2 && i.Sequence == (materials[0].Sequence > 4 ? (materials[0].Sequence == 5 ? 1 : 3) : materials[0].Sequence + 1))); + materials.AddRange(Bot.GetMonsters().Where(i => !i.HasType(CardType.Link) || i.LinkCount < 2)); + if (materials.Count > 2) + materials = materials.Take(2).ToList(); + AI.SelectMaterials(materials); + return true; + } + private bool Effect_Wizard_Ignister() + { + return Card.Location == CardLocation.Hand; + } + private bool GoToBattlePhase() + { + if (!Enemy.GetMonsters().Any(i => i.IsDefense())) + { + if (Util.GetTotalAttackingMonsterAttack(0) >= Enemy.LifePoints + Util.GetTotalAttackingMonsterAttack(1)) + { + return true; + } + } + return false; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MathMechExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MathMechExecutor.cs new file mode 100644 index 0000000..c797a0c --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MathMechExecutor.cs @@ -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 cards = new List(); + 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 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); + } + + } + +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MokeyMokeyExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MokeyMokeyExecutor.cs new file mode 100644 index 0000000..8acc20b --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MokeyMokeyExecutor.cs @@ -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(); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MokeyMokeyKingExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MokeyMokeyKingExecutor.cs new file mode 100644 index 0000000..7fb1641 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/MokeyMokeyKingExecutor.cs @@ -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(); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/NekrozExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/NekrozExecutor.cs new file mode 100644 index 0000000..f74af9d --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/NekrozExecutor.cs @@ -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 NekrozRituelCard = new List(); + List NekrozSpellCard = new List(); + + 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 NekrozCard = new List(); + 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; } + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/OldSchoolExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/OldSchoolExecutor.cs new file mode 100644 index 0000000..bc62aa3 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/OldSchoolExecutor.cs @@ -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); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/OrcustExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/OrcustExecutor.cs new file mode 100644 index 0000000..e202dd8 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/OrcustExecutor.cs @@ -0,0 +1,1183 @@ +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("Orcust", "AI_Orcust")] + class OrcustExecutor : DefaultExecutor + { + public class CardId + { + public const int OrcustKnightmare = 4055337; + public const int OrcustHarpHorror = 57835716; + public const int OrcustCymbalSkeleton = 21441617; + public const int WorldLegacyWorldWand = 93920420; + public const int ThePhantomKnightsofAncientCloak = 90432163; + public const int ThePhantomKnightsofSilentBoots = 36426778; + + public const int TrickstarCarobein = 98169343; + public const int TrickstarCandina = 61283655; + public const int ArmageddonKnight = 28985331; + public const int ScrapRecycler = 4334811; + public const int DestrudoTheLostDragonsFrisson = 5560911; + public const int JetSynchron = 9742784; + + public const int AshBlossomJoyousSpring = 14558127; + public const int GhostBelleHauntedMansion = 73642296; + public const int MaxxC = 23434538; + + public const int SkyStrikerMobilizeEngage = 63166095; + public const int SkyStrikerMechaEagleBooster = 25733157; + public const int SkyStrikerMechaHornetDrones = 52340444; + public const int SkyStrikerMechaHornetDronesToken = 52340445; + public const int TrickstarLightStage = 35371948; + public const int OrcustratedBabel = 90351981; + + public const int ReinforcementofTheArmy = 32807846; + public const int Terraforming = 73628505; + public const int FoolishBurial = 81439173; + public const int CalledbyTheGrave = 24224830; + + public const int ThePhantomKnightsofShadeBrigandine = 98827725; + public const int PhantomKnightsFogBlade = 25542642; + public const int OrcustratedClimax = 703897; + + public const int BorreloadSavageDragon = 27548199; + public const int ShootingRiserDragon = 68431965; + public const int SheorcustDingirsu = 93854893; + public const int BorrelswordDragon = 85289965; + public const int LongirsuTheOrcustOrchestrator = 76145142; + public const int ThePhantomKnightsofRustyBardiche = 26692769; + public const int KnightmarePhoenix = 2857636; + public const int GalateaTheOrcustAutomaton = 30741503; + public const int CrystronNeedlefiber = 50588353; + public const int SkyStrikerAceKagari = 63288573; + public const int KnightmareMermaid = 3679218; + public const int SalamangreatAlmiraj = 60303245; + } + + public OrcustExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, CardId.SkyStrikerMechaEagleBooster, EagleBoosterEffect); + AddExecutor(ExecutorType.Activate, CardId.OrcustratedClimax, ClimaxEffect); + + AddExecutor(ExecutorType.Activate, CardId.MaxxC, DefaultMaxxC); + AddExecutor(ExecutorType.Activate, CardId.AshBlossomJoyousSpring, DefaultAshBlossomAndJoyousSpring); + AddExecutor(ExecutorType.Activate, CardId.GhostBelleHauntedMansion, DefaultGhostBelleAndHauntedMansion); + AddExecutor(ExecutorType.Activate, CardId.CalledbyTheGrave, DefaultCalledByTheGrave); + + AddExecutor(ExecutorType.Activate, CardId.Terraforming, TerraformingEffect); + AddExecutor(ExecutorType.Activate, CardId.ReinforcementofTheArmy, ReinforcementofTheArmyEffect); + AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialEffect); + + AddExecutor(ExecutorType.Activate, CardId.TrickstarLightStage, LightStageEffect); + + AddExecutor(ExecutorType.Activate, CardId.SkyStrikerMobilizeEngage, EngageEffect); + AddExecutor(ExecutorType.Activate, CardId.SkyStrikerMechaHornetDrones, DronesEffectFirst); + AddExecutor(ExecutorType.SpSummon, CardId.SkyStrikerAceKagari); + AddExecutor(ExecutorType.Activate, CardId.SkyStrikerAceKagari); + + AddExecutor(ExecutorType.SpSummon, CardId.KnightmareMermaid, KnightmareMermaidSummon); + AddExecutor(ExecutorType.Activate, CardId.KnightmareMermaid, KnightmareMermaidEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.TrickstarCarobein, CarobeinSummon); + AddExecutor(ExecutorType.Activate, CardId.TrickstarCarobein); + + AddExecutor(ExecutorType.SpellSet, CardId.ThePhantomKnightsofShadeBrigandine); + + AddExecutor(ExecutorType.Summon, CardId.ArmageddonKnight, ArmageddonKnightSummon); + AddExecutor(ExecutorType.Activate, CardId.ArmageddonKnight, ArmageddonKnightEffect); + + AddExecutor(ExecutorType.Summon, CardId.ScrapRecycler, ScrapRecyclerSummon); + AddExecutor(ExecutorType.Activate, CardId.ScrapRecycler, ScrapRecyclerEffect); + + AddExecutor(ExecutorType.Activate, CardId.SkyStrikerMechaHornetDrones, DronesEffect); + + AddExecutor(ExecutorType.Summon, CardId.JetSynchron, JetSynchronSummon); + + AddExecutor(ExecutorType.Activate, CardId.DestrudoTheLostDragonsFrisson, DestrudoSummon); + + AddExecutor(ExecutorType.SpSummon, CardId.CrystronNeedlefiber, NeedlefiberSummonFirst); + AddExecutor(ExecutorType.Activate, CardId.CrystronNeedlefiber, NeedlefiberEffect); + + AddExecutor(ExecutorType.Activate, CardId.ShootingRiserDragon, ShootingRiserDragonEffect); + + AddExecutor(ExecutorType.Summon, CardId.TrickstarCandina, CandinaSummon); + AddExecutor(ExecutorType.Activate, CardId.TrickstarCandina, CandinaEffect); + + AddExecutor(ExecutorType.Summon, CardId.JetSynchron, OneCardComboSummon); + AddExecutor(ExecutorType.Summon, CardId.ThePhantomKnightsofAncientCloak, OneCardComboSummon); + AddExecutor(ExecutorType.Summon, CardId.ThePhantomKnightsofSilentBoots, OneCardComboSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SalamangreatAlmiraj, AlmirajSummon); + + AddExecutor(ExecutorType.Activate, CardId.ThePhantomKnightsofShadeBrigandine, ShadeBrigandineSummonFirst); + + AddExecutor(ExecutorType.SpSummon, CardId.KnightmarePhoenix, KnightmarePhoenixSummon); + AddExecutor(ExecutorType.Activate, CardId.KnightmarePhoenix, KnightmarePhoenixEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.GalateaTheOrcustAutomaton, GalateaSummonFirst); + + AddExecutor(ExecutorType.Activate, CardId.JetSynchron, JetSynchronEffect); + + AddExecutor(ExecutorType.Activate, CardId.OrcustKnightmare, OrcustKnightmareEffect); + + AddExecutor(ExecutorType.Activate, CardId.OrcustHarpHorror, HarpHorrorEffect); + + AddExecutor(ExecutorType.Activate, CardId.WorldLegacyWorldWand, WorldWandEffect); + + AddExecutor(ExecutorType.Activate, CardId.ThePhantomKnightsofAncientCloak, AncientCloakEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.ThePhantomKnightsofRustyBardiche, RustyBardicheSummon); + AddExecutor(ExecutorType.Activate, CardId.ThePhantomKnightsofRustyBardiche, RustyBardicheEffect); + + AddExecutor(ExecutorType.Activate, CardId.OrcustCymbalSkeleton, CymbalSkeletonEffect); + + AddExecutor(ExecutorType.Activate, CardId.GalateaTheOrcustAutomaton, GalateaEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.SheorcustDingirsu, SheorcustDingirsuSummon); + AddExecutor(ExecutorType.Activate, CardId.SheorcustDingirsu, SheorcustDingirsuEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.ThePhantomKnightsofSilentBoots, SilentBootsSummon); + AddExecutor(ExecutorType.Activate, CardId.ThePhantomKnightsofShadeBrigandine, ShadeBrigandineSummonSecond); + + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadSavageDragon); + AddExecutor(ExecutorType.Activate, CardId.BorreloadSavageDragon, BorreloadSavageDragonEffect); + + AddExecutor(ExecutorType.SpSummon, CardId.GalateaTheOrcustAutomaton, GalateaSummonSecond); + + AddExecutor(ExecutorType.Activate, CardId.ThePhantomKnightsofSilentBoots, SilentBootsEffect); + + AddExecutor(ExecutorType.Summon, CardId.GhostBelleHauntedMansion, TunerSummon); + AddExecutor(ExecutorType.Summon, CardId.AshBlossomJoyousSpring, TunerSummon); + AddExecutor(ExecutorType.Summon, CardId.OrcustCymbalSkeleton, OtherSummon); + AddExecutor(ExecutorType.Summon, CardId.OrcustHarpHorror, OtherSummon); + AddExecutor(ExecutorType.Summon, CardId.ThePhantomKnightsofAncientCloak, LinkMaterialSummon); + AddExecutor(ExecutorType.Summon, CardId.MaxxC, LinkMaterialSummon); + AddExecutor(ExecutorType.Summon, CardId.ThePhantomKnightsofSilentBoots, LinkMaterialSummon); + + AddExecutor(ExecutorType.SpSummon, CardId.CrystronNeedlefiber, NeedlefiberSummonSecond); + + AddExecutor(ExecutorType.SpSummon, CardId.BorrelswordDragon, BorrelswordDragonSummon); + AddExecutor(ExecutorType.Activate, CardId.BorrelswordDragon, BorrelswordDragonEffect); + + AddExecutor(ExecutorType.SpellSet, CardId.PhantomKnightsFogBlade); + AddExecutor(ExecutorType.Activate, CardId.PhantomKnightsFogBlade, FogBladeEffect); + AddExecutor(ExecutorType.SpellSet, CardId.OrcustratedClimax); + + AddExecutor(ExecutorType.Activate, CardId.OrcustratedBabel, BabelEffect); + + AddExecutor(ExecutorType.Repos, MonsterRepos); + } + + private bool NormalSummoned = false; + private bool SheorcustDingirsuSummoned = false; + private bool HarpHorrorUsed = false; + private bool CymbalSkeletonUsed = false; + private bool BorrelswordDragonUsed = false; + private ClientCard RustyBardicheTarget = null; + + private int[] HandCosts = new[] + { + CardId.OrcustCymbalSkeleton, + CardId.OrcustKnightmare, + CardId.DestrudoTheLostDragonsFrisson, + CardId.WorldLegacyWorldWand, + CardId.OrcustHarpHorror, + CardId.ThePhantomKnightsofAncientCloak, + CardId.ThePhantomKnightsofSilentBoots, + CardId.JetSynchron, + CardId.TrickstarLightStage, + CardId.SkyStrikerMobilizeEngage, + CardId.Terraforming, + CardId.ReinforcementofTheArmy, + CardId.MaxxC, + CardId.GhostBelleHauntedMansion + }; + + public override bool OnSelectHand() + { + // go first + return true; + } + + public override void OnNewTurn() + { + NormalSummoned = false; + SheorcustDingirsuSummoned = false; + HarpHorrorUsed = false; + CymbalSkeletonUsed = false; + BorrelswordDragonUsed = false; + RustyBardicheTarget = null; + base.OnNewTurn(); + } + + public override void OnChainEnd() + { + RustyBardicheTarget = null; + base.OnChainEnd(); + } + + public override CardPosition OnSelectPosition(int cardId, IList 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.KnightmarePhoenix || 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.z0) > 0) + return Zones.z0; + if ((available & Zones.z1) > 0) + return Zones.z1; + if ((available & Zones.z2) > 0) + return Zones.z2; + if ((available & Zones.z3) > 0) + return Zones.z3; + if ((available & Zones.z4) > 0) + return Zones.z4; + } + if (location == CardLocation.MonsterZone) + { + if (cardId == CardId.SheorcustDingirsu) + { + ClientCard l = Bot.MonsterZone.GetFirstMatchingCard(card => card.Id == CardId.ThePhantomKnightsofRustyBardiche); + int zones = (l?.GetLinkedZones() ?? 0) & available; + if ((zones & Zones.z4) > 0) + return Zones.z4; + if ((zones & Zones.z3) > 0) + return Zones.z3; + if ((zones & Zones.z2) > 0) + return Zones.z2; + if ((zones & Zones.z1) > 0) + return Zones.z1; + if ((zones & Zones.z0) > 0) + return Zones.z0; + } + if (cardId == CardId.GalateaTheOrcustAutomaton) + { + int zones = Bot.GetLinkedZones() & available; + if ((zones & Zones.z0) > 0) + return Zones.z0; + if ((zones & Zones.z2) > 0) + return Zones.z2; + if ((zones & Zones.z1) > 0) + return Zones.z1; + if ((zones & Zones.z3) > 0) + return Zones.z3; + if ((zones & Zones.z4) > 0) + return Zones.z4; + } + if (cardId == CardId.KnightmarePhoenix) + { + if ((Enemy.MonsterZone[5]?.HasLinkMarker(CardLinkMarker.Top) ?? false) && (available & Zones.z3) > 0) + return Zones.z3; + if ((Enemy.MonsterZone[6]?.HasLinkMarker(CardLinkMarker.Top) ?? false) && (available & Zones.z1) > 0) + return Zones.z1; + } + + if ((available & Zones.z6) > 0) + return Zones.z6; + if ((available & Zones.z5) > 0) + return Zones.z5; + if ((available & Zones.z1) > 0) + return Zones.z1; + if ((available & Zones.z3) > 0) + return Zones.z3; + if ((available & Zones.z0) > 0) + return Zones.z0; + if ((available & Zones.z4) > 0) + return Zones.z4; + if ((available & Zones.z2) > 0) + return Zones.z2; + } + return 0; + } + + public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + if (!defender.IsMonsterHasPreventActivationEffectInBattle()) + { + if (attacker.IsCode(CardId.TrickstarCandina) && Bot.HasInHand(CardId.TrickstarCarobein)) + attacker.RealPower = attacker.RealPower + 1800; + + if (attacker.IsCode(CardId.BorrelswordDragon) && !attacker.IsDisabled() && !BorrelswordDragonUsed) + { + attacker.RealPower = attacker.RealPower + defender.GetDefensePower() / 2; + defender.RealPower = defender.RealPower - defender.GetDefensePower() / 2; + } + } + return base.OnPreBattleBetween(attacker, defender); + } + + private bool TerraformingEffect() + { + AI.SelectCard(CardId.TrickstarLightStage); + return true; + } + + private bool ReinforcementofTheArmyEffect() + { + AI.SelectCard(CardId.ArmageddonKnight); + return true; + } + + private bool FoolishBurialEffect() + { + AI.SelectCard(new[] { + CardId.DestrudoTheLostDragonsFrisson, + CardId.JetSynchron, + CardId.OrcustHarpHorror, + CardId.OrcustCymbalSkeleton + }); + return true; + } + + private bool LightStageEffect() + { + if (Card.Location == CardLocation.Hand || Card.IsFacedown()) + { + ClientCard field = Bot.GetFieldSpellCard(); + if ((field?.IsCode(CardId.OrcustratedBabel) ?? false) && Bot.GetMonsterCount() > 1) + return false; + if ((field?.IsCode(CardId.TrickstarLightStage) ?? false) && Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.TrickstarCandina) && Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.TrickstarCarobein)) + return false; + AI.SelectYesNo(true); + if (Bot.HasInHandOrHasInMonstersZone(CardId.TrickstarCandina)) + AI.SelectCard(CardId.TrickstarCarobein); + else + AI.SelectCard(CardId.TrickstarCandina); + return true; + } + ClientCard target = Enemy.SpellZone.GetFirstMatchingCard(card => card.IsFacedown()); + AI.SelectCard(target); + return true; + } + + private bool CarobeinSummon() + { + if (Bot.HasInMonstersZone(CardId.TrickstarCandina)) + { + // TODO: beat mode + return Bot.HasInExtra(CardId.KnightmarePhoenix); + } + else + { + return !NormalSummoned && Bot.Hand.IsExistingMatchingCard(card => card.Level <= 4); + } + } + + private bool EngageEffect() + { + bool needProtect = false; + if (Bot.HasInHand(CardId.ArmageddonKnight)) + needProtect = true; + else if (Bot.HasInHandOrInGraveyard(CardId.DestrudoTheLostDragonsFrisson) && Bot.Hand.IsExistingMatchingCard(card => card.Level <= 4)) + needProtect = true; + else if (Bot.HasInHand(CardId.TrickstarCandina)) + needProtect = true; + if (needProtect) + AI.SelectCard(CardId.SkyStrikerMechaEagleBooster); + else + AI.SelectCard(CardId.SkyStrikerMechaHornetDrones); + AI.SelectYesNo(true); + return true; + } + + private bool DronesEffectFirst() + { + return Bot.GetMonsterCount() == 0; + } + + private bool DronesEffect() + { + return !Bot.HasInHand(CardId.ArmageddonKnight) && !Bot.HasInHand(CardId.TrickstarCandina); + } + + private bool CandinaSummon() + { + NormalSummoned = true; + return true; + } + + private bool CandinaEffect() + { + AI.SelectCard(CardId.TrickstarLightStage); + return true; + } + + private bool ArmageddonKnightSummon() + { + NormalSummoned = true; + return true; + } + + private bool ArmageddonKnightEffect() + { + AI.SelectCard(new[] { + CardId.DestrudoTheLostDragonsFrisson, + CardId.OrcustHarpHorror + }); + return true; + } + + private bool ScrapRecyclerSummon() + { + NormalSummoned = true; + return true; + } + + private bool ScrapRecyclerEffect() + { + AI.SelectCard(new[] { + CardId.JetSynchron, + CardId.OrcustHarpHorror + }); + return true; + } + + private bool JetSynchronSummon() + { + if (Bot.GetMonsterCount() > 0) + { + NormalSummoned = true; + return true; + } + return false; + } + + private bool JetSynchronEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + AI.SelectCard(HandCosts); + return true; + } + + private bool AlmirajSummon() + { + if (Bot.GetMonsterCount() > 1) + return false; + ClientCard mat = Bot.GetMonsters().First(); + if (mat.IsCode(new[] { + CardId.JetSynchron, + CardId.ThePhantomKnightsofAncientCloak, + CardId.ThePhantomKnightsofSilentBoots + })) + { + AI.SelectMaterials(mat); + return true; + } + return false; + } + + private bool DestrudoSummon() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return Bot.GetMonsterCount() < 3 && Bot.HasInExtra(new[] { CardId.CrystronNeedlefiber, CardId.KnightmarePhoenix }); + } + + private bool NeedlefiberSummonFirst() + { + if (!Bot.HasInExtra(CardId.BorreloadSavageDragon)) + return false; + if (!Bot.HasInHand(CardId.JetSynchron) && Bot.GetRemainingCount(CardId.JetSynchron, 1) == 0) + return false; + + int[] matids = new[] { + CardId.DestrudoTheLostDragonsFrisson, + CardId.AshBlossomJoyousSpring, + CardId.GhostBelleHauntedMansion, + CardId.SkyStrikerMechaHornetDronesToken, + CardId.TrickstarCarobein, + CardId.SkyStrikerAceKagari, + CardId.ScrapRecycler, + CardId.ArmageddonKnight, + CardId.TrickstarCandina, + CardId.OrcustHarpHorror, + CardId.OrcustCymbalSkeleton, + CardId.ThePhantomKnightsofAncientCloak, + CardId.ThePhantomKnightsofSilentBoots + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(matids)) >= 2) + { + AI.SelectMaterials(matids); + return true; + } + return false; + } + + private bool NeedlefiberSummonSecond() + { + IList selected = new List(); + + ClientCard tuner = Bot.MonsterZone.GetFirstMatchingFaceupCard(card => card.IsCode(new[] + { + CardId.DestrudoTheLostDragonsFrisson, + CardId.AshBlossomJoyousSpring, + CardId.GhostBelleHauntedMansion, + CardId.JetSynchron + })); + if (tuner != null) + selected.Add(tuner); + + int[] matids = new[] { + CardId.SkyStrikerMechaHornetDronesToken, + CardId.ThePhantomKnightsofShadeBrigandine, + CardId.SkyStrikerAceKagari, + CardId.ScrapRecycler, + CardId.ArmageddonKnight, + CardId.OrcustHarpHorror, + CardId.OrcustCymbalSkeleton, + CardId.ThePhantomKnightsofAncientCloak, + CardId.ThePhantomKnightsofSilentBoots + }; + + IList mats = Bot.MonsterZone.GetMatchingCards(card => card.Attack <= 1700); + + for (int i = 0; i < matids.Length && selected.Count < 2; i++) + { + ClientCard c = mats.GetFirstMatchingFaceupCard(card => card.IsCode(matids[i])); + if (c != null) + { + selected.Add(c); + if (selected.Count == 2 && Util.GetBotAvailZonesFromExtraDeck(selected) == 0) + selected.Remove(c); + } + } + + if (selected.Count == 2) + { + AI.SelectMaterials(selected); + return true; + } + return false; + } + + private bool NeedlefiberEffect() + { + AI.SelectCard(CardId.JetSynchron); + return true; + } + + private bool ShootingRiserDragonEffect() + { + if (ActivateDescription == -1 || (ActivateDescription == Util.GetStringId(CardId.ShootingRiserDragon, 0))) + { + if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == 3 && card.IsFaceup() && !card.IsTuner()) && Bot.GetRemainingCount(CardId.MaxxC, 3) > 0) + { + AI.SelectCard(CardId.MaxxC); + } + else if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == 4 && card.IsFaceup() && !card.IsTuner())) + { + AI.SelectCard(new[] { + CardId.ThePhantomKnightsofAncientCloak, + CardId.ThePhantomKnightsofSilentBoots, + CardId.ScrapRecycler, + CardId.OrcustCymbalSkeleton, + CardId.AshBlossomJoyousSpring, + CardId.GhostBelleHauntedMansion + }); + } + else if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == 5 && card.IsFaceup() && !card.IsTuner())) + { + AI.SelectCard(new[] { + CardId.OrcustHarpHorror, + CardId.ArmageddonKnight, + CardId.TrickstarCandina + }); + } + else + { + FoolishBurialEffect(); + } + return true; + } + else + { + return Duel.LastChainPlayer != 0; + } + } + + private bool KnightmarePhoenixSummon() + { + if (!KnightmareMermaidSummon()) + return false; + if (!Bot.HasInExtra(CardId.KnightmareMermaid)) + return false; + + int[] firstMats = new[] { + CardId.JetSynchron, + CardId.CrystronNeedlefiber, + CardId.SkyStrikerMechaHornetDronesToken, + CardId.ThePhantomKnightsofShadeBrigandine, + CardId.ScrapRecycler, + CardId.SkyStrikerAceKagari, + CardId.ArmageddonKnight, + CardId.TrickstarCandina, + CardId.TrickstarCarobein + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(firstMats)) >= 2) + { + AI.SelectMaterials(firstMats); + return true; + } + int[] secondMats = new[] { + CardId.OrcustCymbalSkeleton, + CardId.OrcustHarpHorror, + CardId.DestrudoTheLostDragonsFrisson, + CardId.JetSynchron, + CardId.AshBlossomJoyousSpring, + CardId.GhostBelleHauntedMansion, + CardId.ThePhantomKnightsofSilentBoots, + CardId.ThePhantomKnightsofAncientCloak, + CardId.MaxxC, + CardId.SalamangreatAlmiraj + }; + int[] mats = firstMats.Concat(secondMats).ToArray(); + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(mats)) >= 2) + { + AI.SelectMaterials(mats); + return true; + } + return false; + } + + private bool KnightmarePhoenixEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + int costcount = Bot.Hand.GetMatchingCardsCount(card => card.IsCode(HandCosts)); + ClientCard target = Enemy.SpellZone.GetFloodgate(); + ClientCard anytarget = Enemy.SpellZone.GetFirstMatchingCard(card => !card.OwnTargets.Any(cont => cont.IsCode(CardId.TrickstarLightStage))); + if ((costcount > 1 && anytarget != null) || (Bot.GetHandCount() > 1 && target != null)) + { + AI.SelectCard(HandCosts); + if (target == null) + target = anytarget; + AI.SelectNextCard(target); + return true; + } + return false; + } + + private bool KnightmareMermaidSummon() + { + if (Bot.GetHandCount() == 0) + return false; + if (Bot.GetRemainingCount(CardId.OrcustKnightmare, 2) == 0) + return false; + AI.SelectPlace(Zones.ExtraMonsterZones); + return true; + } + + private bool KnightmareMermaidEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + AI.SelectCard(HandCosts); + return true; + } + + private bool GalateaSummonFirst() + { + // only summon with Mermaid and Orcust Knightmare + IList mats = Bot.MonsterZone.GetMatchingCards(card => card.IsCode(CardId.KnightmareMermaid, CardId.OrcustKnightmare)); + if (mats.Count >= 2) + { + AI.SelectMaterials(mats); + return true; + } + return false; + } + + private bool OrcustKnightmareEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (!Bot.HasInGraveyard(CardId.OrcustHarpHorror)) + { + AI.SelectCard(Util.GetBestBotMonster()); + AI.SelectNextCard(CardId.OrcustHarpHorror); + return true; + } + else if (!Bot.HasInGraveyard(CardId.WorldLegacyWorldWand) && Bot.GetRemainingCount(CardId.WorldLegacyWorldWand, 1) > 0) + { + AI.SelectCard(CardId.GalateaTheOrcustAutomaton); + AI.SelectNextCard(CardId.WorldLegacyWorldWand); + return true; + } + else if (!Bot.HasInGraveyard(CardId.OrcustCymbalSkeleton) && Bot.GetRemainingCount(CardId.OrcustCymbalSkeleton, 1) > 0 && Bot.HasInGraveyard(CardId.SheorcustDingirsu) && !SheorcustDingirsuSummoned) + { + AI.SelectCard(CardId.GalateaTheOrcustAutomaton); + AI.SelectNextCard(CardId.OrcustCymbalSkeleton); + return true; + } + return false; + } + + private bool HarpHorrorEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + HarpHorrorUsed = true; + AI.SelectCard(CardId.OrcustCymbalSkeleton); + return true; + } + + private bool WorldWandEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + AI.SelectCard(CardId.OrcustCymbalSkeleton); + return true; + } + + private bool RustyBardicheSummon() + { + //if (Bot.GetRemainingCount(CardId.ThePhantomKnightsofAncientCloak, 1) == 0 && Bot.GetRemainingCount(CardId.ThePhantomKnightsofSilentBoots, 1) == 0) + // return false; + //if (Bot.GetRemainingCount(CardId.ThePhantomKnightsofShadeBrigandine, 1) == 0 && Bot.GetRemainingCount(CardId.PhantomKnightsFogBlade, 2) == 0) + // return false; + IList mats = Bot.MonsterZone.GetMatchingCards(card => card.IsCode(CardId.GalateaTheOrcustAutomaton)); + ClientCard mat2 = Bot.MonsterZone.GetMatchingCards(card => card.IsCode(CardId.OrcustCymbalSkeleton)).FirstOrDefault(); + if (mat2 != null) + mats.Add(mat2); + AI.SelectMaterials(mats); + AI.SelectPlace(Zones.ExtraMonsterZones); + return true; + } + + private bool RustyBardicheEffect() + { + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.ThePhantomKnightsofRustyBardiche, 0)) + { + ClientCard target = GetFogBladeTarget(); + if (target == null) + target = Util.GetBestEnemyCard(false, true); + if (target == null) + return false; + RustyBardicheTarget = target; + AI.SelectCard(target); + return true; + } + else + { + AI.SelectCard(CardId.ThePhantomKnightsofAncientCloak); + if (Bot.HasInMonstersZone(CardId.JetSynchron) && !Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == 4)) + AI.SelectNextCard(CardId.ThePhantomKnightsofShadeBrigandine); + else + AI.SelectNextCard(CardId.PhantomKnightsFogBlade); + return true; + } + } + + private ClientCard GetFogBladeTarget() + { + return Enemy.MonsterZone.GetFirstMatchingCard(card => card.OwnTargets.Any(cont => cont.IsCode(CardId.PhantomKnightsFogBlade))); + } + + private bool CymbalSkeletonEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + int[] botTurnTargets = new[] { CardId.GalateaTheOrcustAutomaton, CardId.SheorcustDingirsu }; + int[] emenyTurnTargets = new[] { CardId.SheorcustDingirsu, CardId.GalateaTheOrcustAutomaton }; + if (Duel.Player == 0 && Bot.HasInGraveyard(CardId.GalateaTheOrcustAutomaton) && !Bot.HasInMonstersZone(CardId.GalateaTheOrcustAutomaton) && Bot.HasInExtra(CardId.SheorcustDingirsu) && !SheorcustDingirsuSummoned) + { + AI.SelectCard(botTurnTargets); + CymbalSkeletonUsed = true; + return true; + } + else if (Duel.Player == 0 && Bot.HasInGraveyard(CardId.SheorcustDingirsu) && !SheorcustDingirsuSummoned) + { + AI.SelectCard(emenyTurnTargets); + SheorcustDingirsuSummoned = true; + CymbalSkeletonUsed = true; + return true; + } + if (Duel.Player == 1 && Bot.HasInGraveyard(CardId.SheorcustDingirsu) && !SheorcustDingirsuSummoned && + (Util.GetProblematicEnemyCard() != null || Duel.Phase == DuelPhase.End)) + { + AI.SelectCard(emenyTurnTargets); + CymbalSkeletonUsed = true; + SheorcustDingirsuSummoned = true; + return true; + } + return false; + } + + private bool SheorcustDingirsuSummon() + { + SheorcustDingirsuSummoned = true; + return true; + } + + private bool SheorcustDingirsuEffect() + { + if (ActivateDescription == 96) + { + // TODO: more FogBlade lost target + if ((Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2) && Duel.CurrentChain.Count == 0) + return false; + AI.SelectCard(CardId.OrcustCymbalSkeleton); + return true; + } + ClientCard target; + target = GetFogBladeTarget(); + if (target != null && target != RustyBardicheTarget) + { + AI.SelectOption(0); + AI.SelectCard(target); + return true; + } + target = Util.GetProblematicEnemyMonster(); + if (target != null && target != RustyBardicheTarget) + { + AI.SelectOption(0); + AI.SelectCard(target); + return true; + } + target = Util.GetProblematicEnemySpell(); + if (target != null && target != RustyBardicheTarget) + { + AI.SelectOption(0); + AI.SelectCard(target); + return true; + } + if (Bot.HasInBanished(CardId.OrcustCymbalSkeleton)) + { + AI.SelectOption(1); + AI.SelectCard(CardId.OrcustCymbalSkeleton); + return true; + } + target = Enemy.MonsterZone.GetFirstMatchingCard(card => card != RustyBardicheTarget) ?? Enemy.SpellZone.GetFirstMatchingCard(card => card != RustyBardicheTarget); + if (target != null) + { + AI.SelectOption(0); + AI.SelectCard(target); + return true; + } + AI.SelectOption(1); + //AI.SelectCard(); any card + return true; + } + + private bool AncientCloakEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Bot.HasInMonstersZone(CardId.SalamangreatAlmiraj) && Bot.HasInExtra(CardId.KnightmarePhoenix)) + AI.SelectCard(CardId.ThePhantomKnightsofShadeBrigandine); + else + AI.SelectCard(CardId.ThePhantomKnightsofSilentBoots); + return true; + } + + private bool SilentBootsSummon() + { + return true; + } + + private bool SilentBootsEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Bot.HasInMonstersZone(CardId.SalamangreatAlmiraj) && Bot.HasInExtra(CardId.KnightmarePhoenix)) + AI.SelectCard(CardId.ThePhantomKnightsofShadeBrigandine); + else + AI.SelectCard(CardId.PhantomKnightsFogBlade); + return true; + } + + private bool ShadeBrigandineSummonSecond() + { + if (DefaultOnBecomeTarget()) + return true; + return (Bot.HasInMonstersZone(CardId.SalamangreatAlmiraj) && Bot.HasInExtra(CardId.KnightmarePhoenix)) || + (Bot.HasInMonstersZone(CardId.JetSynchron) && Bot.HasInMonstersZone(CardId.ThePhantomKnightsofSilentBoots)); + } + + private bool GalateaSummonSecond() + { + if (!Util.IsTurn1OrMain2()) + return false; + + if (Bot.HasInMonstersZone(CardId.GalateaTheOrcustAutomaton)) + return false; + + IList selected = new List(); + + if (!Bot.HasInGraveyard(CardId.SheorcustDingirsu)) + { + ClientCard sheorcustDingirsu = Bot.MonsterZone.GetFirstMatchingFaceupCard(card => card.IsCode(CardId.SheorcustDingirsu)); + if (sheorcustDingirsu != null) + selected.Add(sheorcustDingirsu); + } + + int[] matids = new[] { + CardId.OrcustKnightmare, + CardId.ThePhantomKnightsofSilentBoots, + CardId.ThePhantomKnightsofAncientCloak, + CardId.OrcustCymbalSkeleton, + CardId.OrcustHarpHorror, + CardId.ScrapRecycler, + CardId.CrystronNeedlefiber, + CardId.SkyStrikerAceKagari, + CardId.KnightmareMermaid, + CardId.ArmageddonKnight + }; + + IList mats = Bot.MonsterZone.GetMatchingCards(card => card.Level > 0 && card.Level <= 7); + + for (int i = 0; i < matids.Length && selected.Count < 2; i++) + { + ClientCard c = mats.GetFirstMatchingFaceupCard(card => card.IsCode(matids[i])); + if (c != null) + { + selected.Add(c); + if (selected.Count == 2 && Util.GetBotAvailZonesFromExtraDeck(selected) == 0) + selected.Remove(c); + } + } + + if (selected.Count == 2) + { + AI.SelectMaterials(selected); + return true; + } + + return false; + } + + private bool GalateaEffect() + { + if (Duel.Player == 0) + { + AI.SelectCard(CardId.OrcustKnightmare); + AI.SelectNextCard(CardId.OrcustratedBabel); + } + if (Duel.Player == 1) + { + AI.SelectCard(CardId.OrcustKnightmare); + AI.SelectNextCard(CardId.OrcustratedClimax); + } + return true; + } + + private bool BorrelswordDragonSummon() + { + if (Util.IsTurn1OrMain2()) + return false; + + List mats = Bot.MonsterZone.GetMatchingCards(card => card.IsFaceup() && card.HasType(CardType.Effect) && card.Attack <= 2000).ToList(); + mats.Sort(CardContainer.CompareCardAttack); + mats.Reverse(); + + int link = 0; + bool doubleused = false; + IList selected = new List(); + foreach (ClientCard card in mats) + { + selected.Add(card); + if (!doubleused && card.LinkCount == 2) + { + doubleused = true; + link += 2; + } + else + link++; + if (link >= 4) + break; + } + + if (link >= 4 && Util.GetBotAvailZonesFromExtraDeck(selected) > 0) + { + AI.SelectMaterials(selected); + return true; + } + return false; + } + + private bool BorrelswordDragonEffect() + { + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.BorrelswordDragon, 1)) + { + BorrelswordDragonUsed = true; + return true; + } + else + { + if (Duel.Player == 0 && (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2)) + { + return false; + } + ClientCard target = Bot.MonsterZone.GetFirstMatchingCard(card => card.IsAttack() && !card.HasType(CardType.Link) && card.Attacked && !card.IsShouldNotBeTarget()); + if (target != null) + { + AI.SelectCard(target); + return true; + } + if (!Bot.MonsterZone.IsExistingMatchingCard(card => card.IsAttack() && !card.HasType(CardType.Link))) + { + target = Enemy.MonsterZone.GetFirstMatchingCard(card => card.IsAttack() && !card.HasType(CardType.Link) && !card.IsShouldNotBeTarget()); + if (target != null) + { + AI.SelectCard(target); + return true; + } + } + return false; + } + } + + private bool BabelEffect() + { + if (Card.Location == CardLocation.Grave) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + IList costCards = Bot.Hand.GetMatchingCards(card => card.IsCode(HandCosts)); + if (costCards.Count > 0) + { + AI.SelectCard(HandCosts); + return true; + } + return false; + } + return Bot.HasInMonstersZoneOrInGraveyard(new[] { + CardId.OrcustCymbalSkeleton, + CardId.OrcustHarpHorror, + CardId.OrcustKnightmare, + CardId.GalateaTheOrcustAutomaton, + CardId.LongirsuTheOrcustOrchestrator, + CardId.SheorcustDingirsu + }); + } + + private bool ShadeBrigandineSummonFirst() + { + return Bot.GetMonsterCount() < 2; + } + + private bool OneCardComboSummon() + { + if (Bot.HasInExtra(CardId.SalamangreatAlmiraj) && Bot.HasInExtra(new[] { CardId.CrystronNeedlefiber, CardId.KnightmarePhoenix }) && Bot.GetMonsterCount() < 3) + { + NormalSummoned = true; + return true; + } + return false; + } + + private bool LinkMaterialSummon() + { + if (Bot.HasInExtra(CardId.KnightmarePhoenix) && Bot.GetMonsterCount() > 0 && Bot.GetMonsterCount() < 3) + { + NormalSummoned = true; + return true; + } + return false; + } + + private bool TunerSummon() + { + if (Bot.HasInExtra(new[] { CardId.CrystronNeedlefiber, CardId.KnightmarePhoenix }) && Bot.GetMonsterCount() > 0 && Bot.GetMonsterCount() < 3) + { + NormalSummoned = true; + return true; + } + return false; + } + + private bool OtherSummon() + { + NormalSummoned = true; + return true; + } + + private bool BorreloadSavageDragonEffect() + { + if (Duel.CurrentChain.Count == 0) + { + AI.SelectCard(new[] { CardId.KnightmarePhoenix, CardId.CrystronNeedlefiber }); + return true; + } + else + { + return true; + } + } + + private bool FogBladeEffect() + { + if (Card.Location == CardLocation.SpellZone) + { + return !Util.HasChainedTrap(0) && DefaultDisableMonster(); + } + else if (Bot.HasInGraveyard(CardId.ThePhantomKnightsofRustyBardiche) || Bot.GetMonsterCount() < 2) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + AI.SelectCard(CardId.ThePhantomKnightsofRustyBardiche); + return true; + } + return false; + } + + private bool ClimaxEffect() + { + if (Card.Location == CardLocation.SpellZone) + { + return Duel.LastChainPlayer == 1; + } + else if (Duel.Phase == DuelPhase.End) + { + ClientCard target = null; + target = Bot.Banished.GetFirstMatchingFaceupCard(card=>card.IsCode(CardId.OrcustCymbalSkeleton)); + if (target == null) + target = Bot.Banished.GetFirstMatchingFaceupCard(card => card.IsCode(CardId.OrcustHarpHorror)); + if (target != null) + { + AI.SelectCard(target); + return true; + } + if(!Bot.HasInHand(CardId.OrcustHarpHorror) && Bot.GetRemainingCount(CardId.OrcustHarpHorror, 2) > 1) + { + AI.SelectCard(CardId.OrcustHarpHorror); + return true; + } + } + return false; + } + + private bool EagleBoosterEffect() + { + if (Duel.LastChainPlayer != 1) + return false; + ClientCard target = Bot.GetMonstersInExtraZone().GetFirstMatchingCard( + card => Duel.CurrentChain.Contains(card) || card.IsCode(CardId.KnightmareMermaid)); + if (target != null) + { + AI.SelectCard(target); + return true; + } + return false; + } + + private bool MonsterRepos() + { + if (Card.IsFacedown()) + return true; + return DefaultMonsterRepos(); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/PhantasmExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/PhantasmExecutor.cs new file mode 100644 index 0000000..8d0ada7 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/PhantasmExecutor.cs @@ -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 material_list = new List(); + 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 material_list = new List(); + 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 material_list = new List(); + 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 attackers, IList 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; + } + + + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/PureWindsExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/PureWindsExecutor.cs new file mode 100644 index 0000000..6377667 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/PureWindsExecutor.cs @@ -0,0 +1,1065 @@ +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("PureWinds", "AI_PureWinds")] + // Made by Pluani (AniHelp) and Szefo + class PureWindsExecutor : DefaultExecutor + { + public class CardId + { + public const int SpeedroidTerrortop = 81275020; + public const int WindwitchIceBell = 43722862; + public const int PilicaDescendantOfGusto = 71175527; + public const int SpeedroidTaketomborg = 53932291; + public const int WindaPriestessOfGusto = 54455435; + public const int WindwitchGlassBell = 71007216; + + public const int GustoGulldo = 65277087; + public const int GustoEgul = 91662792; + public const int WindwitchSnowBell = 70117860; + public const int SpeedroidRedEyedDice = 16725505; + public const int Raigeki = 12580477; + public const int MonsterReborn = 83764719; + public const int Reasoning = 58577036; + public const int ElShaddollWinda = 94977269; + + public const int QuillPenOfGulldos = 27980138; + public const int CosmicCyclone = 8267140; + public const int EmergencyTeleport = 67723438; + + public const int ForbiddenChalice = 25789292; + public const int SuperTeamBuddyForceUnite = 8608979; + public const int KingsConsonance = 24590232; + public const int GozenMatch = 53334471; + public const int SolemnStrike = 40605147; + public const int SolemnWarning = 84749824; + + public const int MistWurm = 27315304; + public const int CrystalWingSynchroDragon = 50954680; + public const int ClearWingSynchroDragon = 82044279; + public const int WindwitchWinterBell = 14577226; + + public const int StardustChargeWarrior = 64880894; + public const int DaigustoSphreez = 29552709; + public const int DaigustoGulldos = 84766279; + + public const int HiSpeedroidChanbara = 42110604; + public const int OldEntityHastorr = 70913714; + public const int WynnTheWindCharmerVerdant = 30674956; + public const int GreatFly = 90512490; + public const int KnightmareIblee = 10158145; + public const int ChaosMax = 55410871; + public const int SkillDrain = 82732705; + public const int SoulDrain = 73599290; + public const int Rivalry = 90846359; + public const int OnlyOne = 24207889; + } + + List ReposTargets = new List + { CardId.GustoGulldo, + CardId.WindaPriestessOfGusto, + CardId.GustoEgul, + CardId.PilicaDescendantOfGusto, + CardId.DaigustoGulldos + }; + + List taketomborgSpList = new List + { CardId.WindwitchGlassBell, + CardId.GustoGulldo, + CardId.GustoEgul, + CardId.SpeedroidRedEyedDice, + CardId.WindwitchSnowBell, + CardId.SpeedroidTerrortop + }; + + List level1 = new List + { CardId.GustoEgul, + CardId.SpeedroidRedEyedDice, + CardId.WindwitchSnowBell + }; + + List Pilica = new List + { + CardId.ClearWingSynchroDragon, + CardId.WindwitchWinterBell, + CardId.StardustChargeWarrior + }; + + List level3 = new List + { CardId.PilicaDescendantOfGusto, + CardId.WindwitchIceBell, + CardId.SpeedroidTaketomborg + }; + List KeepSynchro = new List + { CardId.DaigustoSphreez, + CardId.CrystalWingSynchroDragon, + CardId.ClearWingSynchroDragon, + CardId.WindwitchWinterBell, + CardId.GreatFly, + CardId.WynnTheWindCharmerVerdant + }; + List KeepSynchro2 = new List + { + CardId.CrystalWingSynchroDragon, + CardId.DaigustoSphreez, + CardId.ClearWingSynchroDragon, + CardId.WindwitchWinterBell + }; + List reborn = new List + { CardId.ClearWingSynchroDragon, + CardId.DaigustoSphreez, + CardId.WindwitchWinterBell, + CardId.PilicaDescendantOfGusto, + CardId.OldEntityHastorr, + CardId.HiSpeedroidChanbara, + CardId.DaigustoGulldos + }; + List Gulldosulist = new List + { CardId.CrystalWingSynchroDragon, + CardId.MistWurm, + CardId.ClearWingSynchroDragon, + CardId.WindwitchWinterBell, + CardId.ClearWingSynchroDragon, + CardId.StardustChargeWarrior + }; + List Gulldosulist2 = new List + { + CardId.SpeedroidTerrortop, + CardId.PilicaDescendantOfGusto, + CardId.WindaPriestessOfGusto, + CardId.WindwitchIceBell, + CardId.SpeedroidTaketomborg, + CardId.OldEntityHastorr, + CardId.HiSpeedroidChanbara, + CardId.DaigustoGulldos, + CardId.DaigustoSphreez + }; + List EgulsuList = new List + { + CardId.SpeedroidTerrortop, + CardId.PilicaDescendantOfGusto, + CardId.WindaPriestessOfGusto, + CardId.WindwitchIceBell, + CardId.SpeedroidTaketomborg, + CardId.OldEntityHastorr, + CardId.HiSpeedroidChanbara, + CardId.DaigustoGulldos, + CardId.DaigustoSphreez, + CardId.StardustChargeWarrior, + CardId.WindwitchWinterBell, + CardId.ClearWingSynchroDragon + }; + List SynchroList = new List + { + CardId.SpeedroidTerrortop, + CardId.PilicaDescendantOfGusto, + CardId.WindwitchIceBell, + CardId.SpeedroidTaketomborg, + CardId.OldEntityHastorr, + CardId.HiSpeedroidChanbara, + CardId.DaigustoGulldos, + CardId.DaigustoSphreez, + CardId.StardustChargeWarrior, + CardId.WindwitchWinterBell, + CardId.ClearWingSynchroDragon, + CardId.CrystalWingSynchroDragon, + CardId.MistWurm + }; + List SynchroFull = new List + { + CardId.OldEntityHastorr, + CardId.HiSpeedroidChanbara, + CardId.DaigustoGulldos, + CardId.DaigustoSphreez, + CardId.StardustChargeWarrior, + CardId.WindwitchWinterBell, + CardId.ClearWingSynchroDragon, + CardId.CrystalWingSynchroDragon, + CardId.MistWurm + }; + List LinkList = new List + { + CardId.WynnTheWindCharmerVerdant, + CardId.GreatFly + }; + List tuner = new List + { + CardId.GustoGulldo, + CardId.GustoEgul, + CardId.SpeedroidRedEyedDice, + CardId.WindwitchGlassBell, + CardId.WindwitchSnowBell + }; + List gusto = new List + { + CardId.GustoGulldo, + CardId.GustoEgul, + CardId.WindaPriestessOfGusto, + CardId.PilicaDescendantOfGusto, + CardId.DaigustoGulldos, + CardId.DaigustoSphreez + }; + List ET = new List + { + CardId.ClearWingSynchroDragon, + CardId.WindwitchWinterBell + }; + + private bool WindwitchGlassBelleff_used; + private bool Summon_used; + private bool Pilica_eff; + private bool plan_A; + + public PureWindsExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + //counter + AddExecutor(ExecutorType.Activate, CardId.SolemnWarning, base.DefaultSolemnWarning); + AddExecutor(ExecutorType.Activate, CardId.ForbiddenChalice, ForbiddenChaliceeff); + AddExecutor(ExecutorType.Activate, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragoneff); + AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, base.DefaultSolemnStrike); + AddExecutor(ExecutorType.Activate, CardId.GustoGulldo, GustoGulldoeff); + AddExecutor(ExecutorType.Activate, CardId.GustoEgul, GustoEguleff); + AddExecutor(ExecutorType.Activate, CardId.WindaPriestessOfGusto, WindaPriestessOfGustoeff); + AddExecutor(ExecutorType.Activate, CardId.PilicaDescendantOfGusto, PilicaDescendantOfGustoeff); + AddExecutor(ExecutorType.Activate, CardId.OldEntityHastorr, OldEntityHastorreff); + AddExecutor(ExecutorType.Activate, CardId.WynnTheWindCharmerVerdant, WynnTheWindCharmerVerdanteff); + AddExecutor(ExecutorType.Activate, CardId.GreatFly, GreatFlyeff); + AddExecutor(ExecutorType.Activate, CardId.QuillPenOfGulldos, QuillPenOfGulldoseff); + AddExecutor(ExecutorType.Activate, CardId.CosmicCyclone, CosmicCycloneeff); + AddExecutor(ExecutorType.Activate, CardId.MonsterReborn, Reborneff); + //plan A + AddExecutor(ExecutorType.Activate, CardId.WindwitchIceBell, WindwitchIceBelleff); + AddExecutor(ExecutorType.Activate, CardId.WindwitchGlassBell, WindwitchGlassBelleff); + AddExecutor(ExecutorType.Activate, CardId.WindwitchSnowBell, WindwitchSnowBellsp); + AddExecutor(ExecutorType.Activate, CardId.StardustChargeWarrior); + AddExecutor(ExecutorType.Activate, CardId.WindwitchWinterBell, WindwitchWinterBelleff); + AddExecutor(ExecutorType.Activate, CardId.ClearWingSynchroDragon, ClearWingSynchroDragoneff); + AddExecutor(ExecutorType.Activate, CardId.DaigustoSphreez, DaigustoSphreezeff); + AddExecutor(ExecutorType.Activate, CardId.SpeedroidTerrortop, SpeedroidTerrortopeff); + AddExecutor(ExecutorType.Activate, CardId.SpeedroidTaketomborg, SpeedroidTaketomborgeff); + AddExecutor(ExecutorType.Activate, CardId.SpeedroidRedEyedDice, SpeedroidRedEyedDiceeff); + AddExecutor(ExecutorType.Activate, CardId.MistWurm, MistWurmeff); + AddExecutor(ExecutorType.Activate, CardId.DaigustoGulldos, DaigustoGulldoseff); + AddExecutor(ExecutorType.SpSummon, CardId.WindwitchWinterBell, WindwitchWinterBellsp); + + AddExecutor(ExecutorType.SpSummon, CardId.CrystalWingSynchroDragon, CrystalWingSynchroDragonsp); + // if fail + AddExecutor(ExecutorType.SpSummon, CardId.ClearWingSynchroDragon, ClearWingSynchroDragonsp); + // if fail + AddExecutor(ExecutorType.SpSummon, CardId.DaigustoSphreez, DaigustoSphreezsp); + // plan B + AddExecutor(ExecutorType.SpSummon, CardId.SpeedroidTerrortop); + AddExecutor(ExecutorType.SpSummon, CardId.SpeedroidTaketomborg, SpeedroidTaketomborgsp); + //summon + AddExecutor(ExecutorType.Summon, CardId.PilicaDescendantOfGusto, PilicaDescendantOfGustosu); + AddExecutor(ExecutorType.Summon, CardId.GustoGulldo, GustoGulldosu); + AddExecutor(ExecutorType.Summon, CardId.GustoEgul, GustoEgulsu); + AddExecutor(ExecutorType.Summon, CardId.WindaPriestessOfGusto, WindaPriestessOfGustosu); + AddExecutor(ExecutorType.Summon, CardId.SpeedroidRedEyedDice, SpeedroidRedEyedDicesu); + //other thing + AddExecutor(ExecutorType.SpSummon, CardId.MistWurm); + AddExecutor(ExecutorType.SpSummon, CardId.DaigustoGulldos); + AddExecutor(ExecutorType.SpSummon, CardId.HiSpeedroidChanbara); + AddExecutor(ExecutorType.SpSummon, CardId.StardustChargeWarrior); + AddExecutor(ExecutorType.SpSummon, CardId.OldEntityHastorr); + AddExecutor(ExecutorType.SpSummon, CardId.GreatFly, GreatFlysp); + AddExecutor(ExecutorType.SpSummon, CardId.WynnTheWindCharmerVerdant, WynnTheWindCharmerVerdantsp); + AddExecutor(ExecutorType.Activate, CardId.Raigeki); + AddExecutor(ExecutorType.Activate, CardId.GozenMatch); + AddExecutor(ExecutorType.Activate, CardId.KingsConsonance, KingsConsonanceeff); + //trap set + AddExecutor(ExecutorType.SpellSet, CardId.KingsConsonance); + AddExecutor(ExecutorType.SpellSet, CardId.SolemnStrike); + AddExecutor(ExecutorType.SpellSet, CardId.SolemnWarning); + AddExecutor(ExecutorType.SpellSet, CardId.ForbiddenChalice); + AddExecutor(ExecutorType.SpellSet, CardId.SuperTeamBuddyForceUnite); + AddExecutor(ExecutorType.SpellSet, CardId.GozenMatch); + AddExecutor(ExecutorType.MonsterSet, CardId.GustoGulldo, gulldoset); + AddExecutor(ExecutorType.MonsterSet, CardId.GustoEgul, egulset); + AddExecutor(ExecutorType.MonsterSet, CardId.WindaPriestessOfGusto, windaset); + AddExecutor(ExecutorType.Summon, CardId.WindwitchGlassBell, WindwitchGlassBellsummonfirst); + AddExecutor(ExecutorType.Summon, CardId.WindwitchGlassBell, WindwitchGlassBellsummon); + AddExecutor(ExecutorType.MonsterSet, CardId.SpeedroidRedEyedDice, SpeedroidRedEyedDiceset); + AddExecutor(ExecutorType.MonsterSet, CardId.WindwitchSnowBell, WindwitchSnowBellset); + AddExecutor(ExecutorType.Activate, CardId.EmergencyTeleport, EmergencyTeleporteff); + AddExecutor(ExecutorType.Activate, CardId.Reasoning, Reasoningeff); + AddExecutor(ExecutorType.Activate, CardId.SuperTeamBuddyForceUnite, SuperTeamBuddyForceUniteeff); + + AddExecutor(ExecutorType.Repos, MonsterRepos); + } + + public override void OnNewTurn() + { + WindwitchGlassBelleff_used = false; + Summon_used = false; + Pilica_eff = false; + plan_A = false; + base.OnNewTurn(); + } + private bool windaset() + { + if (Enemy.HasInMonstersZoneOrInGraveyard(CardId.ChaosMax)) + return false; + return true; + } + private bool egulset() + { + if (Enemy.HasInMonstersZoneOrInGraveyard(CardId.ChaosMax)) + return false; + return true; + } + private bool gulldoset() + { + if (Enemy.HasInMonstersZoneOrInGraveyard(CardId.ChaosMax)) + return false; + return true; + } + + private bool Reasoningeff() + { + if ((Bot.HasInMonstersZone(CardId.CrystalWingSynchroDragon) || + Bot.HasInMonstersZone(CardId.MistWurm)) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + return false; + if (Bot.HasInMonstersZone(level3) && + Bot.HasInMonstersZone(CardId.WindwitchGlassBell) && + Bot.HasInHand(CardId.WindwitchSnowBell)) + return false; + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + private bool KingsConsonanceeff() + { + AI.SelectCard(CardId.CrystalWingSynchroDragon, + CardId.DaigustoSphreez, + CardId.ClearWingSynchroDragon, + CardId.HiSpeedroidChanbara, + CardId.OldEntityHastorr); + return true; + } + private bool Reborneff() + { + if (Bot.HasInGraveyard(KeepSynchro2)) + { + AI.SelectCard(KeepSynchro2); + return true; + } + if (!Util.IsOneEnemyBetter(true)) return false; + if (!Bot.HasInGraveyard(reborn)) + { + return false; + } + AI.SelectCard(reborn); + return true; + } + + private bool SpeedroidRedEyedDiceset() + { + if (Enemy.HasInMonstersZone(CardId.ChaosMax)) + return false; + if ((Bot.GetMonstersInMainZone().Count + Bot.GetMonstersInExtraZone().Count) == 0) + return true; + return false; + } + + private bool WindwitchSnowBellset() + { + if (Enemy.HasInMonstersZone(CardId.ChaosMax)) + return false; + if ((Bot.GetMonstersInMainZone().Count + Bot.GetMonstersInExtraZone().Count) == 0) + return true; + return false; + } + + private bool GreatFlysp() + { + if (Bot.HasInMonstersZone(KeepSynchro)) + return false; + if (Bot.HasInMonstersZone(CardId.HiSpeedroidChanbara)) + return false; + if (Bot.HasInMonstersZone(CardId.WynnTheWindCharmerVerdant)) + return false; + return true; + } + private bool WynnTheWindCharmerVerdantsp() + { + if (Bot.HasInMonstersZone(KeepSynchro)) + return false; + if (Bot.HasInMonstersZone(CardId.HiSpeedroidChanbara)) + return false; + if (Bot.HasInMonstersZone(CardId.GreatFly)) + return false; + return true; + } + private bool MistWurmeff() + { + AI.SelectCard(Util.GetBestEnemyCard(false, true)); + if (Util.GetBestEnemyCard(false, true) != null) + Logger.DebugWriteLine("*************SelectCard= " + Util.GetBestEnemyCard(false, true).Id); + AI.SelectNextCard(Util.GetBestEnemyCard(false, true)); + if (Util.GetBestEnemyCard(false, true) != null) + Logger.DebugWriteLine("*************SelectCard= " + Util.GetBestEnemyCard(false, true).Id); + AI.SelectThirdCard(Util.GetBestEnemyCard(false, true)); + if (Util.GetBestEnemyCard(false, true) != null) + Logger.DebugWriteLine("*************SelectCard= " + Util.GetBestEnemyCard(false, true).Id); + return true; + } + private bool GustoGulldosu() + { + if (Bot.HasInMonstersZone(Gulldosulist) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + { + return false; + } + else if (Bot.HasInMonstersZone(CardId.DaigustoSphreez) || + Bot.HasInHand(CardId.EmergencyTeleport)) + { + Summon_used = true; + return true; + } + else if (Bot.HasInMonstersZone(Gulldosulist2) || Bot.HasInHand(CardId.SpeedroidTaketomborg)) + { + Summon_used = true; + return true; + } + else + { + return false; + } + } + private bool GustoEgulsu() + { + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez) && + !Bot.HasInHand(CardId.GustoGulldo)) + { + Summon_used = true; + return true; + } + else if ((Bot.HasInMonstersZone(CardId.CrystalWingSynchroDragon) || + Bot.HasInMonstersZone(CardId.MistWurm)) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + return false; + else if (Bot.HasInMonstersZone(EgulsuList) || Bot.HasInHand(CardId.SpeedroidTaketomborg)) + { + Summon_used = true; + return true; + } + return false; + } + private bool WindaPriestessOfGustosu() + { + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez) && + !Bot.HasInHand(CardId.GustoGulldo) && + !Bot.HasInHand(CardId.GustoEgul)) + { + Summon_used = true; + return true; + } + else if (Bot.HasInMonstersZone(CardId.GustoGulldo) || + Bot.HasInMonstersZone(CardId.WindwitchGlassBell) || + ((Bot.HasInMonstersZone(level3) || Bot.HasInMonstersZone(CardId.WindaPriestessOfGusto)) && + Bot.HasInMonstersZone(tuner)) || + (Bot.HasInMonstersZone(CardId.OldEntityHastorr) && Bot.HasInMonstersZone(level1)) && + (Util.GetBotAvailZonesFromExtraDeck() >= 1)) + { + Summon_used = true; + return true; + } + return false; + } + private bool SpeedroidRedEyedDicesu() + { + if ((Bot.HasInMonstersZone(CardId.CrystalWingSynchroDragon) || + Bot.HasInMonstersZone(CardId.MistWurm) || + Bot.HasInMonstersZone(CardId.DaigustoSphreez)) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + return false; + else if (Bot.HasInMonstersZone(EgulsuList)) + { + Summon_used = true; + return true; + } + return false; + } + private bool PilicaDescendantOfGustosu() + { + if ((Bot.HasInMonstersZone(CardId.CrystalWingSynchroDragon) || + Bot.HasInMonstersZone(CardId.MistWurm)) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + return false; + else if (Bot.HasInMonstersZone(Pilica) && + !Bot.HasInGraveyard(level1) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + return false; + else if (!Bot.HasInMonstersZoneOrInGraveyard(tuner)) + return false; + else { + Summon_used = true; + return true; + } + } + private bool EmergencyTeleporteff() + { + if ((Bot.HasInMonstersZone(CardId.CrystalWingSynchroDragon) || + Bot.HasInMonstersZone(CardId.MistWurm)) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + return false; + else if (Bot.HasInMonstersZone(level3) && + Bot.HasInMonstersZone(CardId.WindwitchGlassBell) && + Bot.HasInHand(CardId.WindwitchSnowBell)) + return false; + else if (Bot.HasInMonstersZone(tuner) && Bot.HasInMonstersZone(level3)) + return false; + else if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(tuner)) + return false; + else if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(level1) && Bot.HasInMonstersZone(ET)) + return false; + if (Pilica_eff == true) + return false; + AI.SelectCard(CardId.PilicaDescendantOfGusto); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + private bool SpeedroidRedEyedDiceeff() + { + if (Bot.HasInMonstersZone(CardId.SpeedroidTerrortop)) + { + AI.SelectCard(CardId.SpeedroidTerrortop); + AI.SelectNumber(6); + return true; + } + else if (Bot.HasInMonstersZone(CardId.SpeedroidTaketomborg)) + { + AI.SelectCard(CardId.SpeedroidTaketomborg); + AI.SelectNumber(6); + return true; + } + else + { + return false; + } + } + + private bool DaigustoGulldoseff() + { + AI.SelectCard(); + AI.SelectNextCard(Util.GetBestEnemyMonster()); + return true; + } + private bool SpeedroidTaketomborgeff() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if ((Bot.GetRemainingCount(CardId.SpeedroidRedEyedDice, 1) >= 1) && + Bot.HasInMonstersZone(CardId.SpeedroidTerrortop)) + { + AI.SelectCard(CardId.SpeedroidRedEyedDice); + return true; + } + return false; + } + + private bool QuillPenOfGulldoseff() + { + var gyTargets = Bot.Graveyard.Where(x => x.Attribute == (int)CardAttribute.Wind).Select(x => x.Id).ToArray(); + if (gyTargets.Count() >= 2) + { + AI.SelectCard(gyTargets); + if (Bot.HasInSpellZone(CardId.OldEntityHastorr)) + { + AI.SelectNextCard(CardId.OldEntityHastorr); + } + else if (Util.GetProblematicEnemyCard() != null) + { + + AI.SelectNextCard(Util.GetProblematicEnemyCard()); + } + else + { + return false; + } + return true; + } + return false; + } + + private bool WindwitchIceBelleff() + { + if (Enemy.HasInMonstersZone(CardId.ElShaddollWinda)) return false; + if (WindwitchGlassBelleff_used && !Bot.HasInHand(CardId.WindwitchSnowBell)) return false; + //AI.SelectPlace(Zones.z2, 1); + if (Bot.GetRemainingCount(CardId.WindwitchGlassBell, 3) >= 1) + { + AI.SelectCard(CardId.WindwitchGlassBell); + } + else if (Bot.HasInHand(CardId.WindwitchGlassBell)) + { + AI.SelectCard(CardId.WindwitchSnowBell); + } + AI.GetSelectedPosition(); + if (Card.Location == CardLocation.Hand) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + AI.SelectPosition(CardPosition.FaceUpDefence); + } + return true; + } + private bool SpeedroidTaketomborgsp() + { + if (Util.GetBotAvailZonesFromExtraDeck() == 0) + return false; + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + return false; + if (Bot.HasInMonstersZone(taketomborgSpList)) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + return false; + + } + private bool WindwitchGlassBelleff() + { + if ((Bot.HasInHandOrHasInMonstersZone(CardId.WindwitchIceBell) || + Bot.HasInHandOrHasInMonstersZone(CardId.SpeedroidTaketomborg) || + Bot.HasInMonstersZone(CardId.PilicaDescendantOfGusto)) && + !Bot.HasInHand(CardId.WindwitchSnowBell)) + { + AI.SelectCard(CardId.WindwitchSnowBell); + WindwitchGlassBelleff_used = true; + return true; + } + AI.SelectCard(CardId.WindwitchIceBell); + WindwitchGlassBelleff_used = true; + return true; + } + + private bool OldEntityHastorreff() + { + AI.SelectCard(Util.GetBestEnemyMonster()); + return true; + } + + private bool WynnTheWindCharmerVerdanteff() + { + AI.SelectCard(CardId.PilicaDescendantOfGusto, CardId.WindwitchIceBell, CardId.SpeedroidTerrortop, CardId.GustoGulldo, CardId.GustoEgul, CardId.WindaPriestessOfGusto); + return true; + } + private bool SpeedroidTerrortopeff() + { + AI.SelectCard(CardId.SpeedroidTaketomborg, CardId.SpeedroidRedEyedDice); + return true; + } + private bool GreatFlyeff() + { + AI.SelectCard(CardId.PilicaDescendantOfGusto, CardId.WindwitchIceBell, CardId.SpeedroidTerrortop, CardId.GustoGulldo, CardId.GustoEgul, CardId.WindaPriestessOfGusto); + return true; + } + + private bool PilicaDescendantOfGustoeff() + { + AI.SelectCard(CardId.GustoGulldo, CardId.WindwitchGlassBell, CardId.WindwitchSnowBell, CardId.GustoEgul, CardId.SpeedroidRedEyedDice); + Pilica_eff = true; + return true; + } + + private bool SuperTeamBuddyForceUniteeff() + { + foreach (ClientCard card in Duel.CurrentChain) + if (card.IsCode(CardId.SuperTeamBuddyForceUnite)) + return false; + if (Bot.HasInGraveyard(CardId.PilicaDescendantOfGusto) && Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + { + AI.SelectCard(CardId.SuperTeamBuddyForceUnite, CardId.DaigustoSphreez, CardId.PilicaDescendantOfGusto); + AI.SelectPosition(CardPosition.Attack); + return true; + } + + if (Bot.HasInGraveyard(CardId.WindaPriestessOfGusto) && Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + { + AI.SelectCard(CardId.SuperTeamBuddyForceUnite, CardId.DaigustoSphreez, CardId.WindaPriestessOfGusto); + AI.SelectPosition(CardPosition.Attack); + return true; + } + + if (Bot.HasInGraveyard(CardId.DaigustoSphreez) && Bot.HasInMonstersZone(CardId.PilicaDescendantOfGusto)) + { + AI.SelectCard(CardId.SuperTeamBuddyForceUnite, CardId.PilicaDescendantOfGusto, CardId.DaigustoSphreez); + AI.SelectPosition(CardPosition.Attack); + return true; + } + + if (Bot.HasInGraveyard(CardId.DaigustoSphreez) && Bot.HasInMonstersZone(CardId.WindaPriestessOfGusto)) + { + AI.SelectCard(CardId.SuperTeamBuddyForceUnite, CardId.WindaPriestessOfGusto, CardId.DaigustoSphreez); + AI.SelectPosition(CardPosition.Attack); + return true; + } + if (Bot.HasInGraveyard(CardId.DaigustoGulldos) && Bot.HasInMonstersZone(CardId.WindaPriestessOfGusto)) + { + AI.SelectCard(CardId.SuperTeamBuddyForceUnite, CardId.WindaPriestessOfGusto, CardId.DaigustoGulldos); + AI.SelectPosition(CardPosition.Attack); + return true; + } + if (Bot.HasInGraveyard(CardId.DaigustoGulldos) && Bot.HasInMonstersZone(CardId.PilicaDescendantOfGusto)) + { + AI.SelectCard(CardId.SuperTeamBuddyForceUnite, CardId.DaigustoGulldos, CardId.PilicaDescendantOfGusto); + AI.SelectPosition(CardPosition.Attack); + return true; + } + if (Bot.HasInGraveyard(CardId.DaigustoSphreez) && Bot.HasInMonstersZone(CardId.DaigustoGulldos)) + { + AI.SelectCard(CardId.DaigustoGulldos, CardId.DaigustoSphreez); + AI.SelectPosition(CardPosition.Attack); + return true; + } + if (Bot.HasInGraveyard(CardId.CrystalWingSynchroDragon)) + { + AI.SelectCard(CardId.CrystalWingSynchroDragon); + AI.SelectPosition(CardPosition.Attack); + return true; + } + if (Bot.HasInGraveyard(CardId.CrystalWingSynchroDragon)) + { + AI.SelectCard(CardId.ClearWingSynchroDragon); + AI.SelectPosition(CardPosition.Attack); + return true; + } + if (Bot.HasInGraveyard(SynchroList)) + { + AI.SelectCard(SynchroList); + AI.SelectPosition(CardPosition.Attack); + return true; + } + if (Bot.HasInGraveyard(CardId.PilicaDescendantOfGusto) && Bot.HasInMonstersZone(CardId.WindaPriestessOfGusto)) + { + AI.SelectCard(CardId.WindaPriestessOfGusto, CardId.PilicaDescendantOfGusto); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + if (Util.GetBotAvailZonesFromExtraDeck() >= 1) + { + if ((Bot.HasInMonstersZone(CardId.SpeedroidTerrortop) || + Bot.HasInMonstersZone(CardId.SpeedroidRedEyedDice) || + Bot.HasInMonstersZone(CardId.HiSpeedroidChanbara)) && + !Bot.HasInHand(CardId.SpeedroidTaketomborg)) + { + AI.SelectCard(CardId.SpeedroidRedEyedDice, CardId.SpeedroidTerrortop, CardId.SpeedroidTaketomborg); + return true; + } + if ((Bot.HasInMonstersZone(CardId.SpeedroidTerrortop) || + Bot.HasInMonstersZone(CardId.SpeedroidRedEyedDice) || + Bot.HasInMonstersZone(CardId.HiSpeedroidChanbara)) && + Bot.HasInHand(CardId.SpeedroidTaketomborg)) + return false; + } + if (Bot.HasInGraveyard(CardId.SuperTeamBuddyForceUnite)) + { + AI.SelectCard(CardId.SuperTeamBuddyForceUnite); + return true; + } + return false; + } + + private bool WindwitchSnowBellsp() + { + if ((Bot.HasInMonstersZone(CardId.CrystalWingSynchroDragon) || + Bot.HasInMonstersZone(CardId.DaigustoSphreez) || + Bot.HasInMonstersZone(CardId.MistWurm)) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + return false; + if (Bot.HasInMonstersZone(level3) && + Bot.HasInMonstersZone(CardId.WindwitchGlassBell) && + Bot.HasInMonstersZone(level1)) + return false; + if ((Bot.HasInMonstersZone(CardId.ClearWingSynchroDragon) || + Bot.HasInMonstersZone(CardId.WindwitchWinterBell)) && + Bot.HasInMonstersZone(CardId.WindwitchSnowBell) && + (Util.GetBotAvailZonesFromExtraDeck() == 0)) + return false; + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + private bool DaigustoSphreezsp() + { + //AI.SelectPlace(Zones.z5, Zones.ExtraMonsterZones); + AI.SelectCard(CardId.WindwitchSnowBell, CardId.PilicaDescendantOfGusto, CardId.WindaPriestessOfGusto); + AI.SelectCard(CardId.SpeedroidRedEyedDice, CardId.PilicaDescendantOfGusto, CardId.WindaPriestessOfGusto); + AI.SelectCard(CardId.GustoGulldo, CardId.PilicaDescendantOfGusto); + AI.SelectCard(CardId.WindwitchSnowBell, CardId.DaigustoGulldos); + AI.SelectCard(CardId.SpeedroidRedEyedDice, CardId.DaigustoGulldos); + AI.SelectPosition(CardPosition.Attack); + return true; + } + private bool DaigustoSphreezeff() + { + if (Summon_used == true) + { + AI.SelectCard(CardId.PilicaDescendantOfGusto, CardId.GustoGulldo, CardId.GustoEgul, CardId.WindaPriestessOfGusto); + return true; + } + AI.SelectCard(CardId.GustoGulldo, CardId.PilicaDescendantOfGusto, CardId.GustoEgul, CardId.WindaPriestessOfGusto); + return true; + } + private bool WindwitchWinterBelleff() + { + AI.SelectCard(CardId.WindwitchGlassBell); + return true; + } + + private bool WindwitchWinterBellsp() + { + if (Bot.HasInHandOrInSpellZone(CardId.SuperTeamBuddyForceUnite) || + Bot.HasInHandOrInSpellZone(CardId.MonsterReborn)) + return false; + if (Bot.HasInMonstersZone(CardId.WindwitchIceBell) && + Bot.HasInMonstersZone(CardId.WindwitchGlassBell) && + Bot.HasInMonstersZone(CardId.WindwitchSnowBell)) + { + //AI.SelectPlace(Zones.z5, Zones.ExtraMonsterZones); + AI.GetSelectedPosition(); + AI.SelectPosition(CardPosition.FaceUpAttack); + AI.SelectCard(CardId.WindwitchIceBell, CardId.WindwitchGlassBell); + return true; + } + + return false; + } + + private bool ClearWingSynchroDragonsp() + { + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + return false; + AI.SelectPosition(CardPosition.Attack); + return true; + } + + private bool ClearWingSynchroDragoneff() + { + if (Duel.LastChainPlayer == 1) + { + return true; + } + return false; + } + private bool CrystalWingSynchroDragonsp() + { + if (Bot.HasInMonstersZone(CardId.WindwitchSnowBell) && Bot.HasInMonstersZone(CardId.WindwitchWinterBell)) + { + //AI.SelectPlace(Zones.z5, Zones.ExtraMonsterZones); + plan_A = true; + } + else if (Bot.HasInMonstersZone(CardId.WindwitchSnowBell) && Bot.HasInMonstersZone(CardId.ClearWingSynchroDragon)) + { + //AI.SelectPlace(Zones.z5, Zones.ExtraMonsterZones); + plan_A = true; + } + return true; + } + private bool ForbiddenChaliceeff() + { + if (Duel.LastChainPlayer == 1) + { + var target = Util.GetProblematicEnemyMonster(0, true); + if (target != null && !target.IsShouldNotBeSpellTrapTarget() && Duel.CurrentChain.Contains(target)) + { + AI.SelectCard(target); + return true; + } + } + return false; + } + private bool CosmicCycloneeff() + { + foreach (ClientCard card in Duel.CurrentChain) + if (card.IsCode(_CardId.CosmicCyclone)) + return false; + if ((Enemy.HasInSpellZone(CardId.SkillDrain) || + Enemy.HasInSpellZone(CardId.Rivalry) || + Enemy.HasInSpellZone(CardId.OnlyOne)) && + (Bot.LifePoints > 1000)) + { + AI.SelectCard(CardId.SkillDrain, CardId.SoulDrain, CardId.Rivalry, CardId.OnlyOne); + return true; + } + if (Bot.HasInSpellZone(CardId.OldEntityHastorr) && (Bot.LifePoints > 1000)) + { + AI.SelectCard(CardId.OldEntityHastorr); + return true; + } + return (Bot.LifePoints > 1000) && DefaultMysticalSpaceTyphoon(); + } + private bool CrystalWingSynchroDragoneff() + { + if (Duel.LastChainPlayer == 1) + { + return true; + } + return false; + } + private bool GustoGulldoeff() + { + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + { + AI.SelectCard(CardId.GustoEgul, CardId.WindaPriestessOfGusto); + AI.SelectPosition(CardPosition.Attack); + return true; + } + AI.SelectCard(CardId.GustoEgul, CardId.WindaPriestessOfGusto); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + private bool GustoEguleff() + { + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + { + AI.SelectCard(CardId.WindaPriestessOfGusto, CardId.PilicaDescendantOfGusto); + AI.SelectPosition(CardPosition.Attack); + return true; + } + AI.SelectCard(CardId.WindaPriestessOfGusto, CardId.PilicaDescendantOfGusto); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + private bool WindaPriestessOfGustoeff() + { + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + { + AI.SelectCard(CardId.GustoGulldo, CardId.GustoEgul); + AI.SelectPosition(CardPosition.Attack); + } + AI.SelectCard(CardId.GustoGulldo, CardId.GustoEgul); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + private bool WindwitchGlassBellsummonfirst() + { + if (Bot.HasInHand(CardId.PilicaDescendantOfGusto) && + (Bot.HasInGraveyard(CardId.GustoGulldo) || + Bot.HasInGraveyard(CardId.GustoEgul) || + Bot.HasInGraveyard(CardId.WindwitchGlassBell) || + Bot.HasInGraveyard(CardId.SpeedroidRedEyedDice))) + { + return false; + } + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + return false; + else if (!Bot.HasInHand(CardId.WindwitchIceBell)) + { + Summon_used = true; + return true; + } + return false; + } + private bool WindwitchGlassBellsummon() + { + if (!plan_A && (Bot.HasInGraveyard(CardId.WindwitchGlassBell) || Bot.HasInMonstersZone(CardId.WindwitchGlassBell))) + return false; + //AI.SelectPlace(Zones.z2, 1); + if (Bot.HasInMonstersZone(CardId.WindwitchIceBell) && + !Bot.HasInMonstersZone(CardId.WindwitchGlassBell)) + { + Summon_used = true; + return true; + } + if (WindwitchGlassBelleff_used) return false; + return false; + } + + public bool MonsterRepos() + { + if (Card.IsCode(CardId.CrystalWingSynchroDragon) || Card.IsCode(CardId.DaigustoSphreez)) + return (!Card.HasPosition(CardPosition.Attack)); + if (Card.IsCode(SynchroFull)) + { + if (Card.IsFacedown() || Card.IsDefense()) + return true; + } + if (Bot.HasInMonstersZone(CardId.DaigustoSphreez)) + { + if (Card.IsCode(gusto)) + { + if (Card.IsFacedown() || Card.IsDefense()) + { + return true; + } + else + { + return false; + } + } + } + + if ((Util.GetBotAvailZonesFromExtraDeck() >= 1) && + ((Bot.GetMonsterCount() - Bot.GetMonstersInExtraZone().Count) >= 2)) + { + if (Bot.HasInMonstersZone(tuner) && + (Bot.HasInMonstersZone(level3) || + Bot.HasInMonstersZone(CardId.WindwitchGlassBell))) + { + if (Card.IsFacedown()) + return true; + } + if (Bot.HasInMonstersZone(CardId.WindaPriestessOfGusto) && + (Bot.HasInMonstersZone(CardId.GustoGulldo) || + Bot.HasInMonstersZone(CardId.WindwitchGlassBell))) + { + if (Card.IsFacedown()) + return true; + } + if (((Bot.GetMonsterCount() - Bot.GetMonstersInExtraZone().Count) >= 3) && + Bot.HasInMonstersZone(level1) && + (Bot.HasInMonstersZone(CardId.WindaPriestessOfGusto) || + Bot.HasInMonstersZone(level3))) + { + if (Card.IsFacedown()) + return true; + } + if (((Bot.GetMonsterCount() - Bot.GetMonstersInExtraZone().Count) >= 2) && + (Bot.HasInMonstersZone(CardId.GustoGulldo) || Bot.HasInMonstersZone(CardId.WindwitchGlassBell)) && + Bot.HasInMonstersZone(CardId.WindaPriestessOfGusto)) + { + if (Card.IsFacedown()) + return true; + } + } + + if (Card.IsFacedown()) + return false; + return base.DefaultMonsterRepos(); + } + public override bool OnSelectHand() + { + // go first + return true; + } + public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + if (attacker.IsCode(CardId.CrystalWingSynchroDragon)) + { + if (defender.Level >= 5) + attacker.RealPower = attacker.Attack + defender.Attack; + return true; + } + else if (attacker.IsCode(CardId.DaigustoSphreez)) + { + attacker.RealPower = attacker.Attack + defender.Attack + defender.Defense; + return true; + } + else if (Bot.HasInMonstersZone(CardId.DaigustoSphreez) && + attacker.IsCode(CardId.DaigustoSphreez, CardId.GustoGulldo, CardId.GustoEgul, CardId.WindaPriestessOfGusto, CardId.PilicaDescendantOfGusto, CardId.DaigustoGulldos)) + { + attacker.RealPower = attacker.Attack + defender.Attack + defender.Defense; + return true; + } + return base.OnPreBattleBetween(attacker, defender); + } + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/QliphortExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/QliphortExecutor.cs new file mode 100644 index 0000000..483d2dc --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/QliphortExecutor.cs @@ -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 LowScaleCards = new[] + { + CardId.Stealth, + CardId.Carrier + }; + IList 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 OnSelectPendulumSummon(IList cards, int max) + { + Logger.DebugWriteLine("OnSelectPendulumSummon"); + // select the last cards + + IList selected = new List(); + 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; + } + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RainbowExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RainbowExecutor.cs new file mode 100644 index 0000000..03de70b --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RainbowExecutor.cs @@ -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 OnSelectXyzMaterial(IList cards, int min, int max) + { + // select cards with same name (summoned by rescue rabbit) + Logger.DebugWriteLine("OnSelectXyzMaterial " + cards.Count + " " + min + " " + max); + IList result = new List(); + 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 spells = Enemy.GetSpells(); + foreach (ClientCard spell in spells) + { + if (spell.HasType(CardType.Pendulum) && !spell.Equals(target2)) + { + target1 = spell; + break; + } + } + List 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); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/Rank5Executor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/Rank5Executor.cs new file mode 100644 index 0000000..f3c7217 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/Rank5Executor.cs @@ -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 OnSelectXyzMaterial(IList cards, int min, int max) + { + IList 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; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushDinocarriageDynarmixExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushDinocarriageDynarmixExecutor.cs new file mode 100644 index 0000000..c1f64a2 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushDinocarriageDynarmixExecutor.cs @@ -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 targets = new List(); + 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 HintMsgForEnemy = new List + { + HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck, + HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Disable + }; + private List HintMsgForMaxSelect = new List + { + HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.AddToHand, HintMsg.ToDeck, HintMsg.Destroy + }; + + public override IList OnSelectCard(IList _cards, int min, int max, int hint, bool cancelable) + { + if (Duel.Phase == DuelPhase.BattleStart) + return null; + if (AI.HaveSelectedCards()) + return null; + + IList selected = new List(); + IList cards = new List(_cards); + if (max > cards.Count) + max = cards.Count; + + if (HintMsgForEnemy.Contains(hint)) + { + IList 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 spells = Enemy.GetSpells(); List 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; + } + + + } +} + + + + + diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushMokeyMokeyExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushMokeyMokeyExecutor.cs new file mode 100644 index 0000000..edf5207 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushMokeyMokeyExecutor.cs @@ -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 HintMsgForEnemy = new List + { + HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck, + HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Disable + }; + private List HintMsgForMaxSelect = new List + { + HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.AddToHand, HintMsg.ToDeck, HintMsg.Destroy + }; + + public override IList OnSelectCard(IList _cards, int min, int max, int hint, bool cancelable) + { + if (Duel.Phase == DuelPhase.BattleStart) + return null; + if (AI.HaveSelectedCards()) + return null; + + IList selected = new List(); + IList cards = new List(_cards); + if (max > cards.Count) + max = cards.Count; + + if (HintMsgForEnemy.Contains(hint)) + { + IList 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 targets = new List(); + 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; + } + + + + + } +} + + + + + diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushMokeyMokeyKingExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushMokeyMokeyKingExecutor.cs new file mode 100644 index 0000000..1f01ecf --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RushDuel/RushMokeyMokeyKingExecutor.cs @@ -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 HintMsgForEnemy = new List + { + HintMsg.Release, HintMsg.Destroy, HintMsg.Remove, HintMsg.ToGrave, HintMsg.ReturnToHand, HintMsg.ToDeck, + HintMsg.FusionMaterial, HintMsg.SynchroMaterial, HintMsg.XyzMaterial, HintMsg.LinkMaterial, HintMsg.Disable + }; + private List HintMsgForMaxSelect = new List + { + HintMsg.SpSummon, HintMsg.ToGrave, HintMsg.AddToHand, HintMsg.ToDeck, HintMsg.Destroy + }; + + public override IList OnSelectCard(IList _cards, int min, int max, int hint, bool cancelable) + { + if (Duel.Phase == DuelPhase.BattleStart) + return null; + if (AI.HaveSelectedCards()) + return null; + + IList selected = new List(); + IList cards = new List(_cards); + if (max > cards.Count) + max = cards.Count; + + if (HintMsgForEnemy.Contains(hint)) + { + IList 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 targets = new List(); + 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; + } + + + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RyzealExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RyzealExecutor.cs new file mode 100644 index 0000000..8dc0dcf --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/RyzealExecutor.cs @@ -0,0 +1,4129 @@ +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using System.Linq; +using System; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Ryzeal", "AI_Ryzeal")] + public class RyzealExecutor : DefaultExecutor + { + public class CardId + { + public const int IceRyzeal = 8633261; + public const int ThodeRyzeal = 35844557; + public const int NodeRyzeal = 72238166; + public const int ExRyzeal = 34022970; + // _CardId.MulcharmyFuwalos; + // _CardId.MulcharmyPurulia; + // _CardId.MulcharmyNyalus; + // _CardId.AshBlossom; + // _CardId.GhostOgreAndSnowRabbit; + // _CardId.MaxxC; + // _CardId.LockBird; + // _CardId.EffectVeiler; + + public const int SeventhTachyon = 7477101; + public const int TripleTacticsTalent = 25311006; + // _CardId.PotOfDesires; + public const int Bonfire = 85106525; + // _CardId.CalledByTheGrave; + public const int RyzealPlugIn = 60394026; + // _CardId.CrossoutDesignator; + public const int RyzealCross = 6798031; + + // _CardId.InfiniteImpermanence = 10045474; + + public const int MereologicAggregator = 9940036; + public const int RyzealDeadnader = 34909328; + public const int Number104Masquerade = 2061963; + public const int RyzealDuodrive = 7511613; + public const int TwinsOfTheEclipse = 45852939; + public const int FullArmoredUtopicRayLancer = 1269512; + public const int TornadoDragon = 6983839; + // _CardId.Number41BagooskatheTerriblyTiredTapir + // _CardId.EvilswarmExcitonKnight + public const int StarliegePhotonBlastDragon = 16643334; + public const int AbyssDweller = 21044178; + public const int Number60DugaresTheTimeless = 66011101; + public const int DonnerDaggerFurHire = 8728498; + } + + public RyzealExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // counter + AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, CalledbytheGraveActivate); + AddExecutor(ExecutorType.Activate, _CardId.CrossoutDesignator, CrossoutDesignatorActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, _CardId.EffectVeiler, EffectVeilerActivate); + AddExecutor(ExecutorType.Activate, _CardId.GhostOgreAndSnowRabbit, GhostOgreAndSnowRabbitActivate); + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossomActivate); + + AddExecutor(ExecutorType.Activate, CardId.RyzealCross, RyzealCrossActivateCard); + AddExecutor(ExecutorType.Activate, _CardId.EvilswarmExcitonKnight, EvilswarmExcitonKnightActivate); + AddExecutor(ExecutorType.Activate, CardId.RyzealDeadnader, RyzealDeadnaderActivate); + AddExecutor(ExecutorType.Activate, CardId.RyzealDuodrive, RyzealDuodriveActivate); + AddExecutor(ExecutorType.Activate, CardId.TwinsOfTheEclipse, TwinsOfTheEclipseActivate); + AddExecutor(ExecutorType.Activate, CardId.AbyssDweller, AbyssDwellerActivate); + AddExecutor(ExecutorType.Activate, CardId.TornadoDragon, TornadoDragonActivate); + + // hand effect + AddExecutor(ExecutorType.Activate, _CardId.LockBird, LockBirdActivate); + AddExecutor(ExecutorType.Activate, _CardId.MulcharmyPurulia, MulcharmyPuruliaActivate); + AddExecutor(ExecutorType.Activate, _CardId.MulcharmyNyalus, MulcharmyNyalusActivate); + AddExecutor(ExecutorType.Activate, _CardId.MulcharmyFuwalos, MulcharmyFuwalosActivate); + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + + // pre-action activate + AddExecutor(ExecutorType.Activate, CardId.Bonfire, BonfireActivate); + AddExecutor(ExecutorType.Activate, CardId.DonnerDaggerFurHire, DonnerDaggerFurHireActivate); + AddExecutor(ExecutorType.Activate, CardId.Number60DugaresTheTimeless, Number60DugaresTheTimelessActivate); + AddExecutor(ExecutorType.Activate, CardId.TripleTacticsTalent, TripleTacticsTalentActivate); + AddExecutor(ExecutorType.Activate, CardId.Bonfire, BonfireActivateToSearchNecessary); + AddExecutor(ExecutorType.Activate, CardId.SeventhTachyon, SeventhTachyonActivate); + + AddExecutor(ExecutorType.Repos, ChangePositionFirst); + + // xyz summon + AddExecutor(ExecutorType.SpSummon, _CardId.EvilswarmExcitonKnight, EvilswarmExcitonKnightSpSummon); + AddExecutor(ExecutorType.SpSummon, LessSpSummonExtra); + AddExecutor(ExecutorType.SpSummon, CardId.RyzealDuodrive, FirstRyzealDuodriveSpSummon); + AddExecutor(ExecutorType.SpSummon, SecondXyzSummon); + AddExecutor(ExecutorType.SpSummon, CardId.TwinsOfTheEclipse, TwinsOfTheEclipseSpSummon); + AddExecutor(ExecutorType.SpSummon, FinalXyzSummon); + AddExecutor(ExecutorType.SpSummon, CardId.DonnerDaggerFurHire, DonnerDaggerFurHireSpSummon); + + AddExecutor(ExecutorType.Activate, _CardId.PotOfDesires, PotOfDesireActivateForContinue); + + AddExecutor(ExecutorType.Activate, CardId.RyzealPlugIn, RyzealPlugInActivateFirst); + AddExecutor(ExecutorType.Activate, CardId.NodeRyzeal, NodeRyzealActivateFirst); + AddExecutor(ExecutorType.Activate, CardId.RyzealCross, RyzealCrossActivateRecycleFirst); + + // summon/spsummon + AddExecutor(ExecutorType.SpSummon, CardId.IceRyzeal, IceRyzealSpSummonFirst); + AddExecutor(ExecutorType.SpSummon, CardId.NodeRyzeal, NodeRyzealSpSummonFirst); + + AddExecutor(ExecutorType.Summon, CardId.ExRyzeal, ExRyzealSummon); + AddExecutor(ExecutorType.SpSummon, CardId.ExRyzeal, ExRyzealSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.ThodeRyzeal, ThodeRyzealSpSummon); + AddExecutor(ExecutorType.Summon, CardId.IceRyzeal, IceRyzealSummon); + AddExecutor(ExecutorType.SpSummon, CardId.ExRyzeal, ExRyzealSpSummonLater); + AddExecutor(ExecutorType.Summon, CardId.ThodeRyzeal, ThodeRyzealSummon); + AddExecutor(ExecutorType.SpSummon, CardId.NodeRyzeal, NodeRyzealSpSummon); + AddExecutor(ExecutorType.Summon, Level4Summon); + + AddExecutor(ExecutorType.Activate, CardId.NodeRyzeal, NodeRyzealActivate); + AddExecutor(ExecutorType.Activate, CardId.RyzealPlugIn, RyzealPlugInActivate); + AddExecutor(ExecutorType.SpSummon, CardId.IceRyzeal, IceRyzealSpSummon); + + // activate + AddExecutor(ExecutorType.Activate, CardId.MereologicAggregator, MereologicAggregatorActivateFirst); + AddExecutor(ExecutorType.Activate, CardId.IceRyzeal, IceRyzealActivate); + AddExecutor(ExecutorType.Activate, CardId.ThodeRyzeal, ThodeRyzealActivate); + AddExecutor(ExecutorType.Activate, CardId.ExRyzeal, ExRyzealActivate); + AddExecutor(ExecutorType.Activate, CardId.MereologicAggregator, MereologicAggregatorActivateLater); + + // after summon + AddExecutor(ExecutorType.Activate, CardId.RyzealCross, RyzealCrossActivateRecycleLater); + AddExecutor(ExecutorType.Activate, _CardId.PotOfDesires, PotOfDesiresActivate); + + AddExecutor(ExecutorType.Repos, DefaultMonsterRepos); + AddExecutor(ExecutorType.SpellSet, SpellSetCheck); + + } + + const int attrbuteLightDark = (int)CardAttribute.Light | (int)CardAttribute.Dark; + const int SetcodeTimeLord = 0x4a; + const int SetcodeAtlantean = 0x77; + const int SetcodeInfernoid = 0xbb; + const int SetcodeMajespecter = 0xd0; + const int SetcodePhantomKnight = 0x10db; + const int SetcodeSkyStriker = 0x115; + const int SetcodeOrcust = 0x11b; + const int SetcodeSangen = 0x1a9; + const int SetcodeTenpaiDragon = 0x1aa; + const int SetcodeBranded = 0x15d; + const int SetcodeFloowandereeze = 0x16d; + const int SetcodeLabrynth = 0x17e; + const int SetcodeTearlaments = 0x181; + const int SetcodeHorus = 0x19d; + const int SetcodeRyzeal = 0x1be; + const int hintTimingMainEnd = 0x4; + List NotToNegateIdList = new List + { + 58699500, 20343502, 25451383, 19403423 + }; + List AlbazFusionList = new List + { + 1906812, 38811586, 41373230, 44146295, 51409648, 51409648, 87746184 + }; + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.IceRyzeal, CardId.ThodeRyzeal, CardId.ExRyzeal, _CardId.AshBlossom, _CardId.EffectVeiler, CardId.SeventhTachyon, + _CardId.InfiniteImpermanence}}, + {2, new List { _CardId.MulcharmyFuwalos, _CardId.GhostOgreAndSnowRabbit, _CardId.MaxxC, _CardId.PotOfDesires, _CardId.CalledByTheGrave }}, + {1, new List { CardId.NodeRyzeal, _CardId.MulcharmyPurulia, _CardId.MulcharmyNyalus, _CardId.LockBird, CardId.TripleTacticsTalent, + CardId.Bonfire, CardId.RyzealPlugIn, _CardId.CrossoutDesignator, CardId.RyzealCross}} + }; + List NotToDestroySpellTrap = new List { 50005218, 6767771 }; + List targetNegateIdList = new List { + _CardId.EffectVeiler, _CardId.InfiniteImpermanence, _CardId.GhostMournerMoonlitChill, _CardId.BreakthroughSkill, CardId.MereologicAggregator, 74003290, 67037924, + 9753964, 66192538, 23204029, 73445448, 35103106, 30286474, 45002991, 5795980, 38511382, 53742162, 30430448 + }; + List NeedIceToSolveIdList = new List { 80978111, 87170768 }; + List currentCanActivateEffect = new List(); + + int maxSummonCount = 1; + int summonCount = 1; + bool enemyActivateMaxxC = false; + bool enemyActivatePurulia = false; + bool enemyActivateFuwalos = false; + bool enemyActivateNyalus = false; + bool lockBirdSolved = false; + int dimensionShifterCount = 0; + bool botActivateMulcharmy = false; + bool botSolvingCross = false; + List CheckSetcodeList = new List { SetcodePhantomKnight, SetcodeOrcust, SetcodeAtlantean, SetcodeRyzeal, SetcodeTenpaiDragon, SetcodeSangen, + SetcodeInfernoid, SetcodeSkyStriker, SetcodeLabrynth, SetcodeTearlaments }; + List CheckBotSolvedList = new List { _CardId.MaxxC, _CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, _CardId.MulcharmyNyalus, + CardId.AbyssDweller, _CardId.EvilswarmExcitonKnight, CardId.RyzealPlugIn }; + + bool enemyActivateInfiniteImpermanenceFromHand = false; + ClientCard deadnaderDestroySelf = null; + + List infiniteImpermanenceList = new List(); + List currentNegateCardList = new List(); + List currentDestroyCardList = new List(); + List activatedCardIdList = new List(); + List spSummonedCardIdList = new List(); + List botSolvedCardIdList = new List(); + List enemyPlaceThisTurn = new List(); + List summonThisTurn = new List(); + + List hardToDestroyCardList = new List(); + List cannotDestroyCardList = new List(); + HashSet enemyDeckTypeRecord = new HashSet(); + + ///

+ /// Shuffle List and return a random-order card list + /// + public List ShuffleList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(result.Count); + int nextIndex = (index + Program.Rand.Next(result.Count - 1)) % result.Count; + T tempCard = result[index]; + result[index] = result[nextIndex]; + result[nextIndex] = tempCard; + } + return result; + } + + public bool CheckCanBeTargeted(ClientCard card, bool canBeTarget, CardType selfType) + { + if (card == null) return true; + if (canBeTarget) + { + if (card.IsShouldNotBeTarget()) return false; + if (((int)selfType & (int)CardType.Monster) > 0 && card.IsShouldNotBeMonsterTarget()) return false; + if (((int)selfType & (int)CardType.Spell) > 0 && card.IsShouldNotBeSpellTrapTarget()) return false; + if (((int)selfType & (int)CardType.Trap) > 0 + && (card.IsShouldNotBeSpellTrapTarget() && !card.IsDisabled())) return false; + } + return true; + } + + /// + /// Check remain cards in deck + /// + /// Card's ID + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + + public int CheckRemainInDeck(params int[] ids) + { + int sum = 0; + foreach (int id in ids) + { + sum += CheckRemainInDeck(id); + } + return sum; + } + + public bool CheckWhetherHaveFinalMonster() + { + foreach (ClientCard monster in Bot.MonsterZone) + { + if (monster == null) continue; + if (monster.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir) && monster.IsDefense()) return true; + if (monster.IsCode(CardId.AbyssDweller) && monster.Overlays.Count() > 0) return true; + if (monster.IsCode(CardId.RyzealDeadnader) && monster.Overlays.Count() > 0) return true; + } + + return false; + } + + /// + /// Check whether'll be negated + /// + /// check whether card itself is disabled. + public bool CheckWhetherNegated(bool disablecheck = true, bool toFieldCheck = false, CardType type = 0, bool ignore41 = false) + { + bool isMonster = type == 0 && Card.IsMonster(); + isMonster |= ((int)type & (int)CardType.Monster) != 0; + bool isSpellOrTrap = type == 0 && (Card.IsSpell() || Card.IsTrap()); + isSpellOrTrap |= (((int)type & (int)CardType.Spell) != 0) || (((int)type & (int)CardType.Trap) != 0); + bool isCounter = ((int)type & (int)CardType.Counter) != 0; + if (isSpellOrTrap && toFieldCheck && CheckSpellWillBeNegate(isCounter)) + return true; + if (DefaultCheckWhetherCardIsNegated(Card)) return true; + if (isMonster && (toFieldCheck || Card.Location == CardLocation.MonsterZone)) + { + if ((toFieldCheck && (((int)type & (int)CardType.Link) != 0)) || Card.IsDefense()) + { + if (Enemy.MonsterZone.Any(card => CheckNumber41(card, ignore41)) || Bot.MonsterZone.Any(card => CheckNumber41(card, ignore41))) return true; + } + if (Enemy.HasInSpellZone(_CardId.SkillDrain, true, true)) return true; + } + if (disablecheck) return (Card.Location == CardLocation.MonsterZone || Card.Location == CardLocation.SpellZone) && Card.IsDisabled() && Card.IsFaceup(); + return false; + } + + public bool CheckNumber41(ClientCard card, bool ignoreSelf41 = false) + { + return card != null && card.IsFaceup() && card.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled() + && (!ignoreSelf41 || card.Controller == 0); + } + + /// + /// Whether spell or trap will be negate. If so, return true. + /// + /// is counter trap + /// check target + /// + public bool CheckSpellWillBeNegate(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.NaturiaBeast, 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() && (Enemy.HasInSpellZone(_CardId.RoyalDecreel, true) || Bot.HasInSpellZone(_CardId.RoyalDecreel, true))) return true; + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceList.Contains(selfSeq)) return true; + } + // how to get here? + return false; + } + + /// + /// Check whether last chain card should be disabled. + /// + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + return CheckCardShouldNegate(lastcard); + } + + public bool CheckCardShouldNegate(ClientCard card) + { + if (card == null) return false; + if (card.IsMonster() && card.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (NotToNegateIdList.Contains(card.Id)) return false; + if (card.HasSetcode(_Setcode.Danger) && card.Location == CardLocation.Hand) return false; + if (card.IsMonster() && card.Location == CardLocation.MonsterZone && card.HasPosition(CardPosition.Defence)) + { + if (Enemy.MonsterZone.Any(c => CheckNumber41(c)) || Bot.MonsterZone.Any(c => CheckNumber41(c))) return false; + } + if (DefaultCheckWhetherCardIsNegated(card)) return false; + if (Duel.Player == 1 && card.IsCode(_CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, _CardId.MulcharmyNyalus)) return false; + if (card.IsDisabled()) return false; + + return true; + } + + public bool CheckCardShouldNegate(ChainInfo chainInfo) + { + if (chainInfo == null) return false; + ClientCard card = chainInfo.RelatedCard; + + if (card == null) return false; + if (card.IsMonster() && card.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (NotToNegateIdList.Contains(card.Id)) return false; + if (card.HasSetcode(_Setcode.Danger) && card.Location == CardLocation.Hand) return false; + if (card.IsMonster() && chainInfo.HasLocation(CardLocation.MonsterZone) && chainInfo.HasPosition(CardPosition.Defence)) + { + if (Enemy.MonsterZone.Any(c => CheckNumber41(c)) || Bot.MonsterZone.Any(c => CheckNumber41(c))) return false; + } + if (DefaultCheckWhetherCardIsNegated(card)) return false; + if (Duel.Player == 1 && card.IsCode(_CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, _CardId.MulcharmyNyalus)) return false; + if (card.IsDisabled()) return false; + + return true; + } + + /// + /// Check whether bot is at advantage. + /// + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && (Duel.Player == 0 || Bot.GetMonsterCount() > 0)) return true; + return false; + } + + public bool CheckShouldNoMoreSpSummon() + { + if (CheckAtAdvantage() && enemyActivateMaxxC && !lockBirdSolved && (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2)) + { + return true; + } + return false; + } + + public bool CheckShouldNoMoreSpSummon(CardLocation loc) + { + if (CheckShouldNoMoreSpSummon()) return true; + if (lockBirdSolved || (Duel.Turn > 1 && Duel.Phase < DuelPhase.Main2)) return false; + if (enemyActivatePurulia && (loc & CardLocation.Hand) != 0) return true; + if (enemyActivateFuwalos && (loc & (CardLocation.Deck | CardLocation.Extra)) != 0) return true; + if (enemyActivateNyalus && (loc & (CardLocation.Grave | CardLocation.Removed)) != 0) return true; + + return false; + } + + public bool CheckWhetherCanSummon() + { + return Duel.Player == 0 && Duel.Phase < DuelPhase.End && summonCount > 0; + } + + /// + /// Check whether cards will be removed. If so, do not send cards to grave. + /// + public bool CheckWhetherWillbeRemoved() + { + if (dimensionShifterCount > 0) return true; + List checkIdList = new List { _CardId.BanisheroftheRadiance, _CardId.BanisheroftheLight, _CardId.MacroCosmos, _CardId.DimensionalFissure, + _CardId.KashtiraAriseHeart, _CardId.MaskedHERODarkLaw }; + foreach (int cardid in checkIdList) + { + List fields = new List { Bot, Enemy }; + foreach (ClientField cf in fields) + { + if (cf.HasInMonstersZone(cardid, true, false, true) || cf.HasInSpellZone(cardid, true, true)) + { + return true; + } + } + } + return false; + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + ClientCard floodagateCard = Enemy.GetMonsters().Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsFloodgate() && c.IsFaceup() + && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (floodagateCard != null) return floodagateCard; + + ClientCard dangerCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (dangerCard != null) return dangerCard; + + ClientCard invincibleCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (invincibleCard != null) return invincibleCard; + + ClientCard equippedCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.EquipCards.Count > 0 && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (equippedCard != null) return equippedCard; + + ClientCard enemyExtraMonster = Enemy.MonsterZone.Where(c => c != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && (c.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) || (c.HasType(CardType.Link) && c.LinkCount >= 2)) + && CheckCanBeTargeted(c, canBeTarget, selfType) && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (enemyExtraMonster != null) return enemyExtraMonster; + + ClientCard activatingAlbaz = Enemy.MonsterZone.FirstOrDefault(c => c != null && c.IsCode(68468459) && !c.IsDisabled() + && !currentDestroyCardList.Contains(c) && !currentNegateCardList.Contains(c) && Duel.CurrentChain.Contains(c)); + if (activatingAlbaz != null) return activatingAlbaz; + + if (attack >= 0) + { + if (attack == 0) + attack = Util.GetBestAttack(Bot); + ClientCard betterCard = Enemy.MonsterZone.Where(card => card != null + && card.GetDefensePower() >= attack && card.GetDefensePower() > 0 && card.IsAttack() && CheckCanBeTargeted(card, canBeTarget, selfType) + && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (betterCard != null) return betterCard; + } + return null; + } + + public bool CheckShouldNotIgnore(ClientCard cards, bool ignore = false) + { + return !ignore || (!currentDestroyCardList.Contains(cards) && !currentNegateCardList.Contains(cards)); + } + + public bool CheckCanContinueSummon(bool skipDuodriver = false) + { + bool checkFlag = summonCount > 0 && !activatedCardIdList.Contains(CardId.IceRyzeal) && Bot.HasInHand(CardId.IceRyzeal) + && !DefaultCheckWhetherCardIdIsNegated(CardId.IceRyzeal); + if (Bot.HasInHand(CardId.ThodeRyzeal) && !spSummonedCardIdList.Contains(CardId.ThodeRyzeal) + && !activatedCardIdList.Contains(CardId.ThodeRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.ThodeRyzeal)) + { + checkFlag |= Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal)); + checkFlag |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal)); + } + checkFlag |= !spSummonedCardIdList.Contains(CardId.ExRyzeal) && !activatedCardIdList.Contains(CardId.ExRyzeal) + && Bot.HasInHand(CardId.ExRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.ExRyzeal) && !CheckWhetherWillbeRemoved(); + + checkFlag |= !activatedCardIdList.Contains(CardId.RyzealDuodrive + 1) && Bot.HasInExtra(CardId.RyzealDuodrive) + && !DefaultCheckWhetherCardIdIsNegated(CardId.RyzealDuodrive) && !CheckWhetherNegated(true, true, CardType.Monster) + && summonCount > 0 && Bot.Hand.Count(c => c.Level == 4) > 0 && GetLevel4CountOnField() == 1 && !lockBirdSolved + && !skipDuodriver; + + return checkFlag; + } + + /// + /// check enemy's dangerous card in grave + /// + public List GetDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && (card.HasSetcode(SetcodeOrcust) || card.HasSetcode(SetcodePhantomKnight) || card.HasSetcode(SetcodeHorus))).ToList(); + List dangerMonsterIdList = new List{ + 99937011, 63542003, 9411399, 28954097, 30680659 + }; + result.AddRange(Enemy.Graveyard.GetMatchingCards(card => dangerMonsterIdList.Contains(card.Id))); + return result; + } + + public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreSpells = false, CardType selfType = 0) + { + List resultList = new List(); + + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (floodagateList.Count > 0) resultList.AddRange(floodagateList); + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).ToList(); + if (problemEnemySpellList.Count > 0) resultList.AddRange(ShuffleList(problemEnemySpellList)); + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (dangerList.Count > 0 + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) resultList.AddRange(dangerList); + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (invincibleList.Count > 0) resultList.AddRange(invincibleList); + + List enemyMonsters = Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c)).OrderByDescending(card => card.Attack).ToList(); + if (enemyMonsters.Count > 0) + { + foreach (ClientCard target in enemyMonsters) + { + if ((target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2)) + && !resultList.Contains(target) && CheckCanBeTargeted(target, canBeTarget, selfType) + ) + { + resultList.Add(target); + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() && !currentDestroyCardList.Contains(c) + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous) && CheckCanBeTargeted(c, canBeTarget, selfType) + && !NotToDestroySpellTrap.Contains(c.Id)).ToList(); + if (spells.Count > 0 && !ignoreSpells) resultList.AddRange(ShuffleList(spells)); + + return resultList; + } + + public List GetNormalEnemyTargetList(bool canBeTarget = true, bool ignoreCurrentDestroy = false, CardType selfType = 0, bool forNegate = false) + { + List targetList = GetProblematicEnemyCardList(canBeTarget, selfType: selfType); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) + && (!forNegate || (!card.IsDisabled() && card.HasType(CardType.Effect))) + ).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => + (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && enemyPlaceThisTurn.Contains(card) && card.IsFacedown()).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => + (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && !enemyPlaceThisTurn.Contains(card) && card.IsFacedown()).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetMonsters().Where(card => card.IsFacedown() + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) + && (!forNegate || (!card.IsDisabled() && card.HasType(CardType.Effect))) + ).ToList())); + + return targetList; + } + + public List GetMonsterListForTargetNegate(bool canBeTarget = false, CardType selfType = 0) + { + List resultList = new List(); + if (CheckWhetherNegated()) + { + return resultList; + } + + // negate before used + ClientCard target = Enemy.MonsterZone.FirstOrDefault(card => card?.Data != null + && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && !card.IsShouldNotBeTarget() + && CheckCanBeTargeted(card, canBeTarget, selfType) + && !currentNegateCardList.Contains(card)); + if (target != null) + { + resultList.Add(target); + } + + // negate monster effect on the field + foreach (ClientCard chainingCard in Duel.CurrentChain) + { + if (chainingCard.Location == CardLocation.MonsterZone && chainingCard.Controller == 1 && !chainingCard.IsDisabled() + && CheckCanBeTargeted(chainingCard, canBeTarget, selfType) && !currentNegateCardList.Contains(chainingCard)) + { + if (chainingCard.HasPosition(CardPosition.Defence)) + { + bool have41 = Bot.MonsterZone.Any(c => CheckNumber41(c)) | Enemy.MonsterZone.Any(c => CheckNumber41(c)); + } + resultList.Add(chainingCard); + } + } + + return resultList; + } + + public List GetLevel4OnField(Func filter) + { + return Bot.GetMonsters().Where(c => (filter == null || filter(c)) + && c.IsFaceup() && !c.HasType(CardType.Xyz | CardType.Link) && c.Level == 4).OrderBy(c => c.GetDefensePower()).ToList(); + } + + public int GetLevel4CountOnField() + { + return Bot.GetMonsters().Count(c => c.IsFaceup() && !c.HasType(CardType.Xyz | CardType.Link) && c.Level == 4); + } + + public int GetLevel4FinalCountOnField(bool checkSupport, out bool hasNode) + { + // check whether have 4 monsters for material. + // if not, skip the second xyz monster. + int level4Count = GetLevel4CountOnField(); + if (Bot.HasInHand(CardId.ExRyzeal) && !spSummonedCardIdList.Contains(CardId.ExRyzeal) && !CheckWhetherWillbeRemoved()) + { + if (checkSupport || + (!activatedCardIdList.Contains(CardId.ExRyzeal) && Bot.MonsterZone.All(c => c != null && (c.IsFacedown() || !c.HasType(CardType.Link) && c.Level == 4)))) + { + level4Count++; + } + } + if (Bot.HasInHand(CardId.ThodeRyzeal) && !spSummonedCardIdList.Contains(CardId.ThodeRyzeal)) + { + bool flag = Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal)); + flag |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal)); + if (flag) + { + if (checkSupport || !activatedCardIdList.Contains(CardId.ThodeRyzeal)) + { + level4Count++; + } + } + } + hasNode = Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.IsCode(CardId.NodeRyzeal) && !c.IsDisabled()); + if (Bot.HasInHand(CardId.NodeRyzeal) && !spSummonedCardIdList.Contains(CardId.NodeRyzeal)) + { + bool flag = Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasType(CardType.Xyz)); + flag |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.HasType(CardType.Xyz)); + if (flag) + { + hasNode = true; + level4Count++; + } + } + if (Bot.HasInHand(CardId.RyzealPlugIn) && !CheckWhetherNegated(true, true, CardType.Spell) && checkSupport) + { + bool flag = false; + List graveTargetList = Bot.Graveyard.Where( + c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && !c.HasType(CardType.Xyz) && c.Level == 4).ToList(); + flag |= graveTargetList.Count() > 0; + hasNode |= graveTargetList.Any(c => c.IsCode(CardId.NodeRyzeal)); + + List banishedTargetList = Bot.Banished.Where( + c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && !c.HasType(CardType.Xyz) && c.Level == 4).ToList(); + flag |= banishedTargetList.Count() > 0; + hasNode |= banishedTargetList.Any(c => c.IsCode(CardId.NodeRyzeal)); + + if (flag) level4Count++; + } + hasNode &= !CheckWhetherWillbeRemoved() && !activatedCardIdList.Contains(CardId.NodeRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.NodeRyzeal); + hasNode &= Bot.Graveyard.Any(c => c != null && c.IsMonster() && c.HasSetcode(SetcodeRyzeal) && !c.IsCode(CardId.NodeRyzeal) && c.Level == 4); + if (hasNode) + { + bool flag = Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && !c.HasType(CardType.Xyz) && c.Level == 4 && !c.IsCode(CardId.NodeRyzeal)); + if (flag) + { + if (checkSupport || GetCostFromHandAndField(null, false).Count() > 0) level4Count++; + } + } + if (checkSupport) + { + int checkHandCount = 2; + if (summonCount > 0 && Bot.Hand.Any(c => c.Level == 4 && !c.IsCode(CardId.ExRyzeal, CardId.ThodeRyzeal, CardId.NodeRyzeal))) + { + level4Count++; + checkHandCount++; + } + if (Bot.Hand.Count() >= checkHandCount && Bot.HasInHand(CardId.IceRyzeal) && !spSummonedCardIdList.Contains(CardId.IceRyzeal) && !CheckWhetherWillbeRemoved()) + { + level4Count++; + } + } + + return level4Count; + } + + public List GetCostFromHandAndFieldFirst(ClientCard exceptCard) + { + return Bot.MonsterZone.Where(c => c != null && !c.IsDisabled() && c.IsCode(NeedIceToSolveIdList) && c != exceptCard && !c.HasType(CardType.Token)).ToList(); + } + + public List GetCostFromHandAndField(ClientCard exceptCard, bool sendNotNecessary) + { + List resultList = GetCostFromHandAndFieldFirst(exceptCard); + if (!activatedCardIdList.Contains(CardId.TwinsOfTheEclipse + 1)) + { + List xyzList = Bot.Graveyard.Where(c => c.HasType(CardType.Xyz)).ToList(); + // sending twins + ClientCard twins = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsCode(CardId.TwinsOfTheEclipse) && !resultList.Contains(c)); + if (twins == null) + { + twins = Bot.SpellZone.FirstOrDefault(c => c != null && c.IsCode(CardId.TwinsOfTheEclipse) && !resultList.Contains(c)); + } + if (twins != null) + { + int twinsXyzCount = 0; + foreach (int cardId in twins.Overlays) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null && cardData.HasType(CardType.Xyz)) twinsXyzCount++; + } + bool flag = twinsXyzCount >= 2; + flag |= twinsXyzCount > 0 && xyzList.Count() > 0; + flag |= xyzList.Count() > 1 && xyzList.Count(c => c.IsCanRevive()) > 0; + if (flag) + { + resultList.Add(twins); + } + } + } + + if (Bot.HasInSpellZone(CardId.RyzealCross, true, true)) + { + // sending duodrive because not enough material on field + if (Bot.HasInExtra(CardId.RyzealDuodrive) && !activatedCardIdList.Contains(CardId.RyzealDuodrive + 1) && !lockBirdSolved) + { + bool checkOverlay = true; + ClientCard duoDrive = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsCode(CardId.RyzealDuodrive) && !resultList.Contains(c)); + if (duoDrive == null) + { + checkOverlay = false; + duoDrive = Bot.SpellZone.FirstOrDefault(c => c != null && c.IsCode(CardId.RyzealDuodrive) && !resultList.Contains(c)); + } + if (duoDrive != null) + { + int overlayCount = Bot.MonsterZone.Sum(c => c != null ? c.Overlays.Count() : 0); + if (!checkOverlay || overlayCount < 2) + { + resultList.Add(duoDrive); + } + } + } + // send deadnader with no overlay + if (Bot.HasInExtra(CardId.RyzealDeadnader)) + { + ClientCard deadnader = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsCode(CardId.RyzealDeadnader) && c.Overlays.Count() == 0 && !resultList.Contains(c)); + if (deadnader != null) + { + resultList.Add(deadnader); + } + } + } + + // sending monsters in spell zone + List monstersInSpellZone = Bot.SpellZone.Where(c => c != null && c.Data != null + && c.Data.HasType(CardType.Monster) && !c.Data.HasType(CardType.Pendulum | CardType.Token) && !resultList.Contains(c)).ToList(); + resultList.AddRange(monstersInSpellZone); + + // send enemy monsters + List enemyMonsters = Bot.MonsterZone.Where(c => c != null && !resultList.Contains(c) && c.Owner == 1).ToList(); + resultList.AddRange(enemyMonsters); + + if (sendNotNecessary) + { + // send xyz monster with no material + List xyzMonsterWithNoMaterial = Bot.MonsterZone.Where( + c => c != null && c.HasType(CardType.Xyz) && c.GetDefensePower() < 2500 && c.Overlays.Count() == 0 && !resultList.Contains(c)) + .OrderBy(c => c.GetDefensePower()).ToList(); + resultList.AddRange(xyzMonsterWithNoMaterial); + + // sending unimportant card in hand + List unimportantList = new List { _CardId.MulcharmyNyalus, _CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, CardId.SeventhTachyon }; + resultList.AddRange(Bot.Hand.Where(c => c != null && c.IsCode(unimportantList) && !resultList.Contains(c))); + + // sending activated ryzeal monster + List checkRyzealIdList = new List { CardId.IceRyzeal, CardId.ThodeRyzeal, CardId.ExRyzeal }; + foreach (int checkId in checkRyzealIdList) + { + if (summonCount == 0 && spSummonedCardIdList.Contains(checkId)) + { + List ryzealList = Bot.Hand.Where(c => c != null && c != exceptCard && !resultList.Contains(c) && c.IsCode(checkId)).ToList(); + resultList.AddRange(ryzealList); + } + } + + // sending dump cards + foreach (ClientCard card in Bot.Hand) + { + if (Bot.Hand.Count(c => c != null && !resultList.Contains(c) && c.IsCode(card.Id)) > 1) + { + resultList.Add(card); + } + } + + if (resultList.Count() == 0) + { + // sending other cards + List checkIdList = new List { _CardId.CrossoutDesignator, _CardId.CalledByTheGrave, _CardId.InfiniteImpermanence, + _CardId.GhostOgreAndSnowRabbit, _CardId.LockBird, _CardId.AshBlossom, _CardId.MaxxC }; + foreach (int checkId in checkIdList) + { + List costList = Bot.Hand.Where(c => c != null && c != exceptCard && !resultList.Contains(c) && c.IsCode(checkId)).ToList(); + resultList.AddRange(costList); + } + } + } + + return resultList; + } + + public int GetBotCurrentTotalAttack(List exceptList = null) + { + if (Util.IsTurn1OrMain2() || botSolvedCardIdList.Contains(_CardId.EvilswarmExcitonKnight)) return 0; + int result = 0; + foreach (ClientCard monster in Bot.GetMonsters()) + { + if (exceptList != null && exceptList.Contains(monster)) continue; + if (monster.IsAttack() || !summonThisTurn.Contains(monster)) result += monster.Attack; + } + return result; + } + + public int GetNegateEffectCount() + { + int count = 0; + count += GetCalledbytheGraveIdCount(_CardId.MaxxC) < 2 && Bot.HasInHand(_CardId.MaxxC) ? 1 : 0; + count += GetCalledbytheGraveIdCount(_CardId.AshBlossom) < 2 && Bot.HasInHand(_CardId.AshBlossom) ? 1 : 0; + count += GetCalledbytheGraveIdCount(_CardId.EffectVeiler) < 2 && Bot.HasInHand(_CardId.EffectVeiler) ? 1 : 0; + count += GetCalledbytheGraveIdCount(_CardId.GhostOgreAndSnowRabbit) < 2 && Bot.HasInHand(_CardId.GhostOgreAndSnowRabbit) ? 1 : 0; + count += GetCalledbytheGraveIdCount(_CardId.LockBird) < 2 && Bot.HasInHand(_CardId.LockBird) ? 1 : 0; + count += Bot.SpellZone.Count(c => c != null && c.IsFacedown() && c.IsCode(_CardId.InfiniteImpermanence)); + count += Math.Min(4 - Bot.GetSpellCountWithoutField(), Bot.Hand.Count(c => c.IsCode(_CardId.InfiniteImpermanence))); + + return count; + } + + public override BattlePhaseAction OnBattle(IList attackers, IList defenders) + { + if (attackers.Count() > 0 && defenders.Count() > 0) + { + List sortedAttacker = attackers.OrderBy(card => card.Attack).ToList(); + ClientCard rayLancer = attackers.FirstOrDefault(c => c.IsCode(CardId.FullArmoredUtopicRayLancer) && !c.IsDisabled()); + if (rayLancer != null) + { + sortedAttacker.Remove(rayLancer); + sortedAttacker.Insert(0, rayLancer); + } + for (int k = 0; k < sortedAttacker.Count; ++k) + { + ClientCard attacker = sortedAttacker[k]; + attacker.IsLastAttacker = k == sortedAttacker.Count - 1; + BattlePhaseAction result = OnSelectAttackTarget(attacker, defenders); + if (result != null) + return result; + } + } + + return base.OnBattle(attackers, defenders); + } + + public override ClientCard OnSelectAttacker(IList attackers, IList defenders) + { + ClientCard twin = attackers.FirstOrDefault(c => c.IsCode(CardId.TwinsOfTheEclipse) && !c.IsDisabled()); + if (twin != null) + { + if (Enemy.MonsterZone.Any(c => c != null && c.GetDefensePower() <= 2500)) + { + return twin; + } + } + return null; + } + + public override void OnSelectChain(IList cards) + { + if (cards != null && cards.Count() > 0) + { + currentCanActivateEffect.Clear(); + currentCanActivateEffect.AddRange(cards); + } + base.OnSelectChain(cards); + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + ChainInfo currentSolvingChain = Duel.GetCurrentSolvingChainInfo(); + if (currentSolvingChain != null) + { + if (botSolvingCross) + { + if (hint == HintMsg.DeattachFrom) + { + List> funcList = new List> + { + (c) => c.IsDisabled() && c.IsCode(CardId.RyzealDuodrive), + (c) => c.IsCode(CardId.RyzealDuodrive), + (c) => c.IsDisabled() && c.IsCode(CardId.RyzealDeadnader), + (c) => c.IsCode(CardId.RyzealDeadnader) + }; + foreach (Func func in funcList) + { + ClientCard target = cards.FirstOrDefault(c => c != null && func(c)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + + if (hint == HintMsg.RemoveXyz) + { + List targets = cards.OrderBy(c => c.Attack).ToList(); + botSolvingCross = false; + return Util.CheckSelectCount(targets, cards, min, max); + } + } + + if (currentSolvingChain.ActivatePlayer == 1 && currentSolvingChain.IsCode(_CardId.EvenlyMatched)) + { + Logger.DebugWriteLine("=== Evenly Matched activated."); + List banishList = new List(); + List botMonsters = Bot.GetMonsters().Where(card => !card.HasType(CardType.Token)).ToList(); + + // monster + List faceDownMonsters = botMonsters.Where(card => card.IsFacedown()).ToList(); + banishList.AddRange(faceDownMonsters); + List dumpMainMonsterList = botMonsters.Where(card => !banishList.Contains(card) + && CheckRemainInDeck(card.Id) > 0).ToList(); + dumpMainMonsterList.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(dumpMainMonsterList); + + // spells + bool canUsePluginToSpSummonDeadnader = Bot.Graveyard.Any(c => c != null && c.IsCanRevive() && c.IsCode(CardId.RyzealDeadnader)); + canUsePluginToSpSummonDeadnader |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDeadnader)); + + List faceUpSpells = Bot.GetSpells().Where(c => c.IsFaceup()).ToList(); + banishList.AddRange(ShuffleList(faceUpSpells)); + List faceDownSpells = Bot.GetSpells().Where(c => c.IsFacedown() + && !(canUsePluginToSpSummonDeadnader && c.IsCode(CardId.RyzealPlugIn))).ToList(); + banishList.AddRange(ShuffleList(faceDownSpells)); + + List uniqueMainMonster = botMonsters.Where(card => !banishList.Contains(card) + && !card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && CheckRemainInDeck(card.Id) == 0).ToList(); + uniqueMainMonster.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(uniqueMainMonster); + + List dumpExtraMonsterList = botMonsters.Where(card => !banishList.Contains(card) + && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && Bot.HasInExtra(card.Id)).ToList(); + dumpExtraMonsterList.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(dumpExtraMonsterList); + + List uniqueExtraMonsterList = botMonsters.Where(card => !banishList.Contains(card) + && card.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz | CardType.Link) && !Bot.HasInExtra(card.Id)).ToList(); + uniqueExtraMonsterList.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(uniqueExtraMonsterList); + + return Util.CheckSelectCount(banishList, cards, min, max); + } + + if (currentSolvingChain.ActivatePlayer == 0) + { + if (hint == HintMsg.AddToHand) + { + if (currentSolvingChain.IsCode(CardId.ThodeRyzeal)) + { + ClientCard ice = cards.FirstOrDefault(c => c.IsCode(CardId.IceRyzeal)); + ClientCard ex = cards.FirstOrDefault(c => c.IsCode(CardId.ExRyzeal)); + if (ice != null) + { + bool canSummonAndActivateIce = Duel.Player == 0 && summonCount > 0 && Duel.Phase < DuelPhase.End; + bool flag = canSummonAndActivateIce && !Bot.HasInHand(CardId.IceRyzeal) + && !activatedCardIdList.Contains(CardId.IceRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.IceRyzeal); + flag |= ex == null; + flag |= Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled() && c.IsCode(NeedIceToSolveIdList)) + && !spSummonedCardIdList.Contains(CardId.IceRyzeal) && !CheckWhetherWillbeRemoved(); + if (!canSummonAndActivateIce) + { + flag |= DefaultCheckWhetherCardIdIsNegated(CardId.ExRyzeal); + flag |= spSummonedCardIdList.Contains(CardId.ExRyzeal) || activatedCardIdList.Contains(CardId.ExRyzeal); + } + if (flag) + { + return Util.CheckSelectCount(new List { ice }, cards, min, max); + } + } + if (ex != null) + { + bool flag = !Bot.HasInHand(CardId.ExRyzeal) && !spSummonedCardIdList.Contains(CardId.ExRyzeal) && !activatedCardIdList.Contains(CardId.ExRyzeal); + flag |= Bot.HasInHand(CardId.IceRyzeal); + flag |= ice == null; + if (flag) + { + return Util.CheckSelectCount(new List { ex }, cards, min, max); + } + } + } + + if (currentSolvingChain.IsCode(CardId.ExRyzeal)) + { + ClientCard thode = cards.FirstOrDefault(c => c.IsCode(CardId.ThodeRyzeal)); + ClientCard node = cards.FirstOrDefault(c => c.IsCode(CardId.NodeRyzeal)); + if (thode != null) + { + bool flag = node == null; + flag |= !Bot.HasInHand(CardId.ThodeRyzeal) && !spSummonedCardIdList.Contains(CardId.ThodeRyzeal) && !activatedCardIdList.Contains(CardId.ThodeRyzeal); + + if (flag) + { + return Util.CheckSelectCount(new List { thode }, cards, min, max); + } + } + if (node != null) + { + bool flag = thode == null; + flag |= spSummonedCardIdList.Contains(CardId.ThodeRyzeal) && activatedCardIdList.Contains(CardId.ThodeRyzeal) + && !DefaultCheckWhetherCardIdIsNegated(CardId.ThodeRyzeal); + flag |= CheckShouldNoMoreSpSummon(CardLocation.Hand) && !CheckShouldNoMoreSpSummon(CardLocation.Grave) + && !spSummonedCardIdList.Contains(CardId.NodeRyzeal); + + if (flag) + { + return Util.CheckSelectCount(new List { node }, cards, min, max); + } + } + } + + if (currentSolvingChain.IsCode(CardId.Bonfire) || currentSolvingChain.IsCode(CardId.SeventhTachyon)) + { + if (!Bot.HasInHand(CardId.ExRyzeal) && !spSummonedCardIdList.Contains(CardId.ExRyzeal) && !CheckWhetherWillbeRemoved()) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(CardId.ExRyzeal)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + if (!Bot.HasInHand(CardId.IceRyzeal)) + { + bool flag = summonCount > 0 && !activatedCardIdList.Contains(CardId.IceRyzeal); + flag |= !spSummonedCardIdList.Contains(CardId.IceRyzeal) && Bot.Hand.Count > 0; + if (flag) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(CardId.IceRyzeal)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + List searchTargetList = new List { CardId.ExRyzeal, CardId.IceRyzeal }; + foreach (int targetId in searchTargetList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(targetId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + + if (currentSolvingChain.IsCode(CardId.RyzealDuodrive)) + { + // search spells + if (!CheckWhetherNegated(true, true, CardType.Spell)) + { + ClientCard cross = cards.FirstOrDefault(c => c.IsCode(CardId.RyzealCross)); + if (cross != null) + { + return Util.CheckSelectCount(new List { cross }, cards, min, max); + } + + ClientCard plugin = cards.FirstOrDefault(c => c.IsCode(CardId.RyzealPlugIn)); + if (plugin != null) + { + return Util.CheckSelectCount(new List { plugin }, cards, min, max); + } + } + + // search for spsummon + List>> checkList = new List>> + { + new KeyValuePair>(CardId.IceRyzeal, + () => Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled() && c.IsCode(NeedIceToSolveIdList)) + && !spSummonedCardIdList.Contains(CardId.IceRyzeal) && !CheckWhetherWillbeRemoved() ), + new KeyValuePair>(CardId.ExRyzeal, + () => !spSummonedCardIdList.Contains(CardId.ExRyzeal) && !activatedCardIdList.Contains(CardId.ExRyzeal) + && !DefaultCheckWhetherCardIdIsNegated(CardId.ExRyzeal) && !CheckWhetherWillbeRemoved() ), + new KeyValuePair>(CardId.IceRyzeal, + () => summonCount > 0 && !activatedCardIdList.Contains(CardId.IceRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.IceRyzeal) ), + new KeyValuePair>(CardId.ThodeRyzeal, + () => !spSummonedCardIdList.Contains(CardId.ThodeRyzeal) && !activatedCardIdList.Contains(CardId.ThodeRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.ThodeRyzeal) ), + new KeyValuePair>(CardId.NodeRyzeal, + () => !spSummonedCardIdList.Contains(CardId.NodeRyzeal) ) + }; + foreach (KeyValuePair> pair in checkList) + { + if (!Bot.HasInHand(pair.Key) && pair.Value()) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(pair.Key)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + + // search not exists + List searchList = new List { CardId.ExRyzeal, CardId.IceRyzeal, CardId.ThodeRyzeal, CardId.NodeRyzeal }; + foreach (int id in searchList) + { + if (!Bot.HasInHand(id)) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(id)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + + // random search + return Util.CheckSelectCount(ShuffleList(cards.ToList()), cards, min, max); + } + } + + if (hint == HintMsg.SpSummon) + { + if (currentSolvingChain.IsCode(CardId.IceRyzeal)) + { + ClientCard thode = cards.FirstOrDefault(c => c.IsCode(CardId.ThodeRyzeal)); + ClientCard ex = cards.FirstOrDefault(c => c.IsCode(CardId.ExRyzeal)); + ClientCard node = cards.FirstOrDefault(c => c.IsCode(CardId.NodeRyzeal)); + if (thode != null) + { + bool flag = !activatedCardIdList.Contains(CardId.ThodeRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.ThodeRyzeal); + flag |= Bot.HasInHand(CardId.ExRyzeal) && !spSummonedCardIdList.Contains(CardId.ExRyzeal); + flag |= ex == null && node == null; + if (flag) + { + return Util.CheckSelectCount(new List { thode }, cards, min, max); + } + } + if (ex != null) + { + bool flag = !activatedCardIdList.Contains(CardId.ExRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.ExRyzeal); + flag |= Bot.HasInHand(CardId.ThodeRyzeal) && !spSummonedCardIdList.Contains(CardId.ThodeRyzeal); + flag |= thode == null && node == null; + if (flag) + { + return Util.CheckSelectCount(new List { ex }, cards, min, max); + } + } + if (node != null) + { + return Util.CheckSelectCount(new List { node }, cards, min, max); + } + } + + if (currentSolvingChain.IsCode(CardId.TwinsOfTheEclipse)) + { + ClientCard target = TwinsOfTheEclipseRebornTarget(new List(cards)); + + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + + if (hint == HintMsg.ToDeck) + { + if (currentSolvingChain.IsCode(CardId.TripleTacticsTalent)) + { + foreach (ClientCard hand in cards) + { + foreach (int setcode in CheckSetcodeList) + { + if (hand.HasSetcode(setcode)) + { + enemyDeckTypeRecord.Add(setcode); + } + } + } + return Util.CheckSelectCount(ShuffleList(cards.ToList()), cards, min, max); + } + } + + if (hint == HintMsg.XyzMaterial) + { + if (currentSolvingChain.IsCode(CardId.RyzealDeadnader, CardId.RyzealDuodrive, CardId.RyzealPlugIn)) + { + // material that have effect + ClientCard effectTarget = cards.FirstOrDefault(c => c.IsCode(CardId.TwinsOfTheEclipse, CardId.MereologicAggregator)); + if (effectTarget != null) + { + return Util.CheckSelectCount(new List { effectTarget }, cards, min, max); + } + // cards in hand + foreach (ClientCard card in cards) + { + if (Bot.Hand.Count(c => c.IsCode(card.Id)) > 0) + { + return Util.CheckSelectCount(new List { card }, cards, min, max); + } + } + // dump card + foreach (ClientCard card in cards) + { + if (cards.Count(c => c.IsCode(card.Id)) > 1) { + return Util.CheckSelectCount(new List { card }, cards, min, max); + } + } + } + } + + if (hint == HintMsg.RemoveXyz) + { + if (currentSolvingChain.IsCode(CardId.RyzealDuodrive)) + { + List resultList = new List(); + + List detachOwnerIdList = new List { CardId.StarliegePhotonBlastDragon, CardId.RyzealDuodrive, CardId.TwinsOfTheEclipse, + CardId.FullArmoredUtopicRayLancer, _CardId.EvilswarmExcitonKnight, CardId.Number60DugaresTheTimeless, CardId.RyzealDeadnader }; + foreach (int ownerId in detachOwnerIdList) + { + // detach from DuoDrive first + List detachMaterialList = cards.Where(c => c.OwnTargets.Any(oc => oc.IsCode(ownerId))).ToList(); + if (detachMaterialList.Count() > 0) + { + // deadnader + ClientCard deadnader = detachMaterialList.FirstOrDefault(c => c.IsCode(CardId.RyzealDeadnader)); + if (deadnader != null) + { + resultList.Add(deadnader); + } + List> filterList = new List> + { + (c) => !resultList.Contains(c) + && !c.IsCode(CardId.MereologicAggregator, CardId.TwinsOfTheEclipse) + && Bot.HasInSpellZone(CardId.RyzealCross) && c.HasSetcode(SetcodeRyzeal) + && (c.Data == null || ((c.Data.Attribute & attrbuteLightDark) != 0)), + (c) => !resultList.Contains(c) + && !c.IsCode(CardId.MereologicAggregator, CardId.TwinsOfTheEclipse) + && Bot.HasInSpellZone(CardId.RyzealCross) && c.HasSetcode(SetcodeRyzeal), + (c) => !resultList.Contains(c) + && !c.IsCode(CardId.MereologicAggregator, CardId.TwinsOfTheEclipse) + && (c.Data == null || ((c.Data.Attribute & attrbuteLightDark) != 0)), + (c) => !resultList.Contains(c) + && !c.IsCode(CardId.MereologicAggregator, CardId.TwinsOfTheEclipse), + (c) => !resultList.Contains(c) + }; + foreach (Func filter in filterList) + { + foreach (ClientCard material in detachMaterialList) + { + if (filter(material)) + { + resultList.Add(material); + } + } + } + } + } + return Util.CheckSelectCount(resultList, cards, min, max); + } + } + + // gain material by plugin + if (currentSolvingChain.IsCode(CardId.RyzealPlugIn) && cards.All(c => c.Location == CardLocation.MonsterZone)) + { + ClientCard abyssDweller = cards.FirstOrDefault(c => c != null && !c.IsDisabled() && c.IsCode(CardId.AbyssDweller) && c.Overlays.Count() < 2); + if (abyssDweller != null && AbyssDwellerSummonCheck()) + { + return Util.CheckSelectCount(new List { abyssDweller }, cards, min, max); + } + + ClientCard duoDriver = cards.FirstOrDefault(c => c != null && !c.IsDisabled() && c.IsCode(CardId.RyzealDuodrive) && c.Overlays.Count() == 1); + if (duoDriver != null && Bot.HasInMonstersZone(CardId.StarliegePhotonBlastDragon, true, false, true)) + { + return Util.CheckSelectCount(new List { duoDriver }, cards, min, max); + } + + ClientCard deadnader = cards.FirstOrDefault(c => c != null && !c.IsDisabled() && c.IsCode(CardId.RyzealDeadnader)); + if (deadnader != null) + { + return Util.CheckSelectCount(new List { deadnader }, cards, min, max); + } + + if (Bot.HasInSpellZone(CardId.RyzealCross, true, true)) + { + ClientCard ryzealXyz = cards.FirstOrDefault(c => c != null && c.HasSetcode(SetcodeRyzeal)); + if (ryzealXyz != null) + { + return Util.CheckSelectCount(new List { ryzealXyz }, cards, min, max); + } + } + + ClientCard tornadoDragon = cards.FirstOrDefault(c => c != null && !c.IsDisabled() && c.IsCode(CardId.TornadoDragon) && c.Overlays.Count() == 1); + if (tornadoDragon != null && TornadoDragonSummonCheck()) + { + return Util.CheckSelectCount(new List { tornadoDragon }, cards, min, max); + } + + ClientCard no41 = cards.FirstOrDefault(c => c != null && c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir)); + if (no41 != null && Number41BagooskatheTerriblyTiredTapirSummonCheck()) + { + return Util.CheckSelectCount(new List { no41 }, cards, min, max); + } + + duoDriver = cards.FirstOrDefault(c => c != null && !c.IsDisabled() && c.IsCode(CardId.RyzealDuodrive)); + if (duoDriver != null) + { + return Util.CheckSelectCount(new List { duoDriver }, cards, min, max); + } + } + + // double attack + if (currentSolvingChain.IsCode(CardId.Number60DugaresTheTimeless) && cards.All(c => c.Location == CardLocation.MonsterZone)) + { + ClientCard maxAttackMonster = cards.Where(c => c != null && (c.HasPosition(CardPosition.FaceUpAttack) || !summonThisTurn.Contains(c))) + .OrderByDescending(c => c.Attack).FirstOrDefault(); + if (maxAttackMonster != null) + { + return Util.CheckSelectCount(new List { maxAttackMonster }, cards, min, max); + } + } + } + + // hand solve + if (hint == HintMsg.ToDeck || hint == HintMsg.ToGrave || hint == HintMsg.Discard) + { + bool allBotHand = cards.All(c => c.Controller == 0 && c.Location == CardLocation.Hand); + if (allBotHand) + { + List resultList = new List(); + List returnList = new List { _CardId.MulcharmyNyalus, _CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, + CardId.SeventhTachyon + }; + foreach (int code in returnList) + { + List targetList = cards.Where(c => c.IsCode(code) && !resultList.Contains(c)).ToList(); + if (targetList.Count() > 0) + { + resultList.AddRange(targetList); + } + } + // return dump card + foreach (ClientCard card in cards) + { + if (!resultList.Contains(card) && cards.Where(c => c.IsCode(card.Id) && !resultList.Contains(c)).Count() > 1) + { + resultList.Add(card); + } + } + List unproperCardList = new List { _CardId.EffectVeiler, _CardId.InfiniteImpermanence, _CardId.GhostOgreAndSnowRabbit, CardId.TripleTacticsTalent, + CardId.NodeRyzeal, _CardId.LockBird, CardId.RyzealPlugIn, _CardId.CrossoutDesignator, _CardId.CalledByTheGrave, CardId.RyzealCross, + CardId.ThodeRyzeal, CardId.ExRyzeal, CardId.IceRyzeal + }; + foreach (int code in unproperCardList) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(code) && !resultList.Contains(c)); + if (target != null) + { + resultList.Add(target); + } + } + return Util.CheckSelectCount(resultList, cards, min, max); + } + } + } + + if (currentSolvingChain == null) + { + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null) + { + // handle for RyzealDeadnader + if (lastChainCard.Controller == 0 && lastChainCard.IsCode(CardId.RyzealDeadnader)) + { + if (hint == HintMsg.RemoveXyz) + { + if (deadnaderDestroySelf != null) + { + ClientCard detachTarget = cards.FirstOrDefault(c => c.IsCode(CardId.MereologicAggregator, CardId.TwinsOfTheEclipse)); + if (detachTarget != null) + { + return Util.CheckSelectCount(new List { detachTarget }, cards, min, max); + } + } + List targets = cards.OrderBy(c => c.Attack).ToList(); + return Util.CheckSelectCount(targets, cards, min, max); + } else if (hint == HintMsg.Destroy) + { + if (deadnaderDestroySelf != null && cards.Contains(deadnaderDestroySelf)) + { + return Util.CheckSelectCount(new List { deadnaderDestroySelf }, cards, min, max); + } + List targetList = CanDestroyList(); + foreach (ClientCard target in targetList) + { + if (cards.Contains(target)) + { + currentDestroyCardList.Add(target); + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + } + + if (hint == HintMsg.RemoveXyz && Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn)) + { + List checkRyzealIdList = new List { CardId.NodeRyzeal, CardId.ThodeRyzeal, CardId.ExRyzeal }; + foreach (int checkId in checkRyzealIdList) + { + if (!activatedCardIdList.Contains(checkId)) + { + ClientCard target = cards.FirstOrDefault(c => c.IsCode(checkId)); + if (target != null) + { + return Util.CheckSelectCount(new List { target }, cards, min, max); + } + } + } + } + } + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + /// + /// go first + /// + public override bool OnSelectHand() + { + HashSet tenpaiList = new HashSet { SetcodeTenpaiDragon, SetcodeSangen }; + bool maybeTenpai = enemyDeckTypeRecord.Count() > 0 && enemyDeckTypeRecord.All(c => tenpaiList.Contains(c)); + return !maybeTenpai; + } + + public override int OnSelectOption(IList options) + { + bool tripleCheck = false; + for (int opt = 0; opt < 3; ++ opt) + { + if (options.Contains(Util.GetStringId(CardId.TripleTacticsTalent, opt))) + { + tripleCheck = true; + break; + } + } + if (tripleCheck) + { + return TripleTacticsTalentDecision(options); + } + + bool no60Check = false; + for (int opt = 0; opt < 3; ++ opt) + { + if (options.Contains(Util.GetStringId(CardId.Number60DugaresTheTimeless, opt))) + { + no60Check = true; + break; + } + } + if (no60Check) + { + // double attack + if (options.Contains(Util.GetStringId(CardId.Number60DugaresTheTimeless, 2))) + { + if (Number60DugaresTheTimelessDoubleTarget() != null) + { + int res = options.IndexOf(Util.GetStringId(CardId.Number60DugaresTheTimeless, 2)); + if (res >= 0) + { + return res; + } + } + } + // draw effect + if (options.Contains(Util.GetStringId(CardId.Number60DugaresTheTimeless, 0))) + { + if (Number60DugaresTheTimelessDrawEffect()) + { + int res = options.IndexOf(Util.GetStringId(CardId.Number60DugaresTheTimeless, 0)); + if (res >= 0) + { + return res; + } + } + } + // reborn + if (options.Contains(Util.GetStringId(CardId.Number60DugaresTheTimeless, 1))) + { + if (Number60DugaresTheTimelessRebornEffect()) + { + int res = options.IndexOf(Util.GetStringId(CardId.Number60DugaresTheTimeless, 1)); + if (res >= 0) + { + return res; + } + } + } + } + + ClientCard currentSolvingChain = Duel.GetCurrentSolvingChainCard(); + if (currentSolvingChain != null) + { + // TODO + } + + return base.OnSelectOption(options); + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location == CardLocation.MonsterZone) + { + List zoneIdList = ShuffleList(new List { 5, 6 }); + zoneIdList.AddRange(ShuffleList(new List { 0, 2, 4 })); + zoneIdList.AddRange(ShuffleList(new List { 1, 3 })); + foreach (int zoneId in zoneIdList) + { + int zone = (int)System.Math.Pow(2, zoneId); + if ((available & zone) != 0 && Bot.MonsterZone[zoneId] == null) + { + return zone; + } + } + } + return base.OnSelectPlace(cardId, player, location, available); + } + + public override bool OnSelectYesNo(int desc) + { + if (desc == Util.GetStringId(CardId.RyzealPlugIn, 1)) + { + Logger.DebugWriteLine("** plugin set material"); + return true; + } + + return base.OnSelectYesNo(desc); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + if (cardId == _CardId.Number41BagooskatheTerriblyTiredTapir && (Util.IsTurn1OrMain2() || Duel.Player == 1)) + { + return CardPosition.FaceUpDefence; + } + + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2) + { + bool turnDefense = false; + if (cardData.Attack <= cardData.Defense) + { + turnDefense = true; + } + if (turnDefense) + { + return CardPosition.FaceUpDefence; + } + } + if (Duel.Player == 1) + { + if (cardData.Defense >= cardData.Attack || Util.IsOneEnemyBetterThanValue(cardData.Attack, true)) + { + return CardPosition.FaceUpDefence; + } + } + int cardAttack = cardData.Attack; + int bestBotAttack = Math.Max(Util.GetBestAttack(Bot), cardAttack); + + if (Bot.HasInExtra(CardId.Number60DugaresTheTimeless) && GetLevel4FinalCountOnField(true, out _) >= 2) + { + bestBotAttack *= 2; + } + + if (Util.IsAllEnemyBetterThanValue(bestBotAttack, true)) + { + return CardPosition.FaceUpDefence; + } + } + return base.OnSelectPosition(cardId, positions); + } + + public override void OnNewTurn() + { + if (Duel.Turn <= 1) + { + dimensionShifterCount = 0; + // for doom bot + maxSummonCount = 1; + hardToDestroyCardList.Clear(); + cannotDestroyCardList.Clear(); + } + + summonCount = maxSummonCount; + enemyActivateMaxxC = false; + enemyActivatePurulia = false; + enemyActivateFuwalos = false; + enemyActivateNyalus = false; + lockBirdSolved = false; + if (dimensionShifterCount > 0) dimensionShifterCount--; + enemyActivateInfiniteImpermanenceFromHand = false; + botActivateMulcharmy = false; + deadnaderDestroySelf = null; + botSolvingCross = false; + infiniteImpermanenceList.Clear(); + currentNegateCardList.Clear(); + currentDestroyCardList.Clear(); + activatedCardIdList.Clear(); + spSummonedCardIdList.Clear(); + botSolvedCardIdList.Clear(); + enemyPlaceThisTurn.Clear(); + summonThisTurn.Clear(); + currentCanActivateEffect.Clear(); + base.OnNewTurn(); + } + + public override void OnChaining(int player, ClientCard card) + { + Duel.LastChainTargets.Clear(); + if (card == null) return; + + if (player == 1) + { + if (card.IsCode(_CardId.InfiniteImpermanence)) + { + if (enemyActivateInfiniteImpermanenceFromHand) + { + enemyActivateInfiniteImpermanenceFromHand = false; + } + else + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == card) + { + infiniteImpermanenceList.Add(4 - i); + break; + } + } + } + } + + if (card.HasSetcode(SetcodeFloowandereeze)) + { + enemyDeckTypeRecord.Add(SetcodeFloowandereeze); + } + } + + if (player == 0) + { + if (card.IsCode(_CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, _CardId.MulcharmyNyalus)) + { + botActivateMulcharmy = true; + } + } + base.OnChaining(player, card); + } + + public override void OnChainSolved(int chainIndex) + { + botSolvingCross = false; + ChainInfo currentChain = Duel.GetCurrentSolvingChainInfo(); + if (currentChain != null && !Duel.IsCurrentSolvingChainNegated()) + { + if (!Duel.IsCurrentSolvingChainNegated()) + { + if (currentChain.IsCode(_CardId.LockBird)) + lockBirdSolved = true; + if (currentChain.IsCode(_CardId.DimensionShifter)) + dimensionShifterCount = 2; + if (currentChain.ActivatePlayer == 1) + { + if (currentChain.IsCode(_CardId.MaxxC)) + enemyActivateMaxxC = true; + if (currentChain.IsCode(_CardId.MulcharmyPurulia)) + enemyActivatePurulia = true; + if (currentChain.IsCode(_CardId.MulcharmyFuwalos)) + enemyActivateFuwalos = true; + if (currentChain.IsCode(_CardId.MulcharmyNyalus)) + enemyActivateNyalus = true; + } + if (currentChain.ActivatePlayer == 0) + { + foreach (int checkId in CheckBotSolvedList) + { + if (currentChain.IsCode(checkId)) + { + botSolvedCardIdList.Add(checkId); + } + } + } + } + } + + base.OnChainSolved(chainIndex); + } + + public override void OnChainEnd() + { + for (int idx = cannotDestroyCardList.Count - 1; idx >= 0; idx--) + { + ClientCard checkTarget = cannotDestroyCardList[idx]; + if (checkTarget == null || !checkTarget.IsOnField()) + { + cannotDestroyCardList.RemoveAt(idx); + } + } + for (int idx = hardToDestroyCardList.Count - 1; idx >= 0; idx--) + { + ClientCard checkTarget = hardToDestroyCardList[idx]; + if (checkTarget == null || !checkTarget.IsOnField()) + { + hardToDestroyCardList.RemoveAt(idx); + } + } + foreach (ClientCard card in currentDestroyCardList) + { + if (card != null && card.IsOnField()) + { + if (hardToDestroyCardList.Contains(card)) + { + cannotDestroyCardList.Add(card); + } else + { + hardToDestroyCardList.Add(card); + } + } + } + + currentNegateCardList.Clear(); + currentDestroyCardList.Clear(); + currentCanActivateEffect.Clear(); + enemyActivateInfiniteImpermanenceFromHand = false; + botSolvingCross = false; + deadnaderDestroySelf = null; + for (int idx = enemyPlaceThisTurn.Count - 1; idx >= 0; idx--) + { + ClientCard checkTarget = enemyPlaceThisTurn[idx]; + if (checkTarget == null || !checkTarget.IsOnField()) + { + enemyPlaceThisTurn.RemoveAt(idx); + } + } + base.OnChainEnd(); + } + + public override void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + if (card != null) + { + if (previousControler == 1) + { + if (card.IsCode(_CardId.InfiniteImpermanence) && previousLocation == (int)CardLocation.Hand && currentLocation == (int)CardLocation.SpellZone) + enemyActivateInfiniteImpermanenceFromHand = true; + } + if (card.Owner == 1) + { + foreach (int setcode in CheckSetcodeList) + { + if (card.HasSetcode(setcode)) + { + enemyDeckTypeRecord.Add(setcode); + } + } + if (card.IsCode(AlbazFusionList)) + { + enemyDeckTypeRecord.Add(SetcodeBranded); + } + } + if (currentControler == 1 && (currentLocation == (int)CardLocation.MonsterZone || currentLocation == (int)CardLocation.SpellZone)) + { + enemyPlaceThisTurn.Add(card); + } + + if (previousControler == 0 && previousLocation == (int)CardLocation.MonsterZone && currentLocation != (int)CardLocation.MonsterZone && summonThisTurn.Contains(card)) + { + summonThisTurn.Remove(card); + } + if (currentControler == 0 && currentLocation == (int)CardLocation.MonsterZone) + { + summonThisTurn.Add(card); + } + } + + base.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + 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.IceRyzeal, CardId.ThodeRyzeal, CardId.NodeRyzeal, CardId.ExRyzeal)) + { + spSummonedCardIdList.Add(card.GetOriginCode()); + } + } + } + } + + /// + /// Select spell/trap's place randomly to avoid InfiniteImpermanence and so on. + /// + /// Card to set(default current card) + /// Whether need to avoid InfiniteImpermanence + /// Whether need to avoid set in this place + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceList.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public bool IceRyzealSpSummonFirst() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Hand | CardLocation.Deck | CardLocation.Extra)) + { + bool flag = Bot.GetMonsters().Any(c => c.IsFaceup() && c.HasType(CardType.Xyz)); + flag |= GetLevel4CountOnField() >= 2; + if (flag) return false; + } + List costList = GetCostFromHandAndFieldFirst(Card); + if (costList.Count() > 0) + { + AI.SelectCard(costList); + return true; + } + + return false; + } + + public bool IceRyzealSpSummon() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Hand | CardLocation.Deck | CardLocation.Extra)) + { + bool flag = Bot.GetMonsters().Any(c => c.IsFaceup() && c.HasType(CardType.Xyz)); + flag |= GetLevel4CountOnField() >= 2; + if (flag) return false; + } + if (Card.Level != 4) return false; + if (summonCount <= 0 && GetLevel4CountOnField() == 1) + { + List firstCostList = GetCostFromHandAndField(Card, false); + if (firstCostList.Count() > 0) + { + AI.SelectCard(firstCostList); + return true; + } + if (Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && !c.IsDisabled() && c.IsFloodgate()) || !CheckWhetherHaveFinalMonster()) + { + List costList = GetCostFromHandAndField(Card, true); + if (costList.Count() > 0) + { + AI.SelectCard(costList); + return true; + } + } + } + + return false; + } + + public bool IceRyzealSummon() + { + if (CheckWhetherNegated(true, true)) return false; + if (CheckShouldNoMoreSpSummon(CardLocation.Hand | CardLocation.Deck | CardLocation.Extra)) + { + bool flag = Bot.GetMonsters().Any(c => c.IsFaceup() && c.HasType(CardType.Xyz)); + flag |= GetLevel4CountOnField() >= 2; + if (flag) return false; + } + summonCount -= 1; + return true; + } + + public bool IceRyzealActivate() + { + if (CheckWhetherNegated(true)) return false; + if (CheckShouldNoMoreSpSummon(CardLocation.Deck) && GetLevel4CountOnField() >= 2) + { + return false; + } + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool ThodeRyzealSpSummon() + { + int lv4Count = GetLevel4CountOnField(); + if (CheckShouldNoMoreSpSummon(CardLocation.Hand | CardLocation.Deck | CardLocation.Extra)) + { + bool flag = Bot.GetMonsters().Any(c => c.IsFaceup() && c.HasType(CardType.Xyz)); + flag |= lv4Count >= 2; + flag |= lv4Count == 1 && summonCount > 0; + if (flag) return false; + } + bool spsummonFlag = lv4Count == 1; + spsummonFlag |= !CheckWhetherNegated(true, true, CardType.Monster) && CheckRemainInDeck(CardId.IceRyzeal, CardId.ExRyzeal) > 0 + && !activatedCardIdList.Contains(CardId.ThodeRyzeal) && !lockBirdSolved; + if (GetLevel4CountOnField() == 0) + { + spsummonFlag |= GetLevel4FinalCountOnField(true, out _) >= 2 && !CheckWhetherHaveFinalMonster(); + } + + return spsummonFlag; + } + + public bool ThodeRyzealSummon() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Extra)) + { + int lv4Count = GetLevel4CountOnField(); + if (lv4Count == 1) + { + bool flag = !activatedCardIdList.Contains(CardId.ThodeRyzeal); + flag &= !(Bot.HasInHand(CardId.ExRyzeal) && !activatedCardIdList.Contains(CardId.ExRyzeal)); + if (flag) + { + summonCount -= 1; + return true; + } + } + bool skipFlag = Bot.GetMonsters().Any(c => c.IsFaceup() && c.HasType(CardType.Xyz)); + skipFlag |= lv4Count >= 2; + if (skipFlag) return false; + } + if (CheckWhetherNegated(true)) return false; + + summonCount -= 1; + return true; + } + + public bool ThodeRyzealActivate() + { + if (CheckWhetherNegated(true)) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool NodeRyzealSpSummon() + { + int lv4Count = GetLevel4CountOnField(); + if (CheckShouldNoMoreSpSummon(CardLocation.Hand | CardLocation.Deck | CardLocation.Extra)) + { + bool flag = Bot.GetMonsters().Any(c => c.IsFaceup() && c.HasType(CardType.Xyz)); + flag |= lv4Count >= 2; + flag |= lv4Count == 1 && summonCount > 0; + if (flag) return false; + } + bool spsummonFlag = lv4Count == 1; + spsummonFlag |= !CheckWhetherNegated(true, true, CardType.Monster) && Bot.Graveyard.Any(c => !c.HasType(CardType.Xyz) && c.HasSetcode(SetcodeRyzeal) && c.Level == 4); + return spsummonFlag; + } + + public bool NodeRyzealSpSummonFirst() + { + int lv4Count = GetLevel4CountOnField(); + if (CheckShouldNoMoreSpSummon(CardLocation.Hand | CardLocation.Deck | CardLocation.Extra)) + { + bool flag = Bot.GetMonsters().Any(c => c.IsFaceup() && c.HasType(CardType.Xyz)); + flag |= lv4Count >= 2; + flag |= lv4Count == 1 && summonCount > 0; + if (flag) return false; + } + if (!activatedCardIdList.Contains(Card.Id) && GetCostFromHandAndField(Card, false).Count() > 0) + { + return true; + } + return false; + } + + public bool NodeRyzealActivate() + { + if (NodeRyzealActivateInner(true)) + { + return true; + } + + return false; + } + + public bool NodeRyzealActivateFirst() + { + if (NodeRyzealActivateInner(false)) + { + return true; + } + + return false; + } + + public bool NodeRyzealActivateInner(bool sendNotNessary) + { + if (CheckWhetherNegated(true)) return false; + if (CheckShouldNoMoreSpSummon(CardLocation.Grave | CardLocation.Extra)) + { + if (Bot.GetMonsters().Count(c => c.HasType(CardType.Xyz) && c.IsFaceup()) > 0) return false; + } + + ClientCard nonLightDarkTarget = Bot.Graveyard.Where(c => c != null && !c.HasType(CardType.Xyz) && c.HasSetcode(SetcodeRyzeal) && c.Level == 4 + && !c.HasAttribute((CardAttribute)attrbuteLightDark)).OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + ClientCard normalTarget = Bot.Graveyard.Where(c => c != null && !c.HasType(CardType.Xyz) && c.HasSetcode(SetcodeRyzeal) && c.Level == 4 + && c != nonLightDarkTarget).OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (nonLightDarkTarget == null || normalTarget == null) return false; + List rebornTarget = new List { nonLightDarkTarget, normalTarget }; + + List firstCostList = GetCostFromHandAndField(Card, false); + if (firstCostList.Count() > 0) + { + AI.SelectCard(firstCostList); + AI.SelectNextCard(rebornTarget); + activatedCardIdList.Add(Card.Id); + return true; + } + if (GetLevel4CountOnField() == 1 && sendNotNessary) + { + List nextCostList = GetCostFromHandAndField(Card, true); + if (nextCostList.Count() > 0) + { + AI.SelectCard(nextCostList); + AI.SelectNextCard(rebornTarget); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + return false; + } + + public bool ExRyzealSpSummon() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Hand | CardLocation.Extra)) + { + bool checkFlag = !CheckWhetherHaveFinalMonster() && GetLevel4CountOnField() == 1; + if (checkFlag && ExRyzealDiscardExtra()) + { + return true; + } + return false; + } + if (Duel.Turn == 1) + { + bool checkFlag = !activatedCardIdList.Contains(CardId.ExRyzeal) && !lockBirdSolved && !DefaultCheckWhetherCardIdIsNegated(CardId.ExRyzeal) && !Bot.HasInMonstersZone(_CardId.Number41BagooskatheTerriblyTiredTapir); + checkFlag |= !Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasType(CardType.Xyz)) && GetLevel4CountOnField() == 1; + if (checkFlag) + { + // discard ryzeal + AI.SelectCard(CardId.RyzealDeadnader, CardId.RyzealDuodrive); + return true; + } + } + if (ExRyzealDiscardExtra()) + { + return true; + } + + return false; + } + + public bool ExRyzealDiscardExtra() + { + List discardIdCheckList = new List { CardId.MereologicAggregator, CardId.TwinsOfTheEclipse, CardId.Number104Masquerade, CardId.StarliegePhotonBlastDragon, + CardId.TornadoDragon, CardId.AbyssDweller, _CardId.EvilswarmExcitonKnight, CardId.FullArmoredUtopicRayLancer, CardId.Number60DugaresTheTimeless, + CardId.RyzealDuodrive, CardId.RyzealDeadnader}; + + // delay id + List discardIdList = new List(); + foreach (int discardId in discardIdCheckList) + { + if (discardId == CardId.MereologicAggregator) + { + if (!Enemy.MonsterZone.Any(c => c != null && c.IsFaceup() && !c.IsDisabled() && !c.IsShouldNotBeMonsterTarget()) + && Enemy.SpellZone.Any(c => c != null && c.IsFaceup() && !c.IsDisabled() && !c.IsShouldNotBeMonsterTarget())) + { + continue; + } + } + if (discardId == CardId.TwinsOfTheEclipse) + { + if (Bot.Graveyard.Count(c => c.HasType(CardType.Xyz)) < 2 || !Bot.Graveyard.Any(c => c.HasType(CardType.Xyz) && c.IsCanRevive())) + { + continue; + } + } + if (discardId == CardId.Number104Masquerade) + { + if (CheckRemainInDeck(CardId.SeventhTachyon) > 0 || Bot.HasInHandOrInSpellZone(CardId.Number104Masquerade)) + { + continue; + } + } + if (discardId == CardId.TornadoDragon) + { + if (Enemy.GetSpellCount() > 0) + { + continue; + } + } + discardIdList.Add(discardId); + } + discardIdList.AddRange(discardIdCheckList); + + foreach (int id in discardIdList) + { + if (Bot.HasInExtra(id)) + { + AI.SelectCard(id); + return true; + } + } + + return false; + } + + public bool ExRyzealSpSummonLater() + { + // TODO + return false; + } + + public bool ExRyzealSummon() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Extra)) + { + if (GetLevel4CountOnField() == 1) + { + bool flag = !activatedCardIdList.Contains(CardId.ExRyzeal); + flag &= !(Bot.HasInHand(CardId.ThodeRyzeal) && !activatedCardIdList.Contains(CardId.ThodeRyzeal)); + if (flag) + { + summonCount -= 1; + return true; + } + } + } + return false; + } + + public bool ExRyzealActivate() + { + if (CheckWhetherNegated(true)) + { + // use mero to negate No.41? + int count41 = Enemy.GetMonsters().Count(c => c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir) && c.IsFaceup() + && !c.IsDisabled() && c.HasPosition(CardPosition.FaceUpDefence)); + bool canNegate41 = count41 == 1 && currentCanActivateEffect.Any(c => c != null && c.IsCode(CardId.MereologicAggregator)); + + if (canNegate41) + { + activatedCardIdList.Add(Card.Id); + return true; + } else + { + return false; + } + } + activatedCardIdList.Add(Card.Id); + return true; + } + + public bool MulcharmyFuwalosActivate() + { + if (CheckWhetherNegated(true) || Duel.Player == 0) return false; + if (lockBirdSolved || Duel.CurrentChain.Any(c => c.IsCode(_CardId.LockBird))) return false; + if (Duel.Phase > DuelPhase.Main1) return false; + + botActivateMulcharmy = true; + return true; + } + + public bool MulcharmyPuruliaActivate() + { + if (CheckWhetherNegated(true) || Duel.Player == 0) return false; + if (lockBirdSolved || Duel.CurrentChain.Any(c => c.IsCode(_CardId.LockBird))) return false; + if (Duel.Phase > DuelPhase.Main1) return false; + if (botActivateMulcharmy) return false; + + botActivateMulcharmy = true; + return true; + } + + public bool MulcharmyNyalusActivate() + { + if (CheckWhetherNegated(true) || Duel.Player == 0) return false; + if (lockBirdSolved || Duel.CurrentChain.Any(c => c.IsCode(_CardId.LockBird))) return false; + if (Duel.Phase > DuelPhase.Main1) return false; + if (botActivateMulcharmy) return false; + + botActivateMulcharmy = true; + return true; + } + + public bool AshBlossomActivate() + { + if (CheckWhetherNegated(true) || !CheckLastChainShouldNegated()) return false; + if (DefaultAshBlossomAndJoyousSpring()) + { + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard.Location == CardLocation.MonsterZone || lastChainCard.Location == CardLocation.SpellZone) currentNegateCardList.Add(Util.GetLastChainCard()); + return true; + } + return false; + } + + public bool GhostOgreAndSnowRabbitActivate() + { + if (CheckWhetherNegated(true) || Duel.LastChainPlayer == 0) return false; + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard == null || lastChainCard.IsDisabled()) return false; + if (lastChainCard.IsMonster() && !lastChainCard.HasType(CardType.Link | CardType.Fusion | CardType.Synchro | CardType.Xyz)) return false; + return true; + } + + public bool MaxxCActivate() + { + if (CheckWhetherNegated(true) || Duel.LastChainPlayer == 0 || lockBirdSolved) return false; + return DefaultMaxxC(); + } + + public bool LockBirdActivate() + { + if (CheckWhetherNegated(true)) return false; + if (Duel.Player == 0) return false; + List mulcharmyCheckIdList = new List { _CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos }; + if (mulcharmyCheckIdList.Intersect(botSolvedCardIdList).Any()) + { + int enemyFieldCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount(); + if (enemyFieldCount + 6 < Bot.Hand.Count()) return false; + } + if (botSolvedCardIdList.Contains(_CardId.MaxxC)) + { + if (!activatedCardIdList.Contains(_CardId.AshBlossom) || !activatedCardIdList.Contains(_CardId.EffectVeiler)) return false; + } + return true; + } + + public bool EffectVeilerActivate() + { + if (CheckWhetherNegated(true)) return false; + // negate monster + List shouldNegateList = GetMonsterListForTargetNegate(true, CardType.Monster); + if (shouldNegateList.Count > 0) + { + ClientCard negateTarget = shouldNegateList[0]; + currentNegateCardList.Add(negateTarget); + AI.SelectCard(negateTarget); + return true; + } + + return false; + } + + public bool SeventhTachyonActivate() + { + if (CheckWhetherNegated(true, true, CardType.Spell)) return false; + bool flag = !spSummonedCardIdList.Contains(CardId.ExRyzeal) && !Bot.HasInHand(CardId.ExRyzeal); + flag &= !(!activatedCardIdList.Contains(CardId.IceRyzeal) && summonCount > 0 && Bot.HasInHand(CardId.IceRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.IceRyzeal)); + if (flag) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public bool TripleTacticsTalentActivate() + { + if (CheckWhetherNegated(true)) return false; + if (TripleTacticsTalentDecision(null) == -1) return false; + SelectSTPlace(Card, true); + return true; + } + + public int TripleTacticsTalentDecision(IList options) + { + // gain control? + bool dangerFlag = Enemy.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled() && (c.IsFloodgate() + || c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir) && c.HasPosition(CardPosition.FaceUpDefence))); + if (dangerFlag) + { + if (options == null) return 1; + int res = options.IndexOf(Util.GetStringId(CardId.TripleTacticsTalent, 1)); + if (res >= 0) return res; + } + // draw? + if (!lockBirdSolved) + { + bool checkFlag = CheckCanContinueSummon(); + if (!checkFlag) + { + if (options == null) return 1; + int res = options.IndexOf(Util.GetStringId(CardId.TripleTacticsTalent, 0)); + if (res >= 0) return res; + } + } + // shuffle hand + if (Enemy.Hand.Count() > 0) + { + if (options == null) return 1; + int res = options.IndexOf(Util.GetStringId(CardId.TripleTacticsTalent, 2)); + if (res >= 0) return res; + } + return -1; + } + + public bool PotOfDesiresActivate() + { + if (CheckWhetherNegated(true)) return false; + if (Bot.Deck.Count >= 15) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public bool PotOfDesireActivateForContinue() + { + if (CheckWhetherNegated(true)) return false; + if (Bot.Deck.Count >= 15 && !CheckCanContinueSummon() && CheckRemainInDeck(CardId.IceRyzeal, CardId.ThodeRyzeal, CardId.ExRyzeal) > 0) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public bool BonfireActivateToSearchNecessary() + { + if (CheckWhetherNegated(true, true, CardType.Spell)) return false; + bool flag = !spSummonedCardIdList.Contains(CardId.ExRyzeal) && !Bot.HasInHand(CardId.ExRyzeal); + flag |= !activatedCardIdList.Contains(CardId.IceRyzeal) && summonCount > 0 && !Bot.HasInHand(CardId.IceRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.IceRyzeal); + if (flag) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + + public bool BonfireActivate() + { + if (CheckWhetherNegated(true)) return false; + // activate before no60 + if (!activatedCardIdList.Contains(CardId.Number60DugaresTheTimeless)) + { + ClientCard no60 = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(CardId.Number60DugaresTheTimeless) && !c.IsDisabled()); + if (no60 != null && no60.Overlays.Count() >= 2) + { + SelectSTPlace(Card, true); + return true; + } + } + + return false; + } + + public bool CalledbytheGraveActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + ClientCard lastChainCard = Util.GetLastChainCard(); + if (Duel.LastChainPlayer == 1) + { + // negate + if (lastChainCard != null && lastChainCard.IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + + // not to negate same card in hand + List mulcharmyIdList = new List { _CardId.MulcharmyPurulia, _CardId.MulcharmyFuwalos, _CardId.MulcharmyNyalus }; + if (Duel.Player == 0 && Bot.HasInHand(code) && !mulcharmyIdList.Contains(code)) return false; + + ClientCard graveTarget = Enemy.Graveyard.GetFirstMatchingCard(card => card.IsMonster() && card.GetOriginCode() == code); + if (graveTarget != null) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(graveTarget); + currentDestroyCardList.Add(graveTarget); + currentNegateCardList.AddRange(Enemy.MonsterZone.Where(c => c != null && c.IsFaceup() && c.IsCode(code))); + return true; + } + } + + // banish target + foreach (ClientCard graveCard in Enemy.Graveyard) + { + if (Duel.ChainTargets.Contains(graveCard) && graveCard.IsMonster()) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + int code = graveCard.Id; + AI.SelectCard(graveCard); + currentDestroyCardList.Add(graveCard); + return true; + } + } + + // become targets + if (Duel.ChainTargets.Contains(Card)) + { + List enemyMonsters = Enemy.Graveyard.GetMatchingCards(card => card.IsMonster()).ToList(); + if (enemyMonsters.Count > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + int code = enemyMonsters[0].Id; + AI.SelectCard(code); + currentDestroyCardList.Add(enemyMonsters[0]); + return true; + } + } + } + + // avoid danger monster in grave + if (Duel.LastChainPlayer == 1) return false; + List targets = GetDangerousCardinEnemyGrave(true); + if (targets.Count > 0) + { + int code = targets[0].Id; + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(code); + currentDestroyCardList.Add(targets[0]); + return true; + } + + return false; + } + + public bool RyzealPlugInActivate() + { + if (CheckWhetherNegated(true)) return false; + + // spsummon lv4 + if (Duel.Player == 0 && CurrentTiming == -1) + { + bool summonFlag = GetLevel4CountOnField() == 1; + if (GetLevel4CountOnField() == 0) + { + summonFlag |= GetLevel4FinalCountOnField(true, out _) >= 2 && !CheckWhetherHaveFinalMonster(); + } + + // summon extra level4 monster to xyz summon + if (summonFlag) + { + List checkIdList = new List { CardId.NodeRyzeal, CardId.ExRyzeal, CardId.ThodeRyzeal, CardId.IceRyzeal }; + foreach (int id in checkIdList) + { + if (activatedCardIdList.Contains(id)) continue; + ClientCard target = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + if (target == null) + { + target = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + } + if (target != null) + { + AI.SelectCard(target); + SelectSTPlace(Card, true); + return true; + } + } + + foreach (int id in checkIdList) + { + ClientCard target = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + if (target == null) + { + target = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + } + if (target != null) + { + AI.SelectCard(target); + SelectSTPlace(Card, true); + return true; + } + } + } + } + + // spsummon deadnader + if (!Bot.HasInMonstersZone(CardId.RyzealDeadnader, true, true, true) && !Duel.CurrentChain.Any(c => c.IsCode(CardId.TwinsOfTheEclipse)) + && !DefaultCheckWhetherCardIdIsNegated(CardId.RyzealDeadnader) && !Util.ChainContainPlayer(0)) + { + ClientCard deadnader = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(CardId.RyzealDeadnader) && c.IsCanRevive()); + if (deadnader == null) + { + deadnader = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(CardId.RyzealDeadnader) && c.IsCanRevive()); + } + if (deadnader != null) + { + AI.SelectCard(deadnader); + SelectSTPlace(Card, true); + return true; + } + } + + // chain to negate monster effect + if (Bot.HasInSpellZone(CardId.RyzealCross, true, true) && !activatedCardIdList.Contains(CardId.RyzealCross + 2) + && CheckRemainInDeck(CardId.ExRyzeal, CardId.IceRyzeal, CardId.NodeRyzeal, CardId.ThodeRyzeal) > 0) + { + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && lastChainCard.IsMonster() && lastChainCard.Controller == 1 && CheckCardShouldNegate(lastChainCard)) + { + bool activateFlag = false; + bool shouldRebornXyz = false; + bool duodriverActivating = Duel.CurrentChain.Any(c => c.IsCode(CardId.RyzealDuodrive) && c.Controller == 0) && activatedCardIdList.Contains(CardId.RyzealDuodrive + 1); + if (duodriverActivating) + { + // check whether have 3+ material + activateFlag = Bot.MonsterZone.Where(c => c != null && c.HasType(CardType.Xyz)).Sum(c => c.Overlays.Count()) >= 3; + } else + { + if (!Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && c.Overlays.Count() > 0)) + { + activateFlag |= Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasType(CardType.Xyz) && c.HasSetcode(SetcodeRyzeal)); + if (!activateFlag) + { + bool hasXyzTarget = Bot.Banished.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && c.IsCanRevive() && c.HasType(CardType.Xyz)); + hasXyzTarget |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && c.IsCanRevive() && c.HasType(CardType.Xyz)); + if (hasXyzTarget) + { + activateFlag = true; + shouldRebornXyz = true; + } + } + } + } + + if (activateFlag) + { + ClientCard deadnader = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDeadnader)); + if (deadnader == null) + { + deadnader = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDeadnader)); + } + if (deadnader != null) + { + AI.SelectCard(deadnader); + SelectSTPlace(Card, true); + return true; + } + + if (shouldRebornXyz) + { + ClientCard duoDriver = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDuodrive)); + if (duoDriver == null) + { + duoDriver = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDuodrive)); + } + if (duoDriver != null) + { + AI.SelectCard(duoDriver); + SelectSTPlace(Card, true); + return true; + } + } else + { + List checkIdList = new List { CardId.NodeRyzeal, CardId.ExRyzeal, CardId.ThodeRyzeal, CardId.IceRyzeal }; + foreach (int id in checkIdList) + { + if (activatedCardIdList.Contains(id)) continue; + ClientCard target = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + if (target == null) + { + target = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + } + if (target != null) + { + AI.SelectCard(target); + SelectSTPlace(Card, true); + return true; + } + } + foreach (int id in checkIdList) + { + ClientCard target = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + if (target == null) + { + target = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + } + if (target != null) + { + AI.SelectCard(target); + SelectSTPlace(Card, true); + return true; + } + } + } + } + } + } + + bool becomeTargetFlag = DefaultOnBecomeTarget() && Card.Location == CardLocation.SpellZone; + bool endPhaseFlag = Duel.Player == 1 && Duel.Phase == DuelPhase.End; + if (becomeTargetFlag || endPhaseFlag) + { + if (!(Duel.CurrentChain.Any(c => c != null && c.Controller == 1 && c.IsCode(_CardId.EvenlyMatched)) && deadnaderDestroySelf != null)) + { + ClientCard deadnader = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDeadnader)); + if (deadnader == null) + { + deadnader = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDeadnader)); + } + if (deadnader != null) + { + AI.SelectCard(deadnader); + SelectSTPlace(Card, true); + return true; + } + + ClientCard duoDriver = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDuodrive)); + if (duoDriver == null) + { + duoDriver = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDuodrive)); + } + if (duoDriver != null) + { + AI.SelectCard(duoDriver); + SelectSTPlace(Card, true); + return true; + } + + List checkIdList = new List { CardId.NodeRyzeal, CardId.ExRyzeal, CardId.ThodeRyzeal, CardId.IceRyzeal }; + foreach (int id in checkIdList) + { + if (activatedCardIdList.Contains(id)) continue; + ClientCard target = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + if (target == null) + { + target = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + } + if (target != null) + { + AI.SelectCard(target); + SelectSTPlace(Card, true); + return true; + } + } + + if (!endPhaseFlag) + { + foreach (int id in checkIdList) + { + ClientCard target = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + if (target == null) + { + target = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(id)); + } + if (target != null) + { + AI.SelectCard(target); + SelectSTPlace(Card, true); + return true; + } + } + } + } + } + + return false; + } + + public bool RyzealPlugInActivateFirst() + { + if (CheckWhetherNegated(true)) return false; + if (Duel.Player == 0 && CurrentTiming == -1 && !activatedCardIdList.Contains(CardId.NodeRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.NodeRyzeal)) + { + List nodeCostList = GetCostFromHandAndField(Card, false); + if (nodeCostList.Count() > 0) + { + ClientCard target = Bot.Banished.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(CardId.NodeRyzeal)); + if (target == null) + { + target = Bot.Graveyard.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(CardId.NodeRyzeal)); + } + if (target != null) + { + AI.SelectCard(target); + SelectSTPlace(Card, true); + return true; + } + } + } + + return false; + } + + public bool RyzealCrossActivateCard() + { + // whether to negate by cross + if (ActivateDescription == Util.GetStringId(CardId.RyzealCross, 3)) + { + ChainInfo currentChainInfo = Duel.GetCurrentSolvingChainInfo(); + if (currentChainInfo != null && !Duel.IsCurrentSolvingChainNegated()) + { + if (CheckCardShouldNegate(currentChainInfo)) + { + Logger.DebugWriteLine("** cross negate"); + activatedCardIdList.Add(CardId.RyzealCross + 2); + botSolvingCross = true; + return true; + } + } + return false; + } + + if (CheckWhetherNegated(true)) return false; + if (Card.Location == CardLocation.SpellZone && Card.IsFaceup()) return false; + bool flag = RyzealCrossActivateRecycleFirst(); + bool canSetMaterial = Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn) && CheckRemainInDeck(CardId.IceRyzeal, CardId.ExRyzeal, CardId.NodeRyzeal, CardId.ThodeRyzeal) > 0 + && (Bot.Graveyard.Any(c => c != null && c.HasSetcode(SetcodeRyzeal) && (c.IsCanRevive() || !c.HasType(CardType.Xyz))) || + Bot.Banished.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && (c.IsCanRevive() || !c.HasType(CardType.Xyz)))); + flag |= Bot.MonsterZone.Count(c => c != null && c.IsFaceup() && c.HasType(CardType.Xyz) && c.HasSetcode(SetcodeRyzeal) && (c.Overlays.Count() > 0 || canSetMaterial)) > 0; + + if (Duel.MainPhase.SpecialSummonableCards.Any(c => c.IsCode(CardId.RyzealDuodrive))) + { + flag |= RyzealDuodriveSpSummonCheck(); + } + + return flag; + } + + public bool RyzealCrossActivateRecycleFirst() + { + if (CheckWhetherNegated(true) || !(Card.Location == CardLocation.SpellZone && Card.IsFaceup())) return false; + if (ActivateDescription == Util.GetStringId(CardId.RyzealCross, 3)) + { + return false; + } + List checkIdList = new List { CardId.RyzealPlugIn, CardId.RyzealDuodrive, CardId.RyzealDeadnader, CardId.NodeRyzeal, CardId.ExRyzeal, CardId.IceRyzeal, CardId.ThodeRyzeal }; + List targetList = new List(); + foreach (int id in checkIdList) + { + ClientCard target = Bot.Graveyard.FirstOrDefault(c => c.IsCode(id)); + if (target != null && (CheckRemainInDeck(id) + Bot.ExtraDeck.Count(c => c.IsCode(id)) + Bot.Hand.Count(c => c.IsCode(id))) == 0) + { + if (target.HasType(CardType.Xyz) && GetLevel4CountOnField() == 1) continue; + targetList.Add(target); + } + + if (targetList.Count() >= 2) + { + AI.SelectCard(targetList); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + + return false; + } + + public bool RyzealCrossActivateRecycleLater() + { + if (CheckWhetherNegated(true) || !(Card.Location == CardLocation.SpellZone && Card.IsFaceup())) return false; + if (ActivateDescription == Util.GetStringId(CardId.RyzealCross, 3)) + { + return false; + } + SortedDictionary> countDict = new SortedDictionary>(); + List checkIdList = new List { CardId.RyzealPlugIn, CardId.RyzealDuodrive, CardId.RyzealDeadnader, CardId.NodeRyzeal, CardId.ExRyzeal, CardId.IceRyzeal, CardId.ThodeRyzeal }; + foreach (int id in checkIdList) + { + int remainCount = CheckRemainInDeck(id) + Bot.ExtraDeck.Count(c => c.IsCode(id)); + if (!countDict.ContainsKey(remainCount)) + { + countDict.Add(remainCount, new List()); + } + countDict[remainCount].Add(id); + } + + List targetList = new List(); + foreach (KeyValuePair> pair in countDict) + { + foreach (int id in pair.Value) + { + ClientCard target = Bot.Graveyard.FirstOrDefault(c => c.IsCode(id)); + if (target != null) targetList.Add(target); + } + } + + if (targetList.Count() >= 2) + { + AI.SelectCard(targetList); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + + return false; + } + + public bool CrossoutDesignatorActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + // negate + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard() != null) + { + int code = Util.GetLastChainCard().Id; + int alias = Util.GetLastChainCard().Alias; + if (alias != 0 && alias - code < 10) code = alias; + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + if (CheckRemainInDeck(code) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectAnnounceID(code); + currentNegateCardList.AddRange(Enemy.MonsterZone.Where(c => c != null && c.IsFaceup() && c.IsCode(code))); + return true; + } + } + return false; + } + + public bool InfiniteImpermanenceActivate() + { + if (CheckWhetherNegated()) return false; + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || Util.IsChainTarget(Card) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true); + if (target != null) + { + AI.SelectCard(target); + } + else + { + AI.SelectCard(Enemy.GetMonsters()); + } + infiniteImpermanenceList.Add(this_seq); + return true; + } + } + + // negate monster + List shouldNegateList = GetMonsterListForTargetNegate(true, CardType.Trap); + if (shouldNegateList.Count > 0) + { + ClientCard negateTarget = shouldNegateList[0]; + currentNegateCardList.Add(negateTarget); + + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(negateTarget); + return true; + } + + return false; + } + + // TODO extra summon + + public bool AbyssDwellerSummonCheck() + { + bool flag = enemyDeckTypeRecord.Contains(SetcodeAtlantean); + flag |= enemyDeckTypeRecord.Contains(SetcodeOrcust); + flag |= enemyDeckTypeRecord.Contains(SetcodePhantomKnight); + flag |= enemyDeckTypeRecord.Count() > 0 && enemyDeckTypeRecord.All(c => c == SetcodeTearlaments); + + int enemyDeckTotalCount = Enemy.Hand.Count() + Enemy.Deck.Count() + Enemy.Graveyard.Count() + Enemy.Banished.Count() + Enemy.ExtraDeck.Count(); + if (enemyDeckTotalCount > 65) + { + flag |= !enemyDeckTypeRecord.Contains(SetcodeInfernoid); + } + + return flag; + } + + public bool Number41BagooskatheTerriblyTiredTapirSummonCheck() + { + bool flag = enemyDeckTypeRecord.Contains(SetcodeFloowandereeze); + flag |= enemyDeckTypeRecord.Contains(SetcodeBranded); + flag |= enemyDeckTypeRecord.Contains(SetcodeRyzeal); + flag &= Util.IsTurn1OrMain2(); + + return flag; + } + + public bool TornadoDragonSummonCheck() + { + if (CheckWhetherNegated(true, true, CardType.Monster)) return false; + bool flag = enemyDeckTypeRecord.Contains(SetcodeLabrynth); + flag |= Enemy.SpellZone.Any(c => c != null && c.IsFaceup() && !c.IsDisabled() && c.IsFloodgate()); + flag |= Enemy.SpellZone.Count(c => c != null && !c.IsShouldNotBeMonsterTarget() && !NotToDestroySpellTrap.Contains(c.Id)) >= 3; + flag |= !Util.IsTurn1OrMain2() && !botSolvedCardIdList.Contains(_CardId.EvilswarmExcitonKnight) && Enemy.GetMonsterCount() == 0 + && Enemy.SpellZone.Count(c => c != null && !c.IsShouldNotBeMonsterTarget() && !NotToDestroySpellTrap.Contains(c.Id)) > 0; + + return flag; + } + + public bool EvilswarmExcitonKnightSpSummon() + { + if (CheckWhetherNegated(true, true, CardType.Monster) || Duel.Turn == 1) return false; + + return DefaultEvilswarmExcitonKnightSummon(); + } + + public bool LessSpSummonExtra() + { + if (!CheckShouldNoMoreSpSummon(CardLocation.Extra)) return false; + + // No.41 + ClientCard no41 = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir)); + if (no41 != null) + { + if (Number41BagooskatheTerriblyTiredTapirSummonCheck()) + { + if (Card != no41) return false; + + // Select 2 monster with lowest defense + List materialList = GetLevel4OnField(null); + if (materialList.Count() >= 2) + { + AI.SelectMaterials(materialList); + return true; + } + } + } + // abyss + ClientCard abyss = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(CardId.AbyssDweller)); + if (abyss != null) + { + if (AbyssDwellerSummonCheck()) + { + if (Card != abyss) return false; + + // Select 2 monster with lowest defense + List materialList = GetLevel4OnField(null); + if (materialList.Count() >= 2) + { + AI.SelectMaterials(materialList); + return true; + } + } + } + // deadnader + ClientCard deadnader = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(CardId.RyzealDeadnader)); + if (deadnader != null) + { + List materialList = GetLevel4OnField(c => c.HasSetcode(SetcodeRyzeal)); + if (materialList.Count() >= 2) + { + if (Card != deadnader) return false; + AI.SelectMaterials(materialList); + return true; + } + } + + return false; + } + + public bool FirstRyzealDuodriveSpSummon() + { + if (!RyzealDuodriveSpSummonCheck()) return false; + if (Bot.Graveyard.Count(c => c.HasSetcode(SetcodeRyzeal) && c.IsMonster()) == 0) + { + if (!CheckShouldNoMoreSpSummon(CardLocation.Hand) && Bot.HasInHand(CardId.ExRyzeal) + && !spSummonedCardIdList.Contains(CardId.ExRyzeal) && Duel.MainPhase.SpecialSummonableCards.Any(c => c.IsCode(CardId.ExRyzeal)) + && Bot.ExtraDeck.Count(c => c.IsCode(CardId.RyzealDeadnader, CardId.RyzealDuodrive)) > 2) + { + return false; + } + } + + List materialList = GetLevel4OnField(null); + List materialExceptNode = materialList + .Where(c => !(c.IsCode(CardId.NodeRyzeal) && !c.IsDisabled() && !activatedCardIdList.Contains(CardId.NodeRyzeal))).ToList(); + + if (materialExceptNode.Count() >= 2) + { + AI.SelectMaterials(materialExceptNode.Take(2).ToList()); + return true; + } + if (materialList.Count() > 2 && !CheckCanContinueSummon()) + { + AI.SelectMaterials(materialList.Take(2).ToList()); + return true; + } + if (materialList.Count() >= 2 && !CheckCanContinueSummon(true)) + { + AI.SelectMaterials(materialList.Take(2).ToList()); + return true; + } + + return false; + } + + public bool RyzealDuodriveSpSummonCheck() + { + bool checkFlag = Duel.MainPhase.SpecialSummonableCards.Any(c => c.IsCode(CardId.RyzealDuodrive)); + checkFlag &= !Bot.HasInMonstersZone(CardId.RyzealDuodrive, true, true, true); + checkFlag &= CheckRemainInDeck(CardId.IceRyzeal, CardId.ThodeRyzeal, CardId.NodeRyzeal, CardId.ExRyzeal, CardId.RyzealPlugIn, CardId.RyzealCross) >= 2; + checkFlag &= !DefaultCheckWhetherCardIdIsNegated(CardId.RyzealDuodrive); + checkFlag &= !activatedCardIdList.Contains(CardId.RyzealDuodrive + 1); + checkFlag &= !CheckWhetherNegated(true, true, CardType.Monster); + checkFlag &= !lockBirdSolved; + checkFlag &= !CheckShouldNoMoreSpSummon(CardLocation.Extra); + + return checkFlag; + } + + public bool SecondXyzSummon() + { + if (Card.Location != CardLocation.Extra) return false; + + int level4Count = GetLevel4FinalCountOnField(true, out _); + bool result = SecondXyzSummonInner(); + Logger.DebugWriteLine("Second Xyz Count: " + level4Count.ToString()); + Logger.DebugWriteLine("Second Xyz Summon: " + result.ToString()); + return result; + } + + public bool SecondXyzSummonInner() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Extra)) return false; + + // summon after duo driver + if (RyzealDuodriveSpSummonCheck()) { + Logger.DebugWriteLine("Second: summon duodriver first"); + return false; + } + + // check whether have 4 monsters for material. + // if not, skip the second xyz monster. + int level4Count = GetLevel4FinalCountOnField(true, out bool hasNode); + if (level4Count < 4) return false; + + // select which monster to summon + List materialList = GetLevel4OnField(null); + List materialExceptNode = materialList + .Where(c => !(c.IsCode(CardId.NodeRyzeal) && !c.IsDisabled() && !activatedCardIdList.Contains(CardId.NodeRyzeal))).ToList(); + + // abyss + ClientCard abyss = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(CardId.AbyssDweller)); + if (abyss != null) + { + if (AbyssDwellerSummonCheck()) + { + if (Card != abyss) return false; + + if (materialExceptNode.Count() >= 2) + { + AI.SelectMaterials(materialExceptNode.Take(2).ToList()); + return true; + } + if (materialList.Count() > 2 && !CheckCanContinueSummon()) + { + AI.SelectMaterials(materialList.Take(2).ToList()); + return true; + } + } + } + // 41 + ClientCard no41 = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir)); + if (no41 != null) + { + bool flag = hasNode; + flag &= Util.IsTurn1OrMain2(); + flag &= Bot.HasInExtra(CardId.TwinsOfTheEclipse) && Bot.MonsterZone.Any(c => c != null && c.IsFaceup() && c.HasType(CardType.Xyz)); + flag &= (GetNegateEffectCount() >= 2 || lockBirdSolved); + + if (flag) + { + if (Card != no41) return false; + + if (materialExceptNode.Count() >= 2) + { + AI.SelectMaterials(materialExceptNode.Take(2).ToList()); + return true; + } + if (materialList.Count() >= 2 && Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn)) + { + AI.SelectMaterials(materialList.Take(2).ToList()); + return true; + } + } + } + + // photon blast dragon + ClientCard photonDragon = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(CardId.StarliegePhotonBlastDragon)); + bool have2MaterialDuo = false; + if (photonDragon != null) + { + int duoDriveOverlayCount = 0; + foreach (ClientCard monster in Bot.MonsterZone) + { + if (monster == null || !monster.IsCode(CardId.RyzealDuodrive)) continue; + duoDriveOverlayCount += monster.Overlays.Count(); + } + + if (Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn)) duoDriveOverlayCount++; + have2MaterialDuo = duoDriveOverlayCount >= 2; + } + + if (photonDragon != null && have2MaterialDuo && enemyDeckTypeRecord.Contains(SetcodeSkyStriker)) + { + if (Card != photonDragon) return false; + + if (materialExceptNode.Count() >= 2) + { + AI.SelectMaterials(materialExceptNode.Take(2).ToList()); + return true; + } + } + + // 60 + ClientCard no60 = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(CardId.Number60DugaresTheTimeless)); + if (no60 != null && !lockBirdSolved) + { + bool flag = Bot.Deck.Count() > 2; + + if (flag) + { + if (Card != no60) return false; + + if (materialExceptNode.Count() >= 2) + { + AI.SelectMaterials(materialExceptNode.Take(2).ToList()); + return true; + } + if (materialList.Count() >= 2 && Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn)) + { + AI.SelectMaterials(materialList.Take(2).ToList()); + return true; + } + } + } + + if (photonDragon != null && have2MaterialDuo) + { + if (Card != photonDragon) return false; + + if (materialExceptNode.Count() >= 2) + { + AI.SelectMaterials(materialExceptNode.Take(2).ToList()); + return true; + } + } + + // tornado dragon + ClientCard deadnader = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(CardId.RyzealDeadnader)); + if (deadnader == null) + { + ClientCard tornadoDragon = Duel.MainPhase.SummonableCards.FirstOrDefault(c => c.IsCode(CardId.TornadoDragon)); + if (tornadoDragon != null && TornadoDragonSummonCheck() && Card == tornadoDragon) + { + if (materialExceptNode.Count() >= 2) + { + AI.SelectMaterials(materialExceptNode.Take(2).ToList()); + return true; + } + if (materialList.Count() >= 2 && Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn)) + { + AI.SelectMaterials(materialList.Take(2).ToList()); + return true; + } + } + } + + // deadnader + if (deadnader != null && Card == deadnader) + { + if (materialExceptNode.Count() >= 2) + { + AI.SelectMaterials(materialExceptNode.Take(2).ToList()); + return true; + } + if (materialList.Count() >= 2 && Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn)) + { + AI.SelectMaterials(materialList.Take(2).ToList()); + return true; + } + } + + // TODO + Logger.DebugWriteLine("Second: no monster to spsummon"); + + + return false; + } + + public bool TwinsOfTheEclipseSpSummon() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Extra)) return false; + if (Util.IsTurn1OrMain2()) + { + bool hasNode = Bot.HasInHand(CardId.NodeRyzeal) && !spSummonedCardIdList.Contains(CardId.NodeRyzeal); + hasNode |= Bot.HasInMonstersZone(CardId.NodeRyzeal, true, false, true); + if (Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn)) + { + hasNode |= Bot.Graveyard.Any(c => c.IsCode(CardId.NodeRyzeal)); + hasNode |= Bot.Banished.Any(c => c.IsFaceup() && c.IsCode(CardId.NodeRyzeal)); + } + hasNode &= !activatedCardIdList.Contains(CardId.NodeRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.NodeRyzeal); + + List materialList = new List(); + ClientCard duoDriver = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(CardId.RyzealDuodrive)); + if (activatedCardIdList.Contains(CardId.RyzealDuodrive + 1) && duoDriver != null) + { + materialList.Add(duoDriver); + hasNode |= !CheckWhetherWillbeRemoved() && duoDriver.Overlays.Any(id => id == CardId.NodeRyzeal); + } + ClientCard no60 = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(CardId.Number60DugaresTheTimeless)); + if (no60 != null && (activatedCardIdList.Contains(CardId.Number60DugaresTheTimeless) || no60.IsDisabled())) + { + materialList.Add(no60); + hasNode |= !CheckWhetherWillbeRemoved() && no60.Overlays.Any(id => id == CardId.NodeRyzeal); + } + ClientCard no41 = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsFaceup() && c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir)); + if (no41 != null) + { + materialList.Add(no41); + hasNode |= !CheckWhetherWillbeRemoved() && no41.Overlays.Any(id => id == CardId.NodeRyzeal); + } + + if (materialList.Count() >= 2 && hasNode) + { + AI.SelectMaterials(materialList); + return true; + } + } + else + { + if (botSolvedCardIdList.Contains(_CardId.EvilswarmExcitonKnight)) + { + return false; + } + + List materialList = GetLevel4OnField(null); + List xyzMonsterList = Bot.MonsterZone.Where(c => c != null && c.IsFaceup() && c.HasType(CardType.Xyz) && c.Rank == 4 && c.Attack < 2500).ToList(); + int level4Count = GetLevel4FinalCountOnField(true, out bool hasNode) + xyzMonsterList.Count(); + + if (level4Count < 4) return false; + + materialList.AddRange(xyzMonsterList); + materialList = materialList.Where(c => c != null && c.Attack < 2500).OrderBy(c => c.GetDefensePower()).Take(2).ToList(); + if (materialList.Count() >= 2) + { + // check whether enemy have monster with 2more less than 2500 + bool checkFlag = Enemy.MonsterZone.Count(c => c != null && c.GetDefensePower() < 2500) >= 2 && !CheckWhetherNegated(true, true, CardType.Monster) + && !DefaultCheckWhetherCardIdIsNegated(CardId.TwinsOfTheEclipse); + if (checkFlag && materialList.Sum(c => c.Attack) < 5000) + { + AI.SelectMaterials(materialList); + return true; + } + else if (materialList.Sum(c => botSolvedCardIdList.Contains(CardId.RyzealPlugIn) && !c.HasType(CardType.Xyz) ? 0 : c.Attack) < 2500 + && !Duel.MainPhase.SpecialSummonableCards.Any(c => c.IsCode(CardId.RyzealDeadnader))) + { + AI.SelectMaterials(materialList); + return true; + } + } + } + + return false; + } + + public bool FinalXyzSummon() + { + if (Card.Location != CardLocation.Extra) return false; + + int level4Count = GetLevel4FinalCountOnField(false, out _); + bool result = FinalXyzSummonInner(); + Logger.DebugWriteLine("Final Xyz Count: " + level4Count.ToString()); + Logger.DebugWriteLine("Final Xyz Summon: " + result.ToString()); + + return result; + } + + public bool FinalXyzSummonInner() + { + // summon after duo driver + if (RyzealDuodriveSpSummonCheck()) + { + Logger.DebugWriteLine("Final: summon duodriver first"); + return false; + } + + int level4Count = GetLevel4FinalCountOnField(false, out _); + if (level4Count >= 4) return false; + + // No.41 + ClientCard no41 = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir)); + if (no41 != null) + { + if (Number41BagooskatheTerriblyTiredTapirSummonCheck()) + { + if (Card != no41) return false; + + // Select 2 monster with lowest defense + List materialList = GetLevel4OnField(null); + if (materialList.Count() >= 2) + { + AI.SelectMaterials(materialList); + return true; + } + } + } + + // abyss + ClientCard abyss = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(CardId.AbyssDweller)); + if (abyss != null) + { + if (AbyssDwellerSummonCheck()) + { + if (Card != abyss) return false; + + // Select 2 monster with lowest defense + List materialList = GetLevel4OnField(null); + if (materialList.Count() >= 2) + { + AI.SelectMaterials(materialList); + return true; + } + } + } + // deadnader + ClientCard deadnader = Duel.MainPhase.SpecialSummonableCards.FirstOrDefault(c => c.IsCode(CardId.RyzealDeadnader)); + if (deadnader != null) + { + List materialList = GetLevel4OnField(c => c.HasSetcode(SetcodeRyzeal)); + if (materialList.Count() >= 2) + { + if (Card != deadnader) return false; + AI.SelectMaterials(materialList); + return true; + } + } + + // tornado dragon + if (deadnader == null) + { + ClientCard tornadoDragon = Duel.MainPhase.SummonableCards.FirstOrDefault(c => c.IsCode(CardId.TornadoDragon)); + if (tornadoDragon != null && TornadoDragonSummonCheck()) + { + // Select 2 monster with lowest defense + List materialList = GetLevel4OnField(null); + if (materialList.Count() >= 2) + { + AI.SelectMaterials(materialList); + return true; + } + } + } + + return false; + } + + public bool DonnerDaggerFurHireSpSummon() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Extra)) + { + return false; + } + bool haveEnemyTarget = Enemy.MonsterZone.Any(c => c != null && !c.IsShouldNotBeMonsterTarget()) && !CheckWhetherNegated(true, true, CardType.Monster); + + List illegalList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.Level != 4 && card.Rank != 4).OrderBy(c => c.GetDefensePower()).ToList(); + bool necessary = Bot.HasInHand(CardId.ExRyzeal) && !spSummonedCardIdList.Contains(CardId.ExRyzeal) && !activatedCardIdList.Contains(CardId.ExRyzeal) + && illegalList.Count() > 0; + bool needDestory = !CheckWhetherNegated(true, true, CardType.Monster) + && Enemy.MonsterZone.Any(c => c != null && !c.IsShouldNotBeMonsterTarget() && c.IsFloodgate() && !c.IsDisabled()); + necessary |= needDestory; + + if (necessary) + { + if (illegalList.Count() == 1 && haveEnemyTarget) + { + List otherMaterialList = Bot.GetMonsters().Where(card => card.IsFaceup() && !illegalList.Contains(card) && (card.Owner == 1 || !card.HasType(CardType.Xyz))).ToList(); + otherMaterialList.Sort(CardContainer.CompareCardAttack); + illegalList.AddRange(otherMaterialList); + } + + if (illegalList.Count() > 1) + { + List materialList = illegalList.Take(2).ToList(); + if (Util.GetBotAvailZonesFromExtraDeck(materialList) > 0) + { + AI.SelectMaterials(materialList); + return true; + } + } + } + + if (Duel.Phase == DuelPhase.Main2) + { + List enemyOwnerMonsters = Bot.MonsterZone.Where(c => c != null && c.IsFaceup() && c.Owner == 1).OrderBy(c => c.GetDefensePower()).ToList(); + if (enemyOwnerMonsters.Count() > 0 && haveEnemyTarget) + { + if (enemyOwnerMonsters.Count() == 1) + { + List otherMaterialList = Bot.GetMonsters() + .Where(card => card.IsFaceup() && !enemyOwnerMonsters.Contains(card) && (!card.HasType(CardType.Xyz) || card.Overlays.Count() == 0)) + .OrderBy(c => c.GetDefensePower()).ToList(); + enemyOwnerMonsters.AddRange(otherMaterialList); + } + + if (enemyOwnerMonsters.Count() > 1) + { + List materialList = enemyOwnerMonsters.Take(2).ToList(); + if (Util.GetBotAvailZonesFromExtraDeck(materialList) > 0) + { + AI.SelectMaterials(materialList); + return true; + } + } + } + } + + return false; + } + + // TODO extra effect + + + public bool MereologicAggregatorActivateFirst() + { + List> multiNegateFuncList = new List> { + {c => c.IsCode(44665365, 48546368, 54178659) && c.IsMonster() }, + {c => c.IsCode(4280258) && c.Attack >= 800 }, + {c => c.IsCode(47297616) && c.Attack >= 500 && c.Defense >= 500 }, + {c => c.IsCode(19652159) && c.Attack >= 1000 && c.Defense >= 1000 }, + {c => c.IsCode(79600447) && Enemy.MonsterZone.Any(m => m != null && m.IsFaceup() && m.IsCode(23288411) && m.Attack >= 1000) } + }; + List searchCardList = new List(Enemy.GetMonsters()); + searchCardList.AddRange(Enemy.GetSpells()); + foreach (ClientCard card in searchCardList) + { + if (card == null || card.IsFacedown() || card.IsDisabled()) continue; + foreach (Func func in multiNegateFuncList) + { + if (func(card)) + { + AI.SelectCard(card); + currentNegateCardList.Add(card); + activatedCardIdList.Add(Card.Id + 2); + return true; + } + } + } + return false; + } + + public bool MereologicAggregatorActivateLater() + { + if (CheckWhetherNegated(true)) return false; + + ClientCard lastChainCard = Util.GetLastChainCard(); + + // for Chain1 ExRyzeal Chain2 Mereo to negate No41 + if (lastChainCard != null && lastChainCard.Controller == 0 && lastChainCard.IsCode(CardId.ExRyzeal)) + { + ClientCard no41 = Enemy.GetMonsters().FirstOrDefault(c => + c.IsFaceup() && !c.IsDisabled() && c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir) && c.HasPosition(CardPosition.FaceUpDefence) && !currentNegateCardList.Contains(c)); + if (no41 != null) + { + currentNegateCardList.Add(no41); + AI.SelectCard(no41); + activatedCardIdList.Add(Card.Id + 2); + return true; + } + } + + List targetList = GetNormalEnemyTargetList(true, false, CardType.Monster, true).Where(c => c.IsFaceup() && !c.IsDisabled()).ToList(); + if (targetList.Count() > 0) + { + currentNegateCardList.Add(targetList[0]); + AI.SelectCard(targetList); + activatedCardIdList.Add(Card.Id + 2); + return true; + } + + // protect chain + if (lastChainCard != null && lastChainCard.Controller == 0 && lastChainCard.IsCode(CardId.ExRyzeal)) + { + foreach (ClientCard card in Bot.GetMonsters()) + { + if (card.IsFacedown() || Duel.CurrentChain.Contains(card) || card.IsDisabled() || !card.HasType(CardType.Effect)) continue; + bool flag = card.IsCode(CardId.IceRyzeal, CardId.ThodeRyzeal); + flag |= card.IsCode(CardId.NodeRyzeal) && activatedCardIdList.Contains(CardId.NodeRyzeal); + flag |= card.HasType(CardType.Xyz) && !card.HasXyzMaterial() && !card.IsCode(CardId.RyzealDeadnader, CardId.RyzealDuodrive, CardId.FullArmoredUtopicRayLancer); + if (flag) + { + AI.SelectCard(card); + activatedCardIdList.Add(Card.Id + 2); + return true; + } + } + } + + return false; + } + + public bool RyzealDeadnaderActivate() + { + if (ActivateDescription == 96) + { + Logger.DebugWriteLine("** deadnader replace destroy"); + if (deadnaderDestroySelf != Card) + { + activatedCardIdList.Add(CardId.RyzealDeadnader + 2); + return true; + } + return false; + } + if (CheckWhetherNegated(true)) return false; + if (ActivateDescription == Util.GetStringId(CardId.RyzealDeadnader, 1)) + { + // destroy self + bool shouldDestroySelf = false; + bool willBeNegated = false; + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && lastChainCard.Controller == 1 && lastChainCard.IsCode(targetNegateIdList)) + { + shouldDestroySelf = true; + willBeNegated = true; + } + shouldDestroySelf |= Duel.CurrentChain.Any(c => c != null && c.Controller == 1 && !c.IsDisabled() && !DefaultCheckWhetherCardIdIsNegated(c.Id) + && c.IsCode(_CardId.EvenlyMatched, 35480699)); + shouldDestroySelf |= Card.Overlays.Count() == 1 && !activatedCardIdList.Contains(CardId.RyzealDeadnader) + && GetProblematicEnemyCardList(true, false, CardType.Monster).Count() == 0; + + if (shouldDestroySelf) + { + bool canRebornSelf = Bot.SpellZone.Count(c => c != null && c.IsFacedown() && c.IsCode(CardId.RyzealPlugIn) && !Duel.ChainTargets.Contains(c)) > 0; + bool canActivateTwin = !activatedCardIdList.Contains(CardId.TwinsOfTheEclipse + 1) && !DefaultCheckWhetherCardIdIsNegated(CardId.TwinsOfTheEclipse) + && !CheckWhetherWillbeRemoved(); + canRebornSelf |= canActivateTwin && Card.Overlays.Contains(CardId.TwinsOfTheEclipse); + if (Duel.CurrentChain.Any(c => c != null && c.Controller == 1 && !c.IsDisabled() && !DefaultCheckWhetherCardIdIsNegated(c.Id) + && c.IsCode(_CardId.EvenlyMatched))) + { + canRebornSelf |= Bot.MonsterZone.Any(c => c != null && c.HasType(CardType.Xyz) && c.Overlays.Contains(CardId.TwinsOfTheEclipse)); + } + + if (canRebornSelf) + { + deadnaderDestroySelf = Card; + return true; + } + } + + + // destroy + if (CanDestroyList(willBeNegated).Count() > 0) + { + return true; + } + } + else + { + // attach + activatedCardIdList.Add(Card.Id); + return true; + } + return false; + + } + + public bool RyzealDuodriveActivate() + { + if (CheckWhetherNegated(true)) return false; + + if (ActivateDescription == Util.GetStringId(CardId.RyzealDuodrive, 1)) + { + int overlayCount = 0; + foreach (ClientCard card in Bot.MonsterZone) + { + if (card == null || card.Overlays.Count() == 0) continue; + if (card.IsCode(CardId.Number60DugaresTheTimeless) && !card.IsDisabled() && !activatedCardIdList.Contains(CardId.Number60DugaresTheTimeless)) + { + continue; + } + overlayCount += card.Overlays.Count(); + } + if (overlayCount >= 2) + { + // deattach and search + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } else + { + // attach + activatedCardIdList.Add(Card.Id); + return true; + } + + return false; + } + + public bool TwinsOfTheEclipseActivate() + { + if (Card.Location == CardLocation.MonsterZone) + { + // double attack + // dump remove material + if (CheckWhetherNegated(true)) return Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn); + activatedCardIdList.Add(Card.Id); + return true; + + } else if (Card.Location == CardLocation.Grave) + { + // spsummon + if (CheckWhetherNegated(true)) return false; + + activatedCardIdList.Add(Card.Id + 1); + ClientCard rebornTarget = TwinsOfTheEclipseRebornTarget(null); + if (rebornTarget != null) + { + ClientCard mereo = Bot.Graveyard.FirstOrDefault(c => c.IsCode(CardId.MereologicAggregator)); + if (mereo != null) + { + AI.SelectCard(new List { rebornTarget, mereo }); + return true; + } + ClientCard nonLightDark = Bot.Graveyard.FirstOrDefault(c => c.HasType(CardType.Xyz) && !c.HasAttribute((CardAttribute)attrbuteLightDark)); + if (nonLightDark != null) + { + AI.SelectCard(new List { rebornTarget, nonLightDark }); + return true; + } + ClientCard xyzMonster = Bot.Graveyard.FirstOrDefault(c => c.HasType(CardType.Xyz)); + if (xyzMonster != null) + { + AI.SelectCard(new List { rebornTarget, xyzMonster }); + return true; + } + } + + // although cannot find target, still should activate. + Logger.DebugWriteLine("** Twins of The Eclipse: although cannot find target, still should activate."); + return true; + } + + return false; + } + + public ClientCard TwinsOfTheEclipseRebornTarget(List targetList) + { + if (targetList == null) + { + targetList = Bot.Graveyard.Where(c => c.HasType(CardType.Xyz) && c.IsCanRevive()).ToList(); + } + ClientCard duoDriver = targetList.FirstOrDefault(c => c.IsCode(CardId.RyzealDuodrive)); + ClientCard deadnader = targetList.FirstOrDefault(c => c.IsCode(CardId.RyzealDeadnader)); + ClientCard no41 = targetList.FirstOrDefault(c => c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir)); + ClientCard abyssDweller = targetList.FirstOrDefault(c => c.IsCode(CardId.AbyssDweller)); + + if (no41 != null && !DefaultCheckWhetherCardIdIsNegated(_CardId.Number41BagooskatheTerriblyTiredTapir) + && !(deadnader != null && !activatedCardIdList.Contains(CardId.RyzealDeadnader)) + && !(Duel.Turn == 1 && duoDriver != null)) + { + return no41; + } + + if (abyssDweller != null && !DefaultCheckWhetherCardIdIsNegated(CardId.AbyssDweller) && !botSolvedCardIdList.Contains(CardId.AbyssDweller) + && AbyssDwellerSummonCheck()) + { + return abyssDweller; + } + + if (deadnader != null) + { + return deadnader; + } + if (duoDriver != null && (!activatedCardIdList.Contains(CardId.RyzealDuodrive + 1) || Bot.HasInHandOrInSpellZone(CardId.RyzealCross))) + { + return duoDriver; + } + + // random spsummon + if (targetList.Count() > 0) + { + return ShuffleList(targetList)[0]; + } + return null; + } + + public List CanDestroyList(bool ignoreCurrentDestroy = false) + { + List destroyTargetList = GetNormalEnemyTargetList(true, ignoreCurrentDestroy, CardType.Monster).Except(currentNegateCardList).ToList(); + + List cannotDestroyList = new List(NotToDestroySpellTrap); + destroyTargetList.RemoveAll(c => c.IsCode(cannotDestroyList)); + + List undestoryableCardIdlist = new List { 94977269, 58604027, 8062132, 10817524, 53315891, 10000090, 86221741, 71222868, + 83257450, 97489701, 97165977, 24550676, 55410871, 72664875, 85908279, 13331639, 20654247, 43228023, 99585850, 92770064, 10497636, 77313225 }; + destroyTargetList.RemoveAll(c => !c.IsDisabled() && c.IsCode(undestoryableCardIdlist)); + + destroyTargetList.RemoveAll(c => !c.IsDisabled() && c.HasSetcode(SetcodeMajespecter)); + + if (Enemy.GetSpells().Any(c => c.IsFacedown()) || Enemy.GetMonsters().Any(c => c.IsFacedown())) + { + destroyTargetList.RemoveAll(c => c.IsCode(81497285)); + } + destroyTargetList.RemoveAll(c => !c.IsDisabled() && c.HasSetcode(SetcodeMajespecter)); + + + return destroyTargetList; + } + + public bool TornadoDragonActivate() + { + if (CheckWhetherNegated(true)) return false; + + List spells = Enemy.GetSpells(); + if (spells.Count == 0) + return false; + + // destroy faceup card first + ClientCard selected = Enemy.SpellZone.GetFloodgate(); + if (selected == null && Duel.Player == 1) + { + List targetList = spells.Where(c => c.IsFaceup() && !NotToDestroySpellTrap.Contains(c.Id) && !currentDestroyCardList.Contains(c) + && c.HasType(CardType.Continuous | CardType.Equip | CardType.Field | CardType.Pendulum)).ToList(); + if (targetList.Count() > 0) + { + selected = ShuffleList(targetList)[0]; + } + } + + if (selected != null) + { + currentDestroyCardList.Add(selected); + AI.SelectCard(selected); + return true; + } + + // destroy face-down card + if (selected == null) + { + List setThisTurnList = Enemy.SpellZone.Where(c => c != null && c.IsFacedown() && !currentDestroyCardList.Contains(c) + && enemyPlaceThisTurn.Contains(c)).ToList(); + if (setThisTurnList.Count() > 0) + { + selected = ShuffleList(setThisTurnList)[0]; + } + } + if (selected == null) + { + List setThisTurnList = Enemy.SpellZone.Where(c => c != null && c.IsFacedown() && !currentDestroyCardList.Contains(c)).ToList(); + if (setThisTurnList.Count() > 0) + { + selected = ShuffleList(setThisTurnList)[0]; + } + } + + bool flag = Duel.Player == 0; + flag |= Duel.Player == 1 && Duel.Phase == DuelPhase.End; + flag |= DefaultOnBecomeTarget(); + + if (flag) + { + currentDestroyCardList.Add(selected); + AI.SelectCard(selected); + return true; + } + + return false; + } + + public bool EvilswarmExcitonKnightActivate() + { + if (CheckWhetherNegated(true)) return false; + return DefaultEvilswarmExcitonKnightEffect(); + } + + public bool AbyssDwellerActivate() + { + if (botSolvedCardIdList.Contains(CardId.AbyssDweller)) return false; + + if (Duel.Player == 0 && Bot.HasInHandOrInSpellZone(CardId.RyzealPlugIn)) + { + List checkIdList = new List { CardId.NodeRyzeal, CardId.ThodeRyzeal, CardId.ExRyzeal }; + foreach (int checkId in checkIdList) + { + if (Card.Overlays.Contains(checkId) && !Bot.HasInHand(checkId) && !activatedCardIdList.Contains(checkId)) + { + return true; + } + return false; + } + } + if (Duel.Player == 1) + { + if (CheckWhetherNegated(true)) return false; + if (enemyDeckTypeRecord.Contains(SetcodeAtlantean)) return true; + return Enemy.GetMonsterCount() + Enemy.GetSpellCount() > 0; + } + + return false; + } + + public bool Number60DugaresTheTimelessActivate() + { + if (CheckWhetherNegated(true)) return false; + if (Number60DugaresTheTimelessDrawEffect() || Number60DugaresTheTimelessDoubleTarget() != null || Number60DugaresTheTimelessRebornEffect()) + { + activatedCardIdList.Add(Card.Id); + return true; + } + return false; + } + + public bool Number60DugaresTheTimelessDrawEffect() + { + if (lockBirdSolved || Bot.Deck.Count < 2) return false; + activatedCardIdList.Add(Card.Id); + return true; + } + + public ClientCard Number60DugaresTheTimelessDoubleTarget() + { + if (Util.IsTurn1OrMain2()) return null; + ClientCard maxAttackMonster = Bot.MonsterZone.Where(c => c != null && (c.HasPosition(CardPosition.FaceUpAttack) || !summonThisTurn.Contains(c))) + .OrderByDescending(c => c.Attack).FirstOrDefault(); + + if (maxAttackMonster != null) + { + int maxBotAttack = maxAttackMonster.Attack; + + // defeat enemy monster + ClientCard bestEnemyMonster = Enemy.MonsterZone.Where(c => c != null && c.IsFaceup() && (c.IsDisabled() || !c.IsMonsterInvincible())) + .OrderByDescending(c => c.GetDefensePower()).FirstOrDefault(); + if (bestEnemyMonster != null) + { + int maxEnemyPower = bestEnemyMonster.GetDefensePower(); + if (bestEnemyMonster.IsAttack()) maxEnemyPower -= 1; + if (maxBotAttack < maxEnemyPower && maxBotAttack * 2 > maxEnemyPower) + { + return maxAttackMonster; + } + } + + // direct attack + if (!botSolvedCardIdList.Contains(_CardId.EvilswarmExcitonKnight)) + { + int currentAttack = GetBotCurrentTotalAttack(); + if (currentAttack < Enemy.LifePoints && currentAttack + maxBotAttack >= Enemy.LifePoints) + { + return maxAttackMonster; + } + } + } + + return null; + } + + public bool Number60DugaresTheTimelessRebornEffect() + { + // not used + + return false; + } + + public bool DonnerDaggerFurHireActivate() + { + if (CheckAtAdvantage() && !Bot.HasInHand(CardId.ExRyzeal)) + { + return false; + } + + ClientCard targetCard = GetProblematicEnemyMonster(canBeTarget: true, selfType: CardType.Monster); + if (targetCard == null) + { + List enemyMonsters = Enemy.GetMonsters(); + if (enemyMonsters.Count() > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + targetCard = enemyMonsters[0]; + } + } + + if (targetCard != null) + { + AI.SelectCard(Card); + AI.SelectNextCard(targetCard); + currentDestroyCardList.Add(targetCard); + return true; + } + + return false; + } + + + + public bool Level4Summon() + { + if (CheckShouldNoMoreSpSummon(CardLocation.Hand | CardLocation.Extra)) return false; + ClientCard leastAttackLevel4 = Bot.Hand.Where(c => c.Level == 4).OrderBy(c => c.Attack).FirstOrDefault(); + if (leastAttackLevel4 == null || Card != leastAttackLevel4) return false; + + if (GetLevel4CountOnField() == 1) + { + ClientCard target = Duel.MainPhase.SummonableCards.Where(c => c != null && c.Level == 4).OrderBy(c => c.Attack).FirstOrDefault(); + if (Card != target) return false; + summonCount -= 1; + return true; + } + + return false; + } + + + public bool SpellSetCheck() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + + // select place + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay))) + { + // do not set infinite impermanence if don't need to set other cards + if (Card.IsCode(_CardId.InfiniteImpermanence) && Bot.GetMonsterCount() == 0 && Bot.GetSpellCount() == 0 + && !Bot.Hand.Any(c => !c.IsCode(_CardId.InfiniteImpermanence) && (c.IsTrap() || c.HasType(CardType.QuickPlay))) + && Bot.Hand.Count() <= 6) + { + return false; + } + + if (Card.IsCode(CardId.RyzealPlugIn)) + { + bool targetFlag = Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && (c.Level == 4 || c.IsCanRevive())); + targetFlag |= Bot.Banished.Any(c => c != null && c.IsFaceup() && c.HasSetcode(SetcodeRyzeal) && (c.Level == 4 || c.IsCanRevive())); + if (!targetFlag) + { + return false; + } + } + + List avoid_list = new List(); + int setForInfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + setForInfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setForInfiniteImpermanence); + return true; + } + else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } + else + { + SelectSTPlace(); + } + return true; + } + + else if (Enemy.HasInSpellZone(_CardId.AntiSpellFragrance, true) || Bot.HasInSpellZone(_CardId.AntiSpellFragrance, true)) + { + if (Card.IsSpell() && !Bot.HasInSpellZone(Card.Id)) + { + SelectSTPlace(); + return true; + } + } + + return false; + } + + public bool ChangePositionFirst() + { + if (Card.IsFacedown() && Card.Level == 4) + { + return true; + } + + if (Enemy.MonsterZone.Any(c => c != null && c.HasPosition(CardPosition.FaceUpDefence) && !c.IsDisabled() && c.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir))) + { + return false; + } + + if (Card.IsCode(_CardId.Number41BagooskatheTerriblyTiredTapir)) + { + bool haveDangerMonster = Enemy.MonsterZone.Any(c => c != null && c.IsFloodgate() && !c.IsDisabled()); + if (Card.IsDefense()) + { + return !haveDangerMonster && !Util.IsTurn1OrMain2(); + } else + { + return haveDangerMonster || Util.IsTurn1OrMain2(); + } + } + + return false; + } + + protected override bool DefaultSetForDiabellze() + { + if (base.DefaultSetForDiabellze()) + { + SelectSTPlace(Card, true); + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ST1732Executor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ST1732Executor.cs new file mode 100644 index 0000000..92e052d --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ST1732Executor.cs @@ -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 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 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 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 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 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 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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SalamangreatExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SalamangreatExecutor.cs new file mode 100644 index 0000000..995b463 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SalamangreatExecutor.cs @@ -0,0 +1,1268 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using YGOSharp.OCGWrapper.Enums; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Salamangreat", "AI_Salamangreat")] + class SalamangreatExecutor : DefaultExecutor + { + bool foxyPopEnemySpell = false; + bool wasGazelleSummonedThisTurn = false; + bool wasFieldspellUsedThisTurn = false; + bool wasWolfSummonedUsingItself = false; + int sunlightPosition = 0; + bool wasVeilynxSummonedThisTurn = false; + bool falcoHitGY = false; + List CombosInHand; + + + List Impermanence_list = new List(); + public class CardId + { + public const int JackJaguar = 56003780; + public const int EffectVeiler = 97268402; + public const int LadyDebug = 16188701; + public const int Foxy = 94620082; + public const int Gazelle = 26889158; + public const int Fowl = 89662401; + public const int Falco = 20618081; + public const int Spinny = 52277807; + public const int MaxxC = 23434538; + public const int AshBlossom = 14558127; + + public const int FusionOfFire = 25800447; + public const int Circle = 52155219; + public const int HarpieFeatherDuster = 18144507; + public const int FoolishBurial = 81439174; + public const int Sanctuary = 1295111; + public const int CalledByTheGrave = 24224830; + public const int SalamangreatRage = 14934922; + public const int SalamangreatRoar = 51339637; + public const int Impermanence = 10045474; + public const int SolemnJudgment = 41420027; + public const int SolemnStrike = 40605147; + + public const int SalamangreatVioletChimera = 37261776; + public const int ExcitionKnight = 46772449; + public const int MirageStallio = 87327776; + public const int SunlightWolf = 87871125; + public const int Borrelload = 31833038; + public const int HeatLeo = 41463181; + public const int Veilynx = 14812471; + public const int Charmer = 48815792; + public const int KnightmarePheonix = 2857636; + public const int Borrelsword = 85289965; + + public const int GO_SR = 59438930; + public const int DarkHole = 53129443; + public const int NaturalBeast = 33198837; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecreel = 51452091; + public const int Anti_Spell = 58921041; + public const int Hayate = 8491308; + public const int Raye = 26077387; + public const int Drones_Token = 52340445; + public const int Iblee = 10158145; + public const int ImperialOrder = 61740673; + public const int TornadoDragon = 6983839; + } + + List Combo_cards = new List() + { + CardId.Spinny, + CardId.JackJaguar, + CardId.Fowl, + CardId.Foxy, + CardId.Falco, + CardId.Circle, + CardId.Gazelle, + CardId.FoolishBurial + }; + + List normal_counter = new List + { + 53262004, 98338152, 32617464, 45041488, CardId.SolemnStrike, + 61257789, 23440231, 27354732, 12408276, 82419869, CardId.Impermanence, + 49680980, 18621798, 38814750, 17266660, 94689635,CardId.AshBlossom, + 74762582, 75286651, 4810828, 44665365, 21123811, _CardId.CrystalWingSynchroDragon, + 82044279, 82044280, 79606837, 10443957, 1621413, + 90809975, 8165596, 9753964, 53347303, 88307361, _CardId.GamecieltheSeaTurtleKaiju, + 5818294, 2948263, 6150044, 26268488, 51447164, _CardId.JizukirutheStarDestroyingKaiju, + 97268402 + }; + + List should_not_negate = new List + { + 81275020, 28985331 + }; + + List salamangreat_links = new List + { + CardId.HeatLeo, + CardId.SunlightWolf, + CardId.Veilynx + }; + + List JackJaguarTargets = new List + { + CardId.SunlightWolf, + CardId.MirageStallio, + CardId.HeatLeo + }; + + + List salamangreat_combopieces = new List + { + CardId.Gazelle, + CardId.Spinny, + CardId.JackJaguar, + CardId.Foxy, + CardId.Circle, + CardId.Falco + }; + + List WolfMaterials = new List + { + CardId.Veilynx, + CardId.JackJaguar, + CardId.Falco, + CardId.Foxy, + CardId.MirageStallio, + CardId.Gazelle + }; + + List salamangreat_spellTrap = new List + { + CardId.SalamangreatRoar, + CardId.SalamangreatRage, + CardId.Circle, + CardId.Sanctuary + }; + private bool falcoUsedReturnST; + private bool wasStallioActivated; + private bool wasWolfActivatedThisTurn; + + bool JackJaguarActivatedThisTurn = false; + bool FoxyActivatedThisTurn = false; + + public SalamangreatExecutor(GameAI ai, Duel duel) : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, CardId.HarpieFeatherDuster); + AddExecutor(ExecutorType.Activate, CardId.MaxxC, G_activate); + AddExecutor(ExecutorType.Activate, CardId.CalledByTheGrave, Called_activate); + AddExecutor(ExecutorType.Activate, CardId.AshBlossom, Hand_act_eff); + AddExecutor(ExecutorType.Activate, CardId.EffectVeiler, DefaultBreakthroughSkill); + AddExecutor(ExecutorType.Activate, CardId.Impermanence, Impermanence_activate); + AddExecutor(ExecutorType.Activate, CardId.SalamangreatRoar, SolemnJudgment_activate); + AddExecutor(ExecutorType.Activate, CardId.SolemnStrike, SolemnStrike_activate); + AddExecutor(ExecutorType.Activate, CardId.SolemnJudgment, SolemnJudgment_activate); + AddExecutor(ExecutorType.Activate, CardId.Sanctuary, Sanctuary_activate); + + AddExecutor(ExecutorType.Activate, CardId.Charmer); + AddExecutor(ExecutorType.Activate, CardId.SunlightWolf, Wolf_activate); + AddExecutor(ExecutorType.Activate, CardId.LadyDebug, Fadydebug_activate); + AddExecutor(ExecutorType.Activate, CardId.Foxy, Foxy_activate); + AddExecutor(ExecutorType.Activate, CardId.Falco, Falco_activate); + AddExecutor(ExecutorType.Activate, CardId.Circle, Circle_activate); + AddExecutor(ExecutorType.Activate, CardId.Borrelsword, Borrelsword_eff); + AddExecutor(ExecutorType.Activate, CardId.Gazelle, Gazelle_activate); + AddExecutor(ExecutorType.Activate, CardId.Spinny, Spinny_activate); + AddExecutor(ExecutorType.Activate, CardId.MirageStallio, Stallio_activate); + AddExecutor(ExecutorType.Activate, CardId.Veilynx); + + AddExecutor(ExecutorType.Activate, CardId.JackJaguar, JackJaguar_activate); + AddExecutor(ExecutorType.Summon, CardId.LadyDebug); + AddExecutor(ExecutorType.Summon, CardId.Foxy); + AddExecutor(ExecutorType.Summon, CardId.Spinny); + AddExecutor(ExecutorType.Summon, CardId.JackJaguar); + AddExecutor(ExecutorType.Summon, CardId.Gazelle); + AddExecutor(ExecutorType.Summon, CardId.Fowl); + AddExecutor(ExecutorType.Activate, CardId.Spinny, Spinny_activate); + AddExecutor(ExecutorType.Activate, CardId.HeatLeo, DefaultMysticalSpaceTyphoon); + + AddExecutor(ExecutorType.SpSummon, CardId.Borrelsword, Borrelsword_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Veilynx, Veilynx_summon); + AddExecutor(ExecutorType.SpSummon, CardId.MirageStallio, Stallio_summon); + AddExecutor(ExecutorType.Activate, CardId.MirageStallio, Stallio_activate); + AddExecutor(ExecutorType.SpSummon, CardId.Charmer, Charmer_summon); + AddExecutor(ExecutorType.SpSummon, CardId.SunlightWolf, SunlightWolf_summon); + AddExecutor(ExecutorType.SpSummon, CardId.HeatLeo, HeatLeo_summon); + + AddExecutor(ExecutorType.SpSummon, CardId.TornadoDragon); + AddExecutor(ExecutorType.Activate, CardId.TornadoDragon, DefaultMysticalSpaceTyphoon); + + AddExecutor(ExecutorType.Activate, CardId.SalamangreatRage, Rage_activate); + AddExecutor(ExecutorType.Activate, CardId.Fowl, Fowl_activate); + AddExecutor(ExecutorType.Activate, CardId.SunlightWolf, Wolf_activate); + AddExecutor(ExecutorType.Activate, CardId.Gazelle, Gazelle_activate); + AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurial_activate); + + AddExecutor(ExecutorType.Repos, DefaultMonsterRepos); + AddExecutor(ExecutorType.SpellSet, SpellSet); + + } + + public int get_Wolf_linkzone() + { + ClientCard WolfInExtra = Bot.GetMonstersInExtraZone().Where(x => x.Id == CardId.SunlightWolf).ToList().FirstOrDefault(x => x.Id == CardId.SunlightWolf); + if (WolfInExtra != null) + { + int zone = WolfInExtra.Position; + if (zone == 5) return 1; + if (zone == 6) return 3; + } + return -1; + } + + private bool Charmer_summon() + { + if (Duel.Phase != DuelPhase.Main1) return false; + if (Duel.Turn == 1) return false; + if (Enemy.Graveyard.Where(x => x.Attribute == (int)CardAttribute.Fire).Count() > 0 + && (Bot.GetMonstersInExtraZone().Count == 0 + || Bot.GetMonstersInExtraZone().Where(x => + (x.Id == CardId.Veilynx + || x.Id == CardId.MirageStallio) + && x.Owner == 0).Count() == 1)) + { + List material_list = new List(); + List bot_monster = Bot.GetMonsters(); + bot_monster.Sort(CardContainer.CompareCardAttack); + //bot_monster.Reverse(); + int link_count = 0; + foreach (ClientCard card in bot_monster) + { + if (card.IsFacedown()) continue; + if (!material_list.Contains(card) && card.LinkCount < 2) + { + material_list.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 4) break; + } + } + if (link_count >= 3) + { + AI.SelectCard(CardId.Veilynx); + return true; + } + } + return false; + } + + private bool HeatLeo_summon() + { + if (Duel.Turn == 1) return false; + if (Duel.Phase != DuelPhase.Main1) return false; + if (wasWolfSummonedUsingItself && Bot.GetMonsters().Count() <= 3) return false; + + ClientCard self_best = Util.GetBestBotMonster(true); + int self_power = (self_best != null) ? self_best.Attack : 0; + ClientCard enemy_best = Util.GetBestEnemyMonster(true); + int enemy_power = (enemy_best != null) ? enemy_best.GetDefensePower() : 0; + if (enemy_power < self_power) return false; + + if (Enemy.GetSpells().Where(x => x.IsFloodgate()).Count() > 0) + { + List material_list = new List(); + List bot_monster = Bot.GetMonsters(); + bot_monster.Sort(CardContainer.CompareCardAttack); + //bot_monster.Reverse(); + int link_count = 0; + + foreach (ClientCard card in bot_monster) + { + if (card.IsFacedown()) continue; + if (!material_list.Contains(card) && card.LinkCount < 2) + { + material_list.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 3) break; + } + } + if (link_count >= 3) + { + AI.SelectMaterials(material_list); + return true; + } + } + return false; + } + + private bool Stallio_summon() + { + if (!wasStallioActivated) + { + AI.SelectMaterials(CardId.Spinny); + return true; + } + return false; + } + + private bool SunlightWolf_summon() + { + if (Bot.HasInMonstersZone(CardId.SunlightWolf)) + { + if (wasWolfSummonedUsingItself) + { + return false; + } + + if (!wasFieldspellUsedThisTurn && Bot.HasInGraveyard(salamangreat_spellTrap) || Bot.HasInHandOrInSpellZone(CardId.SalamangreatRage)) + { + AI.SelectOption(1); + AI.SelectMaterials(new List() { + CardId.SunlightWolf, + CardId.Veilynx, + CardId.JackJaguar, + CardId.Gazelle + }); + wasWolfSummonedUsingItself = true; + AI.SelectPlace(sunlightPosition); + return true; + } + else + { + return false; + } + } + + wasWolfSummonedUsingItself = false; + if (Bot.HasInMonstersZone(CardId.Veilynx)) + { + + if (Bot.HasInMonstersZone(CardId.MirageStallio) + && Bot.HasInMonstersZone(CardId.Veilynx) + && Bot.HasInMonstersZone(CardId.Gazelle)) + { + AI.SelectCard(CardId.Veilynx); + AI.SelectNextCard(CardId.MirageStallio); + } + else + { + AI.SelectCard(WolfMaterials); + AI.SelectNextCard(WolfMaterials); + } + sunlightPosition = SelectSetPlace(new List() { CardId.Veilynx }, true); + + AI.SelectPlace(sunlightPosition); + } + return true; + } + + private bool Wolf_activate() + { + wasWolfActivatedThisTurn = true; + AI.SelectCard(new List() { + CardId.Gazelle, + CardId.SalamangreatRoar, + CardId.SalamangreatRage, + CardId.Foxy, + CardId.AshBlossom, + CardId.Fowl, + CardId.SunlightWolf, + CardId.Veilynx, + CardId.HeatLeo, + CardId.Spinny + }); + return true; + } + + private bool Stallio_activate() + { + if (Card.Location == CardLocation.MonsterZone) + { + wasStallioActivated = true; + if (!wasGazelleSummonedThisTurn) + { + AI.SelectCard(CardId.Gazelle, CardId.Spinny); + AI.SelectNextCard(CardId.Gazelle); + return true; + } + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.JackJaguar)) + { + AI.SelectCard(CardId.Gazelle); + AI.SelectNextCard(CardId.JackJaguar); + return true; + } + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.Falco) && FalcoToGY(true)) + { + AI.SelectCard(CardId.Gazelle); + AI.SelectNextCard(CardId.Falco); + return true; + } + AI.SelectCard(CardId.Gazelle); + return true; + } + else + { + if (Util.GetBestEnemyMonster(canBeTarget: true) != null) + { + AI.SelectCard(Util.GetBestEnemyMonster(canBeTarget: true)); + return true; + } + } + return false; + } + + private bool Veilynx_summon() + { + if (wasStallioActivated && wasWolfActivatedThisTurn) + { + return false; + } + if ((wasStallioActivated + && !wasWolfActivatedThisTurn) + || + (!wasStallioActivated + && wasWolfActivatedThisTurn)) + { + return false; + } + if (Bot.HasInHand(CardId.Gazelle) + && !wasGazelleSummonedThisTurn + && !Bot.HasInGraveyard(CardId.JackJaguar) + && Bot.GetMonstersInMainZone().Where(x => x.Level == 3).Count() <= 1 + || (Bot.HasInMonstersZone(CardId.SunlightWolf) + && !Bot.HasInSpellZoneOrInGraveyard(CardId.Sanctuary) + && !wasWolfSummonedUsingItself)) + { + + var monsters = Bot.GetMonstersInMainZone(); + if (Bot.HasInMonstersZone(CardId.Veilynx) && monsters.Count == 2) + { + return false; + } + + monsters.Sort(CardContainer.CompareCardLevel); + monsters.Reverse(); + AI.SelectMaterials(monsters); + return true; + } + if (!Bot.HasInMonstersZone(CardId.Veilynx) + && + Bot.GetMonstersInMainZone().Count >= 3 + && + (Bot.GetMonstersInExtraZone().Where(x => x.Owner == 0).Count() == 0)) + { + var monsters = Bot.GetMonstersInMainZone(); + monsters.Sort(CardContainer.CompareCardLevel); + monsters.Reverse(); + AI.SelectMaterials(monsters); + return true; + } + + + if (CombosInHand.Where(x => x != CardId.Foxy).Where(x => x != CardId.Spinny).Count() == 0 + && Bot.HasInHand(CardId.Spinny)) + { + if (Bot.HasInMonstersZone(CardId.Gazelle) && Bot.HasInMonstersZone(CardId.SunlightWolf)) + { + AI.SelectMaterials(CardId.Gazelle); + return true; + } + if (!wasVeilynxSummonedThisTurn) + { + wasVeilynxSummonedThisTurn = true; + return true; + } + } + + return false; + } + + private bool JackJaguar_activate() + { + if (Card.Location == CardLocation.Grave) + { + if (Bot.HasInGraveyard(JackJaguarTargets) + || Bot.Graveyard.Where(x => x.Id == CardId.Veilynx).Count() >= 2 + || (!Bot.HasInGraveyard(salamangreat_spellTrap) + && Bot.HasInMonstersZone(CardId.SunlightWolf) + && Bot.HasInGraveyard(CardId.Gazelle) + && !Bot.HasInHand(CardId.Gazelle))) + { + JackJaguarActivatedThisTurn = true; + if (Bot.Graveyard.Where(x => x.Id == CardId.Veilynx).Count() >= 2 + && Bot.Graveyard.Select(x => x.Id).Intersect(JackJaguarTargets).Count() == 0) + { + AI.SelectCard(CardId.Veilynx); + return true; + } + AI.SelectCard(JackJaguarTargets); + return true; + } + } + return false; + } + + private bool Fowl_activate() + { + if (Card.Location == CardLocation.Hand) + { + return Bot.HasInMonstersZone(CardId.JackJaguar) && JackJaguarActivatedThisTurn; + } + return false; + } + + private bool Spinny_activate() + { + if (Card.Location == CardLocation.Hand) + { + if (Bot.HasInGraveyard(CardId.Foxy) && !FoxyActivatedThisTurn) return false; + if (CombosInHand.Where(x => x != CardId.Foxy).Where(x => x != CardId.Spinny).Count() == 0) + { + return false; + } + + if (!Bot.HasInMonstersZoneOrInGraveyard(CardId.Spinny) + && Util.GetBestBotMonster(true) != null + && !(Bot.GetMonsters().Count == 1 + && Bot.HasInMonstersZone(CardId.Spinny))) + { + AI.SelectCard(Util.GetBestBotMonster(true)); + return true; + } + } + return true; + } + + private bool Falco_activate() + { + if (!falcoUsedReturnST && falcoHitGY) + { + if (Bot.HasInGraveyard(salamangreat_spellTrap)) + { + falcoUsedReturnST = true; + AI.SelectCard(salamangreat_spellTrap); + return true; + } + } + return false; + } + + private bool Gazelle_activate() + { + wasGazelleSummonedThisTurn = true; + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.Spinny)) + { + AI.SelectCard(CardId.Spinny); + return true; + } + if (!Bot.HasInSpellZoneOrInGraveyard(CardId.SalamangreatRoar)) + { + AI.SelectCard(CardId.SalamangreatRoar); + return true; + } + if (!Bot.HasInSpellZoneOrInGraveyard(CardId.SalamangreatRage)) + { + AI.SelectCard(CardId.SalamangreatRage); + return true; + } + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.JackJaguar)) + { + AI.SelectCard(CardId.JackJaguar); + return true; + } + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.Foxy)) + { + AI.SelectCard(CardId.Foxy); + return true; + } + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.Falco)) + { + AI.SelectCard(CardId.Falco); + return true; + } + return true; + } + + private bool Foxy_activate() + { + if (Card.Location == CardLocation.MonsterZone) + { + + if (CombosInHand.Where(x => x != CardId.Foxy).Where(x => x != CardId.Spinny).Count() == 0 && Bot.HasInHand(CardId.Spinny)) + { + return false; + } + AI.SelectCard(salamangreat_combopieces); + FoxyActivatedThisTurn = true; + return true; + } + else + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Bot.HasInHand(CardId.Spinny) || FalcoToGY(false)) + { + if (Bot.HasInHand(CardId.Spinny) && !Bot.HasInGraveyard(CardId.Spinny)) + { + AI.SelectCard(CardId.Spinny); + } + else + { + if (FalcoToGY(false)) + { + AI.SelectCard(CardId.Falco); + } + else + { + return false; + } + } + if (Util.GetBestEnemySpell(true) != null) + { + AI.SelectNextCard(Util.GetBestEnemySpell(true)); + foxyPopEnemySpell = true; + } + FoxyActivatedThisTurn = true; + return true; + } + return false; + } + } + + private bool FalcoToGY(bool FromDeck) + { + if (FromDeck && Bot.Deck.ContainsCardWithId(CardId.Falco)) + { + if (Bot.HasInGraveyard(salamangreat_spellTrap)) + { + return true; + } + return false; + } + else + { + if (Bot.HasInHand(CardId.Falco) && Bot.HasInGraveyard(salamangreat_spellTrap)) + { + return true; + } + return false; + } + } + private bool Fadydebug_activate() + { + if (!Bot.HasInHand(CardId.Gazelle)) + { + AI.SelectCard(CardId.Gazelle); + return true; + } + if (!Bot.HasInHandOrInGraveyard(CardId.Spinny)) + { + AI.SelectCard(CardId.Spinny); + return true; + } + if (!Bot.HasInHand(CardId.Foxy)) + { + AI.SelectCard(CardId.Foxy); + return true; + } + return true; + } + + private bool Circle_activate() + { + var x = ActivateDescription; + if (ActivateDescription == Util.GetStringId(CardId.Circle, 0) || ActivateDescription == 0) + { + AI.SelectOption(0); + if (!Bot.HasInHand(CardId.Gazelle)) + { + AI.SelectCard(CardId.Gazelle); + return true; + } + if (!Bot.HasInHandOrInGraveyard(CardId.Spinny)) + { + AI.SelectCard(CardId.Spinny); + return true; + } + if (!Bot.HasInHand(CardId.Foxy)) + { + AI.SelectCard(CardId.Foxy); + return true; + } + if (!Bot.HasInHand(CardId.Fowl)) + { + AI.SelectCard(CardId.Fowl); + return true; + } + if (!Bot.HasInHand(CardId.JackJaguar)) + { + AI.SelectCard(CardId.JackJaguar); + return true; + } + if (!Bot.HasInHand(CardId.Falco)) + { + AI.SelectCard(CardId.Falco); + return true; + } + return false; + } + + return false; + } + + private bool FoolishBurial_activate() + { + if (FalcoToGY(true) && Bot.HasInHandOrInGraveyard(CardId.Spinny)) + { + AI.SelectCard(CardId.Falco); + return true; + } + AI.SelectCard(CardId.Spinny, CardId.JackJaguar, CardId.Foxy); + return true; + } + + private bool Sanctuary_activate() + { + if (Card.Location == CardLocation.Hand) + { + return true; + } + return false; + } + + private bool Rage_activate() + { + if (ActivateDescription == Util.GetStringId(CardId.SalamangreatRage, 1)) + { + AI.SelectCard(salamangreat_links); + AI.SelectOption(1); + IList targets = new List(); + + ClientCard target1 = Util.GetBestEnemyMonster(canBeTarget: true); + 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 >= 2) + break; + if (!targets.Contains(target)) + targets.Add(target); + } + foreach (ClientCard target in Enemy.GetSpells()) + { + if (targets.Count >= 2) + break; + if (!targets.Contains(target)) + targets.Add(target); + } + if (targets.Count == 0) + return false; + AI.SelectNextCard(targets); + return true; + } + else + { + if (Util.GetProblematicEnemyCard(canBeTarget: true) != null) + { + if (Util.GetBestBotMonster(true) != null) + { + AI.SelectCard(Util.GetProblematicEnemyCard(Util.GetBestBotMonster(true).Attack, canBeTarget: true)); + } + else + { + AI.SelectCard(Util.GetProblematicEnemyCard(canBeTarget: true)); + } + + return true; + } + } + return false; + } + + public bool G_activate() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return (Duel.Player == 1); + } + public bool Hand_act_eff() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return (Duel.LastChainPlayer == 1); + } + + public bool Impermanence_activate() + { + if (!Should_counter()) return false; + if (!spell_trap_activate()) return false; + // negate before effect used + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (m.IsMonsterShouldBeDisabledBeforeItUseEffect() && !m.IsDisabled() && Duel.LastChainPlayer != 0) + { + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + AI.SelectCard(m); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || (Util.IsChainTarget(Card)) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + Impermanence_list.Add(this_seq); + return true; + } + } + } + } + if ((LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || LastChainCard.IsDisabled() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget())) + return false; + // negate monsters + if (is_should_not_negate() && LastChainCard.Location == CardLocation.MonsterZone) return false; + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + return true; + } + } + } + return true; + } + + public bool is_should_not_negate() + { + ClientCard last_card = Util.GetLastChainCard(); + if (last_card != null + && last_card.Controller == 1 && last_card.IsCode(should_not_negate)) + return true; + return false; + } + + public bool SolemnStrike_activate() + { + if (!Should_counter()) return false; + return (DefaultSolemnStrike() && spell_trap_activate(true)); + } + + public bool SolemnJudgment_activate() + { + return !Util.IsChainTargetOnly(Card) + && + !(Duel.Player == 0 + && Duel.LastChainPlayer == -1) + && DefaultTrap() && spell_trap_activate(true); + } + + public bool spell_trap_activate(bool isCounter = false, ClientCard target = null) + { + if (target == null) target = Card; + if (target.Location != CardLocation.SpellZone && target.Location != CardLocation.Hand) return true; + if (target.IsSpell()) + { + if (Enemy.HasInMonstersZone(CardId.NaturalBeast, true) && !Bot.HasInHandOrHasInMonstersZone(CardId.GO_SR) && !isCounter && !Bot.HasInSpellZone(CardId.SolemnStrike)) return false; + if (Enemy.HasInSpellZone(CardId.ImperialOrder, true) || Bot.HasInSpellZone(CardId.ImperialOrder, true)) return false; + if (Enemy.HasInMonstersZone(CardId.SwordsmanLV7, true) || Bot.HasInMonstersZone(CardId.SwordsmanLV7, true)) return false; + return true; + } + if (target.IsTrap()) + { + if (Enemy.HasInSpellZone(CardId.RoyalDecreel, true) || Bot.HasInSpellZone(CardId.RoyalDecreel, true)) return false; + return true; + } + // how to get here? + return false; + } + + public bool Should_counter() + { + if (Duel.CurrentChain.Count < 2) return true; + ClientCard self_card = Duel.CurrentChain[Duel.CurrentChain.Count - 2]; + if (self_card?.Controller != 0 + || !(self_card.Location == CardLocation.MonsterZone || self_card.Location == CardLocation.SpellZone)) return true; + ClientCard enemy_card = Duel.CurrentChain[Duel.CurrentChain.Count - 1]; + if (enemy_card?.Controller != 1 + || !enemy_card.IsCode(normal_counter)) return true; + return false; + } + public int SelectSTPlace(ClientCard card = null, bool avoid_Impermanence = false) + { + List list = new List(); + list.Add(0); + list.Add(1); + list.Add(2); + list.Add(3); + list.Add(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 && Impermanence_list.Contains(seq)) continue; + return zone; + }; + } + return 0; + } + + public override bool OnSelectYesNo(int desc) + { + if (desc == Util.GetStringId(CardId.Sanctuary, 0)) + { + wasFieldspellUsedThisTurn = true; + } + if (desc == Util.GetStringId(CardId.Foxy, 3)) + { + return foxyPopEnemySpell; + } + return base.OnSelectYesNo(desc); + } + + public override void OnNewTurn() + { + FoxyActivatedThisTurn = false; + JackJaguarActivatedThisTurn = false; + wasWolfActivatedThisTurn = false; + wasStallioActivated = false; + falcoUsedReturnST = false; + CombosInHand = Bot.Hand.Select(h => h.Id).Intersect(Combo_cards).ToList(); + wasFieldspellUsedThisTurn = false; + wasGazelleSummonedThisTurn = false; + base.OnNewTurn(); + } + + public override bool OnSelectHand() + { + return true; + } + + public bool SpellSet() + { + if (Card.Id == CardId.Circle) + { + return false; + } + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + if (Card.IsCode(CardId.SolemnStrike) && Bot.LifePoints <= 1500) return false; + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay))) + { + List avoid_list = new List(); + int Impermanence_set = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + Impermanence_set += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(CardId.Impermanence)) + { + if (Card.IsCode(CardId.Impermanence)) + { + AI.SelectPlace(Impermanence_set); + return true; + } + else + { + AI.SelectPlace(SelectSetPlace(avoid_list)); + return true; + } + } + else + { + AI.SelectPlace(SelectSTPlace()); + } + return true; + } + return false; + } + + public bool Called_activate() + { + if (!DefaultUniqueTrap()) + return false; + + if (Duel.Player == 1) + { + ClientCard target = Enemy.MonsterZone.GetShouldBeDisabledBeforeItUseEffectMonster(); + if (target != null && Enemy.HasInGraveyard(target.Id)) + { + AI.SelectCard(target.Id); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + if (LastChainCard != null + && LastChainCard.Controller == 1 + && (LastChainCard.Location == CardLocation.Grave + || LastChainCard.Location == CardLocation.Hand + || LastChainCard.Location == CardLocation.MonsterZone + || LastChainCard.Location == CardLocation.Removed) + && !LastChainCard.IsDisabled() && !LastChainCard.IsShouldNotBeTarget() + && !LastChainCard.IsShouldNotBeSpellTrapTarget() + && Enemy.HasInGraveyard(LastChainCard.Id)) + { + AI.SelectCard(LastChainCard.Id); + return true; + } + + if (Bot.BattlingMonster != null && Enemy.BattlingMonster != null) + { + if (!Enemy.BattlingMonster.IsDisabled() && Enemy.BattlingMonster.IsCode(_CardId.EaterOfMillions) && Enemy.HasInGraveyard(_CardId.EaterOfMillions)) + { + AI.SelectCard(Enemy.BattlingMonster.Id); + return true; + } + } + + if (Duel.Phase == DuelPhase.BattleStart && Duel.Player == 1 && + Enemy.HasInMonstersZone(_CardId.NumberS39UtopiaTheLightning, true) && Enemy.HasInGraveyard(_CardId.NumberS39UtopiaTheLightning)) + { + AI.SelectCard(_CardId.NumberS39UtopiaTheLightning); + return true; + } + + return false; + } + + public bool Borrelsword_ss() + { + if (Duel.Phase != DuelPhase.Main1) return false; + if (Duel.Turn == 1) return false; + if (wasStallioActivated) return false; + + List material_list = new List(); + List bot_monster = Bot.GetMonsters(); + bot_monster.Sort(CardContainer.CompareCardAttack); + //bot_monster.Reverse(); + int link_count = 0; + foreach (ClientCard card in bot_monster) + { + if (card.IsFacedown()) continue; + if (!material_list.Contains(card) && card.LinkCount < 3) + { + material_list.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + } + } + if (link_count >= 4) + { + if (link_count > 4 && material_list.Where(x => x.Id == CardId.MirageStallio).Count() > 0) + { + material_list.Remove(material_list.First(x => x.Id == CardId.MirageStallio)); + } + AI.SelectMaterials(material_list); + return true; + } + return false; + } + + public bool Borrelsword_eff() + { + if (ActivateDescription == -1) return true; + else if ((Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) || Util.IsChainTarget(Card)) + { + List enemy_list = Enemy.GetMonsters(); + enemy_list.Sort(CardContainer.CompareCardAttack); + enemy_list.Reverse(); + foreach (ClientCard card in enemy_list) + { + if (card.HasPosition(CardPosition.Attack) && !card.HasType(CardType.Link)) + { + AI.SelectCard(card); + return true; + } + } + List bot_list = Bot.GetMonsters(); + bot_list.Sort(CardContainer.CompareCardAttack); + //bot_list.Reverse(); + foreach (ClientCard card in bot_list) + { + if (card.HasPosition(CardPosition.Attack) && !card.HasType(CardType.Link)) + { + AI.SelectCard(card); + return true; + } + } + } + return false; + } + public override void OnChainEnd() + { + if (!falcoHitGY && !falcoUsedReturnST && Bot.HasInGraveyard(CardId.Falco)) + { + falcoHitGY = true; + } + else if (!Bot.HasInGraveyard(CardId.Falco)) + { + falcoHitGY = false; + } + base.OnChainEnd(); + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0) + { + if (location == CardLocation.MonsterZone) + { + if (Bot.GetMonstersInExtraZone().Where(x => x.Id == CardId.SunlightWolf).Count() > 1) + { + for (int i = 0; i < 7; ++i) + { + if (Bot.MonsterZone[i] != null && Bot.MonsterZone[i].IsCode(CardId.SunlightWolf)) + { + int next_index = get_Wolf_linkzone(); + if (next_index != -1 && (available & (int)(System.Math.Pow(2, next_index))) > 0) + { + return (int)(System.Math.Pow(2, next_index)); + } + } + } + } + } + } + return base.OnSelectPlace(cardId, player, location, available); + } + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + if (Util.IsTurn1OrMain2() + && + (cardId == CardId.Gazelle + || cardId == CardId.Spinny + || cardId == CardId.Foxy)) + { + return CardPosition.FaceUpDefence; + } + return 0; + } + + public int SelectSetPlace(List avoid_list = null, bool avoid = true) + { + List list = new List(); + list.Add(5); + list.Add(6); + 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.MonsterZone[seq] == null || !avoid) + { + if (avoid) + { + if (avoid_list != null && avoid_list.Contains(seq)) continue; + return zone; + } + else + { + if (avoid_list != null && avoid_list.Contains(seq)) + { + return list.First(x => x == seq); + } + continue; + } + + }; + } + return 0; + } + public override BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList defenders) + { + foreach (ClientCard defender in defenders) + { + attacker.RealPower = attacker.Attack; + defender.RealPower = defender.GetDefensePower(); + if (attacker.IsCode(CardId.Borrelsword) && !attacker.IsDisabled()) + return AI.Attack(attacker, defender); + if (!OnPreBattleBetween(attacker, defender)) + continue; + + if (attacker.RealPower > defender.RealPower || (attacker.RealPower > defender.RealPower && attacker.IsLastAttacker && defender.IsAttack())) + return AI.Attack(attacker, defender); + } + + if (attacker.CanDirectAttack) + return AI.Attack(attacker, null); + + return null; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SkyStrikerExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SkyStrikerExecutor.cs new file mode 100644 index 0000000..41a916a --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SkyStrikerExecutor.cs @@ -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 targets = new List(); + 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 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 targets = new List(); + 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; + } + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SuperheavySamuraiExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SuperheavySamuraiExecutor.cs new file mode 100644 index 0000000..b0911a0 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SuperheavySamuraiExecutor.cs @@ -0,0 +1,1219 @@ +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using System.Linq; +using System; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; +namespace WindBot.Game.AI.Decks +{ + [Deck("SuperheavySamurai", "AI_SuperheavySamurai")] + public class SuperheavySamuraiExecutor : DefaultExecutor + { + public class CardId + { + public const int Benkei = 19510093;//弁庆 + public const int Wagon = 34496660;//大八 + public const int Soulpiercer = 90361010;//岩融 + public const int Wakaushi = 82112494;//牛若 + public const int Scales = 78391364;//天秤 + public const int Booster = 56727340;//地铠 + public const int Motorbike = 83334932;//摩托 + public const int Soulhorns = 14624296;//双角 + public const int Soulpeacemaker = 95500396;//仲裁 + + public const int Regulus = 10604644;//轩辕十四 + + public const int MaxxG = 23434538;//增殖的G + public const int JoyousSpring = 14558127;//灰流丽 + public const int PsyFrameDriver = 49036338;//PSY骨架驱动者 + public const int PsyFramegearGamma = 38814750;//PSY骨架装备·γ + public const int EffectVeiler = 97268402;//效果遮蒙者 + public const int HauntedMansion = 73642296;//屋敷童 + public const int SnowRabbit = 59438930;//幽鬼兔 + public const int LockBird = 94145021;//小丑与锁鸟 + + //extra + public const int Masurawo = 64193046;//益荒男 + public const int Fleur = 84815190;//鲜花女男爵 + public const int ASStardustDragon = 30983281;//加速同调星尘龙 + public const int StardustDragon = 30983281;//星尘龙 + public const int SavageDragon = 27548199;//狞猛龙 + public const int Sarutobi = 76471944;//猿飞 + public const int PSYFramelordOmega = 74586817;//PSY骨架王·Ω + public const int GearGigant = 28912357;//齿轮齿巨人 + public const int Unicorn = 38342335;//独角兽 + public const int Elf = 27381364;//卫星闪灵·淘气精灵 + public const int Genius = 22423493;//路径灵 + public const int IP = 65741786;//I:P伪装舞会莱娜 + public const int Scarecrow = 33918636;//案山子 + + } + + private bool normal_summon = false; + private bool p_summoned = false; + private bool p_summoning = false; + private bool activate_Motorbike = false;//摩托 + private bool activate_Wakaushi = false;//神童 + private bool activate_Scales = false;//天秤 + private bool activate_Wagon = false;//大巴 + private bool activate_Booster = false;//地铠 + private bool activate_Soulpeacemaker = false;//仲裁 + private bool activate_Benkei = false;//弁庆 + private bool need_Gear = false;//齿轮齿巨人 + //案山子 + private bool activate_Scarecrow=false; + private bool summon_Scarecrow=false; + private bool summon_Scarecrow2=true; + private bool activate_Sarutobi = false;//猿飞 + private bool activate_Genius = false;//路径灵 + //淘气精灵 + private bool activate_Elf = false; + private bool summon_Elf = false; + //手坑 + private bool activate_MaxxG = false;//增殖的G + private bool activate_PSY = false;//PSY + private bool activate_LockBird = false;//小丑与锁鸟 + private bool to_deck = false; + + public SuperheavySamuraiExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Repos, MonsterRepos); + AddExecutor(ExecutorType.Activate, CardId.PSYFramelordOmega,PSYFunction); + AddExecutor(ExecutorType.Activate, CardId.IP,IPFunction); + AddExecutor(ExecutorType.Activate, CardId.Sarutobi,SarutobiFunction); + AddExecutor(ExecutorType.Activate, CardId.Unicorn,UnicornFunction); + AddExecutor(ExecutorType.Activate, CardId.MaxxG,MaxxCFunction); + AddExecutor(ExecutorType.Activate, CardId.JoyousSpring,DefaultAshBlossomAndJoyousSpring); + AddExecutor(ExecutorType.Activate, CardId.SnowRabbit,DefaultGhostOgreAndSnowRabbit); + AddExecutor(ExecutorType.Activate, CardId.EffectVeiler,DefaultBreakthroughSkill); + AddExecutor(ExecutorType.Activate, CardId.LockBird,LockBirdFunction); + AddExecutor(ExecutorType.Activate, CardId.PsyFramegearGamma,FunctionInHand); + AddExecutor(ExecutorType.Activate, CardId.HauntedMansion,FunctionInHand); + AddExecutor(ExecutorType.Activate, CardId.Masurawo,MasurawoFunction); + AddExecutor(ExecutorType.Activate, CardId.Genius,GeniusFunction); + + //Motorbike's Effect + AddExecutor(ExecutorType.Activate, CardId.Motorbike,MotorbikeFunction); + + //Scales's Effect + AddExecutor(ExecutorType.SpSummon, CardId.Scales); + AddExecutor(ExecutorType.Activate, CardId.Scales,ScalesFunction); + + //Synchron + AddExecutor(ExecutorType.SpSummon, CardId.PSYFramelordOmega,PSYFramelordOmegaSynchronFunction); + + //Pendulum + AddExecutor(ExecutorType.Activate, CardId.Wakaushi,WakaushiFunction); + AddExecutor(ExecutorType.Activate, CardId.Wakaushi,WakaushiEffectFunction); + AddExecutor(ExecutorType.Activate, CardId.Benkei,BenkeiFunction); + AddExecutor(ExecutorType.Activate, CardId.Benkei,BenkeiEffectFunction); + + //Normal Summon & Effect + AddExecutor(ExecutorType.Summon, CardId.Soulpiercer,NormalSummonFunction); + AddExecutor(ExecutorType.Activate, CardId.Soulpiercer,SoulpiercerFunction); + + AddExecutor(ExecutorType.Summon, CardId.Wagon,NormalSummonFunction); + AddExecutor(ExecutorType.Activate, CardId.Wagon,WagonFunction); + AddExecutor(ExecutorType.Activate, CardId.Wagon,WagonFunction); + + AddExecutor(ExecutorType.Summon, CardId.Booster,BoosterNormalSummonFunction); + AddExecutor(ExecutorType.Summon, CardId.Scales,ScalesNormalSummonFunction); + + //boost & Gear + AddExecutor(ExecutorType.Activate, CardId.Booster,BoosterEquipFunction); + AddExecutor(ExecutorType.Activate, CardId.Booster,BoosterFunction); + AddExecutor(ExecutorType.SpSummon, CardId.GearGigant,GearGigantXyzFunction); + AddExecutor(ExecutorType.Activate, CardId.GearGigant,GearGigantFunction); + + //equip Soulpiercer + AddExecutor(ExecutorType.Activate, CardId.Soulpiercer,SoulpiercerEquipFunction); + + //Link Scarecrow + AddExecutor(ExecutorType.SpSummon, CardId.Scarecrow,ScarecrowLinkFunction); + AddExecutor(ExecutorType.Activate, CardId.Scarecrow,ScarecrowFunction); + AddExecutor(ExecutorType.SpSummon, CardId.Scarecrow,ScarecrowLinkFunction2); + + //Synchron + AddExecutor(ExecutorType.SpSummon, CardId.ASStardustDragon,ASStardustDragonSynchronFunction); + + //Effect After Synchron + AddExecutor(ExecutorType.Activate, CardId.SavageDragon,SavageDragonFunction); + AddExecutor(ExecutorType.Activate, CardId.ASStardustDragon,ASStardustDragonFunction); + + //Wakaushi's Effect After Synchron + AddExecutor(ExecutorType.Activate, CardId.Wakaushi,WakaushiReturnPFunction); + + //Synchron + AddExecutor(ExecutorType.SpSummon, CardId.Fleur,FleurSynchronFunction); + AddExecutor(ExecutorType.Activate, CardId.Fleur,FleurFunction); + + //equip Soulpeacemaker + AddExecutor(ExecutorType.Activate, CardId.Soulpeacemaker,SoulpeacemakerEquipFunction); + AddExecutor(ExecutorType.Activate, CardId.Soulpeacemaker,SoulpeacemakerFunction); + + //Link + AddExecutor(ExecutorType.SpSummon, CardId.Genius,GeniusLinkFunction); + + AddExecutor(ExecutorType.SpSummon, Psummon); + + //Link + AddExecutor(ExecutorType.SpSummon, CardId.Elf,ElfLinkFunction); + AddExecutor(ExecutorType.Activate, CardId.Elf,ElfFunction); + + AddExecutor(ExecutorType.Activate, CardId.Motorbike,MotorbikeFunction); + + //Synchron + AddExecutor(ExecutorType.SpSummon, CardId.SavageDragon,SavageDragonSynchronFunction); + + //Link + AddExecutor(ExecutorType.SpSummon, CardId.IP,IPLinkFunction); + + //Regulus's Effect + AddExecutor(ExecutorType.Activate, CardId.Regulus,RegulusFunction); + + //booster + AddExecutor(ExecutorType.Activate, CardId.Booster,BoosterEquipFunction2); + AddExecutor(ExecutorType.Activate, CardId.Booster,BoosterFunction); + AddExecutor(ExecutorType.Activate, CardId.Booster,BoosterEquipFunction3); + AddExecutor(ExecutorType.Activate, CardId.Booster,BoosterFunction); + + //Synchron + AddExecutor(ExecutorType.SpSummon, CardId.Masurawo,MasurawoSynchronFunction); + AddExecutor(ExecutorType.SpSummon, CardId.Sarutobi,DeSynchronFunction); + + //equip Soulhorns + AddExecutor(ExecutorType.Activate, CardId.Soulhorns,SoulhornsEquipFunction); + + } + public override void OnNewTurn() + { + normal_summon = false; + p_summoned = false; + p_summoning = false; + activate_Motorbike = false; + activate_Wakaushi = false; + activate_Scales = false; + activate_Wagon = false; + activate_Booster = false; + activate_Soulpeacemaker = false; + activate_Benkei = false; + need_Gear = false; + activate_Scarecrow=false; + summon_Scarecrow=false; + summon_Scarecrow2=true; + activate_Elf = false; + summon_Elf = false; + activate_MaxxG = false; + activate_PSY = false; + activate_LockBird = false; + activate_Genius = false; + activate_Sarutobi = false; + to_deck = false; + base.OnNewTurn(); + } + public override bool OnSelectHand() + { + return true; + } + private bool MonsterRepos() + { + if (Card.IsFacedown()) + return true; + if (Card.IsFaceup() && Card.IsAttack() && (Card.Id == CardId.Masurawo || Card.Id == CardId.Sarutobi)) + return true; + return false; + } + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (cardId == CardId.Masurawo || cardId == CardId.Sarutobi) + return CardPosition.FaceUpDefence; + } + return 0; + } + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location == CardLocation.MonsterZone) + { + if (cardId == CardId.Scarecrow) + { + int a=(Zones.z6 & available); + int b=(Zones.z5 & available); + if (Bot.MonsterZone[2] != null && Bot.MonsterZone[2].Controller == 0 && !FinalCards(Bot.MonsterZone[2].Id)) + a = 0; + else if (Bot.MonsterZone[0] != null && Bot.MonsterZone[0].Controller == 0 && !FinalCards(Bot.MonsterZone[0].Id)) + b = 0; + if (b > 0) return Zones.z5; + if (a > 0) return Zones.z6; + } + else if (cardId == CardId.Unicorn || cardId == CardId.Elf || cardId == CardId.IP) + { + if ((Zones.z6 & available) > 0) return Zones.z6; + if ((Zones.z5 & available) > 0) return Zones.z5; + } + else if (cardId == CardId.Genius) + { + int a=(Zones.z6 & available); + int b=(Zones.z5 & available); + if (Bot.MonsterZone[4] != null && Bot.MonsterZone[4].Controller == 0 && !FinalCards(Bot.MonsterZone[4].Id)) + a = 0; + else if (Bot.MonsterZone[0] != null && Bot.MonsterZone[0].Controller == 0 && !FinalCards(Bot.MonsterZone[0].Id)) + b = 0; + if (a > 0) return Zones.z6; + if (b > 0) return Zones.z5; + } + else if (cardId == CardId.Regulus || cardId == CardId.GearGigant) + { + if ((Zones.z3 & available) > 0) return Zones.z3; + } + else + { + if ((Zones.z1 & available) > 0) return Zones.z1; + if ((Zones.z4 & available) > 0) return Zones.z4; + if ((Zones.z2 & available) > 0) return Zones.z2; + if ((Zones.z3 & available) > 0) return Zones.z3; + if ((Zones.z0 & available) > 0) return Zones.z0; + } + } + return base.OnSelectPlace(cardId, player, location, available); + } + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (AI.HaveSelectedCards()) return null; + if (p_summoning || ((Card == Bot.SpellZone[0] || Card == Bot.SpellZone[4]) && hint == HintMsg.SpSummon && + Card.HasType(CardType.Pendulum))) + { + List result = new List(); + List scards = cards.Where(card => card != null && card.HasSetcode(0x9a) && card.Level == 4).ToList(); + if (scards.Count <2) scards = cards.Where(card => card != null && card.HasSetcode(0x9a)).ToList(); + p_summoning = false; + if (scards.Count > 0) return Util.CheckSelectCount(result, scards, 1, 1); + else if (min == 0) return result; // empty + } + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + private List GetZoneCards(CardLocation loc, ClientField player) + { + List res = new List(); + List temp = new List(); + if ((loc & CardLocation.Hand) > 0) { temp = player.Hand.Where(card => card != null).ToList(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.MonsterZone) > 0) { temp = player.GetMonsters(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.SpellZone) > 0) { temp = player.GetSpells(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.Grave) > 0) { temp = player.Graveyard.Where(card => card != null).ToList(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.Removed) > 0) { temp = player.Banished.Where(card => card != null).ToList(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.Extra) > 0) { temp = player.ExtraDeck.Where(card => card != null).ToList(); if (temp.Count() > 0) res.AddRange(temp); } + return res; + } + private bool FinalCards(int cname) + { + int[] cardsname = new[] {CardId.Masurawo,CardId.Fleur,CardId.SavageDragon,CardId.Sarutobi,CardId.Regulus,CardId.IP}; + foreach(var cardname in cardsname) + { + if (cname == cardname) return true; + } + return false; + } + private bool TurnerCards(int cname) + { + int[] cardsname =new[] {CardId.PsyFramegearGamma,CardId.Wakaushi,CardId.Motorbike}; + foreach(var cardname in cardsname) + { + if (cname == cardname) return true; + } + return false; + } + private bool Psummon() + { + List cards = GetZoneCards(CardLocation.Hand, Bot).Where(card => card != null && card.HasSetcode(0x9a) && card.Level > 1 && card.Level < 8).ToList(); + if (cards.Count > 0 && Card.Location == CardLocation.SpellZone) + { + p_summoning = true; + p_summoned = true; + return true; + } + return false; + } + private bool MaxxCFunction() + { + activate_MaxxG = true; + return DefaultMaxxC() && !activate_LockBird; + } + private bool FunctionInHand() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return Duel.LastChainPlayer == 1; + } + private bool LockBirdFunction() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Duel.Player == 0 || activate_LockBird) + { + return false; + } + activate_LockBird = true; + return !activate_MaxxG; + } + private bool MotorbikeFunction() + { + if (Card.Location == CardLocation.Hand) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + int targetid = -1; + List cards = GetZoneCards(CardLocation.MonsterZone, Bot).Where(card => card != null && card.IsFaceup()).ToList(); + if (!(Bot.HasInHand(CardId.Wakaushi) || Bot.HasInMonstersZone(CardId.Wakaushi) || Bot.HasInSpellZone(CardId.Wakaushi)) && !activate_Wakaushi) + { + targetid = CardId.Wakaushi; + } + else if (cards.Count() == 0 && !normal_summon) + { + targetid = CardId.Soulpiercer; + } + else if (!Bot.HasInHand(CardId.Soulpeacemaker) && !Bot.HasInSpellZone(CardId.Soulpeacemaker) && !activate_Soulpeacemaker && (normal_summon || Bot.HasInMonstersZone(CardId.Scarecrow))) + { + targetid = CardId.Soulpeacemaker; + } + else + { + targetid = CardId.Soulpiercer; + } + if (targetid > 0) AI.SelectCard(targetid); + activate_Motorbike = true; + return true; + } + else if (Card.Location == CardLocation.MonsterZone && activate_Elf) + { + AI.SelectCard(Card); + activate_Elf = false; + return true; + } + return false; + } + private bool BoosterNormalSummonFunction() + { + List cards = Bot.Hand.GetMonsters().Where(card => card != null && card.Id == CardId.Booster).ToList(); + return (NormalSummonFunction() && !activate_Booster && cards.Count >= 2); + } + private bool ScalesNormalSummonFunction() + { + return (NormalSummonFunction() && (Bot.HasInGraveyard(new[] { + CardId.Soulpiercer, + CardId.Motorbike, + CardId.Wakaushi, + CardId.Wagon, + CardId.Booster, + }) || (Bot.HasInHand(CardId.Booster) && !activate_Booster))); + } + private bool NormalSummonFunction() + { + normal_summon = true; + return DefaultMonsterSummon(); + } + private bool ScalesFunction() + { + AI.SelectCard(new[] { + CardId.Soulpiercer, + CardId.Motorbike, + CardId.Wakaushi, + CardId.Wagon, + CardId.Booster, + }); + activate_Scales = true; + return true; + } + private bool WagonFunction() + { + if (ActivateDescription == Util.GetStringId(CardId.Wagon, 0)) + return Card.IsAttack(); + if (ActivateDescription == Util.GetStringId(CardId.Wagon, 1)) + { + int targetid = -1; + if (!(Bot.HasInHand(CardId.Soulpiercer)||Bot.HasInMonstersZone(CardId.Soulpiercer))) + { + targetid = CardId.Soulpiercer; + } + else if (!Bot.HasInHand(CardId.Soulpeacemaker) && !activate_Soulpeacemaker) + { + targetid = CardId.Soulpeacemaker; + } + else if (!Bot.HasInHand(CardId.Booster) && !activate_Booster) + { + targetid = CardId.Booster; + } + if (targetid > 0) AI.SelectCard(targetid); + activate_Wagon = true; + return true; + } + else + { + return true; + } + } + private bool SoulpiercerFunction() + { + if (Card.Location == CardLocation.Grave) + { + int CardCount = GetZoneCards(CardLocation.Hand, Bot).Count(card => card != null && card.HasSetcode(0x9a) && card.Level >= 2 && card.Level <= 7); + int targetid = -1; + if (!Bot.HasInHand(CardId.Motorbike) && !activate_Motorbike) + { + targetid = CardId.Motorbike; + } + else if (!(Bot.HasInHand(CardId.Wakaushi) || Bot.HasInMonstersZone(CardId.Wakaushi) || Bot.HasInSpellZone(CardId.Wakaushi)) && !activate_Wakaushi) + { + targetid = CardId.Wakaushi; + } + else if (!Bot.HasInHand(CardId.Soulpeacemaker) && !activate_Soulpeacemaker) + { + targetid = CardId.Soulpeacemaker; + } + else if (!Bot.HasInHand(CardId.Scales) && !activate_Scales && (!normal_summon || !p_summoned) && (activate_Soulpeacemaker || (!Bot.HasInHand(CardId.Soulpeacemaker) && !Bot.HasInSpellZone(CardId.Soulpeacemaker)))) + { + targetid = CardId.Scales; + } + else if (!Bot.HasInHand(CardId.Wagon) && !activate_Wagon) + { + targetid = CardId.Wagon; + } + else if (CardCount < 2 && !p_summoned) + { + targetid = CardId.Wakaushi; + } + else if (!Bot.HasInHand(CardId.Booster) && !activate_Booster) + { + targetid = CardId.Booster; + } + else if (!Bot.HasInHand(CardId.Soulhorns) && !Bot.HasInSpellZone(CardId.Soulhorns) && (Bot.HasInMonstersZone(CardId.Sarutobi) || Bot.HasInMonstersZone(CardId.Masurawo))) + { + targetid = CardId.Soulhorns; + } + else {targetid = CardId.Wakaushi;} + if (targetid > 0) AI.SelectCard(targetid); + return true; + } + return false; + } + private bool WakaushiFunction() + { + if (Card.Location != CardLocation.Hand||Bot.HasInMonstersZone(CardId.Wakaushi)) + 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 WakaushiEffectFunction() + { + if (Card.Location == CardLocation.SpellZone) + { + AI.SelectCard(CardId.Benkei); + activate_Wakaushi = true; + return true; + } + return false; + } + private bool BenkeiFunction() + { + if (Card.Location != CardLocation.Hand || Bot.HasInSpellZone(CardId.Benkei)) return false; + List cards1 = GetZoneCards(CardLocation.Hand, Bot).Where(card => card != null && card.Id == CardId.Benkei).ToList(); + List cards2 = GetZoneCards(CardLocation.Removed, Bot).Where(card => card != null && card.Id == CardId.Benkei).ToList(); + if (cards1.Count() >= 2 || Bot.HasInGraveyard(CardId.Benkei) || Bot.HasInExtra(CardId.Benkei) || cards2.Count() > 0) + return true; + return false; + } + private bool BenkeiEffectFunction() + { + if (Card.Location == CardLocation.SpellZone) + { + int targetid = -1; + if (!(Bot.HasInHand(CardId.Soulpiercer) || Bot.HasInMonstersZone(CardId.Soulpiercer) || Bot.HasInSpellZone(CardId.Soulpiercer)) && !(Bot.HasInMonstersZone(CardId.Scarecrow) && !activate_Soulpeacemaker)) + { + targetid = CardId.Soulpiercer; + } + else if (!Bot.HasInHand(CardId.Soulpeacemaker) && !activate_Soulpeacemaker) + { + targetid = CardId.Soulpeacemaker; + } + else if (!Bot.HasInHand(CardId.Booster) && !activate_Booster) + { + targetid = CardId.Booster; + } + if (targetid > 0) AI.SelectCard(targetid); + activate_Benkei = true; + return true; + } + return false; + } + private bool WakaushiReturnPFunction() + { + if (Card.Location == CardLocation.Extra||Card.Location == CardLocation.Removed) + { + 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 MasurawoFunction() + { + if (ActivateDescription == 96) + { + List cards = GetZoneCards(CardLocation.SpellZone, Bot).Where(card => card != null && card.HasSetcode(0x9a)).ToList(); + if (cards.Count > 0) + { + AI.SelectCard(cards); + return true; + } + else + { + cards = GetZoneCards(CardLocation.MonsterZone, Bot).Where(card => card != null && card.HasSetcode(0x9a) && !FinalCards(card.Id)).ToList(); + if (cards.Count > 0) + { + AI.SelectCard(cards); + return true; + } + } + } + return true; + + } + private bool MasurawoSynchronFunction() + { + bool chk = true; + if (Bot.HasInMonstersZone(CardId.ASStardustDragon) || Bot.HasInMonstersZone(CardId.Benkei)) + chk = false; + var materials_lists = Util.GetSynchroMaterials(Bot.MonsterZone,12,1,1,false,chk,null, + card => { return !FinalCards(card.Id); }); + if (materials_lists.Count <= 0) return false; + AI.SelectMaterials(materials_lists[0]); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + private bool FleurSynchronFunction() + { + bool chk = true; + if (Bot.HasInMonstersZone(CardId.Motorbike) && (Bot.HasInMonstersZone(CardId.ASStardustDragon) || Bot.HasInMonstersZone(CardId.Benkei))) + chk = false; + var materials_lists = Util.GetSynchroMaterials(Bot.MonsterZone,10,1,1,false,chk,null, + card => { return !FinalCards(card.Id); }); + if (materials_lists.Count <= 0) return false; + AI.SelectMaterials(materials_lists[0]); + return true; + } + private bool DeSynchronFunction() + { + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + private bool SavageDragonSynchronFunction() + { + if (Bot.HasInGraveyard(new[] { + CardId.Scarecrow, + CardId.IP, + CardId.Genius, + CardId.Unicorn, + CardId.Elf, + })) + { + return true; + } + return false; + } + private bool ASStardustDragonSynchronFunction() + { + if (Bot.HasInGraveyard(CardId.Motorbike) || Bot.HasInGraveyard(CardId.PsyFramegearGamma)) + { + return (Bot.HasInExtra(CardId.Fleur) || Bot.HasInExtra(CardId.Masurawo)); + } + else if (Bot.HasInMonstersZone(CardId.Motorbike)) + { + AI.SelectMaterials(CardId.Motorbike); + return true; + } + else if (Bot.HasInMonstersZone(CardId.PsyFramegearGamma)) + { + AI.SelectMaterials(CardId.PsyFramegearGamma); + return true; + } + return false; + } + private bool PSYFramelordOmegaSynchronFunction() + { + if (Bot.HasInMonstersZone(CardId.Motorbike)) + AI.SelectMaterials(CardId.Motorbike); + else if (Bot.HasInMonstersZone(CardId.PsyFramegearGamma)) + AI.SelectMaterials(CardId.PsyFramegearGamma); + return activate_PSY || activate_Scales; + } + private bool SavageDragonFunction() + { + if (Duel.LastChainPlayer == 1) + return true; + AI.SelectCard(new[] + { + CardId.Unicorn, + CardId.Genius, + CardId.Elf, + CardId.IP, + CardId.Scarecrow + }); + return true; + } + private bool ASStardustDragonFunction() + { + if (Duel.LastChainPlayer == 1 && ActivateDescription == Util.GetStringId(CardId.ASStardustDragon, 1)) + { + return true; + } + else if (ActivateDescription == Util.GetStringId(CardId.ASStardustDragon, 0)) + { + + int targetid = -1; + if (Bot.HasInGraveyard(CardId.Motorbike)) + { + targetid = CardId.Motorbike; + } + else if (Bot.HasInGraveyard(CardId.PsyFramegearGamma)) + { + targetid = CardId.PsyFramegearGamma; + } + if (targetid > 0) AI.SelectCard(targetid); + if (targetid == CardId.Motorbike && !Bot.HasInExtra(CardId.Fleur) && Bot.HasInExtra(CardId.Masurawo)) + activate_Elf = true; + return true; + } + return false; + } + private bool ScarecrowLinkFunction() + { + List material = new List(); + List cards = Bot.GetMonstersInExtraZone().Where(card => card != null && card.Id == CardId.Scarecrow).ToList(); + if ((cards.Count() > 0 && !summon_Scarecrow) || summon_Scarecrow || activate_Scarecrow) return false; + int targetid = -1; + if (Bot.MonsterZone[0] != null && Bot.MonsterZone[2] != null) { + if (Bot.MonsterZone[0].Id == CardId.Soulpiercer) material.Add(Bot.MonsterZone[0]); + else if (Bot.MonsterZone[2].Id == CardId.Soulpiercer) material.Add(Bot.MonsterZone[2]); + else if (!FinalCards(Bot.MonsterZone[0].Id) && Bot.MonsterZone[0].HasSetcode(0x9a)) material.Add(Bot.MonsterZone[0]); + else if (!FinalCards(Bot.MonsterZone[2].Id) && Bot.MonsterZone[2].HasSetcode(0x9a)) material.Add(Bot.MonsterZone[2]); + } + else if (Bot.HasInMonstersZone(CardId.Soulpiercer)) + { + targetid = CardId.Soulpiercer; + } + else if (Bot.HasInMonstersZone(CardId.Wagon)) + { + targetid = CardId.Wagon; + } + if (material.Count > 0) AI.SelectMaterials(material); + else if (targetid > 0) AI.SelectMaterials(targetid); + summon_Scarecrow=true; + return (Bot.HasInGraveyard(new[] { + CardId.Soulpiercer, + CardId.Wakaushi, + CardId.Benkei, + CardId.Wagon, + })||Bot.HasInMonstersZone(new[] { + CardId.Soulpiercer, + CardId.Wagon, + CardId.Wakaushi, + })); + } + private bool DragonRavineField() + { + if (Card.Location == CardLocation.Hand) + return DefaultField(); + return false; + } + + private bool ScarecrowFunction() + { + int tributeId = -1; + if (Bot.HasInHand(CardId.PsyFrameDriver)) + {tributeId = CardId.PsyFrameDriver;} + else if (Bot.HasInHand(CardId.PsyFramegearGamma)) + {tributeId = CardId.PsyFramegearGamma;} + else if (Bot.HasInHand(CardId.Benkei)) + {tributeId = CardId.Benkei;} + else if (Bot.HasInHand(CardId.HauntedMansion)) + {tributeId = CardId.HauntedMansion;} + else if (Bot.HasInHand(CardId.EffectVeiler)) + {tributeId = CardId.EffectVeiler;} + else if (Bot.HasInHand(CardId.SnowRabbit)) + {tributeId = CardId.SnowRabbit;} + else if (Bot.HasInHand(CardId.JoyousSpring)) + {tributeId = CardId.JoyousSpring;} + else if (Bot.HasInHand(CardId.Booster)) + {tributeId = CardId.Booster;} + else if (Bot.HasInHand(CardId.Wagon)) + {tributeId = CardId.Wagon;} + else if (Bot.HasInHand(CardId.Scales)) + {tributeId = CardId.Scales;} + else if (Bot.HasInHand(CardId.LockBird)) + {tributeId = CardId.LockBird;} + else if (Bot.HasInHand(CardId.MaxxG)) + {tributeId = CardId.MaxxG;} + int needId = -1; + if (Bot.HasInGraveyard(CardId.Soulpiercer)) + { + if (Bot.HasInGraveyard(CardId.Scales) && !activate_Scales) + {needId = CardId.Scales;} + else + {needId = CardId.Soulpiercer;} + } + else if (Bot.HasInGraveyard(CardId.Masurawo)) + {needId = CardId.Masurawo;} + else if (Bot.HasInGraveyard(CardId.Sarutobi)) + {needId = CardId.Sarutobi;} + else if (Bot.HasInMonstersZone(CardId.Soulpiercer)) + { + if (Bot.HasInGraveyard(CardId.Wakaushi)) + {needId = CardId.Wakaushi;} + if (Bot.HasInGraveyard(CardId.Motorbike)) + {needId = CardId.Motorbike;} + } + if (GetZoneCards(CardLocation.Hand, Bot).Count(card => card != null && card.Id == CardId.Scales) + GetZoneCards(CardLocation.Grave, Bot).Count(card => card != null && card.Id == CardId.Scales) + GetZoneCards(CardLocation.Onfield, Bot).Count(card => card != null && card.Id == CardId.Scales) == 2 && GetZoneCards(CardLocation.Hand, Bot).Count(card => card != null && card.Id == CardId.Scales)>=1 && !activate_Scales) + { + tributeId = CardId.Scales; + needId = CardId.Scales; + } + AI.SelectCard(tributeId); + AI.SelectNextCard(needId); + if (((!Bot.HasInHand(CardId.Wakaushi) && !Bot.HasInSpellZone(CardId.Wakaushi)) || activate_Wakaushi) + && (!Bot.HasInHand(CardId.Motorbike) || activate_Motorbike) + && ((!Bot.HasInHand(CardId.Soulpeacemaker) && !Bot.HasInSpellZone(CardId.Soulpeacemaker)) || activate_Soulpeacemaker) + && (!Bot.HasInSpellZone(CardId.Benkei) || activate_Benkei) + && (needId == CardId.Soulpiercer) + && (!activate_Wakaushi || !activate_Motorbike || !activate_Soulpeacemaker || !activate_Benkei) + ) + { + summon_Scarecrow2 = false; + } + activate_Scarecrow = true; + return true; + } + private bool ScarecrowLinkFunction2() + { + if (!summon_Scarecrow2) + { + summon_Scarecrow2 = true; + return true; + } + return false; + } + private bool UnicornFunction() + { + List Enemycards = GetZoneCards(CardLocation.Onfield,Enemy); + if (Bot.Hand.Count == 0 || Enemycards.Count(card => card != null && !card.IsShouldNotBeTarget()) == 0) + { + if (to_deck) to_deck = false; + return false; + } + int tributeId = -1; + if (Bot.HasInHand(CardId.PsyFrameDriver)) + {tributeId = CardId.PsyFrameDriver;} + else if (Bot.HasInHand(CardId.PsyFramegearGamma)) + {tributeId = CardId.PsyFramegearGamma;} + else if (Bot.HasInHand(CardId.Benkei)) + {tributeId = CardId.Benkei;} + else if (Bot.HasInHand(CardId.HauntedMansion)) + {tributeId = CardId.HauntedMansion;} + else if (Bot.HasInHand(CardId.EffectVeiler)) + {tributeId = CardId.EffectVeiler;} + else if (Bot.HasInHand(CardId.SnowRabbit)) + {tributeId = CardId.SnowRabbit;} + else if (Bot.HasInHand(CardId.JoyousSpring)) + {tributeId = CardId.JoyousSpring;} + else if (Bot.HasInHand(CardId.Booster)) + {tributeId = CardId.Booster;} + else if (Bot.HasInHand(CardId.Wagon)) + {tributeId = CardId.Wagon;} + else if (Bot.HasInHand(CardId.Scales)) + {tributeId = CardId.Scales;} + else if (Bot.HasInHand(CardId.LockBird)) + {tributeId = CardId.LockBird;} + else if (Bot.HasInHand(CardId.MaxxG)) + {tributeId = CardId.MaxxG;} + if (to_deck) to_deck = false; + AI.SelectCard(tributeId); + return true; + } + private bool BoosterEquipFunction() + { + if (Card.Location != CardLocation.Hand || activate_Booster) + return false; + List ChkCardsHand = Bot.Hand.GetMonsters().ToList(); + foreach (var card in ChkCardsHand) + { + if (card.Id == CardId.Motorbike && !activate_Motorbike) return false; + else if (card.Id == CardId.Soulpiercer) return false; + else if (card.Id == CardId.Soulpeacemaker && !activate_Soulpeacemaker) return false; + else if (card.Id == CardId.Wakaushi && !activate_Wakaushi) return false; + else if (card.Id == CardId.Wagon && (!activate_Wagon || !normal_summon)) return false; + else if (card.Id == CardId.Benkei && !activate_Benkei) return false; + } + List ChkCardsSpell = GetZoneCards(CardLocation.SpellZone,Bot).Where(card => card != null && card.IsFaceup()).ToList(); + foreach (var card in ChkCardsSpell) + { + if (card.Id == CardId.Wakaushi && !activate_Wakaushi) return false; + else if (card.Id == CardId.Soulpiercer) return false; + else if (card.Id == CardId.Soulpeacemaker && !activate_Soulpeacemaker) return false; + else if (card.Id == CardId.Wakaushi && !activate_Wakaushi) return false; + else if (card.Id == CardId.Benkei && !activate_Benkei) return false; + } + List ChkCardsMonster = GetZoneCards(CardLocation.MonsterZone,Bot).Where(card => card != null && card.IsFaceup() && card.Level == 4).ToList(); + if (ChkCardsMonster.Count == 0) return false; + foreach (var card in ChkCardsMonster) + { + if (card.Id == CardId.Soulpiercer) return false; + } + List ChkCardsGrave = GetZoneCards(CardLocation.Grave,Bot).ToList(); + foreach (var card in ChkCardsGrave) + { + if (card.Id == CardId.Soulpiercer && (Bot.HasInMonstersZone(CardId.Scarecrow) || Bot.HasInExtra(CardId.Scarecrow))) return false; + else if (card.Level == 4 && card.HasRace(CardRace.Machine) && Bot.HasInHand(CardId.Scales) && !normal_summon) return false; + } + if (Bot.HasInExtra(CardId.IP) && p_summoned) return true; + need_Gear = true; + return true; + } + private bool BoosterEquipFunction2() + { + if (Bot.HasInExtra(CardId.IP) && p_summoned && !activate_Booster) return true; + return false; + } + private bool BoosterEquipFunction3() + { + List cards = GetZoneCards(CardLocation.MonsterZone,Bot).Where(card => card != null && card.IsFaceup() && !FinalCards(card.Id) && card.Id != CardId.Scarecrow).ToList(); + if (Bot.HasInMonstersZone(CardId.IP) && p_summoned && !activate_Booster && cards.Count() == 0) return true; + return false; + } + private bool BoosterFunction() + { + if (Card.Location == CardLocation.SpellZone) + { + activate_Booster = true; + return true; + } + return false; + } + private bool GearGigantXyzFunction() + { + if (need_Gear) + { + need_Gear = false; + return true; + } + return false; + } + private bool GearGigantFunction() + { + if (Card.Location == CardLocation.MonsterZone) + { + List ChkCards = GetZoneCards(CardLocation.MonsterZone,Bot).Where(card => card != null && card.IsFaceup() && card.HasSetcode(0x9a)).ToList(); + int targetid = -1; + if (!Bot.HasInHand(CardId.Motorbike) && !activate_Motorbike) + { + targetid = CardId.Motorbike; + } + else if (!(Bot.HasInHand(CardId.Wakaushi) || Bot.HasInSpellZone(CardId.Wakaushi)) && !activate_Wakaushi) + { + targetid = CardId.Wakaushi; + } + else if (!Bot.HasInHand(CardId.Soulpiercer) && (!normal_summon || (ChkCards.Count >= 1))) + { + targetid = CardId.Soulpiercer; + } + if (targetid > 0) AI.SelectCard(targetid); + return true; + } + return false; + } + private bool SoulpiercerEquipFunction() + { + if (Card.Location != CardLocation.Hand) + return false; + int tributeId = -1; + if (Bot.HasInMonstersZone(CardId.Wagon)) + {tributeId = CardId.Wagon;} + else if (Bot.HasInMonstersZone(CardId.Wakaushi)) + {tributeId = CardId.Wakaushi;} + AI.SelectCard(tributeId); + return Bot.HasInMonstersZone(new[] { + CardId.Wakaushi, + CardId.Wagon, + }); + } + private bool SoulpeacemakerEquipFunction() + { + if (Card.Location != CardLocation.Hand) + return false; + int tributeId = -1; + List cards = Bot.GetMonstersInExtraZone().Where(card => card != null && card.Id == CardId.Scarecrow).ToList(); + if (cards.Count() > 0) + AI.SelectCard(cards); + else + { + if (Bot.HasInMonstersZone(CardId.Scarecrow)) + {tributeId = CardId.Scarecrow;} + else if (Bot.HasInMonstersZone(CardId.Soulpiercer)) + {tributeId = CardId.Soulpiercer;} + AI.SelectCard(tributeId); + } + return Bot.HasInMonstersZone(new[] { + CardId.Scarecrow, + CardId.Soulpiercer, + }); + } + private bool SoulhornsEquipFunction() + { + if (Card.Location != CardLocation.Hand) + return false; + int tributeId = -1; + if (Bot.HasInMonstersZone(CardId.Masurawo)) + {tributeId = CardId.Masurawo;} + else if (Bot.HasInMonstersZone(CardId.Sarutobi)) + {tributeId = CardId.Sarutobi;} + AI.SelectCard(tributeId); + return Bot.HasInMonstersZone(new[] { + CardId.Masurawo, + CardId.Sarutobi, + }); + } + private bool SoulpeacemakerFunction() + { + if (Card.Location == CardLocation.SpellZone) + { + int tributeId = -1; + if (Bot.HasInMonstersZone(CardId.Soulpiercer)) + {tributeId = CardId.Wakaushi;} + else if (Bot.HasInGraveyard(CardId.Soulpiercer)||!activate_Scales) + {tributeId = CardId.Scales;} + else if (!Bot.HasInGraveyard(CardId.Soulpiercer)||activate_Scales) + {tributeId = CardId.Soulpiercer;} + AI.SelectCard(tributeId); + activate_Soulpeacemaker = true; + return true; + } + return false; + } + private bool GeniusLinkFunction() + { + if ((Bot.MonsterZone[4] != null && Bot.MonsterZone[4].Controller == 0 && !FinalCards(Bot.MonsterZone[4].Id)) && (Bot.MonsterZone[0] != null && Bot.MonsterZone[0].Controller == 0 && !FinalCards(Bot.MonsterZone[0].Id))) + return false; + List Pcards = GetZoneCards(CardLocation.Hand, Bot).Where(card => card != null && card.HasSetcode(0x9a) && card.Level > 1 && card.Level < 8).ToList(); + if (Pcards.Count() < 2 && !Bot.HasInMonstersZone(CardId.Soulpiercer)) return false; + List Rcards = GetZoneCards(CardLocation.Removed, Bot).Where(card => card != null && card.Id == CardId.Regulus).ToList(); + if (Bot.HasInHand(CardId.Regulus) || Bot.HasInGraveyard(CardId.Regulus) || Bot.HasInSpellZone(CardId.Regulus) || Bot.HasInMonstersZone(CardId.Regulus) || Rcards.Count() > 0) return false; + bool linkchk = false; + List materials = new List(); + if (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].Controller == 0 && Bot.MonsterZone[6].Id != CardId.Scarecrow && !FinalCards(Bot.MonsterZone[6].Id)) + { + materials.Add(Bot.MonsterZone[6]); + linkchk = true; + } + else if (Bot.MonsterZone[5] != null && Bot.MonsterZone[5].Controller == 0 && Bot.MonsterZone[5].Id != CardId.Scarecrow && !FinalCards(Bot.MonsterZone[5].Id)) + { + materials.Add(Bot.MonsterZone[5]); + linkchk = true; + } + List cards = Bot.GetMonstersInMainZone().Where(card => card != null && card.IsFaceup() && card.HasRace(CardRace.Machine)).ToList(); + foreach (var card in cards) + { + if (card == null || FinalCards(card.Id)) continue; + else materials.Add(card); + } + if (materials.Count <=1) return false; + AI.SelectMaterials(materials); + return ((Bot.GetMonstersInExtraZone().Count == 0 || linkchk) && !p_summoned && !activate_Genius); + } + private bool GeniusFunction() + { + if (ActivateDescription == Util.GetStringId(CardId.Genius,1)) + { + AI.SelectCard(CardId.Regulus); + activate_Genius = true; + return true; + } + return false; + } + private bool ElfLinkFunction() + { + if (!Bot.HasInGraveyard(CardId.Motorbike)) return false; + List materials = new List(); + if (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].Controller == 0 && !FinalCards(Bot.MonsterZone[6].Id)) + { + materials.Add(Bot.MonsterZone[6]); + } + else if (Bot.MonsterZone[5] != null && Bot.MonsterZone[5].Controller == 0 && !FinalCards(Bot.MonsterZone[5].Id)) + { + materials.Add(Bot.MonsterZone[5]); + } + List TunrerCards = Bot.GetMonstersInMainZone().Where(card => card != null && card.IsFaceup() && TurnerCards(card.Id) && !FinalCards(card.Id)).ToList(); + List UnTunrercards = Bot.GetMonstersInMainZone().Where(card => card != null && card.IsFaceup() && !TurnerCards(card.Id) && !FinalCards(card.Id)).ToList(); + if (UnTunrercards.Count == 0) return false; + else if (TunrerCards.Count >= UnTunrercards.Count && UnTunrercards.Count > 0) + { + foreach (var card in TunrerCards) + { + if (card == null) continue; + else if (materials.Count(ccard =>ccard != null && ccard.Id == card.Id) <= 0) materials.Add(card); + } + } + else + { + foreach (var card in UnTunrercards) + { + if (card == null) continue; + else if (materials.Count(ccard =>ccard != null && ccard.Id == card.Id) <= 0) materials.Add(card); + } + } + if (materials.Count <=1) return false; + AI.SelectMaterials(materials); + summon_Elf = true; + return true; + } + private bool ElfFunction() + { + if (Duel.Player == 0) + { + activate_Elf = true; + AI.SelectCard(CardId.Motorbike); + return Bot.HasInGraveyard(CardId.Motorbike); + } + List cards1 = GetZoneCards(CardLocation.MonsterZone, Enemy); + List cards2 = GetZoneCards(CardLocation.SpellZone, Enemy); + if (cards1.Count() > 0 || cards2.Count() >= 3) + { + if (Bot.HasInExtra(CardId.Unicorn) && Bot.HasInGraveyard(CardId.IP)) + AI.SelectCard(CardId.IP); + else + { + AI.SelectCard(CardId.Motorbike); + AI.SelectPosition(CardPosition.FaceUpDefence); + } + activate_Elf = true; + return Bot.HasInGraveyard(CardId.Motorbike) || Bot.HasInGraveyard(CardId.IP); + } + return false; + } + private bool RegulusFunction() + { + if (Card.Location == CardLocation.Hand) + { + int tributeId = -1; + if (Bot.HasInGraveyard(CardId.Soulpiercer)) + {tributeId = CardId.Soulpiercer;} + else if (Bot.HasInGraveyard(CardId.Motorbike)) + {tributeId = CardId.Motorbike;} + AI.SelectCard(tributeId); + activate_Genius = true; + return true; + } + else if (Duel.LastChainPlayer == 1) + { + return true; + } + return false; + } + private bool FleurFunction() + { + if (ActivateDescription == Util.GetStringId(CardId.Fleur, 0)) + { + ClientCard card = Util.GetProblematicEnemyMonster(0, true); + if (card != null) + { + AI.SelectCard(card); + return true; + } + card = Util.GetBestEnemySpell(true); + if (card != null) + { + AI.SelectCard(card); + return true; + } + List cards = GetZoneCards(CardLocation.Onfield, Enemy); + cards = cards.Where(tcard => tcard != null && !tcard.IsShouldNotBeTarget()).ToList(); + if (cards.Count <= 0) return false; + AI.SelectCard(cards); + return true; + } + else if (ActivateDescription == Util.GetStringId(CardId.Fleur, 1)) + { + return Duel.LastChainPlayer == 1; + } + return false; + } + private bool IPLinkFunction() + { + List materials = GetZoneCards(CardLocation.MonsterZone,Bot).Where(card => card != null && card.IsFaceup() && card.Id != CardId.Scarecrow && (card.Id != CardId.Elf || (card.Id == CardId.Elf && !summon_Elf)) && !FinalCards(card.Id)).ToList(); + if (materials.Count <=1) return false; + if (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].Controller == 0 && Bot.MonsterZone[6].HasType(CardType.Link)) + { + if (Bot.MonsterZone[2] != null && FinalCards(Bot.MonsterZone[2].Id) && Bot.MonsterZone[4] != null && FinalCards(Bot.MonsterZone[4].Id)) + return false; + } + else if (Bot.MonsterZone[5] != null && Bot.MonsterZone[5].Controller == 0 && Bot.MonsterZone[5].HasType(CardType.Link)) + { + if (Bot.MonsterZone[2] != null && FinalCards(Bot.MonsterZone[2].Id) && Bot.MonsterZone[0] != null && FinalCards(Bot.MonsterZone[0].Id)) + return false; + } + AI.SelectMaterials(materials); + return true; + } + private bool PSYFunction() + { + activate_PSY = true; + return true; + } + private bool IPFunction() + { + if (Duel.LastChainPlayer == 0) return false; + if (Bot.HasInExtra(CardId.Unicorn)) + { + List material = new List(); + List cards = GetZoneCards(CardLocation.MonsterZone,Bot).Where(card => card != null && card != Card && card.IsFaceup() && !FinalCards(card.Id) && card.Id != CardId.IP && card.Id != CardId.Scarecrow).ToList(); + List Enemycards = GetZoneCards(CardLocation.MonsterZone,Enemy); + if (activate_Sarutobi) Enemycards = GetZoneCards(CardLocation.Onfield,Enemy); + if (Bot.Hand.Count == 0 || Enemycards.Count(card => card != null && !card.IsShouldNotBeTarget()) == 0 || cards.Count == 0) return false; + bool linkchk = false; + foreach (var card in cards) + { + if (card != null && (card.Id != CardId.Elf || (card.Id == CardId.Elf && !summon_Elf))) + { + material.Add(card); + linkchk = true; + break; + } + } + AI.SelectCard(CardId.Unicorn); + material.Insert(0,Card); + AI.SelectMaterials(material); + if (!to_deck) to_deck = true; + return linkchk; + } + return false; + } + private bool SarutobiFunction() + { + List Enemycards = GetZoneCards(CardLocation.SpellZone,Enemy); + if (Enemycards.Count(card => card != null && !card.IsShouldNotBeTarget()) == 0 || to_deck) return false; + AI.SelectCard(Enemycards); + activate_Sarutobi = true; + return true; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SwordsoulExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SwordsoulExecutor.cs new file mode 100644 index 0000000..553d402 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/SwordsoulExecutor.cs @@ -0,0 +1,3118 @@ +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using System.Linq; +using System; +using YGOSharp.OCGWrapper; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Swordsoul", "AI_Swordsoul")] + + public class SwordsoulExecutor : DefaultExecutor + { + public class CardId + { + public const int NibiruThePrimalBeing = 27204311; + public const int TenyiSpirit_Ashuna = 87052196; + public const int TenyiSpirit_Vishuda = 23431858; + public const int SwordsoulStrategistLongyuan = 93490856; + public const int SwordsoulOfTaia = 56495147; + public const int SwordsoulOfMoYe = 20001443; + public const int IncredibleEcclesiaTheVirtuous = 55273560; + // _CardId.AshBlossom = 14558127; + // _CardId.MaxxC = 23434538; + // _CardId.EffectVeiler = 97268402; + public const int TenyiSpirit_Adhara = 98159737; + + // _CardId.PotOfDesires = 35261759; + public const int SwordsoulEmergence = 56465981; + public const int SwordsoulSacredSummit = 93850690; + // _CardId.CalledByTheGrave = 24224830; + public const int CrossoutDesignator = 65681983; + + // _CardId.InfiniteImpermanence = 10045474; + public const int SwordsoulBlackout = 14821890; + + public const int GeomathmechFinalSigma = 42632209; + public const int PsychicEndPunisher = 60465049; + public const int SwordsoulSupremeSovereign_Chengying = 96633955; + public const int BaronneDeFleur = 84815190; + public const int SwordsoulSinisterSovereign_QixingLongyuan = 47710198; + public const int AdamancipatorRisen_Dragite = 9464441; + public const int DracoBerserkerOfTheTenyi = 5041348; + public const int SwordsoulGrandmaster_Chixiao = 69248256; + public const int BaxiaBrightnessOfTheYangZing = 83755611; + public const int YaziEvilOfTheYangZing = 43202238; + public const int ShamanOfTheTenyi = 78917791; + public const int MonkOfTheTenyi = 32519092; + + public const int SwordsoulToken = 20001444; + + public const int NaturalExterio = 99916754; + public const int NaturalBeast = 33198837; + public const int ImperialOrder = 61740673; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecree = 51452091; + public const int Number41BagooskatheTerriblyTiredTapir = 90590303; + public const int InspectorBoarder = 15397015; + } + + public SwordsoulExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // startup effect + AddExecutor(ExecutorType.Activate, CardId.BaxiaBrightnessOfTheYangZing, BaxiaBrightnessOfTheYangZingActivate); + AddExecutor(ExecutorType.Activate, CardId.YaziEvilOfTheYangZing, YaziEvilOfTheYangZingActivate); + AddExecutor(ExecutorType.Activate, CardId.IncredibleEcclesiaTheVirtuous, IncredibleEcclesiaTheVirtuousActivate); + + // quick effect + AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, CalledbytheGraveActivate); + AddExecutor(ExecutorType.Activate, CardId.CrossoutDesignator, CrossoutDesignatorActivate); + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossomActivate); + AddExecutor(ExecutorType.Activate, CardId.SwordsoulGrandmaster_Chixiao, SwordsoulGrandmaster_ChixiaoActivate); + AddExecutor(ExecutorType.Activate, _CardId.EffectVeiler, EffectVeilerActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, CardId.SwordsoulSinisterSovereign_QixingLongyuan, SwordsoulSinisterSovereign_QixingLongyuanActivate); + AddExecutor(ExecutorType.Activate, CardId.DracoBerserkerOfTheTenyi, DracoBerserkerOfTheTenyiActivate); + AddExecutor(ExecutorType.Activate, CardId.AdamancipatorRisen_Dragite, AdamancipatorRisen_DragiteActivate); + AddExecutor(ExecutorType.Activate, CardId.BaronneDeFleur, BaronneDeFleurActivate); + AddExecutor(ExecutorType.Activate, CardId.SwordsoulSupremeSovereign_Chengying, SwordsoulSupremeSovereign_ChengyingActivate); + + // free chain + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + AddExecutor(ExecutorType.Activate, CardId.NibiruThePrimalBeing, NibiruThePrimalBeingActivate); + + // startup effect + AddExecutor(ExecutorType.Activate, CardId.SwordsoulEmergence, SwordsoulEmergenceActivate); + AddExecutor(ExecutorType.Activate, CardId.SwordsoulBlackout, SwordsoulBlackoutActivate); + + // synchro + AddExecutor(ExecutorType.SpSummon, CardId.YaziEvilOfTheYangZing, YaziEvilOfTheYangZingSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.BaxiaBrightnessOfTheYangZing, BaxiaBrightnessOfTheYangZingSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SwordsoulGrandmaster_Chixiao, SwordsoulGrandmaster_ChixiaoSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.AdamancipatorRisen_Dragite, AdamancipatorRisen_DragiteSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.DracoBerserkerOfTheTenyi, DracoBerserkerOfTheTenyiSpSummon); + + AddExecutor(ExecutorType.SpSummon, Level10SpSummonCheckInit); + AddExecutor(ExecutorType.SpSummon, Level10SpSummonCheckCount); + AddExecutor(ExecutorType.SpSummon, Level10SpSummonCheckDecide); + AddExecutor(ExecutorType.SpSummon, Level10SpSummonCheckFinal); + + // startup effect + AddExecutor(ExecutorType.Activate, CardId.SwordsoulOfMoYe, SwordsoulOfMoYeActivate); + AddExecutor(ExecutorType.Activate, CardId.SwordsoulOfTaia, SwordsoulOfTaiaActivate); + + // summon + AddExecutor(ExecutorType.Activate, TenyiForShamanSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.IncredibleEcclesiaTheVirtuous, IncredibleEcclesiaTheVirtuousSpSummon); + AddExecutor(ExecutorType.Summon, CardId.SwordsoulOfMoYe, SwordsoulOfMoYeSummon); + AddExecutor(ExecutorType.Summon, CardId.IncredibleEcclesiaTheVirtuous, IncredibleEcclesiaTheVirtuousSummon); + AddExecutor(ExecutorType.Summon, CardId.SwordsoulOfTaia, SwordsoulOfTaiaSummon); + + // activate + AddExecutor(ExecutorType.Activate, CardId.SwordsoulStrategistLongyuan, SwordsoulStrategistLongyuanActivate); + AddExecutor(ExecutorType.Activate, _CardId.PotOfDesires, PotOfDesiresActivate); + AddExecutor(ExecutorType.Activate, CardId.ShamanOfTheTenyi, ShamanOfTheTenyiActivate); + AddExecutor(ExecutorType.Activate, CardId.SwordsoulSacredSummit, SwordsoulSacredSummitActivate); + AddExecutor(ExecutorType.Activate, CardId.TenyiSpirit_Vishuda, TenyiSpirit_VishudaActivate); + AddExecutor(ExecutorType.Activate, CardId.TenyiSpirit_Ashuna, TenyiSpirit_AshunaActivate); + AddExecutor(ExecutorType.Activate, CardId.TenyiSpirit_Adhara, TenyiSpirit_AdharaActivate); + AddExecutor(ExecutorType.Activate, TenyiForBlackoutSpSummon); + + // other + AddExecutor(ExecutorType.SpSummon, CardId.GeomathmechFinalSigma, GeomathmechFinalSigmaSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.PsychicEndPunisher, PsychicEndPunisherSpSummon); + AddExecutor(ExecutorType.Summon, TunerForSynchroSummon); + AddExecutor(ExecutorType.Summon, WyrmForBlackoutSummon); + AddExecutor(ExecutorType.SpSummon, CardId.ShamanOfTheTenyi, ShamanOfTheTenyiSpSummon); + AddExecutor(ExecutorType.SpSummon, CardId.MonkOfTheTenyi, MonkOfTheTenyiSpSummon); + AddExecutor(ExecutorType.Repos, DefaultMonsterRepos); + + AddExecutor(ExecutorType.Activate, CardId.PsychicEndPunisher, PsychicEndPunisherActivate); + AddExecutor(ExecutorType.SpellSet, SpellSetCheck); + } + + const int SetcodeTimeLord = 0x4a; + const int SetcodeYangZing = 0x9e; + const int SetcodePhantom = 0xdb; + const int SetcodeOrcust = 0x11b; + const int SetcodeTenyi = 0x12c; + const int SetcodeSwordsoul = 0x16b; + const int SetcodeFloowandereeze = 0x16d; + List normalCounterList = new List + { + _CardId.AshBlossom, CardId.BaronneDeFleur, 27548199, 4280258, 53262004 + }; + List notToNegateIdList = new List{ + 58699500 + }; + const int hintTimingMainEnd = 0x4; + const int hintReplaceDestroy = 96; + + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.SwordsoulStrategistLongyuan, CardId.SwordsoulOfTaia, CardId.SwordsoulOfMoYe, CardId.IncredibleEcclesiaTheVirtuous, + _CardId.AshBlossom, _CardId.MaxxC, _CardId.EffectVeiler, CardId.SwordsoulEmergence, _CardId.InfiniteImpermanence }}, + {2, new List { CardId.TenyiSpirit_Ashuna, _CardId.PotOfDesires, _CardId.CalledByTheGrave, CardId.SwordsoulBlackout }}, + {1, new List { CardId.NibiruThePrimalBeing, CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Adhara, CardId.SwordsoulSacredSummit, + CardId.CrossoutDesignator }}, + }; + + List currentNegatingIdList = new List(); + bool enemyActivateMaxxC = false; + bool enemyActivateLockBird = false; + bool enemyActivateInfiniteImpermanenceFromHand = false; + List infiniteImpermanenceList = new List(); + + bool summoned = false; + bool onlyWyrmSpSummon = false; + List activatedCardIdList = new List(); + List canSpSummonLevel10IdList = new List(); + + List effectUsedBaronneDeFleurList = new List(); + List currentNegateMonsterList = new List(); + + /// + /// Shuffle List and return a random-order card list + /// + public List ShuffleCardList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(result.Count); + int nextIndex = (index + Program.Rand.Next(result.Count - 1)) % result.Count; + ClientCard tempCard = result[index]; + result[index] = result[nextIndex]; + result[nextIndex] = tempCard; + } + return result; + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false) + { + List floodagateList = Enemy.GetMonsters().Where(c => c?.Data != null && + c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (floodagateList.Count() > 0) + { + floodagateList.Sort(CardContainer.CompareCardAttack); + floodagateList.Reverse(); + return floodagateList[0]; + } + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.IsMonsterDangerous() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (dangerList.Count() > 0) + { + dangerList.Sort(CardContainer.CompareCardAttack); + dangerList.Reverse(); + return dangerList[0]; + } + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && + c.IsMonsterInvincible() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (invincibleList.Count() > 0) + { + invincibleList.Sort(CardContainer.CompareCardAttack); + invincibleList.Reverse(); + return invincibleList[0]; + } + + if (attack == 0) + attack = Util.GetBestAttack(Bot); + List betterList = Enemy.MonsterZone.GetMonsters() + .Where(card => card.GetDefensePower() >= attack && card.IsAttack() && (!canBeTarget || !card.IsShouldNotBeTarget())).ToList(); + if (betterList.Count() > 0) + { + betterList.Sort(CardContainer.CompareCardAttack); + betterList.Reverse(); + return betterList[0]; + } + return null; + } + + public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreNormalSpell = false) + { + List resultList = new List(); + + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (floodagateList.Count() > 0) + { + floodagateList.Sort(CardContainer.CompareCardAttack); + floodagateList.Reverse(); + resultList.AddRange(floodagateList); + } + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !resultList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (problemEnemySpellList.Count() > 0) + { + resultList.AddRange(ShuffleCardList(problemEnemySpellList)); + } + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (dangerList.Count() > 0 + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) + { + dangerList.Sort(CardContainer.CompareCardAttack); + dangerList.Reverse(); + resultList.AddRange(dangerList); + } + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (invincibleList.Count() > 0) + { + invincibleList.Sort(CardContainer.CompareCardAttack); + invincibleList.Reverse(); + resultList.AddRange(invincibleList); + } + + List enemyMonsters = Enemy.GetMonsters().ToList(); + if (enemyMonsters.Count() > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + foreach(ClientCard target in enemyMonsters) + { + if (target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2) ) + { + if (!canBeTarget || !(target.IsShouldNotBeTarget() || target.IsShouldNotBeMonsterTarget())) + { + if (!resultList.Contains(target)) + { + resultList.Add(target); + } + } + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous)).ToList(); + if (spells.Count() > 0 && !ignoreNormalSpell) + { + resultList.AddRange(ShuffleCardList(spells)); + } + + return resultList; + } + + 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 monsters = Enemy.GetMonsters(); + + // after GetHighestAttackMonster, the left monsters must be face-down. + if (monsters.Count() > 0 && !onlyFaceup) + return ShuffleCardList(monsters)[0]; + + return null; + } + + public ClientCard GetBestEnemySpell(bool onlyFaceup = false, bool canBeTarget = false) + { + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (problemEnemySpellList.Count() > 0) + { + return ShuffleCardList(problemEnemySpellList)[0]; + } + + List spells = Enemy.GetSpells().Where(card => !(card.IsFaceup() && card.IsCode(_CardId.EvenlyMatched))).ToList(); + + List faceUpList = spells.Where(ecard => ecard.IsFaceup() && + ecard.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous)).ToList(); + if (faceUpList.Count() > 0) + { + return ShuffleCardList(faceUpList)[0]; + } + + if (spells.Count() > 0 && !onlyFaceup) + { + return ShuffleCardList(spells)[0]; + } + + return null; + } + + public ClientCard GetBestEnemyCard(bool onlyFaceup = false, bool canBeTarget = false, bool checkGrave = false) + { + ClientCard card = GetBestEnemyMonster(onlyFaceup, canBeTarget); + if (card != null) + { + return card; + } + + card = GetBestEnemySpell(onlyFaceup, canBeTarget); + if (card != null) + { + return card; + } + + if (checkGrave && Enemy.Graveyard.Count() > 0) + { + List graveMonsterList = Enemy.Graveyard.GetMatchingCards(c => c.IsMonster()).ToList(); + if (graveMonsterList.Count() > 0) + { + graveMonsterList.Sort(CardContainer.CompareCardAttack); + graveMonsterList.Reverse(); + return graveMonsterList[0]; + } + return ShuffleCardList(Enemy.Graveyard.ToList())[0]; + } + + return null; + } + + public List GetNormalEnemyTargetList(bool canBeTarget = true) + { + List targetList = GetProblematicEnemyCardList(canBeTarget); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card)).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleCardList(Enemy.GetSpells())); + targetList.AddRange(ShuffleCardList(Enemy.GetMonsters().Where(card => card.IsFacedown()).ToList())); + + return targetList; + } + + public List GetMonsterListForTargetNegate(bool canBeMonsterTarget = false, bool canBeTrapTarget = false) + { + List resultList = new List(); + if (CheckWhetherNegated()) + { + return resultList; + } + + // negate before used + ClientCard target = Enemy.MonsterZone.FirstOrDefault(card => card?.Data != null + && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && !card.IsShouldNotBeTarget() + && (!canBeMonsterTarget || !card.IsShouldNotBeMonsterTarget()) && (!canBeTrapTarget || !card.IsShouldNotBeSpellTrapTarget()) + && !currentNegateMonsterList.Contains(card)); + if (target != null) + { + resultList.Add(target); + } + + // negate monster effect on the field + foreach (ClientCard chainingCard in Duel.CurrentChain) + { + if (chainingCard.Location == CardLocation.MonsterZone && chainingCard.Controller == 1 && !chainingCard.IsDisabled() + && (!canBeMonsterTarget || !chainingCard.IsShouldNotBeMonsterTarget()) && (!canBeTrapTarget || !chainingCard.IsShouldNotBeSpellTrapTarget()) + && !chainingCard.IsShouldNotBeTarget() && !currentNegateMonsterList.Contains(chainingCard)) + { + resultList.Add(chainingCard); + } + } + + return resultList; + } + + /// + /// Check whether negate opposite's effect and clear flag + /// + public void CheckDeactiveFlag() + { + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && Duel.LastChainPlayer == 1) + { + if (lastChainCard.Controller == 1 && lastChainCard.Location == CardLocation.MonsterZone) + { + currentNegateMonsterList.Add(lastChainCard); + } + } + } + + /// + /// Check negated turn count of id + /// + public int CheckCalledbytheGrave(int id) + { + if (currentNegatingIdList.Contains(id)) return 1; + if (DefaultCheckWhetherCardIdIsNegated(id)) return 1; + return 0; + } + + /// + /// Check remain cards in deck + /// + /// Card's ID + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + + /// + /// Whether spell or trap will be negate. If so, return true. + /// + /// is counter trap + /// check target + /// + public bool CheckSpellWillBeNegate(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.RoyalDecree, true) || Bot.HasInSpellZone(CardId.RoyalDecree, true)) return true; + } + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceList.Contains(selfSeq)) { + return true; + } + } + // how to get here? + return false; + } + + /// + /// Check whether'll be negated + /// + /// check whether card itself is disabled. + public bool CheckWhetherNegated() + { + if ((Card.IsSpell() || Card.IsTrap()) && CheckSpellWillBeNegate()){ + return true; + } + if (DefaultCheckWhetherCardIsNegated(Card)) { + return true; + } + if (Card.IsMonster() && Card.Location == CardLocation.MonsterZone && Card.IsDefense()) + { + if (Enemy.MonsterZone.Any(card => CheckNumber41(card)) || Bot.MonsterZone.Any(card => CheckNumber41(card))) + { + return true; + } + } + return false; + } + + public bool CheckNumber41(ClientCard card) + { + return card != null && card.IsFaceup() && card.IsCode(CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled(); + } + + /// + /// Check whether bot is at advantage. + /// + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && + (Bot.GetMonsters().Any(card => card.IsFaceup()) || (Duel.Player == 0 && Duel.Turn == 1))) + { + return true; + } + return false; + } + + /// + /// Check whether last chain card should be disabled. + /// + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + if (lastcard.IsMonster() && lastcard.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (notToNegateIdList.Contains(lastcard.Id)) return false; + if (DefaultCheckWhetherCardIsNegated(lastcard)) return false; + if (Duel.CurrentChain.Count >= 2) + { + ClientCard lastlastChainCard = Duel.CurrentChain[Duel.CurrentChain.Count - 2]; + ClientCard lastChainCard = Duel.CurrentChain[Duel.CurrentChain.Count - 1]; + if (lastlastChainCard?.Controller == 0 && lastChainCard?.Controller == 1 && lastChainCard.IsCode(normalCounterList)) + { + bool notImportantFlag = lastlastChainCard.Location == CardLocation.Grave + && (lastlastChainCard.IsCode(CardId.SwordsoulOfTaia) || lastlastChainCard.IsCode(CardId.SwordsoulOfMoYe) || lastlastChainCard.IsCode(CardId.SwordsoulStrategistLongyuan)); + notImportantFlag |= lastlastChainCard.IsCode(CardId.PsychicEndPunisher) && Bot.LifePoints < Enemy.LifePoints; + if (notImportantFlag) + { + return false; + } + } + } + + return true; + } + + /// + /// check enemy's dangerous card in grave + /// + public List CheckDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && (card.HasSetcode(SetcodeOrcust) || card.HasSetcode(SetcodePhantom))).ToList(); + List dangerMonsterIdList = new List{ + 99937011, 63542003, CardId.TenyiSpirit_Adhara, CardId.TenyiSpirit_Ashuna, CardId.TenyiSpirit_Vishuda, + 9411399, 28954097, 30680659 + }; + return result; + } + + /// + /// go first + /// + public override bool OnSelectHand() + { + return true; + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + // Geomathmech Final Sigma always place on extra monster zone + if (cardId == CardId.GeomathmechFinalSigma && location == CardLocation.MonsterZone) + { + if ((Zones.z5 & available) > 0) return Zones.z5; + if ((Zones.z6 & available) > 0) return Zones.z6; + } + return base.OnSelectPlace(cardId, player, location, available); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (cardData.Id == CardId.PsychicEndPunisher) + { + return CardPosition.FaceUpAttack; + } + if (Util.IsTurn1OrMain2()) + { + bool turnDefense = false; + if (!cardData.HasType(CardType.Synchro) || cardData.Attack <= cardData.Defense) + { + turnDefense = true; + } + if (turnDefense) + { + return CardPosition.FaceUpDefence; + } + } + if (Duel.Player == 1) + { + if (!cardData.HasType(CardType.Synchro) || cardData.Defense >= cardData.Attack || Util.IsOneEnemyBetterThanValue(cardData.Attack, true)) + { + return CardPosition.FaceUpDefence; + } + } else if (cardData.HasType(CardType.Synchro)) + { + return CardPosition.FaceUpAttack; + } + int bestBotAttack = Math.Max(Util.GetBestAttack(Bot), cardData.Attack); + if (Util.IsAllEnemyBetterThanValue(bestBotAttack, true)) + { + return CardPosition.FaceUpDefence; + } + } + return base.OnSelectPosition(cardId, positions); + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (Util.ChainContainPlayer(1) && hint == HintMsg.Remove && Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + int botCount = Bot.GetMonsterCount() + Bot.GetSpellCount(); + int oppositeCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount(); + if (botCount - oppositeCount == min && min == max) + { + Logger.DebugWriteLine("=== Evenly Matched activated."); + List banishList = new List(); + List botMonsters = Bot.GetMonsters().Where(card => !card.HasType(CardType.Token)).ToList(); + + // non-synchro monster + List faceDownMonsters = botMonsters.Where(card => card.IsFacedown()).ToList(); + banishList.AddRange(faceDownMonsters); + List nonSynchroMonsters = botMonsters.Where(card => !card.HasType(CardType.Synchro) && !banishList.Contains(card)).ToList(); + nonSynchroMonsters.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(nonSynchroMonsters); + + // spells + List spells = Bot.GetSpells(); + banishList.AddRange(ShuffleCardList(spells)); + + // synchro monster + List synchroMonsters = botMonsters.Where(card => card.HasType(CardType.Synchro) && !banishList.Contains(card)).ToList(); + synchroMonsters.Sort(CardContainer.CompareCardAttack); + banishList.AddRange(synchroMonsters); + + return Util.CheckSelectCount(banishList, cards, min, max); + } + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + public override void OnNewTurn() + { + enemyActivateMaxxC = false; + enemyActivateLockBird = false; + + infiniteImpermanenceList.Clear(); + + summoned = false; + onlyWyrmSpSummon = false; + enemyActivateInfiniteImpermanenceFromHand = false; + activatedCardIdList.Clear(); + currentNegateMonsterList.Clear(); + currentNegatingIdList.Clear(); + base.OnNewTurn(); + } + + public override void OnChainSolved(int chainIndex) + { + ChainInfo currentCard = Duel.GetCurrentSolvingChainInfo(); + if (currentCard != null && !Duel.IsCurrentSolvingChainNegated() && currentCard.ActivatePlayer == 1) + { + if (currentCard.IsCode(_CardId.MaxxC)) + enemyActivateMaxxC = true; + if (currentCard.IsCode(_CardId.LockBird)) + enemyActivateLockBird = true; + if (currentCard.IsCode(_CardId.InfiniteImpermanence) && !enemyActivateInfiniteImpermanenceFromHand) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == currentCard.RelatedCard) + { + infiniteImpermanenceList.Add(4 - i); + break; + } + } + } + } + } + + public override void OnChainEnd() + { + currentNegateMonsterList.Clear(); + currentNegatingIdList.Clear(); + for (int idx = effectUsedBaronneDeFleurList.Count() - 1; idx >= 0; -- idx) + { + ClientCard checkTarget = effectUsedBaronneDeFleurList[idx]; + if (checkTarget == null || checkTarget.IsFacedown() || checkTarget.Location != CardLocation.MonsterZone) + { + effectUsedBaronneDeFleurList.RemoveAt(idx); + } + } + enemyActivateInfiniteImpermanenceFromHand = false; + base.OnChainEnd(); + } + + public override void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + if (previousControler == 1) + { + if (card != null) + { + if (card.IsCode(_CardId.InfiniteImpermanence) && previousLocation == (int)CardLocation.Hand && currentLocation == (int)CardLocation.SpellZone) + enemyActivateInfiniteImpermanenceFromHand = true; + } + } + + base.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + /// + /// Select spell/trap's place randomly to avoid InfiniteImpermanence and so on. + /// + /// Card to set(default current card) + /// Whether need to avoid InfiniteImpermanence + /// Whether need to avoid set in this place + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceList.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public bool NibiruThePrimalBeingActivate() + { + if (CheckWhetherNegated()) return false; + if (Duel.Player == 0 || Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasType(CardType.Synchro))) + { + return false; + } + + if (Util.GetBestAttack(Enemy) > Util.GetBestAttack(Bot)) + { + // end main phase + if ((CurrentTiming & hintTimingMainEnd) != 0) + { + SelectNibiruPosition(); + return true; + } + + // avoid Baronne de Fleur + List tunerList = Enemy.GetMonsters().Where(card => card.IsFaceup() && card.IsTuner() && !card.HasType(CardType.Xyz | CardType.Link)).ToList(); + List nonTunerList = Enemy.GetMonsters().Where(card => card.IsFaceup() && !card.IsTuner() && !card.HasType(CardType.Xyz | CardType.Link)).ToList(); + foreach (ClientCard tuner in tunerList) + { + foreach (ClientCard nonTuner in nonTunerList) + { + if (tuner.Level + nonTuner.Level == 10) + { + SelectNibiruPosition(); + return true; + } + } + } + } + + return false; + } + + public void SelectNibiruPosition() + { + int totalAttack = Bot.GetMonsters().Where(card => card.IsFaceup()).Sum(m => (int?)m.Attack) ?? 0; + totalAttack += Enemy.GetMonsters().Where(card => card.IsFaceup()).Sum(m => (int?)m.Attack) ?? 0; + Logger.DebugWriteLine("Nibiru token attack: " + totalAttack.ToString()); + if (totalAttack >= 3000) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + AI.SelectPosition(CardPosition.FaceUpDefence); + } else { + AI.SelectPosition(CardPosition.FaceUpAttack); + AI.SelectPosition(CardPosition.FaceUpAttack); + } + } + + public bool TenyiSpirit_AshunaActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.TenyiSpirit_Ashuna, 0)) + { + // special summon + if (TenyiSpSummonForTaiaCheck() || Level7TenyiSpSummonCheck()) + { + return true; + } + + } else if (ActivateDescription == Util.GetStringId(CardId.TenyiSpirit_Ashuna, 1) && Card.Location == CardLocation.Grave && CheckCalledbytheGrave(Card.Id) == 0) + { + // deck summon + + // trigger blackout + if (Bot.HasInHandOrInSpellZone(CardId.SwordsoulBlackout)) + { + List blackoutTarget = Bot.GetMonsters().Where(card => card.IsFaceup() + && !card.HasType(CardType.Synchro) && card.HasRace(CardRace.Wyrm)).ToList(); + if (blackoutTarget.Count() == 0) + { + AI.SelectCard(CardId.TenyiSpirit_Adhara, CardId.TenyiSpirit_Vishuda); + onlyWyrmSpSummon = true; + activatedCardIdList.Add(Card.Id); + return true; + } + } + + // for level8/10 synchro + List tunerIdList = new List{_CardId.AshBlossom, _CardId.EffectVeiler, CardId.TenyiSpirit_Adhara}; + bool hasTuner = Bot.GetMonsters().Any(card => card.IsFaceup() && card.IsCode(tunerIdList)); + hasTuner |= !summoned && Bot.HasInHand(tunerIdList); + if (hasTuner && CheckRemainInDeck(CardId.TenyiSpirit_Vishuda) > 0) + { + AI.SelectCard(CardId.TenyiSpirit_Ashuna); + onlyWyrmSpSummon = true; + activatedCardIdList.Add(Card.Id); + return true; + } + if (Bot.HasInMonstersZone(CardId.TenyiSpirit_Ashuna, false, false, true) && CheckRemainInDeck(CardId.TenyiSpirit_Adhara) > 0) + { + AI.SelectCard(CardId.TenyiSpirit_Adhara); + onlyWyrmSpSummon = true; + activatedCardIdList.Add(Card.Id); + return true; + } + } + return false; + } + + public bool TenyiSpirit_VishudaActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.TenyiSpirit_Vishuda, 0)) + { + // special summon + if (TenyiSpSummonForTaiaCheck() || Level7TenyiSpSummonCheck()) + { + return true; + } + + } else if (ActivateDescription == Util.GetStringId(CardId.TenyiSpirit_Vishuda, 1) && Card.Location == CardLocation.Grave && CheckCalledbytheGrave(Card.Id) == 0) + { + // bounce + List dangerList = GetProblematicEnemyCardList(true, true); + if (dangerList.Count() > 0) + { + AI.SelectCard(dangerList); + return true; + } + } + return false; + } + + public bool Level7TenyiSpSummonCheck() + { + List advanceSummonCheckList = new List{CardId.SwordsoulOfMoYe, CardId.SwordsoulOfTaia, CardId.IncredibleEcclesiaTheVirtuous}; + List tunerList = new List{CardId.TenyiSpirit_Adhara, _CardId.EffectVeiler, _CardId.AshBlossom}; + if (!summoned && !Bot.HasInHand(advanceSummonCheckList) && Bot.HasInHand(tunerList)) + { + return true; + } + if (Bot.HasInExtra(CardId.PsychicEndPunisher) && Bot.HasInMonstersZone(CardId.SwordsoulToken) && !onlyWyrmSpSummon) + { + return true; + } + + return false; + } + + public bool SwordsoulStrategistLongyuanActivate() + { + // damage effect + if (Card.Location != CardLocation.Hand) + { + return true; + } + + // special summon token + if (CheckWhetherNegated() || (CheckAtAdvantage() && enemyActivateMaxxC && Util.IsTurn1OrMain2())) + { + return false; + } + List discardIdList = new List(); + + // discard Taia to SS + if (CheckAtAdvantage()) + { + if (Bot.HasInHand(CardId.SwordsoulSacredSummit) && Bot.HasInHand(CardId.SwordsoulOfTaia) + && !activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && !activatedCardIdList.Contains(CardId.SwordsoulSacredSummit)) + { + discardIdList.Add(CardId.SwordsoulOfTaia); + } + } + + // discard tenyi + if (discardIdList.Count() == 0) + { + List tenyiList = new List{CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Ashuna, CardId.TenyiSpirit_Adhara}; + foreach (int tenyiId in tenyiList) + { + if (Bot.HasInHand(tenyiId)) + { + discardIdList.Add(tenyiId); + } + } + } + + // discard dump card + if (discardIdList.Count() == 0) + { + List checkIdList = new List{ + CardId.SwordsoulOfTaia, CardId.SwordsoulOfMoYe, CardId.SwordsoulBlackout, CardId.SwordsoulStrategistLongyuan, CardId.SwordsoulEmergence + }; + foreach (int checkId in checkIdList) + { + if (Bot.Hand.Count(card => card != Card && card.IsCode(checkIdList)) > 1) + { + discardIdList.Add(checkId); + } + } + } + + // discard card + if (discardIdList.Count() == 0) + { + List checkIdList = new List{ + CardId.SwordsoulOfTaia, CardId.SwordsoulOfMoYe, CardId.SwordsoulBlackout, CardId.SwordsoulStrategistLongyuan, + CardId.SwordsoulSacredSummit, CardId.SwordsoulEmergence + }; + foreach (int checkId in checkIdList) + { + if (Bot.Hand.Count(card => card != Card && card.IsCode(checkIdList)) >= 1) + { + discardIdList.Add(checkId); + } + } + } + + if (discardIdList.Count() > 0) + { + AI.SelectCard(discardIdList); + AI.SelectPosition(CardPosition.FaceUpAttack); + AI.SelectPosition(CardPosition.FaceUpDefence); + activatedCardIdList.Add(Card.Id); + return true; + } + + return false; + } + + public bool SwordsoulOfTaiaActivate() + { + // send to GY effect + if (Card.Location != CardLocation.MonsterZone) + { + List sendToGYTarget = new List(); + + // send Mo Ye to SS + if (!Bot.HasInGraveyard(CardId.SwordsoulOfMoYe) && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0) + { + bool sendMoYe = false; + // baxia + if (Bot.HasInMonstersZone(CardId.BaxiaBrightnessOfTheYangZing, true, false, true + && !activatedCardIdList.Contains(CardId.BaxiaBrightnessOfTheYangZing))) + { + sendMoYe = true; + + } + if (Bot.HasInHand(CardId.SwordsoulSacredSummit) && !activatedCardIdList.Contains(CardId.SwordsoulSacredSummit)) { + if (Bot.Hand.Any(card => card.Id != CardId.SwordsoulSacredSummit && (card.HasSetcode(SetcodeSwordsoul) || card.HasRace(CardRace.Wyrm)))) + { + sendMoYe = true; + } + } + + if (sendMoYe) + { + sendToGYTarget.Add(CardId.SwordsoulOfMoYe); + } + } + + // send Tenyi + List checkTenyiList = new List {CardId.TenyiSpirit_Adhara, CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Ashuna}; + foreach (int id in checkTenyiList) + { + if (CheckRemainInDeck(id) > 0) + { + sendToGYTarget.Add(id); + } + } + + if (sendToGYTarget.Count() > 0) + { + AI.SelectCard(sendToGYTarget); + return true; + } + return false; + } + + // special summon token + // ignore negate check if blackout in GY + if (Bot.HasInGraveyard(CardId.SwordsoulBlackout) && !activatedCardIdList.Contains(CardId.SwordsoulBlackout)) + { + AI.SelectCard(CardId.SwordsoulBlackout); + AI.SelectPosition(CardPosition.FaceUpDefence); + activatedCardIdList.Add(Card.Id); + return true; + } + + if (CheckWhetherNegated()) + { + return false; + } + List banishIdList = new List(); + + List checkIdList = new List{ + CardId.SwordsoulStrategistLongyuan, CardId.SwordsoulEmergence, CardId.SwordsoulOfTaia, CardId.SwordsoulOfMoYe, CardId.MonkOfTheTenyi, + CardId.ShamanOfTheTenyi, CardId.SwordsoulSacredSummit, CardId.SwordsoulGrandmaster_Chixiao, CardId.TenyiSpirit_Ashuna, CardId.TenyiSpirit_Vishuda, + CardId.SwordsoulSinisterSovereign_QixingLongyuan, CardId.SwordsoulSupremeSovereign_Chengying, CardId.DracoBerserkerOfTheTenyi, + CardId.TenyiSpirit_Adhara + }; + + // dump check + foreach (int checkId in checkIdList) + { + if (Bot.Graveyard.Count(card => card.IsCode(checkId)) > 1) + { + banishIdList.Add(checkId); + } + } + + // priority check + if (banishIdList.Count() == 0) + { + foreach (int checkId in checkIdList) + { + if (Bot.HasInGraveyard(checkId)) + { + banishIdList.Add(checkId); + } + } + } + + if (banishIdList.Count() > 0) + { + AI.SelectCard(banishIdList); + AI.SelectPosition(CardPosition.FaceUpDefence); + activatedCardIdList.Add(Card.Id); + return true; + } + + return false; + } + + public bool SwordsoulOfTaiaSummon() + { + if (Bot.HasInGraveyard(CardId.SwordsoulBlackout)) + { + if (!activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && !activatedCardIdList.Contains(CardId.SwordsoulBlackout)) + { + summoned = true; + return true; + } + } + if (SummonLevel4ForSynchro()) + { + summoned = true; + return true; + } + if (CheckWhetherNegated()) + { + return false; + } + if (SwordsoulOfTaiaEffectCheck() && !activatedCardIdList.Contains(CardId.SwordsoulOfTaia)) + { + summoned = true; + return true; + } + + return false; + } + + public bool SwordsoulOfTaiaEffectCheck(ClientCard exceptTarget = null) + { + if (exceptTarget == null) + { + exceptTarget = Card; + } + return Bot.Graveyard.Count(card => card != exceptTarget && (card.HasSetcode(SetcodeSwordsoul) || card.HasRace(CardRace.Wyrm))) > 0; + } + + public bool SwordsoulOfMoYeActivate() + { + // draw effect + if (Card.Location != CardLocation.MonsterZone) + { + return true; + } + + // special summon token + if (CheckWhetherNegated()) + { + return false; + } + List revealList = Bot.Hand.Where(card => card.HasSetcode(SetcodeSwordsoul) || card.HasRace(CardRace.Wyrm)).ToList(); + if (revealList.Count() > 0) + { + revealList = ShuffleCardList(revealList); + AI.SelectCard(revealList); + AI.SelectPosition(CardPosition.FaceUpDefence); + activatedCardIdList.Add(Card.Id); + return true; + } + return false; + } + + public bool SwordsoulOfMoYeSummon() + { + if (SummonLevel4ForSynchro()) + { + summoned = true; + return true; + } + if (CheckWhetherNegated()) + { + return false; + } + if (SwordsoulOfMoYeEffectCheck() && !activatedCardIdList.Contains(CardId.SwordsoulOfMoYe)) + { + summoned = true; + return true; + } + + return false; + } + + public bool SwordsoulOfMoYeEffectCheck(List exceptList = null) + { + if (exceptList == null) + { + exceptList = new List{Card}; + } + return Bot.Hand.Count(card => !exceptList.Contains(card) && (card.HasSetcode(SetcodeSwordsoul) || card.HasRace(CardRace.Wyrm))) > 0; + } + + public bool SummonLevel4ForSynchro() + { + bool hasNonTuner = Bot.GetMonsters().Any(card => card.IsFaceup() && !card.HasType(CardType.Xyz | CardType.Link) && !card.IsTuner()); + if (hasNonTuner) + { + return false; + } + List tunerList = Bot.GetMonsters().Where(card => + card.IsFaceup() && !card.HasType(CardType.Xyz | CardType.Link) && card.IsTuner()).ToList(); + if (tunerList.Count() > 0) + { + foreach (ClientCard tuner in tunerList) + { + int checkLevel = tuner.Level + 4; + if (Bot.ExtraDeck.Any(card => card.HasType(CardType.Synchro) && card.Level == checkLevel)) + { + return true; + } + } + } + + return false; + } + + public bool IncredibleEcclesiaTheVirtuousActivate() + { + if (Card.Location == CardLocation.Grave) + { + return true; + } + if (Duel.Player == 0 && !CheckWhetherNegated()) + { + bool canActivateMoye = !activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0 + && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0 && SwordsoulOfMoYeEffectCheck(); + bool canActivateTaia = !activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && CheckRemainInDeck(CardId.SwordsoulOfTaia) > 0 + && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0 && SwordsoulOfTaiaEffectCheck(); + if (canActivateMoye && !summoned && !Bot.HasInHand(CardId.SwordsoulOfMoYe)) + { + AI.SelectCard(CardId.SwordsoulOfMoYe); + activatedCardIdList.Add(Card.Id); + return true; + } + if (canActivateTaia && !summoned && !Bot.HasInHand(CardId.SwordsoulOfTaia)) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + activatedCardIdList.Add(Card.Id); + return true; + } + if (canActivateMoye) + { + AI.SelectCard(CardId.SwordsoulOfMoYe); + activatedCardIdList.Add(Card.Id); + return true; + } + if (canActivateTaia) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + activatedCardIdList.Add(Card.Id); + return true; + } + } + + return false; + } + + public bool IncredibleEcclesiaTheVirtuousSummon() + { + if (CheckWhetherNegated()) + { + return false; + } + if (SwordsoulOfMoYeSummon() && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0) + { + summoned = true; + return true; + } + if (SwordsoulOfTaiaSummon() && CheckRemainInDeck(CardId.SwordsoulOfTaia) > 0) + { + summoned = true; + return true; + } + + return false; + } + + public bool IncredibleEcclesiaTheVirtuousSpSummon() + { + if (CheckWhetherNegated()) + { + return false; + } + if (CheckAtAdvantage() && enemyActivateMaxxC && Util.IsTurn1OrMain2()) + { + return false; + } + + return true; + } + + public bool AshBlossomActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (CheckAtAdvantage() && Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + return false; + } + if (DefaultAshBlossomAndJoyousSpring()) + { + CheckDeactiveFlag(); + return true; + } + return false; + } + + public bool MaxxCActivate() + { + if (CheckWhetherNegated() || Duel.LastChainPlayer == 0) return false; + return DefaultMaxxC(); + } + + public bool EffectVeilerActivate() + { + if (CheckWhetherNegated()) return false; + + List shouldNegateList = GetMonsterListForTargetNegate(true); + if (shouldNegateList.Count() > 0) + { + ClientCard target = shouldNegateList[0]; + currentNegateMonsterList.Add(target); + AI.SelectCard(target); + return true; + } + + return false; + } + + public bool TunerForSynchroSummon() + { + if (!Card.IsCode(_CardId.AshBlossom) && !Card.IsCode(CardId.TenyiSpirit_Adhara) && !Card.IsCode(_CardId.EffectVeiler)) + { + return false; + } + // taia check + if (Bot.HasInExtra(CardId.MonkOfTheTenyi) && Bot.HasInHand(CardId.SwordsoulOfTaia) + && !activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0) + { + return false; + } + + // already has tuner, skip (maybe affected by Dimensional Barrier) + if (Bot.GetMonsters().Any(card => card.IsFaceup() && card.IsTuner())) + { + return false; + } + + // level10 check + List checkOnField = new List{CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Ashuna}; + bool hasLevel7NonTuner = Bot.GetMonsters().Any(card => card.IsFaceup() && checkOnField.Contains(card.Id) && !card.IsTuner()); + if (hasLevel7NonTuner) + { + int totalLevel = Card.Level + 7; + if (Bot.ExtraDeck.Any(card => card.HasType(CardType.Synchro) && card.Level == totalLevel && (!onlyWyrmSpSummon || card.HasRace(CardRace.Wyrm)))) + { + summoned = true; + return true; + } + } + + List checkNonTuner = Bot.GetMonsters().Where(card => card.IsFaceup() && !card.IsTuner()).ToList(); + checkNonTuner.Sort(CardContainer.CompareCardAttack); + // level7 check + if (Bot.HasInExtra(CardId.YaziEvilOfTheYangZing) && GetProblematicEnemyCardList(true, true).Count() > 0) + { + foreach (ClientCard checkCard in checkNonTuner) + { + if (Card.Level + checkCard.Level == 7) + { + summoned = true; + return true; + } + } + } + // level 11 check + if (Bot.HasInExtra(CardId.PsychicEndPunisher)) + { + foreach (ClientCard checkCard in checkNonTuner) + { + if ((checkCard.IsDisabled() || !checkCard.HasType(CardType.Synchro)) && (Card.Level + checkCard.Level == 11)) + { + summoned = true; + return true; + } + } + } + + return false; + } + + public bool WyrmForBlackoutSummon() + { + if (Card.Level > 4 || !Card.HasRace(CardRace.Wyrm)) + { + return false; + } + if (Bot.HasInHandOrInSpellZone(CardId.SwordsoulBlackout) && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasRace(CardRace.Wyrm))) + { + summoned = true; + return true; + } + return false; + } + + public bool TenyiSpirit_AdharaActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.TenyiSpirit_Adhara, 0)) + { + // special summon + if (TenyiSpSummonForTaiaCheck()) + { + return true; + } + + } + else if (ActivateDescription == Util.GetStringId(CardId.TenyiSpirit_Adhara, 1) && Card.Location == CardLocation.Grave && CheckCalledbytheGrave(Card.Id) == 0) + { + // recycle + if (!activatedCardIdList.Contains(CardId.SwordsoulStrategistLongyuan) && SwordsoulOfMoYeEffectCheck() + && Bot.HasInBanished(CardId.SwordsoulStrategistLongyuan)) + { + AI.SelectCard(CardId.SwordsoulStrategistLongyuan); + return true; + } + if (!summoned) + { + if (!activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) && SwordsoulOfMoYeEffectCheck() + && Bot.HasInBanished(CardId.SwordsoulOfMoYe)) + { + AI.SelectCard(CardId.SwordsoulOfMoYe); + return true; + } + if (!activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && SwordsoulOfTaiaEffectCheck() + && Bot.HasInBanished(CardId.SwordsoulOfTaia)) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + return true; + } + } + List recycleList = new List{CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Ashuna}; + foreach (int recycle in recycleList) + { + if (Bot.HasInBanished(recycle)) + { + AI.SelectCard(recycle); + return true; + } + } + } + + return false; + } + + public bool TenyiSpSummonForTaiaCheck() + { + if (!activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0) + { + bool hasTaia = (!summoned && Bot.HasInHand(CardId.SwordsoulOfTaia)) || Bot.HasInMonstersZone(CardId.SwordsoulOfTaia); + bool noTargetInGrave = !Bot.Graveyard.Any(card => card.HasRace(CardRace.Wyrm) || card.HasSetcode(SetcodeSwordsoul)); + bool hasInExtra = Bot.HasInExtra(CardId.MonkOfTheTenyi); + bool notLongyuan = activatedCardIdList.Contains(CardId.SwordsoulStrategistLongyuan) || !Bot.HasInHand(CardId.SwordsoulStrategistLongyuan); + + if (hasTaia && noTargetInGrave && hasInExtra && notLongyuan) + { + return true; + } + } + return false; + } + + public bool TenyiForShamanSpSummon() + { + List checkEffectDesc = new List{ + Util.GetStringId(CardId.TenyiSpirit_Adhara, 0), Util.GetStringId(CardId.TenyiSpirit_Vishuda, 0), + Util.GetStringId(CardId.TenyiSpirit_Ashuna, 0) + }; + if (!checkEffectDesc.Contains(ActivateDescription) || summoned || !Bot.HasInExtra(CardId.ShamanOfTheTenyi) + || (CheckAtAdvantage() && enemyActivateMaxxC)) + { + return false; + } + ClientCard toSummonMoye = Bot.Hand.FirstOrDefault(card => card.IsCode(CardId.SwordsoulOfMoYe)); + if (toSummonMoye == null) + { + return false; + } + List notRevealCheckList = new List{Card, toSummonMoye}; + if (!SwordsoulOfMoYeEffectCheck(notRevealCheckList) || activatedCardIdList.Contains(CardId.SwordsoulOfMoYe)) + { + return false; + } + if (activatedCardIdList.Contains(CardId.SwordsoulOfTaia) || !Bot.HasInHandOrInGraveyard(CardId.SwordsoulOfTaia)) + { + return false; + } + + return true; + } + + public bool TenyiForBlackoutSpSummon() + { + List checkEffectDesc = new List{ + Util.GetStringId(CardId.TenyiSpirit_Adhara, 0), Util.GetStringId(CardId.TenyiSpirit_Vishuda, 0), + Util.GetStringId(CardId.TenyiSpirit_Ashuna, 0) + }; + if (!checkEffectDesc.Contains(ActivateDescription)) + { + return false; + } + if (CheckAtAdvantage() && enemyActivateMaxxC) + { + return false; + } + if (Bot.HasInHandOrInSpellZone(CardId.SwordsoulBlackout) && !Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasRace(CardRace.Wyrm))) + { + return true; + } + return false; + } + + public bool PotOfDesiresActivate() + { + if (CheckWhetherNegated()) + { + return false; + } + if (CheckAtAdvantage()) + { + bool result = Bot.Deck.Count() >= 15; + if (result) + { + SelectSTPlace(null, true); + } + return result; + } + SelectSTPlace(null, true); + return true; + } + + public bool SwordsoulEmergenceActivate() + { + if (Card.Location == CardLocation.Removed) + { + return SwordsoulSpellBanishedEffect(); + } + + // Mo Ye + if (!Bot.HasInHand(CardId.SwordsoulOfMoYe) && !activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) + && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0 && SwordsoulOfMoYeEffectCheck()) + { + AI.SelectCard(CardId.SwordsoulOfMoYe); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + + // Taia + if (!Bot.HasInHand(CardId.SwordsoulOfTaia) && !activatedCardIdList.Contains(CardId.SwordsoulOfTaia) + && CheckRemainInDeck(CardId.SwordsoulOfTaia) > 0 && SwordsoulOfTaiaEffectCheck()) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + + // Longyuan + if (!Bot.HasInHand(CardId.SwordsoulStrategistLongyuan) && !activatedCardIdList.Contains(CardId.SwordsoulStrategistLongyuan) + && CheckRemainInDeck(CardId.SwordsoulStrategistLongyuan) > 0 && SwordsoulOfMoYeEffectCheck()) + { + AI.SelectCard(CardId.SwordsoulStrategistLongyuan); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + + // dump check + if (!Bot.HasInHand(CardId.SwordsoulOfMoYe) && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0 && SwordsoulOfMoYeEffectCheck()) + { + AI.SelectCard(CardId.SwordsoulOfMoYe); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + List checkIdList = new List{CardId.SwordsoulOfTaia, CardId.SwordsoulOfMoYe, CardId.SwordsoulStrategistLongyuan}; + foreach (int checkId in checkIdList) + { + if (CheckRemainInDeck(checkId) > 0) + { + AI.SelectCard(checkId); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + } + + return false; + } + + public bool SwordsoulSacredSummitActivate() + { + if (Card.Location == CardLocation.Removed) + { + return SwordsoulSpellBanishedEffect(); + } + if (CheckAtAdvantage()) + { + if (enemyActivateMaxxC && Util.IsTurn1OrMain2()) + { + return false; + } + if (!activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) && Bot.HasInGraveyard(CardId.SwordsoulOfMoYe) + && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0 && SwordsoulOfMoYeEffectCheck()) + { + AI.SelectCard(CardId.SwordsoulOfMoYe); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + if (!activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0) + { + ClientCard taia = Bot.Graveyard.FirstOrDefault(card => card.IsCode(CardId.SwordsoulOfTaia)); + if (taia != null && SwordsoulOfTaiaEffectCheck(taia)) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + } + } + bool controlSynchro = Bot.GetMonsters().Any(card => card.IsFaceup() && card.HasType(CardType.Synchro)); + + List rebornTargetList = Bot.Graveyard.Where(card => + card.IsMonster() && (card.HasSetcode(SetcodeSwordsoul) || (controlSynchro && card.HasRace(CardRace.Wyrm)))).ToList(); + rebornTargetList.Sort(CardContainer.CompareCardAttack); + rebornTargetList.Reverse(); + + if (rebornTargetList.Count() > 0) + { + ClientCard rebornTarget = rebornTargetList[0]; + if (rebornTarget.IsCode(CardId.SwordsoulOfMoYe) && (activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) || !SwordsoulOfMoYeEffectCheck())) + { + return false; + } + if (rebornTarget.IsCode(CardId.SwordsoulOfTaia) && activatedCardIdList.Contains(CardId.SwordsoulOfTaia)) + { + return false; + } + AI.SelectCard(rebornTargetList); + activatedCardIdList.Add(Card.Id); + SelectSTPlace(null, true); + return true; + } + + return false; + } + + public bool SwordsoulSpellBanishedEffect() + { + // TODO + return false; + } + + public bool CalledbytheGraveActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (CheckAtAdvantage() && Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + return false; + } + if (Duel.LastChainPlayer == 1) + { + // negate + if (Util.GetLastChainCard().IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (CheckCalledbytheGrave(code) > 0) return false; + if (Util.GetLastChainCard().IsCode(_CardId.MaxxC) && CheckAtAdvantage()) + { + return false; + } + ClientCard graveTarget = Enemy.Graveyard.GetFirstMatchingCard(card => card.IsMonster() && card.GetOriginCode() == code); + if (graveTarget != null) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(graveTarget); + currentNegatingIdList.Add(code); + CheckDeactiveFlag(); + return true; + } + } + + // banish target + foreach (ClientCard cards in Enemy.Graveyard) + { + if (Duel.ChainTargets.Contains(cards) && cards.IsMonster()) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + int code = cards.Id; + AI.SelectCard(cards); + currentNegatingIdList.Add(code); + return true; + } + } + + // become targets + if (Duel.ChainTargets.Contains(Card)) + { + List enemyMonsters = Enemy.Graveyard.GetMatchingCards(card => card.IsMonster()).ToList(); + if (enemyMonsters.Count() > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + int code = enemyMonsters[0].Id; + AI.SelectCard(code); + currentNegatingIdList.Add(code); + return true; + } + } + } + + // avoid danger monster in grave + if (Duel.LastChainPlayer == 1) return false; + List targets = CheckDangerousCardinEnemyGrave(true); + if (targets.Count() > 0) { + int code = targets[0].Id; + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(code); + currentNegatingIdList.Add(code); + return true; + } + + return false; + } + + public bool CrossoutDesignatorActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + // negate + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard() != null) + { + int code = Util.GetLastChainCard().Id; + int alias = Util.GetLastChainCard().Alias; + if (alias != 0 && alias - code < 10) code = alias; + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + if (CheckRemainInDeck(code) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectAnnounceID(code); + currentNegatingIdList.Add(code); + CheckDeactiveFlag(); + return true; + } + } + return false; + } + + public bool InfiniteImpermanenceActivate() + { + if (CheckWhetherNegated()) return false; + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ( (this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || Util.IsChainTarget(Card) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + CheckDeactiveFlag(); + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true); + if (target != null) + { + AI.SelectCard(target); + } else { + AI.SelectCard(Enemy.GetMonsters()); + } + infiniteImpermanenceList.Add(this_seq); + return true; + } + } + + // negate monster + List shouldNegateList = GetMonsterListForTargetNegate(false, true); + if (shouldNegateList.Count() > 0) + { + ClientCard negateTarget = shouldNegateList[0]; + currentNegateMonsterList.Add(negateTarget); + + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++ i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(negateTarget); + return true; + } + + return false; + } + + public bool SwordsoulBlackoutActivate() + { + // sp summon token + if (Card.Location == CardLocation.Removed) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + activatedCardIdList.Add(Card.Id); + return true; + } + + // self destroy targer + List selfDestroyList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasRace(CardRace.Wyrm)).ToList(); + selfDestroyList.Sort(CardContainer.CompareCardAttack); + ClientCard selfDestroyTarget = selfDestroyList[0]; + bool selfTargetIsImportant = selfDestroyTarget.HasType(CardType.Synchro); + + // choose Chengying + List chengyingList = Bot.GetMonsters().Where(card => + card.IsCode(CardId.SwordsoulSupremeSovereign_Chengying) && card.IsFaceup() && !card.IsDisabled()).ToList(); + if (chengyingList.Count() > 0 && Bot.Graveyard.Count() > 0) + { + selfDestroyTarget = chengyingList[0]; + selfTargetIsImportant = false; + } + foreach (ClientCard selfCard in selfDestroyList) + { + if (Duel.LastChainTargets.Contains(selfCard)) + { + selfDestroyTarget = selfCard; + selfTargetIsImportant = false; + } + } + + // destroy problem card + List problemCardList = GetProblematicEnemyCardList(true); + if (problemCardList.Count() >= 2 && Duel.Player == 1) + { + AI.SelectCard(selfDestroyTarget); + AI.SelectNextCard(problemCardList); + return true; + } + + List faceUpEnemyMonsterList = Enemy.GetMonsters().Where(card => card.IsFaceup()).ToList(); + faceUpEnemyMonsterList.Sort(CardContainer.CompareCardAttack); + faceUpEnemyMonsterList.Reverse(); + if (!selfTargetIsImportant && Duel.Player == 1) + { + // destroy multi monster + if (faceUpEnemyMonsterList.Count() >= 2) + { + AI.SelectCard(selfDestroyTarget); + AI.SelectNextCard(GetNormalEnemyTargetList()); + return true; + } + + // destroy card in EP + if (Duel.Phase == DuelPhase.End) + { + AI.SelectCard(selfDestroyTarget); + AI.SelectNextCard(GetNormalEnemyTargetList()); + return true; + } + } + + // destroy attack monster + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2 && faceUpEnemyMonsterList.Count() > 0) + { + int botBestAttack = Util.GetBestAttack(Bot); + int enemyBestAttack = faceUpEnemyMonsterList[0].GetDefensePower(); + if (enemyBestAttack >= botBestAttack) + { + AI.SelectCard(selfDestroyTarget); + AI.SelectNextCard(GetNormalEnemyTargetList()); + return true; + } + } + + return false; + } + + + public bool GeomathmechFinalSigmaSpSummon() + { + if (Bot.GetMonstersExtraZoneCount() > 0) return false; + bool hasFloowandereeze = Enemy.GetMonsters().Any(card => card.HasSetcode(SetcodeFloowandereeze)); + hasFloowandereeze |= Enemy.GetSpells().Any(card => card.HasSetcode(SetcodeFloowandereeze)); + hasFloowandereeze |= Enemy.Graveyard.Any(card => card.HasSetcode(SetcodeFloowandereeze)); + hasFloowandereeze |= Enemy.Banished.Any(card => card.HasSetcode(SetcodeFloowandereeze)); + if (hasFloowandereeze) + { + AI.SelectMaterials(GetSynchroMaterial(12)); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + + return false; + } + + public bool PsychicEndPunisherSpSummon() + { + List materialList = GetSynchroMaterial(11); + if (materialList.Count() > 1) + { + AI.SelectMaterials(materialList); + AI.SelectPosition(CardPosition.FaceUpAttack); + return true; + } + + return false; + } + + /// + /// remove level10 summon filter + /// + public bool Level10SpSummonCheckInit() + { + canSpSummonLevel10IdList.Clear(); + return false; + } + + /// + /// check which level10 monster can be summoned + /// + public bool Level10SpSummonCheckCount() + { + List checkIdList = new List{ + CardId.SwordsoulSupremeSovereign_Chengying, CardId.SwordsoulSinisterSovereign_QixingLongyuan, CardId.BaronneDeFleur + }; + foreach (int checkId in checkIdList) + { + if (Card.IsCode(checkId)) + { + canSpSummonLevel10IdList.Add(checkId); + } + } + return false; + } + + /// + /// decide which level10 monster to summon + /// + public bool Level10SpSummonCheckDecide() + { + if (canSpSummonLevel10IdList.Count <= 1) + { + return false; + } + List decideIdList = new List(); + + // BaronneDeFleur + if (canSpSummonLevel10IdList.Contains(CardId.BaronneDeFleur)) + { + // protect maxxc + if (Bot.HasInHand(_CardId.MaxxC)) + { + canSpSummonLevel10IdList.Clear(); + canSpSummonLevel10IdList.Add(CardId.BaronneDeFleur); + return false; + } + + // continue to use taia for synchro + ClientCard taia = Bot.Graveyard.FirstOrDefault(card => card.IsCode(CardId.SwordsoulOfTaia)); + if (taia != null && SwordsoulOfTaiaEffectCheck(taia) && Bot.HasInHand(CardId.SwordsoulSacredSummit)) + { + canSpSummonLevel10IdList.Clear(); + canSpSummonLevel10IdList.Add(CardId.BaronneDeFleur); + return false; + } + + decideIdList.Add(CardId.BaronneDeFleur); + } + + // QixingLongyuan + if (canSpSummonLevel10IdList.Contains(CardId.SwordsoulSinisterSovereign_QixingLongyuan)) + { + if (CheckAtAdvantage()) + { + decideIdList.Add(CardId.SwordsoulSinisterSovereign_QixingLongyuan); + } + } + + // Chengying + if (canSpSummonLevel10IdList.Contains(CardId.SwordsoulSupremeSovereign_Chengying)) + { + int banishCount = Bot.Banished.Count() + Enemy.Banished.Count(); + // use blackout or chixiao to trigger + bool decideFlag = Bot.HasInHandOrInSpellZone(CardId.SwordsoulBlackout) + || Bot.HasInMonstersZone(CardId.SwordsoulGrandmaster_Chixiao, true, false, true); + if (CheckAtAdvantage()) + { + // overkill + if (3000 + banishCount * 100 >= Enemy.LifePoints) + { + decideFlag = true; + } + } else { + ClientCard enemyMonster = GetBestEnemyMonster(true); + if (enemyMonster != null && decideIdList.Count() == 0) + { + // for high-power monster + if (3000 + banishCount * 200 >= enemyMonster.GetDefensePower()) + { + decideFlag = true; + } + } + } + + if (decideFlag) + { + decideIdList.Add(CardId.SwordsoulSupremeSovereign_Chengying); + } + } + + if (decideIdList.Count() > 0) + { + // if multi selections, select randomly + canSpSummonLevel10IdList.Clear(); + int index = Program.Rand.Next(decideIdList.Count()); + int lastDecide = decideIdList[index]; + canSpSummonLevel10IdList.Add(lastDecide); + } + return false; + } + + /// + /// perform level10 monster's synchro summon + /// + public bool Level10SpSummonCheckFinal() + { + if (canSpSummonLevel10IdList.Count() == 1) + { + int finalDecideId = canSpSummonLevel10IdList[0]; + if (Card.IsCode(finalDecideId)) + { + List materialList = GetSynchroMaterial(10, Card.IsCode(CardId.SwordsoulSinisterSovereign_QixingLongyuan)); + if (materialList.Count() > 1) + { + AI.SelectMaterials(materialList); + return true; + } + return true; + } + } + + return false; + } + + public bool AdamancipatorRisen_DragiteSpSummon() + { + if (!Bot.HasInMonstersZone(CardId.SwordsoulGrandmaster_Chixiao, true)) + { + return false; + } + bool containWaterMonsterInGY = Bot.Graveyard.Any(card => card.IsMonster() && card.HasAttribute(CardAttribute.Water)); + bool canContainWaterInGY = containWaterMonsterInGY; + canContainWaterInGY |= Bot.GetMonsters().Any(card => card.HasAttribute(CardAttribute.Water) && card.IsFaceup()); + if (!canContainWaterInGY) + { + return false; + } + + SelectLevel8SynchroMaterial(false, !containWaterMonsterInGY); + return true; + } + + public bool DracoBerserkerOfTheTenyiSpSummon() + { + if (CheckAtAdvantage() && enemyActivateMaxxC && Util.IsTurn1OrMain2()) + { + return false; + } + + SelectLevel8SynchroMaterial(true); + return true; + } + + public bool SwordsoulGrandmaster_ChixiaoSpSummon() + { + if (CheckAtAdvantage() && enemyActivateLockBird) + { + return false; + } + if (!activatedCardIdList.Contains(CardId.SwordsoulGrandmaster_Chixiao)) + { + SelectLevel8SynchroMaterial(true); + return true; + } + + return false; + } + + public bool BaxiaBrightnessOfTheYangZingSpSummon() + { + if (CheckAtAdvantage()) + { + return false; + } + + List problemList = GetProblematicEnemyCardList(true); + if (problemList.Count() > 1 && !activatedCardIdList.Contains(CardId.BaxiaBrightnessOfTheYangZing + 1)) + { + SelectLevel8SynchroMaterial(true); + return true; + } + if (problemList.Count() == 1 && Bot.GetSpellCount() > 0 && !activatedCardIdList.Contains(CardId.BaxiaBrightnessOfTheYangZing + 2)) + { + bool checkFlag = false; + if (!activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) && SwordsoulOfMoYeEffectCheck() && Bot.HasInGraveyard(CardId.SwordsoulOfMoYe)) + { + checkFlag = true; + } + if (!activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && Bot.HasInGraveyard(CardId.SwordsoulOfTaia)) + { + checkFlag = true; + } + if (checkFlag) + { + SelectLevel8SynchroMaterial(true); + return true; + } + } + + return false; + } + + public void SelectLevel8SynchroMaterial(bool needWyrmNonTuner = false, bool needWaterNonTuner = false) + { + List tunerList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.IsTuner() && card.Level < 8).ToList(); + List nonTunerList = Bot.GetMonsters().Where(card => card.IsFaceup() && !card.IsTuner() && card.Level < 8 + && (!needWyrmNonTuner || card.HasRace(CardRace.Wyrm) && (!needWaterNonTuner || card.HasAttribute(CardAttribute.Water)))).ToList(); + tunerList.Sort(CardContainer.CompareCardAttack); + nonTunerList.Sort(CardContainer.CompareCardAttack); + + List materialList = new List(); + foreach (ClientCard tuner in tunerList) + { + materialList.Clear(); + materialList.Add(tuner); + if (tuner.Level == 4) + { + // use moye first + if (activatedCardIdList.Contains(CardId.SwordsoulOfMoYe)) + { + ClientCard moye = nonTunerList.GetFirstMatchingCard(card => card.IsCode(CardId.SwordsoulOfMoYe)); + if (moye != null) + { + materialList.Add(moye); + AI.SelectMaterials(materialList); + return; + } + } + + // use taia + if (activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && !needWaterNonTuner) + { + ClientCard taia = nonTunerList.GetFirstMatchingCard(card => card.IsCode(CardId.SwordsoulOfTaia)); + if (taia != null) + { + materialList.Add(taia); + AI.SelectMaterials(materialList); + return; + } + } + } + + foreach (ClientCard nonTuner in nonTunerList) + { + if (tuner.Level + nonTuner.Level == 8) + { + materialList.Add(nonTuner); + AI.SelectMaterials(materialList); + return; + } + } + } + } + + public bool YaziEvilOfTheYangZingSpSummon() + { + if (Enemy.GetMonsterCount() + Enemy.GetSpellCount() == 0) + { + return false; + } + bool shouldSummon = GetProblematicEnemyCardList(true, true).Count() > 0; + shouldSummon |= !activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0 + && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0 && SwordsoulOfMoYeEffectCheck(); + shouldSummon |= !activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0 + && CheckRemainInDeck(CardId.SwordsoulOfTaia) > 0; + + if (shouldSummon) + { + List materialList = GetSynchroMaterial(7); + if (materialList.Count() > 1) + { + AI.SelectMaterials(materialList); + return true; + } + } + + return false; + } + + public List GetSynchroMaterial(int level, bool needWyrmNonTuner = false) + { + List tunerList = Bot.GetMonsters().Where(card => + card.IsFaceup() && card.IsTuner() && !card.HasType(CardType.Xyz | CardType.Link)).ToList(); + List nonTunerList = Bot.GetMonsters().Where(card => + card.IsFaceup() && !card.IsTuner() && !card.HasType(CardType.Xyz | CardType.Link) && (!needWyrmNonTuner || card.HasRace(CardRace.Wyrm))).ToList(); + tunerList.Sort(CardContainer.CompareCardAttack); + nonTunerList.Sort(CardContainer.CompareCardAttack); + List selectList = new List(); + foreach (ClientCard tuner in tunerList) + { + selectList.Clear(); + selectList.Add(tuner); + foreach (ClientCard nonTuner in nonTunerList) + { + if (tuner.Level + nonTuner.Level == level && (nonTuner.IsDisabled() || !nonTuner.HasType(CardType.Synchro))) + { + selectList.Add(nonTuner); + return selectList; + } + } + } + selectList.Clear(); + return selectList; + } + + public bool ShamanOfTheTenyiSpSummon() + { + if (CheckAtAdvantage() && enemyActivateMaxxC && Util.IsTurn1OrMain2()) + { + Logger.DebugWriteLine("[Shaman] advantage & maxxc, skip"); + return false; + } + // check extra summon + List extraZoneMonsters = Bot.GetMonstersInExtraZone(); + if (extraZoneMonsters.Count() > 0 && extraZoneMonsters.Any(card => card.IsFacedown() || !card.HasType(CardType.Link) || !card.HasRace(CardRace.Wyrm))) + { + Logger.DebugWriteLine("[Shaman] extra zone occupied, skip"); + return false; + } + // check spsummon target + bool hasSpSummonTaret = !activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0 + && Bot.HasInHandOrInGraveyard(CardId.SwordsoulOfTaia); + hasSpSummonTaret |= !activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0 + && Bot.HasInGraveyard(CardId.SwordsoulOfMoYe) && SwordsoulOfMoYeEffectCheck(); + hasSpSummonTaret |= Bot.GetGraveyardMonsters().Any(card => card.HasType(CardType.Synchro) && card.IsCanRevive() && card.HasRace(CardRace.Wyrm)); + if (!hasSpSummonTaret) + { + Logger.DebugWriteLine("[Shaman] no target, skip"); + return false; + } + + // select material + List materialList = new List(extraZoneMonsters); + List mainMonsterZoneMonsters = Bot.GetMonstersInMainZone().Where(card => + card.IsFaceup() && !card.HasType(CardType.Synchro) && card.HasRace(CardRace.Wyrm)).ToList(); + mainMonsterZoneMonsters.Sort(CardContainer.CompareCardAttack); + materialList.AddRange(mainMonsterZoneMonsters); + if (materialList.Count() >= 2) + { + AI.SelectMaterials(materialList.GetRange(0, 2)); + return true; + } + + return false; + } + + public bool MonkOfTheTenyiSpSummon() + { + List materialList = Bot.GetMonsters().Where(card => + card.IsFaceup() && !card.HasType(CardType.Synchro | CardType.Link) && card.HasSetcode(SetcodeTenyi)).ToList(); + if (materialList.Count() > 0) + { + materialList.Sort(CardContainer.CompareCardAttack); + AI.SelectMaterials(materialList); + return true; + } + return false; + } + + + public bool PsychicEndPunisherActivate() + { + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + return true; + } + if (Bot.LifePoints <= 1500 || CheckWhetherNegated()) + { + return false; + } + List selfBanishTarget = Bot.GetMonsters().Where(card => card != Card && (card.IsFacedown() || card.GetDefensePower() <= 1000)).ToList(); + if (selfBanishTarget.Count() == 0) + { + return false; + } + selfBanishTarget.Sort(CardContainer.CompareCardAttack); + AI.SelectCard(selfBanishTarget); + AI.SelectNextCard(GetNormalEnemyTargetList(true)); + return true; + } + + public bool SwordsoulSupremeSovereign_ChengyingActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.SwordsoulSupremeSovereign_Chengying, 0) || ActivateDescription == -1) + { + activatedCardIdList.Add(Card.Id); + List banishTargetList = Duel.CurrentChain.Where(card => card.Controller == 1 && card.Location == CardLocation.Grave).ToList(); + banishTargetList.AddRange(CheckDangerousCardinEnemyGrave(false)); + if (banishTargetList.Count() > 0) + { + ClientCard graveTarget = banishTargetList[0]; + Logger.DebugWriteLine("Chengying banish grave: " + graveTarget?.Name); + } + List fieldTargetList = GetNormalEnemyTargetList(); + if (fieldTargetList.Count() > 0) + { + ClientCard fieldTarget = fieldTargetList[0]; + Logger.DebugWriteLine("Chengying banish field: " + fieldTarget?.Name); + } + banishTargetList.AddRange(fieldTargetList); + AI.SelectCard(banishTargetList); + + } else if (ActivateDescription == hintReplaceDestroy) + { + List removeCardIdList = new List{ + _CardId.CalledByTheGrave, CardId.CrossoutDesignator, _CardId.InfiniteImpermanence, _CardId.AshBlossom, + _CardId.MaxxC, _CardId.EffectVeiler, CardId.MonkOfTheTenyi, CardId.ShamanOfTheTenyi, CardId.SwordsoulGrandmaster_Chixiao, + CardId.SwordsoulOfTaia, CardId.SwordsoulStrategistLongyuan, CardId.SwordsoulOfMoYe + }; + AI.SelectCard(removeCardIdList); + } else + { + Logger.DebugWriteLine("Chengying desc: " + ActivateDescription.ToString()); + } + + return true; + } + + public bool BaronneDeFleurActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.BaronneDeFleur, 1)) + { + // negate + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (Duel.LastChainPlayer == 1) + { + ClientCard lastChainCard = Util.GetLastChainCard(); + if (CheckAtAdvantage() && lastChainCard.IsCode(_CardId.MaxxC)) + { + return false; + } + if (Duel.LastChainTargets.Contains(Card) && lastChainCard.IsCode(_CardId.EffectVeiler, _CardId.InfiniteImpermanence, _CardId.BreakthroughSkill)) + { + return false; + } + } + CheckDeactiveFlag(); + effectUsedBaronneDeFleurList.Add(Card); + return true; + } else if (Duel.Phase == DuelPhase.Standby) + { + // special summon after effect used + if (effectUsedBaronneDeFleurList.Contains(Card) && !CheckWhetherNegated()) + { + if (Duel.Player == 1) + { + if (!Bot.HasInMonstersZone(CardId.SwordsoulGrandmaster_Chixiao) && Bot.HasInGraveyard(CardId.SwordsoulGrandmaster_Chixiao)) + { + AI.SelectCard(CardId.SwordsoulGrandmaster_Chixiao); + return true; + } + } else if (GetProblematicEnemyCardList(true, true).Count() > 0) + { + return false; + } else if (CheckAtAdvantage()) { + if (Bot.ExtraDeck.Any(card => card.IsFacedown() && card.HasType(CardType.Synchro) && card.Level == 8)) + { + if (Bot.HasInGraveyard(CardId.SwordsoulOfMoYe) && SwordsoulOfMoYeEffectCheck() && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0) + { + AI.SelectCard(CardId.SwordsoulOfMoYe); + return true; + } + if (CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0) + { + ClientCard taia = Bot.Graveyard.FirstOrDefault(card => card.IsCode(CardId.SwordsoulOfTaia)); + if (taia != null && SwordsoulOfTaiaEffectCheck(taia)) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + return true; + } + } + } + } + } + } else { + // destroy + List targetList = GetNormalEnemyTargetList(); + if (targetList.Count() > 0) + { + AI.SelectCard(targetList); + return true; + } + } + + return false; + } + + public bool SwordsoulSinisterSovereign_QixingLongyuanActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.SwordsoulSinisterSovereign_QixingLongyuan, 0)) + { + // draw + return true; + } else if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.SwordsoulSinisterSovereign_QixingLongyuan, 1)) + { + // remove monster + return true; + } else if (ActivateDescription == Util.GetStringId(CardId.SwordsoulSinisterSovereign_QixingLongyuan, 2)) + { + // remove spell/trap + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && lastChainCard.Controller == 1) + { + bool activateFlag = DefaultOnBecomeTarget(); + activateFlag |= Enemy.LifePoints <= 1200; + activateFlag |= lastChainCard.HasType(CardType.Continuous | CardType.Equip | CardType.Field | CardType.Pendulum); + if (activateFlag) + { + return true; + } + } + } else + { + Logger.DebugWriteLine("qixinglongyuan desc: " + ActivateDescription); + } + + return false; + } + + public bool AdamancipatorRisen_DragiteActivate() + { + // bounce + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.AdamancipatorRisen_Dragite, 0)) + { + if (CheckWhetherNegated()) + { + return false; + } + if (CheckRemainInDeck(CardId.NibiruThePrimalBeing) > 0 && (Enemy.GetMonsterCount() + Enemy.GetSpellCount() > 0)) + { + AI.SelectCard(GetNormalEnemyTargetList(false)); + return true; + } + return false; + } + + // negate + if (CheckWhetherNegated()) + { + return false; + } + + return true; + } + + public bool DracoBerserkerOfTheTenyiActivate() + { + // do not banish Nibiru + ClientCard lastChainCard = Util.GetLastChainCard(); + if (lastChainCard != null && lastChainCard.IsCode(CardId.NibiruThePrimalBeing) && lastChainCard.Controller == 1) + { + return false; + } + return true; + } + + public bool SwordsoulGrandmaster_ChixiaoActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.SwordsoulGrandmaster_Chixiao, 1)) + { + // negate + if (CheckWhetherNegated()) return false; + + List negateTargetList = new List(); + + List shouldNegateList = GetMonsterListForTargetNegate(true); + if (shouldNegateList.Count() > 0) + { + ClientCard target = shouldNegateList[0]; + currentNegateMonsterList.Add(target); + negateTargetList.AddRange(shouldNegateList); + } + + // negate unbreakable monster + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + bool botCanAttack = Bot.GetMonsters().Any(card => card.IsAttack()); + if (Duel.Player == 0 && botCanAttack) + { + negateTargetList.AddRange(Enemy.GetMonsters().Where(card => card.IsFaceup() && card.IsMonsterDangerous()).ToList()); + } + if (Duel.Player == 1) + { + ClientCard enemyMonster = Enemy.BattlingMonster; + if (enemyMonster != null && enemyMonster.IsMonsterInvincible()) + { + negateTargetList.Add(enemyMonster); + } + } + } + + // trigger Chengying + if (Bot.HasInMonstersZone(CardId.SwordsoulSupremeSovereign_Chengying, true, false, true) + && !activatedCardIdList.Contains(CardId.SwordsoulSupremeSovereign_Chengying) && Enemy.Graveyard.Count() > 0) + { + if (GetProblematicEnemyMonster() != null || (Duel.Phase == DuelPhase.End && Duel.Player == 1)) + { + bool triggerFlag = true; + List enemyTargetList = Enemy.GetMonsters().Where(card => + card.IsFaceup() && card.HasType(CardType.Effect) && !card.IsShouldNotBeMonsterTarget() && card.IsShouldNotBeTarget()).ToList(); + if (enemyTargetList.Count() == 0) + { + List botTargetList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasType(CardType.Effect) + && !card.IsDisabled() && card != Card && !card.IsCode(CardId.SwordsoulSupremeSovereign_Chengying)).ToList(); + if (botTargetList.Count() == 0) + { + triggerFlag = false; + } else { + botTargetList.Sort(CardContainer.CompareCardAttack); + enemyTargetList.AddRange(botTargetList); + } + } else { + enemyTargetList.Sort(CardContainer.CompareCardAttack); + enemyTargetList.Reverse(); + } + if (triggerFlag) + { + negateTargetList.AddRange(enemyTargetList); + } + } + } + + if (negateTargetList.Count() > 0) + { + // select banish card + List graveBanishList = Bot.Graveyard.Where(card => card.HasSetcode(SetcodeSwordsoul) || card.HasRace(CardRace.Wyrm)).ToList(); + + if (graveBanishList.Count() > 0) + { + bool selectFlag = false; + // trigger blackout + ClientCard blackOut = graveBanishList.FirstOrDefault(card => card.IsCode(CardId.SwordsoulBlackout)); + if (Duel.Player == 0 && !activatedCardIdList.Contains(CardId.SwordsoulBlackout) && blackOut != null) + { + AI.SelectCard(blackOut); + selectFlag = true; + } + if (!selectFlag) + { + // banish dump card + List checkIdList = new List{ + CardId.SwordsoulEmergence, CardId.SwordsoulOfTaia, CardId.SwordsoulOfMoYe, CardId.SwordsoulStrategistLongyuan, CardId.MonkOfTheTenyi, + CardId.TenyiSpirit_Adhara, CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Ashuna + }; + foreach (int checkId in checkIdList) + { + List checkCardList = graveBanishList.Where(card => card.IsCode(checkId)).ToList(); + if (checkCardList.Count() > 1) + { + AI.SelectCard(checkCardList); + selectFlag = true; + break; + } + } + } + if (!selectFlag) + { + // banish exists card + List checkIdList = new List{ + CardId.SwordsoulEmergence, CardId.MonkOfTheTenyi, CardId.ShamanOfTheTenyi, CardId.SwordsoulOfTaia, + CardId.SwordsoulStrategistLongyuan, CardId.SwordsoulOfMoYe, CardId.TenyiSpirit_Adhara, CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Ashuna + }; + foreach (int checkId in checkIdList) + { + List checkCardList = graveBanishList.Where(card => card.IsCode(checkId)).ToList(); + if (checkCardList.Count() > 0) + { + AI.SelectCard(checkCardList); + selectFlag = true; + break; + } + } + } + if (!selectFlag) + { + AI.SelectCard(ShuffleCardList(graveBanishList)); + } + } + AI.SelectNextCard(negateTargetList); + activatedCardIdList.Add(Card.Id); + return true; + } + + } else { + // search + if (CheckAtAdvantage() && enemyActivateMaxxC && Util.IsTurn1OrMain2()) + { + if (CheckRemainInDeck(CardId.SwordsoulBlackout) > 0) + { + AI.SelectCard(CardId.SwordsoulBlackout); + activatedCardIdList.Add(Card.Id); + return true; + } + + List searchIdList = new List{ + CardId.SwordsoulBlackout, CardId.SwordsoulOfMoYe, CardId.SwordsoulOfTaia, CardId.SwordsoulEmergence, + CardId.SwordsoulStrategistLongyuan + }; + foreach (int checkId in searchIdList) + { + if (CheckRemainInDeck(checkId) > 0 && !Bot.HasInHand(checkId)) + { + AI.SelectCard(checkId); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + + if (CheckAtAdvantage()) + { + if (!activatedCardIdList.Contains(CardId.SwordsoulStrategistLongyuan) && !Bot.HasInHand(CardId.SwordsoulStrategistLongyuan) + && SwordsoulOfMoYeEffectCheck() && CheckRemainInDeck(CardId.SwordsoulStrategistLongyuan) > 0) + { + AI.SelectCard(CardId.SwordsoulStrategistLongyuan); + activatedCardIdList.Add(Card.Id); + return true; + } + + if (!activatedCardIdList.Contains(CardId.SwordsoulStrategistLongyuan) && Bot.HasInHand(CardId.SwordsoulStrategistLongyuan) + && !activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && !activatedCardIdList.Contains(CardId.SwordsoulSacredSummit)) + { + // ready for another level 8 synchro + if (Bot.HasInHandOrInGraveyard(CardId.SwordsoulOfTaia) && !Bot.HasInHand(CardId.SwordsoulSacredSummit)) + { + if (CheckRemainInDeck(CardId.SwordsoulSacredSummit) > 0) + { + AI.SelectCard(CardId.SwordsoulSacredSummit); + activatedCardIdList.Add(Card.Id); + return true; + } + } + if (!Bot.HasInHandOrInGraveyard(CardId.SwordsoulOfTaia) && Bot.HasInHand(CardId.SwordsoulSacredSummit)) + { + if (CheckRemainInDeck(CardId.SwordsoulOfTaia) > 0) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + } + + if (!Bot.HasInMonstersZone(CardId.SwordsoulToken) && Bot.HasInMonstersZone(CardId.SwordsoulStrategistLongyuan) + && Bot.HasInMonstersZone(CardId.SwordsoulStrategistLongyuan) && CheckRemainInDeck(CardId.SwordsoulBlackout) > 0 + && !activatedCardIdList.Contains(CardId.SwordsoulBlackout)) + { + Logger.DebugWriteLine("Chixiao banish blackout"); + AI.SelectCard(CardId.SwordsoulBlackout); + AI.SelectOption(1); + activatedCardIdList.Add(Card.Id); + return true; + } + + if (CheckAtAdvantage()) + { + List searchIdList = new List{ + CardId.SwordsoulBlackout, CardId.SwordsoulOfMoYe, CardId.SwordsoulOfTaia, CardId.SwordsoulEmergence, + CardId.SwordsoulStrategistLongyuan + }; + foreach (int checkId in searchIdList) + { + if (CheckRemainInDeck(checkId) > 0 && !Bot.HasInHand(checkId)) + { + AI.SelectCard(checkId); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + + List checkIdList = new List{ + CardId.SwordsoulBlackout, CardId.SwordsoulOfMoYe, CardId.SwordsoulOfTaia, CardId.SwordsoulEmergence, + CardId.SwordsoulStrategistLongyuan + }; + foreach (int checkId in checkIdList) + { + if (CheckRemainInDeck(checkId) > 0 && !Bot.HasInHand(checkId)) + { + AI.SelectCard(checkId); + activatedCardIdList.Add(Card.Id); + return true; + } + } + } + + return false; + } + + public bool BaxiaBrightnessOfTheYangZingActivate() + { + Logger.DebugWriteLine("Baxia desc: " + ActivateDescription.ToString()); + + if (ActivateDescription == Util.GetStringId(CardId.BaxiaBrightnessOfTheYangZing, 0)) + { + List enemyTargetList = GetNormalEnemyTargetList(true); + if (enemyTargetList.Count() > 0) + { + AI.SelectCard(enemyTargetList); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } else + { + List destroyTarget = Bot.GetSpells(); + destroyTarget.AddRange(Bot.GetMonsters().Where(card => card.IsFacedown() || card.Attack <= 1000).ToList()); + if (destroyTarget.Count() == 0) + { + return false; + } + + bool canUseMoye = !activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) + && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0 && SwordsoulOfMoYeEffectCheck(); + bool canUseTaia = !activatedCardIdList.Contains(CardId.SwordsoulOfTaia) + && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0 && SwordsoulOfTaiaEffectCheck(); + + if (canUseMoye && Bot.HasInGraveyard(CardId.SwordsoulOfMoYe)) + { + AI.SelectCard(destroyTarget); + AI.SelectNextCard(CardId.SwordsoulOfMoYe); + activatedCardIdList.Add(Card.Id + 2); + return true; + } + if (canUseTaia && Bot.HasInGraveyard(CardId.SwordsoulOfTaia)) + { + AI.SelectCard(destroyTarget); + AI.SelectNextCard(CardId.SwordsoulOfTaia); + activatedCardIdList.Add(Card.Id + 2); + return true; + } + if (Bot.HasInGraveyard(CardId.IncredibleEcclesiaTheVirtuous)) + { + // sp summon ecclesia for moye/taia + if (!activatedCardIdList.Contains(CardId.IncredibleEcclesiaTheVirtuous)) + { + if ((canUseMoye && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0) + || (canUseTaia && CheckRemainInDeck(CardId.SwordsoulOfTaia) > 0)) + { + AI.SelectCard(destroyTarget); + AI.SelectNextCard(CardId.IncredibleEcclesiaTheVirtuous); + activatedCardIdList.Add(Card.Id + 2); + return true; + } + } + // sp summon ecclesia as tuner + if (Bot.GetMonsters().Any(card => card.IsFaceup() && !card.IsTuner() && card.Level == 4)) + { + AI.SelectCard(destroyTarget); + AI.SelectNextCard(CardId.IncredibleEcclesiaTheVirtuous); + activatedCardIdList.Add(Card.Id + 2); + return true; + } + } + } + + return false; + } + + public bool YaziEvilOfTheYangZingActivate() + { + if (Card.Location == CardLocation.Grave) + { + // special summon + if (!activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0 + && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0 && SwordsoulOfMoYeEffectCheck()) + { + AI.SelectCard(CardId.SwordsoulOfMoYe); + return true; + } + if (!activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && CheckRemainInDeck(CardId.SwordsoulOfTaia) > 0 + && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + return true; + } + if (Bot.HasInMonstersZone(CardId.SwordsoulToken)) + { + List specialSummonIdListForSynchro = new List{CardId.SwordsoulStrategistLongyuan, CardId.SwordsoulOfMoYe, CardId.SwordsoulOfTaia}; + foreach (int checkId in specialSummonIdListForSynchro) + { + if (CheckRemainInDeck(checkId) > 0) + { + AI.SelectCard(checkId); + return true; + } + } + } + List specialSummonIdList = new List{ + CardId.TenyiSpirit_Ashuna, CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Adhara, + CardId.SwordsoulStrategistLongyuan, CardId.SwordsoulOfMoYe, CardId.SwordsoulOfTaia + }; + foreach (int checkId in specialSummonIdList) + { + if (CheckRemainInDeck(checkId) > 0) + { + AI.SelectCard(checkId); + return true; + } + } + } else + { + // destroy + if (CheckWhetherNegated()) + { + return false; + } + bool selfDestroy = false; + if (!activatedCardIdList.Contains(CardId.SwordsoulOfMoYe) && CheckRemainInDeck(CardId.SwordsoulOfMoYe) > 0 + && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0 && SwordsoulOfMoYeEffectCheck()) + { + selfDestroy = true; + } + if (!activatedCardIdList.Contains(CardId.SwordsoulOfTaia) && CheckRemainInDeck(CardId.SwordsoulOfTaia) > 0 + && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0) + { + selfDestroy = true; + } + if (selfDestroy) + { + AI.SelectCard(Card); + } else + { + List YangZingList = Bot.GetMonsters().Where(card => card.IsFaceup() && card.HasSetcode(SetcodeYangZing)).ToList(); + YangZingList.Sort(CardContainer.CompareCardAttack); + AI.SelectCard(YangZingList); + } + AI.SelectNextCard(GetNormalEnemyTargetList(true)); + return true; + } + + return false; + } + + public bool ShamanOfTheTenyiActivate() + { + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + // destroy + AI.SelectCard(GetNormalEnemyTargetList()); + return true; + } else + { + // special summon + if (CheckAtAdvantage() && enemyActivateMaxxC && Util.IsTurn1OrMain2()) + { + return false; + } + + bool canUseMoye = Bot.HasInGraveyard(CardId.SwordsoulOfMoYe) && CheckCalledbytheGrave(CardId.SwordsoulOfMoYe) == 0 + && !activatedCardIdList.Contains(CardId.SwordsoulOfMoYe); + bool canUseTaia = Bot.HasInHandOrInGraveyard(CardId.SwordsoulOfTaia) && CheckCalledbytheGrave(CardId.SwordsoulOfTaia) == 0 + && !activatedCardIdList.Contains(CardId.SwordsoulOfTaia); + bool shouldDiscardTaia = !Bot.HasInGraveyard(CardId.SwordsoulOfTaia) && Bot.HasInHand(CardId.SwordsoulOfTaia); + List sortedReviveTargetList = Bot.GetGraveyardMonsters().Where(card => + card.IsCanRevive() && card.HasRace(CardRace.Wyrm)).ToList(); + sortedReviveTargetList.Sort(CardContainer.CompareCardAttack); + sortedReviveTargetList.Reverse(); + + if (CheckAtAdvantage()) + { + // try to kill + if (Duel.Turn > 1 && Enemy.GetMonsterCount() == 0) + { + int currentAttack = Util.GetTotalAttackingMonsterAttack(0); + if (currentAttack < Enemy.LifePoints) + { + List overkillList = sortedReviveTargetList.Where(card => + card.Attack + currentAttack >= Enemy.LifePoints).ToList(); + if (overkillList.Count() > 0) + { + SelectDiscardForShamanOfTheTenyi(shouldDiscardTaia); + AI.SelectNextCard(overkillList); + return true; + } + } + } + + // for next synchro + if (canUseMoye) + { + SelectDiscardForShamanOfTheTenyi(); + AI.SelectNextCard(CardId.SwordsoulOfMoYe); + return true; + } + if (canUseTaia) + { + SelectDiscardForShamanOfTheTenyi(shouldDiscardTaia); + AI.SelectNextCard(CardId.SwordsoulOfTaia); + return true; + } + + // choose max attack + SelectDiscardForShamanOfTheTenyi(); + AI.SelectNextCard(sortedReviveTargetList); + return true; + + } else { + // reborn synchro monster + List synchroMonsterList = sortedReviveTargetList.Where(card => card.HasType(CardType.Synchro)).ToList(); + if (synchroMonsterList.Count() > 0) + { + SelectDiscardForShamanOfTheTenyi(); + AI.SelectNextCard(synchroMonsterList); + return true; + } + + // for next synchro + if (canUseMoye) + { + SelectDiscardForShamanOfTheTenyi(); + AI.SelectNextCard(CardId.SwordsoulOfMoYe); + return true; + } + if (canUseTaia) + { + SelectDiscardForShamanOfTheTenyi(shouldDiscardTaia); + AI.SelectNextCard(CardId.SwordsoulOfTaia); + return true; + } + } + } + + return false; + } + + public void SelectDiscardForShamanOfTheTenyi(bool useTaia = false) + { + if (useTaia) + { + AI.SelectCard(CardId.SwordsoulOfTaia); + } else { + // drop tenyi + List tenyiList = new List{CardId.TenyiSpirit_Vishuda, CardId.TenyiSpirit_Ashuna, CardId.TenyiSpirit_Adhara}; + foreach (int tenyiId in tenyiList) + { + if (Bot.HasInHand(tenyiId)) + { + AI.SelectCard(tenyiId); + return; + } + } + + // drop dump card + foreach (ClientCard hand in Bot.Hand) + { + if (Bot.Hand.Where(card => card.IsCode(hand.Id)).Count() > 1) + { + AI.SelectCard(hand); + return; + } + } + + // check discard list + List discardList = new List{ + CardId.CrossoutDesignator, _CardId.PotOfDesires, CardId.TenyiSpirit_Ashuna, CardId.TenyiSpirit_Vishuda, + CardId.TenyiSpirit_Adhara, CardId.NibiruThePrimalBeing, CardId.SwordsoulSacredSummit, CardId.IncredibleEcclesiaTheVirtuous, + _CardId.InfiniteImpermanence, _CardId.CalledByTheGrave, CardId.SwordsoulOfTaia, CardId.SwordsoulOfMoYe, + CardId.SwordsoulStrategistLongyuan, _CardId.AshBlossom, _CardId.MaxxC, _CardId.EffectVeiler, + CardId.SwordsoulEmergence, CardId.SwordsoulBlackout + }; + foreach (int discardCheck in discardList) + { + if (Bot.HasInHand(discardCheck)) + { + AI.SelectCard(discardCheck); + return; + } + } + + } + } + + public bool SpellSetCheck() + { + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + List onlyOneSetList = new List{ + CardId.SwordsoulBlackout + }; + if (onlyOneSetList.Contains(Card.Id) && Bot.HasInSpellZone(Card.Id)) + { + return false; + } + + // select place + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay))) + { + List avoid_list = new List(); + int setFornfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + setFornfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setFornfiniteImpermanence); + return true; + } else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } else + { + SelectSTPlace(); + } + return true; + } + + else if (Enemy.HasInSpellZone(_CardId.AntiSpellFragrance, true) || Bot.HasInSpellZone(_CardId.AntiSpellFragrance, true)) + { + if (Card.IsSpell() && !Bot.HasInSpellZone(Card.Id)) + { + SelectSTPlace(); + return true; + } + } + + return false; + } + + protected override bool DefaultSetForDiabellze() + { + if (base.DefaultSetForDiabellze()) + { + SelectSTPlace(null, true); + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TearlamentsExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TearlamentsExecutor.cs new file mode 100644 index 0000000..2300de7 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TearlamentsExecutor.cs @@ -0,0 +1,2658 @@ +using YGOSharp.OCGWrapper; +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("Tearlaments", "AI_Tearlaments")] + class TearlamentsExecutor : DefaultExecutor + { + public class CardId + { + public const int ShaddollBeast = 3717252; + public const int ShaddollDragon = 77723643; + public const int TearlamentsScheiren = 572850; + public const int TearlamentsReinoheart = 73956664; + public const int KelbektheAncientVanguard = 25926710; + public const int MudoratheSwordOracle = 99937011; + public const int AgidotheAncientSentinel = 62320425; + public const int KeldotheSacredProtector = 63542003; + public const int NaelshaddollAriel = 97518132; + public const int TearlamentsHavnis = 37961969; + public const int TearlamentsMerrli = 74078255; + public const int DivineroftheHerald = 92919429; + public const int HeraldofOrangeLight = 17266660; + public const int HeraldofGreenLight = 21074344; + public const int Eva = 40177746; + public const int TearlamentsScream = 6767771; + public const int PrimevalPlanetPerlereino = 77103950; + public const int TearlamentsSulliek = 74920585; + + public const int TearlamentsKaleidoHeart = 28226490; + public const int TearlamentsRulkallos = 84330567; + public const int PredaplantDragostapelia = 69946549; + public const int TearlamentsKitkallos = 92731385; + public const int ElShaddollWinda = 94977269; + public const int ElderEntityNtss = 80532587; + public const int BaronnedeFleur = 84815190; + public const int FADawnDragster = 33158448; + public const int AbyssDweller = 21044178; + public const int UnderworldGoddessoftheClosedWorld = 98127546; + public const int MekkKnightCrusadiaAvramax = 21887175; + public const int KnightmareUnicorn = 38342335; + public const int SprightElf = 27381364; + public const int IP = 65741786; + } + // false: EDOPro + const bool IS_YGOPRO = true; + // YGOPro: 0x181 + // EDOPro: 0x182 + int SETCODE = 0x181; + + bool activate_TearlamentsScheiren_1 = false; + bool activate_TearlamentsScheiren_2 = false; + bool activate_TearlamentsReinoheart_1 = false; + bool activate_TearlamentsReinoheart_2 = false; + bool activate_TearlamentsHavnis_1 = false; + bool activate_TearlamentsHavnis_2 = false; + bool activate_TearlamentsMerrli_1 = false; + bool activate_TearlamentsMerrli_2 = false; + + bool activate_TearlamentsKitkallos_1 = false; + bool activate_TearlamentsKitkallos_2 = false; + bool activate_TearlamentsKitkallos_3 = false; + bool TearlamentsKitkallostohand = true; + + bool activate_TearlamentsScream_1 = false; + bool activate_TearlamentsScream_2 = false; + + bool activate_TearlamentsSulliek_1 = false; + bool activate_TearlamentsSulliek_2 = false; + + bool activate_AgidotheAncientSentinel_2 = false; + bool activate_KelbektheAncientVanguard_2 = false; + bool activate_TearlamentsRulkallos_1 = false; + bool activate_TearlamentsRulkallos_2 = false; + bool activate_MudoratheSwordOracle_2 = false; + bool activate_KeldotheSacredProtector_2 = false; + bool activate_PrimevalPlanetPerlereino_1 = false; + bool activate_PrimevalPlanetPerlereino_2 = false; + bool activate_TearlamentsKaleidoHeart_1 = false; + bool activate_TearlamentsKaleidoHeart_2 = false; + bool activate_Eva = false; + bool activate_DivineroftheHerald = false; + bool summoned = false; + bool spsummoned = false; + bool TearlamentsKitkallos_summoned = false; + + bool summon_SprightElf = false; + bool chainlist = false; + + bool pre_activate_PrimevalPlanetPerlereino = false; + + bool select_TearlamentsKitkallos = false; + private enum Flag + { + TearlamentsKitkallos = 0x1, + TearlamentsRulkallos = 0x2, + TearlamentsKaleidoHeart = 0x4, + PredaplantDragostapelia = 0x8, + ElShaddollWinda = 0x10 + } + + List remainCards = new List(); + List fusionExtra = new List(); + List fusionMaterial = new List(); + List on_chaining_cards = new List(); + List mcard_0 = new List() { null, null, null }; + List mcard_1 = new List() { null, null, null }; + List mcard_2 = new List() { null, null, null }; + List mcard_3 = new List() { null, null, null }; + List ran_fusion_mode_0 = new List() { false, false, false }; + List ran_fusion_mode_1 = new List() { false, false, false }; + List ran_fusion_mode_2 = new List() { false, false, false }; + List ran_fusion_mode_3 = new List() { false, false, false }; + + ClientCard _PredaplantDragostapelia = null; + ClientCard chain_PredaplantDragostapelia = null; + ClientCard chain_TearlamentsSulliek = null; + ClientCard tgcard = null; + ClientCard no_fusion_card = null; + List e_PredaplantDragostapelia_cards = new List(); + + ClientCard link_card = null; + List no_link_ids = new List() { CardId.TearlamentsRulkallos, CardId.BaronnedeFleur, CardId.MekkKnightCrusadiaAvramax, CardId.AbyssDweller, CardId.PredaplantDragostapelia, CardId.UnderworldGoddessoftheClosedWorld, CardId.FADawnDragster, CardId.TearlamentsKaleidoHeart }; + + List key_send_to_deck_ids = new List() + { + CardId.TearlamentsMerrli,CardId.TearlamentsScheiren,CardId.TearlamentsHavnis,CardId.TearlamentsReinoheart,8736823, + 98715423,17484499 + }; + List all_key_card_ids = new List() + { + 55623480,86682165,60461804,10000090,28651380,97565997,87074380,80208158,95440946,93880808,16261341, + 91749600,26866984,5141117,50383626,30576089,22586618,7445307,73478096,18558867, + 51617185,60880471,34172284,88774734,25451383,71197066,24226942,78077209,98787535, + 29601381,83203672,62383431,89552119,92418590,31042659,83303851,17502671,11366199, + 46668237,64382839,46290741,25607552,1295442,5560911,56174248,7407724,1855886,27198001, + 11074235,48372950,94142993,81866673,34966096,42006475,99733359,20799347,71985676, + 55787576,43266605,3422200,97962972,20773176,84976088,55151012,80208323,98881700,56677752, + 24506253,6180710,20056760,44928016,45702014,60316373,37683547,62962630,20065259,8571567, + 21351206,35998832,26077387,37351133,94730900,83682209,38695361,59707204,12469386,1833916, + 98806751,82496097,27182739,28762303,74578072,30303854,5370235,50546208,44818,67436768,29169993, + 10286023,19667590,47897376,74891384,66752837,43534808,56815977,81344070,59724555,93708824, + 43411796,7084129,51993760,87988305,23619206,86962245,48144778,30068120,9047460,25538345,69764158, + 70645913,55702233,10928224,79531196,23893227,57421866,94693857,78080961,9742784,59185998, + 93169863,46576366,2830693,68543408,50820852,2511,8972398,61488417,71734607,63180841,51447164, + 74586817,28403802,91575236,286392,97584719,60195675,24701066,20665527,73345237,23732205,146746, + 72218246,41999284,60303245 + }; + List key_no_send_to_deck_ids = new List() + { + CardId.TearlamentsRulkallos,50588353,44097050 + }; + List key_remove_ids = new List() + { + CardId.TearlamentsMerrli,CardId.TearlamentsScheiren,CardId.TearlamentsHavnis,CardId.TearlamentsReinoheart,15291624, + 11738489,44097050,15291624,63288573,70369116,83152482,72329844,24094258,86066372, + 74997493,85289965,21887175,11738489, 98127546,50588353,10389142,90590303,27548199, + }; + List key_no_remove_ids = new List() + { + 18743376,72355272,81555617,45960523,29596581,56713174,80280944,61103515,28297833, + 90020780,8736823 + }; + List bot_send_to_deck_ids = new List(); + public TearlamentsExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, CardId.TearlamentsScream, TearlamentsScreamEffect_1); + AddExecutor(ExecutorType.Activate, CardId.AbyssDweller, () => { return Duel.Player != 0; }); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsKaleidoHeart, TearlamentsKaleidoHeartEffect); + AddExecutor(ExecutorType.Activate, CardId.UnderworldGoddessoftheClosedWorld); + AddExecutor(ExecutorType.SpSummon, CardId.FADawnDragster, FADawnDragsterSummon); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsKitkallos, TearlamentsKitkallosEffect_2); + AddExecutor(ExecutorType.SpSummon, CardId.UnderworldGoddessoftheClosedWorld, UnderworldGoddessoftheClosedWorldSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SprightElf, SprightElfSummon_2); + AddExecutor(ExecutorType.SpSummon, CardId.IP, IPSummon_2); + AddExecutor(ExecutorType.Activate, CardId.BaronnedeFleur, BaronnedeFleurEffect); + AddExecutor(ExecutorType.Activate, CardId.ElderEntityNtss, ElderEntityNtssEffect); + AddExecutor(ExecutorType.Activate, CardId.PredaplantDragostapelia, PredaplantDragostapeliaEffect); + AddExecutor(ExecutorType.Activate, CardId.HeraldofOrangeLight, DefaultTrap); + AddExecutor(ExecutorType.Activate, CardId.HeraldofGreenLight, DefaultTrap); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsRulkallos, TearlamentsRulkallosEffect); + AddExecutor(ExecutorType.Activate, CardId.FADawnDragster); + AddExecutor(ExecutorType.Activate, CardId.PrimevalPlanetPerlereino, PrimevalPlanetPerlereinoEffect); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsScheiren, TearlamentsScheirenEffect); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsKitkallos, TearlamentsKitkallosEffect); + AddExecutor(ExecutorType.Activate, CardId.SprightElf, SprightElfEffect); + AddExecutor(ExecutorType.SpSummon, CardId.UnderworldGoddessoftheClosedWorld, UnderworldGoddessoftheClosedWorldSummon_3); + AddExecutor(ExecutorType.Activate, CardId.MudoratheSwordOracle, MudoratheSwordOracleEffect); + AddExecutor(ExecutorType.Activate, CardId.DivineroftheHerald, DivineroftheHeraldEffect); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsMerrli, TearlamentsMerrliEffect); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsHavnis, TearlamentsHavnisEffect); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsReinoheart, TearlamentsReinoheartEffect); + AddExecutor(ExecutorType.Summon, CardId.DivineroftheHerald, DivineroftheHeraldSummon); + AddExecutor(ExecutorType.Summon, CardId.TearlamentsMerrli, () => { summoned = true; return true; }); + AddExecutor(ExecutorType.Summon, CardId.TearlamentsReinoheart, () => { summoned = true; return true; }); + AddExecutor(ExecutorType.Activate, CardId.AgidotheAncientSentinel, AgidotheAncientSentinelEffect); + AddExecutor(ExecutorType.Activate, CardId.KelbektheAncientVanguard, KelbektheAncientVanguardEffect); + AddExecutor(ExecutorType.Activate, CardId.NaelshaddollAriel, NaelshaddollArielEffect); + AddExecutor(ExecutorType.Activate, CardId.ShaddollDragon, ShaddollDragonEffect); + AddExecutor(ExecutorType.Activate, CardId.Eva, EvaEffect); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsSulliek, TearlamentsSulliekEffect); + AddExecutor(ExecutorType.Activate, CardId.TearlamentsScream,()=> { return !AllActivated(); }); + AddExecutor(ExecutorType.Activate, CardId.KeldotheSacredProtector, MudoratheSwordOracleEffect); + AddExecutor(ExecutorType.Activate, CardId.ShaddollBeast, () => { return Bot.Deck.Count > 0; }); + AddExecutor(ExecutorType.Summon, CardId.DivineroftheHerald, ()=> { return !Bot.HasInHand(CardId.HeraldofGreenLight) && !Bot.HasInHand(CardId.HeraldofOrangeLight); }); + AddExecutor(ExecutorType.SpSummon, CardId.AbyssDweller, AbyssDwellerSummon_2); + AddExecutor(ExecutorType.SpSummon, CardId.SprightElf, SprightElfSummon); + AddExecutor(ExecutorType.SpSummon, CardId.BaronnedeFleur, BaronnedeFleurSummon); + AddExecutor(ExecutorType.SpSummon, CardId.FADawnDragster, () => { SetSpSummon(); return true; }); + AddExecutor(ExecutorType.SpSummon, CardId.AbyssDweller, AbyssDwellerSummon); + AddExecutor(ExecutorType.Activate, CardId.IP, IPEffect); + AddExecutor(ExecutorType.SpSummon, CardId.IP, IPSummon); + AddExecutor(ExecutorType.SpSummon, CardId.UnderworldGoddessoftheClosedWorld, UnderworldGoddessoftheClosedWorldSummon_2); + AddExecutor(ExecutorType.Activate, CardId.KnightmareUnicorn, KnightmareUnicornEffect); + AddExecutor(ExecutorType.SpSummon, CardId.KnightmareUnicorn, KnightmareUnicornSummon); + AddExecutor(ExecutorType.Activate, CardId.MekkKnightCrusadiaAvramax, MekkKnightCrusadiaAvramaxEffect); + AddExecutor(ExecutorType.SpSummon, CardId.MekkKnightCrusadiaAvramax, MekkKnightCrusadiaAvramaxSummon); + AddExecutor(ExecutorType.SpSummon, CardId.BaronnedeFleur, BaronnedeFleurSummon_2); + AddExecutor(ExecutorType.SpSummon, CardId.BaronnedeFleur, () => { return Bot.HasInMonstersZone(CardId.SprightElf, true, false, true); }); + AddExecutor(ExecutorType.Repos, DefaultMonsterRepos); + AddExecutor(ExecutorType.SpellSet, SpellSet); + } + + public override bool OnSelectHand() + { + // go first + return true; + } + + public override void OnNewTurn() + { + List cards = Bot.ExtraDeck.Where(card => card != null && card.Id == CardId.PredaplantDragostapelia).ToList(); + if (_PredaplantDragostapelia == null && cards.Count > 0) _PredaplantDragostapelia = cards.FirstOrDefault(); + if (!key_send_to_deck_ids.Contains(all_key_card_ids[0])) key_send_to_deck_ids.AddRange(all_key_card_ids); + if (!key_remove_ids.Contains(all_key_card_ids[0])) key_remove_ids.AddRange(all_key_card_ids); + if (_PredaplantDragostapelia != null && (_PredaplantDragostapelia.Location != CardLocation.MonsterZone || _PredaplantDragostapelia.IsFacedown())) + e_PredaplantDragostapelia_cards.Clear(); + List temp = new List(e_PredaplantDragostapelia_cards); + foreach (var card in temp) + { + if (card == null || card.Location != CardLocation.MonsterZone || card.IsFacedown()) e_PredaplantDragostapelia_cards.Remove(card); + } + activate_TearlamentsScheiren_1 = false; + activate_TearlamentsScheiren_2 = false; + activate_TearlamentsReinoheart_1 = false; + activate_TearlamentsReinoheart_2 = false; + activate_TearlamentsHavnis_1 = false; + activate_TearlamentsHavnis_2 = false; + activate_TearlamentsMerrli_1 = false; + activate_TearlamentsMerrli_2 = false; + activate_PrimevalPlanetPerlereino_1 = false; + activate_PrimevalPlanetPerlereino_2 = false; + + activate_TearlamentsKitkallos_1 = false; + activate_TearlamentsKitkallos_2 = false; + activate_TearlamentsKitkallos_3 = false; + activate_TearlamentsScream_1 = false; + activate_TearlamentsScream_2 = false; + activate_TearlamentsSulliek_1 = false; + activate_TearlamentsSulliek_2 = false; + activate_TearlamentsRulkallos_1 = false; + activate_TearlamentsKaleidoHeart_1 = false; + activate_TearlamentsKaleidoHeart_2 = false; + activate_AgidotheAncientSentinel_2 = false; + activate_KelbektheAncientVanguard_2 = false; + activate_Eva = false; + activate_DivineroftheHerald = false; + summoned = false; + spsummoned = false; + summon_SprightElf = false; + TearlamentsKitkallos_summoned = false; + base.OnNewTurn(); + } + private List GetZoneCards(CardLocation loc, ClientField player) + { + List res = new List(); + List temp = new List(); + if ((loc & CardLocation.Hand) > 0) { temp = player.Hand.Where(card => card != null).ToList(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.MonsterZone) > 0) { temp = player.GetMonsters(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.SpellZone) > 0) { temp = player.GetSpells(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.Grave) > 0) { temp = player.Graveyard.Where(card => card != null).ToList(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.Removed) > 0) { temp = player.Banished.Where(card => card != null).ToList(); if (temp.Count() > 0) res.AddRange(temp); } + if ((loc & CardLocation.Extra) > 0) { temp = player.ExtraDeck.Where(card => card != null).ToList(); if (temp.Count() > 0) res.AddRange(temp); } + return res; + } + private IList CardsIdToClientCards(IList cardsId, IList cardsList, bool uniqueId = true, bool alias = true) + { + if (cardsList?.Count() <= 0 || cardsId?.Count() <= 0) return new List(); + List res = new List(); + foreach (var cardid in cardsId) + { + List cards = cardsList.Where(card => card != null && (card.Id == cardid || ((card.Alias != 0 && cardid == card.Alias) & alias))).ToList(); + if (cards?.Count <= 0) continue; + cards.Sort(CardContainer.CompareCardAttack); + if (uniqueId) res.Add(cards.First()); + else res.AddRange(cards); + } + res = res.Distinct().ToList(); + return res; + } + private List GetKeyFusionCard(int key) + { + int id = 0; + if (Duel.Player == 0) + { + switch (key) + { + case 0: + case 2: id = CardId.TearlamentsKitkallos; break; + case 1: + case 6: id = CardId.TearlamentsRulkallos; break; + case 3: id = CardId.PredaplantDragostapelia; break; + case 4: id = CardId.TearlamentsKaleidoHeart; break; + case 5: id = CardId.PredaplantDragostapelia; break; + default: break; + } + } + else + { + switch (key) + { + case 0: + case 2: id = CardId.ElShaddollWinda; break; + case 1: + case 4: id = CardId.TearlamentsKitkallos; break; + case 3: id = CardId.TearlamentsRulkallos; break; + case 5: id = CardId.TearlamentsKaleidoHeart; break; + case 6: id = CardId.PredaplantDragostapelia; break; + default: break; + } + } + List res = new List(); + int index = -1; + for (int i = 0; i < fusionExtra.Count; ++i) + { + ClientCard card = fusionExtra[i]; + if (card == null) continue; + if (card.Id == id) + { + index = i; + res.Add(card); + break; + } + } + if (index > -1 && index < fusionExtra.Count) fusionExtra.RemoveAt(index); + return res; + } + private bool IsLastFusionCard() + { + int count = 0; + if (activate_TearlamentsScheiren_2) ++count; + if (activate_TearlamentsHavnis_2) ++count; + if (activate_TearlamentsMerrli_2) ++count; + return count >= 2; + } + private bool CheckFusion(int listindex, int id) + { + int key = -1; + if (Duel.Player == 0) + { + if (fusionExtra.Count > 0) + { + bool flag_4 = fusionExtra.Count(card => card != null && card.Id == CardId.PredaplantDragostapelia) > 0 && Bot.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true); + bool flag_1 = ((Duel.Phase < DuelPhase.End && (!activate_TearlamentsKitkallos_1 || !activate_TearlamentsKitkallos_2)) || (Duel.Phase == DuelPhase.End && !activate_TearlamentsKitkallos_1 && !activate_TearlamentsKitkallos_2)) && fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsKitkallos) > 0; + bool flag_2 = fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsRulkallos) > 0 && (Bot.HasInGraveyard(CardId.TearlamentsKitkallos) || Bot.GetMonsters().Count(card => card != null && card.Id == CardId.TearlamentsKitkallos) > 1 || Duel.CurrentChain.Any(card=>card!=null && card.Controller==0 && card!=Card && (card.Id==CardId.TearlamentsScheiren || card.Id==CardId.TearlamentsHavnis || card.Id==CardId.TearlamentsMerrli))); + // && !activate_TearlamentsKaleidoHeart_1 && GetZoneCards(CardLocation.Onfield, Enemy).Count(card => card != null && !card.IsShouldNotBeTarget()) > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.TearlamentsKaleidoHeart) + //&& (!Bot.HasInSpellZone(CardId.PrimevalPlanetPerlereino, true, true) || (Bot.HasInSpellZone(CardId.PrimevalPlanetPerlereino, true, true) && activate_PrimevalPlanetPerlereino_2) + bool flag_5 = fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart) > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.TearlamentsKaleidoHeart); + //&& Enemy.GetMonsters().Any(card => card != null && card.HasType(CardType.Effect) && !card.IsDisabled() && card.IsFaceup() && !card.IsShouldNotBeTarget()) + bool flag_6 = fusionExtra.Count(card => card != null && card.Id == CardId.PredaplantDragostapelia) > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.PredaplantDragostapelia); + bool flag_7 = fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsRulkallos) > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.TearlamentsRulkallos) && IsLastFusionCard(); + bool flag_3 = fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsKitkallos) > 0; + if (flag_4) key = 3; + else if (flag_1) key = 0; + else if (flag_2) key = 1; + else if (flag_5) key = 4; + else if (flag_6) key = 5; + else if (flag_7) key = 6; + else if (flag_3) key = 2; + if (key > -1) + { + List fusionMaterialTemp = new List(fusionMaterial); + fusionMaterialTemp.Remove(Card); + switch (key) + { + case 0: + case 2: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && (card.HasRace(CardRace.Aqua) || (card.HasType(CardType.Monster) && card.HasSetcode(SETCODE)))).ToList(); + break; + case 1: + case 6: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && card.Id == CardId.TearlamentsKitkallos).ToList(); + break; + case 3: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && card.Id == CardId.ElShaddollWinda).ToList(); + break; + case 4: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && card.HasType(CardType.Monster) && card.HasSetcode(SETCODE)).ToList(); + break; + case 5: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && (card.Id != CardId.TearlamentsRulkallos || card.IsDisabled()) && card.HasType(CardType.Fusion)).ToList(); + break; + default: + return false; + } + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && (card.HasRace(CardRace.Aqua) || (card.HasType(CardType.Monster) && card.HasSetcode(SETCODE)))).ToList(); + int chaining_key_count = on_chaining_cards.Count(card => card != null && (card.Id == CardId.AgidotheAncientSentinel || card.Id == CardId.KelbektheAncientVanguard)); + int chaining_key_count_2 = on_chaining_cards.Count(card => card != null && card.Id == CardId.TearlamentsSulliek); + List current_chain_cards = new List(Duel.CurrentChain); + IList current_chain_key_cards = new List(); + foreach (var card in current_chain_cards) + { + if (card == null || card.Controller == 1) continue; + if ((card.Id == CardId.TearlamentsMerrli && !HasInList(current_chain_key_cards, CardId.TearlamentsMerrli)) + || (card.Id == CardId.TearlamentsHavnis && !HasInList(current_chain_key_cards, CardId.TearlamentsHavnis) + || (card.Id == CardId.TearlamentsScheiren && !HasInList(current_chain_key_cards, CardId.TearlamentsScheiren)))) + current_chain_key_cards.Add(card); + } + if ((fusionMaterialTemp.Count <= 0 && chaining_key_count <= 0 && chaining_key_count_2 <= 0) || current_chain_key_cards.Count() >= 2) + { + if (!remainCards.Contains(Card)) remainCards.Add(Card); + return false; + } + switch (id) + { + case CardId.TearlamentsScheiren: activate_TearlamentsScheiren_2 = true; break; + case CardId.TearlamentsHavnis: activate_TearlamentsHavnis_2 = true; break; + case CardId.TearlamentsMerrli: activate_TearlamentsMerrli_2 = true; break; + default: break; + } + if (chaining_key_count > 0 || chaining_key_count_2 > 0) + { + ran_fusion_mode_0[listindex] = true; + ran_fusion_mode_1[listindex] = true; + ran_fusion_mode_2[listindex] = true; + return true; + } + fusionMaterialTemp.Sort(CardContainer.CompareCardAttack); + fusionMaterialTemp = GetDefaultMaterial(fusionMaterialTemp); + List res = GetKeyFusionCard(key); + mcard_0[listindex] = res.ElementAtOrDefault(0); + mcard_1[listindex] = Card; + mcard_2[listindex] = fusionMaterialTemp.ElementAtOrDefault(0); + if (res.Any(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart)) + { + if (fusionMaterialTemp.Count <= 1) + { + mcard_0[listindex] = null; + mcard_1[listindex] = null; + mcard_2[listindex] = null; + ran_fusion_mode_0[listindex] = true; + ran_fusion_mode_1[listindex] = true; + ran_fusion_mode_2[listindex] = true; + return true; + } + if (mcard_2[listindex] != null && mcard_2[listindex].Id == CardId.TearlamentsReinoheart) + { + mcard_3[listindex] = fusionMaterialTemp.ElementAtOrDefault(1); + } + else + { + List temp = fusionMaterialTemp.Where(card => card != null && card.Id == CardId.TearlamentsReinoheart).ToList(); + if (temp.Count <= 0) + { + mcard_0[listindex] = null; + mcard_1[listindex] = null; + mcard_2[listindex] = null; + ran_fusion_mode_0[listindex] = true; + ran_fusion_mode_1[listindex] = true; + ran_fusion_mode_2[listindex] = true; + return true; + } + mcard_3[listindex] = temp.ElementAtOrDefault(0); + } + } + if (mcard_1[listindex] != null) fusionMaterial.Remove(mcard_1[listindex]); + if (mcard_2[listindex] != null) fusionMaterial.Remove(mcard_2[listindex]); + if (mcard_3[listindex] != null) fusionMaterial.Remove(mcard_3[listindex]); + //foreach (var card in fusionMaterial) + //{ + // if (card == null) continue; + // Logger.DebugWriteLine("remain" + card.Id); + //} + return true; + } + } + return false; + } + else + { + if (fusionExtra.Count > 0) + { + bool flag_1 = (fusionExtra.Count(card => card != null && card.Id == CardId.ElShaddollWinda) > 0 + && (fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsKitkallos) <= 0 || + activate_TearlamentsKitkallos_1 || Bot.GetMonstersInMainZone().Count >= 4 || TearlamentsKitkallos_summoned) && Bot.GetGraveyardMonsters().Any(card => card != null && card.HasSetcode(0x9d)) + && Card.HasAttribute(CardAttribute.Dark)); + bool flag_2 = fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsKitkallos) > 0 && !activate_TearlamentsKitkallos_1; + bool flag_3 = fusionExtra.Count(card => card != null && card.Id == CardId.ElShaddollWinda) > 0 && Bot.GetGraveyardMonsters().Any(card => card != null && card.HasSetcode(0x9d)) + && Card.HasAttribute(CardAttribute.Dark); + bool flag_4 = fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsRulkallos) > 0 && (Bot.HasInGraveyard(CardId.TearlamentsKitkallos) || Bot.HasInMonstersZone(CardId.TearlamentsKitkallos, false, false, true)); + bool flag_6 = fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart) > 0 && !activate_TearlamentsKaleidoHeart_1 && GetZoneCards(CardLocation.Onfield, Enemy).Count(card => card != null && !card.IsShouldNotBeTarget()) > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.TearlamentsKaleidoHeart) + && (!Bot.HasInSpellZone(CardId.PrimevalPlanetPerlereino, true, true) || (Bot.HasInSpellZone(CardId.PrimevalPlanetPerlereino, true, true) && activate_PrimevalPlanetPerlereino_2)); + //&& Enemy.GetMonsters().Any(card => card != null && card.HasType(CardType.Effect) && !card.IsDisabled() && card.IsFaceup() && !card.IsShouldNotBeTarget()) + bool flag_7 = fusionExtra.Count(card => card != null && card.Id == CardId.PredaplantDragostapelia) > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.PredaplantDragostapelia); + bool flag_5 = fusionExtra.Count(card => card != null && card.Id == CardId.TearlamentsKitkallos) > 0; + if (flag_1) key = 0; + else if (flag_2) key = 1; + else if (flag_3) key = 2; + else if (flag_4) key = 3; + else if (flag_6) key = 5; + else if (flag_7) key = 6; + else if (flag_5) key = 4; + if (key > -1) + { + List fusionMaterialTemp = new List(fusionMaterial); + fusionMaterialTemp.Remove(Card); + switch (key) + { + case 0: + case 2: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && (card.HasType(CardType.Monster) && card.HasSetcode(0x9d))).ToList(); + break; + case 1: + case 4: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && (card.HasRace(CardRace.Aqua) || (card.HasType(CardType.Monster) && card.HasSetcode(SETCODE)))).ToList(); + break; + case 3: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && card.Id == CardId.TearlamentsKitkallos).ToList(); + break; + case 5: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && card.HasType(CardType.Monster) && card.HasSetcode(SETCODE)).ToList(); + break; + case 6: + fusionMaterialTemp = fusionMaterialTemp.Where(card => card != null && (card.Id != CardId.TearlamentsRulkallos || card.IsDisabled()) && card.HasType(CardType.Fusion)).ToList(); + break; + default: + return false; + } + int chaining_key_count = on_chaining_cards.Count(card => card != null && (card.Id == CardId.AgidotheAncientSentinel || card.Id == CardId.KelbektheAncientVanguard)); + int chaining_key_count_2 = on_chaining_cards.Count(card => card != null && card.Id == CardId.TearlamentsSulliek); + if (fusionMaterialTemp.Count <= 0 && chaining_key_count <= 0 && chaining_key_count_2 <= 0) + { + if (!remainCards.Contains(Card)) remainCards.Add(Card); + return false; + } + switch (id) + { + case CardId.TearlamentsScheiren: activate_TearlamentsScheiren_2 = true; break; + case CardId.TearlamentsHavnis: activate_TearlamentsHavnis_2 = true; break; + case CardId.TearlamentsMerrli: activate_TearlamentsMerrli_2 = true; break; + default: break; + } + if (chaining_key_count > 0 || chaining_key_count_2 > 0) + { + ran_fusion_mode_0[listindex] = true; + ran_fusion_mode_1[listindex] = true; + ran_fusion_mode_2[listindex] = true; + return true; + } + fusionMaterialTemp.Sort(CardContainer.CompareCardAttack); + fusionMaterialTemp = GetDefaultMaterial(fusionMaterialTemp); + List res = GetKeyFusionCard(key); + mcard_0[listindex] = res.ElementAtOrDefault(0); + mcard_1[listindex] = Card; + mcard_2[listindex] = fusionMaterialTemp.ElementAtOrDefault(0); + if (res.Any(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart)) + { + if (fusionMaterialTemp.Count <= 1) + { + mcard_0[listindex] = null; + mcard_1[listindex] = null; + mcard_2[listindex] = null; + ran_fusion_mode_0[listindex] = true; + ran_fusion_mode_1[listindex] = true; + ran_fusion_mode_2[listindex] = true; + return true; + } + if (mcard_2[listindex] != null && mcard_2[listindex].Id == CardId.TearlamentsReinoheart) + { + mcard_3[listindex] = fusionMaterialTemp.ElementAtOrDefault(1); + } + else + { + List temp = fusionMaterialTemp.Where(card => card != null && card.Id == CardId.TearlamentsReinoheart).ToList(); + if (temp.Count <= 0) + { + mcard_0[listindex] = null; + mcard_1[listindex] = null; + mcard_2[listindex] = null; + ran_fusion_mode_0[listindex] = true; + ran_fusion_mode_1[listindex] = true; + ran_fusion_mode_2[listindex] = true; + return true; + } + mcard_3[listindex] = temp.ElementAtOrDefault(0); + } + } + if (mcard_1[listindex] != null) fusionMaterial.Remove(mcard_1[listindex]); + if (mcard_2[listindex] != null) fusionMaterial.Remove(mcard_2[listindex]); + if (mcard_3[listindex] != null) fusionMaterial.Remove(mcard_3[listindex]); + if (listindex > 0 && mcard_0[0] != null && mcard_0[listindex] != null && mcard_0[listindex].Id == CardId.ElShaddollWinda) + { + ClientCard temp = mcard_0[0]; + mcard_0[0] = mcard_0[listindex]; + mcard_0[listindex] = temp; + + } + return true; + + } + } + return false; + } + } + private bool FusionEffect(int id) + { + if (!chainlist) + { + chainlist = true; + fusionExtra = Bot.ExtraDeck.Where(fcard => fcard != null).ToList(); + fusionMaterial = GetZoneCards(CardLocation.MonsterZone, Bot).Where(mcard => mcard != null && mcard.IsFaceup()).ToList(); + fusionMaterial.AddRange(GetZoneCards(CardLocation.Hand | CardLocation.Grave, Bot)); + + } + int index = 0; + if (id == CardId.TearlamentsScheiren) index = 0; + else if (id == CardId.TearlamentsHavnis) index = 1; + else if (id == CardId.TearlamentsMerrli) index = 2; + if (!CheckFusion(index, id)) return false; + SetSpSummon(); + return true; + } + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + NamedCard card = NamedCard.Get(cardId); + if (Duel.Turn > 1 && Enemy.GetMonsterCount() <= 0 && (card.Attack > 0 || cardId == CardId.FADawnDragster) + && Duel.Player == 0) + { + return CardPosition.FaceUpAttack; + } + else if (Duel.Player == 1) + { + if (card.Attack < 2000) return CardPosition.FaceUpDefence; + int eatk = Util.GetBestAttack(Enemy); + if(eatk > card.Attack ) return CardPosition.FaceUpDefence; + return CardPosition.FaceUpAttack; + } + else + { + if (card.Attack <= 1000) return CardPosition.FaceUpDefence; + } + return base.OnSelectPosition(cardId, positions); + } + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location == CardLocation.MonsterZone) + { + if (cardId == CardId.SprightElf) + { + if ((Zones.z5 & available) > 0) return Zones.z5; + if ((Zones.z6 & available) > 0) return Zones.z6; + } + if (cardId == CardId.TearlamentsRulkallos && Bot.HasInExtra(CardId.SprightElf)) + { + if ((Zones.z2 & available) > 0) return Zones.z2; + if ((Zones.z0 & available) > 0) return Zones.z0; + } + ClientCard card = Bot.MonsterZone[5]; + if (card != null && card.Id == CardId.SprightElf) + { + if ((Zones.z0 & available) > 0) return Zones.z0; + if ((Zones.z2 & available) > 0) return Zones.z2; + } + card = Bot.MonsterZone[6]; + if (card != null && card.Id == CardId.SprightElf) + { + if ((Zones.z4 & available) > 0) return Zones.z4; + if ((Zones.z2 & available) > 0) return Zones.z2; + + } + + } + if (player == 0 && location == CardLocation.SpellZone && location != CardLocation.FieldZone) + { + List keys = new List() { 0, 1, 2, 3, 4 }; + while (keys.Count > 0) + { + int index = Program.Rand.Next(keys.Count); + int key = keys[index]; + int zone = 1 << key; + if ((zone & available) > 0) return zone; + keys.Remove(key); + } + + } + return base.OnSelectPlace(cardId, player, location, available); + } + public override int OnSelectOption(IList options) + { + if (options.Count == 2 && (IS_YGOPRO ? options.Contains(1190) : options.Contains(573))) + { + return TearlamentsKitkallostohand ? 0 : 1; + } + return base.OnSelectOption(options); + } + public override bool OnSelectYesNo(int desc) + { + if (desc == 1233663200) pre_activate_PrimevalPlanetPerlereino = true; + return base.OnSelectYesNo(desc); + } + public override void OnSelectChain(IList cards) + { + if (on_chaining_cards.Count <= 0 && cards.Count > 0) + { + on_chaining_cards = new List(cards); + } + base.OnSelectChain(cards); + } + public override void OnChaining(int player, ClientCard card) + { + if (!chainlist) + { + chainlist = true; + remainCards.Clear(); + fusionExtra = Bot.ExtraDeck.Where(fcard => fcard != null).ToList(); + fusionMaterial = GetZoneCards(CardLocation.MonsterZone, Bot).Where(mcard => mcard != null && mcard.IsFaceup()).ToList(); + fusionMaterial.AddRange(GetZoneCards(CardLocation.Hand | CardLocation.Grave, Bot)); + + } + base.OnChaining(player, card); + } + public override void OnChainEnd() + { + remainCards.Clear(); + fusionExtra.Clear(); + fusionMaterial.Clear(); + on_chaining_cards.Clear(); + tgcard = null; + no_fusion_card = null; + for (int i = 0; i < mcard_0.Count; ++i) mcard_0[i] = null; + for (int i = 0; i < mcard_1.Count; ++i) mcard_1[i] = null; + for (int i = 0; i < mcard_2.Count; ++i) mcard_2[i] = null; + for (int i = 0; i < mcard_3.Count; ++i) mcard_3[i] = null; + for (int i = 0; i < ran_fusion_mode_0.Count; ++i) ran_fusion_mode_0[i] = false; + for (int i = 0; i < ran_fusion_mode_1.Count; ++i) ran_fusion_mode_1[i] = false; + for (int i = 0; i < ran_fusion_mode_2.Count; ++i) ran_fusion_mode_2[i] = false; + chainlist = false; + base.OnChainEnd(); + } + private bool IsAvailableZone(int seq) + { + ClientCard card = Bot.MonsterZone[seq]; + if (seq == 5 || seq == 6) + { + ClientCard card1 = Bot.MonsterZone[5]; + ClientCard card2 = Bot.MonsterZone[6]; + if (card1 != null && card1.Controller == 0 && no_link_ids.Contains(card1.Id)) return false; + if (card2 != null && card2.Controller == 0 && no_link_ids.Contains(card2.Id)) return false; + } + if (card == null) return true; + if (card.Controller != 0) return false; + if (card.IsFacedown()) return false; + if (card.IsDisabled()) return true; + if (card.Id == CardId.SprightElf && summon_SprightElf) return false; + if (no_link_ids.Contains(card.Id)) return false; + return true; + } + private bool IsAvailableLinkZone() + { + int zones = 0; + List cards = Bot.GetMonstersInMainZone().Where(card => card != null && card.IsFaceup()).ToList(); + foreach (var card in cards) + { + zones |= card.GetLinkedZones(); + } + ClientCard e_card = Bot.MonsterZone[5]; + if (e_card != null && e_card.IsFaceup() && e_card.HasType(CardType.Link)) + { + if (e_card.Controller == 0) + { + if (e_card.HasLinkMarker(CardLinkMarker.BottomLeft)) + zones |= 1 << 0; + if (e_card.HasLinkMarker(CardLinkMarker.Bottom)) + zones |= 1 << 1; + if (e_card.HasLinkMarker(CardLinkMarker.BottomRight)) + zones |= 1 << 2; + } + if (e_card.Controller == 1) + { + if (e_card.HasLinkMarker(CardLinkMarker.TopLeft)) + zones |= 1 << 2; + if (e_card.HasLinkMarker(CardLinkMarker.Top)) + zones |= 1 << 1; + if (e_card.HasLinkMarker(CardLinkMarker.TopRight)) + zones |= 1 << 0; + } + } + e_card = Bot.MonsterZone[6]; + if (e_card != null && e_card.IsFaceup() && e_card.HasType(CardType.Link)) + { + if (e_card.Controller == 0) + { + if (e_card.HasLinkMarker(CardLinkMarker.BottomLeft)) + zones |= 1 << 2; + if (e_card.HasLinkMarker(CardLinkMarker.Bottom)) + zones |= 1 << 3; + if (e_card.HasLinkMarker(CardLinkMarker.BottomRight)) + zones |= 1 << 4; + } + if (e_card.Controller == 1) + { + if (e_card.HasLinkMarker(CardLinkMarker.TopLeft)) + zones |= 1 << 4; + if (e_card.HasLinkMarker(CardLinkMarker.Top)) + zones |= 1 << 3; + if (e_card.HasLinkMarker(CardLinkMarker.TopRight)) + zones |= 1 << 2; + } + } + zones &= 0x7f; + link_card = null; + if ((zones & Zones.z0) > 0 && IsAvailableZone(0)) return GetZoneLinkCards(0); + if ((zones & Zones.z1) > 0 && IsAvailableZone(1)) return GetZoneLinkCards(1); + if ((zones & Zones.z2) > 0 && IsAvailableZone(2)) return GetZoneLinkCards(2); + if ((zones & Zones.z3) > 0 && IsAvailableZone(3)) return GetZoneLinkCards(3); + if ((zones & Zones.z4) > 0 && IsAvailableZone(4)) return GetZoneLinkCards(4); + if (IsAvailableZone(5)) return GetZoneLinkCards(5); + if (IsAvailableZone(6)) return GetZoneLinkCards(6); + return false; + } + private bool GetZoneLinkCards(int index) + { + if (index >= Bot.MonsterZone.Count()) index = 0; + link_card = Bot.MonsterZone[index]; + return true; + } + + private List GetDefaultMaterial(IList cards) + { + List first_cards = new List(); + List first_mzone_cards = new List(); + List grave_cards = new List(); + List mzone_cards = new List(); + List hand_cards = new List(); + List last_cards = new List(); + List last_cards_2 = new List(); + foreach (var card in Duel.CurrentChain) + { + if (card == null) continue; + if (((card.Id == CardId.TearlamentsScheiren && !HasInList(last_cards, CardId.TearlamentsScheiren)) + || (card.Id == CardId.TearlamentsMerrli && !HasInList(last_cards, CardId.TearlamentsMerrli)) + || (card.Id == CardId.TearlamentsHavnis && !HasInList(last_cards, CardId.TearlamentsHavnis)) + ) && cards.Contains(card)) + { + last_cards.Add(card); + } + + } + foreach (var card in remainCards) + { + if (card == null) continue; + if (!cards.Contains(card)) first_cards.Add(card); + } + foreach (var card in cards) + { + if (card == null || first_mzone_cards.Contains(card) || first_cards.Contains(card) || last_cards.Contains(card) || + grave_cards.Contains(card) || mzone_cards.Contains(card) || hand_cards.Contains(card)) continue; + if (card.Id == CardId.ElShaddollWinda && card.IsFaceup() && card.Location == CardLocation.MonsterZone && !card.IsDisabled()) first_cards.Add(card); + else if (card.Id != CardId.TearlamentsRulkallos && first_mzone_cards.Count() <= 0 && card.Location == CardLocation.MonsterZone && Bot.GetMonstersInMainZone().Count > 4) + { + first_mzone_cards.Add(card); + } + else if (card.Location == CardLocation.Grave) + { + if ((((card.Id == CardId.TearlamentsScheiren && !activate_TearlamentsScheiren_2) + || (card.Id == CardId.TearlamentsMerrli && !activate_TearlamentsMerrli_2) + || (card.Id == CardId.TearlamentsHavnis && !activate_TearlamentsHavnis_2)) + && last_cards.Count(mcard => mcard != null && mcard.Id == card.Id) <= 0 + && on_chaining_cards.Count(mcard => mcard != null && mcard.Id == card.Id) > 0) + || (on_chaining_cards.Count(ccard => ccard != null && ccard == card) > 0 && on_chaining_cards.Count(cccard => cccard != null && cccard.Id == card.Id) <= 1 + && last_cards.Count(mcard => mcard != null && mcard.Id == card.Id) <= 0 && Duel.CurrentChain.Count(cccard => cccard != null && cccard.Id == card.Id) > 0)|| (no_fusion_card!=null && no_fusion_card==card)) + { + last_cards.Add(card); + } + else grave_cards.Add(card); + + } + else if (card.Location == CardLocation.Hand) + { + if (card.Id == CardId.TearlamentsReinoheart) hand_cards.Insert(0, card); + else if (Duel.Player == 1 && card.Id == CardId.TearlamentsHavnis && !activate_TearlamentsHavnis_1) last_cards.Add(card); + else hand_cards.Add(card); + } + else if (card.Location == CardLocation.MonsterZone) + { + if (card.Id == CardId.TearlamentsKitkallos && card.IsDisabled()) last_cards.Add(card); + else if (card.Id == CardId.TearlamentsKitkallos) last_cards_2.Insert(0, card); + else if (card.Id == CardId.TearlamentsRulkallos + || card.Id == CardId.TearlamentsKaleidoHeart || card.Id == CardId.PredaplantDragostapelia || + (Duel.Player == 1 && card.Id == CardId.ElShaddollWinda)) last_cards_2.Add(card); + else mzone_cards.Add(card); + } + else mzone_cards.Add(card); + } + first_cards.AddRange(first_mzone_cards); + first_cards.AddRange(grave_cards); + first_cards.AddRange(hand_cards); + first_cards.AddRange(mzone_cards); + first_cards.AddRange(last_cards); + first_cards.AddRange(last_cards_2); + return first_cards; + } + public override IList OnSelectFusionMaterial(IList cards, int min, int max) + { + if (AI.HaveSelectedCards()) return null; + for (int i = 2; i >= 0; --i) + { + List keys = cards.Where(card => card != null && card.Location != CardLocation.MonsterZone && card.Id == CardId.TearlamentsReinoheart).ToList(); + if (ran_fusion_mode_1[i] || ran_fusion_mode_2[i] || ran_fusion_mode_3[i]) + { + if (ran_fusion_mode_1[i]) ran_fusion_mode_1[i] = false; + else if (ran_fusion_mode_2[i]) ran_fusion_mode_2[i] = false; + else if (ran_fusion_mode_3[i]) ran_fusion_mode_3[i] = false; + cards.ToList().Sort(CardContainer.CompareCardAttack); + return keys.Count > 0 ? Util.CheckSelectCount(keys, cards, min, max) : Util.CheckSelectCount(GetDefaultMaterial(cards), cards, min, max); + } + List res = null; + ClientCard mcard = mcard_1[i]; + if (mcard != null) + { + if (keys.Count() > 0) + { + mcard_1[i] = null; + return Util.CheckSelectCount(keys, cards, min, max); + } + mcard_1[i] = null; + List temp = new List(cards); + temp.Sort(CardContainer.CompareCardAttack); + res = GetDefaultMaterial(temp); + return Util.CheckSelectCount(res, cards, min, max); + } + mcard = mcard_2[i]; + if (mcard != null) + { + mcard_2[i] = null; + List temp = new List(cards); + temp.Sort(CardContainer.CompareCardAttack); + res = GetDefaultMaterial(temp); + return Util.CheckSelectCount(res, cards, min, max); + } + mcard = mcard_3[i]; + if (mcard != null) + { + mcard_3[i] = null; + List temp = new List(cards); + temp.Sort(CardContainer.CompareCardAttack); + res = GetDefaultMaterial(temp); + return Util.CheckSelectCount(res, cards, min, max); + } + } + return base.OnSelectFusionMaterial(cards, min, max); + } + private bool HasInList(IList cards, int id) + { + if (cards == null || cards.Count <= 0) return false; + return cards.Any(card => card != null && card.Id == id); + } + private bool IsCanSpSummon() + { + if ((Bot.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true) + || Enemy.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true)) && spsummoned) return false; + return true; + } + private void SetSpSummon() + { + if (Bot.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true) || + Enemy.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true)) spsummoned = true; + } + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if ((AI.HaveSelectedCards() && mcard_0.All(card => card == null) && ran_fusion_mode_0.All(flag => !flag)) + || (hint == HintMsg.FusionMaterial)) return null; + if (pre_activate_PrimevalPlanetPerlereino) + { + pre_activate_PrimevalPlanetPerlereino = false; + List ids = GetCardsIdSendToHand(); + return Util.CheckSelectCount(CardsIdToClientCards(ids, cards, false, true), cards, min, max); + + } + //!IS_YGOPRO && select_TearlamentsKitkallos && hint == HintMsg.AddToHand + if ((IS_YGOPRO && hint == HintMsg.OperateCard) || (!IS_YGOPRO && select_TearlamentsKitkallos && hint == HintMsg.AddToHand)) + { + if (!IS_YGOPRO) select_TearlamentsKitkallos = false; + IList ids = new List(); + IList res = new List(); + if (Duel.Player == 0) + { + if (!activate_TearlamentsScheiren_1 && !Bot.HasInHand(CardId.TearlamentsScheiren) && HasInList(cards, CardId.TearlamentsScheiren) && !AllActivated()) ids.Add(CardId.TearlamentsScheiren); + if (!activate_TearlamentsMerrli_1 && !Bot.HasInHand(CardId.TearlamentsMerrli) && HasInList(cards, CardId.TearlamentsMerrli) && !AllActivated()) ids.Add(CardId.TearlamentsMerrli); + if(!Bot.HasInHand(CardId.TearlamentsHavnis) && HasInList(cards, CardId.TearlamentsHavnis)) ids.Add(CardId.TearlamentsHavnis); + if (!activate_TearlamentsReinoheart_1 && !Bot.HasInHand(CardId.TearlamentsReinoheart) && HasInList(cards, CardId.TearlamentsReinoheart)) ids.Add(CardId.TearlamentsReinoheart); + if (ids.Count() <= 0 && !activate_TearlamentsKitkallos_2) + { + List should_spsummon_cards = GetZoneCards(CardLocation.Grave | CardLocation.Hand, Bot); + should_spsummon_cards = should_spsummon_cards.Where(card => card != null && card.HasSetcode(SETCODE) && card.HasType(CardType.Monster)).ToList(); + if (should_spsummon_cards.Count() <= 0) + { + if (HasInList(cards, CardId.TearlamentsScheiren)) ids.Add(CardId.TearlamentsScheiren); + if (HasInList(cards, CardId.TearlamentsMerrli)) ids.Add(CardId.TearlamentsMerrli); + if (HasInList(cards, CardId.TearlamentsReinoheart)) ids.Add(CardId.TearlamentsReinoheart); + if (HasInList(cards, CardId.TearlamentsHavnis)) ids.Add(CardId.TearlamentsHavnis); + } + } + if (HasInList(cards, CardId.TearlamentsScream) && !activate_TearlamentsScream_1) ids.Add(CardId.TearlamentsScream); + if (HasInList(cards, CardId.TearlamentsSulliek) && on_chaining_cards.Count(card => card != null && card.Id == CardId.TearlamentsScream) <= 0) ids.Add(CardId.TearlamentsSulliek); + if (HasInList(cards, CardId.PrimevalPlanetPerlereino) && !activate_PrimevalPlanetPerlereino_1) ids.Add(CardId.PrimevalPlanetPerlereino); + if (ids.Count > 0) + { + TearlamentsKitkallostohand = true; + } + else + { + if (IsShouldSummonFusion(SETCODE, (int)CardRace.Aqua)) + { + if (!activate_TearlamentsHavnis_2 && HasInList(cards, CardId.TearlamentsHavnis)) ids.Add(CardId.TearlamentsHavnis); + if (!activate_TearlamentsScheiren_2 && HasInList(cards, CardId.TearlamentsScheiren)) ids.Add(CardId.TearlamentsScheiren); + if (!activate_TearlamentsMerrli_2 && HasInList(cards, CardId.TearlamentsMerrli)) ids.Add(CardId.TearlamentsMerrli); + if (ids.Count > 0) TearlamentsKitkallostohand = false; + } + } + + } + else + { + if (IsShouldSummonFusion(SETCODE, (int)CardRace.Aqua, true)) + { + if (!activate_TearlamentsHavnis_2 && HasInList(cards, CardId.TearlamentsHavnis) && !Bot.HasInHand(CardId.TearlamentsHavnis)) ids.Add(CardId.TearlamentsHavnis); + if (!activate_TearlamentsScheiren_2 && HasInList(cards, CardId.TearlamentsScheiren) && !Bot.HasInHand(CardId.TearlamentsScheiren)) ids.Add(CardId.TearlamentsScheiren); + if (!activate_TearlamentsMerrli_2 && HasInList(cards, CardId.TearlamentsMerrli) && !Bot.HasInHand(CardId.TearlamentsMerrli)) ids.Add(CardId.TearlamentsMerrli); + if (!activate_TearlamentsHavnis_2 && HasInList(cards, CardId.TearlamentsHavnis) && !ids.Contains(CardId.TearlamentsHavnis)) ids.Add(CardId.TearlamentsHavnis); + if (!activate_TearlamentsScheiren_2 && HasInList(cards, CardId.TearlamentsScheiren) && !ids.Contains(CardId.TearlamentsScheiren)) ids.Add(CardId.TearlamentsScheiren); + if (!activate_TearlamentsMerrli_2 && HasInList(cards, CardId.TearlamentsMerrli) && !ids.Contains(CardId.TearlamentsMerrli)) ids.Add(CardId.TearlamentsMerrli); + } + if (ids.Count > 0) TearlamentsKitkallostohand = false; + else + { + if (!Bot.HasInHand(CardId.TearlamentsHavnis) && !activate_TearlamentsHavnis_1 && HasInList(cards, CardId.TearlamentsHavnis)) + { + ids.Add(CardId.TearlamentsHavnis); + TearlamentsKitkallostohand = true; + } + else if (!activate_TearlamentsReinoheart_2 && HasInList(cards, CardId.TearlamentsReinoheart) && Bot.Hand.Any(card => card != null && card.HasSetcode(SETCODE))) + { + ids.Add(CardId.TearlamentsReinoheart); + TearlamentsKitkallostohand = false; + } + else if (!activate_TearlamentsSulliek_2 && HasInList(cards, CardId.TearlamentsSulliek)) + { + ids.Add(CardId.TearlamentsSulliek); + TearlamentsKitkallostohand = false; + } + else + { + if (!Bot.HasInHand(CardId.PrimevalPlanetPerlereino) && HasInList(cards, CardId.PrimevalPlanetPerlereino)) ids.Add(CardId.PrimevalPlanetPerlereino); + if (!Bot.HasInHand(CardId.TearlamentsScheiren) && HasInList(cards, CardId.TearlamentsScheiren)) ids.Add(CardId.TearlamentsScheiren); + if (!Bot.HasInHand(CardId.TearlamentsMerrli) && HasInList(cards, CardId.TearlamentsMerrli)) ids.Add(CardId.TearlamentsMerrli); + if (!Bot.HasInHand(CardId.TearlamentsReinoheart) && HasInList(cards, CardId.TearlamentsReinoheart)) ids.Add(CardId.TearlamentsReinoheart); + if (!Bot.HasInHand(CardId.TearlamentsScream) && HasInList(cards, CardId.TearlamentsScream)) ids.Add(CardId.TearlamentsScream); + if (!Bot.HasInHand(CardId.TearlamentsSulliek) && HasInList(cards, CardId.TearlamentsSulliek)) ids.Add(CardId.TearlamentsSulliek); + TearlamentsKitkallostohand = true; + } + } + + } + res = CardsIdToClientCards(ids, cards, false); + if (res.Count <= 0 || (Bot.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true) && spsummoned)) TearlamentsKitkallostohand = true; + return res.Count > 0 ? Util.CheckSelectCount(res, cards, min, max) : null; + } + if (hint == HintMsg.Remove && cards.Any(card => card != null && ((card.HasAttribute(CardAttribute.Light) && card.HasRace(CardRace.Fairy)) || card.Controller == 1))) + { + IList res = CardsIdToClientCards(new List() { CardId.HeraldofGreenLight, CardId.HeraldofOrangeLight, CardId.DivineroftheHerald }, cards.Where(card => card != null && card.Location == CardLocation.Grave).ToList(), false); + List eres = cards.Where(card => card != null && card.Controller == 1 && !key_no_remove_ids.Contains(card.Id)).ToList(); + eres.Sort(CardContainer.CompareCardAttack); + eres.Reverse(); + int emax = eres.Count > max ? max : eres.Count <= 0 ? min : eres.Count; + int mmax = res.Count > max ? max : res.Count <= 0 ? min : res.Count; + return eres.Count > 0 ? Util.CheckSelectCount(eres, cards, emax, emax) : res.Count > 0 ? Util.CheckSelectCount(res, cards, mmax, mmax) : null; + } + if (hint == HintMsg.AddToHand && cards.Any(card => card != null && card.Location == CardLocation.Deck)) + { + List ids = new List() { CardId.HeraldofOrangeLight, CardId.HeraldofGreenLight, CardId.DivineroftheHerald }; + if (!Bot.HasInSpellZoneOrInGraveyard(CardId.DivineroftheHerald) && (Bot.HasInHand(CardId.HeraldofOrangeLight) || Bot.HasInHand(CardId.HeraldofGreenLight))) + { + ids.Clear(); + ids.AddRange(new List() { CardId.DivineroftheHerald, CardId.HeraldofOrangeLight, CardId.HeraldofGreenLight }); + } + ids.AddRange(GetCardsIdSendToHand().Distinct()); + IList res = CardsIdToClientCards(ids, cards, false); + return res.Count > 0 ? Util.CheckSelectCount(res, cards, max, max) : null; + } + if (hint == HintMsg.ToGrave && cards.Any(card => card != null && card.Location == CardLocation.MonsterZone) && min == 1 && max == 1) + { + List h_cards = new List(); + List m_cards = new List(); + List s_cards = new List(); + foreach (var card in cards) + { + if (card == null) continue; + if (card.Location == CardLocation.Hand) h_cards.Add(card); + else if (card.Location == CardLocation.SpellZone) s_cards.Add(card); + else m_cards.Add(card); + } + List mkeycards = new List(); + List hkeycards = new List(); + mkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsKitkallos).ToList(); + if (!activate_TearlamentsKitkallos_3 && mkeycards.Count > 0 && !AllActivated() && IsShouldSummonFusion(SETCODE, (int)CardRace.Aqua) + && ((CheckRemainInDeck(CardId.TearlamentsHavnis) > 0 && !activate_TearlamentsHavnis_2) + || (CheckRemainInDeck(CardId.TearlamentsMerrli) > 0 && !activate_TearlamentsMerrli_2) + || (CheckRemainInDeck(CardId.TearlamentsScheiren) > 0 && !activate_TearlamentsScheiren_2))) + return Util.CheckSelectCount(mkeycards, cards, min, max); + if (IsShouldSummonFusion()) + { + if (!activate_TearlamentsScheiren_2 && HasInList(cards, CardId.TearlamentsScheiren)) + { + hkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsScheiren && card.Location == CardLocation.Hand).ToList(); + mkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsScheiren && card.Location == CardLocation.MonsterZone).ToList(); + } + else if (!activate_TearlamentsHavnis_2 && HasInList(cards, CardId.TearlamentsHavnis)) + { + hkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsHavnis && card.Location == CardLocation.Hand).ToList(); + mkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsHavnis && card.Location == CardLocation.MonsterZone).ToList(); + } + else if (!activate_TearlamentsMerrli_2 && HasInList(cards, CardId.TearlamentsMerrli)) + { + hkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsMerrli && card.Location == CardLocation.Hand).ToList(); + mkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsMerrli && card.Location == CardLocation.MonsterZone).ToList(); + } + else if (!activate_TearlamentsReinoheart_2 && (HasinZoneKeyCard(CardLocation.Hand) || (Bot.Hand.Count(ccard => ccard != null && ccard.HasSetcode(SETCODE) && ccard != cards.Where(card => card != null && card.Location == CardLocation.Hand && card.Id == CardId.TearlamentsReinoheart).FirstOrDefault()) > 0 && HasinZoneKeyCard(CardLocation.Deck)))) + { + hkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsReinoheart && card.Location == CardLocation.Hand).ToList(); + mkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsReinoheart && card.Location == CardLocation.MonsterZone).ToList(); + } + if (mkeycards.Count > 0 || hkeycards.Count > 0) + { + if (Bot.GetMonstersInMainZone().Count < 5) + { + hkeycards.AddRange(mkeycards); + return Util.CheckSelectCount(hkeycards, cards, min, max); + } + else + { + mkeycards.AddRange(hkeycards); + return Util.CheckSelectCount(mkeycards, cards, min, max); + } + } + } + mkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart).ToList(); + if (!activate_TearlamentsKaleidoHeart_2 && IsCanSpSummon() && mkeycards.Count > 0) return Util.CheckSelectCount(mkeycards, cards, min, max); + mkeycards = cards.Where(card => card != null && card.Id == CardId.TearlamentsRulkallos).ToList(); + if (!activate_TearlamentsRulkallos_2 && IsCanSpSummon() && mkeycards.Count > 0) return Util.CheckSelectCount(mkeycards, cards, min, max); + s_cards.AddRange(h_cards); + m_cards.Sort(CardContainer.CompareCardAttack); + s_cards.AddRange(m_cards); + return Util.CheckSelectCount(s_cards, cards, min, max); + } + if (hint == HintMsg.ToGrave && cards.Any(card => card != null && card.Location == CardLocation.Hand) && min == 1 && max == 1) + { + IList ids = new List(); + if (!activate_AgidotheAncientSentinel_2) ids.Add(CardId.AgidotheAncientSentinel); + if (!activate_KelbektheAncientVanguard_2) ids.Add(CardId.KelbektheAncientVanguard); + if (IsShouldSummonFusion(SETCODE, (int)CardRace.Aqua)) + { + if (activate_TearlamentsScheiren_1 && !activate_TearlamentsScheiren_2) ids.Add(CardId.TearlamentsScheiren); + if (summoned && !activate_TearlamentsMerrli_2) ids.Add(CardId.TearlamentsMerrli); + if (!activate_TearlamentsHavnis_2) ids.Add(CardId.TearlamentsHavnis); + if (!activate_TearlamentsMerrli_2) ids.Add(CardId.TearlamentsMerrli); + if (!activate_TearlamentsScheiren_2) ids.Add(CardId.TearlamentsScheiren); + } + if (Enemy.GetSpellCount() > 0) ids.Add(CardId.ShaddollDragon); + if (Bot.Deck.Count > 0) ids.Add(CardId.ShaddollBeast); + if (Enemy.Graveyard.Count > 0) ids.Add(CardId.NaelshaddollAriel); + if (!activate_Eva && Bot.Graveyard.Count(card => card != null && card.HasAttribute(CardAttribute.Light) && card.HasRace(CardRace.Fairy)) > 0 + && (CheckRemainInDeck(CardId.HeraldofGreenLight) > 0 || CheckRemainInDeck(CardId.HeraldofOrangeLight) > 0)) ids.Add(CardId.Eva); + if (((Bot.HasInHand(CardId.HeraldofOrangeLight) || Bot.HasInHand(CardId.HeraldofGreenLight)) + && Bot.Hand.Count(card => card != null && card.HasRace(CardRace.Fairy)) > 2) + || (!Bot.HasInHand(CardId.HeraldofOrangeLight) && !Bot.HasInHand(CardId.HeraldofGreenLight))) + { + ids.Add(CardId.MudoratheSwordOracle); + ids.Add(CardId.KeldotheSacredProtector); + } + if (!activate_TearlamentsScream_2 && CheckRemainInDeck(CardId.TearlamentsSulliek) > 0) ids.Add(CardId.TearlamentsScream); + if (!activate_TearlamentsSulliek_2) ids.Add(CardId.TearlamentsSulliek); + if (!activate_TearlamentsReinoheart_2 && HasInList(cards, CardId.TearlamentsReinoheart)) ids.Add(CardId.TearlamentsReinoheart); + if (!cards.Any(card => card != null && !card.HasRace(CardRace.Fairy))) + { + ids.Add(CardId.HeraldofGreenLight); + ids.Add(CardId.HeraldofOrangeLight); + } + ids = ids.Distinct().ToList(); + IList res = CardsIdToClientCards(ids, cards, false); + List temp = new List(cards); + foreach (var card in cards) + { + if (temp.Count <= 1) break; + if ((!summoned && card.Id == CardId.DivineroftheHerald) + || card.Id == CardId.HeraldofOrangeLight || card.Id == CardId.HeraldofGreenLight + || (!summoned && card.Id == CardId.TearlamentsMerrli && !activate_TearlamentsHavnis_1)) + { + temp.Remove(card); + } + } + temp.Sort(CardContainer.CompareCardAttack); + return res.Count > 0 ? Util.CheckSelectCount(res, cards, min, max) : Util.CheckSelectCount(temp, cards, min, max); + + } + if (hint == HintMsg.ToGrave && cards.Any(card => card != null && (card.Location == CardLocation.Deck || card.Location == CardLocation.Extra)) && min == 1 && max == 1) + { + List cardsid = new List(); + if (HasInList(cards, CardId.AgidotheAncientSentinel) && !activate_AgidotheAncientSentinel_2 && !AllActivated()) + { + if (HasInList(cards, CardId.KelbektheAncientVanguard) && !activate_KelbektheAncientVanguard_2 && Bot.HasInHand(CardId.AgidotheAncientSentinel)) + { + cardsid.Add(CardId.KelbektheAncientVanguard); + } + else cardsid.Add(CardId.AgidotheAncientSentinel); + } + else if (HasInList(cards, CardId.KelbektheAncientVanguard) && !activate_KelbektheAncientVanguard_2 && !AllActivated()) + { + cardsid.Add(CardId.KelbektheAncientVanguard); + } + else if (HasInList(cards, CardId.ElderEntityNtss) && GetZoneCards(CardLocation.Onfield, Enemy).Count(card => card != null && !card.IsShouldNotBeTarget()) > 0) + { + cardsid.Add(CardId.ElderEntityNtss); + } + if (HasInList(cards, CardId.Eva) && !activate_Eva && + (CheckRemainInDeck(CardId.HeraldofOrangeLight) > 0 || CheckRemainInDeck(CardId.HeraldofGreenLight) > 0)) + cardsid.Add(CardId.Eva); + if (HasInList(cards, CardId.MudoratheSwordOracle)) cardsid.Add(CardId.MudoratheSwordOracle); + if (HasInList(cards, CardId.KeldotheSacredProtector)) cardsid.Add(CardId.KeldotheSacredProtector); + if (IsShouldSummonFusion()) + { + if (cards.Any(card => card != null && card.Id == CardId.TearlamentsHavnis) && !activate_TearlamentsHavnis_2) cardsid.Add(CardId.TearlamentsHavnis); + if (cards.Any(card => card != null && card.Id == CardId.TearlamentsMerrli) && !activate_TearlamentsMerrli_2) cardsid.Add(CardId.TearlamentsMerrli); + if (cards.Any(card => card != null && card.Id == CardId.TearlamentsScheiren) && !activate_TearlamentsScheiren_2) cardsid.Add(CardId.TearlamentsScheiren); + } + if (cards.Any(card => card != null && card.Id == CardId.TearlamentsSulliek) && !activate_TearlamentsSulliek_2) cardsid.Add(CardId.TearlamentsSulliek); + if (cards.Any(card => card != null && card.Id == CardId.TearlamentsScream) && !activate_TearlamentsScream_2 && CheckRemainInDeck(CardId.TearlamentsSulliek) > 0) cardsid.Add(CardId.TearlamentsScream); + IList res = CardsIdToClientCards(cardsid, cards, false); + if (res.Count > 0) no_fusion_card = res[0]; + return res.Count > 0 ? Util.CheckSelectCount(res, cards, min, max) : null; + } + if (hint == HintMsg.ToDeck && cards.Any(card => card != null && card.Location == CardLocation.Grave)) + { + List b_cards = new List(); + List e_cards = new List(); + List e_temp_1 = new List(); + List e_temp_2 = new List(); + List e_temp_3 = new List(); + List e_temp_4 = new List(); + foreach (var card in cards) + { + if (card == null) continue; + if (card.Controller == 0) b_cards.Add(card); + else e_cards.Add(card); + } + if (e_cards.Count <= 0 && Bot.Deck.Count > 2) + { + return null; + } + int imax = e_cards.Count > max ? max : e_cards.Count < 0 ? min : e_cards.Count; + if (Duel.CurrentChain == null || Duel.ChainTargets == null) return Util.CheckSelectCount(cards, cards, imax, imax); + foreach (var card in Duel.CurrentChain) + { + if (card == null || card.Controller == 0 || card.Location != CardLocation.Grave) continue; + if (cards.Contains(card)) + { + if (key_no_send_to_deck_ids.Contains(card.Id)) continue; + else if (key_send_to_deck_ids.Contains(card.Id) && !e_temp_1.Contains(card)) e_temp_1.Add(card); + else if (!e_temp_2.Contains(card)) e_temp_2.Add(card); + } + } + foreach (var card in Duel.ChainTargets) + { + if (card == null || card.Controller == 0 || card.Location != CardLocation.Grave) continue; + if (cards.Contains(card)) + { + if (key_no_send_to_deck_ids.Contains(card.Id)) continue; + else if (key_send_to_deck_ids.Contains(card.Id) && !e_temp_1.Contains(card)) e_temp_1.Add(card); + else if (!e_temp_2.Contains(card)) e_temp_2.Add(card); + } + } + foreach (var card in cards) + { + if (card == null || card.Controller == 0 || card.Location != CardLocation.Grave) continue; + if (key_send_to_deck_ids.Contains(card.Id) && !e_temp_1.Contains(card) && !e_temp_2.Contains(card)) e_temp_2.Add(card); + } + if (Bot.Deck.Count <= 0 && Duel.CurrentChain.Any(card => card != null && card.Controller == 0 && card.Id == CardId.ShaddollBeast)) + { + bot_send_to_deck_ids = new List { CardId.TearlamentsScheiren, CardId.TearlamentsMerrli, CardId.TearlamentsHavnis }; + IList temp = CardsIdToClientCards(bot_send_to_deck_ids, b_cards); + if (temp.Count <= 0) + { + for (int i = 0; i < b_cards.Count; i++) + { + if (i >= 2) break; + if (b_cards[i] == null || e_temp_1.Contains(b_cards[i])) continue; + e_temp_1.Insert(0, b_cards[i]); + } + } + else + { + for (int i = 0; i < temp.Count; i++) + { + if (i >= 2) break; + if (temp[i] == null || e_temp_1.Contains(temp[i])) continue; + e_temp_1.Insert(0, temp[i]); + } + } + } + if (Bot.Deck.Count < 3) + { + bot_send_to_deck_ids = new List(); + IList temp = new List(); + if (b_cards.Count > 0 && Bot.ExtraDeck.Any(card => card != null && card.HasType(CardType.Fusion) && card.Id != CardId.ElderEntityNtss)) + { + if (CheckRemainInDeck(CardId.TearlamentsScheiren) <= 0 && HasInList(cards, CardId.TearlamentsScheiren)) bot_send_to_deck_ids.Add(CardId.TearlamentsScheiren); + if (CheckRemainInDeck(CardId.TearlamentsMerrli) <= 0 && HasInList(cards, CardId.TearlamentsMerrli)) bot_send_to_deck_ids.Add(CardId.TearlamentsMerrli); + if (CheckRemainInDeck(CardId.TearlamentsHavnis) <= 0 && HasInList(cards, CardId.TearlamentsHavnis)) bot_send_to_deck_ids.Add(CardId.TearlamentsHavnis); + } + temp = CardsIdToClientCards(bot_send_to_deck_ids, b_cards); + if (temp.Count > 0) + { + for (int i = 0; i < temp.Count; i++) + { + if (temp[i] == null || e_temp_4.Contains(temp[i]) || e_temp_1.Contains(temp[i]) + || e_temp_2.Contains(temp[i])) continue; + e_temp_4.Add(temp[i]); + } + } + bot_send_to_deck_ids.Clear(); + if (HasInList(cards, CardId.NaelshaddollAriel)) bot_send_to_deck_ids.Add(CardId.NaelshaddollAriel); + if (CheckRemainInDeck(CardId.KelbektheAncientVanguard) <= 0 && HasInList(cards, CardId.KelbektheAncientVanguard)) bot_send_to_deck_ids.Add(CardId.KelbektheAncientVanguard); + if (CheckRemainInDeck(CardId.AgidotheAncientSentinel) <= 0 && HasInList(cards, CardId.AgidotheAncientSentinel)) bot_send_to_deck_ids.Add(CardId.AgidotheAncientSentinel); + if (CheckRemainInDeck(CardId.HeraldofOrangeLight) <= 0 && HasInList(cards, CardId.HeraldofOrangeLight)) bot_send_to_deck_ids.Add(CardId.HeraldofOrangeLight); + if (CheckRemainInDeck(CardId.HeraldofGreenLight) <= 0 && HasInList(cards, CardId.HeraldofGreenLight)) bot_send_to_deck_ids.Add(CardId.HeraldofGreenLight); + temp = CardsIdToClientCards(bot_send_to_deck_ids, b_cards); + if (temp.Count > 0) + { + for (int i = 0; i < temp.Count; i++) + { + if (temp[i] == null || e_temp_4.Contains(temp[i]) || e_temp_1.Contains(temp[i]) + || e_temp_2.Contains(temp[i])) continue; + e_temp_4.Add(temp[i]); + } + } + foreach (var card in b_cards) + { + if (card == null || e_temp_4.Contains(card) || e_temp_1.Contains(card) + || e_temp_2.Contains(card)) continue; + e_temp_4.Add(card); + } + } + e_temp_3 = e_cards.Where(card => card != null && !e_temp_1.Contains(card) && !e_temp_2.Contains(card) && !e_temp_4.Contains(card)).ToList(); + e_temp_1.AddRange(e_temp_2); + e_temp_1.AddRange(e_temp_4); + e_temp_1.AddRange(e_temp_3); + imax = e_temp_1.Count > max ? max : e_temp_1.Count < 0 ? min : e_temp_1.Count; + return e_temp_1.Count > 0 ? Util.CheckSelectCount(e_temp_1, cards, imax, imax) : Util.CheckSelectCount(e_cards, cards, max, max); + + } + if (hint == HintMsg.SpSummon && cards.Any(card => card != null && (card.Level == 2 || card.LinkCount == 2) && card.Location == CardLocation.Grave)) + { + IList res = new List(); + List ids = new List(); + if (Duel.Player == 0) + { + if (HasInList(cards, CardId.TearlamentsMerrli) && !activate_TearlamentsMerrli_1 && IsCanFusionSummon()) + { + ids.Add(CardId.TearlamentsMerrli); + } + else if (HasInList(cards, CardId.DivineroftheHerald) && !activate_DivineroftheHerald) + { + ids.Add(CardId.DivineroftheHerald); + } + else if (HasInList(cards, CardId.TearlamentsMerrli) && !activate_TearlamentsMerrli_1) + { + ids.Add(CardId.TearlamentsMerrli); + } + else if (HasInList(cards, CardId.IP) && Bot.ExtraDeck.Count(card => card != null && card.LinkCount > 2) > 0) + { + ids.Add(CardId.IP); + } + else + { + ids = new List() { CardId.DivineroftheHerald, CardId.TearlamentsMerrli, CardId.HeraldofOrangeLight, CardId.HeraldofGreenLight }; + } + } + else + { + if (HasInList(cards, CardId.DivineroftheHerald) && !activate_DivineroftheHerald && FusionDeckCheck() + && ((CheckRemainInDeck(CardId.AgidotheAncientSentinel) > 0 && !activate_AgidotheAncientSentinel_2) + || (CheckRemainInDeck(CardId.KelbektheAncientVanguard) > 0 && !activate_KelbektheAncientVanguard_2))) + { + ids.Add(CardId.DivineroftheHerald); + } + if (HasInList(cards, CardId.TearlamentsMerrli) && !activate_TearlamentsMerrli_1 && + IsShouldSummonFusion(-1, -1, true) && FusionDeckCheck()) + { + ids.Add(CardId.TearlamentsMerrli); + } + else if (HasInList(cards, CardId.DivineroftheHerald) && Bot.HasInExtra(CardId.ElderEntityNtss) && GetZoneCards(CardLocation.Onfield, Enemy).Any(card => card != null && !card.IsShouldNotBeTarget())) + { + ids.Add(CardId.DivineroftheHerald); + } + else if (HasInList(cards, CardId.IP) && Bot.ExtraDeck.Any(card => card != null && card.LinkCount > 2)) + { + ids.Add(CardId.IP); + } + else + { + ids = new List() { CardId.DivineroftheHerald, CardId.TearlamentsMerrli, CardId.HeraldofOrangeLight, CardId.HeraldofGreenLight }; + } + } + res = CardsIdToClientCards(ids, cards, false); + return res.Count > 0 ? Util.CheckSelectCount(res, cards, min, max) : null; + } + //(IS_YGOPRO && hint == HintMsg.Disable) || (!IS_YGOPRO && hint == HintMsg.Negate) + if (IS_YGOPRO && hint == HintMsg.Disable) + { + if (chain_TearlamentsSulliek != null && cards.Contains(chain_TearlamentsSulliek)) + { + List res = new List() { chain_TearlamentsSulliek }; + return Util.CheckSelectCount(res, cards, min, max); + } + return null; + } + if (hint == HintMsg.Faceup && cards.Any(card => card != null && card.Controller == 1)) + { + if (chain_PredaplantDragostapelia != null && cards.Contains(chain_PredaplantDragostapelia)) + { + List res = new List() { chain_PredaplantDragostapelia }; + e_PredaplantDragostapelia_cards.Add(chain_PredaplantDragostapelia); + return Util.CheckSelectCount(res, cards, min, max); + } + return null; + } + for (int i = 2; i >= 0; --i) + { + if (ran_fusion_mode_0[i]) + { + ran_fusion_mode_0[i] = false; + if (Duel.Player == 0) + { + List res0 = cards.Where(card => card != null && card.Id == CardId.PredaplantDragostapelia).ToList(); + if (res0.Count > 0 && Bot.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true)) + { + return Util.CheckSelectCount(res0, cards, min, max); + } + res0 = cards.Where(card => card != null && card.Id == CardId.TearlamentsKitkallos).ToList(); + if (res0.Count > 0 && ((!activate_TearlamentsKitkallos_1 && + ((!activate_TearlamentsScheiren_2 && CheckRemainInDeck(CardId.TearlamentsScheiren) > 0) + || (!activate_TearlamentsHavnis_2 && CheckRemainInDeck(CardId.TearlamentsHavnis) > 0) + || (!activate_TearlamentsMerrli_2 && CheckRemainInDeck(CardId.TearlamentsMerrli) > 0))) || !activate_TearlamentsKitkallos_2)) + { + TearlamentsKitkallos_summoned = true; + return Util.CheckSelectCount(res0, cards, min, max); + } + res0 = cards.Where(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart).ToList(); + //if (GetZoneCards(CardLocation.Onfield, Enemy).Count(card => card != null && !card.IsShouldNotBeTarget()) > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.TearlamentsKaleidoHeart) + // && !activate_TearlamentsKaleidoHeart_1 && (!Bot.HasInSpellZone(CardId.PrimevalPlanetPerlereino, true, true) || (Bot.HasInSpellZone(CardId.PrimevalPlanetPerlereino, true, true) && activate_PrimevalPlanetPerlereino_2))) + if(res0.Count>0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.TearlamentsKaleidoHeart)) + { + ran_fusion_mode_3[i] = true; + return Util.CheckSelectCount(res0, cards, min, max); + } + res0 = cards.Where(card => card != null && card.Id == CardId.TearlamentsRulkallos).ToList(); + if (Bot.Graveyard.Count(card => card != null && card.Id == CardId.TearlamentsKitkallos) > 0 || + Bot.MonsterZone.Count(card => card != null && card.Id == CardId.TearlamentsKitkallos && card.IsFaceup()) > 0 && res0.Count > 0) + { + activate_TearlamentsRulkallos_2 = false; + return Util.CheckSelectCount(res0, cards, min, max); + } + res0 = cards.Where(card => card != null && card.Id == CardId.PredaplantDragostapelia).ToList(); + //if (res0.Count > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.PredaplantDragostapelia) && Enemy.GetMonsters().Any(card => card != null && card.HasType(CardType.Effect) && !card.IsDisabled() && card.IsFaceup() && !card.IsShouldNotBeTarget())) + if (res0.Count > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.PredaplantDragostapelia)) + { + return Util.CheckSelectCount(res0, cards, min, max); + } + List res1 = cards.Where(card => card != null && card.Id == CardId.TearlamentsKitkallos).ToList(); + if (res1.Count > 0) + { + List material = GetDefaultMaterial(fusionMaterial); + if (((material.Count(mcard => mcard != null && mcard.Id == CardId.TearlamentsKitkallos && mcard.Location == CardLocation.MonsterZone) > 0 && + activate_TearlamentsKitkallos_1) || (material.Count(mcard => mcard != null && mcard.Id == CardId.TearlamentsKitkallos && mcard.Location == CardLocation.MonsterZone) > 1)) && + material.Count <= 2) + { + if (res0.Count > 0) + { + activate_TearlamentsRulkallos_2 = false; + return Util.CheckSelectCount(res0, cards, min, max); + } + TearlamentsKitkallos_summoned = true; + return Util.CheckSelectCount(res1, cards, min, max); + } + return Util.CheckSelectCount(res1, cards, min, max); + } + + } + else + { + List res = cards.Where(card => card != null && card.Id == CardId.TearlamentsKitkallos).ToList(); + if (res.Count > 0 && !activate_TearlamentsKitkallos_1 && + ((!activate_TearlamentsScheiren_2 && CheckRemainInDeck(CardId.TearlamentsScheiren) > 0) + || (!activate_TearlamentsHavnis_2 && CheckRemainInDeck(CardId.TearlamentsHavnis) > 0) + || (!activate_TearlamentsMerrli_2 && CheckRemainInDeck(CardId.TearlamentsMerrli) > 0)) && Bot.GetMonstersInMainZone().Count < 4) + { + TearlamentsKitkallos_summoned = true; + return Util.CheckSelectCount(res, cards, min, max); + } + res = cards.Where(card => card != null && card.Id == CardId.TearlamentsRulkallos).ToList(); + if (res.Count > 0) return Util.CheckSelectCount(res, cards, min, max); + res = cards.Where(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart).ToList(); + if (res.Count>0 && GetZoneCards(CardLocation.Onfield, Enemy).Count(card => card != null && !card.IsShouldNotBeTarget()) > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.TearlamentsKaleidoHeart) + && !activate_TearlamentsKaleidoHeart_1 && (!Bot.HasInSpellZone(CardId.PrimevalPlanetPerlereino, true, true) || (Bot.HasInSpellZone(CardId.PrimevalPlanetPerlereino, true, true) && activate_PrimevalPlanetPerlereino_2))) + { + ran_fusion_mode_3[i] = true; + return Util.CheckSelectCount(res, cards, min, max); + } + res = cards.Where(card => card != null && card.Id == CardId.ElShaddollWinda).ToList(); + if (res.Count > 0) return Util.CheckSelectCount(res, cards, min, max); + res = cards.Where(card => card != null && card.Id == CardId.PredaplantDragostapelia).ToList(); + if (res.Count > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.PredaplantDragostapelia)) + { + return Util.CheckSelectCount(res, cards, min, max); + } + res = cards.Where(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart).ToList(); + if (res.Count > 0 && IsShouldSummonFusion(-1, -1, false, (int)Flag.TearlamentsKaleidoHeart)) + { + return Util.CheckSelectCount(res, cards, min, max); + } + res = cards.Where(card => card != null && card.Id == CardId.TearlamentsKitkallos).ToList(); + if (res.Count > 0) + { + TearlamentsKitkallos_summoned = true; + return Util.CheckSelectCount(res, cards, min, max); + } + return null; + } + } + if (mcard_0[i] == null) continue; + if (cards.Contains(mcard_0[i])) + { + List res = new List() { mcard_0[i] }; + mcard_0[i] = null; + return Util.CheckSelectCount(res, cards, min, max); + } + else + { + return null; + } + } + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + private bool IsCanFusionSummon() + { + if ((!activate_TearlamentsMerrli_2 && CheckRemainInDeck(CardId.TearlamentsMerrli) > 0) + || (!activate_TearlamentsHavnis_2 && CheckRemainInDeck(CardId.TearlamentsHavnis) > 0) + || (!activate_TearlamentsScheiren_2 && CheckRemainInDeck(CardId.TearlamentsScheiren) > 0)) + return Bot.ExtraDeck.Count(card => card != null && card.HasType(CardType.Fusion) && card.Id != CardId.ElderEntityNtss) > 0; + return false; + + } + private bool BaronnedeFleurSummon_2() + { + if (Duel.Turn > 1 && Duel.Phase < DuelPhase.Main2) return false; + List scards = Bot.GetMonsters().Where(card => card != null && card.Id == CardId.DivineroftheHerald && card.IsFaceup()).ToList(); + List mcards = Bot.GetMonsters().Where(card => card != null && !card.HasType(CardType.Tuner) && card.IsFaceup()).ToList(); + if (scards.Any(card => card != null && card.Level == 2) && mcards.Count(card => card != null && card.Level == 4) > 1) + { + List s = scards.Where(card => card != null && card.Level == 2 && card.Id == CardId.DivineroftheHerald && card.IsFaceup()).ToList(); + List res = new List() { s.FirstOrDefault() }; + res.AddRange(mcards.Where(card => card != null && card.Level == 4 && card.IsFaceup())); + AI.SelectMaterials(res); + SetSpSummon(); + return true; + } + return false; + } + private bool BaronnedeFleurSummon() + { + List scards = Bot.GetMonsters().Where(card => card != null && card.Id == CardId.DivineroftheHerald && card.IsFaceup()).ToList(); + List mcards = Bot.GetMonsters().Where(card => card != null && !card.HasType(CardType.Synchro) && card.IsFaceup()).ToList(); + if (scards.Any(card => card != null && card.Level == 2) && mcards.Any(card => card != null && card.Level == 8 && card.Id != CardId.TearlamentsRulkallos && card.Id != CardId.PredaplantDragostapelia)) { SetSpSummon(); return true; } + else if (scards.Any(card => card != null && card.Level == 5) && mcards.Any(card => card != null && card.Level == 5)) + { + List s = Bot.GetMonsters().Where(card => card != null && card.Level == 5 && card.Id == CardId.DivineroftheHerald && card.IsFaceup()).ToList(); + if (s.Count >= 0) + { + List res = new List() { s.FirstOrDefault() }; + res.AddRange(Bot.GetMonsters().Where(card => card != null && card.Level == 5 && card.Id == CardId.ElShaddollWinda && card.IsFaceup())); + res.AddRange(Bot.GetMonsters().Where(card => card != null && card.Level == 5 && card.IsFaceup())); + AI.SelectMaterials(res); + SetSpSummon(); + return true; + } + } + else if (scards.Any(card => card != null && card.Level == 6) && mcards.Any(card => card != null && card.Level == 4)) { SetSpSummon(); return true; } + return false; + + } + private bool SprightElfEffect() + { + ClientCard card = Util.GetLastChainCard(); + if (card != null && card.Controller == 0) return false; + SetSpSummon(); + return true; + } + private bool FusionDeckCheck() + { + return (CheckRemainInDeck(CardId.TearlamentsHavnis) > 0 && !activate_TearlamentsHavnis_2) + || (CheckRemainInDeck(CardId.TearlamentsMerrli) > 0 && !activate_TearlamentsMerrli_2) + || (CheckRemainInDeck(CardId.TearlamentsScheiren) > 0 && !activate_TearlamentsScheiren_2); + } + private List GetCardsIdSendToHand() + { + List ids = new List(); + if (!activate_TearlamentsScheiren_1 && !Bot.HasInHand(CardId.TearlamentsScheiren) && CheckRemainInDeck(CardId.TearlamentsScheiren) > 0 && Bot.Hand.Count(card => card != null && card.HasType(CardType.Monster)) > 0) ids.Add(CardId.TearlamentsScheiren); + if (!activate_TearlamentsMerrli_1 && !Bot.HasInHand(CardId.TearlamentsMerrli) && CheckRemainInDeck(CardId.TearlamentsMerrli) > 0 && (!summoned ||!activate_TearlamentsKitkallos_2) ) ids.Add(CardId.TearlamentsMerrli); + if (!activate_TearlamentsReinoheart_1 && !Bot.HasInHand(CardId.TearlamentsReinoheart) && CheckRemainInDeck(CardId.TearlamentsReinoheart) > 0) ids.Add(CardId.TearlamentsReinoheart); + if (!activate_TearlamentsScheiren_1 && !Bot.HasInHand(CardId.TearlamentsScheiren) && CheckRemainInDeck(CardId.TearlamentsScheiren) > 0) ids.Add(CardId.TearlamentsScheiren); + if (!activate_TearlamentsHavnis_1 && !Bot.HasInHand(CardId.TearlamentsHavnis) && CheckRemainInDeck(CardId.TearlamentsHavnis) > 0) + { + if (Duel.Player == 0 && (Duel.Phase != DuelPhase.End || AllActivated())) ids.Add(CardId.TearlamentsHavnis); + else ids.Insert(0, CardId.TearlamentsHavnis); + } + ids.AddRange(new List() { CardId.TearlamentsScheiren, CardId.TearlamentsMerrli, CardId.TearlamentsHavnis, CardId.TearlamentsReinoheart }); + return ids; + } + public int CheckRemainInDeck(int id) + { + switch (id) + { + case CardId.ShaddollBeast: + return Bot.GetRemainingCount(CardId.ShaddollBeast, 1); + case CardId.ShaddollDragon: + return Bot.GetRemainingCount(CardId.ShaddollDragon, 1); + case CardId.TearlamentsScheiren: + return Bot.GetRemainingCount(CardId.TearlamentsScheiren, 3); + case CardId.TearlamentsReinoheart: + return Bot.GetRemainingCount(CardId.TearlamentsReinoheart, 2); + case CardId.KelbektheAncientVanguard: + return Bot.GetRemainingCount(CardId.KelbektheAncientVanguard, 3); + case CardId.MudoratheSwordOracle: + return Bot.GetRemainingCount(CardId.MudoratheSwordOracle, 3); + case CardId.AgidotheAncientSentinel: + return Bot.GetRemainingCount(CardId.AgidotheAncientSentinel, 3); + case CardId.KeldotheSacredProtector: + return Bot.GetRemainingCount(CardId.KeldotheSacredProtector, 2); + case CardId.NaelshaddollAriel: + return Bot.GetRemainingCount(CardId.NaelshaddollAriel, 1); + case CardId.TearlamentsHavnis: + return Bot.GetRemainingCount(CardId.TearlamentsHavnis, 3); + case CardId.TearlamentsMerrli: + return Bot.GetRemainingCount(CardId.TearlamentsMerrli, 3); + case CardId.DivineroftheHerald: + return Bot.GetRemainingCount(CardId.DivineroftheHerald, 3); + case CardId.HeraldofOrangeLight: + return Bot.GetRemainingCount(CardId.HeraldofOrangeLight, 3); + case CardId.HeraldofGreenLight: + return Bot.GetRemainingCount(CardId.HeraldofGreenLight, 3); + case CardId.Eva: + return Bot.GetRemainingCount(CardId.Eva, 1); + case CardId.TearlamentsScream: + return Bot.GetRemainingCount(CardId.TearlamentsScream, 1); + case CardId.PrimevalPlanetPerlereino: + return Bot.GetRemainingCount(CardId.PrimevalPlanetPerlereino, 2); + case CardId.TearlamentsSulliek: + return Bot.GetRemainingCount(CardId.TearlamentsSulliek, 2); + default: + return 0; + } + } + private bool PredaplantDragostapeliaEffect() + { + ClientCard card = Util.GetLastChainCard(); + if (card != null && card.Controller != 0 && card.Location == CardLocation.MonsterZone && !card.IsShouldNotBeTarget() && !e_PredaplantDragostapelia_cards.Contains(card)) + { + chain_PredaplantDragostapelia = card; + return true; + } + return false; + } + private bool UnderworldGoddessoftheClosedWorldSummon_2() + { + return UnderworldGoddessoftheClosedWorldLinkSummon(false); + } + private bool UnderworldGoddessoftheClosedWorldLinkSummon(bool filter = true) + { + if (Duel.Turn == 1 || Enemy.GetMonsterCount() <= 0) return false; + List e_cards = Enemy.GetMonsters().Where(card => card != null && card.IsFaceup() && card.IsAttack()).ToList(); + List b_cards = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && card.IsAttack()).ToList(); + if (e_cards.Count <= 0 || b_cards.Count <= 0 || Enemy.MonsterZone.GetDangerousMonster() == null) return false; + e_cards.Sort(CardContainer.CompareCardAttack); + e_cards.Reverse(); + b_cards.Sort(CardContainer.CompareCardAttack); + b_cards.Reverse(); + if ((e_cards[0].Attack > b_cards[0].Attack && (e_cards[0].IsShouldNotBeTarget() || e_cards[0].Attack >= 2500)) || Enemy.MonsterZone.GetDangerousMonster() != null) + { + List e_materials = new List(); + List m_materials = new List(); + List resMaterials = new List(); + foreach (var card in Enemy.GetMonsters()) + { + if (card != null && card.HasType(CardType.Effect) && card.IsFaceup()) + e_materials.Add(card); + } + if (e_materials.Count() <= 0) return false; + List mcards = Bot.GetMonsters(); + mcards.Sort(CardContainer.CompareCardAttack); + foreach (var card in mcards) + { + if (card == null || card.IsFacedown()) continue; + if (card.Id == CardId.SprightElf && summon_SprightElf) continue; + if (card.LinkCount < 3 && !(no_link_ids.Contains(card.Id) & filter) && card.IsFaceup() && card.HasType(CardType.Effect)) + { + if (card.Id == CardId.ElShaddollWinda) m_materials.Insert(0, card); + else m_materials.Add(card); + } + } + if (m_materials.Count() < 3) return false; + int link_count = 0; + int e_link_count = 0; + e_materials.Sort(CardContainer.CompareCardAttack); + e_materials.Reverse(); + foreach (var card in e_materials) + { + if (!resMaterials.Contains(card)) + resMaterials.Add(card); + e_link_count += (card.HasType(CardType.Link)) ? (card.LinkCount == 2 ? 2 : 1) : 1; + if (e_link_count >= 1) break; + } + if (e_link_count <= 0) return false; + link_count += e_link_count; + foreach (var card in m_materials) + { + if (e_link_count <= 1) + { + if (!resMaterials.Contains(card) && card.LinkCount < 3) + { + resMaterials.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 5) break; + } + } + else + { + resMaterials.Add(card); + link_count += 1; + if (link_count >= 5) break; + } + } + if (link_count >= 5) { AI.SelectMaterials(resMaterials); SetSpSummon(); return true; } + } + return false; + } + private bool TearlamentsKaleidoHeartEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + activate_TearlamentsKaleidoHeart_1 = true; + return DestoryEnemyCard(); + } + else + { + activate_TearlamentsKaleidoHeart_2 = true; + return true; + } + } + private bool UnderworldGoddessoftheClosedWorldSummon() + { + if (Bot.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true)) + { + return UnderworldGoddessoftheClosedWorldLinkSummon(); + } + return false; + } + private bool UnderworldGoddessoftheClosedWorldSummon_3() + { + return UnderworldGoddessoftheClosedWorldLinkSummon(); + } + private bool SpellActivate() + { + return Card.Location == CardLocation.Hand || (Card.Location == CardLocation.SpellZone && Card.IsFacedown()); + } + private bool SprightElfSummon_2() + { + List key_cards = Bot.GetMonsters().Where(card => card != null && card.Id == CardId.ElShaddollWinda && !card.IsDisabled() && card.IsFaceup()).ToList(); + if (key_cards.Count <= 0 || key_cards.Count > 1 || !IsAvailableLinkZone()) return false; + List cards = Bot.GetMonsters().Where(card => card != null && card.Level == 2 && card.Id != CardId.ElShaddollWinda && card.IsFaceup()).ToList(); + if (cards.Count <= 0) return false; + cards.Sort(CardContainer.CompareCardAttack); + cards.Insert(0, key_cards[0]); + AI.SelectMaterials(cards); + SetSpSummon(); + return true; + } + private bool FADawnDragsterSummon() + { + List key_cards = Bot.GetMonsters().Where(card => card != null && card.Id == CardId.ElShaddollWinda && !card.IsDisabled() && card.IsFaceup()).ToList(); + if (key_cards.Count <= 0 || key_cards.Count > 1 ) return false; + SetSpSummon(); + IList cards = CardsIdToClientCards(new List() { CardId.DivineroftheHerald }, Bot.GetMonsters().Where(card => card != null && card.IsFaceup()).ToList()); + if (cards.Count > 0) key_cards.Insert(0, cards[0]); + AI.SelectMaterials(key_cards); + return true; + } + private bool IPSummon_2() + { + if ((Bot.GetMonsterCount() <= 2 && Bot.Hand.Count<=2 && !Bot.HasInHand(CardId.TearlamentsScheiren) && !activate_TearlamentsScheiren_1&& !Bot.HasInHand(CardId.TearlamentsMerrli) && !activate_TearlamentsMerrli_1 ) || AllActivated() ) return false; + List key_cards = Bot.GetMonsters().Where(card => card != null && card.Id == CardId.ElShaddollWinda && !card.IsDisabled() && card.IsFaceup()).ToList(); + if (key_cards.Count <= 0 || key_cards.Count > 1 || !IsAvailableLinkZone()) return false; + List cards = Bot.GetMonsters().Where(card => card != null && !card.HasType(CardType.Link) && !no_link_ids.Contains(card.Id) && card.IsFaceup()).ToList(); + cards.Sort(CardContainer.CompareCardAttack); + cards.Insert(0, key_cards[0]); + AI.SelectMaterials(cards); + SetSpSummon(); + return true; + } + private bool SprightElfSummon() + { + if (!IsAvailableLinkZone()) return false; + List cards = GetZoneCards(CardLocation.MonsterZone, Bot).Where(card=>card != null && card.IsFaceup()).ToList(); + cards.Sort(CardContainer.CompareCardAttack); + List materials1 = new List(); + List materials2 = new List(); + List materials3 = new List(); + List materials4 = new List(); + foreach (var card in cards) + { + if (card == null) continue; + if (card.Level == 2 && materials1.Count <= 0) materials1.Add(card); + else if(link_card != null && card == link_card) materials2.Insert(0, link_card); + else if (!card.IsDisabled() && no_link_ids.Contains(card.Id)) materials4.Add(card); + else + { + if(card.Level <= 2) materials2.Add(card); + else materials3.Add(card); + } + + } + if (materials1.Count <= 0 || materials2.Count + materials3.Count <= 0) return false; + materials3.Sort(CardContainer.CompareCardLevel); + materials3.Reverse(); + materials1.AddRange(materials2); + materials1.AddRange(materials3); + summon_SprightElf = true; + AI.SelectMaterials(materials1); + SetSpSummon(); + return true; + } + private bool AbyssDwellerSummon() + { + if (Duel.Turn > 1 && Duel.Phase < DuelPhase.Main2) return false; + SetSpSummon(); + return true; + } + private bool AbyssDwellerSummon_2() + { + if (Bot.GetMonsters().Any(card => card != null && card.IsFaceup() && (card.Id == CardId.TearlamentsRulkallos || card.Id == CardId.TearlamentsKaleidoHeart))) return true; + return false; + } + private bool IPEffect() + { + if (Duel.LastChainPlayer == 0) return false; + if (!Bot.HasInExtra(CardId.KnightmareUnicorn) && !Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax) && !Bot.HasInExtra(CardId.UnderworldGoddessoftheClosedWorld)) return false; + List m = new List(); + List pre_m = new List(); + if (Bot.HasInExtra(CardId.UnderworldGoddessoftheClosedWorld)) + { + List e_cards = Enemy.GetMonsters().Where(card => card != null && card.IsFaceup() && card.IsAttack()).ToList(); + List b_cards = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && card.IsAttack()).ToList(); + if (e_cards.Count > 0 && b_cards.Count > 0) + { + e_cards.Sort(CardContainer.CompareCardAttack); + e_cards.Reverse(); + b_cards.Sort(CardContainer.CompareCardAttack); + b_cards.Reverse(); + if ((e_cards[0].Attack > b_cards[0].Attack && (e_cards[0].IsShouldNotBeTarget() || e_cards[0].Attack >= 2500)) || Enemy.MonsterZone.GetDangerousMonster() != null) + { + pre_m = Bot.GetMonsters().Where(card => card != null && card != Card && card.IsFaceup() && ((card.HasType(CardType.Link) && card.LinkCount < 3) || (card.HasType(CardType.Fusion | CardType.Xyz | CardType.Synchro))) && (!no_link_ids.Contains(card.Id) || card.IsDisabled())).ToList(); + List pre_m2 = new List(); + pre_m2.Add(Enemy.MonsterZone.GetDangerousMonster() == null ? e_cards[0] : Enemy.MonsterZone.GetDangerousMonster()); + pre_m2.AddRange(e_cards); + int link_count = 0; + foreach (var card in pre_m) + { + if (card == null || (card.Id == CardId.SprightElf && summon_SprightElf)) continue; + link_count += 1; + m.Add(card); + if (link_count >= 2) break; + } + if (link_count >= 2) + { + AI.SelectCard(CardId.UnderworldGoddessoftheClosedWorld); + m.Insert(0, Card); + m.Add(pre_m2.FirstOrDefault()); + AI.SelectMaterials(m); + return true; + } + } + } + } + if (Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax)) + { + m.Clear(); + pre_m = Bot.GetMonsters().Where(card => card != null && card != Card && card.IsFaceup() && ((card.HasType(CardType.Link) && card.LinkCount < 3) || (card.HasType(CardType.Fusion|CardType.Xyz|CardType.Synchro))) && (!no_link_ids.Contains(card.Id) || card.IsDisabled())).ToList(); + if (pre_m.Count > 0) + { + pre_m.Sort(CardContainer.CompareCardAttack); + int link_count = 0; + foreach (var card in pre_m) + { + if (card == null || (card.Id == CardId.SprightElf && summon_SprightElf)) continue; + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + m.Add(card); + if (link_count >= 2) break; + } + if (link_count >= 2) + { + AI.SelectCard(CardId.MekkKnightCrusadiaAvramax); + m.Insert(0, Card); + AI.SelectMaterials(m); + return true; + } + } + } + if (Bot.HasInExtra(CardId.KnightmareUnicorn)) + { + List pre_cards = GetZoneCards(CardLocation.Onfield,Enemy); + if (Bot.Hand.Count > 0 && pre_cards.Count(card => card != null && !card.IsShouldNotBeTarget()) > 0) + { + m.Clear(); + pre_m = Bot.GetMonsters().Where(card => card != null && card != Card && card.IsFaceup() && !no_link_ids.Contains(card.Id) && card.Id != Card.Id).ToList(); + if (pre_m.Count > 0) + { + pre_m.Sort(CardContainer.CompareCardAttack); + int link_count = 0; + foreach (var card in pre_m) + { + if (card == null || (card.Id == CardId.SprightElf && summon_SprightElf)) continue; + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + m.Add(card); + if (link_count >= 1) break; + } + if (link_count >= 1) + { + AI.SelectCard(CardId.KnightmareUnicorn); + m.Insert(0, Card); + AI.SelectMaterials(m); + return true; + } + } + } + } + return false; + } + private bool IPSummon() + { + if (Duel.Turn > 1 && Duel.Phase < DuelPhase.Main2) return false; + if (!Bot.HasInMonstersZone(CardId.SprightElf) || Bot.GetMonsterCount() <= 2) return false; + if (Bot.ExtraDeck.Count(card => card != null && card.LinkCount > 2) <= 0 || !IsAvailableLinkZone()) return false; + List cards = GetZoneCards(CardLocation.MonsterZone, Bot).Where(card => card != null && card.IsFaceup() && !card.HasType(CardType.Link)).ToList(); + List materials = new List(); + foreach (var card in cards) + { + if (card == null || (!card.IsDisabled() && no_link_ids.Contains(card.Id)) + || card.LinkCount >= 2) continue; + if (link_card != null && card == link_card) materials.Insert(0, link_card); + else materials.Add(card); + } + if (materials.Count <= 1) return false; + materials.Sort(CardContainer.CompareCardAttack); + AI.SelectMaterials(materials); + SetSpSummon(); + return true; + } + private bool KnightmareUnicornEffect() + { + List cards = GetZoneCards(CardLocation.Onfield,Enemy); + cards = cards.Where(card => card != null && !card.IsShouldNotBeTarget() && (tgcard == null || card != tgcard)).ToList(); + if (cards.Count <= 0) return false; + List ids = new List(); + if (!activate_KelbektheAncientVanguard_2) ids.Add(CardId.KelbektheAncientVanguard); + if (!activate_AgidotheAncientSentinel_2) ids.Add(CardId.AgidotheAncientSentinel); + ids.AddRange(new List() { CardId.MudoratheSwordOracle, CardId.KeldotheSacredProtector, CardId.ShaddollBeast, CardId.ShaddollDragon, CardId.TearlamentsSulliek, CardId.Eva, CardId.TearlamentsReinoheart }); + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + AI.SelectCard(ids); + AI.SelectNextCard(cards); + return true; + + } + private bool MekkKnightCrusadiaAvramaxSummon() + { + if (!IsAvailableLinkZone() || (Duel.Turn > 1 && Duel.Phase < DuelPhase.Main2)) return false; + if (Bot.HasInMonstersZone(CardId.SprightElf, false, false, true) && !summon_SprightElf + && Bot.HasInMonstersZone(CardId.IP, false, false, true)) + { + List m1 = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && card.Id == CardId.SprightElf).ToList(); + List m2 = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && card.Id == CardId.IP).ToList(); + if (m1.Count <= 0 || m2.Count <= 0) return false; + List res = new List() { m1[0] }; + res.Add(m2[0]); + AI.SelectMaterials(res); + SetSpSummon(); + return true; + } + else + { + List cards = Bot.GetMonsters().Where(card => card != null && card.LinkCount != 2 &&card.IsFaceup() && (!no_link_ids.Contains(card.Id) || card.IsDisabled()) + && card.IsExtraCard() && card.Id != CardId.KnightmareUnicorn).ToList(); + List cards2 = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && card.Id == CardId.KnightmareUnicorn).ToList(); + if (cards.Count <= 0 || cards2.Count <= 0) return false; + cards.Sort(CardContainer.CompareCardAttack); + List res = new List(); + res.Add(cards.FirstOrDefault()); + res.Add(cards.FirstOrDefault()); + AI.SelectMaterials(res); + SetSpSummon(); + return true; + } + } + private bool MekkKnightCrusadiaAvramaxEffect() + { + if (Card.Location == CardLocation.MonsterZone) return true; + else return DestoryEnemyCard(); + } + private bool KnightmareUnicornSummon() + { + if (Bot.Hand.Count <= 0) return false; + if (!IsAvailableLinkZone()) return false; + List ecards = GetZoneCards(CardLocation.Onfield, Enemy); + if (ecards.Count(card => card != null && !card.IsShouldNotBeTarget()) <= 0) return false; + List tmepMaterials = new List(); + List resMaterials = new List(); + foreach (var card in Bot.GetMonsters()) + { + if (card == null || card.IsFacedown() || (card.Id == CardId.SprightElf && summon_SprightElf) + || (no_link_ids.Contains(card.Id)) || card.Id == CardId.TearlamentsKitkallos) continue; + if (tmepMaterials.Count(_card => _card != null && _card.Id == card.Id) <= 0) + tmepMaterials.Add(card); + } + int link_count = 0; + tmepMaterials.Sort(CardContainer.CompareCardAttack); + List materials = new List(); + List link_materials = tmepMaterials.Where(card => card != null && card.LinkCount == 2).ToList(); + List normal_materials = tmepMaterials.Where(card => card != null && card.LinkCount != 2).ToList(); + if (link_materials.Count() >= 1) + { + materials.Add(link_materials.FirstOrDefault()); + materials.AddRange(normal_materials); + } + else + { + materials.AddRange(normal_materials); + materials.AddRange(link_materials); + } + if (materials.Count(card => card != null && card.LinkCount >= 2) > 1 + && materials.Count(card => card != null && card.LinkCount < 2) < 1) return false; + foreach (var card in materials) + { + if (!resMaterials.Contains(card) && card.LinkCount < 3) + { + resMaterials.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 3) break; + } + } + if (link_count >= 3) { AI.SelectMaterials(resMaterials);SetSpSummon(); return true; } + return false; + } + private bool BaronnedeFleurEffect() + { + if (ActivateDescription == Util.GetStringId(CardId.BaronnedeFleur, 0)) + { + return DestoryEnemyCard(); + } + if (ActivateDescription == Util.GetStringId(CardId.BaronnedeFleur, 1)) + { + return Duel.LastChainPlayer != 0; + } + return false; + + } + private bool PrimevalPlanetPerlereinoEffect() + { + if (SpellActivate()) return true; + else + { + ClientCard card = Util.GetLastChainCard(); + if (card != null && card.Controller == 0 && card.Id == CardId.TearlamentsKaleidoHeart) return false; + return DestoryEnemyCard(); + } + } + + private bool DestoryEnemyCard() + { + if (Duel.Player == 0 && Card.Id == CardId.PrimevalPlanetPerlereino && !on_chaining_cards.Any(ccard => ccard != null && !ccard.IsDisabled() && ccard.Controller == 0 && ccard.Id == CardId.TearlamentsKitkallos) + && Bot.HasInMonstersZone(CardId.TearlamentsKitkallos) && !activate_TearlamentsKitkallos_3 + && !AllActivated()) + { + List temp = new List(); + List temp2 = new List(); + foreach (var ccard in Bot.GetMonsters()) + { + if (ccard == null) continue; + if (ccard.Id == CardId.TearlamentsKitkallos && ccard.IsDisabled()) temp.Add(ccard); + else if(ccard.Id == CardId.TearlamentsKitkallos) temp2.Add(ccard); + } + temp.AddRange(temp2); + AI.SelectCard(temp); + activate_PrimevalPlanetPerlereino_2 = true; + return true; + } + ClientCard card = Util.GetProblematicEnemyMonster(0, true); + if (card != null && (tgcard == null || tgcard != card)) + { + AI.SelectCard(card); + tgcard = card; + return true; + } + card = Util.GetBestEnemySpell(true); + if (card != null && (tgcard == null || tgcard != card)) + { + AI.SelectCard(card); + tgcard = card; + return true; + } + List cards = GetZoneCards(CardLocation.Onfield, Enemy); + cards = cards.Where(tcard => tcard != null && !tcard.IsShouldNotBeTarget() && (tgcard == null || tcard != tgcard)).ToList(); + if (cards.Count <= 0) return false; + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + tgcard = cards[0]; + AI.SelectCard(cards); + if (Card.Id == CardId.PrimevalPlanetPerlereino) activate_PrimevalPlanetPerlereino_2 = true; + return true; + } + private bool ElderEntityNtssEffect() + { + if (Card.Location == CardLocation.Grave) + { + return DestoryEnemyCard(); + } + else return true; + + } + private bool DivineroftheHeraldSummon() + { + if ((CheckRemainInDeck(CardId.KelbektheAncientVanguard) > 0 && !activate_KelbektheAncientVanguard_2) + || (CheckRemainInDeck(CardId.AgidotheAncientSentinel) > 0 && !activate_AgidotheAncientSentinel_2)) + { + summoned = true; + return true; + } + return false; + } + private bool EvaEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + List cards = Bot.GetGraveyardMonsters().Where(card => card != null && card.HasAttribute(CardAttribute.Light) && card.HasRace(CardRace.Fairy) && card != Card).ToList(); + if (cards.Count <= 0) return false; + activate_Eva = true; + return true; + } + private bool DivineroftheHeraldEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (Duel.Player == 0) + { + if (!IsCanSpSummon() && CheckRemainInDeck(CardId.MudoratheSwordOracle) <= 0 && CheckRemainInDeck(CardId.KeldotheSacredProtector) <= 0) return false; + if ((AllActivated() || Bot.ExtraDeck.Count(card=>card!=null && card.HasType(CardType.Fusion) && card.Id!=CardId.ElderEntityNtss)<=0) + && CheckRemainInDeck(CardId.MudoratheSwordOracle)<=0 && CheckRemainInDeck(CardId.KeldotheSacredProtector)<=0) return false; + if ((activate_KelbektheAncientVanguard_2 || CheckRemainInDeck(CardId.KelbektheAncientVanguard) <= 0) + && (activate_AgidotheAncientSentinel_2 || CheckRemainInDeck(CardId.AgidotheAncientSentinel) <= 0) && Bot.HasInExtra(CardId.SprightElf)) + { + List cards = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && !no_link_ids.Contains(card.Id) && card != Card).ToList(); + if (cards.Count() >= 1) return false; + } + } + activate_DivineroftheHerald = true; + return true; + } + else + { + return true; + } + } + private bool TearlamentsScreamEffect_1() + { + return SpellActivate(); + } + private bool MudoratheSwordOracleEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.Location == CardLocation.Hand) + { + if ((Bot.Hand.Count(card => card != null && card.Id == CardId.AgidotheAncientSentinel) <= 0 || activate_AgidotheAncientSentinel_2) + && (Bot.Hand.Count(card => card != null && card.Id == CardId.KelbektheAncientVanguard) <= 0 || activate_KelbektheAncientVanguard_2) && + !summoned && !Bot.HasInHand(CardId.MudoratheSwordOracle) && !Bot.HasInHand(CardId.KeldotheSacredProtector)) return false; + IList cardsid = new List(); + if (!activate_AgidotheAncientSentinel_2) cardsid.Add(CardId.AgidotheAncientSentinel); + if (!activate_KelbektheAncientVanguard_2) cardsid.Add(CardId.KelbektheAncientVanguard); + cardsid.Add(CardId.KeldotheSacredProtector); + cardsid.Add(CardId.MudoratheSwordOracle); + if (Card.Id == CardId.MudoratheSwordOracle) activate_MudoratheSwordOracle_2 = true; + else if (Card.Id == CardId.KeldotheSacredProtector) activate_KeldotheSacredProtector_2 = true; + AI.SelectCard(cardsid); + SetSpSummon(); + return true; + } + else if (Card.Location == CardLocation.Grave) + { + ClientCard chain_card = Util.GetLastChainCard(); + if (chain_card != null && chain_card.Controller == 0) return false; + if (GetZoneCards(CardLocation.Grave, Enemy).Count() <= 0 && Bot.Deck.Count >= 3) return false; + if ((Duel.CurrentChain == null || Duel.CurrentChain.Count <= 0) && Bot.Deck.Count >= 3) return false; + if (Duel.CurrentChain.Any(card => card != null && card.Controller == 0 && (card.Id == CardId.MudoratheSwordOracle || card.Id == CardId.KeldotheSacredProtector) || card.Id == CardId.NaelshaddollAriel)) return false; + if (Duel.CurrentChain.Any(card => card != null && card.Controller == 0 && card.Id == CardId.ShaddollBeast) && Bot.Deck.Count <= 0) + { + if (Card.Id == CardId.MudoratheSwordOracle) activate_MudoratheSwordOracle_2 = true; + else if (Card.Id == CardId.KeldotheSacredProtector) activate_KeldotheSacredProtector_2 = true; + return true; + } + foreach (var card in Duel.ChainTargets) + { + if (card == null) continue; + if ((card == Card && (Bot.Deck.Count < 5 || Enemy.Graveyard.Count(ccard => ccard != null && !key_no_send_to_deck_ids.Contains(ccard.Id)) > 0)) + || (card.Controller == 1 && card.Location == CardLocation.Grave)) + { + if (Card.Id == CardId.MudoratheSwordOracle) activate_MudoratheSwordOracle_2 = true; + else if (Card.Id == CardId.KeldotheSacredProtector) activate_KeldotheSacredProtector_2 = true; + return true; + } + } + foreach (var card in Duel.CurrentChain) + { + if (card == null || card.Controller == 0 || card.Location != CardLocation.Grave) continue; + if (key_send_to_deck_ids.Contains(card.Id)) + { + if (Card.Id == CardId.MudoratheSwordOracle) activate_MudoratheSwordOracle_2 = true; + else if (Card.Id == CardId.KeldotheSacredProtector) activate_KeldotheSacredProtector_2 = true; + return true; + } + } + if (Duel.Phase == DuelPhase.End && Bot.Deck.Count < 3 && Bot.Graveyard.Count > 0) + { + if (Card.Id == CardId.MudoratheSwordOracle) activate_MudoratheSwordOracle_2 = true; + else if (Card.Id == CardId.KeldotheSacredProtector) activate_KeldotheSacredProtector_2 = true; + return true; + } + return false; + } + else + { + if (Duel.Phase == DuelPhase.End && Bot.Deck.Count < 3 && Bot.Graveyard.Count > 0) + { + if (Card.Id == CardId.MudoratheSwordOracle) activate_MudoratheSwordOracle_2 = true; + else if (Card.Id == CardId.KeldotheSacredProtector) activate_KeldotheSacredProtector_2 = true; + return true; + } + return false; + } + } + + private bool TearlamentsScheirenEffect() + { + if (Card.Location == CardLocation.Grave) + { + return FusionEffect(CardId.TearlamentsScheiren); + } + else + { + if (AllActivated() && (!Bot.GetMonsters().Any(card=>card!=null && card.IsFaceup() && card.Level==4) || !Bot.HasInExtra(CardId.AbyssDweller))) return false; + activate_TearlamentsScheiren_1 = true; + SetSpSummon(); + return true; + } + } + private bool NaelshaddollArielEffect() + { + if (Card.Location == CardLocation.Grave) + { + return Enemy.Graveyard.Count(card => card != null && !key_no_remove_ids.Contains(card.Id)) > 0; + } + else + { + SetSpSummon(); + return true; + } + } + private bool IsShouldSummonFusion(int setcode = -1,int race = -1,bool all = false,int flag = 0x1f) + { + List cards = GetZoneCards(CardLocation.MonsterZone, Bot).Where(card => card != null && card.IsFaceup()).ToList(); + cards.AddRange(GetZoneCards(CardLocation.Grave | CardLocation.Hand, Bot)); + int xcount_1 = 0; + int xcount_2 = 0; + int xcount_3 = 0; + if ((flag & (int)Flag.TearlamentsKitkallos)>0 && Bot.ExtraDeck.Count(card => card != null && card.Id == CardId.TearlamentsKitkallos) > 0) + { + foreach (var card in cards) + { + if (card == null) continue; + if (card.Id == CardId.TearlamentsRulkallos && card.Location == CardLocation.MonsterZone && !card.IsDisabled()) continue; + if (card.HasSetcode(SETCODE) && card.HasType(CardType.Monster)) + { + ++xcount_1; + if (card.HasRace(CardRace.Aqua)) { --xcount_1; ++xcount_3; } + } + else if (card.HasRace(CardRace.Aqua)) ++xcount_2; + } + if (setcode == SETCODE) + { + ++xcount_1; + if (race == (int)CardRace.Aqua) { --xcount_1; ++xcount_3; } + } + else if (race == (int)CardRace.Aqua) ++xcount_2; + if (xcount_3 > 1 || (xcount_1 > 0 && xcount_3 > 0) || (xcount_1 > 0 && xcount_2 > 0) || (xcount_2 > 0 && xcount_3 > 0)) return true; + } + if ((flag & (int)Flag.TearlamentsRulkallos) > 0 && Bot.ExtraDeck.Count(card => card != null && card.Id == CardId.TearlamentsRulkallos) > 0) + { + xcount_1 = 0; + xcount_2 = 0; + foreach (var card in cards) + { + if (card == null) continue; + if (card.Id == CardId.TearlamentsKitkallos && xcount_1 <= 0) ++xcount_1; + else if (card.HasSetcode(SETCODE) && card.HasType(CardType.Monster)) ++xcount_2; + } + if (setcode == SETCODE) ++xcount_2; + if (xcount_1 > 0 && xcount_2 > 0) return true; + } + if ((flag & (int)Flag.TearlamentsKaleidoHeart) > 0 && Bot.ExtraDeck.Count(card => card != null && card.Id == CardId.TearlamentsKaleidoHeart) > 0) + { + xcount_1 = 0; + xcount_2 = 0; + foreach (var card in cards) + { + if (card == null) continue; + if (card.Id == CardId.TearlamentsRulkallos && card.Location == CardLocation.MonsterZone && !card.IsDisabled()) continue; + if (card.Id == CardId.TearlamentsReinoheart && xcount_1 <= 0) ++xcount_1; + else if (card.HasRace(CardRace.Aqua)) ++xcount_2; + } + if (race == (int)CardRace.Aqua) ++xcount_2; + if (xcount_1 > 0 && xcount_2 > 0) return true; + } + if ((flag & (int)Flag.PredaplantDragostapelia) > 0 && Bot.ExtraDeck.Count(card => card != null && card.Id == CardId.PredaplantDragostapelia) > 0) + { + xcount_1 = 0; + foreach (var card in cards) + { + if (card == null) continue; + if (card.Id == CardId.TearlamentsRulkallos && card.Location == CardLocation.MonsterZone && !card.IsDisabled()) continue; + if (((Bot.GetMonstersInMainZone().Count > 4 && card.Location == CardLocation.MonsterZone)|| Bot.GetMonstersInMainZone().Count<=4) && card.HasType(CardType.Fusion)) ++xcount_1; + } + if (xcount_1 > 0) return true; + } + if (all) + { + if ((flag & (int)Flag.ElShaddollWinda) > 0 && Bot.ExtraDeck.Count(card => card != null && card.Id == CardId.ElShaddollWinda) > 0) + { + List materials_1 = new List(); + List materials_2 = new List(); + foreach (var card in cards) + { + if (card == null) continue; + if (card.HasSetcode(0x9d)) materials_1.Add(card); + else if ((card.Id == CardId.TearlamentsHavnis || card.Id == CardId.TearlamentsMerrli + || card.Id == CardId.TearlamentsScheiren) && card.HasAttribute(CardAttribute.Dark)) + materials_2.Add(card); + } + xcount_1 = materials_1.Count; + xcount_2 = materials_2.Count; + if ((setcode == SETCODE) && race == (int)CardRace.Aqua) + { + ++xcount_2; + } + if (xcount_1 > 0 && xcount_2 > 0) return true; + } + } + return false; + } + private bool TearlamentsRulkallosEffect() + { + if (Card.Location == CardLocation.Grave) + { + activate_TearlamentsRulkallos_2 = true; + SetSpSummon(); + return true; + } + else + { + if (Card.IsDisabled()) return false; + activate_TearlamentsRulkallos_1 = true; + return true; + } + } + private bool AgidotheAncientSentinelEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (Duel.Player == 1) + { + //if (!activate_AgidotheAncientSentinel_2 && (Bot.HasInHand(CardId.HeraldofOrangeLight) || Bot.HasInHand(CardId.HeraldofGreenLight)) + // && Bot.Hand.Count(card => card != null && card.Id == CardId.AgidotheAncientSentinel) <= 1) return false; + return false; + } + else + { + if((!Bot.HasInGraveyard(CardId.KelbektheAncientVanguard) && !Bot.HasInGraveyard(CardId.MudoratheSwordOracle) + && !Bot.HasInGraveyard(CardId.KeldotheSacredProtector) && Bot.Hand.Count(card => card != null && card.Id == CardId.AgidotheAncientSentinel)<=1) + || Bot.GetMonstersInMainZone().Count>=4) return false; + } + if(!activate_AgidotheAncientSentinel_2 && (Bot.HasInHand(CardId.HeraldofOrangeLight) || Bot.HasInHand(CardId.HeraldofGreenLight)) + && Bot.Hand.Count(card => card != null && card.Id == CardId.AgidotheAncientSentinel) <= 1) return false; + SetSpSummon(); + return true; + } + else + { + if (AllActivated() && !Duel.CurrentChain.Any(card => card != null && card.Controller == 0 && (card.Id == CardId.TearlamentsHavnis || card.Id == CardId.TearlamentsMerrli || card.Id == CardId.TearlamentsScheiren))) return false; + activate_AgidotheAncientSentinel_2 = true; + return true; + } + } + private bool AllActivated() + { + return (activate_TearlamentsScheiren_2 || CheckRemainInDeck(CardId.TearlamentsScheiren) <= 0) + && (activate_TearlamentsHavnis_2 || CheckRemainInDeck(CardId.TearlamentsHavnis) <= 0) + && (activate_TearlamentsMerrli_2 || CheckRemainInDeck(CardId.TearlamentsMerrli) <= 0); + } + private bool KelbektheAncientVanguardEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (Duel.LastChainPlayer == 0) return false; + if ((Bot.HasInHand(CardId.HeraldofOrangeLight) || Bot.HasInHand(CardId.HeraldofGreenLight)) + && !activate_KelbektheAncientVanguard_2) return false; + List cards = Enemy.GetMonsters(); + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + AI.SelectCard(cards); + + SetSpSummon(); + return true; + } + else + { + if (AllActivated() && !Duel.CurrentChain.Any(card=>card!=null && card.Controller==0 && (card.Id==CardId.TearlamentsHavnis||card.Id==CardId.TearlamentsMerrli || card.Id==CardId.TearlamentsScheiren))) return false; + activate_KelbektheAncientVanguard_2 = true; + return true; + } + } + private bool TearlamentsMerrliEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (AllActivated()) return false; + activate_TearlamentsMerrli_1 = true; + return true; + } + else + { + return FusionEffect(CardId.TearlamentsMerrli); + } + } + private bool TearlamentsHavnisEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (AllActivated()) return false; + activate_TearlamentsHavnis_1 = true; + return true; + } + else + { + return FusionEffect(CardId.TearlamentsHavnis); + } + } + private bool SpellSet() + { + if (Card.Id == CardId.TearlamentsSulliek) return !Bot.GetSpells().Any(card => card != null && card.Id == CardId.TearlamentsSulliek && (card.IsFacedown() || (card.IsFaceup() && !card.IsDisabled()))); + return Card.HasType(CardType.QuickPlay) || Card.HasType(CardType.Trap); + } + private bool TearlamentsReinoheartEffect() + { + if (Card.Location == CardLocation.Grave) + { + List cards = Bot.Hand.Where(card => card != null && card.HasSetcode(SETCODE)).ToList(); + List temp = new List(cards); + foreach (var card in temp) + { + if ((card.Id == CardId.TearlamentsScheiren && !activate_TearlamentsScheiren_1) + || (card.Id == CardId.TearlamentsMerrli && !summoned && !activate_TearlamentsMerrli_1) + ||(card.Id==CardId.TearlamentsHavnis && cards.Count(ccard=>ccard!=null && ccard.Id==CardId.TearlamentsHavnis) > 1)) + cards.Remove(card); + } + if (cards.Count() <= 0) return false; + activate_TearlamentsReinoheart_2 = true; + SetSpSummon(); + return true; + } + else + { + if (AllActivated()) return false; + activate_TearlamentsReinoheart_1 = true; + return true; + } + } + private bool ShaddollDragonEffect() + { + if (Card.Location == CardLocation.Grave) + { + ClientCard card = Util.GetBestEnemySpell(); + List cards = Enemy.GetSpells().Where(ccard=> tgcard == null || tgcard != ccard).ToList(); + if (card != null && (tgcard == null || tgcard != card)) { AI.SelectCard(card); return true; } + else if (cards.Count > 0) { AI.SelectCard(cards); return true; } + return false; + } + else return true; + } + private bool TearlamentsKitkallosEffect_2() + { + if (Bot.HasInMonstersZone(CardId.ElShaddollWinda, true, false, true)) return TearlamentsKitkallosEffect(); + return false; + } + private bool TearlamentsKitkallosEffect() + { + if (ActivateDescription == Util.GetStringId(CardId.TearlamentsKitkallos, 1)) + { + if (Card.IsDisabled()) return false; + if (AllActivated() && !Bot.HasInGraveyard(CardId.TearlamentsKaleidoHeart) && !Bot.HasInGraveyard(CardId.TearlamentsRulkallos) + && !Bot.HasInGraveyard(CardId.TearlamentsKitkallos)) return false; + if(Bot.HasInMonstersZone(CardId.ElShaddollWinda,true,false,true)) AI.SelectCard(CardId.ElShaddollWinda); + else if (Bot.HasInMonstersZone(CardId.TearlamentsKitkallos) && !activate_TearlamentsKitkallos_3 && !AllActivated()) AI.SelectCard(CardId.TearlamentsKitkallos); + else if (!activate_TearlamentsScheiren_2 && Bot.HasInMonstersZone(CardId.TearlamentsScheiren) && IsShouldSummonFusion()) AI.SelectCard(CardId.TearlamentsScheiren); + else if (!activate_TearlamentsMerrli_2 && Bot.HasInMonstersZone(CardId.TearlamentsMerrli) && IsShouldSummonFusion()) AI.SelectCard(CardId.TearlamentsMerrli); + else if (!activate_TearlamentsHavnis_2 && Bot.HasInMonstersZone(CardId.TearlamentsHavnis) && IsShouldSummonFusion()) AI.SelectCard(CardId.TearlamentsHavnis); + else if (Bot.HasInMonstersZone(CardId.TearlamentsReinoheart) && !activate_TearlamentsReinoheart_1 && !AllActivated()) AI.SelectCard(CardId.TearlamentsReinoheart); + else if (Bot.HasInMonstersZone(CardId.Eva) && Bot.Graveyard.Count(card => card != null && card.HasAttribute(CardAttribute.Light) && card.HasRace(CardRace.Fairy)) > 0 + && (CheckRemainInDeck(CardId.HeraldofGreenLight) > 0 || CheckRemainInDeck(CardId.HeraldofOrangeLight) > 0)) AI.SelectCard(CardId.Eva); + else if ((Bot.HasInExtra(CardId.TearlamentsRulkallos) && !Bot.HasInGraveyard(CardId.TearlamentsKitkallos)) + || (Bot.HasInExtra(CardId.PredaplantDragostapelia) && Bot.Graveyard.Count(card => card != null && card.HasType(CardType.Fusion)) <= 0)) AI.SelectCard(CardId.TearlamentsKitkallos); + else if (Bot.HasInMonstersZone(CardId.ShaddollDragon) && Enemy.GetSpellCount() > 0) AI.SelectCard(CardId.ShaddollDragon); + else + { + List mcards = GetZoneCards(CardLocation.MonsterZone, Bot); + mcards.Sort(CardContainer.CompareCardAttack); + AI.SelectCard(mcards); + } + if(!activate_TearlamentsKitkallos_1 && Bot.HasInGraveyard(CardId.TearlamentsKitkallos)) AI.SelectNextCard(Bot.Graveyard.Where(card => card != null && card.Id == CardId.TearlamentsKitkallos).ToList()); + if (!activate_TearlamentsMerrli_1 && Bot.HasInGraveyard(CardId.TearlamentsMerrli) && !AllActivated()) AI.SelectNextCard(Bot.Graveyard.Where(card => card != null && card.Id == CardId.TearlamentsMerrli).ToList()); + else if (!activate_TearlamentsMerrli_1 && Bot.HasInHand(CardId.TearlamentsMerrli) && !AllActivated()) AI.SelectNextCard(Bot.Hand.Where(card => card != null && card.Id == CardId.TearlamentsMerrli).ToList()); + else if (!activate_TearlamentsReinoheart_1 && Bot.HasInGraveyard(CardId.TearlamentsReinoheart) && !AllActivated()) AI.SelectNextCard(Bot.Graveyard.Where(card => card != null && card.Id == CardId.TearlamentsReinoheart).ToList()); + else if (!activate_TearlamentsReinoheart_1 && Bot.HasInHand(CardId.TearlamentsReinoheart) && !AllActivated()) AI.SelectNextCard(Bot.Hand.Where(card => card != null && card.Id == CardId.TearlamentsReinoheart).ToList()); + else AI.SelectNextCard(CardId.TearlamentsKaleidoHeart,CardId.TearlamentsRulkallos,CardId.TearlamentsKitkallos); + activate_TearlamentsKitkallos_2 = true; + SetSpSummon(); + return true; + } + else if (Card.Location == CardLocation.Grave) + { + if (AllActivated()) return false; + activate_TearlamentsKitkallos_3 = true; + return true; + } + else + { + if (Card.IsDisabled()) return false; + if (!IS_YGOPRO) select_TearlamentsKitkallos = true; + activate_TearlamentsKitkallos_1 = true; + return true; + } + } + private bool HasinZoneKeyCard(CardLocation loc) + { + if (loc == CardLocation.Hand) + { + if (!activate_TearlamentsScheiren_2 && Bot.HasInHand(CardId.TearlamentsScheiren)) return true; + if (!activate_TearlamentsHavnis_2 && Bot.HasInHand(CardId.TearlamentsHavnis)) return true; + if (!activate_TearlamentsMerrli_2 && Bot.HasInHand(CardId.TearlamentsMerrli)) return true; + } + if (loc == CardLocation.Deck) + { + if (!activate_TearlamentsScheiren_2 && CheckRemainInDeck(CardId.TearlamentsScheiren)>0) return true; + if (!activate_TearlamentsHavnis_2 && CheckRemainInDeck(CardId.TearlamentsHavnis)>0) return true; + if (!activate_TearlamentsMerrli_2 && CheckRemainInDeck(CardId.TearlamentsMerrli)>0) return true; + } + return false; + } + private bool TearlamentsSulliekEffect() + { + if (SpellActivate()) return true; + if (Card.Location == CardLocation.SpellZone) + { + ClientCard card = Util.GetLastChainCard(); + if (card != null && card.Controller == 1 && card.Location == CardLocation.MonsterZone + && !card.IsShouldNotBeTarget()) + { + if (_PredaplantDragostapelia != null && _PredaplantDragostapelia.Location == CardLocation.MonsterZone && _PredaplantDragostapelia.IsFaceup() + && e_PredaplantDragostapelia_cards.Contains(card)) return false; + chain_TearlamentsSulliek = card; + return true; + } + else + { + if (Duel.Player == 1 || Duel.Phase == DuelPhase.End) + { + if (Duel.LastChainPlayer == 0 || Duel.CurrentChain.Count(ccard=>ccard!=null &&ccard.Controller==0 + && (ccard.Id==CardId.TearlamentsHavnis || ccard.Id == CardId.TearlamentsMerrli || ccard.Id == CardId.TearlamentsScheiren))>0) return false; + if (((Bot.HasInMonstersZone(CardId.TearlamentsKitkallos,false,false,true) && !activate_TearlamentsKitkallos_3 && IsShouldSummonFusion(SETCODE, (int)CardRace.Aqua) + && ((CheckRemainInDeck(CardId.TearlamentsHavnis) > 0 && !activate_TearlamentsHavnis_2) + || (CheckRemainInDeck(CardId.TearlamentsMerrli) > 0 && !activate_TearlamentsMerrli_2) + || (CheckRemainInDeck(CardId.TearlamentsScheiren) > 0 && !activate_TearlamentsScheiren_2)) && Bot.GetMonsterCount()<3) + ||(IsCanFusionSummon() && (Bot.HasInMonstersZone(CardId.TearlamentsScheiren) || Bot.HasInMonstersZone(CardId.TearlamentsHavnis) + || Bot.HasInMonstersZone(CardId.TearlamentsMerrli))) || (!activate_TearlamentsReinoheart_2 && Bot.HasInMonstersZone(CardId.TearlamentsReinoheart) && (HasinZoneKeyCard(CardLocation.Hand) + || (Bot.Hand.Count(ccard=> ccard != null && ccard.HasSetcode(SETCODE))>0 && HasinZoneKeyCard(CardLocation.Deck)))&& IsShouldSummonFusion(SETCODE, (int)CardRace.Aqua))) && IsCanSpSummon()) + { + List cards = Enemy.GetMonsters().Where(ecard=> ecard != null && !ecard.IsShouldNotBeTarget() && ecard.IsFaceup()).ToList(); + if (cards.Count > 0) + { + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + chain_TearlamentsSulliek = cards[0]; + } + else chain_TearlamentsSulliek = null; + return true; + + } + } + } + return false; + } + else + { + return true; + } + + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ThunderDragonExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ThunderDragonExecutor.cs new file mode 100644 index 0000000..e5fb673 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ThunderDragonExecutor.cs @@ -0,0 +1,2575 @@ +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("ThunderDragon", "AI_ThunderDragon")] + class ThunderDragonExecutor : DefaultExecutor + { + public class CardId + { + public const int ThunderDragonlord = 5206415; + public const int TheBystialLubellion = 32731036; + public const int TheChaosCreator = 90488465; + public const int BystialDruiswurm = 6637331; + public const int BystialMagnamhut = 33854624; + public const int ThunderDragonroar = 29596581; + public const int ThunderDragonhawk = 83107873; + public const int NormalThunderDragon = 31786629; + public const int ThunderDragondark = 56713174; + public const int BlackDragonCollapserpent = 61901281; + public const int WhiteDragonWyverburster = 99234526; + public const int AloofLupine = 92998610; + public const int BatterymanSolar = 44586426; + public const int AshBlossom = 14558127; + public const int G = 23434538; + public const int DragonBusterDestructionSword = 76218313; + public const int ThunderDragonmatrix = 20318029; + public const int AllureofDarkness = 1475311; + public const int GoldSarcophagus = 75500286; + public const int ThunderDragonFusion = 95238394; + public const int ChaosSpace = 99266988; + public const int CalledbytheGrave = 24224830; + public const int BrandedRegained = 34090915; + public const int InfiniteImpermanence = 10045474; + public const int BatterymanToken = 44586427; + + public const int ThunderDragonTitan = 41685633; + public const int ThunderDragonColossus = 15291624; + public const int AbyssDweller = 21044178; + public const int UnderworldGoddessoftheClosedWorld = 98127546; + public const int MekkKnightCrusadiaAvramax = 21887175; + public const int AccesscodeTalker = 86066372; + public const int BowoftheGoddess = 4280258; + public const int KnightmareUnicorn = 38342335; + public const int UnionCarrier = 83152482; + public const int IP = 65741786; + public const int CrossSheep = 50277355; + public const int PredaplantVerteAnaconda = 70369116; + public const int StrikerDragon = 73539069; + public const int Linkuriboh = 41999284; + } + private enum Select + { + NormalThunderDragon, + TheChaosCreator, + ChaosSpace_1, + ChaosSpace_2, + ThunderDragonColossus, + AccesscodeTalker, + DestroyReplace + }; + private const int THUNDER_COUNTD = 18; + List selectFlag = new List() + { + false,false,false,false,false,false,false + }; + List selectAtt = new List() + { + false,false,false,false,false,false,false + }; + + bool isSummoned = false; + bool handActivated = false; + bool place_CrossSheep = false; + bool place_ThunderDragonColossus = false; + bool place_Link_4 = false; + bool summon_WhiteDragonWyverburster = false; + bool summon_BlackDragonCollapserpent = false; + bool summon_UnionCarrier = false; + bool summon_TheBystialLubellion = false; + bool activate_ThunderDragonFusion = false; + bool activate_ThunderDragondark = false; + bool activate_ThunderDragonroar = false; + bool activate_ThunderDragonhawk = false; + bool activate_ThunderDragonmatrix = false; + bool activate_TheBystialLubellion_hand = false; + bool activate_BystialMagnamhut_hand = false; + bool activate_BystialDruiswurm_hand = false; + bool activate_ChaosSpace_grave = false; + bool activate_ChaosSpace_hand = false; + bool No_SpSummon = false; + + List SpSummonCardsId = new List() + { + CardId.ThunderDragonmatrix,CardId.BatterymanSolar , + CardId.AshBlossom,CardId.G, + CardId.DragonBusterDestructionSword,CardId.AloofLupine + }; + List NotSpSummonCardsId = new List() + { + CardId.ThunderDragonlord,CardId.TheBystialLubellion,CardId.TheChaosCreator, + CardId.BlackDragonCollapserpent,CardId.WhiteDragonWyverburster + }; + List Impermanence_list = new List(); + List should_not_negate = new List + { + 81275020, 28985331 + }; + public ThunderDragonExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, CardId.InfiniteImpermanence, Impermanence_activate); + AddExecutor(ExecutorType.Activate, CardId.G, GEffect); + AddExecutor(ExecutorType.Activate, CardId.BowoftheGoddess); + AddExecutor(ExecutorType.Activate, CardId.UnderworldGoddessoftheClosedWorld); + AddExecutor(ExecutorType.Activate, CardId.AshBlossom, AshBlossomEffect); + AddExecutor(ExecutorType.Activate, CardId.TheBystialLubellion, TheBystialLubellionEffect); + AddExecutor(ExecutorType.Activate, CardId.CalledbytheGrave, CalledbytheGraveEffect); + AddExecutor(ExecutorType.Activate, CardId.AccesscodeTalker, AccesscodeTalkerEffect); + AddExecutor(ExecutorType.Activate, CardId.BrandedRegained, BrandedRegainedEffect); + AddExecutor(ExecutorType.Activate, CardId.UnionCarrier, UnionCarrierEffect); + AddExecutor(ExecutorType.SpSummon, CardId.TheBystialLubellion, TheBystialLubellionSummon); + AddExecutor(ExecutorType.Activate, CardId.GoldSarcophagus, GoldSarcophagusEffect); + AddExecutor(ExecutorType.Activate, CardId.NormalThunderDragon, NormalThunderDragonEffect); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonmatrix, ThunderDragonmatrixEffect); + AddExecutor(ExecutorType.SpSummon, CardId.StrikerDragon, StrikerDragonSummon); + AddExecutor(ExecutorType.SpSummon, CardId.ThunderDragonColossus, ThunderDragonColossusSummon_2); + AddExecutor(ExecutorType.SpSummon, CardId.CrossSheep, CrossSheepSummon); + AddExecutor(ExecutorType.Activate, CardId.CrossSheep, CrossSheepEffect); + AddExecutor(ExecutorType.Activate, CardId.TheChaosCreator); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonTitan, ThunderDragonTitanEffect); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonColossus, ThunderDragonColossusEffect); + AddExecutor(ExecutorType.SpSummon, CardId.ThunderDragonColossus, ThunderDragonColossusSummon); + AddExecutor(ExecutorType.Summon, CardId.AloofLupine, AloofLupineSummon); + AddExecutor(ExecutorType.Activate, CardId.AloofLupine, AloofLupineEffect); + AddExecutor(ExecutorType.Summon, CardId.BatterymanSolar, BatterymanSolarSummon); + AddExecutor(ExecutorType.Activate, CardId.BatterymanSolar, BatterymanSolarEffect); + AddExecutor(ExecutorType.SpSummon, CardId.WhiteDragonWyverburster, WhiteDragonWyverbursterSummon); + AddExecutor(ExecutorType.Activate, CardId.WhiteDragonWyverburster); + AddExecutor(ExecutorType.SpSummon, CardId.BlackDragonCollapserpent, BlackDragonCollapserpentSummon); + AddExecutor(ExecutorType.Activate, CardId.BlackDragonCollapserpent); + AddExecutor(ExecutorType.SpSummon, CardId.UnionCarrier, UnionCarrierSummon); + AddExecutor(ExecutorType.Activate, CardId.AllureofDarkness, AllureofDarknessEffect); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonhawk, ThunderDragonhawkEffect); + AddExecutor(ExecutorType.Activate, CardId.ChaosSpace, ChaosSpaceEffect); + AddExecutor(ExecutorType.Activate, CardId.BystialMagnamhut, BystialMagnamhutEffect); + AddExecutor(ExecutorType.Activate, CardId.BystialDruiswurm, BystialDruiswurmEffect); + AddExecutor(ExecutorType.SpSummon, CardId.ThunderDragonlord, ThunderDragonlordSummon); + AddExecutor(ExecutorType.Activate, CardId.PredaplantVerteAnaconda, PredaplantVerteAnacondaEffect); + AddExecutor(ExecutorType.MonsterSet, CardId.ThunderDragonmatrix, ThunderDragonmatrixSet); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonFusion, ThunderDragonFusionEffect); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragondark, ThunderDragondarkEffect); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonroar, ThunderDragonroarEffect); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonlord, ThunderDragonlordEffect); + AddExecutor(ExecutorType.SpSummon, CardId.TheChaosCreator, TheChaosCreatorSummon); + AddExecutor(ExecutorType.SpSummon, CardId.UnderworldGoddessoftheClosedWorld, UnderworldGoddessoftheClosedWorldSummon); + AddExecutor(ExecutorType.SpSummon, CardId.BowoftheGoddess, BowoftheGoddessSummon); + AddExecutor(ExecutorType.SpSummon, CardId.UnionCarrier, UnionCarrierSummon_2); + AddExecutor(ExecutorType.Activate, CardId.IP, IPEffect); + AddExecutor(ExecutorType.SpSummon, CardId.IP,IPSummon); + AddExecutor(ExecutorType.Activate, CardId.KnightmareUnicorn, KnightmareUnicornEffect); + AddExecutor(ExecutorType.SpSummon, CardId.KnightmareUnicorn, KnightmareUnicornSummon); + AddExecutor(ExecutorType.SpSummon, CardId.AccesscodeTalker, BowoftheGoddessSummon); + AddExecutor(ExecutorType.Activate, CardId.MekkKnightCrusadiaAvramax, MekkKnightCrusadiaAvramaxEffect); + AddExecutor(ExecutorType.SpSummon, CardId.MekkKnightCrusadiaAvramax, MekkKnightCrusadiaAvramaxSummon); + AddExecutor(ExecutorType.SpSummon, CardId.PredaplantVerteAnaconda, PredaplantVerteAnacondaSummon); + AddExecutor(ExecutorType.Activate, CardId.Linkuriboh); + AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh); + AddExecutor(ExecutorType.SpSummon, CardId.AbyssDweller); + AddExecutor(ExecutorType.Activate, CardId.AbyssDweller, GEffect); + AddExecutor(ExecutorType.Activate, CardId.ChaosSpace, ChaosSpaceEffect_2); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragonmatrix, ThunderDragonmatrixEffect_2); + AddExecutor(ExecutorType.Summon, CardId.ThunderDragonmatrix, ThunderDragonmatrixSummon); + AddExecutor(ExecutorType.SpSummon, CardId.BlackDragonCollapserpent, BlackDragonCollapserpentSummon_2); + AddExecutor(ExecutorType.Summon, CardId.ThunderDragonroar, DefaultSummon); + AddExecutor(ExecutorType.Summon, CardId.ThunderDragondark, DefaultSummon); + AddExecutor(ExecutorType.Summon, CardId.NormalThunderDragon, DefaultSummon); + AddExecutor(ExecutorType.Summon, CardId.DragonBusterDestructionSword, ThunderDragonmatrixSummon); + AddExecutor(ExecutorType.Summon, CardId.AloofLupine, DefaultSummon); + AddExecutor(ExecutorType.Summon, CardId.AshBlossom, DefaultSummon); + AddExecutor(ExecutorType.Summon, CardId.G, DefaultSummon); + AddExecutor(ExecutorType.Activate, CardId.ThunderDragondark, ThunderDragondarkEffect_2); + AddExecutor(ExecutorType.SpellSet, SpellSet); + AddExecutor(ExecutorType.Activate, CardId.AllureofDarkness, AllureofDarknessEffect_2); + AddExecutor(ExecutorType.Activate, CardId.UnionCarrier, UnionCarrierEffect_2); + AddExecutor(ExecutorType.Repos, DefaultMonsterRepos); + + } + #region DeckCheck + public int CheckRemainInDeck(int id) + { + switch (id) + { + case CardId.ThunderDragonlord: + return Bot.GetRemainingCount(CardId.ThunderDragonlord, 1); + case CardId.TheBystialLubellion: + return Bot.GetRemainingCount(CardId.TheBystialLubellion, 2); + case CardId.TheChaosCreator: + return Bot.GetRemainingCount(CardId.TheChaosCreator, 1); + case CardId.BystialDruiswurm: + return Bot.GetRemainingCount(CardId.BystialDruiswurm, 2); + case CardId.BystialMagnamhut: + return Bot.GetRemainingCount(CardId.BystialMagnamhut, 2); + case CardId.ThunderDragonroar: + return Bot.GetRemainingCount(CardId.ThunderDragonroar, 2); + case CardId.ThunderDragonhawk: + return Bot.GetRemainingCount(CardId.ThunderDragonhawk, 2); + case CardId.NormalThunderDragon: + return Bot.GetRemainingCount(CardId.NormalThunderDragon, 3); + case CardId.ThunderDragondark: + return Bot.GetRemainingCount(CardId.ThunderDragondark, 3); + case CardId.BlackDragonCollapserpent: + return Bot.GetRemainingCount(CardId.BlackDragonCollapserpent, 2); + case CardId.WhiteDragonWyverburster: + return Bot.GetRemainingCount(CardId.WhiteDragonWyverburster, 2); + case CardId.AloofLupine: + return Bot.GetRemainingCount(CardId.AloofLupine, 2); + case CardId.BatterymanSolar: + return Bot.GetRemainingCount(CardId.BatterymanSolar, 3); + case CardId.AshBlossom: + return Bot.GetRemainingCount(CardId.AshBlossom, 2); + case CardId.G: + return Bot.GetRemainingCount(CardId.G, 3); + case CardId.DragonBusterDestructionSword: + return Bot.GetRemainingCount(CardId.DragonBusterDestructionSword, 1); + case CardId.ThunderDragonmatrix: + return Bot.GetRemainingCount(CardId.ThunderDragonmatrix, 3); + case CardId.AllureofDarkness: + return Bot.GetRemainingCount(CardId.AllureofDarkness, 3); + case CardId.GoldSarcophagus: + return Bot.GetRemainingCount(CardId.GoldSarcophagus, 1); + case CardId.ThunderDragonFusion: + return Bot.GetRemainingCount(CardId.ThunderDragonFusion, 2); + case CardId.ChaosSpace: + return Bot.GetRemainingCount(CardId.ChaosSpace, 3); + case CardId.CalledbytheGrave: + return Bot.GetRemainingCount(CardId.CalledbytheGrave, 2); + case CardId.BrandedRegained: + return Bot.GetRemainingCount(CardId.BrandedRegained, 1); + case CardId.InfiniteImpermanence: + return Bot.GetRemainingCount(CardId.InfiniteImpermanence, 2); + default: + return 0; + } + } + #endregion + + public override bool OnSelectHand() + { + // go first + return true; + } + + public override void OnNewTurn() + { + handActivated = false; + isSummoned = false; + No_SpSummon = false; + + activate_ThunderDragonFusion = false; + activate_ThunderDragondark = false; + activate_ThunderDragonroar = false; + activate_ThunderDragonhawk = false; + activate_ThunderDragonmatrix = false; + activate_TheBystialLubellion_hand = false; + activate_BystialMagnamhut_hand = false; + activate_BystialDruiswurm_hand = false; + activate_ChaosSpace_grave = false; + + summon_WhiteDragonWyverburster = false; + summon_BlackDragonCollapserpent = false; + summon_TheBystialLubellion = false; + summon_UnionCarrier = false; + + for (int i = 0; i < selectAtt.Count; i++) + selectAtt[i] = false; + + base.OnNewTurn(); + } + private bool IsAvailableZone(int seq) + { + ClientCard card = Bot.MonsterZone[seq]; + if (seq == 5 && Bot.MonsterZone[6] != null && Bot.MonsterZone[6].Controller == 0) return false; + if (seq == 6 && Bot.MonsterZone[5] != null && Bot.MonsterZone[5].Controller == 0) return false; + if (card == null) return true; + if (card.Controller != 0) return false; + if (card.IsFacedown()) return false; + if (card.IsDisabled()) return true; + if (card.Id == CardId.ThunderDragonColossus + || card.Id == CardId.ThunderDragonTitan + || card.Id == CardId.UnderworldGoddessoftheClosedWorld + || card.Id == CardId.MekkKnightCrusadiaAvramax + || card.Id == CardId.AccesscodeTalker + || (card.Id == CardId.BowoftheGoddess && card.Attack > 800) + || (card.Id == CardId.UnionCarrier && summon_UnionCarrier)) return false; + return true; + } + private bool IsAvailableLinkZone() + { + int zones = 0; + List cards = Bot.GetMonstersInMainZone().Where(card => card != null && card.IsFaceup()).ToList(); + foreach (var card in cards) + { + zones |= card.GetLinkedZones(); + } + ClientCard e_card = Bot.MonsterZone[5]; + if (e_card != null && e_card.IsFaceup() && e_card.HasType(CardType.Link)) + { + if (e_card.Controller == 0) + { + if (e_card.HasLinkMarker(CardLinkMarker.BottomLeft)) + zones |= 1 << 0; + if (e_card.HasLinkMarker(CardLinkMarker.Bottom)) + zones |= 1 << 1; + if (e_card.HasLinkMarker(CardLinkMarker.BottomRight)) + zones |= 1 << 2; + } + if (e_card.Controller == 1) + { + if (e_card.HasLinkMarker(CardLinkMarker.TopLeft)) + zones |= 1 << 2; + if (e_card.HasLinkMarker(CardLinkMarker.Top)) + zones |= 1 << 1; + if (e_card.HasLinkMarker(CardLinkMarker.TopRight)) + zones |= 1 << 0; + } + } + e_card = Bot.MonsterZone[6]; + if (e_card != null && e_card.IsFaceup() && e_card.HasType(CardType.Link)) + { + if (e_card.Controller == 0) + { + if (e_card.HasLinkMarker(CardLinkMarker.BottomLeft)) + zones |= 1 << 2; + if (e_card.HasLinkMarker(CardLinkMarker.Bottom)) + zones |= 1 << 3; + if (e_card.HasLinkMarker(CardLinkMarker.BottomRight)) + zones |= 1 << 4; + } + if (e_card.Controller == 1) + { + if (e_card.HasLinkMarker(CardLinkMarker.TopLeft)) + zones |= 1 << 4; + if (e_card.HasLinkMarker(CardLinkMarker.Top)) + zones |= 1 << 3; + if (e_card.HasLinkMarker(CardLinkMarker.TopRight)) + zones |= 1 << 2; + } + } + zones &= 0x7f; + if ((zones & Zones.z0) > 0 && IsAvailableZone(0)) return true; + if ((zones & Zones.z1) > 0 && IsAvailableZone(1)) return true; + if ((zones & Zones.z2) > 0 && IsAvailableZone(2)) return true; + if ((zones & Zones.z3) > 0 && IsAvailableZone(3)) return true; + if ((zones & Zones.z4) > 0 && IsAvailableZone(4)) return true; + if (IsAvailableZone(5)) return true; + if (IsAvailableZone(6)) return true; + return false; + } + private void ResetFlag() + { + for (int i = 0; i < selectFlag.Count; ++i) + { + selectFlag[i] = false; + } + } + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location==CardLocation.MonsterZone) + { + if (place_CrossSheep) + { + place_CrossSheep = false; + if ((Zones.z5 & available) > 0) return Zones.z5; + if ((Zones.z6 & available) > 0) return Zones.z6; + } + if (place_ThunderDragonColossus) + { + place_ThunderDragonColossus = false; + if (Bot.MonsterZone[5] != null && Bot.MonsterZone[5].IsCode(CardId.CrossSheep)) + { + if ((Zones.z0 & available) > 0) return Zones.z0; + if ((Zones.z2 & available) > 0) return Zones.z2; + } + if (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].IsCode(CardId.CrossSheep)) + { + if ((Zones.z2 & available) > 0) return Zones.z2; + if ((Zones.z4 & available) > 0) return Zones.z4; + } + if ((Zones.z2 & available) > 0) return Zones.z2; + if ((Zones.z0 & available) > 0) return Zones.z0; + if ((Zones.z4 & available) > 0) return Zones.z4; + } + if (place_Link_4) + { + place_Link_4 = false; + if ((Zones.z5 & available) > 0) return Zones.z5; + if ((Zones.z6 & available) > 0) return Zones.z6; + } + if (Bot.MonsterZone[5] != null && Bot.MonsterZone[5].IsCode(CardId.CrossSheep)) + { + if ((Zones.z0 & available) > 0 && Bot.MonsterZone[2] != null && Bot.MonsterZone[2].HasType(CardType.Fusion) && Bot.MonsterZone[2].IsFaceup()) return Zones.z0; + if ((Zones.z2 & available) > 0 && Bot.MonsterZone[0] != null && Bot.MonsterZone[0].HasType(CardType.Fusion) && Bot.MonsterZone[0].IsFaceup()) return Zones.z2; + } + if (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].IsCode(CardId.CrossSheep)) + { + if ((Zones.z2 & available) > 0 && Bot.MonsterZone[4] != null && Bot.MonsterZone[4].HasType(CardType.Fusion) && Bot.MonsterZone[4].IsFaceup()) return Zones.z2; + if ((Zones.z4 & available) > 0 && Bot.MonsterZone[2] != null && Bot.MonsterZone[2].HasType(CardType.Fusion) && Bot.MonsterZone[2].IsFaceup()) return Zones.z4; + } + return base.OnSelectPlace(cardId, player, location, available); + } + return base.OnSelectPlace(cardId, player, location, available); + } + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (selectFlag.Count(flag => flag) > 1) + { + if (selectFlag.Count(flag => flag) == 2 && selectFlag[(int)Select.TheChaosCreator] && !selectFlag[(int)Select.DestroyReplace]) + { + selectFlag[(int)Select.TheChaosCreator] = false; + } + else if (selectFlag.Count(flag => flag) == 2 && selectFlag[(int)Select.DestroyReplace]) + { + selectFlag[(int)Select.DestroyReplace] = false; + } + else + { + ResetFlag(); + return null; + } + } + if (selectFlag[(int)Select.NormalThunderDragon]) + { + selectFlag[(int)Select.NormalThunderDragon] = false; + //ThunderDragonTitan + if (cards.Any(card => card != null && card.Controller != 0)) return null; + if (cards.Count <= 1) return null; + if (Bot.HasInHand(CardId.ChaosSpace) && !activate_ChaosSpace_hand) + return Util.CheckSelectCount(cards, cards, max, max); + if(Bot.HasInHand(CardId.AloofLupine) && !isSummoned && GetRemainingThunderCount(true)>0) + return Util.CheckSelectCount(cards, cards, max, max); + if (Bot.HasInHand(CardId.ThunderDragonFusion) && !activate_ThunderDragonFusion) + return Util.CheckSelectCount(cards, cards, min, min); + if(HasInZoneNoActivate(CardId.BlackDragonCollapserpent,CardLocation.Hand) + || HasInZoneNoActivate(CardId.BystialDruiswurm, CardLocation.Hand) + || HasInZoneNoActivate(CardId.BystialMagnamhut, CardLocation.Hand) + || HasInZoneNoActivate(CardId.TheBystialLubellion, CardLocation.Hand)) + return Util.CheckSelectCount(cards, cards, min, min); + if(HasInZoneNoActivate(CardId.ThunderDragonhawk,CardLocation.Hand)) + return Util.CheckSelectCount(cards, cards, min, min); + return Util.CheckSelectCount(cards, cards, max, max); + } + if (selectFlag[(int)Select.ChaosSpace_1]) + { + selectFlag[(int)Select.ChaosSpace_1] = false; + selectFlag[(int)Select.ChaosSpace_2] = true; + List res = new List(); + if (cards.Any(card => card != null && card.IsCode(CardId.ThunderDragonroar)) && !activate_ThunderDragonroar) + res.AddRange(cards.Where(card => card != null && card.IsCode(CardId.ThunderDragonroar)).ToList()); + if (cards.Any(card => card != null && card.IsCode(CardId.ThunderDragondark)) && !activate_ThunderDragondark) + res.AddRange(cards.Where(card => card != null && card.IsCode(CardId.ThunderDragondark)).ToList()); + if (cards.Any(card => card != null && card.IsCode(CardId.ThunderDragondark)) && !activate_ThunderDragondark) + res.AddRange(cards.Where(card => card != null && card.IsCode(CardId.ThunderDragondark)).ToList()); + if (cards.Any(card => card != null && card.IsCode(CardId.NormalThunderDragon))) + res.AddRange(cards.Where(card => card != null && card.IsCode(CardId.NormalThunderDragon)).ToList()); + if (cards.Any(card => card != null && card.IsCode(CardId.ThunderDragonmatrix))) + res.AddRange(cards.Where(card => card != null && card.IsCode(CardId.ThunderDragonmatrix)).ToList()); + if (res.Count <= 0) return null; + return Util.CheckSelectCount(res, cards, min, max); + } + if (selectFlag[(int)Select.ChaosSpace_2]) + { + selectFlag[(int)Select.ChaosSpace_2] = false; + List res = new List(); + //can't get CardAttributes in deck + if (cards.Any(card => card != null && (card.Id == CardId.BlackDragonCollapserpent + || card.Id == CardId.TheChaosCreator))) + { + if (!summon_BlackDragonCollapserpent && cards.Any(card => card != null && card.IsCode(CardId.BlackDragonCollapserpent) && !Bot.HasInHand(CardId.BlackDragonCollapserpent))) + { + IList cards_1 = cards.Where(card => card != null && card.IsCode(CardId.BlackDragonCollapserpent)).ToList(); + IList cards_2 = cards.Where(card => card != null && !card.IsCode(CardId.BlackDragonCollapserpent)).ToList(); + res.AddRange(cards_1); + res.AddRange(cards_2); + return Util.CheckSelectCount(res, cards, min, max); + } + else + { + res = cards.ToList(); + res.Sort(CardContainer.CompareCardLevel); + res.Reverse(); + return Util.CheckSelectCount(res, cards, min, max); + } + } + else if (cards.Any(card => card != null && (card.Id == CardId.WhiteDragonWyverburster + ||card.Id == CardId.ThunderDragonlord || card.Id == CardId.TheBystialLubellion))) + { + if (!summon_WhiteDragonWyverburster && cards.Any(card => card != null && card.IsCode(CardId.WhiteDragonWyverburster) + && (Bot.HasInExtra(CardId.StrikerDragon) || Bot.HasInExtra(CardId.UnionCarrier)) && !Bot.HasInHand(CardId.WhiteDragonWyverburster))) + { + IList cards_1 = cards.Where(card => card != null && card.IsCode(CardId.WhiteDragonWyverburster)).ToList(); + IList cards_2 = cards.Where(card => card != null && !card.IsCode(CardId.WhiteDragonWyverburster)).ToList(); + res.AddRange(cards_1); + res.AddRange(cards_2); + return Util.CheckSelectCount(res, cards, min, max); + } + else if (!activate_TheBystialLubellion_hand && (HasInZoneNoActivate(CardId.BystialMagnamhut, CardLocation.Deck) + || HasInZoneNoActivate(CardId.BystialDruiswurm, CardLocation.Deck) && !Bot.HasInHand(CardId.TheBystialLubellion)) + && cards.Any(card => card != null && card.IsCode(CardId.TheBystialLubellion))) + { + IList cards_1 = cards.Where(card => card != null && card.IsCode(CardId.TheBystialLubellion)).ToList(); + IList cards_2 = cards.Where(card => card != null && !card.IsCode(CardId.TheBystialLubellion)).ToList(); + res.AddRange(cards_1); + res.AddRange(cards_2); + return Util.CheckSelectCount(res, cards, min, max); + } + else if (!summon_WhiteDragonWyverburster && !Bot.HasInHand(CardId.WhiteDragonWyverburster) && cards.Any(card => card != null && card.IsCode(CardId.WhiteDragonWyverburster))) + { + IList cards_1 = cards.Where(card => card != null && card.IsCode(CardId.WhiteDragonWyverburster)).ToList(); + IList cards_2 = cards.Where(card => card != null && !card.IsCode(CardId.WhiteDragonWyverburster)).ToList(); + res.AddRange(cards_1); + res.AddRange(cards_2); + return Util.CheckSelectCount(res, cards, min, max); + } + else + { + res = cards.ToList(); + res.Sort(CardContainer.CompareCardLevel); + return Util.CheckSelectCount(res, cards, min, max); + } + } + return null; + } + if (selectFlag[(int)Select.ThunderDragonColossus]) + { + selectFlag[(int)Select.ThunderDragonColossus] = false; + if (cards.Count < 2) return null; + List copy_cards = new List(cards); + copy_cards.Sort(CardContainer.CompareCardAttack); + IList res = new List(); + for (int i = 0; i < copy_cards.Count; ++i) + { + if ((copy_cards[i].Id == CardId.ThunderDragonroar && HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.MonsterZone) && Bot.GetMonstersInMainZone().Count < 5) + || (copy_cards[i].Id == CardId.ThunderDragondark && HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.MonsterZone)) + || (copy_cards[i].Id == CardId.ThunderDragonmatrix && HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.MonsterZone))) + { + if (i <= 0) continue; + ClientCard temp = copy_cards[0]; + copy_cards[0] = copy_cards[i]; + copy_cards[i] = temp; + } + } + return Util.CheckSelectCount(copy_cards, cards, min, max); + } + if (selectFlag[(int)Select.AccesscodeTalker]) + { + selectFlag[(int)Select.AccesscodeTalker] = false; + List copy_cards = new List(cards); + copy_cards.Sort(CardContainer.CompareCardAttack); + List res = new List(); + res.AddRange(copy_cards.Where(card => card != null && card.Location == CardLocation.Grave)); + res.AddRange(copy_cards.Where(card => card != null && card.Location != CardLocation.Grave)); + if (res.Count <= 0) return null; + CardAttribute att = (CardAttribute)res[0].Attribute; + if (GetAttIndex(att) > 0) selectAtt[GetAttIndex(att)] = true; + return Util.CheckSelectCount(res, cards, min, max); + } + if (selectFlag[(int)Select.DestroyReplace]) + { + selectFlag[(int)Select.DestroyReplace] = false; + if (min == 1 && max == 1) + { + List copy_cards = new List(cards); + copy_cards.Sort(CardContainer.CompareCardAttack); + List res = new List(); + List pre_res = new List(); + foreach (var card in copy_cards) + { + if (card == null) continue; + if (card.Id == CardId.ThunderDragonroar && !activate_ThunderDragonroar && Bot.GetMonstersInMainZone().Count < 5) + res.Add(card); + else if (card.Id == CardId.ThunderDragondark && !activate_ThunderDragondark) + res.Add(card); + else + pre_res.Add(card); + } + res.Reverse(); + res.AddRange(pre_res); + if(res.Count>=0) return Util.CheckSelectCount(res, cards, min, max); + return null; + } + if (min == 2 && max == 2) + { + List res = new List(); + if (!activate_ThunderDragonroar && Bot.GetMonstersInMainZone().Count < 5) + { + foreach (var card in cards) + if (card.Id == CardId.ThunderDragonroar && res.Count(_card => _card != null && _card.Id == CardId.ThunderDragonroar) <= 0) + res.Add(card); + } + if (!activate_ThunderDragondark) + { + foreach (var card in cards) + if (card.Id == CardId.ThunderDragondark && res.Count(_card => _card != null && _card.Id == CardId.ThunderDragondark) <= 0) + res.Add(card); + } + if (!activate_ThunderDragonhawk && !GetZoneRepeatCardsId(0,Bot.Hand).Contains(-1)) + { + foreach (var card in cards) + if (card.Id == CardId.ThunderDragonhawk && res.Count(_card => _card != null && _card.Id == CardId.ThunderDragonhawk) <= 0) + res.Add(card); + } + if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Deck)) + { + foreach (var card in cards) + if (card.Id == CardId.ThunderDragonmatrix && res.Count(_card => _card != null && _card.Id == CardId.ThunderDragonmatrix) <= 0) + res.Add(card); + } + List scards = cards.Where(card => card != null && card.Id != CardId.ChaosSpace && card.Id != CardId.ThunderDragonFusion).ToList(); + if (scards.Count > 0) res.AddRange(scards); + List mcards = cards.Where(card => card != null && !card.HasRace(CardRace.Thunder)).ToList(); + mcards.Sort(CardContainer.CompareCardAttack); + mcards.Reverse(); + if (mcards.Count > 0) res.AddRange(mcards); + if(res.Count>0) return Util.CheckSelectCount(res, cards, min, max); + return null; + + } + } + if (hint == HintMsg.FusionMaterial) + { + List res = new List(); + List banish = cards.Where(card => card != null && card.Location == CardLocation.Removed).ToList(); + if (banish.Count > 0) res.AddRange(banish); + List grave_1 = cards.Where(card => card != null && card.Location == CardLocation.Grave && card.Id != CardId.ThunderDragonroar && card.Id != CardId.ThunderDragondark).ToList(); + List grave_2 = cards.Where(card => card != null && card.Location == CardLocation.Grave && (card.Id == CardId.ThunderDragonroar || card.Id == CardId.ThunderDragondark)).ToList(); + if (grave_1.Count > 0) res.AddRange(grave_1); + if (grave_2.Count > 0) res.AddRange(grave_2); + List monsters = cards.Where(card => card != null && card.Location == CardLocation.MonsterZone).ToList(); + monsters.Sort(CardContainer.CompareCardAttack); + if (monsters.Count > 0) res.AddRange(monsters); + if (res.Count > 0) return Util.CheckSelectCount(res, cards, min, max); + return null; + } + if (Duel.Phase == DuelPhase.End && hint == HintMsg.AddToHand) + { + List res = new List(); + List cards_1 = cards.Where(card => card != null && card.Id == CardId.BystialDruiswurm).ToList(); + List cards_2 = cards.Where(card => card != null && (card.Id == CardId.WhiteDragonWyverburster || card.Id == CardId.BlackDragonCollapserpent)).ToList(); + List cards_3 = cards.Where(card => card != null && card.Id != CardId.BystialDruiswurm && card.Id != CardId.WhiteDragonWyverburster && card.Id != CardId.BlackDragonCollapserpent).ToList(); + if (cards_1.Count > 0) res.AddRange(cards_1); + if (cards_2.Count > 0) res.AddRange(cards_2); + if (cards_3.Count > 0) res.AddRange(cards_3); + if (res.Count > 0) return Util.CheckSelectCount(res, cards, min, max); + return null; + } + if (hint == HintMsg.OperateCard) + { + if (cards.Any(card => card != null && card.Location == CardLocation.Removed)) + { + selectFlag[(int)Select.TheChaosCreator] = true; + List res = new List(); + List cards_1 = cards.Where(card => card != null && card.Controller == 0 && (card.IsCode(CardId.ThunderDragonColossus) || card.IsCode(CardId.ThunderDragonTitan))).ToList(); + if (cards_1.Count > 0) res.AddRange(cards_1); + List cards_2 = cards.Where(card => card != null && card.Controller == 0 && !card.IsCode(CardId.ThunderDragonColossus) && !card.IsCode(CardId.ThunderDragonTitan)).ToList(); + if (cards_2.Count > 0) res.AddRange(cards_2); + List cards_3 = cards.Where(card => card != null && card.Controller == 1).ToList(); + if (cards_3.Count > 0) res.AddRange(cards_3); + if (res.Count > 0) return Util.CheckSelectCount(res, cards, min, max); + return null; + } + return null; + } + if (selectFlag[(int)Select.TheChaosCreator]) + { + selectFlag[(int)Select.TheChaosCreator] = false; + List res = new List(cards); + res.Sort(CardContainer.CompareCardAttack); + if (res.Count <= 0) return null; + if(res[0].Attack= 0 && this_seq + that_seq == 4) + || (Util.IsChainTarget(Card)) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + Impermanence_list.Add(this_seq); + return true; + } + } + } + } + if ((LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || LastChainCard.IsDisabled() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget())) + return false; + // negate monsters + if (is_should_not_negate() && LastChainCard.Location == CardLocation.MonsterZone) return false; + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + return true; + } + } + } + return true; + } + public int SelectSTPlace(ClientCard card = null, bool avoid_Impermanence = false) + { + List list = new List { 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 && Impermanence_list.Contains(seq)) continue; + return zone; + }; + } + return 0; + } + public bool is_should_not_negate() + { + ClientCard last_card = Util.GetLastChainCard(); + if (last_card != null + && last_card.Controller == 1 && last_card.IsCode(should_not_negate)) + return true; + return false; + } + private bool MekkKnightCrusadiaAvramaxEffect() + { + if (Card.Location == CardLocation.Grave) + { + List cards = Enemy.GetMonsters(); + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + cards.AddRange(Enemy.GetSpells()); + if (cards.Count <= 0) return false; + AI.SelectCard(cards); + return true; + } + else return true; + } + private bool ThunderDragonColossusEffect() + { + selectFlag[(int)Select.DestroyReplace] = true; + return true; + } + private IList GetAttUsed() + { + IList attributes = new List(); + for (int i = 0; i < selectAtt.Count; ++i) + if (selectAtt[i]) attributes.Add((CardAttribute)(System.Math.Pow(2, i))); + if (attributes.Count > 0) return attributes; + return null; + } + private int GetRemainingThunderCount(bool isOnlyTunder = false) + { + int remaining = THUNDER_COUNTD; + if (isOnlyTunder) remaining -= 4; + remaining = remaining - Bot.Hand.Count(card => card != null && card.HasRace(CardRace.Thunder) && !card.IsExtraCard() && !(isOnlyTunder & !Card.HasSetcode(0x11c))); + remaining = remaining - Bot.SpellZone.Count(card => card != null && card.HasRace(CardRace.Thunder) && !card.IsExtraCard() && !(isOnlyTunder & !Card.HasSetcode(0x11c))); + remaining = remaining - Bot.MonsterZone.Count(card => card != null && card.HasRace(CardRace.Thunder) && !card.IsExtraCard() && !(isOnlyTunder & !Card.HasSetcode(0x11c))); + remaining = remaining - Bot.Graveyard.Count(card => card != null && card.HasRace(CardRace.Thunder) && !card.IsExtraCard() && !(isOnlyTunder & !Card.HasSetcode(0x11c))); + remaining = remaining - Bot.Banished.Count(card => card != null && card.HasRace(CardRace.Thunder) && !card.IsExtraCard() && !(isOnlyTunder & !Card.HasSetcode(0x11c))); + return (remaining < 0) ? 0 : remaining; + } + private int GetLinkMark(int cardId) + { + if (cardId == CardId.Linkuriboh || cardId == CardId.StrikerDragon) return 1; + if (cardId == CardId.PredaplantVerteAnaconda || cardId == CardId.CrossSheep || cardId == CardId.IP || cardId == CardId.UnionCarrier) return 2; + if (cardId == CardId.KnightmareUnicorn) return 3; + if (cardId == CardId.BowoftheGoddess || cardId == CardId.AccesscodeTalker || cardId == CardId.MekkKnightCrusadiaAvramax) return 4; + if (cardId == CardId.UnderworldGoddessoftheClosedWorld) return 5; + return 1; + } + private bool AshBlossomEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return Duel.CurrentChain.Count > 0 && Duel.LastChainPlayer != 0; + } + public int CompareCardLink(ClientCard cardA, ClientCard cardB) + { + if (cardA.LinkCount < cardB.LinkCount) + return -1; + if (cardA.LinkCount == cardB.LinkCount) + return 0; + return 1; + } + private IList CardsIdToClientCards(IList cardsId, IList cardsList, bool uniqueId = true, bool alias = true) + { + if (cardsList?.Count() <= 0 || cardsId?.Count() <= 0) return new List(); + List res = new List(); + foreach (var cardid in cardsId) + { + List cards = cardsList.Where(card => card != null && (card.Id == cardid || ((card.Alias != 0 && cardid == card.Alias) & alias))).ToList(); + if (cards?.Count <= 0) continue; + cards.Sort(CardContainer.CompareCardAttack); + if (uniqueId) res.Add(cards.First()); + else res.AddRange(cards); + } + return res; + } + private bool IPEffect() + { + if (Duel.LastChainPlayer == 0) return false; + if (!Bot.HasInExtra(CardId.KnightmareUnicorn) && !Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax)) return false; + int[] materials = new[] { + CardId.PredaplantVerteAnaconda, + CardId.UnionCarrier, + CardId.CrossSheep + }; + if (Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax)) + { + List m = new List(); + IList pre_m = CardsIdToClientCards(materials, Bot.GetMonsters().Where(card=>card!=null && card.IsFaceup()).ToList()); + if (pre_m?.Count <= 0) return false; + int link_count = 0; + foreach (var card in pre_m) + { + m.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 4) break; + } + if (link_count < 4) return false; + AI.SelectCard(CardId.MekkKnightCrusadiaAvramax); + AI.SelectMaterials(m); + return true; + } + else if (Bot.HasInExtra(CardId.KnightmareUnicorn)) + { + if (Bot.Hand.Count <= 0) return false; + List pre_cards = Enemy.GetMonsters(); + pre_cards.AddRange(Enemy.GetSpells()); + if (pre_cards.Count(card => card != null && !card.IsShouldNotBeTarget()) <= 0) return false; + List materials_2 = new List(); + List resMaterials = new List(); + foreach (var card in Bot.GetMonsters()) + { + if (card == null) continue; + if (card.Id == CardId.UnionCarrier && summon_UnionCarrier) continue; + if ((GetLinkMark(card.Id) < 3 || (card.Id == CardId.BowoftheGoddess && card.Attack <= 800)) && card.Id != CardId.ThunderDragonTitan + && card.Id != CardId.ThunderDragonColossus && card.IsFaceup() && materials_2.Count(_card => _card != null && _card.Id == card.Id) <= 0) + materials_2.Add(card); + } + int link_count = 0; + materials_2.Sort(CardContainer.CompareCardAttack); + materials_2.Sort(CompareCardLink); + materials_2.Reverse(); + if (materials_2.Count <= 0) return false; + foreach (var card in materials_2) + { + if (!resMaterials.Contains(card)) + { + resMaterials.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 3) break; + } + } + if (link_count >= 3) { AI.SelectCard(CardId.KnightmareUnicorn); AI.SelectMaterials(resMaterials); return true; } + } + return false; + } + private bool AccesscodeTalkerEffect() + { + if (ActivateDescription == Util.GetStringId(CardId.AccesscodeTalker, 1)) + { + if (Card.IsDisabled()) return false; + if (Bot.Graveyard.Count(card => card != null && card.HasType(CardType.Link)) <= 0) return false; + IList attributes = GetAttUsed(); + if (attributes == null || attributes.Count <= 0) { ResetFlag(); selectFlag[(int)Select.AccesscodeTalker] = true; return true; } + if (Bot.Graveyard.Count(card => card != null && card.HasType(CardType.Link) && !attributes.Contains((CardAttribute)card.Attribute)) <= 0) return false; + ResetFlag(); + selectFlag[(int)Select.AccesscodeTalker] = true; + return true; + } + else + { + List cards = Bot.GetGraveyardMonsters(); + cards.Sort(CompareCardLink); + cards.Reverse(); + AI.SelectCard(cards); + return true; + } + } + private bool CalledbytheGraveEffect() + { + ClientCard card = Util.GetLastChainCard(); + if (card == null) return false; + int id = card.Id; + List g_cards = Enemy.GetGraveyardMonsters().Where(g_card => g_card != null && g_card.Id == id).ToList(); + if (Duel.LastChainPlayer != 0 && card != null) + { + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + if (card.Location == CardLocation.Grave && card.HasType(CardType.Monster)) + { + AI.SelectCard(card); + } + else if (g_cards.Count() > 0 && card.HasType(CardType.Monster)) + { + AI.SelectCard(g_cards); + } + else return false; + return true; + } + return false; + } + private bool MekkKnightCrusadiaAvramaxSummon() + { + List materials_1 = new List{ + CardId.PredaplantVerteAnaconda,CardId.CrossSheep, + CardId.IP + }; + List materials_2 = new List{ + CardId.KnightmareUnicorn + }; + List materials_3 = new List{ + CardId.StrikerDragon,CardId.Linkuriboh,CardId.AbyssDweller + }; + if (Bot.GetMonsters().Count(card => card != null && card.IsFaceup() && card.Id == CardId.BowoftheGoddess && card.Attack <= 800) > 0) + materials_3.Add(CardId.BowoftheGoddess); + if (!summon_UnionCarrier) materials_1.Add(CardId.UnionCarrier); + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials_1) && card.IsFaceup()) >= 2) + { + AI.SelectMaterials(materials_1); + place_Link_4 = true; + return true; + } + else if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials_2) && card.IsFaceup()) > 0 + && Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials_3) && card.IsFaceup()) > 0) + { + materials_2.AddRange(materials_3); + AI.SelectMaterials(materials_2); + place_Link_4 = true; + return true; + } + return false; + } + private bool GEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return Duel.Player != 0; + } + private bool ThunderDragonColossusSummon_2() + { + if (handActivated && activate_ThunderDragonmatrix) + return ThunderDragonColossusSummon(); + return false; + } + private bool ThunderDragonTitanEffect() + { + //if (Duel.CurrentChain.Count > 0) + if(ActivateDescription == Util.GetStringId(CardId.ThunderDragonTitan, 0)) + { + List res = new List(); + List mcards = Enemy.GetMonsters(); + List scards = Enemy.GetSpells(); + if (mcards.Count <= 0 && scards.Count <= 0) return false; + if (Duel.CurrentChain.Count(card => card != null && card.Controller == 1) > 0) + { + foreach (var card in Duel.CurrentChain) + { + if (card != null && card.Controller == 1 && (card.Location == CardLocation.MonsterZone || card.Location == CardLocation.SpellZone) + && !card.IsDisabled() && (card.HasType(CardType.Monster) + || card.HasType(CardType.Field) || card.HasType(CardType.Continuous) + || card.HasType(CardType.Equip))) + { + res.Add(card); + } + } + } + mcards.Sort(CardContainer.CompareCardAttack); + mcards.Reverse(); + res.AddRange(mcards); + res.AddRange(scards); + AI.SelectCard(res); + return true; + } + else + { + selectFlag[(int)Select.DestroyReplace] = true; + return true; + } + + } + private bool PredaplantVerteAnacondaEffect() + { + if (ActivateDescription == Util.GetStringId(CardId.PredaplantVerteAnaconda, 1)) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (CheckRemainInDeck(CardId.ThunderDragonFusion) <= 0) return false; + if (Bot.GetMonstersInMainZone().Count > 4 && Bot.GetMonstersInMainZone().Count(card => card != null && !card.IsExtraCard() && card.HasSetcode(0x11c) && card.HasType(CardType.Monster) && card.IsFaceup()) <= 0) return false; + List g_card = Bot.Graveyard.ToList(); + List b_card = Bot.Banished.ToList(); + g_card.AddRange(b_card); + int count = 0; + int Lcount = 0; + foreach (var card in g_card) + { + if (card == null) continue; + if (card.HasType(CardType.Monster) && card.HasSetcode(0x11c)) + ++count; + if (card.IsCode(CardId.NormalThunderDragon)) + ++Lcount; + } + if (Bot.HasInExtra(CardId.ThunderDragonColossus) && Lcount > 0 && g_card.Count(card => card != null && card.HasRace(CardRace.Thunder)) > 1) + { + AI.SelectCard(CardId.ThunderDragonFusion); + AI.SelectNextCard(CardId.ThunderDragonColossus,CardId.ThunderDragonTitan); + No_SpSummon = true; + return true; + } + else if (count >= 3 && Bot.HasInExtra(CardId.ThunderDragonTitan)) + { + AI.SelectCard(CardId.ThunderDragonFusion); + AI.SelectNextCard(CardId.ThunderDragonTitan, CardId.ThunderDragonColossus); + No_SpSummon = true; + return true; + } + return false; + } + return false; + } + private bool CrossSheepEffect() + { + if (Bot.HasInExtra(CardId.UnionCarrier) + && (Bot.HasInGraveyard(CardId.AloofLupine)|| Bot.HasInGraveyard(CardId.G))) + AI.SelectCard(CardId.AloofLupine, CardId.G); + else if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Grave)) + AI.SelectCard(CardId.ThunderDragonmatrix); + else if (Bot.HasInExtra(CardId.Linkuriboh)) + AI.SelectCard(CardId.ThunderDragonmatrix, CardId.DragonBusterDestructionSword); + else AI.SelectCard(CardId.BatterymanSolar, CardId.AshBlossom,CardId.G); + return true; + } + private bool KnightmareUnicornEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + List cards = new List(); + cards.AddRange(Enemy.SpellZone); + cards.AddRange(Enemy.MonsterZone); + cards = cards.Where(card => card != null && !card.IsShouldNotBeTarget()).ToList(); + if (cards.Count <= 0) return false; + List disCardId = new List(); + IList repeatId = GetZoneRepeatCardsId(0, Bot.Hand); + if (!repeatId.Contains(-1)) disCardId.AddRange(repeatId); + foreach (var card in Bot.Hand) + if (card != null && card.HasSetcode(0x11c) && card.HasType(CardType.Monster)) + disCardId.Add(card.Id); + AI.SelectCard(disCardId); + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + AI.SelectNextCard(cards); + return true; + } + private bool ThunderDragonlordEffect() + { + if (Duel.Phase == DuelPhase.End) + { + int count = Bot.Graveyard.Count(card => card != null && card.HasRace(CardRace.Thunder)); + if ((Bot.HasInGraveyard(CardId.ThunderDragonroar) || Bot.HasInGraveyard(CardId.ThunderDragondark) && count > 1) && CheckRemainInDeck(CardId.ThunderDragonFusion) >0 ) + AI.SelectCard(CardId.ThunderDragonFusion); + else if(!Bot.HasInGraveyard(CardId.ThunderDragonroar) && CheckRemainInDeck(CardId.ThunderDragonroar) > 0) + AI.SelectCard(CardId.ThunderDragonroar); + else if(!Bot.HasInGraveyard(CardId.ThunderDragondark) && CheckRemainInDeck(CardId.ThunderDragondark) > 0) + AI.SelectCard(CardId.ThunderDragondark); + else AI.SelectCard(CardId.ThunderDragonmatrix,CardId.NormalThunderDragon,CardId.BatterymanSolar); + return true; + } + if (Duel.Phase == DuelPhase.Standby) + { + List Thundercards = Bot.Graveyard.Where(card => card != null && card.HasRace(CardRace.Thunder)).ToList(); + List NoThundercards = Bot.Graveyard.Where(card => card != null && !card.HasRace(CardRace.Thunder) && !card.IsCode(CardId.ThunderDragonFusion) && !card.IsCode(CardId.ChaosSpace)).ToList(); + if (HasInZoneNoActivate(CardId.ThunderDragonroar,CardLocation.Grave) && Bot.GetMonstersInMainZone().Count < 5) + AI.SelectCard(CardId.ThunderDragonroar); + else if(HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Grave)) + AI.SelectCard(CardId.ThunderDragondark); + else if (HasInZoneNoActivate(CardId.ThunderDragonhawk, CardLocation.Grave) && !GetZoneRepeatCardsId(0,Bot.Hand).Contains(-1)) + AI.SelectCard(CardId.ThunderDragonhawk); + else if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Grave)) + AI.SelectCard(CardId.ThunderDragonmatrix); + else if(Thundercards.Count > 0) + AI.SelectCard(Thundercards); + else AI.SelectCard(CardId.ThunderDragonmatrix); + + List Spellcards = Bot.GetGraveyardSpells().Where(card => card != null && !card.IsCode(CardId.ThunderDragonFusion) && !card.IsCode(CardId.ChaosSpace)).ToList(); + if (Spellcards.Count > 0) AI.SelectNextCard(Spellcards); + else if(NoThundercards.Count > 0 ) AI.SelectNextCard(Spellcards); + else if(Thundercards.Count > 0) AI.SelectNextCard(Thundercards); + else AI.SelectNextCard(CardId.ChaosSpace); + AI.SelectThirdCard(CardId.ThunderDragonColossus, CardId.ThunderDragonTitan, CardId.ThunderDragonlord,CardId.TheChaosCreator); + return true; + } + return false; + } + private bool PredaplantVerteAnacondaSummon() + { + if (CheckRemainInDeck(CardId.ThunderDragonFusion) <= 0) return false; + List g_card = Bot.Graveyard.ToList(); + List b_card = Bot.Banished.ToList(); + g_card.AddRange(b_card); + int count = 0; + int Lcount = 0; + foreach (var card in g_card) + { + if (card == null) continue; + if (card.HasType(CardType.Monster) && card.HasSetcode(0x11c)) + ++count; + if (card.IsCode(CardId.NormalThunderDragon)) + ++Lcount; + } + if (!IsAvailableLinkZone()) return false; + if ((count >= 3 && Bot.HasInExtra(CardId.ThunderDragonTitan)) || + (Bot.HasInExtra(CardId.ThunderDragonColossus) && Lcount > 0 && g_card.Count(card => card != null && card.HasRace(CardRace.Thunder)) > 1)) + { + List cards = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && GetLinkMark(card.Id) < 3 && !card.HasType(CardType.Normal) && !card.IsCode(CardId.ThunderDragonColossus) && !card.IsCode(CardId.ThunderDragonTitan) && !card.IsCode(CardId.ThunderDragonlord) && !(card.IsCode(CardId.UnionCarrier) && summon_UnionCarrier)).ToList(); + if (cards.Count < 2) return false; + cards.Sort(CardContainer.CompareCardAttack); + if (cards.Count(card => card != null && card.Id == CardId.IP) > 0 && cards.Count <= 2) return false; + AI.SelectMaterials(cards); + return true; + } + return false; + } + private bool AllureofDarknessEffect_2() + { + return !Bot.HasInHand(CardId.G) && Bot.Hand.Count <= 3 && Bot.Deck.Count > 2; + } + private bool KnightmareUnicornSummon() + { + if (Bot.Hand.Count <= 0) return false; + if (!IsAvailableLinkZone()) return false; + List pre_cards = Enemy.GetMonsters(); + pre_cards.AddRange(Enemy.GetSpells()); + if (pre_cards.Count(card => card != null && !card.IsShouldNotBeTarget()) <= 0) return false; + List tmepMaterials = new List(); + List resMaterials = new List(); + foreach (var card in Bot.GetMonsters()) + { + if (card == null) continue; + if (card.Id == CardId.UnionCarrier && summon_UnionCarrier) continue; + if ((GetLinkMark(card.Id) < 3 || (card.Id == CardId.BowoftheGoddess && card.Attack <= 800)) && card.Id != CardId.ThunderDragonTitan + && card.Id != CardId.ThunderDragonColossus && card.IsFaceup() && tmepMaterials.Count(_card=> _card != null && _card.Id==card.Id) <= 0) + tmepMaterials.Add(card); + } + int link_count = 0; + tmepMaterials.Sort(CardContainer.CompareCardAttack); + List materials = new List(); + List link_materials = tmepMaterials.Where(card => card != null && card.LinkCount == 2).ToList(); + List normal_materials = tmepMaterials.Where(card => card != null && card.LinkCount != 2).ToList(); + if (link_materials.Count() >= 1) + { + link_materials.InsertRange(1, normal_materials); + materials.AddRange(link_materials); + } + else + { + materials.AddRange(normal_materials); + materials.AddRange(link_materials); + } + if (materials.Count(card => card != null && card.LinkCount >= 2) > 1 + && materials.Count(card => card != null && card.LinkCount < 2) < 1) return false; + foreach (var card in materials) + { + if (!resMaterials.Contains(card) && card.LinkCount < 3) + { + resMaterials.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 3) break; + } + } + if (link_count >= 3) { AI.SelectMaterials(resMaterials); return true; } + return false; + } + private bool UnderworldGoddessoftheClosedWorldSummon() + { + if (Duel.Turn == 0 || Enemy.GetMonsterCount() <= 0) return false; + if (Util.GetBestAttack(Bot) >= Util.GetBestAttack(Enemy) && Enemy.MonsterZone.GetDangerousMonster() == null) return false; + List e_materials = new List(); + List m_materials = new List(); + List resMaterials = new List(); + foreach (var card in Enemy.GetMonsters()) + { + if (card != null && card.HasType(CardType.Effect) && card.IsFaceup()) + e_materials.Add(card); + } + if (e_materials.Count() <= 0) return false; + foreach (var card in Bot.GetMonsters()) + { + if (card == null) continue; + if (card.Id == CardId.UnionCarrier && summon_UnionCarrier) continue; + if (GetLinkMark(card.Id) < 3 && card.Id != CardId.ThunderDragonTitan + && card.Id != CardId.ThunderDragonColossus && card.IsFaceup() && card.HasType(CardType.Effect)) + m_materials.Add(card); + } + if (m_materials.Count() < 3) return false; + int link_count = 0; + int e_link_count = 0; + e_materials.Sort(CardContainer.CompareCardAttack); + e_materials.Reverse(); + foreach (var card in e_materials) + { + if (!resMaterials.Contains(card)) + resMaterials.Add(card); + e_link_count += (card.HasType(CardType.Link)) ? (card.LinkCount == 2 ? 2:1): 1; + if (e_link_count >= 1) break; + } + if (e_link_count <= 0) return false; + link_count += e_link_count; + foreach (var card in m_materials) + { + if (e_link_count <= 1) + { + if (!resMaterials.Contains(card) && card.LinkCount < 3) + { + resMaterials.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 5) break; + } + } + else + { + resMaterials.Add(card); + link_count += 1; + if (link_count >= 5) break; + } + } + if (link_count >= 5) { AI.SelectMaterials(resMaterials); place_Link_4 = true; return true; } + return false; + } + private bool BowoftheGoddessSummon() + { + if (!IsAvailableLinkZone()) return false; + if (Card.Id == CardId.AccesscodeTalker) + { + if (Duel.Turn == 0 || Enemy.GetMonsterCount() + Enemy.GetSpellCount() <= 0) return false; + } + else + { + if (Duel.Turn > 0 && Enemy.GetMonsterCount() + Enemy.GetSpellCount() > 0 + && (Bot.HasInExtra(CardId.UnderworldGoddessoftheClosedWorld) || Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax) + || Bot.HasInExtra(CardId.AccesscodeTalker))) return false; + } + List tempmaterials = new List(); + List resMaterials = new List(); + foreach (var card in Bot.GetMonsters()) + { + if (card == null) continue; + if(card.Id == CardId.UnionCarrier && summon_UnionCarrier) continue; + if (GetLinkMark(card.Id) < 4 && card.Id != CardId.ThunderDragonTitan + && card.Id != CardId.ThunderDragonColossus && card.IsFaceup() && !card.HasType(CardType.Token)) + tempmaterials.Add(card); + } + int link_count = 0; + List materials = new List(); + List link_materials = tempmaterials.Where(card => card != null && (card.LinkCount == 3 || card.LinkCount == 2)).ToList(); + List normal_materials = tempmaterials.Where(card => card != null && card.LinkCount != 3 && card.LinkCount != 2).ToList(); + normal_materials.Sort(CardContainer.CompareCardAttack); + if (link_materials.Count <= 0 && Card.Id == CardId.AccesscodeTalker) return false; + if (link_materials.Count(card => card != null && card.LinkCount == 3) > 0 && normal_materials.Count() > 0) + { + int index = -1; + for (int i = 0; i < link_materials.Count(); i++) + { + if (link_materials[i] != null && link_materials[i].LinkCount == 3) + { + if (i > 0) + { + ClientCard temp = link_materials[0]; + link_materials[0] = link_materials[i]; + link_materials[i] = temp; + } + index = i; + break; + } + } + resMaterials.Sort(CardContainer.CompareCardAttack); + if (index >= 0) link_materials.InsertRange(index + 1, normal_materials); + materials.AddRange(link_materials); + } + else + { + link_materials.Sort(CompareCardLink); + materials.AddRange(link_materials); + materials.AddRange(normal_materials); + } + foreach (var card in materials) + { + if (!resMaterials.Contains(card) && card.LinkCount < 4) + { + if (Card.Id == CardId.BowoftheGoddess && resMaterials.Count(_card => _card != null && _card.Id == card.Id) > 0) break; + resMaterials.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 4) break; + } + } + resMaterials.Sort(CardContainer.CompareCardAttack); + if (link_count >= 4) { AI.SelectMaterials(resMaterials); place_Link_4 = true; return true; } + return false; + } + private bool TheChaosCreatorSummon() + { + IList cardsid = new List(); + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Grave) && Bot.GetMonstersInMainZone().Count < 4) + cardsid.Add(CardId.ThunderDragonroar); + if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Grave)) + cardsid.Add(CardId.ThunderDragondark); + if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Grave)) + cardsid.Add(CardId.ThunderDragonmatrix); + if (Bot.HasInGraveyard(CardId.ChaosSpace) && !activate_ChaosSpace_grave) + { + cardsid.Add(CardId.BlackDragonCollapserpent); + cardsid.Add(CardId.WhiteDragonWyverburster); + cardsid.Add(CardId.TheBystialLubellion); + cardsid.Add(CardId.ThunderDragonlord); + } + if (!Bot.HasInSpellZone(CardId.BrandedRegained, true, true) + || Bot.GetCountCardInZone(Bot.GetGraveyardMonsters(),CardId.BystialMagnamhut) + Bot.GetCountCardInZone(Bot.GetGraveyardMonsters(), CardId.BystialDruiswurm) > 1) + { + cardsid.Add(CardId.BystialMagnamhut); + cardsid.Add(CardId.BystialDruiswurm); + } + List cards = Bot.GetGraveyardMonsters().Where(card => card != null && (card.HasAttribute(CardAttribute.Dark) || card.HasAttribute(CardAttribute.Light))).ToList(); + cards.Sort(CardContainer.CompareCardAttack); + foreach (var card in cards) + if (card != null) cardsid.Add(card.Id); + AI.SelectCard(cardsid); + AI.SelectCard(cardsid); + return true; + } + private bool ThunderDragonColossusSummon() + { + ResetFlag(); + selectFlag[(int)Select.ThunderDragonColossus] = true; + place_ThunderDragonColossus = true; + return true; + } + private bool ThunderDragonmatrixSet() + { + if (handActivated && Bot.HasInExtra(CardId.ThunderDragonColossus) + && Bot.GetMonsters().Count(card=>card != null && card.HasRace(CardRace.Thunder) + && card.IsFaceup() && card.HasType(CardType.Effect)) <= 0) + { + isSummoned = true; + return true; + } + return false; + } + private bool IPSummon() + { + if (Duel.Turn > 0 && Duel.Phase < DuelPhase.Main2) return false; + if (Bot.GetMonsterCount() <= 2) return false; + if (Bot.HasInMonstersZone(CardId.ThunderDragonColossus) && Bot.GetMonsterCount() <= 3) return false; + if (!Bot.HasInExtra(CardId.KnightmareUnicorn) && !Bot.HasInExtra(CardId.BowoftheGoddess) + && !Bot.HasInExtra(CardId.MekkKnightCrusadiaAvramax) && !Bot.HasInExtra(CardId.AccesscodeTalker) && !Bot.HasInExtra(CardId.UnderworldGoddessoftheClosedWorld)) return false; + List cards = Bot.GetMonsters().Where(card => card != null && GetLinkMark(card.Id) < 3 && card.Id != CardId.ThunderDragonTitan && card.Id != CardId.ThunderDragonColossus && !card.HasType(CardType.Link) && card.Attack <= 2500 && card.EquipCards.Count(ecard=> ecard != null && ecard.Id==CardId.DragonBusterDestructionSword && !ecard.IsDisabled())<=0).ToList(); + if (cards.Count < 2) return false; + if (!IsAvailableLinkZone()) return false; + cards.Sort(CardContainer.CompareCardAttack); + List cardsId = new List(); + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.MonsterZone)) + cardsId.Add(CardId.ThunderDragonroar); + if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.MonsterZone)) + cardsId.Add(CardId.ThunderDragondark); + if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.MonsterZone)) + cardsId.Add(CardId.ThunderDragonmatrix); + foreach (var card in cards) + if (card != null) cardsId.Add(card.Id); + AI.SelectMaterials(cardsId); + return true; + } + private bool ThunderDragonlordSummon() + { + if (Bot.GetMonstersInMainZone().Count > 4 && Bot.GetMonstersInMainZone().Count(card => card != null && card.Level <= 8 && card.HasType(CardType.Tuner) && !card.IsExtraCard() && card.IsFaceup()) <= 0) return false; + IList cardsId = new List(); + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Hand) + || HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.MonsterZone, true)) + cardsId.Add(CardId.ThunderDragonroar); + if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Hand) + || HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.MonsterZone, true)) + cardsId.Add(CardId.ThunderDragondark); + if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Hand) + || HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.MonsterZone, true)) + cardsId.Add(CardId.ThunderDragonmatrix); + List handCards = Bot.Hand.Where(card=>card != null).ToList(); + handCards.Sort(CardContainer.CompareCardLevel); + List monsterCards = Bot.GetMonsters().ToList(); + monsterCards.Sort(CardContainer.CompareCardAttack); + foreach (var card in handCards) + { + if (card != null && card.HasRace(CardRace.Thunder) && card.Level <= 8) + cardsId.Add(card.Id); + } + foreach (var card in monsterCards) + { + if (card != null && card.HasRace(CardRace.Thunder) && card.Level <= 8 + && card.Id != CardId.ThunderDragonColossus && card.IsFaceup()) + cardsId.Add(card.Id); + } + if (cardsId.Count <= 0) return false; + AI.SelectCard(cardsId); + return true; + } + private bool UnionCarrierEffect() + { + if (!Bot.HasInMonstersZone(CardId.ThunderDragonColossus)) return false; + return UnionCarrierEffect_2(); + } + private bool UnionCarrierEffect_2() + { + IList cardsId = new List(); + cardsId.Add(CardId.ThunderDragonColossus); + cardsId.Add(CardId.TheChaosCreator); + List cards_1 = Bot.GetMonsters().Where(card => card != null && card.IsFaceup() && (card.HasAttribute(CardAttribute.Dark) || card.HasRace(CardRace.Dragon))).ToList(); + if (cards_1.Count <= 0) + { + List cards_2 = Bot.GetMonsters(); + cards_2.Sort(CardContainer.CompareCardAttack); + cards_2.Reverse(); + foreach (var card in cards_2) + if (card != null && !cardsId.Contains(card.Id)) + cardsId.Add(card.Id); + } + else + { + cards_1.Sort(CardContainer.CompareCardAttack); + cards_1.Reverse(); + foreach (var card in cards_1) + if (card != null && !cardsId.Contains(card.Id)) + cardsId.Add(card.Id); + } + AI.SelectCard(cardsId); + AI.SelectNextCard(CardId.DragonBusterDestructionSword,CardId.ThunderDragonroar,CardId.ThunderDragondark,CardId.ThunderDragonmatrix,CardId.NormalThunderDragon); + return true; + } + private bool StrikerDragonSummon() + { + if ((summon_WhiteDragonWyverburster && summon_BlackDragonCollapserpent) || CheckRemainInDeck(CardId.WhiteDragonWyverburster) <= 0 || CheckRemainInDeck(CardId.BlackDragonCollapserpent) <= 0) return false; + return Bot.GetMonsters().Count(card => card != null && card.HasRace(CardRace.Dragon) && card.Level > 1) > 0; + } + private bool DefaultSummon() + { + if (No_SpSummon) return false; + if (Card.Id == CardId.AshBlossom || Card.Id == CardId.G) + { + if (Bot.GetMonsterCount() >= 2 || handActivated) return false; + if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.MonsterZone, true) + || HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.MonsterZone, true)) + { + if (Bot.HasInExtra(CardId.PredaplantVerteAnaconda) || Bot.HasInExtra(CardId.IP) || Bot.HasInExtra(CardId.CrossSheep)) return true; + } + return false; + } + if (Card.Level == 1) + { + if (Bot.ExtraDeck.Count(card => card != null && card.LinkCount <= 2) <= 0) return false; + } + else + { + if (Bot.ExtraDeck.Count(card => card != null && card.LinkCount == 2) <= 0) return false; + } + if (Card.Id == CardId.ThunderDragonroar || Card.Id == CardId.ThunderDragondark || Card.Id == CardId.NormalThunderDragon) + { + if (!Bot.HasInExtra(CardId.ThunderDragonColossus) || !handActivated) return false; + } + if (Card.Level > 4) + { + List cards = Bot.GetMonsters().Where(card => card != null && GetLinkMark(card.Id) < 3 && card.Id != CardId.ThunderDragonTitan && card.Id != CardId.ThunderDragonColossus && card.Id != CardId.IP && card.Id != CardId.UnionCarrier).ToList(); + if (cards.Count <= 0) return false; + cards.Sort(CardContainer.CompareCardAttack); + if (handActivated && cards[0].Attack >= Card.Attack && !Bot.HasInExtra(CardId.ThunderDragonColossus)) return false; + AI.SelectCard(cards); + } + isSummoned = true; + return true; + } + private bool CheckThunderRemove() + { + if(HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Hand) && GetRemainingThunderCount() > 0) return true; + if(HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Hand) && GetRemainingThunderCount() > 0) return true; + if(Bot.Hand.Any(card=> card != null && card.HasRace(CardRace.Thunder) && !card.IsOriginalCode(CardId.AloofLupine) + && (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck) || HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck)))) return true; + return false; + } + private bool ThunderDragonhawkEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + List banish_cards = new List(); + List grave_cards = new List(); + foreach (var card in Bot.Banished) + if (card != null && card.HasType(CardType.Monster) && card.HasSetcode(0x11c)) + banish_cards.Add(card); + foreach (var card in Bot.Graveyard) + if (card != null && card.HasType(CardType.Monster) && card.HasSetcode(0x11c)) + grave_cards.Add(card); + banish_cards.Sort(CardContainer.CompareCardAttack); + banish_cards.Reverse(); + grave_cards.Sort(CardContainer.CompareCardAttack); + grave_cards.Reverse(); + banish_cards.AddRange(grave_cards); + List res = new List(); + foreach (var card in banish_cards) + { + if (!activate_ThunderDragonroar && card != null && card.Id == CardId.ThunderDragonroar) + res.Add(card); + else if (!activate_ThunderDragondark && card != null && card.Id == CardId.ThunderDragondark) + res.Add(card); + } + res.AddRange(banish_cards); + AI.SelectCard(res); + handActivated = true; + activate_ThunderDragonhawk = true; + return true; + + } + else + { + activate_ThunderDragonhawk = true; + List cardsid = new List() { CardId.DragonBusterDestructionSword }; + cardsid.AddRange(GetZoneRepeatCardsId(0, Bot.Hand)); + List resCards = new List(); + foreach (var card in Bot.Hand) + { + if (card != null && cardsid.Contains(card.Id) && resCards.Count(_card => _card != null && _card.Id == card.Id) <= 0) + { + resCards.Add(card); + } + } + if (resCards.Count() <= 0) return false; + AI.SelectCard(resCards); + return true; + } + } + private bool BlackDragonCollapserpentSummon_2() + { + if (Bot.HasInGraveyard(CardId.WhiteDragonWyverburster) && Bot.HasInGraveyard(CardId.ChaosSpace) + && !activate_ChaosSpace_grave) + AI.SelectCard(CardId.WhiteDragonWyverburster); + else if (Bot.HasInGraveyard(CardId.ThunderDragonlord) && Bot.HasInGraveyard(CardId.ChaosSpace) + && !activate_ChaosSpace_grave) + AI.SelectCard(CardId.ThunderDragonlord); + else if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Grave)) + AI.SelectCard(CardId.ThunderDragonmatrix); + else if (HasInZoneNoActivate(CardId.ThunderDragonhawk, CardLocation.Grave) && !(GetZoneRepeatCardsId(0, Bot.Hand, false)).Contains(-1)) + AI.SelectCard(CardId.ThunderDragonhawk); + else + AI.SelectCard(CardId.WhiteDragonWyverburster, CardId.BatterymanSolar); + summon_BlackDragonCollapserpent = true; + return true; + } + private bool BlackDragonCollapserpentSummon() + { + if (Bot.Graveyard.Count(card => card != null && card.HasAttribute(CardAttribute.Light)) <= 1 + && Bot.HasInGraveyard(CardId.TheBystialLubellion) && CheckRemainInDeck(CardId.BrandedRegained) > 0 && !summon_TheBystialLubellion) + return false; + return BlackDragonCollapserpentSummon_2(); + } + private bool GoldSarcophagusEffect() + { + if (GetRemainingThunderCount() <= 0) return false; + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck) && Bot.GetMonstersInMainZone().Count < 5) + AI.SelectCard(CardId.ThunderDragonroar); + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragondark); + else if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragonmatrix); + else AI.SelectCard(CardId.ThunderDragonmatrix); + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + return true; + } + private bool UnionCarrierSummon() + { + if (CheckRemainInDeck(CardId.DragonBusterDestructionSword) <= 0 || !Bot.HasInMonstersZone(CardId.ThunderDragonColossus,false,false,true)) return false; + return UnionCarrierSummon_2(); + } + private bool LinkCheck(bool exZone_1) + { + int exSq = 0; + int linkSq_1 = 0; + int linkSq_2 = 0; + if (exZone_1) + { + exSq = 5; + linkSq_1 = 0; + linkSq_2 = 2; + } + else + { + exSq = 6; + linkSq_1 = 2; + linkSq_2 = 4; + } + if (Bot.MonsterZone[exSq] != null && Bot.HasInMonstersZone(CardId.ThunderDragonColossus, false, false, true)) + { + CardRace linkRace = (CardRace)Bot.MonsterZone[exSq].Race; + CardAttribute linkAtt = (CardAttribute)Bot.MonsterZone[exSq].Attribute; + int linkRaceCount = Bot.GetMonsters().Count(card => card != null && card.IsFaceup() && !card.IsCode(CardId.ThunderDragonColossus) && card.HasRace(linkRace)); + int linkAttCount = Bot.GetMonsters().Count(card => card != null && card.IsFaceup() && !card.IsCode(CardId.ThunderDragonColossus) && card.HasAttribute(linkAtt)); + if (Bot.MonsterZone[exSq].Id == CardId.CrossSheep + || Bot.MonsterZone[exSq].Id == CardId.PredaplantVerteAnaconda + || Bot.MonsterZone[exSq].Id == CardId.IP + || Bot.MonsterZone[exSq].Id == CardId.MekkKnightCrusadiaAvramax) + { + if (Bot.MonsterZone[linkSq_1] != null && Bot.MonsterZone[linkSq_1].Id == CardId.ThunderDragonColossus) + { + if (Bot.MonsterZone[linkSq_2] != null) + { + CardRace race = (CardRace)Bot.MonsterZone[linkSq_2].Race; + CardAttribute att = (CardAttribute)Bot.MonsterZone[linkSq_2].Attribute; + int raceCount = Bot.GetMonsters().Count(card => card != null && card.IsFaceup() && !card.IsCode(CardId.ThunderDragonColossus) && card.HasRace(race)); + int attCount = Bot.GetMonsters().Count(card => card != null && card.IsFaceup() && !card.IsCode(CardId.ThunderDragonColossus) && card.HasAttribute(att)); + if (raceCount < 2 && attCount < 2 && linkRaceCount < 2 && linkAttCount < 2) return false; + } + } + else if (Bot.MonsterZone[linkSq_2] != null && Bot.MonsterZone[linkSq_2].Id == CardId.ThunderDragonColossus) + { + if (Bot.MonsterZone[linkSq_1] != null) + { + CardRace race = (CardRace)Bot.MonsterZone[linkSq_1].Race; + CardAttribute att = (CardAttribute)Bot.MonsterZone[linkSq_1].Attribute; + int raceCount = Bot.GetMonsters().Count(card => card != null && card.IsFaceup() && !card.IsCode(CardId.ThunderDragonColossus) && card.HasRace(race)); + int attCount = Bot.GetMonsters().Count(card => card != null && card.IsFaceup() && !card.IsCode(CardId.ThunderDragonColossus) && card.HasAttribute(att)); + if (raceCount < 2 && attCount < 2 && linkRaceCount < 2 && linkAttCount < 2) return false; + } + + } + } + } + return true; + } + private bool UnionCarrierSummon_2() + { + if (Bot.GetMonsterCount() <= 2 && (Bot.HasInMonstersZone(CardId.ThunderDragonColossus) || Bot.HasInMonstersZone(CardId.ThunderDragonTitan))) return false; + List attDarkCards = Bot.GetMonsters().Where(card => card != null && card.HasAttribute(CardAttribute.Dark) && card.IsFaceup() && !card.IsOriginalCode(CardId.ThunderDragonColossus) && GetLinkMark(card.Id) < 3).ToList(); + List attLightCards = Bot.GetMonsters().Where(card => card != null && card.HasAttribute(CardAttribute.Light) && card.IsFaceup() && GetLinkMark(card.Id) < 3).ToList(); + List attEarthCards = Bot.GetMonsters().Where(card => card != null && card.HasAttribute(CardAttribute.Earth) && card.IsFaceup() && GetLinkMark(card.Id) < 3).ToList(); + List raceThunderCards = Bot.GetMonsters().Where(card => card != null && card.HasRace(CardRace.Thunder) && card.IsFaceup() && !card.IsOriginalCode(CardId.ThunderDragonColossus) && GetLinkMark(card.Id) < 3).ToList(); + List raceDragonCards = Bot.GetMonsters().Where(card => card != null && card.HasRace(CardRace.Dragon) && card.IsFaceup() && GetLinkMark(card.Id) < 3).ToList(); + List raceBeastCards = Bot.GetMonsters().Where(card => card != null && card.HasRace(CardRace.Beast) && card.IsFaceup() && GetLinkMark(card.Id) < 3).ToList(); + if (attDarkCards.Count() < 2 && attLightCards.Count() < 2 && attEarthCards.Count() < 2 + && raceThunderCards.Count() < 2 && raceDragonCards.Count() < 2 && raceBeastCards.Count() < 2) + return false; + if (!LinkCheck(false) || !LinkCheck(true)) return false; + if (!IsAvailableLinkZone()) return false; + if (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].Controller == 0 && GetLinkMark(Bot.MonsterZone[6].Id) > 1) return false; + int[] materials = new[] { + CardId.StrikerDragon,CardId.BatterymanToken,CardId.BatterymanSolar, + CardId.ThunderDragonmatrix,CardId.NormalThunderDragon, CardId.WhiteDragonWyverburster, + CardId.ThunderDragonhawk,CardId.G, CardId.AloofLupine, CardId.CrossSheep, + CardId.ThunderDragonroar,CardId.ThunderDragondark,CardId.BlackDragonCollapserpent, + CardId.DragonBusterDestructionSword,CardId.BystialMagnamhut,CardId.BystialDruiswurm, + CardId.TheChaosCreator,CardId.Linkuriboh,CardId.TheBystialLubellion, + CardId.ThunderDragonlord,CardId.PredaplantVerteAnaconda,CardId.IP + }; + if (Bot.MonsterZone.GetMatchingCardsCount(card => card.IsCode(materials)) >= 2) + { + AI.SelectMaterials(materials); + summon_UnionCarrier = true; + return true; + } + return false; + } + private bool BatterymanSolarSummon() + { + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck) || HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck) + || HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Deck) || HasInZoneNoActivate(CardId.BlackDragonCollapserpent, CardLocation.Hand) + || HasInZoneNoActivate(CardId.WhiteDragonWyverburster, CardLocation.Hand) || HasInZoneNoActivate(CardId.BystialDruiswurm, CardLocation.Hand) + || HasInZoneNoActivate(CardId.BystialMagnamhut, CardLocation.Hand) || Bot.HasInHand(CardId.TheChaosCreator)) + { + isSummoned = true; + return true; + } + return false; + } + private bool ThunderDragonroarEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (handActivated) return false; + handActivated = true; + activate_ThunderDragonroar = true; + if (HasInZoneNoActivate(CardId.ThunderDragonhawk, CardLocation.Grave) + || HasInZoneNoActivate(CardId.ThunderDragonhawk, CardLocation.Removed)) + { + AI.SelectCard(CardId.ThunderDragonhawk); + } + else AI.SelectCard(CardId.ThunderDragonmatrix,CardId.ThunderDragondark,CardId.ThunderDragonhawk); + return true; + } + else + { + if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragondark); + else if(HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragonmatrix); + else if(HasInZoneNoActivate(CardId.NormalThunderDragon, CardLocation.Deck)) + AI.SelectCard(CardId.NormalThunderDragon); + else + AI.SelectCard(CardId.NormalThunderDragon, CardId.ThunderDragondark, CardId.NormalThunderDragon, CardId.ThunderDragonmatrix); + activate_ThunderDragonroar = true; + return true; + } + } + private bool S_SpSummon() + { + if (Duel.Player == 0) + { + if (Duel.CurrentChain.Count > 0) return false; + List cards = new List(); + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Grave) + && Bot.GetMonstersInMainZone().Count < 4) + { + foreach (var card_1 in Bot.Graveyard) + { + if (card_1 != null && card_1.Id == CardId.ThunderDragonroar) + cards.Add(card_1); + } + } + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Grave)) + { + foreach (var card_2 in Bot.Graveyard) + { + if (card_2 != null && card_2.Id == CardId.ThunderDragondark) + cards.Add(card_2); + } + } + else if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Grave)) + { + foreach (var card_3 in Bot.Graveyard) + { + if (card_3 != null && card_3.Id == CardId.ThunderDragonmatrix) + cards.Add(card_3); + } + } + else if (Bot.HasInGraveyard(CardId.ChaosSpace) && !activate_ChaosSpace_grave) + { + foreach (var card_4 in Bot.Graveyard) + { + if (card_4 != null && NotSpSummonCardsId.Contains(card_4.Id)) + cards.Add(card_4); + } + } + else + { + foreach (var card_5 in Enemy.Graveyard) + { + if (card_5 != null && (card_5.HasAttribute(CardAttribute.Light) + || card_5.HasAttribute(CardAttribute.Dark))) + cards.Add(card_5); + } + foreach (var card_6 in Bot.Graveyard) + { + if (card_6 != null && (card_6.HasAttribute(CardAttribute.Light) + || card_6.HasAttribute(CardAttribute.Dark)) && !card_6.IsCode(CardId.TheBystialLubellion) && !card_6.HasRace(CardRace.Thunder)) + cards.Add(card_6); + } + foreach (var card_7 in Bot.Graveyard) + { + if (card_7 != null && (card_7.HasAttribute(CardAttribute.Light) + || card_7.HasAttribute(CardAttribute.Dark)) && card_7.HasRace(CardRace.Thunder)) + cards.Add(card_7); + } + } + AI.SelectCard(cards); + return true; + } + else + { + if (Duel.Phase < DuelPhase.Battle && Duel.CurrentChain.Count <= 0) return false; + ClientCard card = Util.GetLastChainCard(); + if (card != null && card.Controller != 0 && + card.Location == CardLocation.Grave + && (card.HasAttribute(CardAttribute.Dark) + || card.HasAttribute(CardAttribute.Light))) + { + AI.SelectCard(card); + } + else if (Duel.CurrentChain.Count > 0 && Duel.CurrentChain.Count(_card => _card != null && (_card.Id == CardId.BystialDruiswurm || _card.Id == CardId.BystialMagnamhut)) <= 0 + && Duel.LastChainPlayer == 1 && Enemy.Graveyard.Count(_card => _card != null && (_card.HasAttribute(CardAttribute.Dark) || _card.HasAttribute(CardAttribute.Light))) > 0) + { + List graveCards = Enemy.GetGraveyardMonsters(); + graveCards.Reverse(); + AI.SelectCard(graveCards); + } + else + { + if (Duel.CurrentChain.Count > 0 && Duel.CurrentChain.Count(_card => _card != null && _card.Controller == 0 && (_card.Id == CardId.BystialDruiswurm || _card.Id == CardId.BystialMagnamhut)) > 0) return false; + List res = new List(); + List pre_res = new List(); + foreach (var mcard in Enemy.Graveyard) + { + if (mcard != null && (mcard.HasAttribute(CardAttribute.Dark) + || mcard.HasAttribute(CardAttribute.Light))) + res.Add(mcard); + } + foreach (var mcard in Bot.Graveyard) + { + if (mcard != null && (mcard.HasAttribute(CardAttribute.Dark) + || mcard.HasAttribute(CardAttribute.Light))) + { + if (mcard.Id == CardId.ThunderDragonroar && !activate_ThunderDragonroar && Bot.GetMonstersInMainZone().Count < 5) + res.Add(mcard); + else if(mcard.Id == CardId.ThunderDragondark && !activate_ThunderDragondark) + res.Add(mcard); + else + pre_res.Add(mcard); + } + } + if (res.Count() <= 0) return false; + if (pre_res.Count > 0) res.AddRange(pre_res); + AI.SelectCard(res); + } + return true; + } + } + private bool BystialDruiswurmEffect() + { + if (Card.Location == CardLocation.Hand) return S_SpSummon(); + else + { + List cards = Enemy.GetMonsters(); + cards.Sort(CardContainer.CompareCardAttack); + cards.Reverse(); + AI.SelectCard(cards); + return true; + } + } + private bool BystialMagnamhutEffect() + { + if (Card.Location == CardLocation.Hand) return S_SpSummon(); + return true; + } + private bool CrossSheepSummon() + { + if (Bot.MonsterZone[5] != null && Bot.MonsterZone[5].Controller == 0 && GetLinkMark(Bot.MonsterZone[5].Id) > 1) return false; + if (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].Controller == 0 && GetLinkMark(Bot.MonsterZone[6].Id) > 1) return false; + if (!handActivated && Bot.Hand.Count(card => card != null && card.HasSetcode(0x11c) && card.HasType(CardType.Monster)) + + Bot.MonsterZone.Count(card => card != null && card.HasSetcode(0x11c) && card.IsFaceup() && card.HasType(CardType.Monster)) + + Bot.Graveyard.Count(card => card != null && card.HasSetcode(0x11c) && card.HasType(CardType.Monster)) + + Bot.Banished.Count(card => card != null && card.HasSetcode(0x11c) && card.IsFaceup() && card.HasType(CardType.Monster)) < 2) return false; + if ((Bot.HasInMonstersZone(CardId.ThunderDragonColossus, false, false, true) || Bot.HasInMonstersZone(CardId.ThunderDragonTitan, false, false, true))) + { + bool isShoudlSummon_1 = false; + int light_count = Bot.Graveyard.Count(card => card != null && card.HasAttribute(CardAttribute.Light)); + int dark_count = Bot.Graveyard.Count(card => card != null && card.HasAttribute(CardAttribute.Dark)); + if (HasInZoneNoActivate(CardId.WhiteDragonWyverburster, CardLocation.Hand) && dark_count > 0) isShoudlSummon_1 = true; + else if (HasInZoneNoActivate(CardId.BlackDragonCollapserpent, CardLocation.Hand) && light_count > 0) isShoudlSummon_1 = true; + else if ((HasInZoneNoActivate(CardId.BystialMagnamhut, CardLocation.Hand) || HasInZoneNoActivate(CardId.BystialDruiswurm, CardLocation.Hand)) + && (dark_count > 0 || light_count > 0)) isShoudlSummon_1 = true; + else if (HasInZoneNoActivate(CardId.ThunderDragonhawk, CardLocation.Hand)) + { + List mcards = Bot.GetMonsters().ToList(); + List grave = Bot.Graveyard.ToList(); + List banish = Bot.Banished.ToList(); + mcards.AddRange(grave); + mcards.AddRange(banish); + int mcount = mcards.Count(card => card != null && card.HasType(CardType.Monster) && card.HasSetcode(0x11c) && !card.IsCode(CardId.ThunderDragonColossus) && !card.IsCode(CardId.ThunderDragonTitan)); + isShoudlSummon_1 = mcount > 0 ? true : false; + } + else if(Bot.HasInHand(CardId.TheChaosCreator) && light_count > 0 && dark_count > 0) isShoudlSummon_1 = true; + else if (Bot.HasInHand(CardId.ThunderDragonlord) && Bot.Hand.Count(card=>card != null && card.HasType(CardType.Monster) && card.HasSetcode(0x11c))>1) isShoudlSummon_1 = true; + if (!isShoudlSummon_1) return false; + + } + if (!IsAvailableLinkZone()) return false; + IList cardsid = GetZoneRepeatCardsId(0, Bot.MonsterZone,true); + if (!cardsid.Contains(-1) && Bot.MonsterZone.Count(card => card != null && card.IsFaceup() && !card.IsOriginalCode(CardId.ThunderDragonColossus) && GetLinkMark(card.Id) <= 1) + - cardsid.Count() < 2) return false; + if (cardsid.Contains(-1) && Bot.MonsterZone.Count(card => card != null && card.IsFaceup() && !card.IsOriginalCode(CardId.ThunderDragonColossus) && !card.IsOriginalCode(CardId.ThunderDragonTitan) && GetLinkMark(card.Id) <= 1 ) < 2) return false; + bool isShoudlSummon_2 = false; + foreach (var card in Bot.GetMonsters()) + if (card != null && card.IsFaceup() && SpSummonCardsId.Contains(card.Id)) { isShoudlSummon_2 = true; break; } + if (Bot.Graveyard.Count(card => card != null && card.HasType(CardType.Monster) && card.Level <= 4 && !card.IsCode(CardId.BlackDragonCollapserpent) && !card.IsCode(CardId.WhiteDragonWyverburster)) > 0) isShoudlSummon_2 = true; + if (!isShoudlSummon_2) return false; + List cards = Bot.GetMonsters(); + if (cards.Count < 2) return false; + cards.Sort(CardContainer.CompareCardAttack); + HashSet MaterialsIdSet = new HashSet(); + foreach (var card in cards) + { + if (card == null) continue; + if (card.Id == CardId.UnionCarrier && summon_UnionCarrier) continue; + if (GetLinkMark(card.Id) <= 1 && card.Id != CardId.ThunderDragonColossus && card.Id != CardId.ThunderDragonTitan + && (card.EquipCards == null || (card.EquipCards != null && card.EquipCards.Count(ecard => ecard != null + && ecard.Id == CardId.DragonBusterDestructionSword) <= 0))) + MaterialsIdSet.Add(card.Id); + } + if (MaterialsIdSet.Count() < 2) return false; + List material = new List(); + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.MonsterZone)) + material.Add(CardId.ThunderDragonroar); + if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.MonsterZone)) + material.Add(CardId.ThunderDragondark); + if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.MonsterZone)) + material.Add(CardId.ThunderDragonmatrix); + IList materials = MaterialsIdSet.ToList(); + material.AddRange(materials); + AI.SelectMaterials(material); + place_CrossSheep = true; + return true; + } + private bool ThunderDragonmatrixEffect() + { + if (Card.Location != CardLocation.Hand) + { + activate_ThunderDragonmatrix = true; + return true; + } + return false; + } + private bool IsShouldChainTunder() + { + ClientCard card = Util.GetLastChainCard(); + return card != null && card.Controller != 0 && Bot.HasInMonstersZone(CardId.ThunderDragonTitan, true, false, true) + && !card.IsDisabled() && (card.HasType(CardType.Monster) + || card.HasType(CardType.Continuous) || card.HasType(CardType.Equip) || card.HasType(CardType.Field)) && (card.Location == CardLocation.MonsterZone || card.Location == CardLocation.SpellZone); + } + private bool ThunderDragonmatrixEffect_2() + { + if (Card.Location == CardLocation.Hand) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Duel.Player == 0) + { + if (IsShouldChainTunder()) + { + activate_ThunderDragondark = true; + handActivated = true; + return true; + } + if (Duel.CurrentChain.Count > 0) return false; + List cards = Bot.Graveyard.ToList(); + cards.AddRange(Bot.Banished.ToList()); + if (handActivated || (HasInZoneNoActivate(CardId.ThunderDragonhawk, CardLocation.Hand) && Bot.GetMonstersInMainZone().Count < 5 + && cards.Count(card => card != null && card.HasSetcode(0x11c) && card.HasType(CardType.Monster) + && !card.IsCode(CardId.ThunderDragonhawk) && !card.IsExtraCard() && !card.IsCode(CardId.ThunderDragonlord)) > 0)) return false; + activate_ThunderDragonmatrix = true; + handActivated = true; + return true; + } + else + { + if (IsShouldChainTunder()) + { + AI.SelectCard(CardId.ThunderDragonColossus, CardId.ThunderDragonTitan); + activate_ThunderDragonmatrix = true; + handActivated = true; + return true; + } + else if (Duel.Phase == DuelPhase.Battle) + { + if (Bot.HasInMonstersZone(CardId.ThunderDragonTitan, true, false, true) && Enemy.GetMonsterCount() > 0) + { + AI.SelectCard(CardId.ThunderDragonColossus, CardId.ThunderDragonTitan); + activate_ThunderDragonmatrix = true; + handActivated = true; + return true; + } + } + else if (Duel.Phase == DuelPhase.BattleStep) + { + if (Bot.BattlingMonster != null && Bot.BattlingMonster.HasRace(CardRace.Thunder) + && !Bot.BattlingMonster.IsShouldNotBeTarget()) + { + AI.SelectCard(Bot.BattlingMonster); + activate_ThunderDragonmatrix = true; + handActivated = true; + return true; + } + } + else if(Duel.Phase == DuelPhase.End) + { + AI.SelectCard(CardId.ThunderDragonColossus, CardId.ThunderDragonTitan); + activate_ThunderDragonmatrix = true; + handActivated = true; + return true; + } + return false; + } + } + return false; + } + private bool WhiteDragonWyverbursterSummon() + { + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Grave) + && Bot.GetMonstersInMainZone().Count < 5) + AI.SelectCard(CardId.ThunderDragonroar); + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Grave)) + AI.SelectCard(CardId.ThunderDragondark); + else + { + List cardsid = new List(); + cardsid.Add(CardId.BlackDragonCollapserpent); + cardsid.Add(CardId.TheChaosCreator); + foreach (var card in Bot.Graveyard) + { + if (card != null && !card.HasSetcode(0x11c) && card.HasAttribute(CardAttribute.Dark)) + cardsid.Add(card.Id); + } + foreach (var card in Bot.Graveyard) + { + if (card != null && card.HasSetcode(0x11c) && card.HasAttribute(CardAttribute.Dark)) + cardsid.Add(card.Id); + } + + AI.SelectCard(cardsid); + } + summon_WhiteDragonWyverburster = true; + return true; + } + private bool HasInZoneNoActivate(int cardId , CardLocation location , bool isFaceUp = false) + { + switch (location) + { + case CardLocation.Deck: if (CheckRemainInDeck(cardId) <= 0) return false; break; + case CardLocation.Hand: if (!Bot.HasInHand(cardId)) return false; break; + case CardLocation.Grave: if (!Bot.HasInGraveyard(cardId)) return false; break; + case CardLocation.Removed: if (!Bot.HasInBanished(cardId)) return false; break; + case CardLocation.MonsterZone: if (!Bot.HasInMonstersZone(cardId,false,false, isFaceUp)) return false; break; + default: return false; + } + switch (cardId) + { + case CardId.ThunderDragonroar: return !activate_ThunderDragonroar; + case CardId.ThunderDragondark: return !activate_ThunderDragondark; + case CardId.ThunderDragonhawk: return !activate_ThunderDragonhawk; + case CardId.ThunderDragonmatrix: return !activate_ThunderDragonmatrix; + case CardId.BystialDruiswurm: return !activate_BystialDruiswurm_hand; + case CardId.BystialMagnamhut: return !activate_BystialMagnamhut_hand; + case CardId.TheBystialLubellion: return !activate_TheBystialLubellion_hand; + case CardId.BlackDragonCollapserpent: return !summon_BlackDragonCollapserpent; + case CardId.WhiteDragonWyverburster: return !summon_WhiteDragonWyverburster; + default: return false; + } + } + private bool AloofLupineEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (Bot.Hand.Count(card => card != null && card.HasRace(CardRace.Thunder)) <= 0) return false; + bool _ThunderDragonroar = false, _ThunderDragondark = false, _ThunderDragonmatrix = false; + if (Bot.Hand.Count(card => card != null && card.HasRace(CardRace.Thunder) && !(card.IsCode(CardId.ThunderDragonhawk) && activate_ThunderDragonhawk)) <= 0 + && GetRemainingThunderCount(true) <= 0) return false; + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Hand) && Bot.GetMonstersInMainZone().Count() < 5 + && GetRemainingThunderCount() > 0) + { + AI.SelectCard(CardId.ThunderDragonroar); + _ThunderDragonroar = true; + } + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Hand) && GetRemainingThunderCount() > 0) + { + AI.SelectCard(CardId.ThunderDragondark); + _ThunderDragondark = true; + } + else if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Hand) && GetRemainingThunderCount() > 0) + { + AI.SelectCard(CardId.ThunderDragonmatrix); + _ThunderDragonmatrix = true; + } + else if (Bot.GetCountCardInZone(Bot.Hand, CardId.NormalThunderDragon) > 1) + AI.SelectCard(CardId.NormalThunderDragon); + else + { + IList cards = Bot.Hand.Where(card => card != null && card.HasRace(CardRace.Thunder)).ToList(); + if (cards.Count() > 0) AI.SelectCard(cards); + else AI.SelectCard(CardId.ThunderDragonlord, CardId.BatterymanSolar, CardId.TheChaosCreator, CardId.NormalThunderDragon); + } + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck) && !_ThunderDragonroar + && Bot.GetMonstersInMainZone().Count < 5 && !Bot.HasInMonstersZone(CardId.ThunderDragonroar,false,false,true)) + AI.SelectNextCard(CardId.ThunderDragonroar); + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck) && !_ThunderDragondark + && !Bot.HasInMonstersZone(CardId.ThunderDragondark, false, false, true)) + AI.SelectNextCard(CardId.ThunderDragondark); + else if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Deck) && !_ThunderDragonmatrix + && !Bot.HasInMonstersZone(CardId.ThunderDragonmatrix, false, false, true)) + AI.SelectNextCard(CardId.ThunderDragonmatrix); + else if(Bot.HasInGraveyard(CardId.TheChaosCreator) && !activate_ChaosSpace_grave && CheckRemainInDeck(CardId.ThunderDragonlord) > 0) + AI.SelectNextCard(CardId.ThunderDragonlord); + else + AI.SelectNextCard(CardId.NormalThunderDragon); + return true; + } + else + { + int[] ids = new int[] + { + CardId.ThunderDragonhawk,CardId.ThunderDragonColossus, + CardId.BystialMagnamhut,CardId.BystialDruiswurm, + CardId.BlackDragonCollapserpent,CardId.WhiteDragonWyverburster, + CardId.TheChaosCreator,CardId.TheBystialLubellion + }; + AI.SelectCard(ids); + return true; + } + + } + private bool ThunderDragonmatrixSummon() + { + if (No_SpSummon) return false; + if (Bot.HasInExtra(CardId.Linkuriboh)) + { + if (Bot.MonsterZone[5] != null && Bot.MonsterZone[5].Id == CardId.UnionCarrier && Bot.MonsterZone[5].Controller == 0) + { + if (Bot.MonsterZone[1] != null) return false; + } + if (Bot.MonsterZone[6] != null && Bot.MonsterZone[6].Id == CardId.UnionCarrier && Bot.MonsterZone[6].Controller == 0) + { + if (Bot.MonsterZone[3] != null) return false; + } + isSummoned = true; + return true; + } + if (Bot.GetMonsters().Count(card => card != null && card.Id != CardId.ThunderDragonTitan && card.Id != CardId.ThunderDragonColossus && GetLinkMark(card.Id) < 3 && card.IsFaceup()) < 1) return false; + switch (Card.Id) + { + case CardId.ThunderDragonmatrix: + if((Bot.HasInExtra(CardId.CrossSheep) || Bot.HasInExtra(CardId.IP)) + && (Bot.GetMonsterCount()>0 && !Bot.HasInMonstersZone(CardId.ThunderDragonColossus) + && !Bot.HasInMonstersZone(CardId.ThunderDragonTitan))) + { isSummoned = true; return true; } + break; + default: + break; + } + return false; + } + private bool TheBystialLubellionEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (HasInZoneNoActivate(CardId.BystialMagnamhut,CardLocation.Deck) && !Bot.HasInHand(CardId.BystialMagnamhut)) + AI.SelectCard(CardId.BystialMagnamhut); + else if(HasInZoneNoActivate(CardId.BystialDruiswurm, CardLocation.Deck) && !Bot.HasInHand(CardId.BystialDruiswurm)) + AI.SelectCard(CardId.BystialDruiswurm); + else + AI.SelectCard(CardId.BystialDruiswurm, CardId.BystialMagnamhut); + activate_TheBystialLubellion_hand = true; + return true; + } + return Card.Location == CardLocation.MonsterZone; + } + private bool ThunderDragonFusionEffect() + { + if (Card.Location == CardLocation.Grave) + { + if (Bot.Graveyard.Count(card => card != null && card.HasAttribute(CardAttribute.Dark)) > 0 + && Bot.Graveyard.Count(card => card != null && card.HasAttribute(CardAttribute.Light)) > 0 + && CheckRemainInDeck(CardId.TheChaosCreator) > 0) + AI.SelectCard(CardId.TheChaosCreator); + else if(Bot.HasInGraveyardOrInBanished(CardId.ThunderDragonroar) || Bot.HasInGraveyardOrInBanished(CardId.ThunderDragondark) + || Bot.HasInGraveyardOrInBanished(CardId.ThunderDragonlord) || Bot.HasInGraveyardOrInBanished(CardId.ThunderDragonmatrix) + || Bot.HasInGraveyardOrInBanished(CardId.NormalThunderDragon) && CheckRemainInDeck(CardId.ThunderDragonhawk) > 0) + AI.SelectCard(CardId.ThunderDragonhawk); + else if((HasInZoneNoActivate(CardId.BystialDruiswurm,CardLocation.Hand) || HasInZoneNoActivate(CardId.BystialMagnamhut, CardLocation.Hand) + || HasInZoneNoActivate(CardId.WhiteDragonWyverburster, CardLocation.Hand) || HasInZoneNoActivate(CardId.BlackDragonCollapserpent, CardLocation.Hand) + || HasInZoneNoActivate(CardId.TheChaosCreator, CardLocation.Hand)) && CheckRemainInDeck(CardId.BatterymanSolar) > 0) + AI.SelectCard(CardId.BatterymanSolar); + else if(Bot.HasInMonstersZone(CardId.ThunderDragonTitan,true,false,true) && CheckRemainInDeck(CardId.NormalThunderDragon)>1) + AI.SelectCard(CardId.NormalThunderDragon); + else if(!HasInZoneNoActivate(CardId.ThunderDragonroar,CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragonroar); + else if(handActivated && CheckRemainInDeck(CardId.ThunderDragonlord) > 0) + AI.SelectCard(CardId.ThunderDragonlord); + else + AI.SelectCard(CardId.TheChaosCreator,CardId.ThunderDragondark,CardId.ThunderDragonlord); + return true; + } + else + { + if (Bot.GetMonstersInMainZone().Count > 4 && Bot.GetMonstersInMainZone().Count(card => card != null && !card.IsExtraCard() && card.HasSetcode(0x11c) && card.HasType(CardType.Monster) && card.IsFaceup()) <= 0) return false; + List cards = Bot.Graveyard.ToList(); + IList banish = Bot.Banished; + cards.AddRange(banish); + if (Bot.HasInExtra(CardId.ThunderDragonColossus) && Bot.GetCountCardInZone(cards, CardId.NormalThunderDragon) >= 1 && + Bot.GetCountCardInZone(cards, CardId.NormalThunderDragon) + cards.Count(card => card != null && card.HasSetcode(0x11c) && card.HasType(CardType.Monster) && !card.IsCode(CardId.NormalThunderDragon)) > 1) + { + AI.SelectCard(CardId.ThunderDragonColossus, CardId.ThunderDragonTitan); + return true; + } + else if (Bot.HasInExtra(CardId.ThunderDragonTitan) && cards.Count(card => card != null && card.HasSetcode(0x11c) && card.HasType(CardType.Monster)) >= 3) + { + AI.SelectCard(CardId.ThunderDragonColossus, CardId.ThunderDragonTitan); + return true; + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + return false; + } + } + private bool TheBystialLubellionSummon() + { + if (Bot.HasInGraveyard(CardId.TheBystialLubellion) && Card.Location == CardLocation.Hand) return false; + if (Card.Location == CardLocation.Hand && activate_TheBystialLubellion_hand && !Bot.HasInGraveyard(CardId.TheBystialLubellion)) { summon_TheBystialLubellion = true; return true; } + if (Card.Location == CardLocation.Grave) { summon_TheBystialLubellion = true; return true; } + return false; + } + private bool CheckHandThunder() + { + if (HasInZoneNoActivate(CardId.ThunderDragonroar,CardLocation.Hand)) return true; + if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Hand)) return true; + if (HasInZoneNoActivate(CardId.ThunderDragonhawk, CardLocation.Hand)) return true; + if (Bot.HasInHand(CardId.NormalThunderDragon)) return true; + return false; + } + private bool ChaosSpaceEffect_2() + { + if (Card.Location == CardLocation.Grave) + { + if((CheckRemainInDeck(CardId.ThunderDragonFusion)>0 || Bot.HasInHandOrInSpellZone(CardId.ThunderDragonFusion)) + && !Bot.HasInExtra(CardId.ThunderDragonTitan)) + AI.SelectCard(CardId.ThunderDragonTitan,CardId.ThunderDragonColossus, CardId.BlackDragonCollapserpent, CardId.WhiteDragonWyverburster, CardId.TheBystialLubellion); + else + AI.SelectCard(CardId.ThunderDragonColossus,CardId.WhiteDragonWyverburster, CardId.BlackDragonCollapserpent, CardId.TheBystialLubellion); + activate_ChaosSpace_grave = true; + return true; + } + return false; + } + private bool ChaosSpaceEffect() + { + if (Card.Location != CardLocation.Grave) + { + if (Bot.GetCountCardInZone(Bot.Hand, CardId.ThunderDragonmatrix) > 1 && !activate_ThunderDragonmatrix + && !CheckHandThunder() && Bot.Hand.Any(card => card != null && + (card.HasAttribute(CardAttribute.Dark) || card.HasAttribute(CardAttribute.Light)) + && !card.IsCode(CardId.ThunderDragonroar) && !card.IsCode(CardId.ThunderDragondark) && !card.IsCode(CardId.ThunderDragonhawk) + && !card.IsCode(CardId.NormalThunderDragon))) return false; + ResetFlag(); + selectFlag[(int)Select.ChaosSpace_1] = true; + activate_ChaosSpace_hand = true; + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + return true; + } + return false; + } + private bool AloofLupineSummon() + { + if (Bot.Hand.Count <= 1 || !Bot.Hand.Any(card => card!=null && card.HasRace(CardRace.Thunder) && card != Card)) return false; + if (CheckThunderRemove()) + { + isSummoned = true; + return true; + } + return false; + } + private IList GetZoneRepeatCardsId(int att, IList zoneCards,bool isFaceUp = false) + { + if (zoneCards.Count <= 0) return new List() { -1 }; + IList cards = zoneCards; + if (att > 0) cards = cards.Where(card => card != null && card.HasAttribute((CardAttribute)att)).ToList(); + if(cards.Count <= 0) return new List() { -1 }; + IList cardsid = new List(); + IList res = new List(); + foreach (var card in cards) + if(card != null && !(!card.IsFaceup() & isFaceUp)) + cardsid.Add(card.Id); + for (int i = 0; i < cardsid.Count; i++) + { + if (res.Count >= 0 && res.Contains(cardsid[i])) continue; + int times = 0; + for (int j = 0; j < cardsid.Count; j++) + { + if (times > 1) { res.Add(cardsid[i]); break; } + if (cardsid[i] == cardsid[j]) ++times; + } + } + if (res.Count <= 0) return new List() { -1 }; + return res; + } + private bool AllureofDarknessEffect() + { + if (Bot.Deck.Count <= 2) return false; + if (Bot.Hand.Count(card => card != null && card.HasAttribute(CardAttribute.Dark)) <= 0) return false; + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Hand) && Bot.GetMonstersInMainZone().Count < 5) + AI.SelectCard(CardId.ThunderDragonroar); + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Hand)) + AI.SelectCard(CardId.ThunderDragondark); + else + { + List cardsid = new List(); + IList cardsid_1 = GetZoneRepeatCardsId((int)CardAttribute.Dark, Bot.Hand).ToList(); + IList cardsid_2 = new List(); + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck) && Bot.GetMonstersInMainZone().Count < 5) cardsid.Add(CardId.ThunderDragonroar); + if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck)) cardsid.Add(CardId.ThunderDragondark); + if (HasInZoneNoActivate(CardId.TheBystialLubellion, CardLocation.Hand)) { cardsid_2.Add(CardId.BystialDruiswurm); cardsid_2.Add(CardId.BystialMagnamhut); } + if (!Bot.HasInExtra(CardId.Linkuriboh) || isSummoned) cardsid_2.Add(CardId.DragonBusterDestructionSword); + if (!HasInZoneNoActivate(CardId.BlackDragonCollapserpent, CardLocation.Hand)) cardsid_2.Add(CardId.BlackDragonCollapserpent); + if (isSummoned) cardsid_2.Add(CardId.AloofLupine); + cardsid.AddRange(cardsid_1); + cardsid.AddRange(cardsid_2); + AI.SelectCard(cardsid); + } + if (Card.Location == CardLocation.Hand) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + } + return true; + } + private bool ThunderDragondarkEffect_2() + { + if (Card.Location == CardLocation.Hand) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Duel.Player == 0) + { + if (IsShouldChainTunder()) + { + activate_ThunderDragondark = true; + handActivated = true; + return true; + } + if (Duel.CurrentChain.Count > 0 || Duel.Phase < DuelPhase.Main1) return false; + if (handActivated || (Bot.HasInHand(CardId.NormalThunderDragon) && CheckRemainInDeck(CardId.NormalThunderDragon) > 0) || !Bot.HasInExtra(CardId.ThunderDragonColossus)) return false; + if (!isSummoned && (Bot.HasInHand(CardId.BatterymanSolar) || Bot.HasInHand(CardId.AloofLupine))) return false; + activate_ThunderDragondark = true; + handActivated = true; + return true; + } + else + { + if (IsShouldChainTunder() || (Duel.Phase == DuelPhase.End + && Bot.HasInMonstersZone(CardId.ThunderDragonTitan, true, false, true) + && Enemy.GetMonsterCount() + Enemy.GetSpellCount() > 0) + || (!Bot.HasInMonstersZone(CardId.ThunderDragonTitan, true, false, true) + && !Bot.HasInGraveyard(CardId.ThunderDragondark))) + { + activate_ThunderDragondark = true; + handActivated = true; + return true; + } + return false; + } + } + return false; + } + private bool ThunderDragondarkEffect() + { + if (Card.Location != CardLocation.Hand) + { + if (Duel.Player == 0) + { + if (handActivated && CheckRemainInDeck(CardId.ThunderDragonlord) > 0 && + Bot.Hand.Count(card => card != null && card.HasRace(CardRace.Thunder)) > 0 && + (Bot.HasInMonstersZone(CardId.ThunderDragonColossus) || (!isSummoned && Bot.Hand.Count(card => card != null && card.HasRace(CardRace.Thunder)) > 1))) + AI.SelectCard(CardId.ThunderDragonlord); + else if (HasInZoneNoActivate(CardId.ThunderDragonhawk, CardLocation.Deck) && !Bot.HasInHand(CardId.ThunderDragonhawk)) + AI.SelectCard(CardId.ThunderDragonhawk); + else if (handActivated && Bot.Hand.Count(card => card != null && card.HasRace(CardRace.Thunder) && card.Level < 8) > 0 + && Bot.HasInMonstersZone(CardId.ThunderDragonColossus) && CheckRemainInDeck(CardId.ThunderDragonlord) > 0) + AI.SelectCard(CardId.ThunderDragonlord); + else if (HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragonmatrix); + else if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Hand) && handActivated + && CheckRemainInDeck(CardId.ThunderDragonlord) > 0) + AI.SelectCard(CardId.ThunderDragonlord); + else if (CheckRemainInDeck(CardId.ThunderDragonlord) > 0 && CheckRemainInDeck(CardId.NormalThunderDragon) > 1) + AI.SelectCard(CardId.ThunderDragonlord); + else if (handActivated && Bot.HasInHand(CardId.ThunderDragonlord) && CheckRemainInDeck(CardId.ThunderDragonroar) > 0) + AI.SelectCard(CardId.ThunderDragonroar); + else if (CheckRemainInDeck(CardId.NormalThunderDragon) > 1 && !handActivated) + AI.SelectCard(CardId.NormalThunderDragon); + else + AI.SelectCard(CardId.ThunderDragonmatrix, CardId.ThunderDragondark, CardId.ThunderDragonroar, CardId.NormalThunderDragon); + activate_ThunderDragondark = true; + return true; + } + else + { + if (!Bot.HasInHand(CardId.ThunderDragonmatrix) && HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Deck) + &&(Bot.HasInMonstersZone(CardId.ThunderDragonTitan, true, false, true) + || (Bot.HasInMonstersZone(CardId.ThunderDragonColossus, true, false, true) && Bot.GetGraveyardMonsters().Count(card=>card != null && card.HasRace(CardRace.Thunder)) < 2 ))) + AI.SelectCard(CardId.ThunderDragonmatrix); + else AI.SelectCard(CardId.ThunderDragonFusion, CardId.ThunderDragonhawk,CardId.ThunderDragonroar,CardId.NormalThunderDragon) ; + activate_ThunderDragondark = true; + return true; + } + } + return false; + } + private bool NormalThunderDragonEffect() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + handActivated = true; + ResetFlag(); + selectFlag[(int)Select.NormalThunderDragon] = true; + return true; + } + private bool BatterymanSolarEffect() + { + if (HasInZoneNoActivate(CardId.BystialDruiswurm, CardLocation.Hand) + || HasInZoneNoActivate(CardId.BystialMagnamhut, CardLocation.Hand)) + { + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragonroar); + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck) + && !Bot.HasInMonstersZone(CardId.ThunderDragondark,false,false,true)) + AI.SelectCard(CardId.ThunderDragondark); + else if ((HasInZoneNoActivate(CardId.ThunderDragonmatrix, CardLocation.Deck))) + AI.SelectCard(CardId.ThunderDragonmatrix); + else if (CheckRemainInDeck(CardId.NormalThunderDragon) > 0) + AI.SelectCard(CardId.NormalThunderDragon); + else if (CheckRemainInDeck(CardId.TheChaosCreator) > 0) + AI.SelectCard(CardId.TheChaosCreator); + else AI.SelectCard(CardId.ThunderDragonmatrix); + } + else if (HasInZoneNoActivate(CardId.WhiteDragonWyverburster, CardLocation.Hand)) + { + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragonroar); + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragondark); + else if (CheckRemainInDeck(CardId.TheChaosCreator) > 0) + AI.SelectCard(CardId.TheChaosCreator); + else AI.SelectCard(CardId.ThunderDragonmatrix); + + } + else if (Bot.HasInHand(CardId.ChaosSpace) && !activate_ChaosSpace_hand) + { + if ((Bot.Hand.Count(card => card != null && card.HasAttribute(CardAttribute.Dark)) > 0 + || Bot.Hand.Count(card => card != null && card.HasAttribute(CardAttribute.Light)) > 0) + && HasInZoneNoActivate(CardId.WhiteDragonWyverburster, CardLocation.Deck) + && HasInZoneNoActivate(CardId.BlackDragonCollapserpent, CardLocation.Deck)) + { + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragonroar); + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragondark); + else + AI.SelectCard(CardId.ThunderDragonmatrix, CardId.ThunderDragonhawk, CardId.NormalThunderDragon); + } + } + else if (HasInZoneNoActivate(CardId.BlackDragonCollapserpent, CardLocation.Hand)) + AI.SelectCard(CardId.ThunderDragonmatrix, CardId.ThunderDragonhawk); + else + { + if (HasInZoneNoActivate(CardId.ThunderDragonroar, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragonroar); + else if (HasInZoneNoActivate(CardId.ThunderDragondark, CardLocation.Deck)) + AI.SelectCard(CardId.ThunderDragondark); + else AI.SelectCard(CardId.ThunderDragonmatrix, CardId.ThunderDragonhawk); + } + return true; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TimeThiefExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TimeThiefExecutor.cs new file mode 100644 index 0000000..b0426ec --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TimeThiefExecutor.cs @@ -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 avoid_list = null) + { + List list = new List { 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 enemy = Enemy.GetMonstersInMainZone(); + List 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; + } + + + } + +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ToadallyAwesomeExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ToadallyAwesomeExecutor.cs new file mode 100644 index 0000000..a043e89 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ToadallyAwesomeExecutor.cs @@ -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 monsters = Bot.GetMonsters(); + IList 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 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 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 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 + ); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TrickstarExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TrickstarExecutor.cs new file mode 100644 index 0000000..34370ba --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/TrickstarExecutor.cs @@ -0,0 +1,1837 @@ +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("Trickstar", "AI_Trickstar")] + public class TrickstarExecutor : DefaultExecutor + { + public class CardId + { + public const int White = 98169343; + public const int BF = 9929398; + public const int Yellow = 61283655; + public const int Red = 35199656; + public const int Urara = 14558127; + public const int Ghost = 59438930; + public const int Pink = 98700941; + public const int MG = 23434538; + public const int Tuner = 67441435; + public const int Eater = 63845230; + public const int LockBird = 94145021; + + public const int Feather = 18144506; + public const int Galaxy = 5133471; + public const int Pot = 35261759; + public const int Trans = 73628505; + public const int Sheep = 73915051; + public const int Crown = 22159429; + public const int Stage = 35371948; + public const int GraveCall = 24224830; + public const int DarkHole = 53129443; + + public const int Re = 21076084; + public const int Ring = 83555666; + public const int Strike = 40605147; + public const int Warn = 84749824; + public const int Awaken = 10813327; + + public const int Linkuri = 41999284; + public const int Linkspi = 98978921; + public const int SafeDra = 99111753; + public const int Crystal = 50588353; + public const int Phoneix = 2857636; + public const int Unicorn = 38342335; + public const int Snake = 74997493; + public const int Borrel = 31833038; + public const int TG = 98558751; + + public const int Beelze = 34408491; + public const int Abyss = 9753964; + public const int Exterio = 99916754; + public const int Ultimate = 86221741; + public const int Cardian = 87460579; + + public const int Missus = 3987233; + } + + public int getLinkMarker(int id) + { + if (id == CardId.Borrel || id == CardId.Snake) return 4; + else if (id == CardId.Abyss || id == CardId.Beelze || id == CardId.Exterio || id == CardId.Ultimate || id == CardId.Cardian) return 5; + else if (id == CardId.Unicorn) return 3; + else if (id == CardId.Crystal || id == CardId.Phoneix || id == CardId.SafeDra || id == CardId.Missus) return 2; + return 1; + } + + List Impermanence_list = new List(); + bool NormalSummoned = false; + ClientCard stage_locked = null; + bool pink_ss = false; + bool snake_four_s = false; + bool tuner_eff_used = false; + bool crystal_eff_used = false; + bool white_eff_used = false; + bool lockbird_useful = false; + bool lockbird_used = false; + List currentNegatingIdList = new List(); + + List SkyStrike_list = new List { + 26077387, 8491308, 63288573, 90673288, + 21623008, 25955749, 63166095, 99550630, + 25733157, 51227866, 52340444,98338152, + 24010609, 97616504, 50005218 + }; + + public TrickstarExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // counter + AddExecutor(ExecutorType.Activate, CardId.MG, G_act); + AddExecutor(ExecutorType.Activate, CardId.Strike, DefaultSolemnStrike); + AddExecutor(ExecutorType.Activate, CardId.Warn, DefaultSolemnWarning); + AddExecutor(ExecutorType.Activate, CardId.Awaken, Awaken_ss); + AddExecutor(ExecutorType.Activate, CardId.Urara, Hand_act_eff); + AddExecutor(ExecutorType.Activate, CardId.Ghost, Hand_act_eff); + AddExecutor(ExecutorType.Activate, CardId.Ring, Ring_act); + AddExecutor(ExecutorType.Activate, CardId.Abyss, Abyss_eff); + AddExecutor(ExecutorType.Activate, CardId.Exterio, Exterio_counter); + AddExecutor(ExecutorType.Activate, CardId.Cardian); + AddExecutor(ExecutorType.Activate, CardId.GraveCall, GraveCall_eff); + + AddExecutor(ExecutorType.Activate, CardId.DarkHole, DarkHole_eff); + + // spell clean + AddExecutor(ExecutorType.Activate, field_activate); + AddExecutor(ExecutorType.Activate, CardId.Stage, Stage_Lock); + AddExecutor(ExecutorType.Activate, CardId.Feather, Feather_Act); + AddExecutor(ExecutorType.Activate, CardId.Stage, Stage_act); + AddExecutor(ExecutorType.Activate, CardId.Galaxy, GalaxyCyclone); + AddExecutor(ExecutorType.Activate, CardId.TG, TG_eff); + + AddExecutor(ExecutorType.Activate, CardId.Tuner,Tuner_eff); + AddExecutor(ExecutorType.SpellSet, Five_Rainbow); + + // ex ss + AddExecutor(ExecutorType.SpSummon, CardId.Borrel, Borrel_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Missus, Missus_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Phoneix, Phoneix_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Snake, Snake_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Crystal, Crystal_ss); + AddExecutor(ExecutorType.SpSummon, CardId.SafeDra, Safedragon_ss); + AddExecutor(ExecutorType.Activate, CardId.SafeDra, DefaultCompulsoryEvacuationDevice); + AddExecutor(ExecutorType.Activate, CardId.Linkuri, Linkuri_eff); + AddExecutor(ExecutorType.SpSummon, CardId.Linkuri, Linkuri_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Unicorn, Unicorn_ss); + AddExecutor(ExecutorType.SpSummon, CardId.Linkspi); + + // ex_monster act + AddExecutor(ExecutorType.Activate, CardId.Beelze); + AddExecutor(ExecutorType.Activate, CardId.Missus, Missus_eff); + AddExecutor(ExecutorType.Activate, CardId.Crystal, Crystal_eff); + AddExecutor(ExecutorType.Activate, CardId.Phoneix, Phoneix_eff); + AddExecutor(ExecutorType.Activate, CardId.Unicorn, Unicorn_eff); + AddExecutor(ExecutorType.Activate, CardId.Snake, Snake_eff); + AddExecutor(ExecutorType.Activate, CardId.Borrel, Borrel_eff); + + // normal act + AddExecutor(ExecutorType.Activate, CardId.Trans); + AddExecutor(ExecutorType.SpSummon, CardId.BF, BF_pos); + AddExecutor(ExecutorType.Activate, CardId.BF, BF_pos); + AddExecutor(ExecutorType.Activate, CardId.Sheep, Sheep_Act); + AddExecutor(ExecutorType.Activate, CardId.Eater,Eater_eff); + AddExecutor(ExecutorType.Activate, CardId.LockBird, LockBird_act); + + // ts + AddExecutor(ExecutorType.Activate, CardId.Pink, Pink_eff); + AddExecutor(ExecutorType.Activate, CardId.Re, Reincarnation); + AddExecutor(ExecutorType.Activate, CardId.Red, Red_ss); + AddExecutor(ExecutorType.Activate, CardId.Yellow, Yellow_eff); + AddExecutor(ExecutorType.Activate, CardId.White, White_eff); + AddExecutor(ExecutorType.Activate, CardId.Crown, Crown_eff); + AddExecutor(ExecutorType.Summon, CardId.Yellow, Yellow_sum); + AddExecutor(ExecutorType.Summon, CardId.Red, Red_sum); + AddExecutor(ExecutorType.Summon, CardId.Pink, Pink_sum); + + // normal + AddExecutor(ExecutorType.SpSummon, CardId.Eater, Eater_ss); + AddExecutor(ExecutorType.Summon, CardId.Tuner, Tuner_ns); + AddExecutor(ExecutorType.Summon, CardId.Urara,Tuner_ns); + AddExecutor(ExecutorType.Summon, CardId.Ghost, Tuner_ns); + AddExecutor(ExecutorType.Activate, CardId.Pot, Pot_Act); + AddExecutor(ExecutorType.Repos, MonsterRepos); + AddExecutor(ExecutorType.SummonOrSet, CardId.Red); + AddExecutor(ExecutorType.SummonOrSet, CardId.Pink); + AddExecutor(ExecutorType.SpellSet, SpellSet); + } + + public bool Five_Rainbow() + { + if (Enemy.HasInSpellZone(19619755,true) || Bot.HasInSpellZone(19619755, true)) + { + if (Card.HasType(CardType.Field)) return false; + bool has_setcard = false; + for (int i = 0; i < 5; ++i) + { + ClientCard sp = Bot.SpellZone[i]; + if (sp != null && sp.HasPosition(CardPosition.FaceDown)) + { + has_setcard = true; + break; + } + } + if (has_setcard) return false; + AI.SelectPlace(SelectSTPlace()); + return true; + } + return false; + } + + public int SelectSTPlace(ClientCard card = null, bool avoid_Impermanence = false) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoid_Impermanence && Impermanence_list.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoid_Impermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + return (int)System.Math.Pow(2, seq); + } + } + foreach (int seq in list) + { + return (int)System.Math.Pow(2, seq); + } + return 0; + } + + public bool SpellSet() + { + if (Card.IsCode(CardId.Sheep) && Bot.HasInSpellZone(CardId.Sheep)) return false; + if (DefaultSpellSet()) + { + AI.SelectPlace(SelectSTPlace()); + return true; + } else if (Enemy.HasInSpellZone(58921041,true) || Bot.HasInSpellZone(58921041, true)) + { + if (Card.IsCode(CardId.Stage)) return !Bot.HasInSpellZone(CardId.Stage); + if (Card.IsSpell()) + { + AI.SelectPlace(SelectSTPlace()); + return true; + } + } + return false; + } + + public bool IsTrickstar(ClientCard card) + { + return card.HasSetcode(0x8d); + } + + public bool field_activate() + { + if (Card.HasPosition(CardPosition.FaceDown) && Card.HasType(CardType.Field) && Card.Location == CardLocation.SpellZone) + { + // field spells that forbid other fields' activate + return !Card.IsCode(71650854, 78082039); + } + return false; + } + + public bool spell_trap_activate() + { + if (Card.Location != CardLocation.SpellZone && Card.Location != CardLocation.Hand) return true; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Enemy.HasInMonstersZone(CardId.Exterio,true) && !Bot.HasInHandOrHasInMonstersZone(CardId.Ghost)) return false; + if (Card.IsSpell()) + { + if (Enemy.HasInMonstersZone(_CardId.NaturiaBeast, true) && !Bot.HasInHandOrHasInMonstersZone(CardId.Ghost)) return false; + if (Enemy.HasInSpellZone(_CardId.ImperialOrder, true) || Bot.HasInSpellZone(_CardId.ImperialOrder, true)) return false; + if (Enemy.HasInMonstersZone(37267041, true) || Bot.HasInMonstersZone(37267041, true)) return false; + return true; + } + if (Card.IsTrap()) + { + if (Enemy.HasInSpellZone(_CardId.RoyalDecreel, true) || Bot.HasInSpellZone(_CardId.RoyalDecreel, true)) return false; + return true; + } + // how to get here? + return false; + } + + public int[] Useless_List() + { + return new[] + { + CardId.Tuner, + CardId.Awaken, + CardId.Crown, + CardId.Pink, + CardId.Pot, + CardId.BF, + CardId.White, + CardId.Trans, + CardId.Galaxy, + CardId.Feather, + CardId.Sheep, + CardId.Re, + CardId.Red, + CardId.Yellow, + CardId.Eater, + CardId.MG, + CardId.Ghost, + CardId.Urara, + CardId.Stage, + CardId.Ring, + CardId.Warn, + CardId.Strike + }; + } + + public int GetTotalATK(IList list) + { + int atk = 0; + foreach(ClientCard c in list) + { + if (c == null) continue; + atk += c.Attack; + } + return atk; + } + + public bool Awaken_ss() + { + // judge whether can ss from exdeck + bool judge = (Bot.ExtraDeck.Count > 0); + if (Enemy.GetMonstersExtraZoneCount() > 1) judge = false; // exlink + if (Bot.GetMonstersExtraZoneCount() >= 1) + { + foreach (ClientCard card in Bot.GetMonstersInExtraZone()) + { + if (getLinkMarker(card.Id) == 5) judge = false; + } + } + // can ss from exdeck + if (judge) + { + bool fornextss = Util.ChainContainsCard(CardId.Awaken); + IList ex = Bot.ExtraDeck; + ClientCard ex_best = null; + foreach (ClientCard ex_card in ex) + { + if (!fornextss) + { + if (Bot.HasInExtra(CardId.Exterio)) + { + bool has_skystriker = false; + foreach (ClientCard card in Enemy.Graveyard) + { + if (card != null && card.IsCode(SkyStrike_list)) + { + has_skystriker = true; + break; + } + } + if (!has_skystriker) + { + foreach (ClientCard card in Enemy.GetSpells()) + { + if (card != null && card.IsCode(SkyStrike_list)) + { + has_skystriker = true; + break; + } + } + } + if (!has_skystriker) + { + foreach (ClientCard card in Enemy.GetSpells()) + { + if (card != null && card.IsCode(SkyStrike_list)) + { + has_skystriker = true; + break; + } + } + } + if (has_skystriker) + { + AI.SelectCard(CardId.Exterio); + return true; + } else + { + if (ex_best == null || ex_card.Attack > ex_best.Attack) ex_best = ex_card; + } + } + else + { + if (ex_best == null || ex_card.Attack > ex_best.Attack) ex_best = ex_card; + } + } + else + { + if (getLinkMarker(ex_card.Id) != 5 && (ex_best == null || ex_card.Attack > ex_best.Attack)) ex_best = ex_card; + } + } + if (ex_best != null) + { + AI.SelectCard(ex_best); + } + } + if (!judge || Util.ChainContainsCard(CardId.Awaken)) + { + // cannot ss from exdeck or have more than 1 grass in chain + int[] secondselect = new[] + { + CardId.Borrel, + CardId.Ultimate, + CardId.Abyss, + CardId.Cardian, + CardId.Exterio, + CardId.Ghost, + CardId.White, + CardId.Red, + CardId.Yellow, + CardId.Pink + }; + if (!Util.ChainContainsCard(CardId.Awaken)) + { + if (!judge && Bot.GetRemainingCount(CardId.Ghost, 2) > 0) + { + AI.SelectCard(CardId.Ghost); + AI.SelectPosition(CardPosition.FaceUpDefence); + } + else + AI.SelectCard(secondselect); + } + else + { + if (!judge) + AI.SelectCard(secondselect); + AI.SelectNextCard(secondselect); + AI.SelectThirdCard(secondselect); + } + } + return true; + } + + public bool Abyss_eff() + { + // tuner ss + if (ActivateDescription == -1) + { + AI.SelectCard(CardId.Ghost, CardId.TG, CardId.Tuner, CardId.Urara, CardId.BF); + return true; + }; + // counter + if (!Enemy.HasInMonstersZone(CardId.Ghost) || Enemy.GetHandCount() <= 1) + { + ClientCard tosolve = Util.GetProblematicEnemyCard(); + if (tosolve == null) + { + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard() != null) + { + ClientCard target = Util.GetLastChainCard(); + if (target.HasPosition(CardPosition.FaceUp) && (target.Location == CardLocation.MonsterZone || target.Location == CardLocation.SpellZone)) tosolve = target; + } + } + if (tosolve != null) + { + AI.SelectCard(tosolve); + return true; + } + } + return false; + } + + public void RandomSort(List list) { + + int n = list.Count; + while(n-- > 1) + { + int index = Program.Rand.Next(n + 1); + ClientCard temp = list[index]; + list[index] = list[n]; + list[n] = temp; + } + } + + public bool Stage_Lock() + { + if (Card.Location != CardLocation.SpellZone) return false; + List spells = Enemy.GetSpells(); + RandomSort(spells); + if (spells.Count == 0) return false; + foreach (ClientCard card in spells) + { + if (card.IsFacedown()) + { + AI.SelectCard(card); + stage_locked = card; + return true; + } + } + return false; + } + + public bool GalaxyCyclone() + { + if (!Bot.HasInSpellZone(CardId.Stage)) stage_locked = null; + List spells = Enemy.GetSpells(); + if (spells.Count == 0) + return false; + ClientCard selected = null; + if (Card.Location == CardLocation.Grave) + { + selected = Util.GetBestEnemySpell(true); + } + else + { + if (!spell_trap_activate()) return false; + foreach (ClientCard card in spells) + { + if (card.IsFacedown() && card != stage_locked) + { + selected = card; + break; + } + } + } + if (selected == null) + return false; + AI.SelectCard(selected); + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + + public bool BF_pos() + { + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + + public bool Feather_Act() + { + if (!spell_trap_activate()) return false; + if (Util.GetProblematicEnemySpell() != null) + { + List grave = Bot.GetGraveyardSpells(); + foreach (ClientCard self_card in grave) + { + if (self_card.IsCode(CardId.Galaxy)) + return false; + } + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + // activate when more than 2 cards + if (Enemy.GetSpellCount() <= 1) + return false; + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + + public bool Sheep_Act() + { + if (!spell_trap_activate()) return false; + if (Duel.Player == 0) return false; + if (Duel.Phase == DuelPhase.End) return true; + if (Duel.LastChainPlayer == 1 && (Util.IsChainTarget(Card) || (Util.GetLastChainCard().IsCode(CardId.Feather) && !Bot.HasInSpellZone(CardId.Awaken)))) return true; + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + int total_atk = 0; + List 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 bool Stage_act() + { + if (Card.Location == CardLocation.SpellZone && Card.HasPosition(CardPosition.FaceUp)) return false; + if (!spell_trap_activate()) return false; + if (!NormalSummoned) + { + if (!Bot.HasInHand(CardId.Yellow)) + { + AI.SelectCard(CardId.Yellow, CardId.Pink, CardId.Red, CardId.White); + stage_locked = null; + return true; + } + else if (Enemy.LifePoints <= 1000 && Bot.GetRemainingCount(CardId.Pink,1) > 0) + { + AI.SelectCard(CardId.Pink, CardId.Yellow, CardId.Red, CardId.White); + stage_locked = null; + return true; + } + else if (Bot.HasInHand(CardId.Yellow) && ! Bot.HasInHand(CardId.Red)) + { + AI.SelectCard(CardId.Red, CardId.Pink, CardId.Yellow, CardId.White); + stage_locked = null; + return true; + } + else if (Enemy.GetMonsterCount() > 0 && Util.GetBestEnemyMonster().Attack >= Util.GetBestAttack(Bot)) + { + AI.SelectCard(CardId.White, CardId.Yellow, CardId.Pink, CardId.Red); + stage_locked = null; + return true; + } + else if (!Bot.HasInSpellZone(CardId.Stage)) + { + AI.SelectCard(CardId.Yellow, CardId.Pink, CardId.Red, CardId.White); + stage_locked = null; + return true; + } + return false; + } + + if (NormalSummoned) + { + if (Enemy.LifePoints <= 1000 && !pink_ss && Bot.GetRemainingCount(CardId.Pink,1) > 0) + { + AI.SelectCard(CardId.Pink, CardId.Yellow, CardId.Red, CardId.White); + stage_locked = null; + return true; + } + if (Enemy.GetMonsterCount() > 0 && Util.GetBestEnemyMonster().Attack >= Util.GetBestAttack(Bot) && !Bot.HasInHand(CardId.White) && !DefaultCheckWhetherCardIdIsNegated(CardId.White)) + { + AI.SelectCard(CardId.White, CardId.Yellow, CardId.Pink, CardId.Red); + stage_locked = null; + return true; + } + if (Bot.HasInMonstersZone(CardId.Yellow) && !Bot.HasInHand(CardId.Red)) + { + AI.SelectCard(CardId.Red, CardId.Pink, CardId.Yellow, CardId.White); + stage_locked = null; + return true; + } + AI.SelectCard(CardId.Yellow, CardId.Pink, CardId.Red, CardId.White); + stage_locked = null; + return true; + } + stage_locked = null; + return false; + } + + public bool Pot_Act() + { + if (!spell_trap_activate()) return false; + if (Bot.Deck.Count > 15) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + return false; + } + + public bool Hand_act_eff() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Card.IsCode(CardId.Urara) && Util.GetLastChainCard().HasSetcode(0x11e) && Util.GetLastChainCard().Location == CardLocation.Hand) // Danger! archtype hand effect + return false; + if (Card.IsCode(CardId.Urara) && Bot.HasInHand(CardId.LockBird) && Bot.HasInSpellZone(CardId.Re)) return false; + if (Card.IsCode(CardId.Ghost) && Card.Location == CardLocation.Hand && Bot.HasInMonstersZone(CardId.Ghost)) return false; + return (Duel.LastChainPlayer == 1); + } + + public bool Exterio_counter() + { + if (Duel.LastChainPlayer == 1) + { + AI.SelectCard(Useless_List()); + return true; + } + return false; + } + + public bool G_act() + { + return Duel.Player == 1 && !DefaultCheckWhetherCardIsNegated(Card); + } + + public bool Pink_eff() + { + if (Card.Location == CardLocation.Hand) + { + if ((Enemy.LifePoints <= 1000 && Bot.HasInSpellZone(CardId.Stage)) + || Enemy.LifePoints <= 800 + || (!NormalSummoned && Bot.HasInGraveyard(CardId.Red)) + ) + { + pink_ss = true; + return true; + } + else if (Enemy.GetMonsterCount() > 0 && (Util.GetBestEnemyMonster().Attack - 800 >= Bot.LifePoints)) return false; + pink_ss = true; + return true; + } + else if (Card.Location == CardLocation.Onfield) + { + if (!NormalSummoned && Bot.HasInGraveyard(CardId.Yellow)) + { + AI.SelectCard(CardId.Yellow, CardId.Red, CardId.White); + return true; + } else + { + AI.SelectCard(CardId.Red, CardId.Yellow, CardId.White); + return true; + } + } + return true; + } + + public bool Eater_ss() + { + 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 targets = new List(); + if (Bot.SpellZone[5] != null && !Bot.SpellZone[5].IsCode(CardId.Stage)) + { + targets.Add(Bot.SpellZone[5]); + } + if (Bot.SpellZone[5] != null && Bot.SpellZone[5].IsCode(CardId.Stage) && Bot.HasInHand(CardId.Stage)) + { + targets.Add(Bot.SpellZone[5]); + } + foreach (ClientCard e_c in Bot.ExtraDeck) + { + targets.Add(e_c); + if (targets.Count >= 5) + { + AI.SelectMaterials(targets, HintMsg.Remove); + 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; + } + + public bool Eater_eff() + { + if (Enemy.BattlingMonster.HasPosition(CardPosition.Attack) && (Bot.BattlingMonster.Attack - Enemy.BattlingMonster.GetDefensePower() >= Enemy.LifePoints)) return false; + return true; + } + + public void Red_SelectPos(ClientCard return_card = null) + { + int self_power = (Bot.HasInHand(CardId.White) && !white_eff_used) ? 3200 : 1600; + if (Duel.Player == 0) + { + List monster_list = Bot.GetMonsters(); + monster_list.Sort(CardContainer.CompareCardAttack); + monster_list.Reverse(); + foreach(ClientCard card in monster_list) + { + if (IsTrickstar(card) && card != return_card && card.HasPosition(CardPosition.Attack)) + { + int this_power = (Bot.HasInHand(CardId.White) && !white_eff_used) ? (card.RealPower + card.Attack) : card.RealPower; + if (this_power >= self_power) self_power = this_power; + } else if (card.RealPower >= self_power) self_power = card.RealPower; + } + } + ClientCard bestenemy = Util.GetOneEnemyBetterThanValue(self_power, true); + if (bestenemy != null) AI.SelectPosition(CardPosition.FaceUpDefence); + else AI.SelectPosition(CardPosition.FaceUpAttack); + return; + } + + public bool Red_ss() + { + if ((Util.ChainContainsCard(CardId.DarkHole) || Util.ChainContainsCard(_CardId.InterruptedKaijuSlumber) || Util.ChainContainsCard(_CardId.TorrentialTribute)) && Util.ChainContainsCard(CardId.Red)) return false; + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.Red)) + { + foreach (ClientCard m in Bot.GetMonsters()) + { + if (Util.IsChainTarget(m) && IsTrickstar(m)) + { + AI.SelectCard(m); + Red_SelectPos(); + return true; + } + } + } + if (Duel.LastChainPlayer == 1) return true; + if (Duel.Player == 0) + { + if (Util.IsTurn1OrMain2()) return false; + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + List self_m = Bot.GetMonsters(); + ClientCard tosolve_enemy = Util.GetOneEnemyBetterThanMyBest(); + foreach (ClientCard c in self_m) + { + if (IsTrickstar(c) && !c.IsCode(CardId.Red)) + { + if (c.Attacked) + { + AI.SelectCard(c); + Red_SelectPos(c); + return true; + } + if (c.IsCode(CardId.Pink)) return false; + if (tosolve_enemy != null) + { + if (Bot.HasInHand(CardId.White) && c.Attack + c.BaseAttack < tosolve_enemy.Attack) + { + if (tosolve_enemy.Attack > 3200) AI.SelectPosition(CardPosition.FaceUpDefence); + AI.SelectCard(c); + Red_SelectPos(c); + return true; + } + if (!Bot.HasInHand(CardId.White) && tosolve_enemy.Attack <= 3200 && c.IsCode(CardId.White)) + { + AI.SelectCard(c); + Red_SelectPos(c); + return true; + } + if (!Bot.HasInHand(CardId.White) && c.Attack < tosolve_enemy.Attack) + { + if (!c.Attacked) + { + ClientCard badatk = Enemy.GetMonsters().GetLowestAttackMonster(); + ClientCard baddef = Enemy.GetMonsters().GetLowestDefenseMonster(); + int enemy_power = 99999; + if (badatk != null && badatk.Attack <= enemy_power) enemy_power = badatk.Attack; + if (baddef != null && baddef.Defense <= enemy_power) enemy_power = baddef.Defense; + if (c.Attack > enemy_power) return false; + } + if (tosolve_enemy.Attack > 1600) AI.SelectPosition(CardPosition.FaceUpDefence); + AI.SelectCard(c); + Red_SelectPos(c); + return true; + } + } + } + } + } + } else + { + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + if (Util.GetOneEnemyBetterThanMyBest() != null) + { + List self_monster = Bot.GetMonsters(); + self_monster.Sort(CardContainer.CompareDefensePower); + foreach(ClientCard card in self_monster) + { + if (IsTrickstar(card) && !card.IsCode(CardId.Red)) + { + AI.SelectCard(card); + Red_SelectPos(card); + return true; + } + } + } + } + } + return false; + } + + public bool Yellow_eff() + { + if (!Bot.HasInHand(CardId.Stage) && !Bot.HasInSpellZone(CardId.Stage) && Bot.GetRemainingCount(CardId.Stage, 3) > 0) + { + AI.SelectCard(CardId.Stage, CardId.Red, CardId.White, CardId.Pink, CardId.Re, CardId.Crown, CardId.Yellow); + return true; + } + if (Enemy.LifePoints <= 1000) + { + if (Bot.GetRemainingCount(CardId.Pink, 1) > 0 && !pink_ss) + { + AI.SelectCard(CardId.Pink, CardId.Stage, CardId.Red, CardId.White, CardId.Re, CardId.Crown, CardId.Yellow); + return true; + } + else if (Bot.HasInGraveyard(CardId.Pink) && Bot.GetRemainingCount(CardId.Crown, 1) > 0) + { + AI.SelectCard(CardId.Crown, CardId.Pink, CardId.Re, CardId.Stage, CardId.Red, CardId.White, CardId.Yellow); + return true; + } + } + if (Enemy.GetMonsterCount() == 0 && !Util.IsTurn1OrMain2()) + { + if (Bot.HasInGraveyard(CardId.Red) && Bot.GetRemainingCount(CardId.Pink, 1) > 0 && !pink_ss) + { + AI.SelectCard(CardId.Pink, CardId.Red, CardId.White, CardId.Re, CardId.Stage, CardId.Crown, CardId.Yellow); + } + else if (Bot.HasInGraveyard(CardId.Pink) && Bot.HasInGraveyard(CardId.Red) && Bot.GetRemainingCount(CardId.Ring, 1) > 0) + { + AI.SelectCard(CardId.Crown, CardId.Red, CardId.White, CardId.Re, CardId.Stage, CardId.Pink, CardId.Yellow); + } + else if (Bot.GetRemainingCount(CardId.White, 2) > 0 && Enemy.LifePoints <= 4000) + { + AI.SelectCard(CardId.White, CardId.Red, CardId.Pink, CardId.Re, CardId.Stage, CardId.Crown, CardId.Yellow); + } + else if (Bot.HasInGraveyard(CardId.White) && Bot.GetRemainingCount(CardId.Crown, 1) > 0) + { + AI.SelectCard(CardId.Crown, CardId.Red, CardId.Pink, CardId.Re, CardId.Stage, CardId.White, CardId.Yellow); + } + else + { + AI.SelectCard(CardId.Red, CardId.Pink, CardId.Re, CardId.Crown, CardId.Stage, CardId.White, CardId.Yellow); + } + return true; + } + if (Util.GetProblematicEnemyMonster() != null) + { + int power = Util.GetProblematicEnemyMonster().GetDefensePower(); + if (power >= 1800 && power <= 3600 && Bot.GetRemainingCount(CardId.White, 2) > 0 && !Bot.HasInHand(CardId.White)) + { + AI.SelectCard(CardId.White, CardId.Red, CardId.Pink, CardId.Re, CardId.Stage, CardId.Crown, CardId.Yellow); + } + else + { + AI.SelectCard(CardId.Red, CardId.Pink, CardId.Re, CardId.Crown, CardId.Stage, CardId.White, CardId.Yellow); + } + return true; + } + if ((Bot.HasInHand(CardId.Red) || Bot.HasInHand(CardId.Stage) || Bot.HasInHand(CardId.Yellow)) && Bot.GetRemainingCount(CardId.Re,1) > 0) { + AI.SelectCard(CardId.Re, CardId.Red, CardId.White, CardId.Crown, CardId.Pink, CardId.Stage, CardId.Yellow); + return true; + } + AI.SelectCard(CardId.Red, CardId.Pink, CardId.Re, CardId.Crown, CardId.Stage, CardId.White, CardId.Yellow); + return true; + } + + public bool White_eff() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Duel.Phase >= DuelPhase.Main2) return false; + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + if (Bot.BattlingMonster == null || Enemy.BattlingMonster == null || !IsTrickstar(Bot.BattlingMonster) || Bot.BattlingMonster.HasPosition(CardPosition.Defence)) return false; + if (Bot.BattlingMonster.Attack <= Enemy.BattlingMonster.RealPower && Bot.BattlingMonster.Attack + Bot.BattlingMonster.BaseAttack >= Enemy.BattlingMonster.RealPower) + { + white_eff_used = true; + return true; + } + return false; + } else + { + if (Enemy.GetMonsterCount() == 0 && !Util.IsTurn1OrMain2()) { + white_eff_used = true; + return true; + } + else if (Enemy.GetMonsterCount() != 0) + { + ClientCard tosolve = Util.GetBestEnemyMonster(true); + ClientCard self_card = Bot.GetMonsters().GetHighestAttackMonster(); + if (tosolve == null || self_card == null || (tosolve != null && self_card != null && !IsTrickstar(self_card))) + { + if (Enemy.GetMonsters().GetHighestAttackMonster()== null || + Enemy.GetMonsters().GetHighestDefenseMonster() == null || + Enemy.GetMonsters().GetHighestAttackMonster().GetDefensePower() < 2000 || + Enemy.GetMonsters().GetHighestDefenseMonster().GetDefensePower() < 2000) + { + white_eff_used = true; + return true; + } + else return false; + } + if (tosolve != null && self_card != null && IsTrickstar(self_card) && !tosolve.IsMonsterHasPreventActivationEffectInBattle()) + { + int defender_power = tosolve.GetDefensePower(); + Logger.DebugWriteLine("battle check 0:" + Duel.Phase.ToString()); + Logger.DebugWriteLine("battle check 1:" + self_card.Attack.ToString()); + Logger.DebugWriteLine("battle check 2:" + (self_card.Attack+self_card.BaseAttack).ToString()); + Logger.DebugWriteLine("battle check 3:" + defender_power.ToString()); + if (self_card.Attack <= defender_power && self_card.Attack + self_card.BaseAttack >= defender_power) + { + return false; + } + else if (defender_power <= 2000) + { + white_eff_used = true; + return true; + } + } + } + return false; + } + } + + public bool LockBird_act() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Duel.Player == 0 || lockbird_used) return false; + lockbird_useful = true; + if (Bot.HasInSpellZone(CardId.Re)) + { + if (Util.ChainContainsCard(CardId.Re)) lockbird_used = true; + return Util.ChainContainsCard(CardId.Re); + } + lockbird_used = true; + return true; + } + + public bool Reincarnation() + { + if (Card.Location == CardLocation.Grave) return Ts_reborn(); + if (!spell_trap_activate()) return false; + if (Bot.HasInHand(CardId.LockBird)) + { + if (lockbird_useful || Util.IsChainTarget(Card) || (Duel.Player == 1 && Util.ChainContainsCard(CardId.Feather))) { + lockbird_useful = false; + return true; + } + return false; + } + return true; + } + + public bool Crown_eff() + { + if (Card.Location == CardLocation.Hand || (Card.Location == CardLocation.SpellZone && Card.HasPosition(CardPosition.FaceDown))) + { + if (!spell_trap_activate()) return false; + if (Duel.Phase <= DuelPhase.Main1 && Ts_reborn()) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + return false; + } + if (Bot.HasInHand(CardId.Pink) && DefaultCheckWhetherCardIdIsNegated(CardId.Pink)) + { + AI.SelectCard(CardId.Pink); + return true; + } + if (Enemy.GetMonsterCount() == 0) + { + foreach(ClientCard hand in Bot.Hand) + { + if (hand.IsMonster() && IsTrickstar(hand)) + { + if (hand.Attack >= Enemy.LifePoints) return true; + if (!hand.IsCode(CardId.Yellow)) + { + if (Util.GetOneEnemyBetterThanValue(hand.Attack, false) == null) return true; + } + } + } + } + return false; + } + + public bool Ts_reborn() + { + if (Util.IsTurn1OrMain2()) return false; + if (Duel.Player == 0 && Enemy.LifePoints <= 1000) + { + AI.SelectCard(CardId.Pink); + return true; + } + bool can_summon = (Duel.Player == 0 && NormalSummoned); + if (can_summon) + { + if ((Duel.Phase < DuelPhase.Main2) && Bot.HasInGraveyard(CardId.Pink)) + { + AI.SelectCard(CardId.Pink); + return true; + } + else + { + AI.SelectCard(CardId.Red, CardId.White, CardId.Yellow, CardId.Pink); + return true; + } + } + else + { + + AI.SelectCard(CardId.Red, CardId.White, CardId.Yellow, CardId.Pink); + return true; + } + } + + public bool Yellow_sum() + { + NormalSummoned = true; + return true; + } + + public bool Red_sum() + { + if ((Enemy.GetMonsterCount() == 0 && Enemy.LifePoints <= 1800) || (Duel.Turn == 1 && Bot.HasInHand(CardId.Re))) + { + NormalSummoned = true; + return true; + } + return false; + } + + public bool Pink_sum() + { + if (Enemy.LifePoints <= 1000) + { + NormalSummoned = true; + return true; + } + else if (!Util.IsTurn1OrMain2() && (Bot.HasInGraveyard(CardId.Yellow) || Bot.HasInGraveyard(CardId.Red))) + { + NormalSummoned = true; + return true; + } + return false; + } + + public bool Tuner_ns() + { + if ((Card.IsCode(CardId.Tuner) && Bot.HasInExtra(CardId.Crystal) && !tuner_eff_used) || Tuner_ss()) + { + NormalSummoned = true; + return true; + } + return false; + } + + public bool Tuner_ss() + { + if (crystal_eff_used || Bot.HasInMonstersZone(CardId.Crystal)) return false; + if (Bot.GetMonsterCount() == 0 || !Bot.HasInExtra(CardId.Crystal)) return false; + if (Card.IsCode(CardId.Ghost) && Bot.GetRemainingCount(CardId.Ghost, 2) <= 0) return false; + int count = 0; + if (!Card.IsCode(CardId.Urara)) count += 1; + foreach(ClientCard hand in Bot.Hand) + { + if (hand.IsCode(Card.Id)) count += 1; + } + if (count < 2) return false; + foreach(ClientCard m in Bot.GetMonsters()) + { + if (!m.IsCode(CardId.Eater) && getLinkMarker(m.Id) <= 2) return true; + } + return false; + } + + public bool Tuner_eff() + { + tuner_eff_used = true; + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + + public bool Ring_act() + { + if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard() != null && Util.GetLastChainCard().IsCode(CardId.Ghost)) return false; + if (!spell_trap_activate()) return false; + ClientCard target = Util.GetProblematicEnemyMonster(); + if (target == null && Util.IsChainTarget(Card)) + { + target = Util.GetBestEnemyMonster(); + } + if (target != null) + { + if (Bot.LifePoints <= target.Attack) return false; + AI.SelectCard(target); + return true; + } + return false; + } + + public bool Linkuri_ss() + { + foreach(ClientCard c in Bot.GetMonsters()) + { + if (!c.IsCode(CardId.Eater, CardId.Linkuri, CardId.Linkspi) && c.Level == 1) + { + AI.SelectCard(c); + return true; + } + } + return false; + } + + public bool Linkuri_eff() + { + if (Duel.LastChainPlayer == 0 && Util.GetLastChainCard().IsCode(CardId.Linkuri)) return false; + AI.SelectCard(CardId.Tuner, CardId.BF + 1); + return true; + } + + public bool Crystal_ss() + { + if (crystal_eff_used) return false; + if (Bot.HasInMonstersZone(CardId.BF) && Bot.HasInMonstersZone(CardId.BF + 1)) + { + AI.SelectCard(CardId.BF, CardId.BF + 1); + return true; + } + foreach(ClientCard extra_card in Bot.GetMonstersInExtraZone()) + { + if (getLinkMarker(extra_card.Id) >= 5) return false; + } + IList targets = new List(); + foreach(ClientCard t_check in Bot.GetMonsters()) + { + if (t_check.IsFacedown()) continue; + if (t_check.IsCode(CardId.BF, CardId.Tuner, CardId.Urara, CardId.Ghost)) + { + targets.Add(t_check); + break; + } + } + if (targets.Count == 0) return false; + List m_list = new List(Bot.GetMonsters()); + m_list.Sort(CardContainer.CompareCardAttack); + foreach (ClientCard e_check in m_list) + { + if (e_check.IsFacedown()) continue; + if (targets[0] != e_check && getLinkMarker(e_check.Id) <= 2 && !e_check.IsCode(CardId.Eater, CardId.Crystal)) + { + targets.Add(e_check); + break; + } + } + if (targets.Count <= 1) return false; + AI.SelectMaterials(targets); + return true; + } + + public bool Crystal_eff() + { + if (Duel.Player == 0) + { + crystal_eff_used = true; + AI.SelectCard(CardId.Tuner, CardId.Ghost, CardId.Urara); + return true; + } + else if (Util.IsChainTarget(Card) || Util.GetProblematicEnemySpell() != null) return true; + else if (Duel.Player == 1 && Duel.Phase == DuelPhase.BattleStart && Util.IsOneEnemyBetterThanValue(1500,true)) { + if (Util.IsOneEnemyBetterThanValue(1900, true)) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + } + else + { + AI.SelectPosition(CardPosition.FaceUpAttack); + } + return true; + } + return false; + } + + public bool TG_eff() + { + if (Card.Location != CardLocation.MonsterZone) return true; + ClientCard target = Util.GetProblematicEnemySpell(); + IList list = new List(); + if (target != null) list.Add(target); + foreach(ClientCard spells in Enemy.GetSpells()) + { + if (spells != null && !list.Contains(spells)) list.Add(spells); + } + AI.SelectCard(list); + return true; + } + + public bool Safedragon_ss() + { + if (Util.IsTurn1OrMain2()) return false; + ClientCard m = Util.GetProblematicEnemyMonster(); + foreach(ClientCard ex_m in Bot.GetMonstersInExtraZone()) + { + if (getLinkMarker(ex_m.Id) >= 4) return false; + } + if ((m == null || m.HasPosition(CardPosition.FaceDown)) && Enemy.LifePoints <= 1100) + { + if (Enemy.GetMonsterCount() == 0 && Duel.Phase < DuelPhase.Battle) + { + IList list = new List(); + foreach(ClientCard monster in Bot.GetMonsters()) + { + if (getLinkMarker(monster.Id) <= 2) list.Add(monster); + if (list.Count == 2) break; + } + if (list.Count == 2 && GetTotalATK(list) <= 1100) + { + AI.SelectMaterials(list); + return true; + } + return false; + } + } + ClientCard ex_1 = Bot.MonsterZone[5]; + ClientCard ex_2 = Bot.MonsterZone[6]; + ClientCard ex = null; + if (ex_1 != null && ex_1.Controller == 0) ex = ex_1; + if (ex_2 != null && ex_2.Controller == 0) ex = ex_2; + if (ex == null) return false; + if (!ex.HasLinkMarker(2)) return false; + IList targets = new List(); + foreach (ClientCard s_m in Bot.GetMonsters()) + { + if (s_m.IsCode(CardId.Eater)) continue; + if (s_m != Bot.MonsterZone[5] && s_m != Bot.MonsterZone[6]) targets.Add(s_m); + if (targets.Count == 2) break; + } + if (targets.Count == 2) + { + AI.SelectMaterials(targets); + return true; + } + return false; + } + + public bool Phoneix_ss() + { + ClientCard m = Util.GetProblematicEnemySpell(); + if (m == null) + { + if (Enemy.GetMonsterCount() == 0 && Enemy.LifePoints <= 1900 && Duel.Phase == DuelPhase.Main1) + { + IList m_list = new List(); + List list = new List(Bot.GetMonsters()); + list.Sort(CardContainer.CompareCardAttack); + foreach(ClientCard monster in list) + { + if (getLinkMarker(monster.Id) == 1 && monster.IsFaceup()) m_list.Add(monster); + if (m_list.Count == 2) break; + } + if (m_list.Count == 2 && GetTotalATK(m_list) <= 1900) + { + AI.SelectMaterials(m_list); + return true; + } + } + return false; + } + if (Bot.Hand.Count == 0) return false; + IList targets = new List(); + List main_list = new List(Bot.GetMonstersInMainZone()); + main_list.Sort(CardContainer.CompareCardAttack); + foreach (ClientCard s_m in main_list) + { + if (s_m.IsFacedown()) continue; + if ((!s_m.IsCode(CardId.Eater) || (s_m.IsCode(CardId.Eater) && s_m.IsDisabled())) && !targets.ContainsCardWithId(s_m.Id)) + { + targets.Add(s_m); + }; + if (targets.Count == 2) break; + } + if (targets.Count < 2) + { + foreach (ClientCard s_m in Bot.GetMonstersInExtraZone()) + { + if (s_m.IsFacedown()) continue; + if (!s_m.IsCode(CardId.Eater) && !targets.ContainsCardWithId(s_m.Id)) + { + targets.Add(s_m); + }; + if (targets.Count == 2) break; + } + } + if (targets.Count < 2) return false; + AI.SelectMaterials(targets); + return true; + } + + public bool Phoneix_eff() + { + AI.SelectCard(Useless_List()); + ClientCard target = Util.GetProblematicEnemySpell(); + if (target != null) + { + AI.SelectNextCard(target); + } else + { + List spells = Enemy.GetSpells(); + RandomSort(spells); + foreach (ClientCard card in spells) + { + if ((card != stage_locked || card.HasPosition(CardPosition.FaceUp)) && !(card.IsShouldNotBeTarget() || card.IsShouldNotBeMonsterTarget())) AI.SelectNextCard(card); + } + } + return true; + } + + public bool Unicorn_ss() { + ClientCard m = Util.GetProblematicEnemyCard(); + int link_count = 0; + if (m == null) + { + if (Enemy.GetMonsterCount() == 0 && Enemy.LifePoints <= 2200 && Duel.Phase == DuelPhase.Main1) + { + IList m_list = new List(); + List _sort_list = new List(Bot.GetMonsters()); + _sort_list.Sort(CardContainer.CompareCardAttack); + foreach(ClientCard monster in _sort_list) + { + if (getLinkMarker(monster.Id) == 2) + { + link_count += 2; + m_list.Add(monster); + } else if (getLinkMarker(monster.Id) == 1 && monster.IsFaceup()) + { + link_count += 1; + m_list.Add(monster); + } + if (link_count >= 3) break; + } + if (link_count >= 3 && GetTotalATK(m_list) <= 2200) + { + AI.SelectMaterials(m_list); + return true; + } + } + return false; + } + if (Bot.Hand.Count == 0) return false; + IList targets = new List(); + List sort_list = Bot.GetMonsters(); + sort_list.Sort(CardContainer.CompareCardAttack); + foreach (ClientCard s_m in sort_list) + { + if ((!s_m.IsCode(CardId.Eater) || (s_m.IsCode(CardId.Eater) && m.IsMonsterHasPreventActivationEffectInBattle())) && getLinkMarker(s_m.Id) <= 2 && s_m.IsFaceup()) + { + if (!targets.ContainsCardWithId(s_m.Id)) + { + targets.Add(s_m); + link_count += getLinkMarker(s_m.Id); + } + if (link_count >= 3) break; + } + } + if (link_count < 3) return false; + AI.SelectMaterials(targets); + return true; + } + + public bool Unicorn_eff() + { + ClientCard m = Util.GetProblematicEnemyCard(); + if (m == null) return false; + // avoid cards that cannot target. + AI.SelectCard(Useless_List()); + IList enemy_list = new List(); + if (!m.IsShouldNotBeMonsterTarget() && !m.IsShouldNotBeTarget()) enemy_list.Add(m); + foreach(ClientCard enemy in Enemy.GetMonstersInExtraZone()) + { + if (enemy != null && !enemy_list.Contains(enemy) && !enemy.IsShouldNotBeMonsterTarget() && !enemy.IsShouldNotBeTarget()) enemy_list.Add(enemy); + } + foreach (ClientCard enemy in Enemy.GetMonstersInMainZone()) + { + if (enemy != null && !enemy_list.Contains(enemy) && !enemy.IsShouldNotBeMonsterTarget() && !enemy.IsShouldNotBeTarget()) enemy_list.Add(enemy); + } + foreach (ClientCard enemy in Enemy.GetSpells()) + { + if (enemy != null && !enemy_list.Contains(enemy) && !enemy.IsShouldNotBeMonsterTarget() && !enemy.IsShouldNotBeTarget()) enemy_list.Add(enemy); + } + if (enemy_list.Count > 0) + { + AI.SelectNextCard(enemy_list); + return true; + } else + { + return false; + } + } + + public bool Snake_ss() + { + IList targets = new List(); + // exzone fo first + foreach (ClientCard e_m in Bot.GetMonstersInExtraZone()) + { + if (e_m.Attack < 1900 && !targets.ContainsCardWithId(e_m.Id) && e_m.IsFaceup()) + { + targets.Add(e_m); + } + } + List sort_main_list = new List(Bot.GetMonstersInMainZone()); + sort_main_list.Sort(CardContainer.CompareCardAttack); + foreach (ClientCard m in sort_main_list) + { + if (m.Attack < 1900 && !targets.ContainsCardWithId(m.Id) && m.IsFaceup()) + { + targets.Add(m); + } + if (targets.Count >= 4) + { + if (Enemy.LifePoints <= GetTotalATK(targets) && Enemy.GetMonsterCount() == 0) return false; + AI.SelectMaterials(targets); + AI.SelectYesNo(true); + snake_four_s = true; + return true; + } + } + return false; + } + + public bool Snake_eff() + { + if (snake_four_s) + { + snake_four_s = false; + AI.SelectCard(Useless_List()); + return true; + } + //if (ActivateDescription == Util.GetStringId(CardId.Snake, 2)) return true; + if (ActivateDescription == Util.GetStringId(CardId.Snake, 1)) + { + foreach(ClientCard hand in Bot.Hand) + { + if (hand.IsCode(CardId.Red, CardId.Pink)) + { + AI.SelectCard(hand); + return true; + } + if (hand.IsCode(CardId.Urara, CardId.Ghost)) + { + if (Tuner_ss()) + { + AI.SelectCard(hand); + return true; + } + } + } + } + return false; + } + + public bool Missus_ss() + { + IList material_list = new List(); + foreach(ClientCard monster in Bot.GetMonsters()) + { + if (monster.HasAttribute(CardAttribute.Earth) && getLinkMarker(monster.Id) == 1) material_list.Add(monster); + if (material_list.Count == 2) break; + } + if (material_list.Count < 2) return false; + if (Enemy.GetMonsterCount() == 0 || Util.GetProblematicEnemyMonster(2000) == null) + { + AI.SelectMaterials(material_list); + return true; + } else if (Util.GetProblematicEnemyMonster(2000) != null && Bot.HasInExtra(CardId.Borrel) && !Bot.HasInMonstersZone(CardId.Missus)) + { + AI.SelectMaterials(material_list); + return true; + } + return false; + } + + public bool Missus_eff() + { + AI.SelectCard(CardId.MG, CardId.Missus, CardId.Snake); + return true; + } + + public bool Borrel_ss() + { + bool already_link2 = false; + IList material_list = new List(); + if (Util.GetProblematicEnemyMonster(2000) == null) Logger.DebugWriteLine("***borrel:null"); + else Logger.DebugWriteLine("***borrel:" + (Util.GetProblematicEnemyMonster(2000).Name ?? "unknown")); + if (Util.GetProblematicEnemyMonster(2000) != null || (Enemy.GetMonsterCount() == 0 && Duel.Phase == DuelPhase.Main1 && Enemy.LifePoints <= 3000)) + { + foreach(ClientCard e_m in Bot.GetMonstersInExtraZone()) + { + if (getLinkMarker(e_m.Id) < 3) + { + if (getLinkMarker(e_m.Id) == 2) already_link2 = true; + material_list.Add(e_m); + } + } + List sort_list = new List(Bot.GetMonstersInMainZone()); + sort_list.Sort(CardContainer.CompareCardAttack); + + foreach(ClientCard m in sort_list) + { + if (getLinkMarker(m.Id) < 3) + { + if (getLinkMarker(m.Id) == 2 && !already_link2) + { + already_link2 = true; + material_list.Add(m); + } else if (!m.IsCode(CardId.Sheep + 1, CardId.Eater)) + { + material_list.Add(m); + } + if ((already_link2 && material_list.Count == 3) || (!already_link2 && material_list.Count == 4)) break; + } + } + if ((already_link2 && material_list.Count == 3) || (!already_link2 && material_list.Count == 4)) + { + if (Enemy.GetMonsterCount() == 0 && Duel.Phase == DuelPhase.Main1 && Enemy.LifePoints <= 3000) + { + if (GetTotalATK(material_list) >= 3000) return false; + } + AI.SelectMaterials(material_list); + return true; + } + } + return false; + } + + public bool Borrel_eff() + { + if (ActivateDescription == -1) { + 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; + } + + // unfinished. + public bool GraveCall_eff() + { + if (!spell_trap_activate()) return false; + if (Duel.LastChainPlayer == 1) + { + if (Util.GetLastChainCard().IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (CheckWhetherNegated(code)) return false; + ClientCard target = Enemy.Graveyard.GetFirstMatchingCard(c => c.GetOriginCode() == code); + if (target != null) + { + currentNegatingIdList.Add(code); + AI.SelectCard(target); + return true; + } + } + } + return false; + } + + public bool DarkHole_eff() + { + if (!spell_trap_activate()) return false; + if (Bot.GetMonsterCount() == 0) + { + + int bestPower = -1; + foreach (ClientCard hand in Bot.Hand) + { + if (hand.IsMonster() && hand.Attack > bestPower) bestPower = hand.Attack; + } + int bestenemy = -1; + foreach (ClientCard enemy in Enemy.GetMonsters()) + { + if (enemy.IsMonsterDangerous()) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + if (enemy.IsFaceup() && (enemy.GetDefensePower() > bestenemy)) bestenemy = enemy.GetDefensePower(); + } + if (bestPower <= bestenemy) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + } + return false; + } + + public bool IsAllEnemyBetter() + { + int bestPower = -1; + for (int i = 0; i < 7; ++i) + { + ClientCard card = Bot.MonsterZone[i]; + if (card == null || card.Data == null) continue; + int newPower = card.Attack; + if (IsTrickstar(card) && Bot.HasInHand(CardId.White) && !white_eff_used) newPower += card.RealPower; + if (newPower > bestPower) + bestPower = newPower; + } + return Util.IsAllEnemyBetterThanValue(bestPower,true); + } + + public bool MonsterRepos() + { + if (Card.IsCode(CardId.Eater)) return (!Card.HasPosition(CardPosition.Attack)); + + if (IsTrickstar(Card) && !white_eff_used && Bot.HasInHand(CardId.White) && Card.IsAttack() && Duel.Phase == DuelPhase.Main1) return false; + + if (Card.IsFaceup() && Card.IsDefense() && Card.Attack == 0) + return false; + + if (Card.IsCode(CardId.Pink)) + { + if ((Bot.HasInSpellZone(CardId.Stage, true) && Enemy.LifePoints <= 1000) || (!Bot.HasInSpellZone(CardId.Stage, true) && Enemy.LifePoints <= 800)) + { + return !Card.HasPosition(CardPosition.Attack); + } + } + + bool enemyBetter = IsAllEnemyBetter(); + + if (Card.IsAttack() && enemyBetter) + return true; + if (Card.IsDefense() && !enemyBetter && Card.Attack >= Card.Defense) + return true; + return false; + } + + public override bool OnSelectHand() + { + // go first + return true; + } + + public override void OnNewTurn() + { + NormalSummoned = false; + stage_locked = null; + pink_ss = false; + snake_four_s = false; + crystal_eff_used = false; + white_eff_used = false; + lockbird_useful = false; + lockbird_used = false; + Impermanence_list.Clear(); + currentNegatingIdList.Clear(); + base.OnNewTurn(); + } + + public override void OnChaining(int player, ClientCard card) + { + if (card == null) return; + + if (player == 1) + { + if (card.IsCode(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == card) + { + Impermanence_list.Add(4-i); + break; + } + } + } + } + base.OnChaining(player, card); + } + + public override void OnChainEnd() + { + currentNegatingIdList.Clear(); + base.OnChainEnd(); + } + + public bool CheckWhetherNegated(int cardId) + { + return !DefaultCheckWhetherCardIdIsNegated(cardId) && !currentNegatingIdList.Contains(cardId); + } + + public override BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList defenders) + { + ClientCard lowestattack = null; + for (int i = defenders.Count - 1; i >= 0; --i) + { + ClientCard defender = defenders[i]; + if (defender.HasPosition(CardPosition.Attack) && !defender.IsMonsterDangerous() && (lowestattack == null || defender.Attack < lowestattack.Attack)) lowestattack = defender; + } + if (lowestattack != null && attacker.Attack - lowestattack.Attack >= Enemy.LifePoints) return AI.Attack(attacker, lowestattack); + for (int i = 0; i < defenders.Count; ++i) + { + ClientCard defender = defenders[i]; + + attacker.RealPower = attacker.Attack; + defender.RealPower = defender.GetDefensePower(); + + if (!defender.IsMonsterHasPreventActivationEffectInBattle() && !attacker.IsDisabled()) + { + if ((attacker.IsCode(CardId.Eater) && !defender.HasType(CardType.Token)) || attacker.IsCode(CardId.Borrel)) return AI.Attack(attacker, defender); + if ((attacker.IsCode(CardId.Ultimate, CardId.Cardian)) && attacker.RealPower > defender.RealPower) return AI.Attack(attacker, defender); + } + + if (!OnPreBattleBetween(attacker, defender)) + continue; + + if (attacker.RealPower > defender.RealPower || (attacker.RealPower >= defender.RealPower && attacker.IsLastAttacker && defender.IsAttack())) + return AI.Attack(attacker, defender); + } + + if (attacker.CanDirectAttack) + return AI.Attack(attacker, null); + + return null; + } + + public override ClientCard OnSelectAttacker(IList attackers, IList defenders) + { + for (int i = 0; i < attackers.Count; ++i) + { + ClientCard attacker = attackers[i]; + if (attacker.IsCode(CardId.Borrel, CardId.Eater)) return attacker; + } + return null; + } + + public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + if (!defender.IsMonsterHasPreventActivationEffectInBattle()) + { + if (IsTrickstar(attacker) && Bot.HasInHand(CardId.White) && !white_eff_used && !CheckWhetherNegated(CardId.White)) + attacker.RealPower += attacker.Attack; + } + return base.OnPreBattleBetween(attacker, defender); + } + + protected override bool DefaultSetForDiabellze() + { + if (base.DefaultSetForDiabellze()) + { + AI.SelectPlace(SelectSTPlace(Card, true)); + return true; + } + return false; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/WitchcraftExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/WitchcraftExecutor.cs new file mode 100644 index 0000000..8c2c8fa --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/WitchcraftExecutor.cs @@ -0,0 +1,2913 @@ +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("Witchcraft", "AI_Witchcraft")] + + class WitchcraftExecutor : DefaultExecutor + { + public class CardId + { + public const int PSYDriver = 49036338; + public const int GolemAruru = 71074418; + public const int MadameVerre = 21522601; + public const int Haine = 84523092; + public const int Schmietta = 21744288; + public const int Pittore = 95245544; + public const int PSYGamma = 38814750; + public const int Potterie = 59851535; + public const int Genni = 64756282; + public const int Collaboration = 10805153; + public const int ThatGrassLooksGreener = 11110587; + public const int PotofExtravagance = 49238328; + public const int DarkRulerNoMore = 54693926; + public const int Creation = 57916305; + public const int Reasoning = 58577036; + public const int MetalfoesFusion = 73594093; + public const int Holiday = 83301414; + public const int Draping = 56894757; + public const int Unveiling = 70226289; + public const int MagiciansLeftHand = 13758665; + public const int Scroll = 19673561; + public const int MagiciansRestage = 40252269; + public const int WitchcrafterBystreet = 83289866; + public const int MagicianRightHand = 87769556; + public const int Masterpiece = 55072170; + public const int Patronus = 94553671; + public const int BorreloadSavageDragon = 27548199; + public const int DracoBerserkeroftheTenyi = 5041348; + public const int PSYOmega = 74586817; + public const int TGWonderMagician = 98558751; + public const int BorrelswordDragon = 85289965; + public const int KnightmareUnicorn = 38342335; + public const int KnightmarePhoenix = 2857636; + public const int PSYLambda = 8802510; + public const int CrystronHalqifibrax = 50588353; + public const int SalamangreatAlmiraj = 60303245; + public const int RelinquishedAnima = 94259633; + + public const int NaturalExterio = 99916754; + public const int SwordsmanLV7 = 37267041; + public const int Anti_Spell = 58921041; + public const int Numbe41BagooskatheTerriblyTiredTapir = 90590303; + public const int PerformapalFive_RainbowMagician = 19619755; + + public const int DimensionShifter = 91800273; + public const int MacroCosmos = 30241314; + public const int DimensionalFissure = 81674782; + public const int BanisheroftheRadiance = 94853057; + public const int BanisheroftheLight = 61528025; + } + + public WitchcraftExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + // do first + AddExecutor(ExecutorType.Activate, CardId.PotofExtravagance, PotofExtravaganceActivate); + AddExecutor(ExecutorType.SpellSet, SpellSetForFiveRainbow); + + // clear + AddExecutor(ExecutorType.Activate, CardId.DarkRulerNoMore, DarkRulerNoMoreActivate); + AddExecutor(ExecutorType.Activate, _CardId.LightningStorm, LightningStormActivate); + AddExecutor(ExecutorType.Activate, CardId.RelinquishedAnima); + + // counter & quick effect + AddExecutor(ExecutorType.Activate, CardId.Schmietta, DeckSSWitchcraft); + AddExecutor(ExecutorType.Activate, CardId.Pittore, DeckSSWitchcraft); + AddExecutor(ExecutorType.Activate, CardId.Potterie, DeckSSWitchcraft); + AddExecutor(ExecutorType.Activate, CardId.Genni, DeckSSWitchcraft); + AddExecutor(ExecutorType.Activate, CardId.PSYGamma, PSYGammaActivate); + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + AddExecutor(ExecutorType.Activate, CardId.GolemAruru, GolemAruruActivate); + AddExecutor(ExecutorType.Activate, CardId.BorreloadSavageDragon, BorreloadSavageDragonActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossom_JoyousSpringActivate); + AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, CalledbytheGraveActivate); + AddExecutor(ExecutorType.Activate, _CardId.CrossoutDesignator, CrossoutDesignatorActivate); + AddExecutor(ExecutorType.Activate, CardId.MagicianRightHand, SpellsActivate); + AddExecutor(ExecutorType.Activate, CardId.MagiciansLeftHand, SpellsActivate); + AddExecutor(ExecutorType.Activate, CardId.Unveiling, UnveilingActivate); + AddExecutor(ExecutorType.Activate, CardId.Draping, DrapingActivate); + AddExecutor(ExecutorType.Activate, CardId.PSYOmega, PSYOmegaActivate); + AddExecutor(ExecutorType.Activate, CardId.DracoBerserkeroftheTenyi, DracoBerserkeroftheTenyiActivate); + AddExecutor(ExecutorType.Activate, CardId.MadameVerre, MadameVerreActivate); + AddExecutor(ExecutorType.Activate, CardId.Haine, HaineActivate); + AddExecutor(ExecutorType.Activate, CardId.SalamangreatAlmiraj, SalamangreatAlmirajActivate); + + // PSY auto + AddExecutor(ExecutorType.Activate, CardId.PSYLambda); + AddExecutor(ExecutorType.SpSummon, CardId.PSYLambda, PSYLambdaSummon); + AddExecutor(ExecutorType.SpSummon, CardId.PSYOmega, Lv8Summon); + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadSavageDragon, BorreloadSavageDragonSummon); + AddExecutor(ExecutorType.SpSummon, CardId.DracoBerserkeroftheTenyi, Lv8Summon); + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadSavageDragon, Lv8Summon); + + // auto + AddExecutor(ExecutorType.Activate, CardId.WitchcrafterBystreet, WitchcraftRecycle); + AddExecutor(ExecutorType.Activate, WitchcraftRecycle); + AddExecutor(ExecutorType.Activate, CardId.MetalfoesFusion); + AddExecutor(ExecutorType.Activate, CardId.TGWonderMagician, TGWonderMagicianActivate); + AddExecutor(ExecutorType.Activate, CardId.KnightmareUnicorn, KnightmareUnicornActivate); + AddExecutor(ExecutorType.Activate, CardId.KnightmarePhoenix, KnightmarePhoenixActivate); + AddExecutor(ExecutorType.Activate, CardId.CrystronHalqifibrax, CrystronHalqifibraxActivate); + + // activate with counter + AddExecutor(ExecutorType.Activate, CardId.ThatGrassLooksGreener, SpellsActivatewithCounter); + AddExecutor(ExecutorType.Activate, CardId.Reasoning, SpellsActivatewithCounter); + + // witchcraft summon + AddExecutor(ExecutorType.Activate, CardId.Masterpiece, MasterpieceActivate); + AddExecutor(ExecutorType.Activate, CardId.Patronus, PatronusActivate); + AddExecutor(ExecutorType.Activate, CardId.MagiciansRestage, MagiciansRestageActivate); + AddExecutor(ExecutorType.Activate, CardId.Holiday, HolidayActivate); + + // summon + AddExecutor(ExecutorType.Summon, CardId.Schmietta, WitchcraftSummon); + AddExecutor(ExecutorType.Summon, CardId.Pittore, WitchcraftSummon); + AddExecutor(ExecutorType.Summon, CardId.Potterie, WitchcraftSummon); + AddExecutor(ExecutorType.Summon, CardId.Genni, WitchcraftSummon); + AddExecutor(ExecutorType.Activate, CardId.Creation, CreationActivate); + + // witchcraft resources + AddExecutor(ExecutorType.Activate, CardId.Pittore, PittoreActivate); + AddExecutor(ExecutorType.Activate, CardId.Schmietta, SchmiettaActivate); + AddExecutor(ExecutorType.Activate, CardId.Genni, GenniActivate); + AddExecutor(ExecutorType.Activate, CardId.Potterie, PotterieActivate); + + // extra calling + AddExecutor(ExecutorType.SpSummon, CardId.KnightmarePhoenix, KnightmarePhoenixSummon); + AddExecutor(ExecutorType.SpSummon, CardId.RelinquishedAnima, RelinquishedAnimaSummon); + AddExecutor(ExecutorType.SpSummon, CardId.CrystronHalqifibrax, CrystronHalqifibraxSummon); + AddExecutor(ExecutorType.SpSummon, CardId.BorrelswordDragon, BorrelswordDragonSummon); + AddExecutor(ExecutorType.SpSummon, CardId.KnightmareUnicorn, KnightmareUnicornSummon); + AddExecutor(ExecutorType.SpSummon, CardId.SalamangreatAlmiraj, SalamangreatAlmirajSummon); + AddExecutor(ExecutorType.Summon, SummonForLink); + + // activate spells normally + AddExecutor(ExecutorType.Activate, CardId.ThatGrassLooksGreener, SpellsActivateNoCost); + AddExecutor(ExecutorType.Activate, CardId.Reasoning, SpellsActivateNoCost); + AddExecutor(ExecutorType.Activate, CardId.MagicianRightHand, SpellsActivateNoCost); + AddExecutor(ExecutorType.Activate, CardId.MagiciansLeftHand, SpellsActivateNoCost); + + //AddExecutor(ExecutorType.SummonOrSet); + + // rest + AddExecutor(ExecutorType.Summon, WitchcraftSummonForRecycle); + AddExecutor(ExecutorType.Repos, MonsterRepos); + AddExecutor(ExecutorType.Activate, CardId.WitchcrafterBystreet, WitchcrafterBystreetActivate); + AddExecutor(ExecutorType.Activate, CardId.Scroll, ScrollActivate); + AddExecutor(ExecutorType.SpellSet, SpellSet); + } + + int Witchcraft_setcode = 0x128; + int TimeLord_setcode = 0x4a; + int[] important_witchcraft = { CardId.Haine, CardId.MadameVerre }; + Dictionary witchcraft_level = new Dictionary { + {CardId.GolemAruru, 8}, {CardId.MadameVerre, 7}, {CardId.Haine, 7}, {CardId.Schmietta, 4}, + {CardId.Pittore, 3}, {CardId.Potterie, 2}, {CardId.Genni, 1} + }; + + List Impermanence_list = new List(); + List FirstCheckSS = new List(); + List UseSSEffect = new List(); + List ActivatedCards = new List(); + List currentNegatingIdList = new List(); + bool MadameVerreGainedATK = false; + bool summoned = false; + bool enemy_activate_MaxxC = false; + bool enemy_activate_DimensionShifter = false; + bool MagiciansLeftHand_used = false; + bool MagicianRightHand_used = false; + + // go first + public override bool OnSelectHand() + { + return true; + } + + // reset the negated card in case of activated again + public override void OnChainEnd() + { + currentNegatingIdList.Clear(); + base.OnChainEnd(); + } + + public override void OnChainSolved(int chainIndex) + { + ChainInfo currentCard = Duel.GetCurrentSolvingChainInfo(); + if (currentCard != null && currentCard.ActivatePlayer == 1) + { + if (Duel.IsCurrentSolvingChainNegated()) + { + // MagiciansLeftHand / MagicianRightHand + if (!MagicianRightHand_used && currentCard.IsSpell()) + { + if (Bot.MonsterZone.GetFirstMatchingCard(c => c.HasRace(CardRace.SpellCaster) && c.IsFaceup()) != null + && Bot.HasInSpellZone(CardId.MagicianRightHand, true)) + { + Logger.DebugWriteLine("MagicianRightHand negate: " + currentCard.RelatedCard.Name ?? "???"); + MagicianRightHand_used = true; + } + } + if (!MagiciansLeftHand_used && currentCard.IsTrap() && currentCard.ActivatePlayer == 1) + { + if (Bot.MonsterZone.GetFirstMatchingCard(c => c.HasRace(CardRace.SpellCaster) && c.IsFaceup()) != null + && Bot.HasInSpellZone(CardId.MagiciansLeftHand, true)) + { + Logger.DebugWriteLine("MagiciansLeftHand negate: " + currentCard.RelatedCard.Name ?? "???"); + MagiciansLeftHand_used = true; + } + } + } + if (!Duel.IsCurrentSolvingChainNegated()) + { + if (currentCard.IsCode(_CardId.MaxxC)) + enemy_activate_MaxxC = true; + if (currentCard.IsCode(CardId.DimensionShifter)) + enemy_activate_DimensionShifter = true; + if (currentCard.IsCode(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == currentCard.RelatedCard) + { + Impermanence_list.Add(4 - i); + break; + } + } + } + } + } + } + + // new turn reset + public override void OnNewTurn() + { + MadameVerreGainedATK = false; + summoned = false; + enemy_activate_MaxxC = false; + enemy_activate_DimensionShifter = false; + MagiciansLeftHand_used = false; + MagicianRightHand_used = false; + Impermanence_list.Clear(); + FirstCheckSS.Clear(); + UseSSEffect.Clear(); + ActivatedCards.Clear(); + currentNegatingIdList.Clear(); + base.OnNewTurn(); + } + + // power fix + public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + if (!defender.IsMonsterHasPreventActivationEffectInBattle()) + { + if (!MadameVerreGainedATK && Bot.HasInMonstersZone(CardId.MadameVerre, true, false, true) && attacker.HasSetcode(Witchcraft_setcode)) + { + attacker.RealPower += CheckPlusAttackforMadameVerre(); + } + } + return base.OnPreBattleBetween(attacker, defender); + } + + // overwrite OnSelectCard to act normally in SelectUnselect + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + // Patronus + if (hint == HintMsg.AddToHand) + { + bool flag = true; + foreach(ClientCard card in cards) + { + if (!card.HasSetcode(Witchcraft_setcode) || card.Location != CardLocation.Removed || !card.IsSpell()) + { + flag = false; + break; + } + } + if (flag) + { + Logger.DebugWriteLine("** Patronus recycle."); + // select all + IList selected = new List(); + for (int i = 1; i <= max; ++i) + { + selected.Add(cards[cards.Count - i]); + Logger.DebugWriteLine("** Select " + cards[cards.Count - i].Name ?? "???"); + } + return selected; + } + } + // MaxxC solution + if (hint == HintMsg.SpSummon && enemy_activate_MaxxC) + { + // check whether SS from deck while using effect + bool flag = true; + List levels = new List(); + List check_cardid = new List { CardId.Haine, CardId.MadameVerre, CardId.GolemAruru }; + List checked_card = new List { null, null, null }; + foreach (ClientCard card in cards) + { + if (card != null && card.Location == CardLocation.Deck && card.Controller == 0 && card.HasSetcode(Witchcraft_setcode)) + { + for (int i = 0; i < 3; ++i) + { + if (card.Id == check_cardid[i]) + { + checked_card[i] = card; + } + } + // Patronus also special summon from deck + if (!levels.Contains(card.Level)) + { + levels.Add(card.Level); + } + } + else + { + flag = false; + break; + } + } + + // only special summon advance monster + if (flag && levels.Count > 1) + { + Logger.DebugWriteLine("SS with MaxxC."); + IList result = new List(); + // check MadameVerre + int extra_attack = CheckPlusAttackforMadameVerre(true, true, true); + int bot_best = Util.GetBestAttack(Bot); + if (CheckProblematicCards() != null && Util.IsAllEnemyBetterThanValue(bot_best + extra_attack, true) == false) + { + if (!Bot.HasInMonstersZone(CardId.MadameVerre) && checked_card[1] != null) + { + result.Add(checked_card[1]); + return result; + } + } + for (int i = 0; i < 3; ++i) + { + if (checked_card[i] != null) + { + result.Add(checked_card[i]); + return result; + } + } + } + } + // MadameVerre + if (hint == HintMsg.Confirm) + { + Logger.DebugWriteLine("** min-max: " + min.ToString() + " / " + max.ToString()); + foreach (ClientCard card in cards) + { + Logger.DebugWriteLine(card.Name ?? "???"); + } + + // select all + IList selected = new List(); + for (int i = 1; i <= max; ++i) + { + selected.Add(cards[cards.Count - i]); + Logger.DebugWriteLine("** Select " + cards[cards.Count - i].Name ?? "???"); + } + return selected; + } + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + // position select + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + NamedCard Data = NamedCard.Get(cardId); + if (Data == null) + { + return base.OnSelectPosition(cardId, positions); + } + if (!Enemy.HasInMonstersZone(_CardId.BlueEyesChaosMAXDragon) + && (Duel.Player == 1 && (cardId == CardId.MadameVerre || + Util.GetOneEnemyBetterThanValue(Data.Attack + 1) != null)) + || cardId == _CardId.MaxxC || cardId == _CardId.AshBlossom) + { + return CardPosition.FaceUpDefence; + } + if (cardId == CardId.MadameVerre && Util.IsTurn1OrMain2()) + { + return CardPosition.FaceUpDefence; + } + return base.OnSelectPosition(cardId, positions); + } + + // shuffle List + public List CardListShuffle(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(n + 1); + ClientCard temp = result[index]; + result[index] = result[n]; + result[n] = temp; + } + return result; + } + + // check negated time count of id + public int CheckCalledbytheGrave(int id) + { + if (currentNegatingIdList.Contains(id)) return 1; + if (DefaultCheckWhetherCardIdIsNegated(id)) return 1; + return 0; + } + + // check enemy's dangerous card in grave + public List CheckDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && card.HasSetcode(0x11b)).ToList(); + return result; + } + + /// + /// Check count of discardable spells for witchcraft monsters. + /// + /// Card that prepared to use and can't discard. + public int CheckDiscardableSpellCount(ClientCard except = null) + { + int discardable_hands = 0; + int count_witchcraftspell = Bot.Hand.GetMatchingCardsCount(card => (card.IsSpell() && (card.HasSetcode(Witchcraft_setcode)) && card != except)); + int count_remainhands = CheckRemainInDeck(CardId.MagiciansLeftHand, CardId.MagicianRightHand); + int count_MagiciansRestage = Bot.Hand.GetMatchingCardsCount(card => card.Id == CardId.MagiciansRestage && card != except); + int count_MetalfoesFusion = Bot.Hand.GetCardCount(CardId.MetalfoesFusion); + int count_WitchcrafterBystreet = Bot.SpellZone.GetMatchingCardsCount(card => card.IsFaceup() && card.Id == CardId.WitchcrafterBystreet && !card.IsDisabled()); + if (count_MagiciansRestage > 0) + { + discardable_hands += (count_MagiciansRestage > count_remainhands ? count_remainhands : count_MagiciansRestage); + } + if (!ActivatedCards.Contains(CardId.WitchcrafterBystreet) && (count_WitchcrafterBystreet >= 2 || (count_WitchcrafterBystreet >= 1 && Duel.Phase > DuelPhase.Battle))) + { + discardable_hands += 1; + } + discardable_hands += count_witchcraftspell + count_MetalfoesFusion; + return discardable_hands; + } + + /// + /// Check whether last chain card should be disabled. + /// + public bool CheckLastChainNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + if (lastcard.IsMonster() && lastcard.HasSetcode(TimeLord_setcode) && Duel.Phase == DuelPhase.Standby) return false; + if (DefaultCheckWhetherCardIdIsNegated(lastcard.GetOriginCode())) return false; + + // MagiciansLeftHand / MagicianRightHand + if (!MagicianRightHand_used && lastcard.IsSpell()) + { + if (Bot.MonsterZone.GetFirstMatchingCard(c => c.HasRace(CardRace.SpellCaster) && c.IsFaceup()) != null + && Bot.HasInSpellZone(CardId.MagicianRightHand, true)) + { + return true; + } + } + if (!MagiciansLeftHand_used && lastcard.IsTrap()) + { + if (Bot.MonsterZone.GetFirstMatchingCard(c => c.HasRace(CardRace.SpellCaster) && c.IsFaceup()) != null + && Bot.HasInSpellZone(CardId.MagiciansLeftHand, true)) + { + return true; + } + } + return false; + } + + /// + /// Check whether match link condition. + /// + /// Min Link count + /// Min material count + /// materails list + /// whether need tuner + /// + public bool CheckLinkMaterialsMatch(int LinkCount, int MaterialCount, List list, bool need_tune = false) + { + // material count check + if (list.Count < MaterialCount) return false; + + // link marker check + int linkcount = 0; + foreach(ClientCard card in list) + { + linkcount += (card.HasType(CardType.Link) ? card.LinkCount : 1); + } + if (linkcount != LinkCount) + { + foreach (ClientCard card in list) + { + linkcount += 1; + } + if (linkcount != LinkCount) return false; + } + + // tuner check + if (need_tune && list.GetFirstMatchingCard(card => card.IsTuner()) == null) return false; + return true; + } + + /// + /// Check link summon materials. If not enough, return an empty list. + /// + /// Link monster's link count. + /// Link monster's least material count. + /// Whether materials need tuner(use for CrystronHalqifibrax) + /// Extra monster use for material check. + public List CheckLinkMaterials(int LinkCount, int MaterialCount, bool need_tuner = false, List extra = null) + { + List psy_cardids = new List { CardId.PSYGamma, CardId.PSYDriver }; + List result = Bot.MonsterZone.GetMatchingCards(card => card.IsFaceup() && psy_cardids.Contains(card.Id)).ToList(); + if (CheckLinkMaterialsMatch(LinkCount, MaterialCount, result, need_tuner)) return result; + + List bot_monsters = Enemy.MonsterZone.GetMatchingCards(c => c.IsFaceup()).ToList(); + if (extra != null) bot_monsters = bot_monsters.Union(extra).ToList(); + bot_monsters.Sort(CardContainer.CompareCardAttack); + + int remaindiscard = CheckDiscardableSpellCount(); + int enemybest = Util.GetBestAttack(Enemy); + foreach (ClientCard card in bot_monsters) + { + if ((card.HasSetcode(Witchcraft_setcode) && (card.Level >= 5 || remaindiscard >= 2)) + || (card.Attack >= enemybest) + || (card.HasType(CardType.Link) && card.LinkMarker > 2)) + { + continue; + } + result.Add(card); + if (CheckLinkMaterialsMatch(LinkCount, MaterialCount, result, need_tuner)) return result; + } + if (!CheckLinkMaterialsMatch(LinkCount, MaterialCount, result, need_tuner)) result.Clear(); + + return result; + } + + /// + /// Check how many attack MadameVerre can provide + /// + /// whether ignore the activate of MadameVerre + /// check prerecycle spells in grave + /// force check whether have MadameVerre + public int CheckPlusAttackforMadameVerre(bool ignore_activated = false, bool check_recycle = false, bool force = false) + { + // not MadameVerre on field + if (!force && Bot.MonsterZone.GetFirstMatchingCard(card => card.Id == CardId.MadameVerre && !card.IsDisabled()) == null) return 0; + if (!ignore_activated && MadameVerreGainedATK) return 0; + + HashSet spells_id = new HashSet(); + foreach(ClientCard card in Bot.Hand) + { + if (card.IsSpell()) + { + spells_id.Add(card.Id); + } + } + if (check_recycle && Bot.MonsterZone.GetFirstMatchingCard(card => card.IsFaceup() && card.HasSetcode(Witchcraft_setcode)) != null) + { + List spell_checklist = new List { CardId.Holiday, CardId.Creation, CardId.Draping, CardId.Unveiling, CardId.Collaboration }; + foreach (int cardid in spell_checklist) + { + if (Bot.HasInGraveyard(cardid) && !ActivatedCards.Contains(cardid)) + { + spells_id.Add(Card.Id); + } + } + } + int max_hand = spells_id.Count() >= 6 ? 6 : spells_id.Count(); + return max_hand * 1000; + + } + + /// + /// Check problematic cards on enemy's field. + /// + /// whether can be targeted + /// only check danger monsters + public ClientCard CheckProblematicCards(bool canBeTarget = false, bool OnlyDanger = false) + { + ClientCard card = Enemy.MonsterZone.GetFloodgate(canBeTarget); + if (card != null) + return card; + + card = Enemy.MonsterZone.GetDangerousMonster(canBeTarget); + if (card != null + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) + return card; + + card = Enemy.MonsterZone.GetInvincibleMonster(canBeTarget); + if (card != null + && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) + return card; + + List enemy_monsters = Enemy.MonsterZone.GetMatchingCards(c => c.IsFaceup()).ToList(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard target in enemy_monsters) + { + if (target.HasType(CardType.Fusion) || target.HasType(CardType.Ritual) || target.HasType(CardType.Synchro) || target.HasType(CardType.Xyz) || (target.HasType(CardType.Link) && target.LinkCount >= 2)) + { + if (!canBeTarget || !(target.IsShouldNotBeTarget() || target.IsShouldNotBeMonsterTarget())) return target; + } + } + + if (OnlyDanger) return null; + + int highest_self = Util.GetBestPower(Bot); + if (!MadameVerreGainedATK && Bot.HasInMonstersZone(CardId.MadameVerre, true, false, true)) + { + highest_self += CheckPlusAttackforMadameVerre(); + } + return Util.GetProblematicEnemyCard(highest_self, canBeTarget); + } + + /// + /// Check how many spells can be recylced to hand. + /// + public int CheckRecyclableCount(bool tohand = false, bool ignore_monster = false) + { + if (!ignore_monster && Bot.MonsterZone.GetFirstMatchingCard(card => card.IsFaceup() && card.HasSetcode(Witchcraft_setcode)) == null) return 0; + int result = 0; + List spell_checklist = new List { CardId.Holiday, CardId.Creation, CardId.Draping, CardId.Unveiling, CardId.Collaboration }; + if (!tohand) + { + spell_checklist.Add(CardId.WitchcrafterBystreet); + spell_checklist.Add(CardId.Scroll); + } + foreach (int cardid in spell_checklist) + { + if (Bot.HasInGraveyard(cardid) && !ActivatedCards.Contains(cardid)) + { + result++; + } + } + return result; + } + + /// + /// Check remain cards in deck + /// + /// Card's ID + public int CheckRemainInDeck(int id) + { + switch (id) + { + case CardId.PSYDriver: + return Bot.GetRemainingCount(CardId.PSYDriver, 1); + case CardId.GolemAruru: + return Bot.GetRemainingCount(CardId.GolemAruru, 1); + case CardId.MadameVerre: + return Bot.GetRemainingCount(CardId.MadameVerre, 1); + case CardId.Haine: + return Bot.GetRemainingCount(CardId.Haine, 2); + case CardId.Schmietta: + return Bot.GetRemainingCount(CardId.Schmietta, 3); + case CardId.Pittore: + return Bot.GetRemainingCount(CardId.Pittore, 3); + case _CardId.AshBlossom: + return Bot.GetRemainingCount(_CardId.AshBlossom, 1); + case CardId.PSYGamma: + return Bot.GetRemainingCount(CardId.PSYGamma, 3); + case _CardId.MaxxC: + return Bot.GetRemainingCount(_CardId.MaxxC, 1); + case CardId.Potterie: + return Bot.GetRemainingCount(CardId.Potterie, 1); + case CardId.Genni: + return Bot.GetRemainingCount(CardId.Genni, 2); + case CardId.Collaboration: + return Bot.GetRemainingCount(CardId.Collaboration, 1); + case CardId.ThatGrassLooksGreener: + return Bot.GetRemainingCount(CardId.ThatGrassLooksGreener, 2); + case _CardId.LightningStorm: + return Bot.GetRemainingCount(_CardId.LightningStorm, 2); + case CardId.PotofExtravagance: + return Bot.GetRemainingCount(CardId.PotofExtravagance, 3); + case CardId.DarkRulerNoMore: + return Bot.GetRemainingCount(CardId.DarkRulerNoMore, 2); + case CardId.Creation: + return Bot.GetRemainingCount(CardId.Creation, 3); + case CardId.Reasoning: + return Bot.GetRemainingCount(CardId.Reasoning, 3); + case CardId.MetalfoesFusion: + return Bot.GetRemainingCount(CardId.MetalfoesFusion, 1); + case CardId.Holiday: + return Bot.GetRemainingCount(CardId.Holiday, 3); + case _CardId.CalledByTheGrave: + return Bot.GetRemainingCount(_CardId.CalledByTheGrave, 3); + case CardId.Draping: + return Bot.GetRemainingCount(CardId.Draping, 1); + case _CardId.CrossoutDesignator: + return Bot.GetRemainingCount(_CardId.CrossoutDesignator, 2); + case CardId.Unveiling: + return Bot.GetRemainingCount(CardId.Unveiling, 1); + case CardId.MagiciansLeftHand: + return Bot.GetRemainingCount(CardId.MagiciansLeftHand, 1); + case CardId.Scroll: + return Bot.GetRemainingCount(CardId.Scroll, 1); + case CardId.MagiciansRestage: + return Bot.GetRemainingCount(CardId.MagiciansRestage, 2); + case CardId.WitchcrafterBystreet: + return Bot.GetRemainingCount(CardId.WitchcrafterBystreet, 3); + case CardId.MagicianRightHand: + return Bot.GetRemainingCount(CardId.MagicianRightHand, 1); + case _CardId.InfiniteImpermanence: + return Bot.GetRemainingCount(_CardId.InfiniteImpermanence, 3); + case CardId.Masterpiece: + return Bot.GetRemainingCount(CardId.Masterpiece, 1); + case CardId.Patronus: + return Bot.GetRemainingCount(CardId.Patronus, 2); + default: + return 0; + } + } + + /// + /// Check remain cards in deck + /// + /// Card's ID list + public int CheckRemainInDeck(params int[] ids) + { + int result = 0; + foreach (int cardid in ids) + { + result += CheckRemainInDeck(cardid); + } + return result; + } + + /// + /// Check whether cards will be removed. If so, do not send cards to grave. + /// + public bool CheckWhetherWillbeRemoved() + { + if (enemy_activate_DimensionShifter) return true; + List check_card = new List { CardId.BanisheroftheRadiance, CardId.BanisheroftheLight, CardId.MacroCosmos, CardId.DimensionalFissure }; + foreach(int cardid in check_card) + { + List fields = new List { Bot, Enemy }; + foreach (ClientField cf in fields) + { + if (cf.HasInMonstersZone(cardid, true) || cf.HasInSpellZone(cardid, true)) + { + return true; + } + } + } + return false; + } + + /// + /// Whether spell or trap will be negate. If so, return true. + /// + /// is counter trap + /// check target + /// + public bool SpellNegatable(bool isCounter = false, ClientCard target = null) + { + // target default set + if (target == null) target = Card; + if (CheckCalledbytheGrave(target.GetOriginCode()) > 0) return true; + // 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.NaturiaBeast, 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; + } + + /// + /// Check whether'll be negated + /// + public bool NegatedCheck(bool disablecheck = true){ + if (Card.IsSpell() || Card.IsTrap()){ + if (SpellNegatable()) return true; + } + if (CheckCalledbytheGrave(Card.GetOriginCode()) > 0){ + return true; + } + if (Card.IsMonster() && Card.Location == CardLocation.MonsterZone && Card.IsDefense()) + { + if (Enemy.MonsterZone.GetFirstMatchingFaceupCard(card => card.Id == CardId.Numbe41BagooskatheTerriblyTiredTapir && card.IsDefense() && !card.IsDisabled()) != null + || Bot.MonsterZone.GetFirstMatchingFaceupCard(card => card.Id == CardId.Numbe41BagooskatheTerriblyTiredTapir && card.IsDefense() && !card.IsDisabled()) != null) + { + return true; + } + } + if (disablecheck){ + return Card.IsDisabled(); + } + return false; + } + + /// + /// Select spell/trap's place randomly to avoid InfiniteImpermanence and so on. + /// + /// Card to set(default current card) + /// Whether need to avoid InfiniteImpermanence + /// Whether need to avoid set in this place + public void SelectSTPlace(ClientCard card = null, bool avoid_Impermanence = false, List avoid_list = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoid_Impermanence && Impermanence_list.Contains(seq)) continue; + if (avoid_list != null && avoid_list.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoid_Impermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + // Spell&trap's set + public bool SpellSet(){ + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + if (Card.Id == _CardId.CrossoutDesignator && Duel.Turn >= 5) return false; + + // set condition + int[] activate_with_condition = { CardId.Masterpiece, CardId.Draping }; + if (activate_with_condition.Contains(Card.Id)) + { + if (Bot.MonsterZone.GetFirstMatchingCard(card => card.HasSetcode(Witchcraft_setcode)) == null) + { + return false; + } + } + if (Card.Id == CardId.Unveiling) + { + return false; + } + if (Card.Id == CardId.Patronus) + { + int count = Bot.Banished.GetMatchingCardsCount(card => card.HasSetcode(Witchcraft_setcode)); + if (count == 0) + { + count += Bot.Graveyard.GetMatchingCardsCount(card => card.HasSetcode(Witchcraft_setcode)); + } + if (count == 0) + { + return false; + } + } + + // prepare spells to discard + if (Card.IsSpell()){ + int spells_todiscard = CheckRecyclableCount() + Bot.Hand.GetMatchingCardsCount(card => card.IsSpell()); + int will_discard = 0; + if (Bot.HasInMonstersZone(CardId.Haine)) will_discard ++; + if (Bot.HasInMonstersZone(CardId.MadameVerre)) will_discard ++; + + if (will_discard >= spells_todiscard){ + return false; + } + } + + // select place + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay))) + { + List avoid_list = new List(); + int Impermanence_set = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + Impermanence_set += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(Impermanence_set); + return true; + } else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } else + { + SelectSTPlace(); + } + return true; + } + // anti-spell relevant + else if (Enemy.HasInSpellZone(CardId.Anti_Spell, true) || Bot.HasInSpellZone(CardId.Anti_Spell, true)) + { + if (Card.IsSpell() && Card.Id != CardId.MetalfoesFusion) + { + SelectSTPlace(); + return true; + } + } + return false; + } + + // Spell&trap's set for Performapal Five-Rainbow Magician + public bool SpellSetForFiveRainbow() + { + // check + bool have_FiveRainbow = false; + List list = new List(); + if (Duel.IsNewRule || Duel.IsNewRule2020) + { + list.Add(Enemy.SpellZone[0]); + list.Add(Enemy.SpellZone[4]); + } + else + { + list.Add(Enemy.SpellZone[6]); + list.Add(Enemy.SpellZone[7]); + } + foreach(ClientCard card in list) + { + if (card != null && card.Id == CardId.PerformapalFive_RainbowMagician) + { + have_FiveRainbow = true; + break; + } + } + + if (!have_FiveRainbow) return false; + if (Bot.GetMonsterCount() == 0 || Bot.SpellZone.GetFirstMatchingCard(card => card.IsFacedown()) != null) return false; + if (Card.IsSpell()) + { + SelectSTPlace(null, true); + return true; + } + + return false; + } + + // use for repos + public bool MonsterRepos() + { + int self_attack = Card.Attack + 1; + int extra_attack = CheckPlusAttackforMadameVerre(true, true); + Logger.DebugWriteLine("self_attack of " + (Card.Name ?? "X") + ": " + self_attack.ToString()); + if (Card.HasSetcode(Witchcraft_setcode)) + { + self_attack += extra_attack; + } + + if (Card.IsFaceup() && Card.IsDefense() && self_attack <= 1) + return false; + + int best_attack = 0; + foreach (ClientCard card in Bot.GetMonsters()) + { + int attack = card.Attack; + if (card.HasSetcode(Witchcraft_setcode)) + { + attack += extra_attack; + } + if (attack >= best_attack) + { + best_attack = attack; + } + } + + bool enemyBetter = Util.IsAllEnemyBetterThanValue(best_attack, true); + + if (Card.IsAttack() && enemyBetter) + return true; + if (Card.IsDefense() && !enemyBetter && self_attack >= Card.Defense) + return true; + return false; + } + + /// + /// Select spell cost for Witchcraft. + /// + public void SelectDiscardSpell() + { + int count_remainhands = CheckRemainInDeck(CardId.MagiciansLeftHand, CardId.MagicianRightHand); + int count_witchcraftspell = Bot.Hand.GetMatchingCardsCount(card => (card.IsSpell() && (card.HasSetcode(Witchcraft_setcode)))); + int WitchcrafterBystreet_count = Bot.SpellZone.GetMatchingCardsCount(card => card.IsFaceup() && card.Id == CardId.WitchcrafterBystreet); + if (Bot.HasInHand(CardId.MagiciansRestage) && count_remainhands > 0) + { + AI.SelectCard(CardId.MagiciansRestage); + } + else if (Bot.HasInHand(CardId.MetalfoesFusion)) + { + AI.SelectCard(CardId.MetalfoesFusion); + } + else if (!ActivatedCards.Contains(CardId.Scroll) && Bot.SpellZone.GetCardCount(CardId.Scroll) > 0) + { + AI.SelectCard(Bot.SpellZone.GetFirstMatchingFaceupCard(card => card.Id == CardId.Scroll)); + ActivatedCards.Add(CardId.Scroll); + } + else if (!ActivatedCards.Contains(CardId.WitchcrafterBystreet) && WitchcrafterBystreet_count >= 2) + { + AI.SelectCard(Bot.SpellZone.GetFirstMatchingFaceupCard(card => card.Id == CardId.WitchcrafterBystreet)); + ActivatedCards.Add(CardId.WitchcrafterBystreet); + } + else if (count_witchcraftspell > 0) + { + List cost_list = new List{ CardId.Scroll, CardId.WitchcrafterBystreet, CardId.Collaboration, CardId.Unveiling, CardId.Draping }; + if (Duel.Player == 1) + { + cost_list.Add(CardId.Creation); + cost_list.Add(CardId.Holiday); + } else + { + cost_list.Add(CardId.Holiday); + cost_list.Add(CardId.Creation); + } + foreach (int cardid in cost_list) + { + IList targets = Bot.Hand.GetMatchingCards(card => card.Id == cardid); + if (targets.Count() > 0) + { + AI.SelectCard(targets); + return; + } + } + AI.SelectCard(CardId.Scroll, CardId.WitchcrafterBystreet); + } + else if (Bot.HasInHand(CardId.PotofExtravagance) && Bot.ExtraDeck.Count < 6) + { + AI.SelectCard(CardId.PotofExtravagance); + } + else if (WitchcrafterBystreet_count >= 1) + { + AI.SelectCard(Bot.SpellZone.GetFirstMatchingFaceupCard(card => card.Id == CardId.WitchcrafterBystreet)); + ActivatedCards.Add(CardId.WitchcrafterBystreet); + } + else + { + AI.SelectCard(CardId.ThatGrassLooksGreener, _CardId.LightningStorm, CardId.PotofExtravagance, CardId.MagiciansLeftHand, CardId.MagicianRightHand, _CardId.CrossoutDesignator, _CardId.CalledByTheGrave); + } + } + + /// + /// For normal spells activate + /// + public bool SpellsActivate() + { + if (SpellNegatable()) return false; + if (CheckDiscardableSpellCount() <= 1) return false; + if ((Card.Id == CardId.ThatGrassLooksGreener || Card.Id == CardId.Reasoning) && CheckWhetherWillbeRemoved()) return false; + if (Card.Id == CardId.MagiciansLeftHand || Card.Id == CardId.MagicianRightHand) + { + if (Bot.MonsterZone.GetFirstMatchingCard(card => card.HasRace(CardRace.SpellCaster)) == null + && (summoned || Bot.Hand.GetFirstMatchingCard(card => card.HasRace(CardRace.SpellCaster) && card.Level <= 4) == null)) + { + return false; + } + } + SelectSTPlace(Card, true); + return true; + } + + /// + /// For normal spells activate without cost + /// + public bool SpellsActivateNoCost() + { + if (SpellNegatable()) return false; + if ((Card.Id == CardId.ThatGrassLooksGreener || Card.Id == CardId.Reasoning) && CheckWhetherWillbeRemoved()) return false; + if (Card.Id == CardId.MagiciansLeftHand || Card.Id == CardId.MagicianRightHand) + { + if (Bot.MonsterZone.GetFirstMatchingCard(card => card.HasRace(CardRace.SpellCaster)) == null + && (summoned || Bot.Hand.GetFirstMatchingCard(card => card.HasRace(CardRace.SpellCaster) && card.Level <= 4) == null)) + { + return false; + } + } + SelectSTPlace(Card, true); + return true; + } + + /// + /// Check wheter have enough counter to care for important spells. if not, delay it. + /// + public bool SpellsActivatewithCounter() + { + if (SpellNegatable()) return false; + if ((Card.Id == CardId.ThatGrassLooksGreener || Card.Id == CardId.Reasoning) && CheckWhetherWillbeRemoved()) return false; + int[] counter_cards = { CardId.PSYGamma, _CardId.CalledByTheGrave, _CardId.CrossoutDesignator }; + int count = Bot.Hand.GetMatchingCardsCount(card => counter_cards.Contains(card.Id)); + count += Bot.SpellZone.GetMatchingCardsCount(card => counter_cards.Contains(card.Id)); + if (count > 0 || Bot.Hand.GetCardCount(Card.Id) >= 2) + { + SelectSTPlace(Card, true); + return true; + } + return Program.Rand.Next(2) > 0; + } + + /// + /// Summon Witchcraft for special summoning from deck. + /// + public bool WitchcraftSummon() + { + if (UseSSEffect.Contains(Card.Id)) return false; + int count_spell = Bot.Hand.GetMatchingCardsCount(card => (card.IsSpell())); + int count_target = CheckRemainInDeck(CardId.MadameVerre, CardId.Haine, CardId.GolemAruru); + if (count_spell > 0 && count_target > 0) + { + summoned = true; + return true; + } + return false; + } + + /// + /// Summon Witchcraft for recycling spells + /// + public bool WitchcraftSummonForRecycle() + { + if (!Card.HasSetcode(Witchcraft_setcode) || Card.Level > 4) + { + return false; + } + if (CheckRecyclableCount(false, true) > 0 && Bot.MonsterZone.GetFirstMatchingFaceupCard(card => card.HasSetcode(Witchcraft_setcode)) == null) + { + summoned = true; + return true; + } + return false; + } + + /// + /// Check whether summon monster for link summon. + /// + public bool SummonForLink() + { + // reject advance summon + if (Card.Level >= 5) return false; + summoned = true; + + if (BorrelswordDragonSummonCheck(Card).Count >= 3) + { + Logger.DebugWriteLine("Summon for BorrelswordDragon."); + List list = BorrelswordDragonSummonCheck(Card); + foreach( ClientCard c in list) + { + Logger.DebugWriteLine(c.Name ?? "???"); + } + return true; + } + if (KnightmareUnicornSummonCheck(Card).Count >= 2) + { + Logger.DebugWriteLine("Summon for KnightmareUnicorn."); + return true; + } + if (KnightmarePhoenixSummonCheck(Card).Count >= 2) + { + Logger.DebugWriteLine("Summon for KnightmarePhoenix."); + return true; + } + if (RelinquishedAnimaSummonCheck(Card) != -1) + { + Logger.DebugWriteLine("Summon for RelinquishedAnima."); + return true; + } + if (SalamangreatAlmirajSummonCheck(Card)) + { + Logger.DebugWriteLine("Summon for SalamangreatAlmiraj."); + return true; + } + + summoned = false; + return false; + } + + /// + /// Special Witchcraft from deck for all monsters, except spells/traps. + /// + /// max level can be special summoned. + public bool DeckSSWitchcraft() + { + if (Card.Location != CardLocation.MonsterZone) return false; + if (Duel.LastChainPlayer == 0) return false; + if (NegatedCheck(false)) return false; + if (Duel.Player == 0 && !FirstCheckSS.Contains(Card.Id)) + { + // activate when ask twice + FirstCheckSS.Add(Card.Id); + return false; + } + + // get discardable count + int discardable_hands = CheckDiscardableSpellCount(); + + // not must SS + if (discardable_hands == 0 && Bot.MonsterZone.GetFirstMatchingCard(card => card.HasSetcode(Witchcraft_setcode) && card.Level >= 6) != null) + { + return false; + } + + SelectDiscardSpell(); + + // check whether should call MadameVerre for destroying monster + bool lesssummon = false; + int extra_attack = CheckPlusAttackforMadameVerre(true, false, true); + int best_power = Util.GetBestAttack(Bot); + if (CheckRemainInDeck(CardId.Haine) > 0 && best_power < 2400) best_power = 2400; + Logger.DebugWriteLine("less summon check: " + (best_power + extra_attack - 1000).ToString() + " to " + (best_power + extra_attack).ToString()); + if (Util.GetOneEnemyBetterThanValue(best_power) != null + && Util.GetOneEnemyBetterThanValue(best_power + extra_attack) == null + && Util.GetOneEnemyBetterThanValue(best_power + extra_attack - 1000) != null) + { + lesssummon = true; + } + + // SS lower 4 + if (!enemy_activate_MaxxC && !lesssummon && discardable_hands >= 2 && Duel.Player == 0) + { + int[] SS_priority = { CardId.Schmietta, CardId.Pittore, CardId.Genni, CardId.Potterie }; + foreach (int cardid in SS_priority) + { + if (!UseSSEffect.Contains(cardid) && Card.Id != cardid && CheckRemainInDeck(cardid) > 0 + && Bot.MonsterZone.GetFirstMatchingCard(card => card.Id == cardid && card.IsFaceup()) == null) + { + UseSSEffect.Add(Card.Id); + AI.SelectNextCard(cardid); + return true; + } + } + } + + // check whether continue to ss + bool should_attack = Util.GetOneEnemyBetterThanValue(Card.Attack) == null; + if ((should_attack ^ Card.IsDefense()) && Duel.Player == 1) return false; + if (CheckRemainInDeck(CardId.Haine, CardId.MadameVerre, CardId.GolemAruru) == 0) return false; + + // SS higer level + if (Bot.HasInMonstersZone(CardId.Haine) || (lesssummon && !Bot.HasInMonstersZone(CardId.MadameVerre, true))) + { + AI.SelectNextCard(CardId.MadameVerre, CardId.Haine, CardId.GolemAruru); + } + else + { + AI.SelectNextCard(CardId.Haine, CardId.MadameVerre, CardId.GolemAruru); + } + UseSSEffect.Add(Card.Id); + return true; + } + + // recycle witchcraft spells in grave + public bool WitchcraftRecycle() + { + if (Card.IsSpell() && Card.HasSetcode(Witchcraft_setcode) && Card.Location == CardLocation.Grave) { + ActivatedCards.Add(Card.Id); + if (Card.HasType(CardType.Continuous)) + { + SelectSTPlace(Card); + } + return true; + } + return false; + } + + // activate of GolemAruru + public bool GolemAruruActivate() + { + if (ActivateDescription == Util.GetStringId(CardId.GolemAruru, 2)) + { + return true; + } + if (NegatedCheck()) return false; + ClientCard targetcard = CheckProblematicCards(true); + if (targetcard != null) + { + AI.SelectCard(targetcard); + return true; + } + AI.SelectCard(CardId.Holiday, CardId.Creation, CardId.Draping, CardId.Scroll, CardId.WitchcrafterBystreet, CardId.Unveiling, CardId.Collaboration ); + return true; + } + + // activate of MadameVerre + public bool MadameVerreActivate() + { + if (NegatedCheck(true)) return false; + // negate + if (ActivateDescription == Util.GetStringId(CardId.MadameVerre, 1)) + { + if (Card.IsDisabled()) return false; + if (CheckLastChainNegated()) return false; + + // negate before activate + if (Enemy.MonsterZone.GetFirstMatchingCard(card => card.IsMonsterShouldBeDisabledBeforeItUseEffect() && !card.IsDisabled()) != null) + { + SelectDiscardSpell(); + return true; + } + + // chain check + ClientCard LastChainCard = Util.GetLastChainCard(); + if ((LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.MonsterZone)) + { + // negate monsters' activate + SelectDiscardSpell(); + return true; + } + + // negate battle related effect + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + if (Enemy.MonsterZone.GetFirstMatchingCard(card => + card.IsMonsterDangerous() || (Duel.Player == 0) && card.IsMonsterInvincible()) != null) + { + SelectDiscardSpell(); + return true; + } + } + + return false; + } + // gain ATK + else + { + ClientCard self_card = Bot.BattlingMonster; + ClientCard enemy_card = Enemy.BattlingMonster; + if (self_card != null && enemy_card != null) + { + int power_cangain = CheckPlusAttackforMadameVerre(); + int diff = enemy_card.GetDefensePower() - self_card.GetDefensePower(); + Logger.DebugWriteLine("power: " + power_cangain.ToString()); + Logger.DebugWriteLine("diff: " + diff.ToString()); + if (diff > 0) + { + // avoid useless effect + if (self_card.IsDefense() && power_cangain < diff) + { + return false; + } + AI.SelectCard(Bot.Hand.GetMatchingCards(card => card.IsSpell())); + MadameVerreGainedATK = true; + return true; + } + else if (Enemy.GetMonsterCount() == 1 || (enemy_card.IsAttack() && Enemy.LifePoints <= diff + power_cangain)) + { + AI.SelectCard(Bot.Hand.GetMatchingCards(card => card.IsSpell())); + MadameVerreGainedATK = true; + return true; + } + } + } + return false; + } + + // activate of Haine + public bool HaineActivate() + { + if (NegatedCheck(true) || Duel.LastChainPlayer == 0) return false; + // danger check + ClientCard targetcard = Enemy.MonsterZone.GetFloodgate(true); + if (targetcard == null) + { + Logger.DebugWriteLine("*** Haine 2nd check."); + targetcard = Enemy.SpellZone.FirstOrDefault(card => card?.Data != null && card.IsFloodgate() && card.IsFaceup() && (!card.IsShouldNotBeTarget() || !Duel.ChainTargets.Contains(card))); + // GetFloodgate(true); + } + if (targetcard == null) + { + Logger.DebugWriteLine("*** Haine 3rd check."); + targetcard = CheckProblematicCards(true, (Duel.Phase <= DuelPhase.Main1 || Duel.Phase >= DuelPhase.Main2)); + if (targetcard != null && targetcard.HasSetcode(TimeLord_setcode) && !targetcard.IsDisabled()) targetcard = null; + } + if (targetcard == null && Duel.LastChainPlayer == 1) + { + Logger.DebugWriteLine("*** Haine 4th check."); + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard != null && !lastcard.IsDisabled() && !CheckLastChainNegated() + && (lastcard.HasType(CardType.Continuous) || lastcard.HasType(CardType.Equip) || lastcard.HasType(CardType.Field)) + && (lastcard.Location == CardLocation.SpellZone || lastcard.Location == CardLocation.FieldZone)) + { + targetcard = lastcard; + } + } + if (targetcard != null) + { + Logger.DebugWriteLine("*** Haine target: "+ targetcard.Name ?? "???"); + SelectDiscardSpell(); + AI.SelectNextCard(targetcard); + return true; + } + + // pendulum check + if (!CheckLastChainNegated()) + { + ClientCard l = null; + ClientCard r = null; + if (Duel.IsNewRule || Duel.IsNewRule2020) + { + l = Enemy.SpellZone[0]; + r = Enemy.SpellZone[4]; + } + else + { + l = Enemy.SpellZone[6]; + r = Enemy.SpellZone[7]; + } + if (l != null && r != null && l.LScale != r.RScale) + { + Logger.DebugWriteLine("*** Haine pendulum destroy"); + SelectDiscardSpell(); + AI.SelectNextCard(Program.Rand.Next(2) == 1 ? l : r); + return true; + } + } + + + // end check + if (Duel.Player == 0 && Duel.Phase == DuelPhase.End) + { + Logger.DebugWriteLine("*** Haine self check"); + int selected_cost = 0; + // spare spell check + int[] checklist = { CardId.Collaboration, CardId.Unveiling, CardId.Scroll, CardId.Holiday, CardId.Creation, CardId.Draping }; + foreach (int cardid in checklist) + { + if (!ActivatedCards.Contains(cardid) && Bot.HasInHand(cardid)) + { + selected_cost = cardid; + break; + } + } + + if (selected_cost == 0) return false; + IList target_1 = Enemy.SpellZone.GetMatchingCards(card => card.IsFaceup()); + IList target_2 = Enemy.MonsterZone.GetMatchingCards(card => card.IsFaceup()); + List targets = target_1.Union(target_2).ToList(); + if (targets.Count == 0) + { + return false; + } + // shuffle and select randomly + targets = CardListShuffle(targets); + AI.SelectCard(selected_cost); + AI.SelectNextCard(targets); + return true; + } + return false; + } + + // activate of Schmietta + public bool SchmiettaActivate() + { + if (Card.Location != CardLocation.Grave) return false; + if (NegatedCheck(false) || CheckWhetherWillbeRemoved()) return false; + // spell check + bool can_recycle = Bot.MonsterZone.GetFirstMatchingCard( + card => card.IsFaceup() && card.HasSetcode(Witchcraft_setcode) && card.Id != CardId.GolemAruru + ) != null; + if (can_recycle) + { + int[] spell_checklist = { CardId.WitchcrafterBystreet, CardId.Holiday, CardId.Creation, CardId.Draping, CardId.Scroll, CardId.Unveiling, CardId.Collaboration }; + foreach (int cardid in spell_checklist) + { + if (CheckRemainInDeck(cardid) > 0 && !Bot.HasInHandOrInSpellZone(cardid) && !Bot.HasInGraveyard(cardid) && !ActivatedCards.Contains(cardid)) + { + AI.SelectCard(cardid); + ActivatedCards.Add(CardId.Schmietta); + return true; + } + } + } + + bool can_find_Holiday = Bot.HasInHandOrInSpellZone(CardId.Holiday) || (can_recycle && Bot.HasInGraveyard(CardId.Holiday) && !(ActivatedCards.Contains(CardId.Holiday))); + // monster check + if (Bot.HasInHand(important_witchcraft) && !Bot.HasInGraveyard(CardId.Pittore) + && !ActivatedCards.Contains(CardId.Pittore) && CheckRemainInDeck(CardId.Pittore) > 0 && can_find_Holiday){ + AI.SelectCard(CardId.Pittore); + ActivatedCards.Add(CardId.Schmietta); + return true; + } + + // ss check + if (Bot.HasInHand(CardId.Holiday) && !ActivatedCards.Contains(CardId.Holiday) && !Bot.HasInGraveyard(important_witchcraft)) + { + AI.SelectCard(important_witchcraft); + ActivatedCards.Add(CardId.Schmietta); + return true; + } + + // copy check + if (!ActivatedCards.Contains(CardId.Genni)) + { + int has_Genni = Bot.HasInGraveyard(CardId.Genni) ? 1 : 0; + int has_Holiday = Bot.HasInGraveyard(CardId.Holiday) ? 1 : 0; + int has_important = Bot.HasInGraveyard(important_witchcraft) ? 1 : 0; + // lack one of them + if (has_Genni + has_Holiday + has_important == 2) + { + if (has_Genni == 0) + { + AI.SelectCard(CardId.Genni); + ActivatedCards.Add(CardId.Schmietta); + return true; + } + if (has_Holiday == 0) + { + AI.SelectCard(CardId.Holiday); + ActivatedCards.Add(CardId.Schmietta); + return true; + } + if (has_important == 0) + { + AI.SelectCard(important_witchcraft); + ActivatedCards.Add(CardId.Schmietta); + return true; + } + } + } + + // Pittore check + if (!ActivatedCards.Contains(CardId.Pittore) && !Bot.HasInGraveyard(CardId.Pittore)) + { + if (PittoreActivate()) + { + AI.SelectCard(CardId.Pittore); + ActivatedCards.Add(CardId.Schmietta); + return true; + } + } + + // trap check + if (CheckRemainInDeck(CardId.Masterpiece) >= 2){ + AI.SelectCard(CardId.Masterpiece); + ActivatedCards.Add(CardId.Schmietta); + return true; + } + + return false; + } + + // activate of Pittore + public bool PittoreActivate() + { + if (Card.Location != CardLocation.Grave) return false; + if (NegatedCheck(false) || CheckWhetherWillbeRemoved()) return false; + if (Bot.Hand.GetFirstMatchingCard(card => card.HasSetcode(Witchcraft_setcode)) == null) return false; + + // discard advance + if (Bot.Hand.GetFirstMatchingCard(card => card.Id == CardId.MadameVerre || card.Id == CardId.Haine) != null) + { + AI.SelectCard(CardId.MadameVerre, CardId.Haine); + ActivatedCards.Add(CardId.Pittore); + return true; + } + + // spell check + int[] spell_checklist = { CardId.Scroll, CardId.Unveiling, CardId.Collaboration, CardId.Draping, CardId.WitchcrafterBystreet, CardId.Holiday, CardId.Creation }; + foreach (int cardid in spell_checklist) + { + if (Bot.HasInHand(cardid) && !ActivatedCards.Contains(cardid)){ + AI.SelectCard(cardid); + ActivatedCards.Add(CardId.Pittore); + return true; + } + } + + // monster check + if ((Bot.HasInHand(CardId.Schmietta) && !ActivatedCards.Contains(CardId.Schmietta)) + ||Bot.Hand.GetMatchingCardsCount(card => card.HasSetcode(Witchcraft_setcode) && card.Level <= 4) >= 2){ + int[] monster_checklist = { CardId.Schmietta, CardId.Pittore, CardId.Genni, CardId.Potterie}; + foreach (int cardid in spell_checklist) + { + if (Bot.HasInHand(cardid)){ + AI.SelectCard(cardid); + ActivatedCards.Add(CardId.Pittore); + return true; + } + } + } + + return false; + } + + // activate of AshBlossom_JoyousSpring + public bool AshBlossom_JoyousSpringActivate() + { + if (NegatedCheck(true) || CheckLastChainNegated()) return false; + return DefaultAshBlossomAndJoyousSpring(); + } + + // activate of PSYGamma + public bool PSYGammaActivate() + { + if (NegatedCheck(true)) return false; + return true; + } + + // activate of MaxxC + public bool MaxxCActivate() + { + if (NegatedCheck(true)) return false; + return DefaultMaxxC(); + } + + // activate of Potterie + public bool PotterieActivate() + { + if (Card.Location != CardLocation.Grave) return false; + if (NegatedCheck(true)) return false; + + // Holiday check + if (!ActivatedCards.Contains(CardId.Holiday) && Bot.HasInGraveyard(CardId.Holiday)){ + if (Bot.HasInGraveyard(important_witchcraft)){ + AI.SelectCard(CardId.Holiday); + ActivatedCards.Add(CardId.Potterie); + return true; + } + } + + // safe check + if (CheckProblematicCards() == null){ + int[] checklist = {CardId.Patronus, CardId.GolemAruru}; + foreach (int cardid in checklist){ + if (Bot.HasInGraveyard(cardid)){ + AI.SelectCard(cardid); + ActivatedCards.Add(CardId.Potterie); + return true; + } + } + } + return false; + } + + // activate of Genni + public bool GenniActivate() + { + if (Card.Location != CardLocation.Grave) return false; + if (NegatedCheck(true)) return false; + + // Holiday check + int HolidayCount = Bot.Graveyard.GetMatchingCardsCount(card => card.Id == CardId.Holiday); + int SS_id = HolidayCheck(Card); + if (HolidayCount > 0 && SS_id > 0){ + AI.SelectCard(CardId.Holiday); + AI.SelectNextCard(SS_id); + ActivatedCards.Add(CardId.Genni); + return true; + } + + // Draping check + if (Bot.HasInGraveyard(CardId.Draping)){ + if (Enemy.GetMonsterCount() == 0 && Duel.Phase == DuelPhase.Main1){ + int total_attack = 0; + foreach (ClientCard card in Bot.GetMonsters()){ + total_attack += card.Attack; + } + // otk confirm + if (total_attack >= Enemy.LifePoints){ + int bot_count = Bot.MonsterZone.GetMatchingCardsCount(card => card.IsFaceup() && card.HasSetcode(Witchcraft_setcode)); + IList enemy_cards = Enemy.GetSpells(); + if (bot_count >= enemy_cards.Count()){ + AI.SelectCard(CardId.Draping); + AI.SelectNextCard(enemy_cards); + ActivatedCards.Add(CardId.Genni); + return true; + } + } + } + } + + return false; + } + + // activate of Collaboration + public bool CollaborationActivate() + { + if (Card.Location == CardLocation.Grave) return false; + if (NegatedCheck(true)) return false; + ClientCard target = Util.GetBestBotMonster(true); + if (Util.GetOneEnemyBetterThanMyBest() == null){ + if (Enemy.SpellZone.GetFirstMatchingCard(card => card.IsFacedown()) != null + || Enemy.MonsterZone.GetMatchingCardsCount(card => card.GetDefensePower() < target.Attack) >= 2){ + AI.SelectCard(target); + SelectSTPlace(null, true); + ActivatedCards.Add(CardId.Collaboration); + return true; + } + } + return false; + } + + // activate of LightningStorm + public bool LightningStormActivate() + { + int bestPower = 0; + foreach (ClientCard hand in Bot.Hand) + { + if (hand.IsMonster() && hand.Level <= 4 && hand.Attack > bestPower) bestPower = hand.Attack; + } + + int opt = -1; + // destroy monster + if (Enemy.MonsterZone.GetFirstMatchingCard(card => card.IsFloodgate() && card.IsAttack()) != null + || Enemy.MonsterZone.GetMatchingCardsCount(card => card.IsAttack() && card.Attack >= bestPower) >= 2) opt = 0; + // destroy spell/trap + else if (Enemy.GetSpellCount() >= 2 || Util.GetProblematicEnemySpell() != null) opt = 1; + + if (opt == -1) return false; + + // only one selection + if (Enemy.MonsterZone.GetFirstMatchingCard(card => card.IsAttack()) == null + || Enemy.GetSpellCount() == 0) + { + AI.SelectOption(0); + SelectSTPlace(null, true); + return true; + } + AI.SelectOption(opt); + SelectSTPlace(null, true); + return true; + } + + // 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; + } + + // activate of DarkRulerNoMore + public bool DarkRulerNoMoreActivate() + { + if (SpellNegatable()) return false; + if (Enemy.MonsterZone.GetFirstMatchingCard(card => card.IsFloodgate() && !card.IsDisabled()) != null) + { + SelectSTPlace(null, true); + return true; + } + return false; + } + + // activate of Creation + public bool CreationActivate() + { + if (Card.Location == CardLocation.Grave) return false; + if (NegatedCheck(true)) return false; + + // discard cost ensure + int least_cost = (Bot.HasInMonstersZone(CardId.Haine) ? 1 : 0) + (Bot.HasInMonstersZone(CardId.MadameVerre) ? 1 : 0); + int discardable = Bot.Hand.GetMatchingCardsCount(card => card != Card && card.IsSpell()) + CheckRecyclableCount() -1; + if (discardable < least_cost) return false; + + // search monster to summon + bool need_lower = (!summoned || ( + Bot.MonsterZone.GetFirstMatchingCard(card => card.HasSetcode(Witchcraft_setcode)) == null + && Bot.Hand.GetFirstMatchingCard(card => card.IsMonster() && card.HasSetcode(Witchcraft_setcode) && card.Level <= 4) == null)); + if (need_lower) + { + AI.SelectCard(CardId.Schmietta, CardId.Pittore, CardId.Genni, CardId.Potterie, CardId.GolemAruru); + SelectSTPlace(null, true); + ActivatedCards.Add(CardId.Creation); + return true; + } + // search GolemAruru + else + { + if (Bot.HasInHand(CardId.GolemAruru)) return false; + if (Bot.MonsterZone.GetFirstMatchingCard(card => card.IsFaceup() && card.HasSetcode(Witchcraft_setcode)) == null) + { + AI.SelectCard(CardId.GolemAruru, CardId.Schmietta, CardId.Pittore, CardId.Genni, CardId.Potterie); + SelectSTPlace(null, true); + ActivatedCards.Add(CardId.Creation); + return true; + } else + { + AI.SelectCard(CardId.Schmietta, CardId.Pittore, CardId.Genni, CardId.Potterie, CardId.GolemAruru); + SelectSTPlace(null, true); + ActivatedCards.Add(CardId.Creation); + return true; + } + } + } + + /// + /// Check Holiday's target. If nothing should be SS, return 0. + /// + /// + /// + public int HolidayCheck(ClientCard except_card = null){ + // SS important first + List check_list = new List { CardId.Haine, CardId.MadameVerre, CardId.GolemAruru}; + foreach (int cardid in check_list) + { + if (Bot.HasInGraveyard(cardid) && Bot.MonsterZone.GetFirstMatchingCard(card => card.IsFaceup() && card.Id == cardid) == null) + { + Logger.DebugWriteLine("*** Holiday check 1st: " + cardid.ToString()); + return cardid; + } + } + check_list.Clear(); + if (CheckProblematicCards() == null) + { + if (Bot.HasInGraveyard(CardId.GolemAruru) && Bot.MonsterZone.GetFirstMatchingCard(card => card.IsFaceup() && card.HasSetcode(Witchcraft_setcode)) != null) + { + Logger.DebugWriteLine("*** Holiday check 2nd: GolemAruru"); + return CardId.GolemAruru; + } + check_list.Add(CardId.Schmietta); + check_list.Add(CardId.Pittore); + check_list.Add(CardId.Genni); + check_list.Add(CardId.Potterie); + foreach (int cardid in check_list) + { + if (!UseSSEffect.Contains(cardid) && Bot.Graveyard.GetFirstMatchingCard(card => card.Id == cardid && card != except_card) != null && CheckDiscardableSpellCount(Card) > 0) + { + Logger.DebugWriteLine("*** Holiday check 3rd: " + cardid.ToString()); + return cardid; + } + } + } + else + { + check_list.Add(CardId.Haine); + check_list.Add(CardId.MadameVerre); + check_list.Add(CardId.GolemAruru); + foreach (int cardid in check_list) + { + if (Bot.Graveyard.GetFirstMatchingCard(card => card.Id == cardid && card != except_card) != null) + { + return cardid; + } + } + } + return 0; + } + + // activate of Holiday + public bool HolidayActivate() + { + if (Card.Location == CardLocation.Grave) return false; + if (NegatedCheck(true)) return false; + int target = HolidayCheck(); + if (target != 0) + { + AI.SelectCard(target); + SelectSTPlace(null, true); + ActivatedCards.Add(CardId.Holiday); + return true; + } + return false; + } + + // activate of CalledbytheGrave + public bool CalledbytheGraveActivate() + { + if (NegatedCheck(true)) return false; + if (Duel.LastChainPlayer == 1) + { + // negate + if (Util.GetLastChainCard().IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (CheckCalledbytheGrave(code) > 0) return false; + ClientCard target = Enemy.Graveyard.GetFirstMatchingCard(card => card.IsMonster() && card.IsOriginalCode(code)); + if (target != null) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(target); + currentNegatingIdList.Add(code); + return true; + } + } + + // banish target + foreach (ClientCard cards in Enemy.Graveyard) + { + if (Duel.ChainTargets.Contains(cards)) + { + int code = cards.GetOriginCode(); + AI.SelectCard(cards); + currentNegatingIdList.Add(code); + return true; + } + } + + // become targets + if (Duel.ChainTargets.Contains(Card)) + { + List enemy_monsters = Enemy.Graveyard.GetMatchingCards(card => card.IsMonster()).ToList(); + if (enemy_monsters.Count > 0) + { + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + int code = enemy_monsters[0].GetOriginCode(); + AI.SelectCard(enemy_monsters); + currentNegatingIdList.Add(code); + return true; + } + } + } + + // avoid danger monster in grave + if (Duel.LastChainPlayer == 1) return false; + List targets = CheckDangerousCardinEnemyGrave(true); + if (targets.Count() > 0) { + int code = targets[0].GetOriginCode(); + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(targets); + currentNegatingIdList.Add(code); + return true; + } + + return false; + } + + // activate of Draping + public bool DrapingActivate() + { + if (Card.Location == CardLocation.Grave) return false; + if (NegatedCheck(true)) return false; + + IList dangerours_spells = Enemy.SpellZone.GetMatchingCards(card => card.IsFloodgate() && !card.IsDisabled() && card.IsSpell()); + IList dangerours_traps = Enemy.SpellZone.GetMatchingCards(card => card.IsFloodgate() && !card.IsDisabled() && card.IsTrap()); + List faceup_spells = CardListShuffle(Enemy.SpellZone.GetMatchingCards(card => card.IsFaceup() && card.IsSpell()).ToList()); + List faceup_traps = CardListShuffle(Enemy.SpellZone.GetMatchingCards(card => card.IsFaceup() && card.IsTrap()).ToList()); + List setcards = CardListShuffle(Enemy.SpellZone.GetMatchingCards(card => card.IsFacedown()).ToList()); + if (Duel.Player == 0 || Duel.Phase == DuelPhase.End) + { + IList targets_1 = dangerours_spells.Union(dangerours_traps).Union(faceup_spells).Union(faceup_traps).Union(setcards).ToList(); + if (targets_1.Count() == 0) return false; + AI.SelectCard(targets_1); + SelectSTPlace(null, true); + ActivatedCards.Add(CardId.Draping); + return true; + } + IList targets_2 = dangerours_traps.Union(faceup_traps).ToList(); + if (targets_2.Count() == 0) return false; + targets_2 = targets_2.Union(dangerours_spells).Union(faceup_spells).Union(setcards).ToList(); + AI.SelectCard(targets_2); + SelectSTPlace(null, true); + ActivatedCards.Add(CardId.Draping); + return true; + } + + // activate of CrossoutDesignator + public bool CrossoutDesignatorActivate() + { + if (NegatedCheck(true) || CheckLastChainNegated()) return false; + // negate + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard() != null) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (CheckCalledbytheGrave(code) > 0) return false; + if (CheckRemainInDeck(code) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectAnnounceID(code); + currentNegatingIdList.Add(code); + return true; + } + } + return false; + } + + // activate of Unveiling + public bool UnveilingActivate() + { + if (Card.Location == CardLocation.Grave) return false; + if (NegatedCheck(true)) return false; + + // LightningStorm check + if (Bot.HasInHandOrInSpellZone(_CardId.LightningStorm)) + { + int faceup_count = Bot.SpellZone.GetMatchingCardsCount(card => card.IsFaceup()); + faceup_count += Bot.MonsterZone.GetMatchingCardsCount(card => card.IsFaceup()); + if (faceup_count == 0 && LightningStormActivate()) + { + return false; + } + } + + if (Bot.HasInHand(important_witchcraft)) + { + AI.SelectCard(important_witchcraft); + SelectSTPlace(null, true); + ActivatedCards.Add(CardId.Unveiling); + return true; + } + return false; + } + + // activate of Scroll + public bool ScrollActivate() + { + if (SpellNegatable() || Card.Location == CardLocation.Grave || Duel.Phase == DuelPhase.Main2) + { + return false; + } + if (Bot.MonsterZone.GetFirstMatchingCard(card => card.HasRace(CardRace.SpellCaster)) == null) + { + return false; + } + SelectSTPlace(null, true); + return true; + } + + // activate of MagiciansRestage + public bool MagiciansRestageActivate() + { + // search + if (Card.Location == CardLocation.Grave) + { + if (Enemy.SpellZone.GetFirstMatchingCard(card => card.IsFacedown()) != null) + { + AI.SelectCard(CardId.MagiciansLeftHand, CardId.MagicianRightHand); + } + else + { + AI.SelectCard(CardId.MagicianRightHand, CardId.MagiciansLeftHand); + } + return true; + } + + if (SpellNegatable()) + { + return false; + } + + // find target + if (CheckDiscardableSpellCount(Card) < 1) return false; + int target = 0; + int[] target_list = { CardId.Genni, CardId.Pittore, CardId.Potterie }; + foreach (int cardid in target_list) + { + if (!UseSSEffect.Contains(cardid) && Bot.HasInGraveyard(cardid)) + { + target = cardid; + break; + } + } + if (target == 0) return false; + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(null, true); + return true; + } + AI.SelectCard(target); + return true; + } + + // activate of WitchcrafterBystreet + public bool WitchcrafterBystreetActivate() + { + if (SpellNegatable() || Card.Location == CardLocation.Grave) + { + return false; + } + if (Bot.HasInSpellZone(CardId.WitchcrafterBystreet, true) || Bot.MonsterZone.GetFirstMatchingCard(card => card.HasSetcode(Witchcraft_setcode) && card.IsFaceup()) == null) + { + return false; + } + SelectSTPlace(null, true); + return true; + } + + // activate of Impermanence + public bool InfiniteImpermanenceActivate() + { + if (SpellNegatable()) return false; + if (CheckLastChainNegated()) return false; + // negate before monster's effect's used + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (!m.IsDisabled() && Duel.LastChainPlayer != 0 && + ((m.IsMonsterShouldBeDisabledBeforeItUseEffect() || m.IsFloodgate()) + || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2 && + (m.IsMonsterDangerous() || m.IsMonsterInvincible() + || (m.IsMonsterHasPreventActivationEffectInBattle() && Bot.HasInMonstersZone(CardId.MadameVerre))) + ))) + { + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(m); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + // negate spells + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || (Util.IsChainTarget(Card)) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + Impermanence_list.Add(this_seq); + return true; + } + } + } + } + + // negate monsters + if ((LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || CheckLastChainNegated() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget())) + return false; + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + Impermanence_list.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemy_monsters = Enemy.GetMonsters(); + enemy_monsters.Sort(CardContainer.CompareCardAttack); + enemy_monsters.Reverse(); + foreach (ClientCard card in enemy_monsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + return true; + } + } + } + return true; + } + + // activate of Masterpiece + public bool MasterpieceActivate() + { + // search effect + if (Card.Location == CardLocation.SpellZone) + { + if (NegatedCheck(true)) return false; + // select randomly (TODO) + IList target_1 = Bot.Graveyard.GetMatchingCards(card => card.IsSpell() && CheckRemainInDeck(card.Id) > 0); + IList target_2 = Enemy.Graveyard.GetMatchingCards(card => card.IsSpell() && CheckRemainInDeck(card.Id) > 0); + List targets = CardListShuffle(target_1.Union(target_2).ToList()); + AI.SelectCard(targets); + return true; + } + else + // ss effect + { + // LightningStorm check + if (Bot.HasInHandOrInSpellZone(_CardId.LightningStorm)) + { + int faceup_count = Bot.SpellZone.GetMatchingCardsCount(card => card.IsFaceup()); + faceup_count += Bot.MonsterZone.GetMatchingCardsCount(card => card.IsFaceup()); + if (faceup_count == 0 && LightningStormActivate()) + { + return false; + } + } + + List tobanish_spells = CardListShuffle(Bot.Graveyard.GetMatchingCards(card => card.IsSpell() && !card.HasSetcode(Witchcraft_setcode) && card.Id != CardId.MetalfoesFusion).ToList()); + if (Bot.HasInGraveyard(CardId.Patronus)) + { + List witchcraft_spells = CardListShuffle(Bot.Graveyard.GetMatchingCards(card => card.IsSpell() && card.HasSetcode(Witchcraft_setcode)).ToList()); + tobanish_spells = witchcraft_spells.Union(tobanish_spells).ToList(); + } + int max_level = tobanish_spells.Count(); + + //check discardable count + int discardable_hands = CheckDiscardableSpellCount(); + List will_discard_list = new List { CardId.Haine, CardId.MadameVerre, CardId.Schmietta, CardId.Pittore, CardId.Potterie, CardId.Genni }; + foreach (int cardid in will_discard_list) + { + if (Bot.HasInMonstersZone(cardid)) + { + discardable_hands--; + } + } + + // SS lower 4 + if (discardable_hands >= 1 && Duel.Player == 0) + { + int[] SS_priority = { CardId.Schmietta, CardId.Pittore, CardId.Genni, CardId.Potterie }; + foreach (int cardid in SS_priority) + { + int level = witchcraft_level[cardid]; + if (!UseSSEffect.Contains(cardid) & CheckRemainInDeck(cardid) > 0 && level <= max_level) + { + AI.SelectNumber(level); + AI.SelectCard(tobanish_spells); + AI.SelectNextCard(cardid); + return true; + } + } + } + + // SS higer level + List ss_priority = new List(); + if (Bot.HasInMonstersZone(CardId.Haine)) + { + ss_priority.Add(CardId.MadameVerre); + ss_priority.Add(CardId.Haine); + } + else + { + ss_priority.Add(CardId.Haine); + ss_priority.Add(CardId.MadameVerre); + } + ss_priority.Add(CardId.GolemAruru); + foreach (int cardid in ss_priority) + { + int level = witchcraft_level[cardid]; + if (CheckRemainInDeck(cardid) > 0 && level <= max_level) + { + AI.SelectNumber(level); + AI.SelectCard(tobanish_spells); + AI.SelectNextCard(cardid); + return true; + } + } + + } + return false; + } + + // activate of Patronus + public bool PatronusActivate() + { + // activate immediately + if (ActivateDescription == 94) + { + return true; + } + // search + if (Card.Location == CardLocation.SpellZone) + { + if (NegatedCheck(true) || Duel.LastChainPlayer == 0) return false; + // find lack of spells + int lack_spells = 0; + int[] spell_checklist = { CardId.WitchcrafterBystreet, CardId.Holiday, CardId.Creation, CardId.Draping, CardId.Scroll, CardId.Unveiling, CardId.Collaboration }; + foreach (int cardid in spell_checklist) + { + if (!Bot.HasInHandOrInSpellZone(cardid) && !Bot.HasInGraveyard(cardid)) + { + lack_spells = cardid; + break; + } + } + + // banish check + List banish_checklist = new List{ CardId.Haine, CardId.MadameVerre, CardId.GolemAruru, CardId.Schmietta, CardId.Pittore}; + if (lack_spells == 0) + { + List new_list = new List { CardId.Pittore, CardId.Genni, CardId.Schmietta, CardId.Potterie }; + banish_checklist = banish_checklist.Union(new_list).ToList(); + } + else + { + List new_list = new List { CardId.Schmietta, CardId.Pittore, CardId.Genni, CardId.Potterie }; + banish_checklist = banish_checklist.Union(new_list).ToList(); + } + foreach(int cardid in banish_checklist) + { + ClientCard target = Bot.Banished.GetFirstMatchingCard(card => card.Id == cardid); + if (target != null) + { + AI.SelectCard(target); + AI.SelectNextCard(lack_spells); + return true; + } + } + } + + // recycle + if (Card.Location == CardLocation.Grave) + { + if (Bot.HasInHandOrInSpellZoneOrInGraveyard(CardId.Masterpiece)) + { + return false; + } + IList targets = Bot.Banished.GetMatchingCards(card => card.IsSpell() && card.HasSetcode(Witchcraft_setcode)); + AI.SelectCard(targets); + return true; + } + return false; + } + + // summmon process of Level 8 Synchro Monster + public bool Lv8Summon() + { + if (Bot.HasInMonstersZone(CardId.PSYGamma) && Bot.HasInMonstersZone(CardId.PSYDriver)) + { + List targets = new List { CardId.PSYDriver, CardId.PSYGamma }; + AI.SelectMaterials(targets); + return true; + } + return false; + } + + // summon process of BorreloadSavageDragon + public bool BorreloadSavageDragonSummon() + { + if (Bot.Graveyard.GetFirstMatchingCard(card => card.HasType(CardType.Link)) == null) + { + return false; + } + return Lv8Summon(); + } + + // equip target comparer for BorreloadSavageDragon + public static int BorreloadSavageDragonEquipCompare(ClientCard cardA, ClientCard cardB) + { + if (cardA.LinkCount > cardB.LinkCount) + return -1; + if (cardA.LinkCount < cardB.LinkCount) + return -1; + if (cardA.Attack > cardB.Attack) + return 1; + if (cardA.Attack < cardB.Attack) + return -1; + return 0; + } + + // activate of BorreloadSavageDragon + public bool BorreloadSavageDragonActivate() + { + // equip + if (ActivateDescription == Util.GetStringId(CardId.BorreloadSavageDragon, 0)) + { + List links = Bot.Graveyard.GetMatchingCards(card => card.HasType(CardType.Link)).ToList(); + links.Sort(BorreloadSavageDragonEquipCompare); + AI.SelectCard(links); + return true; + } + // negate + if (NegatedCheck(true) || Duel.LastChainPlayer != 1) return false; + if (Util.GetLastChainCard().HasSetcode(0x11e) && Util.GetLastChainCard().Location == CardLocation.Hand) return false; + return false; + } + + // activate of DracoBerserkeroftheTenyi(TODO) + public bool DracoBerserkeroftheTenyiActivate() + { + Logger.DebugWriteLine("DracoBerserkeroftheTenyi's Effect: " + ActivateDescription.ToString()); + return true; + } + + // activate of PSYOmega + public bool PSYOmegaActivate() + { + // recycle + if (Duel.Phase == DuelPhase.Standby) + { + if (Bot.Banished.Count == 0) + { + return false; + } + List targets = CardListShuffle(Bot.Banished.GetMatchingCards(card => card.HasSetcode(Witchcraft_setcode)).ToList()); + AI.SelectCard(targets); + return true; + } + // banish hands + if (Card.Location == CardLocation.MonsterZone) + { + if (Duel.Player == 1 || Bot.HasInMonstersZone(CardId.PSYLambda) || (Util.IsChainTarget(Card)) ) + { + return true; + } else + { + return Util.IsAllEnemyBetterThanValue(Card.Attack, true); + } + } + // recycle from grave + if (Card.Location == CardLocation.Grave) + { + List enemy_danger = CheckDangerousCardinEnemyGrave(); + if (enemy_danger.Count > 0) + { + AI.SelectCard(enemy_danger); + return true; + } + if (!Bot.HasInHandOrInSpellZoneOrInGraveyard(CardId.Holiday) && Bot.HasInGraveyard(important_witchcraft)) + { + AI.SelectCard(important_witchcraft); + return true; + } + if (CheckProblematicCards() == null) + { + AI.SelectCard(_CardId.CalledByTheGrave, _CardId.CrossoutDesignator, + _CardId.MaxxC, _CardId.AshBlossom, + CardId.MagicianRightHand, CardId.MagiciansLeftHand, CardId.MagiciansRestage, CardId.Patronus, + _CardId.LightningStorm, CardId.Reasoning); + return true; + } + } + return false; + } + + // activate of TGWonderMagician + public bool TGWonderMagicianActivate() + { + if (Card.Location != CardLocation.MonsterZone) return true; + Logger.DebugWriteLine("TGWonderMagician: " + ActivateDescription.ToString()); + List problem_cards = Enemy.SpellZone.GetMatchingCards(card => card.IsFloodgate()).ToList(); + List faceup_cards = Enemy.SpellZone.GetMatchingCards(card => card.IsFaceup()).ToList(); + List facedown_cards = Enemy.SpellZone.GetMatchingCards(card => card.IsFacedown()).ToList(); + List result = problem_cards.Union(faceup_cards).ToList().Union(facedown_cards).ToList(); + AI.SelectCard(result); + return true; + } + + // check whether summon BorrelswordDragon + public List BorrelswordDragonSummonCheck(ClientCard included = null) + { + List empty_list = new List(); + List extra_list = new List(); + if (included != null) extra_list.Add(included); + List materials = CheckLinkMaterials(4, 3, false, extra_list); + if (materials.Count < 3) return empty_list; + + // need BorrelswordDragon? + // for problem monster + ClientCard flag = Util.GetOneEnemyBetterThanMyBest(); + if (flag != null) + { + return materials; + } + // for higher attack + int total_attack = 0; + foreach (ClientCard card in materials) + { + total_attack += card.Attack; + } + if (total_attack >= 3000) return empty_list; + + return materials; + } + + // summon process of BorrelswordDragon + public bool BorrelswordDragonSummon() + { + List materials = BorrelswordDragonSummonCheck(); + if (materials.Count < 3) return false; + AI.SelectMaterials(materials); + return true; + } + + // activate of BorrelswordDragon + public bool BorrelswordDragonActivate() + { + if (ActivateDescription == -1) + { + 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; + } + + // check whether summon KnightmareUnicorn + public List KnightmareUnicornSummonCheck(ClientCard included = null) + { + List empty_list = new List(); + List extra_list = new List(); + if (included != null) extra_list.Add(included); + List materials = CheckLinkMaterials(3, 2, false, extra_list); + if (materials.Count < 2) return empty_list; + + // need KnightmareUnicorn? + // for clear spells + ClientCard flag = CheckProblematicCards(true, true); + if (flag != null) + { + if (Bot.Hand.GetMatchingCardsCount(card => card != Card) == 0) + { + return empty_list; + } + else + { + return materials; + } + } + // for higher attack + int total_attack = 0; + foreach(ClientCard card in materials) + { + total_attack += card.Attack; + } + if (total_attack >= 2200) return empty_list; + + return materials; + } + + // summon process of KnightmareUnicorn + public bool KnightmareUnicornSummon() + { + List materials = KnightmareUnicornSummonCheck(); + if (materials.Count < 2) return false; + AI.SelectMaterials(materials); + return true; + } + + // activate of KnightmareUnicorn + public bool KnightmareUnicornActivate() + { + ClientCard card = CheckProblematicCards(true); + if (card == null) return false; + // avoid cards that cannot target. + IList enemy_list = new List(); + if (!card.IsShouldNotBeMonsterTarget() && !card.IsShouldNotBeTarget()) enemy_list.Add(card); + foreach (ClientCard enemy in Enemy.GetMonstersInExtraZone()) + { + if (enemy != null && !enemy_list.Contains(enemy) && !enemy.IsShouldNotBeMonsterTarget() && !enemy.IsShouldNotBeTarget()) enemy_list.Add(enemy); + } + foreach (ClientCard enemy in Enemy.GetMonstersInMainZone()) + { + if (enemy != null && !enemy_list.Contains(enemy) && !enemy.IsShouldNotBeMonsterTarget() && !enemy.IsShouldNotBeTarget()) enemy_list.Add(enemy); + } + foreach (ClientCard enemy in Enemy.GetSpells()) + { + if (enemy != null && !enemy_list.Contains(enemy) && !enemy.IsShouldNotBeMonsterTarget() && !enemy.IsShouldNotBeTarget()) enemy_list.Add(enemy); + } + if (enemy_list.Count > 0) + { + SelectDiscardSpell(); + AI.SelectNextCard(enemy_list); + return true; + } + return false; + } + + // check whether summon KnightmarePhoenix + public List KnightmarePhoenixSummonCheck(ClientCard included = null) + { + List empty_list = new List(); + List extra_list = new List(); + if (included != null) extra_list.Add(included); + List materials = CheckLinkMaterials(2, 2, true, extra_list); + if (materials.Count < 2) return empty_list; + + // need KnightmarePhoenix? + // for clear spells + ClientCard flag = Util.GetProblematicEnemySpell(); + if (flag != null) + { + if (Bot.Hand.GetMatchingCardsCount(card => card != Card) == 0) + { + return empty_list; + } else + { + return materials; + } + } + // for higher attack + if (materials[0].Attack + materials[1].Attack >= 1900) return empty_list; + + return materials; + } + + // summon process of KnightmarePhoenix + public bool KnightmarePhoenixSummon() + { + List materials = KnightmarePhoenixSummonCheck(); + if (materials.Count < 2) return false; + AI.SelectMaterials(materials); + return true; + } + + // activate of KnightmarePhoenix + public bool KnightmarePhoenixActivate() + { + List targets = new List(); + targets.Add(Util.GetProblematicEnemySpell()); + List spells = Enemy.GetSpells(); + List faceups = new List(); + List facedowns = new List(); + CardListShuffle(spells); + foreach (ClientCard card in spells) + { + if (card.HasPosition(CardPosition.FaceUp) && !(card.IsShouldNotBeTarget() || card.IsShouldNotBeMonsterTarget())) faceups.Add(card); + else if (card.HasPosition(CardPosition.FaceDown)) facedowns.Add(card); + } + targets = targets.Union(faceups).Union(facedowns).ToList(); + if (targets.Count == 0) return false; + SelectDiscardSpell(); + AI.SelectNextCard(targets); + return true; + } + + // check whether summon CrystronHalqifibrax + public List CrystronHalqifibraxSummonCheck(ClientCard included = null) + { + List empty_list = new List(); + List extra_list = new List(); + if (included != null) extra_list.Add(included); + List materials = CheckLinkMaterials(2, 2, true, extra_list); + if (materials.Count < 2) return empty_list; + + // need CrystronHalqifibrax? + if (CheckRemainInDeck(CardId.PSYGamma, _CardId.AshBlossom) == 0) return empty_list; + + + return empty_list; + } + + // summon process of CrystronHalqifibrax + public bool CrystronHalqifibraxSummon() + { + List materials = CrystronHalqifibraxSummonCheck(); + if (materials.Count < 2) return false; + AI.SelectMaterials(materials); + return true; + } + + // activate of CrystronHalqifibrax + public bool CrystronHalqifibraxActivate() + { + if (Duel.Player == 0) + { + return true; + } + else if (Util.IsChainTarget(Card) || Util.GetProblematicEnemySpell() != null) return true; + else if (Duel.Player == 1 && Duel.Phase == DuelPhase.BattleStart && Util.IsOneEnemyBetterThanValue(1500, true)) + { + if (Util.IsOneEnemyBetterThanValue(1900, true)) + { + AI.SelectPosition(CardPosition.FaceUpDefence); + } + else + { + AI.SelectPosition(CardPosition.FaceUpAttack); + } + return true; + } + return false; + } + + // check whether summon SalamangreatAlmiraj + public bool SalamangreatAlmirajSummonCheck(ClientCard included = null) + { + // use witchcraft first + if (CheckDiscardableSpellCount() >= 2) return false; + List materials = Bot.GetMonsters(); + if (included != null) materials.Add(included); + if (materials.GetCardCount(CardId.Pittore) + materials.GetCardCount(CardId.Genni) == 0) return false; + if (Bot.HasInHand(important_witchcraft)) return true; + + return false; + } + + // summmon process of SalamangreatAlmiraj + public bool SalamangreatAlmirajSummon() + { + if (!SalamangreatAlmirajSummonCheck()) return false; + List material = new List { CardId.Pittore, CardId.Genni }; + AI.SelectMaterials(material); + return true; + } + + // activate of SalamangreatAlmiraj + public bool SalamangreatAlmirajActivate() + { + if (Card.Location == CardLocation.Grave) return true; + if (Duel.Player == 1) + { + AI.SelectCard(Util.GetBestBotMonster()); + return true; + } + return false; + } + + // summmon process of PSYLambda + public bool PSYLambdaSummon() + { + if (Bot.HasInMonstersZone(CardId.PSYGamma) && Bot.HasInMonstersZone(CardId.PSYDriver)) + { + if (Bot.HasInHand(CardId.PSYGamma) || Bot.HasInMonstersZone(CardId.PSYOmega)) { + List targets = new List{CardId.PSYDriver, CardId.PSYGamma}; + AI.SelectMaterials(targets); + return true; + } + } + return false; + } + + /// + /// return place to summon RelinquishedAnima. + /// if no need to summon, return -1 + /// + /// Cards included into account + public int RelinquishedAnimaSummonCheck(ClientCard included = null) + { + // use witchcraft first + if (CheckDiscardableSpellCount() >= 2) return -1; + List materials = Bot.GetMonsters(); + if (included != null) materials.Add(included); + + int place = -1; + int attack = Util.GetBestAttack(Bot); + // select place + + List checklist = new List { Enemy.MonsterZone[6], Enemy.MonsterZone[5] }; + List placelist = new List { 1, 3 }; + for (int i = 0; i < 2; ++i) + { + ClientCard card = checklist[i]; + int _place = placelist[i]; + if (card != null && card.HasLinkMarker((int)CardLinkMarker.Top) && card.Attack > attack && + !card.IsShouldNotBeMonsterTarget() && !card.IsShouldNotBeTarget()) + { + ClientCard self_card = Bot.MonsterZone[_place]; + if (self_card == null || self_card.Level == 1) + { + place = _place; + attack = card.Attack; + } + } + } + checklist = new List { Enemy.MonsterZone[3], Enemy.MonsterZone[1] }; + placelist = new List { 5, 6 }; + for (int i = 0; i < 2; ++i) + { + ClientCard card = checklist[i]; + int _place = placelist[i]; + if (card != null && card.Attack > attack && + !card.IsShouldNotBeMonsterTarget() && !card.IsShouldNotBeTarget()) + { + ClientCard enemy_card = Enemy.MonsterZone[11 - _place]; + if (enemy_card != null) continue; + ClientCard self_card = Bot.MonsterZone[_place]; + if (self_card == null || self_card.Level == 1) + { + place = _place; + attack = card.Attack; + } + } + } + + return place; + } + + // summmon process of RelinquishedAnima + public bool RelinquishedAnimaSummon() + { + int place = RelinquishedAnimaSummonCheck(); + Logger.DebugWriteLine("RelinquishedAnima summon check: " + place.ToString()); + if (place != -1) + { + int zone = (int)System.Math.Pow(2, place); + AI.SelectPlace(zone); + if (Bot.MonsterZone[place] != null && Bot.MonsterZone[place].Level == 1) + { + AI.SelectMaterials(Bot.MonsterZone[place]); + } else + { + AI.SelectMaterials(CardId.Genni); + } + return true; + } + return false; + } + + // default Chicken game + public bool ChickenGame() + { + if (SpellNegatable()) return false; + if (Bot.LifePoints <= 1000) + return false; + if (Bot.LifePoints - 1000 <= Enemy.LifePoints && ActivateDescription == Util.GetStringId(_CardId.ChickenGame, 0)) + { + return true; + } + if (Bot.LifePoints - 1000 > Enemy.LifePoints && ActivateDescription == Util.GetStringId(_CardId.ChickenGame, 1)) + { + return true; + } + return false; + } + + protected override bool DefaultSetForDiabellze() + { + if (base.DefaultSetForDiabellze()) + { + SelectSTPlace(null, true); + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/YosenjuExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/YosenjuExecutor.cs new file mode 100644 index 0000000..b58247e --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/YosenjuExecutor.cs @@ -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 OnSelectXyzMaterial(IList cards, int min, int max) + { + IList 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; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/YubelExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/YubelExecutor.cs new file mode 100644 index 0000000..90517f7 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/YubelExecutor.cs @@ -0,0 +1,2360 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Claims; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; +using YGOSharp.Network.Enums; +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; + +namespace WindBot.Game.AI.Decks +{ + [Deck("Yubel", "AI_Yubel")] + public class YubelExecutor : DefaultExecutor + { + public class CardId + { + // === Core Yubel === + public const int YUBEL = 78371393; + public const int YUBEL_TERROR_INCARNATE = 4779091; + public const int SPIRIT_OF_YUBEL = 90829280; + public const int PHANTOM_OF_YUBEL = 80453041; // (extra) + + // === Starters / Engine === + public const int SAMSARA_D_LOTUS = 62318994; + public const int GRUESOME_GRAVE_SQUIRMER = 24215921; + public const int FABLED_LURRIE = 97651498; + + // === Fiendsmith / Fiend package === + public const int SHARVARA = 41165831; + public const int FIENDSMITH_ENGRAVER = 60764609; + public const int LACRIMA_CT = 28803166; + public const int DARK_BECKONING_BEAST = 81034083; + public const int CHAOS_SUMMONING_BEAST = 27439792; + + // === Spells / Traps === + public const int NIGHTMARE_PAIN = 65261141; + public const int NIGHTMARE_THRONE = 93729896; + public const int SPIRIT_GATES = 80312545; + public const int FIENDSMITH_TRACT = 98567237; + public const int ABOMINABLE_CHAMBER = 80801743; + public const int FIENDSMITHS_PARADISE = 99989863; + public const int TERRAFORMING = 73628505; + + // === Extra Deck / อื่น ๆ === + public const int FIENDSMITHS_DESIRAE = 82135803; + //public const int FIENDSMITHS_LACRIMA = 46640168; + public const int VARUDASN_FINAL_BRINGER = 70636044; + public const int DDD_WAVE_HIGH_KING_CAESAR = 79559912; + public const int UNCHAINED_LORD_OF_YAMA = 24269961; + public const int UNCHAINED_SOUL_OF_RAGE = 67680512; + public const int SP_LITTLE_KNIGHT = 29301450; + public const int MOON_OF_THE_CLOSED_HEAVEN = 71818935; + //public const int FIENDSMITHS_SEQUENCE = 49867899; + //public const int MUCKRAKER_UNDERWORLD = 71607202; + public const int FIENDSMITHS_REQUIEM = 2463794; + public const int SALAMANGREAT_ALMIRAJ = 60303245; + public const int NECROQUIP = 93860227; + //public const int ARIALEATER = 28143384; + public const int GORGONOFZIL = 12067160; + public const int GUSTAVMAX = 56910167; + public const int JUGGERNAUT = 26096328; + public const int UNCHAINDEDABOMINATION = 29479265; + + // === Handtraps / Others (blacklist/targets etc.) === + public const int Fuwalos = 42141493; + public const int NaturalExterio = 99916754; + public const int NaturalBeast = 33198837; + public const int ImperialOrder = 61740673; + public const int SwordsmanLV7 = 37267041; + public const int RoyalDecree = 51452091; + public const int Number41BagooskatheTerriblyTiredTapir = 90590303; + public const int InspectorBoarder = 15397015; + public const int SkillDrain = 82732705; + public const int DivineArsenalAAZEUS_SkyThunder = 90448279; + public const int DimensionShifter = 91800273; + public const int MacroCosmos = 30241314; + public const int DimensionalFissure = 81674782; + public const int BanisheroftheRadiance = 94853057; + public const int BanisheroftheLight = 61528025; + public const int KashtiraAriseHeart = 48626373; + public const int AccesscodeTalker = 86066372; + public const int GhostMournerMoonlitChill = 52038441; + public const int NibiruThePrimalBeing = 27204311; + } + + const int SetcodeTimeLord = 0x4a; + const int SetcodePhantom = 0xdb; + const int SetcodeOrcust = 0x11b; + const int SetcodeHorus = 0x19d; + + Dictionary> DeckCountTable = new Dictionary>{ + {3, new List { CardId.SPIRIT_OF_YUBEL, CardId.SAMSARA_D_LOTUS,CardId.NIGHTMARE_THRONE, CardId.SPIRIT_GATES, + _CardId.AshBlossom, CardId.DARK_BECKONING_BEAST,_CardId.InfiniteImpermanence } }, + {2, new List { _CardId.MaxxC, _CardId.CalledByTheGrave,CardId.GRUESOME_GRAVE_SQUIRMER}}, + {1, new List { CardId.FIENDSMITH_ENGRAVER, CardId.FIENDSMITHS_PARADISE, + CardId.YUBEL, CardId.YUBEL_TERROR_INCARNATE, CardId.ABOMINABLE_CHAMBER, + _CardId.CrossoutDesignator, CardId.GRUESOME_GRAVE_SQUIRMER, CardId.FABLED_LURRIE, + CardId.NIGHTMARE_PAIN, CardId.TERRAFORMING, CardId.FIENDSMITH_TRACT,CardId.SHARVARA, + CardId.CHAOS_SUMMONING_BEAST, CardId.LACRIMA_CT + } } + }; + + List notToNegateIdList = new List { 58699500, 20343502, 19403423 }; + List notToDestroySpellTrap = new List { 50005218, 6767771 }; + List targetNegateIdList = new List { + _CardId.EffectVeiler, _CardId.InfiniteImpermanence, CardId.GhostMournerMoonlitChill, _CardId.BreakthroughSkill, 74003290, 67037924, + 9753964, 66192538, 23204029, 73445448, 35103106, 30286474, 45002991, 5795980, 38511382, 53742162, 30430448 + }; + + private static readonly int[] LinkFodderPriority = new[] + { + CardId.SHARVARA, + CardId.YUBEL_TERROR_INCARNATE, + CardId.UNCHAINED_SOUL_OF_RAGE, + CardId.UNCHAINED_LORD_OF_YAMA, + CardId.GRUESOME_GRAVE_SQUIRMER, + CardId.FABLED_LURRIE, + CardId.LACRIMA_CT, + CardId.SALAMANGREAT_ALMIRAJ, + CardId.DARK_BECKONING_BEAST, + CardId.CHAOS_SUMMONING_BEAST, + CardId.SAMSARA_D_LOTUS, + CardId.SPIRIT_OF_YUBEL, + CardId.YUBEL, + CardId.FIENDSMITH_ENGRAVER, + }; + + private static readonly HashSet YUBEL_SET = new HashSet { CardId.YUBEL, CardId.YUBEL_TERROR_INCARNATE, CardId.SPIRIT_OF_YUBEL, CardId.PHANTOM_OF_YUBEL }; + + public YubelExecutor(GameAI ai, Duel duel) : base(ai, duel) + { + + AddExecutor(ExecutorType.Activate, CardId.NIGHTMARE_THRONE, ActNightmareThroneSearch); + // ===== Generic counters ===== + AddExecutor(ExecutorType.Activate, _CardId.CalledByTheGrave, CalledbytheGraveActivate); + AddExecutor(ExecutorType.Activate, _CardId.CrossoutDesignator, CrossoutDesignatorActivate); + AddExecutor(ExecutorType.Activate, _CardId.InfiniteImpermanence, InfiniteImpermanenceActivate); + AddExecutor(ExecutorType.Activate, _CardId.AshBlossom, AshBlossomActivate); + AddExecutor(ExecutorType.Activate, _CardId.MaxxC, MaxxCActivate); + + // ===== Yubel-related ===== + AddExecutor(ExecutorType.Activate, CardId.SAMSARA_D_LOTUS, ActSamsaraDLotusGY); + AddExecutor(ExecutorType.Activate, CardId.YUBEL); + AddExecutor(ExecutorType.Activate, CardId.UNCHAINDEDABOMINATION, UnchainedAbominationActivate); + AddExecutor(ExecutorType.Activate, CardId.PHANTOM_OF_YUBEL, DontSelfNG); + + + // ===== Engine pieces ===== + AddExecutor(ExecutorType.Activate, CardId.ABOMINABLE_CHAMBER, ActAbo); + //AddExecutor(ExecutorType.Activate, CardId.SP_LITTLE_KNIGHT, ActLittleKnightSM); + AddExecutor(ExecutorType.Activate, CardId.SP_LITTLE_KNIGHT, ActLittleKnight); + AddExecutor(ExecutorType.Activate, CardId.DDD_WAVE_HIGH_KING_CAESAR, DontSelfNG); + AddExecutor(ExecutorType.Activate, CardId.FIENDSMITHS_DESIRAE, ActDesirae); + AddExecutor(ExecutorType.Activate, CardId.VARUDASN_FINAL_BRINGER, ActVarudras); + AddExecutor(ExecutorType.Activate, CardId.UNCHAINED_SOUL_OF_RAGE, ActRageQuickLink); + AddExecutor(ExecutorType.Activate, CardId.FIENDSMITHS_PARADISE, ActParadise); + + AddExecutor(ExecutorType.Activate, CardId.FIENDSMITH_ENGRAVER, ActEngraverHand); + AddExecutor(ExecutorType.Activate, CardId.FIENDSMITH_TRACT, ActTract); + AddExecutor(ExecutorType.SpSummon, CardId.FABLED_LURRIE); + AddExecutor(ExecutorType.SpSummon, CardId.FIENDSMITHS_REQUIEM, SSRequiem); + AddExecutor(ExecutorType.Activate, CardId.FIENDSMITHS_REQUIEM, ActRequiemMZ); + AddExecutor(ExecutorType.Activate, CardId.LACRIMA_CT, ActLacimaCT); + AddExecutor(ExecutorType.Activate, CardId.FIENDSMITHS_REQUIEM, ActRequiemEQ); + AddExecutor(ExecutorType.SpSummon, CardId.NECROQUIP, SSNecroquip); + AddExecutor(ExecutorType.Activate, CardId.FIENDSMITH_ENGRAVER, ActEngraverGY); + AddExecutor(ExecutorType.SpSummon, CardId.DDD_WAVE_HIGH_KING_CAESAR); + + AddExecutor(ExecutorType.Activate, CardId.LACRIMA_CT, ActLacimaCTGY); + + // Field & search line + AddExecutor(ExecutorType.Activate, S1_ActivateTerraformingForThrone); + AddExecutor(ExecutorType.Activate, CardId.NIGHTMARE_THRONE, S6_ChainThroneFollowUp); + + // Normal Summon engine + AddExecutor(ExecutorType.Summon, CardId.DARK_BECKONING_BEAST, NSDarkBeckoningBeast); + AddExecutor(ExecutorType.Activate, CardId.DARK_BECKONING_BEAST, ActDarkBeckoningBeast); + + // === SPIRIT GATES === + AddExecutor(ExecutorType.Activate, CardId.SPIRIT_GATES, S4_ActivateSpiritGates); // ใช้จากมือเพื่อค้น + AddExecutor(ExecutorType.Activate, CardId.SPIRIT_GATES, Gate_RecycleContinuous); // e3: เก็บ Continuous (มีเลเวล 10) + + + AddExecutor(ExecutorType.Summon, CardId.SAMSARA_D_LOTUS, NSSamsaraDLotus); + AddExecutor(ExecutorType.Activate, CardId.SAMSARA_D_LOTUS, ActSamsaraDLotus); + + // Follow-ups + AddExecutor(ExecutorType.SpSummon, CardId.SPIRIT_OF_YUBEL); + AddExecutor(ExecutorType.Activate, CardId.SPIRIT_OF_YUBEL); + AddExecutor(ExecutorType.Activate, CardId.NIGHTMARE_PAIN, ActNightmarePainHand); + AddExecutor(ExecutorType.Activate, CardId.NIGHTMARE_PAIN, ActNightmarePainEffect); + AddExecutor(ExecutorType.Activate, CardId.GRUESOME_GRAVE_SQUIRMER, SSGGS); + AddExecutor(ExecutorType.Activate, CardId.GRUESOME_GRAVE_SQUIRMER, ActGGSGY); + + AddExecutor(ExecutorType.SpSummon, CardId.MOON_OF_THE_CLOSED_HEAVEN, SSMoon); + AddExecutor(ExecutorType.SpSummon, CardId.UNCHAINED_LORD_OF_YAMA, L2YamaSetup); + AddExecutor(ExecutorType.Activate, CardId.UNCHAINED_LORD_OF_YAMA, ActYamaMZ); + AddExecutor(ExecutorType.Activate, CardId.UNCHAINED_LORD_OF_YAMA, ActYamaGY); + AddExecutor(ExecutorType.SpSummon, CardId.UNCHAINED_SOUL_OF_RAGE, L2RageKeepYama); + AddExecutor(ExecutorType.SpSummon, CardId.UNCHAINDEDABOMINATION, L4ABOSS); + AddExecutor(ExecutorType.Activate, CardId.SHARVARA, ActSharvara); + AddExecutor(ExecutorType.Activate, CardId.SHARVARA, ActSharvaraGY); + //AddExecutor(ExecutorType.SpSummon, CardId.MUCKRAKER_UNDERWORLD, L2NoBrain); + + + + // Panic line + //AddExecutor(ExecutorType.SpSummon, CardId.VARUDASN_FINAL_BRINGER, SSVarudras); + AddExecutor(ExecutorType.SpSummon, CardId.VARUDASN_FINAL_BRINGER); + AddExecutor(ExecutorType.SpSummon, CardId.SALAMANGREAT_ALMIRAJ, AlmirajSummon); + AddExecutor(ExecutorType.Activate, CardId.SPIRIT_GATES, Gate_Revive00Fiend); // e2: ทิ้งมือ ชุบ Fiend 0/0 + AddExecutor(ExecutorType.SpSummon, CardId.PHANTOM_OF_YUBEL, SSPhantom); + AddExecutor(ExecutorType.SpSummon, CardId.GUSTAVMAX); + AddExecutor(ExecutorType.Activate, CardId.GUSTAVMAX); + AddExecutor(ExecutorType.SpSummon, CardId.JUGGERNAUT); + AddExecutor(ExecutorType.Activate, CardId.JUGGERNAUT); + //AddExecutor(ExecutorType.Activate, CardId.MUCKRAKER_UNDERWORLD, NeverUseMuckrakerRevive); + + // other + AddExecutor(ExecutorType.SpellSet, SpellSetCheck); + AddExecutor(ExecutorType.Repos, MonsterRepos); + } + //======================Default code + #region Default Code Start Here + private int _totalAttack; + private int _totalBotAttack; + bool enemyActivateMaxxC = false; + bool enemyActivateLockBird = false; + int dimensionShifterCount = 0; + bool enemyActivateInfiniteImpermanenceFromHand = false; + List infiniteImpermanenceList = new List(); + List currentNegateCardList = new List(); + List currentDestroyCardList = new List(); + List sendToGYThisTurn = new List(); + List activatedCardIdList = new List(); + List enemyPlaceThisTurn = new List(); + List escapeTargetList = new List(); + List summonThisTurn = new List(); + + private enum ThroneStage { None, Searching, AwaitDestroyPrompt } + private bool _yubelWantsTribute = false; + private ThroneStage _throneStage = ThroneStage.None; + // === Spirit Gates state === + int _gateReviveTargetId = 0; // จะชุบตัวไหน + int _gateDiscardPreferredId = 0; // จะทิ้งใบไหนเป็น cost + bool _gateWantsRecycle = false; // กำลังจะกดโหมดเก็บ Continuous + bool _spQuickMode = false; + bool moonSummoned = false; + bool requiemSummoned = false; + bool thronePending = false; // we're in a Throne activation flow + bool throneSearched = false; // after we chose the monster to search + int throneDesiredPick = 0; // preferred monster id to search + + public List ShuffleList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(result.Count); + int nextIndex = (index + Program.Rand.Next(result.Count - 1)) % result.Count; + T tempCard = result[index]; + result[index] = result[nextIndex]; + result[nextIndex] = tempCard; + } + return result; + } + + public override bool OnSelectHand() { return true; } + + public List ShuffleCardList(List list) + { + List result = list; + int n = result.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(n + 1); + ClientCard temp = result[index]; + result[index] = result[n]; + result[n] = temp; + } + return result; + } + + public int CheckRemainInDeck(int id) + { + for (int count = 1; count < 4; ++count) + { + if (DeckCountTable[count].Contains(id)) + { + return Bot.GetRemainingCount(id, count); + } + } + return 0; + } + + private bool MonsterRepos() + { + bool isYubelFam = + Card.Id == CardId.SPIRIT_OF_YUBEL || + Card.Id == CardId.YUBEL || + Card.Id == CardId.YUBEL_TERROR_INCARNATE || + Card.Id == CardId.PHANTOM_OF_YUBEL; + + if (isYubelFam) + { + if (Card.IsDefense()) + { + AI.SelectPosition(CardPosition.Attack); + return true; + } + return false; + } + if (Card.IsFacedown()) + return true; + if (CheckInDanger() && (_totalAttack > _totalBotAttack)) + return Card.IsDefense(); + return DefaultMonsterRepos(); + } + + public bool CheckAtAdvantage() + { + if (GetProblematicEnemyMonster() == null && Bot.GetMonsters().Any(card => card.IsFaceup())) + { + return true; + } + return false; + } + + public bool CheckInDanger() + { + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + int totalAtk = 0; + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (m.IsAttack() && !m.Attacked) totalAtk += m.Attack; + } + if (totalAtk >= Bot.LifePoints) return true; + } + return false; + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + if (player == 0 && location == CardLocation.MonsterZone && cardId == CardId.UNCHAINED_SOUL_OF_RAGE) + { + int prefer = (GetMyLinkedMMZMask() & available) & 0x1F; + + int choose = (prefer != 0) ? LowestBit(prefer) + : LowestBit(available & 0x1F); // fallback + + AI.SelectPlace(choose); + return choose; + } + SelectSTPlace(Card, true); + return base.OnSelectPlace(cardId, player, location, available); + } + + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + if (positions == null || positions.Count == 0) + return base.OnSelectPosition(cardId, positions); + + bool isYubelFamily = + YUBEL_SET.Contains(cardId) || + (Card != null && YUBEL_SET.Contains(Card.Id)) || + (Card != null && (Card.Name?.Contains("Yubel") ?? false)); + + if(!isYubelFamily) + return base.OnSelectPosition(cardId, positions); + + CardPosition atkPref = + positions.Contains(CardPosition.FaceUpAttack) ? CardPosition.FaceUpAttack : + positions.Contains(CardPosition.Attack) ? CardPosition.Attack : + (CardPosition)0; + + if (isYubelFamily && atkPref != 0) + { + AI.SelectPosition(atkPref); + return atkPref; + } + + var chosen = positions[0]; + AI.SelectPosition(chosen); + return chosen; + } + + public bool AshBlossomActivate() + { + if (BlockIfThrone("AshBlossom")) return false;//added + if (InThroneFlow) return false;//added + if (CheckWhetherNegated(true) || !CheckLastChainShouldNegated()) return false; + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + if (CheckAtAdvantage()) + { + return false; + } + } + return DefaultAshBlossomAndJoyousSpring(); + } + + public bool MaxxCActivate() + { + if (BlockIfThrone("MaxxC")) return false; + if (InThroneFlow) return false;//added + if (CheckWhetherNegated(true) || Duel.LastChainPlayer == 0) return false; + return DefaultMaxxC(); + } + + public bool InfiniteImpermanenceActivate() + { + if (CheckWhetherNegated()) return false; + foreach (ClientCard m in Enemy.GetMonsters()) + { + if (m.IsMonsterShouldBeDisabledBeforeItUseEffect() && !m.IsDisabled() && Duel.LastChainPlayer != 0) + { + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + AI.SelectCard(m); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + if (Card.Location == CardLocation.SpellZone) + { + int this_seq = -1; + int that_seq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) this_seq = i; + if (LastChainCard != null + && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.SpellZone && Enemy.SpellZone[i] == LastChainCard) that_seq = i; + else if (Duel.Player == 0 && Util.GetProblematicEnemySpell() != null + && Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFloodgate()) that_seq = i; + } + if ((this_seq * that_seq >= 0 && this_seq + that_seq == 4) + || (Util.IsChainTarget(Card)) + || (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.IsCode(_CardId.HarpiesFeatherDuster))) + { + ClientCard target = GetProblematicEnemyMonster(canBeTarget: true); + List enemyMonsters = Enemy.GetMonsters(); + AI.SelectCard(target); + infiniteImpermanenceList.Add(this_seq); + return true; + } + } + if ((LastChainCard == null || LastChainCard.Controller != 1 || LastChainCard.Location != CardLocation.MonsterZone + || LastChainCard.IsDisabled() || LastChainCard.IsShouldNotBeTarget() || LastChainCard.IsShouldNotBeSpellTrapTarget())) + return false; + + if (Card.Location == CardLocation.SpellZone) + { + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) + { + infiniteImpermanenceList.Add(i); + break; + } + } + } + if (Card.Location == CardLocation.Hand) + { + SelectSTPlace(Card, true); + } + if (LastChainCard != null) AI.SelectCard(LastChainCard); + else + { + List enemyMonsters = Enemy.GetMonsters(); + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + foreach (ClientCard card in enemyMonsters) + { + if (card.IsFaceup() && !card.IsShouldNotBeTarget() && !card.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(card); + return true; + } + } + } + return true; + } + + public bool CrossoutDesignatorActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (Duel.LastChainPlayer == 1 && Util.GetLastChainCard() != null) + { + int code = Util.GetLastChainCard().Id; + int alias = Util.GetLastChainCard().Alias; + if (alias != 0 && alias - code < 10) code = alias; + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + if (CheckRemainInDeck(code) > 0) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectAnnounceID(code); + currentNegateCardList.AddRange(Enemy.MonsterZone.Where(c => c != null && c.IsFaceup() && c.IsCode(code))); + return true; + } + } + return false; + } + + public bool CalledbytheGraveActivate() + { + if (CheckWhetherNegated() || !CheckLastChainShouldNegated()) return false; + if (CheckAtAdvantage() && Duel.LastChainPlayer == 1 && Util.GetLastChainCard().IsCode(_CardId.MaxxC)) + { + return false; + } + if (Duel.LastChainPlayer == 1) + { + if (Util.GetLastChainCard().IsMonster()) + { + int code = Util.GetLastChainCard().GetOriginCode(); + if (code == 0) return false; + if (DefaultCheckWhetherCardIdIsNegated(code)) return false; + if (Util.GetLastChainCard().IsCode(_CardId.MaxxC) && CheckAtAdvantage()) + { + return false; + } + ClientCard graveTarget = Enemy.Graveyard.GetFirstMatchingCard(card => card.IsMonster() && card.GetOriginCode() == code); + if (graveTarget != null) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(graveTarget); + currentDestroyCardList.Add(graveTarget); + return true; + } + } + + foreach (ClientCard graveCard in Enemy.Graveyard) + { + if (Duel.ChainTargets.Contains(graveCard) && graveCard.IsMonster()) + { + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + int code = graveCard.Id; + AI.SelectCard(graveCard); + currentDestroyCardList.Add(graveCard); + return true; + } + } + + if (Duel.ChainTargets.Contains(Card)) + { + List enemyMonsters = Enemy.Graveyard.GetMatchingCards(card => card.IsMonster()).ToList(); + if (enemyMonsters.Count > 0) + { + enemyMonsters.Sort(CardContainer.CompareCardAttack); + enemyMonsters.Reverse(); + int code = enemyMonsters[0].Id; + AI.SelectCard(code); + currentDestroyCardList.Add(enemyMonsters[0]); + return true; + } + } + } + + if (Duel.LastChainPlayer == 1) return false; + List targets = GetDangerousCardinEnemyGrave(true); + if (targets.Count > 0) + { + int code = targets[0].Id; + if (!(Card.Location == CardLocation.SpellZone)) + { + SelectSTPlace(null, true); + } + AI.SelectCard(code); + currentDestroyCardList.Add(targets[0]); + return true; + } + + return false; + } + + public bool SpellSetCheck() + { + if (Card.Id == CardId.FIENDSMITHS_PARADISE) return false; + + if (Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster() && Duel.Turn > 1) return false; + List onlyOneSetList = new List { CardId.ABOMINABLE_CHAMBER }; + if (onlyOneSetList.Contains(Card.Id) && Bot.HasInSpellZone(Card.Id)) + { + return false; + } + + if ((Card.IsTrap() || Card.HasType(CardType.QuickPlay)))//added + { + List avoid_list = new List(); + int setFornfiniteImpermanence = 0; + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] != null && Enemy.SpellZone[i].IsFaceup() && Bot.SpellZone[4 - i] == null) + { + avoid_list.Add(4 - i); + setFornfiniteImpermanence += (int)System.Math.Pow(2, 4 - i); + } + } + if (Bot.HasInHand(_CardId.InfiniteImpermanence)) + { + if (Card.IsCode(_CardId.InfiniteImpermanence)) + { + AI.SelectPlace(setFornfiniteImpermanence); + return true; + } + else + { + SelectSTPlace(Card, false, avoid_list); + return true; + } + } + else + { + SelectSTPlace(); + } + return true; + } + + return false; + } + + public List GetDangerousCardinEnemyGrave(bool onlyMonster = false) + { + List result = Enemy.Graveyard.GetMatchingCards(card => + (!onlyMonster || card.IsMonster()) && (card.HasSetcode(SetcodeOrcust) || card.HasSetcode(SetcodePhantom) || card.HasSetcode(SetcodeHorus))).ToList(); + List dangerMonsterIdList = new List { 99937011, 63542003, 9411399, 28954097, 30680659 }; + result.AddRange(Enemy.Graveyard.GetMatchingCards(card => dangerMonsterIdList.Contains(card.Id))); + return result; + } + + public bool CheckWhetherNegated(bool disablecheck = true, bool toFieldCheck = false, CardType type = 0) + { + bool isMonster = type == 0 && Card.IsMonster(); + isMonster |= ((int)type & (int)CardType.Monster) != 0; + bool isSpellOrTrap = type == 0 && (Card.IsSpell() || Card.IsTrap()); + isSpellOrTrap |= (((int)type & (int)CardType.Spell) != 0) || (((int)type & (int)CardType.Trap) != 0); + bool isCounter = ((int)type & (int)CardType.Counter) != 0; + if (isSpellOrTrap && toFieldCheck && CheckSpellWillBeNegate(isCounter)) + return true; + if (DefaultCheckWhetherCardIsNegated(Card)) return true; + if (isMonster && (toFieldCheck || Card.Location == CardLocation.MonsterZone)) + { + if ((toFieldCheck && (((int)type & (int)CardType.Link) != 0)) || Card.IsDefense()) + { + if (Enemy.MonsterZone.Any(card => CheckNumber41(card)) || Bot.MonsterZone.Any(card => CheckNumber41(card))) return true; + } + if (Enemy.HasInSpellZone(CardId.SkillDrain, true)) return true; + } + if (disablecheck) return (Card.Location == CardLocation.MonsterZone || Card.Location == CardLocation.SpellZone) && Card.IsDisabled() && Card.IsFaceup(); + return false; + } + + public bool CheckNumber41(ClientCard card) + { + return card != null && card.IsFaceup() && card.IsCode(CardId.Number41BagooskatheTerriblyTiredTapir) && card.IsDefense() && !card.IsDisabled(); + } + + public void SelectSTPlace(ClientCard card = null, bool avoidImpermanence = false, List avoidList = null) + { + if (card == null) card = Card; + List list = new List(); + for (int seq = 0; seq < 5; ++seq) + { + if (Bot.SpellZone[seq] == null) + { + if (card != null && card.Location == CardLocation.Hand && avoidImpermanence && infiniteImpermanenceList.Contains(seq)) continue; + if (avoidList != null && avoidList.Contains(seq)) continue; + list.Add(seq); + } + } + int n = list.Count; + while (n-- > 1) + { + int index = Program.Rand.Next(list.Count); + int nextIndex = (index + Program.Rand.Next(list.Count - 1)) % list.Count; + int tempInt = list[index]; + list[index] = list[nextIndex]; + list[nextIndex] = tempInt; + } + if (avoidImpermanence && Bot.GetMonsters().Any(c => c.IsFaceup() && !c.IsDisabled())) + { + foreach (int seq in list) + { + ClientCard enemySpell = Enemy.SpellZone[4 - seq]; + if (enemySpell != null && enemySpell.IsFacedown()) continue; + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + } + foreach (int seq in list) + { + int zone = (int)System.Math.Pow(2, seq); + AI.SelectPlace(zone); + return; + } + AI.SelectPlace(0); + } + + public bool CheckSpellWillBeNegate(bool isCounter = false, ClientCard target = null) + { + if (target == null) target = Card; + if (target.Location != CardLocation.SpellZone && target.Location != CardLocation.Hand) return false; + + 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() && (Enemy.HasInSpellZone(CardId.RoyalDecree, true) || Bot.HasInSpellZone(CardId.RoyalDecree, true))) return true; + if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap())) + { + int selfSeq = -1; + for (int i = 0; i < 5; ++i) + { + if (Bot.SpellZone[i] == Card) selfSeq = i; + } + if (infiniteImpermanenceList.Contains(selfSeq)) return true; + } + return false; + } + + public bool CheckLastChainShouldNegated() + { + ClientCard lastcard = Util.GetLastChainCard(); + if (lastcard == null || lastcard.Controller != 1) return false; + if (lastcard.IsMonster() && lastcard.HasSetcode(SetcodeTimeLord) && Duel.Phase == DuelPhase.Standby) return false; + if (notToNegateIdList.Contains(lastcard.Id)) return false; + if (DefaultCheckWhetherCardIsNegated(lastcard)) return false; + if (Duel.Turn == 1 && lastcard.IsCode(_CardId.MaxxC)) return false; + + return true; + } + + public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + ClientCard floodagateCard = Enemy.GetMonsters().Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsFloodgate() && c.IsFaceup() + && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (floodagateCard != null) return floodagateCard; + + ClientCard dangerCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (dangerCard != null) return dangerCard; + + ClientCard invincibleCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (invincibleCard != null) return invincibleCard; + + ClientCard equippedCard = Enemy.MonsterZone.Where(c => c?.Data != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && c.EquipCards.Count > 0 && CheckCanBeTargeted(c, canBeTarget, selfType) + && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (equippedCard != null) return equippedCard; + + ClientCard enemyExtraMonster = Enemy.MonsterZone.Where(c => c != null && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(c)) + && (c.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) || (c.HasType(CardType.Link) && c.LinkCount >= 2)) + && CheckCanBeTargeted(c, canBeTarget, selfType) && CheckShouldNotIgnore(c)).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (enemyExtraMonster != null) return enemyExtraMonster; + + if (attack >= 0) + { + if (attack == 0) + attack = Util.GetBestAttack(Bot); + ClientCard betterCard = Enemy.MonsterZone.Where(card => card != null + && card.GetDefensePower() >= attack && card.GetDefensePower() > 0 && card.IsAttack() && CheckCanBeTargeted(card, canBeTarget, selfType) + && (ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).OrderByDescending(card => card.Attack).FirstOrDefault(); + if (betterCard != null) return betterCard; + } + return null; + } + + public bool CheckCanBeTargeted(ClientCard card, bool canBeTarget, CardType selfType) + { + if (card == null) return true; + if (canBeTarget) + { + if (card.IsShouldNotBeTarget()) return false; + if (((int)selfType & (int)CardType.Monster) > 0 && card.IsShouldNotBeMonsterTarget()) return false; + if (((int)selfType & (int)CardType.Spell) > 0 && card.IsShouldNotBeSpellTrapTarget()) return false; + if (((int)selfType & (int)CardType.Trap) > 0 && (card.IsShouldNotBeSpellTrapTarget() && !card.IsDisabled())) return false; + } + return true; + } + + public bool CheckShouldNotIgnore(ClientCard cards, bool ignore = false) + { + return !ignore || (!currentDestroyCardList.Contains(cards) && !currentNegateCardList.Contains(cards)); + } + + public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreSpells = false, CardType selfType = 0) + { + List resultList = new List(); + + List floodagateList = Enemy.MonsterZone.Where(c => c?.Data != null && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (floodagateList.Count > 0) resultList.AddRange(floodagateList); + + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsFloodgate() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).ToList(); + if (problemEnemySpellList.Count > 0) resultList.AddRange(ShuffleList(problemEnemySpellList)); + + List dangerList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterDangerous() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (dangerList.Count > 0 && (Duel.Player == 0 || (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2))) resultList.AddRange(dangerList); + + List invincibleList = Enemy.MonsterZone.Where(c => c?.Data != null && !resultList.Contains(c) && !currentDestroyCardList.Contains(c) + && c.IsMonsterInvincible() && c.IsFaceup() && CheckCanBeTargeted(c, canBeTarget, selfType)).OrderByDescending(card => card.Attack).ToList(); + if (invincibleList.Count > 0) resultList.AddRange(invincibleList); + + List enemyMonsters = Enemy.GetMonsters().Where(c => !currentDestroyCardList.Contains(c)).OrderByDescending(card => card.Attack).ToList(); + if (enemyMonsters.Count > 0) + { + foreach (ClientCard target in enemyMonsters) + { + if ((target.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz) + || (target.HasType(CardType.Link) && target.LinkCount >= 2)) + && !resultList.Contains(target) && CheckCanBeTargeted(target, canBeTarget, selfType)) + { + resultList.Add(target); + } + } + } + + List spells = Enemy.GetSpells().Where(c => c.IsFaceup() && !currentDestroyCardList.Contains(c) + && c.HasType(CardType.Equip | CardType.Pendulum | CardType.Field | CardType.Continuous) && CheckCanBeTargeted(c, canBeTarget, selfType) + && !notToDestroySpellTrap.Contains(c.Id)).ToList(); + if (spells.Count > 0 && !ignoreSpells) resultList.AddRange(ShuffleList(spells)); + + return resultList; + } + + public List GetNormalEnemyTargetList(bool canBeTarget = true, bool ignoreCurrentDestroy = false, CardType selfType = 0) + { + List targetList = GetProblematicEnemyCardList(canBeTarget, selfType: selfType); + List enemyMonster = Enemy.GetMonsters().Where(card => card.IsFaceup() && !targetList.Contains(card) + && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList(); + enemyMonster.Sort(CardContainer.CompareCardAttack); + enemyMonster.Reverse(); + targetList.AddRange(enemyMonster); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && enemyPlaceThisTurn.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetSpells().Where(card => (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card)) && !enemyPlaceThisTurn.Contains(card)).ToList())); + targetList.AddRange(ShuffleList(Enemy.GetMonsters().Where(card => card.IsFacedown() && (!ignoreCurrentDestroy || !currentDestroyCardList.Contains(card))).ToList())); + + return targetList; + } + + public List GetMonsterListForTargetNegate(bool canBeTarget = false, CardType selfType = 0) + { + List resultList = new List(); + if (CheckWhetherNegated()) + { + return resultList; + } + + ClientCard target = Enemy.MonsterZone.FirstOrDefault(card => card?.Data != null + && card.IsMonsterShouldBeDisabledBeforeItUseEffect() && card.IsFaceup() && !card.IsShouldNotBeTarget() + && CheckCanBeTargeted(card, canBeTarget, selfType) + && !currentNegateCardList.Contains(card)); + if (target != null) + { + resultList.Add(target); + } + + foreach (ClientCard chainingCard in Duel.CurrentChain) + { + if (chainingCard.Location == CardLocation.MonsterZone && chainingCard.Controller == 1 && !chainingCard.IsDisabled() + && CheckCanBeTargeted(chainingCard, canBeTarget, selfType) && !currentNegateCardList.Contains(chainingCard)) + { + resultList.Add(chainingCard); + } + } + + return resultList; + } + + 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 monsters = Enemy.GetMonsters(); + if (monsters.Count > 0 && !onlyFaceup) return ShuffleCardList(monsters)[0]; + return null; + } + + public ClientCard GetBestEnemySpell(bool onlyFaceup = false, bool canBeTarget = false) + { + List problemEnemySpellList = Enemy.SpellZone.Where(c => c?.Data != null + && c.IsFloodgate() && c.IsFaceup() && (!canBeTarget || !c.IsShouldNotBeTarget())).ToList(); + if (problemEnemySpellList.Count > 0) + { + return ShuffleCardList(problemEnemySpellList)[0]; + } + + List spells = Enemy.GetSpells().Where(card => !(card.IsFaceup() && card.IsCode(_CardId.EvenlyMatched))).ToList(); + + List faceUpList = spells.Where(ecard => ecard.IsFaceup() && (ecard.HasType(CardType.Continuous) || ecard.HasType(CardType.Field) || ecard.HasType(CardType.Pendulum))).ToList(); + if (faceUpList.Count > 0) + { + return ShuffleCardList(faceUpList)[0]; + } + + if (spells.Count > 0 && !onlyFaceup) + { + return ShuffleCardList(spells)[0]; + } + + return null; + } + + public ClientCard GetBestEnemyCard(bool onlyFaceup = false, bool canBeTarget = false, bool checkGrave = false) + { + ClientCard card = GetBestEnemyMonster(onlyFaceup, canBeTarget); + if (card != null) return card; + + card = GetBestEnemySpell(onlyFaceup, canBeTarget); + if (card != null) return card; + + if (checkGrave && Enemy.Graveyard.Count > 0) + { + List graveMonsterList = Enemy.Graveyard.GetMatchingCards(c => c.IsMonster()).ToList(); + if (graveMonsterList.Count > 0) + { + graveMonsterList.Sort(CardContainer.CompareCardAttack); + graveMonsterList.Reverse(); + return graveMonsterList[0]; + } + return ShuffleCardList(Enemy.Graveyard.ToList())[0]; + } + + return null; + } + #endregion + + public override void OnChainSolved(int chainIndex) + { + ClientCard currentCard = Duel.GetCurrentSolvingChainCard(); + var solving = Duel.GetCurrentSolvingChainCard(); + bool neg = Duel.IsCurrentSolvingChainNegated(); + Logger.DebugWriteLine($"[CHAIN] Solved idx={chainIndex} negated={neg} solving={CardStr(solving)}"); + if (currentCard != null && !Duel.IsCurrentSolvingChainNegated() && currentCard.Controller == 1) + { + if (currentCard.IsCode(_CardId.MaxxC)) enemyActivateMaxxC = true; + if (currentCard.IsCode(CardId.Fuwalos)) enemyActivateMaxxC = true; + if (currentCard.IsCode(_CardId.LockBird)) enemyActivateLockBird = true; + if (currentCard.IsCode(_CardId.InfiniteImpermanence)) + { + for (int i = 0; i < 5; ++i) + { + if (Enemy.SpellZone[i] == currentCard) + { + infiniteImpermanenceList.Add(4 - i); + break; + } + } + } + } + } + public override void OnChainEnd() + { + escapeTargetList.Clear(); + currentNegateCardList.Clear(); + currentDestroyCardList.Clear(); + enemyActivateInfiniteImpermanenceFromHand = false; + for (int idx = enemyPlaceThisTurn.Count - 1; idx >= 0; idx--) + { + ClientCard checkTarget = enemyPlaceThisTurn[idx]; + if (checkTarget == null || (checkTarget.Location != CardLocation.SpellZone && checkTarget.Location != CardLocation.MonsterZone)) + { + enemyPlaceThisTurn.RemoveAt(idx); + } + } + if (thronePending && _throneStage == ThroneStage.None) + { thronePending = false; } + ResetThroneFlow(); + Logger.DebugWriteLine("[CHAIN] OnChainEnd"); + base.OnChainEnd(); + } + private void ResetThroneFlow() + { + Logger.DebugWriteLine($"[THRONE] Reset flow (was stage={_throneStage}, pending={thronePending})"); + thronePending = false; + throneSearched = false; + throneDesiredPick = 0; + _throneStage = ThroneStage.None; + } + public override void OnNewTurn() + { + if (Duel.Turn <= 1) { dimensionShifterCount = 0; } + + enemyActivateMaxxC = false; + enemyActivateLockBird = false; + enemyActivateInfiniteImpermanenceFromHand = false; + if (dimensionShifterCount > 0) dimensionShifterCount--; + infiniteImpermanenceList.Clear(); + currentNegateCardList.Clear(); + currentDestroyCardList.Clear(); + sendToGYThisTurn.Clear(); + activatedCardIdList.Clear(); + enemyPlaceThisTurn.Clear(); + summonThisTurn.Clear(); + + // reset Throne flow + thronePending = false; + throneSearched = false; + throneDesiredPick = 0; + _gateReviveTargetId = 0; + _gateDiscardPreferredId = 0; + _gateWantsRecycle = false; + _spQuickMode = false; + + base.OnNewTurn(); + } + + // ===== Material safety logic (inspired by windbot patterns) ===== + private static readonly HashSet NEVER_SAC = new HashSet + { + CardId.PHANTOM_OF_YUBEL, + CardId.DDD_WAVE_HIGH_KING_CAESAR, + CardId.VARUDASN_FINAL_BRINGER, + CardId.SP_LITTLE_KNIGHT, + CardId.GORGONOFZIL, + CardId.UNCHAINDEDABOMINATION + }; + private bool InThroneFlow => thronePending || _throneStage != ThroneStage.None; + private int PriorityIndex(int id) + { + int idx = Array.IndexOf(LinkFodderPriority, id); + return idx >= 0 ? idx : 999; + } + private bool IsProtectedMaterial(ClientCard c, bool allowUseYubelForLink = false) + { + if (c == null) return true; + + if (NEVER_SAC.Contains(c.Id)) return true; + + if (c.EquipCards != null && c.EquipCards.Count > 0) return true; + if (c.HasType(CardType.Link) && c.LinkCount >= 2) return true; + if (c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz)) return true; + + return false; + } + private ClientCard[] GetSafeMaterials(int need) + { + bool allowYubel = ShouldUseYubelForLink(); + + var list = Bot.GetMonsters() + .Where(m => !IsProtectedMaterial(m, allowYubel)) + .OrderBy(m => PriorityIndex(m.Id)) + .ThenBy(m => m.Attack) + .Take(need) + .ToArray(); + + return list; + } + private bool ShouldUseYubelForLink() + { + if (Duel.Player != 0) return false; // ทำเฉพาะเทิร์นเรา + var mons = Bot.GetMonsters().Where(m => m != null).ToList(); + if (mons.Count == 0) return false; + + bool twoOrLess = mons.Count <= 2; + + // มีลิงก์ที่อัปเกรดบอร์ดได้ + bool canMakeBetter; + + if (HasInExtra(CardId.FIENDSMITHS_REQUIEM)) + { + canMakeBetter = + HasInExtra(CardId.MOON_OF_THE_CLOSED_HEAVEN) || + HasInExtra(CardId.UNCHAINED_SOUL_OF_RAGE) || + HasInExtra(CardId.UNCHAINED_LORD_OF_YAMA) || + + //HasInExtra(CardId.MUCKRAKER_UNDERWORLD) || + //HasInExtra(CardId.FIENDSMITHS_SEQUENCE) || + HasInExtra(CardId.SP_LITTLE_KNIGHT); + //HasInExtra(CardId.GORGONOFZIL) ; + } + else + { + canMakeBetter = + HasInExtra(CardId.UNCHAINED_SOUL_OF_RAGE) || + HasInExtra(CardId.UNCHAINED_LORD_OF_YAMA) || + //HasInExtra(CardId.MUCKRAKER_UNDERWORLD) || + //HasInExtra(CardId.FIENDSMITHS_SEQUENCE) || + HasInExtra(CardId.SP_LITTLE_KNIGHT); + //HasInExtra(CardId.GORGONOFZIL); + } + + // ถ้าบนสนามเหลือแต่ชิ้น Yubel 1-2 ใบ และสามารถอัปเกรดเป็นลิงก์ที่ให้ interrupt/มูฟได้ ⇒ ใช้ไปลิงก์เถอะ + return twoOrLess && canMakeBetter; + } + private static readonly int[] YubelCostPriority = new[] + { + CardId.SAMSARA_D_LOTUS, + CardId.FABLED_LURRIE, + CardId.DARK_BECKONING_BEAST, + CardId.CHAOS_SUMMONING_BEAST, + CardId.GRUESOME_GRAVE_SQUIRMER, + CardId.SALAMANGREAT_ALMIRAJ, + //CardId.FIENDSMITHS_SEQUENCE + }; + private bool HasInExtra(int id) + { + return Bot.ExtraDeck.Any(c => c != null && c.Id == id); + } + // --- State for Nightmare Throne prompt flow --- + + + #region Work Space #1 + private bool DontSelfNG() { return Duel.LastChainPlayer != 0; } + private int LowestBit(int mask) => mask & -mask; + + // เอา mask ของช่องมอนสเตอร์ที่ลิงก์เราชี้ (เฉพาะ Main Monster Zone 0..4) + private int GetMyLinkedMMZMask() + { + int mask = 0; + foreach (var m in Bot.GetMonsters()) + { + if (m == null || !m.IsFaceup() || !m.HasType(CardType.Link)) continue; + mask |= m.GetLinkedZones(); + } + // เอาเฉพาะ 5 โซนหลัก (บิต 0..4) + mask &= 0x1F; + return mask; + } + private bool S1_ActivateTerraformingForThrone() + { + if (Type != ExecutorType.Activate) return false; + if (Card.Id != CardId.TERRAFORMING) return false; + if (Bot.HasInHandOrInSpellZone(CardId.NIGHTMARE_THRONE)) { return false; } + AI.SelectCard(CardId.NIGHTMARE_THRONE); + return true; + } + + private bool ActNightmareThroneSearch() + { + if (Type != ExecutorType.Activate) return false; + if (Card.Location == CardLocation.Hand && Bot.HasInSpellZone(CardId.NIGHTMARE_THRONE)) return false; + + int pick = 0; + if (!Bot.HasInHand(CardId.SAMSARA_D_LOTUS) && CheckRemainInDeck(CardId.SAMSARA_D_LOTUS) > 0) + pick = CardId.SAMSARA_D_LOTUS; + else if (Bot.HasInHand(CardId.SAMSARA_D_LOTUS) && !Bot.HasInHand(CardId.DARK_BECKONING_BEAST) && CheckRemainInDeck(CardId.DARK_BECKONING_BEAST) > 0) + pick = CardId.DARK_BECKONING_BEAST; + else if (Bot.HasInHand(CardId.SAMSARA_D_LOTUS) && Bot.HasInHand(CardId.DARK_BECKONING_BEAST) && !Bot.HasInHand(CardId.CHAOS_SUMMONING_BEAST) && CheckRemainInDeck(CardId.CHAOS_SUMMONING_BEAST) > 0) + pick = CardId.CHAOS_SUMMONING_BEAST; + + thronePending = true; + throneSearched = false; + throneDesiredPick = pick; + + Logger.DebugWriteLine($"[THRONE] Activate search; desiredPick={(pick == 0 ? "(auto)" : pick.ToString())}"); + DumpChain("ThroneActivate"); + + return true; + } + + private bool NSDarkBeckoningBeast() + { + if (Duel.Phase != DuelPhase.Main1) return false; + if (Bot.HasInMonstersZone(CardId.DARK_BECKONING_BEAST)) + { + if (Bot.HasInHand(CardId.SAMSARA_D_LOTUS)) + { + return false; + } + } + return true; + } + + private bool ActDarkBeckoningBeast() + { + if (Duel.Phase != DuelPhase.Main1) return false; + if ((CheckRemainInDeck(CardId.SPIRIT_GATES) > 0) && !Bot.HasInSpellZone(CardId.SPIRIT_GATES)) + { AI.SelectCard(CardId.SPIRIT_GATES); return true; } + else if (CheckRemainInDeck(CardId.CHAOS_SUMMONING_BEAST) > 0) + { AI.SelectCard(CardId.CHAOS_SUMMONING_BEAST); return true; } + else { return false; } + } + + private bool S4_ActivateSpiritGates() + { + // ใช้จาก "มือ" เพื่อค้น DBB/CSB + if (Type != ExecutorType.Activate) return false; + if (Card.Location != CardLocation.Hand) return false; + if (Bot.HasInSpellZone(CardId.SPIRIT_GATES, true, true)) return false; + + // กฎ: ถ้ามี DBB อยู่ "บนสนาม" ให้ค้น CSB + int pick = 0; + bool dbbOnField = Bot.HasInMonstersZone(CardId.DARK_BECKONING_BEAST, false, false, true); + + if (dbbOnField && CheckRemainInDeck(CardId.CHAOS_SUMMONING_BEAST) > 0) + pick = CardId.CHAOS_SUMMONING_BEAST; + else if (CheckRemainInDeck(CardId.DARK_BECKONING_BEAST) > 0) + pick = CardId.DARK_BECKONING_BEAST; + else if (CheckRemainInDeck(CardId.CHAOS_SUMMONING_BEAST) > 0) + pick = CardId.CHAOS_SUMMONING_BEAST; + + if (pick == 0) return false; + + AI.SelectCard(pick); + return true; + } + private bool Gate_RecycleContinuous() + { + // e3: มีเลเวล 10 -> เก็บ Continuous Spell จากสุสาน (เน้นเก็บ NIGHTMARE_PAIN) + if (Card.Location != CardLocation.SpellZone) return false; + if (!HaveFaceupLevel10()) return false; + + if (!Bot.HasInGraveyard(CardId.NIGHTMARE_PAIN)) + return false; + + _gateWantsRecycle = true; + // เลือก Pain ก่อน ถ้าไม่มีค่อยเลือก Paradise ตอน select card + return true; + } + private bool Is00FiendId(int id) + { + // รายชื่อ 0/0 Fiend ที่เราใช้ในเด็คนี้ + return id == CardId.YUBEL + || id == CardId.SPIRIT_OF_YUBEL + || id == CardId.DARK_BECKONING_BEAST + || id == CardId.CHAOS_SUMMONING_BEAST + || id == CardId.SAMSARA_D_LOTUS; + } + + // เลือกเป้าหมายที่จะชุบ ด้วยลำดับความสำคัญตาม 2.2.x + private int PlanSpiritGatesReviveTarget() + { + // Emergency Case + if (Bot.HasInMonstersZone(CardId.SALAMANGREAT_ALMIRAJ)&&Bot.HasInGraveyard(CardId.DARK_BECKONING_BEAST)) + { return CardId.DARK_BECKONING_BEAST; } + + // 2.2.2: ถ้าขาด spirit → SS spirit (จากสุสาน หรือทิ้งจากมือ) + bool spiritOnBoard = Bot.HasInMonstersZone(CardId.SPIRIT_OF_YUBEL, true); + bool spiritInGY = Bot.HasInGraveyard(CardId.SPIRIT_OF_YUBEL); + bool spiritInHand = Bot.HasInHand(CardId.SPIRIT_OF_YUBEL); + if (!spiritOnBoard && (spiritInGY || spiritInHand)) + return CardId.SPIRIT_OF_YUBEL; + + // 2.2.3: ถ้า DBB โดนขัด/ตันเกมแล้วมี Almiraj → ชุบ DBB เพื่อไต่ไป Moon + if (Bot.HasInMonstersZone(CardId.SALAMANGREAT_ALMIRAJ, true) + && Bot.HasInGraveyard(CardId.DARK_BECKONING_BEAST) + && HasInExtra(CardId.MOON_OF_THE_CLOSED_HEAVEN)) + return CardId.DARK_BECKONING_BEAST; + + // 2.2.1: ถ้าขาด lotus → SS lotus + if (!Bot.HasInMonstersZone(CardId.SAMSARA_D_LOTUS, true) && Bot.HasInGraveyard(CardId.SAMSARA_D_LOTUS)) + return CardId.SAMSARA_D_LOTUS; + + // ทางเลือกทั่วไป: DBB > CSB > Yubel + if (Bot.HasInGraveyard(CardId.DARK_BECKONING_BEAST)) return CardId.DARK_BECKONING_BEAST; + if (Bot.HasInGraveyard(CardId.CHAOS_SUMMONING_BEAST)) return CardId.CHAOS_SUMMONING_BEAST; + if (Bot.HasInGraveyard(CardId.YUBEL)) return CardId.YUBEL; + + // ถ้าไม่มีอะไรชุบได้เลย อาจวางแผน discard ให้ Spirit ลงสุสานแล้วค่อยชุบ + if (!spiritOnBoard && spiritInHand) return CardId.SPIRIT_OF_YUBEL; + + return 0; + } + + // เลือกใบจะทิ้ง: CSB > Paradise > Terror > (บางกรณี) Spirit + private int PickSpiritGatesDiscard(int reviveTargetId) + { + // เคสอยากชุบ Spirit แต่ยังอยู่ในมือ → ทิ้ง Spirit เป็น cost แล้วชุบมันเอง + if (reviveTargetId == CardId.SPIRIT_OF_YUBEL && Bot.HasInHand(CardId.SPIRIT_OF_YUBEL)) + return CardId.SPIRIT_OF_YUBEL; + + if (Bot.HasInHand(CardId.FIENDSMITHS_PARADISE)) return CardId.FIENDSMITHS_PARADISE; + if (Bot.HasInHand(CardId.CHAOS_SUMMONING_BEAST)) return CardId.CHAOS_SUMMONING_BEAST; + if (Bot.HasInHand(CardId.YUBEL_TERROR_INCARNATE)) return CardId.YUBEL_TERROR_INCARNATE; + + // fallback: เลือกใบที่ "ทิ้งแล้วเจ็บน้อยสุด" + var hand = Bot.Hand.ToList(); + hand.Sort((a, b) => ScoreOwnCardForCost(a).CompareTo(ScoreOwnCardForCost(b))); + return hand.Count > 0 ? hand[0].Id : 0; + } + + private bool Gate_Revive00Fiend() + { + // e2: ทิ้งมือ 1 → SS Fiend 0/0 จากสุสาน + if (Card.Location != CardLocation.SpellZone) return false; + + if (requiemSummoned) + { + if (!Bot.HasInHandOrInGraveyard(CardId.SPIRIT_OF_YUBEL)) return false; // ต้องมีในหลุม + if (Bot.Hand.Count <= 0) return false; // ต้องมีใบทิ้ง + _gateReviveTargetId = CardId.SPIRIT_OF_YUBEL; + _gateDiscardPreferredId = PickSpiritGatesDiscard(_gateReviveTargetId); + _gateWantsRecycle = false; + return true; + } + + // วางแผนก่อนว่าจะชุบตัวไหน + int target = PlanSpiritGatesReviveTarget(); + if (target == 0) return false; + + // ต้องมีการ์ดให้ทิ้งอย่างน้อย 1 ใบ + if (Bot.Hand.Count <= 0) return false; + + int discard = PickSpiritGatesDiscard(target); + if (discard == 0) return false; + + _gateReviveTargetId = target; + _gateDiscardPreferredId = discard; + _gateWantsRecycle = false; + + // ไม่เลือกอะไรตรงนี้ ปล่อยให้ OnSelectCard จิ้ม cost/เป้าหมายให้ + return true; + } + + private bool HaveFaceupLevel10() + { + return Bot.MonsterZone.Any(m => m != null && m.IsFaceup() && m.Level == 10); + } + private bool ActNightmarePainHand() + { + if (Bot.HasInSpellZone(CardId.NIGHTMARE_PAIN, true, true)) return false; + if (Card.Location == CardLocation.Hand) return true; + return false; + } + + private bool ActNightmarePainEffect() + { + if (Card.Location == CardLocation.SpellZone) + { + if(CheckRemainInDeck(CardId.GRUESOME_GRAVE_SQUIRMER)==0)return false; + + if (Bot.HasInMonstersZone(CardId.SPIRIT_OF_YUBEL) || Bot.HasInHand(CardId.SPIRIT_OF_YUBEL)) + { + AI.SelectCard(CardId.SPIRIT_OF_YUBEL); + AI.SelectNextCard(CardId.GRUESOME_GRAVE_SQUIRMER); + return true; + } + } + return false; + } + + private bool S6_ChainThroneFollowUp() + { + if (Type != ExecutorType.Activate) return false; + if (sendToGYThisTurn.Any(c => c != null && YUBEL_SET.Contains(c.Id)) && Bot.HasInHand(CardId.NIGHTMARE_THRONE)) + { + AI.SelectYesNo(true); + return true; + } + return false; + } + + private bool NSSamsaraDLotus() + { + if (Bot.HasInMonstersZone(CardId.SPIRIT_OF_YUBEL)) return false; + return true; + } + + private bool ActSamsaraDLotus() + { + if (Duel.Player == 0) + { + if (Card.Location == CardLocation.MonsterZone) + { + AI.SelectCard(CardId.SPIRIT_OF_YUBEL); + return true; + } + } + if (Duel.Player == 1) + { + if (Bot.HasInMonstersZone(CardId.YUBEL) || Bot.HasInMonstersZone(CardId.SPIRIT_OF_YUBEL)) + { + return true; + } + } + return false; + } + private bool ActSamsaraDLotusGY() + { + if (Card.Location == CardLocation.Grave) + { + if (Bot.HasInMonstersZone(CardId.YUBEL)) + { + AI.SelectOption(1); + return true; + } + } + return false; + } + + private bool ActTract() + { + if (Card.Location != CardLocation.Hand) return false; + + // ถ้าเข้า Fiendsmith line แล้ว -> ไม่ใช้ Tract + if (requiemSummoned) return false; + AI.SelectCard(CardId.FABLED_LURRIE); + AI.SelectNextCard(CardId.FABLED_LURRIE); + return true; + /*if (Card.Location == CardLocation.Hand) + { + if (CheckRemainInDeck(CardId.FIENDSMITH_ENGRAVER) == 0 && + CheckRemainInDeck(CardId.LACRIMA_CT) == 0) + { + return false; + } + if(CheckRemainInDeck(CardId.FABLED_LURRIE) == 0){ return false; } + AI.SelectCard(CardId.FABLED_LURRIE); + AI.SelectNextCard(CardId.FABLED_LURRIE); + return true; + } + if (Card.LastLocation == CardLocation.Grave) { return false; } + return false;*/ + } + + private bool ActParadise() + { + if (Card.Location != CardLocation.Grave) return false; + if (Bot.HasInMonstersZoneOrInGraveyard(CardId.FIENDSMITHS_DESIRAE) || Bot.HasInBanished(CardId.FIENDSMITHS_DESIRAE)) return false; + AI.SelectCard(CardId.FIENDSMITHS_DESIRAE); + return DontSelfNG(); + } + + private bool ActDesirae() + { + if (Card.Location != CardLocation.Grave) {return false; } + ClientCard target = GetBestEnemyCard(onlyFaceup: true, canBeTarget: true, checkGrave: false); + if (target == null) return false; + if (Bot.HasInGraveyard(CardId.FIENDSMITHS_REQUIEM)) + { + AI.SelectCard(CardId.FIENDSMITHS_REQUIEM); + AI.SelectNextCard(target); + return true; + } + AI.SelectCard(target); + return true; + } + + private bool ActRequiemMZ() + { + if (Card.Location != CardLocation.MonsterZone) { return false; } + if (Bot.HasInHand(CardId.LACRIMA_CT) || CheckRemainInDeck(CardId.LACRIMA_CT) > 0) + { + AI.SelectCard(CardId.LACRIMA_CT); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + else if (Bot.HasInHand(CardId.FIENDSMITH_ENGRAVER) || CheckRemainInDeck(CardId.FIENDSMITH_ENGRAVER) > 0) + { + AI.SelectCard(CardId.FIENDSMITH_ENGRAVER); + AI.SelectPosition(CardPosition.FaceUpDefence); + return true; + } + return false; + } + + private bool ActRequiemEQ() + { + if (!HasInExtra(CardId.NECROQUIP)) { return false; } + if (Card.Location != CardLocation.Grave) { return false; } + if (Bot.HasInMonstersZone(CardId.LACRIMA_CT)) + { + AI.SelectCard(CardId.LACRIMA_CT); + return true; + } + else if (Bot.HasInMonstersZone(CardId.FIENDSMITH_ENGRAVER)) + { + AI.SelectCard(CardId.FIENDSMITH_ENGRAVER); + return true; + } + return false; + } + + private bool SSNecroquip() + { + if (Bot.HasInSpellZone(CardId.FIENDSMITHS_REQUIEM) && Bot.HasInMonstersZone(CardId.LACRIMA_CT)) + { + AI.SelectCard(CardId.FIENDSMITHS_REQUIEM); + AI.SelectNextCard(CardId.LACRIMA_CT); + return true; + } + else if (Bot.HasInSpellZone(CardId.FIENDSMITHS_REQUIEM) && Bot.HasInMonstersZone(CardId.FIENDSMITH_ENGRAVER)) + { + AI.SelectCard(CardId.FIENDSMITHS_REQUIEM); + AI.SelectNextCard(CardId.FIENDSMITH_ENGRAVER); + return true; + } + return false; + } + + private bool ActLacimaCT() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.FIENDSMITH_ENGRAVER) && !Bot.HasInBanished(CardId.FIENDSMITH_ENGRAVER)) + { AI.SelectCard(CardId.FIENDSMITH_ENGRAVER); return true; } + else if (!Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.FIENDSMITHS_PARADISE) && !Bot.HasInBanished(CardId.FIENDSMITHS_PARADISE)) + { AI.SelectCard(CardId.FIENDSMITHS_PARADISE); return true; } + return false; + } + return false; + } + + private bool ActLacimaCTGY() + { + if (Card.Location == CardLocation.Grave) + { + if (Bot.HasInBanished(CardId.FIENDSMITHS_PARADISE) || Bot.HasInHandOrInGraveyard(CardId.FIENDSMITHS_PARADISE)) + { return false; } + else { return DontSelfNG(); } + } + return false; + } + + /*private bool SSVarudras() + { + if (Bot.HasInMonstersZone(CardId.YUBEL) && Bot.HasInMonstersZone(CardId.SPIRIT_OF_YUBEL)) + { + AI.SelectCard(CardId.YUBEL); + AI.SelectNextCard(CardId.SPIRIT_OF_YUBEL); + return true; + } + return true; + }*/ + + private bool ActEngraverHand() + { + if (Card.Location != CardLocation.Hand) return false; + if (!Bot.HasInHandOrInSpellZoneOrInGraveyard(CardId.FIENDSMITH_TRACT) && !Bot.HasInBanished(CardId.FIENDSMITH_TRACT)) + { + AI.SelectCard(CardId.FIENDSMITH_TRACT); + return true; + } + return false; + } + + private bool ActEngraverGY() + { + if (Card.Location != CardLocation.Grave) return false; + if (Bot.HasInGraveyard(CardId.FABLED_LURRIE)) { AI.SelectCard(CardId.FABLED_LURRIE); return true; } + else if (Bot.HasInGraveyard(CardId.MOON_OF_THE_CLOSED_HEAVEN)) { AI.SelectCard(CardId.MOON_OF_THE_CLOSED_HEAVEN); return true; } + return false; + } + + private bool SSMoon() + { + if (moonSummoned){ return false; } + if (requiemSummoned) { return false; } + if (!HasInExtra(CardId.FIENDSMITHS_REQUIEM)) + return false; + var mats = GetSafeMaterials(2); + if (mats.Length < 2) return false; + AI.SelectMaterials(mats); + moonSummoned = true; + return true; + } + + private bool ActAbo() + { + if (Bot.HasInGraveyard(CardId.UNCHAINED_SOUL_OF_RAGE)) + { + AI.SelectCard(CardId.UNCHAINED_SOUL_OF_RAGE); + return true; + } + return false; + } + + private bool AlmirajSummon() + { + if (Bot.GetMonsterCount() > 1) return false; + ClientCard mat = Bot.GetMonsters().First(); + if (mat.IsCode(new[] { CardId.DARK_BECKONING_BEAST })) + { + AI.SelectMaterials(mat); + return true; + } + return false; + } + + private bool SSGGS() + { + if (!DontSelfNG()) { return false; } + if (BlockIfThrone("GGS")) return false; + if (Duel.Player == 1) { return false; } + if (InThroneFlow) { return false; } + if (Card.Location != CardLocation.Hand) { return false; } + if (Bot.HasInMonstersZone(CardId.SPIRIT_OF_YUBEL)) + { + AI.SelectYesNo(true); + AI.SelectCard(CardId.SPIRIT_OF_YUBEL); + return true; + } + AI.SelectYesNo(false); + return true; + } + + private bool ActGGSGY() + { + if (Card.Location != CardLocation.Grave) { return false; } + if (Bot.HasInGraveyard(CardId.SPIRIT_OF_YUBEL)) + { + AI.SelectCard(CardId.SPIRIT_OF_YUBEL); + return true; + } + else { return false; } + } + private bool ActLittleKnight() + { + if (ActivateDescription == -1 || ActivateDescription == Util.GetStringId(CardId.SP_LITTLE_KNIGHT, 0)) + { + // banish card + List problemCardList = GetProblematicEnemyCardList(true, selfType: CardType.Monster); + problemCardList.AddRange(GetDangerousCardinEnemyGrave(false)); + problemCardList.AddRange(GetNormalEnemyTargetList(true, true, CardType.Monster)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => card.HasType(CardType.Monster)).OrderByDescending(card => card.Attack)); + problemCardList.AddRange(Enemy.Graveyard.Where(card => !card.HasType(CardType.Monster))); + if (problemCardList.Count() > 0) + { + AI.SelectCard(problemCardList); + activatedCardIdList.Add(Card.Id); + return true; + } + } + else if (ActivateDescription == Util.GetStringId(CardId.SP_LITTLE_KNIGHT, 1)) + { + ClientCard selfMonster = null; + foreach (ClientCard target in Bot.GetMonsters()) + { + if (Duel.ChainTargets.Contains(target) && !escapeTargetList.Contains(target)) + { + selfMonster = target; + break; + } + } + if (selfMonster == null) + { + if (Duel.Player == 1) + { + selfMonster = Bot.GetMonsters().Where(card => card.IsAttack()).OrderBy(card => card.Attack).FirstOrDefault(); + if (!Util.IsOneEnemyBetterThanValue(selfMonster.Attack, true)) selfMonster = null; + } + } + if (selfMonster != null) + { + ClientCard nextMonster = null; + List selfTargetList = Bot.GetMonsters().Where(card => card != selfMonster).ToList(); + if (Enemy.GetMonsterCount() == 0 && selfTargetList.Count() > 0) + { + selfTargetList.Sort(CompareUsableAttack); + nextMonster = selfTargetList[0]; + escapeTargetList.Add(nextMonster); + } + if (Enemy.GetMonsterCount() > 0) + { + nextMonster = GetBestEnemyMonster(true, true); + currentDestroyCardList.Add(nextMonster); + } + if (nextMonster != null) + { + AI.SelectCard(selfMonster); + AI.SelectNextCard(nextMonster); + escapeTargetList.Add(selfMonster); + activatedCardIdList.Add(Card.Id + 1); + return true; + } + } + } + + return false; + } + public int CompareUsableAttack(ClientCard cardA, ClientCard cardB) + { + if (cardA == null && cardB == null) + return 0; + if (cardA == null) + return -1; + if (cardB == null) + return 1; + int powerA = (cardA.IsDefense() && summonThisTurn.Contains(cardA)) ? 0 : cardA.Attack; + int powerB = (cardB.IsDefense() && summonThisTurn.Contains(cardB)) ? 0 : cardB.Attack; + if (powerA < powerB) + return -1; + if (powerA == powerB) + return CardContainer.CompareCardLevel(cardA, cardB); + return 1; + } + private bool ActRageQuickLink() + { + if (Card.Location != CardLocation.MonsterZone) return false; + // Quick Link เฉพาะเทิร์นศัตรูช่วง Main เพื่อสร้าง 1 interrupt + if (Duel.Player != 1) return false; + if (Duel.Phase < DuelPhase.Main1 || Duel.Phase > DuelPhase.Main2) return false; + if (!HasValidRageLinkCandidate()) return false; + + var target = GetBestEnemyMonster(onlyFaceup: true, canBeTarget: true); + if (target == null) return false; + + // ส่วนใหญ่เอนจินจะถามเลือกการ์ดฝั่งตรงข้ามที่จะใช้เป็นวัสดุ/หรือไล่ + AI.SelectCard(target); + return DontSelfNG(); + } + private bool SSPhantom() + { + var gyMat2Codes = new List { CardId.YUBEL_TERROR_INCARNATE, CardId.YUBEL, CardId.DARK_BECKONING_BEAST, CardId.CHAOS_SUMMONING_BEAST, CardId.SPIRIT_OF_YUBEL }; + if (!Bot.HasInGraveyard(gyMat2Codes)) + { + return false; + } + // select mat 1 + if (Bot.HasInHandOrInMonstersZoneOrInGraveyard(CardId.YUBEL_TERROR_INCARNATE)) + { + AI.SelectCard(CardId.YUBEL_TERROR_INCARNATE); + } + else if (Bot.HasInMonstersZoneOrInGraveyard(CardId.YUBEL)) + { + AI.SelectCard(CardId.YUBEL); + } + else if (Bot.HasInGraveyard(CardId.SPIRIT_OF_YUBEL)) + { + AI.SelectCard(CardId.SPIRIT_OF_YUBEL); + } + else + { + return false; + } + // วัตถุดิบใบที่ 2 จากสุสานตามที่จัดไว้ + AI.SelectNextCard(gyMat2Codes); + return true; + } + + private bool ActSharvara() + { + if (BlockIfThrone("Sharvara")) return false; + if (Duel.Player == 1) { return false; } + if (InThroneFlow) return false; + if (Card.Location != CardLocation.Hand) return false; + if (Bot.HasInMonstersZone(CardId.SPIRIT_OF_YUBEL)) + { + AI.SelectCard(CardId.SPIRIT_OF_YUBEL); + return true; + } + else if (Bot.HasInMonstersZone(CardId.YUBEL)) + { + AI.SelectCard(CardId.YUBEL); + return true; + } + + return false; + } + private bool ActSharvaraGY() + { + if (Card.Location != CardLocation.Grave) return false; + return true; + } + + /*private bool L2NoBrain() + { + var mats = GetSafeMaterials(2); + if (mats.Length < 2) return false; + + AI.SelectMaterials(mats); + return true; + }*/ + private bool ActVarudras() + { + if (CheckWhetherNegated()) return false; + + // รายการเป้า (ศัตรูก่อน ถ้าไม่มีค่อย fallback) + List targetList = GetNormalEnemyTargetList(true, true); + int desc = ActivateDescription; + int d1 = Util.GetStringId(CardId.VARUDASN_FINAL_BRINGER, 1); // ใช้ทั้ง e1 (Negate) และ e2 (Battle Start destroy) + int d2 = Util.GetStringId(CardId.VARUDASN_FINAL_BRINGER, 2); // e3 (Destroyed -> destroy 1) + + Logger.DebugWriteLine("[Varudras] desc: " + desc + ", timing = " + CurrentTiming); + + + var enemyPick = targetList.FirstOrDefault(c => c != null && c.Controller == 1); + + // e1: Quick effect Negate (ฝั่งคู่ต่อสู้กดเอฟเฟกต์) + if (desc == d1 && Duel.LastChainPlayer == 1 && Duel.CurrentChain.Count > 0) + { + if (!CheckLastChainShouldNegated()) return false; + activatedCardIdList.Add(Card.Id); // แท็กว่าเป็น e1 + return true; // เอนจินจะจัดการ detach เป็น cost ให้เอง + } + + // e2: Battle Start ทำลาย 1 / e3: ถูกทำลายแล้วทำลาย 1 + if (desc == d1 || desc == d2 || desc == -1) + { + if (targetList.Count == 0) return false; + + // พยายามให้เลือกฝั่งศัตรูก่อน + if (enemyPick != null) + targetList.Insert(0, enemyPick); + else + { + // ถ้าไม่มีการ์ดฝั่งศัตรูให้เลือกเลย -> แทรกฝั่งเราที่ "เสียหายน้อยสุด" ไว้หัวลิสต์ + var selfBest = + Bot.GetMonsters().Concat(Bot.GetSpells()) + .Where(c => c != null) + .OrderBy(ScoreOwnCardForCost) + .FirstOrDefault(); + if (selfBest != null) targetList.Insert(0, selfBest); + } + + // log / tag effect ย่อย + if (desc == d1 && Duel.CurrentChain.Count == 0) activatedCardIdList.Add(Card.Id + 1); // e2 + if (desc == d2) activatedCardIdList.Add(Card.Id + 2); // e3 + + AI.SelectCard(targetList); + return true; + } + + return false; + } + + private bool ShouldVarudrasDetachForPop(ClientCard target) + { + if (target == null) return false; + if (target.IsFloodgate() || target.IsMonsterDangerous() || target.IsMonsterInvincible()) return true; + // ใช้สกอร์เดิม ๆ ที่เรามีเพื่อประเมินความ "คุ้ม" ของการถอดวัตถุดิบแลกกับ 1 ทำลาย + return ScoreEnemyCardForRemoval(target) >= 3000; + } + private bool ActYamaGY() + { + if (Card.Location != CardLocation.Grave) return false; + if (Bot.HasInGraveyard(CardId.SPIRIT_OF_YUBEL)) return false; + AI.SelectCard(CardId.SPIRIT_OF_YUBEL); + AI.SelectYesNo(false); + return true; + } + private bool ActYamaMZ() + { + if (CheckRemainInDeck(CardId.SHARVARA) == 0 ) return false; + AI.SelectCard(CardId.SHARVARA); + return true; + } + private bool SSRequiem() + { + if (CheckRemainInDeck(CardId.LACRIMA_CT) == 0 && !Bot.HasInHand(CardId.LACRIMA_CT)) { return false; } + requiemSummoned = true; + return true; + } + private bool L4ABOSS() + { + if (!HasInExtra(CardId.UNCHAINDEDABOMINATION)) return false; + + var mons = Bot.GetMonsters(); + var yama = mons.FirstOrDefault(m => m != null && m.Id == CardId.UNCHAINED_LORD_OF_YAMA); + var rage = mons.FirstOrDefault(m => m != null && m.Id == CardId.UNCHAINED_SOUL_OF_RAGE); + var yubel = mons.FirstOrDefault(m => m != null && m.Id == CardId.YUBEL); + var terror = mons.FirstOrDefault(m => m != null && m.Id == CardId.YUBEL_TERROR_INCARNATE); + + if (yama != null && rage != null && IsInEMZ(yama)) + { + AI.SelectMaterials(new[] { yama, rage }); + return true; + } + + if (rage != null && yubel != null && terror != null && IsInEMZ(rage)) + { + AI.SelectMaterials(new[] { rage, yubel, terror }); + return true; + } + + // 3) greedy: เลือกลิงก์ที่มีอยู่ก่อน (prefer Rage > Yama > อื่น ๆ) แล้วเติมการ์ดจนแต้มรวมครบ 4 + ClientCard firstLink = + rage ?? + yama ?? + mons.Where(m => m.HasType(CardType.Link)).OrderByDescending(m => m.LinkCount).FirstOrDefault(); + + if (firstLink != null) + { + // ไม่ใช้ของที่ไม่ควรสังเวย (NEVER_SAC) แต่ยอมใช้ Yubel/Terror ได้ + var pool = mons + .Where(m => m != firstLink && !NEVER_SAC.Contains(m.Id)) + .OrderBy(ScoreOwnCardForCost) // เสียน้อยสุดมาก่อน + .ToList(); + + var pick = new List { firstLink }; + int need = 4 - LinkValue(firstLink); + + foreach (var m in pool) + { + pick.Add(m); + need -= LinkValue(m); + if (need <= 0) break; + } + + if (need <= 0) + { + AI.SelectMaterials(pick.ToArray()); + return true; + } + + } + return false; + } + private int LinkValue(ClientCard c) => (c != null && c.HasType(CardType.Link)) ? Math.Max(1, c.LinkCount) : 1; + + private bool IsInEMZ(ClientCard c) + { + var mz = Bot.MonsterZone; + return (mz.Length > 5 && mz[5] == c) || (mz.Length > 6 && mz[6] == c); + } + public bool UnchainedAbominationActivate() + { + if (CheckWhetherNegated()) return false; + List targetList = GetNormalEnemyTargetList(true, true, CardType.Monster); + if (targetList.Count() == 0) return false; + int logDesc = ActivateDescription; + if (logDesc >= Util.GetStringId(CardId.UNCHAINDEDABOMINATION, 0)) + { + logDesc = Util.GetStringId(CardId.UNCHAINDEDABOMINATION, 0) - 10; + } + Logger.DebugWriteLine("[UnchainedAbomination]desc: " + logDesc + ", timing = " + CurrentTiming); + if (ActivateDescription == Util.GetStringId(CardId.UNCHAINDEDABOMINATION, 0)) activatedCardIdList.Add(Card.Id); + if (ActivateDescription == Util.GetStringId(CardId.UNCHAINDEDABOMINATION, 1) || ActivateDescription == -1) activatedCardIdList.Add(Card.Id + 1); + if (ActivateDescription == Util.GetStringId(CardId.UNCHAINDEDABOMINATION, 2)) activatedCardIdList.Add(Card.Id + 2); + AI.SelectCard(targetList); + + return true; + } + private ClientCard[] GetSafeMaterialsExcluding(HashSet excludeIds, int need) + { + return Bot.GetMonsters() + .Where(m => m != null + && (excludeIds == null || !excludeIds.Contains(m.Id)) + && !IsProtectedMaterial(m) // ไม่ยอมแลกของสำคัญ (Link≥2 / Extra ฯลฯ) + ) + .OrderBy(m => PriorityIndex(m.Id)) + .ThenBy(m => m.Attack) + .Take(need) + .ToArray(); + } + + private bool CanMakeRageWithoutYama() + { + var mats = GetSafeMaterialsExcluding(new HashSet { CardId.UNCHAINED_LORD_OF_YAMA }, 2); + return mats.Length >= 2; + } + private bool L2YamaSetup() + { + var mats = GetSafeMaterials(2); + if (mats.Length < 2) return false; + AI.SelectMaterials(mats); + return true; + } + private bool L2RageKeepYama() + { + // ต้องมี Yama อยู่ก่อน และต้องมีวัตถุดิบอื่น 2 ใบ (ไม่นับ Yama) + if (!Bot.HasInMonstersZone(CardId.UNCHAINED_LORD_OF_YAMA, true)) return false; + if (!CanMakeRageWithoutYama()) return false; + + var mats = GetSafeMaterialsExcluding(new HashSet { CardId.UNCHAINED_LORD_OF_YAMA }, 2); + if (mats.Length < 2) return false; // ยังไม่พอ → รอก่อน อย่าฝืนใช้ Yama + + AI.SelectMaterials(mats); + return true; + } + private bool HasFreeEMZ() + { + // ปกติ MonsterZone มี 7 ช่อง (0..4 = MMZ, 5..6 = EMZ) + var mz = Bot.MonsterZone; + bool slot5Free = mz.Length > 5 && mz[5] == null; + bool slot6Free = mz.Length > 6 && mz[6] == null; + return slot5Free || slot6Free; + } + + private bool HasValidRageLinkCandidate() + { + bool hasSP = HasInExtra(CardId.SP_LITTLE_KNIGHT); + bool hasGorgon = HasInExtra(CardId.GORGONOFZIL); + hasGorgon = HasInExtra(CardId.GORGONOFZIL); + + if (hasSP) return true; + if (hasGorgon && HasFreeEMZ()) return true; + return false; + } + + #endregion + + // ======================= On Select Somethings ==================== + #region Work Space #2 + private bool YesNoFor(int desc, int cardId, int idx) + { + var info = Duel.GetCurrentSolvingChainInfo(); + var card = Duel.GetCurrentSolvingChainCard(); + // ต้องทั้ง: คำอธิบายตรง + การ์ดบน chain ตอนนี้ตรง + return desc == Util.GetStringId(cardId, idx) + && ((info != null && info.IsCode(cardId)) || (card != null && card.IsCode(cardId))); + } + public override bool OnSelectYesNo(int desc) + { + Logger.DebugWriteLine($"[DEBUG] OnSelectYesNo: desc={desc}"); + var info = Duel.GetCurrentSolvingChainInfo(); + var solving = Duel.GetCurrentSolvingChainCard(); + DumpChain("OnSelectYesNo"); + Logger.DebugWriteLine($"[THRONE] OnSelectYesNo desc={desc} stage={_throneStage} solving={CardStr(solving)}"); + if (info != null && info.ActivatePlayer == 1) + { return false; } + // --- Nightmare Throne --- + // idx อาจต่างกันตามสคริปต์ แต่แนวคิดคือ anchor กับ desc+solving เสมอ + if (solving != null && solving.IsCode(CardId.NIGHTMARE_THRONE)) + { + // เปิด map ช่วย debug ให้เห็นว่า desc ตรง index ไหนจริง ๆ + DebugThroneDescMap(desc); + + // ยังไม่ได้เริ่มค้น -> ตอบ YES เพื่อเข้าโหมดค้น + if (_throneStage == ThroneStage.None && !throneSearched) + { + _throneStage = ThroneStage.Searching; + return true; // YES เริ่มค้น + } + + // ค้นเสร็จแล้ว และกำลังถาม "จะทำลายไหม?" -> default = NO + if (_throneStage == ThroneStage.AwaitDestroyPrompt || throneSearched) + { + _throneStage = ThroneStage.None; + return false; // ไม่ทำลาย + } + + // กันเคส engine ถามซ้ำก่อนโชว์เด็ค: ตอบ YES ไป (จะไปเข้า OnSelectCard) + if (_throneStage == ThroneStage.Searching && !throneSearched) + return true; + } + // --- Muckraker --- + /*if (YesNoFor(desc, CardId.MUCKRAKER_UNDERWORLD, 0)) + { + if (Duel.ChainTargets.Contains(Card)) return false; // ตัวเองกำลังโดนเล็งทำลาย -> ไม่ใช้ + bool protectAlly = Duel.ChainTargets.Any(t => t != null && t.Controller == 0 + && t.Location == CardLocation.MonsterZone && !YUBEL_SET.Contains(t.Id)); + return protectAlly; + }*/ + + // --- Varudras: ถามถอดวัตถุดิบอีก 1 เพื่อทำลาย --- + if (YesNoFor(desc, CardId.VARUDASN_FINAL_BRINGER, 1)) + { + var best = GetBestEnemyCard(); + return best != null && ShouldVarudrasDetachForPop(best); + } + if (solving != null + && solving.IsCode(CardId.VARUDASN_FINAL_BRINGER) + && Duel.CurrentChain.Count > 0) // แปลว่าอยู่ใน e1 ไม่ใช่ e2 + { + // มีเป้าศัตรูให้ทำลายไหม? + var t = GetNormalEnemyTargetList(true, true).FirstOrDefault(c => c.Controller == 1); + if (t == null) return false; // ไม่มีเป้า → ไม่ถอด + return ShouldVarudrasDetachForPop(t); // มีเป้า → ใช้เกณฑ์เดิมตัดสิน + } + + // aux.Stringid(78371393,2) -> คำถาม "จะสังเวยไหม?" + if (YesNoFor(desc, CardId.YUBEL, 2)) + { + // มี Lotus "บนสนามเรา" ไหม + bool haveLotusOnField = Bot.GetMonsters().Any(m => m != null && m.Id == CardId.SAMSARA_D_LOTUS); + + // ถ้ามี จะตอบ YES และตั้งธงว่ากำลังจะเลือกตัวสังเวยให้ Yubel + _yubelWantsTribute = haveLotusOnField; + return haveLotusOnField; // YES ถ้ามี Lotus, NO ถ้าไม่มี => Yubel ระเบิดตัวเอง + } + + + return base.OnSelectYesNo(desc); + } + + // Safety net for any selection the specific executors didn't pre-select + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + Logger.DebugWriteLine($"[DEBUG] OnSelectCard: hint={hint} (0x{hint:X}), min={min}, max={max}, cancelable={cancelable}, candidates={cards?.Count ?? 0}"); + + bool isReleasePrompt = + hint == (long)HintMsg.Release || + hint.ToString().ToLower().Contains("release"); // กันเหนียว + var solving = Duel.GetCurrentSolvingChainCard(); + if (cards != null && cards.Count > 0) + { + // === Throne === + if (_throneStage == ThroneStage.Searching && solving != null && solving.IsCode(CardId.NIGHTMARE_THRONE) && !throneSearched && cards != null && cards.Count > 0) + { + throneSearched = true; + _throneStage = ThroneStage.AwaitDestroyPrompt; + + ClientCard chosen = null; + if (throneDesiredPick != 0) + chosen = cards.FirstOrDefault(c => c != null && c.Id == throneDesiredPick); + + // fallback: ถ้าเลือกตามใจไม่ได้ ให้เลือกใบ Yubel ที่มีค่าที่สุด/หรือใบแรก + if (chosen == null) + chosen = cards.FirstOrDefault(c => c != null && YUBEL_SET.Contains(c.Id)) ?? cards[0]; + + Logger.DebugWriteLine($"[THRONE] Search pick => {CardStr(chosen)}"); + return new[] { chosen }; + } + // === SPIRIT GATES selections === + if (Card != null && Card.Id == CardId.SPIRIT_GATES && cards != null && cards.Count > 0) + { + // 2.1: เลือก Continuous Spell จากสุสาน (Recycle) + if (_gateWantsRecycle) + { + var pain = cards.FirstOrDefault(c => c != null && c.Id == CardId.NIGHTMARE_PAIN); + if (pain != null) return new[] { pain }; + + // อะไรต่อมิอะไรที่เป็น Continuous Spell ถ้ามี + var anyCont = cards.FirstOrDefault(c => c != null && c.IsSpell() && c.HasType(CardType.Continuous)); + if (anyCont != null) return new[] { anyCont }; + } + + // เลือกทิ้งมือเป็น cost (ลิสต์ทั้งหมดมาจากมือเรา) + bool selectingDiscard = cards.All(c => c != null && c.Controller == 0 && c.Location == CardLocation.Hand); + if (selectingDiscard && _gateDiscardPreferredId != 0) + { + var want = cards.FirstOrDefault(c => c.Id == _gateDiscardPreferredId); + if (want != null) return new[] { want }; + + // fallback: ใช้สกอร์เดิม + var sorted = cards.OrderBy(ScoreOwnCardForCost).ToList(); + return new[] { sorted[0] }; + } + + // เลือกเป้าหมายชุบจากสุสาน (Fiend 0/0) + bool selectingGYTarget = cards.Any(c => c != null && c.Location == CardLocation.Grave); + + if (selectingGYTarget) + { + if (requiemSummoned) + { + var sp = cards.FirstOrDefault(c => c != null && c.Id == CardId.SPIRIT_OF_YUBEL); + if (sp != null) return new[] { sp }; + } + if (_gateReviveTargetId != 0) + { + var t = cards.FirstOrDefault(c => c != null && c.Id == _gateReviveTargetId); + if (t != null) return new[] { t }; + } + if (moonSummoned) + { + int[] prio = { + CardId.SPIRIT_OF_YUBEL, + CardId.YUBEL + }; + foreach (var id in prio) + { + var pick = cards.FirstOrDefault(c => c != null && c.Id == id); + if (pick != null) return new[] { pick }; + } + } + else + { + int[] prio = { + CardId.SPIRIT_OF_YUBEL, + CardId.SAMSARA_D_LOTUS, + CardId.DARK_BECKONING_BEAST, + CardId.CHAOS_SUMMONING_BEAST, + CardId.YUBEL + }; + foreach (var id in prio) + { + var pick = cards.FirstOrDefault(c => c != null && c.Id == id); + if (pick != null) return new[] { pick }; + } + } + + var any00 = cards.FirstOrDefault(c => c != null && Is00FiendId(c.Id)); + if (any00 != null) return new[] { any00 }; + } + } + // === Throne: เลือกการ์ดที่ค้นเจอ === + if (Card.Id == CardId.NIGHTMARE_THRONE && _throneStage == ThroneStage.Searching && thronePending && !throneSearched) + { + throneSearched = true; + _throneStage = ThroneStage.AwaitDestroyPrompt; + ClientCard chosen = null; + if (throneDesiredPick != 0) chosen = cards.FirstOrDefault(c => c.Id == throneDesiredPick); + if (chosen == null) chosen = cards[0]; + + Logger.DebugWriteLine($"[THRONE] Search pick => {CardStr(chosen)}"); + return new[] { chosen }; + } + // --- Yubel is asking us to choose the tribute target --- + if (_yubelWantsTribute && isReleasePrompt && cards != null && cards.Count > 0) + { + var lotus = cards.FirstOrDefault(c => c != null && c.Id == CardId.SAMSARA_D_LOTUS); + if (lotus != null) + { + _yubelWantsTribute = false; // เคลียร์ธง + return new[] { lotus }; // เลือก Lotus สังเวยตามที่ต้องการ + } + // เผื่อกรณีเอนจินส่งลิสต์มาแต่ดันไม่มี Lotus (ไม่ควรเกิด เพราะเราตอบ YES เมื่อมี Lotus) + _yubelWantsTribute = false; + // ปล่อยให้ base ตัดสินใจ หรือจะ return null ก็ได้ตามฐานของคุณ + } + // --- Varudras: เลือกเป้าหมายทำลาย --- + if (Card.Id == CardId.VARUDASN_FINAL_BRINGER && hint == 502 && cards != null && cards.Count > 0) + { + // พยายามเลือกฝั่งศัตรูก่อน (คัดใบที่อันตราย/ป่วนที่สุด) + var enemyPick = cards + .Where(c => c != null && c.Controller == 1) + .OrderByDescending(c => ScoreEnemyCardForRemoval(c)) + .FirstOrDefault(); + if (enemyPick != null) return new[] { enemyPick }; + + return new[] { cards[0] }; // fallback + } + // --- Abomination: เลือกเป้าหมายทำลาย --- + if (Card.Id == CardId.UNCHAINDEDABOMINATION && hint == 502 && cards != null && cards.Count > 0) + { + // พยายามเลือกฝั่งศัตรูก่อน (คัดใบที่อันตราย/ป่วนที่สุด) + var enemyPick = cards + .Where(c => c != null && c.Controller == 1) + .OrderByDescending(c => ScoreEnemyCardForRemoval(c)) + .FirstOrDefault(); + if (enemyPick != null) return new[] { enemyPick }; + + return new[] { cards[0] }; // fallback + } + // --- Rage Quick Link --- + if (solving != null && solving.IsCode(CardId.UNCHAINED_SOUL_OF_RAGE) && cards.Any(c => c != null && c.Location == CardLocation.Extra)) + { + // 1) เลือก S:P Little Knight ก่อนเสมอ ถ้ามี + var pickSP = cards.FirstOrDefault(c => c != null && c.Id == CardId.SP_LITTLE_KNIGHT); + if (pickSP != null) return new List { pickSP }; + + // 2) เลือก Gorgon เฉพาะเมื่อ EMZ ว่างเท่านั้น + ClientCard pickGorgon = null; + pickGorgon = cards.FirstOrDefault(c => c != null && c.Id == CardId.GORGONOFZIL); + + if (pickGorgon != null) + { + if (HasFreeEMZ()) + return new List { pickGorgon }; + // ถ้า EMZ ไม่ว่าง ห้ามเลือก Gorgon -> ไปหาใบอื่นต่อ + } + + // 3) fallback: ถ้ามีลิงก์ตัวอื่นที่ generic ก็เลือกใบแรกไปก่อน + return new List { cards[0] }; + } + } + + + return base.OnSelectCard(cards, min, max, hint, cancelable); + } + + // --- Scoring helpers ------------------------------------------------- + private int ScoreOwnCardForCost(ClientCard c) + { + if (c == null) return int.MaxValue; + int score = 5000; // lower is more expendable + if (NEVER_SAC.Contains(c.Id)) return int.MaxValue; + if (YUBEL_SET.Contains(c.Id)) return 9000; + if ((c.HasType(CardType.Link) && c.LinkCount >= 2) || c.HasType(CardType.Fusion | CardType.Synchro | CardType.Xyz)) score += 2000; + if (c.EquipCards != null && c.EquipCards.Count > 0) score += 1000; + int idx = Array.IndexOf(YubelCostPriority, c.Id); + if (idx >= 0) score = 10 + idx; + score += Math.Max(0, c.Attack / 100); + return score; + } + + private int ScoreEnemyCardForRemoval(ClientCard c) + { + if (c == null) return -1; + int s = 0; + if (c.IsFloodgate()) s += 6000; + if (c.IsMonsterDangerous()) s += 4000; + if (c.IsMonsterInvincible()) s += 3500; + if (c.EquipCards != null && c.EquipCards.Count > 0) s += 800; + if (c.HasType(CardType.Fusion | CardType.Ritual | CardType.Synchro | CardType.Xyz)) s += 700; + if (c.HasType(CardType.Link) && c.LinkCount >= 2) s += 700; + s += Math.Max(0, c.Attack); + return s; + } + + #endregion + + #region DEBUG + + private string CardStr(ClientCard c) + { + if (c == null) return "null"; + string loc = c.Location.ToString(); + string face = c.IsFaceup() ? "FU" : "FD"; + return $"{c.Name}#{c.Id} [{loc}] P{c.Controller} {face}"; + } + private void DumpChain(string tag = "") + { + Logger.DebugWriteLine($"[CHAIN]{(tag == "" ? "" : $" ({tag})")} turn={Duel.Turn} player={Duel.Player} phase={Duel.Phase} chainCount={Duel.CurrentChain.Count}"); + for (int i = 0; i < Duel.CurrentChain.Count; i++) + { + var c = Duel.CurrentChain[i]; + Logger.DebugWriteLine($" [{i}] {CardStr(c)}"); + } + var solving = Duel.GetCurrentSolvingChainCard(); + if (solving != null) + { + Logger.DebugWriteLine($" -> Solving: {CardStr(solving)} ActivateDescription={ActivateDescription}"); + } + if (Duel.ChainTargets != null && Duel.ChainTargets.Count > 0) + { + var tg = Duel.ChainTargets.Where(t => t != null).Select(CardStr); + Logger.DebugWriteLine($" targets: {string.Join(" | ", tg)}"); + } + } + + private void DebugThroneDescMap(int incomingDesc) + { + for (int i = 0; i < 5; i++) + { + int sid = Util.GetStringId(CardId.NIGHTMARE_THRONE, i); + Logger.DebugWriteLine($"[THRONE] desc map i={i} strId={sid} match={(sid == incomingDesc)}"); + } + } + private bool BlockIfThrone(string who) + { + if (InThroneFlow) + { + Logger.DebugWriteLine($"[THRONE] BLOCKED {who} during Throne flow"); + return true; + } + return false; + } + + #endregion + + // ======================= END OF LIFE ==================== + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZefraExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZefraExecutor.cs new file mode 100644 index 0000000..9ae52dc --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZefraExecutor.cs @@ -0,0 +1,2211 @@ +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; +using System.Collections.Generic; +using System.Linq; +using System; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; +namespace WindBot.Game.AI.Decks +{ + [Deck("Zefra", "AI_Zefra")] + class ZefraExecutor : DefaultExecutor + { + public class CardId + { + //main code + public const int PSY_FrameDriver = 49036338; + public const int Zefraath = 29432356; + public const int TheMightyMasterofMagic = 3611830; + public const int AstrographSorcerer = 76794549; + public const int DestrudotheLostDragon_Frisson = 5560911; + public const int SupremeKingGateZero = 96227613; + public const int MythicalBeastJackalKing = 27354732; + public const int SecretoftheYangZing = 58990362; + public const int FlameBeastoftheNekroz = 20773176; + public const int StellarknightZefraxciton = 22617205; + public const int SupremeKingDragonDarkwurm = 69610326; + public const int Blackwing_ZephyrostheElite = 14785765; + public const int ShaddollZefracore = 95401059; + public const int Raidraptor_SingingLanius = 31314549; + public const int SatellarknightZefrathuban = 96223501; + public const int Raider_Wing = 52159691; + public const int Zefraxi_TreasureoftheYangZing = 21495657; + public const int RitualBeastTamerZeframpilica = 57777714; + public const int ServantofEndymion = 92559258; + public const int PSY_FramegearGamma = 38814750; + public const int MechaPhantomBeastO_Lion = 72291078; + public const int MaxxC = 23434538; + public const int Deskbot001 = 94693857; + public const int JetSynchron = 9742784; + public const int DDLamia = 19580308; + public const int DDSavantKepler = 11609969; + public const int LightoftheYangZing = 61488417; + public const int Rank_Up_MagicSoulShaveForce = 23581825; + public const int SpellPowerMastery = 38943357; + public const int DragonShrine = 41620959; + public const int Terraforming = 73628505; + public const int ZefraProvidence = 74580251; + public const int FoolishBurial = 81439173; + public const int CalledbytheGrave = 24224830; + public const int DarkContractwiththGate = 46372010; + public const int OracleofZefra = 32354768; + public const int ZefraWar = 96073342; + public const int ZefraDivineStrike = 35561352; + public const int NinePillarsofYangZing = 57831349; + public const int OneforOne = 2295440; + + //extra code + public const int BorreloadSavageDragon = 27548199; + public const int Odd_EyesMeteorburstDragon = 80696379; + public const int F_A_DawnDragster = 33158448; + public const int Denglong_FirstoftheYangZing = 65536818; + public const int HeraldoftheArcLight = 79606837; + public const int TruKingofAllCalamities = 88581108; + public const int Raidraptor_ArsenalFalcon = 96157835; + public const int Raidraptor_ForceStrix = 73347079; + public const int SaryujaSkullDread = 74997493; + public const int MechaPhantomBeastAuroradon = 44097050; + public const int HeavymetalfoesElectrumite = 24094258; + public const int CrystronHalqifibrax = 50588353; + public const int Raidraptor_WiseStrix = 36429703; + public const int Linkuriboh = 41999284; + public const int PSY_FramelordOmega = 74586817; + + public const int MechaPhantomBeastToken = 44097051; + } + private bool opt_0 = false; + private bool opt_1 = false; + private bool opt_2 = false; + //edo false + private const bool IS_YGOPRO = true; + private const int P_ACTIVATE_DESC = 1160; + //private const int P_SPSUMMON_DESC = 1163; + private int p_count = 0; + private int spell_activate_count = 0; + private bool summoned = false; + private bool link_summoned = false; + private bool p_summoned = false; + private bool p_summoning = false; + private bool activate_SupremeKingDragonDarkwurm_1 = false; + private bool activate_p_Zefraath = false; + private bool activate_OracleofZefra = false; + private bool activate_ZefraProvidence = false; + private bool activate_SupremeKingDragonDarkwurm_2 = false; + private bool activate_JetSynchron = false; + private bool activate_Blackwing_ZephyrostheElite = false; + private bool activate_DragonShrine = false; + private bool activate_SpellPowerMastery = false; + private bool activate_DestrudotheLostDragon_Frisson = false; + private bool activate_DarkContractwiththGate = false; + private bool activate_SecretoftheYangZing = false; + private bool activate_ShaddollZefracore = false; + private bool activate_DDLamia = false; + private bool xyz_mode = false; + private bool Blackwing_ZephyrostheElite_activate = false; + private bool HeavymetalfoesElectrumite_activate = false; + private bool should_destory = false; + private List Odd_EyesMeteorburstDragon_materials = new List(); + private bool duel_start = true; + private int activate_count = 0; + private int summon_count = 0; + private bool enemy_activate = false; + private enum CustomMessage + { + Happy, + Angry, + Surprise + } + private static class Toos + { + public delegate bool Delegate(ClientCard card); + private static bool DefaultFunc(ClientCard card) + { + return true; + } + public static bool LinqAny(IList cards, Delegate @delegate = null) + { + if (cards == null) return false; + @delegate = @delegate ?? DefaultFunc; + return cards.Any(card => card != null && @delegate(card)); + } + public static bool LinqAll(IList cards, Delegate @delegate = null, bool flag = true) + { + if (cards == null) return false; + IList rcards = new List(cards); + if (flag) rcards = cards.Where(card => card != null).ToList(); + @delegate = @delegate ?? DefaultFunc; + return rcards.All(card => card != null && @delegate(card)); + } + public static int LinqCount(IList cards, Delegate @delegate = null) + { + if (cards == null) return -1; + @delegate = @delegate ?? DefaultFunc; + return cards.Count(card => card != null && @delegate(card)); + } + public static List LinqWhere(IList cards, Delegate @delegate = null) + { + if (cards == null) return new List(); + @delegate = @delegate ?? DefaultFunc; + return cards.Where(card => card != null && @delegate(card)).ToList(); + } + } + private class Func + { + private IList _parameters = new List(); + private List no_p_spsummon_ids = new List() + { + CardId.Zefraath + }; + private List selectCardList = null; + private List selectCardIdList = null; + public List GetSelectCardList() + { + if (selectCardList == null) + { + selectCardList = new List(); + } + else + { + selectCardList.Clear(); + } + return selectCardList; + } + public List GetSelectCardIdList() + { + if (selectCardIdList == null) + { + selectCardIdList = new List(); + } + else + { + selectCardIdList.Clear(); + } + return selectCardIdList; + } + public bool IsLocation(ClientCard card) + { + return card.Location == (CardLocation)_parameters[0]; + } + public bool IsCode(ClientCard card) + { + return card.IsCode((int)_parameters[0]); + } + public static bool IsCode(ClientCard card, params int[] ids) + { + if (card == null) return false; + foreach (var id in ids) + { + if (card.IsCode(id)) return true; + } + return false; + } + public bool HasSetCode(ClientCard card) + { + return card.HasSetcode((int)_parameters[0]); + } + public static bool HasSetCode(ClientCard card, params int[] set_codes) + { + if (card == null) return false; + foreach (var set_code in set_codes) + { + if (card.HasSetcode(set_code)) return true; + } + return false; + } + public static bool IsFaceUp(ClientCard card) + { + return card.IsFaceup(); + } + public bool HasAttribute(ClientCard card) + { + return card.HasAttribute((CardAttribute)_parameters[0]); + } + public bool HasRace(ClientCard card) + { + return card.HasRace((CardRace)_parameters[0]); + } + public bool HasLevel(ClientCard card) + { + return card.Level == (int)_parameters[0]; + } + public bool HasType(ClientCard card) + { + return card.HasType((CardType)_parameters[0]); + } + public static bool IsOnfield(ClientCard card) + { + return (card.Location & CardLocation.MonsterZone) > 0 || (card.Location & CardLocation.SpellZone) > 0; + } + public static Toos.Delegate NegateFunc(Toos.Delegate @delegate) + { + return card => { return !@delegate(card); }; + } + private void SetParameters(IList parameters) + { + ClearParameters(); + for (int i = 0; i < parameters?.Count(); ++i) + { + _parameters.Add(parameters[i]); + } + } + private void ClearParameters() + { + _parameters.Clear(); + } + public bool CardsCheckAny(IList cards, Toos.Delegate @delegate = null, params object[] parameters) + { + SetParameters(parameters); + return Toos.LinqAny(cards, @delegate); + } + public bool CardsCheckALL(IList cards, Toos.Delegate @delegate = null, bool all = true, params object[] parameters) + { + SetParameters(parameters); + return Toos.LinqAll(cards, @delegate, all); + } + public int CardsCheckCount(IList cards, Toos.Delegate @delegate = null, params object[] parameters) + { + SetParameters(parameters); + return Toos.LinqCount(cards, @delegate); + } + public List CardsCheckWhere(IList cards, Toos.Delegate @delegate = null, params object[] parameters) + { + SetParameters(parameters); + return Toos.LinqWhere(cards, @delegate); + } + public static List MergeList(params List[] lists) + { + List result = new List(); + foreach (var list in lists) + { + if (list == null) continue; + result.AddRange(list); + } + return result; + } + public List CardsIdToClientCards(IList cardsId, IList cardsList, bool uniqueId = true) + { + if (cardsList?.Count() <= 0 || cardsId?.Count() <= 0) return new List(); + List result = new List(); + cardsId = cardsId.Distinct().ToList(); + foreach (var cardid in cardsId) + { + List cards = CardsCheckWhere(cardsList, IsCode, cardid); + if (cards.Count <= 0) continue; + if (uniqueId) result.Add(cards.First()); + else result.AddRange(cards); + } + return result; + } + public static List ClientCardsToCardsId(IList cardsList, bool uniqueId = false, bool alias = false) + { + if (cardsList?.Count <= 0) return new List(); + List res = new List(); + foreach (var card in cardsList) + { + if (card == null) continue; + if (card.Alias != 0 && alias && !(res.Contains(card.Alias) & uniqueId)) res.Add(card.Alias); + else if (card.Id != 0 && !(res.Contains(card.Id) & uniqueId)) res.Add(card.Id); + } + return res; + } + //AIUtil + public static IList CheckSelectCount(AIUtil util, IList _selected, IList cards, int min, int max) + { + return _selected?.Count() <= 0 ? null : util.CheckSelectCount(_selected, cards, min, max); + } + public static List GetZoneCards(ClientField player, CardLocation loc, bool feceup = false, bool disable = false) + { + if (!feceup) disable = false; + List result = new List(); + if ((loc & CardLocation.Hand) > 0) result.AddRange(Toos.LinqWhere(player.Hand)); + if ((loc & CardLocation.MonsterZone) > 0) result.AddRange(Toos.LinqWhere(player.MonsterZone, card => !(!card.IsFaceup() & feceup) && !(!card.IsDisabled() & disable))); + if ((loc & CardLocation.SpellZone) > 0) result.AddRange(Toos.LinqWhere(player.SpellZone, card => !(!card.IsFaceup() & feceup) && !(!card.IsDisabled() & disable))); + if ((loc & CardLocation.PendulumZone) > 0) result.AddRange(Toos.LinqWhere(new List() { player.SpellZone[0], player.SpellZone[4] }, card => !(!card.IsFaceup() & feceup) && !(!card.IsDisabled() & disable))); + if ((loc & CardLocation.Grave) > 0) result.AddRange(Toos.LinqWhere(player.Graveyard)); + if ((loc & CardLocation.Removed) > 0) result.AddRange(Toos.LinqWhere(player.Banished, card => !(!card.IsFaceup() & feceup))); + if ((loc & CardLocation.Extra) > 0) result.AddRange(Toos.LinqWhere(player.ExtraDeck, card => !(!card.IsFaceup() & feceup))); + result = result.Distinct().ToList(); + return result; + } + public bool HasInZone(ClientField player, CardLocation loc, int id, bool feceup = false, bool disable = false) + { + return CardsCheckAny(GetZoneCards(player, loc, feceup, disable), IsCode, id); + } + public static bool SpellActivate(ClientCard card) + { + return card.Location == CardLocation.Hand || (card.Location == CardLocation.SpellZone && card.IsFacedown()); + } + public static bool PendulumActivate(int desc, ClientCard card) + { + return desc == P_ACTIVATE_DESC && card.Location == CardLocation.Hand; + } + private static Toos.Delegate GetPSpSummonLimilt(ClientCard pcard) + { + int setcode = -1; + int setcode2 = -1; + switch (pcard.Id) + { + case CardId.SecretoftheYangZing: + case CardId.Zefraxi_TreasureoftheYangZing: { setcode = 0xc4; setcode2 = 0x9e; break; } + case CardId.FlameBeastoftheNekroz: { setcode = 0xc4; setcode2 = 0xb4; break; } + case CardId.StellarknightZefraxciton: + case CardId.SatellarknightZefrathuban: { setcode = 0xc4; setcode2 = 0x109c; break; } + case CardId.RitualBeastTamerZeframpilica: { setcode = 0xc4; setcode2 = 0x10b5; break; } + case CardId.ShaddollZefracore: { setcode = 0xc4; setcode2 = 0x9d; break; } + case CardId.DDSavantKepler: { setcode = 0xaf; break; } + default: break; + } + return card => { + return (setcode == -1 ? true : card.HasSetcode(setcode)) + || (setcode2 == -1 ? true : card.HasSetcode(setcode2)); + }; + } + public static int[] GetPScales(ClientField bot) + { + int[] pScales = new int[2]; + ClientCard lcard = bot.SpellZone[0]; + ClientCard rcard = bot.SpellZone[4]; + pScales[0] = (lcard == null || lcard.IsFacedown() || !lcard.HasType(CardType.Pendulum)) ? -1 : lcard.RScale; + pScales[1] = (rcard == null || rcard.IsFacedown() || !rcard.HasType(CardType.Pendulum)) ? -1 : rcard.LScale; + return pScales; + } + public static int GetPScale(ClientField bot, int id) + { + bool rscale = false; + ClientCard pcard = null; + if (bot.SpellZone[0] != null && bot.SpellZone[0].Id == id) + { + pcard = bot.SpellZone[4]; + } + else + { + pcard = bot.SpellZone[0]; + rscale = true; + } + if (pcard == null || pcard.IsFacedown() || !pcard.HasType(CardType.Pendulum)) return -1; + return rscale ? pcard.RScale : pcard.LScale; + } + public List GetPSpSummonMonster(ClientField bot, ClientCard lcard, ClientCard rcard) + { + if (lcard == null || rcard == null || !lcard.HasType(CardType.Pendulum) || !rcard.HasType(CardType.Pendulum) || (IsOnfield(lcard) & lcard.IsFacedown()) || (IsOnfield(lcard) & rcard.IsFacedown())) return null; + int MaxScale = Math.Max(lcard.RScale, rcard.LScale); + int MinScale = Math.Min(lcard.RScale, rcard.LScale); + Toos.Delegate @llimit = GetPSpSummonLimilt(lcard); + Toos.Delegate @rlimit = GetPSpSummonLimilt(rcard); + return CardsCheckWhere(GetZoneCards(bot, CardLocation.Hand | CardLocation.Extra, true), + card => { + return card != lcard && card != rcard && card.HasType(CardType.Monster) && card.Level > MinScale && card.Level < MaxScale + && !no_p_spsummon_ids.Contains(card.Id) && @llimit(card) && @rlimit(card); + }); ; + } + public bool IsActivateScale(ClientField bot, ClientCard card) + { + ClientCard lcard = bot.SpellZone[0]; + ClientCard rcard = bot.SpellZone[4]; + List spSummonMonster = null; + if (lcard != null && rcard != null) return false; + if (lcard == null && rcard == null) return true; + + spSummonMonster = lcard == null ? GetPSpSummonMonster(bot, card, rcard) : GetPSpSummonMonster(bot, lcard, card); + return spSummonMonster?.Count() > 0; + } + public static int CompareCardScale(ClientCard cardA, ClientCard cardB) + { + if (cardA.RScale < cardB.RScale) + return -1; + if (cardA.RScale == cardB.RScale) + return 0; + return 1; + } + public static List GetCardsRepeatCardsId(IList cards) + { + if (cards?.Count <= 0) return new List() { -1 }; + IList cardsid = new List(); + List res = new List(); + foreach (var card in cards) + { + if (card == null) continue; + cardsid.Add(card.Id); + } + for (int i = 0; i < cardsid.Count; i++) + { + if (res.Count >= 0 && res.Contains(cardsid[i])) continue; + int times = 0; + for (int j = 0; j < cardsid.Count; j++) + { + if (times > 1) { res.Add(cardsid[i]); break; } + if (cardsid[i] == cardsid[j]) ++times; + } + } + if (res.Count <= 0) return new List() { -1 }; + return res; + } + } + private Func func = new Func(); + public ZefraExecutor(GameAI ai, Duel duel) : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, CardId.CalledbytheGrave, CalledbytheGraveEffect); + AddExecutor(ExecutorType.Activate, CardId.BorreloadSavageDragon, BorreloadSavageDragonEffect_2); + AddExecutor(ExecutorType.Activate, CardId.F_A_DawnDragster, ResetFlag); + AddExecutor(ExecutorType.Activate, CardId.NinePillarsofYangZing, NinePillarsofYangZingEffect); + AddExecutor(ExecutorType.Activate, CardId.ZefraDivineStrike, ZefraDivineStrikeEffect); + AddExecutor(ExecutorType.Activate, CardId.HeraldoftheArcLight, HeraldoftheArcLightEffect); + AddExecutor(ExecutorType.Activate, CardId.TruKingofAllCalamities, TruKingofAllCalamitiesEffect); + AddExecutor(ExecutorType.Activate, CardId.PSY_FramegearGamma, ResetFlag); + AddExecutor(ExecutorType.Activate, CardId.MaxxC, DefaultMaxxC); + AddExecutor(ExecutorType.Activate, CardId.SupremeKingDragonDarkwurm, SupremeKingDragonDarkwurmEffect); + AddExecutor(ExecutorType.Activate, CardId.ServantofEndymion, ServantofEndymionEffect); + AddExecutor(ExecutorType.Activate, CardId.Terraforming, TerraformingEffect); + AddExecutor(ExecutorType.Activate, CardId.SpellPowerMastery, ResetFlag); + AddExecutor(ExecutorType.Activate, CardId.DragonShrine, DragonShrineEffect); + AddExecutor(ExecutorType.Activate, CardId.FoolishBurial, FoolishBurialEffect); + AddExecutor(ExecutorType.Activate, CardId.DarkContractwiththGate, DarkContractwiththGateEffect); + AddExecutor(ExecutorType.Activate, CardId.Terraforming, ResetFlag); + AddExecutor(ExecutorType.Activate, CardId.OracleofZefra, OracleofZefraEffect); + AddExecutor(ExecutorType.Activate, CardId.ZefraProvidence, ZefraProvidenceEffect); + AddExecutor(ExecutorType.Activate, CardId.AstrographSorcerer, AstrographSorcererEffect); + AddExecutor(ExecutorType.Activate, CardId.HeavymetalfoesElectrumite, HeavymetalfoesElectrumiteEffect); + AddExecutor(ExecutorType.Summon, CardId.SupremeKingDragonDarkwurm, SupremeKingDragonDarkwurmSummon); + AddExecutor(ExecutorType.Activate, CardId.SupremeKingGateZero, SupremeKingGateZeroEffect); + AddExecutor(ExecutorType.Activate, CardId.Zefraxi_TreasureoftheYangZing, Zefraxi_TreasureoftheYangZingEffect); + AddExecutor(ExecutorType.Activate, CardId.SatellarknightZefrathuban, SatellarknightZefrathubanEffect); + AddExecutor(ExecutorType.Activate, CardId.RitualBeastTamerZeframpilica, RitualBeastTamerZeframpilicaEffect); + AddExecutor(ExecutorType.Activate, CardId.SecretoftheYangZing, SecretoftheYangZingEffect); + AddExecutor(ExecutorType.Activate, CardId.FlameBeastoftheNekroz, FlameBeastoftheNekrozEffect); + AddExecutor(ExecutorType.Activate, CardId.ShaddollZefracore, ShaddollZefracoreEffect); + AddExecutor(ExecutorType.Activate, CardId.StellarknightZefraxciton, StellarknightZefraxcitonEffect); + AddExecutor(ExecutorType.Activate, CardId.SupremeKingDragonDarkwurm, SupremeKingGateZeroEffect); + AddExecutor(ExecutorType.Activate, CardId.AstrographSorcerer, SupremeKingGateZeroEffect); + AddExecutor(ExecutorType.Activate, CardId.Zefraath, ZefraathEffect); + AddExecutor(ExecutorType.Activate, CardId.DDSavantKepler, DDSavantKeplerEffect); + AddExecutor(ExecutorType.Summon, CardId.DDSavantKepler, DDSavantKeplerSummon); + AddExecutor(ExecutorType.Activate, CardId.ServantofEndymion, ServantofEndymionEffect_3); + AddExecutor(ExecutorType.Activate, CardId.MythicalBeastJackalKing, MythicalBeastJackalKingEffect); + AddExecutor(ExecutorType.SpSummon, Psummon); + AddExecutor(ExecutorType.Activate, CardId.OneforOne, OneforOneEffect); + AddExecutor(ExecutorType.Activate, CardId.ServantofEndymion, ServantofEndymionEffect_2); + AddExecutor(ExecutorType.Activate, CardId.CrystronHalqifibrax, CrystronHalqifibraxEffect); + AddExecutor(ExecutorType.SpSummon, CardId.Raidraptor_ArsenalFalcon, Raidraptor_ArsenalFalconSummon); + AddExecutor(ExecutorType.Activate, CardId.Raidraptor_ArsenalFalcon, Raidraptor_ArsenalFalconEffect); + AddExecutor(ExecutorType.SpSummon, CardId.HeavymetalfoesElectrumite, HeavymetalfoesElectrumiteSummon); + //xyz mode + AddExecutor(ExecutorType.SpSummon, CardId.Odd_EyesMeteorburstDragon, Odd_EyesMeteorburstDragonSummon); + AddExecutor(ExecutorType.Activate, CardId.Odd_EyesMeteorburstDragon, Odd_EyesMeteorburstDragonEffect); + AddExecutor(ExecutorType.SpSummon, CardId.Raidraptor_WiseStrix, Raidraptor_WiseStrixSummon); + AddExecutor(ExecutorType.Activate, CardId.Raidraptor_WiseStrix, Raidraptor_WiseStrixEffect); + AddExecutor(ExecutorType.Activate, CardId.Blackwing_ZephyrostheElite, Blackwing_ZephyrostheEliteEffect); + AddExecutor(ExecutorType.SpSummon, CardId.Raidraptor_ForceStrix, Raidraptor_ForceStrixSummon); + AddExecutor(ExecutorType.Activate, CardId.Raidraptor_ForceStrix, Raidraptor_ForceStrixEffect); + AddExecutor(ExecutorType.Activate, CardId.Rank_Up_MagicSoulShaveForce, ResetFlag); + AddExecutor(ExecutorType.Activate, CardId.Raider_Wing, Raider_WingEffect); + AddExecutor(ExecutorType.SpSummon, CardId.Raidraptor_SingingLanius); + //xyz mode + AddExecutor(ExecutorType.SpSummon, CardId.SaryujaSkullDread, SaryujaSkullDreadSummon); + AddExecutor(ExecutorType.Activate, CardId.SaryujaSkullDread, SaryujaSkullDreadEffect); + AddExecutor(ExecutorType.SpSummon, CardId.Denglong_FirstoftheYangZing, Denglong_FirstoftheYangZingSummon_2); + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadSavageDragon, BorreloadSavageDragonSummon_2); + AddExecutor(ExecutorType.SpSummon, CardId.CrystronHalqifibrax, CrystronHalqifibraxSummon); + AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh, LinkuribohSummon); + AddExecutor(ExecutorType.Activate, CardId.DDLamia, DDLamiaEffect); + AddExecutor(ExecutorType.SpSummon, CardId.MechaPhantomBeastAuroradon, MechaPhantomBeastAuroradonSummon); + AddExecutor(ExecutorType.Activate, CardId.MechaPhantomBeastAuroradon, MechaPhantomBeastAuroradonEffect); + AddExecutor(ExecutorType.SpSummon, CardId.Denglong_FirstoftheYangZing, Denglong_FirstoftheYangZingSummon); + AddExecutor(ExecutorType.Activate, CardId.Denglong_FirstoftheYangZing, Denglong_FirstoftheYangZingEffect); + AddExecutor(ExecutorType.SpSummon, CardId.BorreloadSavageDragon, BorreloadSavageDragonSummon); + AddExecutor(ExecutorType.Activate, CardId.BorreloadSavageDragon, BorreloadSavageDragonEffect); + AddExecutor(ExecutorType.SpSummon, CardId.HeraldoftheArcLight); + AddExecutor(ExecutorType.SpSummon, CardId.F_A_DawnDragster, F_A_DawnDragsterSummon); + AddExecutor(ExecutorType.SpSummon, CardId.PSY_FramelordOmega, BorreloadSavageDragonSummon); + AddExecutor(ExecutorType.Activate, CardId.PSY_FramelordOmega, PSY_FramelordOmegaEffect); + AddExecutor(ExecutorType.Activate, CardId.Linkuriboh, LinkuribohEffect); + AddExecutor(ExecutorType.Activate, CardId.MechaPhantomBeastO_Lion); + AddExecutor(ExecutorType.Activate, CardId.JetSynchron, JetSynchronEffect); + AddExecutor(ExecutorType.Activate, CardId.Blackwing_ZephyrostheElite, Blackwing_ZephyrostheEliteEffect_2); + AddExecutor(ExecutorType.Summon, CardId.JetSynchron, DDLamiaSummon); + AddExecutor(ExecutorType.Summon, CardId.DDLamia, DDLamiaSummon); + AddExecutor(ExecutorType.Summon, CardId.Deskbot001, DDLamiaSummon); + AddExecutor(ExecutorType.Summon, CardId.LightoftheYangZing, DDLamiaSummon); + List p_summon_ids = new List() {CardId.Zefraxi_TreasureoftheYangZing,CardId.SatellarknightZefrathuban,CardId.ServantofEndymion,CardId.RitualBeastTamerZeframpilica, + CardId.DDSavantKepler,CardId.StellarknightZefraxciton,CardId.ShaddollZefracore,CardId.SupremeKingDragonDarkwurm}; + for (int i = 0; i < p_summon_ids.Count; ++i) AddExecutor(ExecutorType.Summon, p_summon_ids[i], DefaultSummon); + AddExecutor(ExecutorType.Summon, DefaultSummon); + AddExecutor(ExecutorType.Activate, CardId.Deskbot001, ResetFlag); + AddExecutor(ExecutorType.Activate, CardId.TheMightyMasterofMagic, TheMightyMasterofMagicEffect); + AddExecutor(ExecutorType.Activate, CardId.DestrudotheLostDragon_Frisson, DestrudotheLostDragon_FrissonEffect); + AddExecutor(ExecutorType.Summon, CardId.Blackwing_ZephyrostheElite, DefaultSummon_2); + AddExecutor(ExecutorType.Summon, DefaultSummon_2); + AddExecutor(ExecutorType.SpSummon, CardId.Linkuriboh); + AddExecutor(ExecutorType.SpellSet, SpellSet); + AddExecutor(ExecutorType.SpellSet, SpellSet_2); + AddExecutor(ExecutorType.Repos, DefaultMonsterRepos); + AddExecutor(ExecutorType.Activate, DefaultPActivate); + AddExecutor(ExecutorType.GoToEndPhase, GoToEndPhase); + } + public override void OnNewTurn() + { + if (duel_start) + { + duel_start = false; + // [YGOL] TICKET-349 + } + activate_SupremeKingDragonDarkwurm_1 = false; + activate_SupremeKingDragonDarkwurm_2 = false; + activate_JetSynchron = false; + activate_DestrudotheLostDragon_Frisson = false; + activate_ZefraProvidence = false; + activate_OracleofZefra = false; + activate_DragonShrine = false; + activate_p_Zefraath = false; + p_summoned = false; + summoned = false; + activate_DarkContractwiththGate = false; + activate_SecretoftheYangZing = false; + activate_ShaddollZefracore = false; + activate_SpellPowerMastery = false; + link_summoned = false; + activate_DDLamia = false; + xyz_mode = false; + Blackwing_ZephyrostheElite_activate = false; + HeavymetalfoesElectrumite_activate = false; + spell_activate_count = 0; + p_count = 0; + activate_count = 0; + summon_count = 0; + enemy_activate = false; + base.OnNewTurn(); + } + private bool ZefraProvidenceEffect() + { + if (ActivateDescription == 96) + { + if (should_destory) + { + should_destory = false; + return false; + } + return BeforeResult(ExecutorType.Activate); + } + else + { + activate_ZefraProvidence = true; + return BeforeResult(ExecutorType.Activate); + } + + } + private List CheckShouldSpsummonExtraMonster() + { + List extra_ids = new List() { CardId.HeavymetalfoesElectrumite, CardId.CrystronHalqifibrax }; + if (!Bot.HasInExtra(CardId.HeavymetalfoesElectrumite)) extra_ids.Remove(CardId.HeavymetalfoesElectrumite); + if (!Bot.HasInExtra(CardId.CrystronHalqifibrax)) extra_ids.Remove(CardId.CrystronHalqifibrax); + if (extra_ids.Count <= 0) return extra_ids; + bool DD_summon_check = false; + if (Bot.HasInExtra(CardId.CrystronHalqifibrax) && ((!summoned && HasInDeck(CardId.DDSavantKepler) && (HasInDeck(CardId.DarkContractwiththGate) || Bot.HasInHandOrInSpellZone(CardId.DarkContractwiththGate) + ) && !activate_DarkContractwiththGate && HasInDeck(CardId.DDLamia)) || (func.CardsCheckAny(Bot.Hand, func.HasType, CardType.Tuner) && + (HasInDeck(CardId.AstrographSorcerer) || Bot.HasInHand(CardId.AstrographSorcerer))))) + { + DD_summon_check = true; + } + if (Bot.SpellZone[0] != null && Bot.SpellZone[4] != null) + { + List spSummonMonster = func.GetPSpSummonMonster(Bot, Bot.SpellZone[0], Bot.SpellZone[4]); + if (DD_summon_check && spSummonMonster != null) + { + + List pSpsummonMonster = func.CardsCheckWhere(spSummonMonster, func.HasType, CardType.Pendulum); + List monsterCards = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.MonsterZone), card => + { return card.IsFaceup() && card.HasType(CardType.Pendulum); }); + if (Func.MergeList(pSpsummonMonster, monsterCards).Count <= 0) extra_ids.Remove(CardId.HeavymetalfoesElectrumite); + } + else + { + extra_ids.Remove(CardId.HeavymetalfoesElectrumite); + } + } + else + { + if (!((Bot.HasInHand(CardId.OracleofZefra) && !activate_OracleofZefra) || (Bot.HasInHand(CardId.ZefraProvidence) + && !activate_ZefraProvidence) || (Bot.HasInHand(CardId.Zefraath) && !activate_p_Zefraath))) + { + extra_ids.Clear(); + } + } + if (!DD_summon_check) extra_ids.Remove(CardId.HeavymetalfoesElectrumite); + return extra_ids; + } + private bool DDLamiaSummon() + { + if (!IsCanSynchroSummon(Card.Level)) return false; + if (Bot.HasInExtra(CardId.Linkuriboh) || (Bot.HasInExtra(CardId.CrystronHalqifibrax) && + Func.GetZoneCards(Bot, CardLocation.MonsterZone, true).Count > 0)) + { + summoned = true; + return BeforeResult(ExecutorType.Summon); + } + return false; + } + private bool XyzModeCheck(bool flag1 = false) + { + return !link_summoned && !(!Bot.HasInExtra(CardId.Raidraptor_ArsenalFalcon) & flag1) && HasInDeck(CardId.Blackwing_ZephyrostheElite) && Bot.HasInExtra(CardId.Raidraptor_ForceStrix) && Bot.HasInExtra(CardId.Raidraptor_WiseStrix) + && Bot.HasInExtra(CardId.TruKingofAllCalamities) && (HasInDeck(CardId.Raider_Wing) || Bot.HasInHand(CardId.Raider_Wing)) + && (HasInDeck(CardId.Raidraptor_SingingLanius) || Bot.HasInHand(CardId.Raidraptor_SingingLanius)) + && (HasInDeck(CardId.Rank_Up_MagicSoulShaveForce) || Bot.HasInHand(CardId.Rank_Up_MagicSoulShaveForce)); + } + private bool Raidraptor_ForceStrixEffect() + { + AI.SelectCard(CardId.Raider_Wing); + AI.SelectNextCard(CardId.Raidraptor_SingingLanius); + return BeforeResult(ExecutorType.Activate); + } + private bool Raidraptor_ForceStrixSummon() + { + return xyz_mode && BeforeResult(ExecutorType.Summon); + } + + private bool Blackwing_ZephyrostheEliteEffect_2() + { + if (!xyz_mode && Bot.GetMonstersInMainZone().Count > 4) return false; + List cards = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.Onfield, true), card => { + return !IsNoLinkCards(card) && !card.IsExtraCard() && !(card.Location == CardLocation.SpellZone + && Func.IsCode(card, CardId.SaryujaSkullDread, CardId.MechaPhantomBeastAuroradon, CardId.HeavymetalfoesElectrumite, CardId.CrystronHalqifibrax, CardId.Raidraptor_WiseStrix, + CardId.Linkuriboh)); + }); + if (cards.Count <= 0 || (cards.Count < 2 && func.CardsCheckCount(cards, func.HasLevel, 4) == cards.Count)) + { + Blackwing_ZephyrostheElite_activate = true; + return false; + } + cards.Sort((cardA, cardB) => + { + if (cardA.Location != CardLocation.MonsterZone && cardB.Location == CardLocation.MonsterZone) return -1; + if (cardA.Location == CardLocation.MonsterZone && cardB.Location != CardLocation.MonsterZone) return 1; + if (cardA.Location == CardLocation.SpellZone && cardB.Location == CardLocation.SpellZone) + { + if (cardA.IsCode(CardId.OracleofZefra) && !cardB.IsCode(CardId.OracleofZefra)) return -1; + if (!cardA.IsCode(CardId.OracleofZefra) && cardB.IsCode(CardId.OracleofZefra)) return 1; + return 0; + } + if (xyz_mode) + { + if (cardA.Level == 4 && cardB.Level != 4) return 1; + if (cardA.Level != 4 && cardB.Level == 4) return -1; + return CardContainer.CompareCardAttack(cardA, cardB); + } + else + { + return CardContainer.CompareCardAttack(cardA, cardB); + } + }); + Blackwing_ZephyrostheElite_activate = false; + AI.SelectCard(cards); + return BeforeResult(ExecutorType.Activate); + } + public override void OnChaining(int player, ClientCard card) + { + if (card == null) return; + if (player == 1 && Func.IsCode(card, 14558127, 59438930, 94145021, 38814750, 73642296, 97268402)) + enemy_activate = true; + base.OnChaining(player, card); + } + private bool BeforeResult(ExecutorType type) + { + if (type == ExecutorType.Activate) + { + ResetFlag(); + ++activate_count; + } + if (type == ExecutorType.Summon) + { + ++summon_count; + } + return true; + } + private bool GoToEndPhase() + { + if (Duel.Player == 0 && Duel.Turn == 1 && func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), IsNoLinkCards) <= 0 + && activate_count + summon_count < 5 && !enemy_activate) + { + + // [YGOL] TICKET-349 + return true; + } + return false; + + } + private bool DefaultPActivate() + { + if (PendulumActivate() && Func.IsCode(Card, CardId.Zefraxi_TreasureoftheYangZing, CardId.SecretoftheYangZing)) + { + return Bot.HasInHandOrInSpellZone(CardId.NinePillarsofYangZing) && func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.SpellZone, + true), card => { return Func.IsCode(Card, CardId.Zefraxi_TreasureoftheYangZing, CardId.SecretoftheYangZing); }) <= 0 && BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool Blackwing_ZephyrostheEliteEffect() + { + if (!xyz_mode) return false; + return Blackwing_ZephyrostheEliteEffect_2(); + } + private bool Raidraptor_WiseStrixSummon() + { + if (!xyz_mode) return false; + AI.SelectMaterials(CardId.Raidraptor_ArsenalFalcon, CardId.Blackwing_ZephyrostheElite); + return BeforeResult(ExecutorType.Summon); + } + private bool Raidraptor_WiseStrixEffect() + { + if (ActivateDescription == -1) + { + int count = 0; + if (HasInDeck(CardId.Raidraptor_SingingLanius)) ++count; + if (HasInDeck(CardId.Blackwing_ZephyrostheElite)) ++count; + if (HasInDeck(CardId.Raider_Wing)) ++count; + if (count <= 1) return false; + AI.SelectCard(CardId.Raider_Wing); + return BeforeResult(ExecutorType.Activate); + } + return BeforeResult(ExecutorType.Activate); + } + private bool Raidraptor_ArsenalFalconEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + AI.SelectCard(CardId.SupremeKingGateZero); + AI.SelectNextCard(new int[] { CardId.Blackwing_ZephyrostheElite, CardId.Raider_Wing, CardId.Raidraptor_SingingLanius }); + return BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool Raidraptor_ArsenalFalconSummon() + { + if (!XyzModeCheck(true)) return false; + var materials_lists = Util.GetXyzMaterials(Bot.MonsterZone, 7, 2, false, + card => { return !card.IsCode(CardId.F_A_DawnDragster) && !card.IsCode(CardId.TheMightyMasterofMagic); }); + if (materials_lists.Count <= 0) return false; + AI.SelectMaterials(materials_lists[0]); + xyz_mode = true; + return BeforeResult(ExecutorType.Summon); + } + private bool Odd_EyesMeteorburstDragonCheck() + { + if (!XyzModeCheck()) return false; + var materials_lists = Util.GetXyzMaterials(Func.MergeList(new List() { Card }, + Func.GetZoneCards(Bot, CardLocation.MonsterZone | CardLocation.PendulumZone)), 7, 2, false, + card => { return !card.IsCode(CardId.F_A_DawnDragster) && !card.IsCode(CardId.TheMightyMasterofMagic); }); + if (materials_lists.Count <= 0) return false; + List pre_materials = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), SecretoftheYangZingCheck); + var materials_sy_lists = Util.GetSynchroMaterials(pre_materials, 7, 1, 1, false, true, null, card => { return !card.IsCode(CardId.MythicalBeastJackalKing) && !card.IsCode(CardId.HeraldoftheArcLight); }); + if (materials_sy_lists.Count <= 0) return false; + Odd_EyesMeteorburstDragon_materials.Clear(); + foreach (var materials in materials_sy_lists) + { + if (func.CardsCheckCount(materials, func.IsCode, CardId.SupremeKingGateZero) > 0) + { + Odd_EyesMeteorburstDragon_materials.AddRange(materials); + return true; + } + } + Odd_EyesMeteorburstDragon_materials.AddRange(materials_sy_lists[0]); + return true; + } + private bool Odd_EyesMeteorburstDragonSummon() + { + if (!Odd_EyesMeteorburstDragonCheck()) return false; + AI.SelectMaterials(Odd_EyesMeteorburstDragon_materials); + return BeforeResult(ExecutorType.Summon); + } + private bool Odd_EyesMeteorburstDragonEffect() + { + AI.SelectCard(CardId.SupremeKingGateZero); + return BeforeResult(ExecutorType.Activate); + } + private bool DDSavantKeplerSummon() + { + if (HasInDeck(CardId.DarkContractwiththGate)) + { + summoned = true; + return BeforeResult(ExecutorType.Summon); + } + return false; + } + // private void DebugCards(string msg, IList cards) + // { + //#if DEBUG + // Logger.DebugWriteLine(cards.Count + msg); + // foreach (var card in cards) + // { + // if (card == null) continue; + // NamedCard namedCard = NamedCard.Get(card.Id); + // if (namedCard == null) continue; + // Logger.DebugWriteLine(msg + namedCard.Name); + // } + //#endif + // } + private bool ServantofEndymionEffect_2() + { + if (Card.Location == CardLocation.SpellZone) return BeforeResult(ExecutorType.Activate); + return false; + } + private bool IsSpsummonPMonster(ClientCard card) + { + return IsZefraScaleAbove(card) || IsZefraScaleBelow(card) || card.Id == CardId.SupremeKingGateZero || card.Id == CardId.ServantofEndymion; + } + private int GetSpellActivateCount() + { + int count = 0; + if (!activate_DragonShrine && func.CardsCheckAny(Bot.Hand, func.IsCode, CardId.DragonShrine) && + (HasInDeck(CardId.FlameBeastoftheNekroz) || HasInDeck(CardId.DestrudotheLostDragon_Frisson) || HasInDeck(CardId.SupremeKingDragonDarkwurm))) ++count; + if (!activate_SpellPowerMastery && func.CardsCheckAny(Bot.Hand, func.IsCode, CardId.SpellPowerMastery) + && (HasInDeck(CardId.TheMightyMasterofMagic) || HasInDeck(CardId.ServantofEndymion))) ++count; + if (func.CardsCheckAny(Bot.Hand, func.IsCode, CardId.DarkContractwiththGate)) ++count; + if (!activate_ZefraProvidence && func.CardsCheckAny(Bot.Hand, func.IsCode, CardId.ZefraProvidence)) + { + if (func.CardsCheckCount(Bot.Hand, func.IsCode, CardId.OracleofZefra) <= 0 && !activate_OracleofZefra + && HasInDeck(CardId.OracleofZefra)) + { + count += 2; + } + else + { + ++count; + } + } + if (!activate_OracleofZefra && func.CardsCheckAny(Bot.Hand, func.IsCode, CardId.OracleofZefra)) ++count; + if (func.CardsCheckAny(Bot.Hand, func.IsCode, CardId.Terraforming) && HasInDeck(CardId.OracleofZefra)) ++count; + if (func.CardsCheckAny(Bot.Hand, func.IsCode, CardId.FoolishBurial)) ++count; + if (func.CardsCheckCount(Bot.Hand, func.HasType, CardType.Pendulum) > 1 && Bot.SpellZone[0] == null && + Bot.SpellZone[4] == null) ++count; + if (!summoned && Bot.HasInHand(CardId.DDSavantKepler) && HasInDeck(CardId.DarkContractwiththGate)) ++count; + return count; + } + private bool ServantofEndymionEffect_3() + { + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool ZefraDivineStrikeEffect() + { + if (Duel.LastChainPlayer == 0) return false; + AI.SelectCard(CardId.RitualBeastTamerZeframpilica, CardId.SatellarknightZefrathuban, CardId.StellarknightZefraxciton, CardId.FlameBeastoftheNekroz, CardId.ShaddollZefracore, + CardId.SecretoftheYangZing, CardId.Zefraxi_TreasureoftheYangZing); + return BeforeResult(ExecutorType.Activate); + } + private bool NinePillarsofYangZingEffect() + { + if (Duel.LastChainPlayer == 0) return false; + List cards = func.CardsIdToClientCards(new List { CardId.SecretoftheYangZing }, Bot.MonsterZone); + cards.AddRange(func.CardsIdToClientCards(new List { CardId.SecretoftheYangZing, CardId.Zefraxi_TreasureoftheYangZing }, Bot.SpellZone)); + AI.SelectCard(cards); + should_destory = true; + return BeforeResult(ExecutorType.Activate); + } + private bool IsActivateBlackwing_ZephyrostheElite() + { + return (Blackwing_ZephyrostheElite_activate || HeavymetalfoesElectrumite_activate) && Func.GetZoneCards(Bot, CardLocation.PendulumZone, true).Count <= 0; + } + private bool PendulumDefaultActivate() + { + return IsActivateBlackwing_ZephyrostheElite() || (checkPActivate() && IsActivateScale()); + } + private bool ServantofEndymionEffect() + { + if (PendulumActivate()) + { + if (IsActivateBlackwing_ZephyrostheElite()) return BeforeResult(ExecutorType.Activate); + if ((!HasInDeck(CardId.TheMightyMasterofMagic) && !HasInDeck(CardId.MythicalBeastJackalKing) || GetSpellActivateCount() < 2)) return false; + return BeforeResult(ExecutorType.Activate); + } + else if (Card.Location == CardLocation.SpellZone) + { + if (func.HasInZone(Bot, CardLocation.Hand | CardLocation.PendulumZone, CardId.Zefraath, true)) + { + return func.CardsCheckAny(Bot.Hand, IsSpsummonPMonster) && BeforeResult(ExecutorType.Activate); + } + return BeforeResult(ExecutorType.Activate); + } + else if (Card.Location == CardLocation.MonsterZone) return BeforeResult(ExecutorType.Activate); + else return false; + } + private bool IsZefraScaleAbove(ClientCard card) + { + return Func.IsCode(card, CardId.StellarknightZefraxciton, CardId.SecretoftheYangZing, CardId.FlameBeastoftheNekroz, CardId.ShaddollZefracore); + } + private bool IsZefraScaleBelow(ClientCard card) + { + return Func.IsCode(card, CardId.RitualBeastTamerZeframpilica, CardId.Zefraxi_TreasureoftheYangZing, CardId.SatellarknightZefrathuban); + } + private bool TerraformingEffect() + { + return Bot.HasInHand(CardId.OracleofZefra) && BeforeResult(ExecutorType.Activate); + } + private bool DDSavantKeplerEffect() + { + if (PendulumActivate()) return false; + return BeforeResult(ExecutorType.Activate); + } + private bool FoolishBurialEffect() + { + return BeforeResult(ExecutorType.Activate); + } + private List GetSynchroMaterials() + { + List materials = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), + card => { return !IsNoLinkCards(card) && !card.HasType(CardType.Link | CardType.Xyz); }); + return materials; + } + private bool DestrudotheLostDragon_FrissonEffect() + { + if (Bot.HasInExtra(CardId.CrystronHalqifibrax)) return BeforeResult(ExecutorType.Activate); + if (!Bot.HasInExtra(CardId.F_A_DawnDragster) && !Bot.HasInExtra(CardId.Odd_EyesMeteorburstDragon)) return false; + List pre_materials = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), card => { return SecretoftheYangZingCheck(card) && !IsNoLinkCards(card) && !card.HasType(CardType.Tuner) && card.Level > 0; }); + if (pre_materials.Count <= 0) return false; + List cards = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), card => + { + return !IsNoLinkCards(card) && card.Level > 0 && !card.HasType(CardType.Tuner); + }); + if (cards.Count <= 0) return false; + AI.SelectCard(cards); + return BeforeResult(ExecutorType.Activate); + } + private bool IsCanSynchroSummon(int level) + { + return func.CardsCheckAny(GetSynchroMaterials(), card => { + return (card.Level + level == 8 + && func.CardsCheckAny(Bot.ExtraDeck, synchro_card => { return Func.IsCode(synchro_card, CardId.BorreloadSavageDragon, CardId.PSY_FramelordOmega); })) + || (card.Level + level == 7 && SecretoftheYangZingCheck(card) && func.CardsCheckAny(Bot.ExtraDeck, synchro_card => { return Func.IsCode(synchro_card, CardId.Odd_EyesMeteorburstDragon, CardId.F_A_DawnDragster); })) + || (card.Level + level == 5 && Bot.HasInExtra(CardId.Denglong_FirstoftheYangZing)) + || (card.Level + level == 4 && Bot.HasInExtra(CardId.HeraldoftheArcLight)); + }); + } + private bool DDLamiaEffect() + { + if (Bot.HasInExtra(CardId.MechaPhantomBeastAuroradon) && Bot.GetMonstersInMainZone().Count >= 3) return false; + if (!Bot.HasInExtra(CardId.CrystronHalqifibrax) && !IsCanSynchroSummon(Card.Level)) return false; + AI.SelectCard(CardId.DarkContractwiththGate, CardId.DDSavantKepler); + activate_DDLamia = true; + return true; + } + private bool DragonShrineEffect() + { + return BeforeResult(ExecutorType.Activate); + } + private bool ZefraathEffect() + { + if (PendulumActivate()) return !activate_p_Zefraath || IsActivateBlackwing_ZephyrostheElite(); + if (Card.Location == CardLocation.SpellZone) + { + activate_p_Zefraath = true; + return BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool RitualBeastTamerZeframpilicaEffect() + { + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + return BeforeResult(ExecutorType.Activate); + } + private bool BorreloadSavageDragonSummon_2() + { + if (xyz_mode) return BorreloadSavageDragonSummon(); + return false; + } + private bool BorreloadSavageDragonSummon() + { + var materials_lists = Util.GetSynchroMaterials(Bot.MonsterZone, Card.Level, 1, 1, false, true, null, + card => { return !card.IsCode(CardId.F_A_DawnDragster) && !card.IsCode(CardId.TheMightyMasterofMagic) && !card.IsCode(CardId.HeraldoftheArcLight); }); + if (materials_lists.Count <= 0) return false; + foreach (var materials in materials_lists) + { + if (func.CardsCheckAny(materials, func.IsCode, CardId.MechaPhantomBeastToken)) + { + AI.SelectMaterials(materials); + return BeforeResult(ExecutorType.Summon); + } + } + AI.SelectMaterials(materials_lists[0]); + return BeforeResult(ExecutorType.Summon); + } + private bool BorreloadSavageDragonEffect() + { + /* + * effect1 bug: Unable to read card info in the func "OnselectCard" + * Unable to run in the "ActivateDescription == -1" + */ + AI.SelectCard(new[] + { + CardId.SaryujaSkullDread, + CardId.MechaPhantomBeastAuroradon, + CardId.HeavymetalfoesElectrumite, + CardId.CrystronHalqifibrax, + CardId.Raidraptor_WiseStrix + }); + return BeforeResult(ExecutorType.Activate); + } + private bool TheMightyMasterofMagicEffect() + { + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + else if (Card.Location == CardLocation.MonsterZone) + { + if (Duel.LastChainPlayer == 0) return false; + AI.SelectCard(CardId.ServantofEndymion, CardId.TheMightyMasterofMagic); + return BeforeResult(ExecutorType.Activate); + } + else + { + return BeforeResult(ExecutorType.Activate); + } + } + private bool checkPActivate() + { + if (p_summoned) return false; + if (func.HasInZone(Bot, CardLocation.PendulumZone, CardId.Zefraath, true)) return true; + if (Bot.HasInHand(CardId.Zefraath) && (Bot.SpellZone[0] != null || Bot.SpellZone[4] != null)) return false; + if (Bot.SpellZone[0] == null && Bot.SpellZone[4] == null) + { + if (!Bot.HasInHand(CardId.Zefraath) && !func.CardsCheckAny(Bot.Hand, card => { + return IsSpsummonPMonster(card) && +(Card.LScale >= 5 ? card.LScale < 5 : card.LScale > 5) && func.GetPSpSummonMonster(Bot, card, Card)?.Count > 0; + })) return false; + } + else + { + if (func.GetPSpSummonMonster(Bot, Bot.SpellZone[0], Card)?.Count <= 0 && func.GetPSpSummonMonster(Bot, Bot.SpellZone[4], Card)?.Count <= 0) return false; + } + + return true; + } + private bool SecretoftheYangZingEffect() + { + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + activate_SecretoftheYangZing = true; + return BeforeResult(ExecutorType.Activate); + } + private bool SatellarknightZefrathubanEffect() + { + + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool BorreloadSavageDragonEffect_2() + { + if (Duel.LastChainPlayer == 1) + { + ClientCard card = Util.GetLastChainCard(); + return card != null && !card.HasType(CardType.Continuous | CardType.Field) && card.HasType(CardType.Spell | CardType.Trap) && BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool Zefraxi_TreasureoftheYangZingEffect() + { + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + return BeforeResult(ExecutorType.Activate); + } + private bool OracleofZefraEffect() + { + activate_OracleofZefra = true; + return BeforeResult(ExecutorType.Activate); + + } + private bool FlameBeastoftheNekrozEffect() + { + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + else + { + return BeforeResult(ExecutorType.Activate); + } + + } + private bool AstrographSorcererEffect() + { + if (PendulumActivate()) return false; + return BeforeResult(ExecutorType.Activate); + } + private bool StellarknightZefraxcitonEffect() + { + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + else + { + return BeforeResult(ExecutorType.Activate); + } + } + private bool IsNoLinkCards(ClientCard card) + { + if (card == null) return false; + return ((card.IsCode(CardId.MythicalBeastJackalKing) || card.IsCode(CardId.TheMightyMasterofMagic)) && !card.IsDisabled()) + || card.IsCode(CardId.BorreloadSavageDragon) || card.IsCode(CardId.PSY_FramelordOmega) || card.IsCode(CardId.F_A_DawnDragster) + || card.IsCode(CardId.TruKingofAllCalamities) || card.IsCode(CardId.HeraldoftheArcLight) || card.LinkCount >= 3; + } + private bool LinkuribohSummon() + { + List materials = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), func.HasLevel, 1); + if (func.CardsCheckCount(materials, Func.NegateFunc(func.HasType), CardType.Tuner) <= 0 && + func.CardsCheckCount(materials, func.HasType, CardType.Tuner) <= 1) return false; + materials.Sort((cardA, cardB) => + { + if (cardA.HasType(CardType.Tuner) && !cardB.HasType(CardType.Tuner)) return 1; + if (!cardA.HasType(CardType.Tuner) && cardB.HasType(CardType.Tuner)) return -1; + return 0; + }); + AI.SelectMaterials(materials); + return true; + } + private bool SpellSet() + { + if (Card.HasType(CardType.Trap)) + { + AI.SelectPlace(Zones.z1 | Zones.z2 | Zones.z3 | Zones.z4 | Zones.z0); + return true; + } + return false; + } + private bool SpellSet_2() + { + if (Card.HasType(CardType.QuickPlay)) + { + AI.SelectPlace(Zones.z1 | Zones.z2 | Zones.z3 | Zones.z4 | Zones.z0); + return true; + } + return false; + } + private bool ShaddollZefracoreEffect() + { + if (PendulumActivate()) + { + return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + } + else + { + return BeforeResult(ExecutorType.Activate); + } + } + private bool PSY_FramelordOmegaEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + if (Duel.Player == 0) return BeforeResult(ExecutorType.Activate); + else + { + if (Bot.Banished.Count <= 0) return false; + AI.SelectCard(func.CardsIdToClientCards(new List { CardId.JetSynchron, CardId.DDLamia }, Bot.Banished)); + return BeforeResult(ExecutorType.Activate); + } + } + else + { + if (Bot.Graveyard.Count <= 0) return false; + AI.SelectCard(func.CardsIdToClientCards(new List { CardId.Zefraath, CardId.CrystronHalqifibrax, CardId.Denglong_FirstoftheYangZing, CardId.BorreloadSavageDragon, CardId.DDLamia }, Bot.Graveyard)); + return BeforeResult(ExecutorType.Activate); + } + } + private bool Psummon() + { + //if (ActivateDescription == P_SPSUMMON_DESC) + if (Card.Location == CardLocation.SpellZone) + { + p_summoning = true; + p_summoned = true; + return true; + } + return false; + } + private bool IsExtraZoneCard(ClientCard card) + { + if (card == null) return false; + ClientCard ex_card = Bot.MonsterZone[5]; + if (ex_card == card) return true; + ex_card = Bot.MonsterZone[6]; + if (ex_card == card) return true; + return false; + } + private bool HeavymetalfoesElectrumiteSummon() + { + if (Odd_EyesMeteorburstDragonCheck()) return false; + List materials = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), func.HasType, CardType.Pendulum); + if (materials.Count > 0) + { + materials.Sort((cardA, cardB) => + { + if ((cardA.Level == 3 || cardA.HasType(CardType.Tuner)) && cardB.Level != 3 && !cardB.HasType(CardType.Tuner)) return -1; + if (cardA.Level != 3 && !cardA.HasType(CardType.Tuner) && (cardB.Level == 3 || cardB.HasType(CardType.Tuner))) return 1; + return CardContainer.CompareCardLevel(cardA, cardB); + }); + materials.Reverse(); + List result = new List(); + foreach (var material in materials) + { + if (IsExtraZoneCard(material)) result.Insert(0, material); + else if (IsNoLinkCards(material) || (material.HasType(CardType.Tuner) && Bot.HasInExtra(CardId.CrystronHalqifibrax) + && func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), func.HasType, CardType.Tuner) <= 0)) continue; + else result.Add(material); + } + if (result.Count < 2) return false; + AI.SelectMaterials(result); + return BeforeResult(ExecutorType.Summon); + } + return false; + } + private bool SecretoftheYangZingCheck(ClientCard card) + { + if (card.IsCode(CardId.SecretoftheYangZing) && Bot.HasInHandOrInSpellZone(CardId.NinePillarsofYangZing)) + { + return func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.Hand | CardLocation.PendulumZone | CardLocation.MonsterZone, true), p_card => { + return p_card.HasSetcode(0xc4) && p_card.HasType(CardType.Pendulum); + }) <= 0; + } + return true; + } + private bool F_A_DawnDragsterSummon() + { + List pre_materials = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), SecretoftheYangZingCheck); + var materials_lists = Util.GetSynchroMaterials(pre_materials, 7, 1, 1, false, true, null, card => { return !card.IsCode(CardId.MythicalBeastJackalKing) && !card.IsCode(CardId.HeraldoftheArcLight); }); + if (materials_lists.Count <= 0) return false; + foreach (var materials in materials_lists) + { + if (func.CardsCheckCount(materials, card => + { + return card.HasType(CardType.Tuner) && card.HasRace(CardRace.Machine); + }) <= 0) + { + AI.SelectMaterials(materials); + return BeforeResult(ExecutorType.Summon); + } + } + AI.SelectMaterials(materials_lists[0]); + return BeforeResult(ExecutorType.Summon); + } + private bool CrystronHalqifibraxEffect() + { + return BeforeResult(ExecutorType.Activate); + } + private bool MechaPhantomBeastAuroradonSummon() + { + if (Bot.GetMonstersInMainZone().Count >= 4 || (!HasInDeck(CardId.MechaPhantomBeastO_Lion) && !IsCanSPSummonTunerLevel1() + && !func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.MonsterZone | CardLocation.Grave, true), func.IsCode, CardId.Deskbot001))) return false; + if (XyzModeCheck()) + { + List pre_materials = new List(); + List key_materials = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.Grave), card => { + return (card.IsCode(CardId.DDLamia) && !activate_DDLamia && func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.Onfield | CardLocation.Hand, true), scard => + { return Func.HasSetCode(scard, 0xaf, 0xae) && scard.Id != CardId.DDLamia; }) > 0); + }); + List key_materials_2 = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.Grave), card => { return card.IsCode(CardId.JetSynchron) && !activate_JetSynchron; }); + pre_materials.AddRange(key_materials); + pre_materials.AddRange(key_materials_2); + if (!summoned) pre_materials.AddRange(func.CardsCheckWhere(Bot.Hand, card => { return !card.IsCode(CardId.DestrudotheLostDragon_Frisson) && card.Level < 5; })); + pre_materials.AddRange(Bot.MonsterZone); + var synchro_materials_lists = Util.GetSynchroMaterials(pre_materials, 7, 1, 1, false, true, null, card => { return !card.IsCode(CardId.MythicalBeastJackalKing); }); + var xyz_materials_lists = Util.GetXyzMaterials(Func.GetZoneCards(Bot, CardLocation.MonsterZone | CardLocation.PendulumZone), 7, 1, false, + card => { return !card.IsCode(CardId.F_A_DawnDragster) && !card.IsCode(CardId.TheMightyMasterofMagic); }); + var xyz_materials_lists_2 = Util.GetXyzMaterials(Func.GetZoneCards(Bot, CardLocation.MonsterZone), 7, 2, false, + card => { return !card.IsCode(CardId.F_A_DawnDragster) && !card.IsCode(CardId.TheMightyMasterofMagic); }); + if ((synchro_materials_lists.Count > 0 && xyz_materials_lists.Count > 0) || xyz_materials_lists_2.Count > 0) return false; + } + List m = new List(); + int link_count = 0; + List cards = Bot.GetMonsters(); + cards.Sort(CardContainer.CompareCardLink); + cards.Reverse(); + foreach (var card in Bot.GetMonsters()) + { + if (card == null) continue; + if (card.IsFacedown() || !card.HasRace(CardRace.Machine) || IsNoLinkCards(card)) continue; + m.Add(card); + link_count += (card.HasType(CardType.Link)) ? card.LinkCount : 1; + if (link_count >= 3) break; + } + if (link_count < 3) return false; + AI.SelectMaterials(m); + return true; + } + private bool SaryujaSkullDreadEffect() + { + if (ActivateDescription == Util.GetStringId(CardId.SaryujaSkullDread, 2)) + { + AI.SelectCard(GetSendToDeckIds()); + return BeforeResult(ExecutorType.Activate); + } + return BeforeResult(ExecutorType.Activate); + } + private bool SaryujaSkullDreadSummon() + { + if (Bot.GetMonstersInMainZone().Count < 4 || (!Bot.HasInExtra(CardId.CrystronHalqifibrax) && !xyz_mode)) return false; + List materials = new List(); + int link_count = 0; + int materials_count = 0; + int tuner_count = func.CardsCheckCount(Bot.MonsterZone, func.HasType, CardType.Tuner); + List temp_materials = Bot.GetMonsters(); + temp_materials.Sort((cardA, cardB) => + { + if ((cardA.HasType(CardType.Tuner) && cardB.HasType(CardType.Tuner)) + || (!cardA.HasType(CardType.Tuner) && !cardB.HasType(CardType.Tuner))) + { + return CardContainer.CompareCardLevel(cardA, cardB); + } + else if (cardA.HasType(CardType.Tuner) && !cardB.HasType(CardType.Tuner)) return 1; + return -1; + }); + foreach (var material in temp_materials) + { + ++materials_count; + if (IsExtraZoneCard(material)) materials.Insert(0, material); + else if (IsNoLinkCards(material)) { --materials_count; continue; } + else materials.Add(material); + link_count += material.HasType(CardType.Link) ? material.LinkCount : 1; + if (link_count >= 4) + { + if (materials_count == 3 && Bot.Deck.Count > 4 && ((func.CardsCheckCount(Bot.Hand, func.HasType, CardType.Tuner) > 0 + || (Bot.HasInMonstersZone(CardId.DDLamia, false, false, true) && !activate_DDLamia && func.CardsCheckCount(Func.GetZoneCards + (Bot, CardLocation.Onfield | CardLocation.Hand, true), card => { return Func.HasSetCode(card, 0xaf, 0xae) && card.Id != CardId.DDLamia; }) + > 0) || (Bot.HasInMonstersZone(CardId.JetSynchron, false, false, true) && !activate_JetSynchron)) || xyz_mode)) + { + --link_count; + continue; + } + break; + } + } + if (materials.Count < 3) return false; + AI.SelectMaterials(materials); + return BeforeResult(ExecutorType.Summon); + } + private bool CrystronHalqifibraxSummon() + { + List materials = new List(); + if (Bot.HasInExtra(CardId.MechaPhantomBeastAuroradon)) + { + materials.Add(Bot.MonsterZone[5]); + materials.Add(Bot.MonsterZone[6]); + } + List mainMonsters = Bot.GetMonstersInMainZone(); + mainMonsters.Sort(CardContainer.CompareCardAttack); + materials.AddRange(mainMonsters); + AI.SelectMaterials(materials); + // [YGOL] TICKET-349 + return true; + } + private bool PendulumActivate() + { + return Func.PendulumActivate(ActivateDescription, Card); + } + private bool IsActivateScale() + { + return func.IsActivateScale(Bot, Card); + } + private bool SpellActivate() + { + return Func.SpellActivate(Card); + } + private bool SupremeKingGateZeroEffect() + { + if (PendulumActivate()) return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + return false; + } + private bool MythicalBeastJackalKingEffect() + { + if (PendulumActivate()) return PendulumDefaultActivate() && BeforeResult(ExecutorType.Activate); + return BeforeResult(ExecutorType.Activate); + } + private bool Denglong_FirstoftheYangZingSummon_2() + { + if (xyz_mode) return Denglong_FirstoftheYangZingSummon(); + return false; + } + private bool Denglong_FirstoftheYangZingSummon() + { + var materials_lists = Util.GetSynchroMaterials(Bot.MonsterZone, 5, 1, 1, false, true, null, + card => { return !card.IsCode(CardId.HeraldoftheArcLight); }); + if (materials_lists.Count <= 0) return false; + AI.SelectMaterials(materials_lists[0]); + return BeforeResult(ExecutorType.Summon); + } + private bool Denglong_FirstoftheYangZingEffect() + { + if (ActivateDescription == Util.GetStringId(CardId.Denglong_FirstoftheYangZing, 1)) return false; + if (Card.Location == CardLocation.MonsterZone) + { + AI.SelectCard(CardId.NinePillarsofYangZing, CardId.SecretoftheYangZing, CardId.Zefraxi_TreasureoftheYangZing); + } + else + { + AI.SelectCard(CardId.SecretoftheYangZing, CardId.Zefraxi_TreasureoftheYangZing, CardId.LightoftheYangZing); + } + return true; + } + private bool DarkContractwiththGateEffect() + { + if (SpellActivate()) + { + return (HasInDeck(CardId.DDLamia) || func.HasInZone(Bot, CardLocation.PendulumZone, CardId.ServantofEndymion, true, true)) && BeforeResult(ExecutorType.Activate); + } + return BeforeResult(ExecutorType.Activate); + } + private int DisabledSort(ClientCard cardA, ClientCard cardB) + { + bool RitualBeastTamerZeframpilica_flag = !summoned && Bot.HasInExtra(CardId.HeraldoftheArcLight) && IsCanSPSummonTunerLevel1(); + if (((cardA.IsCode(CardId.RitualBeastTamerZeframpilica) && RitualBeastTamerZeframpilica_flag) || Func.IsCode(cardA, CardId.MaxxC, CardId.Zefraath, CardId.MythicalBeastJackalKing, CardId.TheMightyMasterofMagic) || cardA.HasType(CardType.Trap) || cardA.HasType(CardType.Tuner)) + && !cardB.IsCode(CardId.RitualBeastTamerZeframpilica) && !cardB.HasType(CardType.Trap) && !Func.IsCode(cardB, CardId.MaxxC, CardId.Zefraath, CardId.MythicalBeastJackalKing, CardId.TheMightyMasterofMagic) && !cardB.HasType(CardType.Tuner)) return 1; + else if (!cardA.IsCode(CardId.RitualBeastTamerZeframpilica) && !cardA.HasType(CardType.Trap) && !Func.IsCode(cardA, CardId.MaxxC, CardId.Zefraath, CardId.MythicalBeastJackalKing, CardId.TheMightyMasterofMagic) && !cardA.HasType(CardType.Tuner) + && ((cardB.IsCode(CardId.RitualBeastTamerZeframpilica) && RitualBeastTamerZeframpilica_flag) || Func.IsCode(cardB, CardId.MaxxC, CardId.Zefraath, CardId.MythicalBeastJackalKing, CardId.TheMightyMasterofMagic) || cardB.HasType(CardType.Trap) || cardB.HasType(CardType.Tuner))) return -1; + return 0; + } + private List GetDisabledIds() + { + List ids = new List(); + ids.Add(CardId.DestrudotheLostDragon_Frisson); + ids.Add(CardId.Blackwing_ZephyrostheElite); + ids.Add(CardId.Raider_Wing); + ids.Add(CardId.Raidraptor_SingingLanius); + ids.Add(CardId.PSY_FrameDriver); + if (!Bot.HasInGraveyard(CardId.Raidraptor_ArsenalFalcon) || !Bot.HasInExtra(CardId.TruKingofAllCalamities)) ids.Add(CardId.Rank_Up_MagicSoulShaveForce); + if (Bot.HasInBanished(CardId.PSY_FrameDriver)) ids.Add(CardId.PSY_FramegearGamma); + ids.Add(CardId.LightoftheYangZing); + ids.Add(CardId.DDLamia); + ids.AddRange(Func.GetCardsRepeatCardsId(Bot.Hand)); + List hands = Func.GetZoneCards(Bot, CardLocation.Hand); + hands.Sort(DisabledSort); + List hand_ids = Func.ClientCardsToCardsId(hands, true); + ids.AddRange(hand_ids); + return ids; + } + private List GetSendToDeckIds() + { + List ids = new List(); + List repeat_ids = Func.GetCardsRepeatCardsId(Func.GetZoneCards(Bot, CardLocation.Hand)); + ids.Add(CardId.MechaPhantomBeastO_Lion); + ids.AddRange(repeat_ids); + ids.Add(CardId.Raidraptor_SingingLanius); + ids.Add(CardId.Raider_Wing); + ids.Add(CardId.Blackwing_ZephyrostheElite); + ids.Add(CardId.PSY_FrameDriver); + ids.Add(CardId.LightoftheYangZing); + ids.Add(CardId.Rank_Up_MagicSoulShaveForce); + if (activate_ZefraProvidence) ids.Add(CardId.ZefraProvidence); + if (activate_OracleofZefra) ids.Add(CardId.OracleofZefra); + if (activate_DragonShrine) ids.Add(CardId.DragonShrine); + if (activate_SpellPowerMastery) ids.Add(CardId.SpellPowerMastery); + List hands = Func.GetZoneCards(Bot, CardLocation.Hand); + hands.Sort(DisabledSort); + List hand_ids = Func.ClientCardsToCardsId(hands, true); + ids.AddRange(hand_ids); + return ids; + } + private bool TruKingofAllCalamitiesEffect() + { + if (Duel.Player == 1) + { + AI.SelectAttributes(new CardAttribute[] { CardAttribute.Divine }); + return BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool JetSynchronEffect() + { + + if (Card.Location == CardLocation.Grave) + { + if (!IsCanSynchroSummon(Card.Level)) return false; + if (func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.Extra), card => { return card.HasType(CardType.Synchro) || Func.IsCode(card, CardId.CrystronHalqifibrax, CardId.Linkuriboh); })) + { + activate_JetSynchron = true; + List dcards = func.CardsIdToClientCards(GetDisabledIds(), Bot.Hand); + if (!Bot.HasInExtra(CardId.CrystronHalqifibrax) && dcards.Count <= 0) return false; + AI.SelectCard(dcards); + return BeforeResult(ExecutorType.Activate); + } + } + return false; + } + private bool MechaPhantomBeastAuroradonEffect() + { + if (ActivateDescription == -1) { link_summoned = true; return true; } + else + { + if (!HasInDeck(CardId.MechaPhantomBeastO_Lion) + && Func.GetZoneCards(Enemy, CardLocation.Onfield).Count <= 0) return false; + List tRelease = new List(); + List nRelease = new List(); + foreach (var card in Bot.GetMonsters()) + { + if (card == null || IsNoLinkCards(card)) continue; + if (card.Id == CardId.MechaPhantomBeastToken) tRelease.Add(card); else nRelease.Add(card); + } + int count = tRelease.Count() + nRelease.Count(); + opt_0 = false; + opt_1 = false; + opt_2 = false; + if (count >= 3 && func.CardsCheckCount(Bot.Graveyard, func.HasType, CardType.Trap) > 0) opt_2 = true; + if (count >= 2 && CheckRemainInDeck(CardId.MechaPhantomBeastO_Lion) > 0) opt_1 = true; + if (count >= 1 && Func.GetZoneCards(Enemy, CardLocation.Onfield).Count > 0) opt_0 = true; + if (!opt_0 && !opt_1 && !opt_2) return false; + return true; + } + } + private bool SupremeKingDragonDarkwurmEffect() + { + if (Card.Location == CardLocation.Grave) + { + activate_SupremeKingDragonDarkwurm_1 = true; + return BeforeResult(ExecutorType.Activate); + } + if (Card.Location == CardLocation.MonsterZone) + { + activate_SupremeKingDragonDarkwurm_2 = true; + return BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool SupremeKingDragonDarkwurmSummon() + { + if ((!activate_p_Zefraath && Bot.HasInHand(CardId.Zefraath) && !activate_SupremeKingDragonDarkwurm_1 && HasInDeck(CardId.SupremeKingGateZero) && func.CardsCheckAny(Bot.Hand, func.HasType, CardType.Tuner)) + || (func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.Hand), card => { return card.LinkCount > 5; }) && + !Bot.HasInHand(CardId.SupremeKingGateZero) && !activate_SupremeKingDragonDarkwurm_2)) + { + summoned = true; + return BeforeResult(ExecutorType.Summon); + } + return false; + } + private bool DefaultSummon_2() + { + if (Card.Location == CardLocation.Hand && Card.Level <= 4 + && Bot.HasInExtra(CardId.CrystronHalqifibrax) && (func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), card => { return Card.HasType(CardType.Tuner) ? true : card.HasType(CardType.Tuner); }))) + { + summoned = true; + return BeforeResult(ExecutorType.Summon); + } + return false; + } + private bool IsCanSPSummonTunerLevel1() + { + return func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.MonsterZone | CardLocation.Grave, true), card => { + return (card.IsCode(CardId.DDLamia) && !activate_DDLamia && func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.Onfield | CardLocation.Hand, true), scard => { return Func.HasSetCode(scard, 0xaf, 0xae) && scard.Id != CardId.DDLamia; }) + > 0) || (card.IsCode(CardId.JetSynchron) && !activate_JetSynchron) && Bot.GetMonstersInMainZone().Count <= 3; + }); + } + private bool DefaultSummon() + { + if (Card.Level > 4) return false; + if ((!link_summoned && Bot.HasInExtra(CardId.HeavymetalfoesElectrumite) && func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), func.HasType, CardType.Pendulum) > 0 + && Card.HasType(CardType.Pendulum)) + || (IsCanSPSummonTunerLevel1() && ((Card.Level == 3 && Bot.HasInExtra(CardId.HeraldoftheArcLight)) || ( + Card.Level == 4 && Bot.HasInExtra(CardId.Denglong_FirstoftheYangZing)))) || + (Card.Id == CardId.SupremeKingDragonDarkwurm && !activate_SupremeKingDragonDarkwurm_2) + || (Bot.HasInExtra(CardId.CrystronHalqifibrax) && Bot.HasInHandOrInGraveyard(CardId.DestrudotheLostDragon_Frisson) && !activate_DestrudotheLostDragon_Frisson)) + { + summoned = true; + return BeforeResult(ExecutorType.Summon); + } + return false; + } + private bool OneforOneEffect() + { + AI.SelectCard(GetDisabledIds()); + AI.SelectNextCard(CardId.JetSynchron, CardId.LightoftheYangZing, CardId.DDLamia); + return BeforeResult(ExecutorType.Activate); + } + private void HeavymetalfoesElectrumiteAddIds(List ids) + { + if (!summoned && HasInDeck(CardId.DarkContractwiththGate) && HasInDeck(CardId.DDLamia)) + { + if (!func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), func.HasType, CardType.Tuner)) + { + ids.Add(CardId.DDSavantKepler); + } + else + { + ids.Add(CardId.AstrographSorcerer); + ids.Add(CardId.DDSavantKepler); + } + } + ids.Add(CardId.AstrographSorcerer); + ids.Add(CardId.FlameBeastoftheNekroz); + ids.Add(CardId.DDSavantKepler); + } + private bool LinkuribohEffect() + { + if (Card.Location == CardLocation.Grave) + { + if (Duel.Player != 0) return BeforeResult(ExecutorType.Activate); + return false; + } + return BeforeResult(ExecutorType.Activate); + } + private bool Raider_WingEffect() + { + if (!Bot.HasInMonstersZone(CardId.Raidraptor_ForceStrix, false, true, true)) return false; + AI.SelectCard(CardId.Raidraptor_ForceStrix); + return BeforeResult(ExecutorType.Activate); + } + private bool HeavymetalfoesElectrumiteEffect() + { + if (ActivateDescription != -1) + { + List cards = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.SpellZone, true), Func.NegateFunc(func.IsCode), CardId.DarkContractwiththGate); + if (cards.Count <= 0) + { + HeavymetalfoesElectrumite_activate = true; + return false; + } + HeavymetalfoesElectrumite_activate = false; + return BeforeResult(ExecutorType.Activate); + } + return BeforeResult(ExecutorType.Activate); + } + public override bool OnSelectHand() + { + return true; + } + private bool ResetFlag() + { + should_destory = false; + return true; + } + private bool HeraldoftheArcLightEffect() + { + if (Card.Location == CardLocation.MonsterZone) + { + return Duel.LastChainPlayer != 0 && BeforeResult(ExecutorType.Activate); + } + return false; + } + private bool CalledbytheGraveEffect() + { + if ((Bot.SpellZone[5] == Card || Bot.SpellZone[0] == Card) && Duel.Player == 0) return BeforeResult(ExecutorType.Activate); + ClientCard card = Util.GetLastChainCard(); + if (card == null) return false; + int id = card.Id; + List g_cards = func.CardsCheckWhere(Enemy.Graveyard, func.IsCode, id); + if (Duel.LastChainPlayer != 0) + { + if (card.Location == CardLocation.Grave && card.HasType(CardType.Monster)) + { + AI.SelectCard(card); + return BeforeResult(ExecutorType.Activate); + } + else if (g_cards.Count() > 0 && card.HasType(CardType.Monster)) + { + AI.SelectCard(g_cards); + return BeforeResult(ExecutorType.Activate); + } + } + return false; + } + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + NamedCard card = NamedCard.Get(cardId); + if (cardId == CardId.F_A_DawnDragster && Duel.Turn > 1) return CardPosition.FaceUpAttack; + if (card.Attack <= 1000) return CardPosition.FaceUpDefence; + return base.OnSelectPosition(cardId, positions); + } + public override int OnSelectOption(IList options) + { + if (options.Contains(Util.GetStringId(CardId.MechaPhantomBeastAuroradon, 3))) + { + if (opt_1) return options.IndexOf(Util.GetStringId(CardId.MechaPhantomBeastAuroradon, 3)); + else if (opt_0) return 0; + return options[options.Count - 1]; + } + return base.OnSelectOption(options); + } + + public override int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + NamedCard card = NamedCard.Get(cardId); + if (player == 0) + { + if (location == CardLocation.SpellZone) + { + if (card.HasType(CardType.Pendulum)) + { + if ((available & Zones.z4) > 0) return Zones.z4; + if ((available & Zones.z0) > 0) return Zones.z0; + } + else + { + List keys = new List() { 1, 2, 3 }; + while (keys.Count > 0) + { + int index = Program.Rand.Next(keys.Count); + int key = keys[index]; + int zone = 1 << key; + if ((zone & available) > 0) return zone; + keys.Remove(key); + } + } + } + else if (location == CardLocation.MonsterZone) + { + if (card.HasType(CardType.Link)) + { + if ((available & Zones.z5) > 0) return Zones.z5; + if ((available & Zones.z6) > 0) return Zones.z6; + } + } + } + + return base.OnSelectPlace(cardId, player, location, available); + } + private IList _OnSelectPendulumSummon(IList cards, int min, int max) + { + List ids = func.GetSelectCardIdList(); + List result = func.GetSelectCardList(); + List exs = func.CardsCheckWhere(cards, func.IsLocation, CardLocation.Extra); + List hs = func.CardsCheckWhere(cards, Func.NegateFunc(func.IsLocation), CardLocation.Extra); + if (func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.PendulumZone, true), card => { + return card.HasSetcode(0xc4) && !card.IsCode(CardId.Zefraath); + }) && func.CardsCheckAny(exs, func.IsCode, CardId.ShaddollZefracore)) ids.Add(CardId.ShaddollZefracore); + result = func.CardsIdToClientCards(ids, cards); + List temp_cards = func.CardsCheckWhere(cards, Func.NegateFunc(func.IsCode), CardId.MaxxC); + result.AddRange(temp_cards); + if (result.Count <= 0) return Func.CheckSelectCount(Util, result, cards, min, min); + if (result[0] != null && result[0].Location != CardLocation.Extra) ++p_count; + return Func.CheckSelectCount(Util, result, cards, max, max); + } + + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + if (AI.HaveSelectedCards()) return null; + List ids = func.GetSelectCardIdList(); + List result = func.GetSelectCardList(); + if (hint == HintMsg.AddToHand) + { + if (func.CardsCheckAny(cards, card => { return card.Location == CardLocation.Deck && card.HasSetcode(0xc4); })) + { + if (!activate_ZefraProvidence) ids.Add(CardId.ZefraProvidence); + if (p_summoned) + { + if (!summoned && Bot.HasInExtra(CardId.HeavymetalfoesElectrumite) && func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.MonsterZone, true), func.HasType, CardType.Pendulum) == 1) + { + List pre_ids = new List {CardId.Zefraxi_TreasureoftheYangZing,CardId.StellarknightZefraxciton,CardId.RitualBeastTamerZeframpilica,CardId.NinePillarsofYangZing + ,CardId.StellarknightZefraxciton,CardId.ShaddollZefracore}; + ids.AddRange(pre_ids); + } + ids.Add(CardId.ZefraDivineStrike); + } + if (!activate_OracleofZefra) ids.Add(CardId.OracleofZefra); + if (!activate_p_Zefraath && !func.HasInZone(Bot, CardLocation.Hand | CardLocation.PendulumZone, CardId.Zefraath, true)) ids.Add(CardId.Zefraath); + if (func.HasInZone(Bot, CardLocation.Hand | CardLocation.PendulumZone, CardId.SupremeKingGateZero, true) && !func.CardsCheckAny(Bot.Hand, func.HasType, CardType.Tuner) + && !Bot.HasInHand(CardId.Zefraxi_TreasureoftheYangZing)) ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + List pMonsters = func.CardsCheckWhere(Func.GetZoneCards(Bot, CardLocation.Hand), card => + { + return card.HasType(CardType.Pendulum) && !card.IsCode(CardId.Zefraath); + }); + if (pMonsters.Count > 0) + { + List zefraPMonsters = func.CardsCheckWhere(pMonsters, func.HasSetCode, 0xc4); + if (zefraPMonsters.Count > 0) + { + zefraPMonsters.Sort(Func.CompareCardScale); + int minScale = zefraPMonsters[0].RScale; + if (Bot.HasInHand(CardId.Zefraath)) + { + if (minScale < 5) + { + if (func.CardsCheckCount(cards, IsZefraScaleAbove) > 1) + { + ids.Add(CardId.ShaddollZefracore); + if (!Bot.HasInHand(CardId.Zefraxi_TreasureoftheYangZing)) ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + ids.Add(CardId.SecretoftheYangZing); + ids.Add(CardId.FlameBeastoftheNekroz); + ids.Add(CardId.StellarknightZefraxciton); + ids.Add(CardId.SatellarknightZefrathuban); + ids.Add(CardId.RitualBeastTamerZeframpilica); + } + else + { + ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + ids.Add(CardId.RitualBeastTamerZeframpilica); + ids.Add(CardId.SatellarknightZefrathuban); + } + } + else + { + if (func.CardsCheckCount(cards, IsZefraScaleBelow) > 1) + { + ids.Add(CardId.ShaddollZefracore); + if (!Bot.HasInHand(CardId.Zefraxi_TreasureoftheYangZing)) ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + ids.Add(CardId.SecretoftheYangZing); + ids.Add(CardId.FlameBeastoftheNekroz); + ids.Add(CardId.StellarknightZefraxciton); + ids.Add(CardId.SatellarknightZefrathuban); + ids.Add(CardId.RitualBeastTamerZeframpilica); + } + else + { + ids.Add(CardId.StellarknightZefraxciton); + ids.Add(CardId.SecretoftheYangZing); + ids.Add(CardId.FlameBeastoftheNekroz); + ids.Add(CardId.ShaddollZefracore); + } + } + } + else + { + if (Bot.HasInGraveyard(CardId.FlameBeastoftheNekroz)) ids.Add(CardId.RitualBeastTamerZeframpilica); + ids.Add(CardId.SecretoftheYangZing); + ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + } + } + else + { + ids.Add(CardId.SecretoftheYangZing); + ids.Add(CardId.FlameBeastoftheNekroz); + ids.Add(CardId.StellarknightZefraxciton); + ids.Add(CardId.SatellarknightZefrathuban); + ids.Add(CardId.RitualBeastTamerZeframpilica); + ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + } + } + else + { + if (func.HasInZone(Bot, CardLocation.Hand | CardLocation.PendulumZone, CardId.Zefraath, true) && + !activate_p_Zefraath) + { + ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + ids.Add(CardId.SatellarknightZefrathuban); + ids.Add(CardId.RitualBeastTamerZeframpilica); + } + ids.Add(CardId.SecretoftheYangZing); + ids.Add(CardId.FlameBeastoftheNekroz); + ids.Add(CardId.StellarknightZefraxciton); + ids.Add(CardId.SatellarknightZefrathuban); + ids.Add(CardId.RitualBeastTamerZeframpilica); + ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + } + result = func.CardsIdToClientCards(ids, cards); + } + else if (func.CardsCheckALL(cards, func.IsLocation, true, CardLocation.Extra)) + { + HeavymetalfoesElectrumiteAddIds(ids); + result = func.CardsIdToClientCards(ids, cards); + } + else if (func.CardsCheckALL(cards, func.HasSetCode, true, 0x12a)) + { + if (!func.HasInZone(Bot, CardLocation.PendulumZone | CardLocation.Hand, CardId.ServantofEndymion, true) || + (func.HasInZone(Bot, CardLocation.PendulumZone | CardLocation.Hand, CardId.ServantofEndymion, true) && (!HasInDeck(CardId.TheMightyMasterofMagic) || !HasInDeck(CardId.MythicalBeastJackalKing)))) ids.Add(CardId.ServantofEndymion); + ids.Add(CardId.TheMightyMasterofMagic); + ids.Add(CardId.MythicalBeastJackalKing); + result = func.CardsIdToClientCards(ids, cards); + } + else if (func.CardsCheckALL(cards, func.HasSetCode, true, 0xaf)) + { + ids.Add(CardId.DDLamia); + ids.Add(CardId.DDSavantKepler); + result = func.CardsIdToClientCards(ids, cards); + } + } + else if (hint == HintMsg.ToDeck && func.CardsCheckALL(cards, func.IsLocation, true, CardLocation.Hand) && min == 3 && max == 3) + { + result = func.CardsIdToClientCards(GetSendToDeckIds(), cards); + } + else if (hint == HintMsg.ToGrave && func.CardsCheckALL(cards, func.IsLocation, true, CardLocation.Deck)) + { + List extra_ids = CheckShouldSpsummonExtraMonster(); + //if (func.CardsCheckAny(cards, Func.HasRace, CardRace.Dragon)) + if (extra_ids.Count <= 0) + { + if (!activate_SupremeKingDragonDarkwurm_2 && Bot.GetMonsterCount() <= 0) ids.Add(CardId.SupremeKingDragonDarkwurm); + if (!activate_DestrudotheLostDragon_Frisson) ids.Add(CardId.DestrudotheLostDragon_Frisson); + if (!activate_JetSynchron) ids.Add(CardId.JetSynchron); + ids.Add(CardId.FlameBeastoftheNekroz); + } + else if (extra_ids.Count > 1) + { + if (Bot.GetMonsterCount() <= 0 && !activate_SupremeKingDragonDarkwurm_2) ids.Add(CardId.SupremeKingDragonDarkwurm); + if (func.CardsCheckAny(Bot.Hand, card => { return card.Level < 7 && card.HasType(CardType.Monster); })) ids.Add(CardId.DestrudotheLostDragon_Frisson); + if (Bot.GetHandCount() > 0) ids.Add(CardId.JetSynchron); + if (!summoned && Bot.HasInHand(CardId.RitualBeastTamerZeframpilica)) ids.Add(CardId.FlameBeastoftheNekroz); + ids.Add(CardId.DestrudotheLostDragon_Frisson); + ids.Add(CardId.JetSynchron); + ids.Add(CardId.SupremeKingDragonDarkwurm); + ids.Add(CardId.FlameBeastoftheNekroz); + } + else if (extra_ids.Contains(CardId.HeavymetalfoesElectrumite)) + { + if (Bot.GetMonsterCount() <= 0 && !activate_SupremeKingDragonDarkwurm_2) ids.Add(CardId.SupremeKingDragonDarkwurm); + if (!summoned && Bot.HasInHand(CardId.RitualBeastTamerZeframpilica)) ids.Add(CardId.FlameBeastoftheNekroz); + //if (!summoned && func.CardsCheckAny(Bot.Hand, card => { return card.Level < 7 && card.HasType(CardType.Monster); })) ids.Add(CardId.DestrudotheLostDragon_Frisson); + //if (Bot.GetHandCount() > 0) ids.Add(CardId.JetSynchron); + ids.Add(CardId.DestrudotheLostDragon_Frisson); + ids.Add(CardId.JetSynchron); + ids.Add(CardId.SupremeKingDragonDarkwurm); + ids.Add(CardId.FlameBeastoftheNekroz); + } + else if (extra_ids.Contains(CardId.CrystronHalqifibrax)) + { + if (func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.Hand | CardLocation.MonsterZone, true), func.HasType, CardType.Tuner)) + { + if (Bot.GetMonsterCount() <= 0 && !activate_SupremeKingDragonDarkwurm_2) ids.Add(CardId.SupremeKingDragonDarkwurm); + ids.Add(CardId.DestrudotheLostDragon_Frisson); + ids.Add(CardId.JetSynchron); + ids.Add(CardId.SupremeKingDragonDarkwurm); + ids.Add(CardId.FlameBeastoftheNekroz); + } + else + { + ids.Add(CardId.DestrudotheLostDragon_Frisson); + ids.Add(CardId.JetSynchron); + ids.Add(CardId.SupremeKingDragonDarkwurm); + ids.Add(CardId.FlameBeastoftheNekroz); + + } + } + result = func.CardsIdToClientCards(ids, cards); + } + else if (hint == Util.GetStringId(CardId.Zefraath, 1)) + { + int[] pScales = Func.GetPScales(Bot); + int rScale = pScales[0]; + int lScale = pScales[1]; + int pScale = (rScale != 5) ? rScale : lScale; + if (pScale < 5) + { + if (!activate_SecretoftheYangZing && !func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.Hand | CardLocation.Extra, true), func.IsCode, CardId.SecretoftheYangZing)) ids.Add(CardId.SecretoftheYangZing); + if (!activate_ShaddollZefracore && func.CardsCheckAny(Func.GetZoneCards(Bot, CardLocation.PendulumZone, true), card => { return !card.IsCode(CardId.Zefraath) && card.HasSetcode(0xc4); })) ids.Add(CardId.ShaddollZefracore); + ids.Add(CardId.StellarknightZefraxciton); + ids.Add(CardId.SecretoftheYangZing); + ids.Add(CardId.ShaddollZefracore); + } + else + { + ids.Add(CardId.Zefraxi_TreasureoftheYangZing); + ids.Add(CardId.SatellarknightZefrathuban); + ids.Add(CardId.RitualBeastTamerZeframpilica); + } + result = func.CardsIdToClientCards(ids, cards); + } + else if (hint == Util.GetStringId(CardId.HeavymetalfoesElectrumite, 3)) + { + HeavymetalfoesElectrumiteAddIds(ids); + result = func.CardsIdToClientCards(ids, cards); + } + else if (!(IS_YGOPRO & !(hint == HintMsg.SpSummon)) && func.CardsCheckALL(cards, card => { + return card.IsCode(CardId.TheMightyMasterofMagic) || card.IsCode(CardId.MythicalBeastJackalKing); + }, true)) + { + ids.Add(CardId.MythicalBeastJackalKing); + ids.Add(CardId.TheMightyMasterofMagic); + result = func.CardsIdToClientCards(ids, cards); + } + else if (p_summoning || ((Card == Bot.SpellZone[0] || Card == Bot.SpellZone[4]) && hint == HintMsg.SpSummon && + Card.HasType(CardType.Pendulum))) + { + p_summoning = false; + if (p_count >= 3 && !Bot.HasInExtra(CardId.SaryujaSkullDread) && Bot.HasInExtra(CardId.MechaPhantomBeastAuroradon)) return Func.CheckSelectCount(Util, result, cards, min, min); + return _OnSelectPendulumSummon(cards, min, max); + } + else if (hint == HintMsg.Destroy) + { + if (func.CardsCheckALL(cards, card => { return card.Controller == 0 && card.IsFaceup(); }, true)) + { + should_destory = true; + if (func.CardsCheckALL(cards, func.HasSetCode, true, 0x9e)) + { + if (!activate_SecretoftheYangZing) result = func.CardsIdToClientCards(new List { CardId.SecretoftheYangZing }, func.CardsCheckWhere(cards, + func.IsLocation, CardLocation.MonsterZone)); + result.AddRange(func.CardsIdToClientCards(new List { CardId.SecretoftheYangZing, CardId.Zefraxi_TreasureoftheYangZing }, func.CardsCheckWhere(cards, + Func.NegateFunc(func.IsLocation), CardLocation.MonsterZone))); + } + else + { + List scards = func.CardsCheckWhere(cards, card => { return card.Location == CardLocation.SpellZone; }); + scards.Sort((cardA, cardB) => + { + if (Func.IsCode(cardA, CardId.OracleofZefra, CardId.DarkContractwiththGate) && !Func.IsCode(cardB, CardId.OracleofZefra, CardId.DarkContractwiththGate)) return 1; + if (!Func.IsCode(cardA, CardId.OracleofZefra, CardId.DarkContractwiththGate) && Func.IsCode(cardB, CardId.OracleofZefra, CardId.DarkContractwiththGate)) return -1; + return 0; + }); + result.AddRange(scards); + } + + } + else if (func.CardsCheckAny(cards, card => { return card.Controller == 1 && (card.Location & CardLocation.Onfield) > 0; }) && min == 1 && max == 1) + { + ClientCard card = Util.GetBestEnemyCard(); + if (card != null && cards.Contains(card)) result.Add(card); + else + { + result = new List(func.CardsCheckWhere(cards, ecard => { return ecard.Controller == 1; })); + if (result.Count <= 0) return null; + result.Sort(CardContainer.CompareCardAttack); + result.Reverse(); + } + } + } + else if (hint == HintMsg.SpSummon) + { + List tuner_ids = new List() + { + CardId.DestrudotheLostDragon_Frisson, CardId.PSY_FrameDriver, CardId.JetSynchron, CardId.PSY_FramegearGamma,CardId.LightoftheYangZing + }; + List no_tuner_ids = new List() + { + CardId.TheMightyMasterofMagic, CardId.MythicalBeastJackalKing, CardId.SecretoftheYangZing + }; + if (func.CardsCheckALL(cards, func.IsLocation, true, CardLocation.Hand)) + { + if (summoned && Bot.HasInExtra(CardId.CrystronHalqifibrax) && func.CardsCheckCount(Bot.MonsterZone, card => { + return card.IsFaceup() && card.HasType(CardType.Tuner); + }) <= 0 && !(Bot.HasInGraveyard(CardId.DDLamia) && !activate_DDLamia + && func.CardsCheckCount(Func.GetZoneCards(Bot, CardLocation.Onfield | CardLocation.Hand, true), card => { return Func.HasSetCode(card, 0xaf, 0xae) && card.Id != CardId.DDLamia; }) + <= 0) && !(Bot.HasInGraveyard(CardId.JetSynchron) && !activate_JetSynchron) + && !(Bot.HasInGraveyard(CardId.DestrudotheLostDragon_Frisson) && !activate_DestrudotheLostDragon_Frisson)) + { + ids.AddRange(tuner_ids); + ids.AddRange(no_tuner_ids); + } + else + { + ids.AddRange(no_tuner_ids); + ids.AddRange(tuner_ids); + } + result = func.CardsIdToClientCards(ids, cards); + } + else if (func.CardsCheckALL(cards, card => { + return Func.IsCode(card, CardId.LightoftheYangZing, CardId.PSY_FramegearGamma, + CardId.MechaPhantomBeastO_Lion, CardId.JetSynchron, CardId.Deskbot001, CardId.DDLamia); + })) + { + if (Bot.GetMonstersInMainZone().Count <= 1) ids.Add(CardId.Deskbot001); + ids.Add(CardId.JetSynchron); + ids.Add(CardId.Deskbot001); + ids.Add(CardId.LightoftheYangZing); + ids.Add(CardId.PSY_FramegearGamma); + result = func.CardsIdToClientCards(ids, cards); + } + + } + else if (hint == HintMsg.Release && func.CardsCheckAny(cards, func.IsLocation, CardLocation.MonsterZone)) + { + List tRelease = new List(); + List nRelease = new List(); + foreach (var card in cards) + { + if (card == null || IsNoLinkCards(card)) continue; + if (card.Id == CardId.MechaPhantomBeastToken) tRelease.Add(card); + else if (card.Id == CardId.Raidraptor_WiseStrix) tRelease.Insert(0, card); + else nRelease.Add(card); + } + result.AddRange(tRelease); + result.AddRange(nRelease); + } + IList selectResult = Func.CheckSelectCount(Util, result, cards, min, max); + if (selectResult == null) return base.OnSelectCard(cards, min, max, hint, cancelable); + return selectResult; + } + private bool HasInDeck(int id) + { + return CheckRemainInDeck(id) > 0; + } + private int CheckRemainInDeck(int id) + { + switch (id) + { + case CardId.PSY_FrameDriver: + return Bot.GetRemainingCount(CardId.PSY_FrameDriver, 1); + case CardId.Zefraath: + return Bot.GetRemainingCount(CardId.Zefraath, 3); + case CardId.TheMightyMasterofMagic: + return Bot.GetRemainingCount(CardId.TheMightyMasterofMagic, 1); + case CardId.AstrographSorcerer: + return Bot.GetRemainingCount(CardId.AstrographSorcerer, 1); + case CardId.DestrudotheLostDragon_Frisson: + return Bot.GetRemainingCount(CardId.DestrudotheLostDragon_Frisson, 1); + case CardId.SupremeKingGateZero: + return Bot.GetRemainingCount(CardId.SupremeKingGateZero, 2); + case CardId.MythicalBeastJackalKing: + return Bot.GetRemainingCount(CardId.MythicalBeastJackalKing, 1); + case CardId.SecretoftheYangZing: + return Bot.GetRemainingCount(CardId.SecretoftheYangZing, 3); + case CardId.FlameBeastoftheNekroz: + return Bot.GetRemainingCount(CardId.FlameBeastoftheNekroz, 1); + case CardId.StellarknightZefraxciton: + return Bot.GetRemainingCount(CardId.StellarknightZefraxciton, 1); + case CardId.SupremeKingDragonDarkwurm: + return Bot.GetRemainingCount(CardId.SupremeKingDragonDarkwurm, 1); + case CardId.Blackwing_ZephyrostheElite: + return Bot.GetRemainingCount(CardId.Blackwing_ZephyrostheElite, 1); + case CardId.ShaddollZefracore: + return Bot.GetRemainingCount(CardId.ShaddollZefracore, 1); + case CardId.Raidraptor_SingingLanius: + return Bot.GetRemainingCount(CardId.Raidraptor_SingingLanius, 1); + case CardId.SatellarknightZefrathuban: + return Bot.GetRemainingCount(CardId.SatellarknightZefrathuban, 1); + case CardId.Raider_Wing: + return Bot.GetRemainingCount(CardId.Raider_Wing, 1); + case CardId.Zefraxi_TreasureoftheYangZing: + return Bot.GetRemainingCount(CardId.Zefraxi_TreasureoftheYangZing, 2); + case CardId.RitualBeastTamerZeframpilica: + return Bot.GetRemainingCount(CardId.RitualBeastTamerZeframpilica, 1); + case CardId.ServantofEndymion: + return Bot.GetRemainingCount(CardId.ServantofEndymion, 3); + case CardId.PSY_FramegearGamma: + return Bot.GetRemainingCount(CardId.PSY_FramegearGamma, 3); + case CardId.MechaPhantomBeastO_Lion: + return Bot.GetRemainingCount(CardId.MechaPhantomBeastO_Lion, 1); + case CardId.MaxxC: + return Bot.GetRemainingCount(CardId.MaxxC, 3); + case CardId.Deskbot001: + return Bot.GetRemainingCount(CardId.Deskbot001, 1); + case CardId.JetSynchron: + return Bot.GetRemainingCount(CardId.JetSynchron, 1); + case CardId.DDLamia: + return Bot.GetRemainingCount(CardId.DDLamia, 1); + case CardId.DDSavantKepler: + return Bot.GetRemainingCount(CardId.DDSavantKepler, 1); + case CardId.LightoftheYangZing: + return Bot.GetRemainingCount(CardId.LightoftheYangZing, 1); + case CardId.Rank_Up_MagicSoulShaveForce: + return Bot.GetRemainingCount(CardId.Rank_Up_MagicSoulShaveForce, 1); + case CardId.SpellPowerMastery: + return Bot.GetRemainingCount(CardId.SpellPowerMastery, 3); + case CardId.DragonShrine: + return Bot.GetRemainingCount(CardId.DragonShrine, 3); + case CardId.Terraforming: + return Bot.GetRemainingCount(CardId.Terraforming, 1); + case CardId.ZefraProvidence: + return Bot.GetRemainingCount(CardId.ZefraProvidence, 3); + case CardId.FoolishBurial: + return Bot.GetRemainingCount(CardId.FoolishBurial, 1); + case CardId.CalledbytheGrave: + return Bot.GetRemainingCount(CardId.CalledbytheGrave, 2); + case CardId.DarkContractwiththGate: + return Bot.GetRemainingCount(CardId.DarkContractwiththGate, 1); + case CardId.OracleofZefra: + return Bot.GetRemainingCount(CardId.OracleofZefra, 3); + case CardId.ZefraWar: + return Bot.GetRemainingCount(CardId.ZefraWar, 1); + case CardId.ZefraDivineStrike: + return Bot.GetRemainingCount(CardId.ZefraDivineStrike, 1); + case CardId.NinePillarsofYangZing: + return Bot.GetRemainingCount(CardId.NinePillarsofYangZing, 1); + default: + return 0; + } + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZexalWeaponsExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZexalWeaponsExecutor.cs new file mode 100644 index 0000000..aea55b2 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZexalWeaponsExecutor.cs @@ -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 OnSelectXyzMaterial(IList cards, int min, int max) + { + IList 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 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(); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZoodiacExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZoodiacExecutor.cs new file mode 100644 index 0000000..81d3e5f --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Decks/ZoodiacExecutor.cs @@ -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 materials0 = Bot.Graveyard; + IList materials1 = Enemy.Graveyard; + IList mats = new List(); + 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 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(); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/DecksManager.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/DecksManager.cs new file mode 100644 index 0000000..faba009 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/DecksManager.cs @@ -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 _decks; + private static List _list; + private static Random _rand; + + public static void Init() + { + _decks = new Dictionary(); + _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(); + _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; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/DefaultExecutor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/DefaultExecutor.cs new file mode 100644 index 0000000..a113142 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/DefaultExecutor.cs @@ -0,0 +1,1828 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using YGOSharp.OCGWrapper.Enums; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; + +namespace WindBot.Game.AI +{ + public abstract class DefaultExecutor : Executor + { + protected class _CardId + { + public const int JizukirutheStarDestroyingKaiju = 63941210; + public const int ThunderKingtheLightningstrikeKaiju = 48770333; + public const int DogorantheMadFlameKaiju = 93332803; + public const int RadiantheMultidimensionalKaiju = 28674152; + public const int GadarlatheMysteryDustKaiju = 36956512; + public const int KumongoustheStickyStringKaiju = 29726552; + public const int GamecieltheSeaTurtleKaiju = 55063751; + public const int SuperAntiKaijuWarMachineMechaDogoran = 84769941; + + public const int SandaionTheTimelord = 33015627; + public const int GabrionTheTimelord = 6616912; + public const int MichionTheTimelord = 7733560; + public const int ZaphionTheTimelord = 28929131; + public const int HailonTheTimelord = 34137269; + public const int RaphionTheTimelord = 60222213; + public const int SadionTheTimelord = 65314286; + public const int MetaionTheTimelord = 74530899; + public const int KamionTheTimelord = 91712985; + public const int LazionTheTimelord = 92435533; + + public const int LeftArmofTheForbiddenOne = 7902349; + public const int RightLegofTheForbiddenOne = 8124921; + public const int LeftLegofTheForbiddenOne = 44519536; + public const int RightArmofTheForbiddenOne = 70903634; + public const int ExodiaTheForbiddenOne = 33396948; + + public const int UltimateConductorTytanno = 18940556; + public const int ElShaddollConstruct = 20366274; + public const int AllyOfJusticeCatastor = 26593852; + + public const int DupeFrog = 46239604; + public const int MaraudingCaptain = 2460565; + + public const int BlackRoseDragon = 73580471; + public const int JudgmentDragon = 57774843; + public const int TopologicTrisbaena = 72529749; + public const int EvilswarmExcitonKnight = 46772449; + public const int HarpiesFeatherDuster = 18144506; + public const int DarkMagicAttack = 2314238; + public const int MysticalSpaceTyphoon = 5318639; + public const int CosmicCyclone = 8267140; + public const int GalaxyCyclone = 5133471; + public const int BookOfMoon = 14087893; + public const int CompulsoryEvacuationDevice = 94192409; + public const int CallOfTheHaunted = 97077563; + public const int Scapegoat = 73915051; + public const int BreakthroughSkill = 78474168; + public const int SolemnJudgment = 41420027; + public const int SolemnWarning = 84749824; + public const int SolemnStrike = 40605147; + public const int TorrentialTribute = 53582587; + public const int EvenlyMatched = 15693423; + public const int HeavyStorm = 19613556; + public const int HammerShot = 26412047; + public const int DarkHole = 53129443; + public const int Raigeki = 12580477; + public const int SmashingGround = 97169186; + public const int PotOfDesires = 35261759; + public const int AllureofDarkness = 1475311; + public const int DimensionalBarrier = 83326048; + public const int InterruptedKaijuSlumber = 99330325; + + public const int ChickenGame = 67616300; + public const int SantaClaws = 46565218; + + public const int CastelTheSkyblasterMusketeer = 82633039; + public const int CrystalWingSynchroDragon = 50954680; + public const int NumberS39UtopiaTheLightning = 56832966; + public const int Number39Utopia = 84013237; + public const int UltimayaTzolkin = 1686814; + public const int MekkKnightCrusadiaAstram = 21887175; + public const int HamonLordofStrikingThunder = 32491822; + + public const int MoonMirrorShield = 19508728; + public const int PhantomKnightsFogBlade = 25542642; + + public const int VampireFraeulein = 6039967; + public const int InjectionFairyLily = 79575620; + + public const int BlueEyesChaosMAXDragon = 55410871; + + public const int AshBlossom = 14558127; + public const int MaxxC = 23434538; + public const int LockBird = 94145021; + public const int GhostOgreAndSnowRabbit = 59438930; + public const int GhostBelle = 73642296; + public const int EffectVeiler = 97268402; + public const int GhostMournerMoonlitChill = 52038441; + public const int ArtifactLancea = 34267821; + public const int DimensionShifter = 91800273; + public const int NibiruThePrimalBeing = 27204311; + public const int MulcharmyPurulia = 84192580; + public const int MulcharmyFuwalos = 42141493; + public const int MulcharmyNyalus = 87126721; + + public const int CalledByTheGrave = 24224830; + public const int CrossoutDesignator = 65681983; + public const int InfiniteImpermanence = 10045474; + public const int GalaxySoldier = 46659709; + public const int MacroCosmos = 30241314; + public const int UpstartGoblin = 70368879; + public const int CyberEmergency = 60600126; + public const int TheAgentOfCreationVenus = 64734921; + + public const int EaterOfMillions = 63845230; + + public const int InvokedPurgatrio = 12307878; + public const int ChaosAncientGearGiant = 51788412; + public const int UltimateAncientGearGolem = 12652643; + + public const int RedDragonArchfiend = 70902743; + + public const int ImperialOrder = 61740673; + public const int RoyalDecreel = 51452091; + public const int NaturalExterio = 99916754; + public const int NaturiaBeast = 33198837; + public const int SwordsmanLV7 = 37267041; + public const int AntiSpellFragrance = 58921041; + public const int Number41BagooskatheTerriblyTiredTapir = 90590303; + public const int SkillDrain = 82732705; + + public const int DimensionalFissure = 81674782; + public const int BanisheroftheRadiance = 94853057; + public const int BanisheroftheLight = 61528025; + public const int KashtiraAriseHeart = 48626373; + public const int MaskedHERODarkLaw = 58481572; + + public const int VaylantzWorld_ShinraBansho = 49568943; + public const int VaylantzWorld_KonigWissen = 75952542; + public const int DivineArsenalAAZEUS_SkyThunder = 90448279; + public const int LightningStorm = 14532163; + public const int MistakenArrest = 4227096; + public const int ThunderKingRaiOh = 71564252; + public const int ThunderDragonColossus = 15291624; + public const int DeckLockdown = 1149109; + public const int DoomZDestruction = 80320877; + public const int Mistake = 59305593; + + public const int BelialMarquisOfDarkness = 33655493; + public const int ChirubiméPrincessOfAutumnLeaves = 87294988; + public const int PerformapalBarokuriboh = 19050066; + public const int LabrynthArchfiend = 48745395; + public const int HarpiesPetDragonFearsomeFireBlast = 4991081; + public const int DynaHeroFurHire = 25123713; + public const int Hieracosphinx = 82260502; + public const int SpeedroidPassinglider = 26420373; + public const int TyrOfTheNordicChampions = 2333365; + public const int ValkyrianKnight = 99348756; + public const int Victoria = 75162696; + public const int MadolcheChouxvalier = 75363626; + public const int LadyOfD = 67511500; + public const int MermailAbysslung = 95466842; + public const int HarpiesPetBabyDragon = 6924874; + public const int HandHoldingGenie = 94535485; + public const int GolemDragon = 9666558; + public const int TwilightRoseKnight = 2986553; + public const int PerformapalThunderhino = 70458081; + public const int MiracleFlipper = 131182; + public const int Decoyroid = 25034083; + public const int AltergeistFifinellag = 12977245; + public const int BatterymanD = 55401221; + public const int Watthopper = 61380658; + public const int EgyptianGodSlime = 42166000; + public const int DinowrestlerChimeraTWrextle = 22900219; + public const int DinowrestlerGigaSpinosavate = 58672736; + public const int ScarredWarrior = 45298492; + public const int SharkFortress = 50449881; + public const int HeroicChampionClaivesolish = 97453744; + public const int GhostrickAlucard = 75367227; + public const int DinowrestlerKingTWrextle = 77967790; + public const int NumberF0UtopicFutureZexal = 41522092; + + public const int PerformapalMissDirector = 92932860; + public const int AncientWarriorsMasterfulSunMou = 40140448; + public const int AncientWarriorsVirtuousLiuXuan = 40428851; + public const int CommandKnight = 10375182; + public const int HunterOwl = 51962254; + public const int RokketRecharger = 5969957; + public const int EmissaryOfTheOasis = 6103294; + public const int Zuttomozaurus = 24454387; + public const int Otoshidamashi = 14957440; + public const int NaturiaMosquito = 17285476; + public const int RescueACEHydrant = 37617348; + public const int MeizenTheBattleNinja = 11825276; + public const int VindikiteRGenex = 73483491; + public const int PrincessCologne = 75574498; + public const int Number48ShadowLich = 1426714; + public const int PhantomToken = 1426715; + public const int DuelLinkDragonTheDuelDragon = 60025883; + public const int DuelDragonToken = 60025884; + public const int SeleneQueenOfTheMasterMagicians = 45819647; + public const int TheWingedDragonofRaSphereMode = 10000080; + public const int SelettriceVaalmonica = 23093373; + public const int PerformageTrapezeWitch = 33206889; + public const int PoseidraTheStormingAtlantean = 99193444; + + public const int RockOfTheVanquisher = 28168628; + public const int SpiralDischarge = 29477860; + public const int GaiaTheDragonChampion = 66889139; + public const int CrusadiaVanguard = 55312487; + public const int GladiatorBeastDomitianus = 33652635; + public const int PatricianOfDarkness = 19153634; + public const int DictatorOfD = 66961194; + + public const int LoThePrayersOfTheVoicelessVoice = 25801745; + public const int BarrierOfTheVoicelessVoice = 98477480; + + public const int DiabellzeOfTheOriginalSin = 53765052; + public const int PotOfExtravagance = 49238328; + } + + protected class _Setcode + { + public const int Watt = 0xe; + public const int Speedroid = 0x2016; + public const int EarthboundImmortal = 0x1021; + public const int Naturia = 0x2a; + public const int Nordic = 0x42; + public const int TimeLord = 0x4a; + + public const int Harpie = 0x64; + public const int Madolche = 0x71; + public const int Ghostrick = 0x8d; + public const int OddEyes = 0x99; + public const int Performapal = 0x9f; + public const int Performage = 0xc6; + public const int BlueEyes = 0xdd; + public const int FurHire = 0x114; + public const int Altergeist = 0x103; + public const int Crusadia = 0x116; + public const int Danger = 0x11e; + public const int Endymion = 0x12a; + public const int AncientWarriors = 0x137; + public const int RescueACE = 0x18b; + public const int VanquishSoul = 0x195; + public const int Horus = 0x19d; + } + + protected DefaultExecutor(GameAI ai, Duel duel) + : base(ai, duel) + { + AddExecutor(ExecutorType.Activate, _CardId.ChickenGame, DefaultChickenGame); + AddExecutor(ExecutorType.Activate, _CardId.VaylantzWorld_ShinraBansho, DefaultVaylantzWorld_ShinraBansho); + AddExecutor(ExecutorType.Activate, _CardId.VaylantzWorld_KonigWissen, DefaultVaylantzWorld_KonigWissen); + AddExecutor(ExecutorType.Activate, _CardId.SantaClaws); + AddExecutor(ExecutorType.SpellSet, DefaultSetForDiabellze); + } + + protected int lightningStormOption = -1; + Dictionary calledbytheGraveIdCountMap = new Dictionary(); + List crossoutDesignatorIdList = new List(); + int mistakenArrestAffectedCount = 0; + /// + /// List of effect IDs that have been resolved this turn. + /// + protected List resolvedEffectIdList = new List(); + /// + /// List of effect IDs that have been resolved by enemy this turn. + /// + protected List enemyResolvedEffectIdList = new List(); + + /// Columns 0-4 on Bot's field negated by Infinite Impermanence (enemy's col converted to ours: 4-col). Cleared at turn start. + protected List infiniteImpermanenceNegatedColumns = new List(); + + /// + /// Defined: + /// if monster with code as KEY, other monsters with rules as VALUE won't be targeted for attack. + /// + protected Dictionary> DefenderProtectRule = new Dictionary> { + {_CardId.BelialMarquisOfDarkness, defender => defender.IsFaceup()}, + {_CardId.ChirubiméPrincessOfAutumnLeaves, defender => defender.HasRace(CardRace.Plant)}, + {_CardId.PerformapalBarokuriboh, defender => true}, + {_CardId.LabrynthArchfiend, defender => defender.HasRace(CardRace.Fiend) && !defender.IsCode(_CardId.LabrynthArchfiend)}, + {_CardId.HarpiesPetDragonFearsomeFireBlast, defender => defender.Level <= 6 && defender.HasSetcode(_Setcode.Harpie)}, + {_CardId.DynaHeroFurHire, defender => defender.HasSetcode(_Setcode.FurHire)}, + {_CardId.Hieracosphinx, defender => defender.IsFacedown()}, + {_CardId.SpeedroidPassinglider, defender => defender.HasSetcode(_Setcode.Speedroid)}, + {_CardId.TyrOfTheNordicChampions, defender => defender.HasSetcode(_Setcode.Nordic)}, + {_CardId.ValkyrianKnight, defender => defender.HasRace(CardRace.Warrior) && !defender.IsCode(_CardId.ValkyrianKnight)}, + {_CardId.Victoria, defender => defender.HasRace(CardRace.Fairy)}, + {_CardId.MadolcheChouxvalier, defender => defender.HasSetcode(_Setcode.Madolche) && !defender.IsCode(_CardId.MadolcheChouxvalier)}, + {_CardId.LadyOfD, defender => defender.HasRace(CardRace.Dragon)}, + {_CardId.MermailAbysslung, defender => defender.HasAttribute(CardAttribute.Water)}, + {_CardId.HarpiesPetBabyDragon, defender => defender.HasSetcode(_Setcode.Harpie) && !defender.IsCode(_CardId.HarpiesPetBabyDragon)}, + {_CardId.HandHoldingGenie, defender => true}, + {_CardId.GolemDragon, defender => defender.HasRace(CardRace.Dragon)}, + {_CardId.MaraudingCaptain, defender => defender.HasRace(CardRace.Warrior)}, + {_CardId.TwilightRoseKnight, defender => defender.HasRace(CardRace.Plant)}, + {_CardId.PerformapalThunderhino, defender => defender.HasSetcode(_Setcode.Performapal)}, + {_CardId.MiracleFlipper, defender => defender.IsFaceup()}, + {_CardId.Decoyroid, defender => defender.IsFaceup()}, + {_CardId.DupeFrog, defender => true}, + {_CardId.AltergeistFifinellag, defender => defender.HasSetcode(_Setcode.Altergeist)}, + {_CardId.BatterymanD, defender => defender.HasRace(CardRace.Thunder) && !defender.IsCode(_CardId.BatterymanD)}, + {_CardId.Watthopper, defender => defender.HasSetcode(_Setcode.Watt) && defender.IsFaceup()}, + + {_CardId.EgyptianGodSlime, defender => true}, + {_CardId.DinowrestlerChimeraTWrextle, defender => true}, + {_CardId.DinowrestlerGigaSpinosavate, defender => true}, + {_CardId.ScarredWarrior, defender => defender.HasRace(CardRace.Warrior) && defender.IsFaceup()}, + {_CardId.SharkFortress, defender => true}, + {_CardId.HeroicChampionClaivesolish, defender => true}, + {_CardId.GhostrickAlucard, defender => defender.HasSetcode(_Setcode.Ghostrick) || defender.IsFacedown()}, + {_CardId.MekkKnightCrusadiaAstram, defender => true}, + {_CardId.DinowrestlerKingTWrextle, defender => true}, + {_CardId.NumberF0UtopicFutureZexal, defender => true} + }; + + /// + /// Defined: + /// if monster with KEY on field, and meet VALUE(monster, all monster), it cannot be targeted for attack. + /// + protected Dictionary, bool>> DefenderInvisbleRule = new Dictionary, bool>> { + {_CardId.UltimayaTzolkin, (defender, list) => list.Any(monster => !monster.Equals(defender) && monster.HasType(CardType.Synchro))}, + {_CardId.PerformapalMissDirector, (defender, list) => list.Any(monster => monster.HasSetcode(_Setcode.OddEyes))}, + {_CardId.AncientWarriorsMasterfulSunMou, (defender, list) => list.Any(monster => !monster.Equals(defender) && monster.HasSetcode(_Setcode.AncientWarriors))}, + {_CardId.AncientWarriorsVirtuousLiuXuan, (defender, list) => list.Any(monster => !monster.Equals(defender) && monster.HasSetcode(_Setcode.AncientWarriors))}, + {_CardId.CommandKnight, (defender, list) => list.Any(monster => !monster.Equals(defender))}, + {_CardId.HunterOwl, (defender, list) => list.Any(monster => !monster.Equals(defender) && monster.HasAttribute(CardAttribute.Wind))}, + {_CardId.RokketRecharger, (defender, list) => list.Any(monster => monster.IsExtraCard() && monster.HasAttribute(CardAttribute.Dark))}, + {_CardId.EmissaryOfTheOasis, (defender, list) => list.Any(monster => monster.HasType(CardType.Normal) && monster.Level <= 3)}, + {_CardId.Zuttomozaurus, (defender, list) => list.Any(monster => !monster.Equals(defender) && monster.HasRace(CardRace.Dinosaur))}, + {_CardId.Otoshidamashi, (defender, list) => list.Any(monster => !monster.HasType(CardType.Tuner))}, + {_CardId.NaturiaMosquito, (defender, list) => list.Any(monster => !monster.Equals(defender) && monster.HasSetcode(_Setcode.Naturia))}, + {_CardId.RescueACEHydrant, (defender, list) => list.Any(monster => !monster.IsCode(_CardId.RescueACEHydrant) && monster.HasSetcode(_Setcode.RescueACE))}, + + {_CardId.MeizenTheBattleNinja, (defender, list) => list.Any(monster => monster.IsFacedown())}, + {_CardId.VindikiteRGenex, (defender, list) => true}, + {_CardId.PrincessCologne, (defender, list) => list.Any(monster => !monster.Equals(defender))}, + {_CardId.Number48ShadowLich, (defender, list) => list.Any(monster => monster.IsCode(_CardId.PhantomToken))}, + {_CardId.DuelLinkDragonTheDuelDragon, (defender, list) => list.Any(monster => monster.IsCode(_CardId.DuelDragonToken))}, + {_CardId.SeleneQueenOfTheMasterMagicians, (defender, list) => list.Any(monster => monster.HasSetcode(_Setcode.Endymion))}, + + {_CardId.TheWingedDragonofRaSphereMode, (defender, list) => true}, + {_CardId.SelettriceVaalmonica, (defender, list) => list.Any(monster => !monster.IsCode(_CardId.SelettriceVaalmonica))}, + {_CardId.PerformageTrapezeWitch, (defender, list) => list.Any(monster => !monster.IsCode(_CardId.PerformageTrapezeWitch) && monster.HasSetcode(_Setcode.Performage))}, + {_CardId.PoseidraTheStormingAtlantean, (defender, list) => list.Any(monster => !monster.IsCode(_CardId.PoseidraTheStormingAtlantean))} + }; + + /// + /// Decide which card should the attacker attack. + /// + /// Card that attack. + /// Cards that defend. + /// BattlePhaseAction including the target, or null (in this situation, GameAI will check the next attacker) + public override BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList defenders) + { + foreach (ClientCard defender in defenders) + { + attacker.RealPower = attacker.Attack; + defender.RealPower = defender.GetDefensePower(); + if (!OnPreBattleBetween(attacker, defender)) + continue; + + if (attacker.RealPower > defender.RealPower || (attacker.RealPower >= defender.RealPower && attacker.IsLastAttacker && defender.IsAttack())) + return AI.Attack(attacker, defender); + } + + if (attacker.CanDirectAttack) + return AI.Attack(attacker, null); + + return null; + } + + /// + /// Decide whether to declare attack between attacker and defender. + /// Can be overrided to update the RealPower of attacker for cards like Honest. + /// + /// Card that attack. + /// Card that defend. + /// false if the attack shouldn't be done. + public override bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + if (!attacker.IsMonsterHasPreventActivationEffectInBattle()) + { + if (defender.IsMonsterInvincible() && defender.IsDefense()) + return false; + + if (defender.IsMonsterDangerous()) + { + bool canIgnoreIt = !attacker.IsDisabled() && ( + attacker.IsCode(_CardId.UltimateConductorTytanno) && defender.IsDefense() || + attacker.IsCode(_CardId.ElShaddollConstruct) && defender.IsSpecialSummoned || + attacker.IsCode(_CardId.AllyOfJusticeCatastor) && !defender.HasAttribute(CardAttribute.Dark)); + if (!canIgnoreIt) + return false; + } + + if (defender.EquipCards.Any(equip => equip.IsCode(_CardId.MoonMirrorShield) && !equip.IsDisabled())) + return false; + + if (!defender.IsDisabled()) + { + if (defender.IsCode(_CardId.MekkKnightCrusadiaAstram) && defender.IsAttack() && attacker.IsSpecialSummoned) + defender.RealPower += attacker.Attack; + + if (defender.IsCode(_CardId.CrystalWingSynchroDragon) && defender.IsAttack() && attacker.Level >= 5) + defender.RealPower += attacker.Attack; + + if (defender.IsCode(_CardId.AllyOfJusticeCatastor) && !attacker.HasAttribute(CardAttribute.Dark)) + return false; + + if (defender.IsCode(_CardId.NumberS39UtopiaTheLightning) && defender.IsAttack() && defender.HasXyzMaterial(2, _CardId.Number39Utopia)) + defender.RealPower = 5000; + + if (defender.IsCode(_CardId.VampireFraeulein)) + defender.RealPower += (Enemy.LifePoints > 3000) ? 3000 : (Enemy.LifePoints - 100); + + if (defender.IsCode(_CardId.InjectionFairyLily) && Enemy.LifePoints > 2000) + defender.RealPower += 3000; + } + } + + if (!defender.IsMonsterHasPreventActivationEffectInBattle()) + { + if (attacker.IsCode(_CardId.NumberS39UtopiaTheLightning) && !attacker.IsDisabled() && attacker.HasXyzMaterial(2, _CardId.Number39Utopia)) + attacker.RealPower = 5000; + + if (attacker.IsCode(_CardId.EaterOfMillions) && !attacker.IsDisabled()) + attacker.RealPower = 9999; + + if (attacker.IsMonsterInvincible()) + attacker.RealPower = 9999; + + if (attacker.EquipCards.Any(equip => equip.IsCode(_CardId.MoonMirrorShield) && !equip.IsDisabled())) + attacker.RealPower = defender.RealPower + 100; + } + + foreach (ClientCard protecter in Enemy.GetMonsters()) + { + if (!protecter.IsDisabled() && protecter != defender) + { + Func defenderRule = card => false; + if (DefenderProtectRule.TryGetValue(protecter.Id, out defenderRule)) + { + if (defenderRule(defender)) return false; + } + } + } + + if (attacker.EquipCards.Any(equip => equip.IsCode(_CardId.MoonMirrorShield) && !equip.IsDisabled())) + attacker.RealPower = defender.RealPower + 100; + + if (!defender.IsDisabled()) + { + Func, bool> defenderRule = (card, monsterList) => false; + if (DefenderInvisbleRule.TryGetValue(defender.Id, out defenderRule)) + { + if (defenderRule(defender, Enemy.GetMonsters())) return false; + } + } + + if (Enemy.GetMonsters().Any(monster => !monster.Equals(defender) && monster.IsCode(_CardId.HamonLordofStrikingThunder) && !monster.IsDisabled() && monster.IsDefense())) + return false; + + if (defender.OwnTargets.Any(card => card.IsCode(_CardId.PhantomKnightsFogBlade) && !card.IsDisabled())) + return false; + + if (defender.HasSetcode(_Setcode.EarthboundImmortal) && !defender.IsDisabled()) + return false; + + bool attackHighestMonster = + Enemy.HasInMonstersZone(_CardId.RockOfTheVanquisher, true) && Enemy.GetMonsters().Any(card => card.HasSetcode(_Setcode.VanquishSoul)) || + Enemy.HasInMonstersZone(_CardId.GladiatorBeastDomitianus, true) || Enemy.HasInMonstersZone(_CardId.PatricianOfDarkness) || + Enemy.HasInMonstersZone(_CardId.DictatorOfD, true) && Enemy.GetMonsters().Any(card => card.HasSetcode(_Setcode.BlueEyes)); + if (attackHighestMonster) + { + if (defender.HasPosition(CardPosition.FaceDown)) + return false; + if (Enemy.GetMonsters().Any(card => card.IsFaceup() && card.Attack > defender.Attack)) + return false; + } + + if (Enemy.HasInSpellZone(_CardId.SpiralDischarge, true) && Enemy.HasInMonstersZone(_CardId.GaiaTheDragonChampion) && !defender.IsCode(_CardId.GaiaTheDragonChampion)) + return false; + + if (Enemy.HasInSpellZone(_CardId.CrusadiaVanguard, true) && Enemy.GetMonsters().Any(card => card.HasSetcode(_Setcode.Crusadia) && card.HasType(CardType.Link)) && !defender.HasType(CardType.Link)) + return false; + + if (defender.IsCode(_CardId.RescueACEHydrant) && !defender.IsDisabled() && Enemy.GetMonsters().Any(monster => monster.HasSetcode(_Setcode.RescueACE) && !monster.IsCode(_CardId.RescueACEHydrant))) + return false; + + if (Enemy.HasInSpellZone(_CardId.BarrierOfTheVoicelessVoice, true) && Enemy.HasInMonstersZone(_CardId.LoThePrayersOfTheVoicelessVoice, faceUp: true) + && Enemy.GetMonsters().Any(card => card.HasType(CardType.Ritual) && card.IsFaceup()) && !defender.HasType(CardType.Ritual)) + return false; + + return true; + } + + public override bool OnPreActivate(ClientCard card) + { + ClientCard LastChainCard = Util.GetLastChainCard(); + if (LastChainCard != null && Duel.Phase == DuelPhase.Standby && + LastChainCard.IsCode( + _CardId.SandaionTheTimelord, + _CardId.GabrionTheTimelord, + _CardId.MichionTheTimelord, + _CardId.ZaphionTheTimelord, + _CardId.HailonTheTimelord, + _CardId.RaphionTheTimelord, + _CardId.SadionTheTimelord, + _CardId.MetaionTheTimelord, + _CardId.KamionTheTimelord, + _CardId.LazionTheTimelord + )) + return false; + if ((card.Location == CardLocation.Hand || card.Location == CardLocation.SpellZone && card.IsFacedown()) && + (card.IsSpell() && DefaultSpellWillBeNegated() || card.IsTrap() && DefaultTrapWillBeNegated())) + return false; + return true; + } + + /// + /// Called when the AI has to select a card position. + /// + /// Id of the card to position on the field. + /// List of available positions. + /// Selected position, or 0 if no position is set for this card. + public override CardPosition OnSelectPosition(int cardId, IList positions) + { + YGOSharp.OCGWrapper.NamedCard cardData = YGOSharp.OCGWrapper.NamedCard.Get(cardId); + if (cardData != null) + { + if (cardData.Attack == 0) + return CardPosition.FaceUpDefence; + } + return 0; + } + + public override bool OnSelectBattleReplay() + { + if (Bot.BattlingMonster == null) + return false; + List defenders = new List(Duel.Fields[1].GetMonsters()); + defenders.Sort(CardContainer.CompareDefensePower); + defenders.Reverse(); + BattlePhaseAction result = OnSelectAttackTarget(Bot.BattlingMonster, defenders); + if (result != null && result.Action == BattlePhaseAction.BattleAction.Attack) + { + return true; + } + return false; + } + + /// + /// Set when this card can't beat the enemies + /// + public override bool OnSelectMonsterSummonOrSet(ClientCard card) + { + return card.Level <= 4 && Bot.GetMonsters().Count(m => m.IsFaceup()) == 0 && Util.IsAllEnemyBetterThanValue(card.Attack, true); + } + + /// + /// Called when the AI has to select one or more cards. + /// + /// List of available cards. + /// Minimal quantity. + /// Maximal quantity. + /// The hint message of the select. + /// True if you can return an empty list. + /// A new list containing the selected cards. + public override IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + // wordaround for Dogmatika Alba Zoa + int albaZoaCount = Bot.ExtraDeck.Count / 2; + if (!cancelable && min == albaZoaCount && max == albaZoaCount + && Duel.Player == 1 && (Duel.Phase == DuelPhase.Main1 || Duel.Phase == DuelPhase.Main2) && cards.All(card => + card.Controller == 0 && (card.Location == CardLocation.Hand || card.Location == CardLocation.Extra))) + { + Logger.DebugWriteLine("Dogmatika Alba Zoa solved"); + List extraDeck = new List(Bot.ExtraDeck); + int shuffleCount = extraDeck.Count; + while (shuffleCount-- > 1) + { + int index = Program.Rand.Next(extraDeck.Count); + ClientCard tempCard = extraDeck[shuffleCount]; + extraDeck[shuffleCount] = extraDeck[index]; + extraDeck[index] = tempCard; + } + + return Util.CheckSelectCount(extraDeck, cards, min, max); + } + + return null; + } + + public override void OnPlayerHint(int player, int hintType, int description) + { + base.OnPlayerHint(player, hintType, description); + if (player != 0 && player != 1) + return; + ClientField field = (player == 0) ? Bot : Enemy; + if (hintType == (int)PlayerHintType.DescAdd) + field.HintDescriptions.Add(description); + else if (hintType == (int)PlayerHintType.DescRemove) + field.HintDescriptions.Remove(description); + } + + public override void OnHintZone(int player, int zone) + { + base.OnHintZone(player, zone); + ChainInfo currentChainInfo = Duel.GetCurrentSolvingChainInfo(); + if (currentChainInfo != null) { + if (currentChainInfo.IsCode(_CardId.InfiniteImpermanence)) { + // Zone bit mapping: 0x100=col0, 0x200=col1, 0x400=col2, 0x800=col3, 0x1000=col4. + for (int i = 0; i <= 4; i++) + { + if ((zone & (0x100 << i)) == 0) + continue; + if (currentChainInfo.ActivatePlayer == 0) + { + infiniteImpermanenceNegatedColumns.Add(i); + } + else + { + infiniteImpermanenceNegatedColumns.Add(4 - i); + } + } + } + } + } + + public override void OnReceivingAnnouce(int player, int data) + { + if (player == 1 && data == Util.GetStringId(_CardId.LightningStorm, 0) || data == Util.GetStringId(_CardId.LightningStorm, 1)) + { + lightningStormOption = data - Util.GetStringId(_CardId.LightningStorm, 0); + } + + base.OnReceivingAnnouce(player, data); + } + + public override void OnChainSolved(int chainIndex) + { + ChainInfo currentChain = Duel.GetCurrentSolvingChainInfo(); + if (currentChain != null && !Duel.IsCurrentSolvingChainNegated()) + { + if (currentChain.IsActivateCode(_CardId.LockBird)) + { + resolvedEffectIdList.Add(_CardId.LockBird); + } + if (currentChain.ActivatePlayer == 1) + { + if (currentChain.IsActivateCode(_CardId.MaxxC)) + enemyResolvedEffectIdList.Add(_CardId.MaxxC); + if (currentChain.IsActivateCode(_CardId.MulcharmyPurulia)) + enemyResolvedEffectIdList.Add(_CardId.MulcharmyPurulia); + if (currentChain.IsActivateCode(_CardId.MulcharmyFuwalos)) + enemyResolvedEffectIdList.Add(_CardId.MulcharmyFuwalos); + if (currentChain.IsActivateCode(_CardId.MulcharmyNyalus)) + enemyResolvedEffectIdList.Add(_CardId.MulcharmyNyalus); + if (currentChain.IsActivateCode(_CardId.MistakenArrest)) + { + if (Duel.Player == 1) + { + mistakenArrestAffectedCount = Math.Max(mistakenArrestAffectedCount, 3); + } else + { + mistakenArrestAffectedCount = Math.Max(mistakenArrestAffectedCount, 2); + } + } + } + } + } + + public override void OnChainEnd() + { + lightningStormOption = -1; + base.OnChainEnd(); + } + + /// + /// Reset variables for new turn. + /// + public override void OnNewTurn() + { + infiniteImpermanenceNegatedColumns.Clear(); + resolvedEffectIdList.Clear(); + enemyResolvedEffectIdList.Clear(); + if (Duel.Turn <= 1) + { + calledbytheGraveIdCountMap.Clear(); + mistakenArrestAffectedCount = 0; + } + mistakenArrestAffectedCount = Math.Max(mistakenArrestAffectedCount - 1, 0); + List keyList = calledbytheGraveIdCountMap.Keys.ToList(); + foreach (int dic in keyList) + { + if (calledbytheGraveIdCountMap[dic] > 0) + { + calledbytheGraveIdCountMap[dic] -= 1; + } + } + crossoutDesignatorIdList.Clear(); + + base.OnNewTurn(); + } + + public override void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + if (card != null) + { + ClientCard currentSolvingChain = Duel.GetCurrentSolvingChainCard(); + if (currentSolvingChain != null && currentLocation == (int)CardLocation.Removed) + { + int originId = card.Id; + if (card.Data != null) + { + if (card.Data.Alias > 0) originId = card.Data.Alias; + else originId = card.Id; + } + if (currentSolvingChain.IsCode(_CardId.CalledByTheGrave)) + { + calledbytheGraveIdCountMap[originId] = 2; + } + if (currentSolvingChain.IsCode(_CardId.CrossoutDesignator)) + { + crossoutDesignatorIdList.Add(originId); + } + } + } + base.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + /// + /// Destroy face-down cards first, in our turn. + /// + protected bool DefaultMysticalSpaceTyphoon() + { + if (Duel.CurrentChain.Any(card => card.IsCode(_CardId.MysticalSpaceTyphoon))) + { + return false; + } + + List spells = Enemy.GetSpells(); + if (spells.Count == 0) + return false; + + ClientCard selected = Enemy.SpellZone.GetFloodgate(); + + if (selected == null) + { + if (Duel.Player == 0) + selected = spells.FirstOrDefault(card => card.IsFacedown()); + if (Duel.Player == 1) + selected = spells.FirstOrDefault(card => card.HasType(CardType.Continuous) || card.HasType(CardType.Equip) || card.HasType(CardType.Field)); + } + + if (selected == null) + return false; + AI.SelectCard(selected); + return true; + } + + /// + /// Destroy face-down cards first, in our turn. + /// + protected bool DefaultCosmicCyclone() + { + foreach (ClientCard card in Duel.CurrentChain) + if (card.IsCode(_CardId.CosmicCyclone)) + return false; + return (Bot.LifePoints > 1000) && DefaultMysticalSpaceTyphoon(); + } + + /// + /// Activate if avail. + /// + protected bool DefaultGalaxyCyclone() + { + List spells = Enemy.GetSpells(); + if (spells.Count == 0) + return false; + + ClientCard selected = null; + + if (Card.Location == CardLocation.Grave) + { + selected = Util.GetBestEnemySpell(true); + } + else + { + selected = spells.FirstOrDefault(card => card.IsFacedown()); + } + + if (selected == null) + return false; + + AI.SelectCard(selected); + return true; + } + + /// + /// Set the highest ATK level 4+ effect enemy monster. + /// + protected bool DefaultBookOfMoon() + { + if (Util.IsAllEnemyBetter(true)) + { + ClientCard monster = Enemy.GetMonsters().GetHighestAttackMonster(true); + if (monster != null && monster.HasType(CardType.Effect) && !monster.HasType(CardType.Link) && (monster.HasType(CardType.Xyz) || monster.Level > 4)) + { + AI.SelectCard(monster); + return true; + } + } + return false; + } + + /// + /// Return problematic monster, and if this card become target, return any enemy monster. + /// + protected bool DefaultCompulsoryEvacuationDevice() + { + ClientCard target = Util.GetProblematicEnemyMonster(0, true); + if (target != null) + { + AI.SelectCard(target); + return true; + } + if (Util.IsChainTarget(Card)) + { + ClientCard monster = Util.GetBestEnemyMonster(false, true); + if (monster != null) + { + AI.SelectCard(monster); + return true; + } + } + return false; + } + + /// + /// Revive the best monster when we don't have better one in field. + /// + protected bool DefaultCallOfTheHaunted() + { + if (!Util.IsAllEnemyBetter(true)) + return false; + ClientCard selected = Bot.Graveyard.GetMatchingCards(card => card.IsCanRevive()).OrderByDescending(card => card.Attack).FirstOrDefault(); + AI.SelectCard(selected); + return true; + } + + /// + /// Default Scapegoat effect + /// + protected bool DefaultScapegoat() + { + if (DefaultSpellWillBeNegated()) return false; + if (Duel.Player == 0) return false; + if (Duel.Phase == DuelPhase.End) return true; + if (DefaultOnBecomeTarget()) return true; + if (Duel.Phase > DuelPhase.Main1 && Duel.Phase < DuelPhase.Main2) + { + if (Enemy.HasInMonstersZone(new[] + { + _CardId.UltimateConductorTytanno, + _CardId.InvokedPurgatrio, + _CardId.ChaosAncientGearGiant, + _CardId.UltimateAncientGearGolem, + _CardId.RedDragonArchfiend + }, true)) return false; + if (Util.GetTotalAttackingMonsterAttack(1) >= Bot.LifePoints) return true; + } + return false; + } + /// + /// Always active in opponent's turn. + /// + protected bool DefaultMaxxC() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return Duel.Player == 1; + } + /// + /// Always disable opponent's effect except some cards like UpstartGoblin + /// + protected bool DefaultAshBlossomAndJoyousSpring() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + int[] ignoreList = { + _CardId.MacroCosmos, + _CardId.UpstartGoblin, + _CardId.CyberEmergency, + _CardId.TheAgentOfCreationVenus + }; + if (Util.GetLastChainCard().IsCode(ignoreList)) + return false; + if (Util.GetLastChainCard().HasSetcode(_Setcode.Danger) && Util.GetLastChainCard().Location == CardLocation.Hand) // Danger! archtype hand effect + return false; + return Duel.LastChainPlayer == 1; + } + /// + /// Always activate unless the activating card is disabled + /// + protected bool DefaultGhostOgreAndSnowRabbit() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + if (Util.GetLastChainCard() != null && Util.GetLastChainCard().IsDisabled()) + return false; + return DefaultTrap(); + } + /// + /// Always disable opponent's effect + /// + protected bool DefaultGhostBelleAndHauntedMansion() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return DefaultTrap(); + } + /// + /// Same as DefaultBreakthroughSkill + /// + protected bool DefaultEffectVeiler() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + ClientCard LastChainCard = Util.GetLastChainCard(); + if (LastChainCard != null && (LastChainCard.IsCode(_CardId.GalaxySoldier) && Enemy.Hand.Count >= 3 + || LastChainCard.IsCode(_CardId.EffectVeiler, _CardId.InfiniteImpermanence))) + return false; + return DefaultBreakthroughSkill(); + } + /// + /// Chain common hand traps + /// + protected bool DefaultCalledByTheGrave() + { + int[] targetList = + { + _CardId.MaxxC, + _CardId.LockBird, + _CardId.GhostOgreAndSnowRabbit, + _CardId.AshBlossom, + _CardId.GhostBelle, + _CardId.EffectVeiler, + _CardId.ArtifactLancea + }; + if (Duel.LastChainPlayer == 1) + { + foreach (int id in targetList) + { + if (Util.GetLastChainCard().IsCode(id)) + { + AI.SelectCard(id); + return UniqueFaceupSpell(); + } + } + } + return false; + } + /// + /// Default InfiniteImpermanence effect + /// + protected bool DefaultInfiniteImpermanence() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + // TODO: disable s & t + ClientCard LastChainCard = Util.GetLastChainCard(); + if (LastChainCard != null && (LastChainCard.IsCode(_CardId.GalaxySoldier) && Enemy.Hand.Count >= 3 + || LastChainCard.IsCode(_CardId.EffectVeiler, _CardId.InfiniteImpermanence))) + return false; + return DefaultDisableMonster(); + } + /// + /// Chain the enemy monster, or disable monster like Rescue Rabbit. + /// + protected bool DefaultBreakthroughSkill() + { + if (!DefaultUniqueTrap()) + return false; + return DefaultDisableMonster(); + } + /// + /// Chain the enemy monster, or disable monster like Rescue Rabbit. + /// + protected bool DefaultDisableMonster() + { + if (Duel.Player == 1) + { + ClientCard target = Enemy.MonsterZone.GetShouldBeDisabledBeforeItUseEffectMonster(); + if (target != null) + { + AI.SelectCard(target); + return true; + } + } + + ClientCard LastChainCard = Util.GetLastChainCard(); + + if (LastChainCard != null && LastChainCard.Controller == 1 && LastChainCard.Location == CardLocation.MonsterZone && + !LastChainCard.IsDisabled() && !LastChainCard.IsShouldNotBeTarget() && !LastChainCard.IsShouldNotBeSpellTrapTarget()) + { + AI.SelectCard(LastChainCard); + return true; + } + + if (Bot.BattlingMonster != null && Enemy.BattlingMonster != null) + { + if (!Enemy.BattlingMonster.IsDisabled() && Enemy.BattlingMonster.IsCode(_CardId.EaterOfMillions)) + { + AI.SelectCard(Enemy.BattlingMonster); + return true; + } + } + + if (Duel.Phase == DuelPhase.BattleStart && Duel.Player == 1 && + Enemy.HasInMonstersZone(_CardId.NumberS39UtopiaTheLightning, true)) + { + AI.SelectCard(_CardId.NumberS39UtopiaTheLightning); + return true; + } + + return false; + } + + /// + /// Activate only except this card is the target or we summon monsters. + /// + protected bool DefaultSolemnJudgment() + { + return !Util.IsChainTargetOnly(Card) && !(Duel.Player == 0 && Duel.LastChainPlayer == -1) && !DefaultOnlyHorusSpSummoning() && DefaultTrap(); + } + + /// + /// Activate only except we summon monsters. + /// + protected bool DefaultSolemnWarning() + { + return (Bot.LifePoints > 2000) && !(Duel.Player == 0 && Duel.LastChainPlayer == -1) && !DefaultOnlyHorusSpSummoning() && DefaultTrap(); + } + + /// + /// Activate only except we summon monsters. + /// + protected bool DefaultSolemnStrike() + { + return (Bot.LifePoints > 1500) && !(Duel.Player == 0 && Duel.LastChainPlayer == -1) && !DefaultOnlyHorusSpSummoning() && DefaultTrap(); + } + + /// + /// Check whether only Horus monster is special summoning. + /// If returning true, should not negate the special summon since it can be special summoned again. + /// + /// + protected bool DefaultOnlyHorusSpSummoning() + { + if (Duel.SummoningCards.Count != 0) + { + bool notOnlyHorusFlag = false; + foreach (ClientCard card in Duel.SummoningCards) + { + if (!card.HasSetcode(_Setcode.Horus) || card.LastLocation != CardLocation.Grave) + { + notOnlyHorusFlag = true; + break; + } + } + return !notOnlyHorusFlag; + } + return false; + } + + /// + /// Activate when all enemy monsters have better ATK. + /// + protected bool DefaultTorrentialTribute() + { + return !Util.HasChainedTrap(0) && Util.IsAllEnemyBetter(true); + } + + /// + /// Activate enemy have more S&T. + /// + protected bool DefaultHeavyStorm() + { + return Bot.GetSpellCount() < Enemy.GetSpellCount(); + } + + /// + /// Activate before other winds, if enemy have more than 2 S&T. + /// + protected bool DefaultHarpiesFeatherDusterFirst() + { + return Enemy.GetSpellCount() >= 2; + } + + /// + /// Activate when one enemy monsters have better ATK. + /// + protected bool DefaultHammerShot() + { + return Util.IsOneEnemyBetter(true); + } + + /// + /// Activate when one enemy monsters have better ATK or DEF. + /// + protected bool DefaultDarkHole() + { + return Util.IsOneEnemyBetter(); + } + + /// + /// Activate when one enemy monsters have better ATK or DEF. + /// + protected bool DefaultRaigeki() + { + return Util.IsOneEnemyBetter(); + } + + /// + /// Activate when one enemy monsters have better ATK or DEF. + /// + protected bool DefaultSmashingGround() + { + return Util.IsOneEnemyBetter(); + } + + /// + /// Activate when we have more than 15 cards in deck. + /// + protected bool DefaultPotOfDesires() + { + return Bot.Deck.Count > 15; + } + + /// + /// Set traps only and avoid block the activation of other cards. + /// + protected bool DefaultSpellSet() + { + return (Card.IsTrap() || Card.HasType(CardType.QuickPlay) || DefaultSpellMustSetFirst()) && Bot.GetSpellCountWithoutField() < 4; + } + + /// + /// Summon with no tribute, or with tributes ATK lower. + /// + protected bool DefaultMonsterSummon() + { + if (Card.Level <= 4) + return true; + + if (!UniqueFaceupMonster()) + return false; + int tributecount = (int)Math.Ceiling((Card.Level - 4.0d) / 2.0d); + for (int j = 0; j < 7; ++j) + { + ClientCard tributeCard = Bot.MonsterZone[j]; + if (tributeCard == null) continue; + if (tributeCard.GetDefensePower() < Card.Attack) + tributecount--; + } + return tributecount <= 0; + } + + /// + /// Activate when we have no field. + /// + protected bool DefaultField() + { + return Bot.SpellZone[5] == null; + } + + /// + /// Turn if all enemy is better. + /// + protected bool DefaultMonsterRepos() + { + if (Card.IsMonsterInvincible()) + return Card.IsDefense(); + + if (Card.Attack == 0) + { + if (Card.IsFaceup() && Card.IsAttack()) + return true; + if (Card.IsFaceup() && Card.IsDefense()) + return false; + } + + if (Enemy.HasInMonstersZone(_CardId.BlueEyesChaosMAXDragon, true) && + Card.IsAttack() && (4000 - Card.Defense) * 2 > (4000 - Card.Attack)) + return false; + if (Enemy.HasInMonstersZone(_CardId.BlueEyesChaosMAXDragon, true) && + Card.IsDefense() && Card.IsFaceup() && + (4000 - Card.Defense) * 2 > (4000 - Card.Attack)) + return true; + + bool enemyBetter = Util.IsAllEnemyBetter(); + if (Card.IsAttack() && enemyBetter) + return true; + if (Card.IsDefense() && !enemyBetter && (Card.Attack >= Card.Defense || Card.Attack >= Util.GetBestPower(Enemy))) + return true; + + return false; + } + + /// + /// If spell will be negated + /// + protected bool DefaultSpellWillBeNegated() + { + return (Bot.HasInSpellZone(_CardId.ImperialOrder, true, true) || Enemy.HasInSpellZone(_CardId.ImperialOrder, true)) && !Util.ChainContainsCard(_CardId.ImperialOrder) + || DefaultCheckWhetherCardIsNegated(Card); + } + + /// + /// If trap will be negated + /// + protected bool DefaultTrapWillBeNegated() + { + return (Bot.HasInSpellZone(_CardId.RoyalDecreel, true, true) || Enemy.HasInSpellZone(_CardId.RoyalDecreel, true)) && !Util.ChainContainsCard(_CardId.RoyalDecreel) + || DefaultCheckWhetherCardIsNegated(Card); + } + + /// + /// If spell must set first to activate + /// + protected bool DefaultSpellMustSetFirst() + { + return Bot.HasInSpellZone(_CardId.AntiSpellFragrance, true, true) || Enemy.HasInSpellZone(_CardId.AntiSpellFragrance, true); + } + + /// + /// if spell/trap is the target or enermy activate HarpiesFeatherDuster + /// + protected bool DefaultOnBecomeTarget() + { + if (Util.IsChainTarget(Card)) return true; + int[] destroyAllList = + { + _CardId.EvilswarmExcitonKnight, + _CardId.BlackRoseDragon, + _CardId.JudgmentDragon, + _CardId.TopologicTrisbaena, + _CardId.EvenlyMatched, + _CardId.DivineArsenalAAZEUS_SkyThunder + }; + int[] destroyAllMonsterList = + { + _CardId.DarkHole, + _CardId.InterruptedKaijuSlumber + }; + int[] destroyAllOpponentMonsterList = + { + _CardId.Raigeki + }; + int[] destroyAllOpponentSpellList = + { + _CardId.HarpiesFeatherDuster, + _CardId.DarkMagicAttack + }; + + if (Util.ChainContainsCard(destroyAllList)) return true; + if (Enemy.HasInSpellZone(destroyAllOpponentSpellList, true) && Card.Location == CardLocation.SpellZone) return true; + if (Util.ChainContainsCard(destroyAllMonsterList) && Card.Location == CardLocation.MonsterZone) return true; + if (Duel.CurrentChain.Any(c => c.Controller == 1 && c.IsCode(destroyAllOpponentMonsterList)) && Card.Location == CardLocation.MonsterZone) return true; + if (lightningStormOption == 0 && Card.Location == CardLocation.MonsterZone && Card.IsAttack()) return true; + if (lightningStormOption == 1 && Card.Location == CardLocation.SpellZone) return true; + // TODO: ChainContainsCard(id, player) + return false; + } + /// + /// Chain enemy activation or summon. + /// + protected bool DefaultTrap() + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return (Duel.LastChainPlayer == -1 && Duel.LastSummonPlayer != 0) || Duel.LastChainPlayer == 1; + } + + /// + /// Activate when avail and no other our trap card in this chain or face-up. + /// + protected bool DefaultUniqueTrap() + { + if (Util.HasChainedTrap(0)) + return false; + + return UniqueFaceupSpell(); + } + + /// + /// Check no other our spell or trap card with same name face-up. + /// + protected bool UniqueFaceupSpell() + { + return !Bot.GetSpells().Any(card => card.IsCode(Card.Id) && card.IsFaceup()); + } + + /// + /// Check no other our monster card with same name face-up. + /// + protected bool UniqueFaceupMonster() + { + return !Bot.GetMonsters().Any(card => card.IsCode(Card.Id) && card.IsFaceup()); + } + + /// + /// Dumb way to avoid the bot chain in mess. + /// + protected bool DefaultDontChainMyself() + { + if (Type != ExecutorType.Activate) + return true; + if (Executors.Any(exec => exec.Type == Type && exec.CardId == Card.Id)) + return false; + return Duel.LastChainPlayer != 0; + } + + /// + /// Draw when we have lower LP, or destroy it. Can be overrided. + /// + protected bool DefaultChickenGame() + { + if (Executors.Count(exec => exec.Type == Type && exec.CardId == Card.Id) > 1) + return false; + if (Card.IsFacedown()) + return true; + if (Bot.LifePoints <= 1000) + return false; + if (Bot.LifePoints <= Enemy.LifePoints && ActivateDescription == Util.GetStringId(_CardId.ChickenGame, 0)) + return true; + if (Bot.LifePoints > Enemy.LifePoints && ActivateDescription == Util.GetStringId(_CardId.ChickenGame, 1)) + return true; + return false; + } + + /// + /// Draw when we have Dark monster in hand,and banish random one. Can be overrided. + /// + protected bool DefaultAllureofDarkness() + { + ClientCard target = Bot.Hand.FirstOrDefault(card => card.HasAttribute(CardAttribute.Dark)); + return target != null; + } + + /// + /// Clever enough. + /// + protected bool DefaultDimensionalBarrier() + { + const int RITUAL = 0; + const int FUSION = 1; + const int SYNCHRO = 2; + const int XYZ = 3; + const int PENDULUM = 4; + if (Duel.Player != 0) + { + List monsters = Enemy.GetMonsters(); + int[] levels = new int[13]; + bool tuner = false; + bool nontuner = false; + foreach (ClientCard monster in monsters) + { + if (!monster.HasType(CardType.Xyz | CardType.Link)) + { + if (monster.HasType(CardType.Tuner)) tuner = true; + else nontuner = true; + if (!monster.HasType(CardType.Token)) levels[monster.Level] = levels[monster.Level] + 1; + } + + if (monster.IsOneForXyz()) + { + AI.SelectOption(XYZ); + return true; + } + } + if (tuner && nontuner) + { + AI.SelectOption(SYNCHRO); + return true; + } + for (int i=1; i<=12; i++) + { + if (levels[i]>1) + { + AI.SelectOption(XYZ); + return true; + } + } + ClientCard l = Enemy.SpellZone[6]; + ClientCard r = Enemy.SpellZone[7]; + if (l != null && r != null && l.LScale != r.RScale) + { + AI.SelectOption(PENDULUM); + return true; + } + } + ClientCard lastchaincard = Util.GetLastChainCard(); + if (Duel.LastChainPlayer == 1 && lastchaincard != null && !lastchaincard.IsDisabled() + && (lastchaincard.HasType(CardType.Spell | CardType.Trap) || lastchaincard.Location == CardLocation.MonsterZone)) + { + if (lastchaincard.HasType(CardType.Ritual)) + { + AI.SelectOption(RITUAL); + return true; + } + if (lastchaincard.HasType(CardType.Fusion)) + { + AI.SelectOption(FUSION); + return true; + } + if (lastchaincard.HasType(CardType.Synchro)) + { + AI.SelectOption(SYNCHRO); + return true; + } + if (lastchaincard.HasType(CardType.Xyz)) + { + AI.SelectOption(XYZ); + return true; + } + if (lastchaincard.IsFusionSpell()) + { + AI.SelectOption(FUSION); + return true; + } + } + if (Util.IsChainTarget(Card)) + { + AI.SelectOption(XYZ); + return true; + } + return false; + } + + /// + /// Clever enough + /// + protected bool DefaultInterruptedKaijuSlumber() + { + if (Card.Location == CardLocation.Grave) + { + AI.SelectCard( + _CardId.GamecieltheSeaTurtleKaiju, + _CardId.KumongoustheStickyStringKaiju, + _CardId.GadarlatheMysteryDustKaiju, + _CardId.RadiantheMultidimensionalKaiju, + _CardId.DogorantheMadFlameKaiju, + _CardId.ThunderKingtheLightningstrikeKaiju, + _CardId.JizukirutheStarDestroyingKaiju + ); + return true; + } + + if (DefaultDarkHole()) + { + AI.SelectCard( + _CardId.JizukirutheStarDestroyingKaiju, + _CardId.ThunderKingtheLightningstrikeKaiju, + _CardId.DogorantheMadFlameKaiju, + _CardId.RadiantheMultidimensionalKaiju, + _CardId.GadarlatheMysteryDustKaiju, + _CardId.KumongoustheStickyStringKaiju, + _CardId.GamecieltheSeaTurtleKaiju + ); + AI.SelectNextCard( + _CardId.SuperAntiKaijuWarMachineMechaDogoran, + _CardId.GamecieltheSeaTurtleKaiju, + _CardId.KumongoustheStickyStringKaiju, + _CardId.GadarlatheMysteryDustKaiju, + _CardId.RadiantheMultidimensionalKaiju, + _CardId.DogorantheMadFlameKaiju, + _CardId.ThunderKingtheLightningstrikeKaiju + ); + return true; + } + + return false; + } + + /// + /// Clever enough. + /// + protected bool DefaultKaijuSpsummon() + { + IList kaijus = new[] { + _CardId.JizukirutheStarDestroyingKaiju, + _CardId.GadarlatheMysteryDustKaiju, + _CardId.GamecieltheSeaTurtleKaiju, + _CardId.RadiantheMultidimensionalKaiju, + _CardId.KumongoustheStickyStringKaiju, + _CardId.ThunderKingtheLightningstrikeKaiju, + _CardId.DogorantheMadFlameKaiju, + _CardId.SuperAntiKaijuWarMachineMechaDogoran + }; + foreach (ClientCard monster in Enemy.GetMonsters()) + { + if (monster.IsCode(kaijus)) + return Card.GetDefensePower() > monster.GetDefensePower(); + } + ClientCard card = Enemy.MonsterZone.GetFloodgate(); + if (card != null) + { + AI.SelectCard(card); + return true; + } + card = Enemy.MonsterZone.GetDangerousMonster(); + if (card != null) + { + AI.SelectCard(card); + return true; + } + card = Util.GetOneEnemyBetterThanValue(Card.GetDefensePower()); + if (card != null) + { + AI.SelectCard(card); + return true; + } + return false; + } + + /// + /// Summon when we don't have monster attack higher than enemy's. + /// + protected bool DefaultNumberS39UtopiaTheLightningSummon() + { + int bestBotAttack = Util.GetBestAttack(Bot); + return Util.IsOneEnemyBetterThanValue(bestBotAttack, false); + } + + /// + /// Activate if the card is attack pos, and its attack is below 5000, when the enemy monster is attack pos or not useless faceup defense pos + /// + protected bool DefaultNumberS39UtopiaTheLightningEffect() + { + return Card.IsAttack() && Card.Attack < 5000 && (Enemy.BattlingMonster.IsAttack() || Enemy.BattlingMonster.IsFacedown() || Enemy.BattlingMonster.GetDefensePower() >= Card.Attack); + } + + /// + /// Summon when it can and should use effect. + /// + protected bool DefaultEvilswarmExcitonKnightSummon() + { + int selfCount = Bot.GetMonsterCount() + Bot.GetSpellCount() + Bot.GetHandCount(); + int oppoCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount() + Enemy.GetHandCount(); + return (selfCount - 1 < oppoCount) && DefaultEvilswarmExcitonKnightEffect(); + } + + /// + /// Activate when we have less cards than enemy's, or the atk sum of we is lower than enemy's. + /// + protected bool DefaultEvilswarmExcitonKnightEffect() + { + int selfCount = Bot.GetMonsterCount() + Bot.GetSpellCount(); + int oppoCount = Enemy.GetMonsterCount() + Enemy.GetSpellCount(); + + if (selfCount < oppoCount) + return true; + + int selfAttack = Bot.GetMonsters().Sum(monster => (int?)monster.GetDefensePower()) ?? 0; + int oppoAttack = Enemy.GetMonsters().Sum(monster => (int?)monster.GetDefensePower()) ?? 0; + + return selfAttack < oppoAttack; + } + + /// + /// Summon in main2, or when the attack of we is lower than enemy's, but not when enemy have monster higher than 2500. + /// + protected bool DefaultStardustDragonSummon() + { + int selfBestAttack = Util.GetBestAttack(Bot); + int oppoBestAttack = Util.GetBestPower(Enemy); + return (selfBestAttack <= oppoBestAttack && oppoBestAttack <= 2500) || Util.IsTurn1OrMain2(); + } + + /// + /// Negate enemy's destroy effect, and revive from grave. + /// + protected bool DefaultStardustDragonEffect() + { + return (Card.Location == CardLocation.Grave) || Duel.LastChainPlayer == 1; + } + + /// + /// Summon when enemy have card which we must solve. + /// + protected bool DefaultCastelTheSkyblasterMusketeerSummon() + { + return Util.GetProblematicEnemyCard() != null; + } + + /// + /// Bounce the problematic enemy card. Ignore the 1st effect. + /// + protected bool DefaultCastelTheSkyblasterMusketeerEffect() + { + if (ActivateDescription == Util.GetStringId(_CardId.CastelTheSkyblasterMusketeer, 0)) + return false; + ClientCard target = Util.GetProblematicEnemyCard(); + if (target != null) + { + AI.SelectCard(0); + AI.SelectNextCard(target); + return true; + } + return false; + } + + /// + /// Summon when it should use effect, or when the attack of we is lower than enemy's, but not when enemy have monster higher than 3000. + /// + protected bool DefaultScarlightRedDragonArchfiendSummon() + { + int selfBestAttack = Util.GetBestAttack(Bot); + int oppoBestAttack = Util.GetBestPower(Enemy); + return (selfBestAttack <= oppoBestAttack && oppoBestAttack <= 3000) || DefaultScarlightRedDragonArchfiendEffect(); + } + + protected bool DefaultTimelordSummon() + { + return Bot.GetMonsterCount() == 0; + } + + /// + /// Activate when we have less monsters than enemy, or when enemy have more than 3 monsters. + /// + protected bool DefaultScarlightRedDragonArchfiendEffect() + { + int selfCount = Bot.GetMonsters().Count(monster => !monster.Equals(Card) && monster.IsSpecialSummoned && monster.HasType(CardType.Effect) && monster.Attack <= Card.Attack); + int oppoCount = Enemy.GetMonsters().Count(monster => monster.IsSpecialSummoned && monster.HasType(CardType.Effect) && monster.Attack <= Card.Attack); + return selfCount <= oppoCount && oppoCount > 0 || oppoCount >= 3; + } + + /// + /// Clever enough. + /// + protected bool DefaultHonestEffect() + { + if (Card.Location == CardLocation.Hand) + { + if (DefaultCheckWhetherCardIsNegated(Card)) return false; + return Bot.BattlingMonster.IsAttack() && + ((Bot.BattlingMonster.Attack < Enemy.BattlingMonster.Attack) || Bot.BattlingMonster.Attack >= Enemy.LifePoints + || ((Bot.BattlingMonster.Attack < Enemy.BattlingMonster.Defense) && (Bot.BattlingMonster.Attack + Enemy.BattlingMonster.Attack > Enemy.BattlingMonster.Defense))); + } + + return Util.IsTurn1OrMain2(); + } + + /// + /// Always activate + /// + protected bool DefaultVaylantzWorld_ShinraBansho() + { + if (DefaultSpellWillBeNegated()) { + return false; + } + + return true; + } + + /// + /// Select enemy's best monster + /// + protected bool DefaultVaylantzWorld_KonigWissen() + { + if (DefaultSpellWillBeNegated()) { + return false; + } + + List monsters = Enemy.GetMonsters(); + if (monsters.Count == 0) { + return false; + } + + List targetList = new List(); + List floodgateCards = monsters + .Where(card => card?.Data != null && card.IsFloodgate() && card.IsFaceup() && !card.IsShouldNotBeTarget()) + .OrderByDescending(card => card.Attack).ToList(); + List dangerousCards = monsters + .Where(card => card?.Data != null && card.IsMonsterDangerous() && card.IsFaceup() && !card.IsShouldNotBeTarget()) + .OrderByDescending(card => card.Attack).ToList(); + List attackOrderedCards = monsters + .Where(card => card?.Data != null && card.HasType(CardType.Monster) && card.IsFaceup() && card.IsShouldNotBeTarget()) + .OrderByDescending(card => card.Attack).ToList(); + + targetList.AddRange(floodgateCards); + targetList.AddRange(dangerousCards); + targetList.AddRange(attackOrderedCards); + + if (targetList?.Count > 0) + { + AI.SelectCard(targetList); + return true; + } + + return false; + } + + protected bool DefaultCheckWhetherCardIsNegated(ClientCard card) + { + if (card == null) return true; + if (card.Data == null) return card.IsDisabled(); + int originId = card.Data.Alias; + if (originId == 0) originId = card.Data.Id; + return crossoutDesignatorIdList.Contains(originId) + || (calledbytheGraveIdCountMap.ContainsKey(originId) && calledbytheGraveIdCountMap[originId] > 0) + || (card.IsDisabled() && ((int)card.Location & (int)CardLocation.Onfield) > 0); + } + + protected bool DefaultCheckWhetherCardIdIsNegated(int cardId) + { + return crossoutDesignatorIdList.Contains(cardId) + || (calledbytheGraveIdCountMap.ContainsKey(cardId) && calledbytheGraveIdCountMap[cardId] > 0); + } + + protected int GetCalledbytheGraveIdCount(int cardId) + { + if (!calledbytheGraveIdCountMap.ContainsKey(cardId)) return 0; + return calledbytheGraveIdCountMap[cardId]; + } + + + protected virtual bool DefaultSetForDiabellze() + { + if (Card == null) return false; + if (Card.Id == _CardId.PotOfExtravagance) return false; + if (Enemy.HasInMonstersZone(_CardId.DiabellzeOfTheOriginalSin, true, faceUp: true) && Card.HasType(CardType.Spell) && !Card.HasType(CardType.QuickPlay)) + { + if (Bot.SpellZone.Any(c => c != null && Duel.MainPhase.ActivableCards.Contains(c) && c.HasType(CardType.Spell) && !Card.HasType(CardType.QuickPlay) && c.IsFacedown())) + { + return false; + } + foreach (CardExecutor exec in Executors) + { + if (exec.Type == ExecutorType.Activate && exec.CardId == Card.Id) + { + if (exec.Func == null || exec.Func()) + { + return true; + } + } + } + } + return false; + } + + /// + /// Check whether all available spell columns are negated. + /// + /// + protected bool DefaultCheckAllAvailableSpellColumnNegated() + { + for (int i = 0; i < 5; i++) { + // occupied + if (Bot.SpellZone[i] != null) { + continue; + } + // negated + if (infiniteImpermanenceNegatedColumns.Contains(i)) { + continue; + } + // have empty column that's not negated + return false; + } + // all columns are negated + return true; + } + + /// + /// Check whether the spells will be negated. + /// + /// + /// + protected bool DefaultCheckWhetherSpellActivateWillBeNegated(ClientCard card) + { + if (card == null) return false; + if (card.Location == CardLocation.SpellZone) + { + return infiniteImpermanenceNegatedColumns.Contains(card.Sequence); + } + // check whether will be negated by Infinite Impermanence + return DefaultCheckAllAvailableSpellColumnNegated(); + } + + /// + /// Check whether bot can search cards from deck. + /// + /// + protected bool DefaultCheckWhetherBotCanSearch() + { + if (resolvedEffectIdList.Contains(_CardId.LockBird)) + return false; + if (mistakenArrestAffectedCount > 0) + return false; + if (Bot.HasInMonstersZone(_CardId.ThunderKingRaiOh, notDisabled: true, faceUp: true) + || Enemy.HasInMonstersZone(_CardId.ThunderKingRaiOh, notDisabled: true, faceUp: true)) + return false; + if (Enemy.HasInMonstersZone(_CardId.ThunderDragonColossus)) + return false; + if (Bot.HasInSpellZone(_CardId.DeckLockdown, notDisabled: true, faceUp: true) + || Enemy.HasInSpellZone(_CardId.DeckLockdown, notDisabled: true, faceUp: true) + || Bot.HasInSpellZone(_CardId.Mistake, notDisabled: true, faceUp: true) + || Enemy.HasInSpellZone(_CardId.Mistake, notDisabled: true, faceUp: true)) + return false; + if (Enemy.HasInSpellZone(_CardId.DoomZDestruction, notDisabled: true, faceUp: true)) + return false; + return true; + } + + /// + /// Check whether enemy can draw cards. + /// + /// + protected bool DefaultCheckWhetherEnemyCanDraw() + { + if (resolvedEffectIdList.Contains(_CardId.LockBird)) + return false; + return true; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/DangerousMonster.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/DangerousMonster.cs new file mode 100644 index 0000000..db7cd17 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/DangerousMonster.cs @@ -0,0 +1,34 @@ +namespace WindBot.Game.AI.Enums +{ + /// + /// Cards that are dangerous to attack. + /// + 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 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/Floodgate.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/Floodgate.cs new file mode 100644 index 0000000..8fc912c --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/Floodgate.cs @@ -0,0 +1,277 @@ +namespace WindBot.Game.AI.Enums +{ + /// + /// Cards that restrict player from performing some action. Bot will preferentially destroy them. + /// + 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 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/FusionSpell.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/FusionSpell.cs new file mode 100644 index 0000000..5f9b061 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/FusionSpell.cs @@ -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 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/InvincibleMonster.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/InvincibleMonster.cs new file mode 100644 index 0000000..4b2f5d8 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/InvincibleMonster.cs @@ -0,0 +1,145 @@ +namespace WindBot.Game.AI.Enums +{ + /// + /// Cards that are invincible to battle and should always attack to use effect. + /// + 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 + } + /// + /// Cards that are invincible to battle. + /// + 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 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/NotBeSynchroMaterialMonster.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/NotBeSynchroMaterialMonster.cs new file mode 100644 index 0000000..0323312 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/NotBeSynchroMaterialMonster.cs @@ -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 + + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/NotBeXyzMaterialMonster.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/NotBeXyzMaterialMonster.cs new file mode 100644 index 0000000..94c8f1f --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/NotBeXyzMaterialMonster.cs @@ -0,0 +1,14 @@ +namespace WindBot.Game.AI.Enums +{ + public enum NotBeXyzMaterialMonster + { + YellowDuston = 16366810, + BlueDuston = 40217358, + Centerfrog = 47346782, + GreenDuston = 52182715, + RedDuston = 61019812, + EaterofMillions = 63845230, + PutridPuddingBodyBuddies = 85101097, + Click_Echo = 2992467 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/OneForXyz.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/OneForXyz.cs new file mode 100644 index 0000000..3f1a79e --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/OneForXyz.cs @@ -0,0 +1,28 @@ +namespace WindBot.Game.AI.Enums +{ + public enum OneForXyz + { + ZoodiacThoroughblade = 77150143, + ZoodiacViper = 31755044, + ZoodiacCluckle = 20155904, + ZoodiacRabbina = 4367330, + ZoodiacRam = 4145852, + ZoodiacMarmorat = 78872731, + ZoodiacTigress = 11510448, + ZoodiacHammerkong = 14970113, + ZoodiacLyca = 41375811, + ZoodiacDrancia = 48905153, + ZoodiacBoarbow = 74393852, + ZoodiacBroadbull = 85115440, + Number62 = 31801517, + GalaxyEyesCipherDragon = 18963306, + Number107 = 88177324, + CyberDragonNova = 58069384, + Number39 = 84013237, + Argostars_GloriousAdra = 91438674, + Argostars_LightningTydeu = 65889305, + Argostars_SwiftCapane = 91284003, + Argostars_SlayerEteo = 38379052, + Argostars_FierceParthe = 21050476 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/PreventActivationEffectInBattle.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/PreventActivationEffectInBattle.cs new file mode 100644 index 0000000..74f5b86 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/PreventActivationEffectInBattle.cs @@ -0,0 +1,17 @@ +namespace WindBot.Game.AI.Enums +{ + public enum PreventActivationEffectInBattle + { + Deskbot009 = 25494711, + ArchfiendBlackSkullDragon = 45349196, + FrightfurChimera = 83866861, + GladiatorBeastNerokius = 29357956, + GemKnightCitrine = 67985943, + FrightfurSheep = 57477163, + SamuraiDestroyer = 40509732, + ArmadesKeeperOfBoundaries = 88033975, + NumberS39UtopiaTheLightning = 56832966, + DualAvatarEmpoweredKonGyo = 33026283, + GoukiTheTyrantOgre = 7782069 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldBeDisabledBeforeItUseEffectMonster.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldBeDisabledBeforeItUseEffectMonster.cs new file mode 100644 index 0000000..b706a02 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldBeDisabledBeforeItUseEffectMonster.cs @@ -0,0 +1,78 @@ +namespace WindBot.Game.AI.Enums +{ + /// + /// Monsters that release or banish itself to use effect. So them should be disabled (with Breakthrough Skill) before it use effect. + /// + public enum ShouldBeDisabledBeforeItUseEffectMonster + { + MachinaMegaform = 51617185, + DarkSummoningBeast = 87917187, + GemKnightAlexandrite = 90019393, + RedEyesRetroDragon = 53485634, + DeepSweeper = 8649148, + BeastWarriorPuma = 16796157, + ZefrasaberSwordmasteroftheNekroz = 84388461, + CipherWing = 81974607, + MadolcheAnjelly = 34680482, + PlanetPathfinder = 97526666, + RescueCat = 14878871, + RescueHamster = 50485594, + RescueFerret = 56343672, + RescueRabbit = 85138716, + GalaxyWizard = 98555327, + Backlinker = 71172240, + Merlin = 3580032, + CrystalVanguard = 87475570, + TemperanceofProphecy = 87608852, + Kuribandit = 16404809, + PhotonLizard = 38973775, + SuperheavySamuraiFlutist = 27978707, + ConstellarRasalhague = 70624184, + CardcarD = 45812361, + UnifloraMysticalBeastoftheForest = 36318200, + BusterWhelpoftheDestructionSwordsman = 49823708, + GalaxyEyesCloudragon = 9260791, + SylvanPrincessprout = 20579538, + AltergeistPixiel = 57769391, + AbyssActorExtras = 88412339, + PerformapalTrumpWitch = 91584698, + RaidraptorLastStrix = 97219708, + MythicalBeastJackal = 91182675, + TimeMaiden = 27107590, + SuperQuantalFairyAlphan = 58753372, + TheBlackStoneofLegend = 66574418, + PaladinofDarkDragon = 71408082, + PaladinofPhotonDragon = 85346853, + TwinPhotonLizard = 29455728, + TimeThiefRegulator = 19891131, + MathmechNabla = 53577438, + NidhoggGeneraiderBossofIce = 49275969, + HoarrGeneraiderBossofRumbling = 68199168, + RedFamiliar = 8372133, + AccesscodeTalker = 86066372, + ChaosSummoningBeast = 27439792, + + CosmoBrain = 85679527, + ShiranuiSolitaire = 94801854, + Mixeroid = 71340250, + LonefireBlossom = 48686504, + BrotherhoodoftheFireFist_Leopard = 39699564, + SpringansPedor = 56818977, + GizmekNaganakitheSunriseSignaler = 96399967, + MyutantMutant = 26561172, + ThreeEyedGhost = 31464658, + UrsarcticPolarStar = 62714453, + BattlinBoxerPromoter = 83315222, + TGRocketSalamander = 77392987, + GGolemRockHammer = 98875863, + WishDragon = 64583600, + ChaosWitch = 30327674, + FissioningMotherSpider = 34034150, + AncientGearStatue = 32762201, + SplittingPlanarian = 44175358, + TestBear = 62076252, + RescueHedgehog = 99742859, + SuperQuantalFairyZetan = 66646087, + LightWaterDragon = 82616239 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeMonsterTarget.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeMonsterTarget.cs new file mode 100644 index 0000000..813cfb1 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeMonsterTarget.cs @@ -0,0 +1,23 @@ +namespace WindBot.Game.AI.Enums +{ + /// + /// Cards that are can't be selected as target of monster's effect, or immuned to monster's effect. + /// So them shouldn't be tried to be selected as target of monster at most times. + /// + public enum ShouldNotBeMonsterTarget + { + TheLegendaryFishermanII = 19801646, + GaiaDraketheUniversalForce = 58601383, + FirstoftheDragons = 10817524, + Tatsunoko = 55863245, + CXyzSimontheGreatMoralLeader = 41147577, + PaleozoicAnomalocaris = 61307542, + PaleozoicOpabinia = 37649320, + BorreloadDragon = 31833038, + BorrelendDragon = 98630720, + DrytronMeteonisDraconids = 69815951, + MyutantBeast = 34695290, + VeidosTheDragonOfEndlessDarkness = 8540986, + FirstOfTheDragonlords = 53466722 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeSpellTarget.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeSpellTarget.cs new file mode 100644 index 0000000..9bdc598 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeSpellTarget.cs @@ -0,0 +1,15 @@ +namespace WindBot.Game.AI.Enums +{ + /// + /// Cards that are can't be selected as target of spell&trap's effect, or immuned to spell&trap's effect. + /// So them shouldn't be tried to be selected as target of spell&trap at most times. + /// + public enum ShouldNotBeSpellTrapTarget + { + ApoqliphortTowers = 27279764, + ApoqliphortSkybase = 40061558, + TheLegendaryFishermanIII = 44968687, + ChaosAncientGearGiant = 51788412, + DrytronMeteonisQuadrantids = 95209656 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeTarget.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeTarget.cs new file mode 100644 index 0000000..41b4689 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Enums/ShouldNotBeTarget.cs @@ -0,0 +1,59 @@ +namespace WindBot.Game.AI.Enums +{ + /// + /// Cards that are can't be selected as target, or immuned to most effect. + /// So them shouldn't be tried to be selected as target at most times. + /// + public enum ShouldNotBeTarget + { + DivineSerpentGeh = 82103466, + ObelisktheTormentor = 10000000, + TheWingedDragonofRaSphereMode = 10000080, + TheWingedDragonofRaImmortalPhoenix = 10000090, + KozmoDarkPlanet = 85991529, + ZushintheSleepingGiant = 67547370, + TheLegendaryExodiaIncarnate = 58604027, + KozmoDarkEclipser = 64063868, + KozmoDarkDestroyer = 55885348, + KozmoForerunner = 20849090, + MajespecterUnicornKirin = 31178212, + WorldLegacyWorldShield = 55787576, + KiwiMagicianGirl = 82627406, + MajespecterFoxKyubi = 94784213, + MajespecterToadOgama = 645794, + MajespecterCrowYata = 68395509, + MajespecterRaccoonBunbuku = 31991800, + MajespecterCatNekomata = 5506791, + HazyFlameHydra = 8696773, + HazyFlameMantikor = 96051150, + HazyFlameHyppogrif = 31303283, + HazyFlameCerbereus = 38525760, + HazyFlameSphynx = 1409474, + HazyFlamePeryton = 37803172, + HazyFlameGriffin = 74010769, + BlueEyesChaosMAXDragon = 55410871, + BlueEyesChaosDragon = 20654247, + SupremeKingZARC = 13331639, + CrimsonNovaTrinitytheDarkCubicLord = 72664875, + LunalightLeoDancer = 24550676, + TimaeustheKnightofDestiny = 53315891, + DantePilgrimoftheBurningAbyss = 18386170, + AncientGearHowitzer = 87182127, + InvokedCocytus = 85908279, + LyriluscIndependentNightingale = 76815942, + FlowerCardianLightshower = 42291297, + YaziEviloftheYangZing = 43202238, + RaidraptorUltimateFalcon = 86221741, + DisdainfulBirdofParadise = 27240101, + DarkestDiabolosLordOfTheLair = 50383626, + Blackwing_FullArmoredWing = 54082269, + DragunofRedEyes = 37818794, + RedEyesBDragon = 74677422, // sometimes the name of DragunofRedEyes will be changed to RedEyesBDragon + TheArrivalCyberseIgnister = 11738489, + MajespecterPorcupineYamaarashi = 51073802, + RaidraptorRisingRebellionFalcon = 71222868, + Number97Draglubion = 28400508, + SaintAzamina = 85065943, + LunalightLigerDancer = 54701958 + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Executor.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Executor.cs new file mode 100644 index 0000000..becbb44 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Executor.cs @@ -0,0 +1,316 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using YGOSharp.OCGWrapper.Enums; +using WindBot; +using WindBot.Game; +using WindBot.Game.AI; + +namespace WindBot.Game.AI +{ + public abstract class Executor + { + public string Deck { get; set; } + public Duel Duel { get; private set; } + public IList Executors { get; private set; } + public GameAI AI { get; private set; } + public AIUtil Util { get; private set; } + + protected ExecutorType Type { get; private set; } + protected ClientCard Card { get; private set; } + protected int ActivateDescription { get; private set; } + protected int CurrentTiming { get; private set; } + + protected ClientField Bot { get; private set; } + protected ClientField Enemy { get; private set; } + + protected Executor(GameAI ai, Duel duel) + { + Duel = duel; + AI = ai; + Util = new AIUtil(duel); + Executors = new List(); + + Bot = Duel.Fields[0]; + Enemy = Duel.Fields[1]; + } + + public virtual int OnRockPaperScissors() + { + return Program.Rand.Next(1, 4); + } + + public virtual bool OnSelectHand() + { + return Program.Rand.Next(2) > 0; + } + + /// + /// Called when the AI has to decide if it should attack + /// + /// List of monsters that can attcack. + /// List of monsters of enemy. + /// A new BattlePhaseAction containing the action to do. + public virtual BattlePhaseAction OnBattle(IList attackers, IList defenders) + { + // For overriding + return null; + } + + /// + /// Called when the AI has to decide which card to attack first + /// + /// List of monsters that can attcack. + /// List of monsters of enemy. + /// The card to attack first. + public virtual ClientCard OnSelectAttacker(IList attackers, IList defenders) + { + // For overriding + return null; + } + + public virtual BattlePhaseAction OnSelectAttackTarget(ClientCard attacker, IList defenders) + { + // Overrided in DefaultExecutor + return null; + } + + public virtual bool OnPreBattleBetween(ClientCard attacker, ClientCard defender) + { + // Overrided in DefaultExecutor + return true; + } + + public virtual bool OnPreActivate(ClientCard card) + { + // Overrided in DefaultExecutor + return true; + } + + public virtual void OnChaining(int player, ClientCard card) + { + // For overriding + } + + public virtual void OnChainSolved(int chainIndex) + { + // For overriding + } + + public virtual void OnChainEnd() + { + // For overriding + } + + public virtual void OnReceivingAnnouce(int player, int data) + { + // For overriding + } + + public virtual void OnNewPhase() + { + // Some AI need do something on new phase + } + public virtual void OnNewTurn() + { + // Some AI need do something on new turn + } + + public virtual void OnDraw(int player) + { + // Some AI need do something on draw + } + + /// + /// Called when a PlayerHint is received (e.g. effect description add/remove; can be used to track "once per turn" usage). + /// + /// Player index + /// Hint type, see PlayerHintType (DescAdd=6, DescRemove=7) + /// Effect description id (peffect->description) + public virtual void OnPlayerHint(int player, int hintType, int description) + { + // For overriding + } + + /// + /// Called when a zone hint is received. + /// + /// Player index. + /// Zone data (hinted zones, bit field). + public virtual void OnHintZone(int player, int zone) + { + // For overriding + } + + public virtual void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + // Some AI need do something on card's moving + } + + public virtual IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + // For overriding + return null; + } + + public virtual IList OnSelectSum(IList cards, int sum, int min, int max, int hint, bool mode) + { + // For overriding + return null; + } + + public virtual IList OnSelectFusionMaterial(IList cards, int min, int max) + { + // For overriding + return null; + } + + public virtual IList OnSelectSynchroMaterial(IList cards, int sum, int min, int max) + { + // For overriding + return null; + } + + public virtual IList OnSelectXyzMaterial(IList cards, int min, int max) + { + // For overriding + return null; + } + + public virtual IList OnSelectLinkMaterial(IList cards, int min, int max) + { + // For overriding + return null; + } + + public virtual IList OnSelectRitualTribute(IList cards, int sum, int min, int max) + { + // For overriding + return null; + } + + public virtual IList OnSelectPendulumSummon(IList cards, int max) + { + // For overriding + return null; + } + + public virtual IList OnCardSorting(IList cards) + { + // For overriding + return null; + } + + public virtual void OnSelectChain(IList cards) + { + return; + } + + public virtual bool OnSelectYesNo(int desc) + { + return true; + } + + public virtual int OnSelectOption(IList options) + { + return -1; + } + + public virtual int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + // For overriding + return 0; + } + + public virtual CardPosition OnSelectPosition(int cardId, IList positions) + { + // Overrided in DefaultExecutor + return 0; + } + + public virtual bool OnSelectBattleReplay() + { + // Overrided in DefaultExecutor + return false; + } + + /// + /// Called when the executor type is SummonOrSet + /// + /// True if select to set the monster. + public virtual bool OnSelectMonsterSummonOrSet(ClientCard card) + { + // Overrided in DefaultExecutor + return false; + } + + /// + /// Called when bot is going to annouce a card + /// + /// Available card's ids. + /// Card's id to annouce. + public virtual int OnAnnounceCard(IList avail) + { + // For overriding + return 0; + } + + /// + /// Called when card is successfully special summoned. + /// Used on monsters that can only special summoned once per turn. + /// + public virtual void OnSpSummoned() + { + // For overriding + return; + } + + /// + /// Set global variables Type, Card, ActivateDescription for Executor + /// + public void SetCard(ExecutorType type, ClientCard card, int description, int timing = -1) + { + Type = type; + Card = card; + ActivateDescription = description; + CurrentTiming = timing; + } + + /// + /// Do the action for the card if func return true. + /// + public void AddExecutor(ExecutorType type, int cardId, Func func) + { + Executors.Add(new CardExecutor(type, cardId, func)); + } + + /// + /// Do the action for the card if available. + /// + public void AddExecutor(ExecutorType type, int cardId) + { + Executors.Add(new CardExecutor(type, cardId, null)); + } + + /// + /// Do the action for every card if func return true. + /// + public void AddExecutor(ExecutorType type, Func func) + { + Executors.Add(new CardExecutor(type, -1, func)); + } + + /// + /// Do the action for every card if no other Executor is added to it. + /// + public void AddExecutor(ExecutorType type) + { + Executors.Add(new CardExecutor(type, -1, DefaultNoExecutor)); + } + + private bool DefaultNoExecutor() + { + return Executors.All(exec => exec.Type != Type || exec.CardId != Card.Id); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/ExecutorType.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/ExecutorType.cs new file mode 100644 index 0000000..0a1f33c --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/ExecutorType.cs @@ -0,0 +1,17 @@ +namespace WindBot.Game.AI +{ + public enum ExecutorType + { + Summon, + SpSummon, + Repos, + MonsterSet, + SpellSet, + Activate, + SummonOrSet, + GoToBattlePhase, + GoToMainPhase2, + GoToEndPhase, + Surrender + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/HintMsg.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/HintMsg.cs new file mode 100644 index 0000000..2f868d0 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/HintMsg.cs @@ -0,0 +1,67 @@ +namespace WindBot.Game.AI +{ + public static class HintMsg + { + public const int Release = 500, + Discard = 501, + Destroy = 502, + Remove = 503, + ToGrave = 504, + ReturnToHand = 505, + AddToHand = 506, + ToDeck = 507, + Summon = 508, + SpSummon = 509, + Set = 510, + FusionMaterial = 511, + SynchroMaterial = 512, + XyzMaterial = 513, + Faceup = 514, + Facedown = 515, + Attack = 516, + Defense = 517, + Equip = 518, + RemoveXyz = 519, + Control = 520, + DestroyReplace = 521, + FaceupAttack = 522, + FaceupDefense = 523, + FacedownAttack = 524, + FacedownDefense = 525, + Confirm = 526, + ToField = 527, + PosChange = 528, + Self = 529, + Oppo = 530, + Tribute = 531, + DeattachFrom = 532, + LinkMaterial = 533, + AttackTarget = 549, + Effect = 550, + Target = 551, + Coin = 552, + Dice = 553, + CardType = 554, + Option = 555, + ResolveEffect = 556, + Select = 560, + Position = 561, + Attribute = 562, + Race = 563, + Code = 564, + Number = 565, + LvRank = 567, + ResolveCard = 568, + Zone = 569, + DisableZone = 570, + ToZone = 571, + Counter = 572, + Disable = 573, + OperateCard = 574, + RITUAL = 1057, + FUSION = 1056, + SYNCHRO = 1063, + XYZ = 1073, + PENDULUM = 1074; + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Opcodes.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Opcodes.cs new file mode 100644 index 0000000..8a45b48 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Opcodes.cs @@ -0,0 +1,19 @@ +namespace WindBot.Game.AI +{ + public static class Opcodes + { + public const int OPCODE_ADD = 0x40000000, + OPCODE_SUB = 0x40000001, + OPCODE_MUL = 0x40000002, + OPCODE_DIV = 0x40000003, + OPCODE_AND = 0x40000004, + OPCODE_OR = 0x40000005, + OPCODE_NEG = 0x40000006, + OPCODE_NOT = 0x40000007, + OPCODE_ISCODE = 0x40000100, + OPCODE_ISSETCARD = 0x40000101, + OPCODE_ISTYPE = 0x40000102, + OPCODE_ISRACE = 0x40000103, + OPCODE_ISATTRIBUTE = 0x40000104; + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/AI/Zones.cs b/src/YGOLegacy.Bots/WindBot/Game/AI/Zones.cs new file mode 100644 index 0000000..269e811 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/AI/Zones.cs @@ -0,0 +1,26 @@ +namespace WindBot.Game.AI +{ + public static class Zones + { + public const int z0 = 0x1, + z1 = 0x2, + z2 = 0x4, + z3 = 0x8, + z4 = 0x10, + z5 = 0x20, + z6 = 0x40, + + FieldZone = 0x20, + + MonsterZones = 0x7f, + MainMonsterZones = 0x1f, + ExtraMonsterZones = 0x60, + + SpellZones = 0x1f, + + PendulumZones = 0x3, + + LinkedZones = 0x10000, + NotLinkedZones = 0x20000; + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/BattlePhase.cs b/src/YGOLegacy.Bots/WindBot/Game/BattlePhase.cs new file mode 100644 index 0000000..ad9cbec --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/BattlePhase.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace WindBot.Game +{ + public class BattlePhase + { + public IList AttackableCards { get; private set; } + public IList ActivableCards { get; private set; } + public IList ActivableDescs { get; private set; } + // [YGOL] the BATTLECMD entry index per activable entry; a card with several modes has one entry each + public IList ActivableIndexes { get; private set; } + public bool CanMainPhaseTwo { get; set; } + public bool CanEndPhase { get; set; } + + public BattlePhase() + { + AttackableCards = new List(); + ActivableCards = new List(); + ActivableDescs = new List(); + ActivableIndexes = new List(); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/BattlePhaseAction.cs b/src/YGOLegacy.Bots/WindBot/Game/BattlePhaseAction.cs new file mode 100644 index 0000000..362db64 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/BattlePhaseAction.cs @@ -0,0 +1,40 @@ +namespace WindBot.Game +{ + public class BattlePhaseAction + { + public enum BattleAction + { + Activate = 0, + Attack = 1, + ToMainPhaseTwo = 2, + ToEndPhase = 3 + } + + public BattleAction Action { get; private set; } + public int Index { get; private set; } + + public BattlePhaseAction(BattleAction action) + { + Action = action; + Index = 0; + } + + public BattlePhaseAction(BattleAction action, int[] indexes) + { + Action = action; + Index = indexes[(int)action]; + } + + // [YGOL] explicit entry index, for an Activate of one mode of a multi-mode card + public BattlePhaseAction(BattleAction action, int index) + { + Action = action; + Index = index; + } + + public int ToValue() + { + return (Index << 16) + (int)Action; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/ChainInfo.cs b/src/YGOLegacy.Bots/WindBot/Game/ChainInfo.cs new file mode 100644 index 0000000..5acd0b1 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/ChainInfo.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; + +namespace WindBot.Game +{ + public class ChainInfo + { + public ClientCard RelatedCard { get; private set; } + public int ActivatePlayer { get; private set; } + public int ActivateId { get; private set; } + public int ActivateAlias { get; private set; } + public int ActivateController { get; private set; } + public int ActivatePosition { get; private set; } + public int ActivateSequence { get; private set; } + public CardLocation ActivateLocation { get; private set; } + public int ActivateLevel { get; private set; } + public int ActivateRank { get; private set; } + public int ActivateType { get; private set; } + public int ActivateRace { get; private set; } + public int ActivateAttack { get; private set; } + public int ActivateDefense { get; private set; } + public bool IsSpecialSummoned { get; private set; } + public int ActivateDescription { get; private set; } + + public ChainInfo(ClientCard card) + : this(card, card.Controller, 0) + { + } + + public ChainInfo(ClientCard card, int player, int desc) + { + RelatedCard = card; + ActivatePlayer = player; + ActivateId = card.Id; + ActivateAlias = card.Alias; + ActivateController = card.Controller; + ActivatePosition = card.Position; + ActivateSequence = card.Sequence; + ActivateLocation = card.Location; + ActivateLevel = card.Level; + ActivateRank = card.Rank; + ActivateType = card.Type; + ActivateRace = card.Race; + ActivateAttack = card.Attack; + ActivateDefense = card.Defense; + ActivateAttack = card.Attack; + ActivateDefense = card.Defense; + IsSpecialSummoned = card.IsSpecialSummoned; + ActivateDescription = desc; + } + + public bool HasPosition(CardPosition position) + { + return (ActivatePosition & (int)position) != 0; + } + + public bool HasLocation(CardLocation location) + { + return ((int)ActivateLocation & (int)location) != 0; + } + + public bool IsActivateCode(int id) + { + return ActivateId == id || Math.Abs(ActivateAlias - ActivateId) <= 20 && ActivateAlias == id; + } + + public bool IsCode(int id) + { + return RelatedCard != null && RelatedCard.IsCode(id); + } + + public bool IsCode(IList ids) + { + return RelatedCard != null && RelatedCard.IsCode(ids); + } + + public bool IsCode(params int[] ids) + { + return RelatedCard != null && RelatedCard.IsCode(ids); + } + + public bool HasType(CardType type) + { + return RelatedCard != null && (RelatedCard.Type & (int)type) != 0; + } + public bool IsSpell() + { + return HasType(CardType.Spell); + } + + public bool IsTrap() + { + return HasType(CardType.Trap); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/ClientCard.cs b/src/YGOLegacy.Bots/WindBot/Game/ClientCard.cs new file mode 100644 index 0000000..1c43cbe --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/ClientCard.cs @@ -0,0 +1,394 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; + +namespace WindBot.Game +{ + public class ClientCard + { + public int Id { get; private set; } + public NamedCard Data { get; private set; } + public string Name { get; private set; } + + public int Position { get; set; } + public int Sequence { get; set; } + public CardLocation Location { get; set; } + public CardLocation LastLocation { get; set; } + public int Alias { get; private set; } + public int Level { get; private set; } + public int Rank { get; private set; } + public int Type { get; private set; } + public int Attribute { get; private set; } + public int Race { get; private set; } + public int Attack { get; private set; } + public int Defense { get; private set; } + public int LScale { get; private set; } + public int RScale { get; private set; } + public int LinkCount { get; private set; } + public int LinkMarker { get; private set; } + public int BaseAttack { get; private set; } + public int BaseDefense { get; private set; } + public int RealPower { get; set; } + public List Overlays { get; private set; } + public int Owner { get; private set; } + public int Controller { get; set; } + public int Disabled { get; private set; } + public int ProcCompleted { get; private set; } + public int SelectSeq { get; set; } + public int OpParam1 { get; set; } + public int OpParam2 { get; set; } + + public List EquipCards { get; set; } + public ClientCard EquipTarget; + public List OwnTargets { get; set; } + public List TargetCards { get; set; } + + public bool CanDirectAttack { get; set; } + public bool ShouldDirectAttack { get; set; } + public bool Attacked { get; set; } + public bool IsLastAttacker { get; set; } + public bool IsSpecialSummoned { get; set; } + + public int[] ActionIndex { get; set; } + public IDictionary ActionActivateIndex { get; private set; } + + public ClientCard(int id, CardLocation loc, int sequence) + : this(id, loc, -1 , 0) + { + } + + public ClientCard(int id, CardLocation loc, int sequence, int position) + { + SetId(id); + Sequence = sequence; + Position = position; + Overlays = new List(); + EquipCards = new List(); + OwnTargets = new List(); + TargetCards = new List(); + ActionIndex = new int[16]; + ActionActivateIndex = new Dictionary(); + Location = loc; + LastLocation = 0; + } + + public void SetId(int id) + { + if (Id == id) return; + Id = id; + Data = NamedCard.Get(Id); + if (Data != null) + { + Name = Data.Name; + Alias = Data.Alias; + } else { + Name = null; + Alias = 0; + } + } + + public void Update(BinaryReader packet, Duel duel) + { + int flag = packet.ReadInt32(); + if ((flag & (int)Query.Code) != 0) + SetId(packet.ReadInt32()); + if ((flag & (int)Query.Position) != 0) + { + Controller = duel.GetLocalPlayer(packet.ReadByte()); + Location = (CardLocation)packet.ReadByte(); + Sequence = packet.ReadByte(); + Position = packet.ReadByte(); + } + if ((flag & (int)Query.Alias) != 0) + Alias = packet.ReadInt32(); + if ((flag & (int)Query.Type) != 0) + Type = packet.ReadInt32(); + if ((flag & (int)Query.Level) != 0) + Level = packet.ReadInt32(); + if ((flag & (int)Query.Rank) != 0) + Rank = packet.ReadInt32(); + if ((flag & (int)Query.Attribute) != 0) + Attribute = packet.ReadInt32(); + if ((flag & (int)Query.Race) != 0) + Race = packet.ReadInt32(); + if ((flag & (int)Query.Attack) != 0) + Attack = packet.ReadInt32(); + if ((flag & (int)Query.Defence) != 0) + Defense = packet.ReadInt32(); + if ((flag & (int)Query.BaseAttack) != 0) + BaseAttack = packet.ReadInt32(); + if ((flag & (int)Query.BaseDefence) != 0) + BaseDefense = packet.ReadInt32(); + if ((flag & (int)Query.Reason) != 0) + packet.ReadInt32(); + if ((flag & (int)Query.ReasonCard) != 0) + packet.ReadInt32(); // Int8 * 4 + if ((flag & (int)Query.EquipCard) != 0) + packet.ReadInt32(); // Int8 * 4 + if ((flag & (int)Query.TargetCard) != 0) + { + int count = packet.ReadInt32(); + for (int i = 0; i < count; ++i) + packet.ReadInt32(); // Int8 * 4 + } + if ((flag & (int)Query.OverlayCard) != 0) + { + Overlays.Clear(); + int count = packet.ReadInt32(); + for (int i = 0; i < count; ++i) + Overlays.Add(packet.ReadInt32()); + } + if ((flag & (int)Query.Counters) != 0) + { + int count = packet.ReadInt32(); + for (int i = 0; i < count; ++i) + packet.ReadInt32(); // Int16 * 2 + } + if ((flag & (int)Query.Owner) != 0) + Owner = duel.GetLocalPlayer(packet.ReadInt32()); + if ((flag & (int)Query.Status) != 0) { + int status = packet.ReadInt32(); + const int STATUS_DISABLED = 0x0001; + const int STATUS_PROC_COMPLETE = 0x0008; + Disabled = status & STATUS_DISABLED; + ProcCompleted = status & STATUS_PROC_COMPLETE; + } + if ((flag & (int)Query.LScale) != 0) + LScale = packet.ReadInt32(); + if ((flag & (int)Query.RScale) != 0) + RScale = packet.ReadInt32(); + if ((flag & (int)Query.Link) != 0) + { + LinkCount = packet.ReadInt32(); + LinkMarker = packet.ReadInt32(); + } + } + + public void ClearCardTargets() + { + foreach (ClientCard card in TargetCards) + { + card.OwnTargets.Remove(this); + } + foreach (ClientCard card in OwnTargets) + { + card.TargetCards.Remove(this); + } + OwnTargets.Clear(); + TargetCards.Clear(); + } + + public bool HasLinkMarker(int dir) + { + return (LinkMarker & dir) != 0; + } + + public bool HasLinkMarker(CardLinkMarker dir) + { + return (LinkMarker & (int)dir) != 0; + } + + public int GetLinkedZones() + { + if (!HasType(CardType.Link) || Location != CardLocation.MonsterZone) + return 0; + int zones = 0; + if (Sequence > 0 && Sequence <= 4 && HasLinkMarker(CardLinkMarker.Left)) + zones |= 1 << (Sequence - 1); + if (Sequence <= 3 && HasLinkMarker(CardLinkMarker.Right)) + zones |= 1 << (Sequence + 1); + if (Sequence == 0 && HasLinkMarker(CardLinkMarker.TopRight) + || Sequence == 1 && HasLinkMarker(CardLinkMarker.Top) + || Sequence == 2 && HasLinkMarker(CardLinkMarker.TopLeft)) + zones |= (1 << 5) | (1 << (16 + 6)); + if (Sequence == 2 && HasLinkMarker(CardLinkMarker.TopRight) + || Sequence == 3 && HasLinkMarker(CardLinkMarker.Top) + || Sequence == 4 && HasLinkMarker(CardLinkMarker.TopLeft)) + zones |= (1 << 6) | (1 << (16 + 5)); + if (Sequence == 5) + { + if (HasLinkMarker(CardLinkMarker.BottomLeft)) + zones |= 1 << 0; + if (HasLinkMarker(CardLinkMarker.Bottom)) + zones |= 1 << 1; + if (HasLinkMarker(CardLinkMarker.BottomRight)) + zones |= 1 << 2; + if (HasLinkMarker(CardLinkMarker.TopLeft)) + zones |= 1 << (16 + 4); + if (HasLinkMarker(CardLinkMarker.Top)) + zones |= 1 << (16 + 3); + if (HasLinkMarker(CardLinkMarker.TopRight)) + zones |= 1 << (16 + 2); + } + if (Sequence == 6) + { + if (HasLinkMarker(CardLinkMarker.BottomLeft)) + zones |= 1 << 2; + if (HasLinkMarker(CardLinkMarker.Bottom)) + zones |= 1 << 3; + if (HasLinkMarker(CardLinkMarker.BottomRight)) + zones |= 1 << 4; + if (HasLinkMarker(CardLinkMarker.TopLeft)) + zones |= 1 << (16 + 2); + if (HasLinkMarker(CardLinkMarker.Top)) + zones |= 1 << (16 + 1); + if (HasLinkMarker(CardLinkMarker.TopRight)) + zones |= 1 << (16 + 0); + } + return zones; + } + + public bool HasType(CardType type) + { + return (Type & (int)type) != 0; + } + + public bool HasPosition(CardPosition position) + { + return (Position & (int)position) != 0; + } + + public bool HasAttribute(CardAttribute attribute) + { + return (Attribute & (int)attribute) != 0; + } + + public bool HasRace(CardRace race) + { + return (Race & (int)race) != 0; + } + + public bool HasSetcode(int setcode) + { + if (Data == null) return false; + long setcodes = Data.Setcode; + int settype = setcode & 0xfff; + int setsubtype = setcode & 0xf000; + while (setcodes > 0) + { + long check_setcode = setcodes & 0xffff; + setcodes >>= 16; + if ((check_setcode & 0xfff) == settype && (check_setcode & 0xf000 & setsubtype) == setsubtype) return true; + } + return false; + } + + public bool IsMonster() + { + return HasType(CardType.Monster); + } + + public bool IsTuner() + { + return HasType(CardType.Tuner); + } + + public bool IsSpell() + { + return HasType(CardType.Spell); + } + + public bool IsTrap() + { + return HasType(CardType.Trap); + } + + public bool IsExtraCard() + { + return HasType(CardType.Fusion) || HasType(CardType.Synchro) || HasType(CardType.Xyz) || HasType(CardType.Link); + } + + public bool IsFaceup() + { + return HasPosition(CardPosition.FaceUp); + } + + public bool IsFacedown() + { + return HasPosition(CardPosition.FaceDown); + } + + public bool IsAttack() + { + return HasPosition(CardPosition.Attack); + } + + public bool IsDefense() + { + return HasPosition(CardPosition.Defence); + } + + public bool IsDisabled() + { + return Disabled != 0; + } + + public bool IsCanRevive() + { + return ProcCompleted != 0 || !(IsExtraCard() || HasType(CardType.Ritual) || HasType(CardType.SpSummon)); + } + + public bool IsCode(int id) + { + return Id == id || Alias != 0 && Alias == id; + } + + public bool IsCode(IList ids) + { + return ids.Contains(Id) || Alias != 0 && ids.Contains(Alias); + } + + public bool IsCode(params int[] ids) + { + return ids.Contains(Id) || Alias != 0 && ids.Contains(Alias); + } + + public bool IsOriginalCode(int id) + { + return Id == id || Alias - Id < 20 && Alias == id; + } + + public bool IsOnField() + { + return Location == CardLocation.MonsterZone || Location == CardLocation.SpellZone || Location == CardLocation.PendulumZone || Location == CardLocation.FieldZone; + } + + public bool HasXyzMaterial() + { + return Overlays.Count > 0; + } + + public bool HasXyzMaterial(int count) + { + return Overlays.Count >= count; + } + + public bool HasXyzMaterial(int count, int cardid) + { + return Overlays.Count >= count && Overlays.Contains(cardid); + } + + public int GetDefensePower() + { + return IsAttack() ? Attack : Defense; + } + + public int GetOriginCode() + { + int code = Id; + if (Data != null) + { + if (Data.Alias > 0) code = Data.Alias; + else code = Data.Id; + } + return code; + } + + public bool Equals(ClientCard card) + { + return ReferenceEquals(this, card); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/ClientField.cs b/src/YGOLegacy.Bots/WindBot/Game/ClientField.cs new file mode 100644 index 0000000..083e1b1 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/ClientField.cs @@ -0,0 +1,360 @@ +using System.Collections.Generic; +using System.Linq; +using WindBot.Game.AI; +using YGOSharp.OCGWrapper.Enums; + +namespace WindBot.Game +{ + public class ClientField + { + public IList Hand { get; private set; } + public ClientCard[] MonsterZone { get; private set; } + public ClientCard[] SpellZone { get; private set; } + public IList Graveyard { get; private set; } + public IList Banished { get; private set; } + public IList Deck { get; private set; } + public IList ExtraDeck { get; private set; } + + public int LifePoints; + public ClientCard BattlingMonster; + public bool UnderAttack; + + public HashSet HintDescriptions { get; private set; } + + public ClientField() + { + } + + public void Init(int deck, int extra) + { + Hand = new List(); + MonsterZone = new ClientCard[7]; + SpellZone = new ClientCard[8]; + Graveyard = new List(); + Banished = new List(); + Deck = new List(); + ExtraDeck = new List(); + HintDescriptions = new HashSet(); + + for (int i = 0; i < deck; ++i) + Deck.Add(new ClientCard(0, CardLocation.Deck, -1)); + for (int i = 0; i < extra; ++i) + ExtraDeck.Add(new ClientCard(0, CardLocation.Extra, -1)); + } + + public int GetMonstersExtraZoneCount() + { + int count = 0; + if (MonsterZone[5] != null) + count++; + if (MonsterZone[6] != null) + count++; + return count; + } + public int GetMonsterCount() + { + return GetCount(MonsterZone); + } + + public int GetSpellCount() + { + return GetCount(SpellZone); + } + + public int GetHandCount() + { + return GetCount(Hand); + } + + public int GetSpellCountWithoutField() + { + int count = 0; + for (int i = 0; i < 5; ++i) + { + if (SpellZone[i] != null) + ++count; + } + return count; + } + + /// + /// Count Column + /// + /// range of zone 0-4 + public int GetColumnCount(int zone, bool IncludeExtraMonsterZone = true) + { + int count = 0; + if (SpellZone[zone] != null) + count++; + if (MonsterZone[zone] != null) + count++; + if(zone == 1 && IncludeExtraMonsterZone) + { + if (MonsterZone[5] != null) + count++; + } + if (zone == 3 && IncludeExtraMonsterZone) + { + if (MonsterZone[6] != null) + count++; + } + return count; + } + + public int GetFieldCount() + { + return GetSpellCount() + GetMonsterCount(); + } + + public int GetFieldHandCount() + { + return GetSpellCount() + GetMonsterCount() + GetHandCount(); + } + + public bool IsFieldEmpty() + { + return GetMonsters().Count == 0 && GetSpells().Count == 0; + } + + public int GetLinkedZones() + { + int zones = 0; + for (int i = 0; i < 7; i++) + { + zones |= MonsterZone[i]?.GetLinkedZones() ?? 0; + } + return zones; + } + + public List GetMonsters() + { + return GetCards(MonsterZone); + } + + public List GetGraveyardMonsters() + { + return GetCards(Graveyard, CardType.Monster); + } + + public List GetGraveyardSpells() + { + return GetCards(Graveyard, CardType.Spell); + } + + public List GetGraveyardTraps() + { + return GetCards(Graveyard, CardType.Trap); + } + + public List GetSpells() + { + return GetCards(SpellZone); + } + + public List GetMonstersInExtraZone() + { + return GetMonsters().Where(card => card.Sequence >= 5).ToList(); + } + + public List GetMonstersInMainZone() + { + return GetMonsters().Where(card => card.Sequence < 5).ToList(); + } + + public ClientCard GetFieldSpellCard() + { + return SpellZone[5]; + } + + public bool HasInHand(int cardId) + { + return HasInCards(Hand, cardId); + } + + public bool HasInHand(IList cardId) + { + return HasInCards(Hand, cardId); + } + + public bool HasInGraveyard(int cardId) + { + return HasInCards(Graveyard, cardId); + } + + public bool HasInGraveyard(IList cardId) + { + return HasInCards(Graveyard, cardId); + } + + public bool HasInBanished(int cardId) + { + return HasInCards(Banished, cardId); + } + + public bool HasInBanished(IList cardId) + { + return HasInCards(Banished, cardId); + } + + public bool HasInExtra(int cardId) + { + return HasInCards(ExtraDeck, cardId); + } + + public bool HasInExtra(IList cardId) + { + return HasInCards(ExtraDeck, cardId); + } + + public bool HasAttackingMonster() + { + return GetMonsters().Any(card => card.IsAttack()); + } + + public bool HasDefendingMonster() + { + return GetMonsters().Any(card => card.IsDefense()); + } + + public bool HasInMonstersZone(int cardId, bool notDisabled = false, bool hasXyzMaterial = false, bool faceUp = false) + { + return HasInCards(MonsterZone, cardId, notDisabled, hasXyzMaterial, faceUp); + } + + public bool HasInMonstersZone(IList cardId, bool notDisabled = false, bool hasXyzMaterial = false, bool faceUp = false) + { + return HasInCards(MonsterZone, cardId, notDisabled, hasXyzMaterial, faceUp); + } + + public bool HasInSpellZone(int cardId, bool notDisabled = false, bool faceUp = false) + { + return HasInCards(SpellZone, cardId, notDisabled, false, faceUp); + } + + public bool HasInSpellZone(IList cardId, bool notDisabled = false, bool faceUp = false) + { + return HasInCards(SpellZone, cardId, notDisabled, false, faceUp); + } + + public bool HasInHandOrInSpellZone(int cardId) + { + return HasInHand(cardId) || HasInSpellZone(cardId); + } + + public bool HasInHandOrHasInMonstersZone(int cardId) + { + return HasInHand(cardId) || HasInMonstersZone(cardId); + } + + public bool HasInHandOrInGraveyard(int cardId) + { + return HasInHand(cardId) || HasInGraveyard(cardId); + } + + public bool HasInGraveyardOrInBanished(int cardId) + { + return HasInBanished(cardId) || HasInGraveyard(cardId); + } + + public bool HasInMonstersZoneOrInGraveyard(int cardId) + { + return HasInMonstersZone(cardId) || HasInGraveyard(cardId); + } + + public bool HasInSpellZoneOrInGraveyard(int cardId) + { + return HasInSpellZone(cardId) || HasInGraveyard(cardId); + } + + public bool HasInHandOrInMonstersZoneOrInGraveyard(int cardId) + { + return HasInHand(cardId) || HasInMonstersZone(cardId) || HasInGraveyard(cardId); + } + + public bool HasInHandOrInSpellZoneOrInGraveyard(int cardId) + { + return HasInHand(cardId) || HasInSpellZone(cardId) || HasInGraveyard(cardId); + } + + public bool HasInHandOrInSpellZone(IList cardId) + { + return HasInHand(cardId) || HasInSpellZone(cardId); + } + + public bool HasInHandOrHasInMonstersZone(IList cardId) + { + return HasInHand(cardId) || HasInMonstersZone(cardId); + } + + public bool HasInHandOrInGraveyard(IList cardId) + { + return HasInHand(cardId) || HasInGraveyard(cardId); + } + + public bool HasInMonstersZoneOrInGraveyard(IList cardId) + { + return HasInMonstersZone(cardId) || HasInGraveyard(cardId); + } + + public bool HasInSpellZoneOrInGraveyard(IList cardId) + { + return HasInSpellZone(cardId) || HasInGraveyard(cardId); + } + + public bool HasInHandOrInMonstersZoneOrInGraveyard(IList cardId) + { + return HasInHand(cardId) || HasInMonstersZone(cardId) || HasInGraveyard(cardId); + } + + public bool HasInHandOrInSpellZoneOrInGraveyard(IList cardId) + { + return HasInHand(cardId) || HasInSpellZone(cardId) || HasInGraveyard(cardId); + } + + public int GetRemainingCount(int cardId, int initialCount) + { + int remaining = initialCount; + remaining = remaining - Hand.Count(card => card != null && card.IsOriginalCode(cardId)); + remaining = remaining - SpellZone.Count(card => card != null && card.IsOriginalCode(cardId)); + remaining = remaining - MonsterZone.Count(card => card != null && card.IsOriginalCode(cardId)); + remaining = remaining - Graveyard.Count(card => card != null && card.IsOriginalCode(cardId)); + remaining = remaining - Banished.Count(card => card != null && card.IsOriginalCode(cardId)); + return (remaining < 0) ? 0 : remaining; + } + + private static int GetCount(IEnumerable cards) + { + return cards.Count(card => card != null); + } + + public int GetCountCardInZone(IEnumerable cards, int cardId) + { + return cards.Count(card => card != null && card.IsCode(cardId)); + } + + public int GetCountCardInZone(IEnumerable cards, List cardId) + { + return cards.Count(card => card != null && card.IsCode(cardId)); + } + + private static List GetCards(IEnumerable cards, CardType type) + { + return cards.Where(card => card != null && card.HasType(type)).ToList(); + } + + private static List GetCards(IEnumerable cards) + { + return cards.Where(card => card != null).ToList(); + } + + private static bool HasInCards(IEnumerable cards, int cardId, bool notDisabled = false, bool hasXyzMaterial = false, bool faceUp = false) + { + return cards.Any(card => card != null && card.IsCode(cardId) && !(notDisabled && card.IsDisabled()) && !(hasXyzMaterial && !card.HasXyzMaterial()) && !(faceUp && card.IsFacedown())); + } + + private static bool HasInCards(IEnumerable cards, IList cardId, bool notDisabled = false, bool hasXyzMaterial = false, bool faceUp = false) + { + return cards.Any(card => card != null && card.IsCode(cardId) && !(notDisabled && card.IsDisabled()) && !(hasXyzMaterial && !card.HasXyzMaterial()) && !(faceUp && card.IsFacedown())); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/Deck.cs b/src/YGOLegacy.Bots/WindBot/Game/Deck.cs new file mode 100644 index 0000000..e2e4b41 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/Deck.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.IO; +using YGOSharp.OCGWrapper; + +namespace WindBot.Game +{ + public class Deck + { + public IList Cards { get; private set; } + public IList ExtraCards { get; private set; } + public IList SideCards { get; private set; } + + public Deck() + { + Cards = new List(); + ExtraCards = new List(); + SideCards = new List(); + } + + private void AddNewCard(int cardId, bool sideDeck) + { + NamedCard newCard = NamedCard.Get(cardId); + if (newCard == null) + return; + + if (!sideDeck) + AddCard(newCard); + else + SideCards.Add(newCard); + } + + private void AddCard(NamedCard card) + { + if (card.IsExtraCard()) + ExtraCards.Add(card); + else + Cards.Add(card); + } + + public static Deck Load(string name) + { + StreamReader reader = null; + try + { + reader = new StreamReader(Program.ReadFile("Decks", name, "ydk")); + + Deck deck = new Deck(); + bool side = false; + string ruleset = null; // [YGOL] TICKET-263 + + while (!reader.EndOfStream) + { + string line = reader.ReadLine(); + if (line == null) + continue; + + line = line.Trim(); + ruleset = YGOLegacy.Services.DeckLimits.RulesetOf(line) ?? ruleset; // [YGOL] TICKET-263 + if (line.StartsWith("#")) + continue; + if (line.Equals("!side")) + { + side = true; + continue; + } + + int id; + if (!int.TryParse(line, out id)) + continue; + + deck.AddNewCard(id, side); + } + + reader.Close(); + + // [YGOL] TICKET-012/263: bot-deck file gate follows the deck's + // Ruleset, so bots load the same decks the editor saves. + var limits = YGOLegacy.Services.DeckLimits.For(ruleset); + if (deck.Cards.Count > limits.MainMax) + return null; + if (deck.ExtraCards.Count > limits.ExtraLimit()) + return null; + if (deck.SideCards.Count > limits.SideMax) + return null; + + return deck; + } + catch (Exception) + { + reader?.Close(); + return null; + } + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/Duel.cs b/src/YGOLegacy.Bots/WindBot/Game/Duel.cs new file mode 100644 index 0000000..e0db133 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/Duel.cs @@ -0,0 +1,198 @@ +using System.Collections.Generic; +using YGOSharp.OCGWrapper.Enums; + +namespace WindBot.Game +{ + public class Duel + { + public bool IsFirst { get; set; } + public bool IsNewRule { get; set; } + public bool IsNewRule2020 { get; set; } + + public ClientField[] Fields { get; private set; } + + public int Turn { get; set; } + public int Player { get; set; } + public DuelPhase Phase { get; set; } + public MainPhase MainPhase { get; set; } + public BattlePhase BattlePhase { get; set; } + + public int LastChainPlayer { get; set; } + public CardLocation LastChainLocation { get; set; } + public IList CurrentChain { get; set; } + public IList CurrentChainInfo { get; set; } + public IList ChainTargets { get; set; } + public IList LastChainTargets { get; set; } + public IList ChainTargetOnly { get; set; } + public int LastSummonPlayer { get; set; } + public IList SummoningCards { get; set; } + public IList LastSummonedCards { get; set; } + public int SolvingChainIndex { get; set; } + public IList NegatedChainIndexList { get; set; } + + public Duel() + { + Fields = new ClientField[2]; + Fields[0] = new ClientField(); + Fields[1] = new ClientField(); + LastChainPlayer = -1; + LastChainLocation = 0; + CurrentChain = new List(); + CurrentChainInfo = new List(); + ChainTargets = new List(); + LastChainTargets = new List(); + ChainTargetOnly = new List(); + LastSummonPlayer = -1; + SummoningCards = new List(); + LastSummonedCards = new List(); + SolvingChainIndex = 0; + NegatedChainIndexList = new List(); + MainPhase = new MainPhase(); + BattlePhase = new BattlePhase(); + } + + public ClientCard GetCard(int player, CardLocation loc, int seq) + { + return GetCard(player, (int)loc, seq, 0); + } + + public ClientCard GetCard(int player, int loc, int seq, int subSeq) + { + if (player < 0 || player > 1) + return null; + + bool isXyz = (loc & 0x80) != 0; + CardLocation location = (CardLocation)(loc & 0x7f); + + IList cards = null; + switch (location) + { + case CardLocation.Deck: + cards = Fields[player].Deck; + break; + case CardLocation.Hand: + cards = Fields[player].Hand; + break; + case CardLocation.MonsterZone: + cards = Fields[player].MonsterZone; + break; + case CardLocation.SpellZone: + cards = Fields[player].SpellZone; + break; + case CardLocation.Grave: + cards = Fields[player].Graveyard; + break; + case CardLocation.Removed: + cards = Fields[player].Banished; + break; + case CardLocation.Extra: + cards = Fields[player].ExtraDeck; + break; + } + if (cards == null) + return null; + + if (seq >= cards.Count) + return null; + + if (isXyz) + { + ClientCard card = cards[seq]; + if (card == null || subSeq >= card.Overlays.Count) + return null; + return new ClientCard(card.Overlays[subSeq], CardLocation.Overlay, 0, 0); + } + + return cards[seq]; + } + + public void AddCard(CardLocation loc, int cardId, int player, int seq, int pos) + { + ClientCard card = new ClientCard(cardId, loc, seq, pos); + AddCard(loc, card, player, seq, pos, cardId); + } + + public void AddCard(CardLocation loc, ClientCard card, int player, int seq, int pos, int id) + { + card.Location = loc; + card.Sequence = seq; + card.Position = pos; + card.Controller = player; + card.SetId(id); + switch (loc) + { + case CardLocation.Hand: + Fields[player].Hand.Add(card); + break; + case CardLocation.Grave: + Fields[player].Graveyard.Add(card); + break; + case CardLocation.Removed: + Fields[player].Banished.Add(card); + break; + case CardLocation.MonsterZone: + Fields[player].MonsterZone[seq] = card; + break; + case CardLocation.SpellZone: + Fields[player].SpellZone[seq] = card; + break; + case CardLocation.Deck: + Fields[player].Deck.Add(card); + break; + case CardLocation.Extra: + Fields[player].ExtraDeck.Add(card); + break; + } + } + + public void RemoveCard(CardLocation loc, ClientCard card, int player, int seq) + { + switch (loc) + { + case CardLocation.Hand: + Fields[player].Hand.Remove(card); + break; + case CardLocation.Grave: + Fields[player].Graveyard.Remove(card); + break; + case CardLocation.Removed: + Fields[player].Banished.Remove(card); + break; + case CardLocation.MonsterZone: + Fields[player].MonsterZone[seq] = null; + break; + case CardLocation.SpellZone: + Fields[player].SpellZone[seq] = null; + break; + case CardLocation.Deck: + Fields[player].Deck.Remove(card); + break; + case CardLocation.Extra: + Fields[player].ExtraDeck.Remove(card); + break; + } + } + + public int GetLocalPlayer(int player) + { + return IsFirst ? player : 1 - player; + } + + public ClientCard GetCurrentSolvingChainCard() + { + if (SolvingChainIndex == 0 || SolvingChainIndex > CurrentChain.Count) return null; + return CurrentChain[SolvingChainIndex - 1]; + } + + public ChainInfo GetCurrentSolvingChainInfo() + { + if (SolvingChainIndex == 0 || SolvingChainIndex > CurrentChainInfo.Count) return null; + return CurrentChainInfo[SolvingChainIndex - 1]; + } + + public bool IsCurrentSolvingChainNegated() + { + return SolvingChainIndex > 0 && NegatedChainIndexList.Contains(SolvingChainIndex); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/GameAI.cs b/src/YGOLegacy.Bots/WindBot/Game/GameAI.cs new file mode 100644 index 0000000..81e71e5 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/GameAI.cs @@ -0,0 +1,1362 @@ +using System.Linq; +using System.Collections.Generic; +using System.Threading; +using WindBot.Game.AI; +using YGOSharp.OCGWrapper.Enums; + +namespace WindBot.Game +{ + public class GameAI + { + public GameClient Game { get; private set; } + public Duel Duel { get; private set; } + public Executor Executor { get; set; } + + // [YGOL] TICKET-349 + + // record activated count to prevent infinite actions + private Dictionary _activatedCards; + + public GameAI(GameClient game, Duel duel) + { + Game = game; + Duel = duel; + + // [YGOL] TICKET-349 + _activatedCards = new Dictionary(); + } + + private void CheckSurrender() + { + foreach (CardExecutor exec in Executor.Executors) + { + if (exec.Type == ExecutorType.Surrender && exec.Func()) + { + // [YGOL] TICKET-349 + Game.Surrender(); + } + } + } + + /// + /// Called when the AI got the error message. + /// + public void OnRetry() + { + Logger.WriteErrorLine("Sorry, an error occurs."); // [YGOL] TICKET-349 + } + + public void OnDeckError(string card) + { + // [YGOL] TICKET-349 + if (card == "DECK") + Logger.WriteErrorLine("Deck illegal. Please check the database of your YGOPro and WindBot."); + else + Logger.WriteErrorLine("Deck error: " + card); + Thread.Sleep(1000); + Game.Connection.Close(); + } + + /// + /// Called when the AI join the game. + /// + public void OnJoinGame() + { + // [YGOL] TICKET-349 + } + + /// + /// Called when the duel starts. + /// + public void OnStart() + { + // [YGOL] TICKET-349 + } + + // [YGOL] TICKET-349 + + /// + /// Called when the AI do the rock-paper-scissors. + /// + /// 1 for Scissors, 2 for Rock, 3 for Paper. + public int OnRockPaperScissors() + { + return Executor.OnRockPaperScissors(); + } + + /// + /// Called when the AI won the rock-paper-scissors. + /// + /// True if the AI should begin first, false otherwise. + public bool OnSelectHand() + { + return Executor.OnSelectHand(); + } + + /// + /// Called when any player draw card. + /// + public void OnDraw(int player) + { + Executor.OnDraw(player); + } + + /// + /// Called when it's a new turn. + /// + public void OnNewTurn() + { + _activatedCards.Clear(); + Executor.OnNewTurn(); + } + + /// + /// Called when it's a new phase. + /// + public void OnNewPhase() + { + m_selector.Clear(); + m_position.Clear(); + m_selector_pointer = -1; + m_materialSelector = null; + m_materialSelectorHint = 0; + m_option = -1; + m_yesno = -1; + m_announce = 0; + + m_place = 0; + // [YGOL] TICKET-349 + Executor.OnNewPhase(); + CheckSurrender(); + } + + public void OnMove(ClientCard card, int previousControler, int previousLocation, int currentControler, int currentLocation) + { + Executor.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + /// + /// Called when the AI got attack directly. + /// + public void OnDirectAttack(ClientCard card) + { + // [YGOL] TICKET-349 + CheckSurrender(); + } + + /// + /// Called when a chain is executed. + /// + /// Card who is chained. + /// Player who is currently chaining. + public void OnChaining(ClientCard card, int player) + { + Executor.OnChaining(player,card); + } + + public void OnChainSolved(int chainIndex) + { + Executor.OnChainSolved(chainIndex); + } + + /// + /// Called when card is successfully special summoned. + /// Used on monsters that can only special summoned once per turn. + /// + public void OnSpSummoned() + { + Executor.OnSpSummoned(); + } + + /// + /// Called when a chain has been solved. + /// + public void OnChainEnd() + { + m_selector.Clear(); + m_selector_pointer = -1; + Executor.OnChainEnd(); + CheckSurrender(); + } + + /// + /// Called when a PlayerHint message is received (e.g. effect description add/remove hints). + /// + /// Player index + /// Hint type, see PlayerHintType (DescAdd=6, DescRemove=7) + /// Effect description id (peffect->description) + public void OnPlayerHint(int player, int hintType, int description) + { + Executor.OnPlayerHint(player, hintType, description); + } + + /// + /// Called when a zone hint is received. + /// + /// Player index. + /// Zone data (hinted zones, bit field). + public void OnHintZone(int player, int zone) + { + Executor.OnHintZone(player, zone); + } + + /// + /// Called when receiving annouce + /// + /// Player who announce. + /// Annouced info. + public void OnReceivingAnnouce(int player, int data) + { + Executor.OnReceivingAnnouce(player, data); + } + + /// + /// Called when the AI has to do something during the battle phase. + /// + /// Informations about usable cards. + /// A new BattlePhaseAction containing the action to do. + public BattlePhaseAction OnSelectBattleCmd(BattlePhase battle) + { + foreach (CardExecutor exec in Executor.Executors) + { + if (exec.Type == ExecutorType.GoToMainPhase2 && battle.CanMainPhaseTwo && exec.Func()) // check if should enter main phase 2 directly + { + return ToMainPhase2(); + } + if (exec.Type == ExecutorType.GoToEndPhase && battle.CanEndPhase && exec.Func()) // check if should enter end phase directly + { + return ToEndPhase(); + } + for (int i = 0; i < battle.ActivableCards.Count; ++i) + { + ClientCard card = battle.ActivableCards[i]; + if (ShouldExecute(exec, card, ExecutorType.Activate, battle.ActivableDescs[i])) + { + // [YGOL] TICKET-349 + // [YGOL] send the approved entry, not card.ActionIndex (the card's last-listed mode) + return new BattlePhaseAction(BattlePhaseAction.BattleAction.Activate, battle.ActivableIndexes[i]); + } + } + } + + // Sort the attackers and defenders, make monster with higher attack go first. + List attackers = new List(battle.AttackableCards); + attackers.Sort(CardContainer.CompareCardAttack); + attackers.Reverse(); + + List defenders = new List(Duel.Fields[1].GetMonsters()); + defenders.Sort(CardContainer.CompareDefensePower); + defenders.Reverse(); + + // Let executor decide which card should attack first. + ClientCard selected = Executor.OnSelectAttacker(attackers, defenders); + if (selected != null && attackers.Contains(selected)) + { + attackers.Remove(selected); + attackers.Insert(0, selected); + } + + // Check for the executor. + BattlePhaseAction result = Executor.OnBattle(attackers, defenders); + if (result != null) + return result; + + if (attackers.Count == 0) + return ToMainPhase2(); + + if (defenders.Count == 0) + { + // Attack with the monster with the lowest attack first + ClientCard attacker = attackers[attackers.Count - 1]; + return Attack(attacker, null); + } + else + { + for (int k = 0; k < attackers.Count; ++k) + { + ClientCard attacker = attackers[k]; + attacker.IsLastAttacker = (k == attackers.Count - 1); + result = Executor.OnSelectAttackTarget(attacker, defenders); + if (result != null) + return result; + } + } + + if (!battle.CanMainPhaseTwo) + return Attack(attackers[0], (defenders.Count == 0) ? null : defenders[0]); + + return ToMainPhase2(); + } + + /// + /// Called when the AI has to select one or more cards. + /// + /// List of available cards. + /// Minimal quantity. + /// Maximal quantity. + /// The hint message of the select. + /// True if you can return an empty list. + /// A new list containing the selected cards. + public IList OnSelectCard(IList cards, int min, int max, int hint, bool cancelable) + { + // Check for the executor. + IList result = Executor.OnSelectCard(cards, min, max, hint, cancelable); + if (result != null) + return result; + + if (hint == HintMsg.SpSummon && min == 1 && max > min) // pendulum summon + { + result = Executor.OnSelectPendulumSummon(cards, max); + if (result != null) + return result; + } + + CardSelector selector = null; + if (hint == HintMsg.FusionMaterial || hint == HintMsg.SynchroMaterial || hint == HintMsg.XyzMaterial || hint == HintMsg.LinkMaterial) + { + if (m_materialSelector != null) + { + //Logger.DebugWriteLine("m_materialSelector"); + selector = m_materialSelector; + } + else + { + if (hint == HintMsg.FusionMaterial) + result = Executor.OnSelectFusionMaterial(cards, min, max); + if (hint == HintMsg.SynchroMaterial) + result = Executor.OnSelectSynchroMaterial(cards, 0, min, max); + if (hint == HintMsg.XyzMaterial) + result = Executor.OnSelectXyzMaterial(cards, min, max); + if (hint == HintMsg.LinkMaterial) + result = Executor.OnSelectLinkMaterial(cards, min, max); + + if (result != null) + return result; + + // Update the next selector. + selector = GetSelectedCards(); + } + } + else + { + if (m_materialSelector != null && hint == m_materialSelectorHint) + { + //Logger.DebugWriteLine("m_materialSelector hint match"); + selector = m_materialSelector; + } + else + { + // Update the next selector. + selector = GetSelectedCards(); + } + } + + // If we selected a card, use this card. + if (selector != null) + return selector.Select(cards, min, max); + + // Always select the first available cards and choose the minimum. + IList selected = new List(); + + if (hint == HintMsg.AttackTarget && cancelable) return selected; + + if (cards.Count >= min) + { + for (int i = 0; i < min; ++i) + selected.Add(cards[i]); + } + return selected; + } + + /// + /// Called when the AI can chain (activate) a card. + /// + /// List of activable cards. + /// List of effect descriptions. + /// You can't return -1 if this param is true. + /// Current hint timing + /// Index of the activated card or -1. + public int OnSelectChain(IList cards, IList descs, IList forces, int timing = -1) + { + Executor.OnSelectChain(cards); + foreach (CardExecutor exec in Executor.Executors) + { + for (int i = 0; i < cards.Count; ++i) + { + ClientCard card = cards[i]; + if (ShouldExecute(exec, card, ExecutorType.Activate, descs[i], timing)) + { + // [YGOL] TICKET-349 + return i; + } + } + } + for (int i = 0; i < forces.Count; ++i) + { + if (forces[i]) + { + // If the card is forced, we have to activate it. + // [YGOL] TICKET-349 + return i; + } + } + // Don't do anything. + return -1; + } + + /// + /// Called when the AI has to use one or more counters. + /// + /// Type of counter to use. + /// Quantity of counter to select. + /// List of available cards. + /// List of available counters. + /// List of used counters. + public IList OnSelectCounter(int type, int quantity, IList cards, IList counters) + { + // Always select the first available counters. + int[] used = new int[counters.Count]; + int i = 0; + while (quantity > 0) + { + if (counters[i] >= quantity) + { + used[i] = quantity; + quantity = 0; + } + else + { + used[i] = counters[i]; + quantity -= counters[i]; + } + i++; + } + return used; + } + + /// + /// Called when the AI has to sort cards. + /// + /// Cards to sort. + /// List of sorted cards. + public IList OnCardSorting(IList cards) + { + + IList result = Executor.OnCardSorting(cards); + if (result != null) + return result; + result = new List(); + // TODO: use selector + result = cards.ToList(); + return result; + } + + /// + /// Called when the AI has to choose to activate or not an effect. + /// + /// Card to activate. + /// True for yes, false for no. + public bool OnSelectEffectYn(ClientCard card, int desc) + { + foreach (CardExecutor exec in Executor.Executors) + { + if (ShouldExecute(exec, card, ExecutorType.Activate, desc)) + return true; + } + return false; + } + + /// + /// Called when the AI has to do something during the main phase. + /// + /// A lot of informations about the available actions. + /// A new MainPhaseAction containing the action to do. + public MainPhaseAction OnSelectIdleCmd(MainPhase main) + { + CheckSurrender(); + // [YGOL] TICKET-050 (lookahead prototype). An executor that plans + // ahead re-runs the walk below several times under a veto set, which + // enumerates its top-K idle actions IN ITS OWN PREFERENCE ORDER + // without duplicating a line of its scoring, then picks between them + // with rollouts. No planner installed -- the game today, every Lucky + // seat, every brain with knob `lookahead` 0 -- is the original walk, + // called exactly once, byte for byte as before. + var planner = Executor as YGOLegacy.Bot.IIdlePlanner; + if (planner != null && planner.YGOL_WantsPlan()) + { + // The probe walks call ShouldExecute, which counts activations + // (nine of the same card and it is locked out). Those walks are + // hypothetical, so the counter is restored before the real one. + var savedCounts = new Dictionary(_activatedCards); + int? pick; + try { pick = planner.YGOL_PlanIdle(main, allow => YGOL_WalkIdle(main, allow)); } + finally + { + _activatedCards.Clear(); + foreach (var kv in savedCounts) _activatedCards[kv.Key] = kv.Value; + } + if (pick.HasValue) + // Re-walk accepting only the chosen action, so every side + // effect (combo progress, journal, chat) happens once, for + // the action actually played. + return YGOL_WalkIdle(main, a => a.ToValue() == pick.Value); + } + return YGOL_WalkIdle(main, null); + } + + /// + /// [YGOL] The original OnSelectIdleCmd body, with one addition: + /// (null = accept everything, the normal path) + /// is consulted at the exact point the walk would have returned an + /// action. A vetoed action makes the walk carry on to its next + /// preference instead, so calling this K times with a growing veto set + /// yields the executor's top-K. The last ToEndPhase is never vetoed: + /// the walk must always answer the core. + /// + private MainPhaseAction YGOL_WalkIdle(MainPhase main, System.Func allow) + { + bool Ok(MainPhaseAction a) => allow == null || allow(a); + + foreach (CardExecutor exec in Executor.Executors) + { + if (exec.Type == ExecutorType.GoToEndPhase && main.CanEndPhase && exec.Func()) // check if should enter end phase directly + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.ToEndPhase); + if (Ok(act)) + { + // [YGOL] TICKET-349 + return act; + } + } + if (exec.Type==ExecutorType.GoToBattlePhase && main.CanBattlePhase && exec.Func()) // check if should enter battle phase directly + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.ToBattlePhase); + if (Ok(act)) return act; + } + // NOTICE: GoToBattlePhase and GoToEndPhase has no "card" can be accessed to ShouldExecute(), so instead use exec.Func() to check ... + // enter end phase and enter battle pahse is in higher priority. + + for (int i = 0; i < main.ActivableCards.Count; ++i) + { + ClientCard card = main.ActivableCards[i]; + if (ShouldExecute(exec, card, ExecutorType.Activate, main.ActivableDescs[i])) + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.Activate, card.ActionActivateIndex[main.ActivableDescs[i]]); + if (Ok(act)) + { + // [YGOL] TICKET-349 + return act; + } + } + } + foreach (ClientCard card in main.MonsterSetableCards) + { + if (ShouldExecute(exec, card, ExecutorType.MonsterSet)) + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.SetMonster, card.ActionIndex); + if (Ok(act)) + { + // [YGOL] TICKET-349 + return act; + } + } + } + foreach (ClientCard card in main.ReposableCards) + { + if (ShouldExecute(exec, card, ExecutorType.Repos)) + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.Repos, card.ActionIndex); + if (Ok(act)) return act; + } + } + foreach (ClientCard card in main.SpecialSummonableCards) + { + if (ShouldExecute(exec, card, ExecutorType.SpSummon)) + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.SpSummon, card.ActionIndex); + if (Ok(act)) + { + // [YGOL] TICKET-349 + return act; + } + } + } + foreach (ClientCard card in main.SummonableCards) + { + if (ShouldExecute(exec, card, ExecutorType.Summon)) + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.Summon, card.ActionIndex); + if (Ok(act)) + { + // [YGOL] TICKET-349 + return act; + } + } + if (ShouldExecute(exec, card, ExecutorType.SummonOrSet)) + { + // [YGOL] the original wrote this as an if + unconditional + // fall-through to Summon; it is an if/else here so that a + // vetoed SetMonster does not silently become a Summon the + // executor never asked for (identical behaviour when + // `allow` is null, which is every non-planning seat). + if (main.MonsterSetableCards.Contains(card) && Executor.OnSelectMonsterSummonOrSet(card)) + { + var setAct = new MainPhaseAction(MainPhaseAction.MainAction.SetMonster, card.ActionIndex); + if (Ok(setAct)) + { + // [YGOL] TICKET-349 + return setAct; + } + } + else + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.Summon, card.ActionIndex); + if (Ok(act)) + { + // [YGOL] TICKET-349 + return act; + } + } + } + } + foreach (ClientCard card in main.SpellSetableCards) + { + if (ShouldExecute(exec, card, ExecutorType.SpellSet)) + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.SetSpell, card.ActionIndex); + if (Ok(act)) return act; + } + } + } + + if (main.CanBattlePhase && Duel.Fields[0].HasAttackingMonster()) + { + var act = new MainPhaseAction(MainPhaseAction.MainAction.ToBattlePhase); + if (Ok(act)) return act; + } + + // [YGOL] The core does not always allow the End Phase: MSG_SELECT_IDLECMD + // carries a `to_ep` flag (read into main.CanEndPhase above) and the + // GoToEndPhase executor branch honours it, but this fallback did not. + // Answering ToEndPhase when it is illegal earns MSG_RETRY, which + // OnRetry turns into a thrown exception -- i.e. a lost duel, not a + // recovered one. Measured on Orichalcos/Leon Wilson ORI: 34 of 300 + // duels died this way, on both seats, Smart and Lucky alike. + // Fall back to whatever the core says IS legal, cheapest first. + if (!main.CanEndPhase) + { + if (main.CanBattlePhase) + return new MainPhaseAction(MainPhaseAction.MainAction.ToBattlePhase); + if (main.ActivableCards.Count > 0 && main.ActivableDescs.Count > 0) + return new MainPhaseAction(MainPhaseAction.MainAction.Activate, + main.ActivableCards[0].ActionActivateIndex[main.ActivableDescs[0]]); + if (main.SpellSetableCards.Count > 0) + return new MainPhaseAction(MainPhaseAction.MainAction.SetSpell, main.SpellSetableCards[0].ActionIndex); + if (main.SummonableCards.Count > 0) + return new MainPhaseAction(MainPhaseAction.MainAction.Summon, main.SummonableCards[0].ActionIndex); + if (main.MonsterSetableCards.Count > 0) + return new MainPhaseAction(MainPhaseAction.MainAction.SetMonster, main.MonsterSetableCards[0].ActionIndex); + if (main.SpecialSummonableCards.Count > 0) + return new MainPhaseAction(MainPhaseAction.MainAction.SpSummon, main.SpecialSummonableCards[0].ActionIndex); + if (main.ReposableCards.Count > 0) + return new MainPhaseAction(MainPhaseAction.MainAction.Repos, main.ReposableCards[0].ActionIndex); + // Nothing legal at all: fall through and let the core say so. + } + + // [YGOL] TICKET-349 + return new MainPhaseAction(MainPhaseAction.MainAction.ToEndPhase); + } + + /// + /// Called when the AI has to select an option. + /// + /// List of available options. + /// Index of the selected option. + public int OnSelectOption(IList options) + { + int result = Executor.OnSelectOption(options); + if (result != -1) + return result; + + if (m_option != -1 && m_option < options.Count) + return m_option; + + return 0; // Always select the first option. + } + + public int OnSelectPlace(int cardId, int player, CardLocation location, int available) + { + int selector_selected = m_place; + m_place = 0; + + int executor_selected = Executor.OnSelectPlace(cardId, player, location, available); + + if ((executor_selected & available) > 0) + return executor_selected & available; + if ((selector_selected & available) > 0) + return selector_selected & available; + + // TODO: LinkedZones + + return 0; + } + + /// + /// Called when the AI has to select a card position. + /// + /// Id of the card to position on the field. + /// List of available positions. + /// Selected position. + public CardPosition OnSelectPosition(int cardId, IList positions) + { + CardPosition selector_selected = GetSelectedPosition(); + + CardPosition executor_selected = Executor.OnSelectPosition(cardId, positions); + + // Selects the selected position if available, the first available otherwise. + if (positions.Contains(executor_selected)) + return executor_selected; + if (positions.Contains(selector_selected)) + return selector_selected; + + return positions[0]; + } + + /// + /// Called when the AI has to tribute for a synchro monster or ritual monster. + /// + /// Available cards. + /// Result of the operation. + /// Minimum cards. + /// Maximum cards. + /// True for exact equal. + /// + public IList OnSelectSum(IList cards, int sum, int min, int max, int hint, bool mode) + { + IList selected = Executor.OnSelectSum(cards, sum, min, max, hint, mode); + if (selected != null) + { + return selected; + } + + if (hint == HintMsg.Release || hint == HintMsg.SynchroMaterial) + { + if (m_materialSelector != null) + { + selected = m_materialSelector.Select(cards, min, max); + } + else + { + switch (hint) + { + case HintMsg.SynchroMaterial: + selected = Executor.OnSelectSynchroMaterial(cards, sum, min, max); + break; + case HintMsg.Release: + selected = Executor.OnSelectRitualTribute(cards, sum, min, max); + break; + } + } + // [YGOL] also reject a pick whose card count the engine would RETRY + if (selected != null && selected.Count >= min && selected.Count <= max) + { + int s1 = 0, s2 = 0; + foreach (ClientCard card in selected) + { + s1 += card.OpParam1; + s2 += (card.OpParam2 != 0) ? card.OpParam2 : card.OpParam1; + } + if ((mode && CanSumExactly(selected, sum)) || (!mode && (s1 >= sum || s2 >= sum))) // [YGOL] mixed values + { + return selected; + } + } + } + + if (mode) + { + // equal + + if (sum == 0 && min == 0) + { + return new List(); + } + + if (min <= 1) + { + // try special level first + foreach (ClientCard card in cards) + { + if (card.OpParam2 == sum) + { + return new[] { card }; + } + } + // try level equal + foreach (ClientCard card in cards) + { + if (card.OpParam1 == sum) + { + return new[] { card }; + } + } + } + + // try all + // [YGOL] per-card values (mixed two-value levels) and the engine's count limit + if (cards.Count >= min && cards.Count <= max && CanSumExactly(cards, sum)) + { + return cards; + } + + // try all combinations + int i = (min <= 1) ? 2 : min; + while (i <= max && i <= cards.Count) + { + IEnumerable> combos = CardContainer.GetCombinations(cards, i); + + foreach (IEnumerable combo in combos) + { + Logger.DebugWriteLine("--"); + IList comboList = combo.ToList(); + if (CanSumExactly(comboList, sum)) // [YGOL] mixed two-value levels + { + return comboList; + } + } + i++; + } + } + else + { + // larger + if (min <= 1) + { + // try special level first + foreach (ClientCard card in cards) + { + if (card.OpParam2 >= sum) + { + return new[] { card }; + } + } + // try level equal + foreach (ClientCard card in cards) + { + if (card.OpParam1 >= sum) + { + return new[] { card }; + } + } + } + + // try all combinations + int i = (min <= 1) ? 2 : min; + while (i <= max && i <= cards.Count) + { + IEnumerable> combos = CardContainer.GetCombinations(cards, i); + + foreach (IEnumerable combo in combos) + { + Logger.DebugWriteLine("----"); + int s1 = 0, s2 = 0; + foreach (ClientCard card in combo) + { + s1 += card.OpParam1; + s2 += (card.OpParam2 != 0) ? card.OpParam2 : card.OpParam1; + } + if (s1 >= sum || s2 >= sum) + { + return combo.ToList(); + } + } + i++; + } + } + + Logger.WriteErrorLine("Fail to select sum."); + return new List(); + } + + /// + /// [YGOL] True if each card can take its OpParam1 or OpParam2 on its own so the total is exactly sum, + /// like the engine's select_sum_check1 (e.g. Lv5 = Tuner 2 + Tuning Supporter as 1 + Tuning Supporter as 2). + /// + private static bool CanSumExactly(IList cards, int sum) + { + HashSet totals = new HashSet { 0 }; + foreach (ClientCard card in cards) + { + HashSet next = new HashSet(); + foreach (int total in totals) + { + if (card.OpParam1 >= 0 && card.OpParam1 <= sum - total) + next.Add(total + card.OpParam1); + if (card.OpParam2 > 0 && card.OpParam2 <= sum - total) + next.Add(total + card.OpParam2); + } + if (next.Count == 0) + return false; + totals = next; + } + return totals.Contains(sum); + } + + /// + /// Called when the AI has to tribute one or more cards. + /// + /// List of available cards. + /// Minimal quantity. + /// Maximal quantity. + /// The hint message of the select. + /// True if you can return an empty list. + /// A new list containing the tributed cards. + public IList OnSelectTribute(IList cards, int min, int max, int hint, bool cancelable) + { + // Always choose the minimum and lowest atk. + List sorted = new List(); + sorted.AddRange(cards); + sorted.Sort(CardContainer.CompareCardAttack); + + IList selected = new List(); + + for (int i = 0; i < min && i < sorted.Count; ++i) + selected.Add(sorted[i]); + + return selected; + } + + /// + /// Called when the AI has to select yes or no. + /// + /// Id of the question. + /// True for yes, false for no. + public bool OnSelectYesNo(int desc) + { + if (m_yesno != -1) + return m_yesno > 0; + // [YGOL] 210 = "continue selecting tributes?": the minimum is already met, so + // stop (the base Executor says yes to everything). Executors that override + // OnSelectYesNo (SmartExecutor brain rules, deck executors) still decide. + if (desc == 210 && Executor.GetType().GetMethod(nameof(Executor.OnSelectYesNo), new[] { typeof(int) }).DeclaringType == typeof(Executor)) + return false; + return Executor.OnSelectYesNo(desc); + } + + /// + /// Called when the AI has to select if to continue attacking when replay. + /// + /// True for yes, false for no. + public bool OnSelectBattleReplay() + { + return Executor.OnSelectBattleReplay(); + } + + /// + /// Called when the AI has to declare a card. + /// + /// Available card's ids. + /// Id of the selected card. + public int OnAnnounceCard(IList avail) + { + int selected = Executor.OnAnnounceCard(avail); + if (avail.Contains(selected)) + return selected; + if (avail.Contains(m_announce)) + return m_announce; + else if (m_announce > 0) + Logger.WriteErrorLine("Pre-announced card cant be used: " + m_announce); + return avail[0]; + } + + // _ Others functions _ + // Those functions are used by the AI behavior. + + + private CardSelector m_materialSelector; + private int m_materialSelectorHint; + private int m_place; + private int m_option; + private int m_number; + private int m_announce; + private int m_yesno; + private IList m_attributes = new List(); + private IList m_selector = new List(); + private IList m_position = new List(); + private int m_selector_pointer = -1; + private IList m_races = new List(); + + public void SelectCard(ClientCard card) + { + m_selector_pointer = m_selector.Count(); + m_selector.Add(new CardSelector(card)); + } + + public void SelectCard(IList cards) + { + m_selector_pointer = m_selector.Count(); + m_selector.Add(new CardSelector(cards)); + } + + public void SelectCard(int cardId) + { + m_selector_pointer = m_selector.Count(); + m_selector.Add(new CardSelector(cardId)); + } + + public void SelectCard(IList ids) + { + m_selector_pointer = m_selector.Count(); + m_selector.Add(new CardSelector(ids)); + } + + public void SelectCard(params int[] ids) + { + m_selector_pointer = m_selector.Count(); + m_selector.Add(new CardSelector(ids)); + } + + public void SelectCard(CardLocation loc) + { + m_selector_pointer = m_selector.Count(); + m_selector.Add(new CardSelector(loc)); + } + + public void SelectNextCard(ClientCard card) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectNextCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(card)); + } + + public void SelectNextCard(IList cards) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectNextCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(cards)); + } + + public void SelectNextCard(int cardId) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectNextCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(cardId)); + } + + public void SelectNextCard(IList ids) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectNextCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(ids)); + } + + public void SelectNextCard(params int[] ids) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectNextCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(ids)); + } + + public void SelectNextCard(CardLocation loc) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectNextCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(loc)); + } + + public void SelectThirdCard(ClientCard card) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectThirdCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(card)); + } + + public void SelectThirdCard(IList cards) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectThirdCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(cards)); + } + + public void SelectThirdCard(int cardId) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectThirdCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(cardId)); + } + + public void SelectThirdCard(IList ids) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectThirdCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(ids)); + } + + public void SelectThirdCard(params int[] ids) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectThirdCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(ids)); + } + + public void SelectThirdCard(CardLocation loc) + { + if (m_selector_pointer == -1) + { + Logger.WriteErrorLine("Error: Call SelectThirdCard() before SelectCard()"); + m_selector_pointer = 0; + } + m_selector.Insert(m_selector_pointer, new CardSelector(loc)); + } + + public void SelectMaterials(ClientCard card, int hint = 0) + { + m_materialSelector = new CardSelector(card); + m_materialSelectorHint = hint; + } + + public void SelectMaterials(IList cards, int hint = 0) + { + m_materialSelector = new CardSelector(cards); + m_materialSelectorHint = hint; + } + + public void SelectMaterials(int cardId, int hint = 0) + { + m_materialSelector = new CardSelector(cardId); + m_materialSelectorHint = hint; + } + + public void SelectMaterials(IList ids, int hint = 0) + { + m_materialSelector = new CardSelector(ids); + m_materialSelectorHint = hint; + } + + public void SelectMaterials(CardLocation loc, int hint = 0) + { + m_materialSelector = new CardSelector(loc); + m_materialSelectorHint = hint; + } + + public void CleanSelectMaterials() + { + m_materialSelector = null; + m_materialSelectorHint = 0; + } + + public bool HaveSelectedCards() + { + return m_selector.Count > 0 || m_materialSelector != null; + } + + public CardSelector GetSelectedCards() + { + CardSelector selected = null; + if (m_selector.Count > 0) + { + selected = m_selector[m_selector.Count - 1]; + m_selector.RemoveAt(m_selector.Count - 1); + } + return selected; + } + + public CardPosition GetSelectedPosition() + { + CardPosition selected = CardPosition.FaceUpAttack; + if (m_position.Count > 0) + { + selected = m_position[0]; + m_position.RemoveAt(0); + } + return selected; + } + + public void SelectPosition(CardPosition pos) + { + m_position.Add(pos); + } + + public void SelectPlace(int zones) + { + m_place = zones; + } + + public void SelectOption(int opt) + { + m_option = opt; + } + + public void SelectNumber(int number) + { + m_number = number; + } + + public void SelectAttribute(CardAttribute attribute) + { + m_attributes.Clear(); + m_attributes.Add(attribute); + } + + public void SelectAttributes(CardAttribute[] attributes) + { + m_attributes.Clear(); + foreach (CardAttribute attribute in attributes) + m_attributes.Add(attribute); + } + + public void SelectRace(CardRace race) + { + m_races.Clear(); + m_races.Add(race); + } + + public void SelectRaces(CardRace[] races) + { + m_races.Clear(); + foreach (CardRace race in races) + m_races.Add(race); + } + + public void SelectAnnounceID(int id) + { + m_announce = id; + } + + public void SelectYesNo(bool opt) + { + m_yesno = opt ? 1 : 0; + } + + /// + /// Called when the AI has to declare a number. + /// + /// List of available numbers. + /// Index of the selected number. + public int OnAnnounceNumber(IList numbers) + { + if (numbers.Contains(m_number)) + return numbers.IndexOf(m_number); + + return Program.Rand.Next(0, numbers.Count); // Returns a random number. + } + + /// + /// Called when the AI has to declare one or more attributes. + /// + /// Quantity of attributes to declare. + /// List of available attributes. + /// A list of the selected attributes. + public virtual IList OnAnnounceAttrib(int count, IList attributes) + { + IList foundAttributes = m_attributes.Where(attributes.Contains).ToList(); + if (foundAttributes.Count > 0) + return foundAttributes; + + return attributes; // Returns the first available Attribute. + } + + /// + /// Called when the AI has to declare one or more races. + /// + /// Quantity of races to declare. + /// List of available races. + /// A list of the selected races. + public virtual IList OnAnnounceRace(int count, IList races) + { + IList foundRaces = m_races.Where(races.Contains).ToList(); + if (foundRaces.Count > 0) + return foundRaces; + + return races; // Returns the first available Races. + } + + public BattlePhaseAction Attack(ClientCard attacker, ClientCard defender) + { + Executor.SetCard(0, attacker, -1); + if (defender != null) + { + attacker.ShouldDirectAttack = false; + // [YGOL] TICKET-349 + SelectCard(defender); + } + else + { + attacker.ShouldDirectAttack = true; + // [YGOL] TICKET-349 + } + return new BattlePhaseAction(BattlePhaseAction.BattleAction.Attack, attacker.ActionIndex); + } + + public BattlePhaseAction ToEndPhase() + { + // [YGOL] TICKET-349 + return new BattlePhaseAction(BattlePhaseAction.BattleAction.ToEndPhase); + } + public BattlePhaseAction ToMainPhase2() + { + return new BattlePhaseAction(BattlePhaseAction.BattleAction.ToMainPhaseTwo); + } + + private bool ShouldExecute(CardExecutor exec, ClientCard card, ExecutorType type, int desc = -1, int timing = -1) + { + Executor.SetCard(type, card, desc, timing); + if (card.Id != 0 && type == ExecutorType.Activate) + { + if (_activatedCards.ContainsKey(card.Id) && _activatedCards[card.Id] >= 9) + return false; + if (!Executor.OnPreActivate(card)) + return false; + } + bool result = card != null && exec.Type == type && + (exec.CardId == -1 || exec.CardId == card.Id) && + (exec.Func == null || exec.Func()); + if (card.Id != 0 && type == ExecutorType.Activate && result) + { + int count = card.IsDisabled() ? 3 : 1; + if (!_activatedCards.ContainsKey(card.Id)) + { + _activatedCards.Add(card.Id, count); + } + else + { + _activatedCards[card.Id] += count; + } + } + return result; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/GameBehavior.cs b/src/YGOLegacy.Bots/WindBot/Game/GameBehavior.cs new file mode 100644 index 0000000..33cec3d --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/GameBehavior.cs @@ -0,0 +1,2343 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using WindBot.Game.AI; +using YGOSharp.Network; +using YGOSharp.Network.Enums; +using YGOSharp.Network.Utils; +using YGOSharp.OCGWrapper; +using YGOSharp.OCGWrapper.Enums; +using YGOLegacy.Protocol.Codecs; // [YGOL] TICKET-161 + +namespace WindBot.Game +{ + public class GameBehavior + { + public GameClient Game { get; private set; } + public YGOClient Connection { get; private set; } + public Deck Deck { get; private set; } + + private GameAI _ai; + + private IDictionary> _packets; + private IDictionary> _messages; + private YGOLegacy.Protocol.Routing.StocRouter _router; // [YGOL] TICKET-164: built from _packets at the end of RegisterPackets + + private Room _room; + private Duel _duel; + private int _hand; + private bool _debug; + private int _select_hint; + private GameMessage _lastMessage; + + public GameBehavior(GameClient game) + { + Game = game; + Connection = game.Connection; + _hand = game.Hand; + _debug = game.Debug; + _packets = new Dictionary>(); + _messages = new Dictionary>(); + RegisterPackets(); + + _room = new Room(); + _duel = new Duel(); + + _ai = new GameAI(Game, _duel); + _ai.Executor = DecksManager.Instantiate(_ai, _duel); + // [YGOL] TICKET-285: a deferred bot has no deck until the host assigns one. + Deck = Game.YGOL_DeferDeck && Game.DeckFile == null ? null : Deck.Load(Game.DeckFile ?? _ai.Executor.Deck); + Game.YGOL_HasDeck = Deck != null; + + _select_hint = 0; + } + + #region [YGOL] read-only mirror mode (TICKET-042 duel state bus) + // [YGOL] Duel state bus: YGOLegacy.Bot.DuelStateBus drives a PASSIVE + // copy of this parser per tapped client stream, so a bot can read what + // the other seat was told without a second parser and without any + // server change. A mirror has no connection (it must never answer), no + // deck and no real AI — only the message->state handlers below, and + // only the subset in YGOL_MirrorMessages, which contains nothing that + // sends or that raises YGOL_DuelResult. Everything here is additive: + // the normal constructor and OnPacket are untouched. + + /// [YGOL] Build a mirror: same parsing, no connection, no answers. + private GameBehavior(GameClient game, Func executorFactory) + { + Game = game; + Connection = null; // a mirror never sends anything + _hand = game.Hand; + _debug = false; + _packets = new Dictionary>(); + _messages = new Dictionary>(); + RegisterPackets(); + + _room = new Room(); + _duel = new Duel(); + + _ai = new GameAI(Game, _duel); + _ai.Executor = executorFactory(_ai, _duel); + Deck = null; // never joins, so never uploads a deck + + _select_hint = 0; + } + + /// [YGOL] See the mirror constructor. + public static GameBehavior YGOL_CreateMirror(GameClient game, Func executorFactory) + { + return new GameBehavior(game, executorFactory); + } + + /// [YGOL] The mirrored duel; Fields[0] is the mirrored seat. + public Duel YGOL_MirrorDuel + { + get { return _duel; } + } + + /// + /// [YGOL] The messages a mirror replays. Pure state only: no prompt is + /// answered, and Win is deliberately absent so a mirror never raises a + /// second YGOL_DuelResult for the arena to trip over. + /// + private static readonly HashSet YGOL_MirrorMessages = new HashSet + { + GameMessage.Start, GameMessage.Draw, + GameMessage.ShuffleDeck, GameMessage.ShuffleHand, GameMessage.ShuffleExtra, GameMessage.ShuffleSetCard, + GameMessage.SwapGraveDeck, GameMessage.TagSwap, + GameMessage.NewTurn, GameMessage.NewPhase, + GameMessage.Damage, GameMessage.PayLpCost, GameMessage.Recover, GameMessage.LpUpdate, + GameMessage.Move, GameMessage.Swap, + GameMessage.Attack, GameMessage.Battle, GameMessage.AttackDisabled, GameMessage.PosChange, + GameMessage.Chaining, GameMessage.ChainSolving, GameMessage.ChainNegated, + GameMessage.ChainDisabled, GameMessage.ChainSolved, GameMessage.ChainEnd, + GameMessage.UpdateCard, GameMessage.UpdateData, GameMessage.BecomeTarget, + GameMessage.Equip, GameMessage.Unequip, GameMessage.CardTarget, GameMessage.CancelTarget, + GameMessage.Summoning, GameMessage.Summoned, GameMessage.SpSummoning, GameMessage.SpSummoned, + GameMessage.FlipSummoning, GameMessage.FlipSummoned, GameMessage.ConfirmCards, + }; + + /// [YGOL] Replay one received packet into the mirror. + public void YGOL_MirrorPacket(BinaryReader packet) + { + StocMessage id = (StocMessage)packet.ReadByte(); + if (id != StocMessage.GameMsg) + return; + GameMessage msg = (GameMessage)packet.ReadByte(); + if (!YGOL_MirrorMessages.Contains(msg)) + return; + Action handler; + if (_messages.TryGetValue(msg, out handler)) + handler(packet); + _lastMessage = msg; + } + #endregion + + public int GetLocalPlayer(int player) + { + return _duel.IsFirst ? player : 1 - player; + } + + public void OnPacket(BinaryReader packet) + { + _router.Dispatch(packet, out _); // [YGOL] TICKET-164: was the _packets lookup; a throwing handler still escapes here + } + + // [YGOL] TICKET-164: the GameMsg branch OnPacket used to hold, now one _packets handler like the rest. + private void OnGameMsg(BinaryReader packet) + { + GameMessage msg = (GameMessage)packet.ReadByte(); + if (_messages.ContainsKey(msg)) + _messages[msg](packet); + _lastMessage = msg; + } + + private void RegisterPackets() + { + _packets.Add(StocMessage.JoinGame, OnJoinGame); + _packets.Add(StocMessage.TypeChange, OnTypeChange); + _packets.Add(StocMessage.HsPlayerEnter, OnPlayerEnter); + _packets.Add(StocMessage.HsPlayerChange, OnPlayerChange); + _packets.Add(StocMessage.SelectHand, OnSelectHand); + _packets.Add(StocMessage.SelectTp, OnSelectTp); + _packets.Add(StocMessage.TimeLimit, OnTimeLimit); + _packets.Add(StocMessage.Replay, OnReplay); + _packets.Add(StocMessage.DuelEnd, OnDuelEnd); + _packets.Add(StocMessage.Chat, OnChat); + _packets.Add(StocMessage.ChangeSide, OnChangeSide); + _packets.Add(StocMessage.ErrorMsg, OnErrorMsg); + _packets.Add(StocMessage.TeammateSurrender, OnTeammateSurrender); + _packets.Add(StocMessage.GameMsg, OnGameMsg); // [YGOL] TICKET-164 + + _messages.Add(GameMessage.Retry, OnRetry); + _messages.Add(GameMessage.Start, OnStart); + _messages.Add(GameMessage.Hint, OnHint); + _messages.Add(GameMessage.Win, OnWin); + _messages.Add(GameMessage.Draw, OnDraw); + _messages.Add(GameMessage.ShuffleDeck, OnShuffleDeck); + _messages.Add(GameMessage.ShuffleHand, OnShuffleHand); + _messages.Add(GameMessage.ShuffleExtra, OnShuffleExtra); + _messages.Add(GameMessage.ShuffleSetCard, OnShuffleSetCard); + _messages.Add(GameMessage.SwapGraveDeck, OnSwapGraveDeck); + _messages.Add(GameMessage.TagSwap, OnTagSwap); + _messages.Add(GameMessage.NewTurn, OnNewTurn); + _messages.Add(GameMessage.NewPhase, OnNewPhase); + _messages.Add(GameMessage.Damage, OnDamage); + _messages.Add(GameMessage.PayLpCost, OnDamage); + _messages.Add(GameMessage.Recover, OnRecover); + _messages.Add(GameMessage.LpUpdate, OnLpUpdate); + _messages.Add(GameMessage.Move, OnMove); + _messages.Add(GameMessage.Swap, OnSwap); + _messages.Add(GameMessage.Attack, OnAttack); + _messages.Add(GameMessage.Battle, OnBattle); + _messages.Add(GameMessage.AttackDisabled, OnAttackDisabled); + _messages.Add(GameMessage.PosChange, OnPosChange); + _messages.Add(GameMessage.Chaining, OnChaining); + _messages.Add(GameMessage.ChainSolving, OnChainSolving); + _messages.Add(GameMessage.ChainNegated, OnChainNegated); + _messages.Add(GameMessage.ChainDisabled, OnChainDisabled); + _messages.Add(GameMessage.ChainSolved, OnChainSolved); + _messages.Add(GameMessage.ChainEnd, OnChainEnd); + _messages.Add(GameMessage.SortCard, OnCardSorting); + _messages.Add(GameMessage.SortChain, OnChainSorting); + _messages.Add(GameMessage.UpdateCard, OnUpdateCard); + _messages.Add(GameMessage.UpdateData, OnUpdateData); + _messages.Add(GameMessage.BecomeTarget, OnBecomeTarget); + _messages.Add(GameMessage.SelectBattleCmd, OnSelectBattleCmd); + _messages.Add(GameMessage.SelectCard, OnSelectCard); + _messages.Add(GameMessage.SelectUnselect, OnSelectUnselectCard); + _messages.Add(GameMessage.SelectChain, OnSelectChain); + _messages.Add(GameMessage.SelectCounter, OnSelectCounter); + _messages.Add(GameMessage.SelectDisfield, OnSelectDisfield); + _messages.Add(GameMessage.SelectEffectYn, OnSelectEffectYn); + _messages.Add(GameMessage.SelectIdleCmd, OnSelectIdleCmd); + _messages.Add(GameMessage.SelectOption, OnSelectOption); + _messages.Add(GameMessage.SelectPlace, OnSelectPlace); + _messages.Add(GameMessage.SelectPosition, OnSelectPosition); + _messages.Add(GameMessage.SelectSum, OnSelectSum); + _messages.Add(GameMessage.SelectTribute, OnSelectTribute); + _messages.Add(GameMessage.SelectYesNo, OnSelectYesNo); + _messages.Add(GameMessage.AnnounceAttrib, OnAnnounceAttrib); + _messages.Add(GameMessage.AnnounceCard, OnAnnounceCard); + _messages.Add(GameMessage.AnnounceNumber, OnAnnounceNumber); + _messages.Add(GameMessage.AnnounceRace, OnAnnounceRace); + _messages.Add(GameMessage.RockPaperScissors, OnRockPaperScissors); + _messages.Add(GameMessage.Equip, OnEquip); + _messages.Add(GameMessage.Unequip, OnUnEquip); + _messages.Add(GameMessage.CardTarget, OnCardTarget); + _messages.Add(GameMessage.CancelTarget, OnCancelTarget); + _messages.Add(GameMessage.Summoning, OnSummoning); + _messages.Add(GameMessage.Summoned, OnSummoned); + _messages.Add(GameMessage.SpSummoning, OnSpSummoning); + _messages.Add(GameMessage.SpSummoned, OnSpSummoned); + _messages.Add(GameMessage.FlipSummoning, OnSummoning); + _messages.Add(GameMessage.FlipSummoned, OnSummoned); + _messages.Add(GameMessage.ConfirmCards, OnConfirmCards); + _messages.Add(GameMessage.PlayerHint, OnPlayerHint); + + // [YGOL] TICKET-164: _packets stays the registration list; the router is what OnPacket asks. + // The enums agree by value (ProtocolCodecTests pins it), so the cast is the whole bridge. + _router = new YGOLegacy.Protocol.Routing.StocRouter(); + _router.OnUnknown = (id, bytes) => Logger.DebugWriteLine("[YGOL net] unknown STOC 0x" + ((int)id).ToString("X2") + " (" + bytes + " bytes)"); + foreach (var pair in _packets) + _router.Register((YGOLegacy.Protocol.Contracts.StocMessage)(int)pair.Key, pair.Value); + // Received and dropped on purpose, so an unknown-id line means nobody owns it. + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.HandResult); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.TpResult); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.DeckCount); + _router.Register(YGOLegacy.Protocol.Contracts.StocMessage.DuelStart, _ => _ygolStarted = true); // [YGOL] TICKET-285: host orders stop here + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.HsWatchChange); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.WaitingSide); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.CreateGame); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.LeaveGame); + // [YGOL] TICKET-171: the fork's feature messages; a bot sends its own and consumes none. + _router.Register(YGOLegacy.Protocol.Contracts.StocMessage.Capability, p => // [YGOL] TICKET-299: only the server's own line matters to a bot + { + var line = StocCodecs.Capability.Read(p); + if (line.Seat == YGOLegacy.Protocol.Contracts.Capability.ServerSender) + _ygolRoomKept = line.Payload.Has(YGOLegacy.Protocol.Contracts.FeatureFlags.LobbyAfterMatch); + }); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.Appearance); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.Dialogue); + // [YGOL] TICKET-286: the restart messages; the host owns this bot and restarts it itself. + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.RoomRestarting); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.RestartStatus); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.SeatResumeResult); + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.RestartOpen); + _router.Register(YGOLegacy.Protocol.Contracts.StocMessage.MatchOver, YGOL_OnMatchOver); // [YGOL] TICKET-299 + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.CoinToss); // [YGOL] TICKET-329: the bot answers SELECT_TP; the toss is only for the screen + _router.Ignore(YGOLegacy.Protocol.Contracts.StocMessage.Profile); // [YGOL] TICKET-360: a bot shows no avatars and never sends its own + } + + // [YGOL] TICKET-299: the server kept the room; this seat is held unready until the host's START (YGOL_ReleaseReady completes it). + private void YGOL_OnMatchOver(BinaryReader packet) + { + var over = StocCodecs.MatchOver.Read(packet); + if (over.Seat != YGOLegacy.Protocol.Contracts.Capability.ServerSender) + return; + _ygolStarted = false; + for (int i = 0; i < _room.IsReady.Length; i++) + _room.IsReady[i] = false; + Game.YGOL_HoldReady = true; + Game.YGOL_RestartId = new byte[YGOLegacy.Protocol.Contracts.SeatPlan.IdBytes]; + if (Deck != null) + YGOL_SendDeck(); + _ai.OnJoinGame(); + } + + private void OnJoinGame(BinaryReader packet) + { + int duel_rule = StocCodecs.JoinGame.Read(packet).DuelRule; // [YGOL] TICKET-165 + _ai.Duel.IsNewRule = (duel_rule >= 4); + _ai.Duel.IsNewRule2020 = (duel_rule >= 5); + YGOL_SendFeatures(); // [YGOL] TICKET-171: before the deck - UpdateDeck readies the seat, and a ready seat without Capability is kicked by a new host + if (Deck != null || !Game.YGOL_DeferDeck) // [YGOL] TICKET-285: a deferred bot sits down deckless and unready + YGOL_SendDeck(); // [YGOL] TICKET-161 + _ai.OnJoinGame(); + } + + // [YGOL] TICKET-171: Capability (appearance only, a bot has no dialogue) then the explicit Appearance for this seat. Only here: + // the server drops a Capability that arrives before it processed JoinGame, and at TypeChange the bot is already ready. + private void YGOL_SendFeatures() + { + BinaryWriter capability = CtosPacket.Begin(LobbyCodecs.Capability.Id); + LobbyCodecs.Capability.Write(capability, new YGOLegacy.Protocol.Contracts.Capability( + YGOLegacy.Protocol.Contracts.Capability.ProtocolVersion, YGOLegacy.Protocol.Contracts.FeatureFlags.Appearance)); + Connection.Send(capability); + YGOL_SendAppearance(); + } + + // [YGOL] TICKET-285: split from YGOL_SendFeatures so a deck assignment re-announces only the appearance. + private void YGOL_SendAppearance() + { + string deckFile = Game.DeckFile ?? string.Empty; + int cut = deckFile.LastIndexOf('/'); + string deckName = cut < 0 ? deckFile : deckFile.Substring(cut + 1); + string group = Game.Group ?? (cut < 0 ? string.Empty : deckFile.Substring(0, cut)); + BinaryWriter appearance = CtosPacket.Begin(LobbyCodecs.Appearance.Id); + LobbyCodecs.Appearance.Write(appearance, new YGOLegacy.Protocol.Contracts.AppearanceState( + null, deckName, Game.Character ?? string.Empty, group)); + Connection.Send(appearance); + } + + private void OnChangeSide(BinaryReader packet) + { + YGOL_SendDeck(); // [YGOL] TICKET-161 + _ai.OnJoinGame(); + } + + // [YGOL] TICKET-161: one deck write through the shared codec (was duplicated above). + private void YGOL_SendDeck() + { + BinaryWriter deck = CtosPacket.Begin(LobbyCodecs.UpdateDeck.Id); + LobbyCodecs.UpdateDeck.Write(deck, new YGOLegacy.Protocol.Contracts.UpdateDeck( + Deck.Cards.Select(c => c.Id).ToArray(), + Deck.ExtraCards.Select(c => c.Id).ToArray(), + Deck.SideCards.Select(c => c.Id).ToArray())); + Connection.Send(deck); + } + + private void OnTypeChange(BinaryReader packet) + { + var type = StocCodecs.TypeChange.Read(packet); // [YGOL] TICKET-165 + int pos = type.Position; + if (pos < 0 || pos > 3) + { + Connection.Close(); + return; + } + _room.Position = pos; + Game.YGOL_Position = pos; // [YGOL] TICKET-285: the host reads where this bot actually sits + _room.IsHost = type.IsHost; + if (Game.YGOL_DeferDeck) // [YGOL] TICKET-285: no deck yet, so not ready; an assigned deck goes up before the ready + { + if (Deck == null) + return; + YGOL_SendAppearance(); + YGOL_SendDeck(); + if (YGOL_HoldOrComplete()) // [YGOL] TICKET-286 + return; + } + _room.IsReady[pos] = true; + Connection.Send(CtosMessage.HsReady); + } + + // [YGOL] TICKET-286: a restart's CPU finishes its seat (SeatResume Complete, READY stays false) and waits for the host's START. + private bool YGOL_HoldOrComplete() + { + if (Game.YGOL_RestartId != null) + { + BinaryWriter resume = CtosPacket.Begin(LobbyCodecs.SeatResume.Id); + LobbyCodecs.SeatResume.Write(resume, new YGOLegacy.Protocol.Contracts.SeatResume( + Game.YGOL_RestartId, YGOLegacy.Protocol.Contracts.SeatResumeAction.Complete, 0)); + Connection.Send(resume); + Game.YGOL_RestartId = null; + } + return Game.YGOL_HoldReady; + } + + // The server readies a seat on UpdateDeck alone (HsReady is not read in server mode), so the deck goes up again. + public void YGOL_ReleaseReady() + { + if (_ygolStarted || !Connection.IsConnected || _room.Position < 0) + return; + Game.YGOL_HoldReady = false; + if (Deck == null || _room.IsReady[_room.Position]) + return; + YGOL_HoldOrComplete(); // [YGOL] TICKET-299: a seat held since the match end completes (zero id) before its deck readies it + YGOL_SendDeck(); + _room.IsReady[_room.Position] = true; + Connection.Send(CtosMessage.HsReady); + } + + // [YGOL] TICKET-285: the host's in-process deck order (proposal 20 rule 4): unready, load, rebuild the executor so + // the brain follows the deck, announce, upload (the server readies on UpdateDeck), ready. No kick, no respawn. + private bool _ygolStarted; + + public void YGOL_ApplyDeck(string deckFile, string executor, string character, string group) + { + if (_ygolStarted || !Connection.IsConnected) + return; + Deck deck = Deck.Load(deckFile); + if (deck == null) + { + Logger.WriteErrorLine("[YGOL] could not load assigned deck " + deckFile); + return; + } + Game.DeckFile = deckFile; + if (!string.IsNullOrEmpty(executor)) + Game.Deck = executor; + Game.Character = character; + Game.Group = group; + _ai.Executor = DecksManager.Instantiate(_ai, _duel); + Deck = deck; + Game.YGOL_HasDeck = true; + if (_room.Position < 0) + return; + Connection.Send(CtosMessage.HsNotReady); + _room.IsReady[_room.Position] = false; + YGOL_SendAppearance(); + YGOL_SendDeck(); + if (YGOL_HoldOrComplete()) // [YGOL] TICKET-286 + return; + _room.IsReady[_room.Position] = true; + Connection.Send(CtosMessage.HsReady); + } + + public void YGOL_ApplyDifficulty(string difficulty) + { + if (_ygolStarted) + return; + Game.YGOL_Difficulty = string.IsNullOrEmpty(difficulty) ? null : difficulty; + _ai.Executor = DecksManager.Instantiate(_ai, _duel); + } + + // [YGOL] S5 + public void YGOL_ApplyBrain(string executor, IReadOnlyDictionary knobs, bool debug) + { + if (_ygolStarted) + return; + Game.YGOL_Knobs = knobs; + if (!string.IsNullOrEmpty(executor)) + Game.Deck = executor; + Game.Debug = _debug = debug; + _ai.Executor = DecksManager.Instantiate(_ai, _duel); + } + + private void OnPlayerEnter(BinaryReader packet) + { + var enter = StocCodecs.HsPlayerEnter.Read(packet); // [YGOL] TICKET-165 + string name = enter.Name; + int pos = enter.Position; + if (pos < 8) + _room.Names[pos] = name; + } + + private void OnPlayerChange(BinaryReader packet) + { + var change = StocCodecs.HsPlayerChange.Read(packet); // [YGOL] TICKET-165 + int pos = change.Position; + int state = change.State; + if (pos > 3) + return; + if (state < 8) + { + string oldname = _room.Names[pos]; + _room.Names[pos] = null; + _room.Names[state] = oldname; + _room.IsReady[pos] = false; + _room.IsReady[state] = false; + } + else if (state == (int)PlayerChange.Ready) + _room.IsReady[pos] = true; + else if (state == (int)PlayerChange.NotReady) + _room.IsReady[pos] = false; + else if (state == (int)PlayerChange.Leave || state == (int)PlayerChange.Observe) + { + _room.IsReady[pos] = false; + _room.Names[pos] = null; + } + + if (_room.IsHost && _room.IsReady[0] && _room.IsReady[1]) + Connection.Send(CtosMessage.HsStart); + } + + private void OnSelectHand(BinaryReader packet) + { + int result; + if (_hand > 0) + result = _hand; + else + result = _ai.OnRockPaperScissors(); + Connection.Send(CtosMessage.HandResult, (byte)result); + } + + // [YGOL] The intro shows a local CPU's pick the moment it is made; the server only tells the room at MSG_START. Raised on the bot thread. + public static event Action YGOL_TurnChosen; + + private void OnSelectTp(BinaryReader packet) + { + bool start = _ai.OnSelectHand(); + YGOL_TurnChosen?.Invoke(start); // [YGOL] + Connection.Send(CtosMessage.TpResult, (byte)(start ? 1 : 0)); + } + + private void OnTimeLimit(BinaryReader packet) + { + int player = GetLocalPlayer(StocCodecs.TimeLimit.Read(packet).Player); // [YGOL] TICKET-165 + if (player == 0) + Connection.Send(CtosMessage.TimeConfirm); + } + + /// + /// [YGOL] Bot Arena (TICKET-035): the finished duel's replay as the + /// server sent it (STOC_REPLAY payload = the .yrp bytes), raised on the + /// bot thread with this bot's Username. Upstream WindBot discards it. + /// + public static event Action YGOL_Replay; + + private void OnReplay(BinaryReader packet) + { + byte[] replay = packet.ReadToEnd(); + // [YGOL] see YGOL_Replay. + try { YGOL_Replay?.Invoke(Game.Username, replay); } catch (Exception) { } + + /* + const string directory = "Replays"; + if (!Directory.Exists(directory)) + Directory.CreateDirectory(directory); + + string otherName = _room.Position == 0 ? _room.Names[1] : _room.Names[0]; + string file = DateTime.Now.ToString("yyyy-MM-dd.HH-mm.") + otherName + ".yrp"; + string fullname = Path.Combine(directory, file); + + if (Regex.IsMatch(file, @"^[\w\-. ]+$")) + File.WriteAllBytes(fullname, replay); + */ + + //Connection.Close(); + } + + private bool _ygolRoomKept; // [YGOL] TICKET-299: the server returns to the lobby after the match; MATCH_OVER follows DUEL_END + + private void OnDuelEnd(BinaryReader packet) + { + if (_ygolRoomKept) + return; + Thread.Sleep(500); + Connection.Close(); + } + + private void OnChat(BinaryReader packet) + { + var chat = StocCodecs.Chat.Read(packet); // [YGOL] TICKET-165 + int player = chat.Player; + string message = chat.Text; + string myName = (player != 0) ? _room.Names[1] : _room.Names[0]; + string otherName = (player == 0) ? _room.Names[1] : _room.Names[0]; + if (player < 4) + Logger.DebugWriteLine(otherName + " say to " + myName + ": " + message); + else + Logger.DebugWriteLine("System message(" + player + "): " + message); + } + + private void OnErrorMsg(BinaryReader packet) + { + var error = StocCodecs.ErrorMsg.Read(packet); // [YGOL] TICKET-165 + int msg = error.Msg; + int pcode = error.Code; + Logger.DebugWriteLine("Error message received: " + msg + ", code: " + pcode); + if (msg == 2) //ERRMSG_DECKERROR + { + int code = pcode & 0xFFFFFFF; + int flag = pcode >> 28; + if (flag <= 5) //DECKERROR_CARDCOUNT + { + NamedCard card = NamedCard.Get(code); + if (card != null) + _ai.OnDeckError(card.Name); + else + _ai.OnDeckError("Unknown Card"); + } + else + _ai.OnDeckError("DECK"); + } + //Connection.Close(); + } + + private void OnTeammateSurrender(BinaryReader packet) + { + Thread.Sleep(500); + Game.Surrender(); + } + + private void OnRetry(BinaryReader packet) + { + _ai.OnRetry(); + Connection.Close(); + throw new Exception("Got MSG_RETRY. Last message is " + _lastMessage); + } + + private void OnHint(BinaryReader packet) + { + int type = packet.ReadByte(); + int player = packet.ReadByte(); + int data = packet.ReadInt32(); + if (type == 1) // HINT_EVENT + { + if (data == 24) // battling + { + _duel.Fields[0].UnderAttack = false; + _duel.Fields[1].UnderAttack = false; + } + } + if (type == 3) // HINT_SELECTMSG + { + _select_hint = data; + } + if (type == 4) // HINT_OPSELECTED + { + _ai.OnReceivingAnnouce(player, data); + } + if (type == 11) // HINT_ZONE + { + Logger.DebugWriteLine("HINT_ZONE received: player=" + player + ", zone=" + data); + _ai.OnHintZone(player, data); + } + } + + private void OnStart(BinaryReader packet) + { + int type = packet.ReadByte(); + _duel.IsFirst = (type & 0xF) == 0; + _duel.Turn = 0; + _duel.LastChainLocation = 0; + _duel.LastChainPlayer = -1; + _duel.LastChainTargets.Clear(); + _duel.LastSummonedCards.Clear(); + _duel.LastSummonPlayer = -1; + int duel_rule = packet.ReadByte(); + _ai.Duel.IsNewRule = (duel_rule >= 4); + _ai.Duel.IsNewRule2020 = (duel_rule >= 5); + _duel.Fields[GetLocalPlayer(0)].LifePoints = packet.ReadInt32(); + _duel.Fields[GetLocalPlayer(1)].LifePoints = packet.ReadInt32(); + int deck = packet.ReadInt16(); + int extra = packet.ReadInt16(); + _duel.Fields[GetLocalPlayer(0)].Init(deck, extra); + deck = packet.ReadInt16(); + extra = packet.ReadInt16(); + _duel.Fields[GetLocalPlayer(1)].Init(deck, extra); + + // in case of ending duel in chain's solving + _duel.CurrentChain.Clear(); + _duel.CurrentChainInfo.Clear(); + _duel.ChainTargets.Clear(); + _duel.ChainTargetOnly.Clear(); + _duel.SummoningCards.Clear(); + _duel.SolvingChainIndex = 0; + _duel.NegatedChainIndexList.Clear(); + + Logger.DebugWriteLine("Duel started: " + _room.Names[0] + " versus " + _room.Names[1]); + _ai.OnStart(); + } + + /// + /// [YGOL] Bot Arena (TICKET-030): a bot's own verdict on its duel, raised + /// on the bot thread from OnWin. Args: this bot's Username, result + /// (0 = win, 1 = lose, 2 = draw), the turn count it saw. Each bot + /// already knows whether IT won, so the arena reads the outcome here + /// instead of guessing seat-to-player mapping from the observer stream. + /// + public static event Action YGOL_DuelResult; + + private void OnWin(BinaryReader packet) + { + int result = GetLocalPlayer(packet.ReadByte()); + + string otherName = _room.Position == 0 ? _room.Names[1] : _room.Names[0]; + string textResult = (result == 2 ? "Draw" : result == 0 ? "Win" : "Lose"); + Logger.DebugWriteLine("Duel finished against " + otherName + ", result: " + textResult); + // [YGOL] see YGOL_DuelResult. + try { YGOL_DuelResult?.Invoke(Game.Username, result, _duel.Turn); } catch (Exception) { } + } + + private void OnDraw(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + int count = packet.ReadByte(); + if (_debug) + Logger.WriteLine("(" + player.ToString() + " draw " + count.ToString() + " card)"); + + for (int i = 0; i < count; ++i) + { + _duel.Fields[player].Deck.RemoveAt(_duel.Fields[player].Deck.Count - 1); + _duel.Fields[player].Hand.Add(new ClientCard(0, CardLocation.Hand, -1)); + } + _ai.OnDraw(player); + } + + private void OnShuffleDeck(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + foreach (ClientCard card in _duel.Fields[player].Deck) + card.SetId(0); + } + + private void OnShuffleHand(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + packet.ReadByte(); + foreach (ClientCard card in _duel.Fields[player].Hand) + card.SetId(packet.ReadInt32()); + } + + private void OnShuffleExtra(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + packet.ReadByte(); + foreach (ClientCard card in _duel.Fields[player].ExtraDeck) + { + if (!card.IsFaceup()) + card.SetId(packet.ReadInt32()); + } + } + + private void OnShuffleSetCard(BinaryReader packet) + { + int location = packet.ReadByte(); + int count = packet.ReadByte(); + ClientCard[] list = new ClientCard[5]; + for (int i = 0; i < count; ++i) + { + int player = GetLocalPlayer(packet.ReadByte()); + int loc = packet.ReadByte(); + int seq = packet.ReadByte(); + /*int sseq = */packet.ReadByte(); + ClientCard card = _duel.GetCard(player, (CardLocation)loc, seq); + if (card == null) continue; + list[i] = card; + card.SetId(0); + } + for (int i = 0; i < count; ++i) + { + int player = GetLocalPlayer(packet.ReadByte()); + int loc = packet.ReadByte(); + int seq = packet.ReadByte(); + /*int sseq = */packet.ReadByte(); + ClientCard card = _duel.GetCard(player, (CardLocation)loc, seq); + if (card == null) continue; + ClientCard[] zone = (loc == (int)CardLocation.MonsterZone) ? _duel.Fields[player].MonsterZone : _duel.Fields[player].SpellZone; + zone[seq] = list[i]; + } + } + + private void OnSwapGraveDeck(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + IList tmpDeckList = _duel.Fields[player].Deck.ToList(); + _duel.Fields[player].Deck.Clear(); + int seq = 0; + foreach(var card in _duel.Fields[player].Graveyard) + { + if (card.IsExtraCard()) + { + _duel.Fields[player].ExtraDeck.Add(card); + card.Location = CardLocation.Extra; + card.Position = (int)CardPosition.FaceDown; + // TODO: face-up P cards + } + else + { + _duel.Fields[player].Deck.Add(card); + card.Location = CardLocation.Deck; + card.Sequence = seq++; + } + } + _duel.Fields[player].Graveyard.Clear(); + foreach (var card in tmpDeckList) + { + _duel.Fields[player].Graveyard.Add(card); + card.Location = CardLocation.Grave; + } + } + + private void OnTagSwap(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + int mcount = packet.ReadByte(); + int ecount = packet.ReadByte(); + /*int pcount = */ packet.ReadByte(); + int hcount = packet.ReadByte(); + /*int topcode =*/ packet.ReadInt32(); + _duel.Fields[player].Deck.Clear(); + for (int i = 0; i < mcount; ++i) + { + _duel.Fields[player].Deck.Add(new ClientCard(0, CardLocation.Deck, -1)); + } + _duel.Fields[player].ExtraDeck.Clear(); + for (int i = 0; i < ecount; ++i) + { + int code = packet.ReadInt32() & 0x7fffffff; + _duel.Fields[player].ExtraDeck.Add(new ClientCard(code, CardLocation.Extra, -1)); + } + _duel.Fields[player].Hand.Clear(); + for (int i = 0; i < hcount; ++i) + { + int code = packet.ReadInt32(); + _duel.Fields[player].Hand.Add(new ClientCard(code, CardLocation.Hand,-1)); + } + } + + private void OnNewTurn(BinaryReader packet) + { + _duel.Turn++; + _duel.Player = GetLocalPlayer(packet.ReadByte()); + _ai.OnNewTurn(); + } + + private void OnNewPhase(BinaryReader packet) + { + _duel.Phase = (DuelPhase)packet.ReadInt16(); + if (_debug && _duel.Phase == DuelPhase.Standby) + { + Logger.WriteLine("*********Bot Hand*********"); + foreach (ClientCard card in _duel.Fields[0].Hand) + { + Logger.WriteLine(card.Name); + } + Logger.WriteLine("*********Bot Spell*********"); + foreach (ClientCard card in _duel.Fields[0].SpellZone) + { + Logger.WriteLine(card?.Name); + } + Logger.WriteLine("*********Bot Monster*********"); + foreach (ClientCard card in _duel.Fields[0].MonsterZone) + { + Logger.WriteLine(card?.Name); + } + Logger.WriteLine("*********Finish*********"); + } + if (_debug) + Logger.WriteLine("(Go to " + (_duel.Phase.ToString()) + ")"); + _duel.LastSummonPlayer = -1; + _duel.SummoningCards.Clear(); + _duel.LastSummonedCards.Clear(); + _duel.Fields[0].BattlingMonster = null; + _duel.Fields[1].BattlingMonster = null; + _duel.Fields[0].UnderAttack = false; + _duel.Fields[1].UnderAttack = false; + List monsters = _duel.Fields[0].GetMonsters(); + foreach (ClientCard monster in monsters) + { + monster.Attacked = false; + } + _select_hint = 0; + _ai.OnNewPhase(); + } + + private void OnDamage(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + int final = _duel.Fields[player].LifePoints - packet.ReadInt32(); + if (final < 0) final = 0; + if (_debug) + Logger.WriteLine("(" + player.ToString() + " got damage , LifePoint left = " + final.ToString() + ")"); + _duel.Fields[player].LifePoints = final; + } + + private void OnRecover(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + int final = _duel.Fields[player].LifePoints + packet.ReadInt32(); + if (_debug) + Logger.WriteLine("(" + player.ToString() + " got healed , LifePoint left = " + final.ToString() + ")"); + _duel.Fields[player].LifePoints = final; + } + + private void OnLpUpdate(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + _duel.Fields[player].LifePoints = packet.ReadInt32(); + } + + private void OnMove(BinaryReader packet) + { + // TODO: update equip cards and target cards + int cardId = packet.ReadInt32(); + int previousControler = GetLocalPlayer(packet.ReadByte()); + int previousLocation = packet.ReadByte(); + int previousSequence = packet.ReadSByte(); + /*int previousPosotion = */packet.ReadSByte(); + int currentControler = GetLocalPlayer(packet.ReadByte()); + int currentLocation = packet.ReadByte(); + int currentSequence = packet.ReadSByte(); + int currentPosition = packet.ReadSByte(); + packet.ReadInt32(); // reason + + ClientCard card = _duel.GetCard(previousControler, (CardLocation)previousLocation, previousSequence); + if (card != null) + { + card.LastLocation = (CardLocation)previousLocation; + } + if ((previousLocation & (int)CardLocation.Overlay) != 0) + { + previousLocation = previousLocation & 0x7f; + card = _duel.GetCard(previousControler, (CardLocation)previousLocation, previousSequence); + if (card != null) + { + if (_debug) + Logger.WriteLine("(" + previousControler.ToString() + " 's " + (card.Name ?? "UnKnowCard") + " deattach " + (NamedCard.Get(cardId)?.Name) + ")"); + card.Overlays.Remove(cardId); + } + previousLocation = 0; // the card is removed when it go to overlay, so here we treat it as a new card + } + else + _duel.RemoveCard((CardLocation)previousLocation, card, previousControler, previousSequence); + + if ((currentLocation & (int)CardLocation.Overlay) != 0) + { + currentLocation = currentLocation & 0x7f; + card = _duel.GetCard(currentControler, (CardLocation)currentLocation, currentSequence); + if (card != null) + { + if (_debug) + Logger.WriteLine("(" + previousControler.ToString() + " 's " + (card.Name ?? "UnKnowCard") + " overlay " + (NamedCard.Get(cardId)?.Name) + ")"); + card.Overlays.Add(cardId); + } + } + else + { + if (previousLocation == 0) + { + if (_debug) + Logger.WriteLine("(" + previousControler.ToString() + " 's " + (NamedCard.Get(cardId)?.Name) + + " appear in " + (CardLocation)currentLocation + ")"); + _duel.AddCard((CardLocation)currentLocation, cardId, currentControler, currentSequence, currentPosition); + } + else + { + _duel.AddCard((CardLocation)currentLocation, card, currentControler, currentSequence, currentPosition, cardId); + if (card != null && previousLocation != currentLocation) + card.IsSpecialSummoned = false; + if (_debug && card != null) + Logger.WriteLine("(" + previousControler.ToString() + " 's " + (card.Name ?? "UnKnowCard") + + " from " + + (CardLocation)previousLocation + " move to " + (CardLocation)currentLocation + ")"); + } + } + + _ai.OnMove(card, previousControler, previousLocation, currentControler, currentLocation); + } + + private void OnSwap(BinaryReader packet) + { + int cardId1 = packet.ReadInt32(); + int controler1 = GetLocalPlayer(packet.ReadByte()); + int location1 = packet.ReadByte(); + int sequence1 = packet.ReadByte(); + packet.ReadByte(); + int cardId2 = packet.ReadInt32(); + int controler2 = GetLocalPlayer(packet.ReadByte()); + int location2 = packet.ReadByte(); + int sequence2 = packet.ReadByte(); + packet.ReadByte(); + ClientCard card1 = _duel.GetCard(controler1, (CardLocation)location1, sequence1); + ClientCard card2 = _duel.GetCard(controler2, (CardLocation)location2, sequence2); + if (card1 == null || card2 == null) return; + _duel.RemoveCard((CardLocation)location1, card1, controler1, sequence1); + _duel.RemoveCard((CardLocation)location2, card2, controler2, sequence2); + _duel.AddCard((CardLocation)location2, card1, controler2, sequence2, card1.Position, cardId1); + _duel.AddCard((CardLocation)location1, card2, controler1, sequence1, card2.Position, cardId2); + } + + private void OnAttack(BinaryReader packet) + { + int ca = GetLocalPlayer(packet.ReadByte()); + int la = packet.ReadByte(); + int sa = packet.ReadByte(); + packet.ReadByte(); // + int cd = GetLocalPlayer(packet.ReadByte()); + int ld = packet.ReadByte(); + int sd = packet.ReadByte(); + packet.ReadByte(); // + + ClientCard attackcard = _duel.GetCard(ca, (CardLocation)la, sa); + ClientCard defendcard = _duel.GetCard(cd, (CardLocation)ld, sd); + if (_debug) + { + if (defendcard == null) Logger.WriteLine("(" + (attackcard.Name ?? "UnKnowCard") + " direct attack!!)"); + else Logger.WriteLine("(" + ca.ToString() + " 's " + (attackcard.Name ?? "UnKnowCard") + " attack " + cd.ToString() + " 's " + (defendcard.Name ?? "UnKnowCard") + ")"); + } + _duel.Fields[attackcard.Controller].BattlingMonster = attackcard; + _duel.Fields[1 - attackcard.Controller].BattlingMonster = defendcard; + _duel.Fields[1 - attackcard.Controller].UnderAttack = true; + + if (ld == 0 && ca != 0) + { + _ai.OnDirectAttack(attackcard); + } + } + + private void OnBattle(BinaryReader packet) + { + _duel.Fields[0].UnderAttack = false; + _duel.Fields[1].UnderAttack = false; + } + + private void OnAttackDisabled(BinaryReader packet) + { + _duel.Fields[0].UnderAttack = false; + _duel.Fields[1].UnderAttack = false; + } + + private void OnPosChange(BinaryReader packet) + { + packet.ReadInt32(); // card id + int pc = GetLocalPlayer(packet.ReadByte()); + int pl = packet.ReadByte(); + int ps = packet.ReadSByte(); + int pp = packet.ReadSByte(); + int cp = packet.ReadSByte(); + ClientCard card = _duel.GetCard(pc, (CardLocation)pl, ps); + if (card != null) + { + card.Position = cp; + if ((pp & (int) CardPosition.FaceUp) > 0 && (cp & (int) CardPosition.FaceDown) > 0) + card.ClearCardTargets(); + if (_debug) + Logger.WriteLine("(" + (card.Name ?? "UnKnowCard") + " change position to " + (CardPosition)cp + ")"); + } + } + + private void OnChaining(BinaryReader packet) + { + int cardId = packet.ReadInt32(); + int pcc = GetLocalPlayer(packet.ReadByte()); + int pcl = packet.ReadByte(); + int pcs = packet.ReadSByte(); + int subs = packet.ReadSByte(); + ClientCard card = _duel.GetCard(pcc, pcl, pcs, subs); + if (card.Id == 0) + card.SetId(cardId); + int cc = GetLocalPlayer(packet.ReadByte()); + packet.ReadInt16(); // trigger location + trigger sequence + int desc = packet.ReadInt32(); + if (_debug) + if (card != null) Logger.WriteLine("(" + cc.ToString() + " 's " + (card.Name ?? "UnKnowCard") + " activate effect from " + (CardLocation)pcl + ")"); + _duel.LastChainLocation = (CardLocation)pcl; + _ai.OnChaining(card, cc); + //_duel.ChainTargets.Clear(); + _duel.ChainTargetOnly.Clear(); + _duel.LastSummonPlayer = -1; + _duel.CurrentChain.Add(card); + _duel.CurrentChainInfo.Add(new ChainInfo(card, cc, desc)); + _duel.LastChainPlayer = cc; + + } + + private void OnChainSolving(BinaryReader packet) + { + int chainIndex = packet.ReadByte(); + _duel.SolvingChainIndex = chainIndex; + } + + private void OnChainNegated(BinaryReader packet) + { + int chainIndex = packet.ReadByte(); + _duel.NegatedChainIndexList.Add(chainIndex); + } + + private void OnChainDisabled(BinaryReader packet) + { + int chainIndex = packet.ReadByte(); + _duel.NegatedChainIndexList.Add(chainIndex); + } + + private void OnChainSolved(BinaryReader packet) + { + int chainIndex = packet.ReadByte(); + _ai.OnChainSolved(chainIndex); + } + + private void OnChainEnd(BinaryReader packet) + { + _ai.OnChainEnd(); + _duel.LastChainPlayer = -1; + _duel.LastChainLocation = 0; + _duel.CurrentChain.Clear(); + _duel.CurrentChainInfo.Clear(); + _duel.ChainTargets.Clear(); + _duel.LastChainTargets.Clear(); + _duel.ChainTargetOnly.Clear(); + _duel.SolvingChainIndex = 0; + _duel.NegatedChainIndexList.Clear(); + _duel.SummoningCards.Clear(); + } + + private void OnCardSorting(BinaryReader packet) + { + /*int player =*/ GetLocalPlayer(packet.ReadByte()); + IList originalCards = new List(); + IList cards = new List(); + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + int id = packet.ReadInt32(); + int controler = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + ClientCard card; + if (((int)loc & (int)CardLocation.Overlay) != 0) + card = new ClientCard(id, CardLocation.Overlay, -1); + else + card = _duel.GetCard(controler, loc, seq); + if (card == null) continue; + if (id != 0) + card.SetId(id); + originalCards.Add(card); + cards.Add(card); + } + + IList selected = _ai.OnCardSorting(cards); + byte[] result = new byte[count]; + for (int i = 0; i < count; ++i) + { + int id = 0; + for (int j = 0; j < count; ++j) + { + if (selected[j] == null) continue; + if (selected[j].Equals(originalCards[i])) + { + id = j; + break; + } + } + result[i] = (byte)id; + } + + BinaryWriter reply = CtosPacket.Begin(DuelCodecs.Response.Id); // [YGOL] TICKET-162 + DuelCodecs.Response.Write(reply, new YGOLegacy.Protocol.Contracts.Response(result)); + Connection.Send(reply); + } + + private void OnChainSorting(BinaryReader packet) + { + Connection.Send(CtosMessage.Response, -1); + } + + private void OnUpdateCard(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + int loc = packet.ReadByte(); + int seq = packet.ReadByte(); + + packet.ReadInt32(); // ??? + + ClientCard card = _duel.GetCard(player, (CardLocation)loc, seq); + + card?.Update(packet, _duel); + } + + private void OnUpdateData(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + IList cards = null; + switch (loc) + { + case CardLocation.Hand: + cards = _duel.Fields[player].Hand; + break; + case CardLocation.MonsterZone: + cards = _duel.Fields[player].MonsterZone; + break; + case CardLocation.SpellZone: + cards = _duel.Fields[player].SpellZone; + break; + case CardLocation.Grave: + cards = _duel.Fields[player].Graveyard; + break; + case CardLocation.Removed: + cards = _duel.Fields[player].Banished; + break; + case CardLocation.Deck: + cards = _duel.Fields[player].Deck; + break; + case CardLocation.Extra: + cards = _duel.Fields[player].ExtraDeck; + break; + } + if (cards != null) + { + foreach (ClientCard card in cards) + { + int len = packet.ReadInt32(); + long pos = packet.BaseStream.Position; + if (len > 8) + card.Update(packet, _duel); + packet.BaseStream.Position = pos + len - 4; + } + } + } + + private void OnBecomeTarget(BinaryReader packet) + { + _duel.LastChainTargets.Clear(); + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + int player = GetLocalPlayer(packet.ReadByte()); + int loc = packet.ReadByte(); + int seq = packet.ReadByte(); + /*int sseq = */packet.ReadByte(); + ClientCard card = _duel.GetCard(player, (CardLocation)loc, seq); + if (card == null) continue; + if (_debug) + Logger.WriteLine("(" + (CardLocation)loc + " 's " + (card.Name ?? "UnKnowCard") + " become target)"); + _duel.ChainTargets.Add(card); + _duel.LastChainTargets.Add(card); + _duel.ChainTargetOnly.Add(card); + } + } + + private void OnSelectBattleCmd(BinaryReader packet) + { + packet.ReadByte(); // player + _duel.BattlePhase = new BattlePhase(); + BattlePhase battle = _duel.BattlePhase; + + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + packet.ReadInt32(); // card id + int con = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + int desc = packet.ReadInt32(); + + ClientCard card = _duel.GetCard(con, loc, seq); + if (card != null) + { + card.ActionIndex[0] = i; // only the card's last entry survives here + battle.ActivableCards.Add(card); + battle.ActivableDescs.Add(desc); + battle.ActivableIndexes.Add(i); // [YGOL] keep each entry's own index + } + } + + count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + packet.ReadInt32(); // card id + int con = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + int diratt = packet.ReadByte(); + + ClientCard card = _duel.GetCard(con, loc, seq); + if (card != null) + { + card.ActionIndex[1] = i; + if (diratt > 0) + card.CanDirectAttack = true; + else + card.CanDirectAttack = false; + battle.AttackableCards.Add(card); + card.Attacked = false; + } + } + List monsters = _duel.Fields[0].GetMonsters(); + foreach (ClientCard monster in monsters) + { + if (!battle.AttackableCards.Contains(monster)) + monster.Attacked = true; + } + + battle.CanMainPhaseTwo = packet.ReadByte() != 0; + battle.CanEndPhase = packet.ReadByte() != 0; + + Connection.Send(CtosMessage.Response, _ai.OnSelectBattleCmd(battle).ToValue()); + } + + private void InternalOnSelectCard(BinaryReader packet, Func, int, int, int, bool, IList> func, bool tribute = false) + { + packet.ReadByte(); // player + bool cancelable = packet.ReadByte() != 0; + int min = packet.ReadByte(); + int max = packet.ReadByte(); + + IList cards = new List(); + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + int id = packet.ReadInt32(); + int player = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + packet.ReadByte(); // pos + ClientCard card; + if (((int)loc & (int)CardLocation.Overlay) != 0) + { + card = new ClientCard(id, CardLocation.Overlay, -1); + CardLocation ownerLoc = loc ^ CardLocation.Overlay; + ClientCard ownerCard = _duel.GetCard(player, ownerLoc, seq); + if (ownerCard != null) + card.OwnTargets.Add(ownerCard); + } + else + { + card = _duel.GetCard(player, loc, seq); + card.Controller = player; + } + if (card == null) continue; + if (card.Id == 0 || card.Location == CardLocation.Deck) + card.SetId(id); + cards.Add(card); + } + + if (_select_hint == 575 && cancelable) // HINTMSG_FIELD_FIRST + { + _select_hint = 0; + Connection.Send(CtosMessage.Response, -1); + return; + } + + IList selected = func(cards, min, max, _select_hint, cancelable); + _select_hint = 0; + + // [YGOL] a min-0 tribute (the continuation after YESNO 210) is answered by + // "no more tributes" (count 0); -1 there cancels the whole summon, which the + // bot then retries forever. + if (selected.Count == 0 && cancelable && !(tribute && min == 0)) + { + Connection.Send(CtosMessage.Response, -1); + return; + } + + byte[] result = new byte[selected.Count + 1]; + result[0] = (byte)selected.Count; + for (int i = 0; i < selected.Count; ++i) + { + int id = 0; + for (int j = 0; j < count; ++j) + { + if (cards[j] == null) continue; + if (cards[j].Equals(selected[i])) + { + id = j; + break; + } + } + result[i + 1] = (byte)id; + } + + BinaryWriter reply = CtosPacket.Begin(DuelCodecs.Response.Id); // [YGOL] TICKET-162 + DuelCodecs.Response.Write(reply, new YGOLegacy.Protocol.Contracts.Response(result)); + Connection.Send(reply); + } + + private void InternalOnSelectUnselectCard(BinaryReader packet, Func, int, int, int, bool, IList> func) + { + packet.ReadByte(); // player + bool finishable = packet.ReadByte() != 0; + bool cancelable = packet.ReadByte() != 0 || finishable; + int min = packet.ReadByte(); + int max = packet.ReadByte(); + + IList cards = new List(); + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + int id = packet.ReadInt32(); + int player = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + packet.ReadByte(); // pos + ClientCard card; + if (((int)loc & (int)CardLocation.Overlay) != 0) + card = new ClientCard(id, CardLocation.Overlay, -1); + else + card = _duel.GetCard(player, loc, seq); + if (card == null) continue; + if (card.Id == 0 || card.Location == CardLocation.Deck) + card.SetId(id); + cards.Add(card); + } + int count2 = packet.ReadByte(); + for (int i = 0; i < count2; ++i) + { + int id = packet.ReadInt32(); + int player = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + packet.ReadByte(); // pos + ClientCard card; + if (((int)loc & (int)CardLocation.Overlay) != 0) + card = new ClientCard(id, CardLocation.Overlay, -1); + else + card = _duel.GetCard(player, loc, seq); + if (card == null) continue; + if (card.Id == 0 || card.Location == CardLocation.Deck) + card.SetId(id); + } + if (count2 == 0) cancelable = false; + + IList selected = func(cards, (finishable ? 0 : 1), 1, _select_hint, cancelable); + + if (selected.Count == 0 && cancelable) + { + Connection.Send(CtosMessage.Response, -1); + return; + } + + byte[] result = new byte[selected.Count + 1]; + result[0] = (byte)selected.Count; + for (int i = 0; i < selected.Count; ++i) + { + int id = 0; + for (int j = 0; j < count; ++j) + { + if (cards[j] == null) continue; + if (cards[j].Equals(selected[i])) + { + id = j; + break; + } + } + result[i + 1] = (byte)id; + } + + BinaryWriter reply = CtosPacket.Begin(DuelCodecs.Response.Id); // [YGOL] TICKET-162 + DuelCodecs.Response.Write(reply, new YGOLegacy.Protocol.Contracts.Response(result)); + Connection.Send(reply); + } + + private void OnSelectCard(BinaryReader packet) + { + InternalOnSelectCard(packet, _ai.OnSelectCard); + } + + private void OnSelectUnselectCard(BinaryReader packet) + { + InternalOnSelectUnselectCard(packet, _ai.OnSelectCard); + } + + private void OnSelectChain(BinaryReader packet) + { + packet.ReadByte(); // player + int count = packet.ReadByte(); + packet.ReadByte(); // specount + int hint1 = packet.ReadInt32(); // hint1 + int hint2 = packet.ReadInt32(); // hint2 + + // TODO: use ChainInfo? + IList cards = new List(); + IList descs = new List(); + IList forces = new List(); + + for (int i = 0; i < count; ++i) + { + packet.ReadByte(); // flag + bool forced = packet.ReadByte() != 0; + + int id = packet.ReadInt32(); + int con = GetLocalPlayer(packet.ReadByte()); + int loc = packet.ReadByte(); + int seq = packet.ReadByte(); + int sseq = packet.ReadByte(); + + int desc = packet.ReadInt32(); + if (desc == 221) // trigger effect + { + desc = 0; + } + + ClientCard card = _duel.GetCard(con, loc, seq, sseq); + if (card.Id == 0) + card.SetId(id); + + cards.Add(card); + descs.Add(desc); + forces.Add(forced); + } + + if (cards.Count == 0) + { + Connection.Send(CtosMessage.Response, -1); + return; + } + + if (cards.Count == 1 && forces[0]) + { + Connection.Send(CtosMessage.Response, 0); + return; + } + + Connection.Send(CtosMessage.Response, _ai.OnSelectChain(cards, descs, forces, hint1 | hint2)); + } + + private void OnSelectCounter(BinaryReader packet) + { + packet.ReadByte(); // player + int type = packet.ReadInt16(); + int quantity = packet.ReadInt16(); + + IList cards = new List(); + IList counters = new List(); + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + packet.ReadInt32(); // card id + int player = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation) packet.ReadByte(); + int seq = packet.ReadByte(); + int num = packet.ReadInt16(); + cards.Add(_duel.GetCard(player, loc, seq)); + counters.Add(num); + } + + IList used = _ai.OnSelectCounter(type, quantity, cards, counters); + byte[] result = new byte[used.Count * 2]; + for (int i = 0; i < used.Count; ++i) + { + result[i * 2] = (byte)(used[i] & 0xff); + result[i * 2 + 1] = (byte)(used[i] >> 8); + } + BinaryWriter reply = CtosPacket.Begin(DuelCodecs.Response.Id); // [YGOL] TICKET-162 + DuelCodecs.Response.Write(reply, new YGOLegacy.Protocol.Contracts.Response(result)); + Connection.Send(reply); + } + + private void OnSelectDisfield(BinaryReader packet) + { + packet.ReadByte(); // player + int count = packet.ReadByte(); // [YGOL] was discarded ("TODO: min") + int field = ~packet.ReadInt32(); + + // [YGOL] the core reads max(1, count) {player, location, seq} triplets and answers MSG_RETRY + // for a missing or repeated zone (playerop.cpp select_place), so pick that many distinct zones. + int need = Math.Max(1, count); + byte[] resp = new byte[3 * need]; + for (int n = 0; n < need; ++n) + { + int player; + CardLocation location; + int filter; + if ((field & 0x7f0000) != 0) + { + player = 1; + location = CardLocation.MonsterZone; + filter = (field >> 16) & Zones.MonsterZones; + } + else if ((field & 0x1f000000) != 0) + { + player = 1; + location = CardLocation.SpellZone; + filter = (field >> 24) & Zones.SpellZones; + } + else if ((field & 0x7f) != 0) + { + player = 0; + location = CardLocation.MonsterZone; + filter = field & Zones.MonsterZones; + } + else if ((field & 0x1f00) != 0) + { + player = 0; + location = CardLocation.SpellZone; + filter = (field >> 8) & Zones.SpellZones; + } + else if ((field & 0x2000) != 0) + { + player = 0; + location = CardLocation.FieldZone; + filter = Zones.FieldZone; + } + else if ((field & 0xc000) != 0) + { + player = 0; + location = CardLocation.PendulumZone; + filter = (field >> 14) & Zones.PendulumZones; + } + else if ((field & 0x20000000) != 0) + { + player = 1; + location = CardLocation.FieldZone; + filter = Zones.FieldZone; + } + else + { + player = 1; + location = CardLocation.PendulumZone; + filter = (field >> 30) & Zones.PendulumZones; + } + + int selected = _ai.OnSelectPlace(_select_hint, player, location, filter); + + int o = n * 3; + resp[o] = (byte)GetLocalPlayer(player); + + if (location != CardLocation.PendulumZone && location != CardLocation.FieldZone) + { + resp[o + 1] = (byte)location; + if ((selected & filter) > 0) + filter &= selected; + + if ((filter & Zones.z2) != 0) resp[o + 2] = 2; + else if ((filter & Zones.z1) != 0) resp[o + 2] = 1; + else if ((filter & Zones.z3) != 0) resp[o + 2] = 3; + else if ((filter & Zones.z0) != 0) resp[o + 2] = 0; + else if ((filter & Zones.z4) != 0) resp[o + 2] = 4; + else if ((filter & Zones.z6) != 0) resp[o + 2] = 6; + else if ((filter & Zones.z5) != 0) resp[o + 2] = 5; + } + else + { + resp[o + 1] = (byte)CardLocation.SpellZone; + if ((selected & filter) > 0) + filter &= selected; + + if ((filter & Zones.FieldZone) != 0) resp[o + 2] = 5; + if ((filter & Zones.z0) != 0) resp[o + 2] = 6; // left pendulum zone + if ((filter & Zones.z1) != 0) resp[o + 2] = 7; // right pendulum zone + } + + field &= ~YGOL_PlaceBits(player, resp[o + 1], resp[o + 2]); + } + _select_hint = 0; + + BinaryWriter reply = CtosPacket.Begin(DuelCodecs.Response.Id); // [YGOL] TICKET-162 + DuelCodecs.Response.Write(reply, new YGOLegacy.Protocol.Contracts.Response(resp)); + Connection.Send(reply); + } + + private void OnSelectEffectYn(BinaryReader packet) + { + packet.ReadByte(); // player + + int cardId = packet.ReadInt32(); + int player = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + packet.ReadByte(); + int desc = packet.ReadInt32(); + + if (desc == 0 || desc == 221) + { + // 0: phase trigger effect + // 221: trigger effect + // for compatibility + desc = -1; + } + + ClientCard card = _duel.GetCard(player, loc, seq); + if (card == null) + { + Connection.Send(CtosMessage.Response, 0); + return; + } + + if (card.Id == 0) + card.SetId(cardId); + + int reply = _ai.OnSelectEffectYn(card, desc) ? (1) : (0); + Connection.Send(CtosMessage.Response, reply); + } + + private void OnSelectIdleCmd(BinaryReader packet) + { + packet.ReadByte(); // player + + _duel.MainPhase = new MainPhase(); + MainPhase main = _duel.MainPhase; + int count; + for (int k = 0; k < 5; k++) + { + count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + packet.ReadInt32(); // card id + int con = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + ClientCard card = _duel.GetCard(con, loc, seq); + if (card == null) continue; + card.ActionIndex[k] = i; + switch (k) + { + case 0: + main.SummonableCards.Add(card); + break; + case 1: + main.SpecialSummonableCards.Add(card); + break; + case 2: + main.ReposableCards.Add(card); + break; + case 3: + main.MonsterSetableCards.Add(card); + break; + case 4: + main.SpellSetableCards.Add(card); + break; + } + } + } + count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + packet.ReadInt32(); // card id + int con = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + int desc = packet.ReadInt32(); + + ClientCard card = _duel.GetCard(con, loc, seq); + if (card == null) continue; + card.ActionIndex[5] = i; + if (card.ActionActivateIndex.ContainsKey(desc)) + card.ActionActivateIndex.Remove(desc); + card.ActionActivateIndex.Add(desc, i); + main.ActivableCards.Add(card); + main.ActivableDescs.Add(desc); + } + + main.CanBattlePhase = packet.ReadByte() != 0; + main.CanEndPhase = packet.ReadByte() != 0; + packet.ReadByte(); // CanShuffle + + Connection.Send(CtosMessage.Response, _ai.OnSelectIdleCmd(main).ToValue()); + } + + private void OnSelectOption(BinaryReader packet) + { + IList options = new List(); + packet.ReadByte(); // player + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + options.Add(packet.ReadInt32()); + Connection.Send(CtosMessage.Response, _ai.OnSelectOption(options)); + } + + private void OnSelectPlace(BinaryReader packet) + { + packet.ReadByte(); // player + int count = packet.ReadByte(); // [YGOL] was discarded + int field = ~packet.ReadInt32(); + + // [YGOL] the core reads max(1, count) {player, location, seq} triplets and answers MSG_RETRY + // for a missing or repeated zone (playerop.cpp select_place), so pick that many distinct zones. + int need = Math.Max(1, count); + byte[] resp = new byte[3 * need]; + for (int n = 0; n < need; ++n) + { + int player; + CardLocation location; + int filter; + + if ((field & 0x7f) != 0) + { + player = 0; + location = CardLocation.MonsterZone; + filter = field & Zones.MonsterZones; + } + else if ((field & 0x1f00) != 0) + { + player = 0; + location = CardLocation.SpellZone; + filter = (field >> 8) & Zones.SpellZones; + } + else if ((field & 0x2000) != 0) + { + player = 0; + location = CardLocation.FieldZone; + filter = Zones.FieldZone; + } + else if ((field & 0xc000) != 0) + { + player = 0; + location = CardLocation.PendulumZone; + filter = (field >> 14) & Zones.PendulumZones; + } + else if ((field & 0x7f0000) != 0) + { + player = 1; + location = CardLocation.MonsterZone; + filter = (field >> 16) & Zones.MonsterZones; + } + else if ((field & 0x1f000000) != 0) + { + player = 1; + location = CardLocation.SpellZone; + filter = (field >> 24) & Zones.SpellZones; + } + else if ((field & 0x20000000) != 0) + { + player = 1; + location = CardLocation.FieldZone; + filter = Zones.FieldZone; + } + else + { + player = 1; + location = CardLocation.PendulumZone; + filter = (field >> 30) & Zones.PendulumZones; + } + + int selected = _ai.OnSelectPlace(_select_hint, player, location, filter); + + int o = n * 3; + resp[o] = (byte)GetLocalPlayer(player); + + if (location != CardLocation.PendulumZone && location != CardLocation.FieldZone) + { + resp[o + 1] = (byte)location; + if ((selected & filter) > 0) + filter &= selected; + + if ((filter & Zones.z2) != 0) resp[o + 2] = 2; + else if ((filter & Zones.z1) != 0) resp[o + 2] = 1; + else if ((filter & Zones.z3) != 0) resp[o + 2] = 3; + else if ((filter & Zones.z0) != 0) resp[o + 2] = 0; + else if ((filter & Zones.z4) != 0) resp[o + 2] = 4; + else if ((filter & Zones.z6) != 0) resp[o + 2] = 6; + else if ((filter & Zones.z5) != 0) resp[o + 2] = 5; + } + else + { + resp[o + 1] = (byte)CardLocation.SpellZone; + if ((selected & filter) > 0) + filter &= selected; + + if ((filter & Zones.FieldZone) != 0) resp[o + 2] = 5; + if ((filter & Zones.z0) != 0) resp[o + 2] = 6; // left pendulum zone + if ((filter & Zones.z1) != 0) resp[o + 2] = 7; // right pendulum zone + } + + field &= ~YGOL_PlaceBits(player, resp[o + 1], resp[o + 2]); + } + _select_hint = 0; + + BinaryWriter reply = CtosPacket.Begin(DuelCodecs.Response.Id); // [YGOL] TICKET-162 + DuelCodecs.Response.Write(reply, new YGOLegacy.Protocol.Contracts.Response(resp)); + Connection.Send(reply); + } + + /// + /// [YGOL] The bits one answered zone takes in the select_place flag (own 0-15, opponent +16; spell + /// row +8). An Extra Monster Zone is shared, so the core also marks the mirrored one as taken. + /// + private static int YGOL_PlaceBits(int player, byte location, byte seq) + { + int self = player == 0 ? 0 : 16; + int other = player == 0 ? 16 : 0; + bool monster = location == (byte)CardLocation.MonsterZone; + int bits = 1 << (seq + self + (monster ? 0 : 8)); + if (monster && seq == 5) bits |= 1 << (other + 6); + if (monster && seq == 6) bits |= 1 << (other + 5); + return bits; + } + + private void OnSelectPosition(BinaryReader packet) + { + packet.ReadByte(); // player + int cardId = packet.ReadInt32(); + int pos = packet.ReadByte(); + if (pos == 0x1 || pos == 0x2 || pos == 0x4 || pos == 0x8) + { + Connection.Send(CtosMessage.Response, pos); + return; + } + IList positions = new List(); + if ((pos & (int)CardPosition.FaceUpAttack) != 0) + positions.Add(CardPosition.FaceUpAttack); + if ((pos & (int)CardPosition.FaceDownAttack) != 0) + positions.Add(CardPosition.FaceDownAttack); + if ((pos & (int)CardPosition.FaceUpDefence) != 0) + positions.Add(CardPosition.FaceUpDefence); + if ((pos & (int)CardPosition.FaceDownDefence) != 0) + positions.Add(CardPosition.FaceDownDefence); + Connection.Send(CtosMessage.Response, (int)_ai.OnSelectPosition(cardId, positions)); + } + + private void OnSelectSum(BinaryReader packet) + { + bool mode = packet.ReadByte() == 0; + packet.ReadByte(); // player + int sumval = packet.ReadInt32(); + int min = packet.ReadByte(); + int max = packet.ReadByte(); + + if (max <= 0) + max = 99; + + IList mandatoryCards = new List(); + IList cards = new List(); + + for (int j = 0; j < 2; ++j) + { + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + { + int cardId = packet.ReadInt32(); + int player = GetLocalPlayer(packet.ReadByte()); + CardLocation loc = (CardLocation)packet.ReadByte(); + int seq = packet.ReadByte(); + ClientCard card = _duel.GetCard(player, loc, seq); + if (cardId != 0 && card.Id != cardId) + card.SetId(cardId); + card.SelectSeq = i; + int OpParam = packet.ReadInt32(); + int OpParam1 = OpParam & 0xffff; + int OpParam2 = OpParam >> 16; + if ((OpParam & 0x80000000) > 0) + { + OpParam1 = OpParam & 0x7fffffff; + OpParam2 = 0; + } + if (OpParam2 > 0 && OpParam1 > OpParam2) + { + card.OpParam1 = OpParam2; + card.OpParam2 = OpParam1; + } + else + { + card.OpParam1 = OpParam1; + card.OpParam2 = OpParam2; + } + if (j == 0) + mandatoryCards.Add(card); + else + cards.Add(card); + } + } + + for (int k = 0; k < mandatoryCards.Count; ++k) + { + sumval -= mandatoryCards[k].OpParam1; + } + + IList selected = _ai.OnSelectSum(cards, sumval, min, max, _select_hint, mode); + _select_hint = 0; + + byte[] result = new byte[mandatoryCards.Count + selected.Count + 1]; + int index = 0; + + result[index++] = (byte)(mandatoryCards.Count + selected.Count); + while (index <= mandatoryCards.Count) + { + result[index++] = 0; + } + int l = 0; + while (l < selected.Count) + { + result[index++] = (byte)selected[l].SelectSeq; + ++l; + } + + BinaryWriter reply = CtosPacket.Begin(DuelCodecs.Response.Id); // [YGOL] TICKET-162 + DuelCodecs.Response.Write(reply, new YGOLegacy.Protocol.Contracts.Response(result)); + Connection.Send(reply); + } + + private void OnSelectTribute(BinaryReader packet) + { + InternalOnSelectCard(packet, _ai.OnSelectTribute, true); // [YGOL] tribute: min 0 + empty = count 0 + } + + private void OnSelectYesNo(BinaryReader packet) + { + packet.ReadByte(); // player + int desc = packet.ReadInt32(); + int reply; + if (desc == 30) + reply = _ai.OnSelectBattleReplay() ? 1 : 0; + else + reply = _ai.OnSelectYesNo(desc) ? 1 : 0; + Connection.Send(CtosMessage.Response, reply); + } + + private void OnAnnounceAttrib(BinaryReader packet) + { + IList attributes = new List(); + packet.ReadByte(); // player + int count = packet.ReadByte(); + int available = packet.ReadInt32(); + int filter = 0x1; + for (int i = 0; i < 7; ++i) + { + if ((available & filter) != 0) + attributes.Add((CardAttribute) filter); + filter <<= 1; + } + attributes = _ai.OnAnnounceAttrib(count, attributes); + int reply = 0; + for (int i = 0; i < count; ++i) + reply += (int)attributes[i]; + Connection.Send(CtosMessage.Response, reply); + } + + private void OnAnnounceCard(BinaryReader packet) + { + IList opcodes = new List(); + packet.ReadByte(); // player + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + opcodes.Add(packet.ReadInt32()); + + IList avail = new List(); + IList all = NamedCardsManager.GetAllCards(); + foreach (NamedCard card in all) + { + if (card.HasType(CardType.Token) || (card.Alias > 0 && card.Id - card.Alias < 10)) continue; + Stack stack = new Stack(); + for (int i = 0; i < opcodes.Count; i++) + { + switch (opcodes[i]) + { + case Opcodes.OPCODE_ADD: + if (stack.Count >= 2) + { + int rhs = stack.Pop(); + int lhs = stack.Pop(); + stack.Push(lhs + rhs); + } + break; + case Opcodes.OPCODE_SUB: + if (stack.Count >= 2) + { + int rhs = stack.Pop(); + int lhs = stack.Pop(); + stack.Push(lhs - rhs); + } + break; + case Opcodes.OPCODE_MUL: + if (stack.Count >= 2) + { + int rhs = stack.Pop(); + int lhs = stack.Pop(); + stack.Push(lhs * rhs); + } + break; + case Opcodes.OPCODE_DIV: + if (stack.Count >= 2) + { + int rhs = stack.Pop(); + int lhs = stack.Pop(); + stack.Push(lhs / rhs); + } + break; + case Opcodes.OPCODE_AND: + if (stack.Count >= 2) + { + int rhs = stack.Pop(); + int lhs = stack.Pop(); + bool b0 = rhs != 0; + bool b1 = lhs != 0; + if (b0 && b1) + stack.Push(1); + else + stack.Push(0); + } + break; + case Opcodes.OPCODE_OR: + if (stack.Count >= 2) + { + int rhs = stack.Pop(); + int lhs = stack.Pop(); + bool b0 = rhs != 0; + bool b1 = lhs != 0; + if (b0 || b1) + stack.Push(1); + else + stack.Push(0); + } + break; + case Opcodes.OPCODE_NEG: + if (stack.Count >= 1) + { + int rhs = stack.Pop(); + stack.Push(-rhs); + } + break; + case Opcodes.OPCODE_NOT: + if (stack.Count >= 1) + { + int rhs = stack.Pop(); + bool b0 = rhs != 0; + if (b0) + stack.Push(0); + else + stack.Push(1); + } + break; + case Opcodes.OPCODE_ISCODE: + if (stack.Count >= 1) + { + int code = stack.Pop(); + bool b0 = code == card.Id; + if (b0) + stack.Push(1); + else + stack.Push(0); + } + break; + case Opcodes.OPCODE_ISSETCARD: + if (stack.Count >= 1) + { + if (card.HasSetcode(stack.Pop())) + stack.Push(1); + else + stack.Push(0); + } + break; + case Opcodes.OPCODE_ISTYPE: + if (stack.Count >= 1) + { + if ((stack.Pop() & card.Type) > 0) + stack.Push(1); + else + stack.Push(0); + } + break; + case Opcodes.OPCODE_ISRACE: + if (stack.Count >= 1) + { + if ((stack.Pop() & card.Race) > 0) + stack.Push(1); + else + stack.Push(0); + } + break; + case Opcodes.OPCODE_ISATTRIBUTE: + if (stack.Count >= 1) + { + if ((stack.Pop() & card.Attribute) > 0) + stack.Push(1); + else + stack.Push(0); + } + break; + default: + stack.Push(opcodes[i]); + break; + } + } + if (stack.Count == 1 && stack.Pop() != 0) + avail.Add(card.Id); + } + if (avail.Count == 0) + throw new Exception("No avail card found for announce!"); + Connection.Send(CtosMessage.Response, _ai.OnAnnounceCard(avail)); + } + + private void OnAnnounceNumber(BinaryReader packet) + { + IList numbers = new List(); + packet.ReadByte(); // player + int count = packet.ReadByte(); + for (int i = 0; i < count; ++i) + numbers.Add(packet.ReadInt32()); + Connection.Send(CtosMessage.Response, _ai.OnAnnounceNumber(numbers)); + } + + private void OnAnnounceRace(BinaryReader packet) + { + IList races = new List(); + packet.ReadByte(); // player + int count = packet.ReadByte(); + int available = packet.ReadInt32(); + int filter = 0x1; + for (int i = 0; i < 26; ++i) + { + if ((available & filter) != 0) + races.Add((CardRace)filter); + filter <<= 1; + } + races = _ai.OnAnnounceRace(count, races); + int reply = 0; + for (int i = 0; i < count; ++i) + reply += (int)races[i]; + Connection.Send(CtosMessage.Response, reply); + } + + private void OnRockPaperScissors(BinaryReader packet) + { + packet.ReadByte(); // player + int result; + if (_hand > 0) + result = _hand; + else + result = _ai.OnRockPaperScissors(); + Connection.Send(CtosMessage.Response, result); + } + + private void OnEquip(BinaryReader packet) + { + int equipCardControler = GetLocalPlayer(packet.ReadByte()); + int equipCardLocation = packet.ReadByte(); + int equipCardSequence = packet.ReadSByte(); + packet.ReadByte(); + int targetCardControler = GetLocalPlayer(packet.ReadByte()); + int targetCardLocation = packet.ReadByte(); + int targetCardSequence = packet.ReadSByte(); + packet.ReadByte(); + ClientCard equipCard = _duel.GetCard(equipCardControler, (CardLocation)equipCardLocation, equipCardSequence); + ClientCard targetCard = _duel.GetCard(targetCardControler, (CardLocation)targetCardLocation, targetCardSequence); + if (equipCard == null || targetCard == null) return; + equipCard.EquipTarget?.EquipCards.Remove(equipCard); + equipCard.EquipTarget = targetCard; + targetCard.EquipCards.Add(equipCard); + } + + private void OnUnEquip(BinaryReader packet) + { + int equipCardControler = GetLocalPlayer(packet.ReadByte()); + int equipCardLocation = packet.ReadByte(); + int equipCardSequence = packet.ReadSByte(); + packet.ReadByte(); + ClientCard equipCard = _duel.GetCard(equipCardControler, (CardLocation)equipCardLocation, equipCardSequence); + if (equipCard == null) return; + if (equipCard.EquipTarget != null) + { + equipCard.EquipTarget.EquipCards.Remove(equipCard); + equipCard.EquipTarget = null; + } + } + + private void OnCardTarget(BinaryReader packet) + { + int ownerCardControler = GetLocalPlayer(packet.ReadByte()); + int ownerCardLocation = packet.ReadByte(); + int ownerCardSequence = packet.ReadSByte(); + packet.ReadByte(); + int targetCardControler = GetLocalPlayer(packet.ReadByte()); + int targetCardLocation = packet.ReadByte(); + int targetCardSequence = packet.ReadSByte(); + packet.ReadByte(); + ClientCard ownerCard = _duel.GetCard(ownerCardControler, (CardLocation)ownerCardLocation, ownerCardSequence); + ClientCard targetCard = _duel.GetCard(targetCardControler, (CardLocation)targetCardLocation, targetCardSequence); + if (ownerCard == null || targetCard == null) return; + ownerCard.TargetCards.Add(targetCard); + targetCard.OwnTargets.Add(ownerCard); + } + + private void OnCancelTarget(BinaryReader packet) + { + int ownerCardControler = GetLocalPlayer(packet.ReadByte()); + int ownerCardLocation = packet.ReadByte(); + int ownerCardSequence = packet.ReadSByte(); + packet.ReadByte(); + int targetCardControler = GetLocalPlayer(packet.ReadByte()); + int targetCardLocation = packet.ReadByte(); + int targetCardSequence = packet.ReadSByte(); + packet.ReadByte(); + ClientCard ownerCard = _duel.GetCard(ownerCardControler, (CardLocation)ownerCardLocation, ownerCardSequence); + ClientCard targetCard = _duel.GetCard(targetCardControler, (CardLocation)targetCardLocation, targetCardSequence); + if (ownerCard == null || targetCard == null) return; + ownerCard.TargetCards.Remove(targetCard); + targetCard.OwnTargets.Remove(ownerCard); + } + + private void OnSummoning(BinaryReader packet) + { + _duel.LastSummonedCards.Clear(); + int code = packet.ReadInt32(); + int currentControler = GetLocalPlayer(packet.ReadByte()); + int currentLocation = packet.ReadByte(); + int currentSequence = packet.ReadSByte(); + int currentPosition = packet.ReadSByte(); + ClientCard card = _duel.GetCard(currentControler, (CardLocation)currentLocation, currentSequence); + _duel.SummoningCards.Add(card); + _duel.LastSummonPlayer = currentControler; + } + + private void OnSummoned(BinaryReader packet) + { + foreach (ClientCard card in _duel.SummoningCards) + { + _duel.LastSummonedCards.Add(card); + } + _duel.SummoningCards.Clear(); + } + + private void OnSpSummoning(BinaryReader packet) + { + _duel.LastSummonedCards.Clear(); + _ai.CleanSelectMaterials(); + int code = packet.ReadInt32(); + int currentControler = GetLocalPlayer(packet.ReadByte()); + int currentLocation = packet.ReadByte(); + int currentSequence = packet.ReadSByte(); + int currentPosition = packet.ReadSByte(); + ClientCard card = _duel.GetCard(currentControler, (CardLocation)currentLocation, currentSequence); + _duel.SummoningCards.Add(card); + _duel.LastSummonPlayer = currentControler; + } + + private void OnSpSummoned(BinaryReader packet) + { + foreach (ClientCard card in _duel.SummoningCards) + { + card.IsSpecialSummoned = true; + _duel.LastSummonedCards.Add(card); + } + _ai.OnSpSummoned(); + _duel.SummoningCards.Clear(); + } + + private void OnConfirmCards(BinaryReader packet) + { + /*int playerid = */packet.ReadByte(); + /*int skip_panel = */packet.ReadByte(); + int count = packet.ReadByte(); + for (int i = 0; i < count; ++ i) + { + int cardId = packet.ReadInt32(); + int player = GetLocalPlayer(packet.ReadByte()); + int loc = packet.ReadByte(); + int seq = packet.ReadByte(); + ClientCard card = _duel.GetCard(player, (CardLocation)loc, seq); + if (cardId > 0) card.SetId(cardId); + if (_debug) + Logger.WriteLine("(Confirm " + player.ToString() + "'s " + (CardLocation)loc + " card: " + (card.Name ?? "UnKnowCard") + ")"); + } + } + + /// + /// Handles PlayerHint message. Protocol: player(buffer8), hintType(buffer8), description(buffer32). + /// hintType values: PlayerHintType (e.g. PHINT_DESC_ADD=6, PHINT_DESC_REMOVE=7). + /// + private void OnPlayerHint(BinaryReader packet) + { + int player = GetLocalPlayer(packet.ReadByte()); + int hintType = packet.ReadByte(); + int description = packet.ReadInt32(); + Logger.DebugWriteLine("PlayerHint received: player=" + player + ", hintType=" + hintType + " (" + (PlayerHintType)hintType + "), description=" + description); + _ai.OnPlayerHint(player, hintType, description); + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/Game/GameClient.cs b/src/YGOLegacy.Bots/WindBot/Game/GameClient.cs new file mode 100644 index 0000000..7adfe15 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/GameClient.cs @@ -0,0 +1,212 @@ +using System; +using System.IO; +using System.Linq; +using System.Net; +using YGOSharp.Network; +using YGOSharp.Network.Enums; +using YGOSharp.Network.Utils; +using YGOLegacy.Protocol.Codecs; // [YGOL] TICKET-161 + +namespace WindBot.Game +{ + public class GameClient + { + public YGOClient Connection { get; private set; } + public string Username; + public string Deck; + public string DeckFile; + // [YGOL] TICKET-349 + public int Hand; + public bool Debug; + // [YGOL] TICKET-349 + public string Character; // [YGOL] TICKET-171 + public string Group; // [YGOL] TICKET-171 + // [YGOL] TICKET-285: chosen seat, deferred deck, per-seat difficulty and the host's in-process orders. + public int YGOL_Seat = -1; + public byte[] YGOL_SeatToken; + public bool YGOL_DeferDeck; + public string YGOL_Difficulty; + // [YGOL] S5: the Room host's per-seat brain knobs, on top of the deck's brain. + public System.Collections.Generic.IReadOnlyDictionary YGOL_Knobs; + // [YGOL] TICKET-286: a restart's returning CPU claims with the restart id and holds READY for the host's START. + public byte[] YGOL_RestartId; + public volatile bool YGOL_HoldReady; + public volatile int YGOL_Position = -1; + public volatile bool YGOL_HasDeck; + private readonly System.Collections.Concurrent.ConcurrentQueue YGOL_orders = new System.Collections.Concurrent.ConcurrentQueue(); + private string _serverHost; + private int _serverPort; + private short _proVersion; + + private string _roomInfo; + + private GameBehavior _behavior; + + public GameClient(WindBotInfo Info) + { + Username = Info.Name; + Deck = Info.Deck; + DeckFile = Info.DeckFile; + // [YGOL] TICKET-349 + Hand = Info.Hand; + Debug = Info.Debug; + // [YGOL] TICKET-349 + Character = Info.Character; // [YGOL] TICKET-171 + Group = Info.Group; // [YGOL] TICKET-171 + YGOL_Seat = Info.Seat; // [YGOL] TICKET-285 + YGOL_SeatToken = YGOLegacy.Protocol.Contracts.SeatIds.FromHex(Info.SeatToken); + YGOL_DeferDeck = Info.DeferDeck; + YGOL_Difficulty = string.IsNullOrEmpty(Info.Difficulty) ? null : Info.Difficulty; + YGOL_RestartId = YGOLegacy.Protocol.Contracts.SeatIds.FromHex(Info.RestartId); // [YGOL] TICKET-286 + YGOL_HoldReady = Info.HoldReady; + _serverHost = Info.Host; + _serverPort = Info.Port; + _roomInfo = Info.HostInfo; + _proVersion = (short)Info.Version; + } + + public void Start() + { + Connection = new YGOClient(); + _behavior = new GameBehavior(this); + + Connection.Connected += OnConnected; + Connection.PacketReceived += OnPacketReceived; + + IPAddress target_address; + try + { + target_address = IPAddress.Parse(_serverHost); + } + catch (System.Exception) + { + IPHostEntry _hostEntry = Dns.GetHostEntry(_serverHost); + target_address = _hostEntry.AddressList.FirstOrDefault(findIPv4 => findIPv4.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); + } + + Connection.Connect(target_address, _serverPort); + } + + private void OnConnected() + { + // [YGOL] TICKET-161: the shared lobby codecs write the payloads; CtosPacket writes the id byte. + BinaryWriter packet = CtosPacket.Begin(LobbyCodecs.ExternalAddress.Id); + LobbyCodecs.ExternalAddress.Write(packet, new YGOLegacy.Protocol.Contracts.ExternalAddress(_serverHost)); + Connection.Send(packet); + + packet = CtosPacket.Begin(LobbyCodecs.PlayerInfo.Id); + LobbyCodecs.PlayerInfo.Write(packet, new YGOLegacy.Protocol.Contracts.PlayerInfo(Username)); + Connection.Send(packet); + + // [YGOL] TICKET-285: claim the host's chosen seat before JoinGame; only sent to a server that has chosen seats. + if (YGOL_Seat >= 0 && YGOL_SeatToken != null) + { + packet = CtosPacket.Begin(LobbyCodecs.SeatRequest.Id); + LobbyCodecs.SeatRequest.Write(packet, new YGOLegacy.Protocol.Contracts.SeatRequest( + YGOLegacy.Protocol.Contracts.Capability.ProtocolVersion, YGOL_RestartId, (byte)YGOL_Seat, YGOL_SeatToken)); // [YGOL] TICKET-286: the restart id rides along + Connection.Send(packet); + } + + packet = CtosPacket.Begin(LobbyCodecs.JoinGame.Id); + LobbyCodecs.JoinGame.Write(packet, new YGOLegacy.Protocol.Contracts.JoinGame((ushort)_proVersion, _roomInfo)); + Connection.Send(packet); + } + + /// + /// [YGOL] In-process duel host (TICKET-045): build exactly what Start() + /// builds, but on a loopback transport — no DNS lookup, no socket, no + /// Connect. OnConnected still runs (on the first Tick), so + /// ExternalAddress/PlayerInfo/JoinGame go out through and the host answers them the way ygoserver would. + /// Everything downstream is untouched: GameBehavior, the DuelStateBus + /// tap in OnPacketReceived, YGOL_DuelResult and YGOL_Replay. + /// + public void YGOL_StartLoopback(Action sendHook) + { + Connection = new YGOClient(); + _behavior = new GameBehavior(this); + + Connection.Connected += OnConnected; + Connection.PacketReceived += OnPacketReceived; + Connection.YGOL_SendHook = sendHook; + Connection.YGOL_MarkConnected(); + } + + /// [YGOL] Push one STOC packet into this client's receive queue (loopback). + public void YGOL_Receive(byte[] packet) + { + Connection.YGOL_Inject(packet); + } + + public void Tick() + { + // [YGOL] TICKET-285: the host's orders run here, on the bot thread, between packets. + while (YGOL_orders.TryDequeue(out Action order)) + order(); + Connection.Update(); + } + + // [YGOL] TICKET-285: change this bot's deck (and the brain it picks) without a respawn. Dropped once the duel started. + public void YGOL_AssignDeck(string deckFile, string executor, string character, string group) + { + YGOL_orders.Enqueue(() => _behavior.YGOL_ApplyDeck(deckFile, executor, character, group)); + } + + // [YGOL] TICKET-285: a per-seat difficulty; the executor is rebuilt, the brain file is never touched. + public void YGOL_SetDifficulty(string difficulty) + { + YGOL_orders.Enqueue(() => _behavior.YGOL_ApplyDifficulty(difficulty)); + } + + // [YGOL] S5: per-seat brain and debug log from the Room's CPU settings; the executor is rebuilt. + public void YGOL_SetBrain(string executor, System.Collections.Generic.IReadOnlyDictionary knobs, bool debug) + { + YGOL_orders.Enqueue(() => _behavior.YGOL_ApplyBrain(executor, knobs, debug)); + } + + // [YGOL] TICKET-286: the host's START readies a CPU that came back from a restart unready. + public void YGOL_Ready() + { + YGOL_orders.Enqueue(() => _behavior.YGOL_ReleaseReady()); + } + + // [YGOL] TICKET-285: leave the room; the bot thread ends with the connection. + public void YGOL_Leave() + { + YGOL_orders.Enqueue(() => + { + if (Connection.IsConnected) + Connection.Send(CtosMessage.LeaveGame); + Connection.Close(); + }); + } + + // [YGOL] TICKET-349 + + public void Surrender() + { + Connection.Send(CtosMessage.Surrender); + } + + private void OnPacketReceived(BinaryReader reader) + { + // [YGOL] Duel state bus (TICKET-042): publish a COPY of the raw + // packet before it is parsed, so YGOLegacy.Bot.DuelStateBus can + // mirror this seat's view for the other bot. The reader is not + // touched (ToArray() ignores the stream position), and when no + // brain asked for insight `Active` is false, so this is one static + // bool read and no allocation. + if (YGOLegacy.Bot.DuelStateBus.Active) + { + try + { + MemoryStream buffer = reader.BaseStream as MemoryStream; + if (buffer != null) + YGOLegacy.Bot.DuelStateBus.OnBotPacket(this, buffer.ToArray()); + } + catch (Exception) { } + } + _behavior.OnPacket(reader); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/MainPhase.cs b/src/YGOLegacy.Bots/WindBot/Game/MainPhase.cs new file mode 100644 index 0000000..394ffa7 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/MainPhase.cs @@ -0,0 +1,28 @@ +using System.Collections.Generic; + +namespace WindBot.Game +{ + public class MainPhase + { + public IList SummonableCards { get; private set; } + public IList SpecialSummonableCards { get; private set; } + public IList ReposableCards { get; private set; } + public IList MonsterSetableCards { get; private set; } + public IList SpellSetableCards { get; private set; } + public IList ActivableCards { get; private set; } + public IList ActivableDescs { get; private set; } + public bool CanBattlePhase { get; set; } + public bool CanEndPhase { get; set; } + + public MainPhase() + { + SummonableCards = new List(); + SpecialSummonableCards = new List(); + ReposableCards = new List(); + MonsterSetableCards = new List(); + SpellSetableCards = new List(); + ActivableCards = new List(); + ActivableDescs = new List(); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/MainPhaseAction.cs b/src/YGOLegacy.Bots/WindBot/Game/MainPhaseAction.cs new file mode 100644 index 0000000..00746cd --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/MainPhaseAction.cs @@ -0,0 +1,43 @@ +namespace WindBot.Game +{ + public class MainPhaseAction + { + public enum MainAction + { + Summon = 0, + SpSummon = 1, + Repos = 2, + SetMonster = 3, + SetSpell = 4, + Activate = 5, + ToBattlePhase = 6, + ToEndPhase = 7 + } + + public MainAction Action { get; private set; } + public int Index { get; private set; } + + public MainPhaseAction(MainAction action) + { + Action = action; + Index = 0; + } + + public MainPhaseAction(MainAction action, int index) + { + Action = action; + Index = index; + } + + public MainPhaseAction(MainAction action, int[] indexes) + { + Action = action; + Index = indexes[(int)action]; + } + + public int ToValue() + { + return (Index << 16) + (int)Action; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Game/Room.cs b/src/YGOLegacy.Bots/WindBot/Game/Room.cs new file mode 100644 index 0000000..bf67a3f --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Game/Room.cs @@ -0,0 +1,17 @@ +namespace WindBot.Game +{ + public class Room + { + public bool IsHost { get; set; } + public string[] Names { get; set; } + public bool[] IsReady { get; set; } + public int Position { get; set; } + + public Room() + { + Names = new string[8]; + IsReady = new bool[8]; + Position = -1; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Logger.cs b/src/YGOLegacy.Bots/WindBot/Logger.cs new file mode 100644 index 0000000..84af798 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Logger.cs @@ -0,0 +1,27 @@ +using System; + +namespace WindBot +{ + public static class Logger + { + public static void WriteLine(string message) + { + Console.WriteLine("[" + DateTime.Now.ToString("yy-MM-dd HH:mm:ss") + "] " + message); + UnityEngine.Debug.Log("[WindBot] " + message); // [YGOL] Console.WriteLine is invisible in Unity + } + public static void DebugWriteLine(string message) + { +#if DEBUG + Console.WriteLine("[" + DateTime.Now.ToString("yy-MM-dd HH:mm:ss") + "] " + message); +#endif + } + public static void WriteErrorLine(string message) + { + Console.BackgroundColor = ConsoleColor.Red; + Console.ForegroundColor = ConsoleColor.White; + Console.Error.WriteLine("[" + DateTime.Now.ToString("yy-MM-dd HH:mm:ss") + "] " + message); + Console.ResetColor(); + UnityEngine.Debug.LogWarning("[WindBot] " + message); // [YGOL] + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/WindBot/Program.cs b/src/YGOLegacy.Bots/WindBot/Program.cs new file mode 100644 index 0000000..3a22b0c --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/Program.cs @@ -0,0 +1,291 @@ +using System; +using System.IO; +using System.Threading; +using System.Net; +using WindBot.Game; +using WindBot.Game.AI; +using YGOSharp.OCGWrapper; +using System.Collections.Specialized; +using MDPro3.IO; +using YGOLegacy.Core; + +namespace WindBot +{ + public class Program + { + internal static Random Rand; + + // [YGOL] TICKET-285: the bot thread's own spawner callback; Run hands it the started client. + [ThreadStatic] private static Action YGOL_onClient; + + // [YGOL] TICKET-285: Main that hands the started client back, on the bot thread, to whoever spawned it. + internal static void YGOL_Main(string[] args, Action onClient) + { + YGOL_onClient = onClient; + try { Main(args); } + finally { YGOL_onClient = null; } + } + + internal static void Main(string[] args) + { + Logger.WriteLine("WindBot starting..."); + + Config.Load(args); + + string databasePath = Config.GetString("DbPath", "cards.cdb"); + + InitDatas(databasePath); + + bool serverMode = Config.GetBool("ServerMode", false); + + if (serverMode) + { + // Run in server mode, provide a http interface to create bot. + int serverPort = Config.GetInt("ServerPort", 2399); + RunAsServer(serverPort); + } + else + { + // Join the host specified on the command line. + if (args.Length == 0) + { + Logger.WriteErrorLine("=== WARN ==="); + Logger.WriteLine("No input found, tring to connect to localhost YGOPro host."); + Logger.WriteLine("If it fail, the program will quit sliently."); + } + RunFromArgs(); + } + } + + // [YGOL] the card database and the deck list are process-wide statics shared by every bot thread; a second bot's + // InitDatas replaced them while the first bot was loading its deck, so that deck lost every card not yet re-read. + private static readonly object YGOL_initLock = new object(); + private static bool YGOL_dataReady; + + public static void InitDatas(string databasePath) + { + lock (YGOL_initLock) + { + if (YGOL_dataReady) + return; + YGOL_InitDatas(databasePath); + YGOL_dataReady = true; + } + } + + private static void YGOL_InitDatas(string databasePath) + { + Rand = new Random(); + DecksManager.Init(); + string absolutePath = Path.GetFullPath(databasePath); + //if (!File.Exists(absolutePath)) + // // In case windbot is placed in a folder under ygopro folder + // absolutePath = Path.GetFullPath("../" + databasePath); + //if (!File.Exists(absolutePath)) + // // In case windbot is placed in a folder under ygopro2 folder + // absolutePath = Path.GetFullPath("../cdb/" + databasePath); + absolutePath = Path.GetFullPath("Data/locales/" + MDPro3.Utility.Language.GetConfig() + "/" + databasePath); + if (!File.Exists(absolutePath)) + { + Logger.WriteErrorLine("Can't find cards database file."); + Logger.WriteErrorLine("Please place cards.cdb next to WindBot.exe or Bot.exe ."); + Logger.WriteLine("Press any key to quit..."); + Console.ReadKey(); + System.Environment.Exit(1); + } + var paths = new System.Collections.Generic.List { absolutePath }; + var zipCdbs = ResourceManager.GetAllCdbInZipPaths(); + if (zipCdbs != null) + paths.AddRange(zipCdbs); + foreach (var cdb in Directory.GetFiles(GamePaths.PATH_EXPANSIONS, "*.cdb")) + paths.Add(cdb); + NamedCardsManager.InitForMulti(paths); + } + + private static void RunFromArgs() + { + WindBotInfo Info = new WindBotInfo(); + Info.Name = Config.GetString("Name", Info.Name); + Info.Deck = Config.GetString("Deck", Info.Deck); + Info.DeckFile = Config.GetString("DeckFile", Info.DeckFile); + // [YGOL] TICKET-349 + 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); + // [YGOL] TICKET-349 + Info.Character = Config.GetString("Character", Info.Character); // [YGOL] TICKET-171 + Info.Group = Config.GetString("Group", Info.Group); // [YGOL] TICKET-171 + Info.Seat = Config.GetInt("Seat", Info.Seat); // [YGOL] TICKET-285 + Info.SeatToken = Config.GetString("SeatToken", Info.SeatToken); + Info.DeferDeck = Config.GetBool("DeferDeck", Info.DeferDeck); + Info.Difficulty = Config.GetString("Difficulty", Info.Difficulty); + Info.RestartId = Config.GetString("RestartId", Info.RestartId); // [YGOL] TICKET-286 + Info.HoldReady = Config.GetBool("HoldReady", Info.HoldReady); + Run(Info); + } + + private static void RunAsServer(int ServerPort) + { + using (HttpListener MainServer = new HttpListener()) + { + MainServer.AuthenticationSchemes = AuthenticationSchemes.Anonymous; + MainServer.Prefixes.Add("http://+:" + ServerPort + "/"); + MainServer.Start(); + Logger.WriteLine("WindBot server start successed."); + Logger.WriteLine("HTTP GET http://127.0.0.1:" + ServerPort + "/?name=WindBot&host=127.0.0.1&port=7911 to call the bot."); + while (true) + { +#if !DEBUG + try + { +#endif + HttpListenerContext ctx = MainServer.GetContext(); + + WindBotInfo Info = new WindBotInfo(); + string RawUrl = Path.GetFileName(ctx.Request.RawUrl); + var queryStringParser = QueryStringParser.ParseQueryString(RawUrl); + Info.Name = queryStringParser["name"]; + Info.Deck = queryStringParser["deck"]; + Info.Host = queryStringParser["host"]; + string port = queryStringParser["port"]; + if (port != null) + Info.Port = Int32.Parse(port); + string deckfile = queryStringParser["deckfile"]; + if (deckfile != null) + Info.DeckFile = deckfile; + // [YGOL] TICKET-349 + string version = queryStringParser["version"]; + if (version != null) + Info.Version = Int16.Parse(version); + string password = queryStringParser["password"]; + if (password != null) + Info.HostInfo = password; + string hand = queryStringParser["hand"]; + if (hand != null) + Info.Hand = Int32.Parse(hand); + string debug = queryStringParser["debug"]; + if (debug != null) + Info.Debug= bool.Parse(debug); + // [YGOL] TICKET-349 + + if (Info.Name == null || Info.Host == null || port == null) + { + ctx.Response.StatusCode = 400; + ctx.Response.Close(); + } + else + { +#if !DEBUG + try + { +#endif + Thread workThread = new Thread(new ParameterizedThreadStart(Run)); + workThread.Start(Info); +#if !DEBUG + } + catch (Exception ex) + { + Logger.WriteErrorLine("Start Thread Error: " + ex); + } +#endif + ctx.Response.StatusCode = 200; + ctx.Response.Close(); + } +#if !DEBUG + } + catch (Exception ex) + { + Logger.WriteErrorLine("Parse Http Request Error: " + ex); + } +#endif + } + } + } + + private static void Run(object o) + { +#if !DEBUG + try + { + //all errors will be catched instead of causing the program to crash. +#endif + WindBotInfo Info = (WindBotInfo)o; + GameClient client = new GameClient(Info); + client.Start(); + Logger.DebugWriteLine(client.Username + " started."); + // [YGOL] TICKET-285: hand the client to its spawner (BotSeatService keeps it to assign decks in-process). + try { YGOL_onClient?.Invoke(client); } catch (Exception ex) { Logger.WriteErrorLine("Client hand-back error: " + ex); } + while (client.Connection.IsConnected) + { +#if !DEBUG + try + { +#endif + client.Tick(); + Thread.Sleep(30); +#if !DEBUG + } + catch (Exception ex) + { + Logger.WriteErrorLine("Tick Error: " + ex); + } +#endif + } + Logger.DebugWriteLine(client.Username + " end."); +#if !DEBUG + } + catch (Exception ex) + { + Logger.WriteErrorLine("Run Error: " + ex); + } +#endif + } + + public static FileStream ReadFile(string directory, string filename, string extension) + { + string tryfilename = filename + "." + extension; + string fullpath = Path.Combine(directory, tryfilename); + if (!File.Exists(fullpath)) + fullpath = filename; + if (!File.Exists(fullpath)) + fullpath = Path.Combine("../", filename); + if (!File.Exists(fullpath)) + fullpath = Path.Combine("../deck/", filename); + if (!File.Exists(fullpath)) + fullpath = Path.Combine("../", tryfilename); + if (!File.Exists(fullpath)) + fullpath = Path.Combine("../deck/", tryfilename); + if (!File.Exists(fullpath)) + fullpath = Path.Combine("Data/Windbot/" + directory, tryfilename); + if (!File.Exists(fullpath)) + fullpath = Path.Combine("Deck/", tryfilename); + return new FileStream(fullpath, FileMode.Open, FileAccess.Read); + } + } + + public static class QueryStringParser + { + public static NameValueCollection ParseQueryString(string query) + { + var result = new NameValueCollection(); + if (!string.IsNullOrEmpty(query)) + { + var pairs = query.Split('&'); + foreach (var pair in pairs) + { + if (pair.Contains("=")) + { + var parts = pair.Split('='); + var key = Uri.UnescapeDataString(parts[0]); + var value = parts.Length > 1 ? Uri.UnescapeDataString(parts[1]) : string.Empty; + result[key] = value; + } + } + } + return result; + } + } +} diff --git a/src/YGOLegacy.Bots/WindBot/WindBotInfo.cs b/src/YGOLegacy.Bots/WindBot/WindBotInfo.cs new file mode 100644 index 0000000..e85f385 --- /dev/null +++ b/src/YGOLegacy.Bots/WindBot/WindBotInfo.cs @@ -0,0 +1,49 @@ +using System; + +namespace WindBot +{ + public class WindBotInfo + { + public string Name { get; set; } + public string Deck { get; set; } + public string DeckFile { get; set; } + // [YGOL] TICKET-349 + public string Host { get; set; } + public int Port { get; set; } + public string HostInfo { get; set; } + public int Version { get; set; } + public int Hand { get; set; } + public bool Debug { get; set; } + // [YGOL] TICKET-349 + public string Character { get; set; } // [YGOL] TICKET-171: the character this bot announces over Appearance (null = none) + public string Group { get; set; } // [YGOL] TICKET-171: the deck group it announces (null = DeckFile's path prefix) + public int Seat { get; set; } // [YGOL] TICKET-285: the seat it claims before JoinGame (-1 = the server's choice) + public string SeatToken { get; set; } // [YGOL] TICKET-285: the host's claim token for that seat (hex) + public bool DeferDeck { get; set; } // [YGOL] TICKET-285: sit down deckless and unready; the host assigns the deck + public string Difficulty { get; set; } // [YGOL] TICKET-285: per-seat difficulty (null = the brain's) + public string RestartId { get; set; } // [YGOL] TICKET-286: the rules restart this bot returns for (hex); its claim carries it + public bool HoldReady { get; set; } // [YGOL] TICKET-286: upload the deck, send SeatResume Complete, and leave READY to the host's START + public WindBotInfo() + { + Name = "WindBot"; + Deck = null; + DeckFile = null; + // [YGOL] TICKET-349 + Host = "127.0.0.1"; + Port = 7911; + HostInfo = ""; + Version = 0x1362; + Hand = 0; + Debug = false; + // [YGOL] TICKET-349 + Character = null; // [YGOL] TICKET-171 + Group = null; // [YGOL] TICKET-171 + Seat = -1; // [YGOL] TICKET-285 + SeatToken = null; + DeferDeck = false; + Difficulty = null; + RestartId = null; // [YGOL] TICKET-286 + HoldReady = false; + } + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/BinaryClient.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/BinaryClient.cs new file mode 100644 index 0000000..55abdc2 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/BinaryClient.cs @@ -0,0 +1,292 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Sockets; +using YGOLegacy.Protocol.Framing; // [YGOL] TICKET-163 + +namespace YGOSharp.Network +{ + public class BinaryClient + { + public event Action Connected; + public event Action Disconnected; + public event Action PacketReceived; + + protected int MaxPacketLength = 0xFFFF; + protected int HeaderSize = 2; + protected bool IsHeaderSizeIncluded = false; + + private NetworkClient _client; + + private List _receiveBuffer = new List(); + private Queue _pendingPackets = new Queue(); + private byte[] _lengthBuffer = new byte[16]; + private FrameExtractor _frames = new FrameExtractor(); // [YGOL] TICKET-163 + + private int _pendingLength; + private bool _wasConnected; + private bool _wasDisconnected; + private bool _wasDisconnectedEventFired; + private Exception _closingException; + + public bool IsConnected + { + get { return !_wasDisconnectedEventFired; } + } + + public IPAddress RemoteIPAddress + { + get { return _client.RemoteIPAddress; } + } + + public BinaryClient(NetworkClient client) + { + _client = client; + + client.Connected += Client_Connected; + client.Disconnected += Client_Disconnected; + client.DataReceived += Client_DataReceived; + + if (_client.IsConnected) + { + _client.BeginReceive(); + } + } + + public void Connect(IPAddress address, int port) + { + _client.BeginConnect(address, port); + } + + public void Initialize(Socket socket) + { + _client.Initialize(socket); + } + + /// [YGOL] True while received packets wait for Update() (the standalone + /// bot arena spins its client loop without sleeping while this is set). + public bool HasPendingPackets + { + get { lock (_pendingPackets) return _pendingPackets.Count > 0; } + } + + // [YGOL] In-process duel host (TICKET-045): loopback transport. When + // YGOL_SendHook is set this client has no socket at all — Send() hands + // the (unframed) CTOS payload straight to the host, and the host pushes + // STOC packets in with YGOL_Inject. Nothing else changes: Update(), + // PacketReceived and everything riding them (GameBehavior, the + // DuelStateBus tap) take exactly the socket-fed code path. + public Action YGOL_SendHook; + + /// [YGOL] Queue one STOC packet as if the socket had delivered it. + public void YGOL_Inject(byte[] packet) + { + if (packet == null || packet.Length == 0) return; + lock (_pendingPackets) + { + _pendingPackets.Enqueue(packet); + } + } + + /// [YGOL] Make the next Update() raise Connected without a socket. + public void YGOL_MarkConnected() + { + _wasConnected = true; + } + + public void Update() + { + if (_wasConnected) + { + _wasConnected = false; + Connected?.Invoke(); + } + ReceivePendingPackets(); + if (_wasDisconnected && !_wasDisconnectedEventFired) + { + _wasDisconnectedEventFired = true; + Disconnected?.Invoke(_closingException); + } + } + + public void Send(byte[] packet) + { + // [YGOL] loopback (TICKET-045): no socket, no length header — see YGOL_SendHook. + Action hook = YGOL_SendHook; + if (hook != null) + { + hook(packet); + return; + } + // [YGOL] TICKET-163: the 2-byte frame is FrameCodec's; its ceiling throw replaces the size check on this path. + if (HeaderSize == 2) + { + using (MemoryStream stream = new MemoryStream(packet.Length + FrameCodec.HeaderSize)) + using (BinaryWriter writer = new BinaryWriter(stream)) + { + FrameCodec.Write(writer, packet); + writer.Flush(); + _client.BeginSend(stream.ToArray()); + } + return; + } + if (packet.Length > MaxPacketLength) + { + throw new Exception("Tried to send a too large packet"); + } + + int packetLength = packet.Length; + if (IsHeaderSizeIncluded) packetLength += HeaderSize; + + byte[] header; + if (HeaderSize == 4) + { + header = BitConverter.GetBytes(packetLength); + } + else + { + throw new Exception("Unsupported header size: " + HeaderSize); + } + byte[] data = new byte[packet.Length + HeaderSize]; + Array.Copy(header, 0, data, 0, header.Length); + Array.Copy(packet, 0, data, header.Length, packet.Length); + _client.BeginSend(data); + } + + public void Close(Exception error = null) + { + _client.Close(error); + } + + private void ReceivePendingPackets() + { + bool hasReceived; + do + { + byte[] packet = null; + lock (_pendingPackets) + { + if (_pendingPackets.Count > 0) + { + packet = _pendingPackets.Dequeue(); + } + } + hasReceived = false; + if (packet != null) + { + hasReceived = true; + using (MemoryStream stream = new MemoryStream(packet, false)) + { + using (BinaryReader reader = new BinaryReader(stream)) + { + PacketReceived?.Invoke(reader); + } + } + } + } + while (hasReceived); + } + + private void Client_Connected() + { + _wasConnected = true; + } + + private void Client_Disconnected(Exception ex) + { + _wasDisconnected = true; + _closingException = ex; + } + + private void Client_DataReceived(byte[] data) + { + // [YGOL] TICKET-163: the 2-byte frame is FrameExtractor's: a zero-length frame is skipped, an oversize length closes. + if (HeaderSize == 2) + { + _frames.Feed(data, data.Length); + byte[] packet; + while (_frames.TryTake(out packet)) + { + lock (_pendingPackets) + { + _pendingPackets.Enqueue(packet); + } + } + if (_frames.Faulted) + { + _client.Close(new Exception("Tried to receive a too large packet")); + } + return; + } + _receiveBuffer.AddRange(data); + ExtractPackets(); + } + + private void ExtractPackets() + { + bool hasExtracted; + do + { + if (_pendingLength == 0) + { + hasExtracted = ExtractPendingLength(); + } + else + { + hasExtracted = ExtractPendingPacket(); + } + } + while (hasExtracted); + } + + private bool ExtractPendingLength() + { + if (_receiveBuffer.Count >= HeaderSize) + { + _receiveBuffer.CopyTo(0, _lengthBuffer, 0, HeaderSize); + // [YGOL] TICKET-163: the 2-byte header no longer reaches here (Client_DataReceived); the 4-byte branch stays under the freeze. + if (HeaderSize == 4) + { + _pendingLength = BitConverter.ToInt32(_lengthBuffer, 0); + } + else + { + throw new Exception("Unsupported header size: " + HeaderSize); + } + _receiveBuffer.RemoveRange(0, HeaderSize); + + if (IsHeaderSizeIncluded) _pendingLength -= HeaderSize; + + if (_pendingLength < 0 || _pendingLength > MaxPacketLength) + { + _client.Close(new Exception("Tried to receive a too large packet")); + return false; + } + + return true; + } + return false; + } + + private bool ExtractPendingPacket() + { + if (_receiveBuffer.Count >= _pendingLength) + { + byte[] packet = new byte[_pendingLength]; + + _receiveBuffer.CopyTo(0, packet, 0, _pendingLength); + _receiveBuffer.RemoveRange(0, _pendingLength); + _pendingLength = 0; + + lock (_pendingPackets) + { + _pendingPackets.Enqueue(packet); + } + + return true; + } + return false; + } + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/CtosMessage.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/CtosMessage.cs new file mode 100644 index 0000000..a04bd0d --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/CtosMessage.cs @@ -0,0 +1,24 @@ +namespace YGOSharp.Network.Enums +{ + public enum CtosMessage + { + Response = 0x1, + UpdateDeck = 0x2, + HandResult = 0x3, + TpResult = 0x4, + PlayerInfo = 0x10, + CreateGame = 0x11, + JoinGame = 0x12, + LeaveGame = 0x13, + Surrender = 0x14, + TimeConfirm = 0x15, + Chat = 0x16, + ExternalAddress = 0x17, + HsToDuelist = 0x20, + HsToObserver = 0x21, + HsReady = 0x22, + HsNotReady = 0x23, + HsKick = 0x24, + HsStart = 0x25 + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/GameState.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/GameState.cs new file mode 100644 index 0000000..8f2999f --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/GameState.cs @@ -0,0 +1,12 @@ +namespace YGOSharp.Network.Enums +{ + public enum GameState + { + Lobby = 0, + Hand = 1, + Starting = 2, + Duel = 3, + End = 4, + Side = 5 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerChange.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerChange.cs new file mode 100644 index 0000000..7b28ca6 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerChange.cs @@ -0,0 +1,10 @@ +namespace YGOSharp.Network.Enums +{ + public enum PlayerChange + { + Observe = 0x8, + Ready = 0x9, + NotReady = 0xA, + Leave = 0xB + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerState.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerState.cs new file mode 100644 index 0000000..22091f6 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerState.cs @@ -0,0 +1,8 @@ +namespace YGOSharp.Network.Enums +{ + public enum PlayerState + { + None = 0, + Response = 1 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerType.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerType.cs new file mode 100644 index 0000000..9d17d6f --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/PlayerType.cs @@ -0,0 +1,23 @@ +namespace YGOSharp.Network.Enums +{ + public enum PlayerType + { + Undefined = -1, + Player1 = 0, + Player2 = 1, + Player3 = 2, + Player4 = 3, + Player5 = 4, + Player6 = 5, + Observer = 7, + Host = 0x10, + Red = 11, + Green = 12, + Blue = 13, + BabyBlue = 14, + Pink = 15, + Yellow = 16, + White = 17, + Gray = 18 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/StocMessage.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/StocMessage.cs new file mode 100644 index 0000000..73e2f6a --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Enums/StocMessage.cs @@ -0,0 +1,27 @@ +namespace YGOSharp.Network.Enums +{ + public enum StocMessage + { + GameMsg = 0x1, + ErrorMsg = 0x2, + SelectHand = 0x3, + SelectTp = 0x4, + HandResult = 0x5, + TpResult = 0x6, + ChangeSide = 0x7, + WaitingSide = 0x8, + CreateGame = 0x11, + JoinGame = 0x12, + TypeChange = 0x13, + LeaveGame = 0x14, + DuelStart = 0x15, + DuelEnd = 0x16, + Replay = 0x17, + TimeLimit = 0x18, + Chat = 0x19, + HsPlayerEnter = 0x20, + HsPlayerChange = 0x21, + HsWatchChange = 0x22, + TeammateSurrender = 0x23 + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/NetworkClient.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/NetworkClient.cs new file mode 100644 index 0000000..a7f8178 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/NetworkClient.cs @@ -0,0 +1,161 @@ +using System; +using System.Net; +using System.Net.Sockets; + +namespace YGOSharp.Network +{ + public class NetworkClient + { + public event Action Connected; + public event Action Disconnected; + public event Action DataReceived; + + public bool IsConnected { get; private set; } + + public IPAddress RemoteIPAddress + { + get { return _endPoint.Address; } + } + + private const int BufferSize = 4096; + + private Socket _socket; + private IPEndPoint _endPoint; + private bool _isClosed; + private byte[] _receiveBuffer = new byte[BufferSize]; + + public NetworkClient() + { + } + + public NetworkClient(Socket socket) + { + Initialize(socket); + } + + public void Initialize(Socket socket) + { + _endPoint = (IPEndPoint)socket.RemoteEndPoint; + _socket = socket; + IsConnected = true; + Connected?.Invoke(); + } + + public void BeginConnect(IPAddress address, int port) + { + if (!IsConnected && !_isClosed) + { + IsConnected = true; + try + { + _endPoint = new IPEndPoint(address, port); + _socket = new Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + _socket.BeginConnect(_endPoint, new AsyncCallback(ConnectCallback), null); + } + catch (Exception ex) + { + Close(ex); + } + } + } + + public void BeginSend(byte[] data) + { + try + { + _socket.BeginSend(data, 0, data.Length, SocketFlags.None, SendCallback, data.Length); + } + catch (Exception ex) + { + Close(ex); + } + } + + public void BeginReceive() + { + try + { + _socket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, ReceiveCallback, null); + } + catch (Exception ex) + { + Close(ex); + } + } + + public void Close(Exception error = null) + { + if (!_isClosed) + { + _isClosed = true; + try + { + if (_socket != null) + { + _socket.Close(); + } + } + catch (Exception ex) + { + ex = new AggregateException(error, ex); + } + IsConnected = false; + Disconnected?.Invoke(error); + } + } + + private void ConnectCallback(IAsyncResult result) + { + try + { + _socket.EndConnect(result); + } + catch (Exception ex) + { + Close(ex); + return; + } + Connected?.Invoke(); + BeginReceive(); + } + + private void SendCallback(IAsyncResult result) + { + try + { + int bytesSent = _socket.EndSend(result); + if (bytesSent != (int)result.AsyncState) + { + Close(); + } + } + catch (Exception ex) + { + Close(ex); + } + } + + private void ReceiveCallback(IAsyncResult result) + { + int bytesRead; + try + { + bytesRead = _socket.EndReceive(result); + } + catch (Exception ex) + { + Close(ex); + return; + } + if (bytesRead == 0) + { + Close(); + return; + } + byte[] data = new byte[bytesRead]; + Array.Copy(_receiveBuffer, data, bytesRead); + DataReceived?.Invoke(data); + BeginReceive(); + } + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Utils/BinaryExtensions.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Utils/BinaryExtensions.cs new file mode 100644 index 0000000..f288d77 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/Utils/BinaryExtensions.cs @@ -0,0 +1,57 @@ +using System; +using System.IO; +using System.Text; + +namespace YGOSharp.Network.Utils +{ + public static class BinaryExtensions + { + // fixed length strings + public static void WriteUnicode(this BinaryWriter writer, string text, int len) + { + byte[] unicode = Encoding.Unicode.GetBytes(text); + byte[] result = new byte[len * 2]; + int copy = unicode.Length; + if (unicode.Length > len * 2 - 2) + { + copy = len * 2 - 2; +#if DEBUG + throw new ArgumentException("String '" + text + "' is too long for fixed length " + len + "."); +#endif + } + Array.Copy(unicode, result, copy); + writer.Write(result); + } + + // variable length strings + public static void WriteUnicodeAutoLength(this BinaryWriter writer, string text, int maxlen) + { + byte[] result = Encoding.Unicode.GetBytes(text + "\0"); + int len = result.Length / 2; + if (len > maxlen) + { + len = maxlen; + result[len * 2 - 2] = 0; + result[len * 2 - 1] = 0; +#if DEBUG + throw new ArgumentException("String '" + text + "' is too long for max length " + maxlen + "."); +#endif + } + writer.Write(result, 0, len * 2); + } + + public static string ReadUnicode(this BinaryReader reader, int len) + { + byte[] unicode = reader.ReadBytes(len * 2); + string text = Encoding.Unicode.GetString(unicode); + int index = text.IndexOf('\0'); + if (index > 0) text = text.Substring(0, index); + return text; + } + + public static byte[] ReadToEnd(this BinaryReader reader) + { + return reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)); + } + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/YGOClient.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/YGOClient.cs new file mode 100644 index 0000000..6ff386a --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.Network/YGOClient.cs @@ -0,0 +1,49 @@ +using System.IO; +using YGOSharp.Network.Enums; +using YGOLegacy.Protocol.Codecs; // [YGOL] TICKET-162 + +namespace YGOSharp.Network +{ + public class YGOClient : BinaryClient + { + public YGOClient() + : base(new NetworkClient()) + { + } + + public YGOClient(NetworkClient client) + : base(client) + { + } + + public void Send(BinaryWriter writer) + { + Send(((MemoryStream)writer.BaseStream).ToArray()); + } + + // [YGOL] TICKET-162: these two overloads are the seam for WindBot's legacy Send(CtosMessage[, int]) sites: + // the id byte comes from CtosPacket, the payload from the shared codec for that id. + public void Send(CtosMessage message) + { + using (BinaryWriter writer = CtosPacket.Begin((YGOLegacy.Protocol.Contracts.CtosMessage)(int)message)) + { + Send(writer); + } + } + + public void Send(CtosMessage message, int value) + { + using (BinaryWriter writer = CtosPacket.Begin((YGOLegacy.Protocol.Contracts.CtosMessage)(int)message)) + { + // HandResult and TpResult are 1 byte on the wire (the native struct); they went out as int32 before. + if (message == CtosMessage.HandResult) + DuelCodecs.HandResult.Write(writer, new YGOLegacy.Protocol.Contracts.HandResult((byte)value)); + else if (message == CtosMessage.TpResult) + DuelCodecs.TpResult.Write(writer, new YGOLegacy.Protocol.Contracts.TpResult(value != 0)); + else + DuelCodecs.Response.Write(writer, value); + Send(writer); + } + } + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardAttribute.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardAttribute.cs new file mode 100644 index 0000000..a8d9b43 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardAttribute.cs @@ -0,0 +1,13 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum CardAttribute + { + Earth = 0x01, + Water = 0x02, + Fire = 0x04, + Wind = 0x08, + Light = 0x10, + Dark = 0x20, + Divine = 0x40, + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardLinkMarker.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardLinkMarker.cs new file mode 100644 index 0000000..434cd8c --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardLinkMarker.cs @@ -0,0 +1,15 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum CardLinkMarker + { + BottomLeft = 0x01, + Bottom = 0x02, + BottomRight = 0x04, + Left = 0x08, + + Right = 0x20, + TopLeft = 0x40, + Top = 0x80, + TopRight = 0x100 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardLocation.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardLocation.cs new file mode 100644 index 0000000..5f0ccc7 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardLocation.cs @@ -0,0 +1,17 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum CardLocation + { + Deck = 0x01, + Hand = 0x02, + MonsterZone = 0x04, + SpellZone = 0x08, + Grave = 0x10, + Removed = 0x20, + Extra = 0x40, + Overlay = 0x80, + Onfield = 0x0C, + FieldZone = 0x100, + PendulumZone = 0x200, + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardPosition.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardPosition.cs new file mode 100644 index 0000000..147f326 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardPosition.cs @@ -0,0 +1,14 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum CardPosition + { + FaceUpAttack = 0x1, + FaceDownAttack = 0x2, + FaceUpDefence = 0x4, + FaceDownDefence = 0x8, + FaceUp = 0x5, + FaceDown = 0xA, + Attack = 0x3, + Defence = 0xC + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardRace.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardRace.cs new file mode 100644 index 0000000..f1c9547 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardRace.cs @@ -0,0 +1,30 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum CardRace + { + Warrior = 0x1, + SpellCaster = 0x2, + Fairy = 0x4, + Fiend = 0x8, + Zombie = 0x10, + Machine = 0x20, + Aqua = 0x40, + Pyro = 0x80, + Rock = 0x100, + WindBeast = 0x200, + Plant = 0x400, + Insect = 0x800, + Thunder = 0x1000, + Dragon = 0x2000, + Beast = 0x4000, + BeastWarrior = 0x8000, + Dinosaur = 0x10000, + Fish = 0x20000, + SeaSerpent = 0x40000, + Reptile = 0x80000, + Psycho = 0x100000, + DivineBeast = 0x200000, + Wyrm = 0x800000, + Cyberse = 0x1000000 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardType.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardType.cs new file mode 100644 index 0000000..b5f44d9 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/CardType.cs @@ -0,0 +1,31 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum CardType + { + Monster = 0x1, + Spell = 0x2, + Trap = 0x4, + Normal = 0x10, + Effect = 0x20, + Fusion = 0x40, + Ritual = 0x80, + TrapMonster = 0x100, + Spirit = 0x200, + Union = 0x400, + Dual = 0x800, + Tuner = 0x1000, + Synchro = 0x2000, + Token = 0x4000, + QuickPlay = 0x10000, + Continuous = 0x20000, + Equip = 0x40000, + Field = 0x80000, + Counter = 0x100000, + Flip = 0x200000, + Toon = 0x400000, + Xyz = 0x800000, + Pendulum = 0x1000000, + SpSummon = 0x2000000, + Link = 0x4000000 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/DuelPhase.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/DuelPhase.cs new file mode 100644 index 0000000..f95ce87 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/DuelPhase.cs @@ -0,0 +1,16 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum DuelPhase + { + Draw = 0x01, + Standby = 0x02, + Main1 = 0x04, + BattleStart = 0x08, + BattleStep = 0x10, + Damage = 0x20, + DamageCal = 0x40, + Battle = 0x80, + Main2 = 0x100, + End = 0x200 + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/GameMessage.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/GameMessage.cs new file mode 100644 index 0000000..6746572 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/GameMessage.cs @@ -0,0 +1,102 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum GameMessage + { + Retry = 1, + Hint = 2, + Waiting = 3, + Start = 4, + Win = 5, + UpdateData = 6, + UpdateCard = 7, + RequestDeck = 8, + SelectBattleCmd = 10, + SelectIdleCmd = 11, + SelectEffectYn = 12, + SelectYesNo = 13, + SelectOption = 14, + SelectCard = 15, + SelectChain = 16, + SelectPlace = 18, + SelectPosition = 19, + SelectTribute = 20, + SortChain = 21, + SelectCounter = 22, + SelectSum = 23, + SelectDisfield = 24, + SortCard = 25, + SelectUnselect = 26, + ConfirmDecktop = 30, + ConfirmCards = 31, + ShuffleDeck = 32, + ShuffleHand = 33, + RefreshDeck = 34, + SwapGraveDeck = 35, + ShuffleSetCard = 36, + ReverseDeck = 37, + DeckTop = 38, + ShuffleExtra = 39, + NewTurn = 40, + NewPhase = 41, + ConfirmExtratop = 42, + Move = 50, + PosChange = 53, + Set = 54, + Swap = 55, + FieldDisabled = 56, + Summoning = 60, + Summoned = 61, + SpSummoning = 62, + SpSummoned = 63, + FlipSummoning = 64, + FlipSummoned = 65, + Chaining = 70, + Chained = 71, + ChainSolving = 72, + ChainSolved = 73, + ChainEnd = 74, + ChainNegated = 75, + ChainDisabled = 76, + CardSelected = 80, + RandomSelected = 81, + BecomeTarget = 83, + Draw = 90, + Damage = 91, + Recover = 92, + Equip = 93, + LpUpdate = 94, + Unequip = 95, + CardTarget = 96, + CancelTarget = 97, + PayLpCost = 100, + AddCounter = 101, + RemoveCounter = 102, + Attack = 110, + Battle = 111, + AttackDisabled = 112, + DamageStepStart = 113, + DamageStepEnd = 114, + MissedEffect = 120, + BeChainTarget = 121, + CreateRelation = 122, + ReleaseRelation = 123, + TossCoin = 130, + TossDice = 131, + RockPaperScissors = 132, + HandResult = 133, + AnnounceRace = 140, + AnnounceAttrib = 141, + AnnounceCard = 142, + AnnounceNumber = 143, + AnnounceCardFilter = 144, + CardHint = 160, + TagSwap = 161, + ReloadField = 162, + AiName = 163, + ShowHint = 164, + PlayerHint = 165, + MatchKill = 170, + CustomMsg = 180, + DuelWinner = 200 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/PlayerHintType.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/PlayerHintType.cs new file mode 100644 index 0000000..2a29376 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/PlayerHintType.cs @@ -0,0 +1,13 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + /// + /// Hint type for PlayerHint message (matches PHINT constants in core). + /// + public enum PlayerHintType + { + /// Add effect description hint + DescAdd = 6, + /// Remove effect description hint + DescRemove = 7 + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/Query.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/Query.cs new file mode 100644 index 0000000..31d32eb --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper.Enums/Query.cs @@ -0,0 +1,29 @@ +namespace YGOSharp.OCGWrapper.Enums +{ + public enum Query + { + Code = 0x01, + Position = 0x02, + Alias = 0x04, + Type = 0x08, + Level = 0x10, + Rank = 0x20, + Attribute = 0x40, + Race = 0x80, + Attack = 0x100, + Defence = 0x200, + BaseAttack = 0x400, + BaseDefence = 0x800, + Reason = 0x1000, + ReasonCard = 0x2000, + EquipCard = 0x4000, + TargetCard = 0x8000, + OverlayCard = 0x10000, + Counters = 0x20000, + Owner = 0x40000, + Status = 0x80000, + LScale = 0x200000, + RScale = 0x400000, + Link = 0x800000 + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/Card.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/Card.cs new file mode 100644 index 0000000..48b9250 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/Card.cs @@ -0,0 +1,98 @@ +using YGOSharp.OCGWrapper.Enums; +using System.Data; + +namespace YGOSharp.OCGWrapper +{ + public class Card + { + public struct CardData + { + public int Code; + public int Alias; + public long Setcode; + 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 int Id { get; private set; } + public int Ot { get; private set; } + public int Alias { get; private set; } + public long Setcode { get; private set; } + public int Type { get; private set; } + + public int Level { get; private set; } + public int LScale { get; private set; } + public int RScale { get; private set; } + public int LinkMarker { get; private set; } + + public int Attribute { get; private set; } + public int Race { get; private set; } + public int Attack { get; private set; } + public int Defense { get; private set; } + + internal CardData Data { get; private set; } + + public static Card Get(int id) + { + return CardsManager.GetCard(id); + } + + public bool HasType(CardType type) + { + return ((Type & (int)type) != 0); + } + + public bool IsExtraCard() + { + return (HasType(CardType.Fusion) || HasType(CardType.Synchro) || HasType(CardType.Xyz) || HasType(CardType.Link)); + } + + internal Card(IDataRecord reader) + { + Id = reader.GetInt32(0); + Ot = reader.GetInt32(1); + Alias = reader.GetInt32(2); + Setcode = reader.GetInt64(3); + Type = reader.GetInt32(4); + + int levelInfo = reader.GetInt32(5); + Level = levelInfo & 0xff; + LScale = (levelInfo >> 24) & 0xff; + RScale = (levelInfo >> 16) & 0xff; + + Race = reader.GetInt32(6); + Attribute = reader.GetInt32(7); + Attack = reader.GetInt32(8); + Defense = reader.GetInt32(9); + + if (HasType(CardType.Link)) + { + LinkMarker = Defense; + Defense = 0; + } + + Data = new CardData() + { + Code = Id, + Alias = Alias, + Setcode = Setcode, + Type = Type, + Level = Level, + Attribute = Attribute, + Race = Race, + Attack = Attack, + Defense = Defense, + LScale = LScale, + RScale = RScale, + LinkMarker = LinkMarker + }; + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/CardsManager.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/CardsManager.cs new file mode 100644 index 0000000..0fef6f7 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/CardsManager.cs @@ -0,0 +1,45 @@ +using System.Collections.Generic; +using System.Data; +using Mono.Data.Sqlite; + +namespace YGOSharp.OCGWrapper +{ + internal static class CardsManager + { + private static IDictionary _cards; + + internal static void Init(string databaseFullPath) + { + _cards = new Dictionary(); + + using (SqliteConnection connection = new SqliteConnection("Data Source=" + databaseFullPath)) + { + connection.Open(); + + using (IDbCommand command = new SqliteCommand("SELECT id, ot, alias, setcode, type, level, race, attribute, atk, def FROM datas", connection)) + { + using (IDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + LoadCard(reader); + } + } + } + } + } + + internal static Card GetCard(int id) + { + if (_cards.ContainsKey(id)) + return _cards[id]; + return null; + } + + private static void LoadCard(IDataRecord reader) + { + Card card = new Card(reader); + _cards.Add(card.Id, card); + } + } +} \ No newline at end of file diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/NamedCard.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/NamedCard.cs new file mode 100644 index 0000000..4e962aa --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/NamedCard.cs @@ -0,0 +1,36 @@ +using System.Data; + +namespace YGOSharp.OCGWrapper +{ + public class NamedCard : Card + { + public string Name { get; private set; } + public string Description { get; private set; } + + internal NamedCard(IDataRecord reader) : base(reader) + { + Name = reader.GetString(10); + Description = reader.GetString(11); + } + + public static new NamedCard Get(int id) + { + return NamedCardsManager.GetCard(id); + } + + public bool HasSetcode(int setcode) + { + long num = setcode; + int num2 = setcode & 0xFFF; + int num3 = setcode & 0xF000; + while(num > 0) + { + long num4 = num & 0xFFFF; + num >>= 16; + if((num4 & 0xFFF) == num2 && (num4 & 0xF000 & num3) == num3) + return true; + } + return false; + } + } +} diff --git a/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/NamedCardsManager.cs b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/NamedCardsManager.cs new file mode 100644 index 0000000..2af5f35 --- /dev/null +++ b/src/YGOLegacy.Bots/YGOSharp/YGOSharp.OCGWrapper/NamedCardsManager.cs @@ -0,0 +1,106 @@ +using System.Collections.Generic; +using System.Data; +using Mono.Data.Sqlite; +using System; +using System.IO; + +namespace YGOSharp.OCGWrapper +{ + public static class NamedCardsManager + { + private static IDictionary _cards; + + public static void Init(string databaseFullPath) + { + try + { + if (!File.Exists(databaseFullPath)) + { + throw new Exception("Could not find the cards database."); + } + + _cards = new Dictionary(); + + using (SqliteConnection connection = new SqliteConnection("Data Source=" + databaseFullPath)) + { + connection.Open(); + + using (IDbCommand command = new SqliteCommand( + "SELECT datas.id, ot, alias, setcode, type, level, race, attribute, atk, def, texts.name, texts.desc" + + " FROM datas INNER JOIN texts ON datas.id = texts.id", + connection)) + { + using (IDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + LoadCard(reader); + } + } + } + } + } + catch (Exception ex) + { + throw new Exception("Could not initialize the cards database. Check the inner exception for more details.", ex); + } + } + + public static void InitForMulti(List databaseFullPaths) + { + try + { + _cards = new Dictionary(); + + foreach(var databaseFullPath in databaseFullPaths) + { + if (!File.Exists(databaseFullPath)) + continue; + + using (SqliteConnection connection = new SqliteConnection("Data Source=" + databaseFullPath)) + { + connection.Open(); + + using (IDbCommand command = new SqliteCommand( + "SELECT datas.id, ot, alias, setcode, type, level, race, attribute, atk, def, texts.name, texts.desc" + + " FROM datas INNER JOIN texts ON datas.id = texts.id", + connection)) + { + using (IDataReader reader = command.ExecuteReader()) + { + while (reader.Read()) + { + LoadCard(reader); + } + } + } + } + } + } + catch (Exception ex) + { + throw new Exception("Could not initialize the cards database. Check the inner exception for more details.", ex); + } + } + + internal static NamedCard GetCard(int id) + { + if (_cards.ContainsKey(id)) + return _cards[id]; + return null; + } + internal static IList GetAllCards() + { + var returnValue = new List(); + foreach (NamedCard card in _cards.Values) + returnValue.Add(card); + return returnValue; + } + + private static void LoadCard(IDataRecord reader) + { + NamedCard card = new NamedCard(reader); + _cards[card.Id] = card; + } + } +} \ No newline at end of file