From e4ce822ce62df4ce93a0adc71edf26b498a0f6c1 Mon Sep 17 00:00:00 2001 From: Sirz Benjie <142067137+SirzBenjie@users.noreply.github.com> Date: Fri, 21 Feb 2025 02:34:39 -0600 Subject: [PATCH] [Refactor] Remove Promises from moves and abilities (#5283) * Remove Promises from moves and abilities * Fix `PostSummonPhase` * Apply suggestions from Kev's review * More suggestions Co-authored-by: NightKev <34855794+DayKev@users.noreply.github.com> * Cleaning up some updated functions * Remove Promise from `addEnemyModifier` + fixes to some extraneous `await`s * Test fixes * Fix missing import in revival blessing test Co-authored-by: innerthunder * Add back applyPreLeaveFieldAttrs Attribute was removed due to absence in a cherry-pick * Make applyPostApplyEffects work * Fix move-effect-phase.ts applications Some applyX methods were missed in the cherry pick commit and were still returning functions instead of running the function themselves * Mock `BattleScene.addPokemonIcon` in tests * Revival Blessing condition and tests * Incorporate Despair-Games/poketernity/pull/48 * Break up imports * Remove enemy modifier chance dead code * Remove async from applyAbAttrsInternal Stray async leftover from merge * Remove docs and comments referencing promises * Add `user.setTempAbility` to transform phase --------- Co-authored-by: innerthunder Co-authored-by: innerthunder <168692175+innerthunder@users.noreply.github.com> Co-authored-by: NightKev <34855794+DayKev@users.noreply.github.com> Co-authored-by: PigeonBar <56974298+PigeonBar@users.noreply.github.com> --- src/battle-scene.ts | 2175 ++++++++++++----- src/data/ability.ts | 1050 ++++++-- src/data/move.ts | 658 +++-- .../the-winstrate-challenge-encounter.ts | 2 +- .../encounters/weird-dream-encounter.ts | 4 +- .../utils/encounter-pokemon-utils.ts | 4 +- src/field/pokemon.ts | 148 +- src/modifier/modifier.ts | 28 +- src/phases/add-enemy-buff-modifier-phase.ts | 3 +- src/phases/battle-end-phase.ts | 3 +- src/phases/game-over-modifier-reward-phase.ts | 22 +- src/phases/load-move-anim-phase.ts | 20 + src/phases/modifier-reward-phase.ts | 7 +- src/phases/move-anim-phase.ts | 20 + src/phases/move-charge-phase.ts | 7 +- src/phases/move-effect-phase.ts | 345 ++- src/phases/move-header-phase.ts | 5 +- src/phases/pokemon-transform-phase.ts | 77 + src/phases/post-summon-phase.ts | 10 +- src/phases/revival-blessing-phase.ts | 61 + src/phases/ribbon-modifier-reward-phase.ts | 21 +- src/phases/select-modifier-phase.ts | 35 +- src/test/abilities/unburden.test.ts | 2 +- src/test/moves/revival_blessing.test.ts | 117 + .../clowning-around-encounter.test.ts | 2 +- .../dancing-lessons-encounter.test.ts | 2 - .../encounters/delibirdy-encounter.test.ts | 30 +- .../global-trade-system-encounter.test.ts | 4 +- .../uncommon-breed-encounter.test.ts | 4 +- src/test/utils/gameWrapper.ts | 1 + src/test/utils/phaseInterceptor.ts | 18 +- 31 files changed, 3277 insertions(+), 1608 deletions(-) create mode 100644 src/phases/load-move-anim-phase.ts create mode 100644 src/phases/move-anim-phase.ts create mode 100644 src/phases/pokemon-transform-phase.ts create mode 100644 src/phases/revival-blessing-phase.ts create mode 100644 src/test/moves/revival_blessing.test.ts diff --git a/src/battle-scene.ts b/src/battle-scene.ts index e6649d0999a..962b9c8ca91 100644 --- a/src/battle-scene.ts +++ b/src/battle-scene.ts @@ -8,10 +8,37 @@ import { allSpecies, getPokemonSpecies } from "#app/data/pokemon-species"; import type { Constructor } from "#app/utils"; import { isNullOrUndefined, randSeedInt } from "#app/utils"; import * as Utils from "#app/utils"; -import type { Modifier, ModifierPredicate, TurnHeldItemTransferModifier } from "./modifier/modifier"; -import { ConsumableModifier, ConsumablePokemonModifier, DoubleBattleChanceBoosterModifier, ExpBalanceModifier, ExpShareModifier, FusePokemonModifier, HealingBoosterModifier, ModifierBar, MultipleParticipantExpBonusModifier, PersistentModifier, PokemonExpBoosterModifier, PokemonFormChangeItemModifier, PokemonHeldItemModifier, PokemonHpRestoreModifier, PokemonIncrementingStatModifier, RememberMoveModifier } from "./modifier/modifier"; +import type { + Modifier, + ModifierPredicate, + TurnHeldItemTransferModifier, +} from "./modifier/modifier"; +import { + ConsumableModifier, + ConsumablePokemonModifier, + DoubleBattleChanceBoosterModifier, + ExpBalanceModifier, + ExpShareModifier, + FusePokemonModifier, + HealingBoosterModifier, + ModifierBar, + MultipleParticipantExpBonusModifier, + PersistentModifier, + PokemonExpBoosterModifier, + PokemonFormChangeItemModifier, + PokemonHeldItemModifier, + PokemonHpRestoreModifier, + PokemonIncrementingStatModifier, + RememberMoveModifier, +} from "./modifier/modifier"; import { PokeballType } from "#enums/pokeball"; -import { initCommonAnims, initMoveAnim, loadCommonAnimAssets, loadMoveAnimAssets, populateAnims } from "#app/data/battle-anims"; +import { + initCommonAnims, + initMoveAnim, + loadCommonAnimAssets, + loadMoveAnimAssets, + populateAnims, +} from "#app/data/battle-anims"; import type { Phase } from "#app/phase"; import { initGameSpeed } from "#app/system/game-speed"; import { Arena, ArenaBase } from "#app/field/arena"; @@ -19,9 +46,29 @@ import { GameData } from "#app/system/game-data"; import { addTextObject, getTextColor, TextStyle } from "#app/ui/text"; import { allMoves } from "#app/data/move"; import { MusicPreference } from "#app/system/settings/settings"; -import { getDefaultModifierTypeForTier, getEnemyModifierTypesForWave, getLuckString, getLuckTextTint, getModifierPoolForType, getModifierType, getPartyLuckValue, ModifierPoolType, modifierTypes, PokemonHeldItemModifierType } from "#app/modifier/modifier-type"; +import { + getDefaultModifierTypeForTier, + getEnemyModifierTypesForWave, + getLuckString, + getLuckTextTint, + getModifierPoolForType, + getModifierType, + getPartyLuckValue, + ModifierPoolType, + modifierTypes, + PokemonHeldItemModifierType, +} from "#app/modifier/modifier-type"; import AbilityBar from "#app/ui/ability-bar"; -import { allAbilities, applyAbAttrs, applyPostBattleInitAbAttrs, applyPostItemLostAbAttrs, BlockItemTheftAbAttr, DoubleBattleChanceAbAttr, PostBattleInitAbAttr, PostItemLostAbAttr } from "#app/data/ability"; +import { + allAbilities, + applyAbAttrs, + applyPostBattleInitAbAttrs, + applyPostItemLostAbAttrs, + BlockItemTheftAbAttr, + DoubleBattleChanceAbAttr, + PostBattleInitAbAttr, + PostItemLostAbAttr, +} from "#app/data/ability"; import type { FixedBattleConfig } from "#app/battle"; import Battle, { BattleType } from "#app/battle"; import type { GameMode } from "#app/game-mode"; @@ -46,8 +93,16 @@ import type UIPlugin from "phaser3-rex-plugins/templates/ui/ui-plugin"; import { addUiThemeOverrides } from "#app/ui/ui-theme"; import type PokemonData from "#app/system/pokemon-data"; import { Nature } from "#enums/nature"; -import type { SpeciesFormChange, SpeciesFormChangeTrigger } from "#app/data/pokemon-forms"; -import { FormChangeItem, pokemonFormChanges, SpeciesFormChangeManualTrigger, SpeciesFormChangeTimeOfDayTrigger } from "#app/data/pokemon-forms"; +import type { + SpeciesFormChange, + SpeciesFormChangeTrigger, +} from "#app/data/pokemon-forms"; +import { + FormChangeItem, + pokemonFormChanges, + SpeciesFormChangeManualTrigger, + SpeciesFormChangeTimeOfDayTrigger, +} from "#app/data/pokemon-forms"; import { FormChangePhase } from "#app/phases/form-change-phase"; import { getTypeRgb } from "#app/data/type"; import { Type } from "#enums/type"; @@ -100,7 +155,14 @@ import { ToggleDoublePositionPhase } from "#app/phases/toggle-double-position-ph import { TurnInitPhase } from "#app/phases/turn-init-phase"; import { ShopCursorTarget } from "#app/enums/shop-cursor-target"; import MysteryEncounter from "#app/data/mystery-encounters/mystery-encounter"; -import { allMysteryEncounters, ANTI_VARIANCE_WEIGHT_MODIFIER, AVERAGE_ENCOUNTERS_PER_RUN_TARGET, BASE_MYSTERY_ENCOUNTER_SPAWN_WEIGHT, MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT, mysteryEncountersByBiome } from "#app/data/mystery-encounters/mystery-encounters"; +import { + allMysteryEncounters, + ANTI_VARIANCE_WEIGHT_MODIFIER, + AVERAGE_ENCOUNTERS_PER_RUN_TARGET, + BASE_MYSTERY_ENCOUNTER_SPAWN_WEIGHT, + MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT, + mysteryEncountersByBiome, +} from "#app/data/mystery-encounters/mystery-encounters"; import { MysteryEncounterSaveData } from "#app/data/mystery-encounters/mystery-encounter-save-data"; import { MysteryEncounterType } from "#enums/mystery-encounter-type"; import { MysteryEncounterTier } from "#enums/mystery-encounter-tier"; @@ -118,11 +180,11 @@ export const bypassLogin = import.meta.env.VITE_BYPASS_LOGIN === "1"; const DEBUG_RNG = false; -const OPP_IVS_OVERRIDE_VALIDATED : number[] = ( - Array.isArray(Overrides.OPP_IVS_OVERRIDE) ? - Overrides.OPP_IVS_OVERRIDE : - new Array(6).fill(Overrides.OPP_IVS_OVERRIDE) -).map(iv => isNaN(iv) || iv === null || iv > 31 ? -1 : iv); +const OPP_IVS_OVERRIDE_VALIDATED: number[] = ( + Array.isArray(Overrides.OPP_IVS_OVERRIDE) + ? Overrides.OPP_IVS_OVERRIDE + : new Array(6).fill(Overrides.OPP_IVS_OVERRIDE) +).map((iv) => (isNaN(iv) || iv === null || iv > 31 ? -1 : iv)); export const startingWave = Overrides.STARTING_WAVE_OVERRIDE || 1; @@ -130,18 +192,21 @@ const expSpriteKeys: string[] = []; export let starterColors: StarterColors; interface StarterColors { - [key: string]: [string, string] + [key: string]: [string, string]; } export interface PokeballCounts { - [pb: string]: number; + [pb: string]: number; } -export type AnySound = Phaser.Sound.WebAudioSound | Phaser.Sound.HTML5AudioSound | Phaser.Sound.NoAudioSound; +export type AnySound = + | Phaser.Sound.WebAudioSound + | Phaser.Sound.HTML5AudioSound + | Phaser.Sound.NoAudioSound; export interface InfoToggle { - toggleInfo(force?: boolean): void; - isActive(): boolean; + toggleInfo(force?: boolean): void; + isActive(): boolean; } export default class BattleScene extends SceneBase { @@ -167,7 +232,8 @@ export default class BattleScene extends SceneBase { public showTimeOfDayWidget: boolean = true; public timeOfDayAnimation: EaseType = EaseType.NONE; public showLevelUpStats: boolean = true; - public enableTutorials: boolean = import.meta.env.VITE_BYPASS_TUTORIAL === "1"; + public enableTutorials: boolean = + import.meta.env.VITE_BYPASS_TUTORIAL === "1"; public enableMoveInfo: boolean = true; public enableRetries: boolean = false; public hideIvs: boolean = false; @@ -201,17 +267,17 @@ export default class BattleScene extends SceneBase { public eggSkipPreference: number = 0; /** - * Defines the experience gain display mode. - * - * @remarks - * The `expParty` can have several modes: - * - `0` - Default: The normal experience gain display, nothing changed. - * - `1` - Level Up Notification: Displays the level up in the small frame instead of a message. - * - `2` - Skip: No level up frame nor message. - * - * Modes `1` and `2` are still compatible with stats display, level up, new move, etc. - * @default 0 - Uses the default normal experience gain display. - */ + * Defines the experience gain display mode. + * + * @remarks + * The `expParty` can have several modes: + * - `0` - Default: The normal experience gain display, nothing changed. + * - `1` - Level Up Notification: Displays the level up in the small frame instead of a message. + * - `2` - Skip: No level up frame nor message. + * + * Modes `1` and `2` are still compatible with stats display, level up, new move, etc. + * @default 0 - Uses the default normal experience gain display. + */ public expParty: ExpNotification = 0; public hpBarSpeed: number = 0; public fusionPaletteSwaps: boolean = true; @@ -227,9 +293,9 @@ export default class BattleScene extends SceneBase { public battleStyle: number = BattleStyle.SWITCH; /** - * Defines whether or not to show type effectiveness hints - * - true: No hints - * - false: Show hints for moves + * Defines whether or not to show type effectiveness hints + * - true: No hints + * - false: Show hints for moves */ public typeHints: boolean = false; @@ -276,7 +342,8 @@ export default class BattleScene extends SceneBase { public pokemonInfoContainer: PokemonInfoContainer; private party: PlayerPokemon[]; /** Session save data that pertains to Mystery Encounters */ - public mysteryEncounterSaveData: MysteryEncounterSaveData = new MysteryEncounterSaveData(); + public mysteryEncounterSaveData: MysteryEncounterSaveData = + new MysteryEncounterSaveData(); /** If the previous wave was a MysteryEncounter, tracks the object with this variable. Mostly used for visual object cleanup */ public lastMysteryEncounter?: MysteryEncounter; /** Combined Biome and Wave count text */ @@ -292,7 +359,7 @@ export default class BattleScene extends SceneBase { private fieldOverlay: Phaser.GameObjects.Rectangle; private shopOverlay: Phaser.GameObjects.Rectangle; private shopOverlayShown: boolean = false; - private shopOverlayOpacity: number = .8; + private shopOverlayOpacity: number = 0.8; public modifiers: PersistentModifier[]; private enemyModifiers: PersistentModifier[]; @@ -358,19 +425,30 @@ export default class BattleScene extends SceneBase { if (variant) { atlasPath = atlasPath.replace("variant/", ""); } - this.load.atlas(key, `images/pokemon/${variant ? "variant/" : ""}${experimental ? "exp/" : ""}${atlasPath}.png`, `images/pokemon/${variant ? "variant/" : ""}${experimental ? "exp/" : ""}${atlasPath}.json`); + this.load.atlas( + key, + `images/pokemon/${variant ? "variant/" : ""}${experimental ? "exp/" : ""}${atlasPath}.png`, + `images/pokemon/${variant ? "variant/" : ""}${experimental ? "exp/" : ""}${atlasPath}.json`, + ); } /** * Load the variant assets for the given sprite and stores them in {@linkcode variantColorCache} */ - public async loadPokemonVariantAssets(spriteKey: string, fileRoot: string, variant?: Variant): Promise { - const useExpSprite = this.experimentalSprites && this.hasExpSprite(spriteKey); + public async loadPokemonVariantAssets( + spriteKey: string, + fileRoot: string, + variant?: Variant, + ): Promise { + const useExpSprite = + this.experimentalSprites && this.hasExpSprite(spriteKey); if (useExpSprite) { fileRoot = `exp/${fileRoot}`; } let variantConfig = variantData; - fileRoot.split("/").map((p) => (variantConfig ? (variantConfig = variantConfig[p]) : null)); + fileRoot + .split("/") + .map((p) => (variantConfig ? (variantConfig = variantConfig[p]) : null)); const variantSet = variantConfig as VariantSet; return new Promise((resolve) => { @@ -393,10 +471,20 @@ export default class BattleScene extends SceneBase { async preload() { if (DEBUG_RNG) { const originalRealInRange = Phaser.Math.RND.realInRange; - Phaser.Math.RND.realInRange = function (min: number, max: number): number { + Phaser.Math.RND.realInRange = function ( + min: number, + max: number, + ): number { const ret = originalRealInRange.apply(this, [ min, max ]); - const args = [ "RNG", ++this.rngCounter, ret / (max - min), `min: ${min} / max: ${max}` ]; - args.push(`seed: ${this.rngSeedOverride || this.waveSeed || this.seed}`); + const args = [ + "RNG", + ++this.rngCounter, + ret / (max - min), + `min: ${min} / max: ${max}`, + ]; + args.push( + `seed: ${this.rngSeedOverride || this.waveSeed || this.seed}`, + ); if (this.rngOffset) { args.push(`offset: ${this.rngOffset}`); } @@ -423,10 +511,16 @@ export default class BattleScene extends SceneBase { this.load.setBaseURL(); this.spritePipeline = new SpritePipeline(this.game); - (this.renderer as Phaser.Renderer.WebGL.WebGLRenderer).pipelines.add("Sprite", this.spritePipeline); + (this.renderer as Phaser.Renderer.WebGL.WebGLRenderer).pipelines.add( + "Sprite", + this.spritePipeline, + ); this.fieldSpritePipeline = new FieldSpritePipeline(this.game); - (this.renderer as Phaser.Renderer.WebGL.WebGLRenderer).pipelines.add("FieldSprite", this.fieldSpritePipeline); + (this.renderer as Phaser.Renderer.WebGL.WebGLRenderer).pipelines.add( + "FieldSprite", + this.fieldSpritePipeline, + ); this.launchBattle(); } @@ -441,7 +535,7 @@ export default class BattleScene extends SceneBase { this.arenaBgTransition = this.add.sprite(0, 0, "plains_bg"); this.arenaBgTransition.setName("sprite-arena-bg-transition"); - [ this.arenaBgTransition, this.arenaBg ].forEach(a => { + [ this.arenaBgTransition, this.arenaBg ].forEach((a) => { a.setPipeline(this.fieldSpritePipeline); a.setScale(6); a.setOrigin(0); @@ -461,13 +555,16 @@ export default class BattleScene extends SceneBase { this.fieldUI = fieldUI; - const transition = this.make.rexTransitionImagePack({ - x: 0, - y: 0, - scale: 6, - key: "loading_bg", - origin: { x: 0, y: 0 } - }, true); + const transition = this.make.rexTransitionImagePack( + { + x: 0, + y: 0, + scale: 6, + key: "loading_bg", + origin: { x: 0, y: 0 }, + }, + true, + ); //@ts-ignore (the defined types in the package are incromplete...) transition.transit({ @@ -489,14 +586,26 @@ export default class BattleScene extends SceneBase { this.uiContainer = uiContainer; const overlayWidth = this.game.canvas.width / 6; - const overlayHeight = (this.game.canvas.height / 6) - 48; - this.fieldOverlay = this.add.rectangle(0, overlayHeight * -1 - 48, overlayWidth, overlayHeight, 0x424242); + const overlayHeight = this.game.canvas.height / 6 - 48; + this.fieldOverlay = this.add.rectangle( + 0, + overlayHeight * -1 - 48, + overlayWidth, + overlayHeight, + 0x424242, + ); this.fieldOverlay.setName("rect-field-overlay"); this.fieldOverlay.setOrigin(0, 0); this.fieldOverlay.setAlpha(0); this.fieldUI.add(this.fieldOverlay); - this.shopOverlay = this.add.rectangle(0, overlayHeight * -1 - 48, overlayWidth, overlayHeight, 0x070707); + this.shopOverlay = this.add.rectangle( + 0, + overlayHeight * -1 - 48, + overlayWidth, + overlayHeight, + 0x070707, + ); this.shopOverlay.setName("rect-shop-overlay"); this.shopOverlay.setOrigin(0, 0); this.shopOverlay.setAlpha(0); @@ -547,28 +656,56 @@ export default class BattleScene extends SceneBase { this.candyBar.setup(); this.fieldUI.add(this.candyBar); - this.biomeWaveText = addTextObject((this.game.canvas.width / 6) - 2, 0, startingWave.toString(), TextStyle.BATTLE_INFO); + this.biomeWaveText = addTextObject( + this.game.canvas.width / 6 - 2, + 0, + startingWave.toString(), + TextStyle.BATTLE_INFO, + ); this.biomeWaveText.setName("text-biome-wave"); this.biomeWaveText.setOrigin(1, 0.5); this.fieldUI.add(this.biomeWaveText); - this.moneyText = addTextObject((this.game.canvas.width / 6) - 2, 0, "", TextStyle.MONEY); + this.moneyText = addTextObject( + this.game.canvas.width / 6 - 2, + 0, + "", + TextStyle.MONEY, + ); this.moneyText.setName("text-money"); this.moneyText.setOrigin(1, 0.5); this.fieldUI.add(this.moneyText); - this.scoreText = addTextObject((this.game.canvas.width / 6) - 2, 0, "", TextStyle.PARTY, { fontSize: "54px" }); + this.scoreText = addTextObject( + this.game.canvas.width / 6 - 2, + 0, + "", + TextStyle.PARTY, + { fontSize: "54px" }, + ); this.scoreText.setName("text-score"); this.scoreText.setOrigin(1, 0.5); this.fieldUI.add(this.scoreText); - this.luckText = addTextObject((this.game.canvas.width / 6) - 2, 0, "", TextStyle.PARTY, { fontSize: "54px" }); + this.luckText = addTextObject( + this.game.canvas.width / 6 - 2, + 0, + "", + TextStyle.PARTY, + { fontSize: "54px" }, + ); this.luckText.setName("text-luck"); this.luckText.setOrigin(1, 0.5); this.luckText.setVisible(false); this.fieldUI.add(this.luckText); - this.luckLabelText = addTextObject((this.game.canvas.width / 6) - 2, 0, i18next.t("common:luckIndicator"), TextStyle.PARTY, { fontSize: "54px" }); + this.luckLabelText = addTextObject( + this.game.canvas.width / 6 - 2, + 0, + i18next.t("common:luckIndicator"), + TextStyle.PARTY, + { fontSize: "54px" }, + ); this.luckLabelText.setName("text-luck-label"); this.luckLabelText.setOrigin(1, 0.5); this.luckLabelText.setVisible(false); @@ -576,7 +713,10 @@ export default class BattleScene extends SceneBase { this.arenaFlyout = new ArenaFlyout(); this.fieldUI.add(this.arenaFlyout); - this.fieldUI.moveBelow(this.arenaFlyout, this.fieldOverlay); + this.fieldUI.moveBelow( + this.arenaFlyout, + this.fieldOverlay, + ); this.updateUIPositions(); @@ -585,7 +725,10 @@ export default class BattleScene extends SceneBase { this.spriteSparkleHandler = new PokemonSpriteSparkleHandler(); this.spriteSparkleHandler.setup(); - this.pokemonInfoContainer = new PokemonInfoContainer((this.game.canvas.width / 6) + 52, -(this.game.canvas.height / 6) + 66); + this.pokemonInfoContainer = new PokemonInfoContainer( + this.game.canvas.width / 6 + 52, + -(this.game.canvas.height / 6) + 66, + ); this.pokemonInfoContainer.setup(); this.fieldUI.add(this.pokemonInfoContainer); @@ -607,14 +750,23 @@ export default class BattleScene extends SceneBase { this.arenaPlayerTransition.setVisible(false); this.arenaNextEnemy.setVisible(false); - [ this.arenaPlayer, this.arenaPlayerTransition, this.arenaEnemy, this.arenaNextEnemy ].forEach(a => { + [ + this.arenaPlayer, + this.arenaPlayerTransition, + this.arenaEnemy, + this.arenaNextEnemy, + ].forEach((a) => { if (a instanceof Phaser.GameObjects.Sprite) { a.setOrigin(0, 0); } field.add(a); }); - const trainer = this.addFieldSprite(0, 0, `trainer_${this.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`); + const trainer = this.addFieldSprite( + 0, + 0, + `trainer_${this.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`, + ); trainer.setOrigin(0.5, 1); trainer.setName("sprite-trainer"); @@ -627,16 +779,19 @@ export default class BattleScene extends SceneBase { frames: this.anims.generateFrameNumbers("prompt", { start: 1, end: 4 }), frameRate: 6, repeat: -1, - showOnStart: true + showOnStart: true, }); this.anims.create({ key: "tera_sparkle", - frames: this.anims.generateFrameNumbers("tera_sparkle", { start: 0, end: 12 }), + frames: this.anims.generateFrameNumbers("tera_sparkle", { + start: 0, + end: 12, + }), frameRate: 18, repeat: 0, showOnStart: true, - hideOnComplete: true + hideOnComplete: true, }); this.reset(false, false, true); @@ -648,13 +803,22 @@ export default class BattleScene extends SceneBase { ui.setup(); - const defaultMoves = [ Moves.TACKLE, Moves.TAIL_WHIP, Moves.FOCUS_ENERGY, Moves.STRUGGLE ]; + const defaultMoves = [ + Moves.TACKLE, + Moves.TAIL_WHIP, + Moves.FOCUS_ENERGY, + Moves.STRUGGLE, + ]; Promise.all([ Promise.all(loadPokemonAssets), initCommonAnims().then(() => loadCommonAnimAssets(true)), - Promise.all([ Moves.TACKLE, Moves.TAIL_WHIP, Moves.FOCUS_ENERGY, Moves.STRUGGLE ].map(m => initMoveAnim(m))).then(() => loadMoveAnimAssets(defaultMoves, true)), - this.initStarterColors() + Promise.all( + [ Moves.TACKLE, Moves.TAIL_WHIP, Moves.FOCUS_ENERGY, Moves.STRUGGLE ].map( + (m) => initMoveAnim(m), + ), + ).then(() => loadMoveAnimAssets(defaultMoves, true)), + this.initStarterColors(), ]).then(() => { this.pushPhase(new LoginPhase()); this.pushPhase(new TitlePhase()); @@ -688,7 +852,7 @@ export default class BattleScene extends SceneBase { if (this.lastSavePlayTime !== null) { this.lastSavePlayTime++; } - } + }, }); this.updateBiomeWaveText(); @@ -700,19 +864,22 @@ export default class BattleScene extends SceneBase { if (expSpriteKeys.length) { return; } - this.cachedFetch("./exp-sprites.json").then(res => res.json()).then(keys => { - if (Array.isArray(keys)) { - expSpriteKeys.push(...keys); - } - Promise.resolve(); - }); + this.cachedFetch("./exp-sprites.json") + .then((res) => res.json()) + .then((keys) => { + if (Array.isArray(keys)) { + expSpriteKeys.push(...keys); + } + Promise.resolve(); + }); } async initVariantData(): Promise { - Object.keys(variantData).forEach(key => delete variantData[key]); - await this.cachedFetch("./images/pokemon/variant/_masterlist.json").then(res => res.json()) - .then(v => { - Object.keys(v).forEach(k => variantData[k] = v[k]); + Object.keys(variantData).forEach((key) => delete variantData[key]); + await this.cachedFetch("./images/pokemon/variant/_masterlist.json") + .then((res) => res.json()) + .then((v) => { + Object.keys(v).forEach((k) => (variantData[k] = v[k])); if (this.experimentalSprites) { const expVariantData = variantData["exp"]; const traverseVariantData = (keys: string[]) => { @@ -722,7 +889,10 @@ export default class BattleScene extends SceneBase { if (i < keys.length - 1) { variantTree = variantTree[k]; expTree = expTree[k]; - } else if (variantTree.hasOwnProperty(k) && expTree.hasOwnProperty(k)) { + } else if ( + variantTree.hasOwnProperty(k) && + expTree.hasOwnProperty(k) + ) { if ([ "back", "female" ].includes(k)) { traverseVariantData(keys.concat(k)); } else { @@ -731,7 +901,9 @@ export default class BattleScene extends SceneBase { } }); }; - Object.keys(expVariantData).forEach(ek => traverseVariantData([ ek ])); + Object.keys(expVariantData).forEach((ek) => + traverseVariantData([ ek ]), + ); } Promise.resolve(); }); @@ -749,18 +921,20 @@ export default class BattleScene extends SceneBase { } initStarterColors(): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { if (starterColors) { return resolve(); } - this.cachedFetch("./starter-colors.json").then(res => res.json()).then(sc => { - starterColors = {}; - Object.keys(sc).forEach(key => { - starterColors[key] = sc[key]; - }); + this.cachedFetch("./starter-colors.json") + .then((res) => res.json()) + .then((sc) => { + starterColors = {}; + Object.keys(sc).forEach((key) => { + starterColors[key] = sc[key]; + }); - /*const loadPokemonAssets: Promise[] = []; + /*const loadPokemonAssets: Promise[] = []; for (let s of Object.keys(speciesStarters)) { const species = getPokemonSpecies(parseInt(s)); @@ -782,13 +956,16 @@ export default class BattleScene extends SceneBase { resolve(); });*/ - resolve(); - }); + resolve(); + }); }); } hasExpSprite(key: string): boolean { - const keyMatch = /^pkmn__?(back__)?(shiny__)?(female__)?(\d+)(\-.*?)?(?:_[1-3])?$/g.exec(key); + const keyMatch = + /^pkmn__?(back__)?(shiny__)?(female__)?(\d+)(\-.*?)?(?:_[1-3])?$/g.exec( + key, + ); if (!keyMatch) { return false; } @@ -821,7 +998,7 @@ export default class BattleScene extends SceneBase { * that are {@linkcode Pokemon.isAllowedInBattle | allowed in battle}. */ public getPokemonAllowedInBattle(): PlayerPokemon[] { - return this.getPlayerParty().filter(p => p.isAllowedInBattle()); + return this.getPlayerParty().filter((p) => p.isAllowedInBattle()); } /** @@ -831,8 +1008,12 @@ export default class BattleScene extends SceneBase { * or `undefined` if there are no valid pokemon * @param includeSwitching Whether a pokemon that is currently switching out is valid, default `true` */ - public getPlayerPokemon(includeSwitching: boolean = true): PlayerPokemon | undefined { - return this.getPlayerField().find(p => p.isActive() && (includeSwitching || p.switchOutStatus === false)); + public getPlayerPokemon( + includeSwitching: boolean = true, + ): PlayerPokemon | undefined { + return this.getPlayerField().find( + (p) => p.isActive() && (includeSwitching || p.switchOutStatus === false), + ); } /** @@ -842,7 +1023,10 @@ export default class BattleScene extends SceneBase { */ public getPlayerField(): PlayerPokemon[] { const party = this.getPlayerParty(); - return party.slice(0, Math.min(party.length, this.currentBattle?.double ? 2 : 1)); + return party.slice( + 0, + Math.min(party.length, this.currentBattle?.double ? 2 : 1), + ); } public getEnemyParty(): EnemyPokemon[] { @@ -856,8 +1040,12 @@ export default class BattleScene extends SceneBase { * or `undefined` if there are no valid pokemon * @param includeSwitching Whether a pokemon that is currently switching out is valid, default `true` */ - public getEnemyPokemon(includeSwitching: boolean = true): EnemyPokemon | undefined { - return this.getEnemyField().find(p => p.isActive() && (includeSwitching || p.switchOutStatus === false)); + public getEnemyPokemon( + includeSwitching: boolean = true, + ): EnemyPokemon | undefined { + return this.getEnemyField().find( + (p) => p.isActive() && (includeSwitching || p.switchOutStatus === false), + ); } /** @@ -867,7 +1055,10 @@ export default class BattleScene extends SceneBase { */ public getEnemyField(): EnemyPokemon[] { const party = this.getEnemyParty(); - return party.slice(0, Math.min(party.length, this.currentBattle?.double ? 2 : 1)); + return party.slice( + 0, + Math.min(party.length, this.currentBattle?.double ? 2 : 1), + ); } /** @@ -882,9 +1073,7 @@ export default class BattleScene extends SceneBase { const enemyField = this.getEnemyField(); ret.splice(0, playerField.length, ...playerField); ret.splice(2, enemyField.length, ...enemyField); - return activeOnly - ? ret.filter(p => p?.isActive()) - : ret; + return activeOnly ? ret.filter((p) => p?.isActive()) : ret; } /** @@ -900,8 +1089,17 @@ export default class BattleScene extends SceneBase { if (allyPokemon?.isActive(true)) { let targetingMovePhase: MovePhase; do { - targetingMovePhase = this.findPhase(mp => mp instanceof MovePhase && mp.targets.length === 1 && mp.targets[0] === removedPokemon.getBattlerIndex() && mp.pokemon.isPlayer() !== allyPokemon.isPlayer()) as MovePhase; - if (targetingMovePhase && targetingMovePhase.targets[0] !== allyPokemon.getBattlerIndex()) { + targetingMovePhase = this.findPhase( + (mp) => + mp instanceof MovePhase && + mp.targets.length === 1 && + mp.targets[0] === removedPokemon.getBattlerIndex() && + mp.pokemon.isPlayer() !== allyPokemon.isPlayer(), + ) as MovePhase; + if ( + targetingMovePhase && + targetingMovePhase.targets[0] !== allyPokemon.getBattlerIndex() + ) { targetingMovePhase.targets[0] = allyPokemon.getBattlerIndex(); } } while (targetingMovePhase); @@ -924,16 +1122,46 @@ export default class BattleScene extends SceneBase { // return the stored info toggles; used by ui-inputs getInfoToggles(activeOnly: boolean = false): InfoToggle[] { - return activeOnly ? this.infoToggles.filter(t => t?.isActive()) : this.infoToggles; + return activeOnly + ? this.infoToggles.filter((t) => t?.isActive()) + : this.infoToggles; } getPokemonById(pokemonId: number): Pokemon | null { - const findInParty = (party: Pokemon[]) => party.find(p => p.id === pokemonId); - return (findInParty(this.getPlayerParty()) || findInParty(this.getEnemyParty())) ?? null; + const findInParty = (party: Pokemon[]) => + party.find((p) => p.id === pokemonId); + return ( + (findInParty(this.getPlayerParty()) || + findInParty(this.getEnemyParty())) ?? + null + ); } - addPlayerPokemon(species: PokemonSpecies, level: number, abilityIndex?: number, formIndex?: number, gender?: Gender, shiny?: boolean, variant?: Variant, ivs?: number[], nature?: Nature, dataSource?: Pokemon | PokemonData, postProcess?: (playerPokemon: PlayerPokemon) => void): PlayerPokemon { - const pokemon = new PlayerPokemon(species, level, abilityIndex, formIndex, gender, shiny, variant, ivs, nature, dataSource); + addPlayerPokemon( + species: PokemonSpecies, + level: number, + abilityIndex?: number, + formIndex?: number, + gender?: Gender, + shiny?: boolean, + variant?: Variant, + ivs?: number[], + nature?: Nature, + dataSource?: Pokemon | PokemonData, + postProcess?: (playerPokemon: PlayerPokemon) => void, + ): PlayerPokemon { + const pokemon = new PlayerPokemon( + species, + level, + abilityIndex, + formIndex, + gender, + shiny, + variant, + ivs, + nature, + dataSource, + ); if (postProcess) { postProcess(pokemon); } @@ -941,17 +1169,37 @@ export default class BattleScene extends SceneBase { return pokemon; } - addEnemyPokemon(species: PokemonSpecies, level: number, trainerSlot: TrainerSlot, boss: boolean = false, shinyLock: boolean = false, dataSource?: PokemonData, postProcess?: (enemyPokemon: EnemyPokemon) => void): EnemyPokemon { + addEnemyPokemon( + species: PokemonSpecies, + level: number, + trainerSlot: TrainerSlot, + boss: boolean = false, + shinyLock: boolean = false, + dataSource?: PokemonData, + postProcess?: (enemyPokemon: EnemyPokemon) => void, + ): EnemyPokemon { if (Overrides.OPP_LEVEL_OVERRIDE > 0) { level = Overrides.OPP_LEVEL_OVERRIDE; } if (Overrides.OPP_SPECIES_OVERRIDE) { species = getPokemonSpecies(Overrides.OPP_SPECIES_OVERRIDE); // The fact that a Pokemon is a boss or not can change based on its Species and level - boss = this.getEncounterBossSegments(this.currentBattle.waveIndex, level, species) > 1; + boss = + this.getEncounterBossSegments( + this.currentBattle.waveIndex, + level, + species, + ) > 1; } - const pokemon = new EnemyPokemon(species, level, trainerSlot, boss, shinyLock, dataSource); + const pokemon = new EnemyPokemon( + species, + level, + trainerSlot, + boss, + shinyLock, + dataSource, + ); if (Overrides.OPP_FUSION_OVERRIDE) { pokemon.generateFusionSpecies(); } @@ -960,7 +1208,13 @@ export default class BattleScene extends SceneBase { const secondaryIvs = Utils.getIvsFromId(Utils.randSeedInt(4294967296)); for (let s = 0; s < pokemon.ivs.length; s++) { - pokemon.ivs[s] = Math.round(Phaser.Math.Linear(Math.min(pokemon.ivs[s], secondaryIvs[s]), Math.max(pokemon.ivs[s], secondaryIvs[s]), 0.75)); + pokemon.ivs[s] = Math.round( + Phaser.Math.Linear( + Math.min(pokemon.ivs[s], secondaryIvs[s]), + Math.max(pokemon.ivs[s], secondaryIvs[s]), + 0.75, + ), + ); } } if (postProcess) { @@ -983,7 +1237,10 @@ export default class BattleScene extends SceneBase { * @param pokemon * @param destroy Default true. If true, will destroy the {@linkcode PlayerPokemon} after removing */ - removePokemonFromPlayerParty(pokemon: PlayerPokemon, destroy: boolean = true) { + removePokemonFromPlayerParty( + pokemon: PlayerPokemon, + destroy: boolean = true, + ) { if (!pokemon) { return; } @@ -997,7 +1254,14 @@ export default class BattleScene extends SceneBase { this.updateModifiers(true); } - addPokemonIcon(pokemon: Pokemon, x: number, y: number, originX: number = 0.5, originY: number = 0.5, ignoreOverride: boolean = false): Phaser.GameObjects.Container { + addPokemonIcon( + pokemon: Pokemon, + x: number, + y: number, + originX: number = 0.5, + originY: number = 0.5, + ignoreOverride: boolean = false, + ): Phaser.GameObjects.Container { const container = this.add.container(x, y); container.setName(`${pokemon.name}-icon`); @@ -1006,7 +1270,9 @@ export default class BattleScene extends SceneBase { icon.setFrame(pokemon.getIconId(true)); // Temporary fix to show pokemon's default icon if variant icon doesn't exist if (icon.frame.name !== pokemon.getIconId(true)) { - console.log(`${pokemon.name}'s variant icon does not exist. Replacing with default.`); + console.log( + `${pokemon.name}'s variant icon does not exist. Replacing with default.`, + ); const temp = pokemon.shiny; pokemon.shiny = false; icon.setTexture(pokemon.getIconAtlasKey(ignoreOverride)); @@ -1018,7 +1284,11 @@ export default class BattleScene extends SceneBase { container.add(icon); if (pokemon.isFusion()) { - const fusionIcon = this.add.sprite(0, 0, pokemon.getFusionIconAtlasKey(ignoreOverride)); + const fusionIcon = this.add.sprite( + 0, + 0, + pokemon.getFusionIconAtlasKey(ignoreOverride), + ); fusionIcon.setName("sprite-fusion-icon"); fusionIcon.setOrigin(0.5, 0); fusionIcon.setFrame(pokemon.getFusionIconId(true)); @@ -1027,13 +1297,24 @@ export default class BattleScene extends SceneBase { const originalHeight = icon.height; const originalFrame = icon.frame; - const iconHeight = (icon.frame.cutHeight <= fusionIcon.frame.cutHeight ? Math.ceil : Math.floor)((icon.frame.cutHeight + fusionIcon.frame.cutHeight) / 4); + const iconHeight = ( + icon.frame.cutHeight <= fusionIcon.frame.cutHeight + ? Math.ceil + : Math.floor + )((icon.frame.cutHeight + fusionIcon.frame.cutHeight) / 4); // Inefficient, but for some reason didn't work with only the unique properties as part of the name const iconFrameId = `${icon.frame.name}f${fusionIcon.frame.name}`; if (!icon.frame.texture.has(iconFrameId)) { - icon.frame.texture.add(iconFrameId, icon.frame.sourceIndex, icon.frame.cutX, icon.frame.cutY, icon.frame.cutWidth, iconHeight); + icon.frame.texture.add( + iconFrameId, + icon.frame.sourceIndex, + icon.frame.cutX, + icon.frame.cutY, + icon.frame.cutWidth, + iconHeight, + ); } icon.setFrame(iconFrameId); @@ -1043,13 +1324,21 @@ export default class BattleScene extends SceneBase { const originalFusionFrame = fusionIcon.frame; const fusionIconY = fusionIcon.frame.cutY + icon.frame.cutHeight; - const fusionIconHeight = fusionIcon.frame.cutHeight - icon.frame.cutHeight; + const fusionIconHeight = + fusionIcon.frame.cutHeight - icon.frame.cutHeight; // Inefficient, but for some reason didn't work with only the unique properties as part of the name const fusionIconFrameId = `${fusionIcon.frame.name}f${icon.frame.name}`; if (!fusionIcon.frame.texture.has(fusionIconFrameId)) { - fusionIcon.frame.texture.add(fusionIconFrameId, fusionIcon.frame.sourceIndex, fusionIcon.frame.cutX, fusionIconY, fusionIcon.frame.cutWidth, fusionIconHeight); + fusionIcon.frame.texture.add( + fusionIconFrameId, + fusionIcon.frame.sourceIndex, + fusionIcon.frame.cutX, + fusionIconY, + fusionIcon.frame.cutWidth, + fusionIconHeight, + ); } fusionIcon.setFrame(fusionIconFrameId); @@ -1062,7 +1351,7 @@ export default class BattleScene extends SceneBase { container.x -= originalWidth * (originX - 0.5); } if (originY !== 0) { - container.y -= (originalHeight) * originY; + container.y -= originalHeight * originY; } } else { if (originX !== 0.5) { @@ -1097,7 +1386,11 @@ export default class BattleScene extends SceneBase { return this.currentBattle?.randSeedInt(range, min); } - reset(clearScene: boolean = false, clearData: boolean = false, reloadI18n: boolean = false): void { + reset( + clearScene: boolean = false, + clearData: boolean = false, + reloadI18n: boolean = false, + ): void { if (clearData) { this.gameData = new GameData(); } @@ -1111,7 +1404,11 @@ export default class BattleScene extends SceneBase { this.lockModifierTiers = false; - this.pokeballCounts = Object.fromEntries(Utils.getEnumValues(PokeballType).filter(p => p <= PokeballType.MASTER_BALL).map(t => [ t, 0 ])); + this.pokeballCounts = Object.fromEntries( + Utils.getEnumValues(PokeballType) + .filter((p) => p <= PokeballType.MASTER_BALL) + .map((t) => [ t, 0 ]), + ); this.pokeballCounts[PokeballType.POKEBALL] += 5; if (Overrides.POKEBALL_OVERRIDE.active) { this.pokeballCounts = Overrides.POKEBALL_OVERRIDE.pokeballs; @@ -1132,7 +1429,10 @@ export default class BattleScene extends SceneBase { // If this is a ME, clear any residual visual sprites before reloading if (this.currentBattle?.mysteryEncounter?.introVisuals) { - this.field.remove(this.currentBattle.mysteryEncounter?.introVisuals, true); + this.field.remove( + this.currentBattle.mysteryEncounter?.introVisuals, + true, + ); } //@ts-ignore - allowing `null` for currentBattle causes a lot of trouble @@ -1153,7 +1453,7 @@ export default class BattleScene extends SceneBase { this.updateScoreText(); this.scoreText.setVisible(false); - [ this.luckLabelText, this.luckText ].map(t => t.setVisible(false)); + [ this.luckLabelText, this.luckText ].map((t) => t.setVisible(false)); this.newArena(Overrides.STARTING_BIOME_OVERRIDE || Biome.TOWN); @@ -1162,12 +1462,16 @@ export default class BattleScene extends SceneBase { this.arenaBgTransition.setPosition(0, 0); this.arenaPlayer.setPosition(300, 0); this.arenaPlayerTransition.setPosition(0, 0); - [ this.arenaEnemy, this.arenaNextEnemy ].forEach(a => a.setPosition(-280, 0)); + [ this.arenaEnemy, this.arenaNextEnemy ].forEach((a) => + a.setPosition(-280, 0), + ); this.arenaNextEnemy.setVisible(false); this.arena.init(); - this.trainer.setTexture(`trainer_${this.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`); + this.trainer.setTexture( + `trainer_${this.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`, + ); this.trainer.setPosition(406, 186); this.trainer.setVisible(true); @@ -1180,7 +1484,16 @@ export default class BattleScene extends SceneBase { ...allSpecies, ...allMoves, ...allAbilities, - ...Utils.getEnumValues(ModifierPoolType).map(mpt => getModifierPoolForType(mpt)).map(mp => Object.values(mp).flat().map(mt => mt.modifierType).filter(mt => "localize" in mt).map(lpb => lpb as unknown as Localizable)).flat() + ...Utils.getEnumValues(ModifierPoolType) + .map((mpt) => getModifierPoolForType(mpt)) + .map((mp) => + Object.values(mp) + .flat() + .map((mt) => mt.modifierType) + .filter((mt) => "localize" in mt) + .map((lpb) => lpb as unknown as Localizable), + ) + .flat(), ]; for (const item of localizable) { item.localize(); @@ -1206,21 +1519,32 @@ export default class BattleScene extends SceneBase { this.children.removeAll(true); this.game.domContainer.innerHTML = ""; this.launchBattle(); - } + }, }); } } getDoubleBattleChance(newWaveIndex: number, playerField: PlayerPokemon[]) { - const doubleChance = new Utils.NumberHolder(newWaveIndex % 10 === 0 ? 32 : 8); + const doubleChance = new Utils.NumberHolder( + newWaveIndex % 10 === 0 ? 32 : 8, + ); this.applyModifiers(DoubleBattleChanceBoosterModifier, true, doubleChance); - playerField.forEach(p => applyAbAttrs(DoubleBattleChanceAbAttr, p, null, false, doubleChance)); + playerField.forEach((p) => + applyAbAttrs(DoubleBattleChanceAbAttr, p, null, false, doubleChance), + ); return Math.max(doubleChance.value, 1); } - newBattle(waveIndex?: number, battleType?: BattleType, trainerData?: TrainerData, double?: boolean, mysteryEncounterType?: MysteryEncounterType): Battle | null { + newBattle( + waveIndex?: number, + battleType?: BattleType, + trainerData?: TrainerData, + double?: boolean, + mysteryEncounterType?: MysteryEncounterType, + ): Battle | null { const _startingWave = Overrides.STARTING_WAVE_OVERRIDE || startingWave; - const newWaveIndex = waveIndex || ((this.currentBattle?.waveIndex || (_startingWave - 1)) + 1); + const newWaveIndex = + waveIndex || (this.currentBattle?.waveIndex || _startingWave - 1) + 1; let newDouble: boolean | undefined; let newBattleType: BattleType; let newTrainer: Trainer | undefined; @@ -1231,11 +1555,17 @@ export default class BattleScene extends SceneBase { const playerField = this.getPlayerField(); - if (this.gameMode.isFixedBattle(newWaveIndex) && trainerData === undefined) { + if ( + this.gameMode.isFixedBattle(newWaveIndex) && + trainerData === undefined + ) { battleConfig = this.gameMode.getFixedBattle(newWaveIndex); newDouble = battleConfig.double; newBattleType = battleConfig.battleType; - this.executeWithSeedOffset(() => newTrainer = battleConfig?.getTrainer(), (battleConfig.seedOffsetWaveIndex || newWaveIndex) << 8); + this.executeWithSeedOffset( + () => (newTrainer = battleConfig?.getTrainer()), + (battleConfig.seedOffsetWaveIndex || newWaveIndex) << 8, + ); if (newTrainer) { this.field.add(newTrainer); } @@ -1243,7 +1573,9 @@ export default class BattleScene extends SceneBase { if (!this.gameMode.hasTrainers) { newBattleType = BattleType.WILD; } else if (battleType === undefined) { - newBattleType = this.gameMode.isWaveTrainer(newWaveIndex, this.arena) ? BattleType.TRAINER : BattleType.WILD; + newBattleType = this.gameMode.isWaveTrainer(newWaveIndex, this.arena) + ? BattleType.TRAINER + : BattleType.WILD; } else { newBattleType = battleType; } @@ -1254,29 +1586,50 @@ export default class BattleScene extends SceneBase { if (trainerConfigs[trainerType].doubleOnly) { doubleTrainer = true; } else if (trainerConfigs[trainerType].hasDouble) { - doubleTrainer = !Utils.randSeedInt(this.getDoubleBattleChance(newWaveIndex, playerField)); + doubleTrainer = !Utils.randSeedInt( + this.getDoubleBattleChance(newWaveIndex, playerField), + ); // Add a check that special trainers can't be double except for tate and liza - they should use the normal double chance - if (trainerConfigs[trainerType].trainerTypeDouble && ![ TrainerType.TATE, TrainerType.LIZA ].includes(trainerType)) { + if ( + trainerConfigs[trainerType].trainerTypeDouble && + ![ TrainerType.TATE, TrainerType.LIZA ].includes(trainerType) + ) { doubleTrainer = false; } } - const variant = doubleTrainer ? TrainerVariant.DOUBLE : (Utils.randSeedInt(2) ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT); - newTrainer = trainerData !== undefined ? trainerData.toTrainer() : new Trainer(trainerType, variant); + const variant = doubleTrainer + ? TrainerVariant.DOUBLE + : Utils.randSeedInt(2) + ? TrainerVariant.FEMALE + : TrainerVariant.DEFAULT; + newTrainer = + trainerData !== undefined + ? trainerData.toTrainer() + : new Trainer(trainerType, variant); this.field.add(newTrainer); } // Check for mystery encounter // Can only occur in place of a standard (non-boss) wild battle, waves 10-180 - if (this.isWaveMysteryEncounter(newBattleType, newWaveIndex) || newBattleType === BattleType.MYSTERY_ENCOUNTER) { + if ( + this.isWaveMysteryEncounter(newBattleType, newWaveIndex) || + newBattleType === BattleType.MYSTERY_ENCOUNTER + ) { newBattleType = BattleType.MYSTERY_ENCOUNTER; // Reset to base spawn weight - this.mysteryEncounterSaveData.encounterSpawnChance = BASE_MYSTERY_ENCOUNTER_SPAWN_WEIGHT; + this.mysteryEncounterSaveData.encounterSpawnChance = + BASE_MYSTERY_ENCOUNTER_SPAWN_WEIGHT; } } if (double === undefined && newWaveIndex > 1) { - if (newBattleType === BattleType.WILD && !this.gameMode.isWaveFinal(newWaveIndex)) { - newDouble = !Utils.randSeedInt(this.getDoubleBattleChance(newWaveIndex, playerField)); + if ( + newBattleType === BattleType.WILD && + !this.gameMode.isWaveFinal(newWaveIndex) + ) { + newDouble = !Utils.randSeedInt( + this.getDoubleBattleChance(newWaveIndex, playerField), + ); } else if (newBattleType === BattleType.TRAINER) { newDouble = newTrainer?.variant === TrainerVariant.DOUBLE; } @@ -1300,10 +1653,10 @@ export default class BattleScene extends SceneBase { doubleOverrideForWave = "single"; break; case "even-doubles": - doubleOverrideForWave = (newWaveIndex % 2) ? "single" : "double"; + doubleOverrideForWave = newWaveIndex % 2 ? "single" : "double"; break; case "odd-doubles": - doubleOverrideForWave = (newWaveIndex % 2) ? "double" : "single"; + doubleOverrideForWave = newWaveIndex % 2 ? "double" : "single"; break; } @@ -1314,7 +1667,10 @@ export default class BattleScene extends SceneBase { * Override battles into single only if not fighting with trainers. * @see {@link https://github.com/pagefaultgames/pokerogue/issues/1948 | GitHub Issue #1948} */ - if (newBattleType !== BattleType.TRAINER && doubleOverrideForWave === "single") { + if ( + newBattleType !== BattleType.TRAINER && + doubleOverrideForWave === "single" + ) { newDouble = false; } } @@ -1332,13 +1688,25 @@ export default class BattleScene extends SceneBase { } if (lastBattle?.double && !newDouble) { - this.tryRemovePhase(p => p instanceof SwitchPhase); - this.getPlayerField().forEach(p => p.lapseTag(BattlerTagType.COMMANDED)); + this.tryRemovePhase((p) => p instanceof SwitchPhase); + this.getPlayerField().forEach((p) => + p.lapseTag(BattlerTagType.COMMANDED), + ); } - this.executeWithSeedOffset(() => { - this.currentBattle = new Battle(this.gameMode, newWaveIndex, newBattleType, newTrainer, newDouble); - }, newWaveIndex << 3, this.waveSeed); + this.executeWithSeedOffset( + () => { + this.currentBattle = new Battle( + this.gameMode, + newWaveIndex, + newBattleType, + newTrainer, + newDouble, + ); + }, + newWaveIndex << 3, + this.waveSeed, + ); this.currentBattle.incrementTurn(); if (newBattleType === BattleType.MYSTERY_ENCOUNTER) { @@ -1350,20 +1718,33 @@ export default class BattleScene extends SceneBase { if (!waveIndex && lastBattle) { const isWaveIndexMultipleOfTen = !(lastBattle.waveIndex % 10); - const isEndlessOrDaily = this.gameMode.hasShortBiomes || this.gameMode.isDaily; - const isEndlessFifthWave = this.gameMode.hasShortBiomes && (lastBattle.waveIndex % 5) === 0; - const isWaveIndexMultipleOfFiftyMinusOne = (lastBattle.waveIndex % 50) === 49; - const isNewBiome = isWaveIndexMultipleOfTen || isEndlessFifthWave || (isEndlessOrDaily && isWaveIndexMultipleOfFiftyMinusOne); - const resetArenaState = isNewBiome || [ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(this.currentBattle.battleType) || this.currentBattle.battleSpec === BattleSpec.FINAL_BOSS; - this.getEnemyParty().forEach(enemyPokemon => enemyPokemon.destroy()); + const isEndlessOrDaily = + this.gameMode.hasShortBiomes || this.gameMode.isDaily; + const isEndlessFifthWave = + this.gameMode.hasShortBiomes && lastBattle.waveIndex % 5 === 0; + const isWaveIndexMultipleOfFiftyMinusOne = + lastBattle.waveIndex % 50 === 49; + const isNewBiome = + isWaveIndexMultipleOfTen || + isEndlessFifthWave || + (isEndlessOrDaily && isWaveIndexMultipleOfFiftyMinusOne); + const resetArenaState = + isNewBiome || + [ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes( + this.currentBattle.battleType, + ) || + this.currentBattle.battleSpec === BattleSpec.FINAL_BOSS; + this.getEnemyParty().forEach((enemyPokemon) => enemyPokemon.destroy()); this.trySpreadPokerus(); - if (!isNewBiome && (newWaveIndex % 10) === 5) { + if (!isNewBiome && newWaveIndex % 10 === 5) { this.arena.updatePoolsForTimeOfDay(); } if (resetArenaState) { this.arena.resetArenaEffects(); - playerField.forEach((pokemon) => pokemon.lapseTag(BattlerTagType.COMMANDED)); + playerField.forEach((pokemon) => + pokemon.lapseTag(BattlerTagType.COMMANDED), + ); playerField.forEach((pokemon, p) => { if (pokemon.isOnField()) { @@ -1375,7 +1756,12 @@ export default class BattleScene extends SceneBase { pokemon.resetBattleData(); pokemon.resetTera(); applyPostBattleInitAbAttrs(PostBattleInitAbAttr, pokemon); - if (pokemon.hasSpecies(Species.TERAPAGOS) || (this.gameMode.isClassic && this.currentBattle.waveIndex > 180 && this.currentBattle.waveIndex <= 190)) { + if ( + pokemon.hasSpecies(Species.TERAPAGOS) || + (this.gameMode.isClassic && + this.currentBattle.waveIndex > 180 && + this.currentBattle.waveIndex <= 190) + ) { this.arena.playerTerasUsed = 0; } } @@ -1386,7 +1772,10 @@ export default class BattleScene extends SceneBase { } for (const pokemon of this.getPlayerParty()) { - this.triggerPokemonFormChange(pokemon, SpeciesFormChangeTimeOfDayTrigger); + this.triggerPokemonFormChange( + pokemon, + SpeciesFormChangeTimeOfDayTrigger, + ); } if (!this.gameMode.hasRandomBiomes && !isNewBiome) { @@ -1409,23 +1798,35 @@ export default class BattleScene extends SceneBase { this.arena = new Arena(biome, Biome[biome].toLowerCase(), playerFaints); this.eventTarget.dispatchEvent(new NewArenaEvent()); - this.arenaBg.pipelineData = { terrainColorRatio: this.arena.getBgTerrainColorRatioForBiome() }; + this.arenaBg.pipelineData = { + terrainColorRatio: this.arena.getBgTerrainColorRatioForBiome(), + }; return this.arena; } updateFieldScale(): Promise { - return new Promise(resolve => { - const fieldScale = Math.floor(Math.pow(1 / this.getField(true) - .map(p => p.getSpriteScale()) - .reduce((highestScale: number, scale: number) => highestScale = Math.max(scale, highestScale), 0), 0.7) * 40 - ) / 40; + return new Promise((resolve) => { + const fieldScale = + Math.floor( + Math.pow( + 1 / + this.getField(true) + .map((p) => p.getSpriteScale()) + .reduce( + (highestScale: number, scale: number) => + (highestScale = Math.max(scale, highestScale)), + 0, + ), + 0.7, + ) * 40, + ) / 40; this.setFieldScale(fieldScale).then(() => resolve()); }); } setFieldScale(scale: number, instant: boolean = false): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { scale *= 6; if (this.field.scale === scale) { return resolve(); @@ -1441,19 +1842,28 @@ export default class BattleScene extends SceneBase { scale: scale, x: (defaultWidth - scaledWidth) / 2, y: defaultHeight - scaledHeight, - duration: !instant ? Utils.fixedInt(Math.abs(this.field.scale - scale) * 200) : 0, + duration: !instant + ? Utils.fixedInt(Math.abs(this.field.scale - scale) * 200) + : 0, ease: "Sine.easeInOut", - onComplete: () => resolve() + onComplete: () => resolve(), }); }); } - getSpeciesFormIndex(species: PokemonSpecies, gender?: Gender, nature?: Nature, ignoreArena?: boolean): number { + getSpeciesFormIndex( + species: PokemonSpecies, + gender?: Gender, + nature?: Nature, + ignoreArena?: boolean, + ): number { if (!species.forms?.length) { return 0; } - const isEggPhase: boolean = [ "EggLapsePhase", "EggHatchPhase" ].includes(this.getCurrentPhase()?.constructor.name ?? ""); + const isEggPhase: boolean = [ "EggLapsePhase", "EggHatchPhase" ].includes( + this.getCurrentPhase()?.constructor.name ?? "", + ); switch (species.speciesId) { case Species.UNOWN: @@ -1481,12 +1891,19 @@ export default class BattleScene extends SceneBase { case Species.PALDEA_TAUROS: return Utils.randSeedInt(species.forms.length); case Species.PIKACHU: - if (this.currentBattle?.battleType === BattleType.TRAINER && this.currentBattle?.waveIndex < 30) { + if ( + this.currentBattle?.battleType === BattleType.TRAINER && + this.currentBattle?.waveIndex < 30 + ) { return 0; // Ban Cosplay and Partner Pika from Trainers before wave 30 } return Utils.randSeedInt(8); case Species.EEVEE: - if (this.currentBattle?.battleType === BattleType.TRAINER && this.currentBattle?.waveIndex < 30 && !isEggPhase) { + if ( + this.currentBattle?.battleType === BattleType.TRAINER && + this.currentBattle?.waveIndex < 30 && + !isEggPhase + ) { return 0; // No Partner Eevee for Wave 12 Preschoolers } return Utils.randSeedInt(2); @@ -1509,13 +1926,26 @@ export default class BattleScene extends SceneBase { case Species.OINKOLOGNE: return gender === Gender.FEMALE ? 1 : 0; case Species.TOXTRICITY: - const lowkeyNatures = [ Nature.LONELY, Nature.BOLD, Nature.RELAXED, Nature.TIMID, Nature.SERIOUS, Nature.MODEST, Nature.MILD, Nature.QUIET, Nature.BASHFUL, Nature.CALM, Nature.GENTLE, Nature.CAREFUL ]; + const lowkeyNatures = [ + Nature.LONELY, + Nature.BOLD, + Nature.RELAXED, + Nature.TIMID, + Nature.SERIOUS, + Nature.MODEST, + Nature.MILD, + Nature.QUIET, + Nature.BASHFUL, + Nature.CALM, + Nature.GENTLE, + Nature.CAREFUL, + ]; if (nature !== undefined && lowkeyNatures.indexOf(nature) > -1) { return 1; } return 0; case Species.GIMMIGHOUL: - // Chest form can only be found in Mysterious Chest Encounter, if this is a game mode with MEs + // Chest form can only be found in Mysterious Chest Encounter, if this is a game mode with MEs if (this.gameMode.hasMysteryEncounters && !isEggPhase) { return 1; // Wandering form } else { @@ -1539,21 +1969,34 @@ export default class BattleScene extends SceneBase { private getGeneratedOffsetGym(): boolean { let ret = false; - this.executeWithSeedOffset(() => { - ret = !Utils.randSeedInt(2); - }, 0, this.seed.toString()); + this.executeWithSeedOffset( + () => { + ret = !Utils.randSeedInt(2); + }, + 0, + this.seed.toString(), + ); return ret; } private getGeneratedWaveCycleOffset(): number { let ret = 0; - this.executeWithSeedOffset(() => { - ret = Utils.randSeedInt(8) * 5; - }, 0, this.seed.toString()); + this.executeWithSeedOffset( + () => { + ret = Utils.randSeedInt(8) * 5; + }, + 0, + this.seed.toString(), + ); return ret; } - getEncounterBossSegments(waveIndex: number, level: number, species?: PokemonSpecies, forceBoss: boolean = false): number { + getEncounterBossSegments( + waveIndex: number, + level: number, + species?: PokemonSpecies, + forceBoss: boolean = false, + ): number { if (Overrides.OPP_HEALTH_SEGMENTS_OVERRIDE > 1) { return Overrides.OPP_HEALTH_SEGMENTS_OVERRIDE; } else if (Overrides.OPP_HEALTH_SEGMENTS_OVERRIDE === 1) { @@ -1566,11 +2009,19 @@ export default class BattleScene extends SceneBase { } let isBoss: boolean | undefined; - if (forceBoss || (species && (species.subLegendary || species.legendary || species.mythical))) { + if ( + forceBoss || + (species && + (species.subLegendary || species.legendary || species.mythical)) + ) { isBoss = true; } else { this.executeWithSeedOffset(() => { - isBoss = waveIndex % 10 === 0 || (this.gameMode.hasRandomBosses && Utils.randSeedInt(100) < Math.min(Math.max(Math.ceil((waveIndex - 250) / 50), 0) * 2, 30)); + isBoss = + waveIndex % 10 === 0 || + (this.gameMode.hasRandomBosses && + Utils.randSeedInt(100) < + Math.min(Math.max(Math.ceil((waveIndex - 250) / 50), 0) * 2, 30)); }, waveIndex << 2); } if (!isBoss) { @@ -1607,14 +2058,17 @@ export default class BattleScene extends SceneBase { return; } - this.executeWithSeedOffset(() => { - if (p) { - spread(p, -1); - } - if (p < party.length - 1) { - spread(p, 1); - } - }, this.currentBattle.waveIndex + (p << 8)); + this.executeWithSeedOffset( + () => { + if (p) { + spread(p, -1); + } + if (p < party.length - 1) { + spread(p, 1); + } + }, + this.currentBattle.waveIndex + (p << 8), + ); }); } @@ -1626,7 +2080,11 @@ export default class BattleScene extends SceneBase { this.rngCounter = 0; } - executeWithSeedOffset(func: Function, offset: number, seedOverride?: string): void { + executeWithSeedOffset( + func: Function, + offset: number, + seedOverride?: string, + ): void { if (!func) { return; } @@ -1634,7 +2092,9 @@ export default class BattleScene extends SceneBase { const tempRngOffset = this.rngOffset; const tempRngSeedOverride = this.rngSeedOverride; const state = Phaser.Math.RND.state(); - Phaser.Math.RND.sow([ Utils.shiftCharCodes(seedOverride || this.seed, offset) ]); + Phaser.Math.RND.sow([ + Utils.shiftCharCodes(seedOverride || this.seed, offset), + ]); this.rngCounter = 0; this.rngOffset = offset; this.rngSeedOverride = seedOverride || ""; @@ -1645,7 +2105,13 @@ export default class BattleScene extends SceneBase { this.rngSeedOverride = tempRngSeedOverride; } - addFieldSprite(x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number, terrainColorRatio: number = 0): Phaser.GameObjects.Sprite { + addFieldSprite( + x: number, + y: number, + texture: string | Phaser.Textures.Texture, + frame?: string | number, + terrainColorRatio: number = 0, + ): Phaser.GameObjects.Sprite { const ret = this.add.sprite(x, y, texture, frame); ret.setPipeline(this.fieldSpritePipeline); if (terrainColorRatio) { @@ -1655,14 +2121,33 @@ export default class BattleScene extends SceneBase { return ret; } - addPokemonSprite(pokemon: Pokemon, x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number, hasShadow: boolean = false, ignoreOverride: boolean = false): Phaser.GameObjects.Sprite { + addPokemonSprite( + pokemon: Pokemon, + x: number, + y: number, + texture: string | Phaser.Textures.Texture, + frame?: string | number, + hasShadow: boolean = false, + ignoreOverride: boolean = false, + ): Phaser.GameObjects.Sprite { const ret = this.addFieldSprite(x, y, texture, frame); this.initPokemonSprite(ret, pokemon, hasShadow, ignoreOverride); return ret; } - initPokemonSprite(sprite: Phaser.GameObjects.Sprite, pokemon?: Pokemon, hasShadow: boolean = false, ignoreOverride: boolean = false): Phaser.GameObjects.Sprite { - sprite.setPipeline(this.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: hasShadow, ignoreOverride: ignoreOverride, teraColor: pokemon ? getTypeRgb(pokemon.getTeraType()) : undefined, isTerastallized: pokemon ? pokemon.isTerastallized : false }); + initPokemonSprite( + sprite: Phaser.GameObjects.Sprite, + pokemon?: Pokemon, + hasShadow: boolean = false, + ignoreOverride: boolean = false, + ): Phaser.GameObjects.Sprite { + sprite.setPipeline(this.spritePipeline, { + tone: [ 0.0, 0.0, 0.0, 0.0 ], + hasShadow: hasShadow, + ignoreOverride: ignoreOverride, + teraColor: pokemon ? getTypeRgb(pokemon.getTeraType()) : undefined, + isTerastallized: pokemon ? pokemon.isTerastallized : false, + }); this.spriteSparkleHandler.add(sprite); return sprite; } @@ -1675,25 +2160,25 @@ export default class BattleScene extends SceneBase { } showFieldOverlay(duration: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { this.tweens.add({ targets: this.fieldOverlay, alpha: 0.5, ease: "Sine.easeOut", duration: duration, - onComplete: () => resolve() + onComplete: () => resolve(), }); }); } hideFieldOverlay(duration: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { this.tweens.add({ targets: this.fieldOverlay, alpha: 0, duration: duration, ease: "Cubic.easeIn", - onComplete: () => resolve() + onComplete: () => resolve(), }); }); } @@ -1708,26 +2193,26 @@ export default class BattleScene extends SceneBase { showShopOverlay(duration: number): Promise { this.shopOverlayShown = true; - return new Promise(resolve => { + return new Promise((resolve) => { this.tweens.add({ targets: this.shopOverlay, alpha: this.shopOverlayOpacity, ease: "Sine.easeOut", duration, - onComplete: () => resolve() + onComplete: () => resolve(), }); }); } hideShopOverlay(duration: number): Promise { this.shopOverlayShown = false; - return new Promise(resolve => { + return new Promise((resolve) => { this.tweens.add({ targets: this.shopOverlay, alpha: 0, duration: duration, ease: "Cubic.easeIn", - onComplete: () => resolve() + onComplete: () => resolve(), }); }); } @@ -1744,7 +2229,9 @@ export default class BattleScene extends SceneBase { const isBoss = !(this.currentBattle.waveIndex % 10); const biomeString: string = getBiomeName(this.arena.biomeType); this.fieldUI.moveAbove(this.biomeWaveText, this.luckText); - this.biomeWaveText.setText( biomeString + " - " + this.currentBattle.waveIndex.toString()); + this.biomeWaveText.setText( + biomeString + " - " + this.currentBattle.waveIndex.toString(), + ); this.biomeWaveText.setColor(!isBoss ? "#ffffff" : "#f89890"); this.biomeWaveText.setShadowColor(!isBoss ? "#636363" : "#984038"); this.biomeWaveText.setVisible(true); @@ -1755,7 +2242,9 @@ export default class BattleScene extends SceneBase { return; } const formattedMoney = Utils.formatMoney(this.moneyFormat, this.money); - this.moneyText.setText(i18next.t("battleScene:moneyOwned", { formattedMoney })); + this.moneyText.setText( + i18next.t("battleScene:moneyOwned", { formattedMoney }), + ); this.fieldUI.moveAbove(this.moneyText, this.luckText); if (forceVisible) { this.moneyText.setVisible(true); @@ -1774,7 +2263,8 @@ export default class BattleScene extends SceneBase { scale: this.moneyText.scale + deltaScale, loop: 0, yoyo: true, - onComplete: (_) => this.moneyText.setShadowColor(getTextColor(TextStyle.MONEY, true)), + onComplete: (_) => + this.moneyText.setShadowColor(getTextColor(TextStyle.MONEY, true)), }); } @@ -1789,7 +2279,7 @@ export default class BattleScene extends SceneBase { */ updateAndShowText(duration: number): void { const labels = [ this.luckLabelText, this.luckText ]; - labels.forEach(t => t.setAlpha(0)); + labels.forEach((t) => t.setAlpha(0)); const luckValue = getPartyLuckValue(this.getPlayerParty()); this.luckText.setText(getLuckString(luckValue)); if (luckValue < 14) { @@ -1797,14 +2287,16 @@ export default class BattleScene extends SceneBase { } else { this.luckText.setTint(0xffef5c, 0x47ff69, 0x6b6bff, 0xff6969); } - this.luckLabelText.setX((this.game.canvas.width / 6) - 2 - (this.luckText.displayWidth + 2)); + this.luckLabelText.setX( + this.game.canvas.width / 6 - 2 - (this.luckText.displayWidth + 2), + ); this.tweens.add({ targets: labels, duration: duration, alpha: 1, onComplete: () => { - labels.forEach(t => t.setVisible(true)); - } + labels.forEach((t) => t.setVisible(true)); + }, }); } @@ -1818,21 +2310,29 @@ export default class BattleScene extends SceneBase { duration: duration, alpha: 0, onComplete: () => { - labels.forEach(l => l.setVisible(false)); - } + labels.forEach((l) => l.setVisible(false)); + }, }); } updateUIPositions(): void { - const enemyModifierCount = this.enemyModifiers.filter(m => m.isIconVisible()).length; - const biomeWaveTextHeight = this.biomeWaveText.getBottomLeft().y - this.biomeWaveText.getTopLeft().y; + const enemyModifierCount = this.enemyModifiers.filter((m) => + m.isIconVisible(), + ).length; + const biomeWaveTextHeight = + this.biomeWaveText.getBottomLeft().y - this.biomeWaveText.getTopLeft().y; this.biomeWaveText.setY( - -(this.game.canvas.height / 6) + (enemyModifierCount ? enemyModifierCount <= 12 ? 15 : 24 : 0) + (biomeWaveTextHeight / 2) + -(this.game.canvas.height / 6) + + (enemyModifierCount ? (enemyModifierCount <= 12 ? 15 : 24) : 0) + + biomeWaveTextHeight / 2, ); this.moneyText.setY(this.biomeWaveText.y + 10); this.scoreText.setY(this.moneyText.y + 10); - [ this.luckLabelText, this.luckText ].map(l => l.setY((this.scoreText.visible ? this.scoreText : this.moneyText).y + 10)); - const offsetY = (this.scoreText.visible ? this.scoreText : this.moneyText).y + 15; + [ this.luckLabelText, this.luckText ].map((l) => + l.setY((this.scoreText.visible ? this.scoreText : this.moneyText).y + 10), + ); + const offsetY = + (this.scoreText.visible ? this.scoreText : this.moneyText).y + 15; this.partyExpBar.setY(offsetY); this.candyBar.setY(offsetY + 15); this.ui?.achvBar.setY(this.game.canvas.height / 6 + offsetY); @@ -1848,8 +2348,20 @@ export default class BattleScene extends SceneBase { } addFaintedEnemyScore(enemy: EnemyPokemon): void { - let scoreIncrease = enemy.getSpeciesForm().getBaseExp() * (enemy.level / this.getMaxExpLevel()) * ((enemy.ivs.reduce((iv: number, total: number) => total += iv, 0) / 93) * 0.2 + 0.8); - this.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === enemy.id, false).map(m => scoreIncrease *= (m as PokemonHeldItemModifier).getScoreMultiplier()); + let scoreIncrease = + enemy.getSpeciesForm().getBaseExp() * + (enemy.level / this.getMaxExpLevel()) * + ((enemy.ivs.reduce((iv: number, total: number) => (total += iv), 0) / + 93) * + 0.2 + + 0.8); + this.findModifiers( + (m) => m instanceof PokemonHeldItemModifier && m.pokemonId === enemy.id, + false, + ).map( + (m) => + (scoreIncrease *= (m as PokemonHeldItemModifier).getScoreMultiplier()), + ); if (enemy.isBoss()) { scoreIncrease *= Math.sqrt(enemy.bossSegments); } @@ -1864,35 +2376,68 @@ export default class BattleScene extends SceneBase { } const waveIndex = Math.ceil((this.currentBattle?.waveIndex || 1) / 10) * 10; const difficultyWaveIndex = this.gameMode.getWaveForDifficulty(waveIndex); - const baseLevel = (1 + difficultyWaveIndex / 2 + Math.pow(difficultyWaveIndex / 25, 2)) * 1.2; + const baseLevel = + (1 + difficultyWaveIndex / 2 + Math.pow(difficultyWaveIndex / 25, 2)) * + 1.2; return Math.ceil(baseLevel / 2) * 2 + 2; } - randomSpecies(waveIndex: number, level: number, fromArenaPool?: boolean, speciesFilter?: PokemonSpeciesFilter, filterAllEvolutions?: boolean): PokemonSpecies { + randomSpecies( + waveIndex: number, + level: number, + fromArenaPool?: boolean, + speciesFilter?: PokemonSpeciesFilter, + filterAllEvolutions?: boolean, + ): PokemonSpecies { if (fromArenaPool) { - return this.arena.randomSpecies(waveIndex, level, undefined, getPartyLuckValue(this.party)); + return this.arena.randomSpecies( + waveIndex, + level, + undefined, + getPartyLuckValue(this.party), + ); } - const filteredSpecies = speciesFilter ? [ ...new Set(allSpecies.filter(s => s.isCatchable()).filter(speciesFilter).map(s => { - if (!filterAllEvolutions) { - while (pokemonPrevolutions.hasOwnProperty(s.speciesId)) { - s = getPokemonSpecies(pokemonPrevolutions[s.speciesId]); - } - } - return s; - })) ] : allSpecies.filter(s => s.isCatchable()); + const filteredSpecies = speciesFilter + ? [ + ...new Set( + allSpecies + .filter((s) => s.isCatchable()) + .filter(speciesFilter) + .map((s) => { + if (!filterAllEvolutions) { + while (pokemonPrevolutions.hasOwnProperty(s.speciesId)) { + s = getPokemonSpecies(pokemonPrevolutions[s.speciesId]); + } + } + return s; + }), + ), + ] + : allSpecies.filter((s) => s.isCatchable()); return filteredSpecies[Utils.randSeedInt(filteredSpecies.length)]; } generateRandomBiome(waveIndex: number): Biome { const relWave = waveIndex % 250; - const biomes = Utils.getEnumValues(Biome).filter(b => b !== Biome.TOWN && b !== Biome.END); + const biomes = Utils.getEnumValues(Biome).filter( + (b) => b !== Biome.TOWN && b !== Biome.END, + ); const maxDepth = biomeDepths[Biome.END][0] - 2; - const depthWeights = new Array(maxDepth + 1).fill(null) - .map((_, i: number) => ((1 - Math.min(Math.abs((i / (maxDepth - 1)) - (relWave / 250)) + 0.25, 1)) / 0.75) * 250); + const depthWeights = new Array(maxDepth + 1) + .fill(null) + .map( + (_, i: number) => + ((1 - + Math.min(Math.abs(i / (maxDepth - 1) - relWave / 250) + 0.25, 1)) / + 0.75) * + 250, + ); const biomeThresholds: number[] = []; let totalWeight = 0; for (const biome of biomes) { - totalWeight += Math.ceil(depthWeights[biomeDepths[biome][0] - 1] / biomeDepths[biome][1]); + totalWeight += Math.ceil( + depthWeights[biomeDepths[biome][0] - 1] / biomeDepths[biome][1], + ); biomeThresholds.push(totalWeight); } @@ -1918,7 +2463,7 @@ export default class BattleScene extends SceneBase { if (this.bgm && bgmName === this.bgm.key) { if (!this.bgm.isPlaying) { this.bgm.play({ - volume: this.masterVolume * this.bgmVolume + volume: this.masterVolume * this.bgmVolume, }); } return; @@ -1929,15 +2474,16 @@ export default class BattleScene extends SceneBase { this.bgmCache.add(bgmName); this.loadBgm(bgmName); let loopPoint = 0; - loopPoint = bgmName === this.arena.bgm - ? this.arena.getBgmLoopPoint() - : this.getBgmLoopPoint(bgmName); + loopPoint = + bgmName === this.arena.bgm + ? this.arena.getBgmLoopPoint() + : this.getBgmLoopPoint(bgmName); let loaded = false; const playNewBgm = () => { this.ui.bgmBar.setBgmToBgmBar(bgmName); if (bgmName === null && this.bgm && !this.bgm.pendingRemove) { this.bgm.play({ - volume: this.masterVolume * this.bgmVolume + volume: this.masterVolume * this.bgmVolume, }); return; } @@ -1946,7 +2492,7 @@ export default class BattleScene extends SceneBase { } this.bgm = this.sound.add(bgmName, { loop: true }); this.bgm.play({ - volume: this.masterVolume * this.bgmVolume + volume: this.masterVolume * this.bgmVolume, }); if (loopPoint) { this.bgm.on("looped", () => this.bgm.play({ seek: loopPoint })); @@ -1995,7 +2541,6 @@ export default class BattleScene extends SceneBase { } else { const soundDetails = sound.key.split("/"); switch (soundDetails[0]) { - case "battle_anims": case "cry": if (soundDetails[1].startsWith("PRSFX- ")) { @@ -2017,7 +2562,9 @@ export default class BattleScene extends SceneBase { if (!this.bgm) { return false; } - const bgm = this.sound.getAllPlaying().find(bgm => bgm.key === this.bgm.key); + const bgm = this.sound + .getAllPlaying() + .find((bgm) => bgm.key === this.bgm.key); if (bgm) { SoundFade.fadeOut(this, this.bgm, duration, destroy); return true; @@ -2032,7 +2579,11 @@ export default class BattleScene extends SceneBase { * @param destroy * @param delay */ - fadeAndSwitchBgm(newBgmKey: string, destroy: boolean = false, delay: number = 2000) { + fadeAndSwitchBgm( + newBgmKey: string, + destroy: boolean = false, + delay: number = 2000, + ) { this.fadeOutBgm(delay, destroy); this.time.delayedCall(delay, () => { this.playBgm(newBgmKey); @@ -2052,24 +2603,24 @@ export default class BattleScene extends SceneBase { case "heal": case "evolution": case "evolution_fanfare": - // These sounds are loaded in as BGM, but played as sound effects - // When these sounds are updated in updateVolume(), they are treated as BGM however because they are placed in the BGM Cache through being called by playSoundWithoutBGM() - config["volume"] *= (this.masterVolume * this.bgmVolume); + // These sounds are loaded in as BGM, but played as sound effects + // When these sounds are updated in updateVolume(), they are treated as BGM however because they are placed in the BGM Cache through being called by playSoundWithoutBGM() + config["volume"] *= this.masterVolume * this.bgmVolume; break; case "battle_anims": case "cry": - config["volume"] *= (this.masterVolume * this.fieldVolume); + config["volume"] *= this.masterVolume * this.fieldVolume; //PRSFX sound files are unusually loud if (keyDetails[1].startsWith("PRSFX- ")) { config["volume"] *= 0.5; } break; case "ui": - //As of, right now this applies to the "select", "menu_open", "error" sound effects - config["volume"] *= (this.masterVolume * this.uiVolume); + //As of, right now this applies to the "select", "menu_open", "error" sound effects + config["volume"] *= this.masterVolume * this.uiVolume; break; case "se": - config["volume"] *= (this.masterVolume * this.seVolume); + config["volume"] *= this.masterVolume * this.seVolume; break; } this.sound.play(key, config); @@ -2089,10 +2640,13 @@ export default class BattleScene extends SceneBase { this.bgmResumeTimer.destroy(); } if (resumeBgm) { - this.bgmResumeTimer = this.time.delayedCall((pauseDuration || Utils.fixedInt(sound.totalDuration * 1000)), () => { - this.resumeBgm(); - this.bgmResumeTimer = null; - }); + this.bgmResumeTimer = this.time.delayedCall( + pauseDuration || Utils.fixedInt(sound.totalDuration * 1000), + () => { + this.resumeBgm(); + this.bgmResumeTimer = null; + }, + ); } return sound; } @@ -2101,9 +2655,9 @@ export default class BattleScene extends SceneBase { getBgmLoopPoint(bgmName: string): number { switch (bgmName) { case "title": //Firel PokéRogue Title - return 46.500; + return 46.5; case "battle_kanto_champion": //B2W2 Kanto Champion Battle - return 13.950; + return 13.95; case "battle_johto_champion": //B2W2 Johto Champion Battle return 23.498; case "battle_hoenn_champion_g5": //B2W2 Hoenn Champion Battle @@ -2117,7 +2671,7 @@ export default class BattleScene extends SceneBase { case "battle_champion_iris": //B2W2 Unova Champion Battle return 10.145; case "battle_kalos_champion": //XY Kalos Champion Battle - return 10.380; + return 10.38; case "battle_champion_kukui": //SM Kukui Battle return 15.784; case "battle_alola_champion": //USUM Alola Champion Battle @@ -2133,17 +2687,17 @@ export default class BattleScene extends SceneBase { case "battle_champion_kieran": //SV Champion Kieran Battle return 7.206; case "battle_hoenn_elite": //ORAS Elite Four Battle - return 11.350; + return 11.35; case "battle_unova_elite": //BW Elite Four Battle - return 17.730; + return 17.73; case "battle_kalos_elite": //XY Elite Four Battle - return 12.340; + return 12.34; case "battle_alola_elite": //SM Elite Four Battle return 19.212; case "battle_galar_elite": //SWSH League Tournament Battle return 164.069; case "battle_paldea_elite": //SV Elite Four Battle - return 12.770; + return 12.77; case "battle_bb_elite": //SV BB League Elite Four Battle return 19.434; case "battle_final_encounter": //PMD RTDX Rayquaza's Domain @@ -2161,7 +2715,7 @@ export default class BattleScene extends SceneBase { case "battle_unova_gym": //BW Unova Gym Battle return 19.145; case "battle_kalos_gym": //XY Kalos Gym Battle - return 44.810; + return 44.81; case "battle_galar_gym": //SWSH Galar Gym Battle return 171.262; case "battle_paldea_gym": //SV Paldea Gym Battle @@ -2175,13 +2729,13 @@ export default class BattleScene extends SceneBase { case "battle_legendary_suicune": //HGSS Suicune Battle return 12.636; case "battle_legendary_lugia": //HGSS Lugia Battle - return 19.770; + return 19.77; case "battle_legendary_ho_oh": //HGSS Ho-oh Battle return 17.668; case "battle_legendary_regis_g5": //B2W2 Legendary Titan Battle - return 49.500; + return 49.5; case "battle_legendary_regis_g6": //ORAS Legendary Titan Battle - return 21.130; + return 21.13; case "battle_legendary_gro_kyo": //ORAS Groudon & Kyogre Battle return 10.547; case "battle_legendary_rayquaza": //ORAS Rayquaza Battle @@ -2191,7 +2745,7 @@ export default class BattleScene extends SceneBase { case "battle_legendary_lake_trio": //ORAS Lake Guardians Battle return 16.887; case "battle_legendary_sinnoh": //ORAS Sinnoh Legendary Battle - return 22.770; + return 22.77; case "battle_legendary_dia_pal": //ORAS Dialga & Palkia Battle return 16.009; case "battle_legendary_origin_forme": //LA Origin Dialga & Palkia Battle @@ -2209,7 +2763,7 @@ export default class BattleScene extends SceneBase { case "battle_legendary_xern_yvel": //XY Xerneas & Yveltal Battle return 26.468; case "battle_legendary_tapu": //SM Tapu Battle - return 0.000; + return 0.0; case "battle_legendary_sol_lun": //SM Solgaleo & Lunala Battle return 6.525; case "battle_legendary_ub": //SM Ultra Beast Battle @@ -2233,7 +2787,7 @@ export default class BattleScene extends SceneBase { case "battle_legendary_kor_mir": //SV Depths of Area Zero Battle return 6.442; case "battle_legendary_loyal_three": //SV Loyal Three Battle - return 6.500; + return 6.5; case "battle_legendary_ogerpon": //SV Ogerpon Battle return 14.335; case "battle_legendary_terapagos": //SV Terapagos Battle @@ -2241,7 +2795,7 @@ export default class BattleScene extends SceneBase { case "battle_legendary_pecharunt": //SV Pecharunt Battle return 6.508; case "battle_rival": //BW Rival Battle - return 14.110; + return 14.11; case "battle_rival_2": //BW N Battle return 17.714; case "battle_rival_3": //BW Final N Battle @@ -2251,7 +2805,7 @@ export default class BattleScene extends SceneBase { case "battle_wild": //BW Wild Battle return 12.703; case "battle_wild_strong": //BW Strong Wild Battle - return 13.940; + return 13.94; case "end_summit": //PMD RTDX Sky Tower Summit return 30.025; case "battle_rocket_grunt": //HGSS Team Rocket Battle @@ -2265,7 +2819,7 @@ export default class BattleScene extends SceneBase { case "battle_flare_grunt": //XY Team Flare Battle return 4.228; case "battle_aether_grunt": // SM Aether Foundation Battle - return 16.00; + return 16.0; case "battle_skull_grunt": // SM Team Skull Battle return 20.87; case "battle_macro_grunt": // SWSH Trainer Battle @@ -2279,7 +2833,7 @@ export default class BattleScene extends SceneBase { case "battle_skull_admin": //SM Team Skull Admin Battle return 15.463; case "battle_oleana": //SWSH Oleana Battle - return 14.110; + return 14.11; case "battle_star_admin": //SV Team Star Boss Battle return 9.493; case "battle_rocket_boss": //USUM Giovanni Battle @@ -2332,7 +2886,6 @@ export default class BattleScene extends SceneBase { return this.standbyPhase; } - /** * Adds a phase to the conditional queue and ensures it is executed only when the specified condition is met. * @@ -2364,7 +2917,11 @@ export default class BattleScene extends SceneBase { if (this.phaseQueuePrependSpliceIndex === -1) { this.phaseQueuePrepend.push(...phases); } else { - this.phaseQueuePrepend.splice(this.phaseQueuePrependSpliceIndex, 0, ...phases); + this.phaseQueuePrepend.splice( + this.phaseQueuePrependSpliceIndex, + 0, + ...phases, + ); } } @@ -2437,7 +2994,10 @@ export default class BattleScene extends SceneBase { } if (this.currentPhase) { - console.log(`%cStart Phase ${this.currentPhase.constructor.name}`, "color:green;"); + console.log( + `%cStart Phase ${this.currentPhase.constructor.name}`, + "color:green;", + ); this.currentPhase.start(); } } @@ -2461,11 +3021,16 @@ export default class BattleScene extends SceneBase { * @param phaseFilter filter function to use to find the wanted phase * @returns the found phase or undefined if none found */ - findPhase

(phaseFilter: (phase: P) => boolean): P | undefined { + findPhase

( + phaseFilter: (phase: P) => boolean, + ): P | undefined { return this.phaseQueue.find(phaseFilter) as P; } - tryReplacePhase(phaseFilter: (phase: Phase) => boolean, phase: Phase): boolean { + tryReplacePhase( + phaseFilter: (phase: Phase) => boolean, + phase: Phase, + ): boolean { const phaseIndex = this.phaseQueue.findIndex(phaseFilter); if (phaseIndex > -1) { this.phaseQueue[phaseIndex] = phase; @@ -2502,11 +3067,16 @@ export default class BattleScene extends SceneBase { * @param targetPhase {@linkcode Phase} the type of phase to search for in phaseQueue * @returns boolean if a targetPhase was found and added */ - prependToPhase(phase: Phase | Phase [], targetPhase: Constructor): boolean { + prependToPhase( + phase: Phase | Phase[], + targetPhase: Constructor, + ): boolean { if (!Array.isArray(phase)) { phase = [ phase ]; } - const targetIndex = this.phaseQueue.findIndex(ph => ph instanceof targetPhase); + const targetIndex = this.phaseQueue.findIndex( + (ph) => ph instanceof targetPhase, + ); if (targetIndex !== -1) { this.phaseQueue.splice(targetIndex, 0, ...phase); @@ -2523,11 +3093,16 @@ export default class BattleScene extends SceneBase { * @param targetPhase {@linkcode Phase} the type of phase to search for in {@linkcode phaseQueue} * @returns `true` if a `targetPhase` was found to append to */ - appendToPhase(phase: Phase | Phase[], targetPhase: Constructor): boolean { + appendToPhase( + phase: Phase | Phase[], + targetPhase: Constructor, + ): boolean { if (!Array.isArray(phase)) { phase = [ phase ]; } - const targetIndex = this.phaseQueue.findIndex(ph => ph instanceof targetPhase); + const targetIndex = this.phaseQueue.findIndex( + (ph) => ph instanceof targetPhase, + ); if (targetIndex !== -1 && this.phaseQueue.length > targetIndex) { this.phaseQueue.splice(targetIndex + 1, 0, ...phase); @@ -2546,7 +3121,13 @@ export default class BattleScene extends SceneBase { * @param promptDelay optional param for MessagePhase constructor * @param defer boolean for which queue to add it to, false -> add to PhaseQueuePrepend, true -> nextCommandPhaseQueue */ - queueMessage(message: string, callbackDelay?: number | null, prompt?: boolean | null, promptDelay?: number | null, defer?: boolean | null) { + queueMessage( + message: string, + callbackDelay?: number | null, + prompt?: boolean | null, + promptDelay?: number | null, + defer?: boolean | null, + ) { const phase = new MessagePhase(message, callbackDelay, prompt, promptDelay); if (!defer) { // adds to the end of PhaseQueuePrepend @@ -2578,98 +3159,126 @@ export default class BattleScene extends SceneBase { getWaveMoneyAmount(moneyMultiplier: number): number { const waveIndex = this.currentBattle.waveIndex; const waveSetIndex = Math.ceil(waveIndex / 10) - 1; - const moneyValue = Math.pow((waveSetIndex + 1 + (0.75 + (((waveIndex - 1) % 10) + 1) / 10)) * 100, 1 + 0.005 * waveSetIndex) * moneyMultiplier; + const moneyValue = + Math.pow( + (waveSetIndex + 1 + (0.75 + (((waveIndex - 1) % 10) + 1) / 10)) * 100, + 1 + 0.005 * waveSetIndex, + ) * moneyMultiplier; return Math.floor(moneyValue / 10) * 10; } - addModifier(modifier: Modifier | null, ignoreUpdate?: boolean, playSound?: boolean, virtual?: boolean, instant?: boolean, cost?: number): Promise { + addModifier( + modifier: Modifier | null, + ignoreUpdate?: boolean, + playSound?: boolean, + virtual?: boolean, + instant?: boolean, + cost?: number, + ): boolean { if (!modifier) { - return Promise.resolve(false); + return false; } - return new Promise(resolve => { - let success = false; - const soundName = modifier.type.soundName; - this.validateAchvs(ModifierAchv, modifier); - const modifiersToRemove: PersistentModifier[] = []; - const modifierPromises: Promise[] = []; - if (modifier instanceof PersistentModifier) { - if ((modifier as PersistentModifier).add(this.modifiers, !!virtual)) { - if (modifier instanceof PokemonFormChangeItemModifier) { - const pokemon = this.getPokemonById(modifier.pokemonId); - if (pokemon) { - success = modifier.apply(pokemon, true); - } + let success = false; + const soundName = modifier.type.soundName; + this.validateAchvs(ModifierAchv, modifier); + const modifiersToRemove: PersistentModifier[] = []; + if (modifier instanceof PersistentModifier) { + if ((modifier as PersistentModifier).add(this.modifiers, !!virtual)) { + if (modifier instanceof PokemonFormChangeItemModifier) { + const pokemon = this.getPokemonById(modifier.pokemonId); + if (pokemon) { + success = modifier.apply(pokemon, true); } - if (playSound && !this.sound.get(soundName)) { - this.playSound(soundName); - } - } else if (!virtual) { - const defaultModifierType = getDefaultModifierTypeForTier(modifier.type.tier); - this.queueMessage(i18next.t("battle:itemStackFull", { fullItemName: modifier.type.name, itemName: defaultModifierType.name }), undefined, false, 3000); - return this.addModifier(defaultModifierType.newModifier(), ignoreUpdate, playSound, false, instant).then(success => resolve(success)); } - - for (const rm of modifiersToRemove) { - this.removeModifier(rm); - } - - if (!ignoreUpdate && !virtual) { - return this.updateModifiers(true, instant).then(() => resolve(success)); - } - } else if (modifier instanceof ConsumableModifier) { if (playSound && !this.sound.get(soundName)) { this.playSound(soundName); } - - if (modifier instanceof ConsumablePokemonModifier) { - for (const p in this.party) { - const pokemon = this.party[p]; - - const args: unknown[] = []; - if (modifier instanceof PokemonHpRestoreModifier) { - if (!(modifier as PokemonHpRestoreModifier).fainted) { - const hpRestoreMultiplier = new Utils.NumberHolder(1); - this.applyModifiers(HealingBoosterModifier, true, hpRestoreMultiplier); - args.push(hpRestoreMultiplier.value); - } else { - args.push(1); - } - } else if (modifier instanceof FusePokemonModifier) { - args.push(this.getPokemonById(modifier.fusePokemonId) as PlayerPokemon); - } else if (modifier instanceof RememberMoveModifier && !Utils.isNullOrUndefined(cost)) { - args.push(cost); - } - - if (modifier.shouldApply(pokemon, ...args)) { - const result = modifier.apply(pokemon, ...args); - if (result instanceof Promise) { - modifierPromises.push(result.then(s => success ||= s)); - } else { - success ||= result; - } - } - } - - return Promise.allSettled([ this.party.map(p => p.updateInfo(instant)), ...modifierPromises ]).then(() => resolve(success)); - } else { - const args = [ this ]; - if (modifier.shouldApply(...args)) { - const result = modifier.apply(...args); - if (result instanceof Promise) { - return result.then(success => resolve(success)); - } else { - success ||= result; - } - } - } + } else if (!virtual) { + const defaultModifierType = getDefaultModifierTypeForTier( + modifier.type.tier, + ); + this.queueMessage( + i18next.t("battle:itemStackFull", { + fullItemName: modifier.type.name, + itemName: defaultModifierType.name, + }), + undefined, + false, + 3000, + ); + return this.addModifier( + defaultModifierType.newModifier(), + ignoreUpdate, + playSound, + false, + instant, + ); } - resolve(success); - }); + for (const rm of modifiersToRemove) { + this.removeModifier(rm); + } + + if (!ignoreUpdate && !virtual) { + this.updateModifiers(true, instant); + } + } else if (modifier instanceof ConsumableModifier) { + if (playSound && !this.sound.get(soundName)) { + this.playSound(soundName); + } + + if (modifier instanceof ConsumablePokemonModifier) { + for (const p in this.party) { + const pokemon = this.party[p]; + + const args: unknown[] = []; + if (modifier instanceof PokemonHpRestoreModifier) { + if (!(modifier as PokemonHpRestoreModifier).fainted) { + const hpRestoreMultiplier = new Utils.NumberHolder(1); + this.applyModifiers( + HealingBoosterModifier, + true, + hpRestoreMultiplier, + ); + args.push(hpRestoreMultiplier.value); + } else { + args.push(1); + } + } else if (modifier instanceof FusePokemonModifier) { + args.push( + this.getPokemonById(modifier.fusePokemonId) as PlayerPokemon, + ); + } else if ( + modifier instanceof RememberMoveModifier && + !Utils.isNullOrUndefined(cost) + ) { + args.push(cost); + } + + if (modifier.shouldApply(pokemon, ...args)) { + const result = modifier.apply(pokemon, ...args); + success ||= result; + } + } + + this.party.map((p) => p.updateInfo(instant)); + } else { + const args = [ this ]; + if (modifier.shouldApply(...args)) { + const result = modifier.apply(...args); + success ||= result; + } + } + } + return success; } - addEnemyModifier(modifier: PersistentModifier, ignoreUpdate?: boolean, instant?: boolean): Promise { - return new Promise(resolve => { + addEnemyModifier( + modifier: PersistentModifier, + ignoreUpdate?: boolean, + instant?: boolean, + ): Promise { + return new Promise((resolve) => { const modifiersToRemove: PersistentModifier[] = []; if ((modifier as PersistentModifier).add(this.enemyModifiers, false)) { if (modifier instanceof PokemonFormChangeItemModifier) { @@ -2683,7 +3292,8 @@ export default class BattleScene extends SceneBase { } } if (!ignoreUpdate) { - this.updateModifiers(false, instant).then(() => resolve()); + this.updateModifiers(false, instant); + resolve(); } else { resolve(); } @@ -2704,86 +3314,128 @@ export default class BattleScene extends SceneBase { * @param itemLost If `true`, treat the item's current holder as losing the item (for now, this simply enables Unburden). Default is `true`. * @returns `true` if the transfer was successful */ - tryTransferHeldItemModifier(itemModifier: PokemonHeldItemModifier, target: Pokemon, playSound: boolean, transferQuantity: number = 1, instant?: boolean, ignoreUpdate?: boolean, itemLost: boolean = true): Promise { - return new Promise(resolve => { - const source = itemModifier.pokemonId ? itemModifier.getPokemon() : null; - const cancelled = new Utils.BooleanHolder(false); - Utils.executeIf(!!source && source.isPlayer() !== target.isPlayer(), () => applyAbAttrs(BlockItemTheftAbAttr, source! /* checked in condition*/, cancelled)).then(() => { - if (cancelled.value) { - return resolve(false); - } - const newItemModifier = itemModifier.clone() as PokemonHeldItemModifier; - newItemModifier.pokemonId = target.id; - const matchingModifier = this.findModifier(m => m instanceof PokemonHeldItemModifier - && (m as PokemonHeldItemModifier).matchType(itemModifier) && m.pokemonId === target.id, target.isPlayer()) as PokemonHeldItemModifier; - let removeOld = true; - if (matchingModifier) { - const maxStackCount = matchingModifier.getMaxStackCount(); - if (matchingModifier.stackCount >= maxStackCount) { - return resolve(false); - } - const countTaken = Math.min(transferQuantity, itemModifier.stackCount, maxStackCount - matchingModifier.stackCount); - itemModifier.stackCount -= countTaken; - newItemModifier.stackCount = matchingModifier.stackCount + countTaken; - removeOld = !itemModifier.stackCount; - } else { - const countTaken = Math.min(transferQuantity, itemModifier.stackCount); - itemModifier.stackCount -= countTaken; - newItemModifier.stackCount = countTaken; - } - removeOld = !itemModifier.stackCount; - if (!removeOld || !source || this.removeModifier(itemModifier, !source.isPlayer())) { - const addModifier = () => { - if (!matchingModifier || this.removeModifier(matchingModifier, !target.isPlayer())) { - if (target.isPlayer()) { - this.addModifier(newItemModifier, ignoreUpdate, playSound, false, instant).then(() => { - if (source && itemLost) { - applyPostItemLostAbAttrs(PostItemLostAbAttr, source, false); - } - resolve(true); - }); - } else { - this.addEnemyModifier(newItemModifier, ignoreUpdate, instant).then(() => { - if (source && itemLost) { - applyPostItemLostAbAttrs(PostItemLostAbAttr, source, false); - } - resolve(true); - }); - } - } else { - resolve(false); + tryTransferHeldItemModifier( + itemModifier: PokemonHeldItemModifier, + target: Pokemon, + playSound: boolean, + transferQuantity: number = 1, + instant?: boolean, + ignoreUpdate?: boolean, + itemLost: boolean = true, + ): boolean { + const source = itemModifier.pokemonId ? itemModifier.getPokemon() : null; + const cancelled = new Utils.BooleanHolder(false); + + if (source && source.isPlayer() !== target.isPlayer()) { + applyAbAttrs(BlockItemTheftAbAttr, source, cancelled); + } + + if (cancelled.value) { + return false; + } + + const newItemModifier = itemModifier.clone() as PokemonHeldItemModifier; + newItemModifier.pokemonId = target.id; + const matchingModifier = this.findModifier( + (m) => + m instanceof PokemonHeldItemModifier && + m.matchType(itemModifier) && + m.pokemonId === target.id, + target.isPlayer(), + ) as PokemonHeldItemModifier; + + if (matchingModifier) { + const maxStackCount = matchingModifier.getMaxStackCount(); + if (matchingModifier.stackCount >= maxStackCount) { + return false; + } + const countTaken = Math.min( + transferQuantity, + itemModifier.stackCount, + maxStackCount - matchingModifier.stackCount, + ); + itemModifier.stackCount -= countTaken; + newItemModifier.stackCount = matchingModifier.stackCount + countTaken; + } else { + const countTaken = Math.min(transferQuantity, itemModifier.stackCount); + itemModifier.stackCount -= countTaken; + newItemModifier.stackCount = countTaken; + } + + const removeOld = itemModifier.stackCount === 0; + + if ( + !removeOld || + !source || + this.removeModifier(itemModifier, !source.isPlayer()) + ) { + const addModifier = () => { + if ( + !matchingModifier || + this.removeModifier(matchingModifier, !target.isPlayer()) + ) { + if (target.isPlayer()) { + this.addModifier( + newItemModifier, + ignoreUpdate, + playSound, + false, + instant, + ); + if (source && itemLost) { + applyPostItemLostAbAttrs(PostItemLostAbAttr, source, false); } - }; - if (source && source.isPlayer() !== target.isPlayer() && !ignoreUpdate) { - this.updateModifiers(source.isPlayer(), instant).then(() => addModifier()); + return true; } else { - addModifier(); + this.addEnemyModifier(newItemModifier, ignoreUpdate, instant); + if (source && itemLost) { + applyPostItemLostAbAttrs(PostItemLostAbAttr, source, false); + } + return true; } - return; } - resolve(false); - }); - }); + return false; + }; + if (source && source.isPlayer() !== target.isPlayer() && !ignoreUpdate) { + this.updateModifiers(source.isPlayer(), instant); + addModifier(); + } else { + addModifier(); + } + return true; + } + return false; } removePartyMemberModifiers(partyMemberIndex: number): Promise { - return new Promise(resolve => { + return new Promise((resolve) => { const pokemonId = this.getPlayerParty()[partyMemberIndex].id; - const modifiersToRemove = this.modifiers.filter(m => m instanceof PokemonHeldItemModifier && (m as PokemonHeldItemModifier).pokemonId === pokemonId); + const modifiersToRemove = this.modifiers.filter( + (m) => + m instanceof PokemonHeldItemModifier && + (m as PokemonHeldItemModifier).pokemonId === pokemonId, + ); for (const m of modifiersToRemove) { this.modifiers.splice(this.modifiers.indexOf(m), 1); } - this.updateModifiers().then(() => resolve()); + this.updateModifiers(); + resolve(); }); } - generateEnemyModifiers(heldModifiersConfigs?: HeldModifierConfig[][]): Promise { - return new Promise(resolve => { + generateEnemyModifiers( + heldModifiersConfigs?: HeldModifierConfig[][], + ): Promise { + return new Promise((resolve) => { if (this.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { return resolve(); } - const difficultyWaveIndex = this.gameMode.getWaveForDifficulty(this.currentBattle.waveIndex); - const isFinalBoss = this.gameMode.isWaveFinal(this.currentBattle.waveIndex); + const difficultyWaveIndex = this.gameMode.getWaveForDifficulty( + this.currentBattle.waveIndex, + ); + const isFinalBoss = this.gameMode.isWaveFinal( + this.currentBattle.waveIndex, + ); let chances = Math.ceil(difficultyWaveIndex / 10); if (isFinalBoss) { chances = Math.ceil(chances * 2.5); @@ -2801,8 +3453,12 @@ export default class BattleScene extends SceneBase { } party.forEach((enemyPokemon: EnemyPokemon, i: number) => { - if (heldModifiersConfigs && i < heldModifiersConfigs.length && heldModifiersConfigs[i]) { - heldModifiersConfigs[i].forEach(mt => { + if ( + heldModifiersConfigs && + i < heldModifiersConfigs.length && + heldModifiersConfigs[i] + ) { + heldModifiersConfigs[i].forEach((mt) => { let modifier: PokemonHeldItemModifier; if (mt.modifier instanceof PokemonHeldItemModifierType) { modifier = mt.modifier.newModifier(enemyPokemon); @@ -2811,11 +3467,15 @@ export default class BattleScene extends SceneBase { modifier.pokemonId = enemyPokemon.id; } modifier.stackCount = mt.stackCount ?? 1; - modifier.isTransferable = mt.isTransferable ?? modifier.isTransferable; + modifier.isTransferable = + mt.isTransferable ?? modifier.isTransferable; this.addEnemyModifier(modifier, true); }); } else { - const isBoss = enemyPokemon.isBoss() || (this.currentBattle.battleType === BattleType.TRAINER && !!this.currentBattle.trainer?.config.isBoss); + const isBoss = + enemyPokemon.isBoss() || + (this.currentBattle.battleType === BattleType.TRAINER && + !!this.currentBattle.trainer?.config.isBoss); let upgradeChance = 32; if (isBoss) { upgradeChance /= 2; @@ -2823,96 +3483,115 @@ export default class BattleScene extends SceneBase { if (isFinalBoss) { upgradeChance /= 8; } - const modifierChance = this.gameMode.getEnemyModifierChance(isBoss); - let pokemonModifierChance = modifierChance; - if (this.currentBattle.battleType === BattleType.TRAINER && this.currentBattle.trainer) - pokemonModifierChance = Math.ceil(pokemonModifierChance * this.currentBattle.trainer.getPartyMemberModifierChanceMultiplier(i)); // eslint-disable-line let count = 0; for (let c = 0; c < chances; c++) { - if (!Utils.randSeedInt(modifierChance)) { + if (!Utils.randSeedInt(this.gameMode.getEnemyModifierChance(isBoss))) { count++; } } if (isBoss) { count = Math.max(count, Math.floor(chances / 2)); } - getEnemyModifierTypesForWave(difficultyWaveIndex, count, [ enemyPokemon ], this.currentBattle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD, upgradeChance) - .map(mt => mt.newModifier(enemyPokemon).add(this.enemyModifiers, false)); + getEnemyModifierTypesForWave( + difficultyWaveIndex, + count, + [ enemyPokemon ], + this.currentBattle.battleType === BattleType.TRAINER + ? ModifierPoolType.TRAINER + : ModifierPoolType.WILD, + upgradeChance, + ).map((mt) => + mt.newModifier(enemyPokemon).add(this.enemyModifiers, false), + ); } return true; }); - this.updateModifiers(false).then(() => resolve()); + this.updateModifiers(false); + resolve(); }); } /** - * Removes all modifiers from enemy pokemon of {@linkcode PersistentModifier} type - */ + * Removes all modifiers from enemy pokemon of {@linkcode PersistentModifier} type + */ clearEnemyModifiers(): void { - const modifiersToRemove = this.enemyModifiers.filter(m => m instanceof PersistentModifier); + const modifiersToRemove = this.enemyModifiers.filter( + (m) => m instanceof PersistentModifier, + ); for (const m of modifiersToRemove) { this.enemyModifiers.splice(this.enemyModifiers.indexOf(m), 1); } - this.updateModifiers(false).then(() => this.updateUIPositions()); + this.updateModifiers(false); + this.updateUIPositions(); } /** - * Removes all modifiers from enemy pokemon of {@linkcode PokemonHeldItemModifier} type - * @param pokemon - If specified, only removes held items from that {@linkcode Pokemon} - */ + * Removes all modifiers from enemy pokemon of {@linkcode PokemonHeldItemModifier} type + * @param pokemon - If specified, only removes held items from that {@linkcode Pokemon} + */ clearEnemyHeldItemModifiers(pokemon?: Pokemon): void { - const modifiersToRemove = this.enemyModifiers.filter(m => m instanceof PokemonHeldItemModifier && (!pokemon || m.getPokemon() === pokemon)); + const modifiersToRemove = this.enemyModifiers.filter( + (m) => + m instanceof PokemonHeldItemModifier && + (!pokemon || m.getPokemon() === pokemon), + ); for (const m of modifiersToRemove) { this.enemyModifiers.splice(this.enemyModifiers.indexOf(m), 1); } - this.updateModifiers(false).then(() => this.updateUIPositions()); + this.updateModifiers(false); + this.updateUIPositions(); } setModifiersVisible(visible: boolean) { - [ this.modifierBar, this.enemyModifierBar ].map(m => m.setVisible(visible)); + [ this.modifierBar, this.enemyModifierBar ].map((m) => m.setVisible(visible)); } - updateModifiers(player?: boolean, instant?: boolean): Promise { - if (player === undefined) { - player = true; + updateModifiers(player: boolean = true, instant?: boolean): void { + const modifiers = player + ? this.modifiers + : (this.enemyModifiers as PersistentModifier[]); + for (let m = 0; m < modifiers.length; m++) { + const modifier = modifiers[m]; + if ( + modifier instanceof PokemonHeldItemModifier && + !this.getPokemonById((modifier as PokemonHeldItemModifier).pokemonId) + ) { + modifiers.splice(m--, 1); + } } - return new Promise(resolve => { - const modifiers = player ? this.modifiers : this.enemyModifiers as PersistentModifier[]; - for (let m = 0; m < modifiers.length; m++) { - const modifier = modifiers[m]; - if (modifier instanceof PokemonHeldItemModifier && !this.getPokemonById((modifier as PokemonHeldItemModifier).pokemonId)) { - modifiers.splice(m--, 1); - } - } - for (const modifier of modifiers) { - if (modifier instanceof PersistentModifier) { - (modifier as PersistentModifier).virtualStackCount = 0; - } + for (const modifier of modifiers) { + if (modifier instanceof PersistentModifier) { + (modifier as PersistentModifier).virtualStackCount = 0; } + } - const modifiersClone = modifiers.slice(0); - for (const modifier of modifiersClone) { - if (!modifier.getStackCount()) { - modifiers.splice(modifiers.indexOf(modifier), 1); - } + const modifiersClone = modifiers.slice(0); + for (const modifier of modifiersClone) { + if (!modifier.getStackCount()) { + modifiers.splice(modifiers.indexOf(modifier), 1); } + } - this.updatePartyForModifiers(player ? this.getPlayerParty() : this.getEnemyParty(), instant).then(() => { - (player ? this.modifierBar : this.enemyModifierBar).updateModifiers(modifiers); - if (!player) { - this.updateUIPositions(); - } - resolve(); - }); - }); + this.updatePartyForModifiers( + player ? this.getPlayerParty() : this.getEnemyParty(), + instant, + ); + (player ? this.modifierBar : this.enemyModifierBar).updateModifiers( + modifiers, + ); + if (!player) { + this.updateUIPositions(); + } } updatePartyForModifiers(party: Pokemon[], instant?: boolean): Promise { - return new Promise(resolve => { - Promise.allSettled(party.map(p => { - p.calculateStats(); - return p.updateInfo(instant); - })).then(() => resolve()); + return new Promise((resolve) => { + Promise.allSettled( + party.map((p) => { + p.calculateStats(); + return p.updateInfo(instant); + }), + ).then(() => resolve()); }); } @@ -2924,7 +3603,10 @@ export default class BattleScene extends SceneBase { * @param enemy If `true`, remove an item owned by the enemy. If `false`, remove an item owned by the player. Default is `false`. * @returns `true` if the item exists and was successfully removed, `false` otherwise. */ - removeModifier(modifier: PersistentModifier, enemy: boolean = false): boolean { + removeModifier( + modifier: PersistentModifier, + enemy: boolean = false, + ): boolean { const modifiers = !enemy ? this.modifiers : this.enemyModifiers; const modifierIndex = modifiers.indexOf(modifier); if (modifierIndex > -1) { @@ -2947,8 +3629,13 @@ export default class BattleScene extends SceneBase { * @param player Whether to search the player (`true`) or the enemy (`false`); Defaults to `true` * @returns the list of all modifiers that matched `modifierType`. */ - getModifiers(modifierType: Constructor, player: boolean = true): T[] { - return (player ? this.modifiers : this.enemyModifiers).filter((m): m is T => m instanceof modifierType); + getModifiers( + modifierType: Constructor, + player: boolean = true, + ): T[] { + return (player ? this.modifiers : this.enemyModifiers).filter( + (m): m is T => m instanceof modifierType, + ); } /** @@ -2957,8 +3644,13 @@ export default class BattleScene extends SceneBase { * @param isPlayer Whether to search the player (`true`) or the enemy (`false`); Defaults to `true` * @returns the list of all modifiers that passed the `modifierFilter` function */ - findModifiers(modifierFilter: ModifierPredicate, isPlayer: boolean = true): PersistentModifier[] { - return (isPlayer ? this.modifiers : this.enemyModifiers).filter(modifierFilter); + findModifiers( + modifierFilter: ModifierPredicate, + isPlayer: boolean = true, + ): PersistentModifier[] { + return (isPlayer ? this.modifiers : this.enemyModifiers).filter( + modifierFilter, + ); } /** @@ -2967,7 +3659,10 @@ export default class BattleScene extends SceneBase { * @param player Whether to search the player (`true`) or the enemy (`false`); Defaults to `true` * @returns the first modifier that passed the `modifierFilter` function; `undefined` if none passed */ - findModifier(modifierFilter: ModifierPredicate, player: boolean = true): PersistentModifier | undefined { + findModifier( + modifierFilter: ModifierPredicate, + player: boolean = true, + ): PersistentModifier | undefined { return (player ? this.modifiers : this.enemyModifiers).find(modifierFilter); } @@ -2978,18 +3673,31 @@ export default class BattleScene extends SceneBase { * @param ...args The list of arguments needed to invoke `modifierType.apply` * @returns the list of all modifiers that matched `modifierType` and were applied. */ - applyShuffledModifiers(modifierType: Constructor, player: boolean = true, ...args: Parameters): T[] { - let modifiers = (player ? this.modifiers : this.enemyModifiers).filter((m): m is T => m instanceof modifierType && m.shouldApply(...args)); - this.executeWithSeedOffset(() => { - const shuffleModifiers = mods => { - if (mods.length < 1) { - return mods; - } - const rand = Utils.randSeedInt(mods.length); - return [ mods[rand], ...shuffleModifiers(mods.filter((_, i) => i !== rand)) ]; - }; - modifiers = shuffleModifiers(modifiers); - }, this.currentBattle.turn << 4, this.waveSeed); + applyShuffledModifiers( + modifierType: Constructor, + player: boolean = true, + ...args: Parameters + ): T[] { + let modifiers = (player ? this.modifiers : this.enemyModifiers).filter( + (m): m is T => m instanceof modifierType && m.shouldApply(...args), + ); + this.executeWithSeedOffset( + () => { + const shuffleModifiers = (mods) => { + if (mods.length < 1) { + return mods; + } + const rand = Utils.randSeedInt(mods.length); + return [ + mods[rand], + ...shuffleModifiers(mods.filter((_, i) => i !== rand)), + ]; + }; + modifiers = shuffleModifiers(modifiers); + }, + this.currentBattle.turn << 4, + this.waveSeed, + ); return this.applyModifiersInternal(modifiers, player, args); } @@ -3000,13 +3708,23 @@ export default class BattleScene extends SceneBase { * @param ...args The list of arguments needed to invoke `modifierType.apply` * @returns the list of all modifiers that matched `modifierType` and were applied. */ - applyModifiers(modifierType: Constructor, player: boolean = true, ...args: Parameters): T[] { - const modifiers = (player ? this.modifiers : this.enemyModifiers).filter((m): m is T => m instanceof modifierType && m.shouldApply(...args)); + applyModifiers( + modifierType: Constructor, + player: boolean = true, + ...args: Parameters + ): T[] { + const modifiers = (player ? this.modifiers : this.enemyModifiers).filter( + (m): m is T => m instanceof modifierType && m.shouldApply(...args), + ); return this.applyModifiersInternal(modifiers, player, args); } /** Helper function to apply all passed modifiers */ - applyModifiersInternal(modifiers: T[], player: boolean, args: Parameters): T[] { + applyModifiersInternal( + modifiers: T[], + player: boolean, + args: Parameters, + ): T[] { const appliedModifiers: T[] = []; for (const modifier of modifiers) { if (modifier.apply(...args)) { @@ -3025,8 +3743,14 @@ export default class BattleScene extends SceneBase { * @param ...args The list of arguments needed to invoke `modifierType.apply` * @returns the first modifier that matches `modifierType` and was applied; return `null` if none matched */ - applyModifier(modifierType: Constructor, player: boolean = true, ...args: Parameters): T | null { - const modifiers = (player ? this.modifiers : this.enemyModifiers).filter((m): m is T => m instanceof modifierType && m.shouldApply(...args)); + applyModifier( + modifierType: Constructor, + player: boolean = true, + ...args: Parameters + ): T | null { + const modifiers = (player ? this.modifiers : this.enemyModifiers).filter( + (m): m is T => m instanceof modifierType && m.shouldApply(...args), + ); for (const modifier of modifiers) { if (modifier.apply(...args)) { console.log("Applied", modifier.type.name, !player ? "(enemy)" : ""); @@ -3037,22 +3761,42 @@ export default class BattleScene extends SceneBase { return null; } - triggerPokemonFormChange(pokemon: Pokemon, formChangeTriggerType: Constructor, delayed: boolean = false, modal: boolean = false): boolean { + triggerPokemonFormChange( + pokemon: Pokemon, + formChangeTriggerType: Constructor, + delayed: boolean = false, + modal: boolean = false, + ): boolean { if (pokemonFormChanges.hasOwnProperty(pokemon.species.speciesId)) { - // in case this is NECROZMA, determine which forms this - const matchingFormChangeOpts = pokemonFormChanges[pokemon.species.speciesId].filter(fc => fc.findTrigger(formChangeTriggerType) && fc.canChange(pokemon)); + const matchingFormChangeOpts = pokemonFormChanges[ + pokemon.species.speciesId + ].filter( + (fc) => fc.findTrigger(formChangeTriggerType) && fc.canChange(pokemon), + ); let matchingFormChange: SpeciesFormChange | null; - if (pokemon.species.speciesId === Species.NECROZMA && matchingFormChangeOpts.length > 1) { + if ( + pokemon.species.speciesId === Species.NECROZMA && + matchingFormChangeOpts.length > 1 + ) { // Ultra Necrozma is changing its form back, so we need to figure out into which form it devolves. - const formChangeItemModifiers = (this.findModifiers(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === pokemon.id) as PokemonFormChangeItemModifier[]).filter(m => m.active).map(m => m.formChangeItem); + const formChangeItemModifiers = ( + this.findModifiers( + (m) => + m instanceof PokemonFormChangeItemModifier && + m.pokemonId === pokemon.id, + ) as PokemonFormChangeItemModifier[] + ) + .filter((m) => m.active) + .map((m) => m.formChangeItem); - - matchingFormChange = formChangeItemModifiers.includes(FormChangeItem.N_LUNARIZER) ? - matchingFormChangeOpts[0] : - formChangeItemModifiers.includes(FormChangeItem.N_SOLARIZER) ? - matchingFormChangeOpts[1] : - null; + matchingFormChange = formChangeItemModifiers.includes( + FormChangeItem.N_LUNARIZER, + ) + ? matchingFormChangeOpts[0] + : formChangeItemModifiers.includes(FormChangeItem.N_SOLARIZER) + ? matchingFormChangeOpts[1] + : null; } else { matchingFormChange = matchingFormChangeOpts[0]; } @@ -3063,7 +3807,11 @@ export default class BattleScene extends SceneBase { } else { phase = new QuietFormChangePhase(pokemon, matchingFormChange); } - if (pokemon instanceof PlayerPokemon && !matchingFormChange.quiet && modal) { + if ( + pokemon instanceof PlayerPokemon && + !matchingFormChange.quiet && + modal + ) { this.overridePhase(phase); } else if (delayed) { this.pushPhase(phase); @@ -3077,8 +3825,17 @@ export default class BattleScene extends SceneBase { return false; } - triggerPokemonBattleAnim(pokemon: Pokemon, battleAnimType: PokemonAnimType, fieldAssets?: Phaser.GameObjects.Sprite[], delayed: boolean = false): boolean { - const phase: Phase = new PokemonAnimPhase(battleAnimType, pokemon, fieldAssets); + triggerPokemonBattleAnim( + pokemon: Pokemon, + battleAnimType: PokemonAnimType, + fieldAssets?: Phaser.GameObjects.Sprite[], + delayed: boolean = false, + ): boolean { + const phase: Phase = new PokemonAnimPhase( + battleAnimType, + pokemon, + fieldAssets, + ); if (delayed) { this.pushPhase(phase); } else { @@ -3088,15 +3845,20 @@ export default class BattleScene extends SceneBase { } validateAchvs(achvType: Constructor, ...args: unknown[]): void { - const filteredAchvs = Object.values(achvs).filter(a => a instanceof achvType); + const filteredAchvs = Object.values(achvs).filter( + (a) => a instanceof achvType, + ); for (const achv of filteredAchvs) { this.validateAchv(achv, args); } } validateAchv(achv: Achv, args?: unknown[]): boolean { - if ((!this.gameData.achvUnlocks.hasOwnProperty(achv.id) || Overrides.ACHIEVEMENTS_REUNLOCK_OVERRIDE) - && achv.validate(args)) { + if ( + (!this.gameData.achvUnlocks.hasOwnProperty(achv.id) || + Overrides.ACHIEVEMENTS_REUNLOCK_OVERRIDE) && + achv.validate(args) + ) { this.gameData.achvUnlocks[achv.id] = new Date().getTime(); this.ui.achvBar.showAchv(achv); if (vouchers.hasOwnProperty(achv.id)) { @@ -3109,7 +3871,10 @@ export default class BattleScene extends SceneBase { } validateVoucher(voucher: Voucher, args?: unknown[]): boolean { - if (!this.gameData.voucherUnlocks.hasOwnProperty(voucher.id) && voucher.validate(args)) { + if ( + !this.gameData.voucherUnlocks.hasOwnProperty(voucher.id) && + voucher.validate(args) + ) { this.gameData.voucherUnlocks[voucher.id] = new Date().getTime(); this.ui.achvBar.showAchv(voucher); this.gameData.voucherCounts[voucher.voucherType]++; @@ -3125,19 +3890,21 @@ export default class BattleScene extends SceneBase { gameMode: this.currentBattle ? this.gameMode.getName() : "Title", biome: this.currentBattle ? getBiomeName(this.arena.biomeType) : "", wave: this.currentBattle?.waveIndex ?? 0, - party: this.party ? this.party.map((p) => { - return { - name: p.name, - form: p.getFormKey(), - types: p.getTypes().map((type) => Type[type]), - teraType: Type[p.getTeraType()], - isTerastallized: p.isTerastallized, - level: p.level, - currentHP: p.hp, - maxHP: p.getMaxHp(), - status: p.status?.effect ? StatusEffect[p.status.effect] : "" - }; - }) : [], + party: this.party + ? this.party.map((p) => { + return { + name: p.name, + form: p.getFormKey(), + types: p.getTypes().map((type) => Type[type]), + teraType: Type[p.getTeraType()], + isTerastallized: p.isTerastallized, + level: p.level, + currentHP: p.hp, + maxHP: p.getMaxHp(), + status: p.status?.effect ? StatusEffect[p.status.effect] : "", + }; + }) + : [], modeChain: this.ui?.getModeChain() ?? [], }; (window as any).gameInfo = gameInfo; @@ -3171,26 +3938,44 @@ export default class BattleScene extends SceneBase { * @param pokemon The (enemy) pokemon */ initFinalBossPhaseTwo(pokemon: Pokemon): void { - if (pokemon instanceof EnemyPokemon && pokemon.isBoss() && !pokemon.formIndex && pokemon.bossSegmentIndex < 1) { + if ( + pokemon instanceof EnemyPokemon && + pokemon.isBoss() && + !pokemon.formIndex && + pokemon.bossSegmentIndex < 1 + ) { this.fadeOutBgm(Utils.fixedInt(2000), false); - this.ui.showDialogue(battleSpecDialogue[BattleSpec.FINAL_BOSS].firstStageWin, pokemon.species.name, undefined, () => { - const finalBossMBH = getModifierType(modifierTypes.MINI_BLACK_HOLE).newModifier(pokemon) as TurnHeldItemTransferModifier; - finalBossMBH.setTransferrableFalse(); - this.addEnemyModifier(finalBossMBH, false, true); - pokemon.generateAndPopulateMoveset(1); - this.setFieldScale(0.75); - this.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); - this.currentBattle.double = true; - const availablePartyMembers = this.getPlayerParty().filter((p) => p.isAllowedInBattle()); - if (availablePartyMembers.length > 1) { - this.pushPhase(new ToggleDoublePositionPhase(true)); - if (!availablePartyMembers[1].isOnField()) { - this.pushPhase(new SummonPhase(1)); + this.ui.showDialogue( + battleSpecDialogue[BattleSpec.FINAL_BOSS].firstStageWin, + pokemon.species.name, + undefined, + () => { + const finalBossMBH = getModifierType( + modifierTypes.MINI_BLACK_HOLE, + ).newModifier(pokemon) as TurnHeldItemTransferModifier; + finalBossMBH.setTransferrableFalse(); + this.addEnemyModifier(finalBossMBH, false, true); + pokemon.generateAndPopulateMoveset(1); + this.setFieldScale(0.75); + this.triggerPokemonFormChange( + pokemon, + SpeciesFormChangeManualTrigger, + false, + ); + this.currentBattle.double = true; + const availablePartyMembers = this.getPlayerParty().filter((p) => + p.isAllowedInBattle(), + ); + if (availablePartyMembers.length > 1) { + this.pushPhase(new ToggleDoublePositionPhase(true)); + if (!availablePartyMembers[1].isOnField()) { + this.pushPhase(new SummonPhase(1)); + } } - } - this.shiftPhase(); - }); + this.shiftPhase(); + }, + ); return; } @@ -3204,33 +3989,62 @@ export default class BattleScene extends SceneBase { * @param useWaveIndexMultiplier Default false. If true, will multiply expValue by a scaling waveIndex multiplier. Not needed if expValue is already scaled by level/wave * @param pokemonParticipantIds Participants. If none are defined, no exp will be given. To spread evenly among the party, should pass all ids of party members. */ - applyPartyExp(expValue: number, pokemonDefeated: boolean, useWaveIndexMultiplier?: boolean, pokemonParticipantIds?: Set): void { - const participantIds = pokemonParticipantIds ?? this.currentBattle.playerParticipantIds; + applyPartyExp( + expValue: number, + pokemonDefeated: boolean, + useWaveIndexMultiplier?: boolean, + pokemonParticipantIds?: Set, + ): void { + const participantIds = + pokemonParticipantIds ?? this.currentBattle.playerParticipantIds; const party = this.getPlayerParty(); - const expShareModifier = this.findModifier(m => m instanceof ExpShareModifier) as ExpShareModifier; - const expBalanceModifier = this.findModifier(m => m instanceof ExpBalanceModifier) as ExpBalanceModifier; - const multipleParticipantExpBonusModifier = this.findModifier(m => m instanceof MultipleParticipantExpBonusModifier) as MultipleParticipantExpBonusModifier; - const nonFaintedPartyMembers = party.filter(p => p.hp); - const expPartyMembers = nonFaintedPartyMembers.filter(p => p.level < this.getMaxExpLevel()); + const expShareModifier = this.findModifier( + (m) => m instanceof ExpShareModifier, + ) as ExpShareModifier; + const expBalanceModifier = this.findModifier( + (m) => m instanceof ExpBalanceModifier, + ) as ExpBalanceModifier; + const multipleParticipantExpBonusModifier = this.findModifier( + (m) => m instanceof MultipleParticipantExpBonusModifier, + ) as MultipleParticipantExpBonusModifier; + const nonFaintedPartyMembers = party.filter((p) => p.hp); + const expPartyMembers = nonFaintedPartyMembers.filter( + (p) => p.level < this.getMaxExpLevel(), + ); const partyMemberExp: number[] = []; // EXP value calculation is based off Pokemon.getExpValue if (useWaveIndexMultiplier) { - expValue = Math.floor(expValue * this.currentBattle.waveIndex / 5 + 1); + expValue = Math.floor((expValue * this.currentBattle.waveIndex) / 5 + 1); } if (participantIds.size > 0) { - if (this.currentBattle.battleType === BattleType.TRAINER || this.currentBattle.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE) { + if ( + this.currentBattle.battleType === BattleType.TRAINER || + this.currentBattle.mysteryEncounter?.encounterMode === + MysteryEncounterMode.TRAINER_BATTLE + ) { expValue = Math.floor(expValue * 1.5); - } else if (this.currentBattle.isBattleMysteryEncounter() && this.currentBattle.mysteryEncounter) { - expValue = Math.floor(expValue * this.currentBattle.mysteryEncounter.expMultiplier); + } else if ( + this.currentBattle.isBattleMysteryEncounter() && + this.currentBattle.mysteryEncounter + ) { + expValue = Math.floor( + expValue * this.currentBattle.mysteryEncounter.expMultiplier, + ); } for (const partyMember of nonFaintedPartyMembers) { const pId = partyMember.id; const participated = participantIds.has(pId); if (participated && pokemonDefeated) { partyMember.addFriendship(FRIENDSHIP_GAIN_FROM_BATTLE); - const machoBraceModifier = partyMember.getHeldItems().find(m => m instanceof PokemonIncrementingStatModifier); - if (machoBraceModifier && machoBraceModifier.stackCount < machoBraceModifier.getMaxStackCount()) { + const machoBraceModifier = partyMember + .getHeldItems() + .find((m) => m instanceof PokemonIncrementingStatModifier); + if ( + machoBraceModifier && + machoBraceModifier.stackCount < + machoBraceModifier.getMaxStackCount() + ) { machoBraceModifier.stackCount++; this.updateModifiers(true, true); partyMember.updateInfo(); @@ -3245,12 +4059,14 @@ export default class BattleScene extends SceneBase { } let expMultiplier = 0; if (participated) { - expMultiplier += (1 / participantIds.size); + expMultiplier += 1 / participantIds.size; if (participantIds.size > 1 && multipleParticipantExpBonusModifier) { - expMultiplier += multipleParticipantExpBonusModifier.getStackCount() * 0.2; + expMultiplier += + multipleParticipantExpBonusModifier.getStackCount() * 0.2; } } else if (expShareModifier) { - expMultiplier += (expShareModifier.getStackCount() * 0.2) / participantIds.size; + expMultiplier += + (expShareModifier.getStackCount() * 0.2) / participantIds.size; } if (partyMember.pokerus) { expMultiplier *= 1.5; @@ -3259,7 +4075,12 @@ export default class BattleScene extends SceneBase { expMultiplier = Overrides.XP_MULTIPLIER_OVERRIDE; } const pokemonExp = new Utils.NumberHolder(expValue * expMultiplier); - this.applyModifiers(PokemonExpBoosterModifier, true, partyMember, pokemonExp); + this.applyModifiers( + PokemonExpBoosterModifier, + true, + partyMember, + pokemonExp, + ); partyMemberExp.push(Math.floor(pokemonExp.value)); } @@ -3280,10 +4101,16 @@ export default class BattleScene extends SceneBase { } }); - const splitExp = Math.floor(totalExp / recipientExpPartyMemberIndexes.length); + const splitExp = Math.floor( + totalExp / recipientExpPartyMemberIndexes.length, + ); expPartyMembers.forEach((_partyMember, pm) => { - partyMemberExp[pm] = Phaser.Math.Linear(partyMemberExp[pm], recipientExpPartyMemberIndexes.indexOf(pm) > -1 ? splitExp : 0, 0.2 * expBalanceModifier.getStackCount()); + partyMemberExp[pm] = Phaser.Math.Linear( + partyMemberExp[pm], + recipientExpPartyMemberIndexes.indexOf(pm) > -1 ? splitExp : 0, + 0.2 * expBalanceModifier.getStackCount(), + ); }); } @@ -3292,7 +4119,11 @@ export default class BattleScene extends SceneBase { if (exp) { const partyMemberIndex = party.indexOf(expPartyMembers[pm]); - this.unshiftPhase(expPartyMembers[pm].isOnField() ? new ExpPhase(partyMemberIndex, exp) : new ShowPartyExpBarPhase(partyMemberIndex, exp)); + this.unshiftPhase( + expPartyMembers[pm].isOnField() + ? new ExpPhase(partyMemberIndex, exp) + : new ShowPartyExpBarPhase(partyMemberIndex, exp), + ); } } } @@ -3303,9 +4134,19 @@ export default class BattleScene extends SceneBase { * Even if returns `true`, does not guarantee that a wave will actually be a ME. * That check is made in {@linkcode BattleScene.isWaveMysteryEncounter} instead. */ - isMysteryEncounterValidForWave(battleType: BattleType, waveIndex: number): boolean { - const [ lowestMysteryEncounterWave, highestMysteryEncounterWave ] = this.gameMode.getMysteryEncounterLegalWaves(); - return this.gameMode.hasMysteryEncounters && battleType === BattleType.WILD && !this.gameMode.isBoss(waveIndex) && waveIndex < highestMysteryEncounterWave && waveIndex > lowestMysteryEncounterWave; + isMysteryEncounterValidForWave( + battleType: BattleType, + waveIndex: number, + ): boolean { + const [ lowestMysteryEncounterWave, highestMysteryEncounterWave ] = + this.gameMode.getMysteryEncounterLegalWaves(); + return ( + this.gameMode.hasMysteryEncounters && + battleType === BattleType.WILD && + !this.gameMode.isBoss(waveIndex) && + waveIndex < highestMysteryEncounterWave && + waveIndex > lowestMysteryEncounterWave + ); } /** @@ -3315,31 +4156,56 @@ export default class BattleScene extends SceneBase { * @param newBattleType * @param waveIndex */ - private isWaveMysteryEncounter(newBattleType: BattleType, waveIndex: number): boolean { - const [ lowestMysteryEncounterWave, highestMysteryEncounterWave ] = this.gameMode.getMysteryEncounterLegalWaves(); + private isWaveMysteryEncounter( + newBattleType: BattleType, + waveIndex: number, + ): boolean { + const [ lowestMysteryEncounterWave, highestMysteryEncounterWave ] = + this.gameMode.getMysteryEncounterLegalWaves(); if (this.isMysteryEncounterValidForWave(newBattleType, waveIndex)) { // Base spawn weight is BASE_MYSTERY_ENCOUNTER_SPAWN_WEIGHT/256, and increases by WEIGHT_INCREMENT_ON_SPAWN_MISS/256 for each missed attempt at spawning an encounter on a valid floor - const sessionEncounterRate = this.mysteryEncounterSaveData.encounterSpawnChance; + const sessionEncounterRate = + this.mysteryEncounterSaveData.encounterSpawnChance; const encounteredEvents = this.mysteryEncounterSaveData.encounteredEvents; // If total number of encounters is lower than expected for the run, slightly favor a new encounter spawn (reverse as well) // Reduces occurrence of runs with total encounters significantly different from AVERAGE_ENCOUNTERS_PER_RUN_TARGET // Favored rate changes can never exceed 50%. So if base rate is 15/256 and favored rate would add 200/256, result will be (15 + 128)/256 - const expectedEncountersByFloor = AVERAGE_ENCOUNTERS_PER_RUN_TARGET / (highestMysteryEncounterWave - lowestMysteryEncounterWave) * (waveIndex - lowestMysteryEncounterWave); - const currentRunDiffFromAvg = expectedEncountersByFloor - encounteredEvents.length; - const favoredEncounterRate = sessionEncounterRate + Math.min(currentRunDiffFromAvg * ANTI_VARIANCE_WEIGHT_MODIFIER, MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT / 2); + const expectedEncountersByFloor = + (AVERAGE_ENCOUNTERS_PER_RUN_TARGET / + (highestMysteryEncounterWave - lowestMysteryEncounterWave)) * + (waveIndex - lowestMysteryEncounterWave); + const currentRunDiffFromAvg = + expectedEncountersByFloor - encounteredEvents.length; + const favoredEncounterRate = + sessionEncounterRate + + Math.min( + currentRunDiffFromAvg * ANTI_VARIANCE_WEIGHT_MODIFIER, + MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT / 2, + ); - const successRate = isNullOrUndefined(Overrides.MYSTERY_ENCOUNTER_RATE_OVERRIDE) ? favoredEncounterRate : Overrides.MYSTERY_ENCOUNTER_RATE_OVERRIDE!; + const successRate = isNullOrUndefined( + Overrides.MYSTERY_ENCOUNTER_RATE_OVERRIDE, + ) + ? favoredEncounterRate + : Overrides.MYSTERY_ENCOUNTER_RATE_OVERRIDE!; // If the most recent ME was 3 or fewer waves ago, can never spawn a ME - const canSpawn = encounteredEvents.length === 0 || (waveIndex - encounteredEvents[encounteredEvents.length - 1].waveIndex) > 3 || !isNullOrUndefined(Overrides.MYSTERY_ENCOUNTER_RATE_OVERRIDE); + const canSpawn = + encounteredEvents.length === 0 || + waveIndex - encounteredEvents[encounteredEvents.length - 1].waveIndex > + 3 || + !isNullOrUndefined(Overrides.MYSTERY_ENCOUNTER_RATE_OVERRIDE); if (canSpawn) { let roll = MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT; // Always rolls the check on the same offset to ensure no RNG changes from reloading session - this.executeWithSeedOffset(() => { - roll = randSeedInt(MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT); - }, waveIndex * 3 * 1000); + this.executeWithSeedOffset( + () => { + roll = randSeedInt(MYSTERY_ENCOUNTER_SPAWN_MAX_WEIGHT); + }, + waveIndex * 3 * 1000, + ); return roll < successRate; } } @@ -3353,10 +4219,16 @@ export default class BattleScene extends SceneBase { * @param canBypass optional boolean to indicate that the request is coming from a function that needs to access a Mystery Encounter outside of gameplay requirements * @returns */ - getMysteryEncounter(encounterType?: MysteryEncounterType, canBypass?: boolean): MysteryEncounter { + getMysteryEncounter( + encounterType?: MysteryEncounterType, + canBypass?: boolean, + ): MysteryEncounter { // Loading override or session encounter let encounter: MysteryEncounter | null; - if (!isNullOrUndefined(Overrides.MYSTERY_ENCOUNTER_OVERRIDE) && allMysteryEncounters.hasOwnProperty(Overrides.MYSTERY_ENCOUNTER_OVERRIDE)) { + if ( + !isNullOrUndefined(Overrides.MYSTERY_ENCOUNTER_OVERRIDE) && + allMysteryEncounters.hasOwnProperty(Overrides.MYSTERY_ENCOUNTER_OVERRIDE) + ) { encounter = allMysteryEncounters[Overrides.MYSTERY_ENCOUNTER_OVERRIDE]; if (canBypass) { return encounter; @@ -3365,13 +4237,22 @@ export default class BattleScene extends SceneBase { encounter = allMysteryEncounters[encounterType ?? -1]; return encounter; } else { - encounter = !isNullOrUndefined(encounterType) ? allMysteryEncounters[encounterType] : null; + encounter = !isNullOrUndefined(encounterType) + ? allMysteryEncounters[encounterType] + : null; } // Check for queued encounters first - if (!encounter && this.mysteryEncounterSaveData?.queuedEncounters && this.mysteryEncounterSaveData.queuedEncounters.length > 0) { + if ( + !encounter && + this.mysteryEncounterSaveData?.queuedEncounters && + this.mysteryEncounterSaveData.queuedEncounters.length > 0 + ) { let i = 0; - while (i < this.mysteryEncounterSaveData.queuedEncounters.length && !!encounter) { + while ( + i < this.mysteryEncounterSaveData.queuedEncounters.length && + !!encounter + ) { const candidate = this.mysteryEncounterSaveData.queuedEncounters[i]; const forcedChance = candidate.spawnPercent; if (Utils.randSeedInt(100) < forcedChance) { @@ -3389,34 +4270,56 @@ export default class BattleScene extends SceneBase { } // See Enum values for base tier weights - const tierWeights = [ MysteryEncounterTier.COMMON, MysteryEncounterTier.GREAT, MysteryEncounterTier.ULTRA, MysteryEncounterTier.ROGUE ]; + const tierWeights = [ + MysteryEncounterTier.COMMON, + MysteryEncounterTier.GREAT, + MysteryEncounterTier.ULTRA, + MysteryEncounterTier.ROGUE, + ]; // Adjust tier weights by previously encountered events to lower odds of only Common/Great in run - this.mysteryEncounterSaveData.encounteredEvents.forEach(seenEncounterData => { - if (seenEncounterData.tier === MysteryEncounterTier.COMMON) { - tierWeights[0] = tierWeights[0] - 6; - } else if (seenEncounterData.tier === MysteryEncounterTier.GREAT) { - tierWeights[1] = tierWeights[1] - 4; - } - }); + this.mysteryEncounterSaveData.encounteredEvents.forEach( + (seenEncounterData) => { + if (seenEncounterData.tier === MysteryEncounterTier.COMMON) { + tierWeights[0] = tierWeights[0] - 6; + } else if (seenEncounterData.tier === MysteryEncounterTier.GREAT) { + tierWeights[1] = tierWeights[1] - 4; + } + }, + ); const totalWeight = tierWeights.reduce((a, b) => a + b); const tierValue = Utils.randSeedInt(totalWeight); const commonThreshold = totalWeight - tierWeights[0]; const greatThreshold = totalWeight - tierWeights[0] - tierWeights[1]; - const ultraThreshold = totalWeight - tierWeights[0] - tierWeights[1] - tierWeights[2]; - let tier: MysteryEncounterTier | null = tierValue > commonThreshold ? MysteryEncounterTier.COMMON : tierValue > greatThreshold ? MysteryEncounterTier.GREAT : tierValue > ultraThreshold ? MysteryEncounterTier.ULTRA : MysteryEncounterTier.ROGUE; + const ultraThreshold = + totalWeight - tierWeights[0] - tierWeights[1] - tierWeights[2]; + let tier: MysteryEncounterTier | null = + tierValue > commonThreshold + ? MysteryEncounterTier.COMMON + : tierValue > greatThreshold + ? MysteryEncounterTier.GREAT + : tierValue > ultraThreshold + ? MysteryEncounterTier.ULTRA + : MysteryEncounterTier.ROGUE; if (!isNullOrUndefined(Overrides.MYSTERY_ENCOUNTER_TIER_OVERRIDE)) { tier = Overrides.MYSTERY_ENCOUNTER_TIER_OVERRIDE; } let availableEncounters: MysteryEncounter[] = []; - const previousEncounter = this.mysteryEncounterSaveData.encounteredEvents.length > 0 ? - this.mysteryEncounterSaveData.encounteredEvents[this.mysteryEncounterSaveData.encounteredEvents.length - 1].type - : null; - const disabledEncounters = this.eventManager.getEventMysteryEncountersDisabled(); - const biomeMysteryEncounters = mysteryEncountersByBiome.get(this.arena.biomeType)?.filter(enc => !disabledEncounters.includes(enc)) ?? []; + const previousEncounter = + this.mysteryEncounterSaveData.encounteredEvents.length > 0 + ? this.mysteryEncounterSaveData.encounteredEvents[ + this.mysteryEncounterSaveData.encounteredEvents.length - 1 + ].type + : null; + const disabledEncounters = + this.eventManager.getEventMysteryEncountersDisabled(); + const biomeMysteryEncounters = + mysteryEncountersByBiome + .get(this.arena.biomeType) + ?.filter((enc) => !disabledEncounters.includes(enc)) ?? []; // If no valid encounters exist at tier, checks next tier down, continuing until there are some encounters available while (availableEncounters.length === 0 && tier !== null) { availableEncounters = biomeMysteryEncounters @@ -3425,34 +4328,57 @@ export default class BattleScene extends SceneBase { if (!encounterCandidate) { return false; } - if (this.eventManager.getMysteryEncounterTierForEvent(encounterType, encounterCandidate.encounterTier) !== tier) { + if ( + this.eventManager.getMysteryEncounterTierForEvent( + encounterType, + encounterCandidate.encounterTier, + ) !== tier + ) { return false; } const disallowedGameModes = encounterCandidate.disallowedGameModes; - if (disallowedGameModes && disallowedGameModes.length > 0 - && disallowedGameModes.includes(this.gameMode.modeId)) { + if ( + disallowedGameModes && + disallowedGameModes.length > 0 && + disallowedGameModes.includes(this.gameMode.modeId) + ) { return false; } if (this.gameMode.modeId === GameModes.CHALLENGE) { - const disallowedChallenges = encounterCandidate.disallowedChallenges; - if (disallowedChallenges && disallowedChallenges.length > 0 && this.gameMode.challenges.some(challenge => disallowedChallenges.includes(challenge.id))) { + const disallowedChallenges = + encounterCandidate.disallowedChallenges; + if ( + disallowedChallenges && + disallowedChallenges.length > 0 && + this.gameMode.challenges.some((challenge) => + disallowedChallenges.includes(challenge.id), + ) + ) { return false; } } if (!encounterCandidate.meetsRequirements()) { return false; } - if (previousEncounter !== null && encounterType === previousEncounter) { + if ( + previousEncounter !== null && + encounterType === previousEncounter + ) { return false; } - if (this.mysteryEncounterSaveData.encounteredEvents.length > 0 && - (encounterCandidate.maxAllowedEncounters && encounterCandidate.maxAllowedEncounters > 0) - && this.mysteryEncounterSaveData.encounteredEvents.filter(e => e.type === encounterType).length >= encounterCandidate.maxAllowedEncounters) { + if ( + this.mysteryEncounterSaveData.encounteredEvents.length > 0 && + encounterCandidate.maxAllowedEncounters && + encounterCandidate.maxAllowedEncounters > 0 && + this.mysteryEncounterSaveData.encounteredEvents.filter( + (e) => e.type === encounterType, + ).length >= encounterCandidate.maxAllowedEncounters + ) { return false; } return true; }) - .map((m) => (allMysteryEncounters[m])); + .map((m) => allMysteryEncounters[m]); // Decrement tier if (tier === MysteryEncounterTier.ROGUE) { tier = MysteryEncounterTier.ULTRA; @@ -3467,10 +4393,13 @@ export default class BattleScene extends SceneBase { // If absolutely no encounters are available, spawn 0th encounter if (availableEncounters.length === 0) { - console.log("No Mystery Encounters found, falling back to Mysterious Challengers."); + console.log( + "No Mystery Encounters found, falling back to Mysterious Challengers.", + ); return allMysteryEncounters[MysteryEncounterType.MYSTERIOUS_CHALLENGERS]; } - encounter = availableEncounters[Utils.randSeedInt(availableEncounters.length)]; + encounter = + availableEncounters[Utils.randSeedInt(availableEncounters.length)]; // New encounter object to not dirty flags encounter = new MysteryEncounter(encounter); encounter.populateDialogueTokensFromRequirements(); diff --git a/src/data/ability.ts b/src/data/ability.ts index 95601dc2010..65da3753cde 100644 --- a/src/data/ability.ts +++ b/src/data/ability.ts @@ -1,6 +1,6 @@ -import type { EnemyPokemon } from "../field/pokemon"; +import type { EnemyPokemon, PokemonMove } from "../field/pokemon"; import type Pokemon from "../field/pokemon"; -import { HitResult, MoveResult, PlayerPokemon, PokemonMove } from "../field/pokemon"; +import { HitResult, MoveResult, PlayerPokemon } from "../field/pokemon"; import { Type } from "#enums/type"; import type { Constructor } from "#app/utils"; import * as Utils from "../utils"; @@ -44,6 +44,7 @@ import { MoveEndPhase } from "#app/phases/move-end-phase"; import { PokemonAnimType } from "#enums/pokemon-anim-type"; import { StatusEffect } from "#enums/status-effect"; import { WeatherType } from "#enums/weather-type"; +import { PokemonTransformPhase } from "#app/phases/pokemon-transform-phase"; export class Ability implements Localizable { public id: Abilities; @@ -143,7 +144,7 @@ export class Ability implements Localizable { } } -type AbAttrApplyFunc = (attr: TAttr, passive: boolean) => boolean | Promise; +type AbAttrApplyFunc = (attr: TAttr, passive: boolean) => boolean; type AbAttrCondition = (pokemon: Pokemon) => boolean; // TODO: Can this be improved? @@ -159,7 +160,7 @@ export abstract class AbAttr { this.showAbility = showAbility; } - apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder | null, args: any[]): boolean | Promise { + apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder | null, args: any[]): boolean { return false; } @@ -215,7 +216,7 @@ export class DoubleBattleChanceAbAttr extends AbAttr { } export class PostBattleInitAbAttr extends AbAttr { - applyPostBattleInit(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + applyPostBattleInit(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { return false; } } @@ -250,7 +251,7 @@ export class PostTeraFormChangeStatChangeAbAttr extends AbAttr { this.stages = stages; } - apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder | null, args: any[]): boolean | Promise { + apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder | null, args: any[]): boolean { const statStageChangePhases: StatStageChangePhase[] = []; if (!simulated) { @@ -268,7 +269,15 @@ export class PostTeraFormChangeStatChangeAbAttr extends AbAttr { type PreDefendAbAttrCondition = (pokemon: Pokemon, attacker: Pokemon, move: Move) => boolean; export class PreDefendAbAttr extends AbAttr { - applyPreDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move | null, cancelled: Utils.BooleanHolder | null, args: any[]): boolean | Promise { + applyPreDefend( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + attacker: Pokemon, + move: Move | null, + cancelled: Utils.BooleanHolder | null, + args: any[], + ): boolean { return false; } } @@ -546,7 +555,15 @@ export class FullHpResistTypeAbAttr extends PreDefendAbAttr { * @param args `[0]` a container for the move's current type effectiveness multiplier * @returns `true` if the move's effectiveness is reduced; `false` otherwise */ - applyPreDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move | null, cancelled: Utils.BooleanHolder | null, args: any[]): boolean | Promise { + override applyPreDefend( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + attacker: Pokemon, + move: Move | null, + cancelled: Utils.BooleanHolder | null, + args: any[], + ): boolean { const typeMultiplier = args[0]; if (!(typeMultiplier && typeMultiplier instanceof Utils.NumberHolder)) { return false; @@ -572,7 +589,15 @@ export class FullHpResistTypeAbAttr extends PreDefendAbAttr { } export class PostDefendAbAttr extends AbAttr { - applyPostDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean | Promise { + applyPostDefend( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + attacker: Pokemon, + move: Move, + hitResult: HitResult | null, + args: any[], + ): boolean { return false; } } @@ -593,7 +618,14 @@ export class FieldPriorityMoveImmunityAbAttr extends PreDefendAbAttr { } export class PostStatStageChangeAbAttr extends AbAttr { - applyPostStatStageChange(pokemon: Pokemon, simulated: boolean, statsChanged: BattleStat[], stagesChanged: number, selfTarget: boolean, args: any[]): boolean | Promise { + applyPostStatStageChange( + pokemon: Pokemon, + simulated: boolean, + statsChanged: BattleStat[], + stagesChanged: integer, + selfTarget: boolean, + args: any[], + ): boolean { return false; } } @@ -1142,7 +1174,14 @@ export class PostStatStageChangeStatStageChangeAbAttr extends PostStatStageChang } export class PreAttackAbAttr extends AbAttr { - applyPreAttack(pokemon: Pokemon, passive: boolean, simulated: boolean, defender: Pokemon | null, move: Move, args: any[]): boolean | Promise { + applyPreAttack( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + defender: Pokemon | null, + move: Move, + args: any[], + ): boolean { return false; } } @@ -1208,7 +1247,13 @@ export class VariableMovePowerAbAttr extends PreAttackAbAttr { } export class FieldPreventExplosiveMovesAbAttr extends AbAttr { - apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean | Promise { + override apply( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + cancelled: Utils.BooleanHolder, + args: any[], + ): boolean { cancelled.value = true; return true; } @@ -1562,8 +1607,15 @@ export class StatMultiplierAbAttr extends AbAttr { this.condition = condition ?? null; } - applyStatStage(pokemon: Pokemon, _passive: boolean, simulated: boolean, stat: BattleStat, statValue: Utils.NumberHolder, args: any[]): boolean | Promise { - const move = (args[0] as Move); + applyStatStage( + pokemon: Pokemon, + _passive: boolean, + simulated: boolean, + stat: BattleStat, + statValue: Utils.NumberHolder, + args: any[], + ): boolean { + const move = args[0] as Move; if (stat === this.stat && (!this.condition || this.condition(pokemon, null, move))) { statValue.value *= this.multiplier; return true; @@ -1588,7 +1640,15 @@ export class PostAttackAbAttr extends AbAttr { * applying the effect of any inherited class. This can be changed by providing a different {@link attackCondition} to the constructor. See {@link ConfusionOnStatusEffectAbAttr} * for an example of an effect that does not require a damaging move. */ - applyPostAttack(pokemon: Pokemon, passive: boolean, simulated: boolean, defender: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean | Promise { + applyPostAttack( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + defender: Pokemon, + move: Move, + hitResult: HitResult | null, + args: any[], + ): boolean { // When attackRequired is true, we require the move to be an attack move and to deal damage before checking secondary requirements. // If attackRequired is false, we always defer to the secondary requirements. if (this.attackCondition(pokemon, defender, move)) { @@ -1601,7 +1661,15 @@ export class PostAttackAbAttr extends AbAttr { /** * This method is only called after {@link applyPostAttack} has already been applied. Use this for handling checks specific to the ability in question. */ - applyPostAttackAfterMoveTypeCheck(pokemon: Pokemon, passive: boolean, simulated: boolean, defender: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean | Promise { + applyPostAttackAfterMoveTypeCheck( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + defender: Pokemon, + move: Move, + hitResult: HitResult | null, + args: any[], + ): boolean { return false; } } @@ -1626,7 +1694,15 @@ export class GorillaTacticsAbAttr extends PostAttackAbAttr { * @param args n/a * @returns `true` if the ability is applied */ - applyPostAttackAfterMoveTypeCheck(pokemon: Pokemon, passive: boolean, simulated: boolean, defender: Pokemon, move: Move, hitResult: HitResult | null, args: any[]): boolean | Promise { + override applyPostAttackAfterMoveTypeCheck( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + defender: Pokemon, + move: Move, + hitResult: HitResult | null, + args: any[], + ): boolean { if (simulated) { return simulated; } @@ -1649,23 +1725,36 @@ export class PostAttackStealHeldItemAbAttr extends PostAttackAbAttr { this.stealCondition = stealCondition ?? null; } - applyPostAttackAfterMoveTypeCheck(pokemon: Pokemon, passive: boolean, simulated: boolean, defender: Pokemon, move: Move, hitResult: HitResult, args: any[]): Promise { - return new Promise(resolve => { - if (!simulated && hitResult < HitResult.NO_EFFECT && (!this.stealCondition || this.stealCondition(pokemon, defender, move))) { - const heldItems = this.getTargetHeldItems(defender).filter(i => i.isTransferable); - if (heldItems.length) { - const stolenItem = heldItems[pokemon.randSeedInt(heldItems.length)]; - globalScene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => { - if (success) { - globalScene.queueMessage(i18next.t("abilityTriggers:postAttackStealHeldItem", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), defenderName: defender.name, stolenItemType: stolenItem.type.name })); - } - resolve(success); - }); - return; + override applyPostAttackAfterMoveTypeCheck( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + defender: Pokemon, + move: Move, + hitResult: HitResult, + args: any[], + ): boolean { + if ( + !simulated && + hitResult < HitResult.NO_EFFECT && + (!this.stealCondition || this.stealCondition(pokemon, defender, move)) + ) { + const heldItems = this.getTargetHeldItems(defender).filter((i) => i.isTransferable); + if (heldItems.length) { + const stolenItem = heldItems[pokemon.randSeedInt(heldItems.length)]; + if (globalScene.tryTransferHeldItemModifier(stolenItem, pokemon, false)) { + globalScene.queueMessage( + i18next.t("abilityTriggers:postAttackStealHeldItem", { + pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), + defenderName: defender.name, + stolenItemType: stolenItem.type.name, + }), + ); + return true; } } - resolve(simulated); - }); + } + return false; } getTargetHeldItems(target: Pokemon): PokemonHeldItemModifier[] { @@ -1742,23 +1831,37 @@ export class PostDefendStealHeldItemAbAttr extends PostDefendAbAttr { this.condition = condition; } - override applyPostDefend(pokemon: Pokemon, _passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult, _args: any[]): Promise { - return new Promise(resolve => { - if (!simulated && hitResult < HitResult.NO_EFFECT && (!this.condition || this.condition(pokemon, attacker, move)) && !move.hitsSubstitute(attacker, pokemon)) { - const heldItems = this.getTargetHeldItems(attacker).filter(i => i.isTransferable); - if (heldItems.length) { - const stolenItem = heldItems[pokemon.randSeedInt(heldItems.length)]; - globalScene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => { - if (success) { - globalScene.queueMessage(i18next.t("abilityTriggers:postDefendStealHeldItem", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), attackerName: attacker.name, stolenItemType: stolenItem.type.name })); - } - resolve(success); - }); - return; + override applyPostDefend( + pokemon: Pokemon, + _passive: boolean, + simulated: boolean, + attacker: Pokemon, + move: Move, + hitResult: HitResult, + _args: any[], + ): boolean { + if ( + !simulated && + hitResult < HitResult.NO_EFFECT && + (!this.condition || this.condition(pokemon, attacker, move)) && + !move.hitsSubstitute(attacker, pokemon) + ) { + const heldItems = this.getTargetHeldItems(attacker).filter((i) => i.isTransferable); + if (heldItems.length) { + const stolenItem = heldItems[pokemon.randSeedInt(heldItems.length)]; + if (globalScene.tryTransferHeldItemModifier(stolenItem, pokemon, false)) { + globalScene.queueMessage( + i18next.t("abilityTriggers:postDefendStealHeldItem", { + pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), + attackerName: attacker.name, + stolenItemType: stolenItem.type.name, + }), + ); + return true; } } - resolve(simulated); - }); + } + return false; } getTargetHeldItems(target: Pokemon): PokemonHeldItemModifier[] { @@ -1781,7 +1884,14 @@ export class PostSetStatusAbAttr extends AbAttr { * @param args Set of unique arguments needed by this attribute. * @returns `true` if application of the ability succeeds. */ - applyPostSetStatus(pokemon: Pokemon, sourcePokemon: Pokemon | null = null, passive: boolean, effect: StatusEffect, simulated: boolean, args: any[]) : boolean | Promise { + applyPostSetStatus( + pokemon: Pokemon, + sourcePokemon: Pokemon | null = null, + passive: boolean, + effect: StatusEffect, + simulated: boolean, + args: any[], + ): boolean { return false; } } @@ -1823,7 +1933,7 @@ export class SynchronizeStatusAbAttr extends PostSetStatusAbAttr { } export class PostVictoryAbAttr extends AbAttr { - applyPostVictory(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + applyPostVictory(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { return false; } } @@ -1839,10 +1949,8 @@ class PostVictoryStatStageChangeAbAttr extends PostVictoryAbAttr { this.stages = stages; } - applyPostVictory(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { - const stat = typeof this.stat === "function" - ? this.stat(pokemon) - : this.stat; + applyPostVictory(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { + const stat = typeof this.stat === "function" ? this.stat(pokemon) : this.stat; if (!simulated) { globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], this.stages)); } @@ -1859,7 +1967,7 @@ export class PostVictoryFormChangeAbAttr extends PostVictoryAbAttr { this.formFunc = formFunc; } - applyPostVictory(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + applyPostVictory(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { const formIndex = this.formFunc(pokemon); if (formIndex !== pokemon.formIndex) { if (!simulated) { @@ -1873,7 +1981,7 @@ export class PostVictoryFormChangeAbAttr extends PostVictoryAbAttr { } export class PostKnockOutAbAttr extends AbAttr { - applyPostKnockOut(pokemon: Pokemon, passive: boolean, simulated: boolean, knockedOut: Pokemon, args: any[]): boolean | Promise { + applyPostKnockOut(pokemon: Pokemon, passive: boolean, simulated: boolean, knockedOut: Pokemon, args: any[]): boolean { return false; } } @@ -1889,10 +1997,8 @@ export class PostKnockOutStatStageChangeAbAttr extends PostKnockOutAbAttr { this.stages = stages; } - applyPostKnockOut(pokemon: Pokemon, passive: boolean, simulated: boolean, knockedOut: Pokemon, args: any[]): boolean | Promise { - const stat = typeof this.stat === "function" - ? this.stat(pokemon) - : this.stat; + applyPostKnockOut(pokemon: Pokemon, passive: boolean, simulated: boolean, knockedOut: Pokemon, args: any[]): boolean { + const stat = typeof this.stat === "function" ? this.stat(pokemon) : this.stat; if (!simulated) { globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], this.stages)); } @@ -1905,7 +2011,7 @@ export class CopyFaintedAllyAbilityAbAttr extends PostKnockOutAbAttr { super(); } - applyPostKnockOut(pokemon: Pokemon, passive: boolean, simulated: boolean, knockedOut: Pokemon, args: any[]): boolean | Promise { + applyPostKnockOut(pokemon: Pokemon, passive: boolean, simulated: boolean, knockedOut: Pokemon, args: any[]): boolean { if (pokemon.isPlayer() === knockedOut.isPlayer() && !knockedOut.getAbility().hasAttr(UncopiableAbilityAbAttr)) { if (!simulated) { globalScene.queueMessage(i18next.t("abilityTriggers:copyFaintedAllyAbility", { pokemonNameWithAffix: getPokemonNameWithAffix(knockedOut), abilityName: allAbilities[knockedOut.getAbility().id].name })); @@ -2015,7 +2121,7 @@ export class PostSummonAbAttr extends AbAttr { * @param args Set of unique arguments needed by this attribute * @returns true if application of the ability succeeds */ - applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { return false; } } @@ -2035,7 +2141,7 @@ export class PostSummonRemoveArenaTagAbAttr extends PostSummonAbAttr { this.arenaTags = arenaTags; } - applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + override applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { if (!simulated) { for (const arenaTag of this.arenaTags) { globalScene.arena.removeTag(arenaTag); @@ -2383,9 +2489,9 @@ export class PostSummonUserFieldRemoveStatusEffectAbAttr extends PostSummonAbAtt * @param pokemon - The Pokémon that triggered the ability. * @param passive - n/a * @param args - n/a - * @returns A boolean or a promise that resolves to a boolean indicating the result of the ability application. + * @returns A boolean that resolves to a boolean indicating the result of the ability application. */ - applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + override applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { const party = pokemon instanceof PlayerPokemon ? globalScene.getPlayerField() : globalScene.getEnemyField(); const allowedParty = party.filter(p => p.isAllowedInBattle()); @@ -2445,12 +2551,11 @@ export class PostSummonTransformAbAttr extends PostSummonAbAttr { super(true, false); } - async applyPostSummon(pokemon: Pokemon, _passive: boolean, simulated: boolean, _args: any[]): Promise { + override applyPostSummon(pokemon: Pokemon, _passive: boolean, simulated: boolean, _args: any[]): boolean { const targets = pokemon.getOpponents(); if (simulated || !targets.length) { return simulated; } - const promises: Promise[] = []; let target: Pokemon; if (targets.length > 1) { @@ -2476,41 +2581,14 @@ export class PostSummonTransformAbAttr extends PostSummonAbAttr { return false; } - pokemon.summonData.speciesForm = target.getSpeciesForm(); - pokemon.summonData.gender = target.getGender(); + globalScene.unshiftPhase(new PokemonTransformPhase(pokemon.getBattlerIndex(), target.getBattlerIndex(), true)); - // Copy all stats (except HP) - for (const s of EFFECTIVE_STATS) { - pokemon.setStat(s, target.getStat(s, false), false); - } - - // Copy all stat stages - for (const s of BATTLE_STATS) { - pokemon.setStatStage(s, target.getStatStage(s)); - } - - pokemon.summonData.moveset = target.getMoveset().map((m) => { - if (m) { - // If PP value is less than 5, do nothing. If greater, we need to reduce the value to 5. - return new PokemonMove(m.moveId, 0, 0, false, Math.min(m.getMove().pp, 5)); - } else { - console.warn(`Imposter: somehow iterating over a ${m} value when copying moveset!`); - return new PokemonMove(Moves.NONE); - } - }); - pokemon.summonData.types = target.getTypes(); - promises.push(pokemon.updateInfo()); - - globalScene.queueMessage(i18next.t("abilityTriggers:postSummonTransform", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), targetName: target.name, })); - globalScene.playSound("battle_anims/PRSFX- Transform"); - promises.push(pokemon.loadAssets(false).then(() => { - pokemon.playAnim(); - pokemon.updateInfo(); - // If the new ability activates immediately, it needs to happen after all the transform animations - pokemon.setTempAbility(target.getAbility()); - })); - - await Promise.all(promises); + globalScene.queueMessage( + i18next.t("abilityTriggers:postSummonTransform", { + pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), + targetName: target.name, + }), + ); return true; } @@ -2627,13 +2705,13 @@ export class PreSwitchOutAbAttr extends AbAttr { super(true); } - applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { return false; } } export class PreSwitchOutResetStatusAbAttr extends PreSwitchOutAbAttr { - applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + override applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { if (pokemon.status) { if (!simulated) { pokemon.resetStatus(); @@ -2647,9 +2725,72 @@ export class PreSwitchOutResetStatusAbAttr extends PreSwitchOutAbAttr { } } +/** + * Clears Desolate Land/Primordial Sea/Delta Stream upon the Pokemon switching out. + */ +export class PreSwitchOutClearWeatherAbAttr extends PreSwitchOutAbAttr { + /** + * @param pokemon The {@linkcode Pokemon} with the ability + * @param passive N/A + * @param args N/A + * @returns {boolean} Returns true if the weather clears, otherwise false. + */ + override applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { + const weatherType = globalScene.arena.weather?.weatherType; + let turnOffWeather = false; + + // Clear weather only if user's ability matches the weather and no other pokemon has the ability. + switch (weatherType) { + case WeatherType.HARSH_SUN: + if ( + pokemon.hasAbility(Abilities.DESOLATE_LAND) && + globalScene + .getField(true) + .filter((p) => p !== pokemon) + .filter((p) => p.hasAbility(Abilities.DESOLATE_LAND)).length === 0 + ) { + turnOffWeather = true; + } + break; + case WeatherType.HEAVY_RAIN: + if ( + pokemon.hasAbility(Abilities.PRIMORDIAL_SEA) && + globalScene + .getField(true) + .filter((p) => p !== pokemon) + .filter((p) => p.hasAbility(Abilities.PRIMORDIAL_SEA)).length === 0 + ) { + turnOffWeather = true; + } + break; + case WeatherType.STRONG_WINDS: + if ( + pokemon.hasAbility(Abilities.DELTA_STREAM) && + globalScene + .getField(true) + .filter((p) => p !== pokemon) + .filter((p) => p.hasAbility(Abilities.DELTA_STREAM)).length === 0 + ) { + turnOffWeather = true; + } + break; + } + + if (simulated) { + return turnOffWeather; + } + + if (turnOffWeather) { + globalScene.arena.trySetWeather(WeatherType.NONE, false); + return true; + } + + return false; + } +} export class PreSwitchOutHealAbAttr extends PreSwitchOutAbAttr { - applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + override applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { if (!pokemon.isFullHp()) { if (!simulated) { const healAmount = Utils.toDmgValue(pokemon.getMaxHp() * 0.33); @@ -2685,7 +2826,7 @@ export class PreSwitchOutFormChangeAbAttr extends PreSwitchOutAbAttr { * @param args N/A * @returns true if the form change was successful */ - applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + override applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { const formIndex = this.formFunc(pokemon); if (formIndex !== pokemon.formIndex) { if (!simulated) { @@ -2700,7 +2841,7 @@ export class PreSwitchOutFormChangeAbAttr extends PreSwitchOutAbAttr { } export class PreLeaveFieldAbAttr extends AbAttr { - applyPreLeaveField(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + applyPreLeaveField(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { return false; } } @@ -2715,7 +2856,7 @@ export class PreLeaveFieldClearWeatherAbAttr extends PreLeaveFieldAbAttr { * @param args N/A * @returns Returns `true` if the weather clears, otherwise `false`. */ - applyPreLeaveField(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + applyPreLeaveField(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { const weatherType = globalScene.arena.weather?.weatherType; let turnOffWeather = false; @@ -2755,7 +2896,14 @@ export class PreLeaveFieldClearWeatherAbAttr extends PreLeaveFieldAbAttr { } export class PreStatStageChangeAbAttr extends AbAttr { - applyPreStatStageChange(pokemon: Pokemon | null, passive: boolean, simulated: boolean, stat: BattleStat, cancelled: Utils.BooleanHolder, args: any[]): boolean | Promise { + applyPreStatStageChange( + pokemon: Pokemon | null, + passive: boolean, + simulated: boolean, + stat: BattleStat, + cancelled: Utils.BooleanHolder, + args: any[], + ): boolean { return false; } } @@ -2878,7 +3026,14 @@ export class ConfusionOnStatusEffectAbAttr extends PostAttackAbAttr { } export class PreSetStatusAbAttr extends AbAttr { - applyPreSetStatus(pokemon: Pokemon, passive: boolean, simulated: boolean, effect: StatusEffect | undefined, cancelled: Utils.BooleanHolder, args: any[]): boolean | Promise { + applyPreSetStatus( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + effect: StatusEffect | undefined, + cancelled: Utils.BooleanHolder, + args: any[], + ): boolean { return false; } } @@ -2944,7 +3099,14 @@ export class StatusEffectImmunityAbAttr extends PreSetStatusEffectImmunityAbAttr export class UserFieldStatusEffectImmunityAbAttr extends PreSetStatusEffectImmunityAbAttr { } export class PreApplyBattlerTagAbAttr extends AbAttr { - applyPreApplyBattlerTag(pokemon: Pokemon, passive: boolean, simulated: boolean, tag: BattlerTag, cancelled: Utils.BooleanHolder, args: any[]): boolean | Promise { + applyPreApplyBattlerTag( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + tag: BattlerTag, + cancelled: Utils.BooleanHolder, + args: any[], + ): boolean { return false; } } @@ -3139,7 +3301,14 @@ export class ChangeMovePriorityAbAttr extends AbAttr { export class IgnoreContactAbAttr extends AbAttr { } export class PreWeatherEffectAbAttr extends AbAttr { - applyPreWeatherEffect(pokemon: Pokemon, passive: Boolean, simulated: boolean, weather: Weather | null, cancelled: Utils.BooleanHolder, args: any[]): boolean | Promise { + applyPreWeatherEffect( + pokemon: Pokemon, + passive: Boolean, + simulated: boolean, + weather: Weather | null, + cancelled: Utils.BooleanHolder, + args: any[], + ): boolean { return false; } } @@ -3420,7 +3589,13 @@ export class PostWeatherLapseAbAttr extends AbAttr { this.weatherTypes = weatherTypes; } - applyPostWeatherLapse(pokemon: Pokemon, passive: boolean, simulated: boolean, weather: Weather | null, args: any[]): boolean | Promise { + applyPostWeatherLapse( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + weather: Weather | null, + args: any[], + ): boolean { return false; } @@ -3516,7 +3691,7 @@ function getTerrainCondition(...terrainTypes: TerrainType[]): AbAttrCondition { } export class PostTurnAbAttr extends AbAttr { - applyPostTurn(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + applyPostTurn(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { return false; } } @@ -3542,7 +3717,7 @@ export class PostTurnStatusHealAbAttr extends PostTurnAbAttr { * @param {any[]} args N/A * @returns Returns true if healed from status, false if not */ - applyPostTurn(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + override applyPostTurn(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { if (pokemon.status && this.effects.includes(pokemon.status.effect)) { if (!pokemon.isFullHp()) { if (!simulated) { @@ -3776,7 +3951,7 @@ export class PostTurnHurtIfSleepingAbAttr extends PostTurnAbAttr { * @param args N/A * @returns `true` if any opponents are sleeping */ - applyPostTurn(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + override applyPostTurn(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { let hadEffect: boolean = false; for (const opp of pokemon.getOpponents()) { if ((opp.status?.effect === StatusEffect.SLEEP || opp.hasAbility(Abilities.COMATOSE)) && !opp.hasAbilityWithAttr(BlockNonDirectDamageAbAttr) && !opp.switchOutStatus) { @@ -3870,7 +4045,14 @@ export class PostBiomeChangeTerrainChangeAbAttr extends PostBiomeChangeAbAttr { * @extends AbAttr */ export class PostMoveUsedAbAttr extends AbAttr { - applyPostMoveUsed(pokemon: Pokemon, move: PokemonMove, source: Pokemon, targets: BattlerIndex[], simulated: boolean, args: any[]): boolean | Promise { + applyPostMoveUsed( + pokemon: Pokemon, + move: PokemonMove, + source: Pokemon, + targets: BattlerIndex[], + simulated: boolean, + args: any[], + ): boolean { return false; } } @@ -3891,7 +4073,14 @@ export class PostDancingMoveAbAttr extends PostMoveUsedAbAttr { * * @return true if the Dancer ability was resolved */ - applyPostMoveUsed(dancer: Pokemon, move: PokemonMove, source: Pokemon, targets: BattlerIndex[], simulated: boolean, args: any[]): boolean | Promise { + override applyPostMoveUsed( + dancer: Pokemon, + move: PokemonMove, + source: Pokemon, + targets: BattlerIndex[], + simulated: boolean, + args: any[], + ): boolean { // List of tags that prevent the Dancer from replicating the move const forbiddenTags = [ BattlerTagType.FLYING, BattlerTagType.UNDERWATER, BattlerTagType.UNDERGROUND, BattlerTagType.HIDDEN ]; @@ -3933,7 +4122,7 @@ export class PostDancingMoveAbAttr extends PostMoveUsedAbAttr { * @extends AbAttr */ export class PostItemLostAbAttr extends AbAttr { - applyPostItemLost(pokemon: Pokemon, simulated: boolean, args: any[]): boolean | Promise { + applyPostItemLost(pokemon: Pokemon, simulated: boolean, args: any[]): boolean { return false; } } @@ -3954,7 +4143,7 @@ export class PostItemLostApplyBattlerTagAbAttr extends PostItemLostAbAttr { * @param args N/A * @returns true if BattlerTag was applied */ - applyPostItemLost(pokemon: Pokemon, simulated: boolean, args: any[]): boolean | Promise { + override applyPostItemLost(pokemon: Pokemon, simulated: boolean, args: any[]): boolean { if (!pokemon.getTag(this.tagType) && !simulated) { pokemon.addTag(this.tagType); return true; @@ -3980,7 +4169,13 @@ export class StatStageChangeMultiplierAbAttr extends AbAttr { } export class StatStageChangeCopyAbAttr extends AbAttr { - apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean | Promise { + override apply( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + cancelled: Utils.BooleanHolder, + args: any[], + ): boolean { if (!simulated) { globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, (args[0] as BattleStat[]), (args[1] as number), true, false, false)); } @@ -4096,7 +4291,14 @@ export class CheckTrappedAbAttr extends AbAttr { this.arenaTrapCondition = condition; } - applyCheckTrapped(pokemon: Pokemon, passive: boolean, simulated: boolean, trapped: Utils.BooleanHolder, otherPokemon: Pokemon, args: any[]): boolean | Promise { + applyCheckTrapped( + pokemon: Pokemon, + passive: boolean, + simulated: boolean, + trapped: Utils.BooleanHolder, + otherPokemon: Pokemon, + args: any[], + ): boolean { return false; } } @@ -4170,7 +4372,7 @@ export class PostBattleLootAbAttr extends PostBattleAbAttr { if (!simulated && postBattleLoot.length && args[0]) { const randItem = Utils.randSeedItem(postBattleLoot); //@ts-ignore - TODO see below - if (globalScene.tryTransferHeldItemModifier(randItem, pokemon, true, 1, true, undefined, false)) { // TODO: fix. This is a promise!? + if (globalScene.tryTransferHeldItemModifier(randItem, pokemon, true, 1, true, undefined, false)) { postBattleLoot.splice(postBattleLoot.indexOf(randItem), 1); globalScene.queueMessage(i18next.t("abilityTriggers:postBattleLoot", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), itemName: randItem.type.name })); return true; @@ -4841,7 +5043,7 @@ export class TerrainEventTypeChangeAbAttr extends PostSummonAbAttr { * Checks if the Pokemon should change types if summoned into an active terrain * @returns `true` if there is an active terrain requiring a type change | `false` if not */ - override applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise { + override applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { if (globalScene.arena.getTerrainType() !== TerrainType.NONE) { return this.apply(pokemon, passive, simulated, new Utils.BooleanHolder(false), []); } @@ -4860,27 +5062,7 @@ export class TerrainEventTypeChangeAbAttr extends PostSummonAbAttr { } } -async function applyAbAttrsInternal( - attrType: Constructor, - pokemon: Pokemon | null, - applyFunc: AbAttrApplyFunc, - args: any[], - showAbilityInstant: boolean = false, - simulated: boolean = false, - messages: string[] = [], - gainedMidTurn: boolean = false -) { - for (const passive of [ false, true ]) { - if (!pokemon?.canApplyAbility(passive) || (passive && (pokemon.getPassiveAbility().id === pokemon.getAbility().id))) { - continue; - } - - applySingleAbAttrs(pokemon, passive, attrType, applyFunc, args, gainedMidTurn, simulated, showAbilityInstant, messages); - globalScene.clearPhaseQueueSplice(); - } -} - -async function applySingleAbAttrs( +function applySingleAbAttrs( pokemon: Pokemon, passive: boolean, attrType: Constructor, @@ -4903,13 +5085,7 @@ async function applySingleAbAttrs( } globalScene.setPhaseQueueSplice(); - - let result = applyFunc(attr, passive); - // TODO Remove this when promises get reworked - if (result instanceof Promise) { - result = await result; - } - if (result) { + if (applyFunc(attr, passive)) { if (pokemon.summonData && !pokemon.summonData.abilitiesApplied.includes(ability.id)) { pokemon.summonData.abilitiesApplied.push(ability.id); } @@ -5074,7 +5250,14 @@ function calculateShellBellRecovery(pokemon: Pokemon): number { * @extends AbAttr */ export class PostDamageAbAttr extends AbAttr { - public applyPostDamage(pokemon: Pokemon, damage: number, passive: boolean, simulated: boolean, args: any[], source?: Pokemon): boolean | Promise { + public applyPostDamage( + pokemon: Pokemon, + damage: number, + passive: boolean, + simulated: boolean, + args: any[], + source?: Pokemon, + ): boolean { return false; } } @@ -5111,7 +5294,14 @@ export class PostDamageForceSwitchAbAttr extends PostDamageAbAttr { * @param source The Pokemon that dealt damage * @returns `true` if the switch-out logic was successfully applied */ - public override applyPostDamage(pokemon: Pokemon, damage: number, passive: boolean, simulated: boolean, args: any[], source?: Pokemon): boolean | Promise { + public override applyPostDamage( + pokemon: Pokemon, + damage: number, + passive: boolean, + simulated: boolean, + args: any[], + source?: Pokemon, + ): boolean { const moveHistory = pokemon.getMoveHistory(); // Will not activate when the Pokémon's HP is lowered by cutting its own HP const fordbiddenAttackingMoves = [ Moves.BELLY_DRUM, Moves.SUBSTITUTE, Moves.CURSE, Moves.PAIN_SPLIT ]; @@ -5165,44 +5355,164 @@ export class PostDamageForceSwitchAbAttr extends PostDamageAbAttr { return this.helper.getFailedText(target); } } +function applyAbAttrsInternal( + attrType: Constructor, + pokemon: Pokemon | null, + applyFunc: AbAttrApplyFunc, + args: any[], + showAbilityInstant: boolean = false, + simulated: boolean = false, + messages: string[] = [], + gainedMidTurn: boolean = false +) { + for (const passive of [ false, true ]) { + if (!pokemon?.canApplyAbility(passive) || (passive && (pokemon.getPassiveAbility().id === pokemon.getAbility().id))) { + continue; + } - -export function applyAbAttrs(attrType: Constructor, pokemon: Pokemon, cancelled: Utils.BooleanHolder | null, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.apply(pokemon, passive, simulated, cancelled, args), args, false, simulated); + applySingleAbAttrs(pokemon, passive, attrType, applyFunc, args, gainedMidTurn, simulated, showAbilityInstant, messages); + globalScene.clearPhaseQueueSplice(); + } } -export function applyPostBattleInitAbAttrs(attrType: Constructor, - pokemon: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostBattleInit(pokemon, passive, simulated, args), args, false, simulated); +export function applyAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + cancelled: Utils.BooleanHolder | null, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.apply(pokemon, passive, simulated, cancelled, args), + args, + false, + simulated, + ); } -export function applyPreDefendAbAttrs(attrType: Constructor, - pokemon: Pokemon, attacker: Pokemon, move: Move | null, cancelled: Utils.BooleanHolder | null, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPreDefend(pokemon, passive, simulated, attacker, move, cancelled, args), args, false, simulated); +export function applyPostBattleInitAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostBattleInit(pokemon, passive, simulated, args), + args, + false, + simulated, + ); } -export function applyPostDefendAbAttrs(attrType: Constructor, - pokemon: Pokemon, attacker: Pokemon, move: Move, hitResult: HitResult | null, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostDefend(pokemon, passive, simulated, attacker, move, hitResult, args), args, false, simulated); +export function applyPreDefendAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + attacker: Pokemon, + move: Move | null, + cancelled: Utils.BooleanHolder | null, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPreDefend(pokemon, passive, simulated, attacker, move, cancelled, args), + args, + false, + simulated, + ); } -export function applyPostMoveUsedAbAttrs(attrType: Constructor, - pokemon: Pokemon, move: PokemonMove, source: Pokemon, targets: BattlerIndex[], simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostMoveUsed(pokemon, move, source, targets, simulated, args), args, false, simulated); +export function applyPostDefendAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + attacker: Pokemon, + move: Move, + hitResult: HitResult | null, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostDefend(pokemon, passive, simulated, attacker, move, hitResult, args), + args, + false, + simulated, + ); } -export function applyStatMultiplierAbAttrs(attrType: Constructor, - pokemon: Pokemon, stat: BattleStat, statValue: Utils.NumberHolder, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyStatStage(pokemon, passive, simulated, stat, statValue, args), args); -} -export function applyPostSetStatusAbAttrs(attrType: Constructor, - pokemon: Pokemon, effect: StatusEffect, sourcePokemon?: Pokemon | null, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostSetStatus(pokemon, sourcePokemon, passive, effect, simulated, args), args, false, simulated); +export function applyPostMoveUsedAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + move: PokemonMove, + source: Pokemon, + targets: BattlerIndex[], + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostMoveUsed(pokemon, move, source, targets, simulated, args), + args, + false, + simulated, + ); } -export function applyPostDamageAbAttrs(attrType: Constructor, - pokemon: Pokemon, damage: number, passive: boolean, simulated: boolean = false, args: any[], source?: Pokemon): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostDamage(pokemon, damage, passive, simulated, args, source), args); +export function applyStatMultiplierAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + stat: BattleStat, + statValue: Utils.NumberHolder, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyStatStage(pokemon, passive, simulated, stat, statValue, args), + args, + ); +} +export function applyPostSetStatusAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + effect: StatusEffect, + sourcePokemon?: Pokemon | null, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostSetStatus(pokemon, sourcePokemon, passive, effect, simulated, args), + args, + false, + simulated, + ); +} + +export function applyPostDamageAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + damage: number, + passive: boolean, + simulated: boolean = false, + args: any[], + source?: Pokemon, +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostDamage(pokemon, damage, passive, simulated, args, source), + args, + ); } /** @@ -5215,109 +5525,369 @@ export function applyPostDamageAbAttrs(attrType: Constructor, * @param hasApplied {@linkcode Utils.BooleanHolder} whether or not a FieldMultiplyBattleStatAbAttr has already affected this stat * @param args unused */ -export function applyFieldStatMultiplierAbAttrs(attrType: Constructor, - pokemon: Pokemon, stat: Stat, statValue: Utils.NumberHolder, checkedPokemon: Pokemon, hasApplied: Utils.BooleanHolder, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyFieldStat(pokemon, passive, simulated, stat, statValue, checkedPokemon, hasApplied, args), args); +export function applyFieldStatMultiplierAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + stat: Stat, + statValue: Utils.NumberHolder, + checkedPokemon: Pokemon, + hasApplied: Utils.BooleanHolder, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => + attr.applyFieldStat(pokemon, passive, simulated, stat, statValue, checkedPokemon, hasApplied, args), + args, + ); } -export function applyPreAttackAbAttrs(attrType: Constructor, - pokemon: Pokemon, defender: Pokemon | null, move: Move, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPreAttack(pokemon, passive, simulated, defender, move, args), args, false, simulated); +export function applyPreAttackAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + defender: Pokemon | null, + move: Move, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPreAttack(pokemon, passive, simulated, defender, move, args), + args, + false, + simulated, + ); } -export function applyPostAttackAbAttrs(attrType: Constructor, - pokemon: Pokemon, defender: Pokemon, move: Move, hitResult: HitResult | null, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostAttack(pokemon, passive, simulated, defender, move, hitResult, args), args, false, simulated); +export function applyPostAttackAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + defender: Pokemon, + move: Move, + hitResult: HitResult | null, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostAttack(pokemon, passive, simulated, defender, move, hitResult, args), + args, + false, + simulated, + ); } -export function applyPostKnockOutAbAttrs(attrType: Constructor, - pokemon: Pokemon, knockedOut: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostKnockOut(pokemon, passive, simulated, knockedOut, args), args, false, simulated); +export function applyPostKnockOutAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + knockedOut: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostKnockOut(pokemon, passive, simulated, knockedOut, args), + args, + false, + simulated, + ); } -export function applyPostVictoryAbAttrs(attrType: Constructor, - pokemon: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostVictory(pokemon, passive, simulated, args), args, false, simulated); +export function applyPostVictoryAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostVictory(pokemon, passive, simulated, args), + args, + false, + simulated, + ); } -export function applyPostSummonAbAttrs(attrType: Constructor, - pokemon: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostSummon(pokemon, passive, simulated, args), args, false, simulated); +export function applyPostSummonAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostSummon(pokemon, passive, simulated, args), + args, + false, + simulated, + ); } -export function applyPreSwitchOutAbAttrs(attrType: Constructor, - pokemon: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPreSwitchOut(pokemon, passive, simulated, args), args, true, simulated); +export function applyPreSwitchOutAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPreSwitchOut(pokemon, passive, simulated, args), + args, + true, + simulated, + ); } -export function applyPreLeaveFieldAbAttrs(attrType: Constructor, - pokemon: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPreLeaveField(pokemon, passive, simulated, args), args, true, simulated); +export function applyPreLeaveFieldAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + return applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => + attr.applyPreLeaveField(pokemon, passive, simulated, args), + args, + true, + simulated + ); } -export function applyPreStatStageChangeAbAttrs(attrType: Constructor, - pokemon: Pokemon | null, stat: BattleStat, cancelled: Utils.BooleanHolder, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPreStatStageChange(pokemon, passive, simulated, stat, cancelled, args), args, false, simulated); +export function applyPreStatStageChangeAbAttrs( + attrType: Constructor, + pokemon: Pokemon | null, + stat: BattleStat, + cancelled: Utils.BooleanHolder, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPreStatStageChange(pokemon, passive, simulated, stat, cancelled, args), + args, + false, + simulated, + ); } -export function applyPostStatStageChangeAbAttrs(attrType: Constructor, - pokemon: Pokemon, stats: BattleStat[], stages: number, selfTarget: boolean, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, _passive) => attr.applyPostStatStageChange(pokemon, simulated, stats, stages, selfTarget, args), args, false, simulated); +export function applyPostStatStageChangeAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + stats: BattleStat[], + stages: integer, + selfTarget: boolean, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, _passive) => attr.applyPostStatStageChange(pokemon, simulated, stats, stages, selfTarget, args), + args, + false, + simulated, + ); } -export function applyPreSetStatusAbAttrs(attrType: Constructor, - pokemon: Pokemon, effect: StatusEffect | undefined, cancelled: Utils.BooleanHolder, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPreSetStatus(pokemon, passive, simulated, effect, cancelled, args), args, false, simulated); +export function applyPreSetStatusAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + effect: StatusEffect | undefined, + cancelled: Utils.BooleanHolder, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPreSetStatus(pokemon, passive, simulated, effect, cancelled, args), + args, + false, + simulated, + ); } -export function applyPreApplyBattlerTagAbAttrs(attrType: Constructor, - pokemon: Pokemon, tag: BattlerTag, cancelled: Utils.BooleanHolder, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPreApplyBattlerTag(pokemon, passive, simulated, tag, cancelled, args), args, false, simulated); +export function applyPreApplyBattlerTagAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + tag: BattlerTag, + cancelled: Utils.BooleanHolder, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPreApplyBattlerTag(pokemon, passive, simulated, tag, cancelled, args), + args, + false, + simulated, + ); } -export function applyPreWeatherEffectAbAttrs(attrType: Constructor, - pokemon: Pokemon, weather: Weather | null, cancelled: Utils.BooleanHolder, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPreWeatherEffect(pokemon, passive, simulated, weather, cancelled, args), args, true, simulated); +export function applyPreWeatherEffectAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + weather: Weather | null, + cancelled: Utils.BooleanHolder, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPreWeatherEffect(pokemon, passive, simulated, weather, cancelled, args), + args, + true, + simulated, + ); } -export function applyPostTurnAbAttrs(attrType: Constructor, - pokemon: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostTurn(pokemon, passive, simulated, args), args, false, simulated); +export function applyPostTurnAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostTurn(pokemon, passive, simulated, args), + args, + false, + simulated, + ); } -export function applyPostWeatherChangeAbAttrs(attrType: Constructor, - pokemon: Pokemon, weather: WeatherType, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostWeatherChange(pokemon, passive, simulated, weather, args), args, false, simulated); +export function applyPostWeatherChangeAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + weather: WeatherType, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostWeatherChange(pokemon, passive, simulated, weather, args), + args, + false, + simulated, + ); } -export function applyPostWeatherLapseAbAttrs(attrType: Constructor, - pokemon: Pokemon, weather: Weather | null, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostWeatherLapse(pokemon, passive, simulated, weather, args), args, false, simulated); +export function applyPostWeatherLapseAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + weather: Weather | null, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostWeatherLapse(pokemon, passive, simulated, weather, args), + args, + false, + simulated, + ); } -export function applyPostTerrainChangeAbAttrs(attrType: Constructor, - pokemon: Pokemon, terrain: TerrainType, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostTerrainChange(pokemon, passive, simulated, terrain, args), args, false, simulated); +export function applyPostTerrainChangeAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + terrain: TerrainType, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostTerrainChange(pokemon, passive, simulated, terrain, args), + args, + false, + simulated, + ); } -export function applyCheckTrappedAbAttrs(attrType: Constructor, - pokemon: Pokemon, trapped: Utils.BooleanHolder, otherPokemon: Pokemon, messages: string[], simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyCheckTrapped(pokemon, passive, simulated, trapped, otherPokemon, args), args, false, simulated, messages); +export function applyCheckTrappedAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + trapped: Utils.BooleanHolder, + otherPokemon: Pokemon, + messages: string[], + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyCheckTrapped(pokemon, passive, simulated, trapped, otherPokemon, args), + args, + false, + simulated, + messages, + ); } -export function applyPostBattleAbAttrs(attrType: Constructor, - pokemon: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostBattle(pokemon, passive, simulated, args), args, false, simulated); +export function applyPostBattleAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostBattle(pokemon, passive, simulated, args), + args, + false, + simulated, + ); } -export function applyPostFaintAbAttrs(attrType: Constructor, - pokemon: Pokemon, attacker?: Pokemon, move?: Move, hitResult?: HitResult, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostFaint(pokemon, passive, simulated, attacker, move, hitResult, args), args, false, simulated); +export function applyPostFaintAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + attacker?: Pokemon, + move?: Move, + hitResult?: HitResult, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostFaint(pokemon, passive, simulated, attacker, move, hitResult, args), + args, + false, + simulated, + ); } -export function applyPostItemLostAbAttrs(attrType: Constructor, - pokemon: Pokemon, simulated: boolean = false, ...args: any[]): Promise { - return applyAbAttrsInternal(attrType, pokemon, (attr, passive) => attr.applyPostItemLost(pokemon, simulated, args), args); +export function applyPostItemLostAbAttrs( + attrType: Constructor, + pokemon: Pokemon, + simulated: boolean = false, + ...args: any[] +): void { + applyAbAttrsInternal( + attrType, + pokemon, + (attr, passive) => attr.applyPostItemLost(pokemon, simulated, args), + args, + ); } /** diff --git a/src/data/move.ts b/src/data/move.ts index acc68eb6a26..658534eb48f 100644 --- a/src/data/move.ts +++ b/src/data/move.ts @@ -1,5 +1,16 @@ -import { ChargeAnim, initMoveAnim, loadMoveAnimAssets, MoveChargeAnim } from "./battle-anims"; -import { CommandedTag, EncoreTag, GulpMissileTag, HelpingHandTag, SemiInvulnerableTag, ShellTrapTag, StockpilingTag, SubstituteTag, TrappedTag, TypeBoostTag } from "./battler-tags"; +import { ChargeAnim, MoveChargeAnim } from "./battle-anims"; +import { + CommandedTag, + EncoreTag, + GulpMissileTag, + HelpingHandTag, + SemiInvulnerableTag, + ShellTrapTag, + StockpilingTag, + SubstituteTag, + TrappedTag, + TypeBoostTag, +} from "./battler-tags"; import { getPokemonNameWithAffix } from "../messages"; import type { AttackMoveResult, TurnMove } from "../field/pokemon"; import type Pokemon from "../field/pokemon"; @@ -30,7 +41,7 @@ import { Biome } from "#enums/biome"; import { Moves } from "#enums/moves"; import { Species } from "#enums/species"; import { MoveUsedEvent } from "#app/events/battle-scene"; -import { BATTLE_STATS, type BattleStat, EFFECTIVE_STATS, type EffectiveStat, getStatKey, Stat } from "#app/enums/stat"; +import { BATTLE_STATS, type BattleStat, type EffectiveStat, getStatKey, Stat } from "#app/enums/stat"; import { BattleEndPhase } from "#app/phases/battle-end-phase"; import { MoveEndPhase } from "#app/phases/move-end-phase"; import { MovePhase } from "#app/phases/move-phase"; @@ -46,6 +57,10 @@ import { applyChallenges, ChallengeType } from "./challenge"; import { SwitchType } from "#enums/switch-type"; import { StatusEffect } from "#enums/status-effect"; import { globalScene } from "#app/global-scene"; +import { RevivalBlessingPhase } from "#app/phases/revival-blessing-phase"; +import { LoadMoveAnimPhase } from "#app/phases/load-move-anim-phase"; +import { PokemonTransformPhase } from "#app/phases/pokemon-transform-phase"; +import { MoveAnimPhase } from "#app/phases/move-anim-phase"; export enum MoveCategory { PHYSICAL, @@ -1057,7 +1072,7 @@ export abstract class MoveAttr { * @param args Set of unique arguments needed by this attribute * @returns true if application of the ability succeeds */ - apply(user: Pokemon | null, target: Pokemon | null, move: Move, args: any[]): boolean | Promise { + apply(user: Pokemon | null, target: Pokemon | null, move: Move, args: any[]): boolean { return true; } @@ -1200,7 +1215,7 @@ export class MoveEffectAttr extends MoveAttr { } /** Applies move effects so long as they are able based on {@linkcode canApply} */ - apply(user: Pokemon, target: Pokemon, move: Move, args?: any[]): boolean | Promise { + apply(user: Pokemon, target: Pokemon, move: Move, args?: any[]): boolean { return this.canApply(user, target, move, args); } @@ -1866,7 +1881,7 @@ export class FlameBurstAttr extends MoveEffectAttr { * @param args - n/a * @returns A boolean indicating whether the effect was successfully applied. */ - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean | Promise { + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { const targetAlly = target.getAlly(); const cancelled = new Utils.BooleanHolder(false); @@ -2406,32 +2421,27 @@ export class StealHeldItemChanceAttr extends MoveEffectAttr { this.chance = chance; } - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { - return new Promise(resolve => { - if (move.hitsSubstitute(user, target)) { - return resolve(false); - } - const rand = Phaser.Math.RND.realInRange(0, 1); - if (rand >= this.chance) { - return resolve(false); - } - const heldItems = this.getTargetHeldItems(target).filter(i => i.isTransferable); - if (heldItems.length) { - const poolType = target.isPlayer() ? ModifierPoolType.PLAYER : target.hasTrainer() ? ModifierPoolType.TRAINER : ModifierPoolType.WILD; - const highestItemTier = heldItems.map(m => m.type.getOrInferTier(poolType)).reduce((highestTier, tier) => Math.max(tier!, highestTier), 0); // TODO: is the bang after tier correct? - const tierHeldItems = heldItems.filter(m => m.type.getOrInferTier(poolType) === highestItemTier); - const stolenItem = tierHeldItems[user.randSeedInt(tierHeldItems.length)]; - globalScene.tryTransferHeldItemModifier(stolenItem, user, false).then(success => { - if (success) { - globalScene.queueMessage(i18next.t("moveTriggers:stoleItem", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), itemName: stolenItem.type.name })); - } - resolve(success); - }); - return; - } + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + if (move.hitsSubstitute(user, target)) { + return false; + } - resolve(false); - }); + const rand = Phaser.Math.RND.realInRange(0, 1); + if (rand >= this.chance) { + return false; + } + const heldItems = this.getTargetHeldItems(target).filter((i) => i.isTransferable); + if (heldItems.length) { + const poolType = target.isPlayer() ? ModifierPoolType.PLAYER : target.hasTrainer() ? ModifierPoolType.TRAINER : ModifierPoolType.WILD; + const highestItemTier = heldItems.map((m) => m.type.getOrInferTier(poolType)).reduce((highestTier, tier) => Math.max(tier!, highestTier), 0); // TODO: is the bang after tier correct? + const tierHeldItems = heldItems.filter((m) => m.type.getOrInferTier(poolType) === highestItemTier); + const stolenItem = tierHeldItems[user.randSeedInt(tierHeldItems.length)]; + if (globalScene.tryTransferHeldItemModifier(stolenItem, user, false)) { + globalScene.queueMessage(i18next.t("moveTriggers:stoleItem", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), itemName: stolenItem.type.name })); + return true; + } + } + return false; } getTargetHeldItems(target: Pokemon): PokemonHeldItemModifier[] { @@ -2875,9 +2885,7 @@ export class WeatherInstantChargeAttr extends InstantChargeAttr { } export class OverrideMoveEffectAttr extends MoveAttr { - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean | Promise { - //const overridden = args[0] as Utils.BooleanHolder; - //const virtual = arg[1] as boolean; + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { return true; } } @@ -2903,26 +2911,27 @@ export class DelayedAttackAttr extends OverrideMoveEffectAttr { this.chargeText = chargeText; } - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { // Edge case for the move applied on a pokemon that has fainted if (!target) { - return Promise.resolve(true); + return true; } - const side = target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - return new Promise(resolve => { - if (args.length < 2 || !args[1]) { - new MoveChargeAnim(this.chargeAnim, move.id, user).play(false, () => { - (args[0] as Utils.BooleanHolder).value = true; - globalScene.queueMessage(this.chargeText.replace("{TARGET}", getPokemonNameWithAffix(target)).replace("{USER}", getPokemonNameWithAffix(user))); - user.pushMoveHistory({ move: move.id, targets: [ target.getBattlerIndex() ], result: MoveResult.OTHER }); - globalScene.arena.addTag(this.tagType, 3, move.id, user.id, side, false, target.getBattlerIndex()); - resolve(true); - }); - } else { - globalScene.ui.showText(i18next.t("moveTriggers:tookMoveAttack", { pokemonName: getPokemonNameWithAffix(globalScene.getPokemonById(target.id) ?? undefined), moveName: move.name }), null, () => resolve(true)); - } - }); + const overridden = args[0] as Utils.BooleanHolder; + const virtual = args[1] as boolean; + + if (!virtual) { + overridden.value = true; + globalScene.unshiftPhase(new MoveAnimPhase(new MoveChargeAnim(this.chargeAnim, move.id, user))); + globalScene.queueMessage(this.chargeText.replace("{TARGET}", getPokemonNameWithAffix(target)).replace("{USER}", getPokemonNameWithAffix(user))); + user.pushMoveHistory({ move: move.id, targets: [ target.getBattlerIndex() ], result: MoveResult.OTHER }); + const side = target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; + globalScene.arena.addTag(this.tagType, 3, move.id, user.id, side, false, target.getBattlerIndex()); + } else { + globalScene.queueMessage(i18next.t("moveTriggers:tookMoveAttack", { pokemonName: getPokemonNameWithAffix(globalScene.getPokemonById(target.id) ?? undefined), moveName: move.name })); + } + + return true; } } @@ -3053,7 +3062,7 @@ export class StatStageChangeAttr extends MoveEffectAttr { * @param args unused * @returns whether stat stages were changed */ - apply(user: Pokemon, target: Pokemon, move: Move, args?: any[]): boolean | Promise { + apply(user: Pokemon, target: Pokemon, move: Move, args?: any[]): boolean { if (!super.apply(user, target, move, args) || (this.condition && !this.condition(user, target, move))) { return false; } @@ -3131,7 +3140,7 @@ export class SecretPowerAttr extends MoveEffectAttr { * Used to apply the secondary effect to the target Pokemon * @returns `true` if a secondary effect is successfully applied */ - override apply(user: Pokemon, target: Pokemon, move: Move, args?: any[]): boolean | Promise { + override apply(user: Pokemon, target: Pokemon, move: Move, args?: any[]): boolean { if (!super.apply(user, target, move, args)) { return false; } @@ -3286,8 +3295,8 @@ export class AcupressureStatStageChangeAttr extends MoveEffectAttr { super(); } - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean | Promise { - const randStats = BATTLE_STATS.filter(s => target.getStatStage(s) < 6); + override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + const randStats = BATTLE_STATS.filter((s) => target.getStatStage(s) < 6); if (randStats.length > 0) { const boostStat = [ randStats[user.randSeedInt(randStats.length)] ]; globalScene.unshiftPhase(new StatStageChangePhase(target.getBattlerIndex(), this.selfTarget, boostStat, 2)); @@ -3324,17 +3333,14 @@ export class CutHpStatStageBoostAttr extends StatStageChangeAttr { this.messageCallback = messageCallback; } - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { - return new Promise(resolve => { - user.damageAndUpdate(Utils.toDmgValue(user.getMaxHp() / this.cutRatio), HitResult.OTHER, false, true); - user.updateInfo().then(() => { - const ret = super.apply(user, target, move, args); - if (this.messageCallback) { - this.messageCallback(user); - } - resolve(ret); - }); - }); + override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + user.damageAndUpdate(Utils.toDmgValue(user.getMaxHp() / this.cutRatio), HitResult.OTHER, false, true); + user.updateInfo(); + const ret = super.apply(user, target, move, args); + if (this.messageCallback) { + this.messageCallback(user); + } + return ret; } getCondition(): MoveConditionFunc { @@ -3426,28 +3432,27 @@ export class ResetStatsAttr extends MoveEffectAttr { super(); this.targetAllPokemon = targetAllPokemon; } - async apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { - const promises: Promise[] = []; - if (this.targetAllPokemon) { // Target all pokemon on the field when Freezy Frost or Haze are used + + override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + if (this.targetAllPokemon) { + // Target all pokemon on the field when Freezy Frost or Haze are used const activePokemon = globalScene.getField(true); - activePokemon.forEach(p => promises.push(this.resetStats(p))); + activePokemon.forEach((p) => this.resetStats(p)); globalScene.queueMessage(i18next.t("moveTriggers:statEliminated")); } else { // Affects only the single target when Clear Smog is used if (!move.hitsSubstitute(user, target)) { - promises.push(this.resetStats(target)); + this.resetStats(target); globalScene.queueMessage(i18next.t("moveTriggers:resetStats", { pokemonName: getPokemonNameWithAffix(target) })); } } - - await Promise.all(promises); return true; } - async resetStats(pokemon: Pokemon): Promise { + private resetStats(pokemon: Pokemon): void { for (const s of BATTLE_STATS) { pokemon.setStatStage(s, 0); } - return pokemon.updateInfo(); + pokemon.updateInfo(); } } @@ -3503,43 +3508,28 @@ export class SwapStatStagesAttr extends MoveEffectAttr { } export class HpSplitAttr extends MoveEffectAttr { - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { - return new Promise(resolve => { - if (!super.apply(user, target, move, args)) { - return resolve(false); - } + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + if (!super.apply(user, target, move, args)) { + return false; + } - const infoUpdates: Promise[] = []; - - const hpValue = Math.floor((target.hp + user.hp) / 2); - if (user.hp < hpValue) { - const healing = user.heal(hpValue - user.hp); + const hpValue = Math.floor((target.hp + user.hp) / 2); + [ user, target ].forEach((p) => { + if (p.hp < hpValue) { + const healing = p.heal(hpValue - p.hp); if (healing) { - globalScene.damageNumberHandler.add(user, healing, HitResult.HEAL); + globalScene.damageNumberHandler.add(p, healing, HitResult.HEAL); } - } else if (user.hp > hpValue) { - const damage = user.damage(user.hp - hpValue, true); + } else if (p.hp > hpValue) { + const damage = p.damage(p.hp - hpValue, true); if (damage) { - globalScene.damageNumberHandler.add(user, damage); + globalScene.damageNumberHandler.add(p, damage); } } - infoUpdates.push(user.updateInfo()); - - if (target.hp < hpValue) { - const healing = target.heal(hpValue - target.hp); - if (healing) { - globalScene.damageNumberHandler.add(user, healing, HitResult.HEAL); - } - } else if (target.hp > hpValue) { - const damage = target.damage(target.hp - hpValue, true); - if (damage) { - globalScene.damageNumberHandler.add(target, damage); - } - } - infoUpdates.push(target.updateInfo()); - - return Promise.all(infoUpdates).then(() => resolve(true)); + p.updateInfo(); }); + + return true; } } @@ -6024,44 +6014,44 @@ export class RevivalBlessingAttr extends MoveEffectAttr { * @param args N/A * @returns Promise, true if function succeeds. */ - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { - return new Promise(resolve => { - // If user is player, checks if the user has fainted pokemon - if (user instanceof PlayerPokemon - && globalScene.getPlayerParty().findIndex(p => p.isFainted()) > -1) { - (user as PlayerPokemon).revivalBlessing().then(() => { - resolve(true); - }); - // If user is enemy, checks that it is a trainer, and it has fainted non-boss pokemon in party - } else if (user instanceof EnemyPokemon - && user.hasTrainer() - && globalScene.getEnemyParty().findIndex(p => p.isFainted() && !p.isBoss()) > -1) { - // Selects a random fainted pokemon - const faintedPokemon = globalScene.getEnemyParty().filter(p => p.isFainted() && !p.isBoss()); - const pokemon = faintedPokemon[user.randSeedInt(faintedPokemon.length)]; - const slotIndex = globalScene.getEnemyParty().findIndex(p => pokemon.id === p.id); - pokemon.resetStatus(); - pokemon.heal(Math.min(Utils.toDmgValue(0.5 * pokemon.getMaxHp()), pokemon.getMaxHp())); - globalScene.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: getPokemonNameWithAffix(pokemon) }), 0, true); + override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + // If user is player, checks if the user has fainted pokemon + if (user instanceof PlayerPokemon) { + globalScene.unshiftPhase(new RevivalBlessingPhase(user)); + return true; + } else if (user instanceof EnemyPokemon && user.hasTrainer() && globalScene.getEnemyParty().findIndex((p) => p.isFainted() && !p.isBoss()) > -1) { + // If used by an enemy trainer with at least one fainted non-boss Pokemon, this + // revives one of said Pokemon selected at random. + const faintedPokemon = globalScene.getEnemyParty().filter((p) => p.isFainted() && !p.isBoss()); + const pokemon = faintedPokemon[user.randSeedInt(faintedPokemon.length)]; + const slotIndex = globalScene.getEnemyParty().findIndex((p) => pokemon.id === p.id); + pokemon.resetStatus(); + pokemon.heal(Math.min(Utils.toDmgValue(0.5 * pokemon.getMaxHp()), pokemon.getMaxHp())); + globalScene.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: getPokemonNameWithAffix(pokemon) }), 0, true); - if (globalScene.currentBattle.double && globalScene.getEnemyParty().length > 1) { - const allyPokemon = user.getAlly(); - if (slotIndex <= 1) { - globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, pokemon.getFieldIndex(), slotIndex, false, false)); - } else if (allyPokemon.isFainted()) { - globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, allyPokemon.getFieldIndex(), slotIndex, false, false)); - } + if (globalScene.currentBattle.double && globalScene.getEnemyParty().length > 1) { + const allyPokemon = user.getAlly(); + if (slotIndex <= 1) { + globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, pokemon.getFieldIndex(), slotIndex, false, false)); + } else if (allyPokemon.isFainted()) { + globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, allyPokemon.getFieldIndex(), slotIndex, false, false)); } - resolve(true); - } else { - globalScene.queueMessage(i18next.t("battle:attackFailed")); - resolve(false); } - }); + return true; + } + return false; } - getUserBenefitScore(user: Pokemon, target: Pokemon, move: Move): number { - if (user.hasTrainer() && globalScene.getEnemyParty().findIndex(p => p.isFainted() && !p.isBoss()) > -1) { + getCondition(): MoveConditionFunc { + return (user, target, move) => + (user instanceof PlayerPokemon && globalScene.getPlayerParty().some((p) => p.isFainted())) || + (user instanceof EnemyPokemon && + user.hasTrainer() && + globalScene.getEnemyParty().some((p) => p.isFainted() && !p.isBoss())); + } + + override getUserBenefitScore(user: Pokemon, _target: Pokemon, _move: Move): number { + if (user.hasTrainer() && globalScene.getEnemyParty().some((p) => p.isFainted() && !p.isBoss())) { return 20; } @@ -6579,7 +6569,7 @@ export class FirstMoveTypeAttr extends MoveEffectAttr { class CallMoveAttr extends OverrideMoveEffectAttr { protected invalidMoves: Moves[]; protected hasTarget: boolean; - async apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { const replaceMoveTarget = move.moveTarget === MoveTarget.NEAR_OTHER ? MoveTarget.NEAR_ENEMY : undefined; const moveTargets = getMoveTargets(user, move.id, replaceMoveTarget); if (moveTargets.targets.length === 0) { @@ -6589,11 +6579,8 @@ class CallMoveAttr extends OverrideMoveEffectAttr { ? moveTargets.targets : [ this.hasTarget ? target.getBattlerIndex() : moveTargets.targets[user.randSeedInt(moveTargets.targets.length)] ]; // account for Mirror Move having a target already user.getMoveQueue().push({ move: move.id, targets: targets, virtual: true, ignorePP: true }); + globalScene.unshiftPhase(new LoadMoveAnimPhase(move.id)); globalScene.unshiftPhase(new MovePhase(user, targets, new PokemonMove(move.id, 0, 0, true), true, true)); - - await Promise.resolve(initMoveAnim(move.id).then(() => { - loadMoveAnimAssets([ move.id ], true); - })); return true; } } @@ -6626,7 +6613,7 @@ export class RandomMoveAttr extends CallMoveAttr { * @param move Move being used * @param args Unused */ - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { + override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { const moveIds = Utils.getEnumValues(Moves).map(m => !this.invalidMoves.includes(m) && !allMoves[m].name.endsWith(" (N)") ? m : Moves.NONE); let moveId: Moves = Moves.NONE; do { @@ -6663,7 +6650,7 @@ export class RandomMovesetMoveAttr extends CallMoveAttr { * @param move Move being used * @param args Unused */ - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { return super.apply(user, target, allMoves[this.moveId], args); } @@ -6965,145 +6952,141 @@ const invalidCopycatMoves = [ ]; export class NaturePowerAttr extends OverrideMoveEffectAttr { - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { - return new Promise(resolve => { - let moveId; - switch (globalScene.arena.getTerrainType()) { - // this allows terrains to 'override' the biome move - case TerrainType.NONE: - switch (globalScene.arena.biomeType) { - case Biome.TOWN: - moveId = Moves.ROUND; - break; - case Biome.METROPOLIS: - moveId = Moves.TRI_ATTACK; - break; - case Biome.SLUM: - moveId = Moves.SLUDGE_BOMB; - break; - case Biome.PLAINS: - moveId = Moves.SILVER_WIND; - break; - case Biome.GRASS: - moveId = Moves.GRASS_KNOT; - break; - case Biome.TALL_GRASS: - moveId = Moves.POLLEN_PUFF; - break; - case Biome.MEADOW: - moveId = Moves.GIGA_DRAIN; - break; - case Biome.FOREST: - moveId = Moves.BUG_BUZZ; - break; - case Biome.JUNGLE: - moveId = Moves.LEAF_STORM; - break; - case Biome.SEA: - moveId = Moves.HYDRO_PUMP; - break; - case Biome.SWAMP: - moveId = Moves.MUD_BOMB; - break; - case Biome.BEACH: - moveId = Moves.SCALD; - break; - case Biome.LAKE: - moveId = Moves.BUBBLE_BEAM; - break; - case Biome.SEABED: - moveId = Moves.BRINE; - break; - case Biome.ISLAND: - moveId = Moves.LEAF_TORNADO; - break; - case Biome.MOUNTAIN: - moveId = Moves.AIR_SLASH; - break; - case Biome.BADLANDS: - moveId = Moves.EARTH_POWER; - break; - case Biome.DESERT: - moveId = Moves.SCORCHING_SANDS; - break; - case Biome.WASTELAND: - moveId = Moves.DRAGON_PULSE; - break; - case Biome.CONSTRUCTION_SITE: - moveId = Moves.STEEL_BEAM; - break; - case Biome.CAVE: - moveId = Moves.POWER_GEM; - break; - case Biome.ICE_CAVE: - moveId = Moves.ICE_BEAM; - break; - case Biome.SNOWY_FOREST: - moveId = Moves.FROST_BREATH; - break; - case Biome.VOLCANO: - moveId = Moves.LAVA_PLUME; - break; - case Biome.GRAVEYARD: - moveId = Moves.SHADOW_BALL; - break; - case Biome.RUINS: - moveId = Moves.ANCIENT_POWER; - break; - case Biome.TEMPLE: - moveId = Moves.EXTRASENSORY; - break; - case Biome.DOJO: - moveId = Moves.FOCUS_BLAST; - break; - case Biome.FAIRY_CAVE: - moveId = Moves.ALLURING_VOICE; - break; - case Biome.ABYSS: - moveId = Moves.OMINOUS_WIND; - break; - case Biome.SPACE: - moveId = Moves.DRACO_METEOR; - break; - case Biome.FACTORY: - moveId = Moves.FLASH_CANNON; - break; - case Biome.LABORATORY: - moveId = Moves.ZAP_CANNON; - break; - case Biome.POWER_PLANT: - moveId = Moves.CHARGE_BEAM; - break; - case Biome.END: - moveId = Moves.ETERNABEAM; - break; - } - break; - case TerrainType.MISTY: - moveId = Moves.MOONBLAST; - break; - case TerrainType.ELECTRIC: - moveId = Moves.THUNDERBOLT; - break; - case TerrainType.GRASSY: - moveId = Moves.ENERGY_BALL; - break; - case TerrainType.PSYCHIC: - moveId = Moves.PSYCHIC; - break; - default: - // Just in case there's no match - moveId = Moves.TRI_ATTACK; - break; - } + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + let moveId; + switch (globalScene.arena.getTerrainType()) { + // this allows terrains to 'override' the biome move + case TerrainType.NONE: + switch (globalScene.arena.biomeType) { + case Biome.TOWN: + moveId = Moves.ROUND; + break; + case Biome.METROPOLIS: + moveId = Moves.TRI_ATTACK; + break; + case Biome.SLUM: + moveId = Moves.SLUDGE_BOMB; + break; + case Biome.PLAINS: + moveId = Moves.SILVER_WIND; + break; + case Biome.GRASS: + moveId = Moves.GRASS_KNOT; + break; + case Biome.TALL_GRASS: + moveId = Moves.POLLEN_PUFF; + break; + case Biome.MEADOW: + moveId = Moves.GIGA_DRAIN; + break; + case Biome.FOREST: + moveId = Moves.BUG_BUZZ; + break; + case Biome.JUNGLE: + moveId = Moves.LEAF_STORM; + break; + case Biome.SEA: + moveId = Moves.HYDRO_PUMP; + break; + case Biome.SWAMP: + moveId = Moves.MUD_BOMB; + break; + case Biome.BEACH: + moveId = Moves.SCALD; + break; + case Biome.LAKE: + moveId = Moves.BUBBLE_BEAM; + break; + case Biome.SEABED: + moveId = Moves.BRINE; + break; + case Biome.ISLAND: + moveId = Moves.LEAF_TORNADO; + break; + case Biome.MOUNTAIN: + moveId = Moves.AIR_SLASH; + break; + case Biome.BADLANDS: + moveId = Moves.EARTH_POWER; + break; + case Biome.DESERT: + moveId = Moves.SCORCHING_SANDS; + break; + case Biome.WASTELAND: + moveId = Moves.DRAGON_PULSE; + break; + case Biome.CONSTRUCTION_SITE: + moveId = Moves.STEEL_BEAM; + break; + case Biome.CAVE: + moveId = Moves.POWER_GEM; + break; + case Biome.ICE_CAVE: + moveId = Moves.ICE_BEAM; + break; + case Biome.SNOWY_FOREST: + moveId = Moves.FROST_BREATH; + break; + case Biome.VOLCANO: + moveId = Moves.LAVA_PLUME; + break; + case Biome.GRAVEYARD: + moveId = Moves.SHADOW_BALL; + break; + case Biome.RUINS: + moveId = Moves.ANCIENT_POWER; + break; + case Biome.TEMPLE: + moveId = Moves.EXTRASENSORY; + break; + case Biome.DOJO: + moveId = Moves.FOCUS_BLAST; + break; + case Biome.FAIRY_CAVE: + moveId = Moves.ALLURING_VOICE; + break; + case Biome.ABYSS: + moveId = Moves.OMINOUS_WIND; + break; + case Biome.SPACE: + moveId = Moves.DRACO_METEOR; + break; + case Biome.FACTORY: + moveId = Moves.FLASH_CANNON; + break; + case Biome.LABORATORY: + moveId = Moves.ZAP_CANNON; + break; + case Biome.POWER_PLANT: + moveId = Moves.CHARGE_BEAM; + break; + case Biome.END: + moveId = Moves.ETERNABEAM; + break; + } + break; + case TerrainType.MISTY: + moveId = Moves.MOONBLAST; + break; + case TerrainType.ELECTRIC: + moveId = Moves.THUNDERBOLT; + break; + case TerrainType.GRASSY: + moveId = Moves.ENERGY_BALL; + break; + case TerrainType.PSYCHIC: + moveId = Moves.PSYCHIC; + break; + default: + // Just in case there's no match + moveId = Moves.TRI_ATTACK; + break; + } - user.getMoveQueue().push({ move: moveId, targets: [ target.getBattlerIndex() ], ignorePP: true }); - globalScene.unshiftPhase(new MovePhase(user, [ target.getBattlerIndex() ], new PokemonMove(moveId, 0, 0, true), true)); - initMoveAnim(moveId).then(() => { - loadMoveAnimAssets([ moveId ], true) - .then(() => resolve(true)); - }); - }); + user.getMoveQueue().push({ move: moveId, targets: [ target.getBattlerIndex() ], ignorePP: true }); + globalScene.unshiftPhase(new LoadMoveAnimPhase(moveId)); + globalScene.unshiftPhase(new MovePhase(user, [ target.getBattlerIndex() ], new PokemonMove(moveId, 0, 0, true), true)); + return true; } } @@ -7121,7 +7104,7 @@ export class CopyMoveAttr extends CallMoveAttr { this.invalidMoves = invalidMoves; } - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { + apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { this.hasTarget = this.mirrorMove; const lastMove = this.mirrorMove ? target.getLastXMoves()[0].move : globalScene.currentBattle.lastMove; return super.apply(user, target, allMoves[lastMove], args); @@ -7682,50 +7665,15 @@ export class SuppressAbilitiesIfActedAttr extends MoveEffectAttr { * Used by Transform */ export class TransformAttr extends MoveEffectAttr { - async apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { + override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { if (!super.apply(user, target, move, args)) { return false; } - const promises: Promise[] = []; - user.summonData.speciesForm = target.getSpeciesForm(); - user.summonData.gender = target.getGender(); - - // Power Trick's effect will not preserved after using Transform - user.removeTag(BattlerTagType.POWER_TRICK); - - // Copy all stats (except HP) - for (const s of EFFECTIVE_STATS) { - user.setStat(s, target.getStat(s, false), false); - } - - // Copy all stat stages - for (const s of BATTLE_STATS) { - user.setStatStage(s, target.getStatStage(s)); - } - - user.summonData.moveset = target.getMoveset().map((m) => { - if (m) { - // If PP value is less than 5, do nothing. If greater, we need to reduce the value to 5. - return new PokemonMove(m.moveId, 0, 0, false, Math.min(m.getMove().pp, 5)); - } else { - console.warn(`Transform: somehow iterating over a ${m} value when copying moveset!`); - return new PokemonMove(Moves.NONE); - } - }); - user.summonData.types = target.getTypes(); - promises.push(user.updateInfo()); + globalScene.unshiftPhase(new PokemonTransformPhase(user.getBattlerIndex(), target.getBattlerIndex())); globalScene.queueMessage(i18next.t("moveTriggers:transformedIntoTarget", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target) })); - promises.push(user.loadAssets(false).then(() => { - user.playAnim(); - user.updateInfo(); - // If the new ability activates immediately, it needs to happen after all the transform animations - user.setTempAbility(target.getAbility()); - })); - - await Promise.all(promises); return true; } } @@ -8128,44 +8076,54 @@ const attackedByItemMessageFunc = (user: Pokemon, target: Pokemon, move: Move) = export type MoveAttrFilter = (attr: MoveAttr) => boolean; -function applyMoveAttrsInternal(attrFilter: MoveAttrFilter, user: Pokemon | null, target: Pokemon | null, move: Move, args: any[]): Promise { - return new Promise(resolve => { - const attrPromises: Promise[] = []; - const moveAttrs = move.attrs.filter(a => attrFilter(a)); - for (const attr of moveAttrs) { - const result = attr.apply(user, target, move, args); - if (result instanceof Promise) { - attrPromises.push(result); - } - } - Promise.allSettled(attrPromises).then(() => resolve()); - }); +function applyMoveAttrsInternal( + attrFilter: MoveAttrFilter, + user: Pokemon | null, + target: Pokemon | null, + move: Move, + args: any[], +): void { + move.attrs.filter((attr) => attrFilter(attr)).forEach((attr) => attr.apply(user, target, move, args)); } -function applyMoveChargeAttrsInternal(attrFilter: MoveAttrFilter, user: Pokemon | null, target: Pokemon | null, move: ChargingMove, args: any[]): Promise { - return new Promise(resolve => { - const chargeAttrPromises: Promise[] = []; - const chargeMoveAttrs = move.chargeAttrs.filter(a => attrFilter(a)); - for (const attr of chargeMoveAttrs) { - const result = attr.apply(user, target, move, args); - if (result instanceof Promise) { - chargeAttrPromises.push(result); - } - } - Promise.allSettled(chargeAttrPromises).then(() => resolve()); - }); +function applyMoveChargeAttrsInternal( + attrFilter: MoveAttrFilter, + user: Pokemon | null, + target: Pokemon | null, + move: ChargingMove, + args: any[], +): void { + move.chargeAttrs.filter((attr) => attrFilter(attr)).forEach((attr) => attr.apply(user, target, move, args)); } -export function applyMoveAttrs(attrType: Constructor, user: Pokemon | null, target: Pokemon | null, move: Move, ...args: any[]): Promise { - return applyMoveAttrsInternal((attr: MoveAttr) => attr instanceof attrType, user, target, move, args); +export function applyMoveAttrs( + attrType: Constructor, + user: Pokemon | null, + target: Pokemon | null, + move: Move, + ...args: any[] +): void { + applyMoveAttrsInternal((attr: MoveAttr) => attr instanceof attrType, user, target, move, args); } -export function applyFilteredMoveAttrs(attrFilter: MoveAttrFilter, user: Pokemon, target: Pokemon | null, move: Move, ...args: any[]): Promise { - return applyMoveAttrsInternal(attrFilter, user, target, move, args); +export function applyFilteredMoveAttrs( + attrFilter: MoveAttrFilter, + user: Pokemon, + target: Pokemon | null, + move: Move, + ...args: any[] +): void { + applyMoveAttrsInternal(attrFilter, user, target, move, args); } -export function applyMoveChargeAttrs(attrType: Constructor, user: Pokemon | null, target: Pokemon | null, move: ChargingMove, ...args: any[]): Promise { - return applyMoveChargeAttrsInternal((attr: MoveAttr) => attr instanceof attrType, user, target, move, args); +export function applyMoveChargeAttrs( + attrType: Constructor, + user: Pokemon | null, + target: Pokemon | null, + move: ChargingMove, + ...args: any[] +): void { + applyMoveChargeAttrsInternal((attr: MoveAttr) => attr instanceof attrType, user, target, move, args); } export class MoveCondition { diff --git a/src/data/mystery-encounters/encounters/the-winstrate-challenge-encounter.ts b/src/data/mystery-encounters/encounters/the-winstrate-challenge-encounter.ts index ca6b384cfbb..7d3f6f4c5bc 100644 --- a/src/data/mystery-encounters/encounters/the-winstrate-challenge-encounter.ts +++ b/src/data/mystery-encounters/encounters/the-winstrate-challenge-encounter.ts @@ -151,7 +151,7 @@ async function spawnNextTrainerOrEndEncounter() { // Give 10x Voucher const newModifier = modifierTypes.VOUCHER_PREMIUM().newModifier(); - await globalScene.addModifier(newModifier); + globalScene.addModifier(newModifier); globalScene.playSound("item_fanfare"); await showEncounterText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name })); diff --git a/src/data/mystery-encounters/encounters/weird-dream-encounter.ts b/src/data/mystery-encounters/encounters/weird-dream-encounter.ts index f7c70cb7052..454d179c003 100644 --- a/src/data/mystery-encounters/encounters/weird-dream-encounter.ts +++ b/src/data/mystery-encounters/encounters/weird-dream-encounter.ts @@ -406,7 +406,7 @@ async function doNewTeamPostProcess(transformations: PokemonTransformation[]) { // Copy old items to new pokemon for (const item of transformation.heldItems) { item.pokemonId = newPokemon.id; - await globalScene.addModifier(item, false, false, false, true); + globalScene.addModifier(item, false, false, false, true); } // Any pokemon that is below 570 BST gets +20 permanent BST to 3 stats if (shouldGetOldGateau(newPokemon)) { @@ -416,7 +416,7 @@ async function doNewTeamPostProcess(transformations: PokemonTransformation[]) { ?.withIdFromFunc(modifierTypes.MYSTERY_ENCOUNTER_OLD_GATEAU); const modifier = modType?.newModifier(newPokemon); if (modifier) { - await globalScene.addModifier(modifier, false, false, false, true); + globalScene.addModifier(modifier, false, false, false, true); } } diff --git a/src/data/mystery-encounters/utils/encounter-pokemon-utils.ts b/src/data/mystery-encounters/utils/encounter-pokemon-utils.ts index 580aaaf2cc6..be7d11d6cf1 100644 --- a/src/data/mystery-encounters/utils/encounter-pokemon-utils.ts +++ b/src/data/mystery-encounters/utils/encounter-pokemon-utils.ts @@ -326,7 +326,7 @@ export async function modifyPlayerPokemonBST(pokemon: PlayerPokemon, value: numb ?.withIdFromFunc(modifierTypes.MYSTERY_ENCOUNTER_SHUCKLE_JUICE); const modifier = modType?.newModifier(pokemon); if (modifier) { - await globalScene.addModifier(modifier, false, false, false, true); + globalScene.addModifier(modifier, false, false, false, true); pokemon.calculateStats(); } } @@ -359,7 +359,7 @@ export async function applyModifierTypeToPlayerPokemon(pokemon: PlayerPokemon, m return applyModifierTypeToPlayerPokemon(pokemon, fallbackModifierType); } - await globalScene.addModifier(modifier, false, false, false, true); + globalScene.addModifier(modifier, false, false, false, true); } /** diff --git a/src/field/pokemon.ts b/src/field/pokemon.ts index 246f82b8164..214c667f1c1 100644 --- a/src/field/pokemon.ts +++ b/src/field/pokemon.ts @@ -104,7 +104,6 @@ import { MoveEndPhase } from "#app/phases/move-end-phase"; import { ObtainStatusEffectPhase } from "#app/phases/obtain-status-effect-phase"; import { StatStageChangePhase } from "#app/phases/stat-stage-change-phase"; import { SwitchSummonPhase } from "#app/phases/switch-summon-phase"; -import { ToggleDoublePositionPhase } from "#app/phases/toggle-double-position-phase"; import { Challenges } from "#enums/challenges"; import { PokemonAnimType } from "#enums/pokemon-anim-type"; import { PLAYER_PARTY_MAX_SIZE } from "#app/constants"; @@ -4510,43 +4509,6 @@ export class PlayerPokemon extends Pokemon { this.friendship = Math.max(this.friendship + friendship, 0); } } - /** - * Handles Revival Blessing when used by player. - * @returns Promise to revive a pokemon. - * @see {@linkcode RevivalBlessingAttr} - */ - revivalBlessing(): Promise { - return new Promise(resolve => { - globalScene.ui.setMode(Mode.PARTY, PartyUiMode.REVIVAL_BLESSING, this.getFieldIndex(), (slotIndex:number, option: PartyOption) => { - if (slotIndex >= 0 && slotIndex < 6) { - const pokemon = globalScene.getPlayerParty()[slotIndex]; - if (!pokemon || !pokemon.isFainted()) { - resolve(); - } - - pokemon.resetTurnData(); - pokemon.resetStatus(); - pokemon.heal(Math.min(Utils.toDmgValue(0.5 * pokemon.getMaxHp()), pokemon.getMaxHp())); - globalScene.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: pokemon.name }), 0, true); - - if (globalScene.currentBattle.double && globalScene.getPlayerParty().length > 1) { - const allyPokemon = this.getAlly(); - if (slotIndex <= 1) { - // Revived ally pokemon - globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, pokemon.getFieldIndex(), slotIndex, false, true)); - globalScene.unshiftPhase(new ToggleDoublePositionPhase(true)); - } else if (allyPokemon.isFainted()) { - // Revived party pokemon, and ally pokemon is fainted - globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, allyPokemon.getFieldIndex(), slotIndex, false, true)); - globalScene.unshiftPhase(new ToggleDoublePositionPhase(true)); - } - } - - } - globalScene.ui.setMode(Mode.MESSAGE).then(() => resolve()); - }, PartyUiHandler.FilterFainted); - }); - } getPossibleEvolution(evolution: SpeciesFormEvolution | null): Promise { if (!evolution) { @@ -4728,70 +4690,62 @@ export class PlayerPokemon extends Pokemon { } /** - * Returns a Promise to fuse two PlayerPokemon together - * @param pokemon The PlayerPokemon to fuse to this one - */ - fuse(pokemon: PlayerPokemon): Promise { - return new Promise(resolve => { - this.fusionSpecies = pokemon.species; - this.fusionFormIndex = pokemon.formIndex; - this.fusionAbilityIndex = pokemon.abilityIndex; - this.fusionShiny = pokemon.shiny; - this.fusionVariant = pokemon.variant; - this.fusionGender = pokemon.gender; - this.fusionLuck = pokemon.luck; - this.fusionCustomPokemonData = pokemon.customPokemonData; - if ((pokemon.pauseEvolutions) || (this.pauseEvolutions)) { - this.pauseEvolutions = true; - } + * Returns a Promise to fuse two PlayerPokemon together + * @param pokemon The PlayerPokemon to fuse to this one + */ + fuse(pokemon: PlayerPokemon): void { + this.fusionSpecies = pokemon.species; + this.fusionFormIndex = pokemon.formIndex; + this.fusionAbilityIndex = pokemon.abilityIndex; + this.fusionShiny = pokemon.shiny; + this.fusionVariant = pokemon.variant; + this.fusionGender = pokemon.gender; + this.fusionLuck = pokemon.luck; + this.fusionCustomPokemonData = pokemon.customPokemonData; + if (pokemon.pauseEvolutions || this.pauseEvolutions) { + this.pauseEvolutions = true; + } - globalScene.validateAchv(achvs.SPLICE); - globalScene.gameData.gameStats.pokemonFused++; + globalScene.validateAchv(achvs.SPLICE); + globalScene.gameData.gameStats.pokemonFused++; - // Store the average HP% that each Pokemon has - const maxHp = this.getMaxHp(); - const newHpPercent = ((pokemon.hp / pokemon.getMaxHp()) + (this.hp / maxHp)) / 2; + // Store the average HP% that each Pokemon has + const maxHp = this.getMaxHp(); + const newHpPercent = (pokemon.hp / pokemon.getMaxHp() + this.hp / maxHp) / 2; - this.generateName(); - this.calculateStats(); + this.generateName(); + this.calculateStats(); - // Set this Pokemon's HP to the average % of both fusion components - this.hp = Math.round(maxHp * newHpPercent); - if (!this.isFainted()) { - // If this Pokemon hasn't fainted, make sure the HP wasn't set over the new maximum - this.hp = Math.min(this.hp, maxHp); - this.status = getRandomStatus(this.status, pokemon.status); // Get a random valid status between the two - } else if (!pokemon.isFainted()) { - // If this Pokemon fainted but the other hasn't, make sure the HP wasn't set to zero - this.hp = Math.max(this.hp, 1); - this.status = pokemon.status; // Inherit the other Pokemon's status - } + // Set this Pokemon's HP to the average % of both fusion components + this.hp = Math.round(maxHp * newHpPercent); + if (!this.isFainted()) { + // If this Pokemon hasn't fainted, make sure the HP wasn't set over the new maximum + this.hp = Math.min(this.hp, maxHp); + this.status = getRandomStatus(this.status, pokemon.status); // Get a random valid status between the two + } else if (!pokemon.isFainted()) { + // If this Pokemon fainted but the other hasn't, make sure the HP wasn't set to zero + this.hp = Math.max(this.hp, 1); + this.status = pokemon.status; // Inherit the other Pokemon's status + } - this.generateCompatibleTms(); - this.updateInfo(true); - const fusedPartyMemberIndex = globalScene.getPlayerParty().indexOf(pokemon); - let partyMemberIndex = globalScene.getPlayerParty().indexOf(this); - if (partyMemberIndex > fusedPartyMemberIndex) { - partyMemberIndex--; - } - const fusedPartyMemberHeldModifiers = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier - && m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[]; - const transferModifiers: Promise[] = []; - for (const modifier of fusedPartyMemberHeldModifiers) { - transferModifiers.push(globalScene.tryTransferHeldItemModifier(modifier, this, false, modifier.getStackCount(), true, true, false)); - } - Promise.allSettled(transferModifiers).then(() => { - globalScene.updateModifiers(true, true).then(() => { - globalScene.removePartyMemberModifiers(fusedPartyMemberIndex); - globalScene.getPlayerParty().splice(fusedPartyMemberIndex, 1)[0]; - const newPartyMemberIndex = globalScene.getPlayerParty().indexOf(this); - pokemon.getMoveset(true).map((m: PokemonMove) => globalScene.unshiftPhase(new LearnMovePhase(newPartyMemberIndex, m.getMove().id))); - pokemon.destroy(); - this.updateFusionPalette(); - resolve(); - }); - }); - }); + this.generateCompatibleTms(); + this.updateInfo(true); + const fusedPartyMemberIndex = globalScene.getPlayerParty().indexOf(pokemon); + let partyMemberIndex = globalScene.getPlayerParty().indexOf(this); + if (partyMemberIndex > fusedPartyMemberIndex) { + partyMemberIndex--; + } + const fusedPartyMemberHeldModifiers = globalScene.findModifiers((m) => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[]; + for (const modifier of fusedPartyMemberHeldModifiers) { + globalScene.tryTransferHeldItemModifier(modifier, this, false, modifier.getStackCount(), true, true, false); + } + globalScene.updateModifiers(true, true); + globalScene.removePartyMemberModifiers(fusedPartyMemberIndex); + globalScene.getPlayerParty().splice(fusedPartyMemberIndex, 1)[0]; + const newPartyMemberIndex = globalScene.getPlayerParty().indexOf(this); + pokemon.getMoveset(true).map((m: PokemonMove) => globalScene.unshiftPhase(new LearnMovePhase(newPartyMemberIndex, m.getMove().id))); + pokemon.destroy(); + this.updateFusionPalette(); } unfuse(): Promise { diff --git a/src/modifier/modifier.ts b/src/modifier/modifier.ts index 3af2aa2144f..f6a69fcca2d 100644 --- a/src/modifier/modifier.ts +++ b/src/modifier/modifier.ts @@ -158,7 +158,7 @@ export abstract class Modifier { * Handles applying of {@linkcode Modifier} * @param args collection of all passed parameters */ - abstract apply(...args: unknown[]): boolean | Promise; + abstract apply(...args: unknown[]): boolean; } export abstract class PersistentModifier extends Modifier { @@ -1949,7 +1949,7 @@ export abstract class ConsumablePokemonModifier extends ConsumableModifier { * @param playerPokemon The {@linkcode PlayerPokemon} that consumes the item * @param args Additional arguments passed to {@linkcode ConsumablePokemonModifier.apply} */ - abstract override apply(playerPokemon: PlayerPokemon, ...args: unknown[]): boolean | Promise; + abstract override apply(playerPokemon: PlayerPokemon, ...args: unknown[]): boolean; getPokemon() { return globalScene.getPlayerParty().find(p => p.id === this.pokemonId); @@ -2288,8 +2288,8 @@ export class FusePokemonModifier extends ConsumablePokemonModifier { * @param playerPokemon2 {@linkcode PlayerPokemon} that should be fused with {@linkcode playerPokemon} * @returns always Promise */ - override async apply(playerPokemon: PlayerPokemon, playerPokemon2: PlayerPokemon): Promise { - await playerPokemon.fuse(playerPokemon2); + override apply(playerPokemon: PlayerPokemon, playerPokemon2: PlayerPokemon): boolean { + playerPokemon.fuse(playerPokemon2); return true; } } @@ -3136,8 +3136,6 @@ export abstract class HeldItemTransferModifier extends PokemonHeldItemModifier { let highestItemTier = itemModifiers.map(m => m.type.getOrInferTier(poolType)).reduce((highestTier, tier) => Math.max(tier!, highestTier), 0); // TODO: is this bang correct? let tierItemModifiers = itemModifiers.filter(m => m.type.getOrInferTier(poolType) === highestItemTier); - const heldItemTransferPromises: Promise[] = []; - for (let i = 0; i < transferredItemCount; i++) { if (!tierItemModifiers.length) { while (highestItemTier-- && !tierItemModifiers.length) { @@ -3149,19 +3147,15 @@ export abstract class HeldItemTransferModifier extends PokemonHeldItemModifier { } const randItemIndex = pokemon.randSeedInt(itemModifiers.length); const randItem = itemModifiers[randItemIndex]; - heldItemTransferPromises.push(globalScene.tryTransferHeldItemModifier(randItem, pokemon, false).then(success => { - if (success) { - transferredModifierTypes.push(randItem.type); - itemModifiers.splice(randItemIndex, 1); - } - })); + if (globalScene.tryTransferHeldItemModifier(randItem, pokemon, false)) { + transferredModifierTypes.push(randItem.type); + itemModifiers.splice(randItemIndex, 1); + } } - Promise.all(heldItemTransferPromises).then(() => { - for (const mt of transferredModifierTypes) { - globalScene.queueMessage(this.getTransferMessage(pokemon, targetPokemon, mt)); - } - }); + for (const mt of transferredModifierTypes) { + globalScene.queueMessage(this.getTransferMessage(pokemon, targetPokemon, mt)); + } return !!transferredModifierTypes.length; } diff --git a/src/phases/add-enemy-buff-modifier-phase.ts b/src/phases/add-enemy-buff-modifier-phase.ts index d79b4f6eca5..f504fd0aaa2 100644 --- a/src/phases/add-enemy-buff-modifier-phase.ts +++ b/src/phases/add-enemy-buff-modifier-phase.ts @@ -21,6 +21,7 @@ export class AddEnemyBuffModifierPhase extends Phase { for (let i = 0; i < count; i++) { globalScene.addEnemyModifier(getEnemyBuffModifierForWave(tier, globalScene.findModifiers(m => m instanceof EnemyPersistentModifier, false)), true, true); } - globalScene.updateModifiers(false, true).then(() => this.end()); + globalScene.updateModifiers(false, true); + this.end(); } } diff --git a/src/phases/battle-end-phase.ts b/src/phases/battle-end-phase.ts index edffd8498d6..c0922b91809 100644 --- a/src/phases/battle-end-phase.ts +++ b/src/phases/battle-end-phase.ts @@ -63,6 +63,7 @@ export class BattleEndPhase extends BattlePhase { } } - globalScene.updateModifiers().then(() => this.end()); + globalScene.updateModifiers(); + this.end(); } } diff --git a/src/phases/game-over-modifier-reward-phase.ts b/src/phases/game-over-modifier-reward-phase.ts index c98bb5fff04..93f53bf38c0 100644 --- a/src/phases/game-over-modifier-reward-phase.ts +++ b/src/phases/game-over-modifier-reward-phase.ts @@ -12,16 +12,22 @@ export class GameOverModifierRewardPhase extends ModifierRewardPhase { doReward(): Promise { return new Promise(resolve => { const newModifier = this.modifierType.newModifier(); - globalScene.addModifier(newModifier).then(() => { - // Sound loaded into game as is - globalScene.playSound("level_up_fanfare"); - globalScene.ui.setMode(Mode.MESSAGE); - globalScene.ui.fadeIn(250).then(() => { - globalScene.ui.showText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), null, () => { + globalScene.addModifier(newModifier); + // Sound loaded into game as is + globalScene.playSound("level_up_fanfare"); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.fadeIn(250).then(() => { + globalScene.ui.showText( + i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), + null, + () => { globalScene.time.delayedCall(1500, () => globalScene.arenaBg.setVisible(true)); resolve(); - }, null, true, 1500); - }); + }, + null, + true, + 1500, + ); }); }); } diff --git a/src/phases/load-move-anim-phase.ts b/src/phases/load-move-anim-phase.ts new file mode 100644 index 00000000000..66cb90744e0 --- /dev/null +++ b/src/phases/load-move-anim-phase.ts @@ -0,0 +1,20 @@ +import { initMoveAnim, loadMoveAnimAssets } from "#app/data/battle-anims"; +import type { Moves } from "#enums/moves"; +import { Phase } from "#app/phase"; + +/** + * Phase for synchronous move animation loading. + * Should be used when a move invokes another move that + * isn't already loaded (e.g. for Metronome) + */ +export class LoadMoveAnimPhase extends Phase { + constructor(protected moveId: Moves) { + super(); + } + + public override start(): void { + initMoveAnim(this.moveId) + .then(() => loadMoveAnimAssets([ this.moveId ], true)) + .then(() => this.end()); + } +} diff --git a/src/phases/modifier-reward-phase.ts b/src/phases/modifier-reward-phase.ts index 1cdfd6b2721..e4fac33767f 100644 --- a/src/phases/modifier-reward-phase.ts +++ b/src/phases/modifier-reward-phase.ts @@ -22,10 +22,9 @@ export class ModifierRewardPhase extends BattlePhase { doReward(): Promise { return new Promise(resolve => { const newModifier = this.modifierType.newModifier(); - globalScene.addModifier(newModifier).then(() => { - globalScene.playSound("item_fanfare"); - globalScene.ui.showText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), null, () => resolve(), null, true); - }); + globalScene.addModifier(newModifier); + globalScene.playSound("item_fanfare"); + globalScene.ui.showText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), null, () => resolve(), null, true); }); } } diff --git a/src/phases/move-anim-phase.ts b/src/phases/move-anim-phase.ts new file mode 100644 index 00000000000..005445924a0 --- /dev/null +++ b/src/phases/move-anim-phase.ts @@ -0,0 +1,20 @@ +import type { MoveAnim } from "#app/data/battle-anims"; +import { Phase } from "#app/phase"; + +/** + * Plays the given {@linkcode MoveAnim} sequentially. + */ +export class MoveAnimPhase extends Phase { + constructor( + protected anim: Anim, + protected onSubstitute: boolean = false, + ) { + super(); + } + + public override start(): void { + super.start(); + + this.anim.play(this.onSubstitute, () => this.end()); + } +} diff --git a/src/phases/move-charge-phase.ts b/src/phases/move-charge-phase.ts index b0925f1f6cb..6eccdd20254 100644 --- a/src/phases/move-charge-phase.ts +++ b/src/phases/move-charge-phase.ts @@ -44,10 +44,9 @@ export class MoveChargePhase extends PokemonPhase { new MoveChargeAnim(move.chargeAnim, move.id, user).play(false, () => { move.showChargeText(user, target); - applyMoveChargeAttrs(MoveEffectAttr, user, target, move).then(() => { - user.addTag(BattlerTagType.CHARGING, 1, move.id, user.id); - this.end(); - }); + applyMoveChargeAttrs(MoveEffectAttr, user, target, move); + user.addTag(BattlerTagType.CHARGING, 1, move.id, user.id); + this.end(); }); } diff --git a/src/phases/move-effect-phase.ts b/src/phases/move-effect-phase.ts index 65d8d95cde6..f878cb40e2e 100644 --- a/src/phases/move-effect-phase.ts +++ b/src/phases/move-effect-phase.ts @@ -61,7 +61,7 @@ import { PokemonMultiHitModifier, } from "#app/modifier/modifier"; import { PokemonPhase } from "#app/phases/pokemon-phase"; -import { BooleanHolder, executeIf, isNullOrUndefined, NumberHolder } from "#app/utils"; +import { BooleanHolder, isNullOrUndefined, NumberHolder } from "#app/utils"; import { type nil } from "#app/utils"; import { BattlerTagType } from "#enums/battler-tag-type"; import type { Moves } from "#enums/moves"; @@ -143,86 +143,86 @@ export class MoveEffectPhase extends PokemonPhase { const move = this.move.getMove(); // Assume single target for override - applyMoveAttrs(OverrideMoveEffectAttr, user, this.getFirstTarget() ?? null, move, overridden, this.move.virtual).then(() => { - // If other effects were overriden, stop this phase before they can be applied - if (overridden.value) { - return this.end(); + applyMoveAttrs(OverrideMoveEffectAttr, user, this.getFirstTarget() ?? null, move, overridden, this.move.virtual); + + // If other effects were overriden, stop this phase before they can be applied + if (overridden.value) { + return this.end(); + } + + user.lapseTags(BattlerTagLapseType.MOVE_EFFECT); + + // If the user is acting again (such as due to Instruct), reset hitsLeft/hitCount so that + // the move executes correctly (ensures all hits of a multi-hit are properly calculated) + if (user.turnData.hitsLeft === 0 && user.turnData.hitCount > 0 && user.turnData.extraTurns > 0) { + user.turnData.hitsLeft = -1; + user.turnData.hitCount = 0; + user.turnData.extraTurns--; + } + + /** + * If this phase is for the first hit of the invoked move, + * resolve the move's total hit count. This block combines the + * effects of the move itself, Parental Bond, and Multi-Lens to do so. + */ + if (user.turnData.hitsLeft === -1) { + const hitCount = new NumberHolder(1); + // Assume single target for multi hit + applyMoveAttrs(MultiHitAttr, user, this.getFirstTarget() ?? null, move, hitCount); + // If Parental Bond is applicable, add another hit + applyPreAttackAbAttrs(AddSecondStrikeAbAttr, user, null, move, false, hitCount, null); + // If Multi-Lens is applicable, add hits equal to the number of held Multi-Lenses + globalScene.applyModifiers(PokemonMultiHitModifier, user.isPlayer(), user, move.id, hitCount); + // Set the user's relevant turnData fields to reflect the final hit count + user.turnData.hitCount = hitCount.value; + user.turnData.hitsLeft = hitCount.value; + } + + /** + * Log to be entered into the user's move history once the move result is resolved. + * Note that `result` (a {@linkcode MoveResult}) logs whether the move was successfully + * used in the sense of "Does it have an effect on the user?". + */ + const moveHistoryEntry = { move: this.move.moveId, targets: this.targets, result: MoveResult.PENDING, virtual: this.move.virtual }; + + /** + * Stores results of hit checks of the invoked move against all targets, organized by battler index. + * @see {@linkcode hitCheck} + */ + const targetHitChecks = Object.fromEntries(targets.map(p => [ p.getBattlerIndex(), this.hitCheck(p) ])); + const hasActiveTargets = targets.some(t => t.isActive(true)); + + /** Check if the target is immune via ability to the attacking move, and NOT in semi invulnerable state */ + const isImmune = targets[0]?.hasAbilityWithAttr(TypeImmunityAbAttr) + && (targets[0]?.getAbility()?.getAttrs(TypeImmunityAbAttr)?.[0]?.getImmuneType() === user.getMoveType(move)) + && !targets[0]?.getTag(SemiInvulnerableTag); + + const mayBounce = move.hasFlag(MoveFlags.REFLECTABLE) && !this.reflected && 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 + * (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 || (!mayBounce && !move.hasAttr(VariableTargetAttr) && !move.isMultiTarget() && !targetHitChecks[this.targets[0]] && !targets[0].getTag(ProtectedTag) && !isImmune)) { + this.stopMultiHit(); + if (hasActiveTargets) { + globalScene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: this.getFirstTarget() ? getPokemonNameWithAffix(this.getFirstTarget()!) : "" })); + moveHistoryEntry.result = MoveResult.MISS; + applyMoveAttrs(MissEffectAttr, user, null, this.move.getMove()); + } else { + globalScene.queueMessage(i18next.t("battle:attackFailed")); + moveHistoryEntry.result = MoveResult.FAIL; } + user.pushMoveHistory(moveHistoryEntry); + return this.end(); + } - user.lapseTags(BattlerTagLapseType.MOVE_EFFECT); - - // If the user is acting again (such as due to Instruct), reset hitsLeft/hitCount so that - // the move executes correctly (ensures all hits of a multi-hit are properly calculated) - if (user.turnData.hitsLeft === 0 && user.turnData.hitCount > 0 && user.turnData.extraTurns > 0) { - user.turnData.hitsLeft = -1; - user.turnData.hitCount = 0; - user.turnData.extraTurns--; - } - - /** - * If this phase is for the first hit of the invoked move, - * resolve the move's total hit count. This block combines the - * effects of the move itself, Parental Bond, and Multi-Lens to do so. - */ - if (user.turnData.hitsLeft === -1) { - const hitCount = new NumberHolder(1); - // Assume single target for multi hit - applyMoveAttrs(MultiHitAttr, user, this.getFirstTarget() ?? null, move, hitCount); - // If Parental Bond is applicable, add another hit - applyPreAttackAbAttrs(AddSecondStrikeAbAttr, user, null, move, false, hitCount, null); - // If Multi-Lens is applicable, add hits equal to the number of held Multi-Lenses - globalScene.applyModifiers(PokemonMultiHitModifier, user.isPlayer(), user, move.id, hitCount); - // Set the user's relevant turnData fields to reflect the final hit count - user.turnData.hitCount = hitCount.value; - user.turnData.hitsLeft = hitCount.value; - } - - /** - * Log to be entered into the user's move history once the move result is resolved. - * Note that `result` (a {@linkcode MoveResult}) logs whether the move was successfully - * used in the sense of "Does it have an effect on the user?". - */ - const moveHistoryEntry = { move: this.move.moveId, targets: this.targets, result: MoveResult.PENDING, virtual: this.move.virtual }; - - /** - * Stores results of hit checks of the invoked move against all targets, organized by battler index. - * @see {@linkcode hitCheck} - */ - const targetHitChecks = Object.fromEntries(targets.map(p => [ p.getBattlerIndex(), this.hitCheck(p) ])); - const hasActiveTargets = targets.some(t => t.isActive(true)); - - /** Check if the target is immune via ability to the attacking move, and NOT in semi invulnerable state */ - const isImmune = targets[0]?.hasAbilityWithAttr(TypeImmunityAbAttr) - && (targets[0]?.getAbility()?.getAttrs(TypeImmunityAbAttr)?.[0]?.getImmuneType() === user.getMoveType(move)) - && !targets[0]?.getTag(SemiInvulnerableTag); - - const mayBounce = move.hasFlag(MoveFlags.REFLECTABLE) && !this.reflected && 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 - * (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 || (!mayBounce && !move.hasAttr(VariableTargetAttr) && !move.isMultiTarget() && !targetHitChecks[this.targets[0]] && !targets[0].getTag(ProtectedTag) && !isImmune)) { - this.stopMultiHit(); - if (hasActiveTargets) { - globalScene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: this.getFirstTarget() ? getPokemonNameWithAffix(this.getFirstTarget()!) : "" })); - moveHistoryEntry.result = MoveResult.MISS; - applyMoveAttrs(MissEffectAttr, user, null, this.move.getMove()); - } else { - globalScene.queueMessage(i18next.t("battle:attackFailed")); - moveHistoryEntry.result = MoveResult.FAIL; - } - user.pushMoveHistory(moveHistoryEntry); - return this.end(); - } - - /** All move effect attributes are chained together in this array to be applied asynchronously. */ - const applyAttrs: Promise[] = []; - - 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()!), () => { + 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: boolean = false; @@ -313,7 +313,7 @@ export class MoveEffectPhase extends PokemonPhase { } /** Does this phase represent the invoked move's first strike? */ - const firstHit = (user.turnData.hitsLeft === user.turnData.hitCount); + const firstHit = user.turnData.hitsLeft === user.turnData.hitCount; // Only log the move's result on the first strike if (firstHit) { @@ -363,7 +363,7 @@ export class MoveEffectPhase extends PokemonPhase { } /** Does this phase represent the invoked move's last strike? */ - const lastHit = (user.turnData.hitsLeft === 1 || !this.getFirstTarget()?.isActive()); + const lastHit = user.turnData.hitsLeft === 1 || !this.getFirstTarget()?.isActive(); /** * If the user can change forms by using the invoked move, @@ -381,43 +381,29 @@ export class MoveEffectPhase extends PokemonPhase { } } - /** - * Create a Promise that applies *all* effects from the invoked move's MoveEffectAttrs. - * These are ordered by trigger type (see {@linkcode MoveEffectTrigger}), and each trigger - * type requires different conditions to be met with respect to the move's hit result. - */ - const k = new Promise((resolve) => { - //Start promise chain and apply PRE_APPLY move attributes - let promiseChain: Promise = applyFilteredMoveAttrs((attr: MoveAttr) => - attr instanceof MoveEffectAttr - && attr.trigger === MoveEffectTrigger.PRE_APPLY - && (!attr.firstHitOnly || firstHit) - && (!attr.lastHitOnly || lastHit) - && hitResult !== HitResult.NO_EFFECT, user, target, move); + applyFilteredMoveAttrs( + (attr: MoveAttr) => + attr instanceof MoveEffectAttr && + attr.trigger === MoveEffectTrigger.PRE_APPLY && + (!attr.firstHitOnly || firstHit) && + (!attr.lastHitOnly || lastHit) && + hitResult !== HitResult.NO_EFFECT, + user, + target, + move, + ); - /** Don't complete if the move failed */ - if (hitResult === HitResult.FAIL) { - return resolve(); - } - - /** Apply Move/Ability Effects in correct order */ - promiseChain = promiseChain - .then(this.applySelfTargetEffects(user, target, firstHit, lastHit)); + if (hitResult !== HitResult.FAIL) { + this.applySelfTargetEffects(user, target, firstHit, lastHit); if (hitResult !== HitResult.NO_EFFECT) { - promiseChain - .then(this.applyPostApplyEffects(user, target, firstHit, lastHit)) - .then(this.applyHeldItemFlinchCheck(user, target, dealsDamage)) - .then(this.applySuccessfulAttackEffects(user, target, firstHit, lastHit, !!isProtected, hitResult, firstTarget)) - .then(() => resolve()); + this.applyPostApplyEffects(user, target, firstHit, lastHit); + this.applyHeldItemFlinchCheck(user, target, dealsDamage); + this.applySuccessfulAttackEffects(user, target, firstHit, lastHit, !!isProtected, hitResult, firstTarget); } else { - promiseChain - .then(() => applyMoveAttrs(NoEffectAttr, user, null, move)) - .then(resolve); + applyMoveAttrs(NoEffectAttr, user, null, move); } - }); - - applyAttrs.push(k); + } } // Apply queued phases @@ -425,41 +411,35 @@ export class MoveEffectPhase extends PokemonPhase { globalScene.appendToPhase(queuedPhases, MoveEndPhase); } // Apply the move's POST_TARGET effects on the move's last hit, after all targeted effects have resolved - const postTarget = (user.turnData.hitsLeft === 1 || !this.getFirstTarget()?.isActive()) ? - applyFilteredMoveAttrs((attr: MoveAttr) => attr instanceof MoveEffectAttr && attr.trigger === MoveEffectTrigger.POST_TARGET, user, null, move) : - null; - - if (postTarget) { - if (applyAttrs.length) { // If there is a pending asynchronous move effect, do this after - applyAttrs[applyAttrs.length - 1].then(() => postTarget); - } else { // Otherwise, push a new asynchronous move effect - applyAttrs.push(postTarget); - } + if (user.turnData.hitsLeft === 1 || !this.getFirstTarget()?.isActive()) { + applyFilteredMoveAttrs( + (attr: MoveAttr) => attr instanceof MoveEffectAttr && attr.trigger === MoveEffectTrigger.POST_TARGET, + user, + null, + move, + ); } - // Wait for all move effects to finish applying, then end this phase - Promise.allSettled(applyAttrs).then(() => { - /** - * 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); + /** + * 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); } - - this.end(); }); - }); - }); + + 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 { @@ -500,8 +480,8 @@ export class MoveEffectPhase extends PokemonPhase { * @param lastHit - `true` if this is the last hit in a multi-hit attack * @returns a function intended to be passed into a `then()` call. */ - protected applySelfTargetEffects(user: Pokemon, target: Pokemon, firstHit: boolean, lastHit: boolean): () => Promise { - return () => applyFilteredMoveAttrs((attr: MoveAttr) => + protected applySelfTargetEffects(user: Pokemon, target: Pokemon, firstHit: boolean, lastHit: boolean): void { + applyFilteredMoveAttrs((attr: MoveAttr) => attr instanceof MoveEffectAttr && attr.trigger === MoveEffectTrigger.POST_APPLY && attr.selfTarget @@ -518,8 +498,8 @@ export class MoveEffectPhase extends PokemonPhase { * @param lastHit - `true` if this is the last hit in a multi-hit attack * @returns a function intended to be passed into a `then()` call. */ - protected applyPostApplyEffects(user: Pokemon, target: Pokemon, firstHit: boolean, lastHit: boolean): () => Promise { - return () => applyFilteredMoveAttrs((attr: MoveAttr) => + protected applyPostApplyEffects(user: Pokemon, target: Pokemon, firstHit: boolean, lastHit: boolean): void { + applyFilteredMoveAttrs((attr: MoveAttr) => attr instanceof MoveEffectAttr && attr.trigger === MoveEffectTrigger.POST_APPLY && !attr.selfTarget @@ -537,8 +517,8 @@ export class MoveEffectPhase extends PokemonPhase { * @param firstTarget - `true` if {@linkcode target} is the first target hit by this strike of {@linkcode move} * @returns a function intended to be passed into a `then()` call. */ - protected applyOnHitEffects(user: Pokemon, target: Pokemon, firstHit : boolean, lastHit: boolean, firstTarget: boolean): Promise { - return applyFilteredMoveAttrs((attr: MoveAttr) => + protected applyOnHitEffects(user: Pokemon, target: Pokemon, firstHit : boolean, lastHit: boolean, firstTarget: boolean): void { + applyFilteredMoveAttrs((attr: MoveAttr) => attr instanceof MoveEffectAttr && attr.trigger === MoveEffectTrigger.HIT && (!attr.firstHitOnly || firstHit) @@ -554,21 +534,18 @@ export class MoveEffectPhase extends PokemonPhase { * @param hitResult - The {@linkcode HitResult} of the attempted move * @returns a `Promise` intended to be passed into a `then()` call. */ - protected applyOnGetHitAbEffects(user: Pokemon, target: Pokemon, hitResult: HitResult): Promise { - return executeIf(!target.isFainted() || target.canApplyAbility(), () => - applyPostDefendAbAttrs(PostDefendAbAttr, target, user, this.move.getMove(), hitResult) - .then(() => { + protected applyOnGetHitAbEffects(user: Pokemon, target: Pokemon, hitResult: HitResult): void { + if (!target.isFainted() || target.canApplyAbility()) { + applyPostDefendAbAttrs(PostDefendAbAttr, target, user, this.move.getMove(), hitResult); - if (!this.move.getMove().hitsSubstitute(user, target)) { - if (!user.isPlayer() && this.move.getMove() instanceof AttackMove) { - globalScene.applyShuffledModifiers(EnemyAttackStatusEffectChanceModifier, false, target); - } + if (!this.move.getMove().hitsSubstitute(user, target)) { + if (!user.isPlayer() && this.move.getMove() instanceof AttackMove) { + globalScene.applyShuffledModifiers(EnemyAttackStatusEffectChanceModifier, false, target); + } - target.lapseTags(BattlerTagLapseType.AFTER_HIT); - } - - }) - ); + target.lapseTags(BattlerTagLapseType.AFTER_HIT); + } + } } /** @@ -583,17 +560,15 @@ export class MoveEffectPhase extends PokemonPhase { * @param firstTarget - `true` if {@linkcode target} is the first target hit by this strike of {@linkcode move} * @returns a function intended to be passed into a `then()` call. */ - protected applySuccessfulAttackEffects(user: Pokemon, target: Pokemon, firstHit : boolean, lastHit: boolean, isProtected : boolean, hitResult: HitResult, firstTarget: boolean) : () => Promise { - return () => executeIf(!isProtected, () => - this.applyOnHitEffects(user, target, firstHit, lastHit, firstTarget).then(() => - this.applyOnGetHitAbEffects(user, target, hitResult)).then(() => - applyPostAttackAbAttrs(PostAttackAbAttr, user, target, this.move.getMove(), hitResult)).then(() => { // Item Stealing Effects - - if (this.move.getMove() instanceof AttackMove) { - globalScene.applyModifiers(ContactHeldItemTransferChanceModifier, this.player, user, target); - } - }) - ); + protected applySuccessfulAttackEffects(user: Pokemon, target: Pokemon, firstHit: boolean, lastHit: boolean, isProtected: boolean, hitResult: HitResult, firstTarget: boolean): void { + if (!isProtected) { + this.applyOnHitEffects(user, target, firstHit, lastHit, firstTarget); + this.applyOnGetHitAbEffects(user, target, hitResult); + applyPostAttackAbAttrs(PostAttackAbAttr, user, target, this.move.getMove(), hitResult); + if (this.move.getMove() instanceof AttackMove) { + globalScene.applyModifiers(ContactHeldItemTransferChanceModifier, this.player, user, target); + } + } } /** @@ -603,20 +578,18 @@ export class MoveEffectPhase extends PokemonPhase { * @param dealsDamage - `true` if the attempted move successfully dealt damage * @returns a function intended to be passed into a `then()` call. */ - protected applyHeldItemFlinchCheck(user: Pokemon, target: Pokemon, dealsDamage: boolean) : () => void { - return () => { - if (this.move.getMove().hasAttr(FlinchAttr)) { - return; - } + protected applyHeldItemFlinchCheck(user: Pokemon, target: Pokemon, dealsDamage: boolean) : void { + if (this.move.getMove().hasAttr(FlinchAttr)) { + return; + } - if (dealsDamage && !target.hasAbilityWithAttr(IgnoreMoveEffectsAbAttr) && !this.move.getMove().hitsSubstitute(user, target)) { - const flinched = new BooleanHolder(false); - globalScene.applyModifiers(FlinchChanceModifier, user.isPlayer(), user, flinched); - if (flinched.value) { - target.addTag(BattlerTagType.FLINCHED, undefined, this.move.moveId, user.id); - } + if (dealsDamage && !target.hasAbilityWithAttr(IgnoreMoveEffectsAbAttr) && !this.move.getMove().hitsSubstitute(user, target)) { + const flinched = new BooleanHolder(false); + globalScene.applyModifiers(FlinchChanceModifier, user.isPlayer(), user, flinched); + if (flinched.value) { + target.addTag(BattlerTagType.FLINCHED, undefined, this.move.moveId, user.id); } - }; + } } /** diff --git a/src/phases/move-header-phase.ts b/src/phases/move-header-phase.ts index 6a982646b50..5b89548b663 100644 --- a/src/phases/move-header-phase.ts +++ b/src/phases/move-header-phase.ts @@ -22,9 +22,8 @@ export class MoveHeaderPhase extends BattlePhase { super.start(); if (this.canMove()) { - applyMoveAttrs(MoveHeaderAttr, this.pokemon, null, this.move.getMove()).then(() => this.end()); - } else { - this.end(); + applyMoveAttrs(MoveHeaderAttr, this.pokemon, null, this.move.getMove()); } + this.end(); } } diff --git a/src/phases/pokemon-transform-phase.ts b/src/phases/pokemon-transform-phase.ts new file mode 100644 index 00000000000..d67f758b1fd --- /dev/null +++ b/src/phases/pokemon-transform-phase.ts @@ -0,0 +1,77 @@ +import type { BattlerIndex } from "#app/battle"; +import { BattlerTagType } from "#enums/battler-tag-type"; +import { Moves } from "#enums/moves"; +import { EFFECTIVE_STATS, BATTLE_STATS } from "#enums/stat"; +import { PokemonMove } from "#app/field/pokemon"; +import { globalScene } from "#app/global-scene"; +import { PokemonPhase } from "./pokemon-phase"; + +/** + * Transforms a Pokemon into another Pokemon on the field. + * Used for Transform (move) and Imposter (ability) + */ +export class PokemonTransformPhase extends PokemonPhase { + protected targetIndex: BattlerIndex; + private playSound: boolean; + + constructor(userIndex: BattlerIndex, targetIndex: BattlerIndex, playSound: boolean = false) { + super(userIndex); + + this.targetIndex = targetIndex; + this.playSound = playSound; + } + + public override start(): void { + const user = this.getPokemon(); + const target = globalScene.getField(true).find((p) => p.getBattlerIndex() === this.targetIndex); + + if (!target) { + return this.end(); + } + + user.summonData.speciesForm = target.getSpeciesForm(); + user.summonData.ability = target.getAbility().id; + user.summonData.gender = target.getGender(); + + // Power Trick's effect is removed after using Transform + user.removeTag(BattlerTagType.POWER_TRICK); + + // Copy all stats (except HP) + for (const s of EFFECTIVE_STATS) { + user.setStat(s, target.getStat(s, false), false); + } + + // Copy all stat stages + for (const s of BATTLE_STATS) { + user.setStatStage(s, target.getStatStage(s)); + } + + user.summonData.moveset = target.getMoveset().map((m) => { + if (m) { + // If PP value is less than 5, do nothing. If greater, we need to reduce the value to 5. + return new PokemonMove(m.moveId, 0, 0, false, Math.min(m.getMove().pp, 5)); + } else { + console.warn(`Transform: somehow iterating over a ${m} value when copying moveset!`); + return new PokemonMove(Moves.NONE); + } + }); + user.summonData.types = target.getTypes(); + + const promises = [ user.updateInfo() ]; + + if (this.playSound) { + globalScene.playSound("battle_anims/PRSFX- Transform"); + } + + promises.push( + user.loadAssets(false).then(() => { + user.playAnim(); + user.updateInfo(); + // If the new ability activates immediately, it needs to happen after all the transform animations + user.setTempAbility(target.getAbility()); + }), + ); + + Promise.allSettled(promises).then(() => this.end()); + } +} diff --git a/src/phases/post-summon-phase.ts b/src/phases/post-summon-phase.ts index d76708b7050..b92d79501d4 100644 --- a/src/phases/post-summon-phase.ts +++ b/src/phases/post-summon-phase.ts @@ -27,12 +27,10 @@ export class PostSummonPhase extends PokemonPhase { pokemon.lapseTag(BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON); } - applyPostSummonAbAttrs(PostSummonAbAttr, pokemon) - .then(() => { - const field = pokemon.isPlayer() ? globalScene.getPlayerField() : globalScene.getEnemyField(); - field.forEach((p) => applyAbAttrs(CommanderAbAttr, p, null, false)); + applyPostSummonAbAttrs(PostSummonAbAttr, pokemon); + const field = pokemon.isPlayer() ? globalScene.getPlayerField() : globalScene.getEnemyField(); + field.forEach((p) => applyAbAttrs(CommanderAbAttr, p, null, false)); - this.end(); - }); + this.end(); } } diff --git a/src/phases/revival-blessing-phase.ts b/src/phases/revival-blessing-phase.ts new file mode 100644 index 00000000000..a063e325a31 --- /dev/null +++ b/src/phases/revival-blessing-phase.ts @@ -0,0 +1,61 @@ +import { SwitchType } from "#enums/switch-type"; +import { globalScene } from "#app/global-scene"; +import type { PartyOption } from "#app/ui/party-ui-handler"; +import PartyUiHandler, { PartyUiMode } 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 "#app/phases/battle-phase"; +import { SwitchSummonPhase } from "#app/phases/switch-summon-phase"; +import { ToggleDoublePositionPhase } from "#app/phases/toggle-double-position-phase"; +import type { PlayerPokemon } from "#app/field/pokemon"; + +/** + * Sets the Party UI and handles the effect of Revival Blessing + * when used by one of the player's Pokemon. + */ +export class RevivalBlessingPhase extends BattlePhase { + constructor(protected user: PlayerPokemon) { + super(); + } + + public override start(): void { + globalScene.ui.setMode( + Mode.PARTY, + PartyUiMode.REVIVAL_BLESSING, + this.user.getFieldIndex(), + (slotIndex: integer, option: PartyOption) => { + if (slotIndex >= 0 && slotIndex < 6) { + const pokemon = globalScene.getPlayerParty()[slotIndex]; + if (!pokemon || !pokemon.isFainted()) { + return this.end(); + } + + pokemon.resetTurnData(); + pokemon.resetStatus(); + pokemon.heal(Math.min(Utils.toDmgValue(0.5 * pokemon.getMaxHp()), pokemon.getMaxHp())); + globalScene.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: pokemon.name }), 0, true); + + if (globalScene.currentBattle.double && globalScene.getPlayerParty().length > 1) { + const allyPokemon = this.user.getAlly(); + if (slotIndex <= 1) { + // Revived ally pokemon + globalScene.unshiftPhase( + new SwitchSummonPhase(SwitchType.SWITCH, pokemon.getFieldIndex(), slotIndex, false, true), + ); + globalScene.unshiftPhase(new ToggleDoublePositionPhase(true)); + } else if (allyPokemon.isFainted()) { + // Revived party pokemon, and ally pokemon is fainted + globalScene.unshiftPhase( + new SwitchSummonPhase(SwitchType.SWITCH, allyPokemon.getFieldIndex(), slotIndex, false, true), + ); + globalScene.unshiftPhase(new ToggleDoublePositionPhase(true)); + } + } + } + globalScene.ui.setMode(Mode.MESSAGE).then(() => this.end()); + }, + PartyUiHandler.FilterFainted, + ); + } +} diff --git a/src/phases/ribbon-modifier-reward-phase.ts b/src/phases/ribbon-modifier-reward-phase.ts index 8cf15ba8f2c..72a8f4bf37c 100644 --- a/src/phases/ribbon-modifier-reward-phase.ts +++ b/src/phases/ribbon-modifier-reward-phase.ts @@ -17,17 +17,16 @@ export class RibbonModifierRewardPhase extends ModifierRewardPhase { doReward(): Promise { return new Promise(resolve => { const newModifier = this.modifierType.newModifier(); - globalScene.addModifier(newModifier).then(() => { - globalScene.playSound("level_up_fanfare"); - globalScene.ui.setMode(Mode.MESSAGE); - globalScene.ui.showText(i18next.t("battle:beatModeFirstTime", { - speciesName: this.species.name, - gameMode: globalScene.gameMode.getName(), - newModifier: newModifier?.type.name - }), null, () => { - resolve(); - }, null, true, 1500); - }); + globalScene.addModifier(newModifier); + globalScene.playSound("level_up_fanfare"); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:beatModeFirstTime", { + speciesName: this.species.name, + gameMode: globalScene.gameMode.getName(), + newModifier: newModifier?.type.name, + }), null, () => { + resolve(); + }, null, true, 1500); }); } } diff --git a/src/phases/select-modifier-phase.ts b/src/phases/select-modifier-phase.ts index a3a2fa1aa24..36f18a8d64d 100644 --- a/src/phases/select-modifier-phase.ts +++ b/src/phases/select-modifier-phase.ts @@ -171,30 +171,21 @@ export class SelectModifierPhase extends BattlePhase { } if (cost && !(modifier.type instanceof RememberMoveModifierType)) { - result.then(success => { - if (success) { - if (!Overrides.WAIVE_ROLL_FEE_OVERRIDE) { - globalScene.money -= cost; - globalScene.updateMoneyText(); - globalScene.animateMoneyChanged(false); - } - globalScene.playSound("se/buy"); - (globalScene.ui.getHandler() as ModifierSelectUiHandler).updateCostText(); - } else { - globalScene.ui.playError(); + if (result) { + if (!Overrides.WAIVE_ROLL_FEE_OVERRIDE) { + globalScene.money -= cost; + globalScene.updateMoneyText(); + globalScene.animateMoneyChanged(false); } - }); - } else { - const doEnd = () => { - globalScene.ui.clearText(); - globalScene.ui.setMode(Mode.MESSAGE); - super.end(); - }; - if (result instanceof Promise) { - result.then(() => doEnd()); + globalScene.playSound("se/buy"); + (globalScene.ui.getHandler() as ModifierSelectUiHandler).updateCostText(); } else { - doEnd(); + globalScene.ui.playError(); } + } else { + globalScene.ui.clearText(); + globalScene.ui.setMode(Mode.MESSAGE); + super.end(); } }; @@ -304,7 +295,7 @@ export class SelectModifierPhase extends BattlePhase { ); } - addModifier(modifier: Modifier): Promise { + addModifier(modifier: Modifier): boolean { return globalScene.addModifier(modifier, false, true); } } diff --git a/src/test/abilities/unburden.test.ts b/src/test/abilities/unburden.test.ts index a652f55d591..9c5f6c2d185 100644 --- a/src/test/abilities/unburden.test.ts +++ b/src/test/abilities/unburden.test.ts @@ -391,7 +391,7 @@ describe("Abilities - Unburden", () => { await game.forceEnemyMove(Moves.THIEF, BattlerIndex.PLAYER); await game.forceEnemyMove(Moves.SPLASH); await game.setTurnOrder([ BattlerIndex.PLAYER, BattlerIndex.ENEMY, BattlerIndex.ENEMY_2, BattlerIndex.PLAYER_2 ]); - game.doSelectPartyPokemon(0, "MoveEffectPhase"); + game.doSelectPartyPokemon(0, "RevivalBlessingPhase"); await game.toNextTurn(); expect(game.scene.getPlayerField()[0]).toBe(treecko); diff --git a/src/test/moves/revival_blessing.test.ts b/src/test/moves/revival_blessing.test.ts new file mode 100644 index 00000000000..cdde3941d30 --- /dev/null +++ b/src/test/moves/revival_blessing.test.ts @@ -0,0 +1,117 @@ +import { BattlerIndex } from "#app/battle"; +import { MoveResult } from "#app/field/pokemon"; +import { toDmgValue } from "#app/utils"; +import { Abilities } from "#enums/abilities"; +import { Moves } from "#enums/moves"; +import { Species } from "#enums/species"; +import GameManager from "#test/utils/gameManager"; +import Phaser from "phaser"; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; + +describe("Moves - Revival Blessing", () => { + 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, Moves.REVIVAL_BLESSING, Moves.MEMENTO ]) + .ability(Abilities.BALL_FETCH) + .battleType("single") + .disableCrits() + .enemySpecies(Species.MAGIKARP) + .enemyAbility(Abilities.BALL_FETCH) + .enemyMoveset(Moves.SPLASH); + }); + + it("should revive a selected fainted Pokemon when used by the player", async () => { + await game.classicMode.startBattle([ Species.FEEBAS, Species.MAGIKARP ]); + + game.move.select(Moves.MEMENTO); + game.doSelectPartyPokemon(1, "SwitchPhase"); + await game.toNextTurn(); + + const player = game.scene.getPlayerPokemon()!; + + expect(player.species.speciesId).toBe(Species.MAGIKARP); + game.move.select(Moves.REVIVAL_BLESSING); + + await game.setTurnOrder([ BattlerIndex.PLAYER, BattlerIndex.ENEMY ]); + game.doSelectPartyPokemon(1, "RevivalBlessingPhase"); + + await game.phaseInterceptor.to("MoveEndPhase", false); + + const revivedPokemon = game.scene.getPlayerParty()[1]; + expect(revivedPokemon.status?.effect).toBeFalsy(); + expect(revivedPokemon.hp).toBe(Math.floor(revivedPokemon.getMaxHp() / 2)); + }); + + it("should revive a random fainted enemy when used by an enemy Trainer", async () => { + game.override.enemyMoveset(Moves.REVIVAL_BLESSING).startingWave(8); + + await game.classicMode.startBattle([ Species.MAGIKARP ]); + + game.move.select(Moves.SPLASH); + await game.doKillOpponents(); + + await game.toNextTurn(); + game.move.select(Moves.SPLASH); + await game.setTurnOrder([ BattlerIndex.ENEMY, BattlerIndex.PLAYER ]); + + await game.phaseInterceptor.to("MoveEndPhase", false); + + const revivedPokemon = game.scene.getEnemyParty()[1]; + expect(revivedPokemon.status?.effect).toBeFalsy(); + expect(revivedPokemon.hp).toBe(Math.floor(revivedPokemon.getMaxHp() / 2)); + }); + + it("should fail when there are no fainted Pokemon to target", async () => { + await game.classicMode.startBattle([ Species.FEEBAS, Species.MAGIKARP ]); + + game.move.select(Moves.REVIVAL_BLESSING); + await game.setTurnOrder([ BattlerIndex.PLAYER, BattlerIndex.ENEMY ]); + await game.phaseInterceptor.to("MoveEndPhase", false); + + const player = game.scene.getPlayerPokemon()!; + expect(player.getLastXMoves()[0].result).toBe(MoveResult.FAIL); + }); + + it("should revive a player pokemon and immediately send it back out if used in the same turn it fainted in doubles", async () => { + game.override + .battleType("double") + .enemyMoveset([ Moves.SPLASH, Moves.FISSURE ]) + .enemyAbility(Abilities.NO_GUARD) + .enemyLevel(100); + await game.classicMode.startBattle([ Species.FEEBAS, Species.MILOTIC, Species.GYARADOS ]); + + const feebas = game.scene.getPlayerField()[0]; + + game.move.select(Moves.SPLASH); + game.move.select(Moves.REVIVAL_BLESSING, 1); + await game.forceEnemyMove(Moves.FISSURE, BattlerIndex.PLAYER); + await game.forceEnemyMove(Moves.SPLASH); + await game.setTurnOrder([ BattlerIndex.PLAYER, BattlerIndex.ENEMY, BattlerIndex.ENEMY_2, BattlerIndex.PLAYER_2 ]); + + await game.phaseInterceptor.to("MoveEndPhase"); + await game.phaseInterceptor.to("MoveEndPhase"); + + expect(feebas.isFainted()).toBe(true); + + game.doSelectPartyPokemon(0, "RevivalBlessingPhase"); + await game.toNextTurn(); + + expect(feebas.isFainted()).toBe(false); + expect(feebas.hp).toBe(toDmgValue(0.5 * feebas.getMaxHp())); + expect(game.scene.getPlayerField()[0]).toBe(feebas); + }); +}); diff --git a/src/test/mystery-encounter/encounters/clowning-around-encounter.test.ts b/src/test/mystery-encounter/encounters/clowning-around-encounter.test.ts index f105678e71f..f95450bbf44 100644 --- a/src/test/mystery-encounter/encounters/clowning-around-encounter.test.ts +++ b/src/test/mystery-encounter/encounters/clowning-around-encounter.test.ts @@ -375,6 +375,6 @@ describe("Clowning Around - Mystery Encounter", () => { async function addItemToPokemon(scene: BattleScene, pokemon: Pokemon, stackCount: number, itemType: PokemonHeldItemModifierType) { const itemMod = itemType.newModifier(pokemon) as PokemonHeldItemModifier; itemMod.stackCount = stackCount; - await scene.addModifier(itemMod, true, false, false, true); + scene.addModifier(itemMod, true, false, false, true); await scene.updateModifiers(true); } diff --git a/src/test/mystery-encounter/encounters/dancing-lessons-encounter.test.ts b/src/test/mystery-encounter/encounters/dancing-lessons-encounter.test.ts index 795e6b6650b..ceb457666d7 100644 --- a/src/test/mystery-encounter/encounters/dancing-lessons-encounter.test.ts +++ b/src/test/mystery-encounter/encounters/dancing-lessons-encounter.test.ts @@ -123,8 +123,6 @@ describe("Dancing Lessons - Mystery Encounter", () => { partyLead.level = 1000; partyLead.calculateStats(); await runMysteryEncounterToEnd(game, 1, undefined, true); - // For some reason updateModifiers breaks in this test and does not resolve promise - vi.spyOn(game.scene, "updateModifiers").mockImplementation(() => new Promise(resolve => resolve())); await skipBattleRunMysteryEncounterRewardsPhase(game); await game.phaseInterceptor.to(SelectModifierPhase, false); expect(scene.getCurrentPhase()?.constructor.name).toBe(SelectModifierPhase.name); diff --git a/src/test/mystery-encounter/encounters/delibirdy-encounter.test.ts b/src/test/mystery-encounter/encounters/delibirdy-encounter.test.ts index f99aa24805e..8121916a4d7 100644 --- a/src/test/mystery-encounter/encounters/delibirdy-encounter.test.ts +++ b/src/test/mystery-encounter/encounters/delibirdy-encounter.test.ts @@ -123,7 +123,7 @@ describe("Delibird-y - Mystery Encounter", () => { scene.modifiers = []; const amuletCoin = generateModifierType(modifierTypes.AMULET_COIN)!.newModifier() as MoneyMultiplierModifier; amuletCoin.stackCount = 5; - await scene.addModifier(amuletCoin, true, false, false, true); + scene.addModifier(amuletCoin, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 1); @@ -193,7 +193,7 @@ describe("Delibird-y - Mystery Encounter", () => { const sitrus = generateModifierType(modifierTypes.BERRY, [ BerryType.SITRUS ])!; const sitrusMod = sitrus.newModifier(scene.getPlayerParty()[0]) as BerryModifier; sitrusMod.stackCount = 2; - await scene.addModifier(sitrusMod, true, false, false, true); + scene.addModifier(sitrusMod, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 2, { pokemonNo: 1, optionNo: 1 }); @@ -214,7 +214,7 @@ describe("Delibird-y - Mystery Encounter", () => { const revSeed = generateModifierType(modifierTypes.REVIVER_SEED)!; const modifier = revSeed.newModifier(scene.getPlayerParty()[0]) as PokemonInstantReviveModifier; modifier.stackCount = 1; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 2, { pokemonNo: 1, optionNo: 1 }); @@ -234,13 +234,13 @@ describe("Delibird-y - Mystery Encounter", () => { scene.modifiers = []; const candyJar = generateModifierType(modifierTypes.CANDY_JAR)!.newModifier() as LevelIncrementBoosterModifier; candyJar.stackCount = 99; - await scene.addModifier(candyJar, true, false, false, true); + scene.addModifier(candyJar, true, false, false, true); const sitrus = generateModifierType(modifierTypes.BERRY, [ BerryType.SITRUS ])!; // Sitrus berries on party const sitrusMod = sitrus.newModifier(scene.getPlayerParty()[0]) as BerryModifier; sitrusMod.stackCount = 2; - await scene.addModifier(sitrusMod, true, false, false, true); + scene.addModifier(sitrusMod, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 2, { pokemonNo: 1, optionNo: 1 }); @@ -263,13 +263,13 @@ describe("Delibird-y - Mystery Encounter", () => { scene.modifiers = []; const healingCharm = generateModifierType(modifierTypes.BERRY_POUCH)!.newModifier() as PreserveBerryModifier; healingCharm.stackCount = 3; - await scene.addModifier(healingCharm, true, false, false, true); + scene.addModifier(healingCharm, true, false, false, true); // Set 1 Reviver Seed on party lead const revSeed = generateModifierType(modifierTypes.REVIVER_SEED)!; const modifier = revSeed.newModifier(scene.getPlayerParty()[0]) as PokemonInstantReviveModifier; modifier.stackCount = 1; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 2, { pokemonNo: 1, optionNo: 1 }); @@ -292,7 +292,7 @@ describe("Delibird-y - Mystery Encounter", () => { scene.modifiers = []; const soulDew = generateModifierType(modifierTypes.SOUL_DEW)!; const modifier = soulDew.newModifier(scene.getPlayerParty()[0]); - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await game.phaseInterceptor.to(MysteryEncounterPhase, false); @@ -321,7 +321,7 @@ describe("Delibird-y - Mystery Encounter", () => { const revSeed = generateModifierType(modifierTypes.REVIVER_SEED)!; const modifier = revSeed.newModifier(scene.getPlayerParty()[0]) as PokemonInstantReviveModifier; modifier.stackCount = 1; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 2, { pokemonNo: 1, optionNo: 1 }); @@ -355,7 +355,7 @@ describe("Delibird-y - Mystery Encounter", () => { const soulDew = generateModifierType(modifierTypes.SOUL_DEW)!; const modifier = soulDew.newModifier(scene.getPlayerParty()[0]) as PokemonNatureWeightModifier; modifier.stackCount = 2; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 3, { pokemonNo: 1, optionNo: 1 }); @@ -376,7 +376,7 @@ describe("Delibird-y - Mystery Encounter", () => { const soulDew = generateModifierType(modifierTypes.SOUL_DEW)!; const modifier = soulDew.newModifier(scene.getPlayerParty()[0]) as PokemonNatureWeightModifier; modifier.stackCount = 1; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 3, { pokemonNo: 1, optionNo: 1 }); @@ -396,13 +396,13 @@ describe("Delibird-y - Mystery Encounter", () => { scene.modifiers = []; const healingCharm = generateModifierType(modifierTypes.HEALING_CHARM)!.newModifier() as HealingBoosterModifier; healingCharm.stackCount = 5; - await scene.addModifier(healingCharm, true, false, false, true); + scene.addModifier(healingCharm, true, false, false, true); // Set 1 Soul Dew on party lead const soulDew = generateModifierType(modifierTypes.SOUL_DEW)!; const modifier = soulDew.newModifier(scene.getPlayerParty()[0]) as PokemonNatureWeightModifier; modifier.stackCount = 1; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 3, { pokemonNo: 1, optionNo: 1 }); @@ -425,7 +425,7 @@ describe("Delibird-y - Mystery Encounter", () => { scene.modifiers = []; const revSeed = generateModifierType(modifierTypes.REVIVER_SEED)!; const modifier = revSeed.newModifier(scene.getPlayerParty()[0]); - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await game.phaseInterceptor.to(MysteryEncounterPhase, false); @@ -455,7 +455,7 @@ describe("Delibird-y - Mystery Encounter", () => { const soulDew = generateModifierType(modifierTypes.SOUL_DEW)!; const modifier = soulDew.newModifier(scene.getPlayerParty()[0]) as PokemonNatureWeightModifier; modifier.stackCount = 1; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 3, { pokemonNo: 1, optionNo: 1 }); diff --git a/src/test/mystery-encounter/encounters/global-trade-system-encounter.test.ts b/src/test/mystery-encounter/encounters/global-trade-system-encounter.test.ts index fb5801c941a..60780984014 100644 --- a/src/test/mystery-encounter/encounters/global-trade-system-encounter.test.ts +++ b/src/test/mystery-encounter/encounters/global-trade-system-encounter.test.ts @@ -224,7 +224,7 @@ describe("Global Trade System - Mystery Encounter", () => { const soulDew = generateModifierType(modifierTypes.SOUL_DEW)!; const modifier = soulDew.newModifier(scene.getPlayerParty()[0]) as PokemonNatureWeightModifier; modifier.stackCount = 2; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 3, { pokemonNo: 1, optionNo: 1 }); @@ -249,7 +249,7 @@ describe("Global Trade System - Mystery Encounter", () => { const soulDew = generateModifierType(modifierTypes.SOUL_DEW)!; const modifier = soulDew.newModifier(scene.getPlayerParty()[0]) as PokemonNatureWeightModifier; modifier.stackCount = 1; - await scene.addModifier(modifier, true, false, false, true); + scene.addModifier(modifier, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 3, { pokemonNo: 1, optionNo: 1 }); diff --git a/src/test/mystery-encounter/encounters/uncommon-breed-encounter.test.ts b/src/test/mystery-encounter/encounters/uncommon-breed-encounter.test.ts index 39904c030a3..06bd382879f 100644 --- a/src/test/mystery-encounter/encounters/uncommon-breed-encounter.test.ts +++ b/src/test/mystery-encounter/encounters/uncommon-breed-encounter.test.ts @@ -216,11 +216,11 @@ describe("Uncommon Breed - Mystery Encounter", () => { const sitrus = generateModifierType(modifierTypes.BERRY, [ BerryType.SITRUS ])!; const sitrusMod = sitrus.newModifier(scene.getPlayerParty()[0]) as BerryModifier; sitrusMod.stackCount = 2; - await scene.addModifier(sitrusMod, true, false, false, true); + scene.addModifier(sitrusMod, true, false, false, true); const ganlon = generateModifierType(modifierTypes.BERRY, [ BerryType.GANLON ])!; const ganlonMod = ganlon.newModifier(scene.getPlayerParty()[0]) as BerryModifier; ganlonMod.stackCount = 3; - await scene.addModifier(ganlonMod, true, false, false, true); + scene.addModifier(ganlonMod, true, false, false, true); await scene.updateModifiers(true); await runMysteryEncounterToEnd(game, 2); diff --git a/src/test/utils/gameWrapper.ts b/src/test/utils/gameWrapper.ts index ca5a67f901a..3ba9cae3c8d 100644 --- a/src/test/utils/gameWrapper.ts +++ b/src/test/utils/gameWrapper.ts @@ -91,6 +91,7 @@ export default class GameWrapper { Pokemon.prototype.updateFusionPalette = () => null; Pokemon.prototype.cry = () => null; Pokemon.prototype.faintCry = (cb) => { if (cb) cb(); }; + BattleScene.prototype.addPokemonIcon = () => new Phaser.GameObjects.Container(this.scene); } setScene(scene: BattleScene) { diff --git a/src/test/utils/phaseInterceptor.ts b/src/test/utils/phaseInterceptor.ts index d60e0e78373..91f98e89ec3 100644 --- a/src/test/utils/phaseInterceptor.ts +++ b/src/test/utils/phaseInterceptor.ts @@ -60,6 +60,7 @@ import { RibbonModifierRewardPhase } from "#app/phases/ribbon-modifier-reward-ph import { GameOverModifierRewardPhase } from "#app/phases/game-over-modifier-reward-phase"; import { UnlockPhase } from "#app/phases/unlock-phase"; import { PostGameOverPhase } from "#app/phases/post-game-over-phase"; +import { RevivalBlessingPhase } from "#app/phases/revival-blessing-phase"; export interface PromptHandler { phaseTarget?: string; @@ -126,7 +127,8 @@ type PhaseClass = | typeof EncounterPhase | typeof GameOverPhase | typeof UnlockPhase - | typeof PostGameOverPhase; + | typeof PostGameOverPhase + | typeof RevivalBlessingPhase; type PhaseString = | "LoginPhase" @@ -185,7 +187,8 @@ type PhaseString = | "EncounterPhase" | "GameOverPhase" | "UnlockPhase" - | "PostGameOverPhase"; + | "PostGameOverPhase" + | "RevivalBlessingPhase"; type PhaseInterceptorPhase = PhaseClass | PhaseString; @@ -269,6 +272,7 @@ export default class PhaseInterceptor { [ GameOverPhase, this.startPhase ], [ UnlockPhase, this.startPhase ], [ PostGameOverPhase, this.startPhase ], + [ RevivalBlessingPhase, this.startPhase ], ]; private endBySetMode = [ @@ -511,11 +515,11 @@ export default class PhaseInterceptor { if (expireFn) { this.prompts.shift(); } else if ( - currentMode === actionForNextPrompt.mode - && currentPhase === actionForNextPrompt.phaseTarget - && currentHandler.active - && (!actionForNextPrompt.awaitingActionInput - || (actionForNextPrompt.awaitingActionInput && currentHandler.awaitingActionInput)) + currentMode === actionForNextPrompt.mode && + currentPhase === actionForNextPrompt.phaseTarget && + currentHandler.active && + (!actionForNextPrompt.awaitingActionInput || + (actionForNextPrompt.awaitingActionInput && currentHandler.awaitingActionInput)) ) { const prompt = this.prompts.shift(); if (prompt?.callback) {