diff --git a/src/@types/arena-tags.ts b/src/@types/arena-tags.ts index ab4339b2fef..afcc8a0f924 100644 --- a/src/@types/arena-tags.ts +++ b/src/@types/arena-tags.ts @@ -1,6 +1,5 @@ import type { ArenaTagTypeMap } from "#data/arena-tag"; import type { ArenaTagType } from "#enums/arena-tag-type"; -import type { NonFunctionProperties } from "./type-helpers"; /** Subset of {@linkcode ArenaTagType}s that apply some negative effect to pokemon that switch in ({@link https://bulbapedia.bulbagarden.net/wiki/List_of_moves_that_cause_entry_hazards#List_of_traps | entry hazards} and Imprison. */ export type ArenaTrapTagType = @@ -10,9 +9,6 @@ export type ArenaTrapTagType = | ArenaTagType.STEALTH_ROCK | ArenaTagType.IMPRISON; -/** Subset of {@linkcode ArenaTagType}s that are considered delayed attacks */ -export type ArenaDelayedAttackTagType = ArenaTagType.FUTURE_SIGHT | ArenaTagType.DOOM_DESIRE; - /** Subset of {@linkcode ArenaTagType}s that create {@link https://bulbapedia.bulbagarden.net/wiki/Category:Screen-creating_moves | screens}. */ export type ArenaScreenTagType = ArenaTagType.REFLECT | ArenaTagType.LIGHT_SCREEN | ArenaTagType.AURORA_VEIL; @@ -30,13 +26,13 @@ export type NonSerializableArenaTagType = ArenaTagType.NONE | TurnProtectArenaTa export type SerializableArenaTagType = Exclude; /** - * Type-safe representation of the serializable data of an ArenaTag + * Type-safe representation of an arbitrary, serialized Arena Tag */ -export type ArenaTagTypeData = NonFunctionProperties< +export type ArenaTagTypeData = Parameters< ArenaTagTypeMap[keyof { [K in keyof ArenaTagTypeMap as K extends SerializableArenaTagType ? K : never]: ArenaTagTypeMap[K]; - }] ->; + }]["loadTag"] +>[0]; /** Dummy, typescript-only declaration to ensure that * {@linkcode ArenaTagTypeMap} has a map for all ArenaTagTypes. diff --git a/src/@types/battler-tags.ts b/src/@types/battler-tags.ts new file mode 100644 index 00000000000..0057280e4e5 --- /dev/null +++ b/src/@types/battler-tags.ts @@ -0,0 +1,128 @@ +// biome-ignore-start lint/correctness/noUnusedImports: Used in a TSDoc comment +import type { AbilityBattlerTag, BattlerTagTypeMap, SerializableBattlerTag, TypeBoostTag } from "#data/battler-tags"; +import type { AbilityId } from "#enums/ability-id"; +// biome-ignore-end lint/correctness/noUnusedImports: end +import type { BattlerTagType } from "#enums/battler-tag-type"; + +/** + * Subset of {@linkcode BattlerTagType}s that restrict the use of moves. + */ +export type MoveRestrictionBattlerTagType = + | BattlerTagType.THROAT_CHOPPED + | BattlerTagType.TORMENT + | BattlerTagType.TAUNT + | BattlerTagType.IMPRISON + | BattlerTagType.HEAL_BLOCK + | BattlerTagType.ENCORE + | BattlerTagType.DISABLED + | BattlerTagType.GORILLA_TACTICS; + +/** + * Subset of {@linkcode BattlerTagType}s that block damage from moves. + */ +export type FormBlockDamageBattlerTagType = BattlerTagType.ICE_FACE | BattlerTagType.DISGUISE; + +/** + * Subset of {@linkcode BattlerTagType}s that are related to trapping effects. + */ +export type TrappingBattlerTagType = + | BattlerTagType.BIND + | BattlerTagType.WRAP + | BattlerTagType.FIRE_SPIN + | BattlerTagType.WHIRLPOOL + | BattlerTagType.CLAMP + | BattlerTagType.SAND_TOMB + | BattlerTagType.MAGMA_STORM + | BattlerTagType.SNAP_TRAP + | BattlerTagType.THUNDER_CAGE + | BattlerTagType.INFESTATION + | BattlerTagType.INGRAIN + | BattlerTagType.OCTOLOCK + | BattlerTagType.NO_RETREAT; + +/** + * Subset of {@linkcode BattlerTagType}s that are related to protection effects. + */ +export type ProtectionBattlerTagType = BattlerTagType.PROTECTED | BattlerTagType.SPIKY_SHIELD | DamageProtectedTagType; +/** + * Subset of {@linkcode BattlerTagType}s related to protection effects that block damage but not status moves. + */ +export type DamageProtectedTagType = ContactSetStatusProtectedTagType | ContactStatStageChangeProtectedTagType; + +/** + * Subset of {@linkcode BattlerTagType}s related to protection effects that set a status effect on the attacker. + */ +export type ContactSetStatusProtectedTagType = BattlerTagType.BANEFUL_BUNKER | BattlerTagType.BURNING_BULWARK; + +/** + * Subset of {@linkcode BattlerTagType}s related to protection effects that change stat stages of the attacker. + */ +export type ContactStatStageChangeProtectedTagType = + | BattlerTagType.KINGS_SHIELD + | BattlerTagType.SILK_TRAP + | BattlerTagType.OBSTRUCT; + +/** Subset of {@linkcode BattlerTagType}s that provide the Endure effect */ +export type EndureTagType = BattlerTagType.ENDURE_TOKEN | BattlerTagType.ENDURING; + +/** + * Subset of {@linkcode BattlerTagType}s that are related to semi-invulnerable states. + */ +export type SemiInvulnerableTagType = + | BattlerTagType.FLYING + | BattlerTagType.UNDERGROUND + | BattlerTagType.UNDERWATER + | BattlerTagType.HIDDEN; + +/** + * Subset of {@linkcode BattlerTagType}s corresponding to {@linkcode AbilityBattlerTag}s + * + * @remarks + * ⚠️ {@linkcode AbilityId.FLASH_FIRE | Flash Fire}'s {@linkcode BattlerTagType.FIRE_BOOST} is not included as it + * subclasses {@linkcode TypeBoostTag} and not `AbilityBattlerTag`. + */ +export type AbilityBattlerTagType = + | BattlerTagType.PROTOSYNTHESIS + | BattlerTagType.QUARK_DRIVE + | BattlerTagType.UNBURDEN + | BattlerTagType.SLOW_START + | BattlerTagType.TRUANT; + +/** + * Subset of {@linkcode BattlerTagType}s related to abilities that boost the highest stat. + */ +export type HighestStatBoostTagType = + | BattlerTagType.QUARK_DRIVE // formatting + | BattlerTagType.PROTOSYNTHESIS; +/** + * Subset of {@linkcode BattlerTagType}s that are able to persist between turns and should therefore be serialized + */ +export type SerializableBattlerTagType = keyof { + [K in keyof BattlerTagTypeMap as BattlerTagTypeMap[K] extends SerializableBattlerTag + ? K + : never]: BattlerTagTypeMap[K]; +}; + +/** + * Subset of {@linkcode BattlerTagType}s that are not able to persist across waves and should therefore not be serialized + */ +export type NonSerializableBattlerTagType = Exclude; + +/** + * Type-safe representation of an arbitrary, serialized Battler Tag + */ +export type BattlerTagTypeData = Parameters< + BattlerTagTypeMap[keyof { + [K in keyof BattlerTagTypeMap as K extends SerializableBattlerTagType ? K : never]: BattlerTagTypeMap[K]; + }]["loadTag"] +>[0]; + +/** + * Dummy, typescript-only declaration to ensure that + * {@linkcode BattlerTagTypeMap} has an entry for all `BattlerTagType`s. + * + * If a battler tag is missing from the map, Typescript will throw an error on this statement. + * + * ⚠️ Does not actually exist at runtime, so it must not be used! + */ +declare const EnsureAllBattlerTagTypesAreMapped: BattlerTagTypeMap[BattlerTagType] & never; diff --git a/src/@types/enum-types.ts b/src/@types/helpers/enum-types.ts similarity index 68% rename from src/@types/enum-types.ts rename to src/@types/helpers/enum-types.ts index 84df0a96505..2461f900c6b 100644 --- a/src/@types/enum-types.ts +++ b/src/@types/helpers/enum-types.ts @@ -1,18 +1,14 @@ +import type { ObjectValues } from "#types/type-helpers"; + /** Union type accepting any TS Enum or `const object`, with or without reverse mapping. */ export type EnumOrObject = Record; -/** - * Utility type to extract the enum values from a `const object`, - * or convert an `enum` interface produced by `typeof Enum` into the union type representing its values. - */ -export type EnumValues = E[keyof E]; - /** * Generic type constraint representing a TS numeric enum with reverse mappings. * @example * TSNumericEnum */ -export type TSNumericEnum = number extends EnumValues ? T : never; +export type TSNumericEnum = number extends ObjectValues ? T : never; /** Generic type constraint representing a non reverse-mapped TS enum or `const object`. */ export type NormalEnum = Exclude>; diff --git a/src/@types/type-helpers.ts b/src/@types/helpers/type-helpers.ts similarity index 81% rename from src/@types/type-helpers.ts rename to src/@types/helpers/type-helpers.ts index b3e5b1cfc07..37f97fcf08c 100644 --- a/src/@types/type-helpers.ts +++ b/src/@types/helpers/type-helpers.ts @@ -6,8 +6,6 @@ import type { AbAttr } from "#abilities/ability"; // biome-ignore-end lint/correctness/noUnusedImports: Used in a tsdoc comment -import type { EnumValues } from "#types/enum-types"; - /** * Exactly matches the type of the argument, preventing adding additional properties. * @@ -37,16 +35,25 @@ export type Mutable = { }; /** - * Type helper to obtain the keys associated with a given value inside a `const object`. + * Type helper to obtain the keys associated with a given value inside an object. * @typeParam O - The type of the object * @typeParam V - The type of one of O's values */ -export type InferKeys, V extends EnumValues> = { +export type InferKeys> = { [K in keyof O]: O[K] extends V ? K : never; }[keyof O]; /** - * Type helper that matches any `Function` type. Equivalent to `Function`, but will not raise a warning from Biome. + * Utility type to obtain the values of a given object. \ + * Functions similar to `keyof E`, except producing the values instead of the keys. + * @remarks + * This can be used to convert an `enum` interface produced by `typeof Enum` into the union type representing its members. + */ +export type ObjectValues = E[keyof E]; + +/** + * Type helper that matches any `Function` type. + * Equivalent to `Function`, but will not raise a warning from Biome. */ export type AnyFn = (...args: any[]) => any; @@ -65,6 +72,7 @@ export type NonFunctionProperties = { /** * Type helper to extract out non-function properties from a type, recursively applying to nested properties. + * This can be used to mimic the effects of JSON serialization and de-serialization on a given type. */ export type NonFunctionPropertiesRecursive = { [K in keyof Class as Class[K] extends AnyFn ? never : K]: Class[K] extends Array diff --git a/src/@types/modifier-types.ts b/src/@types/modifier-types.ts index 28b39d1a151..13a84a984e2 100644 --- a/src/@types/modifier-types.ts +++ b/src/@types/modifier-types.ts @@ -3,6 +3,7 @@ import type { Pokemon } from "#field/pokemon"; import type { ModifierConstructorMap } from "#modifiers/modifier"; import type { ModifierType, WeightedModifierType } from "#modifiers/modifier-type"; +import type { ObjectValues } from "#types/type-helpers"; export type ModifierTypeFunc = () => ModifierType; export type WeightedModifierTypeWeightFunc = (party: Pokemon[], rerollCount?: number) => number; @@ -19,7 +20,7 @@ export type ModifierInstanceMap = { /** * Union type of all modifier constructors. */ -export type ModifierClass = ModifierConstructorMap[keyof ModifierConstructorMap]; +export type ModifierClass = ObjectValues; /** * Union type of all modifier names as strings. diff --git a/src/@types/phase-types.ts b/src/@types/phase-types.ts index 1d68c7921dd..91673053747 100644 --- a/src/@types/phase-types.ts +++ b/src/@types/phase-types.ts @@ -1,4 +1,5 @@ import type { PhaseConstructorMap } from "#app/phase-manager"; +import type { ObjectValues } from "#types/type-helpers"; // Intentionally export the types of everything in phase-manager, as this file is meant to be // the centralized place for type definitions for the phase system. @@ -17,7 +18,7 @@ export type PhaseMap = { /** * Union type of all phase constructors. */ -export type PhaseClass = PhaseConstructorMap[keyof PhaseConstructorMap]; +export type PhaseClass = ObjectValues; /** * Union type of all phase names as strings. diff --git a/src/battle-scene.ts b/src/battle-scene.ts index 275f129a63a..9af954c3852 100644 --- a/src/battle-scene.ts +++ b/src/battle-scene.ts @@ -657,9 +657,7 @@ export class BattleScene extends SceneBase { ).then(() => loadMoveAnimAssets(defaultMoves, true)), this.initStarterColors(), ]).then(() => { - this.phaseManager.pushNew("LoginPhase"); - this.phaseManager.pushNew("TitlePhase"); - + this.phaseManager.toTitleScreen(true); this.phaseManager.shiftPhase(); }); } @@ -1269,13 +1267,12 @@ export class BattleScene extends SceneBase { duration: 250, ease: "Sine.easeInOut", onComplete: () => { - this.phaseManager.clearPhaseQueue(); - this.ui.freeUIData(); this.uiContainer.remove(this.ui, true); this.uiContainer.destroy(); this.children.removeAll(true); this.game.domContainer.innerHTML = ""; + // TODO: `launchBattle` calls `reset(false, false, true)` this.launchBattle(); }, }); diff --git a/src/data/arena-tag.ts b/src/data/arena-tag.ts index 2c4c8a04282..9f2a5e09667 100644 --- a/src/data/arena-tag.ts +++ b/src/data/arena-tag.ts @@ -1,3 +1,7 @@ +/** biome-ignore-start lint/correctness/noUnusedImports: TSDoc imports */ +import type { BattlerTag } from "#app/data/battler-tags"; +/** biome-ignore-end lint/correctness/noUnusedImports: TSDoc imports */ + import { applyAbAttrs, applyOnGainAbAttrs, applyOnLoseAbAttrs } from "#abilities/apply-ab-attrs"; import { globalScene } from "#app/global-scene"; import { getPokemonNameWithAffix } from "#app/messages"; @@ -6,58 +10,75 @@ import { allMoves } from "#data/data-lists"; import { AbilityId } from "#enums/ability-id"; import { ArenaTagSide } from "#enums/arena-tag-side"; import { ArenaTagType } from "#enums/arena-tag-type"; -import type { BattlerIndex } from "#enums/battler-index"; import { BattlerTagType } from "#enums/battler-tag-type"; import { HitResult } from "#enums/hit-result"; import { CommonAnim } from "#enums/move-anims-common"; import { MoveCategory } from "#enums/move-category"; import { MoveId } from "#enums/move-id"; import { MoveTarget } from "#enums/move-target"; -import { MoveUseMode } from "#enums/move-use-mode"; import { PokemonType } from "#enums/pokemon-type"; import { Stat } from "#enums/stat"; import { StatusEffect } from "#enums/status-effect"; import type { Arena } from "#field/arena"; import type { Pokemon } from "#field/pokemon"; import type { - ArenaDelayedAttackTagType, ArenaScreenTagType, ArenaTagTypeData, ArenaTrapTagType, SerializableArenaTagType, } from "#types/arena-tags"; -import type { Mutable, NonFunctionProperties } from "#types/type-helpers"; -import { BooleanHolder, isNullOrUndefined, NumberHolder, toDmgValue } from "#utils/common"; +import type { Mutable } from "#types/type-helpers"; +import { BooleanHolder, NumberHolder, toDmgValue } from "#utils/common"; import i18next from "i18next"; -/* -ArenaTags are are meant for effects that are tied to the arena (as opposed to a specific pokemon). -Examples include (but are not limited to) -- Cross-turn effects that persist even if the user/target switches out, such as Wish, Future Sight, and Happy Hour -- Effects that are applied to a specific side of the field, such as Crafty Shield, Reflect, and Spikes -- Field-Effects, like Gravity and Trick Room - -Any arena tag that persists across turns *must* extend from `SerializableArenaTag` in the class definition signature. - -Serializable ArenaTags have strict rules for their fields. -These rules ensure that only the data necessary to reconstruct the tag is serialized, and that the -session loader is able to deserialize saved tags correctly. - -If the data is static (i.e. it is always the same for all instances of the class, such as the -type that is weakened by Mud Sport/Water Sport), then it must not be defined as a field, and must -instead be defined as a getter. -A static property is also acceptable, though static properties are less ergonomic with inheritance. - -If the data is mutable (i.e. it can change over the course of the tag's lifetime), then it *must* -be defined as a field, and it must be set in the `loadTag` method. -Such fields cannot be marked as `private/protected`, as if they were, typescript would omit them from -types that are based off of the class, namely, `ArenaTagTypeData`. It is preferrable to trade the -type-safety of private/protected fields for the type safety when deserializing arena tags from save data. - -For data that is mutable only within a turn (e.g. SuppressAbilitiesTag's beingRemoved field), -where it does not make sense to be serialized, the field should use ES2020's private field syntax (a `#` prepended to the field name). -If the field should be accessible outside of the class, then a public getter should be used. -*/ +/** + * @module + * ArenaTags are are meant for effects that are tied to the arena (as opposed to a specific pokemon). + * Examples include (but are not limited to) + * - Cross-turn effects that persist even if the user/target switches out, such as Happy Hour + * - Effects that are applied to a specific side of the field, such as Crafty Shield, Reflect, and Spikes + * - Field-Effects, like Gravity and Trick Room + * + * Any arena tag that persists across turns *must* extend from `SerializableArenaTag` in the class definition signature. + * + * Serializable ArenaTags have strict rules for their fields. + * These rules ensure that only the data necessary to reconstruct the tag is serialized, and that the + * session loader is able to deserialize saved tags correctly. + * + * If the data is static (i.e. it is always the same for all instances of the class, such as the + * type that is weakened by Mud Sport/Water Sport), then it must not be defined as a field, and must + * instead be defined as a getter. + * A static property is also acceptable, though static properties are less ergonomic with inheritance. + * + * If the data is mutable (i.e. it can change over the course of the tag's lifetime), then it *must* + * be defined as a field, and it must be set in the `loadTag` method. + * Such fields cannot be marked as `private`/`protected`; if they were, Typescript would omit them from + * types that are based off of the class, namely, `ArenaTagTypeData`. It is preferrable to trade the + * type-safety of private/protected fields for the type safety when deserializing arena tags from save data. + * + * For data that is mutable only within a turn (e.g. SuppressAbilitiesTag's beingRemoved field), + * where it does not make sense to be serialized, the field should use ES2020's + * [private field syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_elements#private_fields). + * If the field should be accessible outside of the class, then a public getter should be used. + * + * If any new serializable fields *are* added, then the class *must* override the + * `loadTag` method to set the new fields. Its signature *must* match the example below, + * ``` + * class ExampleTag extends SerializableArenaTag { + * // Example, if we add 2 new fields that should be serialized: + * public a: string; + * public b: number; + * // Then we must also define a loadTag method with one of the following signatures + * public override loadTag(source: BaseArenaTag & Pick(source: BaseArenaTag & Pick): void; + * public override loadTag(source: NonFunctionProperties): void; + * } + * ``` + * Notes + * - If the class has any subclasses, then the second form of `loadTag` *must* be used. + * - The third form *must not* be used if the class has any getters, as typescript would expect such fields to be + * present in `source`. + */ /** Interface containing the serializable fields of ArenaTagData. */ interface BaseArenaTag { @@ -141,9 +162,9 @@ export abstract class ArenaTag implements BaseArenaTag { /** * When given a arena tag or json representing one, load the data for it. * This is meant to be inherited from by any arena tag with custom attributes - * @param source - The {@linkcode BaseArenaTag} being loaded + * @param source - The arena tag being loaded */ - loadTag(source: BaseArenaTag): void { + loadTag(source: BaseArenaTag & Pick): void { this.turnCount = source.turnCount; this.sourceMove = source.sourceMove; this.sourceId = source.sourceId; @@ -604,56 +625,6 @@ export class NoCritTag extends SerializableArenaTag { } } -/** - * Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Wish_(move) | Wish}. - * Heals the Pokémon in the user's position the turn after Wish is used. - */ -class WishTag extends SerializableArenaTag { - // The following fields are meant to be inwardly mutable, but outwardly immutable. - readonly battlerIndex: BattlerIndex; - readonly healHp: number; - readonly sourceName: string; - // End inwardly mutable fields - - public readonly tagType = ArenaTagType.WISH; - - constructor(turnCount: number, sourceId: number | undefined, side: ArenaTagSide) { - super(turnCount, MoveId.WISH, sourceId, side); - } - - onAdd(_arena: Arena): void { - const source = this.getSourcePokemon(); - if (!source) { - console.warn(`Failed to get source Pokemon for WishTag on add message; id: ${this.sourceId}`); - return; - } - - (this as Mutable).sourceName = getPokemonNameWithAffix(source); - (this as Mutable).healHp = toDmgValue(source.getMaxHp() / 2); - (this as Mutable).battlerIndex = source.getBattlerIndex(); - } - - onRemove(_arena: Arena): void { - const target = globalScene.getField()[this.battlerIndex]; - if (target?.isActive(true)) { - globalScene.phaseManager.queueMessage( - // TODO: Rename key as it triggers on activation - i18next.t("arenaTag:wishTagOnAdd", { - pokemonNameWithAffix: this.sourceName, - }), - ); - globalScene.phaseManager.unshiftNew("PokemonHealPhase", target.getBattlerIndex(), this.healHp, null, true, false); - } - } - - override loadTag(source: NonFunctionProperties): void { - super.loadTag(source); - (this as Mutable).battlerIndex = source.battlerIndex; - (this as Mutable).healHp = source.healHp; - (this as Mutable).sourceName = source.sourceName; - } -} - /** * Abstract class to implement weakened moves of a specific type. */ @@ -813,7 +784,7 @@ export abstract class ArenaTrapTag extends SerializableArenaTag { : Phaser.Math.Linear(0, 1 / Math.pow(2, this.layers), Math.min(pokemon.getHpRatio(), 0.5) * 2); } - loadTag(source: NonFunctionProperties): void { + public loadTag(source: BaseArenaTag & Pick): void { super.loadTag(source); this.layers = source.layers; this.maxLayers = source.maxLayers; @@ -1126,48 +1097,6 @@ class StickyWebTag extends ArenaTrapTag { } } -/** - * Arena Tag class for delayed attacks, such as {@linkcode MoveId.FUTURE_SIGHT} or {@linkcode MoveId.DOOM_DESIRE}. - * Delays the attack's effect by a set amount of turns, usually 3 (including the turn the move is used), - * and deals damage after the turn count is reached. - */ -export class DelayedAttackTag extends SerializableArenaTag { - public targetIndex: BattlerIndex; - public readonly tagType: ArenaDelayedAttackTagType; - - constructor( - tagType: ArenaTagType.DOOM_DESIRE | ArenaTagType.FUTURE_SIGHT, - sourceMove: MoveId | undefined, - sourceId: number | undefined, - targetIndex: BattlerIndex, - side: ArenaTagSide = ArenaTagSide.BOTH, - ) { - super(3, sourceMove, sourceId, side); - this.tagType = tagType; - this.targetIndex = targetIndex; - this.side = side; - } - - lapse(arena: Arena): boolean { - const ret = super.lapse(arena); - - if (!ret) { - // TODO: This should not add to move history (for Spite) - globalScene.phaseManager.unshiftNew( - "MoveEffectPhase", - this.sourceId!, - [this.targetIndex], - allMoves[this.sourceMove!], - MoveUseMode.FOLLOW_UP, - ); // TODO: are those bangs correct? - } - - return ret; - } - - onRemove(_arena: Arena): void {} -} - /** * Arena Tag class for {@link https://bulbapedia.bulbagarden.net/wiki/Trick_Room_(move) Trick Room}. * Reverses the Speed stats for all Pokémon on the field as long as this arena tag is up, @@ -1581,7 +1510,7 @@ export class SuppressAbilitiesTag extends SerializableArenaTag { this.#beingRemoved = false; } - public override loadTag(source: NonFunctionProperties): void { + public override loadTag(source: BaseArenaTag & Pick): void { super.loadTag(source); (this as Mutable).sourceCount = source.sourceCount; } @@ -1663,7 +1592,6 @@ export function getArenaTag( turnCount: number, sourceMove: MoveId | undefined, sourceId: number | undefined, - targetIndex?: BattlerIndex, side: ArenaTagSide = ArenaTagSide.BOTH, ): ArenaTag | null { switch (tagType) { @@ -1689,14 +1617,6 @@ export function getArenaTag( return new SpikesTag(sourceId, side); case ArenaTagType.TOXIC_SPIKES: return new ToxicSpikesTag(sourceId, side); - case ArenaTagType.FUTURE_SIGHT: - case ArenaTagType.DOOM_DESIRE: - if (isNullOrUndefined(targetIndex)) { - return null; // If missing target index, no tag is created - } - return new DelayedAttackTag(tagType, sourceMove, sourceId, targetIndex, side); - case ArenaTagType.WISH: - return new WishTag(turnCount, sourceId, side); case ArenaTagType.STEALTH_ROCK: return new StealthRockTag(sourceId, side); case ArenaTagType.STICKY_WEB: @@ -1739,16 +1659,9 @@ export function getArenaTag( * @param source - An arena tag * @returns The valid arena tag */ -export function loadArenaTag(source: (ArenaTag | ArenaTagTypeData) & { targetIndex?: BattlerIndex }): ArenaTag { +export function loadArenaTag(source: ArenaTag | ArenaTagTypeData): ArenaTag { const tag = - getArenaTag( - source.tagType, - source.turnCount, - source.sourceMove, - source.sourceId, - source.targetIndex, - source.side, - ) ?? new NoneTag(); + getArenaTag(source.tagType, source.turnCount, source.sourceMove, source.sourceId, source.side) ?? new NoneTag(); tag.loadTag(source); return tag; } @@ -1765,9 +1678,6 @@ export type ArenaTagTypeMap = { [ArenaTagType.CRAFTY_SHIELD]: CraftyShieldTag; [ArenaTagType.NO_CRIT]: NoCritTag; [ArenaTagType.TOXIC_SPIKES]: ToxicSpikesTag; - [ArenaTagType.FUTURE_SIGHT]: DelayedAttackTag; - [ArenaTagType.DOOM_DESIRE]: DelayedAttackTag; - [ArenaTagType.WISH]: WishTag; [ArenaTagType.STEALTH_ROCK]: StealthRockTag; [ArenaTagType.STICKY_WEB]: StickyWebTag; [ArenaTagType.TRICK_ROOM]: TrickRoomTag; diff --git a/src/data/battler-tags.ts b/src/data/battler-tags.ts index c8ddfe32f0b..e21065c184f 100644 --- a/src/data/battler-tags.ts +++ b/src/data/battler-tags.ts @@ -8,6 +8,7 @@ import { SpeciesFormChangeAbilityTrigger } from "#data/form-change-triggers"; import { getStatusEffectHealText } from "#data/status-effect"; import { TerrainType } from "#data/terrain"; import { AbilityId } from "#enums/ability-id"; +import type { BattlerIndex } from "#enums/battler-index"; import { BattlerTagLapseType } from "#enums/battler-tag-lapse-type"; import { BattlerTagType } from "#enums/battler-tag-type"; import { HitResult } from "#enums/hit-result"; @@ -31,41 +32,125 @@ import type { MoveEffectPhase } from "#phases/move-effect-phase"; import type { MovePhase } from "#phases/move-phase"; import type { StatStageChangeCallback } from "#phases/stat-stage-change-phase"; import i18next from "#plugins/i18n"; +import type { + AbilityBattlerTagType, + ContactSetStatusProtectedTagType, + ContactStatStageChangeProtectedTagType, + DamageProtectedTagType, + EndureTagType, + HighestStatBoostTagType, + MoveRestrictionBattlerTagType, + ProtectionBattlerTagType, + SemiInvulnerableTagType, + TrappingBattlerTagType, +} from "#types/battler-tags"; +import type { Mutable, NonFunctionProperties } from "#types/type-helpers"; import { BooleanHolder, coerceArray, getFrameMs, isNullOrUndefined, NumberHolder, toDmgValue } from "#utils/common"; +/** + * @module + * BattlerTags are used to represent semi-persistent effects that can be attached to a Pokemon. + * Note that before serialization, a new tag object is created, and then `loadTag` is called on the + * tag with the object that was serialized. + * + * This means it is straightforward to avoid serializing fields. + * Fields that are not set in the constructor and not set in `loadTag` will thus not be serialized. + * + * Any battler tag that can persist across sessions must extend SerializableBattlerTag in its class definition signature. + * Only tags that persist across waves (meaning their effect can last >1 turn) should be considered + * serializable. + * + * Serializable battler tags have strict requirements for their fields. + * Properties that are not necessary to reconstruct the tag must not be serialized. This can be avoided + * by using a private property. If access to the property is needed outside of the class, then + * a getter (and potentially, a setter) should be used instead. + * + * If a property that is intended to be private must be serialized, then it should instead + * be declared as a public readonly propety. Then, in the `loadTag` method (or any method inside the class that needs to adjust the property) + * use `(this as Mutable).propertyName = value;` + * These rules ensure that Typescript is aware of the shape of the serialized version of the class. + * + * If any new serializable fields *are* added, then the class *must* override the + * `loadTag` method to set the new fields. Its signature *must* match the example below: + * ``` + * class ExampleTag extends SerializableBattlerTag { + * // Example, if we add 2 new fields that should be serialized: + * public a: string; + * public b: number; + * // Then we must also define a loadTag method with one of the following signatures + * public override loadTag(source: BaseBattlerTag & Pick(source: BaseBattlerTag & Pick): void; + * public override loadTag(source: NonFunctionProperties): void; + * } + * ``` + * Notes + * - If the class has any subclasses, then the second form of `loadTag` *must* be used. + * - The third form *must not* be used if the class has any getters, as typescript would expect such fields to be + * present in `source`. + */ + +/** Interface containing the serializable fields of BattlerTag */ +interface BaseBattlerTag { + /** The tag's remaining duration */ + turnCount: number; + /** The {@linkcode MoveId} that created this tag, or `undefined` if not set by a move */ + sourceMove?: MoveId; + /** The {@linkcode Pokemon.id | PID} of the Pokemon that added this tag, or `undefined` if not set by a pokemon */ + sourceId?: number; +} + /** * A {@linkcode BattlerTag} represents a semi-persistent effect that can be attached to a {@linkcode Pokemon}. * Tags can trigger various effects throughout a turn, and are cleared on switching out * or through their respective {@linkcode BattlerTag.lapse | lapse} methods. */ -export class BattlerTag { - public tagType: BattlerTagType; - public lapseTypes: BattlerTagLapseType[]; +export class BattlerTag implements BaseBattlerTag { + public readonly tagType: BattlerTagType; + public turnCount: number; - public sourceMove: MoveId; + public sourceMove?: MoveId; public sourceId?: number; - public isBatonPassable: boolean; + + //#region non-serializable fields + // Fields that should never be serialized, as they must not change after instantiation + #isBatonPassable = false; + public get isBatonPassable(): boolean { + return this.#isBatonPassable; + } + + #lapseTypes: readonly [BattlerTagLapseType, ...BattlerTagLapseType[]]; + public get lapseTypes(): readonly BattlerTagLapseType[] { + return this.#lapseTypes; + } + //#endregion non-serializable fields constructor( tagType: BattlerTagType, - lapseType: BattlerTagLapseType | BattlerTagLapseType[], + lapseType: BattlerTagLapseType | [BattlerTagLapseType, ...BattlerTagLapseType[]], turnCount: number, sourceMove?: MoveId, sourceId?: number, isBatonPassable = false, ) { this.tagType = tagType; - this.lapseTypes = coerceArray(lapseType); + this.#lapseTypes = coerceArray(lapseType); this.turnCount = turnCount; - this.sourceMove = sourceMove!; // TODO: is this bang correct? + // We intentionally don't want to set source move to `MoveId.NONE` here, so a raw boolean comparison is OK. + if (sourceMove) { + this.sourceMove = sourceMove; + } this.sourceId = sourceId; - this.isBatonPassable = isBatonPassable; + this.#isBatonPassable = isBatonPassable; } canAdd(_pokemon: Pokemon): boolean { return true; } + /** + * Apply effects that occur when the tag is added to a {@linkcode Pokemon} + * @param _pokemon - The {@linkcode Pokemon} the tag was added to + */ onAdd(_pokemon: Pokemon): void {} onRemove(_pokemon: Pokemon): void {} @@ -99,9 +184,9 @@ export class BattlerTag { /** * Load the data for a given {@linkcode BattlerTag} or JSON representation thereof. * Should be inherited from by any battler tag with custom attributes. - * @param source The battler tag to load + * @param source - An object containing the fields needed to reconstruct this tag. */ - loadTag(source: BattlerTag | any): void { + public loadTag(source: BaseBattlerTag & Pick): void { this.turnCount = source.turnCount; this.sourceMove = source.sourceMove; this.sourceId = source.sourceId; @@ -116,12 +201,9 @@ export class BattlerTag { } } -export interface WeatherBattlerTag { - weatherTypes: WeatherType[]; -} - -export interface TerrainBattlerTag { - terrainTypes: TerrainType[]; +export abstract class SerializableBattlerTag extends BattlerTag { + /** Nonexistent, dummy field to allow typescript to distinguish this class from `BattlerTag` */ + private declare __SerializableBattlerTag: never; } /** @@ -132,8 +214,8 @@ export interface TerrainBattlerTag { * match a condition. A restricted move gets cancelled before it is used. * Players and enemies should not be allowed to select restricted moves. */ -export abstract class MoveRestrictionBattlerTag extends BattlerTag { - /** @override */ +export abstract class MoveRestrictionBattlerTag extends SerializableBattlerTag { + public declare readonly tagType: MoveRestrictionBattlerTagType; override lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { if (lapseType === BattlerTagLapseType.PRE_MOVE) { // Cancel the affected pokemon's selected move @@ -154,32 +236,32 @@ export abstract class MoveRestrictionBattlerTag extends BattlerTag { } /** - * Gets whether this tag is restricting a move. + * Determine whether a move's usage is restricted by this tag * - * @param move - {@linkcode MoveId} ID to check restriction for. + * @param move - The {@linkcode MoveId} being checked * @param user - The {@linkcode Pokemon} involved * @returns `true` if the move is restricted by this tag, otherwise `false`. */ public abstract isMoveRestricted(move: MoveId, user?: Pokemon): boolean; /** - * Checks if this tag is restricting a move based on a user's decisions during the target selection phase + * Check if this tag is restricting a move based on a user's decisions during the target selection phase * - * @param {MoveId} _move {@linkcode MoveId} move ID to check restriction for - * @param {Pokemon} _user {@linkcode Pokemon} the user of the above move - * @param {Pokemon} _target {@linkcode Pokemon} the target of the above move - * @returns {boolean} `false` unless overridden by the child tag + * @param _move - {@linkcode MoveId} to check restriction for + * @param _user - The user of the move + * @param _target - The pokemon targeted by the move + * @returns Whether the move is restricted by this tag */ isMoveTargetRestricted(_move: MoveId, _user: Pokemon, _target: Pokemon): boolean { return false; } /** - * Gets the text to display when the player attempts to select a move that is restricted by this tag. + * Get the text to display when the player attempts to select a move that is restricted by this tag. * - * @param {Pokemon} pokemon {@linkcode Pokemon} for which the player is attempting to select the restricted move - * @param {MoveId} move {@linkcode MoveId} ID of the move that is having its selection denied - * @returns {string} text to display when the player attempts to select the restricted move + * @param pokemon - The pokemon for which the player is attempting to select the restricted move + * @param move - The {@linkcode MoveId | ID} of the Move that is having its selection denied + * @returns The text to display when the player attempts to select the restricted move */ abstract selectionDeniedText(pokemon: Pokemon, move: MoveId): string; @@ -188,9 +270,9 @@ export abstract class MoveRestrictionBattlerTag extends BattlerTag { * Because restriction effects also prevent selection of the move, this situation can only arise if a * pokemon first selects a move, then gets outsped by a pokemon using a move that restricts the selected move. * - * @param {Pokemon} _pokemon {@linkcode Pokemon} attempting to use the restricted move - * @param {MoveId} _move {@linkcode MoveId} ID of the move being interrupted - * @returns {string} text to display when the move is interrupted + * @param _pokemon - The pokemon attempting to use the restricted move + * @param _move - The {@linkcode MoveId | ID} of the move being interrupted + * @returns The text to display when the move is interrupted */ interruptedText(_pokemon: Pokemon, _move: MoveId): string { return ""; @@ -200,9 +282,10 @@ export abstract class MoveRestrictionBattlerTag extends BattlerTag { /** * Tag representing the "Throat Chop" effect. Pokemon with this tag cannot use sound-based moves. * @see {@link https://bulbapedia.bulbagarden.net/wiki/Throat_Chop_(move) | Throat Chop} - * @extends MoveRestrictionBattlerTag + * @sealed */ export class ThroatChoppedTag extends MoveRestrictionBattlerTag { + public override readonly tagType = BattlerTagType.THROAT_CHOPPED; constructor() { super( BattlerTagType.THROAT_CHOPPED, @@ -213,10 +296,9 @@ export class ThroatChoppedTag extends MoveRestrictionBattlerTag { } /** - * Checks if a {@linkcode MoveId | move} is restricted by Throat Chop. - * @override - * @param {MoveId} move the {@linkcode MoveId | move} to check for sound-based restriction - * @returns true if the move is sound-based + * Check if a move is restricted by Throat Chop. + * @param move - The {@linkcode MoveId | ID } of the move to check for sound-based restriction + * @returns Whether the move is sound based */ override isMoveRestricted(move: MoveId): boolean { return allMoves[move].hasFlag(MoveFlags.SOUND_BASED); @@ -224,10 +306,9 @@ export class ThroatChoppedTag extends MoveRestrictionBattlerTag { /** * Shows a message when the player attempts to select a move that is restricted by Throat Chop. - * @override - * @param {Pokemon} _pokemon the {@linkcode Pokemon} that is attempting to select the restricted move - * @param {MoveId} move the {@linkcode MoveId | move} that is being restricted - * @returns the message to display when the player attempts to select the restricted move + * @param _pokemon - The {@linkcode Pokemon} that is attempting to select the restricted move + * @param move - The {@linkcode MoveId | move} that is being restricted + * @returns The message to display when the player attempts to select the restricted move */ override selectionDeniedText(_pokemon: Pokemon, move: MoveId): string { return i18next.t("battle:moveCannotBeSelected", { @@ -237,10 +318,9 @@ export class ThroatChoppedTag extends MoveRestrictionBattlerTag { /** * Shows a message when a move is interrupted by Throat Chop. - * @override - * @param {Pokemon} pokemon the interrupted {@linkcode Pokemon} - * @param {MoveId} _move the {@linkcode MoveId | move} that was interrupted - * @returns the message to display when the move is interrupted + * @param pokemon - The interrupted {@linkcode Pokemon} + * @param _move - The {@linkcode MoveId | ID } of the move that was interrupted + * @returns The message to display when the move is interrupted */ override interruptedText(pokemon: Pokemon, _move: MoveId): string { return i18next.t("battle:throatChopInterruptedMove", { @@ -252,10 +332,13 @@ export class ThroatChoppedTag extends MoveRestrictionBattlerTag { /** * Tag representing the "disabling" effect performed by {@linkcode MoveId.DISABLE} and {@linkcode AbilityId.CURSED_BODY}. * When the tag is added, the last-used move of the tag holder is set as the disabled move. + * + * @sealed */ export class DisabledTag extends MoveRestrictionBattlerTag { + public override readonly tagType = BattlerTagType.DISABLED; /** The move being disabled. Gets set when {@linkcode onAdd} is called for this tag. */ - private moveId: MoveId = MoveId.NONE; + public readonly moveId: MoveId = MoveId.NONE; constructor(sourceId: number) { super( @@ -267,14 +350,11 @@ export class DisabledTag extends MoveRestrictionBattlerTag { ); } - /** @override */ override isMoveRestricted(move: MoveId): boolean { return move === this.moveId; } /** - * @override - * * Attempt to disable the target's last move by setting this tag's {@linkcode moveId} * and showing a message. */ @@ -287,7 +367,7 @@ export class DisabledTag extends MoveRestrictionBattlerTag { } super.onAdd(pokemon); - this.moveId = move.move; + (this as Mutable).moveId = move.move; globalScene.phaseManager.queueMessage( i18next.t("battlerTags:disabledOnAdd", { @@ -297,7 +377,6 @@ export class DisabledTag extends MoveRestrictionBattlerTag { ); } - /** @override */ override onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); @@ -309,16 +388,14 @@ export class DisabledTag extends MoveRestrictionBattlerTag { ); } - /** @override */ override selectionDeniedText(_pokemon: Pokemon, move: MoveId): string { return i18next.t("battle:moveDisabled", { moveName: allMoves[move].name }); } /** - * @override - * @param {Pokemon} pokemon {@linkcode Pokemon} attempting to use the restricted move - * @param {MoveId} move {@linkcode MoveId} ID of the move being interrupted - * @returns {string} text to display when the move is interrupted + * @param pokemon - {@linkcode Pokemon} attempting to use the restricted move + * @param move - {@linkcode MoveId | ID} of the move being interrupted + * @returns The text to display when the move is interrupted */ override interruptedText(pokemon: Pokemon, move: MoveId): string { return i18next.t("battle:disableInterruptedMove", { @@ -327,18 +404,21 @@ export class DisabledTag extends MoveRestrictionBattlerTag { }); } - /** @override */ - override loadTag(source: BattlerTag | any): void { + public override loadTag(source: BaseBattlerTag & Pick): void { super.loadTag(source); - this.moveId = source.moveId; + (this as Mutable).moveId = source.moveId; } } /** * Tag used by Gorilla Tactics to restrict the user to using only one move. + * + * @sealed */ export class GorillaTacticsTag extends MoveRestrictionBattlerTag { - private moveId = MoveId.NONE; + public override readonly tagType = BattlerTagType.GORILLA_TACTICS; + /** ID of the move that the user is locked into using*/ + public readonly moveId: MoveId = MoveId.NONE; constructor() { super(BattlerTagType.GORILLA_TACTICS, BattlerTagLapseType.CUSTOM, 0); @@ -367,18 +447,17 @@ export class GorillaTacticsTag extends MoveRestrictionBattlerTag { super.onAdd(pokemon); // Bang is justified as tag is not added if prior move doesn't exist - this.moveId = pokemon.getLastNonVirtualMove()!.move; + (this as Mutable).moveId = pokemon.getLastNonVirtualMove()!.move; pokemon.setStat(Stat.ATK, pokemon.getStat(Stat.ATK, false) * 1.5, false); } /** * Loads the Gorilla Tactics Battler Tag along with its unique class variable moveId - * @override - * @param source Gorilla Tactics' {@linkcode BattlerTag} information + * @param source - Object containing the fields needed to reconstruct this tag. */ - public override loadTag(source: BattlerTag | any): void { + public override loadTag(source: BaseBattlerTag & Pick): void { super.loadTag(source); - this.moveId = source.moveId; + (this as Mutable).moveId = source.moveId; } /** @@ -397,7 +476,8 @@ export class GorillaTacticsTag extends MoveRestrictionBattlerTag { /** * BattlerTag that represents the "recharge" effects of moves like Hyper Beam. */ -export class RechargingTag extends BattlerTag { +export class RechargingTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.RECHARGING; constructor(sourceMove: MoveId) { super(BattlerTagType.RECHARGING, [BattlerTagLapseType.PRE_MOVE, BattlerTagLapseType.TURN_END], 2, sourceMove); } @@ -430,6 +510,8 @@ export class RechargingTag extends BattlerTag { * @see {@link https://bulbapedia.bulbagarden.net/wiki/Beak_Blast_(move) | Beak Blast} */ export class BeakBlastChargingTag extends BattlerTag { + public override readonly tagType = BattlerTagType.BEAK_BLAST_CHARGING; + public declare readonly sourceMove: MoveId.BEAK_BLAST; constructor() { super( BattlerTagType.BEAK_BLAST_CHARGING, @@ -454,8 +536,8 @@ export class BeakBlastChargingTag extends BattlerTag { /** * Inflicts `BURN` status on attackers that make contact, and causes this tag * to be removed after the source makes a move (or the turn ends, whichever comes first) - * @param pokemon {@linkcode Pokemon} the owner of this tag - * @param lapseType {@linkcode BattlerTagLapseType} the type of functionality invoked in battle + * @param pokemon - The owner of this tag + * @param lapseType - The type of functionality invoked in battle * @returns `true` if invoked with the `AFTER_HIT` lapse type */ lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -498,8 +580,8 @@ export class ShellTrapTag extends BattlerTag { /** * "Activates" the shell trap, causing the tag owner to move next. - * @param pokemon {@linkcode Pokemon} the owner of this tag - * @param lapseType {@linkcode BattlerTagLapseType} the type of functionality invoked in battle + * @param pokemon - The owner of this tag + * @param lapseType - The type of functionality invoked in battle * @returns `true` if invoked with the `AFTER_HIT` lapse type */ lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -529,7 +611,8 @@ export class ShellTrapTag extends BattlerTag { } } -export class TrappedTag extends BattlerTag { +export class TrappedTag extends SerializableBattlerTag { + public declare readonly tagType: TrappingBattlerTagType; constructor( tagType: BattlerTagType, lapseType: BattlerTagLapseType, @@ -546,13 +629,13 @@ export class TrappedTag extends BattlerTag { console.warn(`Failed to get source Pokemon for TrappedTag canAdd; id: ${this.sourceId}`); return false; } - - const move = allMoves[this.sourceMove]; + if (this.sourceMove && allMoves[this.sourceMove]?.hitsSubstitute(source, pokemon)) { + return false; + } const isGhost = pokemon.isOfType(PokemonType.GHOST); const isTrapped = pokemon.getTag(TrappedTag); - const hasSubstitute = move.hitsSubstitute(source, pokemon); - return !isTrapped && !isGhost && !hasSubstitute; + return !isTrapped && !isGhost; } onAdd(pokemon: Pokemon): void { @@ -591,9 +674,9 @@ export class TrappedTag extends BattlerTag { * BattlerTag implementing No Retreat's trapping effect. * This is treated separately from other trapping effects to prevent * Ghost-type Pokemon from being able to reuse the move. - * @extends TrappedTag */ class NoRetreatTag extends TrappedTag { + public override readonly tagType = BattlerTagType.NO_RETREAT; constructor(sourceId: number) { super(BattlerTagType.NO_RETREAT, BattlerTagLapseType.CUSTOM, 0, MoveId.NO_RETREAT, sourceId); } @@ -608,6 +691,7 @@ class NoRetreatTag extends TrappedTag { * BattlerTag that represents the {@link https://bulbapedia.bulbagarden.net/wiki/Flinch Flinch} status condition */ export class FlinchedTag extends BattlerTag { + public override readonly tagType = BattlerTagType.FLINCHED; constructor(sourceMove: MoveId) { super(BattlerTagType.FLINCHED, [BattlerTagLapseType.PRE_MOVE, BattlerTagLapseType.TURN_END], 1, sourceMove); } @@ -639,6 +723,7 @@ export class FlinchedTag extends BattlerTag { } export class InterruptedTag extends BattlerTag { + public override readonly tagType = BattlerTagType.INTERRUPTED; constructor(sourceMove: MoveId) { super(BattlerTagType.INTERRUPTED, BattlerTagLapseType.PRE_MOVE, 0, sourceMove); } @@ -668,7 +753,8 @@ export class InterruptedTag extends BattlerTag { /** * BattlerTag that represents the {@link https://bulbapedia.bulbagarden.net/wiki/Confusion_(status_condition) Confusion} status condition */ -export class ConfusedTag extends BattlerTag { +export class ConfusedTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.CONFUSED; constructor(turnCount: number, sourceMove: MoveId) { super(BattlerTagType.CONFUSED, BattlerTagLapseType.MOVE, turnCount, sourceMove, undefined, true); } @@ -752,10 +838,10 @@ export class ConfusedTag extends BattlerTag { /** * Tag applied to the {@linkcode Move.DESTINY_BOND} user. - * @extends BattlerTag * @see {@linkcode apply} */ -export class DestinyBondTag extends BattlerTag { +export class DestinyBondTag extends SerializableBattlerTag { + public readonly tagType = BattlerTagType.DESTINY_BOND; constructor(sourceMove: MoveId, sourceId: number) { super(BattlerTagType.DESTINY_BOND, BattlerTagLapseType.PRE_MOVE, 1, sourceMove, sourceId, true); } @@ -765,9 +851,9 @@ export class DestinyBondTag extends BattlerTag { * or after receiving fatal damage. When the damage is fatal, * the attacking Pokemon is taken down as well, unless it's a boss. * - * @param {Pokemon} pokemon Pokemon that is attacking the Destiny Bond user. - * @param {BattlerTagLapseType} lapseType CUSTOM or PRE_MOVE - * @returns false if the tag source fainted or one turn has passed since the application + * @param pokemon - The Pokemon that is attacking the Destiny Bond user. + * @param lapseType - CUSTOM or PRE_MOVE + * @returns `false` if the tag source fainted or one turn has passed since the application */ lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { if (lapseType !== BattlerTagLapseType.CUSTOM) { @@ -811,7 +897,9 @@ export class DestinyBondTag extends BattlerTag { } } -export class InfatuatedTag extends BattlerTag { +// Technically serializable as in a double battle, a pokemon could be infatuated by its ally +export class InfatuatedTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.INFATUATED; constructor(sourceMove: number, sourceId: number) { super(BattlerTagType.INFATUATED, BattlerTagLapseType.MOVE, 1, sourceMove, sourceId); } @@ -901,8 +989,15 @@ export class InfatuatedTag extends BattlerTag { } } -export class SeedTag extends BattlerTag { - private sourceIndex: number; +/** + * Battler tag for the "Seeded" effect applied by {@linkcode MoveId.LEECH_SEED | Leech Seed} and + * {@linkcode MoveId.SAPPY_SEED | Sappy Seed} + * + * @sealed + */ +export class SeedTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.SEEDED; + public readonly sourceIndex: BattlerIndex; constructor(sourceId: number) { super(BattlerTagType.SEEDED, BattlerTagLapseType.TURN_END, 1, MoveId.LEECH_SEED, sourceId, true); @@ -910,11 +1005,11 @@ export class SeedTag extends BattlerTag { /** * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag + * @param source - An object containing the fields needed to reconstruct this tag. */ - loadTag(source: BattlerTag | any): void { + public override loadTag(source: BaseBattlerTag & Pick): void { super.loadTag(source); - this.sourceIndex = source.sourceIndex; + (this as Mutable).sourceIndex = source.sourceIndex; } canAdd(pokemon: Pokemon): boolean { @@ -935,7 +1030,7 @@ export class SeedTag extends BattlerTag { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), }), ); - this.sourceIndex = source.getBattlerIndex(); + (this as Mutable).sourceIndex = source.getBattlerIndex(); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -990,9 +1085,10 @@ export class SeedTag extends BattlerTag { /** * BattlerTag representing the effects of {@link https://bulbapedia.bulbagarden.net/wiki/Powder_(move) | Powder}. * When the afflicted Pokemon uses a Fire-type move, the move is cancelled, and the - * Pokemon takes damage equal to 1/4 of it's maximum HP (rounded down). + * Pokemon takes damage equal to 1/4 of its maximum HP (rounded down). */ export class PowderTag extends BattlerTag { + public override readonly tagType = BattlerTagType.POWDER; constructor() { super(BattlerTagType.POWDER, [BattlerTagLapseType.PRE_MOVE, BattlerTagLapseType.TURN_END], 1); } @@ -1051,7 +1147,7 @@ export class PowderTag extends BattlerTag { } } -export class NightmareTag extends BattlerTag { +export class NightmareTag extends SerializableBattlerTag { constructor() { super(BattlerTagType.NIGHTMARE, BattlerTagLapseType.TURN_END, 1, MoveId.NIGHTMARE); } @@ -1104,7 +1200,7 @@ export class NightmareTag extends BattlerTag { } } -export class FrenzyTag extends BattlerTag { +export class FrenzyTag extends SerializableBattlerTag { constructor(turnCount: number, sourceMove: MoveId, sourceId: number) { super(BattlerTagType.FRENZY, BattlerTagLapseType.CUSTOM, turnCount, sourceMove, sourceId); } @@ -1122,8 +1218,11 @@ export class FrenzyTag extends BattlerTag { /** * Applies the effects of {@linkcode MoveId.ENCORE} onto the target Pokemon. * Encore forces the target Pokemon to use its most-recent move for 3 turns. + * @sealed */ export class EncoreTag extends MoveRestrictionBattlerTag { + public override readonly tagType = BattlerTagType.ENCORE; + /** The ID of the move the user is locked into using */ public moveId: MoveId; constructor(sourceId: number) { @@ -1136,12 +1235,12 @@ export class EncoreTag extends MoveRestrictionBattlerTag { ); } - loadTag(source: BattlerTag | any): void { + public override loadTag(source: NonFunctionProperties): void { super.loadTag(source); - this.moveId = source.moveId as MoveId; + this.moveId = source.moveId; } - canAdd(pokemon: Pokemon): boolean { + override canAdd(pokemon: Pokemon): boolean { const lastMove = pokemon.getLastNonVirtualMove(); if (!lastMove) { return false; @@ -1156,10 +1255,7 @@ export class EncoreTag extends MoveRestrictionBattlerTag { return true; } - onAdd(pokemon: Pokemon): void { - // TODO: shouldn't this be `onAdd`? - super.onRemove(pokemon); - + override onAdd(pokemon: Pokemon): void { globalScene.phaseManager.queueMessage( i18next.t("battlerTags:encoreOnAdd", { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), @@ -1199,7 +1295,7 @@ export class EncoreTag extends MoveRestrictionBattlerTag { /** * Checks if the move matches the moveId stored within the tag and returns a boolean value - * @param move {@linkcode MoveId} the move selected + * @param move - The ID of the move selected * @param user N/A * @returns `true` if the move does not match with the moveId stored and as a result, restricted */ @@ -1223,6 +1319,7 @@ export class EncoreTag extends MoveRestrictionBattlerTag { } export class HelpingHandTag extends BattlerTag { + public override readonly tagType = BattlerTagType.HELPING_HAND; constructor(sourceId: number) { super(BattlerTagType.HELPING_HAND, BattlerTagLapseType.TURN_END, 1, MoveId.HELPING_HAND, sourceId); } @@ -1245,16 +1342,16 @@ export class HelpingHandTag extends BattlerTag { /** * Applies the Ingrain tag to a pokemon - * @extends TrappedTag */ export class IngrainTag extends TrappedTag { + public override readonly tagType = BattlerTagType.INGRAIN; constructor(sourceId: number) { super(BattlerTagType.INGRAIN, BattlerTagLapseType.TURN_END, 1, MoveId.INGRAIN, sourceId); } /** * Check if the Ingrain tag can be added to the pokemon - * @param pokemon {@linkcode Pokemon} The pokemon to check if the tag can be added to + * @param pokemon - The pokemon to check if the tag can be added to * @returns boolean True if the tag can be added, false otherwise */ canAdd(pokemon: Pokemon): boolean { @@ -1295,6 +1392,7 @@ export class IngrainTag extends TrappedTag { * end of each turn. */ export class OctolockTag extends TrappedTag { + public override readonly tagType = BattlerTagType.OCTOLOCK; constructor(sourceId: number) { super(BattlerTagType.OCTOLOCK, BattlerTagLapseType.TURN_END, 1, MoveId.OCTOLOCK, sourceId); } @@ -1317,7 +1415,8 @@ export class OctolockTag extends TrappedTag { } } -export class AquaRingTag extends BattlerTag { +export class AquaRingTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.AQUA_RING; constructor() { super(BattlerTagType.AQUA_RING, BattlerTagLapseType.TURN_END, 1, MoveId.AQUA_RING, undefined, true); } @@ -1353,7 +1452,8 @@ export class AquaRingTag extends BattlerTag { } /** Tag used to allow moves that interact with {@link MoveId.MINIMIZE} to function */ -export class MinimizeTag extends BattlerTag { +export class MinimizeTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.MINIMIZED; constructor() { super(BattlerTagType.MINIMIZED, BattlerTagLapseType.TURN_END, 1, MoveId.MINIMIZE); } @@ -1371,7 +1471,8 @@ export class MinimizeTag extends BattlerTag { } } -export class DrowsyTag extends BattlerTag { +export class DrowsyTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.DROWSY; constructor() { super(BattlerTagType.DROWSY, BattlerTagLapseType.TURN_END, 2, MoveId.YAWN); } @@ -1405,7 +1506,9 @@ export class DrowsyTag extends BattlerTag { } export abstract class DamagingTrapTag extends TrappedTag { - private commonAnim: CommonAnim; + public declare readonly tagType: TrappingBattlerTagType; + /** The animation to play during the damage sequence */ + #commonAnim: CommonAnim; constructor( tagType: BattlerTagType, @@ -1416,16 +1519,7 @@ export abstract class DamagingTrapTag extends TrappedTag { ) { super(tagType, BattlerTagLapseType.TURN_END, turnCount, sourceMove, sourceId); - this.commonAnim = commonAnim; - } - - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.commonAnim = source.commonAnim as CommonAnim; + this.#commonAnim = commonAnim; } canAdd(pokemon: Pokemon): boolean { @@ -1443,7 +1537,7 @@ export abstract class DamagingTrapTag extends TrappedTag { moveName: this.getMoveName(), }), ); - phaseManager.unshiftNew("CommonAnimPhase", pokemon.getBattlerIndex(), undefined, this.commonAnim); + phaseManager.unshiftNew("CommonAnimPhase", pokemon.getBattlerIndex(), undefined, this.#commonAnim); const cancelled = new BooleanHolder(false); applyAbAttrs("BlockNonDirectDamageAbAttr", { pokemon, cancelled }); @@ -1459,6 +1553,7 @@ export abstract class DamagingTrapTag extends TrappedTag { // TODO: Condense all these tags into 1 singular tag with a modified message func export class BindTag extends DamagingTrapTag { + public override readonly tagType = BattlerTagType.BIND; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.BIND, CommonAnim.BIND, turnCount, MoveId.BIND, sourceId); } @@ -1479,6 +1574,7 @@ export class BindTag extends DamagingTrapTag { } export class WrapTag extends DamagingTrapTag { + public override readonly tagType = BattlerTagType.WRAP; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.WRAP, CommonAnim.WRAP, turnCount, MoveId.WRAP, sourceId); } @@ -1507,18 +1603,21 @@ export abstract class VortexTrapTag extends DamagingTrapTag { } export class FireSpinTag extends VortexTrapTag { + public override readonly tagType = BattlerTagType.FIRE_SPIN; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.FIRE_SPIN, CommonAnim.FIRE_SPIN, turnCount, MoveId.FIRE_SPIN, sourceId); } } export class WhirlpoolTag extends VortexTrapTag { + public override readonly tagType = BattlerTagType.WHIRLPOOL; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.WHIRLPOOL, CommonAnim.WHIRLPOOL, turnCount, MoveId.WHIRLPOOL, sourceId); } } export class ClampTag extends DamagingTrapTag { + public override readonly tagType = BattlerTagType.CLAMP; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.CLAMP, CommonAnim.CLAMP, turnCount, MoveId.CLAMP, sourceId); } @@ -1538,6 +1637,7 @@ export class ClampTag extends DamagingTrapTag { } export class SandTombTag extends DamagingTrapTag { + public override readonly tagType = BattlerTagType.SAND_TOMB; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.SAND_TOMB, CommonAnim.SAND_TOMB, turnCount, MoveId.SAND_TOMB, sourceId); } @@ -1551,6 +1651,7 @@ export class SandTombTag extends DamagingTrapTag { } export class MagmaStormTag extends DamagingTrapTag { + public override readonly tagType = BattlerTagType.MAGMA_STORM; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.MAGMA_STORM, CommonAnim.MAGMA_STORM, turnCount, MoveId.MAGMA_STORM, sourceId); } @@ -1563,6 +1664,7 @@ export class MagmaStormTag extends DamagingTrapTag { } export class SnapTrapTag extends DamagingTrapTag { + public override readonly tagType = BattlerTagType.SNAP_TRAP; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.SNAP_TRAP, CommonAnim.SNAP_TRAP, turnCount, MoveId.SNAP_TRAP, sourceId); } @@ -1575,6 +1677,7 @@ export class SnapTrapTag extends DamagingTrapTag { } export class ThunderCageTag extends DamagingTrapTag { + public override readonly tagType = BattlerTagType.THUNDER_CAGE; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.THUNDER_CAGE, CommonAnim.THUNDER_CAGE, turnCount, MoveId.THUNDER_CAGE, sourceId); } @@ -1594,6 +1697,7 @@ export class ThunderCageTag extends DamagingTrapTag { } export class InfestationTag extends DamagingTrapTag { + public override readonly tagType = BattlerTagType.INFESTATION; constructor(turnCount: number, sourceId: number) { super(BattlerTagType.INFESTATION, CommonAnim.INFESTATION, turnCount, MoveId.INFESTATION, sourceId); } @@ -1613,7 +1717,8 @@ export class InfestationTag extends DamagingTrapTag { } export class ProtectedTag extends BattlerTag { - constructor(sourceMove: MoveId, tagType: BattlerTagType = BattlerTagType.PROTECTED) { + public declare readonly tagType: ProtectionBattlerTagType; + constructor(sourceMove: MoveId, tagType: ProtectionBattlerTagType = BattlerTagType.PROTECTED) { super(tagType, BattlerTagLapseType.TURN_END, 0, sourceMove); } @@ -1649,14 +1754,13 @@ export class ProtectedTag extends BattlerTag { } /** Class for `BattlerTag`s that apply some effect when hit by a contact move */ -export class ContactProtectedTag extends ProtectedTag { +export abstract class ContactProtectedTag extends ProtectedTag { /** * Function to call when a contact move hits the pokemon with this tag. * @param _attacker - The pokemon using the contact move * @param _user - The pokemon that is being attacked and has the tag - * @param _move - The move used by the attacker */ - onContact(_attacker: Pokemon, _user: Pokemon) {} + abstract onContact(_attacker: Pokemon, _user: Pokemon): void; /** * Lapse the tag and apply `onContact` if the move makes contact and @@ -1686,22 +1790,16 @@ export class ContactProtectedTag extends ProtectedTag { /** * `BattlerTag` class for moves that block damaging moves damage the enemy if the enemy's move makes contact * Used by {@linkcode MoveId.SPIKY_SHIELD} + * + * @sealed */ export class ContactDamageProtectedTag extends ContactProtectedTag { - private damageRatio: number; + public override readonly tagType = BattlerTagType.SPIKY_SHIELD; + #damageRatio: number; constructor(sourceMove: MoveId, damageRatio: number) { super(sourceMove, BattlerTagType.SPIKY_SHIELD); - this.damageRatio = damageRatio; - } - - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.damageRatio = source.damageRatio; + this.#damageRatio = damageRatio; } /** @@ -1713,7 +1811,7 @@ export class ContactDamageProtectedTag extends ContactProtectedTag { const cancelled = new BooleanHolder(false); applyAbAttrs("BlockNonDirectDamageAbAttr", { pokemon: user, cancelled }); if (!cancelled.value) { - attacker.damageAndUpdate(toDmgValue(attacker.getMaxHp() * (1 / this.damageRatio)), { + attacker.damageAndUpdate(toDmgValue(attacker.getMaxHp() * (1 / this.#damageRatio)), { result: HitResult.INDIRECT, }); } @@ -1721,20 +1819,22 @@ export class ContactDamageProtectedTag extends ContactProtectedTag { } /** Base class for `BattlerTag`s that block damaging moves but not status moves */ -export class DamageProtectedTag extends ContactProtectedTag {} +export abstract class DamageProtectedTag extends ContactProtectedTag { + public declare readonly tagType: DamageProtectedTagType; +} export class ContactSetStatusProtectedTag extends DamageProtectedTag { + public declare readonly tagType: ContactSetStatusProtectedTagType; + /** The status effect applied to attackers */ + #statusEffect: StatusEffect; /** - * @param sourceMove The move that caused the tag to be applied - * @param tagType The type of the tag - * @param statusEffect The status effect to apply to the attacker + * @param sourceMove - The move that caused the tag to be applied + * @param tagType - The type of the tag + * @param statusEffect - The status effect applied to attackers */ - constructor( - sourceMove: MoveId, - tagType: BattlerTagType, - private statusEffect: StatusEffect, - ) { + constructor(sourceMove: MoveId, tagType: ContactSetStatusProtectedTagType, statusEffect: StatusEffect) { super(sourceMove, tagType); + this.#statusEffect = statusEffect; } /** @@ -1743,7 +1843,7 @@ export class ContactSetStatusProtectedTag extends DamageProtectedTag { * @param user - The pokemon that is being attacked and has the tag */ override onContact(attacker: Pokemon, user: Pokemon): void { - attacker.trySetStatus(this.statusEffect, true, user); + attacker.trySetStatus(this.#statusEffect, true, user); } } @@ -1752,24 +1852,15 @@ export class ContactSetStatusProtectedTag extends DamageProtectedTag { * Used by {@linkcode MoveId.KINGS_SHIELD}, {@linkcode MoveId.OBSTRUCT}, {@linkcode MoveId.SILK_TRAP} */ export class ContactStatStageChangeProtectedTag extends DamageProtectedTag { - private stat: BattleStat; - private levels: number; + public declare readonly tagType: ContactStatStageChangeProtectedTagType; + #stat: BattleStat; + #levels: number; - constructor(sourceMove: MoveId, tagType: BattlerTagType, stat: BattleStat, levels: number) { + constructor(sourceMove: MoveId, tagType: ContactStatStageChangeProtectedTagType, stat: BattleStat, levels: number) { super(sourceMove, tagType); - this.stat = stat; - this.levels = levels; - } - - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - override loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.stat = source.stat; - this.levels = source.levels; + this.#stat = stat; + this.#levels = levels; } /** @@ -1782,19 +1873,19 @@ export class ContactStatStageChangeProtectedTag extends DamageProtectedTag { "StatStageChangePhase", attacker.getBattlerIndex(), false, - [this.stat], - this.levels, + [this.#stat], + this.#levels, ); } } /** * `BattlerTag` class for effects that cause the affected Pokemon to survive lethal attacks at 1 HP. - * Used for {@link https://bulbapedia.bulbagarden.net/wiki/Endure_(move) | Endure} and - * Endure Tokens. + * Used for {@link https://bulbapedia.bulbagarden.net/wiki/Endure_(move) | Endure} and endure tokens. */ export class EnduringTag extends BattlerTag { - constructor(tagType: BattlerTagType, lapseType: BattlerTagLapseType, sourceMove: MoveId) { + public declare readonly tagType: EndureTagType; + constructor(tagType: EndureTagType, lapseType: BattlerTagLapseType, sourceMove: MoveId) { super(tagType, lapseType, 0, sourceMove); } @@ -1823,6 +1914,7 @@ export class EnduringTag extends BattlerTag { } export class SturdyTag extends BattlerTag { + public override readonly tagType = BattlerTagType.STURDY; constructor(sourceMove: MoveId) { super(BattlerTagType.STURDY, BattlerTagLapseType.TURN_END, 0, sourceMove); } @@ -1841,7 +1933,8 @@ export class SturdyTag extends BattlerTag { } } -export class PerishSongTag extends BattlerTag { +export class PerishSongTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.PERISH_SONG; constructor(turnCount: number) { super(BattlerTagType.PERISH_SONG, BattlerTagLapseType.TURN_END, turnCount, MoveId.PERISH_SONG, undefined, true); } @@ -1873,6 +1966,7 @@ export class PerishSongTag extends BattlerTag { * @see {@link https://bulbapedia.bulbagarden.net/wiki/Center_of_attention | Center of Attention} */ export class CenterOfAttentionTag extends BattlerTag { + public override readonly tagType = BattlerTagType.CENTER_OF_ATTENTION; public powder: boolean; constructor(sourceMove: MoveId) { @@ -1899,30 +1993,26 @@ export class CenterOfAttentionTag extends BattlerTag { } } -export class AbilityBattlerTag extends BattlerTag { - public ability: AbilityId; - - constructor(tagType: BattlerTagType, ability: AbilityId, lapseType: BattlerTagLapseType, turnCount: number) { - super(tagType, lapseType, turnCount); - - this.ability = ability; +export class AbilityBattlerTag extends SerializableBattlerTag { + public declare readonly tagType: AbilityBattlerTagType; + #ability: AbilityId; + /** The ability that the tag corresponds to */ + public get ability(): AbilityId { + return this.#ability; } - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.ability = source.ability as AbilityId; + constructor(tagType: AbilityBattlerTagType, ability: AbilityId, lapseType: BattlerTagLapseType, turnCount: number) { + super(tagType, lapseType, turnCount); + + this.#ability = ability; } } /** * Tag used by Unburden to double speed - * @extends AbilityBattlerTag */ export class UnburdenTag extends AbilityBattlerTag { + public override readonly tagType = BattlerTagType.UNBURDEN; constructor() { super(BattlerTagType.UNBURDEN, AbilityId.UNBURDEN, BattlerTagLapseType.CUSTOM, 1); } @@ -1935,6 +2025,7 @@ export class UnburdenTag extends AbilityBattlerTag { } export class TruantTag extends AbilityBattlerTag { + public override readonly tagType = BattlerTagType.TRUANT; constructor() { super(BattlerTagType.TRUANT, AbilityId.TRUANT, BattlerTagLapseType.MOVE, 1); } @@ -1969,6 +2060,7 @@ export class TruantTag extends AbilityBattlerTag { } export class SlowStartTag extends AbilityBattlerTag { + public override readonly tagType = BattlerTagType.SLOW_START; constructor() { super(BattlerTagType.SLOW_START, AbilityId.SLOW_START, BattlerTagLapseType.TURN_END, 5); } @@ -2006,18 +2098,19 @@ export class SlowStartTag extends AbilityBattlerTag { } export class HighestStatBoostTag extends AbilityBattlerTag { + public declare readonly tagType: HighestStatBoostTagType; public stat: Stat; public multiplier: number; - constructor(tagType: BattlerTagType, ability: AbilityId) { + constructor(tagType: HighestStatBoostTagType, ability: AbilityId) { super(tagType, ability, BattlerTagLapseType.CUSTOM, 1); } /** * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag + * @param source - An object containing the fields needed to reconstruct this tag. */ - loadTag(source: BattlerTag | any): void { + public override loadTag(source: BaseBattlerTag & Pick): void { super.loadTag(source); this.stat = source.stat as Stat; this.multiplier = source.multiplier; @@ -2065,43 +2158,32 @@ export class HighestStatBoostTag extends AbilityBattlerTag { } } -export class WeatherHighestStatBoostTag extends HighestStatBoostTag implements WeatherBattlerTag { - public weatherTypes: WeatherType[]; - - constructor(tagType: BattlerTagType, ability: AbilityId, ...weatherTypes: WeatherType[]) { - super(tagType, ability); - this.weatherTypes = weatherTypes; +export class WeatherHighestStatBoostTag extends HighestStatBoostTag { + #weatherTypes: WeatherType[]; + public get weatherTypes(): WeatherType[] { + return this.#weatherTypes; } - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.weatherTypes = source.weatherTypes.map(w => w as WeatherType); + constructor(tagType: HighestStatBoostTagType, ability: AbilityId, ...weatherTypes: WeatherType[]) { + super(tagType, ability); + this.#weatherTypes = weatherTypes; } } -export class TerrainHighestStatBoostTag extends HighestStatBoostTag implements TerrainBattlerTag { - public terrainTypes: TerrainType[]; - - constructor(tagType: BattlerTagType, ability: AbilityId, ...terrainTypes: TerrainType[]) { - super(tagType, ability); - this.terrainTypes = terrainTypes; +export class TerrainHighestStatBoostTag extends HighestStatBoostTag { + #terrainTypes: TerrainType[]; + public get terrainTypes(): TerrainType[] { + return this.#terrainTypes; } - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.terrainTypes = source.terrainTypes.map(w => w as TerrainType); + constructor(tagType: HighestStatBoostTagType, ability: AbilityId, ...terrainTypes: TerrainType[]) { + super(tagType, ability); + this.#terrainTypes = terrainTypes; } } -export class SemiInvulnerableTag extends BattlerTag { +export class SemiInvulnerableTag extends SerializableBattlerTag { + public declare readonly tagType: SemiInvulnerableTagType; constructor(tagType: BattlerTagType, turnCount: number, sourceMove: MoveId) { super(tagType, BattlerTagLapseType.MOVE_EFFECT, turnCount, sourceMove); } @@ -2121,22 +2203,16 @@ export class SemiInvulnerableTag extends BattlerTag { } } -export class TypeImmuneTag extends BattlerTag { - public immuneType: PokemonType; +export class TypeImmuneTag extends SerializableBattlerTag { + #immuneType: PokemonType; + public get immuneType(): PokemonType { + return this.#immuneType; + } constructor(tagType: BattlerTagType, sourceMove: MoveId, immuneType: PokemonType, length = 1) { super(tagType, BattlerTagLapseType.TURN_END, length, sourceMove, undefined, true); - this.immuneType = immuneType; - } - - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.immuneType = source.immuneType as PokemonType; + this.#immuneType = immuneType; } } @@ -2174,10 +2250,20 @@ export class FloatingTag extends TypeImmuneTag { } } -export class TypeBoostTag extends BattlerTag { - public boostedType: PokemonType; - public boostValue: number; - public oneUse: boolean; +export class TypeBoostTag extends SerializableBattlerTag { + #boostedType: PokemonType; + #boostValue: number; + #oneUse: boolean; + + public get boostedType(): PokemonType { + return this.#boostedType; + } + public get boostValue(): number { + return this.#boostValue; + } + public get oneUse(): boolean { + return this.#oneUse; + } constructor( tagType: BattlerTagType, @@ -2188,20 +2274,9 @@ export class TypeBoostTag extends BattlerTag { ) { super(tagType, BattlerTagLapseType.TURN_END, 1, sourceMove); - this.boostedType = boostedType; - this.boostValue = boostValue; - this.oneUse = oneUse; - } - - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.boostedType = source.boostedType as PokemonType; - this.boostValue = source.boostValue; - this.oneUse = source.oneUse; + this.#boostedType = boostedType; + this.#boostValue = boostValue; + this.#oneUse = oneUse; } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -2224,7 +2299,7 @@ export class TypeBoostTag extends BattlerTag { } } -export class CritBoostTag extends BattlerTag { +export class CritBoostTag extends SerializableBattlerTag { constructor(tagType: BattlerTagType, sourceMove: MoveId) { super(tagType, BattlerTagLapseType.TURN_END, 1, sourceMove, undefined, true); } @@ -2256,7 +2331,6 @@ export class CritBoostTag extends BattlerTag { /** * Tag for the effects of Dragon Cheer, which boosts the critical hit ratio of the user's allies. - * @extends {CritBoostTag} */ export class DragonCheerTag extends CritBoostTag { /** The types of the user's ally when the tag is added */ @@ -2273,22 +2347,12 @@ export class DragonCheerTag extends CritBoostTag { } } -export class SaltCuredTag extends BattlerTag { - private sourceIndex: number; - +export class SaltCuredTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.SALT_CURED; constructor(sourceId: number) { super(BattlerTagType.SALT_CURED, BattlerTagLapseType.TURN_END, 1, MoveId.SALT_CURE, sourceId); } - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.sourceIndex = source.sourceIndex; - } - onAdd(pokemon: Pokemon): void { const source = this.getSourcePokemon(); if (!source) { @@ -2302,7 +2366,6 @@ export class SaltCuredTag extends BattlerTag { pokemonNameWithAffix: getPokemonNameWithAffix(pokemon), }), ); - this.sourceIndex = source.getBattlerIndex(); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -2338,22 +2401,11 @@ export class SaltCuredTag extends BattlerTag { } } -export class CursedTag extends BattlerTag { - private sourceIndex: number; - +export class CursedTag extends SerializableBattlerTag { constructor(sourceId: number) { super(BattlerTagType.CURSED, BattlerTagLapseType.TURN_END, 1, MoveId.CURSE, sourceId, true); } - /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.sourceIndex = source.sourceIndex; - } - onAdd(pokemon: Pokemon): void { const source = this.getSourcePokemon(); if (!source) { @@ -2362,7 +2414,6 @@ export class CursedTag extends BattlerTag { } super.onAdd(pokemon); - this.sourceIndex = source.getBattlerIndex(); } lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -2392,10 +2443,11 @@ export class CursedTag extends BattlerTag { return ret; } } + /** * Battler tag for attacks that remove a type post use. */ -export class RemovedTypeTag extends BattlerTag { +export class RemovedTypeTag extends SerializableBattlerTag { constructor(tagType: BattlerTagType, lapseType: BattlerTagLapseType, sourceMove: MoveId) { super(tagType, lapseType, 1, sourceMove); } @@ -2405,7 +2457,7 @@ export class RemovedTypeTag extends BattlerTag { * Battler tag for effects that ground the source, allowing Ground-type moves to hit them. * @description `IGNORE_FLYING`: Persistent grounding effects (i.e. from Smack Down and Thousand Waves) */ -export class GroundedTag extends BattlerTag { +export class GroundedTag extends SerializableBattlerTag { constructor(tagType: BattlerTagType, lapseType: BattlerTagLapseType, sourceMove: MoveId) { super(tagType, lapseType, 1, sourceMove); } @@ -2478,15 +2530,16 @@ export class RoostedTag extends BattlerTag { } /** Common attributes of form change abilities that block damage */ -export class FormBlockDamageTag extends BattlerTag { - constructor(tagType: BattlerTagType) { +export class FormBlockDamageTag extends SerializableBattlerTag { + public declare readonly tagType: BattlerTagType.ICE_FACE | BattlerTagType.DISGUISE; + constructor(tagType: BattlerTagType.ICE_FACE | BattlerTagType.DISGUISE) { super(tagType, BattlerTagLapseType.CUSTOM, 1); } /** * Determines if the tag can be added to the Pokémon. - * @param {Pokemon} pokemon The Pokémon to which the tag might be added. - * @returns {boolean} True if the tag can be added, false otherwise. + * @param pokemon - The Pokémon to which the tag might be added. + * @returns `true` if the tag can be added, `false` otherwise. */ canAdd(pokemon: Pokemon): boolean { return pokemon.formIndex === 0; @@ -2508,7 +2561,7 @@ export class FormBlockDamageTag extends BattlerTag { /** * Removes the tag from the Pokémon. * Triggers a form change when the tag is removed. - * @param {Pokemon} pokemon The Pokémon from which the tag is removed. + * @param pokemon - The Pokémon from which the tag is removed. */ onRemove(pokemon: Pokemon): void { super.onRemove(pokemon); @@ -2516,12 +2569,14 @@ export class FormBlockDamageTag extends BattlerTag { globalScene.triggerPokemonFormChange(pokemon, SpeciesFormChangeAbilityTrigger); } } + /** Provides the additional weather-based effects of the Ice Face ability */ export class IceFaceBlockDamageTag extends FormBlockDamageTag { + public override readonly tagType = BattlerTagType.ICE_FACE; /** * Determines if the tag can be added to the Pokémon. - * @param {Pokemon} pokemon The Pokémon to which the tag might be added. - * @returns {boolean} True if the tag can be added, false otherwise. + * @param pokemon - The Pokémon to which the tag might be added. + * @returns `true` if the tag can be added, `false` otherwise. */ canAdd(pokemon: Pokemon): boolean { const weatherType = globalScene.arena.weather?.weatherType; @@ -2534,21 +2589,19 @@ export class IceFaceBlockDamageTag extends FormBlockDamageTag { /** * Battler tag indicating a Tatsugiri with {@link https://bulbapedia.bulbagarden.net/wiki/Commander_(Ability) | Commander} * has entered the tagged Pokemon's mouth. + * @sealed */ -export class CommandedTag extends BattlerTag { - private _tatsugiriFormKey: string; +export class CommandedTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.COMMANDED; + public readonly tatsugiriFormKey: string; constructor(sourceId: number) { super(BattlerTagType.COMMANDED, BattlerTagLapseType.CUSTOM, 0, MoveId.NONE, sourceId); } - public get tatsugiriFormKey(): string { - return this._tatsugiriFormKey; - } - /** Caches the Tatsugiri's form key and sharply boosts the tagged Pokemon's stats */ override onAdd(pokemon: Pokemon): void { - this._tatsugiriFormKey = this.getSourcePokemon()?.getFormKey() ?? "curly"; + (this as Mutable).tatsugiriFormKey = this.getSourcePokemon()?.getFormKey() ?? "curly"; globalScene.phaseManager.unshiftNew( "StatStageChangePhase", pokemon.getBattlerIndex(), @@ -2565,9 +2618,9 @@ export class CommandedTag extends BattlerTag { } } - override loadTag(source: BattlerTag | any): void { + override loadTag(source: NonFunctionProperties): void { super.loadTag(source); - this._tatsugiriFormKey = source._tatsugiriFormKey; + (this as Mutable).tatsugiriFormKey = source.tatsugiriFormKey; } } @@ -2580,8 +2633,10 @@ export class CommandedTag extends BattlerTag { * - Stat changes on removal of (all) stacks. * - Removing stacks decreases DEF and SPDEF, independently, by one stage for each stack that successfully changed * the stat when added. + * @sealed */ -export class StockpilingTag extends BattlerTag { +export class StockpilingTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.STOCKPILING; public stockpiledCount = 0; public statChangeCounts: { [Stat.DEF]: number; [Stat.SPDEF]: number } = { [Stat.DEF]: 0, @@ -2604,7 +2659,7 @@ export class StockpilingTag extends BattlerTag { } }; - loadTag(source: BattlerTag | any): void { + public override loadTag(source: NonFunctionProperties): void { super.loadTag(source); this.stockpiledCount = source.stockpiledCount || 0; this.statChangeCounts = { @@ -2687,10 +2742,10 @@ export class StockpilingTag extends BattlerTag { /** * Battler tag for Gulp Missile used by Cramorant. - * @extends BattlerTag */ -export class GulpMissileTag extends BattlerTag { - constructor(tagType: BattlerTagType, sourceMove: MoveId) { +export class GulpMissileTag extends SerializableBattlerTag { + public declare readonly tagType: BattlerTagType.GULP_MISSILE_ARROKUDA | BattlerTagType.GULP_MISSILE_PIKACHU; + constructor(tagType: BattlerTagType.GULP_MISSILE_ARROKUDA | BattlerTagType.GULP_MISSILE_PIKACHU, sourceMove: MoveId) { super(tagType, BattlerTagLapseType.HIT, 0, sourceMove); } @@ -2729,11 +2784,12 @@ export class GulpMissileTag extends BattlerTag { /** * Gulp Missile's initial form changes are triggered by using Surf and Dive. - * @param {Pokemon} pokemon The Pokemon with Gulp Missile ability. + * @param pokemon - The Pokemon with Gulp Missile ability. * @returns Whether the BattlerTag can be added. */ canAdd(pokemon: Pokemon): boolean { - const isSurfOrDive = [MoveId.SURF, MoveId.DIVE].includes(this.sourceMove); + // Bang here is OK as if sourceMove was undefined, this would just evaluate to false + const isSurfOrDive = [MoveId.SURF, MoveId.DIVE].includes(this.sourceMove!); const isNormalForm = pokemon.formIndex === 0 && !pokemon.getTag(BattlerTagType.GULP_MISSILE_ARROKUDA) && @@ -2755,52 +2811,46 @@ export class GulpMissileTag extends BattlerTag { } /** - * Tag that makes the target drop all of it type immunities + * Tag that makes the target drop the immunities granted by a particular type * and all accuracy checks ignore its evasiveness stat. * * Applied by moves: {@linkcode MoveId.ODOR_SLEUTH | Odor Sleuth}, * {@linkcode MoveId.MIRACLE_EYE | Miracle Eye} and {@linkcode MoveId.FORESIGHT | Foresight}. * - * @extends BattlerTag * @see {@linkcode ignoreImmunity} */ -export class ExposedTag extends BattlerTag { - private defenderType: PokemonType; - private allowedTypes: PokemonType[]; +export class ExposedTag extends SerializableBattlerTag { + public declare readonly tagType: BattlerTagType.IGNORE_DARK | BattlerTagType.IGNORE_GHOST; + #defenderType: PokemonType; + #allowedTypes: readonly PokemonType[]; - constructor(tagType: BattlerTagType, sourceMove: MoveId, defenderType: PokemonType, allowedTypes: PokemonType[]) { + constructor( + tagType: BattlerTagType.IGNORE_DARK | BattlerTagType.IGNORE_GHOST, + sourceMove: MoveId, + defenderType: PokemonType, + allowedTypes: PokemonType[], + ) { super(tagType, BattlerTagLapseType.CUSTOM, 1, sourceMove); - this.defenderType = defenderType; - this.allowedTypes = allowedTypes; + this.#defenderType = defenderType; + this.#allowedTypes = allowedTypes; } /** - * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag - */ - loadTag(source: BattlerTag | any): void { - super.loadTag(source); - this.defenderType = source.defenderType as PokemonType; - this.allowedTypes = source.allowedTypes as PokemonType[]; - } - - /** - * @param types {@linkcode PokemonType} of the defending Pokemon - * @param moveType {@linkcode PokemonType} of the move targetting it + * @param type - The defending type to check against + * @param moveType - The pokemon type of the move being used * @returns `true` if the move should be allowed to target the defender. */ ignoreImmunity(type: PokemonType, moveType: PokemonType): boolean { - return type === this.defenderType && this.allowedTypes.includes(moveType); + return type === this.#defenderType && this.#allowedTypes.includes(moveType); } } /** * Tag that prevents HP recovery from held items and move effects. It also blocks the usage of recovery moves. * Applied by moves: {@linkcode MoveId.HEAL_BLOCK | Heal Block (5 turns)}, {@linkcode MoveId.PSYCHIC_NOISE | Psychic Noise (2 turns)} - * - * @extends MoveRestrictionBattlerTag */ export class HealBlockTag extends MoveRestrictionBattlerTag { + public override readonly tagType = BattlerTagType.HEAL_BLOCK; constructor(turnCount: number, sourceMove: MoveId) { super( BattlerTagType.HEAL_BLOCK, @@ -2818,7 +2868,7 @@ export class HealBlockTag extends MoveRestrictionBattlerTag { /** * Checks if a move is disabled under Heal Block - * @param {MoveId} move {@linkcode MoveId} the move ID + * @param move - {@linkcode MoveId | ID} of the move being used * @returns `true` if the move has a TRIAGE_MOVE flag and is a status move */ override isMoveRestricted(move: MoveId): boolean { @@ -2828,9 +2878,9 @@ export class HealBlockTag extends MoveRestrictionBattlerTag { /** * Checks if a move is disabled under Heal Block because of its choice of target * Implemented b/c of Pollen Puff - * @param {MoveId} move {@linkcode MoveId} the move ID - * @param {Pokemon} user {@linkcode Pokemon} the move user - * @param {Pokemon} target {@linkcode Pokemon} the target of the move + * @param move - {@linkcode MoveId | ID} of the move being used + * @param user - The pokemon using the move + * @param target - The target of the move * @returns `true` if the move cannot be used because the target is an ally */ override isMoveTargetRestricted(move: MoveId, user: Pokemon, target: Pokemon) { @@ -2851,10 +2901,9 @@ export class HealBlockTag extends MoveRestrictionBattlerTag { } /** - * @override - * @param {Pokemon} pokemon {@linkcode Pokemon} attempting to use the restricted move - * @param {MoveId} move {@linkcode MoveId} ID of the move being interrupted - * @returns {string} text to display when the move is interrupted + * @param pokemon - {@linkcode Pokemon} attempting to use the restricted move + * @param move - {@linkcode MoveId | ID} of the move being interrupted + * @returns Text to display when the move is interrupted */ override interruptedText(pokemon: Pokemon, move: MoveId): string { return i18next.t("battle:moveDisabledHealBlock", { @@ -2880,17 +2929,17 @@ export class HealBlockTag extends MoveRestrictionBattlerTag { /** * Tag that doubles the type effectiveness of Fire-type moves. - * @extends BattlerTag */ -export class TarShotTag extends BattlerTag { +export class TarShotTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.TAR_SHOT; constructor() { super(BattlerTagType.TAR_SHOT, BattlerTagLapseType.CUSTOM, 0); } /** * If the Pokemon is terastallized, the tag cannot be added. - * @param {Pokemon} pokemon the {@linkcode Pokemon} to which the tag is added - * @returns whether the tag is applied + * @param pokemon - The pokemon to check + * @returns Whether the tag can be added */ override canAdd(pokemon: Pokemon): boolean { return !pokemon.isTerastallized; @@ -2910,6 +2959,7 @@ export class TarShotTag extends BattlerTag { * While this tag is in effect, the afflicted Pokemon's moves are changed to Electric type. */ export class ElectrifiedTag extends BattlerTag { + public override readonly tagType = BattlerTagType.ELECTRIFIED; constructor() { super(BattlerTagType.ELECTRIFIED, BattlerTagLapseType.TURN_END, 1, MoveId.ELECTRIFY); } @@ -2928,7 +2978,8 @@ export class ElectrifiedTag extends BattlerTag { * Battler Tag that keeps track of how many times the user has Autotomized * Each count of Autotomization reduces the weight by 100kg */ -export class AutotomizedTag extends BattlerTag { +export class AutotomizedTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.AUTOTOMIZED; public autotomizeCount = 0; constructor(sourceMove: MoveId = MoveId.AUTOTOMIZE) { super(BattlerTagType.AUTOTOMIZED, BattlerTagLapseType.CUSTOM, 1, sourceMove); @@ -2954,20 +3005,45 @@ export class AutotomizedTag extends BattlerTag { onOverlap(pokemon: Pokemon): void { this.onAdd(pokemon); } + + public override loadTag(source: NonFunctionProperties): void { + super.loadTag(source); + this.autotomizeCount = source.autotomizeCount; + } } /** * Tag implementing the {@link https://bulbapedia.bulbagarden.net/wiki/Substitute_(doll)#Effect | Substitute Doll} effect, * for use with the moves Substitute and Shed Tail. Pokemon with this tag deflect most forms of received attack damage * onto the tag. This tag also grants immunity to most Status moves and several move effects. + * + * @sealed */ -export class SubstituteTag extends BattlerTag { +export class SubstituteTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.SUBSTITUTE; /** The substitute's remaining HP. If HP is depleted, the Substitute fades. */ public hp: number; + + //#region non-serializable properties /** A reference to the sprite representing the Substitute doll */ - public sprite: Phaser.GameObjects.Sprite; + #sprite: Phaser.GameObjects.Sprite; + /** A reference to the sprite representing the Substitute doll */ + public get sprite(): Phaser.GameObjects.Sprite { + return this.#sprite; + } + public set sprite(value: Phaser.GameObjects.Sprite) { + this.#sprite = value; + } /** Is the source Pokemon "in focus," i.e. is it fully visible on the field? */ - public sourceInFocus: boolean; + #sourceInFocus: boolean; + /** Is the source Pokemon "in focus," i.e. is it fully visible on the field? */ + public get sourceInFocus(): boolean { + return this.#sourceInFocus; + } + public set sourceInFocus(value: boolean) { + this.#sourceInFocus = value; + } + //#endregion non-serializable properties constructor(sourceMove: MoveId, sourceId: number) { super( @@ -3078,9 +3154,9 @@ export class SubstituteTag extends BattlerTag { /** * When given a battler tag or json representing one, load the data for it. - * @param {BattlerTag | any} source A battler tag + * @param source - An object containing the necessary properties to load the tag */ - loadTag(source: BattlerTag | any): void { + public override loadTag(source: BaseBattlerTag & Pick): void { super.loadTag(source); this.hp = source.hp; } @@ -3093,6 +3169,7 @@ export class SubstituteTag extends BattlerTag { * Currently used only in MysteryEncounters to provide start of fight stat buffs. */ export class MysteryEncounterPostSummonTag extends BattlerTag { + public override readonly tagType = BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON; constructor() { super(BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON, BattlerTagLapseType.CUSTOM, 1); } @@ -3126,15 +3203,11 @@ export class MysteryEncounterPostSummonTag extends BattlerTag { * Torment does not interrupt the move if the move is performed consecutively in the same turn and right after Torment is applied */ export class TormentTag extends MoveRestrictionBattlerTag { + public override readonly tagType = BattlerTagType.TORMENT; constructor(sourceId: number) { super(BattlerTagType.TORMENT, BattlerTagLapseType.AFTER_MOVE, 1, MoveId.TORMENT, sourceId); } - /** - * Adds the battler tag to the target Pokemon and defines the private class variable 'target' - * 'Target' is used to track the Pokemon's current status - * @param {Pokemon} pokemon the Pokemon tormented - */ override onAdd(pokemon: Pokemon) { super.onAdd(pokemon); globalScene.phaseManager.queueMessage( @@ -3147,7 +3220,7 @@ export class TormentTag extends MoveRestrictionBattlerTag { /** * Torment only ends when the affected Pokemon leaves the battle field - * @param {Pokemon} pokemon the Pokemon under the effects of Torment + * @param pokemon - The Pokemon under the effects of Torment * @param _tagType * @returns `true` if still present | `false` if not */ @@ -3156,8 +3229,8 @@ export class TormentTag extends MoveRestrictionBattlerTag { } /** - * This checks if the current move used is identical to the last used move with a {@linkcode MoveResult} of `SUCCESS`/`MISS` - * @param {MoveId} move the move under investigation + * Check if the current move used is identical to the last used move with a {@linkcode MoveResult} of `SUCCESS`/`MISS` + * @param move - The move under investigation * @returns `true` if there is valid consecutive usage | `false` if the moves are different from each other */ public override isMoveRestricted(move: MoveId, user: Pokemon): boolean { @@ -3189,6 +3262,7 @@ export class TormentTag extends MoveRestrictionBattlerTag { * The tag is removed after 4 turns. */ export class TauntTag extends MoveRestrictionBattlerTag { + public override readonly tagType = BattlerTagType.TAUNT; constructor() { super(BattlerTagType.TAUNT, [BattlerTagLapseType.PRE_MOVE, BattlerTagLapseType.AFTER_MOVE], 4, MoveId.TAUNT); } @@ -3214,8 +3288,8 @@ export class TauntTag extends MoveRestrictionBattlerTag { } /** - * Checks if a move is a status move and determines its restriction status on that basis - * @param {MoveId} move the move under investigation + * Check if a move is a status move and determines its restriction status on that basis + * @param move - The move under investigation * @returns `true` if the move is a status move */ override isMoveRestricted(move: MoveId): boolean { @@ -3243,6 +3317,7 @@ export class TauntTag extends MoveRestrictionBattlerTag { * The tag is only removed when the source-user is removed from the field. */ export class ImprisonTag extends MoveRestrictionBattlerTag { + public override readonly tagType = BattlerTagType.IMPRISON; constructor(sourceId: number) { super( BattlerTagType.IMPRISON, @@ -3255,8 +3330,7 @@ export class ImprisonTag extends MoveRestrictionBattlerTag { /** * Checks if the source of Imprison is still active - * @override - * @param pokemon The pokemon this tag is attached to + * @param pokemon - The pokemon this tag is attached to * @returns `true` if the source is still active */ public override lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType): boolean { @@ -3273,8 +3347,7 @@ export class ImprisonTag extends MoveRestrictionBattlerTag { /** * Checks if the source of the tag has the parameter move in its moveset and that the source is still active - * @override - * @param {MoveId} move the move under investigation + * @param move - The move under investigation * @returns `false` if either condition is not met */ public override isMoveRestricted(move: MoveId, _user: Pokemon): boolean { @@ -3306,7 +3379,8 @@ export class ImprisonTag extends MoveRestrictionBattlerTag { * For three turns, starting from the turn of hit, at the end of each turn, the target Pokemon's speed will decrease by 1. * The tag can also expire by taking the target Pokemon off the field, or the Pokemon that originally used the move. */ -export class SyrupBombTag extends BattlerTag { +export class SyrupBombTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.SYRUP_BOMB; constructor(sourceId: number) { super(BattlerTagType.SYRUP_BOMB, BattlerTagLapseType.TURN_END, 3, MoveId.SYRUP_BOMB, sourceId); } @@ -3368,7 +3442,8 @@ export class SyrupBombTag extends BattlerTag { * The effects of Telekinesis can be baton passed to a teammate. * @see {@link https://bulbapedia.bulbagarden.net/wiki/Telekinesis_(move) | MoveId.TELEKINESIS} */ -export class TelekinesisTag extends BattlerTag { +export class TelekinesisTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.TELEKINESIS; constructor(sourceMove: MoveId) { super( BattlerTagType.TELEKINESIS, @@ -3391,9 +3466,9 @@ export class TelekinesisTag extends BattlerTag { /** * Tag that swaps the user's base ATK stat with its base DEF stat. - * @extends BattlerTag */ -export class PowerTrickTag extends BattlerTag { +export class PowerTrickTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.POWER_TRICK; constructor(sourceMove: MoveId, sourceId: number) { super(BattlerTagType.POWER_TRICK, BattlerTagLapseType.CUSTOM, 0, sourceMove, sourceId, true); } @@ -3418,7 +3493,7 @@ export class PowerTrickTag extends BattlerTag { /** * Removes the Power Trick tag and reverts any stat changes if the tag is already applied. - * @param {Pokemon} pokemon The {@linkcode Pokemon} that already has the Power Trick tag. + * @param pokemon - The {@linkcode Pokemon} that already has the Power Trick tag. */ onOverlap(pokemon: Pokemon): void { pokemon.removeTag(this.tagType); @@ -3426,7 +3501,7 @@ export class PowerTrickTag extends BattlerTag { /** * Swaps the user's base ATK stat with its base DEF stat. - * @param {Pokemon} pokemon The {@linkcode Pokemon} whose stats will be swapped. + * @param pokemon - The {@linkcode Pokemon} whose stats will be swapped. */ swapStat(pokemon: Pokemon): void { const temp = pokemon.getStat(Stat.ATK, false); @@ -3440,7 +3515,8 @@ export class PowerTrickTag extends BattlerTag { * If this tag is active when the bearer faints from an opponent's move, the tag reduces that move's PP to 0. * Otherwise, it lapses when the bearer makes another move. */ -export class GrudgeTag extends BattlerTag { +export class GrudgeTag extends SerializableBattlerTag { + public override readonly tagType = BattlerTagType.GRUDGE; constructor() { super(BattlerTagType.GRUDGE, [BattlerTagLapseType.CUSTOM, BattlerTagLapseType.PRE_MOVE], 1, MoveId.GRUDGE); } @@ -3458,7 +3534,7 @@ export class GrudgeTag extends BattlerTag { * Activates Grudge's special effect on the attacking Pokemon and lapses the tag. * @param pokemon * @param lapseType - * @param sourcePokemon {@linkcode Pokemon} the source of the move that fainted the tag's bearer + * @param sourcePokemon - The source of the move that fainted the tag's bearer * @returns `false` if Grudge activates its effect or lapses */ override lapse(pokemon: Pokemon, lapseType: BattlerTagLapseType, sourcePokemon?: Pokemon): boolean { @@ -3486,6 +3562,7 @@ export class GrudgeTag extends BattlerTag { * Tag used to heal the user of Psycho Shift of its status effect if Psycho Shift succeeds in transferring its status effect to the target Pokemon */ export class PsychoShiftTag extends BattlerTag { + public override readonly tagType = BattlerTagType.PSYCHO_SHIFT; constructor() { super(BattlerTagType.PSYCHO_SHIFT, BattlerTagLapseType.AFTER_MOVE, 1, MoveId.PSYCHO_SHIFT); } @@ -3510,6 +3587,7 @@ export class PsychoShiftTag extends BattlerTag { * Tag associated with the move Magic Coat. */ export class MagicCoatTag extends BattlerTag { + public override readonly tagType = BattlerTagType.MAGIC_COAT; constructor() { super(BattlerTagType.MAGIC_COAT, BattlerTagLapseType.TURN_END, 1, MoveId.MAGIC_COAT); } @@ -3729,19 +3807,18 @@ export function getBattlerTag( return new PsychoShiftTag(); case BattlerTagType.MAGIC_COAT: return new MagicCoatTag(); - case BattlerTagType.NONE: - default: - return new BattlerTag(tagType, BattlerTagLapseType.CUSTOM, turnCount, sourceMove, sourceId); } } /** * When given a battler tag or json representing one, creates an actual BattlerTag object with the same data. - * @param {BattlerTag | any} source A battler tag - * @return {BattlerTag} The valid battler tag + * @param source - An object containing the data necessary to reconstruct the BattlerTag. + * @returns The valid battler tag */ -export function loadBattlerTag(source: BattlerTag | any): BattlerTag { - const tag = getBattlerTag(source.tagType, source.turnCount, source.sourceMove, source.sourceId); +export function loadBattlerTag(source: SerializableBattlerTag): BattlerTag { + // TODO: Remove this bang by fixing the signature of `getBattlerTag` + // to allow undefined sourceIds and sourceMoves (with appropriate fallback for tags that require it) + const tag = getBattlerTag(source.tagType, source.turnCount, source.sourceMove!, source.sourceId!); tag.loadTag(source); return tag; } @@ -3749,8 +3826,8 @@ export function loadBattlerTag(source: BattlerTag | any): BattlerTag { /** * Helper function to verify that the current phase is a MoveEffectPhase and provide quick access to commonly used fields * - * @param _pokemon {@linkcode Pokemon} The Pokémon used to access the current phase - * @returns null if current phase is not MoveEffectPhase, otherwise Object containing the {@linkcode MoveEffectPhase}, and its + * @param _pokemon - The Pokémon used to access the current phase (unused) + * @returns `null` if current phase is not MoveEffectPhase, otherwise Object containing the {@linkcode MoveEffectPhase}, and its * corresponding {@linkcode Move} and user {@linkcode Pokemon} */ function getMoveEffectPhaseData(_pokemon: Pokemon): { phase: MoveEffectPhase; attacker: Pokemon; move: Move } | null { @@ -3764,3 +3841,104 @@ function getMoveEffectPhaseData(_pokemon: Pokemon): { phase: MoveEffectPhase; at } return null; } + +/** + * Map from {@linkcode BattlerTagType} to the corresponding {@linkcode BattlerTag} class. + */ +export type BattlerTagTypeMap = { + [BattlerTagType.RECHARGING]: RechargingTag; + [BattlerTagType.SHELL_TRAP]: ShellTrapTag; + [BattlerTagType.FLINCHED]: FlinchedTag; + [BattlerTagType.INTERRUPTED]: InterruptedTag; + [BattlerTagType.CONFUSED]: ConfusedTag; + [BattlerTagType.INFATUATED]: InfatuatedTag; + [BattlerTagType.SEEDED]: SeedTag; + [BattlerTagType.POWDER]: PowderTag; + [BattlerTagType.NIGHTMARE]: NightmareTag; + [BattlerTagType.FRENZY]: FrenzyTag; + [BattlerTagType.CHARGING]: BattlerTag; + [BattlerTagType.ENCORE]: EncoreTag; + [BattlerTagType.HELPING_HAND]: HelpingHandTag; + [BattlerTagType.INGRAIN]: IngrainTag; + [BattlerTagType.AQUA_RING]: AquaRingTag; + [BattlerTagType.DROWSY]: DrowsyTag; + [BattlerTagType.TRAPPED]: TrappedTag; + [BattlerTagType.NO_RETREAT]: NoRetreatTag; + [BattlerTagType.BIND]: BindTag; + [BattlerTagType.WRAP]: WrapTag; + [BattlerTagType.FIRE_SPIN]: FireSpinTag; + [BattlerTagType.WHIRLPOOL]: WhirlpoolTag; + [BattlerTagType.CLAMP]: ClampTag; + [BattlerTagType.SAND_TOMB]: SandTombTag; + [BattlerTagType.MAGMA_STORM]: MagmaStormTag; + [BattlerTagType.SNAP_TRAP]: SnapTrapTag; + [BattlerTagType.THUNDER_CAGE]: ThunderCageTag; + [BattlerTagType.INFESTATION]: InfestationTag; + [BattlerTagType.PROTECTED]: ProtectedTag; + [BattlerTagType.SPIKY_SHIELD]: ContactDamageProtectedTag; + [BattlerTagType.KINGS_SHIELD]: ContactStatStageChangeProtectedTag; + [BattlerTagType.OBSTRUCT]: ContactStatStageChangeProtectedTag; + [BattlerTagType.SILK_TRAP]: ContactStatStageChangeProtectedTag; + [BattlerTagType.BANEFUL_BUNKER]: ContactSetStatusProtectedTag; + [BattlerTagType.BURNING_BULWARK]: ContactSetStatusProtectedTag; + [BattlerTagType.ENDURING]: EnduringTag; + [BattlerTagType.ENDURE_TOKEN]: EnduringTag; + [BattlerTagType.STURDY]: SturdyTag; + [BattlerTagType.PERISH_SONG]: PerishSongTag; + [BattlerTagType.CENTER_OF_ATTENTION]: CenterOfAttentionTag; + [BattlerTagType.TRUANT]: TruantTag; + [BattlerTagType.SLOW_START]: SlowStartTag; + [BattlerTagType.PROTOSYNTHESIS]: WeatherHighestStatBoostTag; + [BattlerTagType.QUARK_DRIVE]: TerrainHighestStatBoostTag; + [BattlerTagType.FLYING]: SemiInvulnerableTag; + [BattlerTagType.UNDERGROUND]: SemiInvulnerableTag; + [BattlerTagType.UNDERWATER]: SemiInvulnerableTag; + [BattlerTagType.HIDDEN]: SemiInvulnerableTag; + [BattlerTagType.FIRE_BOOST]: TypeBoostTag; + [BattlerTagType.CRIT_BOOST]: CritBoostTag; + [BattlerTagType.DRAGON_CHEER]: DragonCheerTag; + [BattlerTagType.ALWAYS_CRIT]: BattlerTag; + [BattlerTagType.IGNORE_ACCURACY]: BattlerTag; + [BattlerTagType.ALWAYS_GET_HIT]: BattlerTag; + [BattlerTagType.RECEIVE_DOUBLE_DAMAGE]: BattlerTag; + [BattlerTagType.BYPASS_SLEEP]: BattlerTag; + [BattlerTagType.IGNORE_FLYING]: GroundedTag; + [BattlerTagType.ROOSTED]: RoostedTag; + [BattlerTagType.BURNED_UP]: RemovedTypeTag; + [BattlerTagType.DOUBLE_SHOCKED]: RemovedTypeTag; + [BattlerTagType.SALT_CURED]: SaltCuredTag; + [BattlerTagType.CURSED]: CursedTag; + [BattlerTagType.CHARGED]: TypeBoostTag; + [BattlerTagType.FLOATING]: FloatingTag; + [BattlerTagType.MINIMIZED]: MinimizeTag; + [BattlerTagType.DESTINY_BOND]: DestinyBondTag; + [BattlerTagType.ICE_FACE]: IceFaceBlockDamageTag; + [BattlerTagType.DISGUISE]: FormBlockDamageTag; + [BattlerTagType.COMMANDED]: CommandedTag; + [BattlerTagType.STOCKPILING]: StockpilingTag; + [BattlerTagType.OCTOLOCK]: OctolockTag; + [BattlerTagType.DISABLED]: DisabledTag; + [BattlerTagType.IGNORE_GHOST]: ExposedTag; + [BattlerTagType.IGNORE_DARK]: ExposedTag; + [BattlerTagType.GULP_MISSILE_ARROKUDA]: GulpMissileTag; + [BattlerTagType.GULP_MISSILE_PIKACHU]: GulpMissileTag; + [BattlerTagType.BEAK_BLAST_CHARGING]: BeakBlastChargingTag; + [BattlerTagType.TAR_SHOT]: TarShotTag; + [BattlerTagType.ELECTRIFIED]: ElectrifiedTag; + [BattlerTagType.THROAT_CHOPPED]: ThroatChoppedTag; + [BattlerTagType.GORILLA_TACTICS]: GorillaTacticsTag; + [BattlerTagType.UNBURDEN]: UnburdenTag; + [BattlerTagType.SUBSTITUTE]: SubstituteTag; + [BattlerTagType.AUTOTOMIZED]: AutotomizedTag; + [BattlerTagType.MYSTERY_ENCOUNTER_POST_SUMMON]: MysteryEncounterPostSummonTag; + [BattlerTagType.HEAL_BLOCK]: HealBlockTag; + [BattlerTagType.TORMENT]: TormentTag; + [BattlerTagType.TAUNT]: TauntTag; + [BattlerTagType.IMPRISON]: ImprisonTag; + [BattlerTagType.SYRUP_BOMB]: SyrupBombTag; + [BattlerTagType.TELEKINESIS]: TelekinesisTag; + [BattlerTagType.POWER_TRICK]: PowerTrickTag; + [BattlerTagType.GRUDGE]: GrudgeTag; + [BattlerTagType.PSYCHO_SHIFT]: PsychoShiftTag; + [BattlerTagType.MAGIC_COAT]: MagicCoatTag; +}; diff --git a/src/data/moves/move.ts b/src/data/moves/move.ts index 965ab23a692..bde5f2977d8 100644 --- a/src/data/moves/move.ts +++ b/src/data/moves/move.ts @@ -25,6 +25,7 @@ import { getBerryEffectFunc } from "#data/berry"; import { applyChallenges } from "#data/challenge"; import { allAbilities, allMoves } from "#data/data-lists"; import { SpeciesFormChangeRevertWeatherFormTrigger } from "#data/form-change-triggers"; +import { DelayedAttackTag } from "#data/positional-tags/positional-tag"; import { getNonVolatileStatusEffects, getStatusEffectHealText, @@ -54,6 +55,7 @@ import { MoveFlags } from "#enums/move-flags"; import { MoveTarget } from "#enums/move-target"; import { MultiHitType } from "#enums/multi-hit-type"; import { PokemonType } from "#enums/pokemon-type"; +import { PositionalTagType } from "#enums/positional-tag-type"; import { SpeciesId } from "#enums/species-id"; import { BATTLE_STATS, @@ -423,9 +425,8 @@ export abstract class Move implements Localizable { /** * Sets the {@linkcode MoveFlags.MAKES_CONTACT} flag for the calling Move - * @param setFlag Default `true`, set to `false` if the move doesn't make contact - * @see {@linkcode AbilityId.STATIC} - * @returns The {@linkcode Move} that called this function + * @param setFlag - Whether the move should make contact; default `true` + * @returns `this` */ makesContact(setFlag: boolean = true): this { this.setFlag(MoveFlags.MAKES_CONTACT, setFlag); @@ -3123,54 +3124,110 @@ export class OverrideMoveEffectAttr extends MoveAttr { * Its sole purpose is to ensure that typescript is able to properly narrow when the `is` method is called. */ declare private _: never; - override apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { + /** + * Apply the move attribute to override other effects of this move. + * @param user - The {@linkcode Pokemon} using the move + * @param target - The {@linkcode Pokemon} targeted by the move + * @param move - The {@linkcode Move} being used + * @param args - + * `[0]`: A {@linkcode BooleanHolder} containing whether move effects were successfully overridden; should be set to `true` on success \ + * `[1]`: The {@linkcode MoveUseMode} dictating how this move was used. + * @returns `true` if the move effect was successfully overridden. + */ + public override apply(_user: Pokemon, _target: Pokemon, _move: Move, _args: [overridden: BooleanHolder, useMode: MoveUseMode]): boolean { return true; } } +/** Abstract class for moves that add {@linkcode PositionalTag}s to the field. */ +abstract class AddPositionalTagAttr extends OverrideMoveEffectAttr { + protected abstract readonly tagType: PositionalTagType; + + public override getCondition(): MoveConditionFunc { + // Check the arena if another similar positional tag is active and affecting the same slot + return (_user, target, move) => globalScene.arena.positionalTagManager.canAddTag(this.tagType, target.getBattlerIndex()) + } +} + /** - * Attack Move that doesn't hit the turn it is played and doesn't allow for multiple - * uses on the same target. Examples are Future Sight or Doom Desire. - * @extends OverrideMoveEffectAttr - * @param tagType The {@linkcode ArenaTagType} that will be placed on the field when the move is used - * @param chargeAnim The {@linkcode ChargeAnim | Charging Animation} used for the move - * @param chargeText The text to display when the move is used + * Attribute to implement delayed attacks, such as {@linkcode MoveId.FUTURE_SIGHT} or {@linkcode MoveId.DOOM_DESIRE}. + * Delays the attack's effect with a {@linkcode DelayedAttackTag}, + * activating against the given slot after the given turn count has elapsed. */ export class DelayedAttackAttr extends OverrideMoveEffectAttr { - public tagType: ArenaTagType; public chargeAnim: ChargeAnim; private chargeText: string; - constructor(tagType: ArenaTagType, chargeAnim: ChargeAnim, chargeText: string) { + /** + * @param chargeAnim - The {@linkcode ChargeAnim | charging animation} used for the move's charging phase. + * @param chargeKey - The `i18next` locales **key** to show when the delayed attack is used. + * In the displayed text, `{{pokemonName}}` will be populated with the user's name. + */ + constructor(chargeAnim: ChargeAnim, chargeKey: string) { super(); - this.tagType = tagType; this.chargeAnim = chargeAnim; - this.chargeText = chargeText; + this.chargeText = chargeKey; } - apply(user: Pokemon, target: Pokemon, move: Move, args: any[]): boolean { - // Edge case for the move applied on a pokemon that has fainted - if (!target) { - return true; + public override apply(user: Pokemon, target: Pokemon, move: Move, args: [overridden: BooleanHolder, useMode: MoveUseMode]): boolean { + const useMode = args[1]; + if (useMode === MoveUseMode.DELAYED_ATTACK) { + // don't trigger if already queueing an indirect attack + return false; } - const overridden = args[0] as BooleanHolder; - const virtual = args[1] as boolean; + const overridden = args[0]; + overridden.value = true; - if (!virtual) { - overridden.value = true; - globalScene.phaseManager.unshiftNew("MoveAnimPhase", new MoveChargeAnim(this.chargeAnim, move.id, user)); - globalScene.phaseManager.queueMessage(this.chargeText.replace("{TARGET}", getPokemonNameWithAffix(target)).replace("{USER}", getPokemonNameWithAffix(user))); - user.pushMoveHistory({ move: move.id, targets: [ target.getBattlerIndex() ], result: MoveResult.OTHER, useMode: MoveUseMode.NORMAL }); - const side = target.isPlayer() ? ArenaTagSide.PLAYER : ArenaTagSide.ENEMY; - globalScene.arena.addTag(this.tagType, 3, move.id, user.id, side, false, target.getBattlerIndex()); - } else { - globalScene.phaseManager.queueMessage(i18next.t("moveTriggers:tookMoveAttack", { pokemonName: getPokemonNameWithAffix(globalScene.getPokemonById(target.id) ?? undefined), moveName: move.name })); - } + // Display the move animation to foresee an attack + globalScene.phaseManager.unshiftNew("MoveAnimPhase", new MoveChargeAnim(this.chargeAnim, move.id, user)); + globalScene.phaseManager.queueMessage( + i18next.t( + this.chargeText, + { pokemonName: getPokemonNameWithAffix(user) } + ) + ) + user.pushMoveHistory({move: move.id, targets: [target.getBattlerIndex()], result: MoveResult.OTHER, useMode, turn: globalScene.currentBattle.turn}) + user.pushMoveHistory({move: move.id, targets: [target.getBattlerIndex()], result: MoveResult.OTHER, useMode, turn: globalScene.currentBattle.turn}) + // Queue up an attack on the given slot. + globalScene.arena.positionalTagManager.addTag({ + tagType: PositionalTagType.DELAYED_ATTACK, + sourceId: user.id, + targetIndex: target.getBattlerIndex(), + sourceMove: move.id, + turnCount: 3 + }) return true; } + + public override getCondition(): MoveConditionFunc { + // Check the arena if another similar attack is active and affecting the same slot + return (_user, target) => globalScene.arena.positionalTagManager.canAddTag(PositionalTagType.DELAYED_ATTACK, target.getBattlerIndex()) + } +} + +/** + * Attribute to queue a {@linkcode WishTag} to activate in 2 turns. + * The tag whill heal + */ +export class WishAttr extends MoveEffectAttr { + public override apply(user: Pokemon, target: Pokemon, _move: Move): boolean { + globalScene.arena.positionalTagManager.addTag({ + tagType: PositionalTagType.WISH, + healHp: toDmgValue(user.getMaxHp() / 2), + targetIndex: target.getBattlerIndex(), + turnCount: 2, + pokemonName: getPokemonNameWithAffix(user), + }); + return true; + } + + public override getCondition(): MoveConditionFunc { + // Check the arena if another wish is active and affecting the same slot + return (_user, target) => globalScene.arena.positionalTagManager.canAddTag(PositionalTagType.WISH, target.getBattlerIndex()) + } } /** @@ -3188,8 +3245,8 @@ export class AwaitCombinedPledgeAttr extends OverrideMoveEffectAttr { * @param user the {@linkcode Pokemon} using this move * @param target n/a * @param move the {@linkcode Move} being used - * @param args - * - [0] a {@linkcode BooleanHolder} indicating whether the move's base + * @param args - + * `[0]`: A {@linkcode BooleanHolder} indicating whether the move's base * effects should be overridden this turn. * @returns `true` if base move effects were overridden; `false` otherwise */ @@ -3576,8 +3633,7 @@ export class CutHpStatStageBoostAttr extends StatStageChangeAttr { /** * Attribute implementing the stat boosting effect of {@link https://bulbapedia.bulbagarden.net/wiki/Order_Up_(move) | Order Up}. * If the user has a Pokemon with {@link https://bulbapedia.bulbagarden.net/wiki/Commander_(Ability) | Commander} in their mouth, - * one of the user's stats are increased by 1 stage, depending on the "commanding" Pokemon's form. This effect does not respect - * effect chance, but Order Up itself may be boosted by Sheer Force. + * one of the user's stats are increased by 1 stage, depending on the "commanding" Pokemon's form. */ export class OrderUpStatBoostAttr extends MoveEffectAttr { constructor() { @@ -9205,9 +9261,12 @@ export function initMoves() { .attr(StatStageChangeAttr, [ Stat.SPDEF ], -1) .ballBombMove(), new AttackMove(MoveId.FUTURE_SIGHT, PokemonType.PSYCHIC, MoveCategory.SPECIAL, 120, 100, 10, -1, 0, 2) - .partial() // cannot be used on multiple Pokemon on the same side in a double battle, hits immediately when called by Metronome/etc, should not apply abilities or held items if user is off the field + .attr(DelayedAttackAttr, ChargeAnim.FUTURE_SIGHT_CHARGING, "moveTriggers:foresawAnAttack") .ignoresProtect() - .attr(DelayedAttackAttr, ArenaTagType.FUTURE_SIGHT, ChargeAnim.FUTURE_SIGHT_CHARGING, i18next.t("moveTriggers:foresawAnAttack", { pokemonName: "{USER}" })), + /* + * Should not apply abilities or held items if user is off the field + */ + .edgeCase(), new AttackMove(MoveId.ROCK_SMASH, PokemonType.FIGHTING, MoveCategory.PHYSICAL, 40, 100, 15, 50, 0, 2) .attr(StatStageChangeAttr, [ Stat.DEF ], -1), new AttackMove(MoveId.WHIRLPOOL, PokemonType.WATER, MoveCategory.SPECIAL, 35, 85, 15, -1, 0, 2) @@ -9228,7 +9287,7 @@ export function initMoves() { new SelfStatusMove(MoveId.STOCKPILE, PokemonType.NORMAL, -1, 20, -1, 0, 3) .condition(user => (user.getTag(StockpilingTag)?.stockpiledCount ?? 0) < 3) .attr(AddBattlerTagAttr, BattlerTagType.STOCKPILING, true), - new AttackMove(MoveId.SPIT_UP, PokemonType.NORMAL, MoveCategory.SPECIAL, -1, -1, 10, -1, 0, 3) + new AttackMove(MoveId.SPIT_UP, PokemonType.NORMAL, MoveCategory.SPECIAL, -1, 100, 10, -1, 0, 3) .condition(hasStockpileStacksCondition) .attr(SpitUpPowerAttr, 100) .attr(RemoveBattlerTagAttr, [ BattlerTagType.STOCKPILING ], true), @@ -9293,8 +9352,8 @@ export function initMoves() { .ignoresSubstitute() .attr(AbilityCopyAttr), new SelfStatusMove(MoveId.WISH, PokemonType.NORMAL, -1, 10, -1, 0, 3) - .triageMove() - .attr(AddArenaTagAttr, ArenaTagType.WISH, 2, true), + .attr(WishAttr) + .triageMove(), new SelfStatusMove(MoveId.ASSIST, PokemonType.NORMAL, -1, 20, -1, 0, 3) .attr(RandomMovesetMoveAttr, invalidAssistMoves, true), new SelfStatusMove(MoveId.INGRAIN, PokemonType.GRASS, -1, 20, -1, 0, 3) @@ -9471,7 +9530,7 @@ export function initMoves() { new AttackMove(MoveId.SAND_TOMB, PokemonType.GROUND, MoveCategory.PHYSICAL, 35, 85, 15, -1, 0, 3) .attr(TrapAttr, BattlerTagType.SAND_TOMB) .makesContact(false), - new AttackMove(MoveId.SHEER_COLD, PokemonType.ICE, MoveCategory.SPECIAL, 200, 20, 5, -1, 0, 3) + new AttackMove(MoveId.SHEER_COLD, PokemonType.ICE, MoveCategory.SPECIAL, 200, 30, 5, -1, 0, 3) .attr(IceNoEffectTypeAttr) .attr(OneHitKOAttr) .attr(SheerColdAccuracyAttr), @@ -9543,9 +9602,12 @@ export function initMoves() { .attr(ConfuseAttr) .pulseMove(), new AttackMove(MoveId.DOOM_DESIRE, PokemonType.STEEL, MoveCategory.SPECIAL, 140, 100, 5, -1, 0, 3) - .partial() // cannot be used on multiple Pokemon on the same side in a double battle, hits immediately when called by Metronome/etc, should not apply abilities or held items if user is off the field + .attr(DelayedAttackAttr, ChargeAnim.DOOM_DESIRE_CHARGING, "moveTriggers:choseDoomDesireAsDestiny") .ignoresProtect() - .attr(DelayedAttackAttr, ArenaTagType.DOOM_DESIRE, ChargeAnim.DOOM_DESIRE_CHARGING, i18next.t("moveTriggers:choseDoomDesireAsDestiny", { pokemonName: "{USER}" })), + /* + * Should not apply abilities or held items if user is off the field + */ + .edgeCase(), new AttackMove(MoveId.PSYCHO_BOOST, PokemonType.PSYCHIC, MoveCategory.SPECIAL, 140, 90, 5, -1, 0, 3) .attr(StatStageChangeAttr, [ Stat.SPATK ], -2, true), new SelfStatusMove(MoveId.ROOST, PokemonType.FLYING, -1, 5, -1, 0, 4) @@ -10393,7 +10455,7 @@ export function initMoves() { .attr(RemoveBattlerTagAttr, [ BattlerTagType.FLYING, BattlerTagType.FLOATING, BattlerTagType.TELEKINESIS ]) .makesContact(false) .target(MoveTarget.ALL_NEAR_ENEMIES), - new AttackMove(MoveId.THOUSAND_WAVES, PokemonType.GROUND, MoveCategory.PHYSICAL, 90, 100, 10, -1, 0, 6) + new AttackMove(MoveId.THOUSAND_WAVES, PokemonType.GROUND, MoveCategory.PHYSICAL, 90, 100, 10, 100, 0, 6) .attr(AddBattlerTagAttr, BattlerTagType.TRAPPED, false, false, 1, 1, true) .makesContact(false) .target(MoveTarget.ALL_NEAR_ENEMIES), @@ -10800,7 +10862,7 @@ export function initMoves() { new SelfStatusMove(MoveId.NO_RETREAT, PokemonType.FIGHTING, -1, 5, -1, 0, 8) .attr(StatStageChangeAttr, [ Stat.ATK, Stat.DEF, Stat.SPATK, Stat.SPDEF, Stat.SPD ], 1, true) .attr(AddBattlerTagAttr, BattlerTagType.NO_RETREAT, true, false) - .condition((user, target, move) => user.getTag(TrappedTag)?.sourceMove !== MoveId.NO_RETREAT), // fails if the user is currently trapped by No Retreat + .condition((user, target, move) => user.getTag(TrappedTag)?.tagType !== BattlerTagType.NO_RETREAT), // fails if the user is currently trapped by No Retreat new StatusMove(MoveId.TAR_SHOT, PokemonType.ROCK, 100, 15, -1, 0, 8) .attr(StatStageChangeAttr, [ Stat.SPD ], -1) .attr(AddBattlerTagAttr, BattlerTagType.TAR_SHOT, false) @@ -10928,7 +10990,8 @@ export function initMoves() { new StatusMove(MoveId.LIFE_DEW, PokemonType.WATER, -1, 10, -1, 0, 8) .attr(HealAttr, 0.25, true, false) .target(MoveTarget.USER_AND_ALLIES) - .ignoresProtect(), + .ignoresProtect() + .triageMove(), new SelfStatusMove(MoveId.OBSTRUCT, PokemonType.DARK, 100, 10, -1, 4, 8) .attr(ProtectAttr, BattlerTagType.OBSTRUCT) .condition(failIfLastCondition), @@ -11006,7 +11069,8 @@ export function initMoves() { new StatusMove(MoveId.JUNGLE_HEALING, PokemonType.GRASS, -1, 10, -1, 0, 8) .attr(HealAttr, 0.25, true, false) .attr(HealStatusEffectAttr, false, getNonVolatileStatusEffects()) - .target(MoveTarget.USER_AND_ALLIES), + .target(MoveTarget.USER_AND_ALLIES) + .triageMove(), new AttackMove(MoveId.WICKED_BLOW, PokemonType.DARK, MoveCategory.PHYSICAL, 75, 100, 5, -1, 0, 8) .attr(CritOnlyAttr) .punchingMove(), @@ -11234,7 +11298,7 @@ export function initMoves() { .makesContact(false), new AttackMove(MoveId.LUMINA_CRASH, PokemonType.PSYCHIC, MoveCategory.SPECIAL, 80, 100, 10, 100, 0, 9) .attr(StatStageChangeAttr, [ Stat.SPDEF ], -2), - new AttackMove(MoveId.ORDER_UP, PokemonType.DRAGON, MoveCategory.PHYSICAL, 80, 100, 10, 100, 0, 9) + new AttackMove(MoveId.ORDER_UP, PokemonType.DRAGON, MoveCategory.PHYSICAL, 80, 100, 10, -1, 0, 9) .attr(OrderUpStatBoostAttr) .makesContact(false), new AttackMove(MoveId.JET_PUNCH, PokemonType.WATER, MoveCategory.PHYSICAL, 60, 100, 15, -1, 1, 9) @@ -11417,7 +11481,7 @@ export function initMoves() { .attr(IvyCudgelTypeAttr) .attr(HighCritAttr) .makesContact(false), - new ChargingAttackMove(MoveId.ELECTRO_SHOT, PokemonType.ELECTRIC, MoveCategory.SPECIAL, 130, 100, 10, 100, 0, 9) + new ChargingAttackMove(MoveId.ELECTRO_SHOT, PokemonType.ELECTRIC, MoveCategory.SPECIAL, 130, 100, 10, -1, 0, 9) .chargeText(i18next.t("moveTriggers:absorbedElectricity", { pokemonName: "{USER}" })) .chargeAttr(StatStageChangeAttr, [ Stat.SPATK ], 1, true) .chargeAttr(WeatherInstantChargeAttr, [ WeatherType.RAIN, WeatherType.HEAVY_RAIN ]), 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 b914927123a..347092fe0b4 100644 --- a/src/data/mystery-encounters/encounters/global-trade-system-encounter.ts +++ b/src/data/mystery-encounters/encounters/global-trade-system-encounter.ts @@ -39,6 +39,7 @@ import { addPokemonDataToDexAndValidateAchievements } from "#mystery-encounters/ import type { MysteryEncounter } from "#mystery-encounters/mystery-encounter"; import { MysteryEncounterBuilder } from "#mystery-encounters/mystery-encounter"; import { MysteryEncounterOptionBuilder } from "#mystery-encounters/mystery-encounter-option"; +import { PartySizeRequirement } from "#mystery-encounters/mystery-encounter-requirements"; import { PokemonData } from "#system/pokemon-data"; import { MusicPreference } from "#system/settings"; import type { OptionSelectItem } from "#ui/abstact-option-select-ui-handler"; @@ -151,7 +152,8 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = MysteryEncounterBuil return true; }) .withOption( - MysteryEncounterOptionBuilder.newOptionWithMode(MysteryEncounterOptionMode.DEFAULT) + MysteryEncounterOptionBuilder.newOptionWithMode(MysteryEncounterOptionMode.DISABLED_OR_DEFAULT) + .withSceneRequirement(new PartySizeRequirement([2, 6], true)) // Requires 2 valid party members .withHasDexProgress(true) .withDialogue({ buttonLabel: `${namespace}:option.1.label`, @@ -257,7 +259,8 @@ export const GlobalTradeSystemEncounter: MysteryEncounter = MysteryEncounterBuil .build(), ) .withOption( - MysteryEncounterOptionBuilder.newOptionWithMode(MysteryEncounterOptionMode.DEFAULT) + MysteryEncounterOptionBuilder.newOptionWithMode(MysteryEncounterOptionMode.DISABLED_OR_DEFAULT) + .withSceneRequirement(new PartySizeRequirement([2, 6], true)) // Requires 2 valid party members .withHasDexProgress(true) .withDialogue({ buttonLabel: `${namespace}:option.2.label`, diff --git a/src/data/pokemon/pokemon-data.ts b/src/data/pokemon/pokemon-data.ts index a2a0138a17a..972d7627bcd 100644 --- a/src/data/pokemon/pokemon-data.ts +++ b/src/data/pokemon/pokemon-data.ts @@ -1,4 +1,5 @@ -import { type BattlerTag, loadBattlerTag } from "#data/battler-tags"; +import type { BattlerTag } from "#data/battler-tags"; +import { loadBattlerTag, SerializableBattlerTag } from "#data/battler-tags"; import { allSpecies } from "#data/data-lists"; import type { Gender } from "#data/gender"; import { PokemonMove } from "#data/moves/pokemon-move"; @@ -187,9 +188,11 @@ export class PokemonSummonData { continue; } - if (key === "tags") { - // load battler tags - this.tags = value.map((t: BattlerTag) => loadBattlerTag(t)); + if (key === "tags" && Array.isArray(value)) { + // load battler tags, discarding any that are not serializable + this.tags = value + .map((t: SerializableBattlerTag) => loadBattlerTag(t)) + .filter((t): t is SerializableBattlerTag => t instanceof SerializableBattlerTag); continue; } this[key] = value; diff --git a/src/data/positional-tags/load-positional-tag.ts b/src/data/positional-tags/load-positional-tag.ts new file mode 100644 index 00000000000..ef3609d93e7 --- /dev/null +++ b/src/data/positional-tags/load-positional-tag.ts @@ -0,0 +1,70 @@ +import { DelayedAttackTag, type PositionalTag, WishTag } from "#data/positional-tags/positional-tag"; +import { PositionalTagType } from "#enums/positional-tag-type"; +import type { ObjectValues } from "#types/type-helpers"; +import type { Constructor } from "#utils/common"; + +/** + * Load the attributes of a {@linkcode PositionalTag}. + * @param tagType - The {@linkcode PositionalTagType} to create + * @param args - The arguments needed to instantize the given tag + * @returns The newly created tag. + * @remarks + * This function does not perform any checking if the added tag is valid. + */ +export function loadPositionalTag({ + tagType, + ...args +}: serializedPosTagMap[T]): posTagInstanceMap[T]; +/** + * Load the attributes of a {@linkcode PositionalTag}. + * @param tag - The {@linkcode SerializedPositionalTag} to instantiate + * @returns The newly created tag. + * @remarks + * This function does not perform any checking if the added tag is valid. + */ +export function loadPositionalTag(tag: SerializedPositionalTag): PositionalTag; +export function loadPositionalTag({ + tagType, + ...rest +}: serializedPosTagMap[T]): posTagInstanceMap[T] { + // Note: We need 2 type assertions here: + // 1 because TS doesn't narrow the type of TagClass correctly based on `T`. + // It converts it into `new (DelayedAttackTag | WishTag) => DelayedAttackTag & WishTag` + const tagClass = posTagConstructorMap[tagType] as new (args: posTagParamMap[T]) => posTagInstanceMap[T]; + // 2 because TS doesn't narrow the type of `rest` correctly + // (from `Omit into `posTagParamMap[T]`) + return new tagClass(rest as unknown as posTagParamMap[T]); +} + +/** Const object mapping tag types to their constructors. */ +const posTagConstructorMap = Object.freeze({ + [PositionalTagType.DELAYED_ATTACK]: DelayedAttackTag, + [PositionalTagType.WISH]: WishTag, +}) satisfies { + // NB: This `satisfies` block ensures that all tag types have corresponding entries in the map. + [k in PositionalTagType]: Constructor; +}; + +/** Type mapping positional tag types to their constructors. */ +type posTagMap = typeof posTagConstructorMap; + +/** Type mapping all positional tag types to their instances. */ +type posTagInstanceMap = { + [k in PositionalTagType]: InstanceType; +}; + +/** Type mapping all positional tag types to their constructors' parameters. */ +type posTagParamMap = { + [k in PositionalTagType]: ConstructorParameters[0]; +}; + +/** + * Type mapping all positional tag types to their constructors' parameters, alongside the `tagType` selector. + * Equivalent to their serialized representations. + */ +export type serializedPosTagMap = { + [k in PositionalTagType]: posTagParamMap[k] & { tagType: k }; +}; + +/** Union type containing all serialized {@linkcode PositionalTag}s. */ +export type SerializedPositionalTag = ObjectValues; diff --git a/src/data/positional-tags/positional-tag-manager.ts b/src/data/positional-tags/positional-tag-manager.ts new file mode 100644 index 00000000000..7bf4d4995c6 --- /dev/null +++ b/src/data/positional-tags/positional-tag-manager.ts @@ -0,0 +1,55 @@ +import { loadPositionalTag } from "#data/positional-tags/load-positional-tag"; +import type { PositionalTag } from "#data/positional-tags/positional-tag"; +import type { BattlerIndex } from "#enums/battler-index"; +import type { PositionalTagType } from "#enums/positional-tag-type"; + +/** A manager for the {@linkcode PositionalTag}s in the arena. */ +export class PositionalTagManager { + /** + * Array containing all pending unactivated {@linkcode PositionalTag}s, + * sorted by order of creation (oldest first). + */ + public tags: PositionalTag[] = []; + + /** + * Add a new {@linkcode PositionalTag} to the arena. + * @remarks + * This function does not perform any checking if the added tag is valid. + */ + public addTag(tag: Parameters>[0]): void { + this.tags.push(loadPositionalTag(tag)); + } + + /** + * Check whether a new {@linkcode PositionalTag} can be added to the battlefield. + * @param tagType - The {@linkcode PositionalTagType} being created + * @param targetIndex - The {@linkcode BattlerIndex} being targeted + * @returns Whether the tag can be added. + */ + public canAddTag(tagType: PositionalTagType, targetIndex: BattlerIndex): boolean { + return !this.tags.some(t => t.tagType === tagType && t.targetIndex === targetIndex); + } + + /** + * Decrement turn counts of and trigger all pending {@linkcode PositionalTag}s on field. + * @remarks + * If multiple tags trigger simultaneously, they will activate in order of **initial creation**, regardless of current speed order. + * (Source: [Smogon]()) + */ + public activateAllTags(): void { + const leftoverTags: PositionalTag[] = []; + for (const tag of this.tags) { + // Check for silent removal, immediately removing invalid tags. + if (--tag.turnCount > 0) { + // tag still cooking + leftoverTags.push(tag); + continue; + } + + if (tag.shouldTrigger()) { + tag.trigger(); + } + } + this.tags = leftoverTags; + } +} diff --git a/src/data/positional-tags/positional-tag.ts b/src/data/positional-tags/positional-tag.ts new file mode 100644 index 00000000000..77ca6f0e9eb --- /dev/null +++ b/src/data/positional-tags/positional-tag.ts @@ -0,0 +1,174 @@ +import { globalScene } from "#app/global-scene"; +import { getPokemonNameWithAffix } from "#app/messages"; +// biome-ignore-start lint/correctness/noUnusedImports: TSDoc +import type { ArenaTag } from "#data/arena-tag"; +// biome-ignore-end lint/correctness/noUnusedImports: TSDoc +import { allMoves } from "#data/data-lists"; +import type { BattlerIndex } from "#enums/battler-index"; +import type { MoveId } from "#enums/move-id"; +import { MoveUseMode } from "#enums/move-use-mode"; +import { PositionalTagType } from "#enums/positional-tag-type"; +import type { Pokemon } from "#field/pokemon"; +import i18next from "i18next"; + +/** + * Baseline arguments used to construct all {@linkcode PositionalTag}s, + * the contents of which are serialized and used to construct new tags. \ + * Does not contain the `tagType` parameter (which is used to select the proper class constructor during tag loading). + * @privateRemarks + * All {@linkcode PositionalTag}s are intended to implement a sub-interface of this containing their respective parameters, + * and should refrain from adding extra serializable fields not contained in said interface. + * This ensures that all tags truly "become" their respective interfaces when converted to and from JSON. + */ +export interface PositionalTagBaseArgs { + /** + * The number of turns remaining until this tag's activation. \ + * Decremented by 1 at the end of each turn until reaching 0, at which point it will + * {@linkcode PositionalTag.trigger | trigger} the tag's effects and be removed. + */ + turnCount: number; + /** + * The {@linkcode BattlerIndex} targeted by this effect. + */ + targetIndex: BattlerIndex; +} + +/** + * A {@linkcode PositionalTag} is a variant of an {@linkcode ArenaTag} that targets a single *slot* of the battlefield. + * Each tag can last one or more turns, triggering various effects on removal. + * Multiple tags of the same kind can stack with one another, provided they are affecting different targets. + */ +export abstract class PositionalTag implements PositionalTagBaseArgs { + /** This tag's {@linkcode PositionalTagType | type} */ + public abstract readonly tagType: PositionalTagType; + // These arguments have to be public to implement the interface, but are functionally private + // outside this and the tag manager. + // Left undocumented to inherit doc comments from the interface + public turnCount: number; + public readonly targetIndex: BattlerIndex; + + constructor({ turnCount, targetIndex }: PositionalTagBaseArgs) { + this.turnCount = turnCount; + this.targetIndex = targetIndex; + } + + /** Trigger this tag's effects prior to removal. */ + public abstract trigger(): void; + + /** + * Check whether this tag should be allowed to {@linkcode trigger} and activate its effects + * upon its duration elapsing. + * @returns Whether this tag should be allowed to trigger prior to being removed. + */ + public abstract shouldTrigger(): boolean; + + /** + * Get the {@linkcode Pokemon} currently targeted by this tag. + * @returns The {@linkcode Pokemon} located in this tag's target position, or `undefined` if none exist in it. + */ + protected getTarget(): Pokemon | undefined { + return globalScene.getField()[this.targetIndex]; + } +} + +/** Interface containing additional properties used to construct a {@linkcode DelayedAttackTag}. */ +interface DelayedAttackArgs extends PositionalTagBaseArgs { + /** + * The {@linkcode Pokemon.id | PID} of the {@linkcode Pokemon} having created this effect. + */ + sourceId: number; + /** The {@linkcode MoveId} that created this attack. */ + sourceMove: MoveId; +} + +/** + * Tag to manage execution of delayed attacks, such as {@linkcode MoveId.FUTURE_SIGHT} or {@linkcode MoveId.DOOM_DESIRE}. \ + * Delayed attacks do nothing for the first several turns after use (including the turn the move is used), + * triggering against a certain slot after the turn count has elapsed. + */ +export class DelayedAttackTag extends PositionalTag implements DelayedAttackArgs { + public override readonly tagType = PositionalTagType.DELAYED_ATTACK; + public readonly sourceMove: MoveId; + public readonly sourceId: number; + + constructor({ sourceId, turnCount, targetIndex, sourceMove }: DelayedAttackArgs) { + super({ turnCount, targetIndex }); + this.sourceId = sourceId; + this.sourceMove = sourceMove; + } + + public override trigger(): void { + // Bangs are justified as the `shouldTrigger` method will queue the tag for removal + // if the source or target no longer exist + const source = globalScene.getPokemonById(this.sourceId)!; + const target = this.getTarget()!; + + source.turnData.extraTurns++; + globalScene.phaseManager.queueMessage( + i18next.t("moveTriggers:tookMoveAttack", { + pokemonName: getPokemonNameWithAffix(target), + moveName: allMoves[this.sourceMove].name, + }), + ); + + globalScene.phaseManager.unshiftNew( + "MoveEffectPhase", + this.sourceId, // TODO: Find an alternate method of passing the source pokemon without a source ID + [this.targetIndex], + allMoves[this.sourceMove], + MoveUseMode.DELAYED_ATTACK, + ); + } + + public override shouldTrigger(): boolean { + const source = globalScene.getPokemonById(this.sourceId); + const target = this.getTarget(); + // Silently disappear if either source or target are missing or happen to be the same pokemon + // (i.e. targeting oneself) + // We also need to check for fainted targets as they don't technically leave the field until _after_ the turn ends + return !!source && !!target && source !== target && !target.isFainted(); + } +} + +/** Interface containing arguments used to construct a {@linkcode WishTag}. */ +interface WishArgs extends PositionalTagBaseArgs { + /** The amount of {@linkcode Stat.HP | HP} to heal; set to 50% of the user's max HP during move usage. */ + healHp: number; + /** The name of the {@linkcode Pokemon} having created the tag. */ + pokemonName: string; +} + +/** + * Tag to implement {@linkcode MoveId.WISH | Wish}. + */ +export class WishTag extends PositionalTag implements WishArgs { + public override readonly tagType = PositionalTagType.WISH; + + public readonly pokemonName: string; + public readonly healHp: number; + + constructor({ turnCount, targetIndex, healHp, pokemonName }: WishArgs) { + super({ turnCount, targetIndex }); + this.healHp = healHp; + this.pokemonName = pokemonName; + } + + public override trigger(): void { + // TODO: Rename this locales key - wish shows a message on REMOVAL, not addition + globalScene.phaseManager.queueMessage( + i18next.t("arenaTag:wishTagOnAdd", { + pokemonNameWithAffix: this.pokemonName, + }), + ); + + globalScene.phaseManager.unshiftNew("PokemonHealPhase", this.targetIndex, this.healHp, null, true, false); + } + + public override shouldTrigger(): boolean { + // Disappear if no target or target is fainted. + // The source need not exist at the time of activation (since all we need is a simple message) + // TODO: Verify whether Wish shows a message if the Pokemon it would affect is KO'd on the turn of activation + const target = this.getTarget(); + return !!target && !target.isFainted(); + } +} diff --git a/src/enums/ability-attr.ts b/src/enums/ability-attr.ts index 5f7d107f2d1..a3b9511ad02 100644 --- a/src/enums/ability-attr.ts +++ b/src/enums/ability-attr.ts @@ -1,3 +1,5 @@ +import type { ObjectValues } from "#types/type-helpers"; + /** * Not to be confused with an Ability Attribute. * This is an object literal storing the slot that an ability can occupy. @@ -8,4 +10,4 @@ export const AbilityAttr = Object.freeze({ ABILITY_HIDDEN: 4, }); -export type AbilityAttr = typeof AbilityAttr[keyof typeof AbilityAttr]; \ No newline at end of file +export type AbilityAttr = ObjectValues; \ No newline at end of file diff --git a/src/enums/arena-tag-type.ts b/src/enums/arena-tag-type.ts index 214826993b3..7f9364395c0 100644 --- a/src/enums/arena-tag-type.ts +++ b/src/enums/arena-tag-type.ts @@ -15,9 +15,6 @@ export enum ArenaTagType { SPIKES = "SPIKES", TOXIC_SPIKES = "TOXIC_SPIKES", MIST = "MIST", - FUTURE_SIGHT = "FUTURE_SIGHT", - DOOM_DESIRE = "DOOM_DESIRE", - WISH = "WISH", STEALTH_ROCK = "STEALTH_ROCK", STICKY_WEB = "STICKY_WEB", TRICK_ROOM = "TRICK_ROOM", diff --git a/src/enums/battler-tag-type.ts b/src/enums/battler-tag-type.ts index 719b08c5b81..6d9d2dd4a92 100644 --- a/src/enums/battler-tag-type.ts +++ b/src/enums/battler-tag-type.ts @@ -1,5 +1,4 @@ export enum BattlerTagType { - NONE = "NONE", RECHARGING = "RECHARGING", FLINCHED = "FLINCHED", INTERRUPTED = "INTERRUPTED", diff --git a/src/enums/dex-attr.ts b/src/enums/dex-attr.ts index ee5ceb43ef2..1a98167b4a1 100644 --- a/src/enums/dex-attr.ts +++ b/src/enums/dex-attr.ts @@ -1,3 +1,5 @@ +import type { ObjectValues } from "#types/type-helpers"; + export const DexAttr = Object.freeze({ NON_SHINY: 1n, SHINY: 2n, @@ -8,4 +10,4 @@ export const DexAttr = Object.freeze({ VARIANT_3: 64n, DEFAULT_FORM: 128n, }); -export type DexAttr = typeof DexAttr[keyof typeof DexAttr]; +export type DexAttr = ObjectValues; diff --git a/src/enums/dynamic-phase-type.ts b/src/enums/dynamic-phase-type.ts index a34ac371668..b9ea6bf197d 100644 --- a/src/enums/dynamic-phase-type.ts +++ b/src/enums/dynamic-phase-type.ts @@ -1,6 +1,7 @@ /** - * Enum representation of the phase types held by implementations of {@linkcode PhasePriorityQueue} + * Enum representation of the phase types held by implementations of {@linkcode PhasePriorityQueue}. */ +// TODO: We currently assume these are in order export enum DynamicPhaseType { POST_SUMMON } diff --git a/src/enums/gacha-types.ts b/src/enums/gacha-types.ts index cd0bc67eae0..08f147b27b1 100644 --- a/src/enums/gacha-types.ts +++ b/src/enums/gacha-types.ts @@ -1,7 +1,9 @@ +import type { ObjectValues } from "#types/type-helpers"; + export const GachaType = Object.freeze({ MOVE: 0, LEGENDARY: 1, SHINY: 2 }); -export type GachaType = typeof GachaType[keyof typeof GachaType]; +export type GachaType = ObjectValues; diff --git a/src/enums/hit-check-result.ts b/src/enums/hit-check-result.ts index cf8a2b17194..0866050341e 100644 --- a/src/enums/hit-check-result.ts +++ b/src/enums/hit-check-result.ts @@ -1,3 +1,5 @@ +import type { ObjectValues } from "#types/type-helpers"; + /** The result of a hit check calculation */ export const HitCheckResult = { /** Hit checks haven't been evaluated yet in this pass */ @@ -20,4 +22,4 @@ export const HitCheckResult = { ERROR: 8, } as const; -export type HitCheckResult = typeof HitCheckResult[keyof typeof HitCheckResult]; +export type HitCheckResult = ObjectValues; diff --git a/src/enums/move-flags.ts b/src/enums/move-flags.ts index 06de265df09..6cdc1e5f8cc 100644 --- a/src/enums/move-flags.ts +++ b/src/enums/move-flags.ts @@ -4,15 +4,19 @@ */ export enum MoveFlags { NONE = 0, + /** + * Whether the move makes contact. + * Set by default on all contact moves, and unset by default on all special moves. + */ MAKES_CONTACT = 1 << 0, IGNORE_PROTECT = 1 << 1, /** * Sound-based moves have the following effects: - * - Pokemon with the {@linkcode AbilityId.SOUNDPROOF Soundproof Ability} are unaffected by other Pokemon's sound-based moves. - * - Pokemon affected by {@linkcode MoveId.THROAT_CHOP Throat Chop} cannot use sound-based moves for two turns. - * - Sound-based moves used by a Pokemon with {@linkcode AbilityId.LIQUID_VOICE Liquid Voice} become Water-type moves. - * - Sound-based moves used by a Pokemon with {@linkcode AbilityId.PUNK_ROCK Punk Rock} are boosted by 30%. Pokemon with Punk Rock also take half damage from sound-based moves. - * - All sound-based moves (except Howl) can hit Pokemon behind an active {@linkcode MoveId.SUBSTITUTE Substitute}. + * - Pokemon with the {@linkcode AbilityId.SOUNDPROOF | Soundproof} Ability are unaffected by other Pokemon's sound-based moves. + * - Pokemon affected by {@linkcode MoveId.THROAT_CHOP | Throat Chop} cannot use sound-based moves for two turns. + * - Sound-based moves used by a Pokemon with {@linkcode AbilityId.LIQUID_VOICE | Liquid Voice} become Water-type moves. + * - Sound-based moves used by a Pokemon with {@linkcode AbilityId.PUNK_ROCK | Punk Rock} are boosted by 30%. Pokemon with Punk Rock also take half damage from sound-based moves. + * - All sound-based moves (except Howl) can hit Pokemon behind an active {@linkcode MoveId.SUBSTITUTE | Substitute}. * * cf https://bulbapedia.bulbagarden.net/wiki/Sound-based_move */ diff --git a/src/enums/move-use-mode.ts b/src/enums/move-use-mode.ts index 1bb9d6374b7..13ea5248853 100644 --- a/src/enums/move-use-mode.ts +++ b/src/enums/move-use-mode.ts @@ -1,5 +1,7 @@ import type { PostDancingMoveAbAttr } from "#abilities/ability"; +import type { DelayedAttackAttr } from "#app/@types/move-types"; import type { BattlerTagLapseType } from "#enums/battler-tag-lapse-type"; +import type { ObjectValues } from "#types/type-helpers"; /** * Enum representing all the possible means through which a given move can be executed. @@ -59,11 +61,20 @@ export const MoveUseMode = { * and retain the same copy prevention as {@linkcode MoveUseMode.FOLLOW_UP}, but additionally * **cannot be reflected by other reflecting effects**. */ - REFLECTED: 5 - // TODO: Add use type TRANSPARENT for Future Sight and Doom Desire to prevent move history pushing + REFLECTED: 5, + /** + * This "move" was created by a transparent effect that **does not count as using a move**, + * such as {@linkcode DelayedAttackAttr | Future Sight/Doom Desire}. + * + * In addition to inheriting the cancellation ignores and copy prevention from {@linkcode MoveUseMode.REFLECTED}, + * transparent moves are ignored by **all forms of move usage checks** due to **not pushing to move history**. + * @todo Consider other means of implementing FS/DD than this - we currently only use it + * to prevent pushing to move history and avoid re-delaying the attack portion + */ + DELAYED_ATTACK: 6 } as const; -export type MoveUseMode = (typeof MoveUseMode)[keyof typeof MoveUseMode]; +export type MoveUseMode = ObjectValues; // # HELPER FUNCTIONS // Please update the markdown tables if any new `MoveUseMode`s get added. @@ -75,13 +86,14 @@ export type MoveUseMode = (typeof MoveUseMode)[keyof typeof MoveUseMode]; * @remarks * This function is equivalent to the following truth table: * - * | Use Type | Returns | - * |------------------------------------|---------| - * | {@linkcode MoveUseMode.NORMAL} | `false` | - * | {@linkcode MoveUseMode.IGNORE_PP} | `false` | - * | {@linkcode MoveUseMode.INDIRECT} | `true` | - * | {@linkcode MoveUseMode.FOLLOW_UP} | `true` | - * | {@linkcode MoveUseMode.REFLECTED} | `true` | + * | Use Type | Returns | + * |----------------------------------------|---------| + * | {@linkcode MoveUseMode.NORMAL} | `false` | + * | {@linkcode MoveUseMode.IGNORE_PP} | `false` | + * | {@linkcode MoveUseMode.INDIRECT} | `true` | + * | {@linkcode MoveUseMode.FOLLOW_UP} | `true` | + * | {@linkcode MoveUseMode.REFLECTED} | `true` | + * | {@linkcode MoveUseMode.DELAYED_ATTACK} | `true` | */ export function isVirtual(useMode: MoveUseMode): boolean { return useMode >= MoveUseMode.INDIRECT @@ -95,13 +107,14 @@ export function isVirtual(useMode: MoveUseMode): boolean { * @remarks * This function is equivalent to the following truth table: * - * | Use Type | Returns | - * |------------------------------------|---------| - * | {@linkcode MoveUseMode.NORMAL} | `false` | - * | {@linkcode MoveUseMode.IGNORE_PP} | `false` | - * | {@linkcode MoveUseMode.INDIRECT} | `false` | - * | {@linkcode MoveUseMode.FOLLOW_UP} | `true` | - * | {@linkcode MoveUseMode.REFLECTED} | `true` | + * | Use Type | Returns | + * |----------------------------------------|---------| + * | {@linkcode MoveUseMode.NORMAL} | `false` | + * | {@linkcode MoveUseMode.IGNORE_PP} | `false` | + * | {@linkcode MoveUseMode.INDIRECT} | `false` | + * | {@linkcode MoveUseMode.FOLLOW_UP} | `true` | + * | {@linkcode MoveUseMode.REFLECTED} | `true` | + * | {@linkcode MoveUseMode.DELAYED_ATTACK} | `true` | */ export function isIgnoreStatus(useMode: MoveUseMode): boolean { return useMode >= MoveUseMode.FOLLOW_UP; @@ -115,13 +128,14 @@ export function isIgnoreStatus(useMode: MoveUseMode): boolean { * @remarks * This function is equivalent to the following truth table: * - * | Use Type | Returns | - * |------------------------------------|---------| - * | {@linkcode MoveUseMode.NORMAL} | `false` | - * | {@linkcode MoveUseMode.IGNORE_PP} | `true` | - * | {@linkcode MoveUseMode.INDIRECT} | `true` | - * | {@linkcode MoveUseMode.FOLLOW_UP} | `true` | - * | {@linkcode MoveUseMode.REFLECTED} | `true` | + * | Use Type | Returns | + * |----------------------------------------|---------| + * | {@linkcode MoveUseMode.NORMAL} | `false` | + * | {@linkcode MoveUseMode.IGNORE_PP} | `true` | + * | {@linkcode MoveUseMode.INDIRECT} | `true` | + * | {@linkcode MoveUseMode.FOLLOW_UP} | `true` | + * | {@linkcode MoveUseMode.REFLECTED} | `true` | + * | {@linkcode MoveUseMode.DELAYED_ATTACK} | `true` | */ export function isIgnorePP(useMode: MoveUseMode): boolean { return useMode >= MoveUseMode.IGNORE_PP; @@ -136,14 +150,15 @@ export function isIgnorePP(useMode: MoveUseMode): boolean { * @remarks * This function is equivalent to the following truth table: * - * | Use Type | Returns | - * |------------------------------------|---------| - * | {@linkcode MoveUseMode.NORMAL} | `false` | - * | {@linkcode MoveUseMode.IGNORE_PP} | `false` | - * | {@linkcode MoveUseMode.INDIRECT} | `false` | - * | {@linkcode MoveUseMode.FOLLOW_UP} | `false` | - * | {@linkcode MoveUseMode.REFLECTED} | `true` | + * | Use Type | Returns | + * |----------------------------------------|---------| + * | {@linkcode MoveUseMode.NORMAL} | `false` | + * | {@linkcode MoveUseMode.IGNORE_PP} | `false` | + * | {@linkcode MoveUseMode.INDIRECT} | `false` | + * | {@linkcode MoveUseMode.FOLLOW_UP} | `false` | + * | {@linkcode MoveUseMode.REFLECTED} | `true` | + * | {@linkcode MoveUseMode.DELAYED_ATTACK} | `false` | */ export function isReflected(useMode: MoveUseMode): boolean { return useMode === MoveUseMode.REFLECTED; -} +} \ No newline at end of file diff --git a/src/enums/positional-tag-type.ts b/src/enums/positional-tag-type.ts new file mode 100644 index 00000000000..254503d0de6 --- /dev/null +++ b/src/enums/positional-tag-type.ts @@ -0,0 +1,10 @@ +/** + * Enum representing all positional tag types. + * @privateRemarks + * When adding new tag types, please update `positionalTagConstructorMap` in `src/data/positionalTags` + * with the new tag type. + */ +export enum PositionalTagType { + DELAYED_ATTACK = "DELAYED_ATTACK", + WISH = "WISH", +} diff --git a/src/field/arena.ts b/src/field/arena.ts index 8f27ddb22e9..484450cc5df 100644 --- a/src/field/arena.ts +++ b/src/field/arena.ts @@ -1,3 +1,7 @@ +// biome-ignore-start lint/correctness/noUnusedImports: TSDoc imports +import type { PositionalTag } from "#data/positional-tags/positional-tag"; +// biome-ignore-end lint/correctness/noUnusedImports: TSDoc imports + import { applyAbAttrs } from "#abilities/apply-ab-attrs"; import { globalScene } from "#app/global-scene"; import Overrides from "#app/overrides"; @@ -7,6 +11,7 @@ import type { ArenaTag } from "#data/arena-tag"; import { ArenaTrapTag, getArenaTag } from "#data/arena-tag"; import { SpeciesFormChangeRevertWeatherFormTrigger, SpeciesFormChangeWeatherTrigger } from "#data/form-change-triggers"; import type { PokemonSpecies } from "#data/pokemon-species"; +import { PositionalTagManager } from "#data/positional-tags/positional-tag-manager"; import { getTerrainClearMessage, getTerrainStartMessage, Terrain, TerrainType } from "#data/terrain"; import { getLegendaryWeatherContinuesMessage, @@ -38,7 +43,14 @@ export class Arena { public biomeType: BiomeId; public weather: Weather | null; public terrain: Terrain | null; - public tags: ArenaTag[]; + /** All currently-active {@linkcode ArenaTag}s on both sides of the field. */ + public tags: ArenaTag[] = []; + /** + * All currently-active {@linkcode PositionalTag}s on both sides of the field, + * sorted by tag type. + */ + public positionalTagManager: PositionalTagManager = new PositionalTagManager(); + public bgm: string; public ignoreAbilities: boolean; public ignoringEffectSource: BattlerIndex | null; @@ -58,7 +70,6 @@ export class Arena { constructor(biome: BiomeId, bgm: string, playerFaints = 0) { this.biomeType = biome; - this.tags = []; this.bgm = bgm; this.trainerPool = biomeTrainerPools[biome]; this.updatePoolsForTimeOfDay(); @@ -676,15 +687,15 @@ export class Arena { } /** - * Adds a new tag to the arena - * @param tagType {@linkcode ArenaTagType} the tag being added - * @param turnCount How many turns the tag lasts - * @param sourceMove {@linkcode MoveId} the move the tag came from, or `undefined` if not from a move - * @param sourceId The ID of the pokemon in play the tag came from (see {@linkcode BattleScene.getPokemonById}) - * @param side {@linkcode ArenaTagSide} which side(s) the tag applies to - * @param quiet If a message should be queued on screen to announce the tag being added - * @param targetIndex The {@linkcode BattlerIndex} of the target pokemon - * @returns `false` if there already exists a tag of this type in the Arena + * Add a new {@linkcode ArenaTag} to the arena, triggering overlap effects on existing tags as applicable. + * @param tagType - The {@linkcode ArenaTagType} of the tag to add. + * @param turnCount - The number of turns the newly-added tag should last. + * @param sourceId - The {@linkcode Pokemon.id | PID} of the Pokemon creating the tag. + * @param sourceMove - The {@linkcode MoveId} of the move creating the tag, or `undefined` if not from a move. + * @param side - The {@linkcode ArenaTagSide}(s) to which the tag should apply; default `ArenaTagSide.BOTH`. + * @param quiet - Whether to suppress messages produced by tag addition; default `false`. + * @returns `true` if the tag was successfully added without overlapping. + // TODO: Do we need the return value here? literally nothing uses it */ addTag( tagType: ArenaTagType, @@ -693,7 +704,6 @@ export class Arena { sourceId: number, side: ArenaTagSide = ArenaTagSide.BOTH, quiet = false, - targetIndex?: BattlerIndex, ): boolean { const existingTag = this.getTagOnSide(tagType, side); if (existingTag) { @@ -708,7 +718,7 @@ export class Arena { } // creates a new tag object - const newTag = getArenaTag(tagType, turnCount || 0, sourceMove, sourceId, targetIndex, side); + const newTag = getArenaTag(tagType, turnCount || 0, sourceMove, sourceId, side); if (newTag) { newTag.onAdd(this, quiet); this.tags.push(newTag); @@ -724,10 +734,19 @@ export class Arena { } /** - * Attempts to get a tag from the Arena via {@linkcode getTagOnSide} that applies to both sides - * @param tagType The {@linkcode ArenaTagType} or {@linkcode ArenaTag} to get - * @returns either the {@linkcode ArenaTag}, or `undefined` if it isn't there + * Attempt to get a tag from the Arena via {@linkcode getTagOnSide} that applies to both sides + * @param tagType - The {@linkcode ArenaTagType} to retrieve + * @returns The existing {@linkcode ArenaTag}, or `undefined` if not present. + * @overload */ + getTag(tagType: ArenaTagType): ArenaTag | undefined; + /** + * Attempt to get a tag from the Arena via {@linkcode getTagOnSide} that applies to both sides + * @param tagType - The constructor of the {@linkcode ArenaTag} to retrieve + * @returns The existing {@linkcode ArenaTag}, or `undefined` if not present. + * @overload + */ + getTag(tagType: Constructor | AbstractConstructor): T | undefined; getTag(tagType: ArenaTagType | Constructor | AbstractConstructor): ArenaTag | undefined { return this.getTagOnSide(tagType, ArenaTagSide.BOTH); } diff --git a/src/phase-manager.ts b/src/phase-manager.ts index 73ea373904f..850f0c564ea 100644 --- a/src/phase-manager.ts +++ b/src/phase-manager.ts @@ -9,6 +9,7 @@ import { AttemptCapturePhase } from "#phases/attempt-capture-phase"; import { AttemptRunPhase } from "#phases/attempt-run-phase"; import { BattleEndPhase } from "#phases/battle-end-phase"; import { BerryPhase } from "#phases/berry-phase"; +import { CheckInterludePhase } from "#phases/check-interlude-phase"; import { CheckStatusEffectPhase } from "#phases/check-status-effect-phase"; import { CheckSwitchPhase } from "#phases/check-switch-phase"; import { CommandPhase } from "#phases/command-phase"; @@ -60,6 +61,7 @@ import { PartyHealPhase } from "#phases/party-heal-phase"; import { PokemonAnimPhase } from "#phases/pokemon-anim-phase"; import { PokemonHealPhase } from "#phases/pokemon-heal-phase"; import { PokemonTransformPhase } from "#phases/pokemon-transform-phase"; +import { PositionalTagPhase } from "#phases/positional-tag-phase"; import { PostGameOverPhase } from "#phases/post-game-over-phase"; import { PostSummonPhase } from "#phases/post-summon-phase"; import { PostTurnStatusEffectPhase } from "#phases/post-turn-status-effect-phase"; @@ -121,6 +123,7 @@ const PHASES = Object.freeze({ AttemptRunPhase, BattleEndPhase, BerryPhase, + CheckInterludePhase, CheckStatusEffectPhase, CheckSwitchPhase, CommandPhase, @@ -170,6 +173,7 @@ const PHASES = Object.freeze({ PokemonAnimPhase, PokemonHealPhase, PokemonTransformPhase, + PositionalTagPhase, PostGameOverPhase, PostSummonPhase, PostTurnStatusEffectPhase, @@ -240,6 +244,21 @@ export class PhaseManager { this.dynamicPhaseTypes = [PostSummonPhase]; } + /** + * Clear all previously set phases, then add a new {@linkcode TitlePhase} to transition to the title screen. + * @param addLogin - Whether to add a new {@linkcode LoginPhase} before the {@linkcode TitlePhase} + * (but reset everything else). + * Default `false` + */ + public toTitleScreen(addLogin = false): void { + this.clearAllPhases(); + + if (addLogin) { + this.unshiftNew("LoginPhase"); + } + this.unshiftNew("TitlePhase"); + } + /* Phase Functions */ getCurrentPhase(): Phase | null { return this.currentPhase; @@ -665,4 +684,15 @@ export class PhaseManager { ): void { this.startDynamicPhase(this.create(phase, ...args)); } + + /** Prevents end of turn effects from triggering when transitioning to a new biome on a X0 wave */ + public onInterlude(): void { + const phasesToRemove = ["WeatherEffectPhase", "BerryPhase", "CheckStatusEffectPhase"]; + this.phaseQueue = this.phaseQueue.filter(p => !phasesToRemove.includes(p.phaseName)); + + const turnEndPhase = this.findPhase(p => p.phaseName === "TurnEndPhase"); + if (turnEndPhase) { + turnEndPhase.upcomingInterlude = true; + } + } } diff --git a/src/phases/check-interlude-phase.ts b/src/phases/check-interlude-phase.ts new file mode 100644 index 00000000000..1589f74f058 --- /dev/null +++ b/src/phases/check-interlude-phase.ts @@ -0,0 +1,18 @@ +import { globalScene } from "#app/global-scene"; +import { Phase } from "#app/phase"; + +export class CheckInterludePhase extends Phase { + public override readonly phaseName = "CheckInterludePhase"; + + public override start(): void { + super.start(); + const { phaseManager } = globalScene; + const { waveIndex } = globalScene.currentBattle; + + if (waveIndex % 10 === 0 && globalScene.getEnemyParty().every(p => p.isFainted())) { + phaseManager.onInterlude(); + } + + this.end(); + } +} diff --git a/src/phases/move-effect-phase.ts b/src/phases/move-effect-phase.ts index b1cb9e48d51..c57e0f6cead 100644 --- a/src/phases/move-effect-phase.ts +++ b/src/phases/move-effect-phase.ts @@ -19,7 +19,7 @@ import { MoveFlags } from "#enums/move-flags"; import { MoveId } from "#enums/move-id"; import { MoveResult } from "#enums/move-result"; import { MoveTarget } from "#enums/move-target"; -import { isReflected, isVirtual, MoveUseMode } from "#enums/move-use-mode"; +import { isReflected, MoveUseMode } from "#enums/move-use-mode"; import { PokemonType } from "#enums/pokemon-type"; import type { Pokemon } from "#field/pokemon"; import { @@ -244,43 +244,19 @@ export class MoveEffectPhase extends PokemonPhase { globalScene.currentBattle.lastPlayerInvolved = this.fieldIndex; } - const isDelayedAttack = this.move.hasAttr("DelayedAttackAttr"); - /** If the user was somehow removed from the field and it's not a delayed attack, end this phase */ - if (!user.isOnField()) { - if (!isDelayedAttack) { - super.end(); - return; - } - if (!user.scene) { - /* - * This happens if the Pokemon that used the delayed attack gets caught and released - * on the turn the attack would have triggered. Having access to the global scene - * in the future may solve this entirely, so for now we just cancel the hit - */ - super.end(); - return; - } - } + const move = this.move; /** * Does an effect from this move override other effects on this turn? * e.g. Charging moves (Fly, etc.) on their first turn of use. */ const overridden = new BooleanHolder(false); - const move = this.move; // Apply effects to override a move effect. // Assuming single target here works as this is (currently) // only used for Future Sight, calling and Pledge moves. // TODO: change if any other move effect overrides are introduced - applyMoveAttrs( - "OverrideMoveEffectAttr", - user, - this.getFirstTarget() ?? null, - move, - overridden, - isVirtual(this.useMode), - ); + applyMoveAttrs("OverrideMoveEffectAttr", user, this.getFirstTarget() ?? null, move, overridden, this.useMode); // If other effects were overriden, stop this phase before they can be applied if (overridden.value) { @@ -355,7 +331,7 @@ export class MoveEffectPhase extends PokemonPhase { */ private postAnimCallback(user: Pokemon, targets: Pokemon[]) { // Add to the move history entry - if (this.firstHit) { + if (this.firstHit && this.useMode !== MoveUseMode.DELAYED_ATTACK) { user.pushMoveHistory(this.moveHistoryEntry); applyAbAttrs("ExecutedMoveAbAttr", { pokemon: user }); } @@ -663,6 +639,7 @@ export class MoveEffectPhase extends PokemonPhase { /** @returns The {@linkcode Pokemon} using this phase's invoked move */ public getUserPokemon(): Pokemon | null { + // TODO: Make this purely a battler index if (this.battlerIndex > BattlerIndex.ENEMY_2) { return globalScene.getPokemonById(this.battlerIndex); } diff --git a/src/phases/move-phase.ts b/src/phases/move-phase.ts index 82bb6b153ef..cd7c7a8f48f 100644 --- a/src/phases/move-phase.ts +++ b/src/phases/move-phase.ts @@ -2,14 +2,12 @@ import { applyAbAttrs } from "#abilities/apply-ab-attrs"; import { globalScene } from "#app/global-scene"; import { getPokemonNameWithAffix } from "#app/messages"; import Overrides from "#app/overrides"; -import type { DelayedAttackTag } from "#data/arena-tag"; import { CenterOfAttentionTag } from "#data/battler-tags"; import { SpeciesFormChangePreMoveTrigger } from "#data/form-change-triggers"; import { getStatusEffectActivationText, getStatusEffectHealText } from "#data/status-effect"; import { getTerrainBlockMessage } from "#data/terrain"; import { getWeatherBlockMessage } from "#data/weather"; import { AbilityId } from "#enums/ability-id"; -import { ArenaTagType } from "#enums/arena-tag-type"; import { BattlerIndex } from "#enums/battler-index"; import { BattlerTagLapseType } from "#enums/battler-tag-lapse-type"; import { BattlerTagType } from "#enums/battler-tag-type"; @@ -297,21 +295,6 @@ export class MovePhase extends BattlePhase { // form changes happen even before we know that the move wll execute. globalScene.triggerPokemonFormChange(this.pokemon, SpeciesFormChangePreMoveTrigger); - // Check the player side arena if another delayed attack is active and hitting the same slot. - if (move.hasAttr("DelayedAttackAttr")) { - const currentTargetIndex = targets[0].getBattlerIndex(); - const delayedAttackHittingSameSlot = globalScene.arena.tags.some( - tag => - (tag.tagType === ArenaTagType.FUTURE_SIGHT || tag.tagType === ArenaTagType.DOOM_DESIRE) && - (tag as DelayedAttackTag).targetIndex === currentTargetIndex, - ); - - if (delayedAttackHittingSameSlot) { - this.failMove(true); - return; - } - } - // Check if the move has any attributes that can interrupt its own use **before** displaying text. // TODO: This should not rely on direct return values let failed = move.getAttrs("PreUseInterruptAttr").some(attr => attr.apply(this.pokemon, targets[0], move)); diff --git a/src/phases/positional-tag-phase.ts b/src/phases/positional-tag-phase.ts new file mode 100644 index 00000000000..dec572273c5 --- /dev/null +++ b/src/phases/positional-tag-phase.ts @@ -0,0 +1,21 @@ +// biome-ignore-start lint/correctness/noUnusedImports: TSDocs +import type { PositionalTag } from "#data/positional-tags/positional-tag"; +import type { TurnEndPhase } from "#phases/turn-end-phase"; +// biome-ignore-end lint/correctness/noUnusedImports: TSDocs + +import { globalScene } from "#app/global-scene"; +import { Phase } from "#app/phase"; + +/** + * Phase to trigger all pending post-turn {@linkcode PositionalTag}s. + * Occurs before {@linkcode TurnEndPhase} to allow for proper electrify timing. + */ +export class PositionalTagPhase extends Phase { + public readonly phaseName = "PositionalTagPhase"; + + public override start(): void { + globalScene.arena.positionalTagManager.activateAllTags(); + super.end(); + return; + } +} diff --git a/src/phases/select-starter-phase.ts b/src/phases/select-starter-phase.ts index af056ebb4ee..6456bacd0e3 100644 --- a/src/phases/select-starter-phase.ts +++ b/src/phases/select-starter-phase.ts @@ -24,10 +24,11 @@ export class SelectStarterPhase extends Phase { globalScene.ui.setMode(UiMode.STARTER_SELECT, (starters: Starter[]) => { globalScene.ui.clearText(); globalScene.ui.setMode(UiMode.SAVE_SLOT, SaveSlotUiMode.SAVE, (slotId: number) => { + // If clicking cancel, back out to title screen if (slotId === -1) { - globalScene.phaseManager.clearPhaseQueue(); - globalScene.phaseManager.pushNew("TitlePhase"); - return this.end(); + globalScene.phaseManager.toTitleScreen(); + this.end(); + return; } globalScene.sessionSlotId = slotId; this.initBattle(starters); diff --git a/src/phases/title-phase.ts b/src/phases/title-phase.ts index 38e3ff3a017..6f0493f707d 100644 --- a/src/phases/title-phase.ts +++ b/src/phases/title-phase.ts @@ -114,11 +114,11 @@ export class TitlePhase extends Phase { }); } } + // Cancel button = back to title options.push({ label: i18next.t("menu:cancel"), handler: () => { - globalScene.phaseManager.clearPhaseQueue(); - globalScene.phaseManager.pushNew("TitlePhase"); + globalScene.phaseManager.toTitleScreen(); super.end(); return true; }, @@ -191,11 +191,12 @@ export class TitlePhase extends Phase { initDailyRun(): void { globalScene.ui.clearText(); globalScene.ui.setMode(UiMode.SAVE_SLOT, SaveSlotUiMode.SAVE, (slotId: number) => { - globalScene.phaseManager.clearPhaseQueue(); if (slotId === -1) { - globalScene.phaseManager.pushNew("TitlePhase"); - return super.end(); + globalScene.phaseManager.toTitleScreen(); + super.end(); + return; } + globalScene.phaseManager.clearPhaseQueue(); globalScene.sessionSlotId = slotId; const generateDaily = (seed: string) => { diff --git a/src/phases/turn-end-phase.ts b/src/phases/turn-end-phase.ts index ce3b2958c23..463f26e73a2 100644 --- a/src/phases/turn-end-phase.ts +++ b/src/phases/turn-end-phase.ts @@ -18,6 +18,8 @@ import i18next from "i18next"; export class TurnEndPhase extends FieldPhase { public readonly phaseName = "TurnEndPhase"; + public upcomingInterlude = false; + start() { super.start(); @@ -59,9 +61,11 @@ export class TurnEndPhase extends FieldPhase { pokemon.tempSummonData.waveTurnCount++; }; - this.executeForAll(handlePokemon); + if (!this.upcomingInterlude) { + this.executeForAll(handlePokemon); - globalScene.arena.lapseTags(); + globalScene.arena.lapseTags(); + } if (globalScene.arena.weather && !globalScene.arena.weather.lapse()) { globalScene.arena.trySetWeather(WeatherType.NONE); diff --git a/src/phases/turn-start-phase.ts b/src/phases/turn-start-phase.ts index 0fc126801ec..9c53a333ed0 100644 --- a/src/phases/turn-start-phase.ts +++ b/src/phases/turn-start-phase.ts @@ -218,6 +218,10 @@ export class TurnStartPhase extends FieldPhase { break; } } + phaseManager.pushNew("CheckInterludePhase"); + + // TODO: Re-order these phases to be consistent with mainline turn order: + // https://www.smogon.com/forums/threads/sword-shield-battle-mechanics-research.3655528/page-64#post-9244179 phaseManager.pushNew("WeatherEffectPhase"); phaseManager.pushNew("BerryPhase"); @@ -225,12 +229,13 @@ export class TurnStartPhase extends FieldPhase { /** Add a new phase to check who should be taking status damage */ phaseManager.pushNew("CheckStatusEffectPhase", moveOrder); + phaseManager.pushNew("PositionalTagPhase"); phaseManager.pushNew("TurnEndPhase"); - /** - * this.end() will call shiftPhase(), which dumps everything from PrependQueue (aka everything that is unshifted()) to the front - * of the queue and dequeues to start the next phase - * this is important since stuff like SwitchSummon, AttemptRun, AttemptCapture Phases break the "flow" and should take precedence + /* + * `this.end()` will call `PhaseManager#shiftPhase()`, which dumps everything from `phaseQueuePrepend` + * (aka everything that is queued via `unshift()`) to the front of the queue and dequeues to start the next phase. + * This is important since stuff like `SwitchSummonPhase`, `AttemptRunPhase`, and `AttemptCapturePhase` break the "flow" and should take precedence */ this.end(); } diff --git a/src/system/arena-data.ts b/src/system/arena-data.ts index c0ad4a25024..b2a04f96a55 100644 --- a/src/system/arena-data.ts +++ b/src/system/arena-data.ts @@ -1,5 +1,6 @@ import type { ArenaTag } from "#data/arena-tag"; import { loadArenaTag, SerializableArenaTag } from "#data/arena-tag"; +import type { SerializedPositionalTag } from "#data/positional-tags/load-positional-tag"; import { Terrain } from "#data/terrain"; import { Weather } from "#data/weather"; import type { BiomeId } from "#enums/biome-id"; @@ -12,6 +13,7 @@ export interface SerializedArenaData { weather: NonFunctionProperties | null; terrain: NonFunctionProperties | null; tags?: ArenaTagTypeData[]; + positionalTags: SerializedPositionalTag[]; playerTerasUsed?: number; } @@ -20,6 +22,7 @@ export class ArenaData { public weather: Weather | null; public terrain: Terrain | null; public tags: ArenaTag[]; + public positionalTags: SerializedPositionalTag[] = []; public playerTerasUsed: number; constructor(source: Arena | SerializedArenaData) { @@ -37,11 +40,15 @@ export class ArenaData { this.biome = source.biomeType; this.weather = source.weather; this.terrain = source.terrain; + // The assertion here is ok - we ensure that all tags are inside the `posTagConstructorMap` map, + // and that all `PositionalTags` will become their respective interfaces when serialized and de-serialized. + this.positionalTags = (source.positionalTagManager.tags as unknown as SerializedPositionalTag[]) ?? []; return; } this.biome = source.biome; this.weather = source.weather ? new Weather(source.weather.weatherType, source.weather.turnsLeft) : null; this.terrain = source.terrain ? new Terrain(source.terrain.terrainType, source.terrain.turnsLeft) : null; + this.positionalTags = source.positionalTags ?? []; } } diff --git a/src/system/game-data.ts b/src/system/game-data.ts index b148ed4e2ba..d899afa19ef 100644 --- a/src/system/game-data.ts +++ b/src/system/game-data.ts @@ -16,6 +16,7 @@ import { allMoves, allSpecies } from "#data/data-lists"; import type { Egg } from "#data/egg"; import { pokemonFormChanges } from "#data/pokemon-forms"; import type { PokemonSpecies } from "#data/pokemon-species"; +import { loadPositionalTag } from "#data/positional-tags/load-positional-tag"; import { TerrainType } from "#data/terrain"; import { AbilityAttr } from "#enums/ability-attr"; import { BattleType } from "#enums/battle-type"; @@ -1096,6 +1097,10 @@ export class GameData { } } + globalScene.arena.positionalTagManager.tags = sessionData.arena.positionalTags.map(tag => + loadPositionalTag(tag), + ); + if (globalScene.modifiers.length) { console.warn("Existing modifiers not cleared on session load, deleting..."); globalScene.modifiers = []; diff --git a/src/ui/challenges-select-ui-handler.ts b/src/ui/challenges-select-ui-handler.ts index 4f205d59de8..4a7ab7641a3 100644 --- a/src/ui/challenges-select-ui-handler.ts +++ b/src/ui/challenges-select-ui-handler.ts @@ -382,8 +382,7 @@ export class GameChallengesUiHandler extends UiHandler { this.cursorObj?.setVisible(true); this.updateChallengeArrows(this.startCursor.visible); } else { - globalScene.phaseManager.clearPhaseQueue(); - globalScene.phaseManager.pushNew("TitlePhase"); + globalScene.phaseManager.toTitleScreen(); globalScene.phaseManager.getCurrentPhase()?.end(); } success = true; diff --git a/src/ui/form-modal-ui-handler.ts b/src/ui/form-modal-ui-handler.ts index 7ae545a7292..203d98a86c7 100644 --- a/src/ui/form-modal-ui-handler.ts +++ b/src/ui/form-modal-ui-handler.ts @@ -72,6 +72,10 @@ export abstract class FormModalUiHandler extends ModalUiHandler { (hasTitle ? 31 : 5) + 20 * (config.length - 1) + 16 + this.getButtonTopMargin(), "", TextStyle.TOOLTIP_CONTENT, + { + fontSize: "42px", + wordWrap: { width: 850 }, + }, ); this.errorMessage.setColor(this.getTextColor(TextStyle.SUMMARY_PINK)); this.errorMessage.setShadowColor(this.getTextColor(TextStyle.SUMMARY_PINK, true)); @@ -84,20 +88,28 @@ export abstract class FormModalUiHandler extends ModalUiHandler { this.inputs = []; this.formLabels = []; fieldsConfig.forEach((config, f) => { - const label = addTextObject(10, (hasTitle ? 31 : 5) + 20 * f, config.label, TextStyle.TOOLTIP_CONTENT); + // The Pokédex Scan Window uses width `300` instead of `160` like the other forms + // Therefore, the label does not need to be shortened + const label = addTextObject( + 10, + (hasTitle ? 31 : 5) + 20 * f, + config.label.length > 25 && this.getWidth() < 200 ? config.label.slice(0, 20) + "..." : config.label, + TextStyle.TOOLTIP_CONTENT, + ); label.name = "formLabel" + f; this.formLabels.push(label); this.modalContainer.add(this.formLabels[this.formLabels.length - 1]); - const inputContainer = globalScene.add.container(70, (hasTitle ? 28 : 2) + 20 * f); + const inputWidth = label.width < 320 ? 80 : 80 - (label.width - 320) / 5.5; + const inputContainer = globalScene.add.container(70 + (80 - inputWidth), (hasTitle ? 28 : 2) + 20 * f); inputContainer.setVisible(false); - const inputBg = addWindow(0, 0, 80, 16, false, false, 0, 0, WindowVariant.XTHIN); + const inputBg = addWindow(0, 0, inputWidth, 16, false, false, 0, 0, WindowVariant.XTHIN); const isPassword = config?.isPassword; const isReadOnly = config?.isReadOnly; - const input = addTextInputObject(4, -2, 440, 116, TextStyle.TOOLTIP_CONTENT, { + const input = addTextInputObject(4, -2, inputWidth * 5.5, 116, TextStyle.TOOLTIP_CONTENT, { type: isPassword ? "password" : "text", maxLength: isPassword ? 64 : 20, readOnly: isReadOnly, diff --git a/src/ui/modal-ui-handler.ts b/src/ui/modal-ui-handler.ts index c93b713831e..228d80968b9 100644 --- a/src/ui/modal-ui-handler.ts +++ b/src/ui/modal-ui-handler.ts @@ -152,7 +152,12 @@ export abstract class ModalUiHandler extends UiHandler { updateContainer(config?: ModalConfig): void { const [marginTop, marginRight, marginBottom, marginLeft] = this.getMargin(config); - const [width, height] = [this.getWidth(config), this.getHeight(config)]; + /** + * If the total amount of characters for the 2 buttons exceeds ~30 characters, + * the width in `registration-form-ui-handler.ts` and `login-form-ui-handler.ts` needs to be increased. + */ + const width = this.getWidth(config); + const height = this.getHeight(config); this.modalContainer.setPosition( (globalScene.game.canvas.width / 6 - (width + (marginRight - marginLeft))) / 2, (-globalScene.game.canvas.height / 6 - (height + (marginBottom - marginTop))) / 2, @@ -166,10 +171,14 @@ export abstract class ModalUiHandler extends UiHandler { this.titleText.setX(width / 2); this.titleText.setVisible(!!title); - for (let b = 0; b < this.buttonContainers.length; b++) { - const sliceWidth = width / (this.buttonContainers.length + 1); - - this.buttonContainers[b].setPosition(sliceWidth * (b + 1), this.modalBg.height - (this.buttonBgs[b].height + 8)); + if (this.buttonContainers.length > 0) { + const spacing = 12; + const totalWidth = this.buttonBgs.reduce((sum, bg) => sum + bg.width, 0) + spacing * (this.buttonBgs.length - 1); + let x = (this.modalBg.width - totalWidth) / 2; + this.buttonContainers.forEach((container, i) => { + container.setPosition(x + this.buttonBgs[i].width / 2, this.modalBg.height - (this.buttonBgs[i].height + 8)); + x += this.buttonBgs[i].width + spacing; + }); } } diff --git a/src/ui/pokedex-scan-ui-handler.ts b/src/ui/pokedex-scan-ui-handler.ts index bcf869f6f39..ab3258a03de 100644 --- a/src/ui/pokedex-scan-ui-handler.ts +++ b/src/ui/pokedex-scan-ui-handler.ts @@ -158,8 +158,11 @@ export class PokedexScanUiHandler extends FormModalUiHandler { if (super.show(args)) { const config = args[0] as ModalConfig; - this.inputs[0].resize(1150, 116); - this.inputContainers[0].list[0].width = 200; + const label = this.formLabels[0]; + + const inputWidth = label.width < 420 ? 200 : 200 - (label.width - 420) / 5.75; + this.inputs[0].resize(inputWidth * 5.75, 116); + this.inputContainers[0].list[0].width = inputWidth; if (args[1] && typeof (args[1] as PlayerPokemon).getNameToRender === "function") { this.inputs[0].text = (args[1] as PlayerPokemon).getNameToRender(); } else { diff --git a/src/ui/registration-form-ui-handler.ts b/src/ui/registration-form-ui-handler.ts index 60f8d1d987f..2c8080d534d 100644 --- a/src/ui/registration-form-ui-handler.ts +++ b/src/ui/registration-form-ui-handler.ts @@ -8,19 +8,6 @@ import type { ModalConfig } from "#ui/modal-ui-handler"; import { addTextObject } from "#ui/text"; import i18next from "i18next"; -interface LanguageSetting { - inputFieldFontSize?: string; - warningMessageFontSize?: string; - errorMessageFontSize?: string; -} - -const languageSettings: { [key: string]: LanguageSetting } = { - "es-ES": { - inputFieldFontSize: "50px", - errorMessageFontSize: "40px", - }, -}; - export class RegistrationFormUiHandler extends FormModalUiHandler { getModalTitle(_config?: ModalConfig): string { return i18next.t("menu:register"); @@ -35,7 +22,7 @@ export class RegistrationFormUiHandler extends FormModalUiHandler { } getButtonTopMargin(): number { - return 8; + return 12; } getButtonLabels(_config?: ModalConfig): string[] { @@ -76,18 +63,9 @@ export class RegistrationFormUiHandler extends FormModalUiHandler { setup(): void { super.setup(); - this.modalContainer.list.forEach((child: Phaser.GameObjects.GameObject) => { - if (child instanceof Phaser.GameObjects.Text && child !== this.titleText) { - const inputFieldFontSize = languageSettings[i18next.resolvedLanguage!]?.inputFieldFontSize; - if (inputFieldFontSize) { - child.setFontSize(inputFieldFontSize); - } - } - }); - - const warningMessageFontSize = languageSettings[i18next.resolvedLanguage!]?.warningMessageFontSize ?? "42px"; const label = addTextObject(10, 87, i18next.t("menu:registrationAgeWarning"), TextStyle.TOOLTIP_CONTENT, { - fontSize: warningMessageFontSize, + fontSize: "42px", + wordWrap: { width: 850 }, }); this.modalContainer.add(label); @@ -107,10 +85,6 @@ export class RegistrationFormUiHandler extends FormModalUiHandler { const onFail = error => { globalScene.ui.setMode(UiMode.REGISTRATION_FORM, Object.assign(config, { errorMessage: error?.trim() })); globalScene.ui.playError(); - const errorMessageFontSize = languageSettings[i18next.resolvedLanguage!]?.errorMessageFontSize; - if (errorMessageFontSize) { - this.errorMessage.setFontSize(errorMessageFontSize); - } }; if (!this.inputs[0].text) { return onFail(i18next.t("menu:emptyUsername")); diff --git a/src/ui/starter-select-ui-handler.ts b/src/ui/starter-select-ui-handler.ts index 5650e777a80..6929d6f818d 100644 --- a/src/ui/starter-select-ui-handler.ts +++ b/src/ui/starter-select-ui-handler.ts @@ -4307,7 +4307,10 @@ export class StarterSelectUiHandler extends MessageUiHandler { return true; } - tryExit(): boolean { + /** + * Attempt to back out of the starter selection screen into the appropriate parent modal + */ + tryExit(): void { this.blockInput = true; const ui = this.getUi(); @@ -4321,12 +4324,13 @@ export class StarterSelectUiHandler extends MessageUiHandler { UiMode.CONFIRM, () => { ui.setMode(UiMode.STARTER_SELECT); - globalScene.phaseManager.clearPhaseQueue(); - if (globalScene.gameMode.isChallenge) { + // Non-challenge modes go directly back to title, while challenge modes go to the selection screen. + if (!globalScene.gameMode.isChallenge) { + globalScene.phaseManager.toTitleScreen(); + } else { + globalScene.phaseManager.clearPhaseQueue(); globalScene.phaseManager.pushNew("SelectChallengePhase"); globalScene.phaseManager.pushNew("EncounterPhase"); - } else { - globalScene.phaseManager.pushNew("TitlePhase"); } this.clearText(); globalScene.phaseManager.getCurrentPhase()?.end(); @@ -4337,8 +4341,6 @@ export class StarterSelectUiHandler extends MessageUiHandler { 19, ); }); - - return true; } tryStart(manualTrigger = false): boolean { diff --git a/src/utils/enums.ts b/src/utils/enums.ts index 98cb4272ee9..25ee864794c 100644 --- a/src/utils/enums.ts +++ b/src/utils/enums.ts @@ -1,5 +1,5 @@ -import type { EnumOrObject, EnumValues, NormalEnum, TSNumericEnum } from "#app/@types/enum-types"; -import type { InferKeys } from "#app/@types/type-helpers"; +import type { EnumOrObject, NormalEnum, TSNumericEnum } from "#types/enum-types"; +import type { InferKeys, ObjectValues } from "#types/type-helpers"; /** * Return the string keys of an Enum object, excluding reverse-mapped numbers. @@ -61,7 +61,7 @@ export function getEnumValues(enumType: TSNumericEnum * If multiple keys map to the same value, the first one (in insertion order) will be retrieved, * but the return type will be the union of ALL their corresponding keys. */ -export function enumValueToKey>( +export function enumValueToKey>( object: NormalEnum, val: V, ): InferKeys { diff --git a/test/moves/delayed-attack.test.ts b/test/moves/delayed-attack.test.ts new file mode 100644 index 00000000000..e8cf2871626 --- /dev/null +++ b/test/moves/delayed-attack.test.ts @@ -0,0 +1,389 @@ +import { getPokemonNameWithAffix } from "#app/messages"; +import { AttackTypeBoosterModifier } from "#app/modifier/modifier"; +import { allMoves } from "#data/data-lists"; +import { AbilityId } from "#enums/ability-id"; +import { BattleType } from "#enums/battle-type"; +import { BattlerIndex } from "#enums/battler-index"; +import { MoveId } from "#enums/move-id"; +import { MoveResult } from "#enums/move-result"; +import { PokemonType } from "#enums/pokemon-type"; +import { PositionalTagType } from "#enums/positional-tag-type"; +import { SpeciesId } from "#enums/species-id"; +import { Stat } from "#enums/stat"; +import { GameManager } from "#test/test-utils/game-manager"; +import i18next from "i18next"; +import Phaser from "phaser"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; + +describe("Moves - Delayed Attacks", () => { + let phaserGame: Phaser.Game; + let game: GameManager; + + beforeAll(() => { + phaserGame = new Phaser.Game({ + type: Phaser.HEADLESS, + }); + }); + + afterEach(() => { + game.phaseInterceptor.restoreOg(); + }); + + beforeEach(() => { + game = new GameManager(phaserGame); + game.override + .ability(AbilityId.NO_GUARD) + .battleStyle("single") + .enemySpecies(SpeciesId.MAGIKARP) + .enemyAbility(AbilityId.STURDY) + .enemyMoveset(MoveId.SPLASH); + }); + + /** + * Wait until a number of turns have passed. + * @param numTurns - Number of turns to pass. + * @param toEndOfTurn - Whether to advance to the `TurnEndPhase` (`true`) or the `PositionalTagPhase` (`false`); + * default `true` + * @returns A Promise that resolves once the specified number of turns has elapsed + * and the specified phase has been reached. + */ + async function passTurns(numTurns: number, toEndOfTurn = true): Promise { + for (let i = 0; i < numTurns; i++) { + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER); + if (game.scene.getPlayerField()[1]?.isActive()) { + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER_2); + } + await game.move.forceEnemyMove(MoveId.SPLASH); + if (game.scene.getEnemyField()[1]?.isActive()) { + await game.move.forceEnemyMove(MoveId.SPLASH); + } + await game.phaseInterceptor.to("PositionalTagPhase"); + } + if (toEndOfTurn) { + await game.toEndOfTurn(); + } + } + + /** + * Expect that future sight is active with the specified number of attacks. + * @param numAttacks - The number of delayed attacks that should be queued; default `1` + */ + function expectFutureSightActive(numAttacks = 1) { + const delayedAttacks = game.scene.arena.positionalTagManager["tags"].filter( + t => t.tagType === PositionalTagType.DELAYED_ATTACK, + ); + expect(delayedAttacks).toHaveLength(numAttacks); + } + + it.each<{ name: string; move: MoveId }>([ + { name: "Future Sight", move: MoveId.FUTURE_SIGHT }, + { name: "Doom Desire", move: MoveId.DOOM_DESIRE }, + ])("$name should show message and strike 2 turns after use, ignoring player/enemy switches", async ({ move }) => { + game.override.battleType(BattleType.TRAINER); + await game.classicMode.startBattle([SpeciesId.FEEBAS, SpeciesId.MILOTIC]); + + game.move.use(move); + await game.toNextTurn(); + + expectFutureSightActive(); + + game.doSwitchPokemon(1); + game.forceEnemyToSwitch(); + await game.toNextTurn(); + + await passTurns(1); + + expectFutureSightActive(0); + const enemy = game.field.getEnemyPokemon(); + expect(enemy.hp).toBeLessThan(enemy.getMaxHp()); + expect(game.textInterceptor.logs).toContain( + i18next.t("moveTriggers:tookMoveAttack", { + pokemonName: getPokemonNameWithAffix(enemy), + moveName: allMoves[move].name, + }), + ); + }); + + it("should fail (preserving prior instances) when used against the same target", async () => { + await game.classicMode.startBattle([SpeciesId.BRONZONG]); + + game.move.use(MoveId.FUTURE_SIGHT); + await game.toNextTurn(); + + expectFutureSightActive(); + const bronzong = game.field.getPlayerPokemon(); + expect(bronzong.getLastXMoves()[0].result).toBe(MoveResult.OTHER); + + game.move.use(MoveId.FUTURE_SIGHT); + await game.toNextTurn(); + + expectFutureSightActive(); + expect(bronzong.getLastXMoves()[0].result).toBe(MoveResult.FAIL); + }); + + it("should still be delayed when called by other moves", async () => { + await game.classicMode.startBattle([SpeciesId.BRONZONG]); + + game.move.use(MoveId.METRONOME); + game.move.forceMetronomeMove(MoveId.FUTURE_SIGHT); + await game.toNextTurn(); + + expectFutureSightActive(); + const enemy = game.field.getEnemyPokemon(); + expect(enemy.hp).toBe(enemy.getMaxHp()); + + await passTurns(2); + + expectFutureSightActive(0); + expect(enemy.hp).toBeLessThan(enemy.getMaxHp()); + }); + + it("should work when used against different targets in doubles", async () => { + game.override.battleStyle("double"); + await game.classicMode.startBattle([SpeciesId.MAGIKARP, SpeciesId.FEEBAS]); + + const [karp, feebas, enemy1, enemy2] = game.scene.getField(); + + game.move.use(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER, BattlerIndex.ENEMY); + game.move.use(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER_2, BattlerIndex.ENEMY_2); + await game.toEndOfTurn(); + + expectFutureSightActive(2); + expect(enemy1.hp).toBe(enemy1.getMaxHp()); + expect(enemy2.hp).toBe(enemy2.getMaxHp()); + expect(karp.getLastXMoves()[0].result).toBe(MoveResult.OTHER); + expect(feebas.getLastXMoves()[0].result).toBe(MoveResult.OTHER); + + await passTurns(2); + + expect(enemy1.hp).toBeLessThan(enemy1.getMaxHp()); + expect(enemy2.hp).toBeLessThan(enemy2.getMaxHp()); + }); + + it("should trigger multiple pending attacks in order of creation, even if that order changes later on", async () => { + game.override.battleStyle("double"); + await game.classicMode.startBattle([SpeciesId.MAGIKARP, SpeciesId.FEEBAS]); + + const [alomomola, blissey] = game.scene.getField(); + + const oldOrder = game.field.getSpeedOrder(); + + game.move.use(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER, BattlerIndex.ENEMY); + game.move.use(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER_2, BattlerIndex.ENEMY_2); + await game.move.forceEnemyMove(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER); + await game.move.forceEnemyMove(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER_2); + // Ensure that the moves are used deterministically in speed order (for speed ties) + await game.setTurnOrder(oldOrder.map(p => p.getBattlerIndex())); + await game.toNextTurn(); + + expectFutureSightActive(4); + + // Lower speed to change turn order + alomomola.setStatStage(Stat.SPD, 6); + blissey.setStatStage(Stat.SPD, -6); + + const newOrder = game.field.getSpeedOrder(); + expect(newOrder).not.toEqual(oldOrder); + + await passTurns(2, false); + + // All attacks have concluded at this point, unshifting new `MoveEffectPhase`s to the queue. + expectFutureSightActive(0); + + const MEPs = game.scene.phaseManager.phaseQueue.filter(p => p.is("MoveEffectPhase")); + expect(MEPs).toHaveLength(4); + expect(MEPs.map(mep => mep.getPokemon())).toEqual(oldOrder); + }); + + it("should vanish silently if it would otherwise hit the user", async () => { + game.override.battleStyle("double"); + await game.classicMode.startBattle([SpeciesId.MAGIKARP, SpeciesId.FEEBAS, SpeciesId.MILOTIC]); + + const [karp, feebas, milotic] = game.scene.getPlayerParty(); + + game.move.use(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER, BattlerIndex.PLAYER_2); + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER_2); + await game.toNextTurn(); + + expectFutureSightActive(1); + + // Milotic / Feebas // Karp + game.doSwitchPokemon(2); + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER_2); + await game.toNextTurn(); + + expect(game.scene.getPlayerParty()).toEqual([milotic, feebas, karp]); + + // Milotic / Karp // Feebas + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER); + game.doSwitchPokemon(2); + + await passTurns(1); + + expect(game.scene.getPlayerParty()).toEqual([milotic, karp, feebas]); + + expect(karp.hp).toBe(karp.getMaxHp()); + expect(feebas.hp).toBe(feebas.getMaxHp()); + expect(game.textInterceptor.logs).not.toContain( + i18next.t("moveTriggers:tookMoveAttack", { + pokemonName: getPokemonNameWithAffix(karp), + moveName: allMoves[MoveId.FUTURE_SIGHT].name, + }), + ); + }); + + it("should redirect normally if target is fainted when move is used", async () => { + game.override.battleStyle("double"); + await game.classicMode.startBattle([SpeciesId.MAGIKARP]); + + const [enemy1, enemy2] = game.scene.getEnemyField(); + + game.move.use(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER, BattlerIndex.ENEMY_2); + await game.killPokemon(enemy2); + await game.toNextTurn(); + + expect(enemy2.isFainted()).toBe(true); + expectFutureSightActive(); + + const attack = game.scene.arena.positionalTagManager.tags.find( + t => t.tagType === PositionalTagType.DELAYED_ATTACK, + )!; + expect(attack).toBeDefined(); + expect(attack.targetIndex).toBe(enemy1.getBattlerIndex()); + + await passTurns(2); + + expect(enemy1.hp).toBeLessThan(enemy1.getMaxHp()); + expect(game.textInterceptor.logs).toContain( + i18next.t("moveTriggers:tookMoveAttack", { + pokemonName: getPokemonNameWithAffix(enemy1), + moveName: allMoves[MoveId.FUTURE_SIGHT].name, + }), + ); + }); + + it("should vanish silently if slot is vacant when attack lands", async () => { + game.override.battleStyle("double"); + await game.classicMode.startBattle([SpeciesId.MAGIKARP]); + + const [enemy1, enemy2] = game.scene.getEnemyField(); + + game.move.use(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER, BattlerIndex.ENEMY_2); + await game.toNextTurn(); + + expectFutureSightActive(1); + + game.move.use(MoveId.SPLASH); + await game.killPokemon(enemy2); + await game.toNextTurn(); + + game.move.use(MoveId.SPLASH); + await game.toNextTurn(); + + expectFutureSightActive(0); + expect(enemy1.hp).toBe(enemy1.getMaxHp()); + expect(game.textInterceptor.logs).not.toContain( + i18next.t("moveTriggers:tookMoveAttack", { + pokemonName: getPokemonNameWithAffix(enemy1), + moveName: allMoves[MoveId.FUTURE_SIGHT].name, + }), + ); + }); + + it("should consider type changes at moment of execution while ignoring redirection", async () => { + game.override.battleStyle("double"); + await game.classicMode.startBattle([SpeciesId.MAGIKARP]); + + // fake left enemy having lightning rod + const [enemy1, enemy2] = game.scene.getEnemyField(); + game.field.mockAbility(enemy1, AbilityId.LIGHTNING_ROD); + + game.move.use(MoveId.FUTURE_SIGHT, BattlerIndex.PLAYER, BattlerIndex.ENEMY_2); + await game.toNextTurn(); + + expectFutureSightActive(1); + + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER); + await game.toNextTurn(); + + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER); + await game.move.forceEnemyMove(MoveId.ELECTRIFY, BattlerIndex.PLAYER); + await game.phaseInterceptor.to("PositionalTagPhase"); + await game.phaseInterceptor.to("MoveEffectPhase", false); + + // Wait until all normal attacks have triggered, then check pending MEP + const karp = game.field.getPlayerPokemon(); + const typeMock = vi.spyOn(karp, "getMoveType"); + + await game.toEndOfTurn(); + + expect(enemy1.hp).toBe(enemy1.getMaxHp()); + expect(enemy2.hp).toBeLessThan(enemy2.getMaxHp()); + expect(game.textInterceptor.logs).toContain( + i18next.t("moveTriggers:tookMoveAttack", { + pokemonName: getPokemonNameWithAffix(enemy2), + moveName: allMoves[MoveId.FUTURE_SIGHT].name, + }), + ); + expect(typeMock).toHaveLastReturnedWith(PokemonType.ELECTRIC); + }); + + // TODO: this is not implemented + it.todo("should not apply Shell Bell recovery, even if user is on field"); + + // TODO: Enable once code is added to MEP to do this + it.todo("should not apply the user's abilities when dealing damage if the user is inactive", async () => { + game.override.ability(AbilityId.NORMALIZE).enemySpecies(SpeciesId.LUNALA); + await game.classicMode.startBattle([SpeciesId.FEEBAS, SpeciesId.MILOTIC]); + + game.move.use(MoveId.DOOM_DESIRE); + await game.toNextTurn(); + + expectFutureSightActive(); + + await passTurns(1); + + game.doSwitchPokemon(1); + const typeMock = vi.spyOn(game.field.getPlayerPokemon(), "getMoveType"); + const powerMock = vi.spyOn(allMoves[MoveId.DOOM_DESIRE], "calculateBattlePower"); + + await game.toNextTurn(); + + // Player Normalize was not applied due to being off field + const enemy = game.field.getEnemyPokemon(); + expect(enemy.hp).toBeLessThan(enemy.getMaxHp()); + expect(game.textInterceptor.logs).toContain( + i18next.t("moveTriggers:tookMoveAttack", { + pokemonName: getPokemonNameWithAffix(enemy), + moveName: allMoves[MoveId.DOOM_DESIRE].name, + }), + ); + expect(typeMock).toHaveLastReturnedWith(PokemonType.STEEL); + expect(powerMock).toHaveLastReturnedWith(150); + }); + + it.todo("should not apply the user's held items when dealing damage if the user is inactive", async () => { + game.override.startingHeldItems([{ name: "ATTACK_TYPE_BOOSTER", count: 99, type: PokemonType.PSYCHIC }]); + await game.classicMode.startBattle([SpeciesId.FEEBAS, SpeciesId.MILOTIC]); + + game.move.use(MoveId.FUTURE_SIGHT); + await game.toNextTurn(); + + expectFutureSightActive(); + + await passTurns(1); + + game.doSwitchPokemon(1); + + const powerMock = vi.spyOn(allMoves[MoveId.FUTURE_SIGHT], "calculateBattlePower"); + const typeBoostSpy = vi.spyOn(AttackTypeBoosterModifier.prototype, "apply"); + + await game.toNextTurn(); + + expect(powerMock).toHaveLastReturnedWith(120); + expect(typeBoostSpy).not.toHaveBeenCalled(); + }); + + // TODO: Implement and move to a power spot's test file + it.todo("Should activate ally's power spot when switched in during single battles"); +}); diff --git a/test/moves/future-sight.test.ts b/test/moves/future-sight.test.ts deleted file mode 100644 index 53e93412570..00000000000 --- a/test/moves/future-sight.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { AbilityId } from "#enums/ability-id"; -import { MoveId } from "#enums/move-id"; -import { SpeciesId } from "#enums/species-id"; -import { GameManager } from "#test/test-utils/game-manager"; -import Phaser from "phaser"; -import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; - -describe("Moves - Future Sight", () => { - let phaserGame: Phaser.Game; - let game: GameManager; - - beforeAll(() => { - phaserGame = new Phaser.Game({ - type: Phaser.HEADLESS, - }); - }); - - afterEach(() => { - game.phaseInterceptor.restoreOg(); - }); - - beforeEach(() => { - game = new GameManager(phaserGame); - game.override - .startingLevel(50) - .moveset([MoveId.FUTURE_SIGHT, MoveId.SPLASH]) - .battleStyle("single") - .enemySpecies(SpeciesId.MAGIKARP) - .enemyAbility(AbilityId.STURDY) - .enemyMoveset(MoveId.SPLASH); - }); - - it("hits 2 turns after use, ignores user switch out", async () => { - await game.classicMode.startBattle([SpeciesId.FEEBAS, SpeciesId.MILOTIC]); - - game.move.select(MoveId.FUTURE_SIGHT); - await game.toNextTurn(); - game.doSwitchPokemon(1); - await game.toNextTurn(); - game.move.select(MoveId.SPLASH); - await game.toNextTurn(); - - expect(game.scene.getEnemyPokemon()!.isFullHp()).toBe(false); - }); -}); diff --git a/test/moves/heal-block.test.ts b/test/moves/heal-block.test.ts index 4e4a9355467..fc814fda4bc 100644 --- a/test/moves/heal-block.test.ts +++ b/test/moves/heal-block.test.ts @@ -1,9 +1,8 @@ import { AbilityId } from "#enums/ability-id"; -import { ArenaTagSide } from "#enums/arena-tag-side"; -import { ArenaTagType } from "#enums/arena-tag-type"; import { BattlerIndex } from "#enums/battler-index"; import { BattlerTagType } from "#enums/battler-tag-type"; import { MoveId } from "#enums/move-id"; +import { PositionalTagType } from "#enums/positional-tag-type"; import { SpeciesId } from "#enums/species-id"; import { WeatherType } from "#enums/weather-type"; import { GameManager } from "#test/test-utils/game-manager"; @@ -68,22 +67,25 @@ describe("Moves - Heal Block", () => { expect(enemy.isFullHp()).toBe(false); }); - it("should stop delayed heals, such as from Wish", async () => { + it("should prevent Wish from restoring HP", async () => { await game.classicMode.startBattle([SpeciesId.CHARIZARD]); - const player = game.scene.getPlayerPokemon()!; + const player = game.field.getPlayerPokemon()!; - player.damageAndUpdate(player.getMaxHp() - 1); + player.hp = 1; - game.move.select(MoveId.WISH); - await game.phaseInterceptor.to("TurnEndPhase"); + game.move.use(MoveId.WISH); + await game.toNextTurn(); - expect(game.scene.arena.getTagOnSide(ArenaTagType.WISH, ArenaTagSide.PLAYER)).toBeDefined(); - while (game.scene.arena.getTagOnSide(ArenaTagType.WISH, ArenaTagSide.PLAYER)) { - game.move.select(MoveId.SPLASH); - await game.phaseInterceptor.to("TurnEndPhase"); - } + expect(game.scene.arena.positionalTagManager.tags.filter(t => t.tagType === PositionalTagType.WISH)) // + .toHaveLength(1); + game.move.use(MoveId.SPLASH); + await game.toNextTurn(); + + // wish triggered, but did NOT heal the player + expect(game.scene.arena.positionalTagManager.tags.filter(t => t.tagType === PositionalTagType.WISH)) // + .toHaveLength(0); expect(player.hp).toBe(1); }); diff --git a/test/moves/order-up.test.ts b/test/moves/order-up.test.ts index 2e77d4b2fa7..2da7cc5daf8 100644 --- a/test/moves/order-up.test.ts +++ b/test/moves/order-up.test.ts @@ -65,23 +65,4 @@ describe("Moves - Order Up", () => { affectedStats.forEach(st => expect(dondozo.getStatStage(st)).toBe(st === stat ? 3 : 2)); }, ); - - it("should be boosted by Sheer Force while still applying a stat boost", async () => { - game.override.passiveAbility(AbilityId.SHEER_FORCE).starterForms({ [SpeciesId.TATSUGIRI]: 0 }); - - await game.classicMode.startBattle([SpeciesId.TATSUGIRI, SpeciesId.DONDOZO]); - - const [tatsugiri, dondozo] = game.scene.getPlayerField(); - - expect(game.scene.triggerPokemonBattleAnim).toHaveBeenLastCalledWith(tatsugiri, PokemonAnimType.COMMANDER_APPLY); - expect(dondozo.getTag(BattlerTagType.COMMANDED)).toBeDefined(); - - game.move.select(MoveId.ORDER_UP, 1, BattlerIndex.ENEMY); - expect(game.scene.currentBattle.turnCommands[0]?.skip).toBeTruthy(); - - await game.phaseInterceptor.to("BerryPhase", false); - - expect(dondozo.waveData.abilitiesApplied.has(AbilityId.SHEER_FORCE)).toBeTruthy(); - expect(dondozo.getStatStage(Stat.ATK)).toBe(3); - }); }); diff --git a/test/moves/wish.test.ts b/test/moves/wish.test.ts new file mode 100644 index 00000000000..147c598106b --- /dev/null +++ b/test/moves/wish.test.ts @@ -0,0 +1,183 @@ +import { getPokemonNameWithAffix } from "#app/messages"; +import { AbilityId } from "#enums/ability-id"; +import { BattlerIndex } from "#enums/battler-index"; +import { MoveId } from "#enums/move-id"; +import { MoveResult } from "#enums/move-result"; +import { PositionalTagType } from "#enums/positional-tag-type"; +import { SpeciesId } from "#enums/species-id"; +import { Stat } from "#enums/stat"; +import { GameManager } from "#test/test-utils/game-manager"; +import { toDmgValue } from "#utils/common"; +import i18next from "i18next"; +import Phaser from "phaser"; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; + +describe("Move - Wish", () => { + let phaserGame: Phaser.Game; + let game: GameManager; + + beforeAll(() => { + phaserGame = new Phaser.Game({ + type: Phaser.HEADLESS, + }); + }); + + afterEach(() => { + game.phaseInterceptor.restoreOg(); + }); + + beforeEach(() => { + game = new GameManager(phaserGame); + game.override + .ability(AbilityId.BALL_FETCH) + .battleStyle("single") + .criticalHits(false) + .enemySpecies(SpeciesId.MAGIKARP) + .enemyAbility(AbilityId.BALL_FETCH) + .enemyMoveset(MoveId.SPLASH) + .startingLevel(100) + .enemyLevel(100); + }); + + /** + * Expect that wish is active with the specified number of attacks. + * @param numAttacks - The number of wish instances that should be queued; default `1` + */ + function expectWishActive(numAttacks = 1) { + const wishes = game.scene.arena.positionalTagManager["tags"].filter(t => t.tagType === PositionalTagType.WISH); + expect(wishes).toHaveLength(numAttacks); + } + + it("should heal the Pokemon in the current slot for 50% of the user's maximum HP", async () => { + await game.classicMode.startBattle([SpeciesId.ALOMOMOLA, SpeciesId.BLISSEY]); + + const [alomomola, blissey] = game.scene.getPlayerParty(); + alomomola.hp = 1; + blissey.hp = 1; + + game.move.use(MoveId.WISH); + await game.toNextTurn(); + + expectWishActive(); + + game.doSwitchPokemon(1); + await game.toEndOfTurn(); + + expectWishActive(0); + expect(game.textInterceptor.logs).toContain( + i18next.t("arenaTag:wishTagOnAdd", { + pokemonNameWithAffix: getPokemonNameWithAffix(alomomola), + }), + ); + expect(alomomola.hp).toBe(1); + expect(blissey.hp).toBe(toDmgValue(alomomola.getMaxHp() / 2) + 1); + }); + + it("should work if the user has full HP, but not if it already has an active Wish", async () => { + await game.classicMode.startBattle([SpeciesId.ALOMOMOLA, SpeciesId.BLISSEY]); + + const alomomola = game.field.getPlayerPokemon(); + alomomola.hp = 1; + + game.move.use(MoveId.WISH); + await game.toNextTurn(); + + expectWishActive(); + + game.move.use(MoveId.WISH); + await game.toEndOfTurn(); + + expect(alomomola.hp).toBe(toDmgValue(alomomola.getMaxHp() / 2) + 1); + expect(alomomola.getLastXMoves()[0].result).toBe(MoveResult.FAIL); + }); + + it("should function independently of Future Sight", async () => { + await game.classicMode.startBattle([SpeciesId.ALOMOMOLA, SpeciesId.BLISSEY]); + + const [alomomola, blissey] = game.scene.getPlayerParty(); + alomomola.hp = 1; + blissey.hp = 1; + + game.move.use(MoveId.WISH); + await game.move.forceEnemyMove(MoveId.FUTURE_SIGHT); + await game.setTurnOrder([BattlerIndex.ENEMY, BattlerIndex.PLAYER]); + await game.toNextTurn(); + + expectWishActive(1); + }); + + it("should work in double battles and trigger in order of creation", async () => { + game.override.battleStyle("double"); + await game.classicMode.startBattle([SpeciesId.ALOMOMOLA, SpeciesId.BLISSEY]); + + const [alomomola, blissey, karp1, karp2] = game.scene.getField(); + alomomola.hp = 1; + blissey.hp = 1; + + vi.spyOn(karp1, "getNameToRender").mockReturnValue("Karp 1"); + vi.spyOn(karp2, "getNameToRender").mockReturnValue("Karp 2"); + + const oldOrder = game.field.getSpeedOrder(); + + game.move.use(MoveId.WISH, BattlerIndex.PLAYER); + game.move.use(MoveId.WISH, BattlerIndex.PLAYER_2); + await game.move.forceEnemyMove(MoveId.WISH); + await game.move.forceEnemyMove(MoveId.WISH); + // Ensure that the wishes are used deterministically in speed order (for speed ties) + await game.setTurnOrder(oldOrder.map(p => p.getBattlerIndex())); + await game.toNextTurn(); + + expectWishActive(4); + + // Lower speed to change turn order + alomomola.setStatStage(Stat.SPD, 6); + blissey.setStatStage(Stat.SPD, -6); + + const newOrder = game.field.getSpeedOrder(); + expect(newOrder).not.toEqual(oldOrder); + + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER); + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER_2); + await game.phaseInterceptor.to("PositionalTagPhase"); + + // all wishes have activated and added healing phases + expectWishActive(0); + + const healPhases = game.scene.phaseManager.phaseQueue.filter(p => p.is("PokemonHealPhase")); + expect(healPhases).toHaveLength(4); + expect.soft(healPhases.map(php => php.getPokemon())).toEqual(oldOrder); + + await game.toEndOfTurn(); + + expect(alomomola.hp).toBe(toDmgValue(alomomola.getMaxHp() / 2) + 1); + expect(blissey.hp).toBe(toDmgValue(blissey.getMaxHp() / 2) + 1); + }); + + it("should vanish and not play message if slot is empty", async () => { + game.override.battleStyle("double"); + await game.classicMode.startBattle([SpeciesId.ALOMOMOLA, SpeciesId.BLISSEY]); + + const [alomomola, blissey] = game.scene.getPlayerParty(); + alomomola.hp = 1; + blissey.hp = 1; + + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER); + game.move.use(MoveId.WISH, BattlerIndex.PLAYER_2); + await game.toNextTurn(); + + expectWishActive(); + + game.move.use(MoveId.SPLASH, BattlerIndex.PLAYER); + game.move.use(MoveId.MEMENTO, BattlerIndex.PLAYER_2, BattlerIndex.ENEMY_2); + await game.toEndOfTurn(); + + // Wish went away without doing anything + expectWishActive(0); + expect(game.textInterceptor.logs).not.toContain( + i18next.t("arenaTag:wishTagOnAdd", { + pokemonNameWithAffix: getPokemonNameWithAffix(blissey), + }), + ); + expect(alomomola.hp).toBe(1); + }); +}); diff --git a/test/mystery-encounter/encounters/global-trade-system-encounter.test.ts b/test/mystery-encounter/encounters/global-trade-system-encounter.test.ts index 2ac55dabe1c..867a33f6ab6 100644 --- a/test/mystery-encounter/encounters/global-trade-system-encounter.test.ts +++ b/test/mystery-encounter/encounters/global-trade-system-encounter.test.ts @@ -93,7 +93,7 @@ describe("Global Trade System - Mystery Encounter", () => { describe("Option 1 - Check Trade Offers", () => { it("should have the correct properties", () => { const option = GlobalTradeSystemEncounter.options[0]; - expect(option.optionMode).toBe(MysteryEncounterOptionMode.DEFAULT); + expect(option.optionMode).toBe(MysteryEncounterOptionMode.DISABLED_OR_DEFAULT); expect(option.dialogue).toBeDefined(); expect(option.dialogue).toStrictEqual({ buttonLabel: `${namespace}:option.1.label`, @@ -154,7 +154,7 @@ describe("Global Trade System - Mystery Encounter", () => { describe("Option 2 - Wonder Trade", () => { it("should have the correct properties", () => { const option = GlobalTradeSystemEncounter.options[1]; - expect(option.optionMode).toBe(MysteryEncounterOptionMode.DEFAULT); + expect(option.optionMode).toBe(MysteryEncounterOptionMode.DISABLED_OR_DEFAULT); expect(option.dialogue).toBeDefined(); expect(option.dialogue).toStrictEqual({ buttonLabel: `${namespace}:option.2.label`, diff --git a/test/phases/check-interlude-phase.test.ts b/test/phases/check-interlude-phase.test.ts new file mode 100644 index 00000000000..d5413d1db35 --- /dev/null +++ b/test/phases/check-interlude-phase.test.ts @@ -0,0 +1,63 @@ +import { AbilityId } from "#enums/ability-id"; +import { BerryType } from "#enums/berry-type"; +import { MoveId } from "#enums/move-id"; +import { SpeciesId } from "#enums/species-id"; +import { WeatherType } from "#enums/weather-type"; +import { GameManager } from "#test/test-utils/game-manager"; +import Phaser from "phaser"; +import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; + +describe("Check Biome End Phase", () => { + let phaserGame: Phaser.Game; + let game: GameManager; + + beforeAll(() => { + phaserGame = new Phaser.Game({ + type: Phaser.HEADLESS, + }); + }); + + afterEach(() => { + game.phaseInterceptor.restoreOg(); + }); + + beforeEach(() => { + game = new GameManager(phaserGame); + game.override + .enemySpecies(SpeciesId.MAGIKARP) + .enemyMoveset(MoveId.SPLASH) + .enemyAbility(AbilityId.BALL_FETCH) + .ability(AbilityId.BALL_FETCH) + .startingLevel(100) + .battleStyle("single"); + }); + + it("should not trigger end of turn effects when defeating the final pokemon of a biome in classic", async () => { + game.override + .startingWave(10) + .weather(WeatherType.SANDSTORM) + .startingHeldItems([{ name: "BERRY", type: BerryType.SITRUS }]); + await game.classicMode.startBattle([SpeciesId.FEEBAS]); + + const player = game.field.getPlayerPokemon(); + + player.hp = 1; + + game.move.use(MoveId.EXTREME_SPEED); + await game.toEndOfTurn(); + + expect(player.hp).toBe(1); + }); + + it("should not prevent end of turn effects when transitioning waves within a biome", async () => { + game.override.weather(WeatherType.SANDSTORM); + await game.classicMode.startBattle([SpeciesId.FEEBAS]); + + const player = game.field.getPlayerPokemon(); + + game.move.use(MoveId.EXTREME_SPEED); + await game.toEndOfTurn(); + + expect(player.hp).toBeLessThan(player.getMaxHp()); + }); +}); diff --git a/test/test-utils/game-manager.ts b/test/test-utils/game-manager.ts index b81b077b2f2..23a2e6240f8 100644 --- a/test/test-utils/game-manager.ts +++ b/test/test-utils/game-manager.ts @@ -103,12 +103,9 @@ export class GameManager { if (!firstTimeScene) { this.scene.reset(false, true); (this.scene.ui.handlers[UiMode.STARTER_SELECT] as StarterSelectUiHandler).clearStarterPreferences(); - this.scene.phaseManager.clearAllPhases(); // Must be run after phase interceptor has been initialized. - - this.scene.phaseManager.pushNew("LoginPhase"); - this.scene.phaseManager.pushNew("TitlePhase"); + this.scene.phaseManager.toTitleScreen(true); this.scene.phaseManager.shiftPhase(); this.gameWrapper.scene = this.scene; diff --git a/test/test-utils/helpers/field-helper.ts b/test/test-utils/helpers/field-helper.ts index 35ca853d049..2d8fd8ee701 100644 --- a/test/test-utils/helpers/field-helper.ts +++ b/test/test-utils/helpers/field-helper.ts @@ -5,7 +5,6 @@ import type { globalScene } from "#app/global-scene"; import type { Ability } from "#abilities/ability"; import { allAbilities } from "#data/data-lists"; import type { AbilityId } from "#enums/ability-id"; -import type { BattlerIndex } from "#enums/battler-index"; import type { PokemonType } from "#enums/pokemon-type"; import { Stat } from "#enums/stat"; import type { EnemyPokemon, PlayerPokemon, Pokemon } from "#field/pokemon"; @@ -45,18 +44,21 @@ export class FieldHelper extends GameManagerHelper { } /** - * @returns The {@linkcode BattlerIndex | indexes} of Pokemon on the field in order of decreasing Speed. + * Helper function to return all on-field {@linkcode Pokemon} in speed order (fastest first). + * @returns An array containing all {@linkcode Pokemon} on the field in order of descending Speed. * Speed ties are returned in increasing order of index. * * @remarks * This does not account for Trick Room as it does not modify the _speed_ of Pokemon on the field, * only their turn order. */ - public getSpeedOrder(): BattlerIndex[] { + public getSpeedOrder(): Pokemon[] { return this.game.scene .getField(true) - .sort((pA, pB) => pB.getEffectiveStat(Stat.SPD) - pA.getEffectiveStat(Stat.SPD)) - .map(p => p.getBattlerIndex()); + .sort( + (pA, pB) => + pB.getEffectiveStat(Stat.SPD) - pA.getEffectiveStat(Stat.SPD) || pA.getBattlerIndex() - pB.getBattlerIndex(), + ); } /** diff --git a/test/test-utils/helpers/move-helper.ts b/test/test-utils/helpers/move-helper.ts index 15605edf31d..041df916cbf 100644 --- a/test/test-utils/helpers/move-helper.ts +++ b/test/test-utils/helpers/move-helper.ts @@ -325,10 +325,16 @@ export class MoveHelper extends GameManagerHelper { } /** - * Force the move used by Metronome to be a specific move. - * @param move - The move to force metronome to use - * @param once - If `true`, uses {@linkcode MockInstance#mockReturnValueOnce} when mocking, else uses {@linkcode MockInstance#mockReturnValue}. + * Force the next move(s) used by Metronome to be a specific move. \ + * Triggers during the next upcoming {@linkcode MoveEffectPhase} that Metronome is used. + * @param move - The move to force Metronome to call + * @param once - If `true`, mocks the return value exactly once; default `false` * @returns The spy that for Metronome that was mocked (Usually unneeded). + * @example + * ```ts + * game.move.use(MoveId.METRONOME); + * game.move.forceMetronomeMove(MoveId.FUTURE_SIGHT); // Can be in any order + * ``` */ public forceMetronomeMove(move: MoveId, once = false): MockInstance { const spy = vi.spyOn(allMoves[MoveId.METRONOME].getAttrs("RandomMoveAttr")[0], "getMoveOverride"); diff --git a/test/test-utils/phase-interceptor.ts b/test/test-utils/phase-interceptor.ts index e0675a722f9..50de7e9f047 100644 --- a/test/test-utils/phase-interceptor.ts +++ b/test/test-utils/phase-interceptor.ts @@ -37,6 +37,7 @@ import { NextEncounterPhase } from "#phases/next-encounter-phase"; import { PartyExpPhase } from "#phases/party-exp-phase"; import { PartyHealPhase } from "#phases/party-heal-phase"; import { PokemonTransformPhase } from "#phases/pokemon-transform-phase"; +import { PositionalTagPhase } from "#phases/positional-tag-phase"; import { PostGameOverPhase } from "#phases/post-game-over-phase"; import { PostSummonPhase } from "#phases/post-summon-phase"; import { QuietFormChangePhase } from "#phases/quiet-form-change-phase"; @@ -142,6 +143,7 @@ export class PhaseInterceptor { [LevelCapPhase, this.startPhase], [AttemptRunPhase, this.startPhase], [SelectBiomePhase, this.startPhase], + [PositionalTagPhase, this.startPhase], [PokemonTransformPhase, this.startPhase], [MysteryEncounterPhase, this.startPhase], [MysteryEncounterOptionSelectedPhase, this.startPhase], diff --git a/test/types/enum-types.test-d.ts b/test/types/enum-types.test-d.ts index 396c479e85a..3d03098c2ad 100644 --- a/test/types/enum-types.test-d.ts +++ b/test/types/enum-types.test-d.ts @@ -1,5 +1,6 @@ -import type { EnumOrObject, EnumValues, NormalEnum, TSNumericEnum } from "#app/@types/enum-types"; import type { enumValueToKey, getEnumKeys, getEnumValues } from "#app/utils/enums"; +import type { EnumOrObject, NormalEnum, TSNumericEnum } from "#types/enum-types"; +import type { ObjectValues } from "#types/type-helpers"; import { describe, expectTypeOf, it } from "vitest"; enum testEnumNum { @@ -16,21 +17,33 @@ const testObjNum = { testON1: 1, testON2: 2 } as const; const testObjString = { testOS1: "apple", testOS2: "banana" } as const; -describe("Enum Type Helpers", () => { - describe("EnumValues", () => { - it("should go from enum object type to value type", () => { - expectTypeOf>().toEqualTypeOf(); - expectTypeOf>().branded.toEqualTypeOf<1 | 2>(); +interface testObject { + key_1: "1"; + key_2: "2"; + key_3: "3"; +} - expectTypeOf>().toEqualTypeOf(); - expectTypeOf>().toEqualTypeOf(); - expectTypeOf>().toMatchTypeOf<"apple" | "banana">(); +describe("Enum Type Helpers", () => { + describe("ObjectValues", () => { + it("should produce a union of an object's values", () => { + expectTypeOf>().toEqualTypeOf<"1" | "2" | "3">(); + }); + + it("should go from enum object type to value type", () => { + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().branded.toEqualTypeOf<1 | 2>(); + + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf< + testEnumString.testS1 | testEnumString.testS2 + >(); + + expectTypeOf>().toExtend<"apple" | "banana">(); }); it("should produce union of const object values as type", () => { - expectTypeOf>().toEqualTypeOf<1 | 2>(); - - expectTypeOf>().toEqualTypeOf<"apple" | "banana">(); + expectTypeOf>().toEqualTypeOf<1 | 2>(); + expectTypeOf>().toEqualTypeOf<"apple" | "banana">(); }); }); @@ -38,7 +51,6 @@ describe("Enum Type Helpers", () => { it("should match numeric enums", () => { expectTypeOf>().toEqualTypeOf(); }); - it("should not match string enums or const objects", () => { expectTypeOf>().toBeNever(); expectTypeOf>().toBeNever(); @@ -59,19 +71,19 @@ describe("Enum Type Helpers", () => { describe("EnumOrObject", () => { it("should match any enum or const object", () => { - expectTypeOf().toMatchTypeOf(); - expectTypeOf().toMatchTypeOf(); - expectTypeOf().toMatchTypeOf(); - expectTypeOf().toMatchTypeOf(); + expectTypeOf().toExtend(); + expectTypeOf().toExtend(); + expectTypeOf().toExtend(); + expectTypeOf().toExtend(); }); it("should not match an enum value union w/o typeof", () => { - expectTypeOf().not.toMatchTypeOf(); - expectTypeOf().not.toMatchTypeOf(); + expectTypeOf().not.toExtend(); + expectTypeOf().not.toExtend(); }); it("should be equivalent to `TSNumericEnum | NormalEnum`", () => { - expectTypeOf().branded.toEqualTypeOf | NormalEnum>(); + expectTypeOf().toEqualTypeOf | NormalEnum>(); }); }); }); @@ -80,6 +92,7 @@ describe("Enum Functions", () => { describe("getEnumKeys", () => { it("should retrieve keys of numeric enum", () => { expectTypeOf>().returns.toEqualTypeOf<("testN1" | "testN2")[]>(); + expectTypeOf>().returns.toEqualTypeOf<("testON1" | "testON2")[]>(); }); }); diff --git a/test/types/positional-tags.test-d.ts b/test/types/positional-tags.test-d.ts new file mode 100644 index 00000000000..a75cc291764 --- /dev/null +++ b/test/types/positional-tags.test-d.ts @@ -0,0 +1,29 @@ +import type { SerializedPositionalTag, serializedPosTagMap } from "#data/positional-tags/load-positional-tag"; +import type { DelayedAttackTag, WishTag } from "#data/positional-tags/positional-tag"; +import type { PositionalTagType } from "#enums/positional-tag-type"; +import type { Mutable, NonFunctionPropertiesRecursive } from "#types/type-helpers"; +import { describe, expectTypeOf, it } from "vitest"; + +// Needed to get around properties being readonly in certain classes +type NonFunctionMutable = Mutable>; + +describe("serializedPositionalTagMap", () => { + it("should contain representations of each tag's serialized form", () => { + expectTypeOf().branded.toEqualTypeOf< + NonFunctionMutable + >(); + expectTypeOf().branded.toEqualTypeOf>(); + }); +}); + +describe("SerializedPositionalTag", () => { + it("should accept a union of all serialized tag forms", () => { + expectTypeOf().branded.toEqualTypeOf< + NonFunctionMutable | NonFunctionMutable + >(); + }); + it("should accept a union of all unserialized tag forms", () => { + expectTypeOf().toExtend(); + expectTypeOf().toExtend(); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 9aa06829789..dcbf7456df8 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -49,7 +49,7 @@ "./system/*.ts" ], "#trainers/*": ["./data/trainers/*.ts"], - "#types/*": ["./@types/*.ts", "./typings/phaser/*.ts"], + "#types/*": ["./@types/helpers/*.ts", "./@types/*.ts", "./typings/phaser/*.ts"], "#ui/*": ["./ui/battle-info/*.ts", "./ui/settings/*.ts", "./ui/*.ts"], "#utils/*": ["./utils/*.ts"], "#data/*": ["./data/pokemon-forms/*.ts", "./data/pokemon/*.ts", "./data/*.ts"],