diff --git a/src/battle_ai_switch_items.c b/src/battle_ai_switch_items.c index aa7d819a1e..9c8061aabf 100644 --- a/src/battle_ai_switch_items.c +++ b/src/battle_ai_switch_items.c @@ -1507,6 +1507,24 @@ static u32 GetBestMonDmg(struct Pokemon *party, int firstId, int lastId, u8 inva return bestMonId; } +static u32 GetFirstNonIvalidMon(u32 firstId, u32 lastId, u32 invalidMons, u32 battlerIn1, u32 battlerIn2) +{ + if (!IsDoubleBattle()) + return PARTY_SIZE; + + if (PARTY_SIZE != gBattleStruct->monToSwitchIntoId[battlerIn1] + && PARTY_SIZE != gBattleStruct->monToSwitchIntoId[battlerIn2]) + return PARTY_SIZE; + + for (u32 chosenMonId = (lastId-1); chosenMonId >= firstId; chosenMonId--) + { + if ((1 << (chosenMonId)) & invalidMons) + continue; + return chosenMonId; // first non invalid mon found + } + return PARTY_SIZE; +} + bool32 IsMonGrounded(u16 heldItemEffect, u32 ability, u8 type1, u8 type2) { // List that makes mon not grounded @@ -2045,6 +2063,7 @@ static u32 GetBestMonIntegrated(struct Pokemon *party, int firstId, int lastId, u32 aiMove, hitsToKOAI, maxHitsToKO = 0; u16 bestResist = UQ_4_12(1.0), bestResistEffective = UQ_4_12(1.0), typeMatchup; bool32 isFreeSwitch = IsFreeSwitch(switchType, battlerIn1, opposingBattler), isSwitchinFirst, canSwitchinWin1v1; + u32 invalidMons = 0; // Iterate through mons for (i = firstId; i < lastId; i++) @@ -2056,6 +2075,7 @@ static u32 GetBestMonIntegrated(struct Pokemon *party, int firstId, int lastId, || i == gBattleStruct->monToSwitchIntoId[battlerIn1] || i == gBattleStruct->monToSwitchIntoId[battlerIn2]) { + invalidMons |= 1u << i; continue; } // Save Ace Pokemon for last @@ -2063,6 +2083,7 @@ static u32 GetBestMonIntegrated(struct Pokemon *party, int firstId, int lastId, { aceMonId = i; aceMonCount++; + invalidMons |= 1u << i; continue; } else @@ -2212,6 +2233,11 @@ static u32 GetBestMonIntegrated(struct Pokemon *party, int firstId, int lastId, && (IsSwitchOutEffect(GetMoveEffect(gCurrentMove)) || gAiLogicData->ejectButtonSwitch || gAiLogicData->ejectPackSwitch)) return aceMonId; + // Fallback + u32 bestMonId = GetFirstNonIvalidMon(firstId, lastId, invalidMons, battlerIn1, battlerIn2); + if (bestMonId != PARTY_SIZE) + return bestMonId; + return PARTY_SIZE; } @@ -2329,6 +2355,11 @@ u32 GetMostSuitableMonToSwitchInto(u32 battler, enum SwitchType switchType) && (IsSwitchOutEffect(GetMoveEffect(gCurrentMove)) || gAiLogicData->ejectButtonSwitch || gAiLogicData->ejectPackSwitch)) return aceMonId; + // Fallback + bestMonId = GetFirstNonIvalidMon(firstId, lastId, invalidMons, battlerIn1, battlerIn2); + if (bestMonId != PARTY_SIZE) + return bestMonId; + return PARTY_SIZE; } }