Merge branch 'beta' into activation-order

This commit is contained in:
Dean 2025-04-07 16:46:05 -07:00 committed by GitHub
commit d6df829f85
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
81 changed files with 1432 additions and 850 deletions

7
package-lock.json generated
View File

@ -10,6 +10,7 @@
"hasInstallScript": true,
"dependencies": {
"@material/material-color-utilities": "^0.2.7",
"compare-versions": "^6.1.1",
"crypto-js": "^4.2.0",
"i18next": "^24.2.2",
"i18next-browser-languagedetector": "^8.0.4",
@ -3605,6 +3606,12 @@
"node": ">=18"
}
},
"node_modules/compare-versions": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/compare-versions/-/compare-versions-6.1.1.tgz",
"integrity": "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg==",
"license": "MIT"
},
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",

View File

@ -55,6 +55,7 @@
},
"dependencies": {
"@material/material-color-utilities": "^0.2.7",
"compare-versions": "^6.1.1",
"crypto-js": "^4.2.0",
"i18next": "^24.2.2",
"i18next-browser-languagedetector": "^8.0.4",

View File

@ -0,0 +1,6 @@
import type { SessionSaveData } from "#app/system/game-data";
export interface SessionSaveMigrator {
version: string;
migrate: (data: SessionSaveData) => void;
}

View File

@ -0,0 +1,5 @@
export interface SettingsSaveMigrator {
version: string;
// biome-ignore lint/complexity/noBannedTypes: TODO - refactor settings
migrate: (data: Object) => void;
}

View File

@ -0,0 +1,6 @@
import type { SystemSaveData } from "#app/system/game-data";
export interface SystemSaveMigrator {
version: string;
migrate: (data: SystemSaveData) => void;
}

View File

@ -1539,8 +1539,6 @@ export default class BattleScene extends SceneBase {
this.currentBattle.mysteryEncounterType = mysteryEncounterType;
}
//this.pushPhase(new TrainerMessageTestPhase(this, TrainerType.RIVAL, TrainerType.RIVAL_2, TrainerType.RIVAL_3, TrainerType.RIVAL_4, TrainerType.RIVAL_5, TrainerType.RIVAL_6));
if (!waveIndex && lastBattle) {
const isWaveIndexMultipleOfTen = !(lastBattle.waveIndex % 10);
const isEndlessOrDaily = this.gameMode.hasShortBiomes || this.gameMode.isDaily;

View File

@ -1000,7 +1000,7 @@ export class PostDefendContactApplyStatusEffectAbAttr extends PostDefendAbAttr {
override canApplyPostDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean {
const effect = this.effects.length === 1 ? this.effects[0] : this.effects[pokemon.randSeedInt(this.effects.length)];
return move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon) && !attacker.status
return move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon}) && !attacker.status
&& (this.chance === -1 || pokemon.randSeedInt(100) < this.chance) && !move.hitsSubstitute(attacker, pokemon)
&& attacker.canSetStatus(effect, true, false, pokemon);
}
@ -1040,7 +1040,7 @@ export class PostDefendContactApplyTagChanceAbAttr extends PostDefendAbAttr {
}
override canApplyPostDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean {
return move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon) && pokemon.randSeedInt(100) < this.chance
return move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon}) && pokemon.randSeedInt(100) < this.chance
&& !move.hitsSubstitute(attacker, pokemon) && attacker.canAddTag(this.tagType);
}
@ -1087,7 +1087,7 @@ export class PostDefendContactDamageAbAttr extends PostDefendAbAttr {
}
override canApplyPostDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean {
return !simulated && move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon)
return !simulated && move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon})
&& !attacker.hasAbilityWithAttr(BlockNonDirectDamageAbAttr) && !move.hitsSubstitute(attacker, pokemon);
}
@ -1120,8 +1120,7 @@ export class PostDefendPerishSongAbAttr extends PostDefendAbAttr {
}
override canApplyPostDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean {
return (move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon) && !move.hitsSubstitute(attacker, pokemon))
&& !attacker.getTag(BattlerTagType.PERISH_SONG);
return move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon}) && !attacker.getTag(BattlerTagType.PERISH_SONG);
}
override applyPostDefend(pokemon: Pokemon, _passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, _hitResult: HitResult, _args: any[]): void {
@ -1165,7 +1164,7 @@ export class PostDefendAbilitySwapAbAttr extends PostDefendAbAttr {
}
override canApplyPostDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean {
return move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon)
return move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon})
&& attacker.getAbility().isSwappable && !move.hitsSubstitute(attacker, pokemon);
}
@ -1191,7 +1190,7 @@ export class PostDefendAbilityGiveAbAttr extends PostDefendAbAttr {
}
override canApplyPostDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean {
return move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon) && attacker.getAbility().isSuppressable
return move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon}) && attacker.getAbility().isSuppressable
&& !attacker.getAbility().hasAttr(PostDefendAbilityGiveAbAttr) && !move.hitsSubstitute(attacker, pokemon);
}
@ -1222,7 +1221,7 @@ export class PostDefendMoveDisableAbAttr extends PostDefendAbAttr {
override canApplyPostDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean {
return attacker.getTag(BattlerTagType.DISABLED) === null && !move.hitsSubstitute(attacker, pokemon)
&& move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon) && (this.chance === -1 || pokemon.randSeedInt(100) < this.chance);
&& move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon}) && (this.chance === -1 || pokemon.randSeedInt(100) < this.chance);
}
override applyPostDefend(pokemon: Pokemon, _passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, _hitResult: HitResult, _args: any[]): void {
@ -1927,7 +1926,7 @@ export class PostAttackApplyStatusEffectAbAttr extends PostAttackAbAttr {
super.canApplyPostAttack(pokemon, passive, simulated, attacker, move, hitResult, args)
&& !(pokemon !== attacker && move.hitsSubstitute(attacker, pokemon))
&& (simulated || !attacker.hasAbilityWithAttr(IgnoreMoveEffectsAbAttr) && pokemon !== attacker
&& (!this.contactRequired || move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon)) && pokemon.randSeedInt(100) < this.chance && !pokemon.status)
&& (!this.contactRequired || move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon})) && pokemon.randSeedInt(100) < this.chance && !pokemon.status)
) {
const effect = this.effects.length === 1 ? this.effects[0] : this.effects[pokemon.randSeedInt(this.effects.length)];
return simulated || attacker.canSetStatus(effect, true, false, pokemon);
@ -1966,7 +1965,7 @@ export class PostAttackApplyBattlerTagAbAttr extends PostAttackAbAttr {
/**Battler tags inflicted by abilities post attacking are also considered additional effects.*/
return super.canApplyPostAttack(pokemon, passive, simulated, attacker, move, hitResult, args) &&
!attacker.hasAbilityWithAttr(IgnoreMoveEffectsAbAttr) && pokemon !== attacker &&
(!this.contactRequired || move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon)) &&
(!this.contactRequired || move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon})) &&
pokemon.randSeedInt(100) < this.chance(attacker, pokemon, move) && !pokemon.status;
}
@ -2298,6 +2297,11 @@ export class PostSummonAbAttr extends AbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): void {}
}
/**
* Base class for ability attributes which remove an effect on summon
*/
export class PostSummonRemoveEffectAbAttr extends PostSummonAbAttr {}
/**
* Removes specified arena tags when a Pokemon is summoned.
*/
@ -2408,6 +2412,31 @@ export class PostSummonAddBattlerTagAbAttr extends PostSummonAbAttr {
}
}
/**
* Removes Specific battler tags when a Pokemon is summoned
*
* This should realistically only ever activate on gain rather than on summon
*/
export class PostSummonRemoveBattlerTagAbAttr extends PostSummonRemoveEffectAbAttr {
private immuneTags: BattlerTagType[];
/**
* @param immuneTags - The {@linkcode BattlerTagType | battler tags} the Pokémon is immune to.
*/
constructor(...immuneTags: BattlerTagType[]) {
super();
this.immuneTags = immuneTags;
}
public override canApplyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
return this.immuneTags.some(tagType => !!pokemon.getTag(tagType));
}
public override applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): void {
this.immuneTags.forEach(tagType => pokemon.removeTag(tagType));
}
}
export class PostSummonStatStageChangeAbAttr extends PostSummonAbAttr {
private stats: BattleStat[];
private stages: number;
@ -2595,6 +2624,43 @@ export class PostSummonTerrainChangeAbAttr extends PostSummonAbAttr {
}
}
/**
* Heals a status effect if the Pokemon is afflicted with it upon switch in (or gain)
*/
export class PostSummonHealStatusAbAttr extends PostSummonRemoveEffectAbAttr {
private immuneEffects: StatusEffect[];
private statusHealed: StatusEffect;
/**
* @param immuneEffects - The {@linkcode StatusEffect}s the Pokémon is immune to.
*/
constructor(...immuneEffects: StatusEffect[]) {
super();
this.immuneEffects = immuneEffects;
}
public override canApplyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
const status = pokemon.status?.effect;
return !Utils.isNullOrUndefined(status) && (this.immuneEffects.length < 1 || this.immuneEffects.includes(status))
}
public override applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): void {
const status = pokemon.status?.effect;
if (!Utils.isNullOrUndefined(status)) {
this.statusHealed = status;
pokemon.resetStatus(false);
pokemon.updateInfo();
}
}
public override getTriggerMessage(_pokemon: Pokemon, _abilityName: string, ..._args: any[]): string | null {
if (this.statusHealed) {
return getStatusEffectHealText(this.statusHealed, getPokemonNameWithAffix(_pokemon));
}
return null;
}
}
export class PostSummonFormChangeAbAttr extends PostSummonAbAttr {
private formFunc: (p: Pokemon) => number;
@ -3501,8 +3567,18 @@ export class BonusCritAbAttr extends AbAttr {
constructor() {
super(false);
}
override apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): void {
(args[0] as Utils.BooleanHolder).value = true;
/**
* Apply the bonus crit ability by increasing the value in the provided number holder by 1
*
* @param pokemon The pokemon with the BonusCrit ability (unused)
* @param passive Unused
* @param simulated Unused
* @param cancelled Unused
* @param args Args[0] is a number holder containing the crit stage.
*/
override apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: [Utils.NumberHolder, ...any]): void {
(args[0] as Utils.NumberHolder).value += 1;
}
}
@ -4753,7 +4829,7 @@ export class PostFaintContactDamageAbAttr extends PostFaintAbAttr {
}
override canApplyPostFaint(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker?: Pokemon, move?: Move, hitResult?: HitResult, ...args: any[]): boolean {
const diedToDirectDamage = move !== undefined && attacker !== undefined && move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon);
const diedToDirectDamage = move !== undefined && attacker !== undefined && move.doesFlagEffectApply({flag: MoveFlags.MAKES_CONTACT, user: attacker, target: pokemon});
const cancelled = new Utils.BooleanHolder(false);
globalScene.getField(true).map(p => applyAbAttrs(FieldPreventExplosiveMovesAbAttr, p, cancelled, simulated));
if (!diedToDirectDamage || cancelled.value || attacker!.hasAbilityWithAttr(BlockNonDirectDamageAbAttr)) {
@ -6299,6 +6375,7 @@ export function initAbilities() {
.ignorable(),
new Ability(Abilities.LIMBER, 3)
.attr(StatusEffectImmunityAbAttr, StatusEffect.PARALYSIS)
.attr(PostSummonHealStatusAbAttr, StatusEffect.PARALYSIS)
.ignorable(),
new Ability(Abilities.SAND_VEIL, 3)
.attr(StatMultiplierAbAttr, Stat.EVA, 1.2)
@ -6316,6 +6393,7 @@ export function initAbilities() {
.ignorable(),
new Ability(Abilities.OBLIVIOUS, 3)
.attr(BattlerTagImmunityAbAttr, [ BattlerTagType.INFATUATED, BattlerTagType.TAUNT ])
.attr(PostSummonRemoveBattlerTagAbAttr, BattlerTagType.INFATUATED, BattlerTagType.TAUNT)
.attr(IntimidateImmunityAbAttr)
.ignorable(),
new Ability(Abilities.CLOUD_NINE, 3)
@ -6328,6 +6406,7 @@ export function initAbilities() {
.attr(StatMultiplierAbAttr, Stat.ACC, 1.3),
new Ability(Abilities.INSOMNIA, 3)
.attr(StatusEffectImmunityAbAttr, StatusEffect.SLEEP)
.attr(PostSummonHealStatusAbAttr, StatusEffect.SLEEP)
.attr(BattlerTagImmunityAbAttr, BattlerTagType.DROWSY)
.ignorable(),
new Ability(Abilities.COLOR_CHANGE, 3)
@ -6335,6 +6414,7 @@ export function initAbilities() {
.condition(getSheerForceHitDisableAbCondition()),
new Ability(Abilities.IMMUNITY, 3)
.attr(StatusEffectImmunityAbAttr, StatusEffect.POISON, StatusEffect.TOXIC)
.attr(PostSummonHealStatusAbAttr, StatusEffect.POISON, StatusEffect.TOXIC)
.ignorable(),
new Ability(Abilities.FLASH_FIRE, 3)
.attr(TypeImmunityAddBattlerTagAbAttr, PokemonType.FIRE, BattlerTagType.FIRE_BOOST, 1)
@ -6344,6 +6424,7 @@ export function initAbilities() {
.ignorable(),
new Ability(Abilities.OWN_TEMPO, 3)
.attr(BattlerTagImmunityAbAttr, BattlerTagType.CONFUSED)
.attr(PostSummonRemoveBattlerTagAbAttr, BattlerTagType.CONFUSED)
.attr(IntimidateImmunityAbAttr)
.ignorable(),
new Ability(Abilities.SUCTION_CUPS, 3)
@ -6409,9 +6490,11 @@ export function initAbilities() {
.ignorable(),
new Ability(Abilities.MAGMA_ARMOR, 3)
.attr(StatusEffectImmunityAbAttr, StatusEffect.FREEZE)
.attr(PostSummonHealStatusAbAttr, StatusEffect.FREEZE)
.ignorable(),
new Ability(Abilities.WATER_VEIL, 3)
.attr(StatusEffectImmunityAbAttr, StatusEffect.BURN)
.attr(PostSummonHealStatusAbAttr, StatusEffect.BURN)
.ignorable(),
new Ability(Abilities.MAGNET_PULL, 3)
.attr(ArenaTrapAbAttr, (user, target) => {
@ -6505,6 +6588,7 @@ export function initAbilities() {
.attr(DoubleBattleChanceAbAttr),
new Ability(Abilities.VITAL_SPIRIT, 3)
.attr(StatusEffectImmunityAbAttr, StatusEffect.SLEEP)
.attr(PostSummonHealStatusAbAttr, StatusEffect.SLEEP)
.attr(BattlerTagImmunityAbAttr, BattlerTagType.DROWSY)
.ignorable(),
new Ability(Abilities.WHITE_SMOKE, 3)
@ -6843,6 +6927,7 @@ export function initAbilities() {
.attr(MoveTypeChangeAbAttr, PokemonType.ICE, 1.2, (user, target, move) => move.type === PokemonType.NORMAL && !move.hasAttr(VariableMoveTypeAttr)),
new Ability(Abilities.SWEET_VEIL, 6)
.attr(UserFieldStatusEffectImmunityAbAttr, StatusEffect.SLEEP)
.attr(PostSummonUserFieldRemoveStatusEffectAbAttr, StatusEffect.SLEEP)
.attr(UserFieldBattlerTagImmunityAbAttr, BattlerTagType.DROWSY)
.ignorable()
.partial(), // Mold Breaker ally should not be affected by Sweet Veil
@ -6927,6 +7012,7 @@ export function initAbilities() {
.attr(ReceivedTypeDamageMultiplierAbAttr, PokemonType.FIRE, 0.5)
.attr(MoveTypePowerBoostAbAttr, PokemonType.WATER, 2)
.attr(StatusEffectImmunityAbAttr, StatusEffect.BURN)
.attr(PostSummonHealStatusAbAttr, StatusEffect.BURN)
.ignorable(),
new Ability(Abilities.STEELWORKER, 7)
.attr(MoveTypePowerBoostAbAttr, PokemonType.STEEL),
@ -7205,6 +7291,7 @@ export function initAbilities() {
new Ability(Abilities.THERMAL_EXCHANGE, 9)
.attr(PostDefendStatStageChangeAbAttr, (target, user, move) => user.getMoveType(move) === PokemonType.FIRE && move.category !== MoveCategory.STATUS, Stat.ATK, 1)
.attr(StatusEffectImmunityAbAttr, StatusEffect.BURN)
.attr(PostSummonHealStatusAbAttr, StatusEffect.BURN)
.ignorable(),
new Ability(Abilities.ANGER_SHELL, 9)
.attr(PostDefendHpGatedStatStageChangeAbAttr, (target, user, move) => move.category !== MoveCategory.STATUS, 0.5, [ Stat.ATK, Stat.SPATK, Stat.SPD ], 1)

View File

@ -1428,7 +1428,8 @@ export class MoveAnim extends BattleAnim {
public move: Moves;
constructor(move: Moves, user: Pokemon, target: BattlerIndex, playOnEmptyField = false) {
super(user, globalScene.getField()[target], playOnEmptyField);
// Set target to the user pokemon if no target is found to avoid crashes
super(user, globalScene.getField()[target] ?? user, playOnEmptyField);
this.move = move;
}

View File

@ -346,7 +346,7 @@ export default class Move implements Localizable {
* @param target The {@linkcode Pokemon} targeted by this move
* @returns `true` if the move can bypass the target's Substitute; `false` otherwise.
*/
hitsSubstitute(user: Pokemon, target: Pokemon | null): boolean {
hitsSubstitute(user: Pokemon, target?: Pokemon): boolean {
if ([ MoveTarget.USER, MoveTarget.USER_SIDE, MoveTarget.ENEMY_SIDE, MoveTarget.BOTH_SIDES ].includes(this.moveTarget)
|| !target?.getTag(BattlerTagType.SUBSTITUTE)) {
return false;
@ -618,12 +618,30 @@ export default class Move implements Localizable {
/**
* Checks if the move flag applies to the pokemon(s) using/receiving the move
*
* This method will take the `user`'s ability into account when reporting flags, e.g.
* calling this method for {@linkcode MoveFlags.MAKES_CONTACT | MAKES_CONTACT}
* will return `false` if the user has a {@linkcode Abilities.LONG_REACH} that is not being suppressed.
*
* **Note:** This method only checks if the move should have effectively have the flag applied to its use.
* It does *not* check whether the flag will trigger related effects.
* For example using this method to check {@linkcode MoveFlags.WIND_MOVE}
* will not consider {@linkcode Abilities.WIND_RIDER | Wind Rider }.
*
* To simply check whether the move has a flag, use {@linkcode hasFlag}.
* @param flag {@linkcode MoveFlags} MoveFlag to check on user and/or target
* @param user {@linkcode Pokemon} the Pokemon using the move
* @param target {@linkcode Pokemon} the Pokemon receiving the move
* @param isFollowUp (defaults to `false`) `true` if the move was used as a follow up
* @returns boolean
* @see {@linkcode hasFlag}
*/
checkFlag(flag: MoveFlags, user: Pokemon, target: Pokemon | null): boolean {
doesFlagEffectApply({ flag, user, target, isFollowUp = false }: {
flag: MoveFlags;
user: Pokemon;
target?: Pokemon;
isFollowUp?: boolean;
}): boolean {
// special cases below, eg: if the move flag is MAKES_CONTACT, and the user pokemon has an ability that ignores contact (like "Long Reach"), then overrides and move does not make contact
switch (flag) {
case MoveFlags.MAKES_CONTACT:
@ -633,16 +651,18 @@ export default class Move implements Localizable {
break;
case MoveFlags.IGNORE_ABILITIES:
if (user.hasAbilityWithAttr(MoveAbilityBypassAbAttr)) {
const abilityEffectsIgnored = new Utils.BooleanHolder(false);
const abilityEffectsIgnored = new Utils.BooleanHolder(false);
applyAbAttrs(MoveAbilityBypassAbAttr, user, abilityEffectsIgnored, false, this);
if (abilityEffectsIgnored.value) {
return true;
}
// Sunsteel strike, Moongeist beam, and photon geyser will not ignore abilities if invoked
// by another move, such as via metronome.
}
break;
return this.hasFlag(MoveFlags.IGNORE_ABILITIES) && !isFollowUp;
case MoveFlags.IGNORE_PROTECT:
if (user.hasAbilityWithAttr(IgnoreProtectOnContactAbAttr)
&& this.checkFlag(MoveFlags.MAKES_CONTACT, user, null)) {
&& this.doesFlagEffectApply({ flag: MoveFlags.MAKES_CONTACT, user })) {
return true;
}
break;
@ -1214,7 +1234,7 @@ export class MoveEffectAttr extends MoveAttr {
canApply(user: Pokemon, target: Pokemon, move: Move, args?: any[]) {
return !! (this.selfTarget ? user.hp && !user.getTag(BattlerTagType.FRENZY) : target.hp)
&& (this.selfTarget || !target.getTag(BattlerTagType.PROTECTED) ||
move.checkFlag(MoveFlags.IGNORE_PROTECT, user, target));
move.doesFlagEffectApply({ flag: MoveFlags.IGNORE_PROTECT, user, target }));
}
/** Applies move effects so long as they are able based on {@linkcode canApply} */
@ -2423,12 +2443,8 @@ export class StatusEffectAttr extends MoveEffectAttr {
const statusCheck = moveChance < 0 || moveChance === 100 || user.randSeedInt(100) < moveChance;
if (statusCheck) {
const pokemon = this.selfTarget ? user : target;
if (pokemon.status) {
if (this.overrideStatus) {
pokemon.resetStatus();
} else {
return false;
}
if (pokemon.status && !this.overrideStatus) {
return false;
}
if (user !== target && target.isSafeguarded(user)) {
@ -2437,8 +2453,8 @@ export class StatusEffectAttr extends MoveEffectAttr {
}
return false;
}
if ((!pokemon.status || (pokemon.status.effect === this.effect && moveChance < 0))
&& pokemon.trySetStatus(this.effect, true, user, this.turnsRemaining)) {
if (((!pokemon.status || this.overrideStatus) || (pokemon.status.effect === this.effect && moveChance < 0))
&& pokemon.trySetStatus(this.effect, true, user, this.turnsRemaining, null, this.overrideStatus)) {
applyPostAttackAbAttrs(ConfusionOnStatusEffectAbAttr, user, target, move, null, false, this.effect);
return true;
}
@ -5908,7 +5924,7 @@ export class AddArenaTagAttr extends MoveEffectAttr {
}
if ((move.chance < 0 || move.chance === 100 || user.randSeedInt(100) < move.chance) && user.getLastXMoves(1)[0]?.result === MoveResult.SUCCESS) {
const side = (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY;
const side = ((this.selfSideTarget ? user : target).isPlayer() !== (move.hasAttr(AddArenaTrapTagAttr) && target === user)) ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY;
globalScene.arena.addTag(this.tagType, this.turnCount, move.id, user.id, side);
return true;
}
@ -5957,7 +5973,7 @@ export class RemoveArenaTagsAttr extends MoveEffectAttr {
export class AddArenaTrapTagAttr extends AddArenaTagAttr {
getCondition(): MoveConditionFunc {
return (user, target, move) => {
const side = (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY;
const side = (this.selfSideTarget !== user.isPlayer()) ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER;
const tag = globalScene.arena.getTagOnSide(this.tagType, side) as ArenaTrapTag;
if (!tag) {
return true;

View File

@ -264,6 +264,7 @@ import { StatusEffect } from "#enums/status-effect";
import { doShinySparkleAnim } from "#app/field/anims";
import { MoveFlags } from "#enums/MoveFlags";
import { timedEventManager } from "#app/global-event-manager";
import { ResetStatusPhase } from "#app/phases/reset-status-phase";
export enum LearnMoveSituation {
MISC,
@ -1340,8 +1341,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
}
/**
* Retrieves the critical-hit stage considering the move used and the Pokemon
* who used it.
* Calculate the critical-hit stage of a move used against this pokemon by
* the given source
*
* @param source the {@linkcode Pokemon} who using the move
* @param move the {@linkcode Move} being used
* @returns the final critical-hit stage value
@ -1360,14 +1362,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
source.isPlayer(),
critStage,
);
const bonusCrit = new Utils.BooleanHolder(false);
//@ts-ignore
if (applyAbAttrs(BonusCritAbAttr, source, null, false, bonusCrit)) {
// TODO: resolve ts-ignore. This is a promise. Checking a promise is bogus.
if (bonusCrit.value) {
critStage.value += 1;
}
}
applyAbAttrs(BonusCritAbAttr, source, null, false, critStage)
const critBoostTag = source.getTag(CritBoostTag);
if (critBoostTag) {
if (critBoostTag instanceof DragonCheerTag) {
@ -4819,7 +4814,6 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
if (newTag.canAdd(this)) {
this.summonData.tags.push(newTag);
newTag.onAdd(this);
return true;
}
@ -5490,8 +5484,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
sourcePokemon: Pokemon | null = null,
turnsRemaining = 0,
sourceText: string | null = null,
overrideStatus?: boolean
): boolean {
if (!this.canSetStatus(effect, asPhase, false, sourcePokemon)) {
if (!this.canSetStatus(effect, asPhase, overrideStatus, sourcePokemon)) {
return false;
}
if (this.isFainted() && effect !== StatusEffect.FAINT) {
@ -5507,6 +5502,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
}
if (asPhase) {
if (overrideStatus) {
this.resetStatus(false);
}
globalScene.unshiftPhase(
new ObtainStatusEffectPhase(
this.getBattlerIndex(),
@ -5546,20 +5544,6 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
effect = effect!; // If `effect` is undefined then `trySetStatus()` will have already returned early via the `canSetStatus()` call
this.status = new Status(effect, 0, sleepTurnsRemaining?.value);
if (effect !== StatusEffect.FAINT) {
globalScene.triggerPokemonFormChange(
this,
SpeciesFormChangeStatusEffectTrigger,
true,
);
applyPostSetStatusAbAttrs(
PostSetStatusAbAttr,
this,
effect,
sourcePokemon,
);
}
return true;
}
@ -5574,21 +5558,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
if (!revive && lastStatus === StatusEffect.FAINT) {
return;
}
this.status = null;
if (lastStatus === StatusEffect.SLEEP) {
this.setFrameRate(10);
if (this.getTag(BattlerTagType.NIGHTMARE)) {
this.lapseTag(BattlerTagType.NIGHTMARE);
}
}
if (confusion) {
if (this.getTag(BattlerTagType.CONFUSED)) {
this.lapseTag(BattlerTagType.CONFUSED);
}
}
if (reloadAssets) {
this.loadAssets(false).then(() => this.playAnim());
}
globalScene.unshiftPhase(new ResetStatusPhase(this, confusion, reloadAssets));
}
/**

View File

@ -2734,7 +2734,7 @@ export class PokemonMoveAccuracyBoosterModifier extends PokemonHeldItemModifier
* @returns always `true`
*/
override apply(_pokemon: Pokemon, moveAccuracy: NumberHolder): boolean {
moveAccuracy.value = Math.min(moveAccuracy.value + this.accuracyAmount * this.getStackCount(), 100);
moveAccuracy.value = moveAccuracy.value + this.accuracyAmount * this.getStackCount();
return true;
}

View File

@ -9,10 +9,6 @@ import { Phase } from "#app/phase";
import { globalScene } from "#app/global-scene";
export class AddEnemyBuffModifierPhase extends Phase {
constructor() {
super();
}
start() {
super.start();

View File

@ -1,10 +1,10 @@
import { applyAbAttrs, applyPreLeaveFieldAbAttrs, PreLeaveFieldAbAttr, RunSuccessAbAttr } from "#app/data/ability";
import { Stat } from "#app/enums/stat";
import { StatusEffect } from "#app/enums/status-effect";
import { Stat } from "#enums/stat";
import { StatusEffect } from "#enums/status-effect";
import type { PlayerPokemon, EnemyPokemon } from "#app/field/pokemon";
import type Pokemon from "#app/field/pokemon";
import i18next from "i18next";
import * as Utils from "#app/utils";
import { NumberHolder } from "#app/utils";
import { BattleEndPhase } from "./battle-end-phase";
import { NewBattlePhase } from "./new-battle-phase";
import { PokemonPhase } from "./pokemon-phase";
@ -22,7 +22,7 @@ export class AttemptRunPhase extends PokemonPhase {
const playerPokemon = this.getPokemon();
const escapeChance = new Utils.NumberHolder(0);
const escapeChance = new NumberHolder(0);
this.attemptRunAway(playerField, enemyField, escapeChance);
@ -63,7 +63,7 @@ export class AttemptRunPhase extends PokemonPhase {
this.end();
}
attemptRunAway(playerField: PlayerPokemon[], enemyField: EnemyPokemon[], escapeChance: Utils.NumberHolder) {
attemptRunAway(playerField: PlayerPokemon[], enemyField: EnemyPokemon[], escapeChance: NumberHolder) {
/** Sum of the speed of all enemy pokemon on the field */
const enemySpeed = enemyField.reduce(
(total: number, enemyPokemon: Pokemon) => total + enemyPokemon.getStat(Stat.SPD),

View File

@ -26,13 +26,15 @@ export class BattleEndPhase extends BattlePhase {
return true;
});
// `phaseQueuePrepend` is private, so we have to use this inefficient loop.
while (globalScene.tryRemoveUnshiftedPhase(phase => {
if (phase instanceof BattleEndPhase) {
this.isVictory ||= phase.isVictory;
return true;
}
return false;
})) {}
while (
globalScene.tryRemoveUnshiftedPhase(phase => {
if (phase instanceof BattleEndPhase) {
this.isVictory ||= phase.isVictory;
return true;
}
return false;
})
) {}
globalScene.gameData.gameStats.battles++;
if (

View File

@ -3,13 +3,13 @@ import { TrainerSlot } from "#enums/trainer-slot";
import { Phase } from "#app/phase";
export class BattlePhase extends Phase {
constructor() {
super();
}
showEnemyTrainer(trainerSlot: TrainerSlot = TrainerSlot.NONE): void {
const sprites = globalScene.currentBattle.trainer?.getSprites()!; // TODO: is this bang correct?
const tintSprites = globalScene.currentBattle.trainer?.getTintSprites()!; // TODO: is this bang correct?
if (!globalScene.currentBattle.trainer) {
console.warn("Enemy trainer is missing!");
return;
}
const sprites = globalScene.currentBattle.trainer.getSprites();
const tintSprites = globalScene.currentBattle.trainer.getTintSprites();
for (let i = 0; i < sprites.length; i++) {
const visible = !trainerSlot || !i === (trainerSlot === TrainerSlot.TRAINER) || sprites.length < 2;
[sprites[i], tintSprites[i]].map(sprite => {

View File

@ -4,7 +4,7 @@ import { BerryUsedEvent } from "#app/events/battle-scene";
import { getPokemonNameWithAffix } from "#app/messages";
import { BerryModifier } from "#app/modifier/modifier";
import i18next from "i18next";
import * as Utils from "#app/utils";
import { BooleanHolder } from "#app/utils";
import { FieldPhase } from "./field-phase";
import { CommonAnimPhase } from "./common-anim-phase";
import { globalScene } from "#app/global-scene";
@ -20,7 +20,7 @@ export class BerryPhase extends FieldPhase {
}, pokemon.isPlayer());
if (hasUsableBerry) {
const cancelled = new Utils.BooleanHolder(false);
const cancelled = new BooleanHolder(false);
pokemon.getOpponents().map(opp => applyAbAttrs(PreventBerryUseAbAttr, opp, cancelled));
if (cancelled.value) {
@ -44,7 +44,7 @@ export class BerryPhase extends FieldPhase {
globalScene.updateModifiers(pokemon.isPlayer());
applyAbAttrs(HealFromBerryUseAbAttr, pokemon, new Utils.BooleanHolder(false));
applyAbAttrs(HealFromBerryUseAbAttr, pokemon, new BooleanHolder(false));
}
}
});

View File

@ -6,13 +6,18 @@ import { PokemonPhase } from "./pokemon-phase";
export class CommonAnimPhase extends PokemonPhase {
private anim: CommonAnim | null;
private targetIndex: number | undefined;
private targetIndex?: BattlerIndex;
private playOnEmptyField: boolean;
constructor(battlerIndex?: BattlerIndex, targetIndex?: BattlerIndex, anim?: CommonAnim, playOnEmptyField = false) {
constructor(
battlerIndex?: BattlerIndex,
targetIndex?: BattlerIndex,
anim: CommonAnim | null = null,
playOnEmptyField = false,
) {
super(battlerIndex);
this.anim = anim!; // TODO: is this bang correct?
this.anim = anim;
this.targetIndex = targetIndex;
this.playOnEmptyField = playOnEmptyField;
}

View File

@ -10,11 +10,16 @@ export class DamageAnimPhase extends PokemonPhase {
private damageResult: DamageResult;
private critical: boolean;
constructor(battlerIndex: BattlerIndex, amount: number, damageResult?: DamageResult, critical = false) {
constructor(
battlerIndex: BattlerIndex,
amount: number,
damageResult: DamageResult = HitResult.EFFECTIVE,
critical = false,
) {
super(battlerIndex);
this.amount = amount;
this.damageResult = damageResult || HitResult.EFFECTIVE;
this.damageResult = damageResult;
this.critical = critical;
}

View File

@ -11,7 +11,7 @@ import PokemonInfoContainer from "#app/ui/pokemon-info-container";
import { Mode } from "#app/ui/ui";
import i18next from "i18next";
import SoundFade from "phaser3-rex-plugins/plugins/soundfade";
import * as Utils from "#app/utils";
import { fixedInt, getFrameMs, randInt } from "#app/utils";
import type { EggLapsePhase } from "./egg-lapse-phase";
import type { EggHatchData } from "#app/data/egg-hatch-data";
import { doShinySparkleAnim } from "#app/field/anims";
@ -306,17 +306,17 @@ export class EggHatchPhase extends Phase {
this.canSkip = false;
this.hatched = true;
if (this.evolutionBgm) {
SoundFade.fadeOut(globalScene, this.evolutionBgm, Utils.fixedInt(100));
SoundFade.fadeOut(globalScene, this.evolutionBgm, fixedInt(100));
}
for (let e = 0; e < 5; e++) {
globalScene.time.delayedCall(Utils.fixedInt(375 * e), () =>
globalScene.time.delayedCall(fixedInt(375 * e), () =>
globalScene.playSound("se/egg_hatch", { volume: 1 - e * 0.2 }),
);
}
this.eggLightraysOverlay.setVisible(true);
this.eggLightraysOverlay.play("egg_lightrays");
globalScene.tweens.add({
duration: Utils.fixedInt(125),
duration: fixedInt(125),
targets: this.eggHatchOverlay,
alpha: 1,
ease: "Cubic.easeIn",
@ -325,7 +325,7 @@ export class EggHatchPhase extends Phase {
this.canSkip = true;
},
});
globalScene.time.delayedCall(Utils.fixedInt(1500), () => {
globalScene.time.delayedCall(fixedInt(1500), () => {
this.canSkip = false;
if (!this.skipped) {
this.doReveal();
@ -363,46 +363,43 @@ export class EggHatchPhase extends Phase {
this.pokemonSprite.setPipelineData("shiny", this.pokemon.shiny);
this.pokemonSprite.setPipelineData("variant", this.pokemon.variant);
this.pokemonSprite.setVisible(true);
globalScene.time.delayedCall(Utils.fixedInt(250), () => {
globalScene.time.delayedCall(fixedInt(250), () => {
this.eggsToHatchCount--;
this.eggHatchHandler.eventTarget.dispatchEvent(new EggCountChangedEvent(this.eggsToHatchCount));
this.pokemon.cry();
if (isShiny) {
globalScene.time.delayedCall(Utils.fixedInt(500), () => {
globalScene.time.delayedCall(fixedInt(500), () => {
doShinySparkleAnim(this.pokemonShinySparkle, this.pokemon.variant);
});
}
globalScene.time.delayedCall(
Utils.fixedInt(!this.skipped ? (!isShiny ? 1250 : 1750) : !isShiny ? 250 : 750),
() => {
this.infoContainer.show(this.pokemon, false, this.skipped ? 2 : 1);
globalScene.time.delayedCall(fixedInt(!this.skipped ? (!isShiny ? 1250 : 1750) : !isShiny ? 250 : 750), () => {
this.infoContainer.show(this.pokemon, false, this.skipped ? 2 : 1);
globalScene.playSoundWithoutBgm("evolution_fanfare");
globalScene.playSoundWithoutBgm("evolution_fanfare");
globalScene.ui.showText(
i18next.t("egg:hatchFromTheEgg", {
pokemonName: this.pokemon.species.getExpandedSpeciesName(),
}),
null,
() => {
globalScene.gameData.updateSpeciesDexIvs(this.pokemon.species.speciesId, this.pokemon.ivs);
globalScene.gameData.setPokemonCaught(this.pokemon, true, true).then(() => {
globalScene.gameData.setEggMoveUnlocked(this.pokemon.species, this.eggMoveIndex).then(value => {
this.eggHatchData.setEggMoveUnlocked(value);
globalScene.ui.showText("", 0);
this.end();
});
globalScene.ui.showText(
i18next.t("egg:hatchFromTheEgg", {
pokemonName: this.pokemon.species.getExpandedSpeciesName(),
}),
null,
() => {
globalScene.gameData.updateSpeciesDexIvs(this.pokemon.species.speciesId, this.pokemon.ivs);
globalScene.gameData.setPokemonCaught(this.pokemon, true, true).then(() => {
globalScene.gameData.setEggMoveUnlocked(this.pokemon.species, this.eggMoveIndex).then(value => {
this.eggHatchData.setEggMoveUnlocked(value);
globalScene.ui.showText("", 0);
this.end();
});
},
null,
true,
3000,
);
},
);
});
},
null,
true,
3000,
);
});
});
globalScene.tweens.add({
duration: Utils.fixedInt(this.skipped ? 500 : 3000),
duration: fixedInt(this.skipped ? 500 : 3000),
targets: this.eggHatchOverlay,
alpha: 0,
ease: "Cubic.easeOut",
@ -427,9 +424,9 @@ export class EggHatchPhase extends Phase {
doSpray(intensity: number, offsetY?: number) {
globalScene.tweens.addCounter({
repeat: intensity,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
this.doSprayParticle(Utils.randInt(8), offsetY || 0);
this.doSprayParticle(randInt(8), offsetY || 0);
},
});
}
@ -448,12 +445,12 @@ export class EggHatchPhase extends Phase {
let f = 0;
let yOffset = 0;
const speed = 3 - Utils.randInt(8);
const amp = 24 + Utils.randInt(32);
const speed = 3 - randInt(8);
const amp = 24 + randInt(32);
const particleTimer = globalScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
updateParticle();
},

View File

@ -43,10 +43,10 @@ import { getNatureName } from "#app/data/nature";
export class EncounterPhase extends BattlePhase {
private loaded: boolean;
constructor(loaded?: boolean) {
constructor(loaded = false) {
super();
this.loaded = !!loaded;
this.loaded = loaded;
}
start() {

View File

@ -5,7 +5,7 @@ import { globalScene } from "#app/global-scene";
import type { SpeciesFormEvolution } from "#app/data/balance/pokemon-evolutions";
import { FusionSpeciesFormEvolution } from "#app/data/balance/pokemon-evolutions";
import type EvolutionSceneHandler from "#app/ui/evolution-scene-handler";
import * as Utils from "#app/utils";
import { fixedInt, getFrameMs, randInt } from "#app/utils";
import { Mode } from "#app/ui/ui";
import { cos, sin } from "#app/field/anims";
import type { PlayerPokemon } from "#app/field/pokemon";
@ -332,9 +332,9 @@ export class EvolutionPhase extends Phase {
() => this.end(),
null,
true,
Utils.fixedInt(4000),
fixedInt(4000),
);
globalScene.time.delayedCall(Utils.fixedInt(4250), () => globalScene.playBgm());
globalScene.time.delayedCall(fixedInt(4250), () => globalScene.playBgm());
});
});
};
@ -392,7 +392,7 @@ export class EvolutionPhase extends Phase {
globalScene.tweens.addCounter({
repeat: 64,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
if (f < 64) {
if (!(f & 7)) {
@ -411,7 +411,7 @@ export class EvolutionPhase extends Phase {
globalScene.tweens.addCounter({
repeat: 96,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
if (f < 96) {
if (f < 6) {
@ -461,7 +461,7 @@ export class EvolutionPhase extends Phase {
globalScene.tweens.addCounter({
repeat: 48,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
if (!f) {
for (let i = 0; i < 16; i++) {
@ -482,14 +482,14 @@ export class EvolutionPhase extends Phase {
globalScene.tweens.addCounter({
repeat: 48,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
if (!f) {
for (let i = 0; i < 8; i++) {
this.doSprayParticle(i);
}
} else if (f < 50) {
this.doSprayParticle(Utils.randInt(8));
this.doSprayParticle(randInt(8));
}
f++;
},
@ -506,7 +506,7 @@ export class EvolutionPhase extends Phase {
const particleTimer = globalScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
updateParticle();
},
@ -543,7 +543,7 @@ export class EvolutionPhase extends Phase {
const particleTimer = globalScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
updateParticle();
},
@ -575,7 +575,7 @@ export class EvolutionPhase extends Phase {
const particleTimer = globalScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
updateParticle();
},
@ -605,12 +605,12 @@ export class EvolutionPhase extends Phase {
let f = 0;
let yOffset = 0;
const speed = 3 - Utils.randInt(8);
const amp = 48 + Utils.randInt(64);
const speed = 3 - randInt(8);
const amp = 48 + randInt(64);
const particleTimer = globalScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
duration: getFrameMs(1),
onRepeat: () => {
updateParticle();
},

View File

@ -2,7 +2,7 @@ import { globalScene } from "#app/global-scene";
import { getPokemonNameWithAffix } from "#app/messages";
import { ExpBoosterModifier } from "#app/modifier/modifier";
import i18next from "i18next";
import * as Utils from "#app/utils";
import { NumberHolder } from "#app/utils";
import { PlayerPartyMemberPokemonPhase } from "./player-party-member-pokemon-phase";
import { LevelUpPhase } from "./level-up-phase";
@ -19,7 +19,7 @@ export class ExpPhase extends PlayerPartyMemberPokemonPhase {
super.start();
const pokemon = this.getPokemon();
const exp = new Utils.NumberHolder(this.expValue);
const exp = new NumberHolder(this.expValue);
globalScene.applyModifiers(ExpBoosterModifier, true, exp);
exp.value = Math.floor(exp.value);
globalScene.ui.showText(

View File

@ -1,5 +1,5 @@
import { globalScene } from "#app/global-scene";
import * as Utils from "../utils";
import { fixedInt } from "#app/utils";
import { achvs } from "../system/achv";
import type { SpeciesFormChange } from "../data/pokemon-forms";
import { getSpeciesFormChangeMessage } from "../data/pokemon-forms";
@ -9,7 +9,7 @@ import type PartyUiHandler from "../ui/party-ui-handler";
import { getPokemonNameWithAffix } from "../messages";
import { EndEvolutionPhase } from "./end-evolution-phase";
import { EvolutionPhase } from "./evolution-phase";
import { BattlerTagType } from "#app/enums/battler-tag-type";
import { BattlerTagType } from "#enums/battler-tag-type";
import { SpeciesFormKey } from "#enums/species-form-key";
export class FormChangePhase extends EvolutionPhase {
@ -151,9 +151,9 @@ export class FormChangePhase extends EvolutionPhase {
() => this.end(),
null,
true,
Utils.fixedInt(delay),
fixedInt(delay),
);
globalScene.time.delayedCall(Utils.fixedInt(delay + 250), () =>
globalScene.time.delayedCall(fixedInt(delay + 250), () =>
globalScene.playBgm(),
);
});

View File

@ -20,7 +20,7 @@ import { UnlockPhase } from "#app/phases/unlock-phase";
import { achvs, ChallengeAchv } from "#app/system/achv";
import { Unlockables } from "#app/system/unlockables";
import { Mode } from "#app/ui/ui";
import * as Utils from "#app/utils";
import { isLocal, isLocalServerConnected } from "#app/utils";
import { PlayerGender } from "#enums/player-gender";
import { TrainerType } from "#enums/trainer-type";
import i18next from "i18next";
@ -219,7 +219,7 @@ export class GameOverPhase extends BattlePhase {
/* Added a local check to see if the game is running offline
If Online, execute apiFetch as intended
If Offline, execute offlineNewClear() only for victory, a localStorage implementation of newClear daily run checks */
if (!Utils.isLocal || Utils.isLocalServerConnected) {
if (!isLocal || isLocalServerConnected) {
pokerogueApi.savedata.session
.newclear({
slot: globalScene.sessionSlotId,

View File

@ -5,26 +5,26 @@ import { Phase } from "#app/phase";
import { handleTutorial, Tutorial } from "#app/tutorial";
import { Mode } from "#app/ui/ui";
import i18next, { t } from "i18next";
import * as Utils from "#app/utils";
import { getCookie, sessionIdKey, executeIf, removeCookie } from "#app/utils";
import { SelectGenderPhase } from "./select-gender-phase";
import { UnavailablePhase } from "./unavailable-phase";
export class LoginPhase extends Phase {
private showText: boolean;
constructor(showText?: boolean) {
constructor(showText = true) {
super();
this.showText = showText === undefined || !!showText;
this.showText = showText;
}
start(): void {
super.start();
const hasSession = !!Utils.getCookie(Utils.sessionIdKey);
const hasSession = !!getCookie(sessionIdKey);
globalScene.ui.setMode(Mode.LOADING, { buttonActions: [] });
Utils.executeIf(bypassLogin || hasSession, updateUserInfo).then(response => {
executeIf(bypassLogin || hasSession, updateUserInfo).then(response => {
const success = response ? response[0] : false;
const statusCode = response ? response[1] : null;
if (!success) {
@ -38,7 +38,7 @@ export class LoginPhase extends Phase {
const loadData = () => {
updateUserInfo().then(success => {
if (!success[0]) {
Utils.removeCookie(Utils.sessionIdKey);
removeCookie(sessionIdKey);
globalScene.reset(true, true);
return;
}
@ -60,7 +60,7 @@ export class LoginPhase extends Phase {
globalScene.ui.playSelect();
updateUserInfo().then(success => {
if (!success[0]) {
Utils.removeCookie(Utils.sessionIdKey);
removeCookie(sessionIdKey);
globalScene.reset(true, true);
return;
}
@ -89,7 +89,7 @@ export class LoginPhase extends Phase {
],
});
} else if (statusCode === 401) {
Utils.removeCookie(Utils.sessionIdKey);
removeCookie(sessionIdKey);
globalScene.reset(true, true);
} else {
globalScene.unshiftPhase(new UnavailablePhase());

View File

@ -3,9 +3,9 @@ import { Phase } from "#app/phase";
export class MessagePhase extends Phase {
private text: string;
private callbackDelay: number | null;
private prompt: boolean | null;
private promptDelay: number | null;
private callbackDelay?: number | null;
private prompt?: boolean | null;
private promptDelay?: number | null;
private speaker?: string;
constructor(
@ -18,9 +18,9 @@ export class MessagePhase extends Phase {
super();
this.text = text;
this.callbackDelay = callbackDelay!; // TODO: is this bang correct?
this.prompt = prompt!; // TODO: is this bang correct?
this.promptDelay = promptDelay!; // TODO: is this bang correct?
this.callbackDelay = callbackDelay;
this.prompt = prompt;
this.promptDelay = promptDelay;
this.speaker = speaker;
}

View File

@ -2,7 +2,7 @@ import { globalScene } from "#app/global-scene";
import { ArenaTagType } from "#app/enums/arena-tag-type";
import { MoneyMultiplierModifier } from "#app/modifier/modifier";
import i18next from "i18next";
import * as Utils from "#app/utils";
import { NumberHolder } from "#app/utils";
import { BattlePhase } from "./battle-phase";
export class MoneyRewardPhase extends BattlePhase {
@ -15,7 +15,7 @@ export class MoneyRewardPhase extends BattlePhase {
}
start() {
const moneyAmount = new Utils.NumberHolder(globalScene.getWaveMoneyAmount(this.moneyMultiplier));
const moneyAmount = new NumberHolder(globalScene.getWaveMoneyAmount(this.moneyMultiplier));
globalScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);

View File

@ -1,50 +0,0 @@
import { globalScene } from "#app/global-scene";
import { initMoveAnim, loadMoveAnimAssets, MoveAnim } from "#app/data/battle-anims";
import { allMoves, SelfStatusMove } from "#app/data/moves/move";
import { Moves } from "#app/enums/moves";
import * as Utils from "#app/utils";
import { BattlePhase } from "./battle-phase";
export class MoveAnimTestPhase extends BattlePhase {
private moveQueue: Moves[];
constructor(moveQueue?: Moves[]) {
super();
this.moveQueue = moveQueue || Utils.getEnumValues(Moves).slice(1);
}
start() {
const moveQueue = this.moveQueue.slice(0);
this.playMoveAnim(moveQueue, true);
}
playMoveAnim(moveQueue: Moves[], player: boolean) {
const moveId = player ? moveQueue[0] : moveQueue.shift();
if (moveId === undefined) {
this.playMoveAnim(this.moveQueue.slice(0), true);
return;
}
if (player) {
console.log(Moves[moveId]);
}
initMoveAnim(moveId).then(() => {
loadMoveAnimAssets([moveId], true).then(() => {
const user = player ? globalScene.getPlayerPokemon()! : globalScene.getEnemyPokemon()!;
const target =
player !== allMoves[moveId] instanceof SelfStatusMove
? globalScene.getEnemyPokemon()!
: globalScene.getPlayerPokemon()!;
new MoveAnim(moveId, user, target.getBattlerIndex()).play(allMoves[moveId].hitsSubstitute(user, target), () => {
// TODO: are the bangs correct here?
if (player) {
this.playMoveAnim(moveQueue, false);
} else {
this.playMoveAnim(moveQueue, true);
}
});
});
});
}
}

View File

@ -26,6 +26,7 @@ import {
} from "#app/data/battler-tags";
import type { MoveAttr } from "#app/data/moves/move";
import {
AddArenaTrapTagAttr,
applyFilteredMoveAttrs,
applyMoveAttrs,
AttackMove,
@ -209,12 +210,12 @@ export class MoveEffectPhase extends PokemonPhase {
targets.some(t => t.hasAbilityWithAttr(ReflectStatusMoveAbAttr) || !!t.getTag(BattlerTagType.MAGIC_COAT));
/**
* If no targets are left for the move to hit (FAIL), or the invoked move is non-reflectable, single-target
* If no targets are left for the move to hit and it is not a hazard move (FAIL), or the invoked move is non-reflectable, single-target
* (and not random target) and failed the hit check against its target (MISS), log the move
* as FAILed or MISSed (depending on the conditions above) and end this phase.
*/
if (
!hasActiveTargets ||
(!hasActiveTargets && !move.hasAttr(AddArenaTrapTagAttr)) ||
(!mayBounce &&
!move.hasAttr(VariableTargetAttr) &&
!move.isMultiTarget() &&
@ -239,18 +240,28 @@ export class MoveEffectPhase extends PokemonPhase {
return this.end();
}
const playOnEmptyField = globalScene.currentBattle?.mysteryEncounter?.hasBattleAnimationsWithoutTargets ?? false;
// Move animation only needs one target
new MoveAnim(move.id as Moves, user, this.getFirstTarget()!.getBattlerIndex(), playOnEmptyField).play(
move.hitsSubstitute(user, this.getFirstTarget()!),
() => {
/** Has the move successfully hit a target (for damage) yet? */
let hasHit = false;
const playOnEmptyField =
(globalScene.currentBattle?.mysteryEncounter?.hasBattleAnimationsWithoutTargets ?? false) ||
(!hasActiveTargets && move.hasAttr(AddArenaTrapTagAttr));
// Move animation only needs one target. The attacker is used as a fallback.
new MoveAnim(
move.id as Moves,
user,
this.getFirstTarget()?.getBattlerIndex() ?? BattlerIndex.ATTACKER,
playOnEmptyField,
).play(move.hitsSubstitute(user, this.getFirstTarget()!), () => {
/** Has the move successfully hit a target (for damage) yet? */
let hasHit = false;
// Prevent ENEMY_SIDE targeted moves from occurring twice in double battles
// and check which target will magic bounce.
const trueTargets: Pokemon[] =
move.moveTarget !== MoveTarget.ENEMY_SIDE
// Prevent ENEMY_SIDE targeted moves from occurring twice in double battles
// and check which target will magic bounce.
// In the event that the move is a hazard move, there may be no target and the move should still succeed.
// In this case, the user is used as the "target" to prevent a crash.
// This should not affect normal execution of the move otherwise.
const trueTargets: Pokemon[] =
!hasActiveTargets && move.hasAttr(AddArenaTrapTagAttr)
? [user]
: move.moveTarget !== MoveTarget.ENEMY_SIDE
? targets
: (() => {
const magicCoatTargets = targets.filter(
@ -264,62 +275,63 @@ export class MoveEffectPhase extends PokemonPhase {
return [magicCoatTargets[0]];
})();
const queuedPhases: Phase[] = [];
for (const target of trueTargets) {
/** The {@linkcode ArenaTagSide} to which the target belongs */
const targetSide = target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY;
/** Has the invoked move been cancelled by conditional protection (e.g Quick Guard)? */
const hasConditionalProtectApplied = new BooleanHolder(false);
/** Does the applied conditional protection bypass Protect-ignoring effects? */
const bypassIgnoreProtect = new BooleanHolder(false);
/** If the move is not targeting a Pokemon on the user's side, try to apply conditional protection effects */
if (!this.move.getMove().isAllyTarget()) {
globalScene.arena.applyTagsForSide(
ConditionalProtectTag,
targetSide,
false,
hasConditionalProtectApplied,
user,
target,
move.id,
bypassIgnoreProtect,
);
}
const queuedPhases: Phase[] = [];
for (const target of trueTargets) {
/** The {@linkcode ArenaTagSide} to which the target belongs */
const targetSide = target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY;
/** Has the invoked move been cancelled by conditional protection (e.g Quick Guard)? */
const hasConditionalProtectApplied = new BooleanHolder(false);
/** Does the applied conditional protection bypass Protect-ignoring effects? */
const bypassIgnoreProtect = new BooleanHolder(false);
/** If the move is not targeting a Pokemon on the user's side, try to apply conditional protection effects */
if (!this.move.getMove().isAllyTarget()) {
globalScene.arena.applyTagsForSide(
ConditionalProtectTag,
targetSide,
false,
hasConditionalProtectApplied,
user,
target,
move.id,
bypassIgnoreProtect,
);
}
/** Is the target protected by Protect, etc. or a relevant conditional protection effect? */
const isProtected =
![MoveTarget.ENEMY_SIDE, MoveTarget.BOTH_SIDES].includes(this.move.getMove().moveTarget) &&
(bypassIgnoreProtect.value || !this.move.getMove().checkFlag(MoveFlags.IGNORE_PROTECT, user, target)) &&
(bypassIgnoreProtect.value ||
!this.move.getMove().doesFlagEffectApply({ flag: MoveFlags.IGNORE_PROTECT, user, target })) &&
(hasConditionalProtectApplied.value ||
(!target.findTags(t => t instanceof DamageProtectedTag).length &&
target.findTags(t => t instanceof ProtectedTag).find(t => target.lapseTag(t.tagType))) ||
(this.move.getMove().category !== MoveCategory.STATUS &&
target.findTags(t => t instanceof DamageProtectedTag).find(t => target.lapseTag(t.tagType))));
/** Is the target hidden by the effects of its Commander ability? */
const isCommanding =
globalScene.currentBattle.double &&
target.getAlly()?.getTag(BattlerTagType.COMMANDED)?.getSourcePokemon() === target;
/** Is the target hidden by the effects of its Commander ability? */
const isCommanding =
globalScene.currentBattle.double &&
target.getAlly()?.getTag(BattlerTagType.COMMANDED)?.getSourcePokemon() === target;
/** Is the target reflecting status moves from the magic coat move? */
const isReflecting = !!target.getTag(BattlerTagType.MAGIC_COAT);
/** Is the target reflecting status moves from the magic coat move? */
const isReflecting = !!target.getTag(BattlerTagType.MAGIC_COAT);
/** Is the target's magic bounce ability not ignored and able to reflect this move? */
const canMagicBounce =
!isReflecting &&
!move.checkFlag(MoveFlags.IGNORE_ABILITIES, user, target) &&
!move.doesFlagEffectApply({ flag: MoveFlags.IGNORE_ABILITIES, user, target }) &&
target.hasAbilityWithAttr(ReflectStatusMoveAbAttr);
const semiInvulnerableTag = target.getTag(SemiInvulnerableTag);
const semiInvulnerableTag = target.getTag(SemiInvulnerableTag);
/** Is the target reflecting the effect, not protected, and not in an semi-invulnerable state?*/
const willBounce =
!isProtected &&
!this.reflected &&
!isCommanding &&
move.hasFlag(MoveFlags.REFLECTABLE) &&
(isReflecting || canMagicBounce) &&
!semiInvulnerableTag;
/** Is the target reflecting the effect, not protected, and not in an semi-invulnerable state?*/
const willBounce =
!isProtected &&
!this.reflected &&
!isCommanding &&
move.hasFlag(MoveFlags.REFLECTABLE) &&
(isReflecting || canMagicBounce) &&
!semiInvulnerableTag;
// If the move will bounce, then queue the bounce and move on to the next target
if (!target.switchOutStatus && willBounce) {
@ -337,171 +349,171 @@ export class MoveEffectPhase extends PokemonPhase {
queuedPhases.push(new HideAbilityPhase());
}
queuedPhases.push(
new MovePhase(target, newTargets, new PokemonMove(move.id, 0, 0, true), true, true, true),
queuedPhases.push(new MovePhase(target, newTargets, new PokemonMove(move.id, 0, 0, true), true, true, true));
continue;
}
/** Is the pokemon immune due to an ablility, and also not in a semi invulnerable state? */
const isImmune =
target.hasAbilityWithAttr(TypeImmunityAbAttr) &&
target.getAbility()?.getAttrs(TypeImmunityAbAttr)?.[0]?.getImmuneType() === user.getMoveType(move) &&
!semiInvulnerableTag;
/**
* If the move missed a target, stop all future hits against that target
* and move on to the next target (if there is one).
*/
if (
target.switchOutStatus ||
isCommanding ||
(!isImmune &&
!isProtected &&
!targetHitChecks[target.getBattlerIndex()] &&
!move.hasAttr(AddArenaTrapTagAttr))
) {
this.stopMultiHit(target);
if (!target.switchOutStatus) {
globalScene.queueMessage(
i18next.t("battle:attackMissed", {
pokemonNameWithAffix: getPokemonNameWithAffix(target),
}),
);
continue;
}
/** Is the pokemon immune due to an ablility, and also not in a semi invulnerable state? */
const isImmune =
target.hasAbilityWithAttr(TypeImmunityAbAttr) &&
target.getAbility()?.getAttrs(TypeImmunityAbAttr)?.[0]?.getImmuneType() === user.getMoveType(move) &&
!semiInvulnerableTag;
/**
* If the move missed a target, stop all future hits against that target
* and move on to the next target (if there is one).
*/
if (
target.switchOutStatus ||
isCommanding ||
(!isImmune && !isProtected && !targetHitChecks[target.getBattlerIndex()])
) {
this.stopMultiHit(target);
if (!target.switchOutStatus) {
globalScene.queueMessage(
i18next.t("battle:attackMissed", {
pokemonNameWithAffix: getPokemonNameWithAffix(target),
}),
);
}
if (moveHistoryEntry.result === MoveResult.PENDING) {
moveHistoryEntry.result = MoveResult.MISS;
}
user.pushMoveHistory(moveHistoryEntry);
applyMoveAttrs(MissEffectAttr, user, null, move);
continue;
}
/** Does this phase represent the invoked move's first strike? */
const firstHit = user.turnData.hitsLeft === user.turnData.hitCount;
// Only log the move's result on the first strike
if (firstHit) {
user.pushMoveHistory(moveHistoryEntry);
}
/**
* Since all fail/miss checks have applied, the move is considered successfully applied.
* It's worth noting that if the move has no effect or is protected against, this assignment
* is overwritten and the move is logged as a FAIL.
*/
moveHistoryEntry.result = MoveResult.SUCCESS;
/**
* Stores the result of applying the invoked move to the target.
* If the target is protected, the result is always `NO_EFFECT`.
* Otherwise, the hit result is based on type effectiveness, immunities,
* and other factors that may negate the attack or status application.
*
* Internally, the call to {@linkcode Pokemon.apply} is where damage is calculated
* (for attack moves) and the target's HP is updated. However, this isn't
* made visible to the user until the resulting {@linkcode DamagePhase}
* is invoked.
*/
const hitResult = !isProtected ? target.apply(user, move) : HitResult.NO_EFFECT;
/** Does {@linkcode hitResult} indicate that damage was dealt to the target? */
const dealsDamage = [
HitResult.EFFECTIVE,
HitResult.SUPER_EFFECTIVE,
HitResult.NOT_VERY_EFFECTIVE,
HitResult.ONE_HIT_KO,
].includes(hitResult);
/** Is this target the first one hit by the move on its current strike? */
const firstTarget = dealsDamage && !hasHit;
if (firstTarget) {
hasHit = true;
}
/**
* If the move has no effect on the target (i.e. the target is protected or immune),
* change the logged move result to FAIL.
*/
if (hitResult === HitResult.NO_EFFECT) {
moveHistoryEntry.result = MoveResult.FAIL;
}
/** Does this phase represent the invoked move's last strike? */
const lastHit = user.turnData.hitsLeft === 1 || !this.getFirstTarget()?.isActive();
/**
* If the user can change forms by using the invoked move,
* it only changes forms after the move's last hit
* (see Relic Song's interaction with Parental Bond when used by Meloetta).
*/
if (lastHit) {
globalScene.triggerPokemonFormChange(user, SpeciesFormChangePostMoveTrigger);
/**
* Multi-Lens, Multi Hit move and Parental Bond check for PostDamageAbAttr
* other damage source are calculated in damageAndUpdate in pokemon.ts
*/
if (user.turnData.hitCount > 1) {
applyPostDamageAbAttrs(PostDamageAbAttr, target, 0, target.hasPassive(), false, [], user);
}
}
applyFilteredMoveAttrs(
(attr: MoveAttr) =>
attr instanceof MoveEffectAttr &&
attr.trigger === MoveEffectTrigger.PRE_APPLY &&
(!attr.firstHitOnly || firstHit) &&
(!attr.lastHitOnly || lastHit) &&
hitResult !== HitResult.NO_EFFECT,
user,
target,
move,
);
if (hitResult !== HitResult.FAIL) {
this.applySelfTargetEffects(user, target, firstHit, lastHit);
if (hitResult !== HitResult.NO_EFFECT) {
this.applyPostApplyEffects(user, target, firstHit, lastHit);
this.applyHeldItemFlinchCheck(user, target, dealsDamage);
this.applySuccessfulAttackEffects(user, target, firstHit, lastHit, !!isProtected, hitResult, firstTarget);
} else {
applyMoveAttrs(NoEffectAttr, user, null, move);
}
if (moveHistoryEntry.result === MoveResult.PENDING) {
moveHistoryEntry.result = MoveResult.MISS;
}
user.pushMoveHistory(moveHistoryEntry);
applyMoveAttrs(MissEffectAttr, user, null, move);
continue;
}
// Apply queued phases
if (queuedPhases.length) {
globalScene.appendToPhase(queuedPhases, MoveEndPhase);
}
// Apply the move's POST_TARGET effects on the move's last hit, after all targeted effects have resolved
if (user.turnData.hitsLeft === 1 || !this.getFirstTarget()?.isActive()) {
applyFilteredMoveAttrs(
(attr: MoveAttr) => attr instanceof MoveEffectAttr && attr.trigger === MoveEffectTrigger.POST_TARGET,
user,
null,
move,
);
/** Does this phase represent the invoked move's first strike? */
const firstHit = user.turnData.hitsLeft === user.turnData.hitCount;
// Only log the move's result on the first strike
if (firstHit) {
user.pushMoveHistory(moveHistoryEntry);
}
/**
* Remove the target's substitute (if it exists and has expired)
* after all targeted effects have applied.
* This prevents blocked effects from applying until after this hit resolves.
* Since all fail/miss checks have applied, the move is considered successfully applied.
* It's worth noting that if the move has no effect or is protected against, this assignment
* is overwritten and the move is logged as a FAIL.
*/
targets.forEach(target => {
const substitute = target.getTag(SubstituteTag);
if (substitute && substitute.hp <= 0) {
target.lapseTag(BattlerTagType.SUBSTITUTE);
}
});
moveHistoryEntry.result = MoveResult.SUCCESS;
const moveType = user.getMoveType(move, true);
if (move.category !== MoveCategory.STATUS && !user.stellarTypesBoosted.includes(moveType)) {
user.stellarTypesBoosted.push(moveType);
/**
* Stores the result of applying the invoked move to the target.
* If the target is protected, the result is always `NO_EFFECT`.
* Otherwise, the hit result is based on type effectiveness, immunities,
* and other factors that may negate the attack or status application.
*
* Internally, the call to {@linkcode Pokemon.apply} is where damage is calculated
* (for attack moves) and the target's HP is updated. However, this isn't
* made visible to the user until the resulting {@linkcode DamagePhase}
* is invoked.
*/
const hitResult = !isProtected ? target.apply(user, move) : HitResult.NO_EFFECT;
/** Does {@linkcode hitResult} indicate that damage was dealt to the target? */
const dealsDamage = [
HitResult.EFFECTIVE,
HitResult.SUPER_EFFECTIVE,
HitResult.NOT_VERY_EFFECTIVE,
HitResult.ONE_HIT_KO,
].includes(hitResult);
/** Is this target the first one hit by the move on its current strike? */
const firstTarget = dealsDamage && !hasHit;
if (firstTarget) {
hasHit = true;
}
this.end();
},
);
/**
* If the move has no effect on the target (i.e. the target is protected or immune),
* change the logged move result to FAIL.
*/
if (hitResult === HitResult.NO_EFFECT) {
moveHistoryEntry.result = MoveResult.FAIL;
}
/** Does this phase represent the invoked move's last strike? */
const lastHit = user.turnData.hitsLeft === 1 || !this.getFirstTarget()?.isActive();
/**
* If the user can change forms by using the invoked move,
* it only changes forms after the move's last hit
* (see Relic Song's interaction with Parental Bond when used by Meloetta).
*/
if (lastHit) {
globalScene.triggerPokemonFormChange(user, SpeciesFormChangePostMoveTrigger);
/**
* Multi-Lens, Multi Hit move and Parental Bond check for PostDamageAbAttr
* other damage source are calculated in damageAndUpdate in pokemon.ts
*/
if (user.turnData.hitCount > 1) {
applyPostDamageAbAttrs(PostDamageAbAttr, target, 0, target.hasPassive(), false, [], user);
}
}
applyFilteredMoveAttrs(
(attr: MoveAttr) =>
attr instanceof MoveEffectAttr &&
attr.trigger === MoveEffectTrigger.PRE_APPLY &&
(!attr.firstHitOnly || firstHit) &&
(!attr.lastHitOnly || lastHit) &&
hitResult !== HitResult.NO_EFFECT,
user,
target,
move,
);
if (hitResult !== HitResult.FAIL) {
this.applySelfTargetEffects(user, target, firstHit, lastHit);
if (hitResult !== HitResult.NO_EFFECT) {
this.applyPostApplyEffects(user, target, firstHit, lastHit);
this.applyHeldItemFlinchCheck(user, target, dealsDamage);
this.applySuccessfulAttackEffects(user, target, firstHit, lastHit, !!isProtected, hitResult, firstTarget);
} else {
applyMoveAttrs(NoEffectAttr, user, null, move);
}
}
}
// Apply queued phases
if (queuedPhases.length) {
globalScene.appendToPhase(queuedPhases, MoveEndPhase);
}
// Apply the move's POST_TARGET effects on the move's last hit, after all targeted effects have resolved
if (user.turnData.hitsLeft === 1 || !this.getFirstTarget()?.isActive()) {
applyFilteredMoveAttrs(
(attr: MoveAttr) => attr instanceof MoveEffectAttr && attr.trigger === MoveEffectTrigger.POST_TARGET,
user,
null,
move,
);
}
/**
* Remove the target's substitute (if it exists and has expired)
* after all targeted effects have applied.
* This prevents blocked effects from applying until after this hit resolves.
*/
targets.forEach(target => {
const substitute = target.getTag(SubstituteTag);
if (substitute && substitute.hp <= 0) {
target.lapseTag(BattlerTagType.SUBSTITUTE);
}
});
const moveType = user.getMoveType(move, true);
if (move.category !== MoveCategory.STATUS && !user.stellarTypesBoosted.includes(moveType)) {
user.stellarTypesBoosted.push(moveType);
}
this.end();
});
}
public override end(): void {

View File

@ -2,11 +2,18 @@ import { globalScene } from "#app/global-scene";
import { BattlerTagLapseType } from "#app/data/battler-tags";
import { PokemonPhase } from "./pokemon-phase";
import type { BattlerIndex } from "#app/battle";
import { applyPostSummonAbAttrs, PostSummonRemoveEffectAbAttr } from "#app/data/ability";
import type Pokemon from "#app/field/pokemon";
export class MoveEndPhase extends PokemonPhase {
private wasFollowUp: boolean;
constructor(battlerIndex: BattlerIndex, wasFollowUp: boolean = false) {
/** Targets from the preceding MovePhase */
private targets: Pokemon[];
constructor(battlerIndex: BattlerIndex, targets: Pokemon[], wasFollowUp = false) {
super(battlerIndex);
this.targets = targets;
this.wasFollowUp = wasFollowUp;
}
@ -17,9 +24,15 @@ export class MoveEndPhase extends PokemonPhase {
if (!this.wasFollowUp && pokemon?.isActive(true)) {
pokemon.lapseTags(BattlerTagLapseType.AFTER_MOVE);
}
globalScene.arena.setIgnoreAbilities(false);
// Remove effects which were set on a Pokemon which removes them on summon (i.e. via Mold Breaker)
for (const target of this.targets) {
if (target) {
applyPostSummonAbAttrs(PostSummonRemoveEffectAbAttr, target);
}
}
this.end();
}
}

View File

@ -15,6 +15,7 @@ import type { DelayedAttackTag } from "#app/data/arena-tag";
import { CommonAnim } from "#app/data/battle-anims";
import { BattlerTagLapseType, CenterOfAttentionTag } from "#app/data/battler-tags";
import {
AddArenaTrapTagAttr,
allMoves,
applyMoveAttrs,
BypassRedirectAttr,
@ -168,7 +169,11 @@ export class MovePhase extends BattlePhase {
// Check move to see if arena.ignoreAbilities should be true.
if (!this.followUp || this.reflected) {
if (this.move.getMove().checkFlag(MoveFlags.IGNORE_ABILITIES, this.pokemon, null)) {
if (
this.move
.getMove()
.doesFlagEffectApply({ flag: MoveFlags.IGNORE_ABILITIES, user: this.pokemon, isFollowUp: this.followUp })
) {
globalScene.arena.setIgnoreAbilities(true, this.pokemon.getBattlerIndex());
}
}
@ -201,7 +206,10 @@ export class MovePhase extends BattlePhase {
const targets = this.getActiveTargetPokemon();
const moveQueue = this.pokemon.getMoveQueue();
if (targets.length === 0 || (moveQueue.length && moveQueue[0].move === Moves.NONE)) {
if (
(targets.length === 0 && !this.move.getMove().hasAttr(AddArenaTrapTagAttr)) ||
(moveQueue.length && moveQueue[0].move === Moves.NONE)
) {
this.showMoveText();
this.showFailedText();
this.cancel();
@ -227,7 +235,7 @@ export class MovePhase extends BattlePhase {
(!this.pokemon.randSeedInt(4) || Overrides.STATUS_ACTIVATION_OVERRIDE === true) &&
Overrides.STATUS_ACTIVATION_OVERRIDE !== false;
break;
case StatusEffect.SLEEP:
case StatusEffect.SLEEP: {
applyMoveAttrs(BypassSleepAttr, this.pokemon, null, this.move.getMove());
const turnsRemaining = new NumberHolder(this.pokemon.status.sleepTurnsRemaining ?? 0);
applyAbAttrs(
@ -242,6 +250,7 @@ export class MovePhase extends BattlePhase {
healed = this.pokemon.status.sleepTurnsRemaining <= 0;
activated = !healed && !this.pokemon.getTag(BattlerTagType.BYPASS_SLEEP);
break;
}
case StatusEffect.FREEZE:
healed =
!!this.move
@ -468,7 +477,9 @@ export class MovePhase extends BattlePhase {
* Queues a {@linkcode MoveEndPhase} and then ends the phase
*/
public end(): void {
globalScene.unshiftPhase(new MoveEndPhase(this.pokemon.getBattlerIndex(), this.followUp));
globalScene.unshiftPhase(
new MoveEndPhase(this.pokemon.getBattlerIndex(), this.getActiveTargetPokemon(), this.followUp),
);
super.end();
}

View File

@ -26,8 +26,7 @@ import { TrainerSlot } from "#enums/trainer-slot";
import { IvScannerModifier } from "../modifier/modifier";
import { Phase } from "../phase";
import { Mode } from "../ui/ui";
import * as Utils from "../utils";
import { isNullOrUndefined } from "../utils";
import { isNullOrUndefined, randSeedItem } from "#app/utils";
/**
* Will handle (in order):
@ -387,7 +386,7 @@ export class MysteryEncounterBattlePhase extends Phase {
const trainer = globalScene.currentBattle.trainer;
let message: string;
globalScene.executeWithSeedOffset(
() => (message = Utils.randSeedItem(encounterMessages)),
() => (message = randSeedItem(encounterMessages)),
globalScene.currentBattle.mysteryEncounter?.getSeedOffset(),
);
message = message!; // tell TS compiler it's defined now

View File

@ -4,10 +4,6 @@ import { getRandomWeatherType } from "#app/data/weather";
import { NextEncounterPhase } from "./next-encounter-phase";
export class NewBiomeEncounterPhase extends NextEncounterPhase {
constructor() {
super();
}
doEncounter(): void {
globalScene.playBgm(undefined, true);

View File

@ -2,10 +2,6 @@ import { globalScene } from "#app/global-scene";
import { EncounterPhase } from "./encounter-phase";
export class NextEncounterPhase extends EncounterPhase {
constructor() {
super();
}
start() {
super.start();
}

View File

@ -6,6 +6,9 @@ import { StatusEffect } from "#app/enums/status-effect";
import type Pokemon from "#app/field/pokemon";
import { getPokemonNameWithAffix } from "#app/messages";
import { PokemonPhase } from "./pokemon-phase";
import { SpeciesFormChangeStatusEffectTrigger } from "#app/data/pokemon-forms";
import { applyPostSetStatusAbAttrs, PostSetStatusAbAttr } from "#app/data/ability";
import { isNullOrUndefined } from "#app/utils";
export class ObtainStatusEffectPhase extends PokemonPhase {
private statusEffect?: StatusEffect;
@ -44,6 +47,12 @@ export class ObtainStatusEffectPhase extends PokemonPhase {
this.sourceText ?? undefined,
),
);
if (!isNullOrUndefined(this.statusEffect) && this.statusEffect !== StatusEffect.FAINT) {
globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeStatusEffectTrigger, true);
// If mold breaker etc was used to set this status, it shouldn't apply to abilities activated afterwards
globalScene.arena.setIgnoreAbilities(false);
applyPostSetStatusAbAttrs(PostSetStatusAbAttr, pokemon, this.statusEffect, this.sourcePokemon);
}
this.end();
});
return;

View File

@ -1,5 +1,5 @@
import { globalScene } from "#app/global-scene";
import * as Utils from "#app/utils";
import { fixedInt } from "#app/utils";
import { BattlePhase } from "./battle-phase";
export class PartyHealPhase extends BattlePhase {
@ -28,7 +28,7 @@ export class PartyHealPhase extends BattlePhase {
pokemon.updateInfo(true);
}
const healSong = globalScene.playSoundWithoutBgm("heal");
globalScene.time.delayedCall(Utils.fixedInt(healSong.totalDuration * 1000), () => {
globalScene.time.delayedCall(fixedInt(healSong.totalDuration * 1000), () => {
healSong.destroy();
if (this.resumeBgm && bgmPlaying) {
globalScene.playBgm();

View File

@ -8,18 +8,18 @@ import { Species } from "#enums/species";
export class PokemonAnimPhase extends BattlePhase {
/** The type of animation to play in this phase */
private key: PokemonAnimType;
protected key: PokemonAnimType;
/** The Pokemon to which this animation applies */
private pokemon: Pokemon;
protected pokemon: Pokemon;
/** Any other field sprites affected by this animation */
private fieldAssets: Phaser.GameObjects.Sprite[];
protected fieldAssets: Phaser.GameObjects.Sprite[];
constructor(key: PokemonAnimType, pokemon: Pokemon, fieldAssets?: Phaser.GameObjects.Sprite[]) {
constructor(key: PokemonAnimType, pokemon: Pokemon, fieldAssets: Phaser.GameObjects.Sprite[] = []) {
super();
this.key = key;
this.pokemon = pokemon;
this.fieldAssets = fieldAssets ?? [];
this.fieldAssets = fieldAssets;
}
start(): void {

View File

@ -8,7 +8,7 @@ import { getPokemonNameWithAffix } from "#app/messages";
import { HealingBoosterModifier } from "#app/modifier/modifier";
import { HealAchv } from "#app/system/achv";
import i18next from "i18next";
import * as Utils from "#app/utils";
import { NumberHolder } from "#app/utils";
import { CommonAnimPhase } from "./common-anim-phase";
import { BattlerTagType } from "#app/enums/battler-tag-type";
import type { HealBlockTag } from "#app/data/battler-tags";
@ -72,11 +72,11 @@ export class PokemonHealPhase extends CommonAnimPhase {
return super.end();
}
if (healOrDamage) {
const hpRestoreMultiplier = new Utils.NumberHolder(1);
const hpRestoreMultiplier = new NumberHolder(1);
if (!this.revive) {
globalScene.applyModifiers(HealingBoosterModifier, this.player, hpRestoreMultiplier);
}
const healAmount = new Utils.NumberHolder(Math.floor(this.hpHealed * hpRestoreMultiplier.value));
const healAmount = new NumberHolder(Math.floor(this.hpHealed * hpRestoreMultiplier.value));
if (healAmount.value < 0) {
pokemon.damageAndUpdate(healAmount.value * -1, { result: HitResult.INDIRECT });
healAmount.value = 0;

View File

@ -11,11 +11,14 @@ export abstract class PokemonPhase extends FieldPhase {
constructor(battlerIndex?: BattlerIndex | number) {
super();
if (battlerIndex === undefined) {
battlerIndex = globalScene
battlerIndex =
battlerIndex ??
globalScene
.getField()
.find(p => p?.isActive())!
.getBattlerIndex(); // TODO: is the bang correct here?
.find(p => p?.isActive())! // TODO: is the bang correct here?
.getBattlerIndex();
if (battlerIndex === undefined) {
console.warn("There are no Pokemon on the field!"); // TODO: figure out a suitable fallback behavior
}
this.battlerIndex = battlerIndex;

View File

@ -4,12 +4,12 @@ import type { EndCardPhase } from "./end-card-phase";
import { TitlePhase } from "./title-phase";
export class PostGameOverPhase extends Phase {
private endCardPhase: EndCardPhase | null;
private endCardPhase?: EndCardPhase;
constructor(endCardPhase?: EndCardPhase) {
super();
this.endCardPhase = endCardPhase!; // TODO: is this bang correct?
this.endCardPhase = endCardPhase;
}
start() {

View File

@ -13,7 +13,7 @@ import { getStatusEffectActivationText } from "#app/data/status-effect";
import { BattleSpec } from "#app/enums/battle-spec";
import { StatusEffect } from "#app/enums/status-effect";
import { getPokemonNameWithAffix } from "#app/messages";
import * as Utils from "#app/utils";
import { BooleanHolder, NumberHolder } from "#app/utils";
import { PokemonPhase } from "./pokemon-phase";
export class PostTurnStatusEffectPhase extends PokemonPhase {
@ -26,7 +26,7 @@ export class PostTurnStatusEffectPhase extends PokemonPhase {
const pokemon = this.getPokemon();
if (pokemon?.isActive(true) && pokemon.status && pokemon.status.isPostTurn() && !pokemon.switchOutStatus) {
pokemon.status.incrementTurn();
const cancelled = new Utils.BooleanHolder(false);
const cancelled = new BooleanHolder(false);
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
applyAbAttrs(BlockStatusDamageAbAttr, pokemon, cancelled);
@ -34,7 +34,7 @@ export class PostTurnStatusEffectPhase extends PokemonPhase {
globalScene.queueMessage(
getStatusEffectActivationText(pokemon.status.effect, getPokemonNameWithAffix(pokemon)),
);
const damage = new Utils.NumberHolder(0);
const damage = new NumberHolder(0);
switch (pokemon.status.effect) {
case StatusEffect.POISON:
damage.value = Math.max(pokemon.getMaxHp() >> 3, 1);

View File

@ -1,15 +1,15 @@
import { globalScene } from "#app/global-scene";
import { Phase } from "#app/phase";
import { Mode } from "#app/ui/ui";
import * as Utils from "#app/utils";
import { fixedInt } from "#app/utils";
export class ReloadSessionPhase extends Phase {
private systemDataStr: string | null;
private systemDataStr?: string;
constructor(systemDataStr?: string) {
super();
this.systemDataStr = systemDataStr ?? null;
this.systemDataStr = systemDataStr;
}
start(): void {
@ -18,7 +18,7 @@ export class ReloadSessionPhase extends Phase {
let delayElapsed = false;
let loaded = false;
globalScene.time.delayedCall(Utils.fixedInt(1500), () => {
globalScene.time.delayedCall(fixedInt(1500), () => {
if (loaded) {
this.end();
} else {

View File

@ -0,0 +1,44 @@
import type Pokemon from "#app/field/pokemon";
import { BattlePhase } from "#app/phases/battle-phase";
import { BattlerTagType } from "#enums/battler-tag-type";
import { StatusEffect } from "#enums/status-effect";
/**
* Phase which handles resetting a Pokemon's status to none
*
* This is necessary to perform in a phase primarly to ensure that the status icon disappears at the correct time in the battle
*/
export class ResetStatusPhase extends BattlePhase {
private readonly pokemon: Pokemon;
private readonly affectConfusion: boolean;
private readonly reloadAssets: boolean;
constructor(pokemon: Pokemon, affectConfusion: boolean, reloadAssets: boolean) {
super();
this.pokemon = pokemon;
this.affectConfusion = affectConfusion;
this.reloadAssets = reloadAssets;
}
public override start() {
const lastStatus = this.pokemon.status?.effect;
this.pokemon.status = null;
if (lastStatus === StatusEffect.SLEEP) {
this.pokemon.setFrameRate(10);
if (this.pokemon.getTag(BattlerTagType.NIGHTMARE)) {
this.pokemon.lapseTag(BattlerTagType.NIGHTMARE);
}
}
if (this.affectConfusion) {
if (this.pokemon.getTag(BattlerTagType.CONFUSED)) {
this.pokemon.lapseTag(BattlerTagType.CONFUSED);
}
}
if (this.reloadAssets) {
this.pokemon.loadAssets(false).then(() => this.pokemon.playAnim());
}
this.pokemon.updateInfo(true);
this.end();
}
}

View File

@ -8,6 +8,7 @@ import i18next from "i18next";
import { PokemonPhase } from "./pokemon-phase";
export class ScanIvsPhase extends PokemonPhase {
// biome-ignore lint/complexity/noUselessConstructor: This changes `battlerIndex` to be required
constructor(battlerIndex: BattlerIndex) {
super(battlerIndex);
}
@ -24,7 +25,8 @@ export class ScanIvsPhase extends PokemonPhase {
const uiTheme = globalScene.uiTheme; // Assuming uiTheme is accessible
for (let e = 0; e < enemyField.length; e++) {
enemyIvs = enemyField[e].ivs;
const currentIvs = globalScene.gameData.dexData[enemyField[e].species.getRootSpeciesId()].ivs; // we are using getRootSpeciesId() here because we want to check against the baby form, not the mid form if it exists
// we are using getRootSpeciesId() here because we want to check against the baby form, not the mid form if it exists
const currentIvs = globalScene.gameData.dexData[enemyField[e].species.getRootSpeciesId()].ivs;
statsContainer = enemyField[e].getBattleInfo().getStatsValueContainer().list as Phaser.GameObjects.Sprite[];
statsContainerLabels = statsContainer.filter(m => m.name.indexOf("icon_stat_label") >= 0);
for (let s = 0; s < statsContainerLabels.length; s++) {

View File

@ -5,15 +5,11 @@ import { MoneyInterestModifier, MapModifier } from "#app/modifier/modifier";
import type { OptionSelectItem } from "#app/ui/abstact-option-select-ui-handler";
import { Mode } from "#app/ui/ui";
import { BattlePhase } from "./battle-phase";
import * as Utils from "#app/utils";
import { randSeedInt } from "#app/utils";
import { PartyHealPhase } from "./party-heal-phase";
import { SwitchBiomePhase } from "./switch-biome-phase";
export class SelectBiomePhase extends BattlePhase {
constructor() {
super();
}
start() {
super.start();
@ -40,7 +36,7 @@ export class SelectBiomePhase extends BattlePhase {
let biomes: Biome[] = [];
globalScene.executeWithSeedOffset(() => {
biomes = (biomeLinks[currentBiome] as (Biome | [Biome, number])[])
.filter(b => !Array.isArray(b) || !Utils.randSeedInt(b[1]))
.filter(b => !Array.isArray(b) || !randSeedInt(b[1]))
.map(b => (!Array.isArray(b) ? b : b[0]));
}, globalScene.currentBattle.waveIndex);
if (biomes.length > 1 && globalScene.findModifier(m => m instanceof MapModifier)) {
@ -51,7 +47,7 @@ export class SelectBiomePhase extends BattlePhase {
? [biomeLinks[currentBiome] as Biome]
: (biomeLinks[currentBiome] as (Biome | [Biome, number])[])
)
.filter((b, _i) => !Array.isArray(b) || !Utils.randSeedInt(b[1]))
.filter(b => !Array.isArray(b) || !randSeedInt(b[1]))
.map(b => (Array.isArray(b) ? b[0] : b));
}, globalScene.currentBattle.waveIndex);
const biomeSelectItems = biomeChoices.map(b => {
@ -70,7 +66,7 @@ export class SelectBiomePhase extends BattlePhase {
delay: 1000,
});
} else {
setNextBiome(biomes[Utils.randSeedInt(biomes.length)]);
setNextBiome(biomes[randSeedInt(biomes.length)]);
}
} else if (biomeLinks.hasOwnProperty(currentBiome)) {
setNextBiome(biomeLinks[currentBiome] as Biome);

View File

@ -3,10 +3,6 @@ import { Phase } from "#app/phase";
import { Mode } from "#app/ui/ui";
export class SelectChallengePhase extends Phase {
constructor() {
super();
}
start() {
super.start();

View File

@ -6,10 +6,6 @@ import { Mode } from "#app/ui/ui";
import i18next from "i18next";
export class SelectGenderPhase extends Phase {
constructor() {
super();
}
start(): void {
super.start();

View File

@ -26,7 +26,6 @@ import { SHOP_OPTIONS_ROW_LIMIT } from "#app/ui/modifier-select-ui-handler";
import PartyUiHandler, { PartyUiMode, PartyOption } from "#app/ui/party-ui-handler";
import { Mode } from "#app/ui/ui";
import i18next from "i18next";
import * as Utils from "#app/utils";
import { BattlePhase } from "./battle-phase";
import Overrides from "#app/overrides";
import type { CustomModifierSettings } from "#app/modifier/modifier-type";
@ -67,7 +66,7 @@ export class SelectModifierPhase extends BattlePhase {
if (!this.isCopy) {
regenerateModifierPoolThresholds(party, this.getPoolType(), this.rerollCount);
}
const modifierCount = new Utils.NumberHolder(3);
const modifierCount = new NumberHolder(3);
if (this.isPlayer()) {
globalScene.applyModifiers(ExtraModifierModifier, true, modifierCount);
globalScene.applyModifiers(TempExtraModifierModifier, true, modifierCount);

View File

@ -15,10 +15,6 @@ import SoundFade from "phaser3-rex-plugins/plugins/soundfade";
import * as Utils from "../utils";
export class SelectStarterPhase extends Phase {
constructor() {
super();
}
start() {
super.start();

View File

@ -8,6 +8,7 @@ import i18next from "#app/plugins/i18n";
import { allMoves } from "#app/data/moves/move";
export class SelectTargetPhase extends PokemonPhase {
// biome-ignore lint/complexity/noUselessConstructor: This makes `fieldIndex` required
constructor(fieldIndex: number) {
super(fieldIndex);
}

View File

@ -3,6 +3,7 @@ import type { BattlerIndex } from "#app/battle";
import { PokemonPhase } from "./pokemon-phase";
export class ShinySparklePhase extends PokemonPhase {
// biome-ignore lint/complexity/noUselessConstructor: This makes `battlerIndex` required
constructor(battlerIndex: BattlerIndex) {
super(battlerIndex);
}

View File

@ -2,7 +2,7 @@ import { globalScene } from "#app/global-scene";
import { ExpGainsSpeed } from "#app/enums/exp-gains-speed";
import { ExpNotification } from "#app/enums/exp-notification";
import { ExpBoosterModifier } from "#app/modifier/modifier";
import * as Utils from "#app/utils";
import { NumberHolder } from "#app/utils";
import { HidePartyExpBarPhase } from "./hide-party-exp-bar-phase";
import { LevelUpPhase } from "./level-up-phase";
import { PlayerPartyMemberPokemonPhase } from "./player-party-member-pokemon-phase";
@ -20,7 +20,7 @@ export class ShowPartyExpBarPhase extends PlayerPartyMemberPokemonPhase {
super.start();
const pokemon = this.getPokemon();
const exp = new Utils.NumberHolder(this.expValue);
const exp = new NumberHolder(this.expValue);
globalScene.applyModifiers(ExpBoosterModifier, true, exp);
exp.value = Math.floor(exp.value);

View File

@ -3,10 +3,6 @@ import { PlayerGender } from "#app/enums/player-gender";
import { BattlePhase } from "./battle-phase";
export class ShowTrainerPhase extends BattlePhase {
constructor() {
super();
}
start() {
super.start();

View File

@ -4,10 +4,6 @@ import { SummonPhase } from "./summon-phase";
import { globalScene } from "#app/global-scene";
export class SummonMissingPhase extends SummonPhase {
constructor(fieldIndex: number) {
super(fieldIndex);
}
preSummon(): void {
globalScene.ui.showText(
i18next.t("battle:sendOutPokemon", {

View File

@ -23,11 +23,11 @@ export class SwitchSummonPhase extends SummonPhase {
/**
* Constructor for creating a new SwitchSummonPhase
* @param switchType the type of switch behavior
* @param fieldIndex integer representing position on the battle field
* @param slotIndex integer for the index of pokemon (in party of 6) to switch into
* @param doReturn boolean whether to render "comeback" dialogue
* @param player boolean if the switch is from the player
* @param switchType - The type of switch behavior
* @param fieldIndex - Position on the battle field
* @param slotIndex - The index of pokemon (in party of 6) to switch into
* @param doReturn - Whether to render "comeback" dialogue
* @param player - (Optional) `true` if the switch is from the player
*/
constructor(switchType: SwitchType, fieldIndex: number, slotIndex: number, doReturn: boolean, player?: boolean) {
super(fieldIndex, player !== undefined ? player : true);

View File

@ -1,7 +0,0 @@
import { MessagePhase } from "./message-phase";
export class TestMessagePhase extends MessagePhase {
constructor(message: string) {
super(message, null, true);
}
}

View File

@ -18,7 +18,7 @@ import { vouchers } from "#app/system/voucher";
import type { OptionSelectConfig, OptionSelectItem } from "#app/ui/abstact-option-select-ui-handler";
import { SaveSlotUiMode } from "#app/ui/save-slot-select-ui-handler";
import { Mode } from "#app/ui/ui";
import * as Utils from "#app/utils";
import { isLocal, isLocalServerConnected, isNullOrUndefined } from "#app/utils";
import i18next from "i18next";
import { CheckSwitchPhase } from "./check-switch-phase";
import { EncounterPhase } from "./encounter-phase";
@ -29,16 +29,10 @@ import { globalScene } from "#app/global-scene";
import Overrides from "#app/overrides";
export class TitlePhase extends Phase {
private loaded: boolean;
private loaded = false;
private lastSessionData: SessionSaveData;
public gameMode: GameModes;
constructor() {
super();
this.loaded = false;
}
start(): void {
super.start();
@ -282,7 +276,7 @@ export class TitlePhase extends Phase {
};
// If Online, calls seed fetch from db to generate daily run. If Offline, generates a daily run based on current date.
if (!Utils.isLocal || Utils.isLocalServerConnected) {
if (!isLocal || isLocalServerConnected) {
fetchDailyRunSeed()
.then(seed => {
if (seed) {
@ -296,7 +290,7 @@ export class TitlePhase extends Phase {
});
} else {
let seed: string = btoa(new Date().toISOString().substring(0, 10));
if (!Utils.isNullOrUndefined(Overrides.DAILY_RUN_SEED_OVERRIDE)) {
if (!isNullOrUndefined(Overrides.DAILY_RUN_SEED_OVERRIDE)) {
seed = Overrides.DAILY_RUN_SEED_OVERRIDE;
}
generateDaily(seed);

View File

@ -1,47 +0,0 @@
import { globalScene } from "#app/global-scene";
import { trainerConfigs } from "#app/data/trainers/trainer-config";
import type { TrainerType } from "#app/enums/trainer-type";
import { BattlePhase } from "./battle-phase";
import { TestMessagePhase } from "./test-message-phase";
export class TrainerMessageTestPhase extends BattlePhase {
private trainerTypes: TrainerType[];
constructor(...trainerTypes: TrainerType[]) {
super();
this.trainerTypes = trainerTypes;
}
start() {
super.start();
const testMessages: string[] = [];
for (const t of Object.keys(trainerConfigs)) {
const type = Number.parseInt(t);
if (this.trainerTypes.length && !this.trainerTypes.find(tt => tt === (type as TrainerType))) {
continue;
}
const config = trainerConfigs[type];
[
config.encounterMessages,
config.femaleEncounterMessages,
config.victoryMessages,
config.femaleVictoryMessages,
config.defeatMessages,
config.femaleDefeatMessages,
].map(messages => {
if (messages?.length) {
testMessages.push(...messages);
}
});
}
for (const message of testMessages) {
globalScene.pushPhase(new TestMessagePhase(message));
}
this.end();
}
}

View File

@ -3,7 +3,7 @@ import { TrainerType } from "#app/enums/trainer-type";
import { modifierTypes } from "#app/modifier/modifier-type";
import { vouchers } from "#app/system/voucher";
import i18next from "i18next";
import * as Utils from "#app/utils";
import { randSeedItem } from "#app/utils";
import { BattlePhase } from "./battle-phase";
import { ModifierRewardPhase } from "./modifier-reward-phase";
import { MoneyRewardPhase } from "./money-reward-phase";
@ -14,10 +14,6 @@ import { achvs } from "#app/system/achv";
import { timedEventManager } from "#app/global-event-manager";
export class TrainerVictoryPhase extends BattlePhase {
constructor() {
super();
}
start() {
globalScene.disableMenu = true;
@ -82,7 +78,7 @@ export class TrainerVictoryPhase extends BattlePhase {
const victoryMessages = globalScene.currentBattle.trainer?.getVictoryMessages()!; // TODO: is this bang correct?
let message: string;
globalScene.executeWithSeedOffset(
() => (message = Utils.randSeedItem(victoryMessages)),
() => (message = randSeedItem(victoryMessages)),
globalScene.currentBattle.waveIndex,
);
message = message!; // tell TS compiler it's defined now

View File

@ -18,10 +18,6 @@ import { PokemonHealPhase } from "./pokemon-heal-phase";
import { globalScene } from "#app/global-scene";
export class TurnEndPhase extends FieldPhase {
constructor() {
super();
}
start() {
super.start();

View File

@ -15,10 +15,6 @@ import { TurnStartPhase } from "./turn-start-phase";
import { globalScene } from "#app/global-scene";
export class TurnInitPhase extends FieldPhase {
constructor() {
super();
}
start() {
super.start();

View File

@ -6,7 +6,7 @@ import type Pokemon from "#app/field/pokemon";
import { PokemonMove } from "#app/field/pokemon";
import { BypassSpeedChanceModifier } from "#app/modifier/modifier";
import { Command } from "#app/ui/command-ui-handler";
import * as Utils from "#app/utils";
import { randSeedShuffle, BooleanHolder } from "#app/utils";
import { AttemptCapturePhase } from "./attempt-capture-phase";
import { AttemptRunPhase } from "./attempt-run-phase";
import { BerryPhase } from "./berry-phase";
@ -24,10 +24,6 @@ import { globalScene } from "#app/global-scene";
import { TeraPhase } from "./tera-phase";
export class TurnStartPhase extends FieldPhase {
constructor() {
super();
}
/**
* This orders the active Pokemon on the field by speed into an BattlerIndex array and returns that array.
* It also checks for Trick Room and reverses the array if it is present.
@ -43,14 +39,14 @@ export class TurnStartPhase extends FieldPhase {
// was varying based on how long since you last reloaded
globalScene.executeWithSeedOffset(
() => {
orderedTargets = Utils.randSeedShuffle(orderedTargets);
orderedTargets = randSeedShuffle(orderedTargets);
},
globalScene.currentBattle.turn,
globalScene.waveSeed,
);
// Next, a check for Trick Room is applied to determine sort order.
const speedReversed = new Utils.BooleanHolder(false);
const speedReversed = new BooleanHolder(false);
globalScene.arena.applyTags(TrickRoomTag, false, speedReversed);
// Adjust the sort function based on whether Trick Room is active.
@ -80,8 +76,8 @@ export class TurnStartPhase extends FieldPhase {
.getField(true)
.filter(p => p.summonData)
.map(p => {
const bypassSpeed = new Utils.BooleanHolder(false);
const canCheckHeldItems = new Utils.BooleanHolder(true);
const bypassSpeed = new BooleanHolder(false);
const canCheckHeldItems = new BooleanHolder(true);
applyAbAttrs(BypassSpeedChanceAbAttr, p, null, false, bypassSpeed);
applyAbAttrs(PreventBypassSpeedChanceAbAttr, p, null, false, bypassSpeed, canCheckHeldItems);
if (canCheckHeldItems.value) {

View File

@ -4,10 +4,6 @@ import { Mode } from "#app/ui/ui";
import { LoginPhase } from "./login-phase";
export class UnavailablePhase extends Phase {
constructor() {
super();
}
start(): void {
globalScene.ui.setMode(Mode.UNAVAILABLE, () => {
globalScene.unshiftPhase(new LoginPhase(true));

View File

@ -15,7 +15,7 @@ import { BattlerTagType } from "#app/enums/battler-tag-type";
import { WeatherType } from "#app/enums/weather-type";
import type Pokemon from "#app/field/pokemon";
import { HitResult } from "#app/field/pokemon";
import * as Utils from "#app/utils";
import { BooleanHolder, toDmgValue } from "#app/utils";
import { CommonAnimPhase } from "./common-anim-phase";
export class WeatherEffectPhase extends CommonAnimPhase {
@ -35,14 +35,13 @@ export class WeatherEffectPhase extends CommonAnimPhase {
this.weather = globalScene?.arena?.weather;
if (!this.weather) {
this.end();
return;
return this.end();
}
this.setAnimation(CommonAnim.SUNNY + (this.weather.weatherType - 1));
if (this.weather.isDamaging()) {
const cancelled = new Utils.BooleanHolder(false);
const cancelled = new BooleanHolder(false);
this.executeForAll((pokemon: Pokemon) =>
applyPreWeatherEffectAbAttrs(SuppressWeatherEffectAbAttr, pokemon, this.weather, cancelled),
@ -50,7 +49,7 @@ export class WeatherEffectPhase extends CommonAnimPhase {
if (!cancelled.value) {
const inflictDamage = (pokemon: Pokemon) => {
const cancelled = new Utils.BooleanHolder(false);
const cancelled = new BooleanHolder(false);
applyPreWeatherEffectAbAttrs(PreWeatherDamageAbAttr, pokemon, this.weather, cancelled);
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
@ -63,9 +62,9 @@ export class WeatherEffectPhase extends CommonAnimPhase {
return;
}
const damage = Utils.toDmgValue(pokemon.getMaxHp() / 16);
const damage = toDmgValue(pokemon.getMaxHp() / 16);
globalScene.queueMessage(getWeatherDamageMessage(this.weather?.weatherType!, pokemon)!); // TODO: are those bangs correct?
globalScene.queueMessage(getWeatherDamageMessage(this.weather!.weatherType, pokemon) ?? "");
pokemon.damageAndUpdate(damage, { result: HitResult.INDIRECT, ignoreSegments: true });
};

View File

@ -1,19 +1,104 @@
import type { SessionSaveData, SystemSaveData } from "../game-data";
import type { SessionSaveMigrator } from "#app/@types/SessionSaveMigrator";
import type { SettingsSaveMigrator } from "#app/@types/SettingsSaveMigrator";
import type { SystemSaveMigrator } from "#app/@types/SystemSaveMigrator";
import type { SessionSaveData, SystemSaveData } from "#app/system/game-data";
import { compareVersions } from "compare-versions";
import { version } from "../../../package.json";
/*
// template for save migrator creation
// versions/vA_B_C.ts
// The version for each migrator should match the filename, ie: `vA_B_C.ts` -> `version: "A.B.C"
// This is the target version (aka the version we're ending up on after the migrators are run)
// The name for each migrator should match its purpose. For example, if you're fixing
// the ability index of a pokemon, it might be called `migratePokemonAbilityIndex`
const systemMigratorA: SystemSaveMigrator = {
version: "A.B.C",
migrate: (data: SystemSaveData): void => {
// migration code goes here
},
};
export const systemMigrators: Readonly<SystemSaveMigrator[]> = [systemMigratorA] as const;
const sessionMigratorA: SessionSaveMigrator = {
version: "A.B.C",
migrate: (data: SessionSaveData): void => {
// migration code goes here
},
};
export const sessionMigrators: Readonly<SessionSaveMigrator[]> = [sessionMigratorA] as const;
const settingsMigratorA: SettingsSaveMigrator = {
version: "A.B.C",
// biome-ignore lint/complexity/noBannedTypes: TODO - refactor settings
migrate: (data: Object): void => {
// migration code goes here
},
};
export const settingsMigrators: Readonly<SettingsSaveMigrator[]> = [settingsMigratorA] as const;
*/
// --- vA.B.C PATCHES --- //
// import * as vA_B_C from "./versions/vA_B_C";
// --- v1.0.4 (and below) PATCHES --- //
import * as v1_0_4 from "./versions/v1_0_4";
// --- v1.1.0 PATCHES --- //
import * as v1_1_0 from "./versions/v1_1_0";
// --- v1.7.0 PATCHES --- //
import * as v1_7_0 from "./versions/v1_7_0";
// --- v1.8.3 PATCHES --- //
import * as v1_8_3 from "./versions/v1_8_3";
const LATEST_VERSION = version.split(".").map(value => Number.parseInt(value));
/** Current game version */
const LATEST_VERSION = version;
type SaveMigrator = SystemSaveMigrator | SessionSaveMigrator | SettingsSaveMigrator;
// biome-ignore lint/complexity/noBannedTypes: TODO - refactor settings
type SaveData = SystemSaveData | SessionSaveData | Object;
// To add a new set of migrators, create a new `.push()` line like so:
// `systemMigrators.push(...vA_B_C.systemMigrators);`
/** All system save migrators */
const systemMigrators: SystemSaveMigrator[] = [];
systemMigrators.push(...v1_0_4.systemMigrators);
systemMigrators.push(...v1_7_0.systemMigrators);
systemMigrators.push(...v1_8_3.systemMigrators);
/** All session save migrators */
const sessionMigrators: SessionSaveMigrator[] = [];
sessionMigrators.push(...v1_0_4.sessionMigrators);
sessionMigrators.push(...v1_7_0.sessionMigrators);
/** All settings migrators */
const settingsMigrators: SettingsSaveMigrator[] = [];
settingsMigrators.push(...v1_0_4.settingsMigrators);
/** Sorts migrators by their stated version, ensuring they are applied in order from oldest to newest */
const sortMigrators = (migrators: SaveMigrator[]): void => {
migrators.sort((a, b) => compareVersions(a.version, b.version));
};
sortMigrators(systemMigrators);
sortMigrators(sessionMigrators);
sortMigrators(settingsMigrators);
const applyMigrators = (migrators: readonly SaveMigrator[], data: SaveData, saveVersion: string) => {
for (const migrator of migrators) {
const isMigratorVersionHigher = compareVersions(saveVersion, migrator.version) === -1;
if (isMigratorVersionHigher) {
migrator.migrate(data as any);
}
}
};
/**
* Converts incoming {@linkcode SystemSaveData} that has a version below the
@ -26,12 +111,12 @@ const LATEST_VERSION = version.split(".").map(value => Number.parseInt(value));
* @see {@link SystemVersionConverter}
*/
export function applySystemVersionMigration(data: SystemSaveData) {
const curVersion = data.gameVersion.split(".").map(value => Number.parseInt(value));
const prevVersion = data.gameVersion;
const isCurrentVersionHigher = compareVersions(prevVersion, LATEST_VERSION) === -1;
if (!curVersion.every((value, index) => value === LATEST_VERSION[index])) {
const converter = new SystemVersionConverter();
converter.applyStaticPreprocessors(data);
converter.applyMigration(data, curVersion);
if (isCurrentVersionHigher) {
applyMigrators(systemMigrators, data, prevVersion);
console.log(`System data successfully migrated to v${LATEST_VERSION}!`);
}
}
@ -46,12 +131,15 @@ export function applySystemVersionMigration(data: SystemSaveData) {
* @see {@link SessionVersionConverter}
*/
export function applySessionVersionMigration(data: SessionSaveData) {
const curVersion = data.gameVersion.split(".").map(value => Number.parseInt(value));
const prevVersion = data.gameVersion;
const isCurrentVersionHigher = compareVersions(prevVersion, LATEST_VERSION) === -1;
if (!curVersion.every((value, index) => value === LATEST_VERSION[index])) {
const converter = new SessionVersionConverter();
converter.applyStaticPreprocessors(data);
converter.applyMigration(data, curVersion);
if (isCurrentVersionHigher) {
// Always sanitize money as a safeguard
data.money = Math.floor(data.money);
applyMigrators(sessionMigrators, data, prevVersion);
console.log(`Session data successfully migrated to v${LATEST_VERSION}!`);
}
}
@ -65,156 +153,13 @@ export function applySessionVersionMigration(data: SessionSaveData) {
* @param data Settings data object
* @see {@link SettingsVersionConverter}
*/
// biome-ignore lint/complexity/noBannedTypes: TODO - refactor settings
export function applySettingsVersionMigration(data: Object) {
const gameVersion: string = data.hasOwnProperty("gameVersion") ? data["gameVersion"] : "1.0.0";
const curVersion = gameVersion.split(".").map(value => Number.parseInt(value));
const prevVersion: string = data.hasOwnProperty("gameVersion") ? data["gameVersion"] : "1.0.0";
const isCurrentVersionHigher = compareVersions(prevVersion, LATEST_VERSION) === -1;
if (!curVersion.every((value, index) => value === LATEST_VERSION[index])) {
const converter = new SettingsVersionConverter();
converter.applyStaticPreprocessors(data);
converter.applyMigration(data, curVersion);
}
}
/**
* Abstract class encapsulating the logic for migrating data from a given version up to
* the current version listed in `package.json`.
*
* Note that, for any version converter, the corresponding `applyMigration`
* function would only need to be changed once when the first migration for a
* given version is introduced. Similarly, a version file (within the `versions`
* folder) would only need to be created for a version once with the appropriate
* array nomenclature.
*/
abstract class VersionConverter {
/**
* Iterates through an array of designated migration functions that are each
* called one by one to transform the data.
* @param data The data to be operated on
* @param migrationArr An array of functions that will transform the incoming data
*/
callMigrators(data: any, migrationArr: readonly any[]) {
for (const migrate of migrationArr) {
migrate(data);
}
}
/**
* Applies any version-agnostic data sanitation as defined within the function
* body.
* @param data The data to be operated on
*/
applyStaticPreprocessors(_data: any): void {}
/**
* Uses the current version the incoming data to determine the starting point
* of the migration which will cascade up to the latest version, calling the
* necessary migration functions in the process.
* @param data The data to be operated on
* @param curVersion [0] Current major version
* [1] Current minor version
* [2] Current patch version
*/
abstract applyMigration(data: any, curVersion: number[]): void;
}
/**
* Class encapsulating the logic for migrating {@linkcode SessionSaveData} from
* a given version up to the current version listed in `package.json`.
* @extends VersionConverter
*/
class SessionVersionConverter extends VersionConverter {
override applyStaticPreprocessors(data: SessionSaveData): void {
// Always sanitize money as a safeguard
data.money = Math.floor(data.money);
}
override applyMigration(data: SessionSaveData, curVersion: number[]): void {
const [curMajor, curMinor, curPatch] = curVersion;
if (curMajor === 1) {
if (curMinor === 0) {
if (curPatch <= 5) {
console.log("Applying v1.0.4 session data migration!");
this.callMigrators(data, v1_0_4.sessionMigrators);
}
}
if (curMinor <= 1) {
console.log("Applying v1.1.0 session data migration!");
this.callMigrators(data, v1_1_0.sessionMigrators);
}
if (curMinor < 7) {
console.log("Applying v1.7.0 session data migration!");
this.callMigrators(data, v1_7_0.sessionMigrators);
}
}
console.log(`Session data successfully migrated to v${version}!`);
}
}
/**
* Class encapsulating the logic for migrating {@linkcode SystemSaveData} from
* a given version up to the current version listed in `package.json`.
* @extends VersionConverter
*/
class SystemVersionConverter extends VersionConverter {
override applyMigration(data: SystemSaveData, curVersion: number[]): void {
const [curMajor, curMinor, curPatch] = curVersion;
if (curMajor === 1) {
if (curMinor === 0) {
if (curPatch <= 4) {
console.log("Applying v1.0.4 system data migraton!");
this.callMigrators(data, v1_0_4.systemMigrators);
}
}
if (curMinor <= 1) {
console.log("Applying v1.1.0 system data migraton!");
this.callMigrators(data, v1_1_0.systemMigrators);
}
if (curMinor < 7) {
console.log("Applying v1.7.0 system data migration!");
this.callMigrators(data, v1_7_0.systemMigrators);
}
if (curMinor === 8) {
if (curPatch <= 2) {
console.log("Applying v1.8.3 system data migration!");
this.callMigrators(data, v1_8_3.systemMigrators);
}
}
}
console.log(`System data successfully migrated to v${version}!`);
}
}
/**
* Class encapsulating the logic for migrating settings data from
* a given version up to the current version listed in `package.json`.
* @extends VersionConverter
*/
class SettingsVersionConverter extends VersionConverter {
override applyMigration(data: Object, curVersion: number[]): void {
const [curMajor, curMinor, curPatch] = curVersion;
if (curMajor === 1) {
if (curMinor === 0) {
if (curPatch <= 4) {
console.log("Applying v1.0.4 settings data migraton!");
this.callMigrators(data, v1_0_4.settingsMigrators);
}
}
if (curMinor <= 1) {
console.log("Applying v1.1.0 settings data migraton!");
this.callMigrators(data, v1_1_0.settingsMigrators);
}
if (curMinor < 7) {
console.log("Applying v1.7.0 settings data migration!");
this.callMigrators(data, v1_7_0.settingsMigrators);
}
}
console.log(`Settings data successfully migrated to v${version}!`);
if (isCurrentVersionHigher) {
applyMigrators(settingsMigrators, data, prevVersion);
console.log(`Settings successfully migrated to v${LATEST_VERSION}!`);
}
}

View File

@ -4,15 +4,18 @@ import { AbilityAttr, defaultStarterSpecies, DexAttr } from "#app/system/game-da
import { allSpecies } from "#app/data/pokemon-species";
import { CustomPokemonData } from "#app/data/custom-pokemon-data";
import { isNullOrUndefined } from "#app/utils";
import type { SystemSaveMigrator } from "#app/@types/SystemSaveMigrator";
import type { SettingsSaveMigrator } from "#app/@types/SettingsSaveMigrator";
import type { SessionSaveMigrator } from "#app/@types/SessionSaveMigrator";
export const systemMigrators = [
/**
* Migrate ability starter data if empty for caught species.
* @param data {@linkcode SystemSaveData}
*/
function migrateAbilityData(data: SystemSaveData) {
/**
* Migrate ability starter data if empty for caught species.
* @param data - {@linkcode SystemSaveData}
*/
const migrateAbilityData: SystemSaveMigrator = {
version: "1.0.4",
migrate: (data: SystemSaveData): void => {
if (data.starterData && data.dexData) {
// biome-ignore lint/complexity/noForEach: <explanation>
Object.keys(data.starterData).forEach(sd => {
if (data.dexData[sd]?.caughtAttr && data.starterData[sd] && !data.starterData[sd].abilityAttr) {
data.starterData[sd].abilityAttr = 1;
@ -20,12 +23,15 @@ export const systemMigrators = [
});
}
},
};
/**
* Populate legendary Pokémon statistics if they are missing.
* @param data {@linkcode SystemSaveData}
*/
function fixLegendaryStats(data: SystemSaveData) {
/**
* Populate legendary Pokémon statistics if they are missing.
* @param data - {@linkcode SystemSaveData}
*/
const fixLegendaryStats: SystemSaveMigrator = {
version: "1.0.4",
migrate: (data: SystemSaveData): void => {
if (
data.gameStats &&
data.gameStats.legendaryPokemonCaught !== undefined &&
@ -34,7 +40,6 @@ export const systemMigrators = [
data.gameStats.subLegendaryPokemonSeen = 0;
data.gameStats.subLegendaryPokemonCaught = 0;
data.gameStats.subLegendaryPokemonHatched = 0;
// biome-ignore lint/complexity/noForEach: <explanation>
allSpecies
.filter(s => s.subLegendary)
.forEach(s => {
@ -66,12 +71,15 @@ export const systemMigrators = [
);
}
},
};
/**
* Unlock all starters' first ability and female gender option.
* @param data {@linkcode SystemSaveData}
*/
function fixStarterData(data: SystemSaveData) {
/**
* Unlock all starters' first ability and female gender option.
* @param data - {@linkcode SystemSaveData}
*/
const fixStarterData: SystemSaveMigrator = {
version: "1.0.4",
migrate: (data: SystemSaveData): void => {
if (!isNullOrUndefined(data.starterData)) {
for (const starterId of defaultStarterSpecies) {
if (data.starterData[starterId]?.abilityAttr) {
@ -83,17 +91,22 @@ export const systemMigrators = [
}
}
},
};
export const systemMigrators: Readonly<SystemSaveMigrator[]> = [
migrateAbilityData,
fixLegendaryStats,
fixStarterData,
] as const;
export const settingsMigrators = [
/**
* Migrate from "REROLL_TARGET" property to {@linkcode
* SettingKeys.Shop_Cursor_Target}.
* @param data the `settings` object
*/
// biome-ignore lint/complexity/noBannedTypes: TODO: fix the type to not be object...
function fixRerollTarget(data: Object) {
/**
* Migrate from `REROLL_TARGET` property to {@linkcode SettingKeys.Shop_Cursor_Target}
* @param data - The `settings` object
*/
const fixRerollTarget: SettingsSaveMigrator = {
version: "1.0.4",
// biome-ignore lint/complexity/noBannedTypes: TODO - refactor settings
migrate: (data: Object): void => {
if (data.hasOwnProperty("REROLL_TARGET") && !data.hasOwnProperty(SettingKeys.Shop_Cursor_Target)) {
data[SettingKeys.Shop_Cursor_Target] = data["REROLL_TARGET"];
// biome-ignore lint/performance/noDelete: intentional
@ -101,16 +114,20 @@ export const settingsMigrators = [
localStorage.setItem("settings", JSON.stringify(data));
}
},
] as const;
};
export const sessionMigrators = [
/**
* Converts old lapsing modifiers (battle items, lures, and Dire Hit) and
* other miscellaneous modifiers (vitamins, White Herb) to any new class
* names and/or change in reload arguments.
* @param data {@linkcode SessionSaveData}
*/
function migrateModifiers(data: SessionSaveData) {
export const settingsMigrators: Readonly<SettingsSaveMigrator[]> = [fixRerollTarget] as const;
/**
* Converts old lapsing modifiers (battle items, lures, and Dire Hit) and
* other miscellaneous modifiers (vitamins, White Herb) to any new class
* names and/or change in reload arguments.
* @param data - {@linkcode SessionSaveData}
*/
const migrateModifiers: SessionSaveMigrator = {
version: "1.0.4",
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: necessary?
migrate: (data: SessionSaveData): void => {
for (const m of data.modifiers) {
if (m.className === "PokemonBaseStatModifier") {
m.className = "BaseStatModifier";
@ -163,12 +180,11 @@ export const sessionMigrators = [
}
}
},
/**
* Converts old Pokemon natureOverride and mysteryEncounterData
* to use the new conjoined {@linkcode Pokemon.customPokemonData} structure instead.
* @param data {@linkcode SessionSaveData}
*/
function migrateCustomPokemonDataAndNatureOverrides(data: SessionSaveData) {
};
const migrateCustomPokemonData: SessionSaveMigrator = {
version: "1.0.4",
migrate: (data: SessionSaveData): void => {
// Fix Pokemon nature overrides and custom data migration
for (const pokemon of data.party) {
if (pokemon["mysteryEncounterPokemonData"]) {
@ -186,4 +202,6 @@ export const sessionMigrators = [
}
}
},
] as const;
};
export const sessionMigrators: Readonly<SessionSaveMigrator[]> = [migrateModifiers, migrateCustomPokemonData] as const;

View File

@ -1,5 +0,0 @@
export const systemMigrators = [] as const;
export const settingsMigrators = [] as const;
export const sessionMigrators = [] as const;

View File

@ -1,15 +1,18 @@
import type { SessionSaveMigrator } from "#app/@types/SessionSaveMigrator";
import type { SystemSaveMigrator } from "#app/@types/SystemSaveMigrator";
import { getPokemonSpecies, getPokemonSpeciesForm } from "#app/data/pokemon-species";
import { globalScene } from "#app/global-scene";
import { DexAttr, type SessionSaveData, type SystemSaveData } from "#app/system/game-data";
import * as Utils from "#app/utils";
import { isNullOrUndefined } from "#app/utils";
export const systemMigrators = [
/**
* If a starter is caught, but the only forms registered as caught are not starterSelectable,
* unlock the default form.
* @param data {@linkcode SystemSaveData}
*/
function migrateUnselectableForms(data: SystemSaveData) {
/**
* If a starter is caught, but the only forms registered as caught are not starterSelectable,
* unlock the default form.
* @param data - {@linkcode SystemSaveData}
*/
const migrateUnselectableForms: SystemSaveMigrator = {
version: "1.7.0",
migrate: (data: SystemSaveData): void => {
if (data.starterData && data.dexData) {
Object.keys(data.starterData).forEach(sd => {
const caughtAttr = data.dexData[sd]?.caughtAttr;
@ -30,12 +33,13 @@ export const systemMigrators = [
});
}
},
] as const;
};
export const settingsMigrators = [] as const;
export const systemMigrators: Readonly<SystemSaveMigrator[]> = [migrateUnselectableForms] as const;
export const sessionMigrators = [
function migrateTera(data: SessionSaveData) {
const migrateTera: SessionSaveMigrator = {
version: "1.7.0",
migrate: (data: SessionSaveData): void => {
for (let i = 0; i < data.modifiers.length; ) {
if (data.modifiers[i].className === "TerastallizeModifier") {
data.party.forEach(p => {
@ -63,15 +67,17 @@ export const sessionMigrators = [
}
data.party.forEach(p => {
if (Utils.isNullOrUndefined(p.teraType)) {
if (isNullOrUndefined(p.teraType)) {
p.teraType = getPokemonSpeciesForm(p.species, p.formIndex).type1;
}
});
data.enemyParty.forEach(p => {
if (Utils.isNullOrUndefined(p.teraType)) {
if (isNullOrUndefined(p.teraType)) {
p.teraType = getPokemonSpeciesForm(p.species, p.formIndex).type1;
}
});
},
] as const;
};
export const sessionMigrators: Readonly<SessionSaveMigrator[]> = [migrateTera] as const;

View File

@ -1,14 +1,16 @@
import type { SystemSaveMigrator } from "#app/@types/SystemSaveMigrator";
import { getPokemonSpecies } from "#app/data/pokemon-species";
import { DexAttr, type SystemSaveData } from "#app/system/game-data";
import { Species } from "#enums/species";
export const systemMigrators = [
/**
* If a starter is caught, but the only forms registered as caught are not starterSelectable,
* unlock the default form.
* @param data {@linkcode SystemSaveData}
*/
function migratePichuForms(data: SystemSaveData) {
/**
* If a starter is caught, but the only forms registered as caught are not starterSelectable,
* unlock the default form.
* @param data - {@linkcode SystemSaveData}
*/
const migratePichuForms: SystemSaveMigrator = {
version: "1.8.3",
migrate: (data: SystemSaveData): void => {
if (data.starterData && data.dexData) {
// This is Pichu's Pokédex number
const sd = 172;
@ -23,8 +25,6 @@ export const systemMigrators = [
}
}
},
] as const;
};
export const settingsMigrators = [] as const;
export const sessionMigrators = [] as const;
export const systemMigrators: Readonly<SystemSaveMigrator[]> = [migratePichuForms] as const;

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import { StatusEffect } from "#enums/status-effect";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Immunity", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove poison when gained", async () => {
game.override.ability(Abilities.IMMUNITY)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.trySetStatus(StatusEffect.POISON);
expect(enemy?.status?.effect).toBe(StatusEffect.POISON);
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.status).toBeNull();
});
});

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import { StatusEffect } from "#enums/status-effect";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Insomnia", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove sleep when gained", async () => {
game.override.ability(Abilities.INSOMNIA)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.trySetStatus(StatusEffect.SLEEP);
expect(enemy?.status?.effect).toBe(StatusEffect.SLEEP);
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.status).toBeNull();
});
});

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import { StatusEffect } from "#enums/status-effect";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Limber", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove paralysis when gained", async () => {
game.override.ability(Abilities.LIMBER)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.trySetStatus(StatusEffect.PARALYSIS);
expect(enemy?.status?.effect).toBe(StatusEffect.PARALYSIS);
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.status).toBeNull();
});
});

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import { StatusEffect } from "#enums/status-effect";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Magma Armor", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove freeze when gained", async () => {
game.override.ability(Abilities.MAGMA_ARMOR)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.trySetStatus(StatusEffect.FREEZE);
expect(enemy?.status?.effect).toBe(StatusEffect.FREEZE);
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.status).toBeNull();
});
});

View File

@ -0,0 +1,69 @@
import { Abilities } from "#enums/abilities";
import { BattlerTagType } from "#enums/battler-tag-type";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
describe("Abilities - Oblivious", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove taunt when gained", async () => {
game.override.ability(Abilities.OBLIVIOUS)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.addTag(BattlerTagType.TAUNT);
expect(enemy?.getTag(BattlerTagType.TAUNT)).toBeTruthy();
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.getTag(BattlerTagType.TAUNT)).toBeFalsy();
});
it("should remove infatuation when gained", async () => {
game.override.ability(Abilities.OBLIVIOUS)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
vi.spyOn(enemy!, "isOppositeGender").mockReturnValue(true);
enemy?.addTag(BattlerTagType.INFATUATED, 5, Moves.JUDGMENT, game.scene.getPlayerPokemon()?.id); // sourceID needs to be defined
expect(enemy?.getTag(BattlerTagType.INFATUATED)).toBeTruthy();
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.getTag(BattlerTagType.INFATUATED)).toBeFalsy();
});
});

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { BattlerTagType } from "#enums/battler-tag-type";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Own Tempo", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove confusion when gained", async () => {
game.override.ability(Abilities.OWN_TEMPO)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.addTag(BattlerTagType.CONFUSED);
expect(enemy?.getTag(BattlerTagType.CONFUSED)).toBeTruthy();
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.getTag(BattlerTagType.CONFUSED)).toBeFalsy();
});
});

View File

@ -0,0 +1,43 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
describe("Abilities - Super Luck", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([Moves.TACKLE])
.ability(Abilities.SUPER_LUCK)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should increase the crit stage of a user by 1", async () => {
await game.classicMode.startBattle([Species.MAGIKARP]);
const enemy = game.scene.getEnemyPokemon()!;
const fn = vi.spyOn(enemy, "getCritStage");
game.move.select(Moves.TACKLE);
await game.phaseInterceptor.to("BerryPhase");
expect(fn).toHaveReturnedWith(1);
fn.mockRestore();
});
});

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import { StatusEffect } from "#enums/status-effect";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Thermal Exchange", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove burn when gained", async () => {
game.override.ability(Abilities.THERMAL_EXCHANGE)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.trySetStatus(StatusEffect.BURN);
expect(enemy?.status?.effect).toBe(StatusEffect.BURN);
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.status).toBeNull();
});
});

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import { StatusEffect } from "#enums/status-effect";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Vital Spirit", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove sleep when gained", async () => {
game.override.ability(Abilities.INSOMNIA)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.trySetStatus(StatusEffect.SLEEP);
expect(enemy?.status?.effect).toBe(StatusEffect.SLEEP);
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.status).toBeNull();
});
});

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import { StatusEffect } from "#enums/status-effect";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Water Bubble", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove burn when gained", async () => {
game.override.ability(Abilities.THERMAL_EXCHANGE)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.trySetStatus(StatusEffect.BURN);
expect(enemy?.status?.effect).toBe(StatusEffect.BURN);
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.status).toBeNull();
});
});

View File

@ -0,0 +1,51 @@
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
import { Species } from "#enums/species";
import { StatusEffect } from "#enums/status-effect";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
describe("Abilities - Water Veil", () => {
let phaserGame: Phaser.Game;
let game: GameManager;
beforeAll(() => {
phaserGame = new Phaser.Game({
type: Phaser.HEADLESS,
});
});
afterEach(() => {
game.phaseInterceptor.restoreOg();
});
beforeEach(() => {
game = new GameManager(phaserGame);
game.override
.moveset([ Moves.SPLASH ])
.ability(Abilities.BALL_FETCH)
.battleType("single")
.disableCrits()
.enemySpecies(Species.MAGIKARP)
.enemyAbility(Abilities.BALL_FETCH)
.enemyMoveset(Moves.SPLASH);
});
it("should remove burn when gained", async () => {
game.override.ability(Abilities.THERMAL_EXCHANGE)
.enemyAbility(Abilities.BALL_FETCH)
.moveset(Moves.SKILL_SWAP)
.enemyMoveset(Moves.SPLASH),
await game.classicMode.startBattle([ Species.FEEBAS ]);
const enemy = game.scene.getEnemyPokemon();
enemy?.trySetStatus(StatusEffect.BURN);
expect(enemy?.status?.effect).toBe(StatusEffect.BURN);
game.move.select(Moves.SKILL_SWAP);
await game.phaseInterceptor.to("BerryPhase");
expect(enemy?.status).toBeNull();
});
});

View File

@ -4,6 +4,7 @@ import { Species } from "#enums/species";
import GameManager from "#test/testUtils/gameManager";
import Phaser from "phaser";
import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { ArenaTagSide, ArenaTrapTag } from "#app/data/arena-tag";
describe("Moves - Spikes", () => {
let phaserGame: Phaser.Game;
@ -77,4 +78,17 @@ describe("Moves - Spikes", () => {
const enemy = game.scene.getEnemyParty()[0];
expect(enemy.hp).toBeLessThan(enemy.getMaxHp());
}, 20000);
it("should work when all targets fainted", async () => {
game.override.enemySpecies(Species.DIGLETT);
game.override.battleType("double");
game.override.startingLevel(50);
await game.classicMode.startBattle([Species.RAYQUAZA, Species.ROWLET]);
game.move.select(Moves.EARTHQUAKE);
game.move.select(Moves.SPIKES, 1);
await game.phaseInterceptor.to("TurnEndPhase");
expect(game.scene.arena.getTagOnSide(ArenaTrapTag, ArenaTagSide.ENEMY)).toBeDefined();
}, 20000);
});