From e2cfb40d4631311238cc6a328fe615fdff8405f9 Mon Sep 17 00:00:00 2001 From: NightKev <34855794+DayKev@users.noreply.github.com> Date: Sun, 10 Nov 2024 18:45:37 -0800 Subject: [PATCH] Rename `gScene` to `globalScene` --- src/battle-scene.ts | 18 +- src/battle.ts | 62 +-- src/data/ability.ts | 270 ++++----- src/data/arena-tag.ts | 140 ++--- src/data/balance/pokemon-evolutions.ts | 122 ++-- src/data/battle-anims.ts | 96 ++-- src/data/battler-tags.ts | 274 ++++----- src/data/berry.ts | 12 +- src/data/daily-run.ts | 6 +- src/data/egg-hatch-data.ts | 12 +- src/data/egg.ts | 46 +- src/data/move.ts | 520 +++++++++--------- .../encounters/a-trainers-test-encounter.ts | 10 +- .../encounters/absolute-avarice-encounter.ts | 58 +- .../an-offer-you-cant-refuse-encounter.ts | 14 +- .../encounters/berries-abound-encounter.ts | 38 +- .../encounters/bug-type-superfan-encounter.ts | 34 +- .../encounters/clowning-around-encounter.ts | 38 +- .../encounters/dancing-lessons-encounter.ts | 38 +- .../encounters/dark-deal-encounter.ts | 14 +- .../encounters/delibirdy-encounter.ts | 54 +- .../encounters/field-trip-encounter.ts | 18 +- .../encounters/fiery-fallout-encounter.ts | 32 +- .../encounters/fight-or-flight-encounter.ts | 26 +- .../encounters/fun-and-games-encounter.ts | 122 ++-- .../global-trade-system-encounter.ts | 164 +++--- .../encounters/lost-at-sea-encounter.ts | 8 +- .../mysterious-challengers-encounter.ts | 34 +- .../encounters/mysterious-chest-encounter.ts | 14 +- .../encounters/part-timer-encounter.ts | 82 +-- .../encounters/safari-zone-encounter.ts | 138 ++--- .../shady-vitamin-dealer-encounter.ts | 14 +- .../slumbering-snorlax-encounter.ts | 10 +- .../teleporting-hijinks-encounter.ts | 74 +-- .../the-expert-pokemon-breeder-encounter.ts | 64 +-- .../the-pokemon-salesman-encounter.ts | 8 +- .../encounters/the-strong-stuff-encounter.ts | 14 +- .../the-winstrate-challenge-encounter.ts | 44 +- .../encounters/training-session-encounter.ts | 58 +- .../encounters/trash-to-treasure-encounter.ts | 42 +- .../encounters/uncommon-breed-encounter.ts | 30 +- .../encounters/weird-dream-encounter.ts | 84 +-- .../mystery-encounter-option.ts | 12 +- .../mystery-encounter-requirements.ts | 66 +-- .../mystery-encounters/mystery-encounter.ts | 18 +- .../can-learn-move-requirement.ts | 4 +- .../utils/encounter-dialogue-utils.ts | 12 +- .../utils/encounter-phase-utils.ts | 238 ++++---- .../utils/encounter-pokemon-utils.ts | 164 +++--- .../encounter-transformation-sequence.ts | 50 +- src/data/pokeball.ts | 8 +- src/data/pokemon-forms.ts | 26 +- src/data/pokemon-species.ts | 34 +- src/data/trainer-config.ts | 38 +- src/data/weather.ts | 4 +- src/field/anims.ts | 42 +- src/field/arena.ts | 80 +-- src/field/damage-number-handler.ts | 16 +- src/field/mystery-encounter-intro.ts | 34 +- src/field/pokemon-sprite-sparkle-handler.ts | 6 +- src/field/pokemon.ts | 493 ++++++++--------- src/field/trainer.ts | 46 +- src/game-mode.ts | 10 +- src/inputs-controller.ts | 40 +- src/loading-scene.ts | 4 +- src/messages.ts | 4 +- src/modifier/modifier-type.ts | 84 +-- src/modifier/modifier.ts | 132 ++--- src/phase.ts | 8 +- src/phases/add-enemy-buff-modifier-phase.ts | 10 +- src/phases/attempt-capture-phase.ts | 110 ++-- src/phases/attempt-run-phase.ts | 24 +- src/phases/battle-end-phase.ts | 38 +- src/phases/battle-phase.ts | 14 +- src/phases/berry-phase.ts | 16 +- src/phases/check-status-effect-phase.ts | 6 +- src/phases/check-switch-phase.ts | 24 +- src/phases/command-phase.ts | 160 +++--- src/phases/common-anim-phase.ts | 4 +- src/phases/damage-phase.ts | 24 +- src/phases/egg-hatch-phase.ts | 104 ++-- src/phases/egg-lapse-phase.ts | 36 +- src/phases/egg-summary-phase.ts | 10 +- src/phases/encounter-phase.ts | 254 +++++---- src/phases/end-card-phase.ts | 22 +- src/phases/end-evolution-phase.ts | 4 +- src/phases/enemy-command-phase.ts | 12 +- src/phases/evolution-phase.ts | 130 ++--- src/phases/exp-phase.ts | 8 +- src/phases/faint-phase.ts | 72 +-- src/phases/field-phase.ts | 4 +- src/phases/form-change-phase.ts | 56 +- src/phases/game-over-modifier-reward-phase.ts | 14 +- src/phases/game-over-phase.ts | 132 ++--- src/phases/hide-party-exp-bar-phase.ts | 4 +- src/phases/learn-move-phase.ts | 56 +- src/phases/level-cap-phase.ts | 8 +- src/phases/level-up-phase.ts | 22 +- src/phases/login-phase.ts | 42 +- src/phases/message-phase.ts | 12 +- src/phases/modifier-reward-phase.ts | 8 +- src/phases/money-reward-phase.ts | 12 +- src/phases/move-anim-test-phase.ts | 6 +- src/phases/move-charge-phase.ts | 10 +- src/phases/move-effect-phase.ts | 34 +- src/phases/move-end-phase.ts | 4 +- src/phases/move-phase.ts | 48 +- src/phases/mystery-encounter-phases.ts | 196 +++---- src/phases/new-battle-phase.ts | 4 +- src/phases/new-biome-encounter-phase.ts | 18 +- src/phases/next-encounter-phase.ts | 40 +- src/phases/obtain-status-effect-phase.ts | 6 +- src/phases/party-exp-phase.ts | 4 +- src/phases/party-heal-phase.ts | 18 +- src/phases/party-member-pokemon-phase.ts | 6 +- src/phases/pokemon-anim-phase.ts | 38 +- src/phases/pokemon-heal-phase.ts | 18 +- src/phases/pokemon-phase.ts | 8 +- src/phases/post-game-over-phase.ts | 18 +- src/phases/post-summon-phase.ts | 6 +- src/phases/post-turn-status-effect-phase.ts | 10 +- src/phases/quiet-form-change-phase.ts | 30 +- src/phases/reload-session-phase.ts | 10 +- src/phases/return-phase.ts | 6 +- src/phases/ribbon-modifier-reward-phase.ts | 12 +- src/phases/scan-ivs-phase.ts | 26 +- src/phases/select-biome-phase.ts | 38 +- src/phases/select-challenge-phase.ts | 6 +- src/phases/select-gender-phase.ts | 20 +- src/phases/select-modifier-phase.ts | 118 ++-- src/phases/select-starter-phase.ts | 52 +- src/phases/select-target-phase.ts | 18 +- src/phases/shiny-sparkle-phase.ts | 4 +- src/phases/show-ability-phase.ts | 4 +- src/phases/show-party-exp-bar-phase.ts | 22 +- src/phases/show-trainer-phase.ts | 10 +- src/phases/stat-stage-change-phase.ts | 50 +- src/phases/summon-missing-phase.ts | 6 +- src/phases/summon-phase.ts | 106 ++-- src/phases/switch-biome-phase.ts | 48 +- src/phases/switch-phase.ts | 18 +- src/phases/switch-summon-phase.ts | 54 +- src/phases/title-phase.ts | 126 ++--- src/phases/toggle-double-position-phase.ts | 8 +- src/phases/trainer-message-test-phase.ts | 4 +- src/phases/trainer-victory-phase.ts | 38 +- src/phases/turn-end-phase.ts | 32 +- src/phases/turn-init-phase.ts | 29 +- src/phases/turn-start-phase.ts | 56 +- src/phases/unavailable-phase.ts | 6 +- src/phases/unlock-phase.ts | 14 +- src/phases/victory-phase.ts | 72 +-- src/phases/weather-effect-phase.ts | 12 +- src/pipelines/field-sprite.ts | 16 +- src/system/achv.ts | 66 +-- src/system/game-data.ts | 219 ++++---- src/system/game-speed.ts | 6 +- src/system/modifier-data.ts | 4 +- src/system/pokemon-data.ts | 6 +- src/system/settings/settings-gamepad.ts | 26 +- src/system/settings/settings-keyboard.ts | 31 +- src/system/settings/settings.ts | 108 ++-- src/test/enemy_command.test.ts | 6 +- src/test/moves/aurora_veil.test.ts | 8 +- src/test/moves/light_screen.test.ts | 8 +- src/test/moves/reflect.test.ts | 8 +- .../bug-type-superfan-encounter.test.ts | 1 + src/timed-event-manager.ts | 10 +- src/touch-controls.ts | 4 +- src/tutorial.ts | 42 +- src/ui-inputs.ts | 64 +-- src/ui/ability-bar.ts | 14 +- src/ui/abstact-option-select-ui-handler.ts | 20 +- src/ui/achv-bar.ts | 22 +- src/ui/achvs-ui-handler.ts | 36 +- src/ui/admin-ui-handler.ts | 30 +- src/ui/arena-flyout.ts | 36 +- src/ui/awaitable-ui-handler.ts | 4 +- src/ui/ball-ui-handler.ts | 22 +- src/ui/battle-flyout.ts | 24 +- src/ui/battle-info.ts | 122 ++-- src/ui/battle-message-ui-handler.ts | 34 +- src/ui/bgm-bar.ts | 12 +- src/ui/candy-bar.ts | 24 +- src/ui/challenges-select-ui-handler.ts | 91 ++- src/ui/char-sprite.ts | 22 +- src/ui/command-ui-handler.ts | 20 +- src/ui/confirm-ui-handler.ts | 6 +- src/ui/daily-run-scoreboard.ts | 16 +- src/ui/dropdown.ts | 12 +- src/ui/egg-counter-container.ts | 8 +- src/ui/egg-gacha-ui-handler.ts | 128 ++--- src/ui/egg-hatch-scene-handler.ts | 18 +- src/ui/egg-list-ui-handler.ts | 28 +- src/ui/egg-summary-ui-handler.ts | 32 +- src/ui/evolution-scene-handler.ts | 14 +- src/ui/fight-ui-handler.ts | 46 +- src/ui/filter-bar.ts | 8 +- src/ui/form-modal-ui-handler.ts | 6 +- src/ui/game-stats-ui-handler.ts | 26 +- src/ui/hatched-pokemon-container.ts | 14 +- src/ui/login-form-ui-handler.ts | 32 +- src/ui/menu-ui-handler.ts | 66 +-- src/ui/message-ui-handler.ts | 28 +- src/ui/modal-ui-handler.ts | 14 +- src/ui/modifier-select-ui-handler.ts | 152 ++--- src/ui/move-info-overlay.ts | 24 +- src/ui/mystery-encounter-ui-handler.ts | 54 +- src/ui/party-exp-bar.ts | 20 +- src/ui/party-ui-handler.ts | 124 ++--- src/ui/pokeball-tray.ts | 30 +- src/ui/pokemon-hatch-info-container.ts | 22 +- src/ui/pokemon-icon-anim-handler.ts | 4 +- src/ui/pokemon-info-container.ts | 86 +-- src/ui/registration-form-ui-handler.ts | 8 +- src/ui/run-history-ui-handler.ts | 50 +- src/ui/run-info-ui-handler.ts | 138 ++--- src/ui/save-slot-select-ui-handler.ts | 40 +- src/ui/saving-icon-handler.ts | 12 +- src/ui/scroll-bar.ts | 10 +- .../settings/abstract-binding-ui-handler.ts | 12 +- .../abstract-control-settings-ui-handler.ts | 34 +- .../settings/abstract-settings-ui-handler.ts | 34 +- src/ui/settings/gamepad-binding-ui-handler.ts | 18 +- .../settings/keyboard-binding-ui-handler.ts | 16 +- .../settings/move-touch-controls-handler.ts | 6 +- src/ui/settings/navigationMenu.ts | 16 +- .../settings/settings-gamepad-ui-handler.ts | 8 +- .../settings/settings-keyboard-ui-handler.ts | 22 +- src/ui/starter-container.ts | 24 +- src/ui/starter-select-ui-handler.ts | 408 +++++++------- src/ui/stats-container.ts | 18 +- src/ui/summary-ui-handler.ts | 154 +++--- src/ui/target-select-ui-handler.ts | 14 +- src/ui/text.ts | 20 +- src/ui/time-of-day-widget.ts | 22 +- src/ui/title-ui-handler.ts | 24 +- src/ui/ui-handler.ts | 8 +- src/ui/ui-theme.ts | 32 +- src/ui/ui.ts | 58 +- src/ui/unavailable-modal-ui-handler.ts | 6 +- 241 files changed, 5483 insertions(+), 5541 deletions(-) diff --git a/src/battle-scene.ts b/src/battle-scene.ts index 2b32d8d8638..5c9b357b611 100644 --- a/src/battle-scene.ts +++ b/src/battle-scene.ts @@ -99,7 +99,7 @@ import { FRIENDSHIP_GAIN_FROM_BATTLE } from "#app/data/balance/starters"; export const bypassLogin = import.meta.env.VITE_BYPASS_LOGIN === "1"; -export let gScene: BattleScene; +export let globalScene: BattleScene; const DEBUG_RNG = false; @@ -326,7 +326,7 @@ export default class BattleScene extends SceneBase { this.phaseQueuePrependSpliceIndex = -1; this.nextCommandPhaseQueue = []; this.updateGameInfo(); - gScene = this; + globalScene = this; } loadPokemonAtlas(key: string, atlasPath: string, experimental?: boolean) { @@ -348,10 +348,10 @@ export default class BattleScene extends SceneBase { 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", ++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}`); + const args = [ "RNG", ++globalScene.rngCounter, ret / (max - min), `min: ${min} / max: ${max}` ]; + args.push(`seed: ${globalScene.rngSeedOverride || globalScene.waveSeed || globalScene.seed}`); + if (globalScene.rngOffset) { + args.push(`offset: ${globalScene.rngOffset}`); } console.log(...args); return ret; @@ -364,7 +364,7 @@ export default class BattleScene extends SceneBase { } create() { - gScene.scene.remove(LoadingScene.KEY); + globalScene.scene.remove(LoadingScene.KEY); initGameSpeed.apply(this); this.inputController = new InputsController(); this.uiInputs = new UiInputs(this.inputController); @@ -2822,7 +2822,7 @@ export default class BattleScene extends SceneBase { */ applyShuffledModifiers(modifierType: Constructor, player: boolean = true, ...args: Parameters): T[] { let modifiers = (player ? this.modifiers : this.enemyModifiers).filter((m): m is T => m instanceof modifierType && m.shouldApply(...args)); - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const shuffleModifiers = mods => { if (mods.length < 1) { return mods; @@ -2831,7 +2831,7 @@ export default class BattleScene extends SceneBase { return [ mods[rand], ...shuffleModifiers(mods.filter((_, i) => i !== rand)) ]; }; modifiers = shuffleModifiers(modifiers); - }, gScene.currentBattle.turn << 4, gScene.waveSeed); + }, globalScene.currentBattle.turn << 4, globalScene.waveSeed); return this.applyModifiersInternal(modifiers, player, args); } diff --git a/src/battle.ts b/src/battle.ts index e25de24ded4..dff23ffb145 100644 --- a/src/battle.ts +++ b/src/battle.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Command } from "./ui/command-ui-handler"; import * as Utils from "./utils"; import Trainer, { TrainerVariant } from "./field/trainer"; @@ -167,7 +167,7 @@ export default class Battle { } addPostBattleLoot(enemyPokemon: EnemyPokemon): void { - this.postBattleLoot.push(...gScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === enemyPokemon.id && m.isTransferable, false).map(i => { + this.postBattleLoot.push(...globalScene.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; @@ -176,39 +176,39 @@ export default class Battle { } pickUpScatteredMoney(): void { - const moneyAmount = new Utils.IntegerHolder(gScene.currentBattle.moneyScattered); - gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); + const moneyAmount = new Utils.IntegerHolder(globalScene.currentBattle.moneyScattered); + globalScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); - if (gScene.arena.getTag(ArenaTagType.HAPPY_HOUR)) { + if (globalScene.arena.getTag(ArenaTagType.HAPPY_HOUR)) { moneyAmount.value *= 2; } - gScene.addMoney(moneyAmount.value); + globalScene.addMoney(moneyAmount.value); const userLocale = navigator.language || "en-US"; const formattedMoneyAmount = moneyAmount.value.toLocaleString(userLocale); const message = i18next.t("battle:moneyPickedUp", { moneyAmount: formattedMoneyAmount }); - gScene.queueMessage(message, undefined, true); + globalScene.queueMessage(message, undefined, true); - gScene.currentBattle.moneyScattered = 0; + globalScene.currentBattle.moneyScattered = 0; } addBattleScore(): void { - let partyMemberTurnMultiplier = gScene.getEnemyParty().length / 2 + 0.5; + let partyMemberTurnMultiplier = globalScene.getEnemyParty().length / 2 + 0.5; if (this.double) { partyMemberTurnMultiplier /= 1.5; } - for (const p of gScene.getEnemyParty()) { + for (const p of globalScene.getEnemyParty()) { if (p.isBoss()) { - partyMemberTurnMultiplier *= (p.bossSegments / 1.5) / gScene.getEnemyParty().length; + partyMemberTurnMultiplier *= (p.bossSegments / 1.5) / globalScene.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); - gScene.score += finalBattleScore; + globalScene.score += finalBattleScore; console.log(`Battle Score: ${finalBattleScore} (${this.turn - 1} Turns x${Math.floor(turnMultiplier * 100) / 100})`); - console.log(`Total Score: ${gScene.score}`); - gScene.updateScoreText(); + console.log(`Total Score: ${globalScene.score}`); + globalScene.updateScoreText(); } getBgmOverride(): string | null { @@ -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 (gScene.musicPreference === 0) { + if (globalScene.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 (gScene.musicPreference === 0) { + if (globalScene.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 (gScene.gameMode.isClassic && this.waveIndex <= 4) { + if (globalScene.gameMode.isClassic && this.waveIndex <= 4) { return "battle_wild"; } @@ -391,8 +391,8 @@ export default class Battle { if (range <= 1) { return min; } - const tempRngCounter = gScene.rngCounter; - const tempSeedOverride = gScene.rngSeedOverride; + const tempRngCounter = globalScene.rngCounter; + const tempSeedOverride = globalScene.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); } - gScene.rngCounter = this.rngCounter++; - gScene.rngSeedOverride = this.battleSeed; + globalScene.rngCounter = this.rngCounter++; + globalScene.rngSeedOverride = this.battleSeed; const ret = Utils.randSeedInt(range, min); this.battleSeedState = Phaser.Math.RND.state(); Phaser.Math.RND.state(state); - gScene.rngCounter = tempRngCounter; - gScene.rngSeedOverride = tempSeedOverride; + globalScene.rngCounter = tempRngCounter; + globalScene.rngSeedOverride = tempSeedOverride; return ret; } @@ -420,7 +420,7 @@ export default class Battle { export class FixedBattle extends Battle { constructor(waveIndex: number, config: FixedBattleConfig) { - super(gScene.gameMode, waveIndex, config.battleType, config.battleType === BattleType.TRAINER ? config.getTrainer() : undefined, config.double); + super(globalScene.gameMode, waveIndex, config.battleType, config.battleType === BattleType.TRAINER ? config.getTrainer() : undefined, config.double); if (config.getEnemyParty) { this.enemyParty = config.getEnemyParty(); } @@ -482,7 +482,7 @@ function getRandomTrainerFunc(trainerPool: (TrainerType | TrainerType[])[], rand const rand = Utils.randSeedInt(trainerPool.length); const trainerTypes: TrainerType[] = []; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { for (const trainerPoolEntry of trainerPool) { const trainerType = Array.isArray(trainerPoolEntry) ? Utils.randSeedItem(trainerPoolEntry) @@ -524,14 +524,14 @@ export const classicFixedBattles: FixedBattleConfigs = { [5]: new FixedBattleConfig().setBattleType(BattleType.TRAINER) .setGetTrainerFunc(() => new Trainer(TrainerType.YOUNGSTER, Utils.randSeedInt(2) ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)), [8]: new FixedBattleConfig().setBattleType(BattleType.TRAINER) - .setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)), + .setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL, globalScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)), [25]: new FixedBattleConfig().setBattleType(BattleType.TRAINER) - .setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_2, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)) + .setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_2, globalScene.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(() => new Trainer(TrainerType.RIVAL_3, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)) + .setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_3, globalScene.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(() => new Trainer(TrainerType.RIVAL_4, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)) + .setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_4, globalScene.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(() => new Trainer(TrainerType.RIVAL_5, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)) + .setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_5, globalScene.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(() => new Trainer(TrainerType.RIVAL_6, gScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)) + .setGetTrainerFunc(() => new Trainer(TrainerType.RIVAL_6, globalScene.gameData.gender === PlayerGender.MALE ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT)) .setCustomModifierRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.ULTRA, ModifierTier.GREAT, ModifierTier.GREAT ], allowLuckUpgrades: false }) }; diff --git a/src/data/ability.ts b/src/data/ability.ts index fe33528e449..5a2f6f59cb1 100644 --- a/src/data/ability.ts +++ b/src/data/ability.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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 gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); + return globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); } return false; @@ -251,9 +251,9 @@ export class PostBattleInitStatStageChangeAbAttr extends PostBattleInitAbAttr { for (const statStageChangePhase of statStageChangePhases) { if (!this.selfTarget && !statStageChangePhase.getPokemon()?.summonData) { - gScene.pushPhase(statStageChangePhase); + globalScene.pushPhase(statStageChangePhase); } else { // TODO: This causes the ability bar to be shown at the wrong time - gScene.unshiftPhase(statStageChangePhase); + globalScene.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; - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + globalScene.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) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ this.stat ], this.stages)); + globalScene.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) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ this.stat ], this.stages)); + globalScene.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) { - gScene.queueMessage(i18next.t("abilityTriggers:reverseDrain", { pokemonNameWithAffix: getPokemonNameWithAffix(attacker) })); + globalScene.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) { - gScene.unshiftPhase(new StatStageChangePhase((other).getBattlerIndex(), false, [ this.stat ], this.stages)); + globalScene.unshiftPhase(new StatStageChangePhase((other).getBattlerIndex(), false, [ this.stat ], this.stages)); } return true; } - gScene.unshiftPhase(new StatStageChangePhase((this.selfTarget ? pokemon : attacker).getBattlerIndex(), this.selfTarget, [ this.stat ], this.stages)); + globalScene.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) { - gScene.unshiftPhase(new StatStageChangePhase((this.selfTarget ? pokemon : attacker).getBattlerIndex(), true, this.stats, this.stages)); + globalScene.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 = gScene.arena.getTag(this.tagType) as ArenaTrapTag; - if (!gScene.arena.getTag(this.tagType) || tag.layers < tag.maxLayers) { + const tag = globalScene.arena.getTag(this.tagType) as ArenaTrapTag; + if (!globalScene.arena.getTag(this.tagType) || tag.layers < tag.maxLayers) { if (!simulated) { - gScene.arena.addTag(this.tagType, 0, undefined, pokemon.id, pokemon.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); + globalScene.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); - gScene.queueMessage(i18next.t("abilityTriggers:windPowerCharged", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name })); + globalScene.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 gScene.arena.terrain?.terrainType !== (this.terrainType || undefined); + return globalScene.arena.terrain?.terrainType !== (this.terrainType || undefined); } else { - return gScene.arena.trySetTerrain(this.terrainType, true); + return globalScene.arena.trySetTerrain(this.terrainType, true); } } @@ -932,7 +932,7 @@ export class PostDefendCritStatStageChangeAbAttr extends PostDefendAbAttr { } if (!simulated) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ this.stat ], this.stages)); + globalScene.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 (!gScene.arena.weather?.isImmutable()) { + if (!globalScene.arena.weather?.isImmutable()) { if (simulated) { - return gScene.arena.weather?.weatherType !== this.weatherType; + return globalScene.arena.weather?.weatherType !== this.weatherType; } - return gScene.arena.trySetWeather(this.weatherType, true); + return globalScene.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) { - gScene.unshiftPhase(new StatStageChangePhase((pokemon).getBattlerIndex(), true, this.statsToChange, this.stages)); + globalScene.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)]; - gScene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => { + globalScene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => { if (success) { - gScene.queueMessage(i18next.t("abilityTriggers:postAttackStealHeldItem", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), defenderName: defender.name, stolenItemType: stolenItem.type.name })); + globalScene.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 gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + return globalScene.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)]; - gScene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => { + globalScene.tryTransferHeldItemModifier(stolenItem, pokemon, false).then(success => { if (success) { - gScene.queueMessage(i18next.t("abilityTriggers:postDefendStealHeldItem", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), attackerName: attacker.name, stolenItemType: stolenItem.type.name })); + globalScene.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 gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + return globalScene.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) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], this.stages)); + globalScene.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) { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); } return true; } @@ -1926,7 +1926,7 @@ export class PostKnockOutStatStageChangeAbAttr extends PostKnockOutAbAttr { ? this.stat(pokemon) : this.stat; if (!simulated) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], this.stages)); + globalScene.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; - gScene.queueMessage(i18next.t("abilityTriggers:copyFaintedAllyAbility", { pokemonNameWithAffix: getPokemonNameWithAffix(knockedOut), abilityName: allAbilities[knockedOut.getAbility().id].name })); + globalScene.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) { - gScene.pushPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, this.stats, this.stages)); + globalScene.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 { if (!simulated) { for (const arenaTag of this.arenaTags) { - gScene.arena.removeTag(arenaTag); + globalScene.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) { - gScene.queueMessage(this.messageFunc(pokemon)); + globalScene.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) { - gScene.queueMessage(this.message); + globalScene.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) - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, this.stats, this.stages)); + globalScene.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) { - gScene.unshiftPhase(new StatStageChangePhase(opponent.getBattlerIndex(), false, this.stats, this.stages)); + globalScene.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) { - gScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(), + globalScene.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); } - gScene.queueMessage(i18next.t("abilityTriggers:postSummonClearAllyStats", { pokemonNameWithAffix: getPokemonNameWithAffix(target) })); + globalScene.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) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, this.stats, 1)); + globalScene.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) || !gScene.arena.weather?.isImmutable()) { + this.weatherType === WeatherType.STRONG_WINDS) || !globalScene.arena.weather?.isImmutable()) { if (simulated) { - return gScene.arena.weather?.weatherType !== this.weatherType; + return globalScene.arena.weather?.weatherType !== this.weatherType; } else { - return gScene.arena.trySetWeather(this.weatherType, true); + return globalScene.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 gScene.arena.terrain?.terrainType !== this.terrainType; + return globalScene.arena.terrain?.terrainType !== this.terrainType; } else { - return gScene.arena.trySetTerrain(this.terrainType, true); + return globalScene.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 || gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); + return simulated || globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); } return false; @@ -2333,7 +2333,7 @@ export class PostSummonCopyAbilityAbAttr extends PostSummonAbAttr { let target: Pokemon; if (targets.length > 1) { - gScene.executeWithSeedOffset(() => target = Utils.randSeedItem(targets), gScene.currentBattle.waveIndex); + globalScene.executeWithSeedOffset(() => target = Utils.randSeedItem(targets), globalScene.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 { - const party = pokemon instanceof PlayerPokemon ? gScene.getPlayerField() : gScene.getEnemyField(); + const party = pokemon instanceof PlayerPokemon ? globalScene.getPlayerField() : globalScene.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)) { - gScene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon))); + globalScene.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 (!gScene.currentBattle.double) { + if (!globalScene.currentBattle.double) { return false; } @@ -2455,7 +2455,7 @@ export class PostSummonTransformAbAttr extends PostSummonAbAttr { let target: Pokemon; if (targets.length > 1) { - gScene.executeWithSeedOffset(() => target = Utils.randSeedItem(targets), gScene.currentBattle.waveIndex); + globalScene.executeWithSeedOffset(() => target = Utils.randSeedItem(targets), globalScene.currentBattle.waveIndex); } else { target = targets[0]; } @@ -2489,8 +2489,8 @@ export class PostSummonTransformAbAttr extends PostSummonAbAttr { pokemon.summonData.types = target.getTypes(); promises.push(pokemon.updateInfo()); - gScene.queueMessage(i18next.t("abilityTriggers:postSummonTransform", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), targetName: target.name, })); - gScene.playSound("battle_anims/PRSFX- Transform"); + globalScene.queueMessage(i18next.t("abilityTriggers:postSummonTransform", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), targetName: target.name, })); + globalScene.playSound("battle_anims/PRSFX- Transform"); promises.push(pokemon.loadAssets(false).then(() => { pokemon.playAnim(); pokemon.updateInfo(); @@ -2523,7 +2523,7 @@ export class PostSummonWeatherSuppressedFormChangeAbAttr extends PostSummonAbAtt } if (!simulated) { - gScene.arena.triggerWeatherBasedFormChangesToNormal(); + globalScene.arena.triggerWeatherBasedFormChangesToNormal(); } return true; @@ -2563,8 +2563,8 @@ export class PostSummonFormChangeByWeatherAbAttr extends PostSummonAbAttr { return simulated; } - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeWeatherTrigger); - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeRevertWeatherFormTrigger); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeWeatherTrigger); + globalScene.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 { - const weatherType = gScene.arena.weather?.weatherType; + const weatherType = globalScene.arena.weather?.weatherType; let turnOffWeather = false; // Clear weather only if user's ability matches the weather and no other pokemon has the ability. switch (weatherType) { case (WeatherType.HARSH_SUN): if (pokemon.hasAbility(Abilities.DESOLATE_LAND) - && gScene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.DESOLATE_LAND)).length === 0) { + && globalScene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.DESOLATE_LAND)).length === 0) { turnOffWeather = true; } break; case (WeatherType.HEAVY_RAIN): if (pokemon.hasAbility(Abilities.PRIMORDIAL_SEA) - && gScene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.PRIMORDIAL_SEA)).length === 0) { + && globalScene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.PRIMORDIAL_SEA)).length === 0) { turnOffWeather = true; } break; case (WeatherType.STRONG_WINDS): if (pokemon.hasAbility(Abilities.DELTA_STREAM) - && gScene.getField(true).filter(p => p !== pokemon).filter(p => p.hasAbility(Abilities.DELTA_STREAM)).length === 0) { + && globalScene.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) { - gScene.arena.trySetWeather(WeatherType.NONE, false); + globalScene.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) { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); } return true; } @@ -3120,13 +3120,13 @@ function getSheerForceHitDisableAbCondition(): AbAttrCondition { function getWeatherCondition(...weatherTypes: WeatherType[]): AbAttrCondition { return () => { - if (!gScene?.arena) { + if (!globalScene?.arena) { return false; } - if (gScene.arena.weather?.isEffectSuppressed()) { + if (globalScene.arena.weather?.isEffectSuppressed()) { return false; } - const weatherType = gScene.arena.weather?.weatherType; + const weatherType = globalScene.arena.weather?.weatherType; return !!weatherType && weatherTypes.indexOf(weatherType) > -1; }; } @@ -3215,7 +3215,7 @@ export class ForewarnAbAttr extends PostSummonAbAttr { } } if (!simulated) { - gScene.queueMessage(i18next.t("abilityTriggers:forewarn", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: maxMove })); + globalScene.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()) { - gScene.queueMessage(i18next.t("abilityTriggers:frisk", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), opponentName: opponent.name, opponentAbilityName: opponent.getAbility().name })); + globalScene.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 = gScene.arena.weather?.weatherType; + const weatherType = globalScene.arena.weather?.weatherType; if (weatherType && this.formRevertingWeathers.includes(weatherType)) { - gScene.arena.triggerWeatherBasedFormChangesToNormal(); + globalScene.arena.triggerWeatherBasedFormChangesToNormal(); } else { - gScene.arena.triggerWeatherBasedFormChanges(); + globalScene.arena.triggerWeatherBasedFormChanges(); } return true; } @@ -3348,7 +3348,7 @@ export class PostWeatherLapseHealAbAttr extends PostWeatherLapseAbAttr { if (!pokemon.isFullHp()) { const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name; if (!simulated) { - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + globalScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), Utils.toDmgValue(pokemon.getMaxHp() / (16 / this.healFactor)), i18next.t("abilityTriggers:postWeatherLapseHeal", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName }), true)); } return true; @@ -3374,7 +3374,7 @@ export class PostWeatherLapseDamageAbAttr extends PostWeatherLapseAbAttr { if (!simulated) { const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name; - gScene.queueMessage(i18next.t("abilityTriggers:postWeatherLapseDamage", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName })); + globalScene.queueMessage(i18next.t("abilityTriggers:postWeatherLapseDamage", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName })); pokemon.damageAndUpdate(Utils.toDmgValue(pokemon.getMaxHp() / (16 / this.damageFactor)), HitResult.OTHER); } @@ -3416,7 +3416,7 @@ export class PostTerrainChangeAddBattlerTagAttr extends PostTerrainChangeAbAttr function getTerrainCondition(...terrainTypes: TerrainType[]): AbAttrCondition { return (pokemon: Pokemon) => { - const terrainType = gScene.arena.terrain?.terrainType; + const terrainType = globalScene.arena.terrain?.terrainType; return !!terrainType && terrainTypes.indexOf(terrainType) > -1; }; } @@ -3453,7 +3453,7 @@ export class PostTurnStatusHealAbAttr extends PostTurnAbAttr { if (!pokemon.isFullHp()) { if (!simulated) { const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name; - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + globalScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), Utils.toDmgValue(pokemon.getMaxHp() / 8), i18next.t("abilityTriggers:poisonHeal", { pokemonName: getPokemonNameWithAffix(pokemon), abilityName }), true)); } return true; @@ -3484,7 +3484,7 @@ export class PostTurnResetStatusAbAttr extends PostTurnAbAttr { } if (this.target?.status) { if (!simulated) { - gScene.queueMessage(getStatusEffectHealText(this.target.status?.effect, getPokemonNameWithAffix(this.target))); + globalScene.queueMessage(getStatusEffectHealText(this.target.status?.effect, getPokemonNameWithAffix(this.target))); this.target.resetStatus(false); this.target.updateInfo(); } @@ -3549,7 +3549,7 @@ export class PostTurnLootAbAttr extends PostTurnAbAttr { const chosenBerry = new BerryModifierType(chosenBerryType); berriesEaten.splice(randomIdx); // Remove berry from memory - const berryModifier = gScene.findModifier( + const berryModifier = globalScene.findModifier( (m) => m instanceof BerryModifier && m.berryType === chosenBerryType, pokemon.isPlayer() ) as BerryModifier | undefined; @@ -3557,16 +3557,16 @@ export class PostTurnLootAbAttr extends PostTurnAbAttr { if (!berryModifier) { const newBerry = new BerryModifier(chosenBerry, pokemon.id, chosenBerryType, 1); if (pokemon.isPlayer()) { - gScene.addModifier(newBerry); + globalScene.addModifier(newBerry); } else { - gScene.addEnemyModifier(newBerry); + globalScene.addEnemyModifier(newBerry); } } else if (berryModifier.stackCount < berryModifier.getMaxHeldItemCount(pokemon)) { berryModifier.stackCount++; } - gScene.queueMessage(i18next.t("abilityTriggers:postTurnLootCreateEatenBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), berryName: chosenBerry.name })); - gScene.updateModifiers(pokemon.isPlayer()); + globalScene.queueMessage(i18next.t("abilityTriggers:postTurnLootCreateEatenBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), berryName: chosenBerry.name })); + globalScene.updateModifiers(pokemon.isPlayer()); return true; } @@ -3599,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); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ raisedStat ], 2)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ raisedStat ], 2)); } if (canLower.length > 0) { const loweredStat = canLower[pokemon.randSeedInt(canLower.length)]; - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ loweredStat ], -1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ loweredStat ], -1)); } } @@ -3620,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) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPD ], 1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPD ], 1)); } else { return false; } @@ -3634,7 +3634,7 @@ export class PostTurnHealAbAttr extends PostTurnAbAttr { if (!pokemon.isFullHp()) { if (!simulated) { const abilityName = (!passive ? pokemon.getAbility() : pokemon.getPassiveAbility()).name; - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + globalScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), Utils.toDmgValue(pokemon.getMaxHp() / 16), i18next.t("abilityTriggers:postTurnHeal", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName }), true)); } @@ -3658,7 +3658,7 @@ export class PostTurnFormChangeAbAttr extends PostTurnAbAttr { const formIndex = this.formFunc(pokemon); if (formIndex !== pokemon.formIndex) { if (!simulated) { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger, false); } return true; @@ -3688,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); - gScene.queueMessage(i18next.t("abilityTriggers:badDreams", { pokemonName: getPokemonNameWithAffix(opp) })); + globalScene.queueMessage(i18next.t("abilityTriggers:badDreams", { pokemonName: getPokemonNameWithAffix(opp) })); } hadEffect = true; } @@ -3718,11 +3718,11 @@ export class FetchBallAbAttr extends PostTurnAbAttr { if (simulated) { return false; } - const lastUsed = gScene.currentBattle.lastUsedPokeball; + const lastUsed = globalScene.currentBattle.lastUsedPokeball; if (lastUsed !== null && !!pokemon.isPlayer) { - gScene.pokeballCounts[lastUsed]++; - gScene.currentBattle.lastUsedPokeball = null; - gScene.queueMessage(i18next.t("abilityTriggers:fetchBall", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), pokeballName: getPokeballName(lastUsed) })); + globalScene.pokeballCounts[lastUsed]++; + globalScene.currentBattle.lastUsedPokeball = null; + globalScene.queueMessage(i18next.t("abilityTriggers:fetchBall", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), pokeballName: getPokeballName(lastUsed) })); return true; } return false; @@ -3741,11 +3741,11 @@ export class PostBiomeChangeWeatherChangeAbAttr extends PostBiomeChangeAbAttr { } apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean { - if (!gScene.arena.weather?.isImmutable()) { + if (!globalScene.arena.weather?.isImmutable()) { if (simulated) { - return gScene.arena.weather?.weatherType !== this.weatherType; + return globalScene.arena.weather?.weatherType !== this.weatherType; } else { - return gScene.arena.trySetWeather(this.weatherType, true); + return globalScene.arena.trySetWeather(this.weatherType, true); } } @@ -3764,9 +3764,9 @@ export class PostBiomeChangeTerrainChangeAbAttr extends PostBiomeChangeAbAttr { apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean { if (simulated) { - return gScene.arena.terrain?.terrainType !== this.terrainType; + return globalScene.arena.terrain?.terrainType !== this.terrainType; } else { - return gScene.arena.trySetTerrain(this.terrainType, true); + return globalScene.arena.trySetTerrain(this.terrainType, true); } } } @@ -3808,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); - gScene.unshiftPhase(new MovePhase(dancer, target, move, true, true)); + globalScene.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 - gScene.unshiftPhase(new MovePhase(dancer, [ dancer.getBattlerIndex() ], move, true, true)); + globalScene.unshiftPhase(new MovePhase(dancer, [ dancer.getBattlerIndex() ], move, true, true)); } } return true; @@ -3853,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 { if (!simulated) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, (args[0] as BattleStat[]), (args[1] as number), true, false, false)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, (args[0] as BattleStat[]), (args[1] as number), true, false, false)); } return true; } @@ -3930,7 +3930,7 @@ 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) { - gScene.unshiftPhase( + globalScene.unshiftPhase( new PokemonHealPhase( pokemon.getBattlerIndex(), Utils.toDmgValue(pokemon.getMaxHp() * this.healPercent), @@ -4033,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 = gScene.currentBattle.postBattleLoot; + const postBattleLoot = globalScene.currentBattle.postBattleLoot; if (!simulated && postBattleLoot.length) { const randItem = Utils.randSeedItem(postBattleLoot); //@ts-ignore - TODO see below - if (gScene.tryTransferHeldItemModifier(randItem, pokemon, true, 1, true)) { // TODO: fix. This is a promise!? + if (globalScene.tryTransferHeldItemModifier(randItem, pokemon, true, 1, true)) { // TODO: fix. This is a promise!? postBattleLoot.splice(postBattleLoot.indexOf(randItem), 1); - gScene.queueMessage(i18next.t("abilityTriggers:postBattleLoot", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), itemName: randItem.type.name })); + globalScene.queueMessage(i18next.t("abilityTriggers:postBattleLoot", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), itemName: randItem.type.name })); return true; } } @@ -4079,7 +4079,7 @@ export class PostFaintUnsuppressedWeatherFormChangeAbAttr extends PostFaintAbAtt } if (!simulated) { - gScene.arena.triggerWeatherBasedFormChanges(); + globalScene.arena.triggerWeatherBasedFormChanges(); } return true; @@ -4101,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 = gScene.arena.weather?.weatherType; + const weatherType = globalScene.arena.weather?.weatherType; let turnOffWeather = false; // Clear weather only if user's ability matches the weather and no other pokemon has the ability. switch (weatherType) { case (WeatherType.HARSH_SUN): if (pokemon.hasAbility(Abilities.DESOLATE_LAND) - && gScene.getField(true).filter(p => p.hasAbility(Abilities.DESOLATE_LAND)).length === 0) { + && globalScene.getField(true).filter(p => p.hasAbility(Abilities.DESOLATE_LAND)).length === 0) { turnOffWeather = true; } break; case (WeatherType.HEAVY_RAIN): if (pokemon.hasAbility(Abilities.PRIMORDIAL_SEA) - && gScene.getField(true).filter(p => p.hasAbility(Abilities.PRIMORDIAL_SEA)).length === 0) { + && globalScene.getField(true).filter(p => p.hasAbility(Abilities.PRIMORDIAL_SEA)).length === 0) { turnOffWeather = true; } break; case (WeatherType.STRONG_WINDS): if (pokemon.hasAbility(Abilities.DELTA_STREAM) - && gScene.getField(true).filter(p => p.hasAbility(Abilities.DELTA_STREAM)).length === 0) { + && globalScene.getField(true).filter(p => p.hasAbility(Abilities.DELTA_STREAM)).length === 0) { turnOffWeather = true; } break; @@ -4131,7 +4131,7 @@ export class PostFaintClearWeatherAbAttr extends PostFaintAbAttr { } if (turnOffWeather) { - gScene.arena.trySetWeather(WeatherType.NONE, false); + globalScene.arena.trySetWeather(WeatherType.NONE, false); return true; } @@ -4151,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); - gScene.getField(true).map(p => applyAbAttrs(FieldPreventExplosiveMovesAbAttr, p, cancelled, simulated)); + globalScene.getField(true).map(p => applyAbAttrs(FieldPreventExplosiveMovesAbAttr, p, cancelled, simulated)); if (cancelled.value || attacker.hasAbilityWithAttr(BlockNonDirectDamageAbAttr)) { return false; } @@ -4282,7 +4282,7 @@ export class FlinchStatStageChangeAbAttr extends FlinchEffectAbAttr { apply(pokemon: Pokemon, passive: boolean, simulated: boolean, cancelled: Utils.BooleanHolder, args: any[]): boolean { if (!simulated) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, this.stats, this.stages)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, this.stats, this.stages)); } return true; } @@ -4500,7 +4500,7 @@ export class MoneyAbAttr extends PostBattleAbAttr { */ applyPostBattle(pokemon: Pokemon, passive: boolean, simulated: boolean, args: any[]): boolean { if (!simulated) { - gScene.currentBattle.moneyScattered += gScene.getWaveMoneyAmount(0.2); + globalScene.currentBattle.moneyScattered += globalScene.getWaveMoneyAmount(0.2); } return true; } @@ -4543,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 (gScene.arena.getTagOnSide(this.tagType, side)) { + if (globalScene.arena.getTagOnSide(this.tagType, side)) { return super.applyPostSummon(pokemon, passive, simulated, args); } return false; @@ -4641,7 +4641,7 @@ export class BypassSpeedChanceAbAttr extends AbAttr { if (!bypassSpeed.value && pokemon.randSeedInt(100) < this.chance) { const turnCommand = - gScene.currentBattle.turnCommands[pokemon.getBattlerIndex()]; + globalScene.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; @@ -4683,7 +4683,7 @@ export class PreventBypassSpeedChanceAbAttr extends AbAttr { const bypassSpeed = args[0] as Utils.BooleanHolder; const canCheckHeldItems = args[1] as Utils.BooleanHolder; - const turnCommand = gScene.currentBattle.turnCommands[pokemon.getBattlerIndex()]; + const turnCommand = globalScene.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) { @@ -4708,7 +4708,7 @@ export class TerrainEventTypeChangeAbAttr extends PostSummonAbAttr { if (pokemon.isTerastallized()) { return false; } - const currentTerrain = gScene.arena.getTerrainType(); + const currentTerrain = globalScene.arena.getTerrainType(); const typeChange: Type[] = this.determineTypeChange(pokemon, currentTerrain); if (typeChange.length !== 0) { if (pokemon.summonData.addedType && typeChange.includes(pokemon.summonData.addedType)) { @@ -4755,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 { - if (gScene.arena.getTerrainType() !== TerrainType.NONE) { + if (globalScene.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 = gScene.arena.getTerrainType(); + const currentTerrain = globalScene.arena.getTerrainType(); const pokemonNameWithAffix = getPokemonNameWithAffix(pokemon); if (currentTerrain === TerrainType.NONE) { return i18next.t("abilityTriggers:pokemonTypeChangeRevert", { pokemonNameWithAffix }); @@ -4794,7 +4794,7 @@ async function applyAbAttrsInternal( continue; } - gScene.setPhaseQueueSplice(); + globalScene.setPhaseQueueSplice(); let result = applyFunc(attr, passive); // TODO Remove this when promises get reworked @@ -4810,7 +4810,7 @@ async function applyAbAttrsInternal( } if (attr.showAbility && !simulated) { if (showAbilityInstant) { - gScene.abilityBar.showAbility(pokemon, passive); + globalScene.abilityBar.showAbility(pokemon, passive); } else { queueShowAbility(pokemon, passive); } @@ -4818,13 +4818,13 @@ async function applyAbAttrsInternal( const message = attr.getTriggerMessage(pokemon, ability.name, args); if (message) { if (!simulated) { - gScene.queueMessage(message); + globalScene.queueMessage(message); } } messages.push(message!); } } - gScene.clearPhaseQueueSplice(); + globalScene.clearPhaseQueueSplice(); } } @@ -4967,8 +4967,8 @@ export function applyPostFaintAbAttrs(attrType: Constructor, } function queueShowAbility(pokemon: Pokemon, passive: boolean): void { - gScene.unshiftPhase(new ShowAbilityPhase(pokemon.id, passive)); - gScene.clearPhaseQueueSplice(); + globalScene.unshiftPhase(new ShowAbilityPhase(pokemon.id, passive)); + globalScene.clearPhaseQueueSplice(); } /** @@ -4986,7 +4986,7 @@ function setAbilityRevealed(pokemon: Pokemon): void { * Returns the Pokemon with weather-based forms */ function getPokemonWithWeatherBasedForms() { - return gScene.getField(true).filter(p => + return globalScene.getField(true).filter(p => (p.hasAbility(Abilities.FORECAST) && p.species.speciesId === Species.CASTFORM) || (p.hasAbility(Abilities.FLOWER_GIFT) && p.species.speciesId === Species.CHERRIM) ); @@ -5082,7 +5082,7 @@ export function initAbilities() { .attr(UnswappableAbilityAbAttr) .ignorable(), new Ability(Abilities.LEVITATE, 3) - .attr(AttackTypeImmunityAbAttr, Type.GROUND, (pokemon: Pokemon) => !pokemon.getTag(GroundedTag) && !gScene.arena.getTag(ArenaTagType.GRAVITY)) + .attr(AttackTypeImmunityAbAttr, Type.GROUND, (pokemon: Pokemon) => !pokemon.getTag(GroundedTag) && !globalScene.arena.getTag(ArenaTagType.GRAVITY)) .ignorable(), new Ability(Abilities.EFFECT_SPORE, 3) .attr(EffectSporeAbAttr), @@ -5174,10 +5174,10 @@ export function initAbilities() { new Ability(Abilities.CUTE_CHARM, 3) .attr(PostDefendContactApplyTagChanceAbAttr, 30, BattlerTagType.INFATUATED), new Ability(Abilities.PLUS, 3) - .conditionalAttr(p => gScene.currentBattle.double && [ Abilities.PLUS, Abilities.MINUS ].some(a => p.getAlly().hasAbility(a)), StatMultiplierAbAttr, Stat.SPATK, 1.5) + .conditionalAttr(p => globalScene.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 => gScene.currentBattle.double && [ Abilities.PLUS, Abilities.MINUS ].some(a => p.getAlly().hasAbility(a)), StatMultiplierAbAttr, Stat.SPATK, 1.5) + .conditionalAttr(p => globalScene.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) @@ -5454,8 +5454,8 @@ export function initAbilities() { .ignorable(), new Ability(Abilities.ANALYTIC, 5) .attr(MovePowerBoostAbAttr, (user, target, move) => - !!target?.getLastXMoves(1).find(m => m.turn === gScene.currentBattle.turn) - || gScene.currentBattle.turnCommands[target?.getBattlerIndex() ?? BattlerIndex.ATTACKER]?.command !== Command.FIGHT, 1.3), + !!target?.getLastXMoves(1).find(m => m.turn === globalScene.currentBattle.turn) + || globalScene.currentBattle.turnCommands[target?.getBattlerIndex() ?? BattlerIndex.ATTACKER]?.command !== Command.FIGHT, 1.3), new Ability(Abilities.ILLUSION, 5) .attr(UncopiableAbilityAbAttr) .attr(UnswappableAbilityAbAttr) @@ -5576,9 +5576,9 @@ export function initAbilities() { .attr(FieldMoveTypePowerBoostAbAttr, Type.FAIRY, 4 / 3), new Ability(Abilities.AURA_BREAK, 6) .ignorable() - .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)), + .conditionalAttr(pokemon => globalScene.getField(true).some(p => p.hasAbility(Abilities.DARK_AURA)), FieldMoveTypePowerBoostAbAttr, Type.DARK, 9 / 16) + .conditionalAttr(pokemon => globalScene.getField(true).some(p => p.hasAbility(Abilities.FAIRY_AURA)), FieldMoveTypePowerBoostAbAttr, Type.FAIRY, 9 / 16) + .conditionalAttr(pokemon => globalScene.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) @@ -5621,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) => gScene.currentBattle.turnCommands[target?.getBattlerIndex() ?? BattlerIndex.ATTACKER]?.command === Command.POKEMON, 2), + .attr(MovePowerBoostAbAttr, (user, target, move) => globalScene.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) @@ -5992,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() ? gScene.currentBattle.playerFaints : gScene.currentBattle.enemyFaints, 5)) + .attr(VariableMovePowerBoostAbAttr, (user, target, move) => 1 + 0.1 * Math.min(user.isPlayer() ? globalScene.currentBattle.playerFaints : globalScene.currentBattle.enemyFaints, 5)) .partial(), // Counter resets every wave instead of on arena reset new Ability(Abilities.COSTAR, 9) .attr(PostSummonCopyAllyStatsAbAttr), diff --git a/src/data/arena-tag.ts b/src/data/arena-tag.ts index 8c1acbd1ac5..ec64d80f52c 100644 --- a/src/data/arena-tag.ts +++ b/src/data/arena-tag.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Arena } from "#app/field/arena"; import { Type } from "#app/data/type"; import { BooleanHolder, NumberHolder, toDmgValue } from "#app/utils"; @@ -44,7 +44,7 @@ export abstract class ArenaTag { onRemove(arena: Arena, quiet: boolean = false): void { if (!quiet) { - gScene.queueMessage(i18next.t(`arenaTag:arenaOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: this.getMoveName() })); + globalScene.queueMessage(i18next.t(`arenaTag:arenaOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: this.getMoveName() })); } } @@ -78,7 +78,7 @@ export abstract class ArenaTag { * @returns The source {@linkcode Pokemon} or `null` if none is found */ public getSourcePokemon(): Pokemon | null { - return this.sourceId ? gScene.getPokemonById(this.sourceId) : null; + return this.sourceId ? globalScene.getPokemonById(this.sourceId) : null; } /** @@ -89,12 +89,12 @@ export abstract class ArenaTag { public getAffectedPokemon(): Pokemon[] { switch (this.side) { case ArenaTagSide.PLAYER: - return gScene.getPlayerField() ?? []; + return globalScene.getPlayerField() ?? []; case ArenaTagSide.ENEMY: - return gScene.getEnemyField() ?? []; + return globalScene.getEnemyField() ?? []; case ArenaTagSide.BOTH: default: - return gScene.getField(true) ?? []; + return globalScene.getField(true) ?? []; } } } @@ -112,10 +112,10 @@ export class MistTag extends ArenaTag { super.onAdd(arena); if (this.sourceId) { - const source = gScene.getPokemonById(this.sourceId); + const source = globalScene.getPokemonById(this.sourceId); if (!quiet && source) { - gScene.queueMessage(i18next.t("arenaTag:mistOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) })); + globalScene.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) { - gScene.queueMessage(i18next.t("arenaTag:mistApply")); + globalScene.queueMessage(i18next.t("arenaTag:mistApply")); } return true; @@ -193,7 +193,7 @@ export class WeakenMoveScreenTag extends ArenaTag { if (bypassed.value) { return false; } - damageMultiplier.value = gScene.currentBattle.double ? 2732 / 4096 : 0.5; + damageMultiplier.value = globalScene.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) { - gScene.queueMessage(i18next.t(`arenaTag:reflectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.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) { - gScene.queueMessage(i18next.t(`arenaTag:lightScreenOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.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) { - gScene.queueMessage(i18next.t(`arenaTag:auroraVeilOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.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 { - gScene.queueMessage(i18next.t(`arenaTag:conditionalProtectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: super.getMoveName() })); + globalScene.queueMessage(i18next.t(`arenaTag:conditionalProtectOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`, { moveName: super.getMoveName() })); } // Removes default message for effect removal @@ -297,7 +297,7 @@ export class ConditionalProtectTag extends ArenaTag { attacker.stopMultiHit(defender); new CommonBattleAnim(CommonAnim.PROTECT, defender).play(); - gScene.queueMessage(i18next.t("arenaTag:conditionalProtectApply", { moveName: super.getMoveName(), pokemonNameWithAffix: getPokemonNameWithAffix(defender) })); + globalScene.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 = gScene.getCurrentPhase(); + const effectPhase = globalScene.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 = gScene.getPokemonById(this.sourceId); + const source = globalScene.getPokemonById(this.sourceId); if (source) { - gScene.queueMessage(i18next.t("arenaTag:matBlockOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) })); + globalScene.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 { - gScene.queueMessage(i18next.t(`arenaTag:noCritOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : "Enemy"}`, { + globalScene.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 = gScene.getPokemonById(this.sourceId!); // TODO: is this bang correct? - gScene.queueMessage(i18next.t("arenaTag:noCritOnRemove", { + const source = globalScene.getPokemonById(this.sourceId!); // TODO: is this bang correct? + globalScene.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 = gScene.getPokemonById(this.sourceId); + const user = globalScene.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 = gScene.getField()[this.battlerIndex]; + const target = globalScene.getField()[this.battlerIndex]; if (target?.isActive(true)) { - gScene.queueMessage(this.triggerMessage); - gScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(), this.healHp, null, true, false)); + globalScene.queueMessage(this.triggerMessage); + globalScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(), this.healHp, null, true, false)); } } } @@ -546,11 +546,11 @@ class MudSportTag extends WeakenMoveTypeTag { } onAdd(arena: Arena): void { - gScene.queueMessage(i18next.t("arenaTag:mudSportOnAdd")); + globalScene.queueMessage(i18next.t("arenaTag:mudSportOnAdd")); } onRemove(arena: Arena): void { - gScene.queueMessage(i18next.t("arenaTag:mudSportOnRemove")); + globalScene.queueMessage(i18next.t("arenaTag:mudSportOnRemove")); } } @@ -564,11 +564,11 @@ class WaterSportTag extends WeakenMoveTypeTag { } onAdd(arena: Arena): void { - gScene.queueMessage(i18next.t("arenaTag:waterSportOnAdd")); + globalScene.queueMessage(i18next.t("arenaTag:waterSportOnAdd")); } onRemove(arena: Arena): void { - gScene.queueMessage(i18next.t("arenaTag:waterSportOnRemove")); + globalScene.queueMessage(i18next.t("arenaTag:waterSportOnRemove")); } } @@ -584,7 +584,7 @@ export class IonDelugeTag extends ArenaTag { /** Queues an on-add message */ onAdd(arena: Arena): void { - gScene.queueMessage(i18next.t("arenaTag:plasmaFistsOnAdd")); + globalScene.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 ? gScene.getPokemonById(this.sourceId) : null; + const source = this.sourceId ? globalScene.getPokemonById(this.sourceId) : null; if (!quiet && source) { - gScene.queueMessage(i18next.t("arenaTag:spikesOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() })); + globalScene.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); - gScene.queueMessage(i18next.t("arenaTag:spikesActivateTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.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 ? gScene.getPokemonById(this.sourceId) : null; + const source = this.sourceId ? globalScene.getPokemonById(this.sourceId) : null; if (!quiet && source) { - gScene.queueMessage(i18next.t("arenaTag:toxicSpikesOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() })); + globalScene.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 (gScene.arena.removeTag(this.tagType)) { - gScene.queueMessage(i18next.t("arenaTag:toxicSpikesActivateTrapPoison", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() })); + if (globalScene.arena.removeTag(this.tagType)) { + globalScene.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) { - gScene.unshiftPhase(new MoveEffectPhase(this.sourceId!, [ this.targetIndex ], new PokemonMove(this.sourceMove!, 0, 0, true))); // TODO: are those bangs correct? + globalScene.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 ? gScene.getPokemonById(this.sourceId) : null; + const source = this.sourceId ? globalScene.getPokemonById(this.sourceId) : null; if (!quiet && source) { - gScene.queueMessage(i18next.t("arenaTag:stealthRockOnAdd", { opponentDesc: source.getOpponentDescriptor() })); + globalScene.queueMessage(i18next.t("arenaTag:stealthRockOnAdd", { opponentDesc: source.getOpponentDescriptor() })); } } @@ -863,7 +863,7 @@ class StealthRockTag extends ArenaTrapTag { return true; } const damage = toDmgValue(pokemon.getMaxHp() * damageHpRatio); - gScene.queueMessage(i18next.t("arenaTag:stealthRockActivateTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.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 ? gScene.getPokemonById(this.sourceId) : null; + const source = this.sourceId ? globalScene.getPokemonById(this.sourceId) : null; if (!quiet && source) { - gScene.queueMessage(i18next.t("arenaTag:stickyWebOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() })); + globalScene.queueMessage(i18next.t("arenaTag:stickyWebOnAdd", { moveName: this.getMoveName(), opponentDesc: source.getOpponentDescriptor() })); } } @@ -908,9 +908,9 @@ class StickyWebTag extends ArenaTrapTag { } if (!cancelled.value) { - gScene.queueMessage(i18next.t("arenaTag:stickyWebActivateTrap", { pokemonName: pokemon.getNameToRender() })); + globalScene.queueMessage(i18next.t("arenaTag:stickyWebActivateTrap", { pokemonName: pokemon.getNameToRender() })); const stages = new NumberHolder(-1); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, [ Stat.SPD ], stages.value)); + globalScene.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 ? gScene.getPokemonById(this.sourceId) : null; + const source = this.sourceId ? globalScene.getPokemonById(this.sourceId) : null; if (source) { - gScene.queueMessage(i18next.t("arenaTag:trickRoomOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) })); + globalScene.queueMessage(i18next.t("arenaTag:trickRoomOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) })); } } onRemove(arena: Arena): void { - gScene.queueMessage(i18next.t("arenaTag:trickRoomOnRemove")); + globalScene.queueMessage(i18next.t("arenaTag:trickRoomOnRemove")); } } @@ -966,8 +966,8 @@ export class GravityTag extends ArenaTag { } onAdd(arena: Arena): void { - gScene.queueMessage(i18next.t("arenaTag:gravityOnAdd")); - gScene.getField(true).forEach((pokemon) => { + globalScene.queueMessage(i18next.t("arenaTag:gravityOnAdd")); + globalScene.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 { - gScene.queueMessage(i18next.t("arenaTag:gravityOnRemove")); + globalScene.queueMessage(i18next.t("arenaTag:gravityOnRemove")); } } @@ -995,29 +995,29 @@ class TailwindTag extends ArenaTag { onAdd(arena: Arena, quiet: boolean = false): void { if (!quiet) { - gScene.queueMessage(i18next.t(`arenaTag:tailwindOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.queueMessage(i18next.t(`arenaTag:tailwindOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); } - const source = gScene.getPokemonById(this.sourceId!); //TODO: this bang is questionable! - const party = (source?.isPlayer() ? gScene.getPlayerField() : gScene.getEnemyField()) ?? []; + const source = globalScene.getPokemonById(this.sourceId!); //TODO: this bang is questionable! + const party = (source?.isPlayer() ? globalScene.getPlayerField() : globalScene.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); - gScene.queueMessage(i18next.t("abilityTriggers:windPowerCharged", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() })); + globalScene.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)) { - gScene.unshiftPhase(new ShowAbilityPhase(pokemon.getBattlerIndex())); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.ATK ], 1, true)); + globalScene.unshiftPhase(new ShowAbilityPhase(pokemon.getBattlerIndex())); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.ATK ], 1, true)); } } } onRemove(arena: Arena, quiet: boolean = false): void { if (!quiet) { - gScene.queueMessage(i18next.t(`arenaTag:tailwindOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.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 { - gScene.queueMessage(i18next.t("arenaTag:happyHourOnAdd")); + globalScene.queueMessage(i18next.t("arenaTag:happyHourOnAdd")); } onRemove(arena: Arena): void { - gScene.queueMessage(i18next.t("arenaTag:happyHourOnRemove")); + globalScene.queueMessage(i18next.t("arenaTag:happyHourOnRemove")); } } @@ -1046,11 +1046,11 @@ class SafeguardTag extends ArenaTag { } onAdd(arena: Arena): void { - gScene.queueMessage(i18next.t(`arenaTag:safeguardOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.queueMessage(i18next.t(`arenaTag:safeguardOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); } onRemove(arena: Arena): void { - gScene.queueMessage(i18next.t(`arenaTag:safeguardOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.queueMessage(i18next.t(`arenaTag:safeguardOnRemove${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); } } @@ -1082,7 +1082,7 @@ class ImprisonTag extends ArenaTrapTag { p.addTag(BattlerTagType.IMPRISON, 1, Moves.IMPRISON, this.sourceId); } }); - gScene.queueMessage(i18next.t("battlerTags:imprisonOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) })); + globalScene.queueMessage(i18next.t("battlerTags:imprisonOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(source) })); } } @@ -1135,19 +1135,19 @@ class FireGrassPledgeTag extends ArenaTag { override onAdd(arena: Arena): void { // "A sea of fire enveloped your/the opposing team!" - gScene.queueMessage(i18next.t(`arenaTag:fireGrassPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.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) - ? gScene.getPlayerField() - : gScene.getEnemyField(); + ? globalScene.getPlayerField() + : globalScene.getEnemyField(); field.filter(pokemon => !pokemon.isOfType(Type.FIRE)).forEach(pokemon => { // "{pokemonNameWithAffix} was hurt by the sea of fire!" - gScene.queueMessage(i18next.t("arenaTag:fireGrassPledgeLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("arenaTag:fireGrassPledgeLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); // TODO: Replace this with a proper animation - gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.MAGMA_STORM)); + globalScene.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!" - gScene.queueMessage(i18next.t(`arenaTag:waterFirePledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.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!" - gScene.queueMessage(i18next.t(`arenaTag:grassWaterPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); + globalScene.queueMessage(i18next.t(`arenaTag:grassWaterPledgeOnAdd${this.side === ArenaTagSide.PLAYER ? "Player" : this.side === ArenaTagSide.ENEMY ? "Enemy" : ""}`)); } } diff --git a/src/data/balance/pokemon-evolutions.ts b/src/data/balance/pokemon-evolutions.ts index 24da2a512b2..436769391ae 100644 --- a/src/data/balance/pokemon-evolutions.ts +++ b/src/data/balance/pokemon-evolutions.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Gender } from "#app/data/gender"; import { PokeballType } from "#app/data/pokeball"; import Pokemon from "#app/field/pokemon"; @@ -267,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 => 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)) + new SpeciesEvolution(Species.ALOLA_MAROWAK, 28, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), + new SpeciesEvolution(Species.MAROWAK, 28, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.TYROGUE]: [ /** @@ -288,8 +288,8 @@ export const pokemonEvolutions: PokemonEvolutions = { )), ], [Species.KOFFING]: [ - 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)) + new SpeciesEvolution(Species.GALAR_WEEZING, 35, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), + new SpeciesEvolution(Species.WEEZING, 35, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.RHYHORN]: [ new SpeciesEvolution(Species.RHYDON, 42, null, null) @@ -334,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 => 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)) + new SpeciesEvolution(Species.HISUI_TYPHLOSION, 36, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), + new SpeciesEvolution(Species.TYPHLOSION, 36, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.TOTODILE]: [ new SpeciesEvolution(Species.CROCONAW, 18, null, null) @@ -437,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 => 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)) + new SpeciesEvolution(Species.SILCOON, 7, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)), + new SpeciesEvolution(Species.CASCOON, 7, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) ], [Species.SILCOON]: [ new SpeciesEvolution(Species.BEAUTIFLY, 10, null, null) @@ -479,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 => gScene.getParty().length < 6 && gScene.pokeballCounts[PokeballType.POKEBALL] > 0)) + new SpeciesEvolution(Species.SHEDINJA, 20, null, new SpeciesEvolutionCondition(p => globalScene.getParty().length < 6 && globalScene.pokeballCounts[PokeballType.POKEBALL] > 0)) ], [Species.WHISMUR]: [ new SpeciesEvolution(Species.LOUDRED, 20, null, null) @@ -661,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 => !!gScene.gameData.dexData[Species.REMORAID].caughtAttr), SpeciesWildEvolutionDelay.MEDIUM) + new SpeciesEvolution(Species.MANTINE, 32, null, new SpeciesEvolutionCondition(p => !!globalScene.gameData.dexData[Species.REMORAID].caughtAttr), SpeciesWildEvolutionDelay.MEDIUM) ], [Species.SNOVER]: [ new SpeciesEvolution(Species.ABOMASNOW, 40, null, null) @@ -682,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 => 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)) + new SpeciesEvolution(Species.HISUI_SAMUROTT, 36, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), + new SpeciesEvolution(Species.SAMUROTT, 36, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.PATRAT]: [ new SpeciesEvolution(Species.WATCHOG, 20, null, null) @@ -833,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 => 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)) + new SpeciesEvolution(Species.HISUI_BRAVIARY, 54, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), + new SpeciesEvolution(Species.BRAVIARY, 54, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.VULLABY]: [ new SpeciesEvolution(Species.MANDIBUZZ, 54, null, null) @@ -891,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 => !!gScene.getParty().find(p => p.getTypes(false, false, true).indexOf(Type.DARK) > -1)), SpeciesWildEvolutionDelay.MEDIUM) + new SpeciesEvolution(Species.PANGORO, 32, null, new SpeciesEvolutionCondition(p => !!globalScene.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)), @@ -913,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY)) + new SpeciesEvolution(Species.TYRANTRUM, 39, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.AMAURA]: [ - new SpeciesEvolution(Species.AURORUS, 39, null, new SpeciesEvolutionCondition(p => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) + new SpeciesEvolution(Species.AURORUS, 39, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) ], [Species.GOOMY]: [ - 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)) + new SpeciesEvolution(Species.HISUI_SLIGGOO, 40, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), + new SpeciesEvolution(Species.SLIGGOO, 40, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.SLIGGOO]: [ - 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) + new SpeciesEvolution(Species.GOODRA, 50, null, new SpeciesEvolutionCondition(p => [ WeatherType.RAIN, WeatherType.FOG, WeatherType.HEAVY_RAIN ].indexOf(globalScene.arena.weather?.weatherType || WeatherType.NONE) > -1), SpeciesWildEvolutionDelay.LONG) ], [Species.BERGMITE]: [ - 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)) + new SpeciesEvolution(Species.HISUI_AVALUGG, 37, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), + new SpeciesEvolution(Species.AVALUGG, 37, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.NOIBAT]: [ new SpeciesEvolution(Species.NOIVERN, 48, null, null) @@ -936,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 => 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)) + new SpeciesEvolution(Species.HISUI_DECIDUEYE, 36, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)), + new SpeciesEvolution(Species.DECIDUEYE, 34, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.LITTEN]: [ new SpeciesEvolution(Species.TORRACAT, 17, null, null) @@ -958,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY)) + new SpeciesEvolution(Species.GUMSHOOS, 20, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.GRUBBIN]: [ new SpeciesEvolution(Species.CHARJABUG, 20, null, null) @@ -976,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY)) + new SpeciesEvolution(Species.LURANTIS, 34, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)) ], [Species.MORELULL]: [ new SpeciesEvolution(Species.SHIINOTIC, 24, null, null) @@ -1013,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) + new SpeciesEvolution(Species.ALOLA_RATICATE, 20, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) ], [Species.ALOLA_DIGLETT]: [ new SpeciesEvolution(Species.ALOLA_DUGTRIO, 26, null, null) @@ -1136,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) + new SpeciesEvolution(Species.OBSTAGOON, 35, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) ], [Species.GALAR_YAMASK]: [ new SpeciesEvolution(Species.RUNERIGUS, 34, null, null) @@ -1145,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(gScene.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(globalScene.arena.weather?.weatherType || WeatherType.NONE) > -1), SpeciesWildEvolutionDelay.LONG) ], [Species.SPRIGATITO]: [ new SpeciesEvolution(Species.FLORAGATO, 16, null, null) @@ -1184,7 +1184,7 @@ export const pokemonEvolutions: PokemonEvolutions = { [Species.TANDEMAUS]: [ new SpeciesFormEvolution(Species.MAUSHOLD, "", "three", 25, null, new SpeciesEvolutionCondition(p => { let ret = false; - gScene.executeWithSeedOffset(() => ret = !Utils.randSeedInt(4), p.id); + globalScene.executeWithSeedOffset(() => ret = !Utils.randSeedInt(4), p.id); return ret; })), new SpeciesEvolution(Species.MAUSHOLD, 25, null, null) @@ -1244,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) + new SpeciesEvolution(Species.HOUNDSTONE, 30, null, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT)) ], [Species.FRIGIBAX]: [ new SpeciesEvolution(Species.ARCTIBAX, 35, null, null) @@ -1312,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 => 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.ESPEON, "", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ESPEON, "partner", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.UMBREON, "", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.UMBREON, "partner", "", 1, null, new SpeciesFriendshipEvolutionCondition(120, p => globalScene.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), @@ -1352,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) { - gScene.executeWithSeedOffset(() => ret = !Utils.randSeedInt(4), p.id); + globalScene.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 => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT /* Razor fang at night*/), SpeciesWildEvolutionDelay.VERY_LONG) + new SpeciesEvolution(Species.GLISCOR, 1, EvolutionItem.RAZOR_FANG, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT /* Razor fang at night*/), SpeciesWildEvolutionDelay.VERY_LONG) ], [Species.SNEASEL]: [ - 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) + new SpeciesEvolution(Species.WEAVILE, 1, EvolutionItem.RAZOR_CLAW, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.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 @@ -1392,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 && (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) + new SpeciesEvolution(Species.GALAR_MR_MIME, 1, null, new SpeciesEvolutionCondition(p => p.moveset.filter(m => m?.moveId === Moves.MIMIC).length > 0 && (globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.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 && (globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY)), SpeciesWildEvolutionDelay.MEDIUM) ], [Species.PANSAGE]: [ new SpeciesEvolution(Species.SIMISAGE, 1, EvolutionItem.LEAF_STONE, null, SpeciesWildEvolutionDelay.LONG) @@ -1443,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 => (gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY) && (p.formIndex === 0))), + new SpeciesFormEvolution(Species.LYCANROC, "", "midday", 25, null, new SpeciesEvolutionCondition(p => (globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.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 => (gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT) && (p.formIndex === 0))) + new SpeciesFormEvolution(Species.LYCANROC, "", "midnight", 25, null, new SpeciesEvolutionCondition(p => (globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.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) @@ -1472,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 => 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) + new SpeciesFormEvolution(Species.ALCREMIE, "", "vanilla-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.TOWN || globalScene.arena.biomeType === Biome.PLAINS || globalScene.arena.biomeType === Biome.GRASS || globalScene.arena.biomeType === Biome.TALL_GRASS || globalScene.arena.biomeType === Biome.METROPOLIS), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ALCREMIE, "", "ruby-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.BADLANDS || globalScene.arena.biomeType === Biome.VOLCANO || globalScene.arena.biomeType === Biome.GRAVEYARD || globalScene.arena.biomeType === Biome.FACTORY || globalScene.arena.biomeType === Biome.SLUM), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ALCREMIE, "", "matcha-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.FOREST || globalScene.arena.biomeType === Biome.SWAMP || globalScene.arena.biomeType === Biome.MEADOW || globalScene.arena.biomeType === Biome.JUNGLE), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ALCREMIE, "", "mint-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.SEA || globalScene.arena.biomeType === Biome.BEACH || globalScene.arena.biomeType === Biome.LAKE || globalScene.arena.biomeType === Biome.SEABED), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ALCREMIE, "", "lemon-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.DESERT || globalScene.arena.biomeType === Biome.POWER_PLANT || globalScene.arena.biomeType === Biome.DOJO || globalScene.arena.biomeType === Biome.RUINS || globalScene.arena.biomeType === Biome.CONSTRUCTION_SITE), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ALCREMIE, "", "salted-cream", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.MOUNTAIN || globalScene.arena.biomeType === Biome.CAVE || globalScene.arena.biomeType === Biome.ICE_CAVE || globalScene.arena.biomeType === Biome.FAIRY_CAVE || globalScene.arena.biomeType === Biome.SNOWY_FOREST), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ALCREMIE, "", "ruby-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.WASTELAND || globalScene.arena.biomeType === Biome.LABORATORY), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ALCREMIE, "", "caramel-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.TEMPLE || globalScene.arena.biomeType === Biome.ISLAND), SpeciesWildEvolutionDelay.LONG), + new SpeciesFormEvolution(Species.ALCREMIE, "", "rainbow-swirl", 1, EvolutionItem.STRAWBERRY_SWEET, new SpeciesEvolutionCondition(p => globalScene.arena.biomeType === Biome.ABYSS || globalScene.arena.biomeType === Biome.SPACE || globalScene.arena.biomeType === Biome.END), SpeciesWildEvolutionDelay.LONG) ], [Species.DURALUDON]: [ new SpeciesFormEvolution(Species.ARCHALUDON, "", "", 1, EvolutionItem.METAL_ALLOY, null, SpeciesWildEvolutionDelay.VERY_LONG) @@ -1502,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY /* Razor claw at day*/), SpeciesWildEvolutionDelay.VERY_LONG) + new SpeciesEvolution(Species.SNEASLER, 1, EvolutionItem.RAZOR_CLAW, new SpeciesEvolutionCondition(p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY /* Razor claw at day*/), SpeciesWildEvolutionDelay.VERY_LONG) ], [Species.CHARCADET]: [ new SpeciesEvolution(Species.ARMAROUGE, 1, EvolutionItem.AUSPICIOUS_ARMOR, null, SpeciesWildEvolutionDelay.LONG), @@ -1582,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 => !!gScene.gameData.dexData[Species.SHELMET].caughtAttr), SpeciesWildEvolutionDelay.VERY_LONG) + new SpeciesEvolution(Species.ESCAVALIER, 1, EvolutionItem.LINKING_CORD, new SpeciesEvolutionCondition(p => !!globalScene.gameData.dexData[Species.SHELMET].caughtAttr), SpeciesWildEvolutionDelay.VERY_LONG) ], [Species.SHELMET]: [ - new SpeciesEvolution(Species.ACCELGOR, 1, EvolutionItem.LINKING_CORD, new SpeciesEvolutionCondition(p => !!gScene.gameData.dexData[Species.KARRABLAST].caughtAttr), SpeciesWildEvolutionDelay.VERY_LONG) + new SpeciesEvolution(Species.ACCELGOR, 1, EvolutionItem.LINKING_CORD, new SpeciesEvolutionCondition(p => !!globalScene.gameData.dexData[Species.KARRABLAST].caughtAttr), SpeciesWildEvolutionDelay.VERY_LONG) ], [Species.SPRITZEE]: [ new SpeciesEvolution(Species.AROMATISSE, 1, EvolutionItem.SACHET, null, SpeciesWildEvolutionDelay.VERY_LONG) @@ -1628,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.SHORT) + new SpeciesEvolution(Species.ROSELIA, 1, null, new SpeciesFriendshipEvolutionCondition(70, p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.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 => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.MEDIUM) + new SpeciesEvolution(Species.CHIMECHO, 1, null, new SpeciesFriendshipEvolutionCondition(90, p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.MEDIUM) ], [Species.HAPPINY]: [ new SpeciesEvolution(Species.CHANSEY, 1, null, new SpeciesFriendshipEvolutionCondition(160), SpeciesWildEvolutionDelay.SHORT) @@ -1643,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DAWN || gScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG) + new SpeciesEvolution(Species.LUCARIO, 1, null, new SpeciesFriendshipEvolutionCondition(120, p => globalScene.arena.getTimeOfDay() === TimeOfDay.DAWN || globalScene.arena.getTimeOfDay() === TimeOfDay.DAY), SpeciesWildEvolutionDelay.LONG) ], [Species.WOOBAT]: [ new SpeciesEvolution(Species.SWOOBAT, 1, null, new SpeciesFriendshipEvolutionCondition(90), SpeciesWildEvolutionDelay.MEDIUM) @@ -1658,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 => gScene.arena.getTimeOfDay() === TimeOfDay.DUSK || gScene.arena.getTimeOfDay() === TimeOfDay.NIGHT), SpeciesWildEvolutionDelay.MEDIUM) + new SpeciesEvolution(Species.FROSMOTH, 1, null, new SpeciesFriendshipEvolutionCondition(90, p => globalScene.arena.getTimeOfDay() === TimeOfDay.DUSK || globalScene.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 - + gScene.findModifiers(m => m instanceof MoneyMultiplierModifier + + globalScene.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 - + gScene.findModifiers(m => m instanceof MoneyMultiplierModifier + + globalScene.findModifiers(m => m instanceof MoneyMultiplierModifier || m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length > 9), SpeciesWildEvolutionDelay.VERY_LONG) ] }; diff --git a/src/data/battle-anims.ts b/src/data/battle-anims.ts index 481618e94bc..3650d4df4ad 100644 --- a/src/data/battle-anims.ts +++ b/src/data/battle-anims.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { AttackMove, BeakBlastHeaderAttr, DelayedAttackAttr, MoveFlags, SelfStatusMove, allMoves } from "./move"; import Pokemon from "../field/pokemon"; import * as Utils from "../utils"; @@ -327,11 +327,11 @@ class AnimTimedSoundEvent extends AnimTimedEvent { const soundConfig = { rate: (this.pitch * 0.01), volume: (this.volume * 0.01) }; if (this.resourceName) { try { - gScene.playSound(`battle_anims/${this.resourceName}`, soundConfig); + globalScene.playSound(`battle_anims/${this.resourceName}`, soundConfig); } catch (err) { console.error(err); } - return Math.ceil((gScene.sound.get(`battle_anims/${this.resourceName}`).totalDuration * 1000) / 33.33); + return Math.ceil((globalScene.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? } @@ -397,7 +397,7 @@ class AnimTimedUpdateBgEvent extends AnimTimedBgEvent { tweenProps["alpha"] = (this.opacity || 0) / 255; } if (Object.keys(tweenProps).length) { - gScene.tweens.add(Object.assign({ + globalScene.tweens.add(Object.assign({ targets: moveAnim.bgSprite, duration: Utils.getFrameMs(this.duration * 3) }, tweenProps)); @@ -420,20 +420,20 @@ class AnimTimedAddBgEvent extends AnimTimedBgEvent { moveAnim.bgSprite.destroy(); } moveAnim.bgSprite = this.resourceName - ? 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); + ? globalScene.add.tileSprite(this.bgX - 320, this.bgY - 284, 896, 576, this.resourceName) + : globalScene.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); - gScene.field.add(moveAnim.bgSprite); - const fieldPokemon = gScene.getNonSwitchedEnemyPokemon() || gScene.getNonSwitchedPlayerPokemon(); + globalScene.field.add(moveAnim.bgSprite); + const fieldPokemon = globalScene.getNonSwitchedEnemyPokemon() || globalScene.getNonSwitchedPlayerPokemon(); if (!isNullOrUndefined(priority)) { - gScene.field.moveTo(moveAnim.bgSprite as Phaser.GameObjects.GameObject, priority); + globalScene.field.moveTo(moveAnim.bgSprite as Phaser.GameObjects.GameObject, priority); } else if (fieldPokemon?.isOnField()) { - gScene.field.moveBelow(moveAnim.bgSprite as Phaser.GameObjects.GameObject, fieldPokemon); + globalScene.field.moveBelow(moveAnim.bgSprite as Phaser.GameObjects.GameObject, fieldPokemon); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: moveAnim.bgSprite, duration: Utils.getFrameMs(this.duration * 3) }); @@ -458,7 +458,7 @@ export function initCommonAnims(): Promise { const commonAnimFetches: Promise>[] = []; for (let ca = 0; ca < commonAnimIds.length; ca++) { const commonAnimId = commonAnimIds[ca]; - commonAnimFetches.push(gScene.cachedFetch(`./battle-anims/common-${commonAnimNames[ca].toLowerCase().replace(/\_/g, "-")}.json`) + commonAnimFetches.push(globalScene.cachedFetch(`./battle-anims/common-${commonAnimNames[ca].toLowerCase().replace(/\_/g, "-")}.json`) .then(response => response.json()) .then(cas => commonAnims.set(commonAnimId, new AnimConfig(cas)))); } @@ -491,7 +491,7 @@ export function initMoveAnim(move: Moves): Promise { const defaultMoveAnim = allMoves[move] instanceof AttackMove ? Moves.TACKLE : allMoves[move] instanceof SelfStatusMove ? Moves.FOCUS_ENERGY : Moves.TAIL_WHIP; const fetchAnimAndResolve = (move: Moves) => { - gScene.cachedFetch(`./battle-anims/${Utils.animationFileName(move)}.json`) + globalScene.cachedFetch(`./battle-anims/${Utils.animationFileName(move)}.json`) .then(response => { const contentType = response.headers.get("content-type"); if (!response.ok || contentType?.indexOf("application/json") === -1) { @@ -565,7 +565,7 @@ export async function initEncounterAnims(encounterAnim: EncounterAnim | Encounte if (encounterAnims.has(anim) && !isNullOrUndefined(encounterAnims.get(anim))) { continue; } - encounterAnimFetches.push(gScene.cachedFetch(`./battle-anims/encounter-${encounterAnimNames[anim].toLowerCase().replace(/\_/g, "-")}.json`) + encounterAnimFetches.push(globalScene.cachedFetch(`./battle-anims/encounter-${encounterAnimNames[anim].toLowerCase().replace(/\_/g, "-")}.json`) .then(response => response.json()) .then(cas => encounterAnims.set(anim, new AnimConfig(cas)))); } @@ -587,7 +587,7 @@ export function initMoveChargeAnim(chargeAnim: ChargeAnim): Promise { } } else { chargeAnims.set(chargeAnim, null); - gScene.cachedFetch(`./battle-anims/${ChargeAnim[chargeAnim].toLowerCase().replace(/\_/g, "-")}.json`) + globalScene.cachedFetch(`./battle-anims/${ChargeAnim[chargeAnim].toLowerCase().replace(/\_/g, "-")}.json`) .then(response => response.json()) .then(ca => { if (Array.isArray(ca)) { @@ -673,19 +673,19 @@ function loadAnimAssets(anims: AnimConfig[], startLoad?: boolean): Promise backgrounds.add(abg); } if (a.graphic) { - gScene.loadSpritesheet(a.graphic, "battle_anims", 96); + globalScene.loadSpritesheet(a.graphic, "battle_anims", 96); } } for (const bg of backgrounds) { - gScene.loadImage(bg, "battle_anims"); + globalScene.loadImage(bg, "battle_anims"); } for (const s of sounds) { - gScene.loadSe(s, "battle_anims", s); + globalScene.loadSe(s, "battle_anims", s); } if (startLoad) { - gScene.load.once(Phaser.Loader.Events.COMPLETE, () => resolve()); - if (!gScene.load.isLoading()) { - gScene.load.start(); + globalScene.load.once(Phaser.Loader.Events.COMPLETE, () => resolve()); + if (!globalScene.load.isLoading()) { + globalScene.load.start(); } } else { resolve(); @@ -904,7 +904,7 @@ export abstract class BattleAnim { } }; - if (!gScene.moveAnimations && !this.playRegardlessOfIssues) { + if (!globalScene.moveAnimations && !this.playRegardlessOfIssues) { return cleanUpAndComplete(); } @@ -921,7 +921,7 @@ export abstract class BattleAnim { let r = anim?.frames.length ?? 0; let f = 0; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ duration: Utils.getFrameMs(3), repeat: anim?.frames.length ?? 0, onRepeat: () => { @@ -947,19 +947,19 @@ export abstract class BattleAnim { const spriteSource = isUser ? userSprite : targetSprite; if ((isUser ? u : t) === sprites.length) { if (isUser || !targetSubstitute) { - const sprite = gScene.addPokemonSprite(isUser ? user! : target, 0, 0, spriteSource!.texture, spriteSource!.frame.name, true); // TODO: are those bangs correct? + const sprite = globalScene.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)); - gScene.field.add(sprite); + globalScene.field.add(sprite); sprites.push(sprite); } else { - const sprite = gScene.addFieldSprite(spriteSource.x, spriteSource.y, spriteSource.texture); + const sprite = globalScene.addFieldSprite(spriteSource.x, spriteSource.y, spriteSource.texture); spriteSource.on("animationupdate", (_anim, frame) => sprite.setFrame(frame.textureFrame)); - gScene.field.add(sprite); + globalScene.field.add(sprite); sprites.push(sprite); } } @@ -984,9 +984,9 @@ export abstract class BattleAnim { } else { const sprites = spriteCache[AnimFrameTarget.GRAPHIC]; if (g === sprites.length) { - const newSprite: Phaser.GameObjects.Sprite = gScene.addFieldSprite(0, 0, anim!.graphic, 1); // TODO: is the bang correct? + const newSprite: Phaser.GameObjects.Sprite = globalScene.addFieldSprite(0, 0, anim!.graphic, 1); // TODO: is the bang correct? sprites.push(newSprite); - gScene.field.add(newSprite); + globalScene.field.add(newSprite); spritePriorities.push(1); } @@ -997,22 +997,22 @@ export abstract class BattleAnim { const setSpritePriority = (priority: integer) => { switch (priority) { case 0: - 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? + globalScene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, globalScene.getNonSwitchedEnemyPokemon() || globalScene.getNonSwitchedPlayerPokemon()!); // This bang assumes that if (the EnemyPokemon is undefined, then the PlayerPokemon function must return an object), correct assumption? break; case 1: - gScene.field.moveTo(moveSprite, gScene.field.getAll().length - 1); + globalScene.field.moveTo(moveSprite, globalScene.field.getAll().length - 1); break; case 2: switch (frame.focus) { case AnimFocus.USER: if (this.bgSprite) { - gScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.bgSprite); + globalScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.bgSprite); } else { - gScene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, this.user!); // TODO: is this bang correct? + globalScene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, this.user!); // TODO: is this bang correct? } break; case AnimFocus.TARGET: - gScene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, this.target!); // TODO: is this bang correct? + globalScene.field.moveBelow(moveSprite as Phaser.GameObjects.GameObject, this.target!); // TODO: is this bang correct? break; default: setSpritePriority(1); @@ -1022,10 +1022,10 @@ export abstract class BattleAnim { case 3: switch (frame.focus) { case AnimFocus.USER: - gScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.user!); // TODO: is this bang correct? + globalScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.user!); // TODO: is this bang correct? break; case AnimFocus.TARGET: - gScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.target!); // TODO: is this bang correct? + globalScene.field.moveAbove(moveSprite as Phaser.GameObjects.GameObject, this.target!); // TODO: is this bang correct? break; default: setSpritePriority(1); @@ -1083,7 +1083,7 @@ export abstract class BattleAnim { } } if (r) { - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ duration: Utils.getFrameMs(r), onComplete: () => cleanUpAndComplete() }); @@ -1153,7 +1153,7 @@ export abstract class BattleAnim { } }; - if (!gScene.moveAnimations && !this.playRegardlessOfIssues) { + if (!globalScene.moveAnimations && !this.playRegardlessOfIssues) { return cleanUpAndComplete(); } @@ -1165,13 +1165,13 @@ export abstract class BattleAnim { let totalFrames = anim!.frames.length; let frameCount = 0; - let existingFieldSprites = gScene.field.getAll().slice(0); + let existingFieldSprites = globalScene.field.getAll().slice(0); - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ duration: Utils.getFrameMs(3) * frameTimeMult, repeat: anim!.frames.length, onRepeat: () => { - existingFieldSprites = gScene.field.getAll().slice(0); + existingFieldSprites = globalScene.field.getAll().slice(0); const spriteFrames = anim!.frames[frameCount]; const frameData = this.getGraphicFrameDataWithoutTarget(anim!.frames[frameCount], targetInitialX, targetInitialY); let graphicFrameCount = 0; @@ -1183,9 +1183,9 @@ export abstract class BattleAnim { const sprites = spriteCache[AnimFrameTarget.GRAPHIC]; if (graphicFrameCount === sprites.length) { - const newSprite: Phaser.GameObjects.Sprite = gScene.addFieldSprite(0, 0, anim!.graphic, 1); + const newSprite: Phaser.GameObjects.Sprite = globalScene.addFieldSprite(0, 0, anim!.graphic, 1); sprites.push(newSprite); - gScene.field.add(newSprite); + globalScene.field.add(newSprite); } const graphicIndex = graphicFrameCount++; @@ -1194,11 +1194,11 @@ export abstract class BattleAnim { const setSpritePriority = (priority: integer) => { if (existingFieldSprites.length > priority) { // Move to specified priority index - const index = gScene.field.getIndex(existingFieldSprites[priority]); - gScene.field.moveTo(moveSprite, index); + const index = globalScene.field.getIndex(existingFieldSprites[priority]); + globalScene.field.moveTo(moveSprite, index); } else { // Move to top of scene - gScene.field.moveTo(moveSprite, gScene.field.getAll().length - 1); + globalScene.field.moveTo(moveSprite, globalScene.field.getAll().length - 1); } }; setSpritePriority(frame.priority); @@ -1245,7 +1245,7 @@ export abstract class BattleAnim { } } if (totalFrames) { - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ duration: Utils.getFrameMs(totalFrames), onComplete: () => cleanUpAndComplete() }); @@ -1279,7 +1279,7 @@ export class MoveAnim extends BattleAnim { public move: Moves; constructor(move: Moves, user: Pokemon, target: BattlerIndex, playOnEmptyField: boolean = false) { - super(user, gScene.getField()[target], playOnEmptyField); + super(user, globalScene.getField()[target], playOnEmptyField); this.move = move; } diff --git a/src/data/battler-tags.ts b/src/data/battler-tags.ts index f1069b174bb..0d7ab757956 100644 --- a/src/data/battler-tags.ts +++ b/src/data/battler-tags.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { allAbilities, applyAbAttrs, @@ -113,7 +113,7 @@ export class BattlerTag { * @returns The source {@linkcode Pokemon} or `null` if none is found */ public getSourcePokemon(): Pokemon | null { - return this.sourceId ? gScene.getPokemonById(this.sourceId) : null; + return this.sourceId ? globalScene.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 = gScene.getCurrentPhase() as MovePhase; + const phase = globalScene.getCurrentPhase() as MovePhase; const move = phase.move; if (this.isMoveRestricted(move.moveId, pokemon)) { if (this.interruptedText(pokemon, move.moveId)) { - gScene.queueMessage(this.interruptedText(pokemon, move.moveId)); + globalScene.queueMessage(this.interruptedText(pokemon, move.moveId)); } phase.cancel(); } @@ -279,14 +279,14 @@ export class DisabledTag extends MoveRestrictionBattlerTag { this.moveId = move.move; - gScene.queueMessage(i18next.t("battlerTags:disabledOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: allMoves[this.moveId].name })); + globalScene.queueMessage(i18next.t("battlerTags:disabledOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: allMoves[this.moveId].name })); } /** @override */ override onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battlerTags:disabledLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: allMoves[this.moveId].name })); + globalScene.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) { - gScene.queueMessage(i18next.t("battlerTags:rechargingLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); - (gScene.getCurrentPhase() as MovePhase).cancel(); + globalScene.queueMessage(i18next.t("battlerTags:rechargingLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + (globalScene.getCurrentPhase() as MovePhase).cancel(); pokemon.getMoveQueue().shift(); } return super.lapse(pokemon, lapseType); @@ -428,7 +428,7 @@ export class BeakBlastChargingTag extends BattlerTag { new MoveChargeAnim(ChargeAnim.BEAK_BLAST_CHARGING, this.sourceMove, pokemon).play(); // Queue Beak Blast's header message - gScene.queueMessage(i18next.t("moveTriggers:startedHeatingUpBeak", { pokemonName: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("moveTriggers:startedHeatingUpBeak", { pokemonName: getPokemonNameWithAffix(pokemon) })); } /** @@ -463,7 +463,7 @@ export class ShellTrapTag extends BattlerTag { } onAdd(pokemon: Pokemon): void { - gScene.queueMessage(i18next.t("moveTriggers:setUpShellTrap", { pokemonName: getPokemonNameWithAffix(pokemon) })); + globalScene.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 = gScene.phaseQueue.findIndex( + const shellTrapPhaseIndex = globalScene.phaseQueue.findIndex( phase => phase instanceof MovePhase && phase.pokemon === pokemon ); - const firstMovePhaseIndex = gScene.phaseQueue.findIndex( + const firstMovePhaseIndex = globalScene.phaseQueue.findIndex( phase => phase instanceof MovePhase ); // Only shift MovePhase timing if it's not already next up if (shellTrapPhaseIndex !== -1 && shellTrapPhaseIndex !== firstMovePhaseIndex) { - const shellTrapMovePhase = gScene.phaseQueue.splice(shellTrapPhaseIndex, 1)[0]; - gScene.prependToPhase(shellTrapMovePhase, MovePhase); + const shellTrapMovePhase = globalScene.phaseQueue.splice(shellTrapPhaseIndex, 1)[0]; + globalScene.prependToPhase(shellTrapMovePhase, MovePhase); } this.activated = true; @@ -507,7 +507,7 @@ export class TrappedTag extends BattlerTag { } canAdd(pokemon: Pokemon): boolean { - const source = gScene.getPokemonById(this.sourceId!)!; + const source = globalScene.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); - gScene.queueMessage(this.getTrapMessage(pokemon)); + globalScene.queueMessage(this.getTrapMessage(pokemon)); } onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battlerTags:trappedOnRemove", { + globalScene.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) { - (gScene.getCurrentPhase() as MovePhase).cancel(); - gScene.queueMessage(i18next.t("battlerTags:flinchedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + (globalScene.getCurrentPhase() as MovePhase).cancel(); + globalScene.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 { - (gScene.getCurrentPhase() as MovePhase).cancel(); + (globalScene.getCurrentPhase() as MovePhase).cancel(); return super.lapse(pokemon, lapseType); } } @@ -627,44 +627,44 @@ export class ConfusedTag extends BattlerTag { } canAdd(pokemon: Pokemon): boolean { - return gScene.arena.terrain?.terrainType !== TerrainType.MISTY || !pokemon.isGrounded(); + return globalScene.arena.terrain?.terrainType !== TerrainType.MISTY || !pokemon.isGrounded(); } onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.CONFUSION)); - gScene.queueMessage(i18next.t("battlerTags:confusedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.CONFUSION)); + globalScene.queueMessage(i18next.t("battlerTags:confusedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battlerTags:confusedOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:confusedOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } onOverlap(pokemon: Pokemon): void { super.onOverlap(pokemon); - gScene.queueMessage(i18next.t("battlerTags:confusedOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.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) { - gScene.queueMessage(i18next.t("battlerTags:confusedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); - gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.CONFUSION)); + globalScene.queueMessage(i18next.t("battlerTags:confusedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.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)); - gScene.queueMessage(i18next.t("battlerTags:confusedLapseHurtItself")); + globalScene.queueMessage(i18next.t("battlerTags:confusedLapseHurtItself")); pokemon.damageAndUpdate(damage); pokemon.battleData.hitCount++; - (gScene.getCurrentPhase() as MovePhase).cancel(); + (globalScene.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 ? gScene.getPokemonById(this.sourceId) : null; + const source = this.sourceId ? globalScene.getPokemonById(this.sourceId) : null; if (!source?.isFainted()) { return true; } @@ -709,11 +709,11 @@ export class DestinyBondTag extends BattlerTag { } if (pokemon.isBossImmune()) { - gScene.queueMessage(i18next.t("battlerTags:destinyBondLapseIsBoss", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:destinyBondLapseIsBoss", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); return false; } - gScene.queueMessage( + globalScene.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 = gScene.getPokemonById(this.sourceId); + const pkm = globalScene.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); - gScene.queueMessage( + globalScene.queueMessage( i18next.t("battlerTags:infatuatedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), - sourcePokemonName: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined) // TODO: is that bang correct? + sourcePokemonName: getPokemonNameWithAffix(globalScene.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); - gScene.queueMessage(i18next.t("battlerTags:infatuatedOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.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) { - gScene.queueMessage( + globalScene.queueMessage( i18next.t("battlerTags:infatuatedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), - sourcePokemonName: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined) // TODO: is that bang correct? + sourcePokemonName: getPokemonNameWithAffix(globalScene.getPokemonById(this.sourceId!) ?? undefined) // TODO: is that bang correct? }) ); - gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.ATTRACT)); + globalScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.ATTRACT)); if (pokemon.randSeedInt(2)) { - gScene.queueMessage(i18next.t("battlerTags:infatuatedLapseImmobilize", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); - (gScene.getCurrentPhase() as MovePhase).cancel(); + globalScene.queueMessage(i18next.t("battlerTags:infatuatedLapseImmobilize", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + (globalScene.getCurrentPhase() as MovePhase).cancel(); } } @@ -786,7 +786,7 @@ export class InfatuatedTag extends BattlerTag { onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battlerTags:infatuatedOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.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); - gScene.queueMessage(i18next.t("battlerTags:seededOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); - this.sourceIndex = gScene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct? + globalScene.queueMessage(i18next.t("battlerTags:seededOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + this.sourceIndex = globalScene.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) { - gScene.unshiftPhase(new CommonAnimPhase(source.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.LEECH_SEED)); + globalScene.unshiftPhase(new CommonAnimPhase(source.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.LEECH_SEED)); const damage = pokemon.damageAndUpdate(toDmgValue(pokemon.getMaxHp() / 8)); const reverseDrain = pokemon.hasAbilityWithAttr(ReverseDrainAbAttr, false); - gScene.unshiftPhase(new PokemonHealPhase(source.getBattlerIndex(), + globalScene.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); - gScene.queueMessage(i18next.t("battlerTags:nightmareOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:nightmareOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } onOverlap(pokemon: Pokemon): void { super.onOverlap(pokemon); - gScene.queueMessage(i18next.t("battlerTags:nightmareOnOverlap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.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) { - gScene.queueMessage(i18next.t("battlerTags:nightmareLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); - gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.CURSE)); // TODO: Update animation type + globalScene.queueMessage(i18next.t("battlerTags:nightmareLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, CommonAnim.CURSE)); // TODO: Update animation type const cancelled = new BooleanHolder(false); applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled); @@ -956,14 +956,14 @@ export class EncoreTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battlerTags:encoreOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:encoreOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); - const movePhase = gScene.findPhase(m => m instanceof MovePhase && m.pokemon === pokemon); + const movePhase = globalScene.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]; - gScene.tryReplacePhase((m => m instanceof MovePhase && m.pokemon === pokemon), + globalScene.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); - gScene.queueMessage(i18next.t("battlerTags:encoreOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:encoreOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } @@ -982,9 +982,9 @@ export class HelpingHandTag extends BattlerTag { } onAdd(pokemon: Pokemon): void { - gScene.queueMessage( + globalScene.queueMessage( i18next.t("battlerTags:helpingHandOnAdd", { - pokemonNameWithAffix: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? + pokemonNameWithAffix: getPokemonNameWithAffix(globalScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? pokemonName: getPokemonNameWithAffix(pokemon) }) ); @@ -1015,7 +1015,7 @@ export class IngrainTag extends TrappedTag { const ret = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType); if (ret) { - gScene.unshiftPhase( + globalScene.unshiftPhase( new PokemonHealPhase( pokemon.getBattlerIndex(), toDmgValue(pokemon.getMaxHp() / 16), @@ -1054,7 +1054,7 @@ export class OctolockTag extends TrappedTag { const shouldLapse = lapseType !== BattlerTagLapseType.CUSTOM || super.lapse(pokemon, lapseType); if (shouldLapse) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, [ Stat.DEF, Stat.SPDEF ], -1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), false, [ Stat.DEF, Stat.SPDEF ], -1)); return true; } @@ -1070,14 +1070,14 @@ export class AquaRingTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:aquaRingOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.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) { - gScene.unshiftPhase( + globalScene.unshiftPhase( new PokemonHealPhase( pokemon.getBattlerIndex(), toDmgValue(pokemon.getMaxHp() / 16), @@ -1117,13 +1117,13 @@ export class DrowsyTag extends BattlerTag { } canAdd(pokemon: Pokemon): boolean { - return gScene.arena.terrain?.terrainType !== TerrainType.ELECTRIC || !pokemon.isGrounded(); + return globalScene.arena.terrain?.terrainType !== TerrainType.ELECTRIC || !pokemon.isGrounded(); } onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:drowsyOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:drowsyOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -1166,13 +1166,13 @@ export abstract class DamagingTrapTag extends TrappedTag { const ret = super.lapse(pokemon, lapseType); if (ret) { - gScene.queueMessage( + globalScene.queueMessage( i18next.t("battlerTags:damagingTrapLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() }) ); - gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, this.commonAnim)); + globalScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), undefined, this.commonAnim)); const cancelled = new BooleanHolder(false); applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled); @@ -1194,7 +1194,7 @@ export class BindTag extends DamagingTrapTag { getTrapMessage(pokemon: Pokemon): string { return i18next.t("battlerTags:bindOnTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), - sourcePokemonName: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? + sourcePokemonName: getPokemonNameWithAffix(globalScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? moveName: this.getMoveName() }); } @@ -1208,7 +1208,7 @@ export class WrapTag extends DamagingTrapTag { getTrapMessage(pokemon: Pokemon): string { return i18next.t("battlerTags:wrapOnTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), - sourcePokemonName: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? + sourcePokemonName: getPokemonNameWithAffix(globalScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? }); } } @@ -1242,7 +1242,7 @@ export class ClampTag extends DamagingTrapTag { getTrapMessage(pokemon: Pokemon): string { return i18next.t("battlerTags:clampOnTrap", { - sourcePokemonNameWithAffix: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? + sourcePokemonNameWithAffix: getPokemonNameWithAffix(globalScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? pokemonName: getPokemonNameWithAffix(pokemon), }); } @@ -1289,7 +1289,7 @@ export class ThunderCageTag extends DamagingTrapTag { getTrapMessage(pokemon: Pokemon): string { return i18next.t("battlerTags:thunderCageOnTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), - sourcePokemonNameWithAffix: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? + sourcePokemonNameWithAffix: getPokemonNameWithAffix(globalScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? }); } } @@ -1302,7 +1302,7 @@ export class InfestationTag extends DamagingTrapTag { getTrapMessage(pokemon: Pokemon): string { return i18next.t("battlerTags:infestationOnTrap", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), - sourcePokemonNameWithAffix: getPokemonNameWithAffix(gScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? + sourcePokemonNameWithAffix: getPokemonNameWithAffix(globalScene.getPokemonById(this.sourceId!) ?? undefined), // TODO: is that bang correct? }); } } @@ -1316,16 +1316,16 @@ export class ProtectedTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:protectedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:protectedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { if (lapseType === BattlerTagLapseType.CUSTOM) { new CommonBattleAnim(CommonAnim.PROTECT, pokemon).play(); - gScene.queueMessage(i18next.t("battlerTags:protectedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:protectedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); // Stop multi-hit moves early - const effectPhase = gScene.getCurrentPhase(); + const effectPhase = globalScene.getCurrentPhase(); if (effectPhase instanceof MoveEffectPhase) { effectPhase.stopMultiHit(pokemon); } @@ -1365,7 +1365,7 @@ export class ContactDamageProtectedTag extends ProtectedTag { const ret = super.lapse(pokemon, lapseType); if (lapseType === BattlerTagLapseType.CUSTOM) { - const effectPhase = gScene.getCurrentPhase(); + const effectPhase = globalScene.getCurrentPhase(); if (effectPhase instanceof MoveEffectPhase && effectPhase.move.getMove().hasFlag(MoveFlags.MAKES_CONTACT)) { const attacker = effectPhase.getPokemon(); if (!attacker.hasAbilityWithAttr(BlockNonDirectDamageAbAttr)) { @@ -1407,10 +1407,10 @@ export class ContactStatStageChangeProtectedTag extends DamageProtectedTag { const ret = super.lapse(pokemon, lapseType); if (lapseType === BattlerTagLapseType.CUSTOM) { - const effectPhase = gScene.getCurrentPhase(); + const effectPhase = globalScene.getCurrentPhase(); if (effectPhase instanceof MoveEffectPhase && effectPhase.move.getMove().hasFlag(MoveFlags.MAKES_CONTACT)) { const attacker = effectPhase.getPokemon(); - gScene.unshiftPhase(new StatStageChangePhase(attacker.getBattlerIndex(), false, [ this.stat ], this.levels)); + globalScene.unshiftPhase(new StatStageChangePhase(attacker.getBattlerIndex(), false, [ this.stat ], this.levels)); } } @@ -1427,7 +1427,7 @@ export class ContactPoisonProtectedTag extends ProtectedTag { const ret = super.lapse(pokemon, lapseType); if (lapseType === BattlerTagLapseType.CUSTOM) { - const effectPhase = gScene.getCurrentPhase(); + const effectPhase = globalScene.getCurrentPhase(); if (effectPhase instanceof MoveEffectPhase && effectPhase.move.getMove().hasFlag(MoveFlags.MAKES_CONTACT)) { const attacker = effectPhase.getPokemon(); attacker.trySetStatus(StatusEffect.POISON, true, pokemon); @@ -1451,7 +1451,7 @@ export class ContactBurnProtectedTag extends DamageProtectedTag { const ret = super.lapse(pokemon, lapseType); if (lapseType === BattlerTagLapseType.CUSTOM) { - const effectPhase = gScene.getCurrentPhase(); + const effectPhase = globalScene.getCurrentPhase(); if (effectPhase instanceof MoveEffectPhase && effectPhase.move.getMove().hasFlag(MoveFlags.MAKES_CONTACT)) { const attacker = effectPhase.getPokemon(); attacker.trySetStatus(StatusEffect.BURN, true); @@ -1470,12 +1470,12 @@ export class EnduringTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:enduringOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:enduringOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { if (lapseType === BattlerTagLapseType.CUSTOM) { - gScene.queueMessage(i18next.t("battlerTags:enduringLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:enduringLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); return true; } @@ -1490,7 +1490,7 @@ export class SturdyTag extends BattlerTag { lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { if (lapseType === BattlerTagLapseType.CUSTOM) { - gScene.queueMessage(i18next.t("battlerTags:sturdyLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:sturdyLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); return true; } @@ -1511,7 +1511,7 @@ export class PerishSongTag extends BattlerTag { const ret = super.lapse(pokemon, lapseType); if (ret) { - gScene.queueMessage( + globalScene.queueMessage( i18next.t("battlerTags:perishSongLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), turnCount: this.turnCount @@ -1540,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() ? gScene.getPlayerField() : gScene.getEnemyField(); + const activeTeam = pokemon.isPlayer() ? globalScene.getPlayerField() : globalScene.getEnemyField(); return !activeTeam.find(p => p.getTag(BattlerTagType.CENTER_OF_ATTENTION)); } @@ -1548,7 +1548,7 @@ export class CenterOfAttentionTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:centerOfAttentionOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:centerOfAttentionOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } @@ -1585,9 +1585,9 @@ export class TruantTag extends AbilityBattlerTag { const lastMove = pokemon.getLastXMoves().find(() => true); if (lastMove && lastMove.move !== Moves.NONE) { - (gScene.getCurrentPhase() as MovePhase).cancel(); - gScene.unshiftPhase(new ShowAbilityPhase(pokemon.id, passive)); - gScene.queueMessage(i18next.t("battlerTags:truantLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + (globalScene.getCurrentPhase() as MovePhase).cancel(); + globalScene.unshiftPhase(new ShowAbilityPhase(pokemon.id, passive)); + globalScene.queueMessage(i18next.t("battlerTags:truantLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } return true; @@ -1602,7 +1602,7 @@ export class SlowStartTag extends AbilityBattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:slowStartOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null, true); + globalScene.queueMessage(i18next.t("battlerTags:slowStartOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null, true); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -1616,7 +1616,7 @@ export class SlowStartTag extends AbilityBattlerTag { onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battlerTags:slowStartOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null); + globalScene.queueMessage(i18next.t("battlerTags:slowStartOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null); } } @@ -1662,13 +1662,13 @@ export class HighestStatBoostTag extends AbilityBattlerTag { break; } - gScene.queueMessage(i18next.t("battlerTags:highestStatBoostOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), statName: i18next.t(getStatKey(highestStat)) }), null, false, null, true); + globalScene.queueMessage(i18next.t("battlerTags:highestStatBoostOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), statName: i18next.t(getStatKey(highestStat)) }), null, false, null, true); } onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battlerTags:highestStatBoostOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName: allAbilities[this.ability].name })); + globalScene.queueMessage(i18next.t("battlerTags:highestStatBoostOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), abilityName: allAbilities[this.ability].name })); } } @@ -1721,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 - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ duration: getFrameMs(2), onComplete: () => pokemon.setVisible(true) }); @@ -1761,7 +1761,7 @@ export class FloatingTag extends TypeImmuneTag { super.onAdd(pokemon); if (this.sourceMove === Moves.MAGNET_RISE) { - gScene.queueMessage(i18next.t("battlerTags:magnetRisenOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:magnetRisenOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } @@ -1769,7 +1769,7 @@ export class FloatingTag extends TypeImmuneTag { onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); if (this.sourceMove === Moves.MAGNET_RISE) { - gScene.queueMessage(i18next.t("battlerTags:magnetRisenOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:magnetRisenOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } } @@ -1811,7 +1811,7 @@ export class CritBoostTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:critBoostOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:critBoostOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -1821,7 +1821,7 @@ export class CritBoostTag extends BattlerTag { onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battlerTags:critBoostOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:critBoostOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } @@ -1863,15 +1863,15 @@ export class SaltCuredTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:saltCuredOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); - this.sourceIndex = gScene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct? + globalScene.queueMessage(i18next.t("battlerTags:saltCuredOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + this.sourceIndex = globalScene.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) { - gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.SALT_CURE)); + globalScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.SALT_CURE)); const cancelled = new BooleanHolder(false); applyAbAttrs(BlockNonDirectDamageAbAttr, pokemon, cancelled); @@ -1880,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)); - gScene.queueMessage( + globalScene.queueMessage( i18next.t("battlerTags:saltCuredLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: this.getMoveName() @@ -1911,21 +1911,21 @@ export class CursedTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - this.sourceIndex = gScene.getPokemonById(this.sourceId!)!.getBattlerIndex(); // TODO: are those bangs correct? + this.sourceIndex = globalScene.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) { - gScene.unshiftPhase(new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.SALT_CURE)); + globalScene.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)); - gScene.queueMessage(i18next.t("battlerTags:cursedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:cursedLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } @@ -2039,7 +2039,7 @@ export class FormBlockDamageTag extends BattlerTag { super.onAdd(pokemon); if (pokemon.formIndex !== 0) { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); } } @@ -2051,7 +2051,7 @@ export class FormBlockDamageTag extends BattlerTag { onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); } } /** Provides the additional weather-based effects of the Ice Face ability */ @@ -2066,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 = gScene.arena.weather?.weatherType; + const weatherType = globalScene.arena.weather?.weatherType; const isWeatherSnowOrHail = weatherType === WeatherType.HAIL || weatherType === WeatherType.SNOW; return super.canAdd(pokemon) || isWeatherSnowOrHail; @@ -2125,13 +2125,13 @@ export class StockpilingTag extends BattlerTag { if (this.stockpiledCount < 3) { this.stockpiledCount++; - gScene.queueMessage(i18next.t("battlerTags:stockpilingOnAdd", { + globalScene.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. - gScene.unshiftPhase(new StatStageChangePhase( + globalScene.unshiftPhase(new StatStageChangePhase( pokemon.getBattlerIndex(), true, [ Stat.SPDEF, Stat.DEF ], 1, true, false, true, this.onStatStagesChanged )); @@ -2151,11 +2151,11 @@ export class StockpilingTag extends BattlerTag { const spDefChange = this.statChangeCounts[Stat.SPDEF]; if (defChange) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.DEF ], -defChange, true, false, true)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.DEF ], -defChange, true, false, true)); } if (spDefChange) { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPDEF ], -spDefChange, true, false, true)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPDEF ], -spDefChange, true, false, true)); } } } @@ -2174,7 +2174,7 @@ export class GulpMissileTag extends BattlerTag { return true; } - const moveEffectPhase = gScene.getCurrentPhase(); + const moveEffectPhase = globalScene.getCurrentPhase(); if (moveEffectPhase instanceof MoveEffectPhase) { const attacker = moveEffectPhase.getUserPokemon(); @@ -2194,7 +2194,7 @@ export class GulpMissileTag extends BattlerTag { } if (this.tagType === BattlerTagType.GULP_MISSILE_ARROKUDA) { - gScene.unshiftPhase(new StatStageChangePhase(attacker.getBattlerIndex(), false, [ Stat.DEF ], -1)); + globalScene.unshiftPhase(new StatStageChangePhase(attacker.getBattlerIndex(), false, [ Stat.DEF ], -1)); } else { attacker.trySetStatus(StatusEffect.PARALYSIS, true, pokemon); } @@ -2217,12 +2217,12 @@ export class GulpMissileTag extends BattlerTag { onAdd(pokemon: Pokemon): void { super.onAdd(pokemon); - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); } onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); } } @@ -2330,7 +2330,7 @@ export class HealBlockTag extends MoveRestrictionBattlerTag { override onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); - gScene.queueMessage(i18next.t("battle:battlerTagsHealBlockOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null); + globalScene.queueMessage(i18next.t("battle:battlerTagsHealBlockOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, false, null); } } @@ -2353,7 +2353,7 @@ export class TarShotTag extends BattlerTag { } override onAdd(pokemon: Pokemon): void { - gScene.queueMessage(i18next.t("battlerTags:tarShotOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:tarShotOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } @@ -2368,7 +2368,7 @@ export class ElectrifiedTag extends BattlerTag { override onAdd(pokemon: Pokemon): void { // "{pokemonNameWithAffix}'s moves have been electrified!" - gScene.queueMessage(i18next.t("battlerTags:electrifiedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:electrifiedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } @@ -2390,7 +2390,7 @@ export class AutotomizedTag extends BattlerTag { onAdd(pokemon: Pokemon): void { const minWeight = 0.1; if (pokemon.getWeight() > minWeight) { - gScene.queueMessage(i18next.t("battlerTags:autotomizeOnAdd", { + globalScene.queueMessage(i18next.t("battlerTags:autotomizeOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } @@ -2421,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(gScene.getPokemonById(this.sourceId!)!.getMaxHp() / 4); + this.hp = Math.floor(globalScene.getPokemonById(this.sourceId!)!.getMaxHp() / 4); this.sourceInFocus = false; // Queue battle animation and message - gScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_ADD); + globalScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_ADD); if (this.sourceMove === Moves.SHED_TAIL) { - gScene.queueMessage(i18next.t("battlerTags:shedTailOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500); + globalScene.queueMessage(i18next.t("battlerTags:shedTailOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500); } else { - gScene.queueMessage(i18next.t("battlerTags:substituteOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500); + globalScene.queueMessage(i18next.t("battlerTags:substituteOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500); } // Remove any binding effects from the user @@ -2440,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) { - gScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_REMOVE, [ this.sprite ]); + globalScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_REMOVE, [ this.sprite ]); } else { this.sprite.destroy(); } - gScene.queueMessage(i18next.t("battlerTags:substituteOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:substituteOnRemove", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -2464,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 { - gScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_PRE_MOVE, [ this.sprite ]); + globalScene.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 { - gScene.triggerPokemonBattleAnim(pokemon, PokemonAnimType.SUBSTITUTE_POST_MOVE, [ this.sprite ]); + globalScene.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 = gScene.getCurrentPhase(); + const moveEffectPhase = globalScene.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)) { - gScene.queueMessage(i18next.t("battlerTags:substituteOnHit", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:substituteOnHit", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } } @@ -2555,7 +2555,7 @@ export class TormentTag extends MoveRestrictionBattlerTag { */ override onAdd(pokemon: Pokemon) { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:tormentOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500); + globalScene.queueMessage(i18next.t("battlerTags:tormentOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500); } /** @@ -2609,7 +2609,7 @@ export class TauntTag extends MoveRestrictionBattlerTag { override onAdd(pokemon: Pokemon) { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:tauntOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500); + globalScene.queueMessage(i18next.t("battlerTags:tauntOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), 1500); } /** @@ -2698,7 +2698,7 @@ export class SyrupBombTag extends BattlerTag { */ override onAdd(pokemon: Pokemon) { super.onAdd(pokemon); - gScene.queueMessage(i18next.t("battlerTags:syrupBombOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:syrupBombOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } /** @@ -2708,12 +2708,12 @@ 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 && !gScene.getPokemonById(this.sourceId)?.isActive(true)) { + if (this.sourceId && !globalScene.getPokemonById(this.sourceId)?.isActive(true)) { return false; } // Custom message in lieu of an animation in mainline - gScene.queueMessage(i18next.t("battlerTags:syrupBombLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); - gScene.unshiftPhase(new StatStageChangePhase( + globalScene.queueMessage(i18next.t("battlerTags:syrupBombLapse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.unshiftPhase(new StatStageChangePhase( pokemon.getBattlerIndex(), true, [ Stat.SPD ], -1, true, false, true )); @@ -2733,7 +2733,7 @@ export class TelekinesisTag extends BattlerTag { } override onAdd(pokemon: Pokemon) { - gScene.queueMessage(i18next.t("battlerTags:telekinesisOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:telekinesisOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } } @@ -2748,12 +2748,12 @@ export class PowerTrickTag extends BattlerTag { onAdd(pokemon: Pokemon): void { this.swapStat(pokemon); - gScene.queueMessage(i18next.t("battlerTags:powerTrickActive", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:powerTrickActive", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } onRemove(pokemon: Pokemon): void { this.swapStat(pokemon); - gScene.queueMessage(i18next.t("battlerTags:powerTrickActive", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("battlerTags:powerTrickActive", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } /** @@ -2977,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 = gScene.getCurrentPhase(); + const phase = globalScene.getCurrentPhase(); if (phase instanceof MoveEffectPhase) { return { phase : phase, diff --git a/src/data/berry.ts b/src/data/berry.ts index f45e07521ba..0d34bdd8f8a 100644 --- a/src/data/berry.ts +++ b/src/data/berry.ts @@ -9,7 +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"; +import { globalScene } from "#app/battle-scene"; export function getBerryName(berryType: BerryType): string { return i18next.t(`berry:${BerryType[berryType]}.name`); @@ -74,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); - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + globalScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), hpHealed.value, i18next.t("battle:hpHealBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), berryName: getBerryName(berryType) }), true)); }; case BerryType.LUM: @@ -83,7 +83,7 @@ export function getBerryEffectFunc(berryType: BerryType): BerryEffectFunc { pokemon.battleData.berriesEaten.push(berryType); } if (pokemon.status) { - gScene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon))); + globalScene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon))); } pokemon.resetStatus(true, true); pokemon.updateInfo(); @@ -101,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); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], statStages.value)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ stat ], statStages.value)); }; case BerryType.LANSAT: return (pokemon: Pokemon) => { @@ -118,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); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ randStat ], stages.value)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ randStat ], stages.value)); }; case BerryType.LEPPA: return (pokemon: Pokemon) => { @@ -128,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); - gScene.queueMessage(i18next.t("battle:ppHealBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: ppRestoreMove!.getName(), berryName: getBerryName(berryType) })); + globalScene.queueMessage(i18next.t("battle:ppHealBerry", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), moveName: ppRestoreMove!.getName(), berryName: getBerryName(berryType) })); } }; } diff --git a/src/data/daily-run.ts b/src/data/daily-run.ts index d2ae02a6ea3..74ea2abe1c8 100644 --- a/src/data/daily-run.ts +++ b/src/data/daily-run.ts @@ -1,6 +1,6 @@ import { PartyMemberStrength } from "#enums/party-member-strength"; import { Species } from "#enums/species"; -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -28,8 +28,8 @@ export function fetchDailyRunSeed(): Promise { export function getDailyRunStarters(seed: string): Starter[] { const starters: Starter[] = []; - gScene.executeWithSeedOffset(() => { - const startingLevel = gScene.gameMode.getStartingLevel(); + globalScene.executeWithSeedOffset(() => { + const startingLevel = globalScene.gameMode.getStartingLevel(); if (/\d{18}$/.test(seed)) { for (let s = 0; s < 3; s++) { diff --git a/src/data/egg-hatch-data.ts b/src/data/egg-hatch-data.ts index 40e8caf219f..53df4fe7bd7 100644 --- a/src/data/egg-hatch-data.ts +++ b/src/data/egg-hatch-data.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { PlayerPokemon } from "#app/field/pokemon"; import { DexEntry, StarterDataEntry } from "#app/system/game-data"; @@ -36,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 = gScene.gameData.dexData[this.pokemon.species.speciesId]; - const currStarterDataEntry = gScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()]; + const currDexEntry = globalScene.gameData.dexData[this.pokemon.species.speciesId]; + const currStarterDataEntry = globalScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()]; this.dexEntryBeforeUpdate = { seenAttr: currDexEntry.seenAttr, caughtAttr: currDexEntry.caughtAttr, @@ -83,9 +83,9 @@ export class EggHatchData { */ updatePokemon(showMessage : boolean = false) { return new Promise(resolve => { - 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) => { + globalScene.gameData.setPokemonCaught(this.pokemon, true, true, showMessage).then(() => { + globalScene.gameData.updateSpeciesDexIvs(this.pokemon.species.speciesId, this.pokemon.ivs); + globalScene.gameData.setEggMoveUnlocked(this.pokemon.species, this.eggMoveIndex, showMessage).then((value) => { this.setEggMoveUnlocked(value); resolve(); }); diff --git a/src/data/egg.ts b/src/data/egg.ts index 6efd26d27f3..1ee07870829 100644 --- a/src/data/egg.ts +++ b/src/data/egg.ts @@ -1,4 +1,4 @@ -import BattleScene, { gScene } from "#app/battle-scene"; +import BattleScene, { globalScene } 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"; @@ -233,7 +233,7 @@ export class Egg { } // This function has way to many optional parameters - ret = gScene.addPlayerPokemon(pokemonSpecies, 1, abilityIndex, undefined, undefined, false); + ret = globalScene.addPlayerPokemon(pokemonSpecies, 1, abilityIndex, undefined, undefined, false); ret.shiny = this._isShiny; ret.variant = this._variantTier; @@ -245,7 +245,7 @@ export class Egg { }; ret = ret!; // Tell TS compiler it's defined now - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { generatePlayerPokemonHelper(); }, this._id, EGG_SEED.toString()); @@ -254,7 +254,7 @@ export class Egg { // Doesn't need to be called if the egg got pulled by a gacha machiene public addEggToGameData(): void { - gScene.gameData.eggs.push(this); + globalScene.gameData.eggs.push(this); } public getEggDescriptor(): string { @@ -352,7 +352,7 @@ export class Egg { } private rollSpecies(): Species | null { - if (!gScene) { + if (!globalScene) { return null; } /** @@ -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 (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 (globalScene.gameData.unlockPity[this.tier] >= 9) { + const lockedPool = speciesPool.filter(s => !globalScene.gameData.dexData[s].caughtAttr && !globalScene.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 (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); + if (globalScene.gameData.dexData[species].caughtAttr || globalScene.gameData.eggs.some(e => e.species === species)) { + globalScene.gameData.unlockPity[this.tier] = Math.min(globalScene.gameData.unlockPity[this.tier] + 1, 10); } else { - gScene.gameData.unlockPity[this.tier] = 0; + globalScene.gameData.unlockPity[this.tier] = 0; } return species; @@ -502,36 +502,36 @@ export class Egg { private checkForPityTierOverrides(): void { const tierValueOffset = this._sourceType === EggSourceType.GACHA_LEGENDARY ? GACHA_LEGENDARY_UP_THRESHOLD_OFFSET : 0; - gScene.gameData.eggPity[EggTier.RARE] += 1; - gScene.gameData.eggPity[EggTier.EPIC] += 1; - gScene.gameData.eggPity[EggTier.LEGENDARY] += 1 + tierValueOffset; + globalScene.gameData.eggPity[EggTier.RARE] += 1; + globalScene.gameData.eggPity[EggTier.EPIC] += 1; + globalScene.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 (gScene.gameData.eggPity[EggTier.LEGENDARY] >= EGG_PITY_LEGENDARY_THRESHOLD && this._tier === EggTier.COMMON) { + if (globalScene.gameData.eggPity[EggTier.LEGENDARY] >= EGG_PITY_LEGENDARY_THRESHOLD && this._tier === EggTier.COMMON) { this._tier = EggTier.LEGENDARY; - } else if (gScene.gameData.eggPity[EggTier.EPIC] >= EGG_PITY_EPIC_THRESHOLD && this._tier === EggTier.COMMON) { + } else if (globalScene.gameData.eggPity[EggTier.EPIC] >= EGG_PITY_EPIC_THRESHOLD && this._tier === EggTier.COMMON) { this._tier = EggTier.EPIC; - } else if (gScene.gameData.eggPity[EggTier.RARE] >= EGG_PITY_RARE_THRESHOLD && this._tier === EggTier.COMMON) { + } else if (globalScene.gameData.eggPity[EggTier.RARE] >= EGG_PITY_RARE_THRESHOLD && this._tier === EggTier.COMMON) { this._tier = EggTier.RARE; } - gScene.gameData.eggPity[this._tier] = 0; + globalScene.gameData.eggPity[this._tier] = 0; } private increasePullStatistic(): void { - gScene.gameData.gameStats.eggsPulled++; + globalScene.gameData.gameStats.eggsPulled++; if (this.isManaphyEgg()) { - gScene.gameData.gameStats.manaphyEggsPulled++; + globalScene.gameData.gameStats.manaphyEggsPulled++; this._hatchWaves = this.getEggTierDefaultHatchWaves(EggTier.EPIC); return; } switch (this.tier) { case EggTier.RARE: - gScene.gameData.gameStats.rareEggsPulled++; + globalScene.gameData.gameStats.rareEggsPulled++; break; case EggTier.EPIC: - gScene.gameData.gameStats.epicEggsPulled++; + globalScene.gameData.gameStats.epicEggsPulled++; break; case EggTier.LEGENDARY: - gScene.gameData.gameStats.legendaryEggsPulled++; + globalScene.gameData.gameStats.legendaryEggsPulled++; break; } } @@ -563,7 +563,7 @@ export function getLegendaryGachaSpeciesForTimestamp(timestamp: number): Species const offset = Math.floor(Math.floor(dayTimestamp / 86400000) / legendarySpecies.length); // Cycle number const index = Math.floor(dayTimestamp / 86400000) % legendarySpecies.length; // Index within cycle - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { ret = Phaser.Math.RND.shuffle(legendarySpecies)[index]; }, offset, EGG_SEED.toString()); ret = ret!; // tell TS compiler it's diff --git a/src/data/move.ts b/src/data/move.ts index 2794e6362ce..25c898e6ebf 100644 --- a/src/data/move.ts +++ b/src/data/move.ts @@ -38,7 +38,7 @@ import { SpeciesFormChangeRevertWeatherFormTrigger } from "./pokemon-forms"; import { GameMode } from "#app/game-mode"; import { applyChallenges, ChallengeType } from "./challenge"; import { SwitchType } from "#enums/switch-type"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export enum MoveCategory { PHYSICAL, @@ -743,10 +743,10 @@ export default class Move implements Localizable { const isOhko = this.hasAttr(OneHitKOAccuracyAttr); if (!isOhko) { - gScene.applyModifiers(PokemonMoveAccuracyBoosterModifier, user.isPlayer(), user, moveAccuracy); + globalScene.applyModifiers(PokemonMoveAccuracyBoosterModifier, user.isPlayer(), user, moveAccuracy); } - if (gScene.arena.weather?.weatherType === WeatherType.FOG) { + if (globalScene.arena.weather?.weatherType === WeatherType.FOG) { /** * The 0.9 multiplier is PokeRogue-only implementation, Bulbapedia uses 3/5 * See Fog {@link https://bulbapedia.bulbagarden.net/wiki/Fog} @@ -754,7 +754,7 @@ export default class Move implements Localizable { moveAccuracy.value = Math.floor(moveAccuracy.value * 0.9); } - if (!isOhko && gScene.arena.getTag(ArenaTagType.GRAVITY)) { + if (!isOhko && globalScene.arena.getTag(ArenaTagType.GRAVITY)) { moveAccuracy.value = Math.floor(moveAccuracy.value * 1.67); } @@ -779,7 +779,7 @@ export default class Move implements Localizable { applyPreAttackAbAttrs(MoveTypeChangeAbAttr, source, target, this, true, null, typeChangeMovePowerMultiplier); const sourceTeraType = source.getTeraType(); - if (sourceTeraType !== Type.UNKNOWN && sourceTeraType === this.type && power.value < 60 && this.priority <= 0 && !this.hasAttr(MultiHitAttr) && !gScene.findModifier(m => m instanceof PokemonMultiHitModifier && m.pokemonId === source.id)) { + if (sourceTeraType !== Type.UNKNOWN && sourceTeraType === this.type && power.value < 60 && this.priority <= 0 && !this.hasAttr(MultiHitAttr) && !globalScene.findModifier(m => m instanceof PokemonMultiHitModifier && m.pokemonId === source.id)) { power.value = 60; } @@ -790,7 +790,7 @@ export default class Move implements Localizable { } const fieldAuras = new Set( - gScene.getField(true) + globalScene.getField(true) .map((p) => p.getAbilityAttrs(FieldMoveTypePowerBoostAbAttr).filter(attr => { const condition = attr.getCondition(); return (!condition || condition(p)); @@ -801,7 +801,7 @@ export default class Move implements Localizable { aura.applyPreAttack(source, null, simulated, target, this, [ power ]); } - const alliedField: Pokemon[] = source instanceof PlayerPokemon ? gScene.getPlayerField() : gScene.getEnemyField(); + const alliedField: Pokemon[] = source instanceof PlayerPokemon ? globalScene.getPlayerField() : globalScene.getEnemyField(); alliedField.forEach(p => applyPreAttackAbAttrs(UserFieldMoveTypePowerBoostAbAttr, p, target, this, simulated, power)); power.value *= typeChangeMovePowerMultiplier.value; @@ -813,11 +813,11 @@ export default class Move implements Localizable { applyMoveAttrs(VariablePowerAttr, source, target, this, power); - gScene.applyModifiers(PokemonMultiHitModifier, source.isPlayer(), source, new Utils.IntegerHolder(0), power); + globalScene.applyModifiers(PokemonMultiHitModifier, source.isPlayer(), source, new Utils.IntegerHolder(0), power); if (!this.hasAttr(TypelessAttr)) { - gScene.arena.applyTags(WeakenMoveTypeTag, simulated, this.type, power); - gScene.applyModifiers(AttackTypeBoosterModifier, source.isPlayer(), source, this.type, power); + globalScene.arena.applyTags(WeakenMoveTypeTag, simulated, this.type, power); + globalScene.applyModifiers(AttackTypeBoosterModifier, source.isPlayer(), source, this.type, power); } if (source.getTag(HelpingHandTag)) { @@ -931,7 +931,7 @@ function ChargeMove(Base: TBase) { * @param target the {@linkcode Pokemon} targeted by this move (optional) */ showChargeText(user: Pokemon, target?: Pokemon): void { - gScene.queueMessage(this._chargeText + globalScene.queueMessage(this._chargeText .replace("{USER}", getPokemonNameWithAffix(user)) .replace("{TARGET}", getPokemonNameWithAffix(target)) ); @@ -1113,7 +1113,7 @@ export class MoveEffectAttr extends MoveAttr { if ((!move.hasAttr(FlinchAttr) || moveChance.value <= move.chance) && !move.hasAttr(SecretPowerAttr)) { const userSide = user.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - gScene.arena.applyTagsForSide(ArenaTagType.WATER_FIRE_PLEDGE, userSide, false, moveChance); + globalScene.arena.applyTagsForSide(ArenaTagType.WATER_FIRE_PLEDGE, userSide, false, moveChance); } if (!selfEffect) { @@ -1153,7 +1153,7 @@ export class MessageHeaderAttr extends MoveHeaderAttr { : this.message(user, move); if (message) { - gScene.queueMessage(message); + globalScene.queueMessage(message); return true; } return false; @@ -1206,7 +1206,7 @@ export class PreMoveMessageAttr extends MoveAttr { ? this.message as string : this.message(user, target, move); if (message) { - gScene.queueMessage(message, 500); + globalScene.queueMessage(message, 500); return true; } return false; @@ -1438,7 +1438,7 @@ export class RecoilAttr extends MoveEffectAttr { } user.damageAndUpdate(recoilDamage, HitResult.OTHER, false, true, true); - gScene.queueMessage(i18next.t("moveTriggers:hitWithRecoil", { pokemonName: getPokemonNameWithAffix(user) })); + globalScene.queueMessage(i18next.t("moveTriggers:hitWithRecoil", { pokemonName: getPokemonNameWithAffix(user) })); user.turnData.damageTaken += recoilDamage; return true; @@ -1550,7 +1550,7 @@ export class HalfSacrificialAttr extends MoveEffectAttr { applyAbAttrs(BlockNonDirectDamageAbAttr, user, cancelled); if (!cancelled.value) { user.damageAndUpdate(Utils.toDmgValue(user.getMaxHp() / 2), HitResult.OTHER, false, true, true); - gScene.queueMessage(i18next.t("moveTriggers:cutHpPowerUpMove", { pokemonName: getPokemonNameWithAffix(user) })); // Queue recoil message + globalScene.queueMessage(i18next.t("moveTriggers:cutHpPowerUpMove", { pokemonName: getPokemonNameWithAffix(user) })); // Queue recoil message } return true; } @@ -1655,7 +1655,7 @@ export class HealAttr extends MoveEffectAttr { * This heals the target and shows the appropriate message. */ addHealPhase(target: Pokemon, healRatio: number) { - gScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(), + globalScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(), Utils.toDmgValue(target.getMaxHp() * healRatio), i18next.t("moveTriggers:healHp", { pokemonName: getPokemonNameWithAffix(target) }), true, !this.showAnim)); } @@ -1695,11 +1695,11 @@ export class PartyStatusCureAttr extends MoveEffectAttr { if (!this.canApply(user, target, move, args)) { return false; } - const partyPokemon = user.isPlayer() ? gScene.getParty() : gScene.getEnemyParty(); + const partyPokemon = user.isPlayer() ? globalScene.getParty() : globalScene.getEnemyParty(); partyPokemon.forEach(p => this.cureStatus(p, user.id)); if (this.message) { - gScene.queueMessage(this.message); + globalScene.queueMessage(this.message); } return true; @@ -1718,7 +1718,7 @@ export class PartyStatusCureAttr extends MoveEffectAttr { pokemon.resetStatus(); pokemon.updateInfo(); } else { - gScene.unshiftPhase(new ShowAbilityPhase(pokemon.id, pokemon.getPassiveAbility()?.id === this.abilityCondition)); + globalScene.unshiftPhase(new ShowAbilityPhase(pokemon.id, pokemon.getPassiveAbility()?.id === this.abilityCondition)); } } } @@ -1767,9 +1767,9 @@ export class SacrificialFullRestoreAttr extends SacrificialAttr { } // We don't know which party member will be chosen, so pick the highest max HP in the party - const maxPartyMemberHp = gScene.getParty().map(p => p.getMaxHp()).reduce((maxHp: integer, hp: integer) => Math.max(hp, maxHp), 0); + const maxPartyMemberHp = globalScene.getParty().map(p => p.getMaxHp()).reduce((maxHp: integer, hp: integer) => Math.max(hp, maxHp), 0); - gScene.pushPhase(new PokemonHealPhase(user.getBattlerIndex(), + globalScene.pushPhase(new PokemonHealPhase(user.getBattlerIndex(), maxPartyMemberHp, i18next.t("moveTriggers:sacrificialFullRestore", { pokemonName: getPokemonNameWithAffix(user) }), true, false, false, true), true); return true; @@ -1780,7 +1780,7 @@ export class SacrificialFullRestoreAttr extends SacrificialAttr { } getCondition(): MoveConditionFunc { - return (user, target, move) => gScene.getParty().filter(p => p.isActive()).length > gScene.currentBattle.getBattlerCount(); + return (user, target, move) => globalScene.getParty().filter(p => p.isActive()).length > globalScene.currentBattle.getBattlerCount(); } } @@ -1809,7 +1809,7 @@ export class IgnoreWeatherTypeDebuffAttr extends MoveAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { const weatherModifier = args[0] as Utils.NumberHolder; //If the type-based attack power modifier due to weather (e.g. Water moves in Sun) is below 1, set it to 1 - if (gScene.arena.weather?.weatherType === this.weather) { + if (globalScene.arena.weather?.weatherType === this.weather) { weatherModifier.value = Math.max(weatherModifier.value, 1); } return true; @@ -1823,8 +1823,8 @@ export abstract class WeatherHealAttr extends HealAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { let healRatio = 0.5; - if (!gScene.arena.weather?.isEffectSuppressed()) { - const weatherType = gScene.arena.weather?.weatherType || WeatherType.NONE; + if (!globalScene.arena.weather?.isEffectSuppressed()) { + const weatherType = globalScene.arena.weather?.weatherType || WeatherType.NONE; healRatio = this.getWeatherHealRatio(weatherType); } this.addHealPhase(user, healRatio); @@ -1971,7 +1971,7 @@ export class HitHealAttr extends MoveEffectAttr { message = ""; } } - gScene.unshiftPhase(new PokemonHealPhase(user.getBattlerIndex(), healAmount, message, false, true)); + globalScene.unshiftPhase(new PokemonHealPhase(user.getBattlerIndex(), healAmount, message, false, true)); return true; } @@ -2110,7 +2110,7 @@ export class MultiHitAttr extends MoveAttr { case MultiHitType._10: return 10; case MultiHitType.BEAT_UP: - const party = user.isPlayer() ? gScene.getParty() : gScene.getEnemyParty(); + const party = user.isPlayer() ? globalScene.getParty() : globalScene.getEnemyParty(); // No status means the ally pokemon can contribute to Beat Up return party.reduce((total, pokemon) => { return total + (pokemon.id === user.id ? 1 : pokemon?.status && pokemon.status.effect !== StatusEffect.NONE ? 0 : 1); @@ -2168,7 +2168,7 @@ export class StatusEffectAttr extends MoveEffectAttr { if (user !== target && target.isSafeguarded(user)) { if (move.category === MoveCategory.STATUS) { - gScene.queueMessage(i18next.t("moveTriggers:safeguard", { targetName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:safeguard", { targetName: getPokemonNameWithAffix(target) })); } return false; } @@ -2228,7 +2228,7 @@ export class PsychoShiftEffectAttr extends MoveEffectAttr { if (canSetStatus) { if (user.status) { - gScene.queueMessage(getStatusEffectHealText(user.status.effect, getPokemonNameWithAffix(user))); + globalScene.queueMessage(getStatusEffectHealText(user.status.effect, getPokemonNameWithAffix(user))); } user.resetStatus(); user.updateInfo(); @@ -2271,9 +2271,9 @@ export class StealHeldItemChanceAttr extends MoveEffectAttr { const highestItemTier = heldItems.map(m => m.type.getOrInferTier(poolType)).reduce((highestTier, tier) => Math.max(tier!, highestTier), 0); // TODO: is the bang after tier correct? const tierHeldItems = heldItems.filter(m => m.type.getOrInferTier(poolType) === highestItemTier); const stolenItem = tierHeldItems[user.randSeedInt(tierHeldItems.length)]; - gScene.tryTransferHeldItemModifier(stolenItem, user, false).then(success => { + globalScene.tryTransferHeldItemModifier(stolenItem, user, false).then(success => { if (success) { - gScene.queueMessage(i18next.t("moveTriggers:stoleItem", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), itemName: stolenItem.type.name })); + globalScene.queueMessage(i18next.t("moveTriggers:stoleItem", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), itemName: stolenItem.type.name })); } resolve(success); }); @@ -2285,7 +2285,7 @@ export class StealHeldItemChanceAttr extends MoveEffectAttr { } getTargetHeldItems(target: Pokemon): PokemonHeldItemModifier[] { - return gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + return globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === target.id, target.isPlayer()) as PokemonHeldItemModifier[]; } @@ -2353,12 +2353,12 @@ export class RemoveHeldItemAttr extends MoveEffectAttr { // Decrease item amount and update icon !--removedItem.stackCount; - gScene.updateModifiers(target.isPlayer()); + globalScene.updateModifiers(target.isPlayer()); if (this.berriesOnly) { - gScene.queueMessage(i18next.t("moveTriggers:incineratedItem", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), itemName: removedItem.type.name })); + globalScene.queueMessage(i18next.t("moveTriggers:incineratedItem", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), itemName: removedItem.type.name })); } else { - gScene.queueMessage(i18next.t("moveTriggers:knockedOffItem", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), itemName: removedItem.type.name })); + globalScene.queueMessage(i18next.t("moveTriggers:knockedOffItem", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), itemName: removedItem.type.name })); } } @@ -2366,7 +2366,7 @@ export class RemoveHeldItemAttr extends MoveEffectAttr { } getTargetHeldItems(target: Pokemon): PokemonHeldItemModifier[] { - return gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + return globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === target.id, target.isPlayer()) as PokemonHeldItemModifier[]; } @@ -2408,7 +2408,7 @@ export class EatBerryAttr extends MoveEffectAttr { } this.chosenBerry = heldBerries[user.randSeedInt(heldBerries.length)]; const preserve = new Utils.BooleanHolder(false); - gScene.applyModifiers(PreserveBerryModifier, target.isPlayer(), target, preserve); // check for berry pouch preservation + globalScene.applyModifiers(PreserveBerryModifier, target.isPlayer(), target, preserve); // check for berry pouch preservation if (!preserve.value) { this.reduceBerryModifier(target); } @@ -2417,17 +2417,17 @@ export class EatBerryAttr extends MoveEffectAttr { } getTargetHeldBerries(target: Pokemon): BerryModifier[] { - return gScene.findModifiers(m => m instanceof BerryModifier + return globalScene.findModifiers(m => m instanceof BerryModifier && (m as BerryModifier).pokemonId === target.id, target.isPlayer()) as BerryModifier[]; } reduceBerryModifier(target: Pokemon) { if (this.chosenBerry?.stackCount === 1) { - gScene.removeModifier(this.chosenBerry, !target.isPlayer()); + globalScene.removeModifier(this.chosenBerry, !target.isPlayer()); } else if (this.chosenBerry !== undefined && this.chosenBerry.stackCount > 1) { this.chosenBerry.stackCount--; } - gScene.updateModifiers(target.isPlayer()); + globalScene.updateModifiers(target.isPlayer()); } eatBerry(consumer: Pokemon) { @@ -2469,7 +2469,7 @@ export class StealEatBerryAttr extends EatBerryAttr { // if the target has berries, pick a random berry and steal it this.chosenBerry = heldBerries[user.randSeedInt(heldBerries.length)]; const message = i18next.t("battle:stealEatBerry", { pokemonName: user.name, targetName: target.name, berryName: this.chosenBerry.type.name }); - gScene.queueMessage(message); + globalScene.queueMessage(message); this.reduceBerryModifier(target); this.eatBerry(user); return true; @@ -2518,7 +2518,7 @@ export class HealStatusEffectAttr extends MoveEffectAttr { const pokemon = this.selfTarget ? user : target; if (pokemon.status && this.effects.includes(pokemon.status.effect)) { - gScene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon))); + globalScene.queueMessage(getStatusEffectHealText(pokemon.status.effect, getPokemonNameWithAffix(pokemon))); pokemon.resetStatus(); pokemon.updateInfo(); @@ -2589,11 +2589,11 @@ export class WeatherChangeAttr extends MoveEffectAttr { } apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - return gScene.arena.trySetWeather(this.weatherType, true); + return globalScene.arena.trySetWeather(this.weatherType, true); } getCondition(): MoveConditionFunc { - return (user, target, move) => !gScene.arena.weather || (gScene.arena.weather.weatherType !== this.weatherType && !gScene.arena.weather.isImmutable()); + return (user, target, move) => !globalScene.arena.weather || (globalScene.arena.weather.weatherType !== this.weatherType && !globalScene.arena.weather.isImmutable()); } } @@ -2607,8 +2607,8 @@ export class ClearWeatherAttr extends MoveEffectAttr { } apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - if (gScene.arena.weather?.weatherType === this.weatherType) { - return gScene.arena.trySetWeather(WeatherType.NONE, true); + if (globalScene.arena.weather?.weatherType === this.weatherType) { + return globalScene.arena.trySetWeather(WeatherType.NONE, true); } return false; @@ -2625,16 +2625,16 @@ export class TerrainChangeAttr extends MoveEffectAttr { } apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - return gScene.arena.trySetTerrain(this.terrainType, true, true); + return globalScene.arena.trySetTerrain(this.terrainType, true, true); } getCondition(): MoveConditionFunc { - return (user, target, move) => !gScene.arena.terrain || (gScene.arena.terrain.terrainType !== this.terrainType); + return (user, target, move) => !globalScene.arena.terrain || (globalScene.arena.terrain.terrainType !== this.terrainType); } getUserBenefitScore(user: Pokemon, target: Pokemon, move: Move): number { // TODO: Expand on this - return gScene.arena.terrain ? 0 : 6; + return globalScene.arena.terrain ? 0 : 6; } } @@ -2644,7 +2644,7 @@ export class ClearTerrainAttr extends MoveEffectAttr { } apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - return gScene.arena.trySetTerrain(TerrainType.NONE, true, true); + return globalScene.arena.trySetTerrain(TerrainType.NONE, true, true); } } @@ -2713,7 +2713,7 @@ export class InstantChargeAttr extends MoveAttr { export class WeatherInstantChargeAttr extends InstantChargeAttr { constructor(weatherTypes: WeatherType[]) { super((user, move) => { - const currentWeather = gScene.arena.weather; + const currentWeather = globalScene.arena.weather; if (Utils.isNullOrUndefined(currentWeather?.weatherType)) { return false; @@ -2751,14 +2751,14 @@ export class DelayedAttackAttr extends OverrideMoveEffectAttr { if (args.length < 2 || !args[1]) { new MoveChargeAnim(this.chargeAnim, move.id, user).play(false, () => { (args[0] as Utils.BooleanHolder).value = true; - gScene.queueMessage(this.chargeText.replace("{TARGET}", getPokemonNameWithAffix(target)).replace("{USER}", getPokemonNameWithAffix(user))); + globalScene.queueMessage(this.chargeText.replace("{TARGET}", getPokemonNameWithAffix(target)).replace("{USER}", getPokemonNameWithAffix(user))); user.pushMoveHistory({ move: move.id, targets: [ target.getBattlerIndex() ], result: MoveResult.OTHER }); - gScene.arena.addTag(this.tagType, 3, move.id, user.id, ArenaTagSide.BOTH, false, target.getBattlerIndex()); + globalScene.arena.addTag(this.tagType, 3, move.id, user.id, ArenaTagSide.BOTH, false, target.getBattlerIndex()); resolve(true); }); } else { - gScene.ui.showText(i18next.t("moveTriggers:tookMoveAttack", { pokemonName: getPokemonNameWithAffix(gScene.getPokemonById(target.id) ?? undefined), moveName: move.name }), null, () => resolve(true)); + globalScene.ui.showText(i18next.t("moveTriggers:tookMoveAttack", { pokemonName: getPokemonNameWithAffix(globalScene.getPokemonById(target.id) ?? undefined), moveName: move.name }), null, () => resolve(true)); } }); } @@ -2787,29 +2787,29 @@ export class AwaitCombinedPledgeAttr extends OverrideMoveEffectAttr { override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { if (user.turnData.combiningPledge) { // "The two moves have become one!\nIt's a combined move!" - gScene.queueMessage(i18next.t("moveTriggers:combiningPledge")); + globalScene.queueMessage(i18next.t("moveTriggers:combiningPledge")); return false; } const overridden = args[0] as Utils.BooleanHolder; - const allyMovePhase = gScene.findPhase((phase) => phase instanceof MovePhase && phase.pokemon.isPlayer() === user.isPlayer()); + const allyMovePhase = globalScene.findPhase((phase) => phase instanceof MovePhase && phase.pokemon.isPlayer() === user.isPlayer()); if (allyMovePhase) { const allyMove = allyMovePhase.move.getMove(); if (allyMove !== move && allyMove.hasAttr(AwaitCombinedPledgeAttr)) { [ user, allyMovePhase.pokemon ].forEach((p) => p.turnData.combiningPledge = move.id); // "{userPokemonName} is waiting for {allyPokemonName}'s move..." - gScene.queueMessage(i18next.t("moveTriggers:awaitingPledge", { + globalScene.queueMessage(i18next.t("moveTriggers:awaitingPledge", { userPokemonName: getPokemonNameWithAffix(user), allyPokemonName: getPokemonNameWithAffix(allyMovePhase.pokemon) })); // Move the ally's MovePhase (if needed) so that the ally moves next - const allyMovePhaseIndex = gScene.phaseQueue.indexOf(allyMovePhase); - const firstMovePhaseIndex = gScene.phaseQueue.findIndex((phase) => phase instanceof MovePhase); + const allyMovePhaseIndex = globalScene.phaseQueue.indexOf(allyMovePhase); + const firstMovePhaseIndex = globalScene.phaseQueue.findIndex((phase) => phase instanceof MovePhase); if (allyMovePhaseIndex !== firstMovePhaseIndex) { - gScene.prependToPhase(gScene.phaseQueue.splice(allyMovePhaseIndex, 1)[0], MovePhase); + globalScene.prependToPhase(globalScene.phaseQueue.splice(allyMovePhaseIndex, 1)[0], MovePhase); } overridden.value = true; @@ -2871,7 +2871,7 @@ export class StatStageChangeAttr extends MoveEffectAttr { const moveChance = this.getMoveChance(user, target, move, this.selfTarget, true); if (moveChance < 0 || moveChance === 100 || user.randSeedInt(100) < moveChance) { const stages = this.getLevels(user); - gScene.unshiftPhase(new StatStageChangePhase((this.selfTarget ? user : target).getBattlerIndex(), this.selfTarget, this.stats, stages, this.showMessage)); + globalScene.unshiftPhase(new StatStageChangePhase((this.selfTarget ? user : target).getBattlerIndex(), this.selfTarget, this.stats, stages, this.showMessage)); return true; } @@ -2956,11 +2956,11 @@ export class SecretPowerAttr extends MoveEffectAttr { return false; } let secondaryEffect: MoveEffectAttr; - const terrain = gScene.arena.getTerrainType(); + const terrain = globalScene.arena.getTerrainType(); if (terrain !== TerrainType.NONE) { secondaryEffect = this.determineTerrainEffect(terrain); } else { - const biome = gScene.arena.biomeType; + const biome = globalScene.arena.biomeType; secondaryEffect = this.determineBiomeEffect(biome); } // effectChanceOverride used in the application of the actual secondary effect @@ -3112,7 +3112,7 @@ export class AcupressureStatStageChangeAttr extends MoveEffectAttr { const randStats = BATTLE_STATS.filter(s => target.getStatStage(s) < 6); if (randStats.length > 0) { const boostStat = [ randStats[user.randSeedInt(randStats.length)] ]; - gScene.unshiftPhase(new StatStageChangePhase(target.getBattlerIndex(), this.selfTarget, boostStat, 2)); + globalScene.unshiftPhase(new StatStageChangePhase(target.getBattlerIndex(), this.selfTarget, boostStat, 2)); return true; } return false; @@ -3125,8 +3125,8 @@ export class GrowthStatStageChangeAttr extends StatStageChangeAttr { } getLevels(user: Pokemon): number { - if (!gScene.arena.weather?.isEffectSuppressed()) { - const weatherType = gScene.arena.weather?.weatherType; + if (!globalScene.arena.weather?.isEffectSuppressed()) { + const weatherType = globalScene.arena.weather?.weatherType; if (weatherType === WeatherType.SUNNY || weatherType === WeatherType.HARSH_SUN) { return this.stages + 1; } @@ -3182,7 +3182,7 @@ export class CopyStatsAttr extends MoveEffectAttr { } target.updateInfo(); user.updateInfo(); - gScene.queueMessage(i18next.t("moveTriggers:copiedStatChanges", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:copiedStatChanges", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target) })); return true; } @@ -3201,7 +3201,7 @@ export class InvertStatsAttr extends MoveEffectAttr { target.updateInfo(); user.updateInfo(); - gScene.queueMessage(i18next.t("moveTriggers:invertStats", { pokemonName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:invertStats", { pokemonName: getPokemonNameWithAffix(target) })); return true; } @@ -3216,13 +3216,13 @@ export class ResetStatsAttr extends MoveEffectAttr { async apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { const promises: Promise[] = []; if (this.targetAllPokemon) { // Target all pokemon on the field when Freezy Frost or Haze are used - const activePokemon = gScene.getField(true); + const activePokemon = globalScene.getField(true); activePokemon.forEach(p => promises.push(this.resetStats(p))); - gScene.queueMessage(i18next.t("moveTriggers:statEliminated")); + globalScene.queueMessage(i18next.t("moveTriggers:statEliminated")); } else { // Affects only the single target when Clear Smog is used if (!move.hitsSubstitute(user, target)) { promises.push(this.resetStats(target)); - gScene.queueMessage(i18next.t("moveTriggers:resetStats", { pokemonName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:resetStats", { pokemonName: getPokemonNameWithAffix(target) })); } } @@ -3275,9 +3275,9 @@ export class SwapStatStagesAttr extends MoveEffectAttr { user.updateInfo(); if (this.stats.length === 7) { - gScene.queueMessage(i18next.t("moveTriggers:switchedStatChanges", { pokemonName: getPokemonNameWithAffix(user) })); + globalScene.queueMessage(i18next.t("moveTriggers:switchedStatChanges", { pokemonName: getPokemonNameWithAffix(user) })); } else if (this.stats.length === 2) { - gScene.queueMessage(i18next.t("moveTriggers:switchedTwoStatChanges", { + globalScene.queueMessage(i18next.t("moveTriggers:switchedTwoStatChanges", { pokemonName: getPokemonNameWithAffix(user), firstStat: i18next.t(getStatKey(this.stats[0])), secondStat: i18next.t(getStatKey(this.stats[1])) @@ -3302,12 +3302,12 @@ export class HpSplitAttr extends MoveEffectAttr { if (user.hp < hpValue) { const healing = user.heal(hpValue - user.hp); if (healing) { - gScene.damageNumberHandler.add(user, healing, HitResult.HEAL); + globalScene.damageNumberHandler.add(user, healing, HitResult.HEAL); } } else if (user.hp > hpValue) { const damage = user.damage(user.hp - hpValue, true); if (damage) { - gScene.damageNumberHandler.add(user, damage); + globalScene.damageNumberHandler.add(user, damage); } } infoUpdates.push(user.updateInfo()); @@ -3315,12 +3315,12 @@ export class HpSplitAttr extends MoveEffectAttr { if (target.hp < hpValue) { const healing = target.heal(hpValue - target.hp); if (healing) { - gScene.damageNumberHandler.add(user, healing, HitResult.HEAL); + globalScene.damageNumberHandler.add(user, healing, HitResult.HEAL); } } else if (target.hp > hpValue) { const damage = target.damage(target.hp - hpValue, true); if (damage) { - gScene.damageNumberHandler.add(target, damage); + globalScene.damageNumberHandler.add(target, damage); } } infoUpdates.push(target.updateInfo()); @@ -3403,7 +3403,7 @@ export class MovePowerMultiplierAttr extends VariablePowerAttr { * @returns The base power of the Beat Up hit. */ const beatUpFunc = (user: Pokemon, allyIndex: number): number => { - const party = user.isPlayer() ? gScene.getParty() : gScene.getEnemyParty(); + const party = user.isPlayer() ? globalScene.getParty() : globalScene.getEnemyParty(); for (let i = allyIndex; i < party.length; i++) { const pokemon = party[i]; @@ -3431,7 +3431,7 @@ export class BeatUpAttr extends VariablePowerAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { const power = args[0] as Utils.NumberHolder; - const party = user.isPlayer() ? gScene.getParty() : gScene.getEnemyParty(); + const party = user.isPlayer() ? globalScene.getParty() : globalScene.getEnemyParty(); const allyCount = party.filter(pokemon => { return pokemon.id === user.id || !pokemon.status?.effect; }).length; @@ -3443,19 +3443,19 @@ export class BeatUpAttr extends VariablePowerAttr { const doublePowerChanceMessageFunc = (user: Pokemon, target: Pokemon, move: Move) => { let message: string = ""; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const rand = Utils.randSeedInt(100); if (rand < move.chance) { message = i18next.t("moveTriggers:goingAllOutForAttack", { pokemonName: getPokemonNameWithAffix(user) }); } - }, gScene.currentBattle.turn << 6, gScene.waveSeed); + }, globalScene.currentBattle.turn << 6, globalScene.waveSeed); return message; }; export class DoublePowerChanceAttr extends VariablePowerAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { let rand: integer; - gScene.executeWithSeedOffset(() => rand = Utils.randSeedInt(100), gScene.currentBattle.turn << 6, gScene.waveSeed); + globalScene.executeWithSeedOffset(() => rand = Utils.randSeedInt(100), globalScene.currentBattle.turn << 6, globalScene.waveSeed); if (rand! < move.chance) { const power = args[0] as Utils.NumberHolder; power.value *= 2; @@ -3689,8 +3689,8 @@ export class OpponentHighHpPowerAttr extends VariablePowerAttr { export class FirstAttackDoublePowerAttr extends VariablePowerAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - console.log(target.getLastXMoves(1), gScene.currentBattle.turn); - if (!target.getLastXMoves(1).find(m => m.turn === gScene.currentBattle.turn)) { + console.log(target.getLastXMoves(1), globalScene.currentBattle.turn); + if (!target.getLastXMoves(1).find(m => m.turn === globalScene.currentBattle.turn)) { (args[0] as Utils.NumberHolder).value *= 2; return true; } @@ -3713,7 +3713,7 @@ export class TurnDamagedDoublePowerAttr extends VariablePowerAttr { const magnitudeMessageFunc = (user: Pokemon, target: Pokemon, move: Move) => { let message: string; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const magnitudeThresholds = [ 5, 15, 35, 65, 75, 95 ]; const rand = Utils.randSeedInt(100); @@ -3726,7 +3726,7 @@ const magnitudeMessageFunc = (user: Pokemon, target: Pokemon, move: Move) => { } message = i18next.t("moveTriggers:magnitudeMessage", { magnitude: m + 4 }); - }, gScene.currentBattle.turn << 6, gScene.waveSeed); + }, globalScene.currentBattle.turn << 6, globalScene.waveSeed); return message!; }; @@ -3739,7 +3739,7 @@ export class MagnitudePowerAttr extends VariablePowerAttr { let rand: integer; - gScene.executeWithSeedOffset(() => rand = Utils.randSeedInt(100), gScene.currentBattle.turn << 6, gScene.waveSeed); + globalScene.executeWithSeedOffset(() => rand = Utils.randSeedInt(100), globalScene.currentBattle.turn << 6, globalScene.waveSeed); let m = 0; for (; m < magnitudeThresholds.length; m++) { @@ -3756,9 +3756,9 @@ export class MagnitudePowerAttr extends VariablePowerAttr { export class AntiSunlightPowerDecreaseAttr extends VariablePowerAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - if (!gScene.arena.weather?.isEffectSuppressed()) { + if (!globalScene.arena.weather?.isEffectSuppressed()) { const power = args[0] as Utils.NumberHolder; - const weatherType = gScene.arena.weather?.weatherType || WeatherType.NONE; + const weatherType = globalScene.arena.weather?.weatherType || WeatherType.NONE; switch (weatherType) { case WeatherType.RAIN: case WeatherType.SANDSTORM: @@ -3874,7 +3874,7 @@ export class PresentPowerAttr extends VariablePowerAttr { } else if (80 < powerSeed && powerSeed <= 100) { // If this move is multi-hit, disable all other hits user.stopMultiHit(); - gScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(), + globalScene.unshiftPhase(new PokemonHealPhase(target.getBattlerIndex(), Utils.toDmgValue(target.getMaxHp() / 4), i18next.t("moveTriggers:regainedHealth", { pokemonName: getPokemonNameWithAffix(target) }), true)); } @@ -4024,7 +4024,7 @@ export class LastMoveDoublePowerAttr extends VariablePowerAttr { pokemonActed.push(enemy); } - if (gScene.currentBattle.double) { + if (globalScene.currentBattle.double) { const userAlly = user.getAlly(); const enemyAlly = enemy?.getAlly(); @@ -4159,9 +4159,9 @@ export class VariableAccuracyAttr extends MoveAttr { */ export class ThunderAccuracyAttr extends VariableAccuracyAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - if (!gScene.arena.weather?.isEffectSuppressed()) { + if (!globalScene.arena.weather?.isEffectSuppressed()) { const accuracy = args[0] as Utils.NumberHolder; - const weatherType = gScene.arena.weather?.weatherType || WeatherType.NONE; + const weatherType = globalScene.arena.weather?.weatherType || WeatherType.NONE; switch (weatherType) { case WeatherType.SUNNY: case WeatherType.HARSH_SUN: @@ -4185,9 +4185,9 @@ export class ThunderAccuracyAttr extends VariableAccuracyAttr { */ export class StormAccuracyAttr extends VariableAccuracyAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - if (!gScene.arena.weather?.isEffectSuppressed()) { + if (!globalScene.arena.weather?.isEffectSuppressed()) { const accuracy = args[0] as Utils.NumberHolder; - const weatherType = gScene.arena.weather?.weatherType || WeatherType.NONE; + const weatherType = globalScene.arena.weather?.weatherType || WeatherType.NONE; switch (weatherType) { case WeatherType.RAIN: case WeatherType.HEAVY_RAIN: @@ -4241,9 +4241,9 @@ export class ToxicAccuracyAttr extends VariableAccuracyAttr { export class BlizzardAccuracyAttr extends VariableAccuracyAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - if (!gScene.arena.weather?.isEffectSuppressed()) { + if (!globalScene.arena.weather?.isEffectSuppressed()) { const accuracy = args[0] as Utils.NumberHolder; - const weatherType = gScene.arena.weather?.weatherType || WeatherType.NONE; + const weatherType = globalScene.arena.weather?.weatherType || WeatherType.NONE; if (weatherType === WeatherType.HAIL || weatherType === WeatherType.SNOW) { accuracy.value = -1; return true; @@ -4540,8 +4540,8 @@ export class WeatherBallTypeAttr extends VariableMoveTypeAttr { return false; } - if (!gScene.arena.weather?.isEffectSuppressed()) { - switch (gScene.arena.weather?.weatherType) { + if (!globalScene.arena.weather?.isEffectSuppressed()) { + switch (globalScene.arena.weather?.weatherType) { case WeatherType.SUNNY: case WeatherType.HARSH_SUN: moveType.value = Type.FIRE; @@ -4591,7 +4591,7 @@ export class TerrainPulseTypeAttr extends VariableMoveTypeAttr { return false; } - const currentTerrain = gScene.arena.getTerrainType(); + const currentTerrain = globalScene.arena.getTerrainType(); switch (currentTerrain) { case TerrainType.MISTY: moveType.value = Type.FAIRY; @@ -4756,7 +4756,7 @@ export class WaterSuperEffectTypeMultiplierAttr extends VariableMoveTypeMultipli const multiplier = args[0] as Utils.NumberHolder; if (target.isOfType(Type.WATER)) { const effectivenessAgainstWater = new Utils.NumberHolder(getTypeDamageMultiplier(move.type, Type.WATER)); - applyChallenges(gScene.gameMode, ChallengeType.TYPE_EFFECTIVENESS, effectivenessAgainstWater); + applyChallenges(globalScene.gameMode, ChallengeType.TYPE_EFFECTIVENESS, effectivenessAgainstWater); if (effectivenessAgainstWater.value !== 0) { multiplier.value *= 2 / effectivenessAgainstWater.value; return true; @@ -4867,7 +4867,7 @@ const crashDamageFunc = (user: Pokemon, move: Move) => { } user.damageAndUpdate(Utils.toDmgValue(user.getMaxHp() / 2), HitResult.OTHER, false, true); - gScene.queueMessage(i18next.t("moveTriggers:keptGoingAndCrashed", { pokemonName: getPokemonNameWithAffix(user) })); + globalScene.queueMessage(i18next.t("moveTriggers:keptGoingAndCrashed", { pokemonName: getPokemonNameWithAffix(user) })); user.turnData.damageTaken += Utils.toDmgValue(user.getMaxHp() / 2); return true; @@ -5157,12 +5157,12 @@ export class CurseAttr extends MoveEffectAttr { apply(user: Pokemon, target: Pokemon, move:Move, args: any[]): boolean { if (user.getTypes(true).includes(Type.GHOST)) { if (target.getTag(BattlerTagType.CURSED)) { - gScene.queueMessage(i18next.t("battle:attackFailed")); + globalScene.queueMessage(i18next.t("battle:attackFailed")); return false; } const curseRecoilDamage = Math.max(1, Math.floor(user.getMaxHp() / 2)); user.damageAndUpdate(curseRecoilDamage, HitResult.OTHER, false, true, true); - gScene.queueMessage( + globalScene.queueMessage( i18next.t("battlerTags:cursedOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(user), pokemonName: getPokemonNameWithAffix(target) @@ -5172,8 +5172,8 @@ export class CurseAttr extends MoveEffectAttr { target.addTag(BattlerTagType.CURSED, 0, move.id, user.id); return true; } else { - gScene.unshiftPhase(new StatStageChangePhase(user.getBattlerIndex(), true, [ Stat.ATK, Stat.DEF ], 1)); - gScene.unshiftPhase(new StatStageChangePhase(user.getBattlerIndex(), true, [ Stat.SPD ], -1)); + globalScene.unshiftPhase(new StatStageChangePhase(user.getBattlerIndex(), true, [ Stat.ATK, Stat.DEF ], 1)); + globalScene.unshiftPhase(new StatStageChangePhase(user.getBattlerIndex(), true, [ Stat.SPD ], -1)); return true; } } @@ -5244,7 +5244,7 @@ export class ConfuseAttr extends AddBattlerTagAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { if (!this.selfTarget && target.isSafeguarded(user)) { if (move.category === MoveCategory.STATUS) { - gScene.queueMessage(i18next.t("moveTriggers:safeguard", { targetName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:safeguard", { targetName: getPokemonNameWithAffix(target) })); } return false; } @@ -5304,7 +5304,7 @@ export class IgnoreAccuracyAttr extends AddBattlerTagAttr { return false; } - gScene.queueMessage(i18next.t("moveTriggers:tookAimAtTarget", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:tookAimAtTarget", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target) })); return true; } @@ -5320,7 +5320,7 @@ export class FaintCountdownAttr extends AddBattlerTagAttr { return false; } - gScene.queueMessage(i18next.t("moveTriggers:faintCountdown", { pokemonName: getPokemonNameWithAffix(target), turnCount: this.turnCountMin - 1 })); + globalScene.queueMessage(i18next.t("moveTriggers:faintCountdown", { pokemonName: getPokemonNameWithAffix(target), turnCount: this.turnCountMin - 1 })); return true; } @@ -5350,7 +5350,7 @@ export class RemoveAllSubstitutesAttr extends MoveEffectAttr { return false; } - gScene.getField(true).forEach(pokemon => + globalScene.getField(true).forEach(pokemon => pokemon.findAndRemoveTags(tag => tag.tagType === BattlerTagType.SUBSTITUTE)); return true; } @@ -5412,7 +5412,7 @@ export class AddArenaTagAttr extends MoveEffectAttr { } if ((move.chance < 0 || move.chance === 100 || user.randSeedInt(100) < move.chance) && user.getLastXMoves(1)[0]?.result === MoveResult.SUCCESS) { - gScene.arena.addTag(this.tagType, this.turnCount, move.id, user.id, (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY); + globalScene.arena.addTag(this.tagType, this.turnCount, move.id, user.id, (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY); return true; } @@ -5421,7 +5421,7 @@ export class AddArenaTagAttr extends MoveEffectAttr { getCondition(): MoveConditionFunc | null { return this.failOnOverlap - ? (user, target, move) => !gScene.arena.getTagOnSide(this.tagType, target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY) + ? (user, target, move) => !globalScene.arena.getTagOnSide(this.tagType, target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY) : null; } } @@ -5450,7 +5450,7 @@ export class RemoveArenaTagsAttr extends MoveEffectAttr { const side = (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; for (const tagType of this.tagTypes) { - gScene.arena.removeTagOnSide(tagType, side); + globalScene.arena.removeTagOnSide(tagType, side); } return true; @@ -5461,7 +5461,7 @@ export class AddArenaTrapTagAttr extends AddArenaTagAttr { getCondition(): MoveConditionFunc { return (user, target, move) => { const side = (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - const tag = gScene.arena.getTagOnSide(this.tagType, side) as ArenaTrapTag; + const tag = globalScene.arena.getTagOnSide(this.tagType, side) as ArenaTrapTag; if (!tag) { return true; } @@ -5485,9 +5485,9 @@ export class AddArenaTrapTagHitAttr extends AddArenaTagAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { const moveChance = this.getMoveChance(user, target, move, this.selfTarget, true); const side = (this.selfSideTarget ? user : target).isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - const tag = gScene.arena.getTagOnSide(this.tagType, side) as ArenaTrapTag; + const tag = globalScene.arena.getTagOnSide(this.tagType, side) as ArenaTrapTag; if ((moveChance < 0 || moveChance === 100 || user.randSeedInt(100) < moveChance) && user.getLastXMoves(1)[0]?.result === MoveResult.SUCCESS) { - gScene.arena.addTag(this.tagType, 0, move.id, user.id, side); + globalScene.arena.addTag(this.tagType, 0, move.id, user.id, side); if (!tag) { return true; } @@ -5513,20 +5513,20 @@ export class RemoveArenaTrapAttr extends MoveEffectAttr { } if (this.targetBothSides) { - gScene.arena.removeTagOnSide(ArenaTagType.SPIKES, ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.TOXIC_SPIKES, ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.STEALTH_ROCK, ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.STICKY_WEB, ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.SPIKES, ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.TOXIC_SPIKES, ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.STEALTH_ROCK, ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.STICKY_WEB, ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.SPIKES, ArenaTagSide.ENEMY); - gScene.arena.removeTagOnSide(ArenaTagType.TOXIC_SPIKES, ArenaTagSide.ENEMY); - gScene.arena.removeTagOnSide(ArenaTagType.STEALTH_ROCK, ArenaTagSide.ENEMY); - gScene.arena.removeTagOnSide(ArenaTagType.STICKY_WEB, ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.SPIKES, ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.TOXIC_SPIKES, ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.STEALTH_ROCK, ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.STICKY_WEB, ArenaTagSide.ENEMY); } else { - gScene.arena.removeTagOnSide(ArenaTagType.SPIKES, target.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.TOXIC_SPIKES, target.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.STEALTH_ROCK, target.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.STICKY_WEB, target.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.SPIKES, target.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.TOXIC_SPIKES, target.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.STEALTH_ROCK, target.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.STICKY_WEB, target.isPlayer() ? ArenaTagSide.ENEMY : ArenaTagSide.PLAYER); } return true; @@ -5549,17 +5549,17 @@ export class RemoveScreensAttr extends MoveEffectAttr { } if (this.targetBothSides) { - gScene.arena.removeTagOnSide(ArenaTagType.REFLECT, ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.LIGHT_SCREEN, ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.AURORA_VEIL, ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.REFLECT, ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.LIGHT_SCREEN, ArenaTagSide.PLAYER); + globalScene.arena.removeTagOnSide(ArenaTagType.AURORA_VEIL, ArenaTagSide.PLAYER); - gScene.arena.removeTagOnSide(ArenaTagType.REFLECT, ArenaTagSide.ENEMY); - gScene.arena.removeTagOnSide(ArenaTagType.LIGHT_SCREEN, ArenaTagSide.ENEMY); - gScene.arena.removeTagOnSide(ArenaTagType.AURORA_VEIL, ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.REFLECT, ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.LIGHT_SCREEN, ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.AURORA_VEIL, ArenaTagSide.ENEMY); } else { - gScene.arena.removeTagOnSide(ArenaTagType.REFLECT, target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY); - gScene.arena.removeTagOnSide(ArenaTagType.LIGHT_SCREEN, target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY); - gScene.arena.removeTagOnSide(ArenaTagType.AURORA_VEIL, target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.REFLECT, target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.LIGHT_SCREEN, target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY); + globalScene.arena.removeTagOnSide(ArenaTagType.AURORA_VEIL, target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY); } return true; @@ -5585,25 +5585,25 @@ export class SwapArenaTagsAttr extends MoveEffectAttr { return false; } - const tagPlayerTemp = gScene.arena.findTagsOnSide((t => this.SwapTags.includes(t.tagType)), ArenaTagSide.PLAYER); - const tagEnemyTemp = gScene.arena.findTagsOnSide((t => this.SwapTags.includes(t.tagType)), ArenaTagSide.ENEMY); + const tagPlayerTemp = globalScene.arena.findTagsOnSide((t => this.SwapTags.includes(t.tagType)), ArenaTagSide.PLAYER); + const tagEnemyTemp = globalScene.arena.findTagsOnSide((t => this.SwapTags.includes(t.tagType)), ArenaTagSide.ENEMY); if (tagPlayerTemp) { for (const swapTagsType of tagPlayerTemp) { - gScene.arena.removeTagOnSide(swapTagsType.tagType, ArenaTagSide.PLAYER, true); - gScene.arena.addTag(swapTagsType.tagType, swapTagsType.turnCount, swapTagsType.sourceMove, swapTagsType.sourceId!, ArenaTagSide.ENEMY, true); // TODO: is the bang correct? + globalScene.arena.removeTagOnSide(swapTagsType.tagType, ArenaTagSide.PLAYER, true); + globalScene.arena.addTag(swapTagsType.tagType, swapTagsType.turnCount, swapTagsType.sourceMove, swapTagsType.sourceId!, ArenaTagSide.ENEMY, true); // TODO: is the bang correct? } } if (tagEnemyTemp) { for (const swapTagsType of tagEnemyTemp) { - gScene.arena.removeTagOnSide(swapTagsType.tagType, ArenaTagSide.ENEMY, true); - gScene.arena.addTag(swapTagsType.tagType, swapTagsType.turnCount, swapTagsType.sourceMove, swapTagsType.sourceId!, ArenaTagSide.PLAYER, true); // TODO: is the bang correct? + globalScene.arena.removeTagOnSide(swapTagsType.tagType, ArenaTagSide.ENEMY, true); + globalScene.arena.addTag(swapTagsType.tagType, swapTagsType.turnCount, swapTagsType.sourceMove, swapTagsType.sourceId!, ArenaTagSide.PLAYER, true); // TODO: is the bang correct? } } - gScene.queueMessage(i18next.t("moveTriggers:swapArenaTags", { pokemonName: getPokemonNameWithAffix(user) })); + globalScene.queueMessage(i18next.t("moveTriggers:swapArenaTags", { pokemonName: getPokemonNameWithAffix(user) })); return true; } } @@ -5656,40 +5656,40 @@ export class RevivalBlessingAttr extends MoveEffectAttr { return new Promise(resolve => { // If user is player, checks if the user has fainted pokemon if (user instanceof PlayerPokemon - && gScene.getParty().findIndex(p => p.isFainted()) > -1) { + && globalScene.getParty().findIndex(p => p.isFainted()) > -1) { (user as PlayerPokemon).revivalBlessing().then(() => { resolve(true); }); // If user is enemy, checks that it is a trainer, and it has fainted non-boss pokemon in party } else if (user instanceof EnemyPokemon && user.hasTrainer() - && gScene.getEnemyParty().findIndex(p => p.isFainted() && !p.isBoss()) > -1) { + && globalScene.getEnemyParty().findIndex(p => p.isFainted() && !p.isBoss()) > -1) { // Selects a random fainted pokemon - const faintedPokemon = gScene.getEnemyParty().filter(p => p.isFainted() && !p.isBoss()); + const faintedPokemon = globalScene.getEnemyParty().filter(p => p.isFainted() && !p.isBoss()); const pokemon = faintedPokemon[user.randSeedInt(faintedPokemon.length)]; - const slotIndex = gScene.getEnemyParty().findIndex(p => pokemon.id === p.id); + const slotIndex = globalScene.getEnemyParty().findIndex(p => pokemon.id === p.id); pokemon.resetStatus(); pokemon.heal(Math.min(Utils.toDmgValue(0.5 * pokemon.getMaxHp()), pokemon.getMaxHp())); - gScene.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: getPokemonNameWithAffix(pokemon) }), 0, true); + globalScene.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: getPokemonNameWithAffix(pokemon) }), 0, true); - if (gScene.currentBattle.double && gScene.getEnemyParty().length > 1) { + if (globalScene.currentBattle.double && globalScene.getEnemyParty().length > 1) { const allyPokemon = user.getAlly(); if (slotIndex <= 1) { - gScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, pokemon.getFieldIndex(), slotIndex, false, false)); + globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, pokemon.getFieldIndex(), slotIndex, false, false)); } else if (allyPokemon.isFainted()) { - gScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, allyPokemon.getFieldIndex(), slotIndex, false, false)); + globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, allyPokemon.getFieldIndex(), slotIndex, false, false)); } } resolve(true); } else { - gScene.queueMessage(i18next.t("battle:attackFailed")); + globalScene.queueMessage(i18next.t("battle:attackFailed")); resolve(false); } }); } getUserBenefitScore(user: Pokemon, target: Pokemon, move: Move): integer { - if (user.hasTrainer() && gScene.getEnemyParty().findIndex(p => p.isFainted() && !p.isBoss()) > -1) { + if (user.hasTrainer() && globalScene.getEnemyParty().findIndex(p => p.isFainted() && !p.isBoss()) > -1) { return 20; } @@ -5722,52 +5722,52 @@ export class ForceSwitchOutAttr extends MoveEffectAttr { const switchOutTarget = this.selfSwitch ? user : target; if (switchOutTarget instanceof PlayerPokemon) { // Switch out logic for the player's Pokemon - if (gScene.getParty().filter((p) => p.isAllowedInBattle() && !p.isOnField()).length < 1) { + if (globalScene.getParty().filter((p) => p.isAllowedInBattle() && !p.isOnField()).length < 1) { return false; } if (switchOutTarget.hp > 0) { switchOutTarget.leaveField(this.switchType === SwitchType.SWITCH); - gScene.prependToPhase(new SwitchPhase(this.switchType, switchOutTarget.getFieldIndex(), true, true), MoveEndPhase); + globalScene.prependToPhase(new SwitchPhase(this.switchType, switchOutTarget.getFieldIndex(), true, true), MoveEndPhase); return true; } return false; - } else if (gScene.currentBattle.battleType !== BattleType.WILD) { + } else if (globalScene.currentBattle.battleType !== BattleType.WILD) { // Switch out logic for trainer battles - if (gScene.getEnemyParty().filter((p) => p.isAllowedInBattle() && !p.isOnField()).length < 1) { + if (globalScene.getEnemyParty().filter((p) => p.isAllowedInBattle() && !p.isOnField()).length < 1) { return false; } if (switchOutTarget.hp > 0) { // for opponent switching out switchOutTarget.leaveField(this.switchType === SwitchType.SWITCH); - gScene.prependToPhase(new SwitchSummonPhase(this.switchType, switchOutTarget.getFieldIndex(), - (gScene.currentBattle.trainer ? gScene.currentBattle.trainer.getNextSummonIndex((switchOutTarget as EnemyPokemon).trainerSlot) : 0), + globalScene.prependToPhase(new SwitchSummonPhase(this.switchType, switchOutTarget.getFieldIndex(), + (globalScene.currentBattle.trainer ? globalScene.currentBattle.trainer.getNextSummonIndex((switchOutTarget as EnemyPokemon).trainerSlot) : 0), false, false), MoveEndPhase); } } else { // Switch out logic for everything else (eg: WILD battles) - if (gScene.currentBattle.waveIndex % 10 === 0) { + if (globalScene.currentBattle.waveIndex % 10 === 0) { return false; } if (switchOutTarget.hp > 0) { switchOutTarget.leaveField(false); - gScene.queueMessage(i18next.t("moveTriggers:fled", { pokemonName: getPokemonNameWithAffix(switchOutTarget) }), null, true, 500); + globalScene.queueMessage(i18next.t("moveTriggers:fled", { pokemonName: getPokemonNameWithAffix(switchOutTarget) }), null, true, 500); // in double battles redirect potential moves off fled pokemon - if (gScene.currentBattle.double) { + if (globalScene.currentBattle.double) { const allyPokemon = switchOutTarget.getAlly(); - gScene.redirectPokemonMoves(switchOutTarget, allyPokemon); + globalScene.redirectPokemonMoves(switchOutTarget, allyPokemon); } } if (!switchOutTarget.getAlly()?.isActive(true)) { - gScene.clearEnemyHeldItemModifiers(); + globalScene.clearEnemyHeldItemModifiers(); if (switchOutTarget.hp) { - gScene.pushPhase(new BattleEndPhase()); - gScene.pushPhase(new NewBattlePhase()); + globalScene.pushPhase(new BattleEndPhase()); + globalScene.pushPhase(new NewBattlePhase()); } } } @@ -5795,7 +5795,7 @@ export class ForceSwitchOutAttr extends MoveEffectAttr { return false; } - if (!player && gScene.currentBattle.isBattleMysteryEncounter() && !gScene.currentBattle.mysteryEncounter?.fleeAllowed) { + if (!player && globalScene.currentBattle.isBattleMysteryEncounter() && !globalScene.currentBattle.mysteryEncounter?.fleeAllowed) { // Don't allow wild opponents to be force switched during MEs with flee disabled return false; } @@ -5805,25 +5805,25 @@ export class ForceSwitchOutAttr extends MoveEffectAttr { return !blockedByAbility.value; } - if (!player && gScene.currentBattle.battleType === BattleType.WILD) { + if (!player && globalScene.currentBattle.battleType === BattleType.WILD) { if (this.isBatonPass()) { return false; } // Don't allow wild opponents to flee on the boss stage since it can ruin a run early on - if (gScene.currentBattle.waveIndex % 10 === 0) { + if (globalScene.currentBattle.waveIndex % 10 === 0) { return false; } } - const party = player ? gScene.getParty() : gScene.getEnemyParty(); - return (!player && !gScene.currentBattle.battleType) + const party = player ? globalScene.getParty() : globalScene.getEnemyParty(); + return (!player && !globalScene.currentBattle.battleType) || party.filter(p => p.isAllowedInBattle() - && (player || (p as EnemyPokemon).trainerSlot === (switchOutTarget as EnemyPokemon).trainerSlot)).length > gScene.currentBattle.getBattlerCount(); + && (player || (p as EnemyPokemon).trainerSlot === (switchOutTarget as EnemyPokemon).trainerSlot)).length > globalScene.currentBattle.getBattlerCount(); }; } getUserBenefitScore(user: Pokemon, target: Pokemon, move: Move): integer { - if (!gScene.getEnemyParty().find(p => p.isActive() && !p.isOnField())) { + if (!globalScene.getEnemyParty().find(p => p.isActive() && !p.isOnField())) { return -20; } let ret = this.selfSwitch ? Math.floor((1 - user.getHpRatio()) * 20) : super.getUserBenefitScore(user, target, move); @@ -5838,13 +5838,13 @@ export class ForceSwitchOutAttr extends MoveEffectAttr { export class ChillyReceptionAttr extends ForceSwitchOutAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - gScene.arena.trySetWeather(WeatherType.SNOW, true); + globalScene.arena.trySetWeather(WeatherType.SNOW, true); return super.apply(user, target, move, args); } getCondition(): MoveConditionFunc { // chilly reception move will go through if the weather is change-able to snow, or the user can switch out, else move will fail - return (user, target, move) => gScene.arena.weather?.weatherType !== WeatherType.SNOW || super.getSwitchOutCondition()(user, target, move); + return (user, target, move) => globalScene.arena.weather?.weatherType !== WeatherType.SNOW || super.getSwitchOutCondition()(user, target, move); } } export class RemoveTypeAttr extends MoveEffectAttr { @@ -5902,7 +5902,7 @@ export class CopyTypeAttr extends MoveEffectAttr { user.summonData.types = targetTypes; user.updateInfo(); - gScene.queueMessage(i18next.t("moveTriggers:copyType", { pokemonName: getPokemonNameWithAffix(user), targetPokemonName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:copyType", { pokemonName: getPokemonNameWithAffix(user), targetPokemonName: getPokemonNameWithAffix(target) })); return true; } @@ -5922,12 +5922,12 @@ export class CopyBiomeTypeAttr extends MoveEffectAttr { return false; } - const biomeType = gScene.arena.getTypeForBiome(); + const biomeType = globalScene.arena.getTypeForBiome(); user.summonData.types = [ biomeType ]; user.updateInfo(); - gScene.queueMessage(i18next.t("moveTriggers:transformedIntoType", { pokemonName: getPokemonNameWithAffix(user), typeName: i18next.t(`pokemonInfo:Type.${Type[biomeType]}`) })); + globalScene.queueMessage(i18next.t("moveTriggers:transformedIntoType", { pokemonName: getPokemonNameWithAffix(user), typeName: i18next.t(`pokemonInfo:Type.${Type[biomeType]}`) })); return true; } @@ -5946,7 +5946,7 @@ export class ChangeTypeAttr extends MoveEffectAttr { target.summonData.types = [ this.type ]; target.updateInfo(); - gScene.queueMessage(i18next.t("moveTriggers:transformedIntoType", { pokemonName: getPokemonNameWithAffix(target), typeName: i18next.t(`pokemonInfo:Type.${Type[this.type]}`) })); + globalScene.queueMessage(i18next.t("moveTriggers:transformedIntoType", { pokemonName: getPokemonNameWithAffix(target), typeName: i18next.t(`pokemonInfo:Type.${Type[this.type]}`) })); return true; } @@ -5969,7 +5969,7 @@ export class AddTypeAttr extends MoveEffectAttr { target.summonData.addedType = this.type; target.updateInfo(); - gScene.queueMessage(i18next.t("moveTriggers:addType", { typeName: i18next.t(`pokemonInfo:Type.${Type[this.type]}`), pokemonName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:addType", { typeName: i18next.t(`pokemonInfo:Type.${Type[this.type]}`), pokemonName: getPokemonNameWithAffix(target) })); return true; } @@ -5991,7 +5991,7 @@ export class FirstMoveTypeAttr extends MoveEffectAttr { const firstMoveType = target.getMoveset()[0]?.getMove().type!; // TODO: is this bang correct? user.summonData.types = [ firstMoveType ]; - gScene.queueMessage(i18next.t("battle:transformedIntoType", { pokemonName: getPokemonNameWithAffix(user), type: i18next.t(`pokemonInfo:Type.${Type[firstMoveType]}`) })); + globalScene.queueMessage(i18next.t("battle:transformedIntoType", { pokemonName: getPokemonNameWithAffix(user), type: i18next.t(`pokemonInfo:Type.${Type[firstMoveType]}`) })); return true; } @@ -6034,7 +6034,7 @@ export class RandomMovesetMoveAttr extends OverrideMoveEffectAttr { } const targets = selectTargets; user.getMoveQueue().push({ move: move?.moveId!, targets: targets, ignorePP: true }); // TODO: is this bang correct? - gScene.unshiftPhase(new MovePhase(user, targets, moveset[moveIndex]!, true)); // There's a PR to re-do the move(s) that use this Attr, gonna put `!` for now + globalScene.unshiftPhase(new MovePhase(user, targets, moveset[moveIndex]!, true)); // There's a PR to re-do the move(s) that use this Attr, gonna put `!` for now return true; } @@ -6059,7 +6059,7 @@ export class RandomMoveAttr extends OverrideMoveEffectAttr { ? [ target.getBattlerIndex() ] : [ moveTargets.targets[user.randSeedInt(moveTargets.targets.length)] ]; user.getMoveQueue().push({ move: moveId, targets: targets, ignorePP: true }); - gScene.unshiftPhase(new MovePhase(user, targets, new PokemonMove(moveId, 0, 0, true), true)); + globalScene.unshiftPhase(new MovePhase(user, targets, new PokemonMove(moveId, 0, 0, true), true)); initMoveAnim(moveId).then(() => { loadMoveAnimAssets([ moveId ], true) .then(() => resolve(true)); @@ -6072,10 +6072,10 @@ export class NaturePowerAttr extends OverrideMoveEffectAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): Promise { return new Promise(resolve => { let moveId; - switch (gScene.arena.getTerrainType()) { + switch (globalScene.arena.getTerrainType()) { // this allows terrains to 'override' the biome move case TerrainType.NONE: - switch (gScene.arena.biomeType) { + switch (globalScene.arena.biomeType) { case Biome.TOWN: moveId = Moves.ROUND; break; @@ -6202,7 +6202,7 @@ export class NaturePowerAttr extends OverrideMoveEffectAttr { } user.getMoveQueue().push({ move: moveId, targets: [ target.getBattlerIndex() ], ignorePP: true }); - gScene.unshiftPhase(new MovePhase(user, [ target.getBattlerIndex() ], new PokemonMove(moveId, 0, 0, true), true)); + globalScene.unshiftPhase(new MovePhase(user, [ target.getBattlerIndex() ], new PokemonMove(moveId, 0, 0, true), true)); initMoveAnim(moveId).then(() => { loadMoveAnimAssets([ moveId ], true) .then(() => resolve(true)); @@ -6212,7 +6212,7 @@ export class NaturePowerAttr extends OverrideMoveEffectAttr { } const lastMoveCopiableCondition: MoveConditionFunc = (user, target, move) => { - const copiableMove = gScene.currentBattle.lastMove; + const copiableMove = globalScene.currentBattle.lastMove; if (!copiableMove) { return false; @@ -6229,7 +6229,7 @@ const lastMoveCopiableCondition: MoveConditionFunc = (user, target, move) => { export class CopyMoveAttr extends OverrideMoveEffectAttr { apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - const lastMove = gScene.currentBattle.lastMove; + const lastMove = globalScene.currentBattle.lastMove; const moveTargets = getMoveTargets(user, lastMove); if (!moveTargets.targets.length) { @@ -6243,7 +6243,7 @@ export class CopyMoveAttr extends OverrideMoveEffectAttr { : [ moveTargets.targets[user.randSeedInt(moveTargets.targets.length)] ]; user.getMoveQueue().push({ move: lastMove, targets: targets, ignorePP: true }); - gScene.unshiftPhase(new MovePhase(user as PlayerPokemon, targets, new PokemonMove(lastMove, 0, 0, true), true)); + globalScene.unshiftPhase(new MovePhase(user as PlayerPokemon, targets, new PokemonMove(lastMove, 0, 0, true), true)); return true; } @@ -6281,8 +6281,8 @@ export class ReducePpMoveAttr extends MoveEffectAttr { movesetMove!.ppUsed = Math.min((movesetMove?.ppUsed!) + this.reduction, movesetMove?.getMovePp()!); // TODO: is the bang correct? const message = i18next.t("battle:ppReduced", { targetName: getPokemonNameWithAffix(target), moveName: movesetMove?.getName(), reduction: (movesetMove?.ppUsed!) - lastPpUsed }); // TODO: is the bang correct? - gScene.eventTarget.dispatchEvent(new MoveUsedEvent(target?.id, movesetMove?.getMove()!, movesetMove?.ppUsed!)); // TODO: are these bangs correct? - gScene.queueMessage(message); + globalScene.eventTarget.dispatchEvent(new MoveUsedEvent(target?.id, movesetMove?.getMove()!, movesetMove?.ppUsed!)); // TODO: are these bangs correct? + globalScene.queueMessage(message); return true; } @@ -6393,7 +6393,7 @@ export class MovesetCopyMoveAttr extends OverrideMoveEffectAttr { user.summonData.moveset = user.getMoveset().slice(0); user.summonData.moveset[thisMoveIndex] = new PokemonMove(copiedMove.id, 0, 0); - gScene.queueMessage(i18next.t("moveTriggers:copiedMove", { pokemonName: getPokemonNameWithAffix(user), moveName: copiedMove.name })); + globalScene.queueMessage(i18next.t("moveTriggers:copiedMove", { pokemonName: getPokemonNameWithAffix(user), moveName: copiedMove.name })); return true; } @@ -6442,7 +6442,7 @@ export class SketchAttr extends MoveEffectAttr { user.setMove(sketchIndex, sketchedMove.id); - gScene.queueMessage(i18next.t("moveTriggers:sketchedMove", { pokemonName: getPokemonNameWithAffix(user), moveName: sketchedMove.name })); + globalScene.queueMessage(i18next.t("moveTriggers:sketchedMove", { pokemonName: getPokemonNameWithAffix(user), moveName: sketchedMove.name })); return true; } @@ -6500,9 +6500,9 @@ export class AbilityChangeAttr extends MoveEffectAttr { const moveTarget = this.selfTarget ? user : target; moveTarget.summonData.ability = this.ability; - gScene.triggerPokemonFormChange(moveTarget, SpeciesFormChangeRevertWeatherFormTrigger); + globalScene.triggerPokemonFormChange(moveTarget, SpeciesFormChangeRevertWeatherFormTrigger); - gScene.queueMessage(i18next.t("moveTriggers:acquiredAbility", { pokemonName: getPokemonNameWithAffix((this.selfTarget ? user : target)), abilityName: allAbilities[this.ability].name })); + globalScene.queueMessage(i18next.t("moveTriggers:acquiredAbility", { pokemonName: getPokemonNameWithAffix((this.selfTarget ? user : target)), abilityName: allAbilities[this.ability].name })); return true; } @@ -6528,11 +6528,11 @@ export class AbilityCopyAttr extends MoveEffectAttr { user.summonData.ability = target.getAbility().id; - gScene.queueMessage(i18next.t("moveTriggers:copiedTargetAbility", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), abilityName: allAbilities[target.getAbility().id].name })); + globalScene.queueMessage(i18next.t("moveTriggers:copiedTargetAbility", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target), abilityName: allAbilities[target.getAbility().id].name })); - if (this.copyToPartner && gScene.currentBattle?.double && user.getAlly().hp) { + if (this.copyToPartner && globalScene.currentBattle?.double && user.getAlly().hp) { user.getAlly().summonData.ability = target.getAbility().id; - gScene.queueMessage(i18next.t("moveTriggers:copiedTargetAbility", { pokemonName: getPokemonNameWithAffix(user.getAlly()), targetName: getPokemonNameWithAffix(target), abilityName: allAbilities[target.getAbility().id].name })); + globalScene.queueMessage(i18next.t("moveTriggers:copiedTargetAbility", { pokemonName: getPokemonNameWithAffix(user.getAlly()), targetName: getPokemonNameWithAffix(target), abilityName: allAbilities[target.getAbility().id].name })); } return true; @@ -6541,7 +6541,7 @@ export class AbilityCopyAttr extends MoveEffectAttr { getCondition(): MoveConditionFunc { return (user, target, move) => { let ret = !target.getAbility().hasAttr(UncopiableAbilityAbAttr) && !user.getAbility().hasAttr(UnsuppressableAbilityAbAttr); - if (this.copyToPartner && gScene.currentBattle?.double) { + if (this.copyToPartner && globalScene.currentBattle?.double) { ret = ret && (!user.getAlly().hp || !user.getAlly().getAbility().hasAttr(UnsuppressableAbilityAbAttr)); } else { ret = ret && user.getAbility().id !== target.getAbility().id; @@ -6565,7 +6565,7 @@ export class AbilityGiveAttr extends MoveEffectAttr { target.summonData.ability = user.getAbility().id; - gScene.queueMessage(i18next.t("moveTriggers:acquiredAbility", { pokemonName: getPokemonNameWithAffix(target), abilityName: allAbilities[user.getAbility().id].name })); + globalScene.queueMessage(i18next.t("moveTriggers:acquiredAbility", { pokemonName: getPokemonNameWithAffix(target), abilityName: allAbilities[user.getAbility().id].name })); return true; } @@ -6585,11 +6585,11 @@ export class SwitchAbilitiesAttr extends MoveEffectAttr { user.summonData.ability = target.getAbility().id; target.summonData.ability = tempAbilityId; - gScene.queueMessage(i18next.t("moveTriggers:swappedAbilitiesWithTarget", { pokemonName: getPokemonNameWithAffix(user) })); + globalScene.queueMessage(i18next.t("moveTriggers:swappedAbilitiesWithTarget", { pokemonName: getPokemonNameWithAffix(user) })); // Swaps Forecast/Flower Gift from Castform/Cherrim - gScene.arena.triggerWeatherBasedFormChangesToNormal(); + globalScene.arena.triggerWeatherBasedFormChangesToNormal(); // Swaps Forecast/Flower Gift to Castform/Cherrim (edge case) - gScene.arena.triggerWeatherBasedFormChanges(); + globalScene.arena.triggerWeatherBasedFormChanges(); return true; } @@ -6615,9 +6615,9 @@ export class SuppressAbilitiesAttr extends MoveEffectAttr { } target.summonData.abilitySuppressed = true; - gScene.arena.triggerWeatherBasedFormChangesToNormal(); + globalScene.arena.triggerWeatherBasedFormChangesToNormal(); - gScene.queueMessage(i18next.t("moveTriggers:suppressAbilities", { pokemonName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:suppressAbilities", { pokemonName: getPokemonNameWithAffix(target) })); return true; } @@ -6695,7 +6695,7 @@ export class TransformAttr extends MoveEffectAttr { user.summonData.types = target.getTypes(); promises.push(user.updateInfo()); - gScene.queueMessage(i18next.t("moveTriggers:transformedIntoTarget", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:transformedIntoTarget", { pokemonName: getPokemonNameWithAffix(user), targetName: getPokemonNameWithAffix(target) })); promises.push(user.loadAssets(false).then(() => { user.playAnim(); @@ -6738,7 +6738,7 @@ export class SwapStatAttr extends MoveEffectAttr { user.setStat(this.stat, target.getStat(this.stat, false), false); target.setStat(this.stat, temp, false); - gScene.queueMessage(i18next.t("moveTriggers:switchedStat", { + globalScene.queueMessage(i18next.t("moveTriggers:switchedStat", { pokemonName: getPokemonNameWithAffix(user), stat: i18next.t(getStatKey(this.stat)), })); @@ -6784,7 +6784,7 @@ export class ShiftStatAttr extends MoveEffectAttr { user.setStat(this.statToSwitch, secondStat, false); user.setStat(this.statToSwitchWith, firstStat, false); - gScene.queueMessage(i18next.t("moveTriggers:shiftedStats", { + globalScene.queueMessage(i18next.t("moveTriggers:shiftedStats", { pokemonName: getPokemonNameWithAffix(user), statToSwitch: i18next.t(getStatKey(this.statToSwitch)), statToSwitchWith: i18next.t(getStatKey(this.statToSwitchWith)) @@ -6843,7 +6843,7 @@ export class AverageStatsAttr extends MoveEffectAttr { target.setStat(s, avg, false); } - gScene.queueMessage(i18next.t(this.msgKey, { pokemonName: getPokemonNameWithAffix(user) })); + globalScene.queueMessage(i18next.t(this.msgKey, { pokemonName: getPokemonNameWithAffix(user) })); return true; } @@ -6871,8 +6871,8 @@ export class MoneyAttr extends MoveEffectAttr { } apply(user: Pokemon, target: Pokemon, move: Move): boolean { - gScene.currentBattle.moneyScattered += gScene.getWaveMoneyAmount(0.2); - gScene.queueMessage(i18next.t("moveTriggers:coinsScatteredEverywhere")); + globalScene.currentBattle.moneyScattered += globalScene.getWaveMoneyAmount(0.2); + globalScene.queueMessage(i18next.t("moveTriggers:coinsScatteredEverywhere")); return true; } } @@ -6896,7 +6896,7 @@ export class DestinyBondAttr extends MoveEffectAttr { * @returns true */ apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - gScene.queueMessage(`${i18next.t("moveTriggers:tryingToTakeFoeDown", { pokemonName: getPokemonNameWithAffix(user) })}`); + globalScene.queueMessage(`${i18next.t("moveTriggers:tryingToTakeFoeDown", { pokemonName: getPokemonNameWithAffix(user) })}`); user.addTag(BattlerTagType.DESTINY_BOND, undefined, move.id, user.id); return true; } @@ -6986,7 +6986,7 @@ export class AttackedByItemAttr extends MoveAttr { } const itemName = heldItems[0]?.type?.name ?? "item"; - gScene.queueMessage(i18next.t("moveTriggers:attackedByItem", { pokemonName: getPokemonNameWithAffix(target), itemName: itemName })); + globalScene.queueMessage(i18next.t("moveTriggers:attackedByItem", { pokemonName: getPokemonNameWithAffix(target), itemName: itemName })); return true; }; @@ -7025,30 +7025,30 @@ export class AfterYouAttr extends MoveEffectAttr { * @returns true */ override apply(user: Pokemon, target: Pokemon, _move: Move, _args: any[]): boolean { - gScene.queueMessage(i18next.t("moveTriggers:afterYou", { targetName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:afterYou", { targetName: getPokemonNameWithAffix(target) })); //Will find next acting phase of the targeted pokémon, delete it and queue it next on successful delete. - const nextAttackPhase = gScene.findPhase((phase) => phase.pokemon === target); - if (nextAttackPhase && gScene.tryRemovePhase((phase: MovePhase) => phase.pokemon === target)) { - gScene.prependToPhase(new MovePhase(target, [ ...nextAttackPhase.targets ], nextAttackPhase.move), MovePhase); + const nextAttackPhase = globalScene.findPhase((phase) => phase.pokemon === target); + if (nextAttackPhase && globalScene.tryRemovePhase((phase: MovePhase) => phase.pokemon === target)) { + globalScene.prependToPhase(new MovePhase(target, [ ...nextAttackPhase.targets ], nextAttackPhase.move), MovePhase); } return true; } } -const failOnGravityCondition: MoveConditionFunc = (user, target, move) => !gScene.arena.getTag(ArenaTagType.GRAVITY); +const failOnGravityCondition: MoveConditionFunc = (user, target, move) => !globalScene.arena.getTag(ArenaTagType.GRAVITY); const failOnBossCondition: MoveConditionFunc = (user, target, move) => !target.isBossImmune(); -const failIfSingleBattle: MoveConditionFunc = (user, target, move) => gScene.currentBattle.double; +const failIfSingleBattle: MoveConditionFunc = (user, target, move) => globalScene.currentBattle.double; const failIfDampCondition: MoveConditionFunc = (user, target, move) => { const cancelled = new Utils.BooleanHolder(false); - gScene.getField(true).map(p=>applyAbAttrs(FieldPreventExplosiveMovesAbAttr, p, cancelled)); + globalScene.getField(true).map(p=>applyAbAttrs(FieldPreventExplosiveMovesAbAttr, p, cancelled)); // Queue a message if an ability prevented usage of the move if (cancelled.value) { - gScene.queueMessage(i18next.t("moveTriggers:cannotUseMove", { pokemonName: getPokemonNameWithAffix(user), moveName: move.name })); + globalScene.queueMessage(i18next.t("moveTriggers:cannotUseMove", { pokemonName: getPokemonNameWithAffix(user), moveName: move.name })); } return !cancelled.value; }; @@ -7057,7 +7057,7 @@ const userSleptOrComatoseCondition: MoveConditionFunc = (user: Pokemon, target: const targetSleptOrComatoseCondition: MoveConditionFunc = (user: Pokemon, target: Pokemon, move: Move) => target.status?.effect === StatusEffect.SLEEP || target.hasAbility(Abilities.COMATOSE); -const failIfLastCondition: MoveConditionFunc = (user: Pokemon, target: Pokemon, move: Move) => gScene.phaseQueue.find(phase => phase instanceof MovePhase) !== undefined; +const failIfLastCondition: MoveConditionFunc = (user: Pokemon, target: Pokemon, move: Move) => globalScene.phaseQueue.find(phase => phase instanceof MovePhase) !== undefined; export type MoveAttrFilter = (attr: MoveAttr) => boolean; @@ -7174,13 +7174,13 @@ export class ResistLastMoveTypeAttr extends MoveEffectAttr { return false; } const userTypes = user.getTypes(); - const validTypes = this.getTypeResistances(gScene.gameMode, moveData.type).filter(t => !userTypes.includes(t)); // valid types are ones that are not already the user's types + const validTypes = this.getTypeResistances(globalScene.gameMode, moveData.type).filter(t => !userTypes.includes(t)); // valid types are ones that are not already the user's types if (!validTypes.length) { return false; } const type = validTypes[user.randSeedInt(validTypes.length)]; user.summonData.types = [ type ]; - gScene.queueMessage(i18next.t("battle:transformedIntoType", { pokemonName: getPokemonNameWithAffix(user), type: Utils.toReadableString(Type[type]) })); + globalScene.queueMessage(i18next.t("battle:transformedIntoType", { pokemonName: getPokemonNameWithAffix(user), type: Utils.toReadableString(Type[type]) })); user.updateInfo(); return true; @@ -7239,7 +7239,7 @@ export class ExposedMoveAttr extends AddBattlerTagAttr { return false; } - gScene.queueMessage(i18next.t("moveTriggers:exposedMove", { pokemonName: getPokemonNameWithAffix(user), targetPokemonName: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("moveTriggers:exposedMove", { pokemonName: getPokemonNameWithAffix(user), targetPokemonName: getPokemonNameWithAffix(target) })); return true; } @@ -7560,7 +7560,7 @@ export function initMoves() { .makesContact(false), new AttackMove(Moves.EARTHQUAKE, Type.GROUND, MoveCategory.PHYSICAL, 100, 100, 10, -1, 0, 1) .attr(HitsTagForDoubleDamageAttr, BattlerTagType.UNDERGROUND) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.GRASSY && target.isGrounded() ? 0.5 : 1) + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.GRASSY && target.isGrounded() ? 0.5 : 1) .makesContact(false) .target(MoveTarget.ALL_NEAR_OTHERS), new AttackMove(Moves.FISSURE, Type.GROUND, MoveCategory.PHYSICAL, 200, 30, 5, -1, 0, 1) @@ -7837,7 +7837,7 @@ export function initMoves() { .attr(ConfuseAttr), new SelfStatusMove(Moves.BELLY_DRUM, Type.NORMAL, -1, 10, -1, 0, 2) .attr(CutHpStatStageBoostAttr, [ Stat.ATK ], 12, 2, (user) => { - gScene.queueMessage(i18next.t("moveTriggers:cutOwnHpAndMaximizedStat", { pokemonName: getPokemonNameWithAffix(user), statName: i18next.t(getStatKey(Stat.ATK)) })); + globalScene.queueMessage(i18next.t("moveTriggers:cutOwnHpAndMaximizedStat", { pokemonName: getPokemonNameWithAffix(user), statName: i18next.t(getStatKey(Stat.ATK)) })); }), new AttackMove(Moves.SLUDGE_BOMB, Type.POISON, MoveCategory.SPECIAL, 90, 100, 10, 30, 0, 2) .attr(StatusEffectAttr, StatusEffect.POISON) @@ -7956,7 +7956,7 @@ export function initMoves() { new AttackMove(Moves.MAGNITUDE, Type.GROUND, MoveCategory.PHYSICAL, -1, 100, 30, -1, 0, 2) .attr(PreMoveMessageAttr, magnitudeMessageFunc) .attr(MagnitudePowerAttr) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.GRASSY && target.isGrounded() ? 0.5 : 1) + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.GRASSY && target.isGrounded() ? 0.5 : 1) .attr(HitsTagForDoubleDamageAttr, BattlerTagType.UNDERGROUND) .makesContact(false) .target(MoveTarget.ALL_NEAR_OTHERS), @@ -8229,7 +8229,7 @@ export function initMoves() { .attr(FlinchAttr), new AttackMove(Moves.WEATHER_BALL, Type.NORMAL, MoveCategory.SPECIAL, 50, 100, 10, -1, 0, 3) .attr(WeatherBallTypeAttr) - .attr(MovePowerMultiplierAttr, (user, target, move) => [ WeatherType.SUNNY, WeatherType.RAIN, WeatherType.SANDSTORM, WeatherType.HAIL, WeatherType.SNOW, WeatherType.FOG, WeatherType.HEAVY_RAIN, WeatherType.HARSH_SUN ].includes(gScene.arena.weather?.weatherType!) && !gScene.arena.weather?.isEffectSuppressed() ? 2 : 1) // TODO: is this bang correct? + .attr(MovePowerMultiplierAttr, (user, target, move) => [ WeatherType.SUNNY, WeatherType.RAIN, WeatherType.SANDSTORM, WeatherType.HAIL, WeatherType.SNOW, WeatherType.FOG, WeatherType.HEAVY_RAIN, WeatherType.HARSH_SUN ].includes(globalScene.arena.weather?.weatherType!) && !globalScene.arena.weather?.isEffectSuppressed() ? 2 : 1) // TODO: is this bang correct? .ballBombMove(), new StatusMove(Moves.AROMATHERAPY, Type.GRASS, -1, 5, -1, 0, 3) .attr(PartyStatusCureAttr, i18next.t("moveTriggers:soothingAromaWaftedThroughArea"), Abilities.SAP_SIPPER) @@ -8402,7 +8402,7 @@ export function initMoves() { new AttackMove(Moves.CLOSE_COMBAT, Type.FIGHTING, MoveCategory.PHYSICAL, 120, 100, 5, -1, 0, 4) .attr(StatStageChangeAttr, [ Stat.DEF, Stat.SPDEF ], -1, true), new AttackMove(Moves.PAYBACK, Type.DARK, MoveCategory.PHYSICAL, 50, 100, 10, -1, 0, 4) - .attr(MovePowerMultiplierAttr, (user, target, move) => target.getLastXMoves(1).find(m => m.turn === gScene.currentBattle.turn) || gScene.currentBattle.turnCommands[target.getBattlerIndex()]?.command === Command.BALL ? 2 : 1), + .attr(MovePowerMultiplierAttr, (user, target, move) => target.getLastXMoves(1).find(m => m.turn === globalScene.currentBattle.turn) || globalScene.currentBattle.turnCommands[target.getBattlerIndex()]?.command === Command.BALL ? 2 : 1), new AttackMove(Moves.ASSURANCE, Type.DARK, MoveCategory.PHYSICAL, 60, 100, 10, -1, 0, 4) .attr(MovePowerMultiplierAttr, (user, target, move) => target.turnData.damageTaken > 0 ? 2 : 1), new StatusMove(Moves.EMBARGO, Type.DARK, 100, 15, -1, 0, 4) @@ -8458,7 +8458,7 @@ export function initMoves() { new StatusMove(Moves.WORRY_SEED, Type.GRASS, 100, 10, -1, 0, 4) .attr(AbilityChangeAttr, Abilities.INSOMNIA), new AttackMove(Moves.SUCKER_PUNCH, Type.DARK, MoveCategory.PHYSICAL, 70, 100, 5, -1, 1, 4) - .condition((user, target, move) => gScene.currentBattle.turnCommands[target.getBattlerIndex()]?.command === Command.FIGHT && !target.turnData.acted && allMoves[gScene.currentBattle.turnCommands[target.getBattlerIndex()]?.move?.move!].category !== MoveCategory.STATUS), // TODO: is this bang correct? + .condition((user, target, move) => globalScene.currentBattle.turnCommands[target.getBattlerIndex()]?.command === Command.FIGHT && !target.turnData.acted && allMoves[globalScene.currentBattle.turnCommands[target.getBattlerIndex()]?.move?.move!].category !== MoveCategory.STATUS), // TODO: is this bang correct? new StatusMove(Moves.TOXIC_SPIKES, Type.POISON, -1, 20, -1, 0, 4) .attr(AddArenaTrapTagAttr, ArenaTagType.TOXIC_SPIKES) .target(MoveTarget.ENEMY_SIDE), @@ -8469,7 +8469,7 @@ export function initMoves() { .attr(AddBattlerTagAttr, BattlerTagType.AQUA_RING, true, true), new SelfStatusMove(Moves.MAGNET_RISE, Type.ELECTRIC, -1, 10, -1, 0, 4) .attr(AddBattlerTagAttr, BattlerTagType.FLOATING, true, true) - .condition((user, target, move) => !gScene.arena.getTag(ArenaTagType.GRAVITY) && [ BattlerTagType.FLOATING, BattlerTagType.IGNORE_FLYING, BattlerTagType.INGRAIN ].every((tag) => !user.getTag(tag))), + .condition((user, target, move) => !globalScene.arena.getTag(ArenaTagType.GRAVITY) && [ BattlerTagType.FLOATING, BattlerTagType.IGNORE_FLYING, BattlerTagType.INGRAIN ].every((tag) => !user.getTag(tag))), new AttackMove(Moves.FLARE_BLITZ, Type.FIRE, MoveCategory.PHYSICAL, 120, 100, 15, 10, 0, 4) .attr(RecoilAttr, false, 0.33) .attr(HealStatusEffectAttr, true, StatusEffect.FREEZE) @@ -8814,9 +8814,9 @@ export function initMoves() { .attr(CopyTypeAttr), new AttackMove(Moves.RETALIATE, Type.NORMAL, MoveCategory.PHYSICAL, 70, 100, 5, -1, 0, 5) .attr(MovePowerMultiplierAttr, (user, target, move) => { - const turn = gScene.currentBattle.turn; - const lastPlayerFaint = gScene.currentBattle.playerFaintsHistory[gScene.currentBattle.playerFaintsHistory.length - 1]; - const lastEnemyFaint = gScene.currentBattle.enemyFaintsHistory[gScene.currentBattle.enemyFaintsHistory.length - 1]; + const turn = globalScene.currentBattle.turn; + const lastPlayerFaint = globalScene.currentBattle.playerFaintsHistory[globalScene.currentBattle.playerFaintsHistory.length - 1]; + const lastEnemyFaint = globalScene.currentBattle.enemyFaintsHistory[globalScene.currentBattle.enemyFaintsHistory.length - 1]; return ( (lastPlayerFaint !== undefined && turn - lastPlayerFaint.turn === 1 && user.isPlayer()) || (lastEnemyFaint !== undefined && turn - lastEnemyFaint.turn === 1 && !user.isPlayer()) @@ -8862,7 +8862,7 @@ export function initMoves() { .target(MoveTarget.ALL_NEAR_ENEMIES), new AttackMove(Moves.BULLDOZE, Type.GROUND, MoveCategory.PHYSICAL, 60, 100, 20, 100, 0, 5) .attr(StatStageChangeAttr, [ Stat.SPD ], -1) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.GRASSY && target.isGrounded() ? 0.5 : 1) + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.GRASSY && target.isGrounded() ? 0.5 : 1) .makesContact(false) .target(MoveTarget.ALL_NEAR_OTHERS), new AttackMove(Moves.FROST_BREATH, Type.ICE, MoveCategory.SPECIAL, 60, 90, 10, 100, 0, 5) @@ -8984,7 +8984,7 @@ export function initMoves() { .target(MoveTarget.ALL) .condition((user, target, move) => { // If any fielded pokémon is grass-type and grounded. - return [ ...gScene.getEnemyParty(), ...gScene.getParty() ].some((poke) => poke.isOfType(Type.GRASS) && poke.isGrounded()); + return [ ...globalScene.getEnemyParty(), ...globalScene.getParty() ].some((poke) => poke.isOfType(Type.GRASS) && poke.isGrounded()); }) .attr(StatStageChangeAttr, [ Stat.ATK, Stat.SPATK ], 1, false, (user, target, move) => target.isOfType(Type.GRASS) && target.isGrounded()), new StatusMove(Moves.STICKY_WEB, Type.BUG, -1, 20, -1, 0, 6) @@ -9304,7 +9304,7 @@ export function initMoves() { .attr(StatStageChangeAttr, [ Stat.SPD ], -1, true) .punchingMove(), new StatusMove(Moves.FLORAL_HEALING, Type.FAIRY, -1, 10, -1, 0, 7) - .attr(BoostHealAttr, 0.5, 2 / 3, true, false, (user, target, move) => gScene.arena.terrain?.terrainType === TerrainType.GRASSY) + .attr(BoostHealAttr, 0.5, 2 / 3, true, false, (user, target, move) => globalScene.arena.terrain?.terrainType === TerrainType.GRASSY) .triageMove(), new AttackMove(Moves.HIGH_HORSEPOWER, Type.GROUND, MoveCategory.PHYSICAL, 95, 95, 10, -1, 0, 7), new StatusMove(Moves.STRENGTH_SAP, Type.GRASS, 100, 10, -1, 0, 7) @@ -9356,7 +9356,7 @@ export function initMoves() { .attr(HealStatusEffectAttr, true, StatusEffect.FREEZE) .attr(AddBattlerTagAttr, BattlerTagType.BURNED_UP, true, false) .attr(RemoveTypeAttr, Type.FIRE, (user) => { - gScene.queueMessage(i18next.t("moveTriggers:burnedItselfOut", { pokemonName: getPokemonNameWithAffix(user) })); + globalScene.queueMessage(i18next.t("moveTriggers:burnedItselfOut", { pokemonName: getPokemonNameWithAffix(user) })); }), new StatusMove(Moves.SPEED_SWAP, Type.PSYCHIC, -1, 10, -1, 0, 7) .attr(SwapStatAttr, Stat.SPD) @@ -9391,7 +9391,7 @@ export function initMoves() { new AttackMove(Moves.BRUTAL_SWING, Type.DARK, MoveCategory.PHYSICAL, 60, 100, 20, -1, 0, 7) .target(MoveTarget.ALL_NEAR_OTHERS), new StatusMove(Moves.AURORA_VEIL, Type.ICE, -1, 20, -1, 0, 7) - .condition((user, target, move) => (gScene.arena.weather?.weatherType === WeatherType.HAIL || gScene.arena.weather?.weatherType === WeatherType.SNOW) && !gScene.arena.weather?.isEffectSuppressed()) + .condition((user, target, move) => (globalScene.arena.weather?.weatherType === WeatherType.HAIL || globalScene.arena.weather?.weatherType === WeatherType.SNOW) && !globalScene.arena.weather?.isEffectSuppressed()) .attr(AddArenaTagAttr, ArenaTagType.AURORA_VEIL, 5, true) .target(MoveTarget.USER_SIDE), /* Unused */ @@ -9547,10 +9547,10 @@ export function initMoves() { new AttackMove(Moves.DYNAMAX_CANNON, Type.DRAGON, MoveCategory.SPECIAL, 100, 100, 5, -1, 0, 8) .attr(MovePowerMultiplierAttr, (user, target, move) => { // Move is only stronger against overleveled foes. - if (target.level > gScene.getMaxExpLevel()) { + if (target.level > globalScene.getMaxExpLevel()) { const dynamaxCannonPercentMarginBeforeFullDamage = 0.05; // How much % above MaxExpLevel of wave will the target need to be to take full damage. // The move's power scales as the margin is approached, reaching double power when it does or goes over it. - return 1 + Math.min(1, (target.level - gScene.getMaxExpLevel()) / (gScene.getMaxExpLevel() * dynamaxCannonPercentMarginBeforeFullDamage)); + return 1 + Math.min(1, (target.level - globalScene.getMaxExpLevel()) / (globalScene.getMaxExpLevel() * dynamaxCannonPercentMarginBeforeFullDamage)); } else { return 1; } @@ -9568,7 +9568,7 @@ export function initMoves() { .attr(EatBerryAttr) .attr(StatStageChangeAttr, [ Stat.DEF ], 2, true) .condition((user) => { - const userBerries = gScene.findModifiers(m => m instanceof BerryModifier, user.isPlayer()); + const userBerries = globalScene.findModifiers(m => m instanceof BerryModifier, user.isPlayer()); return userBerries.length > 0; }) .edgeCase(), // Stuff Cheeks should not be selectable when the user does not have a berry, see wiki @@ -9708,7 +9708,7 @@ export function initMoves() { .attr(StatStageChangeAttr, [ Stat.SPDEF ], -1), new AttackMove(Moves.GRAV_APPLE, Type.GRASS, MoveCategory.PHYSICAL, 80, 100, 10, 100, 0, 8) .attr(StatStageChangeAttr, [ Stat.DEF ], -1) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTag(ArenaTagType.GRAVITY) ? 1.5 : 1) + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTag(ArenaTagType.GRAVITY) ? 1.5 : 1) .makesContact(false), new AttackMove(Moves.SPIRIT_BREAK, Type.FAIRY, MoveCategory.PHYSICAL, 75, 100, 15, 100, 0, 8) .attr(StatStageChangeAttr, [ Stat.SPATK ], -1), @@ -9730,11 +9730,11 @@ export function initMoves() { new AttackMove(Moves.STEEL_BEAM, Type.STEEL, MoveCategory.SPECIAL, 140, 95, 5, -1, 0, 8) .attr(HalfSacrificialAttr), new AttackMove(Moves.EXPANDING_FORCE, Type.PSYCHIC, MoveCategory.SPECIAL, 80, 100, 10, -1, 0, 8) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.PSYCHIC && user.isGrounded() ? 1.5 : 1) - .attr(VariableTargetAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.PSYCHIC && user.isGrounded() ? MoveTarget.ALL_NEAR_ENEMIES : MoveTarget.NEAR_OTHER), + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.PSYCHIC && user.isGrounded() ? 1.5 : 1) + .attr(VariableTargetAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.PSYCHIC && user.isGrounded() ? MoveTarget.ALL_NEAR_ENEMIES : MoveTarget.NEAR_OTHER), new AttackMove(Moves.STEEL_ROLLER, Type.STEEL, MoveCategory.PHYSICAL, 130, 100, 5, -1, 0, 8) .attr(ClearTerrainAttr) - .condition((user, target, move) => !!gScene.arena.terrain), + .condition((user, target, move) => !!globalScene.arena.terrain), new AttackMove(Moves.SCALE_SHOT, Type.DRAGON, MoveCategory.PHYSICAL, 25, 90, 20, -1, 0, 8) .attr(StatStageChangeAttr, [ Stat.SPD ], 1, true, null, true, false, MoveEffectTrigger.HIT, false, true) .attr(StatStageChangeAttr, [ Stat.DEF ], -1, true, null, true, false, MoveEffectTrigger.HIT, false, true) @@ -9751,16 +9751,16 @@ export function initMoves() { new AttackMove(Moves.MISTY_EXPLOSION, Type.FAIRY, MoveCategory.SPECIAL, 100, 100, 5, -1, 0, 8) .attr(SacrificialAttr) .target(MoveTarget.ALL_NEAR_OTHERS) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.MISTY && user.isGrounded() ? 1.5 : 1) + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.MISTY && user.isGrounded() ? 1.5 : 1) .condition(failIfDampCondition) .makesContact(false), new AttackMove(Moves.GRASSY_GLIDE, Type.GRASS, MoveCategory.PHYSICAL, 55, 100, 20, -1, 0, 8) - .attr(IncrementMovePriorityAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.GRASSY && user.isGrounded()), + .attr(IncrementMovePriorityAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.GRASSY && user.isGrounded()), new AttackMove(Moves.RISING_VOLTAGE, Type.ELECTRIC, MoveCategory.SPECIAL, 70, 100, 20, -1, 0, 8) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.ELECTRIC && target.isGrounded() ? 2 : 1), + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.ELECTRIC && target.isGrounded() ? 2 : 1), new AttackMove(Moves.TERRAIN_PULSE, Type.NORMAL, MoveCategory.SPECIAL, 50, 100, 10, -1, 0, 8) .attr(TerrainPulseTypeAttr) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTerrainType() !== TerrainType.NONE && user.isGrounded() ? 2 : 1) + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTerrainType() !== TerrainType.NONE && user.isGrounded() ? 2 : 1) .pulseMove(), new AttackMove(Moves.SKITTER_SMACK, Type.BUG, MoveCategory.PHYSICAL, 70, 90, 10, 100, 0, 8) .attr(StatStageChangeAttr, [ Stat.SPATK ], -1), @@ -10019,7 +10019,7 @@ export function initMoves() { .recklessMove(), new AttackMove(Moves.LAST_RESPECTS, Type.GHOST, MoveCategory.PHYSICAL, 50, 100, 10, -1, 0, 9) .partial() // Counter resets every wave instead of on arena reset - .attr(MovePowerMultiplierAttr, (user, target, move) => 1 + Math.min(user.isPlayer() ? gScene.currentBattle.playerFaints : gScene.currentBattle.enemyFaints, 100)) + .attr(MovePowerMultiplierAttr, (user, target, move) => 1 + Math.min(user.isPlayer() ? globalScene.currentBattle.playerFaints : globalScene.currentBattle.enemyFaints, 100)) .makesContact(false), new AttackMove(Moves.LUMINA_CRASH, Type.PSYCHIC, MoveCategory.SPECIAL, 80, 100, 10, 100, 0, 9) .attr(StatStageChangeAttr, [ Stat.SPDEF ], -2), @@ -10043,7 +10043,7 @@ export function initMoves() { .attr(AddBattlerTagAttr, BattlerTagType.ALWAYS_GET_HIT, true, false, 0, 0, true) .attr(AddBattlerTagAttr, BattlerTagType.RECEIVE_DOUBLE_DAMAGE, true, false, 0, 0, true) .condition((user, target, move) => { - return !(target.getTag(BattlerTagType.PROTECTED)?.tagType === "PROTECTED" || gScene.arena.getTag(ArenaTagType.MAT_BLOCK)?.tagType === "MAT_BLOCK"); + return !(target.getTag(BattlerTagType.PROTECTED)?.tagType === "PROTECTED" || globalScene.arena.getTag(ArenaTagType.MAT_BLOCK)?.tagType === "MAT_BLOCK"); }), new StatusMove(Moves.REVIVAL_BLESSING, Type.NORMAL, -1, 1, -1, 0, 9) .triageMove() @@ -10094,11 +10094,11 @@ export function initMoves() { .attr(StatStageChangeAttr, [ Stat.SPATK ], -1, true, null, true, false, MoveEffectTrigger.HIT, true) .target(MoveTarget.ALL_NEAR_ENEMIES), new AttackMove(Moves.PSYBLADE, Type.PSYCHIC, MoveCategory.PHYSICAL, 80, 100, 15, -1, 0, 9) - .attr(MovePowerMultiplierAttr, (user, target, move) => gScene.arena.getTerrainType() === TerrainType.ELECTRIC && user.isGrounded() ? 1.5 : 1) + .attr(MovePowerMultiplierAttr, (user, target, move) => globalScene.arena.getTerrainType() === TerrainType.ELECTRIC && user.isGrounded() ? 1.5 : 1) .slicingMove(), new AttackMove(Moves.HYDRO_STEAM, Type.WATER, MoveCategory.SPECIAL, 80, 100, 15, -1, 0, 9) .attr(IgnoreWeatherTypeDebuffAttr, WeatherType.SUNNY) - .attr(MovePowerMultiplierAttr, (user, target, move) => [ WeatherType.SUNNY, WeatherType.HARSH_SUN ].includes(gScene.arena.weather?.weatherType!) && !gScene.arena.weather?.isEffectSuppressed() ? 1.5 : 1), // TODO: is this bang correct? + .attr(MovePowerMultiplierAttr, (user, target, move) => [ WeatherType.SUNNY, WeatherType.HARSH_SUN ].includes(globalScene.arena.weather?.weatherType!) && !globalScene.arena.weather?.isEffectSuppressed() ? 1.5 : 1), // TODO: is this bang correct? new AttackMove(Moves.RUINATION, Type.DARK, MoveCategory.SPECIAL, -1, 90, 10, -1, 0, 9) .attr(TargetHalfHpDamageAttr), new AttackMove(Moves.COLLISION_COURSE, Type.FIGHTING, MoveCategory.PHYSICAL, 100, 100, 5, -1, 0, 9) @@ -10145,7 +10145,7 @@ export function initMoves() { }) .attr(AddBattlerTagAttr, BattlerTagType.DOUBLE_SHOCKED, true, false) .attr(RemoveTypeAttr, Type.ELECTRIC, (user) => { - gScene.queueMessage(i18next.t("moveTriggers:usedUpAllElectricity", { pokemonName: getPokemonNameWithAffix(user) })); + globalScene.queueMessage(i18next.t("moveTriggers:usedUpAllElectricity", { pokemonName: getPokemonNameWithAffix(user) })); }), new AttackMove(Moves.GIGATON_HAMMER, Type.STEEL, MoveCategory.PHYSICAL, 160, 100, 5, -1, 0, 9) .makesContact(false) @@ -10212,7 +10212,7 @@ export function initMoves() { .attr(ProtectAttr, BattlerTagType.BURNING_BULWARK) .condition(failIfLastCondition), new AttackMove(Moves.THUNDERCLAP, Type.ELECTRIC, MoveCategory.SPECIAL, 70, 100, 5, -1, 1, 9) - .condition((user, target, move) => gScene.currentBattle.turnCommands[target.getBattlerIndex()]?.command === Command.FIGHT && !target.turnData.acted && allMoves[gScene.currentBattle.turnCommands[target.getBattlerIndex()]?.move?.move!].category !== MoveCategory.STATUS), // TODO: is this bang correct? + .condition((user, target, move) => globalScene.currentBattle.turnCommands[target.getBattlerIndex()]?.command === Command.FIGHT && !target.turnData.acted && allMoves[globalScene.currentBattle.turnCommands[target.getBattlerIndex()]?.move?.move!].category !== MoveCategory.STATUS), // TODO: is this bang correct? new AttackMove(Moves.MIGHTY_CLEAVE, Type.ROCK, MoveCategory.PHYSICAL, 95, 100, 5, -1, 0, 9) .slicingMove() .ignoresProtect(), @@ -10238,7 +10238,7 @@ export function initMoves() { .attr(AddBattlerTagAttr, BattlerTagType.HEAL_BLOCK, false, false, 2), new AttackMove(Moves.UPPER_HAND, Type.FIGHTING, MoveCategory.PHYSICAL, 65, 100, 15, 100, 3, 9) .attr(FlinchAttr) - .condition((user, target, move) => gScene.currentBattle.turnCommands[target.getBattlerIndex()]?.command === Command.FIGHT && !target.turnData.acted && allMoves[gScene.currentBattle.turnCommands[target.getBattlerIndex()]?.move?.move!].category !== MoveCategory.STATUS && allMoves[gScene.currentBattle.turnCommands[target.getBattlerIndex()]?.move?.move!].priority > 0 ) // TODO: is this bang correct? + .condition((user, target, move) => globalScene.currentBattle.turnCommands[target.getBattlerIndex()]?.command === Command.FIGHT && !target.turnData.acted && allMoves[globalScene.currentBattle.turnCommands[target.getBattlerIndex()]?.move?.move!].category !== MoveCategory.STATUS && allMoves[globalScene.currentBattle.turnCommands[target.getBattlerIndex()]?.move?.move!].priority > 0 ) // TODO: is this bang correct? .partial(), // Should also apply when target move priority increased by ability ex. gale wings new AttackMove(Moves.MALIGNANT_CHAIN, Type.POISON, MoveCategory.SPECIAL, 100, 100, 5, 50, 0, 9) .attr(StatusEffectAttr, StatusEffect.TOXIC) diff --git a/src/data/mystery-encounters/encounters/a-trainers-test-encounter.ts b/src/data/mystery-encounters/encounters/a-trainers-test-encounter.ts index 1ec55fb0236..ca5f076df3d 100644 --- a/src/data/mystery-encounters/encounters/a-trainers-test-encounter.ts +++ b/src/data/mystery-encounters/encounters/a-trainers-test-encounter.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -37,7 +37,7 @@ export const ATrainersTestEncounter: MysteryEncounter = ]) .withAutoHideIntroVisuals(false) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Randomly pick from 1 of the 5 stat trainers to spawn let trainerType: TrainerType; @@ -139,7 +139,7 @@ export const ATrainersTestEncounter: MysteryEncounter = buttonTooltip: `${namespace}:option.1.tooltip` }, async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Battle the stat trainer for an Egg and great rewards const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0]; @@ -162,9 +162,9 @@ export const ATrainersTestEncounter: MysteryEncounter = buttonTooltip: `${namespace}:option.2.tooltip` }, async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Full heal party - gScene.unshiftPhase(new PartyHealPhase(true)); + globalScene.unshiftPhase(new PartyHealPhase(true)); const eggOptions: IEggOptions = { pulled: false, diff --git a/src/data/mystery-encounters/encounters/absolute-avarice-encounter.ts b/src/data/mystery-encounters/encounters/absolute-avarice-encounter.ts index 4e96a8d2eea..1fc080c9714 100644 --- a/src/data/mystery-encounters/encounters/absolute-avarice-encounter.ts +++ b/src/data/mystery-encounters/encounters/absolute-avarice-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -171,17 +171,17 @@ export const AbsoluteAvariceEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; - gScene.loadSe("PRSFX- Bug Bite", "battle_anims", "PRSFX- Bug Bite.wav"); - gScene.loadSe("Follow Me", "battle_anims", "Follow Me.mp3"); + globalScene.loadSe("PRSFX- Bug Bite", "battle_anims", "PRSFX- Bug Bite.wav"); + globalScene.loadSe("Follow Me", "battle_anims", "Follow Me.mp3"); // Get all player berry items, remove from party, and store reference - const berryItems = gScene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[]; + const berryItems = globalScene.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(); - gScene.getParty().forEach(pokemon => { + globalScene.getParty().forEach(pokemon => { const pokemonBerries = berryItems.filter(b => b.pokemonId === pokemon.id); if (pokemonBerries?.length > 0) { berryItemsMap.set(pokemon.id, pokemonBerries); @@ -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)[] = gScene.currentBattle.waveIndex < 50 ? + const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = globalScene.currentBattle.waveIndex < 50 ? [ Stat.SPDEF ] : [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ]; @@ -221,7 +221,7 @@ export const AbsoluteAvariceEncounter: MysteryEncounter = tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ], mysteryEncounterBattleEffects: (pokemon: Pokemon) => { queueEncounterMessage(`${namespace}:option.1.boss_enraged`); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1)); } } ], @@ -238,12 +238,12 @@ export const AbsoluteAvariceEncounter: MysteryEncounter = // Remove the berries from the party // Session has been safely saved at this point, so data won't be lost - const berryItems = gScene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[]; + const berryItems = globalScene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[]; berryItems.forEach(berryMod => { - gScene.removeModifier(berryMod); + globalScene.removeModifier(berryMod); }); - gScene.updateModifiers(true); + globalScene.updateModifiers(true); return true; }) @@ -261,18 +261,18 @@ export const AbsoluteAvariceEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Pick battle - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Provides 1x Reviver Seed to each party member at end of battle const revSeed = generateModifierType(modifierTypes.REVIVER_SEED); encounter.setDialogueToken("foodReward", revSeed?.name ?? i18next.t("modifierType:ModifierType.REVIVER_SEED.name")); const givePartyPokemonReviverSeeds = () => { - const party = gScene.getParty(); + const party = globalScene.getParty(); party.forEach(p => { const heldItems = p.getHeldItems(); if (revSeed && !heldItems.some(item => item instanceof PokemonInstantReviveModifier)) { const seedModifier = revSeed.newModifier(p); - gScene.addModifier(seedModifier, false, false, false, true); + globalScene.addModifier(seedModifier, false, false, false, true); } }); queueEncounterMessage(`${namespace}:option.1.food_stash`); @@ -304,11 +304,11 @@ export const AbsoluteAvariceEncounter: MysteryEncounter = ], }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const berryMap = encounter.misc.berryItemsMap; // Returns 2/5 of the berries stolen to each Pokemon - const party = gScene.getParty(); + const party = globalScene.getParty(); party.forEach(pokemon => { const stolenBerries: BerryModifier[] = berryMap.get(pokemon.id); const berryTypesAsArray: BerryType[] = []; @@ -326,7 +326,7 @@ export const AbsoluteAvariceEncounter: MysteryEncounter = } } }); - await gScene.updateModifiers(true); + await globalScene.updateModifiers(true); await transitionMysteryEncounterIntroVisuals(true, true, 500); leaveEncounterWithoutBattle(true); @@ -371,10 +371,10 @@ function doGreedentSpriteSteal() { const shakeDelay = 50; const slideDelay = 500; - const greedentSprites = gScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1); + const greedentSprites = globalScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1); - gScene.playSound("battle_anims/Follow Me"); - gScene.tweens.chain({ + globalScene.playSound("battle_anims/Follow Me"); + globalScene.tweens.chain({ targets: greedentSprites, tweens: [ { // Slide Greedent diagonally @@ -445,9 +445,9 @@ function doGreedentSpriteSteal() { } function doGreedentEatBerries() { - const greedentSprites = gScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1); + const greedentSprites = globalScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1); let index = 1; - gScene.tweens.add({ + globalScene.tweens.add({ targets: greedentSprites, duration: 150, ease: "Cubic.easeOut", @@ -455,11 +455,11 @@ function doGreedentEatBerries() { y: "-=8", loop: 5, onStart: () => { - gScene.playSound("battle_anims/PRSFX- Bug Bite"); + globalScene.playSound("battle_anims/PRSFX- Bug Bite"); }, onLoop: () => { if (index % 2 === 0) { - gScene.playSound("battle_anims/PRSFX- Bug Bite"); + globalScene.playSound("battle_anims/PRSFX- Bug Bite"); } index++; } @@ -477,7 +477,7 @@ function doBerrySpritePile(isEat: boolean = false) { if (isEat) { animationOrder = animationOrder.reverse(); } - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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(isEat: boolean = false) { sprite = sprites[0]; tintSprite = sprites[1]; } - gScene.time.delayedCall(berryAddDelay * i + 400, () => { + globalScene.time.delayedCall(berryAddDelay * i + 400, () => { if (sprite) { sprite.setVisible(!isEat); } @@ -496,7 +496,7 @@ function doBerrySpritePile(isEat: boolean = false) { // Animate Petaya berry falling off the pile if (berry === "petaya" && sprite && tintSprite && !isEat) { - gScene.time.delayedCall(200, () => { + globalScene.time.delayedCall(200, () => { doBerryBounce([ sprite, tintSprite ], 30, 500); }); } @@ -509,7 +509,7 @@ function doBerryBounce(berrySprites: Phaser.GameObjects.Sprite[], yd: number, ba let bounceYOffset = yd; const doBounce = () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: berrySprites, y: "+=" + bounceYOffset, x: { value: "+=" + (bouncePower * bouncePower * 10), ease: "Linear" }, @@ -521,7 +521,7 @@ function doBerryBounce(berrySprites: Phaser.GameObjects.Sprite[], yd: number, ba if (bouncePower) { bounceYOffset = bounceYOffset * bouncePower; - gScene.tweens.add({ + globalScene.tweens.add({ targets: berrySprites, y: "-=" + bounceYOffset, x: { value: "+=" + (bouncePower * bouncePower * 10), ease: "Linear" }, diff --git a/src/data/mystery-encounters/encounters/an-offer-you-cant-refuse-encounter.ts b/src/data/mystery-encounters/encounters/an-offer-you-cant-refuse-encounter.ts index 001b47bb175..9c290d71dc0 100644 --- a/src/data/mystery-encounters/encounters/an-offer-you-cant-refuse-encounter.ts +++ b/src/data/mystery-encounters/encounters/an-offer-you-cant-refuse-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -70,13 +70,13 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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 = gScene.getWaveMoneyAmount(multiplier); + const price = globalScene.getWaveMoneyAmount(multiplier); encounter.setDialogueToken("strongestPokemon", pokemon.getNameToRender()); encounter.setDialogueToken("price", price.toString()); @@ -119,15 +119,15 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter = ], }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Update money and remove pokemon from party updatePlayerMoney(encounter.misc.price); - gScene.removePokemonFromPlayerParty(encounter.misc.pokemon); + globalScene.removePokemonFromPlayerParty(encounter.misc.pokemon); return true; }) .withOptionPhase(async () => { // Give the player a Shiny Charm - gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.SHINY_CHARM)); + globalScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.SHINY_CHARM)); leaveEncounterWithoutBattle(true); }) .build() @@ -154,7 +154,7 @@ export const AnOfferYouCantRefuseEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Extort the rich kid for money - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Update money and remove pokemon from party updatePlayerMoney(encounter.misc.price); diff --git a/src/data/mystery-encounters/encounters/berries-abound-encounter.ts b/src/data/mystery-encounters/encounters/berries-abound-encounter.ts index 9d7cdb91afa..b63a31ec0df 100644 --- a/src/data/mystery-encounters/encounters/berries-abound-encounter.ts +++ b/src/data/mystery-encounters/encounters/berries-abound-encounter.ts @@ -20,7 +20,7 @@ import { import { randSeedInt } from "#app/utils"; import { BattlerTagType } from "#enums/battler-tag-type"; import { MysteryEncounterType } from "#enums/mystery-encounter-type"; -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -58,11 +58,11 @@ export const BerriesAboundEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculate boss mon const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER); - const bossSpecies = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true); + const bossSpecies = globalScene.arena.randomSpecies(globalScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(globalScene.getParty()), true); const bossPokemon = new EnemyPokemon(bossSpecies, level, TrainerSlot.NONE, true); encounter.setDialogueToken("enemyPokemon", getPokemonNameWithAffix(bossPokemon)); const config: EnemyPartyConfig = { @@ -78,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 = - gScene.currentBattle.waveIndex > 160 ? 7 - : gScene.currentBattle.waveIndex > 120 ? 5 - : gScene.currentBattle.waveIndex > 40 ? 4 : 2; - regenerateModifierPoolThresholds(gScene.getParty(), ModifierPoolType.PLAYER, 0); + globalScene.currentBattle.waveIndex > 160 ? 7 + : globalScene.currentBattle.waveIndex > 120 ? 5 + : globalScene.currentBattle.waveIndex > 40 ? 4 : 2; + regenerateModifierPoolThresholds(globalScene.getParty(), ModifierPoolType.PLAYER, 0); encounter.misc = { numBerries }; const { spriteKey, fileRoot } = getSpriteKeysFromPokemon(bossPokemon); @@ -130,13 +130,13 @@ export const BerriesAboundEncounter: MysteryEncounter = }, async () => { // Pick battle - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const numBerries = encounter.misc.numBerries; const doBerryRewards = () => { const berryText = i18next.t(`${namespace}:berries`); - gScene.playSound("item_fanfare"); + globalScene.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 @@ -155,7 +155,7 @@ export const BerriesAboundEncounter: MysteryEncounter = } setEncounterRewards({ guaranteedModifierTypeOptions: shopOptions, fillRemaining: false }, undefined, doBerryRewards); - await initBattleWithEnemyConfig(gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]); + await initBattleWithEnemyConfig(globalScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]); } ) .withOption( @@ -167,7 +167,7 @@ export const BerriesAboundEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Pick race for berries - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const fastestPokemon: PlayerPokemon = encounter.misc.fastestPokemon; const enemySpeed: number = encounter.misc.enemySpeed; const speedDiff = fastestPokemon.getStat(Stat.SPD) / (enemySpeed * 1.1); @@ -187,7 +187,7 @@ export const BerriesAboundEncounter: MysteryEncounter = const doBerryRewards = () => { const berryText = i18next.t(`${namespace}:berries`); - gScene.playSound("item_fanfare"); + globalScene.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 @@ -197,15 +197,15 @@ export const BerriesAboundEncounter: 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)[] = gScene.currentBattle.waveIndex < 50 ? + const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = globalScene.currentBattle.waveIndex < 50 ? [ Stat.DEF, Stat.SPDEF, Stat.SPD ] : [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ]; - const config = gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]; + const config = globalScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]; config.pokemonConfigs![0].tags = [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ]; config.pokemonConfigs![0].mysteryEncounterBattleEffects = (pokemon: Pokemon) => { queueEncounterMessage(`${namespace}:option.2.boss_enraged`); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1)); }; setEncounterRewards({ guaranteedModifierTypeOptions: shopOptions, fillRemaining: false }, undefined, doBerryRewards); await showEncounterText(`${namespace}:option.2.selected_bad`); @@ -218,7 +218,7 @@ export const BerriesAboundEncounter: MysteryEncounter = const doFasterBerryRewards = () => { const berryText = i18next.t(`${namespace}:berries`); - gScene.playSound("item_fanfare"); + globalScene.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) @@ -257,11 +257,11 @@ function tryGiveBerry(prioritizedPokemon?: PlayerPokemon) { const berryType = randSeedInt(Object.keys(BerryType).filter(s => !isNaN(Number(s))).length) as BerryType; const berry = generateModifierType(modifierTypes.BERRY, [ berryType ]) as BerryModifierType; - const party = gScene.getParty(); + const party = globalScene.getParty(); // Will try to apply to prioritized pokemon first, then do normal application method if it fails if (prioritizedPokemon) { - const heldBerriesOfType = gScene.findModifier(m => m instanceof BerryModifier + const heldBerriesOfType = globalScene.findModifier(m => m instanceof BerryModifier && m.pokemonId === prioritizedPokemon.id && (m as BerryModifier).berryType === berryType, true) as BerryModifier; if (!heldBerriesOfType || heldBerriesOfType.getStackCount() < heldBerriesOfType.getMaxStackCount()) { @@ -272,7 +272,7 @@ function tryGiveBerry(prioritizedPokemon?: PlayerPokemon) { // Iterate over the party until berry was successfully given for (const pokemon of party) { - const heldBerriesOfType = gScene.findModifier(m => m instanceof BerryModifier + const heldBerriesOfType = globalScene.findModifier(m => m instanceof BerryModifier && m.pokemonId === pokemon.id && (m as BerryModifier).berryType === berryType, true) as BerryModifier; if (!heldBerriesOfType || heldBerriesOfType.getStackCount() < heldBerriesOfType.getMaxStackCount()) { diff --git a/src/data/mystery-encounters/encounters/bug-type-superfan-encounter.ts b/src/data/mystery-encounters/encounters/bug-type-superfan-encounter.ts index dcc03d01d82..7e316f55b7b 100644 --- a/src/data/mystery-encounters/encounters/bug-type-superfan-encounter.ts +++ b/src/data/mystery-encounters/encounters/bug-type-superfan-encounter.ts @@ -18,7 +18,7 @@ import { } from "#app/data/trainer-config"; import { MysteryEncounterType } from "#enums/mystery-encounter-type"; import { PartyMemberStrength } from "#enums/party-member-strength"; -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -216,11 +216,11 @@ export const BugTypeSuperfanEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculates what trainers are available for battle in the encounter // Bug type superfan trainer config - const config = getTrainerConfigForWave(gScene.currentBattle.waveIndex); + const config = getTrainerConfigForWave(globalScene.currentBattle.waveIndex); const spriteKey = config.getSpriteKey(); encounter.enemyPartyConfigs.push({ trainerConfig: config, @@ -228,7 +228,7 @@ export const BugTypeSuperfanEncounter: MysteryEncounter = }); let beedrillKeys: { spriteKey: string, fileRoot: string }, butterfreeKeys: { spriteKey: string, fileRoot: string }; - if (gScene.currentBattle.waveIndex < WAVE_LEVEL_BREAKPOINTS[3]) { + if (globalScene.currentBattle.waveIndex < WAVE_LEVEL_BREAKPOINTS[3]) { beedrillKeys = getSpriteKeysFromSpecies(Species.BEEDRILL, false); butterfreeKeys = getSpriteKeysFromSpecies(Species.BUTTERFREE, false); } else { @@ -298,7 +298,7 @@ export const BugTypeSuperfanEncounter: MysteryEncounter = }, async () => { // Select battle the bug trainer - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0]; // Init the moves available for tutor @@ -329,10 +329,10 @@ export const BugTypeSuperfanEncounter: MysteryEncounter = }) .withPreOptionPhase(async () => { // Player shows off their bug types - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Player gets different rewards depending on the number of bug types they have - const numBugTypes = gScene.getParty().filter(p => p.isOfType(Type.BUG, true)).length; + const numBugTypes = globalScene.getParty().filter(p => p.isOfType(Type.BUG, true)).length; const numBugTypesText = i18next.t(`${namespace}:numBugTypes`, { count: numBugTypes }); encounter.setDialogueToken("numBugTypes", numBugTypesText); @@ -366,10 +366,10 @@ export const BugTypeSuperfanEncounter: MysteryEncounter = const modifierOptions: ModifierTypeOption[] = [ generateModifierTypeOption(modifierTypes.MASTER_BALL)! ]; const specialOptions: ModifierTypeOption[] = []; - if (!gScene.findModifier(m => m instanceof MegaEvolutionAccessModifier)) { + if (!globalScene.findModifier(m => m instanceof MegaEvolutionAccessModifier)) { modifierOptions.push(generateModifierTypeOption(modifierTypes.MEGA_BRACELET)!); } - if (!gScene.findModifier(m => m instanceof GigantamaxAccessModifier)) { + if (!globalScene.findModifier(m => m instanceof GigantamaxAccessModifier)) { modifierOptions.push(generateModifierTypeOption(modifierTypes.DYNAMAX_BAND)!); } const nonRareEvolutionModifier = generateModifierTypeOption(modifierTypes.EVOLUTION_ITEM); @@ -431,7 +431,7 @@ export const BugTypeSuperfanEncounter: MysteryEncounter = secondOptionPrompt: `${namespace}:option.3.select_prompt`, }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Get Pokemon held items and filter for valid ones @@ -476,15 +476,15 @@ export const BugTypeSuperfanEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const modifier = encounter.misc.chosenModifier; // Remove the modifier if its stacks go to 0 modifier.stackCount -= 1; if (modifier.stackCount === 0) { - gScene.removeModifier(modifier); + globalScene.removeModifier(modifier); } - gScene.updateModifiers(true, true); + globalScene.updateModifiers(true, true); const bugNet = generateModifierTypeOption(modifierTypes.MYSTERY_ENCOUNTER_GOLDEN_BUG_NET)!; bugNet.type.tier = ModifierTier.ROGUE; @@ -648,7 +648,7 @@ function getTrainerConfigForWave(waveIndex: number) { function doBugTypeMoveTutor(): Promise { return new Promise(async resolve => { - const moveOptions = gScene.currentBattle.mysteryEncounter!.misc.moveTutorOptions; + const moveOptions = globalScene.currentBattle.mysteryEncounter!.misc.moveTutorOptions; await showEncounterDialogue(`${namespace}:battle_won`, `${namespace}:speaker`); const overlayScale = 1; @@ -659,9 +659,9 @@ function doBugTypeMoveTutor(): Promise { right: true, x: 1, y: -MoveInfoOverlay.getHeight(overlayScale, true) - 1, - width: (gScene.game.canvas.width / 6) - 2, + width: (globalScene.game.canvas.width / 6) - 2, }); - gScene.ui.add(moveInfoOverlay); + globalScene.ui.add(moveInfoOverlay); const optionSelectItems = moveOptions.map((move: PokemonMove) => { const option: OptionSelectItem = { @@ -695,7 +695,7 @@ function doBugTypeMoveTutor(): Promise { // Option select complete, handle if they are learning a move if (result && result.selectedOptionIndex < moveOptions.length) { - gScene.unshiftPhase(new LearnMovePhase(result.selectedPokemonIndex, moveOptions[result.selectedOptionIndex].moveId)); + globalScene.unshiftPhase(new LearnMovePhase(result.selectedPokemonIndex, moveOptions[result.selectedOptionIndex].moveId)); } // Complete battle and go to rewards diff --git a/src/data/mystery-encounters/encounters/clowning-around-encounter.ts b/src/data/mystery-encounters/encounters/clowning-around-encounter.ts index 0d45c5ae540..c036fd4dfea 100644 --- a/src/data/mystery-encounters/encounters/clowning-around-encounter.ts +++ b/src/data/mystery-encounters/encounters/clowning-around-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -106,7 +106,7 @@ export const ClowningAroundEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const clownTrainerType = TrainerType.HARLEQUIN; const clownConfig = trainerConfigs[clownTrainerType].clone(); @@ -166,7 +166,7 @@ export const ClowningAroundEncounter: MysteryEncounter = ], }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Spawn battle const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0]; @@ -205,15 +205,15 @@ export const ClowningAroundEncounter: MysteryEncounter = // 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 - gScene.tweens.add({ - targets: gScene.currentBattle.trainer, + globalScene.tweens.add({ + targets: globalScene.currentBattle.trainer, x: "+=16", y: "-=16", alpha: 0, ease: "Sine.easeInOut", duration: 250 }); - const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon()); + const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, globalScene.getPlayerPokemon()!, globalScene.getPlayerPokemon()); background.playWithoutTargets(230, 40, 2); return true; }) @@ -243,9 +243,9 @@ export const ClowningAroundEncounter: MysteryEncounter = // 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 = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; - const party = gScene.getParty(); + const party = globalScene.getParty(); let mostHeldItemsPokemon = party[0]; let count = mostHeldItemsPokemon.getHeldItems() .filter(m => m.isTransferable && !(m instanceof BerryModifier)) @@ -270,7 +270,7 @@ export const ClowningAroundEncounter: MysteryEncounter = items.filter(m => m instanceof BerryModifier) .forEach(m => { numBerries += m.stackCount; - gScene.removeModifier(m); + globalScene.removeModifier(m); }); generateItemsOfTier(mostHeldItemsPokemon, numBerries, "Berries"); @@ -284,10 +284,10 @@ export const ClowningAroundEncounter: MysteryEncounter = const tier = type.tier ?? ModifierTier.ULTRA; if (type.id === "GOLDEN_EGG" || tier === ModifierTier.ROGUE) { numRogue += m.stackCount; - gScene.removeModifier(m); + globalScene.removeModifier(m); } else if (type.id === "LUCKY_EGG" || tier === ModifierTier.ULTRA) { numUltra += m.stackCount; - gScene.removeModifier(m); + globalScene.removeModifier(m); } }); @@ -299,7 +299,7 @@ export const ClowningAroundEncounter: MysteryEncounter = }) .withPostOptionPhase(async () => { // Play animations - const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon()); + const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, globalScene.getPlayerPokemon()!, globalScene.getPlayerPokemon()); background.playWithoutTargets(230, 40, 2); await transitionMysteryEncounterIntroVisuals(true, true, 200); }) @@ -328,7 +328,7 @@ export const ClowningAroundEncounter: MysteryEncounter = .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 gScene.getParty()) { + for (const pokemon of globalScene.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 @@ -370,7 +370,7 @@ export const ClowningAroundEncounter: MysteryEncounter = }) .withPostOptionPhase(async () => { // Play animations - const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon()); + const background = new EncounterBattleAnim(EncounterAnim.SMOKESCREEN, globalScene.getPlayerPokemon()!, globalScene.getPlayerPokemon()); background.playWithoutTargets(230, 40, 2); await transitionMysteryEncounterIntroVisuals(true, true, 200); }) @@ -388,7 +388,7 @@ async function handleSwapAbility() { await showEncounterDialogue(`${namespace}:option.1.apply_ability_dialogue`, `${namespace}:speaker`); await showEncounterText(`${namespace}:option.1.apply_ability_message`); - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { displayYesNoOptions(resolve); }); }); @@ -418,21 +418,21 @@ function displayYesNoOptions(resolve) { maxOptions: 7, yOffset: 0 }; - gScene.ui.setModeWithoutClear(Mode.OPTION_SELECT, config, null, true); + globalScene.ui.setModeWithoutClear(Mode.OPTION_SELECT, config, null, true); } function onYesAbilitySwap(resolve) { const onPokemonSelected = (pokemon: PlayerPokemon) => { // Do ability swap - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; applyAbilityOverrideToPokemon(pokemon, encounter.misc.ability); encounter.setDialogueToken("chosenPokemon", pokemon.getNameToRender()); - gScene.ui.setMode(Mode.MESSAGE).then(() => resolve(true)); + globalScene.ui.setMode(Mode.MESSAGE).then(() => resolve(true)); }; const onPokemonNotSelected = () => { - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { displayYesNoOptions(resolve); }); }; diff --git a/src/data/mystery-encounters/encounters/dancing-lessons-encounter.ts b/src/data/mystery-encounters/encounters/dancing-lessons-encounter.ts index 7928666de3a..fc789943bd2 100644 --- a/src/data/mystery-encounters/encounters/dancing-lessons-encounter.ts +++ b/src/data/mystery-encounters/encounters/dancing-lessons-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -92,7 +92,7 @@ export const DancingLessonsEncounter: MysteryEncounter = .withCatchAllowed(true) .withFleeAllowed(false) .withOnVisualsStart(() => { - const danceAnim = new EncounterBattleAnim(EncounterAnim.DANCE, gScene.getEnemyPokemon()!, gScene.getParty()[0]); + const danceAnim = new EncounterBattleAnim(EncounterAnim.DANCE, globalScene.getEnemyPokemon()!, globalScene.getParty()[0]); danceAnim.play(); return true; @@ -107,7 +107,7 @@ export const DancingLessonsEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const species = getPokemonSpecies(Species.ORICORIO); const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER); @@ -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 = gScene.arena.biomeType; + const currentBiome = globalScene.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 = gScene.addEnemyPokemon(species, level, TrainerSlot.NONE, false, oricorioData); + const oricorio = globalScene.addEnemyPokemon(species, level, TrainerSlot.NONE, false, oricorioData); // Adds a real Pokemon sprite to the field (required for the animation) - gScene.getEnemyParty().forEach(enemyPokemon => { - gScene.field.remove(enemyPokemon, true); + globalScene.getEnemyParty().forEach(enemyPokemon => { + globalScene.field.remove(enemyPokemon, true); }); - gScene.currentBattle.enemyParty = [ oricorio ]; - gScene.field.add(oricorio); + globalScene.currentBattle.enemyParty = [ oricorio ]; + globalScene.field.add(oricorio); // Spawns on offscreen field oricorio.x -= 300; encounter.loadAssets.push(oricorio.loadAssets()); @@ -157,7 +157,7 @@ export const DancingLessonsEncounter: MysteryEncounter = tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ], mysteryEncounterBattleEffects: (pokemon: Pokemon) => { queueEncounterMessage(`${namespace}:option.1.boss_enraged`); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF ], 1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF ], 1)); } }], }; @@ -184,7 +184,7 @@ export const DancingLessonsEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Pick battle - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.startOfBattleEffects.push({ sourceBattlerIndex: BattlerIndex.ENEMY, @@ -213,14 +213,14 @@ export const DancingLessonsEncounter: MysteryEncounter = }) .withPreOptionPhase(async () => { // Learn its Dance - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { encounter.setDialogueToken("selectedPokemon", pokemon.getNameToRender()); - gScene.unshiftPhase(new LearnMovePhase(gScene.getParty().indexOf(pokemon), Moves.REVELATION_DANCE)); + globalScene.unshiftPhase(new LearnMovePhase(globalScene.getParty().indexOf(pokemon), Moves.REVELATION_DANCE)); // Play animation again to "learn" the dance - const danceAnim = new EncounterBattleAnim(EncounterAnim.DANCE, gScene.getEnemyPokemon()!, gScene.getPlayerPokemon()); + const danceAnim = new EncounterBattleAnim(EncounterAnim.DANCE, globalScene.getEnemyPokemon()!, globalScene.getPlayerPokemon()); danceAnim.play(); }; @@ -250,7 +250,7 @@ export const DancingLessonsEncounter: MysteryEncounter = }) .withPreOptionPhase(async () => { // Open menu for selecting pokemon with a Dancing move - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Return the options for nature selection return pokemon.moveset @@ -289,7 +289,7 @@ export const DancingLessonsEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Show the Oricorio a dance, and recruit it - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const oricorio = encounter.misc.oricorioData.toPokemon(); oricorio.passive = true; @@ -313,8 +313,8 @@ export const DancingLessonsEncounter: MysteryEncounter = function hideOricorioPokemon() { return new Promise(resolve => { - const oricorioSprite = gScene.getEnemyParty()[0]; - gScene.tweens.add({ + const oricorioSprite = globalScene.getEnemyParty()[0]; + globalScene.tweens.add({ targets: oricorioSprite, x: "+=16", y: "-=16", @@ -322,7 +322,7 @@ function hideOricorioPokemon() { ease: "Sine.easeInOut", duration: 750, onComplete: () => { - gScene.field.remove(oricorioSprite, true); + globalScene.field.remove(oricorioSprite, true); resolve(); } }); diff --git a/src/data/mystery-encounters/encounters/dark-deal-encounter.ts b/src/data/mystery-encounters/encounters/dark-deal-encounter.ts index b73b218d8b0..eb1ea55dd5a 100644 --- a/src/data/mystery-encounters/encounters/dark-deal-encounter.ts +++ b/src/data/mystery-encounters/encounters/dark-deal-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -145,9 +145,9 @@ export const DarkDealEncounter: MysteryEncounter = // Get all the pokemon's held items const modifiers = removedPokemon.getHeldItems().filter(m => !(m instanceof PokemonFormChangeItemModifier)); - gScene.removePokemonFromPlayerParty(removedPokemon); + globalScene.removePokemonFromPlayerParty(removedPokemon); - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.setDialogueToken("pokeName", removedPokemon.getNameToRender()); // Store removed pokemon types @@ -158,14 +158,14 @@ export const DarkDealEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Give the player 5 Rogue Balls - const encounter = gScene.currentBattle.mysteryEncounter!; - gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.ROGUE_BALL)); + const encounter = globalScene.currentBattle.mysteryEncounter!; + globalScene.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 = gScene.gameMode.challenges.filter(c => c.value && c.id === Challenges.SINGLE_TYPE); - if (gScene.gameMode.isChallenge && singleTypeChallenges.length > 0) { + const singleTypeChallenges = globalScene.gameMode.challenges.filter(c => c.value && c.id === Challenges.SINGLE_TYPE); + if (globalScene.gameMode.isChallenge && singleTypeChallenges.length > 0) { bossTypes = singleTypeChallenges.map(c => (c.value - 1) as Type); } diff --git a/src/data/mystery-encounters/encounters/delibirdy-encounter.ts b/src/data/mystery-encounters/encounters/delibirdy-encounter.ts index 2f907b29a04..65528b03af5 100644 --- a/src/data/mystery-encounters/encounters/delibirdy-encounter.ts +++ b/src/data/mystery-encounters/encounters/delibirdy-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -97,14 +97,14 @@ export const DelibirdyEncounter: MysteryEncounter = } ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.setDialogueToken("delibirdName", getPokemonSpecies(Species.DELIBIRD).getName()); - gScene.loadBgm("mystery_encounter_delibirdy", "mystery_encounter_delibirdy.mp3"); + globalScene.loadBgm("mystery_encounter_delibirdy", "mystery_encounter_delibirdy.mp3"); return true; }) .withOnVisualsStart(() => { - gScene.fadeAndSwitchBgm("mystery_encounter_delibirdy"); + globalScene.fadeAndSwitchBgm("mystery_encounter_delibirdy"); return true; }) .withOption( @@ -121,23 +121,23 @@ export const DelibirdyEncounter: MysteryEncounter = ], }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; updatePlayerMoney(-(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney, true, false); return true; }) .withOptionPhase(async () => { // Give the player an Amulet Coin // Check if the player has max stacks of that item already - const existing = gScene.findModifier(m => m instanceof MoneyMultiplierModifier) as MoneyMultiplierModifier; + const existing = globalScene.findModifier(m => m instanceof MoneyMultiplierModifier) as MoneyMultiplierModifier; if (existing && existing.getStackCount() >= existing.getMaxStackCount()) { // At max stacks, give the first party pokemon a Shell Bell instead const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType; - await applyModifierTypeToPlayerPokemon(gScene.getParty()[0], shellBell); - gScene.playSound("item_fanfare"); + await applyModifierTypeToPlayerPokemon(globalScene.getParty()[0], shellBell); + globalScene.playSound("item_fanfare"); await showEncounterText(i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true); } else { - gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.AMULET_COIN)); + globalScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.AMULET_COIN)); } leaveEncounterWithoutBattle(true); @@ -159,7 +159,7 @@ export const DelibirdyEncounter: MysteryEncounter = ], }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Get Pokemon held items and filter for valid ones const validItems = pokemon.getHeldItems().filter((it) => { @@ -196,42 +196,42 @@ export const DelibirdyEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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 = gScene.findModifier(m => m instanceof LevelIncrementBoosterModifier) as LevelIncrementBoosterModifier; + const existing = globalScene.findModifier(m => m instanceof LevelIncrementBoosterModifier) as LevelIncrementBoosterModifier; if (existing && existing.getStackCount() >= existing.getMaxStackCount()) { // At max stacks, give the first party pokemon a Shell Bell instead const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType; - await applyModifierTypeToPlayerPokemon(gScene.getParty()[0], shellBell); - gScene.playSound("item_fanfare"); + await applyModifierTypeToPlayerPokemon(globalScene.getParty()[0], shellBell); + globalScene.playSound("item_fanfare"); await showEncounterText(i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true); } else { - gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.CANDY_JAR)); + globalScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.CANDY_JAR)); } } else { // Check if the player has max stacks of that Berry Pouch already - const existing = gScene.findModifier(m => m instanceof PreserveBerryModifier) as PreserveBerryModifier; + const existing = globalScene.findModifier(m => m instanceof PreserveBerryModifier) as PreserveBerryModifier; if (existing && existing.getStackCount() >= existing.getMaxStackCount()) { // At max stacks, give the first party pokemon a Shell Bell instead const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType; - await applyModifierTypeToPlayerPokemon(gScene.getParty()[0], shellBell); - gScene.playSound("item_fanfare"); + await applyModifierTypeToPlayerPokemon(globalScene.getParty()[0], shellBell); + globalScene.playSound("item_fanfare"); await showEncounterText(i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true); } else { - gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.BERRY_POUCH)); + globalScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.BERRY_POUCH)); } } // Remove the modifier if its stacks go to 0 modifier.stackCount -= 1; if (modifier.stackCount === 0) { - gScene.removeModifier(modifier); + globalScene.removeModifier(modifier); } leaveEncounterWithoutBattle(true); @@ -253,7 +253,7 @@ export const DelibirdyEncounter: MysteryEncounter = ], }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Get Pokemon held items and filter for valid ones const validItems = pokemon.getHeldItems().filter((it) => { @@ -290,26 +290,26 @@ export const DelibirdyEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const modifier = encounter.misc.chosenModifier; // Check if the player has max stacks of Healing Charm already - const existing = gScene.findModifier(m => m instanceof HealingBoosterModifier) as HealingBoosterModifier; + const existing = globalScene.findModifier(m => m instanceof HealingBoosterModifier) as HealingBoosterModifier; if (existing && existing.getStackCount() >= existing.getMaxStackCount()) { // At max stacks, give the first party pokemon a Shell Bell instead const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType; - await applyModifierTypeToPlayerPokemon(gScene.getParty()[0], shellBell); - gScene.playSound("item_fanfare"); + await applyModifierTypeToPlayerPokemon(globalScene.getParty()[0], shellBell); + globalScene.playSound("item_fanfare"); await showEncounterText(i18next.t("battle:rewardGain", { modifierName: shellBell.name }), null, undefined, true); } else { - gScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.HEALING_CHARM)); + globalScene.unshiftPhase(new ModifierRewardPhase(modifierTypes.HEALING_CHARM)); } // Remove the modifier if its stacks go to 0 modifier.stackCount -= 1; if (modifier.stackCount === 0) { - gScene.removeModifier(modifier); + globalScene.removeModifier(modifier); } leaveEncounterWithoutBattle(true); diff --git a/src/data/mystery-encounters/encounters/field-trip-encounter.ts b/src/data/mystery-encounters/encounters/field-trip-encounter.ts index aaa6871fbed..86121587f60 100644 --- a/src/data/mystery-encounters/encounters/field-trip-encounter.ts +++ b/src/data/mystery-encounters/encounters/field-trip-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -65,7 +65,7 @@ export const FieldTripEncounter: MysteryEncounter = secondOptionPrompt: `${namespace}:second_option_prompt`, }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Return the options for Pokemon move valid for this option return pokemon.moveset.map((move: PokemonMove) => { @@ -85,7 +85,7 @@ export const FieldTripEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; if (encounter.misc.correctMove) { const modifiers = [ generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.ATK ])!, @@ -111,7 +111,7 @@ export const FieldTripEncounter: MysteryEncounter = secondOptionPrompt: `${namespace}:second_option_prompt`, }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Return the options for Pokemon move valid for this option return pokemon.moveset.map((move: PokemonMove) => { @@ -131,7 +131,7 @@ export const FieldTripEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; if (encounter.misc.correctMove) { const modifiers = [ generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.SPATK ])!, @@ -157,7 +157,7 @@ export const FieldTripEncounter: MysteryEncounter = secondOptionPrompt: `${namespace}:second_option_prompt`, }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Return the options for Pokemon move valid for this option return pokemon.moveset.map((move: PokemonMove) => { @@ -177,7 +177,7 @@ export const FieldTripEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; if (encounter.misc.correctMove) { const modifiers = [ generateModifierTypeOption(modifierTypes.TEMP_STAT_STAGE_BOOSTER, [ Stat.ACC ])!, @@ -197,7 +197,7 @@ export const FieldTripEncounter: MysteryEncounter = .build(); function pokemonAndMoveChosen(pokemon: PlayerPokemon, move: PokemonMove, correctMoveCategory: MoveCategory) { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const correctMove = move.getMove().category === correctMoveCategory; encounter.setDialogueToken("pokeName", pokemon.getNameToRender()); encounter.setDialogueToken("move", move.getName()); @@ -214,7 +214,7 @@ function pokemonAndMoveChosen(pokemon: PlayerPokemon, move: PokemonMove, correct text: `${namespace}:incorrect_exp`, }, ]; - setEncounterExp(gScene.getParty().map((p) => p.id), 50); + setEncounterExp(globalScene.getParty().map((p) => p.id), 50); } else { encounter.selectedOption!.dialogue!.selected = [ { diff --git a/src/data/mystery-encounters/encounters/fiery-fallout-encounter.ts b/src/data/mystery-encounters/encounters/fiery-fallout-encounter.ts index 6093c4a70c2..a477378e664 100644 --- a/src/data/mystery-encounters/encounters/fiery-fallout-encounter.ts +++ b/src/data/mystery-encounters/encounters/fiery-fallout-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -59,7 +59,7 @@ export const FieryFalloutEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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) => { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPDEF, Stat.SPD ], 1)); + globalScene.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) => { - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPDEF, Stat.SPD ], 1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.SPDEF, Stat.SPD ], 1)); } } ], @@ -115,7 +115,7 @@ export const FieryFalloutEncounter: MysteryEncounter = // Load animations/sfx for Volcarona moves loadCustomMovesForEncounter([ Moves.FIRE_SPIN, Moves.QUIVER_DANCE ]); - gScene.arena.trySetWeather(WeatherType.SUNNY, true); + globalScene.arena.trySetWeather(WeatherType.SUNNY, true); encounter.setDialogueToken("volcaronaName", getPokemonSpecies(Species.VOLCARONA).getName()); @@ -123,14 +123,14 @@ export const FieryFalloutEncounter: MysteryEncounter = }) .withOnVisualsStart(() => { // Play animations - const background = new EncounterBattleAnim(EncounterAnim.MAGMA_BG, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon()); + const background = new EncounterBattleAnim(EncounterAnim.MAGMA_BG, globalScene.getPlayerPokemon()!, globalScene.getPlayerPokemon()); background.playWithoutTargets(200, 70, 2, 3); - const animation = new EncounterBattleAnim(EncounterAnim.MAGMA_SPOUT, gScene.getPlayerPokemon()!, gScene.getPlayerPokemon()); + const animation = new EncounterBattleAnim(EncounterAnim.MAGMA_SPOUT, globalScene.getPlayerPokemon()!, globalScene.getPlayerPokemon()); animation.playWithoutTargets(80, 100, 2); - gScene.time.delayedCall(600, () => { + globalScene.time.delayedCall(600, () => { animation.playWithoutTargets(-20, 100, 2); }); - gScene.time.delayedCall(1200, () => { + globalScene.time.delayedCall(1200, () => { animation.playWithoutTargets(140, 150, 2); }); @@ -152,7 +152,7 @@ export const FieryFalloutEncounter: MysteryEncounter = }, async () => { // Pick battle - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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(gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]); + await initBattleWithEnemyConfig(globalScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]); } ) .withSimpleOption( @@ -183,8 +183,8 @@ export const FieryFalloutEncounter: MysteryEncounter = }, async () => { // Damage non-fire types and burn 1 random non-fire type member + give it Heatproof - const encounter = gScene.currentBattle.mysteryEncounter!; - const nonFireTypes = gScene.getParty().filter((p) => p.isAllowedInBattle() && !p.getTypes().includes(Type.FIRE)); + const encounter = globalScene.currentBattle.mysteryEncounter!; + const nonFireTypes = globalScene.getParty().filter((p) => p.isAllowedInBattle() && !p.getTypes().includes(Type.FIRE)); for (const pkm of nonFireTypes) { const percentage = DAMAGE_PERCENTAGE / 100; @@ -237,7 +237,7 @@ export const FieryFalloutEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Fire types help calm the Volcarona - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; await transitionMysteryEncounterIntroVisuals(); setEncounterRewards( { fillRemaining: true }, @@ -257,7 +257,7 @@ export const FieryFalloutEncounter: MysteryEncounter = function giveLeadPokemonAttackTypeBoostItem() { // Give first party pokemon attack type boost item for free at end of battle - const leadPokemon = gScene.getParty()?.[0]; + const leadPokemon = globalScene.getParty()?.[0]; if (leadPokemon) { // Generate type booster held item, default to Charcoal if item fails to generate let boosterModifierType = generateModifierType(modifierTypes.ATTACK_TYPE_BOOSTER) as AttackTypeBoosterModifierType; @@ -266,7 +266,7 @@ function giveLeadPokemonAttackTypeBoostItem() { } applyModifierTypeToPlayerPokemon(leadPokemon, boosterModifierType); - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.setDialogueToken("itemName", boosterModifierType.name); encounter.setDialogueToken("leadPokemon", leadPokemon.getNameToRender()); queueEncounterMessage(`${namespace}:found_item`); diff --git a/src/data/mystery-encounters/encounters/fight-or-flight-encounter.ts b/src/data/mystery-encounters/encounters/fight-or-flight-encounter.ts index ed540995b1e..efe05f1d951 100644 --- a/src/data/mystery-encounters/encounters/fight-or-flight-encounter.ts +++ b/src/data/mystery-encounters/encounters/fight-or-flight-encounter.ts @@ -17,7 +17,7 @@ import { regenerateModifierPoolThresholds, } from "#app/modifier/modifier-type"; import { MysteryEncounterType } from "#enums/mystery-encounter-type"; -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -53,11 +53,11 @@ export const FightOrFlightEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculate boss mon const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER); - const bossSpecies = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true); + const bossSpecies = globalScene.arena.randomSpecies(globalScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(globalScene.getParty()), true); const bossPokemon = new EnemyPokemon(bossSpecies, level, TrainerSlot.NONE, true); encounter.setDialogueToken("enemyPokemon", bossPokemon.getNameToRender()); const config: EnemyPartyConfig = { @@ -71,7 +71,7 @@ export const FightOrFlightEncounter: MysteryEncounter = queueEncounterMessage(`${namespace}:option.1.stat_boost`); // Randomly boost 1 stat 2 stages // Cannot boost Spd, Acc, or Evasion - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ randSeedInt(4, 1) ], 2)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ randSeedInt(4, 1) ], 2)); } }], }; @@ -80,18 +80,18 @@ export const FightOrFlightEncounter: MysteryEncounter = // Calculate item // Waves 10-40 GREAT, 60-120 ULTRA, 120-160 ROGUE, 160-180 MASTER const tier = - gScene.currentBattle.waveIndex > 160 + globalScene.currentBattle.waveIndex > 160 ? ModifierTier.MASTER - : gScene.currentBattle.waveIndex > 120 + : globalScene.currentBattle.waveIndex > 120 ? ModifierTier.ROGUE - : gScene.currentBattle.waveIndex > 40 + : globalScene.currentBattle.waveIndex > 40 ? ModifierTier.ULTRA : ModifierTier.GREAT; - regenerateModifierPoolThresholds(gScene.getParty(), ModifierPoolType.PLAYER, 0); + regenerateModifierPoolThresholds(globalScene.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, gScene.getParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0]; + item = getPlayerModifierTypeOptions(1, globalScene.getParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0]; } encounter.setDialogueToken("itemName", item.type.name); encounter.misc = item; @@ -138,9 +138,9 @@ export const FightOrFlightEncounter: MysteryEncounter = async () => { // Pick battle // Pokemon will randomly boost 1 stat by 2 stages - const item = gScene.currentBattle.mysteryEncounter!.misc as ModifierTypeOption; + const item = globalScene.currentBattle.mysteryEncounter!.misc as ModifierTypeOption; setEncounterRewards({ guaranteedModifierTypeOptions: [ item ], fillRemaining: false }); - await initBattleWithEnemyConfig(gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]); + await initBattleWithEnemyConfig(globalScene.currentBattle.mysteryEncounter!.enemyPartyConfigs[0]); } ) .withOption( @@ -159,8 +159,8 @@ export const FightOrFlightEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Pick steal - const encounter = gScene.currentBattle.mysteryEncounter!; - const item = gScene.currentBattle.mysteryEncounter!.misc as ModifierTypeOption; + const encounter = globalScene.currentBattle.mysteryEncounter!; + const item = globalScene.currentBattle.mysteryEncounter!.misc as ModifierTypeOption; setEncounterRewards({ guaranteedModifierTypeOptions: [ item ], fillRemaining: false }); // Use primaryPokemon to execute the thievery diff --git a/src/data/mystery-encounters/encounters/fun-and-games-encounter.ts b/src/data/mystery-encounters/encounters/fun-and-games-encounter.ts index 1c56d2fbfd3..7522e8f4893 100644 --- a/src/data/mystery-encounters/encounters/fun-and-games-encounter.ts +++ b/src/data/mystery-encounters/encounters/fun-and-games-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -81,13 +81,13 @@ export const FunAndGamesEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; - gScene.loadBgm("mystery_encounter_fun_and_games", "mystery_encounter_fun_and_games.mp3"); + const encounter = globalScene.currentBattle.mysteryEncounter!; + globalScene.loadBgm("mystery_encounter_fun_and_games", "mystery_encounter_fun_and_games.mp3"); encounter.setDialogueToken("wobbuffetName", getPokemonSpecies(Species.WOBBUFFET).getName()); return true; }) .withOnVisualsStart(() => { - gScene.fadeAndSwitchBgm("mystery_encounter_fun_and_games"); + globalScene.fadeAndSwitchBgm("mystery_encounter_fun_and_games"); return true; }) .withOption(MysteryEncounterOptionBuilder @@ -104,7 +104,7 @@ export const FunAndGamesEncounter: MysteryEncounter = }) .withPreOptionPhase(async () => { // Select Pokemon for minigame - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { encounter.misc = { playerPokemon: pokemon, @@ -120,7 +120,7 @@ export const FunAndGamesEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Start minigame - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.misc.turnsRemaining = 3; // Update money @@ -161,11 +161,11 @@ export const FunAndGamesEncounter: MysteryEncounter = async function summonPlayerPokemon() { return new Promise(async resolve => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const playerPokemon = encounter.misc.playerPokemon; // Swaps the chosen Pokemon and the first player's lead Pokemon in the party - const party = gScene.getParty(); + const party = globalScene.getParty(); const chosenIndex = party.indexOf(playerPokemon); if (chosenIndex !== 0) { const leadPokemon = party[0]; @@ -175,36 +175,36 @@ async function summonPlayerPokemon() { // Do trainer summon animation let playerAnimationPromise: Promise | undefined; - 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"); + globalScene.ui.showText(i18next.t("battle:playerGo", { pokemonName: getPokemonNameWithAffix(playerPokemon) })); + globalScene.pbTray.hide(); + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`); + globalScene.time.delayedCall(562, () => { + globalScene.trainer.setFrame("2"); + globalScene.time.delayedCall(64, () => { + globalScene.trainer.setFrame("3"); }); }); - gScene.tweens.add({ - targets: gScene.trainer, + globalScene.tweens.add({ + targets: globalScene.trainer, x: -36, duration: 1000, - onComplete: () => gScene.trainer.setVisible(false) + onComplete: () => globalScene.trainer.setVisible(false) }); - gScene.time.delayedCall(750, () => { + globalScene.time.delayedCall(750, () => { playerAnimationPromise = summonPlayerPokemonAnimation(playerPokemon); }); // Also loads Wobbuffet data const enemySpecies = getPokemonSpecies(Species.WOBBUFFET); - gScene.currentBattle.enemyParty = []; - const wobbuffet = gScene.addEnemyPokemon(enemySpecies, encounter.misc.playerPokemon.level, TrainerSlot.NONE, false); + globalScene.currentBattle.enemyParty = []; + const wobbuffet = globalScene.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(); - gScene.currentBattle.enemyParty[0] = wobbuffet; - gScene.gameData.setPokemonSeen(wobbuffet, true); + globalScene.currentBattle.enemyParty[0] = wobbuffet; + globalScene.gameData.setPokemonSeen(wobbuffet, true); await wobbuffet.loadAssets(); const id = setInterval(checkPlayerAnimationPromise, 500); async function checkPlayerAnimationPromise() { @@ -220,20 +220,20 @@ async function summonPlayerPokemon() { function handleLoseMinigame() { return new Promise(async resolve => { // Check Wobbuffet is still alive - const wobbuffet = gScene.getEnemyPokemon(); + const wobbuffet = globalScene.getEnemyPokemon(); if (!wobbuffet || wobbuffet.isFainted(true) || wobbuffet.hp === 0) { // Player loses // End the battle if (wobbuffet) { wobbuffet.hideInfo(); - gScene.field.remove(wobbuffet); + globalScene.field.remove(wobbuffet); } transitionMysteryEncounterIntroVisuals(true, true); - gScene.currentBattle.enemyParty = []; - gScene.currentBattle.mysteryEncounter!.doContinueEncounter = undefined; + globalScene.currentBattle.enemyParty = []; + globalScene.currentBattle.mysteryEncounter!.doContinueEncounter = undefined; leaveEncounterWithoutBattle(true); await showEncounterText(`${namespace}:ko`); - const reviveCost = gScene.getWaveMoneyAmount(1.5); + const reviveCost = globalScene.getWaveMoneyAmount(1.5); updatePlayerMoney(-reviveCost, true, false); } @@ -242,9 +242,9 @@ function handleLoseMinigame() { } function handleNextTurn() { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; - const wobbuffet = gScene.getEnemyPokemon(); + const wobbuffet = globalScene.getEnemyPokemon(); if (!wobbuffet) { // Should never be triggered, just handling the edge case handleLoseMinigame(); @@ -275,9 +275,9 @@ function handleNextTurn() { // End the battle wobbuffet.hideInfo(); - gScene.field.remove(wobbuffet); - gScene.currentBattle.enemyParty = []; - gScene.currentBattle.mysteryEncounter!.doContinueEncounter = undefined; + globalScene.field.remove(wobbuffet); + globalScene.currentBattle.enemyParty = []; + globalScene.currentBattle.mysteryEncounter!.doContinueEncounter = undefined; leaveEncounterWithoutBattle(isHealPhase); // Must end the TurnInit phase prematurely so battle phases aren't added to queue queueEncounterMessage(`${namespace}:end_game`); @@ -299,32 +299,32 @@ function handleNextTurn() { } async function showWobbuffetHealthBar() { - const wobbuffet = gScene.getEnemyPokemon()!; + const wobbuffet = globalScene.getEnemyPokemon()!; - gScene.add.existing(wobbuffet); - gScene.field.add(wobbuffet); + globalScene.add.existing(wobbuffet); + globalScene.field.add(wobbuffet); - const playerPokemon = gScene.getPlayerPokemon() as Pokemon; + const playerPokemon = globalScene.getPlayerPokemon() as Pokemon; if (playerPokemon?.visible) { - gScene.field.moveBelow(wobbuffet, playerPokemon); + globalScene.field.moveBelow(wobbuffet, playerPokemon); } // Show health bar and trigger cry wobbuffet.showInfo(); - gScene.time.delayedCall(1000, () => { + globalScene.time.delayedCall(1000, () => { wobbuffet.cry(); }); wobbuffet.resetSummonData(); // Track the HP change across turns - gScene.currentBattle.mysteryEncounter!.misc.wobbuffetHealth = wobbuffet.hp; + globalScene.currentBattle.mysteryEncounter!.misc.wobbuffetHealth = wobbuffet.hp; } function summonPlayerPokemonAnimation(pokemon: PlayerPokemon): Promise { return new Promise(resolve => { - const pokeball = gScene.addFieldSprite(36, 80, "pb", getPokeballAtlasKey(pokemon.pokeball)); + const pokeball = globalScene.addFieldSprite(36, 80, "pb", getPokeballAtlasKey(pokemon.pokeball)); pokeball.setVisible(false); pokeball.setOrigin(0.5, 0.625); - gScene.field.add(pokeball); + globalScene.field.add(pokeball); pokemon.setFieldPosition(FieldPosition.CENTER, 0); @@ -332,32 +332,32 @@ function summonPlayerPokemonAnimation(pokemon: PlayerPokemon): Promise { pokeball.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, duration: 650, x: 100 + fpOffset[0] }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, duration: 150, ease: "Cubic.easeOut", y: 70 + fpOffset[1], onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, duration: 500, ease: "Cubic.easeIn", angle: 1440, y: 132 + fpOffset[1], onComplete: () => { - gScene.playSound("se/pb_rel"); + globalScene.playSound("se/pb_rel"); pokeball.destroy(); - gScene.add.existing(pokemon); - gScene.field.add(pokemon); + globalScene.add.existing(pokemon); + globalScene.field.add(pokemon); addPokeballOpenParticles(pokemon.x, pokemon.y - 16, pokemon.pokeball); - gScene.updateModifiers(true); - gScene.updateFieldScale(); + globalScene.updateModifiers(true); + globalScene.updateFieldScale(); pokemon.showInfo(); pokemon.playAnim(); pokemon.setVisible(true); @@ -365,8 +365,8 @@ function summonPlayerPokemonAnimation(pokemon: PlayerPokemon): Promise { pokemon.setScale(0.5); pokemon.tint(getPokeballTintColor(pokemon.pokeball)); pokemon.untint(250, "Sine.easeIn"); - gScene.updateFieldScale(); - gScene.tweens.add({ + globalScene.updateFieldScale(); + globalScene.tweens.add({ targets: pokemon, duration: 250, ease: "Sine.easeIn", @@ -375,15 +375,15 @@ function summonPlayerPokemonAnimation(pokemon: PlayerPokemon): Promise { pokemon.cry(pokemon.getHpRatio() > 0.25 ? undefined : { rate: 0.85 }); pokemon.getSprite().clearTint(); pokemon.resetSummonData(); - gScene.time.delayedCall(1000, () => { + globalScene.time.delayedCall(1000, () => { if (pokemon.isShiny()) { - gScene.unshiftPhase(new ShinySparklePhase(pokemon.getBattlerIndex())); + globalScene.unshiftPhase(new ShinySparklePhase(pokemon.getBattlerIndex())); } pokemon.resetTurnData(); - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true); - gScene.pushPhase(new PostSummonPhase(pokemon.getBattlerIndex())); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true); + globalScene.pushPhase(new PostSummonPhase(pokemon.getBattlerIndex())); resolve(); }); } @@ -396,12 +396,12 @@ function summonPlayerPokemonAnimation(pokemon: PlayerPokemon): Promise { } 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]; + const carnivalGame = globalScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(0)[0]; + const wobbuffet = globalScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(1)[0]; + const showMan = globalScene.currentBattle.mysteryEncounter!.introVisuals?.getSpriteAtIndex(2)[0]; // Hide the showman - gScene.tweens.add({ + globalScene.tweens.add({ targets: showMan, x: "+=16", y: "-=16", @@ -411,7 +411,7 @@ function hideShowmanIntroSprite() { }); // Slide the Wobbuffet and Game over slightly - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ wobbuffet, carnivalGame ], x: "+=16", ease: "Sine.easeInOut", diff --git a/src/data/mystery-encounters/encounters/global-trade-system-encounter.ts b/src/data/mystery-encounters/encounters/global-trade-system-encounter.ts index ed4ec03b7ee..4c7ca77c11c 100644 --- a/src/data/mystery-encounters/encounters/global-trade-system-encounter.ts +++ b/src/data/mystery-encounters/encounters/global-trade-system-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -101,17 +101,17 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Load bgm let bgmKey: string; - if (gScene.musicPreference === 0) { + if (globalScene.musicPreference === 0) { bgmKey = "mystery_encounter_gen_5_gts"; - gScene.loadBgm(bgmKey, `${bgmKey}.mp3`); + globalScene.loadBgm(bgmKey, `${bgmKey}.mp3`); } else { // Mixed option bgmKey = "mystery_encounter_gen_6_gts"; - gScene.loadBgm(bgmKey, `${bgmKey}.mp3`); + globalScene.loadBgm(bgmKey, `${bgmKey}.mp3`); } // Load possible trade options @@ -126,7 +126,7 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = return true; }) .withOnVisualsStart(() => { - gScene.fadeAndSwitchBgm(gScene.currentBattle.mysteryEncounter!.misc.bgmKey); + globalScene.fadeAndSwitchBgm(globalScene.currentBattle.mysteryEncounter!.misc.bgmKey); return true; }) .withOption( @@ -139,7 +139,7 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = secondOptionPrompt: `${namespace}:option.1.trade_options_prompt`, }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Get the trade species options for the selected pokemon const tradeOptionsMap: Map = encounter.misc.tradeOptionsMap; @@ -173,7 +173,7 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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,27 +183,27 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = encounter.setDialogueToken("tradeTrainerName", traderName.trim()); // Remove the original party member from party - gScene.removePokemonFromPlayerParty(tradedPokemon, false); + globalScene.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 = 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); + const newPlayerPokemon = globalScene.addPlayerPokemon(receivedPokemonData.species, receivedPokemonData.level, dataSource.abilityIndex, dataSource.formIndex, dataSource.gender, dataSource.shiny, dataSource.variant, dataSource.ivs, dataSource.nature, dataSource); + globalScene.getParty().push(newPlayerPokemon); await newPlayerPokemon.loadAssets(); for (const mod of modifiers) { mod.pokemonId = newPlayerPokemon.id; - gScene.addModifier(mod, true, false, false, true); + globalScene.addModifier(mod, true, false, false, true); } // Show the trade animation await showTradeBackground(); await doPokemonTradeSequence(tradedPokemon, newPlayerPokemon); await showEncounterText(`${namespace}:trade_received`, null, 0, true, 4000); - gScene.playBgm(encounter.misc.bgmKey); + globalScene.playBgm(encounter.misc.bgmKey); await addPokemonDataToDexAndValidateAchievements(newPlayerPokemon); await hideTradeBackground(); tradedPokemon.destroy(); @@ -221,18 +221,18 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = buttonTooltip: `${namespace}:option.2.tooltip`, }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Randomly generate a Wonder Trade pokemon - const randomTradeOption = generateTradeOption(gScene.getParty().map(p => p.species)); + const randomTradeOption = generateTradeOption(globalScene.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 (gScene.eventManager.isEventActive()) { - shinyThreshold.value *= gScene.eventManager.getShinyMultiplier(); + if (globalScene.eventManager.isEventActive()) { + shinyThreshold.value *= globalScene.eventManager.getShinyMultiplier(); } - gScene.applyModifiers(ShinyRateBoosterModifier, true, shinyThreshold); + globalScene.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); - gScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); + globalScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); const hasHiddenAbility = !randSeedInt(hiddenAbilityChance.value); @@ -282,7 +282,7 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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,26 +292,26 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = encounter.setDialogueToken("tradeTrainerName", traderName.trim()); // Remove the original party member from party - gScene.removePokemonFromPlayerParty(tradedPokemon, false); + globalScene.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 = 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); + const newPlayerPokemon = globalScene.addPlayerPokemon(receivedPokemonData.species, receivedPokemonData.level, dataSource.abilityIndex, dataSource.formIndex, dataSource.gender, dataSource.shiny, dataSource.variant, dataSource.ivs, dataSource.nature, dataSource); + globalScene.getParty().push(newPlayerPokemon); await newPlayerPokemon.loadAssets(); for (const mod of modifiers) { mod.pokemonId = newPlayerPokemon.id; - gScene.addModifier(mod, true, false, false, true); + globalScene.addModifier(mod, true, false, false, true); } // Show the trade animation await showTradeBackground(); await doPokemonTradeSequence(tradedPokemon, newPlayerPokemon); await showEncounterText(`${namespace}:trade_received`, null, 0, true, 4000); - gScene.playBgm(encounter.misc.bgmKey); + globalScene.playBgm(encounter.misc.bgmKey); await addPokemonDataToDexAndValidateAchievements(newPlayerPokemon); await hideTradeBackground(); tradedPokemon.destroy(); @@ -329,7 +329,7 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = secondOptionPrompt: `${namespace}:option.3.trade_options_prompt`, }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Get Pokemon held items and filter for valid ones const validItems = pokemon.getHeldItems().filter((it) => { @@ -365,7 +365,7 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const modifier = encounter.misc.chosenModifier; // Check tier of the traded item, the received item will be one tier up @@ -384,11 +384,11 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = tier++; } - regenerateModifierPoolThresholds(gScene.getParty(), ModifierPoolType.PLAYER, 0); + regenerateModifierPoolThresholds(globalScene.getParty(), ModifierPoolType.PLAYER, 0); let item: ModifierTypeOption | null = null; // TMs excluded from possible rewards while (!item || item.type.id.includes("TM_")) { - item = getPlayerModifierTypeOptions(1, gScene.getParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0]; + item = getPlayerModifierTypeOptions(1, globalScene.getParty(), [], { guaranteedModifierTiers: [ tier ], allowLuckUpgrades: false })[0]; } encounter.setDialogueToken("itemName", item.type.name); @@ -397,9 +397,9 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = // Remove the chosen modifier if its stacks go to 0 modifier.stackCount -= 1; if (modifier.stackCount === 0) { - gScene.removeModifier(modifier); + globalScene.removeModifier(modifier); } - await gScene.updateModifiers(true, true); + await globalScene.updateModifiers(true, true); // Generate a trainer name const traderName = generateRandomTraderName(); @@ -430,9 +430,9 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = function getPokemonTradeOptions(): Map { const tradeOptionsMap: Map = new Map(); // Starts by filtering out any current party members as valid resulting species - const alreadyUsedSpecies: PokemonSpecies[] = gScene.getParty().map(p => p.species); + const alreadyUsedSpecies: PokemonSpecies[] = globalScene.getParty().map(p => p.species); - gScene.getParty().forEach(pokemon => { + globalScene.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; @@ -498,26 +498,26 @@ function generateTradeOption(alreadyUsedSpecies: PokemonSpecies[], originalBst?: function showTradeBackground() { return new Promise(resolve => { - const tradeContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); + const tradeContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); tradeContainer.setName("Trade Background"); - const flyByStaticBg = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0); + const flyByStaticBg = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6, 0); flyByStaticBg.setName("Black Background"); flyByStaticBg.setOrigin(0, 0); flyByStaticBg.setVisible(false); tradeContainer.add(flyByStaticBg); - const tradeBaseBg = gScene.add.image(0, 0, "default_bg"); + const tradeBaseBg = globalScene.add.image(0, 0, "default_bg"); tradeBaseBg.setName("Trade Background Image"); tradeBaseBg.setOrigin(0, 0); tradeContainer.add(tradeBaseBg); - gScene.fieldUI.add(tradeContainer); - gScene.fieldUI.bringToTop(tradeContainer); + globalScene.fieldUI.add(tradeContainer); + globalScene.fieldUI.bringToTop(tradeContainer); tradeContainer.setVisible(true); tradeContainer.alpha = 0; - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradeContainer, alpha: 1, duration: 500, @@ -531,15 +531,15 @@ function showTradeBackground() { function hideTradeBackground() { return new Promise(resolve => { - const transformationContainer = gScene.fieldUI.getByName("Trade Background"); + const transformationContainer = globalScene.fieldUI.getByName("Trade Background"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: transformationContainer, alpha: 0, duration: 1000, ease: "Sine.easeInOut", onComplete: () => { - gScene.fieldUI.remove(transformationContainer, true); + globalScene.fieldUI.remove(transformationContainer, true); resolve(); } }); @@ -554,7 +554,7 @@ function hideTradeBackground() { */ function doPokemonTradeSequence(tradedPokemon: PlayerPokemon, receivedPokemon: PlayerPokemon) { return new Promise(resolve => { - const tradeContainer = gScene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container; + const tradeContainer = globalScene.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(tradedPokemon: PlayerPokemon, receivedPokemon: P let receivedPokemonTintSprite: Phaser.GameObjects.Sprite; const getPokemonSprite = () => { - 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 }); + const ret = globalScene.addPokemonSprite(tradedPokemon, tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pkmn__sub"); + ret.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); return ret; }; @@ -582,7 +582,7 @@ function doPokemonTradeSequence(tradedPokemon: PlayerPokemon, receivedPokemon: P [ tradedPokemonSprite, tradedPokemonTintSprite ].map(sprite => { sprite.play(tradedPokemon.getSpriteKey(true)); - sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(tradedPokemon.getTeraType()) }); + sprite.setPipeline(globalScene.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(tradedPokemon: PlayerPokemon, receivedPokemon: P [ receivedPokemonSprite, receivedPokemonTintSprite ].map(sprite => { sprite.play(receivedPokemon.getSpriteKey(true)); - sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(tradedPokemon.getTeraType()) }); + sprite.setPipeline(globalScene.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(tradedPokemon: PlayerPokemon, receivedPokemon: P // Traded pokemon pokeball const tradedPbAtlasKey = getPokeballAtlasKey(tradedPokemon.pokeball); - const tradedPokeball: Phaser.GameObjects.Sprite = gScene.add.sprite(tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pb", tradedPbAtlasKey); + const tradedPokeball: Phaser.GameObjects.Sprite = globalScene.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 = gScene.add.sprite(tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pb", receivedPbAtlasKey); + const receivedPokeball: Phaser.GameObjects.Sprite = globalScene.add.sprite(tradeBaseBg.displayWidth / 2, tradeBaseBg.displayHeight / 2, "pb", receivedPbAtlasKey); receivedPokeball.setVisible(false); tradeContainer.add(receivedPokeball); - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradedPokemonSprite, alpha: 1, ease: "Cubic.easeInOut", duration: 500, onComplete: async () => { - gScene.fadeOutBgm(1000, false); + globalScene.fadeOutBgm(1000, false); await showEncounterText(`${namespace}:pokemon_trade_selected`); tradedPokemon.cry(); - gScene.playBgm("evolution"); + globalScene.playBgm("evolution"); await showEncounterText(`${namespace}:pokemon_trade_goodbye`); tradedPokeball.setAlpha(0); tradedPokeball.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradedPokeball, alpha: 1, ease: "Cubic.easeInOut", duration: 250, onComplete: () => { tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}_opening`); - gScene.time.delayedCall(17, () => tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}_open`)); - gScene.playSound("se/pb_rel"); + globalScene.time.delayedCall(17, () => tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}_open`)); + globalScene.playSound("se/pb_rel"); tradedPokemonTintSprite.setVisible(true); // TODO: need to add particles to fieldUI instead of field // addPokeballOpenParticles(tradedPokemon.x, tradedPokemon.y, tradedPokemon.pokeball); - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ tradedPokemonTintSprite, tradedPokemonSprite ], duration: 500, ease: "Sine.easeIn", @@ -659,26 +659,26 @@ function doPokemonTradeSequence(tradedPokemon: PlayerPokemon, receivedPokemon: P tradedPokemonSprite.setVisible(false); tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}_opening`); tradedPokemonTintSprite.setVisible(false); - gScene.playSound("se/pb_catch"); - gScene.time.delayedCall(17, () => tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}`)); + globalScene.playSound("se/pb_catch"); + globalScene.time.delayedCall(17, () => tradedPokeball.setTexture("pb", `${tradedPbAtlasKey}`)); - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradedPokeball, y: "+=10", duration: 200, delay: 250, ease: "Cubic.easeIn", onComplete: () => { - gScene.playSound("se/pb_bounce_1"); + globalScene.playSound("se/pb_bounce_1"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradedPokeball, y: "-=100", duration: 200, delay: 1000, ease: "Cubic.easeInOut", onStart: () => { - gScene.playSound("se/pb_throw"); + globalScene.playSound("se/pb_throw"); }, onComplete: async () => { await doPokemonTradeFlyBySequence(tradedPokemonSprite, receivedPokemonSprite); @@ -699,7 +699,7 @@ function doPokemonTradeSequence(tradedPokemon: PlayerPokemon, receivedPokemon: P function doPokemonTradeFlyBySequence(tradedPokemonSprite: Phaser.GameObjects.Sprite, receivedPokemonSprite: Phaser.GameObjects.Sprite) { return new Promise(resolve => { - const tradeContainer = gScene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container; + const tradeContainer = globalScene.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(tradedPokemonSprite: Phaser.GameObjects.Spr const BASE_ANIM_DURATION = 1000; // Fade out trade background - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradeBaseBg, alpha: 0, ease: "Cubic.easeInOut", duration: FADE_DELAY, onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ receivedPokemonSprite, tradedPokemonSprite ], y: tradeBaseBg.displayWidth / 2 - 100, ease: "Cubic.easeInOut", duration: BASE_ANIM_DURATION * 3, onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: receivedPokemonSprite, x: tradeBaseBg.displayWidth / 4, ease: "Cubic.easeInOut", duration: BASE_ANIM_DURATION / 2, delay: ANIM_DELAY }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradedPokemonSprite, x: tradeBaseBg.displayWidth * 3 / 4, ease: "Cubic.easeInOut", duration: BASE_ANIM_DURATION / 2, delay: ANIM_DELAY, onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: receivedPokemonSprite, y: "+=200", ease: "Cubic.easeInOut", duration: BASE_ANIM_DURATION * 2, delay: ANIM_DELAY, }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradedPokemonSprite, y: "-=200", ease: "Cubic.easeInOut", duration: BASE_ANIM_DURATION * 2, delay: ANIM_DELAY, onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: tradeBaseBg, alpha: 1, ease: "Cubic.easeInOut", @@ -782,7 +782,7 @@ function doPokemonTradeFlyBySequence(tradedPokemonSprite: Phaser.GameObjects.Spr function doTradeReceivedSequence(receivedPokemon: PlayerPokemon, receivedPokemonSprite: Phaser.GameObjects.Sprite, receivedPokemonTintSprite: Phaser.GameObjects.Sprite, receivedPokeballSprite: Phaser.GameObjects.Sprite, receivedPbAtlasKey: string) { return new Promise(resolve => { - const tradeContainer = gScene.fieldUI.getByName("Trade Background") as Phaser.GameObjects.Container; + const tradeContainer = globalScene.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(receivedPokemon: PlayerPokemon, receivedPokemon const BASE_ANIM_DURATION = 1000; // Pokeball falls to the screen - gScene.playSound("se/pb_throw"); - gScene.tweens.add({ + globalScene.playSound("se/pb_throw"); + globalScene.tweens.add({ targets: receivedPokeballSprite, y: "+=100", ease: "Cubic.easeInOut", duration: BASE_ANIM_DURATION, onComplete: () => { - gScene.playSound("se/pb_bounce_1"); - gScene.time.delayedCall(100, () => gScene.playSound("se/pb_bounce_1")); + globalScene.playSound("se/pb_bounce_1"); + globalScene.time.delayedCall(100, () => globalScene.playSound("se/pb_bounce_1")); - gScene.time.delayedCall(2000, () => { - gScene.playSound("se/pb_rel"); - gScene.fadeOutBgm(500, false); + globalScene.time.delayedCall(2000, () => { + globalScene.playSound("se/pb_rel"); + globalScene.fadeOutBgm(500, false); receivedPokemon.cry(); receivedPokemonTintSprite.scale = 0.25; receivedPokemonTintSprite.alpha = 1; @@ -820,14 +820,14 @@ function doTradeReceivedSequence(receivedPokemon: PlayerPokemon, receivedPokemon receivedPokemonTintSprite.alpha = 1; receivedPokemonTintSprite.setVisible(true); receivedPokeballSprite.setTexture("pb", `${receivedPbAtlasKey}_opening`); - gScene.time.delayedCall(17, () => receivedPokeballSprite.setTexture("pb", `${receivedPbAtlasKey}_open`)); - gScene.tweens.add({ + globalScene.time.delayedCall(17, () => receivedPokeballSprite.setTexture("pb", `${receivedPbAtlasKey}_open`)); + globalScene.tweens.add({ targets: receivedPokemonSprite, duration: 250, ease: "Sine.easeOut", scale: 1 }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: receivedPokemonTintSprite, duration: 250, ease: "Sine.easeOut", @@ -835,7 +835,7 @@ function doTradeReceivedSequence(receivedPokemon: PlayerPokemon, receivedPokemon alpha: 0, onComplete: () => { receivedPokeballSprite.destroy(); - gScene.time.delayedCall(2000, () => resolve()); + globalScene.time.delayedCall(2000, () => resolve()); } }); }); diff --git a/src/data/mystery-encounters/encounters/lost-at-sea-encounter.ts b/src/data/mystery-encounters/encounters/lost-at-sea-encounter.ts index 2b2c760bda0..871ee1a5e30 100644 --- a/src/data/mystery-encounters/encounters/lost-at-sea-encounter.ts +++ b/src/data/mystery-encounters/encounters/lost-at-sea-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -42,7 +42,7 @@ export const LostAtSeaEncounter: MysteryEncounter = MysteryEncounterBuilder.with ]) .withIntroDialogue([{ text: `${namespace}:intro` }]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.setDialogueToken("damagePercentage", String(DAMAGE_PERCENTAGE)); encounter.setDialogueToken("option1RequiredMove", new PokemonMove(OPTION_1_REQUIRED_MOVE).getName()); @@ -104,7 +104,7 @@ export const LostAtSeaEncounter: MysteryEncounter = MysteryEncounterBuilder.with ], }, async () => { - const allowedPokemon = gScene.getParty().filter((p) => p.isAllowedInBattle()); + const allowedPokemon = globalScene.getParty().filter((p) => p.isAllowedInBattle()); for (const pkm of allowedPokemon) { const percentage = DAMAGE_PERCENTAGE / 100; @@ -131,7 +131,7 @@ export const LostAtSeaEncounter: MysteryEncounter = MysteryEncounterBuilder.with */ function handlePokemonGuidingYouPhase() { const laprasSpecies = getPokemonSpecies(Species.LAPRAS); - const { mysteryEncounter } = gScene.currentBattle; + const { mysteryEncounter } = globalScene.currentBattle; if (mysteryEncounter?.selectedOption?.primaryPokemon?.id) { setEncounterExp(mysteryEncounter.selectedOption.primaryPokemon.id, laprasSpecies.baseExp, true); diff --git a/src/data/mystery-encounters/encounters/mysterious-challengers-encounter.ts b/src/data/mystery-encounters/encounters/mysterious-challengers-encounter.ts index f4b4df93e62..7866dba1b02 100644 --- a/src/data/mystery-encounters/encounters/mysterious-challengers-encounter.ts +++ b/src/data/mystery-encounters/encounters/mysterious-challengers-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -38,11 +38,11 @@ export const MysteriousChallengersEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculates what trainers are available for battle in the encounter // Normal difficulty trainer is randomly pulled from biome - const normalTrainerType = gScene.arena.randomTrainerType(gScene.currentBattle.waveIndex); + const normalTrainerType = globalScene.arena.randomTrainerType(globalScene.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 = gScene.arena.randomTrainerType(gScene.currentBattle.waveIndex); + let hardTrainerType = globalScene.arena.randomTrainerType(globalScene.currentBattle.waveIndex); while (retries < 5 && hardTrainerType === normalTrainerType) { // Will try to use a different trainer from the normal trainer type - hardTrainerType = gScene.arena.randomTrainerType(gScene.currentBattle.waveIndex); + hardTrainerType = globalScene.arena.randomTrainerType(globalScene.currentBattle.waveIndex); retries++; } const hardTemplate = new TrainerPartyCompoundTemplate( new TrainerPartyTemplate(1, PartyMemberStrength.STRONGER, false, true), new TrainerPartyTemplate( - Math.min(Math.ceil(gScene.currentBattle.waveIndex / 20), 5), + Math.min(Math.ceil(globalScene.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 = gScene.arena.randomTrainerType( - gScene.currentBattle.waveIndex, + const brutalTrainerType = globalScene.arena.randomTrainerType( + globalScene.currentBattle.waveIndex, true ); const e4Template = trainerPartyTemplates.ELITE_FOUR; @@ -146,7 +146,7 @@ export const MysteriousChallengersEncounter: MysteryEncounter = ], }, async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Spawn standard trainer battle with memory mushroom reward const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0]; @@ -154,9 +154,9 @@ export const MysteriousChallengersEncounter: MysteryEncounter = // Seed offsets to remove possibility of different trainers having exact same teams let initBattlePromise: Promise; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { initBattlePromise = initBattleWithEnemyConfig(config); - }, gScene.currentBattle.waveIndex * 10); + }, globalScene.currentBattle.waveIndex * 10); await initBattlePromise!; } ) @@ -171,7 +171,7 @@ export const MysteriousChallengersEncounter: MysteryEncounter = ], }, async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Spawn hard fight const config: EnemyPartyConfig = encounter.enemyPartyConfigs[1]; @@ -179,9 +179,9 @@ export const MysteriousChallengersEncounter: MysteryEncounter = // Seed offsets to remove possibility of different trainers having exact same teams let initBattlePromise: Promise; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { initBattlePromise = initBattleWithEnemyConfig(config); - }, gScene.currentBattle.waveIndex * 100); + }, globalScene.currentBattle.waveIndex * 100); await initBattlePromise!; } ) @@ -196,7 +196,7 @@ export const MysteriousChallengersEncounter: MysteryEncounter = ], }, async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Spawn brutal fight const config: EnemyPartyConfig = encounter.enemyPartyConfigs[2]; @@ -207,9 +207,9 @@ export const MysteriousChallengersEncounter: MysteryEncounter = // Seed offsets to remove possibility of different trainers having exact same teams let initBattlePromise: Promise; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { initBattlePromise = initBattleWithEnemyConfig(config); - }, gScene.currentBattle.waveIndex * 1000); + }, globalScene.currentBattle.waveIndex * 1000); await initBattlePromise!; } ) diff --git a/src/data/mystery-encounters/encounters/mysterious-chest-encounter.ts b/src/data/mystery-encounters/encounters/mysterious-chest-encounter.ts index 1b8f4657c71..a460b92dea2 100644 --- a/src/data/mystery-encounters/encounters/mysterious-chest-encounter.ts +++ b/src/data/mystery-encounters/encounters/mysterious-chest-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -66,7 +66,7 @@ export const MysteriousChestEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculate boss mon const config: EnemyPartyConfig = { @@ -107,7 +107,7 @@ export const MysteriousChestEncounter: MysteryEncounter = }) .withPreOptionPhase(async () => { // Play animation - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const introVisuals = encounter.introVisuals!; // Determine roll first @@ -129,7 +129,7 @@ export const MysteriousChestEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Open the chest - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const roll = encounter.misc.roll; if (roll >= RAND_LENGTH - COMMON_REWARDS_PERCENT) { // Choose between 2 COMMON / 2 GREAT tier items (20%) @@ -177,11 +177,11 @@ export const MysteriousChestEncounter: MysteryEncounter = await showEncounterText(`${namespace}:option.1.bad`); // Handle game over edge case - const allowedPokemon = gScene.getParty().filter(p => p.isAllowedInBattle()); + const allowedPokemon = globalScene.getParty().filter(p => p.isAllowedInBattle()); if (allowedPokemon.length === 0) { // If there are no longer any legal pokemon in the party, game over. - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new GameOverPhase()); + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new GameOverPhase()); } else { // Show which Pokemon was KOed, then start battle against Gimmighoul await transitionMysteryEncounterIntroVisuals(true, true, 500); diff --git a/src/data/mystery-encounters/encounters/part-timer-encounter.ts b/src/data/mystery-encounters/encounters/part-timer-encounter.ts index b0d105d38f7..1b5163a44c0 100644 --- a/src/data/mystery-encounters/encounters/part-timer-encounter.ts +++ b/src/data/mystery-encounters/encounters/part-timer-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -54,18 +54,18 @@ export const PartTimerEncounter: MysteryEncounter = ]) .withOnInit(() => { // Load sfx - 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"); + globalScene.loadSe("PRSFX- Horn Drill1", "battle_anims", "PRSFX- Horn Drill1.wav"); + globalScene.loadSe("PRSFX- Horn Drill3", "battle_anims", "PRSFX- Horn Drill3.wav"); + globalScene.loadSe("PRSFX- Guillotine2", "battle_anims", "PRSFX- Guillotine2.wav"); + globalScene.loadSe("PRSFX- Heavy Slam2", "battle_anims", "PRSFX- Heavy Slam2.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"); + globalScene.loadSe("PRSFX- Agility", "battle_anims", "PRSFX- Agility.wav"); + globalScene.loadSe("PRSFX- Extremespeed1", "battle_anims", "PRSFX- Extremespeed1.wav"); + globalScene.loadSe("PRSFX- Accelerock1", "battle_anims", "PRSFX- Accelerock1.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"); + globalScene.loadSe("PRSFX- Captivate", "battle_anims", "PRSFX- Captivate.wav"); + globalScene.loadSe("PRSFX- Attract2", "battle_anims", "PRSFX- Attract2.wav"); + globalScene.loadSe("PRSFX- Aurora Veil2", "battle_anims", "PRSFX- Aurora Veil2.wav"); return true; }) @@ -85,7 +85,7 @@ export const PartTimerEncounter: MysteryEncounter = ] }) .withPreOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { encounter.setDialogueToken("selectedPokemon", pokemon.getNameToRender()); @@ -129,7 +129,7 @@ export const PartTimerEncounter: MysteryEncounter = // Bring visuals back in await transitionMysteryEncounterIntroVisuals(false, false); - const moneyMultiplier = gScene.currentBattle.mysteryEncounter!.misc.moneyMultiplier; + const moneyMultiplier = globalScene.currentBattle.mysteryEncounter!.misc.moneyMultiplier; // Give money and do dialogue if (moneyMultiplier > 2.5) { @@ -137,7 +137,7 @@ export const PartTimerEncounter: MysteryEncounter = } else { await showEncounterDialogue(`${namespace}:job_complete_bad`, `${namespace}:speaker`); } - const moneyChange = gScene.getWaveMoneyAmount(moneyMultiplier); + const moneyChange = globalScene.getWaveMoneyAmount(moneyMultiplier); updatePlayerMoney(moneyChange, true, false); await showEncounterText(i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange })); await showEncounterText(`${namespace}:pokemon_tired`); @@ -159,7 +159,7 @@ export const PartTimerEncounter: MysteryEncounter = ] }) .withPreOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { encounter.setDialogueToken("selectedPokemon", pokemon.getNameToRender()); @@ -206,7 +206,7 @@ export const PartTimerEncounter: MysteryEncounter = // Bring visuals back in await transitionMysteryEncounterIntroVisuals(false, false); - const moneyMultiplier = gScene.currentBattle.mysteryEncounter!.misc.moneyMultiplier; + const moneyMultiplier = globalScene.currentBattle.mysteryEncounter!.misc.moneyMultiplier; // Give money and do dialogue if (moneyMultiplier > 2.5) { @@ -214,7 +214,7 @@ export const PartTimerEncounter: MysteryEncounter = } else { await showEncounterDialogue(`${namespace}:job_complete_bad`, `${namespace}:speaker`); } - const moneyChange = gScene.getWaveMoneyAmount(moneyMultiplier); + const moneyChange = globalScene.getWaveMoneyAmount(moneyMultiplier); updatePlayerMoney(moneyChange, true, false); await showEncounterText(i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange })); await showEncounterText(`${namespace}:pokemon_tired`); @@ -239,7 +239,7 @@ export const PartTimerEncounter: MysteryEncounter = ], }) .withPreOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const selectedPokemon = encounter.selectedOption?.primaryPokemon!; encounter.setDialogueToken("selectedPokemon", selectedPokemon.getNameToRender()); @@ -266,7 +266,7 @@ export const PartTimerEncounter: MysteryEncounter = // Give money and do dialogue await showEncounterDialogue(`${namespace}:job_complete_good`, `${namespace}:speaker`); - const moneyChange = gScene.getWaveMoneyAmount(2.5); + const moneyChange = globalScene.getWaveMoneyAmount(2.5); updatePlayerMoney(moneyChange, true, false); await showEncounterText(i18next.t("mysteryEncounterMessages:receive_money", { amount: moneyChange })); await showEncounterText(`${namespace}:pokemon_tired`); @@ -285,50 +285,50 @@ export const PartTimerEncounter: MysteryEncounter = .build(); function doStrongWorkSfx() { - gScene.playSound("battle_anims/PRSFX- Horn Drill1"); - gScene.playSound("battle_anims/PRSFX- Horn Drill1"); + globalScene.playSound("battle_anims/PRSFX- Horn Drill1"); + globalScene.playSound("battle_anims/PRSFX- Horn Drill1"); - gScene.time.delayedCall(1000, () => { - gScene.playSound("battle_anims/PRSFX- Guillotine2"); + globalScene.time.delayedCall(1000, () => { + globalScene.playSound("battle_anims/PRSFX- Guillotine2"); }); - gScene.time.delayedCall(2000, () => { - gScene.playSound("battle_anims/PRSFX- Heavy Slam2"); + globalScene.time.delayedCall(2000, () => { + globalScene.playSound("battle_anims/PRSFX- Heavy Slam2"); }); - gScene.time.delayedCall(2500, () => { - gScene.playSound("battle_anims/PRSFX- Guillotine2"); + globalScene.time.delayedCall(2500, () => { + globalScene.playSound("battle_anims/PRSFX- Guillotine2"); }); } function doDeliverySfx() { - gScene.playSound("battle_anims/PRSFX- Accelerock1"); + globalScene.playSound("battle_anims/PRSFX- Accelerock1"); - gScene.time.delayedCall(1500, () => { - gScene.playSound("battle_anims/PRSFX- Extremespeed1"); + globalScene.time.delayedCall(1500, () => { + globalScene.playSound("battle_anims/PRSFX- Extremespeed1"); }); - gScene.time.delayedCall(2000, () => { - gScene.playSound("battle_anims/PRSFX- Extremespeed1"); + globalScene.time.delayedCall(2000, () => { + globalScene.playSound("battle_anims/PRSFX- Extremespeed1"); }); - gScene.time.delayedCall(2250, () => { - gScene.playSound("battle_anims/PRSFX- Agility"); + globalScene.time.delayedCall(2250, () => { + globalScene.playSound("battle_anims/PRSFX- Agility"); }); } function doSalesSfx() { - gScene.playSound("battle_anims/PRSFX- Captivate"); + globalScene.playSound("battle_anims/PRSFX- Captivate"); - gScene.time.delayedCall(1500, () => { - gScene.playSound("battle_anims/PRSFX- Attract2"); + globalScene.time.delayedCall(1500, () => { + globalScene.playSound("battle_anims/PRSFX- Attract2"); }); - gScene.time.delayedCall(2000, () => { - gScene.playSound("battle_anims/PRSFX- Aurora Veil2"); + globalScene.time.delayedCall(2000, () => { + globalScene.playSound("battle_anims/PRSFX- Aurora Veil2"); }); - gScene.time.delayedCall(3000, () => { - gScene.playSound("battle_anims/PRSFX- Attract2"); + globalScene.time.delayedCall(3000, () => { + globalScene.playSound("battle_anims/PRSFX- Attract2"); }); } diff --git a/src/data/mystery-encounters/encounters/safari-zone-encounter.ts b/src/data/mystery-encounters/encounters/safari-zone-encounter.ts index 832cf2b29b2..096d24c7c77 100644 --- a/src/data/mystery-encounters/encounters/safari-zone-encounter.ts +++ b/src/data/mystery-encounters/encounters/safari-zone-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -59,7 +59,7 @@ export const SafariZoneEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - gScene.currentBattle.mysteryEncounter?.setDialogueToken("numEncounters", NUM_SAFARI_ENCOUNTERS.toString()); + globalScene.currentBattle.mysteryEncounter?.setDialogueToken("numEncounters", NUM_SAFARI_ENCOUNTERS.toString()); return true; }) .withOption(MysteryEncounterOptionBuilder @@ -76,20 +76,20 @@ export const SafariZoneEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Start safari encounter - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.continuousEncounter = true; encounter.misc = { safariPokemonRemaining: NUM_SAFARI_ENCOUNTERS }; updatePlayerMoney(-(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney); // Load bait/mud assets - 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"); + globalScene.loadSe("PRSFX- Bug Bite", "battle_anims", "PRSFX- Bug Bite.wav"); + globalScene.loadSe("PRSFX- Sludge Bomb2", "battle_anims", "PRSFX- Sludge Bomb2.wav"); + globalScene.loadSe("PRSFX- Taunt2", "battle_anims", "PRSFX- Taunt2.wav"); + globalScene.loadAtlas("safari_zone_bait", "mystery-encounters"); + globalScene.loadAtlas("safari_zone_mud", "mystery-encounters"); // Clear enemy party - gScene.currentBattle.enemyParty = []; + globalScene.currentBattle.enemyParty = []; await transitionMysteryEncounterIntroVisuals(); await summonSafariPokemon(); initSubsequentOptionSelect({ overrideOptions: safariZoneGameOptions, hideDescription: true }); @@ -144,7 +144,7 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [ }) .withOptionPhase(async () => { // Throw a ball option - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const pokemon = encounter.misc.pokemon; const catchResult = await throwPokeball(pokemon); @@ -179,7 +179,7 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [ }) .withOptionPhase(async () => { // Throw bait option - const pokemon = gScene.currentBattle.mysteryEncounter!.misc.pokemon; + const pokemon = globalScene.currentBattle.mysteryEncounter!.misc.pokemon; await throwBait(pokemon); // 100% chance to increase catch stage +2 @@ -209,7 +209,7 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [ }) .withOptionPhase(async () => { // Throw mud option - const pokemon = gScene.currentBattle.mysteryEncounter!.misc.pokemon; + const pokemon = globalScene.currentBattle.mysteryEncounter!.misc.pokemon; await throwMud(pokemon); // 100% chance to decrease flee stage -2 tryChangeFleeStage(-2); @@ -233,7 +233,7 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [ }) .withOptionPhase(async () => { // Flee option - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const pokemon = encounter.misc.pokemon; await doPlayerFlee(pokemon); // Check how many safari pokemon left @@ -251,20 +251,20 @@ const safariZoneGameOptions: MysteryEncounterOption[] = [ ]; async function summonSafariPokemon() { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Message pokemon remaining encounter.setDialogueToken("remainingCount", encounter.misc.safariPokemonRemaining); - gScene.queueMessage(getEncounterText(`${namespace}:safari.remaining_count`) ?? "", null, true); + globalScene.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; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { enemySpecies = getPokemonSpecies(getRandomSpeciesByStarterTier([ 0, 5 ], undefined, undefined, false, false, false)); - const level = gScene.currentBattle.getLevelForWave(); - enemySpecies = getPokemonSpecies(enemySpecies.getWildSpeciesForLevel(level, true, false, gScene.gameMode)); - pokemon = gScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, false); + const level = globalScene.currentBattle.getLevelForWave(); + enemySpecies = getPokemonSpecies(enemySpecies.getWildSpeciesForLevel(level, true, false, globalScene.gameMode)); + pokemon = globalScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, false); // Roll shiny twice if (!pokemon.shiny) { @@ -276,7 +276,7 @@ async function summonSafariPokemon() { const hiddenIndex = pokemon.species.ability2 ? 2 : 1; if (pokemon.abilityIndex < hiddenIndex) { const hiddenAbilityChance = new IntegerHolder(256); - gScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); + globalScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); const hasHiddenAbility = !randSeedInt(hiddenAbilityChance.value); @@ -288,10 +288,10 @@ async function summonSafariPokemon() { pokemon.calculateStats(); - gScene.currentBattle.enemyParty.unshift(pokemon); - }, gScene.currentBattle.waveIndex * 1000 * encounter.misc.safariPokemonRemaining); + globalScene.currentBattle.enemyParty.unshift(pokemon); + }, globalScene.currentBattle.waveIndex * 1000 * encounter.misc.safariPokemonRemaining); - gScene.gameData.setPokemonSeen(pokemon, true); + globalScene.gameData.setPokemonSeen(pokemon, true); await pokemon.loadAssets(); // Reset safari catch and flee rates @@ -300,7 +300,7 @@ async function summonSafariPokemon() { encounter.misc.pokemon = pokemon; encounter.misc.safariPokemonRemaining -= 1; - gScene.unshiftPhase(new SummonPhase(0, false)); + globalScene.unshiftPhase(new SummonPhase(0, false)); encounter.setDialogueToken("pokemonName", getPokemonNameWithAffix(pokemon)); @@ -309,16 +309,16 @@ async function summonSafariPokemon() { // 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 = gScene.findModifier(m => m instanceof IvScannerModifier); + const ivScannerModifier = globalScene.findModifier(m => m instanceof IvScannerModifier); if (ivScannerModifier) { - gScene.pushPhase(new ScanIvsPhase(pokemon.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6))); + globalScene.pushPhase(new ScanIvsPhase(pokemon.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6))); } } function throwPokeball(pokemon: EnemyPokemon): Promise { const baseCatchRate = pokemon.species.catchRate; // Catch stage ranges from -6 to +6 (like stat boost stages) - const safariCatchStage = gScene.currentBattle.mysteryEncounter!.misc.catchStage; + const safariCatchStage = globalScene.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 @@ -332,26 +332,26 @@ async function throwBait(pokemon: EnemyPokemon): Promise { const originalY: number = pokemon.y; const fpOffset = pokemon.getFieldPositionOffset(); - const bait: Phaser.GameObjects.Sprite = gScene.addFieldSprite(16 + 75, 80 + 25, "safari_zone_bait", "0001.png"); + const bait: Phaser.GameObjects.Sprite = globalScene.addFieldSprite(16 + 75, 80 + 25, "safari_zone_bait", "0001.png"); bait.setOrigin(0.5, 0.625); - gScene.field.add(bait); + globalScene.field.add(bait); return new Promise(resolve => { - 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"); + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`); + globalScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[0], () => { + globalScene.playSound("se/pb_throw"); // Trainer throw frames - 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`); + globalScene.trainer.setFrame("2"); + globalScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[1], () => { + globalScene.trainer.setFrame("3"); + globalScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[2], () => { + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`); }); }); // Pokeball move and catch logic - gScene.tweens.add({ + globalScene.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(pokemon: EnemyPokemon): Promise { onComplete: () => { let index = 1; - gScene.time.delayedCall(768, () => { - gScene.tweens.add({ + globalScene.time.delayedCall(768, () => { + globalScene.tweens.add({ targets: pokemon, duration: 150, ease: "Cubic.easeOut", @@ -368,12 +368,12 @@ async function throwBait(pokemon: EnemyPokemon): Promise { y: originalY - 5, loop: 6, onStart: () => { - gScene.playSound("battle_anims/PRSFX- Bug Bite"); + globalScene.playSound("battle_anims/PRSFX- Bug Bite"); bait.setFrame("0002.png"); }, onLoop: () => { if (index % 2 === 0) { - gScene.playSound("battle_anims/PRSFX- Bug Bite"); + globalScene.playSound("battle_anims/PRSFX- Bug Bite"); } if (index === 4) { bait.setFrame("0003.png"); @@ -381,7 +381,7 @@ async function throwBait(pokemon: EnemyPokemon): Promise { index++; }, onComplete: () => { - gScene.time.delayedCall(256, () => { + globalScene.time.delayedCall(256, () => { bait.destroy(); resolve(true); }); @@ -398,51 +398,51 @@ async function throwMud(pokemon: EnemyPokemon): Promise { const originalY: number = pokemon.y; const fpOffset = pokemon.getFieldPositionOffset(); - const mud: Phaser.GameObjects.Sprite = gScene.addFieldSprite(16 + 75, 80 + 35, "safari_zone_mud", "0001.png"); + const mud: Phaser.GameObjects.Sprite = globalScene.addFieldSprite(16 + 75, 80 + 35, "safari_zone_mud", "0001.png"); mud.setOrigin(0.5, 0.625); - gScene.field.add(mud); + globalScene.field.add(mud); return new Promise(resolve => { - 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"); + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`); + globalScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[0], () => { + globalScene.playSound("se/pb_throw"); // Trainer throw frames - 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`); + globalScene.trainer.setFrame("2"); + globalScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[1], () => { + globalScene.trainer.setFrame("3"); + globalScene.time.delayedCall(TRAINER_THROW_ANIMATION_TIMES[2], () => { + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`); }); }); // Mud throw and splat - gScene.tweens.add({ + globalScene.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 - gScene.playSound("battle_anims/PRSFX- Sludge Bomb2"); + globalScene.playSound("battle_anims/PRSFX- Sludge Bomb2"); mud.setFrame("0002.png"); // Mud splat - gScene.time.delayedCall(200, () => { + globalScene.time.delayedCall(200, () => { mud.setFrame("0003.png"); - gScene.time.delayedCall(400, () => { + globalScene.time.delayedCall(400, () => { mud.setFrame("0004.png"); }); }); // Fade mud then angry animation - gScene.tweens.add({ + globalScene.tweens.add({ targets: mud, alpha: 0, ease: "Cubic.easeIn", duration: 1000, onComplete: () => { mud.destroy(); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, duration: 300, ease: "Cubic.easeOut", @@ -450,10 +450,10 @@ async function throwMud(pokemon: EnemyPokemon): Promise { y: originalY - 20, loop: 1, onStart: () => { - gScene.playSound("battle_anims/PRSFX- Taunt2"); + globalScene.playSound("battle_anims/PRSFX- Taunt2"); }, onLoop: () => { - gScene.playSound("battle_anims/PRSFX- Taunt2"); + globalScene.playSound("battle_anims/PRSFX- Taunt2"); }, onComplete: () => { resolve(true); @@ -481,8 +481,8 @@ function tryChangeFleeStage(change: number, chance?: number): boolean { if (chance && randSeedInt(10) >= chance) { return false; } - const currentFleeStage = gScene.currentBattle.mysteryEncounter!.misc.fleeStage ?? 0; - gScene.currentBattle.mysteryEncounter!.misc.fleeStage = Math.min(Math.max(currentFleeStage + change, -6), 6); + const currentFleeStage = globalScene.currentBattle.mysteryEncounter!.misc.fleeStage ?? 0; + globalScene.currentBattle.mysteryEncounter!.misc.fleeStage = Math.min(Math.max(currentFleeStage + change, -6), 6); return true; } @@ -490,23 +490,23 @@ function tryChangeCatchStage(change: number, chance?: number): boolean { if (chance && randSeedInt(10) >= chance) { return false; } - const currentCatchStage = gScene.currentBattle.mysteryEncounter!.misc.catchStage ?? 0; - gScene.currentBattle.mysteryEncounter!.misc.catchStage = Math.min(Math.max(currentCatchStage + change, -6), 6); + const currentCatchStage = globalScene.currentBattle.mysteryEncounter!.misc.catchStage ?? 0; + globalScene.currentBattle.mysteryEncounter!.misc.catchStage = Math.min(Math.max(currentCatchStage + change, -6), 6); return true; } 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 = gScene.getEnemyParty(); + const party = globalScene.getEnemyParty(); if (party.length > 1) { for (let i = 1; i < party.length; i++) { party[i].destroy(); } - gScene.currentBattle.enemyParty = party.slice(0, 1); + globalScene.currentBattle.enemyParty = party.slice(0, 1); } - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const pokemon = encounter.misc.pokemon; const isFlee = isPokemonFlee(pokemon, encounter.misc.fleeStage); if (isFlee) { @@ -522,7 +522,7 @@ async function doEndTurn(cursorIndex: number) { leaveEncounterWithoutBattle(true); } } else { - gScene.queueMessage(getEncounterText(`${namespace}:safari.watching`) ?? "", 0, null, 1000); + globalScene.queueMessage(getEncounterText(`${namespace}:safari.watching`) ?? "", 0, null, 1000); initSubsequentOptionSelect({ overrideOptions: safariZoneGameOptions, startingCursorIndex: cursorIndex, hideDescription: true }); } } diff --git a/src/data/mystery-encounters/encounters/shady-vitamin-dealer-encounter.ts b/src/data/mystery-encounters/encounters/shady-vitamin-dealer-encounter.ts index badd8086c94..97b83d08149 100644 --- a/src/data/mystery-encounters/encounters/shady-vitamin-dealer-encounter.ts +++ b/src/data/mystery-encounters/encounters/shady-vitamin-dealer-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -80,7 +80,7 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter = ], }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Update money updatePlayerMoney(-(encounter.options[0].requirements[0] as MoneyRequirement).requiredMoney); @@ -114,7 +114,7 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Choose Cheap Option - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const chosenPokemon = encounter.misc.chosenPokemon; const modifiers = encounter.misc.modifiers; @@ -126,7 +126,7 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter = }) .withPostOptionPhase(async () => { // Damage and status applied after dealer leaves (to make thematic sense) - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const chosenPokemon = encounter.misc.chosenPokemon as PlayerPokemon; // Pokemon takes half max HP damage and nature is randomized (does not update dex) @@ -160,7 +160,7 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter = ], }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Update money updatePlayerMoney(-(encounter.options[1].requirements[0] as MoneyRequirement).requiredMoney); @@ -186,7 +186,7 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Choose Expensive Option - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const chosenPokemon = encounter.misc.chosenPokemon; const modifiers = encounter.misc.modifiers; @@ -198,7 +198,7 @@ export const ShadyVitaminDealerEncounter: MysteryEncounter = }) .withPostOptionPhase(async () => { // Status applied after dealer leaves (to make thematic sense) - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const chosenPokemon = encounter.misc.chosenPokemon; queueEncounterMessage(`${namespace}:no_bad_effects`); diff --git a/src/data/mystery-encounters/encounters/slumbering-snorlax-encounter.ts b/src/data/mystery-encounters/encounters/slumbering-snorlax-encounter.ts index f89fe3aa3d2..6a78b47bd06 100644 --- a/src/data/mystery-encounters/encounters/slumbering-snorlax-encounter.ts +++ b/src/data/mystery-encounters/encounters/slumbering-snorlax-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -52,7 +52,7 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; console.log(encounter); // Calculate boss mon @@ -104,7 +104,7 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter = }, async () => { // Pick battle - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.LEFTOVERS ], fillRemaining: true }); encounter.startOfBattleEffects.push( { @@ -135,7 +135,7 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter = async () => { // Fall asleep waiting for Snorlax // Full heal party - gScene.unshiftPhase(new PartyHealPhase(true)); + globalScene.unshiftPhase(new PartyHealPhase(true)); queueEncounterMessage(`${namespace}:option.2.rest_result`); leaveEncounterWithoutBattle(); } @@ -156,7 +156,7 @@ export const SlumberingSnorlaxEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Steal the Snorlax's Leftovers - const instance = gScene.currentBattle.mysteryEncounter!; + const instance = globalScene.currentBattle.mysteryEncounter!; setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.LEFTOVERS ], fillRemaining: false }); // Snorlax exp to Pokemon that did the stealing setEncounterExp(instance.primaryPokemon!.id, getPokemonSpecies(Species.SNORLAX).baseExp); diff --git a/src/data/mystery-encounters/encounters/teleporting-hijinks-encounter.ts b/src/data/mystery-encounters/encounters/teleporting-hijinks-encounter.ts index ad5e0309e5a..dd68f8d55fd 100644 --- a/src/data/mystery-encounters/encounters/teleporting-hijinks-encounter.ts +++ b/src/data/mystery-encounters/encounters/teleporting-hijinks-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -63,8 +63,8 @@ export const TeleportingHijinksEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; - const price = gScene.getWaveMoneyAmount(MONEY_COST_MULTIPLIER); + const encounter = globalScene.currentBattle.mysteryEncounter!; + const price = globalScene.getWaveMoneyAmount(MONEY_COST_MULTIPLIER); encounter.setDialogueToken("price", price.toString()); encounter.misc = { price @@ -87,7 +87,7 @@ export const TeleportingHijinksEncounter: MysteryEncounter = }) .withPreOptionPhase(async () => { // Update money - updatePlayerMoney(-gScene.currentBattle.mysteryEncounter!.misc.price, true, false); + updatePlayerMoney(-globalScene.currentBattle.mysteryEncounter!.misc.price, true, false); }) .withOptionPhase(async () => { const config: EnemyPartyConfig = await doBiomeTransitionDialogueAndBattleInit(); @@ -113,7 +113,7 @@ export const TeleportingHijinksEncounter: MysteryEncounter = .withOptionPhase(async () => { const config: EnemyPartyConfig = await doBiomeTransitionDialogueAndBattleInit(); setEncounterRewards({ fillRemaining: true }); - setEncounterExp(gScene.currentBattle.mysteryEncounter!.selectedOption!.primaryPokemon!.id, 100); + setEncounterExp(globalScene.currentBattle.mysteryEncounter!.selectedOption!.primaryPokemon!.id, 100); await initBattleWithEnemyConfig(config); }) .build() @@ -130,11 +130,11 @@ export const TeleportingHijinksEncounter: MysteryEncounter = }, async () => { // Inspect the Machine - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Init enemy const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER); - const bossSpecies = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true); + const bossSpecies = globalScene.arena.randomSpecies(globalScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(globalScene.getParty()), true); const bossPokemon = new EnemyPokemon(bossSpecies, level, TrainerSlot.NONE, true); encounter.setDialogueToken("enemyPokemon", getPokemonNameWithAffix(bossPokemon)); const config: EnemyPartyConfig = { @@ -156,26 +156,26 @@ export const TeleportingHijinksEncounter: MysteryEncounter = .build(); async function doBiomeTransitionDialogueAndBattleInit() { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculate new biome (cannot be current biome) - const filteredBiomes = BIOME_CANDIDATES.filter(b => gScene.arena.biomeType !== b); + const filteredBiomes = BIOME_CANDIDATES.filter(b => globalScene.arena.biomeType !== b); const newBiome = filteredBiomes[randSeedInt(filteredBiomes.length)]; // Show dialogue and transition biome await showEncounterText(`${namespace}:transport`); await Promise.all([ animateBiomeChange(newBiome), transitionMysteryEncounterIntroVisuals() ]); - gScene.playBgm(); + globalScene.playBgm(); await showEncounterText(`${namespace}:attacked`); // Init enemy const level = getEncounterPokemonLevelForWave(STANDARD_ENCOUNTER_BOOSTED_LEVEL_MODIFIER); - const bossSpecies = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true); + const bossSpecies = globalScene.arena.randomSpecies(globalScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(globalScene.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)[] = gScene.currentBattle.waveIndex < 50 ? + const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = globalScene.currentBattle.waveIndex < 50 ? [ Stat.DEF, Stat.SPDEF, Stat.SPD ] : [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ]; @@ -188,7 +188,7 @@ async function doBiomeTransitionDialogueAndBattleInit() { tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ], mysteryEncounterBattleEffects: (pokemon: Pokemon) => { queueEncounterMessage(`${namespace}:boss_enraged`); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1)); } }], }; @@ -198,44 +198,44 @@ async function doBiomeTransitionDialogueAndBattleInit() { async function animateBiomeChange(nextBiome: Biome) { return new Promise(resolve => { - gScene.tweens.add({ - targets: [ gScene.arenaEnemy, gScene.lastEnemyTrainer ], + globalScene.tweens.add({ + targets: [ globalScene.arenaEnemy, globalScene.lastEnemyTrainer ], x: "+=300", duration: 2000, onComplete: () => { - gScene.newArena(nextBiome); + globalScene.newArena(nextBiome); const biomeKey = getBiomeKey(nextBiome); const bgTexture = `${biomeKey}_bg`; - gScene.arenaBgTransition.setTexture(bgTexture); - gScene.arenaBgTransition.setAlpha(0); - gScene.arenaBgTransition.setVisible(true); - gScene.arenaPlayerTransition.setBiome(nextBiome); - gScene.arenaPlayerTransition.setAlpha(0); - gScene.arenaPlayerTransition.setVisible(true); + globalScene.arenaBgTransition.setTexture(bgTexture); + globalScene.arenaBgTransition.setAlpha(0); + globalScene.arenaBgTransition.setVisible(true); + globalScene.arenaPlayerTransition.setBiome(nextBiome); + globalScene.arenaPlayerTransition.setAlpha(0); + globalScene.arenaPlayerTransition.setVisible(true); - gScene.tweens.add({ - targets: [ gScene.arenaPlayer, gScene.arenaBgTransition, gScene.arenaPlayerTransition ], + globalScene.tweens.add({ + targets: [ globalScene.arenaPlayer, globalScene.arenaBgTransition, globalScene.arenaPlayerTransition ], duration: 1000, ease: "Sine.easeInOut", - alpha: (target: any) => target === gScene.arenaPlayer ? 0 : 1, + alpha: (target: any) => target === globalScene.arenaPlayer ? 0 : 1, onComplete: () => { - 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(); + globalScene.arenaBg.setTexture(bgTexture); + globalScene.arenaPlayer.setBiome(nextBiome); + globalScene.arenaPlayer.setAlpha(1); + globalScene.arenaEnemy.setBiome(nextBiome); + globalScene.arenaEnemy.setAlpha(1); + globalScene.arenaNextEnemy.setBiome(nextBiome); + globalScene.arenaBgTransition.setVisible(false); + globalScene.arenaPlayerTransition.setVisible(false); + if (globalScene.lastEnemyTrainer) { + globalScene.lastEnemyTrainer.destroy(); } resolve(); - gScene.tweens.add({ - targets: gScene.arenaEnemy, + globalScene.tweens.add({ + targets: globalScene.arenaEnemy, x: "-=300", }); } diff --git a/src/data/mystery-encounters/encounters/the-expert-pokemon-breeder-encounter.ts b/src/data/mystery-encounters/encounters/the-expert-pokemon-breeder-encounter.ts index 5d6acd2a7fd..f8ec83a4b3a 100644 --- a/src/data/mystery-encounters/encounters/the-expert-pokemon-breeder-encounter.ts +++ b/src/data/mystery-encounters/encounters/the-expert-pokemon-breeder-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { randSeedShuffle } from "#app/utils"; import MysteryEncounter, { MysteryEncounterBuilder } from "../mystery-encounter"; import { MysteryEncounterTier } from "#enums/mystery-encounter-tier"; @@ -95,8 +95,8 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; - const waveIndex = gScene.currentBattle.waveIndex; + const encounter = globalScene.currentBattle.mysteryEncounter!; + const waveIndex = globalScene.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 @@ -126,7 +126,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter = ]; // Determine the 3 pokemon the player can battle with - let partyCopy = gScene.getParty().slice(0); + let partyCopy = globalScene.getParty().slice(0); partyCopy = partyCopy .filter(p => p.isAllowedInBattle()) .sort((a, b) => a.friendship - b.friendship); @@ -214,7 +214,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter = ], }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Spawn battle with first pokemon const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0]; @@ -266,7 +266,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter = ], }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Spawn battle with second pokemon const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0]; @@ -318,7 +318,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter = ], }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Spawn battle with third pokemon const config: EnemyPartyConfig = encounter.enemyPartyConfigs[0]; @@ -367,7 +367,7 @@ export const TheExpertPokemonBreederEncounter: MysteryEncounter = function getPartyConfig(): EnemyPartyConfig { // Bug type superfan trainer config - const waveIndex = gScene.currentBattle.waveIndex; + const waveIndex = globalScene.currentBattle.waveIndex; const breederConfig = trainerConfigs[TrainerType.EXPERT_POKEMON_BREEDER].clone(); breederConfig.name = i18next.t(trainerNameKey); @@ -394,7 +394,7 @@ function getPartyConfig(): EnemyPartyConfig { ] }; - if (gScene.arena.biomeType === Biome.SPACE) { + if (globalScene.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() }), @@ -506,41 +506,41 @@ function getEggOptions(commonEggs: number, rareEggs: number) { } function removePokemonFromPartyAndStoreHeldItems(encounter: MysteryEncounter, chosenPokemon: PlayerPokemon) { - const party = gScene.getParty(); + const party = globalScene.getParty(); const chosenIndex = party.indexOf(chosenPokemon); party[chosenIndex] = party[0]; party[0] = chosenPokemon; - encounter.misc.originalParty = gScene.getParty().slice(1); + encounter.misc.originalParty = globalScene.getParty().slice(1); encounter.misc.originalPartyHeldItems = encounter.misc.originalParty .map(p => p.getHeldItems()); - gScene["party"] = [ + globalScene["party"] = [ chosenPokemon ]; } function checkAchievement() { - if (gScene.arena.biomeType === Biome.SPACE) { - gScene.validateAchv(achvs.BREEDERS_IN_SPACE); + if (globalScene.arena.biomeType === Biome.SPACE) { + globalScene.validateAchv(achvs.BREEDERS_IN_SPACE); } } function restorePartyAndHeldItems() { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Restore original party - gScene.getParty().push(...encounter.misc.originalParty); + globalScene.getParty().push(...encounter.misc.originalParty); // Restore held items const originalHeldItems = encounter.misc.originalPartyHeldItems; originalHeldItems.forEach((pokemonHeldItemsList: PokemonHeldItemModifier[]) => { pokemonHeldItemsList.forEach(heldItem => { - gScene.addModifier(heldItem, true, false, false, true); + globalScene.addModifier(heldItem, true, false, false, true); }); }); - gScene.updateModifiers(true); + globalScene.updateModifiers(true); } function onGameOver() { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.dialogue.outro = [ { @@ -561,33 +561,33 @@ function onGameOver() { encounter.misc.encounterFailed = true; // Revert BGM - gScene.playBgm(gScene.arena.bgm); + globalScene.playBgm(globalScene.arena.bgm); // Clear any leftover battle phases - gScene.clearPhaseQueue(); - gScene.clearPhaseQueueSplice(); + globalScene.clearPhaseQueue(); + globalScene.clearPhaseQueueSplice(); // Return enemy Pokemon - const pokemon = gScene.getEnemyPokemon(); + const pokemon = globalScene.getEnemyPokemon(); if (pokemon) { - gScene.playSound("se/pb_rel"); + globalScene.playSound("se/pb_rel"); pokemon.hideInfo(); pokemon.tint(getPokeballTintColor(pokemon.pokeball), 1, 250, "Sine.easeIn"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, duration: 250, ease: "Sine.easeIn", scale: 0.5, onComplete: () => { - gScene.field.remove(pokemon, true); + globalScene.field.remove(pokemon, true); } }); } // Show the enemy trainer - gScene.time.delayedCall(250, () => { - const sprites = gScene.currentBattle.trainer?.getSprites(); - const tintSprites = gScene.currentBattle.trainer?.getTintSprites(); + globalScene.time.delayedCall(250, () => { + const sprites = globalScene.currentBattle.trainer?.getSprites(); + const tintSprites = globalScene.currentBattle.trainer?.getTintSprites(); if (sprites && tintSprites) { for (let i = 0; i < sprites.length; i++) { sprites[i].setVisible(true); @@ -596,8 +596,8 @@ function onGameOver() { tintSprites[i].clearTint(); } } - gScene.tweens.add({ - targets: gScene.currentBattle.trainer, + globalScene.tweens.add({ + targets: globalScene.currentBattle.trainer, x: "-=16", y: "+=16", alpha: 1, @@ -613,7 +613,7 @@ function onGameOver() { } function doPostEncounterCleanup() { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; if (!encounter.misc.encounterFailed) { // Give achievement if in Space biome checkAchievement(); diff --git a/src/data/mystery-encounters/encounters/the-pokemon-salesman-encounter.ts b/src/data/mystery-encounters/encounters/the-pokemon-salesman-encounter.ts index 0e0d79cf2cb..8f205ddf969 100644 --- a/src/data/mystery-encounters/encounters/the-pokemon-salesman-encounter.ts +++ b/src/data/mystery-encounters/encounters/the-pokemon-salesman-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -58,7 +58,7 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; let species = getPokemonSpecies(getRandomSpeciesByStarterTier([ 0, 5 ], undefined, undefined, false, false, false)); let tries = 0; @@ -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 = gScene.getWaveMoneyAmount(priceMultiplier); + const price = globalScene.getWaveMoneyAmount(priceMultiplier); encounter.setDialogueToken("purchasePokemon", pokemon.getNameToRender()); encounter.setDialogueToken("price", price.toString()); encounter.misc = { @@ -127,7 +127,7 @@ export const ThePokemonSalesmanEncounter: MysteryEncounter = ], }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const price = encounter.misc.price; const purchasedPokemon = encounter.misc.pokemon as PlayerPokemon; diff --git a/src/data/mystery-encounters/encounters/the-strong-stuff-encounter.ts b/src/data/mystery-encounters/encounters/the-strong-stuff-encounter.ts index a19a49fb37c..206fdec3fc8 100644 --- a/src/data/mystery-encounters/encounters/the-strong-stuff-encounter.ts +++ b/src/data/mystery-encounters/encounters/the-strong-stuff-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -68,7 +68,7 @@ export const TheStrongStuffEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculate boss mon const config: EnemyPartyConfig = { @@ -103,7 +103,7 @@ export const TheStrongStuffEncounter: MysteryEncounter = tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ], mysteryEncounterBattleEffects: (pokemon: Pokemon) => { queueEncounterMessage(`${namespace}:option.2.stat_boost`); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.DEF, Stat.SPDEF ], 2)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, [ Stat.DEF, Stat.SPDEF ], 2)); } } ], @@ -132,15 +132,15 @@ export const TheStrongStuffEncounter: MysteryEncounter = ] }, async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Do blackout and hide intro visuals during blackout - gScene.time.delayedCall(750, () => { + globalScene.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 = gScene.getParty().slice(0) + const sortedParty = globalScene.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); @@ -184,7 +184,7 @@ export const TheStrongStuffEncounter: MysteryEncounter = }, async () => { // Pick battle - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.SOUL_DEW ], fillRemaining: true }); encounter.startOfBattleEffects.push( { diff --git a/src/data/mystery-encounters/encounters/the-winstrate-challenge-encounter.ts b/src/data/mystery-encounters/encounters/the-winstrate-challenge-encounter.ts index 70af9f359c3..afce15f721b 100644 --- a/src/data/mystery-encounters/encounters/the-winstrate-challenge-encounter.ts +++ b/src/data/mystery-encounters/encounters/the-winstrate-challenge-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -83,7 +83,7 @@ export const TheWinstrateChallengeEncounter: MysteryEncounter = ]) .withAutoHideIntroVisuals(false) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Loaded back to front for pop() operations encounter.enemyPartyConfigs.push(getVitoTrainerConfig()); @@ -111,7 +111,7 @@ export const TheWinstrateChallengeEncounter: MysteryEncounter = }, async () => { // Spawn 5 trainer battles back to back with Macho Brace in rewards - gScene.currentBattle.mysteryEncounter!.doContinueEncounter = async () => { + globalScene.currentBattle.mysteryEncounter!.doContinueEncounter = async () => { await endTrainerBattleAndShowDialogue(); }; await transitionMysteryEncounterIntroVisuals(true, false); @@ -131,7 +131,7 @@ export const TheWinstrateChallengeEncounter: MysteryEncounter = }, async () => { // Refuse the challenge, they full heal the party and give the player a Rarer Candy - gScene.unshiftPhase(new PartyHealPhase(true)); + globalScene.unshiftPhase(new PartyHealPhase(true)); setEncounterRewards({ guaranteedModifierTypeFuncs: [ modifierTypes.RARER_CANDY ], fillRemaining: false }); leaveEncounterWithoutBattle(); } @@ -139,7 +139,7 @@ export const TheWinstrateChallengeEncounter: MysteryEncounter = .build(); async function spawnNextTrainerOrEndEncounter() { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const nextConfig = encounter.enemyPartyConfigs.pop(); if (!nextConfig) { await transitionMysteryEncounterIntroVisuals(false, false); @@ -147,12 +147,12 @@ async function spawnNextTrainerOrEndEncounter() { // Give 10x Voucher const newModifier = modifierTypes.VOUCHER_PREMIUM().newModifier(); - await gScene.addModifier(newModifier); - gScene.playSound("item_fanfare"); + await globalScene.addModifier(newModifier); + globalScene.playSound("item_fanfare"); await showEncounterText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name })); await showEncounterDialogue(`${namespace}:victory_2`, `${namespace}:speaker`); - gScene.ui.clearText(); // Clears "Winstrate" title from screen as rewards get animated in + globalScene.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({ guaranteedModifierTypeOptions: [ machoBrace ], fillRemaining: false }); @@ -165,11 +165,11 @@ async function spawnNextTrainerOrEndEncounter() { function endTrainerBattleAndShowDialogue(): Promise { return new Promise(async resolve => { - if (gScene.currentBattle.mysteryEncounter!.enemyPartyConfigs.length === 0) { + if (globalScene.currentBattle.mysteryEncounter!.enemyPartyConfigs.length === 0) { // Battle is over - const trainer = gScene.currentBattle.trainer; + const trainer = globalScene.currentBattle.trainer; if (trainer) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: trainer, x: "+=16", y: "-=16", @@ -177,7 +177,7 @@ function endTrainerBattleAndShowDialogue(): Promise { ease: "Sine.easeInOut", duration: 750, onComplete: () => { - gScene.field.remove(trainer, true); + globalScene.field.remove(trainer, true); } }); } @@ -185,29 +185,29 @@ function endTrainerBattleAndShowDialogue(): Promise { await spawnNextTrainerOrEndEncounter(); resolve(); // Wait for all dialogue/post battle stuff to complete before resolving } else { - gScene.arena.resetArenaEffects(); - const playerField = gScene.getPlayerField(); - playerField.forEach((_, p) => gScene.unshiftPhase(new ReturnPhase(p))); + globalScene.arena.resetArenaEffects(); + const playerField = globalScene.getPlayerField(); + playerField.forEach((_, p) => globalScene.unshiftPhase(new ReturnPhase(p))); - for (const pokemon of gScene.getParty()) { + for (const pokemon of globalScene.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) { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeManualTrigger); } pokemon.resetBattleData(); applyPostBattleInitAbAttrs(PostBattleInitAbAttr, pokemon); } - gScene.unshiftPhase(new ShowTrainerPhase()); + globalScene.unshiftPhase(new ShowTrainerPhase()); // Hide the trainer and init next battle - const trainer = gScene.currentBattle.trainer; + const trainer = globalScene.currentBattle.trainer; // Unassign previous trainer from battle so it isn't destroyed before animation completes - gScene.currentBattle.trainer = null; + globalScene.currentBattle.trainer = null; await spawnNextTrainerOrEndEncounter(); if (trainer) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: trainer, x: "+=16", y: "-=16", @@ -215,7 +215,7 @@ function endTrainerBattleAndShowDialogue(): Promise { ease: "Sine.easeInOut", duration: 750, onComplete: () => { - gScene.field.remove(trainer, true); + globalScene.field.remove(trainer, true); resolve(); } }); diff --git a/src/data/mystery-encounters/encounters/training-session-encounter.ts b/src/data/mystery-encounters/encounters/training-session-encounter.ts index fc0046bf315..a74e1be2d22 100644 --- a/src/data/mystery-encounters/encounters/training-session-encounter.ts +++ b/src/data/mystery-encounters/encounters/training-session-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -71,7 +71,7 @@ export const TrainingSessionEncounter: MysteryEncounter = ], }) .withPreOptionPhase(async (): Promise => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { encounter.misc = { playerPokemon: pokemon, @@ -86,18 +86,18 @@ export const TrainingSessionEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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(gScene.currentBattle.waveIndex / 50), + 2 + Math.floor(globalScene.currentBattle.waveIndex / 50), 5 ); const modifiers = new ModifiersHolder(); const config = getEnemyConfig(playerPokemon, segments, modifiers); - gScene.removePokemonFromPlayerParty(playerPokemon, false); + globalScene.removePokemonFromPlayerParty(playerPokemon, false); const onBeforeRewardsPhase = () => { encounter.setDialogueToken("stat1", "-"); @@ -147,17 +147,17 @@ export const TrainingSessionEncounter: MysteryEncounter = if (improvedCount > 0) { playerPokemon.calculateStats(); - gScene.gameData.updateSpeciesDexIvs(playerPokemon.species.getRootSpeciesId(true), playerPokemon.ivs); - gScene.gameData.setPokemonCaught(playerPokemon, false); + globalScene.gameData.updateSpeciesDexIvs(playerPokemon.species.getRootSpeciesId(true), playerPokemon.ivs); + globalScene.gameData.setPokemonCaught(playerPokemon, false); } // Add pokemon and mods back - gScene.getParty().push(playerPokemon); + globalScene.getParty().push(playerPokemon); for (const mod of modifiers.value) { mod.pokemonId = playerPokemon.id; - gScene.addModifier(mod, true, false, false, true); + globalScene.addModifier(mod, true, false, false, true); } - gScene.updateModifiers(true); + globalScene.updateModifiers(true); queueEncounterMessage(`${namespace}:option.1.finished`); }; @@ -183,13 +183,13 @@ export const TrainingSessionEncounter: MysteryEncounter = }) .withPreOptionPhase(async (): Promise => { // Open menu for selecting pokemon and Nature - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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, gScene.uiTheme), + label: getNatureName(nature, true, true, true, globalScene.uiTheme), handler: () => { // Pokemon and second option selected encounter.setDialogueToken("nature", getNatureName(nature)); @@ -212,29 +212,29 @@ export const TrainingSessionEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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(gScene.currentBattle.waveIndex / 40), 6); + const segments = Math.min(2 + Math.floor(globalScene.currentBattle.waveIndex / 40), 6); const modifiers = new ModifiersHolder(); const config = getEnemyConfig(playerPokemon, segments, modifiers); - gScene.removePokemonFromPlayerParty(playerPokemon, false); + globalScene.removePokemonFromPlayerParty(playerPokemon, false); const onBeforeRewardsPhase = () => { queueEncounterMessage(`${namespace}:option.2.finished`); // Add the pokemon back to party with Nature change playerPokemon.setNature(encounter.misc.chosenNature); - gScene.gameData.setPokemonCaught(playerPokemon, false); + globalScene.gameData.setPokemonCaught(playerPokemon, false); // Add pokemon and modifiers back - gScene.getParty().push(playerPokemon); + globalScene.getParty().push(playerPokemon); for (const mod of modifiers.value) { mod.pokemonId = playerPokemon.id; - gScene.addModifier(mod, true, false, false, true); + globalScene.addModifier(mod, true, false, false, true); } - gScene.updateModifiers(true); + globalScene.updateModifiers(true); }; setEncounterRewards({ fillRemaining: true }, undefined, onBeforeRewardsPhase); @@ -259,7 +259,7 @@ export const TrainingSessionEncounter: MysteryEncounter = }) .withPreOptionPhase(async (): Promise => { // Open menu for selecting pokemon and ability to learn - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const onPokemonSelected = (pokemon: PlayerPokemon) => { // Return the options for ability selection const speciesForm = !!pokemon.getFusionSpeciesForm() @@ -303,19 +303,19 @@ export const TrainingSessionEncounter: MysteryEncounter = return selectPokemonForOption(onPokemonSelected, undefined, selectableFilter); }) .withOptionPhase(async () => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.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(gScene.currentBattle.waveIndex / 30), 6); + const segments = Math.min(2 + Math.floor(globalScene.currentBattle.waveIndex / 30), 6); const modifiers = new ModifiersHolder(); const config = getEnemyConfig(playerPokemon, segments, modifiers); config.pokemonConfigs![0].tags = [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON, ]; - gScene.removePokemonFromPlayerParty(playerPokemon, false); + globalScene.removePokemonFromPlayerParty(playerPokemon, false); const onBeforeRewardsPhase = () => { queueEncounterMessage(`${namespace}:option.3.finished`); @@ -329,8 +329,8 @@ export const TrainingSessionEncounter: MysteryEncounter = const rootFusionSpecies = playerPokemon.fusionSpecies?.getRootSpeciesId(); if (!isNullOrUndefined(rootFusionSpecies) && speciesStarterCosts.hasOwnProperty(rootFusionSpecies) - && !!gScene.gameData.dexData[rootFusionSpecies].caughtAttr) { - gScene.gameData.starterData[rootFusionSpecies].abilityAttr |= playerPokemon.fusionAbilityIndex !== 1 || playerPokemon.fusionSpecies?.ability2 + && !!globalScene.gameData.dexData[rootFusionSpecies].caughtAttr) { + globalScene.gameData.starterData[rootFusionSpecies].abilityAttr |= playerPokemon.fusionAbilityIndex !== 1 || playerPokemon.fusionSpecies?.ability2 ? 1 << playerPokemon.fusionAbilityIndex : AbilityAttr.ABILITY_HIDDEN; } @@ -339,15 +339,15 @@ export const TrainingSessionEncounter: MysteryEncounter = } playerPokemon.calculateStats(); - gScene.gameData.setPokemonCaught(playerPokemon, false); + globalScene.gameData.setPokemonCaught(playerPokemon, false); // Add pokemon and mods back - gScene.getParty().push(playerPokemon); + globalScene.getParty().push(playerPokemon); for (const mod of modifiers.value) { mod.pokemonId = playerPokemon.id; - gScene.addModifier(mod, true, false, false, true); + globalScene.addModifier(mod, true, false, false, true); } - gScene.updateModifiers(true); + globalScene.updateModifiers(true); }; setEncounterRewards({ fillRemaining: true }, undefined, onBeforeRewardsPhase); diff --git a/src/data/mystery-encounters/encounters/trash-to-treasure-encounter.ts b/src/data/mystery-encounters/encounters/trash-to-treasure-encounter.ts index 4bdba3da5f9..cfbfdcce8a6 100644 --- a/src/data/mystery-encounters/encounters/trash-to-treasure-encounter.ts +++ b/src/data/mystery-encounters/encounters/trash-to-treasure-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -59,7 +59,7 @@ export const TrashToTreasureEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculate boss mon const bossSpecies = getPokemonSpecies(Species.GARBODOR); @@ -80,8 +80,8 @@ export const TrashToTreasureEncounter: MysteryEncounter = // Load animations/sfx for Garbodor fight start moves loadCustomMovesForEncounter([ Moves.TOXIC, Moves.AMNESIA ]); - gScene.loadSe("PRSFX- Dig2", "battle_anims", "PRSFX- Dig2.wav"); - gScene.loadSe("PRSFX- Venom Drench", "battle_anims", "PRSFX- Venom Drench.wav"); + globalScene.loadSe("PRSFX- Dig2", "battle_anims", "PRSFX- Dig2.wav"); + globalScene.loadSe("PRSFX- Venom Drench", "battle_anims", "PRSFX- Venom Drench.wav"); encounter.setDialogueToken("costMultiplier", SHOP_ITEM_COST_MULTIPLIER.toString()); @@ -111,8 +111,8 @@ export const TrashToTreasureEncounter: MysteryEncounter = const blackSludge = generateModifierType(modifierTypes.MYSTERY_ENCOUNTER_BLACK_SLUDGE, [ SHOP_ITEM_COST_MULTIPLIER ]); const modifier = blackSludge?.newModifier(); if (modifier) { - await gScene.addModifier(modifier, false, false, false, true); - gScene.playSound("battle_anims/PRSFX- Venom Drench", { volume: 2 }); + await globalScene.addModifier(modifier, false, false, false, true); + globalScene.playSound("battle_anims/PRSFX- Venom Drench", { volume: 2 }); await showEncounterText(i18next.t("battle:rewardGain", { modifierName: modifier.type.name }), null, undefined, true); } @@ -134,11 +134,11 @@ export const TrashToTreasureEncounter: MysteryEncounter = }) .withOptionPhase(async () => { // Investigate garbage, battle Gmax Garbodor - gScene.setFieldScale(0.75); + globalScene.setFieldScale(0.75); await showEncounterText(`${namespace}:option.2.selected_2`); await transitionMysteryEncounterIntroVisuals(); - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; setEncounterRewards({ guaranteedModifierTiers: [ ModifierTier.ROGUE, ModifierTier.ROGUE, ModifierTier.ULTRA, ModifierTier.GREAT ], fillRemaining: true }); encounter.startOfBattleEffects.push( @@ -164,12 +164,12 @@ async function tryApplyDigRewardItems() { const shellBell = generateModifierType(modifierTypes.SHELL_BELL) as PokemonHeldItemModifierType; const leftovers = generateModifierType(modifierTypes.LEFTOVERS) as PokemonHeldItemModifierType; - const party = gScene.getParty(); + const party = globalScene.getParty(); // Iterate over the party until an item was successfully given // First leftovers for (const pokemon of party) { - const heldItems = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const heldItems = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[]; const existingLeftovers = heldItems.find(m => m instanceof TurnHealModifier) as TurnHealModifier; @@ -181,7 +181,7 @@ async function tryApplyDigRewardItems() { // Second leftovers for (const pokemon of party) { - const heldItems = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const heldItems = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[]; const existingLeftovers = heldItems.find(m => m instanceof TurnHealModifier) as TurnHealModifier; @@ -191,12 +191,12 @@ async function tryApplyDigRewardItems() { } } - gScene.playSound("item_fanfare"); + globalScene.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 = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const heldItems = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[]; const existingShellBell = heldItems.find(m => m instanceof HitHealModifier) as HitHealModifier; @@ -208,7 +208,7 @@ async function tryApplyDigRewardItems() { // Second Shell bell for (const pokemon of party) { - const heldItems = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const heldItems = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[]; const existingShellBell = heldItems.find(m => m instanceof HitHealModifier) as HitHealModifier; @@ -218,17 +218,17 @@ async function tryApplyDigRewardItems() { } } - gScene.playSound("item_fanfare"); + globalScene.playSound("item_fanfare"); await showEncounterText(i18next.t("battle:rewardGainCount", { modifierName: shellBell.name, count: 2 }), null, undefined, true); } 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 }); + globalScene.playSound("battle_anims/PRSFX- Dig2"); + globalScene.time.delayedCall(SOUND_EFFECT_WAIT_TIME, () => { + globalScene.playSound("battle_anims/PRSFX- Dig2"); + globalScene.playSound("battle_anims/PRSFX- Venom Drench", { volume: 2 }); }); - gScene.time.delayedCall(SOUND_EFFECT_WAIT_TIME * 2, () => { - gScene.playSound("battle_anims/PRSFX- Dig2"); + globalScene.time.delayedCall(SOUND_EFFECT_WAIT_TIME * 2, () => { + globalScene.playSound("battle_anims/PRSFX- Dig2"); }); } diff --git a/src/data/mystery-encounters/encounters/uncommon-breed-encounter.ts b/src/data/mystery-encounters/encounters/uncommon-breed-encounter.ts index 67793d2a0f3..8aaaf05679a 100644 --- a/src/data/mystery-encounters/encounters/uncommon-breed-encounter.ts +++ b/src/data/mystery-encounters/encounters/uncommon-breed-encounter.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -46,12 +46,12 @@ export const UncommonBreedEncounter: MysteryEncounter = }, ]) .withOnInit(() => { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; // Calculate boss mon // Level equal to 2 below highest party member const level = getHighestLevelPlayerPokemon(false, true).level - 2; - const species = gScene.arena.randomSpecies(gScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(gScene.getParty()), true); + const species = globalScene.arena.randomSpecies(globalScene.currentBattle.waveIndex, level, 0, getPartyLuckValue(globalScene.getParty()), true); const pokemon = new EnemyPokemon(species, level, TrainerSlot.NONE, true); // Pokemon will always have one of its egg moves in its moveset @@ -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)[] = gScene.currentBattle.waveIndex < 50 ? + const statChangesForBattle: (Stat.ATK | Stat.DEF | Stat.SPATK | Stat.SPDEF | Stat.SPD | Stat.ACC | Stat.EVA)[] = globalScene.currentBattle.waveIndex < 50 ? [ Stat.DEF, Stat.SPDEF, Stat.SPD ] : [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ]; @@ -86,7 +86,7 @@ export const UncommonBreedEncounter: MysteryEncounter = tags: [ BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON ], mysteryEncounterBattleEffects: (pokemon: Pokemon) => { queueEncounterMessage(`${namespace}:option.1.stat_boost`); - gScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1)); + globalScene.unshiftPhase(new StatStageChangePhase(pokemon.getBattlerIndex(), true, statChangesForBattle, 1)); } }], }; @@ -105,15 +105,15 @@ export const UncommonBreedEncounter: MysteryEncounter = ]; encounter.setDialogueToken("enemyPokemon", pokemon.getNameToRender()); - gScene.loadSe("PRSFX- Spotlight2", "battle_anims", "PRSFX- Spotlight2.wav"); + globalScene.loadSe("PRSFX- Spotlight2", "battle_anims", "PRSFX- Spotlight2.wav"); return true; }) .withOnVisualsStart(() => { // Animate the pokemon - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const pokemonSprite = encounter.introVisuals!.getSprites(); - gScene.tweens.add({ // Bounce at the end + globalScene.tweens.add({ // Bounce at the end targets: pokemonSprite, duration: 300, ease: "Cubic.easeOut", @@ -122,7 +122,7 @@ export const UncommonBreedEncounter: MysteryEncounter = loop: 1, }); - gScene.time.delayedCall(500, () => gScene.playSound("battle_anims/PRSFX- Spotlight2")); + globalScene.time.delayedCall(500, () => globalScene.playSound("battle_anims/PRSFX- Spotlight2")); return true; }) .setLocalizationKey(`${namespace}`) @@ -141,7 +141,7 @@ export const UncommonBreedEncounter: MysteryEncounter = }, async () => { // Pick battle - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const eggMove = encounter.misc.eggMove; if (!isNullOrUndefined(eggMove)) { @@ -182,20 +182,20 @@ export const UncommonBreedEncounter: MysteryEncounter = // Remove 4 random berries from player's party // Get all player berry items, remove from party, and store reference - const berryItems: BerryModifier[] = gScene.findModifiers(m => m instanceof BerryModifier) as BerryModifier[]; + const berryItems: BerryModifier[] = globalScene.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) { - gScene.removeModifier(randBerry); + globalScene.removeModifier(randBerry); berryItems.splice(index, 1); } } - await gScene.updateModifiers(true, true); + await globalScene.updateModifiers(true, true); // Pokemon joins the team, with 2 egg moves - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const pokemon = encounter.misc.pokemon; // Give 1 additional egg move @@ -224,7 +224,7 @@ export const UncommonBreedEncounter: MysteryEncounter = .withOptionPhase(async () => { // Attract the pokemon with a move // Pokemon joins the team, with 2 egg moves and IVs rolled an additional time - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; const pokemon = encounter.misc.pokemon; // Give 1 additional egg move diff --git a/src/data/mystery-encounters/encounters/weird-dream-encounter.ts b/src/data/mystery-encounters/encounters/weird-dream-encounter.ts index 2555a16e00a..ea8ec1443f8 100644 --- a/src/data/mystery-encounters/encounters/weird-dream-encounter.ts +++ b/src/data/mystery-encounters/encounters/weird-dream-encounter.ts @@ -1,7 +1,7 @@ import { Type } from "#app/data/type"; import { MysteryEncounterType } from "#enums/mystery-encounter-type"; import { Species } from "#enums/species"; -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -139,12 +139,12 @@ export const WeirdDreamEncounter: MysteryEncounter = .withDescription(`${namespace}:description`) .withQuery(`${namespace}:query`) .withOnInit(() => { - gScene.loadBgm("mystery_encounter_weird_dream", "mystery_encounter_weird_dream.mp3"); + globalScene.loadBgm("mystery_encounter_weird_dream", "mystery_encounter_weird_dream.mp3"); // Calculate all the newly transformed Pokemon and begin asset load const teamTransformations = getTeamTransformations(); const loadAssets = teamTransformations.map(t => (t.newPokemon as PlayerPokemon).loadAssets()); - gScene.currentBattle.mysteryEncounter!.misc = { + globalScene.currentBattle.mysteryEncounter!.misc = { teamTransformations, loadAssets }; @@ -152,7 +152,7 @@ export const WeirdDreamEncounter: MysteryEncounter = return true; }) .withOnVisualsStart(() => { - gScene.fadeAndSwitchBgm("mystery_encounter_weird_dream"); + globalScene.fadeAndSwitchBgm("mystery_encounter_weird_dream"); return true; }) .withOption( @@ -170,13 +170,13 @@ export const WeirdDreamEncounter: MysteryEncounter = }) .withPreOptionPhase(async () => { // Play the animation as the player goes through the dialogue - gScene.time.delayedCall(1000, () => { + globalScene.time.delayedCall(1000, () => { doShowDreamBackground(); }); - for (const transformation of gScene.currentBattle.mysteryEncounter!.misc.teamTransformations) { - gScene.removePokemonFromPlayerParty(transformation.previousPokemon, false); - gScene.getParty().push(transformation.newPokemon); + for (const transformation of globalScene.currentBattle.mysteryEncounter!.misc.teamTransformations) { + globalScene.removePokemonFromPlayerParty(transformation.previousPokemon, false); + globalScene.getParty().push(transformation.newPokemon); } }) .withOptionPhase(async () => { @@ -185,8 +185,8 @@ export const WeirdDreamEncounter: MysteryEncounter = // Change the entire player's party // Wait for all new Pokemon assets to be loaded before showing transformation animations - await Promise.all(gScene.currentBattle.mysteryEncounter!.misc.loadAssets); - const transformations = gScene.currentBattle.mysteryEncounter!.misc.teamTransformations; + await Promise.all(globalScene.currentBattle.mysteryEncounter!.misc.loadAssets); + const transformations = globalScene.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 @@ -225,7 +225,7 @@ export const WeirdDreamEncounter: MysteryEncounter = }, async () => { // Battle your "future" team for some item rewards - const transformations: PokemonTransformation[] = gScene.currentBattle.mysteryEncounter!.misc.teamTransformations; + const transformations: PokemonTransformation[] = globalScene.currentBattle.mysteryEncounter!.misc.teamTransformations; // Uses the pokemon that player's party would have transformed into const enemyPokemonConfigs: EnemyPokemonConfig[] = []; @@ -268,7 +268,7 @@ export const WeirdDreamEncounter: MysteryEncounter = enemyPokemonConfigs.push(enemyConfig); } - const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET; + const genderIndex = globalScene.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 = gScene.getParty().filter(p => !p.passive); + const passiveDisabledPokemon = globalScene.getParty().filter(p => !p.passive); if (passiveDisabledPokemon?.length > 0) { const enablePassiveMon = passiveDisabledPokemon[randSeedInt(passiveDisabledPokemon.length)]; enablePassiveMon.passive = true; @@ -306,7 +306,7 @@ export const WeirdDreamEncounter: MysteryEncounter = }, async () => { // Leave, reduce party levels by 10% - for (const pokemon of gScene.getParty()) { + for (const pokemon of globalScene.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; @@ -329,7 +329,7 @@ interface PokemonTransformation { } function getTeamTransformations(): PokemonTransformation[] { - const party = gScene.getParty(); + const party = globalScene.getParty(); // Removes all pokemon from the party const alreadyUsedSpecies: PokemonSpecies[] = party.map(p => p.species); const pokemonTransformations: PokemonTransformation[] = party.map(p => { @@ -378,7 +378,7 @@ function getTeamTransformations(): PokemonTransformation[] { for (const transformation of pokemonTransformations) { const newAbilityIndex = randSeedInt(transformation.newSpecies.getAbilityCount()); - transformation.newPokemon = gScene.addPlayerPokemon(transformation.newSpecies, transformation.previousPokemon.level, newAbilityIndex, undefined); + transformation.newPokemon = globalScene.addPlayerPokemon(transformation.newSpecies, transformation.previousPokemon.level, newAbilityIndex, undefined); } return pokemonTransformations; @@ -398,17 +398,17 @@ async function doNewTeamPostProcess(transformations: PokemonTransformation[]) { // Copy old items to new pokemon for (const item of transformation.heldItems) { item.pokemonId = newPokemon.id; - await gScene.addModifier(item, false, false, false, true); + await globalScene.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(gScene.getParty(), [ OLD_GATEAU_STATS_UP, stats ]) + .generateType(globalScene.getParty(), [ OLD_GATEAU_STATS_UP, stats ]) ?.withIdFromFunc(modifierTypes.MYSTERY_ENCOUNTER_OLD_GATEAU); const modifier = modType?.newModifier(newPokemon); if (modifier) { - await gScene.addModifier(modifier, false, false, false, true); + await globalScene.addModifier(modifier, false, false, false, true); } } @@ -417,7 +417,7 @@ async function doNewTeamPostProcess(transformations: PokemonTransformation[]) { } // One random pokemon will get its passive unlocked - const passiveDisabledPokemon = gScene.getParty().filter(p => !p.passive); + const passiveDisabledPokemon = globalScene.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(transformations: PokemonTransformation[]) { // If at least one new starter was unlocked, play 1 fanfare if (atLeastOneNewStarter) { - gScene.playSound("level_up_fanfare"); + globalScene.playSound("level_up_fanfare"); } } @@ -446,7 +446,7 @@ async function postProcessTransformedPokemon(previousPokemon: PlayerPokemon, new const hiddenIndex = newPokemon.species.ability2 ? 2 : 1; if (newPokemon.abilityIndex < hiddenIndex) { const hiddenAbilityChance = new IntegerHolder(256); - gScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); + globalScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); const hasHiddenAbility = !randSeedInt(hiddenAbilityChance.value); @@ -468,23 +468,23 @@ async function postProcessTransformedPokemon(previousPokemon: PlayerPokemon, new // 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) { - gScene.validateAchv(achvs.HIDDEN_ABILITY); + globalScene.validateAchv(achvs.HIDDEN_ABILITY); } if (newPokemon.species.subLegendary) { - gScene.validateAchv(achvs.CATCH_SUB_LEGENDARY); + globalScene.validateAchv(achvs.CATCH_SUB_LEGENDARY); } if (newPokemon.species.legendary) { - gScene.validateAchv(achvs.CATCH_LEGENDARY); + globalScene.validateAchv(achvs.CATCH_LEGENDARY); } if (newPokemon.species.mythical) { - gScene.validateAchv(achvs.CATCH_MYTHICAL); + globalScene.validateAchv(achvs.CATCH_MYTHICAL); } - gScene.gameData.updateSpeciesDexIvs(newPokemon.species.getRootSpeciesId(true), newPokemon.ivs); - const newStarterUnlocked = await gScene.gameData.setPokemonCaught(newPokemon, true, false, false); + globalScene.gameData.updateSpeciesDexIvs(newPokemon.species.getRootSpeciesId(true), newPokemon.ivs); + const newStarterUnlocked = await globalScene.gameData.setPokemonCaught(newPokemon, true, false, false); if (newStarterUnlocked) { isNewStarter = true; await showEncounterText(i18next.t("battle:addedAsAStarter", { pokemonName: getPokemonSpecies(speciesRootForm).getName() })); @@ -503,8 +503,8 @@ async function postProcessTransformedPokemon(previousPokemon: PlayerPokemon, new }); // For pokemon that the player owns (including ones just caught), gain a candy - if (!forBattle && !!gScene.gameData.dexData[speciesRootForm].caughtAttr) { - gScene.gameData.addStarterCandy(getPokemonSpecies(speciesRootForm), 1); + if (!forBattle && !!globalScene.gameData.dexData[speciesRootForm].caughtAttr) { + globalScene.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 @@ -597,30 +597,30 @@ function getTransformedSpecies(originalBst: number, bstSearchRange: [number, num } function doShowDreamBackground() { - const transformationContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); + const transformationContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); transformationContainer.name = "Dream Background"; // In case it takes a bit for video to load - const transformationStaticBg = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0); + const transformationStaticBg = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6, 0); transformationStaticBg.setName("Black Background"); transformationStaticBg.setOrigin(0, 0); transformationContainer.add(transformationStaticBg); transformationStaticBg.setVisible(true); - const transformationVideoBg: Phaser.GameObjects.Video = gScene.add.video(0, 0, "evo_bg").stop(); + const transformationVideoBg: Phaser.GameObjects.Video = globalScene.add.video(0, 0, "evo_bg").stop(); transformationVideoBg.setLoop(true); transformationVideoBg.setOrigin(0, 0); transformationVideoBg.setScale(0.4359673025); transformationContainer.add(transformationVideoBg); - gScene.fieldUI.add(transformationContainer); - gScene.fieldUI.bringToTop(transformationContainer); + globalScene.fieldUI.add(transformationContainer); + globalScene.fieldUI.bringToTop(transformationContainer); transformationVideoBg.play(); transformationContainer.setVisible(true); transformationContainer.alpha = 0; - gScene.tweens.add({ + globalScene.tweens.add({ targets: transformationContainer, alpha: 1, duration: 3000, @@ -629,15 +629,15 @@ function doShowDreamBackground() { } function doHideDreamBackground() { - const transformationContainer = gScene.fieldUI.getByName("Dream Background"); + const transformationContainer = globalScene.fieldUI.getByName("Dream Background"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: transformationContainer, alpha: 0, duration: 3000, ease: "Sine.easeInOut", onComplete: () => { - gScene.fieldUI.remove(transformationContainer, true); + globalScene.fieldUI.remove(transformationContainer, true); } }); } @@ -647,7 +647,7 @@ function doSideBySideTransformations(transformations: PokemonTransformation[]) { const allTransformationPromises: Promise[] = []; for (let i = 0; i < 3; i++) { const delay = i * 4000; - gScene.time.delayedCall(delay, () => { + globalScene.time.delayedCall(delay, () => { const transformation = transformations[i]; const pokemon1 = transformation.previousPokemon; const pokemon2 = transformation.newPokemon; @@ -711,8 +711,8 @@ async function addEggMoveToNewPokemonMoveset(newPokemon: PlayerPokemon, speciesR } // For pokemon that the player owns (including ones just caught), unlock the egg move - if (!forBattle && !isNullOrUndefined(randomEggMoveIndex) && !!gScene.gameData.dexData[speciesRootForm].caughtAttr) { - await gScene.gameData.setEggMoveUnlocked(getPokemonSpecies(speciesRootForm), randomEggMoveIndex, true); + if (!forBattle && !isNullOrUndefined(randomEggMoveIndex) && !!globalScene.gameData.dexData[speciesRootForm].caughtAttr) { + await globalScene.gameData.setEggMoveUnlocked(getPokemonSpecies(speciesRootForm), randomEggMoveIndex, true); } } } diff --git a/src/data/mystery-encounters/mystery-encounter-option.ts b/src/data/mystery-encounters/mystery-encounter-option.ts index 97f4a9d5b9b..29e5c62674e 100644 --- a/src/data/mystery-encounters/mystery-encounter-option.ts +++ b/src/data/mystery-encounters/mystery-encounter-option.ts @@ -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 { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -88,7 +88,7 @@ export default class MysteryEncounterOption implements IMysteryEncounterOption { * @param pokemon */ pokemonMeetsPrimaryRequirements(pokemon: Pokemon): boolean { - return !this.primaryPokemonRequirements.some(req => !req.queryParty(gScene.getParty()).map(p => p.id).includes(pokemon.id)); + return !this.primaryPokemonRequirements.some(req => !req.queryParty(globalScene.getParty()).map(p => p.id).includes(pokemon.id)); } /** @@ -102,10 +102,10 @@ export default class MysteryEncounterOption implements IMysteryEncounterOption { if (!this.primaryPokemonRequirements || this.primaryPokemonRequirements.length === 0) { return true; } - let qualified: PlayerPokemon[] = gScene.getParty(); + let qualified: PlayerPokemon[] = globalScene.getParty(); for (const req of this.primaryPokemonRequirements) { if (req.meetsRequirement()) { - const queryParty = req.queryParty(gScene.getParty()); + const queryParty = req.queryParty(globalScene.getParty()); qualified = qualified.filter(pkmn => queryParty.includes(pkmn)); } else { this.primaryPokemon = undefined; @@ -162,10 +162,10 @@ export default class MysteryEncounterOption implements IMysteryEncounterOption { return true; } - let qualified: PlayerPokemon[] = gScene.getParty(); + let qualified: PlayerPokemon[] = globalScene.getParty(); for (const req of this.secondaryPokemonRequirements) { if (req.meetsRequirement()) { - const queryParty = req.queryParty(gScene.getParty()); + const queryParty = req.queryParty(globalScene.getParty()); qualified = qualified.filter(pkmn => queryParty.includes(pkmn)); } else { this.secondaryPokemon = []; diff --git a/src/data/mystery-encounters/mystery-encounter-requirements.ts b/src/data/mystery-encounters/mystery-encounter-requirements.ts index 86dff20d4fa..142f15d9d62 100644 --- a/src/data/mystery-encounters/mystery-encounter-requirements.ts +++ b/src/data/mystery-encounters/mystery-encounter-requirements.ts @@ -1,5 +1,5 @@ import { PlayerPokemon } from "#app/field/pokemon"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { isNullOrUndefined } from "#app/utils"; import { Abilities } from "#enums/abilities"; import { Moves } from "#enums/moves"; @@ -201,11 +201,11 @@ export class PreviousEncounterRequirement extends EncounterSceneRequirement { } override meetsRequirement(): boolean { - return gScene.mysteryEncounterSaveData.encounteredEvents.some(e => e.type === this.previousEncounterRequirement); + return globalScene.mysteryEncounterSaveData.encounteredEvents.some(e => e.type === this.previousEncounterRequirement); } override getDialogueToken(pokemon?: PlayerPokemon): [string, string] { - return [ "previousEncounter", gScene.mysteryEncounterSaveData.encounteredEvents.find(e => e.type === this.previousEncounterRequirement)?.[0].toString() ?? "" ]; + return [ "previousEncounter", globalScene.mysteryEncounterSaveData.encounteredEvents.find(e => e.type === this.previousEncounterRequirement)?.[0].toString() ?? "" ]; } } @@ -224,7 +224,7 @@ export class WaveRangeRequirement extends EncounterSceneRequirement { override meetsRequirement(): boolean { if (!isNullOrUndefined(this.waveRange) && this.waveRange[0] <= this.waveRange[1]) { - const waveIndex = gScene.currentBattle.waveIndex; + const waveIndex = globalScene.currentBattle.waveIndex; if (waveIndex >= 0 && (this.waveRange[0] >= 0 && this.waveRange[0] > waveIndex) || (this.waveRange[1] >= 0 && this.waveRange[1] < waveIndex)) { return false; } @@ -233,7 +233,7 @@ export class WaveRangeRequirement extends EncounterSceneRequirement { } override getDialogueToken(pokemon?: PlayerPokemon): [string, string] { - return [ "waveIndex", gScene.currentBattle.waveIndex.toString() ]; + return [ "waveIndex", globalScene.currentBattle.waveIndex.toString() ]; } } @@ -258,11 +258,11 @@ export class WaveModulusRequirement extends EncounterSceneRequirement { } override meetsRequirement(): boolean { - return this.waveModuli.includes(gScene.currentBattle.waveIndex % this.modulusValue); + return this.waveModuli.includes(globalScene.currentBattle.waveIndex % this.modulusValue); } override getDialogueToken(pokemon?: PlayerPokemon): [string, string] { - return [ "waveIndex", gScene.currentBattle.waveIndex.toString() ]; + return [ "waveIndex", globalScene.currentBattle.waveIndex.toString() ]; } } @@ -275,7 +275,7 @@ export class TimeOfDayRequirement extends EncounterSceneRequirement { } override meetsRequirement(): boolean { - const timeOfDay = gScene.arena?.getTimeOfDay(); + const timeOfDay = globalScene.arena?.getTimeOfDay(); if (!isNullOrUndefined(timeOfDay) && this.requiredTimeOfDay?.length > 0 && !this.requiredTimeOfDay.includes(timeOfDay)) { return false; } @@ -284,7 +284,7 @@ export class TimeOfDayRequirement extends EncounterSceneRequirement { } override getDialogueToken(pokemon?: PlayerPokemon): [string, string] { - return [ "timeOfDay", TimeOfDay[gScene.arena.getTimeOfDay()].toLocaleLowerCase() ]; + return [ "timeOfDay", TimeOfDay[globalScene.arena.getTimeOfDay()].toLocaleLowerCase() ]; } } @@ -297,7 +297,7 @@ export class WeatherRequirement extends EncounterSceneRequirement { } override meetsRequirement(): boolean { - const currentWeather = gScene.arena.weather?.weatherType; + const currentWeather = globalScene.arena.weather?.weatherType; if (!isNullOrUndefined(currentWeather) && this.requiredWeather?.length > 0 && !this.requiredWeather.includes(currentWeather!)) { return false; } @@ -306,7 +306,7 @@ export class WeatherRequirement extends EncounterSceneRequirement { } override getDialogueToken(pokemon?: PlayerPokemon): [string, string] { - const currentWeather = gScene.arena.weather?.weatherType; + const currentWeather = globalScene.arena.weather?.weatherType; let token = ""; if (!isNullOrUndefined(currentWeather)) { token = WeatherType[currentWeather].replace("_", " ").toLocaleLowerCase(); @@ -333,7 +333,7 @@ export class PartySizeRequirement extends EncounterSceneRequirement { override meetsRequirement(): boolean { if (!isNullOrUndefined(this.partySizeRange) && this.partySizeRange[0] <= this.partySizeRange[1]) { - const partySize = this.excludeDisallowedPokemon ? gScene.getParty().filter(p => p.isAllowedInBattle()).length : gScene.getParty().length; + const partySize = this.excludeDisallowedPokemon ? globalScene.getParty().filter(p => p.isAllowedInBattle()).length : globalScene.getParty().length; if (partySize >= 0 && (this.partySizeRange[0] >= 0 && this.partySizeRange[0] > partySize) || (this.partySizeRange[1] >= 0 && this.partySizeRange[1] < partySize)) { return false; } @@ -343,7 +343,7 @@ export class PartySizeRequirement extends EncounterSceneRequirement { } override getDialogueToken(pokemon?: PlayerPokemon): [string, string] { - return [ "partySize", gScene.getParty().length.toString() ]; + return [ "partySize", globalScene.getParty().length.toString() ]; } } @@ -358,13 +358,13 @@ export class PersistentModifierRequirement extends EncounterSceneRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredHeldItemModifiers?.length < 0) { return false; } let modifierCount = 0; this.requiredHeldItemModifiers.forEach(modifier => { - const matchingMods = gScene.findModifiers(m => m.constructor.name === modifier); + const matchingMods = globalScene.findModifiers(m => m.constructor.name === modifier); if (matchingMods?.length > 0) { matchingMods.forEach(matchingMod => { modifierCount += matchingMod.stackCount; @@ -391,19 +391,19 @@ export class MoneyRequirement extends EncounterSceneRequirement { } override meetsRequirement(): boolean { - const money = gScene.money; + const money = globalScene.money; if (isNullOrUndefined(money)) { return false; } if (this.scalingMultiplier > 0) { - this.requiredMoney = gScene.getWaveMoneyAmount(this.scalingMultiplier); + this.requiredMoney = globalScene.getWaveMoneyAmount(this.scalingMultiplier); } return !(this.requiredMoney > 0 && this.requiredMoney > money); } override getDialogueToken(pokemon?: PlayerPokemon): [string, string] { - const value = this.scalingMultiplier > 0 ? gScene.getWaveMoneyAmount(this.scalingMultiplier).toString() : this.requiredMoney.toString(); + const value = this.scalingMultiplier > 0 ? globalScene.getWaveMoneyAmount(this.scalingMultiplier).toString() : this.requiredMoney.toString(); return [ "money", value ]; } } @@ -421,7 +421,7 @@ export class SpeciesRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredSpecies?.length < 0) { return false; } @@ -459,7 +459,7 @@ export class NatureRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredNature?.length < 0) { return false; } @@ -498,7 +498,7 @@ export class TypeRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - let partyPokemon = gScene.getParty(); + let partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon)) { return false; @@ -545,7 +545,7 @@ export class MoveRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) { return false; } @@ -594,7 +594,7 @@ export class CompatibleMoveRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) { return false; } @@ -635,7 +635,7 @@ export class AbilityRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredAbilities?.length < 0) { return false; } @@ -677,7 +677,7 @@ export class StatusEffectRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredStatusEffect?.length < 0) { return false; } @@ -746,7 +746,7 @@ export class CanFormChangeWithItemRequirement extends EncounterPokemonRequiremen } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredFormChangeItem?.length < 0) { return false; } @@ -798,7 +798,7 @@ export class CanEvolveWithItemRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon) || this.requiredEvolutionItem?.length < 0) { return false; } @@ -849,7 +849,7 @@ export class HeldItemRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon)) { return false; } @@ -900,7 +900,7 @@ export class AttackTypeBoosterHeldItemTypeRequirement extends EncounterPokemonRe } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); if (isNullOrUndefined(partyPokemon)) { return false; } @@ -957,7 +957,7 @@ export class LevelRequirement extends EncounterPokemonRequirement { override meetsRequirement(): boolean { // Party Pokemon inside required level range if (!isNullOrUndefined(this.requiredLevelRange) && this.requiredLevelRange[0] <= this.requiredLevelRange[1]) { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); const pokemonInRange = this.queryParty(partyPokemon); if (pokemonInRange.length < this.minNumberOfPokemon) { return false; @@ -995,7 +995,7 @@ export class FriendshipRequirement extends EncounterPokemonRequirement { override meetsRequirement(): boolean { // Party Pokemon inside required friendship range if (!isNullOrUndefined(this.requiredFriendshipRange) && this.requiredFriendshipRange[0] <= this.requiredFriendshipRange[1]) { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); const pokemonInRange = this.queryParty(partyPokemon); if (pokemonInRange.length < this.minNumberOfPokemon) { return false; @@ -1038,7 +1038,7 @@ export class HealthRatioRequirement extends EncounterPokemonRequirement { override meetsRequirement(): boolean { // Party Pokemon's health inside required health range if (!isNullOrUndefined(this.requiredHealthRange) && this.requiredHealthRange[0] <= this.requiredHealthRange[1]) { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); const pokemonInRange = this.queryParty(partyPokemon); if (pokemonInRange.length < this.minNumberOfPokemon) { return false; @@ -1082,7 +1082,7 @@ export class WeightRequirement extends EncounterPokemonRequirement { override meetsRequirement(): boolean { // Party Pokemon's weight inside required weight range if (!isNullOrUndefined(this.requiredWeightRange) && this.requiredWeightRange[0] <= this.requiredWeightRange[1]) { - const partyPokemon = gScene.getParty(); + const partyPokemon = globalScene.getParty(); const pokemonInRange = this.queryParty(partyPokemon); if (pokemonInRange.length < this.minNumberOfPokemon) { return false; diff --git a/src/data/mystery-encounters/mystery-encounter.ts b/src/data/mystery-encounters/mystery-encounter.ts index 2f3a3709d6e..72029f7e5cd 100644 --- a/src/data/mystery-encounters/mystery-encounter.ts +++ b/src/data/mystery-encounters/mystery-encounter.ts @@ -15,7 +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"; +import { globalScene } from "#app/battle-scene"; export interface EncounterStartOfBattleEffect { sourcePokemon?: Pokemon; @@ -314,7 +314,7 @@ export default class MysteryEncounter implements IMysteryEncounter { * @param pokemon */ pokemonMeetsPrimaryRequirements(pokemon: Pokemon): boolean { - return !this.primaryPokemonRequirements.some(req => !req.queryParty(gScene.getParty()).map(p => p.id).includes(pokemon.id)); + return !this.primaryPokemonRequirements.some(req => !req.queryParty(globalScene.getParty()).map(p => p.id).includes(pokemon.id)); } /** @@ -326,18 +326,18 @@ export default class MysteryEncounter implements IMysteryEncounter { */ private meetsPrimaryRequirementAndPrimaryPokemonSelected(): boolean { if (!this.primaryPokemonRequirements || this.primaryPokemonRequirements.length === 0) { - const activeMon = gScene.getParty().filter(p => p.isActive(true)); + const activeMon = globalScene.getParty().filter(p => p.isActive(true)); if (activeMon.length > 0) { this.primaryPokemon = activeMon[0]; } else { - this.primaryPokemon = gScene.getParty().filter(p => p.isAllowedInBattle())[0]; + this.primaryPokemon = globalScene.getParty().filter(p => p.isAllowedInBattle())[0]; } return true; } - let qualified: PlayerPokemon[] = gScene.getParty(); + let qualified: PlayerPokemon[] = globalScene.getParty(); for (const req of this.primaryPokemonRequirements) { if (req.meetsRequirement()) { - qualified = qualified.filter(pkmn => req.queryParty(gScene.getParty()).includes(pkmn)); + qualified = qualified.filter(pkmn => req.queryParty(globalScene.getParty()).includes(pkmn)); } else { this.primaryPokemon = undefined; return false; @@ -394,10 +394,10 @@ export default class MysteryEncounter implements IMysteryEncounter { return true; } - let qualified: PlayerPokemon[] = gScene.getParty(); + let qualified: PlayerPokemon[] = globalScene.getParty(); for (const req of this.secondaryPokemonRequirements) { if (req.meetsRequirement()) { - qualified = qualified.filter(pkmn => req.queryParty(gScene.getParty()).includes(pkmn)); + qualified = qualified.filter(pkmn => req.queryParty(globalScene.getParty()).includes(pkmn)); } else { this.secondaryPokemon = []; return false; @@ -521,7 +521,7 @@ export default class MysteryEncounter implements IMysteryEncounter { * @param scene */ updateSeedOffset() { - const currentOffset = this.seedOffset ?? gScene.currentBattle.waveIndex * 1000; + const currentOffset = this.seedOffset ?? globalScene.currentBattle.waveIndex * 1000; this.seedOffset = currentOffset + 512; } } diff --git a/src/data/mystery-encounters/requirements/can-learn-move-requirement.ts b/src/data/mystery-encounters/requirements/can-learn-move-requirement.ts index 2b8e9cfc5d7..7a07a28f6be 100644 --- a/src/data/mystery-encounters/requirements/can-learn-move-requirement.ts +++ b/src/data/mystery-encounters/requirements/can-learn-move-requirement.ts @@ -2,7 +2,7 @@ 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"; +import { globalScene } from "#app/battle-scene"; /** * {@linkcode CanLearnMoveRequirement} options @@ -39,7 +39,7 @@ export class CanLearnMoveRequirement extends EncounterPokemonRequirement { } override meetsRequirement(): boolean { - const partyPokemon = gScene.getParty().filter((pkm) => (this.includeFainted ? pkm.isAllowed() : pkm.isAllowedInBattle())); + const partyPokemon = globalScene.getParty().filter((pkm) => (this.includeFainted ? pkm.isAllowed() : pkm.isAllowedInBattle())); if (isNullOrUndefined(partyPokemon) || this.requiredMoves?.length < 0) { return false; diff --git a/src/data/mystery-encounters/utils/encounter-dialogue-utils.ts b/src/data/mystery-encounters/utils/encounter-dialogue-utils.ts index 12d067d79f5..41ffa4057ed 100644 --- a/src/data/mystery-encounters/utils/encounter-dialogue-utils.ts +++ b/src/data/mystery-encounters/utils/encounter-dialogue-utils.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { getTextWithColors, TextStyle } from "#app/ui/text"; import { UiTheme } from "#enums/ui-theme"; import { isNullOrUndefined } from "#app/utils"; @@ -29,12 +29,12 @@ export function getEncounterText(keyOrString?: string, primaryStyle?: TextStyle, } /** - * Helper function to inject {@linkcode gScene.currentBattle.mysteryEncounter.dialogueTokens} into a given content string + * Helper function to inject {@linkcode globalScene.currentBattle.mysteryEncounter.dialogueTokens} into a given content string * @param scene * @param keyOrString */ function getTextWithDialogueTokens(keyOrString: string): string | null { - const tokens = gScene.currentBattle?.mysteryEncounter?.dialogueTokens; + const tokens = globalScene.currentBattle?.mysteryEncounter?.dialogueTokens; if (i18next.exists(keyOrString, tokens)) { return i18next.t(keyOrString, tokens) as string; @@ -50,7 +50,7 @@ function getTextWithDialogueTokens(keyOrString: string): string | null { */ export function queueEncounterMessage(contentKey: string): void { const text: string | null = getEncounterText(contentKey); - gScene.queueMessage(text ?? "", null, true); + globalScene.queueMessage(text ?? "", null, true); } /** @@ -65,7 +65,7 @@ export function queueEncounterMessage(contentKey: string): void { export function showEncounterText(contentKey: string, delay: number | null = null, callbackDelay: number = 0, prompt: boolean = true, promptDelay: number | null = null): Promise { return new Promise(resolve => { const text: string | null = getEncounterText(contentKey); - gScene.ui.showText(text ?? "", delay, () => resolve(), callbackDelay, prompt, promptDelay); + globalScene.ui.showText(text ?? "", delay, () => resolve(), callbackDelay, prompt, promptDelay); }); } @@ -81,6 +81,6 @@ export function showEncounterDialogue(textContentKey: string, speakerContentKey: return new Promise(resolve => { const text: string | null = getEncounterText(textContentKey); const speaker: string | null = getEncounterText(speakerContentKey); - gScene.ui.showDialogue(text ?? "", speaker ?? "", delay, () => resolve(), callbackDelay); + globalScene.ui.showDialogue(text ?? "", speaker ?? "", delay, () => resolve(), callbackDelay); }); } diff --git a/src/data/mystery-encounters/utils/encounter-phase-utils.ts b/src/data/mystery-encounters/utils/encounter-phase-utils.ts index 79c54f0c6b1..d79a81664f6 100644 --- a/src/data/mystery-encounters/utils/encounter-phase-utils.ts +++ b/src/data/mystery-encounters/utils/encounter-phase-utils.ts @@ -36,33 +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"; +import { globalScene } from "#app/battle-scene"; /** * Animates exclamation sprite over trainer's head at start of encounter * @param scene */ export function doTrainerExclamation() { - const exclamationSprite = gScene.add.sprite(0, 0, "encounter_exclaim"); + const exclamationSprite = globalScene.add.sprite(0, 0, "encounter_exclaim"); exclamationSprite.setName("exclamation"); - gScene.field.add(exclamationSprite); - gScene.field.moveTo(exclamationSprite, gScene.field.getAll().length - 1); + globalScene.field.add(exclamationSprite); + globalScene.field.moveTo(exclamationSprite, globalScene.field.getAll().length - 1); exclamationSprite.setVisible(true); exclamationSprite.setPosition(110, 68); - gScene.tweens.add({ + globalScene.tweens.add({ targets: exclamationSprite, y: "-=25", ease: "Cubic.easeOut", duration: 300, yoyo: true, onComplete: () => { - gScene.time.delayedCall(800, () => { - gScene.field.remove(exclamationSprite, true); + globalScene.time.delayedCall(800, () => { + globalScene.field.remove(exclamationSprite, true); }); } }); - gScene.playSound("battle_anims/GEN8- Exclaim", { volume: 0.7 }); + globalScene.playSound("battle_anims/GEN8- Exclaim", { volume: 0.7 }); } export interface EnemyPokemonConfig { @@ -120,7 +120,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): const loaded: boolean = false; const loadEnemyAssets: Promise[] = []; - const battle: Battle = gScene.currentBattle; + const battle: Battle = globalScene.currentBattle; let doubleBattle: boolean = partyConfig?.doubleBattle ?? false; @@ -129,10 +129,10 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): const partyTrainerConfig = partyConfig?.trainerConfig; let trainerConfig: TrainerConfig; if (!isNullOrUndefined(trainerType) || partyTrainerConfig) { - gScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.TRAINER_BATTLE; - if (gScene.currentBattle.trainer) { - gScene.currentBattle.trainer.setVisible(false); - gScene.currentBattle.trainer.destroy(); + globalScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.TRAINER_BATTLE; + if (globalScene.currentBattle.trainer) { + globalScene.currentBattle.trainer.setVisible(false); + globalScene.currentBattle.trainer.destroy(); } trainerConfig = partyTrainerConfig ? partyTrainerConfig : trainerConfigs[trainerType!]; @@ -143,20 +143,20 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): const newTrainer = new Trainer(trainerConfig.trainerType, doubleTrainer ? TrainerVariant.DOUBLE : trainerFemale ? TrainerVariant.FEMALE : TrainerVariant.DEFAULT, undefined, undefined, undefined, trainerConfig); newTrainer.x += 300; newTrainer.setVisible(false); - gScene.field.add(newTrainer); - gScene.currentBattle.trainer = newTrainer; + globalScene.field.add(newTrainer); + globalScene.currentBattle.trainer = newTrainer; loadEnemyAssets.push(newTrainer.loadAssets().then(() => newTrainer.initSprite())); - battle.enemyLevels = gScene.currentBattle.trainer.getPartyLevels(gScene.currentBattle.waveIndex); + battle.enemyLevels = globalScene.currentBattle.trainer.getPartyLevels(globalScene.currentBattle.waveIndex); } else { // Wild - gScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.WILD_BATTLE; + globalScene.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(() => gScene.currentBattle.getLevelForWave()); + battle.enemyLevels = new Array(numEnemies).fill(null).map(() => globalScene.currentBattle.getLevelForWave()); } - gScene.getEnemyParty().forEach(enemyPokemon => { - gScene.field.remove(enemyPokemon, true); + globalScene.getEnemyParty().forEach(enemyPokemon => { + globalScene.field.remove(enemyPokemon, true); }); battle.enemyParty = []; battle.double = doubleBattle; @@ -167,7 +167,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): // 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((gScene.currentBattle.waveIndex / 10) * mult), 0); + const additive = Math.max(Math.round((globalScene.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(partyConfig: EnemyPartyConfig): dataSource = config.dataSource; enemySpecies = config.species; isBoss = config.isBoss; - battle.enemyParty[e] = gScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.TRAINER, isBoss, dataSource); + battle.enemyParty[e] = globalScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.TRAINER, isBoss, dataSource); } else { battle.enemyParty[e] = battle.trainer.genPartyMember(e); } @@ -195,17 +195,17 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): enemySpecies = config.species; isBoss = config.isBoss; if (isBoss) { - gScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.BOSS_BATTLE; + globalScene.currentBattle.mysteryEncounter!.encounterMode = MysteryEncounterMode.BOSS_BATTLE; } } else { - enemySpecies = gScene.randomSpecies(battle.waveIndex, level, true); + enemySpecies = globalScene.randomSpecies(battle.waveIndex, level, true); } - battle.enemyParty[e] = gScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, isBoss, dataSource); + battle.enemyParty[e] = globalScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, isBoss, dataSource); } } - const enemyPokemon = gScene.getEnemyParty()[e]; + const enemyPokemon = globalScene.getEnemyParty()[e]; // Make sure basic data is clean enemyPokemon.hp = enemyPokemon.getMaxHp(); @@ -218,7 +218,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): } if (!loaded && isNullOrUndefined(partyConfig.countAsSeen) || partyConfig.countAsSeen) { - gScene.gameData.setPokemonSeen(enemyPokemon, true, !!(trainerType || trainerConfig)); + globalScene.gameData.setPokemonSeen(enemyPokemon, true, !!(trainerType || trainerConfig)); } if (partyConfig?.pokemonConfigs && e < partyConfig.pokemonConfigs.length) { @@ -256,7 +256,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): // Set Boss if (config.isBoss) { - let segments = !isNullOrUndefined(config.bossSegments) ? config.bossSegments! : gScene.getEncounterBossSegments(gScene.currentBattle.waveIndex, level, enemySpecies, true); + let segments = !isNullOrUndefined(config.bossSegments) ? config.bossSegments! : globalScene.getEncounterBossSegments(globalScene.currentBattle.waveIndex, level, enemySpecies, true); if (!isNullOrUndefined(config.bossSegmentModifier)) { segments += config.bossSegmentModifier; } @@ -342,7 +342,7 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): console.log(`Pokemon: ${enemyPokemon.name}`, `Species ID: ${enemyPokemon.species.speciesId}`, `Stats: ${enemyPokemon.stats}`, `Ability: ${enemyPokemon.getAbility().name}`, `Passive Ability: ${enemyPokemon.getPassiveAbility().name}`); }); - gScene.pushPhase(new MysteryEncounterBattlePhase(partyConfig.disableSwitch)); + globalScene.pushPhase(new MysteryEncounterBattlePhase(partyConfig.disableSwitch)); await Promise.all(loadEnemyAssets); battle.enemyParty.forEach((enemyPokemon_2, e_1) => { @@ -356,11 +356,11 @@ export async function initBattleWithEnemyConfig(partyConfig: EnemyPartyConfig): } }); if (!loaded) { - regenerateModifierPoolThresholds(gScene.getEnemyField(), battle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD); + regenerateModifierPoolThresholds(globalScene.getEnemyField(), battle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD); const customModifierTypes = partyConfig?.pokemonConfigs ?.filter(config => config?.modifierConfigs) .map(config => config.modifierConfigs!); - gScene.generateEnemyModifiers(customModifierTypes); + globalScene.generateEnemyModifiers(customModifierTypes); } } @@ -386,17 +386,17 @@ export function loadCustomMovesForEncounter(moves: Moves | Moves[]) { * @param showMessage */ 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); + globalScene.money = Math.min(Math.max(globalScene.money + changeValue, 0), Number.MAX_SAFE_INTEGER); + globalScene.updateMoneyText(); + globalScene.animateMoneyChanged(false); if (playSound) { - gScene.playSound("se/buy"); + globalScene.playSound("se/buy"); } if (showMessage) { if (changeValue < 0) { - gScene.queueMessage(i18next.t("mysteryEncounterMessages:paid_money", { amount: -changeValue }), null, true); + globalScene.queueMessage(i18next.t("mysteryEncounterMessages:paid_money", { amount: -changeValue }), null, true); } else { - gScene.queueMessage(i18next.t("mysteryEncounterMessages:receive_money", { amount: changeValue }), null, true); + globalScene.queueMessage(i18next.t("mysteryEncounterMessages:receive_money", { amount: changeValue }), null, true); } } } @@ -420,7 +420,7 @@ export function generateModifierType(modifier: () => ModifierType, pregenArgs?: .withIdFromFunc(modifierTypes[modifierId]) .withTierFromPool(); - return result instanceof ModifierTypeGenerator ? result.generateType(gScene.getParty(), pregenArgs) : result; + return result instanceof ModifierTypeGenerator ? result.generateType(globalScene.getParty(), pregenArgs) : result; } /** @@ -447,22 +447,22 @@ export function generateModifierTypeOption(modifier: () => ModifierType, pregenA */ export function selectPokemonForOption(onPokemonSelected: (pokemon: PlayerPokemon) => void | OptionSelectItem[], onPokemonNotSelected?: () => void, selectablePokemonFilter?: PokemonSelectFilter): Promise { return new Promise(resolve => { - const modeToSetOnExit = gScene.ui.getMode(); + const modeToSetOnExit = globalScene.ui.getMode(); // Open party screen to choose pokemon - 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]; + globalScene.ui.setMode(Mode.PARTY, PartyUiMode.SELECT, -1, (slotIndex: number, option: PartyOption) => { + if (slotIndex < globalScene.getParty().length) { + globalScene.ui.setMode(modeToSetOnExit).then(() => { + const pokemon = globalScene.getParty()[slotIndex]; const secondaryOptions = onPokemonSelected(pokemon); if (!secondaryOptions) { - gScene.currentBattle.mysteryEncounter!.setDialogueToken("selectedPokemon", pokemon.getNameToRender()); + globalScene.currentBattle.mysteryEncounter!.setDialogueToken("selectedPokemon", pokemon.getNameToRender()); resolve(true); return; } // There is a second option to choose after selecting the Pokemon - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.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(onPokemonSelected: (pokemon: PlayerPokemo const onSelect = option.handler; option.handler = () => { onSelect(); - gScene.currentBattle.mysteryEncounter!.setDialogueToken("selectedPokemon", pokemon.getNameToRender()); + globalScene.currentBattle.mysteryEncounter!.setDialogueToken("selectedPokemon", pokemon.getNameToRender()); resolve(true); return true; }; @@ -478,8 +478,8 @@ export function selectPokemonForOption(onPokemonSelected: (pokemon: PlayerPokemo }).concat({ label: i18next.t("menu:cancel"), handler: () => { - gScene.ui.clearText(); - gScene.ui.setMode(modeToSetOnExit); + globalScene.ui.clearText(); + globalScene.ui.setMode(modeToSetOnExit); resolve(false); return true; }, @@ -499,10 +499,10 @@ export function selectPokemonForOption(onPokemonSelected: (pokemon: PlayerPokemo if (fullOptions[0].onHover) { fullOptions[0].onHover(); } - gScene.ui.setModeWithoutClear(Mode.OPTION_SELECT, config, null, true); + globalScene.ui.setModeWithoutClear(Mode.OPTION_SELECT, config, null, true); }; - const textPromptKey = gScene.currentBattle.mysteryEncounter?.selectedOption?.dialogue?.secondOptionPrompt; + const textPromptKey = globalScene.currentBattle.mysteryEncounter?.selectedOption?.dialogue?.secondOptionPrompt; if (!textPromptKey) { displayOptions(); } else { @@ -511,7 +511,7 @@ export function selectPokemonForOption(onPokemonSelected: (pokemon: PlayerPokemo }); }); } else { - gScene.ui.setMode(modeToSetOnExit).then(() => { + globalScene.ui.setMode(modeToSetOnExit).then(() => { if (onPokemonNotSelected) { onPokemonNotSelected(); } @@ -538,23 +538,23 @@ interface PokemonAndOptionSelected { */ export function selectOptionThenPokemon(options: OptionSelectItem[], optionSelectPromptKey: string, selectablePokemonFilter?: PokemonSelectFilter, onHoverOverCancelOption?: () => void): Promise { return new Promise(resolve => { - const modeToSetOnExit = gScene.ui.getMode(); + const modeToSetOnExit = globalScene.ui.getMode(); const displayOptions = (config: OptionSelectConfig) => { - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { if (!optionSelectPromptKey) { // Do hover over the starting selection option if (fullOptions[0].onHover) { fullOptions[0].onHover(); } - gScene.ui.setMode(Mode.OPTION_SELECT, config); + globalScene.ui.setMode(Mode.OPTION_SELECT, config); } else { showEncounterText(optionSelectPromptKey).then(() => { // Do hover over the starting selection option if (fullOptions[0].onHover) { fullOptions[0].onHover(); } - gScene.ui.setMode(Mode.OPTION_SELECT, config); + globalScene.ui.setMode(Mode.OPTION_SELECT, config); }); } }); @@ -562,10 +562,10 @@ export function selectOptionThenPokemon(options: OptionSelectItem[], optionSelec const selectPokemonAfterOption = (selectedOptionIndex: number) => { // Open party screen to choose a Pokemon - gScene.ui.setMode(Mode.PARTY, PartyUiMode.SELECT, -1, (slotIndex: number, option: PartyOption) => { - if (slotIndex < gScene.getParty().length) { + globalScene.ui.setMode(Mode.PARTY, PartyUiMode.SELECT, -1, (slotIndex: number, option: PartyOption) => { + if (slotIndex < globalScene.getParty().length) { // Pokemon and option selected - gScene.ui.setMode(modeToSetOnExit).then(() => { + globalScene.ui.setMode(modeToSetOnExit).then(() => { const result: PokemonAndOptionSelected = { selectedPokemonIndex: slotIndex, selectedOptionIndex: selectedOptionIndex }; resolve(result); }); @@ -589,8 +589,8 @@ export function selectOptionThenPokemon(options: OptionSelectItem[], optionSelec }).concat({ label: i18next.t("menu:cancel"), handler: () => { - gScene.ui.clearText(); - gScene.ui.setMode(modeToSetOnExit); + globalScene.ui.clearText(); + globalScene.ui.setMode(modeToSetOnExit); resolve(null); return true; }, @@ -622,15 +622,15 @@ export function selectOptionThenPokemon(options: OptionSelectItem[], optionSelec * @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(customShopRewards?: CustomModifierSettings, eggRewards?: IEggOptions[], preRewardsCallback?: Function) { - gScene.currentBattle.mysteryEncounter!.doEncounterRewards = () => { + globalScene.currentBattle.mysteryEncounter!.doEncounterRewards = () => { if (preRewardsCallback) { preRewardsCallback(); } if (customShopRewards) { - gScene.unshiftPhase(new SelectModifierPhase(0, undefined, customShopRewards)); + globalScene.unshiftPhase(new SelectModifierPhase(0, undefined, customShopRewards)); } else { - gScene.tryRemovePhase(p => p instanceof SelectModifierPhase); + globalScene.tryRemovePhase(p => p instanceof SelectModifierPhase); } if (eggRewards) { @@ -665,8 +665,8 @@ export function setEncounterRewards(customShopRewards?: CustomModifierSettings, export function setEncounterExp(participantId: number | number[], baseExpValue: number, useWaveIndex: boolean = true) { const participantIds = Array.isArray(participantId) ? participantId : [ participantId ]; - gScene.currentBattle.mysteryEncounter!.doEncounterExp = () => { - gScene.unshiftPhase(new PartyExpPhase(baseExpValue, useWaveIndex, new Set(participantIds))); + globalScene.currentBattle.mysteryEncounter!.doEncounterExp = () => { + globalScene.unshiftPhase(new PartyExpPhase(baseExpValue, useWaveIndex, new Set(participantIds))); return true; }; @@ -689,7 +689,7 @@ export class OptionSelectSettings { * @param optionSelectSettings */ export function initSubsequentOptionSelect(optionSelectSettings: OptionSelectSettings) { - gScene.pushPhase(new MysteryEncounterPhase(optionSelectSettings)); + globalScene.pushPhase(new MysteryEncounterPhase(optionSelectSettings)); } /** @@ -700,9 +700,9 @@ export function initSubsequentOptionSelect(optionSelectSettings: OptionSelectSet * @param encounterMode - Can set custom encounter mode if necessary (may be required for forcing Pokemon to return before next phase) */ export function leaveEncounterWithoutBattle(addHealPhase: boolean = false, encounterMode: MysteryEncounterMode = MysteryEncounterMode.NO_BATTLE) { - gScene.currentBattle.mysteryEncounter!.encounterMode = encounterMode; - gScene.clearPhaseQueue(); - gScene.clearPhaseQueueSplice(); + globalScene.currentBattle.mysteryEncounter!.encounterMode = encounterMode; + globalScene.clearPhaseQueue(); + globalScene.clearPhaseQueueSplice(); handleMysteryEncounterVictory(addHealPhase); } @@ -713,32 +713,32 @@ export function leaveEncounterWithoutBattle(addHealPhase: boolean = false, encou * @param doNotContinue - default `false`. If set to true, will not end the battle and continue to next wave */ export function handleMysteryEncounterVictory(addHealPhase: boolean = false, doNotContinue: boolean = false) { - const allowedPkm = gScene.getParty().filter((pkm) => pkm.isAllowedInBattle()); + const allowedPkm = globalScene.getParty().filter((pkm) => pkm.isAllowedInBattle()); if (allowedPkm.length === 0) { - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new GameOverPhase()); + globalScene.clearPhaseQueue(); + globalScene.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 = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; if (encounter.continuousEncounter || doNotContinue) { return; } else if (encounter.encounterMode === MysteryEncounterMode.NO_BATTLE) { - 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()); + globalScene.pushPhase(new MysteryEncounterRewardsPhase(addHealPhase)); + globalScene.pushPhase(new EggLapsePhase()); + } else if (!globalScene.getEnemyParty().find(p => encounter.encounterMode !== MysteryEncounterMode.TRAINER_BATTLE ? p.isOnField() : !p?.isFainted(true))) { + globalScene.pushPhase(new BattleEndPhase()); if (encounter.encounterMode === MysteryEncounterMode.TRAINER_BATTLE) { - gScene.pushPhase(new TrainerVictoryPhase()); + globalScene.pushPhase(new TrainerVictoryPhase()); } - if (gScene.gameMode.isEndless || !gScene.gameMode.isWaveFinal(gScene.currentBattle.waveIndex)) { - gScene.pushPhase(new MysteryEncounterRewardsPhase(addHealPhase)); + if (globalScene.gameMode.isEndless || !globalScene.gameMode.isWaveFinal(globalScene.currentBattle.waveIndex)) { + globalScene.pushPhase(new MysteryEncounterRewardsPhase(addHealPhase)); if (!encounter.doContinueEncounter) { // Only lapse eggs once for multi-battle encounters - gScene.pushPhase(new EggLapsePhase()); + globalScene.pushPhase(new EggLapsePhase()); } } } @@ -750,28 +750,28 @@ export function handleMysteryEncounterVictory(addHealPhase: boolean = false, doN * @param addHealPhase */ export function handleMysteryEncounterBattleFailed(addHealPhase: boolean = false, doNotContinue: boolean = false) { - const allowedPkm = gScene.getParty().filter((pkm) => pkm.isAllowedInBattle()); + const allowedPkm = globalScene.getParty().filter((pkm) => pkm.isAllowedInBattle()); if (allowedPkm.length === 0) { - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new GameOverPhase()); + globalScene.clearPhaseQueue(); + globalScene.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 = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; if (encounter.continuousEncounter || doNotContinue) { return; } else if (encounter.encounterMode !== MysteryEncounterMode.NO_BATTLE) { - gScene.pushPhase(new BattleEndPhase(false)); + globalScene.pushPhase(new BattleEndPhase(false)); } - gScene.pushPhase(new MysteryEncounterRewardsPhase(addHealPhase)); + globalScene.pushPhase(new MysteryEncounterRewardsPhase(addHealPhase)); if (!encounter.doContinueEncounter) { // Only lapse eggs once for multi-battle encounters - gScene.pushPhase(new EggLapsePhase()); + globalScene.pushPhase(new EggLapsePhase()); } } @@ -784,10 +784,10 @@ export function handleMysteryEncounterBattleFailed(addHealPhase: boolean = false */ export function transitionMysteryEncounterIntroVisuals(hide: boolean = true, destroy: boolean = true, duration: number = 750): Promise { return new Promise(resolve => { - const introVisuals = gScene.currentBattle.mysteryEncounter!.introVisuals; - const enemyPokemon = gScene.getEnemyField(); + const introVisuals = globalScene.currentBattle.mysteryEncounter!.introVisuals; + const enemyPokemon = globalScene.getEnemyField(); if (enemyPokemon) { - gScene.currentBattle.enemyParty = []; + globalScene.currentBattle.enemyParty = []; } if (introVisuals) { if (!hide) { @@ -799,7 +799,7 @@ export function transitionMysteryEncounterIntroVisuals(hide: boolean = true, des } // Transition - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ introVisuals, enemyPokemon ], x: `${hide ? "+" : "-"}=16`, y: `${hide ? "-" : "+"}=16`, @@ -808,13 +808,13 @@ export function transitionMysteryEncounterIntroVisuals(hide: boolean = true, des duration, onComplete: () => { if (hide && destroy) { - gScene.field.remove(introVisuals, true); + globalScene.field.remove(introVisuals, true); enemyPokemon.forEach(pokemon => { - gScene.field.remove(pokemon, true); + globalScene.field.remove(pokemon, true); }); - gScene.currentBattle.mysteryEncounter!.introVisuals = undefined; + globalScene.currentBattle.mysteryEncounter!.introVisuals = undefined; } resolve(true); } @@ -831,8 +831,8 @@ export function transitionMysteryEncounterIntroVisuals(hide: boolean = true, des * @param scene */ export function handleMysteryEncounterBattleStartEffects() { - const encounter = gScene.currentBattle.mysteryEncounter; - if (gScene.currentBattle.isBattleMysteryEncounter() && encounter && encounter.encounterMode !== MysteryEncounterMode.NO_BATTLE && !encounter.startOfBattleEffectsComplete) { + const encounter = globalScene.currentBattle.mysteryEncounter; + if (globalScene.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() { source = effect.sourcePokemon; } else if (!isNullOrUndefined(effect.sourceBattlerIndex)) { if (effect.sourceBattlerIndex === BattlerIndex.ATTACKER) { - source = gScene.getEnemyField()[0]; + source = globalScene.getEnemyField()[0]; } else if (effect.sourceBattlerIndex === BattlerIndex.ENEMY) { - source = gScene.getEnemyField()[0]; + source = globalScene.getEnemyField()[0]; } else if (effect.sourceBattlerIndex === BattlerIndex.ENEMY_2) { - source = gScene.getEnemyField()[1]; + source = globalScene.getEnemyField()[1]; } else if (effect.sourceBattlerIndex === BattlerIndex.PLAYER) { - source = gScene.getPlayerField()[0]; + source = globalScene.getPlayerField()[0]; } else if (effect.sourceBattlerIndex === BattlerIndex.PLAYER_2) { - source = gScene.getPlayerField()[1]; + source = globalScene.getPlayerField()[1]; } } else { - source = gScene.getEnemyField()[0]; + source = globalScene.getEnemyField()[0]; } - gScene.pushPhase(new MovePhase(source, effect.targets, effect.move, effect.followUp, effect.ignorePp)); + globalScene.pushPhase(new MovePhase(source, effect.targets, effect.move, effect.followUp, effect.ignorePp)); }); // Pseudo turn end phase to reset flinch states, Endure, etc. - gScene.pushPhase(new MysteryEncounterBattleStartCleanupPhase()); + globalScene.pushPhase(new MysteryEncounterBattleStartCleanupPhase()); encounter.startOfBattleEffectsComplete = true; } @@ -870,8 +870,8 @@ export function handleMysteryEncounterBattleStartEffects() { * @return boolean - if true, will skip the remainder of the {@linkcode TurnInitPhase} */ export function handleMysteryEncounterTurnStartEffects(): boolean { - const encounter = gScene.currentBattle.mysteryEncounter; - if (gScene.currentBattle.isBattleMysteryEncounter() && encounter && encounter.onTurnStart) { + const encounter = globalScene.currentBattle.mysteryEncounter; + if (globalScene.currentBattle.isBattleMysteryEncounter() && encounter && encounter.onTurnStart) { return encounter.onTurnStart(); } @@ -897,9 +897,9 @@ export function calculateMEAggregateStats(baseSpawnWeight: number) { const encountersByBiome = new Map(biomes.map(b => [ b, 0 ])); const validMEfloorsByBiome = new Map(biomes.map(b => [ b, 0 ])); let currentBiome = Biome.TOWN; - let currentArena = gScene.newArena(currentBiome); - gScene.setSeed(Utils.randomString(24)); - gScene.resetSeed(); + let currentArena = globalScene.newArena(currentBiome); + globalScene.setSeed(Utils.randomString(24)); + globalScene.resetSeed(); for (let i = 10; i < 180; i++) { // Boss if (i % 10 === 0) { @@ -910,7 +910,7 @@ export function calculateMEAggregateStats(baseSpawnWeight: number) { if (i % 10 === 1) { if (Array.isArray(biomeLinks[currentBiome])) { let biomes: Biome[]; - gScene.executeWithSeedOffset(() => { + globalScene.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(baseSpawnWeight: number) { if (!(i % 50)) { currentBiome = Biome.END; } else { - currentBiome = gScene.generateRandomBiome(i); + currentBiome = globalScene.generateRandomBiome(i); } } - currentArena = gScene.newArena(currentBiome); + currentArena = globalScene.newArena(currentBiome); } // Fixed battle - if (gScene.gameMode.isFixedBattle(i)) { + if (globalScene.gameMode.isFixedBattle(i)) { continue; } // Trainer - if (gScene.gameMode.isWaveTrainer(i, currentArena)) { + if (globalScene.gameMode.isWaveTrainer(i, currentArena)) { continue; } @@ -994,7 +994,7 @@ export function calculateMEAggregateStats(baseSpawnWeight: number) { const encountersByBiomeRuns: Map[] = []; const validFloorsByBiome: Map[] = []; while (run < numRuns) { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const [ numEncounters, encountersByBiome, validMEfloorsByBiome ] = calculateNumEncounters(); encounterRuns.push(numEncounters); encountersByBiomeRuns.push(encountersByBiome); @@ -1055,8 +1055,8 @@ export function calculateRareSpawnAggregateStats(luckValue: number) { const calculateNumRareEncounters = (): any[] => { const bossEncountersByRarity = [ 0, 0, 0, 0 ]; - gScene.setSeed(Utils.randomString(24)); - gScene.resetSeed(); + globalScene.setSeed(Utils.randomString(24)); + globalScene.resetSeed(); // There are 12 wild boss floors for (let i = 0; i < 12; i++) { // Roll boss tier @@ -1090,7 +1090,7 @@ export function calculateRareSpawnAggregateStats(luckValue: number) { const encounterRuns: number[][] = []; while (run < numRuns) { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const bossEncountersByRarity = calculateNumRareEncounters(); encounterRuns.push(bossEncountersByRarity); }, 1000 * run); diff --git a/src/data/mystery-encounters/utils/encounter-pokemon-utils.ts b/src/data/mystery-encounters/utils/encounter-pokemon-utils.ts index 4169c4f505b..14f45c830f9 100644 --- a/src/data/mystery-encounters/utils/encounter-pokemon-utils.ts +++ b/src/data/mystery-encounters/utils/encounter-pokemon-utils.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import i18next from "i18next"; import { isNullOrUndefined, randSeedInt } from "#app/utils"; import { PokemonHeldItemModifier } from "#app/modifier/modifier"; @@ -60,7 +60,7 @@ export function getSpriteKeysFromPokemon(pokemon: Pokemon): { spriteKey: string, * @returns */ export function getRandomPlayerPokemon(isAllowed: boolean = false, isFainted: boolean = false, doNotReturnLastAllowedMon: boolean = false): PlayerPokemon { - const party = gScene.getParty(); + const party = globalScene.getParty(); let chosenIndex: number; let chosenPokemon: PlayerPokemon | null = null; const fullyLegalMons = party.filter(p => (!isAllowed || p.isAllowed()) && (isFainted || !p.isFainted())); @@ -99,7 +99,7 @@ export function getRandomPlayerPokemon(isAllowed: boolean = false, isFainted: bo * @returns */ export function getHighestLevelPlayerPokemon(isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon { - const party = gScene.getParty(); + const party = globalScene.getParty(); let pokemon: PlayerPokemon | null = null; for (const p of party) { @@ -125,7 +125,7 @@ export function getHighestLevelPlayerPokemon(isAllowed: boolean = false, isFaint * @returns */ export function getHighestStatPlayerPokemon(stat: PermanentStat, isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon { - const party = gScene.getParty(); + const party = globalScene.getParty(); let pokemon: PlayerPokemon | null = null; for (const p of party) { @@ -150,7 +150,7 @@ export function getHighestStatPlayerPokemon(stat: PermanentStat, isAllowed: bool * @returns */ export function getLowestLevelPlayerPokemon(isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon { - const party = gScene.getParty(); + const party = globalScene.getParty(); let pokemon: PlayerPokemon | null = null; for (const p of party) { @@ -175,7 +175,7 @@ export function getLowestLevelPlayerPokemon(isAllowed: boolean = false, isFainte * @returns */ export function getHighestStatTotalPlayerPokemon(isAllowed: boolean = false, isFainted: boolean = false): PlayerPokemon { - const party = gScene.getParty(); + const party = globalScene.getParty(); let pokemon: PlayerPokemon | null = null; for (const p of party) { @@ -313,11 +313,11 @@ export function applyHealToPokemon(pokemon: PlayerPokemon, heal: number) { */ export async function modifyPlayerPokemonBST(pokemon: PlayerPokemon, value: number) { const modType = modifierTypes.MYSTERY_ENCOUNTER_SHUCKLE_JUICE() - .generateType(gScene.getParty(), [ value ]) + .generateType(globalScene.getParty(), [ value ]) ?.withIdFromFunc(modifierTypes.MYSTERY_ENCOUNTER_SHUCKLE_JUICE); const modifier = modType?.newModifier(pokemon); if (modifier) { - await gScene.addModifier(modifier, false, false, false, true); + await globalScene.addModifier(modifier, false, false, false, true); pokemon.calculateStats(); } } @@ -333,7 +333,7 @@ export async function modifyPlayerPokemonBST(pokemon: PlayerPokemon, value: numb 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 = gScene.findModifier(m => ( + const existing = globalScene.findModifier(m => ( m instanceof PokemonHeldItemModifier && m.type.id === modType.id && m.pokemonId === pokemon.id && @@ -350,7 +350,7 @@ export async function applyModifierTypeToPlayerPokemon(pokemon: PlayerPokemon, m return applyModifierTypeToPlayerPokemon(pokemon, fallbackModifierType); } - await gScene.addModifier(modifier, false, false, false, true); + await globalScene.addModifier(modifier, false, false, false, true); } /** @@ -379,43 +379,43 @@ export function trainerThrowPokeball(pokemon: EnemyPokemon, pokeballType: Pokeba const fpOffset = pokemon.getFieldPositionOffset(); const pokeballAtlasKey = getPokeballAtlasKey(pokeballType); - const pokeball: Phaser.GameObjects.Sprite = gScene.addFieldSprite(16 + 75, 80 + 25, "pb", pokeballAtlasKey); + const pokeball: Phaser.GameObjects.Sprite = globalScene.addFieldSprite(16 + 75, 80 + 25, "pb", pokeballAtlasKey); pokeball.setOrigin(0.5, 0.625); - gScene.field.add(pokeball); + globalScene.field.add(pokeball); - gScene.time.delayedCall(300, () => { - gScene.field.moveBelow(pokeball as Phaser.GameObjects.GameObject, pokemon); + globalScene.time.delayedCall(300, () => { + globalScene.field.moveBelow(pokeball as Phaser.GameObjects.GameObject, pokemon); }); return new Promise(resolve => { - gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`); - gScene.time.delayedCall(512, () => { - gScene.playSound("se/pb_throw"); + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`); + globalScene.time.delayedCall(512, () => { + globalScene.playSound("se/pb_throw"); // Trainer throw frames - 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`); + globalScene.trainer.setFrame("2"); + globalScene.time.delayedCall(256, () => { + globalScene.trainer.setFrame("3"); + globalScene.time.delayedCall(768, () => { + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`); }); }); // Pokeball move and catch logic - gScene.tweens.add({ + globalScene.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`); - gScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}_open`)); - gScene.playSound("se/pb_rel"); + globalScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}_open`)); + globalScene.playSound("se/pb_rel"); pokemon.tint(getPokeballTintColor(pokeballType)); addPokeballOpenParticles(pokeball.x, pokeball.y, pokeballType); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, duration: 500, ease: "Sine.easeIn", @@ -424,13 +424,13 @@ export function trainerThrowPokeball(pokemon: EnemyPokemon, pokeballType: Pokeba onComplete: () => { pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`); pokemon.setVisible(false); - gScene.playSound("se/pb_catch"); - gScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}`)); + globalScene.playSound("se/pb_catch"); + globalScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}`)); const doShake = () => { let shakeCount = 0; const pbX = pokeball.x; - const shakeCounter = gScene.tweens.addCounter({ + const shakeCounter = globalScene.tweens.addCounter({ from: 0, to: 1, repeat: 4, @@ -452,27 +452,27 @@ export function trainerThrowPokeball(pokemon: EnemyPokemon, pokeballType: Pokeba failCatch(pokemon, originalY, pokeball, pokeballType).then(() => resolve(false)); } else if (shakeCount++ < 3) { if (randSeedInt(65536) < ballTwitchRate) { - gScene.playSound("se/pb_move"); + globalScene.playSound("se/pb_move"); } else { shakeCounter.stop(); failCatch(pokemon, originalY, pokeball, pokeballType).then(() => resolve(false)); } } else { - gScene.playSound("se/pb_lock"); + globalScene.playSound("se/pb_lock"); addPokeballCaptureStars(pokeball); - const pbTint = gScene.add.sprite(pokeball.x, pokeball.y, "pb", "pb"); + const pbTint = globalScene.add.sprite(pokeball.x, pokeball.y, "pb", "pb"); pbTint.setOrigin(pokeball.originX, pokeball.originY); pbTint.setTintFill(0); pbTint.setAlpha(0); - gScene.field.add(pbTint); - gScene.tweens.add({ + globalScene.field.add(pbTint); + globalScene.tweens.add({ targets: pbTint, alpha: 0.375, duration: 200, easing: "Sine.easeOut", onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: pbTint, alpha: 0, duration: 200, @@ -489,7 +489,7 @@ export function trainerThrowPokeball(pokemon: EnemyPokemon, pokeballType: Pokeba }); }; - gScene.time.delayedCall(250, () => doPokeballBounceAnim(pokeball, 16, 72, 350, doShake)); + globalScene.time.delayedCall(250, () => doPokeballBounceAnim(pokeball, 16, 72, 350, doShake)); } }); } @@ -508,7 +508,7 @@ export function trainerThrowPokeball(pokemon: EnemyPokemon, pokeballType: Pokeba */ function failCatch(pokemon: EnemyPokemon, originalY: number, pokeball: Phaser.GameObjects.Sprite, pokeballType: PokeballType) { return new Promise(resolve => { - gScene.playSound("se/pb_rel"); + globalScene.playSound("se/pb_rel"); pokemon.setY(originalY); if (pokemon.status?.effect !== StatusEffect.SLEEP) { pokemon.cry(pokemon.getHpRatio() > 0.25 ? undefined : { rate: 0.85 }); @@ -519,19 +519,19 @@ function failCatch(pokemon: EnemyPokemon, originalY: number, pokeball: Phaser.Ga const pokeballAtlasKey = getPokeballAtlasKey(pokeballType); pokeball.setTexture("pb", `${pokeballAtlasKey}_opening`); - gScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}_open`)); + globalScene.time.delayedCall(17, () => pokeball.setTexture("pb", `${pokeballAtlasKey}_open`)); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, duration: 250, ease: "Sine.easeOut", scale: 1 }); - gScene.currentBattle.lastUsedPokeball = pokeballType; + globalScene.currentBattle.lastUsedPokeball = pokeballType; removePb(pokeball); - gScene.ui.showText(i18next.t("battle:pokemonBrokeFree", { pokemonName: pokemon.getNameToRender() }), null, () => resolve(), null, true); + globalScene.ui.showText(i18next.t("battle:pokemonBrokeFree", { pokemonName: pokemon.getNameToRender() }), null, () => resolve(), null, true); }); } @@ -548,34 +548,34 @@ export async function catchPokemon(pokemon: EnemyPokemon, pokeball: Phaser.GameO const speciesForm = !pokemon.fusionSpecies ? pokemon.getSpeciesForm() : pokemon.getFusionSpeciesForm(); if (speciesForm.abilityHidden && (pokemon.fusionSpecies ? pokemon.fusionAbilityIndex : pokemon.abilityIndex) === speciesForm.getAbilityCount() - 1) { - gScene.validateAchv(achvs.HIDDEN_ABILITY); + globalScene.validateAchv(achvs.HIDDEN_ABILITY); } if (pokemon.species.subLegendary) { - gScene.validateAchv(achvs.CATCH_SUB_LEGENDARY); + globalScene.validateAchv(achvs.CATCH_SUB_LEGENDARY); } if (pokemon.species.legendary) { - gScene.validateAchv(achvs.CATCH_LEGENDARY); + globalScene.validateAchv(achvs.CATCH_LEGENDARY); } if (pokemon.species.mythical) { - gScene.validateAchv(achvs.CATCH_MYTHICAL); + globalScene.validateAchv(achvs.CATCH_MYTHICAL); } - gScene.pokemonInfoContainer.show(pokemon, true); + globalScene.pokemonInfoContainer.show(pokemon, true); - gScene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs); + globalScene.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 (!gScene.getEnemyParty().some(p => p.id === pokemon.id)) { - gScene.getEnemyParty().push(pokemon); + if (!globalScene.getEnemyParty().some(p => p.id === pokemon.id)) { + globalScene.getEnemyParty().push(pokemon); } - gScene.unshiftPhase(new VictoryPhase(pokemon.id, true)); - gScene.pokemonInfoContainer.hide(); + globalScene.unshiftPhase(new VictoryPhase(pokemon.id, true)); + globalScene.pokemonInfoContainer.hide(); if (pokeball) { removePb(pokeball); } @@ -583,17 +583,17 @@ export async function catchPokemon(pokemon: EnemyPokemon, pokeball: Phaser.GameO }; const removePokemon = () => { if (pokemon) { - gScene.field.remove(pokemon, true); + globalScene.field.remove(pokemon, true); } }; const addToParty = (slotIndex?: number) => { const newPokemon = pokemon.addToParty(pokeballType, slotIndex); - const modifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier, false); - if (gScene.getParty().filter(p => p.isShiny()).length === 6) { - gScene.validateAchv(achvs.SHINY_PARTY); + const modifiers = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier, false); + if (globalScene.getParty().filter(p => p.isShiny()).length === 6) { + globalScene.validateAchv(achvs.SHINY_PARTY); } - Promise.all(modifiers.map(m => gScene.addModifier(m, true))).then(() => { - gScene.updateModifiers(true); + Promise.all(modifiers.map(m => globalScene.addModifier(m, true))).then(() => { + globalScene.updateModifiers(true); removePokemon(); if (newPokemon) { newPokemon.loadAssets().then(end); @@ -602,21 +602,21 @@ export async function catchPokemon(pokemon: EnemyPokemon, pokeball: Phaser.GameO } }); }; - Promise.all([ pokemon.hideInfo(), gScene.gameData.setPokemonCaught(pokemon) ]).then(() => { - if (gScene.getParty().length === 6) { + Promise.all([ pokemon.hideInfo(), globalScene.gameData.setPokemonCaught(pokemon) ]).then(() => { + if (globalScene.getParty().length === 6) { const promptRelease = () => { - 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(() => { + globalScene.ui.showText(i18next.t("battle:partyFull", { pokemonName: pokemon.getNameToRender() }), null, () => { + globalScene.pokemonInfoContainer.makeRoomForConfirmUi(1, true); + globalScene.ui.setMode(Mode.CONFIRM, () => { + const newPokemon = globalScene.addPlayerPokemon(pokemon.species, pokemon.level, pokemon.abilityIndex, pokemon.formIndex, pokemon.gender, pokemon.shiny, pokemon.variant, pokemon.ivs, pokemon.nature, pokemon); + globalScene.ui.setMode(Mode.SUMMARY, newPokemon, 0, SummaryUiMode.DEFAULT, () => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { promptRelease(); }); }, false); }, () => { - gScene.ui.setMode(Mode.PARTY, PartyUiMode.RELEASE, 0, (slotIndex: integer, _option: PartyOption) => { - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.PARTY, PartyUiMode.RELEASE, 0, (slotIndex: integer, _option: PartyOption) => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { if (slotIndex < 6) { addToParty(slotIndex); } else { @@ -625,7 +625,7 @@ export async function catchPokemon(pokemon: EnemyPokemon, pokeball: Phaser.GameO }); }); }, () => { - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { removePokemon(); end(); }); @@ -640,7 +640,7 @@ export async function catchPokemon(pokemon: EnemyPokemon, pokeball: Phaser.GameO }; if (showCatchObtainMessage) { - gScene.ui.showText(i18next.t(isObtain ? "battle:pokemonObtained" : "battle:pokemonCaught", { pokemonName: pokemon.getNameToRender() }), null, doPokemonCatchMenu, 0, true); + globalScene.ui.showText(i18next.t(isObtain ? "battle:pokemonObtained" : "battle:pokemonCaught", { pokemonName: pokemon.getNameToRender() }), null, doPokemonCatchMenu, 0, true); } else { doPokemonCatchMenu(); } @@ -654,7 +654,7 @@ export async function catchPokemon(pokemon: EnemyPokemon, pokeball: Phaser.GameO */ function removePb(pokeball: Phaser.GameObjects.Sprite) { if (pokeball) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, duration: 250, delay: 250, @@ -674,9 +674,9 @@ function removePb(pokeball: Phaser.GameObjects.Sprite) { */ export async function doPokemonFlee(pokemon: EnemyPokemon): Promise { await new Promise(resolve => { - gScene.playSound("se/flee"); + globalScene.playSound("se/flee"); // Ease pokemon out - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, x: "+=16", y: "-=16", @@ -686,7 +686,7 @@ export async function doPokemonFlee(pokemon: EnemyPokemon): Promise { scale: pokemon.getSpriteScale(), onComplete: () => { pokemon.setVisible(false); - gScene.field.remove(pokemon, true); + globalScene.field.remove(pokemon, true); showEncounterText(i18next.t("battle:pokemonFled", { pokemonName: pokemon.getNameToRender() }), null, 600, false) .then(() => { resolve(); @@ -704,7 +704,7 @@ export async function doPokemonFlee(pokemon: EnemyPokemon): Promise { export function doPlayerFlee(pokemon: EnemyPokemon): Promise { return new Promise(resolve => { // Ease pokemon out - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, x: "+=16", y: "-=16", @@ -714,7 +714,7 @@ export function doPlayerFlee(pokemon: EnemyPokemon): Promise { scale: pokemon.getSpriteScale(), onComplete: () => { pokemon.setVisible(false); - gScene.field.remove(pokemon, true); + globalScene.field.remove(pokemon, true); showEncounterText(i18next.t("battle:playerFled", { pokemonName: pokemon.getNameToRender() }), null, 600, false) .then(() => { resolve(); @@ -784,7 +784,7 @@ export function getGoldenBugNetSpecies(level: number): PokemonSpecies { * @param levelAdditiveModifier Default 0. will add +(1 level / 10 waves * levelAdditiveModifier) to the level calculation */ export function getEncounterPokemonLevelForWave(levelAdditiveModifier: number = 0) { - const currentBattle = gScene.currentBattle; + const currentBattle = globalScene.currentBattle; const baseLevel = currentBattle.getLevelForWave(); // Add a level scaling modifier that is (+1 level per 10 waves) * levelAdditiveModifier @@ -795,23 +795,23 @@ export async function addPokemonDataToDexAndValidateAchievements(pokemon: Player const speciesForm = !pokemon.fusionSpecies ? pokemon.getSpeciesForm() : pokemon.getFusionSpeciesForm(); if (speciesForm.abilityHidden && (pokemon.fusionSpecies ? pokemon.fusionAbilityIndex : pokemon.abilityIndex) === speciesForm.getAbilityCount() - 1) { - gScene.validateAchv(achvs.HIDDEN_ABILITY); + globalScene.validateAchv(achvs.HIDDEN_ABILITY); } if (pokemon.species.subLegendary) { - gScene.validateAchv(achvs.CATCH_SUB_LEGENDARY); + globalScene.validateAchv(achvs.CATCH_SUB_LEGENDARY); } if (pokemon.species.legendary) { - gScene.validateAchv(achvs.CATCH_LEGENDARY); + globalScene.validateAchv(achvs.CATCH_LEGENDARY); } if (pokemon.species.mythical) { - gScene.validateAchv(achvs.CATCH_MYTHICAL); + globalScene.validateAchv(achvs.CATCH_MYTHICAL); } - gScene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs); - return gScene.gameData.setPokemonCaught(pokemon, true, false, false); + globalScene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs); + return globalScene.gameData.setPokemonCaught(pokemon, true, false, false); } /** diff --git a/src/data/mystery-encounters/utils/encounter-transformation-sequence.ts b/src/data/mystery-encounters/utils/encounter-transformation-sequence.ts index 517659f8778..dbda1560c90 100644 --- a/src/data/mystery-encounters/utils/encounter-transformation-sequence.ts +++ b/src/data/mystery-encounters/utils/encounter-transformation-sequence.ts @@ -2,7 +2,7 @@ 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"; +import { globalScene } from "#app/battle-scene"; export enum TransformationScreenPosition { CENTER, @@ -19,8 +19,8 @@ export enum TransformationScreenPosition { */ export function doPokemonTransformationSequence(previousPokemon: PlayerPokemon, transformPokemon: PlayerPokemon, screenPosition: TransformationScreenPosition) { return new Promise(resolve => { - const transformationContainer = gScene.fieldUI.getByName("Dream Background") as Phaser.GameObjects.Container; - const transformationBaseBg = gScene.add.image(0, 0, "default_bg"); + const transformationContainer = globalScene.fieldUI.getByName("Dream Background") as Phaser.GameObjects.Container; + const transformationBaseBg = globalScene.add.image(0, 0, "default_bg"); transformationBaseBg.setOrigin(0, 0); transformationBaseBg.setVisible(false); transformationContainer.add(transformationBaseBg); @@ -36,8 +36,8 @@ export function doPokemonTransformationSequence(previousPokemon: PlayerPokemon, const yOffset = screenPosition !== TransformationScreenPosition.CENTER ? -15 : 0; const getPokemonSprite = () => { - 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 }); + const ret = globalScene.addPokemonSprite(previousPokemon, transformationBaseBg.displayWidth / 2 + xOffset, transformationBaseBg.displayHeight / 2 + yOffset, "pkmn__sub"); + ret.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); return ret; }; @@ -55,7 +55,7 @@ export function doPokemonTransformationSequence(previousPokemon: PlayerPokemon, [ pokemonSprite, pokemonTintSprite, pokemonEvoSprite, pokemonEvoTintSprite ].map(sprite => { sprite.play(previousPokemon.getSpriteKey(true)); - sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(previousPokemon.getTeraType()) }); + sprite.setPipeline(globalScene.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(previousPokemon: PlayerPokemon, }); }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemonSprite, alpha: 1, ease: "Cubic.easeInOut", duration: 2000, onComplete: () => { doSpiralUpward(transformationBaseBg, transformationContainer, xOffset, yOffset); - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ from: 0, to: 1, duration: 1000, @@ -98,26 +98,26 @@ export function doPokemonTransformationSequence(previousPokemon: PlayerPokemon, }, onComplete: () => { pokemonSprite.setVisible(false); - gScene.time.delayedCall(700, () => { + globalScene.time.delayedCall(700, () => { doArcDownward(transformationBaseBg, transformationContainer, xOffset, yOffset); - gScene.time.delayedCall(1000, () => { + globalScene.time.delayedCall(1000, () => { pokemonEvoTintSprite.setScale(0.25); pokemonEvoTintSprite.setVisible(true); doCycle(1.5, 6, pokemonTintSprite, pokemonEvoTintSprite).then(() => { pokemonEvoSprite.setVisible(true); doCircleInward(transformationBaseBg, transformationContainer, xOffset, yOffset); - gScene.time.delayedCall(900, () => { - gScene.tweens.add({ + globalScene.time.delayedCall(900, () => { + globalScene.tweens.add({ targets: pokemonEvoTintSprite, alpha: 0, duration: 1500, delay: 150, easing: "Sine.easeIn", onComplete: () => { - gScene.time.delayedCall(3000, () => { + globalScene.time.delayedCall(3000, () => { resolve(); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemonEvoSprite, alpha: 0, duration: 2000, @@ -154,7 +154,7 @@ export function doPokemonTransformationSequence(previousPokemon: PlayerPokemon, function doSpiralUpward(transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) { let f = 0; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ repeat: 64, duration: getFrameMs(1), onRepeat: () => { @@ -181,7 +181,7 @@ function doSpiralUpward(transformationBaseBg: Phaser.GameObjects.Image, transfor function doArcDownward(transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) { let f = 0; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ repeat: 96, duration: getFrameMs(1), onRepeat: () => { @@ -208,14 +208,14 @@ function doArcDownward(transformationBaseBg: Phaser.GameObjects.Image, transform function doCycle(l: number, lastCycle: number, pokemonTintSprite: Phaser.GameObjects.Sprite, pokemonEvoTintSprite: Phaser.GameObjects.Sprite): Promise { return new Promise(resolve => { const isLastCycle = l === lastCycle; - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemonTintSprite, scale: 0.25, ease: "Cubic.easeInOut", duration: 500 / l, yoyo: !isLastCycle }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemonEvoTintSprite, scale: 1, ease: "Cubic.easeInOut", @@ -244,7 +244,7 @@ function doCycle(l: number, lastCycle: number, pokemonTintSprite: Phaser.GameObj function doCircleInward(transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) { let f = 0; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ repeat: 48, duration: getFrameMs(1), onRepeat: () => { @@ -273,13 +273,13 @@ function doCircleInward(transformationBaseBg: Phaser.GameObjects.Image, transfor */ function doSpiralUpwardParticle(trigIndex: number, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) { const initialX = transformationBaseBg.displayWidth / 2 + xOffset; - const particle = gScene.add.image(initialX, 0, "evo_sparkle"); + const particle = globalScene.add.image(initialX, 0, "evo_sparkle"); transformationContainer.add(particle); let f = 0; let amp = 48; - const particleTimer = gScene.tweens.addCounter({ + const particleTimer = globalScene.tweens.addCounter({ repeat: -1, duration: getFrameMs(1), onRepeat: () => { @@ -318,14 +318,14 @@ function doSpiralUpwardParticle(trigIndex: number, transformationBaseBg: Phaser. */ function doArcDownParticle(trigIndex: number, transformationBaseBg: Phaser.GameObjects.Image, transformationContainer: Phaser.GameObjects.Container, xOffset: number, yOffset: number) { const initialX = transformationBaseBg.displayWidth / 2 + xOffset; - const particle = gScene.add.image(initialX, 0, "evo_sparkle"); + const particle = globalScene.add.image(initialX, 0, "evo_sparkle"); particle.setScale(0.5); transformationContainer.add(particle); let f = 0; let amp = 8; - const particleTimer = gScene.tweens.addCounter({ + const particleTimer = globalScene.tweens.addCounter({ repeat: -1, duration: getFrameMs(1), onRepeat: () => { @@ -362,12 +362,12 @@ function doArcDownParticle(trigIndex: number, transformationBaseBg: Phaser.GameO 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 = gScene.add.image(initialX, initialY, "evo_sparkle"); + const particle = globalScene.add.image(initialX, initialY, "evo_sparkle"); transformationContainer.add(particle); let amp = 120; - const particleTimer = gScene.tweens.addCounter({ + const particleTimer = globalScene.tweens.addCounter({ repeat: -1, duration: getFrameMs(1), onRepeat: () => { diff --git a/src/data/pokeball.ts b/src/data/pokeball.ts index 15c07146ac0..2af39ad57f9 100644 --- a/src/data/pokeball.ts +++ b/src/data/pokeball.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { PokeballType } from "#enums/pokeball"; import i18next from "i18next"; @@ -89,13 +89,13 @@ export function doPokeballBounceAnim(pokeball: Phaser.GameObjects.Sprite, y1: nu const yd = y2 - y1; const doBounce = () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, y: y2, duration: bouncePower * baseBounceDuration, ease: "Cubic.easeIn", onComplete: () => { - gScene.playSound("se/pb_bounce_1", { volume: bouncePower }); + globalScene.playSound("se/pb_bounce_1", { volume: bouncePower }); bouncePower = bouncePower > 0.01 ? bouncePower * 0.5 : 0; @@ -103,7 +103,7 @@ export function doPokeballBounceAnim(pokeball: Phaser.GameObjects.Sprite, y1: nu bounceYOffset = yd * bouncePower; bounceY = y2 - bounceYOffset; - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, y: bounceY, duration: bouncePower * baseBounceDuration, diff --git a/src/data/pokemon-forms.ts b/src/data/pokemon-forms.ts index 4e3655e683a..0fd9d36d98c 100644 --- a/src/data/pokemon-forms.ts +++ b/src/data/pokemon-forms.ts @@ -13,7 +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"; +import { globalScene } from "#app/battle-scene"; export enum FormChangeItem { NONE, @@ -260,7 +260,7 @@ export class SpeciesFormChangeItemTrigger extends SpeciesFormChangeTrigger { } canChange(pokemon: Pokemon): boolean { - return !!gScene.findModifier(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === pokemon.id && m.formChangeItem === this.item && m.active === this.active); + return !!globalScene.findModifier(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === pokemon.id && m.formChangeItem === this.item && m.active === this.active); } } @@ -273,7 +273,7 @@ export class SpeciesFormChangeTimeOfDayTrigger extends SpeciesFormChangeTrigger } canChange(pokemon: Pokemon): boolean { - return this.timesOfDay.indexOf(gScene.arena.getTimeOfDay()) > -1; + return this.timesOfDay.indexOf(globalScene.arena.getTimeOfDay()) > -1; } } @@ -336,7 +336,7 @@ export abstract class SpeciesFormChangeMoveTrigger extends SpeciesFormChangeTrig export class SpeciesFormChangePreMoveTrigger extends SpeciesFormChangeMoveTrigger { canChange(pokemon: Pokemon): boolean { - const command = gScene.currentBattle.turnCommands[pokemon.getBattlerIndex()]; + const command = globalScene.currentBattle.turnCommands[pokemon.getBattlerIndex()]; return !!command?.move && this.movePredicate(command.move.move) === this.used; } } @@ -349,7 +349,7 @@ export class SpeciesFormChangePostMoveTrigger extends SpeciesFormChangeMoveTrigg export class MeloettaFormChangePostMoveTrigger extends SpeciesFormChangePostMoveTrigger { override canChange(pokemon: Pokemon): boolean { - if (gScene.gameMode.hasChallenge(Challenges.SINGLE_TYPE)) { + if (globalScene.gameMode.hasChallenge(Challenges.SINGLE_TYPE)) { return false; } else { return super.canChange(pokemon); @@ -366,7 +366,7 @@ export class SpeciesDefaultFormMatchTrigger extends SpeciesFormChangeTrigger { } canChange(pokemon: Pokemon): boolean { - return this.formKey === pokemon.species.forms[gScene.getSpeciesFormIndex(pokemon.species, pokemon.gender, pokemon.getNature(), true)].formKey; + return this.formKey === pokemon.species.forms[globalScene.getSpeciesFormIndex(pokemon.species, pokemon.gender, pokemon.getNature(), true)].formKey; } } @@ -390,7 +390,7 @@ export class SpeciesFormChangeTeraTrigger extends SpeciesFormChangeTrigger { * @returns `true` if the Pokémon can change forms, `false` otherwise */ canChange(pokemon: Pokemon): boolean { - return !!gScene.findModifier(m => m instanceof TerastallizeModifier && m.pokemonId === pokemon.id && m.teraType === this.teraType); + return !!globalScene.findModifier(m => m instanceof TerastallizeModifier && m.pokemonId === pokemon.id && m.teraType === this.teraType); } } @@ -401,7 +401,7 @@ export class SpeciesFormChangeTeraTrigger extends SpeciesFormChangeTrigger { */ export class SpeciesFormChangeLapseTeraTrigger extends SpeciesFormChangeTrigger { canChange(pokemon: Pokemon): boolean { - return !!gScene.findModifier(m => m instanceof TerastallizeModifier && m.pokemonId === pokemon.id); + return !!globalScene.findModifier(m => m instanceof TerastallizeModifier && m.pokemonId === pokemon.id); } } @@ -429,8 +429,8 @@ export class SpeciesFormChangeWeatherTrigger extends SpeciesFormChangeTrigger { * @returns `true` if the Pokemon can change forms, `false` otherwise */ canChange(pokemon: Pokemon): boolean { - const currentWeather = gScene.arena.weather?.weatherType ?? WeatherType.NONE; - const isWeatherSuppressed = gScene.arena.weather?.isEffectSuppressed(); + const currentWeather = globalScene.arena.weather?.weatherType ?? WeatherType.NONE; + const isWeatherSuppressed = globalScene.arena.weather?.isEffectSuppressed(); const isAbilitySuppressed = pokemon.summonData.abilitySuppressed; return !isAbilitySuppressed && !isWeatherSuppressed && (pokemon.hasAbility(this.ability) && this.weathers.includes(currentWeather)); @@ -463,8 +463,8 @@ export class SpeciesFormChangeRevertWeatherFormTrigger extends SpeciesFormChange */ canChange(pokemon: Pokemon): boolean { if (pokemon.hasAbility(this.ability, false, true)) { - const currentWeather = gScene.arena.weather?.weatherType ?? WeatherType.NONE; - const isWeatherSuppressed = gScene.arena.weather?.isEffectSuppressed(); + const currentWeather = globalScene.arena.weather?.weatherType ?? WeatherType.NONE; + const isWeatherSuppressed = globalScene.arena.weather?.isEffectSuppressed(); const isAbilitySuppressed = pokemon.summonData.abilitySuppressed; const summonDataAbility = pokemon.summonData.ability; const isAbilityChanged = summonDataAbility !== this.ability && summonDataAbility !== Abilities.NONE; @@ -507,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 => !!gScene.gameData.dexData[species].caughtAttr); + return new SpeciesFormChangeCondition(p => !!globalScene.gameData.dexData[species].caughtAttr); } interface PokemonFormChanges { diff --git a/src/data/pokemon-species.ts b/src/data/pokemon-species.ts index 434cf6fc011..abfdee9ce97 100644 --- a/src/data/pokemon-species.ts +++ b/src/data/pokemon-species.ts @@ -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 { AnySound, gScene } from "#app/battle-scene"; +import { AnySound, globalScene } from "#app/battle-scene"; import { GameMode } from "#app/game-mode"; import { StarterMoveset } from "#app/system/game-data"; import * as Utils from "#app/utils"; @@ -470,26 +470,26 @@ export abstract class PokemonSpeciesForm { loadAssets(female: boolean, formIndex?: integer, shiny?: boolean, variant?: Variant, startLoad?: boolean): Promise { return new Promise(resolve => { const spriteKey = this.getSpriteKey(female, formIndex, shiny, variant); - 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, () => { + globalScene.loadPokemonAtlas(spriteKey, this.getSpriteAtlasPath(female, formIndex, shiny, variant)); + globalScene.load.audio(`cry/${this.getCryKey(formIndex)}`, `audio/cry/${this.getCryKey(formIndex)}.m4a`); + globalScene.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 = gScene.anims.generateFrameNames(spriteKey, { zeroPad: 4, suffix: ".png", start: 1, end: 400 }); + const frameNames = globalScene.anims.generateFrameNames(spriteKey, { zeroPad: 4, suffix: ".png", start: 1, end: 400 }); console.warn = originalWarn; - if (!(gScene.anims.exists(spriteKey))) { - gScene.anims.create({ + if (!(globalScene.anims.exists(spriteKey))) { + globalScene.anims.create({ key: this.getSpriteKey(female, formIndex, shiny, variant), frames: frameNames, frameRate: 12, repeat: -1 }); } else { - gScene.anims.get(spriteKey).frameRate = 12; + globalScene.anims.get(spriteKey).frameRate = 12; } let spritePath = this.getSpriteAtlasPath(female, formIndex, shiny, variant).replace("variant/", "").replace(/_[1-3]$/, ""); - const useExpSprite = gScene.experimentalSprites && gScene.hasExpSprite(spriteKey); + const useExpSprite = globalScene.experimentalSprites && globalScene.hasExpSprite(spriteKey); if (useExpSprite) { spritePath = `exp/${spritePath}`; } @@ -502,7 +502,7 @@ export abstract class PokemonSpeciesForm { if (variantColorCache.hasOwnProperty(key)) { return resolve(); } - gScene.cachedFetch(`./images/pokemon/variant/${spritePath}.json`).then(res => res.json()).then(c => { + globalScene.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 (!gScene.load.isLoading()) { - gScene.load.start(); + if (!globalScene.load.isLoading()) { + globalScene.load.start(); } } else { resolve(); @@ -525,11 +525,11 @@ export abstract class PokemonSpeciesForm { cry(soundConfig?: Phaser.Types.Sound.SoundConfig, ignorePlay?: boolean): AnySound { const cryKey = this.getCryKey(this.formIndex); - let cry: AnySound | null = gScene.sound.get(cryKey) as AnySound; + let cry: AnySound | null = globalScene.sound.get(cryKey) as AnySound; if (cry?.pendingRemove) { cry = null; } - cry = gScene.playSound(`cry/${(cry ?? cryKey)}`, soundConfig); + cry = globalScene.playSound(`cry/${(cry ?? cryKey)}`, soundConfig); if (ignorePlay) { cry.stop(); } @@ -537,7 +537,7 @@ export abstract class PokemonSpeciesForm { } generateCandyColors(): integer[][] { - const sourceTexture = gScene.textures.get(this.getSpriteKey(false)); + const sourceTexture = globalScene.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); - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { paletteColors = QuantizerCelebi.quantize(pixelColors, 2); }, 0, "This result should not vary"); @@ -955,7 +955,7 @@ export function getPokerusStarters(): PokemonSpecies[] { const pokerusStarters: PokemonSpecies[] = []; const date = new Date(); date.setUTCHours(0, 0, 0, 0); - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { while (pokerusStarters.length < POKERUS_STARTER_COUNT) { const randomSpeciesId = parseInt(Utils.randSeedItem(Object.keys(speciesStarterCosts)), 10); const species = getPokemonSpecies(randomSpeciesId); diff --git a/src/data/trainer-config.ts b/src/data/trainer-config.ts index 918f0a8a0ff..64618519fb2 100644 --- a/src/data/trainer-config.ts +++ b/src/data/trainer-config.ts @@ -1,4 +1,4 @@ -import { gScene, startingWave } from "#app/battle-scene"; +import { globalScene, 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"; @@ -842,7 +842,7 @@ export class TrainerConfig { this.setBattleBgm("battle_unova_gym"); this.setVictoryBgm("victory_gym"); this.setGenModifiersFunc(party => { - const waveIndex = gScene.currentBattle.waveIndex; + const waveIndex = globalScene.currentBattle.waveIndex; return getRandomTeraModifiers(party, waveIndex >= 100 ? 1 : 0, specialtyTypes.length ? specialtyTypes : undefined); }); @@ -1016,23 +1016,23 @@ export class TrainerConfig { const isDouble = variant === TrainerVariant.DOUBLE; const trainerKey = this.getSpriteKey(variant === TrainerVariant.FEMALE, false); const partnerTrainerKey = this.getSpriteKey(true, true); - gScene.loadAtlas(trainerKey, "trainer"); + globalScene.loadAtlas(trainerKey, "trainer"); if (isDouble) { - gScene.loadAtlas(partnerTrainerKey, "trainer"); + globalScene.loadAtlas(partnerTrainerKey, "trainer"); } - gScene.load.once(Phaser.Loader.Events.COMPLETE, () => { + globalScene.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 = gScene.anims.generateFrameNames(trainerKey, { + const frameNames = globalScene.anims.generateFrameNames(trainerKey, { zeroPad: 4, suffix: ".png", start: 1, end: 128 }); const partnerFrameNames = isDouble - ? gScene.anims.generateFrameNames(partnerTrainerKey, { + ? globalScene.anims.generateFrameNames(partnerTrainerKey, { zeroPad: 4, suffix: ".png", start: 1, @@ -1040,16 +1040,16 @@ export class TrainerConfig { }) : ""; console.warn = originalWarn; - if (!(gScene.anims.exists(trainerKey))) { - gScene.anims.create({ + if (!(globalScene.anims.exists(trainerKey))) { + globalScene.anims.create({ key: trainerKey, frames: frameNames, frameRate: 24, repeat: -1 }); } - if (isDouble && !(gScene.anims.exists(partnerTrainerKey))) { - gScene.anims.create({ + if (isDouble && !(globalScene.anims.exists(partnerTrainerKey))) { + globalScene.anims.create({ key: partnerTrainerKey, frames: partnerFrameNames, frameRate: 24, @@ -1058,8 +1058,8 @@ export class TrainerConfig { } resolve(); }); - if (!gScene.load.isLoading()) { - gScene.load.start(); + if (!globalScene.load.isLoading()) { + globalScene.load.start(); } }); } @@ -1137,7 +1137,7 @@ interface TrainerConfigs { * @returns the correct TrainerPartyTemplate */ function getEvilGruntPartyTemplate(): TrainerPartyTemplate { - const waveIndex = gScene.currentBattle?.waveIndex; + const waveIndex = globalScene.currentBattle?.waveIndex; if (waveIndex < 40) { return trainerPartyTemplates.TWO_AVG; } else if (waveIndex < 63) { @@ -1152,7 +1152,7 @@ function getEvilGruntPartyTemplate(): TrainerPartyTemplate { } 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)]; + return templates[Math.min(Math.max(Math.ceil((globalScene.gameMode.getWaveForDifficulty(globalScene.currentBattle?.waveIndex || startingWave, true) - 20) / 30), 0), templates.length - 1)]; } function getGymLeaderPartyTemplate() { @@ -1161,7 +1161,7 @@ function getGymLeaderPartyTemplate() { /** * Randomly selects one of the `Species` from `speciesPool`, determines its evolution, level, and strength. - * Then adds Pokemon to gScene. + * Then adds Pokemon to globalScene. * @param speciesPool * @param trainerSlot * @param ignoreEvolution @@ -1171,9 +1171,9 @@ export function getRandomPartyMemberFunc(speciesPool: Species[], trainerSlot: Tr return (level: number, strength: PartyMemberStrength) => { let species = Utils.randSeedItem(speciesPool); if (!ignoreEvolution) { - species = getPokemonSpecies(species).getTrainerSpeciesForLevel(level, true, strength, gScene.currentBattle.waveIndex); + species = getPokemonSpecies(species).getTrainerSpeciesForLevel(level, true, strength, globalScene.currentBattle.waveIndex); } - return gScene.addEnemyPokemon(getPokemonSpecies(species), level, trainerSlot, undefined, undefined, postProcess); + return globalScene.addEnemyPokemon(getPokemonSpecies(species), level, trainerSlot, undefined, undefined, postProcess); }; } @@ -1181,7 +1181,7 @@ function getSpeciesFilterRandomPartyMemberFunc(speciesFilter: PokemonSpeciesFilt const originalSpeciesFilter = speciesFilter; speciesFilter = (species: PokemonSpecies) => (allowLegendaries || (!species.legendary && !species.subLegendary && !species.mythical)) && !species.isTrainerForbidden() && originalSpeciesFilter(species); 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); + const ret = globalScene.addEnemyPokemon(getPokemonSpecies(globalScene.randomSpecies(globalScene.currentBattle.waveIndex, level, false, speciesFilter).getTrainerSpeciesForLevel(level, true, strength, globalScene.currentBattle.waveIndex)), level, trainerSlot, undefined, undefined, postProcess); return ret; }; } diff --git a/src/data/weather.ts b/src/data/weather.ts index bb7a6ca2e75..bad4c73317d 100644 --- a/src/data/weather.ts +++ b/src/data/weather.ts @@ -8,7 +8,7 @@ import * as Utils from "../utils"; import { SuppressWeatherEffectAbAttr } from "./ability"; import { TerrainType, getTerrainName } from "./terrain"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export { WeatherType }; export class Weather { @@ -102,7 +102,7 @@ export class Weather { } isEffectSuppressed(): boolean { - const field = gScene.getField(true); + const field = globalScene.getField(true); for (const pokemon of field) { let suppressWeatherEffectAbAttr: SuppressWeatherEffectAbAttr | null = pokemon.getAbility().getAttrs(SuppressWeatherEffectAbAttr)[0]; diff --git a/src/field/anims.ts b/src/field/anims.ts index 0ea81854e41..1669934f0ef 100644 --- a/src/field/anims.ts +++ b/src/field/anims.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { PokeballType } from "../data/pokeball"; import * as Utils from "../utils"; @@ -23,9 +23,9 @@ export function addPokeballOpenParticles(x: number, y: number, pokeballType: Pok } 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({ + const pbOpenParticlesFrameNames = globalScene.anims.generateFrameNames("pb_particles", { start: 0, end: 3, suffix: ".png" }); + if (!(globalScene.anims.exists("pb_open_particle"))) { + globalScene.anims.create({ key: "pb_open_particle", frames: pbOpenParticlesFrameNames, frameRate: 16, @@ -34,11 +34,11 @@ function doDefaultPbOpenParticles(x: number, y: number, radius: number) { } const addParticle = (index: integer) => { - const particle = gScene.add.sprite(x, y, "pb_open_particle"); - gScene.field.add(particle); + const particle = globalScene.add.sprite(x, y, "pb_open_particle"); + globalScene.field.add(particle); const angle = index * 45; const [ xCoord, yCoord ] = [ radius * Math.cos(angle * Math.PI / 180), radius * Math.sin(angle * Math.PI / 180) ]; - gScene.tweens.add({ + globalScene.tweens.add({ targets: particle, x: x + xCoord, y: y + yCoord, @@ -47,9 +47,9 @@ function doDefaultPbOpenParticles(x: number, y: number, radius: number) { particle.play({ key: "pb_open_particle", startFrame: (index + 3) % 4, - frameRate: Math.floor(16 * gScene.gameSpeed) + frameRate: Math.floor(16 * globalScene.gameSpeed) }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: particle, delay: 500, duration: 75, @@ -60,7 +60,7 @@ function doDefaultPbOpenParticles(x: number, y: number, radius: number) { }; let particleCount = 0; - gScene.time.addEvent({ + globalScene.time.addEvent({ delay: 20, repeat: 16, callback: () => addParticle(++particleCount) @@ -73,7 +73,7 @@ function doUbOpenParticles(x: number, y: number, frameIndex: integer) { particles.push(doFanOutParticle(i * 25, x, y, 1, 1, 5, frameIndex)); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: particles, delay: 750, duration: 250, @@ -94,7 +94,7 @@ function doMbOpenParticles(x: number, y: number) { particles.push(doFanOutParticle(i * 32, x, y, j ? 1 : 2, j ? 2 : 1, 8, 4)); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: particles, delay: 750, duration: 250, @@ -112,8 +112,8 @@ function doMbOpenParticles(x: number, y: number) { function doFanOutParticle(trigIndex: integer, x: integer, y: integer, xSpeed: integer, ySpeed: integer, angle: integer, frameIndex: integer): Phaser.GameObjects.Image { let f = 0; - const particle = gScene.add.image(x, y, "pb_particles", `${frameIndex}.png`); - gScene.field.add(particle); + const particle = globalScene.add.image(x, y, "pb_particles", `${frameIndex}.png`); + globalScene.field.add(particle); const updateParticle = () => { if (!particle.scene) { @@ -125,7 +125,7 @@ function doFanOutParticle(trigIndex: integer, x: integer, y: integer, xSpeed: in f++; }; - const particleTimer = gScene.tweens.addCounter({ + const particleTimer = globalScene.tweens.addCounter({ repeat: -1, duration: Utils.getFrameMs(1), onRepeat: () => { @@ -138,18 +138,18 @@ function doFanOutParticle(trigIndex: integer, x: integer, y: integer, xSpeed: in export function addPokeballCaptureStars(pokeball: Phaser.GameObjects.Sprite): void { const addParticle = () => { - const particle = gScene.add.sprite(pokeball.x, pokeball.y, "pb_particles", "4.png"); + const particle = globalScene.add.sprite(pokeball.x, pokeball.y, "pb_particles", "4.png"); particle.setOrigin(pokeball.originX, pokeball.originY); particle.setAlpha(0.5); - gScene.field.add(particle); + globalScene.field.add(particle); - gScene.tweens.add({ + globalScene.tweens.add({ targets: particle, y: pokeball.y - 10, ease: "Sine.easeOut", duration: 250, onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: particle, y: pokeball.y, alpha: 0, @@ -160,13 +160,13 @@ export function addPokeballCaptureStars(pokeball: Phaser.GameObjects.Sprite): vo }); const dist = Utils.randGauss(25); - gScene.tweens.add({ + globalScene.tweens.add({ targets: particle, x: pokeball.x + dist, duration: 500 }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: particle, alpha: 0, delay: 425, diff --git a/src/field/arena.ts b/src/field/arena.ts index da0c6f68c91..84e5b21e4a3 100644 --- a/src/field/arena.ts +++ b/src/field/arena.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; // ? +import { globalScene } 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"; @@ -59,12 +59,12 @@ export class Arena { init() { const biomeKey = getBiomeKey(this.biomeType); - 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`); + globalScene.arenaPlayer.setBiome(this.biomeType); + globalScene.arenaPlayerTransition.setBiome(this.biomeType); + globalScene.arenaEnemy.setBiome(this.biomeType); + globalScene.arenaNextEnemy.setBiome(this.biomeType); + globalScene.arenaBg.setTexture(`${biomeKey}_bg`); + globalScene.arenaBgTransition.setTexture(`${biomeKey}_bg`); // Redo this on initialize because during save/load the current wave isn't always // set correctly during construction @@ -83,12 +83,12 @@ export class Arena { } randomSpecies(waveIndex: integer, level: integer, attempt?: integer, luckValue?: integer, isBoss?: boolean): PokemonSpecies { - const overrideSpecies = gScene.gameMode.getOverrideSpecies(waveIndex); + const overrideSpecies = globalScene.gameMode.getOverrideSpecies(waveIndex); if (overrideSpecies) { return overrideSpecies; } - const isBossSpecies = !!gScene.getEncounterBossSegments(waveIndex, level) && !!this.pokemonPool[BiomePoolTier.BOSS].length - && (this.biomeType !== Biome.END || gScene.gameMode.isClassic || gScene.gameMode.isWaveFinal(waveIndex)); + const isBossSpecies = !!globalScene.getEncounterBossSegments(waveIndex, level) && !!this.pokemonPool[BiomePoolTier.BOSS].length + && (this.biomeType !== Biome.END || globalScene.gameMode.isClassic || globalScene.gameMode.isWaveFinal(waveIndex)); const randVal = isBossSpecies ? 64 : 512; // luck influences encounter rarity let luckModifier = 0; @@ -108,7 +108,7 @@ export class Arena { let ret: PokemonSpecies; let regen = false; if (!tierPool.length) { - ret = gScene.randomSpecies(waveIndex, level); + ret = globalScene.randomSpecies(waveIndex, level); } else { const entry = tierPool[Utils.randSeedInt(tierPool.length)]; let species: Species; @@ -155,7 +155,7 @@ export class Arena { return this.randomSpecies(waveIndex, level, (attempt || 0) + 1); } - const newSpeciesId = ret.getWildSpeciesForLevel(level, true, isBoss ?? isBossSpecies, gScene.gameMode); + const newSpeciesId = ret.getWildSpeciesForLevel(level, true, isBoss ?? isBossSpecies, globalScene.gameMode); if (newSpeciesId !== ret.speciesId) { console.log("Replaced", Species[ret.speciesId], "with", Species[newSpeciesId]); ret = getPokemonSpecies(newSpeciesId); @@ -165,7 +165,7 @@ export class Arena { randomTrainerType(waveIndex: integer, isBoss: boolean = false): TrainerType { const isTrainerBoss = !!this.trainerPool[BiomePoolTier.BOSS].length - && (gScene.gameMode.isTrainerBoss(waveIndex, this.biomeType, gScene.offsetGym) || isBoss); + && (globalScene.gameMode.isTrainerBoss(waveIndex, this.biomeType, globalScene.offsetGym) || isBoss); console.log(isBoss, this.trainerPool); const tierValue = Utils.randSeedInt(!isTrainerBoss ? 512 : 64); let tier = !isTrainerBoss @@ -300,8 +300,8 @@ export class Arena { */ trySetWeatherOverride(weather: WeatherType): boolean { this.weather = new Weather(weather, 0); - gScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.SUNNY + (weather - 1))); - gScene.queueMessage(getWeatherStartMessage(weather)!); // TODO: is this bang correct? + globalScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.SUNNY + (weather - 1))); + globalScene.queueMessage(getWeatherStartMessage(weather)!); // TODO: is this bang correct? return true; } @@ -326,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) { - gScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.SUNNY + (weather - 1), true)); - gScene.queueMessage(getWeatherStartMessage(weather)!); // TODO: is this bang correct? + globalScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.SUNNY + (weather - 1), true)); + globalScene.queueMessage(getWeatherStartMessage(weather)!); // TODO: is this bang correct? } else { - gScene.queueMessage(getWeatherClearMessage(oldWeatherType)!); // TODO: is this bang correct? + globalScene.queueMessage(getWeatherClearMessage(oldWeatherType)!); // TODO: is this bang correct? } - gScene.getField(true).filter(p => p.isOnField()).map(pokemon => { + globalScene.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); }); @@ -344,13 +344,13 @@ export class Arena { * Function to trigger all weather based form changes */ triggerWeatherBasedFormChanges(): void { - gScene.getField(true).forEach( p => { + globalScene.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(p.getBattlerIndex()); - gScene.triggerPokemonFormChange(p, SpeciesFormChangeWeatherTrigger); + globalScene.triggerPokemonFormChange(p, SpeciesFormChangeWeatherTrigger); } }); } @@ -359,13 +359,13 @@ export class Arena { * Function to trigger all weather based form changes back into their normal forms */ triggerWeatherBasedFormChangesToNormal(): void { - gScene.getField(true).forEach( p => { + globalScene.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(p.getBattlerIndex()); - return gScene.triggerPokemonFormChange(p, SpeciesFormChangeRevertWeatherFormTrigger); + return globalScene.triggerPokemonFormChange(p, SpeciesFormChangeRevertWeatherFormTrigger); } }); } @@ -382,14 +382,14 @@ export class Arena { if (this.terrain) { if (!ignoreAnim) { - gScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.MISTY_TERRAIN + (terrain - 1))); + globalScene.unshiftPhase(new CommonAnimPhase(undefined, undefined, CommonAnim.MISTY_TERRAIN + (terrain - 1))); } - gScene.queueMessage(getTerrainStartMessage(terrain)!); // TODO: is this bang correct? + globalScene.queueMessage(getTerrainStartMessage(terrain)!); // TODO: is this bang correct? } else { - gScene.queueMessage(getTerrainClearMessage(oldTerrainType)!); // TODO: is this bang correct? + globalScene.queueMessage(getTerrainClearMessage(oldTerrainType)!); // TODO: is this bang correct? } - gScene.getField(true).filter(p => p.isOnField()).map(pokemon => { + globalScene.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); @@ -478,7 +478,7 @@ export class Arena { return TimeOfDay.NIGHT; } - const waveCycle = ((gScene.currentBattle?.waveIndex || 0) + gScene.waveCycleOffset) % 40; + const waveCycle = ((globalScene.currentBattle?.waveIndex || 0) + globalScene.waveCycleOffset) % 40; if (waveCycle < 15) { return TimeOfDay.DAY; @@ -748,7 +748,7 @@ export class Arena { } preloadBgm(): void { - gScene.loadBgm(this.bgm); + globalScene.loadBgm(this.bgm); } getBgmLoopPoint(): number { @@ -873,16 +873,16 @@ export class ArenaBase extends Phaser.GameObjects.Container { public props: Phaser.GameObjects.Sprite[]; constructor(player: boolean) { - super(gScene, 0, 0); + super(globalScene, 0, 0); this.player = player; - this.base = gScene.addFieldSprite(0, 0, "plains_a", undefined, 1); + this.base = globalScene.addFieldSprite(0, 0, "plains_a", undefined, 1); this.base.setOrigin(0, 0); this.props = !player ? new Array(3).fill(null).map(() => { - const ret = gScene.addFieldSprite(0, 0, "plains_b", undefined, 1); + const ret = globalScene.addFieldSprite(0, 0, "plains_b", undefined, 1); ret.setOrigin(0, 0); ret.setVisible(false); return ret; @@ -898,9 +898,9 @@ export class ArenaBase extends Phaser.GameObjects.Container { this.base.setTexture(baseKey); if (this.base.texture.frameTotal > 1) { - 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({ + const baseFrameNames = globalScene.anims.generateFrameNames(baseKey, { zeroPad: 4, suffix: ".png", start: 1, end: this.base.texture.frameTotal - 1 }); + if (!(globalScene.anims.exists(baseKey))) { + globalScene.anims.create({ key: baseKey, frames: baseFrameNames, frameRate: 12, @@ -916,7 +916,7 @@ export class ArenaBase extends Phaser.GameObjects.Container { } if (!this.player) { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { this.propValue = propValue === undefined ? hasProps ? Utils.randSeedInt(8) : 0 : propValue; @@ -925,9 +925,9 @@ export class ArenaBase extends Phaser.GameObjects.Container { prop.setTexture(propKey); if (hasProps && prop.texture.frameTotal > 1) { - 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({ + const propFrameNames = globalScene.anims.generateFrameNames(propKey, { zeroPad: 4, suffix: ".png", start: 1, end: prop.texture.frameTotal - 1 }); + if (!(globalScene.anims.exists(propKey))) { + globalScene.anims.create({ key: propKey, frames: propFrameNames, frameRate: 12, @@ -942,7 +942,7 @@ export class ArenaBase extends Phaser.GameObjects.Container { prop.setVisible(hasProps && !!(this.propValue & (1 << p))); this.add(prop); }); - }, gScene.currentBattle?.waveIndex || 0, gScene.waveSeed); + }, globalScene.currentBattle?.waveIndex || 0, globalScene.waveSeed); } } } diff --git a/src/field/damage-number-handler.ts b/src/field/damage-number-handler.ts index d594db0927e..0ad130a27b4 100644 --- a/src/field/damage-number-handler.ts +++ b/src/field/damage-number-handler.ts @@ -2,7 +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"; +import { globalScene } from "#app/battle-scene"; type TextAndShadowArr = [ string | null, string | null ]; @@ -14,13 +14,13 @@ export default class DamageNumberHandler { } add(target: Pokemon, amount: integer, result: DamageResult | HitResult.HEAL = HitResult.EFFECTIVE, critical: boolean = false): void { - if (!gScene?.damageNumbersMode) { + if (!globalScene?.damageNumbersMode) { return; } const battlerIndex = target.getBattlerIndex(); const baseScale = target.getSpriteScale() / 6; - const damageNumber = addTextObject(target.x, -(gScene.game.canvas.height / 6) + target.y - target.getSprite().height / 2, Utils.formatStat(amount, true), TextStyle.SUMMARY); + const damageNumber = addTextObject(target.x, -(globalScene.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); @@ -57,7 +57,7 @@ export default class DamageNumberHandler { } } - gScene.fieldUI.add(damageNumber); + globalScene.fieldUI.add(damageNumber); if (!this.damageNumbers.has(battlerIndex)) { this.damageNumbers.set(battlerIndex, []); @@ -70,14 +70,14 @@ export default class DamageNumberHandler { this.damageNumbers.get(battlerIndex)!.push(damageNumber); - if (gScene.damageNumbersMode === 1) { - gScene.tweens.add({ + if (globalScene.damageNumbersMode === 1) { + globalScene.tweens.add({ targets: damageNumber, duration: Utils.fixedInt(750), alpha: 1, y: "-=32" }); - gScene.tweens.add({ + globalScene.tweens.add({ delay: 375, targets: damageNumber, duration: Utils.fixedInt(625), @@ -93,7 +93,7 @@ export default class DamageNumberHandler { damageNumber.setAlpha(0); - gScene.tweens.chain({ + globalScene.tweens.chain({ targets: damageNumber, tweens: [ { diff --git a/src/field/mystery-encounter-intro.ts b/src/field/mystery-encounter-intro.ts index d55a924c099..c781d31d025 100644 --- a/src/field/mystery-encounter-intro.ts +++ b/src/field/mystery-encounter-intro.ts @@ -1,5 +1,5 @@ import { GameObjects } from "phaser"; -import BattleScene, { gScene } from "#app/battle-scene"; +import BattleScene, { globalScene } from "#app/battle-scene"; import MysteryEncounter from "../data/mystery-encounters/mystery-encounter"; import { Species } from "#enums/species"; import { isNullOrUndefined } from "#app/utils"; @@ -76,7 +76,7 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con public enterFromRight: boolean; constructor(encounter: MysteryEncounter) { - super(gScene, -72, 76); + super(globalScene, -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 = gScene.addFieldSprite(0, 0, spriteKey); + const ret = globalScene.addFieldSprite(0, 0, spriteKey); ret.setOrigin(0.5, 1); - ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow, yShadowOffset: yShadow ?? 0 }); + ret.setPipeline(globalScene.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 = gScene.add.sprite(-19, 2, "items", spriteKey); + const icon = globalScene.add.sprite(-19, 2, "items", spriteKey); icon.setOrigin(0.5, 1); - icon.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow, yShadowOffset: yShadow ?? 0 }); + icon.setPipeline(globalScene.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) { - gScene.loadPokemonAtlas(config.spriteKey, config.fileRoot); + globalScene.loadPokemonAtlas(config.spriteKey, config.fileRoot); } else if (config.isItem) { - gScene.loadAtlas("items", ""); + globalScene.loadAtlas("items", ""); } else { - gScene.loadAtlas(config.spriteKey, config.fileRoot); + globalScene.loadAtlas(config.spriteKey, config.fileRoot); } }); - gScene.load.once(Phaser.Loader.Events.COMPLETE, () => { + globalScene.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 = gScene.anims.generateFrameNames(config.spriteKey, { zeroPad: 4, suffix: ".png", start: 1, end: 128 }); + const frameNames = globalScene.anims.generateFrameNames(config.spriteKey, { zeroPad: 4, suffix: ".png", start: 1, end: 128 }); console.warn = originalWarn; - if (!(gScene.anims.exists(config.spriteKey))) { - gScene.anims.create({ + if (!(globalScene.anims.exists(config.spriteKey))) { + globalScene.anims.create({ key: config.spriteKey, frames: frameNames, frameRate: 12, @@ -223,8 +223,8 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con resolve(); }); - if (!gScene.load.isLoading()) { - gScene.load.start(); + if (!globalScene.load.isLoading()) { + globalScene.load.start(); } }); } @@ -374,7 +374,7 @@ export default class MysteryEncounterIntroVisuals extends Phaser.GameObjects.Con if (duration) { sprite.setAlpha(0); - gScene.tweens.add({ + globalScene.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) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: sprite, alpha: 0, duration: duration, diff --git a/src/field/pokemon-sprite-sparkle-handler.ts b/src/field/pokemon-sprite-sparkle-handler.ts index 3865941886b..7fc60cb126c 100644 --- a/src/field/pokemon-sprite-sparkle-handler.ts +++ b/src/field/pokemon-sprite-sparkle-handler.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import Pokemon from "./pokemon"; import * as Utils from "../utils"; @@ -8,7 +8,7 @@ export default class PokemonSpriteSparkleHandler { setup(): void { this.sprites = new Set(); - gScene.tweens.addCounter({ + globalScene.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 = gScene.addFieldSprite(((pokemon?.x || 0) + s.x + pixelX * ratioX + xOffset), ((pokemon?.y || 0) + s.y + pixelY * ratioY + yOffset), "tera_sparkle"); + const sparkle = globalScene.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"); diff --git a/src/field/pokemon.ts b/src/field/pokemon.ts index 47185c30d7d..cc4008d5abe 100644 --- a/src/field/pokemon.ts +++ b/src/field/pokemon.ts @@ -1,5 +1,5 @@ import Phaser from "phaser"; -import BattleScene, { AnySound, gScene } from "#app/battle-scene"; +import BattleScene, { AnySound, globalScene } from "#app/battle-scene"; import { Variant, VariantSet, variantColorCache } from "#app/data/variant"; import { variantData } from "#app/data/variant"; import BattleInfo, { PlayerBattleInfo, EnemyBattleInfo } from "#app/ui/battle-info"; @@ -136,7 +136,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { private shinySparkle: Phaser.GameObjects.Sprite; constructor(x: number, y: number, species: PokemonSpecies, level: integer, abilityIndex?: integer, formIndex?: integer, gender?: Gender, shiny?: boolean, variant?: Variant, ivs?: integer[], nature?: Nature, dataSource?: Pokemon | PokemonData) { - super(gScene, x, y); + super(globalScene, x, y); if (!species.isObtainable() && this.isPlayer()) { throw `Cannot create a player Pokemon for species '${species.getName(formIndex)}'`; @@ -144,7 +144,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const hiddenAbilityChance = new Utils.IntegerHolder(BASE_HIDDEN_ABILITY_CHANCE); if (!this.hasTrainer()) { - gScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); + globalScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); } this.species = species; @@ -222,7 +222,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } if (this.formIndex === undefined) { - this.formIndex = gScene.getSpeciesFormIndex(species, this.gender, this.nature, this.isPlayer()); + this.formIndex = globalScene.getSpeciesFormIndex(species, this.gender, this.nature, this.isPlayer()); } if (this.shiny === undefined) { @@ -243,15 +243,15 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { this.friendship = species.baseFriendship; this.metLevel = level; - this.metBiome = gScene.currentBattle ? gScene.arena.biomeType : -1; + this.metBiome = globalScene.currentBattle ? globalScene.arena.biomeType : -1; this.metSpecies = species.speciesId; - this.metWave = gScene.currentBattle ? gScene.currentBattle.waveIndex : -1; + this.metWave = globalScene.currentBattle ? globalScene.currentBattle.waveIndex : -1; this.pokerus = false; if (level > 1) { - const fused = new Utils.BooleanHolder(gScene.gameMode.isSplicedOnly); + const fused = new Utils.BooleanHolder(globalScene.gameMode.isSplicedOnly); if (!fused.value && !this.isPlayer() && !this.hasTrainer()) { - gScene.applyModifier(EnemyFusionChanceModifier, false, fused); + globalScene.applyModifier(EnemyFusionChanceModifier, false, fused); } if (fused.value) { @@ -292,12 +292,12 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { this.initBattleInfo(); - gScene.fieldUI.addAt(this.battleInfo, 0); + globalScene.fieldUI.addAt(this.battleInfo, 0); const getSprite = (hasShadow?: boolean) => { - const ret = gScene.addPokemonSprite(this, 0, 0, `pkmn__${this.isPlayer() ? "back__" : ""}sub`, undefined, true); + const ret = globalScene.addPokemonSprite(this, 0, 0, `pkmn__${this.isPlayer() ? "back__" : ""}sub`, undefined, true); ret.setOrigin(0.5, 1); - ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow, teraColor: getTypeRgb(this.getTeraType()) }); + ret.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow, teraColor: getTypeRgb(this.getTeraType()) }); return ret; }; @@ -319,10 +319,10 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { abstract initBattleInfo(): void; isOnField(): boolean { - if (!gScene) { + if (!globalScene) { return false; } - return gScene.field.getIndex(this) > -1; + return globalScene.field.getIndex(this) > -1; } isFainted(checkStatus?: boolean): boolean { @@ -345,15 +345,15 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { */ isAllowed(): boolean { const challengeAllowed = new Utils.BooleanHolder(true); - applyChallenges(gScene.gameMode, ChallengeType.POKEMON_IN_BATTLE, this, challengeAllowed); + applyChallenges(globalScene.gameMode, ChallengeType.POKEMON_IN_BATTLE, this, challengeAllowed); return challengeAllowed.value; } isActive(onField?: boolean): boolean { - if (!gScene) { + if (!globalScene) { return false; } - return this.isAllowedInBattle() && !!gScene && (!onField || this.isOnField()); + return this.isAllowedInBattle() && !!globalScene && (!onField || this.isOnField()); } getDexAttr(): bigint { @@ -361,7 +361,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { ret |= this.gender !== Gender.FEMALE ? DexAttr.MALE : DexAttr.FEMALE; ret |= !this.shiny ? DexAttr.NON_SHINY : DexAttr.SHINY; ret |= this.variant >= 2 ? DexAttr.VARIANT_3 : this.variant === 1 ? DexAttr.VARIANT_2 : DexAttr.DEFAULT_VARIANT; - ret |= gScene.gameData.getFormAttr(this.formIndex); + ret |= globalScene.gameData.getFormAttr(this.formIndex); return ret; } @@ -397,21 +397,21 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { loadMoveAnimAssets(moveIds); this.getSpeciesForm().loadAssets(this.getGender() === Gender.FEMALE, this.formIndex, this.shiny, this.variant); if (this.isPlayer() || this.getFusionSpeciesForm()) { - gScene.loadPokemonAtlas(this.getBattleSpriteKey(true, ignoreOverride), this.getBattleSpriteAtlasPath(true, ignoreOverride)); + globalScene.loadPokemonAtlas(this.getBattleSpriteKey(true, ignoreOverride), this.getBattleSpriteAtlasPath(true, ignoreOverride)); } if (this.getFusionSpeciesForm()) { this.getFusionSpeciesForm().loadAssets(this.getFusionGender() === Gender.FEMALE, this.fusionFormIndex, this.fusionShiny, this.fusionVariant); - gScene.loadPokemonAtlas(this.getFusionBattleSpriteKey(true, ignoreOverride), this.getFusionBattleSpriteAtlasPath(true, ignoreOverride)); + globalScene.loadPokemonAtlas(this.getFusionBattleSpriteKey(true, ignoreOverride), this.getFusionBattleSpriteAtlasPath(true, ignoreOverride)); } - gScene.load.once(Phaser.Loader.Events.COMPLETE, () => { + globalScene.load.once(Phaser.Loader.Events.COMPLETE, () => { if (this.isPlayer()) { const originalWarn = console.warn; // Ignore warnings for missing frames, because there will be a lot console.warn = () => {}; - const battleFrameNames = gScene.anims.generateFrameNames(this.getBattleSpriteKey(), { zeroPad: 4, suffix: ".png", start: 1, end: 400 }); + const battleFrameNames = globalScene.anims.generateFrameNames(this.getBattleSpriteKey(), { zeroPad: 4, suffix: ".png", start: 1, end: 400 }); console.warn = originalWarn; - if (!(gScene.anims.exists(this.getBattleSpriteKey()))) { - gScene.anims.create({ + if (!(globalScene.anims.exists(this.getBattleSpriteKey()))) { + globalScene.anims.create({ key: this.getBattleSpriteKey(), frames: battleFrameNames, frameRate: 12, @@ -432,14 +432,14 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { return new Promise(resolve => { const battleSpritePath = this.getBattleSpriteAtlasPath(back, ignoreOverride).replace("variant/", "").replace(/_[1-3]$/, ""); let config = variantData; - const useExpSprite = gScene.experimentalSprites && gScene.hasExpSprite(this.getBattleSpriteKey(back, ignoreOverride)); + const useExpSprite = globalScene.experimentalSprites && globalScene.hasExpSprite(this.getBattleSpriteKey(back, ignoreOverride)); battleSpritePath.split("/").map(p => config ? config = config[p] : null); const variantSet: VariantSet = config as VariantSet; if (variantSet && variantSet[this.variant] === 1) { if (variantColorCache.hasOwnProperty(key)) { return resolve(); } - gScene.cachedFetch(`./images/pokemon/variant/${useExpSprite ? "exp/" : ""}${battleSpritePath}.json`). + globalScene.cachedFetch(`./images/pokemon/variant/${useExpSprite ? "exp/" : ""}${battleSpritePath}.json`). then(res => { // Prevent the JSON from processing if it failed to load if (!res.ok) { @@ -465,8 +465,8 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { updateFusionPaletteAndResolve(); } }); - if (!gScene.load.isLoading()) { - gScene.load.start(); + if (!globalScene.load.isLoading()) { + globalScene.load.start(); } }); }); @@ -612,10 +612,10 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } getHeldItems(): PokemonHeldItemModifier[] { - if (!gScene) { + if (!globalScene) { return []; } - return gScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === this.id, this.isPlayer()) as PokemonHeldItemModifier[]; + return globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === this.id, this.isPlayer()) as PokemonHeldItemModifier[]; } updateScale(): void { @@ -630,12 +630,12 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { initShinySparkle(): void { const keySuffix = this.variant ? `_${this.variant + 1}` : ""; const key = `shiny${keySuffix}`; - const shinySparkle = gScene.addFieldSprite(0, 0, key); + const shinySparkle = globalScene.addFieldSprite(0, 0, key); shinySparkle.setVisible(false); shinySparkle.setOrigin(0.5, 1); - const frameNames = gScene.anims.generateFrameNames(key, { suffix: ".png", end: 34 }); - if (!(gScene.anims.exists(`sparkle${keySuffix}`))) { - gScene.anims.create({ + const frameNames = globalScene.anims.generateFrameNames(key, { suffix: ".png", end: 34 }); + if (!(globalScene.anims.exists(`sparkle${keySuffix}`))) { + globalScene.anims.create({ key: `sparkle${keySuffix}`, frames: frameNames, frameRate: 32, @@ -708,7 +708,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } // During the Pokemon's MoveEffect phase, the offset is removed to put the Pokemon "in focus" - const currentPhase = gScene.getCurrentPhase(); + const currentPhase = globalScene.getCurrentPhase(); if (currentPhase instanceof MoveEffectPhase && currentPhase.getPokemon() === this) { return false; } @@ -753,7 +753,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (subTag?.sprite) { targets.push(subTag.sprite); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: targets, x: (_target, _key, value: number) => value + relX, y: (_target, _key, value: number) => value + relY, @@ -859,8 +859,8 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { getCritStage(source: Pokemon, move: Move): number { const critStage = new Utils.IntegerHolder(0); applyMoveAttrs(HighCritAttr, source, this, move, critStage); - gScene.applyModifiers(CritBoosterModifier, source.isPlayer(), source, critStage); - gScene.applyModifiers(TempCritBoosterModifier, source.isPlayer(), critStage); + globalScene.applyModifiers(CritBoosterModifier, source.isPlayer(), source, critStage); + globalScene.applyModifiers(TempCritBoosterModifier, source.isPlayer(), critStage); const bonusCrit = new Utils.BooleanHolder(false); //@ts-ignore if (applyAbAttrs(BonusCritAbAttr, source, null, false, bonusCrit)) { // TODO: resolve ts-ignore. This is a promise. Checking a promise is bogus. @@ -896,11 +896,11 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { */ getEffectiveStat(stat: EffectiveStat, opponent?: Pokemon, move?: Move, ignoreAbility: boolean = false, ignoreOppAbility: boolean = false, isCritical: boolean = false, simulated: boolean = true): integer { const statValue = new Utils.NumberHolder(this.getStat(stat, false)); - gScene.applyModifiers(StatBoosterModifier, this.isPlayer(), this, stat, statValue); + globalScene.applyModifiers(StatBoosterModifier, this.isPlayer(), this, stat, statValue); // The Ruin abilities here are never ignored, but they reveal themselves on summon anyway const fieldApplied = new Utils.BooleanHolder(false); - for (const pokemon of gScene.getField(true)) { + for (const pokemon of globalScene.getField(true)) { applyFieldStatMultiplierAbAttrs(FieldMultiplyStatAbAttr, pokemon, stat, statValue, this, fieldApplied, simulated); if (fieldApplied.value) { break; @@ -919,23 +919,23 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } break; case Stat.DEF: - if (this.isOfType(Type.ICE) && gScene.arena.weather?.weatherType === WeatherType.SNOW) { + if (this.isOfType(Type.ICE) && globalScene.arena.weather?.weatherType === WeatherType.SNOW) { ret *= 1.5; } break; case Stat.SPATK: break; case Stat.SPDEF: - if (this.isOfType(Type.ROCK) && gScene.arena.weather?.weatherType === WeatherType.SANDSTORM) { + if (this.isOfType(Type.ROCK) && globalScene.arena.weather?.weatherType === WeatherType.SANDSTORM) { ret *= 1.5; } break; case Stat.SPD: const side = this.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - if (gScene.arena.getTagOnSide(ArenaTagType.TAILWIND, side)) { + if (globalScene.arena.getTagOnSide(ArenaTagType.TAILWIND, side)) { ret *= 2; } - if (gScene.arena.getTagOnSide(ArenaTagType.GRASS_WATER_PLEDGE, side)) { + if (globalScene.arena.getTagOnSide(ArenaTagType.GRASS_WATER_PLEDGE, side)) { ret >>= 2; } @@ -968,7 +968,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const statHolder = new Utils.IntegerHolder(Math.floor(((2 * baseStats[s] + this.ivs[s]) * this.level) * 0.01)); if (s === Stat.HP) { statHolder.value = statHolder.value + this.level + 10; - gScene.applyModifier(PokemonIncrementingStatModifier, this.isPlayer(), this, s, statHolder); + globalScene.applyModifier(PokemonIncrementingStatModifier, this.isPlayer(), this, s, statHolder); if (this.hasAbility(Abilities.WONDER_GUARD, false, true)) { statHolder.value = 1; } @@ -983,11 +983,11 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } else { statHolder.value += 5; const natureStatMultiplier = new Utils.NumberHolder(getNatureStatMultiplier(this.getNature(), s)); - gScene.applyModifier(PokemonNatureWeightModifier, this.isPlayer(), this, natureStatMultiplier); + globalScene.applyModifier(PokemonNatureWeightModifier, this.isPlayer(), this, natureStatMultiplier); if (natureStatMultiplier.value !== 1) { statHolder.value = Math.max(Math[natureStatMultiplier.value > 1 ? "ceil" : "floor"](statHolder.value * natureStatMultiplier.value), 1); } - gScene.applyModifier(PokemonIncrementingStatModifier, this.isPlayer(), this, s, statHolder); + globalScene.applyModifier(PokemonIncrementingStatModifier, this.isPlayer(), this, s, statHolder); } statHolder.value = Phaser.Math.Clamp(statHolder.value, 1, Number.MAX_SAFE_INTEGER); @@ -999,21 +999,21 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { calculateBaseStats(): number[] { const baseStats = this.getSpeciesForm(true).baseStats.slice(0); // Shuckle Juice - gScene.applyModifiers(PokemonBaseStatTotalModifier, this.isPlayer(), this, baseStats); + globalScene.applyModifiers(PokemonBaseStatTotalModifier, this.isPlayer(), this, baseStats); // Old Gateau - gScene.applyModifiers(PokemonBaseStatFlatModifier, this.isPlayer(), this, baseStats); + globalScene.applyModifiers(PokemonBaseStatFlatModifier, this.isPlayer(), this, baseStats); if (this.isFusion()) { const fusionBaseStats = this.getFusionSpeciesForm(true).baseStats; for (const s of PERMANENT_STATS) { baseStats[s] = Math.ceil((baseStats[s] + fusionBaseStats[s]) / 2); } - } else if (gScene.gameMode.isSplicedOnly) { + } else if (globalScene.gameMode.isSplicedOnly) { for (const s of PERMANENT_STATS) { baseStats[s] = Math.ceil(baseStats[s] / 2); } } // Vitamins - gScene.applyModifiers(BaseStatModifier, this.isPlayer(), this, baseStats); + globalScene.applyModifiers(BaseStatModifier, this.isPlayer(), this, baseStats); return baseStats; } @@ -1142,7 +1142,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const species = this.metSpecies in speciesEggMoves ? this.metSpecies : this.getSpeciesForm(true).getRootSpeciesId(true); if (species in speciesEggMoves) { for (let i = 0; i < 4; i++) { - if (gScene.gameData.starterData[species].eggMoves & (1 << i)) { + if (globalScene.gameData.starterData[species].eggMoves & (1 << i)) { moves.push(speciesEggMoves[species][i]); } } @@ -1161,7 +1161,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { */ getLearnableLevelMoves(): Moves[] { let levelMoves = this.getLevelMoves(1, true, false, true).map(lm => lm[1]); - if (this.metBiome === -1 && !gScene.gameMode.isFreshStartChallenge() && !gScene.gameMode.isDaily) { + if (this.metBiome === -1 && !globalScene.gameMode.isFreshStartChallenge() && !globalScene.gameMode.isDaily) { levelMoves = this.getUnlockedEggMoves().concat(levelMoves); } if (Array.isArray(this.usedTMs) && this.usedTMs.length > 0) { @@ -1244,9 +1244,6 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } } - // gScene potentially can be undefined for a fainted pokemon in doubles - // use optional chaining to avoid runtime errors - if (!types.length) { // become UNKNOWN if no types are present types.push(Type.UNKNOWN); } @@ -1373,7 +1370,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } // Classic Final boss and Endless Minor/Major bosses do not have passive - const { currentBattle, gameMode } = gScene; + const { currentBattle, gameMode } = globalScene; const waveIndex = currentBattle?.waveIndex; if (this instanceof EnemyPokemon && (currentBattle?.battleSpec === BattleSpec.FINAL_BOSS || @@ -1400,7 +1397,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (this.isFusion() && ability.hasAttr(NoFusionAbilityAbAttr)) { return false; } - const arena = gScene?.arena; + const arena = globalScene?.arena; if (arena.ignoreAbilities && arena.ignoringEffectSource !== this.getBattlerIndex() && ability.isIgnorable) { return false; } @@ -1409,7 +1406,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } if (this.isOnField() && !ability.hasAttr(SuppressFieldAbilitiesAbAttr)) { const suppressed = new Utils.BooleanHolder(false); - gScene.getField(true).filter(p => p !== this).map(p => { + globalScene.getField(true).filter(p => p !== this).map(p => { if (p.getAbility().hasAttr(SuppressFieldAbilitiesAbAttr) && p.canApplyAbility()) { p.getAbility().getAttrs(SuppressFieldAbilitiesAbAttr).map(a => a.apply(this, false, false, suppressed, [ ability ])); } @@ -1483,21 +1480,19 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } /** - * Gets the tera-formed type of the pokemon, or UNKNOWN if not present - * @returns the {@linkcode Type} + * @returns the pokemon's current tera {@linkcode Type}, or `Type.UNKNOWN` if the pokemon is not terastallized */ getTeraType(): Type { - // gScene can be undefined for a fainted mon in doubles - if (gScene !== undefined) { - const teraModifier = gScene.findModifier(m => m instanceof TerastallizeModifier - && m.pokemonId === this.id && !!m.getBattlesLeft(), this.isPlayer()) as TerastallizeModifier; - // return teraType - if (teraModifier) { - return teraModifier.teraType; - } + // I don't think this should be possible anymore, please report if you encounter this. --NightKev + if (globalScene === undefined) { + console.warn("Pokemon.getTeraType(): Global scene is not defined!"); + return Type.UNKNOWN; } - // if scene is undefined, or if teraModifier is considered false, then return unknown type - return Type.UNKNOWN; + const teraModifier = globalScene.findModifier(m => + m instanceof TerastallizeModifier + && m.pokemonId === this.id + && m.getBattlesLeft() > 0, this.isPlayer()) as TerastallizeModifier; + return teraModifier?.teraType ?? Type.UNKNOWN; } isTerastallized(): boolean { @@ -1522,7 +1517,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } const trappedByAbility = new Utils.BooleanHolder(false); - const opposingField = this.isPlayer() ? gScene.getEnemyField() : gScene.getPlayerField(); + const opposingField = this.isPlayer() ? globalScene.getEnemyField() : globalScene.getPlayerField(); opposingField.forEach(opponent => applyCheckTrappedAbAttrs(CheckTrappedAbAttr, opponent, trappedByAbility, this, trappedAbMessages, simulated) @@ -1544,7 +1539,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { applyMoveAttrs(VariableMoveTypeAttr, this, null, move, moveTypeHolder); applyPreAttackAbAttrs(MoveTypeChangeAbAttr, this, null, move, simulated, moveTypeHolder); - gScene.arena.applyTags(ArenaTagType.ION_DELUGE, simulated, moveTypeHolder); + globalScene.arena.applyTags(ArenaTagType.ION_DELUGE, simulated, moveTypeHolder); if (this.getTag(BattlerTagType.ELECTRIFIED)) { moveTypeHolder.value = Type.ELECTRIC; } @@ -1596,7 +1591,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } if (!cancelledHolder.value) { - const defendingSidePlayField = this.isPlayer() ? gScene.getPlayerField() : gScene.getEnemyField(); + const defendingSidePlayField = this.isPlayer() ? globalScene.getPlayerField() : globalScene.getEnemyField(); defendingSidePlayField.forEach((p) => applyPreDefendAbAttrs(FieldPriorityMoveImmunityAbAttr, p, source, move, cancelledHolder)); } } @@ -1634,7 +1629,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { return this.isTerastallized() ? 2 : 1; } const types = this.getTypes(true, true); - const arena = gScene.arena; + const arena = globalScene.arena; // Handle flying v ground type immunity without removing flying type so effective types are still effective // Related to https://github.com/pagefaultgames/pokerogue/issues/524 @@ -1647,7 +1642,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { let multiplier = types.map(defType => { const multiplier = new Utils.NumberHolder(getTypeDamageMultiplier(moveType, defType)); - applyChallenges(gScene.gameMode, ChallengeType.TYPE_EFFECTIVENESS, multiplier); + applyChallenges(globalScene.gameMode, ChallengeType.TYPE_EFFECTIVENESS, multiplier); if (source) { const ignoreImmunity = new Utils.BooleanHolder(false); if (source.isActive(true) && source.hasAbilityWithAttr(IgnoreTypeImmunityAbAttr)) { @@ -1670,12 +1665,12 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { }).reduce((acc, cur) => acc * cur, 1) as TypeDamageMultiplier; const typeMultiplierAgainstFlying = new Utils.NumberHolder(getTypeDamageMultiplier(moveType, Type.FLYING)); - applyChallenges(gScene.gameMode, ChallengeType.TYPE_EFFECTIVENESS, typeMultiplierAgainstFlying); + applyChallenges(globalScene.gameMode, ChallengeType.TYPE_EFFECTIVENESS, typeMultiplierAgainstFlying); // Handle strong winds lowering effectiveness of types super effective against pure flying if (!ignoreStrongWinds && arena.weather?.weatherType === WeatherType.STRONG_WINDS && !arena.weather.isEffectSuppressed() && this.isOfType(Type.FLYING) && typeMultiplierAgainstFlying.value === 2) { multiplier /= 2; if (!simulated) { - gScene.queueMessage(i18next.t("weather:strongWindsEffectMessage")); + globalScene.queueMessage(i18next.t("weather:strongWindsEffectMessage")); } } return multiplier as TypeDamageMultiplier; @@ -1868,23 +1863,23 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { */ trySetShiny(thresholdOverride?: integer): boolean { // Shiny Pokemon should not spawn in the end biome in endless - if (gScene.gameMode.isEndless && gScene.arena.biomeType === Biome.END) { + if (globalScene.gameMode.isEndless && globalScene.arena.biomeType === Biome.END) { return false; } const rand1 = (this.id & 0xFFFF0000) >>> 16; const rand2 = (this.id & 0x0000FFFF); - const E = gScene.gameData.trainerId ^ gScene.gameData.secretId; + const E = globalScene.gameData.trainerId ^ globalScene.gameData.secretId; const F = rand1 ^ rand2; const shinyThreshold = new Utils.IntegerHolder(BASE_SHINY_CHANCE); if (thresholdOverride === undefined) { - if (gScene.eventManager.isEventActive()) { - shinyThreshold.value *= gScene.eventManager.getShinyMultiplier(); + if (globalScene.eventManager.isEventActive()) { + shinyThreshold.value *= globalScene.eventManager.getShinyMultiplier(); } if (!this.hasTrainer()) { - gScene.applyModifiers(ShinyRateBoosterModifier, true, shinyThreshold); + globalScene.applyModifiers(ShinyRateBoosterModifier, true, shinyThreshold); } } else { shinyThreshold.value = thresholdOverride; @@ -1914,11 +1909,11 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (thresholdOverride !== undefined && applyModifiersToOverride) { shinyThreshold.value = thresholdOverride; } - if (gScene.eventManager.isEventActive()) { - shinyThreshold.value *= gScene.eventManager.getShinyMultiplier(); + if (globalScene.eventManager.isEventActive()) { + shinyThreshold.value *= globalScene.eventManager.getShinyMultiplier(); } if (!this.hasTrainer()) { - gScene.applyModifiers(ShinyRateBoosterModifier, true, shinyThreshold); + globalScene.applyModifiers(ShinyRateBoosterModifier, true, shinyThreshold); } } else { shinyThreshold.value = thresholdOverride; @@ -1954,9 +1949,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { return 0; } const rand = new Utils.NumberHolder(0); - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { rand.value = Utils.randSeedInt(10); - }, this.id, gScene.waveSeed); + }, this.id, globalScene.waveSeed); if (rand.value >= SHINY_VARIANT_CHANCE) { return 0; // 6/10 } else if (rand.value >= SHINY_EPIC_CHANCE) { @@ -1969,7 +1964,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { generateFusionSpecies(forStarter?: boolean): void { const hiddenAbilityChance = new Utils.IntegerHolder(BASE_HIDDEN_ABILITY_CHANCE); if (!this.hasTrainer()) { - gScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); + globalScene.applyModifiers(HiddenAbilityRateBoosterModifier, true, hiddenAbilityChance); } const hasHiddenAbility = !Utils.randSeedInt(hiddenAbilityChance.value); @@ -1994,7 +1989,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { fusionOverride = getPokemonSpecies(Overrides.OPP_FUSION_SPECIES_OVERRIDE); } - this.fusionSpecies = fusionOverride ?? gScene.randomSpecies(gScene.currentBattle?.waveIndex || 0, this.level, false, filter, true); + this.fusionSpecies = fusionOverride ?? globalScene.randomSpecies(globalScene.currentBattle?.waveIndex || 0, this.level, false, filter, true); this.fusionAbilityIndex = (this.fusionSpecies.abilityHidden && hasHiddenAbility ? 2 : this.fusionSpecies.ability2 !== this.fusionSpecies.ability1 ? randAbilityIndex : 0); this.fusionShiny = this.shiny; this.fusionVariant = this.variant; @@ -2010,7 +2005,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } } - this.fusionFormIndex = gScene.getSpeciesFormIndex(this.fusionSpecies, this.fusionGender, this.getNature(), true); + this.fusionFormIndex = globalScene.getSpeciesFormIndex(this.fusionSpecies, this.fusionGender, this.getNature(), true); this.fusionLuck = this.luck; this.generateName(); @@ -2194,8 +2189,8 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } // Trigger FormChange, except for enemy Pokemon during Mystery Encounters, to avoid crashes - if (this.isPlayer() || !gScene.currentBattle?.isBattleMysteryEncounter() || !gScene.currentBattle?.mysteryEncounter) { - gScene.triggerPokemonFormChange(this, SpeciesFormChangeMoveLearnedTrigger); + if (this.isPlayer() || !globalScene.currentBattle?.isBattleMysteryEncounter() || !globalScene.currentBattle?.mysteryEncounter) { + globalScene.triggerPokemonFormChange(this, SpeciesFormChangeMoveLearnedTrigger); } } @@ -2208,19 +2203,19 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { showInfo(): void { if (!this.battleInfo.visible) { - const otherBattleInfo = gScene.fieldUI.getAll().slice(0, 4).filter(ui => ui instanceof BattleInfo && ((ui as BattleInfo) instanceof PlayerBattleInfo) === this.isPlayer()).find(() => true); + const otherBattleInfo = globalScene.fieldUI.getAll().slice(0, 4).filter(ui => ui instanceof BattleInfo && ((ui as BattleInfo) instanceof PlayerBattleInfo) === this.isPlayer()).find(() => true); if (!otherBattleInfo || !this.getFieldIndex()) { - gScene.fieldUI.sendToBack(this.battleInfo); - gScene.sendTextToBack(); // Push the top right text objects behind everything else + globalScene.fieldUI.sendToBack(this.battleInfo); + globalScene.sendTextToBack(); // Push the top right text objects behind everything else } else { - gScene.fieldUI.moveAbove(this.battleInfo, otherBattleInfo); + globalScene.fieldUI.moveAbove(this.battleInfo, otherBattleInfo); } this.battleInfo.setX(this.battleInfo.x + (this.isPlayer() ? 150 : !this.isBoss() ? -150 : -198)); this.battleInfo.setVisible(true); if (this.isPlayer()) { this.battleInfo.expMaskRect.x += 150; } - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.battleInfo, this.battleInfo.expMaskRect ], x: this.isPlayer() ? "-=150" : `+=${!this.isBoss() ? 150 : 246}`, duration: 1000, @@ -2232,7 +2227,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { hideInfo(): Promise { return new Promise(resolve => { if (this.battleInfo && this.battleInfo.visible) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.battleInfo, this.battleInfo.expMaskRect ], x: this.isPlayer() ? "+=150" : `-=${!this.isBoss() ? 150 : 246}`, duration: 500, @@ -2281,7 +2276,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } addExp(exp: integer) { - const maxExpLevel = gScene.getMaxExpLevel(); + const maxExpLevel = globalScene.getMaxExpLevel(); const initialExp = this.exp; this.exp += exp; while (this.level < maxExpLevel && this.exp >= getLevelTotalExp(this.level + 1, this.species.growthRate)) { @@ -2312,7 +2307,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } getOpponents(): Pokemon[] { - return ((this.isPlayer() ? gScene.getEnemyField() : gScene.getPlayerField()) as Pokemon[]).filter(p => p.isActive()); + return ((this.isPlayer() ? globalScene.getEnemyField() : globalScene.getPlayerField()) as Pokemon[]).filter(p => p.isActive()); } getOpponentDescriptor(): string { @@ -2324,7 +2319,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } getAlly(): Pokemon { - return (this.isPlayer() ? gScene.getPlayerField() : gScene.getEnemyField())[this.getFieldIndex() ? 0 : 1]; + return (this.isPlayer() ? globalScene.getPlayerField() : globalScene.getEnemyField())[this.getFieldIndex() ? 0 : 1]; } /** @@ -2333,7 +2328,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { * @returns An array of Pokémon on the allied field. */ getAlliedField(): Pokemon[] { - return this instanceof PlayerPokemon ? gScene.getPlayerField() : gScene.getEnemyField(); + return this instanceof PlayerPokemon ? globalScene.getPlayerField() : globalScene.getEnemyField(); } /** @@ -2376,7 +2371,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (!ignoreStatStage.value) { const statStageMultiplier = new Utils.NumberHolder(Math.max(2, 2 + statStage.value) / Math.max(2, 2 - statStage.value)); - gScene.applyModifiers(TempStatStageBoosterModifier, this.isPlayer(), stat, statStageMultiplier); + globalScene.applyModifiers(TempStatStageBoosterModifier, this.isPlayer(), stat, statStageMultiplier); return Math.min(statStageMultiplier.value, 4); } return 1; @@ -2408,7 +2403,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { applyAbAttrs(IgnoreOpponentStatStagesAbAttr, this, null, false, Stat.EVA, ignoreEvaStatStage); applyMoveAttrs(IgnoreOpponentStatStagesAttr, this, target, sourceMove, ignoreEvaStatStage); - gScene.applyModifiers(TempStatStageBoosterModifier, this.isPlayer(), Stat.ACC, userAccStage); + globalScene.applyModifiers(TempStatStageBoosterModifier, this.isPlayer(), Stat.ACC, userAccStage); userAccStage.value = ignoreAccStatStage.value ? 0 : Math.min(userAccStage.value, 6); targetEvaStage.value = ignoreEvaStatStage.value ? 0 : targetEvaStage.value; @@ -2520,7 +2515,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const isPhysical = moveCategory === MoveCategory.PHYSICAL; /** Combined damage multiplier from field effects such as weather, terrain, etc. */ - const arenaAttackTypeMultiplier = new Utils.NumberHolder(gScene.arena.getAttackTypeMultiplier(moveType, source.isGrounded())); + const arenaAttackTypeMultiplier = new Utils.NumberHolder(globalScene.arena.getAttackTypeMultiplier(moveType, source.isGrounded())); applyMoveAttrs(IgnoreWeatherTypeDebuffAttr, source, this, move, arenaAttackTypeMultiplier); const isTypeImmune = (typeMultiplier * arenaAttackTypeMultiplier.value) === 0; @@ -2623,7 +2618,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { /** Reduces damage if this Pokemon has a relevant screen (e.g. Light Screen for special attacks) */ const screenMultiplier = new Utils.NumberHolder(1); - gScene.arena.applyTagsForSide(WeakenMoveScreenTag, defendingSide, simulated, source, moveCategory, screenMultiplier); + globalScene.arena.applyTagsForSide(WeakenMoveScreenTag, defendingSide, simulated, source, moveCategory, screenMultiplier); /** * For each {@linkcode HitsTagAttr} the move has, doubles the damage of the move if: @@ -2639,7 +2634,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { }); /** Halves damage if this Pokemon is grounded in Misty Terrain against a Dragon-type attack */ - const mistyTerrainMultiplier = (gScene.arena.terrain?.terrainType === TerrainType.MISTY && this.isGrounded() && moveType === Type.DRAGON) + const mistyTerrainMultiplier = (globalScene.arena.terrain?.terrainType === TerrainType.MISTY && this.isGrounded() && moveType === Type.DRAGON) ? 0.5 : 1; @@ -2666,10 +2661,10 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { /** Apply the enemy's Damage and Resistance tokens */ if (!source.isPlayer()) { - gScene.applyModifiers(EnemyDamageBoosterModifier, false, damage); + globalScene.applyModifiers(EnemyDamageBoosterModifier, false, damage); } if (!this.isPlayer()) { - gScene.applyModifiers(EnemyDamageReducerModifier, false, damage); + globalScene.applyModifiers(EnemyDamageReducerModifier, false, damage); } @@ -2678,7 +2673,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { applyPreDefendAbAttrs(ReceivedMoveDamageMultiplierAbAttr, this, source, move, cancelled, simulated, damage); /** Additionally apply friend guard damage reduction if ally has it. */ - if (gScene.currentBattle.double && this.getAlly()?.isActive(true)) { + if (globalScene.currentBattle.double && this.getAlly()?.isActive(true)) { applyPreDefendAbAttrs(AlliedFieldDamageReductionAbAttr, this.getAlly(), source, move, cancelled, simulated, damage); } } @@ -2726,7 +2721,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const typeMultiplier = this.getMoveEffectiveness(source, move, false, false, cancelled); if (!cancelled.value && typeMultiplier === 0) { - gScene.queueMessage(i18next.t("battle:hitResultNoEffect", { pokemonName: getPokemonNameWithAffix(this) })); + globalScene.queueMessage(i18next.t("battle:hitResultNoEffect", { pokemonName: getPokemonNameWithAffix(this) })); } return (typeMultiplier === 0) ? HitResult.NO_EFFECT : HitResult.STATUS; } else { @@ -2740,10 +2735,10 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { isCritical = true; } else { const critChance = [ 24, 8, 2, 1 ][Math.max(0, Math.min(this.getCritStage(source, move), 3))]; - isCritical = critChance === 1 || !gScene.randBattleSeedInt(critChance); + isCritical = critChance === 1 || !globalScene.randBattleSeedInt(critChance); } - const noCritTag = gScene.arena.getTagOnSide(NoCritTag, defendingSide); + const noCritTag = globalScene.arena.getTagOnSide(NoCritTag, defendingSide); const blockCrit = new Utils.BooleanHolder(false); applyAbAttrs(BlockCritAbAttr, this, null, false, blockCrit); if (noCritTag || blockCrit.value || Overrides.NEVER_CRIT_OVERRIDE) { @@ -2762,9 +2757,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (!cancelled) { if (result === HitResult.IMMUNE) { - gScene.queueMessage(i18next.t("battle:hitResultImmune", { pokemonName: getPokemonNameWithAffix(this) })); + globalScene.queueMessage(i18next.t("battle:hitResultImmune", { pokemonName: getPokemonNameWithAffix(this) })); } else { - gScene.queueMessage(i18next.t("battle:hitResultNoEffect", { pokemonName: getPokemonNameWithAffix(this) })); + globalScene.queueMessage(i18next.t("battle:hitResultNoEffect", { pokemonName: getPokemonNameWithAffix(this) })); } } return result; @@ -2784,7 +2779,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { substitute.hp -= dmg; } if (!this.isPlayer() && dmg >= this.hp) { - gScene.applyModifiers(EnemyEndureChanceModifier, false, this); + globalScene.applyModifiers(EnemyEndureChanceModifier, false, this); } /** @@ -2795,9 +2790,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (damage > 0) { if (source.isPlayer()) { - gScene.validateAchvs(DamageAchv, new Utils.NumberHolder(damage)); - if (damage > gScene.gameData.gameStats.highestDamage) { - gScene.gameData.gameStats.highestDamage = damage; + globalScene.validateAchvs(DamageAchv, new Utils.NumberHolder(damage)); + if (damage > globalScene.gameData.gameStats.highestDamage) { + globalScene.gameData.gameStats.highestDamage = damage; } } source.turnData.damageDealt += damage; @@ -2807,38 +2802,38 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const attackResult = { move: move.id, result: result as DamageResult, damage: damage, critical: isCritical, sourceId: source.id, sourceBattlerIndex: source.getBattlerIndex() }; this.turnData.attacksReceived.unshift(attackResult); if (source.isPlayer() && !this.isPlayer()) { - gScene.applyModifiers(DamageMoneyRewardModifier, true, source, new Utils.NumberHolder(damage)); + globalScene.applyModifiers(DamageMoneyRewardModifier, true, source, new Utils.NumberHolder(damage)); } } } if (isCritical) { - gScene.queueMessage(i18next.t("battle:hitResultCriticalHit")); + globalScene.queueMessage(i18next.t("battle:hitResultCriticalHit")); } // want to include is.Fainted() in case multi hit move ends early, still want to render message if (source.turnData.hitsLeft === 1 || this.isFainted()) { switch (result) { case HitResult.SUPER_EFFECTIVE: - gScene.queueMessage(i18next.t("battle:hitResultSuperEffective")); + globalScene.queueMessage(i18next.t("battle:hitResultSuperEffective")); break; case HitResult.NOT_VERY_EFFECTIVE: - gScene.queueMessage(i18next.t("battle:hitResultNotVeryEffective")); + globalScene.queueMessage(i18next.t("battle:hitResultNotVeryEffective")); break; case HitResult.ONE_HIT_KO: - gScene.queueMessage(i18next.t("battle:hitResultOneHitKO")); + globalScene.queueMessage(i18next.t("battle:hitResultOneHitKO")); break; } } if (this.isFainted()) { // set splice index here, so future scene queues happen before FaintedPhase - gScene.setPhaseQueueSplice(); + globalScene.setPhaseQueueSplice(); if (!isNullOrUndefined(destinyTag) && dmg) { // Destiny Bond will activate during FaintPhase - gScene.unshiftPhase(new FaintPhase(this.getBattlerIndex(), isOneHitKo, destinyTag, source)); + globalScene.unshiftPhase(new FaintPhase(this.getBattlerIndex(), isOneHitKo, destinyTag, source)); } else { - gScene.unshiftPhase(new FaintPhase(this.getBattlerIndex(), isOneHitKo)); + globalScene.unshiftPhase(new FaintPhase(this.getBattlerIndex(), isOneHitKo)); } this.destroySubstitute(); this.resetSummonData(); @@ -2869,7 +2864,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { surviveDamage.value = this.lapseTag(BattlerTagType.STURDY); } if (!surviveDamage.value) { - gScene.applyModifiers(SurviveDamageModifier, this.isPlayer(), this, surviveDamage); + globalScene.applyModifiers(SurviveDamageModifier, this.isPlayer(), this, surviveDamage); } if (surviveDamage.value) { damage = this.hp - 1; @@ -2886,8 +2881,8 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { * * Once the MoveEffectPhase is over (and calls it's .end() function, shiftPhase() will reset the PhaseQueueSplice via clearPhaseQueueSplice() ) */ - gScene.setPhaseQueueSplice(); - gScene.unshiftPhase(new FaintPhase(this.getBattlerIndex(), preventEndure)); + globalScene.setPhaseQueueSplice(); + globalScene.unshiftPhase(new FaintPhase(this.getBattlerIndex(), preventEndure)); this.destroySubstitute(); this.resetSummonData(); } @@ -2907,7 +2902,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { */ damageAndUpdate(damage: integer, result?: DamageResult, critical: boolean = false, ignoreSegments: boolean = false, preventEndure: boolean = false, ignoreFaintPhase: boolean = false): integer { const damagePhase = new DamagePhase(this.getBattlerIndex(), damage, result as DamageResult, critical); - gScene.unshiftPhase(damagePhase); + globalScene.unshiftPhase(damagePhase); damage = this.damage(damage, ignoreSegments, preventEndure, ignoreFaintPhase); // Damage amount may have changed, but needed to be queued before calling damage function damagePhase.updateAmount(damage); @@ -3063,7 +3058,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { for (const s of BATTLE_STATS) { const sourceStage = source.getStatStage(s); if ((this instanceof PlayerPokemon) && (sourceStage === 6)) { - gScene.validateAchv(achvs.TRANSFER_MAX_STAT_STAGE); + globalScene.validateAchv(achvs.TRANSFER_MAX_STAT_STAGE); } this.setStatStage(s, sourceStage); } @@ -3139,7 +3134,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } pushMoveHistory(turnMove: TurnMove) { - turnMove.turn = gScene.currentBattle?.turn; + turnMove.turn = globalScene.currentBattle?.turn; this.getMoveHistory().push(turnMove); } @@ -3157,7 +3152,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { * @param {Pokemon} target If specified, this only cancels subsequent strikes against the given target */ stopMultiHit(target?: Pokemon): void { - const effectPhase = gScene.getCurrentPhase(); + const effectPhase = globalScene.getCurrentPhase(); if (effectPhase instanceof MoveEffectPhase && effectPhase.getUserPokemon() === this) { effectPhase.stopMultiHit(target); } @@ -3171,18 +3166,18 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (this.abilityIndex >= abilityCount) {// Shouldn't happen this.abilityIndex = abilityCount - 1; } - gScene.gameData.setPokemonSeen(this, false); + globalScene.gameData.setPokemonSeen(this, false); this.setScale(this.getSpriteScale()); this.loadAssets().then(() => { this.calculateStats(); - gScene.updateModifiers(this.isPlayer(), true); - Promise.all([ this.updateInfo(), gScene.updateFieldScale() ]).then(() => resolve()); + globalScene.updateModifiers(this.isPlayer(), true); + Promise.all([ this.updateInfo(), globalScene.updateFieldScale() ]).then(() => resolve()); }); }); } cry(soundConfig?: Phaser.Types.Sound.SoundConfig, sceneOverride?: BattleScene): AnySound { - const scene = sceneOverride || gScene; // TODO: is `sceneOverride` needed? + const scene = sceneOverride || globalScene; // TODO: is `sceneOverride` needed? const cry = this.getSpeciesForm().cry(soundConfig); let duration = cry.totalDuration * 1000; if (this.fusionSpecies && this.getSpeciesForm() !== this.getFusionSpeciesForm()) { @@ -3191,9 +3186,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { fusionCry.destroy(); scene.time.delayedCall(Utils.fixedInt(Math.ceil(duration * 0.4)), () => { try { - SoundFade.fadeOut(gScene, cry, Utils.fixedInt(Math.ceil(duration * 0.2))); + SoundFade.fadeOut(globalScene, cry, Utils.fixedInt(Math.ceil(duration * 0.2))); fusionCry = this.getFusionSpeciesForm().cry(Object.assign({ seek: Math.max(fusionCry.totalDuration * 0.4, 0) }, soundConfig)); - SoundFade.fadeIn(gScene, fusionCry, Utils.fixedInt(Math.ceil(duration * 0.2)), scene.masterVolume * scene.seVolume, 0); + SoundFade.fadeIn(globalScene, fusionCry, Utils.fixedInt(Math.ceil(duration * 0.2)), scene.masterVolume * scene.seVolume, 0); } catch (err) { console.error(err); } @@ -3212,10 +3207,10 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { //eslint-disable-next-line @typescript-eslint/no-unused-vars let i = 0; let rate = 0.85; - const cry = gScene.playSound(key, { rate: rate }) as AnySound; + const cry = globalScene.playSound(key, { rate: rate }) as AnySound; const sprite = this.getSprite(); const tintSprite = this.getTintSprite(); - const delay = Math.max(gScene.sound.get(key).totalDuration * 50, 25); + const delay = Math.max(globalScene.sound.get(key).totalDuration * 50, 25); let frameProgress = 0; let frameThreshold: number; @@ -3223,7 +3218,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { sprite.anims.pause(); tintSprite?.anims.pause(); - let faintCryTimer : Phaser.Time.TimerEvent | null = gScene.time.addEvent({ + let faintCryTimer : Phaser.Time.TimerEvent | null = globalScene.time.addEvent({ delay: Utils.fixedInt(delay), repeat: -1, callback: () => { @@ -3251,8 +3246,8 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { }); // Failsafe - gScene.time.delayedCall(Utils.fixedInt(3000), () => { - if (!faintCryTimer || !gScene) { + globalScene.time.delayedCall(Utils.fixedInt(3000), () => { + if (!faintCryTimer || !globalScene) { return; } if (cry?.isPlaying) { @@ -3269,13 +3264,13 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const key = `cry/${this.species.getCryKey(this.formIndex)}`; let i = 0; let rate = 0.85; - const cry = gScene.playSound(key, { rate: rate }) as AnySound; + const cry = globalScene.playSound(key, { rate: rate }) as AnySound; const sprite = this.getSprite(); const tintSprite = this.getTintSprite(); let duration = cry.totalDuration * 1000; const fusionCryKey = `cry/${this.fusionSpecies?.getCryKey(this.fusionFormIndex)}`; - let fusionCry = gScene.playSound(fusionCryKey, { rate: rate }) as AnySound; + let fusionCry = globalScene.playSound(fusionCryKey, { rate: rate }) as AnySound; fusionCry.stop(); duration = Math.min(duration, fusionCry.totalDuration * 1000); fusionCry.destroy(); @@ -3303,7 +3298,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { sprite.anims.pause(); tintSprite?.anims.pause(); - let faintCryTimer: Phaser.Time.TimerEvent | null = gScene.time.addEvent({ + let faintCryTimer: Phaser.Time.TimerEvent | null = globalScene.time.addEvent({ delay: Utils.fixedInt(delay), repeat: -1, callback: () => { @@ -3318,9 +3313,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { frameProgress -= frameThreshold; } if (i === transitionIndex) { - SoundFade.fadeOut(gScene, cry, Utils.fixedInt(Math.ceil((duration / rate) * 0.2))); - fusionCry = gScene.playSound(fusionCryKey, Object.assign({ seek: Math.max(fusionCry.totalDuration * 0.4, 0), rate: rate })); - SoundFade.fadeIn(gScene, fusionCry, Utils.fixedInt(Math.ceil((duration / rate) * 0.2)), gScene.masterVolume * gScene.seVolume, 0); + SoundFade.fadeOut(globalScene, cry, Utils.fixedInt(Math.ceil((duration / rate) * 0.2))); + fusionCry = globalScene.playSound(fusionCryKey, Object.assign({ seek: Math.max(fusionCry.totalDuration * 0.4, 0), rate: rate })); + SoundFade.fadeIn(globalScene, fusionCry, Utils.fixedInt(Math.ceil((duration / rate) * 0.2)), globalScene.masterVolume * globalScene.seVolume, 0); } rate *= 0.99; if (cry && !cry.pendingRemove) { @@ -3340,8 +3335,8 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { }); // Failsafe - gScene.time.delayedCall(Utils.fixedInt(3000), () => { - if (!faintCryTimer || !gScene) { + globalScene.time.delayedCall(Utils.fixedInt(3000), () => { + if (!faintCryTimer || !globalScene) { return; } if (cry?.isPlaying) { @@ -3366,7 +3361,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (overrideStatus ? this.status?.effect === effect : this.status) { return false; } - if (this.isGrounded() && gScene.arena.terrain?.terrainType === TerrainType.MISTY) { + if (this.isGrounded() && globalScene.arena.terrain?.terrainType === TerrainType.MISTY) { return false; } } @@ -3411,12 +3406,12 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } break; case StatusEffect.SLEEP: - if (this.isGrounded() && gScene.arena.terrain?.terrainType === TerrainType.ELECTRIC) { + if (this.isGrounded() && globalScene.arena.terrain?.terrainType === TerrainType.ELECTRIC) { return false; } break; case StatusEffect.FREEZE: - if (this.isOfType(Type.ICE) || (gScene?.arena?.weather?.weatherType && [ WeatherType.SUNNY, WeatherType.HARSH_SUN ].includes(gScene.arena.weather.weatherType))) { + if (this.isOfType(Type.ICE) || (globalScene?.arena?.weather?.weatherType && [ WeatherType.SUNNY, WeatherType.HARSH_SUN ].includes(globalScene.arena.weather.weatherType))) { return false; } break; @@ -3454,7 +3449,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } if (asPhase) { - gScene.unshiftPhase(new ObtainStatusEffectPhase(this.getBattlerIndex(), effect, turnsRemaining, sourceText, sourcePokemon)); + globalScene.unshiftPhase(new ObtainStatusEffectPhase(this.getBattlerIndex(), effect, turnsRemaining, sourceText, sourcePokemon)); return true; } @@ -3486,7 +3481,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { this.status = new Status(effect, 0, sleepTurnsRemaining?.value); if (effect !== StatusEffect.FAINT) { - gScene.triggerPokemonFormChange(this, SpeciesFormChangeStatusEffectTrigger, true); + globalScene.triggerPokemonFormChange(this, SpeciesFormChangeStatusEffectTrigger, true); applyPostSetStatusAbAttrs(PostSetStatusAbAttr, this, effect, sourcePokemon); } @@ -3528,7 +3523,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { */ isSafeguarded(attacker: Pokemon): boolean { const defendingSide = this.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - if (gScene.arena.getTagOnSide(ArenaTagType.SAFEGUARD, defendingSide)) { + if (globalScene.arena.getTagOnSide(ArenaTagType.SAFEGUARD, defendingSide)) { const bypassed = new Utils.BooleanHolder(false); if (attacker) { applyAbAttrs(InfiltratorAbAttr, attacker, null, false, bypassed); @@ -3561,7 +3556,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } // If this Pokemon has a Substitute when loading in, play an animation to add its sprite if (this.getTag(SubstituteTag)) { - gScene.triggerPokemonBattleAnim(this, PokemonAnimType.SUBSTITUTE_ADD); + globalScene.triggerPokemonBattleAnim(this, PokemonAnimType.SUBSTITUTE_ADD); this.getTag(SubstituteTag)!.sourceInFocus = false; } this.summonDataPrimer = null; @@ -3578,8 +3573,8 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (this.getTag(BattlerTagType.SEEDED)) { this.lapseTag(BattlerTagType.SEEDED); } - if (gScene) { - gScene.triggerPokemonFormChange(this, SpeciesFormChangePostMoveTrigger, true); + if (globalScene) { + globalScene.triggerPokemonFormChange(this, SpeciesFormChangePostMoveTrigger, true); } } @@ -3593,7 +3588,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } setFrameRate(frameRate: integer) { - gScene.anims.get(this.getBattleSpriteKey()).frameRate = frameRate; + globalScene.anims.get(this.getBattleSpriteKey()).frameRate = frameRate; this.getSprite().play(this.getBattleSpriteKey()); this.getTintSprite()?.play(this.getBattleSpriteKey()); } @@ -3606,7 +3601,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (duration) { tintSprite?.setAlpha(0); - gScene.tweens.add({ + globalScene.tweens.add({ targets: tintSprite, alpha: alpha || 1, duration: duration, @@ -3621,7 +3616,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const tintSprite = this.getTintSprite(); if (duration) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: tintSprite, alpha: 0, duration: duration, @@ -3661,7 +3656,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { sparkle(): void { if (this.shinySparkle) { this.shinySparkle.play(`sparkle${this.variant ? `_${this.variant + 1}` : ""}`); - gScene.playSound("se/sparkle"); + globalScene.playSound("se/sparkle"); } } @@ -3682,10 +3677,10 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const fusionSpriteKey = fusionSpeciesForm.getSpriteKey(this.getFusionGender(ignoreOveride) === Gender.FEMALE, fusionSpeciesForm.formIndex, this.fusionShiny, this.fusionVariant); const fusionBackSpriteKey = fusionSpeciesForm.getSpriteKey(this.getFusionGender(ignoreOveride) === Gender.FEMALE, fusionSpeciesForm.formIndex, this.fusionShiny, this.fusionVariant).replace("pkmn__", "pkmn__back__"); - const sourceTexture = gScene.textures.get(spriteKey); - const sourceBackTexture = gScene.textures.get(backSpriteKey); - const fusionTexture = gScene.textures.get(fusionSpriteKey); - const fusionBackTexture = gScene.textures.get(fusionBackSpriteKey); + const sourceTexture = globalScene.textures.get(spriteKey); + const sourceBackTexture = globalScene.textures.get(backSpriteKey); + const fusionTexture = globalScene.textures.get(fusionSpriteKey); + const fusionBackTexture = globalScene.textures.get(fusionBackSpriteKey); const [ sourceFrame, sourceBackFrame, fusionFrame, fusionBackFrame ] = [ sourceTexture, sourceBackTexture, fusionTexture, fusionBackTexture ].map(texture => texture.frames[texture.firstFrame]); const [ sourceImage, sourceBackImage, fusionImage, fusionBackImage ] = [ sourceTexture, sourceBackTexture, fusionTexture, fusionBackTexture ].map(i => i.getSourceImage() as HTMLImageElement); @@ -3787,7 +3782,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { const originalRandom = Math.random; Math.random = () => Phaser.Math.RND.realInRange(0, 1); - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { paletteColors = QuantizerCelebi.quantize(pixelColors, 4); fusionPaletteColors = QuantizerCelebi.quantize(fusionPixelColors, 4); }, 0, "This result should not vary"); @@ -3908,9 +3903,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { } /** - * Generates a random number using the current battle's seed, or the global seed if `gScene.currentBattle` is falsy + * Generates a random number using the current battle's seed, or the global seed if `globalScene.currentBattle` is falsy * - * This calls either {@linkcode BattleScene.randBattleSeedInt}({@linkcode range}, {@linkcode min}) in `src/battle-gScene.ts` + * This calls either {@linkcode BattleScene.randBattleSeedInt}({@linkcode range}, {@linkcode min}) in `src/battle-scene.ts` * which calls {@linkcode Battle.randSeedInt}(`scene`, {@linkcode range}, {@linkcode min}) in `src/battle.ts` * which calls {@linkcode Utils.randSeedInt randSeedInt}({@linkcode range}, {@linkcode min}) in `src/utils.ts`, * or it directly calls {@linkcode Utils.randSeedInt randSeedInt}({@linkcode range}, {@linkcode min}) in `src/utils.ts` if there is no current battle @@ -3920,13 +3915,13 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { * @returns A random integer between {@linkcode min} and ({@linkcode min} + {@linkcode range} - 1) */ randSeedInt(range: integer, min: integer = 0): integer { - return gScene.currentBattle - ? gScene.randBattleSeedInt(range, min) + return globalScene.currentBattle + ? globalScene.randBattleSeedInt(range, min) : Utils.randSeedInt(range, min); } /** - * Generates a random number using the current battle's seed, or the global seed if `gScene.currentBattle` is falsy + * Generates a random number using the current battle's seed, or the global seed if `globalScene.currentBattle` is falsy * @param min The minimum integer to generate * @param max The maximum integer to generate * @returns a random integer between {@linkcode min} and {@linkcode max} inclusive @@ -3953,9 +3948,9 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container { if (hideInfo) { this.hideInfo(); } - gScene.field.remove(this); + globalScene.field.remove(this); this.setSwitchOutStatus(true); - gScene.triggerPokemonFormChange(this, SpeciesFormChangeActiveTrigger, true); + globalScene.triggerPokemonFormChange(this, SpeciesFormChangeActiveTrigger, true); } destroy(): void { @@ -4025,7 +4020,7 @@ export class PlayerPokemon extends Pokemon { } if (!dataSource) { - if (gScene.gameMode.isDaily) { + if (globalScene.gameMode.isDaily) { this.generateAndPopulateMoveset(); } else { this.moveset = []; @@ -4052,7 +4047,7 @@ export class PlayerPokemon extends Pokemon { } getFieldIndex(): integer { - return gScene.getPlayerField().indexOf(this); + return globalScene.getPlayerField().indexOf(this); } getBattlerIndex(): BattlerIndex { @@ -4088,7 +4083,7 @@ export class PlayerPokemon extends Pokemon { } tryPopulateMoveset(moveset: StarterMoveset): boolean { - if (!this.getSpeciesForm().validateStarterMoveset(moveset, gScene.gameData.starterData[this.species.getRootSpeciesId()].eggMoves)) { + if (!this.getSpeciesForm().validateStarterMoveset(moveset, globalScene.gameData.starterData[this.species.getRootSpeciesId()].eggMoves)) { return false; } @@ -4108,11 +4103,11 @@ export class PlayerPokemon extends Pokemon { return new Promise(resolve => { this.leaveField(switchType === SwitchType.SWITCH); - gScene.ui.setMode(Mode.PARTY, PartyUiMode.FAINT_SWITCH, this.getFieldIndex(), (slotIndex: integer, option: PartyOption) => { - if (slotIndex >= gScene.currentBattle.getBattlerCount() && slotIndex < 6) { - gScene.prependToPhase(new SwitchSummonPhase(switchType, this.getFieldIndex(), slotIndex, false), MoveEndPhase); + globalScene.ui.setMode(Mode.PARTY, PartyUiMode.FAINT_SWITCH, this.getFieldIndex(), (slotIndex: integer, option: PartyOption) => { + if (slotIndex >= globalScene.currentBattle.getBattlerCount() && slotIndex < 6) { + globalScene.prependToPhase(new SwitchSummonPhase(switchType, this.getFieldIndex(), slotIndex, false), MoveEndPhase); } - gScene.ui.setMode(Mode.MESSAGE).then(resolve); + globalScene.ui.setMode(Mode.MESSAGE).then(resolve); }, PartyUiHandler.FilterNonFainted); }); } @@ -4121,28 +4116,28 @@ export class PlayerPokemon extends Pokemon { const starterSpeciesId = this.species.getRootSpeciesId(); const fusionStarterSpeciesId = this.isFusion() && this.fusionSpecies ? this.fusionSpecies.getRootSpeciesId() : 0; const starterData = [ - gScene.gameData.starterData[starterSpeciesId], - fusionStarterSpeciesId ? gScene.gameData.starterData[fusionStarterSpeciesId] : null + globalScene.gameData.starterData[starterSpeciesId], + fusionStarterSpeciesId ? globalScene.gameData.starterData[fusionStarterSpeciesId] : null ].filter(d => !!d); const amount = new Utils.IntegerHolder(friendship); let candyFriendshipMultiplier = CLASSIC_CANDY_FRIENDSHIP_MULTIPLIER; - if (gScene.eventManager.isEventActive()) { - candyFriendshipMultiplier *= gScene.eventManager.getFriendshipMultiplier(); + if (globalScene.eventManager.isEventActive()) { + candyFriendshipMultiplier *= globalScene.eventManager.getFriendshipMultiplier(); } - const starterAmount = new Utils.IntegerHolder(Math.floor(friendship * (gScene.gameMode.isClassic && friendship > 0 ? candyFriendshipMultiplier : 1) / (fusionStarterSpeciesId ? 2 : 1))); + const starterAmount = new Utils.IntegerHolder(Math.floor(friendship * (globalScene.gameMode.isClassic && friendship > 0 ? candyFriendshipMultiplier : 1) / (fusionStarterSpeciesId ? 2 : 1))); if (amount.value > 0) { - gScene.applyModifier(PokemonFriendshipBoosterModifier, true, this, amount); - gScene.applyModifier(PokemonFriendshipBoosterModifier, true, this, starterAmount); + globalScene.applyModifier(PokemonFriendshipBoosterModifier, true, this, amount); + globalScene.applyModifier(PokemonFriendshipBoosterModifier, true, this, starterAmount); this.friendship = Math.min(this.friendship + amount.value, 255); if (this.friendship === 255) { - gScene.validateAchv(achvs.MAX_FRIENDSHIP); + globalScene.validateAchv(achvs.MAX_FRIENDSHIP); } starterData.forEach((sd: StarterDataEntry, i: integer) => { const speciesId = !i ? starterSpeciesId : fusionStarterSpeciesId as Species; sd.friendship = (sd.friendship || 0) + starterAmount.value; if (sd.friendship >= getStarterValueFriendshipCap(speciesStarterCosts[speciesId])) { - gScene.gameData.addStarterCandy(getPokemonSpecies(speciesId), 1); + globalScene.gameData.addStarterCandy(getPokemonSpecies(speciesId), 1); sd.friendship = 0; } }); @@ -4160,9 +4155,9 @@ export class PlayerPokemon extends Pokemon { */ revivalBlessing(): Promise { return new Promise(resolve => { - gScene.ui.setMode(Mode.PARTY, PartyUiMode.REVIVAL_BLESSING, this.getFieldIndex(), (slotIndex:integer, option: PartyOption) => { + globalScene.ui.setMode(Mode.PARTY, PartyUiMode.REVIVAL_BLESSING, this.getFieldIndex(), (slotIndex:integer, option: PartyOption) => { if (slotIndex >= 0 && slotIndex < 6) { - const pokemon = gScene.getParty()[slotIndex]; + const pokemon = globalScene.getParty()[slotIndex]; if (!pokemon || !pokemon.isFainted()) { resolve(); } @@ -4170,23 +4165,23 @@ export class PlayerPokemon extends Pokemon { pokemon.resetTurnData(); pokemon.resetStatus(); pokemon.heal(Math.min(Utils.toDmgValue(0.5 * pokemon.getMaxHp()), pokemon.getMaxHp())); - gScene.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: pokemon.name }), 0, true); + globalScene.queueMessage(i18next.t("moveTriggers:revivalBlessing", { pokemonName: pokemon.name }), 0, true); - if (gScene.currentBattle.double && gScene.getParty().length > 1) { + if (globalScene.currentBattle.double && globalScene.getParty().length > 1) { const allyPokemon = this.getAlly(); if (slotIndex <= 1) { // Revived ally pokemon - gScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, pokemon.getFieldIndex(), slotIndex, false, true)); - gScene.unshiftPhase(new ToggleDoublePositionPhase(true)); + globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, pokemon.getFieldIndex(), slotIndex, false, true)); + globalScene.unshiftPhase(new ToggleDoublePositionPhase(true)); } else if (allyPokemon.isFainted()) { // Revived party pokemon, and ally pokemon is fainted - gScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, allyPokemon.getFieldIndex(), slotIndex, false, true)); - gScene.unshiftPhase(new ToggleDoublePositionPhase(true)); + globalScene.unshiftPhase(new SwitchSummonPhase(SwitchType.SWITCH, allyPokemon.getFieldIndex(), slotIndex, false, true)); + globalScene.unshiftPhase(new ToggleDoublePositionPhase(true)); } } } - gScene.ui.setMode(Mode.MESSAGE).then(() => resolve()); + globalScene.ui.setMode(Mode.MESSAGE).then(() => resolve()); }, PartyUiHandler.FilterFainted); }); } @@ -4204,12 +4199,12 @@ export class PlayerPokemon extends Pokemon { const originalFusionFormIndex = this.fusionFormIndex; this.fusionSpecies = evolutionSpecies; this.fusionFormIndex = evolution.evoFormKey !== null ? Math.max(evolutionSpecies.forms.findIndex(f => f.formKey === evolution.evoFormKey), 0) : this.fusionFormIndex; - ret = gScene.addPlayerPokemon(this.species, this.level, this.abilityIndex, this.formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this); + ret = globalScene.addPlayerPokemon(this.species, this.level, this.abilityIndex, this.formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this); this.fusionSpecies = originalFusionSpecies; this.fusionFormIndex = originalFusionFormIndex; } else { const formIndex = evolution.evoFormKey !== null && !isFusion ? Math.max(evolutionSpecies.forms.findIndex(f => f.formKey === evolution.evoFormKey), 0) : this.formIndex; - ret = gScene.addPlayerPokemon(!isFusion ? evolutionSpecies : this.species, this.level, this.abilityIndex, formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this); + ret = globalScene.addPlayerPokemon(!isFusion ? evolutionSpecies : this.species, this.level, this.abilityIndex, formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this); } ret.loadAssets().then(() => resolve(ret)); }); @@ -4275,13 +4270,13 @@ export class PlayerPokemon extends Pokemon { if (preEvolution.speciesId === Species.GIMMIGHOUL) { const evotracker = this.getHeldItems().filter(m => m instanceof EvoTrackerModifier)[0] ?? null; if (evotracker) { - gScene.removeModifier(evotracker); + globalScene.removeModifier(evotracker); } } - if (!gScene.gameMode.isDaily || this.metBiome > -1) { - gScene.gameData.updateSpeciesDexIvs(this.species.speciesId, this.ivs); - gScene.gameData.setPokemonSeen(this, false); - gScene.gameData.setPokemonCaught(this, false).then(() => updateAndResolve()); + if (!globalScene.gameMode.isDaily || this.metBiome > -1) { + globalScene.gameData.updateSpeciesDexIvs(this.species.speciesId, this.ivs); + globalScene.gameData.setPokemonSeen(this, false); + globalScene.gameData.setPokemonCaught(this, false).then(() => updateAndResolve()); } else { updateAndResolve(); } @@ -4296,7 +4291,7 @@ export class PlayerPokemon extends Pokemon { const newEvolution = pokemonEvolutions[evoSpecies.speciesId][1]; if (newEvolution.condition?.predicate(this)) { - const newPokemon = gScene.addPlayerPokemon(this.species, this.level, this.abilityIndex, this.formIndex, undefined, this.shiny, this.variant, this.ivs, this.nature); + const newPokemon = globalScene.addPlayerPokemon(this.species, this.level, this.abilityIndex, this.formIndex, undefined, this.shiny, this.variant, this.ivs, this.nature); newPokemon.passive = this.passive; newPokemon.moveset = this.moveset.slice(); newPokemon.moveset = this.copyMoveset(); @@ -4314,16 +4309,16 @@ export class PlayerPokemon extends Pokemon { newPokemon.fusionLuck = this.fusionLuck; newPokemon.usedTMs = this.usedTMs; - gScene.getParty().push(newPokemon); + globalScene.getParty().push(newPokemon); newPokemon.evolve((!isFusion ? newEvolution : new FusionSpeciesFormEvolution(this.id, newEvolution)), evoSpecies); - const modifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const modifiers = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === this.id, true) as PokemonHeldItemModifier[]; modifiers.forEach(m => { const clonedModifier = m.clone() as PokemonHeldItemModifier; clonedModifier.pokemonId = newPokemon.id; - gScene.addModifier(clonedModifier, true); + globalScene.addModifier(clonedModifier, true); }); - gScene.updateModifiers(true); + globalScene.updateModifiers(true); } } } @@ -4331,7 +4326,7 @@ export class PlayerPokemon extends Pokemon { getPossibleForm(formChange: SpeciesFormChange): Promise { return new Promise(resolve => { const formIndex = Math.max(this.species.forms.findIndex(f => f.formKey === formChange.formKey), 0); - const ret = gScene.addPlayerPokemon(this.species, this.level, this.abilityIndex, formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this); + const ret = globalScene.addPlayerPokemon(this.species, this.level, this.abilityIndex, formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this); ret.loadAssets().then(() => resolve(ret)); }); } @@ -4370,13 +4365,13 @@ export class PlayerPokemon extends Pokemon { const updateAndResolve = () => { this.loadAssets().then(() => { this.calculateStats(); - gScene.updateModifiers(true, true); + globalScene.updateModifiers(true, true); this.updateInfo(true).then(() => resolve()); }); }; - if (!gScene.gameMode.isDaily || this.metBiome > -1) { - gScene.gameData.setPokemonSeen(this, false); - gScene.gameData.setPokemonCaught(this, false).then(() => updateAndResolve()); + if (!globalScene.gameMode.isDaily || this.metBiome > -1) { + globalScene.gameData.setPokemonSeen(this, false); + globalScene.gameData.setPokemonCaught(this, false).then(() => updateAndResolve()); } else { updateAndResolve(); } @@ -4406,8 +4401,8 @@ export class PlayerPokemon extends Pokemon { this.pauseEvolutions = true; } - gScene.validateAchv(achvs.SPLICE); - gScene.gameData.gameStats.pokemonFused++; + globalScene.validateAchv(achvs.SPLICE); + globalScene.gameData.gameStats.pokemonFused++; // Store the average HP% that each Pokemon has const maxHp = this.getMaxHp(); @@ -4430,23 +4425,23 @@ export class PlayerPokemon extends Pokemon { this.generateCompatibleTms(); this.updateInfo(true); - const fusedPartyMemberIndex = gScene.getParty().indexOf(pokemon); - let partyMemberIndex = gScene.getParty().indexOf(this); + const fusedPartyMemberIndex = globalScene.getParty().indexOf(pokemon); + let partyMemberIndex = globalScene.getParty().indexOf(this); if (partyMemberIndex > fusedPartyMemberIndex) { partyMemberIndex--; } - const fusedPartyMemberHeldModifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const fusedPartyMemberHeldModifiers = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id, true) as PokemonHeldItemModifier[]; const transferModifiers: Promise[] = []; for (const modifier of fusedPartyMemberHeldModifiers) { - transferModifiers.push(gScene.tryTransferHeldItemModifier(modifier, this, false, modifier.getStackCount(), true, true)); + transferModifiers.push(globalScene.tryTransferHeldItemModifier(modifier, this, false, modifier.getStackCount(), true, true)); } Promise.allSettled(transferModifiers).then(() => { - gScene.updateModifiers(true, true).then(() => { - gScene.removePartyMemberModifiers(fusedPartyMemberIndex); - gScene.getParty().splice(fusedPartyMemberIndex, 1)[0]; - const newPartyMemberIndex = gScene.getParty().indexOf(this); - pokemon.getMoveset(true).map((m: PokemonMove) => gScene.unshiftPhase(new LearnMovePhase(newPartyMemberIndex, m.getMove().id))); + globalScene.updateModifiers(true, true).then(() => { + globalScene.removePartyMemberModifiers(fusedPartyMemberIndex); + globalScene.getParty().splice(fusedPartyMemberIndex, 1)[0]; + const newPartyMemberIndex = globalScene.getParty().indexOf(this); + pokemon.getMoveset(true).map((m: PokemonMove) => globalScene.unshiftPhase(new LearnMovePhase(newPartyMemberIndex, m.getMove().id))); pokemon.destroy(); this.updateFusionPalette(); resolve(); @@ -4567,7 +4562,7 @@ export class EnemyPokemon extends Pokemon { */ setBoss(boss: boolean = true, bossSegments: integer = 0): void { if (boss) { - this.bossSegments = bossSegments || gScene.getEncounterBossSegments(gScene.currentBattle.waveIndex, this.level, this.species, true); + this.bossSegments = bossSegments || globalScene.getEncounterBossSegments(globalScene.currentBattle.waveIndex, this.level, this.species, true); this.bossSegmentIndex = this.bossSegments - 1; } else { this.bossSegments = 0; @@ -4599,7 +4594,7 @@ export class EnemyPokemon extends Pokemon { new PokemonMove(Moves.FLAMETHROWER), new PokemonMove(Moves.COSMIC_POWER) ]; - if (gScene.gameMode.hasChallenge(Challenges.INVERSE_BATTLE)) { + if (globalScene.gameMode.hasChallenge(Challenges.INVERSE_BATTLE)) { this.moveset[2] = new PokemonMove(Moves.THUNDERBOLT); } break; @@ -4646,7 +4641,7 @@ export class EnemyPokemon extends Pokemon { } switch (this.aiType) { case AiType.RANDOM: // No enemy should spawn with this AI type in-game - const moveId = movePool[gScene.randBattleSeedInt(movePool.length)]!.moveId; // TODO: is the bang correct? + const moveId = movePool[globalScene.randBattleSeedInt(movePool.length)]!.moveId; // TODO: is the bang correct? return { move: moveId, targets: this.getNextTargets(moveId) }; case AiType.SMART_RANDOM: case AiType.SMART: @@ -4665,7 +4660,7 @@ export class EnemyPokemon extends Pokemon { return false; } - const fieldPokemon = gScene.getField(); + const fieldPokemon = globalScene.getField(); const moveTargets = getMoveTargets(this, move.id).targets .map(ind => fieldPokemon[ind]) .filter(p => this.isPlayer() !== p.isPlayer()); @@ -4703,7 +4698,7 @@ export class EnemyPokemon extends Pokemon { break; } - const target = gScene.getField()[mt]; + const target = globalScene.getField()[mt]; /** * The "target score" of a move is given by the move's user benefit score + the move's target benefit score. * If the target is an ally, the target benefit score is multiplied by -1. @@ -4762,13 +4757,13 @@ export class EnemyPokemon extends Pokemon { let r = 0; if (this.aiType === AiType.SMART_RANDOM) { // Has a 5/8 chance to select the best move, and a 3/8 chance to advance to the next best move (and repeat this roll) - while (r < sortedMovePool.length - 1 && gScene.randBattleSeedInt(8) >= 5) { + while (r < sortedMovePool.length - 1 && globalScene.randBattleSeedInt(8) >= 5) { r++; } } else if (this.aiType === AiType.SMART) { // The chance to advance to the next best move increases when the compared moves' scores are closer to each other. while (r < sortedMovePool.length - 1 && (moveScores[movePool.indexOf(sortedMovePool[r + 1])] / moveScores[movePool.indexOf(sortedMovePool[r])]) >= 0 - && gScene.randBattleSeedInt(100) < Math.round((moveScores[movePool.indexOf(sortedMovePool[r + 1])] / moveScores[movePool.indexOf(sortedMovePool[r])]) * 50)) { + && globalScene.randBattleSeedInt(100) < Math.round((moveScores[movePool.indexOf(sortedMovePool[r + 1])] / moveScores[movePool.indexOf(sortedMovePool[r])]) * 50)) { r++; } } @@ -4787,7 +4782,7 @@ export class EnemyPokemon extends Pokemon { */ getNextTargets(moveId: Moves): BattlerIndex[] { const moveTargets = getMoveTargets(this, moveId); - const targets = gScene.getField(true).filter(p => moveTargets.targets.indexOf(p.getBattlerIndex()) > -1); + const targets = globalScene.getField(true).filter(p => moveTargets.targets.indexOf(p.getBattlerIndex()) > -1); // If the move is multi-target, return all targets' indexes if (moveTargets.multiple) { return targets.map(p => p.getBattlerIndex()); @@ -4849,7 +4844,7 @@ export class EnemyPokemon extends Pokemon { * then select the first target whose cumulative weight (with all previous targets' weights) * is greater than that random number. */ - const randValue = gScene.randBattleSeedInt(totalWeight); + const randValue = globalScene.randBattleSeedInt(totalWeight); let targetIndex: integer = 0; thresholds.every((t, i) => { @@ -4920,7 +4915,7 @@ export class EnemyPokemon extends Pokemon { } } - switch (gScene.currentBattle.battleSpec) { + switch (globalScene.currentBattle.battleSpec) { case BattleSpec.FINAL_BOSS: if (!this.formIndex && this.bossSegmentIndex < 1) { damage = Math.min(damage, this.hp - 1); @@ -4944,7 +4939,7 @@ export class EnemyPokemon extends Pokemon { } canBypassBossSegments(segmentCount: integer = 1): boolean { - if (gScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { + if (globalScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { if (!this.formIndex && (this.bossSegmentIndex - segmentCount) < 1) { return false; } @@ -4995,7 +4990,7 @@ export class EnemyPokemon extends Pokemon { stages++; } - gScene.unshiftPhase(new StatStageChangePhase(this.getBattlerIndex(), true, [ boostedStat! ], stages, true, true)); + globalScene.unshiftPhase(new StatStageChangePhase(this.getBattlerIndex(), true, [ boostedStat! ], stages, true, true)); this.bossSegmentIndex--; } } @@ -5021,7 +5016,7 @@ export class EnemyPokemon extends Pokemon { } getFieldIndex(): integer { - return gScene.getEnemyField().indexOf(this); + return globalScene.getEnemyField().indexOf(this); } getBattlerIndex(): BattlerIndex { @@ -5036,16 +5031,16 @@ export class EnemyPokemon extends Pokemon { * @returns the pokemon that was added or null if the pokemon could not be added */ addToParty(pokeballType: PokeballType, slotIndex: number = -1) { - const party = gScene.getParty(); + const party = globalScene.getParty(); let ret: PlayerPokemon | null = null; if (party.length < PLAYER_PARTY_MAX_SIZE) { this.pokeball = pokeballType; this.metLevel = this.level; - this.metBiome = gScene.arena.biomeType; - this.metWave = gScene.currentBattle.waveIndex; + this.metBiome = globalScene.arena.biomeType; + this.metWave = globalScene.currentBattle.waveIndex; this.metSpecies = this.species.speciesId; - const newPokemon = gScene.addPlayerPokemon(this.species, this.level, this.abilityIndex, this.formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this); + const newPokemon = globalScene.addPlayerPokemon(this.species, this.level, this.abilityIndex, this.formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this); if (Utils.isBetween(slotIndex, 0, PLAYER_PARTY_MAX_SIZE - 1)) { if (slotIndex === 0) { @@ -5057,7 +5052,7 @@ export class EnemyPokemon extends Pokemon { } ret = newPokemon; - gScene.triggerPokemonFormChange(newPokemon, SpeciesFormChangeActiveTrigger, true); + globalScene.triggerPokemonFormChange(newPokemon, SpeciesFormChangeActiveTrigger, true); } return ret; diff --git a/src/field/trainer.ts b/src/field/trainer.ts index a46c07c8683..7d3dc51c24e 100644 --- a/src/field/trainer.ts +++ b/src/field/trainer.ts @@ -1,4 +1,4 @@ -import BattleScene, { gScene } from "#app/battle-scene"; +import BattleScene, { globalScene } from "#app/battle-scene"; import { pokemonPrevolutions } from "#app/data/balance/pokemon-evolutions"; import PokemonSpecies, { getPokemonSpecies } from "#app/data/pokemon-species"; import { @@ -36,7 +36,7 @@ export default class Trainer extends Phaser.GameObjects.Container { public partnerName: string; constructor(trainerType: TrainerType, variant: TrainerVariant, partyTemplateIndex?: integer, name?: string, partnerName?: string, trainerConfigOverride?: TrainerConfig) { - super(gScene, -72, 80); + super(globalScene, -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 = gScene.addFieldSprite(0, 0, this.config.getSpriteKey(variant === TrainerVariant.FEMALE || forceFemale, this.isDouble())); + const ret = globalScene.addFieldSprite(0, 0, this.config.getSpriteKey(variant === TrainerVariant.FEMALE || forceFemale, this.isDouble())); ret.setOrigin(0.5, 1); - ret.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow }); + ret.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: !!hasShadow }); return ret; }; @@ -216,7 +216,7 @@ export default class Trainer extends Phaser.GameObjects.Container { const ret: number[] = []; const partyTemplate = this.getPartyTemplate(); - const difficultyWaveIndex = gScene.gameMode.getWaveForDifficulty(waveIndex); + const difficultyWaveIndex = globalScene.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 = gScene.currentBattle; + const battle = globalScene.currentBattle; const level = battle.enemyLevels?.[index]!; // TODO: is this bang correct? let ret: EnemyPokemon; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const template = this.getPartyTemplate(); const strength: PartyMemberStrength = template.getStrength(index); @@ -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), gScene.currentBattle.waveIndex)) + ? getPokemonSpecies(battle.enemyParty[offset].species.getTrainerSpeciesForLevel(level, false, template.getStrength(offset), globalScene.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, gScene.currentBattle.waveIndex)); + species = getPokemonSpecies(species.getSpeciesForLevel(level, true, true, strength, globalScene.currentBattle.waveIndex)); } - 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)); + ret = globalScene.addEnemyPokemon(species, level, !this.isDouble() || !(index % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER); + }, this.config.hasStaticParty ? this.config.getDerivedType() + ((index + 1) << 8) : globalScene.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 = gScene.currentBattle; + const battle = globalScene.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 = gScene.randomSpecies(battle.waveIndex, level, false, this.config.speciesFilter); + baseSpecies = globalScene.randomSpecies(battle.waveIndex, level, false, this.config.speciesFilter); } - let ret = getPokemonSpecies(baseSpecies.getTrainerSpeciesForLevel(level, true, strength, gScene.currentBattle.waveIndex)); + let ret = getPokemonSpecies(baseSpecies.getTrainerSpeciesForLevel(level, true, strength, globalScene.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, gScene.currentBattle.waveIndex)); + ret = getPokemonSpecies(baseSpecies.getTrainerSpeciesForLevel(level, true, strength, globalScene.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 = gScene.getEnemyParty().map(p => { + const currentPartySpecies = globalScene.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 = gScene.getEnemyParty(); - const nonFaintedLegalPartyMembers = party.slice(gScene.currentBattle.getBattlerCount()).filter(p => p.isAllowedInBattle()).filter(p => !trainerSlot || p.trainerSlot === trainerSlot); + const party = globalScene.getEnemyParty(); + const nonFaintedLegalPartyMembers = party.slice(globalScene.currentBattle.getBattlerCount()).filter(p => p.isAllowedInBattle()).filter(p => !trainerSlot || p.trainerSlot === trainerSlot); const partyMemberScores = nonFaintedLegalPartyMembers.map(p => { - const playerField = gScene.getPlayerField().filter(p => p.isAllowedInBattle()); + const playerField = globalScene.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()) { - gScene.arena.findTagsOnSide(t => t instanceof ArenaTrapTag, ArenaTagSide.ENEMY).map(t => score *= (t as ArenaTrapTag).getMatchupScoreMultiplier(p)); + globalScene.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; - gScene.executeWithSeedOffset(() => rand = Utils.randSeedInt(maxScorePartyMemberIndexes.length), gScene.currentBattle.turn << 2); + globalScene.executeWithSeedOffset(() => rand = Utils.randSeedInt(maxScorePartyMemberIndexes.length), globalScene.currentBattle.turn << 2); return maxScorePartyMemberIndexes[rand!]; } @@ -627,7 +627,7 @@ export default class Trainer extends Phaser.GameObjects.Container { if (duration) { tintSprite.setAlpha(0); - gScene.tweens.add({ + globalScene.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) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: tintSprite, alpha: 0, duration: duration, diff --git a/src/game-mode.ts b/src/game-mode.ts index 18bd95ae1c7..5420c8a89be 100644 --- a/src/game-mode.ts +++ b/src/game-mode.ts @@ -8,7 +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"; +import { globalScene } from "#app/battle-scene"; export enum GameModes { CLASSIC, @@ -118,7 +118,7 @@ export class GameMode implements GameModeConfig { getStartingBiome(): Biome { switch (this.modeId) { case GameModes.DAILY: - return gScene.generateRandomBiome(this.getWaveForDifficulty(1)); + return globalScene.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) === (gScene.offsetGym ? 0 : 20) && !this.isWaveFinal(waveIndex)) { + if ((waveIndex % 30) === (globalScene.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) === (gScene.offsetGym ? 0 : 20) || this.isFixedBattle(w)) { + if ((w % 30) === (globalScene.offsetGym ? 0 : 20) || this.isFixedBattle(w)) { allowTrainerBattle = false; break; } else if (w < waveIndex) { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const waveTrainerChance = arena.getTrainerChance(); if (!Utils.randSeedInt(waveTrainerChance)) { allowTrainerBattle = false; diff --git a/src/inputs-controller.ts b/src/inputs-controller.ts index a69ed705108..f87cd976afd 100644 --- a/src/inputs-controller.ts +++ b/src/inputs-controller.ts @@ -15,7 +15,7 @@ import { getButtonWithKeycode, getIconForLatestInput, swap, } from "#app/configs/inputs/configHandler"; -import { gScene } from "./battle-scene"; +import { globalScene } 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"; @@ -132,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 = gScene.game.events; + this.events = globalScene.game.events; - gScene.game.events.on(Phaser.Core.Events.BLUR, () => { + globalScene.game.events.on(Phaser.Core.Events.BLUR, () => { this.loseFocus(); }); - if (typeof gScene.input.gamepad !== "undefined") { - gScene.input.gamepad?.on("connected", function (thisGamepad) { + if (typeof globalScene.input.gamepad !== "undefined") { + globalScene.input.gamepad?.on("connected", function (thisGamepad) { if (!thisGamepad) { return; } @@ -148,23 +148,23 @@ export class InputsController { this.onReconnect(thisGamepad); }, this); - gScene.input.gamepad?.on("disconnected", function (thisGamepad) { + globalScene.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 - gScene.input.gamepad?.refreshPads(); - if (gScene.input.gamepad?.total) { + globalScene.input.gamepad?.refreshPads(); + if (globalScene.input.gamepad?.total) { this.refreshGamepads(); for (const thisGamepad of this.gamepads) { - gScene.input.gamepad.emit("connected", thisGamepad); + globalScene.input.gamepad.emit("connected", thisGamepad); } } - 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); + globalScene.input.gamepad?.on("down", this.gamepadButtonDown, this); + globalScene.input.gamepad?.on("up", this.gamepadButtonUp, this); + globalScene.input.keyboard?.on("keydown", this.keyboardKeyDown, this); + globalScene.input.keyboard?.on("keyup", this.keyboardKeyUp, this); } this.touchControls = new TouchControl(); this.moveTouchControlsHandler = new MoveTouchControlsHandler(this.touchControls); @@ -236,7 +236,7 @@ export class InputsController { if (gamepadName) { this.selectedDevice[Device.GAMEPAD] = gamepadName.toLowerCase(); } - const handler = gScene.ui?.handlers[Mode.SETTINGS_GAMEPAD] as SettingsGamepadUiHandler; + const handler = globalScene.ui?.handlers[Mode.SETTINGS_GAMEPAD] as SettingsGamepadUiHandler; handler && handler.updateChosenGamepadDisplay(); } @@ -249,7 +249,7 @@ export class InputsController { if (layoutKeyboard) { this.selectedDevice[Device.KEYBOARD] = layoutKeyboard.toLowerCase(); } - const handler = gScene.ui?.handlers[Mode.SETTINGS_KEYBOARD] as SettingsKeyboardUiHandler; + const handler = globalScene.ui?.handlers[Mode.SETTINGS_KEYBOARD] as SettingsKeyboardUiHandler; handler && handler.updateChosenKeyboardDisplay(); } @@ -294,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; - gScene.gameData?.saveMappingConfigs(gamepadID, this.configs[gamepadID]); + globalScene.gameData?.saveMappingConfigs(gamepadID, this.configs[gamepadID]); } this.lastSource = "gamepad"; - const handler = gScene.ui?.handlers[Mode.SETTINGS_GAMEPAD] as SettingsGamepadUiHandler; + const handler = globalScene.ui?.handlers[Mode.SETTINGS_GAMEPAD] as SettingsGamepadUiHandler; handler && handler.updateChosenGamepadDisplay(); } @@ -309,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; - gScene.gameData?.saveMappingConfigs(this.selectedDevice[Device.KEYBOARD], this.configs[layout]); + globalScene.gameData?.saveMappingConfigs(this.selectedDevice[Device.KEYBOARD], this.configs[layout]); } this.initChosenLayoutKeyboard(this.selectedDevice[Device.KEYBOARD]); } @@ -324,7 +324,7 @@ export class InputsController { */ refreshGamepads(): void { // Sometimes, gamepads are undefined. For some reason. - this.gamepads = gScene.input.gamepad?.gamepads.filter(function (el) { + this.gamepads = globalScene.input.gamepad?.gamepads.filter(function (el) { return el !== null; }) ?? []; @@ -407,7 +407,7 @@ export class InputsController { return; } this.lastSource = "gamepad"; - if (!this.selectedDevice[Device.GAMEPAD] || (gScene.ui.getMode() !== Mode.GAMEPAD_BINDING && this.selectedDevice[Device.GAMEPAD] !== pad.id.toLowerCase())) { + if (!this.selectedDevice[Device.GAMEPAD] || (globalScene.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()) { diff --git a/src/loading-scene.ts b/src/loading-scene.ts index 04b721f0283..7ed59f6bfdc 100644 --- a/src/loading-scene.ts +++ b/src/loading-scene.ts @@ -20,7 +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"; +import { globalScene } from "#app/battle-scene"; export class LoadingScene extends SceneBase { public static readonly KEY = "loading"; @@ -511,7 +511,7 @@ export class LoadingScene extends SceneBase { async create() { this.events.once(Phaser.Scenes.Events.DESTROY, () => this.handleDestroy()); - gScene.scene.start("battle"); + globalScene.scene.start("battle"); } handleDestroy() { diff --git a/src/messages.ts b/src/messages.ts index d355ccdb6f6..9ca09786d92 100644 --- a/src/messages.ts +++ b/src/messages.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattleSpec } from "#enums/battle-spec"; import Pokemon from "./field/pokemon"; import i18next from "i18next"; @@ -13,7 +13,7 @@ export function getPokemonNameWithAffix(pokemon: Pokemon | undefined): string { return "Missigno"; } - switch (gScene.currentBattle.battleSpec) { + switch (globalScene.currentBattle.battleSpec) { case BattleSpec.DEFAULT: return !pokemon.isPlayer() ? pokemon.hasTrainer() diff --git a/src/modifier/modifier-type.ts b/src/modifier/modifier-type.ts index e9909a95a66..c67f9414498 100644 --- a/src/modifier/modifier-type.ts +++ b/src/modifier/modifier-type.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -187,7 +187,7 @@ class AddPokeballModifierType extends ModifierType { "modifierCount": this.count, "pokeballName": getPokeballName(this.pokeballType), "catchRate": getPokeballCatchMultiplier(this.pokeballType) > -1 ? `${getPokeballCatchMultiplier(this.pokeballType)}x` : "100%", - "pokeballAmount": `${gScene.pokeballCounts[this.pokeballType]}`, + "pokeballAmount": `${globalScene.pokeballCounts[this.pokeballType]}`, }); } } @@ -231,7 +231,7 @@ 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 = gScene.findModifier(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id && m.matchType(dummyModifier)) as PokemonHeldItemModifier; + const matchingModifier = globalScene.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) }); @@ -578,7 +578,7 @@ export class PokemonLevelIncrementModifierType extends PokemonModifierType { getDescription(): string { let levels = 1; - const hasCandyJar = gScene.modifiers.find(modifier => modifier instanceof LevelIncrementBoosterModifier); + const hasCandyJar = globalScene.modifiers.find(modifier => modifier instanceof LevelIncrementBoosterModifier); if (hasCandyJar) { levels += hasCandyJar.stackCount; } @@ -593,7 +593,7 @@ export class AllPokemonLevelIncrementModifierType extends ModifierType { getDescription(): string { let levels = 1; - const hasCandyJar = gScene.modifiers.find(modifier => modifier instanceof LevelIncrementBoosterModifier); + const hasCandyJar = globalScene.modifiers.find(modifier => modifier instanceof LevelIncrementBoosterModifier); if (hasCandyJar) { levels += hasCandyJar.stackCount; } @@ -707,9 +707,9 @@ export class MoneyRewardModifierType extends ModifierType { } getDescription(): string { - const moneyAmount = new IntegerHolder(gScene.getWaveMoneyAmount(this.moneyMultiplier)); - gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); - const formattedMoney = formatMoney(gScene.moneyFormat, moneyAmount.value); + const moneyAmount = new IntegerHolder(globalScene.getWaveMoneyAmount(this.moneyMultiplier)); + globalScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); + const formattedMoney = formatMoney(globalScene.moneyFormat, moneyAmount.value); return i18next.t("modifierType:ModifierType.MoneyRewardModifierType.description", { moneyMultiplier: i18next.t(this.moneyMultiplierDescriptorKey as any), @@ -803,7 +803,7 @@ export class TmModifierType extends PokemonModifierType { } getDescription(): string { - return i18next.t(gScene.enableMoveInfo ? "modifierType:ModifierType.TmModifierTypeWithInfo.description" : "modifierType:ModifierType.TmModifierType.description", { moveName: allMoves[this.moveId].name }); + return i18next.t(globalScene.enableMoveInfo ? "modifierType:ModifierType.TmModifierTypeWithInfo.description" : "modifierType:ModifierType.TmModifierType.description", { moveName: allMoves[this.moveId].name }); } } @@ -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) || gScene.getModifiers(MegaEvolutionAccessModifier).length) - && ((fc.formKey.indexOf(SpeciesFormKey.GIGANTAMAX) === -1 && fc.formKey.indexOf(SpeciesFormKey.ETERNAMAX) === -1) || gScene.getModifiers(GigantamaxAccessModifier).length) + let formChangeItemTriggers = formChanges.filter(fc => ((fc.formKey.indexOf(SpeciesFormKey.MEGA) === -1 && fc.formKey.indexOf(SpeciesFormKey.PRIMAL) === -1) || globalScene.getModifiers(MegaEvolutionAccessModifier).length) + && ((fc.formKey.indexOf(SpeciesFormKey.GIGANTAMAX) === -1 && fc.formKey.indexOf(SpeciesFormKey.ETERNAMAX) === -1) || globalScene.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 && !gScene.findModifier(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === p.id && m.formChangeItem === t.item)); + .filter(t => t && t.active && !globalScene.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... @@ -1252,8 +1252,8 @@ type WeightedModifierTypeWeightFunc = (party: Pokemon[], rerollCount?: integer) */ function skipInClassicAfterWave(wave: integer, defaultWeight: integer): WeightedModifierTypeWeightFunc { return (party: Pokemon[]) => { - const gameMode = gScene.gameMode; - const currentWave = gScene.currentBattle.waveIndex; + const gameMode = globalScene.gameMode; + const currentWave = globalScene.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 = 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; + const lures = globalScene.getModifiers(DoubleBattleChanceBoosterModifier); + return !(globalScene.gameMode.isClassic && globalScene.currentBattle.waveIndex === 199) && (lures.length === 0 || lures.filter(m => m.getMaxBattles() === maxBattles && m.getBattleCount() >= maxBattles * 0.6).length === 0) ? weight : 0; }; } class WeightedModifierType { @@ -1435,7 +1435,7 @@ export const modifierTypes = { if (pregenArgs && (pregenArgs.length === 1) && (pregenArgs[0] in Type)) { return new TerastallizeModifierType(pregenArgs[0] as Type); } - if (!gScene.getModifiers(TerastallizeAccessModifier).length) { + if (!globalScene.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 (gScene.gameMode.isClassic && gScene.pokeballCounts[ballType] >= MAX_PER_TYPE_POKEBALLS); + return (globalScene.gameMode.isClassic && globalScene.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(gScene.currentBattle.waveIndex / 15), 8); + return Math.min(Math.ceil(globalScene.currentBattle.waveIndex / 15), 8); }, 8), new WeightedModifierType(modifierTypes.MAP, - (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), + (party: Pokemon[]) => globalScene.gameMode.isClassic && globalScene.currentBattle.waveIndex < 180 ? globalScene.eventManager.isEventActive() ? 2 : 1 : 0, + (party: Pokemon[]) => globalScene.eventManager.isEventActive() ? 2 : 1), + new WeightedModifierType(modifierTypes.SOOTHE_BELL, (party: Pokemon[]) => globalScene.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[]) => 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), + new WeightedModifierType(modifierTypes.DNA_SPLICERS, (party: Pokemon[]) => globalScene.gameMode.isSplicedOnly && party.filter(p => !p.fusionSpecies).length > 1 ? 4 : 0), + new WeightedModifierType(modifierTypes.VOUCHER, (party: Pokemon[], rerollCount: integer) => !globalScene.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(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.RARE_EVOLUTION_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(globalScene.currentBattle.waveIndex / 15) * 4, 32), 32), + new WeightedModifierType(modifierTypes.FORM_CHANGE_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(globalScene.currentBattle.waveIndex / 50), 4) * 6, 24), new WeightedModifierType(modifierTypes.AMULET_COIN, skipInLastClassicWaveOrDefault(3)), new WeightedModifierType(modifierTypes.EVIOLITE, (party: Pokemon[]) => { - const { gameMode, gameData } = gScene; + const { gameMode, gameData } = globalScene; 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[]) => gScene.eventManager.isEventActive() ? 6 : 4), + new WeightedModifierType(modifierTypes.RARER_CANDY, (party: Pokemon[]) => globalScene.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(gScene.currentBattle.waveIndex / 50) * 2, 1), 4), 4), + new WeightedModifierType(modifierTypes.TERA_ORB, (party: Pokemon[]) => Math.min(Math.max(Math.floor(globalScene.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[]) => gScene.eventManager.isEventActive() ? 0 : 4), + new WeightedModifierType(modifierTypes.SOOTHE_BELL, (party: Pokemon[]) => globalScene.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[]) => gScene.gameMode.isClassic ? 0 : 3), + new WeightedModifierType(modifierTypes.LOCK_CAPSULE, (party: Pokemon[]) => globalScene.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(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), + new WeightedModifierType(modifierTypes.RARE_FORM_CHANGE_ITEM, (party: Pokemon[]) => Math.min(Math.ceil(globalScene.currentBattle.waveIndex / 50), 4) * 6, 24), + new WeightedModifierType(modifierTypes.MEGA_BRACELET, (party: Pokemon[]) => Math.min(Math.ceil(globalScene.currentBattle.waveIndex / 50), 4) * 9, 36), + new WeightedModifierType(modifierTypes.DYNAMAX_BAND, (party: Pokemon[]) => Math.min(Math.ceil(globalScene.currentBattle.waveIndex / 50), 4) * 9, 36), + new WeightedModifierType(modifierTypes.VOUCHER_PLUS, (party: Pokemon[], rerollCount: integer) => !globalScene.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) => - !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), + !globalScene.gameMode.isDaily && !globalScene.gameMode.isEndless && !globalScene.gameMode.isSplicedOnly ? Math.max(5 - rerollCount * 2, 0) : 0, 5), + new WeightedModifierType(modifierTypes.DNA_SPLICERS, (party: Pokemon[]) => !globalScene.gameMode.isSplicedOnly && party.filter(p => !p.fusionSpecies).length > 1 ? 24 : 0, 24), + new WeightedModifierType(modifierTypes.MINI_BLACK_HOLE, (party: Pokemon[]) => (globalScene.gameMode.isDaily || (!globalScene.gameMode.isFreshStartChallenge() && globalScene.gameData.isUnlocked(Unlockables.MINI_BLACK_HOLE))) ? 1 : 0, 1), ].map(m => { m.setTier(ModifierTier.MASTER); return m; }) @@ -2001,7 +2001,7 @@ export function regenerateModifierPoolThresholds(party: Pokemon[], poolType: Mod let i = 0; pool[t].reduce((total: integer, modifierType: WeightedModifierType) => { const weightedModifierType = modifierType as WeightedModifierType; - const existingModifiers = gScene.findModifiers(m => m.type.id === weightedModifierType.modifierType.id, poolType === ModifierPoolType.PLAYER); + const existingModifiers = globalScene.findModifiers(m => m.type.id === weightedModifierType.modifierType.id, poolType === ModifierPoolType.PLAYER); const itemModifierType = weightedModifierType.modifierType instanceof ModifierTypeGenerator ? weightedModifierType.modifierType.generateType(party) : weightedModifierType.modifierType; @@ -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 (gScene.gameMode.isDaily) { + if (globalScene.gameMode.isDaily) { const DailyLuck = new NumberHolder(0); - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { DailyLuck.value = randSeedInt(15); // Random number between 0 and 14 - }, 0, gScene.seed); + }, 0, globalScene.seed); return DailyLuck.value; } const luck = Phaser.Math.Clamp(party.map(p => p.isAllowedInBattle() ? p.getLuck() : 0) diff --git a/src/modifier/modifier.ts b/src/modifier/modifier.ts index a86fdd14c77..f8ec3d42fbc 100644 --- a/src/modifier/modifier.ts +++ b/src/modifier/modifier.ts @@ -30,7 +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"; +import { globalScene } from "#app/battle-scene"; export type ModifierPredicate = (modifier: Modifier) => boolean; @@ -65,7 +65,7 @@ export class ModifierBar extends Phaser.GameObjects.Container { private modifierCache: PersistentModifier[]; constructor(enemy?: boolean) { - super(gScene, 1 + (enemy ? 302 : 0), 2); + super(globalScene, 1 + (enemy ? 302 : 0), 2); this.player = !enemy; this.setScale(0.5); @@ -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", () => { - gScene.ui.showTooltip(modifier.type.name, modifier.type.getDescription()); + globalScene.ui.showTooltip(modifier.type.name, modifier.type.getDescription()); if (this.modifierCache && this.modifierCache.length > iconOverflowIndex) { thisArg.updateModifierOverflowVisibility(true); } }); icon.on("pointerout", () => { - gScene.ui.hideTooltip(); + globalScene.ui.hideTooltip(); if (this.modifierCache && this.modifierCache.length > iconOverflowIndex) { thisArg.updateModifierOverflowVisibility(false); } @@ -215,9 +215,9 @@ export abstract class PersistentModifier extends Modifier { } getIcon(forSummary?: boolean): Phaser.GameObjects.Container { - const container = gScene.add.container(0, 0); + const container = globalScene.add.container(0, 0); - const item = gScene.add.sprite(0, 12, "items"); + const item = globalScene.add.sprite(0, 12, "items"); item.setFrame(this.type.iconImage); item.setOrigin(0, 0.5); container.add(item); @@ -240,7 +240,7 @@ export abstract class PersistentModifier extends Modifier { return null; } - const text = gScene.add.bitmapText(10, 15, "item-count", this.stackCount.toString(), 11); + const text = globalScene.add.bitmapText(10, 15, "item-count", this.stackCount.toString(), 11); text.letterSpacing = -0.5; if (this.getStackCount() >= this.getMaxStackCount()) { text.setTint(0xf89890); @@ -278,7 +278,7 @@ export class AddPokeballModifier extends ConsumableModifier { * @returns always `true` */ override apply(): boolean { - const pokeballCounts = gScene.pokeballCounts; + const pokeballCounts = globalScene.pokeballCounts; pokeballCounts[this.pokeballType] = Math.min(pokeballCounts[this.pokeballType] + this.count, MAX_PER_TYPE_POKEBALLS); return true; @@ -302,7 +302,7 @@ export class AddVoucherModifier extends ConsumableModifier { * @returns always `true` */ override apply(): boolean { - const voucherCounts = gScene.gameData.voucherCounts; + const voucherCounts = globalScene.gameData.voucherCounts; voucherCounts[this.voucherType] += this.count; return true; @@ -348,7 +348,7 @@ export abstract class LapsingPersistentModifier extends PersistentModifier { const modifierInstance = modifier as LapsingPersistentModifier; if (modifierInstance.getBattleCount() < modifierInstance.getMaxBattles()) { modifierInstance.resetBattleCount(); - gScene.playSound("se/restore"); + globalScene.playSound("se/restore"); return true; } // should never get here @@ -684,17 +684,17 @@ export abstract class PokemonHeldItemModifier extends PersistentModifier { } getIcon(forSummary?: boolean): Phaser.GameObjects.Container { - const container = !forSummary ? gScene.add.container(0, 0) : super.getIcon(); + const container = !forSummary ? globalScene.add.container(0, 0) : super.getIcon(); if (!forSummary) { const pokemon = this.getPokemon(); if (pokemon) { - const pokemonIcon = gScene.addPokemonIcon(pokemon, -2, 10, 0, 0.5); + const pokemonIcon = globalScene.addPokemonIcon(pokemon, -2, 10, 0, 0.5); container.add(pokemonIcon); container.setName(pokemon.id.toString()); } - const item = gScene.add.sprite(16, this.virtualStackCount ? 8 : 16, "items"); + const item = globalScene.add.sprite(16, this.virtualStackCount ? 8 : 16, "items"); item.setScale(0.5); item.setOrigin(0, 0.5); item.setTexture("items", this.type.iconImage); @@ -717,7 +717,7 @@ export abstract class PokemonHeldItemModifier extends PersistentModifier { } getPokemon(): Pokemon | undefined { - return this.pokemonId ? gScene.getPokemonById(this.pokemonId) ?? undefined : undefined; + return this.pokemonId ? globalScene.getPokemonById(this.pokemonId) ?? undefined : undefined; } getScoreMultiplier(): number { @@ -746,7 +746,7 @@ export abstract class PokemonHeldItemModifier extends PersistentModifier { return 0; } if (pokemon.isPlayer() && forThreshold) { - return gScene.getParty().map(p => this.getMaxHeldItemCount(p)).reduce((stackCount: number, maxStackCount: number) => Math.max(stackCount, maxStackCount), 0); + return globalScene.getParty().map(p => this.getMaxHeldItemCount(p)).reduce((stackCount: number, maxStackCount: number) => Math.max(stackCount, maxStackCount), 0); } return this.getMaxHeldItemCount(pokemon); } @@ -835,10 +835,10 @@ export class TerastallizeModifier extends LapsingPokemonHeldItemModifier { */ override apply(pokemon: Pokemon): boolean { if (pokemon.isPlayer()) { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeTeraTrigger); - gScene.validateAchv(achvs.TERASTALLIZE); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeTeraTrigger); + globalScene.validateAchv(achvs.TERASTALLIZE); if (this.teraType === Type.STELLAR) { - gScene.validateAchv(achvs.STELLAR_TERASTALLIZE); + globalScene.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) { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeLapseTeraTrigger); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeLapseTeraTrigger); pokemon.updateSpritePipelineData(); } return ret; @@ -964,14 +964,14 @@ export class EvoTrackerModifier extends PokemonHeldItemModifier { return null; } - const pokemon = gScene.getPokemonById(this.pokemonId); + const pokemon = globalScene.getPokemonById(this.pokemonId); this.stackCount = pokemon ? pokemon.evoCounter + pokemon.getHeldItems().filter(m => m instanceof DamageMoneyRewardModifier).length - + gScene.findModifiers(m => m instanceof MoneyMultiplierModifier || m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length + + globalScene.findModifiers(m => m instanceof MoneyMultiplierModifier || m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length : this.stackCount; - const text = gScene.add.bitmapText(10, 15, "item-count", this.stackCount.toString(), 11); + const text = globalScene.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 - + gScene.findModifiers(m => m instanceof MoneyMultiplierModifier || m instanceof ExtraModifierModifier || m instanceof TempExtraModifierModifier).length; + + globalScene.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; - gScene.queueMessage(i18next.t("modifier:surviveDamageApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name })); + globalScene.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 = gScene.currentBattle.turnCommands[pokemon.getBattlerIndex()]?.command === Command.FIGHT; + const isCommandFight = globalScene.currentBattle.turnCommands[pokemon.getBattlerIndex()]?.command === Command.FIGHT; const hasQuickClaw = this.type instanceof PokemonHeldItemModifierType && this.type.id === "QUICK_CLAW"; if (isCommandFight && hasQuickClaw) { - gScene.queueMessage(i18next.t("modifier:bypassSpeedChanceApply", { pokemonName: getPokemonNameWithAffix(pokemon), itemName: i18next.t("modifierType:ModifierType.QUICK_CLAW.name") })); + globalScene.queueMessage(i18next.t("modifier:bypassSpeedChanceApply", { pokemonName: getPokemonNameWithAffix(pokemon), itemName: i18next.t("modifierType:ModifierType.QUICK_CLAW.name") })); } return true; } @@ -1675,7 +1675,7 @@ export class TurnHealModifier extends PokemonHeldItemModifier { */ override apply(pokemon: Pokemon): boolean { if (!pokemon.isFullHp()) { - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + globalScene.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; } @@ -1767,7 +1767,7 @@ export class HitHealModifier extends PokemonHeldItemModifier { */ override apply(pokemon: Pokemon): boolean { if (pokemon.turnData.damageDealt && !pokemon.isFullHp()) { - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + globalScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), toDmgValue(pokemon.turnData.damageDealt / 8) * this.stackCount, i18next.t("modifier:hitHealApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name }), true)); } @@ -1856,7 +1856,7 @@ export class BerryModifier extends PokemonHeldItemModifier { */ override apply(pokemon: Pokemon): boolean { const preserve = new BooleanHolder(false); - gScene.applyModifiers(PreserveBerryModifier, pokemon.isPlayer(), pokemon, preserve); + globalScene.applyModifiers(PreserveBerryModifier, pokemon.isPlayer(), pokemon, preserve); getBerryEffectFunc(this.berryType)(pokemon); if (!preserve.value) { @@ -1935,7 +1935,7 @@ export class PokemonInstantReviveModifier extends PokemonHeldItemModifier { * @returns always `true` */ override apply(pokemon: Pokemon): boolean { - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + globalScene.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); @@ -1983,7 +1983,7 @@ export class ResetNegativeStatStageModifier extends PokemonHeldItemModifier { } if (statRestored) { - gScene.queueMessage(i18next.t("modifier:resetNegativeStatStageApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name })); + globalScene.queueMessage(i18next.t("modifier:resetNegativeStatStageApply", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), typeName: this.type.name })); } return statRestored; } @@ -2020,7 +2020,7 @@ export abstract class ConsumablePokemonModifier extends ConsumableModifier { abstract override apply(playerPokemon: PlayerPokemon, ...args: unknown[]): boolean | Promise; getPokemon() { - return gScene.getParty().find(p => p.id === this.pokemonId); + return globalScene.getParty().find(p => p.id === this.pokemonId); } } @@ -2189,11 +2189,11 @@ export class PokemonNatureChangeModifier extends ConsumablePokemonModifier { override apply(playerPokemon: PlayerPokemon): boolean { playerPokemon.customPokemonData.nature = this.nature; let speciesId = playerPokemon.species.speciesId; - gScene.gameData.dexData[speciesId].natureAttr |= 1 << (this.nature + 1); + globalScene.gameData.dexData[speciesId].natureAttr |= 1 << (this.nature + 1); while (pokemonPrevolutions.hasOwnProperty(speciesId)) { speciesId = pokemonPrevolutions[speciesId]; - gScene.gameData.dexData[speciesId].natureAttr |= 1 << (this.nature + 1); + globalScene.gameData.dexData[speciesId].natureAttr |= 1 << (this.nature + 1); } return true; @@ -2212,17 +2212,17 @@ export class PokemonLevelIncrementModifier extends ConsumablePokemonModifier { * @returns always `true` */ override apply(playerPokemon: PlayerPokemon, levelCount: NumberHolder = new NumberHolder(1)): boolean { - gScene.applyModifiers(LevelIncrementBoosterModifier, true, levelCount); + globalScene.applyModifiers(LevelIncrementBoosterModifier, true, levelCount); playerPokemon.level += levelCount.value; - if (playerPokemon.level <= gScene.getMaxExpLevel(true)) { + if (playerPokemon.level <= globalScene.getMaxExpLevel(true)) { playerPokemon.exp = getLevelTotalExp(playerPokemon.level, playerPokemon.species.growthRate); playerPokemon.levelExp = 0; } playerPokemon.addFriendship(FRIENDSHIP_GAIN_FROM_RARE_CANDY); - gScene.unshiftPhase(new LevelUpPhase(gScene.getParty().indexOf(playerPokemon), playerPokemon.level - levelCount.value, playerPokemon.level)); + globalScene.unshiftPhase(new LevelUpPhase(globalScene.getParty().indexOf(playerPokemon), playerPokemon.level - levelCount.value, playerPokemon.level)); return true; } @@ -2242,7 +2242,7 @@ export class TmModifier extends ConsumablePokemonModifier { */ override apply(playerPokemon: PlayerPokemon): boolean { - gScene.unshiftPhase(new LearnMovePhase(gScene.getParty().indexOf(playerPokemon), this.type.moveId, LearnMoveType.TM)); + globalScene.unshiftPhase(new LearnMovePhase(globalScene.getParty().indexOf(playerPokemon), this.type.moveId, LearnMoveType.TM)); return true; } @@ -2264,7 +2264,7 @@ export class RememberMoveModifier extends ConsumablePokemonModifier { */ override apply(playerPokemon: PlayerPokemon, cost?: number): boolean { - gScene.unshiftPhase(new LearnMovePhase(gScene.getParty().indexOf(playerPokemon), playerPokemon.getLearnableLevelMoves()[this.levelMoveIndex], LearnMoveType.MEMORY, cost)); + globalScene.unshiftPhase(new LearnMovePhase(globalScene.getParty().indexOf(playerPokemon), playerPokemon.getLearnableLevelMoves()[this.levelMoveIndex], LearnMoveType.MEMORY, cost)); return true; } @@ -2299,7 +2299,7 @@ export class EvolutionItemModifier extends ConsumablePokemonModifier { } if (matchingEvolution) { - gScene.unshiftPhase(new EvolutionPhase(playerPokemon, matchingEvolution, playerPokemon.level - 1)); + globalScene.unshiftPhase(new EvolutionPhase(playerPokemon, matchingEvolution, playerPokemon.level - 1)); return true; } @@ -2746,7 +2746,7 @@ export class PokemonFormChangeItemModifier extends PokemonHeldItemModifier { this.active = false; } - const ret = gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeItemTrigger); + const ret = globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeItemTrigger); if (switchActive) { this.active = true; @@ -2774,17 +2774,17 @@ export class MoneyRewardModifier extends ConsumableModifier { * @returns always `true` */ override apply(): boolean { - const moneyAmount = new NumberHolder(gScene.getWaveMoneyAmount(this.moneyMultiplier)); + const moneyAmount = new NumberHolder(globalScene.getWaveMoneyAmount(this.moneyMultiplier)); - gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); + globalScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); - gScene.addMoney(moneyAmount.value); + globalScene.addMoney(moneyAmount.value); - gScene.getParty().map(p => { + globalScene.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; - gScene.addModifier(modifier); + globalScene.addModifier(modifier); } }); @@ -2842,8 +2842,8 @@ export class DamageMoneyRewardModifier extends PokemonHeldItemModifier { */ override apply(pokemon: Pokemon, multiplier: NumberHolder): boolean { const moneyAmount = new NumberHolder(Math.floor(multiplier.value * (0.5 * this.getStackCount()))); - gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); - gScene.addMoney(moneyAmount.value); + globalScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); + globalScene.addMoney(moneyAmount.value); return true; } @@ -2867,13 +2867,13 @@ export class MoneyInterestModifier extends PersistentModifier { * @returns always `true` */ override apply(): boolean { - const interestAmount = Math.floor(gScene.money * 0.1 * this.getStackCount()); - gScene.addMoney(interestAmount); + const interestAmount = Math.floor(globalScene.money * 0.1 * this.getStackCount()); + globalScene.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 }); - gScene.queueMessage(message, undefined, true); + globalScene.queueMessage(message, undefined, true); return true; } @@ -3110,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 = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const itemModifiers = globalScene.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); @@ -3128,7 +3128,7 @@ export abstract class HeldItemTransferModifier extends PokemonHeldItemModifier { } const randItemIndex = pokemon.randSeedInt(itemModifiers.length); const randItem = itemModifiers[randItemIndex]; - heldItemTransferPromises.push(gScene.tryTransferHeldItemModifier(randItem, pokemon, false).then(success => { + heldItemTransferPromises.push(globalScene.tryTransferHeldItemModifier(randItem, pokemon, false).then(success => { if (success) { transferredModifierTypes.push(randItem.type); itemModifiers.splice(randItemIndex, 1); @@ -3138,7 +3138,7 @@ export abstract class HeldItemTransferModifier extends PokemonHeldItemModifier { Promise.all(heldItemTransferPromises).then(() => { for (const mt of transferredModifierTypes) { - gScene.queueMessage(this.getTransferMessage(pokemon, targetPokemon, mt)); + globalScene.queueMessage(this.getTransferMessage(pokemon, targetPokemon, mt)); } }); @@ -3317,7 +3317,7 @@ export class TempExtraModifierModifier extends LapsingPersistentModifier { const newBattleCount = this.getMaxBattles() + modifierInstance.getBattleCount(); modifierInstance.setNewBattleCount(newBattleCount); - gScene.playSound("se/restore"); + globalScene.playSound("se/restore"); return true; } } @@ -3422,7 +3422,7 @@ export class EnemyDamageReducerModifier extends EnemyDamageMultiplierModifier { } getMaxStackCount(): number { - return gScene.currentBattle.waveIndex < 2000 ? super.getMaxStackCount() : 999; + return globalScene.currentBattle.waveIndex < 2000 ? super.getMaxStackCount() : 999; } } @@ -3455,7 +3455,7 @@ export class EnemyTurnHealModifier extends EnemyPersistentModifier { */ override apply(enemyPokemon: Pokemon): boolean { if (!enemyPokemon.isFullHp()) { - gScene.unshiftPhase(new PokemonHealPhase(enemyPokemon.getBattlerIndex(), + globalScene.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; } @@ -3539,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())) { - gScene.queueMessage(getStatusEffectHealText(enemyPokemon.status.effect, getPokemonNameWithAffix(enemyPokemon))); + globalScene.queueMessage(getStatusEffectHealText(enemyPokemon.status.effect, getPokemonNameWithAffix(enemyPokemon))); enemyPokemon.resetStatus(); enemyPokemon.updateInfo(); return true; @@ -3647,13 +3647,13 @@ export class EnemyFusionChanceModifier extends EnemyPersistentModifier { */ export function overrideModifiers(isPlayer: boolean = true): void { const modifiersOverride: ModifierOverride[] = isPlayer ? Overrides.STARTING_MODIFIER_OVERRIDE : Overrides.OPP_MODIFIER_OVERRIDE; - if (!modifiersOverride || modifiersOverride.length === 0 || !gScene) { + if (!modifiersOverride || modifiersOverride.length === 0 || !globalScene) { return; } // If it's the opponent, clear all of their current modifiers to avoid stacking if (!isPlayer) { - gScene.clearEnemyModifiers(); + globalScene.clearEnemyModifiers(); } modifiersOverride.forEach(item => { @@ -3670,9 +3670,9 @@ export function overrideModifiers(isPlayer: boolean = true): void { modifier.stackCount = item.count || 1; if (isPlayer) { - gScene.addModifier(modifier, true, false, false, true); + globalScene.addModifier(modifier, true, false, false, true); } else { - gScene.addEnemyModifier(modifier, true, true); + globalScene.addEnemyModifier(modifier, true, true); } } }); @@ -3688,12 +3688,12 @@ export function overrideModifiers(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 || !gScene) { + if (!heldItemsOverride || heldItemsOverride.length === 0 || !globalScene) { return; } if (!isPlayer) { - gScene.clearEnemyHeldItemModifiers(pokemon); + globalScene.clearEnemyHeldItemModifiers(pokemon); } heldItemsOverride.forEach(item => { @@ -3711,9 +3711,9 @@ export function overrideHeldItems(pokemon: Pokemon, isPlayer: boolean = true): v heldItemModifier.pokemonId = pokemon.id; heldItemModifier.stackCount = qty; if (isPlayer) { - gScene.addModifier(heldItemModifier, true, false, false, true); + globalScene.addModifier(heldItemModifier, true, false, false, true); } else { - gScene.addEnemyModifier(heldItemModifier, true, true); + globalScene.addEnemyModifier(heldItemModifier, true, true); } } }); diff --git a/src/phase.ts b/src/phase.ts index 8a1869d910d..359db402f72 100644 --- a/src/phase.ts +++ b/src/phase.ts @@ -1,13 +1,13 @@ -import { gScene } from "./battle-scene"; +import { globalScene } from "./battle-scene"; export class Phase { start() { - if (gScene.abilityBar.shown) { - gScene.abilityBar.resetAutoHideTimer(); + if (globalScene.abilityBar.shown) { + globalScene.abilityBar.resetAutoHideTimer(); } } end() { - gScene.shiftPhase(); + globalScene.shiftPhase(); } } diff --git a/src/phases/add-enemy-buff-modifier-phase.ts b/src/phases/add-enemy-buff-modifier-phase.ts index bd1234bb54d..4e184770760 100644 --- a/src/phases/add-enemy-buff-modifier-phase.ts +++ b/src/phases/add-enemy-buff-modifier-phase.ts @@ -2,7 +2,7 @@ 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"; +import { globalScene } from "#app/battle-scene"; export class AddEnemyBuffModifierPhase extends Phase { constructor() { @@ -12,15 +12,15 @@ export class AddEnemyBuffModifierPhase extends Phase { start() { super.start(); - const waveIndex = gScene.currentBattle.waveIndex; + const waveIndex = globalScene.currentBattle.waveIndex; const tier = !(waveIndex % 1000) ? ModifierTier.ULTRA : !(waveIndex % 250) ? ModifierTier.GREAT : ModifierTier.COMMON; - regenerateModifierPoolThresholds(gScene.getEnemyParty(), ModifierPoolType.ENEMY_BUFF); + regenerateModifierPoolThresholds(globalScene.getEnemyParty(), ModifierPoolType.ENEMY_BUFF); const count = Math.ceil(waveIndex / 250); for (let i = 0; i < count; i++) { - gScene.addEnemyModifier(getEnemyBuffModifierForWave(tier, gScene.findModifiers(m => m instanceof EnemyPersistentModifier, false)), true, true); + globalScene.addEnemyModifier(getEnemyBuffModifierForWave(tier, globalScene.findModifiers(m => m instanceof EnemyPersistentModifier, false)), true, true); } - gScene.updateModifiers(false, true).then(() => this.end()); + globalScene.updateModifiers(false, true).then(() => this.end()); } } diff --git a/src/phases/attempt-capture-phase.ts b/src/phases/attempt-capture-phase.ts index 80c4653ae9b..9cc91085884 100644 --- a/src/phases/attempt-capture-phase.ts +++ b/src/phases/attempt-capture-phase.ts @@ -15,7 +15,7 @@ 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"; +import { globalScene } from "#app/battle-scene"; export class AttemptCapturePhase extends PokemonPhase { private pokeballType: PokeballType; @@ -42,7 +42,7 @@ export class AttemptCapturePhase extends PokemonPhase { substitute.sprite.setVisible(false); } - gScene.pokeballCounts[this.pokeballType]--; + globalScene.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 = gScene.addFieldSprite(16, 80, "pb", pokeballAtlasKey); + this.pokeball = globalScene.addFieldSprite(16, 80, "pb", pokeballAtlasKey); this.pokeball.setOrigin(0.5, 0.625); - gScene.field.add(this.pokeball); + globalScene.field.add(this.pokeball); - gScene.playSound("se/pb_throw"); - gScene.time.delayedCall(300, () => { - gScene.field.moveBelow(this.pokeball as Phaser.GameObjects.GameObject, pokemon); + globalScene.playSound("se/pb_throw"); + globalScene.time.delayedCall(300, () => { + globalScene.field.moveBelow(this.pokeball as Phaser.GameObjects.GameObject, pokemon); }); - gScene.tweens.add({ + globalScene.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`); - gScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`)); - gScene.playSound("se/pb_rel"); + globalScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`)); + globalScene.playSound("se/pb_rel"); pokemon.tint(getPokeballTintColor(this.pokeballType)); addPokeballOpenParticles(this.pokeball.x, this.pokeball.y, this.pokeballType); - gScene.tweens.add({ + globalScene.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); - gScene.playSound("se/pb_catch"); - gScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}`)); + globalScene.playSound("se/pb_catch"); + globalScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}`)); const doShake = () => { let shakeCount = 0; const pbX = this.pokeball.x; - const shakeCounter = gScene.tweens.addCounter({ + const shakeCounter = globalScene.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) { - gScene.playSound("se/pb_move"); + globalScene.playSound("se/pb_move"); } else { shakeCounter.stop(); this.failCatch(shakeCount); } } else { - gScene.playSound("se/pb_lock"); + globalScene.playSound("se/pb_lock"); addPokeballCaptureStars(this.pokeball); - const pbTint = gScene.add.sprite(this.pokeball.x, this.pokeball.y, "pb", "pb"); + const pbTint = globalScene.add.sprite(this.pokeball.x, this.pokeball.y, "pb", "pb"); pbTint.setOrigin(this.pokeball.originX, this.pokeball.originY); pbTint.setTintFill(0); pbTint.setAlpha(0); - gScene.field.add(pbTint); - gScene.tweens.add({ + globalScene.field.add(pbTint); + globalScene.tweens.add({ targets: pbTint, alpha: 0.375, duration: 200, easing: "Sine.easeOut", onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: pbTint, alpha: 0, duration: 200, @@ -152,7 +152,7 @@ export class AttemptCapturePhase extends PokemonPhase { }); }; - gScene.time.delayedCall(250, () => doPokeballBounceAnim(this.pokeball, 16, 72, 350, doShake)); + globalScene.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(); - gScene.playSound("se/pb_rel"); + globalScene.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`); - gScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`)); + globalScene.time.delayedCall(17, () => this.pokeball.setTexture("pb", `${pokeballAtlasKey}_open`)); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, duration: 250, ease: "Sine.easeOut", scale: 1 }); - gScene.currentBattle.lastUsedPokeball = this.pokeballType; + globalScene.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) { - gScene.validateAchv(achvs.HIDDEN_ABILITY); + globalScene.validateAchv(achvs.HIDDEN_ABILITY); } if (pokemon.species.subLegendary) { - gScene.validateAchv(achvs.CATCH_SUB_LEGENDARY); + globalScene.validateAchv(achvs.CATCH_SUB_LEGENDARY); } if (pokemon.species.legendary) { - gScene.validateAchv(achvs.CATCH_LEGENDARY); + globalScene.validateAchv(achvs.CATCH_LEGENDARY); } if (pokemon.species.mythical) { - gScene.validateAchv(achvs.CATCH_MYTHICAL); + globalScene.validateAchv(achvs.CATCH_MYTHICAL); } - gScene.pokemonInfoContainer.show(pokemon, true); + globalScene.pokemonInfoContainer.show(pokemon, true); - gScene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs); + globalScene.gameData.updateSpeciesDexIvs(pokemon.species.getRootSpeciesId(true), pokemon.ivs); - gScene.ui.showText(i18next.t("battle:pokemonCaught", { pokemonName: getPokemonNameWithAffix(pokemon) }), null, () => { + globalScene.ui.showText(i18next.t("battle:pokemonCaught", { pokemonName: getPokemonNameWithAffix(pokemon) }), null, () => { const end = () => { - gScene.unshiftPhase(new VictoryPhase(this.battlerIndex)); - gScene.pokemonInfoContainer.hide(); + globalScene.unshiftPhase(new VictoryPhase(this.battlerIndex)); + globalScene.pokemonInfoContainer.hide(); this.removePb(); this.end(); }; const removePokemon = () => { - gScene.addFaintedEnemyScore(pokemon); - gScene.getPlayerField().filter(p => p.isActive(true)).forEach(playerPokemon => playerPokemon.removeTagsBySourceId(pokemon.id)); + globalScene.addFaintedEnemyScore(pokemon); + globalScene.getPlayerField().filter(p => p.isActive(true)).forEach(playerPokemon => playerPokemon.removeTagsBySourceId(pokemon.id)); pokemon.hp = 0; pokemon.trySetStatus(StatusEffect.FAINT); - gScene.clearEnemyHeldItemModifiers(); - gScene.field.remove(pokemon, true); + globalScene.clearEnemyHeldItemModifiers(); + globalScene.field.remove(pokemon, true); }; const addToParty = (slotIndex?: number) => { const newPokemon = pokemon.addToParty(this.pokeballType, slotIndex); - const modifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier, false); - if (gScene.getParty().filter(p => p.isShiny()).length === 6) { - gScene.validateAchv(achvs.SHINY_PARTY); + const modifiers = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier, false); + if (globalScene.getParty().filter(p => p.isShiny()).length === 6) { + globalScene.validateAchv(achvs.SHINY_PARTY); } - Promise.all(modifiers.map(m => gScene.addModifier(m, true))).then(() => { - gScene.updateModifiers(true); + Promise.all(modifiers.map(m => globalScene.addModifier(m, true))).then(() => { + globalScene.updateModifiers(true); removePokemon(); if (newPokemon) { newPokemon.loadAssets().then(end); @@ -248,21 +248,21 @@ export class AttemptCapturePhase extends PokemonPhase { } }); }; - Promise.all([ pokemon.hideInfo(), gScene.gameData.setPokemonCaught(pokemon) ]).then(() => { - if (gScene.getParty().length === 6) { + Promise.all([ pokemon.hideInfo(), globalScene.gameData.setPokemonCaught(pokemon) ]).then(() => { + if (globalScene.getParty().length === 6) { const promptRelease = () => { - 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(() => { + globalScene.ui.showText(i18next.t("battle:partyFull", { pokemonName: pokemon.getNameToRender() }), null, () => { + globalScene.pokemonInfoContainer.makeRoomForConfirmUi(1, true); + globalScene.ui.setMode(Mode.CONFIRM, () => { + const newPokemon = globalScene.addPlayerPokemon(pokemon.species, pokemon.level, pokemon.abilityIndex, pokemon.formIndex, pokemon.gender, pokemon.shiny, pokemon.variant, pokemon.ivs, pokemon.nature, pokemon); + globalScene.ui.setMode(Mode.SUMMARY, newPokemon, 0, SummaryUiMode.DEFAULT, () => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { promptRelease(); }); }, false); }, () => { - gScene.ui.setMode(Mode.PARTY, PartyUiMode.RELEASE, this.fieldIndex, (slotIndex: integer, _option: PartyOption) => { - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.PARTY, PartyUiMode.RELEASE, this.fieldIndex, (slotIndex: integer, _option: PartyOption) => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { if (slotIndex < 6) { addToParty(slotIndex); } else { @@ -271,7 +271,7 @@ export class AttemptCapturePhase extends PokemonPhase { }); }); }, () => { - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { removePokemon(); end(); }); @@ -287,7 +287,7 @@ export class AttemptCapturePhase extends PokemonPhase { } removePb() { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pokeball, duration: 250, delay: 250, diff --git a/src/phases/attempt-run-phase.ts b/src/phases/attempt-run-phase.ts index 37ba500c3e0..82b1b5db413 100644 --- a/src/phases/attempt-run-phase.ts +++ b/src/phases/attempt-run-phase.ts @@ -7,7 +7,7 @@ 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"; +import { globalScene } from "#app/battle-scene"; export class AttemptRunPhase extends PokemonPhase { @@ -21,8 +21,8 @@ export class AttemptRunPhase extends PokemonPhase { start() { super.start(); - const playerField = gScene.getPlayerField(); - const enemyField = gScene.getEnemyField(); + const playerField = globalScene.getPlayerField(); + const enemyField = globalScene.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) { - gScene.playSound("se/flee"); - gScene.queueMessage(i18next.t("battle:runAwaySuccess"), null, true, 500); + globalScene.playSound("se/flee"); + globalScene.queueMessage(i18next.t("battle:runAwaySuccess"), null, true, 500); - gScene.tweens.add({ - targets: [ gScene.arenaEnemy, enemyField ].flat(), + globalScene.tweens.add({ + targets: [ globalScene.arenaEnemy, enemyField ].flat(), alpha: 0, duration: 250, ease: "Sine.easeIn", onComplete: () => enemyField.forEach(enemyPokemon => enemyPokemon.destroy()) }); - gScene.clearEnemyHeldItemModifiers(); + globalScene.clearEnemyHeldItemModifiers(); enemyField.forEach(enemyPokemon => { enemyPokemon.hideInfo().then(() => enemyPokemon.destroy()); @@ -52,11 +52,11 @@ export class AttemptRunPhase extends PokemonPhase { enemyPokemon.trySetStatus(StatusEffect.FAINT); }); - gScene.pushPhase(new BattleEndPhase()); - gScene.pushPhase(new NewBattlePhase()); + globalScene.pushPhase(new BattleEndPhase()); + globalScene.pushPhase(new NewBattlePhase()); } else { playerPokemon.turnData.failedRunAway = true; - gScene.queueMessage(i18next.t("battle:runAwayCannotEscape"), null, true, 500); + globalScene.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 * gScene.currentBattle.escapeAttempts++)), minChance, maxChance); + escapeChance.value = Phaser.Math.Clamp(Math.round((escapeSlope * speedRatio) + minChance + (escapeBonus * globalScene.currentBattle.escapeAttempts++)), minChance, maxChance); } } diff --git a/src/phases/battle-end-phase.ts b/src/phases/battle-end-phase.ts index b59295898f4..c577416629c 100644 --- a/src/phases/battle-end-phase.ts +++ b/src/phases/battle-end-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { applyPostBattleAbAttrs, PostBattleAbAttr } from "#app/data/ability"; import { LapsingPersistentModifier, LapsingPokemonHeldItemModifier } from "#app/modifier/modifier"; import { BattlePhase } from "./battle-phase"; @@ -18,50 +18,50 @@ export class BattleEndPhase extends BattlePhase { super.start(); if (this.isVictory) { - gScene.currentBattle.addBattleScore(); + globalScene.currentBattle.addBattleScore(); - gScene.gameData.gameStats.battles++; - if (gScene.currentBattle.trainer) { - gScene.gameData.gameStats.trainersDefeated++; + globalScene.gameData.gameStats.battles++; + if (globalScene.currentBattle.trainer) { + globalScene.gameData.gameStats.trainersDefeated++; } - if (gScene.gameMode.isEndless && gScene.currentBattle.waveIndex + 1 > gScene.gameData.gameStats.highestEndlessWave) { - gScene.gameData.gameStats.highestEndlessWave = gScene.currentBattle.waveIndex + 1; + if (globalScene.gameMode.isEndless && globalScene.currentBattle.waveIndex + 1 > globalScene.gameData.gameStats.highestEndlessWave) { + globalScene.gameData.gameStats.highestEndlessWave = globalScene.currentBattle.waveIndex + 1; } } // Endless graceful end - if (gScene.gameMode.isEndless && gScene.currentBattle.waveIndex >= 5850) { - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new GameOverPhase(true)); + if (globalScene.gameMode.isEndless && globalScene.currentBattle.waveIndex >= 5850) { + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new GameOverPhase(true)); } - for (const pokemon of gScene.getField()) { + for (const pokemon of globalScene.getField()) { if (pokemon && pokemon.battleSummonData) { pokemon.battleSummonData.waveTurnCount = 1; } } - for (const pokemon of gScene.getParty().filter(p => p.isAllowedInBattle())) { + for (const pokemon of globalScene.getParty().filter(p => p.isAllowedInBattle())) { applyPostBattleAbAttrs(PostBattleAbAttr, pokemon); } - if (gScene.currentBattle.moneyScattered) { - gScene.currentBattle.pickUpScatteredMoney(); + if (globalScene.currentBattle.moneyScattered) { + globalScene.currentBattle.pickUpScatteredMoney(); } - gScene.clearEnemyHeldItemModifiers(); + globalScene.clearEnemyHeldItemModifiers(); - const lapsingModifiers = gScene.findModifiers(m => m instanceof LapsingPersistentModifier || m instanceof LapsingPokemonHeldItemModifier) as (LapsingPersistentModifier | LapsingPokemonHeldItemModifier)[]; + const lapsingModifiers = globalScene.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(gScene.getPokemonById(m.pokemonId)); + args.push(globalScene.getPokemonById(m.pokemonId)); } if (!m.lapse(...args)) { - gScene.removeModifier(m); + globalScene.removeModifier(m); } } - gScene.updateModifiers().then(() => this.end()); + globalScene.updateModifiers().then(() => this.end()); } } diff --git a/src/phases/battle-phase.ts b/src/phases/battle-phase.ts index 9422f00221d..52450e7bdd9 100644 --- a/src/phases/battle-phase.ts +++ b/src/phases/battle-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { TrainerSlot } from "#app/data/trainer-config"; import { Phase } from "#app/phase"; @@ -8,8 +8,8 @@ export class BattlePhase extends Phase { } showEnemyTrainer(trainerSlot: TrainerSlot = TrainerSlot.NONE): void { - const sprites = gScene.currentBattle.trainer?.getSprites()!; // TODO: is this bang correct? - const tintSprites = gScene.currentBattle.trainer?.getTintSprites()!; // TODO: is this bang correct? + const sprites = globalScene.currentBattle.trainer?.getSprites()!; // TODO: is this bang correct? + const tintSprites = globalScene.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(); } - gScene.tweens.add({ - targets: gScene.currentBattle.trainer, + globalScene.tweens.add({ + targets: globalScene.currentBattle.trainer, x: "-=16", y: "+=16", alpha: 1, @@ -35,8 +35,8 @@ export class BattlePhase extends Phase { } hideEnemyTrainer(): void { - gScene.tweens.add({ - targets: gScene.currentBattle.trainer, + globalScene.tweens.add({ + targets: globalScene.currentBattle.trainer, x: "+=16", y: "-=16", alpha: 0, diff --git a/src/phases/berry-phase.ts b/src/phases/berry-phase.ts index de96eccd940..13fde4b230c 100644 --- a/src/phases/berry-phase.ts +++ b/src/phases/berry-phase.ts @@ -7,7 +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"; +import { globalScene } from "#app/battle-scene"; /** The phase after attacks where the pokemon eat berries */ export class BerryPhase extends FieldPhase { @@ -15,7 +15,7 @@ export class BerryPhase extends FieldPhase { super.start(); this.executeForAll((pokemon) => { - const hasUsableBerry = !!gScene.findModifier((m) => { + const hasUsableBerry = !!globalScene.findModifier((m) => { return m instanceof BerryModifier && m.shouldApply(pokemon); }, pokemon.isPlayer()); @@ -24,24 +24,24 @@ export class BerryPhase extends FieldPhase { pokemon.getOpponents().map((opp) => applyAbAttrs(PreventBerryUseAbAttr, opp, cancelled)); if (cancelled.value) { - gScene.queueMessage(i18next.t("abilityTriggers:preventBerryUse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); + globalScene.queueMessage(i18next.t("abilityTriggers:preventBerryUse", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) })); } else { - gScene.unshiftPhase( + globalScene.unshiftPhase( new CommonAnimPhase(pokemon.getBattlerIndex(), pokemon.getBattlerIndex(), CommonAnim.USE_ITEM) ); - for (const berryModifier of gScene.applyModifiers(BerryModifier, pokemon.isPlayer(), pokemon)) { + for (const berryModifier of globalScene.applyModifiers(BerryModifier, pokemon.isPlayer(), pokemon)) { if (berryModifier.consumed) { if (!--berryModifier.stackCount) { - gScene.removeModifier(berryModifier); + globalScene.removeModifier(berryModifier); } else { berryModifier.consumed = false; } } - gScene.eventTarget.dispatchEvent(new BerryUsedEvent(berryModifier)); // Announce a berry was used + globalScene.eventTarget.dispatchEvent(new BerryUsedEvent(berryModifier)); // Announce a berry was used } - gScene.updateModifiers(pokemon.isPlayer()); + globalScene.updateModifiers(pokemon.isPlayer()); applyAbAttrs(HealFromBerryUseAbAttr, pokemon, new Utils.BooleanHolder(false)); } diff --git a/src/phases/check-status-effect-phase.ts b/src/phases/check-status-effect-phase.ts index d77c3214146..d3ea70fc390 100644 --- a/src/phases/check-status-effect-phase.ts +++ b/src/phases/check-status-effect-phase.ts @@ -1,7 +1,7 @@ import { PostTurnStatusEffectPhase } from "#app/phases/post-turn-status-effect-phase"; import { Phase } from "#app/phase"; import { BattlerIndex } from "#app/battle"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class CheckStatusEffectPhase extends Phase { private order : BattlerIndex[]; @@ -11,10 +11,10 @@ export class CheckStatusEffectPhase extends Phase { } start() { - const field = gScene.getField(); + const field = globalScene.getField(); for (const o of this.order) { if (field[o].status && field[o].status.isPostTurn()) { - gScene.unshiftPhase(new PostTurnStatusEffectPhase(o)); + globalScene.unshiftPhase(new PostTurnStatusEffectPhase(o)); } } this.end(); diff --git a/src/phases/check-switch-phase.ts b/src/phases/check-switch-phase.ts index aedc6e31ec8..5e2047dd1be 100644 --- a/src/phases/check-switch-phase.ts +++ b/src/phases/check-switch-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattleStyle } from "#app/enums/battle-style"; import { BattlerTagType } from "#app/enums/battler-tag-type"; import { getPokemonNameWithAffix } from "#app/messages"; @@ -24,20 +24,20 @@ export class CheckSwitchPhase extends BattlePhase { start() { super.start(); - const pokemon = gScene.getPlayerField()[this.fieldIndex]; + const pokemon = globalScene.getPlayerField()[this.fieldIndex]; - if (gScene.battleStyle === BattleStyle.SET) { + if (globalScene.battleStyle === BattleStyle.SET) { super.end(); return; } - if (gScene.field.getAll().indexOf(pokemon) === -1) { - gScene.unshiftPhase(new SummonMissingPhase(this.fieldIndex)); + if (globalScene.field.getAll().indexOf(pokemon) === -1) { + globalScene.unshiftPhase(new SummonMissingPhase(this.fieldIndex)); super.end(); return; } - if (!gScene.getParty().slice(1).filter(p => p.isActive()).length) { + if (!globalScene.getParty().slice(1).filter(p => p.isActive()).length) { super.end(); return; } @@ -47,14 +47,14 @@ export class CheckSwitchPhase extends BattlePhase { return; } - 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)); + globalScene.ui.showText(i18next.t("battle:switchQuestion", { pokemonName: this.useName ? getPokemonNameWithAffix(pokemon) : i18next.t("battle:pokemon") }), null, () => { + globalScene.ui.setMode(Mode.CONFIRM, () => { + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.tryRemovePhase(p => p instanceof PostSummonPhase && p.player && p.fieldIndex === this.fieldIndex); + globalScene.unshiftPhase(new SwitchPhase(SwitchType.INITIAL_SWITCH, this.fieldIndex, false, true)); this.end(); }, () => { - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.MESSAGE); this.end(); }); }); diff --git a/src/phases/command-phase.ts b/src/phases/command-phase.ts index 94d66948411..91f20212ee3 100644 --- a/src/phases/command-phase.ts +++ b/src/phases/command-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -30,9 +30,9 @@ export class CommandPhase extends FieldPhase { start() { super.start(); - const commandUiHandler = gScene.ui.handlers[Mode.COMMAND]; + const commandUiHandler = globalScene.ui.handlers[Mode.COMMAND]; if (commandUiHandler) { - if (gScene.currentBattle.turn === 1 || commandUiHandler.getCursor() === Command.POKEMON) { + if (globalScene.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 (gScene.getPlayerField().filter(p => p.isActive()).length === 1) { + if (globalScene.getPlayerField().filter(p => p.isActive()).length === 1) { this.fieldIndex = FieldPosition.CENTER; } else { - const allyCommand = gScene.currentBattle.turnCommands[this.fieldIndex - 1]; + const allyCommand = globalScene.currentBattle.turnCommands[this.fieldIndex - 1]; if (allyCommand?.command === Command.BALL || allyCommand?.command === Command.RUN) { - gScene.currentBattle.turnCommands[this.fieldIndex] = { command: allyCommand?.command, skip: true }; + globalScene.currentBattle.turnCommands[this.fieldIndex] = { command: allyCommand?.command, skip: true }; } } } - if (gScene.currentBattle.turnCommands[this.fieldIndex]?.skip) { + if (globalScene.currentBattle.turnCommands[this.fieldIndex]?.skip) { return this.end(); } - const playerPokemon = gScene.getPlayerField()[this.fieldIndex]; + const playerPokemon = globalScene.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 { - gScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); } } } else { - if (gScene.currentBattle.isBattleMysteryEncounter() && gScene.currentBattle.mysteryEncounter?.skipToFightInput) { - gScene.ui.clearText(); - gScene.ui.setMode(Mode.FIGHT, this.fieldIndex); + if (globalScene.currentBattle.isBattleMysteryEncounter() && globalScene.currentBattle.mysteryEncounter?.skipToFightInput) { + globalScene.ui.clearText(); + globalScene.ui.setMode(Mode.FIGHT, this.fieldIndex); } else { - gScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); } } } handleCommand(command: Command, cursor: integer, ...args: any[]): boolean { - const playerPokemon = gScene.getPlayerField()[this.fieldIndex]; + const playerPokemon = globalScene.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) { - gScene.unshiftPhase(new SelectTargetPhase(this.fieldIndex)); + globalScene.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 { - gScene.unshiftPhase(new SelectTargetPhase(this.fieldIndex)); + globalScene.unshiftPhase(new SelectTargetPhase(this.fieldIndex)); } - gScene.currentBattle.turnCommands[this.fieldIndex] = turnCommand; + globalScene.currentBattle.turnCommands[this.fieldIndex] = turnCommand; success = true; } else if (cursor < playerPokemon.getMoveset().length) { const move = playerPokemon.getMoveset()[cursor]!; //TODO: is this bang correct? - gScene.ui.setMode(Mode.MESSAGE); + globalScene.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 - gScene.ui.showText(i18next.t(errorMessage, { moveName: moveName }), null, () => { - gScene.ui.clearText(); - gScene.ui.setMode(Mode.FIGHT, this.fieldIndex); + globalScene.ui.showText(i18next.t(errorMessage, { moveName: moveName }), null, () => { + globalScene.ui.clearText(); + globalScene.ui.setMode(Mode.FIGHT, this.fieldIndex); }, null, true); } break; case Command.BALL: - 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); + const notInDex = (globalScene.getEnemyField().filter(p => p.isActive(true)).some(p => !globalScene.gameData.dexData[p.species.speciesId].caughtAttr) && globalScene.gameData.getStarterCount(d => !!d.caughtAttr) < Object.keys(speciesStarterCosts).length - 1); + if (globalScene.arena.biomeType === Biome.END && (!globalScene.gameMode.isClassic || globalScene.gameMode.isFreshStartChallenge() || notInDex )) { + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:noPokeballForce"), null, () => { + globalScene.ui.showText("", 0); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); }, null, true); - } 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); + } else if (globalScene.currentBattle.battleType === BattleType.TRAINER) { + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:noPokeballTrainer"), null, () => { + globalScene.ui.showText("", 0); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); }, null, true); - } 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); + } else if (globalScene.currentBattle.isBattleMysteryEncounter() && !globalScene.currentBattle.mysteryEncounter!.catchAllowed) { + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:noPokeballMysteryEncounter"), null, () => { + globalScene.ui.showText("", 0); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); }, null, true); } else { - const targets = gScene.getEnemyField().filter(p => p.isActive(true)).map(p => p.getBattlerIndex()); + const targets = globalScene.getEnemyField().filter(p => p.isActive(true)).map(p => p.getBattlerIndex()); if (targets.length > 1) { - 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); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:noPokeballMulti"), null, () => { + globalScene.ui.showText("", 0); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); }, null, true); } else if (cursor < 5) { - const targetPokemon = gScene.getEnemyField().find(p => p.isActive(true)); + const targetPokemon = globalScene.getEnemyField().find(p => p.isActive(true)); if (targetPokemon?.isBoss() && targetPokemon?.bossSegmentIndex >= 1 && !targetPokemon?.hasAbility(Abilities.WONDER_GUARD, false, true) && cursor < PokeballType.MASTER_BALL) { - 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); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:noPokeballStrong"), null, () => { + globalScene.ui.showText("", 0); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); }, null, true); } else { - gScene.currentBattle.turnCommands[this.fieldIndex] = { command: Command.BALL, cursor: cursor }; - gScene.currentBattle.turnCommands[this.fieldIndex]!.targets = targets; + globalScene.currentBattle.turnCommands[this.fieldIndex] = { command: Command.BALL, cursor: cursor }; + globalScene.currentBattle.turnCommands[this.fieldIndex]!.targets = targets; if (this.fieldIndex) { - gScene.currentBattle.turnCommands[this.fieldIndex - 1]!.skip = true; + globalScene.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 } = gScene; + const { currentBattle, arena } = globalScene; const mysteryEncounterFleeAllowed = currentBattle.mysteryEncounter?.fleeAllowed; if (!isSwitch && (arena.biomeType === Biome.END || (!isNullOrUndefined(mysteryEncounterFleeAllowed) && !mysteryEncounterFleeAllowed))) { - 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); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:noEscapeForce"), null, () => { + globalScene.ui.showText("", 0); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); }, null, true); } else if (!isSwitch && (currentBattle.battleType === BattleType.TRAINER || currentBattle.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE)) { - 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); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:noEscapeTrainer"), null, () => { + globalScene.ui.showText("", 0); + globalScene.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) { - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.MESSAGE); } - gScene.ui.showText(trappedAbMessages[0], null, () => { - gScene.ui.showText("", 0); + globalScene.ui.showText(trappedAbMessages[0], null, () => { + globalScene.ui.showText("", 0); if (!isSwitch) { - gScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); } }, null, true); } else { @@ -238,20 +238,20 @@ export class CommandPhase extends FieldPhase { } if (!isSwitch) { - gScene.ui.setMode(Mode.COMMAND, this.fieldIndex); - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.MESSAGE); } - gScene.ui.showText( + globalScene.ui.showText( i18next.t("battle:noEscapePokemon", { - pokemonName: trapTag.sourceId && gScene.getPokemonById(trapTag.sourceId) ? getPokemonNameWithAffix(gScene.getPokemonById(trapTag.sourceId)!) : "", + pokemonName: trapTag.sourceId && globalScene.getPokemonById(trapTag.sourceId) ? getPokemonNameWithAffix(globalScene.getPokemonById(trapTag.sourceId)!) : "", moveName: trapTag.getMoveName(), escapeVerb: isSwitch ? i18next.t("battle:escapeVerbSwitch") : i18next.t("battle:escapeVerbFlee") }), null, () => { - gScene.ui.showText("", 0); + globalScene.ui.showText("", 0); if (!isSwitch) { - gScene.ui.setMode(Mode.COMMAND, this.fieldIndex); + globalScene.ui.setMode(Mode.COMMAND, this.fieldIndex); } }, null, true); } @@ -268,8 +268,8 @@ export class CommandPhase extends FieldPhase { cancel() { if (this.fieldIndex) { - gScene.unshiftPhase(new CommandPhase(0)); - gScene.unshiftPhase(new CommandPhase(1)); + globalScene.unshiftPhase(new CommandPhase(0)); + globalScene.unshiftPhase(new CommandPhase(1)); this.end(); } } @@ -299,10 +299,10 @@ export class CommandPhase extends FieldPhase { } getPokemon(): PlayerPokemon { - return gScene.getPlayerField()[this.fieldIndex]; + return globalScene.getPlayerField()[this.fieldIndex]; } end() { - gScene.ui.setMode(Mode.MESSAGE).then(() => super.end()); + globalScene.ui.setMode(Mode.MESSAGE).then(() => super.end()); } } diff --git a/src/phases/common-anim-phase.ts b/src/phases/common-anim-phase.ts index c75451c3bf8..c354c1cbd7a 100644 --- a/src/phases/common-anim-phase.ts +++ b/src/phases/common-anim-phase.ts @@ -1,5 +1,5 @@ import { BattlerIndex } from "#app/battle"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { CommonAnim, CommonBattleAnim } from "#app/data/battle-anims"; import { PokemonPhase } from "./pokemon-phase"; @@ -21,7 +21,7 @@ export class CommonAnimPhase extends PokemonPhase { } start() { - const target = this.targetIndex !== undefined ? (this.player ? gScene.getEnemyField() : gScene.getPlayerField())[this.targetIndex] : this.getPokemon(); + const target = this.targetIndex !== undefined ? (this.player ? globalScene.getEnemyField() : globalScene.getPlayerField())[this.targetIndex] : this.getPokemon(); new CommonBattleAnim(this.anim, this.getPokemon(), target).play(false, () => { this.end(); }); diff --git a/src/phases/damage-phase.ts b/src/phases/damage-phase.ts index 9411d613f35..2f6b0efa64b 100644 --- a/src/phases/damage-phase.ts +++ b/src/phases/damage-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { BattleSpec } from "#app/enums/battle-spec"; import { DamageResult, HitResult } from "#app/field/pokemon"; @@ -22,11 +22,11 @@ export class DamagePhase extends PokemonPhase { super.start(); if (this.damageResult === HitResult.ONE_HIT_KO) { - if (gScene.moveAnimations) { - gScene.toggleInvert(true); + if (globalScene.moveAnimations) { + globalScene.toggleInvert(true); } - gScene.time.delayedCall(Utils.fixedInt(1000), () => { - gScene.toggleInvert(false); + globalScene.time.delayedCall(Utils.fixedInt(1000), () => { + globalScene.toggleInvert(false); this.applyDamage(); }); return; @@ -42,23 +42,23 @@ export class DamagePhase extends PokemonPhase { applyDamage() { switch (this.damageResult) { case HitResult.EFFECTIVE: - gScene.playSound("se/hit"); + globalScene.playSound("se/hit"); break; case HitResult.SUPER_EFFECTIVE: case HitResult.ONE_HIT_KO: - gScene.playSound("se/hit_strong"); + globalScene.playSound("se/hit_strong"); break; case HitResult.NOT_VERY_EFFECTIVE: - gScene.playSound("se/hit_weak"); + globalScene.playSound("se/hit_weak"); break; } if (this.amount) { - gScene.damageNumberHandler.add(this.getPokemon(), this.amount, this.damageResult, this.critical); + globalScene.damageNumberHandler.add(this.getPokemon(), this.amount, this.damageResult, this.critical); } if (this.damageResult !== HitResult.OTHER && this.amount > 0) { - const flashTimer = gScene.time.addEvent({ + const flashTimer = globalScene.time.addEvent({ delay: 100, repeat: 5, startAt: 200, @@ -75,8 +75,8 @@ export class DamagePhase extends PokemonPhase { } override end() { - if (gScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { - gScene.initFinalBossPhaseTwo(this.getPokemon()); + if (globalScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { + globalScene.initFinalBossPhaseTwo(this.getPokemon()); } else { super.end(); } diff --git a/src/phases/egg-hatch-phase.ts b/src/phases/egg-hatch-phase.ts index f09f053d0c2..54cf0e66644 100644 --- a/src/phases/egg-hatch-phase.ts +++ b/src/phases/egg-hatch-phase.ts @@ -1,4 +1,4 @@ -import { AnySound, gScene } from "#app/battle-scene"; +import { AnySound, globalScene } from "#app/battle-scene"; import { Egg } from "#app/data/egg"; import { EggCountChangedEvent } from "#app/events/egg"; import { PlayerPokemon } from "#app/field/pokemon"; @@ -76,37 +76,37 @@ export class EggHatchPhase extends Phase { start() { super.start(); - gScene.ui.setModeForceTransition(Mode.EGG_HATCH_SCENE).then(() => { + globalScene.ui.setModeForceTransition(Mode.EGG_HATCH_SCENE).then(() => { if (!this.egg) { return this.end(); } - const eggIndex = gScene.gameData.eggs.findIndex(e => e.id === this.egg.id); + const eggIndex = globalScene.gameData.eggs.findIndex(e => e.id === this.egg.id); if (eggIndex === -1) { return this.end(); } - gScene.gameData.eggs.splice(eggIndex, 1); + globalScene.gameData.eggs.splice(eggIndex, 1); - gScene.fadeOutBgm(undefined, false); + globalScene.fadeOutBgm(undefined, false); - this.eggHatchHandler = gScene.ui.getHandler() as EggHatchSceneHandler; + this.eggHatchHandler = globalScene.ui.getHandler() as EggHatchSceneHandler; this.eggHatchContainer = this.eggHatchHandler.eggHatchContainer; - this.eggHatchBg = gScene.add.image(0, 0, "default_bg"); + this.eggHatchBg = globalScene.add.image(0, 0, "default_bg"); this.eggHatchBg.setOrigin(0, 0); this.eggHatchContainer.add(this.eggHatchBg); - this.eggContainer = gScene.add.container(this.eggHatchBg.displayWidth / 2, this.eggHatchBg.displayHeight / 2); + this.eggContainer = globalScene.add.container(this.eggHatchBg.displayWidth / 2, this.eggHatchBg.displayHeight / 2); - this.eggSprite = gScene.add.sprite(0, 0, "egg", `egg_${this.egg.getKey()}`); - this.eggCrackSprite = gScene.add.sprite(0, 0, "egg_crack", "0"); + this.eggSprite = globalScene.add.sprite(0, 0, "egg", `egg_${this.egg.getKey()}`); + this.eggCrackSprite = globalScene.add.sprite(0, 0, "egg_crack", "0"); this.eggCrackSprite.setVisible(false); - this.eggLightraysOverlay = gScene.add.sprite((-this.eggHatchBg.displayWidth / 2) + 4, -this.eggHatchBg.displayHeight / 2, "egg_lightrays", "3"); + this.eggLightraysOverlay = globalScene.add.sprite((-this.eggHatchBg.displayWidth / 2) + 4, -this.eggHatchBg.displayHeight / 2, "egg_lightrays", "3"); this.eggLightraysOverlay.setOrigin(0, 0); this.eggLightraysOverlay.setVisible(false); @@ -119,22 +119,22 @@ export class EggHatchPhase extends Phase { this.eggHatchContainer.add(this.eggCounterContainer); const getPokemonSprite = () => { - 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 }); + const ret = globalScene.add.sprite(this.eggHatchBg.displayWidth / 2, this.eggHatchBg.displayHeight / 2, "pkmn__sub"); + ret.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); return ret; }; this.eggHatchContainer.add((this.pokemonSprite = getPokemonSprite())); - this.pokemonShinySparkle = gScene.add.sprite(this.pokemonSprite.x, this.pokemonSprite.y, "shiny"); + this.pokemonShinySparkle = globalScene.add.sprite(this.pokemonSprite.x, this.pokemonSprite.y, "shiny"); this.pokemonShinySparkle.setVisible(false); this.eggHatchContainer.add(this.pokemonShinySparkle); - this.eggHatchOverlay = gScene.add.rectangle(0, -gScene.game.canvas.height / 6, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0xFFFFFF); + this.eggHatchOverlay = globalScene.add.rectangle(0, -globalScene.game.canvas.height / 6, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6, 0xFFFFFF); this.eggHatchOverlay.setOrigin(0, 0); this.eggHatchOverlay.setAlpha(0); - gScene.fieldUI.add(this.eggHatchOverlay); + globalScene.fieldUI.add(this.eggHatchOverlay); this.infoContainer = new PokemonInfoContainer(); this.infoContainer.setup(); @@ -154,13 +154,13 @@ export class EggHatchPhase extends Phase { pokemon.loadAssets().then(() => { this.canSkip = true; - gScene.time.delayedCall(1000, () => { + globalScene.time.delayedCall(1000, () => { if (!this.hatched) { - this.evolutionBgm = gScene.playSoundWithoutBgm("evolution"); + this.evolutionBgm = globalScene.playSoundWithoutBgm("evolution"); } }); - gScene.time.delayedCall(2000, () => { + globalScene.time.delayedCall(2000, () => { if (this.hatched) { return; } @@ -170,25 +170,25 @@ export class EggHatchPhase extends Phase { if (this.hatched) { return; } - gScene.time.delayedCall(1000, () => { + globalScene.time.delayedCall(1000, () => { if (this.hatched) { return; } this.doSpray(2, this.eggSprite.displayHeight / -4); this.eggCrackSprite.setFrame("1"); - gScene.time.delayedCall(125, () => this.eggCrackSprite.setFrame("2")); + globalScene.time.delayedCall(125, () => this.eggCrackSprite.setFrame("2")); this.doEggShake(4).then(() => { if (this.hatched) { return; } - gScene.time.delayedCall(1000, () => { + globalScene.time.delayedCall(1000, () => { if (this.hatched) { return; } - gScene.playSound("se/egg_crack"); + globalScene.playSound("se/egg_crack"); this.doSpray(4); this.eggCrackSprite.setFrame("3"); - gScene.time.delayedCall(125, () => this.eggCrackSprite.setFrame("4")); + globalScene.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 (gScene.findPhase((p) => p instanceof EggHatchPhase)) { + if (globalScene.findPhase((p) => p instanceof EggHatchPhase)) { this.eggHatchHandler.clear(); } else { - gScene.time.delayedCall(250, () => gScene.setModifiersVisible(true)); + globalScene.time.delayedCall(250, () => globalScene.setModifiersVisible(true)); } super.end(); } @@ -227,14 +227,14 @@ export class EggHatchPhase extends Phase { if (count === undefined) { count = 0; } - gScene.playSound("se/pb_move"); - gScene.tweens.add({ + globalScene.playSound("se/pb_move"); + globalScene.tweens.add({ targets: this.eggContainer, x: `-=${intensity / (count ? 1 : 2)}`, ease: "Sine.easeInOut", duration: 125, onComplete: () => { - gScene.tweens.add({ + globalScene.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()); } - gScene.tweens.add({ + globalScene.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(gScene, this.evolutionBgm, Utils.fixedInt(100)); + SoundFade.fadeOut(globalScene, this.evolutionBgm, Utils.fixedInt(100)); } for (let e = 0; e < 5; e++) { - gScene.time.delayedCall(Utils.fixedInt(375 * e), () => gScene.playSound("se/egg_hatch", { volume: 1 - (e * 0.2) })); + globalScene.time.delayedCall(Utils.fixedInt(375 * e), () => globalScene.playSound("se/egg_hatch", { volume: 1 - (e * 0.2) })); } this.eggLightraysOverlay.setVisible(true); this.eggLightraysOverlay.play("egg_lightrays"); - gScene.tweens.add({ + globalScene.tweens.add({ duration: Utils.fixedInt(125), targets: this.eggHatchOverlay, alpha: 1, @@ -302,7 +302,7 @@ export class EggHatchPhase extends Phase { this.canSkip = true; } }); - gScene.time.delayedCall(Utils.fixedInt(1500), () => { + globalScene.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) { - gScene.validateAchv(achvs.HATCH_SUB_LEGENDARY); + globalScene.validateAchv(achvs.HATCH_SUB_LEGENDARY); } if (this.pokemon.species.legendary) { - gScene.validateAchv(achvs.HATCH_LEGENDARY); + globalScene.validateAchv(achvs.HATCH_LEGENDARY); } if (this.pokemon.species.mythical) { - gScene.validateAchv(achvs.HATCH_MYTHICAL); + globalScene.validateAchv(achvs.HATCH_MYTHICAL); } if (isShiny) { - gScene.validateAchv(achvs.HATCH_SHINY); + globalScene.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); - gScene.time.delayedCall(Utils.fixedInt(250), () => { + globalScene.time.delayedCall(Utils.fixedInt(250), () => { this.eggsToHatchCount--; this.eggHatchHandler.eventTarget.dispatchEvent(new EggCountChangedEvent(this.eggsToHatchCount)); this.pokemon.cry(); if (isShiny) { - gScene.time.delayedCall(Utils.fixedInt(500), () => { + globalScene.time.delayedCall(Utils.fixedInt(500), () => { this.pokemonShinySparkle.play(`sparkle${this.pokemon.variant ? `_${this.pokemon.variant + 1}` : ""}`); - gScene.playSound("se/sparkle"); + globalScene.playSound("se/sparkle"); }); } - gScene.time.delayedCall(Utils.fixedInt(!this.skipped ? !isShiny ? 1250 : 1750 : !isShiny ? 250 : 750), () => { + globalScene.time.delayedCall(Utils.fixedInt(!this.skipped ? !isShiny ? 1250 : 1750 : !isShiny ? 250 : 750), () => { this.infoContainer.show(this.pokemon, false, this.skipped ? 2 : 1); - gScene.playSoundWithoutBgm("evolution_fanfare"); + globalScene.playSoundWithoutBgm("evolution_fanfare"); - 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) => { + globalScene.ui.showText(i18next.t("egg:hatchFromTheEgg", { pokemonName: getPokemonNameWithAffix(this.pokemon) }), null, () => { + globalScene.gameData.updateSpeciesDexIvs(this.pokemon.species.speciesId, this.pokemon.ivs); + globalScene.gameData.setPokemonCaught(this.pokemon, true, true).then(() => { + globalScene.gameData.setEggMoveUnlocked(this.pokemon.species, this.eggMoveIndex).then((value) => { this.eggHatchData.setEggMoveUnlocked(value); - gScene.ui.showText("", 0); + globalScene.ui.showText("", 0); this.end(); }); }); }, null, true, 3000); }); }); - gScene.tweens.add({ + globalScene.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) { - gScene.tweens.addCounter({ + globalScene.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 = gScene.add.image(initialX, initialY, "egg_shard", `${shardKey}_${Math.floor(trigIndex / 2)}`); + const particle = globalScene.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 = gScene.tweens.addCounter({ + const particleTimer = globalScene.tweens.addCounter({ repeat: -1, duration: Utils.getFrameMs(1), onRepeat: () => { diff --git a/src/phases/egg-lapse-phase.ts b/src/phases/egg-lapse-phase.ts index 18b257393a2..12ca19799af 100644 --- a/src/phases/egg-lapse-phase.ts +++ b/src/phases/egg-lapse-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Egg, EGG_SEED } from "#app/data/egg"; import { Phase } from "#app/phase"; import i18next from "i18next"; @@ -24,18 +24,18 @@ export class EggLapsePhase extends Phase { start() { super.start(); - const eggsToHatch: Egg[] = gScene.gameData.eggs.filter((egg: Egg) => { + const eggsToHatch: Egg[] = globalScene.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 && gScene.eggSkipPreference === 1) { - gScene.ui.showText(i18next.t("battle:eggHatching"), 0, () => { + if (eggsToHatchCount >= this.minEggsToSkip && globalScene.eggSkipPreference === 1) { + globalScene.ui.showText(i18next.t("battle:eggHatching"), 0, () => { // show prompt for skip, blocking inputs for 1 second - gScene.ui.showText(i18next.t("battle:eggSkipPrompt"), 0); - gScene.ui.setModeWithoutClear(Mode.CONFIRM, () => { + globalScene.ui.showText(i18next.t("battle:eggSkipPrompt"), 0); + globalScene.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 && gScene.eggSkipPreference === 2) { - gScene.queueMessage(i18next.t("battle:eggHatching")); + } else if (eggsToHatchCount >= this.minEggsToSkip && globalScene.eggSkipPreference === 2) { + globalScene.queueMessage(i18next.t("battle:eggHatching")); this.hatchEggsSkipped(eggsToHatch); this.showSummary(); } else { // regular hatches, no summary - gScene.queueMessage(i18next.t("battle:eggHatching")); + globalScene.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) { - gScene.unshiftPhase(new EggHatchPhase(this, egg, eggsToHatchCount)); + globalScene.unshiftPhase(new EggHatchPhase(this, egg, eggsToHatchCount)); eggsToHatchCount--; } } @@ -83,7 +83,7 @@ export class EggLapsePhase extends Phase { } showSummary() { - gScene.unshiftPhase(new EggSummaryPhase(this.eggHatchData)); + globalScene.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 = gScene.gameData.eggs.findIndex(e => e.id === egg.id); + const eggIndex = globalScene.gameData.eggs.findIndex(e => e.id === egg.id); if (eggIndex === -1) { return this.end(); } - gScene.gameData.eggs.splice(eggIndex, 1); + globalScene.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) { - gScene.validateAchv(achvs.HATCH_SUB_LEGENDARY); + globalScene.validateAchv(achvs.HATCH_SUB_LEGENDARY); } if (pokemon.species.legendary) { - gScene.validateAchv(achvs.HATCH_LEGENDARY); + globalScene.validateAchv(achvs.HATCH_LEGENDARY); } if (pokemon.species.mythical) { - gScene.validateAchv(achvs.HATCH_MYTHICAL); + globalScene.validateAchv(achvs.HATCH_MYTHICAL); } if (pokemon.isShiny()) { - gScene.validateAchv(achvs.HATCH_SHINY); + globalScene.validateAchv(achvs.HATCH_SHINY); } } @@ -128,7 +128,7 @@ export class EggLapsePhase extends Phase { generatePokemon(egg: Egg): EggHatchData { let ret: PlayerPokemon; let newHatchData: EggHatchData; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { ret = egg.generatePlayerPokemon(); newHatchData = new EggHatchData(ret, egg.eggMoveIndex); newHatchData.setDex(); diff --git a/src/phases/egg-summary-phase.ts b/src/phases/egg-summary-phase.ts index 9b8ef3d3243..b3d3041c2ca 100644 --- a/src/phases/egg-summary-phase.ts +++ b/src/phases/egg-summary-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; import { Mode } from "#app/ui/ui"; import { EggHatchData } from "#app/data/egg-hatch-data"; @@ -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) { - gScene.ui.setModeForceTransition(Mode.EGG_HATCH_SUMMARY, this.eggHatchData).then(() => { - gScene.fadeOutBgm(undefined, false); + globalScene.ui.setModeForceTransition(Mode.EGG_HATCH_SUMMARY, this.eggHatchData).then(() => { + globalScene.fadeOutBgm(undefined, false); }); } else { @@ -40,8 +40,8 @@ export class EggSummaryPhase extends Phase { } end() { - gScene.time.delayedCall(250, () => gScene.setModifiersVisible(true)); - gScene.ui.setModeForceTransition(Mode.MESSAGE).then(() => { + globalScene.time.delayedCall(250, () => globalScene.setModifiersVisible(true)); + globalScene.ui.setModeForceTransition(Mode.MESSAGE).then(() => { super.end(); }); } diff --git a/src/phases/encounter-phase.ts b/src/phases/encounter-phase.ts index 814df0cb80b..f2cff8df838 100644 --- a/src/phases/encounter-phase.ts +++ b/src/phases/encounter-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex, BattleType } from "#app/battle"; import { applyAbAttrs, SyncEncounterNatureAbAttr } from "#app/data/ability"; import { getCharVariantFromDialogue } from "#app/data/dialogue"; @@ -49,26 +49,26 @@ export class EncounterPhase extends BattlePhase { start() { super.start(); - gScene.updateGameInfo(); + globalScene.updateGameInfo(); - gScene.initSession(); + globalScene.initSession(); - gScene.eventTarget.dispatchEvent(new EncounterPhaseEvent()); + globalScene.eventTarget.dispatchEvent(new EncounterPhaseEvent()); // Failsafe if players somehow skip floor 200 in classic mode - if (gScene.gameMode.isClassic && gScene.currentBattle.waveIndex > 200) { - gScene.unshiftPhase(new GameOverPhase()); + if (globalScene.gameMode.isClassic && globalScene.currentBattle.waveIndex > 200) { + globalScene.unshiftPhase(new GameOverPhase()); } const loadEnemyAssets: Promise[] = []; - const battle = gScene.currentBattle; + const battle = globalScene.currentBattle; // Generate and Init Mystery Encounter if (battle.isBattleMysteryEncounter() && !battle.mysteryEncounter) { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const currentSessionEncounterType = battle.mysteryEncounterType; - battle.mysteryEncounter = gScene.getMysteryEncounter(currentSessionEncounterType); + battle.mysteryEncounter = globalScene.getMysteryEncounter(currentSessionEncounterType); }, battle.waveIndex * 16); } const mysteryEncounter = battle.mysteryEncounter; @@ -76,7 +76,7 @@ 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 - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { if (mysteryEncounter.onInit) { mysteryEncounter.onInit(); } @@ -90,7 +90,7 @@ export class EncounterPhase extends BattlePhase { // Add intro visuals for mystery encounter mysteryEncounter.initIntroVisuals(); - gScene.field.add(mysteryEncounter.introVisuals!); + globalScene.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 = gScene.randomSpecies(battle.waveIndex, level, true); + let enemySpecies = globalScene.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 (gScene.findModifier(m => m instanceof BoostBugSpawnModifier) - && !gScene.gameMode.isBoss(battle.waveIndex) - && gScene.arena.biomeType !== Biome.END + if (globalScene.findModifier(m => m instanceof BoostBugSpawnModifier) + && !globalScene.gameMode.isBoss(battle.waveIndex) + && globalScene.arena.biomeType !== Biome.END && randSeedInt(10) === 0) { enemySpecies = getGoldenBugNetSpecies(level); } - 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] = globalScene.addEnemyPokemon(enemySpecies, level, TrainerSlot.NONE, !!globalScene.getEncounterBossSegments(battle.waveIndex, level, enemySpecies)); + if (globalScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { battle.enemyParty[e].ivs = new Array(6).fill(31); } - gScene.getParty().slice(0, !battle.double ? 1 : 2).reverse().forEach(playerPokemon => { + globalScene.getParty().slice(0, !battle.double ? 1 : 2).reverse().forEach(playerPokemon => { applyAbAttrs(SyncEncounterNatureAbAttr, playerPokemon, null, false, battle.enemyParty[e]); }); } } - const enemyPokemon = gScene.getEnemyParty()[e]; + const enemyPokemon = globalScene.getEnemyParty()[e]; if (e < (battle.double ? 2 : 1)) { enemyPokemon.setX(-66 + enemyPokemon.getFieldPositionOffset()[0]); enemyPokemon.resetSummonData(); } if (!this.loaded) { - gScene.gameData.setPokemonSeen(enemyPokemon, true, battle.battleType === BattleType.TRAINER || battle?.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE); + globalScene.gameData.setPokemonSeen(enemyPokemon, true, battle.battleType === BattleType.TRAINER || battle?.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE); } if (enemyPokemon.species.speciesId === Species.ETERNATUS) { - if (gScene.gameMode.isClassic && (battle.battleSpec === BattleSpec.FINAL_BOSS || gScene.gameMode.isWaveFinal(battle.waveIndex))) { + if (globalScene.gameMode.isClassic && (battle.battleSpec === BattleSpec.FINAL_BOSS || globalScene.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 = gScene.findModifier(m => m instanceof TurnHeldItemTransferModifier && m.pokemonId === enemyPokemon.id, false) as TurnHeldItemTransferModifier; - gScene.removeModifier(bossMBH!); + const bossMBH = globalScene.findModifier(m => m instanceof TurnHeldItemTransferModifier && m.pokemonId === enemyPokemon.id, false) as TurnHeldItemTransferModifier; + globalScene.removeModifier(bossMBH!); bossMBH?.setTransferrableFalse(); - gScene.addEnemyModifier(bossMBH!); + globalScene.addEnemyModifier(bossMBH!); } } @@ -156,8 +156,8 @@ export class EncounterPhase extends BattlePhase { return true; }); - if (gScene.getParty().filter(p => p.isShiny()).length === 6) { - gScene.validateAchv(achvs.SHINY_PARTY); + if (globalScene.getParty().filter(p => p.isShiny()).length === 6) { + globalScene.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(resolve => { - 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(); + globalScene.loadSe("GEN8- Exclaim", "battle_anims", "GEN8- Exclaim.wav"); + globalScene.loadImage("encounter_exclaim", "mystery-encounters"); + globalScene.load.once(Phaser.Loader.Events.COMPLETE, () => resolve()); + if (!globalScene.load.isLoading()) { + globalScene.load.start(); } })); } else { @@ -199,16 +199,16 @@ export class EncounterPhase extends BattlePhase { } if (e < (battle.double ? 2 : 1)) { if (battle.battleType === BattleType.WILD) { - gScene.field.add(enemyPokemon); + globalScene.field.add(enemyPokemon); battle.seenEnemyPartyMemberIds.add(enemyPokemon.id); - const playerPokemon = gScene.getPlayerPokemon(); + const playerPokemon = globalScene.getPlayerPokemon(); if (playerPokemon?.visible) { - gScene.field.moveBelow(enemyPokemon as Pokemon, playerPokemon); + globalScene.field.moveBelow(enemyPokemon as Pokemon, playerPokemon); } enemyPokemon.tint(0, 0.5); } else if (battle.battleType === BattleType.TRAINER) { enemyPokemon.setVisible(false); - gScene.currentBattle.trainer?.tint(0, 0.5); + globalScene.currentBattle.trainer?.tint(0, 0.5); } if (battle.double) { enemyPokemon.setFieldPosition(e ? FieldPosition.RIGHT : FieldPosition.LEFT); @@ -218,56 +218,50 @@ export class EncounterPhase extends BattlePhase { }); if (!this.loaded && battle.battleType !== BattleType.MYSTERY_ENCOUNTER) { - regenerateModifierPoolThresholds(gScene.getEnemyField(), battle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD); - gScene.generateEnemyModifiers(); + regenerateModifierPoolThresholds(globalScene.getEnemyField(), battle.battleType === BattleType.TRAINER ? ModifierPoolType.TRAINER : ModifierPoolType.WILD); + globalScene.generateEnemyModifiers(); } - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { if (!this.loaded) { this.trySetWeatherIfNewBiome(); // Set weather before session gets saved - gScene.gameData.saveAll(true, battle.waveIndex % 10 === 1 || (gScene.lastSavePlayTime ?? 0) >= 300).then(success => { - gScene.disableMenu = false; + globalScene.gameData.saveAll(true, battle.waveIndex % 10 === 1 || (globalScene.lastSavePlayTime ?? 0) >= 300).then(success => { + globalScene.disableMenu = false; if (!success) { - return gScene.reset(true); + return globalScene.reset(true); } this.doEncounter(); - gScene.resetSeed(); + globalScene.resetSeed(); }); } else { this.doEncounter(); - gScene.resetSeed(); + globalScene.resetSeed(); } }); }); } doEncounter() { - gScene.playBgm(undefined, true); - gScene.updateModifiers(false); - gScene.setFieldScale(1); + globalScene.playBgm(undefined, true); + globalScene.updateModifiers(false); + globalScene.setFieldScale(1); - /*if (startingWave > 10) { - for (let m = 0; m < Math.min(Math.floor(startingWave / 10), 99); m++) - gScene.addModifier(getPlayerModifierTypeOptionsForWave((m + 1) * 10, 1, gScene.getParty())[0].type.newModifier(), true); - gScene.updateModifiers(true); - }*/ - - const { battleType, waveIndex } = gScene.currentBattle; - if (gScene.isMysteryEncounterValidForWave(battleType, waveIndex) && !gScene.currentBattle.isBattleMysteryEncounter()) { + const { battleType, waveIndex } = globalScene.currentBattle; + if (globalScene.isMysteryEncounterValidForWave(battleType, waveIndex) && !globalScene.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 - gScene.mysteryEncounterSaveData.encounterSpawnChance += WEIGHT_INCREMENT_ON_SPAWN_MISS; + globalScene.mysteryEncounterSaveData.encounterSpawnChance += WEIGHT_INCREMENT_ON_SPAWN_MISS; } - for (const pokemon of gScene.getParty()) { + for (const pokemon of globalScene.getParty()) { if (pokemon) { pokemon.resetBattleData(); } } - const enemyField = gScene.getEnemyField(); - gScene.tweens.add({ - targets: [ gScene.arenaEnemy, gScene.currentBattle.trainer, enemyField, gScene.arenaPlayer, gScene.trainer ].flat(), + const enemyField = globalScene.getEnemyField(); + globalScene.tweens.add({ + targets: [ globalScene.arenaEnemy, globalScene.currentBattle.trainer, enemyField, globalScene.arenaPlayer, globalScene.trainer ].flat(), x: (_target, _key, value, fieldIndex: integer) => fieldIndex < 2 + (enemyField.length) ? value + 300 : value - 300, duration: 2000, onComplete: () => { @@ -277,13 +271,13 @@ export class EncounterPhase extends BattlePhase { } }); - const encounterIntroVisuals = gScene.currentBattle?.mysteryEncounter?.introVisuals; + const encounterIntroVisuals = globalScene.currentBattle?.mysteryEncounter?.introVisuals; if (encounterIntroVisuals) { const enterFromRight = encounterIntroVisuals.enterFromRight; if (enterFromRight) { encounterIntroVisuals.x += 500; } - gScene.tweens.add({ + globalScene.tweens.add({ targets: encounterIntroVisuals, x: enterFromRight ? "-=200" : "+=300", duration: 2000 @@ -292,18 +286,18 @@ export class EncounterPhase extends BattlePhase { } getEncounterMessage(): string { - const enemyField = gScene.getEnemyField(); + const enemyField = globalScene.getEnemyField(); - if (gScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { + if (globalScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { return i18next.t("battle:bossAppeared", { bossName: getPokemonNameWithAffix(enemyField[0]) }); } - if (gScene.currentBattle.battleType === BattleType.TRAINER) { - if (gScene.currentBattle.double) { - return i18next.t("battle:trainerAppearedDouble", { trainerName: gScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }); + if (globalScene.currentBattle.battleType === BattleType.TRAINER) { + if (globalScene.currentBattle.double) { + return i18next.t("battle:trainerAppearedDouble", { trainerName: globalScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }); } else { - return i18next.t("battle:trainerAppeared", { trainerName: gScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }); + return i18next.t("battle:trainerAppeared", { trainerName: globalScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }); } } @@ -313,70 +307,70 @@ export class EncounterPhase extends BattlePhase { } doEncounterCommon(showEncounterMessage: boolean = true) { - const enemyField = gScene.getEnemyField(); + const enemyField = globalScene.getEnemyField(); - if (gScene.currentBattle.battleType === BattleType.WILD) { + if (globalScene.currentBattle.battleType === BattleType.WILD) { enemyField.forEach(enemyPokemon => { enemyPokemon.untint(100, "Sine.easeOut"); enemyPokemon.cry(); enemyPokemon.showInfo(); if (enemyPokemon.isShiny()) { - gScene.validateAchv(achvs.SEE_SHINY); + globalScene.validateAchv(achvs.SEE_SHINY); } }); - gScene.updateFieldScale(); + globalScene.updateFieldScale(); if (showEncounterMessage) { - gScene.ui.showText(this.getEncounterMessage(), null, () => this.end(), 1500); + globalScene.ui.showText(this.getEncounterMessage(), null, () => this.end(), 1500); } else { this.end(); } - } else if (gScene.currentBattle.battleType === BattleType.TRAINER) { - const trainer = gScene.currentBattle.trainer; + } else if (globalScene.currentBattle.battleType === BattleType.TRAINER) { + const trainer = globalScene.currentBattle.trainer; trainer?.untint(100, "Sine.easeOut"); trainer?.playAnim(); const doSummon = () => { - gScene.currentBattle.started = true; - gScene.playBgm(undefined); - gScene.pbTray.showPbTray(gScene.getParty()); - gScene.pbTrayEnemy.showPbTray(gScene.getEnemyParty()); + globalScene.currentBattle.started = true; + globalScene.playBgm(undefined); + globalScene.pbTray.showPbTray(globalScene.getParty()); + globalScene.pbTrayEnemy.showPbTray(globalScene.getEnemyParty()); const doTrainerSummon = () => { this.hideEnemyTrainer(); - 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)); + const availablePartyMembers = globalScene.getEnemyParty().filter(p => !p.isFainted()).length; + globalScene.unshiftPhase(new SummonPhase(0, false)); + if (globalScene.currentBattle.double && availablePartyMembers > 1) { + globalScene.unshiftPhase(new SummonPhase(1, false)); } this.end(); }; if (showEncounterMessage) { - gScene.ui.showText(this.getEncounterMessage(), null, doTrainerSummon, 1500, true); + globalScene.ui.showText(this.getEncounterMessage(), null, doTrainerSummon, 1500, true); } else { doTrainerSummon(); } }; - const encounterMessages = gScene.currentBattle.trainer?.getEncounterMessages(); + const encounterMessages = globalScene.currentBattle.trainer?.getEncounterMessages(); if (!encounterMessages?.length) { doSummon(); } else { let message: string; - gScene.executeWithSeedOffset(() => message = Utils.randSeedItem(encounterMessages), gScene.currentBattle.waveIndex); + globalScene.executeWithSeedOffset(() => message = Utils.randSeedItem(encounterMessages), globalScene.currentBattle.waveIndex); message = message!; // tell TS compiler it's defined now const showDialogueAndSummon = () => { - gScene.ui.showDialogue(message, trainer?.getName(TrainerSlot.NONE, true), null, () => { - gScene.charSprite.hide().then(() => gScene.hideFieldOverlay(250).then(() => doSummon())); + globalScene.ui.showDialogue(message, trainer?.getName(TrainerSlot.NONE, true), null, () => { + globalScene.charSprite.hide().then(() => globalScene.hideFieldOverlay(250).then(() => doSummon())); }); }; - 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? + if (globalScene.currentBattle.trainer?.config.hasCharSprite && !globalScene.ui.shouldSkipDialogue(message)) { + globalScene.showFieldOverlay(500).then(() => globalScene.charSprite.showCharacter(trainer?.getKey()!, getCharVariantFromDialogue(encounterMessages[0])).then(() => showDialogueAndSummon())); // TODO: is this bang correct? } else { showDialogueAndSummon(); } } - } else if (gScene.currentBattle.isBattleMysteryEncounter() && gScene.currentBattle.mysteryEncounter) { - const encounter = gScene.currentBattle.mysteryEncounter; + } else if (globalScene.currentBattle.isBattleMysteryEncounter() && globalScene.currentBattle.mysteryEncounter) { + const encounter = globalScene.currentBattle.mysteryEncounter; const introVisuals = encounter.introVisuals; introVisuals?.playAnim(); @@ -386,10 +380,10 @@ export class EncounterPhase extends BattlePhase { const doEncounter = () => { const doShowEncounterOptions = () => { - gScene.ui.clearText(); - gScene.ui.getMessageHandler().hideNameText(); + globalScene.ui.clearText(); + globalScene.ui.getMessageHandler().hideNameText(); - gScene.unshiftPhase(new MysteryEncounterPhase()); + globalScene.unshiftPhase(new MysteryEncounterPhase()); this.end(); }; @@ -407,9 +401,9 @@ export class EncounterPhase extends BattlePhase { const text = getEncounterText(dialogue.text)!; i++; if (title) { - gScene.ui.showDialogue(text, title, null, nextAction, 0, i === 1 ? FIRST_DIALOGUE_PROMPT_DELAY : 0); + globalScene.ui.showDialogue(text, title, null, nextAction, 0, i === 1 ? FIRST_DIALOGUE_PROMPT_DELAY : 0); } else { - gScene.ui.showText(text, null, nextAction, i === 1 ? FIRST_DIALOGUE_PROMPT_DELAY : 0, true); + globalScene.ui.showText(text, null, nextAction, i === 1 ? FIRST_DIALOGUE_PROMPT_DELAY : 0, true); } }; @@ -428,71 +422,71 @@ export class EncounterPhase extends BattlePhase { doEncounter(); } else { doTrainerExclamation(); - gScene.ui.showDialogue(encounterMessage, "???", null, () => { - gScene.charSprite.hide().then(() => gScene.hideFieldOverlay(250).then(() => doEncounter())); + globalScene.ui.showDialogue(encounterMessage, "???", null, () => { + globalScene.charSprite.hide().then(() => globalScene.hideFieldOverlay(250).then(() => doEncounter())); }); } } } end() { - const enemyField = gScene.getEnemyField(); + const enemyField = globalScene.getEnemyField(); enemyField.forEach((enemyPokemon, e) => { if (enemyPokemon.isShiny()) { - gScene.unshiftPhase(new ShinySparklePhase(BattlerIndex.ENEMY + e)); + globalScene.unshiftPhase(new ShinySparklePhase(BattlerIndex.ENEMY + e)); } }); - if (![ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(gScene.currentBattle.battleType)) { - enemyField.map(p => gScene.pushConditionalPhase(new PostSummonPhase(p.getBattlerIndex()), () => { + if (![ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(globalScene.currentBattle.battleType)) { + enemyField.map(p => globalScene.pushConditionalPhase(new PostSummonPhase(p.getBattlerIndex()), () => { // if there is not a player party, we can't continue - if (!gScene.getParty()?.length) { + if (!globalScene.getParty()?.length) { return false; } // how many player pokemon are on the field ? - const pokemonsOnFieldCount = gScene.getParty().filter(p => p.isOnField()).length; + const pokemonsOnFieldCount = globalScene.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(gScene.getParty().filter((p) => !p.isFainted()).length, 2); + const requiredPokemonsOnField = Math.min(globalScene.getParty().filter((p) => !p.isFainted()).length, 2); // if it's a double, there should be 2, otherwise 1 - if (gScene.currentBattle.double) { + if (globalScene.currentBattle.double) { return pokemonsOnFieldCount === requiredPokemonsOnField; } return pokemonsOnFieldCount === 1; })); - const ivScannerModifier = gScene.findModifier(m => m instanceof IvScannerModifier); + const ivScannerModifier = globalScene.findModifier(m => m instanceof IvScannerModifier); if (ivScannerModifier) { - enemyField.map(p => gScene.pushPhase(new ScanIvsPhase(p.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6)))); + enemyField.map(p => globalScene.pushPhase(new ScanIvsPhase(p.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6)))); } } if (!this.loaded) { - const availablePartyMembers = gScene.getParty().filter(p => p.isAllowedInBattle()); + const availablePartyMembers = globalScene.getParty().filter(p => p.isAllowedInBattle()); if (!availablePartyMembers[0].isOnField()) { - gScene.pushPhase(new SummonPhase(0)); + globalScene.pushPhase(new SummonPhase(0)); } - if (gScene.currentBattle.double) { + if (globalScene.currentBattle.double) { if (availablePartyMembers.length > 1) { - gScene.pushPhase(new ToggleDoublePositionPhase(true)); + globalScene.pushPhase(new ToggleDoublePositionPhase(true)); if (!availablePartyMembers[1].isOnField()) { - gScene.pushPhase(new SummonPhase(1)); + globalScene.pushPhase(new SummonPhase(1)); } } } else { if (availablePartyMembers.length > 1 && availablePartyMembers[1].isOnField()) { - gScene.pushPhase(new ReturnPhase(1)); + globalScene.pushPhase(new ReturnPhase(1)); } - gScene.pushPhase(new ToggleDoublePositionPhase(false)); + globalScene.pushPhase(new ToggleDoublePositionPhase(false)); } - if (gScene.currentBattle.battleType !== BattleType.TRAINER && (gScene.currentBattle.waveIndex > 1 || !gScene.gameMode.isDaily)) { - const minPartySize = gScene.currentBattle.double ? 2 : 1; + if (globalScene.currentBattle.battleType !== BattleType.TRAINER && (globalScene.currentBattle.waveIndex > 1 || !globalScene.gameMode.isDaily)) { + const minPartySize = globalScene.currentBattle.double ? 2 : 1; if (availablePartyMembers.length > minPartySize) { - gScene.pushPhase(new CheckSwitchPhase(0, gScene.currentBattle.double)); - if (gScene.currentBattle.double) { - gScene.pushPhase(new CheckSwitchPhase(1, gScene.currentBattle.double)); + globalScene.pushPhase(new CheckSwitchPhase(0, globalScene.currentBattle.double)); + if (globalScene.currentBattle.double) { + globalScene.pushPhase(new CheckSwitchPhase(1, globalScene.currentBattle.double)); } } } @@ -501,27 +495,27 @@ export class EncounterPhase extends BattlePhase { } tryOverrideForBattleSpec(): boolean { - switch (gScene.currentBattle.battleSpec) { + switch (globalScene.currentBattle.battleSpec) { case BattleSpec.FINAL_BOSS: - const enemy = gScene.getEnemyPokemon(); - gScene.ui.showText(this.getEncounterMessage(), null, () => { + const enemy = globalScene.getEnemyPokemon(); + globalScene.ui.showText(this.getEncounterMessage(), null, () => { const localizationKey = "battleSpecDialogue:encounter"; - if (gScene.ui.shouldSkipDialogue(localizationKey)) { + if (globalScene.ui.shouldSkipDialogue(localizationKey)) { // Logging mirrors logging found in dialogue-ui-handler console.log(`Dialogue ${localizationKey} skipped`); this.doEncounterCommon(false); } else { - const count = 5643853 + gScene.gameData.gameStats.classicSessionsPlayed; + const count = 5643853 + globalScene.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 = gScene.gameData.gender ?? PlayerGender.UNSET; + const genderIndex = globalScene.gameData.gender ?? PlayerGender.UNSET; const genderStr = PlayerGender[genderIndex].toLowerCase(); const encounterDialogue = i18next.t(localizationKey, { context: genderStr, cycleCount: cycleCount }); - if (!gScene.gameData.getSeenDialogues()[localizationKey]) { - gScene.gameData.saveSeenDialogue(localizationKey); + if (!globalScene.gameData.getSeenDialogues()[localizationKey]) { + globalScene.gameData.saveSeenDialogue(localizationKey); } - gScene.ui.showDialogue(encounterDialogue, enemy?.species.name, null, () => { + globalScene.ui.showDialogue(encounterDialogue, enemy?.species.name, null, () => { this.doEncounterCommon(false); }); } @@ -541,7 +535,7 @@ export class EncounterPhase extends BattlePhase { */ trySetWeatherIfNewBiome(): void { if (!this.loaded) { - gScene.arena.trySetWeather(getRandomWeatherType(gScene.arena), false); + globalScene.arena.trySetWeather(getRandomWeatherType(globalScene.arena), false); } } } diff --git a/src/phases/end-card-phase.ts b/src/phases/end-card-phase.ts index f627adf0257..32b00ac3981 100644 --- a/src/phases/end-card-phase.ts +++ b/src/phases/end-card-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { PlayerGender } from "#app/enums/player-gender"; import { Phase } from "#app/phase"; import { addTextObject, TextStyle } from "#app/ui/text"; @@ -15,24 +15,24 @@ export class EndCardPhase extends Phase { start(): void { super.start(); - gScene.ui.getMessageHandler().bg.setVisible(false); - gScene.ui.getMessageHandler().nameBoxContainer.setVisible(false); + globalScene.ui.getMessageHandler().bg.setVisible(false); + globalScene.ui.getMessageHandler().nameBoxContainer.setVisible(false); - this.endCard = gScene.add.image(0, 0, `end_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}`); + this.endCard = globalScene.add.image(0, 0, `end_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}`); this.endCard.setOrigin(0); this.endCard.setScale(0.5); - gScene.field.add(this.endCard); + globalScene.field.add(this.endCard); - this.text = addTextObject(gScene.game.canvas.width / 12, (gScene.game.canvas.height / 6) - 16, i18next.t("battle:congratulations"), TextStyle.SUMMARY, { fontSize: "128px" }); + this.text = addTextObject(globalScene.game.canvas.width / 12, (globalScene.game.canvas.height / 6) - 16, i18next.t("battle:congratulations"), TextStyle.SUMMARY, { fontSize: "128px" }); this.text.setOrigin(0.5); - gScene.field.add(this.text); + globalScene.field.add(this.text); - gScene.ui.clearText(); + globalScene.ui.clearText(); - gScene.ui.fadeIn(1000).then(() => { + globalScene.ui.fadeIn(1000).then(() => { - gScene.ui.showText("", null, () => { - gScene.ui.getMessageHandler().bg.setVisible(true); + globalScene.ui.showText("", null, () => { + globalScene.ui.getMessageHandler().bg.setVisible(true); this.end(); }, null, true); }); diff --git a/src/phases/end-evolution-phase.ts b/src/phases/end-evolution-phase.ts index b7478b60679..3dd644e4793 100644 --- a/src/phases/end-evolution-phase.ts +++ b/src/phases/end-evolution-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; import { Mode } from "#app/ui/ui"; @@ -11,6 +11,6 @@ export class EndEvolutionPhase extends Phase { start() { super.start(); - gScene.ui.setModeForceTransition(Mode.MESSAGE).then(() => this.end()); + globalScene.ui.setModeForceTransition(Mode.MESSAGE).then(() => this.end()); } } diff --git a/src/phases/enemy-command-phase.ts b/src/phases/enemy-command-phase.ts index 3bc148caadd..bae9a2874bb 100644 --- a/src/phases/enemy-command-phase.ts +++ b/src/phases/enemy-command-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { Command } from "#app/ui/command-ui-handler"; import { FieldPhase } from "./field-phase"; @@ -20,7 +20,7 @@ export class EnemyCommandPhase extends FieldPhase { super(); this.fieldIndex = fieldIndex; - if (gScene.currentBattle.mysteryEncounter?.skipEnemyBattleTurns) { + if (globalScene.currentBattle.mysteryEncounter?.skipEnemyBattleTurns) { this.skipTurn = true; } } @@ -28,9 +28,9 @@ export class EnemyCommandPhase extends FieldPhase { start() { super.start(); - const enemyPokemon = gScene.getEnemyField()[this.fieldIndex]; + const enemyPokemon = globalScene.getEnemyField()[this.fieldIndex]; - const battle = gScene.currentBattle; + const battle = globalScene.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(); - gScene.currentBattle.turnCommands[this.fieldIndex + BattlerIndex.ENEMY] = + globalScene.currentBattle.turnCommands[this.fieldIndex + BattlerIndex.ENEMY] = { command: Command.FIGHT, move: nextMove, skip: this.skipTurn }; - gScene.currentBattle.enemySwitchCounter = Math.max(gScene.currentBattle.enemySwitchCounter - 1, 0); + globalScene.currentBattle.enemySwitchCounter = Math.max(globalScene.currentBattle.enemySwitchCounter - 1, 0); this.end(); } diff --git a/src/phases/evolution-phase.ts b/src/phases/evolution-phase.ts index c6e9a8fc271..55aa538b1ae 100644 --- a/src/phases/evolution-phase.ts +++ b/src/phases/evolution-phase.ts @@ -1,6 +1,6 @@ import SoundFade from "phaser3-rex-plugins/plugins/soundfade"; import { Phase } from "#app/phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -42,7 +42,7 @@ export class EvolutionPhase extends Phase { } setMode(): Promise { - return gScene.ui.setModeForceTransition(Mode.EVOLUTION_SCENE); + return globalScene.ui.setModeForceTransition(Mode.EVOLUTION_SCENE); } start() { @@ -54,30 +54,30 @@ export class EvolutionPhase extends Phase { return this.end(); } - gScene.fadeOutBgm(undefined, false); + globalScene.fadeOutBgm(undefined, false); - const evolutionHandler = gScene.ui.getHandler() as EvolutionSceneHandler; + const evolutionHandler = globalScene.ui.getHandler() as EvolutionSceneHandler; this.evolutionContainer = evolutionHandler.evolutionContainer; - this.evolutionBaseBg = gScene.add.image(0, 0, "default_bg"); + this.evolutionBaseBg = globalScene.add.image(0, 0, "default_bg"); this.evolutionBaseBg.setOrigin(0, 0); this.evolutionContainer.add(this.evolutionBaseBg); - this.evolutionBg = gScene.add.video(0, 0, "evo_bg").stop(); + this.evolutionBg = globalScene.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 = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0x262626); + this.evolutionBgOverlay = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6, 0x262626); this.evolutionBgOverlay.setOrigin(0, 0); this.evolutionBgOverlay.setAlpha(0); this.evolutionContainer.add(this.evolutionBgOverlay); const getPokemonSprite = () => { - 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 }); + const ret = globalScene.addPokemonSprite(this.pokemon, this.evolutionBaseBg.displayWidth / 2, this.evolutionBaseBg.displayHeight / 2, "pkmn__sub"); + ret.setPipeline(globalScene.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 = gScene.add.rectangle(0, -gScene.game.canvas.height / 6, gScene.game.canvas.width / 6, (gScene.game.canvas.height / 6) - 48, 0xFFFFFF); + this.evolutionOverlay = globalScene.add.rectangle(0, -globalScene.game.canvas.height / 6, globalScene.game.canvas.width / 6, (globalScene.game.canvas.height / 6) - 48, 0xFFFFFF); this.evolutionOverlay.setOrigin(0, 0); this.evolutionOverlay.setAlpha(0); - gScene.ui.add(this.evolutionOverlay); + globalScene.ui.add(this.evolutionOverlay); [ this.pokemonSprite, this.pokemonTintSprite, this.pokemonEvoSprite, this.pokemonEvoTintSprite ].map(sprite => { sprite.play(this.pokemon.getSpriteKey(true)); - sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(this.pokemon.getTeraType()) }); + sprite.setPipeline(globalScene.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 = gScene.ui.getHandler() as EvolutionSceneHandler; + const evolutionHandler = globalScene.ui.getHandler() as EvolutionSceneHandler; const preName = getPokemonNameWithAffix(this.pokemon); - gScene.ui.showText(i18next.t("menu:evolving", { pokemonName: preName }), null, () => { + globalScene.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 { }); }); - gScene.time.delayedCall(1000, () => { - const evolutionBgm = gScene.playSoundWithoutBgm("evolution"); - gScene.tweens.add({ + globalScene.time.delayedCall(1000, () => { + const evolutionBgm = globalScene.playSoundWithoutBgm("evolution"); + globalScene.tweens.add({ targets: this.evolutionBgOverlay, alpha: 1, delay: 500, duration: 1500, ease: "Sine.easeOut", onComplete: () => { - gScene.time.delayedCall(1000, () => { - gScene.tweens.add({ + globalScene.time.delayedCall(1000, () => { + globalScene.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(); }); - gScene.playSound("se/charge"); + globalScene.playSound("se/charge"); this.doSpiralUpward(); - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ from: 0, to: 1, duration: 2000, @@ -168,10 +168,10 @@ export class EvolutionPhase extends Phase { }, onComplete: () => { this.pokemonSprite.setVisible(false); - gScene.time.delayedCall(1100, () => { - gScene.playSound("se/beam"); + globalScene.time.delayedCall(1100, () => { + globalScene.playSound("se/beam"); this.doArcDownward(); - gScene.time.delayedCall(1500, () => { + globalScene.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); - gScene.tweens.add({ + globalScene.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(gScene, evolutionBgm, 100); + SoundFade.fadeOut(globalScene, evolutionBgm, 100); - gScene.unshiftPhase(new EndEvolutionPhase()); + globalScene.unshiftPhase(new EndEvolutionPhase()); - gScene.ui.showText(i18next.t("menu:stoppedEvolving", { pokemonName: preName }), null, () => { - gScene.ui.showText(i18next.t("menu:pauseEvolutionsQuestion", { pokemonName: preName }), null, () => { + globalScene.ui.showText(i18next.t("menu:stoppedEvolving", { pokemonName: preName }), null, () => { + globalScene.ui.showText(i18next.t("menu:pauseEvolutionsQuestion", { pokemonName: preName }), null, () => { const end = () => { - gScene.ui.showText("", 0); - gScene.playBgm(); + globalScene.ui.showText("", 0); + globalScene.playBgm(); evolvedPokemon.destroy(); this.end(); }; - gScene.ui.setOverlayMode(Mode.CONFIRM, () => { - gScene.ui.revertMode(); + globalScene.ui.setOverlayMode(Mode.CONFIRM, () => { + globalScene.ui.revertMode(); this.pokemon.pauseEvolutions = true; - gScene.ui.showText(i18next.t("menu:evolutionsPaused", { pokemonName: preName }), null, end, 3000); + globalScene.ui.showText(i18next.t("menu:evolutionsPaused", { pokemonName: preName }), null, end, 3000); }, () => { - gScene.ui.revertMode(); - gScene.time.delayedCall(3000, end); + globalScene.ui.revertMode(); + globalScene.time.delayedCall(3000, end); }); }); }, null, true); return; } - gScene.playSound("se/sparkle"); + globalScene.playSound("se/sparkle"); this.pokemonEvoSprite.setVisible(true); this.doCircleInward(); - gScene.time.delayedCall(900, () => { + globalScene.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) { - gScene.unshiftPhase(new LearnMovePhase(gScene.getParty().indexOf(this.pokemon), lm[1])); + globalScene.unshiftPhase(new LearnMovePhase(globalScene.getParty().indexOf(this.pokemon), lm[1])); } - gScene.unshiftPhase(new EndEvolutionPhase()); + globalScene.unshiftPhase(new EndEvolutionPhase()); - gScene.playSound("se/shine"); + globalScene.playSound("se/shine"); this.doSpray(); - gScene.tweens.add({ + globalScene.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); - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.evolutionOverlay, this.pokemonEvoTintSprite ], alpha: 0, duration: 2000, delay: 150, easing: "Sine.easeIn", onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.evolutionBgOverlay, alpha: 0, duration: 250, onComplete: () => { - SoundFade.fadeOut(gScene, evolutionBgm, 100); - gScene.time.delayedCall(250, () => { + SoundFade.fadeOut(globalScene, evolutionBgm, 100); + globalScene.time.delayedCall(250, () => { this.pokemon.cry(); - gScene.time.delayedCall(1250, () => { - gScene.playSoundWithoutBgm("evolution_fanfare"); + globalScene.time.delayedCall(1250, () => { + globalScene.playSoundWithoutBgm("evolution_fanfare"); evolvedPokemon.destroy(); - 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()); + globalScene.ui.showText(i18next.t("menu:evolutionDone", { pokemonName: preName, evolvedPokemonName: this.pokemon.name }), null, () => this.end(), null, true, Utils.fixedInt(4000)); + globalScene.time.delayedCall(Utils.fixedInt(4250), () => globalScene.playBgm()); }); }); } @@ -283,7 +283,7 @@ export class EvolutionPhase extends Phase { doSpiralUpward() { let f = 0; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ repeat: 64, duration: Utils.getFrameMs(1), onRepeat: () => { @@ -302,7 +302,7 @@ export class EvolutionPhase extends Phase { doArcDownward() { let f = 0; - gScene.tweens.addCounter({ + globalScene.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 { return new Promise(resolve => { - const evolutionHandler = gScene.ui.getHandler() as EvolutionSceneHandler; + const evolutionHandler = globalScene.ui.getHandler() as EvolutionSceneHandler; const isLastCycle = l === lastCycle; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pokemonTintSprite, scale: 0.25, ease: "Cubic.easeInOut", duration: 500 / l, yoyo: !isLastCycle }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pokemonEvoTintSprite, scale: 1, ease: "Cubic.easeInOut", @@ -353,7 +353,7 @@ export class EvolutionPhase extends Phase { doCircleInward() { let f = 0; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ repeat: 48, duration: Utils.getFrameMs(1), onRepeat: () => { @@ -374,7 +374,7 @@ export class EvolutionPhase extends Phase { doSpray() { let f = 0; - gScene.tweens.addCounter({ + globalScene.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 = gScene.add.image(initialX, 0, "evo_sparkle"); + const particle = globalScene.add.image(initialX, 0, "evo_sparkle"); this.evolutionContainer.add(particle); let f = 0; let amp = 48; - const particleTimer = gScene.tweens.addCounter({ + const particleTimer = globalScene.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 = gScene.add.image(initialX, 0, "evo_sparkle"); + const particle = globalScene.add.image(initialX, 0, "evo_sparkle"); particle.setScale(0.5); this.evolutionContainer.add(particle); let f = 0; let amp = 8; - const particleTimer = gScene.tweens.addCounter({ + const particleTimer = globalScene.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 = gScene.add.image(initialX, initialY, "evo_sparkle"); + const particle = globalScene.add.image(initialX, initialY, "evo_sparkle"); this.evolutionContainer.add(particle); let amp = 120; - const particleTimer = gScene.tweens.addCounter({ + const particleTimer = globalScene.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 = gScene.add.image(initialX, initialY, "evo_sparkle"); + const particle = globalScene.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 = gScene.tweens.addCounter({ + const particleTimer = globalScene.tweens.addCounter({ repeat: -1, duration: Utils.getFrameMs(1), onRepeat: () => { diff --git a/src/phases/exp-phase.ts b/src/phases/exp-phase.ts index 38a7295a98e..1ce35f366db 100644 --- a/src/phases/exp-phase.ts +++ b/src/phases/exp-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { getPokemonNameWithAffix } from "#app/messages"; import { ExpBoosterModifier } from "#app/modifier/modifier"; import i18next from "i18next"; @@ -20,14 +20,14 @@ export class ExpPhase extends PlayerPartyMemberPokemonPhase { const pokemon = this.getPokemon(); const exp = new Utils.NumberHolder(this.expValue); - gScene.applyModifiers(ExpBoosterModifier, true, exp); + globalScene.applyModifiers(ExpBoosterModifier, true, exp); exp.value = Math.floor(exp.value); - gScene.ui.showText(i18next.t("battle:expGain", { pokemonName: getPokemonNameWithAffix(pokemon), exp: exp.value }), null, () => { + globalScene.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) { - gScene.unshiftPhase(new LevelUpPhase(this.partyMemberIndex, lastLevel, newLevel)); + globalScene.unshiftPhase(new LevelUpPhase(this.partyMemberIndex, lastLevel, newLevel)); } pokemon.updateInfo().then(() => this.end()); }, null, true); diff --git a/src/phases/faint-phase.ts b/src/phases/faint-phase.ts index 749e3bb788c..bdc7542bced 100644 --- a/src/phases/faint-phase.ts +++ b/src/phases/faint-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -54,22 +54,22 @@ export class FaintPhase extends PokemonPhase { } if (!this.preventEndure) { - const instantReviveModifier = gScene.applyModifier(PokemonInstantReviveModifier, this.player, this.getPokemon()) as PokemonInstantReviveModifier; + const instantReviveModifier = globalScene.applyModifier(PokemonInstantReviveModifier, this.player, this.getPokemon()) as PokemonInstantReviveModifier; if (instantReviveModifier) { if (!--instantReviveModifier.stackCount) { - gScene.removeModifier(instantReviveModifier); + globalScene.removeModifier(instantReviveModifier); } - gScene.updateModifiers(this.player); + globalScene.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 */ - gScene.getPlayerField().forEach((pokemon, i) => { + globalScene.getPlayerField().forEach((pokemon, i) => { if (pokemon?.isActive(true)) { if (pokemon.isPlayer()) { - gScene.currentBattle.addParticipant(pokemon as PlayerPokemon); + globalScene.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()) { - gScene.currentBattle.playerFaints += 1; - gScene.currentBattle.playerFaintsHistory.push({ pokemon: pokemon, turn: gScene.currentBattle.turn }); + globalScene.currentBattle.playerFaints += 1; + globalScene.currentBattle.playerFaintsHistory.push({ pokemon: pokemon, turn: globalScene.currentBattle.turn }); } else { - gScene.currentBattle.enemyFaints += 1; - gScene.currentBattle.enemyFaintsHistory.push({ pokemon: pokemon, turn: gScene.currentBattle.turn }); + globalScene.currentBattle.enemyFaints += 1; + globalScene.currentBattle.enemyFaintsHistory.push({ pokemon: pokemon, turn: globalScene.currentBattle.turn }); } - gScene.queueMessage(i18next.t("battle:fainted", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, true); - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true); + globalScene.queueMessage(i18next.t("battle:fainted", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon) }), null, true); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true); if (pokemon.turnData?.attacksReceived?.length) { const lastAttack = pokemon.turnData.attacksReceived[0]; - applyPostFaintAbAttrs(PostFaintAbAttr, pokemon, gScene.getPokemonById(lastAttack.sourceId)!, new PokemonMove(lastAttack.move).getMove(), lastAttack.result); // TODO: is this bang correct? + applyPostFaintAbAttrs(PostFaintAbAttr, pokemon, globalScene.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 = gScene.getField(true); + const alivePlayField = globalScene.getField(true); alivePlayField.forEach(p => applyPostKnockOutAbAttrs(PostKnockOutAbAttr, p, pokemon)); if (pokemon.turnData?.attacksReceived?.length) { - const defeatSource = gScene.getPokemonById(pokemon.turnData.attacksReceived[0].sourceId); + const defeatSource = globalScene.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 = gScene.getParty().filter(p => p.isAllowedInBattle()); + const legalPlayerPokemon = globalScene.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 */ - gScene.unshiftPhase(new GameOverPhase()); - } else if (gScene.currentBattle.double && legalPlayerPokemon.length === 1 && legalPlayerPartyPokemon.length === 0) { + globalScene.unshiftPhase(new GameOverPhase()); + } else if (globalScene.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. */ - gScene.unshiftPhase(new ToggleDoublePositionPhase(true)); + globalScene.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. */ - gScene.pushPhase(new SwitchPhase(SwitchType.SWITCH, this.fieldIndex, true, false)); + globalScene.pushPhase(new SwitchPhase(SwitchType.SWITCH, this.fieldIndex, true, false)); } } else { - 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; + globalScene.unshiftPhase(new VictoryPhase(this.battlerIndex)); + if ([ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(globalScene.currentBattle.battleType)) { + const hasReservePartyMember = !!globalScene.getEnemyParty().filter(p => p.isActive() && !p.isOnField() && p.trainerSlot === (pokemon as EnemyPokemon).trainerSlot).length; if (hasReservePartyMember) { - gScene.pushPhase(new SwitchSummonPhase(SwitchType.SWITCH, this.fieldIndex, -1, false, false)); + globalScene.pushPhase(new SwitchSummonPhase(SwitchType.SWITCH, this.fieldIndex, -1, false, false)); } } } // in double battles redirect potential moves off fainted pokemon - if (gScene.currentBattle.double) { + if (globalScene.currentBattle.double) { const allyPokemon = pokemon.getAlly(); - gScene.redirectPokemonMoves(pokemon, allyPokemon); + globalScene.redirectPokemonMoves(pokemon, allyPokemon); } pokemon.faintCry(() => { @@ -160,8 +160,8 @@ export class FaintPhase extends PokemonPhase { pokemon.addFriendship(-FRIENDSHIP_LOSS_FROM_FAINT); } pokemon.hideInfo(); - gScene.playSound("se/faint"); - gScene.tweens.add({ + globalScene.playSound("se/faint"); + globalScene.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); - gScene.getField(true).filter(p => p !== pokemon).forEach(p => p.removeTagsBySourceId(pokemon.id)); + globalScene.getField(true).filter(p => p !== pokemon).forEach(p => p.removeTagsBySourceId(pokemon.id)); pokemon.y -= 150; pokemon.trySetStatus(StatusEffect.FAINT); if (pokemon.isPlayer()) { - gScene.currentBattle.removeFaintedParticipant(pokemon as PlayerPokemon); + globalScene.currentBattle.removeFaintedParticipant(pokemon as PlayerPokemon); } else { - gScene.addFaintedEnemyScore(pokemon as EnemyPokemon); - gScene.currentBattle.addPostBattleLoot(pokemon as EnemyPokemon); + globalScene.addFaintedEnemyScore(pokemon as EnemyPokemon); + globalScene.currentBattle.addPostBattleLoot(pokemon as EnemyPokemon); } - gScene.field.remove(pokemon); + globalScene.field.remove(pokemon); this.end(); } }); @@ -187,16 +187,16 @@ export class FaintPhase extends PokemonPhase { } tryOverrideForBattleSpec(): boolean { - switch (gScene.currentBattle.battleSpec) { + switch (globalScene.currentBattle.battleSpec) { case BattleSpec.FINAL_BOSS: if (!this.player) { const enemy = this.getPokemon(); if (enemy.formIndex) { - gScene.ui.showDialogue(battleSpecDialogue[BattleSpec.FINAL_BOSS].secondStageWin, enemy.species.name, null, () => this.doFaint()); + globalScene.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++; - gScene.unshiftPhase(new DamagePhase(enemy.getBattlerIndex(), 0, HitResult.OTHER)); + globalScene.unshiftPhase(new DamagePhase(enemy.getBattlerIndex(), 0, HitResult.OTHER)); this.end(); } return true; diff --git a/src/phases/field-phase.ts b/src/phases/field-phase.ts index 65d6f0227e0..3315c649664 100644 --- a/src/phases/field-phase.ts +++ b/src/phases/field-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import Pokemon from "#app/field/pokemon"; import { BattlePhase } from "./battle-phase"; @@ -6,7 +6,7 @@ type PokemonFunc = (pokemon: Pokemon) => void; export abstract class FieldPhase extends BattlePhase { executeForAll(func: PokemonFunc): void { - const field = gScene.getField(true).filter(p => p.summonData); + const field = globalScene.getField(true).filter(p => p.summonData); field.forEach(pokemon => func(pokemon)); } } diff --git a/src/phases/form-change-phase.ts b/src/phases/form-change-phase.ts index aff56251650..07ec7adbd02 100644 --- a/src/phases/form-change-phase.ts +++ b/src/phases/form-change-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "../battle-scene"; +import { globalScene } from "../battle-scene"; import * as Utils from "../utils"; import { achvs } from "../system/achv"; import { SpeciesFormChange, getSpeciesFormChangeMessage } from "../data/pokemon-forms"; @@ -30,7 +30,7 @@ export class FormChangePhase extends EvolutionPhase { if (!this.modal) { return super.setMode(); } - return gScene.ui.setOverlayMode(Mode.EVOLUTION_SCENE); + return globalScene.ui.setOverlayMode(Mode.EVOLUTION_SCENE); } doEvolution(): void { @@ -52,16 +52,16 @@ export class FormChangePhase extends EvolutionPhase { }); }); - gScene.time.delayedCall(250, () => { - gScene.tweens.add({ + globalScene.time.delayedCall(250, () => { + globalScene.tweens.add({ targets: this.evolutionBgOverlay, alpha: 1, delay: 500, duration: 1500, ease: "Sine.easeOut", onComplete: () => { - gScene.time.delayedCall(1000, () => { - gScene.tweens.add({ + globalScene.time.delayedCall(1000, () => { + globalScene.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(); }); - gScene.playSound("se/charge"); + globalScene.playSound("se/charge"); this.doSpiralUpward(); - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ from: 0, to: 1, duration: 2000, @@ -80,25 +80,25 @@ export class FormChangePhase extends EvolutionPhase { }, onComplete: () => { this.pokemonSprite.setVisible(false); - gScene.time.delayedCall(1100, () => { - gScene.playSound("se/beam"); + globalScene.time.delayedCall(1100, () => { + globalScene.playSound("se/beam"); this.doArcDownward(); - gScene.time.delayedCall(1000, () => { + globalScene.time.delayedCall(1000, () => { this.pokemonEvoTintSprite.setScale(0.25); this.pokemonEvoTintSprite.setVisible(true); this.doCycle(1, 1).then(_success => { - gScene.playSound("se/sparkle"); + globalScene.playSound("se/sparkle"); this.pokemonEvoSprite.setVisible(true); this.doCircleInward(); - gScene.time.delayedCall(900, () => { + globalScene.time.delayedCall(900, () => { this.pokemon.changeForm(this.formChange).then(() => { if (!this.modal) { - gScene.unshiftPhase(new EndEvolutionPhase()); + globalScene.unshiftPhase(new EndEvolutionPhase()); } - gScene.playSound("se/shine"); + globalScene.playSound("se/shine"); this.doSpray(); - gScene.tweens.add({ + globalScene.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); - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.evolutionOverlay, this.pokemonEvoTintSprite ], alpha: 0, duration: 2000, delay: 150, easing: "Sine.easeIn", onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.evolutionBgOverlay, alpha: 0, duration: 250, onComplete: () => { - gScene.time.delayedCall(250, () => { + globalScene.time.delayedCall(250, () => { this.pokemon.cry(); - gScene.time.delayedCall(1250, () => { + globalScene.time.delayedCall(1250, () => { let playEvolutionFanfare = false; if (this.formChange.formKey.indexOf(SpeciesFormKey.MEGA) > -1) { - gScene.validateAchv(achvs.MEGA_EVOLVE); + globalScene.validateAchv(achvs.MEGA_EVOLVE); playEvolutionFanfare = true; } else if (this.formChange.formKey.indexOf(SpeciesFormKey.GIGANTAMAX) > -1 || this.formChange.formKey.indexOf(SpeciesFormKey.ETERNAMAX) > -1) { - gScene.validateAchv(achvs.GIGANTAMAX); + globalScene.validateAchv(achvs.GIGANTAMAX); playEvolutionFanfare = true; } const delay = playEvolutionFanfare ? 4000 : 1750; - gScene.playSoundWithoutBgm(playEvolutionFanfare ? "evolution_fanfare" : "minor_fanfare"); + globalScene.playSoundWithoutBgm(playEvolutionFanfare ? "evolution_fanfare" : "minor_fanfare"); transformedPokemon.destroy(); - 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()); + globalScene.ui.showText(getSpeciesFormChangeMessage(this.pokemon, this.formChange, preName), null, () => this.end(), null, true, Utils.fixedInt(delay)); + globalScene.time.delayedCall(Utils.fixedInt(delay + 250), () => globalScene.playBgm()); }); }); } @@ -160,9 +160,9 @@ export class FormChangePhase extends EvolutionPhase { end(): void { this.pokemon.findAndRemoveTags(t => t.tagType === BattlerTagType.AUTOTOMIZED); if (this.modal) { - gScene.ui.revertMode().then(() => { - if (gScene.ui.getMode() === Mode.PARTY) { - const partyUiHandler = gScene.ui.getHandler() as PartyUiHandler; + globalScene.ui.revertMode().then(() => { + if (globalScene.ui.getMode() === Mode.PARTY) { + const partyUiHandler = globalScene.ui.getHandler() as PartyUiHandler; partyUiHandler.clearPartySlots(); partyUiHandler.populatePartySlots(); } diff --git a/src/phases/game-over-modifier-reward-phase.ts b/src/phases/game-over-modifier-reward-phase.ts index 7c7c29e8578..08603f89dab 100644 --- a/src/phases/game-over-modifier-reward-phase.ts +++ b/src/phases/game-over-modifier-reward-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { ModifierTypeFunc } from "#app/modifier/modifier-type"; import { Mode } from "#app/ui/ui"; import i18next from "i18next"; @@ -12,13 +12,13 @@ export class GameOverModifierRewardPhase extends ModifierRewardPhase { doReward(): Promise { return new Promise(resolve => { const newModifier = this.modifierType.newModifier(); - gScene.addModifier(newModifier).then(() => { + globalScene.addModifier(newModifier).then(() => { // Sound loaded into game as is - 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)); + globalScene.playSound("level_up_fanfare"); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.fadeIn(250).then(() => { + globalScene.ui.showText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), null, () => { + globalScene.time.delayedCall(1500, () => globalScene.arenaBg.setVisible(true)); resolve(); }, null, true, 1500); }); diff --git a/src/phases/game-over-phase.ts b/src/phases/game-over-phase.ts index 8ecdb465e53..c40a7f92015 100644 --- a/src/phases/game-over-phase.ts +++ b/src/phases/game-over-phase.ts @@ -1,6 +1,6 @@ import { clientSessionId } from "#app/account"; import { BattleType } from "#app/battle"; -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -38,47 +38,47 @@ export class GameOverPhase extends BattlePhase { super.start(); // Failsafe if players somehow skip floor 200 in classic mode - if (gScene.gameMode.isClassic && gScene.currentBattle.waveIndex > 200) { + if (globalScene.gameMode.isClassic && globalScene.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 && gScene.currentBattle.mysteryEncounter?.onGameOver && !gScene.currentBattle.mysteryEncounter.onGameOver()) { + if (!this.victory && globalScene.currentBattle.mysteryEncounter?.onGameOver && !globalScene.currentBattle.mysteryEncounter.onGameOver()) { // Do not end the game return this.end(); } // Otherwise, continue standard Game Over logic - if (this.victory && gScene.gameMode.isEndless) { - const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET; + if (this.victory && globalScene.gameMode.isEndless) { + const genderIndex = globalScene.gameData.gender ?? PlayerGender.UNSET; const genderStr = PlayerGender[genderIndex].toLowerCase(); - gScene.ui.showDialogue(i18next.t("miscDialogue:ending_endless", { context: genderStr }), i18next.t("miscDialogue:ending_name"), 0, () => this.handleGameOver()); - } else if (this.victory || !gScene.enableRetries) { + globalScene.ui.showDialogue(i18next.t("miscDialogue:ending_endless", { context: genderStr }), i18next.t("miscDialogue:ending_name"), 0, () => this.handleGameOver()); + } else if (this.victory || !globalScene.enableRetries) { this.handleGameOver(); } else { - 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)); + globalScene.ui.showText(i18next.t("battle:retryBattle"), null, () => { + globalScene.ui.setMode(Mode.CONFIRM, () => { + globalScene.ui.fadeOut(1250).then(() => { + globalScene.reset(); + globalScene.clearPhaseQueue(); + globalScene.gameData.loadSession(globalScene.sessionSlotId).then(() => { + globalScene.pushPhase(new EncounterPhase(true)); - const availablePartyMembers = gScene.getParty().filter(p => p.isAllowedInBattle()).length; + const availablePartyMembers = globalScene.getParty().filter(p => p.isAllowedInBattle()).length; - gScene.pushPhase(new SummonPhase(0)); - if (gScene.currentBattle.double && availablePartyMembers > 1) { - gScene.pushPhase(new SummonPhase(1)); + globalScene.pushPhase(new SummonPhase(0)); + if (globalScene.currentBattle.double && availablePartyMembers > 1) { + globalScene.pushPhase(new SummonPhase(1)); } - 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)); + if (globalScene.currentBattle.waveIndex > 1 && globalScene.currentBattle.battleType !== BattleType.TRAINER) { + globalScene.pushPhase(new CheckSwitchPhase(0, globalScene.currentBattle.double)); + if (globalScene.currentBattle.double && availablePartyMembers > 1) { + globalScene.pushPhase(new CheckSwitchPhase(1, globalScene.currentBattle.double)); } } - gScene.ui.fadeIn(1250); + globalScene.ui.fadeIn(1250); this.end(); }); }); @@ -89,38 +89,38 @@ export class GameOverPhase extends BattlePhase { handleGameOver(): void { const doGameOver = (newClear: boolean) => { - gScene.disableMenu = true; - gScene.time.delayedCall(1000, () => { + globalScene.disableMenu = true; + globalScene.time.delayedCall(1000, () => { let firstClear = false; if (this.victory && newClear) { - 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()) { + if (globalScene.gameMode.isClassic) { + firstClear = globalScene.validateAchv(achvs.CLASSIC_VICTORY); + globalScene.validateAchv(achvs.UNEVOLVED_CLASSIC_VICTORY); + globalScene.gameData.gameStats.sessionsWon++; + for (const pokemon of globalScene.getParty()) { this.awardRibbon(pokemon); if (pokemon.species.getRootSpeciesId() !== pokemon.species.getRootSpeciesId(true)) { this.awardRibbon(pokemon, true); } } - } else if (gScene.gameMode.isDaily && newClear) { - gScene.gameData.gameStats.dailyRunSessionsWon++; + } else if (globalScene.gameMode.isDaily && newClear) { + globalScene.gameData.gameStats.dailyRunSessionsWon++; } } - gScene.gameData.saveRunHistory(gScene.gameData.getSessionSaveData(), this.victory); + globalScene.gameData.saveRunHistory(globalScene.gameData.getSessionSaveData(), this.victory); const fadeDuration = this.victory ? 10000 : 5000; - gScene.fadeOutBgm(fadeDuration, true); - const activeBattlers = gScene.getField().filter(p => p?.isActive(true)); + globalScene.fadeOutBgm(fadeDuration, true); + const activeBattlers = globalScene.getField().filter(p => p?.isActive(true)); activeBattlers.map(p => p.hideInfo()); - gScene.ui.fadeOut(fadeDuration).then(() => { + globalScene.ui.fadeOut(fadeDuration).then(() => { activeBattlers.map(a => a.setVisible(false)); - gScene.setFieldScale(1, true); - gScene.clearPhaseQueue(); - gScene.ui.clearText(); + globalScene.setFieldScale(1, true); + globalScene.clearPhaseQueue(); + globalScene.ui.clearText(); - if (this.victory && gScene.gameMode.isChallenge) { - gScene.gameMode.challenges.forEach(c => gScene.validateAchvs(ChallengeAchv, c)); + if (this.victory && globalScene.gameMode.isChallenge) { + globalScene.gameMode.challenges.forEach(c => globalScene.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) { - gScene.unshiftPhase(new RibbonModifierRewardPhase(modifierTypes.VOUCHER_PLUS, species)); + globalScene.unshiftPhase(new RibbonModifierRewardPhase(modifierTypes.VOUCHER_PLUS, species)); } if (!firstClear) { - gScene.unshiftPhase(new GameOverModifierRewardPhase(modifierTypes.VOUCHER_PREMIUM)); + globalScene.unshiftPhase(new GameOverModifierRewardPhase(modifierTypes.VOUCHER_PREMIUM)); } } - gScene.pushPhase(new PostGameOverPhase(endCardPhase)); + globalScene.pushPhase(new PostGameOverPhase(endCardPhase)); this.end(); }; - if (this.victory && gScene.gameMode.isClassic) { + if (this.victory && globalScene.gameMode.isClassic) { const dialogueKey = "miscDialogue:ending"; - if (!gScene.ui.shouldSkipDialogue(dialogueKey)) { - gScene.ui.fadeIn(500).then(() => { - const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET; + if (!globalScene.ui.shouldSkipDialogue(dialogueKey)) { + globalScene.ui.fadeIn(500).then(() => { + const genderIndex = globalScene.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 }); - 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(() => { + globalScene.charSprite.showCharacter(`rival_${globalScene.gameData.gender === PlayerGender.FEMALE ? "m" : "f"}`, getCharVariantFromDialogue(dialogue)).then(() => { + globalScene.ui.showDialogue(dialogueKey, globalScene.gameData.gender === PlayerGender.FEMALE ? trainerConfigs[TrainerType.RIVAL].name : trainerConfigs[TrainerType.RIVAL].nameFemale, null, () => { + globalScene.ui.fadeOut(500).then(() => { + globalScene.charSprite.hide().then(() => { const endCardPhase = new EndCardPhase(); - gScene.unshiftPhase(endCardPhase); + globalScene.unshiftPhase(endCardPhase); clear(endCardPhase); }); }); @@ -162,7 +162,7 @@ export class GameOverPhase extends BattlePhase { }); } else { const endCardPhase = new EndCardPhase(); - gScene.unshiftPhase(endCardPhase); + globalScene.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=${gScene.sessionSlotId}&clientSessionId=${clientSessionId}`, true) + Utils.apiFetch(`savedata/session/newclear?slot=${globalScene.sessionSlotId}&clientSessionId=${clientSessionId}`, true) .then(response => response.json()) .then(newClear => doGameOver(newClear)); } else { - gScene.gameData.offlineNewClear().then(result => { + globalScene.gameData.offlineNewClear().then(result => { doGameOver(result); }); } @@ -191,25 +191,25 @@ export class GameOverPhase extends BattlePhase { } handleUnlocks(): void { - if (this.victory && gScene.gameMode.isClassic) { - if (!gScene.gameData.unlocks[Unlockables.ENDLESS_MODE]) { - gScene.unshiftPhase(new UnlockPhase(Unlockables.ENDLESS_MODE)); + if (this.victory && globalScene.gameMode.isClassic) { + if (!globalScene.gameData.unlocks[Unlockables.ENDLESS_MODE]) { + globalScene.unshiftPhase(new UnlockPhase(Unlockables.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 (globalScene.getParty().filter(p => p.fusionSpecies).length && !globalScene.gameData.unlocks[Unlockables.SPLICED_ENDLESS_MODE]) { + globalScene.unshiftPhase(new UnlockPhase(Unlockables.SPLICED_ENDLESS_MODE)); } - if (!gScene.gameData.unlocks[Unlockables.MINI_BLACK_HOLE]) { - gScene.unshiftPhase(new UnlockPhase(Unlockables.MINI_BLACK_HOLE)); + if (!globalScene.gameData.unlocks[Unlockables.MINI_BLACK_HOLE]) { + globalScene.unshiftPhase(new UnlockPhase(Unlockables.MINI_BLACK_HOLE)); } - if (!gScene.gameData.unlocks[Unlockables.EVIOLITE] && gScene.getParty().some(p => p.getSpeciesForm(true).speciesId in pokemonEvolutions)) { - gScene.unshiftPhase(new UnlockPhase(Unlockables.EVIOLITE)); + if (!globalScene.gameData.unlocks[Unlockables.EVIOLITE] && globalScene.getParty().some(p => p.getSpeciesForm(true).speciesId in pokemonEvolutions)) { + globalScene.unshiftPhase(new UnlockPhase(Unlockables.EVIOLITE)); } } } awardRibbon(pokemon: Pokemon, forStarter: boolean = false): void { const speciesId = getPokemonSpecies(pokemon.species.speciesId); - const speciesRibbonCount = gScene.gameData.incrementRibbonCount(speciesId, forStarter); + const speciesRibbonCount = globalScene.gameData.incrementRibbonCount(speciesId, forStarter); // first time classic win, award voucher if (speciesRibbonCount === 1) { this.firstRibbons.push(getPokemonSpecies(pokemon.species.getRootSpeciesId(forStarter))); diff --git a/src/phases/hide-party-exp-bar-phase.ts b/src/phases/hide-party-exp-bar-phase.ts index 8f3fc54b5bc..ee4a2d58f88 100644 --- a/src/phases/hide-party-exp-bar-phase.ts +++ b/src/phases/hide-party-exp-bar-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlePhase } from "./battle-phase"; export class HidePartyExpBarPhase extends BattlePhase { @@ -9,6 +9,6 @@ export class HidePartyExpBarPhase extends BattlePhase { start() { super.start(); - gScene.partyExpBar.hide().then(() => this.end()); + globalScene.partyExpBar.hide().then(() => this.end()); } } diff --git a/src/phases/learn-move-phase.ts b/src/phases/learn-move-phase.ts index 8732dbaf000..6c932428767 100644 --- a/src/phases/learn-move-phase.ts +++ b/src/phases/learn-move-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } 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"; @@ -48,8 +48,8 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase { return this.end(); } - this.messageMode = gScene.ui.getHandler() instanceof EvolutionSceneHandler ? Mode.EVOLUTION_SCENE : Mode.MESSAGE; - gScene.ui.setMode(this.messageMode); + this.messageMode = globalScene.ui.getHandler() instanceof EvolutionSceneHandler ? Mode.EVOLUTION_SCENE : Mode.MESSAGE; + globalScene.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 gScene.ui.showTextPromise(preQText); - await gScene.ui.showTextPromise(shouldReplaceQ, undefined, false); - await gScene.ui.setModeWithoutClear(Mode.CONFIRM, + await globalScene.ui.showTextPromise(preQText); + await globalScene.ui.showTextPromise(shouldReplaceQ, undefined, false); + await globalScene.ui.setModeWithoutClear(Mode.CONFIRM, () => this.forgetMoveProcess(move, pokemon), // Yes () => { // No - gScene.ui.setMode(this.messageMode); + globalScene.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) { - 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) => { + globalScene.ui.setMode(this.messageMode); + await globalScene.ui.showTextPromise(i18next.t("battle:learnMoveForgetQuestion"), undefined, true); + await globalScene.ui.setModeWithoutClear(Mode.SUMMARY, pokemon, SummaryUiMode.LEARN_MOVE, move, (moveIndex: integer) => { if (moveIndex === 4) { - gScene.ui.setMode(this.messageMode).then(() => this.rejectMoveAndEnd(move, pokemon)); + globalScene.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("$"); - gScene.ui.setMode(this.messageMode).then(() => this.learnMove(moveIndex, move, pokemon, fullText)); + globalScene.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 gScene.ui.showTextPromise(i18next.t("battle:learnMoveStopTeaching", { moveName: move.name }), undefined, false); - gScene.ui.setModeWithoutClear(Mode.CONFIRM, + await globalScene.ui.showTextPromise(i18next.t("battle:learnMoveStopTeaching", { moveName: move.name }), undefined, false); + globalScene.ui.setModeWithoutClear(Mode.CONFIRM, () => { - gScene.ui.setMode(this.messageMode); - gScene.ui.showTextPromise(i18next.t("battle:learnMoveNotLearned", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name }), undefined, true).then(() => this.end()); + globalScene.ui.setMode(this.messageMode); + globalScene.ui.showTextPromise(i18next.t("battle:learnMoveNotLearned", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name }), undefined, true).then(() => this.end()); }, () => { - gScene.ui.setMode(this.messageMode); + globalScene.ui.setMode(this.messageMode); this.replaceMoveCheck(move, pokemon); } ); @@ -154,31 +154,31 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase { pokemon.usedTMs = []; } pokemon.usedTMs.push(this.moveId); - gScene.tryRemovePhase((phase) => phase instanceof SelectModifierPhase); + globalScene.tryRemovePhase((phase) => phase instanceof SelectModifierPhase); } else if (this.learnMoveType === LearnMoveType.MEMORY) { if (this.cost !== -1) { if (!Overrides.WAIVE_ROLL_FEE_OVERRIDE) { - gScene.money -= this.cost; - gScene.updateMoneyText(); - gScene.animateMoneyChanged(false); + globalScene.money -= this.cost; + globalScene.updateMoneyText(); + globalScene.animateMoneyChanged(false); } - gScene.playSound("se/buy"); + globalScene.playSound("se/buy"); } else { - gScene.tryRemovePhase((phase) => phase instanceof SelectModifierPhase); + globalScene.tryRemovePhase((phase) => phase instanceof SelectModifierPhase); } } pokemon.setMove(index, this.moveId); initMoveAnim(this.moveId).then(() => { loadMoveAnimAssets([ this.moveId ], true); }); - gScene.ui.setMode(this.messageMode); + globalScene.ui.setMode(this.messageMode); const learnMoveText = i18next.t("battle:learnMove", { pokemonName: getPokemonNameWithAffix(pokemon), moveName: move.name }); if (textMessage) { - await gScene.ui.showTextPromise(textMessage); + await globalScene.ui.showTextPromise(textMessage); } - gScene.playSound("level_up_fanfare"); // Sound loaded into game as is - gScene.ui.showText(learnMoveText, null, () => { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeMoveLearnedTrigger, true); + globalScene.playSound("level_up_fanfare"); // Sound loaded into game as is + globalScene.ui.showText(learnMoveText, null, () => { + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeMoveLearnedTrigger, true); this.end(); }, this.messageMode === Mode.EVOLUTION_SCENE ? 1000 : undefined, true); } diff --git a/src/phases/level-cap-phase.ts b/src/phases/level-cap-phase.ts index e7a0082eee8..8001daa0e70 100644 --- a/src/phases/level-cap-phase.ts +++ b/src/phases/level-cap-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Mode } from "#app/ui/ui"; import i18next from "i18next"; import { FieldPhase } from "./field-phase"; @@ -11,10 +11,10 @@ export class LevelCapPhase extends FieldPhase { start(): void { super.start(); - gScene.ui.setMode(Mode.MESSAGE).then(() => { + globalScene.ui.setMode(Mode.MESSAGE).then(() => { // Sound loaded into game as is - gScene.playSound("level_up_fanfare"); - gScene.ui.showText(i18next.t("battle:levelCapUp", { levelCap: gScene.getMaxExpLevel() }), null, () => this.end(), null, true); + globalScene.playSound("level_up_fanfare"); + globalScene.ui.showText(i18next.t("battle:levelCapUp", { levelCap: globalScene.getMaxExpLevel() }), null, () => this.end(), null, true); this.executeForAll(pokemon => pokemon.updateInfo(true)); }); } diff --git a/src/phases/level-up-phase.ts b/src/phases/level-up-phase.ts index f1630b9e0a4..a0891508d02 100644 --- a/src/phases/level-up-phase.ts +++ b/src/phases/level-up-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { ExpNotification } from "#app/enums/exp-notification"; import { EvolutionPhase } from "#app/phases/evolution-phase"; import { PlayerPokemon } from "#app/field/pokemon"; @@ -23,35 +23,35 @@ export class LevelUpPhase extends PlayerPartyMemberPokemonPhase { start() { super.start(); - if (this.level > gScene.gameData.gameStats.highestLevel) { - gScene.gameData.gameStats.highestLevel = this.level; + if (this.level > globalScene.gameData.gameStats.highestLevel) { + globalScene.gameData.gameStats.highestLevel = this.level; } - gScene.validateAchvs(LevelAchv, new Utils.NumberHolder(this.level)); + globalScene.validateAchvs(LevelAchv, new Utils.NumberHolder(this.level)); const pokemon = this.getPokemon(); const prevStats = pokemon.stats.slice(0); pokemon.calculateStats(); pokemon.updateInfo(); - if (gScene.expParty === ExpNotification.DEFAULT) { - gScene.playSound("level_up_fanfare"); - gScene.ui.showText(i18next.t("battle:levelUp", { pokemonName: getPokemonNameWithAffix(this.getPokemon()), level: this.level }), null, () => gScene.ui.getMessageHandler().promptLevelUpStats(this.partyMemberIndex, prevStats, false).then(() => this.end()), null, true); - } else if (gScene.expParty === ExpNotification.SKIP) { + if (globalScene.expParty === ExpNotification.DEFAULT) { + globalScene.playSound("level_up_fanfare"); + globalScene.ui.showText(i18next.t("battle:levelUp", { pokemonName: getPokemonNameWithAffix(this.getPokemon()), level: this.level }), null, () => globalScene.ui.getMessageHandler().promptLevelUpStats(this.partyMemberIndex, prevStats, false).then(() => this.end()), null, true); + } else if (globalScene.expParty === ExpNotification.SKIP) { this.end(); } else { // we still want to display the stats if activated - gScene.ui.getMessageHandler().promptLevelUpStats(this.partyMemberIndex, prevStats, false).then(() => this.end()); + globalScene.ui.getMessageHandler().promptLevelUpStats(this.partyMemberIndex, prevStats, false).then(() => this.end()); } if (this.lastLevel < 100) { // this feels like an unnecessary optimization const levelMoves = this.getPokemon().getLevelMoves(this.lastLevel + 1); for (const lm of levelMoves) { - gScene.unshiftPhase(new LearnMovePhase(this.partyMemberIndex, lm[1])); + globalScene.unshiftPhase(new LearnMovePhase(this.partyMemberIndex, lm[1])); } } if (!pokemon.pauseEvolutions) { const evolution = pokemon.getEvolution(); if (evolution) { - gScene.unshiftPhase(new EvolutionPhase(pokemon as PlayerPokemon, evolution, this.lastLevel)); + globalScene.unshiftPhase(new EvolutionPhase(pokemon as PlayerPokemon, evolution, this.lastLevel)); } } } diff --git a/src/phases/login-phase.ts b/src/phases/login-phase.ts index 4bf2e08c9d3..a86782ce348 100644 --- a/src/phases/login-phase.ts +++ b/src/phases/login-phase.ts @@ -1,5 +1,5 @@ import { updateUserInfo } from "#app/account"; -import { bypassLogin, gScene } from "#app/battle-scene"; +import { bypassLogin, globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; import { handleTutorial, Tutorial } from "#app/tutorial"; import { Mode } from "#app/ui/ui"; @@ -22,50 +22,50 @@ export class LoginPhase extends Phase { const hasSession = !!Utils.getCookie(Utils.sessionIdKey); - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); Utils.executeIf(bypassLogin || hasSession, updateUserInfo).then(response => { const success = response ? response[0] : false; const statusCode = response ? response[1] : null; if (!success) { if (!statusCode || statusCode === 400) { if (this.showText) { - gScene.ui.showText(i18next.t("menu:logInOrCreateAccount")); + globalScene.ui.showText(i18next.t("menu:logInOrCreateAccount")); } - gScene.playSound("menu_open"); + globalScene.playSound("menu_open"); const loadData = () => { updateUserInfo().then(success => { if (!success[0]) { Utils.removeCookie(Utils.sessionIdKey); - gScene.reset(true, true); + globalScene.reset(true, true); return; } - gScene.gameData.loadSystem().then(() => this.end()); + globalScene.gameData.loadSystem().then(() => this.end()); }); }; - gScene.ui.setMode(Mode.LOGIN_FORM, { + globalScene.ui.setMode(Mode.LOGIN_FORM, { buttonActions: [ () => { - gScene.ui.playSelect(); + globalScene.ui.playSelect(); loadData(); }, () => { - gScene.playSound("menu_open"); - gScene.ui.setMode(Mode.REGISTRATION_FORM, { + globalScene.playSound("menu_open"); + globalScene.ui.setMode(Mode.REGISTRATION_FORM, { buttonActions: [ () => { - gScene.ui.playSelect(); + globalScene.ui.playSelect(); updateUserInfo().then(success => { if (!success[0]) { Utils.removeCookie(Utils.sessionIdKey); - gScene.reset(true, true); + globalScene.reset(true, true); return; } this.end(); } ); }, () => { - gScene.unshiftPhase(new LoginPhase(false)); + globalScene.unshiftPhase(new LoginPhase(false)); this.end(); } ] @@ -85,19 +85,19 @@ export class LoginPhase extends Phase { }); } else if (statusCode === 401) { Utils.removeCookie(Utils.sessionIdKey); - gScene.reset(true, true); + globalScene.reset(true, true); } else { - gScene.unshiftPhase(new UnavailablePhase()); + globalScene.unshiftPhase(new UnavailablePhase()); super.end(); } return null; } else { - gScene.gameData.loadSystem().then(success => { + globalScene.gameData.loadSystem().then(success => { if (success || bypassLogin) { this.end(); } else { - gScene.ui.setMode(Mode.MESSAGE); - gScene.ui.showText(t("menu:failedToLoadSaveData")); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(t("menu:failedToLoadSaveData")); } }); } @@ -105,10 +105,10 @@ export class LoginPhase extends Phase { } end(): void { - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.MESSAGE); - if (!gScene.gameData.gender) { - gScene.unshiftPhase(new SelectGenderPhase()); + if (!globalScene.gameData.gender) { + globalScene.unshiftPhase(new SelectGenderPhase()); } handleTutorial(Tutorial.Intro).then(() => super.end()); diff --git a/src/phases/message-phase.ts b/src/phases/message-phase.ts index 26587b8d633..2569ca86f27 100644 --- a/src/phases/message-phase.ts +++ b/src/phases/message-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; export class MessagePhase extends Phase { @@ -23,20 +23,20 @@ export class MessagePhase extends Phase { if (this.text.indexOf("$") > -1) { const pageIndex = this.text.indexOf("$"); - gScene.unshiftPhase(new MessagePhase(this.text.slice(pageIndex + 1), this.callbackDelay, this.prompt, this.promptDelay, this.speaker)); + globalScene.unshiftPhase(new MessagePhase(this.text.slice(pageIndex + 1), this.callbackDelay, this.prompt, this.promptDelay, this.speaker)); this.text = this.text.slice(0, pageIndex).trim(); } if (this.speaker) { - gScene.ui.showDialogue(this.text, this.speaker, null, () => this.end(), this.callbackDelay || (this.prompt ? 0 : 1500), this.promptDelay ?? 0); + globalScene.ui.showDialogue(this.text, this.speaker, null, () => this.end(), this.callbackDelay || (this.prompt ? 0 : 1500), this.promptDelay ?? 0); } else { - gScene.ui.showText(this.text, null, () => this.end(), this.callbackDelay || (this.prompt ? 0 : 1500), this.prompt, this.promptDelay); + globalScene.ui.showText(this.text, null, () => this.end(), this.callbackDelay || (this.prompt ? 0 : 1500), this.prompt, this.promptDelay); } } end() { - if (gScene.abilityBar.shown) { - gScene.abilityBar.hide(); + if (globalScene.abilityBar.shown) { + globalScene.abilityBar.hide(); } super.end(); diff --git a/src/phases/modifier-reward-phase.ts b/src/phases/modifier-reward-phase.ts index c83bd8284b2..4e6286ebf92 100644 --- a/src/phases/modifier-reward-phase.ts +++ b/src/phases/modifier-reward-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { ModifierType, ModifierTypeFunc, getModifierType } from "#app/modifier/modifier-type"; import i18next from "i18next"; import { BattlePhase } from "./battle-phase"; @@ -21,9 +21,9 @@ export class ModifierRewardPhase extends BattlePhase { doReward(): Promise { return new Promise(resolve => { const newModifier = this.modifierType.newModifier(); - gScene.addModifier(newModifier).then(() => { - gScene.playSound("item_fanfare"); - gScene.ui.showText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), null, () => resolve(), null, true); + globalScene.addModifier(newModifier).then(() => { + globalScene.playSound("item_fanfare"); + globalScene.ui.showText(i18next.t("battle:rewardGain", { modifierName: newModifier?.type.name }), null, () => resolve(), null, true); }); }); } diff --git a/src/phases/money-reward-phase.ts b/src/phases/money-reward-phase.ts index b397385264f..9b3f2111110 100644 --- a/src/phases/money-reward-phase.ts +++ b/src/phases/money-reward-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { ArenaTagType } from "#app/enums/arena-tag-type"; import { MoneyMultiplierModifier } from "#app/modifier/modifier"; import i18next from "i18next"; @@ -15,20 +15,20 @@ export class MoneyRewardPhase extends BattlePhase { } start() { - const moneyAmount = new Utils.IntegerHolder(gScene.getWaveMoneyAmount(this.moneyMultiplier)); + const moneyAmount = new Utils.IntegerHolder(globalScene.getWaveMoneyAmount(this.moneyMultiplier)); - gScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); + globalScene.applyModifiers(MoneyMultiplierModifier, true, moneyAmount); - if (gScene.arena.getTag(ArenaTagType.HAPPY_HOUR)) { + if (globalScene.arena.getTag(ArenaTagType.HAPPY_HOUR)) { moneyAmount.value *= 2; } - gScene.addMoney(moneyAmount.value); + globalScene.addMoney(moneyAmount.value); const userLocale = navigator.language || "en-US"; const formattedMoneyAmount = moneyAmount.value.toLocaleString(userLocale); const message = i18next.t("battle:moneyWon", { moneyAmount: formattedMoneyAmount }); - gScene.ui.showText(message, null, () => this.end(), null, true); + globalScene.ui.showText(message, null, () => this.end(), null, true); } } diff --git a/src/phases/move-anim-test-phase.ts b/src/phases/move-anim-test-phase.ts index 1059c965040..b6e88d79f2e 100644 --- a/src/phases/move-anim-test-phase.ts +++ b/src/phases/move-anim-test-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { initMoveAnim, loadMoveAnimAssets, MoveAnim } from "#app/data/battle-anims"; import { allMoves, SelfStatusMove } from "#app/data/move"; import { Moves } from "#app/enums/moves"; @@ -31,8 +31,8 @@ export class MoveAnimTestPhase extends BattlePhase { initMoveAnim(moveId).then(() => { loadMoveAnimAssets([ moveId ], true) .then(() => { - const user = player ? gScene.getPlayerPokemon()! : gScene.getEnemyPokemon()!; - const target = (player !== (allMoves[moveId] instanceof SelfStatusMove)) ? gScene.getEnemyPokemon()! : gScene.getPlayerPokemon()!; + const user = player ? globalScene.getPlayerPokemon()! : globalScene.getEnemyPokemon()!; + const target = (player !== (allMoves[moveId] instanceof SelfStatusMove)) ? globalScene.getEnemyPokemon()! : globalScene.getPlayerPokemon()!; new MoveAnim(moveId, user, target.getBattlerIndex()).play(allMoves[moveId].hitsSubstitute(user, target), () => { // TODO: are the bangs correct here? if (player) { this.playMoveAnim(moveQueue, false); diff --git a/src/phases/move-charge-phase.ts b/src/phases/move-charge-phase.ts index 98434c0ad7d..d3ec016c070 100644 --- a/src/phases/move-charge-phase.ts +++ b/src/phases/move-charge-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { MoveChargeAnim } from "#app/data/battle-anims"; import { applyMoveChargeAttrs, MoveEffectAttr, InstantChargeAttr } from "#app/data/move"; @@ -61,9 +61,9 @@ export class MoveChargePhase extends PokemonPhase { if (instantCharge.value) { // this MoveEndPhase will be duplicated by the queued MovePhase if not removed - gScene.tryRemovePhase((phase) => phase instanceof MoveEndPhase && phase.getPokemon() === user); + globalScene.tryRemovePhase((phase) => phase instanceof MoveEndPhase && phase.getPokemon() === user); // queue a new MovePhase for this move's attack phase - gScene.unshiftPhase(new MovePhase(user, [ this.targetIndex ], this.move, false)); + globalScene.unshiftPhase(new MovePhase(user, [ this.targetIndex ], this.move, false)); } else { user.getMoveQueue().push({ move: move.id, targets: [ this.targetIndex ]}); } @@ -75,10 +75,10 @@ export class MoveChargePhase extends PokemonPhase { } public getUserPokemon(): Pokemon { - return (this.player ? gScene.getPlayerField() : gScene.getEnemyField())[this.fieldIndex]; + return (this.player ? globalScene.getPlayerField() : globalScene.getEnemyField())[this.fieldIndex]; } public getTargetPokemon(): Pokemon | undefined { - return gScene.getField(true).find((p) => this.targetIndex === p.getBattlerIndex()); + return globalScene.getField(true).find((p) => this.targetIndex === p.getBattlerIndex()); } } diff --git a/src/phases/move-effect-phase.ts b/src/phases/move-effect-phase.ts index 3e1d950426c..71f86a99126 100644 --- a/src/phases/move-effect-phase.ts +++ b/src/phases/move-effect-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { applyPreAttackAbAttrs, AddSecondStrikeAbAttr, IgnoreMoveEffectsAbAttr, applyPostDefendAbAttrs, PostDefendAbAttr, applyPostAttackAbAttrs, PostAttackAbAttr, MaxMultiHitAbAttr, AlwaysHitAbAttr, TypeImmunityAbAttr } from "#app/data/ability"; import { ArenaTagSide, ConditionalProtectTag } from "#app/data/arena-tag"; @@ -78,7 +78,7 @@ export class MoveEffectPhase extends PokemonPhase { applyPreAttackAbAttrs(AddSecondStrikeAbAttr, user, null, move, false, targets.length, hitCount, new Utils.IntegerHolder(0)); // If Multi-Lens is applicable, multiply the hit count by 1 + the number of Multi-Lenses held by the user if (move instanceof AttackMove && !move.hasAttr(FixedDamageAttr)) { - gScene.applyModifiers(PokemonMultiHitModifier, user.isPlayer(), user, hitCount, new Utils.IntegerHolder(0)); + globalScene.applyModifiers(PokemonMultiHitModifier, user.isPlayer(), user, hitCount, new Utils.IntegerHolder(0)); } // Set the user's relevant turnData fields to reflect the final hit count user.turnData.hitCount = hitCount.value; @@ -111,11 +111,11 @@ export class MoveEffectPhase extends PokemonPhase { if (!hasActiveTargets || (!move.hasAttr(VariableTargetAttr) && !move.isMultiTarget() && !targetHitChecks[this.targets[0]] && !targets[0].getTag(ProtectedTag) && !isImmune)) { this.stopMultiHit(); if (hasActiveTargets) { - gScene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: this.getTarget() ? getPokemonNameWithAffix(this.getTarget()!) : "" })); + globalScene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: this.getTarget() ? getPokemonNameWithAffix(this.getTarget()!) : "" })); moveHistoryEntry.result = MoveResult.MISS; applyMoveAttrs(MissEffectAttr, user, null, move); } else { - gScene.queueMessage(i18next.t("battle:attackFailed")); + globalScene.queueMessage(i18next.t("battle:attackFailed")); moveHistoryEntry.result = MoveResult.FAIL; } user.pushMoveHistory(moveHistoryEntry); @@ -125,7 +125,7 @@ export class MoveEffectPhase extends PokemonPhase { /** All move effect attributes are chained together in this array to be applied asynchronously. */ const applyAttrs: Promise[] = []; - const playOnEmptyField = gScene.currentBattle?.mysteryEncounter?.hasBattleAnimationsWithoutTargets ?? false; + const playOnEmptyField = globalScene.currentBattle?.mysteryEncounter?.hasBattleAnimationsWithoutTargets ?? false; // Move animation only needs one target new MoveAnim(move.id as Moves, user, this.getTarget()!.getBattlerIndex()!, playOnEmptyField).play(move.hitsSubstitute(user, this.getTarget()!), () => { /** Has the move successfully hit a target (for damage) yet? */ @@ -140,7 +140,7 @@ export class MoveEffectPhase extends PokemonPhase { const bypassIgnoreProtect = new Utils.BooleanHolder(false); /** If the move is not targeting a Pokemon on the user's side, try to apply conditional protection effects */ if (!this.move.getMove().isAllyTarget()) { - gScene.arena.applyTagsForSide(ConditionalProtectTag, targetSide, false, hasConditionalProtectApplied, user, target, move.id, bypassIgnoreProtect); + globalScene.arena.applyTagsForSide(ConditionalProtectTag, targetSide, false, hasConditionalProtectApplied, user, target, move.id, bypassIgnoreProtect); } /** Is the target protected by Protect, etc. or a relevant conditional protection effect? */ @@ -158,7 +158,7 @@ export class MoveEffectPhase extends PokemonPhase { */ if (!isImmune && !isProtected && !targetHitChecks[target.getBattlerIndex()]) { this.stopMultiHit(target); - gScene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: getPokemonNameWithAffix(target) })); + globalScene.queueMessage(i18next.t("battle:attackMissed", { pokemonNameWithAffix: getPokemonNameWithAffix(target) })); if (moveHistoryEntry.result === MoveResult.PENDING) { moveHistoryEntry.result = MoveResult.MISS; } @@ -226,7 +226,7 @@ export class MoveEffectPhase extends PokemonPhase { * (see Relic Song's interaction with Parental Bond when used by Meloetta). */ if (lastHit) { - gScene.triggerPokemonFormChange(user, SpeciesFormChangePostMoveTrigger); + globalScene.triggerPokemonFormChange(user, SpeciesFormChangePostMoveTrigger); } /** @@ -258,7 +258,7 @@ export class MoveEffectPhase extends PokemonPhase { */ if (dealsDamage && !target.hasAbilityWithAttr(IgnoreMoveEffectsAbAttr) && !move.hitsSubstitute(user, target)) { const flinched = new Utils.BooleanHolder(false); - gScene.applyModifiers(FlinchChanceModifier, user.isPlayer(), user, flinched); + globalScene.applyModifiers(FlinchChanceModifier, user.isPlayer(), user, flinched); if (flinched.value) { target.addTag(BattlerTagType.FLINCHED, undefined, this.move.moveId, user.id); } @@ -275,7 +275,7 @@ export class MoveEffectPhase extends PokemonPhase { // If the invoked move is an enemy attack, apply the enemy's status effect-inflicting tokens if (!user.isPlayer() && this.move.getMove() instanceof AttackMove) { - gScene.applyShuffledModifiers(EnemyAttackStatusEffectChanceModifier, false, target); + globalScene.applyShuffledModifiers(EnemyAttackStatusEffectChanceModifier, false, target); } target.lapseTags(BattlerTagLapseType.AFTER_HIT); @@ -287,7 +287,7 @@ export class MoveEffectPhase extends PokemonPhase { * steal an item from the target granted by Grip Claw */ if (this.move.getMove() instanceof AttackMove) { - gScene.applyModifiers(ContactHeldItemTransferChanceModifier, this.player, user, target); + globalScene.applyModifiers(ContactHeldItemTransferChanceModifier, this.player, user, target); } resolve(); }); @@ -348,16 +348,16 @@ export class MoveEffectPhase extends PokemonPhase { */ if (user) { if (user.turnData.hitsLeft && --user.turnData.hitsLeft >= 1 && this.getTarget()?.isActive()) { - gScene.unshiftPhase(this.getNewHitPhase()); + globalScene.unshiftPhase(this.getNewHitPhase()); } else { // Queue message for number of hits made by multi-move // If multi-hit attack only hits once, still want to render a message const hitsTotal = user.turnData.hitCount - Math.max(user.turnData.hitsLeft, 0); if (hitsTotal > 1 || (user.turnData.hitsLeft && user.turnData.hitsLeft > 0)) { // If there are multiple hits, or if there are hits of the multi-hit move left - gScene.queueMessage(i18next.t("battle:attackHitsCount", { count: hitsTotal })); + globalScene.queueMessage(i18next.t("battle:attackHitsCount", { count: hitsTotal })); } - gScene.applyModifiers(HitHealModifier, this.player, user); + globalScene.applyModifiers(HitHealModifier, this.player, user); // Clear all cached move effectiveness values among targets this.getTargets().forEach((target) => target.turnData.moveEffectiveness = null); } @@ -428,14 +428,14 @@ export class MoveEffectPhase extends PokemonPhase { /** Returns the {@linkcode Pokemon} using this phase's invoked move */ getUserPokemon(): Pokemon | undefined { if (this.battlerIndex > BattlerIndex.ENEMY_2) { - return gScene.getPokemonById(this.battlerIndex) ?? undefined; + return globalScene.getPokemonById(this.battlerIndex) ?? undefined; } - return (this.player ? gScene.getPlayerField() : gScene.getEnemyField())[this.fieldIndex]; + return (this.player ? globalScene.getPlayerField() : globalScene.getEnemyField())[this.fieldIndex]; } /** Returns an array of all {@linkcode Pokemon} targeted by this phase's invoked move */ getTargets(): Pokemon[] { - return gScene.getField(true).filter(p => this.targets.indexOf(p.getBattlerIndex()) > -1); + return globalScene.getField(true).filter(p => this.targets.indexOf(p.getBattlerIndex()) > -1); } /** Returns the first target of this phase's invoked move */ diff --git a/src/phases/move-end-phase.ts b/src/phases/move-end-phase.ts index d738c1c1981..485c0742e3a 100644 --- a/src/phases/move-end-phase.ts +++ b/src/phases/move-end-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { BattlerTagLapseType } from "#app/data/battler-tags"; import { PokemonPhase } from "./pokemon-phase"; @@ -16,7 +16,7 @@ export class MoveEndPhase extends PokemonPhase { pokemon.lapseTags(BattlerTagLapseType.AFTER_MOVE); } - gScene.arena.setIgnoreAbilities(false); + globalScene.arena.setIgnoreAbilities(false); this.end(); } diff --git a/src/phases/move-phase.ts b/src/phases/move-phase.ts index 73e863cc204..833e81b9a33 100644 --- a/src/phases/move-phase.ts +++ b/src/phases/move-phase.ts @@ -1,5 +1,5 @@ import { BattlerIndex } from "#app/battle"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { applyAbAttrs, applyPostMoveUsedAbAttrs, applyPreAttackAbAttrs, BlockRedirectAbAttr, IncreasePpAbAttr, PokemonTypeChangeAbAttr, PostMoveUsedAbAttr, RedirectMoveAbAttr, ReduceStatusEffectDurationAbAttr } from "#app/data/ability"; import { CommonAnim } from "#app/data/battle-anims"; import { BattlerTagLapseType, CenterOfAttentionTag } from "#app/data/battler-tags"; @@ -118,7 +118,7 @@ export class MovePhase extends BattlePhase { // Check move to see if arena.ignoreAbilities should be true. if (!this.followUp) { if (this.move.getMove().checkFlag(MoveFlags.IGNORE_ABILITIES, this.pokemon, null)) { - gScene.arena.setIgnoreAbilities(true, this.pokemon.getBattlerIndex()); + globalScene.arena.setIgnoreAbilities(true, this.pokemon.getBattlerIndex()); } } @@ -158,7 +158,7 @@ export class MovePhase extends BattlePhase { } public getActiveTargetPokemon(): Pokemon[] { - return gScene.getField(true).filter(p => this.targets.includes(p.getBattlerIndex())); + return globalScene.getField(true).filter(p => this.targets.includes(p.getBattlerIndex())); } /** @@ -197,10 +197,10 @@ export class MovePhase extends BattlePhase { if (activated) { this.cancel(); - gScene.queueMessage(getStatusEffectActivationText(this.pokemon.status.effect, getPokemonNameWithAffix(this.pokemon))); - gScene.unshiftPhase(new CommonAnimPhase(this.pokemon.getBattlerIndex(), undefined, CommonAnim.POISON + (this.pokemon.status.effect - 1))); + globalScene.queueMessage(getStatusEffectActivationText(this.pokemon.status.effect, getPokemonNameWithAffix(this.pokemon))); + globalScene.unshiftPhase(new CommonAnimPhase(this.pokemon.getBattlerIndex(), undefined, CommonAnim.POISON + (this.pokemon.status.effect - 1))); } else if (healed) { - gScene.queueMessage(getStatusEffectHealText(this.pokemon.status.effect, getPokemonNameWithAffix(this.pokemon))); + globalScene.queueMessage(getStatusEffectHealText(this.pokemon.status.effect, getPokemonNameWithAffix(this.pokemon))); this.pokemon.resetStatus(); this.pokemon.updateInfo(); } @@ -225,7 +225,7 @@ export class MovePhase extends BattlePhase { const moveQueue = this.pokemon.getMoveQueue(); // form changes happen even before we know that the move wll execute. - gScene.triggerPokemonFormChange(this.pokemon, SpeciesFormChangePreMoveTrigger); + globalScene.triggerPokemonFormChange(this.pokemon, SpeciesFormChangePreMoveTrigger); this.showMoveText(); @@ -243,12 +243,12 @@ export class MovePhase extends BattlePhase { const ppUsed = 1 + this.getPpIncreaseFromPressure(targets); this.move.usePp(ppUsed); - gScene.eventTarget.dispatchEvent(new MoveUsedEvent(this.pokemon?.id, this.move.getMove(), this.move.ppUsed)); + globalScene.eventTarget.dispatchEvent(new MoveUsedEvent(this.pokemon?.id, this.move.getMove(), this.move.ppUsed)); } // Update the battle's "last move" pointer, unless we're currently mimicking a move. if (!allMoves[this.move.moveId].hasAttr(CopyMoveAttr)) { - gScene.currentBattle.lastMove = this.move.moveId; + globalScene.currentBattle.lastMove = this.move.moveId; } /** @@ -269,8 +269,8 @@ export class MovePhase extends BattlePhase { * TODO: is this sustainable? */ const passesConditions = move.applyConditions(this.pokemon, targets[0], move); - const failedDueToWeather: boolean = gScene.arena.isMoveWeatherCancelled(this.pokemon, move); - const failedDueToTerrain: boolean = gScene.arena.isMoveTerrainCancelled(this.pokemon, this.targets, move); + const failedDueToWeather: boolean = globalScene.arena.isMoveWeatherCancelled(this.pokemon, move); + const failedDueToTerrain: boolean = globalScene.arena.isMoveTerrainCancelled(this.pokemon, this.targets, move); const success = passesConditions && !failedDueToWeather && !failedDueToTerrain; @@ -282,7 +282,7 @@ export class MovePhase extends BattlePhase { */ if (success) { applyPreAttackAbAttrs(PokemonTypeChangeAbAttr, this.pokemon, null, this.move.getMove()); - gScene.unshiftPhase(new MoveEffectPhase(this.pokemon.getBattlerIndex(), this.targets, this.move)); + globalScene.unshiftPhase(new MoveEffectPhase(this.pokemon.getBattlerIndex(), this.targets, this.move)); } else { if ([ Moves.ROAR, Moves.WHIRLWIND, Moves.TRICK_OR_TREAT, Moves.FORESTS_CURSE ].includes(this.move.moveId)) { @@ -297,7 +297,7 @@ export class MovePhase extends BattlePhase { if (failureMessage) { failedText = failureMessage; } else if (failedDueToTerrain) { - failedText = getTerrainBlockMessage(this.pokemon, gScene.arena.getTerrainType()); + failedText = getTerrainBlockMessage(this.pokemon, globalScene.arena.getTerrainType()); } this.showFailedText(failedText); @@ -309,7 +309,7 @@ export class MovePhase extends BattlePhase { // Handle Dancer, which triggers immediately after a move is used (rather than waiting on `this.end()`). // Note that the `!this.followUp` check here prevents an infinite Dancer loop. if (this.move.getMove().hasFlag(MoveFlags.DANCE_MOVE) && !this.followUp) { - gScene.getField(true).forEach(pokemon => { + globalScene.getField(true).forEach(pokemon => { applyPostMoveUsedAbAttrs(PostMoveUsedAbAttr, pokemon, this.move, this.pokemon, this.targets); }); } @@ -325,7 +325,7 @@ export class MovePhase extends BattlePhase { applyPreAttackAbAttrs(PokemonTypeChangeAbAttr, this.pokemon, null, this.move.getMove()); this.showMoveText(); - gScene.unshiftPhase(new MoveChargePhase(this.pokemon.getBattlerIndex(), this.targets[0], this.move)); + globalScene.unshiftPhase(new MoveChargePhase(this.pokemon.getBattlerIndex(), this.targets[0], this.move)); } else { this.pokemon.pushMoveHistory({ move: this.move.moveId, targets: this.targets, result: MoveResult.FAIL, virtual: this.move.virtual }); @@ -350,7 +350,7 @@ export class MovePhase extends BattlePhase { */ public end(): void { if (!this.followUp && this.canMove()) { - gScene.unshiftPhase(new MoveEndPhase(this.pokemon.getBattlerIndex())); + globalScene.unshiftPhase(new MoveEndPhase(this.pokemon.getBattlerIndex())); } super.end(); @@ -378,7 +378,7 @@ export class MovePhase extends BattlePhase { const redirectTarget = new NumberHolder(currentTarget); // check move redirection abilities of every pokemon *except* the user. - gScene.getField(true).filter(p => p !== this.pokemon).forEach(p => applyAbAttrs(RedirectMoveAbAttr, p, null, false, this.move.moveId, redirectTarget)); + globalScene.getField(true).filter(p => p !== this.pokemon).forEach(p => applyAbAttrs(RedirectMoveAbAttr, p, null, false, this.move.moveId, redirectTarget)); /** `true` if an Ability is responsible for redirecting the move to another target; `false` otherwise */ let redirectedByAbility = (currentTarget !== redirectTarget.value); @@ -405,7 +405,7 @@ export class MovePhase extends BattlePhase { if (this.pokemon.hasAbilityWithAttr(BlockRedirectAbAttr)) { redirectTarget.value = currentTarget; - gScene.unshiftPhase(new ShowAbilityPhase(this.pokemon.getBattlerIndex(), this.pokemon.getPassiveAbility().hasAttr(BlockRedirectAbAttr))); + globalScene.unshiftPhase(new ShowAbilityPhase(this.pokemon.getBattlerIndex(), this.pokemon.getPassiveAbility().hasAttr(BlockRedirectAbAttr))); } this.targets[0] = redirectTarget.value; @@ -428,9 +428,9 @@ export class MovePhase extends BattlePhase { // account for metal burst and comeuppance hitting remaining targets in double battles // counterattack will redirect to remaining ally if original attacker faints - if (gScene.currentBattle.double && this.move.getMove().hasFlag(MoveFlags.REDIRECT_COUNTER)) { - if (gScene.getField()[this.targets[0]].hp === 0) { - const opposingField = this.pokemon.isPlayer() ? gScene.getEnemyField() : gScene.getPlayerField(); + if (globalScene.currentBattle.double && this.move.getMove().hasFlag(MoveFlags.REDIRECT_COUNTER)) { + if (globalScene.getField()[this.targets[0]].hp === 0) { + const opposingField = this.pokemon.isPlayer() ? globalScene.getEnemyField() : globalScene.getPlayerField(); this.targets[0] = opposingField.find(p => p.hp > 0)?.getBattlerIndex() ?? BattlerIndex.ATTACKER; } } @@ -467,7 +467,7 @@ export class MovePhase extends BattlePhase { this.move.usePp(); } - gScene.eventTarget.dispatchEvent(new MoveUsedEvent(this.pokemon?.id, this.move.getMove(), ppUsed)); + globalScene.eventTarget.dispatchEvent(new MoveUsedEvent(this.pokemon?.id, this.move.getMove(), ppUsed)); } if (this.cancelled && this.pokemon.summonData?.tags?.find(t => t.tagType === BattlerTagType.FRENZY)) { @@ -496,7 +496,7 @@ export class MovePhase extends BattlePhase { return; } - gScene.queueMessage(i18next.t("battle:useMove", { + globalScene.queueMessage(i18next.t("battle:useMove", { pokemonNameWithAffix: getPokemonNameWithAffix(this.pokemon), moveName: this.move.getName() }), 500); @@ -504,6 +504,6 @@ export class MovePhase extends BattlePhase { } protected showFailedText(failedText?: string): void { - gScene.queueMessage(failedText ?? i18next.t("battle:attackFailed")); + globalScene.queueMessage(failedText ?? i18next.t("battle:attackFailed")); } } diff --git a/src/phases/mystery-encounter-phases.ts b/src/phases/mystery-encounter-phases.ts index efc1c65d253..a926541028d 100644 --- a/src/phases/mystery-encounter-phases.ts +++ b/src/phases/mystery-encounter-phases.ts @@ -1,5 +1,5 @@ import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "../phase"; import { Mode } from "../ui/ui"; import { transitionMysteryEncounterIntroVisuals, OptionSelectSettings } from "../data/mystery-encounters/utils/encounter-phase-utils"; @@ -57,20 +57,20 @@ export class MysteryEncounterPhase extends Phase { super.start(); // Clears out queued phases that are part of standard battle - gScene.clearPhaseQueue(); - gScene.clearPhaseQueueSplice(); + globalScene.clearPhaseQueue(); + globalScene.clearPhaseQueueSplice(); - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; encounter.updateSeedOffset(); if (!this.optionSelectSettings) { // Sets flag that ME was encountered, only if this is not a followup option select phase // Can be used in later MEs to check for requirements to spawn, run history, etc. - gScene.mysteryEncounterSaveData.encounteredEvents.push(new SeenEncounterData(encounter.encounterType, encounter.encounterTier, gScene.currentBattle.waveIndex)); + globalScene.mysteryEncounterSaveData.encounteredEvents.push(new SeenEncounterData(encounter.encounterType, encounter.encounterTier, globalScene.currentBattle.waveIndex)); } // Initiates encounter dialogue window and option select - gScene.ui.setMode(Mode.MYSTERY_ENCOUNTER, this.optionSelectSettings); + globalScene.ui.setMode(Mode.MYSTERY_ENCOUNTER, this.optionSelectSettings); } /** @@ -80,13 +80,13 @@ export class MysteryEncounterPhase extends Phase { */ handleOptionSelect(option: MysteryEncounterOption, index: number): boolean { // Set option selected flag - gScene.currentBattle.mysteryEncounter!.selectedOption = option; + globalScene.currentBattle.mysteryEncounter!.selectedOption = option; if (!this.optionSelectSettings) { // Saves the selected option in the ME save data, only if this is not a followup option select phase // Can be used for analytics purposes to track what options are popular on certain encounters - const encounterSaveData = gScene.mysteryEncounterSaveData.encounteredEvents[gScene.mysteryEncounterSaveData.encounteredEvents.length - 1]; - if (encounterSaveData.type === gScene.currentBattle.mysteryEncounter?.encounterType) { + const encounterSaveData = globalScene.mysteryEncounterSaveData.encounteredEvents[globalScene.mysteryEncounterSaveData.encounteredEvents.length - 1]; + if (encounterSaveData.type === globalScene.currentBattle.mysteryEncounter?.encounterType) { encounterSaveData.selectedOption = index; } } @@ -96,17 +96,17 @@ export class MysteryEncounterPhase extends Phase { } // Populate dialogue tokens for option requirements - gScene.currentBattle.mysteryEncounter!.populateDialogueTokensFromRequirements(); + globalScene.currentBattle.mysteryEncounter!.populateDialogueTokensFromRequirements(); if (option.onPreOptionPhase) { - gScene.executeWithSeedOffset(async () => { + globalScene.executeWithSeedOffset(async () => { return await option.onPreOptionPhase!() .then((result) => { if (isNullOrUndefined(result) || result) { this.continueEncounter(); } }); - }, gScene.currentBattle.mysteryEncounter?.getSeedOffset()); + }, globalScene.currentBattle.mysteryEncounter?.getSeedOffset()); } else { this.continueEncounter(); } @@ -119,14 +119,14 @@ export class MysteryEncounterPhase extends Phase { */ continueEncounter() { const endDialogueAndContinueEncounter = () => { - gScene.pushPhase(new MysteryEncounterOptionSelectedPhase()); + globalScene.pushPhase(new MysteryEncounterOptionSelectedPhase()); this.end(); }; - const optionSelectDialogue = gScene.currentBattle?.mysteryEncounter?.selectedOption?.dialogue; + const optionSelectDialogue = globalScene.currentBattle?.mysteryEncounter?.selectedOption?.dialogue; if (optionSelectDialogue?.selected && optionSelectDialogue.selected.length > 0) { // Handle intermediate dialogue (between player selection event and the onOptionSelect logic) - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.MESSAGE); const selectedDialogue = optionSelectDialogue.selected; let i = 0; const showNextDialogue = () => { @@ -140,9 +140,9 @@ export class MysteryEncounterPhase extends Phase { i++; if (title) { - gScene.ui.showDialogue(text ?? "", title, null, nextAction, 0, i === 1 ? this.FIRST_DIALOGUE_PROMPT_DELAY : 0); + globalScene.ui.showDialogue(text ?? "", title, null, nextAction, 0, i === 1 ? this.FIRST_DIALOGUE_PROMPT_DELAY : 0); } else { - gScene.ui.showText(text ?? "", null, nextAction, i === 1 ? this.FIRST_DIALOGUE_PROMPT_DELAY : 0, true); + globalScene.ui.showText(text ?? "", null, nextAction, i === 1 ? this.FIRST_DIALOGUE_PROMPT_DELAY : 0, true); } }; @@ -156,7 +156,7 @@ export class MysteryEncounterPhase extends Phase { * Ends phase */ end() { - gScene.ui.setMode(Mode.MESSAGE).then(() => super.end()); + globalScene.ui.setMode(Mode.MESSAGE).then(() => super.end()); } } @@ -172,7 +172,7 @@ export class MysteryEncounterOptionSelectedPhase extends Phase { constructor() { super(); - this.onOptionSelect = gScene.currentBattle.mysteryEncounter!.selectedOption!.onOptionPhase; + this.onOptionSelect = globalScene.currentBattle.mysteryEncounter!.selectedOption!.onOptionPhase; } /** @@ -184,20 +184,20 @@ export class MysteryEncounterOptionSelectedPhase extends Phase { */ start() { super.start(); - if (gScene.currentBattle.mysteryEncounter?.autoHideIntroVisuals) { + if (globalScene.currentBattle.mysteryEncounter?.autoHideIntroVisuals) { transitionMysteryEncounterIntroVisuals().then(() => { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { this.onOptionSelect().finally(() => { this.end(); }); - }, gScene.currentBattle.mysteryEncounter?.getSeedOffset() * 500); + }, globalScene.currentBattle.mysteryEncounter?.getSeedOffset() * 500); }); } else { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { this.onOptionSelect().finally(() => { this.end(); }); - }, gScene.currentBattle.mysteryEncounter?.getSeedOffset() * 500); + }, globalScene.currentBattle.mysteryEncounter?.getSeedOffset() * 500); } } } @@ -221,7 +221,7 @@ export class MysteryEncounterBattleStartCleanupPhase extends Phase { // Lapse any residual flinches/endures but ignore all other turn-end battle tags const includedLapseTags = [ BattlerTagType.FLINCHED, BattlerTagType.ENDURING ]; - const field = gScene.getField(true).filter(p => p.summonData); + const field = globalScene.getField(true).filter(p => p.summonData); field.forEach(pokemon => { const tags = pokemon.summonData.tags; tags.filter(t => includedLapseTags.includes(t.tagType) @@ -233,31 +233,31 @@ export class MysteryEncounterBattleStartCleanupPhase extends Phase { }); // Remove any status tick phases - while (!!gScene.findPhase(p => p instanceof PostTurnStatusEffectPhase)) { - gScene.tryRemovePhase(p => p instanceof PostTurnStatusEffectPhase); + while (!!globalScene.findPhase(p => p instanceof PostTurnStatusEffectPhase)) { + globalScene.tryRemovePhase(p => p instanceof PostTurnStatusEffectPhase); } // The total number of Pokemon in the player's party that can legally fight - const legalPlayerPokemon = gScene.getParty().filter(p => p.isAllowedInBattle()); + const legalPlayerPokemon = globalScene.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) { - gScene.unshiftPhase(new GameOverPhase()); + globalScene.unshiftPhase(new GameOverPhase()); return this.end(); } // Check for any KOd player mons and switch // For each fainted mon on the field, if there is a legal replacement, summon it - const playerField = gScene.getPlayerField(); + const playerField = globalScene.getPlayerField(); playerField.forEach((pokemon, i) => { if (!pokemon.isAllowedInBattle() && legalPlayerPartyPokemon.length > i) { - gScene.unshiftPhase(new SwitchPhase(SwitchType.SWITCH, i, true, false)); + globalScene.unshiftPhase(new SwitchPhase(SwitchType.SWITCH, i, true, false)); } }); // THEN, if is a double battle, and player only has 1 summoned pokemon, center pokemon on field - if (gScene.currentBattle.double && legalPlayerPokemon.length === 1 && legalPlayerPartyPokemon.length === 0) { - gScene.unshiftPhase(new ToggleDoublePositionPhase(true)); + if (globalScene.currentBattle.double && legalPlayerPokemon.length === 1 && legalPlayerPartyPokemon.length === 0) { + globalScene.unshiftPhase(new ToggleDoublePositionPhase(true)); } this.end(); @@ -294,19 +294,19 @@ export class MysteryEncounterBattlePhase extends Phase { * @private */ private getBattleMessage(): string { - const enemyField = gScene.getEnemyField(); - const encounterMode = gScene.currentBattle.mysteryEncounter!.encounterMode; + const enemyField = globalScene.getEnemyField(); + const encounterMode = globalScene.currentBattle.mysteryEncounter!.encounterMode; - if (gScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { + if (globalScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { return i18next.t("battle:bossAppeared", { bossName: enemyField[0].name }); } if (encounterMode === MysteryEncounterMode.TRAINER_BATTLE) { - if (gScene.currentBattle.double) { - return i18next.t("battle:trainerAppearedDouble", { trainerName: gScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }); + if (globalScene.currentBattle.double) { + return i18next.t("battle:trainerAppearedDouble", { trainerName: globalScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }); } else { - return i18next.t("battle:trainerAppeared", { trainerName: gScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }); + return i18next.t("battle:trainerAppeared", { trainerName: globalScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }); } } @@ -321,62 +321,62 @@ export class MysteryEncounterBattlePhase extends Phase { * @private */ private doMysteryEncounterBattle() { - const encounterMode = gScene.currentBattle.mysteryEncounter!.encounterMode; + const encounterMode = globalScene.currentBattle.mysteryEncounter!.encounterMode; if (encounterMode === MysteryEncounterMode.WILD_BATTLE || encounterMode === MysteryEncounterMode.BOSS_BATTLE) { // Summons the wild/boss Pokemon if (encounterMode === MysteryEncounterMode.BOSS_BATTLE) { - gScene.playBgm(); + globalScene.playBgm(); } - 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)); + const availablePartyMembers = globalScene.getEnemyParty().filter(p => !p.isFainted()).length; + globalScene.unshiftPhase(new SummonPhase(0, false)); + if (globalScene.currentBattle.double && availablePartyMembers > 1) { + globalScene.unshiftPhase(new SummonPhase(1, false)); } - if (!gScene.currentBattle.mysteryEncounter?.hideBattleIntroMessage) { - gScene.ui.showText(this.getBattleMessage(), null, () => this.endBattleSetup(), 0); + if (!globalScene.currentBattle.mysteryEncounter?.hideBattleIntroMessage) { + globalScene.ui.showText(this.getBattleMessage(), null, () => this.endBattleSetup(), 0); } else { this.endBattleSetup(); } } else if (encounterMode === MysteryEncounterMode.TRAINER_BATTLE) { this.showEnemyTrainer(); const doSummon = () => { - gScene.currentBattle.started = true; - gScene.playBgm(); - gScene.pbTray.showPbTray(gScene.getParty()); - gScene.pbTrayEnemy.showPbTray(gScene.getEnemyParty()); + globalScene.currentBattle.started = true; + globalScene.playBgm(); + globalScene.pbTray.showPbTray(globalScene.getParty()); + globalScene.pbTrayEnemy.showPbTray(globalScene.getEnemyParty()); const doTrainerSummon = () => { this.hideEnemyTrainer(); - 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)); + const availablePartyMembers = globalScene.getEnemyParty().filter(p => !p.isFainted()).length; + globalScene.unshiftPhase(new SummonPhase(0, false)); + if (globalScene.currentBattle.double && availablePartyMembers > 1) { + globalScene.unshiftPhase(new SummonPhase(1, false)); } this.endBattleSetup(); }; - if (!gScene.currentBattle.mysteryEncounter?.hideBattleIntroMessage) { - gScene.ui.showText(this.getBattleMessage(), null, doTrainerSummon, 1000, true); + if (!globalScene.currentBattle.mysteryEncounter?.hideBattleIntroMessage) { + globalScene.ui.showText(this.getBattleMessage(), null, doTrainerSummon, 1000, true); } else { doTrainerSummon(); } }; - const encounterMessages = gScene.currentBattle.trainer?.getEncounterMessages(); + const encounterMessages = globalScene.currentBattle.trainer?.getEncounterMessages(); if (!encounterMessages || !encounterMessages.length) { doSummon(); } else { - const trainer = gScene.currentBattle.trainer; + const trainer = globalScene.currentBattle.trainer; let message: string; - gScene.executeWithSeedOffset(() => message = Utils.randSeedItem(encounterMessages), gScene.currentBattle.mysteryEncounter?.getSeedOffset()); + globalScene.executeWithSeedOffset(() => message = Utils.randSeedItem(encounterMessages), globalScene.currentBattle.mysteryEncounter?.getSeedOffset()); message = message!; // tell TS compiler it's defined now const showDialogueAndSummon = () => { - gScene.ui.showDialogue(message, trainer?.getName(TrainerSlot.NONE, true), null, () => { - gScene.charSprite.hide().then(() => gScene.hideFieldOverlay(250).then(() => doSummon())); + globalScene.ui.showDialogue(message, trainer?.getName(TrainerSlot.NONE, true), null, () => { + globalScene.charSprite.hide().then(() => globalScene.hideFieldOverlay(250).then(() => doSummon())); }); }; - 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? + if (globalScene.currentBattle.trainer?.config.hasCharSprite && !globalScene.ui.shouldSkipDialogue(message)) { + globalScene.showFieldOverlay(500).then(() => globalScene.charSprite.showCharacter(trainer?.getKey()!, getCharVariantFromDialogue(encounterMessages[0])).then(() => showDialogueAndSummon())); // TODO: is this bang correct? } else { showDialogueAndSummon(); } @@ -390,44 +390,44 @@ export class MysteryEncounterBattlePhase extends Phase { * @private */ private endBattleSetup() { - const enemyField = gScene.getEnemyField(); - const encounterMode = gScene.currentBattle.mysteryEncounter!.encounterMode; + const enemyField = globalScene.getEnemyField(); + const encounterMode = globalScene.currentBattle.mysteryEncounter!.encounterMode; // PostSummon and ShinySparkle phases are handled by SummonPhase if (encounterMode !== MysteryEncounterMode.TRAINER_BATTLE) { - const ivScannerModifier = gScene.findModifier(m => m instanceof IvScannerModifier); + const ivScannerModifier = globalScene.findModifier(m => m instanceof IvScannerModifier); if (ivScannerModifier) { - enemyField.map(p => gScene.pushPhase(new ScanIvsPhase(p.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6)))); + enemyField.map(p => globalScene.pushPhase(new ScanIvsPhase(p.getBattlerIndex(), Math.min(ivScannerModifier.getStackCount() * 2, 6)))); } } - const availablePartyMembers = gScene.getParty().filter(p => p.isAllowedInBattle()); + const availablePartyMembers = globalScene.getParty().filter(p => p.isAllowedInBattle()); if (!availablePartyMembers[0].isOnField()) { - gScene.pushPhase(new SummonPhase(0)); + globalScene.pushPhase(new SummonPhase(0)); } - if (gScene.currentBattle.double) { + if (globalScene.currentBattle.double) { if (availablePartyMembers.length > 1) { - gScene.pushPhase(new ToggleDoublePositionPhase(true)); + globalScene.pushPhase(new ToggleDoublePositionPhase(true)); if (!availablePartyMembers[1].isOnField()) { - gScene.pushPhase(new SummonPhase(1)); + globalScene.pushPhase(new SummonPhase(1)); } } } else { if (availablePartyMembers.length > 1 && availablePartyMembers[1].isOnField()) { - gScene.pushPhase(new ReturnPhase(1)); + globalScene.pushPhase(new ReturnPhase(1)); } - gScene.pushPhase(new ToggleDoublePositionPhase(false)); + globalScene.pushPhase(new ToggleDoublePositionPhase(false)); } if (encounterMode !== MysteryEncounterMode.TRAINER_BATTLE && !this.disableSwitch) { - const minPartySize = gScene.currentBattle.double ? 2 : 1; + const minPartySize = globalScene.currentBattle.double ? 2 : 1; if (availablePartyMembers.length > minPartySize) { - gScene.pushPhase(new CheckSwitchPhase(0, gScene.currentBattle.double)); - if (gScene.currentBattle.double) { - gScene.pushPhase(new CheckSwitchPhase(1, gScene.currentBattle.double)); + globalScene.pushPhase(new CheckSwitchPhase(0, globalScene.currentBattle.double)); + if (globalScene.currentBattle.double) { + globalScene.pushPhase(new CheckSwitchPhase(1, globalScene.currentBattle.double)); } } } @@ -441,7 +441,7 @@ export class MysteryEncounterBattlePhase extends Phase { */ private showEnemyTrainer(): void { // Show enemy trainer - const trainer = gScene.currentBattle.trainer; + const trainer = globalScene.currentBattle.trainer; if (!trainer) { return; } @@ -449,7 +449,7 @@ export class MysteryEncounterBattlePhase extends Phase { trainer.x += 16; trainer.y -= 16; trainer.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: trainer, x: "-=16", y: "+=16", @@ -464,8 +464,8 @@ export class MysteryEncounterBattlePhase extends Phase { } private hideEnemyTrainer(): void { - gScene.tweens.add({ - targets: gScene.currentBattle.trainer, + globalScene.tweens.add({ + targets: globalScene.currentBattle.trainer, x: "+=16", y: "-=16", alpha: 0, @@ -499,14 +499,14 @@ export class MysteryEncounterRewardsPhase extends Phase { */ start() { super.start(); - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; if (encounter.doContinueEncounter) { encounter.doContinueEncounter().then(() => { this.end(); }); } else { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { if (encounter.onRewards) { encounter.onRewards().then(() => { this.doEncounterRewardsAndContinue(); @@ -515,7 +515,7 @@ export class MysteryEncounterRewardsPhase extends Phase { this.doEncounterRewardsAndContinue(); } // Do not use ME's seedOffset for rewards, these should always be consistent with waveIndex (once per wave) - }, gScene.currentBattle.waveIndex * 1000); + }, globalScene.currentBattle.waveIndex * 1000); } } @@ -523,7 +523,7 @@ export class MysteryEncounterRewardsPhase extends Phase { * Queues encounter EXP and rewards phases, {@linkcode PostMysteryEncounterPhase}, and ends phase */ doEncounterRewardsAndContinue() { - const encounter = gScene.currentBattle.mysteryEncounter!; + const encounter = globalScene.currentBattle.mysteryEncounter!; if (encounter.doEncounterExp) { encounter.doEncounterExp(); @@ -532,11 +532,11 @@ export class MysteryEncounterRewardsPhase extends Phase { if (encounter.doEncounterRewards) { encounter.doEncounterRewards(); } else if (this.addHealPhase) { - gScene.tryRemovePhase(p => p instanceof SelectModifierPhase); - gScene.unshiftPhase(new SelectModifierPhase(0, undefined, { fillRemaining: false, rerollMultiplier: -1 })); + globalScene.tryRemovePhase(p => p instanceof SelectModifierPhase); + globalScene.unshiftPhase(new SelectModifierPhase(0, undefined, { fillRemaining: false, rerollMultiplier: -1 })); } - gScene.pushPhase(new PostMysteryEncounterPhase()); + globalScene.pushPhase(new PostMysteryEncounterPhase()); this.end(); } } @@ -554,7 +554,7 @@ export class PostMysteryEncounterPhase extends Phase { constructor() { super(); - this.onPostOptionSelect = gScene.currentBattle.mysteryEncounter?.selectedOption?.onPostOptionPhase; + this.onPostOptionSelect = globalScene.currentBattle.mysteryEncounter?.selectedOption?.onPostOptionPhase; } /** @@ -564,14 +564,14 @@ export class PostMysteryEncounterPhase extends Phase { super.start(); if (this.onPostOptionSelect) { - gScene.executeWithSeedOffset(async () => { + globalScene.executeWithSeedOffset(async () => { return await this.onPostOptionSelect!() .then((result) => { if (isNullOrUndefined(result) || result) { this.continueEncounter(); } }); - }, gScene.currentBattle.mysteryEncounter?.getSeedOffset() * 2000); + }, globalScene.currentBattle.mysteryEncounter?.getSeedOffset() * 2000); } else { this.continueEncounter(); } @@ -582,11 +582,11 @@ export class PostMysteryEncounterPhase extends Phase { */ continueEncounter() { const endPhase = () => { - gScene.pushPhase(new NewBattlePhase()); + globalScene.pushPhase(new NewBattlePhase()); this.end(); }; - const outroDialogue = gScene.currentBattle?.mysteryEncounter?.dialogue?.outro; + const outroDialogue = globalScene.currentBattle?.mysteryEncounter?.dialogue?.outro; if (outroDialogue && outroDialogue.length > 0) { let i = 0; const showNextDialogue = () => { @@ -599,11 +599,11 @@ export class PostMysteryEncounterPhase extends Phase { } i++; - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.MESSAGE); if (title) { - gScene.ui.showDialogue(text ?? "", title, null, nextAction, 0, i === 1 ? this.FIRST_DIALOGUE_PROMPT_DELAY : 0); + globalScene.ui.showDialogue(text ?? "", title, null, nextAction, 0, i === 1 ? this.FIRST_DIALOGUE_PROMPT_DELAY : 0); } else { - gScene.ui.showText(text ?? "", null, nextAction, i === 1 ? this.FIRST_DIALOGUE_PROMPT_DELAY : 0, true); + globalScene.ui.showText(text ?? "", null, nextAction, i === 1 ? this.FIRST_DIALOGUE_PROMPT_DELAY : 0, true); } }; diff --git a/src/phases/new-battle-phase.ts b/src/phases/new-battle-phase.ts index a622d11060e..e04cc31afad 100644 --- a/src/phases/new-battle-phase.ts +++ b/src/phases/new-battle-phase.ts @@ -1,11 +1,11 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlePhase } from "./battle-phase"; export class NewBattlePhase extends BattlePhase { start() { super.start(); - gScene.newBattle(); + globalScene.newBattle(); this.end(); } diff --git a/src/phases/new-biome-encounter-phase.ts b/src/phases/new-biome-encounter-phase.ts index ad63e7a7775..9d81dfd4f5e 100644 --- a/src/phases/new-biome-encounter-phase.ts +++ b/src/phases/new-biome-encounter-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { applyAbAttrs, PostBiomeChangeAbAttr } from "#app/data/ability"; import { getRandomWeatherType } from "#app/data/weather"; import { NextEncounterPhase } from "./next-encounter-phase"; @@ -9,26 +9,26 @@ export class NewBiomeEncounterPhase extends NextEncounterPhase { } doEncounter(): void { - gScene.playBgm(undefined, true); + globalScene.playBgm(undefined, true); - for (const pokemon of gScene.getParty()) { + for (const pokemon of globalScene.getParty()) { if (pokemon) { pokemon.resetBattleData(); } } - for (const pokemon of gScene.getParty().filter(p => p.isOnField())) { + for (const pokemon of globalScene.getParty().filter(p => p.isOnField())) { applyAbAttrs(PostBiomeChangeAbAttr, pokemon, null); } - const enemyField = gScene.getEnemyField(); - const moveTargets: any[] = [ gScene.arenaEnemy, enemyField ]; - const mysteryEncounter = gScene.currentBattle?.mysteryEncounter?.introVisuals; + const enemyField = globalScene.getEnemyField(); + const moveTargets: any[] = [ globalScene.arenaEnemy, enemyField ]; + const mysteryEncounter = globalScene.currentBattle?.mysteryEncounter?.introVisuals; if (mysteryEncounter) { moveTargets.push(mysteryEncounter); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: moveTargets.flat(), x: "+=300", duration: 2000, @@ -44,6 +44,6 @@ export class NewBiomeEncounterPhase extends NextEncounterPhase { * Set biome weather. */ trySetWeatherIfNewBiome(): void { - gScene.arena.trySetWeather(getRandomWeatherType(gScene.arena), false); + globalScene.arena.trySetWeather(getRandomWeatherType(globalScene.arena), false); } } diff --git a/src/phases/next-encounter-phase.ts b/src/phases/next-encounter-phase.ts index 7ec1b0d6288..77fe72a9317 100644 --- a/src/phases/next-encounter-phase.ts +++ b/src/phases/next-encounter-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { EncounterPhase } from "./encounter-phase"; export class NextEncounterPhase extends EncounterPhase { @@ -11,29 +11,29 @@ export class NextEncounterPhase extends EncounterPhase { } doEncounter(): void { - gScene.playBgm(undefined, true); + globalScene.playBgm(undefined, true); - for (const pokemon of gScene.getParty()) { + for (const pokemon of globalScene.getParty()) { if (pokemon) { pokemon.resetBattleData(); } } - gScene.arenaNextEnemy.setBiome(gScene.arena.biomeType); - gScene.arenaNextEnemy.setVisible(true); + globalScene.arenaNextEnemy.setBiome(globalScene.arena.biomeType); + globalScene.arenaNextEnemy.setVisible(true); - const enemyField = gScene.getEnemyField(); - const moveTargets: any[] = [ gScene.arenaEnemy, gScene.arenaNextEnemy, gScene.currentBattle.trainer, enemyField, gScene.lastEnemyTrainer ]; - const lastEncounterVisuals = gScene.lastMysteryEncounter?.introVisuals; + const enemyField = globalScene.getEnemyField(); + const moveTargets: any[] = [ globalScene.arenaEnemy, globalScene.arenaNextEnemy, globalScene.currentBattle.trainer, enemyField, globalScene.lastEnemyTrainer ]; + const lastEncounterVisuals = globalScene.lastMysteryEncounter?.introVisuals; if (lastEncounterVisuals) { moveTargets.push(lastEncounterVisuals); } - const nextEncounterVisuals = gScene.currentBattle.mysteryEncounter?.introVisuals; + const nextEncounterVisuals = globalScene.currentBattle.mysteryEncounter?.introVisuals; if (nextEncounterVisuals) { const enterFromRight = nextEncounterVisuals.enterFromRight; if (enterFromRight) { nextEncounterVisuals.x += 500; - gScene.tweens.add({ + globalScene.tweens.add({ targets: nextEncounterVisuals, x: "-=200", duration: 2000 @@ -43,22 +43,22 @@ export class NextEncounterPhase extends EncounterPhase { } } - gScene.tweens.add({ + globalScene.tweens.add({ targets: moveTargets.flat(), x: "+=300", duration: 2000, onComplete: () => { - gScene.arenaEnemy.setBiome(gScene.arena.biomeType); - gScene.arenaEnemy.setX(gScene.arenaNextEnemy.x); - gScene.arenaEnemy.setAlpha(1); - gScene.arenaNextEnemy.setX(gScene.arenaNextEnemy.x - 300); - gScene.arenaNextEnemy.setVisible(false); - if (gScene.lastEnemyTrainer) { - gScene.lastEnemyTrainer.destroy(); + globalScene.arenaEnemy.setBiome(globalScene.arena.biomeType); + globalScene.arenaEnemy.setX(globalScene.arenaNextEnemy.x); + globalScene.arenaEnemy.setAlpha(1); + globalScene.arenaNextEnemy.setX(globalScene.arenaNextEnemy.x - 300); + globalScene.arenaNextEnemy.setVisible(false); + if (globalScene.lastEnemyTrainer) { + globalScene.lastEnemyTrainer.destroy(); } if (lastEncounterVisuals) { - gScene.field.remove(lastEncounterVisuals, true); - gScene.lastMysteryEncounter!.introVisuals = undefined; + globalScene.field.remove(lastEncounterVisuals, true); + globalScene.lastMysteryEncounter!.introVisuals = undefined; } if (!this.tryOverrideForBattleSpec()) { diff --git a/src/phases/obtain-status-effect-phase.ts b/src/phases/obtain-status-effect-phase.ts index 1c6a7a185ae..e5fe1942586 100644 --- a/src/phases/obtain-status-effect-phase.ts +++ b/src/phases/obtain-status-effect-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { CommonBattleAnim, CommonAnim } from "#app/data/battle-anims"; import { getStatusEffectObtainText, getStatusEffectOverlapText } from "#app/data/status-effect"; @@ -31,13 +31,13 @@ export class ObtainStatusEffectPhase extends PokemonPhase { } pokemon.updateInfo(true); new CommonBattleAnim(CommonAnim.POISON + (this.statusEffect! - 1), pokemon).play(false, () => { - gScene.queueMessage(getStatusEffectObtainText(this.statusEffect, getPokemonNameWithAffix(pokemon), this.sourceText ?? undefined)); + globalScene.queueMessage(getStatusEffectObtainText(this.statusEffect, getPokemonNameWithAffix(pokemon), this.sourceText ?? undefined)); this.end(); }); return; } } else if (pokemon.status?.effect === this.statusEffect) { - gScene.queueMessage(getStatusEffectOverlapText(this.statusEffect ?? StatusEffect.NONE, getPokemonNameWithAffix(pokemon))); + globalScene.queueMessage(getStatusEffectOverlapText(this.statusEffect ?? StatusEffect.NONE, getPokemonNameWithAffix(pokemon))); } this.end(); } diff --git a/src/phases/party-exp-phase.ts b/src/phases/party-exp-phase.ts index 6085198ba2d..2670023c39f 100644 --- a/src/phases/party-exp-phase.ts +++ b/src/phases/party-exp-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; /** @@ -24,7 +24,7 @@ export class PartyExpPhase extends Phase { start() { super.start(); - gScene.applyPartyExp(this.expValue, false, this.useWaveIndexMultiplier, this.pokemonParticipantIds); + globalScene.applyPartyExp(this.expValue, false, this.useWaveIndexMultiplier, this.pokemonParticipantIds); this.end(); } diff --git a/src/phases/party-heal-phase.ts b/src/phases/party-heal-phase.ts index 2392a36d8ab..4869c3e5a7b 100644 --- a/src/phases/party-heal-phase.ts +++ b/src/phases/party-heal-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import * as Utils from "#app/utils"; import { BattlePhase } from "./battle-phase"; @@ -14,12 +14,12 @@ export class PartyHealPhase extends BattlePhase { start() { super.start(); - const bgmPlaying = gScene.isBgmPlaying(); + const bgmPlaying = globalScene.isBgmPlaying(); if (bgmPlaying) { - gScene.fadeOutBgm(1000, false); + globalScene.fadeOutBgm(1000, false); } - gScene.ui.fadeOut(1000).then(() => { - for (const pokemon of gScene.getParty()) { + globalScene.ui.fadeOut(1000).then(() => { + for (const pokemon of globalScene.getParty()) { pokemon.hp = pokemon.getMaxHp(); pokemon.resetStatus(); for (const move of pokemon.moveset) { @@ -27,13 +27,13 @@ export class PartyHealPhase extends BattlePhase { } pokemon.updateInfo(true); } - const healSong = gScene.playSoundWithoutBgm("heal"); - gScene.time.delayedCall(Utils.fixedInt(healSong.totalDuration * 1000), () => { + const healSong = globalScene.playSoundWithoutBgm("heal"); + globalScene.time.delayedCall(Utils.fixedInt(healSong.totalDuration * 1000), () => { healSong.destroy(); if (this.resumeBgm && bgmPlaying) { - gScene.playBgm(); + globalScene.playBgm(); } - gScene.ui.fadeIn(500).then(() => this.end()); + globalScene.ui.fadeIn(500).then(() => this.end()); }); }); } diff --git a/src/phases/party-member-pokemon-phase.ts b/src/phases/party-member-pokemon-phase.ts index 632efdb4a0c..3e119d4b4fc 100644 --- a/src/phases/party-member-pokemon-phase.ts +++ b/src/phases/party-member-pokemon-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import Pokemon from "#app/field/pokemon"; import { FieldPhase } from "./field-phase"; @@ -11,14 +11,14 @@ export abstract class PartyMemberPokemonPhase extends FieldPhase { super(); this.partyMemberIndex = partyMemberIndex; - this.fieldIndex = partyMemberIndex < gScene.currentBattle.getBattlerCount() + this.fieldIndex = partyMemberIndex < globalScene.currentBattle.getBattlerCount() ? partyMemberIndex : -1; this.player = player; } getParty(): Pokemon[] { - return this.player ? gScene.getParty() : gScene.getEnemyParty(); + return this.player ? globalScene.getParty() : globalScene.getEnemyParty(); } getPokemon(): Pokemon { diff --git a/src/phases/pokemon-anim-phase.ts b/src/phases/pokemon-anim-phase.ts index df028f5f282..da117c02e91 100644 --- a/src/phases/pokemon-anim-phase.ts +++ b/src/phases/pokemon-anim-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { SubstituteTag } from "#app/data/battler-tags"; import { PokemonAnimType } from "#enums/pokemon-anim-type"; import Pokemon from "#app/field/pokemon"; @@ -49,13 +49,13 @@ export class PokemonAnimPhase extends BattlePhase { } const getSprite = () => { - const sprite = gScene.addFieldSprite( + const sprite = globalScene.addFieldSprite( this.pokemon.x + this.pokemon.getSprite().x, this.pokemon.y + this.pokemon.getSprite().y, `pkmn${this.pokemon.isPlayer() ? "__back" : ""}__sub` ); sprite.setOrigin(0.5, 1); - gScene.field.add(sprite); + globalScene.field.add(sprite); return sprite; }; @@ -68,12 +68,12 @@ export class PokemonAnimPhase extends BattlePhase { subTintSprite.setScale(0.01); if (this.pokemon.isPlayer()) { - gScene.field.bringToTop(this.pokemon); + globalScene.field.bringToTop(this.pokemon); } - gScene.playSound("PRSFX- Transform"); + globalScene.playSound("PRSFX- Transform"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pokemon, duration: 500, x: this.pokemon.x + this.pokemon.getSubstituteOffset()[0], @@ -82,7 +82,7 @@ export class PokemonAnimPhase extends BattlePhase { ease: "Sine.easeIn" }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: subTintSprite, delay: 250, scale: subScale, @@ -90,7 +90,7 @@ export class PokemonAnimPhase extends BattlePhase { duration: 500, onComplete: () => { subSprite.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: subTintSprite, delay: 250, alpha: 0, @@ -116,14 +116,14 @@ export class PokemonAnimPhase extends BattlePhase { return this.end(); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: subSprite, alpha: 0, ease: "Sine.easeInOut", duration: 500 }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pokemon, x: subSprite.x, y: subSprite.y, @@ -145,7 +145,7 @@ export class PokemonAnimPhase extends BattlePhase { return this.end(); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pokemon, x: subSprite.x + this.pokemon.getSubstituteOffset()[0], y: subSprite.y + this.pokemon.getSubstituteOffset()[1], @@ -154,7 +154,7 @@ export class PokemonAnimPhase extends BattlePhase { duration: 500 }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: subSprite, alpha: 1, ease: "Sine.easeInOut", @@ -175,13 +175,13 @@ export class PokemonAnimPhase extends BattlePhase { } const getSprite = () => { - const sprite = gScene.addFieldSprite( + const sprite = globalScene.addFieldSprite( subSprite.x, subSprite.y, `pkmn${this.pokemon.isPlayer() ? "__back" : ""}__sub` ); sprite.setOrigin(0.5, 1); - gScene.field.add(sprite); + globalScene.field.add(sprite); return sprite; }; @@ -191,30 +191,30 @@ export class PokemonAnimPhase extends BattlePhase { subTintSprite.setTintFill(0xFFFFFF); subTintSprite.setScale(subScale); - gScene.tweens.add({ + globalScene.tweens.add({ targets: subTintSprite, alpha: 1, ease: "Sine.easeInOut", duration: 500, onComplete: () => { subSprite.destroy(); - const flashTimer = gScene.time.addEvent({ + const flashTimer = globalScene.time.addEvent({ delay: 100, repeat: 7, startAt: 200, callback: () => { - gScene.playSound("PRSFX- Substitute2.wav"); + globalScene.playSound("PRSFX- Substitute2.wav"); subTintSprite.setVisible(flashTimer.repeatCount % 2 === 0); if (!flashTimer.repeatCount) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: subTintSprite, scale: 0.01, ease: "Sine.cubicEaseIn", duration: 500 }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pokemon, x: this.pokemon.x - this.pokemon.getSubstituteOffset()[0], y: this.pokemon.y - this.pokemon.getSubstituteOffset()[1], diff --git a/src/phases/pokemon-heal-phase.ts b/src/phases/pokemon-heal-phase.ts index 02eea82ffd0..62b774687c1 100644 --- a/src/phases/pokemon-heal-phase.ts +++ b/src/phases/pokemon-heal-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { CommonAnim } from "#app/data/battle-anims"; import { getStatusEffectHealText } from "#app/data/status-effect"; @@ -55,13 +55,13 @@ export class PokemonHealPhase extends CommonAnimPhase { let lastStatusEffect = StatusEffect.NONE; if (healBlock && this.hpHealed > 0) { - gScene.queueMessage(healBlock.onActivation(pokemon)); + globalScene.queueMessage(healBlock.onActivation(pokemon)); this.message = null; return super.end(); } else if (healOrDamage) { const hpRestoreMultiplier = new Utils.IntegerHolder(1); if (!this.revive) { - gScene.applyModifiers(HealingBoosterModifier, this.player, hpRestoreMultiplier); + globalScene.applyModifiers(HealingBoosterModifier, this.player, hpRestoreMultiplier); } const healAmount = new Utils.NumberHolder(Math.floor(this.hpHealed * hpRestoreMultiplier.value)); if (healAmount.value < 0) { @@ -74,12 +74,12 @@ export class PokemonHealPhase extends CommonAnimPhase { } healAmount.value = pokemon.heal(healAmount.value); if (healAmount.value) { - gScene.damageNumberHandler.add(pokemon, healAmount.value, HitResult.HEAL); + globalScene.damageNumberHandler.add(pokemon, healAmount.value, HitResult.HEAL); } if (pokemon.isPlayer()) { - gScene.validateAchvs(HealAchv, healAmount); - if (healAmount.value > gScene.gameData.gameStats.highestHeal) { - gScene.gameData.gameStats.highestHeal = healAmount.value; + globalScene.validateAchvs(HealAchv, healAmount); + if (healAmount.value > globalScene.gameData.gameStats.highestHeal) { + globalScene.gameData.gameStats.highestHeal = healAmount.value; } } if (this.healStatus && !this.revive && pokemon.status) { @@ -96,11 +96,11 @@ export class PokemonHealPhase extends CommonAnimPhase { } if (this.message) { - gScene.queueMessage(this.message); + globalScene.queueMessage(this.message); } if (this.healStatus && lastStatusEffect && !hasMessage) { - gScene.queueMessage(getStatusEffectHealText(lastStatusEffect, getPokemonNameWithAffix(pokemon))); + globalScene.queueMessage(getStatusEffectHealText(lastStatusEffect, getPokemonNameWithAffix(pokemon))); } if (!healOrDamage && !lastStatusEffect) { diff --git a/src/phases/pokemon-phase.ts b/src/phases/pokemon-phase.ts index 1288c1376c2..2f07ef022c9 100644 --- a/src/phases/pokemon-phase.ts +++ b/src/phases/pokemon-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import Pokemon from "#app/field/pokemon"; import { FieldPhase } from "./field-phase"; @@ -12,7 +12,7 @@ export abstract class PokemonPhase extends FieldPhase { super(); if (battlerIndex === undefined) { - battlerIndex = gScene.getField().find(p => p?.isActive())!.getBattlerIndex(); // TODO: is the bang correct here? + battlerIndex = globalScene.getField().find(p => p?.isActive())!.getBattlerIndex(); // TODO: is the bang correct here? } this.battlerIndex = battlerIndex; @@ -22,8 +22,8 @@ export abstract class PokemonPhase extends FieldPhase { getPokemon(): Pokemon { if (this.battlerIndex > BattlerIndex.ENEMY_2) { - return gScene.getPokemonById(this.battlerIndex)!; //TODO: is this bang correct? + return globalScene.getPokemonById(this.battlerIndex)!; //TODO: is this bang correct? } - return gScene.getField()[this.battlerIndex]!; //TODO: is this bang correct? + return globalScene.getField()[this.battlerIndex]!; //TODO: is this bang correct? } } diff --git a/src/phases/post-game-over-phase.ts b/src/phases/post-game-over-phase.ts index ee11e6f97b0..4e9bd29b1b9 100644 --- a/src/phases/post-game-over-phase.ts +++ b/src/phases/post-game-over-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; import { EndCardPhase } from "./end-card-phase"; import { TitlePhase } from "./title-phase"; @@ -16,24 +16,24 @@ export class PostGameOverPhase extends Phase { super.start(); const saveAndReset = () => { - gScene.gameData.saveAll(true, true, true).then(success => { + globalScene.gameData.saveAll(true, true, true).then(success => { if (!success) { - return gScene.reset(true); + return globalScene.reset(true); } - gScene.gameData.tryClearSession(gScene.sessionSlotId).then((success: boolean | [boolean, boolean]) => { + globalScene.gameData.tryClearSession(globalScene.sessionSlotId).then((success: boolean | [boolean, boolean]) => { if (!success[0]) { - return gScene.reset(true); + return globalScene.reset(true); } - gScene.reset(); - gScene.unshiftPhase(new TitlePhase()); + globalScene.reset(); + globalScene.unshiftPhase(new TitlePhase()); this.end(); }); }); }; if (this.endCardPhase) { - gScene.ui.fadeOut(500).then(() => { - gScene.ui.getMessageHandler().bg.setVisible(true); + globalScene.ui.fadeOut(500).then(() => { + globalScene.ui.getMessageHandler().bg.setVisible(true); this.endCardPhase?.endCard.destroy(); this.endCardPhase?.text.destroy(); diff --git a/src/phases/post-summon-phase.ts b/src/phases/post-summon-phase.ts index 62bd77298dc..a533004ce04 100644 --- a/src/phases/post-summon-phase.ts +++ b/src/phases/post-summon-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { applyPostSummonAbAttrs, PostSummonAbAttr } from "#app/data/ability"; import { ArenaTrapTag } from "#app/data/arena-tag"; @@ -20,10 +20,10 @@ export class PostSummonPhase extends PokemonPhase { if (pokemon.status?.effect === StatusEffect.TOXIC) { pokemon.status.toxicTurnCount = 0; } - gScene.arena.applyTags(ArenaTrapTag, false, pokemon); + globalScene.arena.applyTags(ArenaTrapTag, false, pokemon); // If this is mystery encounter and has post summon phase tag, apply post summon effects - if (gScene.currentBattle.isBattleMysteryEncounter() && pokemon.findTags(t => t instanceof MysteryEncounterPostSummonTag).length > 0) { + if (globalScene.currentBattle.isBattleMysteryEncounter() && pokemon.findTags(t => t instanceof MysteryEncounterPostSummonTag).length > 0) { pokemon.lapseTag(BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON); } diff --git a/src/phases/post-turn-status-effect-phase.ts b/src/phases/post-turn-status-effect-phase.ts index 634b2c09210..70cdc6e3472 100644 --- a/src/phases/post-turn-status-effect-phase.ts +++ b/src/phases/post-turn-status-effect-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { applyAbAttrs, BlockNonDirectDamageAbAttr, BlockStatusDamageAbAttr, ReduceBurnDamageAbAttr } from "#app/data/ability"; import { CommonBattleAnim, CommonAnim } from "#app/data/battle-anims"; @@ -23,7 +23,7 @@ export class PostTurnStatusEffectPhase extends PokemonPhase { applyAbAttrs(BlockStatusDamageAbAttr, pokemon, cancelled); if (!cancelled.value) { - gScene.queueMessage(getStatusEffectActivationText(pokemon.status.effect, getPokemonNameWithAffix(pokemon))); + globalScene.queueMessage(getStatusEffectActivationText(pokemon.status.effect, getPokemonNameWithAffix(pokemon))); const damage = new Utils.NumberHolder(0); switch (pokemon.status.effect) { case StatusEffect.POISON: @@ -39,7 +39,7 @@ export class PostTurnStatusEffectPhase extends PokemonPhase { } if (damage.value) { // Set preventEndure flag to avoid pokemon surviving thanks to focus band, sturdy, endure ... - gScene.damageNumberHandler.add(this.getPokemon(), pokemon.damage(damage.value, false, true)); + globalScene.damageNumberHandler.add(this.getPokemon(), pokemon.damage(damage.value, false, true)); pokemon.updateInfo(); } new CommonBattleAnim(CommonAnim.POISON + (pokemon.status.effect - 1), pokemon).play(false, () => this.end()); @@ -52,8 +52,8 @@ export class PostTurnStatusEffectPhase extends PokemonPhase { } override end() { - if (gScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { - gScene.initFinalBossPhaseTwo(this.getPokemon()); + if (globalScene.currentBattle.battleSpec === BattleSpec.FINAL_BOSS) { + globalScene.initFinalBossPhaseTwo(this.getPokemon()); } else { super.end(); } diff --git a/src/phases/quiet-form-change-phase.ts b/src/phases/quiet-form-change-phase.ts index 258f1c4dd35..8d7c91f04e1 100644 --- a/src/phases/quiet-form-change-phase.ts +++ b/src/phases/quiet-form-change-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { SemiInvulnerableTag } from "#app/data/battler-tags"; import { SpeciesFormChange, getSpeciesFormChangeMessage } from "#app/data/pokemon-forms"; import { getTypeRgb } from "#app/data/type"; @@ -31,23 +31,23 @@ export class QuietFormChangePhase extends BattlePhase { if (!this.pokemon.isOnField() || this.pokemon.getTag(SemiInvulnerableTag)) { this.pokemon.changeForm(this.formChange).then(() => { - gScene.ui.showText(getSpeciesFormChangeMessage(this.pokemon, this.formChange, preName), null, () => this.end(), 1500); + globalScene.ui.showText(getSpeciesFormChangeMessage(this.pokemon, this.formChange, preName), null, () => this.end(), 1500); }); return; } const getPokemonSprite = () => { - const sprite = gScene.addPokemonSprite(this.pokemon, this.pokemon.x + this.pokemon.getSprite().x, this.pokemon.y + this.pokemon.getSprite().y, "pkmn__sub"); + const sprite = globalScene.addPokemonSprite(this.pokemon, this.pokemon.x + this.pokemon.getSprite().x, this.pokemon.y + this.pokemon.getSprite().y, "pkmn__sub"); sprite.setOrigin(0.5, 1); sprite.play(this.pokemon.getBattleSpriteKey()).stop(); - sprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(this.pokemon.getTeraType()) }); + sprite.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], hasShadow: false, teraColor: getTypeRgb(this.pokemon.getTeraType()) }); [ "spriteColors", "fusionSpriteColors" ].map(k => { if (this.pokemon.summonData?.speciesForm) { k += "Base"; } sprite.pipelineData[k] = this.pokemon.getSprite().pipelineData[k]; }); - gScene.field.add(sprite); + globalScene.field.add(sprite); return sprite; }; @@ -66,9 +66,9 @@ export class QuietFormChangePhase extends BattlePhase { pokemonFormTintSprite.setVisible(false); pokemonFormTintSprite.setTintFill(0xFFFFFF); - gScene.playSound("battle_anims/PRSFX- Transform"); + globalScene.playSound("battle_anims/PRSFX- Transform"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemonTintSprite, alpha: 1, duration: 1000, @@ -79,7 +79,7 @@ export class QuietFormChangePhase extends BattlePhase { pokemonFormTintSprite.setScale(0.01); pokemonFormTintSprite.play(this.pokemon.getBattleSpriteKey()).stop(); pokemonFormTintSprite.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemonTintSprite, delay: 250, scale: 0.01, @@ -87,7 +87,7 @@ export class QuietFormChangePhase extends BattlePhase { duration: 500, onComplete: () => pokemonTintSprite.destroy() }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemonFormTintSprite, delay: 250, scale: this.pokemon.getSpriteScale(), @@ -95,7 +95,7 @@ export class QuietFormChangePhase extends BattlePhase { duration: 500, onComplete: () => { this.pokemon.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemonFormTintSprite, delay: 250, alpha: 0, @@ -103,7 +103,7 @@ export class QuietFormChangePhase extends BattlePhase { duration: 1000, onComplete: () => { pokemonTintSprite.setVisible(false); - gScene.ui.showText(getSpeciesFormChangeMessage(this.pokemon, this.formChange, preName), null, () => this.end(), 1500); + globalScene.ui.showText(getSpeciesFormChangeMessage(this.pokemon, this.formChange, preName), null, () => this.end(), 1500); } }); } @@ -115,16 +115,16 @@ export class QuietFormChangePhase extends BattlePhase { end(): void { this.pokemon.findAndRemoveTags(t => t.tagType === BattlerTagType.AUTOTOMIZED); - if (gScene?.currentBattle.battleSpec === BattleSpec.FINAL_BOSS && this.pokemon instanceof EnemyPokemon) { - gScene.playBgm(); - gScene.unshiftPhase(new PokemonHealPhase(this.pokemon.getBattlerIndex(), this.pokemon.getMaxHp(), null, false, false, false, true)); + if (globalScene?.currentBattle.battleSpec === BattleSpec.FINAL_BOSS && this.pokemon instanceof EnemyPokemon) { + globalScene.playBgm(); + globalScene.unshiftPhase(new PokemonHealPhase(this.pokemon.getBattlerIndex(), this.pokemon.getMaxHp(), null, false, false, false, true)); this.pokemon.findAndRemoveTags(() => true); this.pokemon.bossSegments = 5; this.pokemon.bossSegmentIndex = 4; this.pokemon.initBattleInfo(); this.pokemon.cry(); - const movePhase = gScene.findPhase(p => p instanceof MovePhase && p.pokemon === this.pokemon) as MovePhase; + const movePhase = globalScene.findPhase(p => p instanceof MovePhase && p.pokemon === this.pokemon) as MovePhase; if (movePhase) { movePhase.cancel(); } diff --git a/src/phases/reload-session-phase.ts b/src/phases/reload-session-phase.ts index 4e0528a306c..c2e71465787 100644 --- a/src/phases/reload-session-phase.ts +++ b/src/phases/reload-session-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; import { Mode } from "#app/ui/ui"; import * as Utils from "#app/utils"; @@ -13,12 +13,12 @@ export class ReloadSessionPhase extends Phase { } start(): void { - gScene.ui.setMode(Mode.SESSION_RELOAD); + globalScene.ui.setMode(Mode.SESSION_RELOAD); let delayElapsed = false; let loaded = false; - gScene.time.delayedCall(Utils.fixedInt(1500), () => { + globalScene.time.delayedCall(Utils.fixedInt(1500), () => { if (loaded) { this.end(); } else { @@ -26,9 +26,9 @@ export class ReloadSessionPhase extends Phase { } }); - gScene.gameData.clearLocalData(); + globalScene.gameData.clearLocalData(); - (this.systemDataStr ? gScene.gameData.initSystem(this.systemDataStr) : gScene.gameData.loadSystem()).then(() => { + (this.systemDataStr ? globalScene.gameData.initSystem(this.systemDataStr) : globalScene.gameData.loadSystem()).then(() => { if (delayElapsed) { this.end(); } else { diff --git a/src/phases/return-phase.ts b/src/phases/return-phase.ts index c2a89ec78ba..3539dbfa951 100644 --- a/src/phases/return-phase.ts +++ b/src/phases/return-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { SpeciesFormChangeActiveTrigger } from "#app/data/pokemon-forms"; import { SwitchType } from "#enums/switch-type"; import { SwitchSummonPhase } from "./switch-summon-phase"; @@ -21,8 +21,8 @@ export class ReturnPhase extends SwitchSummonPhase { pokemon.resetTurnData(); pokemon.resetSummonData(); - gScene.updateFieldScale(); + globalScene.updateFieldScale(); - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger); } } diff --git a/src/phases/ribbon-modifier-reward-phase.ts b/src/phases/ribbon-modifier-reward-phase.ts index f59ed6bb962..320e864f095 100644 --- a/src/phases/ribbon-modifier-reward-phase.ts +++ b/src/phases/ribbon-modifier-reward-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import PokemonSpecies from "#app/data/pokemon-species"; import { ModifierTypeFunc } from "#app/modifier/modifier-type"; import { Mode } from "#app/ui/ui"; @@ -17,12 +17,12 @@ export class RibbonModifierRewardPhase extends ModifierRewardPhase { doReward(): Promise { return new Promise(resolve => { const newModifier = this.modifierType.newModifier(); - gScene.addModifier(newModifier).then(() => { - gScene.playSound("level_up_fanfare"); - gScene.ui.setMode(Mode.MESSAGE); - gScene.ui.showText(i18next.t("battle:beatModeFirstTime", { + globalScene.addModifier(newModifier).then(() => { + globalScene.playSound("level_up_fanfare"); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:beatModeFirstTime", { speciesName: this.species.name, - gameMode: gScene.gameMode.getName(), + gameMode: globalScene.gameMode.getName(), newModifier: newModifier?.type.name }), null, () => { resolve(); diff --git a/src/phases/scan-ivs-phase.ts b/src/phases/scan-ivs-phase.ts index 31eb0f38419..d6b6516bb35 100644 --- a/src/phases/scan-ivs-phase.ts +++ b/src/phases/scan-ivs-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { CommonBattleAnim, CommonAnim } from "#app/data/battle-anims"; import { Stat } from "#app/enums/stat"; @@ -29,12 +29,12 @@ export class ScanIvsPhase extends PokemonPhase { let enemyIvs: number[] = []; let statsContainer: Phaser.GameObjects.Sprite[] = []; let statsContainerLabels: Phaser.GameObjects.Sprite[] = []; - const enemyField = gScene.getEnemyField(); - const uiTheme = gScene.uiTheme; // Assuming uiTheme is accessible + const enemyField = globalScene.getEnemyField(); + const uiTheme = globalScene.uiTheme; // Assuming uiTheme is accessible for (let e = 0; e < enemyField.length; e++) { enemyIvs = enemyField[e].ivs; - const currentIvs = gScene.gameData.dexData[enemyField[e].species.getRootSpeciesId()].ivs; // we are using getRootSpeciesId() here because we want to check against the baby form, not the mid form if it exists - const ivsToShow = gScene.ui.getMessageHandler().getTopIvs(enemyIvs, this.shownIvs); + const currentIvs = globalScene.gameData.dexData[enemyField[e].species.getRootSpeciesId()].ivs; // we are using getRootSpeciesId() here because we want to check against the baby form, not the mid form if it exists + const ivsToShow = globalScene.ui.getMessageHandler().getTopIvs(enemyIvs, this.shownIvs); statsContainer = enemyField[e].getBattleInfo().getStatsValueContainer().list as Phaser.GameObjects.Sprite[]; statsContainerLabels = statsContainer.filter(m => m.name.indexOf("icon_stat_label") >= 0); for (let s = 0; s < statsContainerLabels.length; s++) { @@ -48,17 +48,17 @@ export class ScanIvsPhase extends PokemonPhase { } } - if (!gScene.hideIvs) { - gScene.ui.showText(i18next.t("battle:ivScannerUseQuestion", { pokemonName: getPokemonNameWithAffix(pokemon) }), null, () => { - gScene.ui.setMode(Mode.CONFIRM, () => { - gScene.ui.setMode(Mode.MESSAGE); - gScene.ui.clearText(); + if (!globalScene.hideIvs) { + globalScene.ui.showText(i18next.t("battle:ivScannerUseQuestion", { pokemonName: getPokemonNameWithAffix(pokemon) }), null, () => { + globalScene.ui.setMode(Mode.CONFIRM, () => { + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.clearText(); new CommonBattleAnim(CommonAnim.LOCK_ON, pokemon, pokemon).play(false, () => { - gScene.ui.getMessageHandler().promptIvs(pokemon.id, pokemon.ivs, this.shownIvs).then(() => this.end()); + globalScene.ui.getMessageHandler().promptIvs(pokemon.id, pokemon.ivs, this.shownIvs).then(() => this.end()); }); }, () => { - gScene.ui.setMode(Mode.MESSAGE); - gScene.ui.clearText(); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.clearText(); this.end(); }); }); diff --git a/src/phases/select-biome-phase.ts b/src/phases/select-biome-phase.ts index ccc17d94ef6..d338796e7ab 100644 --- a/src/phases/select-biome-phase.ts +++ b/src/phases/select-biome-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { biomeLinks, getBiomeName } from "#app/data/balance/biomes"; import { Biome } from "#app/enums/biome"; import { MoneyInterestModifier, MapModifier } from "#app/modifier/modifier"; @@ -17,51 +17,51 @@ export class SelectBiomePhase extends BattlePhase { start() { super.start(); - const currentBiome = gScene.arena.biomeType; + const currentBiome = globalScene.arena.biomeType; const setNextBiome = (nextBiome: Biome) => { - if (gScene.currentBattle.waveIndex % 10 === 1) { - gScene.applyModifiers(MoneyInterestModifier, true); - gScene.unshiftPhase(new PartyHealPhase(false)); + if (globalScene.currentBattle.waveIndex % 10 === 1) { + globalScene.applyModifiers(MoneyInterestModifier, true); + globalScene.unshiftPhase(new PartyHealPhase(false)); } - gScene.unshiftPhase(new SwitchBiomePhase(nextBiome)); + globalScene.unshiftPhase(new SwitchBiomePhase(nextBiome)); this.end(); }; - if ((gScene.gameMode.isClassic && gScene.gameMode.isWaveFinal(gScene.currentBattle.waveIndex + 9)) - || (gScene.gameMode.isDaily && gScene.gameMode.isWaveFinal(gScene.currentBattle.waveIndex)) - || (gScene.gameMode.hasShortBiomes && !(gScene.currentBattle.waveIndex % 50))) { + if ((globalScene.gameMode.isClassic && globalScene.gameMode.isWaveFinal(globalScene.currentBattle.waveIndex + 9)) + || (globalScene.gameMode.isDaily && globalScene.gameMode.isWaveFinal(globalScene.currentBattle.waveIndex)) + || (globalScene.gameMode.hasShortBiomes && !(globalScene.currentBattle.waveIndex % 50))) { setNextBiome(Biome.END); - } else if (gScene.gameMode.hasRandomBiomes) { + } else if (globalScene.gameMode.hasRandomBiomes) { setNextBiome(this.generateNextBiome()); } else if (Array.isArray(biomeLinks[currentBiome])) { let biomes: Biome[] = []; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { biomes = (biomeLinks[currentBiome] as (Biome | [Biome, integer])[]) .filter(b => !Array.isArray(b) || !Utils.randSeedInt(b[1])) .map(b => !Array.isArray(b) ? b : b[0]); - }, gScene.currentBattle.waveIndex); - if (biomes.length > 1 && gScene.findModifier(m => m instanceof MapModifier)) { + }, globalScene.currentBattle.waveIndex); + if (biomes.length > 1 && globalScene.findModifier(m => m instanceof MapModifier)) { let biomeChoices: Biome[] = []; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { biomeChoices = (!Array.isArray(biomeLinks[currentBiome]) ? [ biomeLinks[currentBiome] as Biome ] : biomeLinks[currentBiome] as (Biome | [Biome, integer])[]) .filter((b, i) => !Array.isArray(b) || !Utils.randSeedInt(b[1])) .map(b => Array.isArray(b) ? b[0] : b); - }, gScene.currentBattle.waveIndex); + }, globalScene.currentBattle.waveIndex); const biomeSelectItems = biomeChoices.map(b => { const ret: OptionSelectItem = { label: getBiomeName(b), handler: () => { - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.MESSAGE); setNextBiome(b); return true; } }; return ret; }); - gScene.ui.setMode(Mode.OPTION_SELECT, { + globalScene.ui.setMode(Mode.OPTION_SELECT, { options: biomeSelectItems, delay: 1000 }); @@ -76,9 +76,9 @@ export class SelectBiomePhase extends BattlePhase { } generateNextBiome(): Biome { - if (!(gScene.currentBattle.waveIndex % 50)) { + if (!(globalScene.currentBattle.waveIndex % 50)) { return Biome.END; } - return gScene.generateRandomBiome(gScene.currentBattle.waveIndex); + return globalScene.generateRandomBiome(globalScene.currentBattle.waveIndex); } } diff --git a/src/phases/select-challenge-phase.ts b/src/phases/select-challenge-phase.ts index 78e6dca9c76..373ed1c2f46 100644 --- a/src/phases/select-challenge-phase.ts +++ b/src/phases/select-challenge-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; import { Mode } from "#app/ui/ui"; @@ -10,8 +10,8 @@ export class SelectChallengePhase extends Phase { start() { super.start(); - gScene.playBgm("menu"); + globalScene.playBgm("menu"); - gScene.ui.setMode(Mode.CHALLENGE_SELECT); + globalScene.ui.setMode(Mode.CHALLENGE_SELECT); } } diff --git a/src/phases/select-gender-phase.ts b/src/phases/select-gender-phase.ts index 87e2bc344c0..bc0fd1da097 100644 --- a/src/phases/select-gender-phase.ts +++ b/src/phases/select-gender-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { PlayerGender } from "#app/enums/player-gender"; import { Phase } from "#app/phase"; import { SettingKeys } from "#app/system/settings/settings"; @@ -13,24 +13,24 @@ export class SelectGenderPhase extends Phase { start(): void { super.start(); - gScene.ui.showText(i18next.t("menu:boyOrGirl"), null, () => { - gScene.ui.setMode(Mode.OPTION_SELECT, { + globalScene.ui.showText(i18next.t("menu:boyOrGirl"), null, () => { + globalScene.ui.setMode(Mode.OPTION_SELECT, { options: [ { label: i18next.t("settings:boy"), handler: () => { - gScene.gameData.gender = PlayerGender.MALE; - gScene.gameData.saveSetting(SettingKeys.Player_Gender, 0); - gScene.gameData.saveSystem().then(() => this.end()); + globalScene.gameData.gender = PlayerGender.MALE; + globalScene.gameData.saveSetting(SettingKeys.Player_Gender, 0); + globalScene.gameData.saveSystem().then(() => this.end()); return true; } }, { label: i18next.t("settings:girl"), handler: () => { - gScene.gameData.gender = PlayerGender.FEMALE; - gScene.gameData.saveSetting(SettingKeys.Player_Gender, 1); - gScene.gameData.saveSystem().then(() => this.end()); + globalScene.gameData.gender = PlayerGender.FEMALE; + globalScene.gameData.saveSetting(SettingKeys.Player_Gender, 1); + globalScene.gameData.saveSystem().then(() => this.end()); return true; } } @@ -40,7 +40,7 @@ export class SelectGenderPhase extends Phase { } end(): void { - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.MESSAGE); super.end(); } } diff --git a/src/phases/select-modifier-phase.ts b/src/phases/select-modifier-phase.ts index ce1da4688c9..c14fe427f64 100644 --- a/src/phases/select-modifier-phase.ts +++ b/src/phases/select-modifier-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { ModifierTier } from "#app/modifier/modifier-tier"; import { regenerateModifierPoolThresholds, ModifierTypeOption, ModifierType, getPlayerShopModifierTypeOptionsForWave, PokemonModifierType, FusePokemonModifierType, PokemonMoveModifierType, TmModifierType, RememberMoveModifierType, PokemonPpRestoreModifierType, PokemonPpUpModifierType, ModifierPoolType, getPlayerModifierTypeOptions } from "#app/modifier/modifier-type"; import { ExtraModifierModifier, HealShopCostModifier, Modifier, PokemonHeldItemModifier, TempExtraModifierModifier } from "#app/modifier/modifier"; @@ -35,17 +35,17 @@ export class SelectModifierPhase extends BattlePhase { if (!this.rerollCount && !this.isCopy) { this.updateSeed(); } else if (this.rerollCount) { - gScene.reroll = false; + globalScene.reroll = false; } - const party = gScene.getParty(); + const party = globalScene.getParty(); if (!this.isCopy) { regenerateModifierPoolThresholds(party, this.getPoolType(), this.rerollCount); } const modifierCount = new Utils.IntegerHolder(3); if (this.isPlayer()) { - gScene.applyModifiers(ExtraModifierModifier, true, modifierCount); - gScene.applyModifiers(TempExtraModifierModifier, true, modifierCount); + globalScene.applyModifiers(ExtraModifierModifier, true, modifierCount); + globalScene.applyModifiers(TempExtraModifierModifier, true, modifierCount); } // If custom modifiers are specified, overrides default item count @@ -65,64 +65,64 @@ export class SelectModifierPhase extends BattlePhase { const modifierSelectCallback = (rowCursor: integer, cursor: integer) => { if (rowCursor < 0 || cursor < 0) { - gScene.ui.showText(i18next.t("battle:skipItemQuestion"), null, () => { - gScene.ui.setOverlayMode(Mode.CONFIRM, () => { - gScene.ui.revertMode(); - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:skipItemQuestion"), null, () => { + globalScene.ui.setOverlayMode(Mode.CONFIRM, () => { + globalScene.ui.revertMode(); + globalScene.ui.setMode(Mode.MESSAGE); super.end(); - }, () => gScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(gScene.lockModifierTiers))); + }, () => globalScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(globalScene.lockModifierTiers))); }); return false; } let modifierType: ModifierType; let cost: integer; - const rerollCost = this.getRerollCost(gScene.lockModifierTiers); + const rerollCost = this.getRerollCost(globalScene.lockModifierTiers); switch (rowCursor) { case 0: switch (cursor) { case 0: - if (rerollCost < 0 || gScene.money < rerollCost) { - gScene.ui.playError(); + if (rerollCost < 0 || globalScene.money < rerollCost) { + globalScene.ui.playError(); return false; } else { - gScene.reroll = true; - gScene.unshiftPhase(new SelectModifierPhase(this.rerollCount + 1, this.typeOptions.map(o => o.type?.tier).filter(t => t !== undefined) as ModifierTier[])); - gScene.ui.clearText(); - gScene.ui.setMode(Mode.MESSAGE).then(() => super.end()); + globalScene.reroll = true; + globalScene.unshiftPhase(new SelectModifierPhase(this.rerollCount + 1, this.typeOptions.map(o => o.type?.tier).filter(t => t !== undefined) as ModifierTier[])); + globalScene.ui.clearText(); + globalScene.ui.setMode(Mode.MESSAGE).then(() => super.end()); if (!Overrides.WAIVE_ROLL_FEE_OVERRIDE) { - gScene.money -= rerollCost; - gScene.updateMoneyText(); - gScene.animateMoneyChanged(false); + globalScene.money -= rerollCost; + globalScene.updateMoneyText(); + globalScene.animateMoneyChanged(false); } - gScene.playSound("se/buy"); + globalScene.playSound("se/buy"); } break; case 1: - gScene.ui.setModeWithoutClear(Mode.PARTY, PartyUiMode.MODIFIER_TRANSFER, -1, (fromSlotIndex: integer, itemIndex: integer, itemQuantity: integer, toSlotIndex: integer) => { + globalScene.ui.setModeWithoutClear(Mode.PARTY, PartyUiMode.MODIFIER_TRANSFER, -1, (fromSlotIndex: integer, itemIndex: integer, itemQuantity: integer, toSlotIndex: integer) => { if (toSlotIndex !== undefined && fromSlotIndex < 6 && toSlotIndex < 6 && fromSlotIndex !== toSlotIndex && itemIndex > -1) { - const itemModifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const itemModifiers = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.isTransferable && m.pokemonId === party[fromSlotIndex].id) as PokemonHeldItemModifier[]; const itemModifier = itemModifiers[itemIndex]; - gScene.tryTransferHeldItemModifier(itemModifier, party[toSlotIndex], true, itemQuantity); + globalScene.tryTransferHeldItemModifier(itemModifier, party[toSlotIndex], true, itemQuantity); } else { - gScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(gScene.lockModifierTiers)); + globalScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(globalScene.lockModifierTiers)); } }, PartyUiHandler.FilterItemMaxStacks); break; case 2: - gScene.ui.setModeWithoutClear(Mode.PARTY, PartyUiMode.CHECK, -1, () => { - gScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(gScene.lockModifierTiers)); + globalScene.ui.setModeWithoutClear(Mode.PARTY, PartyUiMode.CHECK, -1, () => { + globalScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(globalScene.lockModifierTiers)); }); break; case 3: if (rerollCost < 0) { // Reroll lock button is also disabled when reroll is disabled - gScene.ui.playError(); + globalScene.ui.playError(); return false; } - gScene.lockModifierTiers = !gScene.lockModifierTiers; - const uiHandler = gScene.ui.getHandler() as ModifierSelectUiHandler; - uiHandler.setRerollCost(this.getRerollCost(gScene.lockModifierTiers)); + globalScene.lockModifierTiers = !globalScene.lockModifierTiers; + const uiHandler = globalScene.ui.getHandler() as ModifierSelectUiHandler; + uiHandler.setRerollCost(this.getRerollCost(globalScene.lockModifierTiers)); uiHandler.updateLockRaritiesText(); uiHandler.updateRerollCostText(); return false; @@ -130,8 +130,8 @@ export class SelectModifierPhase extends BattlePhase { return true; case 1: if (this.typeOptions.length === 0) { - gScene.ui.clearText(); - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.clearText(); + globalScene.ui.setMode(Mode.MESSAGE); super.end(); return true; } @@ -140,51 +140,51 @@ export class SelectModifierPhase extends BattlePhase { } break; default: - const shopOptions = getPlayerShopModifierTypeOptionsForWave(gScene.currentBattle.waveIndex, gScene.getWaveMoneyAmount(1)); + const shopOptions = getPlayerShopModifierTypeOptionsForWave(globalScene.currentBattle.waveIndex, globalScene.getWaveMoneyAmount(1)); const shopOption = shopOptions[rowCursor > 2 || shopOptions.length <= SHOP_OPTIONS_ROW_LIMIT ? cursor : cursor + SHOP_OPTIONS_ROW_LIMIT]; if (shopOption.type) { modifierType = shopOption.type; } // Apply Black Sludge to healing item cost const healingItemCost = new NumberHolder(shopOption.cost); - gScene.applyModifier(HealShopCostModifier, true, healingItemCost); + globalScene.applyModifier(HealShopCostModifier, true, healingItemCost); cost = healingItemCost.value; break; } - if (cost! && (gScene.money < cost) && !Overrides.WAIVE_ROLL_FEE_OVERRIDE) { // TODO: is the bang on cost correct? - gScene.ui.playError(); + if (cost! && (globalScene.money < cost) && !Overrides.WAIVE_ROLL_FEE_OVERRIDE) { // TODO: is the bang on cost correct? + globalScene.ui.playError(); return false; } const applyModifier = (modifier: Modifier, playSound: boolean = false) => { - const result = gScene.addModifier(modifier, false, playSound, undefined, undefined, cost); + const result = globalScene.addModifier(modifier, false, playSound, undefined, undefined, cost); // Queue a copy of this phase when applying a TM or Memory Mushroom. // If the player selects either of these, then escapes out of consuming them, // they are returned to a shop in the same state. if (modifier.type instanceof RememberMoveModifierType || modifier.type instanceof TmModifierType) { - gScene.unshiftPhase(this.copy()); + globalScene.unshiftPhase(this.copy()); } if (cost && !(modifier.type instanceof RememberMoveModifierType)) { result.then(success => { if (success) { if (!Overrides.WAIVE_ROLL_FEE_OVERRIDE) { - gScene.money -= cost; - gScene.updateMoneyText(); - gScene.animateMoneyChanged(false); + globalScene.money -= cost; + globalScene.updateMoneyText(); + globalScene.animateMoneyChanged(false); } - gScene.playSound("se/buy"); - (gScene.ui.getHandler() as ModifierSelectUiHandler).updateCostText(); + globalScene.playSound("se/buy"); + (globalScene.ui.getHandler() as ModifierSelectUiHandler).updateCostText(); } else { - gScene.ui.playError(); + globalScene.ui.playError(); } }); } else { const doEnd = () => { - gScene.ui.clearText(); - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.clearText(); + globalScene.ui.setMode(Mode.MESSAGE); super.end(); }; if (result instanceof Promise) { @@ -197,14 +197,14 @@ export class SelectModifierPhase extends BattlePhase { if (modifierType! instanceof PokemonModifierType) { //TODO: is the bang correct? if (modifierType instanceof FusePokemonModifierType) { - gScene.ui.setModeWithoutClear(Mode.PARTY, PartyUiMode.SPLICE, -1, (fromSlotIndex: integer, spliceSlotIndex: integer) => { + globalScene.ui.setModeWithoutClear(Mode.PARTY, PartyUiMode.SPLICE, -1, (fromSlotIndex: integer, spliceSlotIndex: integer) => { if (spliceSlotIndex !== undefined && fromSlotIndex < 6 && spliceSlotIndex < 6 && fromSlotIndex !== spliceSlotIndex) { - gScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer()).then(() => { + globalScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer()).then(() => { const modifier = modifierType.newModifier(party[fromSlotIndex], party[spliceSlotIndex])!; //TODO: is the bang correct? applyModifier(modifier, true); }); } else { - gScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(gScene.lockModifierTiers)); + globalScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(globalScene.lockModifierTiers)); } }, modifierType.selectFilter); } else { @@ -220,9 +220,9 @@ export class SelectModifierPhase extends BattlePhase { const tmMoveId = isTmModifier ? (modifierType as TmModifierType).moveId : undefined; - gScene.ui.setModeWithoutClear(Mode.PARTY, partyUiMode, -1, (slotIndex: integer, option: PartyOption) => { + globalScene.ui.setModeWithoutClear(Mode.PARTY, partyUiMode, -1, (slotIndex: integer, option: PartyOption) => { if (slotIndex < 6) { - gScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer()).then(() => { + globalScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer()).then(() => { const modifier = !isMoveModifier ? !isRememberMoveModifier ? modifierType.newModifier(party[slotIndex]) @@ -231,7 +231,7 @@ export class SelectModifierPhase extends BattlePhase { applyModifier(modifier!, true); // TODO: is the bang correct? }); } else { - gScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(gScene.lockModifierTiers)); + globalScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(globalScene.lockModifierTiers)); } }, pokemonModifierType.selectFilter, modifierType instanceof PokemonMoveModifierType ? (modifierType as PokemonMoveModifierType).moveSelectFilter : undefined, tmMoveId, isPpRestoreModifier); } @@ -241,11 +241,11 @@ export class SelectModifierPhase extends BattlePhase { return !cost!;// TODO: is the bang correct? }; - gScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(gScene.lockModifierTiers)); + globalScene.ui.setMode(Mode.MODIFIER_SELECT, this.isPlayer(), this.typeOptions, modifierSelectCallback, this.getRerollCost(globalScene.lockModifierTiers)); } updateSeed(): void { - gScene.resetSeed(); + globalScene.resetSeed(); } isPlayer(): boolean { @@ -276,11 +276,11 @@ export class SelectModifierPhase extends BattlePhase { multiplier = this.customModifierSettings.rerollMultiplier; } - const baseMultiplier = Math.min(Math.ceil(gScene.currentBattle.waveIndex / 10) * baseValue * (2 ** this.rerollCount) * multiplier, Number.MAX_SAFE_INTEGER); + const baseMultiplier = Math.min(Math.ceil(globalScene.currentBattle.waveIndex / 10) * baseValue * (2 ** this.rerollCount) * multiplier, Number.MAX_SAFE_INTEGER); // Apply Black Sludge to reroll cost const modifiedRerollCost = new NumberHolder(baseMultiplier); - gScene.applyModifier(HealShopCostModifier, true, modifiedRerollCost); + globalScene.applyModifier(HealShopCostModifier, true, modifiedRerollCost); return modifiedRerollCost.value; } @@ -289,7 +289,7 @@ export class SelectModifierPhase extends BattlePhase { } getModifierTypeOptions(modifierCount: integer): ModifierTypeOption[] { - return getPlayerModifierTypeOptions(modifierCount, gScene.getParty(), gScene.lockModifierTiers ? this.modifierTiers : undefined, this.customModifierSettings); + return getPlayerModifierTypeOptions(modifierCount, globalScene.getParty(), globalScene.lockModifierTiers ? this.modifierTiers : undefined, this.customModifierSettings); } copy(): SelectModifierPhase { @@ -302,6 +302,6 @@ export class SelectModifierPhase extends BattlePhase { } addModifier(modifier: Modifier): Promise { - return gScene.addModifier(modifier, false, true); + return globalScene.addModifier(modifier, false, true); } } diff --git a/src/phases/select-starter-phase.ts b/src/phases/select-starter-phase.ts index 3761ee12cc9..233c2ced0a7 100644 --- a/src/phases/select-starter-phase.ts +++ b/src/phases/select-starter-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { applyChallenges, ChallengeType } from "#app/data/challenge"; import { Gender } from "#app/data/gender"; import { SpeciesFormChangeMoveLearnedTrigger } from "#app/data/pokemon-forms"; @@ -23,17 +23,17 @@ export class SelectStarterPhase extends Phase { start() { super.start(); - gScene.playBgm("menu"); + globalScene.playBgm("menu"); - gScene.ui.setMode(Mode.STARTER_SELECT, (starters: Starter[]) => { - gScene.ui.clearText(); - gScene.ui.setMode(Mode.SAVE_SLOT, SaveSlotUiMode.SAVE, (slotId: integer) => { + globalScene.ui.setMode(Mode.STARTER_SELECT, (starters: Starter[]) => { + globalScene.ui.clearText(); + globalScene.ui.setMode(Mode.SAVE_SLOT, SaveSlotUiMode.SAVE, (slotId: integer) => { if (slotId === -1) { - gScene.clearPhaseQueue(); - gScene.pushPhase(new TitlePhase()); + globalScene.clearPhaseQueue(); + globalScene.pushPhase(new TitlePhase()); return this.end(); } - gScene.sessionSlotId = slotId; + globalScene.sessionSlotId = slotId; this.initBattle(starters); }); }); @@ -44,13 +44,13 @@ export class SelectStarterPhase extends Phase { * @param starters {@linkcode Pokemon} with which to start the first battle */ initBattle(starters: Starter[]) { - const party = gScene.getParty(); + const party = globalScene.getParty(); const loadPokemonAssets: Promise[] = []; starters.forEach((starter: Starter, i: integer) => { if (!i && Overrides.STARTER_SPECIES_OVERRIDE) { starter.species = getPokemonSpecies(Overrides.STARTER_SPECIES_OVERRIDE as Species); } - const starterProps = gScene.gameData.getSpeciesDexAttrProps(starter.species, starter.dexAttr); + const starterProps = globalScene.gameData.getSpeciesDexAttrProps(starter.species, starter.dexAttr); let starterFormIndex = Math.min(starterProps.formIndex, Math.max(starter.species.forms.length - 1, 0)); if ( starter.species.speciesId in Overrides.STARTER_FORM_OVERRIDES && @@ -65,13 +65,13 @@ export class SelectStarterPhase extends Phase { if (Overrides.GENDER_OVERRIDE !== null) { starterGender = Overrides.GENDER_OVERRIDE; } - const starterIvs = gScene.gameData.dexData[starter.species.speciesId].ivs.slice(0); - const starterPokemon = gScene.addPlayerPokemon(starter.species, gScene.gameMode.getStartingLevel(), starter.abilityIndex, starterFormIndex, starterGender, starterProps.shiny, starterProps.variant, starterIvs, starter.nature); + const starterIvs = globalScene.gameData.dexData[starter.species.speciesId].ivs.slice(0); + const starterPokemon = globalScene.addPlayerPokemon(starter.species, globalScene.gameMode.getStartingLevel(), starter.abilityIndex, starterFormIndex, starterGender, starterProps.shiny, starterProps.variant, starterIvs, starter.nature); starter.moveset && starterPokemon.tryPopulateMoveset(starter.moveset); if (starter.passive) { starterPokemon.passive = true; } - starterPokemon.luck = gScene.gameData.getDexAttrLuck(gScene.gameData.dexData[starter.species.speciesId].caughtAttr); + starterPokemon.luck = globalScene.gameData.getDexAttrLuck(globalScene.gameData.dexData[starter.species.speciesId].caughtAttr); if (starter.pokerus) { starterPokemon.pokerus = true; } @@ -80,31 +80,31 @@ export class SelectStarterPhase extends Phase { starterPokemon.nickname = starter.nickname; } - if (gScene.gameMode.isSplicedOnly || Overrides.STARTER_FUSION_OVERRIDE) { + if (globalScene.gameMode.isSplicedOnly || Overrides.STARTER_FUSION_OVERRIDE) { starterPokemon.generateFusionSpecies(true); } starterPokemon.setVisible(false); - applyChallenges(gScene.gameMode, ChallengeType.STARTER_MODIFY, starterPokemon); + applyChallenges(globalScene.gameMode, ChallengeType.STARTER_MODIFY, starterPokemon); party.push(starterPokemon); loadPokemonAssets.push(starterPokemon.loadAssets()); }); overrideModifiers(); overrideHeldItems(party[0]); Promise.all(loadPokemonAssets).then(() => { - SoundFade.fadeOut(gScene, gScene.sound.get("menu"), 500, true); - gScene.time.delayedCall(500, () => gScene.playBgm()); - if (gScene.gameMode.isClassic) { - gScene.gameData.gameStats.classicSessionsPlayed++; + SoundFade.fadeOut(globalScene, globalScene.sound.get("menu"), 500, true); + globalScene.time.delayedCall(500, () => globalScene.playBgm()); + if (globalScene.gameMode.isClassic) { + globalScene.gameData.gameStats.classicSessionsPlayed++; } else { - gScene.gameData.gameStats.endlessSessionsPlayed++; + globalScene.gameData.gameStats.endlessSessionsPlayed++; } - gScene.newBattle(); - gScene.arena.init(); - gScene.sessionPlayTime = 0; - gScene.lastSavePlayTime = 0; + globalScene.newBattle(); + globalScene.arena.init(); + globalScene.sessionPlayTime = 0; + globalScene.lastSavePlayTime = 0; // Ensures Keldeo (or any future Pokemon that have this type of form change) starts in the correct form - gScene.getParty().forEach((p: PlayerPokemon) => { - gScene.triggerPokemonFormChange(p, SpeciesFormChangeMoveLearnedTrigger); + globalScene.getParty().forEach((p: PlayerPokemon) => { + globalScene.triggerPokemonFormChange(p, SpeciesFormChangeMoveLearnedTrigger); }); this.end(); }); diff --git a/src/phases/select-target-phase.ts b/src/phases/select-target-phase.ts index da424b36d6d..5bc81f54cb9 100644 --- a/src/phases/select-target-phase.ts +++ b/src/phases/select-target-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { Command } from "#app/ui/command-ui-handler"; import { Mode } from "#app/ui/ui"; @@ -15,26 +15,26 @@ export class SelectTargetPhase extends PokemonPhase { start() { super.start(); - const turnCommand = gScene.currentBattle.turnCommands[this.fieldIndex]; + const turnCommand = globalScene.currentBattle.turnCommands[this.fieldIndex]; const move = turnCommand?.move?.move; - gScene.ui.setMode(Mode.TARGET_SELECT, this.fieldIndex, move, (targets: BattlerIndex[]) => { - gScene.ui.setMode(Mode.MESSAGE); - const fieldSide = gScene.getField(); + globalScene.ui.setMode(Mode.TARGET_SELECT, this.fieldIndex, move, (targets: BattlerIndex[]) => { + globalScene.ui.setMode(Mode.MESSAGE); + const fieldSide = globalScene.getField(); const user = fieldSide[this.fieldIndex]; const moveObject = allMoves[move!]; if (moveObject && user.isMoveTargetRestricted(moveObject.id, user, fieldSide[targets[0]])) { const errorMessage = user.getRestrictingTag(move!, user, fieldSide[targets[0]])!.selectionDeniedText(user, moveObject.id); - gScene.queueMessage(i18next.t(errorMessage, { moveName: moveObject.name }), 0, true); + globalScene.queueMessage(i18next.t(errorMessage, { moveName: moveObject.name }), 0, true); targets = []; } if (targets.length < 1) { - gScene.currentBattle.turnCommands[this.fieldIndex] = null; - gScene.unshiftPhase(new CommandPhase(this.fieldIndex)); + globalScene.currentBattle.turnCommands[this.fieldIndex] = null; + globalScene.unshiftPhase(new CommandPhase(this.fieldIndex)); } else { turnCommand!.targets = targets; //TODO: is the bang correct here? } if (turnCommand?.command === Command.BALL && this.fieldIndex) { - gScene.currentBattle.turnCommands[this.fieldIndex - 1]!.skip = true; //TODO: is the bang correct here? + globalScene.currentBattle.turnCommands[this.fieldIndex - 1]!.skip = true; //TODO: is the bang correct here? } this.end(); }); diff --git a/src/phases/shiny-sparkle-phase.ts b/src/phases/shiny-sparkle-phase.ts index d47d40a0d17..9d9bdf50d1f 100644 --- a/src/phases/shiny-sparkle-phase.ts +++ b/src/phases/shiny-sparkle-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { PokemonPhase } from "./pokemon-phase"; @@ -11,6 +11,6 @@ export class ShinySparklePhase extends PokemonPhase { super.start(); this.getPokemon().sparkle(); - gScene.time.delayedCall(1000, () => this.end()); + globalScene.time.delayedCall(1000, () => this.end()); } } diff --git a/src/phases/show-ability-phase.ts b/src/phases/show-ability-phase.ts index 58e1e8e6d4f..1db8028fe75 100644 --- a/src/phases/show-ability-phase.ts +++ b/src/phases/show-ability-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { PokemonPhase } from "./pokemon-phase"; @@ -17,7 +17,7 @@ export class ShowAbilityPhase extends PokemonPhase { const pokemon = this.getPokemon(); if (pokemon) { - gScene.abilityBar.showAbility(pokemon, this.passive); + globalScene.abilityBar.showAbility(pokemon, this.passive); if (pokemon?.battleData) { pokemon.battleData.abilityRevealed = true; diff --git a/src/phases/show-party-exp-bar-phase.ts b/src/phases/show-party-exp-bar-phase.ts index f6b32215b8f..f7e2b754009 100644 --- a/src/phases/show-party-exp-bar-phase.ts +++ b/src/phases/show-party-exp-bar-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { ExpGainsSpeed } from "#app/enums/exp-gains-speed"; import { ExpNotification } from "#app/enums/exp-notification"; import { ExpBoosterModifier } from "#app/modifier/modifier"; @@ -21,33 +21,33 @@ export class ShowPartyExpBarPhase extends PlayerPartyMemberPokemonPhase { const pokemon = this.getPokemon(); const exp = new Utils.NumberHolder(this.expValue); - gScene.applyModifiers(ExpBoosterModifier, true, exp); + globalScene.applyModifiers(ExpBoosterModifier, true, exp); exp.value = Math.floor(exp.value); const lastLevel = pokemon.level; pokemon.addExp(exp.value); const newLevel = pokemon.level; if (newLevel > lastLevel) { - gScene.unshiftPhase(new LevelUpPhase(this.partyMemberIndex, lastLevel, newLevel)); + globalScene.unshiftPhase(new LevelUpPhase(this.partyMemberIndex, lastLevel, newLevel)); } - gScene.unshiftPhase(new HidePartyExpBarPhase()); + globalScene.unshiftPhase(new HidePartyExpBarPhase()); pokemon.updateInfo(); - if (gScene.expParty === ExpNotification.SKIP) { + if (globalScene.expParty === ExpNotification.SKIP) { this.end(); - } else if (gScene.expParty === ExpNotification.ONLY_LEVEL_UP) { + } else if (globalScene.expParty === ExpNotification.ONLY_LEVEL_UP) { if (newLevel > lastLevel) { // this means if we level up // instead of displaying the exp gain in the small frame, we display the new level // we use the same method for mode 0 & 1, by giving a parameter saying to display the exp or the level - gScene.partyExpBar.showPokemonExp(pokemon, exp.value, gScene.expParty === ExpNotification.ONLY_LEVEL_UP, newLevel).then(() => { - setTimeout(() => this.end(), 800 / Math.pow(2, gScene.expGainsSpeed)); + globalScene.partyExpBar.showPokemonExp(pokemon, exp.value, globalScene.expParty === ExpNotification.ONLY_LEVEL_UP, newLevel).then(() => { + setTimeout(() => this.end(), 800 / Math.pow(2, globalScene.expGainsSpeed)); }); } else { this.end(); } - } else if (gScene.expGainsSpeed < ExpGainsSpeed.SKIP) { - gScene.partyExpBar.showPokemonExp(pokemon, exp.value, false, newLevel).then(() => { - setTimeout(() => this.end(), 500 / Math.pow(2, gScene.expGainsSpeed)); + } else if (globalScene.expGainsSpeed < ExpGainsSpeed.SKIP) { + globalScene.partyExpBar.showPokemonExp(pokemon, exp.value, false, newLevel).then(() => { + setTimeout(() => this.end(), 500 / Math.pow(2, globalScene.expGainsSpeed)); }); } else { this.end(); diff --git a/src/phases/show-trainer-phase.ts b/src/phases/show-trainer-phase.ts index 394058e392a..5bc05d08d63 100644 --- a/src/phases/show-trainer-phase.ts +++ b/src/phases/show-trainer-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { PlayerGender } from "#app/enums/player-gender"; import { BattlePhase } from "./battle-phase"; @@ -10,12 +10,12 @@ export class ShowTrainerPhase extends BattlePhase { start() { super.start(); - gScene.trainer.setVisible(true); + globalScene.trainer.setVisible(true); - gScene.trainer.setTexture(`trainer_${gScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`); + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back`); - gScene.tweens.add({ - targets: gScene.trainer, + globalScene.tweens.add({ + targets: globalScene.trainer, x: 106, duration: 1000, onComplete: () => this.end() diff --git a/src/phases/stat-stage-change-phase.ts b/src/phases/stat-stage-change-phase.ts index bc8055d9382..6e61b697ca3 100644 --- a/src/phases/stat-stage-change-phase.ts +++ b/src/phases/stat-stage-change-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattlerIndex } from "#app/battle"; import { applyAbAttrs, applyPostStatStageChangeAbAttrs, applyPreStatStageChangeAbAttrs, PostStatStageChangeAbAttr, ProtectStatAbAttr, StatStageChangeCopyAbAttr, StatStageChangeMultiplierAbAttr } from "#app/data/ability"; import { ArenaTagSide, MistTag } from "#app/data/arena-tag"; @@ -41,7 +41,7 @@ export class StatStageChangePhase extends PokemonPhase { if (this.stats.length > 1) { for (let i = 0; i < this.stats.length; i++) { const stat = [ this.stats[i] ]; - gScene.unshiftPhase(new StatStageChangePhase(this.battlerIndex, this.selfTarget, stat, this.stages, this.showMessage, this.ignoreAbilities, this.canBeCopied, this.onChange)); + globalScene.unshiftPhase(new StatStageChangePhase(this.battlerIndex, this.selfTarget, stat, this.stages, this.showMessage, this.ignoreAbilities, this.canBeCopied, this.onChange)); } return this.end(); } @@ -65,7 +65,7 @@ export class StatStageChangePhase extends PokemonPhase { if (!this.selfTarget && stages.value < 0) { // TODO: add a reference to the source of the stat change to fix Infiltrator interaction - gScene.arena.applyTagsForSide(MistTag, pokemon.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY, false, null, cancelled); + globalScene.arena.applyTagsForSide(MistTag, pokemon.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY, false, null, cancelled); } if (!cancelled.value && !this.selfTarget && stages.value < 0) { @@ -88,7 +88,7 @@ export class StatStageChangePhase extends PokemonPhase { if (this.showMessage) { const messages = this.getStatStageChangeMessages(filteredStats, stages.value, relLevels); for (const message of messages) { - gScene.queueMessage(message); + globalScene.queueMessage(message); } } @@ -119,17 +119,17 @@ export class StatStageChangePhase extends PokemonPhase { applyPostStatStageChangeAbAttrs(PostStatStageChangeAbAttr, pokemon, filteredStats, this.stages, this.selfTarget); // Look for any other stat change phases; if this is the last one, do White Herb check - const existingPhase = gScene.findPhase(p => p instanceof StatStageChangePhase && p.battlerIndex === this.battlerIndex); + const existingPhase = globalScene.findPhase(p => p instanceof StatStageChangePhase && p.battlerIndex === this.battlerIndex); if (!(existingPhase instanceof StatStageChangePhase)) { // Apply White Herb if needed - const whiteHerb = gScene.applyModifier(ResetNegativeStatStageModifier, this.player, pokemon) as ResetNegativeStatStageModifier; + const whiteHerb = globalScene.applyModifier(ResetNegativeStatStageModifier, this.player, pokemon) as ResetNegativeStatStageModifier; // If the White Herb was applied, consume it if (whiteHerb) { whiteHerb.stackCount--; if (whiteHerb.stackCount <= 0) { - gScene.removeModifier(whiteHerb); + globalScene.removeModifier(whiteHerb); } - gScene.updateModifiers(this.player); + globalScene.updateModifiers(this.player); } } @@ -138,34 +138,34 @@ export class StatStageChangePhase extends PokemonPhase { handleTutorial(Tutorial.Stat_Change).then(() => super.end()); }; - if (relLevels.filter(l => l).length && gScene.moveAnimations) { + if (relLevels.filter(l => l).length && globalScene.moveAnimations) { pokemon.enableMask(); const pokemonMaskSprite = pokemon.maskSprite; - const tileX = (this.player ? 106 : 236) * pokemon.getSpriteScale() * gScene.field.scale; - const tileY = ((this.player ? 148 : 84) + (stages.value >= 1 ? 160 : 0)) * pokemon.getSpriteScale() * gScene.field.scale; - const tileWidth = 156 * gScene.field.scale * pokemon.getSpriteScale(); - const tileHeight = 316 * gScene.field.scale * pokemon.getSpriteScale(); + const tileX = (this.player ? 106 : 236) * pokemon.getSpriteScale() * globalScene.field.scale; + const tileY = ((this.player ? 148 : 84) + (stages.value >= 1 ? 160 : 0)) * pokemon.getSpriteScale() * globalScene.field.scale; + const tileWidth = 156 * globalScene.field.scale * pokemon.getSpriteScale(); + const tileHeight = 316 * globalScene.field.scale * pokemon.getSpriteScale(); // On increase, show the red sprite located at ATK // On decrease, show the blue sprite located at SPD const spriteColor = stages.value >= 1 ? Stat[Stat.ATK].toLowerCase() : Stat[Stat.SPD].toLowerCase(); - const statSprite = gScene.add.tileSprite(tileX, tileY, tileWidth, tileHeight, "battle_stats", spriteColor); - statSprite.setPipeline(gScene.fieldSpritePipeline); + const statSprite = globalScene.add.tileSprite(tileX, tileY, tileWidth, tileHeight, "battle_stats", spriteColor); + statSprite.setPipeline(globalScene.fieldSpritePipeline); statSprite.setAlpha(0); statSprite.setScale(6); statSprite.setOrigin(0.5, 1); - gScene.playSound(`se/stat_${stages.value >= 1 ? "up" : "down"}`); + globalScene.playSound(`se/stat_${stages.value >= 1 ? "up" : "down"}`); - statSprite.setMask(new Phaser.Display.Masks.BitmapMask(gScene, pokemonMaskSprite ?? undefined)); + statSprite.setMask(new Phaser.Display.Masks.BitmapMask(globalScene, pokemonMaskSprite ?? undefined)); - gScene.tweens.add({ + globalScene.tweens.add({ targets: statSprite, duration: 250, alpha: 0.8375, onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: statSprite, delay: 1000, duration: 250, @@ -174,13 +174,13 @@ export class StatStageChangePhase extends PokemonPhase { } }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: statSprite, duration: 1500, y: `${stages.value >= 1 ? "-" : "+"}=${160 * 6}` }); - gScene.time.delayedCall(1750, () => { + globalScene.time.delayedCall(1750, () => { pokemon.disableMask(); end(); }); @@ -194,21 +194,21 @@ export class StatStageChangePhase extends PokemonPhase { const isAccEva = accEva.some(s => this.stats.includes(s)); let existingPhase: StatStageChangePhase; if (this.stats.length === 1) { - while ((existingPhase = (gScene.findPhase(p => p instanceof StatStageChangePhase && p.battlerIndex === this.battlerIndex && p.stats.length === 1 + while ((existingPhase = (globalScene.findPhase(p => p instanceof StatStageChangePhase && p.battlerIndex === this.battlerIndex && p.stats.length === 1 && (p.stats[0] === this.stats[0]) && p.selfTarget === this.selfTarget && p.showMessage === this.showMessage && p.ignoreAbilities === this.ignoreAbilities) as StatStageChangePhase))) { this.stages += existingPhase.stages; - if (!gScene.tryRemovePhase(p => p === existingPhase)) { + if (!globalScene.tryRemovePhase(p => p === existingPhase)) { break; } } } - while ((existingPhase = (gScene.findPhase(p => p instanceof StatStageChangePhase && p.battlerIndex === this.battlerIndex && p.selfTarget === this.selfTarget + while ((existingPhase = (globalScene.findPhase(p => p instanceof StatStageChangePhase && p.battlerIndex === this.battlerIndex && p.selfTarget === this.selfTarget && (accEva.some(s => p.stats.includes(s)) === isAccEva) && p.stages === this.stages && p.showMessage === this.showMessage && p.ignoreAbilities === this.ignoreAbilities) as StatStageChangePhase))) { this.stats.push(...existingPhase.stats); - if (!gScene.tryRemovePhase(p => p === existingPhase)) { + if (!globalScene.tryRemovePhase(p => p === existingPhase)) { break; } } diff --git a/src/phases/summon-missing-phase.ts b/src/phases/summon-missing-phase.ts index 4358ef3d95a..0efb6713ae3 100644 --- a/src/phases/summon-missing-phase.ts +++ b/src/phases/summon-missing-phase.ts @@ -1,7 +1,7 @@ import { getPokemonNameWithAffix } from "#app/messages"; import i18next from "i18next"; import { SummonPhase } from "./summon-phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class SummonMissingPhase extends SummonPhase { constructor(fieldIndex: integer) { @@ -9,7 +9,7 @@ export class SummonMissingPhase extends SummonPhase { } preSummon(): void { - gScene.ui.showText(i18next.t("battle:sendOutPokemon", { pokemonName: getPokemonNameWithAffix(this.getPokemon()) })); - gScene.time.delayedCall(250, () => this.summon()); + globalScene.ui.showText(i18next.t("battle:sendOutPokemon", { pokemonName: getPokemonNameWithAffix(this.getPokemon()) })); + globalScene.time.delayedCall(250, () => this.summon()); } } diff --git a/src/phases/summon-phase.ts b/src/phases/summon-phase.ts index 64c28576db7..b0bb27b8a58 100644 --- a/src/phases/summon-phase.ts +++ b/src/phases/summon-phase.ts @@ -12,7 +12,7 @@ import { PostSummonPhase } from "./post-summon-phase"; import { GameOverPhase } from "./game-over-phase"; import { ShinySparklePhase } from "./shiny-sparkle-phase"; import { MysteryEncounterMode } from "#enums/mystery-encounter-mode"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class SummonPhase extends PartyMemberPokemonPhase { private loaded: boolean; @@ -50,8 +50,8 @@ export class SummonPhase extends PartyMemberPokemonPhase { if (legalIndex === -1) { console.error("Party Details:\n", party); console.error("All available Pokemon were fainted or illegal!"); - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new GameOverPhase()); + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new GameOverPhase()); this.end(); return; } @@ -62,33 +62,33 @@ export class SummonPhase extends PartyMemberPokemonPhase { } if (this.player) { - gScene.ui.showText(i18next.t("battle:playerGo", { pokemonName: getPokemonNameWithAffix(this.getPokemon()) })); + globalScene.ui.showText(i18next.t("battle:playerGo", { pokemonName: getPokemonNameWithAffix(this.getPokemon()) })); if (this.player) { - gScene.pbTray.hide(); + globalScene.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"); + globalScene.trainer.setTexture(`trainer_${globalScene.gameData.gender === PlayerGender.FEMALE ? "f" : "m"}_back_pb`); + globalScene.time.delayedCall(562, () => { + globalScene.trainer.setFrame("2"); + globalScene.time.delayedCall(64, () => { + globalScene.trainer.setFrame("3"); }); }); - gScene.tweens.add({ - targets: gScene.trainer, + globalScene.tweens.add({ + targets: globalScene.trainer, x: -36, duration: 1000, - onComplete: () => gScene.trainer.setVisible(false) + onComplete: () => globalScene.trainer.setVisible(false) }); - gScene.time.delayedCall(750, () => this.summon()); - } else if (gScene.currentBattle.battleType === BattleType.TRAINER || gScene.currentBattle.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE) { - const trainerName = gScene.currentBattle.trainer?.getName(!(this.fieldIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER); + globalScene.time.delayedCall(750, () => this.summon()); + } else if (globalScene.currentBattle.battleType === BattleType.TRAINER || globalScene.currentBattle.mysteryEncounter?.encounterMode === MysteryEncounterMode.TRAINER_BATTLE) { + const trainerName = globalScene.currentBattle.trainer?.getName(!(this.fieldIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER); const pokemonName = this.getPokemon().getNameToRender(); const message = i18next.t("battle:trainerSendOut", { trainerName, pokemonName }); - gScene.pbTrayEnemy.hide(); - gScene.ui.showText(message, null, () => this.summon()); - } else if (gScene.currentBattle.isBattleMysteryEncounter()) { - gScene.pbTrayEnemy.hide(); + globalScene.pbTrayEnemy.hide(); + globalScene.ui.showText(message, null, () => this.summon()); + } else if (globalScene.currentBattle.isBattleMysteryEncounter()) { + globalScene.pbTrayEnemy.hide(); this.summonWild(); } } @@ -99,55 +99,55 @@ export class SummonPhase extends PartyMemberPokemonPhase { summon(): void { const pokemon = this.getPokemon(); - const pokeball = gScene.addFieldSprite(this.player ? 36 : 248, this.player ? 80 : 44, "pb", getPokeballAtlasKey(pokemon.pokeball)); + const pokeball = globalScene.addFieldSprite(this.player ? 36 : 248, this.player ? 80 : 44, "pb", getPokeballAtlasKey(pokemon.pokeball)); pokeball.setVisible(false); pokeball.setOrigin(0.5, 0.625); - gScene.field.add(pokeball); + globalScene.field.add(pokeball); if (this.fieldIndex === 1) { pokemon.setFieldPosition(FieldPosition.RIGHT, 0); } else { const availablePartyMembers = this.getParty().filter(p => p.isAllowedInBattle()).length; - pokemon.setFieldPosition(!gScene.currentBattle.double || availablePartyMembers === 1 ? FieldPosition.CENTER : FieldPosition.LEFT); + pokemon.setFieldPosition(!globalScene.currentBattle.double || availablePartyMembers === 1 ? FieldPosition.CENTER : FieldPosition.LEFT); } const fpOffset = pokemon.getFieldPositionOffset(); pokeball.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, duration: 650, x: (this.player ? 100 : 236) + fpOffset[0] }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, duration: 150, ease: "Cubic.easeOut", y: (this.player ? 70 : 34) + fpOffset[1], onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokeball, duration: 500, ease: "Cubic.easeIn", angle: 1440, y: (this.player ? 132 : 86) + fpOffset[1], onComplete: () => { - gScene.playSound("se/pb_rel"); + globalScene.playSound("se/pb_rel"); pokeball.destroy(); - gScene.add.existing(pokemon); - gScene.field.add(pokemon); + globalScene.add.existing(pokemon); + globalScene.field.add(pokemon); if (!this.player) { - const playerPokemon = gScene.getPlayerPokemon() as Pokemon; + const playerPokemon = globalScene.getPlayerPokemon() as Pokemon; if (playerPokemon?.visible) { - gScene.field.moveBelow(pokemon, playerPokemon); + globalScene.field.moveBelow(pokemon, playerPokemon); } - gScene.currentBattle.seenEnemyPartyMemberIds.add(pokemon.id); + globalScene.currentBattle.seenEnemyPartyMemberIds.add(pokemon.id); } addPokeballOpenParticles(pokemon.x, pokemon.y - 16, pokemon.pokeball); - gScene.updateModifiers(this.player); - gScene.updateFieldScale(); + globalScene.updateModifiers(this.player); + globalScene.updateFieldScale(); pokemon.showInfo(); pokemon.playAnim(); pokemon.setVisible(true); @@ -155,8 +155,8 @@ export class SummonPhase extends PartyMemberPokemonPhase { pokemon.setScale(0.5); pokemon.tint(getPokeballTintColor(pokemon.pokeball)); pokemon.untint(250, "Sine.easeIn"); - gScene.updateFieldScale(); - gScene.tweens.add({ + globalScene.updateFieldScale(); + globalScene.tweens.add({ targets: pokemon, duration: 250, ease: "Sine.easeIn", @@ -165,7 +165,7 @@ export class SummonPhase extends PartyMemberPokemonPhase { pokemon.cry(pokemon.getHpRatio() > 0.25 ? undefined : { rate: 0.85 }); pokemon.getSprite().clearTint(); pokemon.resetSummonData(); - gScene.time.delayedCall(1000, () => this.end()); + globalScene.time.delayedCall(1000, () => this.end()); } }); } @@ -186,20 +186,20 @@ export class SummonPhase extends PartyMemberPokemonPhase { pokemon.setFieldPosition(FieldPosition.RIGHT, 0); } else { const availablePartyMembers = this.getParty().filter(p => !p.isFainted()).length; - pokemon.setFieldPosition(!gScene.currentBattle.double || availablePartyMembers === 1 ? FieldPosition.CENTER : FieldPosition.LEFT); + pokemon.setFieldPosition(!globalScene.currentBattle.double || availablePartyMembers === 1 ? FieldPosition.CENTER : FieldPosition.LEFT); } - gScene.add.existing(pokemon); - gScene.field.add(pokemon); + globalScene.add.existing(pokemon); + globalScene.field.add(pokemon); if (!this.player) { - const playerPokemon = gScene.getPlayerPokemon() as Pokemon; + const playerPokemon = globalScene.getPlayerPokemon() as Pokemon; if (playerPokemon?.visible) { - gScene.field.moveBelow(pokemon, playerPokemon); + globalScene.field.moveBelow(pokemon, playerPokemon); } - gScene.currentBattle.seenEnemyPartyMemberIds.add(pokemon.id); + globalScene.currentBattle.seenEnemyPartyMemberIds.add(pokemon.id); } - gScene.updateModifiers(this.player); - gScene.updateFieldScale(); + globalScene.updateModifiers(this.player); + globalScene.updateFieldScale(); pokemon.showInfo(); pokemon.playAnim(); pokemon.setVisible(true); @@ -207,13 +207,13 @@ export class SummonPhase extends PartyMemberPokemonPhase { pokemon.setScale(0.75); pokemon.tint(getPokeballTintColor(pokemon.pokeball)); pokemon.untint(250, "Sine.easeIn"); - gScene.updateFieldScale(); + globalScene.updateFieldScale(); pokemon.x += 16; pokemon.y -= 20; pokemon.alpha = 0; // Ease pokemon in - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, x: "-=16", y: "+=16", @@ -225,8 +225,8 @@ export class SummonPhase extends PartyMemberPokemonPhase { pokemon.cry(pokemon.getHpRatio() > 0.25 ? undefined : { rate: 0.85 }); pokemon.getSprite().clearTint(); pokemon.resetSummonData(); - gScene.updateFieldScale(); - gScene.time.delayedCall(1000, () => this.end()); + globalScene.updateFieldScale(); + globalScene.time.delayedCall(1000, () => this.end()); } }); } @@ -235,19 +235,19 @@ export class SummonPhase extends PartyMemberPokemonPhase { const pokemon = this.getPokemon(); if (pokemon.isShiny()) { - gScene.unshiftPhase(new ShinySparklePhase(pokemon.getBattlerIndex())); + globalScene.unshiftPhase(new ShinySparklePhase(pokemon.getBattlerIndex())); } pokemon.resetTurnData(); - if (!this.loaded || [ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(gScene.currentBattle.battleType) || (gScene.currentBattle.waveIndex % 10) === 1) { - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true); + if (!this.loaded || [ BattleType.TRAINER, BattleType.MYSTERY_ENCOUNTER ].includes(globalScene.currentBattle.battleType) || (globalScene.currentBattle.waveIndex % 10) === 1) { + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true); this.queuePostSummon(); } } queuePostSummon(): void { - gScene.pushPhase(new PostSummonPhase(this.getPokemon().getBattlerIndex())); + globalScene.pushPhase(new PostSummonPhase(this.getPokemon().getBattlerIndex())); } end() { diff --git a/src/phases/switch-biome-phase.ts b/src/phases/switch-biome-phase.ts index 3a39d841394..42774f7eaf7 100644 --- a/src/phases/switch-biome-phase.ts +++ b/src/phases/switch-biome-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Biome } from "#app/enums/biome"; import { getBiomeKey } from "#app/field/arena"; import { BattlePhase } from "./battle-phase"; @@ -19,41 +19,41 @@ export class SwitchBiomePhase extends BattlePhase { return this.end(); } - gScene.tweens.add({ - targets: [ gScene.arenaEnemy, gScene.lastEnemyTrainer ], + globalScene.tweens.add({ + targets: [ globalScene.arenaEnemy, globalScene.lastEnemyTrainer ], x: "+=300", duration: 2000, onComplete: () => { - gScene.arenaEnemy.setX(gScene.arenaEnemy.x - 600); + globalScene.arenaEnemy.setX(globalScene.arenaEnemy.x - 600); - gScene.newArena(this.nextBiome); + globalScene.newArena(this.nextBiome); const biomeKey = getBiomeKey(this.nextBiome); const bgTexture = `${biomeKey}_bg`; - gScene.arenaBgTransition.setTexture(bgTexture); - gScene.arenaBgTransition.setAlpha(0); - gScene.arenaBgTransition.setVisible(true); - gScene.arenaPlayerTransition.setBiome(this.nextBiome); - gScene.arenaPlayerTransition.setAlpha(0); - gScene.arenaPlayerTransition.setVisible(true); + globalScene.arenaBgTransition.setTexture(bgTexture); + globalScene.arenaBgTransition.setAlpha(0); + globalScene.arenaBgTransition.setVisible(true); + globalScene.arenaPlayerTransition.setBiome(this.nextBiome); + globalScene.arenaPlayerTransition.setAlpha(0); + globalScene.arenaPlayerTransition.setVisible(true); - gScene.tweens.add({ - targets: [ gScene.arenaPlayer, gScene.arenaBgTransition, gScene.arenaPlayerTransition ], + globalScene.tweens.add({ + targets: [ globalScene.arenaPlayer, globalScene.arenaBgTransition, globalScene.arenaPlayerTransition ], duration: 1000, delay: 1000, ease: "Sine.easeInOut", - alpha: (target: any) => target === gScene.arenaPlayer ? 0 : 1, + alpha: (target: any) => target === globalScene.arenaPlayer ? 0 : 1, onComplete: () => { - gScene.arenaBg.setTexture(bgTexture); - gScene.arenaPlayer.setBiome(this.nextBiome); - gScene.arenaPlayer.setAlpha(1); - gScene.arenaEnemy.setBiome(this.nextBiome); - gScene.arenaEnemy.setAlpha(1); - gScene.arenaNextEnemy.setBiome(this.nextBiome); - gScene.arenaBgTransition.setVisible(false); - gScene.arenaPlayerTransition.setVisible(false); - if (gScene.lastEnemyTrainer) { - gScene.lastEnemyTrainer.destroy(); + globalScene.arenaBg.setTexture(bgTexture); + globalScene.arenaPlayer.setBiome(this.nextBiome); + globalScene.arenaPlayer.setAlpha(1); + globalScene.arenaEnemy.setBiome(this.nextBiome); + globalScene.arenaEnemy.setAlpha(1); + globalScene.arenaNextEnemy.setBiome(this.nextBiome); + globalScene.arenaBgTransition.setVisible(false); + globalScene.arenaPlayerTransition.setVisible(false); + if (globalScene.lastEnemyTrainer) { + globalScene.lastEnemyTrainer.destroy(); } this.end(); diff --git a/src/phases/switch-phase.ts b/src/phases/switch-phase.ts index 914bae4c1a5..29b2ca22285 100644 --- a/src/phases/switch-phase.ts +++ b/src/phases/switch-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; // todo? +import { globalScene } from "#app/battle-scene"; // todo? import { SwitchType } from "#enums/switch-type"; import PartyUiHandler, { PartyUiMode, PartyOption } from "#app/ui/party-ui-handler"; import { Mode } from "#app/ui/ui"; @@ -38,7 +38,7 @@ export class SwitchPhase extends BattlePhase { super.start(); // Skip modal switch if impossible (no remaining party members that aren't in battle) - if (this.isModal && !gScene.getParty().filter(p => p.isAllowedInBattle() && !p.isActive(true)).length) { + if (this.isModal && !globalScene.getParty().filter(p => p.isAllowedInBattle() && !p.isActive(true)).length) { return super.end(); } @@ -49,24 +49,24 @@ export class SwitchPhase extends BattlePhase { * if the mon should have already been returned but is still alive and well * on the field. see also; battle.test.ts */ - if (this.isModal && !this.doReturn && !gScene.getParty()[this.fieldIndex].isFainted()) { + if (this.isModal && !this.doReturn && !globalScene.getParty()[this.fieldIndex].isFainted()) { return super.end(); } // Check if there is any space still in field - if (this.isModal && gScene.getPlayerField().filter(p => p.isAllowedInBattle() && p.isActive(true)).length >= gScene.currentBattle.getBattlerCount()) { + if (this.isModal && globalScene.getPlayerField().filter(p => p.isAllowedInBattle() && p.isActive(true)).length >= globalScene.currentBattle.getBattlerCount()) { return super.end(); } // Override field index to 0 in case of double battle where 2/3 remaining legal party members fainted at once - const fieldIndex = gScene.currentBattle.getBattlerCount() === 1 || gScene.getParty().filter(p => p.isAllowedInBattle()).length > 1 ? this.fieldIndex : 0; + const fieldIndex = globalScene.currentBattle.getBattlerCount() === 1 || globalScene.getParty().filter(p => p.isAllowedInBattle()).length > 1 ? this.fieldIndex : 0; - gScene.ui.setMode(Mode.PARTY, this.isModal ? PartyUiMode.FAINT_SWITCH : PartyUiMode.POST_BATTLE_SWITCH, fieldIndex, (slotIndex: integer, option: PartyOption) => { - if (slotIndex >= gScene.currentBattle.getBattlerCount() && slotIndex < 6) { + globalScene.ui.setMode(Mode.PARTY, this.isModal ? PartyUiMode.FAINT_SWITCH : PartyUiMode.POST_BATTLE_SWITCH, fieldIndex, (slotIndex: integer, option: PartyOption) => { + if (slotIndex >= globalScene.currentBattle.getBattlerCount() && slotIndex < 6) { const switchType = (option === PartyOption.PASS_BATON) ? SwitchType.BATON_PASS : this.switchType; - gScene.unshiftPhase(new SwitchSummonPhase(switchType, fieldIndex, slotIndex, this.doReturn)); + globalScene.unshiftPhase(new SwitchSummonPhase(switchType, fieldIndex, slotIndex, this.doReturn)); } - gScene.ui.setMode(Mode.MESSAGE).then(() => super.end()); + globalScene.ui.setMode(Mode.MESSAGE).then(() => super.end()); }, PartyUiHandler.FilterNonFainted); } } diff --git a/src/phases/switch-summon-phase.ts b/src/phases/switch-summon-phase.ts index 314957460a9..aaaaf76cee5 100644 --- a/src/phases/switch-summon-phase.ts +++ b/src/phases/switch-summon-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; // todo? +import { globalScene } from "#app/battle-scene"; // todo? import { applyPreSwitchOutAbAttrs, PreSwitchOutAbAttr } from "#app/data/ability"; import { allMoves, ForceSwitchOutAttr } from "#app/data/move"; import { getPokeballTintColor } from "#app/data/pokeball"; @@ -46,29 +46,29 @@ export class SwitchSummonPhase extends SummonPhase { if (!this.player) { if (this.slotIndex === -1) { //@ts-ignore - this.slotIndex = gScene.currentBattle.trainer?.getNextSummonIndex(!this.fieldIndex ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER); // TODO: what would be the default trainer-slot fallback? + this.slotIndex = globalScene.currentBattle.trainer?.getNextSummonIndex(!this.fieldIndex ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER); // TODO: what would be the default trainer-slot fallback? } if (this.slotIndex > -1) { this.showEnemyTrainer(!(this.fieldIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER); - gScene.pbTrayEnemy.showPbTray(gScene.getEnemyParty()); + globalScene.pbTrayEnemy.showPbTray(globalScene.getEnemyParty()); } } - if (!this.doReturn || (this.slotIndex !== -1 && !(this.player ? gScene.getParty() : gScene.getEnemyParty())[this.slotIndex])) { + if (!this.doReturn || (this.slotIndex !== -1 && !(this.player ? globalScene.getParty() : globalScene.getEnemyParty())[this.slotIndex])) { if (this.player) { return this.switchAndSummon(); } else { - gScene.time.delayedCall(750, () => this.switchAndSummon()); + globalScene.time.delayedCall(750, () => this.switchAndSummon()); return; } } const pokemon = this.getPokemon(); - (this.player ? gScene.getEnemyField() : gScene.getPlayerField()).forEach(enemyPokemon => enemyPokemon.removeTagsBySourceId(pokemon.id)); + (this.player ? globalScene.getEnemyField() : globalScene.getPlayerField()).forEach(enemyPokemon => enemyPokemon.removeTagsBySourceId(pokemon.id)); if (this.switchType === SwitchType.SWITCH || this.switchType === SwitchType.INITIAL_SWITCH) { const substitute = pokemon.getTag(SubstituteTag); if (substitute) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: substitute.sprite, duration: 250, scale: substitute.sprite.scale * 0.5, @@ -78,40 +78,40 @@ export class SwitchSummonPhase extends SummonPhase { } } - gScene.ui.showText(this.player ? + globalScene.ui.showText(this.player ? i18next.t("battle:playerComeBack", { pokemonName: getPokemonNameWithAffix(pokemon) }) : i18next.t("battle:trainerComeBack", { - trainerName: gScene.currentBattle.trainer?.getName(!(this.fieldIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER), + trainerName: globalScene.currentBattle.trainer?.getName(!(this.fieldIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER), pokemonName: pokemon.getNameToRender() }) ); - gScene.playSound("se/pb_rel"); + globalScene.playSound("se/pb_rel"); pokemon.hideInfo(); pokemon.tint(getPokeballTintColor(pokemon.pokeball), 1, 250, "Sine.easeIn"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: pokemon, duration: 250, ease: "Sine.easeIn", scale: 0.5, onComplete: () => { pokemon.leaveField(this.switchType === SwitchType.SWITCH, false); - gScene.time.delayedCall(750, () => this.switchAndSummon()); + globalScene.time.delayedCall(750, () => this.switchAndSummon()); } }); } switchAndSummon() { - const party = this.player ? this.getParty() : gScene.getEnemyParty(); + const party = this.player ? this.getParty() : globalScene.getEnemyParty(); const switchedInPokemon = party[this.slotIndex]; this.lastPokemon = this.getPokemon(); applyPreSwitchOutAbAttrs(PreSwitchOutAbAttr, this.lastPokemon); if (this.switchType === SwitchType.BATON_PASS && switchedInPokemon) { - (this.player ? gScene.getEnemyField() : gScene.getPlayerField()).forEach(enemyPokemon => enemyPokemon.transferTagsBySourceId(this.lastPokemon.id, switchedInPokemon.id)); - if (!gScene.findModifier(m => m instanceof SwitchEffectTransferModifier && (m as SwitchEffectTransferModifier).pokemonId === switchedInPokemon.id)) { - const batonPassModifier = gScene.findModifier(m => m instanceof SwitchEffectTransferModifier + (this.player ? globalScene.getEnemyField() : globalScene.getPlayerField()).forEach(enemyPokemon => enemyPokemon.transferTagsBySourceId(this.lastPokemon.id, switchedInPokemon.id)); + if (!globalScene.findModifier(m => m instanceof SwitchEffectTransferModifier && (m as SwitchEffectTransferModifier).pokemonId === switchedInPokemon.id)) { + const batonPassModifier = globalScene.findModifier(m => m instanceof SwitchEffectTransferModifier && (m as SwitchEffectTransferModifier).pokemonId === this.lastPokemon.id) as SwitchEffectTransferModifier; - if (batonPassModifier && !gScene.findModifier(m => m instanceof SwitchEffectTransferModifier && (m as SwitchEffectTransferModifier).pokemonId === switchedInPokemon.id)) { - gScene.tryTransferHeldItemModifier(batonPassModifier, switchedInPokemon, false); + if (batonPassModifier && !globalScene.findModifier(m => m instanceof SwitchEffectTransferModifier && (m as SwitchEffectTransferModifier).pokemonId === switchedInPokemon.id)) { + globalScene.tryTransferHeldItemModifier(batonPassModifier, switchedInPokemon, false); } } } @@ -119,10 +119,10 @@ export class SwitchSummonPhase extends SummonPhase { party[this.slotIndex] = this.lastPokemon; party[this.fieldIndex] = switchedInPokemon; const showTextAndSummon = () => { - gScene.ui.showText(this.player ? + globalScene.ui.showText(this.player ? i18next.t("battle:playerGo", { pokemonName: getPokemonNameWithAffix(switchedInPokemon) }) : i18next.t("battle:trainerGo", { - trainerName: gScene.currentBattle.trainer?.getName(!(this.fieldIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER), + trainerName: globalScene.currentBattle.trainer?.getName(!(this.fieldIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER), pokemonName: this.getPokemon().getNameToRender() }) ); @@ -146,9 +146,9 @@ export class SwitchSummonPhase extends SummonPhase { if (this.player) { showTextAndSummon(); } else { - gScene.time.delayedCall(1500, () => { + globalScene.time.delayedCall(1500, () => { this.hideEnemyTrainer(); - gScene.pbTrayEnemy.hide(); + globalScene.pbTrayEnemy.hide(); showTextAndSummon(); }); } @@ -162,10 +162,10 @@ export class SwitchSummonPhase extends SummonPhase { const pokemon = this.getPokemon(); - const moveId = gScene.currentBattle.lastMove; + const moveId = globalScene.currentBattle.lastMove; const lastUsedMove = moveId ? allMoves[moveId] : undefined; - const currentCommand = gScene.currentBattle.turnCommands[this.fieldIndex]?.command; + const currentCommand = globalScene.currentBattle.turnCommands[this.fieldIndex]?.command; const lastPokemonIsForceSwitchedAndNotFainted = lastUsedMove?.hasAttr(ForceSwitchOutAttr) && !this.lastPokemon.isFainted(); // Compensate for turn spent summoning @@ -191,12 +191,12 @@ export class SwitchSummonPhase extends SummonPhase { this.lastPokemon?.resetSummonData(); - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeActiveTrigger, true); // Reverts to weather-based forms when weather suppressors (Cloud Nine/Air Lock) are switched out - gScene.arena.triggerWeatherBasedFormChanges(); + globalScene.arena.triggerWeatherBasedFormChanges(); } queuePostSummon(): void { - gScene.unshiftPhase(new PostSummonPhase(this.getPokemon().getBattlerIndex())); + globalScene.unshiftPhase(new PostSummonPhase(this.getPokemon().getBattlerIndex())); } } diff --git a/src/phases/title-phase.ts b/src/phases/title-phase.ts index 234282c7c00..e1a229e47d5 100644 --- a/src/phases/title-phase.ts +++ b/src/phases/title-phase.ts @@ -20,7 +20,7 @@ import { EncounterPhase } from "./encounter-phase"; import { SelectChallengePhase } from "./select-challenge-phase"; import { SelectStarterPhase } from "./select-starter-phase"; import { SummonPhase } from "./summon-phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class TitlePhase extends Phase { @@ -37,17 +37,17 @@ export class TitlePhase extends Phase { start(): void { super.start(); - gScene.ui.clearText(); - gScene.ui.fadeIn(250); + globalScene.ui.clearText(); + globalScene.ui.fadeIn(250); - gScene.playBgm("title", true); + globalScene.playBgm("title", true); - gScene.gameData.getSession(loggedInUser?.lastSessionSlot ?? -1).then(sessionData => { + globalScene.gameData.getSession(loggedInUser?.lastSessionSlot ?? -1).then(sessionData => { if (sessionData) { this.lastSessionData = sessionData; const biomeKey = getBiomeKey(sessionData.arena.biome); const bgTexture = `${biomeKey}_bg`; - gScene.arenaBg.setTexture(bgTexture); + globalScene.arenaBg.setTexture(bgTexture); } this.showOptions(); }).catch(err => { @@ -72,11 +72,11 @@ export class TitlePhase extends Phase { handler: () => { const setModeAndEnd = (gameMode: GameModes) => { this.gameMode = gameMode; - gScene.ui.setMode(Mode.MESSAGE); - gScene.ui.clearText(); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.clearText(); this.end(); }; - const { gameData } = gScene; + const { gameData } = globalScene; if (gameData.isUnlocked(Unlockables.ENDLESS_MODE)) { const options: OptionSelectItem[] = [ { @@ -113,17 +113,17 @@ export class TitlePhase extends Phase { options.push({ label: i18next.t("menu:cancel"), handler: () => { - gScene.clearPhaseQueue(); - gScene.pushPhase(new TitlePhase()); + globalScene.clearPhaseQueue(); + globalScene.pushPhase(new TitlePhase()); super.end(); return true; } }); - gScene.ui.showText(i18next.t("menu:selectGameMode"), null, () => gScene.ui.setOverlayMode(Mode.OPTION_SELECT, { options: options })); + globalScene.ui.showText(i18next.t("menu:selectGameMode"), null, () => globalScene.ui.setOverlayMode(Mode.OPTION_SELECT, { options: options })); } else { this.gameMode = GameModes.CLASSIC; - gScene.ui.setMode(Mode.MESSAGE); - gScene.ui.clearText(); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.clearText(); this.end(); } return true; @@ -132,7 +132,7 @@ export class TitlePhase extends Phase { { label: i18next.t("menu:loadGame"), handler: () => { - gScene.ui.setOverlayMode(Mode.SAVE_SLOT, SaveSlotUiMode.LOAD, + globalScene.ui.setOverlayMode(Mode.SAVE_SLOT, SaveSlotUiMode.LOAD, (slotId: integer) => { if (slotId === -1) { return this.showOptions(); @@ -153,7 +153,7 @@ export class TitlePhase extends Phase { { label: i18next.t("menu:settings"), handler: () => { - gScene.ui.setOverlayMode(Mode.SETTINGS); + globalScene.ui.setOverlayMode(Mode.SETTINGS); return true; }, keepOpen: true @@ -163,55 +163,55 @@ export class TitlePhase extends Phase { noCancel: true, yOffset: 47 }; - gScene.ui.setMode(Mode.TITLE, config); + globalScene.ui.setMode(Mode.TITLE, config); } loadSaveSlot(slotId: integer): void { - gScene.sessionSlotId = slotId > -1 || !loggedInUser ? slotId : loggedInUser.lastSessionSlot; - gScene.ui.setMode(Mode.MESSAGE); - gScene.ui.resetModeChain(); - gScene.gameData.loadSession(slotId, slotId === -1 ? this.lastSessionData : undefined).then((success: boolean) => { + globalScene.sessionSlotId = slotId > -1 || !loggedInUser ? slotId : loggedInUser.lastSessionSlot; + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.resetModeChain(); + globalScene.gameData.loadSession(slotId, slotId === -1 ? this.lastSessionData : undefined).then((success: boolean) => { if (success) { this.loaded = true; - gScene.ui.showText(i18next.t("menu:sessionSuccess"), null, () => this.end()); + globalScene.ui.showText(i18next.t("menu:sessionSuccess"), null, () => this.end()); } else { this.end(); } }).catch(err => { console.error(err); - gScene.ui.showText(i18next.t("menu:failedToLoadSession"), null); + globalScene.ui.showText(i18next.t("menu:failedToLoadSession"), null); }); } initDailyRun(): void { - gScene.ui.setMode(Mode.SAVE_SLOT, SaveSlotUiMode.SAVE, (slotId: integer) => { - gScene.clearPhaseQueue(); + globalScene.ui.setMode(Mode.SAVE_SLOT, SaveSlotUiMode.SAVE, (slotId: integer) => { + globalScene.clearPhaseQueue(); if (slotId === -1) { - gScene.pushPhase(new TitlePhase()); + globalScene.pushPhase(new TitlePhase()); return super.end(); } - gScene.sessionSlotId = slotId; + globalScene.sessionSlotId = slotId; const generateDaily = (seed: string) => { - gScene.gameMode = getGameMode(GameModes.DAILY); + globalScene.gameMode = getGameMode(GameModes.DAILY); - gScene.setSeed(seed); - gScene.resetSeed(0); + globalScene.setSeed(seed); + globalScene.resetSeed(0); - gScene.money = gScene.gameMode.getStartingMoney(); + globalScene.money = globalScene.gameMode.getStartingMoney(); const starters = getDailyRunStarters(seed); - const startingLevel = gScene.gameMode.getStartingLevel(); + const startingLevel = globalScene.gameMode.getStartingLevel(); - const party = gScene.getParty(); + const party = globalScene.getParty(); const loadPokemonAssets: Promise[] = []; for (const starter of starters) { - const starterProps = gScene.gameData.getSpeciesDexAttrProps(starter.species, starter.dexAttr); + const starterProps = globalScene.gameData.getSpeciesDexAttrProps(starter.species, starter.dexAttr); const starterFormIndex = Math.min(starterProps.formIndex, Math.max(starter.species.forms.length - 1, 0)); const starterGender = starter.species.malePercent !== null ? !starterProps.female ? Gender.MALE : Gender.FEMALE : Gender.GENDERLESS; - const starterPokemon = gScene.addPlayerPokemon(starter.species, startingLevel, starter.abilityIndex, starterFormIndex, starterGender, starterProps.shiny, starterProps.variant, undefined, starter.nature); + const starterPokemon = globalScene.addPlayerPokemon(starter.species, startingLevel, starter.abilityIndex, starterFormIndex, starterGender, starterProps.shiny, starterProps.variant, undefined, starter.nature); starterPokemon.setVisible(false); party.push(starterPokemon); loadPokemonAssets.push(starterPokemon.loadAssets()); @@ -226,18 +226,18 @@ export class TitlePhase extends Phase { .filter((m) => m !== null); for (const m of modifiers) { - gScene.addModifier(m, true, false, false, true); + globalScene.addModifier(m, true, false, false, true); } - gScene.updateModifiers(true, true); + globalScene.updateModifiers(true, true); Promise.all(loadPokemonAssets).then(() => { - gScene.time.delayedCall(500, () => gScene.playBgm()); - gScene.gameData.gameStats.dailyRunSessionsPlayed++; - gScene.newArena(gScene.gameMode.getStartingBiome()); - gScene.newBattle(); - gScene.arena.init(); - gScene.sessionPlayTime = 0; - gScene.lastSavePlayTime = 0; + globalScene.time.delayedCall(500, () => globalScene.playBgm()); + globalScene.gameData.gameStats.dailyRunSessionsPlayed++; + globalScene.newArena(globalScene.gameMode.getStartingBiome()); + globalScene.newBattle(); + globalScene.arena.init(); + globalScene.sessionPlayTime = 0; + globalScene.lastSavePlayTime = 0; this.end(); }); }; @@ -260,43 +260,43 @@ export class TitlePhase extends Phase { } end(): void { - if (!this.loaded && !gScene.gameMode.isDaily) { - gScene.arena.preloadBgm(); - gScene.gameMode = getGameMode(this.gameMode); + if (!this.loaded && !globalScene.gameMode.isDaily) { + globalScene.arena.preloadBgm(); + globalScene.gameMode = getGameMode(this.gameMode); if (this.gameMode === GameModes.CHALLENGE) { - gScene.pushPhase(new SelectChallengePhase()); + globalScene.pushPhase(new SelectChallengePhase()); } else { - gScene.pushPhase(new SelectStarterPhase()); + globalScene.pushPhase(new SelectStarterPhase()); } - gScene.newArena(gScene.gameMode.getStartingBiome()); + globalScene.newArena(globalScene.gameMode.getStartingBiome()); } else { - gScene.playBgm(); + globalScene.playBgm(); } - gScene.pushPhase(new EncounterPhase(this.loaded)); + globalScene.pushPhase(new EncounterPhase(this.loaded)); if (this.loaded) { - const availablePartyMembers = gScene.getParty().filter(p => p.isAllowedInBattle()).length; + const availablePartyMembers = globalScene.getParty().filter(p => p.isAllowedInBattle()).length; - gScene.pushPhase(new SummonPhase(0, true, true)); - if (gScene.currentBattle.double && availablePartyMembers > 1) { - gScene.pushPhase(new SummonPhase(1, true, true)); + globalScene.pushPhase(new SummonPhase(0, true, true)); + if (globalScene.currentBattle.double && availablePartyMembers > 1) { + globalScene.pushPhase(new SummonPhase(1, true, true)); } - if (gScene.currentBattle.battleType !== BattleType.TRAINER && (gScene.currentBattle.waveIndex > 1 || !gScene.gameMode.isDaily)) { - const minPartySize = gScene.currentBattle.double ? 2 : 1; + if (globalScene.currentBattle.battleType !== BattleType.TRAINER && (globalScene.currentBattle.waveIndex > 1 || !globalScene.gameMode.isDaily)) { + const minPartySize = globalScene.currentBattle.double ? 2 : 1; if (availablePartyMembers > minPartySize) { - gScene.pushPhase(new CheckSwitchPhase(0, gScene.currentBattle.double)); - if (gScene.currentBattle.double) { - gScene.pushPhase(new CheckSwitchPhase(1, gScene.currentBattle.double)); + globalScene.pushPhase(new CheckSwitchPhase(0, globalScene.currentBattle.double)); + if (globalScene.currentBattle.double) { + globalScene.pushPhase(new CheckSwitchPhase(1, globalScene.currentBattle.double)); } } } } - for (const achv of Object.keys(gScene.gameData.achvUnlocks)) { + for (const achv of Object.keys(globalScene.gameData.achvUnlocks)) { if (vouchers.hasOwnProperty(achv) && achv !== "CLASSIC_VICTORY") { - gScene.validateVoucher(vouchers[achv]); + globalScene.validateVoucher(vouchers[achv]); } } diff --git a/src/phases/toggle-double-position-phase.ts b/src/phases/toggle-double-position-phase.ts index e0005ac7cdf..9ad415049e1 100644 --- a/src/phases/toggle-double-position-phase.ts +++ b/src/phases/toggle-double-position-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { FieldPosition } from "#app/field/pokemon"; import { BattlePhase } from "./battle-phase"; @@ -14,11 +14,11 @@ export class ToggleDoublePositionPhase extends BattlePhase { start() { super.start(); - const playerPokemon = gScene.getPlayerField().find(p => p.isActive(true)); + const playerPokemon = globalScene.getPlayerField().find(p => p.isActive(true)); if (playerPokemon) { - playerPokemon.setFieldPosition(this.double && gScene.getParty().filter(p => p.isAllowedInBattle()).length > 1 ? FieldPosition.LEFT : FieldPosition.CENTER, 500).then(() => { + playerPokemon.setFieldPosition(this.double && globalScene.getParty().filter(p => p.isAllowedInBattle()).length > 1 ? FieldPosition.LEFT : FieldPosition.CENTER, 500).then(() => { if (playerPokemon.getFieldIndex() === 1) { - const party = gScene.getParty(); + const party = globalScene.getParty(); party[1] = party[0]; party[0] = playerPokemon; } diff --git a/src/phases/trainer-message-test-phase.ts b/src/phases/trainer-message-test-phase.ts index eb8275f80eb..90bf69644e6 100644 --- a/src/phases/trainer-message-test-phase.ts +++ b/src/phases/trainer-message-test-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { trainerConfigs } from "#app/data/trainer-config"; import { TrainerType } from "#app/enums/trainer-type"; import { BattlePhase } from "./battle-phase"; @@ -33,7 +33,7 @@ export class TrainerMessageTestPhase extends BattlePhase { } for (const message of testMessages) { - gScene.pushPhase(new TestMessagePhase(message)); + globalScene.pushPhase(new TestMessagePhase(message)); } this.end(); diff --git a/src/phases/trainer-victory-phase.ts b/src/phases/trainer-victory-phase.ts index 7a10788bc09..9c5b5b0eeab 100644 --- a/src/phases/trainer-victory-phase.ts +++ b/src/phases/trainer-victory-phase.ts @@ -8,7 +8,7 @@ import { BattlePhase } from "./battle-phase"; import { ModifierRewardPhase } from "./modifier-reward-phase"; import { MoneyRewardPhase } from "./money-reward-phase"; import { TrainerSlot } from "#app/data/trainer-config"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class TrainerVictoryPhase extends BattlePhase { constructor() { @@ -16,48 +16,48 @@ export class TrainerVictoryPhase extends BattlePhase { } start() { - gScene.disableMenu = true; + globalScene.disableMenu = true; - gScene.playBgm(gScene.currentBattle.trainer?.config.victoryBgm); + globalScene.playBgm(globalScene.currentBattle.trainer?.config.victoryBgm); - gScene.unshiftPhase(new MoneyRewardPhase(gScene.currentBattle.trainer?.config.moneyMultiplier!)); // TODO: is this bang correct? + globalScene.unshiftPhase(new MoneyRewardPhase(globalScene.currentBattle.trainer?.config.moneyMultiplier!)); // TODO: is this bang correct? - const modifierRewardFuncs = gScene.currentBattle.trainer?.config.modifierRewardFuncs!; // TODO: is this bang correct? + const modifierRewardFuncs = globalScene.currentBattle.trainer?.config.modifierRewardFuncs!; // TODO: is this bang correct? for (const modifierRewardFunc of modifierRewardFuncs) { - gScene.unshiftPhase(new ModifierRewardPhase(modifierRewardFunc)); + globalScene.unshiftPhase(new ModifierRewardPhase(modifierRewardFunc)); } - if (gScene.eventManager.isEventActive()) { - for (const rewardFunc of gScene.currentBattle.trainer?.config.eventRewardFuncs!) { - gScene.unshiftPhase(new ModifierRewardPhase(rewardFunc)); + if (globalScene.eventManager.isEventActive()) { + for (const rewardFunc of globalScene.currentBattle.trainer?.config.eventRewardFuncs!) { + globalScene.unshiftPhase(new ModifierRewardPhase(rewardFunc)); } } - const trainerType = gScene.currentBattle.trainer?.config.trainerType!; // TODO: is this bang correct? + const trainerType = globalScene.currentBattle.trainer?.config.trainerType!; // TODO: is this bang correct? if (vouchers.hasOwnProperty(TrainerType[trainerType])) { - if (!gScene.validateVoucher(vouchers[TrainerType[trainerType]]) && gScene.currentBattle.trainer?.config.isBoss) { - gScene.unshiftPhase(new ModifierRewardPhase([ modifierTypes.VOUCHER, modifierTypes.VOUCHER, modifierTypes.VOUCHER_PLUS, modifierTypes.VOUCHER_PREMIUM ][vouchers[TrainerType[trainerType]].voucherType])); + if (!globalScene.validateVoucher(vouchers[TrainerType[trainerType]]) && globalScene.currentBattle.trainer?.config.isBoss) { + globalScene.unshiftPhase(new ModifierRewardPhase([ modifierTypes.VOUCHER, modifierTypes.VOUCHER, modifierTypes.VOUCHER_PLUS, modifierTypes.VOUCHER_PREMIUM ][vouchers[TrainerType[trainerType]].voucherType])); } } - gScene.ui.showText(i18next.t("battle:trainerDefeated", { trainerName: gScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }), null, () => { - const victoryMessages = gScene.currentBattle.trainer?.getVictoryMessages()!; // TODO: is this bang correct? + globalScene.ui.showText(i18next.t("battle:trainerDefeated", { trainerName: globalScene.currentBattle.trainer?.getName(TrainerSlot.NONE, true) }), null, () => { + const victoryMessages = globalScene.currentBattle.trainer?.getVictoryMessages()!; // TODO: is this bang correct? let message: string; - gScene.executeWithSeedOffset(() => message = Utils.randSeedItem(victoryMessages), gScene.currentBattle.waveIndex); + globalScene.executeWithSeedOffset(() => message = Utils.randSeedItem(victoryMessages), globalScene.currentBattle.waveIndex); message = message!; // tell TS compiler it's defined now const showMessage = () => { const originalFunc = showMessageOrEnd; - showMessageOrEnd = () => gScene.ui.showDialogue(message, gScene.currentBattle.trainer?.getName(TrainerSlot.TRAINER, true), null, originalFunc); + showMessageOrEnd = () => globalScene.ui.showDialogue(message, globalScene.currentBattle.trainer?.getName(TrainerSlot.TRAINER, true), null, originalFunc); showMessageOrEnd(); }; let showMessageOrEnd = () => this.end(); if (victoryMessages?.length) { - if (gScene.currentBattle.trainer?.config.hasCharSprite && !gScene.ui.shouldSkipDialogue(message)) { + if (globalScene.currentBattle.trainer?.config.hasCharSprite && !globalScene.ui.shouldSkipDialogue(message)) { const originalFunc = showMessageOrEnd; - showMessageOrEnd = () => gScene.charSprite.hide().then(() => gScene.hideFieldOverlay(250).then(() => originalFunc())); - gScene.showFieldOverlay(500).then(() => gScene.charSprite.showCharacter(gScene.currentBattle.trainer?.getKey()!, getCharVariantFromDialogue(victoryMessages[0])).then(() => showMessage())); // TODO: is this bang correct? + showMessageOrEnd = () => globalScene.charSprite.hide().then(() => globalScene.hideFieldOverlay(250).then(() => originalFunc())); + globalScene.showFieldOverlay(500).then(() => globalScene.charSprite.showCharacter(globalScene.currentBattle.trainer?.getKey()!, getCharVariantFromDialogue(victoryMessages[0])).then(() => showMessage())); // TODO: is this bang correct? } else { showMessage(); } diff --git a/src/phases/turn-end-phase.ts b/src/phases/turn-end-phase.ts index 86ad9f5e99a..c1b500d5e70 100644 --- a/src/phases/turn-end-phase.ts +++ b/src/phases/turn-end-phase.ts @@ -9,7 +9,7 @@ import { TurnHealModifier, EnemyTurnHealModifier, EnemyStatusEffectHealChanceMod import i18next from "i18next"; import { FieldPhase } from "./field-phase"; import { PokemonHealPhase } from "./pokemon-heal-phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class TurnEndPhase extends FieldPhase { constructor() { @@ -19,29 +19,29 @@ export class TurnEndPhase extends FieldPhase { start() { super.start(); - gScene.currentBattle.incrementTurn(); - gScene.eventTarget.dispatchEvent(new TurnEndEvent(gScene.currentBattle.turn)); + globalScene.currentBattle.incrementTurn(); + globalScene.eventTarget.dispatchEvent(new TurnEndEvent(globalScene.currentBattle.turn)); const handlePokemon = (pokemon: Pokemon) => { pokemon.lapseTags(BattlerTagLapseType.TURN_END); - gScene.applyModifiers(TurnHealModifier, pokemon.isPlayer(), pokemon); + globalScene.applyModifiers(TurnHealModifier, pokemon.isPlayer(), pokemon); - if (gScene.arena.terrain?.terrainType === TerrainType.GRASSY && pokemon.isGrounded()) { - gScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), + if (globalScene.arena.terrain?.terrainType === TerrainType.GRASSY && pokemon.isGrounded()) { + globalScene.unshiftPhase(new PokemonHealPhase(pokemon.getBattlerIndex(), Math.max(pokemon.getMaxHp() >> 4, 1), i18next.t("battle:turnEndHpRestore", { pokemonName: getPokemonNameWithAffix(pokemon) }), true)); } if (!pokemon.isPlayer()) { - gScene.applyModifiers(EnemyTurnHealModifier, false, pokemon); - gScene.applyModifier(EnemyStatusEffectHealChanceModifier, false, pokemon); + globalScene.applyModifiers(EnemyTurnHealModifier, false, pokemon); + globalScene.applyModifier(EnemyStatusEffectHealChanceModifier, false, pokemon); } applyPostTurnAbAttrs(PostTurnAbAttr, pokemon); - gScene.applyModifiers(TurnStatusEffectModifier, pokemon.isPlayer(), pokemon); + globalScene.applyModifiers(TurnStatusEffectModifier, pokemon.isPlayer(), pokemon); - gScene.applyModifiers(TurnHeldItemTransferModifier, pokemon.isPlayer(), pokemon); + globalScene.applyModifiers(TurnHeldItemTransferModifier, pokemon.isPlayer(), pokemon); pokemon.battleSummonData.turnCount++; pokemon.battleSummonData.waveTurnCount++; @@ -49,15 +49,15 @@ export class TurnEndPhase extends FieldPhase { this.executeForAll(handlePokemon); - gScene.arena.lapseTags(); + globalScene.arena.lapseTags(); - if (gScene.arena.weather && !gScene.arena.weather.lapse()) { - gScene.arena.trySetWeather(WeatherType.NONE, false); - gScene.arena.triggerWeatherBasedFormChangesToNormal(); + if (globalScene.arena.weather && !globalScene.arena.weather.lapse()) { + globalScene.arena.trySetWeather(WeatherType.NONE, false); + globalScene.arena.triggerWeatherBasedFormChangesToNormal(); } - if (gScene.arena.terrain && !gScene.arena.terrain.lapse()) { - gScene.arena.trySetTerrain(TerrainType.NONE, false); + if (globalScene.arena.terrain && !globalScene.arena.terrain.lapse()) { + globalScene.arena.trySetTerrain(TerrainType.NONE, false); } this.end(); diff --git a/src/phases/turn-init-phase.ts b/src/phases/turn-init-phase.ts index f73ee38a5a9..6756e2354a5 100644 --- a/src/phases/turn-init-phase.ts +++ b/src/phases/turn-init-phase.ts @@ -9,7 +9,7 @@ import { EnemyCommandPhase } from "./enemy-command-phase"; import { GameOverPhase } from "./game-over-phase"; import { TurnStartPhase } from "./turn-start-phase"; import { handleMysteryEncounterBattleStartEffects, handleMysteryEncounterTurnStartEffects } from "#app/data/mystery-encounters/utils/encounter-phase-utils"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class TurnInitPhase extends FieldPhase { constructor() { @@ -19,18 +19,18 @@ export class TurnInitPhase extends FieldPhase { start() { super.start(); - gScene.getPlayerField().forEach(p => { + globalScene.getPlayerField().forEach(p => { // If this pokemon is in play and evolved into something illegal under the current challenge, force a switch if (p.isOnField() && !p.isAllowedInBattle()) { - gScene.queueMessage(i18next.t("challenges:illegalEvolution", { "pokemon": p.name }), null, true); + globalScene.queueMessage(i18next.t("challenges:illegalEvolution", { "pokemon": p.name }), null, true); - const allowedPokemon = gScene.getParty().filter(p => p.isAllowedInBattle()); + const allowedPokemon = globalScene.getParty().filter(p => p.isAllowedInBattle()); if (!allowedPokemon.length) { // If there are no longer any legal pokemon in the party, game over. - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new GameOverPhase()); - } else if (allowedPokemon.length >= gScene.currentBattle.getBattlerCount() || (gScene.currentBattle.double && !allowedPokemon[0].isActive(true))) { + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new GameOverPhase()); + } else if (allowedPokemon.length >= globalScene.currentBattle.getBattlerCount() || (globalScene.currentBattle.double && !allowedPokemon[0].isActive(true))) { // If there is at least one pokemon in the back that is legal to switch in, force a switch. p.switchOut(); } else { @@ -38,14 +38,13 @@ export class TurnInitPhase extends FieldPhase { // This should only happen in double battles. p.leaveField(); } - if (allowedPokemon.length === 1 && gScene.currentBattle.double) { - gScene.unshiftPhase(new ToggleDoublePositionPhase(true)); + if (allowedPokemon.length === 1 && globalScene.currentBattle.double) { + globalScene.unshiftPhase(new ToggleDoublePositionPhase(true)); } } }); - //gScene.pushPhase(new MoveAnimTestPhase()); - gScene.eventTarget.dispatchEvent(new TurnInitEvent()); + globalScene.eventTarget.dispatchEvent(new TurnInitEvent()); handleMysteryEncounterBattleStartEffects(); @@ -55,19 +54,19 @@ export class TurnInitPhase extends FieldPhase { return; } - gScene.getField().forEach((pokemon, i) => { + globalScene.getField().forEach((pokemon, i) => { if (pokemon?.isActive()) { if (pokemon.isPlayer()) { - gScene.currentBattle.addParticipant(pokemon as PlayerPokemon); + globalScene.currentBattle.addParticipant(pokemon as PlayerPokemon); } pokemon.resetTurnData(); - gScene.pushPhase(pokemon.isPlayer() ? new CommandPhase(i) : new EnemyCommandPhase(i - BattlerIndex.ENEMY)); + globalScene.pushPhase(pokemon.isPlayer() ? new CommandPhase(i) : new EnemyCommandPhase(i - BattlerIndex.ENEMY)); } }); - gScene.pushPhase(new TurnStartPhase()); + globalScene.pushPhase(new TurnStartPhase()); this.end(); } diff --git a/src/phases/turn-start-phase.ts b/src/phases/turn-start-phase.ts index 55e222dddc7..a357df7adc4 100644 --- a/src/phases/turn-start-phase.ts +++ b/src/phases/turn-start-phase.ts @@ -19,7 +19,7 @@ import { CheckStatusEffectPhase } from "#app/phases/check-status-effect-phase"; import { BattlerIndex } from "#app/battle"; import { TrickRoomTag } from "#app/data/arena-tag"; import { SwitchType } from "#enums/switch-type"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class TurnStartPhase extends FieldPhase { constructor() { @@ -32,20 +32,20 @@ export class TurnStartPhase extends FieldPhase { * @returns {@linkcode BattlerIndex[]} the battle indices of all pokemon on the field ordered by speed */ getSpeedOrder(): BattlerIndex[] { - const playerField = gScene.getPlayerField().filter(p => p.isActive()) as Pokemon[]; - const enemyField = gScene.getEnemyField().filter(p => p.isActive()) as Pokemon[]; + const playerField = globalScene.getPlayerField().filter(p => p.isActive()) as Pokemon[]; + const enemyField = globalScene.getEnemyField().filter(p => p.isActive()) as Pokemon[]; // We shuffle the list before sorting so speed ties produce random results let orderedTargets: Pokemon[] = playerField.concat(enemyField); // We seed it with the current turn to prevent an inconsistency where it // was varying based on how long since you last reloaded - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { orderedTargets = Utils.randSeedShuffle(orderedTargets); - }, gScene.currentBattle.turn, gScene.waveSeed); + }, globalScene.currentBattle.turn, globalScene.waveSeed); // Next, a check for Trick Room is applied to determine sort order. const speedReversed = new Utils.BooleanHolder(false); - gScene.arena.applyTags(TrickRoomTag, false, speedReversed); + globalScene.arena.applyTags(TrickRoomTag, false, speedReversed); // Adjust the sort function based on whether Trick Room is active. orderedTargets.sort((a: Pokemon, b: Pokemon) => { @@ -70,13 +70,13 @@ export class TurnStartPhase extends FieldPhase { // This occurs before the main loop because of battles with more than two Pokemon const battlerBypassSpeed = {}; - gScene.getField(true).filter(p => p.summonData).map(p => { + globalScene.getField(true).filter(p => p.summonData).map(p => { const bypassSpeed = new Utils.BooleanHolder(false); const canCheckHeldItems = new Utils.BooleanHolder(true); applyAbAttrs(BypassSpeedChanceAbAttr, p, null, false, bypassSpeed); applyAbAttrs(PreventBypassSpeedChanceAbAttr, p, null, false, bypassSpeed, canCheckHeldItems); if (canCheckHeldItems.value) { - gScene.applyModifiers(BypassSpeedChanceModifier, p.isPlayer(), p, bypassSpeed); + globalScene.applyModifiers(BypassSpeedChanceModifier, p.isPlayer(), p, bypassSpeed); } battlerBypassSpeed[p.getBattlerIndex()] = bypassSpeed; }); @@ -85,8 +85,8 @@ export class TurnStartPhase extends FieldPhase { // Non-FIGHT commands (SWITCH, BALL, RUN) have a higher command priority and will always occur before any FIGHT commands. moveOrder = moveOrder.slice(0); moveOrder.sort((a, b) => { - const aCommand = gScene.currentBattle.turnCommands[a]; - const bCommand = gScene.currentBattle.turnCommands[b]; + const aCommand = globalScene.currentBattle.turnCommands[a]; + const bCommand = globalScene.currentBattle.turnCommands[b]; if (aCommand?.command !== bCommand?.command) { if (aCommand?.command === Command.FIGHT) { @@ -102,11 +102,11 @@ export class TurnStartPhase extends FieldPhase { const aPriority = new Utils.IntegerHolder(aMove.priority); const bPriority = new Utils.IntegerHolder(bMove.priority); - applyMoveAttrs(IncrementMovePriorityAttr, gScene.getField().find(p => p?.isActive() && p.getBattlerIndex() === a)!, null, aMove, aPriority); - applyMoveAttrs(IncrementMovePriorityAttr, gScene.getField().find(p => p?.isActive() && p.getBattlerIndex() === b)!, null, bMove, bPriority); + applyMoveAttrs(IncrementMovePriorityAttr, globalScene.getField().find(p => p?.isActive() && p.getBattlerIndex() === a)!, null, aMove, aPriority); + applyMoveAttrs(IncrementMovePriorityAttr, globalScene.getField().find(p => p?.isActive() && p.getBattlerIndex() === b)!, null, bMove, bPriority); - applyAbAttrs(ChangeMovePriorityAbAttr, gScene.getField().find(p => p?.isActive() && p.getBattlerIndex() === a)!, null, false, aMove, aPriority); - applyAbAttrs(ChangeMovePriorityAbAttr, gScene.getField().find(p => p?.isActive() && p.getBattlerIndex() === b)!, null, false, bMove, bPriority); + applyAbAttrs(ChangeMovePriorityAbAttr, globalScene.getField().find(p => p?.isActive() && p.getBattlerIndex() === a)!, null, false, aMove, aPriority); + applyAbAttrs(ChangeMovePriorityAbAttr, globalScene.getField().find(p => p?.isActive() && p.getBattlerIndex() === b)!, null, false, bMove, bPriority); // The game now checks for differences in priority levels. // If the moves share the same original priority bracket, it can check for differences in battlerBypassSpeed and return the result. @@ -137,7 +137,7 @@ export class TurnStartPhase extends FieldPhase { start() { super.start(); - const field = gScene.getField(); + const field = globalScene.getField(); const moveOrder = this.getCommandOrder(); let orderIndex = 0; @@ -145,7 +145,7 @@ export class TurnStartPhase extends FieldPhase { for (const o of moveOrder) { const pokemon = field[o]; - const turnCommand = gScene.currentBattle.turnCommands[o]; + const turnCommand = globalScene.currentBattle.turnCommands[o]; if (turnCommand?.skip) { continue; @@ -160,29 +160,29 @@ export class TurnStartPhase extends FieldPhase { } const move = pokemon.getMoveset().find(m => m?.moveId === queuedMove.move && m?.ppUsed < m?.getMovePp()) || new PokemonMove(queuedMove.move); if (move.getMove().hasAttr(MoveHeaderAttr)) { - gScene.unshiftPhase(new MoveHeaderPhase(pokemon, move)); + globalScene.unshiftPhase(new MoveHeaderPhase(pokemon, move)); } if (pokemon.isPlayer()) { if (turnCommand.cursor === -1) { - gScene.pushPhase(new MovePhase(pokemon, turnCommand.targets || turnCommand.move!.targets, move));//TODO: is the bang correct here? + globalScene.pushPhase(new MovePhase(pokemon, turnCommand.targets || turnCommand.move!.targets, move));//TODO: is the bang correct here? } else { const playerPhase = new MovePhase(pokemon, turnCommand.targets || turnCommand.move!.targets, move, false, queuedMove.ignorePP);//TODO: is the bang correct here? - gScene.pushPhase(playerPhase); + globalScene.pushPhase(playerPhase); } } else { - gScene.pushPhase(new MovePhase(pokemon, turnCommand.targets || turnCommand.move!.targets, move, false, queuedMove.ignorePP));//TODO: is the bang correct here? + globalScene.pushPhase(new MovePhase(pokemon, turnCommand.targets || turnCommand.move!.targets, move, false, queuedMove.ignorePP));//TODO: is the bang correct here? } break; case Command.BALL: - gScene.unshiftPhase(new AttemptCapturePhase(turnCommand.targets![0] % 2, turnCommand.cursor!));//TODO: is the bang correct here? + globalScene.unshiftPhase(new AttemptCapturePhase(turnCommand.targets![0] % 2, turnCommand.cursor!));//TODO: is the bang correct here? break; case Command.POKEMON: const switchType = turnCommand.args?.[0] ? SwitchType.BATON_PASS : SwitchType.SWITCH; - gScene.unshiftPhase(new SwitchSummonPhase(switchType, pokemon.getFieldIndex(), turnCommand.cursor!, true, pokemon.isPlayer())); + globalScene.unshiftPhase(new SwitchSummonPhase(switchType, pokemon.getFieldIndex(), turnCommand.cursor!, true, pokemon.isPlayer())); break; case Command.RUN: let runningPokemon = pokemon; - if (gScene.currentBattle.double) { + if (globalScene.currentBattle.double) { const playerActivePokemon = field.filter(pokemon => { if (!!pokemon) { return pokemon.isPlayer() && pokemon.isActive(); @@ -199,18 +199,18 @@ export class TurnStartPhase extends FieldPhase { runningPokemon = hasRunAway !== undefined ? hasRunAway : fasterPokemon; } } - gScene.unshiftPhase(new AttemptRunPhase(runningPokemon.getFieldIndex())); + globalScene.unshiftPhase(new AttemptRunPhase(runningPokemon.getFieldIndex())); break; } } - gScene.pushPhase(new WeatherEffectPhase()); - gScene.pushPhase(new BerryPhase()); + globalScene.pushPhase(new WeatherEffectPhase()); + globalScene.pushPhase(new BerryPhase()); /** Add a new phase to check who should be taking status damage */ - gScene.pushPhase(new CheckStatusEffectPhase(moveOrder)); + globalScene.pushPhase(new CheckStatusEffectPhase(moveOrder)); - gScene.pushPhase(new TurnEndPhase()); + globalScene.pushPhase(new TurnEndPhase()); /** * this.end() will call shiftPhase(), which dumps everything from PrependQueue (aka everything that is unshifted()) to the front diff --git a/src/phases/unavailable-phase.ts b/src/phases/unavailable-phase.ts index fbca989daeb..db0cc26a68e 100644 --- a/src/phases/unavailable-phase.ts +++ b/src/phases/unavailable-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; import { Mode } from "#app/ui/ui"; import { LoginPhase } from "./login-phase"; @@ -9,8 +9,8 @@ export class UnavailablePhase extends Phase { } start(): void { - gScene.ui.setMode(Mode.UNAVAILABLE, () => { - gScene.unshiftPhase(new LoginPhase(true)); + globalScene.ui.setMode(Mode.UNAVAILABLE, () => { + globalScene.unshiftPhase(new LoginPhase(true)); this.end(); }); } diff --git a/src/phases/unlock-phase.ts b/src/phases/unlock-phase.ts index 0dcdd609ce4..02a59c1c5d8 100644 --- a/src/phases/unlock-phase.ts +++ b/src/phases/unlock-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Phase } from "#app/phase"; import { Unlockables, getUnlockableName } from "#app/system/unlockables"; import { Mode } from "#app/ui/ui"; @@ -14,13 +14,13 @@ export class UnlockPhase extends Phase { } start(): void { - gScene.time.delayedCall(2000, () => { - gScene.gameData.unlocks[this.unlockable] = true; + globalScene.time.delayedCall(2000, () => { + globalScene.gameData.unlocks[this.unlockable] = true; // Sound loaded into game as is - gScene.playSound("level_up_fanfare"); - gScene.ui.setMode(Mode.MESSAGE); - gScene.ui.showText(i18next.t("battle:unlockedSomething", { unlockedThing: getUnlockableName(this.unlockable) }), null, () => { - gScene.time.delayedCall(1500, () => gScene.arenaBg.setVisible(true)); + globalScene.playSound("level_up_fanfare"); + globalScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.showText(i18next.t("battle:unlockedSomething", { unlockedThing: getUnlockableName(this.unlockable) }), null, () => { + globalScene.time.delayedCall(1500, () => globalScene.arenaBg.setVisible(true)); this.end(); }, null, true, 1500); }); diff --git a/src/phases/victory-phase.ts b/src/phases/victory-phase.ts index 10d5dc61c2b..80e58372dc5 100644 --- a/src/phases/victory-phase.ts +++ b/src/phases/victory-phase.ts @@ -10,7 +10,7 @@ import { ModifierRewardPhase } from "./modifier-reward-phase"; import { SelectModifierPhase } from "./select-modifier-phase"; import { TrainerVictoryPhase } from "./trainer-victory-phase"; import { handleMysteryEncounterVictory } from "#app/data/mystery-encounters/utils/encounter-phase-utils"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export class VictoryPhase extends PokemonPhase { /** If true, indicates that the phase is intended for EXP purposes only, and not to continue a battle to next phase */ @@ -25,61 +25,61 @@ export class VictoryPhase extends PokemonPhase { start() { super.start(); - const isMysteryEncounter = gScene.currentBattle.isBattleMysteryEncounter(); + const isMysteryEncounter = globalScene.currentBattle.isBattleMysteryEncounter(); // update Pokemon defeated count except for MEs that disable it - if (!isMysteryEncounter || !gScene.currentBattle.mysteryEncounter?.preventGameStatsUpdates) { - gScene.gameData.gameStats.pokemonDefeated++; + if (!isMysteryEncounter || !globalScene.currentBattle.mysteryEncounter?.preventGameStatsUpdates) { + globalScene.gameData.gameStats.pokemonDefeated++; } const expValue = this.getPokemon().getExpValue(); - gScene.applyPartyExp(expValue, true); + globalScene.applyPartyExp(expValue, true); if (isMysteryEncounter) { handleMysteryEncounterVictory(false, this.isExpOnly); return this.end(); } - if (!gScene.getEnemyParty().find(p => gScene.currentBattle.battleType === BattleType.WILD ? p.isOnField() : !p?.isFainted(true))) { - gScene.pushPhase(new BattleEndPhase()); - if (gScene.currentBattle.battleType === BattleType.TRAINER) { - gScene.pushPhase(new TrainerVictoryPhase()); + if (!globalScene.getEnemyParty().find(p => globalScene.currentBattle.battleType === BattleType.WILD ? p.isOnField() : !p?.isFainted(true))) { + globalScene.pushPhase(new BattleEndPhase()); + if (globalScene.currentBattle.battleType === BattleType.TRAINER) { + globalScene.pushPhase(new TrainerVictoryPhase()); } - if (gScene.gameMode.isEndless || !gScene.gameMode.isWaveFinal(gScene.currentBattle.waveIndex)) { - gScene.pushPhase(new EggLapsePhase()); - if (gScene.gameMode.isClassic && gScene.currentBattle.waveIndex === ClassicFixedBossWaves.EVIL_BOSS_2) { + if (globalScene.gameMode.isEndless || !globalScene.gameMode.isWaveFinal(globalScene.currentBattle.waveIndex)) { + globalScene.pushPhase(new EggLapsePhase()); + if (globalScene.gameMode.isClassic && globalScene.currentBattle.waveIndex === ClassicFixedBossWaves.EVIL_BOSS_2) { // Should get Lock Capsule on 165 before shop phase so it can be used in the rewards shop - gScene.pushPhase(new ModifierRewardPhase(modifierTypes.LOCK_CAPSULE)); + globalScene.pushPhase(new ModifierRewardPhase(modifierTypes.LOCK_CAPSULE)); } - if (gScene.currentBattle.waveIndex % 10) { - gScene.pushPhase(new SelectModifierPhase(undefined, undefined, this.getFixedBattleCustomModifiers())); - } else if (gScene.gameMode.isDaily) { - gScene.pushPhase(new ModifierRewardPhase(modifierTypes.EXP_CHARM)); - if (gScene.currentBattle.waveIndex > 10 && !gScene.gameMode.isWaveFinal(gScene.currentBattle.waveIndex)) { - gScene.pushPhase(new ModifierRewardPhase(modifierTypes.GOLDEN_POKEBALL)); + if (globalScene.currentBattle.waveIndex % 10) { + globalScene.pushPhase(new SelectModifierPhase(undefined, undefined, this.getFixedBattleCustomModifiers())); + } else if (globalScene.gameMode.isDaily) { + globalScene.pushPhase(new ModifierRewardPhase(modifierTypes.EXP_CHARM)); + if (globalScene.currentBattle.waveIndex > 10 && !globalScene.gameMode.isWaveFinal(globalScene.currentBattle.waveIndex)) { + globalScene.pushPhase(new ModifierRewardPhase(modifierTypes.GOLDEN_POKEBALL)); } } else { - const superExpWave = !gScene.gameMode.isEndless ? (gScene.offsetGym ? 0 : 20) : 10; - if (gScene.gameMode.isEndless && gScene.currentBattle.waveIndex === 10) { - gScene.pushPhase(new ModifierRewardPhase(modifierTypes.EXP_SHARE)); + const superExpWave = !globalScene.gameMode.isEndless ? (globalScene.offsetGym ? 0 : 20) : 10; + if (globalScene.gameMode.isEndless && globalScene.currentBattle.waveIndex === 10) { + globalScene.pushPhase(new ModifierRewardPhase(modifierTypes.EXP_SHARE)); } - if (gScene.currentBattle.waveIndex <= 750 && (gScene.currentBattle.waveIndex <= 500 || (gScene.currentBattle.waveIndex % 30) === superExpWave)) { - gScene.pushPhase(new ModifierRewardPhase((gScene.currentBattle.waveIndex % 30) !== superExpWave || gScene.currentBattle.waveIndex > 250 ? modifierTypes.EXP_CHARM : modifierTypes.SUPER_EXP_CHARM)); + if (globalScene.currentBattle.waveIndex <= 750 && (globalScene.currentBattle.waveIndex <= 500 || (globalScene.currentBattle.waveIndex % 30) === superExpWave)) { + globalScene.pushPhase(new ModifierRewardPhase((globalScene.currentBattle.waveIndex % 30) !== superExpWave || globalScene.currentBattle.waveIndex > 250 ? modifierTypes.EXP_CHARM : modifierTypes.SUPER_EXP_CHARM)); } - if (gScene.currentBattle.waveIndex <= 150 && !(gScene.currentBattle.waveIndex % 50)) { - gScene.pushPhase(new ModifierRewardPhase(modifierTypes.GOLDEN_POKEBALL)); + if (globalScene.currentBattle.waveIndex <= 150 && !(globalScene.currentBattle.waveIndex % 50)) { + globalScene.pushPhase(new ModifierRewardPhase(modifierTypes.GOLDEN_POKEBALL)); } - if (gScene.gameMode.isEndless && !(gScene.currentBattle.waveIndex % 50)) { - gScene.pushPhase(new ModifierRewardPhase(!(gScene.currentBattle.waveIndex % 250) ? modifierTypes.VOUCHER_PREMIUM : modifierTypes.VOUCHER_PLUS)); - gScene.pushPhase(new AddEnemyBuffModifierPhase()); + if (globalScene.gameMode.isEndless && !(globalScene.currentBattle.waveIndex % 50)) { + globalScene.pushPhase(new ModifierRewardPhase(!(globalScene.currentBattle.waveIndex % 250) ? modifierTypes.VOUCHER_PREMIUM : modifierTypes.VOUCHER_PLUS)); + globalScene.pushPhase(new AddEnemyBuffModifierPhase()); } } - gScene.pushPhase(new NewBattlePhase()); + globalScene.pushPhase(new NewBattlePhase()); } else { - gScene.currentBattle.battleType = BattleType.CLEAR; - gScene.score += gScene.gameMode.getClearScoreBonus(); - gScene.updateScoreText(); - gScene.pushPhase(new GameOverPhase(true)); + globalScene.currentBattle.battleType = BattleType.CLEAR; + globalScene.score += globalScene.gameMode.getClearScoreBonus(); + globalScene.updateScoreText(); + globalScene.pushPhase(new GameOverPhase(true)); } } @@ -91,8 +91,8 @@ export class VictoryPhase extends PokemonPhase { * will pass those settings to the upcoming {@linkcode SelectModifierPhase}`. */ getFixedBattleCustomModifiers(): CustomModifierSettings | undefined { - const gameMode = gScene.gameMode; - const waveIndex = gScene.currentBattle.waveIndex; + const gameMode = globalScene.gameMode; + const waveIndex = globalScene.currentBattle.waveIndex; if (gameMode.isFixedBattle(waveIndex)) { return gameMode.getFixedBattle(waveIndex).customModifierRewardSettings; } diff --git a/src/phases/weather-effect-phase.ts b/src/phases/weather-effect-phase.ts index e209fa7cfd6..0b48e75e8f3 100644 --- a/src/phases/weather-effect-phase.ts +++ b/src/phases/weather-effect-phase.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { applyPreWeatherEffectAbAttrs, SuppressWeatherEffectAbAttr, PreWeatherDamageAbAttr, applyAbAttrs, BlockNonDirectDamageAbAttr, applyPostWeatherLapseAbAttrs, PostWeatherLapseAbAttr } from "#app/data/ability"; import { CommonAnim } from "#app/data/battle-anims"; import { Weather, getWeatherDamageMessage, getWeatherLapseMessage } from "#app/data/weather"; @@ -12,13 +12,13 @@ export class WeatherEffectPhase extends CommonAnimPhase { public weather: Weather | null; constructor() { - super(undefined, undefined, CommonAnim.SUNNY + ((gScene?.arena?.weather?.weatherType || WeatherType.NONE) - 1)); - this.weather = gScene?.arena?.weather; + super(undefined, undefined, CommonAnim.SUNNY + ((globalScene?.arena?.weather?.weatherType || WeatherType.NONE) - 1)); + this.weather = globalScene?.arena?.weather; } start() { // Update weather state with any changes that occurred during the turn - this.weather = gScene?.arena?.weather; + this.weather = globalScene?.arena?.weather; if (!this.weather) { this.end(); @@ -46,7 +46,7 @@ export class WeatherEffectPhase extends CommonAnimPhase { const damage = Utils.toDmgValue(pokemon.getMaxHp() / 16); - gScene.queueMessage(getWeatherDamageMessage(this.weather?.weatherType!, pokemon)!); // TODO: are those bangs correct? + globalScene.queueMessage(getWeatherDamageMessage(this.weather?.weatherType!, pokemon)!); // TODO: are those bangs correct? pokemon.damageAndUpdate(damage, HitResult.EFFECTIVE, false, false, true); }; @@ -59,7 +59,7 @@ export class WeatherEffectPhase extends CommonAnimPhase { } } - gScene.ui.showText(getWeatherLapseMessage(this.weather.weatherType)!, null, () => { // TODO: is this bang correct? + globalScene.ui.showText(getWeatherLapseMessage(this.weather.weatherType)!, null, () => { // TODO: is this bang correct? this.executeForAll((pokemon: Pokemon) => applyPostWeatherLapseAbAttrs(PostWeatherLapseAbAttr, pokemon, this.weather)); super.start(); diff --git a/src/pipelines/field-sprite.ts b/src/pipelines/field-sprite.ts index cb3308403dd..b51ed847982 100644 --- a/src/pipelines/field-sprite.ts +++ b/src/pipelines/field-sprite.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { TerrainType, getTerrainColor } from "../data/terrain"; import * as Utils from "../utils"; @@ -232,16 +232,16 @@ export default class FieldSpritePipeline extends Phaser.Renderer.WebGL.Pipelines const ignoreTimeTint = data["ignoreTimeTint"] as boolean; const terrainColorRatio = data["terrainColorRatio"] as number || 0; - const time = gScene.currentBattle?.waveIndex - ? ((gScene.currentBattle.waveIndex + gScene.waveCycleOffset) % 40) / 40 // ((new Date().getSeconds() * 1000 + new Date().getMilliseconds()) % 10000) / 10000 + const time = globalScene.currentBattle?.waveIndex + ? ((globalScene.currentBattle.waveIndex + globalScene.waveCycleOffset) % 40) / 40 // ((new Date().getSeconds() * 1000 + new Date().getMilliseconds()) % 10000) / 10000 : Utils.getCurrentTime(); this.set1f("time", time); this.set1i("ignoreTimeTint", ignoreTimeTint ? 1 : 0); - this.set1i("isOutside", gScene.arena.isOutside() ? 1 : 0); - this.set3fv("dayTint", gScene.arena.getDayTint().map(c => c / 255)); - this.set3fv("duskTint", gScene.arena.getDuskTint().map(c => c / 255)); - this.set3fv("nightTint", gScene.arena.getNightTint().map(c => c / 255)); - this.set3fv("terrainColor", getTerrainColor(gScene.arena.terrain?.terrainType || TerrainType.NONE).map(c => c / 255)); + this.set1i("isOutside", globalScene.arena.isOutside() ? 1 : 0); + this.set3fv("dayTint", globalScene.arena.getDayTint().map(c => c / 255)); + this.set3fv("duskTint", globalScene.arena.getDuskTint().map(c => c / 255)); + this.set3fv("nightTint", globalScene.arena.getNightTint().map(c => c / 255)); + this.set3fv("terrainColor", getTerrainColor(globalScene.arena.terrain?.terrainType || TerrainType.NONE).map(c => c / 255)); this.set1f("terrainColorRatio", terrainColorRatio); } diff --git a/src/system/achv.ts b/src/system/achv.ts index 6c98fa03c88..8df506f9c5b 100644 --- a/src/system/achv.ts +++ b/src/system/achv.ts @@ -8,7 +8,7 @@ import { Challenge, FreshStartChallenge, SingleGenerationChallenge, SingleTypeCh import { ConditionFn } from "#app/@types/common"; import { Stat, getShortenedStatKey } from "#app/enums/stat"; import { Challenges } from "#app/enums/challenges"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export enum AchvTier { COMMON, @@ -91,7 +91,7 @@ export class MoneyAchv extends Achv { moneyAmount: integer; constructor(localizationKey: string, name: string, moneyAmount: integer, iconImage: string, score: integer) { - super(localizationKey, name, "", iconImage, score, (_args: any[]) => gScene.money >= this.moneyAmount); + super(localizationKey, name, "", iconImage, score, (_args: any[]) => globalScene.money >= this.moneyAmount); this.moneyAmount = moneyAmount; } } @@ -100,7 +100,7 @@ export class RibbonAchv extends Achv { ribbonAmount: integer; constructor(localizationKey: string, name: string, ribbonAmount: integer, iconImage: string, score: integer) { - super(localizationKey, name, "", iconImage, score, (_args: any[]) => gScene.gameData.gameStats.ribbonsOwned >= this.ribbonAmount); + super(localizationKey, name, "", iconImage, score, (_args: any[]) => globalScene.gameData.gameStats.ribbonsOwned >= this.ribbonAmount); this.ribbonAmount = ribbonAmount; } } @@ -327,36 +327,36 @@ export const achvs = { HATCH_SHINY: new Achv("HATCH_SHINY", "", "HATCH_SHINY.description", "golden_egg", 100).setSecret(), HIDDEN_ABILITY: new Achv("HIDDEN_ABILITY", "", "HIDDEN_ABILITY.description", "ability_charm", 75), PERFECT_IVS: new Achv("PERFECT_IVS", "", "PERFECT_IVS.description", "blunder_policy", 100), - CLASSIC_VICTORY: new Achv("CLASSIC_VICTORY", "", "CLASSIC_VICTORY.description", "relic_crown", 150, (_) => gScene.gameData.gameStats.sessionsWon === 0), - UNEVOLVED_CLASSIC_VICTORY: new Achv("UNEVOLVED_CLASSIC_VICTORY", "", "UNEVOLVED_CLASSIC_VICTORY.description", "eviolite", 175, (_) => gScene.getParty().some(p => p.getSpeciesForm(true).speciesId in pokemonEvolutions)), - MONO_GEN_ONE_VICTORY: new ChallengeAchv("MONO_GEN_ONE", "", "MONO_GEN_ONE.description", "ribbon_gen1", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 1 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GEN_TWO_VICTORY: new ChallengeAchv("MONO_GEN_TWO", "", "MONO_GEN_TWO.description", "ribbon_gen2", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 2 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GEN_THREE_VICTORY: new ChallengeAchv("MONO_GEN_THREE", "", "MONO_GEN_THREE.description", "ribbon_gen3", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 3 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GEN_FOUR_VICTORY: new ChallengeAchv("MONO_GEN_FOUR", "", "MONO_GEN_FOUR.description", "ribbon_gen4", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 4 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GEN_FIVE_VICTORY: new ChallengeAchv("MONO_GEN_FIVE", "", "MONO_GEN_FIVE.description", "ribbon_gen5", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 5 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GEN_SIX_VICTORY: new ChallengeAchv("MONO_GEN_SIX", "", "MONO_GEN_SIX.description", "ribbon_gen6", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 6 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GEN_SEVEN_VICTORY: new ChallengeAchv("MONO_GEN_SEVEN", "", "MONO_GEN_SEVEN.description", "ribbon_gen7", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 7 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GEN_EIGHT_VICTORY: new ChallengeAchv("MONO_GEN_EIGHT", "", "MONO_GEN_EIGHT.description", "ribbon_gen8", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 8 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GEN_NINE_VICTORY: new ChallengeAchv("MONO_GEN_NINE", "", "MONO_GEN_NINE.description", "ribbon_gen9", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 9 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_NORMAL: new ChallengeAchv("MONO_NORMAL", "", "MONO_NORMAL.description", "silk_scarf", 100, (c) => c instanceof SingleTypeChallenge && c.value === 1 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_FIGHTING: new ChallengeAchv("MONO_FIGHTING", "", "MONO_FIGHTING.description", "black_belt", 100, (c) => c instanceof SingleTypeChallenge && c.value === 2 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_FLYING: new ChallengeAchv("MONO_FLYING", "", "MONO_FLYING.description", "sharp_beak", 100, (c) => c instanceof SingleTypeChallenge && c.value === 3 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_POISON: new ChallengeAchv("MONO_POISON", "", "MONO_POISON.description", "poison_barb", 100, (c) => c instanceof SingleTypeChallenge && c.value === 4 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GROUND: new ChallengeAchv("MONO_GROUND", "", "MONO_GROUND.description", "soft_sand", 100, (c) => c instanceof SingleTypeChallenge && c.value === 5 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_ROCK: new ChallengeAchv("MONO_ROCK", "", "MONO_ROCK.description", "hard_stone", 100, (c) => c instanceof SingleTypeChallenge && c.value === 6 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_BUG: new ChallengeAchv("MONO_BUG", "", "MONO_BUG.description", "silver_powder", 100, (c) => c instanceof SingleTypeChallenge && c.value === 7 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GHOST: new ChallengeAchv("MONO_GHOST", "", "MONO_GHOST.description", "spell_tag", 100, (c) => c instanceof SingleTypeChallenge && c.value === 8 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_STEEL: new ChallengeAchv("MONO_STEEL", "", "MONO_STEEL.description", "metal_coat", 100, (c) => c instanceof SingleTypeChallenge && c.value === 9 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_FIRE: new ChallengeAchv("MONO_FIRE", "", "MONO_FIRE.description", "charcoal", 100, (c) => c instanceof SingleTypeChallenge && c.value === 10 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_WATER: new ChallengeAchv("MONO_WATER", "", "MONO_WATER.description", "mystic_water", 100, (c) => c instanceof SingleTypeChallenge && c.value === 11 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_GRASS: new ChallengeAchv("MONO_GRASS", "", "MONO_GRASS.description", "miracle_seed", 100, (c) => c instanceof SingleTypeChallenge && c.value === 12 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_ELECTRIC: new ChallengeAchv("MONO_ELECTRIC", "", "MONO_ELECTRIC.description", "magnet", 100, (c) => c instanceof SingleTypeChallenge && c.value === 13 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_PSYCHIC: new ChallengeAchv("MONO_PSYCHIC", "", "MONO_PSYCHIC.description", "twisted_spoon", 100, (c) => c instanceof SingleTypeChallenge && c.value === 14 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_ICE: new ChallengeAchv("MONO_ICE", "", "MONO_ICE.description", "never_melt_ice", 100, (c) => c instanceof SingleTypeChallenge && c.value === 15 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_DRAGON: new ChallengeAchv("MONO_DRAGON", "", "MONO_DRAGON.description", "dragon_fang", 100, (c) => c instanceof SingleTypeChallenge && c.value === 16 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_DARK: new ChallengeAchv("MONO_DARK", "", "MONO_DARK.description", "black_glasses", 100, (c) => c instanceof SingleTypeChallenge && c.value === 17 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - MONO_FAIRY: new ChallengeAchv("MONO_FAIRY", "", "MONO_FAIRY.description", "fairy_feather", 100, (c) => c instanceof SingleTypeChallenge && c.value === 18 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), - FRESH_START: new ChallengeAchv("FRESH_START", "", "FRESH_START.description", "reviver_seed", 100, (c) => c instanceof FreshStartChallenge && c.value > 0 && !gScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + CLASSIC_VICTORY: new Achv("CLASSIC_VICTORY", "", "CLASSIC_VICTORY.description", "relic_crown", 150, (_) => globalScene.gameData.gameStats.sessionsWon === 0), + UNEVOLVED_CLASSIC_VICTORY: new Achv("UNEVOLVED_CLASSIC_VICTORY", "", "UNEVOLVED_CLASSIC_VICTORY.description", "eviolite", 175, (_) => globalScene.getParty().some(p => p.getSpeciesForm(true).speciesId in pokemonEvolutions)), + MONO_GEN_ONE_VICTORY: new ChallengeAchv("MONO_GEN_ONE", "", "MONO_GEN_ONE.description", "ribbon_gen1", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 1 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GEN_TWO_VICTORY: new ChallengeAchv("MONO_GEN_TWO", "", "MONO_GEN_TWO.description", "ribbon_gen2", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 2 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GEN_THREE_VICTORY: new ChallengeAchv("MONO_GEN_THREE", "", "MONO_GEN_THREE.description", "ribbon_gen3", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 3 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GEN_FOUR_VICTORY: new ChallengeAchv("MONO_GEN_FOUR", "", "MONO_GEN_FOUR.description", "ribbon_gen4", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 4 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GEN_FIVE_VICTORY: new ChallengeAchv("MONO_GEN_FIVE", "", "MONO_GEN_FIVE.description", "ribbon_gen5", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 5 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GEN_SIX_VICTORY: new ChallengeAchv("MONO_GEN_SIX", "", "MONO_GEN_SIX.description", "ribbon_gen6", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 6 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GEN_SEVEN_VICTORY: new ChallengeAchv("MONO_GEN_SEVEN", "", "MONO_GEN_SEVEN.description", "ribbon_gen7", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 7 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GEN_EIGHT_VICTORY: new ChallengeAchv("MONO_GEN_EIGHT", "", "MONO_GEN_EIGHT.description", "ribbon_gen8", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 8 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GEN_NINE_VICTORY: new ChallengeAchv("MONO_GEN_NINE", "", "MONO_GEN_NINE.description", "ribbon_gen9", 100, (c) => c instanceof SingleGenerationChallenge && c.value === 9 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_NORMAL: new ChallengeAchv("MONO_NORMAL", "", "MONO_NORMAL.description", "silk_scarf", 100, (c) => c instanceof SingleTypeChallenge && c.value === 1 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_FIGHTING: new ChallengeAchv("MONO_FIGHTING", "", "MONO_FIGHTING.description", "black_belt", 100, (c) => c instanceof SingleTypeChallenge && c.value === 2 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_FLYING: new ChallengeAchv("MONO_FLYING", "", "MONO_FLYING.description", "sharp_beak", 100, (c) => c instanceof SingleTypeChallenge && c.value === 3 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_POISON: new ChallengeAchv("MONO_POISON", "", "MONO_POISON.description", "poison_barb", 100, (c) => c instanceof SingleTypeChallenge && c.value === 4 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GROUND: new ChallengeAchv("MONO_GROUND", "", "MONO_GROUND.description", "soft_sand", 100, (c) => c instanceof SingleTypeChallenge && c.value === 5 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_ROCK: new ChallengeAchv("MONO_ROCK", "", "MONO_ROCK.description", "hard_stone", 100, (c) => c instanceof SingleTypeChallenge && c.value === 6 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_BUG: new ChallengeAchv("MONO_BUG", "", "MONO_BUG.description", "silver_powder", 100, (c) => c instanceof SingleTypeChallenge && c.value === 7 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GHOST: new ChallengeAchv("MONO_GHOST", "", "MONO_GHOST.description", "spell_tag", 100, (c) => c instanceof SingleTypeChallenge && c.value === 8 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_STEEL: new ChallengeAchv("MONO_STEEL", "", "MONO_STEEL.description", "metal_coat", 100, (c) => c instanceof SingleTypeChallenge && c.value === 9 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_FIRE: new ChallengeAchv("MONO_FIRE", "", "MONO_FIRE.description", "charcoal", 100, (c) => c instanceof SingleTypeChallenge && c.value === 10 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_WATER: new ChallengeAchv("MONO_WATER", "", "MONO_WATER.description", "mystic_water", 100, (c) => c instanceof SingleTypeChallenge && c.value === 11 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_GRASS: new ChallengeAchv("MONO_GRASS", "", "MONO_GRASS.description", "miracle_seed", 100, (c) => c instanceof SingleTypeChallenge && c.value === 12 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_ELECTRIC: new ChallengeAchv("MONO_ELECTRIC", "", "MONO_ELECTRIC.description", "magnet", 100, (c) => c instanceof SingleTypeChallenge && c.value === 13 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_PSYCHIC: new ChallengeAchv("MONO_PSYCHIC", "", "MONO_PSYCHIC.description", "twisted_spoon", 100, (c) => c instanceof SingleTypeChallenge && c.value === 14 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_ICE: new ChallengeAchv("MONO_ICE", "", "MONO_ICE.description", "never_melt_ice", 100, (c) => c instanceof SingleTypeChallenge && c.value === 15 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_DRAGON: new ChallengeAchv("MONO_DRAGON", "", "MONO_DRAGON.description", "dragon_fang", 100, (c) => c instanceof SingleTypeChallenge && c.value === 16 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_DARK: new ChallengeAchv("MONO_DARK", "", "MONO_DARK.description", "black_glasses", 100, (c) => c instanceof SingleTypeChallenge && c.value === 17 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + MONO_FAIRY: new ChallengeAchv("MONO_FAIRY", "", "MONO_FAIRY.description", "fairy_feather", 100, (c) => c instanceof SingleTypeChallenge && c.value === 18 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), + FRESH_START: new ChallengeAchv("FRESH_START", "", "FRESH_START.description", "reviver_seed", 100, (c) => c instanceof FreshStartChallenge && c.value > 0 && !globalScene.gameMode.challenges.some(c => c.id === Challenges.INVERSE_BATTLE && c.value > 0)), INVERSE_BATTLE: new ChallengeAchv("INVERSE_BATTLE", "", "INVERSE_BATTLE.description", "inverse", 100, c => c instanceof InverseBattleChallenge && c.value > 0), BREEDERS_IN_SPACE: new Achv("BREEDERS_IN_SPACE", "", "BREEDERS_IN_SPACE.description", "moon_stone", 100).setSecret(), }; diff --git a/src/system/game-data.ts b/src/system/game-data.ts index db73faccc0b..9b266a4b058 100644 --- a/src/system/game-data.ts +++ b/src/system/game-data.ts @@ -1,5 +1,5 @@ import i18next from "i18next"; -import { bypassLogin, gScene, PokeballCounts } from "#app/battle-scene"; +import { bypassLogin, globalScene, PokeballCounts } from "#app/battle-scene"; import Pokemon, { EnemyPokemon, PlayerPokemon } from "#app/field/pokemon"; import { pokemonPrevolutions } from "#app/data/balance/pokemon-evolutions"; import PokemonSpecies, { allSpecies, getPokemonSpecies, noStarterFormKeys } from "#app/data/pokemon-species"; @@ -364,7 +364,7 @@ export class GameData { voucherUnlocks: this.voucherUnlocks, voucherCounts: this.voucherCounts, eggs: this.eggs.map(e => new EggData(e)), - gameVersion: gScene.game.config.gameVersion, + gameVersion: globalScene.game.config.gameVersion, timestamp: new Date().getTime(), eggPity: this.eggPity.slice(0), unlockPity: this.unlockPity.slice(0) @@ -385,7 +385,7 @@ export class GameData { public saveSystem(): Promise { return new Promise(resolve => { - gScene.ui.savingIcon.show(); + globalScene.ui.savingIcon.show(); const data = this.getSystemSaveData(); const maxIntAttrValue = 0x80000000; @@ -397,11 +397,11 @@ export class GameData { Utils.apiPost(`savedata/system/update?clientSessionId=${clientSessionId}`, systemData, undefined, true) .then(response => response.text()) .then(error => { - gScene.ui.savingIcon.hide(); + globalScene.ui.savingIcon.hide(); if (error) { if (error.startsWith("session out of date")) { - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new ReloadSessionPhase()); + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new ReloadSessionPhase()); } console.error(error); return resolve(false); @@ -409,7 +409,7 @@ export class GameData { resolve(true); }); } else { - gScene.ui.savingIcon.hide(); + globalScene.ui.savingIcon.hide(); resolve(true); } @@ -430,10 +430,10 @@ export class GameData { .then(response => { if (!response.length || response[0] !== "{") { if (response.startsWith("sql: no rows in result set")) { - gScene.queueMessage("Save data could not be found. If this is a new account, you can safely ignore this message.", null, true); + globalScene.queueMessage("Save data could not be found. If this is a new account, you can safely ignore this message.", null, true); return resolve(true); } else if (response.indexOf("Too many connections") > -1) { - gScene.queueMessage("Too many people are trying to connect and the server is overloaded. Please try again later.", null, true); + globalScene.queueMessage("Too many people are trying to connect and the server is overloaded. Please try again later.", null, true); return resolve(false); } console.error(response); @@ -704,8 +704,8 @@ export class GameData { .then(response => response.json()); if (!response.valid) { - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new ReloadSessionPhase(JSON.stringify(response.systemData))); + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new ReloadSessionPhase(JSON.stringify(response.systemData))); this.clearLocalData(); return false; } @@ -738,7 +738,7 @@ export class GameData { setSetting(setting, valueIndex); settings[setting] = valueIndex; - settings["gameVersion"] = gScene.game.config.gameVersion; + settings["gameVersion"] = globalScene.game.config.gameVersion; localStorage.setItem("settings", JSON.stringify(settings)); @@ -784,7 +784,7 @@ export class GameData { const mappingConfigs = JSON.parse(localStorage.getItem("mappingConfigs")!); // Parse the existing 'mappingConfigs' from localStorage // TODO: is this bang correct? for (const key of Object.keys(mappingConfigs)) {// Iterate over the keys of the mapping configurations - gScene.inputController.injectConfig(key, mappingConfigs[key]); + globalScene.inputController.injectConfig(key, mappingConfigs[key]); } // Inject each configuration into the input controller for the corresponding key return true; // Return true to indicate the operation was successful @@ -795,7 +795,7 @@ export class GameData { return false; } // If 'mappingConfigs' does not exist, return false localStorage.removeItem("mappingConfigs"); - gScene.inputController.resetConfigs(); + globalScene.inputController.resetConfigs(); return true; // TODO: is `true` the correct return value? } @@ -942,25 +942,25 @@ export class GameData { public getSessionSaveData(): SessionSaveData { return { - seed: gScene.seed, - playTime: gScene.sessionPlayTime, - gameMode: gScene.gameMode.modeId, - party: gScene.getParty().map(p => new PokemonData(p)), - enemyParty: gScene.getEnemyParty().map(p => new PokemonData(p)), - modifiers: gScene.findModifiers(() => true).map(m => new PersistentModifierData(m, true)), - enemyModifiers: gScene.findModifiers(() => true, false).map(m => new PersistentModifierData(m, false)), - arena: new ArenaData(gScene.arena), - pokeballCounts: gScene.pokeballCounts, - money: Math.floor(gScene.money), - score: gScene.score, - waveIndex: gScene.currentBattle.waveIndex, - battleType: gScene.currentBattle.battleType, - trainer: gScene.currentBattle.battleType === BattleType.TRAINER ? new TrainerData(gScene.currentBattle.trainer) : null, - gameVersion: gScene.game.config.gameVersion, + seed: globalScene.seed, + playTime: globalScene.sessionPlayTime, + gameMode: globalScene.gameMode.modeId, + party: globalScene.getParty().map(p => new PokemonData(p)), + enemyParty: globalScene.getEnemyParty().map(p => new PokemonData(p)), + modifiers: globalScene.findModifiers(() => true).map(m => new PersistentModifierData(m, true)), + enemyModifiers: globalScene.findModifiers(() => true, false).map(m => new PersistentModifierData(m, false)), + arena: new ArenaData(globalScene.arena), + pokeballCounts: globalScene.pokeballCounts, + money: Math.floor(globalScene.money), + score: globalScene.score, + waveIndex: globalScene.currentBattle.waveIndex, + battleType: globalScene.currentBattle.battleType, + trainer: globalScene.currentBattle.battleType === BattleType.TRAINER ? new TrainerData(globalScene.currentBattle.trainer) : null, + gameVersion: globalScene.game.config.gameVersion, timestamp: new Date().getTime(), - challenges: gScene.gameMode.challenges.map(c => new ChallengeData(c)), - mysteryEncounterType: gScene.currentBattle.mysteryEncounter?.encounterType ?? -1, - mysteryEncounterSaveData: gScene.mysteryEncounterSaveData + challenges: globalScene.gameMode.challenges.map(c => new ChallengeData(c)), + mysteryEncounterType: globalScene.currentBattle.mysteryEncounter?.encounterType ?? -1, + mysteryEncounterSaveData: globalScene.mysteryEncounterSaveData } as SessionSaveData; } @@ -1009,22 +1009,22 @@ export class GameData { const initSessionFromData = async (sessionData: SessionSaveData) => { console.debug(sessionData); - gScene.gameMode = getGameMode(sessionData.gameMode || GameModes.CLASSIC); + globalScene.gameMode = getGameMode(sessionData.gameMode || GameModes.CLASSIC); if (sessionData.challenges) { - gScene.gameMode.challenges = sessionData.challenges.map(c => c.toChallenge()); + globalScene.gameMode.challenges = sessionData.challenges.map(c => c.toChallenge()); } - gScene.setSeed(sessionData.seed || gScene.game.config.seed[0]); - gScene.resetSeed(); + globalScene.setSeed(sessionData.seed || globalScene.game.config.seed[0]); + globalScene.resetSeed(); - console.log("Seed:", gScene.seed); + console.log("Seed:", globalScene.seed); - gScene.sessionPlayTime = sessionData.playTime || 0; - gScene.lastSavePlayTime = 0; + globalScene.sessionPlayTime = sessionData.playTime || 0; + globalScene.lastSavePlayTime = 0; const loadPokemonAssets: Promise[] = []; - const party = gScene.getParty(); + const party = globalScene.getParty(); party.splice(0, party.length); for (const p of sessionData.party) { @@ -1034,34 +1034,34 @@ export class GameData { party.push(pokemon); } - Object.keys(gScene.pokeballCounts).forEach((key: string) => { - gScene.pokeballCounts[key] = sessionData.pokeballCounts[key] || 0; + Object.keys(globalScene.pokeballCounts).forEach((key: string) => { + globalScene.pokeballCounts[key] = sessionData.pokeballCounts[key] || 0; }); if (Overrides.POKEBALL_OVERRIDE.active) { - gScene.pokeballCounts = Overrides.POKEBALL_OVERRIDE.pokeballs; + globalScene.pokeballCounts = Overrides.POKEBALL_OVERRIDE.pokeballs; } - gScene.money = Math.floor(sessionData.money || 0); - gScene.updateMoneyText(); + globalScene.money = Math.floor(sessionData.money || 0); + globalScene.updateMoneyText(); - if (gScene.money > this.gameStats.highestMoney) { - this.gameStats.highestMoney = gScene.money; + if (globalScene.money > this.gameStats.highestMoney) { + this.gameStats.highestMoney = globalScene.money; } - gScene.score = sessionData.score; - gScene.updateScoreText(); + globalScene.score = sessionData.score; + globalScene.updateScoreText(); - gScene.mysteryEncounterSaveData = new MysteryEncounterSaveData(sessionData.mysteryEncounterSaveData); + globalScene.mysteryEncounterSaveData = new MysteryEncounterSaveData(sessionData.mysteryEncounterSaveData); - gScene.newArena(sessionData.arena.biome); + globalScene.newArena(sessionData.arena.biome); const battleType = sessionData.battleType || 0; const trainerConfig = sessionData.trainer ? trainerConfigs[sessionData.trainer.trainerType] : null; const mysteryEncounterType = sessionData.mysteryEncounterType !== -1 ? sessionData.mysteryEncounterType : undefined; - const battle = gScene.newBattle(sessionData.waveIndex, battleType, sessionData.trainer, battleType === BattleType.TRAINER ? trainerConfig?.doubleOnly || sessionData.trainer?.variant === TrainerVariant.DOUBLE : sessionData.enemyParty.length > 1, mysteryEncounterType)!; // TODO: is this bang correct? + const battle = globalScene.newBattle(sessionData.waveIndex, battleType, sessionData.trainer, battleType === BattleType.TRAINER ? trainerConfig?.doubleOnly || sessionData.trainer?.variant === TrainerVariant.DOUBLE : sessionData.enemyParty.length > 1, mysteryEncounterType)!; // TODO: is this bang correct? battle.enemyLevels = sessionData.enemyParty.map(p => p.level); - gScene.arena.init(); + globalScene.arena.init(); sessionData.enemyParty.forEach((enemyData, e) => { const enemyPokemon = enemyData.toPokemon(battleType, e, sessionData.trainer?.variant === TrainerVariant.DOUBLE) as EnemyPokemon; @@ -1073,20 +1073,20 @@ export class GameData { loadPokemonAssets.push(enemyPokemon.loadAssets()); }); - gScene.arena.weather = sessionData.arena.weather; - gScene.arena.eventTarget.dispatchEvent(new WeatherChangedEvent(WeatherType.NONE, gScene.arena.weather?.weatherType!, gScene.arena.weather?.turnsLeft!)); // TODO: is this bang correct? + globalScene.arena.weather = sessionData.arena.weather; + globalScene.arena.eventTarget.dispatchEvent(new WeatherChangedEvent(WeatherType.NONE, globalScene.arena.weather?.weatherType!, globalScene.arena.weather?.turnsLeft!)); // TODO: is this bang correct? - gScene.arena.terrain = sessionData.arena.terrain; - gScene.arena.eventTarget.dispatchEvent(new TerrainChangedEvent(TerrainType.NONE, gScene.arena.terrain?.terrainType!, gScene.arena.terrain?.turnsLeft!)); // TODO: is this bang correct? + globalScene.arena.terrain = sessionData.arena.terrain; + globalScene.arena.eventTarget.dispatchEvent(new TerrainChangedEvent(TerrainType.NONE, globalScene.arena.terrain?.terrainType!, globalScene.arena.terrain?.turnsLeft!)); // TODO: is this bang correct? - gScene.arena.tags = sessionData.arena.tags; - if (gScene.arena.tags) { - for (const tag of gScene.arena.tags) { + globalScene.arena.tags = sessionData.arena.tags; + if (globalScene.arena.tags) { + for (const tag of globalScene.arena.tags) { if (tag instanceof ArenaTrapTag) { const { tagType, side, turnCount, layers, maxLayers } = tag as ArenaTrapTag; - gScene.arena.eventTarget.dispatchEvent(new TagAddedEvent(tagType, side, turnCount, layers, maxLayers)); + globalScene.arena.eventTarget.dispatchEvent(new TagAddedEvent(tagType, side, turnCount, layers, maxLayers)); } else { - gScene.arena.eventTarget.dispatchEvent(new TagAddedEvent(tag.tagType, tag.side, tag.turnCount)); + globalScene.arena.eventTarget.dispatchEvent(new TagAddedEvent(tag.tagType, tag.side, tag.turnCount)); } } } @@ -1094,20 +1094,20 @@ export class GameData { for (const modifierData of sessionData.modifiers) { const modifier = modifierData.toModifier(Modifier[modifierData.className]); if (modifier) { - gScene.addModifier(modifier, true); + globalScene.addModifier(modifier, true); } } - gScene.updateModifiers(true); + globalScene.updateModifiers(true); for (const enemyModifierData of sessionData.enemyModifiers) { const modifier = enemyModifierData.toModifier(Modifier[enemyModifierData.className]); if (modifier) { - gScene.addEnemyModifier(modifier, true); + globalScene.addEnemyModifier(modifier, true); } } - gScene.updateModifiers(false); + globalScene.updateModifiers(false); Promise.all(loadPokemonAssets).then(() => resolve(true)); }; @@ -1155,8 +1155,8 @@ export class GameData { }).then(error => { if (error) { if (error.startsWith("session out of date")) { - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new ReloadSessionPhase()); + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new ReloadSessionPhase()); } console.error(error); resolve(false); @@ -1224,8 +1224,8 @@ export class GameData { result = [ true, jsonResponse.success ?? false ]; } else { if (jsonResponse && jsonResponse.error?.startsWith("session out of date")) { - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new ReloadSessionPhase()); + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new ReloadSessionPhase()); } console.error(jsonResponse); @@ -1240,12 +1240,6 @@ export class GameData { parseSessionData(dataStr: string): SessionSaveData { const sessionData = JSON.parse(dataStr, (k: string, v: any) => { - /*const versions = [ gScene.game.config.gameVersion, sessionData.gameVersion || '0.0.0' ]; - - if (versions[0] !== versions[1]) { - const [ versionNumbers, oldVersionNumbers ] = versions.map(ver => ver.split('.').map(v => parseInt(v))); - }*/ - if (k === "party" || k === "enemyParty") { const ret: PokemonData[] = []; if (v === null) { @@ -1317,10 +1311,10 @@ export class GameData { return resolve(false); } if (sync) { - gScene.ui.savingIcon.show(); + globalScene.ui.savingIcon.show(); } const sessionData = useCachedSession ? - this.parseSessionData(decrypt(localStorage.getItem(`sessionData${gScene.sessionSlotId ? gScene.sessionSlotId : ""}_${loggedInUser?.username}`)!, bypassLogin)) // TODO: is this bang correct? + this.parseSessionData(decrypt(localStorage.getItem(`sessionData${globalScene.sessionSlotId ? globalScene.sessionSlotId : ""}_${loggedInUser?.username}`)!, bypassLogin)) // TODO: is this bang correct? : this.getSessionSaveData(); const maxIntAttrValue = 0x80000000; @@ -1329,13 +1323,13 @@ export class GameData { const request = { system: systemData, session: sessionData, - sessionSlotId: gScene.sessionSlotId, + sessionSlotId: globalScene.sessionSlotId, clientSessionId: clientSessionId }; localStorage.setItem(`data_${loggedInUser?.username}`, encrypt(JSON.stringify(systemData, (k: any, v: any) => typeof v === "bigint" ? v <= maxIntAttrValue ? Number(v) : v.toString() : v), bypassLogin)); - localStorage.setItem(`sessionData${gScene.sessionSlotId ? gScene.sessionSlotId : ""}_${loggedInUser?.username}`, encrypt(JSON.stringify(sessionData), bypassLogin)); + localStorage.setItem(`sessionData${globalScene.sessionSlotId ? globalScene.sessionSlotId : ""}_${loggedInUser?.username}`, encrypt(JSON.stringify(sessionData), bypassLogin)); console.debug("Session data saved"); @@ -1344,13 +1338,13 @@ export class GameData { .then(response => response.text()) .then(error => { if (sync) { - gScene.lastSavePlayTime = 0; - gScene.ui.savingIcon.hide(); + globalScene.lastSavePlayTime = 0; + globalScene.ui.savingIcon.hide(); } if (error) { if (error.startsWith("session out of date")) { - gScene.clearPhaseQueue(); - gScene.unshiftPhase(new ReloadSessionPhase()); + globalScene.clearPhaseQueue(); + globalScene.unshiftPhase(new ReloadSessionPhase()); } console.error(error); return resolve(false); @@ -1359,7 +1353,7 @@ export class GameData { }); } else { this.verify().then(success => { - gScene.ui.savingIcon.hide(); + globalScene.ui.savingIcon.hide(); resolve(success); }); } @@ -1459,15 +1453,15 @@ export class GameData { console.error(ex); } - const displayError = (error: string) => gScene.ui.showText(error, null, () => gScene.ui.showText("", 0), Utils.fixedInt(1500)); + const displayError = (error: string) => globalScene.ui.showText(error, null, () => globalScene.ui.showText("", 0), Utils.fixedInt(1500)); dataName = dataName!; // tell TS compiler that dataName is defined! if (!valid) { - return gScene.ui.showText(`Your ${dataName} data could not be loaded. It may be corrupted.`, null, () => gScene.ui.showText("", 0), Utils.fixedInt(1500)); + return globalScene.ui.showText(`Your ${dataName} data could not be loaded. It may be corrupted.`, null, () => globalScene.ui.showText("", 0), Utils.fixedInt(1500)); } - gScene.ui.showText(`Your ${dataName} data will be overridden and the page will reload. Proceed?`, null, () => { - gScene.ui.setOverlayMode(Mode.CONFIRM, () => { + globalScene.ui.showText(`Your ${dataName} data will be overridden and the page will reload. Proceed?`, null, () => { + globalScene.ui.setOverlayMode(Mode.CONFIRM, () => { localStorage.setItem(dataKey, encrypt(dataStr, bypassLogin)); if (!bypassLogin && dataType < GameDataType.SETTINGS) { @@ -1495,8 +1489,8 @@ export class GameData { window.location = window.location; } }, () => { - gScene.ui.revertMode(); - gScene.ui.showText("", 0); + globalScene.ui.revertMode(); + globalScene.ui.showText("", 0); }, false, -98); }); }; @@ -1506,9 +1500,6 @@ export class GameData { } ); saveFile.click(); - /*(gScene.plugins.get('rexfilechooserplugin') as FileChooserPlugin).open({ accept: '.prsv' }) - .then(result => { - });*/ } private initDexData(): void { @@ -1524,7 +1515,7 @@ export class GameData { const defaultStarterNatures: Nature[] = []; - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { const neutralNatures = [ Nature.HARDY, Nature.DOCILE, Nature.SERIOUS, Nature.BASHFUL, Nature.QUIRKY ]; for (let s = 0; s < defaultStarterSpecies.length; s++) { defaultStarterNatures.push(Utils.randSeedItem(neutralNatures)); @@ -1568,7 +1559,7 @@ export class GameData { setPokemonSeen(pokemon: Pokemon, incrementCount: boolean = true, trainer: boolean = false): void { // Some Mystery Encounters block updates to these stats - if (gScene.currentBattle?.isBattleMysteryEncounter() && gScene.currentBattle.mysteryEncounter?.preventGameStatsUpdates) { + if (globalScene.currentBattle?.isBattleMysteryEncounter() && globalScene.currentBattle.mysteryEncounter?.preventGameStatsUpdates) { return; } const dexEntry = this.dexData[pokemon.species.speciesId]; @@ -1601,7 +1592,7 @@ export class GameData { // If incrementCount === false (not a catch scenario), only update the pokemon's dex data if the Pokemon has already been marked as caught in dex // Prevents form changes, nature changes, etc. from unintentionally updating the dex data of a "rental" pokemon const speciesRootForm = pokemon.species.getRootSpeciesId(); - if (!incrementCount && !gScene.gameData.dexData[speciesRootForm].caughtAttr) { + if (!incrementCount && !globalScene.gameData.dexData[speciesRootForm].caughtAttr) { return Promise.resolve(false); } else { return this.setPokemonSpeciesCaught(pokemon, pokemon.species, incrementCount, fromEgg, showMessage); @@ -1674,7 +1665,7 @@ export class GameData { } } - if (!hasPrevolution && (!gScene.gameMode.isDaily || hasNewAttr || fromEgg)) { + if (!hasPrevolution && (!globalScene.gameMode.isDaily || hasNewAttr || fromEgg)) { this.addStarterCandy(species, (1 * (pokemon.isShiny() ? 5 * (1 << (pokemon.variant ?? 0)) : 1)) * (fromEgg || pokemon.isBoss() ? 2 : 1)); } } @@ -1693,8 +1684,8 @@ export class GameData { resolve(true); return; } - gScene.playSound("level_up_fanfare"); - gScene.ui.showText(i18next.t("battle:addedAsAStarter", { pokemonName: species.name }), null, () => checkPrevolution(true), null, true); + globalScene.playSound("level_up_fanfare"); + globalScene.ui.showText(i18next.t("battle:addedAsAStarter", { pokemonName: species.name }), null, () => checkPrevolution(true), null, true); } else { checkPrevolution(false); } @@ -1709,25 +1700,25 @@ export class GameData { } if (!this.starterData[speciesIdToIncrement].classicWinCount) { - gScene.gameData.gameStats.ribbonsOwned++; + globalScene.gameData.gameStats.ribbonsOwned++; } - const ribbonsInStats: integer = gScene.gameData.gameStats.ribbonsOwned; + const ribbonsInStats: integer = globalScene.gameData.gameStats.ribbonsOwned; if (ribbonsInStats >= 100) { - gScene.validateAchv(achvs._100_RIBBONS); + globalScene.validateAchv(achvs._100_RIBBONS); } if (ribbonsInStats >= 75) { - gScene.validateAchv(achvs._75_RIBBONS); + globalScene.validateAchv(achvs._75_RIBBONS); } if (ribbonsInStats >= 50) { - gScene.validateAchv(achvs._50_RIBBONS); + globalScene.validateAchv(achvs._50_RIBBONS); } if (ribbonsInStats >= 25) { - gScene.validateAchv(achvs._25_RIBBONS); + globalScene.validateAchv(achvs._25_RIBBONS); } if (ribbonsInStats >= 10) { - gScene.validateAchv(achvs._10_RIBBONS); + globalScene.validateAchv(achvs._10_RIBBONS); } return ++this.starterData[speciesIdToIncrement].classicWinCount; @@ -1742,8 +1733,8 @@ export class GameData { addStarterCandy(species: PokemonSpecies, count: integer): void { // Only gain candies if the Pokemon has already been marked as caught in dex (ignore "rental" pokemon) const speciesRootForm = species.getRootSpeciesId(); - if (gScene.gameData.dexData[speciesRootForm].caughtAttr) { - gScene.candyBar.showStarterSpeciesCandy(species.speciesId, count); + if (globalScene.gameData.dexData[speciesRootForm].caughtAttr) { + globalScene.candyBar.showStarterSpeciesCandy(species.speciesId, count); this.starterData[species.speciesId].candyCount += count; } } @@ -1779,19 +1770,19 @@ export class GameData { resolve(true); return; } - gScene.playSound("level_up_fanfare"); + globalScene.playSound("level_up_fanfare"); const moveName = allMoves[speciesEggMoves[speciesId][eggMoveIndex]].name; let message = prependSpeciesToMessage ? species.getName() + " " : ""; message += eggMoveIndex === 3 ? i18next.t("egg:rareEggMoveUnlock", { moveName: moveName }) : i18next.t("egg:eggMoveUnlock", { moveName: moveName }); - gScene.ui.showText(message, null, () => resolve(true), null, true); + globalScene.ui.showText(message, null, () => resolve(true), null, true); }); } updateSpeciesDexIvs(speciesId: Species, ivs: integer[]): void { let dexEntry: DexEntry; do { - dexEntry = gScene.gameData.dexData[speciesId]; + dexEntry = globalScene.gameData.dexData[speciesId]; const dexIvs = dexEntry.ivs; for (let i = 0; i < dexIvs.length; i++) { if (dexIvs[i] < ivs[i]) { @@ -1799,7 +1790,7 @@ export class GameData { } } if (dexIvs.filter(iv => iv === 31).length === 6) { - gScene.validateAchv(achvs.PERFECT_IVS); + globalScene.validateAchv(achvs.PERFECT_IVS); } } while (pokemonPrevolutions.hasOwnProperty(speciesId) && (speciesId = pokemonPrevolutions[speciesId])); } @@ -1907,7 +1898,7 @@ export class GameData { } const cost = new Utils.NumberHolder(value); - applyChallenges(gScene.gameMode, ChallengeType.STARTER_COST, speciesId, cost); + applyChallenges(globalScene.gameMode, ChallengeType.STARTER_COST, speciesId, cost); return cost.value; } diff --git a/src/system/game-speed.ts b/src/system/game-speed.ts index 1e054a0f556..657d2c36cd7 100644 --- a/src/system/game-speed.ts +++ b/src/system/game-speed.ts @@ -1,7 +1,7 @@ import SoundFade from "phaser3-rex-plugins/plugins/soundfade"; import FadeIn from "phaser3-rex-plugins/plugins/audio/fade/FadeIn"; import FadeOut from "phaser3-rex-plugins/plugins/audio/fade/FadeOut"; -import BattleScene, { gScene } from "#app/battle-scene"; +import BattleScene, { globalScene } from "#app/battle-scene"; import * as Utils from "../utils"; type FadeIn = typeof FadeIn; @@ -98,7 +98,7 @@ export function initGameSpeed() { sound: Phaser.Sound.BaseSound, duration: number, destroy?: boolean - ) => originalFadeOut(gScene, sound, transformValue(duration), destroy)) as FadeOut; + ) => originalFadeOut(globalScene, sound, transformValue(duration), destroy)) as FadeOut; const originalFadeIn = SoundFade.fadeIn; SoundFade.fadeIn = (( @@ -107,5 +107,5 @@ export function initGameSpeed() { duration: number, endVolume?: number, startVolume?: number - ) => originalFadeIn(gScene, sound, transformValue(duration), endVolume, startVolume)) as FadeIn; + ) => originalFadeIn(globalScene, sound, transformValue(duration), endVolume, startVolume)) as FadeIn; } diff --git a/src/system/modifier-data.ts b/src/system/modifier-data.ts index b5ff35f2c0d..6fbdfb649d7 100644 --- a/src/system/modifier-data.ts +++ b/src/system/modifier-data.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { PersistentModifier } from "#app/modifier/modifier"; import { GeneratedPersistentModifierType, ModifierType, ModifierTypeGenerator, getModifierTypeFuncById } from "#app/modifier/modifier-type"; @@ -38,7 +38,7 @@ export default class ModifierData { type.id = this.typeId; if (type instanceof ModifierTypeGenerator) { - type = (type as ModifierTypeGenerator).generateType(this.player ? gScene.getParty() : gScene.getEnemyField(), this.typePregenArgs); + type = (type as ModifierTypeGenerator).generateType(this.player ? globalScene.getParty() : globalScene.getEnemyField(), this.typePregenArgs); } const ret = Reflect.construct(constructor, ([ type ] as any[]).concat(this.args).concat(this.stackCount)) as PersistentModifier; diff --git a/src/system/pokemon-data.ts b/src/system/pokemon-data.ts index e6456ab53e9..57cb43e0d45 100644 --- a/src/system/pokemon-data.ts +++ b/src/system/pokemon-data.ts @@ -1,5 +1,5 @@ import { BattleType } from "../battle"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Gender } from "../data/gender"; import { Nature } from "../data/nature"; import { PokeballType } from "../data/pokeball"; @@ -166,12 +166,12 @@ export default class PokemonData { toPokemon(battleType?: BattleType, partyMemberIndex: integer = 0, double: boolean = false): Pokemon { const species = getPokemonSpecies(this.species); const ret: Pokemon = this.player - ? gScene.addPlayerPokemon(species, this.level, this.abilityIndex, this.formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this, (playerPokemon) => { + ? globalScene.addPlayerPokemon(species, this.level, this.abilityIndex, this.formIndex, this.gender, this.shiny, this.variant, this.ivs, this.nature, this, (playerPokemon) => { if (this.nickname) { playerPokemon.nickname = this.nickname; } }) - : gScene.addEnemyPokemon(species, this.level, battleType === BattleType.TRAINER ? !double || !(partyMemberIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER : TrainerSlot.NONE, this.boss, this); + : globalScene.addEnemyPokemon(species, this.level, battleType === BattleType.TRAINER ? !double || !(partyMemberIndex % 2) ? TrainerSlot.TRAINER : TrainerSlot.TRAINER_PARTNER : TrainerSlot.NONE, this.boss, this); if (this.summonData) { ret.primeSummonData(this.summonData); } diff --git a/src/system/settings/settings-gamepad.ts b/src/system/settings/settings-gamepad.ts index 36096023a33..3c0d2838c3b 100644 --- a/src/system/settings/settings-gamepad.ts +++ b/src/system/settings/settings-gamepad.ts @@ -3,7 +3,7 @@ import { Mode } from "../../ui/ui"; import { truncateString } from "../../utils"; import { Button } from "#enums/buttons"; import { SettingKeyboard } from "#app/system/settings/settings-keyboard"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export enum SettingGamepad { Controller = "CONTROLLER", @@ -85,7 +85,7 @@ export function setSettingGamepad(setting: SettingGamepad, value: integer): bool case SettingGamepad.Gamepad_Support: // if we change the value of the gamepad support, we call a method in the inputController to // activate or deactivate the controller listener - gScene.inputController.setGamepadSupport(settingGamepadOptions[setting][value] !== "Disabled"); + globalScene.inputController.setGamepadSupport(settingGamepadOptions[setting][value] !== "Disabled"); break; case SettingGamepad.Button_Action: case SettingGamepad.Button_Cancel: @@ -101,13 +101,13 @@ export function setSettingGamepad(setting: SettingGamepad, value: integer): bool case SettingGamepad.Button_Slow_Down: case SettingGamepad.Button_Submit: if (value) { - if (gScene.ui) { + if (globalScene.ui) { const cancelHandler = (success: boolean = false) : boolean => { - gScene.ui.revertMode(); - (gScene.ui.getHandler() as SettingsGamepadUiHandler).updateBindings(); + globalScene.ui.revertMode(); + (globalScene.ui.getHandler() as SettingsGamepadUiHandler).updateBindings(); return success; }; - gScene.ui.setOverlayMode(Mode.GAMEPAD_BINDING, { + globalScene.ui.setOverlayMode(Mode.GAMEPAD_BINDING, { target: setting, cancelHandler: cancelHandler, }); @@ -116,20 +116,20 @@ export function setSettingGamepad(setting: SettingGamepad, value: integer): bool break; case SettingGamepad.Controller: if (value) { - const gp = gScene.inputController.getGamepadsName(); - if (gScene.ui && gp) { + const gp = globalScene.inputController.getGamepadsName(); + if (globalScene.ui && gp) { const cancelHandler = () => { - gScene.ui.revertMode(); - (gScene.ui.getHandler() as SettingsGamepadUiHandler).setOptionCursor(Object.values(SettingGamepad).indexOf(SettingGamepad.Controller), 0, true); - (gScene.ui.getHandler() as SettingsGamepadUiHandler).updateBindings(); + globalScene.ui.revertMode(); + (globalScene.ui.getHandler() as SettingsGamepadUiHandler).setOptionCursor(Object.values(SettingGamepad).indexOf(SettingGamepad.Controller), 0, true); + (globalScene.ui.getHandler() as SettingsGamepadUiHandler).updateBindings(); return false; }; const changeGamepadHandler = (gamepad: string) => { - gScene.inputController.setChosenGamepad(gamepad); + globalScene.inputController.setChosenGamepad(gamepad); cancelHandler(); return true; }; - gScene.ui.setOverlayMode(Mode.OPTION_SELECT, { + globalScene.ui.setOverlayMode(Mode.OPTION_SELECT, { options: [ ...gp.map((g: string) => ({ label: truncateString(g, 30), // Truncate the gamepad name for display handler: () => changeGamepadHandler(g) diff --git a/src/system/settings/settings-keyboard.ts b/src/system/settings/settings-keyboard.ts index d7ca2e97e24..9922b4fbb4f 100644 --- a/src/system/settings/settings-keyboard.ts +++ b/src/system/settings/settings-keyboard.ts @@ -2,7 +2,7 @@ import { Button } from "#enums/buttons"; import { Mode } from "#app/ui/ui"; import SettingsKeyboardUiHandler from "#app/ui/settings/settings-keyboard-ui-handler"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export enum SettingKeyboard { // Default_Layout = "DEFAULT_LAYOUT", @@ -169,40 +169,19 @@ export function setSettingKeyboard(setting: SettingKeyboard, value: integer): bo case SettingKeyboard.Alt_Button_Slow_Down: case SettingKeyboard.Alt_Button_Submit: if (value) { - if (gScene.ui) { + if (globalScene.ui) { const cancelHandler = (success: boolean = false) : boolean => { - gScene.ui.revertMode(); - (gScene.ui.getHandler() as SettingsKeyboardUiHandler).updateBindings(); + globalScene.ui.revertMode(); + (globalScene.ui.getHandler() as SettingsKeyboardUiHandler).updateBindings(); return success; }; - gScene.ui.setOverlayMode(Mode.KEYBOARD_BINDING, { + globalScene.ui.setOverlayMode(Mode.KEYBOARD_BINDING, { target: setting, cancelHandler: cancelHandler, }); } } break; - // case SettingKeyboard.Default_Layout: - // if (value && gScene.ui) { - // const cancelHandler = () => { - // gScene.ui.revertMode(); - // (gScene.ui.getHandler() as SettingsKeyboardUiHandler).setOptionCursor(Object.values(SettingKeyboard).indexOf(SettingKeyboard.Default_Layout), 0, true); - // (gScene.ui.getHandler() as SettingsKeyboardUiHandler).updateBindings(); - // return false; - // }; - // const changeKeyboardHandler = (keyboardLayout: string) => { - // gScene.inputController.setChosenKeyboardLayout(keyboardLayout); - // cancelHandler(); - // return true; - // }; - // gScene.ui.setOverlayMode(Mode.OPTION_SELECT, { - // options: [{ - // label: 'Default', - // handler: changeKeyboardHandler, - // }] - // }); - // return false; - // } } return true; diff --git a/src/system/settings/settings.ts b/src/system/settings/settings.ts index 56817493c7e..dde5815a725 100644 --- a/src/system/settings/settings.ts +++ b/src/system/settings/settings.ts @@ -9,7 +9,7 @@ import { MoneyFormat } from "#enums/money-format"; import { PlayerGender } from "#enums/player-gender"; import { getIsInitialized, initI18n } from "#app/plugins/i18n"; import { ShopCursorTarget } from "#app/enums/shop-cursor-target"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; function getTranslation(key: string): string { if (!getIsInitialized()) { @@ -700,151 +700,151 @@ export function setSetting(setting: string, value: integer): boolean { } switch (Setting[index].key) { case SettingKeys.Game_Speed: - gScene.gameSpeed = parseFloat(Setting[index].options[value].value.replace("x", "")); + globalScene.gameSpeed = parseFloat(Setting[index].options[value].value.replace("x", "")); break; case SettingKeys.Master_Volume: - gScene.masterVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; - gScene.updateSoundVolume(); + globalScene.masterVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; + globalScene.updateSoundVolume(); break; case SettingKeys.BGM_Volume: - gScene.bgmVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; - gScene.updateSoundVolume(); + globalScene.bgmVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; + globalScene.updateSoundVolume(); break; case SettingKeys.Field_Volume: - gScene.fieldVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; - gScene.updateSoundVolume(); + globalScene.fieldVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; + globalScene.updateSoundVolume(); break; case SettingKeys.SE_Volume: - gScene.seVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; - gScene.updateSoundVolume(); + globalScene.seVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; + globalScene.updateSoundVolume(); break; case SettingKeys.UI_Volume: - gScene.uiVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; + globalScene.uiVolume = value ? parseInt(Setting[index].options[value].value) * 0.01 : 0; break; case SettingKeys.Music_Preference: - gScene.musicPreference = value; + globalScene.musicPreference = value; break; case SettingKeys.Damage_Numbers: - gScene.damageNumbersMode = value; + globalScene.damageNumbersMode = value; break; case SettingKeys.UI_Theme: - gScene.uiTheme = value; + globalScene.uiTheme = value; break; case SettingKeys.Window_Type: updateWindowType(parseInt(Setting[index].options[value].value)); break; case SettingKeys.Tutorials: - gScene.enableTutorials = Setting[index].options[value].value === "On"; + globalScene.enableTutorials = Setting[index].options[value].value === "On"; break; case SettingKeys.Move_Info: - gScene.enableMoveInfo = Setting[index].options[value].value === "On"; + globalScene.enableMoveInfo = Setting[index].options[value].value === "On"; break; case SettingKeys.Enable_Retries: - gScene.enableRetries = Setting[index].options[value].value === "On"; + globalScene.enableRetries = Setting[index].options[value].value === "On"; break; case SettingKeys.Hide_IVs: - gScene.hideIvs = Setting[index].options[value].value === "On"; + globalScene.hideIvs = Setting[index].options[value].value === "On"; break; case SettingKeys.Skip_Seen_Dialogues: - gScene.skipSeenDialogues = Setting[index].options[value].value === "On"; + globalScene.skipSeenDialogues = Setting[index].options[value].value === "On"; break; case SettingKeys.Egg_Skip: - gScene.eggSkipPreference = value; + globalScene.eggSkipPreference = value; break; case SettingKeys.Battle_Style: - gScene.battleStyle = value; + globalScene.battleStyle = value; break; case SettingKeys.Show_BGM_Bar: - gScene.showBgmBar = Setting[index].options[value].value === "On"; + globalScene.showBgmBar = Setting[index].options[value].value === "On"; break; case SettingKeys.Candy_Upgrade_Notification: - if (gScene.candyUpgradeNotification === value) { + if (globalScene.candyUpgradeNotification === value) { break; } - gScene.candyUpgradeNotification = value; - gScene.eventTarget.dispatchEvent(new CandyUpgradeNotificationChangedEvent(value)); + globalScene.candyUpgradeNotification = value; + globalScene.eventTarget.dispatchEvent(new CandyUpgradeNotificationChangedEvent(value)); break; case SettingKeys.Candy_Upgrade_Display: - gScene.candyUpgradeDisplay = value; + globalScene.candyUpgradeDisplay = value; case SettingKeys.Money_Format: switch (Setting[index].options[value].value) { case "Normal": - gScene.moneyFormat = MoneyFormat.NORMAL; + globalScene.moneyFormat = MoneyFormat.NORMAL; break; case "Abbreviated": - gScene.moneyFormat = MoneyFormat.ABBREVIATED; + globalScene.moneyFormat = MoneyFormat.ABBREVIATED; break; } - gScene.updateMoneyText(false); + globalScene.updateMoneyText(false); break; case SettingKeys.Sprite_Set: - gScene.experimentalSprites = !!value; + globalScene.experimentalSprites = !!value; if (value) { - gScene.initExpSprites(); + globalScene.initExpSprites(); } break; case SettingKeys.Move_Animations: - gScene.moveAnimations = Setting[index].options[value].value === "On"; + globalScene.moveAnimations = Setting[index].options[value].value === "On"; break; case SettingKeys.Show_Moveset_Flyout: - gScene.showMovesetFlyout = Setting[index].options[value].value === "On"; + globalScene.showMovesetFlyout = Setting[index].options[value].value === "On"; break; case SettingKeys.Show_Arena_Flyout: - gScene.showArenaFlyout = Setting[index].options[value].value === "On"; + globalScene.showArenaFlyout = Setting[index].options[value].value === "On"; break; case SettingKeys.Show_Time_Of_Day_Widget: - gScene.showTimeOfDayWidget = Setting[index].options[value].value === "On"; + globalScene.showTimeOfDayWidget = Setting[index].options[value].value === "On"; break; case SettingKeys.Time_Of_Day_Animation: - gScene.timeOfDayAnimation = Setting[index].options[value].value === "Bounce" ? EaseType.BOUNCE : EaseType.BACK; + globalScene.timeOfDayAnimation = Setting[index].options[value].value === "Bounce" ? EaseType.BOUNCE : EaseType.BACK; break; case SettingKeys.Show_Stats_on_Level_Up: - gScene.showLevelUpStats = Setting[index].options[value].value === "On"; + globalScene.showLevelUpStats = Setting[index].options[value].value === "On"; break; case SettingKeys.Shop_Cursor_Target: const selectedValue = shopCursorTargetIndexMap[value]; - gScene.shopCursorTarget = selectedValue; + globalScene.shopCursorTarget = selectedValue; break; case SettingKeys.EXP_Gains_Speed: - gScene.expGainsSpeed = value; + globalScene.expGainsSpeed = value; break; case SettingKeys.EXP_Party_Display: - gScene.expParty = value; + globalScene.expParty = value; break; case SettingKeys.HP_Bar_Speed: - gScene.hpBarSpeed = value; + globalScene.hpBarSpeed = value; break; case SettingKeys.Fusion_Palette_Swaps: - gScene.fusionPaletteSwaps = !!value; + globalScene.fusionPaletteSwaps = !!value; break; case SettingKeys.Player_Gender: - if (gScene.gameData) { + if (globalScene.gameData) { const female = Setting[index].options[value].value === "Girl"; - gScene.gameData.gender = female ? PlayerGender.FEMALE : PlayerGender.MALE; - gScene.trainer.setTexture(gScene.trainer.texture.key.replace(female ? "m" : "f", female ? "f" : "m")); + globalScene.gameData.gender = female ? PlayerGender.FEMALE : PlayerGender.MALE; + globalScene.trainer.setTexture(globalScene.trainer.texture.key.replace(female ? "m" : "f", female ? "f" : "m")); } else { return false; } break; case SettingKeys.Touch_Controls: - gScene.enableTouchControls = Setting[index].options[value].value !== "Disabled" && hasTouchscreen(); + globalScene.enableTouchControls = Setting[index].options[value].value !== "Disabled" && hasTouchscreen(); const touchControls = document.getElementById("touchControls"); if (touchControls) { - touchControls.classList.toggle("visible", gScene.enableTouchControls); + touchControls.classList.toggle("visible", globalScene.enableTouchControls); } break; case SettingKeys.Vibration: - gScene.enableVibration = Setting[index].options[value].value !== "Disabled" && hasTouchscreen(); + globalScene.enableVibration = Setting[index].options[value].value !== "Disabled" && hasTouchscreen(); break; case SettingKeys.Type_Hints: - gScene.typeHints = Setting[index].options[value].value === "On"; + globalScene.typeHints = Setting[index].options[value].value === "On"; break; case SettingKeys.Language: if (value) { - if (gScene.ui) { + if (globalScene.ui) { const cancelHandler = () => { - gScene.ui.revertMode(); - (gScene.ui.getHandler() as SettingsUiHandler).setOptionCursor(0, 0, true); + globalScene.ui.revertMode(); + (globalScene.ui.getHandler() as SettingsUiHandler).setOptionCursor(0, 0, true); }; const changeLocaleHandler = (locale: string): boolean => { try { @@ -859,7 +859,7 @@ export function setSetting(setting: string, value: integer): boolean { return false; } }; - gScene.ui.setOverlayMode(Mode.OPTION_SELECT, { + globalScene.ui.setOverlayMode(Mode.OPTION_SELECT, { options: [ { label: "English", @@ -917,7 +917,7 @@ export function setSetting(setting: string, value: integer): boolean { } break; case SettingKeys.Shop_Overlay_Opacity: - gScene.updateShopOverlayOpacity(parseInt(Setting[index].options[value].value) * .01); + globalScene.updateShopOverlayOpacity(parseInt(Setting[index].options[value].value) * .01); break; } diff --git a/src/test/enemy_command.test.ts b/src/test/enemy_command.test.ts index 36a5601d2b6..c87ec5709c7 100644 --- a/src/test/enemy_command.test.ts +++ b/src/test/enemy_command.test.ts @@ -9,14 +9,14 @@ import GameManager from "#test/utils/gameManager"; import Phaser from "phaser"; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; -let gScene: BattleScene; +let globalScene: BattleScene; const NUM_TRIALS = 300; type MoveChoiceSet = { [key: number]: number }; function getEnemyMoveChoices(pokemon: EnemyPokemon, moveChoices: MoveChoiceSet): void { // Use an unseeded random number generator in place of the mocked-out randBattleSeedInt - vi.spyOn(gScene, "randBattleSeedInt").mockImplementation((range, min?) => { + vi.spyOn(globalScene, "randBattleSeedInt").mockImplementation((range, min?) => { return randSeedInt(range, min); }); for (let i = 0; i < NUM_TRIALS; i++) { @@ -45,7 +45,7 @@ describe("Enemy Commands - Move Selection", () => { beforeEach(() => { game = new GameManager(phaserGame); - gScene = game.scene; + globalScene = game.scene; game.override .ability(Abilities.BALL_FETCH) diff --git a/src/test/moves/aurora_veil.test.ts b/src/test/moves/aurora_veil.test.ts index 66cea897238..34e1319479b 100644 --- a/src/test/moves/aurora_veil.test.ts +++ b/src/test/moves/aurora_veil.test.ts @@ -13,7 +13,7 @@ import GameManager from "#test/utils/gameManager"; import Phaser from "phaser"; import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; -let gScene: BattleScene; +let globalScene: BattleScene; describe("Moves - Aurora Veil", () => { let phaserGame: Phaser.Game; @@ -33,7 +33,7 @@ describe("Moves - Aurora Veil", () => { beforeEach(() => { game = new GameManager(phaserGame); - gScene = game.scene; + globalScene = game.scene; game.override.battleType("single"); game.override.ability(Abilities.NONE); game.override.moveset([ Moves.ABSORB, Moves.ROCK_SLIDE, Moves.TACKLE ]); @@ -113,8 +113,8 @@ const getMockedMoveDamage = (defender: Pokemon, attacker: Pokemon, move: Move) = const multiplierHolder = new NumberHolder(1); const side = defender.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - if (gScene.arena.getTagOnSide(ArenaTagType.AURORA_VEIL, side)) { - gScene.arena.applyTagsForSide(ArenaTagType.AURORA_VEIL, side, false, attacker, move.category, multiplierHolder); + if (globalScene.arena.getTagOnSide(ArenaTagType.AURORA_VEIL, side)) { + globalScene.arena.applyTagsForSide(ArenaTagType.AURORA_VEIL, side, false, attacker, move.category, multiplierHolder); } return move.power * multiplierHolder.value; diff --git a/src/test/moves/light_screen.test.ts b/src/test/moves/light_screen.test.ts index 2f4a04e8e01..be334b24440 100644 --- a/src/test/moves/light_screen.test.ts +++ b/src/test/moves/light_screen.test.ts @@ -12,7 +12,7 @@ import GameManager from "#test/utils/gameManager"; import Phaser from "phaser"; import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; -let gScene: BattleScene; +let globalScene: BattleScene; describe("Moves - Light Screen", () => { let phaserGame: Phaser.Game; @@ -32,7 +32,7 @@ describe("Moves - Light Screen", () => { beforeEach(() => { game = new GameManager(phaserGame); - gScene = game.scene; + globalScene = game.scene; game.override.battleType("single"); game.override.ability(Abilities.NONE); game.override.moveset([ Moves.ABSORB, Moves.DAZZLING_GLEAM, Moves.TACKLE ]); @@ -96,8 +96,8 @@ const getMockedMoveDamage = (defender: Pokemon, attacker: Pokemon, move: Move) = const multiplierHolder = new NumberHolder(1); const side = defender.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - if (gScene.arena.getTagOnSide(ArenaTagType.LIGHT_SCREEN, side)) { - gScene.arena.applyTagsForSide(ArenaTagType.LIGHT_SCREEN, side, false, attacker, move.category, multiplierHolder); + if (globalScene.arena.getTagOnSide(ArenaTagType.LIGHT_SCREEN, side)) { + globalScene.arena.applyTagsForSide(ArenaTagType.LIGHT_SCREEN, side, false, attacker, move.category, multiplierHolder); } return move.power * multiplierHolder.value; diff --git a/src/test/moves/reflect.test.ts b/src/test/moves/reflect.test.ts index dab61527bb9..03fe050448c 100644 --- a/src/test/moves/reflect.test.ts +++ b/src/test/moves/reflect.test.ts @@ -12,7 +12,7 @@ import GameManager from "#test/utils/gameManager"; import Phaser from "phaser"; import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; -let gScene: BattleScene; +let globalScene: BattleScene; describe("Moves - Reflect", () => { let phaserGame: Phaser.Game; @@ -32,7 +32,7 @@ describe("Moves - Reflect", () => { beforeEach(() => { game = new GameManager(phaserGame); - gScene = game.scene; + globalScene = game.scene; game.override.battleType("single"); game.override.ability(Abilities.NONE); game.override.moveset([ Moves.ABSORB, Moves.ROCK_SLIDE, Moves.TACKLE ]); @@ -96,8 +96,8 @@ const getMockedMoveDamage = (defender: Pokemon, attacker: Pokemon, move: Move) = const multiplierHolder = new NumberHolder(1); const side = defender.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - if (gScene.arena.getTagOnSide(ArenaTagType.REFLECT, side)) { - gScene.arena.applyTagsForSide(ArenaTagType.REFLECT, side, false, attacker, move.category, multiplierHolder); + if (globalScene.arena.getTagOnSide(ArenaTagType.REFLECT, side)) { + globalScene.arena.applyTagsForSide(ArenaTagType.REFLECT, side, false, attacker, move.category, multiplierHolder); } return move.power * multiplierHolder.value; diff --git a/src/test/mystery-encounter/encounters/bug-type-superfan-encounter.test.ts b/src/test/mystery-encounter/encounters/bug-type-superfan-encounter.test.ts index 252df6237fd..f3ebb6db57a 100644 --- a/src/test/mystery-encounter/encounters/bug-type-superfan-encounter.test.ts +++ b/src/test/mystery-encounter/encounters/bug-type-superfan-encounter.test.ts @@ -388,6 +388,7 @@ describe("Bug-Type Superfan - Mystery Encounter", () => { expect(PHYSICAL_TUTOR_MOVES.some(move => new PokemonMove(move).getName() === optionData[0].label)).toBe(true); expect(SPECIAL_TUTOR_MOVES.some(move => new PokemonMove(move).getName() === optionData[1].label)).toBe(true); expect(STATUS_TUTOR_MOVES.some(move => new PokemonMove(move).getName() === optionData[2].label)).toBe(true); + expect(MISC_TUTOR_MOVES.some(move => new PokemonMove(move).getName() === optionData[3].label)).toBe(true); }); }); diff --git a/src/timed-event-manager.ts b/src/timed-event-manager.ts index fedc591e076..c5a3f4f5458 100644 --- a/src/timed-event-manager.ts +++ b/src/timed-event-manager.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { TextStyle, addTextObject } from "#app/ui/text"; import { nil } from "#app/utils"; import i18next from "i18next"; @@ -95,8 +95,8 @@ export class TimedEventDisplay extends Phaser.GameObjects.Container { private eventTimer: NodeJS.Timeout | null; constructor(x: number, y: number, event?: TimedEvent) { - super(gScene, x, y); - this.availableWidth = gScene.scaledCanvas.width; + super(globalScene, x, y); + this.availableWidth = globalScene.scaledCanvas.width; this.event = event; this.setVisible(false); } @@ -132,8 +132,8 @@ export class TimedEventDisplay extends Phaser.GameObjects.Container { console.log(this.event.bannerKey); const padding = 5; const showTimer = this.event.eventType !== EventType.NO_TIMER_DISPLAY; - const yPosition = gScene.game.canvas.height / 6 - padding - (showTimer ? 10 : 0) - (this.event.yOffset ?? 0); - this.banner = new Phaser.GameObjects.Image(gScene, this.availableWidth / 2, yPosition - padding, key); + const yPosition = globalScene.game.canvas.height / 6 - padding - (showTimer ? 10 : 0) - (this.event.yOffset ?? 0); + this.banner = new Phaser.GameObjects.Image(globalScene, this.availableWidth / 2, yPosition - padding, key); this.banner.setName("img-event-banner"); this.banner.setOrigin(0.5, 1); this.banner.setScale(this.event.scale ?? 0.18); diff --git a/src/touch-controls.ts b/src/touch-controls.ts index 8038ce46ed2..db355e2405e 100644 --- a/src/touch-controls.ts +++ b/src/touch-controls.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Button } from "#enums/buttons"; import EventEmitter = Phaser.Events.EventEmitter; @@ -14,7 +14,7 @@ export default class TouchControl { private finishedLastTouch: boolean = false; constructor() { - this.events = gScene.game.events; + this.events = globalScene.game.events; this.init(); } diff --git a/src/tutorial.ts b/src/tutorial.ts index b114b245004..ac7ead838f8 100644 --- a/src/tutorial.ts +++ b/src/tutorial.ts @@ -1,4 +1,4 @@ -import { gScene } from "./battle-scene"; // ? +import { globalScene } from "./battle-scene"; import AwaitableUiHandler from "./ui/awaitable-ui-handler"; import UiHandler from "./ui/ui-handler"; import { Mode } from "./ui/ui"; @@ -19,48 +19,48 @@ export enum Tutorial { const tutorialHandlers = { [Tutorial.Intro]: () => { return new Promise(resolve => { - gScene.ui.showText(i18next.t("tutorial:intro"), null, () => resolve(), null, true); + globalScene.ui.showText(i18next.t("tutorial:intro"), null, () => resolve(), null, true); }); }, [Tutorial.Access_Menu]: () => { return new Promise(resolve => { - if (gScene.enableTouchControls) { + if (globalScene.enableTouchControls) { return resolve(); } - gScene.showFieldOverlay(1000).then(() => gScene.ui.showText(i18next.t("tutorial:accessMenu"), null, () => gScene.hideFieldOverlay(1000).then(() => resolve()), null, true)); + globalScene.showFieldOverlay(1000).then(() => globalScene.ui.showText(i18next.t("tutorial:accessMenu"), null, () => globalScene.hideFieldOverlay(1000).then(() => resolve()), null, true)); }); }, [Tutorial.Menu]: () => { return new Promise(resolve => { - gScene.gameData.saveTutorialFlag(Tutorial.Access_Menu, true); - gScene.ui.showText(i18next.t("tutorial:menu"), null, () => gScene.ui.showText("", null, () => resolve()), null, true); + globalScene.gameData.saveTutorialFlag(Tutorial.Access_Menu, true); + globalScene.ui.showText(i18next.t("tutorial:menu"), null, () => globalScene.ui.showText("", null, () => resolve()), null, true); }); }, [Tutorial.Starter_Select]: () => { return new Promise(resolve => { - gScene.ui.showText(i18next.t("tutorial:starterSelect"), null, () => gScene.ui.showText("", null, () => resolve()), null, true); + globalScene.ui.showText(i18next.t("tutorial:starterSelect"), null, () => globalScene.ui.showText("", null, () => resolve()), null, true); }); }, [Tutorial.Pokerus]: () => { return new Promise(resolve => { - gScene.ui.showText(i18next.t("tutorial:pokerus"), null, () => gScene.ui.showText("", null, () => resolve()), null, true); + globalScene.ui.showText(i18next.t("tutorial:pokerus"), null, () => globalScene.ui.showText("", null, () => resolve()), null, true); }); }, [Tutorial.Stat_Change]: () => { return new Promise(resolve => { - gScene.showFieldOverlay(1000).then(() => gScene.ui.showText(i18next.t("tutorial:statChange"), null, () => gScene.ui.showText("", null, () => gScene.hideFieldOverlay(1000).then(() => resolve())), null, true)); + globalScene.showFieldOverlay(1000).then(() => globalScene.ui.showText(i18next.t("tutorial:statChange"), null, () => globalScene.ui.showText("", null, () => globalScene.hideFieldOverlay(1000).then(() => resolve())), null, true)); }); }, [Tutorial.Select_Item]: () => { return new Promise(resolve => { - gScene.ui.setModeWithoutClear(Mode.MESSAGE).then(() => { - gScene.ui.showText(i18next.t("tutorial:selectItem"), null, () => gScene.ui.showText("", null, () => gScene.ui.setModeWithoutClear(Mode.MODIFIER_SELECT).then(() => resolve())), null, true); + globalScene.ui.setModeWithoutClear(Mode.MESSAGE).then(() => { + globalScene.ui.showText(i18next.t("tutorial:selectItem"), null, () => globalScene.ui.showText("", null, () => globalScene.ui.setModeWithoutClear(Mode.MODIFIER_SELECT).then(() => resolve())), null, true); }); }); }, [Tutorial.Egg_Gacha]: () => { return new Promise(resolve => { - gScene.ui.showText(i18next.t("tutorial:eggGacha"), null, () => gScene.ui.showText("", null, () => resolve()), null, true); + globalScene.ui.showText(i18next.t("tutorial:eggGacha"), null, () => globalScene.ui.showText("", null, () => resolve()), null, true); }); }, }; @@ -74,19 +74,19 @@ const tutorialHandlers = { * @returns a promise with result `true` if the tutorial was run and finished, `false` otherwise */ export async function handleTutorial(tutorial: Tutorial): Promise { - if (!gScene.enableTutorials && !Overrides.BYPASS_TUTORIAL_SKIP_OVERRIDE) { + if (!globalScene.enableTutorials && !Overrides.BYPASS_TUTORIAL_SKIP_OVERRIDE) { return false; } - if (gScene.gameData.getTutorialFlags()[tutorial] && !Overrides.BYPASS_TUTORIAL_SKIP_OVERRIDE) { + if (globalScene.gameData.getTutorialFlags()[tutorial] && !Overrides.BYPASS_TUTORIAL_SKIP_OVERRIDE) { return false; } - const handler = gScene.ui.getHandler(); - const isMenuDisabled = gScene.disableMenu; + const handler = globalScene.ui.getHandler(); + const isMenuDisabled = globalScene.disableMenu; // starting tutorial, disable menu - gScene.disableMenu = true; + globalScene.disableMenu = true; if (handler instanceof AwaitableUiHandler) { handler.tutorialActive = true; } @@ -96,8 +96,8 @@ export async function handleTutorial(tutorial: Tutorial): Promise { await hideTutorialOverlay(handler); // tutorial finished and overlay gone, re-enable menu, save tutorial as seen - gScene.disableMenu = isMenuDisabled; - gScene.gameData.saveTutorialFlag(tutorial, true); + globalScene.disableMenu = isMenuDisabled; + globalScene.gameData.saveTutorialFlag(tutorial, true); if (handler instanceof AwaitableUiHandler) { handler.tutorialActive = false; } @@ -113,7 +113,7 @@ export async function handleTutorial(tutorial: Tutorial): Promise { */ async function showTutorialOverlay(handler: UiHandler) { if (handler instanceof AwaitableUiHandler && handler.tutorialOverlay) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: handler.tutorialOverlay, alpha: 0.5, duration: 750, @@ -135,7 +135,7 @@ async function showTutorialOverlay(handler: UiHandler) { */ async function hideTutorialOverlay(handler: UiHandler) { if (handler instanceof AwaitableUiHandler && handler.tutorialOverlay) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: handler.tutorialOverlay, alpha: 0, duration: 500, diff --git a/src/ui-inputs.ts b/src/ui-inputs.ts index ceaf93befee..2f8f4016edb 100644 --- a/src/ui-inputs.ts +++ b/src/ui-inputs.ts @@ -8,7 +8,7 @@ import SettingsUiHandler from "./ui/settings/settings-ui-handler"; import { Button } from "#enums/buttons"; import SettingsGamepadUiHandler from "./ui/settings/settings-gamepad-ui-handler"; import SettingsKeyboardUiHandler from "#app/ui/settings/settings-keyboard-ui-handler"; -import { gScene } from "./battle-scene"; +import { globalScene } from "./battle-scene"; import SettingsDisplayUiHandler from "./ui/settings/settings-display-ui-handler"; import SettingsAudioUiHandler from "./ui/settings/settings-audio-ui-handler"; import RunInfoUiHandler from "./ui/run-info-ui-handler"; @@ -33,12 +33,12 @@ export class UiInputs { if (evt.controller_type === "keyboard") { //if the touch property is present and defined, then this is a simulated keyboard event from the touch screen if (evt.hasOwnProperty("isTouch") && evt.isTouch) { - gScene.inputMethod = "touch"; + globalScene.inputMethod = "touch"; } else { - gScene.inputMethod = "keyboard"; + globalScene.inputMethod = "keyboard"; } } else if (evt.controller_type === "gamepad") { - gScene.inputMethod = "gamepad"; + globalScene.inputMethod = "gamepad"; } } @@ -63,7 +63,7 @@ export class UiInputs { } doVibration(inputSuccess: boolean, vibrationLength: number): void { - if (inputSuccess && gScene.enableVibration && typeof navigator.vibrate !== "undefined") { + if (inputSuccess && globalScene.enableVibration && typeof navigator.vibrate !== "undefined") { navigator.vibrate(vibrationLength); } } @@ -115,59 +115,59 @@ export class UiInputs { } buttonDirection(direction: Button): void { - const inputSuccess = gScene.ui.processInput(direction); + const inputSuccess = globalScene.ui.processInput(direction); const vibrationLength = 5; this.doVibration(inputSuccess, vibrationLength); } buttonAb(button: Button): void { - gScene.ui.processInput(button); + globalScene.ui.processInput(button); } buttonTouch(): void { - gScene.ui.processInput(Button.SUBMIT) || gScene.ui.processInput(Button.ACTION); + globalScene.ui.processInput(Button.SUBMIT) || globalScene.ui.processInput(Button.ACTION); } buttonStats(pressed: boolean = true): void { // allow access to Button.STATS as a toggle for other elements - for (const t of gScene.getInfoToggles(true)) { + for (const t of globalScene.getInfoToggles(true)) { t.toggleInfo(pressed); } // handle normal pokemon battle ui - for (const p of gScene.getField().filter(p => p?.isActive(true))) { + for (const p of globalScene.getField().filter(p => p?.isActive(true))) { p.toggleStats(pressed); } } buttonGoToFilter(button: Button): void { const whitelist = [ StarterSelectUiHandler ]; - const uiHandler = gScene.ui?.getHandler(); + const uiHandler = globalScene.ui?.getHandler(); if (whitelist.some(handler => uiHandler instanceof handler)) { - gScene.ui.processInput(button); + globalScene.ui.processInput(button); } else { this.buttonStats(true); } } buttonInfo(pressed: boolean = true): void { - if (gScene.showMovesetFlyout ) { - for (const p of gScene.getField().filter(p => p?.isActive(true))) { + if (globalScene.showMovesetFlyout ) { + for (const p of globalScene.getField().filter(p => p?.isActive(true))) { p.toggleFlyout(pressed); } } - if (gScene.showArenaFlyout) { - gScene.ui.processInfoButton(pressed); + if (globalScene.showArenaFlyout) { + globalScene.ui.processInfoButton(pressed); } } buttonMenu(): void { - if (gScene.disableMenu) { + if (globalScene.disableMenu) { return; } - switch (gScene.ui?.getMode()) { + switch (globalScene.ui?.getMode()) { case Mode.MESSAGE: - const messageHandler = gScene.ui.getHandler(); + const messageHandler = globalScene.ui.getHandler(); if (!messageHandler.pendingPrompt || messageHandler.isTextAnimationInProgress()) { return; } @@ -175,14 +175,14 @@ export class UiInputs { case Mode.COMMAND: case Mode.MODIFIER_SELECT: case Mode.MYSTERY_ENCOUNTER: - gScene.ui.setOverlayMode(Mode.MENU); + globalScene.ui.setOverlayMode(Mode.MENU); break; case Mode.STARTER_SELECT: this.buttonTouch(); break; case Mode.MENU: - gScene.ui.revertMode(); - gScene.playSound("ui/select"); + globalScene.ui.revertMode(); + globalScene.playSound("ui/select"); break; default: return; @@ -191,9 +191,9 @@ export class UiInputs { buttonCycleOption(button: Button): void { const whitelist = [ StarterSelectUiHandler, SettingsUiHandler, RunInfoUiHandler, SettingsDisplayUiHandler, SettingsAudioUiHandler, SettingsGamepadUiHandler, SettingsKeyboardUiHandler ]; - const uiHandler = gScene.ui?.getHandler(); + const uiHandler = globalScene.ui?.getHandler(); if (whitelist.some(handler => uiHandler instanceof handler)) { - gScene.ui.processInput(button); + globalScene.ui.processInput(button); } else if (button === Button.V) { this.buttonInfo(true); } @@ -201,15 +201,15 @@ export class UiInputs { buttonSpeedChange(up = true): void { const settingGameSpeed = settingIndex(SettingKeys.Game_Speed); - if (up && gScene.gameSpeed < 5) { - gScene.gameData.saveSetting(SettingKeys.Game_Speed, Setting[settingGameSpeed].options.findIndex((item) => item.label === `${gScene.gameSpeed}x`) + 1); - if (gScene.ui?.getMode() === Mode.SETTINGS) { - (gScene.ui.getHandler() as SettingsUiHandler).show([]); + if (up && globalScene.gameSpeed < 5) { + globalScene.gameData.saveSetting(SettingKeys.Game_Speed, Setting[settingGameSpeed].options.findIndex((item) => item.label === `${globalScene.gameSpeed}x`) + 1); + if (globalScene.ui?.getMode() === Mode.SETTINGS) { + (globalScene.ui.getHandler() as SettingsUiHandler).show([]); } - } else if (!up && gScene.gameSpeed > 1) { - gScene.gameData.saveSetting(SettingKeys.Game_Speed, Math.max(Setting[settingGameSpeed].options.findIndex((item) => item.label === `${gScene.gameSpeed}x`) - 1, 0)); - if (gScene.ui?.getMode() === Mode.SETTINGS) { - (gScene.ui.getHandler() as SettingsUiHandler).show([]); + } else if (!up && globalScene.gameSpeed > 1) { + globalScene.gameData.saveSetting(SettingKeys.Game_Speed, Math.max(Setting[settingGameSpeed].options.findIndex((item) => item.label === `${globalScene.gameSpeed}x`) - 1, 0)); + if (globalScene.ui?.getMode() === Mode.SETTINGS) { + (globalScene.ui.getHandler() as SettingsUiHandler).show([]); } } } diff --git a/src/ui/ability-bar.ts b/src/ui/ability-bar.ts index 69c4844fbc6..c1ba8597dd9 100644 --- a/src/ui/ability-bar.ts +++ b/src/ui/ability-bar.ts @@ -1,5 +1,5 @@ import { getPokemonNameWithAffix } from "#app/messages"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import Pokemon from "../field/pokemon"; import { TextStyle, addTextObject } from "./text"; import i18next from "i18next"; @@ -18,11 +18,11 @@ export default class AbilityBar extends Phaser.GameObjects.Container { public shown: boolean; constructor() { - super(gScene, hiddenX, baseY); + super(globalScene, hiddenX, baseY); } setup(): void { - this.bg = gScene.add.image(0, 0, "ability_bar_left"); + this.bg = globalScene.add.image(0, 0, "ability_bar_left"); this.bg.setOrigin(0, 0); this.add(this.bg); @@ -43,11 +43,11 @@ export default class AbilityBar extends Phaser.GameObjects.Container { return; } - gScene.fieldUI.bringToTop(this); + globalScene.fieldUI.bringToTop(this); - this.y = baseY + (gScene.currentBattle.double ? 14 : 0); - this.tween = gScene.tweens.add({ + this.y = baseY + (globalScene.currentBattle.double ? 14 : 0); + this.tween = globalScene.tweens.add({ targets: this, x: shownX, duration: 500, @@ -75,7 +75,7 @@ export default class AbilityBar extends Phaser.GameObjects.Container { this.tween.stop(); } - this.tween = gScene.tweens.add({ + this.tween = globalScene.tweens.add({ targets: this, x: -91, duration: 500, diff --git a/src/ui/abstact-option-select-ui-handler.ts b/src/ui/abstact-option-select-ui-handler.ts index 18a142954d5..8fd4b6522fd 100644 --- a/src/ui/abstact-option-select-ui-handler.ts +++ b/src/ui/abstact-option-select-ui-handler.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { TextStyle, addTextObject, getTextStyleOptions } from "./text"; import { Mode } from "./ui"; import UiHandler from "./ui-handler"; @@ -59,7 +59,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { setup() { const ui = this.getUi(); - this.optionSelectContainer = gScene.add.container((gScene.game.canvas.width / 6) - 1, -48); + this.optionSelectContainer = globalScene.add.container((globalScene.game.canvas.width / 6) - 1, -48); this.optionSelectContainer.setName(`option-select-${this.mode ? Mode[this.mode] : "UNKNOWN"}`); this.optionSelectContainer.setVisible(false); ui.add(this.optionSelectContainer); @@ -71,7 +71,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { this.optionSelectIcons = []; - this.scale = getTextStyleOptions(TextStyle.WINDOW, gScene.uiTheme).scale; + this.scale = getTextStyleOptions(TextStyle.WINDOW, globalScene.uiTheme).scale; this.setCursor(0); } @@ -84,7 +84,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { // for performance reasons, this limits how many options we can see at once. Without this, it would try to make text options for every single options // which makes the performance take a hit. If there's not enough options to do this (set to 10 at the moment) and the ui mode !== Mode.AUTO_COMPLETE, // this is ignored and the original code is untouched, with the options array being all the options from the config - if (configOptions.length >= 10 && gScene.ui.getMode() === Mode.AUTO_COMPLETE) { + if (configOptions.length >= 10 && globalScene.ui.getMode() === Mode.AUTO_COMPLETE) { const optionsScrollTotal = configOptions.length; const optionStartIndex = this.scrollCursor; const optionEndIndex = Math.min(optionsScrollTotal, optionStartIndex + (!optionStartIndex || this.scrollCursor + (this.config?.maxOptions! - 1) >= optionsScrollTotal ? this.config?.maxOptions! - 1 : this.config?.maxOptions! - 2)); @@ -106,7 +106,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { this.optionSelectText.setName("text-option-select"); this.optionSelectText.setLineSpacing(12); this.optionSelectContainer.add(this.optionSelectText); - this.optionSelectContainer.setPosition((gScene.game.canvas.width / 6) - 1 - (this.config?.xOffset || 0), -48 + (this.config?.yOffset || 0)); + this.optionSelectContainer.setPosition((globalScene.game.canvas.width / 6) - 1 - (this.config?.xOffset || 0), -48 + (this.config?.yOffset || 0)); this.optionSelectBg.width = Math.max(this.optionSelectText.displayWidth + 24, this.getWindowWidth()); @@ -120,7 +120,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { options.forEach((option: OptionSelectItem, i: integer) => { if (option.item) { - const itemIcon = gScene.add.sprite(0, 0, "items", option.item); + const itemIcon = globalScene.add.sprite(0, 0, "items", option.item); itemIcon.setScale(3 * this.scale); this.optionSelectIcons.push(itemIcon); @@ -129,7 +129,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { itemIcon.setPositionRelative(this.optionSelectText, 36 * this.scale, 7 + i * (114 * this.scale - 3)); if (option.item === "candy") { - const itemOverlayIcon = gScene.add.sprite(0, 0, "items", "candy_overlay"); + const itemOverlayIcon = globalScene.add.sprite(0, 0, "items", "candy_overlay"); itemOverlayIcon.setScale(3 * this.scale); this.optionSelectIcons.push(itemOverlayIcon); @@ -156,7 +156,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { this.config = args[0] as OptionSelectConfig; this.setupOptions(); - gScene.ui.bringToTop(this.optionSelectContainer); + globalScene.ui.bringToTop(this.optionSelectContainer); this.optionSelectContainer.setVisible(true); this.scrollCursor = 0; @@ -166,7 +166,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { this.blockInput = true; this.optionSelectText.setAlpha(0.5); this.cursorObj?.setAlpha(0.8); - gScene.time.delayedCall(Utils.fixedInt(this.config.delay), () => this.unblockInput()); + globalScene.time.delayedCall(Utils.fixedInt(this.config.delay), () => this.unblockInput()); } return true; @@ -332,7 +332,7 @@ export default abstract class AbstractOptionSelectUiHandler extends UiHandler { } if (!this.cursorObj) { - this.cursorObj = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.image(0, 0, "cursor"); this.optionSelectContainer.add(this.cursorObj); } diff --git a/src/ui/achv-bar.ts b/src/ui/achv-bar.ts index 1bb867afe6d..c07d93ad910 100644 --- a/src/ui/achv-bar.ts +++ b/src/ui/achv-bar.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Achv, getAchievementDescription } from "../system/achv"; import { Voucher } from "../system/voucher"; import { TextStyle, addTextObject } from "./text"; @@ -20,20 +20,20 @@ export default class AchvBar extends Phaser.GameObjects.Container { public shown: boolean; constructor() { - super(gScene, gScene.game.canvas.width / 6, 0); - this.playerGender = gScene.gameData.gender; + super(globalScene, globalScene.game.canvas.width / 6, 0); + this.playerGender = globalScene.gameData.gender; } setup(): void { this.defaultWidth = 200; this.defaultHeight = 40; - this.bg = gScene.add.nineslice(0, 0, "achv_bar", undefined, this.defaultWidth, this.defaultHeight, 41, 6, 16, 4); + this.bg = globalScene.add.nineslice(0, 0, "achv_bar", undefined, this.defaultWidth, this.defaultHeight, 41, 6, 16, 4); this.bg.setOrigin(0, 0); this.add(this.bg); - this.icon = gScene.add.sprite(4, 4, "items"); + this.icon = globalScene.add.sprite(4, 4, "items"); this.icon.setOrigin(0, 0); this.add(this.icon); @@ -90,16 +90,16 @@ export default class AchvBar extends Phaser.GameObjects.Container { this.bg.height = Math.max(this.defaultHeight, this.titleText.displayHeight + this.descriptionText.displayHeight + 8); this.icon.y = (this.bg.height / 2) - (this.icon.height / 2); - gScene.playSound("se/achv"); + globalScene.playSound("se/achv"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, - x: (gScene.game.canvas.width / 6) - (this.bg.width / 2), + x: (globalScene.game.canvas.width / 6) - (this.bg.width / 2), duration: 500, ease: "Sine.easeOut" }); - gScene.time.delayedCall(10000, () => this.hide(this.playerGender)); + globalScene.time.delayedCall(10000, () => this.hide(this.playerGender)); this.setVisible(true); this.shown = true; @@ -110,9 +110,9 @@ export default class AchvBar extends Phaser.GameObjects.Container { return; } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, - x: (gScene.game.canvas.width / 6), + x: (globalScene.game.canvas.width / 6), duration: 500, ease: "Sine.easeIn", onComplete: () => { diff --git a/src/ui/achvs-ui-handler.ts b/src/ui/achvs-ui-handler.ts index dfe463a2fc5..419b0d65b87 100644 --- a/src/ui/achvs-ui-handler.ts +++ b/src/ui/achvs-ui-handler.ts @@ -8,7 +8,7 @@ import { Mode } from "#app/ui/ui"; import { addWindow } from "#app/ui/ui-theme"; import { ScrollBar } from "#app/ui/scroll-bar"; import { PlayerGender } from "#enums/player-gender"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; enum Page { ACHIEVEMENTS, @@ -68,17 +68,17 @@ export default class AchvsUiHandler extends MessageUiHandler { setup() { const ui = this.getUi(); - this.mainContainer = gScene.add.container(1, -(gScene.game.canvas.height / 6) + 1); + this.mainContainer = globalScene.add.container(1, -(globalScene.game.canvas.height / 6) + 1); - this.mainContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); + this.mainContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); - this.headerBg = addWindow(0, 0, (gScene.game.canvas.width / 6) - 2, 24); + this.headerBg = addWindow(0, 0, (globalScene.game.canvas.width / 6) - 2, 24); this.headerBg.setOrigin(0, 0); this.headerText = addTextObject(0, 0, "", TextStyle.SETTINGS_LABEL); this.headerText.setOrigin(0, 0); this.headerText.setPositionRelative(this.headerBg, 8, 4); - this.headerActionButton = new Phaser.GameObjects.Sprite(gScene, 0, 0, "keyboard", "ACTION.png"); + this.headerActionButton = new Phaser.GameObjects.Sprite(globalScene, 0, 0, "keyboard", "ACTION.png"); this.headerActionButton.setOrigin(0, 0); this.headerActionButton.setPositionRelative(this.headerBg, 236, 6); this.headerActionText = addTextObject(0, 0, "", TextStyle.WINDOW, { fontSize:"60px" }); @@ -86,19 +86,19 @@ export default class AchvsUiHandler extends MessageUiHandler { this.headerActionText.setPositionRelative(this.headerBg, 264, 8); // We need to get the player gender from the game data to add the correct prefix to the achievement name - const genderIndex = gScene.gameData.gender ?? PlayerGender.MALE; + const genderIndex = globalScene.gameData.gender ?? PlayerGender.MALE; const genderStr = PlayerGender[genderIndex].toLowerCase(); this.achvsName = i18next.t("achv:Achievements.name", { context: genderStr }); this.vouchersName = i18next.t("voucher:vouchers"); - this.iconsBg = addWindow(0, this.headerBg.height, (gScene.game.canvas.width / 6) - 2, (gScene.game.canvas.height / 6) - this.headerBg.height - 68); + this.iconsBg = addWindow(0, this.headerBg.height, (globalScene.game.canvas.width / 6) - 2, (globalScene.game.canvas.height / 6) - this.headerBg.height - 68); this.iconsBg.setOrigin(0, 0); const yOffset = 6; this.scrollBar = new ScrollBar(this.iconsBg.width - 9, this.iconsBg.y + yOffset, 4, this.iconsBg.height - yOffset * 2, this.ROWS); - this.iconsContainer = gScene.add.container(5, this.headerBg.height + 8); + this.iconsContainer = globalScene.add.container(5, this.headerBg.height + 8); this.icons = []; @@ -106,7 +106,7 @@ export default class AchvsUiHandler extends MessageUiHandler { const x = (a % this.COLS) * 18; const y = Math.floor(a / this.COLS) * 18; - const icon = gScene.add.sprite(x, y, "items", "unknown"); + const icon = globalScene.add.sprite(x, y, "items", "unknown"); icon.setOrigin(0, 0); icon.setScale(0.5); @@ -126,7 +126,7 @@ export default class AchvsUiHandler extends MessageUiHandler { this.titleText.setOrigin(0.5, 0.5); this.titleText.setPosition(titleBgCenterX, titleBgCenterY); - this.scoreContainer = gScene.add.container(titleBg.x + titleBg.width, titleBg.y); + this.scoreContainer = globalScene.add.container(titleBg.x + titleBg.width, titleBg.y); const scoreBg = addWindow(0, 0, 46, 24); scoreBg.setOrigin(0, 0); this.scoreContainer.add(scoreBg); @@ -142,7 +142,7 @@ export default class AchvsUiHandler extends MessageUiHandler { this.unlockText.setOrigin(0.5, 0.5); this.unlockText.setPositionRelative(unlockBg, unlockBg.width / 2, unlockBg.height / 2); - const descriptionBg = addWindow(0, titleBg.y + titleBg.height, (gScene.game.canvas.width / 6) - 2, 42); + const descriptionBg = addWindow(0, titleBg.y + titleBg.height, (globalScene.game.canvas.width / 6) - 2, 42); descriptionBg.setOrigin(0, 0); const descriptionText = addTextObject(0, 0, "", TextStyle.WINDOW, { maxLines: 2 }); @@ -195,12 +195,12 @@ export default class AchvsUiHandler extends MessageUiHandler { protected showAchv(achv: Achv) { // We need to get the player gender from the game data to add the correct prefix to the achievement name - const genderIndex = gScene.gameData.gender ?? PlayerGender.MALE; + const genderIndex = globalScene.gameData.gender ?? PlayerGender.MALE; const genderStr = PlayerGender[genderIndex].toLowerCase(); achv.name = i18next.t(`achv:${achv.localizationKey}.name`, { context: genderStr }); achv.description = getAchievementDescription(achv.localizationKey); - const achvUnlocks = gScene.gameData.achvUnlocks; + const achvUnlocks = globalScene.gameData.achvUnlocks; const unlocked = achvUnlocks.hasOwnProperty(achv.id); const hidden = !unlocked && achv.secret && (!achv.parentId || !achvUnlocks.hasOwnProperty(achv.parentId)); this.titleText.setText(unlocked ? achv.name : "???"); @@ -210,7 +210,7 @@ export default class AchvsUiHandler extends MessageUiHandler { } protected showVoucher(voucher: Voucher) { - const voucherUnlocks = gScene.gameData.voucherUnlocks; + const voucherUnlocks = globalScene.gameData.voucherUnlocks; const unlocked = voucherUnlocks.hasOwnProperty(voucher.id); this.titleText.setText(getVoucherTypeName(voucher.voucherType)); @@ -240,7 +240,7 @@ export default class AchvsUiHandler extends MessageUiHandler { } if (button === Button.CANCEL) { success = true; - gScene.ui.revertMode(); + globalScene.ui.revertMode(); } else { const rowIndex = Math.floor(this.cursor / this.COLS); const itemOffset = (this.scrollCursor * this.COLS); @@ -306,7 +306,7 @@ export default class AchvsUiHandler extends MessageUiHandler { let update = ret; if (!this.cursorObj) { - this.cursorObj = gScene.add.nineslice(0, 0, "select_cursor_highlight", undefined, 16, 16, 1, 1, 1, 1); + this.cursorObj = globalScene.add.nineslice(0, 0, "select_cursor_highlight", undefined, 16, 16, 1, 1, 1, 1); this.cursorObj.setOrigin(0, 0); this.iconsContainer.add(this.cursorObj); update = true; @@ -382,7 +382,7 @@ export default class AchvsUiHandler extends MessageUiHandler { this.headerActionText.setX(textPosition); this.headerActionButton.setX(textPosition - this.headerActionButton.displayWidth - 4); - const achvUnlocks = gScene.gameData.achvUnlocks; + const achvUnlocks = globalScene.gameData.achvUnlocks; const itemOffset = this.scrollCursor * this.COLS; const itemLimit = this.ROWS * this.COLS; @@ -422,7 +422,7 @@ export default class AchvsUiHandler extends MessageUiHandler { this.headerActionText.setX(textPosition); this.headerActionButton.setX(textPosition - this.headerActionButton.displayWidth - 4); - const voucherUnlocks = gScene.gameData.voucherUnlocks; + const voucherUnlocks = globalScene.gameData.voucherUnlocks; const itemOffset = this.scrollCursor * this.COLS; const itemLimit = this.ROWS * this.COLS; diff --git a/src/ui/admin-ui-handler.ts b/src/ui/admin-ui-handler.ts index 2895d5485e1..2d309696bec 100644 --- a/src/ui/admin-ui-handler.ts +++ b/src/ui/admin-ui-handler.ts @@ -4,7 +4,7 @@ import * as Utils from "../utils"; import { FormModalUiHandler, InputFieldConfig } from "./form-modal-ui-handler"; import { Button } from "#app/enums/buttons"; import { TextStyle } from "./text"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class AdminUiHandler extends FormModalUiHandler { @@ -124,10 +124,10 @@ export default class AdminUiHandler extends FormModalUiHandler { const adminSearchResult: AdminSearchInfo = this.convertInputsToAdmin(); // this converts the input texts into a single object for use later const validFields = this.areFieldsValid(this.adminMode); if (validFields.error) { - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); // this is here to force a loading screen to allow the admin tool to reopen again if there's an error + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); // this is here to force a loading screen to allow the admin tool to reopen again if there's an error return this.showMessage(validFields.errorMessage ?? "", adminSearchResult, true); } - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); if (this.adminMode === AdminMode.LINK) { this.adminLinkUnlink(adminSearchResult, "discord", "Link") // calls server to link discord .then(response => { @@ -156,11 +156,11 @@ export default class AdminUiHandler extends FormModalUiHandler { } showMessage(message: string, adminResult: AdminSearchInfo, isError: boolean) { - gScene.ui.setMode(Mode.ADMIN, Object.assign(this.config, { errorMessage: message?.trim() }), this.adminMode, adminResult, isError); + globalScene.ui.setMode(Mode.ADMIN, Object.assign(this.config, { errorMessage: message?.trim() }), this.adminMode, adminResult, isError); if (isError) { - gScene.ui.playError(); + globalScene.ui.playError(); } else { - gScene.ui.playSelect(); + globalScene.ui.playSelect(); } } @@ -184,7 +184,7 @@ export default class AdminUiHandler extends FormModalUiHandler { this.inputs[i].setText(adminResult[aR]); if (aR === "discordId" || aR === "googleId") { // this is here to add the icons for linking/unlinking of google/discord IDs const nineSlice = this.inputContainers[i].list.find(iC => iC.type === "NineSlice"); - const img = gScene.add.image(this.inputContainers[i].x + nineSlice!.width + this.buttonGap, this.inputContainers[i].y + (Math.floor(nineSlice!.height / 2)), adminResult[aR] === "" ? "link_icon" : "unlink_icon"); + const img = globalScene.add.image(this.inputContainers[i].x + nineSlice!.width + this.buttonGap, this.inputContainers[i].y + (Math.floor(nineSlice!.height / 2)), adminResult[aR] === "" ? "link_icon" : "unlink_icon"); img.setName(`adminBtn_${aR}`); img.setOrigin(0.5, 0.5); img.setInteractive(); @@ -193,15 +193,15 @@ export default class AdminUiHandler extends FormModalUiHandler { const mode = adminResult[aR] === "" ? "Link" : "Unlink"; // this figures out if we're linking or unlinking a service const validFields = this.areFieldsValid(this.adminMode, service); if (validFields.error) { - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); // this is here to force a loading screen to allow the admin tool to reopen again if there's an error + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); // this is here to force a loading screen to allow the admin tool to reopen again if there's an error return this.showMessage(validFields.errorMessage ?? "", adminResult, true); } this.adminLinkUnlink(this.convertInputsToAdmin(), service, mode).then(response => { // attempts to link/unlink depending on the service if (response.error) { - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); return this.showMessage(response.errorType, adminResult, true); // fail } else { // success, reload panel with new results - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); this.adminSearch(adminResult) .then(response => { if (response.error) { @@ -305,16 +305,16 @@ export default class AdminUiHandler extends FormModalUiHandler { private updateAdminPanelInfo(adminSearchResult: AdminSearchInfo, mode?: AdminMode) { mode = mode ?? AdminMode.ADMIN; - gScene.ui.setMode(Mode.ADMIN, { + globalScene.ui.setMode(Mode.ADMIN, { buttonActions: [ // we double revert here and below to go back 2 layers of menus () => { - gScene.ui.revertMode(); - gScene.ui.revertMode(); + globalScene.ui.revertMode(); + globalScene.ui.revertMode(); }, () => { - gScene.ui.revertMode(); - gScene.ui.revertMode(); + globalScene.ui.revertMode(); + globalScene.ui.revertMode(); } ] }, mode, adminSearchResult); diff --git a/src/ui/arena-flyout.ts b/src/ui/arena-flyout.ts index 5770d775f21..f856c1cfab3 100644 --- a/src/ui/arena-flyout.ts +++ b/src/ui/arena-flyout.ts @@ -1,5 +1,5 @@ import { addTextObject, TextStyle } from "./text"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { ArenaTagSide, ArenaTrapTag } from "#app/data/arena-tag"; import { WeatherType } from "#app/data/weather"; import { TerrainType } from "#app/data/terrain"; @@ -96,18 +96,18 @@ export class ArenaFlyout extends Phaser.GameObjects.Container { private readonly onFieldEffectChangedEvent = (event: Event) => this.onFieldEffectChanged(event); constructor() { - super(gScene, 0, 0); + super(globalScene, 0, 0); this.setName("arena-flyout"); this.translationX = this.flyoutWidth; this.anchorX = 0; this.anchorY = -98; - this.flyoutParent = gScene.add.container(this.anchorX - this.translationX, this.anchorY); + this.flyoutParent = globalScene.add.container(this.anchorX - this.translationX, this.anchorY); this.flyoutParent.setAlpha(0); this.add(this.flyoutParent); - this.flyoutContainer = gScene.add.container(0, 0); + this.flyoutContainer = globalScene.add.container(0, 0); this.flyoutParent.add(this.flyoutContainer); this.flyoutWindow = addWindow(0, 0, this.flyoutWidth, this.flyoutHeight, false, false, 0, 0, WindowVariant.THIN); @@ -177,18 +177,18 @@ export class ArenaFlyout extends Phaser.GameObjects.Container { this.flyoutParent.name = "Fight Flyout Parent"; // Subscribes to required events available on game start - gScene.eventTarget.addEventListener(BattleSceneEventType.NEW_ARENA, this.onNewArenaEvent); - gScene.eventTarget.addEventListener(BattleSceneEventType.TURN_END, this.onTurnEndEvent); + globalScene.eventTarget.addEventListener(BattleSceneEventType.NEW_ARENA, this.onNewArenaEvent); + globalScene.eventTarget.addEventListener(BattleSceneEventType.TURN_END, this.onTurnEndEvent); } private onNewArena(event: Event) { this.fieldEffectInfo.length = 0; // Subscribes to required events available on battle start - gScene.arena.eventTarget.addEventListener(ArenaEventType.WEATHER_CHANGED, this.onFieldEffectChangedEvent); - gScene.arena.eventTarget.addEventListener(ArenaEventType.TERRAIN_CHANGED, this.onFieldEffectChangedEvent); - gScene.arena.eventTarget.addEventListener(ArenaEventType.TAG_ADDED, this.onFieldEffectChangedEvent); - gScene.arena.eventTarget.addEventListener(ArenaEventType.TAG_REMOVED, this.onFieldEffectChangedEvent); + globalScene.arena.eventTarget.addEventListener(ArenaEventType.WEATHER_CHANGED, this.onFieldEffectChangedEvent); + globalScene.arena.eventTarget.addEventListener(ArenaEventType.TERRAIN_CHANGED, this.onFieldEffectChangedEvent); + globalScene.arena.eventTarget.addEventListener(ArenaEventType.TAG_ADDED, this.onFieldEffectChangedEvent); + globalScene.arena.eventTarget.addEventListener(ArenaEventType.TAG_REMOVED, this.onFieldEffectChangedEvent); } @@ -251,7 +251,7 @@ export class ArenaFlyout extends Phaser.GameObjects.Container { switch (arenaEffectChangedEvent.constructor) { case TagAddedEvent: const tagAddedEvent = arenaEffectChangedEvent as TagAddedEvent; - const isArenaTrapTag = gScene.arena.getTag(tagAddedEvent.arenaTagType) instanceof ArenaTrapTag; + const isArenaTrapTag = globalScene.arena.getTag(tagAddedEvent.arenaTagType) instanceof ArenaTrapTag; let arenaEffectType: ArenaEffectType; if (tagAddedEvent.arenaTagSide === ArenaTagSide.BOTH) { @@ -363,7 +363,7 @@ export class ArenaFlyout extends Phaser.GameObjects.Container { * @param visible Should the flyout be shown? */ public toggleFlyout(visible: boolean): void { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.flyoutParent, x: visible ? this.anchorX : this.anchorX - this.translationX, duration: Utils.fixedInt(125), @@ -374,13 +374,13 @@ export class ArenaFlyout extends Phaser.GameObjects.Container { } public destroy(fromScene?: boolean): void { - gScene.eventTarget.removeEventListener(BattleSceneEventType.NEW_ARENA, this.onNewArenaEvent); - gScene.eventTarget.removeEventListener(BattleSceneEventType.TURN_END, this.onTurnEndEvent); + globalScene.eventTarget.removeEventListener(BattleSceneEventType.NEW_ARENA, this.onNewArenaEvent); + globalScene.eventTarget.removeEventListener(BattleSceneEventType.TURN_END, this.onTurnEndEvent); - gScene.arena.eventTarget.removeEventListener(ArenaEventType.WEATHER_CHANGED, this.onFieldEffectChangedEvent); - gScene.arena.eventTarget.removeEventListener(ArenaEventType.TERRAIN_CHANGED, this.onFieldEffectChangedEvent); - gScene.arena.eventTarget.removeEventListener(ArenaEventType.TAG_ADDED, this.onFieldEffectChangedEvent); - gScene.arena.eventTarget.removeEventListener(ArenaEventType.TAG_REMOVED, this.onFieldEffectChangedEvent); + globalScene.arena.eventTarget.removeEventListener(ArenaEventType.WEATHER_CHANGED, this.onFieldEffectChangedEvent); + globalScene.arena.eventTarget.removeEventListener(ArenaEventType.TERRAIN_CHANGED, this.onFieldEffectChangedEvent); + globalScene.arena.eventTarget.removeEventListener(ArenaEventType.TAG_ADDED, this.onFieldEffectChangedEvent); + globalScene.arena.eventTarget.removeEventListener(ArenaEventType.TAG_REMOVED, this.onFieldEffectChangedEvent); super.destroy(fromScene); } diff --git a/src/ui/awaitable-ui-handler.ts b/src/ui/awaitable-ui-handler.ts index f191f8d397c..7470b169033 100644 --- a/src/ui/awaitable-ui-handler.ts +++ b/src/ui/awaitable-ui-handler.ts @@ -1,7 +1,7 @@ import { Mode } from "./ui"; import UiHandler from "./ui-handler"; import { Button } from "#enums/buttons"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default abstract class AwaitableUiHandler extends UiHandler { protected awaitingActionInput: boolean; @@ -32,7 +32,7 @@ export default abstract class AwaitableUiHandler extends UiHandler { */ initTutorialOverlay(container: Phaser.GameObjects.Container) { if (!this.tutorialOverlay) { - this.tutorialOverlay = new Phaser.GameObjects.Rectangle(gScene, -1, -1, gScene.scaledCanvas.width, gScene.scaledCanvas.height, 0x070707); + this.tutorialOverlay = new Phaser.GameObjects.Rectangle(globalScene, -1, -1, globalScene.scaledCanvas.width, globalScene.scaledCanvas.height, 0x070707); this.tutorialOverlay.setName("tutorial-overlay"); this.tutorialOverlay.setOrigin(0, 0); this.tutorialOverlay.setAlpha(0); diff --git a/src/ui/ball-ui-handler.ts b/src/ui/ball-ui-handler.ts index 20cad686864..52cd19d2ea4 100644 --- a/src/ui/ball-ui-handler.ts +++ b/src/ui/ball-ui-handler.ts @@ -6,7 +6,7 @@ import UiHandler from "./ui-handler"; import { addWindow } from "./ui-theme"; import { Button } from "#enums/buttons"; import { CommandPhase } from "#app/phases/command-phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class BallUiHandler extends UiHandler { private pokeballSelectContainer: Phaser.GameObjects.Container; @@ -24,17 +24,17 @@ export default class BallUiHandler extends UiHandler { setup() { const ui = this.getUi(); - this.scale = getTextStyleOptions(TextStyle.WINDOW, gScene.uiTheme).scale; + this.scale = getTextStyleOptions(TextStyle.WINDOW, globalScene.uiTheme).scale; let optionsTextContent = ""; - for (let pb = 0; pb < Object.keys(gScene.pokeballCounts).length; pb++) { + for (let pb = 0; pb < Object.keys(globalScene.pokeballCounts).length; pb++) { optionsTextContent += `${getPokeballName(pb)}\n`; } optionsTextContent += "Cancel"; const optionsText = addTextObject(0, 0, optionsTextContent, TextStyle.WINDOW, { align: "right", maxLines: 6 }); const optionsTextWidth = optionsText.displayWidth; - this.pokeballSelectContainer = gScene.add.container((gScene.game.canvas.width / 6) - 51 - Math.max(64, optionsTextWidth), -49); + this.pokeballSelectContainer = globalScene.add.container((globalScene.game.canvas.width / 6) - 51 - Math.max(64, optionsTextWidth), -49); this.pokeballSelectContainer.setVisible(false); ui.add(this.pokeballSelectContainer); @@ -69,16 +69,16 @@ export default class BallUiHandler extends UiHandler { let success = false; - const pokeballTypeCount = Object.keys(gScene.pokeballCounts).length; + const pokeballTypeCount = Object.keys(globalScene.pokeballCounts).length; if (button === Button.ACTION || button === Button.CANCEL) { - const commandPhase = gScene.getCurrentPhase() as CommandPhase; + const commandPhase = globalScene.getCurrentPhase() as CommandPhase; success = true; if (button === Button.ACTION && this.cursor < pokeballTypeCount) { - if (gScene.pokeballCounts[this.cursor]) { + if (globalScene.pokeballCounts[this.cursor]) { if (commandPhase.handleCommand(Command.BALL, this.cursor)) { - gScene.ui.setMode(Mode.COMMAND, commandPhase.getFieldIndex()); - gScene.ui.setMode(Mode.MESSAGE); + globalScene.ui.setMode(Mode.COMMAND, commandPhase.getFieldIndex()); + globalScene.ui.setMode(Mode.MESSAGE); success = true; } } else { @@ -107,14 +107,14 @@ export default class BallUiHandler extends UiHandler { } updateCounts() { - this.countsText.setText(Object.values(gScene.pokeballCounts).map(c => `x${c}`).join("\n")); + this.countsText.setText(Object.values(globalScene.pokeballCounts).map(c => `x${c}`).join("\n")); } setCursor(cursor: integer): boolean { const ret = super.setCursor(cursor); if (!this.cursorObj) { - this.cursorObj = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.image(0, 0, "cursor"); this.pokeballSelectContainer.add(this.cursorObj); } diff --git a/src/ui/battle-flyout.ts b/src/ui/battle-flyout.ts index d8f78b0f688..f950ac87984 100644 --- a/src/ui/battle-flyout.ts +++ b/src/ui/battle-flyout.ts @@ -1,7 +1,7 @@ import { default as Pokemon } from "../field/pokemon"; import { addTextObject, TextStyle } from "./text"; import * as Utils from "../utils"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import Move from "#app/data/move"; import { BattleSceneEventType, BerryUsedEvent, MoveUsedEvent } from "../events/battle-scene"; import { BerryType } from "#enums/berry-type"; @@ -61,7 +61,7 @@ export default class BattleFlyout extends Phaser.GameObjects.Container { private readonly onBerryUsedEvent = (event: Event) => this.onBerryUsed(event); constructor(player: boolean) { - super(gScene, 0, 0); + super(globalScene, 0, 0); // Note that all player based flyouts are disabled. This is included in case of future development this.player = player; @@ -70,17 +70,17 @@ export default class BattleFlyout extends Phaser.GameObjects.Container { this.anchorX = (this.player ? -130 : -40); this.anchorY = -2.5 + (this.player ? -18.5 : -13); - this.flyoutParent = gScene.add.container(this.anchorX - this.translationX, this.anchorY); + this.flyoutParent = globalScene.add.container(this.anchorX - this.translationX, this.anchorY); this.flyoutParent.setAlpha(0); this.add(this.flyoutParent); // Load the background image - this.flyoutBackground = gScene.add.sprite(0, 0, "pbinfo_enemy_boss_stats"); + this.flyoutBackground = globalScene.add.sprite(0, 0, "pbinfo_enemy_boss_stats"); this.flyoutBackground.setOrigin(0, 0); this.flyoutParent.add(this.flyoutBackground); - this.flyoutContainer = gScene.add.container(44 + (this.player ? -this.flyoutWidth : 0), 2); + this.flyoutContainer = globalScene.add.container(44 + (this.player ? -this.flyoutWidth : 0), 2); this.flyoutParent.add(this.flyoutContainer); // Loops through and sets the position of each text object according to the width and height of the flyout @@ -97,9 +97,9 @@ export default class BattleFlyout extends Phaser.GameObjects.Container { this.flyoutContainer.add(this.flyoutText); this.flyoutContainer.add( - new Phaser.GameObjects.Rectangle(gScene, this.flyoutWidth / 2, 0, 1, this.flyoutHeight + (gScene.uiTheme === UiTheme.LEGACY ? 1 : 0), 0x212121).setOrigin(0.5, 0)); + new Phaser.GameObjects.Rectangle(globalScene, this.flyoutWidth / 2, 0, 1, this.flyoutHeight + (globalScene.uiTheme === UiTheme.LEGACY ? 1 : 0), 0x212121).setOrigin(0.5, 0)); this.flyoutContainer.add( - new Phaser.GameObjects.Rectangle(gScene, 0, this.flyoutHeight / 2, this.flyoutWidth + 6, 1, 0x212121).setOrigin(0, 0.5)); + new Phaser.GameObjects.Rectangle(globalScene, 0, this.flyoutHeight / 2, this.flyoutWidth + 6, 1, 0x212121).setOrigin(0, 0.5)); } /** @@ -112,8 +112,8 @@ export default class BattleFlyout extends Phaser.GameObjects.Container { this.name = `Flyout ${getPokemonNameWithAffix(this.pokemon)}`; this.flyoutParent.name = `Flyout Parent ${getPokemonNameWithAffix(this.pokemon)}`; - gScene.eventTarget.addEventListener(BattleSceneEventType.MOVE_USED, this.onMoveUsedEvent); - gScene.eventTarget.addEventListener(BattleSceneEventType.BERRY_USED, this.onBerryUsedEvent); + globalScene.eventTarget.addEventListener(BattleSceneEventType.MOVE_USED, this.onMoveUsedEvent); + globalScene.eventTarget.addEventListener(BattleSceneEventType.BERRY_USED, this.onBerryUsedEvent); } /** Sets and formats the text property for all {@linkcode Phaser.GameObjects.Text} in the flyoutText array */ @@ -171,7 +171,7 @@ export default class BattleFlyout extends Phaser.GameObjects.Container { toggleFlyout(visible: boolean): void { this.flyoutVisible = visible; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.flyoutParent, x: visible ? this.anchorX : this.anchorX - this.translationX, duration: Utils.fixedInt(125), @@ -181,8 +181,8 @@ export default class BattleFlyout extends Phaser.GameObjects.Container { } destroy(fromScene?: boolean): void { - gScene.eventTarget.removeEventListener(BattleSceneEventType.MOVE_USED, this.onMoveUsedEvent); - gScene.eventTarget.removeEventListener(BattleSceneEventType.BERRY_USED, this.onBerryUsedEvent); + globalScene.eventTarget.removeEventListener(BattleSceneEventType.MOVE_USED, this.onMoveUsedEvent); + globalScene.eventTarget.removeEventListener(BattleSceneEventType.BERRY_USED, this.onBerryUsedEvent); super.destroy(fromScene); } diff --git a/src/ui/battle-info.ts b/src/ui/battle-info.ts index 2b35b79ce02..46593dc5d9f 100644 --- a/src/ui/battle-info.ts +++ b/src/ui/battle-info.ts @@ -4,7 +4,7 @@ import * as Utils from "../utils"; import { addTextObject, TextStyle } from "./text"; import { getGenderSymbol, getGenderColor, Gender } from "../data/gender"; import { StatusEffect } from "../data/status-effect"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Type, getTypeRgb } from "../data/type"; import { getVariantTint } from "#app/data/variant"; import { Stat } from "#enums/stat"; @@ -76,7 +76,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { private readonly statOrderEnemy = [ Stat.HP, Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.ACC, Stat.EVA, Stat.SPD ]; constructor(x: number, y: number, player: boolean) { - super(gScene, x, y); + super(globalScene, x, y); this.baseY = y; this.player = player; this.mini = !player; @@ -95,7 +95,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { // Initially invisible and shown via Pokemon.showInfo this.setVisible(false); - this.box = gScene.add.sprite(0, 0, this.getTextureName()); + this.box = globalScene.add.sprite(0, 0, this.getTextureName()); this.box.setName("box"); this.box.setOrigin(1, 0.5); this.add(this.box); @@ -112,14 +112,14 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.add(this.genderText); if (!this.player) { - this.ownedIcon = gScene.add.sprite(0, 0, "icon_owned"); + this.ownedIcon = globalScene.add.sprite(0, 0, "icon_owned"); this.ownedIcon.setName("icon_owned"); this.ownedIcon.setVisible(false); this.ownedIcon.setOrigin(0, 0); this.ownedIcon.setPositionRelative(this.nameText, 0, 11.75); this.add(this.ownedIcon); - this.championRibbon = gScene.add.sprite(0, 0, "champion_ribbon"); + this.championRibbon = globalScene.add.sprite(0, 0, "champion_ribbon"); this.championRibbon.setName("icon_champion_ribbon"); this.championRibbon.setVisible(false); this.championRibbon.setOrigin(0, 0); @@ -127,7 +127,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.add(this.championRibbon); } - this.teraIcon = gScene.add.sprite(0, 0, "icon_tera"); + this.teraIcon = globalScene.add.sprite(0, 0, "icon_tera"); this.teraIcon.setName("icon_tera"); this.teraIcon.setVisible(false); this.teraIcon.setOrigin(0, 0); @@ -136,7 +136,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.teraIcon.setInteractive(new Phaser.Geom.Rectangle(0, 0, 12, 15), Phaser.Geom.Rectangle.Contains); this.add(this.teraIcon); - this.shinyIcon = gScene.add.sprite(0, 0, "shiny_star"); + this.shinyIcon = globalScene.add.sprite(0, 0, "shiny_star"); this.shinyIcon.setName("icon_shiny"); this.shinyIcon.setVisible(false); this.shinyIcon.setOrigin(0, 0); @@ -145,7 +145,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.shinyIcon.setInteractive(new Phaser.Geom.Rectangle(0, 0, 12, 15), Phaser.Geom.Rectangle.Contains); this.add(this.shinyIcon); - this.fusionShinyIcon = gScene.add.sprite(0, 0, "shiny_star_2"); + this.fusionShinyIcon = globalScene.add.sprite(0, 0, "shiny_star_2"); this.fusionShinyIcon.setName("icon_fusion_shiny"); this.fusionShinyIcon.setVisible(false); this.fusionShinyIcon.setOrigin(0, 0); @@ -153,7 +153,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.fusionShinyIcon.setPosition(this.shinyIcon.x, this.shinyIcon.y); this.add(this.fusionShinyIcon); - this.splicedIcon = gScene.add.sprite(0, 0, "icon_spliced"); + this.splicedIcon = globalScene.add.sprite(0, 0, "icon_spliced"); this.splicedIcon.setName("icon_spliced"); this.splicedIcon.setVisible(false); this.splicedIcon.setOrigin(0, 0); @@ -162,42 +162,42 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.splicedIcon.setInteractive(new Phaser.Geom.Rectangle(0, 0, 12, 15), Phaser.Geom.Rectangle.Contains); this.add(this.splicedIcon); - this.statusIndicator = gScene.add.sprite(0, 0, Utils.getLocalizedSpriteKey("statuses")); + this.statusIndicator = globalScene.add.sprite(0, 0, Utils.getLocalizedSpriteKey("statuses")); this.statusIndicator.setName("icon_status"); this.statusIndicator.setVisible(false); this.statusIndicator.setOrigin(0, 0); this.statusIndicator.setPositionRelative(this.nameText, 0, 11.5); this.add(this.statusIndicator); - this.levelContainer = gScene.add.container(player ? -41 : -50, player ? -10 : -5); + this.levelContainer = globalScene.add.container(player ? -41 : -50, player ? -10 : -5); this.levelContainer.setName("container_level"); this.add(this.levelContainer); - const levelOverlay = gScene.add.image(0, 0, "overlay_lv"); + const levelOverlay = globalScene.add.image(0, 0, "overlay_lv"); this.levelContainer.add(levelOverlay); - this.hpBar = gScene.add.image(player ? -61 : -71, player ? -1 : 4.5, "overlay_hp"); + this.hpBar = globalScene.add.image(player ? -61 : -71, player ? -1 : 4.5, "overlay_hp"); this.hpBar.setName("hp_bar"); this.hpBar.setOrigin(0); this.add(this.hpBar); this.hpBarSegmentDividers = []; - this.levelNumbersContainer = gScene.add.container(9.5, gScene.uiTheme ? 0 : -0.5); + this.levelNumbersContainer = globalScene.add.container(9.5, globalScene.uiTheme ? 0 : -0.5); this.levelNumbersContainer.setName("container_level"); this.levelContainer.add(this.levelNumbersContainer); if (this.player) { - this.hpNumbersContainer = gScene.add.container(-15, 10); + this.hpNumbersContainer = globalScene.add.container(-15, 10); this.hpNumbersContainer.setName("container_hp"); this.add(this.hpNumbersContainer); - const expBar = gScene.add.image(-98, 18, "overlay_exp"); + const expBar = globalScene.add.image(-98, 18, "overlay_exp"); expBar.setName("overlay_exp"); expBar.setOrigin(0); this.add(expBar); - const expMaskRect = gScene.make.graphics({}); + const expMaskRect = globalScene.make.graphics({}); expMaskRect.setScale(6); expMaskRect.fillStyle(0xFFFFFF); expMaskRect.beginPath(); @@ -211,12 +211,12 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.expMaskRect = expMaskRect; } - this.statsContainer = gScene.add.container(0, 0); + this.statsContainer = globalScene.add.container(0, 0); this.statsContainer.setName("container_stats"); this.statsContainer.setAlpha(0); this.add(this.statsContainer); - this.statsBox = gScene.add.sprite(0, 0, `${this.getTextureName()}_stats`); + this.statsBox = globalScene.add.sprite(0, 0, `${this.getTextureName()}_stats`); this.statsBox.setName("box_stats"); this.statsBox.setOrigin(1, 0.5); this.statsContainer.add(this.statsBox); @@ -224,7 +224,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { const statLabels: Phaser.GameObjects.Sprite[] = []; this.statNumbers = []; - this.statValuesContainer = gScene.add.container(0, 0); + this.statValuesContainer = globalScene.add.container(0, 0); this.statsContainer.add(this.statValuesContainer); // this gives us a different starting location from the left of the label and padding between stats for a player vs enemy @@ -248,13 +248,13 @@ export default class BattleInfo extends Phaser.GameObjects.Container { statY = baseY + (!!(i % 2) === this.player ? 10 : 0); // we compare i % 2 against this.player to tell us where to place the label; because this.battleStatOrder for enemies has HP, this.battleStatOrder[1]=ATK, but for players this.battleStatOrder[0]=ATK, so this comparing i % 2 to this.player fixes this issue for us } - const statLabel = gScene.add.sprite(statX, statY, "pbinfo_stat", Stat[s]); + const statLabel = globalScene.add.sprite(statX, statY, "pbinfo_stat", Stat[s]); statLabel.setName("icon_stat_label_" + i.toString()); statLabel.setOrigin(0, 0); statLabels.push(statLabel); this.statValuesContainer.add(statLabel); - const statNumber = gScene.add.sprite(statX + statLabel.width, statY, "pbinfo_stat_numbers", this.statOrder[i] !== Stat.HP ? "3" : "empty"); + const statNumber = globalScene.add.sprite(statX + statLabel.width, statY, "pbinfo_stat_numbers", this.statOrder[i] !== Stat.HP ? "3" : "empty"); statNumber.setName("icon_stat_number_" + i.toString()); statNumber.setOrigin(0, 0); this.statNumbers.push(statNumber); @@ -274,23 +274,23 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.moveBelow(this.flyoutMenu, this.box); } - this.type1Icon = gScene.add.sprite(player ? -139 : -15, player ? -17 : -15.5, `pbinfo_${player ? "player" : "enemy"}_type1`); + this.type1Icon = globalScene.add.sprite(player ? -139 : -15, player ? -17 : -15.5, `pbinfo_${player ? "player" : "enemy"}_type1`); this.type1Icon.setName("icon_type_1"); this.type1Icon.setOrigin(0, 0); this.add(this.type1Icon); - this.type2Icon = gScene.add.sprite(player ? -139 : -15, player ? -1 : -2.5, `pbinfo_${player ? "player" : "enemy"}_type2`); + this.type2Icon = globalScene.add.sprite(player ? -139 : -15, player ? -1 : -2.5, `pbinfo_${player ? "player" : "enemy"}_type2`); this.type2Icon.setName("icon_type_2"); this.type2Icon.setOrigin(0, 0); this.add(this.type2Icon); - this.type3Icon = gScene.add.sprite(player ? -154 : 0, player ? -17 : -15.5, `pbinfo_${player ? "player" : "enemy"}_type`); + this.type3Icon = globalScene.add.sprite(player ? -154 : 0, player ? -17 : -15.5, `pbinfo_${player ? "player" : "enemy"}_type`); this.type3Icon.setName("icon_type_3"); this.type3Icon.setOrigin(0, 0); this.add(this.type3Icon); if (!this.player) { - this.effectivenessContainer = gScene.add.container(0, 0); + this.effectivenessContainer = globalScene.add.container(0, 0); this.effectivenessContainer.setPositionRelative(this.type1Icon, 22, 4); this.effectivenessContainer.setVisible(false); this.add(this.effectivenessContainer); @@ -326,18 +326,18 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.teraIcon.setVisible(this.lastTeraType !== Type.UNKNOWN); this.teraIcon.on("pointerover", () => { if (this.lastTeraType !== Type.UNKNOWN) { - gScene.ui.showTooltip("", i18next.t("fightUiHandler:teraHover", { type: i18next.t(`pokemonInfo:Type.${Type[this.lastTeraType]}`) })); + globalScene.ui.showTooltip("", i18next.t("fightUiHandler:teraHover", { type: i18next.t(`pokemonInfo:Type.${Type[this.lastTeraType]}`) })); } }); - this.teraIcon.on("pointerout", () => gScene.ui.hideTooltip()); + this.teraIcon.on("pointerout", () => globalScene.ui.hideTooltip()); const isFusion = pokemon.isFusion(); this.splicedIcon.setPositionRelative(this.nameText, nameTextWidth + this.genderText.displayWidth + 1 + (this.teraIcon.visible ? this.teraIcon.displayWidth + 1 : 0), 2.5); this.splicedIcon.setVisible(isFusion); if (this.splicedIcon.visible) { - this.splicedIcon.on("pointerover", () => gScene.ui.showTooltip("", `${pokemon.species.getName(pokemon.formIndex)}/${pokemon.fusionSpecies?.getName(pokemon.fusionFormIndex)}`)); - this.splicedIcon.on("pointerout", () => gScene.ui.hideTooltip()); + this.splicedIcon.on("pointerover", () => globalScene.ui.showTooltip("", `${pokemon.species.getName(pokemon.formIndex)}/${pokemon.fusionSpecies?.getName(pokemon.fusionFormIndex)}`)); + this.splicedIcon.on("pointerout", () => globalScene.ui.hideTooltip()); } const doubleShiny = isFusion && pokemon.shiny && pokemon.fusionShiny; @@ -351,8 +351,8 @@ export default class BattleInfo extends Phaser.GameObjects.Container { const shinyDescriptor = doubleShiny || baseVariant ? `${baseVariant === 2 ? i18next.t("common:epicShiny") : baseVariant === 1 ? i18next.t("common:rareShiny") : i18next.t("common:commonShiny")}${doubleShiny ? `/${pokemon.fusionVariant === 2 ? i18next.t("common:epicShiny") : pokemon.fusionVariant === 1 ? i18next.t("common:rareShiny") : i18next.t("common:commonShiny")}` : ""}` : ""; - this.shinyIcon.on("pointerover", () => gScene.ui.showTooltip("", `${i18next.t("common:shinyOnHover")}${shinyDescriptor ? ` (${shinyDescriptor})` : ""}`)); - this.shinyIcon.on("pointerout", () => gScene.ui.hideTooltip()); + this.shinyIcon.on("pointerover", () => globalScene.ui.showTooltip("", `${i18next.t("common:shinyOnHover")}${shinyDescriptor ? ` (${shinyDescriptor})` : ""}`)); + this.shinyIcon.on("pointerout", () => globalScene.ui.hideTooltip()); } this.fusionShinyIcon.setPosition(this.shinyIcon.x, this.shinyIcon.y); @@ -363,15 +363,15 @@ export default class BattleInfo extends Phaser.GameObjects.Container { if (!this.player) { if (this.nameText.visible) { - this.nameText.on("pointerover", () => gScene.ui.showTooltip("", i18next.t("battleInfo:generation", { generation: i18next.t(`starterSelectUiHandler:gen${pokemon.species.generation}`) }))); - this.nameText.on("pointerout", () => gScene.ui.hideTooltip()); + this.nameText.on("pointerover", () => globalScene.ui.showTooltip("", i18next.t("battleInfo:generation", { generation: i18next.t(`starterSelectUiHandler:gen${pokemon.species.generation}`) }))); + this.nameText.on("pointerout", () => globalScene.ui.hideTooltip()); } - const dexEntry = gScene.gameData.dexData[pokemon.species.speciesId]; + const dexEntry = globalScene.gameData.dexData[pokemon.species.speciesId]; this.ownedIcon.setVisible(!!dexEntry.caughtAttr); const opponentPokemonDexAttr = pokemon.getDexAttr(); - if (gScene.gameMode.isClassic) { - if (gScene.gameData.starterData[pokemon.species.getRootSpeciesId()].classicWinCount > 0 && gScene.gameData.starterData[pokemon.species.getRootSpeciesId(true)].classicWinCount > 0) { + if (globalScene.gameMode.isClassic) { + if (globalScene.gameData.starterData[pokemon.species.getRootSpeciesId()].classicWinCount > 0 && globalScene.gameData.starterData[pokemon.species.getRootSpeciesId(true)].classicWinCount > 0) { this.championRibbon.setVisible(true); } } @@ -379,7 +379,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { // Check if Player owns all genders and forms of the Pokemon const missingDexAttrs = ((dexEntry.caughtAttr & opponentPokemonDexAttr) < opponentPokemonDexAttr); - const ownedAbilityAttrs = gScene.gameData.starterData[pokemon.species.getRootSpeciesId()].abilityAttr; + const ownedAbilityAttrs = globalScene.gameData.starterData[pokemon.species.getRootSpeciesId()].abilityAttr; // Check if the player owns ability for the root form const playerOwnsThisAbility = pokemon.checkIfPlayerHasAbilityOfStarter(ownedAbilityAttrs); @@ -468,7 +468,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { } toggleStats(visible: boolean): void { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.statsContainer, duration: Utils.fixedInt(125), ease: "Sine.easeInOut", @@ -500,11 +500,11 @@ export default class BattleInfo extends Phaser.GameObjects.Container { } if (this.boss && this.bossSegments > 1) { - const uiTheme = gScene.uiTheme; + const uiTheme = globalScene.uiTheme; const maxHp = pokemon.getMaxHp(); for (let s = 1; s < this.bossSegments; s++) { const dividerX = (Math.round((maxHp / this.bossSegments) * s) / maxHp) * this.hpBar.width; - const divider = gScene.add.rectangle(0, 0, 1, this.hpBar.height - (uiTheme ? 0 : 1), pokemon.bossSegmentIndex >= s ? 0xFFFFFF : 0x404040); + const divider = globalScene.add.rectangle(0, 0, 1, this.hpBar.height - (uiTheme ? 0 : 1), pokemon.bossSegmentIndex >= s ? 0xFFFFFF : 0x404040); divider.setOrigin(0.5, 0); divider.setName("hpBar_divider_" + s.toString()); this.add(divider); @@ -530,7 +530,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { updateInfo(pokemon: Pokemon, instant?: boolean): Promise { return new Promise(resolve => { - if (!gScene) { + if (!globalScene) { return resolve(); } @@ -594,11 +594,11 @@ export default class BattleInfo extends Phaser.GameObjects.Container { const updatePokemonHp = () => { let duration = !instant ? Phaser.Math.Clamp(Math.abs((this.lastHp) - pokemon.hp) * 5, 250, 5000) : 0; - const speed = gScene.hpBarSpeed; + const speed = globalScene.hpBarSpeed; if (speed) { duration = speed >= 3 ? 0 : duration / Math.pow(2, speed); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.hpBar, ease: "Sine.easeOut", scaleX: pokemon.getHpRatio(true), @@ -624,7 +624,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { }; if (this.player) { - const isLevelCapped = pokemon.level >= gScene.getMaxExpLevel(); + const isLevelCapped = pokemon.level >= globalScene.getMaxExpLevel(); if ((this.lastExp !== pokemon.exp || this.lastLevel !== pokemon.level)) { const originalResolve = resolve; @@ -687,7 +687,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { const relLevelExp = getLevelRelExp(this.lastLevel + 1, pokemon.species.growthRate); const levelExp = levelUp ? relLevelExp : pokemon.levelExp; let ratio = relLevelExp ? levelExp / relLevelExp : 0; - if (this.lastLevel >= gScene.getMaxExpLevel(true)) { + if (this.lastLevel >= globalScene.getMaxExpLevel(true)) { if (levelUp) { ratio = 1; } else { @@ -697,7 +697,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { } const durationMultiplier = Phaser.Tweens.Builders.GetEaseFunction("Sine.easeIn")(1 - (Math.max(this.lastLevel - 100, 0) / 150)); let duration = this.visible && !instant ? (((levelExp - this.lastLevelExp) / relLevelExp) * BattleInfo.EXP_GAINS_DURATION_BASE) * durationMultiplier * levelDurationMultiplier : 0; - const speed = gScene.expGainsSpeed; + const speed = globalScene.expGainsSpeed; if (speed && speed >= ExpGainsSpeed.DEFAULT) { duration = speed >= ExpGainsSpeed.SKIP ? ExpGainsSpeed.DEFAULT : duration / Math.pow(2, speed); } @@ -709,24 +709,24 @@ export default class BattleInfo extends Phaser.GameObjects.Container { this.lastLevelExp = pokemon.levelExp; } if (duration) { - gScene.playSound("se/exp"); + globalScene.playSound("se/exp"); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.expMaskRect, ease: "Sine.easeIn", x: ratio * 510, duration: duration, onComplete: () => { - if (!gScene) { + if (!globalScene) { return resolve(); } if (duration) { - gScene.sound.stopByKey("se/exp"); + globalScene.sound.stopByKey("se/exp"); } if (ratio === 1) { - gScene.playSound("se/level_up"); + globalScene.playSound("se/level_up"); this.setLevel(this.lastLevel); - gScene.time.delayedCall(500 * levelDurationMultiplier, () => { + globalScene.time.delayedCall(500 * levelDurationMultiplier, () => { this.expMaskRect.x = 0; this.updateInfo(pokemon, instant).then(() => resolve()); }); @@ -739,17 +739,17 @@ export default class BattleInfo extends Phaser.GameObjects.Container { } setLevel(level: integer): void { - const isCapped = level >= gScene.getMaxExpLevel(); + const isCapped = level >= globalScene.getMaxExpLevel(); this.levelNumbersContainer.removeAll(true); const levelStr = level.toString(); for (let i = 0; i < levelStr.length; i++) { - this.levelNumbersContainer.add(gScene.add.image(i * 8, 0, `numbers${isCapped && this.player ? "_red" : ""}`, levelStr[i])); + this.levelNumbersContainer.add(globalScene.add.image(i * 8, 0, `numbers${isCapped && this.player ? "_red" : ""}`, levelStr[i])); } this.levelContainer.setX((this.player ? -41 : -50) - 8 * Math.max(levelStr.length - 3, 0)); } setHpNumbers(hp: integer, maxHp: integer): void { - if (!this.player || !gScene) { + if (!this.player || !globalScene) { return; } this.hpNumbersContainer.removeAll(true); @@ -757,11 +757,11 @@ export default class BattleInfo extends Phaser.GameObjects.Container { const maxHpStr = maxHp.toString(); let offset = 0; for (let i = maxHpStr.length - 1; i >= 0; i--) { - this.hpNumbersContainer.add(gScene.add.image(offset++ * -8, 0, "numbers", maxHpStr[i])); + this.hpNumbersContainer.add(globalScene.add.image(offset++ * -8, 0, "numbers", maxHpStr[i])); } - this.hpNumbersContainer.add(gScene.add.image(offset++ * -8, 0, "numbers", "/")); + this.hpNumbersContainer.add(globalScene.add.image(offset++ * -8, 0, "numbers", "/")); for (let i = hpStr.length - 1; i >= 0; i--) { - this.hpNumbersContainer.add(gScene.add.image(offset++ * -8, 0, "numbers", hpStr[i])); + this.hpNumbersContainer.add(globalScene.add.image(offset++ * -8, 0, "numbers", hpStr[i])); } } @@ -796,7 +796,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { } this.currentEffectiveness = effectiveness; - if (!gScene.typeHints || effectiveness === undefined || this.flyoutMenu?.flyoutVisible) { + if (!globalScene.typeHints || effectiveness === undefined || this.flyoutMenu?.flyoutVisible) { this.effectivenessContainer.setVisible(false); return; } @@ -817,7 +817,7 @@ export default class BattleInfo extends Phaser.GameObjects.Container { export class PlayerBattleInfo extends BattleInfo { constructor() { - super(Math.floor(gScene.game.canvas.width / 6) - 10, -72, true); + super(Math.floor(globalScene.game.canvas.width / 6) - 10, -72, true); } } diff --git a/src/ui/battle-message-ui-handler.ts b/src/ui/battle-message-ui-handler.ts index ebf94599ce2..abd216f5499 100644 --- a/src/ui/battle-message-ui-handler.ts +++ b/src/ui/battle-message-ui-handler.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { addBBCodeTextObject, addTextObject, getTextColor, TextStyle } from "./text"; import { Mode } from "./ui"; import MessageUiHandler from "./message-ui-handler"; @@ -32,7 +32,7 @@ export default class BattleMessageUiHandler extends MessageUiHandler { this.textTimer = null; this.textCallbackTimer = null; - this.bg = gScene.add.sprite(0, 0, "bg", gScene.windowType); + this.bg = globalScene.add.sprite(0, 0, "bg", globalScene.windowType); this.bg.setName("sprite-battle-msg-bg"); this.bg.setOrigin(0, 1); ui.add(this.bg); @@ -43,7 +43,7 @@ export default class BattleMessageUiHandler extends MessageUiHandler { this.commandWindow.setVisible(false); ui.add(this.commandWindow); - this.movesWindowContainer = gScene.add.container(0, 0); + this.movesWindowContainer = globalScene.add.container(0, 0); this.movesWindowContainer.setName("moves-bg"); this.movesWindowContainer.setVisible(false); @@ -58,7 +58,7 @@ export default class BattleMessageUiHandler extends MessageUiHandler { this.movesWindowContainer.add([ movesWindow, moveDetailsWindow ]); ui.add(this.movesWindowContainer); - const messageContainer = gScene.add.container(12, -39); + const messageContainer = globalScene.add.container(12, -39); ui.add(messageContainer); const message = addTextObject(0, 0, "", TextStyle.MESSAGE, { @@ -71,10 +71,10 @@ export default class BattleMessageUiHandler extends MessageUiHandler { this.message = message; - this.nameBoxContainer = gScene.add.container(0, -16); + this.nameBoxContainer = globalScene.add.container(0, -16); this.nameBoxContainer.setVisible(false); - this.nameBox = gScene.add.nineslice(0, 0, "namebox", gScene.windowType, 72, 16, 8, 8, 5, 5); + this.nameBox = globalScene.add.nineslice(0, 0, "namebox", globalScene.windowType, 72, 16, 8, 8, 5, 5); this.nameBox.setOrigin(0, 0); this.nameText = addTextObject(8, 0, "Rival", TextStyle.MESSAGE, { maxLines: 1 }); @@ -85,13 +85,13 @@ export default class BattleMessageUiHandler extends MessageUiHandler { this.initPromptSprite(messageContainer); - const levelUpStatsContainer = gScene.add.container(0, 0); + const levelUpStatsContainer = globalScene.add.container(0, 0); levelUpStatsContainer.setVisible(false); ui.add(levelUpStatsContainer); this.levelUpStatsContainer = levelUpStatsContainer; - const levelUpStatsLabelsContent = addTextObject((gScene.game.canvas.width / 6) - 73, -94, "", TextStyle.WINDOW, { maxLines: 6 }); + const levelUpStatsLabelsContent = addTextObject((globalScene.game.canvas.width / 6) - 73, -94, "", TextStyle.WINDOW, { maxLines: 6 }); levelUpStatsLabelsContent.setLineSpacing(i18next.resolvedLanguage === "ja" ? 25 : 5); let levelUpStatsLabelText = ""; @@ -101,19 +101,19 @@ export default class BattleMessageUiHandler extends MessageUiHandler { levelUpStatsLabelsContent.text = levelUpStatsLabelText; levelUpStatsLabelsContent.x -= levelUpStatsLabelsContent.displayWidth; - const levelUpStatsBg = addWindow((gScene.game.canvas.width / 6), -100, 80 + levelUpStatsLabelsContent.displayWidth, 100); + const levelUpStatsBg = addWindow((globalScene.game.canvas.width / 6), -100, 80 + levelUpStatsLabelsContent.displayWidth, 100); levelUpStatsBg.setOrigin(1, 0); levelUpStatsContainer.add(levelUpStatsBg); levelUpStatsContainer.add(levelUpStatsLabelsContent); - const levelUpStatsIncrContent = addTextObject((gScene.game.canvas.width / 6) - 50, -94, "+\n+\n+\n+\n+\n+", TextStyle.WINDOW, { maxLines: 6 }); + const levelUpStatsIncrContent = addTextObject((globalScene.game.canvas.width / 6) - 50, -94, "+\n+\n+\n+\n+\n+", TextStyle.WINDOW, { maxLines: 6 }); levelUpStatsIncrContent.setLineSpacing(i18next.resolvedLanguage === "ja" ? 25 : 5); levelUpStatsContainer.add(levelUpStatsIncrContent); this.levelUpStatsIncrContent = levelUpStatsIncrContent; - const levelUpStatsValuesContent = addBBCodeTextObject((gScene.game.canvas.width / 6) - 7, -94, "", TextStyle.WINDOW, { maxLines: 6, lineSpacing: 5 }); + const levelUpStatsValuesContent = addBBCodeTextObject((globalScene.game.canvas.width / 6) - 7, -94, "", TextStyle.WINDOW, { maxLines: 6, lineSpacing: 5 }); levelUpStatsValuesContent.setLineSpacing(i18next.resolvedLanguage === "ja" ? 25 : 5); levelUpStatsValuesContent.setOrigin(1, 0); levelUpStatsValuesContent.setAlign("right"); @@ -167,10 +167,10 @@ export default class BattleMessageUiHandler extends MessageUiHandler { promptLevelUpStats(partyMemberIndex: integer, prevStats: integer[], showTotals: boolean): Promise { return new Promise(resolve => { - if (!gScene.showLevelUpStats) { + if (!globalScene.showLevelUpStats) { return resolve(); } - const newStats = gScene.getParty()[partyMemberIndex].stats; + const newStats = globalScene.getParty()[partyMemberIndex].stats; let levelUpStatsValuesText = ""; for (const s of PERMANENT_STATS) { levelUpStatsValuesText += `${showTotals ? newStats[s] : newStats[s] - prevStats[s]}\n`; @@ -192,7 +192,7 @@ export default class BattleMessageUiHandler extends MessageUiHandler { promptIvs(pokemonId: integer, ivs: integer[], shownIvsCount: integer): Promise { return new Promise(resolve => { - gScene.executeWithSeedOffset(() => { + globalScene.executeWithSeedOffset(() => { let levelUpStatsValuesText = ""; const shownStats = this.getTopIvs(ivs, shownIvsCount); for (const s of PERMANENT_STATS) { @@ -226,9 +226,9 @@ export default class BattleMessageUiHandler extends MessageUiHandler { } getIvDescriptor(value: integer, typeIv: integer, pokemonId: integer): string { - const starterSpecies = gScene.getPokemonById(pokemonId)!.species.getRootSpeciesId(); // we are using getRootSpeciesId() here because we want to check against the baby form, not the mid form if it exists - const starterIvs: number[] = gScene.gameData.dexData[starterSpecies].ivs; - const uiTheme = gScene.uiTheme; // Assuming uiTheme is accessible + const starterSpecies = globalScene.getPokemonById(pokemonId)!.species.getRootSpeciesId(); // we are using getRootSpeciesId() here because we want to check against the baby form, not the mid form if it exists + const starterIvs: number[] = globalScene.gameData.dexData[starterSpecies].ivs; + const uiTheme = globalScene.uiTheme; // Assuming uiTheme is accessible // Function to wrap text in color based on comparison const coloredText = (text: string, isBetter: boolean, ivValue) => { diff --git a/src/ui/bgm-bar.ts b/src/ui/bgm-bar.ts index 21355ce8759..eeb9c92c165 100644 --- a/src/ui/bgm-bar.ts +++ b/src/ui/bgm-bar.ts @@ -1,7 +1,7 @@ import { addTextObject, TextStyle } from "./text"; import i18next from "i18next"; import * as Utils from "#app/utils"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; const hiddenX = -150; const shownX = 0; @@ -17,14 +17,14 @@ export default class BgmBar extends Phaser.GameObjects.Container { public shown: boolean; constructor() { - super(gScene, hiddenX, baseY); + super(globalScene, hiddenX, baseY); } setup(): void { this.defaultWidth = 230; this.defaultHeight = 100; - this.bg = gScene.add.nineslice(-5, -5, "bgm_bar", undefined, this.defaultWidth, this.defaultHeight, 0, 0, 10, 10); + this.bg = globalScene.add.nineslice(-5, -5, "bgm_bar", undefined, this.defaultWidth, this.defaultHeight, 0, 0, 10, 10); this.bg.setOrigin(0, 0); this.add(this.bg); @@ -52,7 +52,7 @@ export default class BgmBar extends Phaser.GameObjects.Container { this.bg.width = Math.min(this.defaultWidth, this.musicText.displayWidth + 23); this.bg.height = Math.min(this.defaultHeight, this.musicText.displayHeight + 20); - gScene.fieldUI.bringToTop(this); + globalScene.fieldUI.bringToTop(this); this.y = baseY; } @@ -72,11 +72,11 @@ export default class BgmBar extends Phaser.GameObjects.Container { return; } - if (!gScene.showBgmBar) { + if (!globalScene.showBgmBar) { this.setVisible(false); return; } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, x: visible ? shownX : hiddenX, duration: 500, diff --git a/src/ui/candy-bar.ts b/src/ui/candy-bar.ts index 8cef5d631fc..086127a47c6 100644 --- a/src/ui/candy-bar.ts +++ b/src/ui/candy-bar.ts @@ -1,4 +1,4 @@ -import { gScene, starterColors } from "#app/battle-scene"; +import { globalScene, starterColors } from "#app/battle-scene"; import { TextStyle, addTextObject } from "./text"; import { argbFromRgba } from "@material/material-color-utilities"; import * as Utils from "../utils"; @@ -17,22 +17,22 @@ export default class CandyBar extends Phaser.GameObjects.Container { public shown: boolean; constructor() { - super(gScene, (gScene.game.canvas.width / 6), -((gScene.game.canvas.height) / 6) + 15); + super(globalScene, (globalScene.game.canvas.width / 6), -((globalScene.game.canvas.height) / 6) + 15); } setup(): void { - this.bg = gScene.add.nineslice(0, 0, "party_exp_bar", undefined, 8, 18, 21, 5, 6, 4); + this.bg = globalScene.add.nineslice(0, 0, "party_exp_bar", undefined, 8, 18, 21, 5, 6, 4); this.bg.setOrigin(0, 0); this.add(this.bg); - this.candyIcon = gScene.add.sprite(14, 0, "items", "candy"); + this.candyIcon = globalScene.add.sprite(14, 0, "items", "candy"); this.candyIcon.setOrigin(0.5, 0); this.candyIcon.setScale(0.5); this.add(this.candyIcon); - this.candyOverlayIcon = gScene.add.sprite(14, 0, "items", "candy_overlay"); + this.candyOverlayIcon = globalScene.add.sprite(14, 0, "items", "candy_overlay"); this.candyOverlayIcon.setOrigin(0.5, 0); this.candyOverlayIcon.setScale(0.5); @@ -61,21 +61,21 @@ export default class CandyBar extends Phaser.GameObjects.Container { this.candyIcon.setTint(argbFromRgba(Utils.rgbHexToRgba(colorScheme[0]))); this.candyOverlayIcon.setTint(argbFromRgba(Utils.rgbHexToRgba(colorScheme[1]))); - this.countText.setText(`${gScene.gameData.starterData[starterSpeciesId].candyCount + count} (+${count.toString()})`); + this.countText.setText(`${globalScene.gameData.starterData[starterSpeciesId].candyCount + count} (+${count.toString()})`); this.bg.width = this.countText.displayWidth + 28; - gScene.fieldUI.bringToTop(this); + globalScene.fieldUI.bringToTop(this); if (this.tween) { this.tween.stop(); } - gScene.playSound("se/shing"); + globalScene.playSound("se/shing"); - this.tween = gScene.tweens.add({ + this.tween = globalScene.tweens.add({ targets: this, - x: (gScene.game.canvas.width / 6) - (this.bg.width - 5), + x: (globalScene.game.canvas.width / 6) - (this.bg.width - 5), duration: 500, ease: "Sine.easeOut", onComplete: () => { @@ -104,9 +104,9 @@ export default class CandyBar extends Phaser.GameObjects.Container { this.tween.stop(); } - this.tween = gScene.tweens.add({ + this.tween = globalScene.tweens.add({ targets: this, - x: (gScene.game.canvas.width / 6), + x: (globalScene.game.canvas.width / 6), duration: 500, ease: "Sine.easeIn", onComplete: () => { diff --git a/src/ui/challenges-select-ui-handler.ts b/src/ui/challenges-select-ui-handler.ts index 5e9fb335b65..ad0f11794a2 100644 --- a/src/ui/challenges-select-ui-handler.ts +++ b/src/ui/challenges-select-ui-handler.ts @@ -11,7 +11,7 @@ import BBCodeText from "phaser3-rex-plugins/plugins/bbcodetext"; import { Color, ShadowColor } from "#app/enums/color"; import { SelectStarterPhase } from "#app/phases/select-starter-phase"; import { TitlePhase } from "#app/phases/title-phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; /** * Handles all the UI for choosing optional challenges. @@ -54,18 +54,18 @@ export default class GameChallengesUiHandler extends UiHandler { this.widestTextBox = 0; - this.challengesContainer = gScene.add.container(1, -(gScene.game.canvas.height / 6) + 1); + this.challengesContainer = globalScene.add.container(1, -(globalScene.game.canvas.height / 6) + 1); this.challengesContainer.setName("challenges"); - this.challengesContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); + this.challengesContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); - const bgOverlay = gScene.add.rectangle(-1, -1, gScene.scaledCanvas.width, gScene.scaledCanvas.height, 0x424242, 0.8); + const bgOverlay = globalScene.add.rectangle(-1, -1, globalScene.scaledCanvas.width, globalScene.scaledCanvas.height, 0x424242, 0.8); bgOverlay.setName("rect-challenge-overlay"); bgOverlay.setOrigin(0, 0); this.challengesContainer.add(bgOverlay); // TODO: Change this back to /9 when adding in difficulty - const headerBg = addWindow(0, 0, (gScene.game.canvas.width / 6), 24); + const headerBg = addWindow(0, 0, (globalScene.game.canvas.width / 6), 24); headerBg.setName("window-header-bg"); headerBg.setOrigin(0, 0); @@ -74,29 +74,17 @@ export default class GameChallengesUiHandler extends UiHandler { headerText.setOrigin(0, 0); headerText.setPositionRelative(headerBg, 8, 4); - // const difficultyBg = addWindow(0, 0, (gScene.game.canvas.width / 18) - 2, 24); - // difficultyBg.setOrigin(0, 0); - // difficultyBg.setPositionRelative(headerBg, headerBg.width, 0); - - // this.difficultyText = addTextObject(0, 0, "0", TextStyle.SETTINGS_LABEL); - // this.difficultyText.setOrigin(0, 0); - // this.difficultyText.setPositionRelative(difficultyBg, 8, 4); - - // const difficultyName = addTextObject(0, 0, i18next.t("challenges:points"), TextStyle.SETTINGS_LABEL); - // difficultyName.setOrigin(0, 0); - // difficultyName.setPositionRelative(difficultyBg, difficultyBg.width - difficultyName.displayWidth - 8, 4); - - this.optionsWidth = gScene.scaledCanvas.width * 0.6; - this.optionsBg = addWindow(0, headerBg.height, this.optionsWidth, gScene.scaledCanvas.height - headerBg.height - 2); + this.optionsWidth = globalScene.scaledCanvas.width * 0.6; + this.optionsBg = addWindow(0, headerBg.height, this.optionsWidth, globalScene.scaledCanvas.height - headerBg.height - 2); this.optionsBg.setName("window-options-bg"); this.optionsBg.setOrigin(0, 0); - const descriptionBg = addWindow(0, headerBg.height, gScene.scaledCanvas.width - this.optionsWidth, gScene.scaledCanvas.height - headerBg.height - 26); + const descriptionBg = addWindow(0, headerBg.height, globalScene.scaledCanvas.width - this.optionsWidth, globalScene.scaledCanvas.height - headerBg.height - 26); descriptionBg.setName("window-desc-bg"); descriptionBg.setOrigin(0, 0); descriptionBg.setPositionRelative(this.optionsBg, this.optionsBg.width, 0); - this.descriptionText = new BBCodeText(gScene, descriptionBg.x + 6, descriptionBg.y + 4, "", { + this.descriptionText = new BBCodeText(globalScene, descriptionBg.x + 6, descriptionBg.y + 4, "", { fontFamily: "emerald", fontSize: 84, color: Color.ORANGE, @@ -109,7 +97,7 @@ export default class GameChallengesUiHandler extends UiHandler { } }); this.descriptionText.setName("text-desc"); - gScene.add.existing(this.descriptionText); + globalScene.add.existing(this.descriptionText); this.descriptionText.setScale(1 / 6); this.descriptionText.setShadow(4, 5, ShadowColor.ORANGE); this.descriptionText.setOrigin(0, 0); @@ -124,13 +112,13 @@ export default class GameChallengesUiHandler extends UiHandler { this.startText.setOrigin(0, 0); this.startText.setPositionRelative(this.startBg, (this.startBg.width - this.startText.displayWidth) / 2, 4); - this.startCursor = gScene.add.nineslice(0, 0, "summary_moves_cursor", undefined, descriptionBg.width - 8, 16, 1, 1, 1, 1); + this.startCursor = globalScene.add.nineslice(0, 0, "summary_moves_cursor", undefined, descriptionBg.width - 8, 16, 1, 1, 1, 1); this.startCursor.setName("9s-start-cursor"); this.startCursor.setOrigin(0, 0); this.startCursor.setPositionRelative(this.startBg, 4, 3); this.startCursor.setVisible(false); - this.valuesContainer = gScene.add.container(0, 0); + this.valuesContainer = globalScene.add.container(0, 0); this.valuesContainer.setName("values"); this.challengeLabels = []; @@ -142,14 +130,14 @@ export default class GameChallengesUiHandler extends UiHandler { this.valuesContainer.add(label); - const leftArrow = gScene.add.image(0, 0, "cursor_reverse"); + const leftArrow = globalScene.add.image(0, 0, "cursor_reverse"); leftArrow.setName(`challenge-left-arrow-${i}`); leftArrow.setOrigin(0, 0); leftArrow.setVisible(false); leftArrow.setScale(0.75); this.valuesContainer.add(leftArrow); - const rightArrow = gScene.add.image(0, 0, "cursor"); + const rightArrow = globalScene.add.image(0, 0, "cursor"); rightArrow.setName(`challenge-right-arrow-${i}`); rightArrow.setOrigin(0, 0); rightArrow.setScale(0.75); @@ -169,7 +157,7 @@ export default class GameChallengesUiHandler extends UiHandler { }; } - this.monoTypeValue = gScene.add.sprite(8, 98, Utils.getLocalizedSpriteKey("types")); + this.monoTypeValue = globalScene.add.sprite(8, 98, Utils.getLocalizedSpriteKey("types")); this.monoTypeValue.setName("challenge-value-monotype-sprite"); this.monoTypeValue.setScale(0.86); this.monoTypeValue.setVisible(false); @@ -209,10 +197,10 @@ export default class GameChallengesUiHandler extends UiHandler { * init all challenge labels */ initLabels(): void { - this.setDescription(gScene.gameMode.challenges[0].getDescription()); + this.setDescription(globalScene.gameMode.challenges[0].getDescription()); this.widestTextBox = 0; for (let i = 0; i < 9; i++) { - if (i < gScene.gameMode.challenges.length) { + if (i < globalScene.gameMode.challenges.length) { this.challengeLabels[i].label.setVisible(true); this.challengeLabels[i].value.setVisible(true); this.challengeLabels[i].leftArrow.setVisible(true); @@ -220,9 +208,9 @@ export default class GameChallengesUiHandler extends UiHandler { const tempText = addTextObject(0, 0, "", TextStyle.SETTINGS_LABEL); // this is added here to get the widest text object for this language, which will be used for the arrow placement - for (let j = 0; j <= gScene.gameMode.challenges[i].maxValue; j++) { // this goes through each challenge's value to find out what the max width will be - if (gScene.gameMode.challenges[i].id !== Challenges.SINGLE_TYPE) { - tempText.setText(gScene.gameMode.challenges[i].getValue(j)); + for (let j = 0; j <= globalScene.gameMode.challenges[i].maxValue; j++) { // this goes through each challenge's value to find out what the max width will be + if (globalScene.gameMode.challenges[i].id !== Challenges.SINGLE_TYPE) { + tempText.setText(globalScene.gameMode.challenges[i].getValue(j)); if (tempText.displayWidth > this.widestTextBox) { this.widestTextBox = tempText.displayWidth; } @@ -240,8 +228,8 @@ export default class GameChallengesUiHandler extends UiHandler { updateText(): void { this.setDescription(this.getActiveChallenge().getDescription()); let monoTypeVisible = false; - for (let i = 0; i < Math.min(9, gScene.gameMode.challenges.length); i++) { - const challenge = gScene.gameMode.challenges[this.scrollCursor + i]; + for (let i = 0; i < Math.min(9, globalScene.gameMode.challenges.length); i++) { + const challenge = globalScene.gameMode.challenges[this.scrollCursor + i]; const challengeLabel = this.challengeLabels[i]; challengeLabel.label.setText(challenge.getName()); challengeLabel.leftArrow.setPositionRelative(challengeLabel.label, this.leftArrowGap, 4.5); @@ -276,7 +264,7 @@ export default class GameChallengesUiHandler extends UiHandler { } // This checks if a challenge has been selected by the user and updates the text/its opacity accordingly. - this.hasSelectedChallenge = gScene.gameMode.challenges.some(c => c.value !== 0); + this.hasSelectedChallenge = globalScene.gameMode.challenges.some(c => c.value !== 0); if (this.hasSelectedChallenge) { this.startText.setText(i18next.t("common:start")); @@ -289,11 +277,6 @@ export default class GameChallengesUiHandler extends UiHandler { this.startText.setPositionRelative(this.startBg, (this.startBg.width - this.startText.displayWidth) / 2, 4); } this.challengesContainer.update(); - - // const totalDifficulty = gScene.gameMode.challenges.reduce((v, c) => v + c.getDifficulty(), 0); - // const totalMinDifficulty = gScene.gameMode.challenges.reduce((v, c) => v + c.getMinDifficulty(), 0); - // this.difficultyText.text = `${totalDifficulty}` + (totalMinDifficulty ? `/${totalMinDifficulty}` : ""); - // this.difficultyText.updateText(); } show(args: any[]): boolean { @@ -303,7 +286,7 @@ export default class GameChallengesUiHandler extends UiHandler { this.updateChallengeArrows(false); this.challengesContainer.setVisible(true); // Should always be false at the start - this.hasSelectedChallenge = gScene.gameMode.challenges.some(c => c.value !== 0); + this.hasSelectedChallenge = globalScene.gameMode.challenges.some(c => c.value !== 0); this.setCursor(0); this.initLabels(); @@ -319,7 +302,7 @@ export default class GameChallengesUiHandler extends UiHandler { /* This code updates the challenge starter arrows to be tinted/not tinted when the start button is selected to show they can't be changed */ updateChallengeArrows(tinted: boolean) { - for (let i = 0; i < Math.min(9, gScene.gameMode.challenges.length); i++) { + for (let i = 0; i < Math.min(9, globalScene.gameMode.challenges.length); i++) { const challengeLabel = this.challengeLabels[i]; if (tinted) { challengeLabel.leftArrow.setTint(0x808080); @@ -354,16 +337,16 @@ export default class GameChallengesUiHandler extends UiHandler { this.cursorObj?.setVisible(true); this.updateChallengeArrows(this.startCursor.visible); } else { - gScene.clearPhaseQueue(); - gScene.pushPhase(new TitlePhase()); - gScene.getCurrentPhase()?.end(); + globalScene.clearPhaseQueue(); + globalScene.pushPhase(new TitlePhase()); + globalScene.getCurrentPhase()?.end(); } success = true; } else if (button === Button.SUBMIT || button === Button.ACTION) { if (this.hasSelectedChallenge) { if (this.startCursor.visible) { - gScene.unshiftPhase(new SelectStarterPhase()); - gScene.getCurrentPhase()?.end(); + globalScene.unshiftPhase(new SelectStarterPhase()); + globalScene.getCurrentPhase()?.end(); } else { this.startCursor.setVisible(true); this.cursorObj?.setVisible(false); @@ -380,14 +363,14 @@ export default class GameChallengesUiHandler extends UiHandler { if (this.cursor === 0) { if (this.scrollCursor === 0) { // When at the top of the menu and pressing UP, move to the bottommost item. - if (gScene.gameMode.challenges.length > rowsToDisplay) { // If there are more than 9 challenges, scroll to the bottom + if (globalScene.gameMode.challenges.length > rowsToDisplay) { // If there are more than 9 challenges, scroll to the bottom // First, set the cursor to the last visible element, preparing for the scroll to the end. const successA = this.setCursor(rowsToDisplay - 1); // Then, adjust the scroll to display the bottommost elements of the menu. - const successB = this.setScrollCursor(gScene.gameMode.challenges.length - rowsToDisplay); + const successB = this.setScrollCursor(globalScene.gameMode.challenges.length - rowsToDisplay); success = successA && successB; // success is just there to play the little validation sound effect } else { // If there are 9 or less challenges, just move to the bottom one - success = this.setCursor(gScene.gameMode.challenges.length - 1); + success = this.setCursor(globalScene.gameMode.challenges.length - 1); } } else { success = this.setScrollCursor(this.scrollCursor - 1); @@ -401,7 +384,7 @@ export default class GameChallengesUiHandler extends UiHandler { break; case Button.DOWN: if (this.cursor === rowsToDisplay - 1) { - if (this.scrollCursor < gScene.gameMode.challenges.length - rowsToDisplay) { + if (this.scrollCursor < globalScene.gameMode.challenges.length - rowsToDisplay) { // When at the bottom and pressing DOWN, scroll if possible. success = this.setScrollCursor(this.scrollCursor + 1); } else { @@ -412,7 +395,7 @@ export default class GameChallengesUiHandler extends UiHandler { const successB = this.setScrollCursor(0); success = successA && successB; // success is just there to play the little validation sound effect } - } else if (gScene.gameMode.challenges.length < rowsToDisplay && this.cursor === gScene.gameMode.challenges.length - 1) { + } else if (globalScene.gameMode.challenges.length < rowsToDisplay && this.cursor === globalScene.gameMode.challenges.length - 1) { // When at the bottom of a non-scrolling menu and pressing DOWN, move to the topmost item. success = this.setCursor(0); } else { @@ -451,7 +434,7 @@ export default class GameChallengesUiHandler extends UiHandler { let ret = super.setCursor(cursor); if (!this.cursorObj) { - this.cursorObj = gScene.add.nineslice(0, 0, "summary_moves_cursor", undefined, this.optionsWidth - 8, 16, 1, 1, 1, 1); + this.cursorObj = globalScene.add.nineslice(0, 0, "summary_moves_cursor", undefined, this.optionsWidth - 8, 16, 1, 1, 1, 1); this.cursorObj.setOrigin(0, 0); this.valuesContainer.add(this.cursorObj); } @@ -477,7 +460,7 @@ export default class GameChallengesUiHandler extends UiHandler { } getActiveChallenge(): Challenge { - return gScene.gameMode.challenges[this.cursor + this.scrollCursor]; + return globalScene.gameMode.challenges[this.cursor + this.scrollCursor]; } clear() { diff --git a/src/ui/char-sprite.ts b/src/ui/char-sprite.ts index 1291777cc7e..02fc933b16b 100644 --- a/src/ui/char-sprite.ts +++ b/src/ui/char-sprite.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import * as Utils from "../utils"; export default class CharSprite extends Phaser.GameObjects.Container { @@ -10,12 +10,12 @@ export default class CharSprite extends Phaser.GameObjects.Container { public shown: boolean; constructor() { - super(gScene, (gScene.game.canvas.width / 6) + 32, -42); + super(globalScene, (globalScene.game.canvas.width / 6) + 32, -42); } setup(): void { [ this.sprite, this.transitionSprite ] = new Array(2).fill(null).map(() => { - const ret = gScene.add.sprite(0, 0, "", ""); + const ret = globalScene.add.sprite(0, 0, "", ""); ret.setOrigin(0.5, 1); this.add(ret); return ret; @@ -45,11 +45,11 @@ export default class CharSprite extends Phaser.GameObjects.Container { this.sprite.setTexture(key, variant); - gScene.fieldUI.bringToTop(this); + globalScene.fieldUI.bringToTop(this); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, - x: (gScene.game.canvas.width / 6) - 102, + x: (globalScene.game.canvas.width / 6) - 102, duration: 750, ease: "Cubic.easeOut", onComplete: () => { @@ -57,7 +57,7 @@ export default class CharSprite extends Phaser.GameObjects.Container { } }); - this.setVisible(gScene.textures.get(key).key !== Utils.MissingTextureKey); + this.setVisible(globalScene.textures.get(key).key !== Utils.MissingTextureKey); this.shown = true; this.key = key; @@ -67,12 +67,12 @@ export default class CharSprite extends Phaser.GameObjects.Container { setVariant(variant: string): Promise { return new Promise(resolve => { - gScene.fieldUI.bringToTop(this); + globalScene.fieldUI.bringToTop(this); this.transitionSprite.setTexture(this.key, variant); this.transitionSprite.setAlpha(0); this.transitionSprite.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.transitionSprite, alpha: 1, duration: 250, @@ -93,9 +93,9 @@ export default class CharSprite extends Phaser.GameObjects.Container { return resolve(); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, - x: (gScene.game.canvas.width / 6) + 32, + x: (globalScene.game.canvas.width / 6) + 32, duration: 750, ease: "Cubic.easeIn", onComplete: () => { diff --git a/src/ui/command-ui-handler.ts b/src/ui/command-ui-handler.ts index 9059159bfe4..fdbfa7cb13b 100644 --- a/src/ui/command-ui-handler.ts +++ b/src/ui/command-ui-handler.ts @@ -6,7 +6,7 @@ import i18next from "i18next"; import { Button } from "#enums/buttons"; import { getPokemonNameWithAffix } from "#app/messages"; import { CommandPhase } from "#app/phases/command-phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export enum Command { FIGHT = 0, @@ -35,7 +35,7 @@ export default class CommandUiHandler extends UiHandler { i18next.t("commandUiHandler:run") ]; - this.commandsContainer = gScene.add.container(217, -38.7); + this.commandsContainer = globalScene.add.container(217, -38.7); this.commandsContainer.setName("commands"); this.commandsContainer.setVisible(false); ui.add(this.commandsContainer); @@ -55,11 +55,11 @@ export default class CommandUiHandler extends UiHandler { this.commandsContainer.setVisible(true); let commandPhase: CommandPhase; - const currentPhase = gScene.getCurrentPhase(); + const currentPhase = globalScene.getCurrentPhase(); if (currentPhase instanceof CommandPhase) { commandPhase = currentPhase; } else { - commandPhase = gScene.getStandbyPhase() as CommandPhase; + commandPhase = globalScene.getStandbyPhase() as CommandPhase; } const messageHandler = this.getUi().getMessageHandler(); @@ -90,10 +90,10 @@ export default class CommandUiHandler extends UiHandler { switch (cursor) { // Fight case Command.FIGHT: - if ((gScene.getCurrentPhase() as CommandPhase).checkFightOverride()) { + if ((globalScene.getCurrentPhase() as CommandPhase).checkFightOverride()) { return true; } - ui.setMode(Mode.FIGHT, (gScene.getCurrentPhase() as CommandPhase).getFieldIndex()); + ui.setMode(Mode.FIGHT, (globalScene.getCurrentPhase() as CommandPhase).getFieldIndex()); success = true; break; // Ball @@ -103,17 +103,17 @@ export default class CommandUiHandler extends UiHandler { break; // Pokemon case Command.POKEMON: - ui.setMode(Mode.PARTY, PartyUiMode.SWITCH, (gScene.getCurrentPhase() as CommandPhase).getPokemon().getFieldIndex(), null, PartyUiHandler.FilterNonFainted); + ui.setMode(Mode.PARTY, PartyUiMode.SWITCH, (globalScene.getCurrentPhase() as CommandPhase).getPokemon().getFieldIndex(), null, PartyUiHandler.FilterNonFainted); success = true; break; // Run case Command.RUN: - (gScene.getCurrentPhase() as CommandPhase).handleCommand(Command.RUN, 0); + (globalScene.getCurrentPhase() as CommandPhase).handleCommand(Command.RUN, 0); success = true; break; } } else { - (gScene.getCurrentPhase() as CommandPhase).cancel(); + (globalScene.getCurrentPhase() as CommandPhase).cancel(); } } else { switch (button) { @@ -162,7 +162,7 @@ export default class CommandUiHandler extends UiHandler { } if (!this.cursorObj) { - this.cursorObj = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.image(0, 0, "cursor"); this.commandsContainer.add(this.cursorObj); } diff --git a/src/ui/confirm-ui-handler.ts b/src/ui/confirm-ui-handler.ts index d8e2dc87adf..2f5b9d09846 100644 --- a/src/ui/confirm-ui-handler.ts +++ b/src/ui/confirm-ui-handler.ts @@ -2,7 +2,7 @@ import AbstractOptionSelectUiHandler, { OptionSelectConfig } from "./abstact-opt import { Mode } from "./ui"; import i18next from "i18next"; import { Button } from "#enums/buttons"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class ConfirmUiHandler extends AbstractOptionSelectUiHandler { @@ -54,7 +54,7 @@ export default class ConfirmUiHandler extends AbstractOptionSelectUiHandler { const xOffset = (args.length >= 6 && args[5] !== null ? args[5] as number : 0); const yOffset = (args.length >= 7 && args[6] !== null ? args[6] as number : 0); - this.optionSelectContainer.setPosition((gScene.game.canvas.width / 6) - 1 + xOffset, -48 + yOffset); + this.optionSelectContainer.setPosition((globalScene.game.canvas.width / 6) - 1 + xOffset, -48 + yOffset); this.setCursor(this.switchCheck ? this.switchCheckCursor : 0); return true; @@ -87,7 +87,7 @@ export default class ConfirmUiHandler extends AbstractOptionSelectUiHandler { const xOffset = (args.length >= 4 && args[3] !== null ? args[3] as number : 0); const yOffset = (args.length >= 5 && args[4] !== null ? args[4] as number : 0); - this.optionSelectContainer.setPosition((gScene.game.canvas.width / 6) - 1 + xOffset, -48 + yOffset); + this.optionSelectContainer.setPosition((globalScene.game.canvas.width / 6) - 1 + xOffset, -48 + yOffset); this.setCursor(this.switchCheck ? this.switchCheckCursor : 0); diff --git a/src/ui/daily-run-scoreboard.ts b/src/ui/daily-run-scoreboard.ts index edce73b666a..32a0a863956 100644 --- a/src/ui/daily-run-scoreboard.ts +++ b/src/ui/daily-run-scoreboard.ts @@ -1,5 +1,5 @@ import i18next from "i18next"; -import BattleScene, { gScene } from "#app/battle-scene"; +import BattleScene, { globalScene } from "#app/battle-scene"; import * as Utils from "../utils"; import { TextStyle, addTextObject } from "./text"; import { WindowVariant, addWindow } from "./ui-theme"; @@ -34,7 +34,7 @@ export class DailyRunScoreboard extends Phaser.GameObjects.Container { private _isUpdating: boolean; constructor(x: number, y: number) { - super(gScene, x, y); + super(globalScene, x, y); this._isUpdating = false; this.setup(); @@ -69,14 +69,14 @@ export class DailyRunScoreboard extends Phaser.GameObjects.Container { const window = addWindow(0, 17, 114, 118, false, false, undefined, undefined, WindowVariant.THIN); this.add(window); - this.rankingsContainer = gScene.add.container(6, 21); + this.rankingsContainer = globalScene.add.container(6, 21); this.add(this.rankingsContainer); this.loadingLabel = addTextObject(window.displayWidth / 2, window.displayHeight / 2 + 16, "", TextStyle.WINDOW); this.loadingLabel.setOrigin(0.5, 0.5); this.loadingLabel.setVisible(false); - this.prevCategoryButton = gScene.add.sprite(4, 4, "cursor_reverse"); + this.prevCategoryButton = globalScene.add.sprite(4, 4, "cursor_reverse"); this.prevCategoryButton.setOrigin(0, 0); this.add(this.prevCategoryButton); @@ -85,7 +85,7 @@ export class DailyRunScoreboard extends Phaser.GameObjects.Container { this.update(this.category ? this.category - 1 : Utils.getEnumKeys(ScoreboardCategory).length - 1); }); - this.nextCategoryButton = gScene.add.sprite(window.displayWidth - 4, 4, "cursor"); + this.nextCategoryButton = globalScene.add.sprite(window.displayWidth - 4, 4, "cursor"); this.nextCategoryButton.setOrigin(1, 0); this.add(this.nextCategoryButton); @@ -94,7 +94,7 @@ export class DailyRunScoreboard extends Phaser.GameObjects.Container { this.update(this.category < Utils.getEnumKeys(ScoreboardCategory).length - 1 ? this.category + 1 : 0); }); - this.prevPageButton = gScene.add.sprite(window.displayWidth / 2 - 16, titleWindow.displayHeight + window.displayHeight - 15, "cursor_reverse"); + this.prevPageButton = globalScene.add.sprite(window.displayWidth / 2 - 16, titleWindow.displayHeight + window.displayHeight - 15, "cursor_reverse"); this.prevPageButton.setOrigin(0, 0); this.prevPageButton.setAlpha(0.5); this.add(this.prevPageButton); @@ -110,7 +110,7 @@ export class DailyRunScoreboard extends Phaser.GameObjects.Container { this.pageNumberLabel.setOrigin(0.5, 0); this.add(this.pageNumberLabel); - this.nextPageButton = gScene.add.sprite(window.displayWidth / 2 + 16, titleWindow.displayHeight + window.displayHeight - 15, "cursor"); + this.nextPageButton = globalScene.add.sprite(window.displayWidth / 2 + 16, titleWindow.displayHeight + window.displayHeight - 15, "cursor"); this.nextPageButton.setOrigin(1, 0); this.nextPageButton.setAlpha(0.5); this.add(this.nextPageButton); @@ -130,7 +130,7 @@ export class DailyRunScoreboard extends Phaser.GameObjects.Container { updateRankings(rankings: RankingEntry[]) { const getEntry = (rank: string, username: string, score: string, wave: string) => { - const entryContainer = gScene.add.container(0, 0); + const entryContainer = globalScene.add.container(0, 0); const rankLabel = addTextObject(0, 0, rank, TextStyle.WINDOW, { fontSize: "54px" }); entryContainer.add(rankLabel); diff --git a/src/ui/dropdown.ts b/src/ui/dropdown.ts index ab7d3a80e2f..4912f1002f3 100644 --- a/src/ui/dropdown.ts +++ b/src/ui/dropdown.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { addTextObject, TextStyle } from "./text"; import { addWindow, WindowVariant } from "./ui-theme"; import i18next from "i18next"; @@ -57,7 +57,7 @@ export class DropDownOption extends Phaser.GameObjects.Container { private unlockableColor = 0xffff00; constructor(val: any, labels: DropDownLabel | DropDownLabel[]) { - super(gScene); + super(globalScene); this.val = val; if (Array.isArray(labels)) { @@ -95,12 +95,12 @@ export class DropDownOption extends Phaser.GameObjects.Container { */ setupToggleIcon(type: DropDownType, visible: boolean): void { if (type === DropDownType.SINGLE) { - this.toggle = gScene.add.sprite(0, 0, "cursor"); + this.toggle = globalScene.add.sprite(0, 0, "cursor"); this.toggle.setScale(0.5); this.toggle.setOrigin(0, 0.5); this.toggle.setRotation(Math.PI / 180 * -90); } else { - this.toggle = gScene.add.sprite(0, 0, "candy"); + this.toggle = globalScene.add.sprite(0, 0, "candy"); this.toggle.setScale(0.3); this.toggle.setOrigin(0, 0.5); } @@ -290,12 +290,12 @@ export class DropDown extends Phaser.GameObjects.Container { const cursorOffset = 7; const optionWidth = 100; - super(gScene, x - cursorOffset - windowPadding, y); + super(globalScene, x - cursorOffset - windowPadding, y); this.options = options; this.dropDownType = type; this.onChange = onChange; - this.cursorObj = gScene.add.image(optionPaddingX + 3, 0, "cursor"); + this.cursorObj = globalScene.add.image(optionPaddingX + 3, 0, "cursor"); this.cursorObj.setScale(0.5); this.cursorObj.setOrigin(0, 0.5); this.cursorObj.setVisible(false); diff --git a/src/ui/egg-counter-container.ts b/src/ui/egg-counter-container.ts index 33d65870d3a..e5efc198194 100644 --- a/src/ui/egg-counter-container.ts +++ b/src/ui/egg-counter-container.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { addWindow } from "./ui-theme"; import { addTextObject, TextStyle } from "./text"; import { EggCountChangedEvent, EggEventType } from "#app/events/egg"; @@ -22,10 +22,10 @@ export default class EggCounterContainer extends Phaser.GameObjects.Container { * @param eggCount - The number of eggs to hatch. */ constructor(eggCount: number) { - super(gScene, 0, 0); + super(globalScene, 0, 0); this.eggCount = eggCount; - const uiHandler = gScene.ui.getHandler() as EggHatchSceneHandler; + const uiHandler = globalScene.ui.getHandler() as EggHatchSceneHandler; uiHandler.eventTarget.addEventListener(EggEventType.EGG_COUNT_CHANGED, this.onEggCountChangedEvent); this.setup(); @@ -42,7 +42,7 @@ export default class EggCounterContainer extends Phaser.GameObjects.Container { this.add(this.eggCountWindow); - const eggSprite = gScene.add.sprite(19, 18, "egg", "egg_0"); + const eggSprite = globalScene.add.sprite(19, 18, "egg", "egg_0"); eggSprite.setScale(0.32); this.eggCountText = addTextObject(28, 13, `${this.eggCount}`, TextStyle.MESSAGE, { fontSize: "66px" }); diff --git a/src/ui/egg-gacha-ui-handler.ts b/src/ui/egg-gacha-ui-handler.ts index fd8f5793249..7e88f795b73 100644 --- a/src/ui/egg-gacha-ui-handler.ts +++ b/src/ui/egg-gacha-ui-handler.ts @@ -12,7 +12,7 @@ import Overrides from "#app/overrides"; import { GachaType } from "#app/enums/gacha-types"; import i18next from "i18next"; import { EggTier } from "#enums/egg-type"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class EggGachaUiHandler extends MessageUiHandler { private eggGachaContainer: Phaser.GameObjects.Container; @@ -53,29 +53,29 @@ export default class EggGachaUiHandler extends MessageUiHandler { setup() { this.gachaCursor = 0; - this.scale = getTextStyleOptions(TextStyle.WINDOW, gScene.uiTheme).scale; + this.scale = getTextStyleOptions(TextStyle.WINDOW, globalScene.uiTheme).scale; const ui = this.getUi(); - this.eggGachaContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); + this.eggGachaContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); this.eggGachaContainer.setVisible(false); ui.add(this.eggGachaContainer); - const bg = gScene.add.nineslice(0, 0, "default_bg", undefined, 320, 180, 0, 0, 16, 0); + const bg = globalScene.add.nineslice(0, 0, "default_bg", undefined, 320, 180, 0, 0, 16, 0); bg.setOrigin(0, 0); this.eggGachaContainer.add(bg); - const hatchFrameNames = gScene.anims.generateFrameNames("gacha_hatch", { suffix: ".png", start: 1, end: 4 }); - if (!(gScene.anims.exists("open"))) { - gScene.anims.create({ + const hatchFrameNames = globalScene.anims.generateFrameNames("gacha_hatch", { suffix: ".png", start: 1, end: 4 }); + if (!(globalScene.anims.exists("open"))) { + globalScene.anims.create({ key: "open", frames: hatchFrameNames, frameRate: 12 }); } - if (!(gScene.anims.exists("close"))) { - gScene.anims.create({ + if (!(globalScene.anims.exists("close"))) { + globalScene.anims.create({ key: "close", frames: hatchFrameNames.reverse(), frameRate: 12 @@ -84,21 +84,21 @@ export default class EggGachaUiHandler extends MessageUiHandler { Utils.getEnumValues(GachaType).forEach((gachaType, g) => { const gachaTypeKey = GachaType[gachaType].toString().toLowerCase(); - const gachaContainer = gScene.add.container(180 * g, 18); + const gachaContainer = globalScene.add.container(180 * g, 18); - const gacha = gScene.add.sprite(0, 0, `gacha_${gachaTypeKey}`); + const gacha = globalScene.add.sprite(0, 0, `gacha_${gachaTypeKey}`); gacha.setOrigin(0, 0); - const gachaUnderlay = gScene.add.sprite(115, 80, `gacha_underlay_${gachaTypeKey}`); + const gachaUnderlay = globalScene.add.sprite(115, 80, `gacha_underlay_${gachaTypeKey}`); gachaUnderlay.setOrigin(0, 0); - const gachaEggs = gScene.add.sprite(0, 0, "gacha_eggs"); + const gachaEggs = globalScene.add.sprite(0, 0, "gacha_eggs"); gachaEggs.setOrigin(0, 0); - const gachaGlass = gScene.add.sprite(0, 0, "gacha_glass"); + const gachaGlass = globalScene.add.sprite(0, 0, "gacha_glass"); gachaGlass.setOrigin(0, 0); - const gachaInfoContainer = gScene.add.container(160, 46); + const gachaInfoContainer = globalScene.add.container(160, 46); const currentLanguage = i18next.resolvedLanguage ?? "en"; let gachaTextStyle = TextStyle.WINDOW_ALT; @@ -139,7 +139,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { } gachaUpLabel.setY(legendaryLabelY); - const pokemonIcon = gScene.add.sprite(pokemonIconX, pokemonIconY, "pokemon_icons_0"); + const pokemonIcon = globalScene.add.sprite(pokemonIconX, pokemonIconY, "pokemon_icons_0"); if ([ "pt-BR" ].includes(currentLanguage)) { pokemonIcon.setX(pokemonIconX - 2); } @@ -170,9 +170,9 @@ export default class EggGachaUiHandler extends MessageUiHandler { break; } - const gachaKnob = gScene.add.sprite(191, 89, "gacha_knob"); + const gachaKnob = globalScene.add.sprite(191, 89, "gacha_knob"); - const gachaHatch = gScene.add.sprite(115, 73, "gacha_hatch"); + const gachaHatch = globalScene.add.sprite(115, 73, "gacha_hatch"); gachaHatch.setOrigin(0, 0); gachaContainer.add(gachaEggs); @@ -198,9 +198,9 @@ export default class EggGachaUiHandler extends MessageUiHandler { this.updateGachaInfo(g); }); - this.eggGachaOptionsContainer = gScene.add.container(); + this.eggGachaOptionsContainer = globalScene.add.container(); - this.eggGachaOptionsContainer = gScene.add.container((gScene.game.canvas.width / 6), 148); + this.eggGachaOptionsContainer = globalScene.add.container((globalScene.game.canvas.width / 6), 148); this.eggGachaContainer.add(this.eggGachaOptionsContainer); @@ -245,7 +245,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { optionText.setPositionRelative(this.eggGachaOptionSelectBg, 16, 9); pullOptions.forEach((option, i) => { - const icon = gScene.add.sprite(0, 0, "items", option.icon); + const icon = globalScene.add.sprite(0, 0, "items", option.icon); icon.setScale(3 * this.scale); icon.setPositionRelative(this.eggGachaOptionSelectBg, 20, 9 + (48 + i * 96) * this.scale); this.eggGachaOptionsContainer.add(icon); @@ -254,7 +254,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { this.eggGachaContainer.add(this.eggGachaOptionsContainer); new Array(Utils.getEnumKeys(VoucherType).length).fill(null).map((_, i) => { - const container = gScene.add.container((gScene.game.canvas.width / 6) - 56 * i, 0); + const container = globalScene.add.container((globalScene.game.canvas.width / 6) - 56 * i, 0); const bg = addWindow(0, 0, 56, 22); bg.setOrigin(1, 0); @@ -268,7 +268,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { const iconImage = getVoucherTypeIcon(i as VoucherType); - const icon = gScene.add.sprite(-19, 2, "items", iconImage); + const icon = globalScene.add.sprite(-19, 2, "items", iconImage); icon.setOrigin(0, 0); icon.setScale(0.5); container.add(icon); @@ -276,17 +276,17 @@ export default class EggGachaUiHandler extends MessageUiHandler { this.eggGachaContainer.add(container); }); - this.eggGachaOverlay = gScene.add.rectangle(0, 0, bg.displayWidth, bg.displayHeight, 0x000000); + this.eggGachaOverlay = globalScene.add.rectangle(0, 0, bg.displayWidth, bg.displayHeight, 0x000000); this.eggGachaOverlay.setOrigin(0, 0); this.eggGachaOverlay.setAlpha(0); this.eggGachaContainer.add(this.eggGachaOverlay); - this.eggGachaSummaryContainer = gScene.add.container(0, 0); + this.eggGachaSummaryContainer = globalScene.add.container(0, 0); this.eggGachaSummaryContainer.setVisible(false); this.eggGachaContainer.add(this.eggGachaSummaryContainer); - const gachaMessageBoxContainer = gScene.add.container(0, 148); + const gachaMessageBoxContainer = globalScene.add.container(0, 148); const gachaMessageBox = addWindow(0, 0, 320, 32); gachaMessageBox.setOrigin(0, 0); @@ -350,41 +350,41 @@ export default class EggGachaUiHandler extends MessageUiHandler { return this.showSummary(eggs!); } - const egg = gScene.add.sprite(127, 75, "egg", `egg_${eggs![count].getKey()}`); + const egg = globalScene.add.sprite(127, 75, "egg", `egg_${eggs![count].getKey()}`); egg.setScale(0.5); this.gachaContainers[this.gachaCursor].add(egg); this.gachaContainers[this.gachaCursor].moveTo(egg, 2); const doPullAnim = () => { - gScene.playSound("se/gacha_running", { loop: true }); - gScene.time.delayedCall(this.getDelayValue(count ? 500 : 1250), () => { - gScene.playSound("se/gacha_dispense"); - gScene.time.delayedCall(this.getDelayValue(750), () => { - gScene.sound.stopByKey("se/gacha_running"); - gScene.tweens.add({ + globalScene.playSound("se/gacha_running", { loop: true }); + globalScene.time.delayedCall(this.getDelayValue(count ? 500 : 1250), () => { + globalScene.playSound("se/gacha_dispense"); + globalScene.time.delayedCall(this.getDelayValue(750), () => { + globalScene.sound.stopByKey("se/gacha_running"); + globalScene.tweens.add({ targets: egg, duration: this.getDelayValue(350), y: 95, ease: "Bounce.easeOut", onComplete: () => { - gScene.time.delayedCall(this.getDelayValue(125), () => { - gScene.playSound("se/pb_catch"); + globalScene.time.delayedCall(this.getDelayValue(125), () => { + globalScene.playSound("se/pb_catch"); this.gachaHatches[this.gachaCursor].play("open"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: egg, duration: this.getDelayValue(350), scale: 0.75, ease: "Sine.easeIn" }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: egg, y: 110, duration: this.getDelayValue(350), ease: "Back.easeOut", onComplete: () => { this.gachaHatches[this.gachaCursor].play("close"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: egg, y: 200, duration: this.getDelayValue(350), @@ -407,20 +407,20 @@ export default class EggGachaUiHandler extends MessageUiHandler { }; if (!count) { - gScene.playSound("se/gacha_dial"); - gScene.tweens.add({ + globalScene.playSound("se/gacha_dial"); + globalScene.tweens.add({ targets: this.gachaKnobs[this.gachaCursor], duration: this.getDelayValue(350), angle: 90, ease: "Cubic.easeInOut", onComplete: () => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.gachaKnobs[this.gachaCursor], duration: this.getDelayValue(350), angle: 0, ease: "Sine.easeInOut" }); - gScene.time.delayedCall(this.getDelayValue(350), doPullAnim); + globalScene.time.delayedCall(this.getDelayValue(350), doPullAnim); } }); } else { @@ -437,7 +437,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { if (!eggs) { eggs = []; for (let i = 1; i <= pullCount; i++) { - const eggOptions: IEggOptions = { scene: gScene, pulled: true, sourceType: this.gachaCursor }; + const eggOptions: IEggOptions = { scene: globalScene, pulled: true, sourceType: this.gachaCursor }; // Before creating the last egg, check if the guaranteed egg tier was already generated // if not, override the egg tier @@ -455,9 +455,9 @@ export default class EggGachaUiHandler extends MessageUiHandler { eggs = Utils.randSeedShuffle(eggs); - (gScene.currentBattle ? gScene.gameData.saveAll(true, true, true) : gScene.gameData.saveSystem()).then(success => { + (globalScene.currentBattle ? globalScene.gameData.saveAll(true, true, true) : globalScene.gameData.saveSystem()).then(success => { if (!success) { - return gScene.reset(true); + return globalScene.reset(true); } doPull(); }); @@ -489,7 +489,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { const eggScale = eggs.length < 20 ? 1 : 0.5; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.eggGachaOverlay, alpha: 0.5, ease: "Sine.easeOut", @@ -507,10 +507,10 @@ export default class EggGachaUiHandler extends MessageUiHandler { const sliceWidth = this.eggGachaOverlay.displayWidth / (cols + 2); const sliceHeight = height / (rows + 2); const yOffset = (sliceHeight / 2 * (row / Math.max(rows - 1, 1))) + sliceHeight / 4; - const ret = gScene.add.container(sliceWidth * (col + 1) + (sliceWidth * 0.5), sliceHeight * (row + 1) + yOffset); + const ret = globalScene.add.container(sliceWidth * (col + 1) + (sliceWidth * 0.5), sliceHeight * (row + 1) + yOffset); ret.setScale(0.0001); - const eggSprite = gScene.add.sprite(0, 0, "egg", `egg_${egg.getKey()}`); + const eggSprite = globalScene.add.sprite(0, 0, "egg", `egg_${egg.getKey()}`); ret.add(eggSprite); const eggText = addTextObject(0, 14, egg.getEggDescriptor(), TextStyle.PARTY, { align: "center" }); @@ -526,8 +526,8 @@ export default class EggGachaUiHandler extends MessageUiHandler { // Otherwise show the eggs one by one with a small delay between each eggContainers.forEach((eggContainer, index) => { const delay = !this.transitionCancelled ? this.getDelayValue(index * 100) : 0; - gScene.time.delayedCall(delay, () => - gScene.tweens.add({ + globalScene.time.delayedCall(delay, () => + globalScene.tweens.add({ targets: eggContainer, duration: this.getDelayValue(350), scale: eggScale, @@ -547,7 +547,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { hideSummary() { this.setTransitioning(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.eggGachaOverlay, this.eggGachaSummaryContainer ], alpha: 0, duration: this.getDelayValue(250), @@ -575,13 +575,13 @@ export default class EggGachaUiHandler extends MessageUiHandler { } consumeVouchers(voucherType: VoucherType, count: integer): void { - gScene.gameData.voucherCounts[voucherType] = Math.max(gScene.gameData.voucherCounts[voucherType] - count, 0); + globalScene.gameData.voucherCounts[voucherType] = Math.max(globalScene.gameData.voucherCounts[voucherType] - count, 0); this.updateVoucherCounts(); } updateVoucherCounts(): void { this.voucherCountLabels.forEach((label, type) => { - label.setText(gScene.gameData.voucherCounts[type].toString()); + label.setText(globalScene.gameData.voucherCounts[type].toString()); }); } @@ -640,10 +640,10 @@ export default class EggGachaUiHandler extends MessageUiHandler { case Button.ACTION: switch (this.cursor) { case 0: - if (!gScene.gameData.voucherCounts[VoucherType.REGULAR] && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { + if (!globalScene.gameData.voucherCounts[VoucherType.REGULAR] && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { error = true; this.showError(i18next.t("egg:notEnoughVouchers")); - } else if (gScene.gameData.eggs.length < 99 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) { + } else if (globalScene.gameData.eggs.length < 99 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) { if (!Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { this.consumeVouchers(VoucherType.REGULAR, 1); } @@ -655,10 +655,10 @@ export default class EggGachaUiHandler extends MessageUiHandler { } break; case 2: - if (!gScene.gameData.voucherCounts[VoucherType.PLUS] && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { + if (!globalScene.gameData.voucherCounts[VoucherType.PLUS] && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { error = true; this.showError(i18next.t("egg:notEnoughVouchers")); - } else if (gScene.gameData.eggs.length < 95 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) { + } else if (globalScene.gameData.eggs.length < 95 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) { if (!Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { this.consumeVouchers(VoucherType.PLUS, 1); } @@ -671,11 +671,11 @@ export default class EggGachaUiHandler extends MessageUiHandler { break; case 1: case 3: - if ((this.cursor === 1 && gScene.gameData.voucherCounts[VoucherType.REGULAR] < 10 && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) - || (this.cursor === 3 && !gScene.gameData.voucherCounts[VoucherType.PREMIUM] && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE)) { + if ((this.cursor === 1 && globalScene.gameData.voucherCounts[VoucherType.REGULAR] < 10 && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) + || (this.cursor === 3 && !globalScene.gameData.voucherCounts[VoucherType.PREMIUM] && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE)) { error = true; this.showError(i18next.t("egg:notEnoughVouchers")); - } else if (gScene.gameData.eggs.length < 90 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) { + } else if (globalScene.gameData.eggs.length < 90 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) { if (this.cursor === 3) { if (!Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { this.consumeVouchers(VoucherType.PREMIUM, 1); @@ -693,10 +693,10 @@ export default class EggGachaUiHandler extends MessageUiHandler { } break; case 4: - if (!gScene.gameData.voucherCounts[VoucherType.GOLDEN] && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { + if (!globalScene.gameData.voucherCounts[VoucherType.GOLDEN] && !Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { error = true; this.showError(i18next.t("egg:notEnoughVouchers")); - } else if (gScene.gameData.eggs.length < 75 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) { + } else if (globalScene.gameData.eggs.length < 75 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) { if (!Overrides.EGG_FREE_GACHA_PULLS_OVERRIDE) { this.consumeVouchers(VoucherType.GOLDEN, 1); } @@ -754,7 +754,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { const ret = super.setCursor(cursor); if (!this.cursorObj) { - this.cursorObj = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.image(0, 0, "cursor"); this.eggGachaOptionsContainer.add(this.cursorObj); } @@ -774,7 +774,7 @@ export default class EggGachaUiHandler extends MessageUiHandler { this.setTransitioning(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.gachaContainers, duration: this.eggGachaContainer.visible ? 500 : 0, x: (_target, _key, _value, index) => 180 * (index - cursor), diff --git a/src/ui/egg-hatch-scene-handler.ts b/src/ui/egg-hatch-scene-handler.ts index 935a04c3cf1..6b19257113d 100644 --- a/src/ui/egg-hatch-scene-handler.ts +++ b/src/ui/egg-hatch-scene-handler.ts @@ -2,7 +2,7 @@ import { Mode } from "./ui"; import UiHandler from "./ui-handler"; import { Button } from "#enums/buttons"; import { EggHatchPhase } from "#app/phases/egg-hatch-phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class EggHatchSceneHandler extends UiHandler { public eggHatchContainer: Phaser.GameObjects.Container; @@ -20,12 +20,12 @@ export default class EggHatchSceneHandler extends UiHandler { } setup() { - this.eggHatchContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); - gScene.fieldUI.add(this.eggHatchContainer); + this.eggHatchContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); + globalScene.fieldUI.add(this.eggHatchContainer); - const eggLightraysAnimFrames = gScene.anims.generateFrameNames("egg_lightrays", { start: 0, end: 3 }); - if (!(gScene.anims.exists("egg_lightrays"))) { - gScene.anims.create({ + const eggLightraysAnimFrames = globalScene.anims.generateFrameNames("egg_lightrays", { start: 0, end: 3 }); + if (!(globalScene.anims.exists("egg_lightrays"))) { + globalScene.anims.create({ key: "egg_lightrays", frames: eggLightraysAnimFrames, frameRate: 32 @@ -38,20 +38,20 @@ export default class EggHatchSceneHandler extends UiHandler { this.getUi().showText("", 0); - gScene.setModifiersVisible(false); + globalScene.setModifiersVisible(false); return true; } processInput(button: Button): boolean { if (button === Button.ACTION || button === Button.CANCEL) { - const phase = gScene.getCurrentPhase(); + const phase = globalScene.getCurrentPhase(); if (phase instanceof EggHatchPhase && phase.trySkip()) { return true; } } - return gScene.ui.getMessageHandler().processInput(button); + return globalScene.ui.getMessageHandler().processInput(button); } setCursor(_cursor: integer): boolean { diff --git a/src/ui/egg-list-ui-handler.ts b/src/ui/egg-list-ui-handler.ts index e62d3ab16af..3b4d2855e02 100644 --- a/src/ui/egg-list-ui-handler.ts +++ b/src/ui/egg-list-ui-handler.ts @@ -7,7 +7,7 @@ import { Button } from "#enums/buttons"; import i18next from "i18next"; import ScrollableGridUiHandler from "#app/ui/scrollable-grid-handler"; import { ScrollBar } from "#app/ui/scroll-bar"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class EggListUiHandler extends MessageUiHandler { private readonly ROWS = 9; @@ -35,15 +35,15 @@ export default class EggListUiHandler extends MessageUiHandler { setup() { const ui = this.getUi(); - this.eggListContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); + this.eggListContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); this.eggListContainer.setVisible(false); ui.add(this.eggListContainer); - const bgColor = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0x006860); + const bgColor = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6, 0x006860); bgColor.setOrigin(0, 0); this.eggListContainer.add(bgColor); - const eggListBg = gScene.add.image(0, 0, "egg_list_bg"); + const eggListBg = globalScene.add.image(0, 0, "egg_list_bg"); eggListBg.setOrigin(0, 0); this.eggListContainer.add(eggListBg); @@ -70,14 +70,14 @@ export default class EggListUiHandler extends MessageUiHandler { this.eggGachaInfoText.setWordWrapWidth(540); this.eggListContainer.add(this.eggGachaInfoText); - this.eggListIconContainer = gScene.add.container(113, 5); + this.eggListIconContainer = globalScene.add.container(113, 5); this.eggListContainer.add(this.eggListIconContainer); - this.cursorObj = gScene.add.image(0, 0, "select_cursor"); + this.cursorObj = globalScene.add.image(0, 0, "select_cursor"); this.cursorObj.setOrigin(0, 0); this.eggListContainer.add(this.cursorObj); - this.eggSprite = gScene.add.sprite(54, 37, "egg"); + this.eggSprite = globalScene.add.sprite(54, 37, "egg"); this.eggListContainer.add(this.eggSprite); const scrollBar = new ScrollBar(310, 5, 4, 170, this.ROWS); @@ -88,7 +88,7 @@ export default class EggListUiHandler extends MessageUiHandler { .withUpdateGridCallBack(() => this.updateEggIcons()) .withUpdateSingleElementCallback((i:number) => this.setEggDetails(i)); - this.eggListMessageBoxContainer = gScene.add.container(0, gScene.game.canvas.height / 6); + this.eggListMessageBoxContainer = globalScene.add.container(0, globalScene.game.canvas.height / 6); this.eggListMessageBoxContainer.setVisible(false); this.eggListContainer.add(this.eggListMessageBoxContainer); @@ -112,7 +112,7 @@ export default class EggListUiHandler extends MessageUiHandler { this.eggListContainer.setVisible(true); - this.scrollGridHandler.setTotalElements(gScene.gameData.eggs.length); + this.scrollGridHandler.setTotalElements(globalScene.gameData.eggs.length); this.updateEggIcons(); this.setCursor(0); @@ -125,10 +125,10 @@ export default class EggListUiHandler extends MessageUiHandler { */ private initEggIcons() { this.eggIcons = []; - for (let i = 0; i < Math.min(this.ROWS * this.COLUMNS, gScene.gameData.eggs.length); i++) { + for (let i = 0; i < Math.min(this.ROWS * this.COLUMNS, globalScene.gameData.eggs.length); i++) { const x = (i % this.COLUMNS) * 18; const y = Math.floor(i / this.COLUMNS) * 18; - const icon = gScene.add.sprite(x - 2, y + 2, "egg_icons"); + const icon = globalScene.add.sprite(x - 2, y + 2, "egg_icons"); icon.setScale(0.5); icon.setOrigin(0, 0); this.eggListIconContainer.add(icon); @@ -141,14 +141,14 @@ export default class EggListUiHandler extends MessageUiHandler { */ private updateEggIcons() { const indexOffset = this.scrollGridHandler.getItemOffset(); - const eggsToShow = Math.min(this.eggIcons.length, gScene.gameData.eggs.length - indexOffset); + const eggsToShow = Math.min(this.eggIcons.length, globalScene.gameData.eggs.length - indexOffset); this.eggIcons.forEach((icon, i) => { if (i !== this.cursor) { this.iconAnimHandler.addOrUpdate(icon, PokemonIconAnimMode.NONE); } if (i < eggsToShow) { - const egg = gScene.gameData.eggs[i + indexOffset]; + const egg = globalScene.gameData.eggs[i + indexOffset]; icon.setFrame(egg.getKey()); icon.setVisible(true); } else { @@ -162,7 +162,7 @@ export default class EggListUiHandler extends MessageUiHandler { * @param index which egg in the list to display the info for */ private setEggDetails(index: number): void { - const egg = gScene.gameData.eggs[index]; + const egg = globalScene.gameData.eggs[index]; this.eggSprite.setFrame(`egg_${egg.getKey()}`); this.eggNameText.setText(`${i18next.t("egg:egg")} (${egg.getEggDescriptor()})`); this.eggDateText.setText( diff --git a/src/ui/egg-summary-ui-handler.ts b/src/ui/egg-summary-ui-handler.ts index 3018f174bb9..bfe7ae7d64f 100644 --- a/src/ui/egg-summary-ui-handler.ts +++ b/src/ui/egg-summary-ui-handler.ts @@ -9,7 +9,7 @@ import { EggHatchData } from "#app/data/egg-hatch-data"; import ScrollableGridUiHandler from "./scrollable-grid-handler"; import { HatchedPokemonContainer } from "./hatched-pokemon-container"; import { ScrollBar } from "#app/ui/scroll-bar"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; const iconContainerX = 112; const iconContainerY = 9; @@ -60,27 +60,27 @@ export default class EggSummaryUiHandler extends MessageUiHandler { setup() { const ui = this.getUi(); - this.summaryContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); + this.summaryContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); this.summaryContainer.setVisible(false); ui.add(this.summaryContainer); - this.eggHatchContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); + this.eggHatchContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); this.eggHatchContainer.setVisible(false); ui.add(this.eggHatchContainer); this.iconAnimHandler = new PokemonIconAnimHandler(); this.iconAnimHandler.setup(); - this.eggHatchBg = gScene.add.image(0, 0, "egg_summary_bg"); + this.eggHatchBg = globalScene.add.image(0, 0, "egg_summary_bg"); this.eggHatchBg.setOrigin(0, 0); this.eggHatchContainer.add(this.eggHatchBg); - this.cursorObj = gScene.add.image(0, 0, "select_cursor"); + this.cursorObj = globalScene.add.image(0, 0, "select_cursor"); this.cursorObj.setOrigin(0, 0); this.summaryContainer.add(this.cursorObj); this.pokemonContainers = []; - this.pokemonIconsContainer = gScene.add.container(iconContainerX, iconContainerY); + this.pokemonIconsContainer = globalScene.add.container(iconContainerX, iconContainerY); this.summaryContainer.add(this.pokemonIconsContainer); this.infoContainer = new PokemonHatchInfoContainer(this.summaryContainer); @@ -89,7 +89,7 @@ export default class EggSummaryUiHandler extends MessageUiHandler { this.infoContainer.setVisible(true); this.summaryContainer.add(this.infoContainer); - const scrollBar = new ScrollBar(iconContainerX + numCols * iconSize, iconContainerY + 3, 4, gScene.game.canvas.height / 6 - 20, numRows); + const scrollBar = new ScrollBar(iconContainerX + numCols * iconSize, iconContainerY + 3, 4, globalScene.game.canvas.height / 6 - 20, numRows); this.summaryContainer.add(scrollBar); this.scrollGridHandler = new ScrollableGridUiHandler(this, numRows, numCols) @@ -112,19 +112,19 @@ export default class EggSummaryUiHandler extends MessageUiHandler { this.getUi().hideTooltip(); // Note: Questions on garbage collection go to @frutescens - const activeKeys = gScene.getActiveKeys(); + const activeKeys = globalScene.getActiveKeys(); // Removing unnecessary sprites from animation manager - const animKeys = Object.keys(gScene.anims["anims"]["entries"]); + const animKeys = Object.keys(globalScene.anims["anims"]["entries"]); animKeys.forEach(key => { if (key.startsWith("pkmn__") && !activeKeys.includes(key)) { - gScene.anims.remove(key); + globalScene.anims.remove(key); } }); // Removing unnecessary cries from audio cache - const audioKeys = Object.keys(gScene.cache.audio.entries.entries); + const audioKeys = Object.keys(globalScene.cache.audio.entries.entries); audioKeys.forEach(key => { if (key.startsWith("cry/") && !activeKeys.includes(key)) { - delete gScene.cache.audio.entries.entries[key]; + delete globalScene.cache.audio.entries.entries[key]; } }); // Clears eggHatchData in EggSummaryUiHandler @@ -170,13 +170,13 @@ export default class EggSummaryUiHandler extends MessageUiHandler { this.updatePokemonIcons(); this.setCursor(0); - gScene.playSoundWithoutBgm("evolution_fanfare"); + globalScene.playSoundWithoutBgm("evolution_fanfare"); // Prevent exiting the egg summary for 2 seconds if the egg hatching // was skipped automatically and for 1 second otherwise - const exitBlockingDuration = (gScene.eggSkipPreference === 2) ? 2000 : 1000; + const exitBlockingDuration = (globalScene.eggSkipPreference === 2) ? 2000 : 1000; this.blockExit = true; - gScene.time.delayedCall(exitBlockingDuration, () => this.blockExit = false); + globalScene.time.delayedCall(exitBlockingDuration, () => this.blockExit = false); return true; } @@ -216,7 +216,7 @@ export default class EggSummaryUiHandler extends MessageUiHandler { let error = false; if (button === Button.CANCEL) { if (!this.blockExit) { - const phase = gScene.getCurrentPhase(); + const phase = globalScene.getCurrentPhase(); if (phase instanceof EggSummaryPhase) { phase.end(); } diff --git a/src/ui/evolution-scene-handler.ts b/src/ui/evolution-scene-handler.ts index aec53c72adc..161dbe5bcd6 100644 --- a/src/ui/evolution-scene-handler.ts +++ b/src/ui/evolution-scene-handler.ts @@ -2,7 +2,7 @@ import MessageUiHandler from "./message-ui-handler"; import { TextStyle, addTextObject } from "./text"; import { Mode } from "./ui"; import { Button } from "#enums/buttons"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class EvolutionSceneHandler extends MessageUiHandler { public evolutionContainer: Phaser.GameObjects.Container; @@ -21,17 +21,17 @@ export default class EvolutionSceneHandler extends MessageUiHandler { const ui = this.getUi(); - this.evolutionContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); + this.evolutionContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); ui.add(this.evolutionContainer); - const messageBg = gScene.add.sprite(0, 0, "bg", gScene.windowType); + const messageBg = globalScene.add.sprite(0, 0, "bg", globalScene.windowType); messageBg.setOrigin(0, 1); messageBg.setVisible(false); ui.add(messageBg); this.messageBg = messageBg; - this.messageContainer = gScene.add.container(12, -39); + this.messageContainer = globalScene.add.container(12, -39); this.messageContainer.setVisible(false); ui.add(this.messageContainer); @@ -51,9 +51,9 @@ export default class EvolutionSceneHandler extends MessageUiHandler { show(_args: any[]): boolean { super.show(_args); - gScene.ui.bringToTop(this.evolutionContainer); - gScene.ui.bringToTop(this.messageBg); - gScene.ui.bringToTop(this.messageContainer); + globalScene.ui.bringToTop(this.evolutionContainer); + globalScene.ui.bringToTop(this.messageBg); + globalScene.ui.bringToTop(this.messageContainer); this.messageBg.setVisible(true); this.messageContainer.setVisible(true); diff --git a/src/ui/fight-ui-handler.ts b/src/ui/fight-ui-handler.ts index 895d94dca14..fcc455af5b9 100644 --- a/src/ui/fight-ui-handler.ts +++ b/src/ui/fight-ui-handler.ts @@ -1,4 +1,4 @@ -import { gScene, InfoToggle } from "#app/battle-scene"; +import { globalScene, InfoToggle } from "#app/battle-scene"; import { addTextObject, TextStyle } from "./text"; import { getTypeDamageMultiplierColor, Type } from "../data/type"; import { Command } from "./command-ui-handler"; @@ -39,51 +39,51 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { setup() { const ui = this.getUi(); - this.movesContainer = gScene.add.container(18, -38.7); + this.movesContainer = globalScene.add.container(18, -38.7); this.movesContainer.setName(FightUiHandler.MOVES_CONTAINER_NAME); ui.add(this.movesContainer); - this.moveInfoContainer = gScene.add.container(1, 0); + this.moveInfoContainer = globalScene.add.container(1, 0); this.moveInfoContainer.setName("move-info"); ui.add(this.moveInfoContainer); - this.typeIcon = gScene.add.sprite(gScene.scaledCanvas.width - 57, -36, Utils.getLocalizedSpriteKey("types"), "unknown"); + this.typeIcon = globalScene.add.sprite(globalScene.scaledCanvas.width - 57, -36, Utils.getLocalizedSpriteKey("types"), "unknown"); this.typeIcon.setVisible(false); this.moveInfoContainer.add(this.typeIcon); - this.moveCategoryIcon = gScene.add.sprite(gScene.scaledCanvas.width - 25, -36, "categories", "physical"); + this.moveCategoryIcon = globalScene.add.sprite(globalScene.scaledCanvas.width - 25, -36, "categories", "physical"); this.moveCategoryIcon.setVisible(false); this.moveInfoContainer.add(this.moveCategoryIcon); - this.ppLabel = addTextObject(gScene.scaledCanvas.width - 70, -26, "PP", TextStyle.MOVE_INFO_CONTENT); + this.ppLabel = addTextObject(globalScene.scaledCanvas.width - 70, -26, "PP", TextStyle.MOVE_INFO_CONTENT); this.ppLabel.setOrigin(0.0, 0.5); this.ppLabel.setVisible(false); this.ppLabel.setText(i18next.t("fightUiHandler:pp")); this.moveInfoContainer.add(this.ppLabel); - this.ppText = addTextObject(gScene.scaledCanvas.width - 12, -26, "--/--", TextStyle.MOVE_INFO_CONTENT); + this.ppText = addTextObject(globalScene.scaledCanvas.width - 12, -26, "--/--", TextStyle.MOVE_INFO_CONTENT); this.ppText.setOrigin(1, 0.5); this.ppText.setVisible(false); this.moveInfoContainer.add(this.ppText); - this.powerLabel = addTextObject(gScene.scaledCanvas.width - 70, -18, "POWER", TextStyle.MOVE_INFO_CONTENT); + this.powerLabel = addTextObject(globalScene.scaledCanvas.width - 70, -18, "POWER", TextStyle.MOVE_INFO_CONTENT); this.powerLabel.setOrigin(0.0, 0.5); this.powerLabel.setVisible(false); this.powerLabel.setText(i18next.t("fightUiHandler:power")); this.moveInfoContainer.add(this.powerLabel); - this.powerText = addTextObject(gScene.scaledCanvas.width - 12, -18, "---", TextStyle.MOVE_INFO_CONTENT); + this.powerText = addTextObject(globalScene.scaledCanvas.width - 12, -18, "---", TextStyle.MOVE_INFO_CONTENT); this.powerText.setOrigin(1, 0.5); this.powerText.setVisible(false); this.moveInfoContainer.add(this.powerText); - this.accuracyLabel = addTextObject(gScene.scaledCanvas.width - 70, -10, "ACC", TextStyle.MOVE_INFO_CONTENT); + this.accuracyLabel = addTextObject(globalScene.scaledCanvas.width - 70, -10, "ACC", TextStyle.MOVE_INFO_CONTENT); this.accuracyLabel.setOrigin(0.0, 0.5); this.accuracyLabel.setVisible(false); this.accuracyLabel.setText(i18next.t("fightUiHandler:accuracy")); this.moveInfoContainer.add(this.accuracyLabel); - this.accuracyText = addTextObject(gScene.scaledCanvas.width - 12, -10, "---", TextStyle.MOVE_INFO_CONTENT); + this.accuracyText = addTextObject(globalScene.scaledCanvas.width - 12, -10, "---", TextStyle.MOVE_INFO_CONTENT); this.accuracyText.setOrigin(1, 0.5); this.accuracyText.setVisible(false); this.moveInfoContainer.add(this.accuracyText); @@ -97,14 +97,14 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { right: true, x: 0, y: -MoveInfoOverlay.getHeight(overlayScale, true), - width: (gScene.game.canvas.width / 6) + 4, + width: (globalScene.game.canvas.width / 6) + 4, hideEffectBox: true, hideBg: true }); ui.add(this.moveInfoOverlay); // register the overlay to receive toggle events - gScene.addInfoToggle(this.moveInfoOverlay); - gScene.addInfoToggle(this); + globalScene.addInfoToggle(this.moveInfoOverlay); + globalScene.addInfoToggle(this); } show(args: any[]): boolean { @@ -116,7 +116,7 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { messageHandler.bg.setVisible(false); messageHandler.commandWindow.setVisible(false); messageHandler.movesWindowContainer.setVisible(true); - const pokemon = (gScene.getCurrentPhase() as CommandPhase).getPokemon(); + const pokemon = (globalScene.getCurrentPhase() as CommandPhase).getPokemon(); if (pokemon.battleSummonData.turnCount <= 1) { this.setCursor(0); } else { @@ -137,14 +137,14 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { if (button === Button.CANCEL || button === Button.ACTION) { if (button === Button.ACTION) { - if ((gScene.getCurrentPhase() as CommandPhase).handleCommand(Command.FIGHT, cursor, false)) { + if ((globalScene.getCurrentPhase() as CommandPhase).handleCommand(Command.FIGHT, cursor, false)) { success = true; } else { ui.playError(); } } else { // Cannot back out of fight menu if skipToFightInput is enabled - const { battleType, mysteryEncounter } = gScene.currentBattle; + const { battleType, mysteryEncounter } = globalScene.currentBattle; if (battleType !== BattleType.MYSTERY_ENCOUNTER || !mysteryEncounter?.skipToFightInput) { ui.setMode(Mode.COMMAND, this.fieldIndex); success = true; @@ -187,7 +187,7 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { this.movesContainer.setVisible(false); this.cursorObj?.setVisible(false); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.movesContainer, this.cursorObj ], duration: Utils.fixedInt(125), ease: "Sine.easeInOut", @@ -221,11 +221,11 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { } if (!this.cursorObj) { - this.cursorObj = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.image(0, 0, "cursor"); ui.add(this.cursorObj); } - const pokemon = (gScene.getCurrentPhase() as CommandPhase).getPokemon(); + const pokemon = (globalScene.getCurrentPhase() as CommandPhase).getPokemon(); const moveset = pokemon.getMoveset(); const hasMove = cursor < moveset.length; @@ -299,7 +299,7 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { } displayMoves() { - const pokemon = (gScene.getCurrentPhase() as CommandPhase).getPokemon(); + const pokemon = (globalScene.getCurrentPhase() as CommandPhase).getPokemon(); const moveset = pokemon.getMoveset(); for (let moveIndex = 0; moveIndex < 4; moveIndex++) { @@ -323,7 +323,7 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { * @returns A color or undefined if the default color should be used */ private getMoveColor(pokemon: Pokemon, pokemonMove: PokemonMove): string | undefined { - if (!gScene.typeHints) { + if (!globalScene.typeHints) { return undefined; } @@ -361,7 +361,7 @@ export default class FightUiHandler extends UiHandler implements InfoToggle { clearMoves() { this.movesContainer.removeAll(true); - const opponents = (gScene.getCurrentPhase() as CommandPhase).getPokemon().getOpponents(); + const opponents = (globalScene.getCurrentPhase() as CommandPhase).getPokemon().getOpponents(); opponents.forEach((opponent) => { opponent.updateEffectiveness(undefined); }); diff --git a/src/ui/filter-bar.ts b/src/ui/filter-bar.ts index d8a2f762924..0f17e5bd4c0 100644 --- a/src/ui/filter-bar.ts +++ b/src/ui/filter-bar.ts @@ -3,7 +3,7 @@ import { StarterContainer } from "./starter-container"; import { addTextObject, getTextColor, TextStyle } from "./text"; import { UiTheme } from "#enums/ui-theme"; import { addWindow, WindowVariant } from "./ui-theme"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export enum DropDownColumn { GEN, @@ -26,7 +26,7 @@ export class FilterBar extends Phaser.GameObjects.Container { private uiTheme: UiTheme; constructor(x: number, y: number, width: number, height: number) { - super(gScene, x, y); + super(globalScene, x, y); this.width = width; this.height = height; @@ -34,13 +34,13 @@ export class FilterBar extends Phaser.GameObjects.Container { this.window = addWindow(0, 0, width, height, false, false, undefined, undefined, WindowVariant.THIN); this.add(this.window); - this.cursorObj = gScene.add.image(1, 1, "cursor"); + this.cursorObj = globalScene.add.image(1, 1, "cursor"); this.cursorObj.setScale(0.5); this.cursorObj.setVisible(false); this.cursorObj.setOrigin(0, 0); this.add(this.cursorObj); - this.uiTheme = gScene.uiTheme; + this.uiTheme = globalScene.uiTheme; } /** diff --git a/src/ui/form-modal-ui-handler.ts b/src/ui/form-modal-ui-handler.ts index d38dff5f92e..2d5e6da9e90 100644 --- a/src/ui/form-modal-ui-handler.ts +++ b/src/ui/form-modal-ui-handler.ts @@ -5,7 +5,7 @@ import { WindowVariant, addWindow } from "./ui-theme"; import InputText from "phaser3-rex-plugins/plugins/inputtext"; import * as Utils from "../utils"; import { Button } from "#enums/buttons"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export interface FormModalConfig extends ModalConfig { errorMessage?: string; @@ -77,7 +77,7 @@ export abstract class FormModalUiHandler extends ModalUiHandler { this.formLabels.push(label); this.modalContainer.add(this.formLabels[this.formLabels.length - 1]); - const inputContainer = gScene.add.container(70, (hasTitle ? 28 : 2) + 20 * f); + const inputContainer = globalScene.add.container(70, (hasTitle ? 28 : 2) + 20 * f); inputContainer.setVisible(false); const inputBg = addWindow(0, 0, 80, 16, false, false, 0, 0, WindowVariant.XTHIN); @@ -119,7 +119,7 @@ export abstract class FormModalUiHandler extends ModalUiHandler { this.modalContainer.y += 24; this.modalContainer.setAlpha(0); - this.tween = gScene.tweens.add({ + this.tween = globalScene.tweens.add({ targets: this.modalContainer, duration: Utils.fixedInt(1000), ease: "Sine.easeInOut", diff --git a/src/ui/game-stats-ui-handler.ts b/src/ui/game-stats-ui-handler.ts index ff5a6e656e7..8e787413f7d 100644 --- a/src/ui/game-stats-ui-handler.ts +++ b/src/ui/game-stats-ui-handler.ts @@ -9,7 +9,7 @@ import { speciesStarterCosts } from "#app/data/balance/starters"; import { Button } from "#enums/buttons"; import i18next from "i18next"; import { UiTheme } from "#enums/ui-theme"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; interface DisplayStat { label_key?: string; @@ -232,27 +232,27 @@ export default class GameStatsUiHandler extends UiHandler { setup() { const ui = this.getUi(); - this.gameStatsContainer = gScene.add.container(1, -(gScene.game.canvas.height / 6) + 1); + this.gameStatsContainer = globalScene.add.container(1, -(globalScene.game.canvas.height / 6) + 1); - this.gameStatsContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); + this.gameStatsContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); - const headerBg = addWindow(0, 0, (gScene.game.canvas.width / 6) - 2, 24); + const headerBg = addWindow(0, 0, (globalScene.game.canvas.width / 6) - 2, 24); headerBg.setOrigin(0, 0); const headerText = addTextObject(0, 0, i18next.t("gameStatsUiHandler:stats"), TextStyle.SETTINGS_LABEL); headerText.setOrigin(0, 0); headerText.setPositionRelative(headerBg, 8, 4); - const statsBgWidth = ((gScene.game.canvas.width / 6) - 2) / 2; + const statsBgWidth = ((globalScene.game.canvas.width / 6) - 2) / 2; const [ statsBgLeft, statsBgRight ] = new Array(2).fill(null).map((_, i) => { const width = statsBgWidth + 2; - const height = Math.floor((gScene.game.canvas.height / 6) - headerBg.height - 2); + const height = Math.floor((globalScene.game.canvas.height / 6) - headerBg.height - 2); const statsBg = addWindow((statsBgWidth - 2) * i, headerBg.height, width, height, false, false, i > 0 ? -3 : 0, 1); statsBg.setOrigin(0, 0); return statsBg; }); - this.statsContainer = gScene.add.container(0, 0); + this.statsContainer = globalScene.add.container(0, 0); new Array(18).fill(null).map((_, s) => { @@ -275,10 +275,10 @@ export default class GameStatsUiHandler extends UiHandler { this.gameStatsContainer.add(this.statsContainer); // arrows to show that we can scroll through the stats - const isLegacyTheme = gScene.uiTheme === UiTheme.LEGACY; - this.arrowDown = gScene.add.sprite(statsBgWidth, gScene.game.canvas.height / 6 - (isLegacyTheme ? 9 : 5), "prompt"); + const isLegacyTheme = globalScene.uiTheme === UiTheme.LEGACY; + this.arrowDown = globalScene.add.sprite(statsBgWidth, globalScene.game.canvas.height / 6 - (isLegacyTheme ? 9 : 5), "prompt"); this.gameStatsContainer.add(this.arrowDown); - this.arrowUp = gScene.add.sprite(statsBgWidth, headerBg.height + (isLegacyTheme ? 7 : 3), "prompt"); + this.arrowUp = globalScene.add.sprite(statsBgWidth, headerBg.height + (isLegacyTheme ? 7 : 3), "prompt"); this.arrowUp.flipY = true; this.gameStatsContainer.add(this.arrowUp); @@ -298,7 +298,7 @@ export default class GameStatsUiHandler extends UiHandler { this.arrowUp.play("prompt"); this.arrowDown.play("prompt"); - if (gScene.uiTheme === UiTheme.LEGACY) { + if (globalScene.uiTheme === UiTheme.LEGACY) { this.arrowUp.setTint(0x484848); this.arrowDown.setTint(0x484848); } @@ -318,7 +318,7 @@ export default class GameStatsUiHandler extends UiHandler { const statKeys = Object.keys(displayStats).slice(this.cursor * 2, this.cursor * 2 + 18); statKeys.forEach((key, s) => { const stat = displayStats[key] as DisplayStat; - const value = stat.sourceFunc!(gScene.gameData); // TODO: is this bang correct? + const value = stat.sourceFunc!(globalScene.gameData); // TODO: is this bang correct? this.statLabels[s].setText(!stat.hidden || isNaN(parseInt(value)) || parseInt(value) ? i18next.t(`gameStatsUiHandler:${stat.label_key}`) : "???"); this.statValues[s].setText(value); }); @@ -348,7 +348,7 @@ export default class GameStatsUiHandler extends UiHandler { if (button === Button.CANCEL) { success = true; - gScene.ui.revertMode(); + globalScene.ui.revertMode(); } else { switch (button) { case Button.UP: diff --git a/src/ui/hatched-pokemon-container.ts b/src/ui/hatched-pokemon-container.ts index 2275d7bc480..22e33c9a54c 100644 --- a/src/ui/hatched-pokemon-container.ts +++ b/src/ui/hatched-pokemon-container.ts @@ -2,7 +2,7 @@ import { EggHatchData } from "#app/data/egg-hatch-data"; import { Gender } from "#app/data/gender"; import { getVariantTint } from "#app/data/variant"; import { DexAttr } from "#app/system/game-data"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import PokemonSpecies from "#app/data/pokemon-species"; import PokemonIconAnimHandler, { PokemonIconAnimMode } from "./pokemon-icon-anim-handler"; @@ -25,7 +25,7 @@ export class HatchedPokemonContainer extends Phaser.GameObjects.Container { * @param hatchData the {@linkcode EggHatchData} to load the icons and sprites for */ constructor(x: number, y: number, hatchData: EggHatchData) { - super(gScene, x, y); + super(globalScene, x, y); const displayPokemon = hatchData.pokemon; this.species = displayPokemon.species; @@ -39,7 +39,7 @@ export class HatchedPokemonContainer extends Phaser.GameObjects.Container { const isShiny = displayPokemon.shiny; // Pokemon sprite - const pokemonIcon = gScene.add.sprite(-offset, offset, species.getIconAtlasKey(formIndex, isShiny, variant)); + const pokemonIcon = globalScene.add.sprite(-offset, offset, species.getIconAtlasKey(formIndex, isShiny, variant)); pokemonIcon.setScale(0.5); pokemonIcon.setOrigin(0, 0); pokemonIcon.setFrame(species.getIconId(female, formIndex, isShiny, variant)); @@ -48,27 +48,27 @@ export class HatchedPokemonContainer extends Phaser.GameObjects.Container { this.add(this.icon); // Shiny icon - this.shinyIcon = gScene.add.image(rightSideX, offset, "shiny_star_small"); + this.shinyIcon = globalScene.add.image(rightSideX, offset, "shiny_star_small"); this.shinyIcon.setOrigin(0, 0); this.shinyIcon.setScale(0.5); this.add(this.shinyIcon); // Hidden ability icon - const haIcon = gScene.add.image(rightSideX, offset * 4, "ha_capsule"); + const haIcon = globalScene.add.image(rightSideX, offset * 4, "ha_capsule"); haIcon.setOrigin(0, 0); haIcon.setScale(0.5); this.hiddenAbilityIcon = haIcon; this.add(this.hiddenAbilityIcon); // Pokeball icon - const pokeballIcon = gScene.add.image(rightSideX, offset * 7, "icon_owned"); + const pokeballIcon = globalScene.add.image(rightSideX, offset * 7, "icon_owned"); pokeballIcon.setOrigin(0, 0); pokeballIcon.setScale(0.5); this.pokeballIcon = pokeballIcon; this.add(this.pokeballIcon); // Egg move icon - const eggMoveIcon = gScene.add.image(0, offset, "icon_egg_move"); + const eggMoveIcon = globalScene.add.image(0, offset, "icon_egg_move"); eggMoveIcon.setOrigin(0, 0); eggMoveIcon.setScale(0.5); this.eggMoveIcon = eggMoveIcon; diff --git a/src/ui/login-form-ui-handler.ts b/src/ui/login-form-ui-handler.ts index 55949c9d15a..28ce7ba309f 100644 --- a/src/ui/login-form-ui-handler.ts +++ b/src/ui/login-form-ui-handler.ts @@ -6,7 +6,7 @@ import i18next from "i18next"; import { addTextObject, TextStyle } from "./text"; import { addWindow } from "./ui-theme"; import { OptionSelectItem } from "#app/ui/abstact-option-select-ui-handler"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; interface BuildInteractableImageOpts { scale?: number; @@ -38,7 +38,7 @@ export default class LoginFormUiHandler extends FormModalUiHandler { super.setup(); this.buildExternalPartyContainer(); - this.infoContainer = gScene.add.container(0, 0); + this.infoContainer = globalScene.add.container(0, 0); this.usernameInfoImage = this.buildInteractableImage("settings_icon", "username-info-icon", { x: 20, @@ -52,8 +52,8 @@ export default class LoginFormUiHandler extends FormModalUiHandler { } private buildExternalPartyContainer() { - this.externalPartyContainer = gScene.add.container(0, 0); - this.externalPartyContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 12, gScene.game.canvas.height / 12), Phaser.Geom.Rectangle.Contains); + this.externalPartyContainer = globalScene.add.container(0, 0); + this.externalPartyContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 12, globalScene.game.canvas.height / 12), Phaser.Geom.Rectangle.Contains); this.externalPartyTitle = addTextObject(0, 4, "", TextStyle.SETTINGS_LABEL); this.externalPartyTitle.setOrigin(0.5, 0); this.externalPartyBg = addWindow(0, 0, 0, 0); @@ -127,10 +127,10 @@ export default class LoginFormUiHandler extends FormModalUiHandler { // Prevent overlapping overrides on action modification this.submitAction = originalLoginAction; this.sanitizeInputs(); - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); const onFail = error => { - gScene.ui.setMode(Mode.LOGIN_FORM, Object.assign(config, { errorMessage: error?.trim() })); - gScene.ui.playError(); + globalScene.ui.setMode(Mode.LOGIN_FORM, Object.assign(config, { errorMessage: error?.trim() })); + globalScene.ui.playError(); }; if (!this.inputs[0].text) { return onFail(i18next.t("menu:emptyUsername")); @@ -198,9 +198,9 @@ export default class LoginFormUiHandler extends FormModalUiHandler { }); const onFail = error => { - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); - gScene.ui.setModeForceTransition(Mode.LOGIN_FORM, Object.assign(config, { errorMessage: error?.trim() })); - gScene.ui.playError(); + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); + globalScene.ui.setModeForceTransition(Mode.LOGIN_FORM, Object.assign(config, { errorMessage: error?.trim() })); + globalScene.ui.playError(); }; this.usernameInfoImage.on("pointerdown", () => { @@ -213,17 +213,17 @@ export default class LoginFormUiHandler extends FormModalUiHandler { options.push({ label: dataKeys[i].replace(keyToFind, ""), handler: () => { - gScene.ui.revertMode(); + globalScene.ui.revertMode(); this.infoContainer.disableInteractive(); return true; } }); } - gScene.ui.setOverlayMode(Mode.OPTION_SELECT, { + globalScene.ui.setOverlayMode(Mode.OPTION_SELECT, { options: options, delay: 1000 }); - this.infoContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width, gScene.game.canvas.height), Phaser.Geom.Rectangle.Contains); + this.infoContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width, globalScene.game.canvas.height), Phaser.Geom.Rectangle.Contains); } else { if (dataKeys.length > 2) { return onFail(this.ERR_TOO_MANY_SAVES); @@ -234,7 +234,7 @@ export default class LoginFormUiHandler extends FormModalUiHandler { }); this.externalPartyContainer.setAlpha(0); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.externalPartyContainer, duration: Utils.fixedInt(1000), ease: "Sine.easeInOut", @@ -243,7 +243,7 @@ export default class LoginFormUiHandler extends FormModalUiHandler { }); this.infoContainer.setAlpha(0); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.infoContainer, duration: Utils.fixedInt(1000), ease: "Sine.easeInOut", @@ -259,7 +259,7 @@ export default class LoginFormUiHandler extends FormModalUiHandler { y = 0, origin = { x: 0, y: 0 } } = opts; - const img = gScene.add.image(x, y, texture); + const img = globalScene.add.image(x, y, texture); img.setName(name); img.setOrigin(origin.x, origin.y); img.setScale(scale); diff --git a/src/ui/menu-ui-handler.ts b/src/ui/menu-ui-handler.ts index 37d1bd1a63d..2746e158eb0 100644 --- a/src/ui/menu-ui-handler.ts +++ b/src/ui/menu-ui-handler.ts @@ -1,4 +1,4 @@ -import { bypassLogin, gScene } from "#app/battle-scene"; +import { bypassLogin, globalScene } from "#app/battle-scene"; import { TextStyle, addTextObject, getTextStyleOptions } from "./text"; import { Mode } from "./ui"; import * as Utils from "../utils"; @@ -90,11 +90,11 @@ export default class MenuUiHandler extends MessageUiHandler { ui.bgmBar = this.bgmBar; - this.menuContainer = gScene.add.container(1, -(gScene.game.canvas.height / 6) + 1); + this.menuContainer = globalScene.add.container(1, -(globalScene.game.canvas.height / 6) + 1); this.menuContainer.setName("menu"); - this.menuContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); + this.menuContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); - this.menuOverlay = new Phaser.GameObjects.Rectangle(gScene, -1, -1, gScene.scaledCanvas.width, gScene.scaledCanvas.height, 0xffffff, 0.3); + this.menuOverlay = new Phaser.GameObjects.Rectangle(globalScene, -1, -1, globalScene.scaledCanvas.width, globalScene.scaledCanvas.height, 0xffffff, 0.3); this.menuOverlay.setName("menu-overlay"); this.menuOverlay.setOrigin(0, 0); this.menuContainer.add(this.menuOverlay); @@ -109,7 +109,7 @@ export default class MenuUiHandler extends MessageUiHandler { render() { const ui = this.getUi(); this.excludedMenus = () => [ - { condition: gScene.getCurrentPhase() instanceof SelectModifierPhase, options: [ MenuOptions.EGG_GACHA, MenuOptions.EGG_LIST ]}, + { condition: globalScene.getCurrentPhase() instanceof SelectModifierPhase, options: [ MenuOptions.EGG_GACHA, MenuOptions.EGG_LIST ]}, { condition: bypassLogin, options: [ MenuOptions.LOG_OUT ]} ]; @@ -122,12 +122,12 @@ export default class MenuUiHandler extends MessageUiHandler { this.optionSelectText = addTextObject(0, 0, this.menuOptions.map(o => `${i18next.t(`menuUiHandler:${MenuOptions[o]}`)}`).join("\n"), TextStyle.WINDOW, { maxLines: this.menuOptions.length }); this.optionSelectText.setLineSpacing(12); - this.scale = getTextStyleOptions(TextStyle.WINDOW, gScene.uiTheme).scale; + this.scale = getTextStyleOptions(TextStyle.WINDOW, globalScene.uiTheme).scale; this.menuBg = addWindow( - (gScene.game.canvas.width / 6) - (this.optionSelectText.displayWidth + 25), + (globalScene.game.canvas.width / 6) - (this.optionSelectText.displayWidth + 25), 0, this.optionSelectText.displayWidth + 19 + 24 * this.scale, - (gScene.game.canvas.height / 6) - 2 + (globalScene.game.canvas.height / 6) - 2 ); this.menuBg.setOrigin(0, 0); @@ -139,7 +139,7 @@ export default class MenuUiHandler extends MessageUiHandler { ui.add(this.menuContainer); - this.menuMessageBoxContainer = gScene.add.container(0, 130); + this.menuMessageBoxContainer = globalScene.add.container(0, 130); this.menuMessageBoxContainer.setName("menu-message-box"); this.menuMessageBoxContainer.setVisible(false); @@ -149,7 +149,7 @@ export default class MenuUiHandler extends MessageUiHandler { this.menuMessageBoxContainer.add(this.menuMessageBox); // Full-width window used for testing dialog messages in debug mode - this.dialogueMessageBox = addWindow(-this.textPadding, 0, gScene.game.canvas.width / 6 + this.textPadding * 2, 49, false, false, 0, 0, WindowVariant.THIN); + this.dialogueMessageBox = addWindow(-this.textPadding, 0, globalScene.game.canvas.width / 6 + this.textPadding * 2, 49, false, false, 0, 0, WindowVariant.THIN); this.dialogueMessageBox.setOrigin(0, 0); this.menuMessageBoxContainer.add(this.dialogueMessageBox); @@ -202,7 +202,7 @@ export default class MenuUiHandler extends MessageUiHandler { manageDataOptions.push({ label: i18next.t("menuUiHandler:importSession"), handler: () => { - confirmSlot(i18next.t("menuUiHandler:importSlotSelect"), () => true, slotId => gScene.gameData.importData(GameDataType.SESSION, slotId)); + confirmSlot(i18next.t("menuUiHandler:importSlotSelect"), () => true, slotId => globalScene.gameData.importData(GameDataType.SESSION, slotId)); return true; }, keepOpen: true @@ -215,7 +215,7 @@ export default class MenuUiHandler extends MessageUiHandler { Promise.all( new Array(5).fill(null).map((_, i) => { const slotId = i; - return gScene.gameData.getSession(slotId).then(data => { + return globalScene.gameData.getSession(slotId).then(data => { if (data) { dataSlots.push(slotId); } @@ -223,7 +223,7 @@ export default class MenuUiHandler extends MessageUiHandler { })).then(() => { confirmSlot(i18next.t("menuUiHandler:exportSlotSelect"), i => dataSlots.indexOf(i) > -1, - slotId => gScene.gameData.tryExportData(GameDataType.SESSION, slotId)); + slotId => globalScene.gameData.tryExportData(GameDataType.SESSION, slotId)); }); return true; }, @@ -232,7 +232,7 @@ export default class MenuUiHandler extends MessageUiHandler { manageDataOptions.push({ label: i18next.t("menuUiHandler:importRunHistory"), handler: () => { - gScene.gameData.importData(GameDataType.RUN_HISTORY); + globalScene.gameData.importData(GameDataType.RUN_HISTORY); return true; }, keepOpen: true @@ -240,7 +240,7 @@ export default class MenuUiHandler extends MessageUiHandler { manageDataOptions.push({ label: i18next.t("menuUiHandler:exportRunHistory"), handler: () => { - gScene.gameData.tryExportData(GameDataType.RUN_HISTORY); + globalScene.gameData.tryExportData(GameDataType.RUN_HISTORY); return true; }, keepOpen: true @@ -250,7 +250,7 @@ export default class MenuUiHandler extends MessageUiHandler { label: i18next.t("menuUiHandler:importData"), handler: () => { ui.revertMode(); - gScene.gameData.importData(GameDataType.SYSTEM); + globalScene.gameData.importData(GameDataType.SYSTEM); return true; }, keepOpen: true @@ -259,7 +259,7 @@ export default class MenuUiHandler extends MessageUiHandler { manageDataOptions.push({ label: i18next.t("menuUiHandler:exportData"), handler: () => { - gScene.gameData.tryExportData(GameDataType.SYSTEM); + globalScene.gameData.tryExportData(GameDataType.SYSTEM); return true; }, keepOpen: true @@ -310,7 +310,7 @@ export default class MenuUiHandler extends MessageUiHandler { } // Switch to the dialog test window this.setDialogTestMode(true); - ui.showText(String(i18next.t(translatedString, interpolatorOptions)), null, () => gScene.ui.showText("", 0, () => { + ui.showText(String(i18next.t(translatedString, interpolatorOptions)), null, () => globalScene.ui.showText("", 0, () => { handler.tutorialActive = false; // Go back to the default message window this.setDialogTestMode(false); @@ -329,7 +329,7 @@ export default class MenuUiHandler extends MessageUiHandler { manageDataOptions.push({ label: i18next.t("menuUiHandler:cancel"), handler: () => { - gScene.ui.revertMode(); + globalScene.ui.revertMode(); return true; }, keepOpen: true @@ -420,7 +420,7 @@ export default class MenuUiHandler extends MessageUiHandler { return true; } }); - gScene.ui.setOverlayMode(Mode.OPTION_SELECT, { + globalScene.ui.setOverlayMode(Mode.OPTION_SELECT, { options: options, delay: 0 }); @@ -432,7 +432,7 @@ export default class MenuUiHandler extends MessageUiHandler { communityOptions.push({ label: i18next.t("menuUiHandler:cancel"), handler: () => { - gScene.ui.revertMode(); + globalScene.ui.revertMode(); return true; } }); @@ -460,7 +460,7 @@ export default class MenuUiHandler extends MessageUiHandler { this.getUi().hideTooltip(); - gScene.playSound("ui/menu_open"); + globalScene.playSound("ui/menu_open"); // Make sure the tutorial overlay sits above everything, but below the message box this.menuContainer.bringToTop(this.tutorialOverlay); @@ -511,7 +511,7 @@ export default class MenuUiHandler extends MessageUiHandler { success = true; break; case MenuOptions.EGG_LIST: - if (gScene.gameData.eggs.length) { + if (globalScene.gameData.eggs.length) { ui.revertMode(); ui.setOverlayMode(Mode.EGG_LIST); success = true; @@ -543,7 +543,7 @@ export default class MenuUiHandler extends MessageUiHandler { if (!res.ok) { console.error(`Unlink failed (${res.status}: ${res.statusText})`); } - updateUserInfo().then(() => gScene.reset(true, true)); + updateUserInfo().then(() => globalScene.reset(true, true)); }); return true; } @@ -564,7 +564,7 @@ export default class MenuUiHandler extends MessageUiHandler { if (!res.ok) { console.error(`Unlink failed (${res.status}: ${res.statusText})`); } - updateUserInfo().then(() => gScene.reset(true, true)); + updateUserInfo().then(() => globalScene.reset(true, true)); }); return true; } @@ -579,18 +579,18 @@ export default class MenuUiHandler extends MessageUiHandler { success = true; break; case MenuOptions.SAVE_AND_QUIT: - if (gScene.currentBattle) { + if (globalScene.currentBattle) { success = true; const doSaveQuit = () => { ui.setMode(Mode.LOADING, { buttonActions: [], fadeOut: () => - gScene.gameData.saveAll(true, true, true, true).then(() => { + globalScene.gameData.saveAll(true, true, true, true).then(() => { - gScene.reset(true); + globalScene.reset(true); }) }); }; - if (gScene.currentBattle.turn > 1) { + if (globalScene.currentBattle.turn > 1) { ui.showText(i18next.t("menuUiHandler:losingProgressionWarning"), null, () => { if (!this.active) { this.showText("", 0); @@ -617,11 +617,11 @@ export default class MenuUiHandler extends MessageUiHandler { console.error(`Log out failed (${res.status}: ${res.statusText})`); } Utils.removeCookie(Utils.sessionIdKey); - updateUserInfo().then(() => gScene.reset(true, true)); + updateUserInfo().then(() => globalScene.reset(true, true)); }) }); }; - if (gScene.currentBattle) { + if (globalScene.currentBattle) { ui.showText(i18next.t("menuUiHandler:losingProgressionWarning"), null, () => { if (!this.active) { this.showText("", 0); @@ -682,7 +682,7 @@ export default class MenuUiHandler extends MessageUiHandler { this.menuMessageBox.setVisible(!isDialogMode); this.dialogueMessageBox.setVisible(isDialogMode); // If we're testing dialog, we use the same word wrapping as the battle message handler - this.message.setWordWrapWidth(isDialogMode ? gScene.ui.getMessageHandler().wordWrapWidth : this.defaultWordWrapWidth); + this.message.setWordWrapWidth(isDialogMode ? globalScene.ui.getMessageHandler().wordWrapWidth : this.defaultWordWrapWidth); this.message.setX(isDialogMode ? this.textPadding + 1 : this.textPadding); this.message.setY(isDialogMode ? this.textPadding + 0.4 : this.textPadding); } @@ -697,7 +697,7 @@ export default class MenuUiHandler extends MessageUiHandler { const ret = super.setCursor(cursor); if (!this.cursorObj) { - this.cursorObj = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.image(0, 0, "cursor"); this.cursorObj.setOrigin(0, 0); this.menuContainer.add(this.cursorObj); } diff --git a/src/ui/message-ui-handler.ts b/src/ui/message-ui-handler.ts index 475cac69ec8..9fe4b76e3f6 100644 --- a/src/ui/message-ui-handler.ts +++ b/src/ui/message-ui-handler.ts @@ -1,7 +1,7 @@ import AwaitableUiHandler from "./awaitable-ui-handler"; import { Mode } from "./ui"; import * as Utils from "../utils"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default abstract class MessageUiHandler extends AwaitableUiHandler { protected textTimer: Phaser.Time.TimerEvent | null; @@ -23,7 +23,7 @@ export default abstract class MessageUiHandler extends AwaitableUiHandler { */ initPromptSprite(container: Phaser.GameObjects.Container) { if (!this.prompt) { - const promptSprite = gScene.add.sprite(0, 0, "prompt"); + const promptSprite = globalScene.add.sprite(0, 0, "prompt"); promptSprite.setVisible(false); promptSprite.setOrigin(0, 0); this.prompt = promptSprite; @@ -108,7 +108,7 @@ export default abstract class MessageUiHandler extends AwaitableUiHandler { callback = () => { const showPrompt = () => this.showPrompt(originalCallback, callbackDelay); if (promptDelay) { - gScene.time.delayedCall(promptDelay, showPrompt); + globalScene.time.delayedCall(promptDelay, showPrompt); } else { showPrompt(); } @@ -119,7 +119,7 @@ export default abstract class MessageUiHandler extends AwaitableUiHandler { if (prompt) { this.pendingPrompt = true; } - this.textTimer = gScene.time.addEvent({ + this.textTimer = globalScene.time.addEvent({ delay: delay, callback: () => { const charIndex = text.length - (this.textTimer?.repeatCount!); // TODO: is this bang correct? @@ -130,14 +130,14 @@ export default abstract class MessageUiHandler extends AwaitableUiHandler { this.message.setText(text.slice(0, charIndex)); const advance = () => { if (charVar) { - gScene.charSprite.setVariant(charVar); + globalScene.charSprite.setVariant(charVar); } if (charSound) { - gScene.playSound(charSound); + globalScene.playSound(charSound); } if (callback && !this.textTimer?.repeatCount) { if (callbackDelay && !prompt) { - this.textCallbackTimer = gScene.time.delayedCall(callbackDelay, () => { + this.textCallbackTimer = globalScene.time.delayedCall(callbackDelay, () => { if (this.textCallbackTimer) { this.textCallbackTimer.destroy(); this.textCallbackTimer = null; @@ -151,7 +151,7 @@ export default abstract class MessageUiHandler extends AwaitableUiHandler { }; if (charDelay) { this.textTimer!.paused = true; // TODO: is the bang correct? - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ duration: Utils.getFrameMs(charDelay), onComplete: () => { this.textTimer!.paused = false; // TODO: is the bang correct? @@ -160,11 +160,11 @@ export default abstract class MessageUiHandler extends AwaitableUiHandler { }); } else if (charFade) { this.textTimer!.paused = true; - gScene.time.delayedCall(150, () => { - gScene.ui.fadeOut(750).then(() => { + globalScene.time.delayedCall(150, () => { + globalScene.ui.fadeOut(750).then(() => { const delay = Utils.getFrameMs(charFade); - gScene.time.delayedCall(delay, () => { - gScene.ui.fadeIn(500).then(() => { + globalScene.time.delayedCall(delay, () => { + globalScene.ui.fadeIn(500).then(() => { this.textTimer!.paused = false; advance(); }); @@ -192,7 +192,7 @@ export default abstract class MessageUiHandler extends AwaitableUiHandler { const wrappedTextLines = this.message.runWordWrap(this.message.text).split(/\n/g); const textLinesCount = wrappedTextLines.length; const lastTextLine = wrappedTextLines[wrappedTextLines.length - 1]; - const lastLineTest = gScene.add.text(0, 0, lastTextLine, { font: "96px emerald" }); + const lastLineTest = globalScene.add.text(0, 0, lastTextLine, { font: "96px emerald" }); lastLineTest.setScale(this.message.scale); const lastLineWidth = lastLineTest.displayWidth; lastLineTest.destroy(); @@ -209,7 +209,7 @@ export default abstract class MessageUiHandler extends AwaitableUiHandler { } if (callback) { if (callbackDelay) { - this.textCallbackTimer = gScene.time.delayedCall(callbackDelay, () => { + this.textCallbackTimer = globalScene.time.delayedCall(callbackDelay, () => { if (this.textCallbackTimer) { this.textCallbackTimer.destroy(); this.textCallbackTimer = null; diff --git a/src/ui/modal-ui-handler.ts b/src/ui/modal-ui-handler.ts index f7f5ff200eb..ff41a1817ee 100644 --- a/src/ui/modal-ui-handler.ts +++ b/src/ui/modal-ui-handler.ts @@ -3,7 +3,7 @@ import { Mode } from "./ui"; import UiHandler from "./ui-handler"; import { WindowVariant, addWindow } from "./ui-theme"; import { Button } from "#enums/buttons"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export interface ModalConfig { buttonActions: Function[]; @@ -42,9 +42,9 @@ export abstract class ModalUiHandler extends UiHandler { setup() { const ui = this.getUi(); - this.modalContainer = gScene.add.container(0, 0); + this.modalContainer = globalScene.add.container(0, 0); - this.modalContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); + this.modalContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); this.modalBg = addWindow(0, 0, 0, 0); @@ -75,7 +75,7 @@ export abstract class ModalUiHandler extends UiHandler { buttonBg.setOrigin(0.5, 0); buttonBg.setInteractive(new Phaser.Geom.Rectangle(0, 0, buttonBg.width, buttonBg.height), Phaser.Geom.Rectangle.Contains); - const buttonContainer = gScene.add.container(0, buttonTopMargin); + const buttonContainer = globalScene.add.container(0, buttonTopMargin); this.buttonLabels.push(buttonLabel); this.buttonBgs.push(buttonBg); @@ -95,7 +95,7 @@ export abstract class ModalUiHandler extends UiHandler { if (args[0].hasOwnProperty("fadeOut") && typeof args[0].fadeOut === "function") { const [ marginTop, marginRight, marginBottom, marginLeft ] = this.getMargin(); - const overlay = gScene.add.rectangle(( this.getWidth() + marginLeft + marginRight) / 2, (this.getHeight() + marginTop + marginBottom) / 2, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0); + const overlay = globalScene.add.rectangle(( this.getWidth() + marginLeft + marginRight) / 2, (this.getHeight() + marginTop + marginBottom) / 2, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6, 0); overlay.setOrigin(0.5, 0.5); overlay.setName("rect-ui-overlay-modal"); overlay.setAlpha(0); @@ -103,7 +103,7 @@ export abstract class ModalUiHandler extends UiHandler { this.modalContainer.add(overlay); this.modalContainer.moveTo(overlay, 0); - gScene.tweens.add({ + globalScene.tweens.add({ targets: overlay, alpha: 1, duration: 250, @@ -136,7 +136,7 @@ export abstract class ModalUiHandler extends UiHandler { const [ marginTop, marginRight, marginBottom, marginLeft ] = this.getMargin(config); const [ width, height ] = [ this.getWidth(config), this.getHeight(config) ]; - this.modalContainer.setPosition((((gScene.game.canvas.width / 6) - (width + (marginRight - marginLeft))) / 2), (((-gScene.game.canvas.height / 6) - (height + (marginBottom - marginTop))) / 2)); + this.modalContainer.setPosition((((globalScene.game.canvas.width / 6) - (width + (marginRight - marginLeft))) / 2), (((-globalScene.game.canvas.height / 6) - (height + (marginBottom - marginTop))) / 2)); this.modalBg.setSize(width, height); diff --git a/src/ui/modifier-select-ui-handler.ts b/src/ui/modifier-select-ui-handler.ts index b9c95f7f5d6..09e12d136a1 100644 --- a/src/ui/modifier-select-ui-handler.ts +++ b/src/ui/modifier-select-ui-handler.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { getPlayerShopModifierTypeOptionsForWave, ModifierTypeOption, TmModifierType } from "../modifier/modifier-type"; import { getPokeballAtlasKey, PokeballType } from "../data/pokeball"; import { addTextObject, getTextStyleOptions, getModifierTierTextTint, getTextColor, TextStyle } from "./text"; @@ -58,12 +58,12 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { setup() { const ui = this.getUi(); - this.modifierContainer = gScene.add.container(0, 0); + this.modifierContainer = globalScene.add.container(0, 0); ui.add(this.modifierContainer); const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); - const styleOptions = getTextStyleOptions(TextStyle.PARTY, gScene.uiTheme).styleOptions; + const styleOptions = getTextStyleOptions(TextStyle.PARTY, globalScene.uiTheme).styleOptions; if (context) { context.font = styleOptions.fontSize + "px " + styleOptions.fontFamily; @@ -71,7 +71,7 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { this.checkButtonWidth = context.measureText(i18next.t("modifierSelectUiHandler:checkTeam")).width; } - this.transferButtonContainer = gScene.add.container((gScene.game.canvas.width - this.checkButtonWidth) / 6 - 21, OPTION_BUTTON_YPOSITION); + this.transferButtonContainer = globalScene.add.container((globalScene.game.canvas.width - this.checkButtonWidth) / 6 - 21, OPTION_BUTTON_YPOSITION); this.transferButtonContainer.setName("transfer-btn"); this.transferButtonContainer.setVisible(false); ui.add(this.transferButtonContainer); @@ -81,7 +81,7 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { transferButtonText.setOrigin(1, 0); this.transferButtonContainer.add(transferButtonText); - this.checkButtonContainer = gScene.add.container((gScene.game.canvas.width) / 6 - 1, OPTION_BUTTON_YPOSITION); + this.checkButtonContainer = globalScene.add.container((globalScene.game.canvas.width) / 6 - 1, OPTION_BUTTON_YPOSITION); this.checkButtonContainer.setName("use-btn"); this.checkButtonContainer.setVisible(false); ui.add(this.checkButtonContainer); @@ -91,7 +91,7 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { checkButtonText.setOrigin(1, 0); this.checkButtonContainer.add(checkButtonText); - this.rerollButtonContainer = gScene.add.container(16, OPTION_BUTTON_YPOSITION); + this.rerollButtonContainer = globalScene.add.container(16, OPTION_BUTTON_YPOSITION); this.rerollButtonContainer.setName("reroll-brn"); this.rerollButtonContainer.setVisible(false); ui.add(this.rerollButtonContainer); @@ -107,7 +107,7 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { this.rerollCostText.setPositionRelative(rerollButtonText, rerollButtonText.displayWidth + 5, 1); this.rerollButtonContainer.add(this.rerollCostText); - this.lockRarityButtonContainer = gScene.add.container(16, OPTION_BUTTON_YPOSITION); + this.lockRarityButtonContainer = globalScene.add.container(16, OPTION_BUTTON_YPOSITION); this.lockRarityButtonContainer.setVisible(false); ui.add(this.lockRarityButtonContainer); @@ -115,7 +115,7 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { this.lockRarityButtonText.setOrigin(0, 0); this.lockRarityButtonContainer.add(this.lockRarityButtonText); - this.continueButtonContainer = gScene.add.container((gScene.game.canvas.width / 12), -(gScene.game.canvas.height / 12)); + this.continueButtonContainer = globalScene.add.container((globalScene.game.canvas.width / 12), -(globalScene.game.canvas.height / 12)); this.continueButtonContainer.setVisible(false); ui.add(this.continueButtonContainer); @@ -133,16 +133,16 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { right: true, x: 1, y: -MoveInfoOverlay.getHeight(overlayScale, true) - 1, - width: (gScene.game.canvas.width / 6) - 2, + width: (globalScene.game.canvas.width / 6) - 2, }); ui.add(this.moveInfoOverlay); // register the overlay to receive toggle events - gScene.addInfoToggle(this.moveInfoOverlay); + globalScene.addInfoToggle(this.moveInfoOverlay); } show(args: any[]): boolean { - gScene.disableMenu = false; + globalScene.disableMenu = false; if (this.active) { if (args.length >= 3) { @@ -163,8 +163,8 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { this.player = args[0]; - const partyHasHeldItem = this.player && !!gScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.isTransferable).length; - const canLockRarities = !!gScene.findModifier(m => m instanceof LockModifierTiersModifier); + const partyHasHeldItem = this.player && !!globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.isTransferable).length; + const canLockRarities = !!globalScene.findModifier(m => m instanceof LockModifierTiersModifier); this.transferButtonContainer.setVisible(false); this.transferButtonContainer.setAlpha(0); @@ -188,19 +188,19 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { this.updateRerollCostText(); const typeOptions = args[1] as ModifierTypeOption[]; - const removeHealShop = gScene.gameMode.hasNoShop; - const baseShopCost = new IntegerHolder(gScene.getWaveMoneyAmount(1)); - gScene.applyModifier(HealShopCostModifier, true, baseShopCost); + const removeHealShop = globalScene.gameMode.hasNoShop; + const baseShopCost = new IntegerHolder(globalScene.getWaveMoneyAmount(1)); + globalScene.applyModifier(HealShopCostModifier, true, baseShopCost); const shopTypeOptions = !removeHealShop - ? getPlayerShopModifierTypeOptionsForWave(gScene.currentBattle.waveIndex, baseShopCost.value) + ? getPlayerShopModifierTypeOptionsForWave(globalScene.currentBattle.waveIndex, baseShopCost.value) : []; const optionsYOffset = shopTypeOptions.length > SHOP_OPTIONS_ROW_LIMIT ? -SINGLE_SHOP_ROW_YOFFSET : -DOUBLE_SHOP_ROW_YOFFSET; for (let m = 0; m < typeOptions.length; m++) { - const sliceWidth = (gScene.game.canvas.width / 6) / (typeOptions.length + 2); - const option = new ModifierOption(sliceWidth * (m + 1) + (sliceWidth * 0.5), -gScene.game.canvas.height / 12 + optionsYOffset, typeOptions[m]); + const sliceWidth = (globalScene.game.canvas.width / 6) / (typeOptions.length + 2); + const option = new ModifierOption(sliceWidth * (m + 1) + (sliceWidth * 0.5), -globalScene.game.canvas.height / 12 + optionsYOffset, typeOptions[m]); option.setScale(0.5); - gScene.add.existing(option); + globalScene.add.existing(option); this.modifierContainer.add(option); this.options.push(option); } @@ -214,10 +214,10 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { const row = m < SHOP_OPTIONS_ROW_LIMIT ? 0 : 1; const col = m < SHOP_OPTIONS_ROW_LIMIT ? m : m - SHOP_OPTIONS_ROW_LIMIT; const rowOptions = shopTypeOptions.slice(row ? SHOP_OPTIONS_ROW_LIMIT : 0, row ? undefined : SHOP_OPTIONS_ROW_LIMIT); - const sliceWidth = (gScene.game.canvas.width / 6) / (rowOptions.length + 2); - const option = new ModifierOption(sliceWidth * (col + 1) + (sliceWidth * 0.5), ((-gScene.game.canvas.height / 12) - (gScene.game.canvas.height / 32) - (42 - (28 * row - 1))), shopTypeOptions[m]); + const sliceWidth = (globalScene.game.canvas.width / 6) / (rowOptions.length + 2); + const option = new ModifierOption(sliceWidth * (col + 1) + (sliceWidth * 0.5), ((-globalScene.game.canvas.height / 12) - (globalScene.game.canvas.height / 32) - (42 - (28 * row - 1))), shopTypeOptions[m]); option.setScale(0.375); - gScene.add.existing(option); + globalScene.add.existing(option); this.modifierContainer.add(option); if (row >= this.shopOptionsRows.length) { @@ -229,17 +229,17 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { const maxUpgradeCount = typeOptions.map(to => to.upgradeCount).reduce((max, current) => Math.max(current, max), 0); /* Force updateModifiers without pokemonSpecificModifiers */ - gScene.getModifierBar().updateModifiers(gScene.modifiers, true); + globalScene.getModifierBar().updateModifiers(globalScene.modifiers, true); /* Multiplies the appearance duration by the speed parameter so that it is always constant, and avoids "flashbangs" at game speed x5 */ - gScene.showShopOverlay(750 * gScene.gameSpeed); - gScene.updateAndShowText(750); - gScene.updateBiomeWaveText(); - gScene.updateMoneyText(); + globalScene.showShopOverlay(750 * globalScene.gameSpeed); + globalScene.updateAndShowText(750); + globalScene.updateBiomeWaveText(); + globalScene.updateMoneyText(); let i = 0; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ ease: "Sine.easeIn", duration: 1250, onUpdate: t => { @@ -253,17 +253,17 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { } }); - gScene.time.delayedCall(1000 + maxUpgradeCount * 2000, () => { + globalScene.time.delayedCall(1000 + maxUpgradeCount * 2000, () => { for (const shopOption of this.shopOptionsRows.flat()) { shopOption.show(0, 0); } }); - gScene.time.delayedCall(4000 + maxUpgradeCount * 2000, () => { + globalScene.time.delayedCall(4000 + maxUpgradeCount * 2000, () => { if (partyHasHeldItem) { this.transferButtonContainer.setAlpha(0); this.transferButtonContainer.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.transferButtonContainer, alpha: 1, duration: 250 @@ -279,27 +279,27 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { this.continueButtonContainer.setVisible(this.rerollCost < 0); this.lockRarityButtonContainer.setVisible(canLockRarities); - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.checkButtonContainer, this.continueButtonContainer ], alpha: 1, duration: 250 }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.rerollButtonContainer, this.lockRarityButtonContainer ], alpha: this.rerollCost < 0 ? 0.5 : 1, duration: 250 }); const updateCursorTarget = () => { - if (gScene.shopCursorTarget === ShopCursorTarget.CHECK_TEAM) { + if (globalScene.shopCursorTarget === ShopCursorTarget.CHECK_TEAM) { this.setRowCursor(0); this.setCursor(2); - } else if ((gScene.shopCursorTarget === ShopCursorTarget.SHOP) && gScene.gameMode.hasNoShop) { + } else if ((globalScene.shopCursorTarget === ShopCursorTarget.SHOP) && globalScene.gameMode.hasNoShop) { this.setRowCursor(ShopCursorTarget.REWARDS); this.setCursor(0); } else { - this.setRowCursor(gScene.shopCursorTarget); + this.setRowCursor(globalScene.shopCursorTarget); this.setCursor(0); } }; @@ -445,7 +445,7 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { const ret = super.setCursor(cursor); if (!this.cursorObj) { - this.cursorObj = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.image(0, 0, "cursor"); this.modifierContainer.add(this.cursorObj); } @@ -459,18 +459,18 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { if (this.rowCursor === 1 && options.length === 0) { // Continue button when no shop items this.cursorObj.setScale(1.25); - this.cursorObj.setPosition((gScene.game.canvas.width / 18) + 23, (-gScene.game.canvas.height / 12) - (this.shopOptionsRows.length > 1 ? SINGLE_SHOP_ROW_YOFFSET - 2 : DOUBLE_SHOP_ROW_YOFFSET - 2)); + this.cursorObj.setPosition((globalScene.game.canvas.width / 18) + 23, (-globalScene.game.canvas.height / 12) - (this.shopOptionsRows.length > 1 ? SINGLE_SHOP_ROW_YOFFSET - 2 : DOUBLE_SHOP_ROW_YOFFSET - 2)); ui.showText(i18next.t("modifierSelectUiHandler:continueNextWaveDescription")); return ret; } - const sliceWidth = (gScene.game.canvas.width / 6) / (options.length + 2); + const sliceWidth = (globalScene.game.canvas.width / 6) / (options.length + 2); if (this.rowCursor < 2) { // Cursor on free items - this.cursorObj.setPosition(sliceWidth * (cursor + 1) + (sliceWidth * 0.5) - 20, (-gScene.game.canvas.height / 12) - (this.shopOptionsRows.length > 1 ? SINGLE_SHOP_ROW_YOFFSET - 2 : DOUBLE_SHOP_ROW_YOFFSET - 2)); + this.cursorObj.setPosition(sliceWidth * (cursor + 1) + (sliceWidth * 0.5) - 20, (-globalScene.game.canvas.height / 12) - (this.shopOptionsRows.length > 1 ? SINGLE_SHOP_ROW_YOFFSET - 2 : DOUBLE_SHOP_ROW_YOFFSET - 2)); } else { // Cursor on paying items - this.cursorObj.setPosition(sliceWidth * (cursor + 1) + (sliceWidth * 0.5) - 16, (-gScene.game.canvas.height / 12 - gScene.game.canvas.height / 32) - (-14 + 28 * (this.rowCursor - (this.shopOptionsRows.length - 1)))); + this.cursorObj.setPosition(sliceWidth * (cursor + 1) + (sliceWidth * 0.5) - 16, (-globalScene.game.canvas.height / 12 - globalScene.game.canvas.height / 32) - (-14 + 28 * (this.rowCursor - (this.shopOptionsRows.length - 1)))); } const type = options[this.cursor].modifierTypeOption.type; @@ -483,10 +483,10 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { this.cursorObj.setPosition(6, this.lockRarityButtonContainer.visible ? OPTION_BUTTON_YPOSITION - 8 : OPTION_BUTTON_YPOSITION + 4); ui.showText(i18next.t("modifierSelectUiHandler:rerollDesc")); } else if (cursor === 1) { - this.cursorObj.setPosition((gScene.game.canvas.width - this.transferButtonWidth - this.checkButtonWidth) / 6 - 30, OPTION_BUTTON_YPOSITION + 4); + this.cursorObj.setPosition((globalScene.game.canvas.width - this.transferButtonWidth - this.checkButtonWidth) / 6 - 30, OPTION_BUTTON_YPOSITION + 4); ui.showText(i18next.t("modifierSelectUiHandler:transferDesc")); } else if (cursor === 2) { - this.cursorObj.setPosition((gScene.game.canvas.width - this.checkButtonWidth) / 6 - 10, OPTION_BUTTON_YPOSITION + 4); + this.cursorObj.setPosition((globalScene.game.canvas.width - this.checkButtonWidth) / 6 - 10, OPTION_BUTTON_YPOSITION + 4); ui.showText(i18next.t("modifierSelectUiHandler:checkTeamDesc")); } else { this.cursorObj.setPosition(6, OPTION_BUTTON_YPOSITION + 4); @@ -557,9 +557,9 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { } else { this.rerollCostText.setVisible(true); } - const canReroll = gScene.money >= this.rerollCost; + const canReroll = globalScene.money >= this.rerollCost; - const formattedMoney = Utils.formatMoney(gScene.moneyFormat, this.rerollCost); + const formattedMoney = Utils.formatMoney(globalScene.moneyFormat, this.rerollCost); this.rerollCostText.setText(i18next.t("modifierSelectUiHandler:rerollCost", { formattedMoney })); this.rerollCostText.setColor(this.getTextColor(canReroll ? TextStyle.MONEY : TextStyle.PARTY_RED)); @@ -567,7 +567,7 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { } updateLockRaritiesText(): void { - const textStyle = gScene.lockModifierTiers ? TextStyle.SUMMARY_BLUE : TextStyle.PARTY; + const textStyle = globalScene.lockModifierTiers ? TextStyle.SUMMARY_BLUE : TextStyle.PARTY; this.lockRarityButtonText.setColor(this.getTextColor(textStyle)); this.lockRarityButtonText.setShadowColor(this.getTextColor(textStyle, true)); } @@ -587,17 +587,17 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { this.rowCursor = 0; /* Multiplies the fade time duration by the speed parameter so that it is always constant, and avoids "flashbangs" at game speed x5 */ - gScene.hideShopOverlay(750 * gScene.gameSpeed); - gScene.hideLuckText(250); + globalScene.hideShopOverlay(750 * globalScene.gameSpeed); + globalScene.hideLuckText(250); /* Normally already called just after the shop, but not sure if it happens in 100% of cases */ - gScene.getModifierBar().updateModifiers(gScene.modifiers); + globalScene.getModifierBar().updateModifiers(globalScene.modifiers); const options = this.options.concat(this.shopOptionsRows.flat()); this.options.splice(0, this.options.length); this.shopOptionsRows.splice(0, this.shopOptionsRows.length); - gScene.tweens.add({ + globalScene.tweens.add({ targets: options, scale: 0.01, duration: 250, @@ -607,7 +607,7 @@ export default class ModifierSelectUiHandler extends AwaitableUiHandler { [ this.rerollButtonContainer, this.checkButtonContainer, this.transferButtonContainer, this.lockRarityButtonContainer, this.continueButtonContainer ].forEach(container => { if (container.visible) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: container, alpha: 0, duration: 250, @@ -643,7 +643,7 @@ class ModifierOption extends Phaser.GameObjects.Container { private itemCostText: Phaser.GameObjects.Text; constructor(x: number, y: number, modifierTypeOption: ModifierTypeOption) { - super(gScene, x, y); + super(globalScene, x, y); this.modifierTypeOption = modifierTypeOption; @@ -653,7 +653,7 @@ class ModifierOption extends Phaser.GameObjects.Container { setup() { if (!this.modifierTypeOption.cost) { const getPb = (): Phaser.GameObjects.Sprite => { - const pb = gScene.add.sprite(0, -182, "pb", this.getPbAtlasKey(-this.modifierTypeOption.upgradeCount)); + const pb = globalScene.add.sprite(0, -182, "pb", this.getPbAtlasKey(-this.modifierTypeOption.upgradeCount)); pb.setScale(2); return pb; }; @@ -666,13 +666,13 @@ class ModifierOption extends Phaser.GameObjects.Container { this.add(this.pbTint); } - this.itemContainer = gScene.add.container(0, 0); + this.itemContainer = globalScene.add.container(0, 0); this.itemContainer.setScale(0.5); this.itemContainer.setAlpha(0); this.add(this.itemContainer); const getItem = () => { - const item = gScene.add.sprite(0, 0, "items", this.modifierTypeOption.type?.iconImage); + const item = globalScene.add.sprite(0, 0, "items", this.modifierTypeOption.type?.iconImage); return item; }; @@ -704,7 +704,7 @@ class ModifierOption extends Phaser.GameObjects.Container { show(remainingDuration: integer, upgradeCountOffset: integer) { if (!this.modifierTypeOption.cost) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pb, y: 0, duration: 1250, @@ -715,18 +715,18 @@ class ModifierOption extends Phaser.GameObjects.Container { let bounceCount = 0; let bounce = false; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ from: 1, to: 0, duration: 1250, ease: "Bounce.Out", onUpdate: t => { - if (!gScene) { + if (!globalScene) { return; } const value = t.getValue(); if (!bounce && value > lastValue) { - gScene.playSound("se/pb_bounce_1", { volume: 1 / ++bounceCount }); + globalScene.playSound("se/pb_bounce_1", { volume: 1 / ++bounceCount }); bounce = true; } else if (bounce && value < lastValue) { bounce = false; @@ -737,20 +737,20 @@ class ModifierOption extends Phaser.GameObjects.Container { for (let u = 0; u < this.modifierTypeOption.upgradeCount; u++) { const upgradeIndex = u; - gScene.time.delayedCall(remainingDuration - 2000 * (this.modifierTypeOption.upgradeCount - (upgradeIndex + 1 + upgradeCountOffset)), () => { - gScene.playSound("se/upgrade", { rate: 1 + 0.25 * upgradeIndex }); + globalScene.time.delayedCall(remainingDuration - 2000 * (this.modifierTypeOption.upgradeCount - (upgradeIndex + 1 + upgradeCountOffset)), () => { + globalScene.playSound("se/upgrade", { rate: 1 + 0.25 * upgradeIndex }); this.pbTint.setPosition(this.pb.x, this.pb.y); this.pbTint.setTintFill(0xFFFFFF); this.pbTint.setAlpha(0); this.pbTint.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pbTint, alpha: 1, duration: 1000, ease: "Sine.easeIn", onComplete: () => { this.pb.setTexture("pb", this.getPbAtlasKey(-this.modifierTypeOption.upgradeCount + (upgradeIndex + 1))); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pbTint, alpha: 0, duration: 750, @@ -765,16 +765,16 @@ class ModifierOption extends Phaser.GameObjects.Container { } } - gScene.time.delayedCall(remainingDuration + 2000, () => { - if (!gScene) { + globalScene.time.delayedCall(remainingDuration + 2000, () => { + if (!globalScene) { return; } if (!this.modifierTypeOption.cost) { this.pb.setTexture("pb", `${this.getPbAtlasKey(0)}_open`); - gScene.playSound("se/pb_rel"); + globalScene.playSound("se/pb_rel"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pb, duration: 500, delay: 250, @@ -784,7 +784,7 @@ class ModifierOption extends Phaser.GameObjects.Container { }); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.itemContainer, duration: 500, ease: "Elastic.Out", @@ -792,7 +792,7 @@ class ModifierOption extends Phaser.GameObjects.Container { alpha: 1 }); if (!this.modifierTypeOption.cost) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.itemTint, alpha: 0, duration: 500, @@ -800,7 +800,7 @@ class ModifierOption extends Phaser.GameObjects.Container { onComplete: () => this.itemTint.destroy() }); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.itemText, duration: 500, alpha: 1, @@ -808,7 +808,7 @@ class ModifierOption extends Phaser.GameObjects.Container { ease: "Cubic.easeInOut" }); if (this.itemCostText) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.itemCostText, duration: 500, alpha: 1, @@ -825,12 +825,12 @@ class ModifierOption extends Phaser.GameObjects.Container { updateCostText(): void { const cost = Overrides.WAIVE_ROLL_FEE_OVERRIDE ? 0 : this.modifierTypeOption.cost; - const textStyle = cost <= gScene.money ? TextStyle.MONEY : TextStyle.PARTY_RED; + const textStyle = cost <= globalScene.money ? TextStyle.MONEY : TextStyle.PARTY_RED; - const formattedMoney = Utils.formatMoney(gScene.moneyFormat, cost); + const formattedMoney = Utils.formatMoney(globalScene.moneyFormat, cost); this.itemCostText.setText(i18next.t("modifierSelectUiHandler:itemCost", { formattedMoney })); - this.itemCostText.setColor(getTextColor(textStyle, false, gScene.uiTheme)); - this.itemCostText.setShadowColor(getTextColor(textStyle, true, gScene.uiTheme)); + this.itemCostText.setColor(getTextColor(textStyle, false, globalScene.uiTheme)); + this.itemCostText.setShadowColor(getTextColor(textStyle, true, globalScene.uiTheme)); } } diff --git a/src/ui/move-info-overlay.ts b/src/ui/move-info-overlay.ts index fc4c5bb1365..32f22f2ec86 100644 --- a/src/ui/move-info-overlay.ts +++ b/src/ui/move-info-overlay.ts @@ -1,4 +1,4 @@ -import { gScene, InfoToggle } from "#app/battle-scene"; +import { globalScene, InfoToggle } from "#app/battle-scene"; import { TextStyle, addTextObject } from "./text"; import { addWindow } from "./ui-theme"; import * as Utils from "../utils"; @@ -50,7 +50,7 @@ export default class MoveInfoOverlay extends Phaser.GameObjects.Container implem if (options?.onSide) { options.top = false; } - super(gScene, options?.x, options?.y); + super(globalScene, options?.x, options?.y); const scale = options?.scale || 1; // set up the scale this.setScale(scale); this.options = options || {}; @@ -71,13 +71,13 @@ export default class MoveInfoOverlay extends Phaser.GameObjects.Container implem y: (options?.y || 0), }; if (maskPointOrigin.x < 0) { - maskPointOrigin.x += gScene.game.canvas.width / GLOBAL_SCALE; + maskPointOrigin.x += globalScene.game.canvas.width / GLOBAL_SCALE; } if (maskPointOrigin.y < 0) { - maskPointOrigin.y += gScene.game.canvas.height / GLOBAL_SCALE; + maskPointOrigin.y += globalScene.game.canvas.height / GLOBAL_SCALE; } - const moveDescriptionTextMaskRect = gScene.make.graphics(); + const moveDescriptionTextMaskRect = globalScene.make.graphics(); moveDescriptionTextMaskRect.fillStyle(0xFF0000); moveDescriptionTextMaskRect.fillRect( maskPointOrigin.x + ((options?.onSide && !options?.right ? EFF_WIDTH : 0) + BORDER) * scale, maskPointOrigin.y + ((options?.top ? EFF_HEIGHT : 0) + BORDER - 2) * scale, @@ -89,18 +89,18 @@ export default class MoveInfoOverlay extends Phaser.GameObjects.Container implem this.desc.setMask(moveDescriptionTextMask); // prepare the effect box - this.val = new Phaser.GameObjects.Container(gScene, options?.right ? width - EFF_WIDTH : 0, options?.top || options?.onSide ? 0 : DESC_HEIGHT); + this.val = new Phaser.GameObjects.Container(globalScene, options?.right ? width - EFF_WIDTH : 0, options?.top || options?.onSide ? 0 : DESC_HEIGHT); this.add(this.val); const valuesBg = addWindow(0, 0, EFF_WIDTH, EFF_HEIGHT); valuesBg.setOrigin(0, 0); this.val.add(valuesBg); - this.typ = gScene.add.sprite(25, EFF_HEIGHT - 35, Utils.getLocalizedSpriteKey("types"), "unknown"); + this.typ = globalScene.add.sprite(25, EFF_HEIGHT - 35, Utils.getLocalizedSpriteKey("types"), "unknown"); this.typ.setScale(0.8); this.val.add(this.typ); - this.cat = gScene.add.sprite(57, EFF_HEIGHT - 35, "categories", "physical"); + this.cat = globalScene.add.sprite(57, EFF_HEIGHT - 35, "categories", "physical"); this.val.add(this.cat); const ppTxt = addTextObject(12, EFF_HEIGHT - 25, "PP", TextStyle.MOVE_INFO_CONTENT); @@ -144,7 +144,7 @@ export default class MoveInfoOverlay extends Phaser.GameObjects.Container implem // show this component with infos for the specific move show(move : Move):boolean { - if (!gScene.enableMoveInfo) { + if (!globalScene.enableMoveInfo) { return false; // move infos have been disabled // TODO:: is `false` correct? i used to be `undeefined` } this.move = move; @@ -167,7 +167,7 @@ export default class MoveInfoOverlay extends Phaser.GameObjects.Container implem const moveDescriptionLineCount = Math.floor(this.desc.displayHeight * (96 / 72) / 14.83); if (moveDescriptionLineCount > 3) { // generate scrolling effects - this.descScroll = gScene.tweens.add({ + this.descScroll = globalScene.tweens.add({ targets: this.desc, delay: Utils.fixedInt(2000), loop: -1, @@ -193,7 +193,7 @@ export default class MoveInfoOverlay extends Phaser.GameObjects.Container implem if (visible) { this.setVisible(true); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.desc, duration: Utils.fixedInt(125), ease: "Sine.easeInOut", @@ -210,7 +210,7 @@ export default class MoveInfoOverlay extends Phaser.GameObjects.Container implem // width of this element static getWidth(scale:number):number { - return gScene.game.canvas.width / GLOBAL_SCALE / 2; + return globalScene.game.canvas.width / GLOBAL_SCALE / 2; } // height of this element diff --git a/src/ui/mystery-encounter-ui-handler.ts b/src/ui/mystery-encounter-ui-handler.ts index 3c0b1e49a68..7e219515ba9 100644 --- a/src/ui/mystery-encounter-ui-handler.ts +++ b/src/ui/mystery-encounter-ui-handler.ts @@ -15,7 +15,7 @@ import i18next from "i18next"; import { MysteryEncounterOptionMode } from "#enums/mystery-encounter-option-mode"; import { MysteryEncounterTier } from "#enums/mystery-encounter-tier"; import BBCodeText from "phaser3-rex-plugins/plugins/bbcodetext"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class MysteryEncounterUiHandler extends UiHandler { private cursorContainer: Phaser.GameObjects.Container; @@ -54,19 +54,19 @@ export default class MysteryEncounterUiHandler extends UiHandler { override setup() { const ui = this.getUi(); - this.cursorContainer = gScene.add.container(18, -38.7); + this.cursorContainer = globalScene.add.container(18, -38.7); this.cursorContainer.setVisible(false); ui.add(this.cursorContainer); - this.optionsContainer = gScene.add.container(12, -38.7); + this.optionsContainer = globalScene.add.container(12, -38.7); this.optionsContainer.setVisible(false); ui.add(this.optionsContainer); - this.dexProgressContainer = gScene.add.container(214, -43); + this.dexProgressContainer = globalScene.add.container(214, -43); this.dexProgressContainer.setVisible(false); ui.add(this.dexProgressContainer); - this.descriptionContainer = gScene.add.container(0, -152); + this.descriptionContainer = globalScene.add.container(0, -152); this.descriptionContainer.setVisible(false); ui.add(this.descriptionContainer); - this.tooltipContainer = gScene.add.container(210, -48); + this.tooltipContainer = globalScene.add.container(210, -48); this.tooltipContainer.setVisible(false); ui.add(this.tooltipContainer); @@ -81,11 +81,11 @@ export default class MysteryEncounterUiHandler extends UiHandler { this.dexProgressWindow = addWindow(0, 0, 24, 28, false, false, 0, 0, WindowVariant.THIN); this.dexProgressContainer.add(this.dexProgressWindow); - this.rarityBall = gScene.add.sprite(141, 9, "pb"); + this.rarityBall = globalScene.add.sprite(141, 9, "pb"); this.rarityBall.setScale(0.75); this.descriptionContainer.add(this.rarityBall); - const dexProgressIndicator = gScene.add.sprite(12, 10, "encounter_radar"); + const dexProgressIndicator = globalScene.add.sprite(12, 10, "encounter_radar"); dexProgressIndicator.setScale(0.80); this.dexProgressContainer.add(dexProgressIndicator); this.dexProgressContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, 24, 28), Phaser.Geom.Rectangle.Contains); @@ -138,8 +138,8 @@ export default class MysteryEncounterUiHandler extends UiHandler { ...this.overrideSettings, slideInDescription: false }; - gScene.ui.setMode(Mode.PARTY, PartyUiMode.CHECK, -1, () => { - gScene.ui.setMode(Mode.MYSTERY_ENCOUNTER, overrideSettings); + globalScene.ui.setMode(Mode.PARTY, PartyUiMode.CHECK, -1, () => { + globalScene.ui.setMode(Mode.MYSTERY_ENCOUNTER, overrideSettings); setTimeout(() => { this.setCursor(this.viewPartyIndex); this.unblockInput(); @@ -148,7 +148,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { } else if (this.blockInput || (!this.optionsMeetsReqs[cursor] && (selected.optionMode === MysteryEncounterOptionMode.DISABLED_OR_DEFAULT || selected.optionMode === MysteryEncounterOptionMode.DISABLED_OR_SPECIAL))) { success = false; } else { - if ((gScene.getCurrentPhase() as MysteryEncounterPhase).handleOptionSelect(selected, cursor)) { + if ((globalScene.getCurrentPhase() as MysteryEncounterPhase).handleOptionSelect(selected, cursor)) { success = true; } else { ui.playError(); @@ -315,7 +315,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { this.viewPartyIndex = this.optionsContainer.getAll()?.length - 1; if (!this.cursorObj) { - this.cursorObj = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.image(0, 0, "cursor"); this.cursorContainer.add(this.cursorObj); } @@ -334,7 +334,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { displayEncounterOptions(slideInDescription: boolean = true): void { this.getUi().clearText(); - const mysteryEncounter = gScene.currentBattle.mysteryEncounter!; + const mysteryEncounter = globalScene.currentBattle.mysteryEncounter!; this.encounterOptions = this.overrideSettings?.overrideOptions ?? mysteryEncounter.options; this.optionsMeetsReqs = []; @@ -387,7 +387,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { // Sets up the mask that hides the option text to give an illusion of scrolling const nonScrollWidth = 90; - const optionTextMaskRect = gScene.make.graphics({}); + const optionTextMaskRect = globalScene.make.graphics({}); optionTextMaskRect.setScale(6); optionTextMaskRect.fillStyle(0xFFFFFF); optionTextMaskRect.beginPath(); @@ -406,7 +406,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { // Animates the option text scrolling sideways if (optionTextWidth > nonScrollWidth) { - this.optionScrollTweens[i] = gScene.tweens.add({ + this.optionScrollTweens[i] = globalScene.tweens.add({ targets: optionText, delay: Utils.fixedInt(2000), loop: -1, @@ -420,7 +420,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { } // View Party Button - const viewPartyText = addBBCodeTextObject((gScene.game.canvas.width) / 6, -24, getBBCodeFrag(i18next.t("mysteryEncounterMessages:view_party_button"), TextStyle.PARTY), TextStyle.PARTY); + const viewPartyText = addBBCodeTextObject((globalScene.game.canvas.width) / 6, -24, getBBCodeFrag(i18next.t("mysteryEncounterMessages:view_party_button"), TextStyle.PARTY), TextStyle.PARTY); this.optionsContainer.add(viewPartyText); viewPartyText.x -= (viewPartyText.displayWidth + 16); this.viewPartyXPosition = viewPartyText.x - 10; @@ -441,7 +441,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { const descriptionTextObject = addBBCodeTextObject(6, 25, descriptionText ?? "", TextStyle.TOOLTIP_CONTENT, { wordWrap: { width: 830 }}); // Sets up the mask that hides the description text to give an illusion of scrolling - const descriptionTextMaskRect = gScene.make.graphics({}); + const descriptionTextMaskRect = globalScene.make.graphics({}); descriptionTextMaskRect.setScale(6); descriptionTextMaskRect.fillStyle(0xFFFFFF); descriptionTextMaskRect.beginPath(); @@ -460,7 +460,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { // Animates the description text moving upwards if (descriptionLineCount > 6) { - this.descriptionScrollTween = gScene.tweens.add({ + this.descriptionScrollTween = globalScene.tweens.add({ targets: descriptionTextObject, delay: Utils.fixedInt(2000), loop: -1, @@ -479,7 +479,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { // Slide in description container if (slideInDescription) { this.descriptionContainer.x -= 150; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.descriptionContainer, x: "+=150", ease: "Sine.easeInOut", @@ -528,7 +528,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { this.tooltipContainer.add(tooltipTextObject); // Sets up the mask that hides the description text to give an illusion of scrolling - const tooltipTextMaskRect = gScene.make.graphics({}); + const tooltipTextMaskRect = globalScene.make.graphics({}); tooltipTextMaskRect.setScale(6); tooltipTextMaskRect.fillStyle(0xFFFFFF); tooltipTextMaskRect.beginPath(); @@ -546,7 +546,7 @@ export default class MysteryEncounterUiHandler extends UiHandler { // Animates the tooltip text moving upwards if (tooltipLineCount > 3) { - this.tooltipScrollTween = gScene.tweens.add({ + this.tooltipScrollTween = globalScene.tweens.add({ targets: tooltipTextObject, delay: Utils.fixedInt(1200), loop: -1, @@ -593,25 +593,25 @@ export default class MysteryEncounterUiHandler extends UiHandler { private showHideDexProgress(show: boolean) { if (show && !this.showDexProgress) { this.showDexProgress = true; - gScene.tweens.killTweensOf(this.dexProgressContainer); - gScene.tweens.add({ + globalScene.tweens.killTweensOf(this.dexProgressContainer); + globalScene.tweens.add({ targets: this.dexProgressContainer, y: -63, ease: "Sine.easeInOut", duration: 750, onComplete: () => { this.dexProgressContainer.on("pointerover", () => { - gScene.ui.showTooltip("", i18next.t("mysteryEncounterMessages:affects_pokedex"), true); + globalScene.ui.showTooltip("", i18next.t("mysteryEncounterMessages:affects_pokedex"), true); }); this.dexProgressContainer.on("pointerout", () => { - gScene.ui.hideTooltip(); + globalScene.ui.hideTooltip(); }); } }); } else if (!show && this.showDexProgress) { this.showDexProgress = false; - gScene.tweens.killTweensOf(this.dexProgressContainer); - gScene.tweens.add({ + globalScene.tweens.killTweensOf(this.dexProgressContainer); + globalScene.tweens.add({ targets: this.dexProgressContainer, y: -43, ease: "Sine.easeInOut", diff --git a/src/ui/party-exp-bar.ts b/src/ui/party-exp-bar.ts index e1d5e6dc9ba..f892b0f9b7e 100644 --- a/src/ui/party-exp-bar.ts +++ b/src/ui/party-exp-bar.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import Pokemon from "../field/pokemon"; import { TextStyle, addTextObject } from "./text"; @@ -12,11 +12,11 @@ export default class PartyExpBar extends Phaser.GameObjects.Container { public shown: boolean; constructor() { - super(gScene, (gScene.game.canvas.width / 6), -((gScene.game.canvas.height) / 6) + 15); + super(globalScene, (globalScene.game.canvas.width / 6), -((globalScene.game.canvas.height) / 6) + 15); } setup(): void { - this.bg = gScene.add.nineslice(0, 0, "party_exp_bar", undefined, 8, 18, 21, 5, 6, 4); + this.bg = globalScene.add.nineslice(0, 0, "party_exp_bar", undefined, 8, 18, 21, 5, 6, 4); this.bg.setOrigin(0, 0); this.add(this.bg); @@ -35,7 +35,7 @@ export default class PartyExpBar extends Phaser.GameObjects.Container { return resolve(); } - this.pokemonIcon = gScene.addPokemonIcon(pokemon, -8, 15, 0, 0.5); + this.pokemonIcon = globalScene.addPokemonIcon(pokemon, -8, 15, 0, 0.5); this.pokemonIcon.setScale(0.5); this.add(this.pokemonIcon); @@ -54,16 +54,16 @@ export default class PartyExpBar extends Phaser.GameObjects.Container { this.bg.width = this.expText.displayWidth + 28; - gScene.fieldUI.bringToTop(this); + globalScene.fieldUI.bringToTop(this); if (this.tween) { this.tween.stop(); } - this.tween = gScene.tweens.add({ + this.tween = globalScene.tweens.add({ targets: this, - x: (gScene.game.canvas.width / 6) - (this.bg.width - 5), - duration: 500 / Math.pow(2, gScene.expGainsSpeed), + x: (globalScene.game.canvas.width / 6) - (this.bg.width - 5), + duration: 500 / Math.pow(2, globalScene.expGainsSpeed), ease: "Sine.easeOut", onComplete: () => { this.tween = null; @@ -86,9 +86,9 @@ export default class PartyExpBar extends Phaser.GameObjects.Container { this.tween.stop(); } - this.tween = gScene.tweens.add({ + this.tween = globalScene.tweens.add({ targets: this, - x: (gScene.game.canvas.width / 6), + x: (globalScene.game.canvas.width / 6), duration: 500, ease: "Sine.easeIn", onComplete: () => { diff --git a/src/ui/party-ui-handler.ts b/src/ui/party-ui-handler.ts index d37a8cf5c60..37b248149b0 100644 --- a/src/ui/party-ui-handler.ts +++ b/src/ui/party-ui-handler.ts @@ -23,7 +23,7 @@ import { Species } from "#enums/species"; import { getPokemonNameWithAffix } from "#app/messages"; import { CommandPhase } from "#app/phases/command-phase"; import { SelectModifierPhase } from "#app/phases/select-modifier-phase"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; const defaultMessage = i18next.t("partyUiHandler:choosePokemon"); @@ -197,7 +197,7 @@ export default class PartyUiHandler extends MessageUiHandler { */ private FilterChallengeLegal = (pokemon: PlayerPokemon) => { const challengeAllowed = new Utils.BooleanHolder(true); - applyChallenges(gScene.gameMode, ChallengeType.POKEMON_IN_BATTLE, pokemon, challengeAllowed); + applyChallenges(globalScene.gameMode, ChallengeType.POKEMON_IN_BATTLE, pokemon, challengeAllowed); if (!challengeAllowed.value) { return i18next.t("partyUiHandler:cantBeUsed", { pokemonName: getPokemonNameWithAffix(pokemon) }); } @@ -207,7 +207,7 @@ export default class PartyUiHandler extends MessageUiHandler { private static FilterAllMoves = (_pokemonMove: PokemonMove) => null; public static FilterItemMaxStacks = (pokemon: PlayerPokemon, modifier: PokemonHeldItemModifier) => { - const matchingModifier = gScene.findModifier(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id && m.matchType(modifier)) as PokemonHeldItemModifier; + const matchingModifier = globalScene.findModifier(m => m instanceof PokemonHeldItemModifier && m.pokemonId === pokemon.id && m.matchType(modifier)) as PokemonHeldItemModifier; if (matchingModifier && matchingModifier.stackCount === matchingModifier.getMaxStackCount()) { return i18next.t("partyUiHandler:tooManyItems", { pokemonName: getPokemonNameWithAffix(pokemon) }); } @@ -225,26 +225,26 @@ export default class PartyUiHandler extends MessageUiHandler { setup() { const ui = this.getUi(); - const partyContainer = gScene.add.container(0, 0); + const partyContainer = globalScene.add.container(0, 0); partyContainer.setName("party"); partyContainer.setVisible(false); ui.add(partyContainer); this.partyContainer = partyContainer; - this.partyBg = gScene.add.image(0, 0, "party_bg"); + this.partyBg = globalScene.add.image(0, 0, "party_bg"); this.partyBg.setName("img-party-bg"); partyContainer.add(this.partyBg); this.partyBg.setOrigin(0, 1); - const partySlotsContainer = gScene.add.container(0, 0); + const partySlotsContainer = globalScene.add.container(0, 0); partySlotsContainer.setName("party-slots"); partyContainer.add(partySlotsContainer); this.partySlotsContainer = partySlotsContainer; - const partyMessageBoxContainer = gScene.add.container(0, -32); + const partyMessageBoxContainer = globalScene.add.container(0, -32); partyMessageBoxContainer.setName("party-msg-box"); partyContainer.add(partyMessageBoxContainer); @@ -268,7 +268,7 @@ export default class PartyUiHandler extends MessageUiHandler { this.partyCancelButton = partyCancelButton; - this.optionsContainer = gScene.add.container((gScene.game.canvas.width / 6) - 1, -1); + this.optionsContainer = globalScene.add.container((globalScene.game.canvas.width / 6) - 1, -1); partyContainer.add(this.optionsContainer); this.iconAnimHandler = new PokemonIconAnimHandler(); @@ -280,8 +280,8 @@ export default class PartyUiHandler extends MessageUiHandler { scale: overlayScale, top: true, x: 1, - y: -MoveInfoOverlay.getHeight(overlayScale) - 1, //gScene.game.canvas.height / 6 - MoveInfoOverlay.getHeight(overlayScale) - 29, - width: gScene.game.canvas.width / 12 - 30, + y: -MoveInfoOverlay.getHeight(overlayScale) - 1, + width: globalScene.game.canvas.width / 12 - 30, }); ui.add(this.moveInfoOverlay); @@ -315,7 +315,7 @@ export default class PartyUiHandler extends MessageUiHandler { this.showMovePp = args.length > 6 && args[6]; this.partyContainer.setVisible(true); - this.partyBg.setTexture(`party_bg${gScene.currentBattle.double ? "_double" : ""}`); + this.partyBg.setTexture(`party_bg${globalScene.currentBattle.double ? "_double" : ""}`); this.populatePartySlots(); this.setCursor(0); @@ -346,18 +346,18 @@ export default class PartyUiHandler extends MessageUiHandler { if (this.optionsMode) { const option = this.options[this.optionsCursor]; if (button === Button.ACTION) { - const pokemon = gScene.getParty()[this.cursor]; + const pokemon = globalScene.getParty()[this.cursor]; if (this.partyUiMode === PartyUiMode.MODIFIER_TRANSFER && !this.transferMode && option !== PartyOption.CANCEL) { this.startTransfer(); let ableToTransfer: string; - for (let p = 0; p < gScene.getParty().length; p++) { // this fore look goes through each of the party pokemon - const newPokemon = gScene.getParty()[p]; + for (let p = 0; p < globalScene.getParty().length; p++) { // this fore look goes through each of the party pokemon + const newPokemon = globalScene.getParty()[p]; // this next line gets all of the transferable items from pokemon [p]; it does this by getting all the held modifiers that are transferable and checking to see if they belong to pokemon [p] const getTransferrableItemsFromPokemon = (newPokemon: PlayerPokemon) => - gScene.findModifiers(m => m instanceof PokemonHeldItemModifier && (m as PokemonHeldItemModifier).isTransferable && (m as PokemonHeldItemModifier).pokemonId === newPokemon.id) as PokemonHeldItemModifier[]; + globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && (m as PokemonHeldItemModifier).isTransferable && (m as PokemonHeldItemModifier).pokemonId === newPokemon.id) as PokemonHeldItemModifier[]; // this next bit checks to see if the the selected item from the original transfer pokemon exists on the new pokemon [p]; this returns undefined if the new pokemon doesn't have the item at all, otherwise it returns the pokemonHeldItemModifier for that item - const matchingModifier = gScene.findModifier(m => m instanceof PokemonHeldItemModifier && m.pokemonId === newPokemon.id && m.matchType(getTransferrableItemsFromPokemon(pokemon)[this.transferOptionCursor])) as PokemonHeldItemModifier; + const matchingModifier = globalScene.findModifier(m => m instanceof PokemonHeldItemModifier && m.pokemonId === newPokemon.id && m.matchType(getTransferrableItemsFromPokemon(pokemon)[this.transferOptionCursor])) as PokemonHeldItemModifier; const partySlot = this.partySlots.filter(m => m.getPokemon() === newPokemon)[0]; // this gets pokemon [p] for us if (p !== this.transferCursor) { // this skips adding the able/not able labels on the pokemon doing the transfer if (matchingModifier) { // if matchingModifier exists then the item exists on the new pokemon @@ -399,7 +399,7 @@ export default class PartyUiHandler extends MessageUiHandler { || (option === PartyOption.RELEASE && this.partyUiMode === PartyUiMode.RELEASE)) { let filterResult: string | null; const getTransferrableItemsFromPokemon = (pokemon: PlayerPokemon) => - gScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.isTransferable && m.pokemonId === pokemon.id) as PokemonHeldItemModifier[]; + globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.isTransferable && m.pokemonId === pokemon.id) as PokemonHeldItemModifier[]; if (option !== PartyOption.TRANSFER && option !== PartyOption.SPLICE) { filterResult = (this.selectFilter as PokemonSelectFilter)(pokemon); if (filterResult === null && (option === PartyOption.SEND_OUT || option === PartyOption.PASS_BATON)) { @@ -409,7 +409,7 @@ export default class PartyUiHandler extends MessageUiHandler { filterResult = this.moveSelectFilter(pokemon.moveset[this.optionsCursor]!); // TODO: is this bang correct? } } else { - filterResult = (this.selectFilter as PokemonModifierTransferSelectFilter)(pokemon, getTransferrableItemsFromPokemon(gScene.getParty()[this.transferCursor])[this.transferOptionCursor]); + filterResult = (this.selectFilter as PokemonModifierTransferSelectFilter)(pokemon, getTransferrableItemsFromPokemon(globalScene.getParty()[this.transferCursor])[this.transferOptionCursor]); } if (filterResult === null) { if (this.partyUiMode !== PartyUiMode.SPLICE) { @@ -419,7 +419,7 @@ export default class PartyUiHandler extends MessageUiHandler { if (option === PartyOption.TRANSFER) { if (this.transferCursor !== this.cursor) { if (this.transferAll) { - getTransferrableItemsFromPokemon(gScene.getParty()[this.transferCursor]).forEach((_, i) => (this.selectCallback as PartyModifierTransferSelectCallback)(this.transferCursor, i, this.transferQuantitiesMax[i], this.cursor)); + getTransferrableItemsFromPokemon(globalScene.getParty()[this.transferCursor]).forEach((_, i) => (this.selectCallback as PartyModifierTransferSelectCallback)(this.transferCursor, i, this.transferQuantitiesMax[i], this.cursor)); } else { (this.selectCallback as PartyModifierTransferSelectCallback)(this.transferCursor, this.transferOptionCursor, this.transferQuantities[this.transferOptionCursor], this.cursor); } @@ -441,15 +441,15 @@ export default class PartyUiHandler extends MessageUiHandler { selectCallback(this.cursor, option); } } else { - if (option >= PartyOption.FORM_CHANGE_ITEM && gScene.getCurrentPhase() instanceof SelectModifierPhase) { + if (option >= PartyOption.FORM_CHANGE_ITEM && globalScene.getCurrentPhase() instanceof SelectModifierPhase) { if (this.partyUiMode === PartyUiMode.CHECK) { const formChangeItemModifiers = this.getFormChangeItemsModifiers(pokemon); const modifier = formChangeItemModifiers[option - PartyOption.FORM_CHANGE_ITEM]; modifier.active = !modifier.active; - gScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeItemTrigger, false, true); + globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeItemTrigger, false, true); } } else if (this.cursor) { - (gScene.getCurrentPhase() as CommandPhase).handleCommand(Command.POKEMON, this.cursor, option === PartyOption.PASS_BATON); + (globalScene.getCurrentPhase() as CommandPhase).handleCommand(Command.POKEMON, this.cursor, option === PartyOption.PASS_BATON); } } if (this.partyUiMode !== PartyUiMode.MODIFIER && this.partyUiMode !== PartyUiMode.TM_MODIFIER && this.partyUiMode !== PartyUiMode.MOVE_MODIFIER) { @@ -492,7 +492,7 @@ export default class PartyUiHandler extends MessageUiHandler { } else if (option === PartyOption.RELEASE) { this.clearOptions(); ui.playSelect(); - if (this.cursor >= gScene.currentBattle.getBattlerCount() || !pokemon.isAllowedInBattle()) { + if (this.cursor >= globalScene.currentBattle.getBattlerCount() || !pokemon.isAllowedInBattle()) { this.blockInput = true; this.showText(i18next.t("partyUiHandler:releaseConfirmation", { pokemonName: getPokemonNameWithAffix(pokemon) }), null, () => { this.blockInput = false; @@ -580,7 +580,7 @@ export default class PartyUiHandler extends MessageUiHandler { // show move description if (this.partyUiMode === PartyUiMode.REMEMBER_MOVE_MODIFIER) { const option = this.options[this.optionsCursor]; - const pokemon = gScene.getParty()[this.cursor]; + const pokemon = globalScene.getParty()[this.cursor]; const move = allMoves[pokemon.getLearnableLevelMoves()[option]]; if (move) { this.moveInfoOverlay.show(move); @@ -595,8 +595,8 @@ export default class PartyUiHandler extends MessageUiHandler { if (this.cursor < 6) { if (this.partyUiMode === PartyUiMode.MODIFIER_TRANSFER && !this.transferMode) { /** Initialize item quantities for the selected Pokemon */ - const itemModifiers = gScene.findModifiers(m => m instanceof PokemonHeldItemModifier - && m.isTransferable && m.pokemonId === gScene.getParty()[this.cursor].id) as PokemonHeldItemModifier[]; + const itemModifiers = globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier + && m.isTransferable && m.pokemonId === globalScene.getParty()[this.cursor].id) as PokemonHeldItemModifier[]; this.transferQuantities = itemModifiers.map(item => item.getStackCount()); this.transferQuantitiesMax = itemModifiers.map(item => item.getStackCount()); } @@ -628,7 +628,7 @@ export default class PartyUiHandler extends MessageUiHandler { } const slotCount = this.partySlots.length; - const battlerCount = gScene.currentBattle.getBattlerCount(); + const battlerCount = globalScene.currentBattle.getBattlerCount(); switch (button) { case Button.UP: @@ -664,7 +664,7 @@ export default class PartyUiHandler extends MessageUiHandler { } populatePartySlots() { - const party = gScene.getParty(); + const party = globalScene.getParty(); if (this.cursor < 6 && this.cursor >= party.length) { this.cursor = party.length - 1; @@ -678,7 +678,7 @@ export default class PartyUiHandler extends MessageUiHandler { for (const p in party) { const slotIndex = parseInt(p); const partySlot = new PartySlot(slotIndex, party[p], this.iconAnimHandler, this.partyUiMode, this.tmMoveId); - gScene.add.existing(partySlot); + globalScene.add.existing(partySlot); this.partySlotsContainer.add(partySlot); this.partySlots.push(partySlot); if (this.cursor === slotIndex) { @@ -721,7 +721,7 @@ export default class PartyUiHandler extends MessageUiHandler { this.optionsCursor = cursor; } if (!this.optionsCursorObj) { - this.optionsCursorObj = gScene.add.image(0, 0, "cursor"); + this.optionsCursorObj = globalScene.add.image(0, 0, "cursor"); this.optionsCursorObj.setOrigin(0, 0); this.optionsContainer.add(this.optionsCursorObj); } @@ -803,7 +803,7 @@ export default class PartyUiHandler extends MessageUiHandler { } updateOptions(): void { - const pokemon = gScene.getParty()[this.cursor]; + const pokemon = globalScene.getParty()[this.cursor]; const learnableLevelMoves = this.partyUiMode === PartyUiMode.REMEMBER_MOVE_MODIFIER ? pokemon.getLearnableLevelMoves() @@ -815,7 +815,7 @@ export default class PartyUiHandler extends MessageUiHandler { } const itemModifiers = this.partyUiMode === PartyUiMode.MODIFIER_TRANSFER - ? gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + ? globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.isTransferable && m.pokemonId === pokemon.id) as PokemonHeldItemModifier[] : []; @@ -832,13 +832,13 @@ export default class PartyUiHandler extends MessageUiHandler { case PartyUiMode.SWITCH: case PartyUiMode.FAINT_SWITCH: case PartyUiMode.POST_BATTLE_SWITCH: - if (this.cursor >= gScene.currentBattle.getBattlerCount()) { + if (this.cursor >= globalScene.currentBattle.getBattlerCount()) { const allowBatonModifierSwitch = this.partyUiMode !== PartyUiMode.FAINT_SWITCH - && gScene.findModifier(m => m instanceof SwitchEffectTransferModifier - && (m as SwitchEffectTransferModifier).pokemonId === gScene.getPlayerField()[this.fieldIndex].id); + && globalScene.findModifier(m => m instanceof SwitchEffectTransferModifier + && (m as SwitchEffectTransferModifier).pokemonId === globalScene.getPlayerField()[this.fieldIndex].id); - const moveHistory = gScene.getPlayerField()[this.fieldIndex].getMoveHistory(); + const moveHistory = globalScene.getPlayerField()[this.fieldIndex].getMoveHistory(); const isBatonPassMove = this.partyUiMode === PartyUiMode.FAINT_SWITCH && moveHistory.length && allMoves[moveHistory[moveHistory.length - 1].move].getAttrs(ForceSwitchOutAttr)[0]?.isBatonPass() && moveHistory[moveHistory.length - 1].result === MoveResult.SUCCESS; // isBatonPassMove and allowBatonModifierSwitch shouldn't ever be true @@ -877,7 +877,7 @@ export default class PartyUiHandler extends MessageUiHandler { this.options.push(PartyOption.RELEASE); break; case PartyUiMode.CHECK: - if (gScene.getCurrentPhase() instanceof SelectModifierPhase) { + if (globalScene.getCurrentPhase() instanceof SelectModifierPhase) { formChangeItemModifiers = this.getFormChangeItemsModifiers(pokemon); for (let i = 0; i < formChangeItemModifiers.length; i++) { this.options.push(PartyOption.FORM_CHANGE_ITEM + i); @@ -1059,13 +1059,13 @@ export default class PartyUiHandler extends MessageUiHandler { } doRelease(slotIndex: integer): void { - this.showText(this.getReleaseMessage(getPokemonNameWithAffix(gScene.getParty()[slotIndex])), null, () => { + this.showText(this.getReleaseMessage(getPokemonNameWithAffix(globalScene.getParty()[slotIndex])), null, () => { this.clearPartySlots(); - gScene.removePartyMemberModifiers(slotIndex); - const releasedPokemon = gScene.getParty().splice(slotIndex, 1)[0]; + globalScene.removePartyMemberModifiers(slotIndex); + const releasedPokemon = globalScene.getParty().splice(slotIndex, 1)[0]; releasedPokemon.destroy(); this.populatePartySlots(); - if (this.cursor >= gScene.getParty().length) { + if (this.cursor >= globalScene.getParty().length) { this.setCursor(this.cursor - 1); } if (this.partyUiMode === PartyUiMode.RELEASE) { @@ -1103,7 +1103,7 @@ export default class PartyUiHandler extends MessageUiHandler { } getFormChangeItemsModifiers(pokemon: Pokemon) { - let formChangeItemModifiers = gScene.findModifiers(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === pokemon.id) as PokemonFormChangeItemModifier[]; + let formChangeItemModifiers = globalScene.findModifiers(m => m instanceof PokemonFormChangeItemModifier && m.pokemonId === pokemon.id) as PokemonFormChangeItemModifier[]; const ultraNecrozmaModifiers = formChangeItemModifiers.filter(m => m.active && m.formChangeItem === FormChangeItem.ULTRANECROZIUM_Z); if (ultraNecrozmaModifiers.length > 0) { // ULTRANECROZIUM_Z is active and deactivating it should be the only option @@ -1178,9 +1178,9 @@ class PartySlot extends Phaser.GameObjects.Container { private iconAnimHandler: PokemonIconAnimHandler; constructor(slotIndex: integer, pokemon: PlayerPokemon, iconAnimHandler: PokemonIconAnimHandler, partyUiMode: PartyUiMode, tmMoveId: Moves) { - super(gScene, slotIndex >= gScene.currentBattle.getBattlerCount() ? 230.5 : 64, - slotIndex >= gScene.currentBattle.getBattlerCount() ? -184 + (gScene.currentBattle.double ? -40 : 0) - + (28 + (gScene.currentBattle.double ? 8 : 0)) * slotIndex : -124 + (gScene.currentBattle.double ? -8 : 0) + slotIndex * 64); + super(globalScene, slotIndex >= globalScene.currentBattle.getBattlerCount() ? 230.5 : 64, + slotIndex >= globalScene.currentBattle.getBattlerCount() ? -184 + (globalScene.currentBattle.double ? -40 : 0) + + (28 + (globalScene.currentBattle.double ? 8 : 0)) * slotIndex : -124 + (globalScene.currentBattle.double ? -8 : 0) + slotIndex * 64); this.slotIndex = slotIndex; this.pokemon = pokemon; @@ -1194,27 +1194,27 @@ class PartySlot extends Phaser.GameObjects.Container { } setup(partyUiMode: PartyUiMode, tmMoveId: Moves) { - const battlerCount = gScene.currentBattle.getBattlerCount(); + const battlerCount = globalScene.currentBattle.getBattlerCount(); const slotKey = `party_slot${this.slotIndex >= battlerCount ? "" : "_main"}`; - const slotBg = gScene.add.sprite(0, 0, slotKey, `${slotKey}${this.pokemon.hp ? "" : "_fnt"}`); + const slotBg = globalScene.add.sprite(0, 0, slotKey, `${slotKey}${this.pokemon.hp ? "" : "_fnt"}`); this.slotBg = slotBg; this.add(slotBg); - const slotPb = gScene.add.sprite(this.slotIndex >= battlerCount ? -85.5 : -51, this.slotIndex >= battlerCount ? 0 : -20.5, "party_pb"); + const slotPb = globalScene.add.sprite(this.slotIndex >= battlerCount ? -85.5 : -51, this.slotIndex >= battlerCount ? 0 : -20.5, "party_pb"); this.slotPb = slotPb; this.add(slotPb); - this.pokemonIcon = gScene.addPokemonIcon(this.pokemon, slotPb.x, slotPb.y, 0.5, 0.5, true); + this.pokemonIcon = globalScene.addPokemonIcon(this.pokemon, slotPb.x, slotPb.y, 0.5, 0.5, true); this.add(this.pokemonIcon); this.iconAnimHandler.addOrUpdate(this.pokemonIcon, PokemonIconAnimMode.PASSIVE); - const slotInfoContainer = gScene.add.container(0, 0); + const slotInfoContainer = globalScene.add.container(0, 0); this.add(slotInfoContainer); let displayName = this.pokemon.getNameToRender(); @@ -1235,11 +1235,11 @@ class PartySlot extends Phaser.GameObjects.Container { this.slotName.setPositionRelative(slotBg, this.slotIndex >= battlerCount ? 21 : 24, this.slotIndex >= battlerCount ? 2 : 10); this.slotName.setOrigin(0, 0); - const slotLevelLabel = gScene.add.image(0, 0, "party_slot_overlay_lv"); + const slotLevelLabel = globalScene.add.image(0, 0, "party_slot_overlay_lv"); slotLevelLabel.setPositionRelative(this.slotName, 8, 12); slotLevelLabel.setOrigin(0, 0); - const slotLevelText = addTextObject(0, 0, this.pokemon.level.toString(), this.pokemon.level < gScene.getMaxExpLevel() ? TextStyle.PARTY : TextStyle.PARTY_RED); + const slotLevelText = addTextObject(0, 0, this.pokemon.level.toString(), this.pokemon.level < globalScene.getMaxExpLevel() ? TextStyle.PARTY : TextStyle.PARTY_RED); slotLevelText.setPositionRelative(slotLevelLabel, 9, 0); slotLevelText.setOrigin(0, 0.25); @@ -1262,7 +1262,7 @@ class PartySlot extends Phaser.GameObjects.Container { } if (this.pokemon.fusionSpecies) { - const splicedIcon = gScene.add.image(0, 0, "icon_spliced"); + const splicedIcon = globalScene.add.image(0, 0, "icon_spliced"); splicedIcon.setScale(0.5); splicedIcon.setOrigin(0, 0); if (this.slotIndex >= battlerCount) { @@ -1275,7 +1275,7 @@ class PartySlot extends Phaser.GameObjects.Container { } if (this.pokemon.status) { - const statusIndicator = gScene.add.sprite(0, 0, Utils.getLocalizedSpriteKey("statuses")); + const statusIndicator = globalScene.add.sprite(0, 0, Utils.getLocalizedSpriteKey("statuses")); statusIndicator.setFrame(StatusEffect[this.pokemon.status?.effect].toLowerCase()); statusIndicator.setOrigin(0, 0); statusIndicator.setPositionRelative(slotLevelLabel, this.slotIndex >= battlerCount ? 43 : 55, 0); @@ -1286,7 +1286,7 @@ class PartySlot extends Phaser.GameObjects.Container { if (this.pokemon.isShiny()) { const doubleShiny = this.pokemon.isFusion() && this.pokemon.shiny && this.pokemon.fusionShiny; - const shinyStar = gScene.add.image(0, 0, `shiny_star_small${doubleShiny ? "_1" : ""}`); + const shinyStar = globalScene.add.image(0, 0, `shiny_star_small${doubleShiny ? "_1" : ""}`); shinyStar.setOrigin(0, 0); shinyStar.setPositionRelative(this.slotName, -9, 3); shinyStar.setTint(getVariantTint(!doubleShiny ? this.pokemon.getVariant() : this.pokemon.variant)); @@ -1294,7 +1294,7 @@ class PartySlot extends Phaser.GameObjects.Container { slotInfoContainer.add(shinyStar); if (doubleShiny) { - const fusionShinyStar = gScene.add.image(0, 0, "shiny_star_small_2"); + const fusionShinyStar = globalScene.add.image(0, 0, "shiny_star_small_2"); fusionShinyStar.setOrigin(0, 0); fusionShinyStar.setPosition(shinyStar.x, shinyStar.y); fusionShinyStar.setTint(getVariantTint(this.pokemon.fusionVariant)); @@ -1303,14 +1303,14 @@ class PartySlot extends Phaser.GameObjects.Container { } } - this.slotHpBar = gScene.add.image(0, 0, "party_slot_hp_bar"); + this.slotHpBar = globalScene.add.image(0, 0, "party_slot_hp_bar"); this.slotHpBar.setPositionRelative(slotBg, this.slotIndex >= battlerCount ? 72 : 8, this.slotIndex >= battlerCount ? 6 : 31); this.slotHpBar.setOrigin(0, 0); this.slotHpBar.setVisible(false); const hpRatio = this.pokemon.getHpRatio(); - this.slotHpOverlay = gScene.add.sprite(0, 0, "party_slot_hp_overlay", hpRatio > 0.5 ? "high" : hpRatio > 0.25 ? "medium" : "low"); + this.slotHpOverlay = globalScene.add.sprite(0, 0, "party_slot_hp_overlay", hpRatio > 0.5 ? "high" : hpRatio > 0.25 ? "medium" : "low"); this.slotHpOverlay.setPositionRelative(this.slotHpBar, 16, 2); this.slotHpOverlay.setOrigin(0, 0); this.slotHpOverlay.setScale(hpRatio, 1); @@ -1387,7 +1387,7 @@ class PartySlot extends Phaser.GameObjects.Container { } private updateSlotTexture(): void { - const battlerCount = gScene.currentBattle.getBattlerCount(); + const battlerCount = globalScene.currentBattle.getBattlerCount(); this.slotBg.setTexture(`party_slot${this.slotIndex >= battlerCount ? "" : "_main"}`, `party_slot${this.slotIndex >= battlerCount ? "" : "_main"}${this.transfer ? "_swap" : this.pokemon.hp ? "" : "_fnt"}${this.selected ? "_sel" : ""}`); } @@ -1400,18 +1400,18 @@ class PartyCancelButton extends Phaser.GameObjects.Container { private partyCancelPb: Phaser.GameObjects.Sprite; constructor(x: number, y: number) { - super(gScene, x, y); + super(globalScene, x, y); this.setup(); } setup() { - const partyCancelBg = gScene.add.sprite(0, 0, "party_cancel"); + const partyCancelBg = globalScene.add.sprite(0, 0, "party_cancel"); this.add(partyCancelBg); this.partyCancelBg = partyCancelBg; - const partyCancelPb = gScene.add.sprite(-17, 0, "party_pb"); + const partyCancelPb = globalScene.add.sprite(-17, 0, "party_pb"); this.add(partyCancelPb); this.partyCancelPb = partyCancelPb; diff --git a/src/ui/pokeball-tray.ts b/src/ui/pokeball-tray.ts index 30a90f2f699..0997c78a67f 100644 --- a/src/ui/pokeball-tray.ts +++ b/src/ui/pokeball-tray.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import Pokemon from "../field/pokemon"; export default class PokeballTray extends Phaser.GameObjects.Container { @@ -10,17 +10,17 @@ export default class PokeballTray extends Phaser.GameObjects.Container { public shown: boolean; constructor(player: boolean) { - super(gScene, player ? (gScene.game.canvas.width / 6) : 0, player ? -72 : -144); + super(globalScene, player ? (globalScene.game.canvas.width / 6) : 0, player ? -72 : -144); this.player = player; } setup(): void { - this.bg = gScene.add.nineslice(0, 0, `pb_tray_overlay_${this.player ? "player" : "enemy"}`, undefined, 104, 4, 48, 8, 0, 0); + this.bg = globalScene.add.nineslice(0, 0, `pb_tray_overlay_${this.player ? "player" : "enemy"}`, undefined, 104, 4, 48, 8, 0, 0); this.bg.setOrigin(this.player ? 1 : 0, 0); this.add(this.bg); - this.balls = new Array(6).fill(null).map((_, i) => gScene.add.sprite((this.player ? -83 : 76) + (gScene.game.canvas.width / 6) * (this.player ? -1 : 1) + 10 * i * (this.player ? 1 : -1), -8, "pb_tray_ball", "empty")); + this.balls = new Array(6).fill(null).map((_, i) => globalScene.add.sprite((this.player ? -83 : 76) + (globalScene.game.canvas.width / 6) * (this.player ? -1 : 1) + 10 * i * (this.player ? 1 : -1), -8, "pb_tray_ball", "empty")); for (const ball of this.balls) { ball.setOrigin(0, 0); @@ -37,7 +37,7 @@ export default class PokeballTray extends Phaser.GameObjects.Container { return resolve(); } - gScene.fieldUI.bringToTop(this); + globalScene.fieldUI.bringToTop(this); this.x += 104 * (this.player ? 1 : -1); @@ -45,7 +45,7 @@ export default class PokeballTray extends Phaser.GameObjects.Container { this.bg.alpha = 1; this.balls.forEach((ball, b) => { - ball.x += (gScene.game.canvas.width / 6 + 104) * (this.player ? 1 : -1); + ball.x += (globalScene.game.canvas.width / 6 + 104) * (this.player ? 1 : -1); let ballFrame = "ball"; if (b >= party.length) { ballFrame = "empty"; @@ -57,21 +57,21 @@ export default class PokeballTray extends Phaser.GameObjects.Container { ball.setFrame(ballFrame); }); - gScene.playSound("se/pb_tray_enter"); + globalScene.playSound("se/pb_tray_enter"); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, x: `${this.player ? "-" : "+"}=104`, duration: 500, ease: "Sine.easeIn", onComplete: () => { this.balls.forEach((ball, b) => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: ball, x: `${this.player ? "-" : "+"}=104`, duration: b * 100, ease: "Sine.easeIn", - onComplete: () => gScene.playSound(`se/${(b < party.length ? "pb_tray_ball" : "pb_tray_empty")}`) + onComplete: () => globalScene.playSound(`se/${(b < party.length ? "pb_tray_ball" : "pb_tray_empty")}`) }); }); } @@ -80,7 +80,7 @@ export default class PokeballTray extends Phaser.GameObjects.Container { this.setVisible(true); this.shown = true; - gScene.time.delayedCall(1100, () => resolve()); + globalScene.time.delayedCall(1100, () => resolve()); }); } @@ -91,16 +91,16 @@ export default class PokeballTray extends Phaser.GameObjects.Container { } this.balls.forEach((ball, b) => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: ball, - x: `${this.player ? "-" : "+"}=${gScene.game.canvas.width / 6}`, + x: `${this.player ? "-" : "+"}=${globalScene.game.canvas.width / 6}`, duration: 250, delay: b * 100, ease: "Sine.easeIn" }); }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.bg, width: 144, alpha: 0, @@ -108,7 +108,7 @@ export default class PokeballTray extends Phaser.GameObjects.Container { ease: "Sine.easeIn" }); - gScene.time.delayedCall(850, () => { + globalScene.time.delayedCall(850, () => { this.setVisible(false); resolve(); }); diff --git a/src/ui/pokemon-hatch-info-container.ts b/src/ui/pokemon-hatch-info-container.ts index 88fb70380d6..bfff9855b7f 100644 --- a/src/ui/pokemon-hatch-info-container.ts +++ b/src/ui/pokemon-hatch-info-container.ts @@ -7,7 +7,7 @@ import { speciesEggMoves } from "#app/data/balance/egg-moves"; import { allMoves } from "#app/data/move"; import { Species } from "#enums/species"; import { getEggTierForSpecies } from "#app/data/egg"; -import { gScene, starterColors } from "#app/battle-scene"; +import { globalScene, starterColors } from "#app/battle-scene"; import { argbFromRgba } from "@material/material-color-utilities"; import { EggHatchData } from "#app/data/egg-hatch-data"; import { PlayerPokemon } from "#app/field/pokemon"; @@ -40,9 +40,9 @@ export default class PokemonHatchInfoContainer extends PokemonInfoContainer { super.setup(); super.changeToEggSummaryLayout(); - this.currentPokemonSprite = gScene.add.sprite(54, 80, "pkmn__sub"); + this.currentPokemonSprite = globalScene.add.sprite(54, 80, "pkmn__sub"); this.currentPokemonSprite.setScale(0.8); - this.currentPokemonSprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); + this.currentPokemonSprite.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); this.pokemonListContainer.add(this.currentPokemonSprite); // setup name and number @@ -55,17 +55,17 @@ export default class PokemonHatchInfoContainer extends PokemonInfoContainer { this.pokemonListContainer.add(this.pokemonNameText); // setup egg icon and candy count - this.pokemonHatchedIcon = gScene.add.sprite(-5, 90, "egg_icons"); + this.pokemonHatchedIcon = globalScene.add.sprite(-5, 90, "egg_icons"); this.pokemonHatchedIcon.setOrigin(0, 0.2); this.pokemonHatchedIcon.setScale(0.8); this.pokemonListContainer.add(this.pokemonHatchedIcon); - this.pokemonCandyIcon = gScene.add.sprite(4.5, 40, "candy"); + this.pokemonCandyIcon = globalScene.add.sprite(4.5, 40, "candy"); this.pokemonCandyIcon.setScale(0.5); this.pokemonCandyIcon.setOrigin(0, 0); this.pokemonListContainer.add(this.pokemonCandyIcon); - this.pokemonCandyOverlayIcon = gScene.add.sprite(4.5, 40, "candy_overlay"); + this.pokemonCandyOverlayIcon = globalScene.add.sprite(4.5, 40, "candy_overlay"); this.pokemonCandyOverlayIcon.setScale(0.5); this.pokemonCandyOverlayIcon.setOrigin(0, 0); this.pokemonListContainer.add(this.pokemonCandyOverlayIcon); @@ -78,14 +78,14 @@ export default class PokemonHatchInfoContainer extends PokemonInfoContainer { this.pokemonEggMoveContainers = []; this.pokemonEggMoveBgs = []; this.pokemonEggMoveLabels = []; - this.pokemonEggMovesContainer = gScene.add.container(0, 200); + this.pokemonEggMovesContainer = globalScene.add.container(0, 200); this.pokemonEggMovesContainer.setVisible(false); this.pokemonEggMovesContainer.setScale(0.5); for (let m = 0; m < 4; m++) { - const eggMoveContainer = gScene.add.container(0, 0 + 6 * m); + const eggMoveContainer = globalScene.add.container(0, 0 + 6 * m); - const eggMoveBg = gScene.add.nineslice(70, 0, "type_bgs", "unknown", 92, 14, 2, 2, 2, 2); + const eggMoveBg = globalScene.add.nineslice(70, 0, "type_bgs", "unknown", 92, 14, 2, 2, 2, 2); eggMoveBg.setOrigin(1, 0); const eggMoveLabel = addTextObject(70 - eggMoveBg.width / 2, 0, "???", TextStyle.PARTY); @@ -155,7 +155,7 @@ export default class PokemonHatchInfoContainer extends PokemonInfoContainer { this.pokemonCandyIcon.setVisible(true); this.pokemonCandyOverlayIcon.setTint(argbFromRgba(Utils.rgbHexToRgba(colorScheme[1]))); this.pokemonCandyOverlayIcon.setVisible(true); - this.pokemonCandyCountText.setText(`x${gScene.gameData.starterData[species.speciesId].candyCount}`); + this.pokemonCandyCountText.setText(`x${globalScene.gameData.starterData[species.speciesId].candyCount}`); this.pokemonCandyCountText.setVisible(true); this.pokemonNumberText.setText(Utils.padInt(species.speciesId, 4)); @@ -165,7 +165,7 @@ export default class PokemonHatchInfoContainer extends PokemonInfoContainer { for (let em = 0; em < 4; em++) { const eggMove = hasEggMoves ? allMoves[speciesEggMoves[species.speciesId][em]] : null; - const eggMoveUnlocked = eggMove && gScene.gameData.starterData[species.speciesId].eggMoves & Math.pow(2, em); + const eggMoveUnlocked = eggMove && globalScene.gameData.starterData[species.speciesId].eggMoves & Math.pow(2, em); this.pokemonEggMoveBgs[em].setFrame(Type[eggMove ? eggMove.type : Type.UNKNOWN].toString().toLowerCase()); this.pokemonEggMoveLabels[em].setText(eggMove && eggMoveUnlocked ? eggMove.name : "???"); diff --git a/src/ui/pokemon-icon-anim-handler.ts b/src/ui/pokemon-icon-anim-handler.ts index 76ad0d90d35..d6fda22a1ee 100644 --- a/src/ui/pokemon-icon-anim-handler.ts +++ b/src/ui/pokemon-icon-anim-handler.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import * as Utils from "../utils"; export enum PokemonIconAnimMode { @@ -26,7 +26,7 @@ export default class PokemonIconAnimHandler { i.y += delta * (this.toggled ? 1 : -1); } }; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ duration: Utils.fixedInt(200), from: 0, to: 1, diff --git a/src/ui/pokemon-info-container.ts b/src/ui/pokemon-info-container.ts index 86748b6051c..48cc56882d8 100644 --- a/src/ui/pokemon-info-container.ts +++ b/src/ui/pokemon-info-container.ts @@ -1,6 +1,6 @@ import { getVariantTint } from "#app/data/variant"; import BBCodeText from "phaser3-rex-plugins/plugins/bbcodetext"; -import BattleScene, { gScene } from "#app/battle-scene"; +import BattleScene, { globalScene } from "#app/battle-scene"; import { Gender, getGenderColor, getGenderSymbol } from "../data/gender"; import { getNatureName } from "../data/nature"; import { Type } from "../data/type"; @@ -76,7 +76,7 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { public shown: boolean; constructor(x: number = 372, y: number = 66) { - super(gScene, x, y); + super(globalScene, x, y); this.initialX = x; } @@ -89,7 +89,7 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { this.infoBg.setOrigin(0.5, 0.5); this.infoBg.setName("window-info-bg"); - this.pokemonMovesContainer = gScene.add.container(6, 14); + this.pokemonMovesContainer = globalScene.add.container(6, 14); this.pokemonMovesContainer.setName("pkmn-moves"); this.movesContainerInitialX = this.pokemonMovesContainer.x; @@ -109,11 +109,11 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { this.pokemonMovesContainer.add(movesLabel); for (let m = 0; m < 4; m++) { - const moveContainer = gScene.add.container(-6, 18 + 7 * m); + const moveContainer = globalScene.add.container(-6, 18 + 7 * m); moveContainer.setScale(0.5); moveContainer.setName("move"); - const moveBg = gScene.add.nineslice(0, 0, "type_bgs", "unknown", 92, 14, 2, 2, 2, 2); + const moveBg = globalScene.add.nineslice(0, 0, "type_bgs", "unknown", 92, 14, 2, 2, 2, 2); moveBg.setOrigin(1, 0); moveBg.setName("nineslice-move-bg"); @@ -187,7 +187,7 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { this.pokemonNatureText.setName("text-pkmn-nature"); this.add(this.pokemonNatureText); - this.pokemonShinyIcon = gScene.add.image(-43.5, 48.5, "shiny_star"); + this.pokemonShinyIcon = globalScene.add.image(-43.5, 48.5, "shiny_star"); this.pokemonShinyIcon.setOrigin(0, 0); this.pokemonShinyIcon.setScale(0.75); this.pokemonShinyIcon.setInteractive(new Phaser.Geom.Rectangle(0, 0, 12, 15), Phaser.Geom.Rectangle.Contains); @@ -200,7 +200,7 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { this.add(this.pokemonShinyNewIcon); this.pokemonShinyNewIcon.setVisible(false); - this.pokemonFusionShinyIcon = gScene.add.image(this.pokemonShinyIcon.x, this.pokemonShinyIcon.y, "shiny_star_2"); + this.pokemonFusionShinyIcon = globalScene.add.image(this.pokemonShinyIcon.x, this.pokemonShinyIcon.y, "shiny_star_2"); this.pokemonFusionShinyIcon.setOrigin(0, 0); this.pokemonFusionShinyIcon.setScale(0.75); this.pokemonFusionShinyIcon.setName("img-pkmn-fusion-shiny-icon"); @@ -212,10 +212,10 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { show(pokemon: Pokemon, showMoves: boolean = false, speedMultiplier: number = 1, dexEntry?: DexEntry, starterEntry?: StarterDataEntry, eggInfo = false): Promise { return new Promise(resolve => { if (!dexEntry) { - dexEntry = gScene.gameData.dexData[pokemon.species.speciesId]; + dexEntry = globalScene.gameData.dexData[pokemon.species.speciesId]; } if (!starterEntry) { - starterEntry = gScene.gameData.starterData[pokemon.species.getRootSpeciesId()]; + starterEntry = globalScene.gameData.starterData[pokemon.species.getRootSpeciesId()]; } const caughtAttr = BigInt(dexEntry.caughtAttr); @@ -227,8 +227,8 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { const newGender = BigInt(1 << pokemon.gender) * DexAttr.MALE; this.pokemonGenderNewText.setText("(+)"); - this.pokemonGenderNewText.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, gScene.uiTheme)); - this.pokemonGenderNewText.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, gScene.uiTheme)); + this.pokemonGenderNewText.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, globalScene.uiTheme)); + this.pokemonGenderNewText.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, globalScene.uiTheme)); this.pokemonGenderNewText.setVisible((newGender & caughtAttr) === BigInt(0)); } else { this.pokemonGenderNewText.setVisible(false); @@ -259,18 +259,18 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { const newForm = BigInt(1 << pokemon.formIndex) * DexAttr.DEFAULT_FORM; if ((newForm & caughtAttr) === BigInt(0)) { - this.pokemonFormLabelText.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, gScene.uiTheme)); - this.pokemonFormLabelText.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, gScene.uiTheme)); + this.pokemonFormLabelText.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, globalScene.uiTheme)); + this.pokemonFormLabelText.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, globalScene.uiTheme)); } else { - this.pokemonFormLabelText.setColor(getTextColor(TextStyle.WINDOW, false, gScene.uiTheme)); - this.pokemonFormLabelText.setShadowColor(getTextColor(TextStyle.WINDOW, true, gScene.uiTheme)); + this.pokemonFormLabelText.setColor(getTextColor(TextStyle.WINDOW, false, globalScene.uiTheme)); + this.pokemonFormLabelText.setShadowColor(getTextColor(TextStyle.WINDOW, true, globalScene.uiTheme)); } this.pokemonFormText.setText(formName.length > this.numCharsBeforeCutoff ? formName.substring(0, this.numCharsBeforeCutoff - 3) + "..." : formName); if (formName.length > this.numCharsBeforeCutoff) { this.pokemonFormText.setInteractive(new Phaser.Geom.Rectangle(0, 0, this.pokemonFormText.width, this.pokemonFormText.height), Phaser.Geom.Rectangle.Contains); - this.pokemonFormText.on("pointerover", () => gScene.ui.showTooltip("", formName, true)); - this.pokemonFormText.on("pointerout", () => gScene.ui.hideTooltip()); + this.pokemonFormText.on("pointerover", () => globalScene.ui.showTooltip("", formName, true)); + this.pokemonFormText.on("pointerout", () => globalScene.ui.hideTooltip()); } else { this.pokemonFormText.disableInteractive(); } @@ -282,31 +282,31 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { const abilityTextStyle = pokemon.abilityIndex === 2 ? TextStyle.MONEY : TextStyle.WINDOW; this.pokemonAbilityText.setText(pokemon.getAbility(true).name); - this.pokemonAbilityText.setColor(getTextColor(abilityTextStyle, false, gScene.uiTheme)); - this.pokemonAbilityText.setShadowColor(getTextColor(abilityTextStyle, true, gScene.uiTheme)); + this.pokemonAbilityText.setColor(getTextColor(abilityTextStyle, false, globalScene.uiTheme)); + this.pokemonAbilityText.setShadowColor(getTextColor(abilityTextStyle, true, globalScene.uiTheme)); // Check if the player owns ability for the root form const playerOwnsThisAbility = pokemon.checkIfPlayerHasAbilityOfStarter(starterEntry.abilityAttr); if (!playerOwnsThisAbility) { - this.pokemonAbilityLabelText.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, gScene.uiTheme)); - this.pokemonAbilityLabelText.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, gScene.uiTheme)); + this.pokemonAbilityLabelText.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, globalScene.uiTheme)); + this.pokemonAbilityLabelText.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, globalScene.uiTheme)); } else { - this.pokemonAbilityLabelText.setColor(getTextColor(TextStyle.WINDOW, false, gScene.uiTheme)); - this.pokemonAbilityLabelText.setShadowColor(getTextColor(TextStyle.WINDOW, true, gScene.uiTheme)); + this.pokemonAbilityLabelText.setColor(getTextColor(TextStyle.WINDOW, false, globalScene.uiTheme)); + this.pokemonAbilityLabelText.setShadowColor(getTextColor(TextStyle.WINDOW, true, globalScene.uiTheme)); } - this.pokemonNatureText.setText(getNatureName(pokemon.getNature(), true, false, false, gScene.uiTheme)); + this.pokemonNatureText.setText(getNatureName(pokemon.getNature(), true, false, false, globalScene.uiTheme)); const dexNatures = dexEntry.natureAttr; const newNature = 1 << (pokemon.nature + 1); if (!(dexNatures & newNature)) { - this.pokemonNatureLabelText.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, gScene.uiTheme)); - this.pokemonNatureLabelText.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, gScene.uiTheme)); + this.pokemonNatureLabelText.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, globalScene.uiTheme)); + this.pokemonNatureLabelText.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, globalScene.uiTheme)); } else { - this.pokemonNatureLabelText.setColor(getTextColor(TextStyle.WINDOW, false, gScene.uiTheme)); - this.pokemonNatureLabelText.setShadowColor(getTextColor(TextStyle.WINDOW, true, gScene.uiTheme)); + this.pokemonNatureLabelText.setColor(getTextColor(TextStyle.WINDOW, false, globalScene.uiTheme)); + this.pokemonNatureLabelText.setShadowColor(getTextColor(TextStyle.WINDOW, true, globalScene.uiTheme)); } const isFusion = pokemon.isFusion(); @@ -320,15 +320,15 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { const shinyDescriptor = doubleShiny || baseVariant ? `${baseVariant === 2 ? i18next.t("common:epicShiny") : baseVariant === 1 ? i18next.t("common:rareShiny") : i18next.t("common:commonShiny")}${doubleShiny ? `/${pokemon.fusionVariant === 2 ? i18next.t("common:epicShiny") : pokemon.fusionVariant === 1 ? i18next.t("common:rareShiny") : i18next.t("common:commonShiny")}` : ""}` : ""; - this.pokemonShinyIcon.on("pointerover", () => gScene.ui.showTooltip("", `${i18next.t("common:shinyOnHover")}${shinyDescriptor ? ` (${shinyDescriptor})` : ""}`, true)); - this.pokemonShinyIcon.on("pointerout", () => gScene.ui.hideTooltip()); + this.pokemonShinyIcon.on("pointerover", () => globalScene.ui.showTooltip("", `${i18next.t("common:shinyOnHover")}${shinyDescriptor ? ` (${shinyDescriptor})` : ""}`, true)); + this.pokemonShinyIcon.on("pointerout", () => globalScene.ui.hideTooltip()); const newShiny = BigInt(1 << (pokemon.shiny ? 1 : 0)); const newVariant = BigInt(1 << (pokemon.variant + 4)); this.pokemonShinyNewIcon.setText("(+)"); - this.pokemonShinyNewIcon.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, gScene.uiTheme)); - this.pokemonShinyNewIcon.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, gScene.uiTheme)); + this.pokemonShinyNewIcon.setColor(getTextColor(TextStyle.SUMMARY_BLUE, false, globalScene.uiTheme)); + this.pokemonShinyNewIcon.setShadowColor(getTextColor(TextStyle.SUMMARY_BLUE, true, globalScene.uiTheme)); const newShinyOrVariant = ((newShiny & caughtAttr) === BigInt(0)) || ((newVariant & caughtAttr) === BigInt(0)); this.pokemonShinyNewIcon.setVisible(!!newShinyOrVariant); } else { @@ -342,12 +342,12 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { } const starterSpeciesId = pokemon.species.getRootSpeciesId(); - const originalIvs: integer[] | null = eggInfo ? (dexEntry.caughtAttr ? dexEntry.ivs : null) : (gScene.gameData.dexData[starterSpeciesId].caughtAttr - ? gScene.gameData.dexData[starterSpeciesId].ivs : null); + const originalIvs: integer[] | null = eggInfo ? (dexEntry.caughtAttr ? dexEntry.ivs : null) : (globalScene.gameData.dexData[starterSpeciesId].caughtAttr + ? globalScene.gameData.dexData[starterSpeciesId].ivs : null); this.statsContainer.updateIvs(pokemon.ivs, originalIvs!); // TODO: is this bang correct? if (!eggInfo) { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, duration: Utils.fixedInt(Math.floor(750 / speedMultiplier)), ease: "Cubic.easeInOut", @@ -358,7 +358,7 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { }); if (showMoves) { - gScene.tweens.add({ + globalScene.tweens.add({ delay: Utils.fixedInt(Math.floor(325 / speedMultiplier)), targets: this.pokemonMovesContainer, duration: Utils.fixedInt(Math.floor(325 / speedMultiplier)), @@ -378,7 +378,7 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { this.setVisible(true); this.shown = true; - gScene.hideEnemyModifierBar(); + globalScene.hideEnemyModifierBar(); }); } @@ -415,7 +415,7 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { makeRoomForConfirmUi(speedMultiplier: number = 1, fromCatch: boolean = false): Promise { const xPosition = fromCatch ? this.initialX - this.infoWindowWidth - 65 : this.initialX - this.infoWindowWidth - ConfirmUiHandler.windowWidth; return new Promise(resolve => { - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, duration: Utils.fixedInt(Math.floor(150 / speedMultiplier)), ease: "Cubic.easeInOut", @@ -430,18 +430,18 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { hide(speedMultiplier: number = 1): Promise { return new Promise(resolve => { if (!this.shown) { - gScene.showEnemyModifierBar(); + globalScene.showEnemyModifierBar(); return resolve(); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.pokemonMovesContainer, duration: Utils.fixedInt(Math.floor(750 / speedMultiplier)), ease: "Cubic.easeInOut", x: this.movesContainerInitialX }); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, duration: Utils.fixedInt(Math.floor(750 / speedMultiplier)), ease: "Cubic.easeInOut", @@ -450,8 +450,8 @@ export default class PokemonInfoContainer extends Phaser.GameObjects.Container { this.setVisible(false); this.pokemonShinyIcon.off("pointerover"); this.pokemonShinyIcon.off("pointerout"); - gScene.ui.hideTooltip(); - gScene.showEnemyModifierBar(); + globalScene.ui.hideTooltip(); + globalScene.showEnemyModifierBar(); resolve(); } }); diff --git a/src/ui/registration-form-ui-handler.ts b/src/ui/registration-form-ui-handler.ts index 2f94ebec7e1..81401a8df1b 100644 --- a/src/ui/registration-form-ui-handler.ts +++ b/src/ui/registration-form-ui-handler.ts @@ -4,7 +4,7 @@ import * as Utils from "../utils"; import { Mode } from "./ui"; import { TextStyle, addTextObject } from "./text"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; interface LanguageSetting { @@ -93,10 +93,10 @@ export default class RegistrationFormUiHandler extends FormModalUiHandler { // Prevent overlapping overrides on action modification this.submitAction = originalRegistrationAction; this.sanitizeInputs(); - gScene.ui.setMode(Mode.LOADING, { buttonActions: []}); + globalScene.ui.setMode(Mode.LOADING, { buttonActions: []}); const onFail = error => { - gScene.ui.setMode(Mode.REGISTRATION_FORM, Object.assign(config, { errorMessage: error?.trim() })); - gScene.ui.playError(); + globalScene.ui.setMode(Mode.REGISTRATION_FORM, Object.assign(config, { errorMessage: error?.trim() })); + globalScene.ui.playError(); const errorMessageFontSize = languageSettings[i18next.resolvedLanguage!]?.errorMessageFontSize; if (errorMessageFontSize) { this.errorMessage.setFontSize(errorMessageFontSize); diff --git a/src/ui/run-history-ui-handler.ts b/src/ui/run-history-ui-handler.ts index d18de4d875d..05d46ff5a51 100644 --- a/src/ui/run-history-ui-handler.ts +++ b/src/ui/run-history-ui-handler.ts @@ -1,4 +1,4 @@ -import BattleScene, { gScene } from "#app/battle-scene"; +import BattleScene, { globalScene } from "#app/battle-scene"; import { GameModes } from "../game-mode"; import { TextStyle, addTextObject } from "./text"; import { Mode } from "./ui"; @@ -47,27 +47,27 @@ export default class RunHistoryUiHandler extends MessageUiHandler { override setup() { const ui = this.getUi(); - this.runSelectContainer = gScene.add.container(0, 0); + this.runSelectContainer = globalScene.add.container(0, 0); this.runSelectContainer.setVisible(false); ui.add(this.runSelectContainer); - const loadSessionBg = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, -gScene.game.canvas.height / 6, 0x006860); + const loadSessionBg = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width / 6, -globalScene.game.canvas.height / 6, 0x006860); loadSessionBg.setOrigin(0, 0); this.runSelectContainer.add(loadSessionBg); - this.runContainerInitialY = -gScene.game.canvas.height / 6 + 8; + this.runContainerInitialY = -globalScene.game.canvas.height / 6 + 8; - this.runsContainer = gScene.add.container(8, this.runContainerInitialY); + this.runsContainer = globalScene.add.container(8, this.runContainerInitialY); this.runSelectContainer.add(this.runsContainer); this.runs = []; - gScene.loadImage("hall_of_fame_red", "ui"); - gScene.loadImage("hall_of_fame_blue", "ui"); + globalScene.loadImage("hall_of_fame_red", "ui"); + globalScene.loadImage("hall_of_fame_blue", "ui"); // For some reason, the game deletes/unloads the rival sprites. As a result, Run Info cannot access the rival sprites. // The rivals are loaded here to have some way of accessing those sprites. - gScene.loadAtlas("rival_f", "trainer"); - gScene.loadAtlas("rival_m", "trainer"); + globalScene.loadAtlas("rival_f", "trainer"); + globalScene.loadAtlas("rival_m", "trainer"); } override show(args: any[]): boolean { @@ -105,7 +105,7 @@ export default class RunHistoryUiHandler extends MessageUiHandler { if (button === Button.ACTION) { const cursor = this.cursor + this.scrollCursor; if (this.runs[cursor]) { - gScene.ui.setOverlayMode(Mode.RUN_INFO, this.runs[cursor].entryData, RunDisplayMode.RUN_HISTORY, true); + globalScene.ui.setOverlayMode(Mode.RUN_INFO, this.runs[cursor].entryData, RunDisplayMode.RUN_HISTORY, true); } else { return false; } @@ -114,7 +114,7 @@ export default class RunHistoryUiHandler extends MessageUiHandler { } else { this.runSelectCallback = null; success = true; - gScene.ui.revertMode(); + globalScene.ui.revertMode(); } } else if (this.runs.length > 0) { switch (button) { @@ -157,7 +157,7 @@ export default class RunHistoryUiHandler extends MessageUiHandler { * In the for loop, each run is processed to create an RunEntryContainer used to display and store the run's unique information */ private async populateRuns() { - const response = await gScene.gameData.getRunHistoryData(); + const response = await globalScene.gameData.getRunHistoryData(); const timestamps = Object.keys(response); if (timestamps.length === 0) { this.showEmpty(); @@ -170,7 +170,7 @@ export default class RunHistoryUiHandler extends MessageUiHandler { const entryCount = timestamps.length; for (let s = 0; s < entryCount; s++) { const entry = new RunEntryContainer(response[timestampsNo[s]], s); - gScene.add.existing(entry); + globalScene.add.existing(entry); this.runsContainer.add(entry); this.runs.push(entry); } @@ -195,7 +195,7 @@ export default class RunHistoryUiHandler extends MessageUiHandler { const changed = super.setCursor(cursor); if (!this.cursorObj) { - this.cursorObj = gScene.add.nineslice(0, 0, "select_cursor_highlight_thick", undefined, 296, 46, 6, 6, 6, 6); + this.cursorObj = globalScene.add.nineslice(0, 0, "select_cursor_highlight_thick", undefined, 296, 46, 6, 6, 6, 6); this.cursorObj.setOrigin(0, 0); this.runsContainer.add(this.cursorObj); } @@ -209,7 +209,7 @@ export default class RunHistoryUiHandler extends MessageUiHandler { if (changed) { this.scrollCursor = scrollCursor; this.setCursor(this.cursor); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.runsContainer, y: this.runContainerInitialY - 56 * scrollCursor, duration: Utils.fixedInt(325), @@ -255,7 +255,7 @@ class RunEntryContainer extends Phaser.GameObjects.Container { public entryData: RunEntry; constructor(entryData: RunEntry, slotId: number) { - super(gScene, 0, slotId * 56); + super(globalScene, 0, slotId * 56); this.slotId = slotId; this.entryData = entryData; @@ -277,7 +277,7 @@ class RunEntryContainer extends Phaser.GameObjects.Container { private setup(run: RunEntry) { const victory = run.isVictory; - const data = gScene.gameData.parseSessionData(JSON.stringify(run.entry)); + const data = globalScene.gameData.parseSessionData(JSON.stringify(run.entry)); const slotWindow = addWindow(0, 0, 304, 52); this.add(slotWindow); @@ -287,20 +287,20 @@ class RunEntryContainer extends Phaser.GameObjects.Container { const gameOutcomeLabel = addTextObject(8, 5, `${i18next.t("runHistory:victory")}`, TextStyle.WINDOW); this.add(gameOutcomeLabel); } else { // Run Result: Defeats - const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET; + const genderIndex = globalScene.gameData.gender ?? PlayerGender.UNSET; const genderStr = PlayerGender[genderIndex].toLowerCase(); // Defeats from wild Pokemon battles will show the Pokemon responsible by the text of the run result. if (data.battleType === BattleType.WILD || (data.battleType === BattleType.MYSTERY_ENCOUNTER && !data.trainer)) { - const enemyContainer = gScene.add.container(8, 5); + const enemyContainer = globalScene.add.container(8, 5); const gameOutcomeLabel = addTextObject(0, 0, `${i18next.t("runHistory:defeatedWild", { context: genderStr })}`, TextStyle.WINDOW); enemyContainer.add(gameOutcomeLabel); data.enemyParty.forEach((enemyData, e) => { - const enemyIconContainer = gScene.add.container(65 + (e * 25), -8); + const enemyIconContainer = globalScene.add.container(65 + (e * 25), -8); enemyIconContainer.setScale(0.75); enemyData.boss = false; enemyData["player"] = true; const enemy = enemyData.toPokemon(); - const enemyIcon = gScene.addPokemonIcon(enemy, 0, 0, 0, 0); + const enemyIcon = globalScene.addPokemonIcon(enemy, 0, 0, 0, 0); const enemyLevel = addTextObject(32, 20, `${i18next.t("saveSlotSelectUiHandler:lv")}${Utils.formatLargeNumber(enemy.level, 1000)}`, TextStyle.PARTY, { fontSize: "54px", color: "#f8f8f8" }); enemyLevel.setShadow(0, 0, undefined); enemyLevel.setStroke("#424242", 14); @@ -348,7 +348,7 @@ class RunEntryContainer extends Phaser.GameObjects.Container { } gameModeLabel.appendText(mode, false); if (data.gameMode === GameModes.SPLICED_ENDLESS) { - const splicedIcon = gScene.add.image(0, 0, "icon_spliced"); + const splicedIcon = globalScene.add.image(0, 0, "icon_spliced"); splicedIcon.setScale(0.75); const coords = gameModeLabel.getTopRight(); splicedIcon.setPosition(coords.x + 5, 27); @@ -367,13 +367,13 @@ class RunEntryContainer extends Phaser.GameObjects.Container { // pokemonIconsContainer holds the run's party Pokemon icons and levels // Icons should be level with each other here, but there are significant number of icons that have a center axis / position far from the norm. // The code here does not account for icon weirdness. - const pokemonIconsContainer = gScene.add.container(140, 17); + const pokemonIconsContainer = globalScene.add.container(140, 17); data.party.forEach((p: PokemonData, i: number) => { - const iconContainer = gScene.add.container(26 * i, 0); + const iconContainer = globalScene.add.container(26 * i, 0); iconContainer.setScale(0.75); const pokemon = p.toPokemon(); - const icon = gScene.addPokemonIcon(pokemon, 0, 0, 0, 0); + const icon = globalScene.addPokemonIcon(pokemon, 0, 0, 0, 0); const text = addTextObject(32, 20, `${i18next.t("saveSlotSelectUiHandler:lv")}${Utils.formatLargeNumber(pokemon.level, 1000)}`, TextStyle.PARTY, { fontSize: "54px", color: "#f8f8f8" }); text.setShadow(0, 0, undefined); diff --git a/src/ui/run-info-ui-handler.ts b/src/ui/run-info-ui-handler.ts index 67aee01042d..fe98c7d18f4 100644 --- a/src/ui/run-info-ui-handler.ts +++ b/src/ui/run-info-ui-handler.ts @@ -24,7 +24,7 @@ import { PlayerGender } from "#enums/player-gender"; import { SettingKeyboard } from "#app/system/settings/settings-keyboard"; import { getBiomeName } from "#app/data/balance/biomes"; import { MysteryEncounterType } from "#enums/mystery-encounter-type"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; /** * RunInfoUiMode indicates possible overlays of RunInfoUiHandler. @@ -71,11 +71,11 @@ export default class RunInfoUiHandler extends UiHandler { } override async setup() { - this.runContainer = gScene.add.container(1, -(gScene.game.canvas.height / 6) + 1); + this.runContainer = globalScene.add.container(1, -(globalScene.game.canvas.height / 6) + 1); // The import of the modifiersModule is loaded here to sidestep async/await issues. this.modifiersModule = Modifier; this.runContainer.setVisible(false); - gScene.loadImage("encounter_exclaim", "mystery-encounters"); + globalScene.loadImage("encounter_exclaim", "mystery-encounters"); } /** @@ -92,14 +92,14 @@ export default class RunInfoUiHandler extends UiHandler { override show(args: any[]): boolean { super.show(args); - const gameStatsBg = gScene.add.rectangle(0, 0, gScene.game.canvas.width, gScene.game.canvas.height, 0x006860); + const gameStatsBg = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width, globalScene.game.canvas.height, 0x006860); gameStatsBg.setOrigin(0, 0); this.runContainer.add(gameStatsBg); const run = args[0]; this.runDisplayMode = args[1]; if (this.runDisplayMode === RunDisplayMode.RUN_HISTORY) { - this.runInfo = gScene.gameData.parseSessionData(JSON.stringify(run.entry)); + this.runInfo = globalScene.gameData.parseSessionData(JSON.stringify(run.entry)); this.isVictory = run.isVictory ?? false; } else if (this.runDisplayMode === RunDisplayMode.SESSION_PREVIEW) { this.runInfo = args[0]; @@ -111,10 +111,10 @@ export default class RunInfoUiHandler extends UiHandler { // Creates Header and adds to this.runContainer this.addHeader(); - this.statsBgWidth = ((gScene.game.canvas.width / 6) - 2) / 3; + this.statsBgWidth = ((globalScene.game.canvas.width / 6) - 2) / 3; // Creates Run Result Container - this.runResultContainer = gScene.add.container(0, 24); + this.runResultContainer = globalScene.add.container(0, 24); const runResultWindow = addWindow(0, 0, this.statsBgWidth - 11, 65); runResultWindow.setOrigin(0, 0); this.runResultContainer.add(runResultWindow); @@ -125,18 +125,18 @@ export default class RunInfoUiHandler extends UiHandler { } // Creates Run Info Container - this.runInfoContainer = gScene.add.container(0, 89); + this.runInfoContainer = globalScene.add.container(0, 89); const runInfoWindow = addWindow(0, 0, this.statsBgWidth - 11, 90); const runInfoWindowCoords = runInfoWindow.getBottomRight(); this.runInfoContainer.add(runInfoWindow); this.parseRunInfo(runInfoWindowCoords.x, runInfoWindowCoords.y); // Creates Player Party Container - this.partyContainer = gScene.add.container(this.statsBgWidth - 10, 23); + this.partyContainer = globalScene.add.container(this.statsBgWidth - 10, 23); this.parsePartyInfo(); this.showParty(true); - this.runContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); + this.runContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); this.getUi().bringToTop(this.runContainer); this.runContainer.setVisible(true); @@ -161,19 +161,19 @@ export default class RunInfoUiHandler extends UiHandler { * It does not check if the run has any PokemonHeldItemModifiers though. */ private addHeader() { - const headerBg = addWindow(0, 0, (gScene.game.canvas.width / 6) - 2, 24); + const headerBg = addWindow(0, 0, (globalScene.game.canvas.width / 6) - 2, 24); headerBg.setOrigin(0, 0); this.runContainer.add(headerBg); if (this.runInfo.modifiers.length !== 0) { const headerBgCoords = headerBg.getTopRight(); - const abilityButtonContainer = gScene.add.container(0, 0); + const abilityButtonContainer = globalScene.add.container(0, 0); const abilityButtonText = addTextObject(8, 0, i18next.t("runHistory:viewHeldItems"), TextStyle.WINDOW, { fontSize:"34px" }); const gamepadType = this.getUi().getGamepadType(); let abilityButtonElement: Phaser.GameObjects.Sprite; if (gamepadType === "touch") { - abilityButtonElement = new Phaser.GameObjects.Sprite(gScene, 0, 2, "keyboard", "E.png"); + abilityButtonElement = new Phaser.GameObjects.Sprite(globalScene, 0, 2, "keyboard", "E.png"); } else { - abilityButtonElement = new Phaser.GameObjects.Sprite(gScene, 0, 2, gamepadType, gScene.inputController?.getIconForLatestInputRecorded(SettingKeyboard.Button_Cycle_Ability)); + abilityButtonElement = new Phaser.GameObjects.Sprite(globalScene, 0, 2, gamepadType, globalScene.inputController?.getIconForLatestInputRecorded(SettingKeyboard.Button_Cycle_Ability)); } abilityButtonContainer.add([ abilityButtonText, abilityButtonElement ]); abilityButtonContainer.setPosition(headerBgCoords.x - abilityButtonText.displayWidth - abilityButtonElement.displayWidth - 8, 10); @@ -194,25 +194,25 @@ export default class RunInfoUiHandler extends UiHandler { * */ private async parseRunResult() { - const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET; + const genderIndex = globalScene.gameData.gender ?? PlayerGender.UNSET; const genderStr = PlayerGender[genderIndex]; const runResultTextStyle = this.isVictory ? TextStyle.PERFECT_IV : TextStyle.SUMMARY_RED; const runResultTitle = this.isVictory ? i18next.t("runHistory:victory") : i18next.t("runHistory:defeated", { context: genderStr }); const runResultText = addTextObject(6, 5, `${runResultTitle} - ${i18next.t("saveSlotSelectUiHandler:wave")} ${this.runInfo.waveIndex}`, runResultTextStyle, { fontSize : "65px", lineSpacing: 0.1 }); if (this.isVictory) { - const hallofFameInstructionContainer = gScene.add.container(0, 0); + const hallofFameInstructionContainer = globalScene.add.container(0, 0); const shinyButtonText = addTextObject(8, 0, i18next.t("runHistory:viewHallOfFame"), TextStyle.WINDOW, { fontSize:"65px" }); const formButtonText = addTextObject(8, 12, i18next.t("runHistory:viewEndingSplash"), TextStyle.WINDOW, { fontSize:"65px" }); const gamepadType = this.getUi().getGamepadType(); let shinyButtonElement: Phaser.GameObjects.Sprite; let formButtonElement: Phaser.GameObjects.Sprite; if (gamepadType === "touch") { - shinyButtonElement = new Phaser.GameObjects.Sprite(gScene, 0, 4, "keyboard", "R.png"); - formButtonElement = new Phaser.GameObjects.Sprite(gScene, 0, 16, "keyboard", "F.png"); + shinyButtonElement = new Phaser.GameObjects.Sprite(globalScene, 0, 4, "keyboard", "R.png"); + formButtonElement = new Phaser.GameObjects.Sprite(globalScene, 0, 16, "keyboard", "F.png"); } else { - shinyButtonElement = new Phaser.GameObjects.Sprite(gScene, 0, 4, gamepadType, gScene.inputController?.getIconForLatestInputRecorded(SettingKeyboard.Button_Cycle_Shiny)); - formButtonElement = new Phaser.GameObjects.Sprite(gScene, 0, 16, gamepadType, gScene.inputController?.getIconForLatestInputRecorded(SettingKeyboard.Button_Cycle_Form)); + shinyButtonElement = new Phaser.GameObjects.Sprite(globalScene, 0, 4, gamepadType, globalScene.inputController?.getIconForLatestInputRecorded(SettingKeyboard.Button_Cycle_Shiny)); + formButtonElement = new Phaser.GameObjects.Sprite(globalScene, 0, 16, gamepadType, globalScene.inputController?.getIconForLatestInputRecorded(SettingKeyboard.Button_Cycle_Form)); } hallofFameInstructionContainer.add([ shinyButtonText, shinyButtonElement ]); @@ -225,7 +225,7 @@ export default class RunInfoUiHandler extends UiHandler { this.runResultContainer.add(runResultText); if (!this.isVictory) { - const enemyContainer = gScene.add.container(0, 0); + const enemyContainer = globalScene.add.container(0, 0); // Wild - Single and Doubles if (this.runInfo.battleType === BattleType.WILD || (this.runInfo.battleType === BattleType.MYSTERY_ENCOUNTER && !this.runInfo.trainer)) { switch (this.runInfo.enemyParty.length) { @@ -255,7 +255,7 @@ export default class RunInfoUiHandler extends UiHandler { private parseRunStatus() { const runStatusText = addTextObject(6, 5, `${i18next.t("saveSlotSelectUiHandler:wave")} ${this.runInfo.waveIndex} - ${getBiomeName(this.runInfo.arena.biome)}`, TextStyle.WINDOW, { fontSize : "65px", lineSpacing: 0.1 }); - const enemyContainer = gScene.add.container(0, 0); + const enemyContainer = globalScene.add.container(0, 0); this.runResultContainer.add(enemyContainer); if (this.runInfo.battleType === BattleType.WILD) { if (this.runInfo.enemyParty.length === 1) { @@ -267,7 +267,7 @@ export default class RunInfoUiHandler extends UiHandler { this.showTrainerSprites(enemyContainer); const row_limit = 3; this.runInfo.enemyParty.forEach((p, i) => { - const pokeball = gScene.add.sprite(0, 0, "pb"); + const pokeball = globalScene.add.sprite(0, 0, "pb"); pokeball.setFrame(getPokeballAtlasKey(p.pokeball)); pokeball.setScale(0.5); pokeball.setPosition(52 + ((i % row_limit) * 8), (i <= 2) ? 18 : 25); @@ -282,20 +282,20 @@ export default class RunInfoUiHandler extends UiHandler { trainerName = trainerObj.getName(0, true); } const boxString = i18next.t(trainerObj.variant !== TrainerVariant.DOUBLE ? "battle:trainerAppeared" : "battle:trainerAppearedDouble", { trainerName: trainerName }).replace(/\n/g, " "); - const descContainer = gScene.add.container(0, 0); + const descContainer = globalScene.add.container(0, 0); const textBox = addTextObject(0, 0, boxString, TextStyle.WINDOW, { fontSize : "35px", wordWrap: { width: 200 }}); descContainer.add(textBox); descContainer.setPosition(52, 29); this.runResultContainer.add(descContainer); } else if (this.runInfo.battleType === BattleType.MYSTERY_ENCOUNTER) { - const encounterExclaim = gScene.add.sprite(0, 0, "encounter_exclaim"); + const encounterExclaim = globalScene.add.sprite(0, 0, "encounter_exclaim"); encounterExclaim.setPosition(34, 26); encounterExclaim.setScale(0.65); - const subSprite = gScene.add.sprite(56, -106, "pkmn__sub"); + const subSprite = globalScene.add.sprite(56, -106, "pkmn__sub"); subSprite.setScale(0.65); subSprite.setPosition(34, 46); - const mysteryEncounterTitle = i18next.t(gScene.getMysteryEncounter(this.runInfo.mysteryEncounterType as MysteryEncounterType, true).localizationKey + ":title"); - const descContainer = gScene.add.container(0, 0); + const mysteryEncounterTitle = i18next.t(globalScene.getMysteryEncounter(this.runInfo.mysteryEncounterType as MysteryEncounterType, true).localizationKey + ":title"); + const descContainer = globalScene.add.container(0, 0); const textBox = addTextObject(0, 0, mysteryEncounterTitle, TextStyle.WINDOW, { fontSize : "45px", wordWrap: { width: 160 }}); descContainer.add(textBox); descContainer.setPosition(47, 37); @@ -311,14 +311,14 @@ export default class RunInfoUiHandler extends UiHandler { * @param enemyContainer - container holding enemy visual and level information */ private parseWildSingleDefeat(enemyContainer: Phaser.GameObjects.Container) { - const enemyIconContainer = gScene.add.container(0, 0); + const enemyIconContainer = globalScene.add.container(0, 0); const enemyData = this.runInfo.enemyParty[0]; const bossStatus = enemyData.boss; enemyData.boss = false; enemyData["player"] = true; //addPokemonIcon() throws an error if the Pokemon used is a boss const enemy = enemyData.toPokemon(); - const enemyIcon = gScene.addPokemonIcon(enemy, 0, 0, 0, 0); + const enemyIcon = globalScene.addPokemonIcon(enemy, 0, 0, 0, 0); const enemyLevelStyle = bossStatus ? TextStyle.PARTY_RED : TextStyle.PARTY; const enemyLevel = addTextObject(36, 26, `${i18next.t("saveSlotSelectUiHandler:lv")}${Utils.formatLargeNumber(enemy.level, 1000)}`, enemyLevelStyle, { fontSize: "44px", color: "#f8f8f8" }); enemyLevel.setShadow(0, 0, undefined); @@ -338,12 +338,12 @@ export default class RunInfoUiHandler extends UiHandler { */ private parseWildDoubleDefeat(enemyContainer: Phaser.GameObjects.Container) { this.runInfo.enemyParty.forEach((enemyData, e) => { - const enemyIconContainer = gScene.add.container(0, 0); + const enemyIconContainer = globalScene.add.container(0, 0); const bossStatus = enemyData.boss; enemyData.boss = false; enemyData["player"] = true; const enemy = enemyData.toPokemon(); - const enemyIcon = gScene.addPokemonIcon(enemy, 0, 0, 0, 0); + const enemyIcon = globalScene.addPokemonIcon(enemy, 0, 0, 0, 0); const enemyLevel = addTextObject(36, 26, `${i18next.t("saveSlotSelectUiHandler:lv")}${Utils.formatLargeNumber(enemy.level, 1000)}`, bossStatus ? TextStyle.PARTY_RED : TextStyle.PARTY, { fontSize: "44px", color: "#f8f8f8" }); enemyLevel.setShadow(0, 0, undefined); enemyLevel.setStroke("#424242", 14); @@ -368,12 +368,12 @@ export default class RunInfoUiHandler extends UiHandler { // Loads trainer assets on demand, as they are not loaded by default in the scene tObj.config.loadAssets(this.runInfo.trainer.variant).then(() => { const tObjSpriteKey = tObj.config.getSpriteKey(this.runInfo.trainer.variant === TrainerVariant.FEMALE, false); - const tObjSprite = gScene.add.sprite(0, 5, tObjSpriteKey); + const tObjSprite = globalScene.add.sprite(0, 5, tObjSpriteKey); if (this.runInfo.trainer.variant === TrainerVariant.DOUBLE && !tObj.config.doubleOnly) { - const doubleContainer = gScene.add.container(5, 8); + const doubleContainer = globalScene.add.container(5, 8); tObjSprite.setPosition(-3, -3); const tObjPartnerSpriteKey = tObj.config.getSpriteKey(true, true); - const tObjPartnerSprite = gScene.add.sprite(5, -3, tObjPartnerSpriteKey); + const tObjPartnerSprite = globalScene.add.sprite(5, -3, tObjPartnerSpriteKey); // Double Trainers have smaller sprites than Single Trainers if (this.runDisplayMode === RunDisplayMode.RUN_HISTORY) { tObjPartnerSprite.setScale(0.20); @@ -424,16 +424,16 @@ export default class RunInfoUiHandler extends UiHandler { // Creates the Pokemon icons + level information and adds it to enemyContainer // 2 Rows x 3 Columns - const enemyPartyContainer = gScene.add.container(0, 0); + const enemyPartyContainer = globalScene.add.container(0, 0); this.runInfo.enemyParty.forEach((enemyData, e) => { const pokemonRowHeight = Math.floor(e / 3); - const enemyIconContainer = gScene.add.container(0, 0); + const enemyIconContainer = globalScene.add.container(0, 0); enemyIconContainer.setScale(0.6); const isBoss = enemyData.boss; enemyData.boss = false; enemyData["player"] = true; const enemy = enemyData.toPokemon(); - const enemyIcon = gScene.addPokemonIcon(enemy, 0, 0, 0, 0); + const enemyIcon = globalScene.addPokemonIcon(enemy, 0, 0, 0, 0); // Applying Terastallizing Type tint to Pokemon icon // If the Pokemon is a fusion, it has two sprites and so, the tint has to be applied to each icon separately const enemySprite1 = enemyIcon.list[0] as Phaser.GameObjects.Sprite; @@ -504,19 +504,19 @@ export default class RunInfoUiHandler extends UiHandler { } // If the player achieves a personal best in Endless, the mode text will be tinted similarly to SSS luck to celebrate their achievement. - if ((this.runInfo.gameMode === GameModes.ENDLESS || this.runInfo.gameMode === GameModes.SPLICED_ENDLESS) && this.runInfo.waveIndex === gScene.gameData.gameStats.highestEndlessWave) { + if ((this.runInfo.gameMode === GameModes.ENDLESS || this.runInfo.gameMode === GameModes.SPLICED_ENDLESS) && this.runInfo.waveIndex === globalScene.gameData.gameStats.highestEndlessWave) { modeText.appendText(` [${i18next.t("runHistory:personalBest")}]`); modeText.setTint(0xffef5c, 0x47ff69, 0x6b6bff, 0xff6969); } // Duration + Money - const runInfoTextContainer = gScene.add.container(0, 0); + const runInfoTextContainer = globalScene.add.container(0, 0); // Japanese is set to a greater line spacing of 35px in addBBCodeTextObject() if lineSpacing < 12. const lineSpacing = (i18next.resolvedLanguage === "ja") ? 12 : 3; const runInfoText = addBBCodeTextObject(7, 0, "", TextStyle.WINDOW, { fontSize: "50px", lineSpacing: lineSpacing }); const runTime = Utils.getPlayTimeString(this.runInfo.playTime); runInfoText.appendText(`${i18next.t("runHistory:runLength")}: ${runTime}`, false); - const runMoney = Utils.formatMoney(gScene.moneyFormat, this.runInfo.money); + const runMoney = Utils.formatMoney(globalScene.moneyFormat, this.runInfo.money); runInfoText.appendText(`[color=${getTextColor(TextStyle.MONEY)}]${i18next.t("battleScene:moneyOwned", { formattedMoney : runMoney })}[/color]`); runInfoText.setPosition(7, 70); runInfoTextContainer.add(runInfoText); @@ -539,7 +539,7 @@ export default class RunInfoUiHandler extends UiHandler { if (this.runInfo.modifiers.length) { let visibleModifierIndex = 0; - const modifierIconsContainer = gScene.add.container(8, (this.runInfo.gameMode === GameModes.CHALLENGE) ? 20 : 15); + const modifierIconsContainer = globalScene.add.container(8, (this.runInfo.gameMode === GameModes.CHALLENGE) ? 20 : 15); modifierIconsContainer.setScale(0.45); for (const m of this.runInfo.modifiers) { const modifier = m.toModifier(this.modifiersModule[m.className]); @@ -608,13 +608,13 @@ export default class RunInfoUiHandler extends UiHandler { private parsePartyInfo(): void { const party = this.runInfo.party; const currentLanguage = i18next.resolvedLanguage ?? "en"; - const windowHeight = ((gScene.game.canvas.height / 6) - 23) / 6; + const windowHeight = ((globalScene.game.canvas.height / 6) - 23) / 6; party.forEach((p: PokemonData, i: integer) => { - const pokemonInfoWindow = new RoundRectangle(gScene, 0, 14, (this.statsBgWidth * 2) + 10, windowHeight - 2, 3); + const pokemonInfoWindow = new RoundRectangle(globalScene, 0, 14, (this.statsBgWidth * 2) + 10, windowHeight - 2, 3); const pokemon = p.toPokemon(); - const pokemonInfoContainer = gScene.add.container(this.statsBgWidth + 5, (windowHeight - 0.5) * i); + const pokemonInfoContainer = globalScene.add.container(this.statsBgWidth + 5, (windowHeight - 0.5) * i); const types = pokemon.getTypes(); const type1 = getTypeRgb(types[0]); @@ -623,8 +623,8 @@ export default class RunInfoUiHandler extends UiHandler { const bgColor = type1Color.clone().darken(45); pokemonInfoWindow.setFillStyle(bgColor.color); - const iconContainer = gScene.add.container(0, 0); - const icon = gScene.addPokemonIcon(pokemon, 0, 0, 0, 0); + const iconContainer = globalScene.add.container(0, 0); + const icon = globalScene.addPokemonIcon(pokemon, 0, 0, 0, 0); icon.setScale(0.75); icon.setPosition(-99, 1); const type2 = types[1] ? getTypeRgb(types[1]) : undefined; @@ -634,7 +634,7 @@ export default class RunInfoUiHandler extends UiHandler { this.getUi().bringToTop(icon); // Contains Name, Level + Nature, Ability, Passive - const pokeInfoTextContainer = gScene.add.container(-85, 3.5); + const pokeInfoTextContainer = globalScene.add.container(-85, 3.5); const textContainerFontSize = "34px"; // This checks if the Pokemon's nature has been overwritten during the run and displays the change accurately const pNature = pokemon.getNature(); @@ -661,7 +661,7 @@ export default class RunInfoUiHandler extends UiHandler { // Pokemon Stats // Colored Arrows (Red/Blue) are placed by stats that are boosted from natures - const pokeStatTextContainer = gScene.add.container(-35, 6); + const pokeStatTextContainer = globalScene.add.container(-35, 6); const pStats : string[] = []; pokemon.stats.forEach((element) => pStats.push(Utils.formatFancyLargeNumber(element, 1))); for (let i = 0; i < pStats.length; i++) { @@ -688,9 +688,9 @@ export default class RunInfoUiHandler extends UiHandler { pokeStatTextContainer.add(pokeStatText2); // Shiny + Fusion Status - const marksContainer = gScene.add.container(0, 0); + const marksContainer = globalScene.add.container(0, 0); if (pokemon.fusionSpecies) { - const splicedIcon = gScene.add.image(0, 0, "icon_spliced"); + const splicedIcon = globalScene.add.image(0, 0, "icon_spliced"); splicedIcon.setScale(0.35); splicedIcon.setOrigin(0, 0); pokemon.isShiny() ? splicedIcon.setPositionRelative(pokeInfoTextContainer, 35, 0) : splicedIcon.setPositionRelative(pokeInfoTextContainer, 28, 0); @@ -699,7 +699,7 @@ export default class RunInfoUiHandler extends UiHandler { } if (pokemon.isShiny()) { const doubleShiny = pokemon.isFusion() && pokemon.shiny && pokemon.fusionShiny; - const shinyStar = gScene.add.image(0, 0, `shiny_star_small${doubleShiny ? "_1" : ""}`); + const shinyStar = globalScene.add.image(0, 0, `shiny_star_small${doubleShiny ? "_1" : ""}`); shinyStar.setOrigin(0, 0); shinyStar.setScale(0.65); shinyStar.setPositionRelative(pokeInfoTextContainer, 28, 0); @@ -707,7 +707,7 @@ export default class RunInfoUiHandler extends UiHandler { marksContainer.add(shinyStar); this.getUi().bringToTop(shinyStar); if (doubleShiny) { - const fusionShinyStar = gScene.add.image(0, 0, "shiny_star_small_2"); + const fusionShinyStar = globalScene.add.image(0, 0, "shiny_star_small_2"); fusionShinyStar.setOrigin(0, 0); fusionShinyStar.setScale(0.5); fusionShinyStar.setPosition(shinyStar.x + 1, shinyStar.y + 1); @@ -720,14 +720,14 @@ export default class RunInfoUiHandler extends UiHandler { // Pokemon Moveset // Need to check if dynamically typed moves const pokemonMoveset = pokemon.getMoveset(); - const movesetContainer = gScene.add.container(70, -29); + const movesetContainer = globalScene.add.container(70, -29); const pokemonMoveBgs : Phaser.GameObjects.NineSlice[] = []; const pokemonMoveLabels : Phaser.GameObjects.Text[] = []; const movePos = [[ -6.5, 35.5 ], [ 37, 35.5 ], [ -6.5, 43.5 ], [ 37, 43.5 ]]; for (let m = 0; m < pokemonMoveset?.length; m++) { - const moveContainer = gScene.add.container(movePos[m][0], movePos[m][1]); + const moveContainer = globalScene.add.container(movePos[m][0], movePos[m][1]); moveContainer.setScale(0.5); - const moveBg = gScene.add.nineslice(0, 0, "type_bgs", "unknown", 85, 15, 2, 2, 2, 2); + const moveBg = globalScene.add.nineslice(0, 0, "type_bgs", "unknown", 85, 15, 2, 2, 2, 2); moveBg.setOrigin(1, 0); const moveLabel = addTextObject(-moveBg.width / 2, 2, "-", TextStyle.PARTY); moveLabel.setOrigin(0.5, 0); @@ -745,7 +745,7 @@ export default class RunInfoUiHandler extends UiHandler { // Pokemon Held Items - not displayed by default // Endless/Endless Spliced have a different scale because Pokemon tend to accumulate more items in these runs. const heldItemsScale = (this.runInfo.gameMode === GameModes.SPLICED_ENDLESS || this.runInfo.gameMode === GameModes.ENDLESS) ? 0.25 : 0.5; - const heldItemsContainer = gScene.add.container(-82, 2); + const heldItemsContainer = globalScene.add.container(-82, 2); const heldItemsList : Modifier.PokemonHeldItemModifier[] = []; if (this.runInfo.modifiers.length) { for (const m of this.runInfo.modifiers) { @@ -822,13 +822,13 @@ export default class RunInfoUiHandler extends UiHandler { * Shows the ending art. */ private createVictorySplash(): void { - this.endCardContainer = gScene.add.container(0, 0); - const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET; + this.endCardContainer = globalScene.add.container(0, 0); + const genderIndex = globalScene.gameData.gender ?? PlayerGender.UNSET; const isFemale = genderIndex === PlayerGender.FEMALE; - const endCard = gScene.add.image(0, 0, `end_${isFemale ? "f" : "m"}`); + const endCard = globalScene.add.image(0, 0, `end_${isFemale ? "f" : "m"}`); endCard.setOrigin(0); endCard.setScale(0.5); - const text = addTextObject(gScene.game.canvas.width / 12, (gScene.game.canvas.height / 6) - 16, i18next.t("battle:congratulations"), TextStyle.SUMMARY, { fontSize: "128px" }); + const text = addTextObject(globalScene.game.canvas.width / 12, (globalScene.game.canvas.height / 6) - 16, i18next.t("battle:congratulations"), TextStyle.SUMMARY, { fontSize: "128px" }); text.setOrigin(0.5); this.endCardContainer.add(endCard); this.endCardContainer.add(text); @@ -839,22 +839,22 @@ export default class RunInfoUiHandler extends UiHandler { * This could be adapted into a public-facing method for victory screens. Perhaps. */ private createHallofFame(): void { - const genderIndex = gScene.gameData.gender ?? PlayerGender.UNSET; + const genderIndex = globalScene.gameData.gender ?? PlayerGender.UNSET; const isFemale = genderIndex === PlayerGender.FEMALE; const genderStr = PlayerGender[genderIndex].toLowerCase(); // Issue Note (08-05-2024): It seems as if fused pokemon do not appear with the averaged color b/c pokemonData's loadAsset requires there to be some active battle? // As an alternative, the icons of the second/bottom fused Pokemon have been placed next to their fellow fused Pokemon in Hall of Fame - this.hallofFameContainer = gScene.add.container(0, 0); + this.hallofFameContainer = globalScene.add.container(0, 0); // Thank you Hayuna for the code - const endCard = gScene.add.image(0, 0, `end_${isFemale ? "f" : "m"}`); + const endCard = globalScene.add.image(0, 0, `end_${isFemale ? "f" : "m"}`); endCard.setOrigin(0); endCard.setPosition(-1, -1); endCard.setScale(0.5); const endCardCoords = endCard.getBottomCenter(); const overlayColor = isFemale ? "red" : "blue"; - const hallofFameBg = gScene.add.image(0, 0, "hall_of_fame_" + overlayColor); + const hallofFameBg = globalScene.add.image(0, 0, "hall_of_fame_" + overlayColor); hallofFameBg.setPosition(159, 89); - hallofFameBg.setSize(gScene.game.canvas.width, gScene.game.canvas.height + 10); + hallofFameBg.setSize(globalScene.game.canvas.width, globalScene.game.canvas.height + 10); hallofFameBg.setAlpha(0.8); this.hallofFameContainer.add(endCard); this.hallofFameContainer.add(hallofFameBg); @@ -870,8 +870,8 @@ export default class RunInfoUiHandler extends UiHandler { const formIndex = pkmn.formIndex; const variant = pkmn.variant; const species = pkmn.getSpeciesForm(); - const pokemonSprite: Phaser.GameObjects.Sprite = gScene.add.sprite(60 + 40 * i, 40 + row * 80, "pkmn__sub"); - pokemonSprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); + const pokemonSprite: Phaser.GameObjects.Sprite = globalScene.add.sprite(60 + 40 * i, 40 + row * 80, "pkmn__sub"); + pokemonSprite.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); this.hallofFameContainer.add(pokemonSprite); const speciesLoaded: Map = new Map(); speciesLoaded.set(id, false); @@ -886,7 +886,7 @@ export default class RunInfoUiHandler extends UiHandler { pokemonSprite.setVisible(true); }); if (pkmn.isFusion()) { - const fusionIcon = gScene.add.sprite(80 + 40 * i, 50 + row * 80, pkmn.getFusionIconAtlasKey()); + const fusionIcon = globalScene.add.sprite(80 + 40 * i, 50 + row * 80, pkmn.getFusionIconAtlasKey()); fusionIcon.setName("sprite-fusion-icon"); fusionIcon.setOrigin(0.5, 0); fusionIcon.setFrame(pkmn.getFusionIconId(true)); diff --git a/src/ui/save-slot-select-ui-handler.ts b/src/ui/save-slot-select-ui-handler.ts index 07719237095..d3c8c53d064 100644 --- a/src/ui/save-slot-select-ui-handler.ts +++ b/src/ui/save-slot-select-ui-handler.ts @@ -1,5 +1,5 @@ import i18next from "i18next"; -import BattleScene, { gScene } from "#app/battle-scene"; +import BattleScene, { globalScene } from "#app/battle-scene"; import { Button } from "#enums/buttons"; import { GameMode } from "../game-mode"; import * as Modifier from "../modifier/modifier"; @@ -46,20 +46,20 @@ export default class SaveSlotSelectUiHandler extends MessageUiHandler { setup() { const ui = this.getUi(); - this.saveSlotSelectContainer = gScene.add.container(0, 0); + this.saveSlotSelectContainer = globalScene.add.container(0, 0); this.saveSlotSelectContainer.setVisible(false); ui.add(this.saveSlotSelectContainer); - const loadSessionBg = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, -gScene.game.canvas.height / 6, 0x006860); + const loadSessionBg = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width / 6, -globalScene.game.canvas.height / 6, 0x006860); loadSessionBg.setOrigin(0, 0); this.saveSlotSelectContainer.add(loadSessionBg); - this.sessionSlotsContainerInitialY = -gScene.game.canvas.height / 6 + 8; + this.sessionSlotsContainerInitialY = -globalScene.game.canvas.height / 6 + 8; - this.sessionSlotsContainer = gScene.add.container(8, this.sessionSlotsContainerInitialY); + this.sessionSlotsContainer = globalScene.add.container(8, this.sessionSlotsContainerInitialY); this.saveSlotSelectContainer.add(this.sessionSlotsContainer); - this.saveSlotSelectMessageBoxContainer = gScene.add.container(0, 0); + this.saveSlotSelectMessageBoxContainer = globalScene.add.container(0, 0); this.saveSlotSelectMessageBoxContainer.setVisible(false); this.saveSlotSelectContainer.add(this.saveSlotSelectMessageBoxContainer); @@ -122,9 +122,9 @@ export default class SaveSlotSelectUiHandler extends MessageUiHandler { if (this.sessionSlots[cursor].hasData) { ui.showText(i18next.t("saveSlotSelectUiHandler:overwriteData"), null, () => { ui.setOverlayMode(Mode.CONFIRM, () => { - gScene.gameData.deleteSession(cursor).then(response => { + globalScene.gameData.deleteSession(cursor).then(response => { if (response === false) { - gScene.reset(true); + globalScene.reset(true); } else { saveAndCallback(); } @@ -168,7 +168,7 @@ export default class SaveSlotSelectUiHandler extends MessageUiHandler { break; case Button.RIGHT: if (this.sessionSlots[cursorPosition].hasData && this.sessionSlots[cursorPosition].saveData) { - gScene.ui.setOverlayMode(Mode.RUN_INFO, this.sessionSlots[cursorPosition].saveData, RunDisplayMode.SESSION_PREVIEW); + globalScene.ui.setOverlayMode(Mode.RUN_INFO, this.sessionSlots[cursorPosition].saveData, RunDisplayMode.SESSION_PREVIEW); success = true; } } @@ -186,7 +186,7 @@ export default class SaveSlotSelectUiHandler extends MessageUiHandler { populateSessionSlots() { for (let s = 0; s < SESSION_SLOTS_COUNT; s++) { const sessionSlot = new SessionSlot(s); - gScene.add.existing(sessionSlot); + globalScene.add.existing(sessionSlot); this.sessionSlotsContainer.add(sessionSlot); this.sessionSlots.push(sessionSlot); sessionSlot.load().then((success) => { @@ -223,9 +223,9 @@ export default class SaveSlotSelectUiHandler extends MessageUiHandler { const changed = super.setCursor(cursor); if (!this.cursorObj) { - this.cursorObj = gScene.add.container(0, 0); - const cursorBox = gScene.add.nineslice(0, 0, "select_cursor_highlight_thick", undefined, 296, 44, 6, 6, 6, 6); - const rightArrow = gScene.add.image(0, 0, "cursor"); + this.cursorObj = globalScene.add.container(0, 0); + const cursorBox = globalScene.add.nineslice(0, 0, "select_cursor_highlight_thick", undefined, 296, 44, 6, 6, 6, 6); + const rightArrow = globalScene.add.image(0, 0, "cursor"); rightArrow.setPosition(160, 0); rightArrow.setName("rightArrow"); this.cursorObj.add([ cursorBox, rightArrow ]); @@ -286,7 +286,7 @@ export default class SaveSlotSelectUiHandler extends MessageUiHandler { if (changed) { this.scrollCursor = scrollCursor; this.setCursor(this.cursor, prevSlotIndex); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.sessionSlotsContainer, y: this.sessionSlotsContainerInitialY - 56 * scrollCursor, duration: Utils.fixedInt(325), @@ -327,7 +327,7 @@ class SessionSlot extends Phaser.GameObjects.Container { public saveData: SessionSaveData; constructor(slotId: integer) { - super(gScene, 0, slotId * 56); + super(globalScene, 0, slotId * 56); this.slotId = slotId; @@ -355,13 +355,13 @@ class SessionSlot extends Phaser.GameObjects.Container { const playTimeLabel = addTextObject(8, 33, Utils.getPlayTimeString(data.playTime), TextStyle.WINDOW); this.add(playTimeLabel); - const pokemonIconsContainer = gScene.add.container(144, 4); + const pokemonIconsContainer = globalScene.add.container(144, 4); data.party.forEach((p: PokemonData, i: integer) => { - const iconContainer = gScene.add.container(26 * i, 0); + const iconContainer = globalScene.add.container(26 * i, 0); iconContainer.setScale(0.75); const pokemon = p.toPokemon(); - const icon = gScene.addPokemonIcon(pokemon, 0, 0, 0, 0); + const icon = globalScene.addPokemonIcon(pokemon, 0, 0, 0, 0); const text = addTextObject(32, 20, `${i18next.t("saveSlotSelectUiHandler:lv")}${Utils.formatLargeNumber(pokemon.level, 1000)}`, TextStyle.PARTY, { fontSize: "54px", color: "#f8f8f8" }); text.setShadow(0, 0, undefined); @@ -378,7 +378,7 @@ class SessionSlot extends Phaser.GameObjects.Container { this.add(pokemonIconsContainer); - const modifierIconsContainer = gScene.add.container(148, 30); + const modifierIconsContainer = globalScene.add.container(148, 30); modifierIconsContainer.setScale(0.5); let visibleModifierIndex = 0; for (const m of data.modifiers) { @@ -401,7 +401,7 @@ class SessionSlot extends Phaser.GameObjects.Container { load(): Promise { return new Promise(resolve => { - gScene.gameData.getSession(this.slotId).then(async sessionData => { + globalScene.gameData.getSession(this.slotId).then(async sessionData => { // Ignore the results if the view was exited if (!this.active) { return; diff --git a/src/ui/saving-icon-handler.ts b/src/ui/saving-icon-handler.ts index d5538ed2b08..2793194c151 100644 --- a/src/ui/saving-icon-handler.ts +++ b/src/ui/saving-icon-handler.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import * as Utils from "../utils"; export default class SavingIconHandler extends Phaser.GameObjects.Container { @@ -8,11 +8,11 @@ export default class SavingIconHandler extends Phaser.GameObjects.Container { private shown: boolean; constructor() { - super(gScene, gScene.game.canvas.width / 6 - 4, gScene.game.canvas.height / 6 - 4); + super(globalScene, globalScene.game.canvas.width / 6 - 4, globalScene.game.canvas.height / 6 - 4); } setup(): void { - this.icon = gScene.add.sprite(0, 0, "saving_icon"); + this.icon = globalScene.add.sprite(0, 0, "saving_icon"); this.icon.setOrigin(1, 1); this.add(this.icon); @@ -33,13 +33,13 @@ export default class SavingIconHandler extends Phaser.GameObjects.Container { this.animActive = true; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, alpha: 1, duration: Utils.fixedInt(250), ease: "Sine.easeInOut", onComplete: () => { - gScene.time.delayedCall(Utils.fixedInt(500), () => { + globalScene.time.delayedCall(Utils.fixedInt(500), () => { this.animActive = false; if (!this.shown) { this.hide(); @@ -61,7 +61,7 @@ export default class SavingIconHandler extends Phaser.GameObjects.Container { this.animActive = true; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this, alpha: 0, duration: Utils.fixedInt(250), diff --git a/src/ui/scroll-bar.ts b/src/ui/scroll-bar.ts index 426736be4e7..ffa341afceb 100644 --- a/src/ui/scroll-bar.ts +++ b/src/ui/scroll-bar.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; /** * A vertical scrollbar element that resizes dynamically based on the current scrolling @@ -21,7 +21,7 @@ export class ScrollBar extends Phaser.GameObjects.Container { * @param maxRows the maximum number of rows that can be shown at once */ constructor(x: number, y: number, width: number, height: number, maxRows: number) { - super(gScene, x, y); + super(globalScene, x, y); this.maxRows = maxRows; this.totalRows = maxRows; @@ -30,15 +30,15 @@ export class ScrollBar extends Phaser.GameObjects.Container { const borderSize = 2; width = Math.max(width, 4); - this.bg = gScene.add.nineslice(0, 0, "scroll_bar", undefined, width, height, borderSize, borderSize, borderSize, borderSize); + this.bg = globalScene.add.nineslice(0, 0, "scroll_bar", undefined, width, height, borderSize, borderSize, borderSize, borderSize); this.bg.setOrigin(0, 0); this.add(this.bg); - this.handleBody = gScene.add.rectangle(1, 1, width - 2, 4, 0xaaaaaa); + this.handleBody = globalScene.add.rectangle(1, 1, width - 2, 4, 0xaaaaaa); this.handleBody.setOrigin(0, 0); this.add(this.handleBody); - this.handleBottom = gScene.add.nineslice(1, 1, "scroll_bar_handle", undefined, width - 2, 2, 2, 0, 0, 0); + this.handleBottom = globalScene.add.nineslice(1, 1, "scroll_bar_handle", undefined, width - 2, 2, 2, 0, 0, 0); this.handleBottom.setOrigin(0, 0); this.add(this.handleBottom); } diff --git a/src/ui/settings/abstract-binding-ui-handler.ts b/src/ui/settings/abstract-binding-ui-handler.ts index 1b42e2f38cd..6b4e0b13330 100644 --- a/src/ui/settings/abstract-binding-ui-handler.ts +++ b/src/ui/settings/abstract-binding-ui-handler.ts @@ -5,7 +5,7 @@ import { addTextObject, TextStyle } from "../text"; import { Button } from "#enums/buttons"; import { NavigationManager } from "#app/ui/settings/navigationMenu"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; type CancelFn = (succes?: boolean) => boolean; @@ -61,8 +61,8 @@ export default abstract class AbstractBindingUiHandler extends UiHandler { */ setup() { const ui = this.getUi(); - this.optionSelectContainer = gScene.add.container(0, 0); - this.actionsContainer = gScene.add.container(0, 0); + this.optionSelectContainer = globalScene.add.container(0, 0); + this.actionsContainer = globalScene.add.container(0, 0); // Initially, containers are not visible. this.optionSelectContainer.setVisible(false); this.actionsContainer.setVisible(false); @@ -72,11 +72,11 @@ export default abstract class AbstractBindingUiHandler extends UiHandler { ui.add(this.actionsContainer); // Setup backgrounds and text objects for UI. - this.titleBg = addWindow((gScene.game.canvas.width / 6) - this.getWindowWidth(), -(gScene.game.canvas.height / 6) + 28 + 21, this.getWindowWidth(), 24); + this.titleBg = addWindow((globalScene.game.canvas.width / 6) - this.getWindowWidth(), -(globalScene.game.canvas.height / 6) + 28 + 21, this.getWindowWidth(), 24); this.titleBg.setOrigin(0.5); this.optionSelectContainer.add(this.titleBg); - this.actionBg = addWindow((gScene.game.canvas.width / 6) - this.getWindowWidth(), -(gScene.game.canvas.height / 6) + this.getWindowHeight() + 28 + 21 + 21, this.getWindowWidth(), 24); + this.actionBg = addWindow((globalScene.game.canvas.width / 6) - this.getWindowWidth(), -(globalScene.game.canvas.height / 6) + this.getWindowHeight() + 28 + 21 + 21, this.getWindowWidth(), 24); this.actionBg.setOrigin(0.5); this.actionsContainer.add(this.actionBg); @@ -91,7 +91,7 @@ export default abstract class AbstractBindingUiHandler extends UiHandler { this.timerText.setPositionRelative(this.unlockText, (this.unlockText.width / 6) + 5, 0); this.optionSelectContainer.add(this.timerText); - this.optionSelectBg = addWindow((gScene.game.canvas.width / 6) - this.getWindowWidth(), -(gScene.game.canvas.height / 6) + this.getWindowHeight() + 28, this.getWindowWidth(), this.getWindowHeight()); + this.optionSelectBg = addWindow((globalScene.game.canvas.width / 6) - this.getWindowWidth(), -(globalScene.game.canvas.height / 6) + this.getWindowHeight() + 28, this.getWindowWidth(), this.getWindowHeight()); this.optionSelectBg.setOrigin(0.5); this.optionSelectContainer.add(this.optionSelectBg); diff --git a/src/ui/settings/abstract-control-settings-ui-handler.ts b/src/ui/settings/abstract-control-settings-ui-handler.ts index 311d2e13f9b..e7ae290cb04 100644 --- a/src/ui/settings/abstract-control-settings-ui-handler.ts +++ b/src/ui/settings/abstract-control-settings-ui-handler.ts @@ -9,7 +9,7 @@ import NavigationMenu, { NavigationManager } from "#app/ui/settings/navigationMe import { Device } from "#enums/devices"; import { Button } from "#enums/buttons"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export interface InputsIcons { [key: string]: Phaser.GameObjects.Sprite; @@ -99,21 +99,21 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler const ui = this.getUi(); this.navigationIcons = {}; - this.settingsContainer = gScene.add.container(1, -(gScene.game.canvas.height / 6) + 1); + this.settingsContainer = globalScene.add.container(1, -(globalScene.game.canvas.height / 6) + 1); this.settingsContainer.setName(`settings-${this.titleSelected}`); - this.settingsContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); + this.settingsContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6), Phaser.Geom.Rectangle.Contains); this.navigationContainer = new NavigationMenu(0, 0); - this.optionsBg = addWindow(0, this.navigationContainer.height, (gScene.game.canvas.width / 6) - 2, (gScene.game.canvas.height / 6) - 16 - this.navigationContainer.height - 2); + this.optionsBg = addWindow(0, this.navigationContainer.height, (globalScene.game.canvas.width / 6) - 2, (globalScene.game.canvas.height / 6) - 16 - this.navigationContainer.height - 2); this.optionsBg.setOrigin(0, 0); - this.actionsBg = addWindow(0, (gScene.game.canvas.height / 6) - this.navigationContainer.height, (gScene.game.canvas.width / 6) - 2, 22); + this.actionsBg = addWindow(0, (globalScene.game.canvas.height / 6) - this.navigationContainer.height, (globalScene.game.canvas.width / 6) - 2, 22); this.actionsBg.setOrigin(0, 0); - const iconAction = gScene.add.sprite(0, 0, "keyboard"); + const iconAction = globalScene.add.sprite(0, 0, "keyboard"); iconAction.setOrigin(0, -0.1); iconAction.setPositionRelative(this.actionsBg, this.navigationContainer.width - 32, 4); this.navigationIcons["BUTTON_ACTION"] = iconAction; @@ -122,7 +122,7 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler actionText.setOrigin(0, 0.15); actionText.setPositionRelative(iconAction, -actionText.width / 6 - 2, 0); - const iconCancel = gScene.add.sprite(0, 0, "keyboard"); + const iconCancel = globalScene.add.sprite(0, 0, "keyboard"); iconCancel.setOrigin(0, -0.1); iconCancel.setPositionRelative(this.actionsBg, this.navigationContainer.width - 100, 4); this.navigationIcons["BUTTON_CANCEL"] = iconCancel; @@ -131,7 +131,7 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler cancelText.setOrigin(0, 0.15); cancelText.setPositionRelative(iconCancel, -cancelText.width / 6 - 2, 0); - const iconReset = gScene.add.sprite(0, 0, "keyboard"); + const iconReset = globalScene.add.sprite(0, 0, "keyboard"); iconReset.setOrigin(0, -0.1); iconReset.setPositionRelative(this.actionsBg, this.navigationContainer.width - 180, 4); this.navigationIcons["BUTTON_HOME"] = iconReset; @@ -156,7 +156,7 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler this.layout[config.padType] = new Map(); // Create a container for gamepad options in the scene, initially hidden. - const optionsContainer = gScene.add.container(0, 0); + const optionsContainer = globalScene.add.container(0, 0); optionsContainer.setVisible(false); // Gather all binding settings from the configuration. @@ -185,7 +185,7 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler // Convert the setting key from format 'Key_Name' to 'Key name' for display. const settingName = setting.replace(/\_/g, " "); - // Create and add a text object for the setting name to the gScene. + // Create and add a text object for the setting name to the scene. const isLock = this.settingBlacklisted.includes(this.setting[setting]); const labelStyle = isLock ? TextStyle.SETTINGS_LOCKED : TextStyle.SETTINGS_LABEL; let labelText: string; @@ -215,7 +215,7 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler continue; } // For null options, add an icon for the key. - const icon = gScene.add.sprite(0, 0, this.textureOverride ? this.textureOverride : config.padType); + const icon = globalScene.add.sprite(0, 0, this.textureOverride ? this.textureOverride : config.padType); icon.setOrigin(0, -0.15); inputsIcons[this.setting[setting]] = icon; optionsContainer.add(icon); @@ -289,7 +289,7 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler * @returns The active configuration for current device */ getActiveConfig(): InterfaceConfig { - return gScene.inputController.getActiveConfig(this.device); + return globalScene.inputController.getActiveConfig(this.device); } /** @@ -349,9 +349,9 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler this.navigationIcons[settingName].alpha = 1; continue; } - const icon = gScene.inputController?.getIconForLatestInputRecorded(settingName); + const icon = globalScene.inputController?.getIconForLatestInputRecorded(settingName); if (icon) { - const type = gScene.inputController?.getLastSourceType(); + const type = globalScene.inputController?.getLastSourceType(); this.navigationIcons[settingName].setTexture(type); this.navigationIcons[settingName].setFrame(icon); this.navigationIcons[settingName].alpha = 1; @@ -444,7 +444,7 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler // Handle cancel button press, reverting UI mode to previous state. success = true; NavigationManager.getInstance().reset(); - gScene.ui.revertMode(); + globalScene.ui.revertMode(); } else { const cursor = this.cursor + this.scrollCursor; // Calculate the absolute cursor position. const setting = this.setting[Object.keys(this.setting)[cursor]]; @@ -556,8 +556,8 @@ export default abstract class AbstractControlSettingsUiHandler extends UiHandler // Check if the cursor object exists, if not, create it. if (!this.cursorObj) { - const cursorWidth = (gScene.game.canvas.width / 6) - (this.scrollBar.visible ? 16 : 10); - this.cursorObj = gScene.add.nineslice(0, 0, "summary_moves_cursor", undefined, cursorWidth, 16, 1, 1, 1, 1); + const cursorWidth = (globalScene.game.canvas.width / 6) - (this.scrollBar.visible ? 16 : 10); + this.cursorObj = globalScene.add.nineslice(0, 0, "summary_moves_cursor", undefined, cursorWidth, 16, 1, 1, 1, 1); this.cursorObj.setOrigin(0, 0); // Set the origin to the top-left corner. this.optionsContainer.add(this.cursorObj); // Add the cursor to the options container. } diff --git a/src/ui/settings/abstract-settings-ui-handler.ts b/src/ui/settings/abstract-settings-ui-handler.ts index a54cbe1e8d2..9e6eb277720 100644 --- a/src/ui/settings/abstract-settings-ui-handler.ts +++ b/src/ui/settings/abstract-settings-ui-handler.ts @@ -9,7 +9,7 @@ import { InputsIcons } from "#app/ui/settings/abstract-control-settings-ui-handl import NavigationMenu, { NavigationManager } from "#app/ui/settings/navigationMenu"; import { Setting, SettingKeys, SettingType } from "#app/system/settings/settings"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; /** @@ -55,22 +55,22 @@ export default class AbstractSettingsUiHandler extends UiHandler { setup() { const ui = this.getUi(); - this.settingsContainer = gScene.add.container(1, -(gScene.game.canvas.height / 6) + 1); + this.settingsContainer = globalScene.add.container(1, -(globalScene.game.canvas.height / 6) + 1); this.settingsContainer.setName(`settings-${this.title}`); - this.settingsContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6 - 20), Phaser.Geom.Rectangle.Contains); + this.settingsContainer.setInteractive(new Phaser.Geom.Rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6 - 20), Phaser.Geom.Rectangle.Contains); this.navigationIcons = {}; this.navigationContainer = new NavigationMenu(0, 0); - this.optionsBg = addWindow(0, this.navigationContainer.height, (gScene.game.canvas.width / 6) - 2, (gScene.game.canvas.height / 6) - 16 - this.navigationContainer.height - 2); + this.optionsBg = addWindow(0, this.navigationContainer.height, (globalScene.game.canvas.width / 6) - 2, (globalScene.game.canvas.height / 6) - 16 - this.navigationContainer.height - 2); this.optionsBg.setName("window-options-bg"); this.optionsBg.setOrigin(0, 0); - const actionsBg = addWindow(0, (gScene.game.canvas.height / 6) - this.navigationContainer.height, (gScene.game.canvas.width / 6) - 2, 22); + const actionsBg = addWindow(0, (globalScene.game.canvas.height / 6) - this.navigationContainer.height, (globalScene.game.canvas.width / 6) - 2, 22); actionsBg.setOrigin(0, 0); - const iconAction = gScene.add.sprite(0, 0, "keyboard"); + const iconAction = globalScene.add.sprite(0, 0, "keyboard"); iconAction.setOrigin(0, -0.1); iconAction.setPositionRelative(actionsBg, this.navigationContainer.width - 32, 4); this.navigationIcons["BUTTON_ACTION"] = iconAction; @@ -79,7 +79,7 @@ export default class AbstractSettingsUiHandler extends UiHandler { actionText.setOrigin(0, 0.15); actionText.setPositionRelative(iconAction, -actionText.width / 6 - 2, 0); - const iconCancel = gScene.add.sprite(0, 0, "keyboard"); + const iconCancel = globalScene.add.sprite(0, 0, "keyboard"); iconCancel.setOrigin(0, -0.1); iconCancel.setPositionRelative(actionsBg, this.navigationContainer.width - 100, 4); this.navigationIcons["BUTTON_CANCEL"] = iconCancel; @@ -88,7 +88,7 @@ export default class AbstractSettingsUiHandler extends UiHandler { cancelText.setOrigin(0, 0.15); cancelText.setPositionRelative(iconCancel, -cancelText.width / 6 - 2, 0); - this.optionsContainer = gScene.add.container(0, 0); + this.optionsContainer = globalScene.add.container(0, 0); this.settingLabels = []; this.optionValueLabels = []; @@ -163,9 +163,9 @@ export default class AbstractSettingsUiHandler extends UiHandler { this.navigationIcons[settingName].alpha = 1; continue; } - const icon = gScene.inputController?.getIconForLatestInputRecorded(settingName); + const icon = globalScene.inputController?.getIconForLatestInputRecorded(settingName); if (icon) { - const type = gScene.inputController?.getLastSourceType(); + const type = globalScene.inputController?.getLastSourceType(); this.navigationIcons[settingName].setTexture(type); this.navigationIcons[settingName].setFrame(icon); this.navigationIcons[settingName].alpha = 1; @@ -220,7 +220,7 @@ export default class AbstractSettingsUiHandler extends UiHandler { success = true; NavigationManager.getInstance().reset(); // Reverts UI to its previous state on cancel. - gScene.ui.revertMode(); + globalScene.ui.revertMode(); } else { const cursor = this.cursor + this.scrollCursor; switch (button) { @@ -296,7 +296,7 @@ export default class AbstractSettingsUiHandler extends UiHandler { activateSetting(setting: Setting): boolean { switch (setting.key) { case SettingKeys.Move_Touch_Controls: - gScene.inputController.moveTouchControlsHandler.enableConfigurationMode(this.getUi(), gScene); + globalScene.inputController.moveTouchControlsHandler.enableConfigurationMode(this.getUi(), globalScene); return true; } return false; @@ -312,8 +312,8 @@ export default class AbstractSettingsUiHandler extends UiHandler { const ret = super.setCursor(cursor); if (!this.cursorObj) { - const cursorWidth = (gScene.game.canvas.width / 6) - (this.scrollBar.visible ? 16 : 10); - this.cursorObj = gScene.add.nineslice(0, 0, "summary_moves_cursor", undefined, cursorWidth, 16, 1, 1, 1, 1); + const cursorWidth = (globalScene.game.canvas.width / 6) - (this.scrollBar.visible ? 16 : 10); + this.cursorObj = globalScene.add.nineslice(0, 0, "summary_moves_cursor", undefined, cursorWidth, 16, 1, 1, 1, 1); this.cursorObj.setOrigin(0, 0); this.optionsContainer.add(this.cursorObj); } @@ -352,7 +352,7 @@ export default class AbstractSettingsUiHandler extends UiHandler { newValueLabel.setShadowColor(this.getTextColor(TextStyle.SETTINGS_SELECTED, true)); if (save) { - gScene.gameData.saveSetting(setting.key, cursor); + globalScene.gameData.saveSetting(setting.key, cursor); if (this.reloadSettings.includes(setting)) { this.reloadRequired = true; } @@ -405,10 +405,10 @@ export default class AbstractSettingsUiHandler extends UiHandler { this.settingsContainer.setVisible(false); this.setScrollCursor(0); this.eraseCursor(); - this.getUi().bgmBar.toggleBgmBar(gScene.showBgmBar); + this.getUi().bgmBar.toggleBgmBar(globalScene.showBgmBar); if (this.reloadRequired) { this.reloadRequired = false; - gScene.reset(true, false, true); + globalScene.reset(true, false, true); } } diff --git a/src/ui/settings/gamepad-binding-ui-handler.ts b/src/ui/settings/gamepad-binding-ui-handler.ts index 65d8c78b259..7db82658ee6 100644 --- a/src/ui/settings/gamepad-binding-ui-handler.ts +++ b/src/ui/settings/gamepad-binding-ui-handler.ts @@ -3,20 +3,20 @@ import { Mode } from "../ui"; import { Device } from "#enums/devices"; import { getIconWithSettingName, getKeyWithKeycode } from "#app/configs/inputs/configHandler"; import { addTextObject, TextStyle } from "#app/ui/text"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class GamepadBindingUiHandler extends AbstractBindingUiHandler { constructor(mode: Mode | null = null) { super(mode); - gScene.input.gamepad?.on("down", this.gamepadButtonDown, this); + globalScene.input.gamepad?.on("down", this.gamepadButtonDown, this); } setup() { super.setup(); // New button icon setup. - this.newButtonIcon = gScene.add.sprite(0, 0, "xbox"); + this.newButtonIcon = globalScene.add.sprite(0, 0, "xbox"); this.newButtonIcon.setPositionRelative(this.optionSelectBg, 78, 16); this.newButtonIcon.setOrigin(0.5); this.newButtonIcon.setVisible(false); @@ -26,7 +26,7 @@ export default class GamepadBindingUiHandler extends AbstractBindingUiHandler { this.swapText.setPositionRelative(this.optionSelectBg, this.optionSelectBg.width / 2 - 2, this.optionSelectBg.height / 2 - 2); this.swapText.setVisible(false); - this.targetButtonIcon = gScene.add.sprite(0, 0, "xbox"); + this.targetButtonIcon = globalScene.add.sprite(0, 0, "xbox"); this.targetButtonIcon.setPositionRelative(this.optionSelectBg, 78, 48); this.targetButtonIcon.setOrigin(0.5); this.targetButtonIcon.setVisible(false); @@ -42,7 +42,7 @@ export default class GamepadBindingUiHandler extends AbstractBindingUiHandler { } getSelectedDevice() { - return gScene.inputController?.selectedDevice[Device.GAMEPAD]; + return globalScene.inputController?.selectedDevice[Device.GAMEPAD]; } gamepadButtonDown(pad: Phaser.Input.Gamepad.Gamepad, button: Phaser.Input.Gamepad.Button, value: number): void { @@ -51,7 +51,7 @@ export default class GamepadBindingUiHandler extends AbstractBindingUiHandler { if (!this.listening || pad.id.toLowerCase() !== this.getSelectedDevice() || blacklist.includes(button.index) || this.buttonPressed !== null) { return; } - const activeConfig = gScene.inputController.getActiveConfig(Device.GAMEPAD); + const activeConfig = globalScene.inputController.getActiveConfig(Device.GAMEPAD); const type = activeConfig.padType; const key = getKeyWithKeycode(activeConfig, button.index); const buttonIcon = activeConfig.icons[key]; @@ -64,9 +64,9 @@ export default class GamepadBindingUiHandler extends AbstractBindingUiHandler { } swapAction(): boolean { - const activeConfig = gScene.inputController.getActiveConfig(Device.GAMEPAD); - if (gScene.inputController.assignBinding(activeConfig, this.target, this.buttonPressed)) { - gScene.gameData.saveMappingConfigs(this.getSelectedDevice(), activeConfig); + const activeConfig = globalScene.inputController.getActiveConfig(Device.GAMEPAD); + if (globalScene.inputController.assignBinding(activeConfig, this.target, this.buttonPressed)) { + globalScene.gameData.saveMappingConfigs(this.getSelectedDevice(), activeConfig); return true; } return false; diff --git a/src/ui/settings/keyboard-binding-ui-handler.ts b/src/ui/settings/keyboard-binding-ui-handler.ts index 070c8ec3903..a6b45b1801f 100644 --- a/src/ui/settings/keyboard-binding-ui-handler.ts +++ b/src/ui/settings/keyboard-binding-ui-handler.ts @@ -3,7 +3,7 @@ import { Mode } from "../ui"; import { getKeyWithKeycode } from "#app/configs/inputs/configHandler"; import { Device } from "#enums/devices"; import { addTextObject, TextStyle } from "#app/ui/text"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class KeyboardBindingUiHandler extends AbstractBindingUiHandler { @@ -11,14 +11,14 @@ export default class KeyboardBindingUiHandler extends AbstractBindingUiHandler { constructor(mode: Mode | null = null) { super(mode); // Listen to gamepad button down events to initiate binding. - gScene.input.keyboard?.on("keydown", this.onKeyDown, this); + globalScene.input.keyboard?.on("keydown", this.onKeyDown, this); } setup() { super.setup(); // New button icon setup. - this.newButtonIcon = gScene.add.sprite(0, 0, "keyboard"); + this.newButtonIcon = globalScene.add.sprite(0, 0, "keyboard"); this.newButtonIcon.setPositionRelative(this.optionSelectBg, 78, 32); this.newButtonIcon.setOrigin(0.5); this.newButtonIcon.setVisible(false); @@ -32,7 +32,7 @@ export default class KeyboardBindingUiHandler extends AbstractBindingUiHandler { } getSelectedDevice() { - return gScene.inputController?.selectedDevice[Device.KEYBOARD]; + return globalScene.inputController?.selectedDevice[Device.KEYBOARD]; } onKeyDown(event): void { @@ -51,7 +51,7 @@ export default class KeyboardBindingUiHandler extends AbstractBindingUiHandler { if (!this.listening || this.buttonPressed !== null || blacklist.includes(key)) { return; } - const activeConfig = gScene.inputController.getActiveConfig(Device.KEYBOARD); + const activeConfig = globalScene.inputController.getActiveConfig(Device.KEYBOARD); const _key = getKeyWithKeycode(activeConfig, key); const buttonIcon = activeConfig.icons[_key]; if (!buttonIcon) { @@ -63,9 +63,9 @@ export default class KeyboardBindingUiHandler extends AbstractBindingUiHandler { } swapAction(): boolean { - const activeConfig = gScene.inputController.getActiveConfig(Device.KEYBOARD); - if (gScene.inputController.assignBinding(activeConfig, this.target, this.buttonPressed)) { - gScene.gameData.saveMappingConfigs(this.getSelectedDevice(), activeConfig); + const activeConfig = globalScene.inputController.getActiveConfig(Device.KEYBOARD); + if (globalScene.inputController.assignBinding(activeConfig, this.target, this.buttonPressed)) { + globalScene.gameData.saveMappingConfigs(this.getSelectedDevice(), activeConfig); return true; } return false; diff --git a/src/ui/settings/move-touch-controls-handler.ts b/src/ui/settings/move-touch-controls-handler.ts index dbc7f1b68a2..59ec6149358 100644 --- a/src/ui/settings/move-touch-controls-handler.ts +++ b/src/ui/settings/move-touch-controls-handler.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import TouchControl from "#app/touch-controls"; import UI from "#app/ui/ui"; import { Scene } from "phaser"; @@ -323,8 +323,8 @@ export default class MoveTouchControlsHandler { * @param scene The scene of the game. */ private createOverlay(ui: UI, scene: Scene) { - const container = new Phaser.GameObjects.Container(gScene, 0, 0); - const overlay = new Phaser.GameObjects.Rectangle(gScene, 0, 0, gScene.game.canvas.width, gScene.game.canvas.height, 0x000000, 0.5); + const container = new Phaser.GameObjects.Container(globalScene, 0, 0); + const overlay = new Phaser.GameObjects.Rectangle(globalScene, 0, 0, globalScene.game.canvas.width, globalScene.game.canvas.height, 0x000000, 0.5); overlay.setInteractive(); container.add(overlay); ui.add(container); diff --git a/src/ui/settings/navigationMenu.ts b/src/ui/settings/navigationMenu.ts index b3169cf9afe..8caba76a19e 100644 --- a/src/ui/settings/navigationMenu.ts +++ b/src/ui/settings/navigationMenu.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { Mode } from "#app/ui/ui"; import { InputsIcons } from "#app/ui/settings/abstract-control-settings-ui-handler"; import { addTextObject, setTextStyle, TextStyle } from "#app/ui/text"; @@ -68,7 +68,7 @@ export class NavigationManager { } else { this.selectedMode = this.modes[pos + increment]; } - gScene.ui.setMode(this.selectedMode); + globalScene.ui.setMode(this.selectedMode); this.updateNavigationMenus(); } @@ -103,7 +103,7 @@ export default class NavigationMenu extends Phaser.GameObjects.Container { * @param y The y position of the NavigationMenu. */ constructor(x: number, y: number) { - super(gScene, x, y); + super(globalScene, x, y); this.setup(); } @@ -113,7 +113,7 @@ export default class NavigationMenu extends Phaser.GameObjects.Container { */ setup() { const navigationManager = NavigationManager.getInstance(); - const headerBg = addWindow(0, 0, (gScene.game.canvas.width / 6) - 2, 24); + const headerBg = addWindow(0, 0, (globalScene.game.canvas.width / 6) - 2, 24); headerBg.setOrigin(0, 0); this.add(headerBg); this.width = headerBg.width; @@ -121,12 +121,12 @@ export default class NavigationMenu extends Phaser.GameObjects.Container { this.navigationIcons = {}; - const iconPreviousTab = gScene.add.sprite(8, 4, "keyboard"); + const iconPreviousTab = globalScene.add.sprite(8, 4, "keyboard"); iconPreviousTab.setOrigin(0, -0.1); iconPreviousTab.setPositionRelative(headerBg, 8, 4); this.navigationIcons["BUTTON_CYCLE_FORM"] = iconPreviousTab; - const iconNextTab = gScene.add.sprite(0, 0, "keyboard"); + const iconNextTab = globalScene.add.sprite(0, 0, "keyboard"); iconNextTab.setOrigin(0, -0.1); iconNextTab.setPositionRelative(headerBg, headerBg.width - 20, 4); this.navigationIcons["BUTTON_CYCLE_SHINY"] = iconNextTab; @@ -176,9 +176,9 @@ export default class NavigationMenu extends Phaser.GameObjects.Container { this.navigationIcons[settingName].alpha = 1; continue; } - const icon = gScene.inputController?.getIconForLatestInputRecorded(settingName); + const icon = globalScene.inputController?.getIconForLatestInputRecorded(settingName); if (icon) { - const type = gScene.inputController?.getLastSourceType(); + const type = globalScene.inputController?.getLastSourceType(); this.navigationIcons[settingName].setTexture(type); this.navigationIcons[settingName].setFrame(icon); this.navigationIcons[settingName].alpha = 1; diff --git a/src/ui/settings/settings-gamepad-ui-handler.ts b/src/ui/settings/settings-gamepad-ui-handler.ts index 8866cfdd68c..72f6502003a 100644 --- a/src/ui/settings/settings-gamepad-ui-handler.ts +++ b/src/ui/settings/settings-gamepad-ui-handler.ts @@ -15,7 +15,7 @@ import AbstractControlSettingsUiHandler from "#app/ui/settings/abstract-control- import { Device } from "#enums/devices"; import { truncateString } from "#app/utils"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; /** * Class representing the settings UI handler for gamepads. @@ -53,7 +53,7 @@ export default class SettingsGamepadUiHandler extends AbstractControlSettingsUiH super.setup(); // If no gamepads are detected, set up a default UI prompt in the settings container. this.layout["noGamepads"] = new Map(); - const optionsContainer = gScene.add.container(0, 0); + const optionsContainer = globalScene.add.container(0, 0); optionsContainer.setVisible(false); // Initially hide the container as no gamepads are connected. const label = addTextObject(8, 28, i18next.t("settings:gamepadPleasePlug"), TextStyle.SETTINGS_LABEL); label.setOrigin(0, 0); @@ -107,7 +107,7 @@ export default class SettingsGamepadUiHandler extends AbstractControlSettingsUiH // Update the text of the first option label under the current setting to the name of the chosen gamepad, // truncating the name to 30 characters if necessary. - this.layout[_key].optionValueLabels[index][0].setText(truncateString(gScene.inputController.selectedDevice[Device.GAMEPAD], 20)); + this.layout[_key].optionValueLabels[index][0].setText(truncateString(globalScene.inputController.selectedDevice[Device.GAMEPAD], 20)); } } } @@ -121,7 +121,7 @@ export default class SettingsGamepadUiHandler extends AbstractControlSettingsUiH */ saveSettingToLocalStorage(settingName, cursor): void { if (this.setting[settingName] !== this.setting.Controller) { - gScene.gameData.saveControlSetting(this.device, this.localStoragePropertyName, settingName, this.settingDeviceDefaults, cursor); + globalScene.gameData.saveControlSetting(this.device, this.localStoragePropertyName, settingName, this.settingDeviceDefaults, cursor); } } } diff --git a/src/ui/settings/settings-keyboard-ui-handler.ts b/src/ui/settings/settings-keyboard-ui-handler.ts index 418292c9272..e13f5ba8b88 100644 --- a/src/ui/settings/settings-keyboard-ui-handler.ts +++ b/src/ui/settings/settings-keyboard-ui-handler.ts @@ -15,7 +15,7 @@ import { deleteBind } from "#app/configs/inputs/configHandler"; import { Device } from "#enums/devices"; import { NavigationManager } from "#app/ui/settings/navigationMenu"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; /** * Class representing the settings UI handler for keyboards. @@ -42,8 +42,8 @@ export default class SettingsKeyboardUiHandler extends AbstractControlSettingsUi this.settingBlacklisted = settingKeyboardBlackList; this.device = Device.KEYBOARD; - const deleteEvent = gScene.input.keyboard?.addKey(Phaser.Input.Keyboard.KeyCodes.DELETE); - const restoreDefaultEvent = gScene.input.keyboard?.addKey(Phaser.Input.Keyboard.KeyCodes.HOME); + const deleteEvent = globalScene.input.keyboard?.addKey(Phaser.Input.Keyboard.KeyCodes.DELETE); + const restoreDefaultEvent = globalScene.input.keyboard?.addKey(Phaser.Input.Keyboard.KeyCodes.HOME); deleteEvent && deleteEvent.on("up", this.onDeleteDown, this); restoreDefaultEvent && restoreDefaultEvent.on("up", this.onHomeDown, this); } @@ -57,14 +57,14 @@ export default class SettingsKeyboardUiHandler extends AbstractControlSettingsUi super.setup(); // If no gamepads are detected, set up a default UI prompt in the settings container. this.layout["noKeyboard"] = new Map(); - const optionsContainer = gScene.add.container(0, 0); + const optionsContainer = globalScene.add.container(0, 0); optionsContainer.setVisible(false); // Initially hide the container as no gamepads are connected. const label = addTextObject(8, 28, i18next.t("settings:keyboardPleasePress"), TextStyle.SETTINGS_LABEL); label.setOrigin(0, 0); optionsContainer.add(label); this.settingsContainer.add(optionsContainer); - const iconDelete = gScene.add.sprite(0, 0, "keyboard"); + const iconDelete = globalScene.add.sprite(0, 0, "keyboard"); iconDelete.setOrigin(0, -0.1); iconDelete.setPositionRelative(this.actionsBg, this.navigationContainer.width - 260, 4); this.navigationIcons["BUTTON_DELETE"] = iconDelete; @@ -86,10 +86,10 @@ export default class SettingsKeyboardUiHandler extends AbstractControlSettingsUi * Handle the home key press event. */ onHomeDown(): void { - if (![ Mode.SETTINGS_KEYBOARD, Mode.SETTINGS_GAMEPAD ].includes(gScene.ui.getMode())) { + if (![ Mode.SETTINGS_KEYBOARD, Mode.SETTINGS_GAMEPAD ].includes(globalScene.ui.getMode())) { return; } - gScene.gameData.resetMappingToFactory(); + globalScene.gameData.resetMappingToFactory(); NavigationManager.getInstance().updateIcons(); } @@ -97,7 +97,7 @@ export default class SettingsKeyboardUiHandler extends AbstractControlSettingsUi * Handle the delete key press event. */ onDeleteDown(): void { - if (gScene.ui.getMode() !== Mode.SETTINGS_KEYBOARD) { + if (globalScene.ui.getMode() !== Mode.SETTINGS_KEYBOARD) { return; } const cursor = this.cursor + this.scrollCursor; // Calculate the absolute cursor position. @@ -153,7 +153,7 @@ export default class SettingsKeyboardUiHandler extends AbstractControlSettingsUi } // Skip updating the no gamepad layout. // Update the text of the first option label under the current setting to the name of the chosen gamepad, // truncating the name to 30 characters if necessary. - this.layout[_key].optionValueLabels[index][0].setText(truncateString(gScene.inputController.selectedDevice[Device.KEYBOARD], 22)); + this.layout[_key].optionValueLabels[index][0].setText(truncateString(globalScene.inputController.selectedDevice[Device.KEYBOARD], 22)); } } } @@ -166,7 +166,7 @@ export default class SettingsKeyboardUiHandler extends AbstractControlSettingsUi * @param config - The configuration to save. */ saveCustomKeyboardMappingToLocalStorage(config): void { - gScene.gameData.saveMappingConfigs(gScene.inputController?.selectedDevice[Device.KEYBOARD], config); + globalScene.gameData.saveMappingConfigs(globalScene.inputController?.selectedDevice[Device.KEYBOARD], config); } /** @@ -177,7 +177,7 @@ export default class SettingsKeyboardUiHandler extends AbstractControlSettingsUi */ saveSettingToLocalStorage(settingName, cursor): void { if (this.setting[settingName] !== this.setting.Default_Layout) { - gScene.gameData.saveControlSetting(this.device, this.localStoragePropertyName, settingName, this.settingDeviceDefaults, cursor); + globalScene.gameData.saveControlSetting(this.device, this.localStoragePropertyName, settingName, this.settingDeviceDefaults, cursor); } } } diff --git a/src/ui/starter-container.ts b/src/ui/starter-container.ts index 9962e37b8f8..43151d45f83 100644 --- a/src/ui/starter-container.ts +++ b/src/ui/starter-container.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import PokemonSpecies from "../data/pokemon-species"; import { addTextObject, TextStyle } from "./text"; @@ -16,15 +16,15 @@ export class StarterContainer extends Phaser.GameObjects.Container { public cost: number = 0; constructor(species: PokemonSpecies) { - super(gScene, 0, 0); + super(globalScene, 0, 0); this.species = species; - const defaultDexAttr = gScene.gameData.getSpeciesDefaultDexAttr(species, false, true); - const defaultProps = gScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); + const defaultDexAttr = globalScene.gameData.getSpeciesDefaultDexAttr(species, false, true); + const defaultProps = globalScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); // starter passive bg - const starterPassiveBg = gScene.add.image(2, 5, "passive_bg"); + const starterPassiveBg = globalScene.add.image(2, 5, "passive_bg"); starterPassiveBg.setOrigin(0, 0); starterPassiveBg.setScale(0.75); starterPassiveBg.setVisible(false); @@ -32,7 +32,7 @@ export class StarterContainer extends Phaser.GameObjects.Container { this.starterPassiveBgs = starterPassiveBg; // icon - this.icon = gScene.add.sprite(-2, 2, species.getIconAtlasKey(defaultProps.formIndex, defaultProps.shiny, defaultProps.variant)); + this.icon = globalScene.add.sprite(-2, 2, species.getIconAtlasKey(defaultProps.formIndex, defaultProps.shiny, defaultProps.variant)); this.icon.setScale(0.5); this.icon.setOrigin(0, 0); this.icon.setFrame(species.getIconId(defaultProps.female, defaultProps.formIndex, defaultProps.shiny, defaultProps.variant)); @@ -42,7 +42,7 @@ export class StarterContainer extends Phaser.GameObjects.Container { // shiny icons for (let i = 0; i < 3; i++) { - const shinyIcon = gScene.add.image(i * -3 + 12, 2, "shiny_star_small"); + const shinyIcon = globalScene.add.image(i * -3 + 12, 2, "shiny_star_small"); shinyIcon.setScale(0.5); shinyIcon.setOrigin(0, 0); shinyIcon.setVisible(false); @@ -59,7 +59,7 @@ export class StarterContainer extends Phaser.GameObjects.Container { this.label = label; // hidden ability icon - const abilityIcon = gScene.add.image(12, 7, "ha_capsule"); + const abilityIcon = globalScene.add.image(12, 7, "ha_capsule"); abilityIcon.setOrigin(0, 0); abilityIcon.setScale(0.5); abilityIcon.setVisible(false); @@ -67,7 +67,7 @@ export class StarterContainer extends Phaser.GameObjects.Container { this.hiddenAbilityIcon = abilityIcon; // favorite icon - const favoriteIcon = gScene.add.image(0, 7, "favorite"); + const favoriteIcon = globalScene.add.image(0, 7, "favorite"); favoriteIcon.setOrigin(0, 0); favoriteIcon.setScale(0.5); favoriteIcon.setVisible(false); @@ -75,7 +75,7 @@ export class StarterContainer extends Phaser.GameObjects.Container { this.favoriteIcon = favoriteIcon; // classic win icon - const classicWinIcon = gScene.add.image(0, 12, "champion_ribbon"); + const classicWinIcon = globalScene.add.image(0, 12, "champion_ribbon"); classicWinIcon.setOrigin(0, 0); classicWinIcon.setScale(0.5); classicWinIcon.setVisible(false); @@ -83,7 +83,7 @@ export class StarterContainer extends Phaser.GameObjects.Container { this.classicWinIcon = classicWinIcon; // candy upgrade icon - const candyUpgradeIcon = gScene.add.image(12, 12, "candy"); + const candyUpgradeIcon = globalScene.add.image(12, 12, "candy"); candyUpgradeIcon.setOrigin(0, 0); candyUpgradeIcon.setScale(0.25); candyUpgradeIcon.setVisible(false); @@ -91,7 +91,7 @@ export class StarterContainer extends Phaser.GameObjects.Container { this.candyUpgradeIcon = candyUpgradeIcon; // candy upgrade overlay icon - const candyUpgradeOverlayIcon = gScene.add.image(12, 12, "candy_overlay"); + const candyUpgradeOverlayIcon = globalScene.add.image(12, 12, "candy_overlay"); candyUpgradeOverlayIcon.setOrigin(0, 0); candyUpgradeOverlayIcon.setScale(0.25); candyUpgradeOverlayIcon.setVisible(false); diff --git a/src/ui/starter-select-ui-handler.ts b/src/ui/starter-select-ui-handler.ts index c3bed0fb464..668a974ca2c 100644 --- a/src/ui/starter-select-ui-handler.ts +++ b/src/ui/starter-select-ui-handler.ts @@ -4,7 +4,7 @@ import { Variant, getVariantTint, getVariantIcon } from "#app/data/variant"; import { argbFromRgba } from "@material/material-color-utilities"; import i18next from "i18next"; import BBCodeText from "phaser3-rex-plugins/plugins/bbcodetext"; -import { gScene, starterColors } from "#app/battle-scene"; +import { globalScene, starterColors } from "#app/battle-scene"; import { allAbilities } from "#app/data/ability"; import { speciesEggMoves } from "#app/data/balance/egg-moves"; import { GrowthRate, getGrowthRateColor } from "#app/data/exp"; @@ -335,25 +335,25 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const langSettingKey = Object.keys(languageSettings).find(lang => currentLanguage.includes(lang)) ?? "en"; const textSettings = languageSettings[langSettingKey]; - this.starterSelectContainer = gScene.add.container(0, -gScene.game.canvas.height / 6); + this.starterSelectContainer = globalScene.add.container(0, -globalScene.game.canvas.height / 6); this.starterSelectContainer.setVisible(false); ui.add(this.starterSelectContainer); - const bgColor = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0x006860); + const bgColor = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6, 0x006860); bgColor.setOrigin(0, 0); this.starterSelectContainer.add(bgColor); - const starterSelectBg = gScene.add.image(0, 0, "starter_select_bg"); + const starterSelectBg = globalScene.add.image(0, 0, "starter_select_bg"); starterSelectBg.setOrigin(0, 0); this.starterSelectContainer.add(starterSelectBg); - this.shinyOverlay = gScene.add.image(6, 6, "summary_overlay_shiny"); + this.shinyOverlay = globalScene.add.image(6, 6, "summary_overlay_shiny"); this.shinyOverlay.setOrigin(0, 0); this.shinyOverlay.setVisible(false); this.starterSelectContainer.add(this.shinyOverlay); const starterContainerWindow = addWindow(speciesContainerX, filterBarHeight + 1, 175, 161); - const starterContainerBg = gScene.add.image(speciesContainerX + 1, filterBarHeight + 2, "starter_container_bg"); + const starterContainerBg = globalScene.add.image(speciesContainerX + 1, filterBarHeight + 2, "starter_container_bg"); starterContainerBg.setOrigin(0, 0); this.starterSelectContainer.add(starterContainerBg); @@ -362,7 +362,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.starterSelectContainer.add(starterContainerWindow); // Create and initialise filter bar - this.filterBarContainer = gScene.add.container(0, 0); + this.filterBarContainer = globalScene.add.container(0, 0); this.filterBar = new FilterBar(Math.min(speciesContainerX, teamWindowX), 1, 210, filterBarHeight); // gen filter @@ -387,7 +387,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { if (index === 0 || index === 19) { return; } - const typeSprite = gScene.add.sprite(0, 0, Utils.getLocalizedSpriteKey("types")); + const typeSprite = globalScene.add.sprite(0, 0, Utils.getLocalizedSpriteKey("types")); typeSprite.setScale(0.5); typeSprite.setFrame(type.toLowerCase()); typeOptions.push(new DropDownOption(index, new DropDownLabel("", typeSprite))); @@ -395,17 +395,17 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.filterBar.addFilter(DropDownColumn.TYPES, i18next.t("filterBar:typeFilter"), new DropDown(0, 0, typeOptions, this.updateStarters, DropDownType.HYBRID, 0.5)); // caught filter - const shiny1Sprite = gScene.add.sprite(0, 0, "shiny_icons"); + const shiny1Sprite = globalScene.add.sprite(0, 0, "shiny_icons"); shiny1Sprite.setOrigin(0.15, 0.2); shiny1Sprite.setScale(0.6); shiny1Sprite.setFrame(getVariantIcon(0)); shiny1Sprite.setTint(getVariantTint(0)); - const shiny2Sprite = gScene.add.sprite(0, 0, "shiny_icons"); + const shiny2Sprite = globalScene.add.sprite(0, 0, "shiny_icons"); shiny2Sprite.setOrigin(0.15, 0.2); shiny2Sprite.setScale(0.6); shiny2Sprite.setFrame(getVariantIcon(1)); shiny2Sprite.setTint(getVariantTint(1)); - const shiny3Sprite = gScene.add.sprite(0, 0, "shiny_icons"); + const shiny3Sprite = globalScene.add.sprite(0, 0, "shiny_icons"); shiny3Sprite.setOrigin(0.15, 0.2); shiny3Sprite.setScale(0.6); shiny3Sprite.setFrame(getVariantIcon(2)); @@ -492,7 +492,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { // Offset the generation filter dropdown to avoid covering the filtered pokemon this.filterBar.offsetHybridFilters(); - if (!gScene.uiTheme) { + if (!globalScene.uiTheme) { starterContainerWindow.setVisible(false); } @@ -554,13 +554,13 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonPassiveText.setInteractive(new Phaser.Geom.Rectangle(0, 0, 250, 55), Phaser.Geom.Rectangle.Contains); this.starterSelectContainer.add(this.pokemonPassiveText); - this.pokemonPassiveDisabledIcon = gScene.add.sprite(starterInfoXPos, 137 + starterInfoYOffset, "icon_stop"); + this.pokemonPassiveDisabledIcon = globalScene.add.sprite(starterInfoXPos, 137 + starterInfoYOffset, "icon_stop"); this.pokemonPassiveDisabledIcon.setOrigin(0, 0.5); this.pokemonPassiveDisabledIcon.setScale(0.35); this.pokemonPassiveDisabledIcon.setVisible(false); this.starterSelectContainer.add(this.pokemonPassiveDisabledIcon); - this.pokemonPassiveLockedIcon = gScene.add.sprite(starterInfoXPos, 137 + starterInfoYOffset, "icon_lock"); + this.pokemonPassiveLockedIcon = globalScene.add.sprite(starterInfoXPos, 137 + starterInfoYOffset, "icon_lock"); this.pokemonPassiveLockedIcon.setOrigin(0, 0.5); this.pokemonPassiveLockedIcon.setScale(0.42, 0.38); this.pokemonPassiveLockedIcon.setVisible(false); @@ -591,21 +591,21 @@ export default class StarterSelectUiHandler extends MessageUiHandler { startLabel.setOrigin(0.5, 0); this.starterSelectContainer.add(startLabel); - this.startCursorObj = gScene.add.nineslice(teamWindowX + 4, 160, "select_cursor", undefined, 26, 15, 6, 6, 6, 6); + this.startCursorObj = globalScene.add.nineslice(teamWindowX + 4, 160, "select_cursor", undefined, 26, 15, 6, 6, 6, 6); this.startCursorObj.setVisible(false); this.startCursorObj.setOrigin(0, 0); this.starterSelectContainer.add(this.startCursorObj); const starterSpecies: Species[] = []; - const starterBoxContainer = gScene.add.container(speciesContainerX + 6, 9); //115 + const starterBoxContainer = globalScene.add.container(speciesContainerX + 6, 9); //115 this.starterSelectScrollBar = new ScrollBar(161, 12, 5, starterContainerWindow.height - 6, 9); starterBoxContainer.add(this.starterSelectScrollBar); this.pokerusCursorObjs = new Array(POKERUS_STARTER_COUNT).fill(null).map(() => { - const cursorObj = gScene.add.image(0, 0, "select_cursor_pokerus"); + const cursorObj = globalScene.add.image(0, 0, "select_cursor_pokerus"); cursorObj.setVisible(false); cursorObj.setOrigin(0, 0); starterBoxContainer.add(cursorObj); @@ -613,16 +613,16 @@ export default class StarterSelectUiHandler extends MessageUiHandler { }); this.starterCursorObjs = new Array(6).fill(null).map(() => { - const cursorObj = gScene.add.image(0, 0, "select_cursor_highlight"); + const cursorObj = globalScene.add.image(0, 0, "select_cursor_highlight"); cursorObj.setVisible(false); cursorObj.setOrigin(0, 0); starterBoxContainer.add(cursorObj); return cursorObj; }); - this.cursorObj = gScene.add.image(0, 0, "select_cursor"); + this.cursorObj = globalScene.add.image(0, 0, "select_cursor"); this.cursorObj.setOrigin(0, 0); - this.starterIconsCursorObj = gScene.add.image(289, 64, "select_gen_cursor"); + this.starterIconsCursorObj = globalScene.add.image(289, 64, "select_gen_cursor"); this.starterIconsCursorObj.setName("starter-icons-cursor"); this.starterIconsCursorObj.setVisible(false); this.starterIconsCursorObj.setOrigin(0, 0); @@ -648,7 +648,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.starterSelectContainer.add(starterBoxContainer); this.starterIcons = new Array(6).fill(null).map((_, i) => { - const icon = gScene.add.sprite(teamWindowX + 7, calcStarterIconY(i), "pokemon_icons_0"); + const icon = globalScene.add.sprite(teamWindowX + 7, calcStarterIconY(i), "pokemon_icons_0"); icon.setScale(0.5); icon.setOrigin(0, 0); icon.setFrame("unknown"); @@ -657,16 +657,16 @@ export default class StarterSelectUiHandler extends MessageUiHandler { return icon; }); - this.pokemonSprite = gScene.add.sprite(53, 63, "pkmn__sub"); - this.pokemonSprite.setPipeline(gScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); + this.pokemonSprite = globalScene.add.sprite(53, 63, "pkmn__sub"); + this.pokemonSprite.setPipeline(globalScene.spritePipeline, { tone: [ 0.0, 0.0, 0.0, 0.0 ], ignoreTimeTint: true }); this.starterSelectContainer.add(this.pokemonSprite); - this.type1Icon = gScene.add.sprite(8, 98, Utils.getLocalizedSpriteKey("types")); + this.type1Icon = globalScene.add.sprite(8, 98, Utils.getLocalizedSpriteKey("types")); this.type1Icon.setScale(0.5); this.type1Icon.setOrigin(0, 0); this.starterSelectContainer.add(this.type1Icon); - this.type2Icon = gScene.add.sprite(26, 98, Utils.getLocalizedSpriteKey("types")); + this.type2Icon = globalScene.add.sprite(26, 98, Utils.getLocalizedSpriteKey("types")); this.type2Icon.setScale(0.5); this.type2Icon.setOrigin(0, 0); this.starterSelectContainer.add(this.type2Icon); @@ -679,7 +679,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonLuckText.setOrigin(0, 0); this.starterSelectContainer.add(this.pokemonLuckText); - this.pokemonCandyIcon = gScene.add.sprite(4.5, 18, "candy"); + this.pokemonCandyIcon = globalScene.add.sprite(4.5, 18, "candy"); this.pokemonCandyIcon.setScale(0.5); this.pokemonCandyIcon.setOrigin(0, 0); this.starterSelectContainer.add(this.pokemonCandyIcon); @@ -688,12 +688,12 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonFormText.setOrigin(0, 0); this.starterSelectContainer.add(this.pokemonFormText); - this.pokemonCandyOverlayIcon = gScene.add.sprite(4.5, 18, "candy_overlay"); + this.pokemonCandyOverlayIcon = globalScene.add.sprite(4.5, 18, "candy_overlay"); this.pokemonCandyOverlayIcon.setScale(0.5); this.pokemonCandyOverlayIcon.setOrigin(0, 0); this.starterSelectContainer.add(this.pokemonCandyOverlayIcon); - this.pokemonCandyDarknessOverlay = gScene.add.sprite(4.5, 18, "candy"); + this.pokemonCandyDarknessOverlay = globalScene.add.sprite(4.5, 18, "candy"); this.pokemonCandyDarknessOverlay.setScale(0.5); this.pokemonCandyDarknessOverlay.setOrigin(0, 0); this.pokemonCandyDarknessOverlay.setTint(0x000000); @@ -705,11 +705,11 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonCandyCountText.setOrigin(0, 0); this.starterSelectContainer.add(this.pokemonCandyCountText); - this.pokemonCaughtHatchedContainer = gScene.add.container(2, 25); + this.pokemonCaughtHatchedContainer = globalScene.add.container(2, 25); this.pokemonCaughtHatchedContainer.setScale(0.5); this.starterSelectContainer.add(this.pokemonCaughtHatchedContainer); - const pokemonCaughtIcon = gScene.add.sprite(1, 0, "items", "pb"); + const pokemonCaughtIcon = globalScene.add.sprite(1, 0, "items", "pb"); pokemonCaughtIcon.setOrigin(0, 0); pokemonCaughtIcon.setScale(0.75); this.pokemonCaughtHatchedContainer.add(pokemonCaughtIcon); @@ -718,12 +718,12 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonCaughtCountText.setOrigin(0, 0); this.pokemonCaughtHatchedContainer.add(this.pokemonCaughtCountText); - this.pokemonHatchedIcon = gScene.add.sprite(1, 14, "egg_icons"); + this.pokemonHatchedIcon = globalScene.add.sprite(1, 14, "egg_icons"); this.pokemonHatchedIcon.setOrigin(0.15, 0.2); this.pokemonHatchedIcon.setScale(0.8); this.pokemonCaughtHatchedContainer.add(this.pokemonHatchedIcon); - this.pokemonShinyIcon = gScene.add.sprite(14, 76, "shiny_icons"); + this.pokemonShinyIcon = globalScene.add.sprite(14, 76, "shiny_icons"); this.pokemonShinyIcon.setOrigin(0.15, 0.2); this.pokemonShinyIcon.setScale(1); this.pokemonCaughtHatchedContainer.add(this.pokemonShinyIcon); @@ -732,13 +732,13 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonHatchedCountText.setOrigin(0, 0); this.pokemonCaughtHatchedContainer.add(this.pokemonHatchedCountText); - this.pokemonMovesContainer = gScene.add.container(102, 16); + this.pokemonMovesContainer = globalScene.add.container(102, 16); this.pokemonMovesContainer.setScale(0.375); for (let m = 0; m < 4; m++) { - const moveContainer = gScene.add.container(0, 14 * m); + const moveContainer = globalScene.add.container(0, 14 * m); - const moveBg = gScene.add.nineslice(0, 0, "type_bgs", "unknown", 92, 14, 2, 2, 2, 2); + const moveBg = globalScene.add.nineslice(0, 0, "type_bgs", "unknown", 92, 14, 2, 2, 2, 2); moveBg.setOrigin(1, 0); const moveLabel = addTextObject(-moveBg.width / 2, 0, "-", TextStyle.PARTY); @@ -761,7 +761,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.starterSelectContainer.add(this.pokemonMovesContainer); - this.pokemonEggMovesContainer = gScene.add.container(102, 85); + this.pokemonEggMovesContainer = globalScene.add.container(102, 85); this.pokemonEggMovesContainer.setScale(0.375); const eggMovesLabel = addTextObject(-46, 0, i18next.t("starterSelectUiHandler:eggMoves"), TextStyle.WINDOW_ALT); @@ -770,9 +770,9 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonEggMovesContainer.add(eggMovesLabel); for (let m = 0; m < 4; m++) { - const eggMoveContainer = gScene.add.container(0, 16 + 14 * m); + const eggMoveContainer = globalScene.add.container(0, 16 + 14 * m); - const eggMoveBg = gScene.add.nineslice(0, 0, "type_bgs", "unknown", 92, 14, 2, 2, 2, 2); + const eggMoveBg = globalScene.add.nineslice(0, 0, "type_bgs", "unknown", 92, 14, 2, 2, 2, 2); eggMoveBg.setOrigin(1, 0); const eggMoveLabel = addTextObject(-eggMoveBg.width / 2, 0, "???", TextStyle.PARTY); @@ -794,55 +794,55 @@ export default class StarterSelectUiHandler extends MessageUiHandler { // The font size should be set per language const instructionTextSize = textSettings.instructionTextSize; - this.instructionsContainer = gScene.add.container(4, 156); + this.instructionsContainer = globalScene.add.container(4, 156); this.instructionsContainer.setVisible(true); this.starterSelectContainer.add(this.instructionsContainer); // instruction rows that will be pushed into the container dynamically based on need // creating new sprites since they will be added to the scene later - this.shinyIconElement = new Phaser.GameObjects.Sprite(gScene, this.instructionRowX, this.instructionRowY, "keyboard", "R.png"); + this.shinyIconElement = new Phaser.GameObjects.Sprite(globalScene, this.instructionRowX, this.instructionRowY, "keyboard", "R.png"); this.shinyIconElement.setName("sprite-shiny-icon-element"); this.shinyIconElement.setScale(0.675); this.shinyIconElement.setOrigin(0.0, 0.0); this.shinyLabel = addTextObject(this.instructionRowX + this.instructionRowTextOffset, this.instructionRowY, i18next.t("starterSelectUiHandler:cycleShiny"), TextStyle.PARTY, { fontSize: instructionTextSize }); this.shinyLabel.setName("text-shiny-label"); - this.formIconElement = new Phaser.GameObjects.Sprite(gScene, this.instructionRowX, this.instructionRowY, "keyboard", "F.png"); + this.formIconElement = new Phaser.GameObjects.Sprite(globalScene, this.instructionRowX, this.instructionRowY, "keyboard", "F.png"); this.formIconElement.setName("sprite-form-icon-element"); this.formIconElement.setScale(0.675); this.formIconElement.setOrigin(0.0, 0.0); this.formLabel = addTextObject(this.instructionRowX + this.instructionRowTextOffset, this.instructionRowY, i18next.t("starterSelectUiHandler:cycleForm"), TextStyle.PARTY, { fontSize: instructionTextSize }); this.formLabel.setName("text-form-label"); - this.genderIconElement = new Phaser.GameObjects.Sprite(gScene, this.instructionRowX, this.instructionRowY, "keyboard", "G.png"); + this.genderIconElement = new Phaser.GameObjects.Sprite(globalScene, this.instructionRowX, this.instructionRowY, "keyboard", "G.png"); this.genderIconElement.setName("sprite-gender-icon-element"); this.genderIconElement.setScale(0.675); this.genderIconElement.setOrigin(0.0, 0.0); this.genderLabel = addTextObject(this.instructionRowX + this.instructionRowTextOffset, this.instructionRowY, i18next.t("starterSelectUiHandler:cycleGender"), TextStyle.PARTY, { fontSize: instructionTextSize }); this.genderLabel.setName("text-gender-label"); - this.abilityIconElement = new Phaser.GameObjects.Sprite(gScene, this.instructionRowX, this.instructionRowY, "keyboard", "E.png"); + this.abilityIconElement = new Phaser.GameObjects.Sprite(globalScene, this.instructionRowX, this.instructionRowY, "keyboard", "E.png"); this.abilityIconElement.setName("sprite-ability-icon-element"); this.abilityIconElement.setScale(0.675); this.abilityIconElement.setOrigin(0.0, 0.0); this.abilityLabel = addTextObject(this.instructionRowX + this.instructionRowTextOffset, this.instructionRowY, i18next.t("starterSelectUiHandler:cycleAbility"), TextStyle.PARTY, { fontSize: instructionTextSize }); this.abilityLabel.setName("text-ability-label"); - this.natureIconElement = new Phaser.GameObjects.Sprite(gScene, this.instructionRowX, this.instructionRowY, "keyboard", "N.png"); + this.natureIconElement = new Phaser.GameObjects.Sprite(globalScene, this.instructionRowX, this.instructionRowY, "keyboard", "N.png"); this.natureIconElement.setName("sprite-nature-icon-element"); this.natureIconElement.setScale(0.675); this.natureIconElement.setOrigin(0.0, 0.0); this.natureLabel = addTextObject(this.instructionRowX + this.instructionRowTextOffset, this.instructionRowY, i18next.t("starterSelectUiHandler:cycleNature"), TextStyle.PARTY, { fontSize: instructionTextSize }); this.natureLabel.setName("text-nature-label"); - this.variantIconElement = new Phaser.GameObjects.Sprite(gScene, this.instructionRowX, this.instructionRowY, "keyboard", "V.png"); + this.variantIconElement = new Phaser.GameObjects.Sprite(globalScene, this.instructionRowX, this.instructionRowY, "keyboard", "V.png"); this.variantIconElement.setName("sprite-variant-icon-element"); this.variantIconElement.setScale(0.675); this.variantIconElement.setOrigin(0.0, 0.0); this.variantLabel = addTextObject(this.instructionRowX + this.instructionRowTextOffset, this.instructionRowY, i18next.t("starterSelectUiHandler:cycleVariant"), TextStyle.PARTY, { fontSize: instructionTextSize }); this.variantLabel.setName("text-variant-label"); - this.goFilterIconElement = new Phaser.GameObjects.Sprite(gScene, this.filterInstructionRowX, this.filterInstructionRowY, "keyboard", "C.png"); + this.goFilterIconElement = new Phaser.GameObjects.Sprite(globalScene, this.filterInstructionRowX, this.filterInstructionRowY, "keyboard", "C.png"); this.goFilterIconElement.setName("sprite-goFilter-icon-element"); this.goFilterIconElement.setScale(0.675); this.goFilterIconElement.setOrigin(0.0, 0.0); @@ -851,11 +851,11 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.hideInstructions(); - this.filterInstructionsContainer = gScene.add.container(50, 5); + this.filterInstructionsContainer = globalScene.add.container(50, 5); this.filterInstructionsContainer.setVisible(true); this.starterSelectContainer.add(this.filterInstructionsContainer); - this.starterSelectMessageBoxContainer = gScene.add.container(0, gScene.game.canvas.height / 6); + this.starterSelectMessageBoxContainer = globalScene.add.container(0, globalScene.game.canvas.height / 6); this.starterSelectMessageBoxContainer.setVisible(false); this.starterSelectContainer.add(this.starterSelectMessageBoxContainer); @@ -872,7 +872,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.statsContainer = new StatsContainer(6, 16); - gScene.add.existing(this.statsContainer); + globalScene.add.existing(this.statsContainer); this.statsContainer.setVisible(false); @@ -884,7 +884,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { scale: overlayScale, top: true, x: 1, - y: gScene.game.canvas.height / 6 - MoveInfoOverlay.getHeight(overlayScale) - 29, + y: globalScene.game.canvas.height / 6 - MoveInfoOverlay.getHeight(overlayScale) - 29, }); this.starterSelectContainer.add(this.moveInfoOverlay); @@ -893,7 +893,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.initTutorialOverlay(this.starterSelectContainer); this.starterSelectContainer.bringToTop(this.starterSelectMessageBoxContainer); - gScene.eventTarget.addEventListener(BattleSceneEventType.CANDY_UPGRADE_NOTIFICATION_CHANGED, (e) => this.onCandyUpgradeDisplayChanged(e)); + globalScene.eventTarget.addEventListener(BattleSceneEventType.CANDY_UPGRADE_NOTIFICATION_CHANGED, (e) => this.onCandyUpgradeDisplayChanged(e)); this.updateInstructions(); } @@ -914,7 +914,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.allSpecies.forEach((species, s) => { const icon = this.starterContainers[s].icon; - const dexEntry = gScene.gameData.dexData[species.speciesId]; + const dexEntry = globalScene.gameData.dexData[species.speciesId]; // Initialize the StarterAttributes for this species this.starterPreferences[species.speciesId] = this.initStarterPrefs(species); @@ -954,8 +954,8 @@ export default class StarterSelectUiHandler extends MessageUiHandler { */ initStarterPrefs(species: PokemonSpecies): StarterAttributes { const starterAttributes = this.starterPreferences[species.speciesId]; - const dexEntry = gScene.gameData.dexData[species.speciesId]; - const starterData = gScene.gameData.starterData[species.speciesId]; + const dexEntry = globalScene.gameData.dexData[species.speciesId]; + const starterData = globalScene.gameData.starterData[species.speciesId]; // no preferences or Pokemon wasn't caught, return empty attribute if (!starterAttributes || !dexEntry.caughtAttr) { @@ -1014,13 +1014,13 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } const selectedForm = starterAttributes.form; - if (selectedForm !== undefined && (!species.forms[selectedForm]?.isStarterSelectable || !(caughtAttr & gScene.gameData.getFormAttr(selectedForm)))) { + if (selectedForm !== undefined && (!species.forms[selectedForm]?.isStarterSelectable || !(caughtAttr & globalScene.gameData.getFormAttr(selectedForm)))) { // requested form wasn't unlocked/isn't a starter form, purging setting delete starterAttributes.form; } if (starterAttributes.nature !== undefined) { - const unlockedNatures = gScene.gameData.getNaturesForAttr(dexEntry.natureAttr); + const unlockedNatures = globalScene.gameData.getNaturesForAttr(dexEntry.natureAttr); if (unlockedNatures.indexOf(starterAttributes.nature as unknown as Nature) < 0) { // requested nature wasn't unlocked, purging setting delete starterAttributes.nature; @@ -1066,14 +1066,14 @@ export default class StarterSelectUiHandler extends MessageUiHandler { * @returns true if upgrade notifications are enabled and set to display an 'Icon' */ isUpgradeIconEnabled(): boolean { - return gScene.candyUpgradeNotification !== 0 && gScene.candyUpgradeDisplay === 0; + return globalScene.candyUpgradeNotification !== 0 && globalScene.candyUpgradeDisplay === 0; } /** * Determines if 'Animation' based upgrade notifications should be shown * @returns true if upgrade notifications are enabled and set to display an 'Animation' */ isUpgradeAnimationEnabled(): boolean { - return gScene.candyUpgradeNotification !== 0 && gScene.candyUpgradeDisplay === 1; + return globalScene.candyUpgradeNotification !== 0 && globalScene.candyUpgradeDisplay === 1; } /** @@ -1083,7 +1083,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { */ isPassiveAvailable(speciesId: number): boolean { // Get this species ID's starter data - const starterData = gScene.gameData.starterData[speciesId]; + const starterData = globalScene.gameData.starterData[speciesId]; return starterData.candyCount >= getPassiveCandyCount(speciesStarterCosts[speciesId]) && !(starterData.passiveAttr & PassiveAttr.UNLOCKED); @@ -1096,7 +1096,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { */ isValueReductionAvailable(speciesId: number): boolean { // Get this species ID's starter data - const starterData = gScene.gameData.starterData[speciesId]; + const starterData = globalScene.gameData.starterData[speciesId]; return starterData.candyCount >= getValueReductionCandyCounts(speciesStarterCosts[speciesId])[starterData.valueReduction] && starterData.valueReduction < valueReductionMax; @@ -1109,7 +1109,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { */ isSameSpeciesEggAvailable(speciesId: number): boolean { // Get this species ID's starter data - const starterData = gScene.gameData.starterData[speciesId]; + const starterData = globalScene.gameData.starterData[speciesId]; return starterData.candyCount >= getSameSpeciesEggCandyCounts(speciesStarterCosts[speciesId]); } @@ -1121,9 +1121,9 @@ export default class StarterSelectUiHandler extends MessageUiHandler { * @param startPaused Should this animation be paused after it is added? */ setUpgradeAnimation(icon: Phaser.GameObjects.Sprite, species: PokemonSpecies, startPaused: boolean = false): void { - gScene.tweens.killTweensOf(icon); + globalScene.tweens.killTweensOf(icon); // Skip animations if they are disabled - if (gScene.candyUpgradeDisplay === 0 || species.speciesId !== species.getRootSpeciesId(false)) { + if (globalScene.candyUpgradeDisplay === 0 || species.speciesId !== species.getRootSpeciesId(false)) { return; } @@ -1157,14 +1157,14 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const isSameSpeciesEggAvailable = this.isSameSpeciesEggAvailable(species.speciesId); // 'Passives Only' mode - if (gScene.candyUpgradeNotification === 1) { + if (globalScene.candyUpgradeNotification === 1) { if (isPassiveAvailable) { - gScene.tweens.chain(tweenChain).paused = startPaused; + globalScene.tweens.chain(tweenChain).paused = startPaused; } // 'On' mode - } else if (gScene.candyUpgradeNotification === 2) { + } else if (globalScene.candyUpgradeNotification === 2) { if (isPassiveAvailable || isValueReductionAvailable || isSameSpeciesEggAvailable) { - gScene.tweens.chain(tweenChain).paused = startPaused; + globalScene.tweens.chain(tweenChain).paused = startPaused; } } } @@ -1176,7 +1176,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const species = starter.species; const slotVisible = !!species?.speciesId; - if (!species || gScene.candyUpgradeNotification === 0 || species.speciesId !== species.getRootSpeciesId(false)) { + if (!species || globalScene.candyUpgradeNotification === 0 || species.speciesId !== species.getRootSpeciesId(false)) { starter.candyUpgradeIcon.setVisible(false); starter.candyUpgradeOverlayIcon.setVisible(false); return; @@ -1187,12 +1187,12 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const isSameSpeciesEggAvailable = this.isSameSpeciesEggAvailable(species.speciesId); // 'Passive Only' mode - if (gScene.candyUpgradeNotification === 1) { + if (globalScene.candyUpgradeNotification === 1) { starter.candyUpgradeIcon.setVisible(slotVisible && isPassiveAvailable); starter.candyUpgradeOverlayIcon.setVisible(slotVisible && starter.candyUpgradeIcon.visible); // 'On' mode - } else if (gScene.candyUpgradeNotification === 2) { + } else if (globalScene.candyUpgradeNotification === 2) { starter.candyUpgradeIcon.setVisible( slotVisible && ( isPassiveAvailable || isValueReductionAvailable || isSameSpeciesEggAvailable )); starter.candyUpgradeOverlayIcon.setVisible(slotVisible && starter.candyUpgradeIcon.visible); @@ -1223,7 +1223,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } // Loop through all visible candy icons when set to 'Icon' mode - if (gScene.candyUpgradeDisplay === 0) { + if (globalScene.candyUpgradeDisplay === 0) { this.filteredStarterContainers.forEach((starter) => { this.setUpgradeIcon(starter); }); @@ -1420,7 +1420,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } else { let starterContainer; - const starterData = gScene.gameData.starterData[this.lastSpecies.speciesId]; + const starterData = globalScene.gameData.starterData[this.lastSpecies.speciesId]; // prepare persistent starter data to store changes let starterAttributes = this.starterPreferences[this.lastSpecies.speciesId]; @@ -1444,17 +1444,17 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const isPartyValid = this.isPartyValid(); const isValidForChallenge = new Utils.BooleanHolder(true); - Challenge.applyChallenges(gScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, this.lastSpecies, isValidForChallenge, gScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, this.getCurrentDexProps(this.lastSpecies.speciesId)), isPartyValid); + Challenge.applyChallenges(globalScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, this.lastSpecies, isValidForChallenge, globalScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, this.getCurrentDexProps(this.lastSpecies.speciesId)), isPartyValid); - const currentPartyValue = this.starterSpecies.map(s => s.generation).reduce((total: number, gen: number, i: number) => total += gScene.gameData.getSpeciesStarterValue(this.starterSpecies[i].speciesId), 0); - const newCost = gScene.gameData.getSpeciesStarterValue(this.lastSpecies.speciesId); + const currentPartyValue = this.starterSpecies.map(s => s.generation).reduce((total: number, gen: number, i: number) => total += globalScene.gameData.getSpeciesStarterValue(this.starterSpecies[i].speciesId), 0); + const newCost = globalScene.gameData.getSpeciesStarterValue(this.lastSpecies.speciesId); if (!isDupe && isValidForChallenge.value && currentPartyValue + newCost <= this.getValueLimit() && this.starterSpecies.length < 6) { // this checks to make sure the pokemon doesn't exist in your party, it's valid for the challenge and that it won't go over the cost limit; if it meets all these criteria it will add it to your party options = [ { label: i18next.t("starterSelectUiHandler:addToParty"), handler: () => { ui.setMode(Mode.STARTER_SELECT); - const isOverValueLimit = this.tryUpdateValue(gScene.gameData.getSpeciesStarterValue(this.lastSpecies.speciesId), true); + const isOverValueLimit = this.tryUpdateValue(globalScene.gameData.getSpeciesStarterValue(this.lastSpecies.speciesId), true); if (!isDupe && isValidForChallenge.value && isOverValueLimit) { const cursorObj = this.starterCursorObjs[this.starterSpecies.length]; cursorObj.setVisible(true); @@ -1583,11 +1583,11 @@ export default class StarterSelectUiHandler extends MessageUiHandler { ui.setMode(Mode.STARTER_SELECT).then(() => { ui.showText(i18next.t("starterSelectUiHandler:selectNature"), null, () => { - const natures = gScene.gameData.getNaturesForAttr(this.speciesStarterDexEntry?.natureAttr); + const natures = globalScene.gameData.getNaturesForAttr(this.speciesStarterDexEntry?.natureAttr); ui.setModeWithoutClear(Mode.OPTION_SELECT, { options: natures.map((n: Nature, i: number) => { const option: OptionSelectItem = { - label: getNatureName(n, true, true, true, gScene.uiTheme), + label: getNatureName(n, true, true, true, globalScene.uiTheme), handler: () => { // update default nature in starter save data if (!starterAttributes) { @@ -1725,19 +1725,19 @@ export default class StarterSelectUiHandler extends MessageUiHandler { starterData.candyCount -= passiveCost; } this.pokemonCandyCountText.setText(`x${starterData.candyCount}`); - gScene.gameData.saveSystem().then(success => { + globalScene.gameData.saveSystem().then(success => { if (!success) { - return gScene.reset(true); + return globalScene.reset(true); } }); ui.setMode(Mode.STARTER_SELECT); this.setSpeciesDetails(this.lastSpecies); - gScene.playSound("se/buy"); + globalScene.playSound("se/buy"); // update the passive background and icon/animation for available upgrade if (starterContainer) { this.updateCandyUpgradeDisplay(starterContainer); - starterContainer.starterPassiveBgs.setVisible(!!gScene.gameData.starterData[this.lastSpecies.speciesId].passiveAttr); + starterContainer.starterPassiveBgs.setVisible(!!globalScene.gameData.starterData[this.lastSpecies.speciesId].passiveAttr); } return true; } @@ -1761,14 +1761,14 @@ export default class StarterSelectUiHandler extends MessageUiHandler { starterData.candyCount -= reductionCost; } this.pokemonCandyCountText.setText(`x${starterData.candyCount}`); - gScene.gameData.saveSystem().then(success => { + globalScene.gameData.saveSystem().then(success => { if (!success) { - return gScene.reset(true); + return globalScene.reset(true); } }); this.tryUpdateValue(0); ui.setMode(Mode.STARTER_SELECT); - gScene.playSound("se/buy"); + globalScene.playSound("se/buy"); // update the value label and icon/animation for available upgrade if (starterContainer) { @@ -1789,23 +1789,23 @@ export default class StarterSelectUiHandler extends MessageUiHandler { options.push({ label: `x${sameSpeciesEggCost} ${i18next.t("starterSelectUiHandler:sameSpeciesEgg")}`, handler: () => { - if ((gScene.gameData.eggs.length < 99 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) + if ((globalScene.gameData.eggs.length < 99 || Overrides.UNLIMITED_EGG_COUNT_OVERRIDE) && (Overrides.FREE_CANDY_UPGRADE_OVERRIDE || candyCount >= sameSpeciesEggCost)) { if (!Overrides.FREE_CANDY_UPGRADE_OVERRIDE) { starterData.candyCount -= sameSpeciesEggCost; } this.pokemonCandyCountText.setText(`x${starterData.candyCount}`); - const egg = new Egg({ scene: gScene, species: this.lastSpecies.speciesId, sourceType: EggSourceType.SAME_SPECIES_EGG }); + const egg = new Egg({ scene: globalScene, species: this.lastSpecies.speciesId, sourceType: EggSourceType.SAME_SPECIES_EGG }); egg.addEggToGameData(); - gScene.gameData.saveSystem().then(success => { + globalScene.gameData.saveSystem().then(success => { if (!success) { - return gScene.reset(true); + return globalScene.reset(true); } }); ui.setMode(Mode.STARTER_SELECT); - gScene.playSound("se/buy"); + globalScene.playSound("se/buy"); // update the icon/animation for available upgrade if (starterContainer) { @@ -1854,7 +1854,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { success = true; } } else { - const props = gScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, this.getCurrentDexProps(this.lastSpecies.speciesId)); + const props = globalScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, this.getCurrentDexProps(this.lastSpecies.speciesId)); switch (button) { case Button.CYCLE_SHINY: if (this.canCycleShiny) { @@ -1862,11 +1862,11 @@ export default class StarterSelectUiHandler extends MessageUiHandler { if (starterAttributes.shiny) { // Change to shiny, we need to get the proper default variant - const newProps = gScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, this.getCurrentDexProps(this.lastSpecies.speciesId)); + const newProps = globalScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, this.getCurrentDexProps(this.lastSpecies.speciesId)); const newVariant = starterAttributes.variant ? starterAttributes.variant as Variant : newProps.variant; this.setSpeciesDetails(this.lastSpecies, true, undefined, undefined, newVariant, undefined, undefined); - gScene.playSound("se/sparkle"); + globalScene.playSound("se/sparkle"); // Set the variant label to the shiny tint const tint = getVariantTint(newVariant); this.pokemonShinyIcon.setFrame(getVariantIcon(newVariant)); @@ -1885,7 +1885,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { let newFormIndex = props.formIndex; do { newFormIndex = (newFormIndex + 1) % formCount; - if (this.lastSpecies.forms[newFormIndex].isStarterSelectable && this.speciesStarterDexEntry!.caughtAttr! & gScene.gameData.getFormAttr(newFormIndex)) { // TODO: are those bangs correct? + if (this.lastSpecies.forms[newFormIndex].isStarterSelectable && this.speciesStarterDexEntry!.caughtAttr! & globalScene.gameData.getFormAttr(newFormIndex)) { // TODO: are those bangs correct? break; } } while (newFormIndex !== props.formIndex); @@ -1904,7 +1904,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { case Button.CYCLE_ABILITY: if (this.canCycleAbility) { const abilityCount = this.lastSpecies.getAbilityCount(); - const abilityAttr = gScene.gameData.starterData[this.lastSpecies.speciesId].abilityAttr; + const abilityAttr = globalScene.gameData.starterData[this.lastSpecies.speciesId].abilityAttr; const hasAbility1 = abilityAttr & AbilityAttr.ABILITY_1; let newAbilityIndex = this.abilityCursor; do { @@ -1927,11 +1927,11 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } while (newAbilityIndex !== this.abilityCursor); starterAttributes.ability = newAbilityIndex; // store the selected ability - const { visible: tooltipVisible } = gScene.ui.getTooltip(); + const { visible: tooltipVisible } = globalScene.ui.getTooltip(); if (tooltipVisible && this.activeTooltip === "ABILITY") { const newAbility = allAbilities[this.lastSpecies.getAbility(newAbilityIndex)]; - gScene.ui.editTooltip(`${newAbility.name}`, `${newAbility.description}`); + globalScene.ui.editTooltip(`${newAbility.name}`, `${newAbility.description}`); } this.setSpeciesDetails(this.lastSpecies, undefined, undefined, undefined, undefined, newAbilityIndex, undefined); @@ -1940,7 +1940,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { break; case Button.CYCLE_NATURE: if (this.canCycleNature) { - const natures = gScene.gameData.getNaturesForAttr(this.speciesStarterDexEntry?.natureAttr); + const natures = globalScene.gameData.getNaturesForAttr(this.speciesStarterDexEntry?.natureAttr); const natureIndex = natures.indexOf(this.natureCursor); const newNature = natures[natureIndex < natures.length - 1 ? natureIndex + 1 : 0]; // store cycled nature as default @@ -2136,7 +2136,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } addToParty(species: PokemonSpecies, dexAttr: bigint, abilityIndex: integer, nature: Nature, moveset: StarterMoveset) { - const props = gScene.gameData.getSpeciesDexAttrProps(species, dexAttr); + const props = globalScene.gameData.getSpeciesDexAttrProps(species, dexAttr); this.starterIcons[this.starterSpecies.length].setTexture(species.getIconAtlasKey(props.formIndex, props.shiny, props.variant)); this.starterIcons[this.starterSpecies.length].setFrame(species.getIconId(props.female, props.formIndex, props.shiny, props.variant)); this.checkIconId(this.starterIcons[this.starterSpecies.length], species, props.female, props.formIndex, props.shiny, props.variant); @@ -2153,7 +2153,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } updatePartyIcon(species: PokemonSpecies, index: number) { - const props = gScene.gameData.getSpeciesDexAttrProps(species, this.getCurrentDexProps(species.speciesId)); + const props = globalScene.gameData.getSpeciesDexAttrProps(species, this.getCurrentDexProps(species.speciesId)); this.starterIcons[index].setTexture(species.getIconAtlasKey(props.formIndex, props.shiny, props.variant)); this.starterIcons[index].setFrame(species.getIconId(props.female, props.formIndex, props.shiny, props.variant)); this.checkIconId(this.starterIcons[index], species, props.female, props.formIndex, props.shiny, props.variant); @@ -2166,29 +2166,29 @@ export default class StarterSelectUiHandler extends MessageUiHandler { if (existingMoveIndex > -1) { this.starterMoveset![existingMoveIndex] = move; // TODO: is this bang correct? } - const props: DexAttrProps = gScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, this.dexAttrCursor); + const props: DexAttrProps = globalScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, this.dexAttrCursor); // species has different forms if (pokemonFormLevelMoves.hasOwnProperty(speciesId)) { // starterMoveData doesn't have base form moves or is using the single form format - if (!gScene.gameData.starterData[speciesId].moveset || Array.isArray(gScene.gameData.starterData[speciesId].moveset)) { - gScene.gameData.starterData[speciesId].moveset = { [props.formIndex]: this.starterMoveset?.slice(0) as StarterMoveset }; + if (!globalScene.gameData.starterData[speciesId].moveset || Array.isArray(globalScene.gameData.starterData[speciesId].moveset)) { + globalScene.gameData.starterData[speciesId].moveset = { [props.formIndex]: this.starterMoveset?.slice(0) as StarterMoveset }; } - const starterMoveData = gScene.gameData.starterData[speciesId].moveset; + const starterMoveData = globalScene.gameData.starterData[speciesId].moveset; // starterMoveData doesn't have active form moves if (!starterMoveData.hasOwnProperty(props.formIndex)) { - gScene.gameData.starterData[speciesId].moveset[props.formIndex] = this.starterMoveset?.slice(0) as StarterMoveset; + globalScene.gameData.starterData[speciesId].moveset[props.formIndex] = this.starterMoveset?.slice(0) as StarterMoveset; } // does the species' starter move data have its form's starter moves and has it been updated if (starterMoveData.hasOwnProperty(props.formIndex)) { // active form move hasn't been updated if (starterMoveData[props.formIndex][existingMoveIndex] !== newMove) { - gScene.gameData.starterData[speciesId].moveset[props.formIndex] = this.starterMoveset?.slice(0) as StarterMoveset; + globalScene.gameData.starterData[speciesId].moveset[props.formIndex] = this.starterMoveset?.slice(0) as StarterMoveset; } } } else { - gScene.gameData.starterData[speciesId].moveset = this.starterMoveset?.slice(0) as StarterMoveset; + globalScene.gameData.starterData[speciesId].moveset = this.starterMoveset?.slice(0) as StarterMoveset; } this.setSpeciesDetails(this.lastSpecies, undefined, undefined, undefined, undefined, undefined, undefined, false); @@ -2235,7 +2235,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { break; } } else { - iconPath = gScene.inputController?.getIconForLatestInputRecorded(iconSetting); + iconPath = globalScene.inputController?.getIconForLatestInputRecorded(iconSetting); } iconElement.setTexture(gamepadType, iconPath); iconElement.setPosition(this.instructionRowX, this.instructionRowY); @@ -2258,7 +2258,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { gamepadType = "keyboard"; iconPath = "C.png"; } else { - iconPath = gScene.inputController?.getIconForLatestInputRecorded(iconSetting); + iconPath = globalScene.inputController?.getIconForLatestInputRecorded(iconSetting); } iconElement.setTexture(gamepadType, iconPath); iconElement.setPosition(this.filterInstructionRowX, this.filterInstructionRowY); @@ -2282,10 +2282,10 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.instructionsContainer.removeAll(); this.filterInstructionsContainer.removeAll(); let gamepadType; - if (gScene.inputMethod === "gamepad") { - gamepadType = gScene.inputController.getConfig(gScene.inputController.selectedDevice[Device.GAMEPAD]).padType; + if (globalScene.inputMethod === "gamepad") { + gamepadType = globalScene.inputController.getConfig(globalScene.inputController.selectedDevice[Device.GAMEPAD]).padType; } else { - gamepadType = gScene.inputMethod; + gamepadType = globalScene.inputMethod; } if (!gamepadType) { @@ -2322,7 +2322,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { getValueLimit(): integer { const valueLimit = new Utils.IntegerHolder(0); - switch (gScene.gameMode.modeId) { + switch (globalScene.gameMode.modeId) { case GameModes.ENDLESS: case GameModes.SPLICED_ENDLESS: valueLimit.value = 15; @@ -2331,7 +2331,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { valueLimit.value = 10; } - Challenge.applyChallenges(gScene.gameMode, Challenge.ChallengeType.STARTER_POINTS, valueLimit); + Challenge.applyChallenges(globalScene.gameMode, Challenge.ChallengeType.STARTER_POINTS, valueLimit); return valueLimit.value; } @@ -2347,7 +2347,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.filterBar.updateFilterLabels(); // pre filter for challenges - if (gScene.gameMode.modeId === GameModes.CHALLENGE) { + if (globalScene.gameMode.modeId === GameModes.CHALLENGE) { this.starterContainers.forEach(container => { const species = container.species; let allFormsValid = false; @@ -2358,12 +2358,12 @@ export default class StarterSelectUiHandler extends MessageUiHandler { */ const tempFormProps = BigInt(Math.pow(2, i)) * DexAttr.DEFAULT_FORM; const isValidForChallenge = new Utils.BooleanHolder(true); - Challenge.applyChallenges(gScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, container.species, isValidForChallenge, gScene.gameData.getSpeciesDexAttrProps(species, tempFormProps), true); + Challenge.applyChallenges(globalScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, container.species, isValidForChallenge, globalScene.gameData.getSpeciesDexAttrProps(species, tempFormProps), true); allFormsValid = allFormsValid || isValidForChallenge.value; } } else { const isValidForChallenge = new Utils.BooleanHolder(true); - Challenge.applyChallenges(gScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, container.species, isValidForChallenge, gScene.gameData.getSpeciesDexAttrProps(species, gScene.gameData.getSpeciesDefaultDexAttr(container.species, false, true)), true); + Challenge.applyChallenges(globalScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, container.species, isValidForChallenge, globalScene.gameData.getSpeciesDexAttrProps(species, globalScene.gameData.getSpeciesDefaultDexAttr(container.species, false, true)), true); allFormsValid = isValidForChallenge.value; } if (allFormsValid) { @@ -2382,7 +2382,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const starterSprite = currentFilteredContainer.icon as Phaser.GameObjects.Sprite; const currentDexAttr = this.getCurrentDexProps(currentFilteredContainer.species.speciesId); - const props = gScene.gameData.getSpeciesDexAttrProps(currentFilteredContainer.species, currentDexAttr); + const props = globalScene.gameData.getSpeciesDexAttrProps(currentFilteredContainer.species, currentDexAttr); starterSprite.setTexture(currentFilteredContainer.species.getIconAtlasKey(props.formIndex, props.shiny, props.variant), currentFilteredContainer.species.getIconId(props.female!, props.formIndex, props.shiny, props.variant)); currentFilteredContainer.checkIconId(props.female, props.formIndex, props.shiny, props.variant); @@ -2392,11 +2392,11 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.validStarterContainers.forEach(container => { container.setVisible(false); - container.cost = gScene.gameData.getSpeciesStarterValue(container.species.speciesId); + container.cost = globalScene.gameData.getSpeciesStarterValue(container.species.speciesId); // First, ensure you have the caught attributes for the species else default to bigint 0 - const caughtAttr = gScene.gameData.dexData[container.species.speciesId]?.caughtAttr || BigInt(0); - const starterData = gScene.gameData.starterData[container.species.speciesId]; + const caughtAttr = globalScene.gameData.dexData[container.species.speciesId]?.caughtAttr || BigInt(0); + const starterData = globalScene.gameData.starterData[container.species.speciesId]; const isStarterProgressable = speciesEggMoves.hasOwnProperty(container.species.speciesId); // Gen filter @@ -2539,12 +2539,12 @@ export default class StarterSelectUiHandler extends MessageUiHandler { case SortCriteria.COST: return (a.cost - b.cost) * -sort.dir; case SortCriteria.CANDY: - const candyCountA = gScene.gameData.starterData[a.species.speciesId].candyCount; - const candyCountB = gScene.gameData.starterData[b.species.speciesId].candyCount; + const candyCountA = globalScene.gameData.starterData[a.species.speciesId].candyCount; + const candyCountB = globalScene.gameData.starterData[b.species.speciesId].candyCount; return (candyCountA - candyCountB) * -sort.dir; case SortCriteria.IV: - const avgIVsA = gScene.gameData.dexData[a.species.speciesId].ivs.reduce((a, b) => a + b, 0) / gScene.gameData.dexData[a.species.speciesId].ivs.length; - const avgIVsB = gScene.gameData.dexData[b.species.speciesId].ivs.reduce((a, b) => a + b, 0) / gScene.gameData.dexData[b.species.speciesId].ivs.length; + const avgIVsA = globalScene.gameData.dexData[a.species.speciesId].ivs.reduce((a, b) => a + b, 0) / globalScene.gameData.dexData[a.species.speciesId].ivs.length; + const avgIVsB = globalScene.gameData.dexData[b.species.speciesId].ivs.reduce((a, b) => a + b, 0) / globalScene.gameData.dexData[b.species.speciesId].ivs.length; return (avgIVsA - avgIVsB) * -sort.dir; case SortCriteria.NAME: return a.species.name.localeCompare(b.species.name) * -sort.dir; @@ -2599,8 +2599,8 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.updateStarterValueLabel(container); container.label.setVisible(true); - const speciesVariants = speciesId && gScene.gameData.dexData[speciesId].caughtAttr & DexAttr.SHINY - ? [ DexAttr.DEFAULT_VARIANT, DexAttr.VARIANT_2, DexAttr.VARIANT_3 ].filter(v => !!(gScene.gameData.dexData[speciesId].caughtAttr & v)) + const speciesVariants = speciesId && globalScene.gameData.dexData[speciesId].caughtAttr & DexAttr.SHINY + ? [ DexAttr.DEFAULT_VARIANT, DexAttr.VARIANT_2, DexAttr.VARIANT_3 ].filter(v => !!(globalScene.gameData.dexData[speciesId].caughtAttr & v)) : []; for (let v = 0; v < 3; v++) { const hasVariant = speciesVariants.length > v; @@ -2610,13 +2610,13 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } } - container.starterPassiveBgs.setVisible(!!gScene.gameData.starterData[speciesId].passiveAttr); - container.hiddenAbilityIcon.setVisible(!!gScene.gameData.dexData[speciesId].caughtAttr && !!(gScene.gameData.starterData[speciesId].abilityAttr & 4)); - container.classicWinIcon.setVisible(gScene.gameData.starterData[speciesId].classicWinCount > 0); + container.starterPassiveBgs.setVisible(!!globalScene.gameData.starterData[speciesId].passiveAttr); + container.hiddenAbilityIcon.setVisible(!!globalScene.gameData.dexData[speciesId].caughtAttr && !!(globalScene.gameData.starterData[speciesId].abilityAttr & 4)); + container.classicWinIcon.setVisible(globalScene.gameData.starterData[speciesId].classicWinCount > 0); container.favoriteIcon.setVisible(this.starterPreferences[speciesId]?.favorite ?? false); // 'Candy Icon' mode - if (gScene.candyUpgradeDisplay === 0) { + if (globalScene.candyUpgradeDisplay === 0) { if (!starterColors[speciesId]) { // Default to white if no colors are found @@ -2628,7 +2628,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { container.candyUpgradeOverlayIcon.setTint(argbFromRgba(Utils.rgbHexToRgba(starterColors[speciesId][1]))); this.setUpgradeIcon(container); - } else if (gScene.candyUpgradeDisplay === 1) { + } else if (globalScene.candyUpgradeDisplay === 1) { container.candyUpgradeIcon.setVisible(false); container.candyUpgradeOverlayIcon.setVisible(false); } @@ -2655,7 +2655,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { if (species) { const defaultDexAttr = this.getCurrentDexProps(species.speciesId); - const defaultProps = gScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); + const defaultProps = globalScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); const variant = this.starterPreferences[species.speciesId]?.variant ? this.starterPreferences[species.speciesId].variant as Variant : defaultProps.variant; const tint = getVariantTint(variant); this.pokemonShinyIcon.setFrame(getVariantIcon(variant)); @@ -2699,7 +2699,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } getFriendship(speciesId: number) { - let currentFriendship = gScene.gameData.starterData[speciesId].friendship; + let currentFriendship = globalScene.gameData.starterData[speciesId].friendship; if (!currentFriendship || currentFriendship === undefined) { currentFriendship = 0; } @@ -2710,13 +2710,13 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } setSpecies(species: PokemonSpecies | null) { - this.speciesStarterDexEntry = species ? gScene.gameData.dexData[species.speciesId] : null; + this.speciesStarterDexEntry = species ? globalScene.gameData.dexData[species.speciesId] : null; this.dexAttrCursor = species ? this.getCurrentDexProps(species.speciesId) : 0n; - this.abilityCursor = species ? gScene.gameData.getStarterSpeciesDefaultAbilityIndex(species) : 0; - this.natureCursor = species ? gScene.gameData.getSpeciesDefaultNature(species) : 0; + this.abilityCursor = species ? globalScene.gameData.getStarterSpeciesDefaultAbilityIndex(species) : 0; + this.natureCursor = species ? globalScene.gameData.getSpeciesDefaultNature(species) : 0; - if (!species && gScene.ui.getTooltip().visible) { - gScene.ui.hideTooltip(); + if (!species && globalScene.ui.getTooltip().visible) { + globalScene.ui.hideTooltip(); } this.pokemonAbilityText.off("pointerover"); @@ -2746,7 +2746,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { if (this.lastSpecies) { const dexAttr = this.getCurrentDexProps(this.lastSpecies.speciesId); - const props = gScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, dexAttr); + const props = globalScene.gameData.getSpeciesDexAttrProps(this.lastSpecies, dexAttr); const speciesIndex = this.allSpecies.indexOf(this.lastSpecies); const lastSpeciesIcon = this.starterContainers[speciesIndex].icon; this.checkIconId(lastSpeciesIcon, this.lastSpecies, props.female, props.formIndex, props.shiny, props.variant); @@ -2754,7 +2754,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { // Resume the animation for the previously selected species const icon = this.starterContainers[speciesIndex].icon; - gScene.tweens.getTweensOf(icon).forEach(tween => tween.resume()); + globalScene.tweens.getTweensOf(icon).forEach(tween => tween.resume()); } this.lastSpecies = species!; // TODO: is this bang correct? @@ -2771,7 +2771,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { if (this.speciesStarterDexEntry?.caughtAttr) { const colorScheme = starterColors[species.speciesId]; - const luck = gScene.gameData.getDexAttrLuck(this.speciesStarterDexEntry.caughtAttr); + const luck = globalScene.gameData.getDexAttrLuck(this.speciesStarterDexEntry.caughtAttr); this.pokemonLuckText.setVisible(!!luck); this.pokemonLuckText.setText(luck.toString()); this.pokemonLuckText.setTint(getVariantTint(Math.min(luck - 1, 2) as Variant)); @@ -2801,7 +2801,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonHatchedCountText.setText(`${this.speciesStarterDexEntry.hatchedCount}`); const defaultDexAttr = this.getCurrentDexProps(species.speciesId); - const defaultProps = gScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); + const defaultProps = globalScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); const variant = defaultProps.variant; const tint = getVariantTint(variant); this.pokemonShinyIcon.setFrame(getVariantIcon(variant)); @@ -2831,7 +2831,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonCandyOverlayIcon.setTint(argbFromRgba(Utils.rgbHexToRgba(colorScheme[1]))); this.pokemonCandyOverlayIcon.setVisible(true); this.pokemonCandyDarknessOverlay.setVisible(true); - this.pokemonCandyCountText.setText(`x${gScene.gameData.starterData[species.speciesId].candyCount}`); + this.pokemonCandyCountText.setText(`x${globalScene.gameData.starterData[species.speciesId].candyCount}`); this.pokemonCandyCountText.setVisible(true); this.pokemonFormText.setY(42); this.pokemonHatchedIcon.setVisible(true); @@ -2842,11 +2842,11 @@ export default class StarterSelectUiHandler extends MessageUiHandler { if (this.pokemonCandyDarknessOverlay.visible) { this.pokemonCandyDarknessOverlay.on("pointerover", () => { - gScene.ui.showTooltip("", `${currentFriendship}/${friendshipCap}`, true); + globalScene.ui.showTooltip("", `${currentFriendship}/${friendshipCap}`, true); this.activeTooltip = "CANDY"; }); this.pokemonCandyDarknessOverlay.on("pointerout", () => { - gScene.ui.hideTooltip(); + globalScene.ui.hideTooltip(); this.activeTooltip = undefined; }); } @@ -2860,7 +2860,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const icon = this.starterContainers[speciesIndex].icon; if (this.isUpgradeAnimationEnabled()) { - gScene.tweens.getTweensOf(icon).forEach(tween => tween.pause()); + globalScene.tweens.getTweensOf(icon).forEach(tween => tween.pause()); // Reset the position of the icon icon.x = -2; icon.y = 2; @@ -2874,14 +2874,14 @@ export default class StarterSelectUiHandler extends MessageUiHandler { let props: DexAttrProps; if (starterIndex > -1) { - props = gScene.gameData.getSpeciesDexAttrProps(species, this.starterAttr[starterIndex]); + props = globalScene.gameData.getSpeciesDexAttrProps(species, this.starterAttr[starterIndex]); this.setSpeciesDetails(species, props.shiny, props.formIndex, props.female, props.variant, this.starterAbilityIndexes[starterIndex], this.starterNatures[starterIndex]); } else { const defaultDexAttr = this.getCurrentDexProps(species.speciesId); - const defaultAbilityIndex = starterAttributes?.ability ?? gScene.gameData.getStarterSpeciesDefaultAbilityIndex(species); + const defaultAbilityIndex = starterAttributes?.ability ?? globalScene.gameData.getStarterSpeciesDefaultAbilityIndex(species); // load default nature from stater save data, if set - const defaultNature = starterAttributes?.nature || gScene.gameData.getSpeciesDefaultNature(species); - props = gScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); + const defaultNature = starterAttributes?.nature || globalScene.gameData.getSpeciesDefaultNature(species); + props = globalScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); if (starterAttributes?.variant && !isNaN(starterAttributes.variant)) { if (props.shiny) { props.variant = starterAttributes.variant as Variant; @@ -2919,10 +2919,10 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonCandyCountText.setVisible(false); this.pokemonFormText.setVisible(false); - const defaultDexAttr = gScene.gameData.getSpeciesDefaultDexAttr(species, true, true); - const defaultAbilityIndex = gScene.gameData.getStarterSpeciesDefaultAbilityIndex(species); - const defaultNature = gScene.gameData.getSpeciesDefaultNature(species); - const props = gScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); + const defaultDexAttr = globalScene.gameData.getSpeciesDefaultDexAttr(species, true, true); + const defaultAbilityIndex = globalScene.gameData.getStarterSpeciesDefaultAbilityIndex(species); + const defaultNature = globalScene.gameData.getSpeciesDefaultNature(species); + const props = globalScene.gameData.getSpeciesDexAttrProps(species, defaultDexAttr); this.setSpeciesDetails(species, props.shiny, props.formIndex, props.female, props.variant, defaultAbilityIndex, defaultNature, true); this.pokemonSprite.setTint(0x808080); @@ -2955,9 +2955,9 @@ export default class StarterSelectUiHandler extends MessageUiHandler { setSpeciesDetails(species: PokemonSpecies, shiny?: boolean, formIndex?: integer, female?: boolean, variant?: Variant, abilityIndex?: integer, natureIndex?: integer, forSeen: boolean = false): void { - const oldProps = species ? gScene.gameData.getSpeciesDexAttrProps(species, this.dexAttrCursor) : null; - const oldAbilityIndex = this.abilityCursor > -1 ? this.abilityCursor : gScene.gameData.getStarterSpeciesDefaultAbilityIndex(species); - const oldNatureIndex = this.natureCursor > -1 ? this.natureCursor : gScene.gameData.getSpeciesDefaultNature(species); + const oldProps = species ? globalScene.gameData.getSpeciesDexAttrProps(species, this.dexAttrCursor) : null; + const oldAbilityIndex = this.abilityCursor > -1 ? this.abilityCursor : globalScene.gameData.getStarterSpeciesDefaultAbilityIndex(species); + const oldNatureIndex = this.natureCursor > -1 ? this.natureCursor : globalScene.gameData.getSpeciesDefaultNature(species); this.dexAttrCursor = 0n; this.abilityCursor = -1; this.natureCursor = -1; @@ -2965,9 +2965,9 @@ export default class StarterSelectUiHandler extends MessageUiHandler { if (this.activeTooltip === "CANDY") { if (this.lastSpecies) { const { currentFriendship, friendshipCap } = this.getFriendship(this.lastSpecies.speciesId); - gScene.ui.editTooltip("", `${currentFriendship}/${friendshipCap}`); + globalScene.ui.editTooltip("", `${currentFriendship}/${friendshipCap}`); } else { - gScene.ui.hideTooltip(); + globalScene.ui.hideTooltip(); } } @@ -2983,7 +2983,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.dexAttrCursor |= (shiny !== undefined ? !shiny : !(shiny = oldProps?.shiny)) ? DexAttr.NON_SHINY : DexAttr.SHINY; this.dexAttrCursor |= (female !== undefined ? !female : !(female = oldProps?.female)) ? DexAttr.MALE : DexAttr.FEMALE; this.dexAttrCursor |= (variant !== undefined ? !variant : !(variant = oldProps?.variant)) ? DexAttr.DEFAULT_VARIANT : variant === 1 ? DexAttr.VARIANT_2 : DexAttr.VARIANT_3; - this.dexAttrCursor |= gScene.gameData.getFormAttr(formIndex !== undefined ? formIndex : (formIndex = oldProps!.formIndex)); // TODO: is this bang correct? + this.dexAttrCursor |= globalScene.gameData.getFormAttr(formIndex !== undefined ? formIndex : (formIndex = oldProps!.formIndex)); // TODO: is this bang correct? this.abilityCursor = abilityIndex !== undefined ? abilityIndex : (abilityIndex = oldAbilityIndex); this.natureCursor = natureIndex !== undefined ? natureIndex : (natureIndex = oldNatureIndex); const [ isInParty, partyIndex ]: [boolean, number] = this.isInParty(species); // we use this to firstly check if the pokemon is in the party, and if so, to get the party index in order to update the icon image @@ -3007,15 +3007,15 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.speciesStarterMoves = []; if (species) { - const dexEntry = gScene.gameData.dexData[species.speciesId]; - const abilityAttr = gScene.gameData.starterData[species.speciesId].abilityAttr; + const dexEntry = globalScene.gameData.dexData[species.speciesId]; + const abilityAttr = globalScene.gameData.starterData[species.speciesId].abilityAttr; - const caughtAttr = gScene.gameData.dexData[species.speciesId]?.caughtAttr || BigInt(0); + const caughtAttr = globalScene.gameData.dexData[species.speciesId]?.caughtAttr || BigInt(0); if (!dexEntry.caughtAttr) { - const props = gScene.gameData.getSpeciesDexAttrProps(species, this.getCurrentDexProps(species.speciesId)); - const defaultAbilityIndex = gScene.gameData.getStarterSpeciesDefaultAbilityIndex(species); - const defaultNature = gScene.gameData.getSpeciesDefaultNature(species); + const props = globalScene.gameData.getSpeciesDexAttrProps(species, this.getCurrentDexProps(species.speciesId)); + const defaultAbilityIndex = globalScene.gameData.getStarterSpeciesDefaultAbilityIndex(species); + const defaultNature = globalScene.gameData.getSpeciesDefaultNature(species); if (shiny === undefined || shiny !== props.shiny) { shiny = props.shiny; @@ -3068,7 +3068,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const isValidForChallenge = new Utils.BooleanHolder(true); - Challenge.applyChallenges(gScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, species, isValidForChallenge, gScene.gameData.getSpeciesDexAttrProps(species, this.dexAttrCursor), !!this.starterSpecies.length); + Challenge.applyChallenges(globalScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, species, isValidForChallenge, globalScene.gameData.getSpeciesDexAttrProps(species, this.dexAttrCursor), !!this.starterSpecies.length); const currentFilteredContainer = this.filteredStarterContainers.find(p => p.species.speciesId === species.speciesId); if (currentFilteredContainer) { const starterSprite = currentFilteredContainer.icon as Phaser.GameObjects.Sprite; @@ -3105,8 +3105,8 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.canCycleAbility = [ hasAbility1, hasAbility2, hasHiddenAbility ].filter(a => a).length > 1; this.canCycleForm = species.forms.filter(f => f.isStarterSelectable || !pokemonFormChanges[species.speciesId]?.find(fc => fc.formKey)) - .map((_, f) => dexEntry.caughtAttr & gScene.gameData.getFormAttr(f)).filter(f => f).length > 1; - this.canCycleNature = gScene.gameData.getNaturesForAttr(dexEntry.natureAttr).length > 1; + .map((_, f) => dexEntry.caughtAttr & globalScene.gameData.getFormAttr(f)).filter(f => f).length > 1; + this.canCycleNature = globalScene.gameData.getNaturesForAttr(dexEntry.natureAttr).length > 1; } @@ -3127,20 +3127,20 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonAbilityText.setColor(this.getTextColor(!isHidden ? TextStyle.SUMMARY_ALT : TextStyle.SUMMARY_GOLD)); this.pokemonAbilityText.setShadowColor(this.getTextColor(!isHidden ? TextStyle.SUMMARY_ALT : TextStyle.SUMMARY_GOLD, true)); - const passiveAttr = gScene.gameData.starterData[species.speciesId].passiveAttr; + const passiveAttr = globalScene.gameData.starterData[species.speciesId].passiveAttr; const passiveAbility = allAbilities[starterPassiveAbilities[this.lastSpecies.speciesId]]; if (this.pokemonAbilityText.visible) { if (this.activeTooltip === "ABILITY") { - gScene.ui.editTooltip(`${ability.name}`, `${ability.description}`); + globalScene.ui.editTooltip(`${ability.name}`, `${ability.description}`); } this.pokemonAbilityText.on("pointerover", () => { - gScene.ui.showTooltip(`${ability.name}`, `${ability.description}`, true); + globalScene.ui.showTooltip(`${ability.name}`, `${ability.description}`, true); this.activeTooltip = "ABILITY"; }); this.pokemonAbilityText.on("pointerout", () => { - gScene.ui.hideTooltip(); + globalScene.ui.hideTooltip(); this.activeTooltip = undefined; }); } @@ -3162,16 +3162,16 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.pokemonPassiveText.setShadowColor(this.getTextColor(textStyle, true)); if (this.activeTooltip === "PASSIVE") { - gScene.ui.editTooltip(`${passiveAbility.name}`, `${passiveAbility.description}`); + globalScene.ui.editTooltip(`${passiveAbility.name}`, `${passiveAbility.description}`); } if (this.pokemonPassiveText.visible) { this.pokemonPassiveText.on("pointerover", () => { - gScene.ui.showTooltip(`${passiveAbility.name}`, `${passiveAbility.description}`, true); + globalScene.ui.showTooltip(`${passiveAbility.name}`, `${passiveAbility.description}`, true); this.activeTooltip = "PASSIVE"; }); this.pokemonPassiveText.on("pointerout", () => { - gScene.ui.hideTooltip(); + globalScene.ui.hideTooltip(); this.activeTooltip = undefined; }); } @@ -3187,7 +3187,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } - this.pokemonNatureText.setText(getNatureName(natureIndex as unknown as Nature, true, true, false, gScene.uiTheme)); + this.pokemonNatureText.setText(getNatureName(natureIndex as unknown as Nature, true, true, false, globalScene.uiTheme)); let levelMoves: LevelMoves; if (pokemonFormLevelMoves.hasOwnProperty(species.speciesId) && formIndex && pokemonFormLevelMoves[species.speciesId].hasOwnProperty(formIndex)) { @@ -3198,19 +3198,19 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.speciesStarterMoves.push(...levelMoves.filter(lm => lm[0] > 0 && lm[0] <= 5).map(lm => lm[1])); if (speciesEggMoves.hasOwnProperty(species.speciesId)) { for (let em = 0; em < 4; em++) { - if (gScene.gameData.starterData[species.speciesId].eggMoves & (1 << em)) { + if (globalScene.gameData.starterData[species.speciesId].eggMoves & (1 << em)) { this.speciesStarterMoves.push(speciesEggMoves[species.speciesId][em]); } } } - const speciesMoveData = gScene.gameData.starterData[species.speciesId].moveset; + const speciesMoveData = globalScene.gameData.starterData[species.speciesId].moveset; const moveData: StarterMoveset | null = speciesMoveData ? Array.isArray(speciesMoveData) ? speciesMoveData : speciesMoveData[formIndex!] // TODO: is this bang correct? : null; - const availableStarterMoves = this.speciesStarterMoves.concat(speciesEggMoves.hasOwnProperty(species.speciesId) ? speciesEggMoves[species.speciesId].filter((_, em: integer) => gScene.gameData.starterData[species.speciesId].eggMoves & (1 << em)) : []); + const availableStarterMoves = this.speciesStarterMoves.concat(speciesEggMoves.hasOwnProperty(species.speciesId) ? speciesEggMoves[species.speciesId].filter((_, em: integer) => globalScene.gameData.starterData[species.speciesId].eggMoves & (1 << em)) : []); this.starterMoveset = (moveData || (this.speciesStarterMoves.slice(0, 4) as StarterMoveset)).filter(m => availableStarterMoves.find(sm => sm === m)) as StarterMoveset; // Consolidate move data if it contains an incompatible move if (this.starterMoveset.length < 4 && this.starterMoveset.length < availableStarterMoves.length) { @@ -3267,7 +3267,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { for (let em = 0; em < 4; em++) { const eggMove = hasEggMoves ? allMoves[speciesEggMoves[species.speciesId][em]] : null; - const eggMoveUnlocked = eggMove && gScene.gameData.starterData[species.speciesId].eggMoves & (1 << em); + const eggMoveUnlocked = eggMove && globalScene.gameData.starterData[species.speciesId].eggMoves & (1 << em); this.pokemonEggMoveBgs[em].setFrame(Type[eggMove ? eggMove.type : Type.UNKNOWN].toString().toLowerCase()); this.pokemonEggMoveLabels[em].setText(eggMove && eggMoveUnlocked ? eggMove.name : "???"); } @@ -3307,7 +3307,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { for (let s = 0; s < this.starterSpecies.length; s++) { const species = this.starterSpecies[s]; const currentDexAttr = this.getCurrentDexProps(species.speciesId); - const props = gScene.gameData.getSpeciesDexAttrProps(species, currentDexAttr); + const props = globalScene.gameData.getSpeciesDexAttrProps(species, currentDexAttr); this.starterIcons[s].setTexture(species.getIconAtlasKey(props.formIndex, props.shiny, props.variant)); this.starterIcons[s].setFrame(species.getIconId(props.female, props.formIndex, props.shiny, props.variant)); this.checkIconId(this.starterIcons[s], species, props.female, props.formIndex, props.shiny, props.variant); @@ -3353,7 +3353,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { updateStarterValueLabel(starter: StarterContainer): void { const speciesId = starter.species.speciesId; const baseStarterValue = speciesStarterCosts[speciesId]; - const starterValue = gScene.gameData.getSpeciesStarterValue(speciesId); + const starterValue = globalScene.gameData.getSpeciesStarterValue(speciesId); starter.cost = starterValue; let valueStr = starterValue.toString(); if (valueStr.startsWith("0.")) { @@ -3380,7 +3380,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { } tryUpdateValue(add?: integer, addingToParty?: boolean): boolean { - const value = this.starterSpecies.map(s => s.generation).reduce((total: integer, gen: integer, i: integer) => total += gScene.gameData.getSpeciesStarterValue(this.starterSpecies[i].speciesId), 0); + const value = this.starterSpecies.map(s => s.generation).reduce((total: integer, gen: integer, i: integer) => total += globalScene.gameData.getSpeciesStarterValue(this.starterSpecies[i].speciesId), 0); const newValue = value + (add || 0); const valueLimit = this.getValueLimit(); const overLimit = newValue > valueLimit; @@ -3392,14 +3392,14 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.valueLimitLabel.setColor(this.getTextColor(!overLimit ? TextStyle.TOOLTIP_CONTENT : TextStyle.SUMMARY_PINK)); this.valueLimitLabel.setShadowColor(this.getTextColor(!overLimit ? TextStyle.TOOLTIP_CONTENT : TextStyle.SUMMARY_PINK, true)); if (overLimit) { - gScene.time.delayedCall(Utils.fixedInt(500), () => this.tryUpdateValue()); + globalScene.time.delayedCall(Utils.fixedInt(500), () => this.tryUpdateValue()); return false; } let isPartyValid: boolean = this.isPartyValid(); // this checks to see if the party is valid if (addingToParty) { // this does a check to see if the pokemon being added is valid; if so, it will update the isPartyValid boolean const isNewPokemonValid = new Utils.BooleanHolder(true); const species = this.filteredStarterContainers[this.cursor].species; - Challenge.applyChallenges(gScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, species, isNewPokemonValid, gScene.gameData.getSpeciesDexAttrProps(species, this.getCurrentDexProps(species.speciesId)), false); + Challenge.applyChallenges(globalScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, species, isNewPokemonValid, globalScene.gameData.getSpeciesDexAttrProps(species, this.getCurrentDexProps(species.speciesId)), false); isPartyValid = isPartyValid || isNewPokemonValid.value; } @@ -3410,9 +3410,9 @@ export default class StarterSelectUiHandler extends MessageUiHandler { const remainValue = valueLimit - newValue; for (let s = 0; s < this.allSpecies.length; s++) { /** Cost of pokemon species */ - const speciesStarterValue = gScene.gameData.getSpeciesStarterValue(this.allSpecies[s].speciesId); + const speciesStarterValue = globalScene.gameData.getSpeciesStarterValue(this.allSpecies[s].speciesId); /** Used to detect if this pokemon is registered in starter */ - const speciesStarterDexEntry = gScene.gameData.dexData[this.allSpecies[s].speciesId]; + const speciesStarterDexEntry = globalScene.gameData.dexData[this.allSpecies[s].speciesId]; /** {@linkcode Phaser.GameObjects.Sprite} object of Pokémon for setting the alpha value */ const speciesSprite = this.starterContainers[s].icon; @@ -3428,7 +3428,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { * we change to can AddParty value to true since the user has enough cost to choose this pokemon and this pokemon registered too. */ const isValidForChallenge = new Utils.BooleanHolder(true); - Challenge.applyChallenges(gScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, this.allSpecies[s], isValidForChallenge, gScene.gameData.getSpeciesDexAttrProps(this.allSpecies[s], this.getCurrentDexProps(this.allSpecies[s].speciesId)), isPartyValid); + Challenge.applyChallenges(globalScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, this.allSpecies[s], isValidForChallenge, globalScene.gameData.getSpeciesDexAttrProps(this.allSpecies[s], this.getCurrentDexProps(this.allSpecies[s].speciesId)), isPartyValid); const canBeChosen = remainValue >= speciesStarterValue && isValidForChallenge.value; @@ -3471,15 +3471,15 @@ export default class StarterSelectUiHandler extends MessageUiHandler { ui.showText(i18next.t("starterSelectUiHandler:confirmExit"), null, () => { ui.setModeWithoutClear(Mode.CONFIRM, () => { ui.setMode(Mode.STARTER_SELECT); - gScene.clearPhaseQueue(); - if (gScene.gameMode.isChallenge) { - gScene.pushPhase(new SelectChallengePhase()); - gScene.pushPhase(new EncounterPhase()); + globalScene.clearPhaseQueue(); + if (globalScene.gameMode.isChallenge) { + globalScene.pushPhase(new SelectChallengePhase()); + globalScene.pushPhase(new EncounterPhase()); } else { - gScene.pushPhase(new TitlePhase()); + globalScene.pushPhase(new TitlePhase()); } this.clearText(); - gScene.getCurrentPhase()?.end(); + globalScene.getCurrentPhase()?.end(); }, cancel, null, null, 19); }); @@ -3507,7 +3507,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { ui.showText(i18next.t("starterSelectUiHandler:confirmStartTeam"), null, () => { ui.setModeWithoutClear(Mode.CONFIRM, () => { const startRun = () => { - gScene.money = gScene.gameMode.getStartingMoney(); + globalScene.money = globalScene.gameMode.getStartingMoney(); ui.setMode(Mode.STARTER_SELECT); const thisObj = this; const originalStarterSelectCallback = this.starterSelectCallback; @@ -3518,7 +3518,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { species: starterSpecies, dexAttr: thisObj.starterAttr[i], abilityIndex: thisObj.starterAbilityIndexes[i], - passive: !(gScene.gameData.starterData[starterSpecies.speciesId].passiveAttr ^ (PassiveAttr.ENABLED | PassiveAttr.UNLOCKED)), + passive: !(globalScene.gameData.starterData[starterSpecies.speciesId].passiveAttr ^ (PassiveAttr.ENABLED | PassiveAttr.UNLOCKED)), nature: thisObj.starterNatures[i] as Nature, moveset: thisObj.starterMovesets[i], pokerus: thisObj.pokerusSpecies.includes(starterSpecies), @@ -3530,9 +3530,9 @@ export default class StarterSelectUiHandler extends MessageUiHandler { }, cancel, null, null, 19); }); } else { - const handler = gScene.ui.getHandler() as AwaitableUiHandler; + const handler = globalScene.ui.getHandler() as AwaitableUiHandler; handler.tutorialActive = true; - gScene.ui.showText(i18next.t("starterSelectUiHandler:invalidParty"), null, () => gScene.ui.showText("", 0, () => handler.tutorialActive = false), null, true); + globalScene.ui.showText(i18next.t("starterSelectUiHandler:invalidParty"), null, () => globalScene.ui.showText("", 0, () => handler.tutorialActive = false), null, true); } return true; } @@ -3545,7 +3545,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { for (let s = 0; s < this.starterSpecies.length; s++) { const isValidForChallenge = new Utils.BooleanHolder(true); const species = this.starterSpecies[s]; - Challenge.applyChallenges(gScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, species, isValidForChallenge, gScene.gameData.getSpeciesDexAttrProps(species, this.getCurrentDexProps(species.speciesId)), false); + Challenge.applyChallenges(globalScene.gameMode, Challenge.ChallengeType.STARTER_CHOICE, species, isValidForChallenge, globalScene.gameData.getSpeciesDexAttrProps(species, this.getCurrentDexProps(species.speciesId)), false); canStart = canStart || isValidForChallenge.value; } return canStart; @@ -3560,7 +3560,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { */ getCurrentDexProps(speciesId: number): bigint { let props = 0n; - const caughtAttr = gScene.gameData.dexData[speciesId].caughtAttr; + const caughtAttr = globalScene.gameData.dexData[speciesId].caughtAttr; /* this checks the gender of the pokemon; this works by checking a) that the starter preferences for the species exist, and if so, is it female. If so, it'll add DexAttr.FEMALE to our temp props * It then checks b) if the caughtAttr for the pokemon is female and NOT male - this means that the ONLY gender we've gotten is female, and we need to add DexAttr.FEMALE to our temp props @@ -3598,7 +3598,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { props += BigInt(Math.pow(2, this.starterPreferences[speciesId]?.form)) * DexAttr.DEFAULT_FORM; } else { // Get the first unlocked form - props += gScene.gameData.getFormAttr(gScene.gameData.getFormIndex(caughtAttr)); + props += globalScene.gameData.getFormAttr(globalScene.gameData.getFormIndex(caughtAttr)); } return props; @@ -3660,7 +3660,7 @@ export default class StarterSelectUiHandler extends MessageUiHandler { this.cursor = -1; this.hideInstructions(); this.activeTooltip = undefined; - gScene.ui.hideTooltip(); + globalScene.ui.hideTooltip(); this.starterSelectContainer.setVisible(false); this.blockInput = false; diff --git a/src/ui/stats-container.ts b/src/ui/stats-container.ts index ab090ffa0c2..8398f94c681 100644 --- a/src/ui/stats-container.ts +++ b/src/ui/stats-container.ts @@ -2,7 +2,7 @@ import BBCodeText from "phaser3-rex-plugins/plugins/gameobjects/tagtext/bbcodete import { TextStyle, addBBCodeTextObject, addTextObject, getTextColor } from "./text"; import { PERMANENT_STATS, getStatKey } from "#app/enums/stat"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; const ivChartSize = 24; @@ -22,7 +22,7 @@ export class StatsContainer extends Phaser.GameObjects.Container { private ivStatValueTexts: BBCodeText[]; constructor(x: number, y: number, showDiff?: boolean) { - super(gScene, x, y); + super(globalScene, x, y); this.showDiff = !!showDiff; @@ -32,21 +32,21 @@ export class StatsContainer extends Phaser.GameObjects.Container { setup() { this.setName("stats"); const ivChartBgData = new Array(6).fill(null).map((_, i: integer) => [ ivChartSize * ivChartStatCoordMultipliers[ivChartStatIndexes[i]][0], ivChartSize * ivChartStatCoordMultipliers[ivChartStatIndexes[i]][1] ] ).flat(); - const ivChartBg = gScene.add.polygon(48, 44, ivChartBgData, 0xd8e0f0, 0.625); + const ivChartBg = globalScene.add.polygon(48, 44, ivChartBgData, 0xd8e0f0, 0.625); ivChartBg.setOrigin(0, 0); - const ivChartBorder = gScene.add.polygon(ivChartBg.x, ivChartBg.y, ivChartBgData) + const ivChartBorder = globalScene.add.polygon(ivChartBg.x, ivChartBg.y, ivChartBgData) .setStrokeStyle(1, 0x484050); ivChartBorder.setOrigin(0, 0); const ivChartBgLines = [[ 0, -1, 0, 1 ], [ -0.825, -0.5, 0.825, 0.5 ], [ 0.825, -0.5, -0.825, 0.5 ]].map(coords => { - const line = new Phaser.GameObjects.Line(gScene, ivChartBg.x, ivChartBg.y, ivChartSize * coords[0], ivChartSize * coords[1], ivChartSize * coords[2], ivChartSize * coords[3], 0xffffff) + const line = new Phaser.GameObjects.Line(globalScene, ivChartBg.x, ivChartBg.y, ivChartSize * coords[0], ivChartSize * coords[1], ivChartSize * coords[2], ivChartSize * coords[3], 0xffffff) .setLineWidth(0.5); line.setOrigin(0, 0); return line; }); - this.ivChart = gScene.add.polygon(ivChartBg.x, ivChartBg.y, defaultIvChartData, 0x98d8a0, 0.75); + this.ivChart = globalScene.add.polygon(ivChartBg.x, ivChartBg.y, defaultIvChartData, 0x98d8a0, 0.75); this.ivChart.setOrigin(0, 0); this.add(ivChartBg); @@ -78,7 +78,7 @@ export class StatsContainer extends Phaser.GameObjects.Container { if (ivs) { const ivChartData = new Array(6).fill(null).map((_, i) => [ (ivs[ivChartStatIndexes[i]] / 31) * ivChartSize * ivChartStatCoordMultipliers[ivChartStatIndexes[i]][0], (ivs[ivChartStatIndexes[i]] / 31) * ivChartSize * ivChartStatCoordMultipliers[ivChartStatIndexes[i]][1] ] ).flat(); const lastIvChartData = this.statsIvsCache || defaultIvChartData; - const perfectIVColor: string = getTextColor(TextStyle.SUMMARY_GOLD, false, gScene.uiTheme); + const perfectIVColor: string = getTextColor(TextStyle.SUMMARY_GOLD, false, globalScene.uiTheme); this.statsIvsCache = ivChartData.slice(0); this.ivStatValueTexts.map((t: BBCodeText, i: integer) => { @@ -92,7 +92,7 @@ export class StatsContainer extends Phaser.GameObjects.Container { } if (this.showDiff && originalIvs) { if (originalIvs[i] < ivs[i]) { - label += ` ([color=${getTextColor(TextStyle.SUMMARY_BLUE, false, gScene.uiTheme)}][shadow=${getTextColor(TextStyle.SUMMARY_BLUE, true, gScene.uiTheme)}]+${ivs[i] - originalIvs[i]}[/shadow][/color])`; + label += ` ([color=${getTextColor(TextStyle.SUMMARY_BLUE, false, globalScene.uiTheme)}][shadow=${getTextColor(TextStyle.SUMMARY_BLUE, true, globalScene.uiTheme)}]+${ivs[i] - originalIvs[i]}[/shadow][/color])`; } else { label += " (-)"; } @@ -107,7 +107,7 @@ export class StatsContainer extends Phaser.GameObjects.Container { Phaser.Display.Color.IntegerToColor(newColor) ] : null; - gScene.tweens.addCounter({ + globalScene.tweens.addCounter({ from: 0, to: 1, duration: 1000, diff --git a/src/ui/summary-ui-handler.ts b/src/ui/summary-ui-handler.ts index cd52f5823a0..1a874043172 100644 --- a/src/ui/summary-ui-handler.ts +++ b/src/ui/summary-ui-handler.ts @@ -1,4 +1,4 @@ -import { gScene, starterColors } from "#app/battle-scene"; +import { globalScene, starterColors } from "#app/battle-scene"; import { Mode } from "#app/ui/ui"; import UiHandler from "#app/ui/ui-handler"; import * as Utils from "#app/utils"; @@ -116,15 +116,15 @@ export default class SummaryUiHandler extends UiHandler { setup() { const ui = this.getUi(); - this.summaryContainer = gScene.add.container(0, 0); + this.summaryContainer = globalScene.add.container(0, 0); this.summaryContainer.setVisible(false); ui.add(this.summaryContainer); - const summaryBg = gScene.add.image(0, 0, "summary_bg"); + const summaryBg = globalScene.add.image(0, 0, "summary_bg"); summaryBg.setOrigin(0, 1); this.summaryContainer.add(summaryBg); - this.tabSprite = gScene.add.sprite(134, (-summaryBg.displayHeight) + 16, "summary_tabs_1"); + this.tabSprite = globalScene.add.sprite(134, (-summaryBg.displayHeight) + 16, "summary_tabs_1"); this.tabSprite.setOrigin(1, 1); this.summaryContainer.add(this.tabSprite); @@ -132,7 +132,7 @@ export default class SummaryUiHandler extends UiHandler { summaryLabel.setOrigin(0, 1); this.summaryContainer.add(summaryLabel); - this.shinyOverlay = gScene.add.image(6, -54, "summary_overlay_shiny"); + this.shinyOverlay = globalScene.add.image(6, -54, "summary_overlay_shiny"); this.shinyOverlay.setOrigin(0, 1); this.shinyOverlay.setVisible(false); this.summaryContainer.add(this.shinyOverlay); @@ -141,46 +141,46 @@ export default class SummaryUiHandler extends UiHandler { this.numberText.setOrigin(0, 1); this.summaryContainer.add(this.numberText); - this.pokemonSprite = gScene.initPokemonSprite(gScene.add.sprite(56, -106, "pkmn__sub"), undefined, false, true); + this.pokemonSprite = globalScene.initPokemonSprite(globalScene.add.sprite(56, -106, "pkmn__sub"), undefined, false, true); this.summaryContainer.add(this.pokemonSprite); this.nameText = addTextObject(6, -54, "", TextStyle.SUMMARY); this.nameText.setOrigin(0, 0); this.summaryContainer.add(this.nameText); - this.splicedIcon = gScene.add.sprite(0, -54, "icon_spliced"); + this.splicedIcon = globalScene.add.sprite(0, -54, "icon_spliced"); this.splicedIcon.setVisible(false); this.splicedIcon.setOrigin(0, 0); this.splicedIcon.setScale(0.75); this.splicedIcon.setInteractive(new Phaser.Geom.Rectangle(0, 0, 12, 15), Phaser.Geom.Rectangle.Contains); this.summaryContainer.add(this.splicedIcon); - this.shinyIcon = gScene.add.image(0, -54, "shiny_star"); + this.shinyIcon = globalScene.add.image(0, -54, "shiny_star"); this.shinyIcon.setVisible(false); this.shinyIcon.setOrigin(0, 0); this.shinyIcon.setScale(0.75); this.shinyIcon.setInteractive(new Phaser.Geom.Rectangle(0, 0, 12, 15), Phaser.Geom.Rectangle.Contains); this.summaryContainer.add(this.shinyIcon); - this.fusionShinyIcon = gScene.add.image(0, 0, "shiny_star_2"); + this.fusionShinyIcon = globalScene.add.image(0, 0, "shiny_star_2"); this.fusionShinyIcon.setVisible(false); this.fusionShinyIcon.setOrigin(0, 0); this.fusionShinyIcon.setScale(0.75); this.summaryContainer.add(this.fusionShinyIcon); - this.pokeball = gScene.add.sprite(6, -19, "pb"); + this.pokeball = globalScene.add.sprite(6, -19, "pb"); this.pokeball.setOrigin(0, 1); this.summaryContainer.add(this.pokeball); - this.candyIcon = gScene.add.sprite(13, -140, "candy"); + this.candyIcon = globalScene.add.sprite(13, -140, "candy"); this.candyIcon.setScale(0.8); this.summaryContainer.add(this.candyIcon); - this.candyOverlay = gScene.add.sprite(13, -140, "candy_overlay"); + this.candyOverlay = globalScene.add.sprite(13, -140, "candy_overlay"); this.candyOverlay.setScale(0.8); this.summaryContainer.add(this.candyOverlay); - this.candyShadow = gScene.add.sprite(13, -140, "candy"); + this.candyShadow = globalScene.add.sprite(13, -140, "candy"); this.candyShadow.setTint(0x000000); this.candyShadow.setAlpha(0.50); this.candyShadow.setScale(0.8); @@ -191,15 +191,15 @@ export default class SummaryUiHandler extends UiHandler { this.candyCountText.setOrigin(0, 0); this.summaryContainer.add(this.candyCountText); - this.friendshipIcon = gScene.add.sprite(13, -60, "friendship"); + this.friendshipIcon = globalScene.add.sprite(13, -60, "friendship"); this.friendshipIcon.setScale(0.8); this.summaryContainer.add(this.friendshipIcon); - this.friendshipOverlay = gScene.add.sprite(13, -60, "friendship_overlay"); + this.friendshipOverlay = globalScene.add.sprite(13, -60, "friendship_overlay"); this.friendshipOverlay.setScale(0.8); this.summaryContainer.add(this.friendshipOverlay); - this.friendshipShadow = gScene.add.sprite(13, -60, "friendship"); + this.friendshipShadow = globalScene.add.sprite(13, -60, "friendship"); this.friendshipShadow.setTint(0x000000); this.friendshipShadow.setAlpha(0.50); this.friendshipShadow.setScale(0.8); @@ -210,7 +210,7 @@ export default class SummaryUiHandler extends UiHandler { this.friendshipText.setOrigin(0, 0); this.summaryContainer.add(this.friendshipText); - this.championRibbon = gScene.add.image(88, -146, "champion_ribbon"); + this.championRibbon = globalScene.add.image(88, -146, "champion_ribbon"); this.championRibbon.setOrigin(0, 0); //this.championRibbon.setScale(0.8); this.championRibbon.setScale(1.25); @@ -225,9 +225,9 @@ export default class SummaryUiHandler extends UiHandler { this.genderText.setOrigin(0, 1); this.summaryContainer.add(this.genderText); - this.statusContainer = gScene.add.container(-106, -16); + this.statusContainer = globalScene.add.container(-106, -16); - const statusBg = gScene.add.image(0, 0, "summary_status"); + const statusBg = globalScene.add.image(0, 0, "summary_status"); statusBg.setOrigin(0, 0); this.statusContainer.add(statusBg); @@ -237,18 +237,18 @@ export default class SummaryUiHandler extends UiHandler { this.statusContainer.add(statusLabel); - this.status = gScene.add.sprite(91, 4, Utils.getLocalizedSpriteKey("statuses")); + this.status = globalScene.add.sprite(91, 4, Utils.getLocalizedSpriteKey("statuses")); this.status.setOrigin(0.5, 0); this.statusContainer.add(this.status); this.summaryContainer.add(this.statusContainer); - this.moveEffectContainer = gScene.add.container(106, -62); + this.moveEffectContainer = globalScene.add.container(106, -62); this.summaryContainer.add(this.moveEffectContainer); - const moveEffectBg = gScene.add.image(0, 0, "summary_moves_effect"); + const moveEffectBg = globalScene.add.image(0, 0, "summary_moves_effect"); moveEffectBg.setOrigin(0, 0); this.moveEffectContainer.add(moveEffectBg); @@ -266,20 +266,20 @@ export default class SummaryUiHandler extends UiHandler { this.moveAccuracyText.setOrigin(1, 1); this.moveEffectContainer.add(this.moveAccuracyText); - this.moveCategoryIcon = gScene.add.sprite(99, 57, "categories"); + this.moveCategoryIcon = globalScene.add.sprite(99, 57, "categories"); this.moveCategoryIcon.setOrigin(1, 1); this.moveEffectContainer.add(this.moveCategoryIcon); const getSummaryPageBg = () => { - const ret = gScene.add.sprite(0, 0, this.getPageKey(0)); + const ret = globalScene.add.sprite(0, 0, this.getPageKey(0)); ret.setOrigin(0, 1); return ret; }; - this.summaryContainer.add((this.summaryPageContainer = gScene.add.container(106, 0))); + this.summaryContainer.add((this.summaryPageContainer = globalScene.add.container(106, 0))); this.summaryPageContainer.add(getSummaryPageBg()); this.summaryPageContainer.setVisible(false); - this.summaryContainer.add((this.summaryPageTransitionContainer = gScene.add.container(106, 0))); + this.summaryContainer.add((this.summaryPageTransitionContainer = globalScene.add.container(106, 0))); this.summaryPageTransitionContainer.add(getSummaryPageBg()); this.summaryPageTransitionContainer.setVisible(false); } @@ -304,7 +304,7 @@ export default class SummaryUiHandler extends UiHandler { this.pokemon = args[0] as PlayerPokemon; this.summaryUiMode = args.length > 1 ? args[1] as SummaryUiMode : SummaryUiMode.DEFAULT; this.playerParty = args[4] ?? true; - gScene.ui.bringToTop(this.summaryContainer); + globalScene.ui.bringToTop(this.summaryContainer); this.summaryContainer.setVisible(true); this.cursor = -1; @@ -342,17 +342,17 @@ export default class SummaryUiHandler extends UiHandler { this.splicedIcon.setPositionRelative(this.nameText, this.nameText.displayWidth + 2, 3); this.splicedIcon.setVisible(isFusion); if (this.splicedIcon.visible) { - this.splicedIcon.on("pointerover", () => gScene.ui.showTooltip("", `${this.pokemon?.species.getName(this.pokemon.formIndex)}/${this.pokemon?.fusionSpecies?.getName(this.pokemon?.fusionFormIndex)}`, true)); - this.splicedIcon.on("pointerout", () => gScene.ui.hideTooltip()); + this.splicedIcon.on("pointerover", () => globalScene.ui.showTooltip("", `${this.pokemon?.species.getName(this.pokemon.formIndex)}/${this.pokemon?.fusionSpecies?.getName(this.pokemon?.fusionFormIndex)}`, true)); + this.splicedIcon.on("pointerout", () => globalScene.ui.hideTooltip()); } - if (gScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()].classicWinCount > 0 && gScene.gameData.starterData[this.pokemon.species.getRootSpeciesId(true)].classicWinCount > 0) { + if (globalScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()].classicWinCount > 0 && globalScene.gameData.starterData[this.pokemon.species.getRootSpeciesId(true)].classicWinCount > 0) { this.championRibbon.setVisible(true); } else { this.championRibbon.setVisible(false); } - let currentFriendship = gScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()].friendship; + let currentFriendship = globalScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()].friendship; if (!currentFriendship || currentFriendship === undefined) { currentFriendship = 0; } @@ -361,17 +361,17 @@ export default class SummaryUiHandler extends UiHandler { const candyCropY = 16 - (16 * (currentFriendship / friendshipCap)); if (this.candyShadow.visible) { - this.candyShadow.on("pointerover", () => gScene.ui.showTooltip("", `${currentFriendship}/${friendshipCap}`, true)); - this.candyShadow.on("pointerout", () => gScene.ui.hideTooltip()); + this.candyShadow.on("pointerover", () => globalScene.ui.showTooltip("", `${currentFriendship}/${friendshipCap}`, true)); + this.candyShadow.on("pointerout", () => globalScene.ui.hideTooltip()); } - this.candyCountText.setText(`x${gScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()].candyCount}`); + this.candyCountText.setText(`x${globalScene.gameData.starterData[this.pokemon.species.getRootSpeciesId()].candyCount}`); this.candyShadow.setCrop(0, 0, 16, candyCropY); if (this.friendshipShadow.visible) { - this.friendshipShadow.on("pointerover", () => gScene.ui.showTooltip("", `${i18next.t("pokemonSummary:friendship")}`, true)); - this.friendshipShadow.on("pointerout", () => gScene.ui.hideTooltip()); + this.friendshipShadow.on("pointerover", () => globalScene.ui.showTooltip("", `${i18next.t("pokemonSummary:friendship")}`, true)); + this.friendshipShadow.on("pointerout", () => globalScene.ui.hideTooltip()); } this.friendshipText.setText(`${this.pokemon?.friendship || "0"} / 255`); @@ -389,8 +389,8 @@ export default class SummaryUiHandler extends UiHandler { const shinyDescriptor = doubleShiny || baseVariant ? `${baseVariant === 2 ? i18next.t("common:epicShiny") : baseVariant === 1 ? i18next.t("common:rareShiny") : i18next.t("common:commonShiny")}${doubleShiny ? `/${this.pokemon.fusionVariant === 2 ? i18next.t("common:epicShiny") : this.pokemon.fusionVariant === 1 ? i18next.t("common:rareShiny") : i18next.t("common:commonShiny")}` : ""}` : ""; - this.shinyIcon.on("pointerover", () => gScene.ui.showTooltip("", `${i18next.t("common:shinyOnHover")}${shinyDescriptor ? ` (${shinyDescriptor})` : ""}`, true)); - this.shinyIcon.on("pointerout", () => gScene.ui.hideTooltip()); + this.shinyIcon.on("pointerover", () => globalScene.ui.showTooltip("", `${i18next.t("common:shinyOnHover")}${shinyDescriptor ? ` (${shinyDescriptor})` : ""}`, true)); + this.shinyIcon.on("pointerout", () => globalScene.ui.hideTooltip()); } this.fusionShinyIcon.setPosition(this.shinyIcon.x, this.shinyIcon.y); @@ -554,7 +554,7 @@ export default class SummaryUiHandler extends UiHandler { break; } const isDown = button === Button.DOWN; - const party = gScene.getParty(); + const party = globalScene.getParty(); const partyMemberIndex = this.pokemon ? party.indexOf(this.pokemon) : -1; if ((isDown && partyMemberIndex < party.length - 1) || (!isDown && partyMemberIndex)) { const page = this.cursor; @@ -615,7 +615,7 @@ export default class SummaryUiHandler extends UiHandler { } if (moveDescriptionLineCount > 3) { - this.descriptionScrollTween = gScene.tweens.add({ + this.descriptionScrollTween = globalScene.tweens.add({ targets: this.moveDescriptionText, delay: Utils.fixedInt(2000), loop: -1, @@ -626,7 +626,7 @@ export default class SummaryUiHandler extends UiHandler { } if (!this.moveCursorObj) { - this.moveCursorObj = gScene.add.sprite(-2, 0, "summary_moves_cursor", "highlight"); + this.moveCursorObj = globalScene.add.sprite(-2, 0, "summary_moves_cursor", "highlight"); this.moveCursorObj.setOrigin(0, 1); this.movesContainer.add(this.moveCursorObj); } @@ -637,12 +637,12 @@ export default class SummaryUiHandler extends UiHandler { this.moveCursorBlinkTimer.destroy(); } this.moveCursorObj.setVisible(true); - this.moveCursorBlinkTimer = gScene.time.addEvent({ + this.moveCursorBlinkTimer = globalScene.time.addEvent({ loop: true, delay: Utils.fixedInt(600), callback: () => { this.moveCursorObj?.setVisible(false); - gScene.time.delayedCall(Utils.fixedInt(100), () => { + globalScene.time.delayedCall(Utils.fixedInt(100), () => { if (!this.moveCursorObj) { return; } @@ -652,7 +652,7 @@ export default class SummaryUiHandler extends UiHandler { }); if (this.selectedMoveIndex > -1) { if (!this.selectedMoveCursorObj) { - this.selectedMoveCursorObj = gScene.add.sprite(-2, 0, "summary_moves_cursor", "select"); + this.selectedMoveCursorObj = globalScene.add.sprite(-2, 0, "summary_moves_cursor", "select"); this.selectedMoveCursorObj.setOrigin(0, 1); this.movesContainer.add(this.selectedMoveCursorObj); this.movesContainer.moveBelow(this.selectedMoveCursorObj, this.moveCursorObj); @@ -678,7 +678,7 @@ export default class SummaryUiHandler extends UiHandler { } else { this.populatePageContainer(this.summaryPageContainer); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.summaryPageTransitionContainer, x: forward ? "-=214" : "+=214", duration: 250, @@ -731,15 +731,15 @@ export default class SummaryUiHandler extends UiHandler { switch (page) { case Page.PROFILE: - const profileContainer = gScene.add.container(0, -pageBg.height); + const profileContainer = globalScene.add.container(0, -pageBg.height); pageContainer.add(profileContainer); // TODO: should add field for original trainer name to Pokemon object, to support gift/traded Pokemon from MEs - const trainerText = addBBCodeTextObject(7, 12, `${i18next.t("pokemonSummary:ot")}/${getBBCodeFrag(loggedInUser?.username || i18next.t("pokemonSummary:unknown"), gScene.gameData.gender === PlayerGender.FEMALE ? TextStyle.SUMMARY_PINK : TextStyle.SUMMARY_BLUE)}`, TextStyle.SUMMARY_ALT); + const trainerText = addBBCodeTextObject(7, 12, `${i18next.t("pokemonSummary:ot")}/${getBBCodeFrag(loggedInUser?.username || i18next.t("pokemonSummary:unknown"), globalScene.gameData.gender === PlayerGender.FEMALE ? TextStyle.SUMMARY_PINK : TextStyle.SUMMARY_BLUE)}`, TextStyle.SUMMARY_ALT); trainerText.setOrigin(0, 0); profileContainer.add(trainerText); - const trainerIdText = addTextObject(174, 12, gScene.gameData.trainerId.toString(), TextStyle.SUMMARY_ALT); + const trainerIdText = addTextObject(174, 12, globalScene.gameData.trainerId.toString(), TextStyle.SUMMARY_ALT); trainerIdText.setOrigin(0, 0); profileContainer.add(trainerIdText); @@ -750,8 +750,8 @@ export default class SummaryUiHandler extends UiHandler { const getTypeIcon = (index: integer, type: Type, tera: boolean = false) => { const xCoord = typeLabel.width * typeLabel.scale + 9 + 34 * index; const typeIcon = !tera - ? gScene.add.sprite(xCoord, 42, Utils.getLocalizedSpriteKey("types"), Type[type].toLowerCase()) - : gScene.add.sprite(xCoord, 42, "type_tera"); + ? globalScene.add.sprite(xCoord, 42, Utils.getLocalizedSpriteKey("types"), Type[type].toLowerCase()) + : globalScene.add.sprite(xCoord, 42, "type_tera"); if (tera) { typeIcon.setScale(0.5); const typeRgb = getTypeRgb(type); @@ -782,7 +782,7 @@ export default class SummaryUiHandler extends UiHandler { } this.abilityContainer = { - labelImage: gScene.add.image(0, 0, "summary_profile_ability"), + labelImage: globalScene.add.image(0, 0, "summary_profile_ability"), ability: this.pokemon?.getAbility(true)!, // TODO: is this bang correct? nameText: null, descriptionText: null }; @@ -791,14 +791,14 @@ export default class SummaryUiHandler extends UiHandler { // Only add to the array and set up displaying a passive if it's unlocked if (this.pokemon?.hasPassive()) { this.passiveContainer = { - labelImage: gScene.add.image(0, 0, "summary_profile_passive"), + labelImage: globalScene.add.image(0, 0, "summary_profile_passive"), ability: this.pokemon.getPassiveAbility(), nameText: null, descriptionText: null }; allAbilityInfo.push(this.passiveContainer); // Sets up the pixel button prompt image - this.abilityPrompt = gScene.add.image(0, 0, !gScene.inputController?.gamepadSupport ? "summary_profile_prompt_z" : "summary_profile_prompt_a"); + this.abilityPrompt = globalScene.add.image(0, 0, !globalScene.inputController?.gamepadSupport ? "summary_profile_prompt_z" : "summary_profile_prompt_a"); this.abilityPrompt.setPosition(8, 43); this.abilityPrompt.setVisible(true); this.abilityPrompt.setOrigin(0, 0); @@ -820,7 +820,7 @@ export default class SummaryUiHandler extends UiHandler { profileContainer.add(abilityInfo.descriptionText); // Sets up the mask that hides the description text to give an illusion of scrolling - const descriptionTextMaskRect = gScene.make.graphics({}); + const descriptionTextMaskRect = globalScene.make.graphics({}); descriptionTextMaskRect.setScale(6); descriptionTextMaskRect.fillStyle(0xFFFFFF); descriptionTextMaskRect.beginPath(); @@ -835,7 +835,7 @@ export default class SummaryUiHandler extends UiHandler { // Animates the description text moving upwards if (abilityDescriptionLineCount > 2) { abilityInfo.descriptionText.setY(69); - this.descriptionScrollTween = gScene.tweens.add({ + this.descriptionScrollTween = globalScene.tweens.add({ targets: abilityInfo.descriptionText, delay: Utils.fixedInt(2000), loop: -1, @@ -868,7 +868,7 @@ export default class SummaryUiHandler extends UiHandler { profileContainer.add(memoText); break; case Page.STATS: - const statsContainer = gScene.add.container(0, -pageBg.height); + const statsContainer = globalScene.add.container(0, -pageBg.height); pageContainer.add(statsContainer); PERMANENT_STATS.forEach((stat, s) => { @@ -891,7 +891,7 @@ export default class SummaryUiHandler extends UiHandler { statsContainer.add(statValue); }); - const itemModifiers = (gScene.findModifiers(m => m instanceof PokemonHeldItemModifier + const itemModifiers = (globalScene.findModifiers(m => m instanceof PokemonHeldItemModifier && m.pokemonId === this.pokemon?.id, this.playerParty) as PokemonHeldItemModifier[]) .sort(modifierSortFunc); @@ -902,8 +902,8 @@ export default class SummaryUiHandler extends UiHandler { statsContainer.add(icon); icon.setInteractive(new Phaser.Geom.Rectangle(0, 0, 32, 32), Phaser.Geom.Rectangle.Contains); - icon.on("pointerover", () => gScene.ui.showTooltip(item.type.name, item.type.getDescription(), true)); - icon.on("pointerout", () => gScene.ui.hideTooltip()); + icon.on("pointerover", () => globalScene.ui.showTooltip(item.type.name, item.type.getDescription(), true)); + icon.on("pointerout", () => globalScene.ui.hideTooltip()); }); const pkmLvl = this.pokemon?.level!; // TODO: is this bang correct? @@ -911,7 +911,7 @@ export default class SummaryUiHandler extends UiHandler { const pkmExp = this.pokemon?.exp!; // TODO: is this bang correct? const pkmSpeciesGrowthRate = this.pokemon?.species.growthRate!; // TODO: is this bang correct? const relLvExp = getLevelRelExp(pkmLvl + 1, pkmSpeciesGrowthRate); - const expRatio = pkmLvl < gScene.getMaxExpLevel() ? pkmLvlExp / relLvExp : 0; + const expRatio = pkmLvl < globalScene.getMaxExpLevel() ? pkmLvlExp / relLvExp : 0; const expLabel = addTextObject(6, 112, i18next.t("pokemonSummary:expPoints"), TextStyle.SUMMARY); expLabel.setOrigin(0, 0); @@ -925,18 +925,18 @@ export default class SummaryUiHandler extends UiHandler { expText.setOrigin(1, 0); statsContainer.add(expText); - const nextLvExp = pkmLvl < gScene.getMaxExpLevel() + const nextLvExp = pkmLvl < globalScene.getMaxExpLevel() ? getLevelTotalExp(pkmLvl + 1, pkmSpeciesGrowthRate) - pkmExp : 0; const nextLvExpText = addTextObject(208, 128, nextLvExp.toString(), TextStyle.WINDOW_ALT); nextLvExpText.setOrigin(1, 0); statsContainer.add(nextLvExpText); - const expOverlay = gScene.add.image(140, 145, "summary_stats_overlay_exp"); + const expOverlay = globalScene.add.image(140, 145, "summary_stats_overlay_exp"); expOverlay.setOrigin(0, 0); statsContainer.add(expOverlay); - const expMaskRect = gScene.make.graphics({}); + const expMaskRect = globalScene.make.graphics({}); expMaskRect.setScale(6); expMaskRect.fillStyle(0xFFFFFF); expMaskRect.beginPath(); @@ -947,14 +947,14 @@ export default class SummaryUiHandler extends UiHandler { expOverlay.setMask(expMask); break; case Page.MOVES: - this.movesContainer = gScene.add.container(5, -pageBg.height + 26); + this.movesContainer = globalScene.add.container(5, -pageBg.height + 26); pageContainer.add(this.movesContainer); - this.extraMoveRowContainer = gScene.add.container(0, 64); + this.extraMoveRowContainer = globalScene.add.container(0, 64); this.extraMoveRowContainer.setVisible(false); this.movesContainer.add(this.extraMoveRowContainer); - const extraRowOverlay = gScene.add.image(-2, 1, "summary_moves_overlay_row"); + const extraRowOverlay = globalScene.add.image(-2, 1, "summary_moves_overlay_row"); extraRowOverlay.setOrigin(0, 1); this.extraMoveRowContainer.add(extraRowOverlay); @@ -969,11 +969,11 @@ export default class SummaryUiHandler extends UiHandler { if (this.newMove && this.pokemon) { const spriteKey = Utils.getLocalizedSpriteKey("types"); const moveType = this.pokemon.getMoveType(this.newMove); - const newMoveTypeIcon = gScene.add.sprite(0, 0, spriteKey, Type[moveType].toLowerCase()); + const newMoveTypeIcon = globalScene.add.sprite(0, 0, spriteKey, Type[moveType].toLowerCase()); newMoveTypeIcon.setOrigin(0, 1); this.extraMoveRowContainer.add(newMoveTypeIcon); } - const ppOverlay = gScene.add.image(163, -1, "summary_moves_overlay_pp"); + const ppOverlay = globalScene.add.image(163, -1, "summary_moves_overlay_pp"); ppOverlay.setOrigin(0, 1); this.extraMoveRowContainer.add(ppOverlay); @@ -983,18 +983,18 @@ export default class SummaryUiHandler extends UiHandler { this.extraMoveRowContainer.add(ppText); } - this.moveRowsContainer = gScene.add.container(0, 0); + this.moveRowsContainer = globalScene.add.container(0, 0); this.movesContainer.add(this.moveRowsContainer); for (let m = 0; m < 4; m++) { const move: PokemonMove | null = this.pokemon && this.pokemon.moveset.length > m ? this.pokemon?.moveset[m] : null; - const moveRowContainer = gScene.add.container(0, 16 * m); + const moveRowContainer = globalScene.add.container(0, 16 * m); this.moveRowsContainer.add(moveRowContainer); if (move && this.pokemon) { const spriteKey = Utils.getLocalizedSpriteKey("types"); const moveType = this.pokemon.getMoveType(move.getMove()); - const typeIcon = gScene.add.sprite(0, 0, spriteKey, Type[moveType].toLowerCase()); + const typeIcon = globalScene.add.sprite(0, 0, spriteKey, Type[moveType].toLowerCase()); typeIcon.setOrigin(0, 1); moveRowContainer.add(typeIcon); } @@ -1003,7 +1003,7 @@ export default class SummaryUiHandler extends UiHandler { moveText.setOrigin(0, 1); moveRowContainer.add(moveText); - const ppOverlay = gScene.add.image(163, -1, "summary_moves_overlay_pp"); + const ppOverlay = globalScene.add.image(163, -1, "summary_moves_overlay_pp"); ppOverlay.setOrigin(0, 1); moveRowContainer.add(ppOverlay); @@ -1022,7 +1022,7 @@ export default class SummaryUiHandler extends UiHandler { this.moveDescriptionText = addTextObject(2, 84, "", TextStyle.WINDOW_ALT, { wordWrap: { width: 1212 }}); this.movesContainer.add(this.moveDescriptionText); - const moveDescriptionTextMaskRect = gScene.make.graphics({}); + const moveDescriptionTextMaskRect = globalScene.make.graphics({}); moveDescriptionTextMaskRect.setScale(6); moveDescriptionTextMaskRect.fillStyle(0xFFFFFF); moveDescriptionTextMaskRect.beginPath(); @@ -1040,7 +1040,7 @@ export default class SummaryUiHandler extends UiHandler { return; } this.statusVisible = true; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.statusContainer, x: 0, duration: instant ? 0 : 250, @@ -1053,7 +1053,7 @@ export default class SummaryUiHandler extends UiHandler { return; } this.statusVisible = false; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.statusContainer, x: -106, duration: instant ? 0 : 250, @@ -1116,7 +1116,7 @@ export default class SummaryUiHandler extends UiHandler { return; } this.moveEffectsVisible = true; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.moveEffectContainer, x: 6, duration: instant ? 0 : 250, @@ -1129,7 +1129,7 @@ export default class SummaryUiHandler extends UiHandler { return; } this.moveEffectsVisible = false; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.moveEffectContainer, x: 106, duration: instant ? 0 : 250, diff --git a/src/ui/target-select-ui-handler.ts b/src/ui/target-select-ui-handler.ts index 55d3d13ae8a..84224ee01f8 100644 --- a/src/ui/target-select-ui-handler.ts +++ b/src/ui/target-select-ui-handler.ts @@ -8,7 +8,7 @@ import { Moves } from "#enums/moves"; import Pokemon from "#app/field/pokemon"; import { ModifierBar } from "#app/modifier/modifier"; import { SubstituteTag } from "#app/data/battler-tags"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export type TargetSelectCallback = (targets: BattlerIndex[]) => void; @@ -43,7 +43,7 @@ export default class TargetSelectUiHandler extends UiHandler { this.move = args[1] as Moves; this.targetSelectCallback = args[2] as TargetSelectCallback; - const moveTargets = getMoveTargets(gScene.getPlayerField()[this.fieldIndex], this.move); + const moveTargets = getMoveTargets(globalScene.getPlayerField()[this.fieldIndex], this.move); this.targets = moveTargets.targets; this.isMultipleTargets = moveTargets.multiple ?? false; @@ -51,7 +51,7 @@ export default class TargetSelectUiHandler extends UiHandler { return false; } - this.enemyModifiers = gScene.getModifierBar(true); + this.enemyModifiers = globalScene.getModifierBar(true); this.setCursor(this.targets.includes(this.cursor) ? this.cursor : this.targets[0]); @@ -102,8 +102,8 @@ export default class TargetSelectUiHandler extends UiHandler { } setCursor(cursor: integer): boolean { - const singleTarget = gScene.getField()[cursor]; - const multipleTargets = this.targets.map(index => gScene.getField()[index]); + const singleTarget = globalScene.getField()[cursor]; + const multipleTargets = this.targets.map(index => globalScene.getField()[index]); this.targetsHighlighted = this.isMultipleTargets ? multipleTargets : [ singleTarget ]; @@ -117,7 +117,7 @@ export default class TargetSelectUiHandler extends UiHandler { } } - this.targetFlashTween = gScene.tweens.add({ + this.targetFlashTween = globalScene.tweens.add({ targets: this.targetsHighlighted, key: { start: 1, to: 0.25 }, loop: -1, @@ -143,7 +143,7 @@ export default class TargetSelectUiHandler extends UiHandler { const targetsBattleInfo = this.targetsHighlighted.map(target => target.getBattleInfo()); targetsBattleInfo.map(info => { - this.targetBattleInfoMoveTween.push(gScene.tweens.add({ + this.targetBattleInfoMoveTween.push(globalScene.tweens.add({ targets: [ info ], y: { start: info.getBaseY(), to: info.getBaseY() + 1 }, loop: -1, diff --git a/src/ui/text.ts b/src/ui/text.ts index 789c978bb5b..a1f645e687d 100644 --- a/src/ui/text.ts +++ b/src/ui/text.ts @@ -3,7 +3,7 @@ import { UiTheme } from "#enums/ui-theme"; import Phaser from "phaser"; import BBCodeText from "phaser3-rex-plugins/plugins/gameobjects/tagtext/bbcodetext/BBCodeText"; import InputText from "phaser3-rex-plugins/plugins/inputtext"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { ModifierTier } from "../modifier/modifier-tier"; import i18next from "#app/plugins/i18n"; @@ -50,9 +50,9 @@ export interface TextStyleOptions { } export function addTextObject(x: number, y: number, content: string, style: TextStyle, extraStyleOptions?: Phaser.Types.GameObjects.Text.TextStyle): Phaser.GameObjects.Text { - const { scale, styleOptions, shadowColor, shadowXpos, shadowYpos } = getTextStyleOptions(style, gScene.uiTheme, extraStyleOptions); + const { scale, styleOptions, shadowColor, shadowXpos, shadowYpos } = getTextStyleOptions(style, globalScene.uiTheme, extraStyleOptions); - const ret = gScene.add.text(x, y, content, styleOptions); + const ret = globalScene.add.text(x, y, content, styleOptions); ret.setScale(scale); ret.setShadow(shadowXpos, shadowYpos, shadowColor); if (!(styleOptions as Phaser.Types.GameObjects.Text.TextStyle).lineSpacing) { @@ -67,7 +67,7 @@ export function addTextObject(x: number, y: number, content: string, style: Text } export function setTextStyle(obj: Phaser.GameObjects.Text, style: TextStyle, extraStyleOptions?: Phaser.Types.GameObjects.Text.TextStyle) { - const { scale, styleOptions, shadowColor, shadowXpos, shadowYpos } = getTextStyleOptions(style, gScene.uiTheme, extraStyleOptions); + const { scale, styleOptions, shadowColor, shadowXpos, shadowYpos } = getTextStyleOptions(style, globalScene.uiTheme, extraStyleOptions); obj.setScale(scale); obj.setShadow(shadowXpos, shadowYpos, shadowColor); if (!(styleOptions as Phaser.Types.GameObjects.Text.TextStyle).lineSpacing) { @@ -80,10 +80,10 @@ export function setTextStyle(obj: Phaser.GameObjects.Text, style: TextStyle, ext } export function addBBCodeTextObject(x: number, y: number, content: string, style: TextStyle, extraStyleOptions?: Phaser.Types.GameObjects.Text.TextStyle): BBCodeText { - const { scale, styleOptions, shadowColor, shadowXpos, shadowYpos } = getTextStyleOptions(style, gScene.uiTheme, extraStyleOptions); + const { scale, styleOptions, shadowColor, shadowXpos, shadowYpos } = getTextStyleOptions(style, globalScene.uiTheme, extraStyleOptions); - const ret = new BBCodeText(gScene, x, y, content, styleOptions as BBCodeText.TextStyle); - gScene.add.existing(ret); + const ret = new BBCodeText(globalScene, x, y, content, styleOptions as BBCodeText.TextStyle); + globalScene.add.existing(ret); ret.setScale(scale); ret.setShadow(shadowXpos, shadowYpos, shadowColor); if (!(styleOptions as BBCodeText.TextStyle).lineSpacing) { @@ -98,10 +98,10 @@ export function addBBCodeTextObject(x: number, y: number, content: string, style } export function addTextInputObject(x: number, y: number, width: number, height: number, style: TextStyle, extraStyleOptions?: InputText.IConfig): InputText { - const { scale, styleOptions } = getTextStyleOptions(style, gScene.uiTheme, extraStyleOptions); + const { scale, styleOptions } = getTextStyleOptions(style, globalScene.uiTheme, extraStyleOptions); - const ret = new InputText(gScene, x, y, width, height, styleOptions as InputText.IConfig); - gScene.add.existing(ret); + const ret = new InputText(globalScene, x, y, width, height, styleOptions as InputText.IConfig); + globalScene.add.existing(ret); ret.setScale(scale); return ret; diff --git a/src/ui/time-of-day-widget.ts b/src/ui/time-of-day-widget.ts index b316a2c3d99..9c81ff561fb 100644 --- a/src/ui/time-of-day-widget.ts +++ b/src/ui/time-of-day-widget.ts @@ -1,5 +1,5 @@ import * as Utils from "../utils"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { BattleSceneEventType } from "../events/battle-scene"; import { EaseType } from "#enums/ease-type"; import { TimeOfDay } from "#enums/time-of-day"; @@ -40,7 +40,7 @@ export default class TimeOfDayWidget extends Phaser.GameObjects.Container { public set parentVisible(visible: boolean) { if (visible && !this._parentVisible) { // Only resume the tweens if parent is newly visible this.timeOfDayIcons?.forEach( - icon => gScene.tweens.getTweensOf(icon).forEach( + icon => globalScene.tweens.getTweensOf(icon).forEach( tween => tween.resume())); } @@ -48,10 +48,10 @@ export default class TimeOfDayWidget extends Phaser.GameObjects.Container { } constructor(x: number = 0, y: number = 0) { - super(gScene, x, y); + super(globalScene, x, y); - this.setVisible(gScene.showTimeOfDayWidget); - if (!gScene.showTimeOfDayWidget) { + this.setVisible(globalScene.showTimeOfDayWidget); + if (!globalScene.showTimeOfDayWidget) { return; } @@ -59,14 +59,14 @@ export default class TimeOfDayWidget extends Phaser.GameObjects.Container { this.timeOfDayIconPairs.forEach( (icons, key) => { for (let i = 0; i < icons.length; i++) { - icons[i] = gScene.add.sprite(0, 0, "dawn_icon_" + key).setOrigin(); + icons[i] = globalScene.add.sprite(0, 0, "dawn_icon_" + key).setOrigin(); } }); // Store a flat array of all icons for later this.timeOfDayIcons = [ this.timeOfDayIconBgs, this.timeOfDayIconMgs, this.timeOfDayIconFgs ].flat(); this.add(this.timeOfDayIcons); - gScene.eventTarget.addEventListener(BattleSceneEventType.ENCOUNTER_PHASE, this.onEncounterPhaseEvent); + globalScene.eventTarget.addEventListener(BattleSceneEventType.ENCOUNTER_PHASE, this.onEncounterPhaseEvent); } /** @@ -133,13 +133,13 @@ export default class TimeOfDayWidget extends Phaser.GameObjects.Container { /** Adds the proper tween for all icons */ private tweenTimeOfDayIcon() { - gScene.tweens.killTweensOf(this.timeOfDayIcons); + globalScene.tweens.killTweensOf(this.timeOfDayIcons); this.resetIcons(); // Tween based on the player setting - (gScene.timeOfDayAnimation === EaseType.BACK ? this.getBackTween() : this.getBounceTween()) - .forEach(tween => gScene.tweens.add(tween)); + (globalScene.timeOfDayAnimation === EaseType.BACK ? this.getBackTween() : this.getBounceTween()) + .forEach(tween => globalScene.tweens.add(tween)); // Swaps all elements of the icon arrays by shifting the first element onto the end of the array // This ensures index[0] is always the new time of day icon and index[1] is always the current one @@ -155,7 +155,7 @@ export default class TimeOfDayWidget extends Phaser.GameObjects.Container { * @param event {@linkcode Event} being sent */ private onEncounterPhase(event: Event) { - const newTime = gScene.arena.getTimeOfDay(); + const newTime = globalScene.arena.getTimeOfDay(); if (this.currentTime === newTime) { return; diff --git a/src/ui/title-ui-handler.ts b/src/ui/title-ui-handler.ts index 85ed1f6df90..e02c45cd853 100644 --- a/src/ui/title-ui-handler.ts +++ b/src/ui/title-ui-handler.ts @@ -6,7 +6,7 @@ import { getSplashMessages } from "../data/splash-messages"; import i18next from "i18next"; import { TimedEventDisplay } from "#app/timed-event-manager"; import { version } from "../../package.json"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class TitleUiHandler extends OptionSelectUiHandler { /** If the stats can not be retrieved, use this fallback value */ @@ -30,24 +30,24 @@ export default class TitleUiHandler extends OptionSelectUiHandler { const ui = this.getUi(); - this.titleContainer = gScene.add.container(0, -(gScene.game.canvas.height / 6)); + this.titleContainer = globalScene.add.container(0, -(globalScene.game.canvas.height / 6)); this.titleContainer.setName("title"); this.titleContainer.setAlpha(0); ui.add(this.titleContainer); - const logo = gScene.add.image((gScene.game.canvas.width / 6) / 2, 8, "logo"); + const logo = globalScene.add.image((globalScene.game.canvas.width / 6) / 2, 8, "logo"); logo.setOrigin(0.5, 0); this.titleContainer.add(logo); - if (gScene.eventManager.isEventActive()) { - this.eventDisplay = new TimedEventDisplay(0, 0, gScene.eventManager.activeEvent()); + if (globalScene.eventManager.isEventActive()) { + this.eventDisplay = new TimedEventDisplay(0, 0, globalScene.eventManager.activeEvent()); this.eventDisplay.setup(); this.titleContainer.add(this.eventDisplay); } this.playerCountLabel = addTextObject( - (gScene.game.canvas.width / 6) - 2, - (gScene.game.canvas.height / 6) - 13 - 576 * getTextStyleOptions(TextStyle.WINDOW, gScene.uiTheme).scale, + (globalScene.game.canvas.width / 6) - 2, + (globalScene.game.canvas.height / 6) - 13 - 576 * getTextStyleOptions(TextStyle.WINDOW, globalScene.uiTheme).scale, `? ${i18next.t("menu:playersOnline")}`, TextStyle.MESSAGE, { fontSize: "54px" } @@ -62,7 +62,7 @@ export default class TitleUiHandler extends OptionSelectUiHandler { const originalSplashMessageScale = this.splashMessageText.scale; - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.splashMessageText, duration: Utils.fixedInt(350), scale: originalSplashMessageScale * 1.25, @@ -101,8 +101,8 @@ export default class TitleUiHandler extends OptionSelectUiHandler { const ui = this.getUi(); - if (gScene.eventManager.isEventActive()) { - this.eventDisplay.setWidth(gScene.scaledCanvas.width - this.optionSelectBg.width - this.optionSelectBg.x); + if (globalScene.eventManager.isEventActive()) { + this.eventDisplay.setWidth(globalScene.scaledCanvas.width - this.optionSelectBg.width - this.optionSelectBg.x); this.eventDisplay.show(); } @@ -112,7 +112,7 @@ export default class TitleUiHandler extends OptionSelectUiHandler { this.updateTitleStats(); }, 60000); - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.titleContainer, ui.getMessageHandler().bg ], duration: Utils.fixedInt(325), alpha: (target: any) => target === this.titleContainer ? 1 : 0, @@ -133,7 +133,7 @@ export default class TitleUiHandler extends OptionSelectUiHandler { this.titleStatsTimer && clearInterval(this.titleStatsTimer); this.titleStatsTimer = null; - gScene.tweens.add({ + globalScene.tweens.add({ targets: [ this.titleContainer, ui.getMessageHandler().bg ], duration: Utils.fixedInt(325), alpha: (target: any) => target === this.titleContainer ? 0 : 1, diff --git a/src/ui/ui-handler.ts b/src/ui/ui-handler.ts index 14d3c7f7f30..c63290927e2 100644 --- a/src/ui/ui-handler.ts +++ b/src/ui/ui-handler.ts @@ -1,4 +1,4 @@ -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; import { TextStyle, getTextColor } from "./text"; import { Mode } from "./ui"; import { Button } from "#enums/buttons"; @@ -30,11 +30,11 @@ export default abstract class UiHandler { abstract processInput(button: Button): boolean; getUi() { - return gScene.ui; + return globalScene.ui; } getTextColor(style: TextStyle, shadow: boolean = false): string { - return getTextColor(style, shadow, gScene.uiTheme); + return getTextColor(style, shadow, globalScene.uiTheme); } getCursor(): integer { @@ -56,7 +56,7 @@ export default abstract class UiHandler { * @param cursorStyle cursor style to apply */ protected setMouseCursorStyle(cursorStyle: "pointer" | "default") { - gScene.input.manager.canvas.style.cursor = cursorStyle; + globalScene.input.manager.canvas.style.cursor = cursorStyle; } clear() { diff --git a/src/ui/ui-theme.ts b/src/ui/ui-theme.ts index a10f033b812..64bb3eb90bf 100644 --- a/src/ui/ui-theme.ts +++ b/src/ui/ui-theme.ts @@ -1,6 +1,6 @@ import { UiTheme } from "#enums/ui-theme"; import { legacyCompatibleImages } from "#app/scene-base"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export enum WindowVariant { NORMAL, @@ -41,9 +41,9 @@ export function addWindow(x: number, y: number, width: number, height: number, m windowVariant = WindowVariant.NORMAL; } - const borderSize = gScene.uiTheme ? 6 : 8; + const borderSize = globalScene.uiTheme ? 6 : 8; - const window = gScene.add.nineslice(x, y, `window_${gScene.windowType}${getWindowVariantSuffix(windowVariant)}`, undefined, width, height, borderSize, borderSize, borderSize, borderSize); + const window = globalScene.add.nineslice(x, y, `window_${globalScene.windowType}${getWindowVariantSuffix(windowVariant)}`, undefined, width, height, borderSize, borderSize, borderSize, borderSize); window.setOrigin(0, 0); if (mergeMaskLeft || mergeMaskTop || maskOffsetX || maskOffsetY) { @@ -54,7 +54,7 @@ export function addWindow(x: number, y: number, width: number, height: number, m * height: bottom */ const maskRect = new Phaser.GameObjects.Rectangle( - gScene, + globalScene, 6 * (x - (mergeMaskLeft ? 2 : 0) - (maskOffsetX || 0)), 6 * (y + (mergeMaskTop ? 2 : 0) + (maskOffsetY || 0)), width - (mergeMaskLeft ? 2 : 0), @@ -96,12 +96,12 @@ export function updateWindowType(windowTypeIndex: integer): void { } }; - traverse(gScene); + traverse(globalScene); - gScene.windowType = windowTypeIndex; + globalScene.windowType = windowTypeIndex; const rootStyle = document.documentElement.style; - [ "base", "light", "dark" ].map((k, i) => rootStyle.setProperty(`--color-${k}`, windowTypeControlColors[gScene.uiTheme][windowTypeIndex - 1][i])); + [ "base", "light", "dark" ].map((k, i) => rootStyle.setProperty(`--color-${k}`, windowTypeControlColors[globalScene.uiTheme][windowTypeIndex - 1][i])); const windowKey = `window_${windowTypeIndex}`; @@ -115,10 +115,10 @@ export function updateWindowType(windowTypeIndex: integer): void { } export function addUiThemeOverrides(): void { - const originalAddImage = gScene.add.image; - gScene.add.image = function (x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number): Phaser.GameObjects.Image { + const originalAddImage = globalScene.add.image; + globalScene.add.image = function (x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number): Phaser.GameObjects.Image { let legacy = false; - if (typeof texture === "string" && gScene.uiTheme && legacyCompatibleImages.includes(texture)) { + if (typeof texture === "string" && globalScene.uiTheme && legacyCompatibleImages.includes(texture)) { legacy = true; texture += "_legacy"; } @@ -133,10 +133,10 @@ export function addUiThemeOverrides(): void { return ret; }; - const originalAddSprite = gScene.add.sprite; - gScene.add.sprite = function (x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number): Phaser.GameObjects.Sprite { + const originalAddSprite = globalScene.add.sprite; + globalScene.add.sprite = function (x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number): Phaser.GameObjects.Sprite { let legacy = false; - if (typeof texture === "string" && gScene.uiTheme && legacyCompatibleImages.includes(texture)) { + if (typeof texture === "string" && globalScene.uiTheme && legacyCompatibleImages.includes(texture)) { legacy = true; texture += "_legacy"; } @@ -151,10 +151,10 @@ export function addUiThemeOverrides(): void { return ret; }; - const originalAddNineslice = gScene.add.nineslice; - gScene.add.nineslice = function (x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number, width?: number, height?: number, leftWidth?: number, rightWidth?: number, topHeight?: number, bottomHeight?: number): Phaser.GameObjects.NineSlice { + const originalAddNineslice = globalScene.add.nineslice; + globalScene.add.nineslice = function (x: number, y: number, texture: string | Phaser.Textures.Texture, frame?: string | number, width?: number, height?: number, leftWidth?: number, rightWidth?: number, topHeight?: number, bottomHeight?: number): Phaser.GameObjects.NineSlice { let legacy = false; - if (typeof texture === "string" && gScene.uiTheme && legacyCompatibleImages.includes(texture)) { + if (typeof texture === "string" && globalScene.uiTheme && legacyCompatibleImages.includes(texture)) { legacy = true; texture += "_legacy"; } diff --git a/src/ui/ui.ts b/src/ui/ui.ts index 371cdeff411..7f645b2faa1 100644 --- a/src/ui/ui.ts +++ b/src/ui/ui.ts @@ -1,4 +1,4 @@ -import { default as BattleScene, gScene } from "#app/battle-scene"; +import { default as BattleScene, globalScene } from "#app/battle-scene"; import UiHandler from "./ui-handler"; import BattleMessageUiHandler from "./battle-message-ui-handler"; import CommandUiHandler from "./command-ui-handler"; @@ -157,7 +157,7 @@ export default class UI extends Phaser.GameObjects.Container { private overlayActive: boolean; constructor() { - super(gScene, 0, gScene.game.canvas.height / 6); + super(globalScene, 0, globalScene.game.canvas.height / 6); this.mode = Mode.MESSAGE; this.modeChain = []; @@ -213,26 +213,26 @@ export default class UI extends Phaser.GameObjects.Container { for (const handler of this.handlers) { handler.setup(); } - this.overlay = gScene.add.rectangle(0, 0, gScene.game.canvas.width / 6, gScene.game.canvas.height / 6, 0); + this.overlay = globalScene.add.rectangle(0, 0, globalScene.game.canvas.width / 6, globalScene.game.canvas.height / 6, 0); this.overlay.setName("rect-ui-overlay"); this.overlay.setOrigin(0, 0); - gScene.uiContainer.add(this.overlay); + globalScene.uiContainer.add(this.overlay); this.overlay.setVisible(false); this.setupTooltip(); this.achvBar = new AchvBar; this.achvBar.setup(); - gScene.uiContainer.add(this.achvBar); + globalScene.uiContainer.add(this.achvBar); this.savingIcon = new SavingIconHandler; this.savingIcon.setup(); - gScene.uiContainer.add(this.savingIcon); + globalScene.uiContainer.add(this.savingIcon); } private setupTooltip() { - this.tooltipContainer = gScene.add.container(0, 0); + this.tooltipContainer = globalScene.add.container(0, 0); this.tooltipContainer.setName("tooltip"); this.tooltipContainer.setVisible(false); @@ -252,7 +252,7 @@ export default class UI extends Phaser.GameObjects.Container { this.tooltipContainer.add(this.tooltipTitle); this.tooltipContainer.add(this.tooltipContent); - gScene.uiContainer.add(this.tooltipContainer); + globalScene.uiContainer.add(this.tooltipContainer); } getHandler(): H { @@ -268,7 +268,7 @@ export default class UI extends Phaser.GameObjects.Container { return false; } - const battleScene = gScene as BattleScene; + const battleScene = globalScene as BattleScene; if ([ Mode.CONFIRM, Mode.COMMAND, Mode.FIGHT, Mode.MESSAGE ].includes(this.mode)) { battleScene?.processInfoButton(pressed); return true; @@ -318,7 +318,7 @@ export default class UI extends Phaser.GameObjects.Container { } showDialogue(keyOrText: string, name: string | undefined, delay: integer | null = 0, callback: Function, callbackDelay?: integer, promptDelay?: integer): void { - const battleScene = gScene as BattleScene; + const battleScene = globalScene as BattleScene; // Get localized dialogue (if available) let hasi18n = false; let text = keyOrText; @@ -360,7 +360,7 @@ export default class UI extends Phaser.GameObjects.Container { } shouldSkipDialogue(i18nKey: string): boolean { - const battleScene = gScene as BattleScene; + const battleScene = globalScene as BattleScene; if (i18next.exists(i18nKey) ) { if (battleScene.skipSeenDialogues && battleScene.gameData.getSeenDialogues()[i18nKey] === true) { @@ -378,9 +378,9 @@ export default class UI extends Phaser.GameObjects.Container { this.tooltipContainer.setVisible(true); this.editTooltip(title, content); if (overlap) { - gScene.uiContainer.moveAbove(this.tooltipContainer, this); + globalScene.uiContainer.moveAbove(this.tooltipContainer, this); } else { - gScene.uiContainer.moveBelow(this.tooltipContainer, this); + globalScene.uiContainer.moveBelow(this.tooltipContainer, this); } } @@ -400,11 +400,11 @@ export default class UI extends Phaser.GameObjects.Container { update(): void { if (this.tooltipContainer.visible) { - const xReverse = gScene.game.input.mousePointer && gScene.game.input.mousePointer.x >= gScene.game.canvas.width - this.tooltipBg.width * 6 - 12; - const yReverse = gScene.game.input.mousePointer && gScene.game.input.mousePointer.y >= gScene.game.canvas.height - this.tooltipBg.height * 6 - 12; + const xReverse = globalScene.game.input.mousePointer && globalScene.game.input.mousePointer.x >= globalScene.game.canvas.width - this.tooltipBg.width * 6 - 12; + const yReverse = globalScene.game.input.mousePointer && globalScene.game.input.mousePointer.y >= globalScene.game.canvas.height - this.tooltipBg.height * 6 - 12; this.tooltipContainer.setPosition( - !xReverse ? gScene.game.input.mousePointer!.x / 6 + 2 : gScene.game.input.mousePointer!.x / 6 - this.tooltipBg.width - 2, - !yReverse ? gScene.game.input.mousePointer!.y / 6 + 2 : gScene.game.input.mousePointer!.y / 6 - this.tooltipBg.height - 2, + !xReverse ? globalScene.game.input.mousePointer!.x / 6 + 2 : globalScene.game.input.mousePointer!.x / 6 - this.tooltipBg.width - 2, + !yReverse ? globalScene.game.input.mousePointer!.y / 6 + 2 : globalScene.game.input.mousePointer!.y / 6 - this.tooltipBg.height - 2, ); } } @@ -428,11 +428,11 @@ export default class UI extends Phaser.GameObjects.Container { } playSelect(): void { - gScene.playSound("ui/select"); + globalScene.playSound("ui/select"); } playError(): void { - gScene.playSound("ui/error"); + globalScene.playSound("ui/error"); } fadeOut(duration: integer): Promise { @@ -443,7 +443,7 @@ export default class UI extends Phaser.GameObjects.Container { this.overlayActive = true; this.overlay.setAlpha(0); this.overlay.setVisible(true); - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.overlay, alpha: 1, duration: duration, @@ -458,7 +458,7 @@ export default class UI extends Phaser.GameObjects.Container { if (!this.overlayActive) { return resolve(); } - gScene.tweens.add({ + globalScene.tweens.add({ targets: this.overlay, alpha: 0, duration: duration, @@ -485,7 +485,7 @@ export default class UI extends Phaser.GameObjects.Container { } if (chainMode && this.mode && !clear) { this.modeChain.push(this.mode); - gScene.updateGameInfo(); + globalScene.updateGameInfo(); } this.mode = mode; const touchControls = document?.getElementById("touchControls"); @@ -500,7 +500,7 @@ export default class UI extends Phaser.GameObjects.Container { && (noTransitionModes.indexOf(this.mode) === -1 && noTransitionModes.indexOf(mode) === -1))) || (chainMode && noTransitionModes.indexOf(mode) === -1))) { this.fadeOut(250).then(() => { - gScene.time.delayedCall(100, () => { + globalScene.time.delayedCall(100, () => { doSetMode(); this.fadeIn(250); }); @@ -533,7 +533,7 @@ export default class UI extends Phaser.GameObjects.Container { resetModeChain(): void { this.modeChain = []; - gScene.updateGameInfo(); + globalScene.updateGameInfo(); } revertMode(): Promise { @@ -547,7 +547,7 @@ export default class UI extends Phaser.GameObjects.Container { const doRevertMode = () => { this.getHandler().clear(); this.mode = this.modeChain.pop()!; // TODO: is this bang correct? - gScene.updateGameInfo(); + globalScene.updateGameInfo(); const touchControls = document.getElementById("touchControls"); if (touchControls) { touchControls.dataset.uiMode = Mode[this.mode]; @@ -557,7 +557,7 @@ export default class UI extends Phaser.GameObjects.Container { if (noTransitionModes.indexOf(lastMode) === -1) { this.fadeOut(250).then(() => { - gScene.time.delayedCall(100, () => { + globalScene.time.delayedCall(100, () => { doRevertMode(); this.fadeIn(250); }); @@ -589,10 +589,10 @@ export default class UI extends Phaser.GameObjects.Container { * @returns gamepad type */ public getGamepadType(): string { - if (gScene.inputMethod === "gamepad") { - return gScene.inputController.getConfig(gScene.inputController.selectedDevice[Device.GAMEPAD]).padType; + if (globalScene.inputMethod === "gamepad") { + return globalScene.inputController.getConfig(globalScene.inputController.selectedDevice[Device.GAMEPAD]).padType; } else { - return gScene.inputMethod; + return globalScene.inputMethod; } } } diff --git a/src/ui/unavailable-modal-ui-handler.ts b/src/ui/unavailable-modal-ui-handler.ts index 4e6bba20f7a..fd084424bf2 100644 --- a/src/ui/unavailable-modal-ui-handler.ts +++ b/src/ui/unavailable-modal-ui-handler.ts @@ -4,7 +4,7 @@ import { Mode } from "./ui"; import { updateUserInfo } from "#app/account"; import * as Utils from "#app/utils"; import i18next from "i18next"; -import { gScene } from "#app/battle-scene"; +import { globalScene } from "#app/battle-scene"; export default class UnavailableModalUiHandler extends ModalUiHandler { private reconnectTimer: NodeJS.Timeout | null; @@ -55,11 +55,11 @@ export default class UnavailableModalUiHandler extends ModalUiHandler { if (response[0] || [ 200, 400 ].includes(response[1])) { this.reconnectTimer = null; this.reconnectDuration = this.minTime; - gScene.playSound("se/pb_bounce_1"); + globalScene.playSound("se/pb_bounce_1"); this.reconnectCallback(); } else if (response[1] === 401) { Utils.removeCookie(Utils.sessionIdKey); - gScene.reset(true, true); + globalScene.reset(true, true); } else { this.reconnectDuration = Math.min(this.reconnectDuration * 2, this.maxTime); // Set a max delay so it isn't infinite this.reconnectTimer =