diff --git a/ExecutorBase/ExecutorBase.csproj b/ExecutorBase/ExecutorBase.csproj
index 03209f616..eed8724dc 100644
--- a/ExecutorBase/ExecutorBase.csproj
+++ b/ExecutorBase/ExecutorBase.csproj
@@ -56,6 +56,7 @@
+
diff --git a/ExecutorBase/Game/AI/Executor.cs b/ExecutorBase/Game/AI/Executor.cs
index 7162c7bb5..bcf4ad274 100644
--- a/ExecutorBase/Game/AI/Executor.cs
+++ b/ExecutorBase/Game/AI/Executor.cs
@@ -256,6 +256,12 @@ public virtual bool OnSelectMonsterSummonOrSet(ClientCard card)
return false;
}
+ public virtual bool TryGetMainPhaseAction(MainPhase main, out MainPhaseAction action)
+ {
+ action = null;
+ return false;
+ }
+
///
/// Called when bot is going to annouce a card
///
diff --git a/ExecutorBase/Game/AI/IMainPhaseDecisionObserver.cs b/ExecutorBase/Game/AI/IMainPhaseDecisionObserver.cs
new file mode 100644
index 000000000..6b05e38ef
--- /dev/null
+++ b/ExecutorBase/Game/AI/IMainPhaseDecisionObserver.cs
@@ -0,0 +1,9 @@
+namespace WindBot.Game.AI
+{
+ // Optional observer; other decks need not implement it.
+ public interface IMainPhaseDecisionObserver
+ {
+ void ObserveDuelStart();
+ void ObserveLegacyMainPhaseAction(string kind, int cardId, long description);
+ }
+}
diff --git a/ExecutorBase/Game/GameAI.cs b/ExecutorBase/Game/GameAI.cs
index b181b35b9..27bc76c76 100644
--- a/ExecutorBase/Game/GameAI.cs
+++ b/ExecutorBase/Game/GameAI.cs
@@ -75,6 +75,8 @@ public void OnJoinGame()
///
public void OnStart()
{
+ var observer = Executor as IMainPhaseDecisionObserver;
+ if (observer != null) observer.ObserveDuelStart();
_dialogs.SendDuelStart();
}
@@ -474,19 +476,30 @@ public bool OnSelectEffectYn(ClientCard card, long desc)
///
/// A lot of informations about the available actions.
/// A new MainPhaseAction containing the action to do.
+ private MainPhaseAction ObserveLegacyIdleAction(MainPhaseAction action, string kind, int cardId, long description)
+ {
+ var observer = Executor as IMainPhaseDecisionObserver;
+ if (observer != null) observer.ObserveLegacyMainPhaseAction(kind, cardId, description);
+ return action;
+ }
+
public MainPhaseAction OnSelectIdleCmd(MainPhase main)
{
CheckSurrender();
+ MainPhaseAction candidateAction;
+ if (Executor.TryGetMainPhaseAction(main, out candidateAction))
+ return candidateAction;
+
foreach (CardExecutor exec in Executor.Executors)
{
if (exec.Type == ExecutorType.GoToEndPhase && main.CanEndPhase && exec.Func()) // check if should enter end phase directly
{
_dialogs.SendEndTurn();
- return new MainPhaseAction(MainPhaseAction.MainAction.ToEndPhase);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.ToEndPhase), "ToEndPhase", 0, -1);
}
if (exec.Type==ExecutorType.GoToBattlePhase && main.CanBattlePhase && exec.Func()) // check if should enter battle phase directly
{
- return new MainPhaseAction(MainPhaseAction.MainAction.ToBattlePhase);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.ToBattlePhase), "ToBattlePhase", 0, -1);
}
// 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.
@@ -497,7 +510,7 @@ public MainPhaseAction OnSelectIdleCmd(MainPhase main)
if (ShouldExecute(exec, card, ExecutorType.Activate, main.ActivableDescs[i]))
{
_dialogs.SendActivate(card.Name);
- return new MainPhaseAction(MainPhaseAction.MainAction.Activate, card.ActionActivateIndex[main.ActivableDescs[i]]);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.Activate, card.ActionActivateIndex[main.ActivableDescs[i]]), "Activate", card.Id, main.ActivableDescs[i]);
}
}
foreach (ClientCard card in main.MonsterSetableCards)
@@ -505,20 +518,20 @@ public MainPhaseAction OnSelectIdleCmd(MainPhase main)
if (ShouldExecute(exec, card, ExecutorType.MonsterSet))
{
_dialogs.SendSetMonster();
- return new MainPhaseAction(MainPhaseAction.MainAction.SetMonster, card.ActionIndex);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.SetMonster, card.ActionIndex), "SetMonster", card.Id, -1);
}
}
foreach (ClientCard card in main.ReposableCards)
{
if (ShouldExecute(exec, card, ExecutorType.Repos))
- return new MainPhaseAction(MainPhaseAction.MainAction.Repos, card.ActionIndex);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.Repos, card.ActionIndex), "Repos", card.Id, -1);
}
foreach (ClientCard card in main.SpecialSummonableCards)
{
if (ShouldExecute(exec, card, ExecutorType.SpSummon))
{
_dialogs.SendSummon(card.Name);
- return new MainPhaseAction(MainPhaseAction.MainAction.SpSummon, card.ActionIndex);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.SpSummon, card.ActionIndex), "SpSummon", card.Id, -1);
}
}
foreach (ClientCard card in main.SummonableCards)
@@ -526,31 +539,31 @@ public MainPhaseAction OnSelectIdleCmd(MainPhase main)
if (ShouldExecute(exec, card, ExecutorType.Summon))
{
_dialogs.SendSummon(card.Name);
- return new MainPhaseAction(MainPhaseAction.MainAction.Summon, card.ActionIndex);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.Summon, card.ActionIndex), "Summon", card.Id, -1);
}
if (ShouldExecute(exec, card, ExecutorType.SummonOrSet))
{
if (main.MonsterSetableCards.Contains(card) && Executor.OnSelectMonsterSummonOrSet(card))
{
_dialogs.SendSetMonster();
- return new MainPhaseAction(MainPhaseAction.MainAction.SetMonster, card.ActionIndex);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.SetMonster, card.ActionIndex), "SetMonster", card.Id, -1);
}
_dialogs.SendSummon(card.Name);
- return new MainPhaseAction(MainPhaseAction.MainAction.Summon, card.ActionIndex);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.Summon, card.ActionIndex), "Summon", card.Id, -1);
}
}
foreach (ClientCard card in main.SpellSetableCards)
{
if (ShouldExecute(exec, card, ExecutorType.SpellSet))
- return new MainPhaseAction(MainPhaseAction.MainAction.SetSpell, card.ActionIndex);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.SetSpell, card.ActionIndex), "SetSpell", card.Id, -1);
}
}
if (main.CanBattlePhase && Duel.Fields[0].HasAttackingMonster())
- return new MainPhaseAction(MainPhaseAction.MainAction.ToBattlePhase);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.ToBattlePhase), "ToBattlePhase", 0, -1);
_dialogs.SendEndTurn();
- return new MainPhaseAction(MainPhaseAction.MainAction.ToEndPhase);
+ return ObserveLegacyIdleAction(new MainPhaseAction(MainPhaseAction.MainAction.ToEndPhase), "ToEndPhase", 0, -1);
}
///
diff --git a/Game/AI/Decks/ActionCandidate.cs b/Game/AI/Decks/ActionCandidate.cs
new file mode 100644
index 000000000..c953334ea
--- /dev/null
+++ b/Game/AI/Decks/ActionCandidate.cs
@@ -0,0 +1,21 @@
+using System;
+
+namespace RyzealAI.Prototype
+{
+ public enum ActionType { NormalSummon, SpecialSummon, Activate }
+
+ // AI policy가 평가할 수 있는, 엔진이 이미 합법으로 제시한 행동 1개.
+ public sealed class ActionCandidate
+ {
+ public ActionType ActionType { get; set; }
+ public int CardId { get; set; }
+ public int ActionIndex { get; set; }
+ public long ActivationDescription { get; set; }
+ public double BaselineScore { get; set; }
+ public string Label { get; set; }
+ public string GoalTag { get; set; }
+ // Planned prompt choices, for traceability. This is not an engine legality source.
+ public string SelectionPlan { get; set; }
+ public Func Commit { get; set; }
+ }
+}
diff --git a/Game/AI/Decks/CardValueEngine.cs b/Game/AI/Decks/CardValueEngine.cs
new file mode 100644
index 000000000..d2601dfe5
--- /dev/null
+++ b/Game/AI/Decks/CardValueEngine.cs
@@ -0,0 +1,715 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace RyzealAI.Prototype
+{
+ // ============================================================
+ // 0. 이 파일의 목적 / 이번 확장에서 바뀐 것
+ // ============================================================
+ // - 카드 20개로 늘어나면서, 조건 없는/단순한 카드까지 전부 함수로
+ // 따로 짜는 건 유지보수가 안 되므로 "데이터 선언 + 해석기" 구조로 전환.
+ // - Star / Plugin / Cross 는 여전히 다른 카드의 파워 총합을 참조해야
+ // 해서(Tier1/Tier2) 예전처럼 전용 함수로 남겨둠.
+ // - 나머지(Ice/Sword/Ext/Node/PlasmaHole + 핸드트랩/튜터/기타 전부)는
+ // SimpleCardValue(BasePower + Modifier[]) 선언만으로 처리.
+ //
+ // *** 버그 수정 ***
+ // 기존 코드는 "몬스터인가"(CardKindTable.IsMonster)로
+ // "Ryzeal 몬스터 존재/총합"을 판정했음. 이제 비Ryzeal 몬스터(핸드트랩 등)가
+ // 추가되면서 이 가정이 깨짐 -> RyzealMonsterTag로 별도 분리.
+ //
+ // *** 데이터 미확정 항목 (TODO, 실제 값으로 교체 필요) ***
+ // 1) CardId.MulcharmyPurulia / Sakitama / TrapHole / SkullMeister / LightningCrash
+ // 실제 카드ID를 몰라서 임의의 음수 placeholder를 넣어뒀음.
+ // 2) CardLevelTable: Sakitama의 "다른 level4가 없을 경우" 조건 판정용.
+ // Ryzeal 몬스터들의 실제 레벨을 몰라서 비어있음 -> 지금은 항상
+ // "다른 level4 없음"으로 평가됨. 실제 레벨 채워야 정확해짐.
+ // 3) GameState.XyzExistsAnywhere: 엑시즈 소재 판정 로직 미구현이라
+ // 여전히 외부에서 값을 세팅해줘야 함(Node 카드용).
+ // ============================================================
+
+
+ #region 카드 ID / 태그 정의
+
+ public static class CardId
+ {
+ // --- Ryzeal 코어 ---
+ public const int StarRyzeal = 84433129;
+ public const int IceRyzeal = 8633261;
+ public const int SwordRyzeal = 35844557;
+ public const int NodeRyzeal = 72238166;
+ public const int ExtRyzeal = 34022970;
+ public const int RyzealPlugin = 60394026;
+ public const int RyzealCross = 6798031;
+ public const int RyzealPlasmaHole = 33787730;
+
+ // --- 핸드트랩 ---
+ public const int AshBlossomAndJoyousSpring = 14558127;
+ public const int MaxxC = 23434538;
+ public const int MulcharmyFuwalos = 42141493;
+ public const int MulcharmyPurulia = 84192580;
+ public const int NibiruThePrimalBeing = 27204311;
+ public const int GhostBelle = 73642296; // Ghost Belle & Haunted Mansion
+ public const int InfiniteImpermanence = 10045474;
+ public const int GhostOgreAndSnowRabbit = 59438930; // AshBlossom과 동일값 처리
+ public const int SkullMeister = 67750322;
+
+ // --- 튜터 / 기타 ---
+ public const int SeventhTachyon = 7477101;
+ public const int Bonfire = 85106525;
+ public const int LightningCrash = 89753095;
+ public const int TripleTacticsTalent = 25311006;
+ public const int CrossoutDesignator = 65681983;
+ public const int GravediggersTrapHole = 31548215;
+ public const int PotOfProsperity = 84211599; // etc, 보정없음 80
+ public const int Sakitama = 67972302;
+
+ // --- 엑스트라 덱 (전부 Xyz) ---
+ public const int SuperStarslayerTYPHON = 93039339;
+ public const int MereologicAggregator = 9940036;
+ public const int RyzealDetonator = 34909328;
+ public const int Number104Masquerade = 2061963;
+ public const int ExosisterKarmael = 77675029;
+ public const int RyzealDuoDrive = 7511613;
+ public const int DarkRebellionXyzDragon = 90091224;
+ public const int EclipseTwins = 45852939;
+ public const int FullArmoredUtopicRayLancer = 1269512;
+ public const int TornadoDragon = 6983839;
+ public const int EvilswarmExcitonKnight = 46772449;
+ public const int TraptrixRafflesia = 6511113;
+ }
+
+ public enum CardKind { Monster, Spell }
+
+ public static class CardKindTable
+ {
+ public static readonly Dictionary Kind = new Dictionary
+ {
+ // Ryzeal 코어
+ { CardId.StarRyzeal, CardKind.Monster },
+ { CardId.IceRyzeal, CardKind.Monster },
+ { CardId.SwordRyzeal, CardKind.Monster },
+ { CardId.NodeRyzeal, CardKind.Monster },
+ { CardId.ExtRyzeal, CardKind.Monster },
+ { CardId.RyzealPlugin, CardKind.Spell },
+ { CardId.RyzealCross, CardKind.Spell },
+ { CardId.RyzealPlasmaHole, CardKind.Spell },
+
+ // 핸드트랩
+ { CardId.AshBlossomAndJoyousSpring, CardKind.Monster },
+ { CardId.MaxxC, CardKind.Monster },
+ { CardId.MulcharmyFuwalos, CardKind.Monster },
+ { CardId.MulcharmyPurulia, CardKind.Monster },
+ { CardId.NibiruThePrimalBeing, CardKind.Monster },
+ { CardId.GhostBelle, CardKind.Monster },
+ { CardId.GhostOgreAndSnowRabbit, CardKind.Monster },
+ { CardId.SkullMeister, CardKind.Monster },
+ { CardId.InfiniteImpermanence, CardKind.Spell }, // 함정
+
+ // 튜터/기타
+ { CardId.SeventhTachyon, CardKind.Spell },
+ { CardId.PotOfProsperity, CardKind.Spell },
+ { CardId.Bonfire, CardKind.Spell },
+ { CardId.LightningCrash, CardKind.Spell },
+ { CardId.Sakitama, CardKind.Monster },
+ { CardId.GravediggersTrapHole, CardKind.Spell },
+ { CardId.TripleTacticsTalent, CardKind.Spell },
+ { CardId.CrossoutDesignator, CardKind.Spell },
+
+ // 엑스트라 덱 (전부 Xyz 몬스터)
+ { CardId.SuperStarslayerTYPHON, CardKind.Monster },
+ { CardId.MereologicAggregator, CardKind.Monster },
+ { CardId.RyzealDetonator, CardKind.Monster },
+ { CardId.Number104Masquerade, CardKind.Monster },
+ { CardId.ExosisterKarmael, CardKind.Monster },
+ { CardId.RyzealDuoDrive, CardKind.Monster },
+ { CardId.DarkRebellionXyzDragon, CardKind.Monster },
+ { CardId.EclipseTwins, CardKind.Monster },
+ { CardId.FullArmoredUtopicRayLancer, CardKind.Monster },
+ { CardId.TornadoDragon, CardKind.Monster },
+ { CardId.EvilswarmExcitonKnight, CardKind.Monster },
+ { CardId.TraptrixRafflesia, CardKind.Monster },
+ };
+
+ public static bool IsMonster(int cardId)
+ {
+ CardKind k;
+ return Kind.TryGetValue(cardId, out k) && k == CardKind.Monster;
+ }
+ }
+
+ // "Ryzeal 몬스터 파워 총합" 계산에 실제로 들어가는 카드만 담는 태그.
+ // (버그수정 지점: CardKindTable.IsMonster와 절대 혼용하지 말 것)
+ public static class RyzealMonsterTag
+ {
+ public static readonly HashSet Set = new HashSet
+ {
+ CardId.StarRyzeal, CardId.IceRyzeal, CardId.SwordRyzeal,
+ CardId.NodeRyzeal, CardId.ExtRyzeal,
+ };
+
+ public static bool IsRyzealMonster(int cardId) => Set.Contains(cardId);
+ }
+
+ // "hand에 Ryzeal spell/trap 카드가 있을 경우" (Seventh Tachyon 조건용)
+ public static class RyzealSpellTrapTag
+ {
+ public static readonly HashSet Set = new HashSet
+ {
+ CardId.RyzealPlugin, CardId.RyzealCross, CardId.RyzealPlasmaHole,
+ };
+
+ public static bool IsRyzealSpellTrap(int cardId) => Set.Contains(cardId);
+ }
+
+ // 엑스트라덱 Xyz 카드 전체 (Node의 "XYZ 몬스터 존재" 판정 자동화용)
+ public static class ExtraDeckXyzTag
+ {
+ public static readonly HashSet Set = new HashSet
+ {
+ CardId.SuperStarslayerTYPHON, CardId.MereologicAggregator, CardId.RyzealDetonator,
+ CardId.Number104Masquerade, CardId.ExosisterKarmael, CardId.RyzealDuoDrive,
+ CardId.DarkRebellionXyzDragon, CardId.EclipseTwins, CardId.FullArmoredUtopicRayLancer,
+ CardId.TornadoDragon, CardId.EvilswarmExcitonKnight, CardId.TraptrixRafflesia,
+ };
+
+ public static bool IsXyz(int cardId) => Set.Contains(cardId);
+ }
+
+ // Sakitama "다른 level4" 조건 등에 사용. 실제 레벨 데이터 반영됨.
+ public static class CardLevelTable
+ {
+ public static readonly Dictionary Level = new Dictionary
+ {
+ { CardId.NibiruThePrimalBeing, 11 },
+ { CardId.StarRyzeal, 4 },
+ { CardId.IceRyzeal, 4 },
+ { CardId.SwordRyzeal, 4 },
+ { CardId.NodeRyzeal, 4 },
+ { CardId.ExtRyzeal, 4 },
+ { CardId.MulcharmyFuwalos, 4 },
+ { CardId.MulcharmyPurulia, 4 },
+ { CardId.Sakitama, 4 },
+ { CardId.SkullMeister, 4 },
+ { CardId.AshBlossomAndJoyousSpring, 3 },
+ { CardId.GhostOgreAndSnowRabbit, 3 },
+ { CardId.GhostBelle, 3 },
+ { CardId.MaxxC, 2 },
+ };
+
+ public static int GetLevel(int cardId)
+ {
+ int lv;
+ return Level.TryGetValue(cardId, out lv) ? lv : -1; // -1 = 레벨 미확인 (몬스터가 아니거나 미등록)
+ }
+ }
+
+ #endregion
+
+
+ #region GameState
+
+ public enum Zone { Hand, Field, Grave, Banished }
+
+ public class GameState
+ {
+ public Dictionary> Zones = new Dictionary>
+ {
+ { Zone.Hand, new List() },
+ { Zone.Field, new List() },
+ { Zone.Grave, new List() },
+ { Zone.Banished, new List() },
+ };
+
+ public bool NormalSummonUsed = false;
+ public bool IsFirstPlayer = true;
+ public int Turn = 1;
+
+ public bool HasXyzMonsterInZones(params Zone[] zones)
+ {
+ return zones.SelectMany(z => Zones[z]).Any(ExtraDeckXyzTag.IsXyz);
+ }
+
+ public bool ExistsInZone(int cardId, params Zone[] zones)
+ {
+ return zones.Any(z => Zones[z].Contains(cardId));
+ }
+
+ public int CountInZones(int cardId, params Zone[] zones)
+ {
+ return zones.Sum(z => Zones[z].Count(id => id == cardId));
+ }
+
+ public IEnumerable RyzealMonstersInZonesExcluding(int excludeCardId, params Zone[] zones)
+ {
+ return zones.SelectMany(z => Zones[z])
+ .Where(id => id != excludeCardId && RyzealMonsterTag.IsRyzealMonster(id));
+ }
+
+ // "hand에 중복 카드" = Junk Resource. 카드 하나라도 손에 2장 이상이면 그 카드는 junk.
+ public bool IsJunkResourceInHand(int cardId)
+ {
+ return Zones[Zone.Hand].Count(id => id == cardId) >= 2;
+ }
+
+ public bool HasAnyJunkResourceInHand()
+ {
+ return Zones[Zone.Hand].GroupBy(id => id).Any(g => g.Count() >= 2);
+ }
+
+ public bool HasRyzealSpellTrapInHand()
+ {
+ return Zones[Zone.Hand].Any(RyzealSpellTrapTag.IsRyzealSpellTrap);
+ }
+
+ public bool HasOtherLevelInZone(int level, int excludeCardId, params Zone[] zones)
+ {
+ return zones.SelectMany(z => Zones[z])
+ .Any(id => id != excludeCardId && CardLevelTable.GetLevel(id) == level);
+ }
+ }
+
+ #endregion
+
+
+ #region 선언형 카드 가치 (Tier 0: 다른 카드 파워를 참조하지 않는 카드 전용)
+
+ public enum ModifierType { Add, Multiply }
+
+ public class ValueModifier
+ {
+ public Func Condition; // 순수 GameState 기반 판정만 허용 (다른 카드 파워 참조 금지)
+ public ModifierType Type;
+ public double Value;
+ public string Description; // 디버깅/로그용
+
+ public ValueModifier(Func condition, ModifierType type, double value, string description)
+ {
+ Condition = condition;
+ Type = type;
+ Value = value;
+ Description = description;
+ }
+ }
+
+ public class SimpleCardValue
+ {
+ public int CardId;
+ public double BasePower;
+ public List Modifiers = new List();
+ }
+
+ public static class SimpleCardEvaluator
+ {
+ // 계산 순서 고정: Base + 모든 Add 모디파이어 → 그 결과에 모든 Multiply 모디파이어 순차 적용
+ public static double Evaluate(SimpleCardValue cv, GameState s)
+ {
+ double power = cv.BasePower;
+
+ foreach (var m in cv.Modifiers.Where(m => m.Type == ModifierType.Add))
+ if (m.Condition(s))
+ power += m.Value;
+
+ foreach (var m in cv.Modifiers.Where(m => m.Type == ModifierType.Multiply))
+ if (m.Condition(s))
+ power *= m.Value;
+
+ return power;
+ }
+ }
+
+ #endregion
+
+
+ #region Tier 0 카드 데이터 선언
+
+ public static class SimpleCardTable
+ {
+ public static readonly List All = new List
+ {
+ // ---------------- Ryzeal 코어 (Star/Plugin/Cross 제외) ----------------
+ new SimpleCardValue
+ {
+ CardId = CardId.IceRyzeal, BasePower = 80,
+ Modifiers = {
+ new ValueModifier(s => s.NormalSummonUsed, ModifierType.Add, -20, "일반소환권 사용됨"),
+ }
+ },
+ new SimpleCardValue
+ {
+ CardId = CardId.SwordRyzeal, BasePower = 80,
+ Modifiers = {
+ new ValueModifier(
+ s => !s.RyzealMonstersInZonesExcluding(CardId.SwordRyzeal, Zone.Field).Any()
+ && !s.RyzealMonstersInZonesExcluding(CardId.SwordRyzeal, Zone.Grave).Any(),
+ ModifierType.Add, -20, "필드+묘지에 Ryzeal 몬스터 없음"),
+ }
+ },
+ new SimpleCardValue { CardId = CardId.ExtRyzeal, BasePower = 100 },
+ new SimpleCardValue
+ {
+ CardId = CardId.NodeRyzeal, BasePower = 30,
+ Modifiers = {
+ new ValueModifier(s => !s.HasXyzMonsterInZones(Zone.Field, Zone.Grave), ModifierType.Add, -20, "필드+묘지에 XYZ 없음"),
+ new ValueModifier(s => !s.HasAnyJunkResourceInHand(), ModifierType.Add, -10, "Junk Resource 없음"),
+ }
+ },
+ new SimpleCardValue
+ {
+ CardId = CardId.RyzealPlasmaHole, BasePower = 20,
+ Modifiers = {
+ new ValueModifier(s => s.IsFirstPlayer, ModifierType.Add, 10, "선공"),
+ new ValueModifier(s => !s.IsFirstPlayer, ModifierType.Add, -10, "후공"),
+ }
+ },
+
+ // ---------------- 핸드트랩 ----------------
+ new SimpleCardValue { CardId = CardId.AshBlossomAndJoyousSpring, BasePower = 80 },
+ new SimpleCardValue { CardId = CardId.GhostOgreAndSnowRabbit, BasePower = 80 }, // Ash Blossom과 동일값/보정
+ new SimpleCardValue { CardId = CardId.MaxxC, BasePower = 120 },
+ new SimpleCardValue
+ {
+ CardId = CardId.MulcharmyFuwalos, BasePower = 100,
+ Modifiers = {
+ new ValueModifier(s => s.Turn > 1, ModifierType.Add, -60, "1턴 이후"),
+ }
+ },
+ new SimpleCardValue
+ {
+ CardId = CardId.MulcharmyPurulia, BasePower = 100,
+ Modifiers = {
+ new ValueModifier(s => s.Turn > 1, ModifierType.Add, -60, "1턴 이후"),
+ }
+ },
+ new SimpleCardValue { CardId = CardId.NibiruThePrimalBeing, BasePower = 60 },
+ new SimpleCardValue { CardId = CardId.GhostBelle, BasePower = 70 },
+ new SimpleCardValue { CardId = CardId.InfiniteImpermanence, BasePower = 60 },
+ new SimpleCardValue { CardId = CardId.SkullMeister, BasePower = 60 },
+
+ // ---------------- 튜터 ----------------
+ new SimpleCardValue
+ {
+ CardId = CardId.SeventhTachyon, BasePower = 80,
+ Modifiers = {
+ new ValueModifier(s => !s.HasAnyJunkResourceInHand(), ModifierType.Add, -30, "hand에 Junk Resource 없음"),
+ new ValueModifier(s => s.HasRyzealSpellTrapInHand(), ModifierType.Add, 20, "hand에 Ryzeal 스펠/트랩 있음"),
+ }
+ },
+ new SimpleCardValue { CardId = CardId.Bonfire, BasePower = 70 },
+ new SimpleCardValue { CardId = CardId.LightningCrash, BasePower = 70 },
+
+ // ---------------- 기타 ----------------
+ new SimpleCardValue
+ {
+ CardId = CardId.Sakitama, BasePower = 60,
+ Modifiers = {
+ new ValueModifier(
+ s => !s.HasOtherLevelInZone(4, CardId.Sakitama, Zone.Hand),
+ ModifierType.Add, -40, "패에 다른 level4 없음"),
+ }
+ },
+ new SimpleCardValue
+ {
+ // "자동 junk resource 보정" = 별도 처리 아님, 전 카드 공통 Junk Resource 로직이
+ // 이 카드에도 동일하게 적용된다는 의미로 해석 (EvaluateAll의 전역 후처리 단계에서 자동 반영)
+ CardId = CardId.GravediggersTrapHole, BasePower = 10,
+ Modifiers = {
+ new ValueModifier(s => !s.IsFirstPlayer, ModifierType.Add, -10, "후공"),
+ }
+ },
+ new SimpleCardValue { CardId = CardId.TripleTacticsTalent, BasePower = 40 },
+ new SimpleCardValue { CardId = CardId.CrossoutDesignator, BasePower = 40 },
+ new SimpleCardValue { CardId = CardId.PotOfProsperity, BasePower = 80 },
+ };
+
+ public static readonly Dictionary ById =
+ All.ToDictionary(cv => cv.CardId, cv => cv);
+ }
+
+ #endregion
+
+
+ #region Tier 1 / Tier 2 (다른 카드 파워를 참조하는 카드 - 전용 함수 유지)
+
+ public static class TieredCardEvaluator
+ {
+ private static double GetOrZero(IDictionary dict, int cardId)
+ {
+ double v;
+ return dict.TryGetValue(cardId, out v) ? v : 0;
+ }
+
+ // Tier 1: Star - 다른 "몬스터"(Tier 0 결과)를 참조
+ public static double EvaluateStar(GameState s, IDictionary tier0Powers)
+ {
+ double power = 40;
+
+ if (s.ExistsInZone(CardId.RyzealPlugin, Zone.Hand)) power -= 10;
+ if (s.ExistsInZone(CardId.RyzealPlugin, Zone.Field)) power -= 10;
+ if (s.ExistsInZone(CardId.RyzealPlugin, Zone.Grave)) power -= 10;
+ if (s.ExistsInZone(CardId.RyzealPlugin, Zone.Banished)) power -= 10;
+
+ if (s.ExistsInZone(CardId.RyzealCross, Zone.Hand)) power -= 20;
+ if (s.ExistsInZone(CardId.RyzealCross, Zone.Field)) power -= 20;
+ if (s.ExistsInZone(CardId.RyzealCross, Zone.Grave)) power -= 20;
+
+ if (s.ExistsInZone(CardId.RyzealPlasmaHole, Zone.Hand)) power -= 10;
+ if (s.ExistsInZone(CardId.RyzealPlasmaHole, Zone.Field)) power -= 10;
+ if (s.ExistsInZone(CardId.RyzealPlasmaHole, Zone.Grave)) power -= 10;
+
+ double otherMonsterPowerSum = s.RyzealMonstersInZonesExcluding(CardId.StarRyzeal, Zone.Hand, Zone.Field)
+ .Sum(id => GetOrZero(tier0Powers, id));
+
+ if (otherMonsterPowerSum <= 50)
+ power -= 30;
+
+ return power;
+ }
+
+ // Tier 2: Plugin/Cross - 몬스터 전체(Tier 0 + Tier 1)를 참조
+ public static double EvaluatePlugin(GameState s, IDictionary allMonsterPowers)
+ {
+ double power = 50;
+
+ double otherRyzealMonsterSum = s.RyzealMonstersInZonesExcluding(CardId.RyzealPlugin, Zone.Hand, Zone.Field)
+ .Sum(id => GetOrZero(allMonsterPowers, id));
+
+ if (otherRyzealMonsterSum <= 60)
+ power -= 20;
+
+ return power;
+ }
+
+ public static double EvaluateCross(GameState s, IDictionary allMonsterPowers)
+ {
+ double power = 60;
+
+ bool hasStrongInHand = s.Zones[Zone.Hand]
+ .Where(id => id != CardId.RyzealCross && RyzealMonsterTag.IsRyzealMonster(id))
+ .Any(id => GetOrZero(allMonsterPowers, id) >= 80);
+
+ bool hasStrongInField = s.Zones[Zone.Field]
+ .Where(RyzealMonsterTag.IsRyzealMonster)
+ .Any(id => GetOrZero(allMonsterPowers, id) >= 80);
+
+ if (!hasStrongInHand && !hasStrongInField)
+ power -= 20;
+
+ int graveRyzealCount = s.Zones[Zone.Grave].Count(RyzealMonsterTag.IsRyzealMonster);
+ if (graveRyzealCount >= 2)
+ power += 10;
+
+ return power;
+ }
+ }
+
+ #endregion
+
+
+ #region 전체 오케스트레이션
+
+ public static class CardValueEngine
+ {
+ public static Dictionary EvaluateAll(GameState s)
+ {
+ // Tier 0: 선언형 테이블 전부 일괄 계산
+ var tier0 = new Dictionary();
+ foreach (var cv in SimpleCardTable.All)
+ tier0[cv.CardId] = SimpleCardEvaluator.Evaluate(cv, s);
+
+ // Tier 1: Star (Tier 0 결과 참조)
+ var tier1 = new Dictionary(tier0);
+ tier1[CardId.StarRyzeal] = TieredCardEvaluator.EvaluateStar(s, tier0);
+
+ // Tier 2: Plugin/Cross (Tier 0+1 결과 참조)
+ var result = new Dictionary(tier1);
+ result[CardId.RyzealPlugin] = TieredCardEvaluator.EvaluatePlugin(s, tier1);
+ result[CardId.RyzealCross] = TieredCardEvaluator.EvaluateCross(s, tier1);
+
+ // 전역 후처리: Junk Resource(손패 중복) -> 모든 카드에 균일하게 ×0.75
+ // (Tier 0/1/2 내부 계산에는 영향 없도록 반드시 마지막에 적용)
+ var finalKeys = result.Keys.ToList();
+ foreach (var cardId in finalKeys)
+ if (s.IsJunkResourceInHand(cardId))
+ result[cardId] *= 0.75;
+
+ return result;
+ }
+ }
+
+ #endregion
+
+
+ #region 유닛 테스트
+
+ public static class CardValueEngineTests
+ {
+ private static int _pass = 0;
+ private static int _fail = 0;
+
+ private static void AssertEqual(double expected, double actual, string testName)
+ {
+ if (Math.Abs(expected - actual) < 0.0001)
+ {
+ _pass++;
+ Console.WriteLine("[PASS] " + testName + " (expected=" + expected + ", actual=" + actual + ")");
+ }
+ else
+ {
+ _fail++;
+ Console.WriteLine("[FAIL] " + testName + " (expected=" + expected + ", actual=" + actual + ")");
+ }
+ }
+
+ // ---- 회귀 테스트 (지난 4장 프로토타입에서 그대로 유지돼야 함) ----
+
+ public static void Test_Regression_Cross_StrongHandAndGraveResource()
+ {
+ var s = new GameState();
+ s.Zones[Zone.Hand].AddRange(new[] { CardId.IceRyzeal, CardId.ExtRyzeal });
+ s.Zones[Zone.Grave].AddRange(new[] { CardId.SwordRyzeal, CardId.NodeRyzeal, CardId.ExtRyzeal });
+
+ var powers = CardValueEngine.EvaluateAll(s);
+ AssertEqual(70, powers[CardId.RyzealCross], "회귀_Cross_강한패+묘지자원");
+ }
+
+ public static void Test_Regression_Star_WithNodeOnlyDropsTo10()
+ {
+ var s = new GameState();
+ s.Zones[Zone.Hand].Add(CardId.StarRyzeal);
+ s.Zones[Zone.Field].Add(CardId.NodeRyzeal);
+
+ var powers = CardValueEngine.EvaluateAll(s);
+ AssertEqual(10, powers[CardId.StarRyzeal], "회귀_Star_Node뿐일때");
+ }
+
+ // ---- 버그 수정 검증: 비Ryzeal 몬스터가 Ryzeal 총합에 안 끼는지 ----
+
+ public static void Test_BugFix_NonRyzealMonsterNotCountedInStarSum()
+ {
+ var s = new GameState();
+ s.Zones[Zone.Hand].Add(CardId.StarRyzeal);
+ s.Zones[Zone.Hand].Add(CardId.AshBlossomAndJoyousSpring); // 몬스터지만 Ryzeal 아님
+
+ var powers = CardValueEngine.EvaluateAll(s);
+ // Ash Blossom(80)이 총합에 안 잡히므로 "Ryzeal 파워 총합 0 <= 50" -> -30 그대로 적용돼야 함
+ AssertEqual(10, powers[CardId.StarRyzeal], "버그수정_비Ryzeal몬스터_Star합산제외");
+ }
+
+ public static void Test_BugFix_NonRyzealMonsterInGraveNotBlockingSwordCondition()
+ {
+ var s = new GameState();
+ // 묘지에 Ash Blossom만 있고 실제 Ryzeal 몬스터는 필드/묘지 어디에도 없음
+ s.Zones[Zone.Grave].Add(CardId.AshBlossomAndJoyousSpring);
+
+ var powers = CardValueEngine.EvaluateAll(s);
+ // "필드+묘지에 Ryzeal 몬스터 없음"이 참이어야 하므로 -20 적용 -> 80-20=60
+ AssertEqual(60, powers[CardId.SwordRyzeal], "버그수정_비Ryzeal몬스터_Sword조건오염안됨");
+ }
+
+ // ---- 신규 카드 카테고리 검증 ----
+
+ public static void Test_SimpleHandtrap_NoModifier()
+ {
+ var s = new GameState();
+ var powers = CardValueEngine.EvaluateAll(s);
+ AssertEqual(80, powers[CardId.AshBlossomAndJoyousSpring], "핸드트랩_AshBlossom_기본값");
+ AssertEqual(80, powers[CardId.GhostOgreAndSnowRabbit], "핸드트랩_GhostOgre_AshBlossom과동일값");
+ AssertEqual(120, powers[CardId.MaxxC], "핸드트랩_MaxxC_기본값");
+ AssertEqual(80, powers[CardId.PotOfProsperity], "기타_PotOfProsperity_기본값");
+ }
+
+ public static void Test_Mulcharmy_TurnCondition()
+ {
+ var sTurn1 = new GameState { Turn = 1 };
+ var sTurn2 = new GameState { Turn = 2 };
+
+ var p1 = CardValueEngine.EvaluateAll(sTurn1);
+ var p2 = CardValueEngine.EvaluateAll(sTurn2);
+
+ AssertEqual(100, p1[CardId.MulcharmyFuwalos], "Mulcharmy_1턴차_보정없음");
+ AssertEqual(40, p2[CardId.MulcharmyFuwalos], "Mulcharmy_2턴차_100-60");
+ }
+
+ public static void Test_SeventhTachyon_CombinedModifiers()
+ {
+ var s = new GameState();
+ s.Zones[Zone.Hand].Add(CardId.RyzealCross); // Ryzeal 스펠/트랩 보유 -> +20
+ // Junk Resource는 없음 (중복카드 없음) -> "없을 경우" 조건 True -> -30
+ var powers = CardValueEngine.EvaluateAll(s);
+ // 80 - 30(junk없음) + 20(ryzeal s/t 있음) = 70
+ AssertEqual(70, powers[CardId.SeventhTachyon], "SeventhTachyon_복합조건_70");
+ }
+
+ public static void Test_JunkResourceMultiplier_AppliedGlobally()
+ {
+ var s = new GameState();
+ s.Zones[Zone.Hand].AddRange(new[] { CardId.Bonfire, CardId.Bonfire }); // 중복 -> Junk Resource
+ var powers = CardValueEngine.EvaluateAll(s);
+ AssertEqual(70 * 0.75, powers[CardId.Bonfire], "JunkResource_중복카드_0.75배");
+ }
+
+ public static void Test_TrapHole_SecondPlayerAndJunk()
+ {
+ var s = new GameState { IsFirstPlayer = false };
+ s.Zones[Zone.Hand].AddRange(new[] { CardId.GravediggersTrapHole, CardId.GravediggersTrapHole });
+ var powers = CardValueEngine.EvaluateAll(s);
+ // (10 - 10후공) * 0.75중복 = 0
+ AssertEqual(0, powers[CardId.GravediggersTrapHole], "TrapHole_후공+중복_복합");
+ }
+
+ public static void Test_Node_AutoXyzDetectionFromExtraDeckList()
+ {
+ var sNoXyz = new GameState();
+ var sWithXyz = new GameState();
+ sWithXyz.Zones[Zone.Grave].Add(CardId.TraptrixRafflesia); // 엑스트라덱 목록에 있는 실제 Xyz 카드
+
+ var pNoXyz = CardValueEngine.EvaluateAll(sNoXyz);
+ var pWithXyz = CardValueEngine.EvaluateAll(sWithXyz);
+
+ AssertEqual(0, pNoXyz[CardId.NodeRyzeal], "Node_XYZ없음_Junk없음_30-20-10");
+ AssertEqual(20, pWithXyz[CardId.NodeRyzeal], "Node_묘지Xyz자동감지_30-10");
+ }
+
+ public static void Test_Sakitama_LevelConditionNowWorks()
+ {
+ var sAlone = new GameState();
+ sAlone.Zones[Zone.Hand].Add(CardId.Sakitama);
+
+ var sWithOtherLevel4 = new GameState();
+ sWithOtherLevel4.Zones[Zone.Hand].AddRange(new[] { CardId.Sakitama, CardId.IceRyzeal });
+
+ var pAlone = CardValueEngine.EvaluateAll(sAlone);
+ var pWith = CardValueEngine.EvaluateAll(sWithOtherLevel4);
+
+ AssertEqual(20, pAlone[CardId.Sakitama], "Sakitama_혼자있음_60-40");
+ AssertEqual(60, pWith[CardId.Sakitama], "Sakitama_다른lv4있음_보정없음");
+ }
+
+ public static void RunAll()
+ {
+ _pass = 0; _fail = 0;
+
+ Test_Regression_Cross_StrongHandAndGraveResource();
+ Test_Regression_Star_WithNodeOnlyDropsTo10();
+ Test_BugFix_NonRyzealMonsterNotCountedInStarSum();
+ Test_BugFix_NonRyzealMonsterInGraveNotBlockingSwordCondition();
+ Test_SimpleHandtrap_NoModifier();
+ Test_Mulcharmy_TurnCondition();
+ Test_SeventhTachyon_CombinedModifiers();
+ Test_JunkResourceMultiplier_AppliedGlobally();
+ Test_TrapHole_SecondPlayerAndJunk();
+ Test_Node_AutoXyzDetectionFromExtraDeckList();
+ Test_Sakitama_LevelConditionNowWorks();
+
+ Console.WriteLine("");
+ Console.WriteLine("결과: " + _pass + " 통과 / " + _fail + " 실패");
+ }
+ }
+
+ #endregion
+
+
+
+}
diff --git a/Game/AI/Decks/DuelDecisionLogger.cs b/Game/AI/Decks/DuelDecisionLogger.cs
new file mode 100644
index 000000000..882e8bf78
--- /dev/null
+++ b/Game/AI/Decks/DuelDecisionLogger.cs
@@ -0,0 +1,156 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace RyzealAI.Prototype
+{
+ // 외부 JSON 라이브러리 없이 JSONL을 남긴다. 한 줄은 한 번의 Main Phase 의사결정이다.
+ public sealed class DuelDecisionLogger
+ {
+ private string _path;
+ private readonly string _directory;
+ private readonly object _gate = new object();
+ private string _duelId = "unstarted-" + Guid.NewGuid().ToString("N");
+ private int _decisionNumber;
+ private string _decisionId;
+
+ public void BeginDuel()
+ {
+ lock (_gate)
+ {
+ _duelId = Guid.NewGuid().ToString("N");
+ _decisionNumber = 0;
+ _decisionId = null;
+ SelectNewLogPath();
+ }
+ }
+ public void BeginDecision()
+ {
+ _decisionNumber++;
+ _decisionId = _duelId + ":" + _decisionNumber.ToString(CultureInfo.InvariantCulture);
+ }
+ private string CorrelationJson(bool associateDecision)
+ {
+ return Field("duelId", _duelId) + "," +
+ "\"decisionId\":" + (associateDecision && _decisionId != null ? "\"" + Escape(_decisionId) + "\"" : "null") + "," +
+ Field("timestampUtc", DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture));
+ }
+
+
+ public DuelDecisionLogger(string path)
+ {
+ // Keep the existing constructor call; only its directory is used.
+ _directory = Path.GetDirectoryName(path);
+ if (String.IsNullOrEmpty(_directory)) _directory = ".";
+ SelectNewLogPath();
+ string directory = _directory;
+ if (!String.IsNullOrEmpty(directory))
+ {
+ try { Directory.CreateDirectory(directory); }
+ catch (IOException ex) { Console.Error.WriteLine("Ryzeal log directory failed: " + ex.Message); }
+ catch (UnauthorizedAccessException ex) { Console.Error.WriteLine("Ryzeal log directory access failed: " + ex.Message); }
+ }
+ }
+
+ public string LogPath { get { return _path; } }
+
+ private void SelectNewLogPath()
+ {
+ // Local machine time; UTC timestamps inside events stay unchanged.
+ // Full GUID prevents concurrent duel files sharing the same timestamp.
+ string fileName = DateTime.Now.ToString("yyyyMMdd_HHmmss_fff", CultureInfo.InvariantCulture)
+ + "_" + _duelId + ".jsonl";
+ _path = Path.Combine(_directory, fileName);
+ }
+
+ public void Write(DecisionTrace trace)
+ {
+ lock (_gate)
+ {
+ try { File.AppendAllText(_path, ToJson(trace) + Environment.NewLine, Encoding.UTF8); }
+ catch (IOException ex) { Console.Error.WriteLine("Ryzeal log write failed: " + ex.Message); }
+ catch (UnauthorizedAccessException ex) { Console.Error.WriteLine("Ryzeal log access failed: " + ex.Message); }
+ }
+ }
+
+ public void WriteLegacyAction(int turn, string phase, string kind, int cardId, long description)
+ {
+ string json = "{" + Field("eventType", "legacyMainPhaseSelection") + "," + CorrelationJson(true) + "," +
+ Field("turn", turn) + "," + Field("phase", phase) + "," +
+ Field("kind", kind) + "," + Field("cardId", cardId) + "," +
+ Field("activationDescription", description.ToString(CultureInfo.InvariantCulture)) + "}";
+ lock (_gate)
+ {
+ try { File.AppendAllText(_path, json + Environment.NewLine, Encoding.UTF8); }
+ catch (IOException ex) { Console.Error.WriteLine("Ryzeal legacy log failed: " + ex.Message); }
+ catch (UnauthorizedAccessException ex) { Console.Error.WriteLine("Ryzeal legacy log access failed: " + ex.Message); }
+ }
+ }
+
+ public void WriteSelection(string context, int turn, IEnumerable offered, int selected)
+ {
+ string json = "{" + Field("eventType", "cardSelection") + "," + CorrelationJson(false) + "," +
+ Field("context", context) + "," + Field("turn", turn) + "," +
+ IntArray("offeredCardIds", offered) + "," + Field("selectedCardId", selected) + "}";
+ lock (_gate)
+ {
+ try { File.AppendAllText(_path, json + Environment.NewLine, Encoding.UTF8); }
+ catch (IOException ex) { Console.Error.WriteLine("Ryzeal selection log failed: " + ex.Message); }
+ catch (UnauthorizedAccessException ex) { Console.Error.WriteLine("Ryzeal selection log access failed: " + ex.Message); }
+ }
+ }
+
+ private string ToJson(DecisionTrace t)
+ {
+ return "{" +
+ Field("eventType", "mainPhaseDecision") + "," + CorrelationJson(true) + "," +
+ Field("turn", t.Turn) + "," +
+ Field("phase", t.Phase) + "," +
+ Field("turnPlayer", t.TurnPlayer) + "," +
+ Field("isFirst", t.IsFirst) + "," +
+ Field("normalSummonUsed", t.NormalSummonUsed) + "," +
+ "\"self\":" + ZoneJson(t.Self) + "," +
+ "\"opponent\":" + ZoneJson(t.Opponent) + "," +
+ "\"legalActions\":" + LegalJson(t.LegalActions) + "," +
+ "\"policyCandidates\":" + CandidateJson(t.PolicyCandidates) + "," +
+ "\"selected\":" + SelectedJson(t.Selected) + "," +
+ Field("selectionResult", t.SelectionResult) +
+ "}";
+ }
+
+ private static string ZoneJson(FieldTrace f)
+ {
+ return "{" + IntArray("hand", f.Hand) + "," + IntArray("monsters", f.Monsters) + "," +
+ IntArray("spells", f.Spells) + "," + IntArray("graveyard", f.Graveyard) + "," +
+ IntArray("banished", f.Banished) + "," + IntArray("extra", f.Extra) + "}";
+ }
+ private static string LegalJson(IEnumerable xs) =>
+ "[" + String.Join(",", xs.Select(x => "{" + Field("kind", x.Kind) + "," + Field("cardId", x.CardId) + "," + Field("activationDescription", x.ActivationDescription) + "," + Field("actionIndex", x.ActionIndex) + "}")) + "]";
+ private static string CandidateJson(IEnumerable xs) =>
+ "[" + String.Join(",", xs.Select(x => "{" + Field("kind", x.Kind) + "," + Field("cardId", x.CardId) + "," + Field("baselineScore", x.BaselineScore) + "," + Field("label", x.Label) + "," + Field("goalTag", x.GoalTag) + "," + Field("selectionPlan", x.SelectionPlan) + "}")) + "]";
+ private static string SelectedJson(CandidateTrace x) => x == null ? "null" :
+ "{" + Field("kind", x.Kind) + "," + Field("cardId", x.CardId) + "," + Field("baselineScore", x.BaselineScore) + "," + Field("label", x.Label) + "," + Field("goalTag", x.GoalTag) + "," + Field("selectionPlan", x.SelectionPlan) + "}";
+ private static string IntArray(string key, IEnumerable xs) => "\"" + key + "\":[" + String.Join(",", xs) + "]";
+ private static string Field(string key, string value) => "\"" + key + "\":\"" + Escape(value ?? "") + "\"";
+ private static string Field(string key, int value) => "\"" + key + "\":" + value.ToString(CultureInfo.InvariantCulture);
+ private static string Field(string key, long value) => "\"" + key + "\":" + value.ToString(CultureInfo.InvariantCulture);
+ private static string Field(string key, double value) => "\"" + key + "\":" + value.ToString("R", CultureInfo.InvariantCulture);
+ private static string Field(string key, bool value) => "\"" + key + "\":" + (value ? "true" : "false");
+ private static string Escape(string s) => s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "\\r").Replace("\n", "\\n");
+ }
+
+ public sealed class DecisionTrace
+ {
+ public int Turn; public string Phase; public int TurnPlayer; public bool IsFirst; public bool NormalSummonUsed;
+ public FieldTrace Self = new FieldTrace(); public FieldTrace Opponent = new FieldTrace();
+ public List LegalActions = new List();
+ public List PolicyCandidates = new List();
+ public CandidateTrace Selected; public string SelectionResult;
+ }
+ public sealed class FieldTrace { public List Hand = new List(); public List Monsters = new List(); public List Spells = new List(); public List Graveyard = new List(); public List Banished = new List(); public List Extra = new List(); }
+ public sealed class LegalActionTrace { public string Kind; public int CardId; public long ActivationDescription; public int ActionIndex; }
+ public sealed class CandidateTrace { public string Kind; public int CardId; public double BaselineScore; public string Label; public string GoalTag; public string SelectionPlan; }
+}
diff --git a/Game/AI/Decks/GameStateAdapter.cs b/Game/AI/Decks/GameStateAdapter.cs
new file mode 100644
index 000000000..7bee56bb6
--- /dev/null
+++ b/Game/AI/Decks/GameStateAdapter.cs
@@ -0,0 +1,44 @@
+using System.Collections.Generic;
+using System.Linq;
+using WindBot.Game;
+using RyzealAI.Prototype;
+
+namespace WindBot.Game.AI.Decks
+{
+ // ============================================================
+ // ClientField/Duel(실제 게임 상태) -> GameState(CardValueEngine용 목업) 변환기
+ //
+ // 사용법 (RyzealExecutor 안에서):
+ // var state = GameStateAdapter.ToGameState(Bot, Duel, NormalSummonUsed);
+ // var powers = CardValueEngine.EvaluateAll(state);
+ //
+ // 주의:
+ // - "Zone.Field"는 몬스터존+스펠존을 합친 것. Star/Plugin/Cross 조건문에서
+ // "필드에 존재"가 몬스터/스펠 구분 없이 쓰이므로 이렇게 합쳐야 정확함.
+ // - NormalSummonUsed / EffectUsed(HOPT)류는 엔진이 안 주므로 Executor가
+ // 직접 추적해온 값을 파라미터로 반드시 넘겨야 함 (지난 대화에서 확인된 내용).
+ // ============================================================
+ public static class GameStateAdapter
+ {
+ public static GameState ToGameState(ClientField bot, Duel duel, bool normalSummonUsed)
+ {
+ var state = new GameState();
+
+ state.Zones[Zone.Hand] = bot.Hand.Select(c => c.Id).ToList();
+
+ var fieldIds = new List();
+ fieldIds.AddRange(bot.GetMonsters().Select(c => c.Id));
+ fieldIds.AddRange(bot.GetSpells().Select(c => c.Id));
+ state.Zones[Zone.Field] = fieldIds;
+
+ state.Zones[Zone.Grave] = bot.Graveyard.Select(c => c.Id).ToList();
+ state.Zones[Zone.Banished] = bot.Banished.Select(c => c.Id).ToList();
+
+ state.NormalSummonUsed = normalSummonUsed;
+ state.IsFirstPlayer = duel.IsFirst;
+ state.Turn = duel.Turn;
+
+ return state;
+ }
+ }
+}
diff --git a/Game/AI/Decks/RyzealDeckProfile.cs b/Game/AI/Decks/RyzealDeckProfile.cs
new file mode 100644
index 000000000..bebf9daa2
--- /dev/null
+++ b/Game/AI/Decks/RyzealDeckProfile.cs
@@ -0,0 +1,65 @@
+using System;
+using System.Collections.Generic;
+
+namespace RyzealAI.Prototype
+{
+ // Single source of truth for AI_Ryzeal - 복사본.txt (40 main / 15 extra).
+ // This is deck composition metadata only; the duel engine remains the authority
+ // for current in-duel availability and legal actions.
+ public static class RyzealDeckProfile
+ {
+ public const string Name = "AI_Ryzeal";
+ public const int MainDeckSize = 40;
+ public const int ExtraDeckSize = 15;
+
+ public static readonly Dictionary Main =
+ new Dictionary
+ {
+ { 27204311, 1 }, // Nibiru
+ { 84433129, 1 }, // Star Ryzeal
+ { 8633261, 3 }, // Ice Ryzeal
+ { 67750322, 1 }, // Skull Meister
+ { 35844557, 3 }, // Sword Ryzeal
+ { 72238166, 1 }, // Node Ryzeal
+ { 34022970, 3 }, // Ext Ryzeal
+ { 67972302, 2 }, // Sakitama
+ { 42141493, 3 }, // Mulcharmy Fuwalos
+ { 84192580, 2 }, // Mulcharmy Purulia
+ { 14558127, 2 }, // Ash Blossom
+ { 59438930, 1 }, // Ghost Ogre
+ { 73642296, 1 }, // Ghost Belle
+ { 23434538, 1 }, // Maxx "C"
+ { 7477101, 1 }, // Seventh Tachyon
+ { 25311006, 1 }, // Triple Tactics Talent
+ { 84211599, 1 }, // Pot of Prosperity
+ { 85106525, 1 }, // Bonfire
+ { 89753095, 3 }, // Lightning Crash
+ { 60394026, 1 }, // Ryzeal Plugin
+ { 65681983, 1 }, // Crossout Designator
+ { 6798031, 1 }, // Ryzeal Cross
+ { 10045474, 3 }, // Infinite Impermanence
+ { 31548215, 1 }, // Gravedigger's Trap Hole
+ { 33787730, 1 }, // Ryzeal Plasma Hole
+ };
+
+ public static readonly Dictionary Extra =
+ new Dictionary
+ {
+ { 93039339, 1 }, // Super Starslayer TY-PHON
+ { 9940036, 1 }, // Mereologic Aggregator
+ { 34909328, 3 }, // Ryzeal Detonator
+ { 2061963, 1 }, // Number 104: Masquerade
+ { 77675029, 1 }, // Exosister Karmael
+ { 7511613, 2 }, // Ryzeal Duo Drive
+ { 90091224, 1 }, // Dark Rebellion Xyz Dragon of the Four Heavenly Dragons
+ { 45852939, 1 }, // Eclipse Twins
+ { 1269512, 1 }, // Full Armored Utopic Ray Lancer
+ { 6983839, 1 }, // Tornado Dragon
+ { 46772449, 1 }, // Evilswarm Exciton Knight
+ { 6511113, 1 }, // Traptrix Rafflesia
+ };
+
+ public static bool IsInMain(int cardId) { return Main.ContainsKey(cardId); }
+ public static bool IsInExtra(int cardId) { return Extra.ContainsKey(cardId); }
+ }
+}
diff --git a/Game/AI/Decks/RyzealExecutor.cs b/Game/AI/Decks/RyzealExecutor.cs
index 9a58eb615..29b18efb4 100644
--- a/Game/AI/Decks/RyzealExecutor.cs
+++ b/Game/AI/Decks/RyzealExecutor.cs
@@ -1,4192 +1,1348 @@
-using YGOSharp.OCGWrapper;
+using System;
+using System.Linq;
using YGOSharp.OCGWrapper.Enums;
using System.Collections.Generic;
-using System.Linq;
-using System;
using WindBot;
using WindBot.Game;
using WindBot.Game.AI;
+using RyzealAI.Prototype;
namespace WindBot.Game.AI.Decks
{
- [Deck("Ryzeal", "AI_Ryzeal")]
- public class RyzealExecutor : DefaultExecutor
+ [Deck("Ryzeal", "AI_Ryzeal", "Easy")]
+ class RyzealExecutor : DefaultExecutor, IMainPhaseDecisionObserver
{
+
+ #region Card IDs
+
public class CardId
{
+ // 덱에 사용되는 카드 ID (중복 카드 하나만 선언)
+ public const int NibiruThePrimalBeing = 27204311;
+ public const int StarRyzeal = 84433129;
public const int IceRyzeal = 8633261;
public const int SwordRyzeal = 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 ExtRyzeal = 34022970;
+ public const int MulcharmyFuwalos = 42141493;
+ public const int MulcharmyPurulia = 84192580;
+ public const int AshBlossomAndJoyousSpring = 14558127;
+ public const int GhostOgreAndSnowRabbit = 59438930;
+ public const int GhostBelleAndHauntedMansion = 73642296;
+ public const int MaxxC = 23434538;
public const int SeventhTachyon = 7477101;
+ public const int SeventhAscension = 23153227;
public const int TripleTacticsTalent = 25311006;
- // _CardId.PotOfDesires;
+ public const int PotOfProsperity = 84211599;
public const int Bonfire = 85106525;
- // _CardId.CalledByTheGrave;
- public const int RyzealPlugIn = 60394026;
- // _CardId.CrossoutDesignator;
+ public const int CalledByTheGrave = 24224830;
+ public const int RyzealPlugin = 60394026;
+ public const int CrossoutDesignator = 65681983;
public const int RyzealCross = 6798031;
+ public const int InfiniteImpermanence = 10045474;
+ public const int GravediggersTrapHole = 31548215;
+ public const int RyzealPlasmaHole = 33787730;
- // _CardId.InfiniteImpermanence = 10045474;
-
+ // Extra Deck
+ public const int DivineArsenalAAZEUSSkyThunder = 90448279;
public const int MereologicAggregator = 9940036;
public const int RyzealDetonator = 34909328;
public const int Number104Masquerade = 2061963;
- public const int RyzealDuodrive = 7511613;
- public const int TwinsOfTheEclipse = 45852939;
+ public const int RyzealDuoDrive = 7511613;
+ public const int EclipseTwins = 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 const int EvilswarmExcitonKnight = 46772449;
+ public const int InfernalFlameBanshee = 29423048;
+ public const int TraptrixRafflesia = 6511113;
+ public const int NumberF0UtopicFutureZexal = 41522092;
}
- 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.RyzealDetonator, RyzealDetonatorActivate);
- 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.SwordRyzeal, SwordRyzealSpSummon);
- AddExecutor(ExecutorType.Summon, CardId.IceRyzeal, IceRyzealSummon);
- AddExecutor(ExecutorType.SpSummon, CardId.ExRyzeal, ExRyzealSpSummonLater);
- AddExecutor(ExecutorType.Summon, CardId.SwordRyzeal, SwordRyzealSummon);
- AddExecutor(ExecutorType.SpSummon, CardId.NodeRyzeal, NodeRyzealSpSummon);
- AddExecutor(ExecutorType.Summon, Level4Summon);
+ // 상태 추적 변수들 (필요시 추가)
+ private bool NormalSummonUsed = false;
- AddExecutor(ExecutorType.Activate, CardId.NodeRyzeal, NodeRyzealActivate);
- AddExecutor(ExecutorType.Activate, CardId.RyzealPlugIn, RyzealPlugInActivate);
- AddExecutor(ExecutorType.SpSummon, CardId.IceRyzeal, IceRyzealSpSummon);
+ // HOPT(카드별 "이 효과는 턴에 1번" 제약) 추적.
+ // *** 중요: 정정된 설계 ***
+ // Ryzeal 몬스터들은 실제로 카드 하나당 "룰 특수소환 효과(체인 안 씀)"와
+ // "발동형 효과(서치 등)"라는 서로 독립적인 턴당1번 제약을 두 개씩 갖고 있다.
+ // 한 쪽 효과가 이번 턴 이미 쓰였어도 다른 쪽 효과는 여전히 쓸 수 있어야 하므로
+ // (예: 2장째 Ice를 룰 특수소환해서 엑시즈 소재로 쓰는 플레이), 카드ID 하나에
+ // 플래그 하나로 묶으면 안 되고 효과종류별로 별도 추적해야 함.
+ private readonly HashSet _activateEffectUsedThisTurn = new HashSet();
+ private readonly HashSet _specialSummonEffectUsedThisTurn = new HashSet();
+
+ // Ice의 발동효과(c8633261.lua e2)는 "일반소환 성공시"에만 터지고 룰특수소환으론 안 터짐.
+ // NormalSummonUsed(범용 일반소환권 사용여부)와 별개로, "Ice 본인이 이번 턴에 일반소환됐는가"를
+ // 정확히 추적해야 해서 전용 플래그로 둠.
+ private bool _iceNormalSummonedThisTurn = false;
- // activate
- AddExecutor(ExecutorType.Activate, CardId.MereologicAggregator, MereologicAggregatorActivateFirst);
- AddExecutor(ExecutorType.Activate, CardId.IceRyzeal, IceRyzealActivate);
- AddExecutor(ExecutorType.Activate, CardId.SwordRyzeal, SwordRyzealActivate);
- AddExecutor(ExecutorType.Activate, CardId.ExRyzeal, ExRyzealActivate);
- AddExecutor(ExecutorType.Activate, CardId.MereologicAggregator, MereologicAggregatorActivateLater);
+ private bool IsActivateEffectUsedThisTurn(int cardId)
+ {
+ return _activateEffectUsedThisTurn.Contains(cardId);
+ }
- // after summon
- AddExecutor(ExecutorType.Activate, CardId.RyzealCross, RyzealCrossActivateRecycleLater);
- AddExecutor(ExecutorType.Activate, _CardId.PotOfDesires, PotOfDesiresActivate);
+ private void MarkActivateEffectUsedThisTurn(int cardId)
+ {
+ _activateEffectUsedThisTurn.Add(cardId);
+ }
- AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
- AddExecutor(ExecutorType.SpellSet, SpellSetCheck);
+ private bool IsSpecialSummonEffectUsedThisTurn(int cardId)
+ {
+ return _specialSummonEffectUsedThisTurn.Contains(cardId);
+ }
+ private void MarkSpecialSummonEffectUsedThisTurn(int cardId)
+ {
+ _specialSummonEffectUsedThisTurn.Add(cardId);
}
- 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 = 0x160;
- const int SetcodeFloowandereeze = 0x16d;
- const int SetcodeLabrynth = 0x17f;
- const int SetcodeTearlaments = 0x182;
- const int SetcodeHorus = 0x3;
- const int SetcodeRyzeal = 0x1b6;
- const int hintTimingMainEnd = 0x4;
- List NotToNegateIdList = new List
+ // 메인 Ryzeal 덱 카드 그룹 (기본 5장 + 메인덱 서포트)
+ private readonly int[] Ryzeals =
{
- 58699500, 20343502, 25451383, 19403423
+ CardId.StarRyzeal,
+ CardId.IceRyzeal,
+ CardId.SwordRyzeal,
+ CardId.NodeRyzeal,
+ CardId.ExtRyzeal,
+ CardId.RyzealPlugin,
+ CardId.RyzealCross,
+ CardId.RyzealPlasmaHole
};
- List AlbazFusionList = new List
+
+ // Ryzeal 몬스터 전체 (기본 5장 + 추가 강화 카드)
+ private readonly int[] RyzealMonsters =
{
- 1906812, 38811586, 41373230, 44146295, 51409648, 76666602, 87746184, 03410461, 34848821
+ CardId.StarRyzeal,
+ CardId.IceRyzeal,
+ CardId.SwordRyzeal,
+ CardId.NodeRyzeal,
+ CardId.ExtRyzeal,
+ CardId.RyzealDetonator,
+ CardId.RyzealDuoDrive
};
- Dictionary> DeckCountTable = new Dictionary>{
- {3, new List { CardId.IceRyzeal, CardId.SwordRyzeal, 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}}
+
+ // 카드의 실제 속성/종족을 런타임에 Deck에서 조회하지 않고,
+ // 현재 확정 덱에서 검색 가능한 범위를 정적으로 정의한다.
+ // Sword Ryzeal: LIGHT + Pyro
+ private readonly int[] PyroMonsters =
+ {
+ CardId.StarRyzeal,
+ CardId.IceRyzeal
};
- 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
+
+ // Ext Ryzeal: FIRE + Thunder
+ private readonly int[] ThunderMonsters =
+ {
+ CardId.SwordRyzeal,
+ CardId.NodeRyzeal,
+ CardId.ExtRyzeal
};
- 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 DetonatorDestroySelf = 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)
+ // 현재 덱에서 필드의 Rank 4 Xyz 소재로 활용할 수 있는 Level 4 몬스터.
+ // 특히 Ice 룰 특수소환의 코스트를 고를 때 필드의 Level 4를 최대한 보존한다.
+ private readonly int[] Level4Monsters =
+ {
+ CardId.StarRyzeal,
+ CardId.IceRyzeal,
+ CardId.SwordRyzeal,
+ CardId.NodeRyzeal,
+ CardId.ExtRyzeal,
+ CardId.MulcharmyFuwalos,
+ CardId.MulcharmyPurulia
+ };
+
+ public RyzealExecutor(GameAI ai, Duel duel)
+ : base(ai, duel)
{
- 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;
+ // 1) 상대 효과 대응 (핸드트랩/무효화)
+ AddExecutor(ExecutorType.Activate, CardId.NibiruThePrimalBeing, NibiruEffect);
+ AddExecutor(ExecutorType.Activate, CardId.AshBlossomAndJoyousSpring, DefaultAshBlossomAndJoyousSpring);
+ AddExecutor(ExecutorType.Activate, CardId.GhostOgreAndSnowRabbit, DefaultGhostOgreAndSnowRabbit);
+ AddExecutor(ExecutorType.Activate, CardId.GhostBelleAndHauntedMansion, DefaultGhostBelleAndHauntedMansion);
+ AddExecutor(ExecutorType.Activate, CardId.MaxxC, DefaultMaxxC);
+ AddExecutor(ExecutorType.Activate, CardId.MulcharmyFuwalos, DefaultMulcharmyFuwalos);
+ AddExecutor(ExecutorType.Activate, CardId.MulcharmyPurulia, DefaultMulcharmyPurulia);
+ AddExecutor(ExecutorType.Activate, CardId.CalledByTheGrave, DefaultCalledByTheGrave);
+ AddExecutor(ExecutorType.Activate, CardId.CrossoutDesignator, CrossOutNegate);
+ AddExecutor(ExecutorType.Activate, CardId.InfiniteImpermanence, DefaultInfiniteImpermanence);
+ AddExecutor(ExecutorType.Activate, CardId.GravediggersTrapHole, DefaultUniqueTrap);
+
+ // Detonator optional on-summon attachment trigger. Other effects remain unsupported.
+ AddExecutor(ExecutorType.Activate, CardId.RyzealDetonator, DetonatorAttachEffect);
+ AddExecutor(ExecutorType.Activate, CardId.RyzealDetonator, DetonatorDestroyEffect);
+ AddExecutor(ExecutorType.Activate, CardId.RyzealDuoDrive, DuoDriveAttachEffect);
+ AddExecutor(ExecutorType.Activate, CardId.RyzealDuoDrive, DuoDriveSearchEffect);
+
+ // 2) 서치 / 초기 세팅
+ AddExecutor(ExecutorType.Activate, CardId.SeventhAscension, SeventhAscensionEffect);
+ AddExecutor(ExecutorType.Activate, CardId.SeventhTachyon, SeventhTachyonEffect);
+ AddExecutor(ExecutorType.Activate, CardId.Bonfire, BonfireEffect);
+
+ // 2.5) 기본 Ryzeal 순차 전개
+ AddExecutor(ExecutorType.Summon, CardId.IceRyzeal, IceRyzealSummon);
+ AddExecutor(ExecutorType.Activate, CardId.IceRyzeal, IceRyzealEffect);
+ AddExecutor(ExecutorType.SpSummon, CardId.IceRyzeal, IceRyzealSpSummon);
+ AddExecutor(ExecutorType.SpSummon, CardId.SwordRyzeal, SwordRyzealSpSummon);
+ AddExecutor(ExecutorType.SpSummon, CardId.NodeRyzeal, NodeRyzealSpSummon);
+ AddExecutor(ExecutorType.Activate, CardId.NodeRyzeal, NodeRyzealEffect);
+ AddExecutor(ExecutorType.SpSummon, CardId.ExtRyzeal, ExtRyzealSpSummon);
+ AddExecutor(ExecutorType.Activate, CardId.ExtRyzeal, ExtRyzealEffect);
+ AddExecutor(ExecutorType.SpSummon, CardId.StarRyzeal, StarRyzealSpSummon);
+ AddExecutor(ExecutorType.Activate, CardId.SwordRyzeal, SwordRyzealEffect);
+
+ // 3) 덱/엑스트라덱 활용
+ AddExecutor(ExecutorType.SpSummon, CardId.TraptrixRafflesia, TraptrixRafflesiaSummon);
+
+ // 기본 Spell/Trap/Repos 처리 (비-리질/비-아키타입 카드에 대해)
+ AddExecutor(ExecutorType.SpellSet, DefaultSpellSet);
+ AddExecutor(ExecutorType.Repos, DefaultMonsterRepos);
+ AddExecutor(ExecutorType.Activate, CardId.PotOfProsperity, DefaultPotOfDesires);
+ AddExecutor(ExecutorType.Activate, CardId.TripleTacticsTalent, DefaultTrap);
+
+ // TODO: 추가 콤보/소환 로직 구현
}
- public bool CheckCanBeTargeted(ClientCard card, bool canBeTarget, CardType selfType)
+ public override bool OnSelectHand()
{
- 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)
+ // 우선순위: Seventh Ascension -> Seventh Tachyon -> Bonfire -> 기타는 Default_OnSelectCard
+ // (Then: Ext Ryzeal / Ice Ryzeal search priority)
+ public override IList OnSelectCard(IList cards, int min, int max, long hint, bool cancelable)
{
- for (int count = 1; count < 4; ++count)
+ // Detach cost and target occur before this activation is added to CurrentChain.
+ // Route using the explicitly accepted activation, not the previous chain card.
+ if (_pendingDetonatorDestroySource != null && cards.Count > 0)
{
- if (DeckCountTable[count].Contains(id)) {
- return Bot.GetRemainingCount(id, count);
+ if (cards.All(c => c.Location == CardLocation.Overlay))
+ {
+ var chosen = cards.OrderBy(c => IsRyzealMonster(c.Id) ? 0 : 1)
+ .ThenBy(c => c.Id).Take(min).ToList();
+ if (chosen.Count == min)
+ {
+ foreach (var c in chosen)
+ _decisionLogger.WriteSelection("DetonatorDestroyDetach", Duel.Turn, cards.Select(x => x.Id), c.Id);
+ return chosen;
+ }
+ }
+ if (hint == (long)HintMsg.Destroy && min == 1 && max == 1)
+ {
+ var chosen = cards.Where(c => c.Controller == 1)
+ .OrderByDescending(c => c.IsFaceup())
+ .ThenBy(c => c.Id).FirstOrDefault();
+ _pendingDetonatorDestroySource = null;
+ if (chosen != null)
+ {
+ _decisionLogger.WriteSelection("DetonatorDestroyTarget", Duel.Turn, cards.Select(x => x.Id), chosen.Id);
+ return new List { chosen };
+ }
+ // The actual prompt may differ from the field snapshot; let host handle it.
+ }
+ }
+ // Resolution can concern an earlier chain link, not the last activated card.
+ ClientCard current = Duel.SolvingChainIndex > 0 && Duel.SolvingChainIndex <= Duel.CurrentChain.Count
+ ? Duel.CurrentChain[Duel.SolvingChainIndex - 1] : Util.GetLastChainCard();
+ // Handle engine-offered selections only; do not queue detach as an activation cost.
+ if (current != null && current.Id == CardId.RyzealDuoDrive && cards.Count > 0)
+ {
+ if (cards.All(c => c.Location == CardLocation.Overlay))
+ {
+ var chosen = cards.OrderBy(c => IsRyzealMonster(c.Id) ? 0 : 1)
+ .ThenBy(c => c.Id).Take(min).ToList();
+ foreach (var c in chosen)
+ _decisionLogger.WriteSelection("DuoDriveDetach", Duel.Turn, cards.Select(x => x.Id), c.Id);
+ if (chosen.Count == min) return chosen;
+ }
+ if (cards.All(c => c.Location == CardLocation.Deck))
+ {
+ // Verified upstream OnSelectUnselectCard exposes only selectable first-group
+ // cards, calls OnSelectCard(min=1,max=1), and min=0 when finishable.
+ // Select one valid card each time; return empty when engine allows finishing.
+ if (min == 0 && cancelable) return new List();
+ var chosen = cards.GroupBy(c => c.Id).Select(g => g.First())
+ .OrderBy(c => Bot.Hand.Any(x => x.Id == c.Id) ? 1 : 0)
+ .ThenBy(c => DuoDriveSearchPriority(c.Id)).ThenBy(c => c.Id)
+ .Take(min).ToList();
+ if (chosen.Count == min)
+ {
+ foreach (var c in chosen)
+ _decisionLogger.WriteSelection("DuoDriveSearch", Duel.Turn, cards.Select(x => x.Id), c.Id);
+ return chosen;
+ }
}
}
- return 0;
- }
- public int CheckRemainInDeck(params int[] ids)
- {
- int sum = 0;
- foreach (int id in ids)
+ // Lua selects one material during resolution, not at activation. Use the engine's
+ // offered candidates rather than attempting to duplicate attachfilter in C#.
+ if (current != null && current.IsCode(CardId.RyzealDetonator, CardId.RyzealDuoDrive) &&
+ hint == (long)HintMsg.XyzMaterial && min == 1 && max == 1 &&
+ cards.All(c => c.Location == CardLocation.Grave))
{
- sum += CheckRemainInDeck(id);
+ var selected = cards.OrderBy(c => IsRyzealMonster(c.Id) ? 1 : 0)
+ .ThenBy(c => c.Id).FirstOrDefault();
+ if (selected != null)
+ {
+ _decisionLogger.WriteSelection(current.Id == CardId.RyzealDetonator ? "DetonatorAttach" : "DuoDriveAttach", Duel.Turn,
+ cards.Select(c => c.Id), selected.Id);
+ return new List { selected };
+ }
}
- return sum;
- }
- public bool CheckWhetherHaveFinalMonster()
- {
- foreach (ClientCard monster in Bot.MonsterZone)
+ if (current == null)
+ return base.OnSelectCard(cards, min, max, hint, cancelable);
+
+ // Ryzeal 기반 카드/서치 이외에는 기본 선택 로직으로 처리
+ if (!IsRyzealCard(current.Id) &&
+ !current.IsCode(CardId.SeventhAscension, CardId.SeventhTachyon, CardId.Bonfire, CardId.MulcharmyFuwalos))
{
- 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.RyzealDetonator) && monster.Overlays.Count() > 0) return true;
+ return base.OnSelectCard(cards, min, max, hint, cancelable);
}
- return false;
- }
+ if (current.IsCode(CardId.SeventhAscension))
+ {
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.SeventhTachyon));
+ if (selected != null)
+ return new List { selected };
+ }
- ///
- /// 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 (current.IsCode(CardId.SwordRyzeal) && cards.All(c => c.Location == CardLocation.Deck))
{
- if ((toFieldCheck && (((int)type & (int)CardType.Link) != 0)) || Card.IsDefense())
+ // Sword Ryzeal 효과로 덱에서 Ext -> Star -> Ice 우선 선택
+ bool hasExt = IsCardAnywhere(CardId.ExtRyzeal);
+ bool hasStar = IsCardAnywhere(CardId.StarRyzeal);
+ bool hasIce = IsCardAnywhere(CardId.IceRyzeal);
+
+ if (!hasExt)
{
- if (Enemy.MonsterZone.Any(card => CheckNumber41(card, ignore41)) || Bot.MonsterZone.Any(card => CheckNumber41(card, ignore41))) return true;
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.ExtRyzeal));
+ if (selected != null)
+ return new List { selected };
}
- 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);
- }
+ if (!hasStar)
+ {
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.StarRyzeal));
+ if (selected != null)
+ return new List { selected };
+ }
- ///
- /// Whether spell or trap will be negated. 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 (!hasIce)
+ {
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.IceRyzeal));
+ if (selected != null)
+ return new List { selected };
+ }
+
+ ClientCard fallback = cards.FirstOrDefault(c => c.IsCode(CardId.ExtRyzeal) || c.IsCode(CardId.IceRyzeal));
+ if (fallback != null)
+ return new List { fallback };
+ }
+
+ // Seventh Tachyon 발동 후 덱 맨 위로 넣을 카드 선택 (패에서 선택)
+ if (current.IsCode(CardId.SeventhTachyon) && cards.All(c => c.Location == CardLocation.Hand))
{
- 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;
+ // 1. MulcharmyFuwalos 우선
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.MulcharmyFuwalos));
+ if (selected != null)
+ return new List { selected };
+
+ // 2. 중복 카드 (손패에서 같은 ID의 카드가 2장 이상인 것)
+ var duplicateCards = cards.GroupBy(c => c.Id).Where(g => g.Count() > 1).SelectMany(g => g).ToList();
+ if (duplicateCards.Any())
+ {
+ return new List { duplicateCards.First() };
+ }
+
+ // 3. RyzealPlugin, RyzealCross, RyzealPlasmaHole 중 패에 있는 것 (그리고 필드/묘지/제외에 존재하는 경우)
+ var ryzealCards = new[] { CardId.RyzealPlugin, CardId.RyzealCross, CardId.RyzealPlasmaHole };
+ var availableRyzealCards = cards.Where(c => ryzealCards.Contains(c.Id)).ToList();
+ if (availableRyzealCards.Any())
+ {
+ // 모두 패, 필드, 묘지, 제외 중 하나에 있는지 확인 (즉, 게임에 존재하는지)
+ bool allExist = ryzealCards.All(id =>
+ Bot.Hand.Any(c => c.Id == id) ||
+ Bot.GetMonsters().Any(c => c.Id == id) ||
+ Bot.GetSpells().Any(c => c.Id == id) ||
+ Bot.Graveyard.Any(c => c.Id == id) ||
+ Bot.Banished.Any(c => c.Id == id));
+ if (allExist)
+ {
+ return new List { availableRyzealCards.First() };
+ }
+ }
+
+ // 4. Ryzeal 카드가 아닌 카드 하나
+ var nonRyzealCards = cards.Where(c => !IsRyzealCard(c.Id)).ToList();
+ if (nonRyzealCards.Any())
+ {
+ return new List { nonRyzealCards.First() };
+ }
+
+ // 5. 랜덤
+ return new List { cards.First() };
}
- if (target.IsTrap() && (Enemy.HasInSpellZone(_CardId.RoyalDecreel, true) || Bot.HasInSpellZone(_CardId.RoyalDecreel, true))) return true;
- if (target.Location == CardLocation.SpellZone && (target.IsSpell() || target.IsTrap()))
+
+ if (current.IsCode(CardId.SeventhTachyon) || current.IsCode(CardId.Bonfire))
{
- int selfSeq = -1;
- for (int i = 0; i < 5; ++i)
+ // Ext/Ice/Star 모두 1장 이상 있고 Ext 2장 이상이면 추가 서치 필요 없음
+ int extCount = CountInHand(CardId.ExtRyzeal);
+ int iceCount = CountInHand(CardId.IceRyzeal);
+ int starCount = CountInHand(CardId.StarRyzeal);
+ if (extCount >= 2 && iceCount >= 1 && starCount >= 1)
+ return base.OnSelectCard(cards, min, max, hint, cancelable);
+
+ // 우선순위: Ext Ryzeal → Ice Ryzeal → Star Ryzeal → (2장째) Ext Ryzeal → (2장째) Star Ryzeal
+ if (extCount == 0)
{
- if (Bot.SpellZone[i] == Card) selfSeq = i;
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.ExtRyzeal));
+ if (selected != null)
+ return new List { selected };
+ }
+
+ if (iceCount == 0)
+ {
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.IceRyzeal));
+ if (selected != null)
+ return new List { selected };
+ }
+
+ if (starCount == 0)
+ {
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.StarRyzeal));
+ if (selected != null)
+ return new List { selected };
+ }
+
+ if (extCount == 1)
+ {
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.ExtRyzeal));
+ if (selected != null)
+ return new List { selected };
+ }
+
+ if (starCount == 1)
+ {
+ ClientCard selected = cards.FirstOrDefault(c => c.IsCode(CardId.StarRyzeal));
+ if (selected != null)
+ return new List { selected };
}
- if (infiniteImpermanenceList.Contains(selfSeq)) return true;
}
- // how to get here?
- return false;
+
+ return base.OnSelectCard(cards, min, max, hint, cancelable);
}
- ///
- /// Check whether last chain card should be disabled.
- ///
- public bool CheckLastChainShouldNegated()
+ // "가지고 있는 카드"는 손패에 있는 카드만을 의미합니다.
+ private bool HasCardInHand(int cardId)
{
- ClientCard lastcard = Util.GetLastChainCard();
- if (lastcard == null || lastcard.Controller != 1) return false;
- return CheckCardShouldNegate(lastcard);
+ return Bot.HasInHand(cardId);
}
- public bool CheckCardShouldNegate(ClientCard card)
+ private int CountInHand(int cardId)
{
- 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 Bot.Hand.Count(card => card != null && card.Id == cardId);
+ }
- return true;
+ private bool IsRyzealCard(int cardId)
+ {
+ if (RyzealMonsters.Contains(cardId))
+ return true;
+
+ // 확장/서포트 카드도 Ryzeal 범위로 간주
+ return cardId == CardId.RyzealPlugin || cardId == CardId.RyzealCross || cardId == CardId.RyzealPlasmaHole;
}
- public bool CheckCardShouldNegate(ChainInfo chainInfo)
+ private bool SeventhAscensionEffect()
{
- if (chainInfo == null) return false;
- ClientCard card = chainInfo.RelatedCard;
+ // 우선적으로 꺼내야 하는 카드가 있는 경우 발동 (패에 7th Tachyon이 없을 때)
+ return !HasCardInHand(CardId.SeventhTachyon);
+ }
- 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;
+ private bool SeventhTachyonEffect()
+ {
+ // Ext/Ice/Star 모두 손패에 있고 Ext가 2장 이상이면 더 이상 사용할 필요 없음
+ if (CountInHand(CardId.ExtRyzeal) >= 2 && HasCardInHand(CardId.IceRyzeal) && HasCardInHand(CardId.StarRyzeal))
+ return false;
- return true;
+ // Ext/Ice Ryzeal이 손패에 부족할 때만 발동
+ return CountInHand(CardId.ExtRyzeal) < 2 || !HasCardInHand(CardId.IceRyzeal) || !HasCardInHand(CardId.StarRyzeal);
}
- ///
- /// Check whether bot is at advantage.
- ///
- public bool CheckAtAdvantage()
+ private bool BonfireEffect()
{
- if (GetProblematicEnemyMonster() == null && (Duel.Player == 0 || Bot.GetMonsterCount() > 0)) return true;
- return false;
+ // Ext/Ice/Star 모두 손패에 있고 Ext가 2장 이상이면 더 이상 사용할 필요 없음
+ if (CountInHand(CardId.ExtRyzeal) >= 2 && HasCardInHand(CardId.IceRyzeal) && HasCardInHand(CardId.StarRyzeal))
+ return false;
+
+ // Ext/Ice/Star가 손패에 부족할 때 발동
+ return CountInHand(CardId.ExtRyzeal) < 2 || !HasCardInHand(CardId.IceRyzeal) || !HasCardInHand(CardId.StarRyzeal);
}
- public bool CheckShouldNoMoreSpSummon()
+ private bool IsCardAnywhere(int cardId)
{
- if (CheckAtAdvantage() && enemyActivateMaxxC && !lockBirdSolved && (Duel.Turn == 1 || Duel.Phase >= DuelPhase.Main2))
- {
- return true;
- }
- return false;
+ return Bot.HasInHandOrHasInMonstersZone(cardId)
+ || Bot.HasInGraveyard(cardId)
+ || Bot.HasInSpellZone(cardId)
+ || Bot.HasInBanished(cardId);
}
- public bool CheckShouldNoMoreSpSummon(CardLocation loc)
+ private bool CanSummonIceRyzeal()
{
- 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 !NormalSummonUsed && Bot.HasInHand(CardId.IceRyzeal);
+ }
- return false;
+ private bool CommitSummonIceRyzeal()
+ {
+ NormalSummonUsed = true;
+ _iceNormalSummonedThisTurn = true;
+ return true;
}
- public bool CheckWhetherCanSummon()
+ private bool IceRyzealSummon()
{
- return Duel.Player == 0 && Duel.Phase < DuelPhase.End && summonCount > 0;
+ if (!CanSummonIceRyzeal()) return false;
+ return CommitSummonIceRyzeal();
}
- ///
- /// Check whether cards will be removed. If so, do not send cards to grave.
- ///
- public bool CheckWhetherWillbeRemoved()
+ // Ryzeal 몬스터들 중 "아직 어디에도 없는" 카드를 우선으로, 덱에 남아있는 걸 고르는 공용 로직.
+ // (Ice의 덱 특수소환 효과, Node의 묘지 소생 효과 등 여러 곳에서 재사용)
+ private int GetRyzealDeckTarget(int excludeCardId)
{
- 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)
+ int[] candidates = { CardId.StarRyzeal, CardId.IceRyzeal, CardId.SwordRyzeal, CardId.NodeRyzeal, CardId.ExtRyzeal };
+ foreach (var id in candidates)
{
- 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;
- }
- }
+ if (id == excludeCardId) continue;
+ if (!IsCardAnywhere(id) && Bot.GetRemainingCount(id, 1) > 0)
+ return id;
}
- return false;
+ foreach (var id in candidates)
+ {
+ if (id == excludeCardId) continue;
+ if (Bot.GetRemainingCount(id, 1) > 0)
+ return id;
+ }
+ return -1;
}
- public ClientCard GetProblematicEnemyMonster(int attack = 0, bool canBeTarget = false, bool ignoreCurrentDestroy = false, CardType selfType = 0)
+ // *** c8633261.lua 확인 결과 전면 재작성 ***
+ // 실제 효과: "일반소환 성공시"에만 발동(EVENT_SUMMON_SUCCESS - 특수소환으론 안 터짐),
+ // 손으로 서치가 아니라 덱의 다른 Ryzeal 몬스터를 필드로 직접 특수소환(CATEGORY_SPECIAL_SUMMON).
+ // 대상은 "Sword 고정"이 아니라 자신을 제외한 아무 Ryzeal 몬스터.
+ private bool CanActivateIceRyzealEffect()
{
- 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;
+ if (IsActivateEffectUsedThisTurn(CardId.IceRyzeal)) // HOPT: 발동효과 턴당 1번 (룰특수소환과 별개)
+ return false;
+
+ if (!_iceNormalSummonedThisTurn) // 일반소환 성공시에만 - 룰특수소환으론 안 터짐
+ return false;
+
+ if (Card == null || Card.Location != CardLocation.MonsterZone)
+ return false;
+
+ if (!Bot.HasInMonstersZone(CardId.IceRyzeal))
+ return false;
+
+ if (Bot.GetMonsterCount() >= 5) // 특수소환할 빈 몬스터존 필요 (메인 몬스터존 5칸 기준 근사치)
+ return false;
+
+ return GetRyzealDeckTarget(CardId.IceRyzeal) != -1;
}
- public bool CheckShouldNotIgnore(ClientCard cards, bool ignore = false)
+ private bool CommitActivateIceRyzealEffect()
{
- return !ignore || (!currentDestroyCardList.Contains(cards) && !currentNegateCardList.Contains(cards));
+ int target = GetRyzealDeckTarget(CardId.IceRyzeal);
+ if (target == -1) return false; // 안전장치
+
+ MarkActivateEffectUsedThisTurn(CardId.IceRyzeal);
+ AI.SelectCard(target); // 손 서치가 아니라 덱 -> 필드 직접 특수소환
+ return true;
}
- public bool CheckCanContinueSummon(bool skipDuodriver = false)
+ private bool IceRyzealEffect()
{
- bool checkFlag = summonCount > 0 && !activatedCardIdList.Contains(CardId.IceRyzeal) && Bot.HasInHand(CardId.IceRyzeal)
- && !DefaultCheckWhetherCardIdIsNegated(CardId.IceRyzeal);
- if (Bot.HasInHand(CardId.SwordRyzeal) && !spSummonedCardIdList.Contains(CardId.SwordRyzeal)
- && !activatedCardIdList.Contains(CardId.SwordRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.SwordRyzeal))
- {
- 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();
+ if (!CanActivateIceRyzealEffect()) return false;
+ return CommitActivateIceRyzealEffect();
+ }
- 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;
+ // ============================================================
+ // Ryzeal 몬스터들의 "1번 효과" = 룰 특수소환(체인 안 씀), 카드마다 조건/코스트가 다름.
+ // 발동형 효과(서치 등, 위쪽 IceRyzealEffect/SwordRyzealEffect)와는 별개의 HOPT.
+ // ============================================================
- return checkFlag;
+ private bool IsRyzealMonster(int cardId)
+ {
+ return RyzealMonsters.Contains(cardId);
}
- ///
- /// check enemy's dangerous card in grave
- ///
- public List GetDangerousCardinEnemyGrave(bool onlyMonster = false)
+ private bool HasLevel4OnField()
{
- 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;
+ return Bot.GetMonsters().Any(c => Level4Monsters.Contains(c.Id));
+ }
+
+ // 필드 Level4 카드 수가 홀수일 때, Level4 몬스터를 필드에 하나 더 추가하는 행동은
+ // Detonator/Duo Drive(레벨4 2장 필요) 같은 Rank4 엑시즈 소환을 "짝수"로 맞춰줘서
+ // 추가 전개로 이어질 수 있게 한다.
+ // 원래는 "이 행동 이후 실제로 Rank4 엑시즈를 하면 그 가치가 높다"를 미래 예측(lookahead)으로
+ // 반영해야 하지만, 지금 단계에선 그 계산이 어려워서 "짝수를 만드는 행동" 자체에
+ // 직접 가산점을 주는 방식으로 근사한다. (다섯 룰 특수소환 전부 "레벨4 자신을 필드에
+ // 추가"하는 동일 매커니즘이라 Ice/Sword/Node/Ext/Star 전부에 동일 적용)
+ private const double EvenLevel4BonusScore = 50; // TODO: 실전 테스트로 값 조정 필요
+
+ private double GetEvenLevel4Bonus()
+ {
+ int level4Count = Bot.GetMonsters().Count(c => Level4Monsters.Contains(c.Id));
+ return (level4Count % 2 == 1) ? EvenLevel4BonusScore : 0;
}
- public List GetProblematicEnemyCardList(bool canBeTarget = false, bool ignoreSpells = false, CardType selfType = 0)
+ // --- Ice: 패/필드의 카드 1장을 묘지로 보내고 특수소환 ---
+ private bool CanSpecialSummonIceRyzeal()
{
- List resultList = new List();
+ if (IsSpecialSummonEffectUsedThisTurn(CardId.IceRyzeal)) return false;
+ if (!Bot.HasInHand(CardId.IceRyzeal)) return false;
- 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);
+ // 코스트: Ice 자신 말고 묘지로 보낼 카드가 손패 또는 필드에 있어야 함
+ bool hasCostTarget = Bot.Hand.Count(c => c.Id != CardId.IceRyzeal) > 0
+ || Bot.GetMonsters().Count > 0
+ || Bot.GetSpells().Count > 0;
+ return hasCostTarget;
+ }
- 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));
+ // Ice 룰 특수소환의 코스트로 보낼 카드를 선택한다.
+ // 기본 원칙:
+ // 1) 손패의 Ice 이외 카드 우선
+ // 2) 손패에 없으면 필드의 Level 4가 아닌 몬스터 우선
+ // 3) 그래도 없으면 필드의 다른 카드
+ // 4) 마지막 수단으로 필드의 Level 4를 허용
+ //
+ // 필드의 Level 4를 남겨두면 Mulcharmy Fuwalos/Purulia 같은 Level 4
+ // 몬스터를 추가 소재로 활용해 Rank 4 Xyz로 이어갈 수 있으므로 보존한다.
+ private int GetIceRyzealCostTarget()
+ {
+ // 1. 손패의 Ice 이외 카드: 필드 Level 4를 건드리지 않는다.
+ ClientCard handTarget = Bot.Hand.FirstOrDefault(c => c.Id != CardId.IceRyzeal);
+ if (handTarget != null)
+ return handTarget.Id;
- 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);
+ // 2. 필드의 Level 4가 아닌 몬스터.
+ ClientCard nonLevel4Monster = Bot.GetMonsters()
+ .FirstOrDefault(c => !Level4Monsters.Contains(c.Id));
+ if (nonLevel4Monster != null)
+ return nonLevel4Monster.Id;
- 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);
+ // 3. 필드의 마법/함정.
+ ClientCard spellTarget = Bot.GetSpells().FirstOrDefault();
+ if (spellTarget != null)
+ return spellTarget.Id;
- 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);
- }
- }
- }
+ // 4. 다른 선택지가 없으면 Level 4 몬스터를 코스트로 사용.
+ ClientCard level4Monster = Bot.GetMonsters()
+ .FirstOrDefault(c => Level4Monsters.Contains(c.Id));
+ if (level4Monster != null)
+ return level4Monster.Id;
- 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 -1;
+ }
+
+ private bool CommitSpecialSummonIceRyzeal()
+ {
+ int target = GetIceRyzealCostTarget();
+ if (target == -1)
+ return false;
- return resultList;
+ MarkSpecialSummonEffectUsedThisTurn(CardId.IceRyzeal);
+ AI.SelectCard(target);
+ return true;
}
- public List GetNormalEnemyTargetList(bool canBeTarget = true, bool ignoreCurrentDestroy = false, CardType selfType = 0, bool forNegate = false)
+ // --- Sword: 필드/묘지에 Ryzeal 몬스터가 존재하면 특수소환 (코스트 없음) ---
+ private bool CanSpecialSummonSwordRyzeal()
{
- 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;
+ if (IsSpecialSummonEffectUsedThisTurn(CardId.SwordRyzeal)) return false;
+ if (!Bot.HasInHand(CardId.SwordRyzeal)) return false;
+
+ bool hasRyzealMonster = Bot.GetMonsters().Any(c => IsRyzealMonster(c.Id))
+ || Bot.Graveyard.Any(c => IsRyzealMonster(c.Id));
+ return hasRyzealMonster;
}
- public List GetMonsterListForTargetNegate(bool canBeTarget = false, CardType selfType = 0)
+ private bool CommitSpecialSummonSwordRyzeal()
{
- List resultList = new List();
- if (CheckWhetherNegated())
- {
- return resultList;
- }
+ MarkSpecialSummonEffectUsedThisTurn(CardId.SwordRyzeal);
+ return true; // 코스트 없음 - 추가 선택 불필요
+ }
- // 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);
- }
+ // --- Node: 필드/묘지에 Xyz 몬스터가 존재하면 특수소환 (코스트 없음) ---
+ private bool CanSpecialSummonNodeRyzeal()
+ {
+ if (IsSpecialSummonEffectUsedThisTurn(CardId.NodeRyzeal)) return false;
+ if (!Bot.HasInHand(CardId.NodeRyzeal)) return false;
- // 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);
- }
- }
+ bool hasXyz = Bot.GetMonsters().Any(c => c.HasType(CardType.Xyz))
+ || Bot.Graveyard.Any(c => c.HasType(CardType.Xyz));
+ return hasXyz;
+ }
- return resultList;
+ private bool CommitSpecialSummonNodeRyzeal()
+ {
+ MarkSpecialSummonEffectUsedThisTurn(CardId.NodeRyzeal);
+ return true;
}
- public List GetLevel4OnField(Func filter)
+ // Node ignition effect (c72238166.lua e2): send 1 card from hand/field as cost,
+ // then target and revive another Ryzeal monster from GY in face-up defense with effects negated.
+ // Both selections are queued before the engine asks; no prompt is left to the default selector.
+ private ClientCard GetNodeRyzealCostCard()
+ {
+ // On a full field prefer a monster cost; a hand/spell cost cannot free a zone.
+ if (Bot.GetMonsterCount() >= 5)
+ return Bot.GetMonsters().FirstOrDefault(c => c.IsFaceup());
+ var duplicate = Bot.Hand.FirstOrDefault(c => c.Id != CardId.NodeRyzeal && Bot.Hand.Count(x => x.Id == c.Id) > 1);
+ if (duplicate != null) return duplicate;
+ var nonRyzeal = Bot.Hand.FirstOrDefault(c => !IsRyzealCard(c.Id));
+ if (nonRyzeal != null) return nonRyzeal;
+ var spell = Bot.GetSpells().FirstOrDefault();
+ if (spell != null) return spell;
+ // Remaining Ryzeal hand cards are legal costs as well.
+ var hand = Bot.Hand.FirstOrDefault();
+ if (hand != null) return hand;
+ return Bot.GetMonsters().FirstOrDefault();
+ }
+ private int GetNodeRyzealCostTarget()
{
- 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();
+ var card = GetNodeRyzealCostCard();
+ return card == null ? -1 : card.Id;
}
- public int GetLevel4CountOnField()
+ private int GetNodeRyzealReviveTarget()
{
- int count = Bot.GetMonsters().Count(c => c.IsFaceup() && !c.HasType(CardType.Xyz | CardType.Link) && c.Level == 4);
- return count;
+ // The revived monster is negated, so choose it as a Rank 4 body rather than for its effect.
+ int[] priority = { CardId.ExtRyzeal, CardId.SwordRyzeal, CardId.IceRyzeal, CardId.StarRyzeal };
+ foreach (int id in priority)
+ if (Bot.Graveyard.Any(c => c.Id == id)) return id;
+ return -1;
}
- public int GetLevel4FinalCountOnField(bool checkSupport, out bool hasNode)
+ private bool CanActivateNodeRyzealEffect()
{
- // 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.SwordRyzeal) && !spSummonedCardIdList.Contains(CardId.SwordRyzeal))
- {
- 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.SwordRyzeal))
- {
- 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.SwordRyzeal, CardId.NodeRyzeal)))
- {
- level4Count++;
- checkHandCount++;
- }
- if (Bot.Hand.Count() >= checkHandCount && Bot.HasInHand(CardId.IceRyzeal) && !spSummonedCardIdList.Contains(CardId.IceRyzeal) && !CheckWhetherWillbeRemoved())
- {
- level4Count++;
- }
- }
+ if (IsActivateEffectUsedThisTurn(CardId.NodeRyzeal)) return false;
+ if (Card == null || Card.Location != CardLocation.MonsterZone) return false;
+ if (!Bot.HasInMonstersZone(CardId.NodeRyzeal)) return false;
+ if (GetNodeRyzealCostTarget() == -1 || GetNodeRyzealReviveTarget() == -1) return false;
- return level4Count;
+ // Lua checks Duel.GetMZoneCount(tp, costCard). A full field remains legal only when
+ // the selected cost itself is a monster and therefore frees a monster zone.
+ return Bot.GetMonsterCount() < 5 || Bot.GetMonsters().Count > 0;
}
- public List GetCostFromHandAndFieldFirst(ClientCard exceptCard)
+ private string GetNodeRyzealSelectionPlan()
{
- return Bot.MonsterZone.Where(c => c != null && !c.IsDisabled() && c.IsCode(NeedIceToSolveIdList) && c != exceptCard && !c.HasType(CardType.Token)).ToList();
+ return "cost:" + GetNodeRyzealCostTarget() + ";revive:" + GetNodeRyzealReviveTarget()
+ + ";position:FaceUpDefence;revivedEffects:negated";
}
- public List GetCostFromHandAndField(ClientCard exceptCard, bool sendNotNecessary)
+ private bool CommitActivateNodeRyzealEffect()
{
- 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 Detonator with no overlay
- if (Bot.HasInExtra(CardId.RyzealDetonator))
- {
- ClientCard Detonator = Bot.MonsterZone.FirstOrDefault(c => c != null && c.IsCode(CardId.RyzealDetonator) && c.Overlays.Count() == 0 && !resultList.Contains(c));
- if (Detonator != null)
- {
- resultList.Add(Detonator);
- }
- }
- }
-
- // 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.SwordRyzeal, 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, long hint, bool cancelable)
- {
- ChainInfo currentSolvingChain = Duel.GetCurrentSolvingChainInfo();
- ClientCard solvingCard = currentSolvingChain?.RelatedCard;
- string cardOptionsText = cards == null ? "null": string.Join(" | ", cards.Select(c => c == null
- ? "null" : $"Id={c.Id}, Name={(c.Name ?? "Unknown")}, Loc={c.Location},"));
-
- int solvingPlayer = currentSolvingChain?.ActivatePlayer ?? Duel.LastChainPlayer;
- 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.RyzealDetonator),
- (c) => c.IsCode(CardId.RyzealDetonator)
- };
- 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 (solvingPlayer == 1 && solvingCard.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 canUsePluginToSpSummonDetonator = Bot.Graveyard.Any(c => c != null && c.IsCanRevive() && c.IsCode(CardId.RyzealDetonator));
- canUsePluginToSpSummonDetonator |= Bot.Graveyard.Any(c => c != null && c.IsFaceup() && c.IsCanRevive() && c.IsCode(CardId.RyzealDetonator));
-
- List faceUpSpells = Bot.GetSpells().Where(c => c.IsFaceup()).ToList();
- banishList.AddRange(ShuffleList(faceUpSpells));
- List faceDownSpells = Bot.GetSpells().Where(c => c.IsFacedown()
- && !(canUsePluginToSpSummonDetonator && 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 (solvingCard.IsCode(CardId.SwordRyzeal))
- {
- 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 (solvingCard.IsCode(CardId.ExRyzeal))
- {
- ClientCard sword = cards.FirstOrDefault(c => c.IsCode(CardId.SwordRyzeal));
- ClientCard node = cards.FirstOrDefault(c => c.IsCode(CardId.NodeRyzeal));
- if (sword != null)
- {
- bool flag = node == null;
- flag |= !Bot.HasInHand(CardId.SwordRyzeal) && !spSummonedCardIdList.Contains(CardId.SwordRyzeal) && !activatedCardIdList.Contains(CardId.SwordRyzeal);
-
- if (flag)
- {
- return Util.CheckSelectCount(new List { sword }, cards, min, max);
- }
- }
- if (node != null)
- {
- bool flag = sword == null;
- flag |= spSummonedCardIdList.Contains(CardId.SwordRyzeal) && activatedCardIdList.Contains(CardId.SwordRyzeal)
- && !DefaultCheckWhetherCardIdIsNegated(CardId.SwordRyzeal);
- flag |= CheckShouldNoMoreSpSummon(CardLocation.Hand) && !CheckShouldNoMoreSpSummon(CardLocation.Grave)
- && !spSummonedCardIdList.Contains(CardId.NodeRyzeal);
-
- if (flag)
- {
- return Util.CheckSelectCount(new List { node }, cards, min, max);
- }
- }
- }
-
- if (solvingCard.IsCode(CardId.Bonfire) || solvingCard.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 (solvingCard.IsCode(CardId.RyzealDuodrive))
- {
- // search spells
- bool spellNegated = CheckWhetherNegated(true, true, CardType.Spell);
- if (!spellNegated)
- {
- 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.SwordRyzeal,
- () => !spSummonedCardIdList.Contains(CardId.SwordRyzeal) && !activatedCardIdList.Contains(CardId.SwordRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.SwordRyzeal) ),
- new KeyValuePair>(CardId.NodeRyzeal,
- () => !spSummonedCardIdList.Contains(CardId.NodeRyzeal) )
- };
- foreach (KeyValuePair> pair in checkList)
- {
- bool alreadyInHand = Bot.HasInHand(pair.Key);
- bool shouldSearch = pair.Value();
- if (!alreadyInHand && shouldSearch)
- {
- 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.SwordRyzeal, 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 (solvingCard.IsCode(CardId.IceRyzeal))
- {
- ClientCard sword = cards.FirstOrDefault(c => c.IsCode(CardId.SwordRyzeal));
- ClientCard ex = cards.FirstOrDefault(c => c.IsCode(CardId.ExRyzeal));
- ClientCard node = cards.FirstOrDefault(c => c.IsCode(CardId.NodeRyzeal));
- if (sword != null)
- {
- bool flag = !activatedCardIdList.Contains(CardId.SwordRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.SwordRyzeal);
- flag |= Bot.HasInHand(CardId.ExRyzeal) && !spSummonedCardIdList.Contains(CardId.ExRyzeal);
- flag |= ex == null && node == null;
- if (flag)
- {
- return Util.CheckSelectCount(new List { sword }, cards, min, max);
- }
- }
- if (ex != null)
- {
- bool flag = !activatedCardIdList.Contains(CardId.ExRyzeal) && !DefaultCheckWhetherCardIdIsNegated(CardId.ExRyzeal);
- flag |= Bot.HasInHand(CardId.SwordRyzeal) && !spSummonedCardIdList.Contains(CardId.SwordRyzeal);
- flag |= sword == 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 (solvingCard.IsCode(CardId.TwinsOfTheEclipse))
- {
- ClientCard target = TwinsOfTheEclipseRebornTarget(new List(cards));
-
- return Util.CheckSelectCount(new List { target }, cards, min, max);
- }
- }
-
- if (hint == HintMsg.ToDeck)
- {
- if (solvingCard.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 (solvingCard.IsCode(CardId.RyzealDetonator, 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 (solvingCard.IsCode(CardId.RyzealDuodrive))
- {
- List resultList = new List();
-
- List detachOwnerIdList = new List { CardId.StarliegePhotonBlastDragon, CardId.RyzealDuodrive, CardId.TwinsOfTheEclipse,
- CardId.FullArmoredUtopicRayLancer, _CardId.EvilswarmExcitonKnight, CardId.Number60DugaresTheTimeless, CardId.RyzealDetonator };
- 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)
- {
- // Detonator
- ClientCard Detonator = detachMaterialList.FirstOrDefault(c => c.IsCode(CardId.RyzealDetonator));
- if (Detonator != null)
- {
- resultList.Add(Detonator);
- }
- 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);
- }
- }
-
- // choose attach material by plugin from Deck
- if (solvingCard.IsCode(CardId.RyzealPlugIn) && cards.All(c => c.Location == CardLocation.Deck))
- {
- List priority = new List
- {
- CardId.ExRyzeal,
- CardId.IceRyzeal,
- CardId.SwordRyzeal,
- CardId.NodeRyzeal
- };
- foreach (int id in priority)
- {
- ClientCard target = cards.FirstOrDefault(c => c.IsCode(id));
- if (target != null)
- {
- return Util.CheckSelectCount(new List { target }, cards, min, max);
- }
- }
- }
-
- // gain material by plugin
- if (solvingCard.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 Detonator = cards.FirstOrDefault(c => c != null && !c.IsDisabled() && c.IsCode(CardId.RyzealDetonator));
- if (Detonator != null)
- {
- return Util.CheckSelectCount(new List { Detonator }, 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 (solvingCard.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.SwordRyzeal, 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 (solvingCard == null)
- {
- ClientCard lastChainCard = Util.GetLastChainCard();
- if (lastChainCard != null)
- {
- // handle for RyzealDetonator
- if (lastChainCard.Controller == 0 && lastChainCard.IsCode(CardId.RyzealDetonator))
- {
- if (hint == HintMsg.RemoveXyz)
- {
- if (DetonatorDestroySelf != 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