Replace various scene pass-arounds with global scene variable

This commit is contained in:
NightKev 2024-10-31 01:28:45 -07:00
parent 5755180279
commit 7dc8f2427c
254 changed files with 7810 additions and 7879 deletions

View File

@ -1,3 +1 @@
import BattleScene from "#app/battle-scene";
export type ConditionFn = (scene: BattleScene, args?: any[]) => boolean;
export type ConditionFn = (args?: any[]) => boolean;

View File

@ -99,6 +99,8 @@ import { FRIENDSHIP_GAIN_FROM_BATTLE } from "#app/data/balance/starters";
export const bypassLogin = import.meta.env.VITE_BYPASS_LOGIN === "1";
export let gScene: BattleScene;
const DEBUG_RNG = false;
const OPP_IVS_OVERRIDE_VALIDATED : integer[] = (
@ -324,6 +326,7 @@ export default class BattleScene extends SceneBase {
this.phaseQueuePrependSpliceIndex = -1;
this.nextCommandPhaseQueue = [];
this.updateGameInfo();
gScene = this;
}
loadPokemonAtlas(key: string, atlasPath: string, experimental?: boolean) {
@ -342,14 +345,13 @@ export default class BattleScene extends SceneBase {
async preload() {
if (DEBUG_RNG) {
const scene = this;
const originalRealInRange = Phaser.Math.RND.realInRange;
Phaser.Math.RND.realInRange = function (min: number, max: number): number {
const ret = originalRealInRange.apply(this, [ min, max ]);
const args = [ "RNG", ++scene.rngCounter, ret / (max - min), `min: ${min} / max: ${max}` ];
args.push(`seed: ${scene.rngSeedOverride || scene.waveSeed || scene.seed}`);
if (scene.rngOffset) {
args.push(`offset: ${scene.rngOffset}`);
const args = [ "RNG", ++gScene.rngCounter, ret / (max - min), `min: ${min} / max: ${max}` ];
args.push(`seed: ${gScene.rngSeedOverride || gScene.waveSeed || gScene.seed}`);
if (gScene.rngOffset) {
args.push(`offset: ${gScene.rngOffset}`);
}
console.log(...args);
return ret;
@ -362,14 +364,14 @@ export default class BattleScene extends SceneBase {
}
create() {
this.scene.remove(LoadingScene.KEY);
gScene.scene.remove(LoadingScene.KEY);
initGameSpeed.apply(this);
this.inputController = new InputsController(this);
this.uiInputs = new UiInputs(this, this.inputController);
this.inputController = new InputsController();
this.uiInputs = new UiInputs(this.inputController);
this.gameData = new GameData(this);
this.gameData = new GameData();
addUiThemeOverrides(this);
addUiThemeOverrides();
this.load.setBaseURL();
@ -457,76 +459,76 @@ export default class BattleScene extends SceneBase {
this.modifiers = [];
this.enemyModifiers = [];
this.modifierBar = new ModifierBar(this);
this.modifierBar = new ModifierBar();
this.modifierBar.setName("modifier-bar");
this.add.existing(this.modifierBar);
uiContainer.add(this.modifierBar);
this.enemyModifierBar = new ModifierBar(this, true);
this.enemyModifierBar = new ModifierBar(true);
this.enemyModifierBar.setName("enemy-modifier-bar");
this.add.existing(this.enemyModifierBar);
uiContainer.add(this.enemyModifierBar);
this.charSprite = new CharSprite(this);
this.charSprite = new CharSprite();
this.charSprite.setName("sprite-char");
this.charSprite.setup();
this.fieldUI.add(this.charSprite);
this.pbTray = new PokeballTray(this, true);
this.pbTray = new PokeballTray(true);
this.pbTray.setName("pb-tray");
this.pbTray.setup();
this.pbTrayEnemy = new PokeballTray(this, false);
this.pbTrayEnemy = new PokeballTray(false);
this.pbTrayEnemy.setName("enemy-pb-tray");
this.pbTrayEnemy.setup();
this.fieldUI.add(this.pbTray);
this.fieldUI.add(this.pbTrayEnemy);
this.abilityBar = new AbilityBar(this);
this.abilityBar = new AbilityBar();
this.abilityBar.setName("ability-bar");
this.abilityBar.setup();
this.fieldUI.add(this.abilityBar);
this.partyExpBar = new PartyExpBar(this);
this.partyExpBar = new PartyExpBar();
this.partyExpBar.setName("party-exp-bar");
this.partyExpBar.setup();
this.fieldUI.add(this.partyExpBar);
this.candyBar = new CandyBar(this);
this.candyBar = new CandyBar();
this.candyBar.setName("candy-bar");
this.candyBar.setup();
this.fieldUI.add(this.candyBar);
this.biomeWaveText = addTextObject(this, (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, (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, (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, (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, (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);
this.fieldUI.add(this.luckLabelText);
this.arenaFlyout = new ArenaFlyout(this);
this.arenaFlyout = new ArenaFlyout();
this.fieldUI.add(this.arenaFlyout);
this.fieldUI.moveBelow<Phaser.GameObjects.GameObject>(this.arenaFlyout, this.fieldOverlay);
@ -535,9 +537,9 @@ export default class BattleScene extends SceneBase {
this.damageNumberHandler = new DamageNumberHandler();
this.spriteSparkleHandler = new PokemonSpriteSparkleHandler();
this.spriteSparkleHandler.setup(this);
this.spriteSparkleHandler.setup();
this.pokemonInfoContainer = new PokemonInfoContainer(this, (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);
@ -546,13 +548,13 @@ export default class BattleScene extends SceneBase {
const loadPokemonAssets = [];
this.arenaPlayer = new ArenaBase(this, true);
this.arenaPlayer = new ArenaBase(true);
this.arenaPlayer.setName("arena-player");
this.arenaPlayerTransition = new ArenaBase(this, true);
this.arenaPlayerTransition = new ArenaBase(true);
this.arenaPlayerTransition.setName("arena-player-transition");
this.arenaEnemy = new ArenaBase(this, false);
this.arenaEnemy = new ArenaBase(false);
this.arenaEnemy.setName("arena-enemy");
this.arenaNextEnemy = new ArenaBase(this, false);
this.arenaNextEnemy = new ArenaBase(false);
this.arenaNextEnemy.setName("arena-next-enemy");
this.arenaBgTransition.setVisible(false);
@ -593,7 +595,7 @@ export default class BattleScene extends SceneBase {
this.reset(false, false, true);
const ui = new UI(this);
const ui = new UI();
this.uiContainer.add(ui);
this.ui = ui;
@ -604,12 +606,12 @@ export default class BattleScene extends SceneBase {
Promise.all([
Promise.all(loadPokemonAssets),
initCommonAnims(this).then(() => loadCommonAnimAssets(this, true)),
Promise.all([ Moves.TACKLE, Moves.TAIL_WHIP, Moves.FOCUS_ENERGY, Moves.STRUGGLE ].map(m => initMoveAnim(this, m))).then(() => loadMoveAnimAssets(this, defaultMoves, true)),
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()
]).then(() => {
this.pushPhase(new LoginPhase(this));
this.pushPhase(new TitlePhase(this));
this.pushPhase(new LoginPhase());
this.pushPhase(new TitlePhase());
this.shiftPhase();
});
@ -871,7 +873,7 @@ export default class BattleScene extends SceneBase {
}
addPlayerPokemon(species: PokemonSpecies, level: integer, abilityIndex?: integer, formIndex?: integer, gender?: Gender, shiny?: boolean, variant?: Variant, ivs?: integer[], nature?: Nature, dataSource?: Pokemon | PokemonData, postProcess?: (playerPokemon: PlayerPokemon) => void): PlayerPokemon {
const pokemon = new PlayerPokemon(this, species, level, abilityIndex, formIndex, gender, shiny, variant, ivs, nature, dataSource);
const pokemon = new PlayerPokemon(species, level, abilityIndex, formIndex, gender, shiny, variant, ivs, nature, dataSource);
if (postProcess) {
postProcess(pokemon);
}
@ -889,13 +891,13 @@ export default class BattleScene extends SceneBase {
boss = this.getEncounterBossSegments(this.currentBattle.waveIndex, level, species) > 1;
}
const pokemon = new EnemyPokemon(this, species, level, trainerSlot, boss, dataSource);
const pokemon = new EnemyPokemon(species, level, trainerSlot, boss, dataSource);
if (Overrides.OPP_FUSION_OVERRIDE) {
pokemon.generateFusionSpecies();
}
overrideModifiers(this, false);
overrideHeldItems(this, pokemon, false);
overrideModifiers(false);
overrideHeldItems(pokemon, false);
if (boss && !dataSource) {
const secondaryIvs = Utils.getIvsFromId(Utils.randSeedInt(4294967296));
@ -1034,12 +1036,12 @@ export default class BattleScene extends SceneBase {
* @returns A random integer between {@linkcode min} and ({@linkcode min} + {@linkcode range} - 1)
*/
randBattleSeedInt(range: integer, min: integer = 0): integer {
return this.currentBattle?.randSeedInt(this, range, min);
return this.currentBattle?.randSeedInt(range, min);
}
reset(clearScene: boolean = false, clearData: boolean = false, reloadI18n: boolean = false): void {
if (clearData) {
this.gameData = new GameData(this);
this.gameData = new GameData();
}
this.gameMode = getGameMode(GameModes.CLASSIC);
@ -1172,7 +1174,7 @@ export default class BattleScene extends SceneBase {
battleConfig = this.gameMode.getFixedBattle(newWaveIndex);
newDouble = battleConfig.double;
newBattleType = battleConfig.battleType;
this.executeWithSeedOffset(() => newTrainer = battleConfig?.getTrainer(this), (battleConfig.seedOffsetWaveIndex || newWaveIndex) << 8);
this.executeWithSeedOffset(() => newTrainer = battleConfig?.getTrainer(), (battleConfig.seedOffsetWaveIndex || newWaveIndex) << 8);
if (newTrainer) {
this.field.add(newTrainer);
}
@ -1198,7 +1200,7 @@ export default class BattleScene extends SceneBase {
}
}
const variant = doubleTrainer ? TrainerVariant.DOUBLE : (Utils.randSeedInt(2) ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT);
newTrainer = trainerData !== undefined ? trainerData.toTrainer(this) : new Trainer(this, trainerType, variant);
newTrainer = trainerData !== undefined ? trainerData.toTrainer() : new Trainer(trainerType, variant);
this.field.add(newTrainer);
}
@ -1243,7 +1245,7 @@ export default class BattleScene extends SceneBase {
this.executeWithSeedOffset(() => {
this.currentBattle = new Battle(this.gameMode, newWaveIndex, newBattleType, newTrainer, newDouble);
}, newWaveIndex << 3, this.waveSeed);
this.currentBattle.incrementTurn(this);
this.currentBattle.incrementTurn();
if (newBattleType === BattleType.MYSTERY_ENCOUNTER) {
// Disable double battle on mystery encounters (it may be re-enabled as part of encounter)
@ -1271,7 +1273,7 @@ export default class BattleScene extends SceneBase {
playerField.forEach((pokemon, p) => {
if (pokemon.isOnField()) {
this.pushPhase(new ReturnPhase(this, p));
this.pushPhase(new ReturnPhase(p));
}
});
@ -1281,7 +1283,7 @@ export default class BattleScene extends SceneBase {
}
if (!this.trainer.visible) {
this.pushPhase(new ShowTrainerPhase(this));
this.pushPhase(new ShowTrainerPhase());
}
}
@ -1290,14 +1292,14 @@ export default class BattleScene extends SceneBase {
}
if (!this.gameMode.hasRandomBiomes && !isNewBiome) {
this.pushPhase(new NextEncounterPhase(this));
this.pushPhase(new NextEncounterPhase());
} else {
this.pushPhase(new SelectBiomePhase(this));
this.pushPhase(new NewBiomeEncounterPhase(this));
this.pushPhase(new SelectBiomePhase());
this.pushPhase(new NewBiomeEncounterPhase());
const newMaxExpLevel = this.getMaxExpLevel();
if (newMaxExpLevel > maxExpLevel) {
this.pushPhase(new LevelCapPhase(this));
this.pushPhase(new LevelCapPhase());
}
}
}
@ -1306,7 +1308,7 @@ export default class BattleScene extends SceneBase {
}
newArena(biome: Biome): Arena {
this.arena = new Arena(this, biome, Biome[biome].toLowerCase());
this.arena = new Arena(biome, Biome[biome].toLowerCase());
this.eventTarget.dispatchEvent(new NewArenaEvent());
this.arenaBg.pipelineData = { terrainColorRatio: this.arena.getBgTerrainColorRatioForBiome() };
@ -1711,7 +1713,7 @@ export default class BattleScene extends SceneBase {
}
updateUIPositions(): void {
const enemyModifierCount = this.enemyModifiers.filter(m => m.isIconVisible(this)).length;
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)
@ -1798,7 +1800,7 @@ export default class BattleScene extends SceneBase {
playBgm(bgmName?: string, fadeOut?: boolean): void {
if (bgmName === undefined) {
bgmName = this.currentBattle?.getBgmOverride(this) || this.arena?.bgm;
bgmName = this.currentBattle?.getBgmOverride() || this.arena?.bgm;
}
if (this.bgm && bgmName === this.bgm.key) {
if (!this.bgm.isPlaying) {
@ -2399,7 +2401,7 @@ export default class BattleScene extends SceneBase {
* @param defer boolean for which queue to add it to, false -> add to PhaseQueuePrepend, true -> nextCommandPhaseQueue
*/
queueMessage(message: string, callbackDelay?: integer | null, prompt?: boolean | null, promptDelay?: integer | null, defer?: boolean | null) {
const phase = new MessagePhase(this, message, callbackDelay, prompt, promptDelay);
const phase = new MessagePhase(message, callbackDelay, prompt, promptDelay);
if (!defer) {
// adds to the end of PhaseQueuePrepend
this.unshiftPhase(phase);
@ -2417,7 +2419,7 @@ export default class BattleScene extends SceneBase {
this.phaseQueue.push(...this.nextCommandPhaseQueue);
this.nextCommandPhaseQueue.splice(0, this.nextCommandPhaseQueue.length);
}
this.phaseQueue.push(new TurnInitPhase(this));
this.phaseQueue.push(new TurnInitPhase());
}
addMoney(amount: integer): void {
@ -2448,7 +2450,7 @@ export default class BattleScene extends SceneBase {
if (modifier instanceof TerastallizeModifier) {
modifiersToRemove.push(...(this.findModifiers(m => m instanceof TerastallizeModifier && m.pokemonId === modifier.pokemonId)));
}
if ((modifier as PersistentModifier).add(this.modifiers, !!virtual, this)) {
if ((modifier as PersistentModifier).add(this.modifiers, !!virtual)) {
if (modifier instanceof PokemonFormChangeItemModifier || modifier instanceof TerastallizeModifier) {
const pokemon = this.getPokemonById(modifier.pokemonId);
if (pokemon) {
@ -2529,7 +2531,7 @@ export default class BattleScene extends SceneBase {
if (modifier instanceof TerastallizeModifier) {
modifiersToRemove.push(...(this.findModifiers(m => m instanceof TerastallizeModifier && m.pokemonId === modifier.pokemonId, false)));
}
if ((modifier as PersistentModifier).add(this.enemyModifiers, false, this)) {
if ((modifier as PersistentModifier).add(this.enemyModifiers, false)) {
if (modifier instanceof PokemonFormChangeItemModifier || modifier instanceof TerastallizeModifier) {
const pokemon = this.getPokemonById(modifier.pokemonId);
if (pokemon) {
@ -2563,7 +2565,7 @@ export default class BattleScene extends SceneBase {
*/
tryTransferHeldItemModifier(itemModifier: PokemonHeldItemModifier, target: Pokemon, playSound: boolean, transferQuantity: integer = 1, instant?: boolean, ignoreUpdate?: boolean): Promise<boolean> {
return new Promise(resolve => {
const source = itemModifier.pokemonId ? itemModifier.getPokemon(target.scene) : null;
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) {
@ -2571,11 +2573,11 @@ export default class BattleScene extends SceneBase {
}
const newItemModifier = itemModifier.clone() as PokemonHeldItemModifier;
newItemModifier.pokemonId = target.id;
const matchingModifier = target.scene.findModifier(m => m instanceof PokemonHeldItemModifier
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(target.scene);
const maxStackCount = matchingModifier.getMaxStackCount();
if (matchingModifier.stackCount >= maxStackCount) {
return resolve(false);
}
@ -2682,7 +2684,7 @@ export default class BattleScene extends SceneBase {
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, this));
.map(mt => mt.newModifier(enemyPokemon).add(this.enemyModifiers, false));
}
return true;
});
@ -2706,7 +2708,7 @@ export default class BattleScene extends SceneBase {
* @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(this) === 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);
}
@ -2818,9 +2820,9 @@ 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<T extends PersistentModifier>(scene: BattleScene, modifierType: Constructor<T>, player: boolean = true, ...args: Parameters<T["apply"]>): T[] {
applyShuffledModifiers<T extends PersistentModifier>(modifierType: Constructor<T>, player: boolean = true, ...args: Parameters<T["apply"]>): T[] {
let modifiers = (player ? this.modifiers : this.enemyModifiers).filter((m): m is T => m instanceof modifierType && m.shouldApply(...args));
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
const shuffleModifiers = mods => {
if (mods.length < 1) {
return mods;
@ -2829,7 +2831,7 @@ export default class BattleScene extends SceneBase {
return [ mods[rand], ...shuffleModifiers(mods.filter((_, i) => i !== rand)) ];
};
modifiers = shuffleModifiers(modifiers);
}, scene.currentBattle.turn << 4, scene.waveSeed);
}, gScene.currentBattle.turn << 4, gScene.waveSeed);
return this.applyModifiersInternal(modifiers, player, args);
}
@ -2899,9 +2901,9 @@ export default class BattleScene extends SceneBase {
if (matchingFormChange) {
let phase: Phase;
if (pokemon instanceof PlayerPokemon && !matchingFormChange.quiet) {
phase = new FormChangePhase(this, pokemon, matchingFormChange, modal);
phase = new FormChangePhase(pokemon, matchingFormChange, modal);
} else {
phase = new QuietFormChangePhase(this, pokemon, matchingFormChange);
phase = new QuietFormChangePhase(pokemon, matchingFormChange);
}
if (pokemon instanceof PlayerPokemon && !matchingFormChange.quiet && modal) {
this.overridePhase(phase);
@ -2918,7 +2920,7 @@ export default class BattleScene extends SceneBase {
}
triggerPokemonBattleAnim(pokemon: Pokemon, battleAnimType: PokemonAnimType, fieldAssets?: Phaser.GameObjects.Sprite[], delayed: boolean = false): boolean {
const phase: Phase = new PokemonAnimPhase(this, battleAnimType, pokemon, fieldAssets);
const phase: Phase = new PokemonAnimPhase(battleAnimType, pokemon, fieldAssets);
if (delayed) {
this.pushPhase(phase);
} else {
@ -2935,7 +2937,7 @@ export default class BattleScene extends SceneBase {
}
validateAchv(achv: Achv, args?: unknown[]): boolean {
if (!this.gameData.achvUnlocks.hasOwnProperty(achv.id) && achv.validate(this, args)) {
if (!this.gameData.achvUnlocks.hasOwnProperty(achv.id) && achv.validate(args)) {
this.gameData.achvUnlocks[achv.id] = new Date().getTime();
this.ui.achvBar.showAchv(achv);
if (vouchers.hasOwnProperty(achv.id)) {
@ -2948,7 +2950,7 @@ export default class BattleScene extends SceneBase {
}
validateVoucher(voucher: Voucher, args?: unknown[]): boolean {
if (!this.gameData.voucherUnlocks.hasOwnProperty(voucher.id) && voucher.validate(this, 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]++;
@ -3018,9 +3020,9 @@ export default class BattleScene extends SceneBase {
this.currentBattle.double = true;
const availablePartyMembers = this.getParty().filter((p) => p.isAllowedInBattle());
if (availablePartyMembers.length > 1) {
this.pushPhase(new ToggleDoublePositionPhase(this, true));
this.pushPhase(new ToggleDoublePositionPhase(true));
if (!availablePartyMembers[1].isOnField()) {
this.pushPhase(new SummonPhase(this, 1));
this.pushPhase(new SummonPhase(1));
}
}
@ -3065,7 +3067,7 @@ export default class BattleScene extends SceneBase {
if (participated && pokemonDefeated) {
partyMember.addFriendship(FRIENDSHIP_GAIN_FROM_BATTLE);
const machoBraceModifier = partyMember.getHeldItems().find(m => m instanceof PokemonIncrementingStatModifier);
if (machoBraceModifier && machoBraceModifier.stackCount < machoBraceModifier.getMaxStackCount(this)) {
if (machoBraceModifier && machoBraceModifier.stackCount < machoBraceModifier.getMaxStackCount()) {
machoBraceModifier.stackCount++;
this.updateModifiers(true, true);
partyMember.updateInfo();
@ -3127,7 +3129,7 @@ export default class BattleScene extends SceneBase {
if (exp) {
const partyMemberIndex = party.indexOf(expPartyMembers[pm]);
this.unshiftPhase(expPartyMembers[pm].isOnField() ? new ExpPhase(this, partyMemberIndex, exp) : new ShowPartyExpBarPhase(this, partyMemberIndex, exp));
this.unshiftPhase(expPartyMembers[pm].isOnField() ? new ExpPhase(partyMemberIndex, exp) : new ShowPartyExpBarPhase(partyMemberIndex, exp));
}
}
}
@ -3219,7 +3221,7 @@ export default class BattleScene extends SceneBase {
if (encounter) {
encounter = new MysteryEncounter(encounter);
encounter.populateDialogueTokensFromRequirements(this);
encounter.populateDialogueTokensFromRequirements();
return encounter;
}
@ -3247,8 +3249,9 @@ export default class BattleScene extends SceneBase {
}
let availableEncounters: MysteryEncounter[] = [];
// New encounter should never be the same as the most recent encounter
const previousEncounter = this.mysteryEncounterSaveData.encounteredEvents.length > 0 ? this.mysteryEncounterSaveData.encounteredEvents[this.mysteryEncounterSaveData.encounteredEvents.length - 1].type : null;
const previousEncounter = this.mysteryEncounterSaveData.encounteredEvents.length > 0 ?
this.mysteryEncounterSaveData.encounteredEvents[this.mysteryEncounterSaveData.encounteredEvents.length - 1].type
: null;
const biomeMysteryEncounters = mysteryEncountersByBiome.get(this.arena.biomeType) ?? [];
// If no valid encounters exist at tier, checks next tier down, continuing until there are some encounters available
while (availableEncounters.length === 0 && tier !== null) {
@ -3258,27 +3261,27 @@ export default class BattleScene extends SceneBase {
if (!encounterCandidate) {
return false;
}
if (encounterCandidate.encounterTier !== tier) { // Encounter is in tier
if (encounterCandidate.encounterTier !== tier) {
return false;
}
const disallowedGameModes = encounterCandidate.disallowedGameModes;
if (disallowedGameModes && disallowedGameModes.length > 0
&& disallowedGameModes.includes(this.gameMode.modeId)) { // Encounter is enabled for game mode
&& disallowedGameModes.includes(this.gameMode.modeId)) {
return false;
}
if (this.gameMode.modeId === GameModes.CHALLENGE) { // Encounter is enabled for challenges
if (this.gameMode.modeId === GameModes.CHALLENGE) {
const disallowedChallenges = encounterCandidate.disallowedChallenges;
if (disallowedChallenges && disallowedChallenges.length > 0 && this.gameMode.challenges.some(challenge => disallowedChallenges.includes(challenge.id))) {
return false;
}
}
if (!encounterCandidate.meetsRequirements(this)) { // Meets encounter requirements
if (!encounterCandidate.meetsRequirements()) {
return false;
}
if (previousEncounter !== null && encounterType === previousEncounter) { // Previous encounter was not this one
if (previousEncounter !== null && encounterType === previousEncounter) {
return false;
}
if (this.mysteryEncounterSaveData.encounteredEvents.length > 0 && // Encounter has not exceeded max allowed encounters
if (this.mysteryEncounterSaveData.encounteredEvents.length > 0 &&
(encounterCandidate.maxAllowedEncounters && encounterCandidate.maxAllowedEncounters > 0)
&& this.mysteryEncounterSaveData.encounteredEvents.filter(e => e.type === encounterType).length >= encounterCandidate.maxAllowedEncounters) {
return false;
@ -3306,7 +3309,7 @@ export default class BattleScene extends SceneBase {
encounter = availableEncounters[Utils.randSeedInt(availableEncounters.length)];
// New encounter object to not dirty flags
encounter = new MysteryEncounter(encounter);
encounter.populateDialogueTokensFromRequirements(this);
encounter.populateDialogueTokensFromRequirements();
return encounter;
}
}

View File

@ -1,4 +1,4 @@
import BattleScene from "./battle-scene";
import { gScene } from "#app/battle-scene";
import { Command } from "./ui/command-ui-handler";
import * as Utils from "./utils";
import Trainer, { TrainerVariant } from "./field/trainer";
@ -152,7 +152,7 @@ export default class Battle {
return this.double ? 2 : 1;
}
incrementTurn(scene: BattleScene): void {
incrementTurn(): void {
this.turn++;
this.turnCommands = Object.fromEntries(Utils.getEnumValues(BattlerIndex).map(bt => [ bt, null ]));
this.battleSeedState = null;
@ -167,7 +167,7 @@ export default class Battle {
}
addPostBattleLoot(enemyPokemon: EnemyPokemon): void {
this.postBattleLoot.push(...enemyPokemon.scene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === enemyPokemon.id && m.isTransferable, false).map(i => {
this.postBattleLoot.push(...gScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === enemyPokemon.id && m.isTransferable, false).map(i => {
const ret = i as PokemonHeldItemModifier;
//@ts-ignore - this is awful to fix/change
ret.pokemonId = null;
@ -175,43 +175,43 @@ export default class Battle {
}));
}
pickUpScatteredMoney(scene: BattleScene): void {
const moneyAmount = new Utils.IntegerHolder(scene.currentBattle.moneyScattered);
scene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);
pickUpScatteredMoney(): void {
const moneyAmount = new Utils.IntegerHolder(gScene.currentBattle.moneyScattered);
gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);
if (scene.arena.getTag(ArenaTagType.HAPPY_HOUR)) {
if (gScene.arena.getTag(ArenaTagType.HAPPY_HOUR)) {
moneyAmount.value *= 2;
}
scene.addMoney(moneyAmount.value);
gScene.addMoney(moneyAmount.value);
const userLocale = navigator.language || "en-US";
const formattedMoneyAmount = moneyAmount.value.toLocaleString(userLocale);
const message = i18next.t("battle:moneyPickedUp", { moneyAmount: formattedMoneyAmount });
scene.queueMessage(message, undefined, true);
gScene.queueMessage(message, undefined, true);
scene.currentBattle.moneyScattered = 0;
gScene.currentBattle.moneyScattered = 0;
}
addBattleScore(scene: BattleScene): void {
let partyMemberTurnMultiplier = scene.getEnemyParty().length / 2 + 0.5;
addBattleScore(): void {
let partyMemberTurnMultiplier = gScene.getEnemyParty().length / 2 + 0.5;
if (this.double) {
partyMemberTurnMultiplier /= 1.5;
}
for (const p of scene.getEnemyParty()) {
for (const p of gScene.getEnemyParty()) {
if (p.isBoss()) {
partyMemberTurnMultiplier *= (p.bossSegments / 1.5) / scene.getEnemyParty().length;
partyMemberTurnMultiplier *= (p.bossSegments / 1.5) / gScene.getEnemyParty().length;
}
}
const turnMultiplier = Phaser.Tweens.Builders.GetEaseFunction("Sine.easeIn")(1 - Math.min(this.turn - 2, 10 * partyMemberTurnMultiplier) / (10 * partyMemberTurnMultiplier));
const finalBattleScore = Math.ceil(this.battleScore * turnMultiplier);
scene.score += finalBattleScore;
gScene.score += finalBattleScore;
console.log(`Battle Score: ${finalBattleScore} (${this.turn - 1} Turns x${Math.floor(turnMultiplier * 100) / 100})`);
console.log(`Total Score: ${scene.score}`);
scene.updateScoreText();
console.log(`Total Score: ${gScene.score}`);
gScene.updateScoreText();
}
getBgmOverride(scene: BattleScene): string | null {
getBgmOverride(): string | null {
const battlers = this.enemyParty.slice(0, this.getBattlerCount());
if (this.isBattleMysteryEncounter() && this.mysteryEncounter?.encounterMode === MysteryEncounterMode.DEFAULT) {
// Music is overridden for MEs during ME onInit()
@ -221,7 +221,7 @@ export default class Battle {
if (!this.started && this.trainer?.config.encounterBgm && this.trainer?.getEncounterMessages()?.length) {
return `encounter_${this.trainer?.getEncounterBgm()}`;
}
if (scene.musicPreference === 0) {
if (gScene.musicPreference === 0) {
return this.trainer?.getBattleBgm() ?? null;
} else {
return this.trainer?.getMixedBattleBgm() ?? null;
@ -237,7 +237,7 @@ export default class Battle {
return "battle_final_encounter";
}
if (pokemon.species.legendary || pokemon.species.subLegendary || pokemon.species.mythical) {
if (scene.musicPreference === 0) {
if (gScene.musicPreference === 0) {
if (pokemon.species.speciesId === Species.REGIROCK || pokemon.species.speciesId === Species.REGICE || pokemon.species.speciesId === Species.REGISTEEL || pokemon.species.speciesId === Species.REGIGIGAS || pokemon.species.speciesId === Species.REGIELEKI || pokemon.species.speciesId === Species.REGIDRAGO) {
return "battle_legendary_regis_g5";
}
@ -374,7 +374,7 @@ export default class Battle {
}
}
if (scene.gameMode.isClassic && this.waveIndex <= 4) {
if (gScene.gameMode.isClassic && this.waveIndex <= 4) {
return "battle_wild";
}
@ -387,12 +387,12 @@ export default class Battle {
* @param min The minimum integer to pick, default `0`
* @returns A random integer between {@linkcode min} and ({@linkcode min} + {@linkcode range} - 1)
*/
randSeedInt(scene: BattleScene, range: number, min: number = 0): number {
randSeedInt(range: number, min: number = 0): number {
if (range <= 1) {
return min;
}
const tempRngCounter = scene.rngCounter;
const tempSeedOverride = scene.rngSeedOverride;
const tempRngCounter = gScene.rngCounter;
const tempSeedOverride = gScene.rngSeedOverride;
const state = Phaser.Math.RND.state();
if (this.battleSeedState) {
Phaser.Math.RND.state(this.battleSeedState);
@ -400,13 +400,13 @@ export default class Battle {
Phaser.Math.RND.sow([ Utils.shiftCharCodes(this.battleSeed, this.turn << 6) ]);
console.log("Battle Seed:", this.battleSeed);
}
scene.rngCounter = this.rngCounter++;
scene.rngSeedOverride = this.battleSeed;
gScene.rngCounter = this.rngCounter++;
gScene.rngSeedOverride = this.battleSeed;
const ret = Utils.randSeedInt(range, min);
this.battleSeedState = Phaser.Math.RND.state();
Phaser.Math.RND.state(state);
scene.rngCounter = tempRngCounter;
scene.rngSeedOverride = tempSeedOverride;
gScene.rngCounter = tempRngCounter;
gScene.rngSeedOverride = tempSeedOverride;
return ret;
}
@ -419,16 +419,16 @@ export default class Battle {
}
export class FixedBattle extends Battle {
constructor(scene: BattleScene, waveIndex: number, config: FixedBattleConfig) {
super(scene.gameMode, waveIndex, config.battleType, config.battleType === BattleType.TRAINER ? config.getTrainer(scene) : undefined, config.double);
constructor(waveIndex: number, config: FixedBattleConfig) {
super(gScene.gameMode, waveIndex, config.battleType, config.battleType === BattleType.TRAINER ? config.getTrainer() : undefined, config.double);
if (config.getEnemyParty) {
this.enemyParty = config.getEnemyParty(scene);
this.enemyParty = config.getEnemyParty();
}
}
}
type GetTrainerFunc = (scene: BattleScene) => Trainer;
type GetEnemyPartyFunc = (scene: BattleScene) => EnemyPokemon[];
type GetTrainerFunc = () => Trainer;
type GetEnemyPartyFunc = () => EnemyPokemon[];
export class FixedBattleConfig {
public battleType: BattleType;
@ -478,11 +478,11 @@ export class FixedBattleConfig {
* @returns the generated trainer
*/
function getRandomTrainerFunc(trainerPool: (TrainerType | TrainerType[])[], randomGender: boolean = false, seedOffset: number = 0): GetTrainerFunc {
return (scene: BattleScene) => {
return () => {
const rand = Utils.randSeedInt(trainerPool.length);
const trainerTypes: TrainerType[] = [];
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
for (const trainerPoolEntry of trainerPool) {
const trainerType = Array.isArray(trainerPoolEntry)
? Utils.randSeedItem(trainerPoolEntry)
@ -501,10 +501,10 @@ function getRandomTrainerFunc(trainerPool: (TrainerType | TrainerType[])[], rand
const isEvilTeamGrunt = evilTeamGrunts.includes(trainerTypes[rand]);
if (trainerConfigs[trainerTypes[rand]].hasDouble && isEvilTeamGrunt) {
return new Trainer(scene, trainerTypes[rand], (Utils.randInt(3) === 0) ? TrainerVariant.DOUBLE : trainerGender);
return new Trainer(trainerTypes[rand], (Utils.randInt(3) === 0) ? TrainerVariant.DOUBLE : trainerGender);
}
return new Trainer(scene, trainerTypes[rand], trainerGender);
return new Trainer(trainerTypes[rand], trainerGender);
};
}
@ -522,16 +522,16 @@ export interface FixedBattleConfigs {
*/
export const classicFixedBattles: FixedBattleConfigs = {
[5]: new FixedBattleConfig().setBattleType(BattleType.TRAINER)
.setGetTrainerFunc(scene => new Trainer(scene, TrainerType.YOUNGSTER, Utils.randSeedInt(2) ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)),
.setGetTrainerFunc(() => new Trainer(TrainerType.YOUNGSTER, Utils.randSeedInt(2) ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)),
[8]: new FixedBattleConfig().setBattleType(BattleType.TRAINER)
.setGetTrainerFunc(scene => new Trainer(scene, TrainerType.RIVAL, scene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)),
.setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)),
[25]: new FixedBattleConfig().setBattleType(BattleType.TRAINER)
.setGetTrainerFunc(scene => new Trainer(scene, TrainerType.RIVAL_2, scene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_2, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setCustomModifierRewards({ guaranteedModifierTiers: [ ModifierTier.ULTRA, ModifierTier.GREAT, ModifierTier.GREAT ], allowLuckUpgrades: false }),
[35]: new FixedBattleConfig().setBattleType(BattleType.TRAINER)
.setGetTrainerFunc(getRandomTrainerFunc([ TrainerType.ROCKET_GRUNT, TrainerType.MAGMA_GRUNT, TrainerType.AQUA_GRUNT, TrainerType.GALACTIC_GRUNT, TrainerType.PLASMA_GRUNT, TrainerType.FLARE_GRUNT, TrainerType.AETHER_GRUNT, TrainerType.SKULL_GRUNT, TrainerType.MACRO_GRUNT, TrainerType.STAR_GRUNT ], true)),
[55]: new FixedBattleConfig().setBattleType(BattleType.TRAINER)
.setGetTrainerFunc(scene => new Trainer(scene, TrainerType.RIVAL_3, scene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_3, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setCustomModifierRewards({ guaranteedModifierTiers: [ ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.GREAT, ModifierTier.GREAT ], allowLuckUpgrades: false }),
[62]: new FixedBattleConfig().setBattleType(BattleType.TRAINER).setSeedOffsetWave(35)
.setGetTrainerFunc(getRandomTrainerFunc([ TrainerType.ROCKET_GRUNT, TrainerType.MAGMA_GRUNT, TrainerType.AQUA_GRUNT, TrainerType.GALACTIC_GRUNT, TrainerType.PLASMA_GRUNT, TrainerType.FLARE_GRUNT, TrainerType.AETHER_GRUNT, TrainerType.SKULL_GRUNT, TrainerType.MACRO_GRUNT, TrainerType.STAR_GRUNT ], true)),
@ -540,7 +540,7 @@ export const classicFixedBattles: FixedBattleConfigs = {
[66]: new FixedBattleConfig().setBattleType(BattleType.TRAINER).setSeedOffsetWave(35)
.setGetTrainerFunc(getRandomTrainerFunc([[ TrainerType.ARCHER, TrainerType.ARIANA, TrainerType.PROTON, TrainerType.PETREL ], [ TrainerType.TABITHA, TrainerType.COURTNEY ], [ TrainerType.MATT, TrainerType.SHELLY ], [ TrainerType.JUPITER, TrainerType.MARS, TrainerType.SATURN ], [ TrainerType.ZINZOLIN, TrainerType.ROOD ], [ TrainerType.XEROSIC, TrainerType.BRYONY ], TrainerType.FABA, TrainerType.PLUMERIA, TrainerType.OLEANA, [ TrainerType.GIACOMO, TrainerType.MELA, TrainerType.ATTICUS, TrainerType.ORTEGA, TrainerType.ERI ]], true)),
[95]: new FixedBattleConfig().setBattleType(BattleType.TRAINER)
.setGetTrainerFunc(scene => new Trainer(scene, TrainerType.RIVAL_4, scene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_4, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setCustomModifierRewards({ guaranteedModifierTiers: [ ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.ULTRA ], allowLuckUpgrades: false }),
[112]: new FixedBattleConfig().setBattleType(BattleType.TRAINER).setSeedOffsetWave(35)
.setGetTrainerFunc(getRandomTrainerFunc([ TrainerType.ROCKET_GRUNT, TrainerType.MAGMA_GRUNT, TrainerType.AQUA_GRUNT, TrainerType.GALACTIC_GRUNT, TrainerType.PLASMA_GRUNT, TrainerType.FLARE_GRUNT, TrainerType.AETHER_GRUNT, TrainerType.SKULL_GRUNT, TrainerType.MACRO_GRUNT, TrainerType.STAR_GRUNT ], true)),
@ -550,7 +550,7 @@ export const classicFixedBattles: FixedBattleConfigs = {
.setGetTrainerFunc(getRandomTrainerFunc([ TrainerType.ROCKET_BOSS_GIOVANNI_1, TrainerType.MAXIE, TrainerType.ARCHIE, TrainerType.CYRUS, TrainerType.GHETSIS, TrainerType.LYSANDRE, TrainerType.LUSAMINE, TrainerType.GUZMA, TrainerType.ROSE, TrainerType.PENNY ]))
.setCustomModifierRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.ULTRA ], allowLuckUpgrades: false }),
[145]: new FixedBattleConfig().setBattleType(BattleType.TRAINER)
.setGetTrainerFunc(scene => new Trainer(scene, TrainerType.RIVAL_5, scene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_5, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setCustomModifierRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.ULTRA ], allowLuckUpgrades: false }),
[ClassicFixedBossWaves.EVIL_BOSS_2]: new FixedBattleConfig().setBattleType(BattleType.TRAINER).setSeedOffsetWave(35)
.setGetTrainerFunc(getRandomTrainerFunc([ TrainerType.ROCKET_BOSS_GIOVANNI_2, TrainerType.MAXIE_2, TrainerType.ARCHIE_2, TrainerType.CYRUS_2, TrainerType.GHETSIS_2, TrainerType.LYSANDRE_2, TrainerType.LUSAMINE_2, TrainerType.GUZMA_2, TrainerType.ROSE_2, TrainerType.PENNY_2 ]))
@ -566,6 +566,6 @@ export const classicFixedBattles: FixedBattleConfigs = {
[190]: new FixedBattleConfig().setBattleType(BattleType.TRAINER).setSeedOffsetWave(182)
.setGetTrainerFunc(getRandomTrainerFunc([ TrainerType.BLUE, [ TrainerType.RED, TrainerType.LANCE_CHAMPION ], [ TrainerType.STEVEN, TrainerType.WALLACE ], TrainerType.CYNTHIA, [ TrainerType.ALDER, TrainerType.IRIS ], TrainerType.DIANTHA, TrainerType.HAU, TrainerType.LEON, [ TrainerType.GEETA, TrainerType.NEMONA ], TrainerType.KIERAN ])),
[195]: new FixedBattleConfig().setBattleType(BattleType.TRAINER)
.setGetTrainerFunc(scene => new Trainer(scene, TrainerType.RIVAL_6, scene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_6, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT))
.setCustomModifierRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.GREAT, ModifierTier.GREAT ], allowLuckUpgrades: false })
};

View File

@ -28,7 +28,7 @@ import { MovePhase } from "#app/phases/move-phase";
import { PokemonHealPhase } from "#app/phases/pokemon-heal-phase";
import { ShowAbilityPhase } from "#app/phases/show-ability-phase";
import { StatStageChangePhase } from "#app/phases/stat-stage-change-phase";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
export class Ability implements Localizable {
public id: Abilities;
@ -217,7 +217,7 @@ export class PostBattleInitFormChangeAbAttr extends PostBattleInitAbAttr {
applyPostBattleInit(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
const formIndex = this.formFunc(pokemon);
if (formIndex !== pokemon.formIndex && !simulated) {
return pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
return gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
}
return false;
@ -242,18 +242,18 @@ export class PostBattleInitStatStageChangeAbAttr extends PostBattleInitAbAttr {
if (!simulated) {
if (this.selfTarget) {
statStageChangePhases.push(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, this.stats, this.stages));
statStageChangePhases.push(new StatStageChangePhase(pokemon.getBattlerIndex(), true, this.stats, this.stages));
} else {
for (const opponent of pokemon.getOpponents()) {
statStageChangePhases.push(new StatStageChangePhase(pokemon.scene, opponent.getBattlerIndex(), false, this.stats, this.stages));
statStageChangePhases.push(new StatStageChangePhase(opponent.getBattlerIndex(), false, this.stats, this.stages));
}
}
for (const statStageChangePhase of statStageChangePhases) {
if (!this.selfTarget && !statStageChangePhase.getPokemon()?.summonData) {
pokemon.scene.pushPhase(statStageChangePhase);
gScene.pushPhase(statStageChangePhase);
} else { // TODO: This causes the ability bar to be shown at the wrong time
pokemon.scene.unshiftPhase(statStageChangePhase);
gScene.unshiftPhase(statStageChangePhase);
}
}
}
@ -438,7 +438,7 @@ export class TypeImmunityHealAbAttr extends TypeImmunityAbAttr {
if (ret) {
if (!pokemon.isFullHp() && !simulated) {
const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name;
pokemon.scene.unshiftPhase(new PokemonHealPhase(pokemon.scene, pokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(),
Utils.toDmgValue(pokemon.getMaxHp() / 4), i18next.t("abilityTriggers:typeImmunityHeal", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName }), true));
cancelled.value = true; // Suppresses "No Effect" message
}
@ -466,7 +466,7 @@ class TypeImmunityStatStageChangeAbAttr extends TypeImmunityAbAttr {
if (ret) {
cancelled.value = true; // Suppresses "No Effect" message
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ this.stat ], this.stages));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ this.stat ], this.stages));
}
}
@ -649,7 +649,7 @@ export class MoveImmunityStatStageChangeAbAttr extends MoveImmunityAbAttr {
applyPreDefend(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, cancelled: Utils.BooleanHolder, args: any[]): boolean {
const ret = super.applyPreDefend(pokemon, passive, simulated, attacker, move, cancelled, args);
if (ret && !simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ this.stat ], this.stages));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ this.stat ], this.stages));
}
return ret;
@ -676,7 +676,7 @@ export class ReverseDrainAbAttr extends PostDefendAbAttr {
override applyPostDefend(pokemon: Pokemon, _passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, _hitResult: HitResult, _args: any[]): boolean {
if (move.hasAttr(HitHealAttr) && !move.hitsSubstitute(attacker, pokemon)) {
if (!simulated) {
pokemon.scene.queueMessage(i18next.t("abilityTriggers:reverseDrain", { pokemonNameWithAffix: getPokemonNameWithAffix(attacker) }));
gScene.queueMessage(i18next.t("abilityTriggers:reverseDrain", { pokemonNameWithAffix: getPokemonNameWithAffix(attacker) }));
}
return true;
}
@ -710,11 +710,11 @@ export class PostDefendStatStageChangeAbAttr extends PostDefendAbAttr {
if (this.allOthers) {
const otherPokemon = pokemon.getAlly() ? pokemon.getOpponents().concat([ pokemon.getAlly() ]) : pokemon.getOpponents();
for (const other of otherPokemon) {
other.scene.unshiftPhase(new StatStageChangePhase(other.scene, (other).getBattlerIndex(), false, [ this.stat ], this.stages));
gScene.unshiftPhase(new StatStageChangePhase((other).getBattlerIndex(), false, [ this.stat ], this.stages));
}
return true;
}
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, (this.selfTarget ? pokemon : attacker).getBattlerIndex(), this.selfTarget, [ this.stat ], this.stages));
gScene.unshiftPhase(new StatStageChangePhase((this.selfTarget ? pokemon : attacker).getBattlerIndex(), this.selfTarget, [ this.stat ], this.stages));
return true;
}
@ -746,7 +746,7 @@ export class PostDefendHpGatedStatStageChangeAbAttr extends PostDefendAbAttr {
if (this.condition(pokemon, attacker, move) && (pokemon.hp <= hpGateFlat && (pokemon.hp + damageReceived) > hpGateFlat) && !move.hitsSubstitute(attacker, pokemon)) {
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, (this.selfTarget ? pokemon : attacker).getBattlerIndex(), true, this.stats, this.stages));
gScene.unshiftPhase(new StatStageChangePhase((this.selfTarget ? pokemon : attacker).getBattlerIndex(), true, this.stats, this.stages));
}
return true;
}
@ -768,10 +768,10 @@ export class PostDefendApplyArenaTrapTagAbAttr extends PostDefendAbAttr {
override applyPostDefend(pokemon: Pokemon, _passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, _hitResult: HitResult, _args: any[]): boolean {
if (this.condition(pokemon, attacker, move) && !move.hitsSubstitute(attacker, pokemon)) {
const tag = pokemon.scene.arena.getTag(this.tagType) as ArenaTrapTag;
if (!pokemon.scene.arena.getTag(this.tagType) || tag.layers < tag.maxLayers) {
const tag = gScene.arena.getTag(this.tagType) as ArenaTrapTag;
if (!gScene.arena.getTag(this.tagType) || tag.layers < tag.maxLayers) {
if (!simulated) {
pokemon.scene.arena.addTag(this.tagType, 0, undefined, pokemon.id, pokemon.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER);
gScene.arena.addTag(this.tagType, 0, undefined, pokemon.id, pokemon.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER);
}
return true;
}
@ -794,7 +794,7 @@ export class PostDefendApplyBattlerTagAbAttr extends PostDefendAbAttr {
if (this.condition(pokemon, attacker, move) && !move.hitsSubstitute(attacker, pokemon)) {
if (!pokemon.getTag(this.tagType) && !simulated) {
pokemon.addTag(this.tagType, undefined, undefined, pokemon.id);
pokemon.scene.queueMessage(i18next.t("abilityTriggers:windPowerCharged", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name }));
gScene.queueMessage(i18next.t("abilityTriggers:windPowerCharged", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name }));
}
return true;
}
@ -840,9 +840,9 @@ export class PostDefendTerrainChangeAbAttr extends PostDefendAbAttr {
override applyPostDefend(pokemon: Pokemon, _passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult, _args: any[]): boolean {
if (hitResult < HitResult.NO_EFFECT && !move.hitsSubstitute(attacker, pokemon)) {
if (simulated) {
return pokemon.scene.arena.terrain?.terrainType !== (this.terrainType || undefined);
return gScene.arena.terrain?.terrainType !== (this.terrainType || undefined);
} else {
return pokemon.scene.arena.trySetTerrain(this.terrainType, true);
return gScene.arena.trySetTerrain(this.terrainType, true);
}
}
@ -932,7 +932,7 @@ export class PostDefendCritStatStageChangeAbAttr extends PostDefendAbAttr {
}
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ this.stat ], this.stages));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ this.stat ], this.stages));
}
return true;
@ -1021,11 +1021,11 @@ export class PostDefendWeatherChangeAbAttr extends PostDefendAbAttr {
if (this.condition && !this.condition(pokemon, attacker, move) || move.hitsSubstitute(attacker, pokemon)) {
return false;
}
if (!pokemon.scene.arena.weather?.isImmutable()) {
if (!gScene.arena.weather?.isImmutable()) {
if (simulated) {
return pokemon.scene.arena.weather?.weatherType !== this.weatherType;
return gScene.arena.weather?.weatherType !== this.weatherType;
}
return pokemon.scene.arena.trySetWeather(this.weatherType, true);
return gScene.arena.trySetWeather(this.weatherType, true);
}
return false;
@ -1129,7 +1129,7 @@ export class PostStatStageChangeStatStageChangeAbAttr extends PostStatStageChang
applyPostStatStageChange(pokemon: Pokemon, simulated: boolean, statStagesChanged: BattleStat[], stagesChanged: number, selfTarget: boolean, args: any[]): boolean {
if (this.condition(pokemon, statStagesChanged, stagesChanged) && !selfTarget) {
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, (pokemon).getBattlerIndex(), true, this.statsToChange, this.stages));
gScene.unshiftPhase(new StatStageChangePhase((pokemon).getBattlerIndex(), true, this.statsToChange, this.stages));
}
return true;
}
@ -1687,9 +1687,9 @@ export class PostAttackStealHeldItemAbAttr extends PostAttackAbAttr {
const heldItems = this.getTargetHeldItems(defender).filter(i => i.isTransferable);
if (heldItems.length) {
const stolenItem = heldItems[pokemon.randSeedInt(heldItems.length)];
pokemon.scene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => {
gScene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => {
if (success) {
pokemon.scene.queueMessage(i18next.t("abilityTriggers:postAttackStealHeldItem", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), defenderName: defender.name, stolenItemType: stolenItem.type.name }));
gScene.queueMessage(i18next.t("abilityTriggers:postAttackStealHeldItem", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), defenderName: defender.name, stolenItemType: stolenItem.type.name }));
}
resolve(success);
});
@ -1701,7 +1701,7 @@ export class PostAttackStealHeldItemAbAttr extends PostAttackAbAttr {
}
getTargetHeldItems(target: Pokemon): PokemonHeldItemModifier[] {
return target.scene.findModifiers(m => m instanceof PokemonHeldItemModifier
return gScene.findModifiers(m => m instanceof PokemonHeldItemModifier
&& m.pokemonId === target.id, target.isPlayer()) as PokemonHeldItemModifier[];
}
}
@ -1780,9 +1780,9 @@ export class PostDefendStealHeldItemAbAttr extends PostDefendAbAttr {
const heldItems = this.getTargetHeldItems(attacker).filter(i => i.isTransferable);
if (heldItems.length) {
const stolenItem = heldItems[pokemon.randSeedInt(heldItems.length)];
pokemon.scene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => {
gScene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => {
if (success) {
pokemon.scene.queueMessage(i18next.t("abilityTriggers:postDefendStealHeldItem", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), attackerName: attacker.name, stolenItemType: stolenItem.type.name }));
gScene.queueMessage(i18next.t("abilityTriggers:postDefendStealHeldItem", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), attackerName: attacker.name, stolenItemType: stolenItem.type.name }));
}
resolve(success);
});
@ -1794,7 +1794,7 @@ export class PostDefendStealHeldItemAbAttr extends PostDefendAbAttr {
}
getTargetHeldItems(target: Pokemon): PokemonHeldItemModifier[] {
return target.scene.findModifiers(m => m instanceof PokemonHeldItemModifier
return gScene.findModifiers(m => m instanceof PokemonHeldItemModifier
&& m.pokemonId === target.id, target.isPlayer()) as PokemonHeldItemModifier[];
}
}
@ -1876,7 +1876,7 @@ class PostVictoryStatStageChangeAbAttr extends PostVictoryAbAttr {
? this.stat(pokemon)
: this.stat;
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ stat ], this.stages));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], this.stages));
}
return true;
}
@ -1895,7 +1895,7 @@ export class PostVictoryFormChangeAbAttr extends PostVictoryAbAttr {
const formIndex = this.formFunc(pokemon);
if (formIndex !== pokemon.formIndex) {
if (!simulated) {
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
}
return true;
}
@ -1926,7 +1926,7 @@ export class PostKnockOutStatStageChangeAbAttr extends PostKnockOutAbAttr {
? this.stat(pokemon)
: this.stat;
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ stat ], this.stages));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], this.stages));
}
return true;
}
@ -1941,7 +1941,7 @@ export class CopyFaintedAllyAbilityAbAttr extends PostKnockOutAbAttr {
if (pokemon.isPlayer() === knockedOut.isPlayer() && !knockedOut.getAbility().hasAttr(UncopiableAbilityAbAttr)) {
if (!simulated) {
pokemon.summonData.ability = knockedOut.getAbility().id;
pokemon.scene.queueMessage(i18next.t("abilityTriggers:copyFaintedAllyAbility", { pokemonNameWithAffix: getPokemonNameWithAffix(knockedOut), abilityName: allAbilities[knockedOut.getAbility().id].name }));
gScene.queueMessage(i18next.t("abilityTriggers:copyFaintedAllyAbility", { pokemonNameWithAffix: getPokemonNameWithAffix(knockedOut), abilityName: allAbilities[knockedOut.getAbility().id].name }));
}
return true;
}
@ -2000,7 +2000,7 @@ export class PostIntimidateStatStageChangeAbAttr extends AbAttr {
apply(pokemon: Pokemon, passive: boolean, simulated:boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean {
if (!simulated) {
pokemon.scene.pushPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), false, this.stats, this.stages));
gScene.pushPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, this.stats, this.stages));
}
cancelled.value = this.overwrites;
return true;
@ -2042,7 +2042,7 @@ export class PostSummonRemoveArenaTagAbAttr extends PostSummonAbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise<boolean> {
if (!simulated) {
for (const arenaTag of this.arenaTags) {
pokemon.scene.arena.removeTag(arenaTag);
gScene.arena.removeTag(arenaTag);
}
}
return true;
@ -2060,7 +2060,7 @@ export class PostSummonMessageAbAttr extends PostSummonAbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if (!simulated) {
pokemon.scene.queueMessage(this.messageFunc(pokemon));
gScene.queueMessage(this.messageFunc(pokemon));
}
return true;
@ -2079,7 +2079,7 @@ export class PostSummonUnnamedMessageAbAttr extends PostSummonAbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if (!simulated) {
pokemon.scene.queueMessage(this.message);
gScene.queueMessage(this.message);
}
return true;
@ -2130,7 +2130,7 @@ export class PostSummonStatStageChangeAbAttr extends PostSummonAbAttr {
if (this.selfTarget) {
// we unshift the StatStageChangePhase to put it right after the showAbility and not at the end of the
// phase list (which could be after CommandPhase for example)
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, this.stats, this.stages));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, this.stats, this.stages));
return true;
}
for (const opponent of pokemon.getOpponents()) {
@ -2144,7 +2144,7 @@ export class PostSummonStatStageChangeAbAttr extends PostSummonAbAttr {
}
}
if (!cancelled.value) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, opponent.getBattlerIndex(), false, this.stats, this.stages));
gScene.unshiftPhase(new StatStageChangePhase(opponent.getBattlerIndex(), false, this.stats, this.stages));
}
}
return true;
@ -2166,7 +2166,7 @@ export class PostSummonAllyHealAbAttr extends PostSummonAbAttr {
const target = pokemon.getAlly();
if (target?.isActive(true)) {
if (!simulated) {
target.scene.unshiftPhase(new PokemonHealPhase(target.scene, target.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(),
Utils.toDmgValue(pokemon.getMaxHp() / this.healRatio), i18next.t("abilityTriggers:postSummonAllyHeal", { pokemonNameWithAffix: getPokemonNameWithAffix(target), pokemonName: pokemon.name }), true, !this.showAnim));
}
@ -2198,7 +2198,7 @@ export class PostSummonClearAllyStatStagesAbAttr extends PostSummonAbAttr {
target.setStatStage(s, 0);
}
target.scene.queueMessage(i18next.t("abilityTriggers:postSummonClearAllyStats", { pokemonNameWithAffix: getPokemonNameWithAffix(target) }));
gScene.queueMessage(i18next.t("abilityTriggers:postSummonClearAllyStats", { pokemonNameWithAffix: getPokemonNameWithAffix(target) }));
}
return true;
@ -2250,7 +2250,7 @@ export class DownloadAbAttr extends PostSummonAbAttr {
if (this.enemyDef > 0 && this.enemySpDef > 0) { // only activate if there's actually an enemy to download from
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), false, this.stats, 1));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, this.stats, 1));
}
return true;
}
@ -2271,11 +2271,11 @@ export class PostSummonWeatherChangeAbAttr extends PostSummonAbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if ((this.weatherType === WeatherType.HEAVY_RAIN ||
this.weatherType === WeatherType.HARSH_SUN ||
this.weatherType === WeatherType.STRONG_WINDS) || !pokemon.scene.arena.weather?.isImmutable()) {
this.weatherType === WeatherType.STRONG_WINDS) || !gScene.arena.weather?.isImmutable()) {
if (simulated) {
return pokemon.scene.arena.weather?.weatherType !== this.weatherType;
return gScene.arena.weather?.weatherType !== this.weatherType;
} else {
return pokemon.scene.arena.trySetWeather(this.weatherType, true);
return gScene.arena.trySetWeather(this.weatherType, true);
}
}
@ -2294,9 +2294,9 @@ export class PostSummonTerrainChangeAbAttr extends PostSummonAbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if (simulated) {
return pokemon.scene.arena.terrain?.terrainType !== this.terrainType;
return gScene.arena.terrain?.terrainType !== this.terrainType;
} else {
return pokemon.scene.arena.trySetTerrain(this.terrainType, true);
return gScene.arena.trySetTerrain(this.terrainType, true);
}
}
}
@ -2313,7 +2313,7 @@ export class PostSummonFormChangeAbAttr extends PostSummonAbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
const formIndex = this.formFunc(pokemon);
if (formIndex !== pokemon.formIndex) {
return simulated || pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
return simulated || gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
}
return false;
@ -2333,7 +2333,7 @@ export class PostSummonCopyAbilityAbAttr extends PostSummonAbAttr {
let target: Pokemon;
if (targets.length > 1) {
pokemon.scene.executeWithSeedOffset(() => target = Utils.randSeedItem(targets), pokemon.scene.currentBattle.waveIndex);
gScene.executeWithSeedOffset(() => target = Utils.randSeedItem(targets), gScene.currentBattle.waveIndex);
} else {
target = targets[0];
}
@ -2390,7 +2390,7 @@ export class PostSummonUserFieldRemoveStatusEffectAbAttr extends PostSummonAbAtt
* @returns A boolean or a promise that resolves to a boolean indicating the result of the ability application.
*/
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise<boolean> {
const party = pokemon instanceof PlayerPokemon ? pokemon.scene.getPlayerField() : pokemon.scene.getEnemyField();
const party = pokemon instanceof PlayerPokemon ? gScene.getPlayerField() : gScene.getEnemyField();
const allowedParty = party.filter(p => p.isAllowedInBattle());
if (allowedParty.length < 1) {
@ -2400,7 +2400,7 @@ export class PostSummonUserFieldRemoveStatusEffectAbAttr extends PostSummonAbAtt
if (!simulated) {
for (const pokemon of allowedParty) {
if (pokemon.status && this.statusEffect.includes(pokemon.status.effect)) {
pokemon.scene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon)));
gScene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon)));
pokemon.resetStatus(false);
pokemon.updateInfo();
}
@ -2414,7 +2414,7 @@ export class PostSummonUserFieldRemoveStatusEffectAbAttr extends PostSummonAbAtt
/** Attempt to copy the stat changes on an ally pokemon */
export class PostSummonCopyAllyStatsAbAttr extends PostSummonAbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if (!pokemon.scene.currentBattle.double) {
if (!gScene.currentBattle.double) {
return false;
}
@ -2455,7 +2455,7 @@ export class PostSummonTransformAbAttr extends PostSummonAbAttr {
let target: Pokemon;
if (targets.length > 1) {
pokemon.scene.executeWithSeedOffset(() => target = Utils.randSeedItem(targets), pokemon.scene.currentBattle.waveIndex);
gScene.executeWithSeedOffset(() => target = Utils.randSeedItem(targets), gScene.currentBattle.waveIndex);
} else {
target = targets[0];
}
@ -2489,8 +2489,8 @@ export class PostSummonTransformAbAttr extends PostSummonAbAttr {
pokemon.summonData.types = target.getTypes();
promises.push(pokemon.updateInfo());
pokemon.scene.queueMessage(i18next.t("abilityTriggers:postSummonTransform", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), targetName: target.name, }));
pokemon.scene.playSound("battle_anims/PRSFX- Transform");
gScene.queueMessage(i18next.t("abilityTriggers:postSummonTransform", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), targetName: target.name, }));
gScene.playSound("battle_anims/PRSFX- Transform");
promises.push(pokemon.loadAssets(false).then(() => {
pokemon.playAnim();
pokemon.updateInfo();
@ -2516,14 +2516,14 @@ export class PostSummonWeatherSuppressedFormChangeAbAttr extends PostSummonAbAtt
* @returns whether a Pokemon was reverted to its normal form
*/
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]) {
const pokemonToTransform = getPokemonWithWeatherBasedForms(pokemon.scene);
const pokemonToTransform = getPokemonWithWeatherBasedForms();
if (pokemonToTransform.length < 1) {
return false;
}
if (!simulated) {
pokemon.scene.arena.triggerWeatherBasedFormChangesToNormal();
gScene.arena.triggerWeatherBasedFormChangesToNormal();
}
return true;
@ -2563,8 +2563,8 @@ export class PostSummonFormChangeByWeatherAbAttr extends PostSummonAbAttr {
return simulated;
}
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeWeatherTrigger);
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeRevertWeatherFormTrigger);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeWeatherTrigger);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeRevertWeatherFormTrigger);
queueShowAbility(pokemon, passive);
return true;
}
@ -2609,26 +2609,26 @@ export class PreSwitchOutClearWeatherAbAttr extends PreSwitchOutAbAttr {
* @returns {boolean} Returns true if the weather clears, otherwise false.
*/
applyPreSwitchOut(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean | Promise<boolean> {
const weatherType = pokemon.scene.arena.weather?.weatherType;
const weatherType = gScene.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)
&& pokemon.scene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.DESOLATE_LAND)).length === 0) {
&& gScene.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)
&& pokemon.scene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.PRIMORDIAL_SEA)).length === 0) {
&& gScene.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)
&& pokemon.scene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.DELTA_STREAM)).length === 0) {
&& gScene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.DELTA_STREAM)).length === 0) {
turnOffWeather = true;
}
break;
@ -2639,7 +2639,7 @@ export class PreSwitchOutClearWeatherAbAttr extends PreSwitchOutAbAttr {
}
if (turnOffWeather) {
pokemon.scene.arena.trySetWeather(WeatherType.NONE, false);
gScene.arena.trySetWeather(WeatherType.NONE, false);
return true;
}
@ -2688,7 +2688,7 @@ export class PreSwitchOutFormChangeAbAttr extends PreSwitchOutAbAttr {
const formIndex = this.formFunc(pokemon);
if (formIndex !== pokemon.formIndex) {
if (!simulated) {
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
}
return true;
}
@ -3119,14 +3119,14 @@ function getSheerForceHitDisableAbCondition(): AbAttrCondition {
}
function getWeatherCondition(...weatherTypes: WeatherType[]): AbAttrCondition {
return (pokemon: Pokemon) => {
if (!pokemon.scene?.arena) {
return () => {
if (!gScene?.arena) {
return false;
}
if (pokemon.scene.arena.weather?.isEffectSuppressed(pokemon.scene)) {
if (gScene.arena.weather?.isEffectSuppressed()) {
return false;
}
const weatherType = pokemon.scene.arena.weather?.weatherType;
const weatherType = gScene.arena.weather?.weatherType;
return !!weatherType && weatherTypes.indexOf(weatherType) > -1;
};
}
@ -3215,7 +3215,7 @@ export class ForewarnAbAttr extends PostSummonAbAttr {
}
}
if (!simulated) {
pokemon.scene.queueMessage(i18next.t("abilityTriggers:forewarn", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: maxMove }));
gScene.queueMessage(i18next.t("abilityTriggers:forewarn", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: maxMove }));
}
return true;
}
@ -3229,7 +3229,7 @@ export class FriskAbAttr extends PostSummonAbAttr {
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if (!simulated) {
for (const opponent of pokemon.getOpponents()) {
pokemon.scene.queueMessage(i18next.t("abilityTriggers:frisk", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), opponentName: opponent.name, opponentAbilityName: opponent.getAbility().name }));
gScene.queueMessage(i18next.t("abilityTriggers:frisk", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), opponentName: opponent.name, opponentAbilityName: opponent.getAbility().name }));
setAbilityRevealed(opponent);
}
}
@ -3277,12 +3277,12 @@ export class PostWeatherChangeFormChangeAbAttr extends PostWeatherChangeAbAttr {
return simulated;
}
const weatherType = pokemon.scene.arena.weather?.weatherType;
const weatherType = gScene.arena.weather?.weatherType;
if (weatherType && this.formRevertingWeathers.includes(weatherType)) {
pokemon.scene.arena.triggerWeatherBasedFormChangesToNormal();
gScene.arena.triggerWeatherBasedFormChangesToNormal();
} else {
pokemon.scene.arena.triggerWeatherBasedFormChanges();
gScene.arena.triggerWeatherBasedFormChanges();
}
return true;
}
@ -3346,10 +3346,9 @@ export class PostWeatherLapseHealAbAttr extends PostWeatherLapseAbAttr {
applyPostWeatherLapse(pokemon: Pokemon, passive: boolean, simulated: boolean, weather: Weather, args: any[]): boolean {
if (!pokemon.isFullHp()) {
const scene = pokemon.scene;
const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name;
if (!simulated) {
scene.unshiftPhase(new PokemonHealPhase(scene, pokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(),
Utils.toDmgValue(pokemon.getMaxHp() / (16 / this.healFactor)), i18next.t("abilityTriggers:postWeatherLapseHeal", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName }), true));
}
return true;
@ -3369,14 +3368,13 @@ export class PostWeatherLapseDamageAbAttr extends PostWeatherLapseAbAttr {
}
applyPostWeatherLapse(pokemon: Pokemon, passive: boolean, simulated: boolean, weather: Weather, args: any[]): boolean {
const scene = pokemon.scene;
if (pokemon.hasAbilityWithAttr(BlockNonDirectDamageAbAttr)) {
return false;
}
if (!simulated) {
const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name;
scene.queueMessage(i18next.t("abilityTriggers:postWeatherLapseDamage", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName }));
gScene.queueMessage(i18next.t("abilityTriggers:postWeatherLapseDamage", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName }));
pokemon.damageAndUpdate(Utils.toDmgValue(pokemon.getMaxHp() / (16 / this.damageFactor)), HitResult.OTHER);
}
@ -3418,7 +3416,7 @@ export class PostTerrainChangeAddBattlerTagAttr extends PostTerrainChangeAbAttr
function getTerrainCondition(...terrainTypes: TerrainType[]): AbAttrCondition {
return (pokemon: Pokemon) => {
const terrainType = pokemon.scene.arena.terrain?.terrainType;
const terrainType = gScene.arena.terrain?.terrainType;
return !!terrainType && terrainTypes.indexOf(terrainType) > -1;
};
}
@ -3454,9 +3452,8 @@ export class PostTurnStatusHealAbAttr extends PostTurnAbAttr {
if (pokemon.status && this.effects.includes(pokemon.status.effect)) {
if (!pokemon.isFullHp()) {
if (!simulated) {
const scene = pokemon.scene;
const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name;
scene.unshiftPhase(new PokemonHealPhase(scene, pokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(),
Utils.toDmgValue(pokemon.getMaxHp() / 8), i18next.t("abilityTriggers:poisonHeal", { pokemonName: getPokemonNameWithAffix(pokemon), abilityName }), true));
}
return true;
@ -3487,7 +3484,7 @@ export class PostTurnResetStatusAbAttr extends PostTurnAbAttr {
}
if (this.target?.status) {
if (!simulated) {
this.target.scene.queueMessage(getStatusEffectHealText(this.target.status?.effect, getPokemonNameWithAffix(this.target)));
gScene.queueMessage(getStatusEffectHealText(this.target.status?.effect, getPokemonNameWithAffix(this.target)));
this.target.resetStatus(false);
this.target.updateInfo();
}
@ -3552,7 +3549,7 @@ export class PostTurnLootAbAttr extends PostTurnAbAttr {
const chosenBerry = new BerryModifierType(chosenBerryType);
berriesEaten.splice(randomIdx); // Remove berry from memory
const berryModifier = pokemon.scene.findModifier(
const berryModifier = gScene.findModifier(
(m) => m instanceof BerryModifier && m.berryType === chosenBerryType,
pokemon.isPlayer()
) as BerryModifier | undefined;
@ -3560,16 +3557,16 @@ export class PostTurnLootAbAttr extends PostTurnAbAttr {
if (!berryModifier) {
const newBerry = new BerryModifier(chosenBerry, pokemon.id, chosenBerryType, 1);
if (pokemon.isPlayer()) {
pokemon.scene.addModifier(newBerry);
gScene.addModifier(newBerry);
} else {
pokemon.scene.addEnemyModifier(newBerry);
gScene.addEnemyModifier(newBerry);
}
} else if (berryModifier.stackCount < berryModifier.getMaxHeldItemCount(pokemon)) {
berryModifier.stackCount++;
}
pokemon.scene.queueMessage(i18next.t("abilityTriggers:postTurnLootCreateEatenBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), berryName: chosenBerry.name }));
pokemon.scene.updateModifiers(pokemon.isPlayer());
gScene.queueMessage(i18next.t("abilityTriggers:postTurnLootCreateEatenBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), berryName: chosenBerry.name }));
gScene.updateModifiers(pokemon.isPlayer());
return true;
}
@ -3602,11 +3599,11 @@ export class MoodyAbAttr extends PostTurnAbAttr {
if (canRaise.length > 0) {
const raisedStat = canRaise[pokemon.randSeedInt(canRaise.length)];
canLower = canRaise.filter(s => s !== raisedStat);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ raisedStat ], 2));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ raisedStat ], 2));
}
if (canLower.length > 0) {
const loweredStat = canLower[pokemon.randSeedInt(canLower.length)];
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ loweredStat ], -1));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ loweredStat ], -1));
}
}
@ -3623,7 +3620,7 @@ export class SpeedBoostAbAttr extends PostTurnAbAttr {
applyPostTurn(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if (!simulated) {
if (!pokemon.turnData.switchedInThisTurn && !pokemon.turnData.failedRunAway) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.SPD ], 1));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPD ], 1));
} else {
return false;
}
@ -3636,9 +3633,8 @@ export class PostTurnHealAbAttr extends PostTurnAbAttr {
applyPostTurn(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if (!pokemon.isFullHp()) {
if (!simulated) {
const scene = pokemon.scene;
const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name;
scene.unshiftPhase(new PokemonHealPhase(scene, pokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(),
Utils.toDmgValue(pokemon.getMaxHp() / 16), i18next.t("abilityTriggers:postTurnHeal", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName }), true));
}
@ -3662,7 +3658,7 @@ export class PostTurnFormChangeAbAttr extends PostTurnAbAttr {
const formIndex = this.formFunc(pokemon);
if (formIndex !== pokemon.formIndex) {
if (!simulated) {
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false);
}
return true;
@ -3692,7 +3688,7 @@ export class PostTurnHurtIfSleepingAbAttr extends PostTurnAbAttr {
if ((opp.status?.effect === StatusEffect.SLEEP || opp.hasAbility(Abilities.COMATOSE)) && !opp.hasAbilityWithAttr(BlockNonDirectDamageAbAttr)) {
if (!simulated) {
opp.damageAndUpdate(Utils.toDmgValue(opp.getMaxHp() / 8), HitResult.OTHER);
pokemon.scene.queueMessage(i18next.t("abilityTriggers:badDreams", { pokemonName: getPokemonNameWithAffix(opp) }));
gScene.queueMessage(i18next.t("abilityTriggers:badDreams", { pokemonName: getPokemonNameWithAffix(opp) }));
}
hadEffect = true;
}
@ -3722,11 +3718,11 @@ export class FetchBallAbAttr extends PostTurnAbAttr {
if (simulated) {
return false;
}
const lastUsed = pokemon.scene.currentBattle.lastUsedPokeball;
const lastUsed = gScene.currentBattle.lastUsedPokeball;
if (lastUsed !== null && !!pokemon.isPlayer) {
pokemon.scene.pokeballCounts[lastUsed]++;
pokemon.scene.currentBattle.lastUsedPokeball = null;
pokemon.scene.queueMessage(i18next.t("abilityTriggers:fetchBall", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), pokeballName: getPokeballName(lastUsed) }));
gScene.pokeballCounts[lastUsed]++;
gScene.currentBattle.lastUsedPokeball = null;
gScene.queueMessage(i18next.t("abilityTriggers:fetchBall", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), pokeballName: getPokeballName(lastUsed) }));
return true;
}
return false;
@ -3745,11 +3741,11 @@ export class PostBiomeChangeWeatherChangeAbAttr extends PostBiomeChangeAbAttr {
}
apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean {
if (!pokemon.scene.arena.weather?.isImmutable()) {
if (!gScene.arena.weather?.isImmutable()) {
if (simulated) {
return pokemon.scene.arena.weather?.weatherType !== this.weatherType;
return gScene.arena.weather?.weatherType !== this.weatherType;
} else {
return pokemon.scene.arena.trySetWeather(this.weatherType, true);
return gScene.arena.trySetWeather(this.weatherType, true);
}
}
@ -3768,9 +3764,9 @@ export class PostBiomeChangeTerrainChangeAbAttr extends PostBiomeChangeAbAttr {
apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean {
if (simulated) {
return pokemon.scene.arena.terrain?.terrainType !== this.terrainType;
return gScene.arena.terrain?.terrainType !== this.terrainType;
} else {
return pokemon.scene.arena.trySetTerrain(this.terrainType, true);
return gScene.arena.trySetTerrain(this.terrainType, true);
}
}
}
@ -3812,10 +3808,10 @@ export class PostDancingMoveAbAttr extends PostMoveUsedAbAttr {
// If the move is an AttackMove or a StatusMove the Dancer must replicate the move on the source of the Dance
if (move.getMove() instanceof AttackMove || move.getMove() instanceof StatusMove) {
const target = this.getTarget(dancer, source, targets);
dancer.scene.unshiftPhase(new MovePhase(dancer.scene, dancer, target, move, true, true));
gScene.unshiftPhase(new MovePhase(dancer, target, move, true, true));
} else if (move.getMove() instanceof SelfStatusMove) {
// If the move is a SelfStatusMove (ie. Swords Dance) the Dancer should replicate it on itself
dancer.scene.unshiftPhase(new MovePhase(dancer.scene, dancer, [ dancer.getBattlerIndex() ], move, true, true));
gScene.unshiftPhase(new MovePhase(dancer, [ dancer.getBattlerIndex() ], move, true, true));
}
}
return true;
@ -3857,7 +3853,7 @@ export class StatStageChangeMultiplierAbAttr extends AbAttr {
export class StatStageChangeCopyAbAttr extends AbAttr {
apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean | Promise<boolean> {
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, (args[0] as BattleStat[]), (args[1] as number), true, false, false));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, (args[0] as BattleStat[]), (args[1] as number), true, false, false));
}
return true;
}
@ -3934,9 +3930,8 @@ export class HealFromBerryUseAbAttr extends AbAttr {
apply(pokemon: Pokemon, passive: boolean, simulated: boolean, ...args: [Utils.BooleanHolder, any[]]): boolean {
const { name: abilityName } = passive ? pokemon.getPassiveAbility() : pokemon.getAbility();
if (!simulated) {
pokemon.scene.unshiftPhase(
gScene.unshiftPhase(
new PokemonHealPhase(
pokemon.scene,
pokemon.getBattlerIndex(),
Utils.toDmgValue(pokemon.getMaxHp() * this.healPercent),
i18next.t("abilityTriggers:healFromBerryUse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName }),
@ -4038,13 +4033,13 @@ export class PostBattleAbAttr extends AbAttr {
export class PostBattleLootAbAttr extends PostBattleAbAttr {
applyPostBattle(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
const postBattleLoot = pokemon.scene.currentBattle.postBattleLoot;
const postBattleLoot = gScene.currentBattle.postBattleLoot;
if (!simulated && postBattleLoot.length) {
const randItem = Utils.randSeedItem(postBattleLoot);
//@ts-ignore - TODO see below
if (pokemon.scene.tryTransferHeldItemModifier(randItem, pokemon, true, 1, true)) { // TODO: fix. This is a promise!?
if (gScene.tryTransferHeldItemModifier(randItem, pokemon, true, 1, true)) { // TODO: fix. This is a promise!?
postBattleLoot.splice(postBattleLoot.indexOf(randItem), 1);
pokemon.scene.queueMessage(i18next.t("abilityTriggers:postBattleLoot", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), itemName: randItem.type.name }));
gScene.queueMessage(i18next.t("abilityTriggers:postBattleLoot", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), itemName: randItem.type.name }));
return true;
}
}
@ -4077,14 +4072,14 @@ export class PostFaintUnsuppressedWeatherFormChangeAbAttr extends PostFaintAbAtt
* @returns whether the form change was triggered
*/
applyPostFaint(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker: Pokemon, move: Move, hitResult: HitResult, args: any[]): boolean {
const pokemonToTransform = getPokemonWithWeatherBasedForms(pokemon.scene);
const pokemonToTransform = getPokemonWithWeatherBasedForms();
if (pokemonToTransform.length < 1) {
return false;
}
if (!simulated) {
pokemon.scene.arena.triggerWeatherBasedFormChanges();
gScene.arena.triggerWeatherBasedFormChanges();
}
return true;
@ -4106,26 +4101,26 @@ export class PostFaintClearWeatherAbAttr extends PostFaintAbAttr {
* @returns {boolean} Returns true if the weather clears, otherwise false.
*/
applyPostFaint(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker?: Pokemon, move?: Move, hitResult?: HitResult, ...args: any[]): boolean {
const weatherType = pokemon.scene.arena.weather?.weatherType;
const weatherType = gScene.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)
&& pokemon.scene.getField(true).filter(p => p.hasAbility(Abilities.DESOLATE_LAND)).length === 0) {
&& gScene.getField(true).filter(p => p.hasAbility(Abilities.DESOLATE_LAND)).length === 0) {
turnOffWeather = true;
}
break;
case (WeatherType.HEAVY_RAIN):
if (pokemon.hasAbility(Abilities.PRIMORDIAL_SEA)
&& pokemon.scene.getField(true).filter(p => p.hasAbility(Abilities.PRIMORDIAL_SEA)).length === 0) {
&& gScene.getField(true).filter(p => p.hasAbility(Abilities.PRIMORDIAL_SEA)).length === 0) {
turnOffWeather = true;
}
break;
case (WeatherType.STRONG_WINDS):
if (pokemon.hasAbility(Abilities.DELTA_STREAM)
&& pokemon.scene.getField(true).filter(p => p.hasAbility(Abilities.DELTA_STREAM)).length === 0) {
&& gScene.getField(true).filter(p => p.hasAbility(Abilities.DELTA_STREAM)).length === 0) {
turnOffWeather = true;
}
break;
@ -4136,7 +4131,7 @@ export class PostFaintClearWeatherAbAttr extends PostFaintAbAttr {
}
if (turnOffWeather) {
pokemon.scene.arena.trySetWeather(WeatherType.NONE, false);
gScene.arena.trySetWeather(WeatherType.NONE, false);
return true;
}
@ -4156,7 +4151,7 @@ export class PostFaintContactDamageAbAttr extends PostFaintAbAttr {
applyPostFaint(pokemon: Pokemon, passive: boolean, simulated: boolean, attacker?: Pokemon, move?: Move, hitResult?: HitResult, ...args: any[]): boolean {
if (move !== undefined && attacker !== undefined && move.checkFlag(MoveFlags.MAKES_CONTACT, attacker, pokemon)) { //If the mon didn't die to indirect damage
const cancelled = new Utils.BooleanHolder(false);
pokemon.scene.getField(true).map(p => applyAbAttrs(FieldPreventExplosiveMovesAbAttr, p, cancelled, simulated));
gScene.getField(true).map(p => applyAbAttrs(FieldPreventExplosiveMovesAbAttr, p, cancelled, simulated));
if (cancelled.value || attacker.hasAbilityWithAttr(BlockNonDirectDamageAbAttr)) {
return false;
}
@ -4287,7 +4282,7 @@ export class FlinchStatStageChangeAbAttr extends FlinchEffectAbAttr {
apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean {
if (!simulated) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, this.stats, this.stages));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, this.stats, this.stages));
}
return true;
}
@ -4505,7 +4500,7 @@ export class MoneyAbAttr extends PostBattleAbAttr {
*/
applyPostBattle(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
if (!simulated) {
pokemon.scene.currentBattle.moneyScattered += pokemon.scene.getWaveMoneyAmount(0.2);
gScene.currentBattle.moneyScattered += gScene.getWaveMoneyAmount(0.2);
}
return true;
}
@ -4548,7 +4543,7 @@ export class PostSummonStatStageChangeOnArenaAbAttr extends PostSummonStatStageC
applyPostSummon(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean {
const side = pokemon.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY;
if (pokemon.scene.arena.getTagOnSide(this.tagType, side)) {
if (gScene.arena.getTagOnSide(this.tagType, side)) {
return super.applyPostSummon(pokemon, passive, simulated, args);
}
return false;
@ -4646,7 +4641,7 @@ export class BypassSpeedChanceAbAttr extends AbAttr {
if (!bypassSpeed.value && pokemon.randSeedInt(100) < this.chance) {
const turnCommand =
pokemon.scene.currentBattle.turnCommands[pokemon.getBattlerIndex()];
gScene.currentBattle.turnCommands[pokemon.getBattlerIndex()];
const isCommandFight = turnCommand?.command === Command.FIGHT;
const move = turnCommand?.move?.move ? allMoves[turnCommand.move.move] : null;
const isDamageMove = move?.category === MoveCategory.PHYSICAL || move?.category === MoveCategory.SPECIAL;
@ -4688,7 +4683,7 @@ export class PreventBypassSpeedChanceAbAttr extends AbAttr {
const bypassSpeed = args[0] as Utils.BooleanHolder;
const canCheckHeldItems = args[1] as Utils.BooleanHolder;
const turnCommand = pokemon.scene.currentBattle.turnCommands[pokemon.getBattlerIndex()];
const turnCommand = gScene.currentBattle.turnCommands[pokemon.getBattlerIndex()];
const isCommandFight = turnCommand?.command === Command.FIGHT;
const move = turnCommand?.move?.move ? allMoves[turnCommand.move.move] : null;
if (this.condition(pokemon, move!) && isCommandFight) {
@ -4713,7 +4708,7 @@ export class TerrainEventTypeChangeAbAttr extends PostSummonAbAttr {
if (pokemon.isTerastallized()) {
return false;
}
const currentTerrain = pokemon.scene.arena.getTerrainType();
const currentTerrain = gScene.arena.getTerrainType();
const typeChange: Type[] = this.determineTypeChange(pokemon, currentTerrain);
if (typeChange.length !== 0) {
if (pokemon.summonData.addedType && typeChange.includes(pokemon.summonData.addedType)) {
@ -4760,14 +4755,14 @@ export class TerrainEventTypeChangeAbAttr extends PostSummonAbAttr {
* @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<boolean> {
if (pokemon.scene.arena.getTerrainType() !== TerrainType.NONE) {
if (gScene.arena.getTerrainType() !== TerrainType.NONE) {
return this.apply(pokemon, passive, simulated, new Utils.BooleanHolder(false), []);
}
return false;
}
override getTriggerMessage(pokemon: Pokemon, abilityName: string, ...args: any[]) {
const currentTerrain = pokemon.scene.arena.getTerrainType();
const currentTerrain = gScene.arena.getTerrainType();
const pokemonNameWithAffix = getPokemonNameWithAffix(pokemon);
if (currentTerrain === TerrainType.NONE) {
return i18next.t("abilityTriggers:pokemonTypeChangeRevert", { pokemonNameWithAffix });
@ -4799,7 +4794,7 @@ async function applyAbAttrsInternal<TAttr extends AbAttr>(
continue;
}
pokemon.scene.setPhaseQueueSplice();
gScene.setPhaseQueueSplice();
let result = applyFunc(attr, passive);
// TODO Remove this when promises get reworked
@ -4815,7 +4810,7 @@ async function applyAbAttrsInternal<TAttr extends AbAttr>(
}
if (attr.showAbility && !simulated) {
if (showAbilityInstant) {
pokemon.scene.abilityBar.showAbility(pokemon, passive);
gScene.abilityBar.showAbility(pokemon, passive);
} else {
queueShowAbility(pokemon, passive);
}
@ -4823,13 +4818,13 @@ async function applyAbAttrsInternal<TAttr extends AbAttr>(
const message = attr.getTriggerMessage(pokemon, ability.name, args);
if (message) {
if (!simulated) {
pokemon.scene.queueMessage(message);
gScene.queueMessage(message);
}
}
messages.push(message!);
}
}
pokemon.scene.clearPhaseQueueSplice();
gScene.clearPhaseQueueSplice();
}
}
@ -4972,8 +4967,8 @@ export function applyPostFaintAbAttrs(attrType: Constructor<PostFaintAbAttr>,
}
function queueShowAbility(pokemon: Pokemon, passive: boolean): void {
pokemon.scene.unshiftPhase(new ShowAbilityPhase(pokemon.scene, pokemon.id, passive));
pokemon.scene.clearPhaseQueueSplice();
gScene.unshiftPhase(new ShowAbilityPhase(pokemon.id, passive));
gScene.clearPhaseQueueSplice();
}
/**
@ -4989,10 +4984,9 @@ function setAbilityRevealed(pokemon: Pokemon): void {
/**
* Returns the Pokemon with weather-based forms
* @param {BattleScene} scene - The current scene
*/
function getPokemonWithWeatherBasedForms(scene: BattleScene) {
return scene.getField(true).filter(p =>
function getPokemonWithWeatherBasedForms() {
return gScene.getField(true).filter(p =>
(p.hasAbility(Abilities.FORECAST) && p.species.speciesId === Species.CASTFORM)
|| (p.hasAbility(Abilities.FLOWER_GIFT) && p.species.speciesId === Species.CHERRIM)
);
@ -5088,7 +5082,7 @@ export function initAbilities() {
.attr(UnswappableAbilityAbAttr)
.ignorable(),
new Ability(Abilities.LEVITATE, 3)
.attr(AttackTypeImmunityAbAttr, Type.GROUND, (pokemon: Pokemon) => !pokemon.getTag(GroundedTag) && !pokemon.scene.arena.getTag(ArenaTagType.GRAVITY))
.attr(AttackTypeImmunityAbAttr, Type.GROUND, (pokemon: Pokemon) => !pokemon.getTag(GroundedTag) && !gScene.arena.getTag(ArenaTagType.GRAVITY))
.ignorable(),
new Ability(Abilities.EFFECT_SPORE, 3)
.attr(EffectSporeAbAttr),
@ -5180,10 +5174,10 @@ export function initAbilities() {
new Ability(Abilities.CUTE_CHARM, 3)
.attr(PostDefendContactApplyTagChanceAbAttr, 30, BattlerTagType.INFATUATED),
new Ability(Abilities.PLUS, 3)
.conditionalAttr(p => p.scene.currentBattle.double && [ Abilities.PLUS, Abilities.MINUS ].some(a => p.getAlly().hasAbility(a)), StatMultiplierAbAttr, Stat.SPATK, 1.5)
.conditionalAttr(p => gScene.currentBattle.double && [ Abilities.PLUS, Abilities.MINUS ].some(a => p.getAlly().hasAbility(a)), StatMultiplierAbAttr, Stat.SPATK, 1.5)
.ignorable(),
new Ability(Abilities.MINUS, 3)
.conditionalAttr(p => p.scene.currentBattle.double && [ Abilities.PLUS, Abilities.MINUS ].some(a => p.getAlly().hasAbility(a)), StatMultiplierAbAttr, Stat.SPATK, 1.5)
.conditionalAttr(p => gScene.currentBattle.double && [ Abilities.PLUS, Abilities.MINUS ].some(a => p.getAlly().hasAbility(a)), StatMultiplierAbAttr, Stat.SPATK, 1.5)
.ignorable(),
new Ability(Abilities.FORECAST, 3)
.attr(UncopiableAbilityAbAttr)
@ -5460,8 +5454,8 @@ export function initAbilities() {
.ignorable(),
new Ability(Abilities.ANALYTIC, 5)
.attr(MovePowerBoostAbAttr, (user, target, move) =>
!!target?.getLastXMoves(1).find(m => m.turn === target?.scene.currentBattle.turn)
|| user?.scene.currentBattle.turnCommands[target?.getBattlerIndex() ?? BattlerIndex.ATTACKER]?.command !== Command.FIGHT, 1.3),
!!target?.getLastXMoves(1).find(m => m.turn === gScene.currentBattle.turn)
|| gScene.currentBattle.turnCommands[target?.getBattlerIndex() ?? BattlerIndex.ATTACKER]?.command !== Command.FIGHT, 1.3),
new Ability(Abilities.ILLUSION, 5)
.attr(UncopiableAbilityAbAttr)
.attr(UnswappableAbilityAbAttr)
@ -5582,9 +5576,9 @@ export function initAbilities() {
.attr(FieldMoveTypePowerBoostAbAttr, Type.FAIRY, 4 / 3),
new Ability(Abilities.AURA_BREAK, 6)
.ignorable()
.conditionalAttr(pokemon => pokemon.scene.getField(true).some(p => p.hasAbility(Abilities.DARK_AURA)), FieldMoveTypePowerBoostAbAttr, Type.DARK, 9 / 16)
.conditionalAttr(pokemon => pokemon.scene.getField(true).some(p => p.hasAbility(Abilities.FAIRY_AURA)), FieldMoveTypePowerBoostAbAttr, Type.FAIRY, 9 / 16)
.conditionalAttr(pokemon => pokemon.scene.getField(true).some(p => p.hasAbility(Abilities.DARK_AURA) || p.hasAbility(Abilities.FAIRY_AURA)),
.conditionalAttr(pokemon => gScene.getField(true).some(p => p.hasAbility(Abilities.DARK_AURA)), FieldMoveTypePowerBoostAbAttr, Type.DARK, 9 / 16)
.conditionalAttr(pokemon => gScene.getField(true).some(p => p.hasAbility(Abilities.FAIRY_AURA)), FieldMoveTypePowerBoostAbAttr, Type.FAIRY, 9 / 16)
.conditionalAttr(pokemon => gScene.getField(true).some(p => p.hasAbility(Abilities.DARK_AURA) || p.hasAbility(Abilities.FAIRY_AURA)),
PostSummonMessageAbAttr, (pokemon: Pokemon) => i18next.t("abilityTriggers:postSummonAuraBreak", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })),
new Ability(Abilities.PRIMORDIAL_SEA, 6)
.attr(PostSummonWeatherChangeAbAttr, WeatherType.HEAVY_RAIN)
@ -5627,7 +5621,7 @@ export function initAbilities() {
.bypassFaint()
.partial(), // Meteor form should protect against status effects and yawn
new Ability(Abilities.STAKEOUT, 7)
.attr(MovePowerBoostAbAttr, (user, target, move) => user?.scene.currentBattle.turnCommands[target?.getBattlerIndex() ?? BattlerIndex.ATTACKER]?.command === Command.POKEMON, 2),
.attr(MovePowerBoostAbAttr, (user, target, move) => gScene.currentBattle.turnCommands[target?.getBattlerIndex() ?? BattlerIndex.ATTACKER]?.command === Command.POKEMON, 2),
new Ability(Abilities.WATER_BUBBLE, 7)
.attr(ReceivedTypeDamageMultiplierAbAttr, Type.FIRE, 0.5)
.attr(MoveTypePowerBoostAbAttr, Type.WATER, 2)
@ -5998,7 +5992,7 @@ export function initAbilities() {
new Ability(Abilities.SHARPNESS, 9)
.attr(MovePowerBoostAbAttr, (user, target, move) => move.hasFlag(MoveFlags.SLICING_MOVE), 1.5),
new Ability(Abilities.SUPREME_OVERLORD, 9)
.attr(VariableMovePowerBoostAbAttr, (user, target, move) => 1 + 0.1 * Math.min(user.isPlayer() ? user.scene.currentBattle.playerFaints : user.scene.currentBattle.enemyFaints, 5))
.attr(VariableMovePowerBoostAbAttr, (user, target, move) => 1 + 0.1 * Math.min(user.isPlayer() ? gScene.currentBattle.playerFaints : gScene.currentBattle.enemyFaints, 5))
.partial(), // Counter resets every wave instead of on arena reset
new Ability(Abilities.COSTAR, 9)
.attr(PostSummonCopyAllyStatsAbAttr),

View File

@ -1,5 +1,5 @@
import { gScene } from "#app/battle-scene";
import { Arena } from "#app/field/arena";
import BattleScene from "#app/battle-scene";
import { Type } from "#app/data/type";
import { BooleanHolder, NumberHolder, toDmgValue } from "#app/utils";
import { MoveCategory, allMoves, MoveTarget, IncrementMovePriorityAttr, applyMoveAttrs } from "#app/data/move";
@ -44,7 +44,7 @@ export abstract class ArenaTag {
onRemove(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:arenaOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: this.getMoveName() }));
gScene.queueMessage(i18next.t(`arenaTag:arenaOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: this.getMoveName() }));
}
}
@ -77,8 +77,8 @@ export abstract class ArenaTag {
* @param scene medium to retrieve the source Pokemon
* @returns The source {@linkcode Pokemon} or `null` if none is found
*/
public getSourcePokemon(scene: BattleScene): Pokemon | null {
return this.sourceId ? scene.getPokemonById(this.sourceId) : null;
public getSourcePokemon(): Pokemon | null {
return this.sourceId ? gScene.getPokemonById(this.sourceId) : null;
}
/**
@ -86,15 +86,15 @@ export abstract class ArenaTag {
* @param scene - medium to retrieve the involved Pokemon
* @returns list of PlayerPokemon or EnemyPokemon on the field
*/
public getAffectedPokemon(scene: BattleScene): Pokemon[] {
public getAffectedPokemon(): Pokemon[] {
switch (this.side) {
case ArenaTagSide.PLAYER:
return scene.getPlayerField() ?? [];
return gScene.getPlayerField() ?? [];
case ArenaTagSide.ENEMY:
return scene.getEnemyField() ?? [];
return gScene.getEnemyField() ?? [];
case ArenaTagSide.BOTH:
default:
return scene.getField(true) ?? [];
return gScene.getField(true) ?? [];
}
}
}
@ -112,10 +112,10 @@ export class MistTag extends ArenaTag {
super.onAdd(arena);
if (this.sourceId) {
const source = arena.scene.getPokemonById(this.sourceId);
const source = gScene.getPokemonById(this.sourceId);
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:mistOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
gScene.queueMessage(i18next.t("arenaTag:mistOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
} else if (!quiet) {
console.warn("Failed to get source for MistTag onAdd");
}
@ -146,7 +146,7 @@ export class MistTag extends ArenaTag {
cancelled.value = true;
if (!simulated) {
arena.scene.queueMessage(i18next.t("arenaTag:mistApply"));
gScene.queueMessage(i18next.t("arenaTag:mistApply"));
}
return true;
@ -193,7 +193,7 @@ export class WeakenMoveScreenTag extends ArenaTag {
if (bypassed.value) {
return false;
}
damageMultiplier.value = arena.scene.currentBattle.double ? 2732 / 4096 : 0.5;
damageMultiplier.value = gScene.currentBattle.double ? 2732 / 4096 : 0.5;
return true;
}
return false;
@ -211,7 +211,7 @@ class ReflectTag extends WeakenMoveScreenTag {
onAdd(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:reflectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:reflectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
}
@ -227,7 +227,7 @@ class LightScreenTag extends WeakenMoveScreenTag {
onAdd(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:lightScreenOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:lightScreenOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
}
@ -243,7 +243,7 @@ class AuroraVeilTag extends WeakenMoveScreenTag {
onAdd(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:auroraVeilOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:auroraVeilOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
}
@ -268,7 +268,7 @@ export class ConditionalProtectTag extends ArenaTag {
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t(`arenaTag:conditionalProtectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: super.getMoveName() }));
gScene.queueMessage(i18next.t(`arenaTag:conditionalProtectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: super.getMoveName() }));
}
// Removes default message for effect removal
@ -296,8 +296,8 @@ export class ConditionalProtectTag extends ArenaTag {
if (!simulated) {
attacker.stopMultiHit(defender);
new CommonBattleAnim(CommonAnim.PROTECT, defender).play(arena.scene);
arena.scene.queueMessage(i18next.t("arenaTag:conditionalProtectApply", { moveName: super.getMoveName(), pokemonNameWithAffix: getPokemonNameWithAffix(defender) }));
new CommonBattleAnim(CommonAnim.PROTECT, defender).play();
gScene.queueMessage(i18next.t("arenaTag:conditionalProtectApply", { moveName: super.getMoveName(), pokemonNameWithAffix: getPokemonNameWithAffix(defender) }));
}
}
@ -319,7 +319,7 @@ export class ConditionalProtectTag extends ArenaTag {
const QuickGuardConditionFunc: ProtectConditionFunc = (arena, moveId) => {
const move = allMoves[moveId];
const priority = new NumberHolder(move.priority);
const effectPhase = arena.scene.getCurrentPhase();
const effectPhase = gScene.getCurrentPhase();
if (effectPhase instanceof MoveEffectPhase) {
const attacker = effectPhase.getUserPokemon()!;
@ -393,9 +393,9 @@ class MatBlockTag extends ConditionalProtectTag {
onAdd(arena: Arena) {
if (this.sourceId) {
const source = arena.scene.getPokemonById(this.sourceId);
const source = gScene.getPokemonById(this.sourceId);
if (source) {
arena.scene.queueMessage(i18next.t("arenaTag:matBlockOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
gScene.queueMessage(i18next.t("arenaTag:matBlockOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
} else {
console.warn("Failed to get source for MatBlockTag onAdd");
}
@ -448,15 +448,15 @@ export class NoCritTag extends ArenaTag {
/** Queues a message upon adding this effect to the field */
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t(`arenaTag:noCritOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : "Enemy"}`, {
gScene.queueMessage(i18next.t(`arenaTag:noCritOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : "Enemy"}`, {
moveName: this.getMoveName()
}));
}
/** Queues a message upon removing this effect from the field */
onRemove(arena: Arena): void {
const source = arena.scene.getPokemonById(this.sourceId!); // TODO: is this bang correct?
arena.scene.queueMessage(i18next.t("arenaTag:noCritOnRemove", {
const source = gScene.getPokemonById(this.sourceId!); // TODO: is this bang correct?
gScene.queueMessage(i18next.t("arenaTag:noCritOnRemove", {
pokemonNameWithAffix: getPokemonNameWithAffix(source ?? undefined),
moveName: this.getMoveName()
}));
@ -478,7 +478,7 @@ class WishTag extends ArenaTag {
onAdd(arena: Arena): void {
if (this.sourceId) {
const user = arena.scene.getPokemonById(this.sourceId);
const user = gScene.getPokemonById(this.sourceId);
if (user) {
this.battlerIndex = user.getBattlerIndex();
this.triggerMessage = i18next.t("arenaTag:wishTagOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(user) });
@ -490,10 +490,10 @@ class WishTag extends ArenaTag {
}
onRemove(arena: Arena): void {
const target = arena.scene.getField()[this.battlerIndex];
const target = gScene.getField()[this.battlerIndex];
if (target?.isActive(true)) {
arena.scene.queueMessage(this.triggerMessage);
arena.scene.unshiftPhase(new PokemonHealPhase(target.scene, target.getBattlerIndex(), this.healHp, null, true, false));
gScene.queueMessage(this.triggerMessage);
gScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(), this.healHp, null, true, false));
}
}
}
@ -546,11 +546,11 @@ class MudSportTag extends WeakenMoveTypeTag {
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:mudSportOnAdd"));
gScene.queueMessage(i18next.t("arenaTag:mudSportOnAdd"));
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:mudSportOnRemove"));
gScene.queueMessage(i18next.t("arenaTag:mudSportOnRemove"));
}
}
@ -564,11 +564,11 @@ class WaterSportTag extends WeakenMoveTypeTag {
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:waterSportOnAdd"));
gScene.queueMessage(i18next.t("arenaTag:waterSportOnAdd"));
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:waterSportOnRemove"));
gScene.queueMessage(i18next.t("arenaTag:waterSportOnRemove"));
}
}
@ -584,7 +584,7 @@ export class IonDelugeTag extends ArenaTag {
/** Queues an on-add message */
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:plasmaFistsOnAdd"));
gScene.queueMessage(i18next.t("arenaTag:plasmaFistsOnAdd"));
}
onRemove(arena: Arena): void { } // Removes default on-remove message
@ -679,9 +679,9 @@ class SpikesTag extends ArenaTrapTag {
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
const source = this.sourceId ? gScene.getPokemonById(this.sourceId) : null;
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:spikesOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
gScene.queueMessage(i18next.t("arenaTag:spikesOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
}
}
@ -698,7 +698,7 @@ class SpikesTag extends ArenaTrapTag {
const damageHpRatio = 1 / (10 - 2 * this.layers);
const damage = toDmgValue(pokemon.getMaxHp() * damageHpRatio);
pokemon.scene.queueMessage(i18next.t("arenaTag:spikesActivateTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("arenaTag:spikesActivateTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
pokemon.damageAndUpdate(damage, HitResult.OTHER);
if (pokemon.turnData) {
pokemon.turnData.damageTaken += damage;
@ -728,9 +728,9 @@ class ToxicSpikesTag extends ArenaTrapTag {
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
const source = this.sourceId ? gScene.getPokemonById(this.sourceId) : null;
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:toxicSpikesOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
gScene.queueMessage(i18next.t("arenaTag:toxicSpikesOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
}
}
@ -747,8 +747,8 @@ class ToxicSpikesTag extends ArenaTrapTag {
}
if (pokemon.isOfType(Type.POISON)) {
this.neutralized = true;
if (pokemon.scene.arena.removeTag(this.tagType)) {
pokemon.scene.queueMessage(i18next.t("arenaTag:toxicSpikesActivateTrapPoison", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() }));
if (gScene.arena.removeTag(this.tagType)) {
gScene.queueMessage(i18next.t("arenaTag:toxicSpikesActivateTrapPoison", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() }));
return true;
}
} else if (!pokemon.status) {
@ -791,7 +791,7 @@ class DelayedAttackTag extends ArenaTag {
const ret = super.lapse(arena);
if (!ret) {
arena.scene.unshiftPhase(new MoveEffectPhase(arena.scene, this.sourceId!, [ this.targetIndex ], new PokemonMove(this.sourceMove!, 0, 0, true))); // TODO: are those bangs correct?
gScene.unshiftPhase(new MoveEffectPhase(this.sourceId!, [ this.targetIndex ], new PokemonMove(this.sourceMove!, 0, 0, true))); // TODO: are those bangs correct?
}
return ret;
@ -813,9 +813,9 @@ class StealthRockTag extends ArenaTrapTag {
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
const source = this.sourceId ? gScene.getPokemonById(this.sourceId) : null;
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:stealthRockOnAdd", { opponentDesc: source.getOpponentDescriptor() }));
gScene.queueMessage(i18next.t("arenaTag:stealthRockOnAdd", { opponentDesc: source.getOpponentDescriptor() }));
}
}
@ -863,7 +863,7 @@ class StealthRockTag extends ArenaTrapTag {
return true;
}
const damage = toDmgValue(pokemon.getMaxHp() * damageHpRatio);
pokemon.scene.queueMessage(i18next.t("arenaTag:stealthRockActivateTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("arenaTag:stealthRockActivateTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
pokemon.damageAndUpdate(damage, HitResult.OTHER);
if (pokemon.turnData) {
pokemon.turnData.damageTaken += damage;
@ -892,9 +892,9 @@ class StickyWebTag extends ArenaTrapTag {
onAdd(arena: Arena, quiet: boolean = false): void {
super.onAdd(arena);
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
const source = this.sourceId ? gScene.getPokemonById(this.sourceId) : null;
if (!quiet && source) {
arena.scene.queueMessage(i18next.t("arenaTag:stickyWebOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
gScene.queueMessage(i18next.t("arenaTag:stickyWebOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() }));
}
}
@ -908,9 +908,9 @@ class StickyWebTag extends ArenaTrapTag {
}
if (!cancelled.value) {
pokemon.scene.queueMessage(i18next.t("arenaTag:stickyWebActivateTrap", { pokemonName: pokemon.getNameToRender() }));
gScene.queueMessage(i18next.t("arenaTag:stickyWebActivateTrap", { pokemonName: pokemon.getNameToRender() }));
const stages = new NumberHolder(-1);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), false, [ Stat.SPD ], stages.value));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, [ Stat.SPD ], stages.value));
return true;
}
}
@ -944,14 +944,14 @@ export class TrickRoomTag extends ArenaTag {
}
onAdd(arena: Arena): void {
const source = this.sourceId ? arena.scene.getPokemonById(this.sourceId) : null;
const source = this.sourceId ? gScene.getPokemonById(this.sourceId) : null;
if (source) {
arena.scene.queueMessage(i18next.t("arenaTag:trickRoomOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
gScene.queueMessage(i18next.t("arenaTag:trickRoomOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
}
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:trickRoomOnRemove"));
gScene.queueMessage(i18next.t("arenaTag:trickRoomOnRemove"));
}
}
@ -966,8 +966,8 @@ export class GravityTag extends ArenaTag {
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:gravityOnAdd"));
arena.scene.getField(true).forEach((pokemon) => {
gScene.queueMessage(i18next.t("arenaTag:gravityOnAdd"));
gScene.getField(true).forEach((pokemon) => {
if (pokemon !== null) {
pokemon.removeTag(BattlerTagType.FLOATING);
pokemon.removeTag(BattlerTagType.TELEKINESIS);
@ -979,7 +979,7 @@ export class GravityTag extends ArenaTag {
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:gravityOnRemove"));
gScene.queueMessage(i18next.t("arenaTag:gravityOnRemove"));
}
}
@ -995,29 +995,29 @@ class TailwindTag extends ArenaTag {
onAdd(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:tailwindOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:tailwindOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
const source = arena.scene.getPokemonById(this.sourceId!); //TODO: this bang is questionable!
const party = (source?.isPlayer() ? source.scene.getPlayerField() : source?.scene.getEnemyField()) ?? [];
const source = gScene.getPokemonById(this.sourceId!); //TODO: this bang is questionable!
const party = (source?.isPlayer() ? gScene.getPlayerField() : gScene.getEnemyField()) ?? [];
for (const pokemon of party) {
// Apply the CHARGED tag to party members with the WIND_POWER ability
if (pokemon.hasAbility(Abilities.WIND_POWER) && !pokemon.getTag(BattlerTagType.CHARGED)) {
pokemon.addTag(BattlerTagType.CHARGED);
pokemon.scene.queueMessage(i18next.t("abilityTriggers:windPowerCharged", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() }));
gScene.queueMessage(i18next.t("abilityTriggers:windPowerCharged", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() }));
}
// Raise attack by one stage if party member has WIND_RIDER ability
if (pokemon.hasAbility(Abilities.WIND_RIDER)) {
pokemon.scene.unshiftPhase(new ShowAbilityPhase(pokemon.scene, pokemon.getBattlerIndex()));
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.ATK ], 1, true));
gScene.unshiftPhase(new ShowAbilityPhase(pokemon.getBattlerIndex()));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.ATK ], 1, true));
}
}
}
onRemove(arena: Arena, quiet: boolean = false): void {
if (!quiet) {
arena.scene.queueMessage(i18next.t(`arenaTag:tailwindOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:tailwindOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
}
@ -1032,11 +1032,11 @@ class HappyHourTag extends ArenaTag {
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:happyHourOnAdd"));
gScene.queueMessage(i18next.t("arenaTag:happyHourOnAdd"));
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t("arenaTag:happyHourOnRemove"));
gScene.queueMessage(i18next.t("arenaTag:happyHourOnRemove"));
}
}
@ -1046,11 +1046,11 @@ class SafeguardTag extends ArenaTag {
}
onAdd(arena: Arena): void {
arena.scene.queueMessage(i18next.t(`arenaTag:safeguardOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:safeguardOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
onRemove(arena: Arena): void {
arena.scene.queueMessage(i18next.t(`arenaTag:safeguardOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:safeguardOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}
@ -1073,16 +1073,16 @@ class ImprisonTag extends ArenaTrapTag {
* This function applies the effects of Imprison to the opposing Pokemon already present on the field.
* @param arena
*/
override onAdd({ scene }: Arena) {
const source = this.getSourcePokemon(scene);
override onAdd() {
const source = this.getSourcePokemon();
if (source) {
const party = this.getAffectedPokemon(scene);
const party = this.getAffectedPokemon();
party?.forEach((p: Pokemon ) => {
if (p.isAllowedInBattle()) {
p.addTag(BattlerTagType.IMPRISON, 1, Moves.IMPRISON, this.sourceId);
}
});
scene.queueMessage(i18next.t("battlerTags:imprisonOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
gScene.queueMessage(i18next.t("battlerTags:imprisonOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) }));
}
}
@ -1091,8 +1091,8 @@ class ImprisonTag extends ArenaTrapTag {
* @param _arena
* @returns `true` if the source of the tag is still active on the field | `false` if not
*/
override lapse({ scene }: Arena): boolean {
const source = this.getSourcePokemon(scene);
override lapse(): boolean {
const source = this.getSourcePokemon();
return source ? source.isActive(true) : false;
}
@ -1102,7 +1102,7 @@ class ImprisonTag extends ArenaTrapTag {
* @returns `true`
*/
override activateTrap(pokemon: Pokemon): boolean {
const source = this.getSourcePokemon(pokemon.scene);
const source = this.getSourcePokemon();
if (source && source.isActive(true) && pokemon.isAllowedInBattle()) {
pokemon.addTag(BattlerTagType.IMPRISON, 1, Moves.IMPRISON, this.sourceId);
}
@ -1113,8 +1113,8 @@ class ImprisonTag extends ArenaTrapTag {
* When the arena tag is removed, it also attempts to remove any related Battler Tags if they haven't already been removed from the affected Pokemon
* @param arena
*/
override onRemove({ scene }: Arena): void {
const party = this.getAffectedPokemon(scene);
override onRemove(): void {
const party = this.getAffectedPokemon();
party?.forEach((p: Pokemon) => {
p.removeTag(BattlerTagType.IMPRISON);
});
@ -1135,19 +1135,19 @@ class FireGrassPledgeTag extends ArenaTag {
override onAdd(arena: Arena): void {
// "A sea of fire enveloped your/the opposing team!"
arena.scene.queueMessage(i18next.t(`arenaTag:fireGrassPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:fireGrassPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
override lapse(arena: Arena): boolean {
const field: Pokemon[] = (this.side === ArenaTagSide.PLAYER)
? arena.scene.getPlayerField()
: arena.scene.getEnemyField();
? gScene.getPlayerField()
: gScene.getEnemyField();
field.filter(pokemon => !pokemon.isOfType(Type.FIRE)).forEach(pokemon => {
// "{pokemonNameWithAffix} was hurt by the sea of fire!"
pokemon.scene.queueMessage(i18next.t("arenaTag:fireGrassPledgeLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("arenaTag:fireGrassPledgeLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
// TODO: Replace this with a proper animation
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.MAGMA_STORM));
gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.MAGMA_STORM));
pokemon.damageAndUpdate(toDmgValue(pokemon.getMaxHp() / 8));
});
@ -1169,7 +1169,7 @@ class WaterFirePledgeTag extends ArenaTag {
override onAdd(arena: Arena): void {
// "A rainbow appeared in the sky on your/the opposing team's side!"
arena.scene.queueMessage(i18next.t(`arenaTag:waterFirePledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:waterFirePledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
/**
@ -1199,7 +1199,7 @@ class GrassWaterPledgeTag extends ArenaTag {
override onAdd(arena: Arena): void {
// "A swamp enveloped your/the opposing team!"
arena.scene.queueMessage(i18next.t(`arenaTag:grassWaterPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
gScene.queueMessage(i18next.t(`arenaTag:grassWaterPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`));
}
}

View File

@ -1,3 +1,4 @@
import { gScene } from "#app/battle-scene";
import { Gender } from "#app/data/gender";
import { PokeballType } from "#app/data/pokeball";
import Pokemon from "#app/field/pokemon";
@ -266,8 +267,8 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.ELECTRODE, 30, null, null)
],
[Species.CUBONE]: [
new SpeciesEvolution(Species.ALOLA_MAROWAK, 28, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.MAROWAK, 28, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.ALOLA_MAROWAK, 28, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.MAROWAK, 28, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.TYROGUE]: [
/**
@ -287,8 +288,8 @@ export const pokemonEvolutions: PokemonEvolutions = {
)),
],
[Species.KOFFING]: [
new SpeciesEvolution(Species.GALAR_WEEZING, 35, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.WEEZING, 35, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.GALAR_WEEZING, 35, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.WEEZING, 35, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.RHYHORN]: [
new SpeciesEvolution(Species.RHYDON, 42, null, null)
@ -333,8 +334,8 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.QUILAVA, 14, null, null)
],
[Species.QUILAVA]: [
new SpeciesEvolution(Species.HISUI_TYPHLOSION, 36, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.TYPHLOSION, 36, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.HISUI_TYPHLOSION, 36, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.TYPHLOSION, 36, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.TOTODILE]: [
new SpeciesEvolution(Species.CROCONAW, 18, null, null)
@ -436,8 +437,8 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.LINOONE, 20, null, null)
],
[Species.WURMPLE]: [
new SpeciesEvolution(Species.SILCOON, 7, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY)),
new SpeciesEvolution(Species.CASCOON, 7, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
new SpeciesEvolution(Species.SILCOON, 7, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY)),
new SpeciesEvolution(Species.CASCOON, 7, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
],
[Species.SILCOON]: [
new SpeciesEvolution(Species.BEAUTIFLY, 10, null, null)
@ -478,7 +479,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
],
[Species.NINCADA]: [
new SpeciesEvolution(Species.NINJASK, 20, null, null),
new SpeciesEvolution(Species.SHEDINJA, 20, null, new SpeciesEvolutionCondition(p => p.scene.getParty().length < 6 && p.scene.pokeballCounts[PokeballType.POKEBALL] > 0))
new SpeciesEvolution(Species.SHEDINJA, 20, null, new SpeciesEvolutionCondition(p => gScene.getParty().length < 6 && gScene.pokeballCounts[PokeballType.POKEBALL] > 0))
],
[Species.WHISMUR]: [
new SpeciesEvolution(Species.LOUDRED, 20, null, null)
@ -660,7 +661,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.LUMINEON, 31, null, null)
],
[Species.MANTYKE]: [
new SpeciesEvolution(Species.MANTINE, 32, null, new SpeciesEvolutionCondition(p => !!p.scene.gameData.dexData[Species.REMORAID].caughtAttr), SpeciesWildEvolutionDelay.MEDIUM)
new SpeciesEvolution(Species.MANTINE, 32, null, new SpeciesEvolutionCondition(p => !!gScene.gameData.dexData[Species.REMORAID].caughtAttr), SpeciesWildEvolutionDelay.MEDIUM)
],
[Species.SNOVER]: [
new SpeciesEvolution(Species.ABOMASNOW, 40, null, null)
@ -681,8 +682,8 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.DEWOTT, 17, null, null)
],
[Species.DEWOTT]: [
new SpeciesEvolution(Species.HISUI_SAMUROTT, 36, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.SAMUROTT, 36, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.HISUI_SAMUROTT, 36, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.SAMUROTT, 36, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.PATRAT]: [
new SpeciesEvolution(Species.WATCHOG, 20, null, null)
@ -832,8 +833,8 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.KINGAMBIT, 1, EvolutionItem.LEADERS_CREST, null, SpeciesWildEvolutionDelay.VERY_LONG)
],
[Species.RUFFLET]: [
new SpeciesEvolution(Species.HISUI_BRAVIARY, 54, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.BRAVIARY, 54, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.HISUI_BRAVIARY, 54, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.BRAVIARY, 54, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.VULLABY]: [
new SpeciesEvolution(Species.MANDIBUZZ, 54, null, null)
@ -890,7 +891,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.GOGOAT, 32, null, null)
],
[Species.PANCHAM]: [
new SpeciesEvolution(Species.PANGORO, 32, null, new SpeciesEvolutionCondition(p => !!p.scene.getParty().find(p => p.getTypes(false, false, true).indexOf(Type.DARK) > -1)), SpeciesWildEvolutionDelay.MEDIUM)
new SpeciesEvolution(Species.PANGORO, 32, null, new SpeciesEvolutionCondition(p => !!gScene.getParty().find(p => p.getTypes(false, false, true).indexOf(Type.DARK) > -1)), SpeciesWildEvolutionDelay.MEDIUM)
],
[Species.ESPURR]: [
new SpeciesFormEvolution(Species.MEOWSTIC, "", "female", 25, null, new SpeciesEvolutionCondition(p => p.gender === Gender.FEMALE, p => p.gender = Gender.FEMALE)),
@ -912,21 +913,21 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.CLAWITZER, 37, null, null)
],
[Species.TYRUNT]: [
new SpeciesEvolution(Species.TYRANTRUM, 39, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.TYRANTRUM, 39, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.AMAURA]: [
new SpeciesEvolution(Species.AURORUS, 39, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
new SpeciesEvolution(Species.AURORUS, 39, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
],
[Species.GOOMY]: [
new SpeciesEvolution(Species.HISUI_SLIGGOO, 40, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.SLIGGOO, 40, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.HISUI_SLIGGOO, 40, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.SLIGGOO, 40, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.SLIGGOO]: [
new SpeciesEvolution(Species.GOODRA, 50, null, new SpeciesEvolutionCondition(p => [ WeatherType.RAIN, WeatherType.FOG, WeatherType.HEAVY_RAIN ].indexOf(p.scene.arena.weather?.weatherType || WeatherType.NONE) > -1), SpeciesWildEvolutionDelay.LONG)
new SpeciesEvolution(Species.GOODRA, 50, null, new SpeciesEvolutionCondition(p => [ WeatherType.RAIN, WeatherType.FOG, WeatherType.HEAVY_RAIN ].indexOf(gScene.arena.weather?.weatherType || WeatherType.NONE) > -1), SpeciesWildEvolutionDelay.LONG)
],
[Species.BERGMITE]: [
new SpeciesEvolution(Species.HISUI_AVALUGG, 37, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.AVALUGG, 37, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.HISUI_AVALUGG, 37, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.AVALUGG, 37, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.NOIBAT]: [
new SpeciesEvolution(Species.NOIVERN, 48, null, null)
@ -935,8 +936,8 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.DARTRIX, 17, null, null)
],
[Species.DARTRIX]: [
new SpeciesEvolution(Species.HISUI_DECIDUEYE, 36, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.DECIDUEYE, 34, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.HISUI_DECIDUEYE, 36, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)),
new SpeciesEvolution(Species.DECIDUEYE, 34, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.LITTEN]: [
new SpeciesEvolution(Species.TORRACAT, 17, null, null)
@ -957,7 +958,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.TOUCANNON, 28, null, null)
],
[Species.YUNGOOS]: [
new SpeciesEvolution(Species.GUMSHOOS, 20, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.GUMSHOOS, 20, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.GRUBBIN]: [
new SpeciesEvolution(Species.CHARJABUG, 20, null, null)
@ -975,7 +976,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.ARAQUANID, 22, null, null)
],
[Species.FOMANTIS]: [
new SpeciesEvolution(Species.LURANTIS, 34, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY))
new SpeciesEvolution(Species.LURANTIS, 34, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY))
],
[Species.MORELULL]: [
new SpeciesEvolution(Species.SHIINOTIC, 24, null, null)
@ -1012,7 +1013,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.MELMETAL, 48, null, null)
],
[Species.ALOLA_RATTATA]: [
new SpeciesEvolution(Species.ALOLA_RATICATE, 20, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
new SpeciesEvolution(Species.ALOLA_RATICATE, 20, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
],
[Species.ALOLA_DIGLETT]: [
new SpeciesEvolution(Species.ALOLA_DUGTRIO, 26, null, null)
@ -1135,7 +1136,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.GALAR_LINOONE, 20, null, null)
],
[Species.GALAR_LINOONE]: [
new SpeciesEvolution(Species.OBSTAGOON, 35, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
new SpeciesEvolution(Species.OBSTAGOON, 35, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
],
[Species.GALAR_YAMASK]: [
new SpeciesEvolution(Species.RUNERIGUS, 34, null, null)
@ -1144,7 +1145,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.HISUI_ZOROARK, 30, null, null)
],
[Species.HISUI_SLIGGOO]: [
new SpeciesEvolution(Species.HISUI_GOODRA, 50, null, new SpeciesEvolutionCondition(p => [ WeatherType.RAIN, WeatherType.FOG, WeatherType.HEAVY_RAIN ].indexOf(p.scene.arena.weather?.weatherType || WeatherType.NONE) > -1), SpeciesWildEvolutionDelay.LONG)
new SpeciesEvolution(Species.HISUI_GOODRA, 50, null, new SpeciesEvolutionCondition(p => [ WeatherType.RAIN, WeatherType.FOG, WeatherType.HEAVY_RAIN ].indexOf(gScene.arena.weather?.weatherType || WeatherType.NONE) > -1), SpeciesWildEvolutionDelay.LONG)
],
[Species.SPRIGATITO]: [
new SpeciesEvolution(Species.FLORAGATO, 16, null, null)
@ -1183,7 +1184,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
[Species.TANDEMAUS]: [
new SpeciesFormEvolution(Species.MAUSHOLD, "", "three", 25, null, new SpeciesEvolutionCondition(p => {
let ret = false;
p.scene.executeWithSeedOffset(() => ret = !Utils.randSeedInt(4), p.id);
gScene.executeWithSeedOffset(() => ret = !Utils.randSeedInt(4), p.id);
return ret;
})),
new SpeciesEvolution(Species.MAUSHOLD, 25, null, null)
@ -1243,7 +1244,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.GLIMMORA, 35, null, null)
],
[Species.GREAVARD]: [
new SpeciesEvolution(Species.HOUNDSTONE, 30, null, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
new SpeciesEvolution(Species.HOUNDSTONE, 30, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT))
],
[Species.FRIGIBAX]: [
new SpeciesEvolution(Species.ARCTIBAX, 35, null, null)
@ -1311,10 +1312,10 @@ export const pokemonEvolutions: PokemonEvolutions = {
[Species.EEVEE]: [
new SpeciesFormEvolution(Species.SYLVEON, "", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => !!p.getMoveset().find(m => m?.getMove().type === Type.FAIRY)), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.SYLVEON, "partner", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => !!p.getMoveset().find(m => m?.getMove().type === Type.FAIRY)), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ESPEON, "", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ESPEON, "partner", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.UMBREON, "", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.UMBREON, "partner", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ESPEON, "", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => gScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ESPEON, "partner", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => gScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.UMBREON, "", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.UMBREON, "partner", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.VAPOREON, "", "", 1, EvolutionItem.WATER_STONE, null, SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.VAPOREON, "partner", "", 1, EvolutionItem.WATER_STONE, null, SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.JOLTEON, "", "", 1, EvolutionItem.THUNDER_STONE, null, SpeciesWildEvolutionDelay.LONG),
@ -1351,17 +1352,17 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesFormEvolution(Species.DUDUNSPARCE, "", "three-segment", 32, null, new SpeciesEvolutionCondition(p => {
let ret = false;
if (p.moveset.filter(m => m?.moveId === Moves.HYPER_DRILL).length > 0) {
p.scene.executeWithSeedOffset(() => ret = !Utils.randSeedInt(4), p.id);
gScene.executeWithSeedOffset(() => ret = !Utils.randSeedInt(4), p.id);
}
return ret;
}), SpeciesWildEvolutionDelay.LONG),
new SpeciesEvolution(Species.DUDUNSPARCE, 32, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.HYPER_DRILL).length > 0), SpeciesWildEvolutionDelay.LONG)
],
[Species.GLIGAR]: [
new SpeciesEvolution(Species.GLISCOR, 1, EvolutionItem.RAZOR_FANG, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT /* Razor fang at night*/), SpeciesWildEvolutionDelay.VERY_LONG)
new SpeciesEvolution(Species.GLISCOR, 1, EvolutionItem.RAZOR_FANG, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT /* Razor fang at night*/), SpeciesWildEvolutionDelay.VERY_LONG)
],
[Species.SNEASEL]: [
new SpeciesEvolution(Species.WEAVILE, 1, EvolutionItem.RAZOR_CLAW, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT /* Razor claw at night*/), SpeciesWildEvolutionDelay.VERY_LONG)
new SpeciesEvolution(Species.WEAVILE, 1, EvolutionItem.RAZOR_CLAW, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT /* Razor claw at night*/), SpeciesWildEvolutionDelay.VERY_LONG)
],
[Species.URSARING]: [
new SpeciesEvolution(Species.URSALUNA, 1, EvolutionItem.PEAT_BLOCK, null, SpeciesWildEvolutionDelay.VERY_LONG) //Ursaring does not evolve into Bloodmoon Ursaluna
@ -1391,8 +1392,8 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.SUDOWOODO, 1, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.MIMIC).length > 0), SpeciesWildEvolutionDelay.MEDIUM)
],
[Species.MIME_JR]: [
new SpeciesEvolution(Species.GALAR_MR_MIME, 1, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.MIMIC).length > 0 && (p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), SpeciesWildEvolutionDelay.MEDIUM),
new SpeciesEvolution(Species.MR_MIME, 1, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.MIMIC).length > 0 && (p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY)), SpeciesWildEvolutionDelay.MEDIUM)
new SpeciesEvolution(Species.GALAR_MR_MIME, 1, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.MIMIC).length > 0 && (gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), SpeciesWildEvolutionDelay.MEDIUM),
new SpeciesEvolution(Species.MR_MIME, 1, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.MIMIC).length > 0 && (gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY)), SpeciesWildEvolutionDelay.MEDIUM)
],
[Species.PANSAGE]: [
new SpeciesEvolution(Species.SIMISAGE, 1, EvolutionItem.LEAF_STONE, null, SpeciesWildEvolutionDelay.LONG)
@ -1442,9 +1443,9 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.CRABOMINABLE, 1, EvolutionItem.ICE_STONE, null, SpeciesWildEvolutionDelay.LONG)
],
[Species.ROCKRUFF]: [
new SpeciesFormEvolution(Species.LYCANROC, "", "midday", 25, null, new SpeciesEvolutionCondition(p => (p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY) && (p.formIndex === 0))),
new SpeciesFormEvolution(Species.LYCANROC, "", "midday", 25, null, new SpeciesEvolutionCondition(p => (gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY) && (p.formIndex === 0))),
new SpeciesFormEvolution(Species.LYCANROC, "own-tempo", "dusk", 25, null, new SpeciesEvolutionCondition(p => p.formIndex === 1)),
new SpeciesFormEvolution(Species.LYCANROC, "", "midnight", 25, null, new SpeciesEvolutionCondition(p => (p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT) && (p.formIndex === 0)))
new SpeciesFormEvolution(Species.LYCANROC, "", "midnight", 25, null, new SpeciesEvolutionCondition(p => (gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT) && (p.formIndex === 0)))
],
[Species.STEENEE]: [
new SpeciesEvolution(Species.TSAREENA, 28, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.STOMP).length > 0), SpeciesWildEvolutionDelay.LONG)
@ -1471,15 +1472,15 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesFormEvolution(Species.POLTEAGEIST, "antique", "antique", 1, EvolutionItem.CHIPPED_POT, null, SpeciesWildEvolutionDelay.LONG)
],
[Species.MILCERY]: [
new SpeciesFormEvolution(Species.ALCREMIE, "", "vanilla-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.TOWN || p.scene.arena.biomeType === Biome.PLAINS || p.scene.arena.biomeType === Biome.GRASS || p.scene.arena.biomeType === Biome.TALL_GRASS || p.scene.arena.biomeType === Biome.METROPOLIS), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "ruby-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.BADLANDS || p.scene.arena.biomeType === Biome.VOLCANO || p.scene.arena.biomeType === Biome.GRAVEYARD || p.scene.arena.biomeType === Biome.FACTORY || p.scene.arena.biomeType === Biome.SLUM), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "matcha-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.FOREST || p.scene.arena.biomeType === Biome.SWAMP || p.scene.arena.biomeType === Biome.MEADOW || p.scene.arena.biomeType === Biome.JUNGLE), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "mint-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.SEA || p.scene.arena.biomeType === Biome.BEACH || p.scene.arena.biomeType === Biome.LAKE || p.scene.arena.biomeType === Biome.SEABED), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "lemon-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.DESERT || p.scene.arena.biomeType === Biome.POWER_PLANT || p.scene.arena.biomeType === Biome.DOJO || p.scene.arena.biomeType === Biome.RUINS || p.scene.arena.biomeType === Biome.CONSTRUCTION_SITE), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "salted-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.MOUNTAIN || p.scene.arena.biomeType === Biome.CAVE || p.scene.arena.biomeType === Biome.ICE_CAVE || p.scene.arena.biomeType === Biome.FAIRY_CAVE || p.scene.arena.biomeType === Biome.SNOWY_FOREST), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "ruby-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.WASTELAND || p.scene.arena.biomeType === Biome.LABORATORY), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "caramel-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.TEMPLE || p.scene.arena.biomeType === Biome.ISLAND), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "rainbow-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => p.scene.arena.biomeType === Biome.ABYSS || p.scene.arena.biomeType === Biome.SPACE || p.scene.arena.biomeType === Biome.END), SpeciesWildEvolutionDelay.LONG)
new SpeciesFormEvolution(Species.ALCREMIE, "", "vanilla-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.TOWN || gScene.arena.biomeType === Biome.PLAINS || gScene.arena.biomeType === Biome.GRASS || gScene.arena.biomeType === Biome.TALL_GRASS || gScene.arena.biomeType === Biome.METROPOLIS), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "ruby-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.BADLANDS || gScene.arena.biomeType === Biome.VOLCANO || gScene.arena.biomeType === Biome.GRAVEYARD || gScene.arena.biomeType === Biome.FACTORY || gScene.arena.biomeType === Biome.SLUM), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "matcha-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.FOREST || gScene.arena.biomeType === Biome.SWAMP || gScene.arena.biomeType === Biome.MEADOW || gScene.arena.biomeType === Biome.JUNGLE), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "mint-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.SEA || gScene.arena.biomeType === Biome.BEACH || gScene.arena.biomeType === Biome.LAKE || gScene.arena.biomeType === Biome.SEABED), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "lemon-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.DESERT || gScene.arena.biomeType === Biome.POWER_PLANT || gScene.arena.biomeType === Biome.DOJO || gScene.arena.biomeType === Biome.RUINS || gScene.arena.biomeType === Biome.CONSTRUCTION_SITE), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "salted-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.MOUNTAIN || gScene.arena.biomeType === Biome.CAVE || gScene.arena.biomeType === Biome.ICE_CAVE || gScene.arena.biomeType === Biome.FAIRY_CAVE || gScene.arena.biomeType === Biome.SNOWY_FOREST), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "ruby-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.WASTELAND || gScene.arena.biomeType === Biome.LABORATORY), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "caramel-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.TEMPLE || gScene.arena.biomeType === Biome.ISLAND), SpeciesWildEvolutionDelay.LONG),
new SpeciesFormEvolution(Species.ALCREMIE, "", "rainbow-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => gScene.arena.biomeType === Biome.ABYSS || gScene.arena.biomeType === Biome.SPACE || gScene.arena.biomeType === Biome.END), SpeciesWildEvolutionDelay.LONG)
],
[Species.DURALUDON]: [
new SpeciesFormEvolution(Species.ARCHALUDON, "", "", 1, EvolutionItem.METAL_ALLOY, null, SpeciesWildEvolutionDelay.VERY_LONG)
@ -1501,7 +1502,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.OVERQWIL, 28, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.BARB_BARRAGE).length > 0), SpeciesWildEvolutionDelay.LONG)
],
[Species.HISUI_SNEASEL]: [
new SpeciesEvolution(Species.SNEASLER, 1, EvolutionItem.RAZOR_CLAW, new SpeciesEvolutionCondition(p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY /* Razor claw at day*/), SpeciesWildEvolutionDelay.VERY_LONG)
new SpeciesEvolution(Species.SNEASLER, 1, EvolutionItem.RAZOR_CLAW, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY /* Razor claw at day*/), SpeciesWildEvolutionDelay.VERY_LONG)
],
[Species.CHARCADET]: [
new SpeciesEvolution(Species.ARMAROUGE, 1, EvolutionItem.AUSPICIOUS_ARMOR, null, SpeciesWildEvolutionDelay.LONG),
@ -1581,10 +1582,10 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.CONKELDURR, 1, EvolutionItem.LINKING_CORD, null, SpeciesWildEvolutionDelay.VERY_LONG)
],
[Species.KARRABLAST]: [
new SpeciesEvolution(Species.ESCAVALIER, 1, EvolutionItem.LINKING_CORD, new SpeciesEvolutionCondition(p => !!p.scene.gameData.dexData[Species.SHELMET].caughtAttr), SpeciesWildEvolutionDelay.VERY_LONG)
new SpeciesEvolution(Species.ESCAVALIER, 1, EvolutionItem.LINKING_CORD, new SpeciesEvolutionCondition(p => !!gScene.gameData.dexData[Species.SHELMET].caughtAttr), SpeciesWildEvolutionDelay.VERY_LONG)
],
[Species.SHELMET]: [
new SpeciesEvolution(Species.ACCELGOR, 1, EvolutionItem.LINKING_CORD, new SpeciesEvolutionCondition(p => !!p.scene.gameData.dexData[Species.KARRABLAST].caughtAttr), SpeciesWildEvolutionDelay.VERY_LONG)
new SpeciesEvolution(Species.ACCELGOR, 1, EvolutionItem.LINKING_CORD, new SpeciesEvolutionCondition(p => !!gScene.gameData.dexData[Species.KARRABLAST].caughtAttr), SpeciesWildEvolutionDelay.VERY_LONG)
],
[Species.SPRITZEE]: [
new SpeciesEvolution(Species.AROMATISSE, 1, EvolutionItem.SACHET, null, SpeciesWildEvolutionDelay.VERY_LONG)
@ -1627,13 +1628,13 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.MARILL, 1, null, new SpeciesFriendshipEvolutionCondition(70), SpeciesWildEvolutionDelay.SHORT)
],
[Species.BUDEW]: [
new SpeciesEvolution(Species.ROSELIA, 1, null, new SpeciesFriendshipEvolutionCondition(70, p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.SHORT)
new SpeciesEvolution(Species.ROSELIA, 1, null, new SpeciesFriendshipEvolutionCondition(70, p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.SHORT)
],
[Species.BUNEARY]: [
new SpeciesEvolution(Species.LOPUNNY, 1, null, new SpeciesFriendshipEvolutionCondition(70), SpeciesWildEvolutionDelay.MEDIUM)
],
[Species.CHINGLING]: [
new SpeciesEvolution(Species.CHIMECHO, 1, null, new SpeciesFriendshipEvolutionCondition(90, p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.MEDIUM)
new SpeciesEvolution(Species.CHIMECHO, 1, null, new SpeciesFriendshipEvolutionCondition(90, p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.MEDIUM)
],
[Species.HAPPINY]: [
new SpeciesEvolution(Species.CHANSEY, 1, null, new SpeciesFriendshipEvolutionCondition(160), SpeciesWildEvolutionDelay.SHORT)
@ -1642,7 +1643,7 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.SNORLAX, 1, null, new SpeciesFriendshipEvolutionCondition(120), SpeciesWildEvolutionDelay.LONG)
],
[Species.RIOLU]: [
new SpeciesEvolution(Species.LUCARIO, 1, null, new SpeciesFriendshipEvolutionCondition(120, p => p.scene.arena.getTimeOfDay() === TimeOfDay.DAWN || p.scene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG)
new SpeciesEvolution(Species.LUCARIO, 1, null, new SpeciesFriendshipEvolutionCondition(120, p => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG)
],
[Species.WOOBAT]: [
new SpeciesEvolution(Species.SWOOBAT, 1, null, new SpeciesFriendshipEvolutionCondition(90), SpeciesWildEvolutionDelay.MEDIUM)
@ -1657,16 +1658,16 @@ export const pokemonEvolutions: PokemonEvolutions = {
new SpeciesEvolution(Species.ALOLA_PERSIAN, 1, null, new SpeciesFriendshipEvolutionCondition(120), SpeciesWildEvolutionDelay.LONG)
],
[Species.SNOM]: [
new SpeciesEvolution(Species.FROSMOTH, 1, null, new SpeciesFriendshipEvolutionCondition(90, p => p.scene.arena.getTimeOfDay() === TimeOfDay.DUSK || p.scene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.MEDIUM)
new SpeciesEvolution(Species.FROSMOTH, 1, null, new SpeciesFriendshipEvolutionCondition(90, p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.MEDIUM)
],
[Species.GIMMIGHOUL]: [
new SpeciesFormEvolution(Species.GHOLDENGO, "chest", "", 1, null, new SpeciesEvolutionCondition(p => p.evoCounter
+ p.getHeldItems().filter(m => m instanceof DamageMoneyRewardModifier).length
+ p.scene.findModifiers(m => m instanceof MoneyMultiplierModifier
+ gScene.findModifiers(m => m instanceof MoneyMultiplierModifier
|| m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length > 9), SpeciesWildEvolutionDelay.VERY_LONG),
new SpeciesFormEvolution(Species.GHOLDENGO, "roaming", "", 1, null, new SpeciesEvolutionCondition(p => p.evoCounter
+ p.getHeldItems().filter(m => m instanceof DamageMoneyRewardModifier).length
+ p.scene.findModifiers(m => m instanceof MoneyMultiplierModifier
+ gScene.findModifiers(m => m instanceof MoneyMultiplierModifier
|| m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length > 9), SpeciesWildEvolutionDelay.VERY_LONG)
]
};

View File

@ -1,5 +1,4 @@
//import { battleAnimRawData } from "./battle-anim-raw-data";
import BattleScene from "../battle-scene";
import { gScene } from "#app/battle-scene";
import { AttackMove, BeakBlastHeaderAttr, DelayedAttackAttr, MoveFlags, SelfStatusMove, allMoves } from "./move";
import Pokemon from "../field/pokemon";
import * as Utils from "../utils";
@ -10,7 +9,6 @@ import { SubstituteTag } from "./battler-tags";
import { isNullOrUndefined } from "../utils";
import Phaser from "phaser";
import { EncounterAnim } from "#enums/encounter-anims";
//import fs from 'vite-plugin-fs/browser';
export enum AnimFrameTarget {
USER,
@ -307,7 +305,7 @@ abstract class AnimTimedEvent {
this.resourceName = resourceName;
}
abstract execute(scene: BattleScene, battleAnim: BattleAnim, priority?: number): integer;
abstract execute(battleAnim: BattleAnim, priority?: number): integer;
abstract getEventType(): string;
}
@ -325,15 +323,15 @@ class AnimTimedSoundEvent extends AnimTimedEvent {
}
}
execute(scene: BattleScene, battleAnim: BattleAnim, priority?: number): integer {
execute(battleAnim: BattleAnim, priority?: number): integer {
const soundConfig = { rate: (this.pitch * 0.01), volume: (this.volume * 0.01) };
if (this.resourceName) {
try {
scene.playSound(`battle_anims/${this.resourceName}`, soundConfig);
gScene.playSound(`battle_anims/${this.resourceName}`, soundConfig);
} catch (err) {
console.error(err);
}
return Math.ceil((scene.sound.get(`battle_anims/${this.resourceName}`).totalDuration * 1000) / 33.33);
return Math.ceil((gScene.sound.get(`battle_anims/${this.resourceName}`).totalDuration * 1000) / 33.33);
} else {
return Math.ceil((battleAnim.user!.cry(soundConfig).totalDuration * 1000) / 33.33); // TODO: is the bang behind user correct?
}
@ -387,7 +385,7 @@ class AnimTimedUpdateBgEvent extends AnimTimedBgEvent {
super(frameIndex, resourceName, source);
}
execute(scene: BattleScene, moveAnim: MoveAnim, priority?: number): integer {
execute(moveAnim: MoveAnim, priority?: number): integer {
const tweenProps = {};
if (this.bgX !== undefined) {
tweenProps["x"] = (this.bgX * 0.5) - 320;
@ -399,7 +397,7 @@ class AnimTimedUpdateBgEvent extends AnimTimedBgEvent {
tweenProps["alpha"] = (this.opacity || 0) / 255;
}
if (Object.keys(tweenProps).length) {
scene.tweens.add(Object.assign({
gScene.tweens.add(Object.assign({
targets: moveAnim.bgSprite,
duration: Utils.getFrameMs(this.duration * 3)
}, tweenProps));
@ -417,25 +415,25 @@ class AnimTimedAddBgEvent extends AnimTimedBgEvent {
super(frameIndex, resourceName, source);
}
execute(scene: BattleScene, moveAnim: MoveAnim, priority?: number): integer {
execute(moveAnim: MoveAnim, priority?: number): integer {
if (moveAnim.bgSprite) {
moveAnim.bgSprite.destroy();
}
moveAnim.bgSprite = this.resourceName
? scene.add.tileSprite(this.bgX - 320, this.bgY - 284, 896, 576, this.resourceName)
: scene.add.rectangle(this.bgX - 320, this.bgY - 284, 896, 576, 0);
? gScene.add.tileSprite(this.bgX - 320, this.bgY - 284, 896, 576, this.resourceName)
: gScene.add.rectangle(this.bgX - 320, this.bgY - 284, 896, 576, 0);
moveAnim.bgSprite.setOrigin(0, 0);
moveAnim.bgSprite.setScale(1.25);
moveAnim.bgSprite.setAlpha(this.opacity / 255);
scene.field.add(moveAnim.bgSprite);
const fieldPokemon = scene.getNonSwitchedEnemyPokemon() || scene.getNonSwitchedPlayerPokemon();
gScene.field.add(moveAnim.bgSprite);
const fieldPokemon = gScene.getNonSwitchedEnemyPokemon() || gScene.getNonSwitchedPlayerPokemon();
if (!isNullOrUndefined(priority)) {
scene.field.moveTo(moveAnim.bgSprite as Phaser.GameObjects.GameObject, priority);
gScene.field.moveTo(moveAnim.bgSprite as Phaser.GameObjects.GameObject, priority);
} else if (fieldPokemon?.isOnField()) {
scene.field.moveBelow(moveAnim.bgSprite as Phaser.GameObjects.GameObject, fieldPokemon);
gScene.field.moveBelow(moveAnim.bgSprite as Phaser.GameObjects.GameObject, fieldPokemon);
}
scene.tweens.add({
gScene.tweens.add({
targets: moveAnim.bgSprite,
duration: Utils.getFrameMs(this.duration * 3)
});
@ -453,14 +451,14 @@ export const chargeAnims = new Map<ChargeAnim, AnimConfig | [AnimConfig, AnimCon
export const commonAnims = new Map<CommonAnim, AnimConfig>();
export const encounterAnims = new Map<EncounterAnim, AnimConfig>();
export function initCommonAnims(scene: BattleScene): Promise<void> {
export function initCommonAnims(): Promise<void> {
return new Promise(resolve => {
const commonAnimNames = Utils.getEnumKeys(CommonAnim);
const commonAnimIds = Utils.getEnumValues(CommonAnim);
const commonAnimFetches: Promise<Map<CommonAnim, AnimConfig>>[] = [];
for (let ca = 0; ca < commonAnimIds.length; ca++) {
const commonAnimId = commonAnimIds[ca];
commonAnimFetches.push(scene.cachedFetch(`./battle-anims/common-${commonAnimNames[ca].toLowerCase().replace(/\_/g, "-")}.json`)
commonAnimFetches.push(gScene.cachedFetch(`./battle-anims/common-${commonAnimNames[ca].toLowerCase().replace(/\_/g, "-")}.json`)
.then(response => response.json())
.then(cas => commonAnims.set(commonAnimId, new AnimConfig(cas))));
}
@ -468,7 +466,7 @@ export function initCommonAnims(scene: BattleScene): Promise<void> {
});
}
export function initMoveAnim(scene: BattleScene, move: Moves): Promise<void> {
export function initMoveAnim(move: Moves): Promise<void> {
return new Promise(resolve => {
if (moveAnims.has(move)) {
if (moveAnims.get(move) !== null) {
@ -493,7 +491,7 @@ export function initMoveAnim(scene: BattleScene, move: Moves): Promise<void> {
const defaultMoveAnim = allMoves[move] instanceof AttackMove ? Moves.TACKLE : allMoves[move] instanceof SelfStatusMove ? Moves.FOCUS_ENERGY : Moves.TAIL_WHIP;
const fetchAnimAndResolve = (move: Moves) => {
scene.cachedFetch(`./battle-anims/${Utils.animationFileName(move)}.json`)
gScene.cachedFetch(`./battle-anims/${Utils.animationFileName(move)}.json`)
.then(response => {
const contentType = response.headers.get("content-type");
if (!response.ok || contentType?.indexOf("application/json") === -1) {
@ -515,7 +513,7 @@ export function initMoveAnim(scene: BattleScene, move: Moves): Promise<void> {
: (allMoves[move].getAttrs(DelayedAttackAttr)[0]
?? allMoves[move].getAttrs(BeakBlastHeaderAttr)[0]);
if (chargeAnimSource) {
initMoveChargeAnim(scene, chargeAnimSource.chargeAnim).then(() => resolve());
initMoveChargeAnim(chargeAnimSource.chargeAnim).then(() => resolve());
} else {
resolve();
}
@ -559,7 +557,7 @@ function logMissingMoveAnim(move: Moves, ...optionalParams: any[]) {
* @param scene
* @param encounterAnim one or more animations to fetch
*/
export async function initEncounterAnims(scene: BattleScene, encounterAnim: EncounterAnim | EncounterAnim[]): Promise<void> {
export async function initEncounterAnims(encounterAnim: EncounterAnim | EncounterAnim[]): Promise<void> {
const anims = Array.isArray(encounterAnim) ? encounterAnim : [ encounterAnim ];
const encounterAnimNames = Utils.getEnumKeys(EncounterAnim);
const encounterAnimFetches: Promise<Map<EncounterAnim, AnimConfig>>[] = [];
@ -567,14 +565,14 @@ export async function initEncounterAnims(scene: BattleScene, encounterAnim: Enco
if (encounterAnims.has(anim) && !isNullOrUndefined(encounterAnims.get(anim))) {
continue;
}
encounterAnimFetches.push(scene.cachedFetch(`./battle-anims/encounter-${encounterAnimNames[anim].toLowerCase().replace(/\_/g, "-")}.json`)
encounterAnimFetches.push(gScene.cachedFetch(`./battle-anims/encounter-${encounterAnimNames[anim].toLowerCase().replace(/\_/g, "-")}.json`)
.then(response => response.json())
.then(cas => encounterAnims.set(anim, new AnimConfig(cas))));
}
await Promise.allSettled(encounterAnimFetches);
}
export function initMoveChargeAnim(scene: BattleScene, chargeAnim: ChargeAnim): Promise<void> {
export function initMoveChargeAnim(chargeAnim: ChargeAnim): Promise<void> {
return new Promise(resolve => {
if (chargeAnims.has(chargeAnim)) {
if (chargeAnims.get(chargeAnim) !== null) {
@ -589,7 +587,7 @@ export function initMoveChargeAnim(scene: BattleScene, chargeAnim: ChargeAnim):
}
} else {
chargeAnims.set(chargeAnim, null);
scene.cachedFetch(`./battle-anims/${ChargeAnim[chargeAnim].toLowerCase().replace(/\_/g, "-")}.json`)
gScene.cachedFetch(`./battle-anims/${ChargeAnim[chargeAnim].toLowerCase().replace(/\_/g, "-")}.json`)
.then(response => response.json())
.then(ca => {
if (Array.isArray(ca)) {
@ -622,9 +620,9 @@ function populateMoveChargeAnim(chargeAnim: ChargeAnim, animSource: any) {
chargeAnims.set(chargeAnim, [ chargeAnims.get(chargeAnim) as AnimConfig, moveChargeAnim ]);
}
export function loadCommonAnimAssets(scene: BattleScene, startLoad?: boolean): Promise<void> {
export function loadCommonAnimAssets(startLoad?: boolean): Promise<void> {
return new Promise(resolve => {
loadAnimAssets(scene, Array.from(commonAnims.values()), startLoad).then(() => resolve());
loadAnimAssets(Array.from(commonAnims.values()), startLoad).then(() => resolve());
});
}
@ -634,11 +632,11 @@ export function loadCommonAnimAssets(scene: BattleScene, startLoad?: boolean): P
* @param scene
* @param startLoad
*/
export async function loadEncounterAnimAssets(scene: BattleScene, startLoad?: boolean): Promise<void> {
await loadAnimAssets(scene, Array.from(encounterAnims.values()), startLoad);
export async function loadEncounterAnimAssets(startLoad?: boolean): Promise<void> {
await loadAnimAssets(Array.from(encounterAnims.values()), startLoad);
}
export function loadMoveAnimAssets(scene: BattleScene, moveIds: Moves[], startLoad?: boolean): Promise<void> {
export function loadMoveAnimAssets(moveIds: Moves[], startLoad?: boolean): Promise<void> {
return new Promise(resolve => {
const moveAnimations = moveIds.map(m => moveAnims.get(m) as AnimConfig).flat();
for (const moveId of moveIds) {
@ -654,11 +652,11 @@ export function loadMoveAnimAssets(scene: BattleScene, moveIds: Moves[], startLo
}
}
}
loadAnimAssets(scene, moveAnimations, startLoad).then(() => resolve());
loadAnimAssets(moveAnimations, startLoad).then(() => resolve());
});
}
function loadAnimAssets(scene: BattleScene, anims: AnimConfig[], startLoad?: boolean): Promise<void> {
function loadAnimAssets(anims: AnimConfig[], startLoad?: boolean): Promise<void> {
return new Promise(resolve => {
const backgrounds = new Set<string>();
const sounds = new Set<string>();
@ -675,19 +673,19 @@ function loadAnimAssets(scene: BattleScene, anims: AnimConfig[], startLoad?: boo
backgrounds.add(abg);
}
if (a.graphic) {
scene.loadSpritesheet(a.graphic, "battle_anims", 96);
gScene.loadSpritesheet(a.graphic, "battle_anims", 96);
}
}
for (const bg of backgrounds) {
scene.loadImage(bg, "battle_anims");
gScene.loadImage(bg, "battle_anims");
}
for (const s of sounds) {
scene.loadSe(s, "battle_anims", s);
gScene.loadSe(s, "battle_anims", s);
}
if (startLoad) {
scene.load.once(Phaser.Loader.Events.COMPLETE, () => resolve());
if (!scene.load.isLoading()) {
scene.load.start();
gScene.load.once(Phaser.Loader.Events.COMPLETE, () => resolve());
if (!gScene.load.isLoading()) {
gScene.load.start();
}
} else {
resolve();
@ -777,7 +775,7 @@ export abstract class BattleAnim {
return false;
}
private getGraphicFrameData(scene: BattleScene, frames: AnimFrame[], onSubstitute?: boolean): Map<integer, Map<AnimFrameTarget, GraphicFrameData>> {
private getGraphicFrameData(frames: AnimFrame[], onSubstitute?: boolean): Map<integer, Map<AnimFrameTarget, GraphicFrameData>> {
const ret: Map<integer, Map<AnimFrameTarget, GraphicFrameData>> = new Map([
[ AnimFrameTarget.GRAPHIC, new Map<AnimFrameTarget, GraphicFrameData>() ],
[ AnimFrameTarget.USER, new Map<AnimFrameTarget, GraphicFrameData>() ],
@ -834,7 +832,7 @@ export abstract class BattleAnim {
return ret;
}
play(scene: BattleScene, onSubstitute?: boolean, callback?: Function) {
play(onSubstitute?: boolean, callback?: Function) {
const isOppAnim = this.isOppAnim();
const user = !isOppAnim ? this.user! : this.target!; // TODO: are those bangs correct?
const target = !isOppAnim ? this.target! : this.user!;
@ -906,7 +904,7 @@ export abstract class BattleAnim {
}
};
if (!scene.moveAnimations && !this.playRegardlessOfIssues) {
if (!gScene.moveAnimations && !this.playRegardlessOfIssues) {
return cleanUpAndComplete();
}
@ -923,7 +921,7 @@ export abstract class BattleAnim {
let r = anim?.frames.length ?? 0;
let f = 0;
scene.tweens.addCounter({
gScene.tweens.addCounter({
duration: Utils.getFrameMs(3),
repeat: anim?.frames.length ?? 0,
onRepeat: () => {
@ -933,7 +931,7 @@ export abstract class BattleAnim {
}
const spriteFrames = anim!.frames[f]; // TODO: is the bang correcT?
const frameData = this.getGraphicFrameData(scene, anim!.frames[f], onSubstitute); // TODO: is the bang correct?
const frameData = this.getGraphicFrameData(anim!.frames[f], onSubstitute); // TODO: is the bang correct?
let u = 0;
let t = 0;
let g = 0;
@ -949,19 +947,19 @@ export abstract class BattleAnim {
const spriteSource = isUser ? userSprite : targetSprite;
if ((isUser ? u : t) === sprites.length) {
if (isUser || !targetSubstitute) {
const sprite = scene.addPokemonSprite(isUser ? user! : target, 0, 0, spriteSource!.texture, spriteSource!.frame.name, true); // TODO: are those bangs correct?
const sprite = gScene.addPokemonSprite(isUser ? user! : target, 0, 0, spriteSource!.texture, spriteSource!.frame.name, true); // TODO: are those bangs correct?
[ "spriteColors", "fusionSpriteColors" ].map(k => sprite.pipelineData[k] = (isUser ? user! : target).getSprite().pipelineData[k]); // TODO: are those bangs correct?
sprite.setPipelineData("spriteKey", (isUser ? user! : target).getBattleSpriteKey());
sprite.setPipelineData("shiny", (isUser ? user : target).shiny);
sprite.setPipelineData("variant", (isUser ? user : target).variant);
sprite.setPipelineData("ignoreFieldPos", true);
spriteSource.on("animationupdate", (_anim, frame) => sprite.setFrame(frame.textureFrame));
scene.field.add(sprite);
gScene.field.add(sprite);
sprites.push(sprite);
} else {
const sprite = scene.addFieldSprite(spriteSource.x, spriteSource.y, spriteSource.texture);
const sprite = gScene.addFieldSprite(spriteSource.x, spriteSource.y, spriteSource.texture);
spriteSource.on("animationupdate", (_anim, frame) => sprite.setFrame(frame.textureFrame));
scene.field.add(sprite);
gScene.field.add(sprite);
sprites.push(sprite);
}
}
@ -986,9 +984,9 @@ export abstract class BattleAnim {
} else {
const sprites = spriteCache[AnimFrameTarget.GRAPHIC];
if (g === sprites.length) {
const newSprite: Phaser.GameObjects.Sprite = scene.addFieldSprite(0, 0, anim!.graphic, 1); // TODO: is the bang correct?
const newSprite: Phaser.GameObjects.Sprite = gScene.addFieldSprite(0, 0, anim!.graphic, 1); // TODO: is the bang correct?
sprites.push(newSprite);
scene.field.add(newSprite);
gScene.field.add(newSprite);
spritePriorities.push(1);
}
@ -999,22 +997,22 @@ export abstract class BattleAnim {
const setSpritePriority = (priority: integer) => {
switch (priority) {
case 0:
scene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, scene.getNonSwitchedEnemyPokemon() || scene.getNonSwitchedPlayerPokemon()!); // This bang assumes that if (the EnemyPokemon is undefined, then the PlayerPokemon function must return an object), correct assumption?
gScene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, gScene.getNonSwitchedEnemyPokemon() || gScene.getNonSwitchedPlayerPokemon()!); // This bang assumes that if (the EnemyPokemon is undefined, then the PlayerPokemon function must return an object), correct assumption?
break;
case 1:
scene.field.moveTo(moveSprite, scene.field.getAll().length - 1);
gScene.field.moveTo(moveSprite, gScene.field.getAll().length - 1);
break;
case 2:
switch (frame.focus) {
case AnimFocus.USER:
if (this.bgSprite) {
scene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.bgSprite);
gScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.bgSprite);
} else {
scene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, this.user!); // TODO: is this bang correct?
gScene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, this.user!); // TODO: is this bang correct?
}
break;
case AnimFocus.TARGET:
scene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, this.target!); // TODO: is this bang correct?
gScene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, this.target!); // TODO: is this bang correct?
break;
default:
setSpritePriority(1);
@ -1024,10 +1022,10 @@ export abstract class BattleAnim {
case 3:
switch (frame.focus) {
case AnimFocus.USER:
scene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.user!); // TODO: is this bang correct?
gScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.user!); // TODO: is this bang correct?
break;
case AnimFocus.TARGET:
scene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.target!); // TODO: is this bang correct?
gScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.target!); // TODO: is this bang correct?
break;
default:
setSpritePriority(1);
@ -1055,7 +1053,7 @@ export abstract class BattleAnim {
}
if (anim?.frameTimedEvents.has(f)) {
for (const event of anim.frameTimedEvents.get(f)!) { // TODO: is this bang correct?
r = Math.max((anim.frames.length - f) + event.execute(scene, this), r);
r = Math.max((anim.frames.length - f) + event.execute(this), r);
}
}
const targets = Utils.getEnumValues(AnimFrameTarget);
@ -1085,7 +1083,7 @@ export abstract class BattleAnim {
}
}
if (r) {
scene.tweens.addCounter({
gScene.tweens.addCounter({
duration: Utils.getFrameMs(r),
onComplete: () => cleanUpAndComplete()
});
@ -1134,7 +1132,7 @@ export abstract class BattleAnim {
* - 5 is on top of player sprite
* @param callback
*/
playWithoutTargets(scene: BattleScene, targetInitialX: number, targetInitialY: number, frameTimeMult: number, frameTimedEventPriority?: 0 | 1 | 3 | 5, callback?: Function) {
playWithoutTargets(targetInitialX: number, targetInitialY: number, frameTimeMult: number, frameTimedEventPriority?: 0 | 1 | 3 | 5, callback?: Function) {
const spriteCache: SpriteCache = {
[AnimFrameTarget.GRAPHIC]: [],
[AnimFrameTarget.USER]: [],
@ -1155,7 +1153,7 @@ export abstract class BattleAnim {
}
};
if (!scene.moveAnimations && !this.playRegardlessOfIssues) {
if (!gScene.moveAnimations && !this.playRegardlessOfIssues) {
return cleanUpAndComplete();
}
@ -1167,13 +1165,13 @@ export abstract class BattleAnim {
let totalFrames = anim!.frames.length;
let frameCount = 0;
let existingFieldSprites = scene.field.getAll().slice(0);
let existingFieldSprites = gScene.field.getAll().slice(0);
scene.tweens.addCounter({
gScene.tweens.addCounter({
duration: Utils.getFrameMs(3) * frameTimeMult,
repeat: anim!.frames.length,
onRepeat: () => {
existingFieldSprites = scene.field.getAll().slice(0);
existingFieldSprites = gScene.field.getAll().slice(0);
const spriteFrames = anim!.frames[frameCount];
const frameData = this.getGraphicFrameDataWithoutTarget(anim!.frames[frameCount], targetInitialX, targetInitialY);
let graphicFrameCount = 0;
@ -1185,9 +1183,9 @@ export abstract class BattleAnim {
const sprites = spriteCache[AnimFrameTarget.GRAPHIC];
if (graphicFrameCount === sprites.length) {
const newSprite: Phaser.GameObjects.Sprite = scene.addFieldSprite(0, 0, anim!.graphic, 1);
const newSprite: Phaser.GameObjects.Sprite = gScene.addFieldSprite(0, 0, anim!.graphic, 1);
sprites.push(newSprite);
scene.field.add(newSprite);
gScene.field.add(newSprite);
}
const graphicIndex = graphicFrameCount++;
@ -1196,11 +1194,11 @@ export abstract class BattleAnim {
const setSpritePriority = (priority: integer) => {
if (existingFieldSprites.length > priority) {
// Move to specified priority index
const index = scene.field.getIndex(existingFieldSprites[priority]);
scene.field.moveTo(moveSprite, index);
const index = gScene.field.getIndex(existingFieldSprites[priority]);
gScene.field.moveTo(moveSprite, index);
} else {
// Move to top of scene
scene.field.moveTo(moveSprite, scene.field.getAll().length - 1);
gScene.field.moveTo(moveSprite, gScene.field.getAll().length - 1);
}
};
setSpritePriority(frame.priority);
@ -1220,7 +1218,7 @@ export abstract class BattleAnim {
}
if (anim?.frameTimedEvents.get(frameCount)) {
for (const event of anim.frameTimedEvents.get(frameCount)!) {
totalFrames = Math.max((anim.frames.length - frameCount) + event.execute(scene, this, frameTimedEventPriority), totalFrames);
totalFrames = Math.max((anim.frames.length - frameCount) + event.execute(this, frameTimedEventPriority), totalFrames);
}
}
const targets = Utils.getEnumValues(AnimFrameTarget);
@ -1247,7 +1245,7 @@ export abstract class BattleAnim {
}
}
if (totalFrames) {
scene.tweens.addCounter({
gScene.tweens.addCounter({
duration: Utils.getFrameMs(totalFrames),
onComplete: () => cleanUpAndComplete()
});
@ -1281,7 +1279,7 @@ export class MoveAnim extends BattleAnim {
public move: Moves;
constructor(move: Moves, user: Pokemon, target: BattlerIndex, playOnEmptyField: boolean = false) {
super(user, user.scene.getField()[target], playOnEmptyField);
super(user, gScene.getField()[target], playOnEmptyField);
this.move = move;
}

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import {
allAbilities,
applyAbAttrs,
@ -112,8 +112,8 @@ export class BattlerTag {
* @param scene medium to retrieve the source Pokemon
* @returns The source {@linkcode Pokemon} or `null` if none is found
*/
public getSourcePokemon(scene: BattleScene): Pokemon | null {
return this.sourceId ? scene.getPokemonById(this.sourceId) : null;
public getSourcePokemon(): Pokemon | null {
return this.sourceId ? gScene.getPokemonById(this.sourceId) : null;
}
}
@ -142,12 +142,12 @@ export abstract class MoveRestrictionBattlerTag extends BattlerTag {
override lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
if (lapseType === BattlerTagLapseType.PRE_MOVE) {
// Cancel the affected pokemon's selected move
const phase = pokemon.scene.getCurrentPhase() as MovePhase;
const phase = gScene.getCurrentPhase() as MovePhase;
const move = phase.move;
if (this.isMoveRestricted(move.moveId, pokemon)) {
if (this.interruptedText(pokemon, move.moveId)) {
pokemon.scene.queueMessage(this.interruptedText(pokemon, move.moveId));
gScene.queueMessage(this.interruptedText(pokemon, move.moveId));
}
phase.cancel();
}
@ -279,14 +279,14 @@ export class DisabledTag extends MoveRestrictionBattlerTag {
this.moveId = move.move;
pokemon.scene.queueMessage(i18next.t("battlerTags:disabledOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: allMoves[this.moveId].name }));
gScene.queueMessage(i18next.t("battlerTags:disabledOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: allMoves[this.moveId].name }));
}
/** @override */
override onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:disabledLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: allMoves[this.moveId].name }));
gScene.queueMessage(i18next.t("battlerTags:disabledLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: allMoves[this.moveId].name }));
}
/** @override */
@ -405,8 +405,8 @@ export class RechargingTag extends BattlerTag {
/** Cancels the source's move this turn and queues a "__ must recharge!" message */
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
if (lapseType === BattlerTagLapseType.PRE_MOVE) {
pokemon.scene.queueMessage(i18next.t("battlerTags:rechargingLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
(pokemon.scene.getCurrentPhase() as MovePhase).cancel();
gScene.queueMessage(i18next.t("battlerTags:rechargingLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
(gScene.getCurrentPhase() as MovePhase).cancel();
pokemon.getMoveQueue().shift();
}
return super.lapse(pokemon, lapseType);
@ -425,10 +425,10 @@ export class BeakBlastChargingTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
// Play Beak Blast's charging animation
new MoveChargeAnim(ChargeAnim.BEAK_BLAST_CHARGING, this.sourceMove, pokemon).play(pokemon.scene);
new MoveChargeAnim(ChargeAnim.BEAK_BLAST_CHARGING, this.sourceMove, pokemon).play();
// Queue Beak Blast's header message
pokemon.scene.queueMessage(i18next.t("moveTriggers:startedHeatingUpBeak", { pokemonName: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("moveTriggers:startedHeatingUpBeak", { pokemonName: getPokemonNameWithAffix(pokemon) }));
}
/**
@ -463,7 +463,7 @@ export class ShellTrapTag extends BattlerTag {
}
onAdd(pokemon: Pokemon): void {
pokemon.scene.queueMessage(i18next.t("moveTriggers:setUpShellTrap", { pokemonName: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("moveTriggers:setUpShellTrap", { pokemonName: getPokemonNameWithAffix(pokemon) }));
}
/**
@ -478,17 +478,17 @@ export class ShellTrapTag extends BattlerTag {
// Trap should only be triggered by opponent's Physical moves
if (phaseData?.move.category === MoveCategory.PHYSICAL && pokemon.isOpponent(phaseData.attacker)) {
const shellTrapPhaseIndex = pokemon.scene.phaseQueue.findIndex(
const shellTrapPhaseIndex = gScene.phaseQueue.findIndex(
phase => phase instanceof MovePhase && phase.pokemon === pokemon
);
const firstMovePhaseIndex = pokemon.scene.phaseQueue.findIndex(
const firstMovePhaseIndex = gScene.phaseQueue.findIndex(
phase => phase instanceof MovePhase
);
// Only shift MovePhase timing if it's not already next up
if (shellTrapPhaseIndex !== -1 && shellTrapPhaseIndex !== firstMovePhaseIndex) {
const shellTrapMovePhase = pokemon.scene.phaseQueue.splice(shellTrapPhaseIndex, 1)[0];
pokemon.scene.prependToPhase(shellTrapMovePhase, MovePhase);
const shellTrapMovePhase = gScene.phaseQueue.splice(shellTrapPhaseIndex, 1)[0];
gScene.prependToPhase(shellTrapMovePhase, MovePhase);
}
this.activated = true;
@ -507,7 +507,7 @@ export class TrappedTag extends BattlerTag {
}
canAdd(pokemon: Pokemon): boolean {
const source = pokemon.scene.getPokemonById(this.sourceId!)!;
const source = gScene.getPokemonById(this.sourceId!)!;
const move = allMoves[this.sourceMove];
const isGhost = pokemon.isOfType(Type.GHOST);
@ -520,13 +520,13 @@ export class TrappedTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(this.getTrapMessage(pokemon));
gScene.queueMessage(this.getTrapMessage(pokemon));
}
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:trappedOnRemove", {
gScene.queueMessage(i18next.t("battlerTags:trappedOnRemove", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
moveName: this.getMoveName()
}));
@ -584,8 +584,8 @@ export class FlinchedTag extends BattlerTag {
*/
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
if (lapseType === BattlerTagLapseType.PRE_MOVE) {
(pokemon.scene.getCurrentPhase() as MovePhase).cancel();
pokemon.scene.queueMessage(i18next.t("battlerTags:flinchedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
(gScene.getCurrentPhase() as MovePhase).cancel();
gScene.queueMessage(i18next.t("battlerTags:flinchedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
return super.lapse(pokemon, lapseType);
@ -613,7 +613,7 @@ export class InterruptedTag extends BattlerTag {
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
(pokemon.scene.getCurrentPhase() as MovePhase).cancel();
(gScene.getCurrentPhase() as MovePhase).cancel();
return super.lapse(pokemon, lapseType);
}
}
@ -627,44 +627,44 @@ export class ConfusedTag extends BattlerTag {
}
canAdd(pokemon: Pokemon): boolean {
return pokemon.scene.arena.terrain?.terrainType !== TerrainType.MISTY || !pokemon.isGrounded();
return gScene.arena.terrain?.terrainType !== TerrainType.MISTY || !pokemon.isGrounded();
}
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), undefined, CommonAnim.CONFUSION));
pokemon.scene.queueMessage(i18next.t("battlerTags:confusedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.CONFUSION));
gScene.queueMessage(i18next.t("battlerTags:confusedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:confusedOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:confusedOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
onOverlap(pokemon: Pokemon): void {
super.onOverlap(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:confusedOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:confusedOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
const ret = lapseType !== BattlerTagLapseType.CUSTOM && super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.queueMessage(i18next.t("battlerTags:confusedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), undefined, CommonAnim.CONFUSION));
gScene.queueMessage(i18next.t("battlerTags:confusedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.CONFUSION));
// 1/3 chance of hitting self with a 40 base power move
if (pokemon.randSeedInt(3) === 0) {
const atk = pokemon.getEffectiveStat(Stat.ATK);
const def = pokemon.getEffectiveStat(Stat.DEF);
const damage = toDmgValue(((((2 * pokemon.level / 5 + 2) * 40 * atk / def) / 50) + 2) * (pokemon.randSeedIntRange(85, 100) / 100));
pokemon.scene.queueMessage(i18next.t("battlerTags:confusedLapseHurtItself"));
gScene.queueMessage(i18next.t("battlerTags:confusedLapseHurtItself"));
pokemon.damageAndUpdate(damage);
pokemon.battleData.hitCount++;
(pokemon.scene.getCurrentPhase() as MovePhase).cancel();
(gScene.getCurrentPhase() as MovePhase).cancel();
}
}
@ -699,7 +699,7 @@ export class DestinyBondTag extends BattlerTag {
if (lapseType !== BattlerTagLapseType.CUSTOM) {
return super.lapse(pokemon, lapseType);
}
const source = this.sourceId ? pokemon.scene.getPokemonById(this.sourceId) : null;
const source = this.sourceId ? gScene.getPokemonById(this.sourceId) : null;
if (!source?.isFainted()) {
return true;
}
@ -709,11 +709,11 @@ export class DestinyBondTag extends BattlerTag {
}
if (pokemon.isBossImmune()) {
pokemon.scene.queueMessage(i18next.t("battlerTags:destinyBondLapseIsBoss", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:destinyBondLapseIsBoss", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
return false;
}
pokemon.scene.queueMessage(
gScene.queueMessage(
i18next.t("battlerTags:destinyBondLapse", {
pokemonNameWithAffix: getPokemonNameWithAffix(source),
pokemonNameWithAffix2: getPokemonNameWithAffix(pokemon)
@ -731,7 +731,7 @@ export class InfatuatedTag extends BattlerTag {
canAdd(pokemon: Pokemon): boolean {
if (this.sourceId) {
const pkm = pokemon.scene.getPokemonById(this.sourceId);
const pkm = gScene.getPokemonById(this.sourceId);
if (pkm) {
return pokemon.isOppositeGender(pkm);
@ -748,10 +748,10 @@ export class InfatuatedTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(
gScene.queueMessage(
i18next.t("battlerTags:infatuatedOnAdd", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
sourcePokemonName: getPokemonNameWithAffix(pokemon.scene.getPokemonById(this.sourceId!) ?? undefined) // TODO: is that bang correct?
sourcePokemonName: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined) // TODO: is that bang correct?
})
);
}
@ -759,24 +759,24 @@ export class InfatuatedTag extends BattlerTag {
onOverlap(pokemon: Pokemon): void {
super.onOverlap(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:infatuatedOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:infatuatedOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
const ret = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.queueMessage(
gScene.queueMessage(
i18next.t("battlerTags:infatuatedLapse", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
sourcePokemonName: getPokemonNameWithAffix(pokemon.scene.getPokemonById(this.sourceId!) ?? undefined) // TODO: is that bang correct?
sourcePokemonName: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined) // TODO: is that bang correct?
})
);
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), undefined, CommonAnim.ATTRACT));
gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.ATTRACT));
if (pokemon.randSeedInt(2)) {
pokemon.scene.queueMessage(i18next.t("battlerTags:infatuatedLapseImmobilize", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
(pokemon.scene.getCurrentPhase() as MovePhase).cancel();
gScene.queueMessage(i18next.t("battlerTags:infatuatedLapseImmobilize", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
(gScene.getCurrentPhase() as MovePhase).cancel();
}
}
@ -786,7 +786,7 @@ export class InfatuatedTag extends BattlerTag {
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:infatuatedOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:infatuatedOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
isSourceLinked(): boolean {
@ -821,8 +821,8 @@ export class SeedTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:seededOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
this.sourceIndex = pokemon.scene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct?
gScene.queueMessage(i18next.t("battlerTags:seededOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
this.sourceIndex = gScene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct?
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
@ -835,11 +835,11 @@ export class SeedTag extends BattlerTag {
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
if (!cancelled.value) {
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, source.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.LEECH_SEED));
gScene.unshiftPhase(new CommonAnimPhase(source.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.LEECH_SEED));
const damage = pokemon.damageAndUpdate(toDmgValue(pokemon.getMaxHp() / 8));
const reverseDrain = pokemon.hasAbilityWithAttr(ReverseDrainAbAttr, false);
pokemon.scene.unshiftPhase(new PokemonHealPhase(pokemon.scene, source.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(source.getBattlerIndex(),
!reverseDrain ? damage : damage * -1,
!reverseDrain ? i18next.t("battlerTags:seededLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }) : i18next.t("battlerTags:seededLapseShed", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }),
false, true));
@ -863,21 +863,21 @@ export class NightmareTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:nightmareOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:nightmareOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
onOverlap(pokemon: Pokemon): void {
super.onOverlap(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:nightmareOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:nightmareOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
const ret = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.queueMessage(i18next.t("battlerTags:nightmareLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), undefined, CommonAnim.CURSE)); // TODO: Update animation type
gScene.queueMessage(i18next.t("battlerTags:nightmareLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.CURSE)); // TODO: Update animation type
const cancelled = new BooleanHolder(false);
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
@ -956,15 +956,15 @@ export class EncoreTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:encoreOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:encoreOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
const movePhase = pokemon.scene.findPhase(m => m instanceof MovePhase && m.pokemon === pokemon);
const movePhase = gScene.findPhase(m => m instanceof MovePhase && m.pokemon === pokemon);
if (movePhase) {
const movesetMove = pokemon.getMoveset().find(m => m!.moveId === this.moveId); // TODO: is this bang correct?
if (movesetMove) {
const lastMove = pokemon.getLastXMoves(1)[0];
pokemon.scene.tryReplacePhase((m => m instanceof MovePhase && m.pokemon === pokemon),
new MovePhase(pokemon.scene, pokemon, lastMove.targets!, movesetMove)); // TODO: is this bang correct?
gScene.tryReplacePhase((m => m instanceof MovePhase && m.pokemon === pokemon),
new MovePhase(pokemon, lastMove.targets!, movesetMove)); // TODO: is this bang correct?
}
}
}
@ -972,7 +972,7 @@ export class EncoreTag extends BattlerTag {
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:encoreOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:encoreOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
@ -982,9 +982,9 @@ export class HelpingHandTag extends BattlerTag {
}
onAdd(pokemon: Pokemon): void {
pokemon.scene.queueMessage(
gScene.queueMessage(
i18next.t("battlerTags:helpingHandOnAdd", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon.scene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
pokemonNameWithAffix: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
pokemonName: getPokemonNameWithAffix(pokemon)
})
);
@ -1015,9 +1015,8 @@ export class IngrainTag extends TrappedTag {
const ret = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.unshiftPhase(
gScene.unshiftPhase(
new PokemonHealPhase(
pokemon.scene,
pokemon.getBattlerIndex(),
toDmgValue(pokemon.getMaxHp() / 16),
i18next.t("battlerTags:ingrainLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }),
@ -1055,7 +1054,7 @@ export class OctolockTag extends TrappedTag {
const shouldLapse = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType);
if (shouldLapse) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), false, [ Stat.DEF, Stat.SPDEF ], -1));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, [ Stat.DEF, Stat.SPDEF ], -1));
return true;
}
@ -1071,16 +1070,15 @@ export class AquaRingTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:aquaRingOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:aquaRingOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
const ret = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.unshiftPhase(
gScene.unshiftPhase(
new PokemonHealPhase(
pokemon.scene,
pokemon.getBattlerIndex(),
toDmgValue(pokemon.getMaxHp() / 16),
i18next.t("battlerTags:aquaRingLapse", {
@ -1119,13 +1117,13 @@ export class DrowsyTag extends BattlerTag {
}
canAdd(pokemon: Pokemon): boolean {
return pokemon.scene.arena.terrain?.terrainType !== TerrainType.ELECTRIC || !pokemon.isGrounded();
return gScene.arena.terrain?.terrainType !== TerrainType.ELECTRIC || !pokemon.isGrounded();
}
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:drowsyOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:drowsyOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
@ -1168,13 +1166,13 @@ export abstract class DamagingTrapTag extends TrappedTag {
const ret = super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.queueMessage(
gScene.queueMessage(
i18next.t("battlerTags:damagingTrapLapse", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
moveName: this.getMoveName()
})
);
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), undefined, this.commonAnim));
gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, this.commonAnim));
const cancelled = new BooleanHolder(false);
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
@ -1196,7 +1194,7 @@ export class BindTag extends DamagingTrapTag {
getTrapMessage(pokemon: Pokemon): string {
return i18next.t("battlerTags:bindOnTrap", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
sourcePokemonName: getPokemonNameWithAffix(pokemon.scene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
sourcePokemonName: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
moveName: this.getMoveName()
});
}
@ -1210,7 +1208,7 @@ export class WrapTag extends DamagingTrapTag {
getTrapMessage(pokemon: Pokemon): string {
return i18next.t("battlerTags:wrapOnTrap", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
sourcePokemonName: getPokemonNameWithAffix(pokemon.scene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
sourcePokemonName: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
});
}
}
@ -1244,7 +1242,7 @@ export class ClampTag extends DamagingTrapTag {
getTrapMessage(pokemon: Pokemon): string {
return i18next.t("battlerTags:clampOnTrap", {
sourcePokemonNameWithAffix: getPokemonNameWithAffix(pokemon.scene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
sourcePokemonNameWithAffix: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
pokemonName: getPokemonNameWithAffix(pokemon),
});
}
@ -1291,7 +1289,7 @@ export class ThunderCageTag extends DamagingTrapTag {
getTrapMessage(pokemon: Pokemon): string {
return i18next.t("battlerTags:thunderCageOnTrap", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
sourcePokemonNameWithAffix: getPokemonNameWithAffix(pokemon.scene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
sourcePokemonNameWithAffix: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
});
}
}
@ -1304,7 +1302,7 @@ export class InfestationTag extends DamagingTrapTag {
getTrapMessage(pokemon: Pokemon): string {
return i18next.t("battlerTags:infestationOnTrap", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
sourcePokemonNameWithAffix: getPokemonNameWithAffix(pokemon.scene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
sourcePokemonNameWithAffix: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct?
});
}
}
@ -1318,16 +1316,16 @@ export class ProtectedTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:protectedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:protectedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
if (lapseType === BattlerTagLapseType.CUSTOM) {
new CommonBattleAnim(CommonAnim.PROTECT, pokemon).play(pokemon.scene);
pokemon.scene.queueMessage(i18next.t("battlerTags:protectedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
new CommonBattleAnim(CommonAnim.PROTECT, pokemon).play();
gScene.queueMessage(i18next.t("battlerTags:protectedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
// Stop multi-hit moves early
const effectPhase = pokemon.scene.getCurrentPhase();
const effectPhase = gScene.getCurrentPhase();
if (effectPhase instanceof MoveEffectPhase) {
effectPhase.stopMultiHit(pokemon);
}
@ -1367,7 +1365,7 @@ export class ContactDamageProtectedTag extends ProtectedTag {
const ret = super.lapse(pokemon, lapseType);
if (lapseType === BattlerTagLapseType.CUSTOM) {
const effectPhase = pokemon.scene.getCurrentPhase();
const effectPhase = gScene.getCurrentPhase();
if (effectPhase instanceof MoveEffectPhase && effectPhase.move.getMove().hasFlag(MoveFlags.MAKES_CONTACT)) {
const attacker = effectPhase.getPokemon();
if (!attacker.hasAbilityWithAttr(BlockNonDirectDamageAbAttr)) {
@ -1409,10 +1407,10 @@ export class ContactStatStageChangeProtectedTag extends DamageProtectedTag {
const ret = super.lapse(pokemon, lapseType);
if (lapseType === BattlerTagLapseType.CUSTOM) {
const effectPhase = pokemon.scene.getCurrentPhase();
const effectPhase = gScene.getCurrentPhase();
if (effectPhase instanceof MoveEffectPhase && effectPhase.move.getMove().hasFlag(MoveFlags.MAKES_CONTACT)) {
const attacker = effectPhase.getPokemon();
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, attacker.getBattlerIndex(), false, [ this.stat ], this.levels));
gScene.unshiftPhase(new StatStageChangePhase(attacker.getBattlerIndex(), false, [ this.stat ], this.levels));
}
}
@ -1429,7 +1427,7 @@ export class ContactPoisonProtectedTag extends ProtectedTag {
const ret = super.lapse(pokemon, lapseType);
if (lapseType === BattlerTagLapseType.CUSTOM) {
const effectPhase = pokemon.scene.getCurrentPhase();
const effectPhase = gScene.getCurrentPhase();
if (effectPhase instanceof MoveEffectPhase && effectPhase.move.getMove().hasFlag(MoveFlags.MAKES_CONTACT)) {
const attacker = effectPhase.getPokemon();
attacker.trySetStatus(StatusEffect.POISON, true, pokemon);
@ -1453,7 +1451,7 @@ export class ContactBurnProtectedTag extends DamageProtectedTag {
const ret = super.lapse(pokemon, lapseType);
if (lapseType === BattlerTagLapseType.CUSTOM) {
const effectPhase = pokemon.scene.getCurrentPhase();
const effectPhase = gScene.getCurrentPhase();
if (effectPhase instanceof MoveEffectPhase && effectPhase.move.getMove().hasFlag(MoveFlags.MAKES_CONTACT)) {
const attacker = effectPhase.getPokemon();
attacker.trySetStatus(StatusEffect.BURN, true);
@ -1472,12 +1470,12 @@ export class EnduringTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:enduringOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:enduringOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
if (lapseType === BattlerTagLapseType.CUSTOM) {
pokemon.scene.queueMessage(i18next.t("battlerTags:enduringLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:enduringLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
return true;
}
@ -1492,7 +1490,7 @@ export class SturdyTag extends BattlerTag {
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
if (lapseType === BattlerTagLapseType.CUSTOM) {
pokemon.scene.queueMessage(i18next.t("battlerTags:sturdyLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:sturdyLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
return true;
}
@ -1513,7 +1511,7 @@ export class PerishSongTag extends BattlerTag {
const ret = super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.queueMessage(
gScene.queueMessage(
i18next.t("battlerTags:perishSongLapse", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
turnCount: this.turnCount
@ -1542,7 +1540,7 @@ export class CenterOfAttentionTag extends BattlerTag {
/** "Center of Attention" can't be added if an ally is already the Center of Attention. */
canAdd(pokemon: Pokemon): boolean {
const activeTeam = pokemon.isPlayer() ? pokemon.scene.getPlayerField() : pokemon.scene.getEnemyField();
const activeTeam = pokemon.isPlayer() ? gScene.getPlayerField() : gScene.getEnemyField();
return !activeTeam.find(p => p.getTag(BattlerTagType.CENTER_OF_ATTENTION));
}
@ -1550,7 +1548,7 @@ export class CenterOfAttentionTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:centerOfAttentionOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:centerOfAttentionOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
@ -1587,9 +1585,9 @@ export class TruantTag extends AbilityBattlerTag {
const lastMove = pokemon.getLastXMoves().find(() => true);
if (lastMove && lastMove.move !== Moves.NONE) {
(pokemon.scene.getCurrentPhase() as MovePhase).cancel();
pokemon.scene.unshiftPhase(new ShowAbilityPhase(pokemon.scene, pokemon.id, passive));
pokemon.scene.queueMessage(i18next.t("battlerTags:truantLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
(gScene.getCurrentPhase() as MovePhase).cancel();
gScene.unshiftPhase(new ShowAbilityPhase(pokemon.id, passive));
gScene.queueMessage(i18next.t("battlerTags:truantLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
return true;
@ -1604,7 +1602,7 @@ export class SlowStartTag extends AbilityBattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:slowStartOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null, true);
gScene.queueMessage(i18next.t("battlerTags:slowStartOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null, true);
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
@ -1618,7 +1616,7 @@ export class SlowStartTag extends AbilityBattlerTag {
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:slowStartOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null);
gScene.queueMessage(i18next.t("battlerTags:slowStartOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null);
}
}
@ -1664,13 +1662,13 @@ export class HighestStatBoostTag extends AbilityBattlerTag {
break;
}
pokemon.scene.queueMessage(i18next.t("battlerTags:highestStatBoostOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), statName: i18next.t(getStatKey(highestStat)) }), null, false, null, true);
gScene.queueMessage(i18next.t("battlerTags:highestStatBoostOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), statName: i18next.t(getStatKey(highestStat)) }), null, false, null, true);
}
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:highestStatBoostOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName: allAbilities[this.ability].name }));
gScene.queueMessage(i18next.t("battlerTags:highestStatBoostOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName: allAbilities[this.ability].name }));
}
}
@ -1723,7 +1721,7 @@ export class SemiInvulnerableTag extends BattlerTag {
onRemove(pokemon: Pokemon): void {
// Wait 2 frames before setting visible for battle animations that don't immediately show the sprite invisible
pokemon.scene.tweens.addCounter({
gScene.tweens.addCounter({
duration: getFrameMs(2),
onComplete: () => pokemon.setVisible(true)
});
@ -1763,7 +1761,7 @@ export class FloatingTag extends TypeImmuneTag {
super.onAdd(pokemon);
if (this.sourceMove === Moves.MAGNET_RISE) {
pokemon.scene.queueMessage(i18next.t("battlerTags:magnetRisenOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:magnetRisenOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
@ -1771,7 +1769,7 @@ export class FloatingTag extends TypeImmuneTag {
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
if (this.sourceMove === Moves.MAGNET_RISE) {
pokemon.scene.queueMessage(i18next.t("battlerTags:magnetRisenOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:magnetRisenOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
}
@ -1813,7 +1811,7 @@ export class CritBoostTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:critBoostOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:critBoostOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
@ -1823,7 +1821,7 @@ export class CritBoostTag extends BattlerTag {
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:critBoostOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:critBoostOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
@ -1865,15 +1863,15 @@ export class SaltCuredTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:saltCuredOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
this.sourceIndex = pokemon.scene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct?
gScene.queueMessage(i18next.t("battlerTags:saltCuredOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
this.sourceIndex = gScene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct?
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
const ret = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.SALT_CURE));
gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.SALT_CURE));
const cancelled = new BooleanHolder(false);
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
@ -1882,7 +1880,7 @@ export class SaltCuredTag extends BattlerTag {
const pokemonSteelOrWater = pokemon.isOfType(Type.STEEL) || pokemon.isOfType(Type.WATER);
pokemon.damageAndUpdate(toDmgValue(pokemonSteelOrWater ? pokemon.getMaxHp() / 4 : pokemon.getMaxHp() / 8));
pokemon.scene.queueMessage(
gScene.queueMessage(
i18next.t("battlerTags:saltCuredLapse", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
moveName: this.getMoveName()
@ -1913,21 +1911,21 @@ export class CursedTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
this.sourceIndex = pokemon.scene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct?
this.sourceIndex = gScene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct?
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
const ret = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType);
if (ret) {
pokemon.scene.unshiftPhase(new CommonAnimPhase(pokemon.scene, pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.SALT_CURE));
gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.SALT_CURE));
const cancelled = new BooleanHolder(false);
applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled);
if (!cancelled.value) {
pokemon.damageAndUpdate(toDmgValue(pokemon.getMaxHp() / 4));
pokemon.scene.queueMessage(i18next.t("battlerTags:cursedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:cursedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
@ -2041,7 +2039,7 @@ export class FormBlockDamageTag extends BattlerTag {
super.onAdd(pokemon);
if (pokemon.formIndex !== 0) {
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
}
}
@ -2053,7 +2051,7 @@ export class FormBlockDamageTag extends BattlerTag {
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
}
}
/** Provides the additional weather-based effects of the Ice Face ability */
@ -2068,7 +2066,7 @@ export class IceFaceBlockDamageTag extends FormBlockDamageTag {
* @returns {boolean} True if the tag can be added, false otherwise.
*/
canAdd(pokemon: Pokemon): boolean {
const weatherType = pokemon.scene.arena.weather?.weatherType;
const weatherType = gScene.arena.weather?.weatherType;
const isWeatherSnowOrHail = weatherType === WeatherType.HAIL || weatherType === WeatherType.SNOW;
return super.canAdd(pokemon) || isWeatherSnowOrHail;
@ -2127,14 +2125,14 @@ export class StockpilingTag extends BattlerTag {
if (this.stockpiledCount < 3) {
this.stockpiledCount++;
pokemon.scene.queueMessage(i18next.t("battlerTags:stockpilingOnAdd", {
gScene.queueMessage(i18next.t("battlerTags:stockpilingOnAdd", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon),
stockpiledCount: this.stockpiledCount
}));
// Attempt to increase DEF and SPDEF by one stage, keeping track of successful changes.
pokemon.scene.unshiftPhase(new StatStageChangePhase(
pokemon.scene, pokemon.getBattlerIndex(), true,
gScene.unshiftPhase(new StatStageChangePhase(
pokemon.getBattlerIndex(), true,
[ Stat.SPDEF, Stat.DEF ], 1, true, false, true, this.onStatStagesChanged
));
}
@ -2153,11 +2151,11 @@ export class StockpilingTag extends BattlerTag {
const spDefChange = this.statChangeCounts[Stat.SPDEF];
if (defChange) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.DEF ], -defChange, true, false, true));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.DEF ], -defChange, true, false, true));
}
if (spDefChange) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.SPDEF ], -spDefChange, true, false, true));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPDEF ], -spDefChange, true, false, true));
}
}
}
@ -2176,7 +2174,7 @@ export class GulpMissileTag extends BattlerTag {
return true;
}
const moveEffectPhase = pokemon.scene.getCurrentPhase();
const moveEffectPhase = gScene.getCurrentPhase();
if (moveEffectPhase instanceof MoveEffectPhase) {
const attacker = moveEffectPhase.getUserPokemon();
@ -2196,7 +2194,7 @@ export class GulpMissileTag extends BattlerTag {
}
if (this.tagType === BattlerTagType.GULP_MISSILE_ARROKUDA) {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, attacker.getBattlerIndex(), false, [ Stat.DEF ], -1));
gScene.unshiftPhase(new StatStageChangePhase(attacker.getBattlerIndex(), false, [ Stat.DEF ], -1));
} else {
attacker.trySetStatus(StatusEffect.PARALYSIS, true, pokemon);
}
@ -2219,12 +2217,12 @@ export class GulpMissileTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
super.onAdd(pokemon);
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
}
onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
}
}
@ -2332,7 +2330,7 @@ export class HealBlockTag extends MoveRestrictionBattlerTag {
override onRemove(pokemon: Pokemon): void {
super.onRemove(pokemon);
pokemon.scene.queueMessage(i18next.t("battle:battlerTagsHealBlockOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null);
gScene.queueMessage(i18next.t("battle:battlerTagsHealBlockOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null);
}
}
@ -2355,7 +2353,7 @@ export class TarShotTag extends BattlerTag {
}
override onAdd(pokemon: Pokemon): void {
pokemon.scene.queueMessage(i18next.t("battlerTags:tarShotOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:tarShotOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
@ -2370,7 +2368,7 @@ export class ElectrifiedTag extends BattlerTag {
override onAdd(pokemon: Pokemon): void {
// "{pokemonNameWithAffix}'s moves have been electrified!"
pokemon.scene.queueMessage(i18next.t("battlerTags:electrifiedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:electrifiedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
@ -2392,7 +2390,7 @@ export class AutotomizedTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
const minWeight = 0.1;
if (pokemon.getWeight() > minWeight) {
pokemon.scene.queueMessage(i18next.t("battlerTags:autotomizeOnAdd", {
gScene.queueMessage(i18next.t("battlerTags:autotomizeOnAdd", {
pokemonNameWithAffix: getPokemonNameWithAffix(pokemon)
}));
}
@ -2423,15 +2421,15 @@ export class SubstituteTag extends BattlerTag {
/** Sets the Substitute's HP and queues an on-add battle animation that initializes the Substitute's sprite. */
onAdd(pokemon: Pokemon): void {
this.hp = Math.floor(pokemon.scene.getPokemonById(this.sourceId!)!.getMaxHp() / 4);
this.hp = Math.floor(gScene.getPokemonById(this.sourceId!)!.getMaxHp() / 4);
this.sourceInFocus = false;
// Queue battle animation and message
pokemon.scene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_ADD);
gScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_ADD);
if (this.sourceMove === Moves.SHED_TAIL) {
pokemon.scene.queueMessage(i18next.t("battlerTags:shedTailOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500);
gScene.queueMessage(i18next.t("battlerTags:shedTailOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500);
} else {
pokemon.scene.queueMessage(i18next.t("battlerTags:substituteOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500);
gScene.queueMessage(i18next.t("battlerTags:substituteOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500);
}
// Remove any binding effects from the user
@ -2442,11 +2440,11 @@ export class SubstituteTag extends BattlerTag {
onRemove(pokemon: Pokemon): void {
// Only play the animation if the cause of removal isn't from the source's own move
if (!this.sourceInFocus) {
pokemon.scene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_REMOVE, [ this.sprite ]);
gScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_REMOVE, [ this.sprite ]);
} else {
this.sprite.destroy();
}
pokemon.scene.queueMessage(i18next.t("battlerTags:substituteOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:substituteOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
@ -2466,26 +2464,26 @@ export class SubstituteTag extends BattlerTag {
/** Triggers an animation that brings the Pokemon into focus before it uses a move */
onPreMove(pokemon: Pokemon): void {
pokemon.scene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_PRE_MOVE, [ this.sprite ]);
gScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_PRE_MOVE, [ this.sprite ]);
this.sourceInFocus = true;
}
/** Triggers an animation that brings the Pokemon out of focus after it uses a move */
onAfterMove(pokemon: Pokemon): void {
pokemon.scene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_POST_MOVE, [ this.sprite ]);
gScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_POST_MOVE, [ this.sprite ]);
this.sourceInFocus = false;
}
/** If the Substitute redirects damage, queue a message to indicate it. */
onHit(pokemon: Pokemon): void {
const moveEffectPhase = pokemon.scene.getCurrentPhase();
const moveEffectPhase = gScene.getCurrentPhase();
if (moveEffectPhase instanceof MoveEffectPhase) {
const attacker = moveEffectPhase.getUserPokemon()!;
const move = moveEffectPhase.move.getMove();
const firstHit = (attacker.turnData.hitCount === attacker.turnData.hitsLeft);
if (firstHit && move.hitsSubstitute(attacker, pokemon)) {
pokemon.scene.queueMessage(i18next.t("battlerTags:substituteOnHit", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:substituteOnHit", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
}
@ -2557,7 +2555,7 @@ export class TormentTag extends MoveRestrictionBattlerTag {
*/
override onAdd(pokemon: Pokemon) {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:tormentOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500);
gScene.queueMessage(i18next.t("battlerTags:tormentOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500);
}
/**
@ -2611,7 +2609,7 @@ export class TauntTag extends MoveRestrictionBattlerTag {
override onAdd(pokemon: Pokemon) {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:tauntOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500);
gScene.queueMessage(i18next.t("battlerTags:tauntOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500);
}
/**
@ -2649,7 +2647,7 @@ export class ImprisonTag extends MoveRestrictionBattlerTag {
* @returns `true` if the source is still active
*/
public override lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean {
const source = this.getSourcePokemon(pokemon.scene);
const source = this.getSourcePokemon();
if (source) {
if (lapseType === BattlerTagLapseType.PRE_MOVE) {
return super.lapse(pokemon, lapseType) && source.isActive(true);
@ -2667,7 +2665,7 @@ export class ImprisonTag extends MoveRestrictionBattlerTag {
* @returns `false` if either condition is not met
*/
public override isMoveRestricted(move: Moves, user: Pokemon): boolean {
const source = this.getSourcePokemon(user.scene);
const source = this.getSourcePokemon();
if (source) {
const sourceMoveset = source.getMoveset().map(m => m!.moveId);
return sourceMoveset?.includes(move) && source.isActive(true);
@ -2700,7 +2698,7 @@ export class SyrupBombTag extends BattlerTag {
*/
override onAdd(pokemon: Pokemon) {
super.onAdd(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:syrupBombOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:syrupBombOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
/**
@ -2710,13 +2708,13 @@ export class SyrupBombTag extends BattlerTag {
* @returns `true` if the `turnCount` is still greater than `0`; `false` if the `turnCount` is `0` or the target or source Pokemon has been removed from the field
*/
override lapse(pokemon: Pokemon, _lapseType: BattlerTagLapseType): boolean {
if (this.sourceId && !pokemon.scene.getPokemonById(this.sourceId)?.isActive(true)) {
if (this.sourceId && !gScene.getPokemonById(this.sourceId)?.isActive(true)) {
return false;
}
// Custom message in lieu of an animation in mainline
pokemon.scene.queueMessage(i18next.t("battlerTags:syrupBombLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
pokemon.scene.unshiftPhase(new StatStageChangePhase(
pokemon.scene, pokemon.getBattlerIndex(), true,
gScene.queueMessage(i18next.t("battlerTags:syrupBombLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.unshiftPhase(new StatStageChangePhase(
pokemon.getBattlerIndex(), true,
[ Stat.SPD ], -1, true, false, true
));
return --this.turnCount > 0;
@ -2735,7 +2733,7 @@ export class TelekinesisTag extends BattlerTag {
}
override onAdd(pokemon: Pokemon) {
pokemon.scene.queueMessage(i18next.t("battlerTags:telekinesisOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:telekinesisOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
}
@ -2750,12 +2748,12 @@ export class PowerTrickTag extends BattlerTag {
onAdd(pokemon: Pokemon): void {
this.swapStat(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:powerTrickActive", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:powerTrickActive", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
onRemove(pokemon: Pokemon): void {
this.swapStat(pokemon);
pokemon.scene.queueMessage(i18next.t("battlerTags:powerTrickActive", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("battlerTags:powerTrickActive", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
/**
@ -2979,7 +2977,7 @@ export function loadBattlerTag(source: BattlerTag | any): BattlerTag {
* corresponding {@linkcode Move} and user {@linkcode Pokemon}
*/
function getMoveEffectPhaseData(pokemon: Pokemon): {phase: MoveEffectPhase, attacker: Pokemon, move: Move} | null {
const phase = pokemon.scene.getCurrentPhase();
const phase = gScene.getCurrentPhase();
if (phase instanceof MoveEffectPhase) {
return {
phase : phase,

View File

@ -9,6 +9,7 @@ import { BerryType } from "#enums/berry-type";
import { Stat, type BattleStat } from "#app/enums/stat";
import { PokemonHealPhase } from "#app/phases/pokemon-heal-phase";
import { StatStageChangePhase } from "#app/phases/stat-stage-change-phase";
import { gScene } from "#app/battle-scene";
export function getBerryName(berryType: BerryType): string {
return i18next.t(`berry:${BerryType[berryType]}.name`);
@ -73,7 +74,7 @@ export function getBerryEffectFunc(berryType: BerryType): BerryEffectFunc {
}
const hpHealed = new Utils.NumberHolder(Utils.toDmgValue(pokemon.getMaxHp() / 4));
applyAbAttrs(DoubleBerryEffectAbAttr, pokemon, null, false, hpHealed);
pokemon.scene.unshiftPhase(new PokemonHealPhase(pokemon.scene, pokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(),
hpHealed.value, i18next.t("battle:hpHealBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), berryName: getBerryName(berryType) }), true));
};
case BerryType.LUM:
@ -82,7 +83,7 @@ export function getBerryEffectFunc(berryType: BerryType): BerryEffectFunc {
pokemon.battleData.berriesEaten.push(berryType);
}
if (pokemon.status) {
pokemon.scene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon)));
gScene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon)));
}
pokemon.resetStatus(true, true);
pokemon.updateInfo();
@ -100,7 +101,7 @@ export function getBerryEffectFunc(berryType: BerryType): BerryEffectFunc {
const stat: BattleStat = berryType - BerryType.ENIGMA;
const statStages = new Utils.NumberHolder(1);
applyAbAttrs(DoubleBerryEffectAbAttr, pokemon, null, false, statStages);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ stat ], statStages.value));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], statStages.value));
};
case BerryType.LANSAT:
return (pokemon: Pokemon) => {
@ -117,7 +118,7 @@ export function getBerryEffectFunc(berryType: BerryType): BerryEffectFunc {
const randStat = Utils.randSeedInt(Stat.SPD, Stat.ATK);
const stages = new Utils.NumberHolder(2);
applyAbAttrs(DoubleBerryEffectAbAttr, pokemon, null, false, stages);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ randStat ], stages.value));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ randStat ], stages.value));
};
case BerryType.LEPPA:
return (pokemon: Pokemon) => {
@ -127,7 +128,7 @@ export function getBerryEffectFunc(berryType: BerryType): BerryEffectFunc {
const ppRestoreMove = pokemon.getMoveset().find(m => !m?.getPpRatio()) ? pokemon.getMoveset().find(m => !m?.getPpRatio()) : pokemon.getMoveset().find(m => m!.getPpRatio() < 1); // TODO: is this bang correct?
if (ppRestoreMove !== undefined) {
ppRestoreMove!.ppUsed = Math.max(ppRestoreMove!.ppUsed - 10, 0);
pokemon.scene.queueMessage(i18next.t("battle:ppHealBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: ppRestoreMove!.getName(), berryName: getBerryName(berryType) }));
gScene.queueMessage(i18next.t("battle:ppHealBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: ppRestoreMove!.getName(), berryName: getBerryName(berryType) }));
}
};
}

View File

@ -467,7 +467,7 @@ export class SingleGenerationChallenge extends Challenge {
if (trainerTypes.length === 0) {
return false;
} else {
battleConfig.setBattleType(BattleType.TRAINER).setGetTrainerFunc(scene => new Trainer(scene, trainerTypes[this.value - 1], TrainerVariant.DEFAULT));
battleConfig.setBattleType(BattleType.TRAINER).setGetTrainerFunc(() => new Trainer(trainerTypes[this.value - 1], TrainerVariant.DEFAULT));
return true;
}
}

View File

@ -1,6 +1,6 @@
import { PartyMemberStrength } from "#enums/party-member-strength";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { PlayerPokemon } from "#app/field/pokemon";
import { Starter } from "#app/ui/starter-select-ui-handler";
import * as Utils from "#app/utils";
@ -25,17 +25,17 @@ export function fetchDailyRunSeed(): Promise<string | null> {
});
}
export function getDailyRunStarters(scene: BattleScene, seed: string): Starter[] {
export function getDailyRunStarters(seed: string): Starter[] {
const starters: Starter[] = [];
scene.executeWithSeedOffset(() => {
const startingLevel = scene.gameMode.getStartingLevel();
gScene.executeWithSeedOffset(() => {
const startingLevel = gScene.gameMode.getStartingLevel();
if (/\d{18}$/.test(seed)) {
for (let s = 0; s < 3; s++) {
const offset = 6 + s * 6;
const starterSpeciesForm = getPokemonSpeciesForm(parseInt(seed.slice(offset, offset + 4)) as Species, parseInt(seed.slice(offset + 4, offset + 6)));
starters.push(getDailyRunStarter(scene, starterSpeciesForm, startingLevel));
starters.push(getDailyRunStarter(starterSpeciesForm, startingLevel));
}
return;
}
@ -52,17 +52,17 @@ export function getDailyRunStarters(scene: BattleScene, seed: string): Starter[]
.filter(s => speciesStarterCosts[s] === cost);
const randPkmSpecies = getPokemonSpecies(Utils.randSeedItem(costSpecies));
const starterSpecies = getPokemonSpecies(randPkmSpecies.getTrainerSpeciesForLevel(startingLevel, true, PartyMemberStrength.STRONGER));
starters.push(getDailyRunStarter(scene, starterSpecies, startingLevel));
starters.push(getDailyRunStarter(starterSpecies, startingLevel));
}
}, 0, seed);
return starters;
}
function getDailyRunStarter(scene: BattleScene, starterSpeciesForm: PokemonSpeciesForm, startingLevel: integer): Starter {
function getDailyRunStarter(starterSpeciesForm: PokemonSpeciesForm, startingLevel: integer): Starter {
const starterSpecies = starterSpeciesForm instanceof PokemonSpecies ? starterSpeciesForm : getPokemonSpecies(starterSpeciesForm.speciesId);
const formIndex = starterSpeciesForm instanceof PokemonSpecies ? undefined : starterSpeciesForm.formIndex;
const pokemon = new PlayerPokemon(scene, starterSpecies, startingLevel, undefined, formIndex, undefined, undefined, undefined, undefined, undefined, undefined);
const pokemon = new PlayerPokemon(starterSpecies, startingLevel, undefined, formIndex, undefined, undefined, undefined, undefined, undefined, undefined);
const starter: Starter = {
species: starterSpecies,
dexAttr: pokemon.getDexAttr(),

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { PlayerPokemon } from "#app/field/pokemon";
import { DexEntry, StarterDataEntry } from "#app/system/game-data";
@ -17,11 +17,8 @@ export class EggHatchData {
public dexEntryBeforeUpdate: DexEntry;
/** stored copy of the hatched pokemon's starter entry before it was updated due to hatch */
public starterDataEntryBeforeUpdate: StarterDataEntry;
/** reference to the battle scene to get gamedata and update dex */
private scene: BattleScene;
constructor(scene: BattleScene, pokemon: PlayerPokemon, eggMoveIndex: number) {
this.scene = scene;
constructor(pokemon: PlayerPokemon, eggMoveIndex: number) {
this.pokemon = pokemon;
this.eggMoveIndex = eggMoveIndex;
}
@ -39,8 +36,8 @@ export class EggHatchData {
* Used before updating the dex, so comparing the pokemon to these entries will show the new attributes
*/
setDex() {
const currDexEntry = this.scene.gameData.dexData[this.pokemon.species.speciesId];
const currStarterDataEntry = this.scene.gameData.starterData[this.pokemon.species.getRootSpeciesId()];
const currDexEntry = gScene.gameData.dexData[this.pokemon.species.speciesId];
const currStarterDataEntry = gScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()];
this.dexEntryBeforeUpdate = {
seenAttr: currDexEntry.seenAttr,
caughtAttr: currDexEntry.caughtAttr,
@ -86,9 +83,9 @@ export class EggHatchData {
*/
updatePokemon(showMessage : boolean = false) {
return new Promise<void>(resolve => {
this.scene.gameData.setPokemonCaught(this.pokemon, true, true, showMessage).then(() => {
this.scene.gameData.updateSpeciesDexIvs(this.pokemon.species.speciesId, this.pokemon.ivs);
this.scene.gameData.setEggMoveUnlocked(this.pokemon.species, this.eggMoveIndex, showMessage).then((value) => {
gScene.gameData.setPokemonCaught(this.pokemon, true, true, showMessage).then(() => {
gScene.gameData.updateSpeciesDexIvs(this.pokemon.species.speciesId, this.pokemon.ivs);
gScene.gameData.setEggMoveUnlocked(this.pokemon.species, this.eggMoveIndex, showMessage).then((value) => {
this.setEggMoveUnlocked(value);
resolve();
});

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import BattleScene, { gScene } from "#app/battle-scene";
import PokemonSpecies, { getPokemonSpecies } from "#app/data/pokemon-species";
import { speciesStarterCosts } from "#app/data/balance/starters";
import { VariantTier } from "#enums/variant-tier";
@ -17,42 +17,42 @@ export const EGG_SEED = 1073741824;
/** Egg options to override egg properties */
export interface IEggOptions {
/** Id. Used to check if egg type will be manaphy (id % 204 === 0) */
/** Id. Used to check if egg type will be manaphy (`id % 204 === 0`) */
id?: number;
/** Timestamp when this egg got created */
timestamp?: number;
/** Defines if the egg got pulled from a gacha or not. If true, egg pity and pull statistics will be applyed.
/**
* Defines if the egg got pulled from a gacha or not. If true, egg pity and pull statistics will be applied.
* Egg will be automaticly added to the game data.
* NEEDS scene eggOption to work.
*/
pulled?: boolean;
/** Defines where the egg comes from. Applies specific modifiers.
/**
* Defines where the egg comes from. Applies specific modifiers.
* Will also define the text displayed in the egg list.
*/
sourceType?: EggSourceType;
/** Needs to be defined if eggOption pulled is defined or if no species or isShiny is degined since this will be needed to generate them. */
/** Legacy field, kept for backwards-compatibility */
scene?: BattleScene;
/** Sets the tier of the egg. Only species of this tier can be hatched from this egg.
/**
* Sets the tier of the egg. Only species of this tier can be hatched from this egg.
* Tier will be overriden if species eggOption is set.
*/
tier?: EggTier;
/** Sets how many waves it will take till this egg hatches. */
hatchWaves?: number;
/** Sets the exact species that will hatch from this egg.
* Needs scene eggOption if not provided.
*/
/** Sets the exact species that will hatch from this egg. */
species?: Species;
/** Defines if the hatched pokemon will be a shiny. */
isShiny?: boolean;
/** Defines the variant of the pokemon that will hatch from this egg. If no variantTier is given the normal variant rates will apply. */
/** Defines the variant of the pokemon that will hatch from this egg. If no `variantTier` is given the normal variant rates will apply. */
variantTier?: VariantTier;
/** Defines which egg move will be unlocked. 3 = rare egg move. */
eggMoveIndex?: number;
/** Defines if the egg will hatch with the hidden ability of this species.
* If no hidden ability exist, a random one will get choosen.
/**
* Defines if the egg will hatch with the hidden ability of this species.
* If no hidden ability exist, a random one will get choosen.
*/
overrideHiddenAbility?: boolean,
overrideHiddenAbility?: boolean;
/** Can customize the message displayed for where the egg was obtained */
eggDescriptor?: string;
}
@ -143,7 +143,7 @@ export class Egg {
// If egg was pulled, check if egg pity needs to override the egg tier
if (eggOptions?.pulled) {
// Needs this._tier and this._sourceType to work
this.checkForPityTierOverrides(eggOptions.scene!); // TODO: is this bang correct?
this.checkForPityTierOverrides();
}
this._id = eggOptions?.id ?? Utils.randInt(EGG_SEED, EGG_SEED * this._tier);
@ -155,7 +155,7 @@ export class Egg {
// First roll shiny and variant so we can filter if species with an variant exist
this._isShiny = eggOptions?.isShiny ?? (Overrides.EGG_SHINY_OVERRIDE || this.rollShiny());
this._variantTier = eggOptions?.variantTier ?? (Overrides.EGG_VARIANT_OVERRIDE ?? this.rollVariant());
this._species = eggOptions?.species ?? this.rollSpecies(eggOptions!.scene!)!; // TODO: Are those bangs correct?
this._species = eggOptions?.species ?? this.rollSpecies()!; // TODO: Is this bang correct?
this._overrideHiddenAbility = eggOptions?.overrideHiddenAbility ?? false;
@ -173,8 +173,8 @@ export class Egg {
// Needs this._tier so it needs to be generated afer the tier override if bought from same species
this._eggMoveIndex = eggOptions?.eggMoveIndex ?? this.rollEggMoveIndex();
if (eggOptions?.pulled) {
this.increasePullStatistic(eggOptions.scene!); // TODO: is this bang correct?
this.addEggToGameData(eggOptions.scene!); // TODO: is this bang correct?
this.increasePullStatistic();
this.addEggToGameData();
}
};
@ -207,14 +207,14 @@ export class Egg {
}
// Generates a PlayerPokemon from an egg
public generatePlayerPokemon(scene: BattleScene): PlayerPokemon {
public generatePlayerPokemon(): PlayerPokemon {
let ret: PlayerPokemon;
const generatePlayerPokemonHelper = (scene: BattleScene) => {
const generatePlayerPokemonHelper = () => {
// Legacy egg wants to hatch. Generate missing properties
if (!this._species) {
this._isShiny = this.rollShiny();
this._species = this.rollSpecies(scene!)!; // TODO: are these bangs correct?
this._species = this.rollSpecies()!; // TODO: is this bang correct?
}
let pokemonSpecies = getPokemonSpecies(this._species);
@ -233,7 +233,7 @@ export class Egg {
}
// This function has way to many optional parameters
ret = scene.addPlayerPokemon(pokemonSpecies, 1, abilityIndex, undefined, undefined, false);
ret = gScene.addPlayerPokemon(pokemonSpecies, 1, abilityIndex, undefined, undefined, false);
ret.shiny = this._isShiny;
ret.variant = this._variantTier;
@ -245,16 +245,16 @@ export class Egg {
};
ret = ret!; // Tell TS compiler it's defined now
scene.executeWithSeedOffset(() => {
generatePlayerPokemonHelper(scene);
gScene.executeWithSeedOffset(() => {
generatePlayerPokemonHelper();
}, this._id, EGG_SEED.toString());
return ret;
}
// Doesn't need to be called if the egg got pulled by a gacha machiene
public addEggToGameData(scene: BattleScene): void {
scene.gameData.eggs.push(this);
public addEggToGameData(): void {
gScene.gameData.eggs.push(this);
}
public getEggDescriptor(): string {
@ -286,12 +286,12 @@ export class Egg {
return i18next.t("egg:hatchWavesMessageLongTime");
}
public getEggTypeDescriptor(scene: BattleScene): string {
public getEggTypeDescriptor(): string {
switch (this.sourceType) {
case EggSourceType.SAME_SPECIES_EGG:
return this._eggDescriptor ?? i18next.t("egg:sameSpeciesEgg", { species: getPokemonSpecies(this._species).getName() });
case EggSourceType.GACHA_LEGENDARY:
return this._eggDescriptor ?? `${i18next.t("egg:gachaTypeLegendary")} (${getPokemonSpecies(getLegendaryGachaSpeciesForTimestamp(scene, this.timestamp)).getName()})`;
return this._eggDescriptor ?? `${i18next.t("egg:gachaTypeLegendary")} (${getPokemonSpecies(getLegendaryGachaSpeciesForTimestamp(this.timestamp)).getName()})`;
case EggSourceType.GACHA_SHINY:
return this._eggDescriptor ?? i18next.t("egg:gachaTypeShiny");
case EggSourceType.GACHA_MOVE:
@ -351,8 +351,8 @@ export class Egg {
return tierValue >= GACHA_DEFAULT_COMMON_EGG_THRESHOLD + tierValueOffset ? EggTier.COMMON : tierValue >= GACHA_DEFAULT_RARE_EGG_THRESHOLD + tierValueOffset ? EggTier.RARE : tierValue >= GACHA_DEFAULT_EPIC_EGG_THRESHOLD + tierValueOffset ? EggTier.EPIC : EggTier.LEGENDARY;
}
private rollSpecies(scene: BattleScene): Species | null {
if (!scene) {
private rollSpecies(): Species | null {
if (!gScene) {
return null;
}
/**
@ -371,7 +371,7 @@ export class Egg {
} else if (this.tier === EggTier.LEGENDARY
&& this._sourceType === EggSourceType.GACHA_LEGENDARY) {
if (!Utils.randSeedInt(2)) {
return getLegendaryGachaSpeciesForTimestamp(scene, this.timestamp);
return getLegendaryGachaSpeciesForTimestamp(this.timestamp);
}
}
@ -405,8 +405,8 @@ export class Egg {
.filter(s => !pokemonPrevolutions.hasOwnProperty(s) && getPokemonSpecies(s).isObtainable() && ignoredSpecies.indexOf(s) === -1);
// If this is the 10th egg without unlocking something new, attempt to force it.
if (scene.gameData.unlockPity[this.tier] >= 9) {
const lockedPool = speciesPool.filter(s => !scene.gameData.dexData[s].caughtAttr && !scene.gameData.eggs.some(e => e.species === s));
if (gScene.gameData.unlockPity[this.tier] >= 9) {
const lockedPool = speciesPool.filter(s => !gScene.gameData.dexData[s].caughtAttr && !gScene.gameData.eggs.some(e => e.species === s));
if (lockedPool.length) { // Skip this if everything is unlocked
speciesPool = lockedPool;
}
@ -453,10 +453,10 @@ export class Egg {
}
species = species!; // tell TS compiled it's defined now!
if (!!scene.gameData.dexData[species].caughtAttr || scene.gameData.eggs.some(e => e.species === species)) {
scene.gameData.unlockPity[this.tier] = Math.min(scene.gameData.unlockPity[this.tier] + 1, 10);
if (gScene.gameData.dexData[species].caughtAttr || gScene.gameData.eggs.some(e => e.species === species)) {
gScene.gameData.unlockPity[this.tier] = Math.min(gScene.gameData.unlockPity[this.tier] + 1, 10);
} else {
scene.gameData.unlockPity[this.tier] = 0;
gScene.gameData.unlockPity[this.tier] = 0;
}
return species;
@ -464,7 +464,7 @@ export class Egg {
/**
* Rolls whether the egg is shiny or not.
* @returns True if the egg is shiny
* @returns `true` if the egg is shiny
**/
private rollShiny(): boolean {
let shinyChance = GACHA_DEFAULT_SHINY_RATE;
@ -484,6 +484,7 @@ export class Egg {
// Uses the same logic as pokemon.generateVariant(). I would like to only have this logic in one
// place but I don't want to touch the pokemon class.
// TODO: Remove this or replace the one in the Pokemon class.
private rollVariant(): VariantTier {
if (!this.isShiny) {
return VariantTier.STANDARD;
@ -499,38 +500,38 @@ export class Egg {
}
}
private checkForPityTierOverrides(scene: BattleScene): void {
private checkForPityTierOverrides(): void {
const tierValueOffset = this._sourceType === EggSourceType.GACHA_LEGENDARY ? GACHA_LEGENDARY_UP_THRESHOLD_OFFSET : 0;
scene.gameData.eggPity[EggTier.RARE] += 1;
scene.gameData.eggPity[EggTier.EPIC] += 1;
scene.gameData.eggPity[EggTier.LEGENDARY] += 1 + tierValueOffset;
gScene.gameData.eggPity[EggTier.RARE] += 1;
gScene.gameData.eggPity[EggTier.EPIC] += 1;
gScene.gameData.eggPity[EggTier.LEGENDARY] += 1 + tierValueOffset;
// These numbers are roughly the 80% mark. That is, 80% of the time you'll get an egg before this gets triggered.
if (scene.gameData.eggPity[EggTier.LEGENDARY] >= EGG_PITY_LEGENDARY_THRESHOLD && this._tier === EggTier.COMMON) {
if (gScene.gameData.eggPity[EggTier.LEGENDARY] >= EGG_PITY_LEGENDARY_THRESHOLD && this._tier === EggTier.COMMON) {
this._tier = EggTier.LEGENDARY;
} else if (scene.gameData.eggPity[EggTier.EPIC] >= EGG_PITY_EPIC_THRESHOLD && this._tier === EggTier.COMMON) {
} else if (gScene.gameData.eggPity[EggTier.EPIC] >= EGG_PITY_EPIC_THRESHOLD && this._tier === EggTier.COMMON) {
this._tier = EggTier.EPIC;
} else if (scene.gameData.eggPity[EggTier.RARE] >= EGG_PITY_RARE_THRESHOLD && this._tier === EggTier.COMMON) {
} else if (gScene.gameData.eggPity[EggTier.RARE] >= EGG_PITY_RARE_THRESHOLD && this._tier === EggTier.COMMON) {
this._tier = EggTier.RARE;
}
scene.gameData.eggPity[this._tier] = 0;
gScene.gameData.eggPity[this._tier] = 0;
}
private increasePullStatistic(scene: BattleScene): void {
scene.gameData.gameStats.eggsPulled++;
private increasePullStatistic(): void {
gScene.gameData.gameStats.eggsPulled++;
if (this.isManaphyEgg()) {
scene.gameData.gameStats.manaphyEggsPulled++;
gScene.gameData.gameStats.manaphyEggsPulled++;
this._hatchWaves = this.getEggTierDefaultHatchWaves(EggTier.EPIC);
return;
}
switch (this.tier) {
case EggTier.RARE:
scene.gameData.gameStats.rareEggsPulled++;
gScene.gameData.gameStats.rareEggsPulled++;
break;
case EggTier.EPIC:
scene.gameData.gameStats.epicEggsPulled++;
gScene.gameData.gameStats.epicEggsPulled++;
break;
case EggTier.LEGENDARY:
scene.gameData.gameStats.legendaryEggsPulled++;
gScene.gameData.gameStats.legendaryEggsPulled++;
break;
}
}
@ -551,7 +552,7 @@ export function getValidLegendaryGachaSpecies() : Species[] {
.filter(s => getPokemonSpecies(s).isObtainable() && s !== Species.ETERNATUS);
}
export function getLegendaryGachaSpeciesForTimestamp(scene: BattleScene, timestamp: number): Species {
export function getLegendaryGachaSpeciesForTimestamp(timestamp: number): Species {
const legendarySpecies = getValidLegendaryGachaSpecies();
let ret: Species;
@ -562,7 +563,7 @@ export function getLegendaryGachaSpeciesForTimestamp(scene: BattleScene, timesta
const offset = Math.floor(Math.floor(dayTimestamp / 86400000) / legendarySpecies.length); // Cycle number
const index = Math.floor(dayTimestamp / 86400000) % legendarySpecies.length; // Index within cycle
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
ret = Phaser.Math.RND.shuffle(legendarySpecies)[index];
}, offset, EGG_SEED.toString());
ret = ret!; // tell TS compiler it's

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
import { gScene } from "#app/battle-scene";
import { EnemyPartyConfig, initBattleWithEnemyConfig, leaveEncounterWithoutBattle, setEncounterRewards, transitionMysteryEncounterIntroVisuals, } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { trainerConfigs, } from "#app/data/trainer-config";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
import { TrainerType } from "#enums/trainer-type";
@ -36,8 +36,8 @@ export const ATrainersTestEncounter: MysteryEncounter =
},
])
.withAutoHideIntroVisuals(false)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Randomly pick from 1 of the 5 stat trainers to spawn
let trainerType: TrainerType;
@ -138,23 +138,22 @@ export const ATrainersTestEncounter: MysteryEncounter =
buttonLabel: `${namespace}:option.1.label`,
buttonTooltip: `${namespace}:option.1.tooltip`
},
async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Battle the stat trainer for an Egg and great rewards
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0];
await transitionMysteryEncounterIntroVisuals(scene);
await transitionMysteryEncounterIntroVisuals();
const eggOptions: IEggOptions = {
scene,
pulled: false,
sourceType: EggSourceType.EVENT,
eggDescriptor: encounter.misc.trainerEggDescription,
tier: EggTier.EPIC
};
encounter.setDialogueToken("eggType", i18next.t(`${namespace}:eggTypes.epic`));
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.SACRED_ASH ], guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ULTRA ], fillRemaining: true }, [ eggOptions ]);
await initBattleWithEnemyConfig(scene, config);
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.SACRED_ASH ], guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ULTRA ], fillRemaining: true }, [ eggOptions ]);
await initBattleWithEnemyConfig(config);
}
)
.withSimpleOption(
@ -162,21 +161,20 @@ export const ATrainersTestEncounter: MysteryEncounter =
buttonLabel: `${namespace}:option.2.label`,
buttonTooltip: `${namespace}:option.2.tooltip`
},
async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Full heal party
scene.unshiftPhase(new PartyHealPhase(scene, true));
gScene.unshiftPhase(new PartyHealPhase(true));
const eggOptions: IEggOptions = {
scene,
pulled: false,
sourceType: EggSourceType.EVENT,
eggDescriptor: encounter.misc.trainerEggDescription,
tier: EggTier.RARE
};
encounter.setDialogueToken("eggType", i18next.t(`${namespace}:eggTypes.rare`));
setEncounterRewards(scene, { fillRemaining: false, rerollMultiplier: -1 }, [ eggOptions ]);
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ fillRemaining: false, rerollMultiplier: -1 }, [ eggOptions ]);
leaveEncounterWithoutBattle();
}
)
.withOutroDialogue([

View File

@ -3,7 +3,7 @@ import Pokemon, { EnemyPokemon, PokemonMove } from "#app/field/pokemon";
import { BerryModifierType, modifierTypes, PokemonHeldItemModifierType } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { PersistentModifierRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
@ -170,18 +170,18 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
scene.loadSe("PRSFX- Bug Bite", "battle_anims", "PRSFX- Bug Bite.wav");
scene.loadSe("Follow Me", "battle_anims", "Follow Me.mp3");
gScene.loadSe("PRSFX- Bug Bite", "battle_anims", "PRSFX- Bug Bite.wav");
gScene.loadSe("Follow Me", "battle_anims", "Follow Me.mp3");
// Get all player berry items, remove from party, and store reference
const berryItems = scene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[];
const berryItems = gScene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[];
// Sort berries by party member ID to more easily re-add later if necessary
const berryItemsMap = new Map<number, BerryModifier[]>();
scene.getParty().forEach(pokemon => {
gScene.getParty().forEach(pokemon => {
const pokemonBerries = berryItems.filter(b => b.pokemonId === pokemon.id);
if (pokemonBerries?.length > 0) {
berryItemsMap.set(pokemon.id, pokemonBerries);
@ -196,7 +196,7 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
// Can't define stack count on a ModifierType, have to just create separate instances for each stack
// Overflow berries will be "lost" on the boss, but it's un-catchable anyway
for (let i = 0; i < berryMod.stackCount; i++) {
const modifierType = generateModifierType(scene, modifierTypes.BERRY, [ berryMod.berryType ]) as PokemonHeldItemModifierType;
const modifierType = generateModifierType(modifierTypes.BERRY, [ berryMod.berryType ]) as PokemonHeldItemModifierType;
bossModifierConfigs.push({ modifier: modifierType });
}
});
@ -204,7 +204,7 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
// Do NOT remove the real berries yet or else it will be persisted in the session data
// SpDef buff below wave 50, +1 to all stats otherwise
const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = scene.currentBattle.waveIndex < 50 ?
const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = gScene.currentBattle.waveIndex < 50 ?
[ Stat.SPDEF ] :
[ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ];
@ -220,8 +220,8 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
modifierConfigs: bossModifierConfigs,
tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ],
mysteryEncounterBattleEffects: (pokemon: Pokemon) => {
queueEncounterMessage(pokemon.scene, `${namespace}:option.1.boss_enraged`);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, statChangesForBattle, 1));
queueEncounterMessage(`${namespace}:option.1.boss_enraged`);
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1));
}
}
],
@ -232,18 +232,18 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
return true;
})
.withOnVisualsStart((scene: BattleScene) => {
doGreedentSpriteSteal(scene);
doBerrySpritePile(scene);
.withOnVisualsStart(() => {
doGreedentSpriteSteal();
doBerrySpritePile();
// Remove the berries from the party
// Session has been safely saved at this point, so data won't be lost
const berryItems = scene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[];
const berryItems = gScene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[];
berryItems.forEach(berryMod => {
scene.removeModifier(berryMod);
gScene.removeModifier(berryMod);
});
scene.updateModifiers(true);
gScene.updateModifiers(true);
return true;
})
@ -259,26 +259,26 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Pick battle
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
// Provides 1x Reviver Seed to each party member at end of battle
const revSeed = generateModifierType(scene, modifierTypes.REVIVER_SEED);
const revSeed = generateModifierType(modifierTypes.REVIVER_SEED);
encounter.setDialogueToken("foodReward", revSeed?.name ?? i18next.t("modifierType:ModifierType.REVIVER_SEED.name"));
const givePartyPokemonReviverSeeds = () => {
const party = scene.getParty();
const party = gScene.getParty();
party.forEach(p => {
const heldItems = p.getHeldItems();
if (revSeed && !heldItems.some(item => item instanceof PokemonInstantReviveModifier)) {
const seedModifier = revSeed.newModifier(p);
scene.addModifier(seedModifier, false, false, false, true);
gScene.addModifier(seedModifier, false, false, false, true);
}
});
queueEncounterMessage(scene, `${namespace}:option.1.food_stash`);
queueEncounterMessage(`${namespace}:option.1.food_stash`);
};
setEncounterRewards(scene, { fillRemaining: true }, undefined, givePartyPokemonReviverSeeds);
setEncounterRewards({ fillRemaining: true }, undefined, givePartyPokemonReviverSeeds);
encounter.startOfBattleEffects.push({
sourceBattlerIndex: BattlerIndex.ENEMY,
targets: [ BattlerIndex.ENEMY ],
@ -286,8 +286,8 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
ignorePp: true
});
await transitionMysteryEncounterIntroVisuals(scene, true, true, 500);
await initBattleWithEnemyConfig(scene, encounter.enemyPartyConfigs[0]);
await transitionMysteryEncounterIntroVisuals(true, true, 500);
await initBattleWithEnemyConfig(encounter.enemyPartyConfigs[0]);
})
.build()
)
@ -303,12 +303,12 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const berryMap = encounter.misc.berryItemsMap;
// Returns 2/5 of the berries stolen to each Pokemon
const party = scene.getParty();
const party = gScene.getParty();
party.forEach(pokemon => {
const stolenBerries: BerryModifier[] = berryMap.get(pokemon.id);
const berryTypesAsArray: BerryType[] = [];
@ -321,15 +321,15 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
Phaser.Math.RND.shuffle(berryTypesAsArray);
const randBerryType = berryTypesAsArray.pop();
const berryModType = generateModifierType(scene, modifierTypes.BERRY, [ randBerryType ]) as BerryModifierType;
applyModifierTypeToPlayerPokemon(scene, pokemon, berryModType);
const berryModType = generateModifierType(modifierTypes.BERRY, [ randBerryType ]) as BerryModifierType;
applyModifierTypeToPlayerPokemon(pokemon, berryModType);
}
}
});
await scene.updateModifiers(true);
await gScene.updateModifiers(true);
await transitionMysteryEncounterIntroVisuals(scene, true, true, 500);
leaveEncounterWithoutBattle(scene, true);
await transitionMysteryEncounterIntroVisuals(true, true, 500);
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -345,36 +345,36 @@ export const AbsoluteAvariceEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Animate berries being eaten
doGreedentEatBerries(scene);
doBerrySpritePile(scene, true);
doGreedentEatBerries();
doBerrySpritePile(true);
return true;
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Let it have the food
// Greedent joins the team, level equal to 2 below highest party member
const level = getHighestLevelPlayerPokemon(scene, false, true).level - 2;
const greedent = new EnemyPokemon(scene, getPokemonSpecies(Species.GREEDENT), level, TrainerSlot.NONE, false);
const level = getHighestLevelPlayerPokemon(false, true).level - 2;
const greedent = new EnemyPokemon(getPokemonSpecies(Species.GREEDENT), level, TrainerSlot.NONE, false);
greedent.moveset = [ new PokemonMove(Moves.THRASH), new PokemonMove(Moves.BODY_PRESS), new PokemonMove(Moves.STUFF_CHEEKS), new PokemonMove(Moves.SLACK_OFF) ];
greedent.passive = true;
await transitionMysteryEncounterIntroVisuals(scene, true, true, 500);
await catchPokemon(scene, greedent, null, PokeballType.POKEBALL, false);
leaveEncounterWithoutBattle(scene, true);
await transitionMysteryEncounterIntroVisuals(true, true, 500);
await catchPokemon(greedent, null, PokeballType.POKEBALL, false);
leaveEncounterWithoutBattle(true);
})
.build()
)
.build();
function doGreedentSpriteSteal(scene: BattleScene) {
function doGreedentSpriteSteal() {
const shakeDelay = 50;
const slideDelay = 500;
const greedentSprites = scene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1);
const greedentSprites = gScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1);
scene.playSound("battle_anims/Follow Me");
scene.tweens.chain({
gScene.playSound("battle_anims/Follow Me");
gScene.tweens.chain({
targets: greedentSprites,
tweens: [
{ // Slide Greedent diagonally
@ -444,10 +444,10 @@ function doGreedentSpriteSteal(scene: BattleScene) {
});
}
function doGreedentEatBerries(scene: BattleScene) {
const greedentSprites = scene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1);
function doGreedentEatBerries() {
const greedentSprites = gScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1);
let index = 1;
scene.tweens.add({
gScene.tweens.add({
targets: greedentSprites,
duration: 150,
ease: "Cubic.easeOut",
@ -455,11 +455,11 @@ function doGreedentEatBerries(scene: BattleScene) {
y: "-=8",
loop: 5,
onStart: () => {
scene.playSound("battle_anims/PRSFX- Bug Bite");
gScene.playSound("battle_anims/PRSFX- Bug Bite");
},
onLoop: () => {
if (index % 2 === 0) {
scene.playSound("battle_anims/PRSFX- Bug Bite");
gScene.playSound("battle_anims/PRSFX- Bug Bite");
}
index++;
}
@ -471,13 +471,13 @@ function doGreedentEatBerries(scene: BattleScene) {
* @param scene
* @param isEat Default false. Will "create" pile when false, and remove pile when true.
*/
function doBerrySpritePile(scene: BattleScene, isEat: boolean = false) {
function doBerrySpritePile(isEat: boolean = false) {
const berryAddDelay = 150;
let animationOrder = [ "starf", "sitrus", "lansat", "salac", "apicot", "enigma", "liechi", "ganlon", "lum", "petaya", "leppa" ];
if (isEat) {
animationOrder = animationOrder.reverse();
}
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
animationOrder.forEach((berry, i) => {
const introVisualsIndex = encounter.spriteConfigs.findIndex(config => config.spriteKey?.includes(berry));
let sprite: Phaser.GameObjects.Sprite, tintSprite: Phaser.GameObjects.Sprite;
@ -486,7 +486,7 @@ function doBerrySpritePile(scene: BattleScene, isEat: boolean = false) {
sprite = sprites[0];
tintSprite = sprites[1];
}
scene.time.delayedCall(berryAddDelay * i + 400, () => {
gScene.time.delayedCall(berryAddDelay * i + 400, () => {
if (sprite) {
sprite.setVisible(!isEat);
}
@ -496,20 +496,20 @@ function doBerrySpritePile(scene: BattleScene, isEat: boolean = false) {
// Animate Petaya berry falling off the pile
if (berry === "petaya" && sprite && tintSprite && !isEat) {
scene.time.delayedCall(200, () => {
doBerryBounce(scene, [ sprite, tintSprite ], 30, 500);
gScene.time.delayedCall(200, () => {
doBerryBounce([ sprite, tintSprite ], 30, 500);
});
}
});
});
}
function doBerryBounce(scene: BattleScene, berrySprites: Phaser.GameObjects.Sprite[], yd: number, baseBounceDuration: number) {
function doBerryBounce(berrySprites: Phaser.GameObjects.Sprite[], yd: number, baseBounceDuration: number) {
let bouncePower = 1;
let bounceYOffset = yd;
const doBounce = () => {
scene.tweens.add({
gScene.tweens.add({
targets: berrySprites,
y: "+=" + bounceYOffset,
x: { value: "+=" + (bouncePower * bouncePower * 10), ease: "Linear" },
@ -521,7 +521,7 @@ function doBerryBounce(scene: BattleScene, berrySprites: Phaser.GameObjects.Spri
if (bouncePower) {
bounceYOffset = bounceYOffset * bouncePower;
scene.tweens.add({
gScene.tweens.add({
targets: berrySprites,
y: "-=" + bounceYOffset,
x: { value: "+=" + (bouncePower * bouncePower * 10), ease: "Linear" },

View File

@ -2,7 +2,7 @@ import { generateModifierType, leaveEncounterWithoutBattle, setEncounterExp, upd
import { modifierTypes } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { AbilityRequirement, CombinationPokemonRequirement, MoveRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
@ -69,14 +69,14 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
const pokemon = getHighestStatTotalPlayerPokemon(scene, true, true);
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const pokemon = getHighestStatTotalPlayerPokemon(true, true);
const baseSpecies = pokemon.getSpeciesForm().getRootSpeciesId();
const starterValue: number = speciesStarterCosts[baseSpecies] ?? 1;
const multiplier = Math.max(MONEY_MAXIMUM_MULTIPLIER / 10 * starterValue, MONEY_MINIMUM_MULTIPLIER);
const price = scene.getWaveMoneyAmount(multiplier);
const price = gScene.getWaveMoneyAmount(multiplier);
encounter.setDialogueToken("strongestPokemon", pokemon.getNameToRender());
encounter.setDialogueToken("price", price.toString());
@ -89,7 +89,7 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter =
// If player meets the combo OR requirements for option 2, populate the token
const opt2Req = encounter.options[1].primaryPokemonRequirements[0];
if (opt2Req.meetsRequirement(scene)) {
if (opt2Req.meetsRequirement()) {
const abilityToken = encounter.dialogueTokens["option2PrimaryAbility"];
const moveToken = encounter.dialogueTokens["option2PrimaryMove"];
if (abilityToken) {
@ -99,7 +99,7 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter =
}
}
const shinyCharm = generateModifierType(scene, modifierTypes.SHINY_CHARM);
const shinyCharm = generateModifierType(modifierTypes.SHINY_CHARM);
encounter.setDialogueToken("itemName", shinyCharm?.name ?? i18next.t("modifierType:ModifierType.SHINY_CHARM.name"));
encounter.setDialogueToken("liepardName", getPokemonSpecies(Species.LIEPARD).getName());
@ -118,17 +118,17 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Update money and remove pokemon from party
updatePlayerMoney(scene, encounter.misc.price);
scene.removePokemonFromPlayerParty(encounter.misc.pokemon);
updatePlayerMoney(encounter.misc.price);
gScene.removePokemonFromPlayerParty(encounter.misc.pokemon);
return true;
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Give the player a Shiny Charm
scene.unshiftPhase(new ModifierRewardPhase(scene, modifierTypes.SHINY_CHARM));
leaveEncounterWithoutBattle(scene, true);
gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.SHINY_CHARM));
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -152,15 +152,15 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Extort the rich kid for money
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
// Update money and remove pokemon from party
updatePlayerMoney(scene, encounter.misc.price);
updatePlayerMoney(encounter.misc.price);
setEncounterExp(scene, encounter.options[1].primaryPokemon!.id, getPokemonSpecies(Species.LIEPARD).baseExp, true);
setEncounterExp(encounter.options[1].primaryPokemon!.id, getPokemonSpecies(Species.LIEPARD).baseExp, true);
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -175,9 +175,9 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)

View File

@ -1,8 +1,11 @@
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import {
EnemyPartyConfig, generateModifierType, generateModifierTypeOption,
EnemyPartyConfig,
generateModifierType,
generateModifierTypeOption,
initBattleWithEnemyConfig,
leaveEncounterWithoutBattle, setEncounterExp,
leaveEncounterWithoutBattle,
setEncounterExp,
setEncounterRewards
} from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import Pokemon, { EnemyPokemon, PlayerPokemon } from "#app/field/pokemon";
@ -10,13 +13,14 @@ import {
BerryModifierType,
getPartyLuckValue,
ModifierPoolType,
ModifierTypeOption, modifierTypes,
ModifierTypeOption,
modifierTypes,
regenerateModifierPoolThresholds,
} from "#app/modifier/modifier-type";
import { randSeedInt } from "#app/utils";
import { BattlerTagType } from "#enums/battler-tag-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { queueEncounterMessage, showEncounterText } from "#app/data/mystery-encounters/utils/encounter-dialogue-utils";
import { getPokemonNameWithAffix } from "#app/messages";
@ -53,13 +57,13 @@ export const BerriesAboundEncounter: MysteryEncounter =
text: `${namespace}:intro`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculate boss mon
const level = getEncounterPokemonLevelForWave(scene, STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const bossSpecies = scene.arena.randomSpecies(scene.currentBattle.waveIndex, level, 0, getPartyLuckValue(scene.getParty()), true);
const bossPokemon = new EnemyPokemon(scene, bossSpecies, level, TrainerSlot.NONE, true);
const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const bossSpecies = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true);
const bossPokemon = new EnemyPokemon(bossSpecies, level, TrainerSlot.NONE, true);
encounter.setDialogueToken("enemyPokemon", getPokemonNameWithAffix(bossPokemon));
const config: EnemyPartyConfig = {
pokemonConfigs: [{
@ -74,10 +78,10 @@ export const BerriesAboundEncounter: MysteryEncounter =
// Calculate the number of extra berries that player receives
// 10-40: 2, 40-120: 4, 120-160: 5, 160-180: 7
const numBerries =
scene.currentBattle.waveIndex > 160 ? 7
: scene.currentBattle.waveIndex > 120 ? 5
: scene.currentBattle.waveIndex > 40 ? 4 : 2;
regenerateModifierPoolThresholds(scene.getParty(), ModifierPoolType.PLAYER, 0);
gScene.currentBattle.waveIndex > 160 ? 7
: gScene.currentBattle.waveIndex > 120 ? 5
: gScene.currentBattle.waveIndex > 40 ? 4 : 2;
regenerateModifierPoolThresholds(gScene.getParty(), ModifierPoolType.PLAYER, 0);
encounter.misc = { numBerries };
const { spriteKey, fileRoot } = getSpriteKeysFromPokemon(bossPokemon);
@ -103,7 +107,7 @@ export const BerriesAboundEncounter: MysteryEncounter =
];
// Get fastest party pokemon for option 2
const fastestPokemon = getHighestStatPlayerPokemon(scene, PERMANENT_STATS[Stat.SPD], true, false);
const fastestPokemon = getHighestStatPlayerPokemon(PERMANENT_STATS[Stat.SPD], true, false);
encounter.misc.fastestPokemon = fastestPokemon;
encounter.misc.enemySpeed = bossPokemon.getStat(Stat.SPD);
encounter.setDialogueToken("fastestPokemon", fastestPokemon.getNameToRender());
@ -124,34 +128,34 @@ export const BerriesAboundEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Pick battle
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const numBerries = encounter.misc.numBerries;
const doBerryRewards = () => {
const berryText = i18next.t(`${namespace}:berries`);
scene.playSound("item_fanfare");
queueEncounterMessage(scene, i18next.t("battle:rewardGainCount", { modifierName: berryText, count: numBerries }));
gScene.playSound("item_fanfare");
queueEncounterMessage(i18next.t("battle:rewardGainCount", { modifierName: berryText, count: numBerries }));
// Generate a random berry and give it to the first Pokemon with room for it
for (let i = 0; i < numBerries; i++) {
tryGiveBerry(scene);
tryGiveBerry();
}
};
const shopOptions: ModifierTypeOption[] = [];
for (let i = 0; i < 5; i++) {
// Generate shop berries
const mod = generateModifierTypeOption(scene, modifierTypes.BERRY);
const mod = generateModifierTypeOption(modifierTypes.BERRY);
if (mod) {
shopOptions.push(mod);
}
}
setEncounterRewards(scene, { guaranteedModifierTypeOptions: shopOptions, fillRemaining: false }, undefined, doBerryRewards);
await initBattleWithEnemyConfig(scene, scene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]);
setEncounterRewards({ guaranteedModifierTypeOptions: shopOptions, fillRemaining: false }, undefined, doBerryRewards);
await initBattleWithEnemyConfig(gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]);
}
)
.withOption(
@ -161,9 +165,9 @@ export const BerriesAboundEncounter: MysteryEncounter =
buttonLabel: `${namespace}:option.2.label`,
buttonTooltip: `${namespace}:option.2.tooltip`
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Pick race for berries
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const fastestPokemon: PlayerPokemon = encounter.misc.fastestPokemon;
const enemySpeed: number = encounter.misc.enemySpeed;
const speedDiff = fastestPokemon.getStat(Stat.SPD) / (enemySpeed * 1.1);
@ -172,7 +176,7 @@ export const BerriesAboundEncounter: MysteryEncounter =
const shopOptions: ModifierTypeOption[] = [];
for (let i = 0; i < 5; i++) {
// Generate shop berries
const mod = generateModifierTypeOption(scene, modifierTypes.BERRY);
const mod = generateModifierTypeOption(modifierTypes.BERRY);
if (mod) {
shopOptions.push(mod);
}
@ -183,29 +187,29 @@ export const BerriesAboundEncounter: MysteryEncounter =
const doBerryRewards = () => {
const berryText = i18next.t(`${namespace}:berries`);
scene.playSound("item_fanfare");
queueEncounterMessage(scene, i18next.t("battle:rewardGainCount", { modifierName: berryText, count: numBerries }));
gScene.playSound("item_fanfare");
queueEncounterMessage(i18next.t("battle:rewardGainCount", { modifierName: berryText, count: numBerries }));
// Generate a random berry and give it to the first Pokemon with room for it
for (let i = 0; i < numBerries; i++) {
tryGiveBerry(scene);
tryGiveBerry();
}
};
// Defense/Spd buffs below wave 50, +1 to all stats otherwise
const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = scene.currentBattle.waveIndex < 50 ?
const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = gScene.currentBattle.waveIndex < 50 ?
[ Stat.DEF, Stat.SPDEF, Stat.SPD ] :
[ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ];
const config = scene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0];
const config = gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0];
config.pokemonConfigs![0].tags = [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ];
config.pokemonConfigs![0].mysteryEncounterBattleEffects = (pokemon: Pokemon) => {
queueEncounterMessage(pokemon.scene, `${namespace}:option.2.boss_enraged`);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, statChangesForBattle, 1));
queueEncounterMessage(`${namespace}:option.2.boss_enraged`);
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1));
};
setEncounterRewards(scene, { guaranteedModifierTypeOptions: shopOptions, fillRemaining: false }, undefined, doBerryRewards);
await showEncounterText(scene, `${namespace}:option.2.selected_bad`);
await initBattleWithEnemyConfig(scene, config);
setEncounterRewards({ guaranteedModifierTypeOptions: shopOptions, fillRemaining: false }, undefined, doBerryRewards);
await showEncounterText(`${namespace}:option.2.selected_bad`);
await initBattleWithEnemyConfig(config);
return;
} else {
// Gains 1 berry for every 10% faster the player's pokemon is than the enemy, up to a max of numBerries, minimum of 2
@ -214,19 +218,19 @@ export const BerriesAboundEncounter: MysteryEncounter =
const doFasterBerryRewards = () => {
const berryText = i18next.t(`${namespace}:berries`);
scene.playSound("item_fanfare");
queueEncounterMessage(scene, i18next.t("battle:rewardGainCount", { modifierName: berryText, count: numBerriesGrabbed }));
gScene.playSound("item_fanfare");
queueEncounterMessage(i18next.t("battle:rewardGainCount", { modifierName: berryText, count: numBerriesGrabbed }));
// Generate a random berry and give it to the first Pokemon with room for it (trying to give to fastest first)
for (let i = 0; i < numBerriesGrabbed; i++) {
tryGiveBerry(scene, fastestPokemon);
tryGiveBerry(fastestPokemon);
}
};
setEncounterExp(scene, fastestPokemon.id, encounter.enemyPartyConfigs[0].pokemonConfigs![0].species.baseExp);
setEncounterRewards(scene, { guaranteedModifierTypeOptions: shopOptions, fillRemaining: false }, undefined, doFasterBerryRewards);
await showEncounterText(scene, `${namespace}:option.2.selected`);
leaveEncounterWithoutBattle(scene);
setEncounterExp(fastestPokemon.id, encounter.enemyPartyConfigs[0].pokemonConfigs![0].species.baseExp);
setEncounterRewards({ guaranteedModifierTypeOptions: shopOptions, fillRemaining: false }, undefined, doFasterBerryRewards);
await showEncounterText(`${namespace}:option.2.selected`);
leaveEncounterWithoutBattle();
}
})
.build()
@ -241,38 +245,38 @@ export const BerriesAboundEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)
.build();
function tryGiveBerry(scene: BattleScene, prioritizedPokemon?: PlayerPokemon) {
function tryGiveBerry(prioritizedPokemon?: PlayerPokemon) {
const berryType = randSeedInt(Object.keys(BerryType).filter(s => !isNaN(Number(s))).length) as BerryType;
const berry = generateModifierType(scene, modifierTypes.BERRY, [ berryType ]) as BerryModifierType;
const berry = generateModifierType(modifierTypes.BERRY, [ berryType ]) as BerryModifierType;
const party = scene.getParty();
const party = gScene.getParty();
// Will try to apply to prioritized pokemon first, then do normal application method if it fails
if (prioritizedPokemon) {
const heldBerriesOfType = scene.findModifier(m => m instanceof BerryModifier
const heldBerriesOfType = gScene.findModifier(m => m instanceof BerryModifier
&& m.pokemonId === prioritizedPokemon.id && (m as BerryModifier).berryType === berryType, true) as BerryModifier;
if (!heldBerriesOfType || heldBerriesOfType.getStackCount() < heldBerriesOfType.getMaxStackCount(scene)) {
applyModifierTypeToPlayerPokemon(scene, prioritizedPokemon, berry);
if (!heldBerriesOfType || heldBerriesOfType.getStackCount() < heldBerriesOfType.getMaxStackCount()) {
applyModifierTypeToPlayerPokemon(prioritizedPokemon, berry);
return;
}
}
// Iterate over the party until berry was successfully given
for (const pokemon of party) {
const heldBerriesOfType = scene.findModifier(m => m instanceof BerryModifier
const heldBerriesOfType = gScene.findModifier(m => m instanceof BerryModifier
&& m.pokemonId === pokemon.id && (m as BerryModifier).berryType === berryType, true) as BerryModifier;
if (!heldBerriesOfType || heldBerriesOfType.getStackCount() < heldBerriesOfType.getMaxStackCount(scene)) {
applyModifierTypeToPlayerPokemon(scene, pokemon, berry);
if (!heldBerriesOfType || heldBerriesOfType.getStackCount() < heldBerriesOfType.getMaxStackCount()) {
applyModifierTypeToPlayerPokemon(pokemon, berry);
return;
}
}

View File

@ -1,5 +1,6 @@
import {
EnemyPartyConfig, generateModifierType,
EnemyPartyConfig,
generateModifierType,
generateModifierTypeOption,
initBattleWithEnemyConfig,
leaveEncounterWithoutBattle,
@ -17,7 +18,7 @@ import {
} from "#app/data/trainer-config";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { PartyMemberStrength } from "#enums/party-member-strength";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { isNullOrUndefined, randSeedInt, randSeedShuffle } from "#app/utils";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -214,12 +215,12 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
text: `${namespace}:intro_dialogue`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculates what trainers are available for battle in the encounter
// Bug type superfan trainer config
const config = getTrainerConfigForWave(scene.currentBattle.waveIndex);
const config = getTrainerConfigForWave(gScene.currentBattle.waveIndex);
const spriteKey = config.getSpriteKey();
encounter.enemyPartyConfigs.push({
trainerConfig: config,
@ -227,7 +228,7 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
});
let beedrillKeys: { spriteKey: string, fileRoot: string }, butterfreeKeys: { spriteKey: string, fileRoot: string };
if (scene.currentBattle.waveIndex < WAVE_LEVEL_BREAKPOINTS[3]) {
if (gScene.currentBattle.waveIndex < WAVE_LEVEL_BREAKPOINTS[3]) {
beedrillKeys = getSpriteKeysFromSpecies(Species.BEEDRILL, false);
butterfreeKeys = getSpriteKeysFromSpecies(Species.BUTTERFREE, false);
} else {
@ -270,9 +271,9 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
];
const requiredItems = [
generateModifierType(scene, modifierTypes.QUICK_CLAW),
generateModifierType(scene, modifierTypes.GRIP_CLAW),
generateModifierType(scene, modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.BUG ]),
generateModifierType(modifierTypes.QUICK_CLAW),
generateModifierType(modifierTypes.GRIP_CLAW),
generateModifierType(modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.BUG ]),
];
const requiredItemString = requiredItems.map(m => m?.name ?? "unknown").join("/");
@ -295,9 +296,9 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Select battle the bug trainer
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0];
// Init the moves available for tutor
@ -313,9 +314,9 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
// Assigns callback that teaches move before continuing to rewards
encounter.onRewards = doBugTypeMoveTutor;
setEncounterRewards(scene, { fillRemaining: true });
await transitionMysteryEncounterIntroVisuals(scene, true, true);
await initBattleWithEnemyConfig(scene, config);
setEncounterRewards({ fillRemaining: true });
await transitionMysteryEncounterIntroVisuals(true, true);
await initBattleWithEnemyConfig(config);
}
)
.withOption(MysteryEncounterOptionBuilder
@ -326,17 +327,17 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
buttonTooltip: `${namespace}:option.2.tooltip`,
disabledButtonTooltip: `${namespace}:option.2.disabled_tooltip`
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Player shows off their bug types
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
// Player gets different rewards depending on the number of bug types they have
const numBugTypes = scene.getParty().filter(p => p.isOfType(Type.BUG, true)).length;
const numBugTypes = gScene.getParty().filter(p => p.isOfType(Type.BUG, true)).length;
const numBugTypesText = i18next.t(`${namespace}:numBugTypes`, { count: numBugTypes });
encounter.setDialogueToken("numBugTypes", numBugTypesText);
if (numBugTypes < 2) {
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.SUPER_LURE, modifierTypes.GREAT_BALL ], fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.SUPER_LURE, modifierTypes.GREAT_BALL ], fillRemaining: false });
encounter.selectedOption!.dialogue!.selected = [
{
speaker: `${namespace}:speaker`,
@ -344,7 +345,7 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
},
];
} else if (numBugTypes < 4) {
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.QUICK_CLAW, modifierTypes.MAX_LURE, modifierTypes.ULTRA_BALL ], fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.QUICK_CLAW, modifierTypes.MAX_LURE, modifierTypes.ULTRA_BALL ], fillRemaining: false });
encounter.selectedOption!.dialogue!.selected = [
{
speaker: `${namespace}:speaker`,
@ -352,7 +353,7 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
},
];
} else if (numBugTypes < 6) {
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.GRIP_CLAW, modifierTypes.MAX_LURE, modifierTypes.ROGUE_BALL ], fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.GRIP_CLAW, modifierTypes.MAX_LURE, modifierTypes.ROGUE_BALL ], fillRemaining: false });
encounter.selectedOption!.dialogue!.selected = [
{
speaker: `${namespace}:speaker`,
@ -362,28 +363,28 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
} else {
// If the player has any evolution/form change items that are valid for their party,
// spawn one of those items in addition to Dynamax Band, Mega Band, and Master Ball
const modifierOptions: ModifierTypeOption[] = [ generateModifierTypeOption(scene, modifierTypes.MASTER_BALL)! ];
const modifierOptions: ModifierTypeOption[] = [ generateModifierTypeOption(modifierTypes.MASTER_BALL)! ];
const specialOptions: ModifierTypeOption[] = [];
if (!scene.findModifier(m => m instanceof MegaEvolutionAccessModifier)) {
modifierOptions.push(generateModifierTypeOption(scene, modifierTypes.MEGA_BRACELET)!);
if (!gScene.findModifier(m => m instanceof MegaEvolutionAccessModifier)) {
modifierOptions.push(generateModifierTypeOption(modifierTypes.MEGA_BRACELET)!);
}
if (!scene.findModifier(m => m instanceof GigantamaxAccessModifier)) {
modifierOptions.push(generateModifierTypeOption(scene, modifierTypes.DYNAMAX_BAND)!);
if (!gScene.findModifier(m => m instanceof GigantamaxAccessModifier)) {
modifierOptions.push(generateModifierTypeOption(modifierTypes.DYNAMAX_BAND)!);
}
const nonRareEvolutionModifier = generateModifierTypeOption(scene, modifierTypes.EVOLUTION_ITEM);
const nonRareEvolutionModifier = generateModifierTypeOption(modifierTypes.EVOLUTION_ITEM);
if (nonRareEvolutionModifier) {
specialOptions.push(nonRareEvolutionModifier);
}
const rareEvolutionModifier = generateModifierTypeOption(scene, modifierTypes.RARE_EVOLUTION_ITEM);
const rareEvolutionModifier = generateModifierTypeOption(modifierTypes.RARE_EVOLUTION_ITEM);
if (rareEvolutionModifier) {
specialOptions.push(rareEvolutionModifier);
}
const formChangeModifier = generateModifierTypeOption(scene, modifierTypes.FORM_CHANGE_ITEM);
const formChangeModifier = generateModifierTypeOption(modifierTypes.FORM_CHANGE_ITEM);
if (formChangeModifier) {
specialOptions.push(formChangeModifier);
}
const rareFormChangeModifier = generateModifierTypeOption(scene, modifierTypes.RARE_FORM_CHANGE_ITEM);
const rareFormChangeModifier = generateModifierTypeOption(modifierTypes.RARE_FORM_CHANGE_ITEM);
if (rareFormChangeModifier) {
specialOptions.push(rareFormChangeModifier);
}
@ -391,7 +392,7 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
modifierOptions.push(specialOptions[randSeedInt(specialOptions.length)]);
}
setEncounterRewards(scene, { guaranteedModifierTypeOptions: modifierOptions, fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeOptions: modifierOptions, fillRemaining: false });
encounter.selectedOption!.dialogue!.selected = [
{
speaker: `${namespace}:speaker`,
@ -400,9 +401,9 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
];
}
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Player shows off their bug types
leaveEncounterWithoutBattle(scene);
leaveEncounterWithoutBattle();
})
.build())
.withOption(MysteryEncounterOptionBuilder
@ -429,8 +430,8 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
],
secondOptionPrompt: `${namespace}:option.3.select_prompt`,
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Get Pokemon held items and filter for valid ones
@ -466,30 +467,30 @@ export const BugTypeSuperfanEncounter: MysteryEncounter =
(item instanceof AttackTypeBoosterModifier && (item.type as AttackTypeBoosterModifierType).moveType === Type.BUG);
});
if (!hasValidItem) {
return getEncounterText(scene, `${namespace}:option.3.invalid_selection`) ?? null;
return getEncounterText(`${namespace}:option.3.invalid_selection`) ?? null;
}
return null;
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const modifier = encounter.misc.chosenModifier;
// Remove the modifier if its stacks go to 0
modifier.stackCount -= 1;
if (modifier.stackCount === 0) {
scene.removeModifier(modifier);
gScene.removeModifier(modifier);
}
scene.updateModifiers(true, true);
gScene.updateModifiers(true, true);
const bugNet = generateModifierTypeOption(scene, modifierTypes.MYSTERY_ENCOUNTER_GOLDEN_BUG_NET)!;
const bugNet = generateModifierTypeOption(modifierTypes.MYSTERY_ENCOUNTER_GOLDEN_BUG_NET)!;
bugNet.type.tier = ModifierTier.ROGUE;
setEncounterRewards(scene, { guaranteedModifierTypeOptions: [ bugNet ], guaranteedModifierTypeFuncs: [ modifierTypes.REVIVER_SEED ], fillRemaining: false });
leaveEncounterWithoutBattle(scene, true);
setEncounterRewards({ guaranteedModifierTypeOptions: [ bugNet ], guaranteedModifierTypeFuncs: [ modifierTypes.REVIVER_SEED ], fillRemaining: false });
leaveEncounterWithoutBattle(true);
})
.build())
.withOutroDialogue([
@ -645,22 +646,22 @@ function getTrainerConfigForWave(waveIndex: number) {
return config;
}
function doBugTypeMoveTutor(scene: BattleScene): Promise<void> {
function doBugTypeMoveTutor(): Promise<void> {
return new Promise<void>(async resolve => {
const moveOptions = scene.currentBattle.mysteryEncounter!.misc.moveTutorOptions;
await showEncounterDialogue(scene, `${namespace}:battle_won`, `${namespace}:speaker`);
const moveOptions = gScene.currentBattle.mysteryEncounter!.misc.moveTutorOptions;
await showEncounterDialogue(`${namespace}:battle_won`, `${namespace}:speaker`);
const overlayScale = 1;
const moveInfoOverlay = new MoveInfoOverlay(scene, {
const moveInfoOverlay = new MoveInfoOverlay({
delayVisibility: false,
scale: overlayScale,
onSide: true,
right: true,
x: 1,
y: -MoveInfoOverlay.getHeight(overlayScale, true) - 1,
width: (scene.game.canvas.width / 6) - 2,
width: (gScene.game.canvas.width / 6) - 2,
});
scene.ui.add(moveInfoOverlay);
gScene.ui.add(moveInfoOverlay);
const optionSelectItems = moveOptions.map((move: PokemonMove) => {
const option: OptionSelectItem = {
@ -683,7 +684,7 @@ function doBugTypeMoveTutor(scene: BattleScene): Promise<void> {
moveInfoOverlay.setVisible(false);
};
const result = await selectOptionThenPokemon(scene, optionSelectItems, `${namespace}:teach_move_prompt`, undefined, onHoverOverCancel);
const result = await selectOptionThenPokemon(optionSelectItems, `${namespace}:teach_move_prompt`, undefined, onHoverOverCancel);
// let forceExit = !!result;
if (!result) {
moveInfoOverlay.active = false;
@ -694,7 +695,7 @@ function doBugTypeMoveTutor(scene: BattleScene): Promise<void> {
// Option select complete, handle if they are learning a move
if (result && result.selectedOptionIndex < moveOptions.length) {
scene.unshiftPhase(new LearnMovePhase(scene, result.selectedPokemonIndex, moveOptions[result.selectedOptionIndex].moveId));
gScene.unshiftPhase(new LearnMovePhase(result.selectedPokemonIndex, moveOptions[result.selectedOptionIndex].moveId));
}
// Complete battle and go to rewards

View File

@ -4,7 +4,7 @@ import { ModifierTier } from "#app/modifier/modifier-tier";
import { modifierTypes, PokemonHeldItemModifierType } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { PartyMemberStrength } from "#enums/party-member-strength";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
import { Species } from "#enums/species";
@ -105,8 +105,8 @@ export const ClowningAroundEncounter: MysteryEncounter =
speaker: `${namespace}:speaker`
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const clownTrainerType = TrainerType.HARLEQUIN;
const clownConfig = trainerConfigs[clownTrainerType].clone();
@ -142,7 +142,7 @@ export const ClowningAroundEncounter: MysteryEncounter =
});
// Load animations/sfx for start of fight moves
loadCustomMovesForEncounter(scene, [ Moves.ROLE_PLAY, Moves.TAUNT ]);
loadCustomMovesForEncounter([ Moves.ROLE_PLAY, Moves.TAUNT ]);
encounter.setDialogueToken("blacephalonName", getPokemonSpecies(Species.BLACEPHALON).getName());
@ -165,12 +165,12 @@ export const ClowningAroundEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Spawn battle
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0];
setEncounterRewards(scene, { fillRemaining: true });
setEncounterRewards({ fillRemaining: true });
// TODO: when Magic Room and Wonder Room are implemented, add those to start of battle
encounter.startOfBattleEffects.push(
@ -193,28 +193,28 @@ export const ClowningAroundEncounter: MysteryEncounter =
ignorePp: true
});
await transitionMysteryEncounterIntroVisuals(scene);
await initBattleWithEnemyConfig(scene, config);
await transitionMysteryEncounterIntroVisuals();
await initBattleWithEnemyConfig(config);
})
.withPostOptionPhase(async (scene: BattleScene): Promise<boolean> => {
.withPostOptionPhase(async (): Promise<boolean> => {
// After the battle, offer the player the opportunity to permanently swap ability
const abilityWasSwapped = await handleSwapAbility(scene);
const abilityWasSwapped = await handleSwapAbility();
if (abilityWasSwapped) {
await showEncounterText(scene, `${namespace}:option.1.ability_gained`);
await showEncounterText(`${namespace}:option.1.ability_gained`);
}
// Play animations once ability swap is complete
// Trainer sprite that is shown at end of battle is not the same as mystery encounter intro visuals
scene.tweens.add({
targets: scene.currentBattle.trainer,
gScene.tweens.add({
targets: gScene.currentBattle.trainer,
x: "+=16",
y: "-=16",
alpha: 0,
ease: "Sine.easeInOut",
duration: 250
});
const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, scene.getPlayerPokemon()!, scene.getPlayerPokemon());
background.playWithoutTargets(scene, 230, 40, 2);
const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon());
background.playWithoutTargets(230, 40, 2);
return true;
})
.build()
@ -239,13 +239,13 @@ export const ClowningAroundEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Swap player's items on pokemon with the most items
// Item comparisons look at whichever Pokemon has the greatest number of TRANSFERABLE, non-berry items
// So Vitamins, form change items, etc. are not included
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const party = scene.getParty();
const party = gScene.getParty();
let mostHeldItemsPokemon = party[0];
let count = mostHeldItemsPokemon.getHeldItems()
.filter(m => m.isTransferable && !(m instanceof BerryModifier))
@ -270,10 +270,10 @@ export const ClowningAroundEncounter: MysteryEncounter =
items.filter(m => m instanceof BerryModifier)
.forEach(m => {
numBerries += m.stackCount;
scene.removeModifier(m);
gScene.removeModifier(m);
});
generateItemsOfTier(scene, mostHeldItemsPokemon, numBerries, "Berries");
generateItemsOfTier(mostHeldItemsPokemon, numBerries, "Berries");
// Shuffle Transferable held items in the same tier (only shuffles Ultra and Rogue atm)
let numUltra = 0;
@ -284,24 +284,24 @@ export const ClowningAroundEncounter: MysteryEncounter =
const tier = type.tier ?? ModifierTier.ULTRA;
if (type.id === "GOLDEN_EGG" || tier === ModifierTier.ROGUE) {
numRogue += m.stackCount;
scene.removeModifier(m);
gScene.removeModifier(m);
} else if (type.id === "LUCKY_EGG" || tier === ModifierTier.ULTRA) {
numUltra += m.stackCount;
scene.removeModifier(m);
gScene.removeModifier(m);
}
});
generateItemsOfTier(scene, mostHeldItemsPokemon, numUltra, ModifierTier.ULTRA);
generateItemsOfTier(scene, mostHeldItemsPokemon, numRogue, ModifierTier.ROGUE);
generateItemsOfTier(mostHeldItemsPokemon, numUltra, ModifierTier.ULTRA);
generateItemsOfTier(mostHeldItemsPokemon, numRogue, ModifierTier.ROGUE);
})
.withOptionPhase(async (scene: BattleScene) => {
leaveEncounterWithoutBattle(scene, true);
.withOptionPhase(async () => {
leaveEncounterWithoutBattle(true);
})
.withPostOptionPhase(async (scene: BattleScene) => {
.withPostOptionPhase(async () => {
// Play animations
const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, scene.getPlayerPokemon()!, scene.getPlayerPokemon());
background.playWithoutTargets(scene, 230, 40, 2);
await transitionMysteryEncounterIntroVisuals(scene, true, true, 200);
const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon());
background.playWithoutTargets(230, 40, 2);
await transitionMysteryEncounterIntroVisuals(true, true, 200);
})
.build()
)
@ -325,10 +325,10 @@ export const ClowningAroundEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Randomize the second type of all player's pokemon
// If the pokemon does not normally have a second type, it will gain 1
for (const pokemon of scene.getParty()) {
for (const pokemon of gScene.getParty()) {
const originalTypes = pokemon.getTypes(false, false, true);
// If the Pokemon has non-status moves that don't match the Pokemon's type, prioritizes those as the new type
@ -365,14 +365,14 @@ export const ClowningAroundEncounter: MysteryEncounter =
}
}
})
.withOptionPhase(async (scene: BattleScene) => {
leaveEncounterWithoutBattle(scene, true);
.withOptionPhase(async () => {
leaveEncounterWithoutBattle(true);
})
.withPostOptionPhase(async (scene: BattleScene) => {
.withPostOptionPhase(async () => {
// Play animations
const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, scene.getPlayerPokemon()!, scene.getPlayerPokemon());
background.playWithoutTargets(scene, 230, 40, 2);
await transitionMysteryEncounterIntroVisuals(scene, true, true, 200);
const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon());
background.playWithoutTargets(230, 40, 2);
await transitionMysteryEncounterIntroVisuals(true, true, 200);
})
.build()
)
@ -383,24 +383,24 @@ export const ClowningAroundEncounter: MysteryEncounter =
])
.build();
async function handleSwapAbility(scene: BattleScene) {
async function handleSwapAbility() {
return new Promise<boolean>(async resolve => {
await showEncounterDialogue(scene, `${namespace}:option.1.apply_ability_dialogue`, `${namespace}:speaker`);
await showEncounterText(scene, `${namespace}:option.1.apply_ability_message`);
await showEncounterDialogue(`${namespace}:option.1.apply_ability_dialogue`, `${namespace}:speaker`);
await showEncounterText(`${namespace}:option.1.apply_ability_message`);
scene.ui.setMode(Mode.MESSAGE).then(() => {
displayYesNoOptions(scene, resolve);
gScene.ui.setMode(Mode.MESSAGE).then(() => {
displayYesNoOptions(resolve);
});
});
}
function displayYesNoOptions(scene: BattleScene, resolve) {
showEncounterText(scene, `${namespace}:option.1.ability_prompt`, null, 500, false);
function displayYesNoOptions(resolve) {
showEncounterText(`${namespace}:option.1.ability_prompt`, null, 500, false);
const fullOptions = [
{
label: i18next.t("menu:yes"),
handler: () => {
onYesAbilitySwap(scene, resolve);
onYesAbilitySwap(resolve);
return true;
}
},
@ -418,29 +418,29 @@ function displayYesNoOptions(scene: BattleScene, resolve) {
maxOptions: 7,
yOffset: 0
};
scene.ui.setModeWithoutClear(Mode.OPTION_SELECT, config, null, true);
gScene.ui.setModeWithoutClear(Mode.OPTION_SELECT, config, null, true);
}
function onYesAbilitySwap(scene: BattleScene, resolve) {
function onYesAbilitySwap(resolve) {
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Do ability swap
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
applyAbilityOverrideToPokemon(pokemon, encounter.misc.ability);
encounter.setDialogueToken("chosenPokemon", pokemon.getNameToRender());
scene.ui.setMode(Mode.MESSAGE).then(() => resolve(true));
gScene.ui.setMode(Mode.MESSAGE).then(() => resolve(true));
};
const onPokemonNotSelected = () => {
scene.ui.setMode(Mode.MESSAGE).then(() => {
displayYesNoOptions(scene, resolve);
gScene.ui.setMode(Mode.MESSAGE).then(() => {
displayYesNoOptions(resolve);
});
};
selectPokemonForOption(scene, onPokemonSelected, onPokemonNotSelected);
selectPokemonForOption(onPokemonSelected, onPokemonNotSelected);
}
function generateItemsOfTier(scene: BattleScene, pokemon: PlayerPokemon, numItems: number, tier: ModifierTier | "Berries") {
function generateItemsOfTier(pokemon: PlayerPokemon, numItems: number, tier: ModifierTier | "Berries") {
// These pools have to be defined at runtime so that modifierTypes exist
// Pools have instances of the modifier type equal to the max stacks that modifier can be applied to any one pokemon
// This is to prevent "over-generating" a random item of a certain type during item swaps
@ -494,11 +494,11 @@ function generateItemsOfTier(scene: BattleScene, pokemon: PlayerPokemon, numItem
const newItemType = pool[randIndex];
let newMod: PokemonHeldItemModifierType;
if (tier === "Berries") {
newMod = generateModifierType(scene, modifierTypes.BERRY, [ newItemType[0] ]) as PokemonHeldItemModifierType;
newMod = generateModifierType(modifierTypes.BERRY, [ newItemType[0] ]) as PokemonHeldItemModifierType;
} else {
newMod = generateModifierType(scene, newItemType[0]) as PokemonHeldItemModifierType;
newMod = generateModifierType(newItemType[0]) as PokemonHeldItemModifierType;
}
applyModifierTypeToPlayerPokemon(scene, pokemon, newMod);
applyModifierTypeToPlayerPokemon(pokemon, newMod);
// Decrement max stacks and remove from pool if at max
newItemType[1]--;
if (newItemType[1] <= 0) {

View File

@ -2,7 +2,7 @@ import { EnemyPartyConfig, initBattleWithEnemyConfig, leaveEncounterWithoutBattl
import Pokemon, { EnemyPokemon, PlayerPokemon, PokemonMove } from "#app/field/pokemon";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -91,9 +91,9 @@ export const DancingLessonsEncounter: MysteryEncounter =
.withAutoHideIntroVisuals(false)
.withCatchAllowed(true)
.withFleeAllowed(false)
.withOnVisualsStart((scene: BattleScene) => {
const danceAnim = new EncounterBattleAnim(EncounterAnim.DANCE, scene.getEnemyPokemon()!, scene.getParty()[0]);
danceAnim.play(scene);
.withOnVisualsStart(() => {
const danceAnim = new EncounterBattleAnim(EncounterAnim.DANCE, gScene.getEnemyPokemon()!, gScene.getParty()[0]);
danceAnim.play();
return true;
})
@ -106,12 +106,12 @@ export const DancingLessonsEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const species = getPokemonSpecies(Species.ORICORIO);
const level = getEncounterPokemonLevelForWave(scene, STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const enemyPokemon = new EnemyPokemon(scene, species, level, TrainerSlot.NONE, false);
const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const enemyPokemon = new EnemyPokemon(species, level, TrainerSlot.NONE, false);
if (!enemyPokemon.moveset.some(m => m && m.getMove().id === Moves.REVELATION_DANCE)) {
if (enemyPokemon.moveset.length < 4) {
enemyPokemon.moveset.push(new PokemonMove(Moves.REVELATION_DANCE));
@ -122,7 +122,7 @@ export const DancingLessonsEncounter: MysteryEncounter =
// Set the form index based on the biome
// Defaults to Baile style if somehow nothing matches
const currentBiome = scene.arena.biomeType;
const currentBiome = gScene.arena.biomeType;
if (BAILE_STYLE_BIOMES.includes(currentBiome)) {
enemyPokemon.formIndex = 0;
} else if (POM_POM_STYLE_BIOMES.includes(currentBiome)) {
@ -136,14 +136,14 @@ export const DancingLessonsEncounter: MysteryEncounter =
}
const oricorioData = new PokemonData(enemyPokemon);
const oricorio = scene.addEnemyPokemon(species, level, TrainerSlot.NONE, false, oricorioData);
const oricorio = gScene.addEnemyPokemon(species, level, TrainerSlot.NONE, false, oricorioData);
// Adds a real Pokemon sprite to the field (required for the animation)
scene.getEnemyParty().forEach(enemyPokemon => {
scene.field.remove(enemyPokemon, true);
gScene.getEnemyParty().forEach(enemyPokemon => {
gScene.field.remove(enemyPokemon, true);
});
scene.currentBattle.enemyParty = [ oricorio ];
scene.field.add(oricorio);
gScene.currentBattle.enemyParty = [ oricorio ];
gScene.field.add(oricorio);
// Spawns on offscreen field
oricorio.x -= 300;
encounter.loadAssets.push(oricorio.loadAssets());
@ -156,8 +156,8 @@ export const DancingLessonsEncounter: MysteryEncounter =
// Gets +1 to all stats except SPD on battle start
tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ],
mysteryEncounterBattleEffects: (pokemon: Pokemon) => {
queueEncounterMessage(pokemon.scene, `${namespace}:option.1.boss_enraged`);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF ], 1));
queueEncounterMessage(`${namespace}:option.1.boss_enraged`);
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF ], 1));
}
}],
};
@ -182,9 +182,9 @@ export const DancingLessonsEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Pick battle
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
encounter.startOfBattleEffects.push({
sourceBattlerIndex: BattlerIndex.ENEMY,
@ -193,9 +193,9 @@ export const DancingLessonsEncounter: MysteryEncounter =
ignorePp: true
});
await hideOricorioPokemon(scene);
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.BATON ], fillRemaining: true });
await initBattleWithEnemyConfig(scene, encounter.enemyPartyConfigs[0]);
await hideOricorioPokemon();
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.BATON ], fillRemaining: true });
await initBattleWithEnemyConfig(encounter.enemyPartyConfigs[0]);
})
.build()
)
@ -211,25 +211,25 @@ export const DancingLessonsEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Learn its Dance
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
encounter.setDialogueToken("selectedPokemon", pokemon.getNameToRender());
scene.unshiftPhase(new LearnMovePhase(scene, scene.getParty().indexOf(pokemon), Moves.REVELATION_DANCE));
gScene.unshiftPhase(new LearnMovePhase(gScene.getParty().indexOf(pokemon), Moves.REVELATION_DANCE));
// Play animation again to "learn" the dance
const danceAnim = new EncounterBattleAnim(EncounterAnim.DANCE, scene.getEnemyPokemon()!, scene.getPlayerPokemon());
danceAnim.play(scene);
const danceAnim = new EncounterBattleAnim(EncounterAnim.DANCE, gScene.getEnemyPokemon()!, gScene.getPlayerPokemon());
danceAnim.play();
};
return selectPokemonForOption(scene, onPokemonSelected);
return selectPokemonForOption(onPokemonSelected);
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Learn its Dance
await hideOricorioPokemon(scene);
leaveEncounterWithoutBattle(scene, true);
await hideOricorioPokemon();
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -248,9 +248,9 @@ export const DancingLessonsEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Open menu for selecting pokemon with a Dancing move
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Return the options for nature selection
return pokemon.moveset
@ -277,20 +277,20 @@ export const DancingLessonsEncounter: MysteryEncounter =
if (!pokemon.isAllowedInBattle()) {
return i18next.t("partyUiHandler:cantBeUsed", { pokemonName: pokemon.getNameToRender() }) ?? null;
}
const meetsReqs = encounter.options[2].pokemonMeetsPrimaryRequirements(scene, pokemon);
const meetsReqs = encounter.options[2].pokemonMeetsPrimaryRequirements(pokemon);
if (!meetsReqs) {
return getEncounterText(scene, `${namespace}:invalid_selection`) ?? null;
return getEncounterText(`${namespace}:invalid_selection`) ?? null;
}
return null;
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Show the Oricorio a dance, and recruit it
const encounter = scene.currentBattle.mysteryEncounter!;
const oricorio = encounter.misc.oricorioData.toPokemon(scene);
const encounter = gScene.currentBattle.mysteryEncounter!;
const oricorio = encounter.misc.oricorioData.toPokemon();
oricorio.passive = true;
// Ensure the Oricorio's moveset gains the Dance move the player used
@ -303,18 +303,18 @@ export const DancingLessonsEncounter: MysteryEncounter =
}
}
await hideOricorioPokemon(scene);
await catchPokemon(scene, oricorio, null, PokeballType.POKEBALL, false);
leaveEncounterWithoutBattle(scene, true);
await hideOricorioPokemon();
await catchPokemon(oricorio, null, PokeballType.POKEBALL, false);
leaveEncounterWithoutBattle(true);
})
.build()
)
.build();
function hideOricorioPokemon(scene: BattleScene) {
function hideOricorioPokemon() {
return new Promise<void>(resolve => {
const oricorioSprite = scene.getEnemyParty()[0];
scene.tweens.add({
const oricorioSprite = gScene.getEnemyParty()[0];
gScene.tweens.add({
targets: oricorioSprite,
x: "+=16",
y: "-=16",
@ -322,7 +322,7 @@ function hideOricorioPokemon(scene: BattleScene) {
ease: "Sine.easeInOut",
duration: 750,
onComplete: () => {
scene.field.remove(oricorioSprite, true);
gScene.field.remove(oricorioSprite, true);
resolve();
}
});

View File

@ -2,7 +2,7 @@ import { Type } from "#app/data/type";
import { isNullOrUndefined, randSeedInt } from "#app/utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { modifierTypes } from "#app/modifier/modifier-type";
import { getPokemonSpecies } from "#app/data/pokemon-species";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
@ -138,16 +138,16 @@ export const DarkDealEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Removes random pokemon (including fainted) from party and adds name to dialogue data tokens
// Will never return last battle able mon and instead pick fainted/unable to battle
const removedPokemon = getRandomPlayerPokemon(scene, true, false, true);
const removedPokemon = getRandomPlayerPokemon(true, false, true);
// Get all the pokemon's held items
const modifiers = removedPokemon.getHeldItems().filter(m => !(m instanceof PokemonFormChangeItemModifier));
scene.removePokemonFromPlayerParty(removedPokemon);
gScene.removePokemonFromPlayerParty(removedPokemon);
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
encounter.setDialogueToken("pokeName", removedPokemon.getNameToRender());
// Store removed pokemon types
@ -156,16 +156,16 @@ export const DarkDealEncounter: MysteryEncounter =
modifiers
};
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Give the player 5 Rogue Balls
const encounter = scene.currentBattle.mysteryEncounter!;
scene.unshiftPhase(new ModifierRewardPhase(scene, modifierTypes.ROGUE_BALL));
const encounter = gScene.currentBattle.mysteryEncounter!;
gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.ROGUE_BALL));
// Start encounter with random legendary (7-10 starter strength) that has level additive
// If this is a mono-type challenge, always ensure the required type is filtered for
let bossTypes: Type[] = encounter.misc.removedTypes;
const singleTypeChallenges = scene.gameMode.challenges.filter(c => c.value && c.id === Challenges.SINGLE_TYPE);
if (scene.gameMode.isChallenge && singleTypeChallenges.length > 0) {
const singleTypeChallenges = gScene.gameMode.challenges.filter(c => c.value && c.id === Challenges.SINGLE_TYPE);
if (gScene.gameMode.isChallenge && singleTypeChallenges.length > 0) {
bossTypes = singleTypeChallenges.map(c => (c.value - 1) as Type);
}
@ -191,7 +191,7 @@ export const DarkDealEncounter: MysteryEncounter =
const config: EnemyPartyConfig = {
pokemonConfigs: [ pokemonConfig ],
};
await initBattleWithEnemyConfig(scene, config);
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -206,9 +206,9 @@ export const DarkDealEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)

View File

@ -3,7 +3,7 @@ import Pokemon, { PlayerPokemon } from "#app/field/pokemon";
import { modifierTypes, PokemonHeldItemModifierType } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { CombinationPokemonRequirement, HeldItemRequirement, MoneyRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
@ -96,15 +96,15 @@ export const DelibirdyEncounter: MysteryEncounter =
text: `${namespace}:outro`,
}
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
encounter.setDialogueToken("delibirdName", getPokemonSpecies(Species.DELIBIRD).getName());
scene.loadBgm("mystery_encounter_delibirdy", "mystery_encounter_delibirdy.mp3");
gScene.loadBgm("mystery_encounter_delibirdy", "mystery_encounter_delibirdy.mp3");
return true;
})
.withOnVisualsStart((scene: BattleScene) => {
scene.fadeAndSwitchBgm("mystery_encounter_delibirdy");
.withOnVisualsStart(() => {
gScene.fadeAndSwitchBgm("mystery_encounter_delibirdy");
return true;
})
.withOption(
@ -120,27 +120,27 @@ export const DelibirdyEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
updatePlayerMoney(scene, -(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney, true, false);
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
updatePlayerMoney(-(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney, true, false);
return true;
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Give the player an Amulet Coin
// Check if the player has max stacks of that item already
const existing = scene.findModifier(m => m instanceof MoneyMultiplierModifier) as MoneyMultiplierModifier;
const existing = gScene.findModifier(m => m instanceof MoneyMultiplierModifier) as MoneyMultiplierModifier;
if (existing && existing.getStackCount() >= existing.getMaxStackCount(scene)) {
if (existing && existing.getStackCount() >= existing.getMaxStackCount()) {
// At max stacks, give the first party pokemon a Shell Bell instead
const shellBell = generateModifierType(scene, modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
await applyModifierTypeToPlayerPokemon(scene, scene.getParty()[0], shellBell);
scene.playSound("item_fanfare");
await showEncounterText(scene, i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true);
const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
await applyModifierTypeToPlayerPokemon(gScene.getParty()[0], shellBell);
gScene.playSound("item_fanfare");
await showEncounterText(i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true);
} else {
scene.unshiftPhase(new ModifierRewardPhase(scene, modifierTypes.AMULET_COIN));
gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.AMULET_COIN));
}
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -158,8 +158,8 @@ export const DelibirdyEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Get Pokemon held items and filter for valid ones
const validItems = pokemon.getHeldItems().filter((it) => {
@ -185,56 +185,56 @@ export const DelibirdyEncounter: MysteryEncounter =
const selectableFilter = (pokemon: Pokemon) => {
// If pokemon has valid item, it can be selected
const meetsReqs = encounter.options[1].pokemonMeetsPrimaryRequirements(scene, pokemon);
const meetsReqs = encounter.options[1].pokemonMeetsPrimaryRequirements(pokemon);
if (!meetsReqs) {
return getEncounterText(scene, `${namespace}:invalid_selection`) ?? null;
return getEncounterText(`${namespace}:invalid_selection`) ?? null;
}
return null;
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const modifier: BerryModifier | HealingBoosterModifier = encounter.misc.chosenModifier;
// Give the player a Candy Jar if they gave a Berry, and a Berry Pouch for Reviver Seed
if (modifier instanceof BerryModifier) {
// Check if the player has max stacks of that Candy Jar already
const existing = scene.findModifier(m => m instanceof LevelIncrementBoosterModifier) as LevelIncrementBoosterModifier;
const existing = gScene.findModifier(m => m instanceof LevelIncrementBoosterModifier) as LevelIncrementBoosterModifier;
if (existing && existing.getStackCount() >= existing.getMaxStackCount(scene)) {
if (existing && existing.getStackCount() >= existing.getMaxStackCount()) {
// At max stacks, give the first party pokemon a Shell Bell instead
const shellBell = generateModifierType(scene, modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
await applyModifierTypeToPlayerPokemon(scene, scene.getParty()[0], shellBell);
scene.playSound("item_fanfare");
await showEncounterText(scene, i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true);
const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
await applyModifierTypeToPlayerPokemon(gScene.getParty()[0], shellBell);
gScene.playSound("item_fanfare");
await showEncounterText(i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true);
} else {
scene.unshiftPhase(new ModifierRewardPhase(scene, modifierTypes.CANDY_JAR));
gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.CANDY_JAR));
}
} else {
// Check if the player has max stacks of that Berry Pouch already
const existing = scene.findModifier(m => m instanceof PreserveBerryModifier) as PreserveBerryModifier;
const existing = gScene.findModifier(m => m instanceof PreserveBerryModifier) as PreserveBerryModifier;
if (existing && existing.getStackCount() >= existing.getMaxStackCount(scene)) {
if (existing && existing.getStackCount() >= existing.getMaxStackCount()) {
// At max stacks, give the first party pokemon a Shell Bell instead
const shellBell = generateModifierType(scene, modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
await applyModifierTypeToPlayerPokemon(scene, scene.getParty()[0], shellBell);
scene.playSound("item_fanfare");
await showEncounterText(scene, i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true);
const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
await applyModifierTypeToPlayerPokemon(gScene.getParty()[0], shellBell);
gScene.playSound("item_fanfare");
await showEncounterText(i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true);
} else {
scene.unshiftPhase(new ModifierRewardPhase(scene, modifierTypes.BERRY_POUCH));
gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.BERRY_POUCH));
}
}
// Remove the modifier if its stacks go to 0
modifier.stackCount -= 1;
if (modifier.stackCount === 0) {
scene.removeModifier(modifier);
gScene.removeModifier(modifier);
}
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -252,8 +252,8 @@ export const DelibirdyEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Get Pokemon held items and filter for valid ones
const validItems = pokemon.getHeldItems().filter((it) => {
@ -279,40 +279,40 @@ export const DelibirdyEncounter: MysteryEncounter =
const selectableFilter = (pokemon: Pokemon) => {
// If pokemon has valid item, it can be selected
const meetsReqs = encounter.options[2].pokemonMeetsPrimaryRequirements(scene, pokemon);
const meetsReqs = encounter.options[2].pokemonMeetsPrimaryRequirements(pokemon);
if (!meetsReqs) {
return getEncounterText(scene, `${namespace}:invalid_selection`) ?? null;
return getEncounterText(`${namespace}:invalid_selection`) ?? null;
}
return null;
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const modifier = encounter.misc.chosenModifier;
// Check if the player has max stacks of Healing Charm already
const existing = scene.findModifier(m => m instanceof HealingBoosterModifier) as HealingBoosterModifier;
const existing = gScene.findModifier(m => m instanceof HealingBoosterModifier) as HealingBoosterModifier;
if (existing && existing.getStackCount() >= existing.getMaxStackCount(scene)) {
if (existing && existing.getStackCount() >= existing.getMaxStackCount()) {
// At max stacks, give the first party pokemon a Shell Bell instead
const shellBell = generateModifierType(scene, modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
await applyModifierTypeToPlayerPokemon(scene, scene.getParty()[0], shellBell);
scene.playSound("item_fanfare");
await showEncounterText(scene, i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true);
const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
await applyModifierTypeToPlayerPokemon(gScene.getParty()[0], shellBell);
gScene.playSound("item_fanfare");
await showEncounterText(i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true);
} else {
scene.unshiftPhase(new ModifierRewardPhase(scene, modifierTypes.HEALING_CHARM));
gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.HEALING_CHARM));
}
// Remove the modifier if its stacks go to 0
modifier.stackCount -= 1;
if (modifier.stackCount === 0) {
scene.removeModifier(modifier);
gScene.removeModifier(modifier);
}
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.build()
)

View File

@ -6,7 +6,6 @@ import { ModifierTypeFunc, modifierTypes } from "#app/modifier/modifier-type";
import { randSeedInt } from "#app/utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import MysteryEncounter, {
MysteryEncounterBuilder,
} from "#app/data/mystery-encounters/mystery-encounter";
@ -60,7 +59,7 @@ export const DepartmentStoreSaleEncounter: MysteryEncounter =
buttonLabel: `${namespace}:option.1.label`,
buttonTooltip: `${namespace}:option.1.tooltip`,
},
async (scene: BattleScene) => {
async () => {
// Choose TMs
const modifiers: ModifierTypeFunc[] = [];
let i = 0;
@ -77,8 +76,8 @@ export const DepartmentStoreSaleEncounter: MysteryEncounter =
i++;
}
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: modifiers, fillRemaining: false, });
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ guaranteedModifierTypeFuncs: modifiers, fillRemaining: false, });
leaveEncounterWithoutBattle();
}
)
.withSimpleOption(
@ -86,7 +85,7 @@ export const DepartmentStoreSaleEncounter: MysteryEncounter =
buttonLabel: `${namespace}:option.2.label`,
buttonTooltip: `${namespace}:option.2.tooltip`,
},
async (scene: BattleScene) => {
async () => {
// Choose Vitamins
const modifiers: ModifierTypeFunc[] = [];
let i = 0;
@ -101,8 +100,8 @@ export const DepartmentStoreSaleEncounter: MysteryEncounter =
i++;
}
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: modifiers, fillRemaining: false, });
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ guaranteedModifierTypeFuncs: modifiers, fillRemaining: false, });
leaveEncounterWithoutBattle();
}
)
.withSimpleOption(
@ -110,7 +109,7 @@ export const DepartmentStoreSaleEncounter: MysteryEncounter =
buttonLabel: `${namespace}:option.3.label`,
buttonTooltip: `${namespace}:option.3.tooltip`,
},
async (scene: BattleScene) => {
async () => {
// Choose X Items
const modifiers: ModifierTypeFunc[] = [];
let i = 0;
@ -125,8 +124,8 @@ export const DepartmentStoreSaleEncounter: MysteryEncounter =
i++;
}
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: modifiers, fillRemaining: false, });
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ guaranteedModifierTypeFuncs: modifiers, fillRemaining: false, });
leaveEncounterWithoutBattle();
}
)
.withSimpleOption(
@ -134,7 +133,7 @@ export const DepartmentStoreSaleEncounter: MysteryEncounter =
buttonLabel: `${namespace}:option.4.label`,
buttonTooltip: `${namespace}:option.4.tooltip`,
},
async (scene: BattleScene) => {
async () => {
// Choose Pokeballs
const modifiers: ModifierTypeFunc[] = [];
let i = 0;
@ -153,8 +152,8 @@ export const DepartmentStoreSaleEncounter: MysteryEncounter =
i++;
}
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: modifiers, fillRemaining: false, });
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ guaranteedModifierTypeFuncs: modifiers, fillRemaining: false, });
leaveEncounterWithoutBattle();
}
)
.withOutroDialogue([

View File

@ -5,7 +5,7 @@ import { PlayerPokemon, PokemonMove } from "#app/field/pokemon";
import { modifierTypes } from "#app/modifier/modifier-type";
import { OptionSelectItem } from "#app/ui/abstact-option-select-ui-handler";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
import { MysteryEncounterOptionMode } from "#enums/mystery-encounter-option-mode";
@ -64,8 +64,8 @@ export const FieldTripEncounter: MysteryEncounter =
buttonTooltip: `${namespace}:option.1.tooltip`,
secondOptionPrompt: `${namespace}:second_option_prompt`,
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Return the options for Pokemon move valid for this option
return pokemon.moveset.map((move: PokemonMove) => {
@ -74,7 +74,7 @@ export const FieldTripEncounter: MysteryEncounter =
handler: () => {
// Pokemon and move selected
encounter.setDialogueToken("moveCategory", i18next.t(`${namespace}:physical`));
pokemonAndMoveChosen(scene, pokemon, move, MoveCategory.PHYSICAL);
pokemonAndMoveChosen(pokemon, move, MoveCategory.PHYSICAL);
return true;
},
};
@ -82,23 +82,23 @@ export const FieldTripEncounter: MysteryEncounter =
});
};
return selectPokemonForOption(scene, onPokemonSelected);
return selectPokemonForOption(onPokemonSelected);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
if (encounter.misc.correctMove) {
const modifiers = [
generateModifierTypeOption(scene, modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.ATK ])!,
generateModifierTypeOption(scene, modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.DEF ])!,
generateModifierTypeOption(scene, modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPD ])!,
generateModifierTypeOption(scene, modifierTypes.DIRE_HIT)!,
generateModifierTypeOption(scene, modifierTypes.RARER_CANDY)!,
generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.ATK ])!,
generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.DEF ])!,
generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPD ])!,
generateModifierTypeOption(modifierTypes.DIRE_HIT)!,
generateModifierTypeOption(modifierTypes.RARER_CANDY)!,
];
setEncounterRewards(scene, { guaranteedModifierTypeOptions: modifiers, fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeOptions: modifiers, fillRemaining: false });
}
leaveEncounterWithoutBattle(scene, !encounter.misc.correctMove);
leaveEncounterWithoutBattle(!encounter.misc.correctMove);
})
.build()
)
@ -110,8 +110,8 @@ export const FieldTripEncounter: MysteryEncounter =
buttonTooltip: `${namespace}:option.2.tooltip`,
secondOptionPrompt: `${namespace}:second_option_prompt`,
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Return the options for Pokemon move valid for this option
return pokemon.moveset.map((move: PokemonMove) => {
@ -120,7 +120,7 @@ export const FieldTripEncounter: MysteryEncounter =
handler: () => {
// Pokemon and move selected
encounter.setDialogueToken("moveCategory", i18next.t(`${namespace}:special`));
pokemonAndMoveChosen(scene, pokemon, move, MoveCategory.SPECIAL);
pokemonAndMoveChosen(pokemon, move, MoveCategory.SPECIAL);
return true;
},
};
@ -128,23 +128,23 @@ export const FieldTripEncounter: MysteryEncounter =
});
};
return selectPokemonForOption(scene, onPokemonSelected);
return selectPokemonForOption(onPokemonSelected);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
if (encounter.misc.correctMove) {
const modifiers = [
generateModifierTypeOption(scene, modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPATK ])!,
generateModifierTypeOption(scene, modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPDEF ])!,
generateModifierTypeOption(scene, modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPD ])!,
generateModifierTypeOption(scene, modifierTypes.DIRE_HIT)!,
generateModifierTypeOption(scene, modifierTypes.RARER_CANDY)!,
generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPATK ])!,
generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPDEF ])!,
generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPD ])!,
generateModifierTypeOption(modifierTypes.DIRE_HIT)!,
generateModifierTypeOption(modifierTypes.RARER_CANDY)!,
];
setEncounterRewards(scene, { guaranteedModifierTypeOptions: modifiers, fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeOptions: modifiers, fillRemaining: false });
}
leaveEncounterWithoutBattle(scene, !encounter.misc.correctMove);
leaveEncounterWithoutBattle(!encounter.misc.correctMove);
})
.build()
)
@ -156,8 +156,8 @@ export const FieldTripEncounter: MysteryEncounter =
buttonTooltip: `${namespace}:option.3.tooltip`,
secondOptionPrompt: `${namespace}:second_option_prompt`,
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Return the options for Pokemon move valid for this option
return pokemon.moveset.map((move: PokemonMove) => {
@ -166,7 +166,7 @@ export const FieldTripEncounter: MysteryEncounter =
handler: () => {
// Pokemon and move selected
encounter.setDialogueToken("moveCategory", i18next.t(`${namespace}:status`));
pokemonAndMoveChosen(scene, pokemon, move, MoveCategory.STATUS);
pokemonAndMoveChosen(pokemon, move, MoveCategory.STATUS);
return true;
},
};
@ -174,30 +174,30 @@ export const FieldTripEncounter: MysteryEncounter =
});
};
return selectPokemonForOption(scene, onPokemonSelected);
return selectPokemonForOption(onPokemonSelected);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
if (encounter.misc.correctMove) {
const modifiers = [
generateModifierTypeOption(scene, modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.ACC ])!,
generateModifierTypeOption(scene, modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPD ])!,
generateModifierTypeOption(scene, modifierTypes.GREAT_BALL)!,
generateModifierTypeOption(scene, modifierTypes.IV_SCANNER)!,
generateModifierTypeOption(scene, modifierTypes.RARER_CANDY)!,
generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.ACC ])!,
generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPD ])!,
generateModifierTypeOption(modifierTypes.GREAT_BALL)!,
generateModifierTypeOption(modifierTypes.IV_SCANNER)!,
generateModifierTypeOption(modifierTypes.RARER_CANDY)!,
];
setEncounterRewards(scene, { guaranteedModifierTypeOptions: modifiers, fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeOptions: modifiers, fillRemaining: false });
}
leaveEncounterWithoutBattle(scene, !encounter.misc.correctMove);
leaveEncounterWithoutBattle(!encounter.misc.correctMove);
})
.build()
)
.build();
function pokemonAndMoveChosen(scene: BattleScene, pokemon: PlayerPokemon, move: PokemonMove, correctMoveCategory: MoveCategory) {
const encounter = scene.currentBattle.mysteryEncounter!;
function pokemonAndMoveChosen(pokemon: PlayerPokemon, move: PokemonMove, correctMoveCategory: MoveCategory) {
const encounter = gScene.currentBattle.mysteryEncounter!;
const correctMove = move.getMove().category === correctMoveCategory;
encounter.setDialogueToken("pokeName", pokemon.getNameToRender());
encounter.setDialogueToken("move", move.getName());
@ -214,7 +214,7 @@ function pokemonAndMoveChosen(scene: BattleScene, pokemon: PlayerPokemon, move:
text: `${namespace}:incorrect_exp`,
},
];
setEncounterExp(scene, scene.getParty().map((p) => p.id), 50);
setEncounterExp(gScene.getParty().map((p) => p.id), 50);
} else {
encounter.selectedOption!.dialogue!.selected = [
{
@ -228,7 +228,7 @@ function pokemonAndMoveChosen(scene: BattleScene, pokemon: PlayerPokemon, move:
text: `${namespace}:correct_exp`,
},
];
setEncounterExp(scene, [ pokemon.id ], 100);
setEncounterExp([ pokemon.id ], 100);
}
encounter.misc = {
correctMove: correctMove,

View File

@ -2,7 +2,7 @@ import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/myst
import { EnemyPartyConfig, initBattleWithEnemyConfig, loadCustomMovesForEncounter, leaveEncounterWithoutBattle, setEncounterExp, setEncounterRewards, transitionMysteryEncounterIntroVisuals, generateModifierType } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { AttackTypeBoosterModifierType, modifierTypes, } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { AbilityRequirement, CombinationPokemonRequirement, TypeRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
import { Species } from "#enums/species";
@ -58,8 +58,8 @@ export const FieryFalloutEncounter: MysteryEncounter =
text: `${namespace}:intro`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculate boss mons
const volcaronaSpecies = getPokemonSpecies(Species.VOLCARONA);
@ -71,7 +71,7 @@ export const FieryFalloutEncounter: MysteryEncounter =
gender: Gender.MALE,
tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ],
mysteryEncounterBattleEffects: (pokemon: Pokemon) => {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.SPDEF, Stat.SPD ], 1));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPDEF, Stat.SPD ], 1));
}
},
{
@ -80,7 +80,7 @@ export const FieryFalloutEncounter: MysteryEncounter =
gender: Gender.FEMALE,
tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ],
mysteryEncounterBattleEffects: (pokemon: Pokemon) => {
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.SPDEF, Stat.SPD ], 1));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPDEF, Stat.SPD ], 1));
}
}
],
@ -113,25 +113,25 @@ export const FieryFalloutEncounter: MysteryEncounter =
];
// Load animations/sfx for Volcarona moves
loadCustomMovesForEncounter(scene, [ Moves.FIRE_SPIN, Moves.QUIVER_DANCE ]);
loadCustomMovesForEncounter([ Moves.FIRE_SPIN, Moves.QUIVER_DANCE ]);
scene.arena.trySetWeather(WeatherType.SUNNY, true);
gScene.arena.trySetWeather(WeatherType.SUNNY, true);
encounter.setDialogueToken("volcaronaName", getPokemonSpecies(Species.VOLCARONA).getName());
return true;
})
.withOnVisualsStart((scene: BattleScene) => {
.withOnVisualsStart(() => {
// Play animations
const background = new EncounterBattleAnim(EncounterAnim.MAGMA_BG, scene.getPlayerPokemon()!, scene.getPlayerPokemon());
background.playWithoutTargets(scene, 200, 70, 2, 3);
const animation = new EncounterBattleAnim(EncounterAnim.MAGMA_SPOUT, scene.getPlayerPokemon()!, scene.getPlayerPokemon());
animation.playWithoutTargets(scene, 80, 100, 2);
scene.time.delayedCall(600, () => {
animation.playWithoutTargets(scene, -20, 100, 2);
const background = new EncounterBattleAnim(EncounterAnim.MAGMA_BG, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon());
background.playWithoutTargets(200, 70, 2, 3);
const animation = new EncounterBattleAnim(EncounterAnim.MAGMA_SPOUT, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon());
animation.playWithoutTargets(80, 100, 2);
gScene.time.delayedCall(600, () => {
animation.playWithoutTargets(-20, 100, 2);
});
scene.time.delayedCall(1200, () => {
animation.playWithoutTargets(scene, 140, 150, 2);
gScene.time.delayedCall(1200, () => {
animation.playWithoutTargets(140, 150, 2);
});
return true;
@ -150,10 +150,10 @@ export const FieryFalloutEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Pick battle
const encounter = scene.currentBattle.mysteryEncounter!;
setEncounterRewards(scene, { fillRemaining: true }, undefined, () => giveLeadPokemonAttackTypeBoostItem(scene));
const encounter = gScene.currentBattle.mysteryEncounter!;
setEncounterRewards({ fillRemaining: true }, undefined, () => giveLeadPokemonAttackTypeBoostItem());
encounter.startOfBattleEffects.push(
{
@ -168,7 +168,7 @@ export const FieryFalloutEncounter: MysteryEncounter =
move: new PokemonMove(Moves.FIRE_SPIN),
ignorePp: true
});
await initBattleWithEnemyConfig(scene, scene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]);
await initBattleWithEnemyConfig(gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]);
}
)
.withSimpleOption(
@ -181,15 +181,15 @@ export const FieryFalloutEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Damage non-fire types and burn 1 random non-fire type member + give it Heatproof
const encounter = scene.currentBattle.mysteryEncounter!;
const nonFireTypes = scene.getParty().filter((p) => p.isAllowedInBattle() && !p.getTypes().includes(Type.FIRE));
const encounter = gScene.currentBattle.mysteryEncounter!;
const nonFireTypes = gScene.getParty().filter((p) => p.isAllowedInBattle() && !p.getTypes().includes(Type.FIRE));
for (const pkm of nonFireTypes) {
const percentage = DAMAGE_PERCENTAGE / 100;
const damage = Math.floor(pkm.getMaxHp() * percentage);
applyDamageToPokemon(scene, pkm, damage);
applyDamageToPokemon(pkm, damage);
}
// Burn random member
@ -201,7 +201,7 @@ export const FieryFalloutEncounter: MysteryEncounter =
// Burn applied
encounter.setDialogueToken("burnedPokemon", chosenPokemon.getNameToRender());
encounter.setDialogueToken("abilityName", new Ability(Abilities.HEATPROOF, 3).name);
queueEncounterMessage(scene, `${namespace}:option.2.target_burned`);
queueEncounterMessage(`${namespace}:option.2.target_burned`);
// Also permanently change the burned Pokemon's ability to Heatproof
applyAbilityOverrideToPokemon(chosenPokemon, Abilities.HEATPROOF);
@ -209,7 +209,7 @@ export const FieryFalloutEncounter: MysteryEncounter =
}
// No rewards
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
}
)
.withOption(
@ -231,44 +231,44 @@ export const FieryFalloutEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Do NOT await this, to prevent player from repeatedly pressing options
transitionMysteryEncounterIntroVisuals(scene, false, false, 2000);
transitionMysteryEncounterIntroVisuals(false, false, 2000);
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Fire types help calm the Volcarona
const encounter = scene.currentBattle.mysteryEncounter!;
await transitionMysteryEncounterIntroVisuals(scene);
setEncounterRewards(scene,
const encounter = gScene.currentBattle.mysteryEncounter!;
await transitionMysteryEncounterIntroVisuals();
setEncounterRewards(
{ fillRemaining: true },
undefined,
() => {
giveLeadPokemonAttackTypeBoostItem(scene);
giveLeadPokemonAttackTypeBoostItem();
});
const primary = encounter.options[2].primaryPokemon!;
setEncounterExp(scene, [ primary.id ], getPokemonSpecies(Species.VOLCARONA).baseExp * 2);
leaveEncounterWithoutBattle(scene);
setEncounterExp([ primary.id ], getPokemonSpecies(Species.VOLCARONA).baseExp * 2);
leaveEncounterWithoutBattle();
})
.build()
)
.build();
function giveLeadPokemonAttackTypeBoostItem(scene: BattleScene) {
function giveLeadPokemonAttackTypeBoostItem() {
// Give first party pokemon attack type boost item for free at end of battle
const leadPokemon = scene.getParty()?.[0];
const leadPokemon = gScene.getParty()?.[0];
if (leadPokemon) {
// Generate type booster held item, default to Charcoal if item fails to generate
let boosterModifierType = generateModifierType(scene, modifierTypes.ATTACK_TYPE_BOOSTER) as AttackTypeBoosterModifierType;
let boosterModifierType = generateModifierType(modifierTypes.ATTACK_TYPE_BOOSTER) as AttackTypeBoosterModifierType;
if (!boosterModifierType) {
boosterModifierType = generateModifierType(scene, modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.FIRE ]) as AttackTypeBoosterModifierType;
boosterModifierType = generateModifierType(modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.FIRE ]) as AttackTypeBoosterModifierType;
}
applyModifierTypeToPlayerPokemon(scene, leadPokemon, boosterModifierType);
applyModifierTypeToPlayerPokemon(leadPokemon, boosterModifierType);
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
encounter.setDialogueToken("itemName", boosterModifierType.name);
encounter.setDialogueToken("leadPokemon", leadPokemon.getNameToRender());
queueEncounterMessage(scene, `${namespace}:found_item`);
queueEncounterMessage(`${namespace}:found_item`);
}
}

View File

@ -2,7 +2,8 @@ import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/myst
import {
EnemyPartyConfig,
initBattleWithEnemyConfig,
leaveEncounterWithoutBattle, setEncounterExp,
leaveEncounterWithoutBattle,
setEncounterExp,
setEncounterRewards
} from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { STEALING_MOVES } from "#app/data/mystery-encounters/requirements/requirement-groups";
@ -16,7 +17,7 @@ import {
regenerateModifierPoolThresholds,
} from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MoveRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -51,13 +52,13 @@ export const FightOrFlightEncounter: MysteryEncounter =
text: `${namespace}:intro`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculate boss mon
const level = getEncounterPokemonLevelForWave(scene, STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const bossSpecies = scene.arena.randomSpecies(scene.currentBattle.waveIndex, level, 0, getPartyLuckValue(scene.getParty()), true);
const bossPokemon = new EnemyPokemon(scene, bossSpecies, level, TrainerSlot.NONE, true);
const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const bossSpecies = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true);
const bossPokemon = new EnemyPokemon(bossSpecies, level, TrainerSlot.NONE, true);
encounter.setDialogueToken("enemyPokemon", bossPokemon.getNameToRender());
const config: EnemyPartyConfig = {
pokemonConfigs: [{
@ -67,10 +68,10 @@ export const FightOrFlightEncounter: MysteryEncounter =
isBoss: true,
tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ],
mysteryEncounterBattleEffects: (pokemon: Pokemon) => {
queueEncounterMessage(pokemon.scene, `${namespace}:option.1.stat_boost`);
queueEncounterMessage(`${namespace}:option.1.stat_boost`);
// Randomly boost 1 stat 2 stages
// Cannot boost Spd, Acc, or Evasion
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ randSeedInt(4, 1) ], 2));
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ randSeedInt(4, 1) ], 2));
}
}],
};
@ -79,18 +80,18 @@ export const FightOrFlightEncounter: MysteryEncounter =
// Calculate item
// Waves 10-40 GREAT, 60-120 ULTRA, 120-160 ROGUE, 160-180 MASTER
const tier =
scene.currentBattle.waveIndex > 160
gScene.currentBattle.waveIndex > 160
? ModifierTier.MASTER
: scene.currentBattle.waveIndex > 120
: gScene.currentBattle.waveIndex > 120
? ModifierTier.ROGUE
: scene.currentBattle.waveIndex > 40
: gScene.currentBattle.waveIndex > 40
? ModifierTier.ULTRA
: ModifierTier.GREAT;
regenerateModifierPoolThresholds(scene.getParty(), ModifierPoolType.PLAYER, 0);
regenerateModifierPoolThresholds(gScene.getParty(), ModifierPoolType.PLAYER, 0);
let item: ModifierTypeOption | null = null;
// TMs and Candy Jar excluded from possible rewards as they're too swingy in value for a singular item reward
while (!item || item.type.id.includes("TM_") || item.type.id === "CANDY_JAR") {
item = getPlayerModifierTypeOptions(1, scene.getParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0];
item = getPlayerModifierTypeOptions(1, gScene.getParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0];
}
encounter.setDialogueToken("itemName", item.type.name);
encounter.misc = item;
@ -134,12 +135,12 @@ export const FightOrFlightEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Pick battle
// Pokemon will randomly boost 1 stat by 2 stages
const item = scene.currentBattle.mysteryEncounter!.misc as ModifierTypeOption;
setEncounterRewards(scene, { guaranteedModifierTypeOptions: [ item ], fillRemaining: false });
await initBattleWithEnemyConfig(scene, scene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]);
const item = gScene.currentBattle.mysteryEncounter!.misc as ModifierTypeOption;
setEncounterRewards({ guaranteedModifierTypeOptions: [ item ], fillRemaining: false });
await initBattleWithEnemyConfig(gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]);
}
)
.withOption(
@ -156,16 +157,16 @@ export const FightOrFlightEncounter: MysteryEncounter =
}
]
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Pick steal
const encounter = scene.currentBattle.mysteryEncounter!;
const item = scene.currentBattle.mysteryEncounter!.misc as ModifierTypeOption;
setEncounterRewards(scene, { guaranteedModifierTypeOptions: [ item ], fillRemaining: false });
const encounter = gScene.currentBattle.mysteryEncounter!;
const item = gScene.currentBattle.mysteryEncounter!.misc as ModifierTypeOption;
setEncounterRewards({ guaranteedModifierTypeOptions: [ item ], fillRemaining: false });
// Use primaryPokemon to execute the thievery
const primaryPokemon = encounter.options[1].primaryPokemon!;
setEncounterExp(scene, primaryPokemon.id, encounter.enemyPartyConfigs[0].pokemonConfigs![0].species.baseExp);
leaveEncounterWithoutBattle(scene);
setEncounterExp(primaryPokemon.id, encounter.enemyPartyConfigs[0].pokemonConfigs![0].species.baseExp);
leaveEncounterWithoutBattle();
})
.build()
)
@ -179,9 +180,9 @@ export const FightOrFlightEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)

View File

@ -1,6 +1,6 @@
import { leaveEncounterWithoutBattle, selectPokemonForOption, setEncounterRewards, transitionMysteryEncounterIntroVisuals, updatePlayerMoney, } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { TrainerSlot } from "#app/data/trainer-config";
@ -80,14 +80,14 @@ export const FunAndGamesEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
scene.loadBgm("mystery_encounter_fun_and_games", "mystery_encounter_fun_and_games.mp3");
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
gScene.loadBgm("mystery_encounter_fun_and_games", "mystery_encounter_fun_and_games.mp3");
encounter.setDialogueToken("wobbuffetName", getPokemonSpecies(Species.WOBBUFFET).getName());
return true;
})
.withOnVisualsStart((scene: BattleScene) => {
scene.fadeAndSwitchBgm("mystery_encounter_fun_and_games");
.withOnVisualsStart(() => {
gScene.fadeAndSwitchBgm("mystery_encounter_fun_and_games");
return true;
})
.withOption(MysteryEncounterOptionBuilder
@ -102,9 +102,9 @@ export const FunAndGamesEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Select Pokemon for minigame
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
encounter.misc = {
playerPokemon: pokemon,
@ -113,28 +113,28 @@ export const FunAndGamesEncounter: MysteryEncounter =
// Only Pokemon that are not KOed/legal can be selected
const selectableFilter = (pokemon: Pokemon) => {
return isPokemonValidForEncounterOptionSelection(pokemon, scene, `${namespace}:invalid_selection`);
return isPokemonValidForEncounterOptionSelection(pokemon, `${namespace}:invalid_selection`);
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Start minigame
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
encounter.misc.turnsRemaining = 3;
// Update money
const moneyCost = (encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney;
updatePlayerMoney(scene, -moneyCost, true, false);
await showEncounterText(scene, i18next.t("mysteryEncounterMessages:paid_money", { amount: moneyCost }));
updatePlayerMoney(-moneyCost, true, false);
await showEncounterText(i18next.t("mysteryEncounterMessages:paid_money", { amount: moneyCost }));
// Handlers for battle events
encounter.onTurnStart = handleNextTurn; // triggered during TurnInitPhase
encounter.doContinueEncounter = handleLoseMinigame; // triggered during MysteryEncounterRewardsPhase, post VictoryPhase if the player KOs Wobbuffet
hideShowmanIntroSprite(scene);
await summonPlayerPokemon(scene);
await showWobbuffetHealthBar(scene);
hideShowmanIntroSprite();
await summonPlayerPokemon();
await showWobbuffetHealthBar();
return true;
})
@ -150,22 +150,22 @@ export const FunAndGamesEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
await transitionMysteryEncounterIntroVisuals(scene, true, true);
leaveEncounterWithoutBattle(scene, true);
await transitionMysteryEncounterIntroVisuals(true, true);
leaveEncounterWithoutBattle(true);
return true;
}
)
.build();
async function summonPlayerPokemon(scene: BattleScene) {
async function summonPlayerPokemon() {
return new Promise<void>(async resolve => {
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const playerPokemon = encounter.misc.playerPokemon;
// Swaps the chosen Pokemon and the first player's lead Pokemon in the party
const party = scene.getParty();
const party = gScene.getParty();
const chosenIndex = party.indexOf(playerPokemon);
if (chosenIndex !== 0) {
const leadPokemon = party[0];
@ -175,36 +175,36 @@ async function summonPlayerPokemon(scene: BattleScene) {
// Do trainer summon animation
let playerAnimationPromise: Promise<void> | undefined;
scene.ui.showText(i18next.t("battle:playerGo", { pokemonName: getPokemonNameWithAffix(playerPokemon) }));
scene.pbTray.hide();
scene.trainer.setTexture(`trainer_${scene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`);
scene.time.delayedCall(562, () => {
scene.trainer.setFrame("2");
scene.time.delayedCall(64, () => {
scene.trainer.setFrame("3");
gScene.ui.showText(i18next.t("battle:playerGo", { pokemonName: getPokemonNameWithAffix(playerPokemon) }));
gScene.pbTray.hide();
gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`);
gScene.time.delayedCall(562, () => {
gScene.trainer.setFrame("2");
gScene.time.delayedCall(64, () => {
gScene.trainer.setFrame("3");
});
});
scene.tweens.add({
targets: scene.trainer,
gScene.tweens.add({
targets: gScene.trainer,
x: -36,
duration: 1000,
onComplete: () => scene.trainer.setVisible(false)
onComplete: () => gScene.trainer.setVisible(false)
});
scene.time.delayedCall(750, () => {
playerAnimationPromise = summonPlayerPokemonAnimation(scene, playerPokemon);
gScene.time.delayedCall(750, () => {
playerAnimationPromise = summonPlayerPokemonAnimation(playerPokemon);
});
// Also loads Wobbuffet data
const enemySpecies = getPokemonSpecies(Species.WOBBUFFET);
scene.currentBattle.enemyParty = [];
const wobbuffet = scene.addEnemyPokemon(enemySpecies, encounter.misc.playerPokemon.level, TrainerSlot.NONE, false);
gScene.currentBattle.enemyParty = [];
const wobbuffet = gScene.addEnemyPokemon(enemySpecies, encounter.misc.playerPokemon.level, TrainerSlot.NONE, false);
wobbuffet.ivs = [ 0, 0, 0, 0, 0, 0 ];
wobbuffet.setNature(Nature.MILD);
wobbuffet.setAlpha(0);
wobbuffet.setVisible(false);
wobbuffet.calculateStats();
scene.currentBattle.enemyParty[0] = wobbuffet;
scene.gameData.setPokemonSeen(wobbuffet, true);
gScene.currentBattle.enemyParty[0] = wobbuffet;
gScene.gameData.setPokemonSeen(wobbuffet, true);
await wobbuffet.loadAssets();
const id = setInterval(checkPlayerAnimationPromise, 500);
async function checkPlayerAnimationPromise() {
@ -217,37 +217,37 @@ async function summonPlayerPokemon(scene: BattleScene) {
});
}
function handleLoseMinigame(scene: BattleScene) {
function handleLoseMinigame() {
return new Promise<void>(async resolve => {
// Check Wobbuffet is still alive
const wobbuffet = scene.getEnemyPokemon();
const wobbuffet = gScene.getEnemyPokemon();
if (!wobbuffet || wobbuffet.isFainted(true) || wobbuffet.hp === 0) {
// Player loses
// End the battle
if (wobbuffet) {
wobbuffet.hideInfo();
scene.field.remove(wobbuffet);
gScene.field.remove(wobbuffet);
}
transitionMysteryEncounterIntroVisuals(scene, true, true);
scene.currentBattle.enemyParty = [];
scene.currentBattle.mysteryEncounter!.doContinueEncounter = undefined;
leaveEncounterWithoutBattle(scene, true);
await showEncounterText(scene, `${namespace}:ko`);
const reviveCost = scene.getWaveMoneyAmount(1.5);
updatePlayerMoney(scene, -reviveCost, true, false);
transitionMysteryEncounterIntroVisuals(true, true);
gScene.currentBattle.enemyParty = [];
gScene.currentBattle.mysteryEncounter!.doContinueEncounter = undefined;
leaveEncounterWithoutBattle(true);
await showEncounterText(`${namespace}:ko`);
const reviveCost = gScene.getWaveMoneyAmount(1.5);
updatePlayerMoney(-reviveCost, true, false);
}
resolve();
});
}
function handleNextTurn(scene: BattleScene) {
const encounter = scene.currentBattle.mysteryEncounter!;
function handleNextTurn() {
const encounter = gScene.currentBattle.mysteryEncounter!;
const wobbuffet = scene.getEnemyPokemon();
const wobbuffet = gScene.getEnemyPokemon();
if (!wobbuffet) {
// Should never be triggered, just handling the edge case
handleLoseMinigame(scene);
handleLoseMinigame();
return true;
}
if (encounter.misc.turnsRemaining <= 0) {
@ -257,15 +257,15 @@ function handleNextTurn(scene: BattleScene) {
let isHealPhase = false;
if (healthRatio < 0.03) {
// Grand prize
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.MULTI_LENS ], fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.MULTI_LENS ], fillRemaining: false });
resultMessageKey = `${namespace}:best_result`;
} else if (healthRatio < 0.15) {
// 2nd prize
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.SCOPE_LENS ], fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.SCOPE_LENS ], fillRemaining: false });
resultMessageKey = `${namespace}:great_result`;
} else if (healthRatio < 0.33) {
// 3rd prize
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.WIDE_LENS ], fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.WIDE_LENS ], fillRemaining: false });
resultMessageKey = `${namespace}:good_result`;
} else {
// No prize
@ -275,22 +275,22 @@ function handleNextTurn(scene: BattleScene) {
// End the battle
wobbuffet.hideInfo();
scene.field.remove(wobbuffet);
scene.currentBattle.enemyParty = [];
scene.currentBattle.mysteryEncounter!.doContinueEncounter = undefined;
leaveEncounterWithoutBattle(scene, isHealPhase);
gScene.field.remove(wobbuffet);
gScene.currentBattle.enemyParty = [];
gScene.currentBattle.mysteryEncounter!.doContinueEncounter = undefined;
leaveEncounterWithoutBattle(isHealPhase);
// Must end the TurnInit phase prematurely so battle phases aren't added to queue
queueEncounterMessage(scene, `${namespace}:end_game`);
queueEncounterMessage(scene, resultMessageKey);
queueEncounterMessage(`${namespace}:end_game`);
queueEncounterMessage(resultMessageKey);
// Skip remainder of TurnInitPhase
return true;
} else {
if (encounter.misc.turnsRemaining < 3) {
// Display charging messages on turns that aren't the initial turn
queueEncounterMessage(scene, `${namespace}:charging_continue`);
queueEncounterMessage(`${namespace}:charging_continue`);
}
queueEncounterMessage(scene, `${namespace}:turn_remaining_${encounter.misc.turnsRemaining}`);
queueEncounterMessage(`${namespace}:turn_remaining_${encounter.misc.turnsRemaining}`);
encounter.misc.turnsRemaining--;
}
@ -298,33 +298,33 @@ function handleNextTurn(scene: BattleScene) {
return false;
}
async function showWobbuffetHealthBar(scene: BattleScene) {
const wobbuffet = scene.getEnemyPokemon()!;
async function showWobbuffetHealthBar() {
const wobbuffet = gScene.getEnemyPokemon()!;
scene.add.existing(wobbuffet);
scene.field.add(wobbuffet);
gScene.add.existing(wobbuffet);
gScene.field.add(wobbuffet);
const playerPokemon = scene.getPlayerPokemon() as Pokemon;
const playerPokemon = gScene.getPlayerPokemon() as Pokemon;
if (playerPokemon?.visible) {
scene.field.moveBelow(wobbuffet, playerPokemon);
gScene.field.moveBelow(wobbuffet, playerPokemon);
}
// Show health bar and trigger cry
wobbuffet.showInfo();
scene.time.delayedCall(1000, () => {
gScene.time.delayedCall(1000, () => {
wobbuffet.cry();
});
wobbuffet.resetSummonData();
// Track the HP change across turns
scene.currentBattle.mysteryEncounter!.misc.wobbuffetHealth = wobbuffet.hp;
gScene.currentBattle.mysteryEncounter!.misc.wobbuffetHealth = wobbuffet.hp;
}
function summonPlayerPokemonAnimation(scene: BattleScene, pokemon: PlayerPokemon): Promise<void> {
function summonPlayerPokemonAnimation(pokemon: PlayerPokemon): Promise<void> {
return new Promise<void>(resolve => {
const pokeball = scene.addFieldSprite(36, 80, "pb", getPokeballAtlasKey(pokemon.pokeball));
const pokeball = gScene.addFieldSprite(36, 80, "pb", getPokeballAtlasKey(pokemon.pokeball));
pokeball.setVisible(false);
pokeball.setOrigin(0.5, 0.625);
scene.field.add(pokeball);
gScene.field.add(pokeball);
pokemon.setFieldPosition(FieldPosition.CENTER, 0);
@ -332,32 +332,32 @@ function summonPlayerPokemonAnimation(scene: BattleScene, pokemon: PlayerPokemon
pokeball.setVisible(true);
scene.tweens.add({
gScene.tweens.add({
targets: pokeball,
duration: 650,
x: 100 + fpOffset[0]
});
scene.tweens.add({
gScene.tweens.add({
targets: pokeball,
duration: 150,
ease: "Cubic.easeOut",
y: 70 + fpOffset[1],
onComplete: () => {
scene.tweens.add({
gScene.tweens.add({
targets: pokeball,
duration: 500,
ease: "Cubic.easeIn",
angle: 1440,
y: 132 + fpOffset[1],
onComplete: () => {
scene.playSound("se/pb_rel");
gScene.playSound("se/pb_rel");
pokeball.destroy();
scene.add.existing(pokemon);
scene.field.add(pokemon);
addPokeballOpenParticles(scene, pokemon.x, pokemon.y - 16, pokemon.pokeball);
scene.updateModifiers(true);
scene.updateFieldScale();
gScene.add.existing(pokemon);
gScene.field.add(pokemon);
addPokeballOpenParticles(pokemon.x, pokemon.y - 16, pokemon.pokeball);
gScene.updateModifiers(true);
gScene.updateFieldScale();
pokemon.showInfo();
pokemon.playAnim();
pokemon.setVisible(true);
@ -365,8 +365,8 @@ function summonPlayerPokemonAnimation(scene: BattleScene, pokemon: PlayerPokemon
pokemon.setScale(0.5);
pokemon.tint(getPokeballTintColor(pokemon.pokeball));
pokemon.untint(250, "Sine.easeIn");
scene.updateFieldScale();
scene.tweens.add({
gScene.updateFieldScale();
gScene.tweens.add({
targets: pokemon,
duration: 250,
ease: "Sine.easeIn",
@ -375,15 +375,15 @@ function summonPlayerPokemonAnimation(scene: BattleScene, pokemon: PlayerPokemon
pokemon.cry(pokemon.getHpRatio() > 0.25 ? undefined : { rate: 0.85 });
pokemon.getSprite().clearTint();
pokemon.resetSummonData();
scene.time.delayedCall(1000, () => {
gScene.time.delayedCall(1000, () => {
if (pokemon.isShiny()) {
scene.unshiftPhase(new ShinySparklePhase(scene, pokemon.getBattlerIndex()));
gScene.unshiftPhase(new ShinySparklePhase(pokemon.getBattlerIndex()));
}
pokemon.resetTurnData();
scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true);
scene.pushPhase(new PostSummonPhase(scene, pokemon.getBattlerIndex()));
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true);
gScene.pushPhase(new PostSummonPhase(pokemon.getBattlerIndex()));
resolve();
});
}
@ -395,13 +395,13 @@ function summonPlayerPokemonAnimation(scene: BattleScene, pokemon: PlayerPokemon
});
}
function hideShowmanIntroSprite(scene: BattleScene) {
const carnivalGame = scene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(0)[0];
const wobbuffet = scene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1)[0];
const showMan = scene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(2)[0];
function hideShowmanIntroSprite() {
const carnivalGame = gScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(0)[0];
const wobbuffet = gScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1)[0];
const showMan = gScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(2)[0];
// Hide the showman
scene.tweens.add({
gScene.tweens.add({
targets: showMan,
x: "+=16",
y: "-=16",
@ -411,7 +411,7 @@ function hideShowmanIntroSprite(scene: BattleScene) {
});
// Slide the Wobbuffet and Game over slightly
scene.tweens.add({
gScene.tweens.add({
targets: [ wobbuffet, carnivalGame ],
x: "+=16",
ease: "Sine.easeInOut",

View File

@ -3,7 +3,7 @@ import { TrainerSlot, } from "#app/data/trainer-config";
import { ModifierTier } from "#app/modifier/modifier-tier";
import { getPlayerModifierTypeOptions, ModifierPoolType, ModifierTypeOption, regenerateModifierPoolThresholds } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
import { Species } from "#enums/species";
@ -100,24 +100,24 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Load bgm
let bgmKey: string;
if (scene.musicPreference === 0) {
if (gScene.musicPreference === 0) {
bgmKey = "mystery_encounter_gen_5_gts";
scene.loadBgm(bgmKey, `${bgmKey}.mp3`);
gScene.loadBgm(bgmKey, `${bgmKey}.mp3`);
} else {
// Mixed option
bgmKey = "mystery_encounter_gen_6_gts";
scene.loadBgm(bgmKey, `${bgmKey}.mp3`);
gScene.loadBgm(bgmKey, `${bgmKey}.mp3`);
}
// Load possible trade options
// Maps current party member's id to 3 EnemyPokemon objects
// None of the trade options can be the same species
const tradeOptionsMap: Map<number, EnemyPokemon[]> = getPokemonTradeOptions(scene);
const tradeOptionsMap: Map<number, EnemyPokemon[]> = getPokemonTradeOptions();
encounter.misc = {
tradeOptionsMap,
bgmKey
@ -125,8 +125,8 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
return true;
})
.withOnVisualsStart((scene: BattleScene) => {
scene.fadeAndSwitchBgm(scene.currentBattle.mysteryEncounter!.misc.bgmKey);
.withOnVisualsStart(() => {
gScene.fadeAndSwitchBgm(gScene.currentBattle.mysteryEncounter!.misc.bgmKey);
return true;
})
.withOption(
@ -138,8 +138,8 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
buttonTooltip: `${namespace}:option.1.tooltip`,
secondOptionPrompt: `${namespace}:option.1.trade_options_prompt`,
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Get the trade species options for the selected pokemon
const tradeOptionsMap: Map<number, EnemyPokemon[]> = encounter.misc.tradeOptionsMap;
@ -163,17 +163,17 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
const formName = tradePokemon.species.forms && tradePokemon.species.forms.length > tradePokemon.formIndex ? tradePokemon.species.forms[tradePokemon.formIndex].formName : null;
const line1 = i18next.t("pokemonInfoContainer:ability") + " " + tradePokemon.getAbility().name + (tradePokemon.getGender() !== Gender.GENDERLESS ? " | " + i18next.t("pokemonInfoContainer:gender") + " " + getGenderSymbol(tradePokemon.getGender()) : "");
const line2 = i18next.t("pokemonInfoContainer:nature") + " " + getNatureName(tradePokemon.getNature()) + (formName ? " | " + i18next.t("pokemonInfoContainer:form") + " " + formName : "");
showEncounterText(scene, `${line1}\n${line2}`, 0, 0, false);
showEncounterText(`${line1}\n${line2}`, 0, 0, false);
},
};
return option;
});
};
return selectPokemonForOption(scene, onPokemonSelected);
return selectPokemonForOption(onPokemonSelected);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const tradedPokemon: PlayerPokemon = encounter.misc.tradedPokemon;
const receivedPokemonData: EnemyPokemon = encounter.misc.receivedPokemon;
const modifiers = tradedPokemon.getHeldItems().filter(m => !(m instanceof PokemonFormChangeItemModifier) && !(m instanceof SpeciesStatBoosterModifier));
@ -183,32 +183,32 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
encounter.setDialogueToken("tradeTrainerName", traderName.trim());
// Remove the original party member from party
scene.removePokemonFromPlayerParty(tradedPokemon, false);
gScene.removePokemonFromPlayerParty(tradedPokemon, false);
// Set data properly, then generate the new Pokemon's assets
receivedPokemonData.passive = tradedPokemon.passive;
// Pokeball to Ultra ball, randomly
receivedPokemonData.pokeball = randInt(4) as PokeballType;
const dataSource = new PokemonData(receivedPokemonData);
const newPlayerPokemon = scene.addPlayerPokemon(receivedPokemonData.species, receivedPokemonData.level, dataSource.abilityIndex, dataSource.formIndex, dataSource.gender, dataSource.shiny, dataSource.variant, dataSource.ivs, dataSource.nature, dataSource);
scene.getParty().push(newPlayerPokemon);
const newPlayerPokemon = gScene.addPlayerPokemon(receivedPokemonData.species, receivedPokemonData.level, dataSource.abilityIndex, dataSource.formIndex, dataSource.gender, dataSource.shiny, dataSource.variant, dataSource.ivs, dataSource.nature, dataSource);
gScene.getParty().push(newPlayerPokemon);
await newPlayerPokemon.loadAssets();
for (const mod of modifiers) {
mod.pokemonId = newPlayerPokemon.id;
scene.addModifier(mod, true, false, false, true);
gScene.addModifier(mod, true, false, false, true);
}
// Show the trade animation
await showTradeBackground(scene);
await doPokemonTradeSequence(scene, tradedPokemon, newPlayerPokemon);
await showEncounterText(scene, `${namespace}:trade_received`, null, 0, true, 4000);
scene.playBgm(encounter.misc.bgmKey);
await addPokemonDataToDexAndValidateAchievements(scene, newPlayerPokemon);
await hideTradeBackground(scene);
await showTradeBackground();
await doPokemonTradeSequence(tradedPokemon, newPlayerPokemon);
await showEncounterText(`${namespace}:trade_received`, null, 0, true, 4000);
gScene.playBgm(encounter.misc.bgmKey);
await addPokemonDataToDexAndValidateAchievements(newPlayerPokemon);
await hideTradeBackground();
tradedPokemon.destroy();
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -220,19 +220,19 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
buttonLabel: `${namespace}:option.2.label`,
buttonTooltip: `${namespace}:option.2.tooltip`,
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Randomly generate a Wonder Trade pokemon
const randomTradeOption = generateTradeOption(scene.getParty().map(p => p.species));
const tradePokemon = new EnemyPokemon(scene, randomTradeOption, pokemon.level, TrainerSlot.NONE, false);
const randomTradeOption = generateTradeOption(gScene.getParty().map(p => p.species));
const tradePokemon = new EnemyPokemon(randomTradeOption, pokemon.level, TrainerSlot.NONE, false);
// Extra shiny roll at 1/128 odds (boosted by events and charms)
if (!tradePokemon.shiny) {
const shinyThreshold = new Utils.IntegerHolder(WONDER_TRADE_SHINY_CHANCE);
if (scene.eventManager.isEventActive()) {
shinyThreshold.value *= scene.eventManager.getShinyMultiplier();
if (gScene.eventManager.isEventActive()) {
shinyThreshold.value *= gScene.eventManager.getShinyMultiplier();
}
scene.applyModifiers(ShinyRateBoosterModifier, true, shinyThreshold);
gScene.applyModifiers(ShinyRateBoosterModifier, true, shinyThreshold);
// Base shiny chance of 512/65536 -> 1/128, affected by events and Shiny Charms
// Maximum shiny chance of 4096/65536 -> 1/16, cannot improve further after that
@ -246,7 +246,7 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
if (tradePokemon.species.abilityHidden) {
if (tradePokemon.abilityIndex < hiddenIndex) {
const hiddenAbilityChance = new IntegerHolder(64);
scene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance);
gScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance);
const hasHiddenAbility = !randSeedInt(hiddenAbilityChance.value);
@ -279,10 +279,10 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
encounter.misc.receivedPokemon = tradePokemon;
};
return selectPokemonForOption(scene, onPokemonSelected);
return selectPokemonForOption(onPokemonSelected);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const tradedPokemon: PlayerPokemon = encounter.misc.tradedPokemon;
const receivedPokemonData: EnemyPokemon = encounter.misc.receivedPokemon;
const modifiers = tradedPokemon.getHeldItems().filter(m => !(m instanceof PokemonFormChangeItemModifier) && !(m instanceof SpeciesStatBoosterModifier));
@ -292,31 +292,31 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
encounter.setDialogueToken("tradeTrainerName", traderName.trim());
// Remove the original party member from party
scene.removePokemonFromPlayerParty(tradedPokemon, false);
gScene.removePokemonFromPlayerParty(tradedPokemon, false);
// Set data properly, then generate the new Pokemon's assets
receivedPokemonData.passive = tradedPokemon.passive;
receivedPokemonData.pokeball = randInt(4) as PokeballType;
const dataSource = new PokemonData(receivedPokemonData);
const newPlayerPokemon = scene.addPlayerPokemon(receivedPokemonData.species, receivedPokemonData.level, dataSource.abilityIndex, dataSource.formIndex, dataSource.gender, dataSource.shiny, dataSource.variant, dataSource.ivs, dataSource.nature, dataSource);
scene.getParty().push(newPlayerPokemon);
const newPlayerPokemon = gScene.addPlayerPokemon(receivedPokemonData.species, receivedPokemonData.level, dataSource.abilityIndex, dataSource.formIndex, dataSource.gender, dataSource.shiny, dataSource.variant, dataSource.ivs, dataSource.nature, dataSource);
gScene.getParty().push(newPlayerPokemon);
await newPlayerPokemon.loadAssets();
for (const mod of modifiers) {
mod.pokemonId = newPlayerPokemon.id;
scene.addModifier(mod, true, false, false, true);
gScene.addModifier(mod, true, false, false, true);
}
// Show the trade animation
await showTradeBackground(scene);
await doPokemonTradeSequence(scene, tradedPokemon, newPlayerPokemon);
await showEncounterText(scene, `${namespace}:trade_received`, null, 0, true, 4000);
scene.playBgm(encounter.misc.bgmKey);
await addPokemonDataToDexAndValidateAchievements(scene, newPlayerPokemon);
await hideTradeBackground(scene);
await showTradeBackground();
await doPokemonTradeSequence(tradedPokemon, newPlayerPokemon);
await showEncounterText(`${namespace}:trade_received`, null, 0, true, 4000);
gScene.playBgm(encounter.misc.bgmKey);
await addPokemonDataToDexAndValidateAchievements(newPlayerPokemon);
await hideTradeBackground();
tradedPokemon.destroy();
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -328,8 +328,8 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
buttonTooltip: `${namespace}:option.3.tooltip`,
secondOptionPrompt: `${namespace}:option.3.trade_options_prompt`,
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Get Pokemon held items and filter for valid ones
const validItems = pokemon.getHeldItems().filter((it) => {
@ -356,16 +356,16 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
return it.isTransferable;
}).length > 0;
if (!meetsReqs) {
return getEncounterText(scene, `${namespace}:option.3.invalid_selection`) ?? null;
return getEncounterText(`${namespace}:option.3.invalid_selection`) ?? null;
}
return null;
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const modifier = encounter.misc.chosenModifier;
// Check tier of the traded item, the received item will be one tier up
@ -384,28 +384,28 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
tier++;
}
regenerateModifierPoolThresholds(scene.getParty(), ModifierPoolType.PLAYER, 0);
regenerateModifierPoolThresholds(gScene.getParty(), ModifierPoolType.PLAYER, 0);
let item: ModifierTypeOption | null = null;
// TMs excluded from possible rewards
while (!item || item.type.id.includes("TM_")) {
item = getPlayerModifierTypeOptions(1, scene.getParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0];
item = getPlayerModifierTypeOptions(1, gScene.getParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0];
}
encounter.setDialogueToken("itemName", item.type.name);
setEncounterRewards(scene, { guaranteedModifierTypeOptions: [ item ], fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeOptions: [ item ], fillRemaining: false });
// Remove the chosen modifier if its stacks go to 0
modifier.stackCount -= 1;
if (modifier.stackCount === 0) {
scene.removeModifier(modifier);
gScene.removeModifier(modifier);
}
await scene.updateModifiers(true, true);
await gScene.updateModifiers(true, true);
// Generate a trainer name
const traderName = generateRandomTraderName();
encounter.setDialogueToken("tradeTrainerName", traderName.trim());
await showEncounterText(scene, `${namespace}:item_trade_selected`);
leaveEncounterWithoutBattle(scene);
await showEncounterText(`${namespace}:item_trade_selected`);
leaveEncounterWithoutBattle();
})
.build()
)
@ -419,26 +419,26 @@ export const GlobalTradeSystemEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)
.build();
function getPokemonTradeOptions(scene: BattleScene): Map<number, EnemyPokemon[]> {
function getPokemonTradeOptions(): Map<number, EnemyPokemon[]> {
const tradeOptionsMap: Map<number, EnemyPokemon[]> = new Map<number, EnemyPokemon[]>();
// Starts by filtering out any current party members as valid resulting species
const alreadyUsedSpecies: PokemonSpecies[] = scene.getParty().map(p => p.species);
const alreadyUsedSpecies: PokemonSpecies[] = gScene.getParty().map(p => p.species);
scene.getParty().forEach(pokemon => {
gScene.getParty().forEach(pokemon => {
// If the party member is legendary/mythical, the only trade options available are always pulled from generation-specific legendary trade pools
if (pokemon.species.legendary || pokemon.species.subLegendary || pokemon.species.mythical) {
const generation = pokemon.species.generation;
const tradeOptions: EnemyPokemon[] = LEGENDARY_TRADE_POOLS[generation].map(s => {
const pokemonSpecies = getPokemonSpecies(s);
return new EnemyPokemon(scene, pokemonSpecies, 5, TrainerSlot.NONE, false);
return new EnemyPokemon(pokemonSpecies, 5, TrainerSlot.NONE, false);
});
tradeOptionsMap.set(pokemon.id, tradeOptions);
} else {
@ -453,7 +453,7 @@ function getPokemonTradeOptions(scene: BattleScene): Map<number, EnemyPokemon[]>
// Add trade options to map
tradeOptionsMap.set(pokemon.id, tradeOptions.map(s => {
return new EnemyPokemon(scene, s, pokemon.level, TrainerSlot.NONE, false);
return new EnemyPokemon(s, pokemon.level, TrainerSlot.NONE, false);
}));
}
});
@ -496,28 +496,28 @@ function generateTradeOption(alreadyUsedSpecies: PokemonSpecies[], originalBst?:
return newSpecies!;
}
function showTradeBackground(scene: BattleScene) {
function showTradeBackground() {
return new Promise<void>(resolve => {
const tradeContainer = scene.add.container(0, -scene.game.canvas.height / 6);
const tradeContainer = gScene.add.container(0, -gScene.game.canvas.height / 6);
tradeContainer.setName("Trade Background");
const flyByStaticBg = scene.add.rectangle(0, 0, scene.game.canvas.width / 6, scene.game.canvas.height / 6, 0);
const flyByStaticBg = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0);
flyByStaticBg.setName("Black Background");
flyByStaticBg.setOrigin(0, 0);
flyByStaticBg.setVisible(false);
tradeContainer.add(flyByStaticBg);
const tradeBaseBg = scene.add.image(0, 0, "default_bg");
const tradeBaseBg = gScene.add.image(0, 0, "default_bg");
tradeBaseBg.setName("Trade Background Image");
tradeBaseBg.setOrigin(0, 0);
tradeContainer.add(tradeBaseBg);
scene.fieldUI.add(tradeContainer);
scene.fieldUI.bringToTop(tradeContainer);
gScene.fieldUI.add(tradeContainer);
gScene.fieldUI.bringToTop(tradeContainer);
tradeContainer.setVisible(true);
tradeContainer.alpha = 0;
scene.tweens.add({
gScene.tweens.add({
targets: tradeContainer,
alpha: 1,
duration: 500,
@ -529,17 +529,17 @@ function showTradeBackground(scene: BattleScene) {
});
}
function hideTradeBackground(scene: BattleScene) {
function hideTradeBackground() {
return new Promise<void>(resolve => {
const transformationContainer = scene.fieldUI.getByName("Trade Background");
const transformationContainer = gScene.fieldUI.getByName("Trade Background");
scene.tweens.add({
gScene.tweens.add({
targets: transformationContainer,
alpha: 0,
duration: 1000,
ease: "Sine.easeInOut",
onComplete: () => {
scene.fieldUI.remove(transformationContainer, true);
gScene.fieldUI.remove(transformationContainer, true);
resolve();
}
});
@ -552,9 +552,9 @@ function hideTradeBackground(scene: BattleScene) {
* @param tradedPokemon
* @param receivedPokemon
*/
function doPokemonTradeSequence(scene: BattleScene, tradedPokemon: PlayerPokemon, receivedPokemon: PlayerPokemon) {
function doPokemonTradeSequence(tradedPokemon: PlayerPokemon, receivedPokemon: PlayerPokemon) {
return new Promise<void>(resolve => {
const tradeContainer = scene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container;
const tradeContainer = gScene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container;
const tradeBaseBg = tradeContainer.getByName("Trade Background Image") as Phaser.GameObjects.Image;
let tradedPokemonSprite: Phaser.GameObjects.Sprite;
@ -563,8 +563,8 @@ function doPokemonTradeSequence(scene: BattleScene, tradedPokemon: PlayerPokemon
let receivedPokemonTintSprite: Phaser.GameObjects.Sprite;
const getPokemonSprite = () => {
const ret = scene.addPokemonSprite(tradedPokemon, tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pkmn__sub");
ret.setPipeline(scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true });
const ret = gScene.addPokemonSprite(tradedPokemon, tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pkmn__sub");
ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true });
return ret;
};
@ -582,7 +582,7 @@ function doPokemonTradeSequence(scene: BattleScene, tradedPokemon: PlayerPokemon
[ tradedPokemonSprite, tradedPokemonTintSprite ].map(sprite => {
sprite.play(tradedPokemon.getSpriteKey(true));
sprite.setPipeline(scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(tradedPokemon.getTeraType()) });
sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(tradedPokemon.getTeraType()) });
sprite.setPipelineData("ignoreTimeTint", true);
sprite.setPipelineData("spriteKey", tradedPokemon.getSpriteKey());
sprite.setPipelineData("shiny", tradedPokemon.shiny);
@ -597,7 +597,7 @@ function doPokemonTradeSequence(scene: BattleScene, tradedPokemon: PlayerPokemon
[ receivedPokemonSprite, receivedPokemonTintSprite ].map(sprite => {
sprite.play(receivedPokemon.getSpriteKey(true));
sprite.setPipeline(scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(tradedPokemon.getTeraType()) });
sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(tradedPokemon.getTeraType()) });
sprite.setPipelineData("ignoreTimeTint", true);
sprite.setPipelineData("spriteKey", receivedPokemon.getSpriteKey());
sprite.setPipelineData("shiny", receivedPokemon.shiny);
@ -612,45 +612,45 @@ function doPokemonTradeSequence(scene: BattleScene, tradedPokemon: PlayerPokemon
// Traded pokemon pokeball
const tradedPbAtlasKey = getPokeballAtlasKey(tradedPokemon.pokeball);
const tradedPokeball: Phaser.GameObjects.Sprite = scene.add.sprite(tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pb", tradedPbAtlasKey);
const tradedPokeball: Phaser.GameObjects.Sprite = gScene.add.sprite(tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pb", tradedPbAtlasKey);
tradedPokeball.setVisible(false);
tradeContainer.add(tradedPokeball);
// Received pokemon pokeball
const receivedPbAtlasKey = getPokeballAtlasKey(receivedPokemon.pokeball);
const receivedPokeball: Phaser.GameObjects.Sprite = scene.add.sprite(tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pb", receivedPbAtlasKey);
const receivedPokeball: Phaser.GameObjects.Sprite = gScene.add.sprite(tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pb", receivedPbAtlasKey);
receivedPokeball.setVisible(false);
tradeContainer.add(receivedPokeball);
scene.tweens.add({
gScene.tweens.add({
targets: tradedPokemonSprite,
alpha: 1,
ease: "Cubic.easeInOut",
duration: 500,
onComplete: async () => {
scene.fadeOutBgm(1000, false);
await showEncounterText(scene, `${namespace}:pokemon_trade_selected`);
gScene.fadeOutBgm(1000, false);
await showEncounterText(`${namespace}:pokemon_trade_selected`);
tradedPokemon.cry();
scene.playBgm("evolution");
await showEncounterText(scene, `${namespace}:pokemon_trade_goodbye`);
gScene.playBgm("evolution");
await showEncounterText(`${namespace}:pokemon_trade_goodbye`);
tradedPokeball.setAlpha(0);
tradedPokeball.setVisible(true);
scene.tweens.add({
gScene.tweens.add({
targets: tradedPokeball,
alpha: 1,
ease: "Cubic.easeInOut",
duration: 250,
onComplete: () => {
tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}_opening`);
scene.time.delayedCall(17, () => tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}_open`));
scene.playSound("se/pb_rel");
gScene.time.delayedCall(17, () => tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}_open`));
gScene.playSound("se/pb_rel");
tradedPokemonTintSprite.setVisible(true);
// TODO: need to add particles to fieldUI instead of field
// addPokeballOpenParticles(scene, tradedPokemon.x, tradedPokemon.y, tradedPokemon.pokeball);
// addPokeballOpenParticles(tradedPokemon.x, tradedPokemon.y, tradedPokemon.pokeball);
scene.tweens.add({
gScene.tweens.add({
targets: [ tradedPokemonTintSprite, tradedPokemonSprite ],
duration: 500,
ease: "Sine.easeIn",
@ -659,30 +659,30 @@ function doPokemonTradeSequence(scene: BattleScene, tradedPokemon: PlayerPokemon
tradedPokemonSprite.setVisible(false);
tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}_opening`);
tradedPokemonTintSprite.setVisible(false);
scene.playSound("se/pb_catch");
scene.time.delayedCall(17, () => tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}`));
gScene.playSound("se/pb_catch");
gScene.time.delayedCall(17, () => tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}`));
scene.tweens.add({
gScene.tweens.add({
targets: tradedPokeball,
y: "+=10",
duration: 200,
delay: 250,
ease: "Cubic.easeIn",
onComplete: () => {
scene.playSound("se/pb_bounce_1");
gScene.playSound("se/pb_bounce_1");
scene.tweens.add({
gScene.tweens.add({
targets: tradedPokeball,
y: "-=100",
duration: 200,
delay: 1000,
ease: "Cubic.easeInOut",
onStart: () => {
scene.playSound("se/pb_throw");
gScene.playSound("se/pb_throw");
},
onComplete: async () => {
await doPokemonTradeFlyBySequence(scene, tradedPokemonSprite, receivedPokemonSprite);
await doTradeReceivedSequence(scene, receivedPokemon, receivedPokemonSprite, receivedPokemonTintSprite, receivedPokeball, receivedPbAtlasKey);
await doPokemonTradeFlyBySequence(tradedPokemonSprite, receivedPokemonSprite);
await doTradeReceivedSequence(receivedPokemon, receivedPokemonSprite, receivedPokemonTintSprite, receivedPokeball, receivedPbAtlasKey);
resolve();
}
});
@ -697,9 +697,9 @@ function doPokemonTradeSequence(scene: BattleScene, tradedPokemon: PlayerPokemon
});
}
function doPokemonTradeFlyBySequence(scene: BattleScene, tradedPokemonSprite: Phaser.GameObjects.Sprite, receivedPokemonSprite: Phaser.GameObjects.Sprite) {
function doPokemonTradeFlyBySequence(tradedPokemonSprite: Phaser.GameObjects.Sprite, receivedPokemonSprite: Phaser.GameObjects.Sprite) {
return new Promise<void>(resolve => {
const tradeContainer = scene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container;
const tradeContainer = gScene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container;
const tradeBaseBg = tradeContainer.getByName("Trade Background Image") as Phaser.GameObjects.Image;
const flyByStaticBg = tradeContainer.getByName("Black Background") as Phaser.GameObjects.Rectangle;
flyByStaticBg.setVisible(true);
@ -720,47 +720,47 @@ function doPokemonTradeFlyBySequence(scene: BattleScene, tradedPokemonSprite: Ph
const BASE_ANIM_DURATION = 1000;
// Fade out trade background
scene.tweens.add({
gScene.tweens.add({
targets: tradeBaseBg,
alpha: 0,
ease: "Cubic.easeInOut",
duration: FADE_DELAY,
onComplete: () => {
scene.tweens.add({
gScene.tweens.add({
targets: [ receivedPokemonSprite, tradedPokemonSprite ],
y: tradeBaseBg.displayWidth / 2 - 100,
ease: "Cubic.easeInOut",
duration: BASE_ANIM_DURATION * 3,
onComplete: () => {
scene.tweens.add({
gScene.tweens.add({
targets: receivedPokemonSprite,
x: tradeBaseBg.displayWidth / 4,
ease: "Cubic.easeInOut",
duration: BASE_ANIM_DURATION / 2,
delay: ANIM_DELAY
});
scene.tweens.add({
gScene.tweens.add({
targets: tradedPokemonSprite,
x: tradeBaseBg.displayWidth * 3 / 4,
ease: "Cubic.easeInOut",
duration: BASE_ANIM_DURATION / 2,
delay: ANIM_DELAY,
onComplete: () => {
scene.tweens.add({
gScene.tweens.add({
targets: receivedPokemonSprite,
y: "+=200",
ease: "Cubic.easeInOut",
duration: BASE_ANIM_DURATION * 2,
delay: ANIM_DELAY,
});
scene.tweens.add({
gScene.tweens.add({
targets: tradedPokemonSprite,
y: "-=200",
ease: "Cubic.easeInOut",
duration: BASE_ANIM_DURATION * 2,
delay: ANIM_DELAY,
onComplete: () => {
scene.tweens.add({
gScene.tweens.add({
targets: tradeBaseBg,
alpha: 1,
ease: "Cubic.easeInOut",
@ -780,9 +780,9 @@ function doPokemonTradeFlyBySequence(scene: BattleScene, tradedPokemonSprite: Ph
});
}
function doTradeReceivedSequence(scene: BattleScene, receivedPokemon: PlayerPokemon, receivedPokemonSprite: Phaser.GameObjects.Sprite, receivedPokemonTintSprite: Phaser.GameObjects.Sprite, receivedPokeballSprite: Phaser.GameObjects.Sprite, receivedPbAtlasKey: string) {
function doTradeReceivedSequence(receivedPokemon: PlayerPokemon, receivedPokemonSprite: Phaser.GameObjects.Sprite, receivedPokemonTintSprite: Phaser.GameObjects.Sprite, receivedPokeballSprite: Phaser.GameObjects.Sprite, receivedPbAtlasKey: string) {
return new Promise<void>(resolve => {
const tradeContainer = scene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container;
const tradeContainer = gScene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container;
const tradeBaseBg = tradeContainer.getByName("Trade Background Image") as Phaser.GameObjects.Image;
receivedPokemonSprite.setVisible(false);
@ -799,19 +799,19 @@ function doTradeReceivedSequence(scene: BattleScene, receivedPokemon: PlayerPoke
const BASE_ANIM_DURATION = 1000;
// Pokeball falls to the screen
scene.playSound("se/pb_throw");
scene.tweens.add({
gScene.playSound("se/pb_throw");
gScene.tweens.add({
targets: receivedPokeballSprite,
y: "+=100",
ease: "Cubic.easeInOut",
duration: BASE_ANIM_DURATION,
onComplete: () => {
scene.playSound("se/pb_bounce_1");
scene.time.delayedCall(100, () => scene.playSound("se/pb_bounce_1"));
gScene.playSound("se/pb_bounce_1");
gScene.time.delayedCall(100, () => gScene.playSound("se/pb_bounce_1"));
scene.time.delayedCall(2000, () => {
scene.playSound("se/pb_rel");
scene.fadeOutBgm(500, false);
gScene.time.delayedCall(2000, () => {
gScene.playSound("se/pb_rel");
gScene.fadeOutBgm(500, false);
receivedPokemon.cry();
receivedPokemonTintSprite.scale = 0.25;
receivedPokemonTintSprite.alpha = 1;
@ -820,14 +820,14 @@ function doTradeReceivedSequence(scene: BattleScene, receivedPokemon: PlayerPoke
receivedPokemonTintSprite.alpha = 1;
receivedPokemonTintSprite.setVisible(true);
receivedPokeballSprite.setTexture("pb", `${receivedPbAtlasKey}_opening`);
scene.time.delayedCall(17, () => receivedPokeballSprite.setTexture("pb", `${receivedPbAtlasKey}_open`));
scene.tweens.add({
gScene.time.delayedCall(17, () => receivedPokeballSprite.setTexture("pb", `${receivedPbAtlasKey}_open`));
gScene.tweens.add({
targets: receivedPokemonSprite,
duration: 250,
ease: "Sine.easeOut",
scale: 1
});
scene.tweens.add({
gScene.tweens.add({
targets: receivedPokemonTintSprite,
duration: 250,
ease: "Sine.easeOut",
@ -835,7 +835,7 @@ function doTradeReceivedSequence(scene: BattleScene, receivedPokemon: PlayerPoke
alpha: 0,
onComplete: () => {
receivedPokeballSprite.destroy();
scene.time.delayedCall(2000, () => resolve());
gScene.time.delayedCall(2000, () => resolve());
}
});
});

View File

@ -2,7 +2,7 @@ import { getPokemonSpecies } from "#app/data/pokemon-species";
import { Moves } from "#app/enums/moves";
import { Species } from "#app/enums/species";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { leaveEncounterWithoutBattle, setEncounterExp } from "../utils/encounter-phase-utils";
@ -41,8 +41,8 @@ export const LostAtSeaEncounter: MysteryEncounter = MysteryEncounterBuilder.with
},
])
.withIntroDialogue([{ text: `${namespace}:intro` }])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
encounter.setDialogueToken("damagePercentage", String(DAMAGE_PERCENTAGE));
encounter.setDialogueToken("option1RequiredMove", new PokemonMove(OPTION_1_REQUIRED_MOVE).getName());
@ -70,7 +70,7 @@ export const LostAtSeaEncounter: MysteryEncounter = MysteryEncounterBuilder.with
},
],
})
.withOptionPhase(async (scene: BattleScene) => handlePokemonGuidingYouPhase(scene))
.withOptionPhase(async () => handlePokemonGuidingYouPhase())
.build()
)
.withOption(
@ -89,7 +89,7 @@ export const LostAtSeaEncounter: MysteryEncounter = MysteryEncounterBuilder.with
},
],
})
.withOptionPhase(async (scene: BattleScene) => handlePokemonGuidingYouPhase(scene))
.withOptionPhase(async () => handlePokemonGuidingYouPhase())
.build()
)
.withSimpleOption(
@ -103,16 +103,16 @@ export const LostAtSeaEncounter: MysteryEncounter = MysteryEncounterBuilder.with
},
],
},
async (scene: BattleScene) => {
const allowedPokemon = scene.getParty().filter((p) => p.isAllowedInBattle());
async () => {
const allowedPokemon = gScene.getParty().filter((p) => p.isAllowedInBattle());
for (const pkm of allowedPokemon) {
const percentage = DAMAGE_PERCENTAGE / 100;
const damage = Math.floor(pkm.getMaxHp() * percentage);
applyDamageToPokemon(scene, pkm, damage);
applyDamageToPokemon(pkm, damage);
}
leaveEncounterWithoutBattle(scene);
leaveEncounterWithoutBattle();
return true;
}
@ -129,16 +129,16 @@ export const LostAtSeaEncounter: MysteryEncounter = MysteryEncounterBuilder.with
*
* @param scene Battle scene
*/
function handlePokemonGuidingYouPhase(scene: BattleScene) {
function handlePokemonGuidingYouPhase() {
const laprasSpecies = getPokemonSpecies(Species.LAPRAS);
const { mysteryEncounter } = scene.currentBattle;
const { mysteryEncounter } = gScene.currentBattle;
if (mysteryEncounter?.selectedOption?.primaryPokemon?.id) {
setEncounterExp(scene, mysteryEncounter.selectedOption.primaryPokemon.id, laprasSpecies.baseExp, true);
setEncounterExp(mysteryEncounter.selectedOption.primaryPokemon.id, laprasSpecies.baseExp, true);
} else {
console.warn("Lost at sea: No guide pokemon found but pokemon guides player. huh!?");
}
leaveEncounterWithoutBattle(scene);
leaveEncounterWithoutBattle();
return true;
}

View File

@ -13,7 +13,7 @@ import { ModifierTier } from "#app/modifier/modifier-tier";
import { modifierTypes } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { PartyMemberStrength } from "#enums/party-member-strength";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import * as Utils from "#app/utils";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -37,12 +37,12 @@ export const MysteriousChallengersEncounter: MysteryEncounter =
text: `${namespace}:intro`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculates what trainers are available for battle in the encounter
// Normal difficulty trainer is randomly pulled from biome
const normalTrainerType = scene.arena.randomTrainerType(scene.currentBattle.waveIndex);
const normalTrainerType = gScene.arena.randomTrainerType(gScene.currentBattle.waveIndex);
const normalConfig = trainerConfigs[normalTrainerType].clone();
let female = false;
if (normalConfig.hasGenders) {
@ -57,16 +57,16 @@ export const MysteriousChallengersEncounter: MysteryEncounter =
// Hard difficulty trainer is another random trainer, but with AVERAGE_BALANCED config
// Number of mons is based off wave: 1-20 is 2, 20-40 is 3, etc. capping at 6 after wave 100
let retries = 0;
let hardTrainerType = scene.arena.randomTrainerType(scene.currentBattle.waveIndex);
let hardTrainerType = gScene.arena.randomTrainerType(gScene.currentBattle.waveIndex);
while (retries < 5 && hardTrainerType === normalTrainerType) {
// Will try to use a different trainer from the normal trainer type
hardTrainerType = scene.arena.randomTrainerType(scene.currentBattle.waveIndex);
hardTrainerType = gScene.arena.randomTrainerType(gScene.currentBattle.waveIndex);
retries++;
}
const hardTemplate = new TrainerPartyCompoundTemplate(
new TrainerPartyTemplate(1, PartyMemberStrength.STRONGER, false, true),
new TrainerPartyTemplate(
Math.min(Math.ceil(scene.currentBattle.waveIndex / 20), 5),
Math.min(Math.ceil(gScene.currentBattle.waveIndex / 20), 5),
PartyMemberStrength.AVERAGE,
false,
true
@ -87,8 +87,8 @@ export const MysteriousChallengersEncounter: MysteryEncounter =
// Brutal trainer is pulled from pool of boss trainers (gym leaders) for the biome
// They are given an E4 template team, so will be stronger than usual boss encounter and always have 6 mons
const brutalTrainerType = scene.arena.randomTrainerType(
scene.currentBattle.waveIndex,
const brutalTrainerType = gScene.arena.randomTrainerType(
gScene.currentBattle.waveIndex,
true
);
const e4Template = trainerPartyTemplates.ELITE_FOUR;
@ -145,18 +145,18 @@ export const MysteriousChallengersEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Spawn standard trainer battle with memory mushroom reward
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0];
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.TM_COMMON, modifierTypes.TM_GREAT, modifierTypes.MEMORY_MUSHROOM ], fillRemaining: true });
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.TM_COMMON, modifierTypes.TM_GREAT, modifierTypes.MEMORY_MUSHROOM ], fillRemaining: true });
// Seed offsets to remove possibility of different trainers having exact same teams
let initBattlePromise: Promise<void>;
scene.executeWithSeedOffset(() => {
initBattlePromise = initBattleWithEnemyConfig(scene, config);
}, scene.currentBattle.waveIndex * 10);
gScene.executeWithSeedOffset(() => {
initBattlePromise = initBattleWithEnemyConfig(config);
}, gScene.currentBattle.waveIndex * 10);
await initBattlePromise!;
}
)
@ -170,18 +170,18 @@ export const MysteriousChallengersEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Spawn hard fight
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[1];
setEncounterRewards(scene, { guaranteedModifierTiers: [ ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.GREAT, ModifierTier.GREAT ], fillRemaining: true });
setEncounterRewards({ guaranteedModifierTiers: [ ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.GREAT, ModifierTier.GREAT ], fillRemaining: true });
// Seed offsets to remove possibility of different trainers having exact same teams
let initBattlePromise: Promise<void>;
scene.executeWithSeedOffset(() => {
initBattlePromise = initBattleWithEnemyConfig(scene, config);
}, scene.currentBattle.waveIndex * 100);
gScene.executeWithSeedOffset(() => {
initBattlePromise = initBattleWithEnemyConfig(config);
}, gScene.currentBattle.waveIndex * 100);
await initBattlePromise!;
}
)
@ -195,21 +195,21 @@ export const MysteriousChallengersEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Spawn brutal fight
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[2];
// To avoid player level snowballing from picking this option
encounter.expMultiplier = 0.9;
setEncounterRewards(scene, { guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.GREAT ], fillRemaining: true });
setEncounterRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.GREAT ], fillRemaining: true });
// Seed offsets to remove possibility of different trainers having exact same teams
let initBattlePromise: Promise<void>;
scene.executeWithSeedOffset(() => {
initBattlePromise = initBattleWithEnemyConfig(scene, config);
}, scene.currentBattle.waveIndex * 1000);
gScene.executeWithSeedOffset(() => {
initBattlePromise = initBattleWithEnemyConfig(config);
}, gScene.currentBattle.waveIndex * 1000);
await initBattlePromise!;
}
)

View File

@ -4,7 +4,7 @@ import { getHighestLevelPlayerPokemon, koPlayerPokemon } from "#app/data/mystery
import { ModifierTier } from "#app/modifier/modifier-tier";
import { randSeedInt } from "#app/utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -65,8 +65,8 @@ export const MysteriousChestEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculate boss mon
const config: EnemyPartyConfig = {
@ -105,9 +105,9 @@ export const MysteriousChestEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Play animation
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const introVisuals = encounter.introVisuals!;
// Determine roll first
@ -127,13 +127,13 @@ export const MysteriousChestEncounter: MysteryEncounter =
introVisuals.spriteConfigs[1].disableAnimation = false;
introVisuals.playAnim();
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Open the chest
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const roll = encounter.misc.roll;
if (roll >= RAND_LENGTH - COMMON_REWARDS_PERCENT) {
// Choose between 2 COMMON / 2 GREAT tier items (20%)
setEncounterRewards(scene, {
setEncounterRewards({
guaranteedModifierTiers: [
ModifierTier.COMMON,
ModifierTier.COMMON,
@ -142,11 +142,11 @@ export const MysteriousChestEncounter: MysteryEncounter =
],
});
// Display result message then proceed to rewards
queueEncounterMessage(scene, `${namespace}:option.1.normal`);
leaveEncounterWithoutBattle(scene);
queueEncounterMessage(`${namespace}:option.1.normal`);
leaveEncounterWithoutBattle();
} else if (roll >= RAND_LENGTH - COMMON_REWARDS_PERCENT - ULTRA_REWARDS_PERCENT) {
// Choose between 3 ULTRA tier items (30%)
setEncounterRewards(scene, {
setEncounterRewards({
guaranteedModifierTiers: [
ModifierTier.ULTRA,
ModifierTier.ULTRA,
@ -154,39 +154,39 @@ export const MysteriousChestEncounter: MysteryEncounter =
],
});
// Display result message then proceed to rewards
queueEncounterMessage(scene, `${namespace}:option.1.good`);
leaveEncounterWithoutBattle(scene);
queueEncounterMessage(`${namespace}:option.1.good`);
leaveEncounterWithoutBattle();
} else if (roll >= RAND_LENGTH - COMMON_REWARDS_PERCENT - ULTRA_REWARDS_PERCENT - ROGUE_REWARDS_PERCENT) {
// Choose between 2 ROGUE tier items (10%)
setEncounterRewards(scene, { guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE ]});
setEncounterRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE ]});
// Display result message then proceed to rewards
queueEncounterMessage(scene, `${namespace}:option.1.great`);
leaveEncounterWithoutBattle(scene);
queueEncounterMessage(`${namespace}:option.1.great`);
leaveEncounterWithoutBattle();
} else if (roll >= RAND_LENGTH - COMMON_REWARDS_PERCENT - ULTRA_REWARDS_PERCENT - ROGUE_REWARDS_PERCENT - MASTER_REWARDS_PERCENT) {
// Choose 1 MASTER tier item (5%)
setEncounterRewards(scene, { guaranteedModifierTiers: [ ModifierTier.MASTER ]});
setEncounterRewards({ guaranteedModifierTiers: [ ModifierTier.MASTER ]});
// Display result message then proceed to rewards
queueEncounterMessage(scene, `${namespace}:option.1.amazing`);
leaveEncounterWithoutBattle(scene);
queueEncounterMessage(`${namespace}:option.1.amazing`);
leaveEncounterWithoutBattle();
} else {
// Your highest level unfainted Pokemon gets OHKO. Start battle against a Gimmighoul (35%)
const highestLevelPokemon = getHighestLevelPlayerPokemon(scene, true, false);
koPlayerPokemon(scene, highestLevelPokemon);
const highestLevelPokemon = getHighestLevelPlayerPokemon(true, false);
koPlayerPokemon(highestLevelPokemon);
encounter.setDialogueToken("pokeName", highestLevelPokemon.getNameToRender());
await showEncounterText(scene, `${namespace}:option.1.bad`);
await showEncounterText(`${namespace}:option.1.bad`);
// Handle game over edge case
const allowedPokemon = scene.getParty().filter(p => p.isAllowedInBattle());
const allowedPokemon = gScene.getParty().filter(p => p.isAllowedInBattle());
if (allowedPokemon.length === 0) {
// If there are no longer any legal pokemon in the party, game over.
scene.clearPhaseQueue();
scene.unshiftPhase(new GameOverPhase(scene));
gScene.clearPhaseQueue();
gScene.unshiftPhase(new GameOverPhase());
} else {
// Show which Pokemon was KOed, then start battle against Gimmighoul
await transitionMysteryEncounterIntroVisuals(scene, true, true, 500);
setEncounterRewards(scene, { fillRemaining: true });
await initBattleWithEnemyConfig(scene, encounter.enemyPartyConfigs[0]);
await transitionMysteryEncounterIntroVisuals(true, true, 500);
setEncounterRewards({ fillRemaining: true });
await initBattleWithEnemyConfig(encounter.enemyPartyConfigs[0]);
}
}
})
@ -202,9 +202,9 @@ export const MysteriousChestEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)

View File

@ -1,7 +1,7 @@
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { leaveEncounterWithoutBattle, selectPokemonForOption, setEncounterExp, setEncounterRewards, transitionMysteryEncounterIntroVisuals, updatePlayerMoney } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MoveRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -52,20 +52,20 @@ export const PartTimerEncounter: MysteryEncounter =
text: `${namespace}:intro_dialogue`,
},
])
.withOnInit((scene: BattleScene) => {
.withOnInit(() => {
// Load sfx
scene.loadSe("PRSFX- Horn Drill1", "battle_anims", "PRSFX- Horn Drill1.wav");
scene.loadSe("PRSFX- Horn Drill3", "battle_anims", "PRSFX- Horn Drill3.wav");
scene.loadSe("PRSFX- Guillotine2", "battle_anims", "PRSFX- Guillotine2.wav");
scene.loadSe("PRSFX- Heavy Slam2", "battle_anims", "PRSFX- Heavy Slam2.wav");
gScene.loadSe("PRSFX- Horn Drill1", "battle_anims", "PRSFX- Horn Drill1.wav");
gScene.loadSe("PRSFX- Horn Drill3", "battle_anims", "PRSFX- Horn Drill3.wav");
gScene.loadSe("PRSFX- Guillotine2", "battle_anims", "PRSFX- Guillotine2.wav");
gScene.loadSe("PRSFX- Heavy Slam2", "battle_anims", "PRSFX- Heavy Slam2.wav");
scene.loadSe("PRSFX- Agility", "battle_anims", "PRSFX- Agility.wav");
scene.loadSe("PRSFX- Extremespeed1", "battle_anims", "PRSFX- Extremespeed1.wav");
scene.loadSe("PRSFX- Accelerock1", "battle_anims", "PRSFX- Accelerock1.wav");
gScene.loadSe("PRSFX- Agility", "battle_anims", "PRSFX- Agility.wav");
gScene.loadSe("PRSFX- Extremespeed1", "battle_anims", "PRSFX- Extremespeed1.wav");
gScene.loadSe("PRSFX- Accelerock1", "battle_anims", "PRSFX- Accelerock1.wav");
scene.loadSe("PRSFX- Captivate", "battle_anims", "PRSFX- Captivate.wav");
scene.loadSe("PRSFX- Attract2", "battle_anims", "PRSFX- Attract2.wav");
scene.loadSe("PRSFX- Aurora Veil2", "battle_anims", "PRSFX- Aurora Veil2.wav");
gScene.loadSe("PRSFX- Captivate", "battle_anims", "PRSFX- Captivate.wav");
gScene.loadSe("PRSFX- Attract2", "battle_anims", "PRSFX- Attract2.wav");
gScene.loadSe("PRSFX- Aurora Veil2", "battle_anims", "PRSFX- Aurora Veil2.wav");
return true;
})
@ -84,8 +84,8 @@ export const PartTimerEncounter: MysteryEncounter =
}
]
})
.withPreOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
encounter.setDialogueToken("selectedPokemon", pokemon.getNameToRender());
@ -109,41 +109,41 @@ export const PartTimerEncounter: MysteryEncounter =
}
});
setEncounterExp(scene, pokemon.id, 100);
setEncounterExp(pokemon.id, 100);
// Hide intro visuals
transitionMysteryEncounterIntroVisuals(scene, true, false);
transitionMysteryEncounterIntroVisuals(true, false);
// Play sfx for "working"
doDeliverySfx(scene);
doDeliverySfx();
};
// Only Pokemon non-KOd pokemon can be selected
const selectableFilter = (pokemon: Pokemon) => {
return isPokemonValidForEncounterOptionSelection(pokemon, scene, `${namespace}:invalid_selection`);
return isPokemonValidForEncounterOptionSelection(pokemon, `${namespace}:invalid_selection`);
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Pick Deliveries
// Bring visuals back in
await transitionMysteryEncounterIntroVisuals(scene, false, false);
await transitionMysteryEncounterIntroVisuals(false, false);
const moneyMultiplier = scene.currentBattle.mysteryEncounter!.misc.moneyMultiplier;
const moneyMultiplier = gScene.currentBattle.mysteryEncounter!.misc.moneyMultiplier;
// Give money and do dialogue
if (moneyMultiplier > 2.5) {
await showEncounterDialogue(scene, `${namespace}:job_complete_good`, `${namespace}:speaker`);
await showEncounterDialogue(`${namespace}:job_complete_good`, `${namespace}:speaker`);
} else {
await showEncounterDialogue(scene, `${namespace}:job_complete_bad`, `${namespace}:speaker`);
await showEncounterDialogue(`${namespace}:job_complete_bad`, `${namespace}:speaker`);
}
const moneyChange = scene.getWaveMoneyAmount(moneyMultiplier);
updatePlayerMoney(scene, moneyChange, true, false);
await showEncounterText(scene, i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange }));
await showEncounterText(scene, `${namespace}:pokemon_tired`);
const moneyChange = gScene.getWaveMoneyAmount(moneyMultiplier);
updatePlayerMoney(moneyChange, true, false);
await showEncounterText(i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange }));
await showEncounterText(`${namespace}:pokemon_tired`);
setEncounterRewards(scene, { fillRemaining: true });
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ fillRemaining: true });
leaveEncounterWithoutBattle();
})
.build()
)
@ -158,8 +158,8 @@ export const PartTimerEncounter: MysteryEncounter =
}
]
})
.withPreOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
encounter.setDialogueToken("selectedPokemon", pokemon.getNameToRender());
@ -186,41 +186,41 @@ export const PartTimerEncounter: MysteryEncounter =
}
});
setEncounterExp(scene, pokemon.id, 100);
setEncounterExp(pokemon.id, 100);
// Hide intro visuals
transitionMysteryEncounterIntroVisuals(scene, true, false);
transitionMysteryEncounterIntroVisuals(true, false);
// Play sfx for "working"
doStrongWorkSfx(scene);
doStrongWorkSfx();
};
// Only Pokemon non-KOd pokemon can be selected
const selectableFilter = (pokemon: Pokemon) => {
return isPokemonValidForEncounterOptionSelection(pokemon, scene, `${namespace}:invalid_selection`);
return isPokemonValidForEncounterOptionSelection(pokemon, `${namespace}:invalid_selection`);
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Pick Move Warehouse items
// Bring visuals back in
await transitionMysteryEncounterIntroVisuals(scene, false, false);
await transitionMysteryEncounterIntroVisuals(false, false);
const moneyMultiplier = scene.currentBattle.mysteryEncounter!.misc.moneyMultiplier;
const moneyMultiplier = gScene.currentBattle.mysteryEncounter!.misc.moneyMultiplier;
// Give money and do dialogue
if (moneyMultiplier > 2.5) {
await showEncounterDialogue(scene, `${namespace}:job_complete_good`, `${namespace}:speaker`);
await showEncounterDialogue(`${namespace}:job_complete_good`, `${namespace}:speaker`);
} else {
await showEncounterDialogue(scene, `${namespace}:job_complete_bad`, `${namespace}:speaker`);
await showEncounterDialogue(`${namespace}:job_complete_bad`, `${namespace}:speaker`);
}
const moneyChange = scene.getWaveMoneyAmount(moneyMultiplier);
updatePlayerMoney(scene, moneyChange, true, false);
await showEncounterText(scene, i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange }));
await showEncounterText(scene, `${namespace}:pokemon_tired`);
const moneyChange = gScene.getWaveMoneyAmount(moneyMultiplier);
updatePlayerMoney(moneyChange, true, false);
await showEncounterText(i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange }));
await showEncounterText(`${namespace}:pokemon_tired`);
setEncounterRewards(scene, { fillRemaining: true });
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ fillRemaining: true });
leaveEncounterWithoutBattle();
})
.build()
)
@ -238,8 +238,8 @@ export const PartTimerEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const selectedPokemon = encounter.selectedOption?.primaryPokemon!;
encounter.setDialogueToken("selectedPokemon", selectedPokemon.getNameToRender());
@ -251,28 +251,28 @@ export const PartTimerEncounter: MysteryEncounter =
}
});
setEncounterExp(scene, selectedPokemon.id, 100);
setEncounterExp(selectedPokemon.id, 100);
// Hide intro visuals
transitionMysteryEncounterIntroVisuals(scene, true, false);
transitionMysteryEncounterIntroVisuals(true, false);
// Play sfx for "working"
doSalesSfx(scene);
doSalesSfx();
return true;
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Assist with Sales
// Bring visuals back in
await transitionMysteryEncounterIntroVisuals(scene, false, false);
await transitionMysteryEncounterIntroVisuals(false, false);
// Give money and do dialogue
await showEncounterDialogue(scene, `${namespace}:job_complete_good`, `${namespace}:speaker`);
const moneyChange = scene.getWaveMoneyAmount(2.5);
updatePlayerMoney(scene, moneyChange, true, false);
await showEncounterText(scene, i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange }));
await showEncounterText(scene, `${namespace}:pokemon_tired`);
await showEncounterDialogue(`${namespace}:job_complete_good`, `${namespace}:speaker`);
const moneyChange = gScene.getWaveMoneyAmount(2.5);
updatePlayerMoney(moneyChange, true, false);
await showEncounterText(i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange }));
await showEncounterText(`${namespace}:pokemon_tired`);
setEncounterRewards(scene, { fillRemaining: true });
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ fillRemaining: true });
leaveEncounterWithoutBattle();
})
.build()
)
@ -284,51 +284,51 @@ export const PartTimerEncounter: MysteryEncounter =
])
.build();
function doStrongWorkSfx(scene: BattleScene) {
scene.playSound("battle_anims/PRSFX- Horn Drill1");
scene.playSound("battle_anims/PRSFX- Horn Drill1");
function doStrongWorkSfx() {
gScene.playSound("battle_anims/PRSFX- Horn Drill1");
gScene.playSound("battle_anims/PRSFX- Horn Drill1");
scene.time.delayedCall(1000, () => {
scene.playSound("battle_anims/PRSFX- Guillotine2");
gScene.time.delayedCall(1000, () => {
gScene.playSound("battle_anims/PRSFX- Guillotine2");
});
scene.time.delayedCall(2000, () => {
scene.playSound("battle_anims/PRSFX- Heavy Slam2");
gScene.time.delayedCall(2000, () => {
gScene.playSound("battle_anims/PRSFX- Heavy Slam2");
});
scene.time.delayedCall(2500, () => {
scene.playSound("battle_anims/PRSFX- Guillotine2");
gScene.time.delayedCall(2500, () => {
gScene.playSound("battle_anims/PRSFX- Guillotine2");
});
}
function doDeliverySfx(scene: BattleScene) {
scene.playSound("battle_anims/PRSFX- Accelerock1");
function doDeliverySfx() {
gScene.playSound("battle_anims/PRSFX- Accelerock1");
scene.time.delayedCall(1500, () => {
scene.playSound("battle_anims/PRSFX- Extremespeed1");
gScene.time.delayedCall(1500, () => {
gScene.playSound("battle_anims/PRSFX- Extremespeed1");
});
scene.time.delayedCall(2000, () => {
scene.playSound("battle_anims/PRSFX- Extremespeed1");
gScene.time.delayedCall(2000, () => {
gScene.playSound("battle_anims/PRSFX- Extremespeed1");
});
scene.time.delayedCall(2250, () => {
scene.playSound("battle_anims/PRSFX- Agility");
gScene.time.delayedCall(2250, () => {
gScene.playSound("battle_anims/PRSFX- Agility");
});
}
function doSalesSfx(scene: BattleScene) {
scene.playSound("battle_anims/PRSFX- Captivate");
function doSalesSfx() {
gScene.playSound("battle_anims/PRSFX- Captivate");
scene.time.delayedCall(1500, () => {
scene.playSound("battle_anims/PRSFX- Attract2");
gScene.time.delayedCall(1500, () => {
gScene.playSound("battle_anims/PRSFX- Attract2");
});
scene.time.delayedCall(2000, () => {
scene.playSound("battle_anims/PRSFX- Aurora Veil2");
gScene.time.delayedCall(2000, () => {
gScene.playSound("battle_anims/PRSFX- Aurora Veil2");
});
scene.time.delayedCall(3000, () => {
scene.playSound("battle_anims/PRSFX- Attract2");
gScene.time.delayedCall(3000, () => {
gScene.playSound("battle_anims/PRSFX- Attract2");
});
}

View File

@ -1,6 +1,6 @@
import { initSubsequentOptionSelect, leaveEncounterWithoutBattle, transitionMysteryEncounterIntroVisuals, updatePlayerMoney, } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import MysteryEncounterOption, { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { TrainerSlot } from "#app/data/trainer-config";
@ -58,8 +58,8 @@ export const SafariZoneEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
scene.currentBattle.mysteryEncounter?.setDialogueToken("numEncounters", NUM_SAFARI_ENCOUNTERS.toString());
.withOnInit(() => {
gScene.currentBattle.mysteryEncounter?.setDialogueToken("numEncounters", NUM_SAFARI_ENCOUNTERS.toString());
return true;
})
.withOption(MysteryEncounterOptionBuilder
@ -74,25 +74,25 @@ export const SafariZoneEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Start safari encounter
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
encounter.continuousEncounter = true;
encounter.misc = {
safariPokemonRemaining: NUM_SAFARI_ENCOUNTERS
};
updatePlayerMoney(scene, -(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney);
updatePlayerMoney(-(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney);
// Load bait/mud assets
scene.loadSe("PRSFX- Bug Bite", "battle_anims", "PRSFX- Bug Bite.wav");
scene.loadSe("PRSFX- Sludge Bomb2", "battle_anims", "PRSFX- Sludge Bomb2.wav");
scene.loadSe("PRSFX- Taunt2", "battle_anims", "PRSFX- Taunt2.wav");
scene.loadAtlas("safari_zone_bait", "mystery-encounters");
scene.loadAtlas("safari_zone_mud", "mystery-encounters");
gScene.loadSe("PRSFX- Bug Bite", "battle_anims", "PRSFX- Bug Bite.wav");
gScene.loadSe("PRSFX- Sludge Bomb2", "battle_anims", "PRSFX- Sludge Bomb2.wav");
gScene.loadSe("PRSFX- Taunt2", "battle_anims", "PRSFX- Taunt2.wav");
gScene.loadAtlas("safari_zone_bait", "mystery-encounters");
gScene.loadAtlas("safari_zone_mud", "mystery-encounters");
// Clear enemy party
scene.currentBattle.enemyParty = [];
await transitionMysteryEncounterIntroVisuals(scene);
await summonSafariPokemon(scene);
initSubsequentOptionSelect(scene, { overrideOptions: safariZoneGameOptions, hideDescription: true });
gScene.currentBattle.enemyParty = [];
await transitionMysteryEncounterIntroVisuals();
await summonSafariPokemon();
initSubsequentOptionSelect({ overrideOptions: safariZoneGameOptions, hideDescription: true });
return true;
})
.build()
@ -107,9 +107,9 @@ export const SafariZoneEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)
@ -142,26 +142,26 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [
}
],
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Throw a ball option
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const pokemon = encounter.misc.pokemon;
const catchResult = await throwPokeball(scene, pokemon);
const catchResult = await throwPokeball(pokemon);
if (catchResult) {
// You caught pokemon
// Check how many safari pokemon left
if (encounter.misc.safariPokemonRemaining > 0) {
await summonSafariPokemon(scene);
initSubsequentOptionSelect(scene, { overrideOptions: safariZoneGameOptions, startingCursorIndex: 0, hideDescription: true });
await summonSafariPokemon();
initSubsequentOptionSelect({ overrideOptions: safariZoneGameOptions, startingCursorIndex: 0, hideDescription: true });
} else {
// End safari mode
encounter.continuousEncounter = false;
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
}
} else {
// Pokemon catch failed, end turn
await doEndTurn(scene, 0);
await doEndTurn(0);
}
return true;
})
@ -177,22 +177,22 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Throw bait option
const pokemon = scene.currentBattle.mysteryEncounter!.misc.pokemon;
await throwBait(scene, pokemon);
const pokemon = gScene.currentBattle.mysteryEncounter!.misc.pokemon;
await throwBait(pokemon);
// 100% chance to increase catch stage +2
tryChangeCatchStage(scene, 2);
tryChangeCatchStage(2);
// 80% chance to increase flee stage +1
const fleeChangeResult = tryChangeFleeStage(scene, 1, 8);
const fleeChangeResult = tryChangeFleeStage(1, 8);
if (!fleeChangeResult) {
await showEncounterText(scene, getEncounterText(scene, `${namespace}:safari.busy_eating`) ?? "", null, 1000, false );
await showEncounterText(getEncounterText(`${namespace}:safari.busy_eating`) ?? "", null, 1000, false );
} else {
await showEncounterText(scene, getEncounterText(scene, `${namespace}:safari.eating`) ?? "", null, 1000, false);
await showEncounterText(getEncounterText(`${namespace}:safari.eating`) ?? "", null, 1000, false);
}
await doEndTurn(scene, 1);
await doEndTurn(1);
return true;
})
.build(),
@ -207,21 +207,21 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Throw mud option
const pokemon = scene.currentBattle.mysteryEncounter!.misc.pokemon;
await throwMud(scene, pokemon);
const pokemon = gScene.currentBattle.mysteryEncounter!.misc.pokemon;
await throwMud(pokemon);
// 100% chance to decrease flee stage -2
tryChangeFleeStage(scene, -2);
tryChangeFleeStage(-2);
// 80% chance to decrease catch stage -1
const catchChangeResult = tryChangeCatchStage(scene, -1, 8);
const catchChangeResult = tryChangeCatchStage(-1, 8);
if (!catchChangeResult) {
await showEncounterText(scene, getEncounterText(scene, `${namespace}:safari.beside_itself_angry`) ?? "", null, 1000, false );
await showEncounterText(getEncounterText(`${namespace}:safari.beside_itself_angry`) ?? "", null, 1000, false );
} else {
await showEncounterText(scene, getEncounterText(scene, `${namespace}:safari.angry`) ?? "", null, 1000, false );
await showEncounterText(getEncounterText(`${namespace}:safari.angry`) ?? "", null, 1000, false );
}
await doEndTurn(scene, 2);
await doEndTurn(2);
return true;
})
.build(),
@ -231,40 +231,40 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [
buttonLabel: `${namespace}:safari.4.label`,
buttonTooltip: `${namespace}:safari.4.tooltip`,
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Flee option
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const pokemon = encounter.misc.pokemon;
await doPlayerFlee(scene, pokemon);
await doPlayerFlee(pokemon);
// Check how many safari pokemon left
if (encounter.misc.safariPokemonRemaining > 0) {
await summonSafariPokemon(scene);
initSubsequentOptionSelect(scene, { overrideOptions: safariZoneGameOptions, startingCursorIndex: 3, hideDescription: true });
await summonSafariPokemon();
initSubsequentOptionSelect({ overrideOptions: safariZoneGameOptions, startingCursorIndex: 3, hideDescription: true });
} else {
// End safari mode
encounter.continuousEncounter = false;
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
}
return true;
})
.build()
];
async function summonSafariPokemon(scene: BattleScene) {
const encounter = scene.currentBattle.mysteryEncounter!;
async function summonSafariPokemon() {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Message pokemon remaining
encounter.setDialogueToken("remainingCount", encounter.misc.safariPokemonRemaining);
scene.queueMessage(getEncounterText(scene, `${namespace}:safari.remaining_count`) ?? "", null, true);
gScene.queueMessage(getEncounterText(`${namespace}:safari.remaining_count`) ?? "", null, true);
// Generate pokemon using safariPokemonRemaining so they are always the same pokemon no matter how many turns are taken
// Safari pokemon roll twice on shiny and HA chances, but are otherwise normal
let enemySpecies;
let pokemon;
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
enemySpecies = getPokemonSpecies(getRandomSpeciesByStarterTier([ 0, 5 ], undefined, undefined, false, false, false));
const level = scene.currentBattle.getLevelForWave();
enemySpecies = getPokemonSpecies(enemySpecies.getWildSpeciesForLevel(level, true, false, scene.gameMode));
pokemon = scene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, false);
const level = gScene.currentBattle.getLevelForWave();
enemySpecies = getPokemonSpecies(enemySpecies.getWildSpeciesForLevel(level, true, false, gScene.gameMode));
pokemon = gScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, false);
// Roll shiny twice
if (!pokemon.shiny) {
@ -276,7 +276,7 @@ async function summonSafariPokemon(scene: BattleScene) {
const hiddenIndex = pokemon.species.ability2 ? 2 : 1;
if (pokemon.abilityIndex < hiddenIndex) {
const hiddenAbilityChance = new IntegerHolder(256);
scene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance);
gScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance);
const hasHiddenAbility = !randSeedInt(hiddenAbilityChance.value);
@ -288,10 +288,10 @@ async function summonSafariPokemon(scene: BattleScene) {
pokemon.calculateStats();
scene.currentBattle.enemyParty.unshift(pokemon);
}, scene.currentBattle.waveIndex * 1000 * encounter.misc.safariPokemonRemaining);
gScene.currentBattle.enemyParty.unshift(pokemon);
}, gScene.currentBattle.waveIndex * 1000 * encounter.misc.safariPokemonRemaining);
scene.gameData.setPokemonSeen(pokemon, true);
gScene.gameData.setPokemonSeen(pokemon, true);
await pokemon.loadAssets();
// Reset safari catch and flee rates
@ -300,7 +300,7 @@ async function summonSafariPokemon(scene: BattleScene) {
encounter.misc.pokemon = pokemon;
encounter.misc.safariPokemonRemaining -= 1;
scene.unshiftPhase(new SummonPhase(scene, 0, false));
gScene.unshiftPhase(new SummonPhase(0, false));
encounter.setDialogueToken("pokemonName", getPokemonNameWithAffix(pokemon));
@ -309,49 +309,49 @@ async function summonSafariPokemon(scene: BattleScene) {
// shows up and the IV scanner breaks. For now, we place the IV scanner code
// separately so that at least the IV scanner works.
const ivScannerModifier = scene.findModifier(m => m instanceof IvScannerModifier);
const ivScannerModifier = gScene.findModifier(m => m instanceof IvScannerModifier);
if (ivScannerModifier) {
scene.pushPhase(new ScanIvsPhase(scene, pokemon.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6)));
gScene.pushPhase(new ScanIvsPhase(pokemon.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6)));
}
}
function throwPokeball(scene: BattleScene, pokemon: EnemyPokemon): Promise<boolean> {
function throwPokeball(pokemon: EnemyPokemon): Promise<boolean> {
const baseCatchRate = pokemon.species.catchRate;
// Catch stage ranges from -6 to +6 (like stat boost stages)
const safariCatchStage = scene.currentBattle.mysteryEncounter!.misc.catchStage;
const safariCatchStage = gScene.currentBattle.mysteryEncounter!.misc.catchStage;
// Catch modifier ranges from 2/8 (-6 stage) to 8/2 (+6)
const safariModifier = (2 + Math.min(Math.max(safariCatchStage, 0), 6)) / (2 - Math.max(Math.min(safariCatchStage, 0), -6));
// Catch rate same as safari ball
const pokeballMultiplier = 1.5;
const catchRate = Math.round(baseCatchRate * pokeballMultiplier * safariModifier);
const ballTwitchRate = Math.round(1048560 / Math.sqrt(Math.sqrt(16711680 / catchRate)));
return trainerThrowPokeball(scene, pokemon, PokeballType.POKEBALL, ballTwitchRate);
return trainerThrowPokeball(pokemon, PokeballType.POKEBALL, ballTwitchRate);
}
async function throwBait(scene: BattleScene, pokemon: EnemyPokemon): Promise<boolean> {
async function throwBait(pokemon: EnemyPokemon): Promise<boolean> {
const originalY: number = pokemon.y;
const fpOffset = pokemon.getFieldPositionOffset();
const bait: Phaser.GameObjects.Sprite = scene.addFieldSprite(16 + 75, 80 + 25, "safari_zone_bait", "0001.png");
const bait: Phaser.GameObjects.Sprite = gScene.addFieldSprite(16 + 75, 80 + 25, "safari_zone_bait", "0001.png");
bait.setOrigin(0.5, 0.625);
scene.field.add(bait);
gScene.field.add(bait);
return new Promise(resolve => {
scene.trainer.setTexture(`trainer_${scene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`);
scene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[0], () => {
scene.playSound("se/pb_throw");
gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`);
gScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[0], () => {
gScene.playSound("se/pb_throw");
// Trainer throw frames
scene.trainer.setFrame("2");
scene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[1], () => {
scene.trainer.setFrame("3");
scene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[2], () => {
scene.trainer.setTexture(`trainer_${scene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`);
gScene.trainer.setFrame("2");
gScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[1], () => {
gScene.trainer.setFrame("3");
gScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[2], () => {
gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`);
});
});
// Pokeball move and catch logic
scene.tweens.add({
gScene.tweens.add({
targets: bait,
x: { value: 210 + fpOffset[0], ease: "Linear" },
y: { value: 55 + fpOffset[1], ease: "Cubic.easeOut" },
@ -359,8 +359,8 @@ async function throwBait(scene: BattleScene, pokemon: EnemyPokemon): Promise<boo
onComplete: () => {
let index = 1;
scene.time.delayedCall(768, () => {
scene.tweens.add({
gScene.time.delayedCall(768, () => {
gScene.tweens.add({
targets: pokemon,
duration: 150,
ease: "Cubic.easeOut",
@ -368,12 +368,12 @@ async function throwBait(scene: BattleScene, pokemon: EnemyPokemon): Promise<boo
y: originalY - 5,
loop: 6,
onStart: () => {
scene.playSound("battle_anims/PRSFX- Bug Bite");
gScene.playSound("battle_anims/PRSFX- Bug Bite");
bait.setFrame("0002.png");
},
onLoop: () => {
if (index % 2 === 0) {
scene.playSound("battle_anims/PRSFX- Bug Bite");
gScene.playSound("battle_anims/PRSFX- Bug Bite");
}
if (index === 4) {
bait.setFrame("0003.png");
@ -381,7 +381,7 @@ async function throwBait(scene: BattleScene, pokemon: EnemyPokemon): Promise<boo
index++;
},
onComplete: () => {
scene.time.delayedCall(256, () => {
gScene.time.delayedCall(256, () => {
bait.destroy();
resolve(true);
});
@ -394,55 +394,55 @@ async function throwBait(scene: BattleScene, pokemon: EnemyPokemon): Promise<boo
});
}
async function throwMud(scene: BattleScene, pokemon: EnemyPokemon): Promise<boolean> {
async function throwMud(pokemon: EnemyPokemon): Promise<boolean> {
const originalY: number = pokemon.y;
const fpOffset = pokemon.getFieldPositionOffset();
const mud: Phaser.GameObjects.Sprite = scene.addFieldSprite(16 + 75, 80 + 35, "safari_zone_mud", "0001.png");
const mud: Phaser.GameObjects.Sprite = gScene.addFieldSprite(16 + 75, 80 + 35, "safari_zone_mud", "0001.png");
mud.setOrigin(0.5, 0.625);
scene.field.add(mud);
gScene.field.add(mud);
return new Promise(resolve => {
scene.trainer.setTexture(`trainer_${scene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`);
scene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[0], () => {
scene.playSound("se/pb_throw");
gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`);
gScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[0], () => {
gScene.playSound("se/pb_throw");
// Trainer throw frames
scene.trainer.setFrame("2");
scene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[1], () => {
scene.trainer.setFrame("3");
scene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[2], () => {
scene.trainer.setTexture(`trainer_${scene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`);
gScene.trainer.setFrame("2");
gScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[1], () => {
gScene.trainer.setFrame("3");
gScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[2], () => {
gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`);
});
});
// Mud throw and splat
scene.tweens.add({
gScene.tweens.add({
targets: mud,
x: { value: 230 + fpOffset[0], ease: "Linear" },
y: { value: 55 + fpOffset[1], ease: "Cubic.easeOut" },
duration: 500,
onComplete: () => {
// Mud frame 2
scene.playSound("battle_anims/PRSFX- Sludge Bomb2");
gScene.playSound("battle_anims/PRSFX- Sludge Bomb2");
mud.setFrame("0002.png");
// Mud splat
scene.time.delayedCall(200, () => {
gScene.time.delayedCall(200, () => {
mud.setFrame("0003.png");
scene.time.delayedCall(400, () => {
gScene.time.delayedCall(400, () => {
mud.setFrame("0004.png");
});
});
// Fade mud then angry animation
scene.tweens.add({
gScene.tweens.add({
targets: mud,
alpha: 0,
ease: "Cubic.easeIn",
duration: 1000,
onComplete: () => {
mud.destroy();
scene.tweens.add({
gScene.tweens.add({
targets: pokemon,
duration: 300,
ease: "Cubic.easeOut",
@ -450,10 +450,10 @@ async function throwMud(scene: BattleScene, pokemon: EnemyPokemon): Promise<bool
y: originalY - 20,
loop: 1,
onStart: () => {
scene.playSound("battle_anims/PRSFX- Taunt2");
gScene.playSound("battle_anims/PRSFX- Taunt2");
},
onLoop: () => {
scene.playSound("battle_anims/PRSFX- Taunt2");
gScene.playSound("battle_anims/PRSFX- Taunt2");
},
onComplete: () => {
resolve(true);
@ -477,52 +477,52 @@ function isPokemonFlee(pokemon: EnemyPokemon, fleeStage: number): boolean {
return roll < fleeRate;
}
function tryChangeFleeStage(scene: BattleScene, change: number, chance?: number): boolean {
function tryChangeFleeStage(change: number, chance?: number): boolean {
if (chance && randSeedInt(10) >= chance) {
return false;
}
const currentFleeStage = scene.currentBattle.mysteryEncounter!.misc.fleeStage ?? 0;
scene.currentBattle.mysteryEncounter!.misc.fleeStage = Math.min(Math.max(currentFleeStage + change, -6), 6);
const currentFleeStage = gScene.currentBattle.mysteryEncounter!.misc.fleeStage ?? 0;
gScene.currentBattle.mysteryEncounter!.misc.fleeStage = Math.min(Math.max(currentFleeStage + change, -6), 6);
return true;
}
function tryChangeCatchStage(scene: BattleScene, change: number, chance?: number): boolean {
function tryChangeCatchStage(change: number, chance?: number): boolean {
if (chance && randSeedInt(10) >= chance) {
return false;
}
const currentCatchStage = scene.currentBattle.mysteryEncounter!.misc.catchStage ?? 0;
scene.currentBattle.mysteryEncounter!.misc.catchStage = Math.min(Math.max(currentCatchStage + change, -6), 6);
const currentCatchStage = gScene.currentBattle.mysteryEncounter!.misc.catchStage ?? 0;
gScene.currentBattle.mysteryEncounter!.misc.catchStage = Math.min(Math.max(currentCatchStage + change, -6), 6);
return true;
}
async function doEndTurn(scene: BattleScene, cursorIndex: number) {
async function doEndTurn(cursorIndex: number) {
// First cleanup and destroy old Pokemon objects that were left in the enemyParty
// They are left in enemyParty temporarily so that VictoryPhase properly handles EXP
const party = scene.getEnemyParty();
const party = gScene.getEnemyParty();
if (party.length > 1) {
for (let i = 1; i < party.length; i++) {
party[i].destroy();
}
scene.currentBattle.enemyParty = party.slice(0, 1);
gScene.currentBattle.enemyParty = party.slice(0, 1);
}
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const pokemon = encounter.misc.pokemon;
const isFlee = isPokemonFlee(pokemon, encounter.misc.fleeStage);
if (isFlee) {
// Pokemon flees!
await doPokemonFlee(scene, pokemon);
await doPokemonFlee(pokemon);
// Check how many safari pokemon left
if (encounter.misc.safariPokemonRemaining > 0) {
await summonSafariPokemon(scene);
initSubsequentOptionSelect(scene, { overrideOptions: safariZoneGameOptions, startingCursorIndex: cursorIndex, hideDescription: true });
await summonSafariPokemon();
initSubsequentOptionSelect({ overrideOptions: safariZoneGameOptions, startingCursorIndex: cursorIndex, hideDescription: true });
} else {
// End safari mode
encounter.continuousEncounter = false;
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
}
} else {
scene.queueMessage(getEncounterText(scene, `${namespace}:safari.watching`) ?? "", 0, null, 1000);
initSubsequentOptionSelect(scene, { overrideOptions: safariZoneGameOptions, startingCursorIndex: cursorIndex, hideDescription: true });
gScene.queueMessage(getEncounterText(`${namespace}:safari.watching`) ?? "", 0, null, 1000);
initSubsequentOptionSelect({ overrideOptions: safariZoneGameOptions, startingCursorIndex: cursorIndex, hideDescription: true });
}
}

View File

@ -4,7 +4,7 @@ import { modifierTypes } from "#app/modifier/modifier-type";
import { randSeedInt } from "#app/utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { MoneyRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
@ -79,15 +79,15 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Update money
updatePlayerMoney(scene, -(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney);
updatePlayerMoney(-(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney);
// Calculate modifiers and dialogue tokens
const modifiers = [
generateModifierType(scene, modifierTypes.BASE_STAT_BOOSTER)!,
generateModifierType(scene, modifierTypes.BASE_STAT_BOOSTER)!,
generateModifierType(modifierTypes.BASE_STAT_BOOSTER)!,
generateModifierType(modifierTypes.BASE_STAT_BOOSTER)!,
];
encounter.setDialogueToken("boost1", modifiers[0].name);
encounter.setDialogueToken("boost2", modifiers[1].name);
@ -103,34 +103,34 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter =
if (!pokemon.isAllowed()) {
return i18next.t("partyUiHandler:cantBeUsed", { pokemonName: pokemon.getNameToRender() }) ?? null;
}
if (!encounter.pokemonMeetsPrimaryRequirements(scene, pokemon)) {
return getEncounterText(scene, `${namespace}:invalid_selection`) ?? null;
if (!encounter.pokemonMeetsPrimaryRequirements(pokemon)) {
return getEncounterText(`${namespace}:invalid_selection`) ?? null;
}
return null;
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Choose Cheap Option
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const chosenPokemon = encounter.misc.chosenPokemon;
const modifiers = encounter.misc.modifiers;
for (const modType of modifiers) {
await applyModifierTypeToPlayerPokemon(scene, chosenPokemon, modType);
await applyModifierTypeToPlayerPokemon(chosenPokemon, modType);
}
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.withPostOptionPhase(async (scene: BattleScene) => {
.withPostOptionPhase(async () => {
// Damage and status applied after dealer leaves (to make thematic sense)
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const chosenPokemon = encounter.misc.chosenPokemon as PlayerPokemon;
// Pokemon takes half max HP damage and nature is randomized (does not update dex)
applyDamageToPokemon(scene, chosenPokemon, Math.floor(chosenPokemon.getMaxHp() / 2));
applyDamageToPokemon(chosenPokemon, Math.floor(chosenPokemon.getMaxHp() / 2));
const currentNature = chosenPokemon.nature;
let newNature = randSeedInt(25) as Nature;
@ -140,8 +140,8 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter =
chosenPokemon.customPokemonData.nature = newNature;
encounter.setDialogueToken("newNature", getNatureName(newNature));
queueEncounterMessage(scene, `${namespace}:cheap_side_effects`);
setEncounterExp(scene, [ chosenPokemon.id ], 100);
queueEncounterMessage(`${namespace}:cheap_side_effects`);
setEncounterExp([ chosenPokemon.id ], 100);
await chosenPokemon.updateInfo();
})
.build()
@ -159,15 +159,15 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Update money
updatePlayerMoney(scene, -(encounter.options[1].requirements[0] as MoneyRequirement).requiredMoney);
updatePlayerMoney(-(encounter.options[1].requirements[0] as MoneyRequirement).requiredMoney);
// Calculate modifiers and dialogue tokens
const modifiers = [
generateModifierType(scene, modifierTypes.BASE_STAT_BOOSTER)!,
generateModifierType(scene, modifierTypes.BASE_STAT_BOOSTER)!,
generateModifierType(modifierTypes.BASE_STAT_BOOSTER)!,
generateModifierType(modifierTypes.BASE_STAT_BOOSTER)!,
];
encounter.setDialogueToken("boost1", modifiers[0].name);
encounter.setDialogueToken("boost2", modifiers[1].name);
@ -179,30 +179,30 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter =
// Only Pokemon that can gain benefits are unfainted
const selectableFilter = (pokemon: Pokemon) => {
return isPokemonValidForEncounterOptionSelection(pokemon, scene, `${namespace}:invalid_selection`);
return isPokemonValidForEncounterOptionSelection(pokemon, `${namespace}:invalid_selection`);
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Choose Expensive Option
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const chosenPokemon = encounter.misc.chosenPokemon;
const modifiers = encounter.misc.modifiers;
for (const modType of modifiers) {
await applyModifierTypeToPlayerPokemon(scene, chosenPokemon, modType);
await applyModifierTypeToPlayerPokemon(chosenPokemon, modType);
}
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.withPostOptionPhase(async (scene: BattleScene) => {
.withPostOptionPhase(async () => {
// Status applied after dealer leaves (to make thematic sense)
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const chosenPokemon = encounter.misc.chosenPokemon;
queueEncounterMessage(scene, `${namespace}:no_bad_effects`);
setEncounterExp(scene, [ chosenPokemon.id ], 100);
queueEncounterMessage(`${namespace}:no_bad_effects`);
setEncounterExp([ chosenPokemon.id ], 100);
await chosenPokemon.updateInfo();
})
@ -219,9 +219,9 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter =
}
]
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)

View File

@ -2,7 +2,7 @@ import { STEALING_MOVES } from "#app/data/mystery-encounters/requirements/requir
import { modifierTypes, PokemonHeldItemModifierType } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { StatusEffect } from "#app/data/status-effect";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
@ -51,8 +51,8 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter =
text: `${namespace}:intro`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
console.log(encounter);
// Calculate boss mon
@ -64,11 +64,11 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter =
moveSet: [ Moves.REST, Moves.SLEEP_TALK, Moves.CRUNCH, Moves.GIGA_IMPACT ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.SITRUS ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.SITRUS ]) as PokemonHeldItemModifierType,
stackCount: 2
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.ENIGMA ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.ENIGMA ]) as PokemonHeldItemModifierType,
stackCount: 2
},
],
@ -82,7 +82,7 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter =
encounter.enemyPartyConfigs = [ config ];
// Load animations/sfx for Snorlax fight start moves
loadCustomMovesForEncounter(scene, [ Moves.SNORE ]);
loadCustomMovesForEncounter([ Moves.SNORE ]);
encounter.setDialogueToken("snorlaxName", getPokemonSpecies(Species.SNORLAX).getName());
@ -102,10 +102,10 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Pick battle
const encounter = scene.currentBattle.mysteryEncounter!;
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.LEFTOVERS ], fillRemaining: true });
const encounter = gScene.currentBattle.mysteryEncounter!;
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.LEFTOVERS ], fillRemaining: true });
encounter.startOfBattleEffects.push(
{
sourceBattlerIndex: BattlerIndex.ENEMY,
@ -119,7 +119,7 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter =
move: new PokemonMove(Moves.SNORE),
ignorePp: true
});
await initBattleWithEnemyConfig(scene, encounter.enemyPartyConfigs[0]);
await initBattleWithEnemyConfig(encounter.enemyPartyConfigs[0]);
}
)
.withSimpleOption(
@ -132,12 +132,12 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Fall asleep waiting for Snorlax
// Full heal party
scene.unshiftPhase(new PartyHealPhase(scene, true));
queueEncounterMessage(scene, `${namespace}:option.2.rest_result`);
leaveEncounterWithoutBattle(scene);
gScene.unshiftPhase(new PartyHealPhase(true));
queueEncounterMessage(`${namespace}:option.2.rest_result`);
leaveEncounterWithoutBattle();
}
)
.withOption(
@ -154,13 +154,13 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter =
}
]
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Steal the Snorlax's Leftovers
const instance = scene.currentBattle.mysteryEncounter!;
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.LEFTOVERS ], fillRemaining: false });
const instance = gScene.currentBattle.mysteryEncounter!;
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.LEFTOVERS ], fillRemaining: false });
// Snorlax exp to Pokemon that did the stealing
setEncounterExp(scene, instance.primaryPokemon!.id, getPokemonSpecies(Species.SNORLAX).baseExp);
leaveEncounterWithoutBattle(scene);
setEncounterExp(instance.primaryPokemon!.id, getPokemonSpecies(Species.SNORLAX).baseExp);
leaveEncounterWithoutBattle();
})
.build()
)

View File

@ -1,7 +1,7 @@
import { EnemyPartyConfig, generateModifierTypeOption, initBattleWithEnemyConfig, setEncounterExp, setEncounterRewards, transitionMysteryEncounterIntroVisuals, updatePlayerMoney, } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { randSeedInt } from "#app/utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MoneyRequirement, WaveModulusRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
import Pokemon, { EnemyPokemon } from "#app/field/pokemon";
@ -62,9 +62,9 @@ export const TeleportingHijinksEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
const price = scene.getWaveMoneyAmount(MONEY_COST_MULTIPLIER);
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const price = gScene.getWaveMoneyAmount(MONEY_COST_MULTIPLIER);
encounter.setDialogueToken("price", price.toString());
encounter.misc = {
price
@ -85,14 +85,14 @@ export const TeleportingHijinksEncounter: MysteryEncounter =
}
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Update money
updatePlayerMoney(scene, -scene.currentBattle.mysteryEncounter!.misc.price, true, false);
updatePlayerMoney(-gScene.currentBattle.mysteryEncounter!.misc.price, true, false);
})
.withOptionPhase(async (scene: BattleScene) => {
const config: EnemyPartyConfig = await doBiomeTransitionDialogueAndBattleInit(scene);
setEncounterRewards(scene, { fillRemaining: true });
await initBattleWithEnemyConfig(scene, config);
.withOptionPhase(async () => {
const config: EnemyPartyConfig = await doBiomeTransitionDialogueAndBattleInit();
setEncounterRewards({ fillRemaining: true });
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -110,11 +110,11 @@ export const TeleportingHijinksEncounter: MysteryEncounter =
}
],
})
.withOptionPhase(async (scene: BattleScene) => {
const config: EnemyPartyConfig = await doBiomeTransitionDialogueAndBattleInit(scene);
setEncounterRewards(scene, { fillRemaining: true });
setEncounterExp(scene, scene.currentBattle.mysteryEncounter!.selectedOption!.primaryPokemon!.id, 100);
await initBattleWithEnemyConfig(scene, config);
.withOptionPhase(async () => {
const config: EnemyPartyConfig = await doBiomeTransitionDialogueAndBattleInit();
setEncounterRewards({ fillRemaining: true });
setEncounterExp(gScene.currentBattle.mysteryEncounter!.selectedOption!.primaryPokemon!.id, 100);
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -128,14 +128,14 @@ export const TeleportingHijinksEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Inspect the Machine
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
// Init enemy
const level = getEncounterPokemonLevelForWave(scene, STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const bossSpecies = scene.arena.randomSpecies(scene.currentBattle.waveIndex, level, 0, getPartyLuckValue(scene.getParty()), true);
const bossPokemon = new EnemyPokemon(scene, bossSpecies, level, TrainerSlot.NONE, true);
const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const bossSpecies = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true);
const bossPokemon = new EnemyPokemon(bossSpecies, level, TrainerSlot.NONE, true);
encounter.setDialogueToken("enemyPokemon", getPokemonNameWithAffix(bossPokemon));
const config: EnemyPartyConfig = {
pokemonConfigs: [{
@ -146,36 +146,36 @@ export const TeleportingHijinksEncounter: MysteryEncounter =
}],
};
const magnet = generateModifierTypeOption(scene, modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.STEEL ])!;
const metalCoat = generateModifierTypeOption(scene, modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.ELECTRIC ])!;
setEncounterRewards(scene, { guaranteedModifierTypeOptions: [ magnet, metalCoat ], fillRemaining: true });
await transitionMysteryEncounterIntroVisuals(scene, true, true);
await initBattleWithEnemyConfig(scene, config);
const magnet = generateModifierTypeOption(modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.STEEL ])!;
const metalCoat = generateModifierTypeOption(modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.ELECTRIC ])!;
setEncounterRewards({ guaranteedModifierTypeOptions: [ magnet, metalCoat ], fillRemaining: true });
await transitionMysteryEncounterIntroVisuals(true, true);
await initBattleWithEnemyConfig(config);
}
)
.build();
async function doBiomeTransitionDialogueAndBattleInit(scene: BattleScene) {
const encounter = scene.currentBattle.mysteryEncounter!;
async function doBiomeTransitionDialogueAndBattleInit() {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculate new biome (cannot be current biome)
const filteredBiomes = BIOME_CANDIDATES.filter(b => scene.arena.biomeType !== b);
const filteredBiomes = BIOME_CANDIDATES.filter(b => gScene.arena.biomeType !== b);
const newBiome = filteredBiomes[randSeedInt(filteredBiomes.length)];
// Show dialogue and transition biome
await showEncounterText(scene, `${namespace}:transport`);
await Promise.all([ animateBiomeChange(scene, newBiome), transitionMysteryEncounterIntroVisuals(scene) ]);
scene.playBgm();
await showEncounterText(scene, `${namespace}:attacked`);
await showEncounterText(`${namespace}:transport`);
await Promise.all([ animateBiomeChange(newBiome), transitionMysteryEncounterIntroVisuals() ]);
gScene.playBgm();
await showEncounterText(`${namespace}:attacked`);
// Init enemy
const level = getEncounterPokemonLevelForWave(scene, STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const bossSpecies = scene.arena.randomSpecies(scene.currentBattle.waveIndex, level, 0, getPartyLuckValue(scene.getParty()), true);
const bossPokemon = new EnemyPokemon(scene, bossSpecies, level, TrainerSlot.NONE, true);
const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER);
const bossSpecies = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true);
const bossPokemon = new EnemyPokemon(bossSpecies, level, TrainerSlot.NONE, true);
encounter.setDialogueToken("enemyPokemon", getPokemonNameWithAffix(bossPokemon));
// Defense/Spd buffs below wave 50, +1 to all stats otherwise
const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = scene.currentBattle.waveIndex < 50 ?
const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = gScene.currentBattle.waveIndex < 50 ?
[ Stat.DEF, Stat.SPDEF, Stat.SPD ] :
[ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ];
@ -187,8 +187,8 @@ async function doBiomeTransitionDialogueAndBattleInit(scene: BattleScene) {
isBoss: true,
tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ],
mysteryEncounterBattleEffects: (pokemon: Pokemon) => {
queueEncounterMessage(pokemon.scene, `${namespace}:boss_enraged`);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, statChangesForBattle, 1));
queueEncounterMessage(`${namespace}:boss_enraged`);
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1));
}
}],
};
@ -196,46 +196,46 @@ async function doBiomeTransitionDialogueAndBattleInit(scene: BattleScene) {
return config;
}
async function animateBiomeChange(scene: BattleScene, nextBiome: Biome) {
async function animateBiomeChange(nextBiome: Biome) {
return new Promise<void>(resolve => {
scene.tweens.add({
targets: [ scene.arenaEnemy, scene.lastEnemyTrainer ],
gScene.tweens.add({
targets: [ gScene.arenaEnemy, gScene.lastEnemyTrainer ],
x: "+=300",
duration: 2000,
onComplete: () => {
scene.newArena(nextBiome);
gScene.newArena(nextBiome);
const biomeKey = getBiomeKey(nextBiome);
const bgTexture = `${biomeKey}_bg`;
scene.arenaBgTransition.setTexture(bgTexture);
scene.arenaBgTransition.setAlpha(0);
scene.arenaBgTransition.setVisible(true);
scene.arenaPlayerTransition.setBiome(nextBiome);
scene.arenaPlayerTransition.setAlpha(0);
scene.arenaPlayerTransition.setVisible(true);
gScene.arenaBgTransition.setTexture(bgTexture);
gScene.arenaBgTransition.setAlpha(0);
gScene.arenaBgTransition.setVisible(true);
gScene.arenaPlayerTransition.setBiome(nextBiome);
gScene.arenaPlayerTransition.setAlpha(0);
gScene.arenaPlayerTransition.setVisible(true);
scene.tweens.add({
targets: [ scene.arenaPlayer, scene.arenaBgTransition, scene.arenaPlayerTransition ],
gScene.tweens.add({
targets: [ gScene.arenaPlayer, gScene.arenaBgTransition, gScene.arenaPlayerTransition ],
duration: 1000,
ease: "Sine.easeInOut",
alpha: (target: any) => target === scene.arenaPlayer ? 0 : 1,
alpha: (target: any) => target === gScene.arenaPlayer ? 0 : 1,
onComplete: () => {
scene.arenaBg.setTexture(bgTexture);
scene.arenaPlayer.setBiome(nextBiome);
scene.arenaPlayer.setAlpha(1);
scene.arenaEnemy.setBiome(nextBiome);
scene.arenaEnemy.setAlpha(1);
scene.arenaNextEnemy.setBiome(nextBiome);
scene.arenaBgTransition.setVisible(false);
scene.arenaPlayerTransition.setVisible(false);
if (scene.lastEnemyTrainer) {
scene.lastEnemyTrainer.destroy();
gScene.arenaBg.setTexture(bgTexture);
gScene.arenaPlayer.setBiome(nextBiome);
gScene.arenaPlayer.setAlpha(1);
gScene.arenaEnemy.setBiome(nextBiome);
gScene.arenaEnemy.setAlpha(1);
gScene.arenaNextEnemy.setBiome(nextBiome);
gScene.arenaBgTransition.setVisible(false);
gScene.arenaPlayerTransition.setVisible(false);
if (gScene.lastEnemyTrainer) {
gScene.lastEnemyTrainer.destroy();
}
resolve();
scene.tweens.add({
targets: scene.arenaEnemy,
gScene.tweens.add({
targets: gScene.arenaEnemy,
x: "-=300",
});
}

View File

@ -1,7 +1,7 @@
import { EnemyPartyConfig, generateModifierType, handleMysteryEncounterBattleFailed, initBattleWithEnemyConfig, setEncounterRewards, } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { trainerConfigs } from "#app/data/trainer-config";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { randSeedShuffle } from "#app/utils";
import MysteryEncounter, { MysteryEncounterBuilder } from "../mystery-encounter";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -94,14 +94,14 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
text: `${namespace}:intro_dialogue`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
const waveIndex = scene.currentBattle.waveIndex;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const waveIndex = gScene.currentBattle.waveIndex;
// Calculates what trainers are available for battle in the encounter
// If player is in space biome, uses special "Space" version of the trainer
encounter.enemyPartyConfigs = [
getPartyConfig(scene)
getPartyConfig()
];
const cleffaSpecies = waveIndex < FIRST_STAGE_EVOLUTION_WAVE ? Species.CLEFFA : waveIndex < FINAL_STAGE_EVOLUTION_WAVE ? Species.CLEFAIRY : Species.CLEFABLE;
@ -126,7 +126,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
];
// Determine the 3 pokemon the player can battle with
let partyCopy = scene.getParty().slice(0);
let partyCopy = gScene.getParty().slice(0);
partyCopy = partyCopy
.filter(p => p.isAllowedInBattle())
.sort((a, b) => a.friendship - b.friendship);
@ -140,7 +140,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
// Dialogue and egg calcs for Pokemon 1
const [ pokemon1CommonEggs, pokemon1RareEggs ] = calculateEggRewardsForPokemon(pokemon1);
let pokemon1Tooltip = getEncounterText(scene, `${namespace}:option.1.tooltip_base`)!;
let pokemon1Tooltip = getEncounterText(`${namespace}:option.1.tooltip_base`)!;
if (pokemon1RareEggs > 0) {
const eggsText = i18next.t(`${namespace}:numEggs`, { count: pokemon1RareEggs, rarity: i18next.t("egg:greatTier") });
pokemon1Tooltip += i18next.t(`${namespace}:eggs_tooltip`, { eggs: eggsText });
@ -155,7 +155,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
// Dialogue and egg calcs for Pokemon 2
const [ pokemon2CommonEggs, pokemon2RareEggs ] = calculateEggRewardsForPokemon(pokemon2);
let pokemon2Tooltip = getEncounterText(scene, `${namespace}:option.2.tooltip_base`)!;
let pokemon2Tooltip = getEncounterText(`${namespace}:option.2.tooltip_base`)!;
if (pokemon2RareEggs > 0) {
const eggsText = i18next.t(`${namespace}:numEggs`, { count: pokemon2RareEggs, rarity: i18next.t("egg:greatTier") });
pokemon2Tooltip += i18next.t(`${namespace}:eggs_tooltip`, { eggs: eggsText });
@ -170,7 +170,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
// Dialogue and egg calcs for Pokemon 3
const [ pokemon3CommonEggs, pokemon3RareEggs ] = calculateEggRewardsForPokemon(pokemon3);
let pokemon3Tooltip = getEncounterText(scene, `${namespace}:option.3.tooltip_base`)!;
let pokemon3Tooltip = getEncounterText(`${namespace}:option.3.tooltip_base`)!;
if (pokemon3RareEggs > 0) {
const eggsText = i18next.t(`${namespace}:numEggs`, { count: pokemon3RareEggs, rarity: i18next.t("egg:greatTier") });
pokemon3Tooltip += i18next.t(`${namespace}:eggs_tooltip`, { eggs: eggsText });
@ -213,22 +213,22 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Spawn battle with first pokemon
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0];
const { pokemon1, pokemon1CommonEggs, pokemon1RareEggs } = encounter.misc;
encounter.misc.chosenPokemon = pokemon1;
encounter.setDialogueToken("chosenPokemon", pokemon1.getNameToRender());
const eggOptions = getEggOptions(scene, pokemon1CommonEggs, pokemon1RareEggs);
setEncounterRewards(scene,
const eggOptions = getEggOptions(pokemon1CommonEggs, pokemon1RareEggs);
setEncounterRewards(
{ guaranteedModifierTypeFuncs: [ modifierTypes.SOOTHE_BELL ], fillRemaining: true },
eggOptions,
() => doPostEncounterCleanup(scene));
() => doPostEncounterCleanup());
// Remove all Pokemon from the party except the chosen Pokemon
removePokemonFromPartyAndStoreHeldItems(scene, encounter, pokemon1);
removePokemonFromPartyAndStoreHeldItems(encounter, pokemon1);
// Configure outro dialogue for egg rewards
encounter.dialogue.outro = [
@ -249,7 +249,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
}
encounter.onGameOver = onGameOver;
await initBattleWithEnemyConfig(scene, config);
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -265,22 +265,22 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Spawn battle with second pokemon
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0];
const { pokemon2, pokemon2CommonEggs, pokemon2RareEggs } = encounter.misc;
encounter.misc.chosenPokemon = pokemon2;
encounter.setDialogueToken("chosenPokemon", pokemon2.getNameToRender());
const eggOptions = getEggOptions(scene, pokemon2CommonEggs, pokemon2RareEggs);
setEncounterRewards(scene,
const eggOptions = getEggOptions(pokemon2CommonEggs, pokemon2RareEggs);
setEncounterRewards(
{ guaranteedModifierTypeFuncs: [ modifierTypes.SOOTHE_BELL ], fillRemaining: true },
eggOptions,
() => doPostEncounterCleanup(scene));
() => doPostEncounterCleanup());
// Remove all Pokemon from the party except the chosen Pokemon
removePokemonFromPartyAndStoreHeldItems(scene, encounter, pokemon2);
removePokemonFromPartyAndStoreHeldItems(encounter, pokemon2);
// Configure outro dialogue for egg rewards
encounter.dialogue.outro = [
@ -301,7 +301,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
}
encounter.onGameOver = onGameOver;
await initBattleWithEnemyConfig(scene, config);
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -317,22 +317,22 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Spawn battle with third pokemon
const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0];
const { pokemon3, pokemon3CommonEggs, pokemon3RareEggs } = encounter.misc;
encounter.misc.chosenPokemon = pokemon3;
encounter.setDialogueToken("chosenPokemon", pokemon3.getNameToRender());
const eggOptions = getEggOptions(scene, pokemon3CommonEggs, pokemon3RareEggs);
setEncounterRewards(scene,
const eggOptions = getEggOptions(pokemon3CommonEggs, pokemon3RareEggs);
setEncounterRewards(
{ guaranteedModifierTypeFuncs: [ modifierTypes.SOOTHE_BELL ], fillRemaining: true },
eggOptions,
() => doPostEncounterCleanup(scene));
() => doPostEncounterCleanup());
// Remove all Pokemon from the party except the chosen Pokemon
removePokemonFromPartyAndStoreHeldItems(scene, encounter, pokemon3);
removePokemonFromPartyAndStoreHeldItems(encounter, pokemon3);
// Configure outro dialogue for egg rewards
encounter.dialogue.outro = [
@ -353,7 +353,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
}
encounter.onGameOver = onGameOver;
await initBattleWithEnemyConfig(scene, config);
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -365,9 +365,9 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter =
])
.build();
function getPartyConfig(scene: BattleScene): EnemyPartyConfig {
function getPartyConfig(): EnemyPartyConfig {
// Bug type superfan trainer config
const waveIndex = scene.currentBattle.waveIndex;
const waveIndex = gScene.currentBattle.waveIndex;
const breederConfig = trainerConfigs[TrainerType.EXPERT_POKEMON_BREEDER].clone();
breederConfig.name = i18next.t(trainerNameKey);
@ -387,14 +387,14 @@ function getPartyConfig(scene: BattleScene): EnemyPartyConfig {
ivs: [ 31, 31, 31, 31, 31, 31 ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.TERA_SHARD, [ Type.STEEL ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.TERA_SHARD, [ Type.STEEL ]) as PokemonHeldItemModifierType,
}
]
}
]
};
if (scene.arena.biomeType === Biome.SPACE) {
if (gScene.arena.biomeType === Biome.SPACE) {
// All 3 members always Cleffa line, but different configs
baseConfig.pokemonConfigs!.push({
nickname: i18next.t(`${namespace}:cleffa_2_nickname`, { speciesName: getPokemonSpecies(cleffaSpecies).getName() }),
@ -477,14 +477,13 @@ function calculateEggRewardsForPokemon(pokemon: PlayerPokemon): [number, number]
return [ numCommons, numRares ];
}
function getEggOptions(scene: BattleScene, commonEggs: number, rareEggs: number) {
function getEggOptions(commonEggs: number, rareEggs: number) {
const eggDescription = i18next.t(`${namespace}:title`) + ":\n" + i18next.t(trainerNameKey);
const eggOptions: IEggOptions[] = [];
if (commonEggs > 0) {
for (let i = 0; i < commonEggs; i++) {
eggOptions.push({
scene,
pulled: false,
sourceType: EggSourceType.EVENT,
eggDescriptor: eggDescription,
@ -495,7 +494,6 @@ function getEggOptions(scene: BattleScene, commonEggs: number, rareEggs: number)
if (rareEggs > 0) {
for (let i = 0; i < rareEggs; i++) {
eggOptions.push({
scene,
pulled: false,
sourceType: EggSourceType.EVENT,
eggDescriptor: eggDescription,
@ -507,42 +505,42 @@ function getEggOptions(scene: BattleScene, commonEggs: number, rareEggs: number)
return eggOptions;
}
function removePokemonFromPartyAndStoreHeldItems(scene: BattleScene, encounter: MysteryEncounter, chosenPokemon: PlayerPokemon) {
const party = scene.getParty();
function removePokemonFromPartyAndStoreHeldItems(encounter: MysteryEncounter, chosenPokemon: PlayerPokemon) {
const party = gScene.getParty();
const chosenIndex = party.indexOf(chosenPokemon);
party[chosenIndex] = party[0];
party[0] = chosenPokemon;
encounter.misc.originalParty = scene.getParty().slice(1);
encounter.misc.originalParty = gScene.getParty().slice(1);
encounter.misc.originalPartyHeldItems = encounter.misc.originalParty
.map(p => p.getHeldItems());
scene["party"] = [
gScene["party"] = [
chosenPokemon
];
}
function checkAchievement(scene: BattleScene) {
if (scene.arena.biomeType === Biome.SPACE) {
scene.validateAchv(achvs.BREEDERS_IN_SPACE);
function checkAchievement() {
if (gScene.arena.biomeType === Biome.SPACE) {
gScene.validateAchv(achvs.BREEDERS_IN_SPACE);
}
}
function restorePartyAndHeldItems(scene: BattleScene) {
const encounter = scene.currentBattle.mysteryEncounter!;
function restorePartyAndHeldItems() {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Restore original party
scene.getParty().push(...encounter.misc.originalParty);
gScene.getParty().push(...encounter.misc.originalParty);
// Restore held items
const originalHeldItems = encounter.misc.originalPartyHeldItems;
originalHeldItems.forEach((pokemonHeldItemsList: PokemonHeldItemModifier[]) => {
pokemonHeldItemsList.forEach(heldItem => {
scene.addModifier(heldItem, true, false, false, true);
gScene.addModifier(heldItem, true, false, false, true);
});
});
scene.updateModifiers(true);
gScene.updateModifiers(true);
}
function onGameOver(scene: BattleScene) {
const encounter = scene.currentBattle.mysteryEncounter!;
function onGameOver() {
const encounter = gScene.currentBattle.mysteryEncounter!;
encounter.dialogue.outro = [
{
@ -552,7 +550,7 @@ function onGameOver(scene: BattleScene) {
];
// Restore original party, player loses all friendship with chosen mon (it remains fainted)
restorePartyAndHeldItems(scene);
restorePartyAndHeldItems();
const chosenPokemon = encounter.misc.chosenPokemon;
chosenPokemon.friendship = 0;
@ -563,33 +561,33 @@ function onGameOver(scene: BattleScene) {
encounter.misc.encounterFailed = true;
// Revert BGM
scene.playBgm(scene.arena.bgm);
gScene.playBgm(gScene.arena.bgm);
// Clear any leftover battle phases
scene.clearPhaseQueue();
scene.clearPhaseQueueSplice();
gScene.clearPhaseQueue();
gScene.clearPhaseQueueSplice();
// Return enemy Pokemon
const pokemon = scene.getEnemyPokemon();
const pokemon = gScene.getEnemyPokemon();
if (pokemon) {
scene.playSound("se/pb_rel");
gScene.playSound("se/pb_rel");
pokemon.hideInfo();
pokemon.tint(getPokeballTintColor(pokemon.pokeball), 1, 250, "Sine.easeIn");
scene.tweens.add({
gScene.tweens.add({
targets: pokemon,
duration: 250,
ease: "Sine.easeIn",
scale: 0.5,
onComplete: () => {
scene.field.remove(pokemon, true);
gScene.field.remove(pokemon, true);
}
});
}
// Show the enemy trainer
scene.time.delayedCall(250, () => {
const sprites = scene.currentBattle.trainer?.getSprites();
const tintSprites = scene.currentBattle.trainer?.getTintSprites();
gScene.time.delayedCall(250, () => {
const sprites = gScene.currentBattle.trainer?.getSprites();
const tintSprites = gScene.currentBattle.trainer?.getTintSprites();
if (sprites && tintSprites) {
for (let i = 0; i < sprites.length; i++) {
sprites[i].setVisible(true);
@ -598,8 +596,8 @@ function onGameOver(scene: BattleScene) {
tintSprites[i].clearTint();
}
}
scene.tweens.add({
targets: scene.currentBattle.trainer,
gScene.tweens.add({
targets: gScene.currentBattle.trainer,
x: "-=16",
y: "+=16",
alpha: 1,
@ -609,18 +607,18 @@ function onGameOver(scene: BattleScene) {
});
handleMysteryEncounterBattleFailed(scene, true);
handleMysteryEncounterBattleFailed(true);
return false;
}
function doPostEncounterCleanup(scene: BattleScene) {
const encounter = scene.currentBattle.mysteryEncounter!;
function doPostEncounterCleanup() {
const encounter = gScene.currentBattle.mysteryEncounter!;
if (!encounter.misc.encounterFailed) {
// Give achievement if in Space biome
checkAchievement(scene);
checkAchievement();
// Give 20 friendship to the chosen pokemon
encounter.misc.chosenPokemon.addFriendship(FRIENDSHIP_ADDED);
restorePartyAndHeldItems(scene);
restorePartyAndHeldItems();
}
}

View File

@ -1,7 +1,7 @@
import { leaveEncounterWithoutBattle, transitionMysteryEncounterIntroVisuals, updatePlayerMoney, } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { isNullOrUndefined, randSeedInt } from "#app/utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MoneyRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
import { catchPokemon, getRandomSpeciesByStarterTier, getSpriteKeysFromPokemon } from "#app/data/mystery-encounters/utils/encounter-pokemon-utils";
@ -57,8 +57,8 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
let species = getPokemonSpecies(getRandomSpeciesByStarterTier([ 0, 5 ], undefined, undefined, false, false, false));
let tries = 0;
@ -74,10 +74,10 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter =
// If no HA mon found or you roll 1%, give shiny Magikarp
species = getPokemonSpecies(Species.MAGIKARP);
const hiddenIndex = species.ability2 ? 2 : 1;
pokemon = new PlayerPokemon(scene, species, 5, hiddenIndex, species.formIndex, undefined, true, 0);
pokemon = new PlayerPokemon(species, 5, hiddenIndex, species.formIndex, undefined, true, 0);
} else {
const hiddenIndex = species.ability2 ? 2 : 1;
pokemon = new PlayerPokemon(scene, species, 5, hiddenIndex, species.formIndex);
pokemon = new PlayerPokemon(species, 5, hiddenIndex, species.formIndex);
}
pokemon.generateAndPopulateMoveset();
@ -100,7 +100,7 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter =
encounter.dialogue.encounterOptionsDialogue!.description = `${namespace}:description_shiny`;
encounter.options[0].dialogue!.buttonTooltip = `${namespace}:option.1.tooltip_shiny`;
}
const price = scene.getWaveMoneyAmount(priceMultiplier);
const price = gScene.getWaveMoneyAmount(priceMultiplier);
encounter.setDialogueToken("purchasePokemon", pokemon.getNameToRender());
encounter.setDialogueToken("price", price.toString());
encounter.misc = {
@ -126,24 +126,24 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter =
}
],
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const price = encounter.misc.price;
const purchasedPokemon = encounter.misc.pokemon as PlayerPokemon;
// Update money
updatePlayerMoney(scene, -price, true, false);
updatePlayerMoney(-price, true, false);
// Show dialogue
await showEncounterDialogue(scene, `${namespace}:option.1.selected_dialogue`, `${namespace}:speaker`);
await transitionMysteryEncounterIntroVisuals(scene);
await showEncounterDialogue(`${namespace}:option.1.selected_dialogue`, `${namespace}:speaker`);
await transitionMysteryEncounterIntroVisuals();
// "Catch" purchased pokemon
const data = new PokemonData(purchasedPokemon);
data.player = false;
await catchPokemon(scene, data.toPokemon(scene) as EnemyPokemon, null, PokeballType.POKEBALL, true, true);
await catchPokemon(data.toPokemon() as EnemyPokemon, null, PokeballType.POKEBALL, true, true);
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -157,9 +157,9 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)

View File

@ -1,7 +1,7 @@
import { EnemyPartyConfig, initBattleWithEnemyConfig, loadCustomMovesForEncounter, leaveEncounterWithoutBattle, setEncounterRewards, transitionMysteryEncounterIntroVisuals, generateModifierType } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { modifierTypes, PokemonHeldItemModifierType, } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { getPokemonSpecies } from "#app/data/pokemon-species";
import { Species } from "#enums/species";
@ -67,8 +67,8 @@ export const TheStrongStuffEncounter: MysteryEncounter =
text: `${namespace}:intro`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculate boss mon
const config: EnemyPartyConfig = {
@ -84,26 +84,26 @@ export const TheStrongStuffEncounter: MysteryEncounter =
moveSet: [ Moves.INFESTATION, Moves.SALT_CURE, Moves.GASTRO_ACID, Moves.HEAL_ORDER ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.SITRUS ]) as PokemonHeldItemModifierType
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.SITRUS ]) as PokemonHeldItemModifierType
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.ENIGMA ]) as PokemonHeldItemModifierType
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.ENIGMA ]) as PokemonHeldItemModifierType
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.APICOT ]) as PokemonHeldItemModifierType
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.APICOT ]) as PokemonHeldItemModifierType
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.GANLON ]) as PokemonHeldItemModifierType
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.GANLON ]) as PokemonHeldItemModifierType
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.LUM ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.LUM ]) as PokemonHeldItemModifierType,
stackCount: 2
}
],
tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ],
mysteryEncounterBattleEffects: (pokemon: Pokemon) => {
queueEncounterMessage(pokemon.scene, `${namespace}:option.2.stat_boost`);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, [ Stat.DEF, Stat.SPDEF ], 2));
queueEncounterMessage(`${namespace}:option.2.stat_boost`);
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.DEF, Stat.SPDEF ], 2));
}
}
],
@ -111,7 +111,7 @@ export const TheStrongStuffEncounter: MysteryEncounter =
encounter.enemyPartyConfigs = [ config ];
loadCustomMovesForEncounter(scene, [ Moves.GASTRO_ACID, Moves.STEALTH_ROCK ]);
loadCustomMovesForEncounter([ Moves.GASTRO_ACID, Moves.STEALTH_ROCK ]);
encounter.setDialogueToken("shuckleName", getPokemonSpecies(Species.SHUCKLE).getName());
@ -131,16 +131,16 @@ export const TheStrongStuffEncounter: MysteryEncounter =
}
]
},
async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Do blackout and hide intro visuals during blackout
scene.time.delayedCall(750, () => {
transitionMysteryEncounterIntroVisuals(scene, true, true, 50);
gScene.time.delayedCall(750, () => {
transitionMysteryEncounterIntroVisuals(true, true, 50);
});
// -15 to all base stats of highest BST (halved for HP), +10 to all base stats of rest of party (halved for HP)
// Sort party by bst
const sortedParty = scene.getParty().slice(0)
const sortedParty = gScene.getParty().slice(0)
.sort((pokemon1, pokemon2) => {
const pokemon1Bst = pokemon1.calculateBaseStats().reduce((a, b) => a + b, 0);
const pokemon2Bst = pokemon2.calculateBaseStats().reduce((a, b) => a + b, 0);
@ -160,15 +160,15 @@ export const TheStrongStuffEncounter: MysteryEncounter =
encounter.setDialogueToken("reductionValue", HIGH_BST_REDUCTION_VALUE.toString());
encounter.setDialogueToken("increaseValue", BST_INCREASE_VALUE.toString());
await showEncounterText(scene, `${namespace}:option.1.selected_2`, null, undefined, true);
await showEncounterText(`${namespace}:option.1.selected_2`, null, undefined, true);
encounter.dialogue.outro = [
{
text: `${namespace}:outro`,
}
];
setEncounterRewards(scene, { fillRemaining: true });
leaveEncounterWithoutBattle(scene, true);
setEncounterRewards({ fillRemaining: true });
leaveEncounterWithoutBattle(true);
return true;
}
)
@ -182,10 +182,10 @@ export const TheStrongStuffEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Pick battle
const encounter = scene.currentBattle.mysteryEncounter!;
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.SOUL_DEW ], fillRemaining: true });
const encounter = gScene.currentBattle.mysteryEncounter!;
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.SOUL_DEW ], fillRemaining: true });
encounter.startOfBattleEffects.push(
{
sourceBattlerIndex: BattlerIndex.ENEMY,
@ -201,8 +201,8 @@ export const TheStrongStuffEncounter: MysteryEncounter =
});
encounter.dialogue.outro = [];
await transitionMysteryEncounterIntroVisuals(scene, true, true, 500);
await initBattleWithEnemyConfig(scene, encounter.enemyPartyConfigs[0]);
await transitionMysteryEncounterIntroVisuals(true, true, 500);
await initBattleWithEnemyConfig(encounter.enemyPartyConfigs[0]);
}
)
.build();

View File

@ -1,7 +1,7 @@
import { EnemyPartyConfig, generateModifierType, generateModifierTypeOption, initBattleWithEnemyConfig, leaveEncounterWithoutBattle, setEncounterRewards, transitionMysteryEncounterIntroVisuals, } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { modifierTypes, PokemonHeldItemModifierType } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
import { TrainerType } from "#enums/trainer-type";
@ -82,15 +82,15 @@ export const TheWinstrateChallengeEncounter: MysteryEncounter =
},
])
.withAutoHideIntroVisuals(false)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Loaded back to front for pop() operations
encounter.enemyPartyConfigs.push(getVitoTrainerConfig(scene));
encounter.enemyPartyConfigs.push(getVickyTrainerConfig(scene));
encounter.enemyPartyConfigs.push(getViviTrainerConfig(scene));
encounter.enemyPartyConfigs.push(getVictoriaTrainerConfig(scene));
encounter.enemyPartyConfigs.push(getVictorTrainerConfig(scene));
encounter.enemyPartyConfigs.push(getVitoTrainerConfig());
encounter.enemyPartyConfigs.push(getVickyTrainerConfig());
encounter.enemyPartyConfigs.push(getViviTrainerConfig());
encounter.enemyPartyConfigs.push(getVictoriaTrainerConfig());
encounter.enemyPartyConfigs.push(getVictorTrainerConfig());
return true;
})
@ -109,13 +109,13 @@ export const TheWinstrateChallengeEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Spawn 5 trainer battles back to back with Macho Brace in rewards
scene.currentBattle.mysteryEncounter!.doContinueEncounter = async (scene: BattleScene) => {
await endTrainerBattleAndShowDialogue(scene);
gScene.currentBattle.mysteryEncounter!.doContinueEncounter = async () => {
await endTrainerBattleAndShowDialogue();
};
await transitionMysteryEncounterIntroVisuals(scene, true, false);
await spawnNextTrainerOrEndEncounter(scene);
await transitionMysteryEncounterIntroVisuals(true, false);
await spawnNextTrainerOrEndEncounter();
}
)
.withSimpleOption(
@ -129,47 +129,47 @@ export const TheWinstrateChallengeEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Refuse the challenge, they full heal the party and give the player a Rarer Candy
scene.unshiftPhase(new PartyHealPhase(scene, true));
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.RARER_CANDY ], fillRemaining: false });
leaveEncounterWithoutBattle(scene);
gScene.unshiftPhase(new PartyHealPhase(true));
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.RARER_CANDY ], fillRemaining: false });
leaveEncounterWithoutBattle();
}
)
.build();
async function spawnNextTrainerOrEndEncounter(scene: BattleScene) {
const encounter = scene.currentBattle.mysteryEncounter!;
async function spawnNextTrainerOrEndEncounter() {
const encounter = gScene.currentBattle.mysteryEncounter!;
const nextConfig = encounter.enemyPartyConfigs.pop();
if (!nextConfig) {
await transitionMysteryEncounterIntroVisuals(scene, false, false);
await showEncounterDialogue(scene, `${namespace}:victory`, `${namespace}:speaker`);
await transitionMysteryEncounterIntroVisuals(false, false);
await showEncounterDialogue(`${namespace}:victory`, `${namespace}:speaker`);
// Give 10x Voucher
const newModifier = modifierTypes.VOUCHER_PREMIUM().newModifier();
await scene.addModifier(newModifier);
scene.playSound("item_fanfare");
await showEncounterText(scene, i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }));
await gScene.addModifier(newModifier);
gScene.playSound("item_fanfare");
await showEncounterText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }));
await showEncounterDialogue(scene, `${namespace}:victory_2`, `${namespace}:speaker`);
scene.ui.clearText(); // Clears "Winstrate" title from screen as rewards get animated in
const machoBrace = generateModifierTypeOption(scene, modifierTypes.MYSTERY_ENCOUNTER_MACHO_BRACE)!;
await showEncounterDialogue(`${namespace}:victory_2`, `${namespace}:speaker`);
gScene.ui.clearText(); // Clears "Winstrate" title from screen as rewards get animated in
const machoBrace = generateModifierTypeOption(modifierTypes.MYSTERY_ENCOUNTER_MACHO_BRACE)!;
machoBrace.type.tier = ModifierTier.MASTER;
setEncounterRewards(scene, { guaranteedModifierTypeOptions: [ machoBrace ], fillRemaining: false });
setEncounterRewards({ guaranteedModifierTypeOptions: [ machoBrace ], fillRemaining: false });
encounter.doContinueEncounter = undefined;
leaveEncounterWithoutBattle(scene, false, MysteryEncounterMode.NO_BATTLE);
leaveEncounterWithoutBattle(false, MysteryEncounterMode.NO_BATTLE);
} else {
await initBattleWithEnemyConfig(scene, nextConfig);
await initBattleWithEnemyConfig(nextConfig);
}
}
function endTrainerBattleAndShowDialogue(scene: BattleScene): Promise<void> {
function endTrainerBattleAndShowDialogue(): Promise<void> {
return new Promise(async resolve => {
if (scene.currentBattle.mysteryEncounter!.enemyPartyConfigs.length === 0) {
if (gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs.length === 0) {
// Battle is over
const trainer = scene.currentBattle.trainer;
const trainer = gScene.currentBattle.trainer;
if (trainer) {
scene.tweens.add({
gScene.tweens.add({
targets: trainer,
x: "+=16",
y: "-=16",
@ -177,37 +177,37 @@ function endTrainerBattleAndShowDialogue(scene: BattleScene): Promise<void> {
ease: "Sine.easeInOut",
duration: 750,
onComplete: () => {
scene.field.remove(trainer, true);
gScene.field.remove(trainer, true);
}
});
}
await spawnNextTrainerOrEndEncounter(scene);
await spawnNextTrainerOrEndEncounter();
resolve(); // Wait for all dialogue/post battle stuff to complete before resolving
} else {
scene.arena.resetArenaEffects();
const playerField = scene.getPlayerField();
playerField.forEach((_, p) => scene.unshiftPhase(new ReturnPhase(scene, p)));
gScene.arena.resetArenaEffects();
const playerField = gScene.getPlayerField();
playerField.forEach((_, p) => gScene.unshiftPhase(new ReturnPhase(p)));
for (const pokemon of scene.getParty()) {
for (const pokemon of gScene.getParty()) {
// Only trigger form change when Eiscue is in Noice form
// Hardcoded Eiscue for now in case it is fused with another pokemon
if (pokemon.species.speciesId === Species.EISCUE && pokemon.hasAbility(Abilities.ICE_FACE) && pokemon.formIndex === 1) {
scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger);
}
pokemon.resetBattleData();
applyPostBattleInitAbAttrs(PostBattleInitAbAttr, pokemon);
}
scene.unshiftPhase(new ShowTrainerPhase(scene));
gScene.unshiftPhase(new ShowTrainerPhase());
// Hide the trainer and init next battle
const trainer = scene.currentBattle.trainer;
const trainer = gScene.currentBattle.trainer;
// Unassign previous trainer from battle so it isn't destroyed before animation completes
scene.currentBattle.trainer = null;
await spawnNextTrainerOrEndEncounter(scene);
gScene.currentBattle.trainer = null;
await spawnNextTrainerOrEndEncounter();
if (trainer) {
scene.tweens.add({
gScene.tweens.add({
targets: trainer,
x: "+=16",
y: "-=16",
@ -215,7 +215,7 @@ function endTrainerBattleAndShowDialogue(scene: BattleScene): Promise<void> {
ease: "Sine.easeInOut",
duration: 750,
onComplete: () => {
scene.field.remove(trainer, true);
gScene.field.remove(trainer, true);
resolve();
}
});
@ -224,7 +224,7 @@ function endTrainerBattleAndShowDialogue(scene: BattleScene): Promise<void> {
});
}
function getVictorTrainerConfig(scene: BattleScene): EnemyPartyConfig {
function getVictorTrainerConfig(): EnemyPartyConfig {
return {
trainerType: TrainerType.VICTOR,
pokemonConfigs: [
@ -236,11 +236,11 @@ function getVictorTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.FACADE, Moves.BRAVE_BIRD, Moves.PROTECT, Moves.QUICK_ATTACK ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.FLAME_ORB) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.FLAME_ORB) as PokemonHeldItemModifierType,
isTransferable: false
},
{
modifier: generateModifierType(scene, modifierTypes.FOCUS_BAND) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.FOCUS_BAND) as PokemonHeldItemModifierType,
stackCount: 2,
isTransferable: false
},
@ -254,11 +254,11 @@ function getVictorTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.FACADE, Moves.OBSTRUCT, Moves.NIGHT_SLASH, Moves.FIRE_PUNCH ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.FLAME_ORB) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.FLAME_ORB) as PokemonHeldItemModifierType,
isTransferable: false
},
{
modifier: generateModifierType(scene, modifierTypes.LEFTOVERS) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.LEFTOVERS) as PokemonHeldItemModifierType,
stackCount: 2,
isTransferable: false
}
@ -268,7 +268,7 @@ function getVictorTrainerConfig(scene: BattleScene): EnemyPartyConfig {
};
}
function getVictoriaTrainerConfig(scene: BattleScene): EnemyPartyConfig {
function getVictoriaTrainerConfig(): EnemyPartyConfig {
return {
trainerType: TrainerType.VICTORIA,
pokemonConfigs: [
@ -280,11 +280,11 @@ function getVictoriaTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.SYNTHESIS, Moves.SLUDGE_BOMB, Moves.GIGA_DRAIN, Moves.SLEEP_POWDER ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.SOUL_DEW) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.SOUL_DEW) as PokemonHeldItemModifierType,
isTransferable: false
},
{
modifier: generateModifierType(scene, modifierTypes.QUICK_CLAW) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.QUICK_CLAW) as PokemonHeldItemModifierType,
stackCount: 2,
isTransferable: false
}
@ -298,12 +298,12 @@ function getVictoriaTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.PSYSHOCK, Moves.MOONBLAST, Moves.SHADOW_BALL, Moves.WILL_O_WISP ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.PSYCHIC ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.PSYCHIC ]) as PokemonHeldItemModifierType,
stackCount: 1,
isTransferable: false
},
{
modifier: generateModifierType(scene, modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.FAIRY ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.ATTACK_TYPE_BOOSTER, [ Type.FAIRY ]) as PokemonHeldItemModifierType,
stackCount: 1,
isTransferable: false
}
@ -313,7 +313,7 @@ function getVictoriaTrainerConfig(scene: BattleScene): EnemyPartyConfig {
};
}
function getViviTrainerConfig(scene: BattleScene): EnemyPartyConfig {
function getViviTrainerConfig(): EnemyPartyConfig {
return {
trainerType: TrainerType.VIVI,
pokemonConfigs: [
@ -325,12 +325,12 @@ function getViviTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.WATERFALL, Moves.MEGAHORN, Moves.KNOCK_OFF, Moves.REST ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.LUM ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.LUM ]) as PokemonHeldItemModifierType,
stackCount: 2,
isTransferable: false
},
{
modifier: generateModifierType(scene, modifierTypes.BASE_STAT_BOOSTER, [ Stat.HP ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BASE_STAT_BOOSTER, [ Stat.HP ]) as PokemonHeldItemModifierType,
stackCount: 4,
isTransferable: false
}
@ -344,12 +344,12 @@ function getViviTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.SPORE, Moves.SWORDS_DANCE, Moves.SEED_BOMB, Moves.DRAIN_PUNCH ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.BASE_STAT_BOOSTER, [ Stat.HP ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BASE_STAT_BOOSTER, [ Stat.HP ]) as PokemonHeldItemModifierType,
stackCount: 4,
isTransferable: false
},
{
modifier: generateModifierType(scene, modifierTypes.TOXIC_ORB) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.TOXIC_ORB) as PokemonHeldItemModifierType,
isTransferable: false
}
]
@ -362,7 +362,7 @@ function getViviTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.EARTH_POWER, Moves.FIRE_BLAST, Moves.YAWN, Moves.PROTECT ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.QUICK_CLAW) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.QUICK_CLAW) as PokemonHeldItemModifierType,
stackCount: 3,
isTransferable: false
},
@ -372,7 +372,7 @@ function getViviTrainerConfig(scene: BattleScene): EnemyPartyConfig {
};
}
function getVickyTrainerConfig(scene: BattleScene): EnemyPartyConfig {
function getVickyTrainerConfig(): EnemyPartyConfig {
return {
trainerType: TrainerType.VICKY,
pokemonConfigs: [
@ -384,7 +384,7 @@ function getVickyTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.AXE_KICK, Moves.ICE_PUNCH, Moves.ZEN_HEADBUTT, Moves.BULLET_PUNCH ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType,
isTransferable: false
}
]
@ -393,7 +393,7 @@ function getVickyTrainerConfig(scene: BattleScene): EnemyPartyConfig {
};
}
function getVitoTrainerConfig(scene: BattleScene): EnemyPartyConfig {
function getVitoTrainerConfig(): EnemyPartyConfig {
return {
trainerType: TrainerType.VITO,
pokemonConfigs: [
@ -405,7 +405,7 @@ function getVitoTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.THUNDERBOLT, Moves.GIGA_DRAIN, Moves.FOUL_PLAY, Moves.THUNDER_WAVE ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.BASE_STAT_BOOSTER, [ Stat.SPD ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BASE_STAT_BOOSTER, [ Stat.SPD ]) as PokemonHeldItemModifierType,
stackCount: 2,
isTransferable: false
}
@ -419,47 +419,47 @@ function getVitoTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.SLUDGE_BOMB, Moves.GIGA_DRAIN, Moves.ICE_BEAM, Moves.EARTHQUAKE ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.SITRUS ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.SITRUS ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.APICOT ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.APICOT ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.GANLON ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.GANLON ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.STARF ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.STARF ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.SALAC ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.SALAC ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.LUM ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.LUM ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.LANSAT ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.LANSAT ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.LIECHI ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.LIECHI ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.PETAYA ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.PETAYA ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.ENIGMA ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.ENIGMA ]) as PokemonHeldItemModifierType,
stackCount: 2,
},
{
modifier: generateModifierType(scene, modifierTypes.BERRY, [ BerryType.LEPPA ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.BERRY, [ BerryType.LEPPA ]) as PokemonHeldItemModifierType,
stackCount: 2,
}
]
@ -472,7 +472,7 @@ function getVitoTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.DRILL_PECK, Moves.QUICK_ATTACK, Moves.THRASH, Moves.KNOCK_OFF ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.KINGS_ROCK) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.KINGS_ROCK) as PokemonHeldItemModifierType,
stackCount: 2,
isTransferable: false
}
@ -486,7 +486,7 @@ function getVitoTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.PSYCHIC, Moves.SHADOW_BALL, Moves.FOCUS_BLAST, Moves.THUNDERBOLT ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.WIDE_LENS) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.WIDE_LENS) as PokemonHeldItemModifierType,
stackCount: 2,
isTransferable: false
},
@ -500,7 +500,7 @@ function getVitoTrainerConfig(scene: BattleScene): EnemyPartyConfig {
moveSet: [ Moves.EARTHQUAKE, Moves.U_TURN, Moves.FLARE_BLITZ, Moves.ROCK_SLIDE ],
modifierConfigs: [
{
modifier: generateModifierType(scene, modifierTypes.QUICK_CLAW) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.QUICK_CLAW) as PokemonHeldItemModifierType,
stackCount: 2,
isTransferable: false
},

View File

@ -10,7 +10,7 @@ import { OptionSelectItem } from "#app/ui/abstact-option-select-ui-handler";
import { isNullOrUndefined, randSeedShuffle } from "#app/utils";
import { BattlerTagType } from "#enums/battler-tag-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { queueEncounterMessage, showEncounterText } from "#app/data/mystery-encounters/utils/encounter-dialogue-utils";
@ -70,8 +70,8 @@ export const TrainingSessionEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withPreOptionPhase(async (): Promise<boolean> => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
encounter.misc = {
playerPokemon: pokemon,
@ -80,24 +80,24 @@ export const TrainingSessionEncounter: MysteryEncounter =
// Only Pokemon that are not KOed/legal can be trained
const selectableFilter = (pokemon: Pokemon) => {
return isPokemonValidForEncounterOptionSelection(pokemon, scene, `${namespace}:invalid_selection`);
return isPokemonValidForEncounterOptionSelection(pokemon, `${namespace}:invalid_selection`);
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const playerPokemon: PlayerPokemon = encounter.misc.playerPokemon;
// Spawn light training session with chosen pokemon
// Every 50 waves, add +1 boss segment, capping at 5
const segments = Math.min(
2 + Math.floor(scene.currentBattle.waveIndex / 50),
2 + Math.floor(gScene.currentBattle.waveIndex / 50),
5
);
const modifiers = new ModifiersHolder();
const config = getEnemyConfig(scene, playerPokemon, segments, modifiers);
scene.removePokemonFromPlayerParty(playerPokemon, false);
const config = getEnemyConfig(playerPokemon, segments, modifiers);
gScene.removePokemonFromPlayerParty(playerPokemon, false);
const onBeforeRewardsPhase = () => {
encounter.setDialogueToken("stat1", "-");
@ -147,23 +147,23 @@ export const TrainingSessionEncounter: MysteryEncounter =
if (improvedCount > 0) {
playerPokemon.calculateStats();
scene.gameData.updateSpeciesDexIvs(playerPokemon.species.getRootSpeciesId(true), playerPokemon.ivs);
scene.gameData.setPokemonCaught(playerPokemon, false);
gScene.gameData.updateSpeciesDexIvs(playerPokemon.species.getRootSpeciesId(true), playerPokemon.ivs);
gScene.gameData.setPokemonCaught(playerPokemon, false);
}
// Add pokemon and mods back
scene.getParty().push(playerPokemon);
gScene.getParty().push(playerPokemon);
for (const mod of modifiers.value) {
mod.pokemonId = playerPokemon.id;
scene.addModifier(mod, true, false, false, true);
gScene.addModifier(mod, true, false, false, true);
}
scene.updateModifiers(true);
queueEncounterMessage(scene, `${namespace}:option.1.finished`);
gScene.updateModifiers(true);
queueEncounterMessage(`${namespace}:option.1.finished`);
};
setEncounterRewards(scene, { fillRemaining: true }, undefined, onBeforeRewardsPhase);
setEncounterRewards({ fillRemaining: true }, undefined, onBeforeRewardsPhase);
await initBattleWithEnemyConfig(scene, config);
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -181,15 +181,15 @@ export const TrainingSessionEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
.withPreOptionPhase(async (): Promise<boolean> => {
// Open menu for selecting pokemon and Nature
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const natures = new Array(25).fill(null).map((val, i) => i as Nature);
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Return the options for nature selection
return natures.map((nature: Nature) => {
const option: OptionSelectItem = {
label: getNatureName(nature, true, true, true, scene.uiTheme),
label: getNatureName(nature, true, true, true, gScene.uiTheme),
handler: () => {
// Pokemon and second option selected
encounter.setDialogueToken("nature", getNatureName(nature));
@ -206,40 +206,40 @@ export const TrainingSessionEncounter: MysteryEncounter =
// Only Pokemon that are not KOed/legal can be trained
const selectableFilter = (pokemon: Pokemon) => {
return isPokemonValidForEncounterOptionSelection(pokemon, scene, `${namespace}:invalid_selection`);
return isPokemonValidForEncounterOptionSelection(pokemon, `${namespace}:invalid_selection`);
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const playerPokemon: PlayerPokemon = encounter.misc.playerPokemon;
// Spawn medium training session with chosen pokemon
// Every 40 waves, add +1 boss segment, capping at 6
const segments = Math.min(2 + Math.floor(scene.currentBattle.waveIndex / 40), 6);
const segments = Math.min(2 + Math.floor(gScene.currentBattle.waveIndex / 40), 6);
const modifiers = new ModifiersHolder();
const config = getEnemyConfig(scene, playerPokemon, segments, modifiers);
scene.removePokemonFromPlayerParty(playerPokemon, false);
const config = getEnemyConfig(playerPokemon, segments, modifiers);
gScene.removePokemonFromPlayerParty(playerPokemon, false);
const onBeforeRewardsPhase = () => {
queueEncounterMessage(scene, `${namespace}:option.2.finished`);
queueEncounterMessage(`${namespace}:option.2.finished`);
// Add the pokemon back to party with Nature change
playerPokemon.setNature(encounter.misc.chosenNature);
scene.gameData.setPokemonCaught(playerPokemon, false);
gScene.gameData.setPokemonCaught(playerPokemon, false);
// Add pokemon and modifiers back
scene.getParty().push(playerPokemon);
gScene.getParty().push(playerPokemon);
for (const mod of modifiers.value) {
mod.pokemonId = playerPokemon.id;
scene.addModifier(mod, true, false, false, true);
gScene.addModifier(mod, true, false, false, true);
}
scene.updateModifiers(true);
gScene.updateModifiers(true);
};
setEncounterRewards(scene, { fillRemaining: true }, undefined, onBeforeRewardsPhase);
setEncounterRewards({ fillRemaining: true }, undefined, onBeforeRewardsPhase);
await initBattleWithEnemyConfig(scene, config);
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -257,9 +257,9 @@ export const TrainingSessionEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene): Promise<boolean> => {
.withPreOptionPhase(async (): Promise<boolean> => {
// Open menu for selecting pokemon and ability to learn
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const onPokemonSelected = (pokemon: PlayerPokemon) => {
// Return the options for ability selection
const speciesForm = !!pokemon.getFusionSpeciesForm()
@ -285,7 +285,7 @@ export const TrainingSessionEncounter: MysteryEncounter =
return true;
},
onHover: () => {
showEncounterText(scene, ability.description, 0, 0, false);
showEncounterText(ability.description, 0, 0, false);
},
};
optionSelectItems.push(option);
@ -297,28 +297,28 @@ export const TrainingSessionEncounter: MysteryEncounter =
// Only Pokemon that are not KOed/legal can be trained
const selectableFilter = (pokemon: Pokemon) => {
return isPokemonValidForEncounterOptionSelection(pokemon, scene, `${namespace}:invalid_selection`);
return isPokemonValidForEncounterOptionSelection(pokemon, `${namespace}:invalid_selection`);
};
return selectPokemonForOption(scene, onPokemonSelected, undefined, selectableFilter);
return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter);
})
.withOptionPhase(async (scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOptionPhase(async () => {
const encounter = gScene.currentBattle.mysteryEncounter!;
const playerPokemon: PlayerPokemon = encounter.misc.playerPokemon;
// Spawn hard training session with chosen pokemon
// Every 30 waves, add +1 boss segment, capping at 6
// Also starts with +1 to all stats
const segments = Math.min(2 + Math.floor(scene.currentBattle.waveIndex / 30), 6);
const segments = Math.min(2 + Math.floor(gScene.currentBattle.waveIndex / 30), 6);
const modifiers = new ModifiersHolder();
const config = getEnemyConfig(scene, playerPokemon, segments, modifiers);
const config = getEnemyConfig(playerPokemon, segments, modifiers);
config.pokemonConfigs![0].tags = [
BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON,
];
scene.removePokemonFromPlayerParty(playerPokemon, false);
gScene.removePokemonFromPlayerParty(playerPokemon, false);
const onBeforeRewardsPhase = () => {
queueEncounterMessage(scene, `${namespace}:option.3.finished`);
queueEncounterMessage(`${namespace}:option.3.finished`);
// Add the pokemon back to party with ability change
const abilityIndex = encounter.misc.abilityIndex;
@ -329,8 +329,8 @@ export const TrainingSessionEncounter: MysteryEncounter =
const rootFusionSpecies = playerPokemon.fusionSpecies?.getRootSpeciesId();
if (!isNullOrUndefined(rootFusionSpecies)
&& speciesStarterCosts.hasOwnProperty(rootFusionSpecies)
&& !!scene.gameData.dexData[rootFusionSpecies].caughtAttr) {
scene.gameData.starterData[rootFusionSpecies].abilityAttr |= playerPokemon.fusionAbilityIndex !== 1 || playerPokemon.fusionSpecies?.ability2
&& !!gScene.gameData.dexData[rootFusionSpecies].caughtAttr) {
gScene.gameData.starterData[rootFusionSpecies].abilityAttr |= playerPokemon.fusionAbilityIndex !== 1 || playerPokemon.fusionSpecies?.ability2
? 1 << playerPokemon.fusionAbilityIndex
: AbilityAttr.ABILITY_HIDDEN;
}
@ -339,20 +339,20 @@ export const TrainingSessionEncounter: MysteryEncounter =
}
playerPokemon.calculateStats();
scene.gameData.setPokemonCaught(playerPokemon, false);
gScene.gameData.setPokemonCaught(playerPokemon, false);
// Add pokemon and mods back
scene.getParty().push(playerPokemon);
gScene.getParty().push(playerPokemon);
for (const mod of modifiers.value) {
mod.pokemonId = playerPokemon.id;
scene.addModifier(mod, true, false, false, true);
gScene.addModifier(mod, true, false, false, true);
}
scene.updateModifiers(true);
gScene.updateModifiers(true);
};
setEncounterRewards(scene, { fillRemaining: true }, undefined, onBeforeRewardsPhase);
setEncounterRewards({ fillRemaining: true }, undefined, onBeforeRewardsPhase);
await initBattleWithEnemyConfig(scene, config);
await initBattleWithEnemyConfig(config);
})
.build()
)
@ -366,15 +366,15 @@ export const TrainingSessionEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave encounter with no rewards or exp
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)
.build();
function getEnemyConfig(scene: BattleScene, playerPokemon: PlayerPokemon, segments: number, modifiers: ModifiersHolder): EnemyPartyConfig {
function getEnemyConfig(playerPokemon: PlayerPokemon, segments: number, modifiers: ModifiersHolder): EnemyPartyConfig {
playerPokemon.resetSummonData();
// Passes modifiers by reference

View File

@ -1,7 +1,7 @@
import { EnemyPartyConfig, EnemyPokemonConfig, generateModifierType, initBattleWithEnemyConfig, leaveEncounterWithoutBattle, loadCustomMovesForEncounter, setEncounterRewards, transitionMysteryEncounterIntroVisuals, } from "#app/data/mystery-encounters/utils/encounter-phase-utils";
import { modifierTypes, PokemonHeldItemModifierType } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -58,8 +58,8 @@ export const TrashToTreasureEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculate boss mon
const bossSpecies = getPokemonSpecies(Species.GARBODOR);
@ -78,10 +78,10 @@ export const TrashToTreasureEncounter: MysteryEncounter =
encounter.enemyPartyConfigs = [ config ];
// Load animations/sfx for Garbodor fight start moves
loadCustomMovesForEncounter(scene, [ Moves.TOXIC, Moves.AMNESIA ]);
loadCustomMovesForEncounter([ Moves.TOXIC, Moves.AMNESIA ]);
scene.loadSe("PRSFX- Dig2", "battle_anims", "PRSFX- Dig2.wav");
scene.loadSe("PRSFX- Venom Drench", "battle_anims", "PRSFX- Venom Drench.wav");
gScene.loadSe("PRSFX- Dig2", "battle_anims", "PRSFX- Dig2.wav");
gScene.loadSe("PRSFX- Venom Drench", "battle_anims", "PRSFX- Venom Drench.wav");
encounter.setDialogueToken("costMultiplier", SHOP_ITEM_COST_MULTIPLIER.toString());
@ -99,24 +99,24 @@ export const TrashToTreasureEncounter: MysteryEncounter =
},
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Play Dig2 and then Venom Drench sfx
doGarbageDig(scene);
doGarbageDig();
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Gain 2 Leftovers and 2 Shell Bell
await transitionMysteryEncounterIntroVisuals(scene);
await tryApplyDigRewardItems(scene);
await transitionMysteryEncounterIntroVisuals();
await tryApplyDigRewardItems();
const blackSludge = generateModifierType(scene, modifierTypes.MYSTERY_ENCOUNTER_BLACK_SLUDGE, [ SHOP_ITEM_COST_MULTIPLIER ]);
const blackSludge = generateModifierType(modifierTypes.MYSTERY_ENCOUNTER_BLACK_SLUDGE, [ SHOP_ITEM_COST_MULTIPLIER ]);
const modifier = blackSludge?.newModifier();
if (modifier) {
await scene.addModifier(modifier, false, false, false, true);
scene.playSound("battle_anims/PRSFX- Venom Drench", { volume: 2 });
await showEncounterText(scene, i18next.t("battle:rewardGain", { modifierName: modifier.type.name }), null, undefined, true);
await gScene.addModifier(modifier, false, false, false, true);
gScene.playSound("battle_anims/PRSFX- Venom Drench", { volume: 2 });
await showEncounterText(i18next.t("battle:rewardGain", { modifierName: modifier.type.name }), null, undefined, true);
}
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -132,15 +132,15 @@ export const TrashToTreasureEncounter: MysteryEncounter =
},
],
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Investigate garbage, battle Gmax Garbodor
scene.setFieldScale(0.75);
await showEncounterText(scene, `${namespace}:option.2.selected_2`);
await transitionMysteryEncounterIntroVisuals(scene);
gScene.setFieldScale(0.75);
await showEncounterText(`${namespace}:option.2.selected_2`);
await transitionMysteryEncounterIntroVisuals();
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
setEncounterRewards(scene, { guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.GREAT ], fillRemaining: true });
setEncounterRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.GREAT ], fillRemaining: true });
encounter.startOfBattleEffects.push(
{
sourceBattlerIndex: BattlerIndex.ENEMY,
@ -154,81 +154,81 @@ export const TrashToTreasureEncounter: MysteryEncounter =
move: new PokemonMove(Moves.AMNESIA),
ignorePp: true
});
await initBattleWithEnemyConfig(scene, encounter.enemyPartyConfigs[0]);
await initBattleWithEnemyConfig(encounter.enemyPartyConfigs[0]);
})
.build()
)
.build();
async function tryApplyDigRewardItems(scene: BattleScene) {
const shellBell = generateModifierType(scene, modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
const leftovers = generateModifierType(scene, modifierTypes.LEFTOVERS) as PokemonHeldItemModifierType;
async function tryApplyDigRewardItems() {
const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType;
const leftovers = generateModifierType(modifierTypes.LEFTOVERS) as PokemonHeldItemModifierType;
const party = scene.getParty();
const party = gScene.getParty();
// Iterate over the party until an item was successfully given
// First leftovers
for (const pokemon of party) {
const heldItems = scene.findModifiers(m => m instanceof PokemonHeldItemModifier
const heldItems = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier
&& m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[];
const existingLeftovers = heldItems.find(m => m instanceof TurnHealModifier) as TurnHealModifier;
if (!existingLeftovers || existingLeftovers.getStackCount() < existingLeftovers.getMaxStackCount(scene)) {
await applyModifierTypeToPlayerPokemon(scene, pokemon, leftovers);
if (!existingLeftovers || existingLeftovers.getStackCount() < existingLeftovers.getMaxStackCount()) {
await applyModifierTypeToPlayerPokemon(pokemon, leftovers);
break;
}
}
// Second leftovers
for (const pokemon of party) {
const heldItems = scene.findModifiers(m => m instanceof PokemonHeldItemModifier
const heldItems = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier
&& m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[];
const existingLeftovers = heldItems.find(m => m instanceof TurnHealModifier) as TurnHealModifier;
if (!existingLeftovers || existingLeftovers.getStackCount() < existingLeftovers.getMaxStackCount(scene)) {
await applyModifierTypeToPlayerPokemon(scene, pokemon, leftovers);
if (!existingLeftovers || existingLeftovers.getStackCount() < existingLeftovers.getMaxStackCount()) {
await applyModifierTypeToPlayerPokemon(pokemon, leftovers);
break;
}
}
scene.playSound("item_fanfare");
await showEncounterText(scene, i18next.t("battle:rewardGainCount", { modifierName: leftovers.name, count: 2 }), null, undefined, true);
gScene.playSound("item_fanfare");
await showEncounterText(i18next.t("battle:rewardGainCount", { modifierName: leftovers.name, count: 2 }), null, undefined, true);
// First Shell bell
for (const pokemon of party) {
const heldItems = scene.findModifiers(m => m instanceof PokemonHeldItemModifier
const heldItems = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier
&& m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[];
const existingShellBell = heldItems.find(m => m instanceof HitHealModifier) as HitHealModifier;
if (!existingShellBell || existingShellBell.getStackCount() < existingShellBell.getMaxStackCount(scene)) {
await applyModifierTypeToPlayerPokemon(scene, pokemon, shellBell);
if (!existingShellBell || existingShellBell.getStackCount() < existingShellBell.getMaxStackCount()) {
await applyModifierTypeToPlayerPokemon(pokemon, shellBell);
break;
}
}
// Second Shell bell
for (const pokemon of party) {
const heldItems = scene.findModifiers(m => m instanceof PokemonHeldItemModifier
const heldItems = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier
&& m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[];
const existingShellBell = heldItems.find(m => m instanceof HitHealModifier) as HitHealModifier;
if (!existingShellBell || existingShellBell.getStackCount() < existingShellBell.getMaxStackCount(scene)) {
await applyModifierTypeToPlayerPokemon(scene, pokemon, shellBell);
if (!existingShellBell || existingShellBell.getStackCount() < existingShellBell.getMaxStackCount()) {
await applyModifierTypeToPlayerPokemon(pokemon, shellBell);
break;
}
}
scene.playSound("item_fanfare");
await showEncounterText(scene, i18next.t("battle:rewardGainCount", { modifierName: shellBell.name, count: 2 }), null, undefined, true);
gScene.playSound("item_fanfare");
await showEncounterText(i18next.t("battle:rewardGainCount", { modifierName: shellBell.name, count: 2 }), null, undefined, true);
}
function doGarbageDig(scene: BattleScene) {
scene.playSound("battle_anims/PRSFX- Dig2");
scene.time.delayedCall(SOUND_EFFECT_WAIT_TIME, () => {
scene.playSound("battle_anims/PRSFX- Dig2");
scene.playSound("battle_anims/PRSFX- Venom Drench", { volume: 2 });
function doGarbageDig() {
gScene.playSound("battle_anims/PRSFX- Dig2");
gScene.time.delayedCall(SOUND_EFFECT_WAIT_TIME, () => {
gScene.playSound("battle_anims/PRSFX- Dig2");
gScene.playSound("battle_anims/PRSFX- Venom Drench", { volume: 2 });
});
scene.time.delayedCall(SOUND_EFFECT_WAIT_TIME * 2, () => {
scene.playSound("battle_anims/PRSFX- Dig2");
gScene.time.delayedCall(SOUND_EFFECT_WAIT_TIME * 2, () => {
gScene.playSound("battle_anims/PRSFX- Dig2");
});
}

View File

@ -4,7 +4,7 @@ import { CHARMING_MOVES } from "#app/data/mystery-encounters/requirements/requir
import Pokemon, { EnemyPokemon, PokemonMove } from "#app/field/pokemon";
import { getPartyLuckValue } from "#app/modifier/modifier-type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MoveRequirement, PersistentModifierRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
import { MysteryEncounterTier } from "#enums/mystery-encounter-tier";
@ -45,14 +45,14 @@ export const UncommonBreedEncounter: MysteryEncounter =
text: `${namespace}:intro`,
},
])
.withOnInit((scene: BattleScene) => {
const encounter = scene.currentBattle.mysteryEncounter!;
.withOnInit(() => {
const encounter = gScene.currentBattle.mysteryEncounter!;
// Calculate boss mon
// Level equal to 2 below highest party member
const level = getHighestLevelPlayerPokemon(scene, false, true).level - 2;
const species = scene.arena.randomSpecies(scene.currentBattle.waveIndex, level, 0, getPartyLuckValue(scene.getParty()), true);
const pokemon = new EnemyPokemon(scene, species, level, TrainerSlot.NONE, true);
const level = getHighestLevelPlayerPokemon(false, true).level - 2;
const species = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true);
const pokemon = new EnemyPokemon(species, level, TrainerSlot.NONE, true);
// Pokemon will always have one of its egg moves in its moveset
const eggMoves = pokemon.getEggMoves();
@ -73,7 +73,7 @@ export const UncommonBreedEncounter: MysteryEncounter =
}
// Defense/Spd buffs below wave 50, +1 to all stats otherwise
const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = scene.currentBattle.waveIndex < 50 ?
const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = gScene.currentBattle.waveIndex < 50 ?
[ Stat.DEF, Stat.SPDEF, Stat.SPD ] :
[ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ];
@ -85,8 +85,8 @@ export const UncommonBreedEncounter: MysteryEncounter =
isBoss: false,
tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ],
mysteryEncounterBattleEffects: (pokemon: Pokemon) => {
queueEncounterMessage(pokemon.scene, `${namespace}:option.1.stat_boost`);
pokemon.scene.unshiftPhase(new StatStageChangePhase(pokemon.scene, pokemon.getBattlerIndex(), true, statChangesForBattle, 1));
queueEncounterMessage(`${namespace}:option.1.stat_boost`);
gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1));
}
}],
};
@ -105,15 +105,15 @@ export const UncommonBreedEncounter: MysteryEncounter =
];
encounter.setDialogueToken("enemyPokemon", pokemon.getNameToRender());
scene.loadSe("PRSFX- Spotlight2", "battle_anims", "PRSFX- Spotlight2.wav");
gScene.loadSe("PRSFX- Spotlight2", "battle_anims", "PRSFX- Spotlight2.wav");
return true;
})
.withOnVisualsStart((scene: BattleScene) => {
.withOnVisualsStart(() => {
// Animate the pokemon
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const pokemonSprite = encounter.introVisuals!.getSprites();
scene.tweens.add({ // Bounce at the end
gScene.tweens.add({ // Bounce at the end
targets: pokemonSprite,
duration: 300,
ease: "Cubic.easeOut",
@ -122,7 +122,7 @@ export const UncommonBreedEncounter: MysteryEncounter =
loop: 1,
});
scene.time.delayedCall(500, () => scene.playSound("battle_anims/PRSFX- Spotlight2"));
gScene.time.delayedCall(500, () => gScene.playSound("battle_anims/PRSFX- Spotlight2"));
return true;
})
.setLocalizationKey(`${namespace}`)
@ -139,9 +139,9 @@ export const UncommonBreedEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Pick battle
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const eggMove = encounter.misc.eggMove;
if (!isNullOrUndefined(eggMove)) {
@ -159,8 +159,8 @@ export const UncommonBreedEncounter: MysteryEncounter =
});
}
setEncounterRewards(scene, { fillRemaining: true });
await initBattleWithEnemyConfig(scene, encounter.enemyPartyConfigs[0]);
setEncounterRewards({ fillRemaining: true });
await initBattleWithEnemyConfig(encounter.enemyPartyConfigs[0]);
}
)
.withOption(
@ -177,33 +177,33 @@ export const UncommonBreedEncounter: MysteryEncounter =
}
]
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Give it some food
// Remove 4 random berries from player's party
// Get all player berry items, remove from party, and store reference
const berryItems: BerryModifier[] = scene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[];
const berryItems: BerryModifier[] = gScene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[];
for (let i = 0; i < 4; i++) {
const index = randSeedInt(berryItems.length);
const randBerry = berryItems[index];
randBerry.stackCount--;
if (randBerry.stackCount === 0) {
scene.removeModifier(randBerry);
gScene.removeModifier(randBerry);
berryItems.splice(index, 1);
}
}
await scene.updateModifiers(true, true);
await gScene.updateModifiers(true, true);
// Pokemon joins the team, with 2 egg moves
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const pokemon = encounter.misc.pokemon;
// Give 1 additional egg move
givePokemonExtraEggMove(pokemon, encounter.misc.eggMove);
await catchPokemon(scene, pokemon, null, PokeballType.POKEBALL, false);
setEncounterRewards(scene, { fillRemaining: true });
leaveEncounterWithoutBattle(scene);
await catchPokemon(pokemon, null, PokeballType.POKEBALL, false);
setEncounterRewards({ fillRemaining: true });
leaveEncounterWithoutBattle();
})
.build()
)
@ -221,10 +221,10 @@ export const UncommonBreedEncounter: MysteryEncounter =
}
]
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Attract the pokemon with a move
// Pokemon joins the team, with 2 egg moves and IVs rolled an additional time
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
const pokemon = encounter.misc.pokemon;
// Give 1 additional egg move
@ -236,12 +236,12 @@ export const UncommonBreedEncounter: MysteryEncounter =
return newValue > iv ? newValue : iv;
});
await catchPokemon(scene, pokemon, null, PokeballType.POKEBALL, false);
await catchPokemon(pokemon, null, PokeballType.POKEBALL, false);
if (encounter.selectedOption?.primaryPokemon?.id) {
setEncounterExp(scene, encounter.selectedOption.primaryPokemon.id, pokemon.getExpValue(), false);
setEncounterExp(encounter.selectedOption.primaryPokemon.id, pokemon.getExpValue(), false);
}
setEncounterRewards(scene, { fillRemaining: true });
leaveEncounterWithoutBattle(scene);
setEncounterRewards({ fillRemaining: true });
leaveEncounterWithoutBattle();
})
.build()
)

View File

@ -1,7 +1,7 @@
import { Type } from "#app/data/type";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import { Species } from "#enums/species";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import MysteryEncounter, { MysteryEncounterBuilder } from "#app/data/mystery-encounters/mystery-encounter";
import { MysteryEncounterOptionBuilder } from "#app/data/mystery-encounters/mystery-encounter-option";
import { EnemyPartyConfig, EnemyPokemonConfig, generateModifierType, initBattleWithEnemyConfig, leaveEncounterWithoutBattle, setEncounterRewards, } from "../utils/encounter-phase-utils";
@ -138,21 +138,21 @@ export const WeirdDreamEncounter: MysteryEncounter =
.withTitle(`${namespace}:title`)
.withDescription(`${namespace}:description`)
.withQuery(`${namespace}:query`)
.withOnInit((scene: BattleScene) => {
scene.loadBgm("mystery_encounter_weird_dream", "mystery_encounter_weird_dream.mp3");
.withOnInit(() => {
gScene.loadBgm("mystery_encounter_weird_dream", "mystery_encounter_weird_dream.mp3");
// Calculate all the newly transformed Pokemon and begin asset load
const teamTransformations = getTeamTransformations(scene);
const teamTransformations = getTeamTransformations();
const loadAssets = teamTransformations.map(t => (t.newPokemon as PlayerPokemon).loadAssets());
scene.currentBattle.mysteryEncounter!.misc = {
gScene.currentBattle.mysteryEncounter!.misc = {
teamTransformations,
loadAssets
};
return true;
})
.withOnVisualsStart((scene: BattleScene) => {
scene.fadeAndSwitchBgm("mystery_encounter_weird_dream");
.withOnVisualsStart(() => {
gScene.fadeAndSwitchBgm("mystery_encounter_weird_dream");
return true;
})
.withOption(
@ -168,25 +168,25 @@ export const WeirdDreamEncounter: MysteryEncounter =
}
],
})
.withPreOptionPhase(async (scene: BattleScene) => {
.withPreOptionPhase(async () => {
// Play the animation as the player goes through the dialogue
scene.time.delayedCall(1000, () => {
doShowDreamBackground(scene);
gScene.time.delayedCall(1000, () => {
doShowDreamBackground();
});
for (const transformation of scene.currentBattle.mysteryEncounter!.misc.teamTransformations) {
scene.removePokemonFromPlayerParty(transformation.previousPokemon, false);
scene.getParty().push(transformation.newPokemon);
for (const transformation of gScene.currentBattle.mysteryEncounter!.misc.teamTransformations) {
gScene.removePokemonFromPlayerParty(transformation.previousPokemon, false);
gScene.getParty().push(transformation.newPokemon);
}
})
.withOptionPhase(async (scene: BattleScene) => {
.withOptionPhase(async () => {
// Starts cutscene dialogue, but does not await so that cutscene plays as player goes through dialogue
const cutsceneDialoguePromise = showEncounterText(scene, `${namespace}:option.1.cutscene`);
const cutsceneDialoguePromise = showEncounterText(`${namespace}:option.1.cutscene`);
// Change the entire player's party
// Wait for all new Pokemon assets to be loaded before showing transformation animations
await Promise.all(scene.currentBattle.mysteryEncounter!.misc.loadAssets);
const transformations = scene.currentBattle.mysteryEncounter!.misc.teamTransformations;
await Promise.all(gScene.currentBattle.mysteryEncounter!.misc.loadAssets);
const transformations = gScene.currentBattle.mysteryEncounter!.misc.teamTransformations;
// If there are 1-3 transformations, do them centered back to back
// Otherwise, the first 3 transformations are executed side-by-side, then any remaining 1-3 transformations occur in those same respective positions
@ -195,21 +195,21 @@ export const WeirdDreamEncounter: MysteryEncounter =
const pokemon1 = transformation.previousPokemon;
const pokemon2 = transformation.newPokemon;
await doPokemonTransformationSequence(scene, pokemon1, pokemon2, TransformationScreenPosition.CENTER);
await doPokemonTransformationSequence(pokemon1, pokemon2, TransformationScreenPosition.CENTER);
}
} else {
await doSideBySideTransformations(scene, transformations);
await doSideBySideTransformations(transformations);
}
// Make sure player has finished cutscene dialogue
await cutsceneDialoguePromise;
doHideDreamBackground(scene);
await showEncounterText(scene, `${namespace}:option.1.dream_complete`);
doHideDreamBackground();
await showEncounterText(`${namespace}:option.1.dream_complete`);
await doNewTeamPostProcess(scene, transformations);
setEncounterRewards(scene, { guaranteedModifierTypeFuncs: [ modifierTypes.MEMORY_MUSHROOM, modifierTypes.ROGUE_BALL, modifierTypes.MINT, modifierTypes.MINT, modifierTypes.MINT ], fillRemaining: false });
leaveEncounterWithoutBattle(scene, true);
await doNewTeamPostProcess(transformations);
setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.MEMORY_MUSHROOM, modifierTypes.ROGUE_BALL, modifierTypes.MINT, modifierTypes.MINT, modifierTypes.MINT ], fillRemaining: false });
leaveEncounterWithoutBattle(true);
})
.build()
)
@ -223,9 +223,9 @@ export const WeirdDreamEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Battle your "future" team for some item rewards
const transformations: PokemonTransformation[] = scene.currentBattle.mysteryEncounter!.misc.teamTransformations;
const transformations: PokemonTransformation[] = gScene.currentBattle.mysteryEncounter!.misc.teamTransformations;
// Uses the pokemon that player's party would have transformed into
const enemyPokemonConfigs: EnemyPokemonConfig[] = [];
@ -233,7 +233,7 @@ export const WeirdDreamEncounter: MysteryEncounter =
const newPokemon = transformation.newPokemon;
const previousPokemon = transformation.previousPokemon;
await postProcessTransformedPokemon(scene, previousPokemon, newPokemon, newPokemon.species.getRootSpeciesId(), true);
await postProcessTransformedPokemon(previousPokemon, newPokemon, newPokemon.species.getRootSpeciesId(), true);
const dataSource = new PokemonData(newPokemon);
dataSource.player = false;
@ -251,7 +251,7 @@ export const WeirdDreamEncounter: MysteryEncounter =
if (shouldGetOldGateau(newPokemon)) {
const stats = getOldGateauBoostedStats(newPokemon);
newPokemonHeldItemConfigs.push({
modifier: generateModifierType(scene, modifierTypes.MYSTERY_ENCOUNTER_OLD_GATEAU, [ OLD_GATEAU_STATS_UP, stats ]) as PokemonHeldItemModifierType,
modifier: generateModifierType(modifierTypes.MYSTERY_ENCOUNTER_OLD_GATEAU, [ OLD_GATEAU_STATS_UP, stats ]) as PokemonHeldItemModifierType,
stackCount: 1,
isTransferable: false
});
@ -268,7 +268,7 @@ export const WeirdDreamEncounter: MysteryEncounter =
enemyPokemonConfigs.push(enemyConfig);
}
const genderIndex = scene.gameData.gender ?? PlayerGender.UNSET;
const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET;
const trainerConfig = trainerConfigs[genderIndex === PlayerGender.FEMALE ? TrainerType.FUTURE_SELF_F : TrainerType.FUTURE_SELF_M].clone();
trainerConfig.setPartyTemplates(new TrainerPartyTemplate(transformations.length, PartyMemberStrength.STRONG));
const enemyPartyConfig: EnemyPartyConfig = {
@ -280,7 +280,7 @@ export const WeirdDreamEncounter: MysteryEncounter =
const onBeforeRewards = () => {
// Before battle rewards, unlock the passive on a pokemon in the player's team for the rest of the run (not permanently)
// One random pokemon will get its passive unlocked
const passiveDisabledPokemon = scene.getParty().filter(p => !p.passive);
const passiveDisabledPokemon = gScene.getParty().filter(p => !p.passive);
if (passiveDisabledPokemon?.length > 0) {
const enablePassiveMon = passiveDisabledPokemon[randSeedInt(passiveDisabledPokemon.length)];
enablePassiveMon.passive = true;
@ -288,10 +288,10 @@ export const WeirdDreamEncounter: MysteryEncounter =
}
};
setEncounterRewards(scene, { guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.GREAT, ModifierTier.GREAT ], fillRemaining: false }, undefined, onBeforeRewards);
setEncounterRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.GREAT, ModifierTier.GREAT ], fillRemaining: false }, undefined, onBeforeRewards);
await showEncounterText(scene, `${namespace}:option.2.selected_2`, null, undefined, true);
await initBattleWithEnemyConfig(scene, enemyPartyConfig);
await showEncounterText(`${namespace}:option.2.selected_2`, null, undefined, true);
await initBattleWithEnemyConfig(enemyPartyConfig);
}
)
.withSimpleOption(
@ -304,9 +304,9 @@ export const WeirdDreamEncounter: MysteryEncounter =
},
],
},
async (scene: BattleScene) => {
async () => {
// Leave, reduce party levels by 10%
for (const pokemon of scene.getParty()) {
for (const pokemon of gScene.getParty()) {
pokemon.level = Math.max(Math.ceil((100 - PERCENT_LEVEL_LOSS_ON_REFUSE) / 100 * pokemon.level), 1);
pokemon.exp = getLevelTotalExp(pokemon.level, pokemon.species.growthRate);
pokemon.levelExp = 0;
@ -315,7 +315,7 @@ export const WeirdDreamEncounter: MysteryEncounter =
await pokemon.updateInfo();
}
leaveEncounterWithoutBattle(scene, true);
leaveEncounterWithoutBattle(true);
return true;
}
)
@ -328,8 +328,8 @@ interface PokemonTransformation {
heldItems: PokemonHeldItemModifier[];
}
function getTeamTransformations(scene: BattleScene): PokemonTransformation[] {
const party = scene.getParty();
function getTeamTransformations(): PokemonTransformation[] {
const party = gScene.getParty();
// Removes all pokemon from the party
const alreadyUsedSpecies: PokemonSpecies[] = party.map(p => p.species);
const pokemonTransformations: PokemonTransformation[] = party.map(p => {
@ -378,37 +378,37 @@ function getTeamTransformations(scene: BattleScene): PokemonTransformation[] {
for (const transformation of pokemonTransformations) {
const newAbilityIndex = randSeedInt(transformation.newSpecies.getAbilityCount());
transformation.newPokemon = scene.addPlayerPokemon(transformation.newSpecies, transformation.previousPokemon.level, newAbilityIndex, undefined);
transformation.newPokemon = gScene.addPlayerPokemon(transformation.newSpecies, transformation.previousPokemon.level, newAbilityIndex, undefined);
}
return pokemonTransformations;
}
async function doNewTeamPostProcess(scene: BattleScene, transformations: PokemonTransformation[]) {
async function doNewTeamPostProcess(transformations: PokemonTransformation[]) {
let atLeastOneNewStarter = false;
for (const transformation of transformations) {
const previousPokemon = transformation.previousPokemon;
const newPokemon = transformation.newPokemon;
const speciesRootForm = newPokemon.species.getRootSpeciesId();
if (await postProcessTransformedPokemon(scene, previousPokemon, newPokemon, speciesRootForm)) {
if (await postProcessTransformedPokemon(previousPokemon, newPokemon, speciesRootForm)) {
atLeastOneNewStarter = true;
}
// Copy old items to new pokemon
for (const item of transformation.heldItems) {
item.pokemonId = newPokemon.id;
await scene.addModifier(item, false, false, false, true);
await gScene.addModifier(item, false, false, false, true);
}
// Any pokemon that is below 570 BST gets +20 permanent BST to 3 stats
if (shouldGetOldGateau(newPokemon)) {
const stats = getOldGateauBoostedStats(newPokemon);
const modType = modifierTypes.MYSTERY_ENCOUNTER_OLD_GATEAU()
.generateType(scene.getParty(), [ OLD_GATEAU_STATS_UP, stats ])
.generateType(gScene.getParty(), [ OLD_GATEAU_STATS_UP, stats ])
?.withIdFromFunc(modifierTypes.MYSTERY_ENCOUNTER_OLD_GATEAU);
const modifier = modType?.newModifier(newPokemon);
if (modifier) {
await scene.addModifier(modifier, false, false, false, true);
await gScene.addModifier(modifier, false, false, false, true);
}
}
@ -417,7 +417,7 @@ async function doNewTeamPostProcess(scene: BattleScene, transformations: Pokemon
}
// One random pokemon will get its passive unlocked
const passiveDisabledPokemon = scene.getParty().filter(p => !p.passive);
const passiveDisabledPokemon = gScene.getParty().filter(p => !p.passive);
if (passiveDisabledPokemon?.length > 0) {
const enablePassiveMon = passiveDisabledPokemon[randSeedInt(passiveDisabledPokemon.length)];
enablePassiveMon.passive = true;
@ -426,7 +426,7 @@ async function doNewTeamPostProcess(scene: BattleScene, transformations: Pokemon
// If at least one new starter was unlocked, play 1 fanfare
if (atLeastOneNewStarter) {
scene.playSound("level_up_fanfare");
gScene.playSound("level_up_fanfare");
}
}
@ -439,14 +439,14 @@ async function doNewTeamPostProcess(scene: BattleScene, transformations: Pokemon
* @param speciesRootForm
* @param forBattle Default `false`. If false, will perform achievements and dex unlocks for the player.
*/
async function postProcessTransformedPokemon(scene: BattleScene, previousPokemon: PlayerPokemon, newPokemon: PlayerPokemon, speciesRootForm: Species, forBattle: boolean = false): Promise<boolean> {
async function postProcessTransformedPokemon(previousPokemon: PlayerPokemon, newPokemon: PlayerPokemon, speciesRootForm: Species, forBattle: boolean = false): Promise<boolean> {
let isNewStarter = false;
// Roll HA a second time
if (newPokemon.species.abilityHidden) {
const hiddenIndex = newPokemon.species.ability2 ? 2 : 1;
if (newPokemon.abilityIndex < hiddenIndex) {
const hiddenAbilityChance = new IntegerHolder(256);
scene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance);
gScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance);
const hasHiddenAbility = !randSeedInt(hiddenAbilityChance.value);
@ -468,26 +468,26 @@ async function postProcessTransformedPokemon(scene: BattleScene, previousPokemon
// For pokemon at/below 570 BST or any shiny pokemon, unlock it permanently as if you had caught it
if (!forBattle && (newPokemon.getSpeciesForm().getBaseStatTotal() <= NON_LEGENDARY_BST_THRESHOLD || newPokemon.isShiny())) {
if (newPokemon.getSpeciesForm().abilityHidden && newPokemon.abilityIndex === newPokemon.getSpeciesForm().getAbilityCount() - 1) {
scene.validateAchv(achvs.HIDDEN_ABILITY);
gScene.validateAchv(achvs.HIDDEN_ABILITY);
}
if (newPokemon.species.subLegendary) {
scene.validateAchv(achvs.CATCH_SUB_LEGENDARY);
gScene.validateAchv(achvs.CATCH_SUB_LEGENDARY);
}
if (newPokemon.species.legendary) {
scene.validateAchv(achvs.CATCH_LEGENDARY);
gScene.validateAchv(achvs.CATCH_LEGENDARY);
}
if (newPokemon.species.mythical) {
scene.validateAchv(achvs.CATCH_MYTHICAL);
gScene.validateAchv(achvs.CATCH_MYTHICAL);
}
scene.gameData.updateSpeciesDexIvs(newPokemon.species.getRootSpeciesId(true), newPokemon.ivs);
const newStarterUnlocked = await scene.gameData.setPokemonCaught(newPokemon, true, false, false);
gScene.gameData.updateSpeciesDexIvs(newPokemon.species.getRootSpeciesId(true), newPokemon.ivs);
const newStarterUnlocked = await gScene.gameData.setPokemonCaught(newPokemon, true, false, false);
if (newStarterUnlocked) {
isNewStarter = true;
await showEncounterText(scene, i18next.t("battle:addedAsAStarter", { pokemonName: getPokemonSpecies(speciesRootForm).getName() }));
await showEncounterText(i18next.t("battle:addedAsAStarter", { pokemonName: getPokemonSpecies(speciesRootForm).getName() }));
}
}
@ -503,8 +503,8 @@ async function postProcessTransformedPokemon(scene: BattleScene, previousPokemon
});
// For pokemon that the player owns (including ones just caught), gain a candy
if (!forBattle && !!scene.gameData.dexData[speciesRootForm].caughtAttr) {
scene.gameData.addStarterCandy(getPokemonSpecies(speciesRootForm), 1);
if (!forBattle && !!gScene.gameData.dexData[speciesRootForm].caughtAttr) {
gScene.gameData.addStarterCandy(getPokemonSpecies(speciesRootForm), 1);
}
// Set the moveset of the new pokemon to be the same as previous, but with 1 egg move and 1 (attempted) STAB move of the new species
@ -514,7 +514,7 @@ async function postProcessTransformedPokemon(scene: BattleScene, previousPokemon
newPokemon.moveset = previousPokemon.moveset.slice(0);
const newEggMoveIndex = await addEggMoveToNewPokemonMoveset(scene, newPokemon, speciesRootForm, forBattle);
const newEggMoveIndex = await addEggMoveToNewPokemonMoveset(newPokemon, speciesRootForm, forBattle);
// Try to add a favored STAB move (might fail if Pokemon already knows a bunch of moves from newPokemonGeneratedMoveset)
addFavoredMoveToNewPokemonMoveset(newPokemon, newPokemonGeneratedMoveset, newEggMoveIndex);
@ -596,31 +596,31 @@ function getTransformedSpecies(originalBst: number, bstSearchRange: [number, num
return newSpecies;
}
function doShowDreamBackground(scene: BattleScene) {
const transformationContainer = scene.add.container(0, -scene.game.canvas.height / 6);
function doShowDreamBackground() {
const transformationContainer = gScene.add.container(0, -gScene.game.canvas.height / 6);
transformationContainer.name = "Dream Background";
// In case it takes a bit for video to load
const transformationStaticBg = scene.add.rectangle(0, 0, scene.game.canvas.width / 6, scene.game.canvas.height / 6, 0);
const transformationStaticBg = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0);
transformationStaticBg.setName("Black Background");
transformationStaticBg.setOrigin(0, 0);
transformationContainer.add(transformationStaticBg);
transformationStaticBg.setVisible(true);
const transformationVideoBg: Phaser.GameObjects.Video = scene.add.video(0, 0, "evo_bg").stop();
const transformationVideoBg: Phaser.GameObjects.Video = gScene.add.video(0, 0, "evo_bg").stop();
transformationVideoBg.setLoop(true);
transformationVideoBg.setOrigin(0, 0);
transformationVideoBg.setScale(0.4359673025);
transformationContainer.add(transformationVideoBg);
scene.fieldUI.add(transformationContainer);
scene.fieldUI.bringToTop(transformationContainer);
gScene.fieldUI.add(transformationContainer);
gScene.fieldUI.bringToTop(transformationContainer);
transformationVideoBg.play();
transformationContainer.setVisible(true);
transformationContainer.alpha = 0;
scene.tweens.add({
gScene.tweens.add({
targets: transformationContainer,
alpha: 1,
duration: 3000,
@ -628,39 +628,39 @@ function doShowDreamBackground(scene: BattleScene) {
});
}
function doHideDreamBackground(scene: BattleScene) {
const transformationContainer = scene.fieldUI.getByName("Dream Background");
function doHideDreamBackground() {
const transformationContainer = gScene.fieldUI.getByName("Dream Background");
scene.tweens.add({
gScene.tweens.add({
targets: transformationContainer,
alpha: 0,
duration: 3000,
ease: "Sine.easeInOut",
onComplete: () => {
scene.fieldUI.remove(transformationContainer, true);
gScene.fieldUI.remove(transformationContainer, true);
}
});
}
function doSideBySideTransformations(scene: BattleScene, transformations: PokemonTransformation[]) {
function doSideBySideTransformations(transformations: PokemonTransformation[]) {
return new Promise<void>(resolve => {
const allTransformationPromises: Promise<void>[] = [];
for (let i = 0; i < 3; i++) {
const delay = i * 4000;
scene.time.delayedCall(delay, () => {
gScene.time.delayedCall(delay, () => {
const transformation = transformations[i];
const pokemon1 = transformation.previousPokemon;
const pokemon2 = transformation.newPokemon;
const screenPosition = i as TransformationScreenPosition;
const transformationPromise = doPokemonTransformationSequence(scene, pokemon1, pokemon2, screenPosition)
const transformationPromise = doPokemonTransformationSequence(pokemon1, pokemon2, screenPosition)
.then(() => {
if (transformations.length > i + 3) {
const nextTransformationAtPosition = transformations[i + 3];
const nextPokemon1 = nextTransformationAtPosition.previousPokemon;
const nextPokemon2 = nextTransformationAtPosition.newPokemon;
allTransformationPromises.push(doPokemonTransformationSequence(scene, nextPokemon1, nextPokemon2, screenPosition));
allTransformationPromises.push(doPokemonTransformationSequence(nextPokemon1, nextPokemon2, screenPosition));
}
});
allTransformationPromises.push(transformationPromise);
@ -685,7 +685,7 @@ function doSideBySideTransformations(scene: BattleScene, transformations: Pokemo
* @param newPokemon
* @param speciesRootForm
*/
async function addEggMoveToNewPokemonMoveset(scene: BattleScene, newPokemon: PlayerPokemon, speciesRootForm: Species, forBattle: boolean = false): Promise<number | null> {
async function addEggMoveToNewPokemonMoveset(newPokemon: PlayerPokemon, speciesRootForm: Species, forBattle: boolean = false): Promise<number | null> {
let eggMoveIndex: null | number = null;
const eggMoves = newPokemon.getEggMoves()?.slice(0);
if (eggMoves) {
@ -711,8 +711,8 @@ async function addEggMoveToNewPokemonMoveset(scene: BattleScene, newPokemon: Pla
}
// For pokemon that the player owns (including ones just caught), unlock the egg move
if (!forBattle && !isNullOrUndefined(randomEggMoveIndex) && !!scene.gameData.dexData[speciesRootForm].caughtAttr) {
await scene.gameData.setEggMoveUnlocked(getPokemonSpecies(speciesRootForm), randomEggMoveIndex, true);
if (!forBattle && !isNullOrUndefined(randomEggMoveIndex) && !!gScene.gameData.dexData[speciesRootForm].caughtAttr) {
await gScene.gameData.setEggMoveUnlocked(getPokemonSpecies(speciesRootForm), randomEggMoveIndex, true);
}
}
}

View File

@ -1,7 +1,7 @@
import { OptionTextDisplay } from "#app/data/mystery-encounters/mystery-encounter-dialogue";
import { Moves } from "#app/enums/moves";
import Pokemon, { PlayerPokemon } from "#app/field/pokemon";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { Type } from "../type";
import { EncounterPokemonRequirement, EncounterSceneRequirement, MoneyRequirement, TypeRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
import { CanLearnMoveRequirement, CanLearnMoveRequirementOptions } from "./requirements/can-learn-move-requirement";
@ -9,7 +9,7 @@ import { isNullOrUndefined, randSeedInt } from "#app/utils";
import { MysteryEncounterOptionMode } from "#enums/mystery-encounter-option-mode";
export type OptionPhaseCallback = (scene: BattleScene) => Promise<void | boolean>;
export type OptionPhaseCallback = () => Promise<void | boolean>;
/**
* Used by {@linkcode MysteryEncounterOptionBuilder} class to define required/optional properties on the {@linkcode MysteryEncounterOption} class when building.
@ -76,10 +76,10 @@ export default class MysteryEncounterOption implements IMysteryEncounterOption {
* Returns true if all {@linkcode EncounterRequirement}s for the option are met
* @param scene
*/
meetsRequirements(scene: BattleScene): boolean {
return !this.requirements.some(requirement => !requirement.meetsRequirement(scene))
&& this.meetsSupportingRequirementAndSupportingPokemonSelected(scene)
&& this.meetsPrimaryRequirementAndPrimaryPokemonSelected(scene);
meetsRequirements(): boolean {
return !this.requirements.some(requirement => !requirement.meetsRequirement())
&& this.meetsSupportingRequirementAndSupportingPokemonSelected()
&& this.meetsPrimaryRequirementAndPrimaryPokemonSelected();
}
/**
@ -87,8 +87,8 @@ export default class MysteryEncounterOption implements IMysteryEncounterOption {
* @param scene
* @param pokemon
*/
pokemonMeetsPrimaryRequirements(scene: BattleScene, pokemon: Pokemon): boolean {
return !this.primaryPokemonRequirements.some(req => !req.queryParty(scene.getParty()).map(p => p.id).includes(pokemon.id));
pokemonMeetsPrimaryRequirements(pokemon: Pokemon): boolean {
return !this.primaryPokemonRequirements.some(req => !req.queryParty(gScene.getParty()).map(p => p.id).includes(pokemon.id));
}
/**
@ -98,14 +98,14 @@ export default class MysteryEncounterOption implements IMysteryEncounterOption {
* can cause scenarios where there are not enough Pokemon that are sufficient for all requirements.
* @param scene
*/
meetsPrimaryRequirementAndPrimaryPokemonSelected(scene: BattleScene): boolean {
meetsPrimaryRequirementAndPrimaryPokemonSelected(): boolean {
if (!this.primaryPokemonRequirements || this.primaryPokemonRequirements.length === 0) {
return true;
}
let qualified: PlayerPokemon[] = scene.getParty();
let qualified: PlayerPokemon[] = gScene.getParty();
for (const req of this.primaryPokemonRequirements) {
if (req.meetsRequirement(scene)) {
const queryParty = req.queryParty(scene.getParty());
if (req.meetsRequirement()) {
const queryParty = req.queryParty(gScene.getParty());
qualified = qualified.filter(pkmn => queryParty.includes(pkmn));
} else {
this.primaryPokemon = undefined;
@ -156,16 +156,16 @@ export default class MysteryEncounterOption implements IMysteryEncounterOption {
* can cause scenarios where there are not enough Pokemon that are sufficient for all requirements.
* @param scene
*/
meetsSupportingRequirementAndSupportingPokemonSelected(scene: BattleScene): boolean {
meetsSupportingRequirementAndSupportingPokemonSelected(): boolean {
if (!this.secondaryPokemonRequirements || this.secondaryPokemonRequirements.length === 0) {
this.secondaryPokemon = [];
return true;
}
let qualified: PlayerPokemon[] = scene.getParty();
let qualified: PlayerPokemon[] = gScene.getParty();
for (const req of this.secondaryPokemonRequirements) {
if (req.meetsRequirement(scene)) {
const queryParty = req.queryParty(scene.getParty());
if (req.meetsRequirement()) {
const queryParty = req.queryParty(gScene.getParty());
qualified = qualified.filter(pkmn => queryParty.includes(pkmn));
} else {
this.secondaryPokemon = [];

View File

@ -1,5 +1,5 @@
import { PlayerPokemon } from "#app/field/pokemon";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { isNullOrUndefined } from "#app/utils";
import { Abilities } from "#enums/abilities";
import { Moves } from "#enums/moves";
@ -18,8 +18,8 @@ import { SpeciesFormKey } from "#enums/species-form-key";
import { allAbilities } from "#app/data/ability";
export interface EncounterRequirement {
meetsRequirement(scene: BattleScene): boolean; // Boolean to see if a requirement is met
getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string];
meetsRequirement(): boolean; // Boolean to see if a requirement is met
getDialogueToken(pokemon?: PlayerPokemon): [string, string];
}
export abstract class EncounterSceneRequirement implements EncounterRequirement {
@ -27,14 +27,14 @@ export abstract class EncounterSceneRequirement implements EncounterRequirement
* Returns whether the EncounterSceneRequirement's... requirements, are met by the given scene
* @param partyPokemon
*/
abstract meetsRequirement(scene: BattleScene): boolean;
abstract meetsRequirement(): boolean;
/**
* Returns a dialogue token key/value pair for a given Requirement.
* Should be overridden by child Requirement classes.
* @param scene
* @param pokemon
*/
abstract getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string];
abstract getDialogueToken(pokemon?: PlayerPokemon): [string, string];
}
/**
@ -64,10 +64,10 @@ export class CombinationSceneRequirement extends EncounterSceneRequirement {
* @param scene The {@linkcode BattleScene} to check against
* @returns true if all/any requirements are met (depends on {@linkcode isAnd})
*/
override meetsRequirement(scene: BattleScene): boolean {
override meetsRequirement(): boolean {
return this.isAnd
? this.requirements.every(req => req.meetsRequirement(scene))
: this.requirements.some(req => req.meetsRequirement(scene));
? this.requirements.every(req => req.meetsRequirement())
: this.requirements.some(req => req.meetsRequirement());
}
/**
@ -77,17 +77,17 @@ export class CombinationSceneRequirement extends EncounterSceneRequirement {
* @returns A dialogue token key/value pair
* @throws An {@linkcode Error} if {@linkcode isAnd} is `true` (not supported)
*/
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
if (this.isAnd) {
throw new Error("Not implemented (Sorry)");
} else {
for (const req of this.requirements) {
if (req.meetsRequirement(scene)) {
return req.getDialogueToken(scene, pokemon);
if (req.meetsRequirement()) {
return req.getDialogueToken(pokemon);
}
}
return this.requirements[0].getDialogueToken(scene, pokemon);
return this.requirements[0].getDialogueToken(pokemon);
}
}
}
@ -100,7 +100,7 @@ export abstract class EncounterPokemonRequirement implements EncounterRequiremen
* Returns whether the EncounterPokemonRequirement's... requirements, are met by the given scene
* @param partyPokemon
*/
abstract meetsRequirement(scene: BattleScene): boolean;
abstract meetsRequirement(): boolean;
/**
* Returns all party members that are compatible with this requirement. For non pokemon related requirements, the entire party is returned.
@ -114,7 +114,7 @@ export abstract class EncounterPokemonRequirement implements EncounterRequiremen
* @param scene
* @param pokemon
*/
abstract getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string];
abstract getDialogueToken(pokemon?: PlayerPokemon): [string, string];
}
/**
@ -146,10 +146,10 @@ export class CombinationPokemonRequirement extends EncounterPokemonRequirement {
* @param scene The {@linkcode BattleScene} to check against
* @returns true if all/any requirements are met (depends on {@linkcode isAnd})
*/
override meetsRequirement(scene: BattleScene): boolean {
override meetsRequirement(): boolean {
return this.isAnd
? this.requirements.every(req => req.meetsRequirement(scene))
: this.requirements.some(req => req.meetsRequirement(scene));
? this.requirements.every(req => req.meetsRequirement())
: this.requirements.some(req => req.meetsRequirement());
}
/**
@ -173,17 +173,17 @@ export class CombinationPokemonRequirement extends EncounterPokemonRequirement {
* @returns A dialogue token key/value pair
* @throws An {@linkcode Error} if {@linkcode isAnd} is `true` (not supported)
*/
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
if (this.isAnd) {
throw new Error("Not implemented (Sorry)");
} else {
for (const req of this.requirements) {
if (req.meetsRequirement(scene)) {
return req.getDialogueToken(scene, pokemon);
if (req.meetsRequirement()) {
return req.getDialogueToken(pokemon);
}
}
return this.requirements[0].getDialogueToken(scene, pokemon);
return this.requirements[0].getDialogueToken(pokemon);
}
}
}
@ -200,12 +200,12 @@ export class PreviousEncounterRequirement extends EncounterSceneRequirement {
this.previousEncounterRequirement = previousEncounterRequirement;
}
override meetsRequirement(scene: BattleScene): boolean {
return scene.mysteryEncounterSaveData.encounteredEvents.some(e => e.type === this.previousEncounterRequirement);
override meetsRequirement(): boolean {
return gScene.mysteryEncounterSaveData.encounteredEvents.some(e => e.type === this.previousEncounterRequirement);
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
return [ "previousEncounter", scene.mysteryEncounterSaveData.encounteredEvents.find(e => e.type === this.previousEncounterRequirement)?.[0].toString() ?? "" ];
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "previousEncounter", gScene.mysteryEncounterSaveData.encounteredEvents.find(e => e.type === this.previousEncounterRequirement)?.[0].toString() ?? "" ];
}
}
@ -222,9 +222,9 @@ export class WaveRangeRequirement extends EncounterSceneRequirement {
this.waveRange = waveRange;
}
override meetsRequirement(scene: BattleScene): boolean {
override meetsRequirement(): boolean {
if (!isNullOrUndefined(this.waveRange) && this.waveRange[0] <= this.waveRange[1]) {
const waveIndex = scene.currentBattle.waveIndex;
const waveIndex = gScene.currentBattle.waveIndex;
if (waveIndex >= 0 && (this.waveRange[0] >= 0 && this.waveRange[0] > waveIndex) || (this.waveRange[1] >= 0 && this.waveRange[1] < waveIndex)) {
return false;
}
@ -232,8 +232,8 @@ export class WaveRangeRequirement extends EncounterSceneRequirement {
return true;
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
return [ "waveIndex", scene.currentBattle.waveIndex.toString() ];
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "waveIndex", gScene.currentBattle.waveIndex.toString() ];
}
}
@ -257,12 +257,12 @@ export class WaveModulusRequirement extends EncounterSceneRequirement {
this.modulusValue = modulusValue;
}
override meetsRequirement(scene: BattleScene): boolean {
return this.waveModuli.includes(scene.currentBattle.waveIndex % this.modulusValue);
override meetsRequirement(): boolean {
return this.waveModuli.includes(gScene.currentBattle.waveIndex % this.modulusValue);
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
return [ "waveIndex", scene.currentBattle.waveIndex.toString() ];
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "waveIndex", gScene.currentBattle.waveIndex.toString() ];
}
}
@ -274,8 +274,8 @@ export class TimeOfDayRequirement extends EncounterSceneRequirement {
this.requiredTimeOfDay = Array.isArray(timeOfDay) ? timeOfDay : [ timeOfDay ];
}
override meetsRequirement(scene: BattleScene): boolean {
const timeOfDay = scene.arena?.getTimeOfDay();
override meetsRequirement(): boolean {
const timeOfDay = gScene.arena?.getTimeOfDay();
if (!isNullOrUndefined(timeOfDay) && this.requiredTimeOfDay?.length > 0 && !this.requiredTimeOfDay.includes(timeOfDay)) {
return false;
}
@ -283,8 +283,8 @@ export class TimeOfDayRequirement extends EncounterSceneRequirement {
return true;
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
return [ "timeOfDay", TimeOfDay[scene.arena.getTimeOfDay()].toLocaleLowerCase() ];
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "timeOfDay", TimeOfDay[gScene.arena.getTimeOfDay()].toLocaleLowerCase() ];
}
}
@ -296,8 +296,8 @@ export class WeatherRequirement extends EncounterSceneRequirement {
this.requiredWeather = Array.isArray(weather) ? weather : [ weather ];
}
override meetsRequirement(scene: BattleScene): boolean {
const currentWeather = scene.arena.weather?.weatherType;
override meetsRequirement(): boolean {
const currentWeather = gScene.arena.weather?.weatherType;
if (!isNullOrUndefined(currentWeather) && this.requiredWeather?.length > 0 && !this.requiredWeather.includes(currentWeather!)) {
return false;
}
@ -305,8 +305,8 @@ export class WeatherRequirement extends EncounterSceneRequirement {
return true;
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
const currentWeather = scene.arena.weather?.weatherType;
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const currentWeather = gScene.arena.weather?.weatherType;
let token = "";
if (!isNullOrUndefined(currentWeather)) {
token = WeatherType[currentWeather].replace("_", " ").toLocaleLowerCase();
@ -331,9 +331,9 @@ export class PartySizeRequirement extends EncounterSceneRequirement {
this.excludeDisallowedPokemon = excludeDisallowedPokemon;
}
override meetsRequirement(scene: BattleScene): boolean {
override meetsRequirement(): boolean {
if (!isNullOrUndefined(this.partySizeRange) && this.partySizeRange[0] <= this.partySizeRange[1]) {
const partySize = this.excludeDisallowedPokemon ? scene.getParty().filter(p => p.isAllowedInBattle()).length : scene.getParty().length;
const partySize = this.excludeDisallowedPokemon ? gScene.getParty().filter(p => p.isAllowedInBattle()).length : gScene.getParty().length;
if (partySize >= 0 && (this.partySizeRange[0] >= 0 && this.partySizeRange[0] > partySize) || (this.partySizeRange[1] >= 0 && this.partySizeRange[1] < partySize)) {
return false;
}
@ -342,8 +342,8 @@ export class PartySizeRequirement extends EncounterSceneRequirement {
return true;
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
return [ "partySize", scene.getParty().length.toString() ];
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "partySize", gScene.getParty().length.toString() ];
}
}
@ -357,14 +357,14 @@ export class PersistentModifierRequirement extends EncounterSceneRequirement {
this.requiredHeldItemModifiers = Array.isArray(heldItem) ? heldItem : [ heldItem ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredHeldItemModifiers?.length < 0) {
return false;
}
let modifierCount = 0;
this.requiredHeldItemModifiers.forEach(modifier => {
const matchingMods = scene.findModifiers(m => m.constructor.name === modifier);
const matchingMods = gScene.findModifiers(m => m.constructor.name === modifier);
if (matchingMods?.length > 0) {
matchingMods.forEach(matchingMod => {
modifierCount += matchingMod.stackCount;
@ -375,7 +375,7 @@ export class PersistentModifierRequirement extends EncounterSceneRequirement {
return modifierCount >= this.minNumberOfItems;
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "requiredItem", this.requiredHeldItemModifiers[0] ];
}
}
@ -390,20 +390,20 @@ export class MoneyRequirement extends EncounterSceneRequirement {
this.scalingMultiplier = scalingMultiplier ?? 0;
}
override meetsRequirement(scene: BattleScene): boolean {
const money = scene.money;
override meetsRequirement(): boolean {
const money = gScene.money;
if (isNullOrUndefined(money)) {
return false;
}
if (this.scalingMultiplier > 0) {
this.requiredMoney = scene.getWaveMoneyAmount(this.scalingMultiplier);
this.requiredMoney = gScene.getWaveMoneyAmount(this.scalingMultiplier);
}
return !(this.requiredMoney > 0 && this.requiredMoney > money);
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
const value = this.scalingMultiplier > 0 ? scene.getWaveMoneyAmount(this.scalingMultiplier).toString() : this.requiredMoney.toString();
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const value = this.scalingMultiplier > 0 ? gScene.getWaveMoneyAmount(this.scalingMultiplier).toString() : this.requiredMoney.toString();
return [ "money", value ];
}
}
@ -420,8 +420,8 @@ export class SpeciesRequirement extends EncounterPokemonRequirement {
this.requiredSpecies = Array.isArray(species) ? species : [ species ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredSpecies?.length < 0) {
return false;
}
@ -437,7 +437,7 @@ export class SpeciesRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
if (pokemon?.species.speciesId && this.requiredSpecies.includes(pokemon.species.speciesId)) {
return [ "species", Species[pokemon.species.speciesId] ];
}
@ -458,8 +458,8 @@ export class NatureRequirement extends EncounterPokemonRequirement {
this.requiredNature = Array.isArray(nature) ? nature : [ nature ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredNature?.length < 0) {
return false;
}
@ -475,7 +475,7 @@ export class NatureRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
if (!isNullOrUndefined(pokemon?.nature) && this.requiredNature.includes(pokemon.nature)) {
return [ "nature", Nature[pokemon.nature] ];
}
@ -497,8 +497,8 @@ export class TypeRequirement extends EncounterPokemonRequirement {
this.requiredType = Array.isArray(type) ? type : [ type ];
}
override meetsRequirement(scene: BattleScene): boolean {
let partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
let partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon)) {
return false;
@ -520,7 +520,7 @@ export class TypeRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const includedTypes = this.requiredType.filter((ty) => pokemon?.getTypes().includes(ty));
if (includedTypes.length > 0) {
return [ "type", Type[includedTypes[0]] ];
@ -544,8 +544,8 @@ export class MoveRequirement extends EncounterPokemonRequirement {
this.requiredMoves = Array.isArray(moves) ? moves : [ moves ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) {
return false;
}
@ -566,7 +566,7 @@ export class MoveRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const includedMoves = pokemon?.moveset.filter((move) => move?.moveId && this.requiredMoves.includes(move.moveId));
if (includedMoves && includedMoves.length > 0 && includedMoves[0]) {
return [ "move", includedMoves[0].getName() ];
@ -593,8 +593,8 @@ export class CompatibleMoveRequirement extends EncounterPokemonRequirement {
this.requiredMoves = Array.isArray(learnableMove) ? learnableMove : [ learnableMove ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) {
return false;
}
@ -610,7 +610,7 @@ export class CompatibleMoveRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const includedCompatMoves = this.requiredMoves.filter((reqMove) => pokemon?.compatibleTms.filter((tm) => !pokemon.moveset.find(m => m?.moveId === tm)).includes(reqMove));
if (includedCompatMoves.length > 0) {
return [ "compatibleMove", Moves[includedCompatMoves[0]] ];
@ -634,8 +634,8 @@ export class AbilityRequirement extends EncounterPokemonRequirement {
this.requiredAbilities = Array.isArray(abilities) ? abilities : [ abilities ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredAbilities?.length < 0) {
return false;
}
@ -655,7 +655,7 @@ export class AbilityRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(_scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const matchingAbility = this.requiredAbilities.find(a => pokemon?.hasAbility(a, false));
if (!isNullOrUndefined(matchingAbility)) {
return [ "ability", allAbilities[matchingAbility].name ];
@ -676,8 +676,8 @@ export class StatusEffectRequirement extends EncounterPokemonRequirement {
this.requiredStatusEffect = Array.isArray(statusEffect) ? statusEffect : [ statusEffect ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredStatusEffect?.length < 0) {
return false;
}
@ -713,7 +713,7 @@ export class StatusEffectRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const reqStatus = this.requiredStatusEffect.filter((a) => {
if (a === StatusEffect.NONE) {
return isNullOrUndefined(pokemon?.status) || isNullOrUndefined(pokemon.status.effect) || pokemon.status.effect === a;
@ -745,8 +745,8 @@ export class CanFormChangeWithItemRequirement extends EncounterPokemonRequiremen
this.requiredFormChangeItem = Array.isArray(formChangeItem) ? formChangeItem : [ formChangeItem ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredFormChangeItem?.length < 0) {
return false;
}
@ -775,7 +775,7 @@ export class CanFormChangeWithItemRequirement extends EncounterPokemonRequiremen
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const requiredItems = this.requiredFormChangeItem.filter((formChangeItem) => this.filterByForm(pokemon, formChangeItem));
if (requiredItems.length > 0) {
return [ "formChangeItem", FormChangeItem[requiredItems[0]] ];
@ -797,8 +797,8 @@ export class CanEvolveWithItemRequirement extends EncounterPokemonRequirement {
this.requiredEvolutionItem = Array.isArray(evolutionItems) ? evolutionItems : [ evolutionItems ];
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon) || this.requiredEvolutionItem?.length < 0) {
return false;
}
@ -825,7 +825,7 @@ export class CanEvolveWithItemRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const requiredItems = this.requiredEvolutionItem.filter((evoItem) => this.filterByEvo(pokemon, evoItem));
if (requiredItems.length > 0) {
return [ "evolutionItem", EvolutionItem[requiredItems[0]] ];
@ -848,8 +848,8 @@ export class HeldItemRequirement extends EncounterPokemonRequirement {
this.requireTransferable = requireTransferable;
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon)) {
return false;
}
@ -873,7 +873,7 @@ export class HeldItemRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const requiredItems = pokemon?.getHeldItems().filter((it) => {
return this.requiredHeldItemModifiers.some(heldItem => it.constructor.name === heldItem)
&& (!this.requireTransferable || it.isTransferable);
@ -899,8 +899,8 @@ export class AttackTypeBoosterHeldItemTypeRequirement extends EncounterPokemonRe
this.requireTransferable = requireTransferable;
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty();
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty();
if (isNullOrUndefined(partyPokemon)) {
return false;
}
@ -928,7 +928,7 @@ export class AttackTypeBoosterHeldItemTypeRequirement extends EncounterPokemonRe
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const requiredItems = pokemon?.getHeldItems().filter((it) => {
return this.requiredHeldItemTypes.some(heldItemType =>
it instanceof AttackTypeBoosterModifier
@ -954,10 +954,10 @@ export class LevelRequirement extends EncounterPokemonRequirement {
this.requiredLevelRange = requiredLevelRange;
}
override meetsRequirement(scene: BattleScene): boolean {
override meetsRequirement(): boolean {
// Party Pokemon inside required level range
if (!isNullOrUndefined(this.requiredLevelRange) && this.requiredLevelRange[0] <= this.requiredLevelRange[1]) {
const partyPokemon = scene.getParty();
const partyPokemon = gScene.getParty();
const pokemonInRange = this.queryParty(partyPokemon);
if (pokemonInRange.length < this.minNumberOfPokemon) {
return false;
@ -975,7 +975,7 @@ export class LevelRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "level", pokemon?.level.toString() ?? "" ];
}
}
@ -992,10 +992,10 @@ export class FriendshipRequirement extends EncounterPokemonRequirement {
this.requiredFriendshipRange = requiredFriendshipRange;
}
override meetsRequirement(scene: BattleScene): boolean {
override meetsRequirement(): boolean {
// Party Pokemon inside required friendship range
if (!isNullOrUndefined(this.requiredFriendshipRange) && this.requiredFriendshipRange[0] <= this.requiredFriendshipRange[1]) {
const partyPokemon = scene.getParty();
const partyPokemon = gScene.getParty();
const pokemonInRange = this.queryParty(partyPokemon);
if (pokemonInRange.length < this.minNumberOfPokemon) {
return false;
@ -1013,7 +1013,7 @@ export class FriendshipRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "friendship", pokemon?.friendship.toString() ?? "" ];
}
}
@ -1035,10 +1035,10 @@ export class HealthRatioRequirement extends EncounterPokemonRequirement {
this.requiredHealthRange = requiredHealthRange;
}
override meetsRequirement(scene: BattleScene): boolean {
override meetsRequirement(): boolean {
// Party Pokemon's health inside required health range
if (!isNullOrUndefined(this.requiredHealthRange) && this.requiredHealthRange[0] <= this.requiredHealthRange[1]) {
const partyPokemon = scene.getParty();
const partyPokemon = gScene.getParty();
const pokemonInRange = this.queryParty(partyPokemon);
if (pokemonInRange.length < this.minNumberOfPokemon) {
return false;
@ -1058,7 +1058,7 @@ export class HealthRatioRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
const hpRatio = pokemon?.getHpRatio();
if (!isNullOrUndefined(hpRatio)) {
return [ "healthRatio", Math.floor(hpRatio * 100).toString() + "%" ];
@ -1079,10 +1079,10 @@ export class WeightRequirement extends EncounterPokemonRequirement {
this.requiredWeightRange = requiredWeightRange;
}
override meetsRequirement(scene: BattleScene): boolean {
override meetsRequirement(): boolean {
// Party Pokemon's weight inside required weight range
if (!isNullOrUndefined(this.requiredWeightRange) && this.requiredWeightRange[0] <= this.requiredWeightRange[1]) {
const partyPokemon = scene.getParty();
const partyPokemon = gScene.getParty();
const pokemonInRange = this.queryParty(partyPokemon);
if (pokemonInRange.length < this.minNumberOfPokemon) {
return false;
@ -1100,7 +1100,7 @@ export class WeightRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(scene: BattleScene, pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(pokemon?: PlayerPokemon): [string, string] {
return [ "weight", pokemon?.getWeight().toString() ?? "" ];
}
}

View File

@ -2,7 +2,6 @@ import { EnemyPartyConfig } from "#app/data/mystery-encounters/utils/encounter-p
import Pokemon, { PlayerPokemon, PokemonMove } from "#app/field/pokemon";
import { capitalizeFirstLetter, isNullOrUndefined } from "#app/utils";
import { MysteryEncounterType } from "#enums/mystery-encounter-type";
import BattleScene from "#app/battle-scene";
import MysteryEncounterIntroVisuals, { MysteryEncounterSpriteConfig } from "#app/field/mystery-encounter-intro";
import * as Utils from "#app/utils";
import { StatusEffect } from "../status-effect";
@ -16,6 +15,7 @@ import { MysteryEncounterOptionMode } from "#enums/mystery-encounter-option-mode
import { GameModes } from "#app/game-mode";
import { EncounterAnim } from "#enums/encounter-anims";
import { Challenges } from "#enums/challenges";
import { gScene } from "#app/battle-scene";
export interface EncounterStartOfBattleEffect {
sourcePokemon?: Pokemon;
@ -55,11 +55,11 @@ export interface IMysteryEncounter {
skipToFightInput: boolean;
preventGameStatsUpdates: boolean;
onInit?: (scene: BattleScene) => boolean;
onVisualsStart?: (scene: BattleScene) => boolean;
doEncounterExp?: (scene: BattleScene) => boolean;
doEncounterRewards?: (scene: BattleScene) => boolean;
doContinueEncounter?: (scene: BattleScene) => Promise<void>;
onInit?: () => boolean;
onVisualsStart?: () => boolean;
doEncounterExp?: () => boolean;
doEncounterRewards?: () => boolean;
doContinueEncounter?: () => Promise<void>;
requirements: EncounterSceneRequirement[];
primaryPokemonRequirements: EncounterPokemonRequirement[];
@ -159,24 +159,24 @@ export default class MysteryEncounter implements IMysteryEncounter {
// #region Event callback functions
/** Event when Encounter is first loaded, use it for data conditioning */
onInit?: (scene: BattleScene) => boolean;
onInit?: () => boolean;
/** Event when battlefield visuals have finished sliding in and the encounter dialogue begins */
onVisualsStart?: (scene: BattleScene) => boolean;
onVisualsStart?: () => boolean;
/** Event triggered prior to {@linkcode CommandPhase}, during {@linkcode TurnInitPhase} */
onTurnStart?: (scene: BattleScene) => boolean;
onTurnStart?: () => boolean;
/** Event prior to any rewards logic in {@linkcode MysteryEncounterRewardsPhase} */
onRewards?: (scene: BattleScene) => Promise<void>;
onRewards?: () => Promise<void>;
/** Will provide the player party EXP before rewards are displayed for that wave */
doEncounterExp?: (scene: BattleScene) => boolean;
doEncounterExp?: () => boolean;
/** Will provide the player a rewards shop for that wave */
doEncounterRewards?: (scene: BattleScene) => boolean;
doEncounterRewards?: () => boolean;
/** Will execute callback during VictoryPhase of a continuousEncounter */
doContinueEncounter?: (scene: BattleScene) => Promise<void>;
doContinueEncounter?: () => Promise<void>;
/**
* Can perform special logic when a ME battle is lost, before GameOver/battle retry prompt.
* Should return `true` if it is treated as "real" Game Over, `false` if not.
*/
onGameOver?: (scene: BattleScene) => boolean;
onGameOver?: () => boolean;
/**
* Requirements
@ -299,10 +299,10 @@ export default class MysteryEncounter implements IMysteryEncounter {
* @param scene
* @returns
*/
meetsRequirements(scene: BattleScene): boolean {
const sceneReq = !this.requirements.some(requirement => !requirement.meetsRequirement(scene));
const secReqs = this.meetsSecondaryRequirementAndSecondaryPokemonSelected(scene); // secondary is checked first to handle cases of primary overlapping with secondary
const priReqs = this.meetsPrimaryRequirementAndPrimaryPokemonSelected(scene);
meetsRequirements(): boolean {
const sceneReq = !this.requirements.some(requirement => !requirement.meetsRequirement());
const secReqs = this.meetsSecondaryRequirementAndSecondaryPokemonSelected(); // secondary is checked first to handle cases of primary overlapping with secondary
const priReqs = this.meetsPrimaryRequirementAndPrimaryPokemonSelected();
return sceneReq && secReqs && priReqs;
}
@ -313,8 +313,8 @@ export default class MysteryEncounter implements IMysteryEncounter {
* @param scene
* @param pokemon
*/
pokemonMeetsPrimaryRequirements(scene: BattleScene, pokemon: Pokemon): boolean {
return !this.primaryPokemonRequirements.some(req => !req.queryParty(scene.getParty()).map(p => p.id).includes(pokemon.id));
pokemonMeetsPrimaryRequirements(pokemon: Pokemon): boolean {
return !this.primaryPokemonRequirements.some(req => !req.queryParty(gScene.getParty()).map(p => p.id).includes(pokemon.id));
}
/**
@ -324,20 +324,20 @@ export default class MysteryEncounter implements IMysteryEncounter {
* can cause scenarios where there are not enough Pokemon that are sufficient for all requirements.
* @param scene
*/
private meetsPrimaryRequirementAndPrimaryPokemonSelected(scene: BattleScene): boolean {
private meetsPrimaryRequirementAndPrimaryPokemonSelected(): boolean {
if (!this.primaryPokemonRequirements || this.primaryPokemonRequirements.length === 0) {
const activeMon = scene.getParty().filter(p => p.isActive(true));
const activeMon = gScene.getParty().filter(p => p.isActive(true));
if (activeMon.length > 0) {
this.primaryPokemon = activeMon[0];
} else {
this.primaryPokemon = scene.getParty().filter(p => p.isAllowedInBattle())[0];
this.primaryPokemon = gScene.getParty().filter(p => p.isAllowedInBattle())[0];
}
return true;
}
let qualified: PlayerPokemon[] = scene.getParty();
let qualified: PlayerPokemon[] = gScene.getParty();
for (const req of this.primaryPokemonRequirements) {
if (req.meetsRequirement(scene)) {
qualified = qualified.filter(pkmn => req.queryParty(scene.getParty()).includes(pkmn));
if (req.meetsRequirement()) {
qualified = qualified.filter(pkmn => req.queryParty(gScene.getParty()).includes(pkmn));
} else {
this.primaryPokemon = undefined;
return false;
@ -388,16 +388,16 @@ export default class MysteryEncounter implements IMysteryEncounter {
* can cause scenarios where there are not enough Pokemon that are sufficient for all requirements.
* @param scene
*/
private meetsSecondaryRequirementAndSecondaryPokemonSelected(scene: BattleScene): boolean {
private meetsSecondaryRequirementAndSecondaryPokemonSelected(): boolean {
if (!this.secondaryPokemonRequirements || this.secondaryPokemonRequirements.length === 0) {
this.secondaryPokemon = [];
return true;
}
let qualified: PlayerPokemon[] = scene.getParty();
let qualified: PlayerPokemon[] = gScene.getParty();
for (const req of this.secondaryPokemonRequirements) {
if (req.meetsRequirement(scene)) {
qualified = qualified.filter(pkmn => req.queryParty(scene.getParty()).includes(pkmn));
if (req.meetsRequirement()) {
qualified = qualified.filter(pkmn => req.queryParty(gScene.getParty()).includes(pkmn));
} else {
this.secondaryPokemon = [];
return false;
@ -411,8 +411,8 @@ export default class MysteryEncounter implements IMysteryEncounter {
* Initializes encounter intro sprites based on the sprite configs defined in spriteConfigs
* @param scene
*/
initIntroVisuals(scene: BattleScene): void {
this.introVisuals = new MysteryEncounterIntroVisuals(scene, this);
initIntroVisuals(): void {
this.introVisuals = new MysteryEncounterIntroVisuals(this);
}
/**
@ -420,11 +420,11 @@ export default class MysteryEncounter implements IMysteryEncounter {
* Will use the first support pokemon in list
* For multiple support pokemon in the dialogue token, it will have to be overridden.
*/
populateDialogueTokensFromRequirements(scene: BattleScene): void {
this.meetsRequirements(scene);
populateDialogueTokensFromRequirements(): void {
this.meetsRequirements();
if (this.requirements?.length > 0) {
for (const req of this.requirements) {
const dialogueToken = req.getDialogueToken(scene);
const dialogueToken = req.getDialogueToken();
if (dialogueToken?.length === 2) {
this.setDialogueToken(...dialogueToken);
}
@ -434,7 +434,7 @@ export default class MysteryEncounter implements IMysteryEncounter {
this.setDialogueToken("primaryName", this.primaryPokemon.getNameToRender());
for (const req of this.primaryPokemonRequirements) {
if (!req.invertQuery) {
const value = req.getDialogueToken(scene, this.primaryPokemon);
const value = req.getDialogueToken(this.primaryPokemon);
if (value?.length === 2) {
this.setDialogueToken("primary" + capitalizeFirstLetter(value[0]), value[1]);
}
@ -445,7 +445,7 @@ export default class MysteryEncounter implements IMysteryEncounter {
this.setDialogueToken("secondaryName", this.secondaryPokemon[0].getNameToRender());
for (const req of this.secondaryPokemonRequirements) {
if (!req.invertQuery) {
const value = req.getDialogueToken(scene, this.secondaryPokemon[0]);
const value = req.getDialogueToken(this.secondaryPokemon[0]);
if (value?.length === 2) {
this.setDialogueToken("primary" + capitalizeFirstLetter(value[0]), value[1]);
}
@ -457,11 +457,11 @@ export default class MysteryEncounter implements IMysteryEncounter {
// Dialogue tokens for options
for (let i = 0; i < this.options.length; i++) {
const opt = this.options[i];
opt.meetsRequirements(scene);
opt.meetsRequirements();
const j = i + 1;
if (opt.requirements.length > 0) {
for (const req of opt.requirements) {
const dialogueToken = req.getDialogueToken(scene);
const dialogueToken = req.getDialogueToken();
if (dialogueToken?.length === 2) {
this.setDialogueToken("option" + j + capitalizeFirstLetter(dialogueToken[0]), dialogueToken[1]);
}
@ -471,7 +471,7 @@ export default class MysteryEncounter implements IMysteryEncounter {
this.setDialogueToken("option" + j + "PrimaryName", opt.primaryPokemon.getNameToRender());
for (const req of opt.primaryPokemonRequirements) {
if (!req.invertQuery) {
const value = req.getDialogueToken(scene, opt.primaryPokemon);
const value = req.getDialogueToken(opt.primaryPokemon);
if (value?.length === 2) {
this.setDialogueToken("option" + j + "Primary" + capitalizeFirstLetter(value[0]), value[1]);
}
@ -482,7 +482,7 @@ export default class MysteryEncounter implements IMysteryEncounter {
this.setDialogueToken("option" + j + "SecondaryName", opt.secondaryPokemon[0].getNameToRender());
for (const req of opt.secondaryPokemonRequirements) {
if (!req.invertQuery) {
const value = req.getDialogueToken(scene, opt.secondaryPokemon[0]);
const value = req.getDialogueToken(opt.secondaryPokemon[0]);
if (value?.length === 2) {
this.setDialogueToken("option" + j + "Secondary" + capitalizeFirstLetter(value[0]), value[1]);
}
@ -520,8 +520,8 @@ export default class MysteryEncounter implements IMysteryEncounter {
* Increments if the same {@linkcode MysteryEncounter} has multiple option select cycles
* @param scene
*/
updateSeedOffset(scene: BattleScene) {
const currentOffset = this.seedOffset ?? scene.currentBattle.waveIndex * 1000;
updateSeedOffset() {
const currentOffset = this.seedOffset ?? gScene.currentBattle.waveIndex * 1000;
this.seedOffset = currentOffset + 512;
}
}
@ -858,7 +858,7 @@ export class MysteryEncounterBuilder implements Partial<IMysteryEncounter> {
* @param doEncounterRewards Synchronous callback function to perform during rewards phase of the encounter
* @returns
*/
withRewards(doEncounterRewards: (scene: BattleScene) => boolean): this & Required<Pick<IMysteryEncounter, "doEncounterRewards">> {
withRewards(doEncounterRewards: () => boolean): this & Required<Pick<IMysteryEncounter, "doEncounterRewards">> {
return Object.assign(this, { doEncounterRewards: doEncounterRewards });
}
@ -872,7 +872,7 @@ export class MysteryEncounterBuilder implements Partial<IMysteryEncounter> {
* @param doEncounterExp Synchronous callback function to perform during rewards phase of the encounter
* @returns
*/
withExp(doEncounterExp: (scene: BattleScene) => boolean): this & Required<Pick<IMysteryEncounter, "doEncounterExp">> {
withExp(doEncounterExp: () => boolean): this & Required<Pick<IMysteryEncounter, "doEncounterExp">> {
return Object.assign(this, { doEncounterExp: doEncounterExp });
}
@ -883,7 +883,7 @@ export class MysteryEncounterBuilder implements Partial<IMysteryEncounter> {
* @param onInit Synchronous callback function to perform as soon as the encounter is selected for the next phase
* @returns
*/
withOnInit(onInit: (scene: BattleScene) => boolean): this & Required<Pick<IMysteryEncounter, "onInit">> {
withOnInit(onInit: () => boolean): this & Required<Pick<IMysteryEncounter, "onInit">> {
return Object.assign(this, { onInit });
}
@ -893,7 +893,7 @@ export class MysteryEncounterBuilder implements Partial<IMysteryEncounter> {
* @param onVisualsStart Synchronous callback function to perform as soon as the enemy field finishes sliding in
* @returns
*/
withOnVisualsStart(onVisualsStart: (scene: BattleScene) => boolean): this & Required<Pick<IMysteryEncounter, "onVisualsStart">> {
withOnVisualsStart(onVisualsStart: () => boolean): this & Required<Pick<IMysteryEncounter, "onVisualsStart">> {
return Object.assign(this, { onVisualsStart: onVisualsStart });
}

View File

@ -1,8 +1,8 @@
import BattleScene from "#app/battle-scene";
import { Moves } from "#app/enums/moves";
import { PlayerPokemon, PokemonMove } from "#app/field/pokemon";
import { isNullOrUndefined } from "#app/utils";
import { EncounterPokemonRequirement } from "#app/data/mystery-encounters/mystery-encounter-requirements";
import { gScene } from "#app/battle-scene";
/**
* {@linkcode CanLearnMoveRequirement} options
@ -38,8 +38,8 @@ export class CanLearnMoveRequirement extends EncounterPokemonRequirement {
this.invertQuery = options.invertQuery ?? false;
}
override meetsRequirement(scene: BattleScene): boolean {
const partyPokemon = scene.getParty().filter((pkm) => (this.includeFainted ? pkm.isAllowed() : pkm.isAllowedInBattle()));
override meetsRequirement(): boolean {
const partyPokemon = gScene.getParty().filter((pkm) => (this.includeFainted ? pkm.isAllowed() : pkm.isAllowedInBattle()));
if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) {
return false;
@ -63,7 +63,7 @@ export class CanLearnMoveRequirement extends EncounterPokemonRequirement {
}
}
override getDialogueToken(_scene: BattleScene, _pokemon?: PlayerPokemon): [string, string] {
override getDialogueToken(__pokemon?: PlayerPokemon): [string, string] {
return [ "requiredMoves", this.requiredMoves.map(m => new PokemonMove(m).getName()).join(", ") ];
}

View File

@ -1,23 +1,23 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { getTextWithColors, TextStyle } from "#app/ui/text";
import { UiTheme } from "#enums/ui-theme";
import { isNullOrUndefined } from "#app/utils";
import i18next from "i18next";
/**
* Will inject all relevant dialogue tokens that exist in the {@linkcode BattleScene.currentBattle.mysteryEncounter.dialogueTokens}, into i18n text.
* Will inject all relevant dialogue tokens that exist in the {@linkcode BattlegScene.currentBattle.mysteryEncounter.dialogueTokens}, into i18n text.
* Also adds BBCodeText fragments for colored text, if applicable
* @param scene
* @param keyOrString
* @param primaryStyle Can define a text style to be applied to the entire string. Must be defined for BBCodeText styles to be applied correctly
* @param uiTheme
*/
export function getEncounterText(scene: BattleScene, keyOrString?: string, primaryStyle?: TextStyle, uiTheme: UiTheme = UiTheme.DEFAULT): string | null {
export function getEncounterText(keyOrString?: string, primaryStyle?: TextStyle, uiTheme: UiTheme = UiTheme.DEFAULT): string | null {
if (isNullOrUndefined(keyOrString)) {
return null;
}
let textString: string | null = getTextWithDialogueTokens(scene, keyOrString);
let textString: string | null = getTextWithDialogueTokens(keyOrString);
// Can only color the text if a Primary Style is defined
// primaryStyle is applied to all text that does not have its own specified style
@ -29,12 +29,12 @@ export function getEncounterText(scene: BattleScene, keyOrString?: string, prima
}
/**
* Helper function to inject {@linkcode BattleScene.currentBattle.mysteryEncounter.dialogueTokens} into a given content string
* Helper function to inject {@linkcode gScene.currentBattle.mysteryEncounter.dialogueTokens} into a given content string
* @param scene
* @param keyOrString
*/
function getTextWithDialogueTokens(scene: BattleScene, keyOrString: string): string | null {
const tokens = scene.currentBattle?.mysteryEncounter?.dialogueTokens;
function getTextWithDialogueTokens(keyOrString: string): string | null {
const tokens = gScene.currentBattle?.mysteryEncounter?.dialogueTokens;
if (i18next.exists(keyOrString, tokens)) {
return i18next.t(keyOrString, tokens) as string;
@ -48,9 +48,9 @@ function getTextWithDialogueTokens(scene: BattleScene, keyOrString: string): str
* @param scene
* @param contentKey
*/
export function queueEncounterMessage(scene: BattleScene, contentKey: string): void {
const text: string | null = getEncounterText(scene, contentKey);
scene.queueMessage(text ?? "", null, true);
export function queueEncounterMessage(contentKey: string): void {
const text: string | null = getEncounterText(contentKey);
gScene.queueMessage(text ?? "", null, true);
}
/**
@ -62,10 +62,10 @@ export function queueEncounterMessage(scene: BattleScene, contentKey: string): v
* @param callbackDelay
* @param promptDelay
*/
export function showEncounterText(scene: BattleScene, contentKey: string, delay: number | null = null, callbackDelay: number = 0, prompt: boolean = true, promptDelay: number | null = null): Promise<void> {
export function showEncounterText(contentKey: string, delay: number | null = null, callbackDelay: number = 0, prompt: boolean = true, promptDelay: number | null = null): Promise<void> {
return new Promise<void>(resolve => {
const text: string | null = getEncounterText(scene, contentKey);
scene.ui.showText(text ?? "", delay, () => resolve(), callbackDelay, prompt, promptDelay);
const text: string | null = getEncounterText(contentKey);
gScene.ui.showText(text ?? "", delay, () => resolve(), callbackDelay, prompt, promptDelay);
});
}
@ -77,10 +77,10 @@ export function showEncounterText(scene: BattleScene, contentKey: string, delay:
* @param speakerContentKey
* @param callbackDelay
*/
export function showEncounterDialogue(scene: BattleScene, textContentKey: string, speakerContentKey: string, delay: number | null = null, callbackDelay: number = 0): Promise<void> {
export function showEncounterDialogue(textContentKey: string, speakerContentKey: string, delay: number | null = null, callbackDelay: number = 0): Promise<void> {
return new Promise<void>(resolve => {
const text: string | null = getEncounterText(scene, textContentKey);
const speaker: string | null = getEncounterText(scene, speakerContentKey);
scene.ui.showDialogue(text ?? "", speaker ?? "", delay, () => resolve(), callbackDelay);
const text: string | null = getEncounterText(textContentKey);
const speaker: string | null = getEncounterText(speakerContentKey);
gScene.ui.showDialogue(text ?? "", speaker ?? "", delay, () => resolve(), callbackDelay);
});
}

View File

@ -16,7 +16,6 @@ import { BattlerTagType } from "#enums/battler-tag-type";
import { Biome } from "#enums/biome";
import { TrainerType } from "#enums/trainer-type";
import i18next from "i18next";
import BattleScene from "#app/battle-scene";
import Trainer, { TrainerVariant } from "#app/field/trainer";
import { Gender } from "#app/data/gender";
import { Nature } from "#app/data/nature";
@ -37,32 +36,33 @@ import { GameOverPhase } from "#app/phases/game-over-phase";
import { SelectModifierPhase } from "#app/phases/select-modifier-phase";
import { PartyExpPhase } from "#app/phases/party-exp-phase";
import { Variant } from "#app/data/variant";
import { gScene } from "#app/battle-scene";
/**
* Animates exclamation sprite over trainer's head at start of encounter
* @param scene
*/
export function doTrainerExclamation(scene: BattleScene) {
const exclamationSprite = scene.add.sprite(0, 0, "encounter_exclaim");
export function doTrainerExclamation() {
const exclamationSprite = gScene.add.sprite(0, 0, "encounter_exclaim");
exclamationSprite.setName("exclamation");
scene.field.add(exclamationSprite);
scene.field.moveTo(exclamationSprite, scene.field.getAll().length - 1);
gScene.field.add(exclamationSprite);
gScene.field.moveTo(exclamationSprite, gScene.field.getAll().length - 1);
exclamationSprite.setVisible(true);
exclamationSprite.setPosition(110, 68);
scene.tweens.add({
gScene.tweens.add({
targets: exclamationSprite,
y: "-=25",
ease: "Cubic.easeOut",
duration: 300,
yoyo: true,
onComplete: () => {
scene.time.delayedCall(800, () => {
scene.field.remove(exclamationSprite, true);
gScene.time.delayedCall(800, () => {
gScene.field.remove(exclamationSprite, true);
});
}
});
scene.playSound("battle_anims/GEN8- Exclaim", { volume: 0.7 });
gScene.playSound("battle_anims/GEN8- Exclaim", { volume: 0.7 });
}
export interface EnemyPokemonConfig {
@ -116,11 +116,11 @@ export interface EnemyPartyConfig {
* @param scene Battle Scene
* @param partyConfig Can pass various customizable attributes for the enemy party, see EnemyPartyConfig
*/
export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig: EnemyPartyConfig): Promise<void> {
export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): Promise<void> {
const loaded: boolean = false;
const loadEnemyAssets: Promise<void>[] = [];
const battle: Battle = scene.currentBattle;
const battle: Battle = gScene.currentBattle;
let doubleBattle: boolean = partyConfig?.doubleBattle ?? false;
@ -129,10 +129,10 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
const partyTrainerConfig = partyConfig?.trainerConfig;
let trainerConfig: TrainerConfig;
if (!isNullOrUndefined(trainerType) || partyTrainerConfig) {
scene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.TRAINER_BATTLE;
if (scene.currentBattle.trainer) {
scene.currentBattle.trainer.setVisible(false);
scene.currentBattle.trainer.destroy();
gScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.TRAINER_BATTLE;
if (gScene.currentBattle.trainer) {
gScene.currentBattle.trainer.setVisible(false);
gScene.currentBattle.trainer.destroy();
}
trainerConfig = partyTrainerConfig ? partyTrainerConfig : trainerConfigs[trainerType!];
@ -140,23 +140,23 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
const doubleTrainer = trainerConfig.doubleOnly || (trainerConfig.hasDouble && !!partyConfig.doubleBattle);
doubleBattle = doubleTrainer;
const trainerFemale = isNullOrUndefined(partyConfig.female) ? !!(Utils.randSeedInt(2)) : partyConfig.female;
const newTrainer = new Trainer(scene, trainerConfig.trainerType, doubleTrainer ? TrainerVariant.DOUBLE : trainerFemale ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT, undefined, undefined, undefined, trainerConfig);
const newTrainer = new Trainer(trainerConfig.trainerType, doubleTrainer ? TrainerVariant.DOUBLE : trainerFemale ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT, undefined, undefined, undefined, trainerConfig);
newTrainer.x += 300;
newTrainer.setVisible(false);
scene.field.add(newTrainer);
scene.currentBattle.trainer = newTrainer;
gScene.field.add(newTrainer);
gScene.currentBattle.trainer = newTrainer;
loadEnemyAssets.push(newTrainer.loadAssets().then(() => newTrainer.initSprite()));
battle.enemyLevels = scene.currentBattle.trainer.getPartyLevels(scene.currentBattle.waveIndex);
battle.enemyLevels = gScene.currentBattle.trainer.getPartyLevels(gScene.currentBattle.waveIndex);
} else {
// Wild
scene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.WILD_BATTLE;
gScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.WILD_BATTLE;
const numEnemies = partyConfig?.pokemonConfigs && partyConfig.pokemonConfigs.length > 0 ? partyConfig?.pokemonConfigs?.length : doubleBattle ? 2 : 1;
battle.enemyLevels = new Array(numEnemies).fill(null).map(() => scene.currentBattle.getLevelForWave());
battle.enemyLevels = new Array(numEnemies).fill(null).map(() => gScene.currentBattle.getLevelForWave());
}
scene.getEnemyParty().forEach(enemyPokemon => {
scene.field.remove(enemyPokemon, true);
gScene.getEnemyParty().forEach(enemyPokemon => {
gScene.field.remove(enemyPokemon, true);
});
battle.enemyParty = [];
battle.double = doubleBattle;
@ -167,7 +167,7 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
// levelAdditiveModifier value of 0.5 will halve the modifier scaling, 2 will double it, etc.
// Leaving null/undefined will disable level scaling
const mult: number = !isNullOrUndefined(partyConfig.levelAdditiveModifier) ? partyConfig.levelAdditiveModifier : 0;
const additive = Math.max(Math.round((scene.currentBattle.waveIndex / 10) * mult), 0);
const additive = Math.max(Math.round((gScene.currentBattle.waveIndex / 10) * mult), 0);
battle.enemyLevels = battle.enemyLevels.map(level => level + additive);
battle.enemyLevels.forEach((level, e) => {
@ -183,7 +183,7 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
dataSource = config.dataSource;
enemySpecies = config.species;
isBoss = config.isBoss;
battle.enemyParty[e] = scene.addEnemyPokemon(enemySpecies, level, TrainerSlot.TRAINER, isBoss, dataSource);
battle.enemyParty[e] = gScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.TRAINER, isBoss, dataSource);
} else {
battle.enemyParty[e] = battle.trainer.genPartyMember(e);
}
@ -195,17 +195,17 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
enemySpecies = config.species;
isBoss = config.isBoss;
if (isBoss) {
scene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.BOSS_BATTLE;
gScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.BOSS_BATTLE;
}
} else {
enemySpecies = scene.randomSpecies(battle.waveIndex, level, true);
enemySpecies = gScene.randomSpecies(battle.waveIndex, level, true);
}
battle.enemyParty[e] = scene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, isBoss, dataSource);
battle.enemyParty[e] = gScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, isBoss, dataSource);
}
}
const enemyPokemon = scene.getEnemyParty()[e];
const enemyPokemon = gScene.getEnemyParty()[e];
// Make sure basic data is clean
enemyPokemon.hp = enemyPokemon.getMaxHp();
@ -218,7 +218,7 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
}
if (!loaded && isNullOrUndefined(partyConfig.countAsSeen) || partyConfig.countAsSeen) {
scene.gameData.setPokemonSeen(enemyPokemon, true, !!(trainerType || trainerConfig));
gScene.gameData.setPokemonSeen(enemyPokemon, true, !!(trainerType || trainerConfig));
}
if (partyConfig?.pokemonConfigs && e < partyConfig.pokemonConfigs.length) {
@ -256,7 +256,7 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
// Set Boss
if (config.isBoss) {
let segments = !isNullOrUndefined(config.bossSegments) ? config.bossSegments! : scene.getEncounterBossSegments(scene.currentBattle.waveIndex, level, enemySpecies, true);
let segments = !isNullOrUndefined(config.bossSegments) ? config.bossSegments! : gScene.getEncounterBossSegments(gScene.currentBattle.waveIndex, level, enemySpecies, true);
if (!isNullOrUndefined(config.bossSegmentModifier)) {
segments += config.bossSegmentModifier;
}
@ -342,7 +342,7 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
console.log(`Pokemon: ${enemyPokemon.name}`, `Species ID: ${enemyPokemon.species.speciesId}`, `Stats: ${enemyPokemon.stats}`, `Ability: ${enemyPokemon.getAbility().name}`, `Passive Ability: ${enemyPokemon.getPassiveAbility().name}`);
});
scene.pushPhase(new MysteryEncounterBattlePhase(scene, partyConfig.disableSwitch));
gScene.pushPhase(new MysteryEncounterBattlePhase(partyConfig.disableSwitch));
await Promise.all(loadEnemyAssets);
battle.enemyParty.forEach((enemyPokemon_2, e_1) => {
@ -356,11 +356,11 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
}
});
if (!loaded) {
regenerateModifierPoolThresholds(scene.getEnemyField(), battle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD);
regenerateModifierPoolThresholds(gScene.getEnemyField(), battle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD);
const customModifierTypes = partyConfig?.pokemonConfigs
?.filter(config => config?.modifierConfigs)
.map(config => config.modifierConfigs!);
scene.generateEnemyModifiers(customModifierTypes);
gScene.generateEnemyModifiers(customModifierTypes);
}
}
@ -372,10 +372,10 @@ export async function initBattleWithEnemyConfig(scene: BattleScene, partyConfig:
* @param scene
* @param moves
*/
export function loadCustomMovesForEncounter(scene: BattleScene, moves: Moves | Moves[]) {
export function loadCustomMovesForEncounter(moves: Moves | Moves[]) {
moves = Array.isArray(moves) ? moves : [ moves ];
return Promise.all(moves.map(move => initMoveAnim(scene, move)))
.then(() => loadMoveAnimAssets(scene, moves));
return Promise.all(moves.map(move => initMoveAnim(move)))
.then(() => loadMoveAnimAssets(moves));
}
/**
@ -385,18 +385,18 @@ export function loadCustomMovesForEncounter(scene: BattleScene, moves: Moves | M
* @param playSound
* @param showMessage
*/
export function updatePlayerMoney(scene: BattleScene, changeValue: number, playSound: boolean = true, showMessage: boolean = true) {
scene.money = Math.min(Math.max(scene.money + changeValue, 0), Number.MAX_SAFE_INTEGER);
scene.updateMoneyText();
scene.animateMoneyChanged(false);
export function updatePlayerMoney(changeValue: number, playSound: boolean = true, showMessage: boolean = true) {
gScene.money = Math.min(Math.max(gScene.money + changeValue, 0), Number.MAX_SAFE_INTEGER);
gScene.updateMoneyText();
gScene.animateMoneyChanged(false);
if (playSound) {
scene.playSound("se/buy");
gScene.playSound("se/buy");
}
if (showMessage) {
if (changeValue < 0) {
scene.queueMessage(i18next.t("mysteryEncounterMessages:paid_money", { amount: -changeValue }), null, true);
gScene.queueMessage(i18next.t("mysteryEncounterMessages:paid_money", { amount: -changeValue }), null, true);
} else {
scene.queueMessage(i18next.t("mysteryEncounterMessages:receive_money", { amount: changeValue }), null, true);
gScene.queueMessage(i18next.t("mysteryEncounterMessages:receive_money", { amount: changeValue }), null, true);
}
}
}
@ -407,7 +407,7 @@ export function updatePlayerMoney(scene: BattleScene, changeValue: number, playS
* @param modifier
* @param pregenArgs Can specify BerryType for berries, TM for TMs, AttackBoostType for item, etc.
*/
export function generateModifierType(scene: BattleScene, modifier: () => ModifierType, pregenArgs?: any[]): ModifierType | null {
export function generateModifierType(modifier: () => ModifierType, pregenArgs?: any[]): ModifierType | null {
const modifierId = Object.keys(modifierTypes).find(k => modifierTypes[k] === modifier);
if (!modifierId) {
return null;
@ -420,7 +420,7 @@ export function generateModifierType(scene: BattleScene, modifier: () => Modifie
.withIdFromFunc(modifierTypes[modifierId])
.withTierFromPool();
return result instanceof ModifierTypeGenerator ? result.generateType(scene.getParty(), pregenArgs) : result;
return result instanceof ModifierTypeGenerator ? result.generateType(gScene.getParty(), pregenArgs) : result;
}
/**
@ -429,8 +429,8 @@ export function generateModifierType(scene: BattleScene, modifier: () => Modifie
* @param modifier
* @param pregenArgs - can specify BerryType for berries, TM for TMs, AttackBoostType for item, etc.
*/
export function generateModifierTypeOption(scene: BattleScene, modifier: () => ModifierType, pregenArgs?: any[]): ModifierTypeOption | null {
const result = generateModifierType(scene, modifier, pregenArgs);
export function generateModifierTypeOption(modifier: () => ModifierType, pregenArgs?: any[]): ModifierTypeOption | null {
const result = generateModifierType(modifier, pregenArgs);
if (result) {
return new ModifierTypeOption(result, 0);
}
@ -445,24 +445,24 @@ export function generateModifierTypeOption(scene: BattleScene, modifier: () => M
* @param onPokemonNotSelected - Any logic that needs to be performed if no Pokemon is chosen
* @param selectablePokemonFilter
*/
export function selectPokemonForOption(scene: BattleScene, onPokemonSelected: (pokemon: PlayerPokemon) => void | OptionSelectItem[], onPokemonNotSelected?: () => void, selectablePokemonFilter?: PokemonSelectFilter): Promise<boolean> {
export function selectPokemonForOption(onPokemonSelected: (pokemon: PlayerPokemon) => void | OptionSelectItem[], onPokemonNotSelected?: () => void, selectablePokemonFilter?: PokemonSelectFilter): Promise<boolean> {
return new Promise(resolve => {
const modeToSetOnExit = scene.ui.getMode();
const modeToSetOnExit = gScene.ui.getMode();
// Open party screen to choose pokemon
scene.ui.setMode(Mode.PARTY, PartyUiMode.SELECT, -1, (slotIndex: number, option: PartyOption) => {
if (slotIndex < scene.getParty().length) {
scene.ui.setMode(modeToSetOnExit).then(() => {
const pokemon = scene.getParty()[slotIndex];
gScene.ui.setMode(Mode.PARTY, PartyUiMode.SELECT, -1, (slotIndex: number, option: PartyOption) => {
if (slotIndex < gScene.getParty().length) {
gScene.ui.setMode(modeToSetOnExit).then(() => {
const pokemon = gScene.getParty()[slotIndex];
const secondaryOptions = onPokemonSelected(pokemon);
if (!secondaryOptions) {
scene.currentBattle.mysteryEncounter!.setDialogueToken("selectedPokemon", pokemon.getNameToRender());
gScene.currentBattle.mysteryEncounter!.setDialogueToken("selectedPokemon", pokemon.getNameToRender());
resolve(true);
return;
}
// There is a second option to choose after selecting the Pokemon
scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
const displayOptions = () => {
// Always appends a cancel option to bottom of options
const fullOptions = secondaryOptions.map(option => {
@ -470,7 +470,7 @@ export function selectPokemonForOption(scene: BattleScene, onPokemonSelected: (p
const onSelect = option.handler;
option.handler = () => {
onSelect();
scene.currentBattle.mysteryEncounter!.setDialogueToken("selectedPokemon", pokemon.getNameToRender());
gScene.currentBattle.mysteryEncounter!.setDialogueToken("selectedPokemon", pokemon.getNameToRender());
resolve(true);
return true;
};
@ -478,13 +478,13 @@ export function selectPokemonForOption(scene: BattleScene, onPokemonSelected: (p
}).concat({
label: i18next.t("menu:cancel"),
handler: () => {
scene.ui.clearText();
scene.ui.setMode(modeToSetOnExit);
gScene.ui.clearText();
gScene.ui.setMode(modeToSetOnExit);
resolve(false);
return true;
},
onHover: () => {
showEncounterText(scene, i18next.t("mysteryEncounterMessages:cancel_option"), 0, 0, false);
showEncounterText(i18next.t("mysteryEncounterMessages:cancel_option"), 0, 0, false);
}
});
@ -499,19 +499,19 @@ export function selectPokemonForOption(scene: BattleScene, onPokemonSelected: (p
if (fullOptions[0].onHover) {
fullOptions[0].onHover();
}
scene.ui.setModeWithoutClear(Mode.OPTION_SELECT, config, null, true);
gScene.ui.setModeWithoutClear(Mode.OPTION_SELECT, config, null, true);
};
const textPromptKey = scene.currentBattle.mysteryEncounter?.selectedOption?.dialogue?.secondOptionPrompt;
const textPromptKey = gScene.currentBattle.mysteryEncounter?.selectedOption?.dialogue?.secondOptionPrompt;
if (!textPromptKey) {
displayOptions();
} else {
showEncounterText(scene, textPromptKey).then(() => displayOptions());
showEncounterText(textPromptKey).then(() => displayOptions());
}
});
});
} else {
scene.ui.setMode(modeToSetOnExit).then(() => {
gScene.ui.setMode(modeToSetOnExit).then(() => {
if (onPokemonNotSelected) {
onPokemonNotSelected();
}
@ -536,25 +536,25 @@ interface PokemonAndOptionSelected {
* @param selectablePokemonFilter
* @param onHoverOverCancelOption
*/
export function selectOptionThenPokemon(scene: BattleScene, options: OptionSelectItem[], optionSelectPromptKey: string, selectablePokemonFilter?: PokemonSelectFilter, onHoverOverCancelOption?: () => void): Promise<PokemonAndOptionSelected | null> {
export function selectOptionThenPokemon(options: OptionSelectItem[], optionSelectPromptKey: string, selectablePokemonFilter?: PokemonSelectFilter, onHoverOverCancelOption?: () => void): Promise<PokemonAndOptionSelected | null> {
return new Promise<PokemonAndOptionSelected | null>(resolve => {
const modeToSetOnExit = scene.ui.getMode();
const modeToSetOnExit = gScene.ui.getMode();
const displayOptions = (config: OptionSelectConfig) => {
scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
if (!optionSelectPromptKey) {
// Do hover over the starting selection option
if (fullOptions[0].onHover) {
fullOptions[0].onHover();
}
scene.ui.setMode(Mode.OPTION_SELECT, config);
gScene.ui.setMode(Mode.OPTION_SELECT, config);
} else {
showEncounterText(scene, optionSelectPromptKey).then(() => {
showEncounterText(optionSelectPromptKey).then(() => {
// Do hover over the starting selection option
if (fullOptions[0].onHover) {
fullOptions[0].onHover();
}
scene.ui.setMode(Mode.OPTION_SELECT, config);
gScene.ui.setMode(Mode.OPTION_SELECT, config);
});
}
});
@ -562,10 +562,10 @@ export function selectOptionThenPokemon(scene: BattleScene, options: OptionSelec
const selectPokemonAfterOption = (selectedOptionIndex: number) => {
// Open party screen to choose a Pokemon
scene.ui.setMode(Mode.PARTY, PartyUiMode.SELECT, -1, (slotIndex: number, option: PartyOption) => {
if (slotIndex < scene.getParty().length) {
gScene.ui.setMode(Mode.PARTY, PartyUiMode.SELECT, -1, (slotIndex: number, option: PartyOption) => {
if (slotIndex < gScene.getParty().length) {
// Pokemon and option selected
scene.ui.setMode(modeToSetOnExit).then(() => {
gScene.ui.setMode(modeToSetOnExit).then(() => {
const result: PokemonAndOptionSelected = { selectedPokemonIndex: slotIndex, selectedOptionIndex: selectedOptionIndex };
resolve(result);
});
@ -589,8 +589,8 @@ export function selectOptionThenPokemon(scene: BattleScene, options: OptionSelec
}).concat({
label: i18next.t("menu:cancel"),
handler: () => {
scene.ui.clearText();
scene.ui.setMode(modeToSetOnExit);
gScene.ui.clearText();
gScene.ui.setMode(modeToSetOnExit);
resolve(null);
return true;
},
@ -598,7 +598,7 @@ export function selectOptionThenPokemon(scene: BattleScene, options: OptionSelec
if (onHoverOverCancelOption) {
onHoverOverCancelOption();
}
showEncounterText(scene, i18next.t("mysteryEncounterMessages:cancel_option"), 0, 0, false);
showEncounterText(i18next.t("mysteryEncounterMessages:cancel_option"), 0, 0, false);
}
});
@ -621,22 +621,22 @@ export function selectOptionThenPokemon(scene: BattleScene, options: OptionSelec
* @param eggRewards
* @param preRewardsCallback - can execute an arbitrary callback before the new phases if necessary (useful for updating items/party/injecting new phases before {@linkcode MysteryEncounterRewardsPhase})
*/
export function setEncounterRewards(scene: BattleScene, customShopRewards?: CustomModifierSettings, eggRewards?: IEggOptions[], preRewardsCallback?: Function) {
scene.currentBattle.mysteryEncounter!.doEncounterRewards = (scene: BattleScene) => {
export function setEncounterRewards(customShopRewards?: CustomModifierSettings, eggRewards?: IEggOptions[], preRewardsCallback?: Function) {
gScene.currentBattle.mysteryEncounter!.doEncounterRewards = () => {
if (preRewardsCallback) {
preRewardsCallback();
}
if (customShopRewards) {
scene.unshiftPhase(new SelectModifierPhase(scene, 0, undefined, customShopRewards));
gScene.unshiftPhase(new SelectModifierPhase(0, undefined, customShopRewards));
} else {
scene.tryRemovePhase(p => p instanceof SelectModifierPhase);
gScene.tryRemovePhase(p => p instanceof SelectModifierPhase);
}
if (eggRewards) {
eggRewards.forEach(eggOptions => {
const egg = new Egg(eggOptions);
egg.addEggToGameData(scene);
egg.addEggToGameData();
});
}
@ -662,11 +662,11 @@ export function setEncounterRewards(scene: BattleScene, customShopRewards?: Cust
* https://bulbapedia.bulbagarden.net/wiki/List_of_Pok%C3%A9mon_by_effort_value_yield_(Generation_IX)
* @param useWaveIndex - set to false when directly passing the the full exp value instead of baseExpValue
*/
export function setEncounterExp(scene: BattleScene, participantId: number | number[], baseExpValue: number, useWaveIndex: boolean = true) {
export function setEncounterExp(participantId: number | number[], baseExpValue: number, useWaveIndex: boolean = true) {
const participantIds = Array.isArray(participantId) ? participantId : [ participantId ];
scene.currentBattle.mysteryEncounter!.doEncounterExp = (scene: BattleScene) => {
scene.unshiftPhase(new PartyExpPhase(scene, baseExpValue, useWaveIndex, new Set(participantIds)));
gScene.currentBattle.mysteryEncounter!.doEncounterExp = () => {
gScene.unshiftPhase(new PartyExpPhase(baseExpValue, useWaveIndex, new Set(participantIds)));
return true;
};
@ -688,8 +688,8 @@ export class OptionSelectSettings {
* @param scene
* @param optionSelectSettings
*/
export function initSubsequentOptionSelect(scene: BattleScene, optionSelectSettings: OptionSelectSettings) {
scene.pushPhase(new MysteryEncounterPhase(scene, optionSelectSettings));
export function initSubsequentOptionSelect(optionSelectSettings: OptionSelectSettings) {
gScene.pushPhase(new MysteryEncounterPhase(optionSelectSettings));
}
/**
@ -699,11 +699,11 @@ export function initSubsequentOptionSelect(scene: BattleScene, optionSelectSetti
* @param addHealPhase - when true, will add a shop phase to end of encounter with 0 rewards but healing items are available
* @param encounterMode - Can set custom encounter mode if necessary (may be required for forcing Pokemon to return before next phase)
*/
export function leaveEncounterWithoutBattle(scene: BattleScene, addHealPhase: boolean = false, encounterMode: MysteryEncounterMode = MysteryEncounterMode.NO_BATTLE) {
scene.currentBattle.mysteryEncounter!.encounterMode = encounterMode;
scene.clearPhaseQueue();
scene.clearPhaseQueueSplice();
handleMysteryEncounterVictory(scene, addHealPhase);
export function leaveEncounterWithoutBattle(addHealPhase: boolean = false, encounterMode: MysteryEncounterMode = MysteryEncounterMode.NO_BATTLE) {
gScene.currentBattle.mysteryEncounter!.encounterMode = encounterMode;
gScene.clearPhaseQueue();
gScene.clearPhaseQueueSplice();
handleMysteryEncounterVictory(addHealPhase);
}
/**
@ -712,33 +712,33 @@ export function leaveEncounterWithoutBattle(scene: BattleScene, addHealPhase: bo
* @param addHealPhase - Adds an empty shop phase to allow player to purchase healing items
* @param doNotContinue - default `false`. If set to true, will not end the battle and continue to next wave
*/
export function handleMysteryEncounterVictory(scene: BattleScene, addHealPhase: boolean = false, doNotContinue: boolean = false) {
const allowedPkm = scene.getParty().filter((pkm) => pkm.isAllowedInBattle());
export function handleMysteryEncounterVictory(addHealPhase: boolean = false, doNotContinue: boolean = false) {
const allowedPkm = gScene.getParty().filter((pkm) => pkm.isAllowedInBattle());
if (allowedPkm.length === 0) {
scene.clearPhaseQueue();
scene.unshiftPhase(new GameOverPhase(scene));
gScene.clearPhaseQueue();
gScene.unshiftPhase(new GameOverPhase());
return;
}
// If in repeated encounter variant, do nothing
// Variant must eventually be swapped in order to handle "true" end of the encounter
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
if (encounter.continuousEncounter || doNotContinue) {
return;
} else if (encounter.encounterMode === MysteryEncounterMode.NO_BATTLE) {
scene.pushPhase(new MysteryEncounterRewardsPhase(scene, addHealPhase));
scene.pushPhase(new EggLapsePhase(scene));
} else if (!scene.getEnemyParty().find(p => encounter.encounterMode !== MysteryEncounterMode.TRAINER_BATTLE ? p.isOnField() : !p?.isFainted(true))) {
scene.pushPhase(new BattleEndPhase(scene));
gScene.pushPhase(new MysteryEncounterRewardsPhase(addHealPhase));
gScene.pushPhase(new EggLapsePhase());
} else if (!gScene.getEnemyParty().find(p => encounter.encounterMode !== MysteryEncounterMode.TRAINER_BATTLE ? p.isOnField() : !p?.isFainted(true))) {
gScene.pushPhase(new BattleEndPhase());
if (encounter.encounterMode === MysteryEncounterMode.TRAINER_BATTLE) {
scene.pushPhase(new TrainerVictoryPhase(scene));
gScene.pushPhase(new TrainerVictoryPhase());
}
if (scene.gameMode.isEndless || !scene.gameMode.isWaveFinal(scene.currentBattle.waveIndex)) {
scene.pushPhase(new MysteryEncounterRewardsPhase(scene, addHealPhase));
if (gScene.gameMode.isEndless || !gScene.gameMode.isWaveFinal(gScene.currentBattle.waveIndex)) {
gScene.pushPhase(new MysteryEncounterRewardsPhase(addHealPhase));
if (!encounter.doContinueEncounter) {
// Only lapse eggs once for multi-battle encounters
scene.pushPhase(new EggLapsePhase(scene));
gScene.pushPhase(new EggLapsePhase());
}
}
}
@ -749,29 +749,29 @@ export function handleMysteryEncounterVictory(scene: BattleScene, addHealPhase:
* @param scene
* @param addHealPhase
*/
export function handleMysteryEncounterBattleFailed(scene: BattleScene, addHealPhase: boolean = false, doNotContinue: boolean = false) {
const allowedPkm = scene.getParty().filter((pkm) => pkm.isAllowedInBattle());
export function handleMysteryEncounterBattleFailed(addHealPhase: boolean = false, doNotContinue: boolean = false) {
const allowedPkm = gScene.getParty().filter((pkm) => pkm.isAllowedInBattle());
if (allowedPkm.length === 0) {
scene.clearPhaseQueue();
scene.unshiftPhase(new GameOverPhase(scene));
gScene.clearPhaseQueue();
gScene.unshiftPhase(new GameOverPhase());
return;
}
// If in repeated encounter variant, do nothing
// Variant must eventually be swapped in order to handle "true" end of the encounter
const encounter = scene.currentBattle.mysteryEncounter!;
const encounter = gScene.currentBattle.mysteryEncounter!;
if (encounter.continuousEncounter || doNotContinue) {
return;
} else if (encounter.encounterMode !== MysteryEncounterMode.NO_BATTLE) {
scene.pushPhase(new BattleEndPhase(scene, false));
gScene.pushPhase(new BattleEndPhase(false));
}
scene.pushPhase(new MysteryEncounterRewardsPhase(scene, addHealPhase));
gScene.pushPhase(new MysteryEncounterRewardsPhase(addHealPhase));
if (!encounter.doContinueEncounter) {
// Only lapse eggs once for multi-battle encounters
scene.pushPhase(new EggLapsePhase(scene));
gScene.pushPhase(new EggLapsePhase());
}
}
@ -782,12 +782,12 @@ export function handleMysteryEncounterBattleFailed(scene: BattleScene, addHealPh
* @param destroy - If true, will destroy visuals ONLY ON HIDE TRANSITION. Does nothing on show. Defaults to true
* @param duration
*/
export function transitionMysteryEncounterIntroVisuals(scene: BattleScene, hide: boolean = true, destroy: boolean = true, duration: number = 750): Promise<boolean> {
export function transitionMysteryEncounterIntroVisuals(hide: boolean = true, destroy: boolean = true, duration: number = 750): Promise<boolean> {
return new Promise(resolve => {
const introVisuals = scene.currentBattle.mysteryEncounter!.introVisuals;
const enemyPokemon = scene.getEnemyField();
const introVisuals = gScene.currentBattle.mysteryEncounter!.introVisuals;
const enemyPokemon = gScene.getEnemyField();
if (enemyPokemon) {
scene.currentBattle.enemyParty = [];
gScene.currentBattle.enemyParty = [];
}
if (introVisuals) {
if (!hide) {
@ -799,7 +799,7 @@ export function transitionMysteryEncounterIntroVisuals(scene: BattleScene, hide:
}
// Transition
scene.tweens.add({
gScene.tweens.add({
targets: [ introVisuals, enemyPokemon ],
x: `${hide ? "+" : "-"}=16`,
y: `${hide ? "-" : "+"}=16`,
@ -808,13 +808,13 @@ export function transitionMysteryEncounterIntroVisuals(scene: BattleScene, hide:
duration,
onComplete: () => {
if (hide && destroy) {
scene.field.remove(introVisuals, true);
gScene.field.remove(introVisuals, true);
enemyPokemon.forEach(pokemon => {
scene.field.remove(pokemon, true);
gScene.field.remove(pokemon, true);
});
scene.currentBattle.mysteryEncounter!.introVisuals = undefined;
gScene.currentBattle.mysteryEncounter!.introVisuals = undefined;
}
resolve(true);
}
@ -830,9 +830,9 @@ export function transitionMysteryEncounterIntroVisuals(scene: BattleScene, hide:
* Mostly useful for allowing {@linkcode MysteryEncounter} enemies to "cheat" and use moves before the first turn
* @param scene
*/
export function handleMysteryEncounterBattleStartEffects(scene: BattleScene) {
const encounter = scene.currentBattle.mysteryEncounter;
if (scene.currentBattle.isBattleMysteryEncounter() && encounter && encounter.encounterMode !== MysteryEncounterMode.NO_BATTLE && !encounter.startOfBattleEffectsComplete) {
export function handleMysteryEncounterBattleStartEffects() {
const encounter = gScene.currentBattle.mysteryEncounter;
if (gScene.currentBattle.isBattleMysteryEncounter() && encounter && encounter.encounterMode !== MysteryEncounterMode.NO_BATTLE && !encounter.startOfBattleEffectsComplete) {
const effects = encounter.startOfBattleEffects;
effects.forEach(effect => {
let source;
@ -840,24 +840,24 @@ export function handleMysteryEncounterBattleStartEffects(scene: BattleScene) {
source = effect.sourcePokemon;
} else if (!isNullOrUndefined(effect.sourceBattlerIndex)) {
if (effect.sourceBattlerIndex === BattlerIndex.ATTACKER) {
source = scene.getEnemyField()[0];
source = gScene.getEnemyField()[0];
} else if (effect.sourceBattlerIndex === BattlerIndex.ENEMY) {
source = scene.getEnemyField()[0];
source = gScene.getEnemyField()[0];
} else if (effect.sourceBattlerIndex === BattlerIndex.ENEMY_2) {
source = scene.getEnemyField()[1];
source = gScene.getEnemyField()[1];
} else if (effect.sourceBattlerIndex === BattlerIndex.PLAYER) {
source = scene.getPlayerField()[0];
source = gScene.getPlayerField()[0];
} else if (effect.sourceBattlerIndex === BattlerIndex.PLAYER_2) {
source = scene.getPlayerField()[1];
source = gScene.getPlayerField()[1];
}
} else {
source = scene.getEnemyField()[0];
source = gScene.getEnemyField()[0];
}
scene.pushPhase(new MovePhase(scene, source, effect.targets, effect.move, effect.followUp, effect.ignorePp));
gScene.pushPhase(new MovePhase(source, effect.targets, effect.move, effect.followUp, effect.ignorePp));
});
// Pseudo turn end phase to reset flinch states, Endure, etc.
scene.pushPhase(new MysteryEncounterBattleStartCleanupPhase(scene));
gScene.pushPhase(new MysteryEncounterBattleStartCleanupPhase());
encounter.startOfBattleEffectsComplete = true;
}
@ -869,10 +869,10 @@ export function handleMysteryEncounterBattleStartEffects(scene: BattleScene) {
* @param scene
* @return boolean - if true, will skip the remainder of the {@linkcode TurnInitPhase}
*/
export function handleMysteryEncounterTurnStartEffects(scene: BattleScene): boolean {
const encounter = scene.currentBattle.mysteryEncounter;
if (scene.currentBattle.isBattleMysteryEncounter() && encounter && encounter.onTurnStart) {
return encounter.onTurnStart(scene);
export function handleMysteryEncounterTurnStartEffects(): boolean {
const encounter = gScene.currentBattle.mysteryEncounter;
if (gScene.currentBattle.isBattleMysteryEncounter() && encounter && encounter.onTurnStart) {
return encounter.onTurnStart();
}
return false;
@ -884,7 +884,7 @@ export function handleMysteryEncounterTurnStartEffects(scene: BattleScene): bool
* @param scene
* @param baseSpawnWeight
*/
export function calculateMEAggregateStats(scene: BattleScene, baseSpawnWeight: number) {
export function calculateMEAggregateStats(baseSpawnWeight: number) {
const numRuns = 1000;
let run = 0;
const biomes = Object.keys(Biome).filter(key => isNaN(Number(key)));
@ -897,9 +897,9 @@ export function calculateMEAggregateStats(scene: BattleScene, baseSpawnWeight: n
const encountersByBiome = new Map<string, number>(biomes.map(b => [ b, 0 ]));
const validMEfloorsByBiome = new Map<string, number>(biomes.map(b => [ b, 0 ]));
let currentBiome = Biome.TOWN;
let currentArena = scene.newArena(currentBiome);
scene.setSeed(Utils.randomString(24));
scene.resetSeed();
let currentArena = gScene.newArena(currentBiome);
gScene.setSeed(Utils.randomString(24));
gScene.resetSeed();
for (let i = 10; i < 180; i++) {
// Boss
if (i % 10 === 0) {
@ -910,7 +910,7 @@ export function calculateMEAggregateStats(scene: BattleScene, baseSpawnWeight: n
if (i % 10 === 1) {
if (Array.isArray(biomeLinks[currentBiome])) {
let biomes: Biome[];
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
biomes = (biomeLinks[currentBiome] as (Biome | [Biome, number])[])
.filter(b => {
return !Array.isArray(b) || !Utils.randSeedInt(b[1]);
@ -931,20 +931,20 @@ export function calculateMEAggregateStats(scene: BattleScene, baseSpawnWeight: n
if (!(i % 50)) {
currentBiome = Biome.END;
} else {
currentBiome = scene.generateRandomBiome(i);
currentBiome = gScene.generateRandomBiome(i);
}
}
currentArena = scene.newArena(currentBiome);
currentArena = gScene.newArena(currentBiome);
}
// Fixed battle
if (scene.gameMode.isFixedBattle(i)) {
if (gScene.gameMode.isFixedBattle(i)) {
continue;
}
// Trainer
if (scene.gameMode.isWaveTrainer(i, currentArena)) {
if (gScene.gameMode.isWaveTrainer(i, currentArena)) {
continue;
}
@ -994,7 +994,7 @@ export function calculateMEAggregateStats(scene: BattleScene, baseSpawnWeight: n
const encountersByBiomeRuns: Map<string, number>[] = [];
const validFloorsByBiome: Map<string, number>[] = [];
while (run < numRuns) {
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
const [ numEncounters, encountersByBiome, validMEfloorsByBiome ] = calculateNumEncounters();
encounterRuns.push(numEncounters);
encountersByBiomeRuns.push(encountersByBiome);
@ -1049,14 +1049,14 @@ export function calculateMEAggregateStats(scene: BattleScene, baseSpawnWeight: n
* @param scene
* @param luckValue - 0 to 14
*/
export function calculateRareSpawnAggregateStats(scene: BattleScene, luckValue: number) {
export function calculateRareSpawnAggregateStats(luckValue: number) {
const numRuns = 1000;
let run = 0;
const calculateNumRareEncounters = (): any[] => {
const bossEncountersByRarity = [ 0, 0, 0, 0 ];
scene.setSeed(Utils.randomString(24));
scene.resetSeed();
gScene.setSeed(Utils.randomString(24));
gScene.resetSeed();
// There are 12 wild boss floors
for (let i = 0; i < 12; i++) {
// Roll boss tier
@ -1090,7 +1090,7 @@ export function calculateRareSpawnAggregateStats(scene: BattleScene, luckValue:
const encounterRuns: number[][] = [];
while (run < numRuns) {
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
const bossEncountersByRarity = calculateNumRareEncounters();
encounterRuns.push(bossEncountersByRarity);
}, 1000 * run);

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import i18next from "i18next";
import { isNullOrUndefined, randSeedInt } from "#app/utils";
import { PokemonHeldItemModifier } from "#app/modifier/modifier";
@ -43,7 +43,6 @@ export function getSpriteKeysFromSpecies(species: Species, female?: boolean, for
/**
* Gets the sprite key and file root for a given Pokemon (accounts for gender, shiny, variants, forms, and experimental)
* @param pokemon
*/
export function getSpriteKeysFromPokemon(pokemon: Pokemon): { spriteKey: string, fileRoot: string } {
const spriteKey = pokemon.getSpeciesForm().getSpriteKey(pokemon.getGender() === Gender.FEMALE, pokemon.formIndex, pokemon.shiny, pokemon.variant);
@ -55,14 +54,13 @@ export function getSpriteKeysFromPokemon(pokemon: Pokemon): { spriteKey: string,
/**
* Will never remove the player's last non-fainted Pokemon (if they only have 1)
* Otherwise, picks a Pokemon completely at random and removes from the party
* @param scene
* @param isAllowed Default false. If true, only picks from legal mons. If no legal mons are found (or there is 1, with `doNotReturnLastAllowedMon = true), will return a mon that is not allowed.
* @param isFainted Default false. If true, includes fainted mons.
* @param doNotReturnLastAllowedMon Default false. If true, will never return the last unfainted pokemon in the party. Useful when this function is being used to determine what Pokemon to remove from the party (Don't want to remove last unfainted)
* @returns
*/
export function getRandomPlayerPokemon(scene: BattleScene, isAllowed: boolean = false, isFainted: boolean = false, doNotReturnLastAllowedMon: boolean = false): PlayerPokemon {
const party = scene.getParty();
export function getRandomPlayerPokemon(isAllowed: boolean = false, isFainted: boolean = false, doNotReturnLastAllowedMon: boolean = false): PlayerPokemon {
const party = gScene.getParty();
let chosenIndex: number;
let chosenPokemon: PlayerPokemon | null = null;
const fullyLegalMons = party.filter(p => (!isAllowed || p.isAllowed()) && (isFainted || !p.isFainted()));
@ -100,8 +98,8 @@ export function getRandomPlayerPokemon(scene: BattleScene, isAllowed: boolean =
* @param isFainted Default false. If true, includes fainted mons.
* @returns
*/
export function getHighestLevelPlayerPokemon(scene: BattleScene, isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon {
const party = scene.getParty();
export function getHighestLevelPlayerPokemon(isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon {
const party = gScene.getParty();
let pokemon: PlayerPokemon | null = null;
for (const p of party) {
@ -126,8 +124,8 @@ export function getHighestLevelPlayerPokemon(scene: BattleScene, isAllowed: bool
* @param isFainted Default false. If true, includes fainted mons.
* @returns
*/
export function getHighestStatPlayerPokemon(scene: BattleScene, stat: PermanentStat, isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon {
const party = scene.getParty();
export function getHighestStatPlayerPokemon(stat: PermanentStat, isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon {
const party = gScene.getParty();
let pokemon: PlayerPokemon | null = null;
for (const p of party) {
@ -151,8 +149,8 @@ export function getHighestStatPlayerPokemon(scene: BattleScene, stat: PermanentS
* @param isFainted Default false. If true, includes fainted mons.
* @returns
*/
export function getLowestLevelPlayerPokemon(scene: BattleScene, isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon {
const party = scene.getParty();
export function getLowestLevelPlayerPokemon(isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon {
const party = gScene.getParty();
let pokemon: PlayerPokemon | null = null;
for (const p of party) {
@ -176,8 +174,8 @@ export function getLowestLevelPlayerPokemon(scene: BattleScene, isAllowed: boole
* @param isFainted Default false. If true, includes fainted mons.
* @returns
*/
export function getHighestStatTotalPlayerPokemon(scene: BattleScene, isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon {
const party = scene.getParty();
export function getHighestStatTotalPlayerPokemon(isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon {
const party = gScene.getParty();
let pokemon: PlayerPokemon | null = null;
for (const p of party) {
@ -251,11 +249,11 @@ export function getRandomSpeciesByStarterTier(starterTiers: number | [number, nu
* @param scene the battle scene
* @param pokemon the player pokemon to KO
*/
export function koPlayerPokemon(scene: BattleScene, pokemon: PlayerPokemon) {
export function koPlayerPokemon(pokemon: PlayerPokemon) {
pokemon.hp = 0;
pokemon.trySetStatus(StatusEffect.FAINT);
pokemon.updateInfo();
queueEncounterMessage(scene, i18next.t("battle:fainted", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
queueEncounterMessage(i18next.t("battle:fainted", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
}
/**
@ -267,11 +265,11 @@ export function koPlayerPokemon(scene: BattleScene, pokemon: PlayerPokemon) {
* @param value the hp change amount. Positive for heal. Negative for damage
*
*/
function applyHpChangeToPokemon(scene: BattleScene, pokemon: PlayerPokemon, value: number) {
function applyHpChangeToPokemon(pokemon: PlayerPokemon, value: number) {
const hpChange = Math.round(pokemon.hp + value);
const nextHp = Math.max(Math.min(hpChange, pokemon.getMaxHp()), 0);
if (nextHp === 0) {
koPlayerPokemon(scene, pokemon);
koPlayerPokemon(pokemon);
} else {
pokemon.hp = nextHp;
}
@ -284,12 +282,12 @@ function applyHpChangeToPokemon(scene: BattleScene, pokemon: PlayerPokemon, valu
* @param damage the amount of damage to apply
* @see {@linkcode applyHpChangeToPokemon}
*/
export function applyDamageToPokemon(scene: BattleScene, pokemon: PlayerPokemon, damage: number) {
export function applyDamageToPokemon(pokemon: PlayerPokemon, damage: number) {
if (damage <= 0) {
console.warn("Healing pokemon with `applyDamageToPokemon` is not recommended! Please use `applyHealToPokemon` instead.");
}
applyHpChangeToPokemon(scene, pokemon, -damage);
applyHpChangeToPokemon(pokemon, -damage);
}
/**
@ -299,12 +297,12 @@ export function applyDamageToPokemon(scene: BattleScene, pokemon: PlayerPokemon,
* @param heal the amount of heal to apply
* @see {@linkcode applyHpChangeToPokemon}
*/
export function applyHealToPokemon(scene: BattleScene, pokemon: PlayerPokemon, heal: number) {
export function applyHealToPokemon(pokemon: PlayerPokemon, heal: number) {
if (heal <= 0) {
console.warn("Damaging pokemon with `applyHealToPokemon` is not recommended! Please use `applyDamageToPokemon` instead.");
}
applyHpChangeToPokemon(scene, pokemon, heal);
applyHpChangeToPokemon(pokemon, heal);
}
/**
@ -315,11 +313,11 @@ export function applyHealToPokemon(scene: BattleScene, pokemon: PlayerPokemon, h
*/
export async function modifyPlayerPokemonBST(pokemon: PlayerPokemon, value: number) {
const modType = modifierTypes.MYSTERY_ENCOUNTER_SHUCKLE_JUICE()
.generateType(pokemon.scene.getParty(), [ value ])
.generateType(gScene.getParty(), [ value ])
?.withIdFromFunc(modifierTypes.MYSTERY_ENCOUNTER_SHUCKLE_JUICE);
const modifier = modType?.newModifier(pokemon);
if (modifier) {
await pokemon.scene.addModifier(modifier, false, false, false, true);
await gScene.addModifier(modifier, false, false, false, true);
pokemon.calculateStats();
}
}
@ -332,10 +330,10 @@ export async function modifyPlayerPokemonBST(pokemon: PlayerPokemon, value: numb
* @param modType
* @param fallbackModifierType
*/
export async function applyModifierTypeToPlayerPokemon(scene: BattleScene, pokemon: PlayerPokemon, modType: PokemonHeldItemModifierType, fallbackModifierType?: PokemonHeldItemModifierType) {
export async function applyModifierTypeToPlayerPokemon(pokemon: PlayerPokemon, modType: PokemonHeldItemModifierType, fallbackModifierType?: PokemonHeldItemModifierType) {
// Check if the Pokemon has max stacks of that item already
const modifier = modType.newModifier(pokemon);
const existing = scene.findModifier(m => (
const existing = gScene.findModifier(m => (
m instanceof PokemonHeldItemModifier &&
m.type.id === modType.id &&
m.pokemonId === pokemon.id &&
@ -343,16 +341,16 @@ export async function applyModifierTypeToPlayerPokemon(scene: BattleScene, pokem
)) as PokemonHeldItemModifier;
// At max stacks
if (existing && existing.getStackCount() >= existing.getMaxStackCount(scene)) {
if (existing && existing.getStackCount() >= existing.getMaxStackCount()) {
if (!fallbackModifierType) {
return;
}
// Apply fallback
return applyModifierTypeToPlayerPokemon(scene, pokemon, fallbackModifierType);
return applyModifierTypeToPlayerPokemon(pokemon, fallbackModifierType);
}
await scene.addModifier(modifier, false, false, false, true);
await gScene.addModifier(modifier, false, false, false, true);
}
/**
@ -366,7 +364,7 @@ export async function applyModifierTypeToPlayerPokemon(scene: BattleScene, pokem
* @param pokeballType
* @param ballTwitchRate - can pass custom ball catch rates (for special events, like safari)
*/
export function trainerThrowPokeball(scene: BattleScene, pokemon: EnemyPokemon, pokeballType: PokeballType, ballTwitchRate?: number): Promise<boolean> {
export function trainerThrowPokeball(pokemon: EnemyPokemon, pokeballType: PokeballType, ballTwitchRate?: number): Promise<boolean> {
const originalY: number = pokemon.y;
if (!ballTwitchRate) {
@ -381,43 +379,43 @@ export function trainerThrowPokeball(scene: BattleScene, pokemon: EnemyPokemon,
const fpOffset = pokemon.getFieldPositionOffset();
const pokeballAtlasKey = getPokeballAtlasKey(pokeballType);
const pokeball: Phaser.GameObjects.Sprite = scene.addFieldSprite(16 + 75, 80 + 25, "pb", pokeballAtlasKey);
const pokeball: Phaser.GameObjects.Sprite = gScene.addFieldSprite(16 + 75, 80 + 25, "pb", pokeballAtlasKey);
pokeball.setOrigin(0.5, 0.625);
scene.field.add(pokeball);
gScene.field.add(pokeball);
scene.time.delayedCall(300, () => {
scene.field.moveBelow(pokeball as Phaser.GameObjects.GameObject, pokemon);
gScene.time.delayedCall(300, () => {
gScene.field.moveBelow(pokeball as Phaser.GameObjects.GameObject, pokemon);
});
return new Promise(resolve => {
scene.trainer.setTexture(`trainer_${scene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`);
scene.time.delayedCall(512, () => {
scene.playSound("se/pb_throw");
gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`);
gScene.time.delayedCall(512, () => {
gScene.playSound("se/pb_throw");
// Trainer throw frames
scene.trainer.setFrame("2");
scene.time.delayedCall(256, () => {
scene.trainer.setFrame("3");
scene.time.delayedCall(768, () => {
scene.trainer.setTexture(`trainer_${scene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`);
gScene.trainer.setFrame("2");
gScene.time.delayedCall(256, () => {
gScene.trainer.setFrame("3");
gScene.time.delayedCall(768, () => {
gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`);
});
});
// Pokeball move and catch logic
scene.tweens.add({
gScene.tweens.add({
targets: pokeball,
x: { value: 236 + fpOffset[0], ease: "Linear" },
y: { value: 16 + fpOffset[1], ease: "Cubic.easeOut" },
duration: 500,
onComplete: () => {
pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
scene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
scene.playSound("se/pb_rel");
gScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
gScene.playSound("se/pb_rel");
pokemon.tint(getPokeballTintColor(pokeballType));
addPokeballOpenParticles(scene, pokeball.x, pokeball.y, pokeballType);
addPokeballOpenParticles(pokeball.x, pokeball.y, pokeballType);
scene.tweens.add({
gScene.tweens.add({
targets: pokemon,
duration: 500,
ease: "Sine.easeIn",
@ -426,13 +424,13 @@ export function trainerThrowPokeball(scene: BattleScene, pokemon: EnemyPokemon,
onComplete: () => {
pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
pokemon.setVisible(false);
scene.playSound("se/pb_catch");
scene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}`));
gScene.playSound("se/pb_catch");
gScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}`));
const doShake = () => {
let shakeCount = 0;
const pbX = pokeball.x;
const shakeCounter = scene.tweens.addCounter({
const shakeCounter = gScene.tweens.addCounter({
from: 0,
to: 1,
repeat: 4,
@ -451,30 +449,30 @@ export function trainerThrowPokeball(scene: BattleScene, pokemon: EnemyPokemon,
onRepeat: () => {
if (!pokemon.species.isObtainable()) {
shakeCounter.stop();
failCatch(scene, pokemon, originalY, pokeball, pokeballType).then(() => resolve(false));
failCatch(pokemon, originalY, pokeball, pokeballType).then(() => resolve(false));
} else if (shakeCount++ < 3) {
if (randSeedInt(65536) < ballTwitchRate) {
scene.playSound("se/pb_move");
gScene.playSound("se/pb_move");
} else {
shakeCounter.stop();
failCatch(scene, pokemon, originalY, pokeball, pokeballType).then(() => resolve(false));
failCatch(pokemon, originalY, pokeball, pokeballType).then(() => resolve(false));
}
} else {
scene.playSound("se/pb_lock");
addPokeballCaptureStars(scene, pokeball);
gScene.playSound("se/pb_lock");
addPokeballCaptureStars(pokeball);
const pbTint = scene.add.sprite(pokeball.x, pokeball.y, "pb", "pb");
const pbTint = gScene.add.sprite(pokeball.x, pokeball.y, "pb", "pb");
pbTint.setOrigin(pokeball.originX, pokeball.originY);
pbTint.setTintFill(0);
pbTint.setAlpha(0);
scene.field.add(pbTint);
scene.tweens.add({
gScene.field.add(pbTint);
gScene.tweens.add({
targets: pbTint,
alpha: 0.375,
duration: 200,
easing: "Sine.easeOut",
onComplete: () => {
scene.tweens.add({
gScene.tweens.add({
targets: pbTint,
alpha: 0,
duration: 200,
@ -486,12 +484,12 @@ export function trainerThrowPokeball(scene: BattleScene, pokemon: EnemyPokemon,
}
},
onComplete: () => {
catchPokemon(scene, pokemon, pokeball, pokeballType).then(() => resolve(true));
catchPokemon(pokemon, pokeball, pokeballType).then(() => resolve(true));
}
});
};
scene.time.delayedCall(250, () => doPokeballBounceAnim(scene, pokeball, 16, 72, 350, doShake));
gScene.time.delayedCall(250, () => doPokeballBounceAnim(pokeball, 16, 72, 350, doShake));
}
});
}
@ -508,9 +506,9 @@ export function trainerThrowPokeball(scene: BattleScene, pokemon: EnemyPokemon,
* @param pokeball
* @param pokeballType
*/
function failCatch(scene: BattleScene, pokemon: EnemyPokemon, originalY: number, pokeball: Phaser.GameObjects.Sprite, pokeballType: PokeballType) {
function failCatch(pokemon: EnemyPokemon, originalY: number, pokeball: Phaser.GameObjects.Sprite, pokeballType: PokeballType) {
return new Promise<void>(resolve => {
scene.playSound("se/pb_rel");
gScene.playSound("se/pb_rel");
pokemon.setY(originalY);
if (pokemon.status?.effect !== StatusEffect.SLEEP) {
pokemon.cry(pokemon.getHpRatio() > 0.25 ? undefined : { rate: 0.85 });
@ -521,19 +519,19 @@ function failCatch(scene: BattleScene, pokemon: EnemyPokemon, originalY: number,
const pokeballAtlasKey = getPokeballAtlasKey(pokeballType);
pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
scene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
gScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
scene.tweens.add({
gScene.tweens.add({
targets: pokemon,
duration: 250,
ease: "Sine.easeOut",
scale: 1
});
scene.currentBattle.lastUsedPokeball = pokeballType;
removePb(scene, pokeball);
gScene.currentBattle.lastUsedPokeball = pokeballType;
removePb(pokeball);
scene.ui.showText(i18next.t("battle:pokemonBrokeFree", { pokemonName: pokemon.getNameToRender() }), null, () => resolve(), null, true);
gScene.ui.showText(i18next.t("battle:pokemonBrokeFree", { pokemonName: pokemon.getNameToRender() }), null, () => resolve(), null, true);
});
}
@ -546,56 +544,56 @@ function failCatch(scene: BattleScene, pokemon: EnemyPokemon, originalY: number,
* @param showCatchObtainMessage
* @param isObtain
*/
export async function catchPokemon(scene: BattleScene, pokemon: EnemyPokemon, pokeball: Phaser.GameObjects.Sprite | null, pokeballType: PokeballType, showCatchObtainMessage: boolean = true, isObtain: boolean = false): Promise<void> {
export async function catchPokemon(pokemon: EnemyPokemon, pokeball: Phaser.GameObjects.Sprite | null, pokeballType: PokeballType, showCatchObtainMessage: boolean = true, isObtain: boolean = false): Promise<void> {
const speciesForm = !pokemon.fusionSpecies ? pokemon.getSpeciesForm() : pokemon.getFusionSpeciesForm();
if (speciesForm.abilityHidden && (pokemon.fusionSpecies ? pokemon.fusionAbilityIndex : pokemon.abilityIndex) === speciesForm.getAbilityCount() - 1) {
scene.validateAchv(achvs.HIDDEN_ABILITY);
gScene.validateAchv(achvs.HIDDEN_ABILITY);
}
if (pokemon.species.subLegendary) {
scene.validateAchv(achvs.CATCH_SUB_LEGENDARY);
gScene.validateAchv(achvs.CATCH_SUB_LEGENDARY);
}
if (pokemon.species.legendary) {
scene.validateAchv(achvs.CATCH_LEGENDARY);
gScene.validateAchv(achvs.CATCH_LEGENDARY);
}
if (pokemon.species.mythical) {
scene.validateAchv(achvs.CATCH_MYTHICAL);
gScene.validateAchv(achvs.CATCH_MYTHICAL);
}
scene.pokemonInfoContainer.show(pokemon, true);
gScene.pokemonInfoContainer.show(pokemon, true);
scene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs);
gScene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs);
return new Promise(resolve => {
const doPokemonCatchMenu = () => {
const end = () => {
// Ensure the pokemon is in the enemy party in all situations
if (!scene.getEnemyParty().some(p => p.id === pokemon.id)) {
scene.getEnemyParty().push(pokemon);
if (!gScene.getEnemyParty().some(p => p.id === pokemon.id)) {
gScene.getEnemyParty().push(pokemon);
}
scene.unshiftPhase(new VictoryPhase(scene, pokemon.id, true));
scene.pokemonInfoContainer.hide();
gScene.unshiftPhase(new VictoryPhase(pokemon.id, true));
gScene.pokemonInfoContainer.hide();
if (pokeball) {
removePb(scene, pokeball);
removePb(pokeball);
}
resolve();
};
const removePokemon = () => {
if (pokemon) {
scene.field.remove(pokemon, true);
gScene.field.remove(pokemon, true);
}
};
const addToParty = (slotIndex?: number) => {
const newPokemon = pokemon.addToParty(pokeballType, slotIndex);
const modifiers = scene.findModifiers(m => m instanceof PokemonHeldItemModifier, false);
if (scene.getParty().filter(p => p.isShiny()).length === 6) {
scene.validateAchv(achvs.SHINY_PARTY);
const modifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier, false);
if (gScene.getParty().filter(p => p.isShiny()).length === 6) {
gScene.validateAchv(achvs.SHINY_PARTY);
}
Promise.all(modifiers.map(m => scene.addModifier(m, true))).then(() => {
scene.updateModifiers(true);
Promise.all(modifiers.map(m => gScene.addModifier(m, true))).then(() => {
gScene.updateModifiers(true);
removePokemon();
if (newPokemon) {
newPokemon.loadAssets().then(end);
@ -604,21 +602,21 @@ export async function catchPokemon(scene: BattleScene, pokemon: EnemyPokemon, po
}
});
};
Promise.all([ pokemon.hideInfo(), scene.gameData.setPokemonCaught(pokemon) ]).then(() => {
if (scene.getParty().length === 6) {
Promise.all([ pokemon.hideInfo(), gScene.gameData.setPokemonCaught(pokemon) ]).then(() => {
if (gScene.getParty().length === 6) {
const promptRelease = () => {
scene.ui.showText(i18next.t("battle:partyFull", { pokemonName: pokemon.getNameToRender() }), null, () => {
scene.pokemonInfoContainer.makeRoomForConfirmUi(1, true);
scene.ui.setMode(Mode.CONFIRM, () => {
const newPokemon = scene.addPlayerPokemon(pokemon.species, pokemon.level, pokemon.abilityIndex, pokemon.formIndex, pokemon.gender, pokemon.shiny, pokemon.variant, pokemon.ivs, pokemon.nature, pokemon);
scene.ui.setMode(Mode.SUMMARY, newPokemon, 0, SummaryUiMode.DEFAULT, () => {
scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.showText(i18next.t("battle:partyFull", { pokemonName: pokemon.getNameToRender() }), null, () => {
gScene.pokemonInfoContainer.makeRoomForConfirmUi(1, true);
gScene.ui.setMode(Mode.CONFIRM, () => {
const newPokemon = gScene.addPlayerPokemon(pokemon.species, pokemon.level, pokemon.abilityIndex, pokemon.formIndex, pokemon.gender, pokemon.shiny, pokemon.variant, pokemon.ivs, pokemon.nature, pokemon);
gScene.ui.setMode(Mode.SUMMARY, newPokemon, 0, SummaryUiMode.DEFAULT, () => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
promptRelease();
});
}, false);
}, () => {
scene.ui.setMode(Mode.PARTY, PartyUiMode.RELEASE, 0, (slotIndex: integer, _option: PartyOption) => {
scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.setMode(Mode.PARTY, PartyUiMode.RELEASE, 0, (slotIndex: integer, _option: PartyOption) => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
if (slotIndex < 6) {
addToParty(slotIndex);
} else {
@ -627,7 +625,7 @@ export async function catchPokemon(scene: BattleScene, pokemon: EnemyPokemon, po
});
});
}, () => {
scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
removePokemon();
end();
});
@ -642,7 +640,7 @@ export async function catchPokemon(scene: BattleScene, pokemon: EnemyPokemon, po
};
if (showCatchObtainMessage) {
scene.ui.showText(i18next.t(isObtain ? "battle:pokemonObtained" : "battle:pokemonCaught", { pokemonName: pokemon.getNameToRender() }), null, doPokemonCatchMenu, 0, true);
gScene.ui.showText(i18next.t(isObtain ? "battle:pokemonObtained" : "battle:pokemonCaught", { pokemonName: pokemon.getNameToRender() }), null, doPokemonCatchMenu, 0, true);
} else {
doPokemonCatchMenu();
}
@ -654,9 +652,9 @@ export async function catchPokemon(scene: BattleScene, pokemon: EnemyPokemon, po
* @param scene
* @param pokeball
*/
function removePb(scene: BattleScene, pokeball: Phaser.GameObjects.Sprite) {
function removePb(pokeball: Phaser.GameObjects.Sprite) {
if (pokeball) {
scene.tweens.add({
gScene.tweens.add({
targets: pokeball,
duration: 250,
delay: 250,
@ -674,11 +672,11 @@ function removePb(scene: BattleScene, pokeball: Phaser.GameObjects.Sprite) {
* @param scene
* @param pokemon
*/
export async function doPokemonFlee(scene: BattleScene, pokemon: EnemyPokemon): Promise<void> {
export async function doPokemonFlee(pokemon: EnemyPokemon): Promise<void> {
await new Promise<void>(resolve => {
scene.playSound("se/flee");
gScene.playSound("se/flee");
// Ease pokemon out
scene.tweens.add({
gScene.tweens.add({
targets: pokemon,
x: "+=16",
y: "-=16",
@ -688,8 +686,8 @@ export async function doPokemonFlee(scene: BattleScene, pokemon: EnemyPokemon):
scale: pokemon.getSpriteScale(),
onComplete: () => {
pokemon.setVisible(false);
scene.field.remove(pokemon, true);
showEncounterText(scene, i18next.t("battle:pokemonFled", { pokemonName: pokemon.getNameToRender() }), null, 600, false)
gScene.field.remove(pokemon, true);
showEncounterText(i18next.t("battle:pokemonFled", { pokemonName: pokemon.getNameToRender() }), null, 600, false)
.then(() => {
resolve();
});
@ -703,10 +701,10 @@ export async function doPokemonFlee(scene: BattleScene, pokemon: EnemyPokemon):
* @param scene
* @param pokemon
*/
export function doPlayerFlee(scene: BattleScene, pokemon: EnemyPokemon): Promise<void> {
export function doPlayerFlee(pokemon: EnemyPokemon): Promise<void> {
return new Promise<void>(resolve => {
// Ease pokemon out
scene.tweens.add({
gScene.tweens.add({
targets: pokemon,
x: "+=16",
y: "-=16",
@ -716,8 +714,8 @@ export function doPlayerFlee(scene: BattleScene, pokemon: EnemyPokemon): Promise
scale: pokemon.getSpriteScale(),
onComplete: () => {
pokemon.setVisible(false);
scene.field.remove(pokemon, true);
showEncounterText(scene, i18next.t("battle:playerFled", { pokemonName: pokemon.getNameToRender() }), null, 600, false)
gScene.field.remove(pokemon, true);
showEncounterText(i18next.t("battle:playerFled", { pokemonName: pokemon.getNameToRender() }), null, 600, false)
.then(() => {
resolve();
});
@ -785,35 +783,35 @@ export function getGoldenBugNetSpecies(level: number): PokemonSpecies {
* @param scene
* @param levelAdditiveModifier Default 0. will add +(1 level / 10 waves * levelAdditiveModifier) to the level calculation
*/
export function getEncounterPokemonLevelForWave(scene: BattleScene, levelAdditiveModifier: number = 0) {
const currentBattle = scene.currentBattle;
export function getEncounterPokemonLevelForWave(levelAdditiveModifier: number = 0) {
const currentBattle = gScene.currentBattle;
const baseLevel = currentBattle.getLevelForWave();
// Add a level scaling modifier that is (+1 level per 10 waves) * levelAdditiveModifier
return baseLevel + Math.max(Math.round((currentBattle.waveIndex / 10) * levelAdditiveModifier), 0);
}
export async function addPokemonDataToDexAndValidateAchievements(scene: BattleScene, pokemon: PlayerPokemon) {
export async function addPokemonDataToDexAndValidateAchievements(pokemon: PlayerPokemon) {
const speciesForm = !pokemon.fusionSpecies ? pokemon.getSpeciesForm() : pokemon.getFusionSpeciesForm();
if (speciesForm.abilityHidden && (pokemon.fusionSpecies ? pokemon.fusionAbilityIndex : pokemon.abilityIndex) === speciesForm.getAbilityCount() - 1) {
scene.validateAchv(achvs.HIDDEN_ABILITY);
gScene.validateAchv(achvs.HIDDEN_ABILITY);
}
if (pokemon.species.subLegendary) {
scene.validateAchv(achvs.CATCH_SUB_LEGENDARY);
gScene.validateAchv(achvs.CATCH_SUB_LEGENDARY);
}
if (pokemon.species.legendary) {
scene.validateAchv(achvs.CATCH_LEGENDARY);
gScene.validateAchv(achvs.CATCH_LEGENDARY);
}
if (pokemon.species.mythical) {
scene.validateAchv(achvs.CATCH_MYTHICAL);
gScene.validateAchv(achvs.CATCH_MYTHICAL);
}
scene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs);
return scene.gameData.setPokemonCaught(pokemon, true, false, false);
gScene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs);
return gScene.gameData.setPokemonCaught(pokemon, true, false, false);
}
/**
@ -825,12 +823,12 @@ export async function addPokemonDataToDexAndValidateAchievements(scene: BattleSc
* @param scene
* @param invalidSelectionKey
*/
export function isPokemonValidForEncounterOptionSelection(pokemon: Pokemon, scene: BattleScene, invalidSelectionKey: string): string | null {
export function isPokemonValidForEncounterOptionSelection(pokemon: Pokemon, invalidSelectionKey: string): string | null {
if (!pokemon.isAllowed()) {
return i18next.t("partyUiHandler:cantBeUsed", { pokemonName: pokemon.getNameToRender() }) ?? null;
}
if (!pokemon.isAllowedInBattle()) {
return getEncounterText(scene, invalidSelectionKey) ?? null;
return getEncounterText(invalidSelectionKey) ?? null;
}
return null;

View File

@ -1,8 +1,8 @@
import BattleScene from "#app/battle-scene";
import { PlayerPokemon } from "#app/field/pokemon";
import { getFrameMs } from "#app/utils";
import { cos, sin } from "#app/field/anims";
import { getTypeRgb } from "#app/data/type";
import { gScene } from "#app/battle-scene";
export enum TransformationScreenPosition {
CENTER,
@ -17,10 +17,10 @@ export enum TransformationScreenPosition {
* @param transformPokemon
* @param screenPosition
*/
export function doPokemonTransformationSequence(scene: BattleScene, previousPokemon: PlayerPokemon, transformPokemon: PlayerPokemon, screenPosition: TransformationScreenPosition) {
export function doPokemonTransformationSequence(previousPokemon: PlayerPokemon, transformPokemon: PlayerPokemon, screenPosition: TransformationScreenPosition) {
return new Promise<void>(resolve => {
const transformationContainer = scene.fieldUI.getByName("Dream Background") as Phaser.GameObjects.Container;
const transformationBaseBg = scene.add.image(0, 0, "default_bg");
const transformationContainer = gScene.fieldUI.getByName("Dream Background") as Phaser.GameObjects.Container;
const transformationBaseBg = gScene.add.image(0, 0, "default_bg");
transformationBaseBg.setOrigin(0, 0);
transformationBaseBg.setVisible(false);
transformationContainer.add(transformationBaseBg);
@ -36,8 +36,8 @@ export function doPokemonTransformationSequence(scene: BattleScene, previousPoke
const yOffset = screenPosition !== TransformationScreenPosition.CENTER ? -15 : 0;
const getPokemonSprite = () => {
const ret = scene.addPokemonSprite(previousPokemon, transformationBaseBg.displayWidth / 2 + xOffset, transformationBaseBg.displayHeight / 2 + yOffset, "pkmn__sub");
ret.setPipeline(scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true });
const ret = gScene.addPokemonSprite(previousPokemon, transformationBaseBg.displayWidth / 2 + xOffset, transformationBaseBg.displayHeight / 2 + yOffset, "pkmn__sub");
ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true });
return ret;
};
@ -55,7 +55,7 @@ export function doPokemonTransformationSequence(scene: BattleScene, previousPoke
[ pokemonSprite, pokemonTintSprite, pokemonEvoSprite, pokemonEvoTintSprite ].map(sprite => {
sprite.play(previousPokemon.getSpriteKey(true));
sprite.setPipeline(scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(previousPokemon.getTeraType()) });
sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(previousPokemon.getTeraType()) });
sprite.setPipelineData("ignoreTimeTint", true);
sprite.setPipelineData("spriteKey", previousPokemon.getSpriteKey());
sprite.setPipelineData("shiny", previousPokemon.shiny);
@ -82,14 +82,14 @@ export function doPokemonTransformationSequence(scene: BattleScene, previousPoke
});
});
scene.tweens.add({
gScene.tweens.add({
targets: pokemonSprite,
alpha: 1,
ease: "Cubic.easeInOut",
duration: 2000,
onComplete: () => {
doSpiralUpward(scene, transformationBaseBg, transformationContainer, xOffset, yOffset);
scene.tweens.addCounter({
doSpiralUpward(transformationBaseBg, transformationContainer, xOffset, yOffset);
gScene.tweens.addCounter({
from: 0,
to: 1,
duration: 1000,
@ -98,26 +98,26 @@ export function doPokemonTransformationSequence(scene: BattleScene, previousPoke
},
onComplete: () => {
pokemonSprite.setVisible(false);
scene.time.delayedCall(700, () => {
doArcDownward(scene, transformationBaseBg, transformationContainer, xOffset, yOffset);
scene.time.delayedCall(1000, () => {
gScene.time.delayedCall(700, () => {
doArcDownward(transformationBaseBg, transformationContainer, xOffset, yOffset);
gScene.time.delayedCall(1000, () => {
pokemonEvoTintSprite.setScale(0.25);
pokemonEvoTintSprite.setVisible(true);
doCycle(scene, 1.5, 6, pokemonTintSprite, pokemonEvoTintSprite).then(() => {
doCycle(1.5, 6, pokemonTintSprite, pokemonEvoTintSprite).then(() => {
pokemonEvoSprite.setVisible(true);
doCircleInward(scene, transformationBaseBg, transformationContainer, xOffset, yOffset);
doCircleInward(transformationBaseBg, transformationContainer, xOffset, yOffset);
scene.time.delayedCall(900, () => {
scene.tweens.add({
gScene.time.delayedCall(900, () => {
gScene.tweens.add({
targets: pokemonEvoTintSprite,
alpha: 0,
duration: 1500,
delay: 150,
easing: "Sine.easeIn",
onComplete: () => {
scene.time.delayedCall(3000, () => {
gScene.time.delayedCall(3000, () => {
resolve();
scene.tweens.add({
gScene.tweens.add({
targets: pokemonEvoSprite,
alpha: 0,
duration: 2000,
@ -151,17 +151,17 @@ export function doPokemonTransformationSequence(scene: BattleScene, previousPoke
* @param xOffset
* @param yOffset
*/
function doSpiralUpward(scene: BattleScene, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
function doSpiralUpward(transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
let f = 0;
scene.tweens.addCounter({
gScene.tweens.addCounter({
repeat: 64,
duration: getFrameMs(1),
onRepeat: () => {
if (f < 64) {
if (!(f & 7)) {
for (let i = 0; i < 4; i++) {
doSpiralUpwardParticle(scene, (f & 120) * 2 + i * 64, transformationBaseBg, transformationContainer, xOffset, yOffset);
doSpiralUpwardParticle((f & 120) * 2 + i * 64, transformationBaseBg, transformationContainer, xOffset, yOffset);
}
}
f++;
@ -178,17 +178,17 @@ function doSpiralUpward(scene: BattleScene, transformationBaseBg: Phaser.GameObj
* @param xOffset
* @param yOffset
*/
function doArcDownward(scene: BattleScene, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
function doArcDownward(transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
let f = 0;
scene.tweens.addCounter({
gScene.tweens.addCounter({
repeat: 96,
duration: getFrameMs(1),
onRepeat: () => {
if (f < 96) {
if (f < 6) {
for (let i = 0; i < 9; i++) {
doArcDownParticle(scene, i * 16, transformationBaseBg, transformationContainer, xOffset, yOffset);
doArcDownParticle(i * 16, transformationBaseBg, transformationContainer, xOffset, yOffset);
}
}
f++;
@ -205,17 +205,17 @@ function doArcDownward(scene: BattleScene, transformationBaseBg: Phaser.GameObje
* @param pokemonTintSprite
* @param pokemonEvoTintSprite
*/
function doCycle(scene: BattleScene, l: number, lastCycle: number, pokemonTintSprite: Phaser.GameObjects.Sprite, pokemonEvoTintSprite: Phaser.GameObjects.Sprite): Promise<boolean> {
function doCycle(l: number, lastCycle: number, pokemonTintSprite: Phaser.GameObjects.Sprite, pokemonEvoTintSprite: Phaser.GameObjects.Sprite): Promise<boolean> {
return new Promise(resolve => {
const isLastCycle = l === lastCycle;
scene.tweens.add({
gScene.tweens.add({
targets: pokemonTintSprite,
scale: 0.25,
ease: "Cubic.easeInOut",
duration: 500 / l,
yoyo: !isLastCycle
});
scene.tweens.add({
gScene.tweens.add({
targets: pokemonEvoTintSprite,
scale: 1,
ease: "Cubic.easeInOut",
@ -223,7 +223,7 @@ function doCycle(scene: BattleScene, l: number, lastCycle: number, pokemonTintSp
yoyo: !isLastCycle,
onComplete: () => {
if (l < lastCycle) {
doCycle(scene, l + 0.5, lastCycle, pokemonTintSprite, pokemonEvoTintSprite).then(success => resolve(success));
doCycle(l + 0.5, lastCycle, pokemonTintSprite, pokemonEvoTintSprite).then(success => resolve(success));
} else {
pokemonTintSprite.setVisible(false);
resolve(true);
@ -241,20 +241,20 @@ function doCycle(scene: BattleScene, l: number, lastCycle: number, pokemonTintSp
* @param xOffset
* @param yOffset
*/
function doCircleInward(scene: BattleScene, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
function doCircleInward(transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
let f = 0;
scene.tweens.addCounter({
gScene.tweens.addCounter({
repeat: 48,
duration: getFrameMs(1),
onRepeat: () => {
if (!f) {
for (let i = 0; i < 16; i++) {
doCircleInwardParticle(scene, i * 16, 4, transformationBaseBg, transformationContainer, xOffset, yOffset);
doCircleInwardParticle(i * 16, 4, transformationBaseBg, transformationContainer, xOffset, yOffset);
}
} else if (f === 32) {
for (let i = 0; i < 16; i++) {
doCircleInwardParticle(scene, i * 16, 8, transformationBaseBg, transformationContainer, xOffset, yOffset);
doCircleInwardParticle(i * 16, 8, transformationBaseBg, transformationContainer, xOffset, yOffset);
}
}
f++;
@ -271,15 +271,15 @@ function doCircleInward(scene: BattleScene, transformationBaseBg: Phaser.GameObj
* @param xOffset
* @param yOffset
*/
function doSpiralUpwardParticle(scene: BattleScene, trigIndex: number, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
function doSpiralUpwardParticle(trigIndex: number, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
const initialX = transformationBaseBg.displayWidth / 2 + xOffset;
const particle = scene.add.image(initialX, 0, "evo_sparkle");
const particle = gScene.add.image(initialX, 0, "evo_sparkle");
transformationContainer.add(particle);
let f = 0;
let amp = 48;
const particleTimer = scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: getFrameMs(1),
onRepeat: () => {
@ -316,16 +316,16 @@ function doSpiralUpwardParticle(scene: BattleScene, trigIndex: number, transform
* @param xOffset
* @param yOffset
*/
function doArcDownParticle(scene: BattleScene, trigIndex: number, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
function doArcDownParticle(trigIndex: number, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
const initialX = transformationBaseBg.displayWidth / 2 + xOffset;
const particle = scene.add.image(initialX, 0, "evo_sparkle");
const particle = gScene.add.image(initialX, 0, "evo_sparkle");
particle.setScale(0.5);
transformationContainer.add(particle);
let f = 0;
let amp = 8;
const particleTimer = scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: getFrameMs(1),
onRepeat: () => {
@ -359,15 +359,15 @@ function doArcDownParticle(scene: BattleScene, trigIndex: number, transformation
* @param xOffset
* @param yOffset
*/
function doCircleInwardParticle(scene: BattleScene, trigIndex: number, speed: number, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
function doCircleInwardParticle(trigIndex: number, speed: number, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) {
const initialX = transformationBaseBg.displayWidth / 2 + xOffset;
const initialY = transformationBaseBg.displayHeight / 2 + yOffset;
const particle = scene.add.image(initialX, initialY, "evo_sparkle");
const particle = gScene.add.image(initialX, initialY, "evo_sparkle");
transformationContainer.add(particle);
let amp = 120;
const particleTimer = scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: getFrameMs(1),
onRepeat: () => {

View File

@ -1,5 +1,5 @@
import { gScene } from "#app/battle-scene";
import { PokeballType } from "#enums/pokeball";
import BattleScene from "../battle-scene";
import i18next from "i18next";
export { PokeballType };
@ -82,20 +82,20 @@ export function getPokeballTintColor(type: PokeballType): number {
}
}
export function doPokeballBounceAnim(scene: BattleScene, pokeball: Phaser.GameObjects.Sprite, y1: number, y2: number, baseBounceDuration: integer, callback: Function) {
export function doPokeballBounceAnim(pokeball: Phaser.GameObjects.Sprite, y1: number, y2: number, baseBounceDuration: integer, callback: Function) {
let bouncePower = 1;
let bounceYOffset = y1;
let bounceY = y2;
const yd = y2 - y1;
const doBounce = () => {
scene.tweens.add({
gScene.tweens.add({
targets: pokeball,
y: y2,
duration: bouncePower * baseBounceDuration,
ease: "Cubic.easeIn",
onComplete: () => {
scene.playSound("se/pb_bounce_1", { volume: bouncePower });
gScene.playSound("se/pb_bounce_1", { volume: bouncePower });
bouncePower = bouncePower > 0.01 ? bouncePower * 0.5 : 0;
@ -103,7 +103,7 @@ export function doPokeballBounceAnim(scene: BattleScene, pokeball: Phaser.GameOb
bounceYOffset = yd * bouncePower;
bounceY = y2 - bounceYOffset;
scene.tweens.add({
gScene.tweens.add({
targets: pokeball,
y: bounceY,
duration: bouncePower * baseBounceDuration,

View File

@ -13,6 +13,7 @@ import i18next from "i18next";
import { WeatherType } from "./weather";
import { Challenges } from "#app/enums/challenges";
import { SpeciesFormKey } from "#enums/species-form-key";
import { gScene } from "#app/battle-scene";
export enum FormChangeItem {
NONE,
@ -259,7 +260,7 @@ export class SpeciesFormChangeItemTrigger extends SpeciesFormChangeTrigger {
}
canChange(pokemon: Pokemon): boolean {
return !!pokemon.scene.findModifier(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === pokemon.id && m.formChangeItem === this.item && m.active === this.active);
return !!gScene.findModifier(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === pokemon.id && m.formChangeItem === this.item && m.active === this.active);
}
}
@ -272,7 +273,7 @@ export class SpeciesFormChangeTimeOfDayTrigger extends SpeciesFormChangeTrigger
}
canChange(pokemon: Pokemon): boolean {
return this.timesOfDay.indexOf(pokemon.scene.arena.getTimeOfDay()) > -1;
return this.timesOfDay.indexOf(gScene.arena.getTimeOfDay()) > -1;
}
}
@ -335,7 +336,7 @@ export abstract class SpeciesFormChangeMoveTrigger extends SpeciesFormChangeTrig
export class SpeciesFormChangePreMoveTrigger extends SpeciesFormChangeMoveTrigger {
canChange(pokemon: Pokemon): boolean {
const command = pokemon.scene.currentBattle.turnCommands[pokemon.getBattlerIndex()];
const command = gScene.currentBattle.turnCommands[pokemon.getBattlerIndex()];
return !!command?.move && this.movePredicate(command.move.move) === this.used;
}
}
@ -348,7 +349,7 @@ export class SpeciesFormChangePostMoveTrigger extends SpeciesFormChangeMoveTrigg
export class MeloettaFormChangePostMoveTrigger extends SpeciesFormChangePostMoveTrigger {
override canChange(pokemon: Pokemon): boolean {
if (pokemon.scene.gameMode.hasChallenge(Challenges.SINGLE_TYPE)) {
if (gScene.gameMode.hasChallenge(Challenges.SINGLE_TYPE)) {
return false;
} else {
return super.canChange(pokemon);
@ -365,7 +366,7 @@ export class SpeciesDefaultFormMatchTrigger extends SpeciesFormChangeTrigger {
}
canChange(pokemon: Pokemon): boolean {
return this.formKey === pokemon.species.forms[pokemon.scene.getSpeciesFormIndex(pokemon.species, pokemon.gender, pokemon.getNature(), true)].formKey;
return this.formKey === pokemon.species.forms[gScene.getSpeciesFormIndex(pokemon.species, pokemon.gender, pokemon.getNature(), true)].formKey;
}
}
@ -389,7 +390,7 @@ export class SpeciesFormChangeTeraTrigger extends SpeciesFormChangeTrigger {
* @returns `true` if the Pokémon can change forms, `false` otherwise
*/
canChange(pokemon: Pokemon): boolean {
return !!pokemon.scene.findModifier(m => m instanceof TerastallizeModifier && m.pokemonId === pokemon.id && m.teraType === this.teraType);
return !!gScene.findModifier(m => m instanceof TerastallizeModifier && m.pokemonId === pokemon.id && m.teraType === this.teraType);
}
}
@ -400,7 +401,7 @@ export class SpeciesFormChangeTeraTrigger extends SpeciesFormChangeTrigger {
*/
export class SpeciesFormChangeLapseTeraTrigger extends SpeciesFormChangeTrigger {
canChange(pokemon: Pokemon): boolean {
return !!pokemon.scene.findModifier(m => m instanceof TerastallizeModifier && m.pokemonId === pokemon.id);
return !!gScene.findModifier(m => m instanceof TerastallizeModifier && m.pokemonId === pokemon.id);
}
}
@ -428,8 +429,8 @@ export class SpeciesFormChangeWeatherTrigger extends SpeciesFormChangeTrigger {
* @returns `true` if the Pokemon can change forms, `false` otherwise
*/
canChange(pokemon: Pokemon): boolean {
const currentWeather = pokemon.scene.arena.weather?.weatherType ?? WeatherType.NONE;
const isWeatherSuppressed = pokemon.scene.arena.weather?.isEffectSuppressed(pokemon.scene);
const currentWeather = gScene.arena.weather?.weatherType ?? WeatherType.NONE;
const isWeatherSuppressed = gScene.arena.weather?.isEffectSuppressed();
const isAbilitySuppressed = pokemon.summonData.abilitySuppressed;
return !isAbilitySuppressed && !isWeatherSuppressed && (pokemon.hasAbility(this.ability) && this.weathers.includes(currentWeather));
@ -462,8 +463,8 @@ export class SpeciesFormChangeRevertWeatherFormTrigger extends SpeciesFormChange
*/
canChange(pokemon: Pokemon): boolean {
if (pokemon.hasAbility(this.ability, false, true)) {
const currentWeather = pokemon.scene.arena.weather?.weatherType ?? WeatherType.NONE;
const isWeatherSuppressed = pokemon.scene.arena.weather?.isEffectSuppressed(pokemon.scene);
const currentWeather = gScene.arena.weather?.weatherType ?? WeatherType.NONE;
const isWeatherSuppressed = gScene.arena.weather?.isEffectSuppressed();
const isAbilitySuppressed = pokemon.summonData.abilitySuppressed;
const summonDataAbility = pokemon.summonData.ability;
const isAbilityChanged = summonDataAbility !== this.ability && summonDataAbility !== Abilities.NONE;
@ -506,7 +507,7 @@ export function getSpeciesFormChangeMessage(pokemon: Pokemon, formChange: Specie
* @returns A {@linkcode SpeciesFormChangeCondition} checking if that species is registered as caught
*/
function getSpeciesDependentFormChangeCondition(species: Species): SpeciesFormChangeCondition {
return new SpeciesFormChangeCondition(p => !!p.scene.gameData.dexData[species].caughtAttr);
return new SpeciesFormChangeCondition(p => !!gScene.gameData.dexData[species].caughtAttr);
}
interface PokemonFormChanges {

View File

@ -4,7 +4,7 @@ import { PartyMemberStrength } from "#enums/party-member-strength";
import { Species } from "#enums/species";
import { QuantizerCelebi, argbFromRgba, rgbaFromArgb } from "@material/material-color-utilities";
import i18next from "i18next";
import BattleScene, { AnySound } from "#app/battle-scene";
import { AnySound, gScene } from "#app/battle-scene";
import { GameMode } from "#app/game-mode";
import { StarterMoveset } from "#app/system/game-data";
import * as Utils from "#app/utils";
@ -467,29 +467,29 @@ export abstract class PokemonSpeciesForm {
return true;
}
loadAssets(scene: BattleScene, female: boolean, formIndex?: integer, shiny?: boolean, variant?: Variant, startLoad?: boolean): Promise<void> {
loadAssets(female: boolean, formIndex?: integer, shiny?: boolean, variant?: Variant, startLoad?: boolean): Promise<void> {
return new Promise(resolve => {
const spriteKey = this.getSpriteKey(female, formIndex, shiny, variant);
scene.loadPokemonAtlas(spriteKey, this.getSpriteAtlasPath(female, formIndex, shiny, variant));
scene.load.audio(`cry/${this.getCryKey(formIndex)}`, `audio/cry/${this.getCryKey(formIndex)}.m4a`);
scene.load.once(Phaser.Loader.Events.COMPLETE, () => {
gScene.loadPokemonAtlas(spriteKey, this.getSpriteAtlasPath(female, formIndex, shiny, variant));
gScene.load.audio(`cry/${this.getCryKey(formIndex)}`, `audio/cry/${this.getCryKey(formIndex)}.m4a`);
gScene.load.once(Phaser.Loader.Events.COMPLETE, () => {
const originalWarn = console.warn;
// Ignore warnings for missing frames, because there will be a lot
console.warn = () => {};
const frameNames = scene.anims.generateFrameNames(spriteKey, { zeroPad: 4, suffix: ".png", start: 1, end: 400 });
const frameNames = gScene.anims.generateFrameNames(spriteKey, { zeroPad: 4, suffix: ".png", start: 1, end: 400 });
console.warn = originalWarn;
if (!(scene.anims.exists(spriteKey))) {
scene.anims.create({
if (!(gScene.anims.exists(spriteKey))) {
gScene.anims.create({
key: this.getSpriteKey(female, formIndex, shiny, variant),
frames: frameNames,
frameRate: 12,
repeat: -1
});
} else {
scene.anims.get(spriteKey).frameRate = 12;
gScene.anims.get(spriteKey).frameRate = 12;
}
let spritePath = this.getSpriteAtlasPath(female, formIndex, shiny, variant).replace("variant/", "").replace(/_[1-3]$/, "");
const useExpSprite = scene.experimentalSprites && scene.hasExpSprite(spriteKey);
const useExpSprite = gScene.experimentalSprites && gScene.hasExpSprite(spriteKey);
if (useExpSprite) {
spritePath = `exp/${spritePath}`;
}
@ -502,7 +502,7 @@ export abstract class PokemonSpeciesForm {
if (variantColorCache.hasOwnProperty(key)) {
return resolve();
}
scene.cachedFetch(`./images/pokemon/variant/${spritePath}.json`).then(res => res.json()).then(c => {
gScene.cachedFetch(`./images/pokemon/variant/${spritePath}.json`).then(res => res.json()).then(c => {
variantColorCache[key] = c;
resolve();
});
@ -514,8 +514,8 @@ export abstract class PokemonSpeciesForm {
resolve();
});
if (startLoad) {
if (!scene.load.isLoading()) {
scene.load.start();
if (!gScene.load.isLoading()) {
gScene.load.start();
}
} else {
resolve();
@ -523,21 +523,21 @@ export abstract class PokemonSpeciesForm {
});
}
cry(scene: BattleScene, soundConfig?: Phaser.Types.Sound.SoundConfig, ignorePlay?: boolean): AnySound {
cry(soundConfig?: Phaser.Types.Sound.SoundConfig, ignorePlay?: boolean): AnySound {
const cryKey = this.getCryKey(this.formIndex);
let cry: AnySound | null = scene.sound.get(cryKey) as AnySound;
let cry: AnySound | null = gScene.sound.get(cryKey) as AnySound;
if (cry?.pendingRemove) {
cry = null;
}
cry = scene.playSound(`cry/${(cry ?? cryKey)}`, soundConfig);
cry = gScene.playSound(`cry/${(cry ?? cryKey)}`, soundConfig);
if (ignorePlay) {
cry.stop();
}
return cry;
}
generateCandyColors(scene: BattleScene): integer[][] {
const sourceTexture = scene.textures.get(this.getSpriteKey(false));
generateCandyColors(): integer[][] {
const sourceTexture = gScene.textures.get(this.getSpriteKey(false));
const sourceFrame = sourceTexture.frames[sourceTexture.firstFrame];
const sourceImage = sourceTexture.getSourceImage() as HTMLImageElement;
@ -580,7 +580,7 @@ export abstract class PokemonSpeciesForm {
const originalRandom = Math.random;
Math.random = () => Phaser.Math.RND.realInRange(0, 1);
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
paletteColors = QuantizerCelebi.quantize(pixelColors, 2);
}, 0, "This result should not vary");
@ -951,11 +951,11 @@ export const noStarterFormKeys: string[] = [
* @param scene {@linkcode BattleScene} used as part of RNG
* @returns A list of starters with Pokerus
*/
export function getPokerusStarters(scene: BattleScene): PokemonSpecies[] {
export function getPokerusStarters(): PokemonSpecies[] {
const pokerusStarters: PokemonSpecies[] = [];
const date = new Date();
date.setUTCHours(0, 0, 0, 0);
scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
while (pokerusStarters.length < POKERUS_STARTER_COUNT) {
const randomSpeciesId = parseInt(Utils.randSeedItem(Object.keys(speciesStarterCosts)), 10);
const species = getPokemonSpecies(randomSpeciesId);

View File

@ -1,4 +1,4 @@
import BattleScene, { startingWave } from "#app/battle-scene";
import { gScene, startingWave } from "#app/battle-scene";
import { ModifierTypeFunc, modifierTypes } from "#app/modifier/modifier-type";
import { EnemyPokemon, PokemonMove } from "#app/field/pokemon";
import * as Utils from "#app/utils";
@ -169,8 +169,8 @@ export const trainerPartyTemplates = {
RIVAL_6: new TrainerPartyCompoundTemplate(new TrainerPartyTemplate(1, PartyMemberStrength.STRONG), new TrainerPartyTemplate(1, PartyMemberStrength.AVERAGE), new TrainerPartyTemplate(3, PartyMemberStrength.AVERAGE, false, true), new TrainerPartyTemplate(1, PartyMemberStrength.STRONGER))
};
type PartyTemplateFunc = (scene: BattleScene) => TrainerPartyTemplate;
type PartyMemberFunc = (scene: BattleScene, level: integer, strength: PartyMemberStrength) => EnemyPokemon;
type PartyTemplateFunc = () => TrainerPartyTemplate;
type PartyMemberFunc = (level: integer, strength: PartyMemberStrength) => EnemyPokemon;
type GenModifiersFunc = (party: EnemyPokemon[]) => PersistentModifier[];
export interface PartyMemberFuncs {
@ -842,7 +842,7 @@ export class TrainerConfig {
this.setBattleBgm("battle_unova_gym");
this.setVictoryBgm("victory_gym");
this.setGenModifiersFunc(party => {
const waveIndex = party[0].scene.currentBattle.waveIndex;
const waveIndex = gScene.currentBattle.waveIndex;
return getRandomTeraModifiers(party, waveIndex >= 100 ? 1 : 0, specialtyTypes.length ? specialtyTypes : undefined);
});
@ -1011,28 +1011,28 @@ export class TrainerConfig {
return ret;
}
loadAssets(scene: BattleScene, variant: TrainerVariant): Promise<void> {
loadAssets(variant: TrainerVariant): Promise<void> {
return new Promise(resolve => {
const isDouble = variant === TrainerVariant.DOUBLE;
const trainerKey = this.getSpriteKey(variant === TrainerVariant.FEMALE, false);
const partnerTrainerKey = this.getSpriteKey(true, true);
scene.loadAtlas(trainerKey, "trainer");
gScene.loadAtlas(trainerKey, "trainer");
if (isDouble) {
scene.loadAtlas(partnerTrainerKey, "trainer");
gScene.loadAtlas(partnerTrainerKey, "trainer");
}
scene.load.once(Phaser.Loader.Events.COMPLETE, () => {
gScene.load.once(Phaser.Loader.Events.COMPLETE, () => {
const originalWarn = console.warn;
// Ignore warnings for missing frames, because there will be a lot
console.warn = () => {
};
const frameNames = scene.anims.generateFrameNames(trainerKey, {
const frameNames = gScene.anims.generateFrameNames(trainerKey, {
zeroPad: 4,
suffix: ".png",
start: 1,
end: 128
});
const partnerFrameNames = isDouble
? scene.anims.generateFrameNames(partnerTrainerKey, {
? gScene.anims.generateFrameNames(partnerTrainerKey, {
zeroPad: 4,
suffix: ".png",
start: 1,
@ -1040,16 +1040,16 @@ export class TrainerConfig {
})
: "";
console.warn = originalWarn;
if (!(scene.anims.exists(trainerKey))) {
scene.anims.create({
if (!(gScene.anims.exists(trainerKey))) {
gScene.anims.create({
key: trainerKey,
frames: frameNames,
frameRate: 24,
repeat: -1
});
}
if (isDouble && !(scene.anims.exists(partnerTrainerKey))) {
scene.anims.create({
if (isDouble && !(gScene.anims.exists(partnerTrainerKey))) {
gScene.anims.create({
key: partnerTrainerKey,
frames: partnerFrameNames,
frameRate: 24,
@ -1058,8 +1058,8 @@ export class TrainerConfig {
}
resolve();
});
if (!scene.load.isLoading()) {
scene.load.start();
if (!gScene.load.isLoading()) {
gScene.load.start();
}
});
}
@ -1136,8 +1136,8 @@ interface TrainerConfigs {
* @param scene the singleton scene being passed in
* @returns the correct TrainerPartyTemplate
*/
function getEvilGruntPartyTemplate(scene: BattleScene): TrainerPartyTemplate {
const waveIndex = scene.currentBattle?.waveIndex;
function getEvilGruntPartyTemplate(): TrainerPartyTemplate {
const waveIndex = gScene.currentBattle?.waveIndex;
if (waveIndex < 40) {
return trainerPartyTemplates.TWO_AVG;
} else if (waveIndex < 63) {
@ -1151,37 +1151,37 @@ function getEvilGruntPartyTemplate(scene: BattleScene): TrainerPartyTemplate {
}
}
function getWavePartyTemplate(scene: BattleScene, ...templates: TrainerPartyTemplate[]) {
return templates[Math.min(Math.max(Math.ceil((scene.gameMode.getWaveForDifficulty(scene.currentBattle?.waveIndex || startingWave, true) - 20) / 30), 0), templates.length - 1)];
function getWavePartyTemplate(...templates: TrainerPartyTemplate[]) {
return templates[Math.min(Math.max(Math.ceil((gScene.gameMode.getWaveForDifficulty(gScene.currentBattle?.waveIndex || startingWave, true) - 20) / 30), 0), templates.length - 1)];
}
function getGymLeaderPartyTemplate(scene: BattleScene) {
return getWavePartyTemplate(scene, trainerPartyTemplates.GYM_LEADER_1, trainerPartyTemplates.GYM_LEADER_2, trainerPartyTemplates.GYM_LEADER_3, trainerPartyTemplates.GYM_LEADER_4, trainerPartyTemplates.GYM_LEADER_5);
function getGymLeaderPartyTemplate() {
return getWavePartyTemplate(trainerPartyTemplates.GYM_LEADER_1, trainerPartyTemplates.GYM_LEADER_2, trainerPartyTemplates.GYM_LEADER_3, trainerPartyTemplates.GYM_LEADER_4, trainerPartyTemplates.GYM_LEADER_5);
}
/**
* Randomly selects one of the `Species` from `speciesPool`, determines its evolution, level, and strength.
* Then adds Pokemon to scene.
* Then adds Pokemon to gScene.
* @param speciesPool
* @param trainerSlot
* @param ignoreEvolution
* @param postProcess
*/
export function getRandomPartyMemberFunc(speciesPool: Species[], trainerSlot: TrainerSlot = TrainerSlot.TRAINER, ignoreEvolution: boolean = false, postProcess?: (enemyPokemon: EnemyPokemon) => void) {
return (scene: BattleScene, level: number, strength: PartyMemberStrength) => {
return (level: number, strength: PartyMemberStrength) => {
let species = Utils.randSeedItem(speciesPool);
if (!ignoreEvolution) {
species = getPokemonSpecies(species).getTrainerSpeciesForLevel(level, true, strength, scene.currentBattle.waveIndex);
species = getPokemonSpecies(species).getTrainerSpeciesForLevel(level, true, strength, gScene.currentBattle.waveIndex);
}
return scene.addEnemyPokemon(getPokemonSpecies(species), level, trainerSlot, undefined, undefined, postProcess);
return gScene.addEnemyPokemon(getPokemonSpecies(species), level, trainerSlot, undefined, undefined, postProcess);
};
}
function getSpeciesFilterRandomPartyMemberFunc(speciesFilter: PokemonSpeciesFilter, trainerSlot: TrainerSlot = TrainerSlot.TRAINER, allowLegendaries?: boolean, postProcess?: (EnemyPokemon: EnemyPokemon) => void): PartyMemberFunc {
const originalSpeciesFilter = speciesFilter;
speciesFilter = (species: PokemonSpecies) => (allowLegendaries || (!species.legendary && !species.subLegendary && !species.mythical)) && !species.isTrainerForbidden() && originalSpeciesFilter(species);
return (scene: BattleScene, level: integer, strength: PartyMemberStrength) => {
const ret = scene.addEnemyPokemon(getPokemonSpecies(scene.randomSpecies(scene.currentBattle.waveIndex, level, false, speciesFilter).getTrainerSpeciesForLevel(level, true, strength, scene.currentBattle.waveIndex)), level, trainerSlot, undefined, undefined, postProcess);
return (level: integer, strength: PartyMemberStrength) => {
const ret = gScene.addEnemyPokemon(getPokemonSpecies(gScene.randomSpecies(gScene.currentBattle.waveIndex, level, false, speciesFilter).getTrainerSpeciesForLevel(level, true, strength, gScene.currentBattle.waveIndex)), level, trainerSlot, undefined, undefined, postProcess);
return ret;
};
}
@ -1341,7 +1341,7 @@ export const signatureSpecies: SignatureSpecies = {
export const trainerConfigs: TrainerConfigs = {
[TrainerType.UNKNOWN]: new TrainerConfig(0).setHasGenders(),
[TrainerType.ACE_TRAINER]: new TrainerConfig(++t).setHasGenders("Ace Trainer Female").setHasDouble("Ace Duo").setMoneyMultiplier(2.25).setEncounterBgm(TrainerType.ACE_TRAINER)
.setPartyTemplateFunc(scene => getWavePartyTemplate(scene, trainerPartyTemplates.THREE_WEAK_BALANCED, trainerPartyTemplates.FOUR_WEAK_BALANCED, trainerPartyTemplates.FIVE_WEAK_BALANCED, trainerPartyTemplates.SIX_WEAK_BALANCED)),
.setPartyTemplateFunc(() => getWavePartyTemplate(trainerPartyTemplates.THREE_WEAK_BALANCED, trainerPartyTemplates.FOUR_WEAK_BALANCED, trainerPartyTemplates.FIVE_WEAK_BALANCED, trainerPartyTemplates.SIX_WEAK_BALANCED)),
[TrainerType.ARTIST]: new TrainerConfig(++t).setEncounterBgm(TrainerType.RICH).setPartyTemplates(trainerPartyTemplates.ONE_STRONG, trainerPartyTemplates.TWO_AVG, trainerPartyTemplates.THREE_AVG)
.setSpeciesPools([ Species.SMEARGLE ]),
[TrainerType.BACKERS]: new TrainerConfig(++t).setHasGenders("Backers").setDoubleOnly().setEncounterBgm(TrainerType.CYCLIST),
@ -1366,7 +1366,7 @@ export const trainerConfigs: TrainerConfigs = {
[TrainerPoolTier.ULTRA_RARE]: [ Species.KUBFU ]
}),
[TrainerType.BREEDER]: new TrainerConfig(++t).setMoneyMultiplier(1.325).setEncounterBgm(TrainerType.POKEFAN).setHasGenders("Breeder Female").setHasDouble("Breeders")
.setPartyTemplateFunc(scene => getWavePartyTemplate(scene, trainerPartyTemplates.FOUR_WEAKER, trainerPartyTemplates.FIVE_WEAKER, trainerPartyTemplates.SIX_WEAKER))
.setPartyTemplateFunc(() => getWavePartyTemplate(trainerPartyTemplates.FOUR_WEAKER, trainerPartyTemplates.FIVE_WEAKER, trainerPartyTemplates.SIX_WEAKER))
.setSpeciesFilter(s => s.baseTotal < 450),
[TrainerType.CLERK]: new TrainerConfig(++t).setHasGenders("Clerk Female").setHasDouble("Colleagues").setEncounterBgm(TrainerType.CLERK)
.setPartyTemplates(trainerPartyTemplates.TWO_WEAK, trainerPartyTemplates.THREE_WEAK, trainerPartyTemplates.ONE_AVG, trainerPartyTemplates.TWO_AVG, trainerPartyTemplates.TWO_WEAK_ONE_AVG)
@ -1485,7 +1485,7 @@ export const trainerConfigs: TrainerConfigs = {
}),
[TrainerType.SWIMMER]: new TrainerConfig(++t).setMoneyMultiplier(1.3).setEncounterBgm(TrainerType.PARASOL_LADY).setHasGenders("Swimmer Female").setHasDouble("Swimmers").setSpecialtyTypes(Type.WATER).setSpeciesFilter(s => s.isOfType(Type.WATER)),
[TrainerType.TWINS]: new TrainerConfig(++t).setDoubleOnly().setMoneyMultiplier(0.65).setUseSameSeedForAllMembers()
.setPartyTemplateFunc(scene => getWavePartyTemplate(scene, trainerPartyTemplates.TWO_WEAK, trainerPartyTemplates.TWO_AVG, trainerPartyTemplates.TWO_STRONG))
.setPartyTemplateFunc(() => getWavePartyTemplate(trainerPartyTemplates.TWO_WEAK, trainerPartyTemplates.TWO_AVG, trainerPartyTemplates.TWO_STRONG))
.setPartyMemberFunc(0, getRandomPartyMemberFunc([ Species.PLUSLE, Species.VOLBEAT, Species.PACHIRISU, Species.SILCOON, Species.METAPOD, Species.IGGLYBUFF, Species.PETILIL, Species.EEVEE ]))
.setPartyMemberFunc(1, getRandomPartyMemberFunc([ Species.MINUN, Species.ILLUMISE, Species.EMOLGA, Species.CASCOON, Species.KAKUNA, Species.CLEFFA, Species.COTTONEE, Species.EEVEE ], TrainerSlot.TRAINER_PARTNER))
.setEncounterBgm(TrainerType.TWINS),
@ -1501,115 +1501,115 @@ export const trainerConfigs: TrainerConfigs = {
.setSpeciesPools(
[ Species.CATERPIE, Species.WEEDLE, Species.RATTATA, Species.SENTRET, Species.POOCHYENA, Species.ZIGZAGOON, Species.WURMPLE, Species.BIDOOF, Species.PATRAT, Species.LILLIPUP ]
),
[TrainerType.ROCKET_GRUNT]: new TrainerConfig(++t).setHasGenders("Rocket Grunt Female").setHasDouble("Rocket Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.ROCKET_GRUNT]: new TrainerConfig(++t).setHasGenders("Rocket Grunt Female").setHasDouble("Rocket Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.WEEDLE, Species.RATTATA, Species.EKANS, Species.SANDSHREW, Species.ZUBAT, Species.GEODUDE, Species.KOFFING, Species.GRIMER, Species.ODDISH, Species.SLOWPOKE ],
[TrainerPoolTier.UNCOMMON]: [ Species.GYARADOS, Species.LICKITUNG, Species.TAUROS, Species.MANKEY, Species.SCYTHER, Species.ELEKID, Species.MAGBY, Species.CUBONE, Species.GROWLITHE, Species.MURKROW, Species.GASTLY, Species.EXEGGCUTE, Species.VOLTORB, Species.MAGNEMITE ],
[TrainerPoolTier.RARE]: [ Species.PORYGON, Species.ALOLA_RATTATA, Species.ALOLA_SANDSHREW, Species.ALOLA_MEOWTH, Species.ALOLA_GRIMER, Species.ALOLA_GEODUDE, Species.PALDEA_TAUROS, Species.OMANYTE, Species.KABUTO ],
[TrainerPoolTier.SUPER_RARE]: [ Species.DRATINI, Species.LARVITAR ]
}),
[TrainerType.ARCHER]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("rocket_admin", "rocket", [ Species.HOUNDOOM ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.ARIANA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("rocket_admin_female", "rocket", [ Species.ARBOK ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.PROTON]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("rocket_admin", "rocket", [ Species.CROBAT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.PETREL]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("rocket_admin", "rocket", [ Species.WEEZING ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.MAGMA_GRUNT]: new TrainerConfig(++t).setHasGenders("Magma Grunt Female").setHasDouble("Magma Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.ARCHER]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("rocket_admin", "rocket", [ Species.HOUNDOOM ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.ARIANA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("rocket_admin_female", "rocket", [ Species.ARBOK ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.PROTON]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("rocket_admin", "rocket", [ Species.CROBAT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.PETREL]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("rocket_admin", "rocket", [ Species.WEEZING ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_rocket_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.MAGMA_GRUNT]: new TrainerConfig(++t).setHasGenders("Magma Grunt Female").setHasDouble("Magma Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.SLUGMA, Species.POOCHYENA, Species.NUMEL, Species.ZIGZAGOON, Species.DIGLETT, Species.MAGBY, Species.TORKOAL, Species.GROWLITHE, Species.BALTOY ],
[TrainerPoolTier.UNCOMMON]: [ Species.SOLROCK, Species.HIPPOPOTAS, Species.SANDACONDA, Species.PHANPY, Species.ROLYCOLY, Species.GLIGAR, Species.RHYHORN, Species.HEATMOR ],
[TrainerPoolTier.RARE]: [ Species.TRAPINCH, Species.LILEEP, Species.ANORITH, Species.HISUI_GROWLITHE, Species.TURTONATOR, Species.ARON, Species.TOEDSCOOL ],
[TrainerPoolTier.SUPER_RARE]: [ Species.CAPSAKID, Species.CHARCADET ]
}),
[TrainerType.TABITHA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("magma_admin", "magma", [ Species.CAMERUPT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.COURTNEY]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("magma_admin_female", "magma", [ Species.CAMERUPT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.AQUA_GRUNT]: new TrainerConfig(++t).setHasGenders("Aqua Grunt Female").setHasDouble("Aqua Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.TABITHA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("magma_admin", "magma", [ Species.CAMERUPT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.COURTNEY]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("magma_admin_female", "magma", [ Species.CAMERUPT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.AQUA_GRUNT]: new TrainerConfig(++t).setHasGenders("Aqua Grunt Female").setHasDouble("Aqua Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.CARVANHA, Species.WAILMER, Species.ZIGZAGOON, Species.LOTAD, Species.CORPHISH, Species.SPHEAL, Species.REMORAID, Species.QWILFISH, Species.BARBOACH ],
[TrainerPoolTier.UNCOMMON]: [ Species.CLAMPERL, Species.CHINCHOU, Species.WOOPER, Species.WINGULL, Species.TENTACOOL, Species.AZURILL, Species.CLOBBOPUS, Species.HORSEA ],
[TrainerPoolTier.RARE]: [ Species.MANTYKE, Species.DHELMISE, Species.HISUI_QWILFISH, Species.ARROKUDA, Species.PALDEA_WOOPER, Species.SKRELP ],
[TrainerPoolTier.SUPER_RARE]: [ Species.DONDOZO, Species.BASCULEGION ]
}),
[TrainerType.MATT]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("aqua_admin", "aqua", [ Species.SHARPEDO ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.SHELLY]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("aqua_admin_female", "aqua", [ Species.SHARPEDO ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.GALACTIC_GRUNT]: new TrainerConfig(++t).setHasGenders("Galactic Grunt Female").setHasDouble("Galactic Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_galactic_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.MATT]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("aqua_admin", "aqua", [ Species.SHARPEDO ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.SHELLY]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("aqua_admin_female", "aqua", [ Species.SHARPEDO ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aqua_magma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.GALACTIC_GRUNT]: new TrainerConfig(++t).setHasGenders("Galactic Grunt Female").setHasDouble("Galactic Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_galactic_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.GLAMEOW, Species.STUNKY, Species.CROAGUNK, Species.SHINX, Species.WURMPLE, Species.BRONZOR, Species.DRIFLOON, Species.BURMY, Species.CARNIVINE ],
[TrainerPoolTier.UNCOMMON]: [ Species.LICKITUNG, Species.RHYHORN, Species.TANGELA, Species.ZUBAT, Species.YANMA, Species.SKORUPI, Species.GLIGAR, Species.SWINUB ],
[TrainerPoolTier.RARE]: [ Species.HISUI_GROWLITHE, Species.HISUI_QWILFISH, Species.SNEASEL, Species.ELEKID, Species.MAGBY, Species.DUSKULL ],
[TrainerPoolTier.SUPER_RARE]: [ Species.ROTOM, Species.SPIRITOMB, Species.HISUI_SNEASEL ]
}),
[TrainerType.JUPITER]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("galactic_commander_female", "galactic", [ Species.SKUNTANK ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_galactic_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.MARS]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("galactic_commander_female", "galactic", [ Species.PURUGLY ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_galactic_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.SATURN]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("galactic_commander", "galactic", [ Species.TOXICROAK ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_galactic_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.PLASMA_GRUNT]: new TrainerConfig(++t).setHasGenders("Plasma Grunt Female").setHasDouble("Plasma Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_plasma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.JUPITER]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("galactic_commander_female", "galactic", [ Species.SKUNTANK ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_galactic_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.MARS]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("galactic_commander_female", "galactic", [ Species.PURUGLY ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_galactic_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.SATURN]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("galactic_commander", "galactic", [ Species.TOXICROAK ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_galactic_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.PLASMA_GRUNT]: new TrainerConfig(++t).setHasGenders("Plasma Grunt Female").setHasDouble("Plasma Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_plasma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.PATRAT, Species.LILLIPUP, Species.PURRLOIN, Species.SCRAFTY, Species.WOOBAT, Species.VANILLITE, Species.SANDILE, Species.TRUBBISH, Species.TYMPOLE ],
[TrainerPoolTier.UNCOMMON]: [ Species.FRILLISH, Species.VENIPEDE, Species.GOLETT, Species.TIMBURR, Species.DARUMAKA, Species.FOONGUS, Species.JOLTIK, Species.CUBCHOO, Species.KLINK ],
[TrainerPoolTier.RARE]: [ Species.PAWNIARD, Species.RUFFLET, Species.VULLABY, Species.ZORUA, Species.DRILBUR, Species.MIENFOO, Species.DURANT, Species.BOUFFALANT ],
[TrainerPoolTier.SUPER_RARE]: [ Species.DRUDDIGON, Species.HISUI_ZORUA, Species.AXEW, Species.DEINO ]
}),
[TrainerType.ZINZOLIN]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("plasma_sage", "plasma", [ Species.CRYOGONAL ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_plasma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.ROOD]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("plasma_sage", "plasma", [ Species.SWOOBAT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_plasma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.FLARE_GRUNT]: new TrainerConfig(++t).setHasGenders("Flare Grunt Female").setHasDouble("Flare Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_flare_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.ZINZOLIN]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("plasma_sage", "plasma", [ Species.CRYOGONAL ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_plasma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.ROOD]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("plasma_sage", "plasma", [ Species.SWOOBAT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_plasma_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.FLARE_GRUNT]: new TrainerConfig(++t).setHasGenders("Flare Grunt Female").setHasDouble("Flare Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_flare_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.FLETCHLING, Species.LITLEO, Species.PONYTA, Species.INKAY, Species.HOUNDOUR, Species.SKORUPI, Species.SCRAFTY, Species.CROAGUNK, Species.SCATTERBUG, Species.ESPURR ],
[TrainerPoolTier.UNCOMMON]: [ Species.HELIOPTILE, Species.ELECTRIKE, Species.SKRELP, Species.PANCHAM, Species.PURRLOIN, Species.POOCHYENA, Species.BINACLE, Species.CLAUNCHER, Species.PUMPKABOO, Species.PHANTUMP, Species.FOONGUS ],
[TrainerPoolTier.RARE]: [ Species.LITWICK, Species.SNEASEL, Species.PAWNIARD, Species.SLIGGOO ],
[TrainerPoolTier.SUPER_RARE]: [ Species.NOIBAT, Species.HISUI_SLIGGOO, Species.HISUI_AVALUGG ]
}),
[TrainerType.BRYONY]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("flare_admin_female", "flare", [ Species.LIEPARD ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_flare_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.XEROSIC]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("flare_admin", "flare", [ Species.MALAMAR ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_flare_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.AETHER_GRUNT]: new TrainerConfig(++t).setHasGenders("Aether Grunt Female").setHasDouble("Aether Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aether_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.BRYONY]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("flare_admin_female", "flare", [ Species.LIEPARD ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_flare_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.XEROSIC]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("flare_admin", "flare", [ Species.MALAMAR ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_flare_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.AETHER_GRUNT]: new TrainerConfig(++t).setHasGenders("Aether Grunt Female").setHasDouble("Aether Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aether_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.PIKIPEK, Species.ROCKRUFF, Species.ALOLA_DIGLETT, Species.ALOLA_EXEGGUTOR, Species.YUNGOOS, Species.CORSOLA, Species.ALOLA_GEODUDE, Species.ALOLA_RAICHU, Species.BOUNSWEET, Species.LILLIPUP, Species.KOMALA, Species.MORELULL, Species.COMFEY, Species.TOGEDEMARU ],
[TrainerPoolTier.UNCOMMON]: [ Species.POLIWAG, Species.STUFFUL, Species.ORANGURU, Species.PASSIMIAN, Species.BRUXISH, Species.MINIOR, Species.WISHIWASHI, Species.ALOLA_SANDSHREW, Species.ALOLA_VULPIX, Species.CRABRAWLER, Species.CUTIEFLY, Species.ORICORIO, Species.MUDBRAY, Species.PYUKUMUKU, Species.ALOLA_MAROWAK ],
[TrainerPoolTier.RARE]: [ Species.GALAR_CORSOLA, Species.TURTONATOR, Species.MIMIKYU, Species.MAGNEMITE, Species.DRAMPA ],
[TrainerPoolTier.SUPER_RARE]: [ Species.JANGMO_O, Species.PORYGON ]
}),
[TrainerType.FABA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("aether_admin", "aether", [ Species.HYPNO ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aether_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.SKULL_GRUNT]: new TrainerConfig(++t).setHasGenders("Skull Grunt Female").setHasDouble("Skull Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_skull_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.FABA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("aether_admin", "aether", [ Species.HYPNO ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_aether_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.SKULL_GRUNT]: new TrainerConfig(++t).setHasGenders("Skull Grunt Female").setHasDouble("Skull Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_skull_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.SALANDIT, Species.ALOLA_RATTATA, Species.EKANS, Species.ALOLA_MEOWTH, Species.SCRAGGY, Species.KOFFING, Species.ALOLA_GRIMER, Species.MAREANIE, Species.SPINARAK, Species.TRUBBISH, Species.DROWZEE ],
[TrainerPoolTier.UNCOMMON]: [ Species.FOMANTIS, Species.SABLEYE, Species.SANDILE, Species.HOUNDOUR, Species.ALOLA_MAROWAK, Species.GASTLY, Species.PANCHAM, Species.ZUBAT, Species.VENIPEDE, Species.VULLABY ],
[TrainerPoolTier.RARE]: [ Species.SANDYGAST, Species.PAWNIARD, Species.MIMIKYU, Species.DHELMISE, Species.WISHIWASHI, Species.NYMBLE ],
[TrainerPoolTier.SUPER_RARE]: [ Species.GRUBBIN, Species.DEWPIDER ]
}),
[TrainerType.PLUMERIA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("skull_admin", "skull", [ Species.SALAZZLE ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_skull_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.MACRO_GRUNT]: new TrainerConfig(++t).setHasGenders("Macro Grunt Female").setHasDouble("Macro Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_macro_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.PLUMERIA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("skull_admin", "skull", [ Species.SALAZZLE ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_skull_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.MACRO_GRUNT]: new TrainerConfig(++t).setHasGenders("Macro Grunt Female").setHasDouble("Macro Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_macro_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.CUFANT, Species.GALAR_MEOWTH, Species.KLINK, Species.ROOKIDEE, Species.CRAMORANT, Species.GALAR_ZIGZAGOON, Species.SKWOVET, Species.STEELIX, Species.MAWILE, Species.FERROSEED ],
[TrainerPoolTier.UNCOMMON]: [ Species.DRILBUR, Species.MAGNEMITE, Species.HATENNA, Species.ARROKUDA, Species.APPLIN, Species.GALAR_PONYTA, Species.GALAR_YAMASK, Species.SINISTEA, Species.RIOLU ],
[TrainerPoolTier.RARE]: [ Species.FALINKS, Species.BELDUM, Species.GALAR_FARFETCHD, Species.GALAR_MR_MIME, Species.HONEDGE, Species.SCIZOR, Species.GALAR_DARUMAKA ],
[TrainerPoolTier.SUPER_RARE]: [ Species.DURALUDON, Species.DREEPY ]
}),
[TrainerType.OLEANA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("macro_admin", "macro", [ Species.GARBODOR ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_oleana").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene)),
[TrainerType.STAR_GRUNT]: new TrainerConfig(++t).setHasGenders("Star Grunt Female").setHasDouble("Star Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.OLEANA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("macro_admin", "macro", [ Species.GARBODOR ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_oleana").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate()),
[TrainerType.STAR_GRUNT]: new TrainerConfig(++t).setHasGenders("Star Grunt Female").setHasDouble("Star Grunts").setMoneyMultiplier(1.0).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_grunt").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setSpeciesPools({
[TrainerPoolTier.COMMON]: [ Species.DUNSPARCE, Species.HOUNDOUR, Species.AZURILL, Species.GULPIN, Species.FOONGUS, Species.FLETCHLING, Species.LITLEO, Species.FLABEBE, Species.CRABRAWLER, Species.NYMBLE, Species.PAWMI, Species.FIDOUGH, Species.SQUAWKABILLY, Species.MASCHIFF, Species.SHROODLE, Species.KLAWF, Species.WIGLETT, Species.PALDEA_WOOPER ],
[TrainerPoolTier.UNCOMMON]: [ Species.KOFFING, Species.EEVEE, Species.GIRAFARIG, Species.RALTS, Species.TORKOAL, Species.SEVIPER, Species.SCRAGGY, Species.ZORUA, Species.MIMIKYU, Species.IMPIDIMP, Species.FALINKS, Species.CAPSAKID, Species.TINKATINK, Species.BOMBIRDIER, Species.CYCLIZAR, Species.FLAMIGO, Species.PALDEA_TAUROS ],
[TrainerPoolTier.RARE]: [ Species.MANKEY, Species.PAWNIARD, Species.CHARCADET, Species.FLITTLE, Species.VAROOM, Species.ORTHWORM ],
[TrainerPoolTier.SUPER_RARE]: [ Species.DONDOZO, Species.GIMMIGHOUL ]
}),
[TrainerType.GIACOMO]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_1", [ Species.KINGAMBIT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.GIACOMO]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_1", [ Species.KINGAMBIT ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setPartyMemberFunc(3, getRandomPartyMemberFunc([ Species.REVAVROOM ], TrainerSlot.TRAINER, true, p => {
p.formIndex = 1; // Segin Starmobile
p.moveset = [ new PokemonMove(Moves.WICKED_TORQUE), new PokemonMove(Moves.SPIN_OUT), new PokemonMove(Moves.SHIFT_GEAR), new PokemonMove(Moves.HIGH_HORSEPOWER) ];
})),
[TrainerType.MELA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_2", [ Species.ARMAROUGE ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.MELA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_2", [ Species.ARMAROUGE ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setPartyMemberFunc(3, getRandomPartyMemberFunc([ Species.REVAVROOM ], TrainerSlot.TRAINER, true, p => {
p.formIndex = 2; // Schedar Starmobile
p.moveset = [ new PokemonMove(Moves.BLAZING_TORQUE), new PokemonMove(Moves.SPIN_OUT), new PokemonMove(Moves.SHIFT_GEAR), new PokemonMove(Moves.HIGH_HORSEPOWER) ];
})),
[TrainerType.ATTICUS]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_3", [ Species.REVAVROOM ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.ATTICUS]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_3", [ Species.REVAVROOM ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setPartyMemberFunc(3, getRandomPartyMemberFunc([ Species.REVAVROOM ], TrainerSlot.TRAINER, true, p => {
p.formIndex = 3; // Navi Starmobile
p.moveset = [ new PokemonMove(Moves.NOXIOUS_TORQUE), new PokemonMove(Moves.SPIN_OUT), new PokemonMove(Moves.SHIFT_GEAR), new PokemonMove(Moves.HIGH_HORSEPOWER) ];
})),
[TrainerType.ORTEGA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_4", [ Species.DACHSBUN ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.ORTEGA]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_4", [ Species.DACHSBUN ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setPartyMemberFunc(3, getRandomPartyMemberFunc([ Species.REVAVROOM ], TrainerSlot.TRAINER, true, p => {
p.formIndex = 4; // Ruchbah Starmobile
p.moveset = [ new PokemonMove(Moves.MAGICAL_TORQUE), new PokemonMove(Moves.SPIN_OUT), new PokemonMove(Moves.SHIFT_GEAR), new PokemonMove(Moves.HIGH_HORSEPOWER) ];
})),
[TrainerType.ERI]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_5", [ Species.ANNIHILAPE ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(scene => getEvilGruntPartyTemplate(scene))
[TrainerType.ERI]: new TrainerConfig(++t).setMoneyMultiplier(1.5).initForEvilTeamAdmin("star_admin", "star_5", [ Species.ANNIHILAPE ]).setEncounterBgm(TrainerType.PLASMA_GRUNT).setBattleBgm("battle_plasma_grunt").setMixedBattleBgm("battle_star_admin").setVictoryBgm("victory_team_plasma").setPartyTemplateFunc(() => getEvilGruntPartyTemplate())
.setPartyMemberFunc(3, getRandomPartyMemberFunc([ Species.REVAVROOM ], TrainerSlot.TRAINER, true, p => {
p.formIndex = 5; // Caph Starmobile
p.moveset = [ new PokemonMove(Moves.COMBAT_TORQUE), new PokemonMove(Moves.SPIN_OUT), new PokemonMove(Moves.SHIFT_GEAR), new PokemonMove(Moves.HIGH_HORSEPOWER) ];

View File

@ -5,10 +5,10 @@ import Pokemon from "../field/pokemon";
import { Type } from "./type";
import Move, { AttackMove } from "./move";
import * as Utils from "../utils";
import BattleScene from "../battle-scene";
import { SuppressWeatherEffectAbAttr } from "./ability";
import { TerrainType, getTerrainName } from "./terrain";
import i18next from "i18next";
import { gScene } from "#app/battle-scene";
export { WeatherType };
export class Weather {
@ -101,8 +101,8 @@ export class Weather {
return false;
}
isEffectSuppressed(scene: BattleScene): boolean {
const field = scene.getField(true);
isEffectSuppressed(): boolean {
const field = gScene.getField(true);
for (const pokemon of field) {
let suppressWeatherEffectAbAttr: SuppressWeatherEffectAbAttr | null = pokemon.getAbility().getAttrs(SuppressWeatherEffectAbAttr)[0];

View File

@ -1,31 +1,31 @@
import BattleScene from "../battle-scene";
import { gScene } from "#app/battle-scene";
import { PokeballType } from "../data/pokeball";
import * as Utils from "../utils";
export function addPokeballOpenParticles(scene: BattleScene, x: number, y: number, pokeballType: PokeballType): void {
export function addPokeballOpenParticles(x: number, y: number, pokeballType: PokeballType): void {
switch (pokeballType) {
case PokeballType.POKEBALL:
doDefaultPbOpenParticles(scene, x, y, 48);
doDefaultPbOpenParticles(x, y, 48);
break;
case PokeballType.GREAT_BALL:
doDefaultPbOpenParticles(scene, x, y, 96);
doDefaultPbOpenParticles(x, y, 96);
break;
case PokeballType.ULTRA_BALL:
doUbOpenParticles(scene, x, y, 8);
doUbOpenParticles(x, y, 8);
break;
case PokeballType.ROGUE_BALL:
doUbOpenParticles(scene, x, y, 10);
doUbOpenParticles(x, y, 10);
break;
case PokeballType.MASTER_BALL:
doMbOpenParticles(scene, x, y);
doMbOpenParticles(x, y);
break;
}
}
function doDefaultPbOpenParticles(scene: BattleScene, x: number, y: number, radius: number) {
const pbOpenParticlesFrameNames = scene.anims.generateFrameNames("pb_particles", { start: 0, end: 3, suffix: ".png" });
if (!(scene.anims.exists("pb_open_particle"))) {
scene.anims.create({
function doDefaultPbOpenParticles(x: number, y: number, radius: number) {
const pbOpenParticlesFrameNames = gScene.anims.generateFrameNames("pb_particles", { start: 0, end: 3, suffix: ".png" });
if (!(gScene.anims.exists("pb_open_particle"))) {
gScene.anims.create({
key: "pb_open_particle",
frames: pbOpenParticlesFrameNames,
frameRate: 16,
@ -34,11 +34,11 @@ function doDefaultPbOpenParticles(scene: BattleScene, x: number, y: number, radi
}
const addParticle = (index: integer) => {
const particle = scene.add.sprite(x, y, "pb_open_particle");
scene.field.add(particle);
const particle = gScene.add.sprite(x, y, "pb_open_particle");
gScene.field.add(particle);
const angle = index * 45;
const [ xCoord, yCoord ] = [ radius * Math.cos(angle * Math.PI / 180), radius * Math.sin(angle * Math.PI / 180) ];
scene.tweens.add({
gScene.tweens.add({
targets: particle,
x: x + xCoord,
y: y + yCoord,
@ -47,9 +47,9 @@ function doDefaultPbOpenParticles(scene: BattleScene, x: number, y: number, radi
particle.play({
key: "pb_open_particle",
startFrame: (index + 3) % 4,
frameRate: Math.floor(16 * scene.gameSpeed)
frameRate: Math.floor(16 * gScene.gameSpeed)
});
scene.tweens.add({
gScene.tweens.add({
targets: particle,
delay: 500,
duration: 75,
@ -60,20 +60,20 @@ function doDefaultPbOpenParticles(scene: BattleScene, x: number, y: number, radi
};
let particleCount = 0;
scene.time.addEvent({
gScene.time.addEvent({
delay: 20,
repeat: 16,
callback: () => addParticle(++particleCount)
});
}
function doUbOpenParticles(scene: BattleScene, x: number, y: number, frameIndex: integer) {
function doUbOpenParticles(x: number, y: number, frameIndex: integer) {
const particles: Phaser.GameObjects.Image[] = [];
for (let i = 0; i < 10; i++) {
particles.push(doFanOutParticle(scene, i * 25, x, y, 1, 1, 5, frameIndex));
particles.push(doFanOutParticle(i * 25, x, y, 1, 1, 5, frameIndex));
}
scene.tweens.add({
gScene.tweens.add({
targets: particles,
delay: 750,
duration: 250,
@ -87,14 +87,14 @@ function doUbOpenParticles(scene: BattleScene, x: number, y: number, frameIndex:
});
}
function doMbOpenParticles(scene: BattleScene, x: number, y: number) {
function doMbOpenParticles(x: number, y: number) {
const particles: Phaser.GameObjects.Image[] = [];
for (let j = 0; j < 2; j++) {
for (let i = 0; i < 8; i++) {
particles.push(doFanOutParticle(scene, i * 32, x, y, j ? 1 : 2, j ? 2 : 1, 8, 4));
particles.push(doFanOutParticle(i * 32, x, y, j ? 1 : 2, j ? 2 : 1, 8, 4));
}
scene.tweens.add({
gScene.tweens.add({
targets: particles,
delay: 750,
duration: 250,
@ -109,11 +109,11 @@ function doMbOpenParticles(scene: BattleScene, x: number, y: number) {
}
}
function doFanOutParticle(scene: BattleScene, trigIndex: integer, x: integer, y: integer, xSpeed: integer, ySpeed: integer, angle: integer, frameIndex: integer): Phaser.GameObjects.Image {
function doFanOutParticle(trigIndex: integer, x: integer, y: integer, xSpeed: integer, ySpeed: integer, angle: integer, frameIndex: integer): Phaser.GameObjects.Image {
let f = 0;
const particle = scene.add.image(x, y, "pb_particles", `${frameIndex}.png`);
scene.field.add(particle);
const particle = gScene.add.image(x, y, "pb_particles", `${frameIndex}.png`);
gScene.field.add(particle);
const updateParticle = () => {
if (!particle.scene) {
@ -125,7 +125,7 @@ function doFanOutParticle(scene: BattleScene, trigIndex: integer, x: integer, y:
f++;
};
const particleTimer = scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -136,20 +136,20 @@ function doFanOutParticle(scene: BattleScene, trigIndex: integer, x: integer, y:
return particle;
}
export function addPokeballCaptureStars(scene: BattleScene, pokeball: Phaser.GameObjects.Sprite): void {
export function addPokeballCaptureStars(pokeball: Phaser.GameObjects.Sprite): void {
const addParticle = () => {
const particle = scene.add.sprite(pokeball.x, pokeball.y, "pb_particles", "4.png");
const particle = gScene.add.sprite(pokeball.x, pokeball.y, "pb_particles", "4.png");
particle.setOrigin(pokeball.originX, pokeball.originY);
particle.setAlpha(0.5);
scene.field.add(particle);
gScene.field.add(particle);
scene.tweens.add({
gScene.tweens.add({
targets: particle,
y: pokeball.y - 10,
ease: "Sine.easeOut",
duration: 250,
onComplete: () => {
scene.tweens.add({
gScene.tweens.add({
targets: particle,
y: pokeball.y,
alpha: 0,
@ -160,13 +160,13 @@ export function addPokeballCaptureStars(scene: BattleScene, pokeball: Phaser.Gam
});
const dist = Utils.randGauss(25);
scene.tweens.add({
gScene.tweens.add({
targets: particle,
x: pokeball.x + dist,
duration: 500
});
scene.tweens.add({
gScene.tweens.add({
targets: particle,
alpha: 0,
delay: 425,

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene"; // ?
import { biomePokemonPools, BiomePoolTier, BiomeTierTrainerPools, biomeTrainerPools, PokemonPools } from "#app/data/balance/biomes";
import { Constructor } from "#app/utils";
import * as Utils from "#app/utils";
@ -33,7 +33,6 @@ import { CommonAnimPhase } from "#app/phases/common-anim-phase";
import { ShowAbilityPhase } from "#app/phases/show-ability-phase";
export class Arena {
public scene: BattleScene;
public biomeType: Biome;
public weather: Weather | null;
public terrain: Terrain | null;
@ -49,8 +48,7 @@ export class Arena {
public readonly eventTarget: EventTarget = new EventTarget();
constructor(scene: BattleScene, biome: Biome, bgm: string) {
this.scene = scene;
constructor(biome: Biome, bgm: string) {
this.biomeType = biome;
this.tags = [];
this.bgm = bgm;
@ -61,12 +59,12 @@ export class Arena {
init() {
const biomeKey = getBiomeKey(this.biomeType);
this.scene.arenaPlayer.setBiome(this.biomeType);
this.scene.arenaPlayerTransition.setBiome(this.biomeType);
this.scene.arenaEnemy.setBiome(this.biomeType);
this.scene.arenaNextEnemy.setBiome(this.biomeType);
this.scene.arenaBg.setTexture(`${biomeKey}_bg`);
this.scene.arenaBgTransition.setTexture(`${biomeKey}_bg`);
gScene.arenaPlayer.setBiome(this.biomeType);
gScene.arenaPlayerTransition.setBiome(this.biomeType);
gScene.arenaEnemy.setBiome(this.biomeType);
gScene.arenaNextEnemy.setBiome(this.biomeType);
gScene.arenaBg.setTexture(`${biomeKey}_bg`);
gScene.arenaBgTransition.setTexture(`${biomeKey}_bg`);
// Redo this on initialize because during save/load the current wave isn't always
// set correctly during construction
@ -85,12 +83,12 @@ export class Arena {
}
randomSpecies(waveIndex: integer, level: integer, attempt?: integer, luckValue?: integer, isBoss?: boolean): PokemonSpecies {
const overrideSpecies = this.scene.gameMode.getOverrideSpecies(waveIndex);
const overrideSpecies = gScene.gameMode.getOverrideSpecies(waveIndex);
if (overrideSpecies) {
return overrideSpecies;
}
const isBossSpecies = !!this.scene.getEncounterBossSegments(waveIndex, level) && !!this.pokemonPool[BiomePoolTier.BOSS].length
&& (this.biomeType !== Biome.END || this.scene.gameMode.isClassic || this.scene.gameMode.isWaveFinal(waveIndex));
const isBossSpecies = !!gScene.getEncounterBossSegments(waveIndex, level) && !!this.pokemonPool[BiomePoolTier.BOSS].length
&& (this.biomeType !== Biome.END || gScene.gameMode.isClassic || gScene.gameMode.isWaveFinal(waveIndex));
const randVal = isBossSpecies ? 64 : 512;
// luck influences encounter rarity
let luckModifier = 0;
@ -110,7 +108,7 @@ export class Arena {
let ret: PokemonSpecies;
let regen = false;
if (!tierPool.length) {
ret = this.scene.randomSpecies(waveIndex, level);
ret = gScene.randomSpecies(waveIndex, level);
} else {
const entry = tierPool[Utils.randSeedInt(tierPool.length)];
let species: Species;
@ -157,7 +155,7 @@ export class Arena {
return this.randomSpecies(waveIndex, level, (attempt || 0) + 1);
}
const newSpeciesId = ret.getWildSpeciesForLevel(level, true, isBoss ?? isBossSpecies, this.scene.gameMode);
const newSpeciesId = ret.getWildSpeciesForLevel(level, true, isBoss ?? isBossSpecies, gScene.gameMode);
if (newSpeciesId !== ret.speciesId) {
console.log("Replaced", Species[ret.speciesId], "with", Species[newSpeciesId]);
ret = getPokemonSpecies(newSpeciesId);
@ -167,7 +165,7 @@ export class Arena {
randomTrainerType(waveIndex: integer, isBoss: boolean = false): TrainerType {
const isTrainerBoss = !!this.trainerPool[BiomePoolTier.BOSS].length
&& (this.scene.gameMode.isTrainerBoss(waveIndex, this.biomeType, this.scene.offsetGym) || isBoss);
&& (gScene.gameMode.isTrainerBoss(waveIndex, this.biomeType, gScene.offsetGym) || isBoss);
console.log(isBoss, this.trainerPool);
const tierValue = Utils.randSeedInt(!isTrainerBoss ? 512 : 64);
let tier = !isTrainerBoss
@ -302,8 +300,8 @@ export class Arena {
*/
trySetWeatherOverride(weather: WeatherType): boolean {
this.weather = new Weather(weather, 0);
this.scene.unshiftPhase(new CommonAnimPhase(this.scene, undefined, undefined, CommonAnim.SUNNY + (weather - 1)));
this.scene.queueMessage(getWeatherStartMessage(weather)!); // TODO: is this bang correct?
gScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.SUNNY + (weather - 1)));
gScene.queueMessage(getWeatherStartMessage(weather)!); // TODO: is this bang correct?
return true;
}
@ -328,13 +326,13 @@ export class Arena {
this.eventTarget.dispatchEvent(new WeatherChangedEvent(oldWeatherType, this.weather?.weatherType!, this.weather?.turnsLeft!)); // TODO: is this bang correct?
if (this.weather) {
this.scene.unshiftPhase(new CommonAnimPhase(this.scene, undefined, undefined, CommonAnim.SUNNY + (weather - 1), true));
this.scene.queueMessage(getWeatherStartMessage(weather)!); // TODO: is this bang correct?
gScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.SUNNY + (weather - 1), true));
gScene.queueMessage(getWeatherStartMessage(weather)!); // TODO: is this bang correct?
} else {
this.scene.queueMessage(getWeatherClearMessage(oldWeatherType)!); // TODO: is this bang correct?
gScene.queueMessage(getWeatherClearMessage(oldWeatherType)!); // TODO: is this bang correct?
}
this.scene.getField(true).filter(p => p.isOnField()).map(pokemon => {
gScene.getField(true).filter(p => p.isOnField()).map(pokemon => {
pokemon.findAndRemoveTags(t => "weatherTypes" in t && !(t.weatherTypes as WeatherType[]).find(t => t === weather));
applyPostWeatherChangeAbAttrs(PostWeatherChangeAbAttr, pokemon, weather);
});
@ -346,13 +344,13 @@ export class Arena {
* Function to trigger all weather based form changes
*/
triggerWeatherBasedFormChanges(): void {
this.scene.getField(true).forEach( p => {
gScene.getField(true).forEach( p => {
const isCastformWithForecast = (p.hasAbility(Abilities.FORECAST) && p.species.speciesId === Species.CASTFORM);
const isCherrimWithFlowerGift = (p.hasAbility(Abilities.FLOWER_GIFT) && p.species.speciesId === Species.CHERRIM);
if (isCastformWithForecast || isCherrimWithFlowerGift) {
new ShowAbilityPhase(this.scene, p.getBattlerIndex());
this.scene.triggerPokemonFormChange(p, SpeciesFormChangeWeatherTrigger);
new ShowAbilityPhase(p.getBattlerIndex());
gScene.triggerPokemonFormChange(p, SpeciesFormChangeWeatherTrigger);
}
});
}
@ -361,13 +359,13 @@ export class Arena {
* Function to trigger all weather based form changes back into their normal forms
*/
triggerWeatherBasedFormChangesToNormal(): void {
this.scene.getField(true).forEach( p => {
gScene.getField(true).forEach( p => {
const isCastformWithForecast = (p.hasAbility(Abilities.FORECAST, false, true) && p.species.speciesId === Species.CASTFORM);
const isCherrimWithFlowerGift = (p.hasAbility(Abilities.FLOWER_GIFT, false, true) && p.species.speciesId === Species.CHERRIM);
if (isCastformWithForecast || isCherrimWithFlowerGift) {
new ShowAbilityPhase(this.scene, p.getBattlerIndex());
return this.scene.triggerPokemonFormChange(p, SpeciesFormChangeRevertWeatherFormTrigger);
new ShowAbilityPhase(p.getBattlerIndex());
return gScene.triggerPokemonFormChange(p, SpeciesFormChangeRevertWeatherFormTrigger);
}
});
}
@ -384,14 +382,14 @@ export class Arena {
if (this.terrain) {
if (!ignoreAnim) {
this.scene.unshiftPhase(new CommonAnimPhase(this.scene, undefined, undefined, CommonAnim.MISTY_TERRAIN + (terrain - 1)));
gScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.MISTY_TERRAIN + (terrain - 1)));
}
this.scene.queueMessage(getTerrainStartMessage(terrain)!); // TODO: is this bang correct?
gScene.queueMessage(getTerrainStartMessage(terrain)!); // TODO: is this bang correct?
} else {
this.scene.queueMessage(getTerrainClearMessage(oldTerrainType)!); // TODO: is this bang correct?
gScene.queueMessage(getTerrainClearMessage(oldTerrainType)!); // TODO: is this bang correct?
}
this.scene.getField(true).filter(p => p.isOnField()).map(pokemon => {
gScene.getField(true).filter(p => p.isOnField()).map(pokemon => {
pokemon.findAndRemoveTags(t => "terrainTypes" in t && !(t.terrainTypes as TerrainType[]).find(t => t === terrain));
applyPostTerrainChangeAbAttrs(PostTerrainChangeAbAttr, pokemon, terrain);
applyAbAttrs(TerrainEventTypeChangeAbAttr, pokemon, null, false);
@ -401,7 +399,7 @@ export class Arena {
}
public isMoveWeatherCancelled(user: Pokemon, move: Move): boolean {
return !!this.weather && !this.weather.isEffectSuppressed(this.scene) && this.weather.isMoveWeatherCancelled(user, move);
return !!this.weather && !this.weather.isEffectSuppressed() && this.weather.isMoveWeatherCancelled(user, move);
}
public isMoveTerrainCancelled(user: Pokemon, targets: BattlerIndex[], move: Move): boolean {
@ -414,7 +412,7 @@ export class Arena {
getAttackTypeMultiplier(attackType: Type, grounded: boolean): number {
let weatherMultiplier = 1;
if (this.weather && !this.weather.isEffectSuppressed(this.scene)) {
if (this.weather && !this.weather.isEffectSuppressed()) {
weatherMultiplier = this.weather.getAttackTypeMultiplier(attackType);
}
@ -480,7 +478,7 @@ export class Arena {
return TimeOfDay.NIGHT;
}
const waveCycle = ((this.scene.currentBattle?.waveIndex || 0) + this.scene.waveCycleOffset) % 40;
const waveCycle = ((gScene.currentBattle?.waveIndex || 0) + gScene.waveCycleOffset) % 40;
if (waveCycle < 15) {
return TimeOfDay.DAY;
@ -750,7 +748,7 @@ export class Arena {
}
preloadBgm(): void {
this.scene.loadBgm(this.bgm);
gScene.loadBgm(this.bgm);
}
getBgmLoopPoint(): number {
@ -874,17 +872,17 @@ export class ArenaBase extends Phaser.GameObjects.Container {
public base: Phaser.GameObjects.Sprite;
public props: Phaser.GameObjects.Sprite[];
constructor(scene: BattleScene, player: boolean) {
super(scene, 0, 0);
constructor(player: boolean) {
super(gScene, 0, 0);
this.player = player;
this.base = scene.addFieldSprite(0, 0, "plains_a", undefined, 1);
this.base = gScene.addFieldSprite(0, 0, "plains_a", undefined, 1);
this.base.setOrigin(0, 0);
this.props = !player ?
new Array(3).fill(null).map(() => {
const ret = scene.addFieldSprite(0, 0, "plains_b", undefined, 1);
const ret = gScene.addFieldSprite(0, 0, "plains_b", undefined, 1);
ret.setOrigin(0, 0);
ret.setVisible(false);
return ret;
@ -900,9 +898,9 @@ export class ArenaBase extends Phaser.GameObjects.Container {
this.base.setTexture(baseKey);
if (this.base.texture.frameTotal > 1) {
const baseFrameNames = this.scene.anims.generateFrameNames(baseKey, { zeroPad: 4, suffix: ".png", start: 1, end: this.base.texture.frameTotal - 1 });
if (!(this.scene.anims.exists(baseKey))) {
this.scene.anims.create({
const baseFrameNames = gScene.anims.generateFrameNames(baseKey, { zeroPad: 4, suffix: ".png", start: 1, end: this.base.texture.frameTotal - 1 });
if (!(gScene.anims.exists(baseKey))) {
gScene.anims.create({
key: baseKey,
frames: baseFrameNames,
frameRate: 12,
@ -918,7 +916,7 @@ export class ArenaBase extends Phaser.GameObjects.Container {
}
if (!this.player) {
(this.scene as BattleScene).executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
this.propValue = propValue === undefined
? hasProps ? Utils.randSeedInt(8) : 0
: propValue;
@ -927,9 +925,9 @@ export class ArenaBase extends Phaser.GameObjects.Container {
prop.setTexture(propKey);
if (hasProps && prop.texture.frameTotal > 1) {
const propFrameNames = this.scene.anims.generateFrameNames(propKey, { zeroPad: 4, suffix: ".png", start: 1, end: prop.texture.frameTotal - 1 });
if (!(this.scene.anims.exists(propKey))) {
this.scene.anims.create({
const propFrameNames = gScene.anims.generateFrameNames(propKey, { zeroPad: 4, suffix: ".png", start: 1, end: prop.texture.frameTotal - 1 });
if (!(gScene.anims.exists(propKey))) {
gScene.anims.create({
key: propKey,
frames: propFrameNames,
frameRate: 12,
@ -944,7 +942,7 @@ export class ArenaBase extends Phaser.GameObjects.Container {
prop.setVisible(hasProps && !!(this.propValue & (1 << p)));
this.add(prop);
});
}, (this.scene as BattleScene).currentBattle?.waveIndex || 0, (this.scene as BattleScene).waveSeed);
}, gScene.currentBattle?.waveIndex || 0, gScene.waveSeed);
}
}
}

View File

@ -2,6 +2,7 @@ import { TextStyle, addTextObject } from "../ui/text";
import Pokemon, { DamageResult, HitResult } from "./pokemon";
import * as Utils from "../utils";
import { BattlerIndex } from "../battle";
import { gScene } from "#app/battle-scene";
type TextAndShadowArr = [ string | null, string | null ];
@ -13,15 +14,13 @@ export default class DamageNumberHandler {
}
add(target: Pokemon, amount: integer, result: DamageResult | HitResult.HEAL = HitResult.EFFECTIVE, critical: boolean = false): void {
const scene = target.scene;
if (!scene?.damageNumbersMode) {
if (!gScene?.damageNumbersMode) {
return;
}
const battlerIndex = target.getBattlerIndex();
const baseScale = target.getSpriteScale() / 6;
const damageNumber = addTextObject(scene, target.x, -(scene.game.canvas.height / 6) + target.y - target.getSprite().height / 2, Utils.formatStat(amount, true), TextStyle.SUMMARY);
const damageNumber = addTextObject(target.x, -(gScene.game.canvas.height / 6) + target.y - target.getSprite().height / 2, Utils.formatStat(amount, true), TextStyle.SUMMARY);
damageNumber.setName("text-damage-number");
damageNumber.setOrigin(0.5, 1);
damageNumber.setScale(baseScale);
@ -58,7 +57,7 @@ export default class DamageNumberHandler {
}
}
scene.fieldUI.add(damageNumber);
gScene.fieldUI.add(damageNumber);
if (!this.damageNumbers.has(battlerIndex)) {
this.damageNumbers.set(battlerIndex, []);
@ -71,14 +70,14 @@ export default class DamageNumberHandler {
this.damageNumbers.get(battlerIndex)!.push(damageNumber);
if (scene.damageNumbersMode === 1) {
scene.tweens.add({
if (gScene.damageNumbersMode === 1) {
gScene.tweens.add({
targets: damageNumber,
duration: Utils.fixedInt(750),
alpha: 1,
y: "-=32"
});
scene.tweens.add({
gScene.tweens.add({
delay: 375,
targets: damageNumber,
duration: Utils.fixedInt(625),
@ -94,7 +93,7 @@ export default class DamageNumberHandler {
damageNumber.setAlpha(0);
scene.tweens.chain({
gScene.tweens.chain({
targets: damageNumber,
tweens: [
{

View File

@ -1,5 +1,5 @@
import { GameObjects } from "phaser";
import BattleScene from "../battle-scene";
import BattleScene, { gScene } from "#app/battle-scene";
import MysteryEncounter from "../data/mystery-encounters/mystery-encounter";
import { Species } from "#enums/species";
import { isNullOrUndefined } from "#app/utils";
@ -75,8 +75,8 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con
public spriteConfigs: MysteryEncounterSpriteConfig[];
public enterFromRight: boolean;
constructor(scene: BattleScene, encounter: MysteryEncounter) {
super(scene, -72, 76);
constructor(encounter: MysteryEncounter) {
super(gScene, -72, 76);
this.encounter = encounter;
this.enterFromRight = encounter.enterIntroVisualsFromRight ?? false;
// Shallow copy configs to allow visual config updates at runtime without dirtying master copy of Encounter
@ -99,16 +99,16 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con
}
const getSprite = (spriteKey: string, hasShadow?: boolean, yShadow?: number) => {
const ret = this.scene.addFieldSprite(0, 0, spriteKey);
const ret = gScene.addFieldSprite(0, 0, spriteKey);
ret.setOrigin(0.5, 1);
ret.setPipeline(this.scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow, yShadowOffset: yShadow ?? 0 });
ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow, yShadowOffset: yShadow ?? 0 });
return ret;
};
const getItemSprite = (spriteKey: string, hasShadow?: boolean, yShadow?: number) => {
const icon = this.scene.add.sprite(-19, 2, "items", spriteKey);
const icon = gScene.add.sprite(-19, 2, "items", spriteKey);
icon.setOrigin(0.5, 1);
icon.setPipeline(this.scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow, yShadowOffset: yShadow ?? 0 });
icon.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow, yShadowOffset: yShadow ?? 0 });
return icon;
};
@ -186,15 +186,15 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con
this.spriteConfigs.forEach((config) => {
if (config.isPokemon) {
this.scene.loadPokemonAtlas(config.spriteKey, config.fileRoot);
gScene.loadPokemonAtlas(config.spriteKey, config.fileRoot);
} else if (config.isItem) {
this.scene.loadAtlas("items", "");
gScene.loadAtlas("items", "");
} else {
this.scene.loadAtlas(config.spriteKey, config.fileRoot);
gScene.loadAtlas(config.spriteKey, config.fileRoot);
}
});
this.scene.load.once(Phaser.Loader.Events.COMPLETE, () => {
gScene.load.once(Phaser.Loader.Events.COMPLETE, () => {
this.spriteConfigs.every((config) => {
if (config.isItem) {
return true;
@ -205,11 +205,11 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con
// Ignore warnings for missing frames, because there will be a lot
console.warn = () => {
};
const frameNames = this.scene.anims.generateFrameNames(config.spriteKey, { zeroPad: 4, suffix: ".png", start: 1, end: 128 });
const frameNames = gScene.anims.generateFrameNames(config.spriteKey, { zeroPad: 4, suffix: ".png", start: 1, end: 128 });
console.warn = originalWarn;
if (!(this.scene.anims.exists(config.spriteKey))) {
this.scene.anims.create({
if (!(gScene.anims.exists(config.spriteKey))) {
gScene.anims.create({
key: config.spriteKey,
frames: frameNames,
frameRate: 12,
@ -223,8 +223,8 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con
resolve();
});
if (!this.scene.load.isLoading()) {
this.scene.load.start();
if (!gScene.load.isLoading()) {
gScene.load.start();
}
});
}
@ -374,7 +374,7 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con
if (duration) {
sprite.setAlpha(0);
this.scene.tweens.add({
gScene.tweens.add({
targets: sprite,
alpha: alpha || 1,
duration: duration,
@ -407,7 +407,7 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con
*/
private untint(sprite, duration: integer, ease?: string): void {
if (duration) {
this.scene.tweens.add({
gScene.tweens.add({
targets: sprite,
alpha: 0,
duration: duration,

View File

@ -1,14 +1,14 @@
import BattleScene from "../battle-scene";
import { gScene } from "#app/battle-scene";
import Pokemon from "./pokemon";
import * as Utils from "../utils";
export default class PokemonSpriteSparkleHandler {
private sprites: Set<Phaser.GameObjects.Sprite>;
setup(scene: BattleScene): void {
setup(): void {
this.sprites = new Set();
scene.tweens.addCounter({
gScene.tweens.addCounter({
duration: Utils.fixedInt(200),
from: 0,
to: 1,
@ -37,7 +37,7 @@ export default class PokemonSpriteSparkleHandler {
const pixel = texture.manager.getPixel(pixelX, pixelY, texture.key, "__BASE");
if (pixel?.alpha) {
const [ xOffset, yOffset ] = [ -s.originX * s.width, -s.originY * s.height ];
const sparkle = (s.scene as BattleScene).addFieldSprite(((pokemon?.x || 0) + s.x + pixelX * ratioX + xOffset), ((pokemon?.y || 0) + s.y + pixelY * ratioY + yOffset), "tera_sparkle");
const sparkle = gScene.addFieldSprite(((pokemon?.x || 0) + s.x + pixelX * ratioX + xOffset), ((pokemon?.y || 0) + s.y + pixelY * ratioY + yOffset), "tera_sparkle");
sparkle.pipelineData["ignoreTimeTint"] = s.pipelineData["ignoreTimeTint"];
sparkle.setName("sprite-tera-sparkle");
sparkle.play("tera_sparkle");

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import BattleScene, { gScene } from "#app/battle-scene";
import { pokemonPrevolutions } from "#app/data/balance/pokemon-evolutions";
import PokemonSpecies, { getPokemonSpecies } from "#app/data/pokemon-species";
import {
@ -35,8 +35,8 @@ export default class Trainer extends Phaser.GameObjects.Container {
public name: string;
public partnerName: string;
constructor(scene: BattleScene, trainerType: TrainerType, variant: TrainerVariant, partyTemplateIndex?: integer, name?: string, partnerName?: string, trainerConfigOverride?: TrainerConfig) {
super(scene, -72, 80);
constructor(trainerType: TrainerType, variant: TrainerVariant, partyTemplateIndex?: integer, name?: string, partnerName?: string, trainerConfigOverride?: TrainerConfig) {
super(gScene, -72, 80);
this.config = trainerConfigs.hasOwnProperty(trainerType)
? trainerConfigs[trainerType]
: trainerConfigs[TrainerType.ACE_TRAINER];
@ -80,9 +80,9 @@ export default class Trainer extends Phaser.GameObjects.Container {
console.log(Object.keys(trainerPartyTemplates)[Object.values(trainerPartyTemplates).indexOf(this.getPartyTemplate())]);
const getSprite = (hasShadow?: boolean, forceFemale?: boolean) => {
const ret = this.scene.addFieldSprite(0, 0, this.config.getSpriteKey(variant === TrainerVariant.FEMALE || forceFemale, this.isDouble()));
const ret = gScene.addFieldSprite(0, 0, this.config.getSpriteKey(variant === TrainerVariant.FEMALE || forceFemale, this.isDouble()));
ret.setOrigin(0.5, 1);
ret.setPipeline(this.scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow });
ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow });
return ret;
};
@ -207,7 +207,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
getPartyTemplate(): TrainerPartyTemplate {
if (this.config.partyTemplateFunc) {
return this.config.partyTemplateFunc(this.scene);
return this.config.partyTemplateFunc();
}
return this.config.partyTemplates[this.partyTemplateIndex];
}
@ -216,7 +216,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
const ret: number[] = [];
const partyTemplate = this.getPartyTemplate();
const difficultyWaveIndex = this.scene.gameMode.getWaveForDifficulty(waveIndex);
const difficultyWaveIndex = gScene.gameMode.getWaveForDifficulty(waveIndex);
const baseLevel = 1 + difficultyWaveIndex / 2 + Math.pow(difficultyWaveIndex / 25, 2);
if (this.isDouble() && partyTemplate.size < 2) {
@ -261,12 +261,12 @@ export default class Trainer extends Phaser.GameObjects.Container {
}
genPartyMember(index: integer): EnemyPokemon {
const battle = this.scene.currentBattle;
const battle = gScene.currentBattle;
const level = battle.enemyLevels?.[index]!; // TODO: is this bang correct?
let ret: EnemyPokemon;
this.scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
const template = this.getPartyTemplate();
const strength: PartyMemberStrength = template.getStrength(index);
@ -275,11 +275,11 @@ export default class Trainer extends Phaser.GameObjects.Container {
if (!(this.config.trainerTypeDouble && this.isDouble() && !this.config.doubleOnly)) {
if (this.config.partyMemberFuncs.hasOwnProperty(index)) {
ret = this.config.partyMemberFuncs[index](this.scene, level, strength);
ret = this.config.partyMemberFuncs[index](level, strength);
return;
}
if (this.config.partyMemberFuncs.hasOwnProperty(index - template.size)) {
ret = this.config.partyMemberFuncs[index - template.size](this.scene, level, template.getStrength(index));
ret = this.config.partyMemberFuncs[index - template.size](level, template.getStrength(index));
return;
}
}
@ -364,23 +364,23 @@ export default class Trainer extends Phaser.GameObjects.Container {
let species = useNewSpeciesPool
? getPokemonSpecies(newSpeciesPool[Math.floor(Utils.randSeedInt(newSpeciesPool.length))])
: template.isSameSpecies(index) && index > offset
? getPokemonSpecies(battle.enemyParty[offset].species.getTrainerSpeciesForLevel(level, false, template.getStrength(offset), this.scene.currentBattle.waveIndex))
? getPokemonSpecies(battle.enemyParty[offset].species.getTrainerSpeciesForLevel(level, false, template.getStrength(offset), gScene.currentBattle.waveIndex))
: this.genNewPartyMemberSpecies(level, strength);
// If the species is from newSpeciesPool, we need to adjust it based on the level and strength
if (newSpeciesPool) {
species = getPokemonSpecies(species.getSpeciesForLevel(level, true, true, strength, this.scene.currentBattle.waveIndex));
species = getPokemonSpecies(species.getSpeciesForLevel(level, true, true, strength, gScene.currentBattle.waveIndex));
}
ret = this.scene.addEnemyPokemon(species, level, !this.isDouble() || !(index % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER);
}, this.config.hasStaticParty ? this.config.getDerivedType() + ((index + 1) << 8) : this.scene.currentBattle.waveIndex + (this.config.getDerivedType() << 10) + (((!this.config.useSameSeedForAllMembers ? index : 0) + 1) << 8));
ret = gScene.addEnemyPokemon(species, level, !this.isDouble() || !(index % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER);
}, this.config.hasStaticParty ? this.config.getDerivedType() + ((index + 1) << 8) : gScene.currentBattle.waveIndex + (this.config.getDerivedType() << 10) + (((!this.config.useSameSeedForAllMembers ? index : 0) + 1) << 8));
return ret!; // TODO: is this bang correct?
}
genNewPartyMemberSpecies(level: integer, strength: PartyMemberStrength, attempt?: integer): PokemonSpecies {
const battle = this.scene.currentBattle;
const battle = gScene.currentBattle;
const template = this.getPartyTemplate();
let baseSpecies: PokemonSpecies;
@ -395,10 +395,10 @@ export default class Trainer extends Phaser.GameObjects.Container {
const tierPool = this.config.speciesPools[tier];
baseSpecies = getPokemonSpecies(Utils.randSeedItem(tierPool));
} else {
baseSpecies = this.scene.randomSpecies(battle.waveIndex, level, false, this.config.speciesFilter);
baseSpecies = gScene.randomSpecies(battle.waveIndex, level, false, this.config.speciesFilter);
}
let ret = getPokemonSpecies(baseSpecies.getTrainerSpeciesForLevel(level, true, strength, this.scene.currentBattle.waveIndex));
let ret = getPokemonSpecies(baseSpecies.getTrainerSpeciesForLevel(level, true, strength, gScene.currentBattle.waveIndex));
let retry = false;
console.log(ret.getName());
@ -417,7 +417,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
console.log("Attempting reroll of species evolution to fit specialty type...");
let evoAttempt = 0;
while (retry && evoAttempt++ < 10) {
ret = getPokemonSpecies(baseSpecies.getTrainerSpeciesForLevel(level, true, strength, this.scene.currentBattle.waveIndex));
ret = getPokemonSpecies(baseSpecies.getTrainerSpeciesForLevel(level, true, strength, gScene.currentBattle.waveIndex));
console.log(ret.name);
if (this.config.specialtyTypes.find(t => ret.isOfType(t))) {
retry = false;
@ -448,7 +448,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
checkDuplicateSpecies(species: PokemonSpecies, baseSpecies: PokemonSpecies): boolean {
const staticPartyPokemon = (signatureSpecies[TrainerType[this.config.trainerType]] ?? []).flat(1);
const currentPartySpecies = this.scene.getEnemyParty().map(p => {
const currentPartySpecies = gScene.getEnemyParty().map(p => {
return p.species.speciesId;
});
return currentPartySpecies.includes(species.speciesId) || staticPartyPokemon.includes(baseSpecies.speciesId);
@ -459,10 +459,10 @@ export default class Trainer extends Phaser.GameObjects.Container {
trainerSlot = TrainerSlot.NONE;
}
const party = this.scene.getEnemyParty();
const nonFaintedLegalPartyMembers = party.slice(this.scene.currentBattle.getBattlerCount()).filter(p => p.isAllowedInBattle()).filter(p => !trainerSlot || p.trainerSlot === trainerSlot);
const party = gScene.getEnemyParty();
const nonFaintedLegalPartyMembers = party.slice(gScene.currentBattle.getBattlerCount()).filter(p => p.isAllowedInBattle()).filter(p => !trainerSlot || p.trainerSlot === trainerSlot);
const partyMemberScores = nonFaintedLegalPartyMembers.map(p => {
const playerField = this.scene.getPlayerField().filter(p => p.isAllowedInBattle());
const playerField = gScene.getPlayerField().filter(p => p.isAllowedInBattle());
let score = 0;
if (playerField.length > 0) {
@ -474,7 +474,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
}
score /= playerField.length;
if (forSwitch && !p.isOnField()) {
this.scene.arena.findTagsOnSide(t => t instanceof ArenaTrapTag, ArenaTagSide.ENEMY).map(t => score *= (t as ArenaTrapTag).getMatchupScoreMultiplier(p));
gScene.arena.findTagsOnSide(t => t instanceof ArenaTrapTag, ArenaTagSide.ENEMY).map(t => score *= (t as ArenaTrapTag).getMatchupScoreMultiplier(p));
}
}
@ -506,7 +506,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
if (maxScorePartyMemberIndexes.length > 1) {
let rand: integer;
this.scene.executeWithSeedOffset(() => rand = Utils.randSeedInt(maxScorePartyMemberIndexes.length), this.scene.currentBattle.turn << 2);
gScene.executeWithSeedOffset(() => rand = Utils.randSeedInt(maxScorePartyMemberIndexes.length), gScene.currentBattle.turn << 2);
return maxScorePartyMemberIndexes[rand!];
}
@ -539,7 +539,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
}
loadAssets(): Promise<void> {
return this.config.loadAssets(this.scene, this.variant);
return this.config.loadAssets(this.variant);
}
initSprite(): void {
@ -627,7 +627,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
if (duration) {
tintSprite.setAlpha(0);
this.scene.tweens.add({
gScene.tweens.add({
targets: tintSprite,
alpha: alpha || 1,
duration: duration,
@ -643,7 +643,7 @@ export default class Trainer extends Phaser.GameObjects.Container {
const tintSprites = this.getTintSprites();
tintSprites.map(tintSprite => {
if (duration) {
this.scene.tweens.add({
gScene.tweens.add({
targets: tintSprite,
alpha: 0,
duration: duration,

View File

@ -1,6 +1,5 @@
import i18next from "i18next";
import { classicFixedBattles, FixedBattleConfig, FixedBattleConfigs } from "./battle";
import BattleScene from "./battle-scene";
import { allChallenges, applyChallenges, Challenge, ChallengeType, copyChallenge } from "./data/challenge";
import PokemonSpecies, { allSpecies } from "./data/pokemon-species";
import { Arena } from "./field/arena";
@ -9,6 +8,7 @@ import * as Utils from "./utils";
import { Biome } from "#enums/biome";
import { Species } from "#enums/species";
import { Challenges } from "./enums/challenges";
import { gScene } from "#app/battle-scene";
export enum GameModes {
CLASSIC,
@ -115,10 +115,10 @@ export class GameMode implements GameModeConfig {
* - override from overrides.ts
* - Town
*/
getStartingBiome(scene: BattleScene): Biome {
getStartingBiome(): Biome {
switch (this.modeId) {
case GameModes.DAILY:
return scene.generateRandomBiome(this.getWaveForDifficulty(1));
return gScene.generateRandomBiome(this.getWaveForDifficulty(1));
default:
return Overrides.STARTING_BIOME_OVERRIDE || Biome.TOWN;
}
@ -146,7 +146,7 @@ export class GameMode implements GameModeConfig {
if (this.isDaily) {
return waveIndex % 10 === 5 || (!(waveIndex % 10) && waveIndex > 10 && !this.isWaveFinal(waveIndex));
}
if ((waveIndex % 30) === (arena.scene.offsetGym ? 0 : 20) && !this.isWaveFinal(waveIndex)) {
if ((waveIndex % 30) === (gScene.offsetGym ? 0 : 20) && !this.isWaveFinal(waveIndex)) {
return true;
} else if (waveIndex % 10 !== 1 && waveIndex % 10) {
/**
@ -163,11 +163,11 @@ export class GameMode implements GameModeConfig {
if (w === waveIndex) {
continue;
}
if ((w % 30) === (arena.scene.offsetGym ? 0 : 20) || this.isFixedBattle(w)) {
if ((w % 30) === (gScene.offsetGym ? 0 : 20) || this.isFixedBattle(w)) {
allowTrainerBattle = false;
break;
} else if (w < waveIndex) {
arena.scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
const waveTrainerChance = arena.getTrainerChance();
if (!Utils.randSeedInt(waveTrainerChance)) {
allowTrainerBattle = false;

View File

@ -15,7 +15,7 @@ import {
getButtonWithKeycode,
getIconForLatestInput, swap,
} from "#app/configs/inputs/configHandler";
import BattleScene from "./battle-scene";
import { gScene } from "./battle-scene";
import { SettingGamepad } from "#app/system/settings/settings-gamepad";
import { SettingKeyboard } from "#app/system/settings/settings-keyboard";
import TouchControl from "#app/touch-controls";
@ -75,7 +75,6 @@ const repeatInputDelayMillis = 250;
*/
export class InputsController {
private gamepads: Array<Phaser.Input.Gamepad.Gamepad> = new Array();
private scene: BattleScene;
public events: Phaser.Events.EventEmitter;
private buttonLock: Button[] = new Array();
@ -105,8 +104,7 @@ export class InputsController {
* It concludes by calling the `init` method to complete the setup.
*/
constructor(scene: BattleScene) {
this.scene = scene;
constructor() {
this.selectedDevice = {
[Device.GAMEPAD]: null,
[Device.KEYBOARD]: "default"
@ -134,14 +132,14 @@ export class InputsController {
* Additionally, it manages the game's behavior when it loses focus to prevent unwanted game actions during this state.
*/
init(): void {
this.events = this.scene.game.events;
this.events = gScene.game.events;
this.scene.game.events.on(Phaser.Core.Events.BLUR, () => {
gScene.game.events.on(Phaser.Core.Events.BLUR, () => {
this.loseFocus();
});
if (typeof this.scene.input.gamepad !== "undefined") {
this.scene.input.gamepad?.on("connected", function (thisGamepad) {
if (typeof gScene.input.gamepad !== "undefined") {
gScene.input.gamepad?.on("connected", function (thisGamepad) {
if (!thisGamepad) {
return;
}
@ -150,25 +148,25 @@ export class InputsController {
this.onReconnect(thisGamepad);
}, this);
this.scene.input.gamepad?.on("disconnected", function (thisGamepad) {
gScene.input.gamepad?.on("disconnected", function (thisGamepad) {
this.onDisconnect(thisGamepad); // when a gamepad is disconnected
}, this);
// Check to see if the gamepad has already been setup by the browser
this.scene.input.gamepad?.refreshPads();
if (this.scene.input.gamepad?.total) {
gScene.input.gamepad?.refreshPads();
if (gScene.input.gamepad?.total) {
this.refreshGamepads();
for (const thisGamepad of this.gamepads) {
this.scene.input.gamepad.emit("connected", thisGamepad);
gScene.input.gamepad.emit("connected", thisGamepad);
}
}
this.scene.input.gamepad?.on("down", this.gamepadButtonDown, this);
this.scene.input.gamepad?.on("up", this.gamepadButtonUp, this);
this.scene.input.keyboard?.on("keydown", this.keyboardKeyDown, this);
this.scene.input.keyboard?.on("keyup", this.keyboardKeyUp, this);
gScene.input.gamepad?.on("down", this.gamepadButtonDown, this);
gScene.input.gamepad?.on("up", this.gamepadButtonUp, this);
gScene.input.keyboard?.on("keydown", this.keyboardKeyDown, this);
gScene.input.keyboard?.on("keyup", this.keyboardKeyUp, this);
}
this.touchControls = new TouchControl(this.scene);
this.touchControls = new TouchControl();
this.moveTouchControlsHandler = new MoveTouchControlsHandler(this.touchControls);
}
@ -238,7 +236,7 @@ export class InputsController {
if (gamepadName) {
this.selectedDevice[Device.GAMEPAD] = gamepadName.toLowerCase();
}
const handler = this.scene.ui?.handlers[Mode.SETTINGS_GAMEPAD] as SettingsGamepadUiHandler;
const handler = gScene.ui?.handlers[Mode.SETTINGS_GAMEPAD] as SettingsGamepadUiHandler;
handler && handler.updateChosenGamepadDisplay();
}
@ -251,7 +249,7 @@ export class InputsController {
if (layoutKeyboard) {
this.selectedDevice[Device.KEYBOARD] = layoutKeyboard.toLowerCase();
}
const handler = this.scene.ui?.handlers[Mode.SETTINGS_KEYBOARD] as SettingsKeyboardUiHandler;
const handler = gScene.ui?.handlers[Mode.SETTINGS_KEYBOARD] as SettingsKeyboardUiHandler;
handler && handler.updateChosenKeyboardDisplay();
}
@ -296,10 +294,10 @@ export class InputsController {
const config = deepCopy(this.getConfig(gamepadID)) as InterfaceConfig;
config.custom = this.configs[gamepadID]?.custom || { ...config.default };
this.configs[gamepadID] = config;
this.scene.gameData?.saveMappingConfigs(gamepadID, this.configs[gamepadID]);
gScene.gameData?.saveMappingConfigs(gamepadID, this.configs[gamepadID]);
}
this.lastSource = "gamepad";
const handler = this.scene.ui?.handlers[Mode.SETTINGS_GAMEPAD] as SettingsGamepadUiHandler;
const handler = gScene.ui?.handlers[Mode.SETTINGS_GAMEPAD] as SettingsGamepadUiHandler;
handler && handler.updateChosenGamepadDisplay();
}
@ -311,7 +309,7 @@ export class InputsController {
const config = deepCopy(this.getConfigKeyboard(layout)) as InterfaceConfig;
config.custom = this.configs[layout]?.custom || { ...config.default };
this.configs[layout] = config;
this.scene.gameData?.saveMappingConfigs(this.selectedDevice[Device.KEYBOARD], this.configs[layout]);
gScene.gameData?.saveMappingConfigs(this.selectedDevice[Device.KEYBOARD], this.configs[layout]);
}
this.initChosenLayoutKeyboard(this.selectedDevice[Device.KEYBOARD]);
}
@ -326,7 +324,7 @@ export class InputsController {
*/
refreshGamepads(): void {
// Sometimes, gamepads are undefined. For some reason.
this.gamepads = this.scene.input.gamepad?.gamepads.filter(function (el) {
this.gamepads = gScene.input.gamepad?.gamepads.filter(function (el) {
return el !== null;
}) ?? [];
@ -409,7 +407,7 @@ export class InputsController {
return;
}
this.lastSource = "gamepad";
if (!this.selectedDevice[Device.GAMEPAD] || (this.scene.ui.getMode() !== Mode.GAMEPAD_BINDING && this.selectedDevice[Device.GAMEPAD] !== pad.id.toLowerCase())) {
if (!this.selectedDevice[Device.GAMEPAD] || (gScene.ui.getMode() !== Mode.GAMEPAD_BINDING && this.selectedDevice[Device.GAMEPAD] !== pad.id.toLowerCase())) {
this.setChosenGamepad(pad.id);
}
if (!this.gamepadSupport || pad.id.toLowerCase() !== this.selectedDevice[Device.GAMEPAD].toLowerCase()) {

View File

@ -20,6 +20,7 @@ import { initStatsKeys } from "#app/ui/game-stats-ui-handler";
import { initVouchers } from "#app/system/voucher";
import { Biome } from "#enums/biome";
import { initMysteryEncounters } from "#app/data/mystery-encounters/mystery-encounters";
import { gScene } from "#app/battle-scene";
export class LoadingScene extends SceneBase {
public static readonly KEY = "loading";
@ -510,7 +511,7 @@ export class LoadingScene extends SceneBase {
async create() {
this.events.once(Phaser.Scenes.Events.DESTROY, () => this.handleDestroy());
this.scene.start("battle");
gScene.scene.start("battle");
}
handleDestroy() {

View File

@ -1,3 +1,4 @@
import { gScene } from "#app/battle-scene";
import { BattleSpec } from "#enums/battle-spec";
import Pokemon from "./field/pokemon";
import i18next from "i18next";
@ -12,7 +13,7 @@ export function getPokemonNameWithAffix(pokemon: Pokemon | undefined): string {
return "Missigno";
}
switch (pokemon.scene.currentBattle.battleSpec) {
switch (gScene.currentBattle.battleSpec) {
case BattleSpec.DEFAULT:
return !pokemon.isPlayer()
? pokemon.hasTrainer()

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { EvolutionItem, pokemonEvolutions } from "#app/data/balance/pokemon-evolutions";
import { tmPoolTiers, tmSpecies } from "#app/data/balance/tms";
import { getBerryEffectDescription, getBerryName } from "#app/data/berry";
@ -63,7 +63,7 @@ export class ModifierType {
return i18next.t(`${this.localeKey}.name` as any);
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t(`${this.localeKey}.description` as any);
}
@ -182,12 +182,12 @@ class AddPokeballModifierType extends ModifierType {
});
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.AddPokeballModifierType.description", {
"modifierCount": this.count,
"pokeballName": getPokeballName(this.pokeballType),
"catchRate": getPokeballCatchMultiplier(this.pokeballType) > -1 ? `${getPokeballCatchMultiplier(this.pokeballType)}x` : "100%",
"pokeballAmount": `${scene.pokeballCounts[this.pokeballType]}`,
"pokeballAmount": `${gScene.pokeballCounts[this.pokeballType]}`,
});
}
}
@ -209,7 +209,7 @@ class AddVoucherModifierType extends ModifierType {
});
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.AddVoucherModifierType.description", {
"modifierCount": this.count,
"voucherTypeName": getVoucherTypeName(this.voucherType),
@ -231,8 +231,8 @@ export class PokemonHeldItemModifierType extends PokemonModifierType {
constructor(localeKey: string, iconImage: string, newModifierFunc: NewModifierFunc, group?: string, soundName?: string) {
super(localeKey, iconImage, newModifierFunc, (pokemon: PlayerPokemon) => {
const dummyModifier = this.newModifier(pokemon);
const matchingModifier = pokemon.scene.findModifier(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id && m.matchType(dummyModifier)) as PokemonHeldItemModifier;
const maxStackCount = dummyModifier.getMaxStackCount(pokemon.scene);
const matchingModifier = gScene.findModifier(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id && m.matchType(dummyModifier)) as PokemonHeldItemModifier;
const maxStackCount = dummyModifier.getMaxStackCount();
if (!maxStackCount) {
return i18next.t("modifierType:ModifierType.PokemonHeldItemModifierType.extra.inoperable", { "pokemonName": getPokemonNameWithAffix(pokemon) });
}
@ -267,7 +267,7 @@ export class PokemonHpRestoreModifierType extends PokemonModifierType {
this.healStatus = healStatus;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return this.restorePoints
? i18next.t("modifierType:ModifierType.PokemonHpRestoreModifierType.description", {
restorePoints: this.restorePoints,
@ -297,7 +297,7 @@ export class PokemonReviveModifierType extends PokemonHpRestoreModifierType {
};
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonReviveModifierType.description", { restorePercent: this.restorePercent });
}
}
@ -313,7 +313,7 @@ export class PokemonStatusHealModifierType extends PokemonModifierType {
}));
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonStatusHealModifierType.description");
}
}
@ -345,7 +345,7 @@ export class PokemonPpRestoreModifierType extends PokemonMoveModifierType {
this.restorePoints = restorePoints;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return this.restorePoints > -1
? i18next.t("modifierType:ModifierType.PokemonPpRestoreModifierType.description", { restorePoints: this.restorePoints })
: i18next.t("modifierType:ModifierType.PokemonPpRestoreModifierType.extra.fully")
@ -368,7 +368,7 @@ export class PokemonAllMovePpRestoreModifierType extends PokemonModifierType {
this.restorePoints = restorePoints;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return this.restorePoints > -1
? i18next.t("modifierType:ModifierType.PokemonAllMovePpRestoreModifierType.description", { restorePoints: this.restorePoints })
: i18next.t("modifierType:ModifierType.PokemonAllMovePpRestoreModifierType.extra.fully")
@ -393,7 +393,7 @@ export class PokemonPpUpModifierType extends PokemonMoveModifierType {
this.upPoints = upPoints;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonPpUpModifierType.description", { upPoints: this.upPoints });
}
}
@ -417,7 +417,7 @@ export class PokemonNatureChangeModifierType extends PokemonModifierType {
return i18next.t("modifierType:ModifierType.PokemonNatureChangeModifierType.name", { natureName: getNatureName(this.nature) });
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonNatureChangeModifierType.description", { natureName: getNatureName(this.nature, true, true, true) });
}
}
@ -443,7 +443,7 @@ export class DoubleBattleChanceBoosterModifierType extends ModifierType {
this.maxBattles = maxBattles;
}
getDescription(_scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.DoubleBattleChanceBoosterModifierType.description", {
battleCount: this.maxBattles
});
@ -468,7 +468,7 @@ export class TempStatStageBoosterModifierType extends ModifierType implements Ge
return i18next.t(`modifierType:TempStatStageBoosterItem.${this.nameKey}`);
}
getDescription(_scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.TempStatStageBoosterModifierType.description", {
stat: i18next.t(getStatKey(this.stat)),
amount: i18next.t(`modifierType:ModifierType.TempStatStageBoosterModifierType.extra.${this.quantityKey}`)
@ -493,7 +493,7 @@ export class BerryModifierType extends PokemonHeldItemModifierType implements Ge
return getBerryName(this.berryType);
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return getBerryEffectDescription(this.berryType);
}
@ -539,7 +539,7 @@ export class AttackTypeBoosterModifierType extends PokemonHeldItemModifierType i
return i18next.t(`modifierType:AttackTypeBoosterItem.${AttackTypeBoosterItem[this.moveType]?.toLowerCase()}`);
}
getDescription(scene: BattleScene): string {
getDescription(): string {
// TODO: Need getTypeName?
return i18next.t("modifierType:ModifierType.AttackTypeBoosterModifierType.description", { moveType: i18next.t(`pokemonInfo:Type.${Type[this.moveType]}`) });
}
@ -576,9 +576,9 @@ export class PokemonLevelIncrementModifierType extends PokemonModifierType {
super(localeKey, iconImage, (_type, args) => new PokemonLevelIncrementModifier(this, (args[0] as PlayerPokemon).id), (_pokemon: PlayerPokemon) => null);
}
getDescription(scene: BattleScene): string {
getDescription(): string {
let levels = 1;
const hasCandyJar = scene.modifiers.find(modifier => modifier instanceof LevelIncrementBoosterModifier);
const hasCandyJar = gScene.modifiers.find(modifier => modifier instanceof LevelIncrementBoosterModifier);
if (hasCandyJar) {
levels += hasCandyJar.stackCount;
}
@ -591,9 +591,9 @@ export class AllPokemonLevelIncrementModifierType extends ModifierType {
super(localeKey, iconImage, (_type, _args) => new PokemonLevelIncrementModifier(this, -1));
}
getDescription(scene: BattleScene): string {
getDescription(): string {
let levels = 1;
const hasCandyJar = scene.modifiers.find(modifier => modifier instanceof LevelIncrementBoosterModifier);
const hasCandyJar = gScene.modifiers.find(modifier => modifier instanceof LevelIncrementBoosterModifier);
if (hasCandyJar) {
levels += hasCandyJar.stackCount;
}
@ -617,7 +617,7 @@ export class BaseStatBoosterModifierType extends PokemonHeldItemModifierType imp
return i18next.t(`modifierType:BaseStatBoosterItem.${this.key}`);
}
getDescription(_scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.BaseStatBoosterModifierType.description", { stat: i18next.t(getStatKey(this.stat)) });
}
@ -637,7 +637,7 @@ export class PokemonBaseStatTotalModifierType extends PokemonHeldItemModifierTyp
this.statModifier = statModifier;
}
override getDescription(scene: BattleScene): string {
override getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonBaseStatTotalModifierType.description", {
increaseDecrease: i18next.t(this.statModifier >= 0 ? "modifierType:ModifierType.PokemonBaseStatTotalModifierType.extra.increase" : "modifierType:ModifierType.PokemonBaseStatTotalModifierType.extra.decrease"),
blessCurse: i18next.t(this.statModifier >= 0 ? "modifierType:ModifierType.PokemonBaseStatTotalModifierType.extra.blessed" : "modifierType:ModifierType.PokemonBaseStatTotalModifierType.extra.cursed"),
@ -663,7 +663,7 @@ export class PokemonBaseStatFlatModifierType extends PokemonHeldItemModifierType
this.stats = stats;
}
override getDescription(scene: BattleScene): string {
override getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonBaseStatFlatModifierType.description", {
stats: this.stats.map(stat => i18next.t(getStatKey(stat))).join("/"),
statValue: this.statModifier,
@ -684,7 +684,7 @@ class AllPokemonFullHpRestoreModifierType extends ModifierType {
this.descriptionKey = descriptionKey!; // TODO: is this bang correct?
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t(`${this.descriptionKey || "modifierType:ModifierType.AllPokemonFullHpRestoreModifierType"}.description` as any);
}
}
@ -706,10 +706,10 @@ export class MoneyRewardModifierType extends ModifierType {
this.moneyMultiplierDescriptorKey = moneyMultiplierDescriptorKey;
}
getDescription(scene: BattleScene): string {
const moneyAmount = new IntegerHolder(scene.getWaveMoneyAmount(this.moneyMultiplier));
scene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);
const formattedMoney = formatMoney(scene.moneyFormat, moneyAmount.value);
getDescription(): string {
const moneyAmount = new IntegerHolder(gScene.getWaveMoneyAmount(this.moneyMultiplier));
gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);
const formattedMoney = formatMoney(gScene.moneyFormat, moneyAmount.value);
return i18next.t("modifierType:ModifierType.MoneyRewardModifierType.description", {
moneyMultiplier: i18next.t(this.moneyMultiplierDescriptorKey as any),
@ -727,7 +727,7 @@ export class ExpBoosterModifierType extends ModifierType {
this.boostPercent = boostPercent;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.ExpBoosterModifierType.description", { boostPercent: this.boostPercent });
}
}
@ -741,7 +741,7 @@ export class PokemonExpBoosterModifierType extends PokemonHeldItemModifierType {
this.boostPercent = boostPercent;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonExpBoosterModifierType.description", { boostPercent: this.boostPercent });
}
}
@ -751,7 +751,7 @@ export class PokemonFriendshipBoosterModifierType extends PokemonHeldItemModifie
super(localeKey, iconImage, (_type, args) => new PokemonFriendshipBoosterModifier(this, (args[0] as Pokemon).id));
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonFriendshipBoosterModifierType.description");
}
}
@ -765,7 +765,7 @@ export class PokemonMoveAccuracyBoosterModifierType extends PokemonHeldItemModif
this.amount = amount;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonMoveAccuracyBoosterModifierType.description", { accuracyAmount: this.amount });
}
}
@ -775,7 +775,7 @@ export class PokemonMultiHitModifierType extends PokemonHeldItemModifierType {
super(localeKey, iconImage, (type, args) => new PokemonMultiHitModifier(type as PokemonMultiHitModifierType, (args[0] as Pokemon).id));
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.PokemonMultiHitModifierType.description");
}
}
@ -802,8 +802,8 @@ export class TmModifierType extends PokemonModifierType {
});
}
getDescription(scene: BattleScene): string {
return i18next.t(scene.enableMoveInfo ? "modifierType:ModifierType.TmModifierTypeWithInfo.description" : "modifierType:ModifierType.TmModifierType.description", { moveName: allMoves[this.moveId].name });
getDescription(): string {
return i18next.t(gScene.enableMoveInfo ? "modifierType:ModifierType.TmModifierTypeWithInfo.description" : "modifierType:ModifierType.TmModifierType.description", { moveName: allMoves[this.moveId].name });
}
}
@ -831,7 +831,7 @@ export class EvolutionItemModifierType extends PokemonModifierType implements Ge
return i18next.t(`modifierType:EvolutionItem.${EvolutionItem[this.evolutionItem]}`);
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.EvolutionItemModifierType.description");
}
@ -870,7 +870,7 @@ export class FormChangeItemModifierType extends PokemonModifierType implements G
return i18next.t(`modifierType:FormChangeItem.${FormChangeItem[this.formChangeItem]}`);
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.FormChangeItemModifierType.description");
}
@ -890,7 +890,7 @@ export class FusePokemonModifierType extends PokemonModifierType {
});
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.FusePokemonModifierType.description");
}
}
@ -1116,12 +1116,12 @@ class FormChangeItemModifierTypeGenerator extends ModifierTypeGenerator {
const formChangeItemPool = [ ...new Set(party.filter(p => pokemonFormChanges.hasOwnProperty(p.species.speciesId)).map(p => {
const formChanges = pokemonFormChanges[p.species.speciesId];
let formChangeItemTriggers = formChanges.filter(fc => ((fc.formKey.indexOf(SpeciesFormKey.MEGA) === -1 && fc.formKey.indexOf(SpeciesFormKey.PRIMAL) === -1) || party[0].scene.getModifiers(MegaEvolutionAccessModifier).length)
&& ((fc.formKey.indexOf(SpeciesFormKey.GIGANTAMAX) === -1 && fc.formKey.indexOf(SpeciesFormKey.ETERNAMAX) === -1) || party[0].scene.getModifiers(GigantamaxAccessModifier).length)
let formChangeItemTriggers = formChanges.filter(fc => ((fc.formKey.indexOf(SpeciesFormKey.MEGA) === -1 && fc.formKey.indexOf(SpeciesFormKey.PRIMAL) === -1) || gScene.getModifiers(MegaEvolutionAccessModifier).length)
&& ((fc.formKey.indexOf(SpeciesFormKey.GIGANTAMAX) === -1 && fc.formKey.indexOf(SpeciesFormKey.ETERNAMAX) === -1) || gScene.getModifiers(GigantamaxAccessModifier).length)
&& (!fc.conditions.length || fc.conditions.filter(cond => cond instanceof SpeciesFormChangeCondition && cond.predicate(p)).length)
&& (fc.preFormKey === p.getFormKey()))
.map(fc => fc.findTrigger(SpeciesFormChangeItemTrigger) as SpeciesFormChangeItemTrigger)
.filter(t => t && t.active && !p.scene.findModifier(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === p.id && m.formChangeItem === t.item));
.filter(t => t && t.active && !gScene.findModifier(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === p.id && m.formChangeItem === t.item));
if (p.species.speciesId === Species.NECROZMA) {
// technically we could use a simplified version and check for formChanges.length > 3, but in case any code changes later, this might break...
@ -1174,7 +1174,7 @@ export class TerastallizeModifierType extends PokemonHeldItemModifierType implem
return i18next.t("modifierType:ModifierType.TerastallizeModifierType.name", { teraType: i18next.t(`pokemonInfo:Type.${Type[this.teraType]}`) });
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.TerastallizeModifierType.description", { teraType: i18next.t(`pokemonInfo:Type.${Type[this.teraType]}`) });
}
@ -1192,7 +1192,7 @@ export class ContactHeldItemTransferChanceModifierType extends PokemonHeldItemMo
this.chancePercent = chancePercent;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.ContactHeldItemTransferChanceModifierType.description", { chancePercent: this.chancePercent });
}
}
@ -1202,7 +1202,7 @@ export class TurnHeldItemTransferModifierType extends PokemonHeldItemModifierTyp
super(localeKey, iconImage, (type, args) => new TurnHeldItemTransferModifier(type, (args[0] as Pokemon).id), group, soundName);
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.TurnHeldItemTransferModifierType.description");
}
}
@ -1218,7 +1218,7 @@ export class EnemyAttackStatusEffectChanceModifierType extends ModifierType {
this.effect = effect;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.EnemyAttackStatusEffectChanceModifierType.description", {
chancePercent: this.chancePercent,
statusEffect: getStatusEffectDescriptor(this.effect),
@ -1235,7 +1235,7 @@ export class EnemyEndureChanceModifierType extends ModifierType {
this.chancePercent = chancePercent;
}
getDescription(scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.EnemyEndureChanceModifierType.description", { chancePercent: this.chancePercent });
}
}
@ -1252,8 +1252,8 @@ type WeightedModifierTypeWeightFunc = (party: Pokemon[], rerollCount?: integer)
*/
function skipInClassicAfterWave(wave: integer, defaultWeight: integer): WeightedModifierTypeWeightFunc {
return (party: Pokemon[]) => {
const gameMode = party[0].scene.gameMode;
const currentWave = party[0].scene.currentBattle.waveIndex;
const gameMode = gScene.gameMode;
const currentWave = gScene.currentBattle.waveIndex;
return gameMode.isClassic && currentWave >= wave ? 0 : defaultWeight;
};
}
@ -1277,8 +1277,8 @@ function skipInLastClassicWaveOrDefault(defaultWeight: integer) : WeightedModifi
*/
function lureWeightFunc(maxBattles: number, weight: number): WeightedModifierTypeWeightFunc {
return (party: Pokemon[]) => {
const lures = party[0].scene.getModifiers(DoubleBattleChanceBoosterModifier);
return !(party[0].scene.gameMode.isClassic && party[0].scene.currentBattle.waveIndex === 199) && (lures.length === 0 || lures.filter(m => m.getMaxBattles() === maxBattles && m.getBattleCount() >= maxBattles * 0.6).length === 0) ? weight : 0;
const lures = gScene.getModifiers(DoubleBattleChanceBoosterModifier);
return !(gScene.gameMode.isClassic && gScene.currentBattle.waveIndex === 199) && (lures.length === 0 || lures.filter(m => m.getMaxBattles() === maxBattles && m.getBattleCount() >= maxBattles * 0.6).length === 0) ? weight : 0;
};
}
class WeightedModifierType {
@ -1412,7 +1412,7 @@ export const modifierTypes = {
TEMP_STAT_STAGE_BOOSTER: () => new TempStatStageBoosterModifierTypeGenerator(),
DIRE_HIT: () => new class extends ModifierType {
getDescription(_scene: BattleScene): string {
getDescription(): string {
return i18next.t("modifierType:ModifierType.TempStatStageBoosterModifierType.description", {
stat: i18next.t("modifierType:ModifierType.DIRE_HIT.extra.raises"),
amount: i18next.t("modifierType:ModifierType.TempStatStageBoosterModifierType.extra.stage")
@ -1435,7 +1435,7 @@ export const modifierTypes = {
if (pregenArgs && (pregenArgs.length === 1) && (pregenArgs[0] in Type)) {
return new TerastallizeModifierType(pregenArgs[0] as Type);
}
if (!party[0].scene.getModifiers(TerastallizeAccessModifier).length) {
if (!gScene.getModifiers(TerastallizeAccessModifier).length) {
return null;
}
let type: Type;
@ -1588,7 +1588,7 @@ interface ModifierPool {
* @returns boolean: true if the player has the maximum of a given ball type
*/
function hasMaximumBalls(party: Pokemon[], ballType: PokeballType): boolean {
return (party[0].scene.gameMode.isClassic && party[0].scene.pokeballCounts[ballType] >= MAX_PER_TYPE_POKEBALLS);
return (gScene.gameMode.isClassic && gScene.pokeballCounts[ballType] >= MAX_PER_TYPE_POKEBALLS);
}
const modifierPool: ModifierPool = {
@ -1671,12 +1671,12 @@ const modifierPool: ModifierPool = {
new WeightedModifierType(modifierTypes.SUPER_LURE, lureWeightFunc(15, 4)),
new WeightedModifierType(modifierTypes.NUGGET, skipInLastClassicWaveOrDefault(5)),
new WeightedModifierType(modifierTypes.EVOLUTION_ITEM, (party: Pokemon[]) => {
return Math.min(Math.ceil(party[0].scene.currentBattle.waveIndex / 15), 8);
return Math.min(Math.ceil(gScene.currentBattle.waveIndex / 15), 8);
}, 8),
new WeightedModifierType(modifierTypes.MAP,
(party: Pokemon[]) => party[0].scene.gameMode.isClassic && party[0].scene.currentBattle.waveIndex < 180 ? party[0].scene.eventManager.isEventActive() ? 2 : 1 : 0,
(party: Pokemon[]) => party[0].scene.eventManager.isEventActive() ? 2 : 1),
new WeightedModifierType(modifierTypes.SOOTHE_BELL, (party: Pokemon[]) => party[0].scene.eventManager.isEventActive() ? 3 : 0),
(party: Pokemon[]) => gScene.gameMode.isClassic && gScene.currentBattle.waveIndex < 180 ? gScene.eventManager.isEventActive() ? 2 : 1 : 0,
(party: Pokemon[]) => gScene.eventManager.isEventActive() ? 2 : 1),
new WeightedModifierType(modifierTypes.SOOTHE_BELL, (party: Pokemon[]) => gScene.eventManager.isEventActive() ? 3 : 0),
new WeightedModifierType(modifierTypes.TM_GREAT, 3),
new WeightedModifierType(modifierTypes.MEMORY_MUSHROOM, (party: Pokemon[]) => {
if (!party.find(p => p.getLearnableLevelMoves().length)) {
@ -1687,8 +1687,8 @@ const modifierPool: ModifierPool = {
}, 4),
new WeightedModifierType(modifierTypes.BASE_STAT_BOOSTER, 3),
new WeightedModifierType(modifierTypes.TERA_SHARD, 1),
new WeightedModifierType(modifierTypes.DNA_SPLICERS, (party: Pokemon[]) => party[0].scene.gameMode.isSplicedOnly && party.filter(p => !p.fusionSpecies).length > 1 ? 4 : 0),
new WeightedModifierType(modifierTypes.VOUCHER, (party: Pokemon[], rerollCount: integer) => !party[0].scene.gameMode.isDaily ? Math.max(1 - rerollCount, 0) : 0, 1),
new WeightedModifierType(modifierTypes.DNA_SPLICERS, (party: Pokemon[]) => gScene.gameMode.isSplicedOnly && party.filter(p => !p.fusionSpecies).length > 1 ? 4 : 0),
new WeightedModifierType(modifierTypes.VOUCHER, (party: Pokemon[], rerollCount: integer) => !gScene.gameMode.isDaily ? Math.max(1 - rerollCount, 0) : 0, 1),
].map(m => {
m.setTier(ModifierTier.GREAT); return m;
}),
@ -1698,11 +1698,11 @@ const modifierPool: ModifierPool = {
new WeightedModifierType(modifierTypes.BIG_NUGGET, skipInLastClassicWaveOrDefault(12)),
new WeightedModifierType(modifierTypes.PP_MAX, 3),
new WeightedModifierType(modifierTypes.MINT, 4),
new WeightedModifierType(modifierTypes.RARE_EVOLUTION_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(party[0].scene.currentBattle.waveIndex / 15) * 4, 32), 32),
new WeightedModifierType(modifierTypes.FORM_CHANGE_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(party[0].scene.currentBattle.waveIndex / 50), 4) * 6, 24),
new WeightedModifierType(modifierTypes.RARE_EVOLUTION_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(gScene.currentBattle.waveIndex / 15) * 4, 32), 32),
new WeightedModifierType(modifierTypes.FORM_CHANGE_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(gScene.currentBattle.waveIndex / 50), 4) * 6, 24),
new WeightedModifierType(modifierTypes.AMULET_COIN, skipInLastClassicWaveOrDefault(3)),
new WeightedModifierType(modifierTypes.EVIOLITE, (party: Pokemon[]) => {
const { gameMode, gameData } = party[0].scene;
const { gameMode, gameData } = gScene;
if (gameMode.isDaily || (!gameMode.isFreshStartChallenge() && gameData.isUnlocked(Unlockables.EVIOLITE))) {
return party.some(p => ((p.getSpeciesForm(true).speciesId in pokemonEvolutions) || (p.isFusion() && (p.getFusionSpeciesForm(true).speciesId in pokemonEvolutions)))
&& !p.getHeldItems().some(i => i instanceof EvolutionStatBoosterModifier) && !p.isMax()) ? 10 : 0;
@ -1744,13 +1744,13 @@ const modifierPool: ModifierPool = {
new WeightedModifierType(modifierTypes.CANDY_JAR, skipInLastClassicWaveOrDefault(5)),
new WeightedModifierType(modifierTypes.ATTACK_TYPE_BOOSTER, 9),
new WeightedModifierType(modifierTypes.TM_ULTRA, 11),
new WeightedModifierType(modifierTypes.RARER_CANDY, (party: Pokemon[]) => party[0].scene.eventManager.isEventActive() ? 6 : 4),
new WeightedModifierType(modifierTypes.RARER_CANDY, (party: Pokemon[]) => gScene.eventManager.isEventActive() ? 6 : 4),
new WeightedModifierType(modifierTypes.GOLDEN_PUNCH, skipInLastClassicWaveOrDefault(2)),
new WeightedModifierType(modifierTypes.IV_SCANNER, skipInLastClassicWaveOrDefault(4)),
new WeightedModifierType(modifierTypes.EXP_CHARM, skipInLastClassicWaveOrDefault(8)),
new WeightedModifierType(modifierTypes.EXP_SHARE, skipInLastClassicWaveOrDefault(10)),
new WeightedModifierType(modifierTypes.EXP_BALANCE, skipInLastClassicWaveOrDefault(3)),
new WeightedModifierType(modifierTypes.TERA_ORB, (party: Pokemon[]) => Math.min(Math.max(Math.floor(party[0].scene.currentBattle.waveIndex / 50) * 2, 1), 4), 4),
new WeightedModifierType(modifierTypes.TERA_ORB, (party: Pokemon[]) => Math.min(Math.max(Math.floor(gScene.currentBattle.waveIndex / 50) * 2, 1), 4), 4),
new WeightedModifierType(modifierTypes.QUICK_CLAW, 3),
new WeightedModifierType(modifierTypes.WIDE_LENS, 4),
].map(m => {
@ -1767,16 +1767,16 @@ const modifierPool: ModifierPool = {
new WeightedModifierType(modifierTypes.BATON, 2),
new WeightedModifierType(modifierTypes.SOUL_DEW, 7),
//new WeightedModifierType(modifierTypes.OVAL_CHARM, 6),
new WeightedModifierType(modifierTypes.SOOTHE_BELL, (party: Pokemon[]) => party[0].scene.eventManager.isEventActive() ? 0 : 4),
new WeightedModifierType(modifierTypes.SOOTHE_BELL, (party: Pokemon[]) => gScene.eventManager.isEventActive() ? 0 : 4),
new WeightedModifierType(modifierTypes.ABILITY_CHARM, skipInClassicAfterWave(189, 6)),
new WeightedModifierType(modifierTypes.FOCUS_BAND, 5),
new WeightedModifierType(modifierTypes.KINGS_ROCK, 3),
new WeightedModifierType(modifierTypes.LOCK_CAPSULE, (party: Pokemon[]) => party[0].scene.gameMode.isClassic ? 0 : 3),
new WeightedModifierType(modifierTypes.LOCK_CAPSULE, (party: Pokemon[]) => gScene.gameMode.isClassic ? 0 : 3),
new WeightedModifierType(modifierTypes.SUPER_EXP_CHARM, skipInLastClassicWaveOrDefault(8)),
new WeightedModifierType(modifierTypes.RARE_FORM_CHANGE_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(party[0].scene.currentBattle.waveIndex / 50), 4) * 6, 24),
new WeightedModifierType(modifierTypes.MEGA_BRACELET, (party: Pokemon[]) => Math.min(Math.ceil(party[0].scene.currentBattle.waveIndex / 50), 4) * 9, 36),
new WeightedModifierType(modifierTypes.DYNAMAX_BAND, (party: Pokemon[]) => Math.min(Math.ceil(party[0].scene.currentBattle.waveIndex / 50), 4) * 9, 36),
new WeightedModifierType(modifierTypes.VOUCHER_PLUS, (party: Pokemon[], rerollCount: integer) => !party[0].scene.gameMode.isDaily ? Math.max(3 - rerollCount * 1, 0) : 0, 3),
new WeightedModifierType(modifierTypes.RARE_FORM_CHANGE_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(gScene.currentBattle.waveIndex / 50), 4) * 6, 24),
new WeightedModifierType(modifierTypes.MEGA_BRACELET, (party: Pokemon[]) => Math.min(Math.ceil(gScene.currentBattle.waveIndex / 50), 4) * 9, 36),
new WeightedModifierType(modifierTypes.DYNAMAX_BAND, (party: Pokemon[]) => Math.min(Math.ceil(gScene.currentBattle.waveIndex / 50), 4) * 9, 36),
new WeightedModifierType(modifierTypes.VOUCHER_PLUS, (party: Pokemon[], rerollCount: integer) => !gScene.gameMode.isDaily ? Math.max(3 - rerollCount * 1, 0) : 0, 3),
].map(m => {
m.setTier(ModifierTier.ROGUE); return m;
}),
@ -1786,9 +1786,9 @@ const modifierPool: ModifierPool = {
new WeightedModifierType(modifierTypes.HEALING_CHARM, 18),
new WeightedModifierType(modifierTypes.MULTI_LENS, 18),
new WeightedModifierType(modifierTypes.VOUCHER_PREMIUM, (party: Pokemon[], rerollCount: integer) =>
!party[0].scene.gameMode.isDaily && !party[0].scene.gameMode.isEndless && !party[0].scene.gameMode.isSplicedOnly ? Math.max(5 - rerollCount * 2, 0) : 0, 5),
new WeightedModifierType(modifierTypes.DNA_SPLICERS, (party: Pokemon[]) => !party[0].scene.gameMode.isSplicedOnly && party.filter(p => !p.fusionSpecies).length > 1 ? 24 : 0, 24),
new WeightedModifierType(modifierTypes.MINI_BLACK_HOLE, (party: Pokemon[]) => (party[0].scene.gameMode.isDaily || (!party[0].scene.gameMode.isFreshStartChallenge() && party[0].scene.gameData.isUnlocked(Unlockables.MINI_BLACK_HOLE))) ? 1 : 0, 1),
!gScene.gameMode.isDaily && !gScene.gameMode.isEndless && !gScene.gameMode.isSplicedOnly ? Math.max(5 - rerollCount * 2, 0) : 0, 5),
new WeightedModifierType(modifierTypes.DNA_SPLICERS, (party: Pokemon[]) => !gScene.gameMode.isSplicedOnly && party.filter(p => !p.fusionSpecies).length > 1 ? 24 : 0, 24),
new WeightedModifierType(modifierTypes.MINI_BLACK_HOLE, (party: Pokemon[]) => (gScene.gameMode.isDaily || (!gScene.gameMode.isFreshStartChallenge() && gScene.gameData.isUnlocked(Unlockables.MINI_BLACK_HOLE))) ? 1 : 0, 1),
].map(m => {
m.setTier(ModifierTier.MASTER); return m;
})
@ -2001,14 +2001,14 @@ export function regenerateModifierPoolThresholds(party: Pokemon[], poolType: Mod
let i = 0;
pool[t].reduce((total: integer, modifierType: WeightedModifierType) => {
const weightedModifierType = modifierType as WeightedModifierType;
const existingModifiers = party[0].scene.findModifiers(m => m.type.id === weightedModifierType.modifierType.id, poolType === ModifierPoolType.PLAYER);
const existingModifiers = gScene.findModifiers(m => m.type.id === weightedModifierType.modifierType.id, poolType === ModifierPoolType.PLAYER);
const itemModifierType = weightedModifierType.modifierType instanceof ModifierTypeGenerator
? weightedModifierType.modifierType.generateType(party)
: weightedModifierType.modifierType;
const weight = !existingModifiers.length
|| itemModifierType instanceof PokemonHeldItemModifierType
|| itemModifierType instanceof FormChangeItemModifierType
|| existingModifiers.find(m => m.stackCount < m.getMaxStackCount(party[0].scene, true))
|| existingModifiers.find(m => m.stackCount < m.getMaxStackCount(true))
? weightedModifierType.weight instanceof Function
? (weightedModifierType.weight as Function)(party, rerollCount)
: weightedModifierType.weight as integer
@ -2229,7 +2229,7 @@ export function getPlayerShopModifierTypeOptionsForWave(waveIndex: integer, base
return options.slice(0, Math.ceil(Math.max(waveIndex + 10, 0) / 30)).flat();
}
export function getEnemyBuffModifierForWave(tier: ModifierTier, enemyModifiers: PersistentModifier[], scene: BattleScene): EnemyPersistentModifier {
export function getEnemyBuffModifierForWave(tier: ModifierTier, enemyModifiers: PersistentModifier[]): EnemyPersistentModifier {
let tierStackCount: number;
switch (tier) {
case ModifierTier.ULTRA:
@ -2247,7 +2247,7 @@ export function getEnemyBuffModifierForWave(tier: ModifierTier, enemyModifiers:
let candidate = getNewModifierTypeOption([], ModifierPoolType.ENEMY_BUFF, tier);
let r = 0;
let matchingModifier: PersistentModifier | undefined;
while (++r < retryCount && (matchingModifier = enemyModifiers.find(m => m.type.id === candidate?.type?.id)) && matchingModifier.getMaxStackCount(scene) < matchingModifier.stackCount + (r < 10 ? tierStackCount : 1)) {
while (++r < retryCount && (matchingModifier = enemyModifiers.find(m => m.type.id === candidate?.type?.id)) && matchingModifier.getMaxStackCount() < matchingModifier.stackCount + (r < 10 ? tierStackCount : 1)) {
candidate = getNewModifierTypeOption([], ModifierPoolType.ENEMY_BUFF, tier);
}
@ -2438,11 +2438,11 @@ export class ModifierTypeOption {
* @returns A number between 0 and 14 based on the party's total luck value, or a random number between 0 and 14 if the player is in Daily Run mode.
*/
export function getPartyLuckValue(party: Pokemon[]): integer {
if (party[0].scene.gameMode.isDaily) {
if (gScene.gameMode.isDaily) {
const DailyLuck = new NumberHolder(0);
party[0].scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
DailyLuck.value = randSeedInt(15); // Random number between 0 and 14
}, 0, party[0].scene.seed);
}, 0, gScene.seed);
return DailyLuck.value;
}
const luck = Phaser.Math.Clamp(party.map(p => p.isAllowedInBattle() ? p.getLuck() : 0)

View File

@ -1,4 +1,3 @@
import type BattleScene from "#app/battle-scene";
import { FusionSpeciesFormEvolution, pokemonEvolutions, pokemonPrevolutions } from "#app/data/balance/pokemon-evolutions";
import { getBerryEffectFunc, getBerryPredicate } from "#app/data/berry";
import { getLevelTotalExp } from "#app/data/exp";
@ -31,6 +30,7 @@ import i18next from "i18next";
import { type DoubleBattleChanceBoosterModifierType, type EvolutionItemModifierType, type FormChangeItemModifierType, type ModifierOverride, type ModifierType, type PokemonBaseStatTotalModifierType, type PokemonExpBoosterModifierType, type PokemonFriendshipBoosterModifierType, type PokemonMoveAccuracyBoosterModifierType, type PokemonMultiHitModifierType, type TerastallizeModifierType, type TmModifierType, getModifierType, ModifierPoolType, ModifierTypeGenerator, modifierTypes, PokemonHeldItemModifierType } from "./modifier-type";
import { Color, ShadowColor } from "#enums/color";
import { FRIENDSHIP_GAIN_FROM_RARE_CANDY } from "#app/data/balance/starters";
import { gScene } from "#app/battle-scene";
export type ModifierPredicate = (modifier: Modifier) => boolean;
@ -64,8 +64,8 @@ export class ModifierBar extends Phaser.GameObjects.Container {
private player: boolean;
private modifierCache: PersistentModifier[];
constructor(scene: BattleScene, enemy?: boolean) {
super(scene, 1 + (enemy ? 302 : 0), 2);
constructor(enemy?: boolean) {
super(gScene, 1 + (enemy ? 302 : 0), 2);
this.player = !enemy;
this.setScale(0.5);
@ -79,7 +79,7 @@ export class ModifierBar extends Phaser.GameObjects.Container {
updateModifiers(modifiers: PersistentModifier[], hideHeldItems: boolean = false) {
this.removeAll(true);
const visibleIconModifiers = modifiers.filter(m => m.isIconVisible(this.scene as BattleScene));
const visibleIconModifiers = modifiers.filter(m => m.isIconVisible());
const nonPokemonSpecificModifiers = visibleIconModifiers.filter(m => !(m as PokemonHeldItemModifier).pokemonId).sort(modifierSortFunc);
const pokemonSpecificModifiers = visibleIconModifiers.filter(m => (m as PokemonHeldItemModifier).pokemonId).sort(modifierSortFunc);
@ -88,7 +88,7 @@ export class ModifierBar extends Phaser.GameObjects.Container {
const thisArg = this;
sortedVisibleIconModifiers.forEach((modifier: PersistentModifier, i: number) => {
const icon = modifier.getIcon(this.scene as BattleScene);
const icon = modifier.getIcon();
if (i >= iconOverflowIndex) {
icon.setVisible(false);
}
@ -96,13 +96,13 @@ export class ModifierBar extends Phaser.GameObjects.Container {
this.setModifierIconPosition(icon, sortedVisibleIconModifiers.length);
icon.setInteractive(new Phaser.Geom.Rectangle(0, 0, 32, 24), Phaser.Geom.Rectangle.Contains);
icon.on("pointerover", () => {
(this.scene as BattleScene).ui.showTooltip(modifier.type.name, modifier.type.getDescription(this.scene as BattleScene));
gScene.ui.showTooltip(modifier.type.name, modifier.type.getDescription());
if (this.modifierCache && this.modifierCache.length > iconOverflowIndex) {
thisArg.updateModifierOverflowVisibility(true);
}
});
icon.on("pointerout", () => {
(this.scene as BattleScene).ui.hideTooltip();
gScene.ui.hideTooltip();
if (this.modifierCache && this.modifierCache.length > iconOverflowIndex) {
thisArg.updateModifierOverflowVisibility(false);
}
@ -170,10 +170,10 @@ export abstract class PersistentModifier extends Modifier {
this.virtualStackCount = 0;
}
add(modifiers: PersistentModifier[], virtual: boolean, scene: BattleScene): boolean {
add(modifiers: PersistentModifier[], virtual: boolean): boolean {
for (const modifier of modifiers) {
if (this.match(modifier)) {
return modifier.incrementStack(scene, this.stackCount, virtual);
return modifier.incrementStack(this.stackCount, virtual);
}
}
@ -191,8 +191,8 @@ export abstract class PersistentModifier extends Modifier {
return [];
}
incrementStack(scene: BattleScene, amount: number, virtual: boolean): boolean {
if (this.getStackCount() + amount <= this.getMaxStackCount(scene)) {
incrementStack(amount: number, virtual: boolean): boolean {
if (this.getStackCount() + amount <= this.getMaxStackCount()) {
if (!virtual) {
this.stackCount += amount;
} else {
@ -208,26 +208,26 @@ export abstract class PersistentModifier extends Modifier {
return this.stackCount + this.virtualStackCount;
}
abstract getMaxStackCount(scene: BattleScene, forThreshold?: boolean): number;
abstract getMaxStackCount(forThreshold?: boolean): number;
isIconVisible(scene: BattleScene): boolean {
isIconVisible(): boolean {
return true;
}
getIcon(scene: BattleScene, forSummary?: boolean): Phaser.GameObjects.Container {
const container = scene.add.container(0, 0);
getIcon(forSummary?: boolean): Phaser.GameObjects.Container {
const container = gScene.add.container(0, 0);
const item = scene.add.sprite(0, 12, "items");
const item = gScene.add.sprite(0, 12, "items");
item.setFrame(this.type.iconImage);
item.setOrigin(0, 0.5);
container.add(item);
const stackText = this.getIconStackText(scene);
const stackText = this.getIconStackText();
if (stackText) {
container.add(stackText);
}
const virtualStackText = this.getIconStackText(scene, true);
const virtualStackText = this.getIconStackText(true);
if (virtualStackText) {
container.add(virtualStackText);
}
@ -235,14 +235,14 @@ export abstract class PersistentModifier extends Modifier {
return container;
}
getIconStackText(scene: BattleScene, virtual?: boolean): Phaser.GameObjects.BitmapText | null {
if (this.getMaxStackCount(scene) === 1 || (virtual && !this.virtualStackCount)) {
getIconStackText(virtual?: boolean): Phaser.GameObjects.BitmapText | null {
if (this.getMaxStackCount() === 1 || (virtual && !this.virtualStackCount)) {
return null;
}
const text = scene.add.bitmapText(10, 15, "item-count", this.stackCount.toString(), 11);
const text = gScene.add.bitmapText(10, 15, "item-count", this.stackCount.toString(), 11);
text.letterSpacing = -0.5;
if (this.getStackCount() >= this.getMaxStackCount(scene)) {
if (this.getStackCount() >= this.getMaxStackCount()) {
text.setTint(0xf89890);
}
text.setOrigin(0, 0);
@ -277,8 +277,8 @@ export class AddPokeballModifier extends ConsumableModifier {
* @param battleScene {@linkcode BattleScene}
* @returns always `true`
*/
override apply(battleScene: BattleScene): boolean {
const pokeballCounts = battleScene.pokeballCounts;
override apply(): boolean {
const pokeballCounts = gScene.pokeballCounts;
pokeballCounts[this.pokeballType] = Math.min(pokeballCounts[this.pokeballType] + this.count, MAX_PER_TYPE_POKEBALLS);
return true;
@ -301,8 +301,8 @@ export class AddVoucherModifier extends ConsumableModifier {
* @param battleScene {@linkcode BattleScene}
* @returns always `true`
*/
override apply(battleScene: BattleScene): boolean {
const voucherCounts = battleScene.gameData.voucherCounts;
override apply(): boolean {
const voucherCounts = gScene.gameData.voucherCounts;
voucherCounts[this.voucherType] += this.count;
return true;
@ -342,13 +342,13 @@ export abstract class LapsingPersistentModifier extends PersistentModifier {
* @param _scene N/A
* @returns `true` if the modifier was successfully added or applied, false otherwise
*/
add(modifiers: PersistentModifier[], _virtual: boolean, scene: BattleScene): boolean {
add(modifiers: PersistentModifier[], _virtual: boolean): boolean {
for (const modifier of modifiers) {
if (this.match(modifier)) {
const modifierInstance = modifier as LapsingPersistentModifier;
if (modifierInstance.getBattleCount() < modifierInstance.getMaxBattles()) {
modifierInstance.resetBattleCount();
scene.playSound("se/restore");
gScene.playSound("se/restore");
return true;
}
// should never get here
@ -370,8 +370,8 @@ export abstract class LapsingPersistentModifier extends PersistentModifier {
return this.battleCount > 0;
}
getIcon(scene: BattleScene): Phaser.GameObjects.Container {
const container = super.getIcon(scene);
getIcon(): Phaser.GameObjects.Container {
const container = super.getIcon();
// Linear interpolation on hue
const hue = Math.floor(120 * (this.battleCount / this.maxBattles) + 5);
@ -380,7 +380,7 @@ export abstract class LapsingPersistentModifier extends PersistentModifier {
const typeHex = hslToHex(hue, 0.5, 0.9);
const strokeHex = hslToHex(hue, 0.7, 0.3);
const battleCountText = addTextObject(scene, 27, 0, this.battleCount.toString(), TextStyle.PARTY, {
const battleCountText = addTextObject(27, 0, this.battleCount.toString(), TextStyle.PARTY, {
fontSize: "66px",
color: typeHex,
});
@ -392,7 +392,7 @@ export abstract class LapsingPersistentModifier extends PersistentModifier {
return container;
}
getIconStackText(_scene: BattleScene, _virtual?: boolean): Phaser.GameObjects.BitmapText | null {
getIconStackText(_virtual?: boolean): Phaser.GameObjects.BitmapText | null {
return null;
}
@ -420,7 +420,7 @@ export abstract class LapsingPersistentModifier extends PersistentModifier {
return [ this.maxBattles, this.battleCount ];
}
getMaxStackCount(_scene: BattleScene, _forThreshold?: boolean): number {
getMaxStackCount(_forThreshold?: boolean): number {
// Must be an abitrary number greater than 1
return 2;
}
@ -573,7 +573,7 @@ export class MapModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 1;
}
}
@ -591,7 +591,7 @@ export class MegaEvolutionAccessModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 1;
}
}
@ -614,7 +614,7 @@ export class GigantamaxAccessModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 1;
}
}
@ -637,7 +637,7 @@ export class TerastallizeAccessModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 1;
}
}
@ -679,33 +679,33 @@ export abstract class PokemonHeldItemModifier extends PersistentModifier {
return !!pokemon && (this.pokemonId === -1 || pokemon.id === this.pokemonId);
}
isIconVisible(scene: BattleScene): boolean {
return !!(this.getPokemon(scene)?.isOnField());
isIconVisible(): boolean {
return !!(this.getPokemon()?.isOnField());
}
getIcon(scene: BattleScene, forSummary?: boolean): Phaser.GameObjects.Container {
const container = !forSummary ? scene.add.container(0, 0) : super.getIcon(scene);
getIcon(forSummary?: boolean): Phaser.GameObjects.Container {
const container = !forSummary ? gScene.add.container(0, 0) : super.getIcon();
if (!forSummary) {
const pokemon = this.getPokemon(scene);
const pokemon = this.getPokemon();
if (pokemon) {
const pokemonIcon = scene.addPokemonIcon(pokemon, -2, 10, 0, 0.5);
const pokemonIcon = gScene.addPokemonIcon(pokemon, -2, 10, 0, 0.5);
container.add(pokemonIcon);
container.setName(pokemon.id.toString());
}
const item = scene.add.sprite(16, this.virtualStackCount ? 8 : 16, "items");
const item = gScene.add.sprite(16, this.virtualStackCount ? 8 : 16, "items");
item.setScale(0.5);
item.setOrigin(0, 0.5);
item.setTexture("items", this.type.iconImage);
container.add(item);
const stackText = this.getIconStackText(scene);
const stackText = this.getIconStackText();
if (stackText) {
container.add(stackText);
}
const virtualStackText = this.getIconStackText(scene, true);
const virtualStackText = this.getIconStackText(true);
if (virtualStackText) {
container.add(virtualStackText);
}
@ -716,8 +716,8 @@ export abstract class PokemonHeldItemModifier extends PersistentModifier {
return container;
}
getPokemon(scene: BattleScene): Pokemon | undefined {
return this.pokemonId ? scene.getPokemonById(this.pokemonId) ?? undefined : undefined;
getPokemon(): Pokemon | undefined {
return this.pokemonId ? gScene.getPokemonById(this.pokemonId) ?? undefined : undefined;
}
getScoreMultiplier(): number {
@ -740,13 +740,13 @@ export abstract class PokemonHeldItemModifier extends PersistentModifier {
return 1;
}
getMaxStackCount(scene: BattleScene, forThreshold?: boolean): number {
const pokemon = this.getPokemon(scene);
getMaxStackCount(forThreshold?: boolean): number {
const pokemon = this.getPokemon();
if (!pokemon) {
return 0;
}
if (pokemon.isPlayer() && forThreshold) {
return scene.getParty().map(p => this.getMaxHeldItemCount(p)).reduce((stackCount: number, maxStackCount: number) => Math.max(stackCount, maxStackCount), 0);
return gScene.getParty().map(p => this.getMaxHeldItemCount(p)).reduce((stackCount: number, maxStackCount: number) => Math.max(stackCount, maxStackCount), 0);
}
return this.getMaxHeldItemCount(pokemon);
}
@ -779,11 +779,11 @@ export abstract class LapsingPokemonHeldItemModifier extends PokemonHeldItemModi
* @param forSummary `true` if the icon is for the summary screen
* @returns the icon as a {@linkcode Phaser.GameObjects.Container | Container}
*/
public getIcon(scene: BattleScene, forSummary?: boolean): Phaser.GameObjects.Container {
const container = super.getIcon(scene, forSummary);
public getIcon(forSummary?: boolean): Phaser.GameObjects.Container {
const container = super.getIcon(forSummary);
if (this.getPokemon(scene)?.isPlayer()) {
const battleCountText = addTextObject(scene, 27, 0, this.battlesLeft.toString(), TextStyle.PARTY, { fontSize: "66px", color: Color.PINK });
if (this.getPokemon()?.isPlayer()) {
const battleCountText = addTextObject(27, 0, this.battlesLeft.toString(), TextStyle.PARTY, { fontSize: "66px", color: Color.PINK });
battleCountText.setShadow(0, 0);
battleCountText.setStroke(ShadowColor.RED, 16);
battleCountText.setOrigin(1, 0);
@ -797,7 +797,7 @@ export abstract class LapsingPokemonHeldItemModifier extends PokemonHeldItemModi
return this.battlesLeft;
}
getMaxStackCount(scene: BattleScene, forThreshold?: boolean): number {
getMaxStackCount(forThreshold?: boolean): number {
return 1;
}
}
@ -835,10 +835,10 @@ export class TerastallizeModifier extends LapsingPokemonHeldItemModifier {
*/
override apply(pokemon: Pokemon): boolean {
if (pokemon.isPlayer()) {
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeTeraTrigger);
pokemon.scene.validateAchv(achvs.TERASTALLIZE);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeTeraTrigger);
gScene.validateAchv(achvs.TERASTALLIZE);
if (this.teraType === Type.STELLAR) {
pokemon.scene.validateAchv(achvs.STELLAR_TERASTALLIZE);
gScene.validateAchv(achvs.STELLAR_TERASTALLIZE);
}
}
pokemon.updateSpritePipelineData();
@ -853,7 +853,7 @@ export class TerastallizeModifier extends LapsingPokemonHeldItemModifier {
public override lapse(pokemon: Pokemon): boolean {
const ret = super.lapse(pokemon);
if (!ret) {
pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeLapseTeraTrigger);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeLapseTeraTrigger);
pokemon.updateSpritePipelineData();
}
return ret;
@ -959,19 +959,19 @@ export class EvoTrackerModifier extends PokemonHeldItemModifier {
return true;
}
getIconStackText(scene: BattleScene, virtual?: boolean): Phaser.GameObjects.BitmapText | null {
if (this.getMaxStackCount(scene) === 1 || (virtual && !this.virtualStackCount)) {
getIconStackText(virtual?: boolean): Phaser.GameObjects.BitmapText | null {
if (this.getMaxStackCount() === 1 || (virtual && !this.virtualStackCount)) {
return null;
}
const pokemon = scene.getPokemonById(this.pokemonId);
const pokemon = gScene.getPokemonById(this.pokemonId);
this.stackCount = pokemon
? pokemon.evoCounter + pokemon.getHeldItems().filter(m => m instanceof DamageMoneyRewardModifier).length
+ pokemon.scene.findModifiers(m => m instanceof MoneyMultiplierModifier || m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length
+ gScene.findModifiers(m => m instanceof MoneyMultiplierModifier || m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length
: this.stackCount;
const text = scene.add.bitmapText(10, 15, "item-count", this.stackCount.toString(), 11);
const text = gScene.add.bitmapText(10, 15, "item-count", this.stackCount.toString(), 11);
text.letterSpacing = -0.5;
if (this.getStackCount() >= this.required) {
text.setTint(0xf89890);
@ -983,7 +983,7 @@ export class EvoTrackerModifier extends PokemonHeldItemModifier {
getMaxHeldItemCount(pokemon: Pokemon): number {
this.stackCount = pokemon.evoCounter + pokemon.getHeldItems().filter(m => m instanceof DamageMoneyRewardModifier).length
+ pokemon.scene.findModifiers(m => m instanceof MoneyMultiplierModifier || m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length;
+ gScene.findModifiers(m => m instanceof MoneyMultiplierModifier || m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length;
return 999;
}
}
@ -1551,7 +1551,7 @@ export class SurviveDamageModifier extends PokemonHeldItemModifier {
if (!surviveDamage.value && pokemon.randSeedInt(10) < this.getStackCount()) {
surviveDamage.value = true;
pokemon.scene.queueMessage(i18next.t("modifier:surviveDamageApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }));
gScene.queueMessage(i18next.t("modifier:surviveDamageApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }));
return true;
}
@ -1595,11 +1595,11 @@ export class BypassSpeedChanceModifier extends PokemonHeldItemModifier {
override apply(pokemon: Pokemon, doBypassSpeed: BooleanHolder): boolean {
if (!doBypassSpeed.value && pokemon.randSeedInt(10) < this.getStackCount()) {
doBypassSpeed.value = true;
const isCommandFight = pokemon.scene.currentBattle.turnCommands[pokemon.getBattlerIndex()]?.command === Command.FIGHT;
const isCommandFight = gScene.currentBattle.turnCommands[pokemon.getBattlerIndex()]?.command === Command.FIGHT;
const hasQuickClaw = this.type instanceof PokemonHeldItemModifierType && this.type.id === "QUICK_CLAW";
if (isCommandFight && hasQuickClaw) {
pokemon.scene.queueMessage(i18next.t("modifier:bypassSpeedChanceApply", { pokemonName: getPokemonNameWithAffix(pokemon), itemName: i18next.t("modifierType:ModifierType.QUICK_CLAW.name") }));
gScene.queueMessage(i18next.t("modifier:bypassSpeedChanceApply", { pokemonName: getPokemonNameWithAffix(pokemon), itemName: i18next.t("modifierType:ModifierType.QUICK_CLAW.name") }));
}
return true;
}
@ -1675,8 +1675,7 @@ export class TurnHealModifier extends PokemonHeldItemModifier {
*/
override apply(pokemon: Pokemon): boolean {
if (!pokemon.isFullHp()) {
const scene = pokemon.scene;
scene.unshiftPhase(new PokemonHealPhase(scene, pokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(),
toDmgValue(pokemon.getMaxHp() / 16) * this.stackCount, i18next.t("modifier:turnHealApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }), true));
return true;
}
@ -1768,8 +1767,7 @@ export class HitHealModifier extends PokemonHeldItemModifier {
*/
override apply(pokemon: Pokemon): boolean {
if (pokemon.turnData.damageDealt && !pokemon.isFullHp()) {
const scene = pokemon.scene;
scene.unshiftPhase(new PokemonHealPhase(scene, pokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(),
toDmgValue(pokemon.turnData.damageDealt / 8) * this.stackCount, i18next.t("modifier:hitHealApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }), true));
}
@ -1814,7 +1812,7 @@ export class LevelIncrementBoosterModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene, forThreshold?: boolean): number {
getMaxStackCount(forThreshold?: boolean): number {
return 99;
}
}
@ -1858,7 +1856,7 @@ export class BerryModifier extends PokemonHeldItemModifier {
*/
override apply(pokemon: Pokemon): boolean {
const preserve = new BooleanHolder(false);
pokemon.scene.applyModifiers(PreserveBerryModifier, pokemon.isPlayer(), pokemon, preserve);
gScene.applyModifiers(PreserveBerryModifier, pokemon.isPlayer(), pokemon, preserve);
getBerryEffectFunc(this.berryType)(pokemon);
if (!preserve.value) {
@ -1913,7 +1911,7 @@ export class PreserveBerryModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 3;
}
}
@ -1937,7 +1935,7 @@ export class PokemonInstantReviveModifier extends PokemonHeldItemModifier {
* @returns always `true`
*/
override apply(pokemon: Pokemon): boolean {
pokemon.scene.unshiftPhase(new PokemonHealPhase(pokemon.scene, pokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(),
toDmgValue(pokemon.getMaxHp() / 2), i18next.t("modifier:pokemonInstantReviveApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }), false, false, true));
pokemon.resetStatus(true, false, true);
@ -1985,7 +1983,7 @@ export class ResetNegativeStatStageModifier extends PokemonHeldItemModifier {
}
if (statRestored) {
pokemon.scene.queueMessage(i18next.t("modifier:resetNegativeStatStageApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }));
gScene.queueMessage(i18next.t("modifier:resetNegativeStatStageApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }));
}
return statRestored;
}
@ -2021,8 +2019,8 @@ export abstract class ConsumablePokemonModifier extends ConsumableModifier {
*/
abstract override apply(playerPokemon: PlayerPokemon, ...args: unknown[]): boolean | Promise<boolean>;
getPokemon(scene: BattleScene) {
return scene.getParty().find(p => p.id === this.pokemonId);
getPokemon() {
return gScene.getParty().find(p => p.id === this.pokemonId);
}
}
@ -2191,11 +2189,11 @@ export class PokemonNatureChangeModifier extends ConsumablePokemonModifier {
override apply(playerPokemon: PlayerPokemon): boolean {
playerPokemon.customPokemonData.nature = this.nature;
let speciesId = playerPokemon.species.speciesId;
playerPokemon.scene.gameData.dexData[speciesId].natureAttr |= 1 << (this.nature + 1);
gScene.gameData.dexData[speciesId].natureAttr |= 1 << (this.nature + 1);
while (pokemonPrevolutions.hasOwnProperty(speciesId)) {
speciesId = pokemonPrevolutions[speciesId];
playerPokemon.scene.gameData.dexData[speciesId].natureAttr |= 1 << (this.nature + 1);
gScene.gameData.dexData[speciesId].natureAttr |= 1 << (this.nature + 1);
}
return true;
@ -2214,17 +2212,17 @@ export class PokemonLevelIncrementModifier extends ConsumablePokemonModifier {
* @returns always `true`
*/
override apply(playerPokemon: PlayerPokemon, levelCount: NumberHolder = new NumberHolder(1)): boolean {
playerPokemon.scene.applyModifiers(LevelIncrementBoosterModifier, true, levelCount);
gScene.applyModifiers(LevelIncrementBoosterModifier, true, levelCount);
playerPokemon.level += levelCount.value;
if (playerPokemon.level <= playerPokemon.scene.getMaxExpLevel(true)) {
if (playerPokemon.level <= gScene.getMaxExpLevel(true)) {
playerPokemon.exp = getLevelTotalExp(playerPokemon.level, playerPokemon.species.growthRate);
playerPokemon.levelExp = 0;
}
playerPokemon.addFriendship(FRIENDSHIP_GAIN_FROM_RARE_CANDY);
playerPokemon.scene.unshiftPhase(new LevelUpPhase(playerPokemon.scene, playerPokemon.scene.getParty().indexOf(playerPokemon), playerPokemon.level - levelCount.value, playerPokemon.level));
gScene.unshiftPhase(new LevelUpPhase(gScene.getParty().indexOf(playerPokemon), playerPokemon.level - levelCount.value, playerPokemon.level));
return true;
}
@ -2244,7 +2242,7 @@ export class TmModifier extends ConsumablePokemonModifier {
*/
override apply(playerPokemon: PlayerPokemon): boolean {
playerPokemon.scene.unshiftPhase(new LearnMovePhase(playerPokemon.scene, playerPokemon.scene.getParty().indexOf(playerPokemon), this.type.moveId, LearnMoveType.TM));
gScene.unshiftPhase(new LearnMovePhase(gScene.getParty().indexOf(playerPokemon), this.type.moveId, LearnMoveType.TM));
return true;
}
@ -2266,7 +2264,7 @@ export class RememberMoveModifier extends ConsumablePokemonModifier {
*/
override apply(playerPokemon: PlayerPokemon, cost?: number): boolean {
playerPokemon.scene.unshiftPhase(new LearnMovePhase(playerPokemon.scene, playerPokemon.scene.getParty().indexOf(playerPokemon), playerPokemon.getLearnableLevelMoves()[this.levelMoveIndex], LearnMoveType.MEMORY, cost));
gScene.unshiftPhase(new LearnMovePhase(gScene.getParty().indexOf(playerPokemon), playerPokemon.getLearnableLevelMoves()[this.levelMoveIndex], LearnMoveType.MEMORY, cost));
return true;
}
@ -2301,7 +2299,7 @@ export class EvolutionItemModifier extends ConsumablePokemonModifier {
}
if (matchingEvolution) {
playerPokemon.scene.unshiftPhase(new EvolutionPhase(playerPokemon.scene, playerPokemon, matchingEvolution, playerPokemon.level - 1));
gScene.unshiftPhase(new EvolutionPhase(playerPokemon, matchingEvolution, playerPokemon.level - 1));
return true;
}
@ -2361,7 +2359,7 @@ export class MultipleParticipantExpBonusModifier extends PersistentModifier {
return new MultipleParticipantExpBonusModifier(this.type, this.stackCount);
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 5;
}
}
@ -2398,7 +2396,7 @@ export class HealingBoosterModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 5;
}
}
@ -2439,7 +2437,7 @@ export class ExpBoosterModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene, forThreshold?: boolean): number {
getMaxStackCount(forThreshold?: boolean): number {
return this.boostMultiplier < 1 ? this.boostMultiplier < 0.6 ? 99 : 30 : 10;
}
}
@ -2518,7 +2516,7 @@ export class ExpShareModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 5;
}
}
@ -2544,7 +2542,7 @@ export class ExpBalanceModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 4;
}
}
@ -2748,7 +2746,7 @@ export class PokemonFormChangeItemModifier extends PokemonHeldItemModifier {
this.active = false;
}
const ret = pokemon.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeItemTrigger);
const ret = gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeItemTrigger);
if (switchActive) {
this.active = true;
@ -2773,21 +2771,20 @@ export class MoneyRewardModifier extends ConsumableModifier {
/**
* Applies {@linkcode MoneyRewardModifier}
* @param battleScene The current {@linkcode BattleScene}
* @returns always `true`
*/
override apply(battleScene: BattleScene): boolean {
const moneyAmount = new NumberHolder(battleScene.getWaveMoneyAmount(this.moneyMultiplier));
override apply(): boolean {
const moneyAmount = new NumberHolder(gScene.getWaveMoneyAmount(this.moneyMultiplier));
battleScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);
gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);
battleScene.addMoney(moneyAmount.value);
gScene.addMoney(moneyAmount.value);
battleScene.getParty().map(p => {
gScene.getParty().map(p => {
if (p.species?.speciesId === Species.GIMMIGHOUL || p.fusionSpecies?.speciesId === Species.GIMMIGHOUL) {
p.evoCounter ? p.evoCounter++ : p.evoCounter = 1;
const modifier = getModifierType(modifierTypes.EVOLUTION_TRACKER_GIMMIGHOUL).newModifier(p) as EvoTrackerModifier;
battleScene.addModifier(modifier);
gScene.addModifier(modifier);
}
});
@ -2819,7 +2816,7 @@ export class MoneyMultiplierModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 5;
}
}
@ -2844,10 +2841,9 @@ export class DamageMoneyRewardModifier extends PokemonHeldItemModifier {
* @returns always `true`
*/
override apply(pokemon: Pokemon, multiplier: NumberHolder): boolean {
const battleScene = pokemon.scene;
const moneyAmount = new NumberHolder(Math.floor(multiplier.value * (0.5 * this.getStackCount())));
battleScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);
battleScene.addMoney(moneyAmount.value);
gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount);
gScene.addMoney(moneyAmount.value);
return true;
}
@ -2868,17 +2864,16 @@ export class MoneyInterestModifier extends PersistentModifier {
/**
* Applies {@linkcode MoneyInterestModifier}
* @param battleScene The current {@linkcode BattleScene}
* @returns always `true`
*/
override apply(battleScene: BattleScene): boolean {
const interestAmount = Math.floor(battleScene.money * 0.1 * this.getStackCount());
battleScene.addMoney(interestAmount);
override apply(): boolean {
const interestAmount = Math.floor(gScene.money * 0.1 * this.getStackCount());
gScene.addMoney(interestAmount);
const userLocale = navigator.language || "en-US";
const formattedMoneyAmount = interestAmount.toLocaleString(userLocale);
const message = i18next.t("modifier:moneyInterestApply", { moneyAmount: formattedMoneyAmount, typeName: this.type.name });
battleScene.queueMessage(message, undefined, true);
gScene.queueMessage(message, undefined, true);
return true;
}
@ -2887,7 +2882,7 @@ export class MoneyInterestModifier extends PersistentModifier {
return new MoneyInterestModifier(this.type, this.stackCount);
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 5;
}
}
@ -2916,7 +2911,7 @@ export class HiddenAbilityRateBoosterModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 4;
}
}
@ -2945,7 +2940,7 @@ export class ShinyRateBoosterModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 4;
}
}
@ -2971,7 +2966,7 @@ export class LockModifierTiersModifier extends PersistentModifier {
return new LockModifierTiersModifier(this.type, this.stackCount);
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 1;
}
}
@ -3011,7 +3006,7 @@ export class HealShopCostModifier extends PersistentModifier {
return super.getArgs().concat(this.shopMultiplier);
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 1;
}
}
@ -3037,7 +3032,7 @@ export class BoostBugSpawnModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 1;
}
}
@ -3115,7 +3110,7 @@ export abstract class HeldItemTransferModifier extends PokemonHeldItemModifier {
const poolType = pokemon.isPlayer() ? ModifierPoolType.PLAYER : pokemon.hasTrainer() ? ModifierPoolType.TRAINER : ModifierPoolType.WILD;
const transferredModifierTypes: ModifierType[] = [];
const itemModifiers = pokemon.scene.findModifiers(m => m instanceof PokemonHeldItemModifier
const itemModifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier
&& m.pokemonId === targetPokemon.id && m.isTransferable, targetPokemon.isPlayer()) as 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);
@ -3133,7 +3128,7 @@ export abstract class HeldItemTransferModifier extends PokemonHeldItemModifier {
}
const randItemIndex = pokemon.randSeedInt(itemModifiers.length);
const randItem = itemModifiers[randItemIndex];
heldItemTransferPromises.push(pokemon.scene.tryTransferHeldItemModifier(randItem, pokemon, false).then(success => {
heldItemTransferPromises.push(gScene.tryTransferHeldItemModifier(randItem, pokemon, false).then(success => {
if (success) {
transferredModifierTypes.push(randItem.type);
itemModifiers.splice(randItemIndex, 1);
@ -3143,7 +3138,7 @@ export abstract class HeldItemTransferModifier extends PokemonHeldItemModifier {
Promise.all(heldItemTransferPromises).then(() => {
for (const mt of transferredModifierTypes) {
pokemon.scene.queueMessage(this.getTransferMessage(pokemon, targetPokemon, mt));
gScene.queueMessage(this.getTransferMessage(pokemon, targetPokemon, mt));
}
});
@ -3262,7 +3257,7 @@ export class IvScannerModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 3;
}
}
@ -3291,7 +3286,7 @@ export class ExtraModifierModifier extends PersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 3;
}
}
@ -3315,14 +3310,14 @@ export class TempExtraModifierModifier extends LapsingPersistentModifier {
* @param scene
* @returns true if the modifier was successfully added or applied, false otherwise
*/
add(modifiers: PersistentModifier[], _virtual: boolean, scene: BattleScene): boolean {
add(modifiers: PersistentModifier[], _virtual: boolean): boolean {
for (const modifier of modifiers) {
if (this.match(modifier)) {
const modifierInstance = modifier as TempExtraModifierModifier;
const newBattleCount = this.getMaxBattles() + modifierInstance.getBattleCount();
modifierInstance.setNewBattleCount(newBattleCount);
scene.playSound("se/restore");
gScene.playSound("se/restore");
return true;
}
}
@ -3355,7 +3350,7 @@ export abstract class EnemyPersistentModifier extends PersistentModifier {
super(type, stackCount);
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 5;
}
}
@ -3380,7 +3375,7 @@ abstract class EnemyDamageMultiplierModifier extends EnemyPersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 99;
}
}
@ -3403,7 +3398,7 @@ export class EnemyDamageBoosterModifier extends EnemyDamageMultiplierModifier {
return [ (this.damageMultiplier - 1) * 100 ];
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 999;
}
}
@ -3426,8 +3421,8 @@ export class EnemyDamageReducerModifier extends EnemyDamageMultiplierModifier {
return [ (1 - this.damageMultiplier) * 100 ];
}
getMaxStackCount(scene: BattleScene): number {
return scene.currentBattle.waveIndex < 2000 ? super.getMaxStackCount(scene) : 999;
getMaxStackCount(): number {
return gScene.currentBattle.waveIndex < 2000 ? super.getMaxStackCount() : 999;
}
}
@ -3460,8 +3455,7 @@ export class EnemyTurnHealModifier extends EnemyPersistentModifier {
*/
override apply(enemyPokemon: Pokemon): boolean {
if (!enemyPokemon.isFullHp()) {
const scene = enemyPokemon.scene;
scene.unshiftPhase(new PokemonHealPhase(scene, enemyPokemon.getBattlerIndex(),
gScene.unshiftPhase(new PokemonHealPhase(enemyPokemon.getBattlerIndex(),
Math.max(Math.floor(enemyPokemon.getMaxHp() / (100 / this.healPercent)) * this.stackCount, 1), i18next.t("modifier:enemyTurnHealApply", { pokemonNameWithAffix: getPokemonNameWithAffix(enemyPokemon) }), true, false, false, false, true));
return true;
}
@ -3469,7 +3463,7 @@ export class EnemyTurnHealModifier extends EnemyPersistentModifier {
return false;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 10;
}
}
@ -3511,7 +3505,7 @@ export class EnemyAttackStatusEffectChanceModifier extends EnemyPersistentModifi
return false;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 10;
}
}
@ -3545,7 +3539,7 @@ export class EnemyStatusEffectHealChanceModifier extends EnemyPersistentModifier
*/
override apply(enemyPokemon: Pokemon): boolean {
if (enemyPokemon.status && Phaser.Math.RND.realInRange(0, 1) < (this.chance * this.getStackCount())) {
enemyPokemon.scene.queueMessage(getStatusEffectHealText(enemyPokemon.status.effect, getPokemonNameWithAffix(enemyPokemon)));
gScene.queueMessage(getStatusEffectHealText(enemyPokemon.status.effect, getPokemonNameWithAffix(enemyPokemon)));
enemyPokemon.resetStatus();
enemyPokemon.updateInfo();
return true;
@ -3554,7 +3548,7 @@ export class EnemyStatusEffectHealChanceModifier extends EnemyPersistentModifier
return false;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 10;
}
}
@ -3598,7 +3592,7 @@ export class EnemyEndureChanceModifier extends EnemyPersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 10;
}
}
@ -3639,7 +3633,7 @@ export class EnemyFusionChanceModifier extends EnemyPersistentModifier {
return true;
}
getMaxStackCount(scene: BattleScene): number {
getMaxStackCount(): number {
return 10;
}
}
@ -3651,15 +3645,15 @@ export class EnemyFusionChanceModifier extends EnemyPersistentModifier {
* @param scene current {@linkcode BattleScene}
* @param isPlayer {@linkcode boolean} for whether the player (`true`) or enemy (`false`) is being overridden
*/
export function overrideModifiers(scene: BattleScene, isPlayer: boolean = true): void {
export function overrideModifiers(isPlayer: boolean = true): void {
const modifiersOverride: ModifierOverride[] = isPlayer ? Overrides.STARTING_MODIFIER_OVERRIDE : Overrides.OPP_MODIFIER_OVERRIDE;
if (!modifiersOverride || modifiersOverride.length === 0 || !scene) {
if (!modifiersOverride || modifiersOverride.length === 0 || !gScene) {
return;
}
// If it's the opponent, clear all of their current modifiers to avoid stacking
if (!isPlayer) {
scene.clearEnemyModifiers();
gScene.clearEnemyModifiers();
}
modifiersOverride.forEach(item => {
@ -3676,9 +3670,9 @@ export function overrideModifiers(scene: BattleScene, isPlayer: boolean = true):
modifier.stackCount = item.count || 1;
if (isPlayer) {
scene.addModifier(modifier, true, false, false, true);
gScene.addModifier(modifier, true, false, false, true);
} else {
scene.addEnemyModifier(modifier, true, true);
gScene.addEnemyModifier(modifier, true, true);
}
}
});
@ -3692,14 +3686,14 @@ export function overrideModifiers(scene: BattleScene, isPlayer: boolean = true):
* @param pokemon {@linkcode Pokemon} whose held items are being overridden
* @param isPlayer {@linkcode boolean} for whether the {@linkcode pokemon} is the player's (`true`) or an enemy (`false`)
*/
export function overrideHeldItems(scene: BattleScene, pokemon: Pokemon, isPlayer: boolean = true): void {
export function overrideHeldItems(pokemon: Pokemon, isPlayer: boolean = true): void {
const heldItemsOverride: ModifierOverride[] = isPlayer ? Overrides.STARTING_HELD_ITEMS_OVERRIDE : Overrides.OPP_HELD_ITEMS_OVERRIDE;
if (!heldItemsOverride || heldItemsOverride.length === 0 || !scene) {
if (!heldItemsOverride || heldItemsOverride.length === 0 || !gScene) {
return;
}
if (!isPlayer) {
scene.clearEnemyHeldItemModifiers(pokemon);
gScene.clearEnemyHeldItemModifiers(pokemon);
}
heldItemsOverride.forEach(item => {
@ -3717,9 +3711,9 @@ export function overrideHeldItems(scene: BattleScene, pokemon: Pokemon, isPlayer
heldItemModifier.pokemonId = pokemon.id;
heldItemModifier.stackCount = qty;
if (isPlayer) {
scene.addModifier(heldItemModifier, true, false, false, true);
gScene.addModifier(heldItemModifier, true, false, false, true);
} else {
scene.addEnemyModifier(heldItemModifier, true, true);
gScene.addEnemyModifier(heldItemModifier, true, true);
}
}
});

View File

@ -1,19 +1,13 @@
import BattleScene from "./battle-scene";
import { gScene } from "./battle-scene";
export class Phase {
protected scene: BattleScene;
constructor(scene: BattleScene) {
this.scene = scene;
}
start() {
if (this.scene.abilityBar.shown) {
this.scene.abilityBar.resetAutoHideTimer();
if (gScene.abilityBar.shown) {
gScene.abilityBar.resetAutoHideTimer();
}
}
end() {
this.scene.shiftPhase();
gScene.shiftPhase();
}
}

View File

@ -1,26 +1,26 @@
import BattleScene from "#app/battle-scene";
import { ModifierTier } from "#app/modifier/modifier-tier";
import { regenerateModifierPoolThresholds, ModifierPoolType, getEnemyBuffModifierForWave } from "#app/modifier/modifier-type";
import { EnemyPersistentModifier } from "#app/modifier/modifier";
import { Phase } from "#app/phase";
import { gScene } from "#app/battle-scene";
export class AddEnemyBuffModifierPhase extends Phase {
constructor(scene: BattleScene) {
super(scene);
constructor() {
super();
}
start() {
super.start();
const waveIndex = this.scene.currentBattle.waveIndex;
const waveIndex = gScene.currentBattle.waveIndex;
const tier = !(waveIndex % 1000) ? ModifierTier.ULTRA : !(waveIndex % 250) ? ModifierTier.GREAT : ModifierTier.COMMON;
regenerateModifierPoolThresholds(this.scene.getEnemyParty(), ModifierPoolType.ENEMY_BUFF);
regenerateModifierPoolThresholds(gScene.getEnemyParty(), ModifierPoolType.ENEMY_BUFF);
const count = Math.ceil(waveIndex / 250);
for (let i = 0; i < count; i++) {
this.scene.addEnemyModifier(getEnemyBuffModifierForWave(tier, this.scene.findModifiers(m => m instanceof EnemyPersistentModifier, false), this.scene), true, true);
gScene.addEnemyModifier(getEnemyBuffModifierForWave(tier, gScene.findModifiers(m => m instanceof EnemyPersistentModifier, false)), true, true);
}
this.scene.updateModifiers(false, true).then(() => this.end());
gScene.updateModifiers(false, true).then(() => this.end());
}
}

View File

@ -1,4 +1,3 @@
import BattleScene from "#app/battle-scene";
import { BattlerIndex } from "#app/battle";
import { getPokeballCatchMultiplier, getPokeballAtlasKey, getPokeballTintColor, doPokeballBounceAnim } from "#app/data/pokeball";
import { getStatusEffectCatchRateMultiplier } from "#app/data/status-effect";
@ -16,14 +15,15 @@ import i18next from "i18next";
import { PokemonPhase } from "./pokemon-phase";
import { VictoryPhase } from "./victory-phase";
import { SubstituteTag } from "#app/data/battler-tags";
import { gScene } from "#app/battle-scene";
export class AttemptCapturePhase extends PokemonPhase {
private pokeballType: PokeballType;
private pokeball: Phaser.GameObjects.Sprite;
private originalY: number;
constructor(scene: BattleScene, targetIndex: integer, pokeballType: PokeballType) {
super(scene, BattlerIndex.ENEMY + targetIndex);
constructor(targetIndex: integer, pokeballType: PokeballType) {
super(BattlerIndex.ENEMY + targetIndex);
this.pokeballType = pokeballType;
}
@ -42,7 +42,7 @@ export class AttemptCapturePhase extends PokemonPhase {
substitute.sprite.setVisible(false);
}
this.scene.pokeballCounts[this.pokeballType]--;
gScene.pokeballCounts[this.pokeballType]--;
this.originalY = pokemon.y;
@ -56,29 +56,29 @@ export class AttemptCapturePhase extends PokemonPhase {
const fpOffset = pokemon.getFieldPositionOffset();
const pokeballAtlasKey = getPokeballAtlasKey(this.pokeballType);
this.pokeball = this.scene.addFieldSprite(16, 80, "pb", pokeballAtlasKey);
this.pokeball = gScene.addFieldSprite(16, 80, "pb", pokeballAtlasKey);
this.pokeball.setOrigin(0.5, 0.625);
this.scene.field.add(this.pokeball);
gScene.field.add(this.pokeball);
this.scene.playSound("se/pb_throw");
this.scene.time.delayedCall(300, () => {
this.scene.field.moveBelow(this.pokeball as Phaser.GameObjects.GameObject, pokemon);
gScene.playSound("se/pb_throw");
gScene.time.delayedCall(300, () => {
gScene.field.moveBelow(this.pokeball as Phaser.GameObjects.GameObject, pokemon);
});
this.scene.tweens.add({
gScene.tweens.add({
targets: this.pokeball,
x: { value: 236 + fpOffset[0], ease: "Linear" },
y: { value: 16 + fpOffset[1], ease: "Cubic.easeOut" },
duration: 500,
onComplete: () => {
this.pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
this.scene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
this.scene.playSound("se/pb_rel");
gScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
gScene.playSound("se/pb_rel");
pokemon.tint(getPokeballTintColor(this.pokeballType));
addPokeballOpenParticles(this.scene, this.pokeball.x, this.pokeball.y, this.pokeballType);
addPokeballOpenParticles(this.pokeball.x, this.pokeball.y, this.pokeballType);
this.scene.tweens.add({
gScene.tweens.add({
targets: pokemon,
duration: 500,
ease: "Sine.easeIn",
@ -87,13 +87,13 @@ export class AttemptCapturePhase extends PokemonPhase {
onComplete: () => {
this.pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
pokemon.setVisible(false);
this.scene.playSound("se/pb_catch");
this.scene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}`));
gScene.playSound("se/pb_catch");
gScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}`));
const doShake = () => {
let shakeCount = 0;
const pbX = this.pokeball.x;
const shakeCounter = this.scene.tweens.addCounter({
const shakeCounter = gScene.tweens.addCounter({
from: 0,
to: 1,
repeat: 4,
@ -115,27 +115,27 @@ export class AttemptCapturePhase extends PokemonPhase {
this.failCatch(shakeCount);
} else if (shakeCount++ < 3) {
if (pokeballMultiplier === -1 || pokemon.randSeedInt(65536) < y) {
this.scene.playSound("se/pb_move");
gScene.playSound("se/pb_move");
} else {
shakeCounter.stop();
this.failCatch(shakeCount);
}
} else {
this.scene.playSound("se/pb_lock");
addPokeballCaptureStars(this.scene, this.pokeball);
gScene.playSound("se/pb_lock");
addPokeballCaptureStars(this.pokeball);
const pbTint = this.scene.add.sprite(this.pokeball.x, this.pokeball.y, "pb", "pb");
const pbTint = gScene.add.sprite(this.pokeball.x, this.pokeball.y, "pb", "pb");
pbTint.setOrigin(this.pokeball.originX, this.pokeball.originY);
pbTint.setTintFill(0);
pbTint.setAlpha(0);
this.scene.field.add(pbTint);
this.scene.tweens.add({
gScene.field.add(pbTint);
gScene.tweens.add({
targets: pbTint,
alpha: 0.375,
duration: 200,
easing: "Sine.easeOut",
onComplete: () => {
this.scene.tweens.add({
gScene.tweens.add({
targets: pbTint,
alpha: 0,
duration: 200,
@ -152,7 +152,7 @@ export class AttemptCapturePhase extends PokemonPhase {
});
};
this.scene.time.delayedCall(250, () => doPokeballBounceAnim(this.scene, this.pokeball, 16, 72, 350, doShake));
gScene.time.delayedCall(250, () => doPokeballBounceAnim(this.pokeball, 16, 72, 350, doShake));
}
});
}
@ -162,7 +162,7 @@ export class AttemptCapturePhase extends PokemonPhase {
failCatch(shakeCount: integer) {
const pokemon = this.getPokemon();
this.scene.playSound("se/pb_rel");
gScene.playSound("se/pb_rel");
pokemon.setY(this.originalY);
if (pokemon.status?.effect !== StatusEffect.SLEEP) {
pokemon.cry(pokemon.getHpRatio() > 0.25 ? undefined : { rate: 0.85 });
@ -178,16 +178,16 @@ export class AttemptCapturePhase extends PokemonPhase {
const pokeballAtlasKey = getPokeballAtlasKey(this.pokeballType);
this.pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`);
this.scene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
gScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`));
this.scene.tweens.add({
gScene.tweens.add({
targets: pokemon,
duration: 250,
ease: "Sine.easeOut",
scale: 1
});
this.scene.currentBattle.lastUsedPokeball = this.pokeballType;
gScene.currentBattle.lastUsedPokeball = this.pokeballType;
this.removePb();
this.end();
}
@ -198,48 +198,48 @@ export class AttemptCapturePhase extends PokemonPhase {
const speciesForm = !pokemon.fusionSpecies ? pokemon.getSpeciesForm() : pokemon.getFusionSpeciesForm();
if (speciesForm.abilityHidden && (pokemon.fusionSpecies ? pokemon.fusionAbilityIndex : pokemon.abilityIndex) === speciesForm.getAbilityCount() - 1) {
this.scene.validateAchv(achvs.HIDDEN_ABILITY);
gScene.validateAchv(achvs.HIDDEN_ABILITY);
}
if (pokemon.species.subLegendary) {
this.scene.validateAchv(achvs.CATCH_SUB_LEGENDARY);
gScene.validateAchv(achvs.CATCH_SUB_LEGENDARY);
}
if (pokemon.species.legendary) {
this.scene.validateAchv(achvs.CATCH_LEGENDARY);
gScene.validateAchv(achvs.CATCH_LEGENDARY);
}
if (pokemon.species.mythical) {
this.scene.validateAchv(achvs.CATCH_MYTHICAL);
gScene.validateAchv(achvs.CATCH_MYTHICAL);
}
this.scene.pokemonInfoContainer.show(pokemon, true);
gScene.pokemonInfoContainer.show(pokemon, true);
this.scene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs);
gScene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs);
this.scene.ui.showText(i18next.t("battle:pokemonCaught", { pokemonName: getPokemonNameWithAffix(pokemon) }), null, () => {
gScene.ui.showText(i18next.t("battle:pokemonCaught", { pokemonName: getPokemonNameWithAffix(pokemon) }), null, () => {
const end = () => {
this.scene.unshiftPhase(new VictoryPhase(this.scene, this.battlerIndex));
this.scene.pokemonInfoContainer.hide();
gScene.unshiftPhase(new VictoryPhase(this.battlerIndex));
gScene.pokemonInfoContainer.hide();
this.removePb();
this.end();
};
const removePokemon = () => {
this.scene.addFaintedEnemyScore(pokemon);
this.scene.getPlayerField().filter(p => p.isActive(true)).forEach(playerPokemon => playerPokemon.removeTagsBySourceId(pokemon.id));
gScene.addFaintedEnemyScore(pokemon);
gScene.getPlayerField().filter(p => p.isActive(true)).forEach(playerPokemon => playerPokemon.removeTagsBySourceId(pokemon.id));
pokemon.hp = 0;
pokemon.trySetStatus(StatusEffect.FAINT);
this.scene.clearEnemyHeldItemModifiers();
this.scene.field.remove(pokemon, true);
gScene.clearEnemyHeldItemModifiers();
gScene.field.remove(pokemon, true);
};
const addToParty = (slotIndex?: number) => {
const newPokemon = pokemon.addToParty(this.pokeballType, slotIndex);
const modifiers = this.scene.findModifiers(m => m instanceof PokemonHeldItemModifier, false);
if (this.scene.getParty().filter(p => p.isShiny()).length === 6) {
this.scene.validateAchv(achvs.SHINY_PARTY);
const modifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier, false);
if (gScene.getParty().filter(p => p.isShiny()).length === 6) {
gScene.validateAchv(achvs.SHINY_PARTY);
}
Promise.all(modifiers.map(m => this.scene.addModifier(m, true))).then(() => {
this.scene.updateModifiers(true);
Promise.all(modifiers.map(m => gScene.addModifier(m, true))).then(() => {
gScene.updateModifiers(true);
removePokemon();
if (newPokemon) {
newPokemon.loadAssets().then(end);
@ -248,21 +248,21 @@ export class AttemptCapturePhase extends PokemonPhase {
}
});
};
Promise.all([ pokemon.hideInfo(), this.scene.gameData.setPokemonCaught(pokemon) ]).then(() => {
if (this.scene.getParty().length === 6) {
Promise.all([ pokemon.hideInfo(), gScene.gameData.setPokemonCaught(pokemon) ]).then(() => {
if (gScene.getParty().length === 6) {
const promptRelease = () => {
this.scene.ui.showText(i18next.t("battle:partyFull", { pokemonName: pokemon.getNameToRender() }), null, () => {
this.scene.pokemonInfoContainer.makeRoomForConfirmUi(1, true);
this.scene.ui.setMode(Mode.CONFIRM, () => {
const newPokemon = this.scene.addPlayerPokemon(pokemon.species, pokemon.level, pokemon.abilityIndex, pokemon.formIndex, pokemon.gender, pokemon.shiny, pokemon.variant, pokemon.ivs, pokemon.nature, pokemon);
this.scene.ui.setMode(Mode.SUMMARY, newPokemon, 0, SummaryUiMode.DEFAULT, () => {
this.scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.showText(i18next.t("battle:partyFull", { pokemonName: pokemon.getNameToRender() }), null, () => {
gScene.pokemonInfoContainer.makeRoomForConfirmUi(1, true);
gScene.ui.setMode(Mode.CONFIRM, () => {
const newPokemon = gScene.addPlayerPokemon(pokemon.species, pokemon.level, pokemon.abilityIndex, pokemon.formIndex, pokemon.gender, pokemon.shiny, pokemon.variant, pokemon.ivs, pokemon.nature, pokemon);
gScene.ui.setMode(Mode.SUMMARY, newPokemon, 0, SummaryUiMode.DEFAULT, () => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
promptRelease();
});
}, false);
}, () => {
this.scene.ui.setMode(Mode.PARTY, PartyUiMode.RELEASE, this.fieldIndex, (slotIndex: integer, _option: PartyOption) => {
this.scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.setMode(Mode.PARTY, PartyUiMode.RELEASE, this.fieldIndex, (slotIndex: integer, _option: PartyOption) => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
if (slotIndex < 6) {
addToParty(slotIndex);
} else {
@ -271,7 +271,7 @@ export class AttemptCapturePhase extends PokemonPhase {
});
});
}, () => {
this.scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
removePokemon();
end();
});
@ -287,7 +287,7 @@ export class AttemptCapturePhase extends PokemonPhase {
}
removePb() {
this.scene.tweens.add({
gScene.tweens.add({
targets: this.pokeball,
duration: 250,
delay: 250,

View File

@ -1,4 +1,3 @@
import BattleScene from "#app/battle-scene";
import { applyAbAttrs, RunSuccessAbAttr } from "#app/data/ability";
import { Stat } from "#app/enums/stat";
import { StatusEffect } from "#app/enums/status-effect";
@ -8,21 +7,22 @@ import * as Utils from "#app/utils";
import { BattleEndPhase } from "./battle-end-phase";
import { NewBattlePhase } from "./new-battle-phase";
import { PokemonPhase } from "./pokemon-phase";
import { gScene } from "#app/battle-scene";
export class AttemptRunPhase extends PokemonPhase {
/** For testing purposes: this is to force the pokemon to fail and escape */
public forceFailEscape = false;
constructor(scene: BattleScene, fieldIndex: number) {
super(scene, fieldIndex);
constructor(fieldIndex: number) {
super(fieldIndex);
}
start() {
super.start();
const playerField = this.scene.getPlayerField();
const enemyField = this.scene.getEnemyField();
const playerField = gScene.getPlayerField();
const enemyField = gScene.getEnemyField();
const playerPokemon = this.getPokemon();
@ -33,18 +33,18 @@ export class AttemptRunPhase extends PokemonPhase {
applyAbAttrs(RunSuccessAbAttr, playerPokemon, null, false, escapeChance);
if (playerPokemon.randSeedInt(100) < escapeChance.value && !this.forceFailEscape) {
this.scene.playSound("se/flee");
this.scene.queueMessage(i18next.t("battle:runAwaySuccess"), null, true, 500);
gScene.playSound("se/flee");
gScene.queueMessage(i18next.t("battle:runAwaySuccess"), null, true, 500);
this.scene.tweens.add({
targets: [ this.scene.arenaEnemy, enemyField ].flat(),
gScene.tweens.add({
targets: [ gScene.arenaEnemy, enemyField ].flat(),
alpha: 0,
duration: 250,
ease: "Sine.easeIn",
onComplete: () => enemyField.forEach(enemyPokemon => enemyPokemon.destroy())
});
this.scene.clearEnemyHeldItemModifiers();
gScene.clearEnemyHeldItemModifiers();
enemyField.forEach(enemyPokemon => {
enemyPokemon.hideInfo().then(() => enemyPokemon.destroy());
@ -52,11 +52,11 @@ export class AttemptRunPhase extends PokemonPhase {
enemyPokemon.trySetStatus(StatusEffect.FAINT);
});
this.scene.pushPhase(new BattleEndPhase(this.scene));
this.scene.pushPhase(new NewBattlePhase(this.scene));
gScene.pushPhase(new BattleEndPhase());
gScene.pushPhase(new NewBattlePhase());
} else {
playerPokemon.turnData.failedRunAway = true;
this.scene.queueMessage(i18next.t("battle:runAwayCannotEscape"), null, true, 500);
gScene.queueMessage(i18next.t("battle:runAwayCannotEscape"), null, true, 500);
}
this.end();
@ -103,6 +103,6 @@ export class AttemptRunPhase extends PokemonPhase {
const escapeSlope = (maxChance - minChance) / speedCap;
// This will calculate the escape chance given all of the above and clamp it to the range of [`minChance`, `maxChance`]
escapeChance.value = Phaser.Math.Clamp(Math.round((escapeSlope * speedRatio) + minChance + (escapeBonus * this.scene.currentBattle.escapeAttempts++)), minChance, maxChance);
escapeChance.value = Phaser.Math.Clamp(Math.round((escapeSlope * speedRatio) + minChance + (escapeBonus * gScene.currentBattle.escapeAttempts++)), minChance, maxChance);
}
}

View File

@ -1,15 +1,15 @@
import { gScene } from "#app/battle-scene";
import { applyPostBattleAbAttrs, PostBattleAbAttr } from "#app/data/ability";
import { LapsingPersistentModifier, LapsingPokemonHeldItemModifier } from "#app/modifier/modifier";
import { BattlePhase } from "./battle-phase";
import { GameOverPhase } from "./game-over-phase";
import BattleScene from "#app/battle-scene";
export class BattleEndPhase extends BattlePhase {
/** If true, will increment battles won */
isVictory: boolean;
constructor(scene: BattleScene, isVictory: boolean = true) {
super(scene);
constructor(isVictory: boolean = true) {
super();
this.isVictory = isVictory;
}
@ -18,50 +18,50 @@ export class BattleEndPhase extends BattlePhase {
super.start();
if (this.isVictory) {
this.scene.currentBattle.addBattleScore(this.scene);
gScene.currentBattle.addBattleScore();
this.scene.gameData.gameStats.battles++;
if (this.scene.currentBattle.trainer) {
this.scene.gameData.gameStats.trainersDefeated++;
gScene.gameData.gameStats.battles++;
if (gScene.currentBattle.trainer) {
gScene.gameData.gameStats.trainersDefeated++;
}
if (this.scene.gameMode.isEndless && this.scene.currentBattle.waveIndex + 1 > this.scene.gameData.gameStats.highestEndlessWave) {
this.scene.gameData.gameStats.highestEndlessWave = this.scene.currentBattle.waveIndex + 1;
if (gScene.gameMode.isEndless && gScene.currentBattle.waveIndex + 1 > gScene.gameData.gameStats.highestEndlessWave) {
gScene.gameData.gameStats.highestEndlessWave = gScene.currentBattle.waveIndex + 1;
}
}
// Endless graceful end
if (this.scene.gameMode.isEndless && this.scene.currentBattle.waveIndex >= 5850) {
this.scene.clearPhaseQueue();
this.scene.unshiftPhase(new GameOverPhase(this.scene, true));
if (gScene.gameMode.isEndless && gScene.currentBattle.waveIndex >= 5850) {
gScene.clearPhaseQueue();
gScene.unshiftPhase(new GameOverPhase(true));
}
for (const pokemon of this.scene.getField()) {
for (const pokemon of gScene.getField()) {
if (pokemon && pokemon.battleSummonData) {
pokemon.battleSummonData.waveTurnCount = 1;
}
}
for (const pokemon of this.scene.getParty().filter(p => p.isAllowedInBattle())) {
for (const pokemon of gScene.getParty().filter(p => p.isAllowedInBattle())) {
applyPostBattleAbAttrs(PostBattleAbAttr, pokemon);
}
if (this.scene.currentBattle.moneyScattered) {
this.scene.currentBattle.pickUpScatteredMoney(this.scene);
if (gScene.currentBattle.moneyScattered) {
gScene.currentBattle.pickUpScatteredMoney();
}
this.scene.clearEnemyHeldItemModifiers();
gScene.clearEnemyHeldItemModifiers();
const lapsingModifiers = this.scene.findModifiers(m => m instanceof LapsingPersistentModifier || m instanceof LapsingPokemonHeldItemModifier) as (LapsingPersistentModifier | LapsingPokemonHeldItemModifier)[];
const lapsingModifiers = gScene.findModifiers(m => m instanceof LapsingPersistentModifier || m instanceof LapsingPokemonHeldItemModifier) as (LapsingPersistentModifier | LapsingPokemonHeldItemModifier)[];
for (const m of lapsingModifiers) {
const args: any[] = [];
if (m instanceof LapsingPokemonHeldItemModifier) {
args.push(this.scene.getPokemonById(m.pokemonId));
args.push(gScene.getPokemonById(m.pokemonId));
}
if (!m.lapse(...args)) {
this.scene.removeModifier(m);
gScene.removeModifier(m);
}
}
this.scene.updateModifiers().then(() => this.end());
gScene.updateModifiers().then(() => this.end());
}
}

View File

@ -1,15 +1,15 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { TrainerSlot } from "#app/data/trainer-config";
import { Phase } from "#app/phase";
export class BattlePhase extends Phase {
constructor(scene: BattleScene) {
super(scene);
constructor() {
super();
}
showEnemyTrainer(trainerSlot: TrainerSlot = TrainerSlot.NONE): void {
const sprites = this.scene.currentBattle.trainer?.getSprites()!; // TODO: is this bang correct?
const tintSprites = this.scene.currentBattle.trainer?.getTintSprites()!; // TODO: is this bang correct?
const sprites = gScene.currentBattle.trainer?.getSprites()!; // TODO: is this bang correct?
const tintSprites = gScene.currentBattle.trainer?.getTintSprites()!; // TODO: is this bang correct?
for (let i = 0; i < sprites.length; i++) {
const visible = !trainerSlot || !i === (trainerSlot === TrainerSlot.TRAINER) || sprites.length < 2;
[ sprites[i], tintSprites[i] ].map(sprite => {
@ -24,8 +24,8 @@ export class BattlePhase extends Phase {
sprites[i].clearTint();
tintSprites[i].clearTint();
}
this.scene.tweens.add({
targets: this.scene.currentBattle.trainer,
gScene.tweens.add({
targets: gScene.currentBattle.trainer,
x: "-=16",
y: "+=16",
alpha: 1,
@ -35,8 +35,8 @@ export class BattlePhase extends Phase {
}
hideEnemyTrainer(): void {
this.scene.tweens.add({
targets: this.scene.currentBattle.trainer,
gScene.tweens.add({
targets: gScene.currentBattle.trainer,
x: "+=16",
y: "-=16",
alpha: 0,

View File

@ -7,6 +7,7 @@ import i18next from "i18next";
import * as Utils from "#app/utils";
import { FieldPhase } from "./field-phase";
import { CommonAnimPhase } from "./common-anim-phase";
import { gScene } from "#app/battle-scene";
/** The phase after attacks where the pokemon eat berries */
export class BerryPhase extends FieldPhase {
@ -14,7 +15,7 @@ export class BerryPhase extends FieldPhase {
super.start();
this.executeForAll((pokemon) => {
const hasUsableBerry = !!this.scene.findModifier((m) => {
const hasUsableBerry = !!gScene.findModifier((m) => {
return m instanceof BerryModifier && m.shouldApply(pokemon);
}, pokemon.isPlayer());
@ -23,24 +24,24 @@ export class BerryPhase extends FieldPhase {
pokemon.getOpponents().map((opp) => applyAbAttrs(PreventBerryUseAbAttr, opp, cancelled));
if (cancelled.value) {
pokemon.scene.queueMessage(i18next.t("abilityTriggers:preventBerryUse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
gScene.queueMessage(i18next.t("abilityTriggers:preventBerryUse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }));
} else {
this.scene.unshiftPhase(
new CommonAnimPhase(this.scene, pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.USE_ITEM)
gScene.unshiftPhase(
new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.USE_ITEM)
);
for (const berryModifier of this.scene.applyModifiers(BerryModifier, pokemon.isPlayer(), pokemon)) {
for (const berryModifier of gScene.applyModifiers(BerryModifier, pokemon.isPlayer(), pokemon)) {
if (berryModifier.consumed) {
if (!--berryModifier.stackCount) {
this.scene.removeModifier(berryModifier);
gScene.removeModifier(berryModifier);
} else {
berryModifier.consumed = false;
}
}
this.scene.eventTarget.dispatchEvent(new BerryUsedEvent(berryModifier)); // Announce a berry was used
gScene.eventTarget.dispatchEvent(new BerryUsedEvent(berryModifier)); // Announce a berry was used
}
this.scene.updateModifiers(pokemon.isPlayer());
gScene.updateModifiers(pokemon.isPlayer());
applyAbAttrs(HealFromBerryUseAbAttr, pokemon, new Utils.BooleanHolder(false));
}

View File

@ -1,21 +1,20 @@
import { PostTurnStatusEffectPhase } from "#app/phases/post-turn-status-effect-phase";
import { Phase } from "#app/phase";
import { BattlerIndex } from "#app/battle";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
export class CheckStatusEffectPhase extends Phase {
private order : BattlerIndex[];
constructor(scene : BattleScene, order : BattlerIndex[]) {
super(scene);
this.scene = scene;
constructor(order : BattlerIndex[]) {
super();
this.order = order;
}
start() {
const field = this.scene.getField();
const field = gScene.getField();
for (const o of this.order) {
if (field[o].status && field[o].status.isPostTurn()) {
this.scene.unshiftPhase(new PostTurnStatusEffectPhase(this.scene, o));
gScene.unshiftPhase(new PostTurnStatusEffectPhase(o));
}
}
this.end();

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { BattleStyle } from "#app/enums/battle-style";
import { BattlerTagType } from "#app/enums/battler-tag-type";
import { getPokemonNameWithAffix } from "#app/messages";
@ -14,8 +14,8 @@ export class CheckSwitchPhase extends BattlePhase {
protected fieldIndex: integer;
protected useName: boolean;
constructor(scene: BattleScene, fieldIndex: integer, useName: boolean) {
super(scene);
constructor(fieldIndex: integer, useName: boolean) {
super();
this.fieldIndex = fieldIndex;
this.useName = useName;
@ -24,20 +24,20 @@ export class CheckSwitchPhase extends BattlePhase {
start() {
super.start();
const pokemon = this.scene.getPlayerField()[this.fieldIndex];
const pokemon = gScene.getPlayerField()[this.fieldIndex];
if (this.scene.battleStyle === BattleStyle.SET) {
if (gScene.battleStyle === BattleStyle.SET) {
super.end();
return;
}
if (this.scene.field.getAll().indexOf(pokemon) === -1) {
this.scene.unshiftPhase(new SummonMissingPhase(this.scene, this.fieldIndex));
if (gScene.field.getAll().indexOf(pokemon) === -1) {
gScene.unshiftPhase(new SummonMissingPhase(this.fieldIndex));
super.end();
return;
}
if (!this.scene.getParty().slice(1).filter(p => p.isActive()).length) {
if (!gScene.getParty().slice(1).filter(p => p.isActive()).length) {
super.end();
return;
}
@ -47,14 +47,14 @@ export class CheckSwitchPhase extends BattlePhase {
return;
}
this.scene.ui.showText(i18next.t("battle:switchQuestion", { pokemonName: this.useName ? getPokemonNameWithAffix(pokemon) : i18next.t("battle:pokemon") }), null, () => {
this.scene.ui.setMode(Mode.CONFIRM, () => {
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.tryRemovePhase(p => p instanceof PostSummonPhase && p.player && p.fieldIndex === this.fieldIndex);
this.scene.unshiftPhase(new SwitchPhase(this.scene, SwitchType.INITIAL_SWITCH, this.fieldIndex, false, true));
gScene.ui.showText(i18next.t("battle:switchQuestion", { pokemonName: this.useName ? getPokemonNameWithAffix(pokemon) : i18next.t("battle:pokemon") }), null, () => {
gScene.ui.setMode(Mode.CONFIRM, () => {
gScene.ui.setMode(Mode.MESSAGE);
gScene.tryRemovePhase(p => p instanceof PostSummonPhase && p.player && p.fieldIndex === this.fieldIndex);
gScene.unshiftPhase(new SwitchPhase(SwitchType.INITIAL_SWITCH, this.fieldIndex, false, true));
this.end();
}, () => {
this.scene.ui.setMode(Mode.MESSAGE);
gScene.ui.setMode(Mode.MESSAGE);
this.end();
});
});

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { TurnCommand, BattleType } from "#app/battle";
import { TrappedTag, EncoreTag } from "#app/data/battler-tags";
import { MoveTargetSet, getMoveTargets } from "#app/data/move";
@ -21,8 +21,8 @@ import { isNullOrUndefined } from "#app/utils";
export class CommandPhase extends FieldPhase {
protected fieldIndex: integer;
constructor(scene: BattleScene, fieldIndex: integer) {
super(scene);
constructor(fieldIndex: integer) {
super();
this.fieldIndex = fieldIndex;
}
@ -30,9 +30,9 @@ export class CommandPhase extends FieldPhase {
start() {
super.start();
const commandUiHandler = this.scene.ui.handlers[Mode.COMMAND];
const commandUiHandler = gScene.ui.handlers[Mode.COMMAND];
if (commandUiHandler) {
if (this.scene.currentBattle.turn === 1 || commandUiHandler.getCursor() === Command.POKEMON) {
if (gScene.currentBattle.turn === 1 || commandUiHandler.getCursor() === Command.POKEMON) {
commandUiHandler.setCursor(Command.FIGHT);
} else {
commandUiHandler.setCursor(commandUiHandler.getCursor());
@ -42,21 +42,21 @@ export class CommandPhase extends FieldPhase {
if (this.fieldIndex) {
// If we somehow are attempting to check the right pokemon but there's only one pokemon out
// Switch back to the center pokemon. This can happen rarely in double battles with mid turn switching
if (this.scene.getPlayerField().filter(p => p.isActive()).length === 1) {
if (gScene.getPlayerField().filter(p => p.isActive()).length === 1) {
this.fieldIndex = FieldPosition.CENTER;
} else {
const allyCommand = this.scene.currentBattle.turnCommands[this.fieldIndex - 1];
const allyCommand = gScene.currentBattle.turnCommands[this.fieldIndex - 1];
if (allyCommand?.command === Command.BALL || allyCommand?.command === Command.RUN) {
this.scene.currentBattle.turnCommands[this.fieldIndex] = { command: allyCommand?.command, skip: true };
gScene.currentBattle.turnCommands[this.fieldIndex] = { command: allyCommand?.command, skip: true };
}
}
}
if (this.scene.currentBattle.turnCommands[this.fieldIndex]?.skip) {
if (gScene.currentBattle.turnCommands[this.fieldIndex]?.skip) {
return this.end();
}
const playerPokemon = this.scene.getPlayerField()[this.fieldIndex];
const playerPokemon = gScene.getPlayerField()[this.fieldIndex];
const moveQueue = playerPokemon.getMoveQueue();
@ -75,21 +75,21 @@ export class CommandPhase extends FieldPhase {
if (moveIndex > -1 && playerPokemon.getMoveset()[moveIndex]!.isUsable(playerPokemon, queuedMove.ignorePP)) { // TODO: is the bang correct?
this.handleCommand(Command.FIGHT, moveIndex, queuedMove.ignorePP, { targets: queuedMove.targets, multiple: queuedMove.targets.length > 1 });
} else {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}
}
} else {
if (this.scene.currentBattle.isBattleMysteryEncounter() && this.scene.currentBattle.mysteryEncounter?.skipToFightInput) {
this.scene.ui.clearText();
this.scene.ui.setMode(Mode.FIGHT, this.fieldIndex);
if (gScene.currentBattle.isBattleMysteryEncounter() && gScene.currentBattle.mysteryEncounter?.skipToFightInput) {
gScene.ui.clearText();
gScene.ui.setMode(Mode.FIGHT, this.fieldIndex);
} else {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}
}
}
handleCommand(command: Command, cursor: integer, ...args: any[]): boolean {
const playerPokemon = this.scene.getPlayerField()[this.fieldIndex];
const playerPokemon = gScene.getPlayerField()[this.fieldIndex];
let success: boolean;
switch (command) {
@ -106,20 +106,20 @@ export class CommandPhase extends FieldPhase {
}
console.log(moveTargets, getPokemonNameWithAffix(playerPokemon));
if (moveTargets.targets.length > 1 && moveTargets.multiple) {
this.scene.unshiftPhase(new SelectTargetPhase(this.scene, this.fieldIndex));
gScene.unshiftPhase(new SelectTargetPhase(this.fieldIndex));
}
if (moveTargets.targets.length <= 1 || moveTargets.multiple) {
turnCommand.move!.targets = moveTargets.targets; //TODO: is the bang correct here?
} else if (playerPokemon.getTag(BattlerTagType.CHARGING) && playerPokemon.getMoveQueue().length >= 1) {
turnCommand.move!.targets = playerPokemon.getMoveQueue()[0].targets; //TODO: is the bang correct here?
} else {
this.scene.unshiftPhase(new SelectTargetPhase(this.scene, this.fieldIndex));
gScene.unshiftPhase(new SelectTargetPhase(this.fieldIndex));
}
this.scene.currentBattle.turnCommands[this.fieldIndex] = turnCommand;
gScene.currentBattle.turnCommands[this.fieldIndex] = turnCommand;
success = true;
} else if (cursor < playerPokemon.getMoveset().length) {
const move = playerPokemon.getMoveset()[cursor]!; //TODO: is this bang correct?
this.scene.ui.setMode(Mode.MESSAGE);
gScene.ui.setMode(Mode.MESSAGE);
// Decides between a Disabled, Not Implemented, or No PP translation message
const errorMessage =
@ -128,58 +128,58 @@ export class CommandPhase extends FieldPhase {
: move.getName().endsWith(" (N)") ? "battle:moveNotImplemented" : "battle:moveNoPP";
const moveName = move.getName().replace(" (N)", ""); // Trims off the indicator
this.scene.ui.showText(i18next.t(errorMessage, { moveName: moveName }), null, () => {
this.scene.ui.clearText();
this.scene.ui.setMode(Mode.FIGHT, this.fieldIndex);
gScene.ui.showText(i18next.t(errorMessage, { moveName: moveName }), null, () => {
gScene.ui.clearText();
gScene.ui.setMode(Mode.FIGHT, this.fieldIndex);
}, null, true);
}
break;
case Command.BALL:
const notInDex = (this.scene.getEnemyField().filter(p => p.isActive(true)).some(p => !p.scene.gameData.dexData[p.species.speciesId].caughtAttr) && this.scene.gameData.getStarterCount(d => !!d.caughtAttr) < Object.keys(speciesStarterCosts).length - 1);
if (this.scene.arena.biomeType === Biome.END && (!this.scene.gameMode.isClassic || this.scene.gameMode.isFreshStartChallenge() || notInDex )) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.ui.showText(i18next.t("battle:noPokeballForce"), null, () => {
this.scene.ui.showText("", 0);
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
const notInDex = (gScene.getEnemyField().filter(p => p.isActive(true)).some(p => !gScene.gameData.dexData[p.species.speciesId].caughtAttr) && gScene.gameData.getStarterCount(d => !!d.caughtAttr) < Object.keys(speciesStarterCosts).length - 1);
if (gScene.arena.biomeType === Biome.END && (!gScene.gameMode.isClassic || gScene.gameMode.isFreshStartChallenge() || notInDex )) {
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.MESSAGE);
gScene.ui.showText(i18next.t("battle:noPokeballForce"), null, () => {
gScene.ui.showText("", 0);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}, null, true);
} else if (this.scene.currentBattle.battleType === BattleType.TRAINER) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.ui.showText(i18next.t("battle:noPokeballTrainer"), null, () => {
this.scene.ui.showText("", 0);
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
} else if (gScene.currentBattle.battleType === BattleType.TRAINER) {
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.MESSAGE);
gScene.ui.showText(i18next.t("battle:noPokeballTrainer"), null, () => {
gScene.ui.showText("", 0);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}, null, true);
} else if (this.scene.currentBattle.isBattleMysteryEncounter() && !this.scene.currentBattle.mysteryEncounter!.catchAllowed) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.ui.showText(i18next.t("battle:noPokeballMysteryEncounter"), null, () => {
this.scene.ui.showText("", 0);
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
} else if (gScene.currentBattle.isBattleMysteryEncounter() && !gScene.currentBattle.mysteryEncounter!.catchAllowed) {
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.MESSAGE);
gScene.ui.showText(i18next.t("battle:noPokeballMysteryEncounter"), null, () => {
gScene.ui.showText("", 0);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}, null, true);
} else {
const targets = this.scene.getEnemyField().filter(p => p.isActive(true)).map(p => p.getBattlerIndex());
const targets = gScene.getEnemyField().filter(p => p.isActive(true)).map(p => p.getBattlerIndex());
if (targets.length > 1) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.ui.showText(i18next.t("battle:noPokeballMulti"), null, () => {
this.scene.ui.showText("", 0);
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.MESSAGE);
gScene.ui.showText(i18next.t("battle:noPokeballMulti"), null, () => {
gScene.ui.showText("", 0);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}, null, true);
} else if (cursor < 5) {
const targetPokemon = this.scene.getEnemyField().find(p => p.isActive(true));
const targetPokemon = gScene.getEnemyField().find(p => p.isActive(true));
if (targetPokemon?.isBoss() && targetPokemon?.bossSegmentIndex >= 1 && !targetPokemon?.hasAbility(Abilities.WONDER_GUARD, false, true) && cursor < PokeballType.MASTER_BALL) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.ui.showText(i18next.t("battle:noPokeballStrong"), null, () => {
this.scene.ui.showText("", 0);
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.MESSAGE);
gScene.ui.showText(i18next.t("battle:noPokeballStrong"), null, () => {
gScene.ui.showText("", 0);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}, null, true);
} else {
this.scene.currentBattle.turnCommands[this.fieldIndex] = { command: Command.BALL, cursor: cursor };
this.scene.currentBattle.turnCommands[this.fieldIndex]!.targets = targets;
gScene.currentBattle.turnCommands[this.fieldIndex] = { command: Command.BALL, cursor: cursor };
gScene.currentBattle.turnCommands[this.fieldIndex]!.targets = targets;
if (this.fieldIndex) {
this.scene.currentBattle.turnCommands[this.fieldIndex - 1]!.skip = true;
gScene.currentBattle.turnCommands[this.fieldIndex - 1]!.skip = true;
}
success = true;
}
@ -189,21 +189,21 @@ export class CommandPhase extends FieldPhase {
case Command.POKEMON:
case Command.RUN:
const isSwitch = command === Command.POKEMON;
const { currentBattle, arena } = this.scene;
const { currentBattle, arena } = gScene;
const mysteryEncounterFleeAllowed = currentBattle.mysteryEncounter?.fleeAllowed;
if (!isSwitch && (arena.biomeType === Biome.END || (!isNullOrUndefined(mysteryEncounterFleeAllowed) && !mysteryEncounterFleeAllowed))) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.ui.showText(i18next.t("battle:noEscapeForce"), null, () => {
this.scene.ui.showText("", 0);
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.MESSAGE);
gScene.ui.showText(i18next.t("battle:noEscapeForce"), null, () => {
gScene.ui.showText("", 0);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}, null, true);
} else if (!isSwitch && (currentBattle.battleType === BattleType.TRAINER || currentBattle.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE)) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.ui.showText(i18next.t("battle:noEscapeTrainer"), null, () => {
this.scene.ui.showText("", 0);
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.MESSAGE);
gScene.ui.showText(i18next.t("battle:noEscapeTrainer"), null, () => {
gScene.ui.showText("", 0);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}, null, true);
} else {
const batonPass = isSwitch && args[0] as boolean;
@ -218,12 +218,12 @@ export class CommandPhase extends FieldPhase {
}
} else if (trappedAbMessages.length > 0) {
if (!isSwitch) {
this.scene.ui.setMode(Mode.MESSAGE);
gScene.ui.setMode(Mode.MESSAGE);
}
this.scene.ui.showText(trappedAbMessages[0], null, () => {
this.scene.ui.showText("", 0);
gScene.ui.showText(trappedAbMessages[0], null, () => {
gScene.ui.showText("", 0);
if (!isSwitch) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}
}, null, true);
} else {
@ -238,20 +238,20 @@ export class CommandPhase extends FieldPhase {
}
if (!isSwitch) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
this.scene.ui.setMode(Mode.MESSAGE);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.MESSAGE);
}
this.scene.ui.showText(
gScene.ui.showText(
i18next.t("battle:noEscapePokemon", {
pokemonName: trapTag.sourceId && this.scene.getPokemonById(trapTag.sourceId) ? getPokemonNameWithAffix(this.scene.getPokemonById(trapTag.sourceId)!) : "",
pokemonName: trapTag.sourceId && gScene.getPokemonById(trapTag.sourceId) ? getPokemonNameWithAffix(gScene.getPokemonById(trapTag.sourceId)!) : "",
moveName: trapTag.getMoveName(),
escapeVerb: isSwitch ? i18next.t("battle:escapeVerbSwitch") : i18next.t("battle:escapeVerbFlee")
}),
null,
() => {
this.scene.ui.showText("", 0);
gScene.ui.showText("", 0);
if (!isSwitch) {
this.scene.ui.setMode(Mode.COMMAND, this.fieldIndex);
gScene.ui.setMode(Mode.COMMAND, this.fieldIndex);
}
}, null, true);
}
@ -268,8 +268,8 @@ export class CommandPhase extends FieldPhase {
cancel() {
if (this.fieldIndex) {
this.scene.unshiftPhase(new CommandPhase(this.scene, 0));
this.scene.unshiftPhase(new CommandPhase(this.scene, 1));
gScene.unshiftPhase(new CommandPhase(0));
gScene.unshiftPhase(new CommandPhase(1));
this.end();
}
}
@ -299,10 +299,10 @@ export class CommandPhase extends FieldPhase {
}
getPokemon(): PlayerPokemon {
return this.scene.getPlayerField()[this.fieldIndex];
return gScene.getPlayerField()[this.fieldIndex];
}
end() {
this.scene.ui.setMode(Mode.MESSAGE).then(() => super.end());
gScene.ui.setMode(Mode.MESSAGE).then(() => super.end());
}
}

View File

@ -1,5 +1,5 @@
import BattleScene from "#app/battle-scene";
import { BattlerIndex } from "#app/battle";
import { gScene } from "#app/battle-scene";
import { CommonAnim, CommonBattleAnim } from "#app/data/battle-anims";
import { PokemonPhase } from "./pokemon-phase";
@ -8,8 +8,8 @@ export class CommonAnimPhase extends PokemonPhase {
private targetIndex: integer | undefined;
private playOnEmptyField: boolean;
constructor(scene: BattleScene, battlerIndex?: BattlerIndex, targetIndex?: BattlerIndex | undefined, anim?: CommonAnim, playOnEmptyField: boolean = false) {
super(scene, battlerIndex);
constructor(battlerIndex?: BattlerIndex, targetIndex?: BattlerIndex, anim?: CommonAnim, playOnEmptyField: boolean = false) {
super(battlerIndex);
this.anim = anim!; // TODO: is this bang correct?
this.targetIndex = targetIndex;
@ -21,8 +21,8 @@ export class CommonAnimPhase extends PokemonPhase {
}
start() {
const target = this.targetIndex !== undefined ? (this.player ? this.scene.getEnemyField() : this.scene.getPlayerField())[this.targetIndex] : this.getPokemon();
new CommonBattleAnim(this.anim, this.getPokemon(), target).play(this.scene, false, () => {
const target = this.targetIndex !== undefined ? (this.player ? gScene.getEnemyField() : gScene.getPlayerField())[this.targetIndex] : this.getPokemon();
new CommonBattleAnim(this.anim, this.getPokemon(), target).play(false, () => {
this.end();
});
}

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { BattlerIndex } from "#app/battle";
import { BattleSpec } from "#app/enums/battle-spec";
import { DamageResult, HitResult } from "#app/field/pokemon";
@ -10,8 +10,8 @@ export class DamagePhase extends PokemonPhase {
private damageResult: DamageResult;
private critical: boolean;
constructor(scene: BattleScene, battlerIndex: BattlerIndex, amount: integer, damageResult?: DamageResult, critical: boolean = false) {
super(scene, battlerIndex);
constructor(battlerIndex: BattlerIndex, amount: integer, damageResult?: DamageResult, critical: boolean = false) {
super(battlerIndex);
this.amount = amount;
this.damageResult = damageResult || HitResult.EFFECTIVE;
@ -22,11 +22,11 @@ export class DamagePhase extends PokemonPhase {
super.start();
if (this.damageResult === HitResult.ONE_HIT_KO) {
if (this.scene.moveAnimations) {
this.scene.toggleInvert(true);
if (gScene.moveAnimations) {
gScene.toggleInvert(true);
}
this.scene.time.delayedCall(Utils.fixedInt(1000), () => {
this.scene.toggleInvert(false);
gScene.time.delayedCall(Utils.fixedInt(1000), () => {
gScene.toggleInvert(false);
this.applyDamage();
});
return;
@ -42,23 +42,23 @@ export class DamagePhase extends PokemonPhase {
applyDamage() {
switch (this.damageResult) {
case HitResult.EFFECTIVE:
this.scene.playSound("se/hit");
gScene.playSound("se/hit");
break;
case HitResult.SUPER_EFFECTIVE:
case HitResult.ONE_HIT_KO:
this.scene.playSound("se/hit_strong");
gScene.playSound("se/hit_strong");
break;
case HitResult.NOT_VERY_EFFECTIVE:
this.scene.playSound("se/hit_weak");
gScene.playSound("se/hit_weak");
break;
}
if (this.amount) {
this.scene.damageNumberHandler.add(this.getPokemon(), this.amount, this.damageResult, this.critical);
gScene.damageNumberHandler.add(this.getPokemon(), this.amount, this.damageResult, this.critical);
}
if (this.damageResult !== HitResult.OTHER && this.amount > 0) {
const flashTimer = this.scene.time.addEvent({
const flashTimer = gScene.time.addEvent({
delay: 100,
repeat: 5,
startAt: 200,
@ -75,8 +75,8 @@ export class DamagePhase extends PokemonPhase {
}
override end() {
if (this.scene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) {
this.scene.initFinalBossPhaseTwo(this.getPokemon());
if (gScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) {
gScene.initFinalBossPhaseTwo(this.getPokemon());
} else {
super.end();
}

View File

@ -1,4 +1,4 @@
import BattleScene, { AnySound } from "#app/battle-scene";
import { AnySound, gScene } from "#app/battle-scene";
import { Egg } from "#app/data/egg";
import { EggCountChangedEvent } from "#app/events/egg";
import { PlayerPokemon } from "#app/field/pokemon";
@ -66,8 +66,8 @@ export class EggHatchPhase extends Phase {
private evolutionBgm: AnySound;
private eggLapsePhase: EggLapsePhase;
constructor(scene: BattleScene, hatchScene: EggLapsePhase, egg: Egg, eggsToHatchCount: integer) {
super(scene);
constructor(hatchScene: EggLapsePhase, egg: Egg, eggsToHatchCount: integer) {
super();
this.eggLapsePhase = hatchScene;
this.egg = egg;
this.eggsToHatchCount = eggsToHatchCount;
@ -76,37 +76,37 @@ export class EggHatchPhase extends Phase {
start() {
super.start();
this.scene.ui.setModeForceTransition(Mode.EGG_HATCH_SCENE).then(() => {
gScene.ui.setModeForceTransition(Mode.EGG_HATCH_SCENE).then(() => {
if (!this.egg) {
return this.end();
}
const eggIndex = this.scene.gameData.eggs.findIndex(e => e.id === this.egg.id);
const eggIndex = gScene.gameData.eggs.findIndex(e => e.id === this.egg.id);
if (eggIndex === -1) {
return this.end();
}
this.scene.gameData.eggs.splice(eggIndex, 1);
gScene.gameData.eggs.splice(eggIndex, 1);
this.scene.fadeOutBgm(undefined, false);
gScene.fadeOutBgm(undefined, false);
this.eggHatchHandler = this.scene.ui.getHandler() as EggHatchSceneHandler;
this.eggHatchHandler = gScene.ui.getHandler() as EggHatchSceneHandler;
this.eggHatchContainer = this.eggHatchHandler.eggHatchContainer;
this.eggHatchBg = this.scene.add.image(0, 0, "default_bg");
this.eggHatchBg = gScene.add.image(0, 0, "default_bg");
this.eggHatchBg.setOrigin(0, 0);
this.eggHatchContainer.add(this.eggHatchBg);
this.eggContainer = this.scene.add.container(this.eggHatchBg.displayWidth / 2, this.eggHatchBg.displayHeight / 2);
this.eggContainer = gScene.add.container(this.eggHatchBg.displayWidth / 2, this.eggHatchBg.displayHeight / 2);
this.eggSprite = this.scene.add.sprite(0, 0, "egg", `egg_${this.egg.getKey()}`);
this.eggCrackSprite = this.scene.add.sprite(0, 0, "egg_crack", "0");
this.eggSprite = gScene.add.sprite(0, 0, "egg", `egg_${this.egg.getKey()}`);
this.eggCrackSprite = gScene.add.sprite(0, 0, "egg_crack", "0");
this.eggCrackSprite.setVisible(false);
this.eggLightraysOverlay = this.scene.add.sprite((-this.eggHatchBg.displayWidth / 2) + 4, -this.eggHatchBg.displayHeight / 2, "egg_lightrays", "3");
this.eggLightraysOverlay = gScene.add.sprite((-this.eggHatchBg.displayWidth / 2) + 4, -this.eggHatchBg.displayHeight / 2, "egg_lightrays", "3");
this.eggLightraysOverlay.setOrigin(0, 0);
this.eggLightraysOverlay.setVisible(false);
@ -115,28 +115,28 @@ export class EggHatchPhase extends Phase {
this.eggContainer.add(this.eggLightraysOverlay);
this.eggHatchContainer.add(this.eggContainer);
this.eggCounterContainer = new EggCounterContainer(this.scene, this.eggsToHatchCount);
this.eggCounterContainer = new EggCounterContainer(this.eggsToHatchCount);
this.eggHatchContainer.add(this.eggCounterContainer);
const getPokemonSprite = () => {
const ret = this.scene.add.sprite(this.eggHatchBg.displayWidth / 2, this.eggHatchBg.displayHeight / 2, "pkmn__sub");
ret.setPipeline(this.scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true });
const ret = gScene.add.sprite(this.eggHatchBg.displayWidth / 2, this.eggHatchBg.displayHeight / 2, "pkmn__sub");
ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true });
return ret;
};
this.eggHatchContainer.add((this.pokemonSprite = getPokemonSprite()));
this.pokemonShinySparkle = this.scene.add.sprite(this.pokemonSprite.x, this.pokemonSprite.y, "shiny");
this.pokemonShinySparkle = gScene.add.sprite(this.pokemonSprite.x, this.pokemonSprite.y, "shiny");
this.pokemonShinySparkle.setVisible(false);
this.eggHatchContainer.add(this.pokemonShinySparkle);
this.eggHatchOverlay = this.scene.add.rectangle(0, -this.scene.game.canvas.height / 6, this.scene.game.canvas.width / 6, this.scene.game.canvas.height / 6, 0xFFFFFF);
this.eggHatchOverlay = gScene.add.rectangle(0, -gScene.game.canvas.height / 6, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0xFFFFFF);
this.eggHatchOverlay.setOrigin(0, 0);
this.eggHatchOverlay.setAlpha(0);
this.scene.fieldUI.add(this.eggHatchOverlay);
gScene.fieldUI.add(this.eggHatchOverlay);
this.infoContainer = new PokemonInfoContainer(this.scene);
this.infoContainer = new PokemonInfoContainer();
this.infoContainer.setup();
this.eggHatchContainer.add(this.infoContainer);
@ -154,13 +154,13 @@ export class EggHatchPhase extends Phase {
pokemon.loadAssets().then(() => {
this.canSkip = true;
this.scene.time.delayedCall(1000, () => {
gScene.time.delayedCall(1000, () => {
if (!this.hatched) {
this.evolutionBgm = this.scene.playSoundWithoutBgm("evolution");
this.evolutionBgm = gScene.playSoundWithoutBgm("evolution");
}
});
this.scene.time.delayedCall(2000, () => {
gScene.time.delayedCall(2000, () => {
if (this.hatched) {
return;
}
@ -170,25 +170,25 @@ export class EggHatchPhase extends Phase {
if (this.hatched) {
return;
}
this.scene.time.delayedCall(1000, () => {
gScene.time.delayedCall(1000, () => {
if (this.hatched) {
return;
}
this.doSpray(2, this.eggSprite.displayHeight / -4);
this.eggCrackSprite.setFrame("1");
this.scene.time.delayedCall(125, () => this.eggCrackSprite.setFrame("2"));
gScene.time.delayedCall(125, () => this.eggCrackSprite.setFrame("2"));
this.doEggShake(4).then(() => {
if (this.hatched) {
return;
}
this.scene.time.delayedCall(1000, () => {
gScene.time.delayedCall(1000, () => {
if (this.hatched) {
return;
}
this.scene.playSound("se/egg_crack");
gScene.playSound("se/egg_crack");
this.doSpray(4);
this.eggCrackSprite.setFrame("3");
this.scene.time.delayedCall(125, () => this.eggCrackSprite.setFrame("4"));
gScene.time.delayedCall(125, () => this.eggCrackSprite.setFrame("4"));
this.doEggShake(8, 2).then(() => {
if (!this.hatched) {
this.doHatch();
@ -204,10 +204,10 @@ export class EggHatchPhase extends Phase {
}
end() {
if (this.scene.findPhase((p) => p instanceof EggHatchPhase)) {
if (gScene.findPhase((p) => p instanceof EggHatchPhase)) {
this.eggHatchHandler.clear();
} else {
this.scene.time.delayedCall(250, () => this.scene.setModifiersVisible(true));
gScene.time.delayedCall(250, () => gScene.setModifiersVisible(true));
}
super.end();
}
@ -227,14 +227,14 @@ export class EggHatchPhase extends Phase {
if (count === undefined) {
count = 0;
}
this.scene.playSound("se/pb_move");
this.scene.tweens.add({
gScene.playSound("se/pb_move");
gScene.tweens.add({
targets: this.eggContainer,
x: `-=${intensity / (count ? 1 : 2)}`,
ease: "Sine.easeInOut",
duration: 125,
onComplete: () => {
this.scene.tweens.add({
gScene.tweens.add({
targets: this.eggContainer,
x: `+=${intensity}`,
ease: "Sine.easeInOut",
@ -244,7 +244,7 @@ export class EggHatchPhase extends Phase {
if (count! < repeatCount!) { // we know they are defined
return this.doEggShake(intensity, repeatCount, count).then(() => resolve());
}
this.scene.tweens.add({
gScene.tweens.add({
targets: this.eggContainer,
x: `-=${intensity / 2}`,
ease: "Sine.easeInOut",
@ -285,14 +285,14 @@ export class EggHatchPhase extends Phase {
this.canSkip = false;
this.hatched = true;
if (this.evolutionBgm) {
SoundFade.fadeOut(this.scene, this.evolutionBgm, Utils.fixedInt(100));
SoundFade.fadeOut(this.evolutionBgm, Utils.fixedInt(100));
}
for (let e = 0; e < 5; e++) {
this.scene.time.delayedCall(Utils.fixedInt(375 * e), () => this.scene.playSound("se/egg_hatch", { volume: 1 - (e * 0.2) }));
gScene.time.delayedCall(Utils.fixedInt(375 * e), () => gScene.playSound("se/egg_hatch", { volume: 1 - (e * 0.2) }));
}
this.eggLightraysOverlay.setVisible(true);
this.eggLightraysOverlay.play("egg_lightrays");
this.scene.tweens.add({
gScene.tweens.add({
duration: Utils.fixedInt(125),
targets: this.eggHatchOverlay,
alpha: 1,
@ -302,7 +302,7 @@ export class EggHatchPhase extends Phase {
this.canSkip = true;
}
});
this.scene.time.delayedCall(Utils.fixedInt(1500), () => {
gScene.time.delayedCall(Utils.fixedInt(1500), () => {
this.canSkip = false;
if (!this.skipped) {
this.doReveal();
@ -317,16 +317,16 @@ export class EggHatchPhase extends Phase {
// set the previous dex data so info container can show new unlocks in egg summary
const isShiny = this.pokemon.isShiny();
if (this.pokemon.species.subLegendary) {
this.scene.validateAchv(achvs.HATCH_SUB_LEGENDARY);
gScene.validateAchv(achvs.HATCH_SUB_LEGENDARY);
}
if (this.pokemon.species.legendary) {
this.scene.validateAchv(achvs.HATCH_LEGENDARY);
gScene.validateAchv(achvs.HATCH_LEGENDARY);
}
if (this.pokemon.species.mythical) {
this.scene.validateAchv(achvs.HATCH_MYTHICAL);
gScene.validateAchv(achvs.HATCH_MYTHICAL);
}
if (isShiny) {
this.scene.validateAchv(achvs.HATCH_SHINY);
gScene.validateAchv(achvs.HATCH_SHINY);
}
this.eggContainer.setVisible(false);
this.pokemonSprite.play(this.pokemon.getSpriteKey(true));
@ -335,34 +335,34 @@ export class EggHatchPhase extends Phase {
this.pokemonSprite.setPipelineData("shiny", this.pokemon.shiny);
this.pokemonSprite.setPipelineData("variant", this.pokemon.variant);
this.pokemonSprite.setVisible(true);
this.scene.time.delayedCall(Utils.fixedInt(250), () => {
gScene.time.delayedCall(Utils.fixedInt(250), () => {
this.eggsToHatchCount--;
this.eggHatchHandler.eventTarget.dispatchEvent(new EggCountChangedEvent(this.eggsToHatchCount));
this.pokemon.cry();
if (isShiny) {
this.scene.time.delayedCall(Utils.fixedInt(500), () => {
gScene.time.delayedCall(Utils.fixedInt(500), () => {
this.pokemonShinySparkle.play(`sparkle${this.pokemon.variant ? `_${this.pokemon.variant + 1}` : ""}`);
this.scene.playSound("se/sparkle");
gScene.playSound("se/sparkle");
});
}
this.scene.time.delayedCall(Utils.fixedInt(!this.skipped ? !isShiny ? 1250 : 1750 : !isShiny ? 250 : 750), () => {
gScene.time.delayedCall(Utils.fixedInt(!this.skipped ? !isShiny ? 1250 : 1750 : !isShiny ? 250 : 750), () => {
this.infoContainer.show(this.pokemon, false, this.skipped ? 2 : 1);
this.scene.playSoundWithoutBgm("evolution_fanfare");
gScene.playSoundWithoutBgm("evolution_fanfare");
this.scene.ui.showText(i18next.t("egg:hatchFromTheEgg", { pokemonName: getPokemonNameWithAffix(this.pokemon) }), null, () => {
this.scene.gameData.updateSpeciesDexIvs(this.pokemon.species.speciesId, this.pokemon.ivs);
this.scene.gameData.setPokemonCaught(this.pokemon, true, true).then(() => {
this.scene.gameData.setEggMoveUnlocked(this.pokemon.species, this.eggMoveIndex).then((value) => {
gScene.ui.showText(i18next.t("egg:hatchFromTheEgg", { pokemonName: getPokemonNameWithAffix(this.pokemon) }), null, () => {
gScene.gameData.updateSpeciesDexIvs(this.pokemon.species.speciesId, this.pokemon.ivs);
gScene.gameData.setPokemonCaught(this.pokemon, true, true).then(() => {
gScene.gameData.setEggMoveUnlocked(this.pokemon.species, this.eggMoveIndex).then((value) => {
this.eggHatchData.setEggMoveUnlocked(value);
this.scene.ui.showText("", 0);
gScene.ui.showText("", 0);
this.end();
});
});
}, null, true, 3000);
});
});
this.scene.tweens.add({
gScene.tweens.add({
duration: Utils.fixedInt(this.skipped ? 500 : 3000),
targets: this.eggHatchOverlay,
alpha: 0,
@ -386,7 +386,7 @@ export class EggHatchPhase extends Phase {
* @param offsetY how much to offset the Y coordinates
*/
doSpray(intensity: integer, offsetY?: number) {
this.scene.tweens.addCounter({
gScene.tweens.addCounter({
repeat: intensity,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -404,7 +404,7 @@ export class EggHatchPhase extends Phase {
const initialX = this.eggHatchBg.displayWidth / 2;
const initialY = this.eggHatchBg.displayHeight / 2 + offsetY;
const shardKey = !this.egg.isManaphyEgg() ? this.egg.tier.toString() : "1";
const particle = this.scene.add.image(initialX, initialY, "egg_shard", `${shardKey}_${Math.floor(trigIndex / 2)}`);
const particle = gScene.add.image(initialX, initialY, "egg_shard", `${shardKey}_${Math.floor(trigIndex / 2)}`);
this.eggHatchContainer.add(particle);
let f = 0;
@ -412,7 +412,7 @@ export class EggHatchPhase extends Phase {
const speed = 3 - Utils.randInt(8);
const amp = 24 + Utils.randInt(32);
const particleTimer = this.scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
onRepeat: () => {

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { Egg, EGG_SEED } from "#app/data/egg";
import { Phase } from "#app/phase";
import i18next from "i18next";
@ -18,24 +18,24 @@ export class EggLapsePhase extends Phase {
private eggHatchData: EggHatchData[] = [];
private readonly minEggsToSkip: number = 2;
constructor(scene: BattleScene) {
super(scene);
constructor() {
super();
}
start() {
super.start();
const eggsToHatch: Egg[] = this.scene.gameData.eggs.filter((egg: Egg) => {
const eggsToHatch: Egg[] = gScene.gameData.eggs.filter((egg: Egg) => {
return Overrides.EGG_IMMEDIATE_HATCH_OVERRIDE ? true : --egg.hatchWaves < 1;
});
const eggsToHatchCount: number = eggsToHatch.length;
this.eggHatchData = [];
if (eggsToHatchCount > 0) {
if (eggsToHatchCount >= this.minEggsToSkip && this.scene.eggSkipPreference === 1) {
this.scene.ui.showText(i18next.t("battle:eggHatching"), 0, () => {
if (eggsToHatchCount >= this.minEggsToSkip && gScene.eggSkipPreference === 1) {
gScene.ui.showText(i18next.t("battle:eggHatching"), 0, () => {
// show prompt for skip, blocking inputs for 1 second
this.scene.ui.showText(i18next.t("battle:eggSkipPrompt"), 0);
this.scene.ui.setModeWithoutClear(Mode.CONFIRM, () => {
gScene.ui.showText(i18next.t("battle:eggSkipPrompt"), 0);
gScene.ui.setModeWithoutClear(Mode.CONFIRM, () => {
this.hatchEggsSkipped(eggsToHatch);
this.showSummary();
}, () => {
@ -45,13 +45,13 @@ export class EggLapsePhase extends Phase {
null, null, null, 1000, true
);
}, 100, true);
} else if (eggsToHatchCount >= this.minEggsToSkip && this.scene.eggSkipPreference === 2) {
this.scene.queueMessage(i18next.t("battle:eggHatching"));
} else if (eggsToHatchCount >= this.minEggsToSkip && gScene.eggSkipPreference === 2) {
gScene.queueMessage(i18next.t("battle:eggHatching"));
this.hatchEggsSkipped(eggsToHatch);
this.showSummary();
} else {
// regular hatches, no summary
this.scene.queueMessage(i18next.t("battle:eggHatching"));
gScene.queueMessage(i18next.t("battle:eggHatching"));
this.hatchEggsRegular(eggsToHatch);
this.end();
}
@ -67,7 +67,7 @@ export class EggLapsePhase extends Phase {
hatchEggsRegular(eggsToHatch: Egg[]) {
let eggsToHatchCount: number = eggsToHatch.length;
for (const egg of eggsToHatch) {
this.scene.unshiftPhase(new EggHatchPhase(this.scene, this, egg, eggsToHatchCount));
gScene.unshiftPhase(new EggHatchPhase(this, egg, eggsToHatchCount));
eggsToHatchCount--;
}
}
@ -83,7 +83,7 @@ export class EggLapsePhase extends Phase {
}
showSummary() {
this.scene.unshiftPhase(new EggSummaryPhase(this.scene, this.eggHatchData));
gScene.unshiftPhase(new EggSummaryPhase(this.eggHatchData));
this.end();
}
@ -93,11 +93,11 @@ export class EggLapsePhase extends Phase {
* @param egg egg to hatch
*/
hatchEggSilently(egg: Egg) {
const eggIndex = this.scene.gameData.eggs.findIndex(e => e.id === egg.id);
const eggIndex = gScene.gameData.eggs.findIndex(e => e.id === egg.id);
if (eggIndex === -1) {
return this.end();
}
this.scene.gameData.eggs.splice(eggIndex, 1);
gScene.gameData.eggs.splice(eggIndex, 1);
const data = this.generatePokemon(egg);
const pokemon = data.pokemon;
@ -106,16 +106,16 @@ export class EggLapsePhase extends Phase {
}
if (pokemon.species.subLegendary) {
this.scene.validateAchv(achvs.HATCH_SUB_LEGENDARY);
gScene.validateAchv(achvs.HATCH_SUB_LEGENDARY);
}
if (pokemon.species.legendary) {
this.scene.validateAchv(achvs.HATCH_LEGENDARY);
gScene.validateAchv(achvs.HATCH_LEGENDARY);
}
if (pokemon.species.mythical) {
this.scene.validateAchv(achvs.HATCH_MYTHICAL);
gScene.validateAchv(achvs.HATCH_MYTHICAL);
}
if (pokemon.isShiny()) {
this.scene.validateAchv(achvs.HATCH_SHINY);
gScene.validateAchv(achvs.HATCH_SHINY);
}
}
@ -128,9 +128,9 @@ export class EggLapsePhase extends Phase {
generatePokemon(egg: Egg): EggHatchData {
let ret: PlayerPokemon;
let newHatchData: EggHatchData;
this.scene.executeWithSeedOffset(() => {
ret = egg.generatePlayerPokemon(this.scene);
newHatchData = new EggHatchData(this.scene, ret, egg.eggMoveIndex);
gScene.executeWithSeedOffset(() => {
ret = egg.generatePlayerPokemon();
newHatchData = new EggHatchData(ret, egg.eggMoveIndex);
newHatchData.setDex();
this.eggHatchData.push(newHatchData);

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { Phase } from "#app/phase";
import { Mode } from "#app/ui/ui";
import { EggHatchData } from "#app/data/egg-hatch-data";
@ -11,8 +11,8 @@ import { EggHatchData } from "#app/data/egg-hatch-data";
export class EggSummaryPhase extends Phase {
private eggHatchData: EggHatchData[];
constructor(scene: BattleScene, eggHatchData: EggHatchData[]) {
super(scene);
constructor(eggHatchData: EggHatchData[]) {
super();
this.eggHatchData = eggHatchData;
}
@ -22,8 +22,8 @@ export class EggSummaryPhase extends Phase {
// updates next pokemon once the current update has been completed
const updateNextPokemon = (i: number) => {
if (i >= this.eggHatchData.length) {
this.scene.ui.setModeForceTransition(Mode.EGG_HATCH_SUMMARY, this.eggHatchData).then(() => {
this.scene.fadeOutBgm(undefined, false);
gScene.ui.setModeForceTransition(Mode.EGG_HATCH_SUMMARY, this.eggHatchData).then(() => {
gScene.fadeOutBgm(undefined, false);
});
} else {
@ -40,8 +40,8 @@ export class EggSummaryPhase extends Phase {
}
end() {
this.scene.time.delayedCall(250, () => this.scene.setModifiersVisible(true));
this.scene.ui.setModeForceTransition(Mode.MESSAGE).then(() => {
gScene.time.delayedCall(250, () => gScene.setModifiersVisible(true));
gScene.ui.setModeForceTransition(Mode.MESSAGE).then(() => {
super.end();
});
}

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { BattlerIndex, BattleType } from "#app/battle";
import { applyAbAttrs, SyncEncounterNatureAbAttr } from "#app/data/ability";
import { getCharVariantFromDialogue } from "#app/data/dialogue";
@ -40,8 +40,8 @@ import { WEIGHT_INCREMENT_ON_SPAWN_MISS } from "#app/data/mystery-encounters/mys
export class EncounterPhase extends BattlePhase {
private loaded: boolean;
constructor(scene: BattleScene, loaded?: boolean) {
super(scene);
constructor(loaded?: boolean) {
super();
this.loaded = !!loaded;
}
@ -49,26 +49,26 @@ export class EncounterPhase extends BattlePhase {
start() {
super.start();
this.scene.updateGameInfo();
gScene.updateGameInfo();
this.scene.initSession();
gScene.initSession();
this.scene.eventTarget.dispatchEvent(new EncounterPhaseEvent());
gScene.eventTarget.dispatchEvent(new EncounterPhaseEvent());
// Failsafe if players somehow skip floor 200 in classic mode
if (this.scene.gameMode.isClassic && this.scene.currentBattle.waveIndex > 200) {
this.scene.unshiftPhase(new GameOverPhase(this.scene));
if (gScene.gameMode.isClassic && gScene.currentBattle.waveIndex > 200) {
gScene.unshiftPhase(new GameOverPhase());
}
const loadEnemyAssets: Promise<void>[] = [];
const battle = this.scene.currentBattle;
const battle = gScene.currentBattle;
// Generate and Init Mystery Encounter
if (battle.isBattleMysteryEncounter() && !battle.mysteryEncounter) {
this.scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
const currentSessionEncounterType = battle.mysteryEncounterType;
battle.mysteryEncounter = this.scene.getMysteryEncounter(currentSessionEncounterType);
battle.mysteryEncounter = gScene.getMysteryEncounter(currentSessionEncounterType);
}, battle.waveIndex * 16);
}
const mysteryEncounter = battle.mysteryEncounter;
@ -76,21 +76,21 @@ export class EncounterPhase extends BattlePhase {
// If ME has an onInit() function, call it
// Usually used for calculating rand data before initializing anything visual
// Also prepopulates any dialogue tokens from encounter/option requirements
this.scene.executeWithSeedOffset(() => {
gScene.executeWithSeedOffset(() => {
if (mysteryEncounter.onInit) {
mysteryEncounter.onInit(this.scene);
mysteryEncounter.onInit();
}
mysteryEncounter.populateDialogueTokensFromRequirements(this.scene);
mysteryEncounter.populateDialogueTokensFromRequirements();
}, battle.waveIndex);
// Add any special encounter animations to load
if (mysteryEncounter.encounterAnimations && mysteryEncounter.encounterAnimations.length > 0) {
loadEnemyAssets.push(initEncounterAnims(this.scene, mysteryEncounter.encounterAnimations).then(() => loadEncounterAnimAssets(this.scene, true)));
loadEnemyAssets.push(initEncounterAnims(mysteryEncounter.encounterAnimations).then(() => loadEncounterAnimAssets(true)));
}
// Add intro visuals for mystery encounter
mysteryEncounter.initIntroVisuals(this.scene);
this.scene.field.add(mysteryEncounter.introVisuals!);
mysteryEncounter.initIntroVisuals();
gScene.field.add(mysteryEncounter.introVisuals!);
}
let totalBst = 0;
@ -104,35 +104,35 @@ export class EncounterPhase extends BattlePhase {
if (battle.battleType === BattleType.TRAINER) {
battle.enemyParty[e] = battle.trainer?.genPartyMember(e)!; // TODO:: is the bang correct here?
} else {
let enemySpecies = this.scene.randomSpecies(battle.waveIndex, level, true);
let enemySpecies = gScene.randomSpecies(battle.waveIndex, level, true);
// If player has golden bug net, rolls 10% chance to replace non-boss wave wild species from the golden bug net bug pool
if (this.scene.findModifier(m => m instanceof BoostBugSpawnModifier)
&& !this.scene.gameMode.isBoss(battle.waveIndex)
&& this.scene.arena.biomeType !== Biome.END
if (gScene.findModifier(m => m instanceof BoostBugSpawnModifier)
&& !gScene.gameMode.isBoss(battle.waveIndex)
&& gScene.arena.biomeType !== Biome.END
&& randSeedInt(10) === 0) {
enemySpecies = getGoldenBugNetSpecies(level);
}
battle.enemyParty[e] = this.scene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, !!this.scene.getEncounterBossSegments(battle.waveIndex, level, enemySpecies));
if (this.scene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) {
battle.enemyParty[e] = gScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, !!gScene.getEncounterBossSegments(battle.waveIndex, level, enemySpecies));
if (gScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) {
battle.enemyParty[e].ivs = new Array(6).fill(31);
}
this.scene.getParty().slice(0, !battle.double ? 1 : 2).reverse().forEach(playerPokemon => {
gScene.getParty().slice(0, !battle.double ? 1 : 2).reverse().forEach(playerPokemon => {
applyAbAttrs(SyncEncounterNatureAbAttr, playerPokemon, null, false, battle.enemyParty[e]);
});
}
}
const enemyPokemon = this.scene.getEnemyParty()[e];
const enemyPokemon = gScene.getEnemyParty()[e];
if (e < (battle.double ? 2 : 1)) {
enemyPokemon.setX(-66 + enemyPokemon.getFieldPositionOffset()[0]);
enemyPokemon.resetSummonData();
}
if (!this.loaded) {
this.scene.gameData.setPokemonSeen(enemyPokemon, true, battle.battleType === BattleType.TRAINER || battle?.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE);
gScene.gameData.setPokemonSeen(enemyPokemon, true, battle.battleType === BattleType.TRAINER || battle?.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE);
}
if (enemyPokemon.species.speciesId === Species.ETERNATUS) {
if (this.scene.gameMode.isClassic && (battle.battleSpec === BattleSpec.FINAL_BOSS || this.scene.gameMode.isWaveFinal(battle.waveIndex))) {
if (gScene.gameMode.isClassic && (battle.battleSpec === BattleSpec.FINAL_BOSS || gScene.gameMode.isWaveFinal(battle.waveIndex))) {
if (battle.battleSpec !== BattleSpec.FINAL_BOSS) {
enemyPokemon.formIndex = 1;
enemyPokemon.updateScale();
@ -141,10 +141,10 @@ export class EncounterPhase extends BattlePhase {
} else if (!(battle.waveIndex % 1000)) {
enemyPokemon.formIndex = 1;
enemyPokemon.updateScale();
const bossMBH = this.scene.findModifier(m => m instanceof TurnHeldItemTransferModifier && m.pokemonId === enemyPokemon.id, false) as TurnHeldItemTransferModifier;
this.scene.removeModifier(bossMBH!);
const bossMBH = gScene.findModifier(m => m instanceof TurnHeldItemTransferModifier && m.pokemonId === enemyPokemon.id, false) as TurnHeldItemTransferModifier;
gScene.removeModifier(bossMBH!);
bossMBH?.setTransferrableFalse();
this.scene.addEnemyModifier(bossMBH!);
gScene.addEnemyModifier(bossMBH!);
}
}
@ -156,8 +156,8 @@ export class EncounterPhase extends BattlePhase {
return true;
});
if (this.scene.getParty().filter(p => p.isShiny()).length === 6) {
this.scene.validateAchv(achvs.SHINY_PARTY);
if (gScene.getParty().filter(p => p.isShiny()).length === 6) {
gScene.validateAchv(achvs.SHINY_PARTY);
}
if (battle.battleType === BattleType.TRAINER) {
@ -171,11 +171,11 @@ export class EncounterPhase extends BattlePhase {
}
// Load Mystery Encounter Exclamation bubble and sfx
loadEnemyAssets.push(new Promise<void>(resolve => {
this.scene.loadSe("GEN8- Exclaim", "battle_anims", "GEN8- Exclaim.wav");
this.scene.loadImage("encounter_exclaim", "mystery-encounters");
this.scene.load.once(Phaser.Loader.Events.COMPLETE, () => resolve());
if (!this.scene.load.isLoading()) {
this.scene.load.start();
gScene.loadSe("GEN8- Exclaim", "battle_anims", "GEN8- Exclaim.wav");
gScene.loadImage("encounter_exclaim", "mystery-encounters");
gScene.load.once(Phaser.Loader.Events.COMPLETE, () => resolve());
if (!gScene.load.isLoading()) {
gScene.load.start();
}
}));
} else {
@ -199,16 +199,16 @@ export class EncounterPhase extends BattlePhase {
}
if (e < (battle.double ? 2 : 1)) {
if (battle.battleType === BattleType.WILD) {
this.scene.field.add(enemyPokemon);
gScene.field.add(enemyPokemon);
battle.seenEnemyPartyMemberIds.add(enemyPokemon.id);
const playerPokemon = this.scene.getPlayerPokemon();
const playerPokemon = gScene.getPlayerPokemon();
if (playerPokemon?.visible) {
this.scene.field.moveBelow(enemyPokemon as Pokemon, playerPokemon);
gScene.field.moveBelow(enemyPokemon as Pokemon, playerPokemon);
}
enemyPokemon.tint(0, 0.5);
} else if (battle.battleType === BattleType.TRAINER) {
enemyPokemon.setVisible(false);
this.scene.currentBattle.trainer?.tint(0, 0.5);
gScene.currentBattle.trainer?.tint(0, 0.5);
}
if (battle.double) {
enemyPokemon.setFieldPosition(e ? FieldPosition.RIGHT : FieldPosition.LEFT);
@ -218,56 +218,56 @@ export class EncounterPhase extends BattlePhase {
});
if (!this.loaded && battle.battleType !== BattleType.MYSTERY_ENCOUNTER) {
regenerateModifierPoolThresholds(this.scene.getEnemyField(), battle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD);
this.scene.generateEnemyModifiers();
regenerateModifierPoolThresholds(gScene.getEnemyField(), battle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD);
gScene.generateEnemyModifiers();
}
this.scene.ui.setMode(Mode.MESSAGE).then(() => {
gScene.ui.setMode(Mode.MESSAGE).then(() => {
if (!this.loaded) {
this.trySetWeatherIfNewBiome(); // Set weather before session gets saved
this.scene.gameData.saveAll(this.scene, true, battle.waveIndex % 10 === 1 || (this.scene.lastSavePlayTime ?? 0) >= 300).then(success => {
this.scene.disableMenu = false;
gScene.gameData.saveAll(true, battle.waveIndex % 10 === 1 || (gScene.lastSavePlayTime ?? 0) >= 300).then(success => {
gScene.disableMenu = false;
if (!success) {
return this.scene.reset(true);
return gScene.reset(true);
}
this.doEncounter();
this.scene.resetSeed();
gScene.resetSeed();
});
} else {
this.doEncounter();
this.scene.resetSeed();
gScene.resetSeed();
}
});
});
}
doEncounter() {
this.scene.playBgm(undefined, true);
this.scene.updateModifiers(false);
this.scene.setFieldScale(1);
gScene.playBgm(undefined, true);
gScene.updateModifiers(false);
gScene.setFieldScale(1);
/*if (startingWave > 10) {
for (let m = 0; m < Math.min(Math.floor(startingWave / 10), 99); m++)
this.scene.addModifier(getPlayerModifierTypeOptionsForWave((m + 1) * 10, 1, this.scene.getParty())[0].type.newModifier(), true);
this.scene.updateModifiers(true);
gScene.addModifier(getPlayerModifierTypeOptionsForWave((m + 1) * 10, 1, gScene.getParty())[0].type.newModifier(), true);
gScene.updateModifiers(true);
}*/
const { battleType, waveIndex } = this.scene.currentBattle;
if (this.scene.isMysteryEncounterValidForWave(battleType, waveIndex) && !this.scene.currentBattle.isBattleMysteryEncounter()) {
const { battleType, waveIndex } = gScene.currentBattle;
if (gScene.isMysteryEncounterValidForWave(battleType, waveIndex) && !gScene.currentBattle.isBattleMysteryEncounter()) {
// Increment ME spawn chance if an ME could have spawned but did not
// Only do this AFTER session has been saved to avoid duplicating increments
this.scene.mysteryEncounterSaveData.encounterSpawnChance += WEIGHT_INCREMENT_ON_SPAWN_MISS;
gScene.mysteryEncounterSaveData.encounterSpawnChance += WEIGHT_INCREMENT_ON_SPAWN_MISS;
}
for (const pokemon of this.scene.getParty()) {
for (const pokemon of gScene.getParty()) {
if (pokemon) {
pokemon.resetBattleData();
}
}
const enemyField = this.scene.getEnemyField();
this.scene.tweens.add({
targets: [ this.scene.arenaEnemy, this.scene.currentBattle.trainer, enemyField, this.scene.arenaPlayer, this.scene.trainer ].flat(),
const enemyField = gScene.getEnemyField();
gScene.tweens.add({
targets: [ gScene.arenaEnemy, gScene.currentBattle.trainer, enemyField, gScene.arenaPlayer, gScene.trainer ].flat(),
x: (_target, _key, value, fieldIndex: integer) => fieldIndex < 2 + (enemyField.length) ? value + 300 : value - 300,
duration: 2000,
onComplete: () => {
@ -277,13 +277,13 @@ export class EncounterPhase extends BattlePhase {
}
});
const encounterIntroVisuals = this.scene.currentBattle?.mysteryEncounter?.introVisuals;
const encounterIntroVisuals = gScene.currentBattle?.mysteryEncounter?.introVisuals;
if (encounterIntroVisuals) {
const enterFromRight = encounterIntroVisuals.enterFromRight;
if (enterFromRight) {
encounterIntroVisuals.x += 500;
}
this.scene.tweens.add({
gScene.tweens.add({
targets: encounterIntroVisuals,
x: enterFromRight ? "-=200" : "+=300",
duration: 2000
@ -292,18 +292,18 @@ export class EncounterPhase extends BattlePhase {
}
getEncounterMessage(): string {
const enemyField = this.scene.getEnemyField();
const enemyField = gScene.getEnemyField();
if (this.scene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) {
if (gScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) {
return i18next.t("battle:bossAppeared", { bossName: getPokemonNameWithAffix(enemyField[0]) });
}
if (this.scene.currentBattle.battleType === BattleType.TRAINER) {
if (this.scene.currentBattle.double) {
return i18next.t("battle:trainerAppearedDouble", { trainerName: this.scene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) });
if (gScene.currentBattle.battleType === BattleType.TRAINER) {
if (gScene.currentBattle.double) {
return i18next.t("battle:trainerAppearedDouble", { trainerName: gScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) });
} else {
return i18next.t("battle:trainerAppeared", { trainerName: this.scene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) });
return i18next.t("battle:trainerAppeared", { trainerName: gScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) });
}
}
@ -313,83 +313,83 @@ export class EncounterPhase extends BattlePhase {
}
doEncounterCommon(showEncounterMessage: boolean = true) {
const enemyField = this.scene.getEnemyField();
const enemyField = gScene.getEnemyField();
if (this.scene.currentBattle.battleType === BattleType.WILD) {
if (gScene.currentBattle.battleType === BattleType.WILD) {
enemyField.forEach(enemyPokemon => {
enemyPokemon.untint(100, "Sine.easeOut");
enemyPokemon.cry();
enemyPokemon.showInfo();
if (enemyPokemon.isShiny()) {
this.scene.validateAchv(achvs.SEE_SHINY);
gScene.validateAchv(achvs.SEE_SHINY);
}
});
this.scene.updateFieldScale();
gScene.updateFieldScale();
if (showEncounterMessage) {
this.scene.ui.showText(this.getEncounterMessage(), null, () => this.end(), 1500);
gScene.ui.showText(this.getEncounterMessage(), null, () => this.end(), 1500);
} else {
this.end();
}
} else if (this.scene.currentBattle.battleType === BattleType.TRAINER) {
const trainer = this.scene.currentBattle.trainer;
} else if (gScene.currentBattle.battleType === BattleType.TRAINER) {
const trainer = gScene.currentBattle.trainer;
trainer?.untint(100, "Sine.easeOut");
trainer?.playAnim();
const doSummon = () => {
this.scene.currentBattle.started = true;
this.scene.playBgm(undefined);
this.scene.pbTray.showPbTray(this.scene.getParty());
this.scene.pbTrayEnemy.showPbTray(this.scene.getEnemyParty());
gScene.currentBattle.started = true;
gScene.playBgm(undefined);
gScene.pbTray.showPbTray(gScene.getParty());
gScene.pbTrayEnemy.showPbTray(gScene.getEnemyParty());
const doTrainerSummon = () => {
this.hideEnemyTrainer();
const availablePartyMembers = this.scene.getEnemyParty().filter(p => !p.isFainted()).length;
this.scene.unshiftPhase(new SummonPhase(this.scene, 0, false));
if (this.scene.currentBattle.double && availablePartyMembers > 1) {
this.scene.unshiftPhase(new SummonPhase(this.scene, 1, false));
const availablePartyMembers = gScene.getEnemyParty().filter(p => !p.isFainted()).length;
gScene.unshiftPhase(new SummonPhase(0, false));
if (gScene.currentBattle.double && availablePartyMembers > 1) {
gScene.unshiftPhase(new SummonPhase(1, false));
}
this.end();
};
if (showEncounterMessage) {
this.scene.ui.showText(this.getEncounterMessage(), null, doTrainerSummon, 1500, true);
gScene.ui.showText(this.getEncounterMessage(), null, doTrainerSummon, 1500, true);
} else {
doTrainerSummon();
}
};
const encounterMessages = this.scene.currentBattle.trainer?.getEncounterMessages();
const encounterMessages = gScene.currentBattle.trainer?.getEncounterMessages();
if (!encounterMessages?.length) {
doSummon();
} else {
let message: string;
this.scene.executeWithSeedOffset(() => message = Utils.randSeedItem(encounterMessages), this.scene.currentBattle.waveIndex);
gScene.executeWithSeedOffset(() => message = Utils.randSeedItem(encounterMessages), gScene.currentBattle.waveIndex);
message = message!; // tell TS compiler it's defined now
const showDialogueAndSummon = () => {
this.scene.ui.showDialogue(message, trainer?.getName(TrainerSlot.NONE, true), null, () => {
this.scene.charSprite.hide().then(() => this.scene.hideFieldOverlay(250).then(() => doSummon()));
gScene.ui.showDialogue(message, trainer?.getName(TrainerSlot.NONE, true), null, () => {
gScene.charSprite.hide().then(() => gScene.hideFieldOverlay(250).then(() => doSummon()));
});
};
if (this.scene.currentBattle.trainer?.config.hasCharSprite && !this.scene.ui.shouldSkipDialogue(message)) {
this.scene.showFieldOverlay(500).then(() => this.scene.charSprite.showCharacter(trainer?.getKey()!, getCharVariantFromDialogue(encounterMessages[0])).then(() => showDialogueAndSummon())); // TODO: is this bang correct?
if (gScene.currentBattle.trainer?.config.hasCharSprite && !gScene.ui.shouldSkipDialogue(message)) {
gScene.showFieldOverlay(500).then(() => gScene.charSprite.showCharacter(trainer?.getKey()!, getCharVariantFromDialogue(encounterMessages[0])).then(() => showDialogueAndSummon())); // TODO: is this bang correct?
} else {
showDialogueAndSummon();
}
}
} else if (this.scene.currentBattle.isBattleMysteryEncounter() && this.scene.currentBattle.mysteryEncounter) {
const encounter = this.scene.currentBattle.mysteryEncounter;
} else if (gScene.currentBattle.isBattleMysteryEncounter() && gScene.currentBattle.mysteryEncounter) {
const encounter = gScene.currentBattle.mysteryEncounter;
const introVisuals = encounter.introVisuals;
introVisuals?.playAnim();
if (encounter.onVisualsStart) {
encounter.onVisualsStart(this.scene);
encounter.onVisualsStart();
}
const doEncounter = () => {
const doShowEncounterOptions = () => {
this.scene.ui.clearText();
this.scene.ui.getMessageHandler().hideNameText();
gScene.ui.clearText();
gScene.ui.getMessageHandler().hideNameText();
this.scene.unshiftPhase(new MysteryEncounterPhase(this.scene));
gScene.unshiftPhase(new MysteryEncounterPhase());
this.end();
};
@ -403,13 +403,13 @@ export class EncounterPhase extends BattlePhase {
const showNextDialogue = () => {
const nextAction = i === introDialogue.length - 1 ? doShowEncounterOptions : showNextDialogue;
const dialogue = introDialogue[i];
const title = getEncounterText(this.scene, dialogue?.speaker);
const text = getEncounterText(this.scene, dialogue.text)!;
const title = getEncounterText(dialogue?.speaker);
const text = getEncounterText(dialogue.text)!;
i++;
if (title) {
this.scene.ui.showDialogue(text, title, null, nextAction, 0, i === 1 ? FIRST_DIALOGUE_PROMPT_DELAY : 0);
gScene.ui.showDialogue(text, title, null, nextAction, 0, i === 1 ? FIRST_DIALOGUE_PROMPT_DELAY : 0);
} else {
this.scene.ui.showText(text, null, nextAction, i === 1 ? FIRST_DIALOGUE_PROMPT_DELAY : 0, true);
gScene.ui.showText(text, null, nextAction, i === 1 ? FIRST_DIALOGUE_PROMPT_DELAY : 0, true);
}
};
@ -427,101 +427,101 @@ export class EncounterPhase extends BattlePhase {
if (!encounterMessage) {
doEncounter();
} else {
doTrainerExclamation(this.scene);
this.scene.ui.showDialogue(encounterMessage, "???", null, () => {
this.scene.charSprite.hide().then(() => this.scene.hideFieldOverlay(250).then(() => doEncounter()));
doTrainerExclamation();
gScene.ui.showDialogue(encounterMessage, "???", null, () => {
gScene.charSprite.hide().then(() => gScene.hideFieldOverlay(250).then(() => doEncounter()));
});
}
}
}
end() {
const enemyField = this.scene.getEnemyField();
const enemyField = gScene.getEnemyField();
enemyField.forEach((enemyPokemon, e) => {
if (enemyPokemon.isShiny()) {
this.scene.unshiftPhase(new ShinySparklePhase(this.scene, BattlerIndex.ENEMY + e));
gScene.unshiftPhase(new ShinySparklePhase(BattlerIndex.ENEMY + e));
}
});
if (![ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(this.scene.currentBattle.battleType)) {
enemyField.map(p => this.scene.pushConditionalPhase(new PostSummonPhase(this.scene, p.getBattlerIndex()), () => {
if (![ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(gScene.currentBattle.battleType)) {
enemyField.map(p => gScene.pushConditionalPhase(new PostSummonPhase(p.getBattlerIndex()), () => {
// if there is not a player party, we can't continue
if (!this.scene.getParty()?.length) {
if (!gScene.getParty()?.length) {
return false;
}
// how many player pokemon are on the field ?
const pokemonsOnFieldCount = this.scene.getParty().filter(p => p.isOnField()).length;
const pokemonsOnFieldCount = gScene.getParty().filter(p => p.isOnField()).length;
// if it's a 2vs1, there will never be a 2nd pokemon on our field even
const requiredPokemonsOnField = Math.min(this.scene.getParty().filter((p) => !p.isFainted()).length, 2);
const requiredPokemonsOnField = Math.min(gScene.getParty().filter((p) => !p.isFainted()).length, 2);
// if it's a double, there should be 2, otherwise 1
if (this.scene.currentBattle.double) {
if (gScene.currentBattle.double) {
return pokemonsOnFieldCount === requiredPokemonsOnField;
}
return pokemonsOnFieldCount === 1;
}));
const ivScannerModifier = this.scene.findModifier(m => m instanceof IvScannerModifier);
const ivScannerModifier = gScene.findModifier(m => m instanceof IvScannerModifier);
if (ivScannerModifier) {
enemyField.map(p => this.scene.pushPhase(new ScanIvsPhase(this.scene, p.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6))));
enemyField.map(p => gScene.pushPhase(new ScanIvsPhase(p.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6))));
}
}
if (!this.loaded) {
const availablePartyMembers = this.scene.getParty().filter(p => p.isAllowedInBattle());
const availablePartyMembers = gScene.getParty().filter(p => p.isAllowedInBattle());
if (!availablePartyMembers[0].isOnField()) {
this.scene.pushPhase(new SummonPhase(this.scene, 0));
gScene.pushPhase(new SummonPhase(0));
}
if (this.scene.currentBattle.double) {
if (gScene.currentBattle.double) {
if (availablePartyMembers.length > 1) {
this.scene.pushPhase(new ToggleDoublePositionPhase(this.scene, true));
gScene.pushPhase(new ToggleDoublePositionPhase(true));
if (!availablePartyMembers[1].isOnField()) {
this.scene.pushPhase(new SummonPhase(this.scene, 1));
gScene.pushPhase(new SummonPhase(1));
}
}
} else {
if (availablePartyMembers.length > 1 && availablePartyMembers[1].isOnField()) {
this.scene.pushPhase(new ReturnPhase(this.scene, 1));
gScene.pushPhase(new ReturnPhase(1));
}
this.scene.pushPhase(new ToggleDoublePositionPhase(this.scene, false));
gScene.pushPhase(new ToggleDoublePositionPhase(false));
}
if (this.scene.currentBattle.battleType !== BattleType.TRAINER && (this.scene.currentBattle.waveIndex > 1 || !this.scene.gameMode.isDaily)) {
const minPartySize = this.scene.currentBattle.double ? 2 : 1;
if (gScene.currentBattle.battleType !== BattleType.TRAINER && (gScene.currentBattle.waveIndex > 1 || !gScene.gameMode.isDaily)) {
const minPartySize = gScene.currentBattle.double ? 2 : 1;
if (availablePartyMembers.length > minPartySize) {
this.scene.pushPhase(new CheckSwitchPhase(this.scene, 0, this.scene.currentBattle.double));
if (this.scene.currentBattle.double) {
this.scene.pushPhase(new CheckSwitchPhase(this.scene, 1, this.scene.currentBattle.double));
gScene.pushPhase(new CheckSwitchPhase(0, gScene.currentBattle.double));
if (gScene.currentBattle.double) {
gScene.pushPhase(new CheckSwitchPhase(1, gScene.currentBattle.double));
}
}
}
}
handleTutorial(this.scene, Tutorial.Access_Menu).then(() => super.end());
handleTutorial(Tutorial.Access_Menu).then(() => super.end());
}
tryOverrideForBattleSpec(): boolean {
switch (this.scene.currentBattle.battleSpec) {
switch (gScene.currentBattle.battleSpec) {
case BattleSpec.FINAL_BOSS:
const enemy = this.scene.getEnemyPokemon();
this.scene.ui.showText(this.getEncounterMessage(), null, () => {
const enemy = gScene.getEnemyPokemon();
gScene.ui.showText(this.getEncounterMessage(), null, () => {
const localizationKey = "battleSpecDialogue:encounter";
if (this.scene.ui.shouldSkipDialogue(localizationKey)) {
if (gScene.ui.shouldSkipDialogue(localizationKey)) {
// Logging mirrors logging found in dialogue-ui-handler
console.log(`Dialogue ${localizationKey} skipped`);
this.doEncounterCommon(false);
} else {
const count = 5643853 + this.scene.gameData.gameStats.classicSessionsPlayed;
const count = 5643853 + gScene.gameData.gameStats.classicSessionsPlayed;
// The line below checks if an English ordinal is necessary or not based on whether an entry for encounterLocalizationKey exists in the language or not.
const ordinalUsed = !i18next.exists(localizationKey, { fallbackLng: []}) || i18next.resolvedLanguage === "en" ? i18next.t("battleSpecDialogue:key", { count: count, ordinal: true }) : "";
const cycleCount = count.toLocaleString() + ordinalUsed;
const genderIndex = this.scene.gameData.gender ?? PlayerGender.UNSET;
const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET;
const genderStr = PlayerGender[genderIndex].toLowerCase();
const encounterDialogue = i18next.t(localizationKey, { context: genderStr, cycleCount: cycleCount });
if (!this.scene.gameData.getSeenDialogues()[localizationKey]) {
this.scene.gameData.saveSeenDialogue(localizationKey);
if (!gScene.gameData.getSeenDialogues()[localizationKey]) {
gScene.gameData.saveSeenDialogue(localizationKey);
}
this.scene.ui.showDialogue(encounterDialogue, enemy?.species.name, null, () => {
gScene.ui.showDialogue(encounterDialogue, enemy?.species.name, null, () => {
this.doEncounterCommon(false);
});
}
@ -541,7 +541,7 @@ export class EncounterPhase extends BattlePhase {
*/
trySetWeatherIfNewBiome(): void {
if (!this.loaded) {
this.scene.arena.trySetWeather(getRandomWeatherType(this.scene.arena), false);
gScene.arena.trySetWeather(getRandomWeatherType(gScene.arena), false);
}
}
}

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { PlayerGender } from "#app/enums/player-gender";
import { Phase } from "#app/phase";
import { addTextObject, TextStyle } from "#app/ui/text";
@ -8,31 +8,31 @@ export class EndCardPhase extends Phase {
public endCard: Phaser.GameObjects.Image;
public text: Phaser.GameObjects.Text;
constructor(scene: BattleScene) {
super(scene);
constructor() {
super();
}
start(): void {
super.start();
this.scene.ui.getMessageHandler().bg.setVisible(false);
this.scene.ui.getMessageHandler().nameBoxContainer.setVisible(false);
gScene.ui.getMessageHandler().bg.setVisible(false);
gScene.ui.getMessageHandler().nameBoxContainer.setVisible(false);
this.endCard = this.scene.add.image(0, 0, `end_${this.scene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}`);
this.endCard = gScene.add.image(0, 0, `end_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}`);
this.endCard.setOrigin(0);
this.endCard.setScale(0.5);
this.scene.field.add(this.endCard);
gScene.field.add(this.endCard);
this.text = addTextObject(this.scene, this.scene.game.canvas.width / 12, (this.scene.game.canvas.height / 6) - 16, i18next.t("battle:congratulations"), TextStyle.SUMMARY, { fontSize: "128px" });
this.text = addTextObject(gScene.game.canvas.width / 12, (gScene.game.canvas.height / 6) - 16, i18next.t("battle:congratulations"), TextStyle.SUMMARY, { fontSize: "128px" });
this.text.setOrigin(0.5);
this.scene.field.add(this.text);
gScene.field.add(this.text);
this.scene.ui.clearText();
gScene.ui.clearText();
this.scene.ui.fadeIn(1000).then(() => {
gScene.ui.fadeIn(1000).then(() => {
this.scene.ui.showText("", null, () => {
this.scene.ui.getMessageHandler().bg.setVisible(true);
gScene.ui.showText("", null, () => {
gScene.ui.getMessageHandler().bg.setVisible(true);
this.end();
}, null, true);
});

View File

@ -1,16 +1,16 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { Phase } from "#app/phase";
import { Mode } from "#app/ui/ui";
export class EndEvolutionPhase extends Phase {
constructor(scene: BattleScene) {
super(scene);
constructor() {
super();
}
start() {
super.start();
this.scene.ui.setModeForceTransition(Mode.MESSAGE).then(() => this.end());
gScene.ui.setModeForceTransition(Mode.MESSAGE).then(() => this.end());
}
}

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { BattlerIndex } from "#app/battle";
import { Command } from "#app/ui/command-ui-handler";
import { FieldPhase } from "./field-phase";
@ -16,11 +16,11 @@ export class EnemyCommandPhase extends FieldPhase {
protected fieldIndex: integer;
protected skipTurn: boolean = false;
constructor(scene: BattleScene, fieldIndex: integer) {
super(scene);
constructor(fieldIndex: integer) {
super();
this.fieldIndex = fieldIndex;
if (this.scene.currentBattle.mysteryEncounter?.skipEnemyBattleTurns) {
if (gScene.currentBattle.mysteryEncounter?.skipEnemyBattleTurns) {
this.skipTurn = true;
}
}
@ -28,9 +28,9 @@ export class EnemyCommandPhase extends FieldPhase {
start() {
super.start();
const enemyPokemon = this.scene.getEnemyField()[this.fieldIndex];
const enemyPokemon = gScene.getEnemyField()[this.fieldIndex];
const battle = this.scene.currentBattle;
const battle = gScene.currentBattle;
const trainer = battle.trainer;
@ -74,10 +74,10 @@ export class EnemyCommandPhase extends FieldPhase {
/** Select a move to use (and a target to use it against, if applicable) */
const nextMove = enemyPokemon.getNextMove();
this.scene.currentBattle.turnCommands[this.fieldIndex + BattlerIndex.ENEMY] =
gScene.currentBattle.turnCommands[this.fieldIndex + BattlerIndex.ENEMY] =
{ command: Command.FIGHT, move: nextMove, skip: this.skipTurn };
this.scene.currentBattle.enemySwitchCounter = Math.max(this.scene.currentBattle.enemySwitchCounter - 1, 0);
gScene.currentBattle.enemySwitchCounter = Math.max(gScene.currentBattle.enemySwitchCounter - 1, 0);
this.end();
}

View File

@ -1,10 +1,9 @@
import BattleScene from "#app/battle-scene";
import { EnemyPokemon } from "#app/field/pokemon";
import { PartyMemberPokemonPhase } from "./party-member-pokemon-phase";
export abstract class EnemyPartyMemberPokemonPhase extends PartyMemberPokemonPhase {
constructor(scene: BattleScene, partyMemberIndex: integer) {
super(scene, partyMemberIndex, false);
constructor(partyMemberIndex: integer) {
super(partyMemberIndex, false);
}
getEnemyPokemon(): EnemyPokemon {

View File

@ -1,6 +1,6 @@
import SoundFade from "phaser3-rex-plugins/plugins/soundfade";
import { Phase } from "#app/phase";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { SpeciesFormEvolution } from "#app/data/balance/pokemon-evolutions";
import EvolutionSceneHandler from "#app/ui/evolution-scene-handler";
import * as Utils from "#app/utils";
@ -29,8 +29,8 @@ export class EvolutionPhase extends Phase {
protected pokemonEvoSprite: Phaser.GameObjects.Sprite;
protected pokemonEvoTintSprite: Phaser.GameObjects.Sprite;
constructor(scene: BattleScene, pokemon: PlayerPokemon, evolution: SpeciesFormEvolution | null, lastLevel: integer) {
super(scene);
constructor(pokemon: PlayerPokemon, evolution: SpeciesFormEvolution | null, lastLevel: integer) {
super();
this.pokemon = pokemon;
this.evolution = evolution;
@ -42,7 +42,7 @@ export class EvolutionPhase extends Phase {
}
setMode(): Promise<void> {
return this.scene.ui.setModeForceTransition(Mode.EVOLUTION_SCENE);
return gScene.ui.setModeForceTransition(Mode.EVOLUTION_SCENE);
}
start() {
@ -54,30 +54,30 @@ export class EvolutionPhase extends Phase {
return this.end();
}
this.scene.fadeOutBgm(undefined, false);
gScene.fadeOutBgm(undefined, false);
const evolutionHandler = this.scene.ui.getHandler() as EvolutionSceneHandler;
const evolutionHandler = gScene.ui.getHandler() as EvolutionSceneHandler;
this.evolutionContainer = evolutionHandler.evolutionContainer;
this.evolutionBaseBg = this.scene.add.image(0, 0, "default_bg");
this.evolutionBaseBg = gScene.add.image(0, 0, "default_bg");
this.evolutionBaseBg.setOrigin(0, 0);
this.evolutionContainer.add(this.evolutionBaseBg);
this.evolutionBg = this.scene.add.video(0, 0, "evo_bg").stop();
this.evolutionBg = gScene.add.video(0, 0, "evo_bg").stop();
this.evolutionBg.setOrigin(0, 0);
this.evolutionBg.setScale(0.4359673025);
this.evolutionBg.setVisible(false);
this.evolutionContainer.add(this.evolutionBg);
this.evolutionBgOverlay = this.scene.add.rectangle(0, 0, this.scene.game.canvas.width / 6, this.scene.game.canvas.height / 6, 0x262626);
this.evolutionBgOverlay = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0x262626);
this.evolutionBgOverlay.setOrigin(0, 0);
this.evolutionBgOverlay.setAlpha(0);
this.evolutionContainer.add(this.evolutionBgOverlay);
const getPokemonSprite = () => {
const ret = this.scene.addPokemonSprite(this.pokemon, this.evolutionBaseBg.displayWidth / 2, this.evolutionBaseBg.displayHeight / 2, "pkmn__sub");
ret.setPipeline(this.scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true });
const ret = gScene.addPokemonSprite(this.pokemon, this.evolutionBaseBg.displayWidth / 2, this.evolutionBaseBg.displayHeight / 2, "pkmn__sub");
ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true });
return ret;
};
@ -92,14 +92,14 @@ export class EvolutionPhase extends Phase {
this.pokemonEvoTintSprite.setVisible(false);
this.pokemonEvoTintSprite.setTintFill(0xFFFFFF);
this.evolutionOverlay = this.scene.add.rectangle(0, -this.scene.game.canvas.height / 6, this.scene.game.canvas.width / 6, (this.scene.game.canvas.height / 6) - 48, 0xFFFFFF);
this.evolutionOverlay = gScene.add.rectangle(0, -gScene.game.canvas.height / 6, gScene.game.canvas.width / 6, (gScene.game.canvas.height / 6) - 48, 0xFFFFFF);
this.evolutionOverlay.setOrigin(0, 0);
this.evolutionOverlay.setAlpha(0);
this.scene.ui.add(this.evolutionOverlay);
gScene.ui.add(this.evolutionOverlay);
[ this.pokemonSprite, this.pokemonTintSprite, this.pokemonEvoSprite, this.pokemonEvoTintSprite ].map(sprite => {
sprite.play(this.pokemon.getSpriteKey(true));
sprite.setPipeline(this.scene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(this.pokemon.getTeraType()) });
sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(this.pokemon.getTeraType()) });
sprite.setPipelineData("ignoreTimeTint", true);
sprite.setPipelineData("spriteKey", this.pokemon.getSpriteKey());
sprite.setPipelineData("shiny", this.pokemon.shiny);
@ -117,10 +117,10 @@ export class EvolutionPhase extends Phase {
}
doEvolution(): void {
const evolutionHandler = this.scene.ui.getHandler() as EvolutionSceneHandler;
const evolutionHandler = gScene.ui.getHandler() as EvolutionSceneHandler;
const preName = getPokemonNameWithAffix(this.pokemon);
this.scene.ui.showText(i18next.t("menu:evolving", { pokemonName: preName }), null, () => {
gScene.ui.showText(i18next.t("menu:evolving", { pokemonName: preName }), null, () => {
this.pokemon.cry();
this.pokemon.getPossibleEvolution(this.evolution).then(evolvedPokemon => {
@ -139,17 +139,17 @@ export class EvolutionPhase extends Phase {
});
});
this.scene.time.delayedCall(1000, () => {
const evolutionBgm = this.scene.playSoundWithoutBgm("evolution");
this.scene.tweens.add({
gScene.time.delayedCall(1000, () => {
const evolutionBgm = gScene.playSoundWithoutBgm("evolution");
gScene.tweens.add({
targets: this.evolutionBgOverlay,
alpha: 1,
delay: 500,
duration: 1500,
ease: "Sine.easeOut",
onComplete: () => {
this.scene.time.delayedCall(1000, () => {
this.scene.tweens.add({
gScene.time.delayedCall(1000, () => {
gScene.tweens.add({
targets: this.evolutionBgOverlay,
alpha: 0,
duration: 250
@ -157,9 +157,9 @@ export class EvolutionPhase extends Phase {
this.evolutionBg.setVisible(true);
this.evolutionBg.play();
});
this.scene.playSound("se/charge");
gScene.playSound("se/charge");
this.doSpiralUpward();
this.scene.tweens.addCounter({
gScene.tweens.addCounter({
from: 0,
to: 1,
duration: 2000,
@ -168,10 +168,10 @@ export class EvolutionPhase extends Phase {
},
onComplete: () => {
this.pokemonSprite.setVisible(false);
this.scene.time.delayedCall(1100, () => {
this.scene.playSound("se/beam");
gScene.time.delayedCall(1100, () => {
gScene.playSound("se/beam");
this.doArcDownward();
this.scene.time.delayedCall(1500, () => {
gScene.time.delayedCall(1500, () => {
this.pokemonEvoTintSprite.setScale(0.25);
this.pokemonEvoTintSprite.setVisible(true);
evolutionHandler.canCancel = true;
@ -180,7 +180,7 @@ export class EvolutionPhase extends Phase {
this.pokemonSprite.setVisible(true);
this.pokemonTintSprite.setScale(1);
this.scene.tweens.add({
gScene.tweens.add({
targets: [ this.evolutionBg, this.pokemonTintSprite, this.pokemonEvoSprite, this.pokemonEvoTintSprite ],
alpha: 0,
duration: 250,
@ -189,47 +189,47 @@ export class EvolutionPhase extends Phase {
}
});
SoundFade.fadeOut(this.scene, evolutionBgm, 100);
SoundFade.fadeOut(evolutionBgm, 100);
this.scene.unshiftPhase(new EndEvolutionPhase(this.scene));
gScene.unshiftPhase(new EndEvolutionPhase());
this.scene.ui.showText(i18next.t("menu:stoppedEvolving", { pokemonName: preName }), null, () => {
this.scene.ui.showText(i18next.t("menu:pauseEvolutionsQuestion", { pokemonName: preName }), null, () => {
gScene.ui.showText(i18next.t("menu:stoppedEvolving", { pokemonName: preName }), null, () => {
gScene.ui.showText(i18next.t("menu:pauseEvolutionsQuestion", { pokemonName: preName }), null, () => {
const end = () => {
this.scene.ui.showText("", 0);
this.scene.playBgm();
gScene.ui.showText("", 0);
gScene.playBgm();
evolvedPokemon.destroy();
this.end();
};
this.scene.ui.setOverlayMode(Mode.CONFIRM, () => {
this.scene.ui.revertMode();
gScene.ui.setOverlayMode(Mode.CONFIRM, () => {
gScene.ui.revertMode();
this.pokemon.pauseEvolutions = true;
this.scene.ui.showText(i18next.t("menu:evolutionsPaused", { pokemonName: preName }), null, end, 3000);
gScene.ui.showText(i18next.t("menu:evolutionsPaused", { pokemonName: preName }), null, end, 3000);
}, () => {
this.scene.ui.revertMode();
this.scene.time.delayedCall(3000, end);
gScene.ui.revertMode();
gScene.time.delayedCall(3000, end);
});
});
}, null, true);
return;
}
this.scene.playSound("se/sparkle");
gScene.playSound("se/sparkle");
this.pokemonEvoSprite.setVisible(true);
this.doCircleInward();
this.scene.time.delayedCall(900, () => {
gScene.time.delayedCall(900, () => {
evolutionHandler.canCancel = false;
this.pokemon.evolve(this.evolution, this.pokemon.species).then(() => {
const levelMoves = this.pokemon.getLevelMoves(this.lastLevel + 1, true);
for (const lm of levelMoves) {
this.scene.unshiftPhase(new LearnMovePhase(this.scene, this.scene.getParty().indexOf(this.pokemon), lm[1]));
gScene.unshiftPhase(new LearnMovePhase(gScene.getParty().indexOf(this.pokemon), lm[1]));
}
this.scene.unshiftPhase(new EndEvolutionPhase(this.scene));
gScene.unshiftPhase(new EndEvolutionPhase());
this.scene.playSound("se/shine");
gScene.playSound("se/shine");
this.doSpray();
this.scene.tweens.add({
gScene.tweens.add({
targets: this.evolutionOverlay,
alpha: 1,
duration: 250,
@ -237,27 +237,27 @@ export class EvolutionPhase extends Phase {
onComplete: () => {
this.evolutionBgOverlay.setAlpha(1);
this.evolutionBg.setVisible(false);
this.scene.tweens.add({
gScene.tweens.add({
targets: [ this.evolutionOverlay, this.pokemonEvoTintSprite ],
alpha: 0,
duration: 2000,
delay: 150,
easing: "Sine.easeIn",
onComplete: () => {
this.scene.tweens.add({
gScene.tweens.add({
targets: this.evolutionBgOverlay,
alpha: 0,
duration: 250,
onComplete: () => {
SoundFade.fadeOut(this.scene, evolutionBgm, 100);
this.scene.time.delayedCall(250, () => {
SoundFade.fadeOut(evolutionBgm, 100);
gScene.time.delayedCall(250, () => {
this.pokemon.cry();
this.scene.time.delayedCall(1250, () => {
this.scene.playSoundWithoutBgm("evolution_fanfare");
gScene.time.delayedCall(1250, () => {
gScene.playSoundWithoutBgm("evolution_fanfare");
evolvedPokemon.destroy();
this.scene.ui.showText(i18next.t("menu:evolutionDone", { pokemonName: preName, evolvedPokemonName: this.pokemon.name }), null, () => this.end(), null, true, Utils.fixedInt(4000));
this.scene.time.delayedCall(Utils.fixedInt(4250), () => this.scene.playBgm());
gScene.ui.showText(i18next.t("menu:evolutionDone", { pokemonName: preName, evolvedPokemonName: this.pokemon.name }), null, () => this.end(), null, true, Utils.fixedInt(4000));
gScene.time.delayedCall(Utils.fixedInt(4250), () => gScene.playBgm());
});
});
}
@ -283,7 +283,7 @@ export class EvolutionPhase extends Phase {
doSpiralUpward() {
let f = 0;
this.scene.tweens.addCounter({
gScene.tweens.addCounter({
repeat: 64,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -302,7 +302,7 @@ export class EvolutionPhase extends Phase {
doArcDownward() {
let f = 0;
this.scene.tweens.addCounter({
gScene.tweens.addCounter({
repeat: 96,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -320,16 +320,16 @@ export class EvolutionPhase extends Phase {
doCycle(l: number, lastCycle: integer = 15): Promise<boolean> {
return new Promise(resolve => {
const evolutionHandler = this.scene.ui.getHandler() as EvolutionSceneHandler;
const evolutionHandler = gScene.ui.getHandler() as EvolutionSceneHandler;
const isLastCycle = l === lastCycle;
this.scene.tweens.add({
gScene.tweens.add({
targets: this.pokemonTintSprite,
scale: 0.25,
ease: "Cubic.easeInOut",
duration: 500 / l,
yoyo: !isLastCycle
});
this.scene.tweens.add({
gScene.tweens.add({
targets: this.pokemonEvoTintSprite,
scale: 1,
ease: "Cubic.easeInOut",
@ -353,7 +353,7 @@ export class EvolutionPhase extends Phase {
doCircleInward() {
let f = 0;
this.scene.tweens.addCounter({
gScene.tweens.addCounter({
repeat: 48,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -374,7 +374,7 @@ export class EvolutionPhase extends Phase {
doSpray() {
let f = 0;
this.scene.tweens.addCounter({
gScene.tweens.addCounter({
repeat: 48,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -392,13 +392,13 @@ export class EvolutionPhase extends Phase {
doSpiralUpwardParticle(trigIndex: integer) {
const initialX = this.evolutionBaseBg.displayWidth / 2;
const particle = this.scene.add.image(initialX, 0, "evo_sparkle");
const particle = gScene.add.image(initialX, 0, "evo_sparkle");
this.evolutionContainer.add(particle);
let f = 0;
let amp = 48;
const particleTimer = this.scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -428,14 +428,14 @@ export class EvolutionPhase extends Phase {
doArcDownParticle(trigIndex: integer) {
const initialX = this.evolutionBaseBg.displayWidth / 2;
const particle = this.scene.add.image(initialX, 0, "evo_sparkle");
const particle = gScene.add.image(initialX, 0, "evo_sparkle");
particle.setScale(0.5);
this.evolutionContainer.add(particle);
let f = 0;
let amp = 8;
const particleTimer = this.scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -462,12 +462,12 @@ export class EvolutionPhase extends Phase {
doCircleInwardParticle(trigIndex: integer, speed: integer) {
const initialX = this.evolutionBaseBg.displayWidth / 2;
const initialY = this.evolutionBaseBg.displayHeight / 2;
const particle = this.scene.add.image(initialX, initialY, "evo_sparkle");
const particle = gScene.add.image(initialX, initialY, "evo_sparkle");
this.evolutionContainer.add(particle);
let amp = 120;
const particleTimer = this.scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
onRepeat: () => {
@ -494,7 +494,7 @@ export class EvolutionPhase extends Phase {
doSprayParticle(trigIndex: integer) {
const initialX = this.evolutionBaseBg.displayWidth / 2;
const initialY = this.evolutionBaseBg.displayHeight / 2;
const particle = this.scene.add.image(initialX, initialY, "evo_sparkle");
const particle = gScene.add.image(initialX, initialY, "evo_sparkle");
this.evolutionContainer.add(particle);
let f = 0;
@ -502,7 +502,7 @@ export class EvolutionPhase extends Phase {
const speed = 3 - Utils.randInt(8);
const amp = 48 + Utils.randInt(64);
const particleTimer = this.scene.tweens.addCounter({
const particleTimer = gScene.tweens.addCounter({
repeat: -1,
duration: Utils.getFrameMs(1),
onRepeat: () => {

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { getPokemonNameWithAffix } from "#app/messages";
import { ExpBoosterModifier } from "#app/modifier/modifier";
import i18next from "i18next";
@ -9,8 +9,8 @@ import { LevelUpPhase } from "./level-up-phase";
export class ExpPhase extends PlayerPartyMemberPokemonPhase {
private expValue: number;
constructor(scene: BattleScene, partyMemberIndex: integer, expValue: number) {
super(scene, partyMemberIndex);
constructor(partyMemberIndex: integer, expValue: number) {
super(partyMemberIndex);
this.expValue = expValue;
}
@ -20,14 +20,14 @@ export class ExpPhase extends PlayerPartyMemberPokemonPhase {
const pokemon = this.getPokemon();
const exp = new Utils.NumberHolder(this.expValue);
this.scene.applyModifiers(ExpBoosterModifier, true, exp);
gScene.applyModifiers(ExpBoosterModifier, true, exp);
exp.value = Math.floor(exp.value);
this.scene.ui.showText(i18next.t("battle:expGain", { pokemonName: getPokemonNameWithAffix(pokemon), exp: exp.value }), null, () => {
gScene.ui.showText(i18next.t("battle:expGain", { pokemonName: getPokemonNameWithAffix(pokemon), exp: exp.value }), null, () => {
const lastLevel = pokemon.level;
pokemon.addExp(exp.value);
const newLevel = pokemon.level;
if (newLevel > lastLevel) {
this.scene.unshiftPhase(new LevelUpPhase(this.scene, this.partyMemberIndex, lastLevel, newLevel));
gScene.unshiftPhase(new LevelUpPhase(this.partyMemberIndex, lastLevel, newLevel));
}
pokemon.updateInfo().then(() => this.end());
}, null, true);

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { BattlerIndex, BattleType } from "#app/battle";
import { applyPostFaintAbAttrs, PostFaintAbAttr, applyPostKnockOutAbAttrs, PostKnockOutAbAttr, applyPostVictoryAbAttrs, PostVictoryAbAttr } from "#app/data/ability";
import { BattlerTagLapseType, DestinyBondTag } from "#app/data/battler-tags";
@ -38,8 +38,8 @@ export class FaintPhase extends PokemonPhase {
*/
private source?: Pokemon;
constructor(scene: BattleScene, battlerIndex: BattlerIndex, preventEndure: boolean = false, destinyTag?: DestinyBondTag, source?: Pokemon) {
super(scene, battlerIndex);
constructor(battlerIndex: BattlerIndex, preventEndure: boolean = false, destinyTag?: DestinyBondTag, source?: Pokemon) {
super(battlerIndex);
this.preventEndure = preventEndure;
this.destinyTag = destinyTag;
@ -54,22 +54,22 @@ export class FaintPhase extends PokemonPhase {
}
if (!this.preventEndure) {
const instantReviveModifier = this.scene.applyModifier(PokemonInstantReviveModifier, this.player, this.getPokemon()) as PokemonInstantReviveModifier;
const instantReviveModifier = gScene.applyModifier(PokemonInstantReviveModifier, this.player, this.getPokemon()) as PokemonInstantReviveModifier;
if (instantReviveModifier) {
if (!--instantReviveModifier.stackCount) {
this.scene.removeModifier(instantReviveModifier);
gScene.removeModifier(instantReviveModifier);
}
this.scene.updateModifiers(this.player);
gScene.updateModifiers(this.player);
return this.end();
}
}
/** In case the current pokemon was just switched in, make sure it is counted as participating in the combat */
this.scene.getPlayerField().forEach((pokemon, i) => {
gScene.getPlayerField().forEach((pokemon, i) => {
if (pokemon?.isActive(true)) {
if (pokemon.isPlayer()) {
this.scene.currentBattle.addParticipant(pokemon as PlayerPokemon);
gScene.currentBattle.addParticipant(pokemon as PlayerPokemon);
}
}
});
@ -85,27 +85,27 @@ export class FaintPhase extends PokemonPhase {
// Track total times pokemon have been KO'd for supreme overlord/last respects
if (pokemon.isPlayer()) {
this.scene.currentBattle.playerFaints += 1;
this.scene.currentBattle.playerFaintsHistory.push({ pokemon: pokemon, turn: this.scene.currentBattle.turn });
gScene.currentBattle.playerFaints += 1;
gScene.currentBattle.playerFaintsHistory.push({ pokemon: pokemon, turn: gScene.currentBattle.turn });
} else {
this.scene.currentBattle.enemyFaints += 1;
this.scene.currentBattle.enemyFaintsHistory.push({ pokemon: pokemon, turn: this.scene.currentBattle.turn });
gScene.currentBattle.enemyFaints += 1;
gScene.currentBattle.enemyFaintsHistory.push({ pokemon: pokemon, turn: gScene.currentBattle.turn });
}
this.scene.queueMessage(i18next.t("battle:fainted", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, true);
this.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true);
gScene.queueMessage(i18next.t("battle:fainted", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, true);
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true);
if (pokemon.turnData?.attacksReceived?.length) {
const lastAttack = pokemon.turnData.attacksReceived[0];
applyPostFaintAbAttrs(PostFaintAbAttr, pokemon, this.scene.getPokemonById(lastAttack.sourceId)!, new PokemonMove(lastAttack.move).getMove(), lastAttack.result); // TODO: is this bang correct?
applyPostFaintAbAttrs(PostFaintAbAttr, pokemon, gScene.getPokemonById(lastAttack.sourceId)!, new PokemonMove(lastAttack.move).getMove(), lastAttack.result); // TODO: is this bang correct?
} else { //If killed by indirect damage, apply post-faint abilities without providing a last move
applyPostFaintAbAttrs(PostFaintAbAttr, pokemon);
}
const alivePlayField = this.scene.getField(true);
const alivePlayField = gScene.getField(true);
alivePlayField.forEach(p => applyPostKnockOutAbAttrs(PostKnockOutAbAttr, p, pokemon));
if (pokemon.turnData?.attacksReceived?.length) {
const defeatSource = this.scene.getPokemonById(pokemon.turnData.attacksReceived[0].sourceId);
const defeatSource = gScene.getPokemonById(pokemon.turnData.attacksReceived[0].sourceId);
if (defeatSource?.isOnField()) {
applyPostVictoryAbAttrs(PostVictoryAbAttr, defeatSource);
const pvmove = allMoves[pokemon.turnData.attacksReceived[0].move];
@ -120,39 +120,39 @@ export class FaintPhase extends PokemonPhase {
if (this.player) {
/** The total number of Pokemon in the player's party that can legally fight */
const legalPlayerPokemon = this.scene.getParty().filter(p => p.isAllowedInBattle());
const legalPlayerPokemon = gScene.getParty().filter(p => p.isAllowedInBattle());
/** The total number of legal player Pokemon that aren't currently on the field */
const legalPlayerPartyPokemon = legalPlayerPokemon.filter(p => !p.isActive(true));
if (!legalPlayerPokemon.length) {
/** If the player doesn't have any legal Pokemon, end the game */
this.scene.unshiftPhase(new GameOverPhase(this.scene));
} else if (this.scene.currentBattle.double && legalPlayerPokemon.length === 1 && legalPlayerPartyPokemon.length === 0) {
gScene.unshiftPhase(new GameOverPhase());
} else if (gScene.currentBattle.double && legalPlayerPokemon.length === 1 && legalPlayerPartyPokemon.length === 0) {
/**
* If the player has exactly one Pokemon in total at this point in a double battle, and that Pokemon
* is already on the field, unshift a phase that moves that Pokemon to center position.
*/
this.scene.unshiftPhase(new ToggleDoublePositionPhase(this.scene, true));
gScene.unshiftPhase(new ToggleDoublePositionPhase(true));
} else if (legalPlayerPartyPokemon.length > 0) {
/**
* If previous conditions weren't met, and the player has at least 1 legal Pokemon off the field,
* push a phase that prompts the player to summon a Pokemon from their party.
*/
this.scene.pushPhase(new SwitchPhase(this.scene, SwitchType.SWITCH, this.fieldIndex, true, false));
gScene.pushPhase(new SwitchPhase(SwitchType.SWITCH, this.fieldIndex, true, false));
}
} else {
this.scene.unshiftPhase(new VictoryPhase(this.scene, this.battlerIndex));
if ([ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(this.scene.currentBattle.battleType)) {
const hasReservePartyMember = !!this.scene.getEnemyParty().filter(p => p.isActive() && !p.isOnField() && p.trainerSlot === (pokemon as EnemyPokemon).trainerSlot).length;
gScene.unshiftPhase(new VictoryPhase(this.battlerIndex));
if ([ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(gScene.currentBattle.battleType)) {
const hasReservePartyMember = !!gScene.getEnemyParty().filter(p => p.isActive() && !p.isOnField() && p.trainerSlot === (pokemon as EnemyPokemon).trainerSlot).length;
if (hasReservePartyMember) {
this.scene.pushPhase(new SwitchSummonPhase(this.scene, SwitchType.SWITCH, this.fieldIndex, -1, false, false));
gScene.pushPhase(new SwitchSummonPhase(SwitchType.SWITCH, this.fieldIndex, -1, false, false));
}
}
}
// in double battles redirect potential moves off fainted pokemon
if (this.scene.currentBattle.double) {
if (gScene.currentBattle.double) {
const allyPokemon = pokemon.getAlly();
this.scene.redirectPokemonMoves(pokemon, allyPokemon);
gScene.redirectPokemonMoves(pokemon, allyPokemon);
}
pokemon.faintCry(() => {
@ -160,8 +160,8 @@ export class FaintPhase extends PokemonPhase {
pokemon.addFriendship(-FRIENDSHIP_LOSS_FROM_FAINT);
}
pokemon.hideInfo();
this.scene.playSound("se/faint");
this.scene.tweens.add({
gScene.playSound("se/faint");
gScene.tweens.add({
targets: pokemon,
duration: 500,
y: pokemon.y + 150,
@ -169,17 +169,17 @@ export class FaintPhase extends PokemonPhase {
onComplete: () => {
pokemon.resetSprite();
pokemon.lapseTags(BattlerTagLapseType.FAINT);
this.scene.getField(true).filter(p => p !== pokemon).forEach(p => p.removeTagsBySourceId(pokemon.id));
gScene.getField(true).filter(p => p !== pokemon).forEach(p => p.removeTagsBySourceId(pokemon.id));
pokemon.y -= 150;
pokemon.trySetStatus(StatusEffect.FAINT);
if (pokemon.isPlayer()) {
this.scene.currentBattle.removeFaintedParticipant(pokemon as PlayerPokemon);
gScene.currentBattle.removeFaintedParticipant(pokemon as PlayerPokemon);
} else {
this.scene.addFaintedEnemyScore(pokemon as EnemyPokemon);
this.scene.currentBattle.addPostBattleLoot(pokemon as EnemyPokemon);
gScene.addFaintedEnemyScore(pokemon as EnemyPokemon);
gScene.currentBattle.addPostBattleLoot(pokemon as EnemyPokemon);
}
this.scene.field.remove(pokemon);
gScene.field.remove(pokemon);
this.end();
}
});
@ -187,16 +187,16 @@ export class FaintPhase extends PokemonPhase {
}
tryOverrideForBattleSpec(): boolean {
switch (this.scene.currentBattle.battleSpec) {
switch (gScene.currentBattle.battleSpec) {
case BattleSpec.FINAL_BOSS:
if (!this.player) {
const enemy = this.getPokemon();
if (enemy.formIndex) {
this.scene.ui.showDialogue(battleSpecDialogue[BattleSpec.FINAL_BOSS].secondStageWin, enemy.species.name, null, () => this.doFaint());
gScene.ui.showDialogue(battleSpecDialogue[BattleSpec.FINAL_BOSS].secondStageWin, enemy.species.name, null, () => this.doFaint());
} else {
// Final boss' HP threshold has been bypassed; cancel faint and force check for 2nd phase
enemy.hp++;
this.scene.unshiftPhase(new DamagePhase(this.scene, enemy.getBattlerIndex(), 0, HitResult.OTHER));
gScene.unshiftPhase(new DamagePhase(enemy.getBattlerIndex(), 0, HitResult.OTHER));
this.end();
}
return true;

View File

@ -1,3 +1,4 @@
import { gScene } from "#app/battle-scene";
import Pokemon from "#app/field/pokemon";
import { BattlePhase } from "./battle-phase";
@ -5,7 +6,7 @@ type PokemonFunc = (pokemon: Pokemon) => void;
export abstract class FieldPhase extends BattlePhase {
executeForAll(func: PokemonFunc): void {
const field = this.scene.getField(true).filter(p => p.summonData);
const field = gScene.getField(true).filter(p => p.summonData);
field.forEach(pokemon => func(pokemon));
}
}

View File

@ -1,4 +1,4 @@
import BattleScene from "../battle-scene";
import { gScene } from "../battle-scene";
import * as Utils from "../utils";
import { achvs } from "../system/achv";
import { SpeciesFormChange, getSpeciesFormChangeMessage } from "../data/pokemon-forms";
@ -15,8 +15,8 @@ export class FormChangePhase extends EvolutionPhase {
private formChange: SpeciesFormChange;
private modal: boolean;
constructor(scene: BattleScene, pokemon: PlayerPokemon, formChange: SpeciesFormChange, modal: boolean) {
super(scene, pokemon, null, 0);
constructor(pokemon: PlayerPokemon, formChange: SpeciesFormChange, modal: boolean) {
super(pokemon, null, 0);
this.formChange = formChange;
this.modal = modal;
@ -30,7 +30,7 @@ export class FormChangePhase extends EvolutionPhase {
if (!this.modal) {
return super.setMode();
}
return this.scene.ui.setOverlayMode(Mode.EVOLUTION_SCENE);
return gScene.ui.setOverlayMode(Mode.EVOLUTION_SCENE);
}
doEvolution(): void {
@ -52,16 +52,16 @@ export class FormChangePhase extends EvolutionPhase {
});
});
this.scene.time.delayedCall(250, () => {
this.scene.tweens.add({
gScene.time.delayedCall(250, () => {
gScene.tweens.add({
targets: this.evolutionBgOverlay,
alpha: 1,
delay: 500,
duration: 1500,
ease: "Sine.easeOut",
onComplete: () => {
this.scene.time.delayedCall(1000, () => {
this.scene.tweens.add({
gScene.time.delayedCall(1000, () => {
gScene.tweens.add({
targets: this.evolutionBgOverlay,
alpha: 0,
duration: 250
@ -69,9 +69,9 @@ export class FormChangePhase extends EvolutionPhase {
this.evolutionBg.setVisible(true);
this.evolutionBg.play();
});
this.scene.playSound("se/charge");
gScene.playSound("se/charge");
this.doSpiralUpward();
this.scene.tweens.addCounter({
gScene.tweens.addCounter({
from: 0,
to: 1,
duration: 2000,
@ -80,25 +80,25 @@ export class FormChangePhase extends EvolutionPhase {
},
onComplete: () => {
this.pokemonSprite.setVisible(false);
this.scene.time.delayedCall(1100, () => {
this.scene.playSound("se/beam");
gScene.time.delayedCall(1100, () => {
gScene.playSound("se/beam");
this.doArcDownward();
this.scene.time.delayedCall(1000, () => {
gScene.time.delayedCall(1000, () => {
this.pokemonEvoTintSprite.setScale(0.25);
this.pokemonEvoTintSprite.setVisible(true);
this.doCycle(1, 1).then(_success => {
this.scene.playSound("se/sparkle");
gScene.playSound("se/sparkle");
this.pokemonEvoSprite.setVisible(true);
this.doCircleInward();
this.scene.time.delayedCall(900, () => {
gScene.time.delayedCall(900, () => {
this.pokemon.changeForm(this.formChange).then(() => {
if (!this.modal) {
this.scene.unshiftPhase(new EndEvolutionPhase(this.scene));
gScene.unshiftPhase(new EndEvolutionPhase());
}
this.scene.playSound("se/shine");
gScene.playSound("se/shine");
this.doSpray();
this.scene.tweens.add({
gScene.tweens.add({
targets: this.evolutionOverlay,
alpha: 1,
duration: 250,
@ -106,36 +106,36 @@ export class FormChangePhase extends EvolutionPhase {
onComplete: () => {
this.evolutionBgOverlay.setAlpha(1);
this.evolutionBg.setVisible(false);
this.scene.tweens.add({
gScene.tweens.add({
targets: [ this.evolutionOverlay, this.pokemonEvoTintSprite ],
alpha: 0,
duration: 2000,
delay: 150,
easing: "Sine.easeIn",
onComplete: () => {
this.scene.tweens.add({
gScene.tweens.add({
targets: this.evolutionBgOverlay,
alpha: 0,
duration: 250,
onComplete: () => {
this.scene.time.delayedCall(250, () => {
gScene.time.delayedCall(250, () => {
this.pokemon.cry();
this.scene.time.delayedCall(1250, () => {
gScene.time.delayedCall(1250, () => {
let playEvolutionFanfare = false;
if (this.formChange.formKey.indexOf(SpeciesFormKey.MEGA) > -1) {
this.scene.validateAchv(achvs.MEGA_EVOLVE);
gScene.validateAchv(achvs.MEGA_EVOLVE);
playEvolutionFanfare = true;
} else if (this.formChange.formKey.indexOf(SpeciesFormKey.GIGANTAMAX) > -1 || this.formChange.formKey.indexOf(SpeciesFormKey.ETERNAMAX) > -1) {
this.scene.validateAchv(achvs.GIGANTAMAX);
gScene.validateAchv(achvs.GIGANTAMAX);
playEvolutionFanfare = true;
}
const delay = playEvolutionFanfare ? 4000 : 1750;
this.scene.playSoundWithoutBgm(playEvolutionFanfare ? "evolution_fanfare" : "minor_fanfare");
gScene.playSoundWithoutBgm(playEvolutionFanfare ? "evolution_fanfare" : "minor_fanfare");
transformedPokemon.destroy();
this.scene.ui.showText(getSpeciesFormChangeMessage(this.pokemon, this.formChange, preName), null, () => this.end(), null, true, Utils.fixedInt(delay));
this.scene.time.delayedCall(Utils.fixedInt(delay + 250), () => this.scene.playBgm());
gScene.ui.showText(getSpeciesFormChangeMessage(this.pokemon, this.formChange, preName), null, () => this.end(), null, true, Utils.fixedInt(delay));
gScene.time.delayedCall(Utils.fixedInt(delay + 250), () => gScene.playBgm());
});
});
}
@ -160,9 +160,9 @@ export class FormChangePhase extends EvolutionPhase {
end(): void {
this.pokemon.findAndRemoveTags(t => t.tagType === BattlerTagType.AUTOTOMIZED);
if (this.modal) {
this.scene.ui.revertMode().then(() => {
if (this.scene.ui.getMode() === Mode.PARTY) {
const partyUiHandler = this.scene.ui.getHandler() as PartyUiHandler;
gScene.ui.revertMode().then(() => {
if (gScene.ui.getMode() === Mode.PARTY) {
const partyUiHandler = gScene.ui.getHandler() as PartyUiHandler;
partyUiHandler.clearPartySlots();
partyUiHandler.populatePartySlots();
}

View File

@ -1,24 +1,24 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { ModifierTypeFunc } from "#app/modifier/modifier-type";
import { Mode } from "#app/ui/ui";
import i18next from "i18next";
import { ModifierRewardPhase } from "./modifier-reward-phase";
export class GameOverModifierRewardPhase extends ModifierRewardPhase {
constructor(scene: BattleScene, modifierTypeFunc: ModifierTypeFunc) {
super(scene, modifierTypeFunc);
constructor(modifierTypeFunc: ModifierTypeFunc) {
super(modifierTypeFunc);
}
doReward(): Promise<void> {
return new Promise<void>(resolve => {
const newModifier = this.modifierType.newModifier();
this.scene.addModifier(newModifier).then(() => {
gScene.addModifier(newModifier).then(() => {
// Sound loaded into game as is
this.scene.playSound("level_up_fanfare");
this.scene.ui.setMode(Mode.MESSAGE);
this.scene.ui.fadeIn(250).then(() => {
this.scene.ui.showText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), null, () => {
this.scene.time.delayedCall(1500, () => this.scene.arenaBg.setVisible(true));
gScene.playSound("level_up_fanfare");
gScene.ui.setMode(Mode.MESSAGE);
gScene.ui.fadeIn(250).then(() => {
gScene.ui.showText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), null, () => {
gScene.time.delayedCall(1500, () => gScene.arenaBg.setVisible(true));
resolve();
}, null, true, 1500);
});

View File

@ -1,6 +1,6 @@
import { clientSessionId } from "#app/account";
import { BattleType } from "#app/battle";
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { getCharVariantFromDialogue } from "#app/data/dialogue";
import { pokemonEvolutions } from "#app/data/balance/pokemon-evolutions";
import PokemonSpecies, { getPokemonSpecies } from "#app/data/pokemon-species";
@ -28,8 +28,8 @@ export class GameOverPhase extends BattlePhase {
private victory: boolean;
private firstRibbons: PokemonSpecies[] = [];
constructor(scene: BattleScene, victory?: boolean) {
super(scene);
constructor(victory?: boolean) {
super();
this.victory = !!victory;
}
@ -38,47 +38,47 @@ export class GameOverPhase extends BattlePhase {
super.start();
// Failsafe if players somehow skip floor 200 in classic mode
if (this.scene.gameMode.isClassic && this.scene.currentBattle.waveIndex > 200) {
if (gScene.gameMode.isClassic && gScene.currentBattle.waveIndex > 200) {
this.victory = true;
}
// Handle Mystery Encounter special Game Over cases
// Situations such as when player lost a battle, but it isn't treated as full Game Over
if (!this.victory && this.scene.currentBattle.mysteryEncounter?.onGameOver && !this.scene.currentBattle.mysteryEncounter.onGameOver(this.scene)) {
if (!this.victory && gScene.currentBattle.mysteryEncounter?.onGameOver && !gScene.currentBattle.mysteryEncounter.onGameOver()) {
// Do not end the game
return this.end();
}
// Otherwise, continue standard Game Over logic
if (this.victory && this.scene.gameMode.isEndless) {
const genderIndex = this.scene.gameData.gender ?? PlayerGender.UNSET;
if (this.victory && gScene.gameMode.isEndless) {
const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET;
const genderStr = PlayerGender[genderIndex].toLowerCase();
this.scene.ui.showDialogue(i18next.t("miscDialogue:ending_endless", { context: genderStr }), i18next.t("miscDialogue:ending_name"), 0, () => this.handleGameOver());
} else if (this.victory || !this.scene.enableRetries) {
gScene.ui.showDialogue(i18next.t("miscDialogue:ending_endless", { context: genderStr }), i18next.t("miscDialogue:ending_name"), 0, () => this.handleGameOver());
} else if (this.victory || !gScene.enableRetries) {
this.handleGameOver();
} else {
this.scene.ui.showText(i18next.t("battle:retryBattle"), null, () => {
this.scene.ui.setMode(Mode.CONFIRM, () => {
this.scene.ui.fadeOut(1250).then(() => {
this.scene.reset();
this.scene.clearPhaseQueue();
this.scene.gameData.loadSession(this.scene, this.scene.sessionSlotId).then(() => {
this.scene.pushPhase(new EncounterPhase(this.scene, true));
gScene.ui.showText(i18next.t("battle:retryBattle"), null, () => {
gScene.ui.setMode(Mode.CONFIRM, () => {
gScene.ui.fadeOut(1250).then(() => {
gScene.reset();
gScene.clearPhaseQueue();
gScene.gameData.loadSession(gScene.sessionSlotId).then(() => {
gScene.pushPhase(new EncounterPhase(true));
const availablePartyMembers = this.scene.getParty().filter(p => p.isAllowedInBattle()).length;
const availablePartyMembers = gScene.getParty().filter(p => p.isAllowedInBattle()).length;
this.scene.pushPhase(new SummonPhase(this.scene, 0));
if (this.scene.currentBattle.double && availablePartyMembers > 1) {
this.scene.pushPhase(new SummonPhase(this.scene, 1));
gScene.pushPhase(new SummonPhase(0));
if (gScene.currentBattle.double && availablePartyMembers > 1) {
gScene.pushPhase(new SummonPhase(1));
}
if (this.scene.currentBattle.waveIndex > 1 && this.scene.currentBattle.battleType !== BattleType.TRAINER) {
this.scene.pushPhase(new CheckSwitchPhase(this.scene, 0, this.scene.currentBattle.double));
if (this.scene.currentBattle.double && availablePartyMembers > 1) {
this.scene.pushPhase(new CheckSwitchPhase(this.scene, 1, this.scene.currentBattle.double));
if (gScene.currentBattle.waveIndex > 1 && gScene.currentBattle.battleType !== BattleType.TRAINER) {
gScene.pushPhase(new CheckSwitchPhase(0, gScene.currentBattle.double));
if (gScene.currentBattle.double && availablePartyMembers > 1) {
gScene.pushPhase(new CheckSwitchPhase(1, gScene.currentBattle.double));
}
}
this.scene.ui.fadeIn(1250);
gScene.ui.fadeIn(1250);
this.end();
});
});
@ -89,38 +89,38 @@ export class GameOverPhase extends BattlePhase {
handleGameOver(): void {
const doGameOver = (newClear: boolean) => {
this.scene.disableMenu = true;
this.scene.time.delayedCall(1000, () => {
gScene.disableMenu = true;
gScene.time.delayedCall(1000, () => {
let firstClear = false;
if (this.victory && newClear) {
if (this.scene.gameMode.isClassic) {
firstClear = this.scene.validateAchv(achvs.CLASSIC_VICTORY);
this.scene.validateAchv(achvs.UNEVOLVED_CLASSIC_VICTORY);
this.scene.gameData.gameStats.sessionsWon++;
for (const pokemon of this.scene.getParty()) {
if (gScene.gameMode.isClassic) {
firstClear = gScene.validateAchv(achvs.CLASSIC_VICTORY);
gScene.validateAchv(achvs.UNEVOLVED_CLASSIC_VICTORY);
gScene.gameData.gameStats.sessionsWon++;
for (const pokemon of gScene.getParty()) {
this.awardRibbon(pokemon);
if (pokemon.species.getRootSpeciesId() !== pokemon.species.getRootSpeciesId(true)) {
this.awardRibbon(pokemon, true);
}
}
} else if (this.scene.gameMode.isDaily && newClear) {
this.scene.gameData.gameStats.dailyRunSessionsWon++;
} else if (gScene.gameMode.isDaily && newClear) {
gScene.gameData.gameStats.dailyRunSessionsWon++;
}
}
this.scene.gameData.saveRunHistory(this.scene, this.scene.gameData.getSessionSaveData(this.scene), this.victory);
gScene.gameData.saveRunHistory(gScene.gameData.getSessionSaveData(), this.victory);
const fadeDuration = this.victory ? 10000 : 5000;
this.scene.fadeOutBgm(fadeDuration, true);
const activeBattlers = this.scene.getField().filter(p => p?.isActive(true));
gScene.fadeOutBgm(fadeDuration, true);
const activeBattlers = gScene.getField().filter(p => p?.isActive(true));
activeBattlers.map(p => p.hideInfo());
this.scene.ui.fadeOut(fadeDuration).then(() => {
gScene.ui.fadeOut(fadeDuration).then(() => {
activeBattlers.map(a => a.setVisible(false));
this.scene.setFieldScale(1, true);
this.scene.clearPhaseQueue();
this.scene.ui.clearText();
gScene.setFieldScale(1, true);
gScene.clearPhaseQueue();
gScene.ui.clearText();
if (this.victory && this.scene.gameMode.isChallenge) {
this.scene.gameMode.challenges.forEach(c => this.scene.validateAchvs(ChallengeAchv, c));
if (this.victory && gScene.gameMode.isChallenge) {
gScene.gameMode.challenges.forEach(c => gScene.validateAchvs(ChallengeAchv, c));
}
const clear = (endCardPhase?: EndCardPhase) => {
@ -129,31 +129,31 @@ export class GameOverPhase extends BattlePhase {
}
if (this.victory && newClear) {
for (const species of this.firstRibbons) {
this.scene.unshiftPhase(new RibbonModifierRewardPhase(this.scene, modifierTypes.VOUCHER_PLUS, species));
gScene.unshiftPhase(new RibbonModifierRewardPhase(modifierTypes.VOUCHER_PLUS, species));
}
if (!firstClear) {
this.scene.unshiftPhase(new GameOverModifierRewardPhase(this.scene, modifierTypes.VOUCHER_PREMIUM));
gScene.unshiftPhase(new GameOverModifierRewardPhase(modifierTypes.VOUCHER_PREMIUM));
}
}
this.scene.pushPhase(new PostGameOverPhase(this.scene, endCardPhase));
gScene.pushPhase(new PostGameOverPhase(endCardPhase));
this.end();
};
if (this.victory && this.scene.gameMode.isClassic) {
if (this.victory && gScene.gameMode.isClassic) {
const dialogueKey = "miscDialogue:ending";
if (!this.scene.ui.shouldSkipDialogue(dialogueKey)) {
this.scene.ui.fadeIn(500).then(() => {
const genderIndex = this.scene.gameData.gender ?? PlayerGender.UNSET;
if (!gScene.ui.shouldSkipDialogue(dialogueKey)) {
gScene.ui.fadeIn(500).then(() => {
const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET;
const genderStr = PlayerGender[genderIndex].toLowerCase();
// Dialogue has to be retrieved so that the rival's expressions can be loaded and shown via getCharVariantFromDialogue
const dialogue = i18next.t(dialogueKey, { context: genderStr });
this.scene.charSprite.showCharacter(`rival_${this.scene.gameData.gender === PlayerGender.FEMALE ? "m" : "f"}`, getCharVariantFromDialogue(dialogue)).then(() => {
this.scene.ui.showDialogue(dialogueKey, this.scene.gameData.gender === PlayerGender.FEMALE ? trainerConfigs[TrainerType.RIVAL].name : trainerConfigs[TrainerType.RIVAL].nameFemale, null, () => {
this.scene.ui.fadeOut(500).then(() => {
this.scene.charSprite.hide().then(() => {
const endCardPhase = new EndCardPhase(this.scene);
this.scene.unshiftPhase(endCardPhase);
gScene.charSprite.showCharacter(`rival_${gScene.gameData.gender === PlayerGender.FEMALE ? "m" : "f"}`, getCharVariantFromDialogue(dialogue)).then(() => {
gScene.ui.showDialogue(dialogueKey, gScene.gameData.gender === PlayerGender.FEMALE ? trainerConfigs[TrainerType.RIVAL].name : trainerConfigs[TrainerType.RIVAL].nameFemale, null, () => {
gScene.ui.fadeOut(500).then(() => {
gScene.charSprite.hide().then(() => {
const endCardPhase = new EndCardPhase();
gScene.unshiftPhase(endCardPhase);
clear(endCardPhase);
});
});
@ -161,8 +161,8 @@ export class GameOverPhase extends BattlePhase {
});
});
} else {
const endCardPhase = new EndCardPhase(this.scene);
this.scene.unshiftPhase(endCardPhase);
const endCardPhase = new EndCardPhase();
gScene.unshiftPhase(endCardPhase);
clear(endCardPhase);
}
} else {
@ -177,11 +177,11 @@ export class GameOverPhase extends BattlePhase {
If Offline, execute offlineNewClear(), a localStorage implementation of newClear daily run checks */
if (this.victory) {
if (!Utils.isLocal) {
Utils.apiFetch(`savedata/session/newclear?slot=${this.scene.sessionSlotId}&clientSessionId=${clientSessionId}`, true)
Utils.apiFetch(`savedata/session/newclear?slot=${gScene.sessionSlotId}&clientSessionId=${clientSessionId}`, true)
.then(response => response.json())
.then(newClear => doGameOver(newClear));
} else {
this.scene.gameData.offlineNewClear(this.scene).then(result => {
gScene.gameData.offlineNewClear().then(result => {
doGameOver(result);
});
}
@ -191,25 +191,25 @@ export class GameOverPhase extends BattlePhase {
}
handleUnlocks(): void {
if (this.victory && this.scene.gameMode.isClassic) {
if (!this.scene.gameData.unlocks[Unlockables.ENDLESS_MODE]) {
this.scene.unshiftPhase(new UnlockPhase(this.scene, Unlockables.ENDLESS_MODE));
if (this.victory && gScene.gameMode.isClassic) {
if (!gScene.gameData.unlocks[Unlockables.ENDLESS_MODE]) {
gScene.unshiftPhase(new UnlockPhase(Unlockables.ENDLESS_MODE));
}
if (this.scene.getParty().filter(p => p.fusionSpecies).length && !this.scene.gameData.unlocks[Unlockables.SPLICED_ENDLESS_MODE]) {
this.scene.unshiftPhase(new UnlockPhase(this.scene, Unlockables.SPLICED_ENDLESS_MODE));
if (gScene.getParty().filter(p => p.fusionSpecies).length && !gScene.gameData.unlocks[Unlockables.SPLICED_ENDLESS_MODE]) {
gScene.unshiftPhase(new UnlockPhase(Unlockables.SPLICED_ENDLESS_MODE));
}
if (!this.scene.gameData.unlocks[Unlockables.MINI_BLACK_HOLE]) {
this.scene.unshiftPhase(new UnlockPhase(this.scene, Unlockables.MINI_BLACK_HOLE));
if (!gScene.gameData.unlocks[Unlockables.MINI_BLACK_HOLE]) {
gScene.unshiftPhase(new UnlockPhase(Unlockables.MINI_BLACK_HOLE));
}
if (!this.scene.gameData.unlocks[Unlockables.EVIOLITE] && this.scene.getParty().some(p => p.getSpeciesForm(true).speciesId in pokemonEvolutions)) {
this.scene.unshiftPhase(new UnlockPhase(this.scene, Unlockables.EVIOLITE));
if (!gScene.gameData.unlocks[Unlockables.EVIOLITE] && gScene.getParty().some(p => p.getSpeciesForm(true).speciesId in pokemonEvolutions)) {
gScene.unshiftPhase(new UnlockPhase(Unlockables.EVIOLITE));
}
}
}
awardRibbon(pokemon: Pokemon, forStarter: boolean = false): void {
const speciesId = getPokemonSpecies(pokemon.species.speciesId);
const speciesRibbonCount = this.scene.gameData.incrementRibbonCount(speciesId, forStarter);
const speciesRibbonCount = gScene.gameData.incrementRibbonCount(speciesId, forStarter);
// first time classic win, award voucher
if (speciesRibbonCount === 1) {
this.firstRibbons.push(getPokemonSpecies(pokemon.species.getRootSpeciesId(forStarter)));

View File

@ -1,14 +1,14 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { BattlePhase } from "./battle-phase";
export class HidePartyExpBarPhase extends BattlePhase {
constructor(scene: BattleScene) {
super(scene);
constructor() {
super();
}
start() {
super.start();
this.scene.partyExpBar.hide().then(() => this.end());
gScene.partyExpBar.hide().then(() => this.end());
}
}

View File

@ -1,4 +1,4 @@
import BattleScene from "#app/battle-scene";
import { gScene } from "#app/battle-scene";
import { initMoveAnim, loadMoveAnimAssets } from "#app/data/battle-anims";
import Move, { allMoves } from "#app/data/move";
import { SpeciesFormChangeMoveLearnedTrigger } from "#app/data/pokemon-forms";
@ -28,8 +28,8 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase {
private learnMoveType;
private cost: number;
constructor(scene: BattleScene, partyMemberIndex: integer, moveId: Moves, learnMoveType: LearnMoveType = LearnMoveType.LEARN_MOVE, cost: number = -1) {
super(scene, partyMemberIndex);
constructor(partyMemberIndex: integer, moveId: Moves, learnMoveType: LearnMoveType = LearnMoveType.LEARN_MOVE, cost: number = -1) {
super(partyMemberIndex);
this.moveId = moveId;
this.learnMoveType = learnMoveType;
this.cost = cost;
@ -48,8 +48,8 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase {
return this.end();
}
this.messageMode = this.scene.ui.getHandler() instanceof EvolutionSceneHandler ? Mode.EVOLUTION_SCENE : Mode.MESSAGE;
this.scene.ui.setMode(this.messageMode);
this.messageMode = gScene.ui.getHandler() instanceof EvolutionSceneHandler ? Mode.EVOLUTION_SCENE : Mode.MESSAGE;
gScene.ui.setMode(this.messageMode);
// If the Pokemon has less than 4 moves, the new move is added to the largest empty moveset index
// If it has 4 moves, the phase then checks if the player wants to replace the move itself.
if (currentMoveset.length < 4) {
@ -73,12 +73,12 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase {
const moveLimitReached = i18next.t("battle:learnMoveLimitReached", { pokemonName: getPokemonNameWithAffix(pokemon) });
const shouldReplaceQ = i18next.t("battle:learnMoveReplaceQuestion", { moveName: move.name });
const preQText = [ learnMovePrompt, moveLimitReached ].join("$");
await this.scene.ui.showTextPromise(preQText);
await this.scene.ui.showTextPromise(shouldReplaceQ, undefined, false);
await this.scene.ui.setModeWithoutClear(Mode.CONFIRM,
await gScene.ui.showTextPromise(preQText);
await gScene.ui.showTextPromise(shouldReplaceQ, undefined, false);
await gScene.ui.setModeWithoutClear(Mode.CONFIRM,
() => this.forgetMoveProcess(move, pokemon), // Yes
() => { // No
this.scene.ui.setMode(this.messageMode);
gScene.ui.setMode(this.messageMode);
this.rejectMoveAndEnd(move, pokemon);
}
);
@ -96,16 +96,16 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase {
* @param Pokemon The Pokemon learning the move
*/
async forgetMoveProcess(move: Move, pokemon: Pokemon) {
this.scene.ui.setMode(this.messageMode);
await this.scene.ui.showTextPromise(i18next.t("battle:learnMoveForgetQuestion"), undefined, true);
await this.scene.ui.setModeWithoutClear(Mode.SUMMARY, pokemon, SummaryUiMode.LEARN_MOVE, move, (moveIndex: integer) => {
gScene.ui.setMode(this.messageMode);
await gScene.ui.showTextPromise(i18next.t("battle:learnMoveForgetQuestion"), undefined, true);
await gScene.ui.setModeWithoutClear(Mode.SUMMARY, pokemon, SummaryUiMode.LEARN_MOVE, move, (moveIndex: integer) => {
if (moveIndex === 4) {
this.scene.ui.setMode(this.messageMode).then(() => this.rejectMoveAndEnd(move, pokemon));
gScene.ui.setMode(this.messageMode).then(() => this.rejectMoveAndEnd(move, pokemon));
return;
}
const forgetSuccessText = i18next.t("battle:learnMoveForgetSuccess", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: pokemon.moveset[moveIndex]!.getName() });
const fullText = [ i18next.t("battle:countdownPoof"), forgetSuccessText, i18next.t("battle:learnMoveAnd") ].join("$");
this.scene.ui.setMode(this.messageMode).then(() => this.learnMove(moveIndex, move, pokemon, fullText));
gScene.ui.setMode(this.messageMode).then(() => this.learnMove(moveIndex, move, pokemon, fullText));
});
}
@ -120,14 +120,14 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase {
* @param Pokemon The Pokemon learning the move
*/
async rejectMoveAndEnd(move: Move, pokemon: Pokemon) {
await this.scene.ui.showTextPromise(i18next.t("battle:learnMoveStopTeaching", { moveName: move.name }), undefined, false);
this.scene.ui.setModeWithoutClear(Mode.CONFIRM,
await gScene.ui.showTextPromise(i18next.t("battle:learnMoveStopTeaching", { moveName: move.name }), undefined, false);
gScene.ui.setModeWithoutClear(Mode.CONFIRM,
() => {
this.scene.ui.setMode(this.messageMode);
this.scene.ui.showTextPromise(i18next.t("battle:learnMoveNotLearned", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name }), undefined, true).then(() => this.end());
gScene.ui.setMode(this.messageMode);
gScene.ui.showTextPromise(i18next.t("battle:learnMoveNotLearned", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name }), undefined, true).then(() => this.end());
},
() => {
this.scene.ui.setMode(this.messageMode);
gScene.ui.setMode(this.messageMode);
this.replaceMoveCheck(move, pokemon);
}
);
@ -154,31 +154,31 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase {
pokemon.usedTMs = [];
}
pokemon.usedTMs.push(this.moveId);
this.scene.tryRemovePhase((phase) => phase instanceof SelectModifierPhase);
gScene.tryRemovePhase((phase) => phase instanceof SelectModifierPhase);
} else if (this.learnMoveType === LearnMoveType.MEMORY) {
if (this.cost !== -1) {
if (!Overrides.WAIVE_ROLL_FEE_OVERRIDE) {
this.scene.money -= this.cost;
this.scene.updateMoneyText();
this.scene.animateMoneyChanged(false);
gScene.money -= this.cost;
gScene.updateMoneyText();
gScene.animateMoneyChanged(false);
}
this.scene.playSound("se/buy");
gScene.playSound("se/buy");
} else {
this.scene.tryRemovePhase((phase) => phase instanceof SelectModifierPhase);
gScene.tryRemovePhase((phase) => phase instanceof SelectModifierPhase);
}
}
pokemon.setMove(index, this.moveId);
initMoveAnim(this.scene, this.moveId).then(() => {
loadMoveAnimAssets(this.scene, [ this.moveId ], true);
initMoveAnim(this.moveId).then(() => {
loadMoveAnimAssets([ this.moveId ], true);
});
this.scene.ui.setMode(this.messageMode);
gScene.ui.setMode(this.messageMode);
const learnMoveText = i18next.t("battle:learnMove", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name });
if (textMessage) {
await this.scene.ui.showTextPromise(textMessage);
await gScene.ui.showTextPromise(textMessage);
}
this.scene.playSound("level_up_fanfare"); // Sound loaded into game as is
this.scene.ui.showText(learnMoveText, null, () => {
this.scene.triggerPokemonFormChange(pokemon, SpeciesFormChangeMoveLearnedTrigger, true);
gScene.playSound("level_up_fanfare"); // Sound loaded into game as is
gScene.ui.showText(learnMoveText, null, () => {
gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeMoveLearnedTrigger, true);
this.end();
}, this.messageMode === Mode.EVOLUTION_SCENE ? 1000 : undefined, true);
}

Some files were not shown because too many files have changed in this diff Show More